Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

feat(cli): add the official Kaneo command-line client

Andrej0e16a492c36c
diff --git a/.github/workflows/publish-cli.yml b/.github/workflows/publish-cli.yml
new file mode 100644
index 000000000..648c28c6e
--- /dev/null
+++ b/.github/workflows/publish-cli.yml
@@ -0,0 +1,112 @@
+name: Publish CLI Package
+
+on:
+ release:
+ types: [published]
+ push:
+ branches: [main]
+ paths:
+ - packages/cli/package.json
+
+permissions:
+ contents: write
+ id-token: write
+
+concurrency:
+ group: publish-cli
+ cancel-in-progress: false
+
+jobs:
+ publish:
+ runs-on: ubuntu-24.04
+ if: ${{ github.event_name == 'push' || startsWith(github.event.release.tag_name, 'cli-v') }}
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ persist-credentials: false
+ fetch-depth: 0
+
+ - name: Require reviewed release source
+ env:
+ EVENT_NAME: ${{ github.event_name }}
+ run: |
+ set -euo pipefail
+ if [ "$EVENT_NAME" = push ] && [ "$GITHUB_REF" != refs/heads/main ]; then
+ exit 1
+ fi
+ git merge-base --is-ancestor "$GITHUB_SHA" refs/remotes/origin/main
+
+ - name: Setup pnpm
+ uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
+ with:
+ version: 10.32.1
+
+ - name: Setup Node.js
+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
+ with:
+ node-version: 24
+ package-manager-cache: false
+
+ - name: Install dependencies
+ run: pnpm install --frozen-lockfile
+
+ - name: Run CLI checks
+ run: |
+ pnpm --filter @kaneo/cli typecheck
+ pnpm --filter @kaneo/cli test
+ pnpm --filter @kaneo/cli build
+ node packages/cli/dist/kaneo.mjs --version --json
+
+ - name: Validate CLI release tag
+ if: ${{ github.event_name == 'release' }}
+ run: |
+ PACKAGE_VERSION=$(node -p "require('./packages/cli/package.json').version")
+ TAG_VERSION="${GITHUB_REF_NAME#cli-v}"
+
+ if [ "${GITHUB_REF_NAME}" = "${TAG_VERSION}" ]; then
+ echo "Release tag must start with cli-v, got ${GITHUB_REF_NAME}"
+ exit 1
+ fi
+
+ if [ "${TAG_VERSION}" != "${PACKAGE_VERSION}" ]; then
+ echo "Release tag version (${TAG_VERSION}) does not match packages/cli version (${PACKAGE_VERSION})"
+ exit 1
+ fi
+
+ - name: Check whether @kaneo/cli version is already published
+ id: version_check
+ run: |
+ PACKAGE_VERSION=$(node -p "require('./packages/cli/package.json').version")
+
+ if npm view "@kaneo/cli@${PACKAGE_VERSION}" version >/dev/null 2>&1; then
+ echo "already_published=true" >> "$GITHUB_OUTPUT"
+ echo "@kaneo/cli@${PACKAGE_VERSION} is already published; skipping publish."
+ else
+ echo "already_published=false" >> "$GITHUB_OUTPUT"
+ fi
+
+ - name: Publish @kaneo/cli
+ if: ${{ steps.version_check.outputs.already_published == 'false' }}
+ run: |
+ cd packages/cli
+ npm publish --access public --provenance
+
+ - name: Create CLI release
+ if: ${{ github.event_name == 'push' }}
+ run: |
+ PACKAGE_VERSION=$(node -p "require('./packages/cli/package.json').version")
+
+ if gh release view "cli-v${PACKAGE_VERSION}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1; then
+ echo "Release cli-v${PACKAGE_VERSION} already exists; skipping."
+ exit 0
+ fi
+
+ gh release create "cli-v${PACKAGE_VERSION}" \
+ --target "${GITHUB_SHA}" \
+ --title "@kaneo/cli v${PACKAGE_VERSION}" \
+ --notes "Published [@kaneo/cli@${PACKAGE_VERSION}](https://www.npmjs.com/package/@kaneo/cli/v/${PACKAGE_VERSION}) to npm." \
+ --latest=false
+ env:
+ GH_TOKEN: ${{ github.token }}
diff --git a/README.md b/README.md
index 6a501de06..822960244 100644
--- a/README.md
+++ b/README.md
@@ -40,7 +40,7 @@
- **Work with your team:** shared workspaces, invitations, custom roles, live updates, and public project views.
- **Shape your workflow:** custom columns and fields, with rules that move tasks when repository activity changes.
- **Stay informed:** in-app notifications, email, ntfy, Gotify, and personal webhooks.
-- **Connect other tools:** GitHub and Gitea, chat integrations, project webhooks, a [REST API](https://kaneo.app/docs/api-reference/introduction), and [MCP](https://kaneo.app/docs/core/integrations/mcp) for AI assistants.
+- **Connect other tools:** GitHub and Gitea, chat integrations, project webhooks, a [REST API](https://kaneo.app/docs/api-reference/introduction), a [command-line client](https://kaneo.app/docs/core/integrations/cli), and [MCP](https://kaneo.app/docs/core/integrations/mcp) for AI assistants.
## Installation
diff --git a/apps/docs/core/integrations/cli-commands.mdx b/apps/docs/core/integrations/cli-commands.mdx
new file mode 100644
index 000000000..dd090fa86
--- /dev/null
+++ b/apps/docs/core/integrations/cli-commands.mdx
@@ -0,0 +1,856 @@
+---
+title: CLI command reference
+description: Every kaneo command with its arguments and flags.
+---
+
+This page lists every command of the [Kaneo CLI](/core/integrations/cli) with its arguments and flags. Run any command with `--help` to see the same information in your terminal.
+
+## Conventions
+
+- `<task>` is a ticket ID such as `KAN-12`, or a task ID.
+- `-p`, `--project` takes a project key such as `KAN`, or a project ID. Without it, the CLI uses `KANEO_PROJECT` or the project in `.kaneo.json`.
+- Dates accept `YYYY-MM-DD`, `today`, `tomorrow` or a number of days ahead such as `+3d`. Edit commands also accept `none` to clear a date.
+- Arguments in `[brackets]` are optional. Many of them open a picker or a prompt when you run the command in a terminal. In scripts, pass them.
+- Commands that delete or remove data ask for confirmation in a terminal. In scripts they stop with an error until you pass `-y`, `--yes`.
+- Repeatable flags can be passed more than once.
+
+## Global flags
+
+These work with every command.
+
+| Flag | Description |
+| --- | --- |
+| `--json` | Print one JSON value on stdout. This is the default when stdout is not a terminal. |
+| `--human` | Print styled output even when stdout is not a terminal. |
+| `--jq <expression>` | Filter the JSON output with a jq expression. Turns on JSON mode. |
+| `--token <token>` | API key or access token to use instead of the stored login. |
+| `--api-url <url>` | Kaneo server URL. |
+| `-w`, `--workspace <id>` | Workspace ID. |
+| `--profile <name>` | Stored login to use. |
+| `-h`, `--help` | Show help for the command. |
+| `-v`, `--version` | Show the CLI version. |
+| `--completions <shell>` | Print a completion script for `bash`, `zsh`, `fish` or `sh`. |
+
+## Account and setup
+
+### `kaneo`
+
+Shows your account, workspace, open tasks and the main commands.
+
+### `kaneo login`
+
+```bash
+kaneo login [--no-browser]
+```
+
+Signs in with your browser and stores the login. `--no-browser` prints the sign-in link instead of opening a browser. Add `--api-url` for a self-hosted server, and `--profile` to store the login under a name other than `default`.
+
+### `kaneo logout`
+
+Signs out and forgets the stored token.
+
+### `kaneo whoami`
+
+Shows the account and server you are using. Terminals that can show images also show your avatar.
+
+### `kaneo context`
+
+Shows the server, web app, profile, account, workspace, project, config file and output mode in use, and where each value came from: a flag, an environment variable, `.kaneo.json` or the stored login.
+
+### `kaneo doctor`
+
+Checks the config file, that the server answers, that you are signed in, that the workspace exists, and that the server has every API operation this CLI uses. Exits with code 1 when a check fails.
+
+### `kaneo link`
+
+```bash
+kaneo link [-w <workspace>] [-p <project>]
+```
+
+Saves the workspace and project for this repository in `.kaneo.json`. In a terminal, missing values are picked from a list. In scripts, pass both. `-w` takes a workspace ID or slug here.
+
+### `kaneo unlink`
+
+```bash
+kaneo unlink [--yes]
+```
+
+Removes the workspace and project from `.kaneo.json`, and deletes the file when nothing else is left in it. It asks first in a terminal. In scripts it unlinks right away.
+
+### `kaneo profile list`
+
+Lists stored logins with the server and user of each.
+
+### `kaneo profile use`
+
+```bash
+kaneo profile use [<name>]
+```
+
+Switches the stored login your commands use.
+
+### `kaneo profile rename`
+
+```bash
+kaneo profile rename <old> <new>
+```
+
+Renames a stored login.
+
+### `kaneo profile remove`
+
+```bash
+kaneo profile remove <name> [--yes]
+```
+
+Signs out of a stored login and forgets it.
+
+## Tasks
+
+### `kaneo task list`
+
+```bash
+kaneo task list [-p <project>] [flags]
+```
+
+Lists a project's tasks grouped by column.
+
+| Flag | Description |
+| --- | --- |
+| `-p`, `--project` | Project key or ID |
+| `-s`, `--status` | Only tasks in this column, by slug, such as `in-progress` |
+| `--priority` | Only tasks with this priority: `no-priority`, `low`, `medium`, `high` or `urgent` |
+| `-a`, `--assignee` | Only tasks assigned to this user ID, or `me` |
+| `--mine` | Only tasks assigned to you, like `--assignee me` |
+| `-l`, `--label` | Only tasks with this label. Repeat to require several. |
+| `--open` | Hide tasks in done columns |
+| `--sort` | Sort by `created`, `priority`, `due`, `position`, `title` or `number` |
+| `--order` | `asc` or `desc`. Default: `desc` for `created` and `priority`, `asc` otherwise. |
+| `--due-before` | Only tasks due on or before this day |
+| `--due-after` | Only tasks due on or after this day |
+| `--all` | Show every matching task |
+| `-L`, `--limit` | Maximum number of tasks to show. Default: 50. |
+
+```bash
+kaneo task list -p KAN --mine --open --sort due
+```
+
+### `kaneo task mine`
+
+```bash
+kaneo task mine [--all-workspaces]
+```
+
+Lists the open tasks assigned to you in the current workspace, soonest due first. `--all-workspaces` includes every workspace you belong to.
+
+### `kaneo task view`
+
+```bash
+kaneo task view <task>
+```
+
+Shows a task with its details and description.
+
+### `kaneo task create`
+
+```bash
+kaneo task create [<title>] [flags]
+```
+
+Creates a task. In a terminal, the title is asked for when you leave it out.
+
+| Flag | Description |
+| --- | --- |
+| `-p`, `--project` | Project key or ID |
+| `-d`, `--description` | Description in Markdown, or `-` to read stdin |
+| `-F`, `--description-file` | Read the description from a file, or `-` for stdin |
+| `--priority` | `no-priority`, `low`, `medium`, `high` or `urgent` |
+| `-s`, `--status` | Column slug, such as `in-progress`. Default: the first column. |
+| `-a`, `--assignee` | `me`, or a member by email, name or ID |
+| `--due` | Due date |
+| `--start` | Start date |
+| `--label` | Add a workspace label by name. Repeatable. |
+| `--parent` | Create it as a subtask of this task, such as `KAN-12`. The project defaults to the parent's. |
+
+```bash
+kaneo task create "Fix login redirect" -p KAN --priority high --due tomorrow --label Bug
+```
+
+### `kaneo task edit`
+
+```bash
+kaneo task edit <task> [flags]
+```
+
+Changes a task's title, description, priority, dates or labels.
+
+| Flag | Description |
+| --- | --- |
+| `--title` | New title |
+| `-d`, `--description` | New description in Markdown, or `-` to read stdin. Replaces the current one. |
+| `-F`, `--description-file` | Read the new description from a file, or `-` for stdin |
+| `--priority` | New priority |
+| `--due` | Due date, or `none` to clear it |
+| `--start` | Start date, or `none` to clear it |
+| `--add-label` | Add a workspace label by name. Repeatable. |
+| `--remove-label` | Remove a label by name. Repeatable. |
+
+### `kaneo task open`
+
+```bash
+kaneo task open <task>
+```
+
+Opens the task in your browser.
+
+### `kaneo task status`
+
+```bash
+kaneo task status <task> [<status>]
+```
+
+Moves a task to another column of its project. The column is a slug or a name, such as `in-progress` or `Done`.
+
+### `kaneo task move`
+
+```bash
+kaneo task move <task> [-p <project>] [-s <status>]
+```
+
+Moves a task to another project. `-s`, `--status` picks the column in the destination project. By default the task keeps the same column, or goes to the first one.
+
+### `kaneo task duplicate`
+
+```bash
+kaneo task duplicate <task> [--title <title>] [-p <project>]
+```
+
+Copies a task with its description, labels and custom fields. `--title` sets the title of the copy. `-p` puts the copy in another project.
+
+### `kaneo task bulk`
+
+```bash
+kaneo task bulk <task...> [flags]
+```
+
+Applies one change to many tasks. Pass one change per call. If any task is unknown, nothing changes.
+
+| Flag | Description |
+| --- | --- |
+| `-s`, `--status` | Move every task to this column |
+| `--priority` | Set this priority on every task |
+| `-a`, `--assignee` | Assign every task to `me`, or a member by email, name or ID |
+| `--unassign` | Remove the assignee from every task |
+| `--due` | Set the due date, or `none` to clear it |
+| `--add-label` | Add this workspace label to every task |
+| `--remove-label` | Remove this label from every task |
+| `--delete` | Delete every task |
+| `-y`, `--yes` | Delete without asking for confirmation |
+
+```bash
+kaneo task bulk KAN-12 KAN-13 KAN-14 --status done
+```
+
+### `kaneo task assign`
+
+```bash
+kaneo task assign <task> [<user>] [--unassign]
+```
+
+Assigns a task to `me`, an email address, a name or a user ID. `--unassign` removes the assignee.
+
+### `kaneo task field`
+
+```bash
+kaneo task field <task> [<field>] [<value>] [--clear]
+```
+
+Shows or sets the custom field values of a task. Leave out the field to show every field. A value can be text, a number, a date, `yes` or `no`, an option, or comma-separated options. `--clear` removes the value.
+
+### `kaneo task comment`
+
+```bash
+kaneo task comment <task> [<text...>]
+```
+
+Adds a comment to a task. When you leave out the text, it is read from stdin.
+
+### `kaneo task attach`
+
+```bash
+kaneo task attach <task> [<file...>] [flags]
+```
+
+Uploads files to a task and adds them to its description. Images are shown inline.
+
+| Flag | Description |
+| --- | --- |
+| `--comment` | Post the files as a new comment instead |
+| `-m`, `--message` | Comment text to post with the files, or `-` for stdin. Implies `--comment`. |
+| `-F`, `--message-file` | Read the comment text from a file, or `-` for stdin. Implies `--comment`. |
+
+### `kaneo task images`
+
+```bash
+kaneo task images <task> [--max <n>]
+```
+
+Shows the images in a task description inline, or lists their links when the terminal cannot show images. `--max` shows at most this many images. Default: 10. JSON output lists every image unless you pass `--max`.
+
+### `kaneo task relation list`
+
+```bash
+kaneo task relation list <task>
+```
+
+Shows the parent, subtasks and linked tasks of a task.
+
+### `kaneo task relation add`
+
+```bash
+kaneo task relation add <task> <type> <other-task>
+```
+
+Links two tasks. `<type>` says how the first task relates to the other: `subtask-of`, `parent-of`, `blocks`, `blocked-by` or `relates-to`.
+
+```bash
+kaneo task relation add KAN-3 blocked-by KAN-4
+```
+
+### `kaneo task relation remove`
+
+```bash
+kaneo task relation remove <task> <other-task> [-t <type>] [--yes]
+```
+
+Unlinks two tasks. `-t`, `--type` removes only that relation. When several relations would be removed, the CLI asks first.
+
+### `kaneo task link list`
+
+```bash
+kaneo task link list <task>
+```
+
+Lists a task's links, including issues and pull requests from integrations.
+
+### `kaneo task link add`
+
+```bash
+kaneo task link add <task> <url> [-t <title>]
+```
+
+Attaches an `http` or `https` link to a task. `-t`, `--title` sets the text shown instead of the address.
+
+### `kaneo task link remove`
+
+```bash
+kaneo task link remove <task> <link> [--yes]
+```
+
+Removes a link you added. `<link>` is the link ID from `kaneo task link list` (the first characters are enough) or its URL.
+
+### `kaneo task activity`
+
+```bash
+kaneo task activity <task> [-L <n>]
+```
+
+Shows the history of a task: status changes, assignments, comments and more. `-L`, `--limit` shows only the latest events. Default: 30.
+
+### `kaneo task delete`
+
+```bash
+kaneo task delete <task> [--yes]
+```
+
+Permanently deletes a task with its comments and time entries.
+
+### `kaneo task export`
+
+```bash
+kaneo task export [-p <project>] [-o <file>]
+```
+
+Exports a project's tasks as JSON, ready for `kaneo task import`. `-o`, `--output` writes to a file instead of stdout.
+
+### `kaneo task import`
+
+```bash
+kaneo task import <file> [-p <project>] [--dry-run] [--yes]
+```
+
+Creates tasks in a project from a JSON file, or `-` for stdin. The file is the output of `kaneo task export`, or a JSON array of tasks that each have at least a `title`. Labels are not imported. `--dry-run` checks the file and shows what would be imported.
+
+```bash
+kaneo task export -p KAN | kaneo task import - -p MOB --yes
+```
+
+## Comments
+
+### `kaneo comment list`
+
+```bash
+kaneo comment list <task> [-L <n>]
+```
+
+Shows the comments on a task, oldest first. `-L`, `--limit` shows only the latest comments. Default: 50.
+
+### `kaneo comment add`
+
+```bash
+kaneo comment add <task> [<text...>] [-F <file>]
+```
+
+Adds a comment in Markdown. Pass the text, `-` to read stdin, or `-F`, `--file` to read a file (`-` for stdin). With no text, it is read from stdin.
+
+```bash
+git log -1 --format=%B | kaneo comment add KAN-12 -
+```
+
+### `kaneo comment edit`
+
+```bash
+kaneo comment edit <comment-id> [<text...>] [-F <file>]
+```
+
+Changes the text of one of your comments. Pass the new text, `-` to read stdin, or `-F`, `--file`. In a terminal, it is asked for when you leave it out. Get the ID from `kaneo comment list`.
+
+### `kaneo comment delete`
+
+```bash
+kaneo comment delete <comment-id> [--yes]
+```
+
+Deletes one of your comments.
+
+## Labels
+
+### `kaneo label list`
+
+Lists the labels in your workspace.
+
+### `kaneo label create`
+
+```bash
+kaneo label create [<name>] [-c <color>]
+```
+
+Creates a workspace label. `-c`, `--color` takes a hex color such as `#e7000b`, or one of `stone`, `slate`, `lavender`, `sage`, `forest`, `amber`, `terracotta`, `rose` or `crimson`. By default the CLI picks an unused color.
+
+### `kaneo label edit`
+
+```bash
+kaneo label edit [<label>] [--name <name>] [-c <color>]
+```
+
+Renames a label or changes its color, on every task that uses it.
+
+### `kaneo label delete`
+
+```bash
+kaneo label delete [<label>] [--yes]
+```
+
+Deletes a label and removes it from every task.
+
+## Time
+
+Durations look like `1h30m`, `45m`, `2h`, `1.5h` or `1:30`, and must be at least one minute. `-m`, `--note` adds a short note about the work.
+
+### `kaneo time start`
+
+```bash
+kaneo time start [<task>] [-m <note>]
+```
+
+Starts a timer on a task. Only one timer runs at a time. If another one is running, the CLI offers to stop it in a terminal. In scripts it stops with an error.
+
+### `kaneo time stop`
+
+```bash
+kaneo time stop [<task>]
+```
+
+Stops your running timer. If you started it outside the CLI on a task that is not assigned to you, pass the task.
+
+### `kaneo time status`
+
+Shows your running timer.
+
+### `kaneo time log`
+
+```bash
+kaneo time log [<task>] [<duration>] [--date <day>] [-m <note>]
+```
+
+Logs time you already spent. `--date` takes `today`, `yesterday` or `YYYY-MM-DD`.
+
+```bash
+kaneo time log KAN-12 1h30m --date yesterday -m "Code review"
+```
+
+### `kaneo time list`
+
+```bash
+kaneo time list [<task>]
+```
+
+Lists the time logged on a task, with a total.
+
+### `kaneo time edit`
+
+```bash
+kaneo time edit <entry-id> [-d <duration>] [-m <note>]
+```
+
+Changes the length or note of a time entry. `-d`, `--duration` keeps the start time. Get the ID from `kaneo time list`.
+
+## Projects
+
+### `kaneo project list`
+
+```bash
+kaneo project list [--archived]
+```
+
+Lists the projects in your workspace. `--archived` includes archived projects.
+
+### `kaneo project view`
+
+```bash
+kaneo project view [<project>]
+```
+
+Shows a project with its columns and task counts.
+
+### `kaneo project create`
+
+```bash
+kaneo project create [<name>] [flags]
+```
+
+Creates a project with the default columns.
+
+| Flag | Description |
+| --- | --- |
+| `-k`, `--key` | Task ID prefix such as `KAN`. Default: made from the name, like the web app. |
+| `-d`, `--description` | Description in Markdown, or `-` for stdin |
+| `-F`, `--description-file` | Read the description from a file, or `-` for stdin |
+| `--icon` | Lucide icon name from the web app, such as `Rocket`. Default: `Layout`. |
+
+### `kaneo project edit`
+
+```bash
+kaneo project edit [<project>] [flags]
+```
+
+Changes a project's name, key, description, icon or visibility.
+
+| Flag | Description |
+| --- | --- |
+| `--name` | New name |
+| `-k`, `--key` | New task ID prefix. Existing ticket IDs change with it. |
+| `-d`, `--description` | New description in Markdown, or `-` for stdin. Replaces the current one. |
+| `-F`, `--description-file` | Read the description from a file, or `-` for stdin |
+| `--icon` | Lucide icon name |
+| `--public` | Let anyone with the link view the board |
+| `--private` | Only workspace members can view the board |
+
+### `kaneo project archive`
+
+```bash
+kaneo project archive [<project>]
+```
+
+Hides a project from the project list without deleting it.
+
+### `kaneo project unarchive`
+
+```bash
+kaneo project unarchive [<project>]
+```
+
+Brings an archived project back to the project list.
+
+### `kaneo project move`
+
+```bash
+kaneo project move [<project>] --to <workspace> [--yes]
+```
+
+Moves a project and its tasks to another workspace. `--to` takes a workspace ID or slug.
+
+### `kaneo project delete`
+
+```bash
+kaneo project delete [<project>] [--yes]
+```
+
+Permanently deletes a project with all its tasks, comments and columns. In a terminal, you type the project key to confirm.
+
+## Columns
+
+### `kaneo column list`
+
+```bash
+kaneo column list [-p <project>]
+```
+
+Lists a project's columns in board order.
+
+### `kaneo column create`
+
+```bash
+kaneo column create [<name>] [-p <project>] [--final] [--icon <name>] [--color <hex>]
+```
+
+Adds a column to the end of the board. The slug comes from the name. `--final` marks it as a done column, which stops overdue reminders for its tasks.
+
+### `kaneo column edit`
+
+```bash
+kaneo column edit <column> [-p <project>] [flags]
+```
+
+Renames a column or changes its done state, color or icon. `--name` keeps the slug and the tasks. `--final` and `--no-final` mark or unmark it as done. `--color` and `--icon` accept `none` to clear them.
+
+### `kaneo column move`
+
+```bash
+kaneo column move <column> [-p <project>] (--before <column> | --after <column>)
+```
+
+Moves a column before or after another one.
+
+### `kaneo column delete`
+
+```bash
+kaneo column delete <column> [-p <project>] [--move-tasks-to <column>] [--yes]
+```
+
+Deletes a column. When it holds tasks, `--move-tasks-to` is required and moves them first.
+
+## Custom fields
+
+### `kaneo field list`
+
+```bash
+kaneo field list [-p <project>]
+```
+
+Lists the custom fields of a project.
+
+### `kaneo field create`
+
+```bash
+kaneo field create [<name>] [-t <type>] [-o <option>...] [-p <project>]
+```
+
+Adds a custom field. `-t`, `--type` is `text`, `number`, `date`, `dropdown` (or `select`), `multiselect` or `boolean`. `-o`, `--option` adds a choice for dropdown and multiselect fields. Repeatable.
+
+```bash
+kaneo field create Size -t dropdown -o S -o M -o L -p KAN
+```
+
+### `kaneo field delete`
+
+```bash
+kaneo field delete [<field>] [-p <project>] [--yes]
+```
+
+Deletes a custom field and its values on every task.
+
+## Workflow rules
+
+Workflow rules move tasks to a column when GitHub, GitLab or Gitea events arrive. The integrations are `github`, `gitlab` and `gitea`. The events are `branch_push`, `pr_opened`, `pr_merged`, `issue_opened`, `issue_closed` and `issue_reopened`.
+
+### `kaneo workflow list`
+
+```bash
+kaneo workflow list [-p <project>]
+```
+
+Lists the rules of a project.
+
+### `kaneo workflow set`
+
+```bash
+kaneo workflow set [<integration>] [<event>] [<column>] [-p <project>]
+```
+
+Chooses the column tasks move to when an event arrives.
+
+```bash
+kaneo workflow set github pr_merged done -p KAN
+```
+
+### `kaneo workflow delete`
+
+```bash
+kaneo workflow delete [<rule>] [<event>] [-p <project>] [--yes]
+```
+
+Deletes a rule. Pass the integration and the event, an event alone, or a rule ID.
+
+## Workspaces
+
+### `kaneo workspace list`
+
+Lists the workspaces you belong to.
+
+### `kaneo workspace use`
+
+```bash
+kaneo workspace use [<workspace>]
+```
+
+Chooses the default workspace for your commands. Takes a slug, name or ID.
+
+### `kaneo workspace create`
+
+```bash
+kaneo workspace create [<name>] [--slug <slug>]
+```
+
+Creates a workspace and makes you its owner. The slug is made from the name unless you pass `--slug`.
+
+### `kaneo workspace edit`
+
+```bash
+kaneo workspace edit [<workspace>] [flags]
+```
+
+Changes the current workspace, or the one you name.
+
+| Flag | Description |
+| --- | --- |
+| `--name` | New name |
+| `--slug` | New URL slug, such as `acme-studio` |
+| `-d`, `--description` | New description, or `-` for stdin. Pass `""` to clear it. |
+| `-F`, `--description-file` | Read the description from a file, or `-` for stdin |
+
+### `kaneo workspace leave`
+
+```bash
+kaneo workspace leave <workspace> [--yes]
+```
+
+Leaves a workspace you are a member of.
+
+### `kaneo workspace delete`
+
+```bash
+kaneo workspace delete <workspace> [--yes]
+```
+
+Permanently deletes a workspace with all its projects and tasks. In a terminal, you type the slug to confirm.
+
+## Members and invitations
+
+Roles are `owner`, `admin`, `member`, `viewer`, or a custom role of the workspace.
+
+### `kaneo member list`
+
+Lists the members of a workspace with their roles.
+
+### `kaneo member invite`
+
+```bash
+kaneo member invite <email...> [-r <role>]
+```
+
+Invites one or more people by email. `-r`, `--role` sets their role.
+
+### `kaneo member role`
+
+```bash
+kaneo member role [<member>] [<role>] [--yes]
+```
+
+Changes a member's role. The member is an email address, name or ID. Demoting an owner or admin asks first.
+
+### `kaneo member remove`
+
+```bash
+kaneo member remove [<member>] [--yes]
+```
+
+Removes someone from the workspace.
+
+### `kaneo invitation list`
+
+Lists pending invitations sent from the workspace.
+
+### `kaneo invitation pending`
+
+Lists invitations for you to join other workspaces.
+
+### `kaneo invitation accept`
+
+```bash
+kaneo invitation accept [<id>]
+```
+
+Accepts an invitation and joins the workspace.
+
+### `kaneo invitation decline`
+
+```bash
+kaneo invitation decline [<id>]
+```
+
+Declines an invitation.
+
+### `kaneo invitation cancel`
+
+```bash
+kaneo invitation cancel [<invitation>] [--yes]
+```
+
+Cancels a pending invitation you sent. Takes the invitation ID or the invited email address.
+
+## Notifications
+
+`kaneo inbox` is a shorter name for `kaneo notification`.
+
+### `kaneo notification list`
+
+```bash
+kaneo notification list [-u] [-L <n>]
+```
+
+Lists your latest notifications, in the selected workspace if there is one. `-u`, `--unread` shows only unread ones. `-L`, `--limit` defaults to 20. The server keeps the latest 50.
+
+### `kaneo notification read`
+
+```bash
+kaneo notification read [<id...>] [--all]
+```
+
+Marks notifications as read. Pass notification IDs or the short IDs from `kaneo notification list`, or `-a`, `--all` for every notification.
+
+## Search and API
+
+### `kaneo search`
+
+```bash
+kaneo search <query...> [-t <type>] [-L <n>] [-p <project>]
+```
+
+Searches tasks, projects and comments. The query can be words or a ticket ID such as `KAN-12`. `-t`, `--type` is `all`, `tasks`, `projects`, `workspaces`, `comments` or `activities`. `-L`, `--limit` is 1 to 50, default 20. `-p` searches one project.
+
+### `kaneo api`
+
+```bash
+kaneo api <method> <path> [-f key=value...] [--input <file>] [--query key=value...]
+```
+
+Sends an authenticated request to the Kaneo API and prints the response. The method is `GET`, `POST`, `PUT`, `PATCH` or `DELETE`. The path is under `/api`, and the `/api` prefix is optional.
+
+| Flag | Description |
+| --- | --- |
+| `-f`, `--field` | Add `key=value` to the JSON body. Values that parse as JSON keep their type, and `a.b=1` nests. Repeatable. |
+| `--input` | Read the JSON body from a file, or `-` for stdin |
+| `--query` | Add a `key=value` query parameter. Repeatable. |
+
+`GET` requests cannot have a body. See [the CLI guide](/core/integrations/cli#call-the-api-directly) for examples.
diff --git a/apps/docs/core/integrations/cli.mdx b/apps/docs/core/integrations/cli.mdx
new file mode 100644
index 000000000..20b9e9869
--- /dev/null
+++ b/apps/docs/core/integrations/cli.mdx
@@ -0,0 +1,330 @@
+---
+title: Kaneo CLI
+description: Manage tasks and projects from your terminal with the official Kaneo command-line client.
+---
+
+The official CLI, [`@kaneo/cli`](https://www.npmjs.com/package/@kaneo/cli), installs the `kaneo` command. It works with Kaneo Cloud and self-hosted instances, shows styled output in a terminal, and prints plain JSON for scripts and agents.
+
+## Install
+
+You need Node.js 20 or newer.
+
+```bash
+npm install -g @kaneo/cli
+```
+
+Run `kaneo` on its own to see your account, your open tasks and the main commands.
+
+## Sign in
+
+```bash
+kaneo login
+```
+
+The CLI shows a one-time code, copies it to your clipboard, and opens the approval page of your Kaneo web app. Approve the request there and the CLI saves the login. After signing in you can choose a default workspace. Pass `--no-browser` to print the link instead of opening a browser.
+
+For a self-hosted instance, pass its address once. Later commands reuse it:
+
+```bash
+kaneo login --api-url https://kaneo.example.com
+```
+
+`kaneo login` uses [device authorization](/api-reference/authentication) with the `kaneo-cli` client ID, which self-hosted Kaneo allows by default. If you set `DEVICE_AUTH_CLIENT_IDS`, keep `kaneo-cli` in the list.
+
+Check or end the session with:
+
+```bash
+kaneo whoami
+kaneo logout
+```
+
+### API keys for CI and scripts
+
+Create a key in **Settings → Account → API Keys** and set it in the environment:
+
+```bash
+export KANEO_API_KEY=your-key
+kaneo task list -w your-workspace-id -p KAN
+```
+
+The CLI picks credentials in this order: `--token`, then `KANEO_API_KEY`, then the stored login. A stored login is only ever sent to the server it was created for. A few account-level actions need a signed-in session, and the CLI tells you when an API key cannot be used.
+
+### Profiles
+
+Each login is stored as a profile. The first one is called `default`. To keep a second server or account, sign in with another profile name:
+
+```bash
+kaneo login --profile work --api-url https://kaneo.example.com
+kaneo profile list
+kaneo profile use default
+```
+
+`kaneo login` and `kaneo profile use` make that profile the active one. To use a profile for a single command, pass `--profile work` or set `KANEO_PROFILE=work`. `kaneo profile rename` and `kaneo profile remove` manage the rest.
+
+## Everyday commands
+
+```bash
+kaneo workspace list
+kaneo workspace use # pick the default workspace
+kaneo project list
+kaneo task list -p KAN # tasks grouped by column
+kaneo task list -p KAN --mine --open
+kaneo task mine # your open tasks, soonest due first
+kaneo task view KAN-12
+kaneo task create "Fix login redirect" -p KAN --priority high --due tomorrow
+kaneo task status KAN-12 done
+kaneo task assign KAN-12 me
+kaneo comment add KAN-12 "Shipped in v2.35"
+kaneo time start KAN-12
+kaneo time stop
+kaneo task open KAN-12
+kaneo search "login redirect"
+```
+
+Tasks are addressed by their ticket ID, such as `KAN-12`, or by their ID. If a ticket ID exists in more than one of your workspaces, pass `-w` to choose one.
+
+When a workspace, project or column is missing and you are in a terminal, the CLI shows a searchable picker. In scripts it stops with an error that names the flag to pass.
+
+Every command has `--help`. Print a shell completion script with `kaneo --completions zsh` (or `bash`, `fish`, `sh`).
+
+## Commands
+
+Each line is one command. The [command reference](/core/integrations/cli-commands) lists every argument and flag.
+
+### Tasks
+
+| Command | What it does |
+| --- | --- |
+| `kaneo task list` | List a project's tasks grouped by column, with filters and sorting |
+| `kaneo task mine` | List the open tasks assigned to you, soonest due first |
+| `kaneo task view` | Show a task with its details and description |
+| `kaneo task create` | Create a task, optionally as a subtask |
+| `kaneo task edit` | Change a task's title, description, priority, dates or labels |
+| `kaneo task open` | Open a task in your browser |
+| `kaneo task status` | Move a task to another column |
+| `kaneo task move` | Move a task to another project |
+| `kaneo task duplicate` | Copy a task with its description, labels and custom fields |
+| `kaneo task bulk` | Apply one change to many tasks at once |
+| `kaneo task assign` | Assign a task to a member, or unassign it |
+| `kaneo task field` | Show or set a task's custom field values |
+| `kaneo task attach` | Upload files to a task's description or a comment |
+| `kaneo task images` | Show the images in a task description |
+| `kaneo task relation list`, `add`, `remove` | Manage parents, subtasks, blockers and related tasks |
+| `kaneo task link list`, `add`, `remove` | Manage a task's links, including issues and pull requests |
+| `kaneo task activity` | Show the history of a task |
+| `kaneo task delete` | Permanently delete a task |
+| `kaneo task export` | Export a project's tasks as JSON |
+| `kaneo task import` | Create tasks from a JSON file |
+
+### Comments
+
+| Command | What it does |
+| --- | --- |
+| `kaneo comment list` | Show the comments on a task, oldest first |
+| `kaneo comment add` | Add a comment (also `kaneo task comment`) |
+| `kaneo comment edit` | Change one of your comments |
+| `kaneo comment delete` | Delete one of your comments |
+
+### Labels
+
+| Command | What it does |
+| --- | --- |
+| `kaneo label list` | List the workspace labels |
+| `kaneo label create` | Create a label |
+| `kaneo label edit` | Rename a label or change its color |
+| `kaneo label delete` | Delete a label and remove it from every task |
+
+### Time
+
+| Command | What it does |
+| --- | --- |
+| `kaneo time start` | Start a timer on a task |
+| `kaneo time stop` | Stop your running timer |
+| `kaneo time status` | Show your running timer |
+| `kaneo time log` | Log time you already spent |
+| `kaneo time list` | List the time logged on a task, with a total |
+| `kaneo time edit` | Change the length or note of a time entry |
+
+### Projects and columns
+
+| Command | What it does |
+| --- | --- |
+| `kaneo project list` | List the projects in your workspace |
+| `kaneo project view` | Show a project with its columns and task counts |
+| `kaneo project create` | Create a project with the default columns |
+| `kaneo project edit` | Change a project's name, key, description, icon or visibility |
+| `kaneo project archive`, `unarchive` | Hide a project or bring it back |
+| `kaneo project move` | Move a project and its tasks to another workspace |
+| `kaneo project delete` | Permanently delete a project |
+| `kaneo column list` | List a project's columns in board order |
+| `kaneo column create` | Add a column to the end of the board |
+| `kaneo column edit` | Rename a column, or change its done state, color or icon |
+| `kaneo column move` | Move a column before or after another one |
+| `kaneo column delete` | Delete a column, moving its tasks first |
+| `kaneo field list`, `create`, `delete` | Manage a project's custom fields |
+| `kaneo workflow list`, `set`, `delete` | Move tasks when GitHub, GitLab or Gitea events arrive |
+
+### Workspaces and members
+
+| Command | What it does |
+| --- | --- |
+| `kaneo workspace list` | List the workspaces you belong to |
+| `kaneo workspace use` | Choose the default workspace |
+| `kaneo workspace create` | Create a workspace and become its owner |
+| `kaneo workspace edit` | Change a workspace's name, slug or description |
+| `kaneo workspace leave` | Leave a workspace |
+| `kaneo workspace delete` | Permanently delete a workspace |
+| `kaneo member list` | List members and their roles |
+| `kaneo member invite` | Invite people by email |
+| `kaneo member role` | Change a member's role |
+| `kaneo member remove` | Remove someone from the workspace |
+| `kaneo invitation list` | List invitations sent from the workspace |
+| `kaneo invitation pending` | List invitations for you to join other workspaces |
+| `kaneo invitation accept`, `decline` | Answer an invitation |
+| `kaneo invitation cancel` | Cancel an invitation you sent |
+
+### Notifications
+
+| Command | What it does |
+| --- | --- |
+| `kaneo notification list` | List your latest notifications (also `kaneo inbox list`) |
+| `kaneo notification read` | Mark notifications as read |
+
+### Setup and utilities
+
+| Command | What it does |
+| --- | --- |
+| `kaneo` | Show your account, open tasks and the main commands |
+| `kaneo login`, `logout`, `whoami` | Sign in, sign out, show the current account and server |
+| `kaneo profile list`, `use`, `rename`, `remove` | Manage stored logins |
+| `kaneo link`, `unlink` | Save or remove the workspace and project for a repository |
+| `kaneo context` | Show the settings in use and where each came from |
+| `kaneo doctor` | Check the server, your login and API compatibility |
+| `kaneo search` | Search tasks, projects and comments |
+| `kaneo api` | Send an authenticated request to the Kaneo API |
+
+## Output for scripts and agents
+
+The CLI uses JSON mode when you pass `--json` or `--jq`, set `KANEO_JSON=true`, or pipe its output:
+
+- A successful command prints exactly one JSON value on stdout.
+- A failed command prints `{"error": "message"}` on stdout and exits with code 1.
+- JSON mode never prints colors, spinners, progress lines or images.
+
+```bash
+kaneo task list -p KAN --json | jq '.[] | select(.priority == "urgent") | .ticketId'
+```
+
+Pass `--human` to force styled output. Styled output respects `NO_COLOR`, `FORCE_COLOR` and `TERM=dumb`, and uses plain ASCII when the terminal cannot show Unicode. Ticket IDs and project names are clickable links in terminals that support them.
+
+### Filter with `--jq`
+
+`--jq` filters the JSON output with a jq expression. The engine is built in, so you do not need `jq` installed. Each result goes on its own line, and strings print without quotes:
+
+```bash
+kaneo task list -p KAN --jq '.[].ticketId'
+kaneo task list -p KAN --jq '.[] | select(.priority == "urgent") | .ticketId'
+kaneo task view KAN-12 --jq '.url'
+kaneo task mine --jq '.[] | {ticketId, dueDate}'
+```
+
+An invalid expression fails before any request is sent. Run the same command with `--json` to see the data the expression receives.
+
+### Long text and stdin
+
+Comments and descriptions can come from a file or from stdin. Pass `-F <file>` to read a file, or `-` to read stdin:
+
+```bash
+kaneo comment add KAN-12 -F notes.md
+git log -1 --format=%B | kaneo comment add KAN-12 -
+kaneo project edit KAN -F README.md
+kaneo task create "Write release notes" -p KAN -F notes.md
+kaneo task attach KAN-12 screenshot.png -m "Before and after"
+```
+
+`kaneo task create`, `task edit`, `comment add`, `comment edit`, `task attach`, `project create`, `project edit` and `workspace edit` accept `-F`. `kaneo comment add` and `kaneo task comment` also read stdin when you leave out the text.
+
+### Confirmations
+
+Commands that delete or remove data, such as `kaneo task delete` or `kaneo label delete`, ask for confirmation in a terminal. Deleting a project asks you to type its key, and deleting a workspace asks for its slug. In scripts, these commands stop with an error until you pass `--yes`:
+
+```bash
+kaneo task delete KAN-12 --yes
+```
+
+## Call the API directly
+
+`kaneo api` sends an authenticated request to any Kaneo API endpoint, like `gh api` does for GitHub. It uses the same server, credentials and output modes as the other commands. The path is under `/api`, and the `/api` prefix is optional:
+
+```bash
+kaneo api GET /user/me
+kaneo api GET /task/assigned --query workspaceId=your-workspace-id
+kaneo api PUT /task/status/your-task-id -f status=done
+kaneo api POST /time-entry --input entry.json
+```
+
+`-f key=value` builds a JSON body. Values that parse as JSON keep their type, and dotted keys such as `a.b=1` nest. `--input` reads the body from a file, or `-` for stdin. See the [API reference](/api-reference/introduction) for the available endpoints.
+
+## Images in the terminal
+
+`kaneo task images` shows the images in a task description, `kaneo task attach` previews the images you upload, and `kaneo whoami` shows your avatar.
+
+- Kitty and Ghostty show full images with the Kitty graphics protocol.
+- iTerm2 and WezTerm show full images with the iTerm2 protocol.
+- Other terminals with 256 colors and Unicode get a preview drawn with colored blocks. Inside tmux, screen or Zellij the CLI also uses blocks.
+- When none of these work, the CLI lists the image links instead.
+
+Set `KANEO_IMAGES` to `kitty`, `iterm` or `blocks` to choose the method, or to `off` to turn images off. JSON mode never shows images.
+
+The CLI sends your token only with image requests to your Kaneo server's own file URLs. Images hosted anywhere else are fetched without it.
+
+## Configuration
+
+| Setting | Flag | Environment variable |
+| --- | --- | --- |
+| Server | `--api-url` | `KANEO_API_URL` (default `https://cloud.kaneo.app`) |
+| Token or API key | `--token` | `KANEO_API_KEY` |
+| Workspace | `-w`, `--workspace` | `KANEO_WORKSPACE` |
+| Project | `-p`, `--project` | `KANEO_PROJECT` |
+| Stored login | `--profile` | `KANEO_PROFILE` |
+| JSON output | `--json` | `KANEO_JSON=true` |
+| Inline images | | `KANEO_IMAGES` (`kitty`, `iterm`, `blocks` or `off`) |
+| Web app address for links | | `KANEO_WEB_URL` (detected during login) |
+| Config file | | `KANEO_CONFIG` |
+
+Logins are stored in `~/.config/kaneo/config.json`, or `$XDG_CONFIG_HOME/kaneo/config.json`, with permissions that only your user can read. If another kaneo CLI already uses that file, the official CLI leaves it untouched and asks you to move it or set `KANEO_CONFIG`. The CLI keeps track of your running timer in `timer.json` next to the config file.
+
+### Repository defaults
+
+Link a repository to a workspace and project, so commands run anywhere inside it use them:
+
+```bash
+kaneo link # pick from a list in a terminal
+kaneo link -w your-workspace-id -p KAN
+```
+
+`kaneo link` writes a `.kaneo.json` at the root of the Git repository, or in the current directory outside a repository. It keeps any other keys already in the file:
+
+```json
+{ "workspace": "your-workspace-id", "project": "KAN" }
+```
+
+Commands look for `.kaneo.json` in the current directory and its parents. `kaneo unlink` removes the two keys, and deletes the file when nothing else is left.
+
+The CLI picks the workspace from `-w`, then `KANEO_WORKSPACE`, then `.kaneo.json`, then the default you chose with `kaneo workspace use`. It picks the project from `-p`, then `KANEO_PROJECT`, then `.kaneo.json`.
+
+### Check your setup
+
+`kaneo context` shows the server, profile, account, workspace and project in use, and where each one came from. Use it when a command picks the wrong workspace or server.
+
+`kaneo doctor` checks the config file, the server, your login, the workspace, and whether the server has every API operation this CLI uses. It exits with code 1 when a check fails, so it also works in CI:
+
+```bash
+kaneo doctor
+```
+
+## Related
+
+- [CLI command reference](/core/integrations/cli-commands) for every command, argument and flag.
+- [MCP server](/core/integrations/mcp) for AI assistants such as Claude and Cursor.
+- [API reference](/api-reference/introduction) for direct HTTP access.
diff --git a/apps/docs/core/integrations/mcp.mdx b/apps/docs/core/integrations/mcp.mdx
index 99a2eab7d..34b44856c 100644
--- a/apps/docs/core/integrations/mcp.mdx
+++ b/apps/docs/core/integrations/mcp.mdx
@@ -10,6 +10,8 @@ Kaneo supports the Model Context Protocol (MCP) in two ways:
Both offer the same tools for managing workspaces, projects, tasks, comments, and labels.
+To work with Kaneo from a terminal or a shell script instead, use the [Kaneo CLI](/core/integrations/cli).
+
## Built-in HTTP endpoint
Every Kaneo API instance ships with a Streamable HTTP MCP endpoint. This is the recommended approach for self-hosted deployments.
diff --git a/apps/docs/docs.json b/apps/docs/docs.json
index e21a0bfc9..0579874c1 100644
--- a/apps/docs/docs.json
+++ b/apps/docs/docs.json
@@ -158,6 +158,10 @@
"core/integrations/personal-webhooks"
]
},
+ {
+ "group": "Command line",
+ "pages": ["core/integrations/cli", "core/integrations/cli-commands"]
+ },
{
"group": "AI assistants",
"pages": ["core/integrations/mcp"]
diff --git a/packages/cli/LICENSE b/packages/cli/LICENSE
new file mode 100644
index 000000000..d2772bd91
--- /dev/null
+++ b/packages/cli/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Kaneo contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/packages/cli/README.md b/packages/cli/README.md
new file mode 100644
index 000000000..9f0067bc9
--- /dev/null
+++ b/packages/cli/README.md
@@ -0,0 +1,126 @@
+# Kaneo CLI
+
+[`@kaneo/cli`](https://www.npmjs.com/package/@kaneo/cli) is the official command-line client for [Kaneo](https://kaneo.app), the open source project manager. It is maintained in the [usekaneo/kaneo](https://github.com/usekaneo/kaneo) monorepo and installs the `kaneo` command.
+
+```bash
+npm install -g @kaneo/cli
+kaneo login
+kaneo task list
+```
+
+It works with Kaneo Cloud and with self-hosted instances, prints styled output in a terminal and plain JSON everywhere else, and needs Node.js 20 or newer.
+
+## Sign in
+
+`kaneo login` uses device authorization: it shows a one-time code, copies it to your clipboard, and opens the approval page in your browser. Approve it there and the CLI stores a token for that server.
+
+```bash
+kaneo login # Kaneo Cloud
+kaneo login --api-url https://kaneo.example.com
+kaneo whoami
+kaneo logout
+```
+
+For CI and scripts, use an API key instead (create one in Settings, then Account, then API Keys):
+
+```bash
+export KANEO_API_KEY=...
+kaneo task list -w <workspace-id> -p KAN
+```
+
+Credentials are resolved in this order: `--token`, then `KANEO_API_KEY`, then the stored login. A stored login is only sent to the server it was created for.
+
+## Commands
+
+| Command | What it does |
+| --- | --- |
+| `kaneo` | Home screen: your account, workspace, open tasks and the main commands |
+| `kaneo login`, `logout`, `whoami` | Sign in, sign out, show the current account and server |
+| `kaneo profile list`, `use`, `rename`, `remove` | Manage stored logins for several servers or accounts |
+| `kaneo task list`, `mine`, `view`, `open` | List a project's tasks or your own, show one, open it in the browser |
+| `kaneo task create`, `edit`, `duplicate`, `delete` | Create, change, copy and delete tasks |
+| `kaneo task status`, `move`, `assign`, `field` | Change a task's column, project, assignee or custom fields |
+| `kaneo task bulk` | Apply one change to many tasks at once |
+| `kaneo task attach`, `images` | Upload files to a task, show the images in its description |
+| `kaneo task relation`, `link`, `activity` | Subtasks and blockers, links, and the task's history |
+| `kaneo task export`, `import` | Export a project's tasks as JSON and create tasks from such a file |
+| `kaneo comment list`, `add`, `edit`, `delete` | Read and manage task comments |
+| `kaneo label list`, `create`, `edit`, `delete` | Manage workspace labels |
+| `kaneo time start`, `stop`, `status`, `log`, `list`, `edit` | Track time with a timer or log it afterwards |
+| `kaneo project list`, `view`, `create`, `edit`, `archive`, `unarchive`, `move`, `delete` | Manage projects |
+| `kaneo column list`, `create`, `edit`, `move`, `delete` | Manage a project's columns |
+| `kaneo field list`, `create`, `delete` | Manage a project's custom fields |
+| `kaneo workflow list`, `set`, `delete` | Move tasks when GitHub, GitLab or Gitea events arrive |
+| `kaneo workspace list`, `use`, `create`, `edit`, `leave`, `delete` | Choose and manage workspaces |
+| `kaneo member list`, `invite`, `role`, `remove` | Manage workspace members |
+| `kaneo invitation list`, `pending`, `accept`, `decline`, `cancel` | Manage invitations you sent or received |
+| `kaneo notification list`, `read` | Read your notifications (also `kaneo inbox`) |
+| `kaneo search` | Search tasks, projects and comments |
+| `kaneo link`, `unlink` | Save or remove the workspace and project for a repository |
+| `kaneo context` | Show the settings in use and where each came from |
+| `kaneo doctor` | Check the server, your login and API compatibility |
+| `kaneo api` | Send an authenticated request to any API endpoint, like `gh api` |
+
+The [command reference](https://kaneo.app/docs/core/integrations/cli-commands) lists every argument and flag. Run any command with `--help` for the same information, and `kaneo --completions zsh` (or `bash`, `fish`, `sh`) to print a shell completion script.
+
+Tasks are addressed by their ticket ID, such as `KAN-123`, or by id. When a required workspace, project or column is missing and you are in a terminal, the CLI offers a searchable picker. In scripts it fails with an error that says which flag to pass.
+
+Commands that delete or remove data ask for confirmation in a terminal and need `--yes` in scripts. Comments and descriptions can be read from a file with `-F <file>`, or from stdin with `-`.
+
+## Output
+
+Human mode is the default in a terminal. JSON mode is used with `--json` or `--jq`, with `KANEO_JSON=true`, or whenever stdout is not a terminal:
+
+- A successful command prints exactly one JSON value on stdout.
+- A failed command prints `{"error": "message"}` on stdout and exits with code 1.
+- JSON mode never prints colors, spinners, images or extra lines.
+
+`--jq` filters the JSON with a built-in jq engine, so `jq` does not need to be installed. Strings print without quotes, one result per line:
+
+```bash
+kaneo task list -p KAN --jq '.[] | select(.priority == "urgent") | .ticketId'
+```
+
+Use `--human` to force styled output. Styled output respects `NO_COLOR`, `FORCE_COLOR` and `TERM=dumb`, and falls back to ASCII when the terminal cannot show Unicode.
+
+Images in task descriptions (`kaneo task images`), uploads (`kaneo task attach`) and your avatar (`kaneo whoami`) are shown inline in Kitty, Ghostty, iTerm2 and WezTerm. Other terminals with 256 colors and Unicode get a preview drawn with colored blocks, and the rest get links. Set `KANEO_IMAGES=kitty|iterm|blocks|off` to override this. Your token is only sent with requests for files on your Kaneo server.
+
+## Configuration
+
+| Setting | Flag | Environment |
+| --- | --- | --- |
+| Server | `--api-url` | `KANEO_API_URL` (default `https://cloud.kaneo.app`) |
+| Token | `--token` | `KANEO_API_KEY` |
+| Workspace | `-w`, `--workspace` | `KANEO_WORKSPACE` |
+| Project | `-p`, `--project` | `KANEO_PROJECT` |
+| Stored login | `--profile` | `KANEO_PROFILE` |
+| JSON output | `--json` | `KANEO_JSON=true` |
+| Inline images | | `KANEO_IMAGES` (`kitty`, `iterm`, `blocks` or `off`) |
+| Web app address for links | | `KANEO_WEB_URL` (detected at login) |
+| Config file | | `KANEO_CONFIG` |
+
+Logins live in `~/.config/kaneo/config.json` (or `$XDG_CONFIG_HOME/kaneo/config.json`), readable only by you. The running timer is tracked in `timer.json` next to it. If that file was written by a different kaneo CLI, this one leaves it untouched and asks you to move it or set `KANEO_CONFIG`.
+
+`kaneo link` saves the workspace and project for a repository in a `.kaneo.json` at its root, and `kaneo unlink` removes them:
+
+```json
+{ "workspace": "your-workspace-id", "project": "KAN" }
+```
+
+The workspace comes from `-w`, then `KANEO_WORKSPACE`, then `.kaneo.json`, then the default from `kaneo workspace use`. The project comes from `-p`, then `KANEO_PROJECT`, then `.kaneo.json`. Run `kaneo context` to see which values are in use and where each came from.
+
+## Develop
+
+```bash
+pnpm install
+pnpm --filter @kaneo/cli build # bundles to dist/kaneo.mjs
+node packages/cli/dist/kaneo.mjs --help
+pnpm --filter @kaneo/cli test
+pnpm --filter @kaneo/cli typecheck
+```
+
+The CLI is written with [Effect](https://effect.website) 4 (`effect/cli`, `effect/http`, `effect/schema`) and bundled into one file with no runtime dependencies, so `kaneo --version` starts in about 50 ms. Commands are `Effect.fn` functions, failures are tagged errors mapped in one place (`src/errors/describe.ts`), and the API client, config store and terminal are services that tests replace with layers.
+
+## Releasing
+
+Bump `version` in `package.json` and merge to `main`. The `Publish CLI Package` workflow publishes to npm with provenance and creates a `cli-v<version>` release.
diff --git a/packages/cli/package.json b/packages/cli/package.json
new file mode 100644
index 000000000..d3c6e7245
--- /dev/null
+++ b/packages/cli/package.json
@@ -0,0 +1,59 @@
+{
+ "name": "@kaneo/cli",
+ "version": "0.1.0",
+ "description": "Official command-line client for Kaneo, the open source project manager: sign in, list and update tasks, and script your boards from the terminal",
+ "license": "MIT",
+ "author": "Kaneo (https://kaneo.app)",
+ "homepage": "https://kaneo.app/docs/core/integrations/cli",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/usekaneo/kaneo/",
+ "directory": "packages/cli"
+ },
+ "type": "module",
+ "bin": {
+ "kaneo": "dist/kaneo.mjs"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "publishConfig": {
+ "access": "public"
+ },
+ "files": [
+ "dist",
+ "README.md",
+ "LICENSE"
+ ],
+ "keywords": [
+ "cli",
+ "kanban",
+ "kaneo",
+ "project-management",
+ "tasks",
+ "terminal"
+ ],
+ "scripts": {
+ "build": "vp run compile",
+ "prepublishOnly": "pnpm run build",
+ "dev": "tsx src/bin.ts",
+ "lint": "vp check .",
+ "test": "vp run test:run",
+ "test:watch": "vp test --config vitest.config.ts",
+ "typecheck": "vp run check:types"
+ },
+ "devDependencies": {
+ "@effect/platform-node": "4.0.2",
+ "@gabrielbryk/jq-ts": "^1.7.0",
+ "@kaneo/mcp": "workspace:*",
+ "@kaneo/typescript-config": "workspace:*",
+ "@types/node": "^26.6.2",
+ "@types/pngjs": "^6.0.5",
+ "effect": "4.0.2",
+ "jpeg-js": "^0.4.4",
+ "pngjs": "^7.0.0",
+ "tsx": "^4.23.15",
+ "typescript": "^7.0.2",
+ "vite-plus": "catalog:"
+ }
+}
diff --git a/packages/cli/src/admin/answer-invitation.ts b/packages/cli/src/admin/answer-invitation.ts
new file mode 100644
index 000000000..875d4ae29
--- /dev/null
+++ b/packages/cli/src/admin/answer-invitation.ts
@@ -0,0 +1,117 @@
+import { Effect, Option } from "effect";
+import {
+ acceptInvitation,
+ getInvitationDetails,
+ listReceivedInvitations,
+ rejectInvitation,
+} from "../api/invitations.js";
+import { listOrganizations } from "../api/workspace-admin.js";
+import { InvalidArgument } from "../errors/errors.js";
+import { emit } from "../output/emit.js";
+import { Output } from "../output/output.js";
+import { withSpinner } from "../output/spinner.js";
+import { pick } from "../prompts/pick.js";
+import { renderInvitationAnswer } from "./render-invitation-change.js";
+
+const notPending = (id: string) =>
+ new InvalidArgument({
+ message: `No pending invitation ${id} for your account.`,
+ hint: "It may have expired, been canceled, or been answered already. Run kaneo invitation pending to see yours.",
+ });
+
+export const answerInvitation = Effect.fnUntraced(function* (
+ reference: Option.Option<string>,
+ accept: boolean,
+) {
+ const output = yield* Output;
+ const verb = accept ? "accept" : "decline";
+ if (Option.isNone(reference) && !output.interactive) {
+ return yield* new InvalidArgument({
+ message: `Which invitation should be ${accept ? "accepted" : "declined"}?`,
+ hint: `Pass its id, for example kaneo invitation ${verb} <id>. Run kaneo invitation pending to see them.`,
+ });
+ }
+ const received = yield* withSpinner("Loading invitations")(
+ listReceivedInvitations(),
+ );
+ const id = Option.isSome(reference)
+ ? reference.value.trim()
+ : received.length > 0
+ ? yield* pick(
+ accept ? "Accept which invitation?" : "Decline which invitation?",
+ received.map((invitation) => ({
+ title: invitation.workspaceName,
+ value: invitation.id,
+ description: `from ${invitation.inviterName}`,
+ })),
+ )
+ : yield* new InvalidArgument({
+ message: "You have no pending invitations.",
+ });
+ const known = received.find((invitation) => invitation.id === id);
+ const details = yield* withSpinner("Loading the invitation")(
+ getInvitationDetails(id),
+ );
+ if (!details.valid) {
+ return yield* new InvalidArgument({
+ message: `${details.error ?? "This invitation can no longer be used"}.`,
+ hint: "Run kaneo invitation pending to see the invitations you can answer.",
+ });
+ }
+
+ const answer = yield* withSpinner(
+ accept ? "Accepting the invitation" : "Declining the invitation",
+ )(accept ? acceptInvitation(id) : rejectInvitation(id)).pipe(
+ Effect.catchTags({
+ InvalidRequest: (error) =>
+ Effect.fail(
+ /invitation not found/i.test(error.message) ? notPending(id) : error,
+ ),
+ PermissionDenied: (error) =>
+ Effect.fail(
+ /not the recipient/i.test(error.message)
+ ? new InvalidArgument({
+ message: "This invitation was sent to another email address.",
+ hint: "Sign in with the invited account, then try again.",
+ })
+ : error,
+ ),
+ }),
+ );
+
+ const workspaceId =
+ known?.workspaceId ?? answer.invitation?.organizationId ?? null;
+ const joined =
+ accept && workspaceId
+ ? yield* listOrganizations().pipe(
+ Effect.map((organizations) =>
+ organizations.find(
+ (organization) => organization.id === workspaceId,
+ ),
+ ),
+ Effect.orElseSucceed(() => undefined),
+ )
+ : undefined;
+ const workspaceName =
+ known?.workspaceName ??
+ details.invitation?.workspaceName ??
+ joined?.name ??
+ null;
+
+ yield* emit(
+ {
+ id,
+ workspaceId,
+ workspaceName,
+ ...(accept ? { accepted: true } : { declined: true }),
+ },
+ (ui) =>
+ renderInvitationAnswer(ui, {
+ accepted: accept,
+ workspaceName,
+ next: joined
+ ? `Run kaneo workspace use ${joined.slug} to switch to it.`
+ : null,
+ }),
+ );
+});
diff --git a/packages/cli/src/admin/choose-member.ts b/packages/cli/src/admin/choose-member.ts
new file mode 100644
index 000000000..6dfb93c91
--- /dev/null
+++ b/packages/cli/src/admin/choose-member.ts
@@ -0,0 +1,37 @@
+import { Effect, Option } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+import { Output } from "../output/output.js";
+import { pick } from "../prompts/pick.js";
+import { matchOrgMember } from "./match-org-member.js";
+import type { MemberJson } from "./member-json.js";
+import { roleLabel } from "./roles.js";
+
+export const chooseMember = Effect.fnUntraced(function* (
+ members: ReadonlyArray<MemberJson>,
+ reference: Option.Option<string>,
+ options: { readonly question: string; readonly example: string },
+) {
+ const output = yield* Output;
+ if (Option.isSome(reference)) {
+ const match = matchOrgMember(members, reference.value);
+ if (match) return match;
+ return yield* new InvalidArgument({
+ message: `No workspace member matches "${reference.value}".`,
+ hint: "Use an email address, a name, or an id. Run kaneo member list to see them.",
+ });
+ }
+ if (output.interactive && members.length > 0) {
+ return yield* pick(
+ options.question,
+ members.map((member) => ({
+ title: member.name,
+ value: member,
+ description: `${member.email}, ${roleLabel(member.role)}`,
+ })),
+ );
+ }
+ return yield* new InvalidArgument({
+ message: "Which member?",
+ hint: `Pass an email address, a name, or an id, for example ${options.example}.`,
+ });
+});
diff --git a/packages/cli/src/admin/confirm-slug.ts b/packages/cli/src/admin/confirm-slug.ts
new file mode 100644
index 000000000..e8b0fcf3f
--- /dev/null
+++ b/packages/cli/src/admin/confirm-slug.ts
@@ -0,0 +1,39 @@
+import { Effect } from "effect";
+import { Prompt } from "effect/cli";
+import { Cancelled, InvalidArgument } from "../errors/errors.js";
+import { note } from "../output/emit.js";
+import { Output } from "../output/output.js";
+import { promptTheme } from "../prompts/prompt-theme.js";
+
+export const confirmBySlug = Effect.fnUntraced(function* (options: {
+ readonly yes: boolean;
+ readonly action: string;
+ readonly warning: string;
+ readonly slug: string;
+}) {
+ if (options.yes) return;
+ const output = yield* Output;
+ if (!output.interactive) {
+ return yield* new InvalidArgument({
+ message: `${options.action} needs confirmation.`,
+ hint: "Pass --yes to skip the prompt.",
+ });
+ }
+ yield* note((ui) => [
+ "",
+ ` ${ui.theme.danger(ui.glyphs.warning)} ${options.warning}`,
+ "",
+ ]);
+ const typed = yield* Prompt.run(
+ Prompt.String({
+ message: `Type ${options.slug} to confirm`,
+ theme: promptTheme(output.ui),
+ }),
+ ).pipe(Effect.catchTag("QuitError", () => Effect.fail(new Cancelled())));
+ if (typed.trim() !== options.slug) {
+ return yield* new InvalidArgument({
+ message: `"${typed.trim()}" does not match ${options.slug}, so nothing changed.`,
+ hint: "Type the slug exactly, or pass --yes in scripts.",
+ });
+ }
+});
diff --git a/packages/cli/src/admin/description-metadata.test.ts b/packages/cli/src/admin/description-metadata.test.ts
new file mode 100644
index 000000000..9f0511c4f
--- /dev/null
+++ b/packages/cli/src/admin/description-metadata.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from "vite-plus/test";
+import { metadataWithDescription } from "./description-metadata.js";
+
+describe("metadataWithDescription", () => {
+ it("leaves metadata alone when it never held a description", () => {
+ expect(metadataWithDescription(null, "New")).toBeUndefined();
+ expect(metadataWithDescription({ theme: "dark" }, "New")).toBeUndefined();
+ });
+
+ it("replaces the description and keeps other keys", () => {
+ expect(
+ metadataWithDescription({ description: "Old", theme: "dark" }, ""),
+ ).toEqual({ description: "", theme: "dark" });
+ });
+
+ it("reads metadata stored as a JSON string", () => {
+ expect(
+ metadataWithDescription('{"description":"Old"}', "Design team"),
+ ).toEqual({ description: "Design team" });
+ expect(metadataWithDescription("not json", "New")).toBeUndefined();
+ });
+});
diff --git a/packages/cli/src/admin/description-metadata.ts b/packages/cli/src/admin/description-metadata.ts
new file mode 100644
index 000000000..64ff5d6c3
--- /dev/null
+++ b/packages/cli/src/admin/description-metadata.ts
@@ -0,0 +1,21 @@
+function asRecord(value: unknown): Record<string, unknown> | null {
+ if (typeof value === "string") {
+ try {
+ return asRecord(JSON.parse(value) as unknown);
+ } catch {
+ return null;
+ }
+ }
+ return typeof value === "object" && value !== null && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : null;
+}
+
+export function metadataWithDescription(
+ metadata: unknown,
+ description: string,
+): Record<string, unknown> | undefined {
+ const record = asRecord(metadata);
+ if (!record || !("description" in record)) return undefined;
+ return { ...record, description };
+}
diff --git a/packages/cli/src/admin/invitation-json.ts b/packages/cli/src/admin/invitation-json.ts
new file mode 100644
index 000000000..66e6c1373
--- /dev/null
+++ b/packages/cli/src/admin/invitation-json.ts
@@ -0,0 +1,61 @@
+import type { ReceivedInvitation, SentInvitation } from "../api/invitations.js";
+import { isoTimestamp } from "./iso-timestamp.js";
+
+export type SentInvitationJson = {
+ readonly id: string;
+ readonly email: string;
+ readonly role: string;
+ readonly status: string;
+ readonly expiresAt: string | null;
+ readonly createdAt: string | null;
+ readonly url: string;
+};
+
+export type ReceivedInvitationJson = {
+ readonly id: string;
+ readonly email: string;
+ readonly workspaceId: string;
+ readonly workspaceName: string;
+ readonly inviterName: string;
+ readonly expiresAt: string | null;
+};
+
+export function invitationUrl(webUrl: string, id: string): string {
+ return `${webUrl.replace(/\/+$/, "")}/invitation/accept/${encodeURIComponent(id)}`;
+}
+
+export function toSentInvitationJson(
+ invitation: SentInvitation,
+ webUrl: string,
+): SentInvitationJson {
+ return {
+ id: invitation.id,
+ email: invitation.email,
+ role: invitation.role,
+ status: invitation.status,
+ expiresAt: isoTimestamp(invitation.expiresAt),
+ createdAt: isoTimestamp(invitation.createdAt),
+ url: invitationUrl(webUrl, invitation.id),
+ };
+}
+
+export function isPending(invitation: SentInvitationJson, now: Date): boolean {
+ return (
+ invitation.status === "pending" &&
+ invitation.expiresAt !== null &&
+ new Date(invitation.expiresAt).getTime() > now.getTime()
+ );
+}
+
+export function toReceivedInvitationJson(
+ invitation: ReceivedInvitation,
+): ReceivedInvitationJson {
+ return {
+ id: invitation.id,
+ email: invitation.email,
+ workspaceId: invitation.workspaceId,
+ workspaceName: invitation.workspaceName,
+ inviterName: invitation.inviterName,
+ expiresAt: isoTimestamp(invitation.expiresAt),
+ };
+}
diff --git a/packages/cli/src/admin/iso-timestamp.ts b/packages/cli/src/admin/iso-timestamp.ts
new file mode 100644
index 000000000..71b0daf8d
--- /dev/null
+++ b/packages/cli/src/admin/iso-timestamp.ts
@@ -0,0 +1,5 @@
+export function isoTimestamp(value: unknown): string | null {
+ if (typeof value !== "string" && typeof value !== "number") return null;
+ const date = new Date(value);
+ return Number.isNaN(date.getTime()) ? null : date.toISOString();
+}
diff --git a/packages/cli/src/admin/match-org-member.test.ts b/packages/cli/src/admin/match-org-member.test.ts
new file mode 100644
index 000000000..a41febd17
--- /dev/null
+++ b/packages/cli/src/admin/match-org-member.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { OrganizationMember } from "../api/members.js";
+import { sortMembers, toMemberJson } from "./member-json.js";
+import { matchOrgMember } from "./match-org-member.js";
+
+function member(
+ id: string,
+ userId: string,
+ name: string,
+ email: string,
+ role: string,
+): OrganizationMember {
+ return {
+ id,
+ userId,
+ role,
+ createdAt: "2026-03-03T10:00:00.000Z",
+ user: { name, email },
+ };
+}
+
+const ada = toMemberJson(
+ member("m_ada", "u_ada", "Ada Lovelace", "[email protected]", "owner"),
+);
+const grace = toMemberJson(
+ member("m_grace", "u_grace", "Grace Hopper", "[email protected]", "member"),
+);
+const alan = toMemberJson(
+ member("m_alan", "u_alan", "Alan Turing", "[email protected]", "admin"),
+);
+const all = [ada, grace, alan];
+
+describe("toMemberJson", () => {
+ it("uses the user id as id and keeps the membership id", () => {
+ expect(ada).toEqual({
+ id: "u_ada",
+ memberId: "m_ada",
+ name: "Ada Lovelace",
+ email: "[email protected]",
+ role: "owner",
+ joinedAt: "2026-03-03T10:00:00.000Z",
+ });
+ });
+
+ it("leaves joinedAt empty when the server sends no date", () => {
+ expect(
+ toMemberJson({
+ ...member("m", "u", "N", "[email protected]", "member"),
+ createdAt: null,
+ }).joinedAt,
+ ).toBeNull();
+ });
+});
+
+describe("matchOrgMember", () => {
+ it("matches email, name, user id and membership id", () => {
+ expect(matchOrgMember(all, "[email protected]")).toBe(grace);
+ expect(matchOrgMember(all, "alan turing")).toBe(alan);
+ expect(matchOrgMember(all, "u_ada")).toBe(ada);
+ expect(matchOrgMember(all, "m_grace")).toBe(grace);
+ });
+
+ it("falls back to a unique email name or the start of a name", () => {
+ expect(matchOrgMember(all, "grace")).toBe(grace);
+ expect(matchOrgMember(all, "Alan T")).toBe(alan);
+ });
+
+ it("refuses a short form that fits more than one member", () => {
+ const adam = toMemberJson(
+ member("m_adam", "u_adam", "Adam Smith", "[email protected]", "member"),
+ );
+ expect(matchOrgMember([...all, adam], "ad")).toBeUndefined();
+ expect(matchOrgMember([...all, adam], "ada")).toBe(ada);
+ });
+
+ it("returns nothing for an unknown reference", () => {
+ expect(matchOrgMember(all, "[email protected]")).toBeUndefined();
+ expect(matchOrgMember(all, " ")).toBeUndefined();
+ });
+});
+
+describe("sortMembers", () => {
+ it("puts owners and admins first, then sorts by name", () => {
+ expect(sortMembers([grace, alan, ada]).map((entry) => entry.id)).toEqual([
+ "u_ada",
+ "u_alan",
+ "u_grace",
+ ]);
+ });
+});
diff --git a/packages/cli/src/admin/match-org-member.ts b/packages/cli/src/admin/match-org-member.ts
new file mode 100644
index 000000000..0b955137a
--- /dev/null
+++ b/packages/cli/src/admin/match-org-member.ts
@@ -0,0 +1,29 @@
+import { matchMember } from "../tasks/match-member.js";
+import type { MemberJson } from "./member-json.js";
+
+function only<A>(matches: ReadonlyArray<A>): A | undefined {
+ return matches.length === 1 ? matches[0] : undefined;
+}
+
+export function matchOrgMember(
+ members: ReadonlyArray<MemberJson>,
+ reference: string,
+): MemberJson | undefined {
+ const trimmed = reference.trim();
+ const wanted = trimmed.toLowerCase();
+ if (wanted === "") return undefined;
+ const byMemberId = members.find((member) => member.memberId === trimmed);
+ if (byMemberId) return byMemberId;
+ const match = matchMember(members, reference);
+ if (match) return members.find((member) => member.id === match.id);
+ return (
+ only(
+ members.filter(
+ (member) => member.email.toLowerCase().split("@")[0] === wanted,
+ ),
+ ) ??
+ only(
+ members.filter((member) => member.name.toLowerCase().startsWith(wanted)),
+ )
+ );
+}
diff --git a/packages/cli/src/admin/member-json.ts b/packages/cli/src/admin/member-json.ts
new file mode 100644
index 000000000..276a0b636
--- /dev/null
+++ b/packages/cli/src/admin/member-json.ts
@@ -0,0 +1,34 @@
+import type { OrganizationMember } from "../api/members.js";
+import { isoTimestamp } from "./iso-timestamp.js";
+import { roleRank } from "./roles.js";
+
+export type MemberJson = {
+ readonly id: string;
+ readonly memberId: string;
+ readonly name: string;
+ readonly email: string;
+ readonly role: string;
+ readonly joinedAt: string | null;
+};
+
+export function toMemberJson(member: OrganizationMember): MemberJson {
+ return {
+ id: member.userId,
+ memberId: member.id,
+ name: member.user.name,
+ email: member.user.email,
+ role: member.role,
+ joinedAt: isoTimestamp(member.createdAt),
+ };
+}
+
+export function sortMembers(
+ members: ReadonlyArray<MemberJson>,
+): Array<MemberJson> {
+ return [...members].sort(
+ (a, b) =>
+ roleRank(a.role) - roleRank(b.role) ||
+ a.name.toLowerCase().localeCompare(b.name.toLowerCase()) ||
+ a.email.localeCompare(b.email),
+ );
+}
diff --git a/packages/cli/src/admin/parse-emails.test.ts b/packages/cli/src/admin/parse-emails.test.ts
new file mode 100644
index 000000000..1fe4df1fb
--- /dev/null
+++ b/packages/cli/src/admin/parse-emails.test.ts
@@ -0,0 +1,25 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { parseEmails } from "./parse-emails.js";
+
+describe("parseEmails", () => {
+ it("lowercases, splits on commas and drops duplicates", () => {
+ expect(
+ ).toEqual(Result.succeed(["[email protected]", "[email protected]"]));
+ });
+
+ it("names every invalid address", () => {
+ const result = parseEmails(["grace", "[email protected]", "x@y"]);
+ expect(Result.isFailure(result) && result.failure.message).toBe(
+ "These are not email addresses: grace, x@y.",
+ );
+ });
+
+ it("asks for at least one address", () => {
+ const result = parseEmails([" , "]);
+ expect(Result.isFailure(result) && result.failure.message).toBe(
+ "Who should be invited?",
+ );
+ });
+});
diff --git a/packages/cli/src/admin/parse-emails.ts b/packages/cli/src/admin/parse-emails.ts
new file mode 100644
index 000000000..9d5b802db
--- /dev/null
+++ b/packages/cli/src/admin/parse-emails.ts
@@ -0,0 +1,34 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+
+const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/u;
+
+export function parseEmails(
+ inputs: ReadonlyArray<string>,
+): Result.Result<ReadonlyArray<string>, InvalidArgument> {
+ const emails = inputs
+ .flatMap((input) => input.split(","))
+ .map((value) => value.trim().toLowerCase())
+ .filter(Boolean);
+ const invalid = emails.filter((email) => !EMAIL.test(email));
+ if (invalid.length > 0) {
+ return Result.fail(
+ new InvalidArgument({
+ message:
+ invalid.length === 1
+ ? `"${invalid[0]}" is not an email address.`
+ : `These are not email addresses: ${invalid.join(", ")}.`,
+ hint: "Pass addresses such as [email protected], separated by spaces.",
+ }),
+ );
+ }
+ if (emails.length === 0) {
+ return Result.fail(
+ new InvalidArgument({
+ message: "Who should be invited?",
+ hint: "Pass one or more email addresses, for example kaneo member invite [email protected].",
+ }),
+ );
+ }
+ return Result.succeed([...new Set(emails)]);
+}
diff --git a/packages/cli/src/admin/render-invitation-change.test.ts b/packages/cli/src/admin/render-invitation-change.test.ts
new file mode 100644
index 000000000..63814e4d5
--- /dev/null
+++ b/packages/cli/src/admin/render-invitation-change.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import {
+ renderInvitationAnswer,
+ renderInvitationCanceled,
+ renderInvites,
+} from "./render-invitation-change.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+describe("renderInvites", () => {
+ it("prints one line per address", () => {
+ expect(
+ renderInvites(ui, [
+ {
+ id: "inv_1",
+ email: "[email protected]",
+ role: "member",
+ resent: false,
+ emailSent: true,
+ url: "http://localhost:5173/invitation/accept/inv_1",
+ },
+ {
+ id: "inv_2",
+ email: "[email protected]",
+ role: "admin",
+ resent: true,
+ emailSent: true,
+ url: "http://localhost:5173/invitation/accept/inv_2",
+ },
+ ]),
+ ).toEqual([
+ "",
+ " ✓ Invited [email protected] · Member",
+ " ✓ Resent the invitation to [email protected] · Admin",
+ "",
+ ]);
+ });
+
+ it("offers the link when the email could not be sent", () => {
+ expect(
+ renderInvites(ui, [
+ {
+ id: "inv_1",
+ email: "[email protected]",
+ role: "member",
+ resent: false,
+ emailSent: false,
+ url: "http://localhost:5173/invitation/accept/inv_1",
+ },
+ ]),
+ ).toEqual([
+ "",
+ " ▲ Invited [email protected] · Member, but the email could not be sent",
+ " Share the link instead: http://localhost:5173/invitation/accept/inv_1",
+ "",
+ ]);
+ });
+});
+
+describe("renderInvitationAnswer", () => {
+ it("confirms joining with a next step", () => {
+ expect(
+ renderInvitationAnswer(ui, {
+ accepted: true,
+ workspaceName: "Side Project",
+ next: "Run kaneo workspace use side-project to switch to it.",
+ }),
+ ).toEqual([
+ "",
+ " ✓ Joined Side Project",
+ "",
+ " Run kaneo workspace use side-project to switch to it.",
+ "",
+ ]);
+ });
+
+ it("confirms declining without a known workspace name", () => {
+ expect(
+ renderInvitationAnswer(ui, {
+ accepted: false,
+ workspaceName: null,
+ next: null,
+ }),
+ ).toEqual(["", " ✓ Declined the invitation to the workspace", ""]);
+ });
+});
+
+describe("renderInvitationCanceled", () => {
+ it("names the invited address", () => {
+ expect(
+ renderInvitationCanceled(ui, { email: "[email protected]" }),
+ ).toEqual(["", " ✓ Canceled the invitation for [email protected]", ""]);
+ });
+});
diff --git a/packages/cli/src/admin/render-invitation-change.ts b/packages/cli/src/admin/render-invitation-change.ts
new file mode 100644
index 000000000..96eb95001
--- /dev/null
+++ b/packages/cli/src/admin/render-invitation-change.ts
@@ -0,0 +1,75 @@
+import { renderCell, text } from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+import { roleLabel } from "./roles.js";
+
+export type InviteJson = {
+ readonly id: string | null;
+ readonly email: string;
+ readonly role: string;
+ readonly resent: boolean;
+ readonly emailSent: boolean;
+ readonly url: string | null;
+};
+
+export function renderInvites(
+ ui: Ui,
+ invites: ReadonlyArray<InviteJson>,
+): string[] {
+ const { theme, glyphs } = ui;
+ const lines = [""];
+ for (const invite of invites) {
+ const email = theme.strong(invite.email);
+ const role = theme.muted(`${glyphs.separator} ${roleLabel(invite.role)}`);
+ if (!invite.emailSent) {
+ lines.push(
+ ` ${theme.warning(glyphs.warning)} ${invite.resent ? "Resent" : "Invited"} ${email} ${role}, but the email could not be sent`,
+ );
+ if (invite.url) {
+ lines.push(
+ ` ${theme.muted("Share the link instead:")} ${renderCell([text(invite.url, theme.info, invite.url)], ui)}`,
+ );
+ }
+ continue;
+ }
+ lines.push(
+ ` ${theme.success(glyphs.tick)} ${invite.resent ? "Resent the invitation to" : "Invited"} ${email} ${role}`,
+ );
+ }
+ lines.push("");
+ return lines;
+}
+
+export function renderInvitationAnswer(
+ ui: Ui,
+ answer: {
+ readonly accepted: boolean;
+ readonly workspaceName: string | null;
+ readonly next: string | null;
+ },
+): string[] {
+ const { theme, glyphs } = ui;
+ const workspace = answer.workspaceName
+ ? theme.strong(answer.workspaceName)
+ : "the workspace";
+ const lines = [
+ "",
+ answer.accepted
+ ? ` ${theme.success(glyphs.tick)} Joined ${workspace}`
+ : ` ${theme.success(glyphs.tick)} Declined the invitation to ${workspace}`,
+ "",
+ ];
+ if (answer.next) lines.push(` ${theme.muted(answer.next)}`, "");
+ return lines;
+}
+
+export function renderInvitationCanceled(
+ ui: Ui,
+ invitation: { readonly email: string },
+): string[] {
+ const { theme, glyphs } = ui;
+ return [
+ "",
+ ` ${theme.success(glyphs.tick)} Canceled the invitation for ${theme.strong(invitation.email)}`,
+ "",
+ ];
+}
diff --git a/packages/cli/src/admin/render-invitation-list.test.ts b/packages/cli/src/admin/render-invitation-list.test.ts
new file mode 100644
index 000000000..7cdd289e3
--- /dev/null
+++ b/packages/cli/src/admin/render-invitation-list.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import {
+ invitationUrl,
+ isPending,
+ type ReceivedInvitationJson,
+ type SentInvitationJson,
+} from "./invitation-json.js";
+import {
+ renderReceivedInvitations,
+ renderSentInvitations,
+} from "./render-invitation-list.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+const now = new Date(2026, 9, 8, 12);
+
+const sent: SentInvitationJson = {
+ id: "inv_9f2c41a7d3",
+ email: "[email protected]",
+ role: "member",
+ status: "pending",
+ expiresAt: new Date(2026, 9, 9, 12).toISOString(),
+ createdAt: new Date(2026, 9, 7, 12).toISOString(),
+ url: invitationUrl("http://localhost:5173/", "inv_9f2c41a7d3"),
+};
+
+const received: ReceivedInvitationJson = {
+ id: "inv_4b1e88c2f0",
+ email: "[email protected]",
+ workspaceId: "ws_side",
+ workspaceName: "Side Project",
+ inviterName: "Grace Hopper",
+ expiresAt: new Date(2026, 9, 15, 12).toISOString(),
+};
+
+describe("invitation helpers", () => {
+ it("builds the accept link the web app shares", () => {
+ expect(sent.url).toBe(
+ "http://localhost:5173/invitation/accept/inv_9f2c41a7d3",
+ );
+ });
+
+ it("treats canceled and expired invitations as not pending", () => {
+ expect(isPending(sent, now)).toBe(true);
+ expect(isPending({ ...sent, status: "canceled" }, now)).toBe(false);
+ expect(
+ isPending(
+ { ...sent, expiresAt: new Date(2026, 9, 1).toISOString() },
+ now,
+ ),
+ ).toBe(false);
+ });
+});
+
+describe("renderSentInvitations", () => {
+ it("lists email, role, expiry and id within 80 columns", () => {
+ const lines = renderSentInvitations(ui, { invitations: [sent], now });
+ expect(lines).toEqual([
+ "",
+ " [email protected] Member expires Tomorrow inv_9f2c41a7d3",
+ "",
+ ]);
+ });
+
+ it("suggests inviting someone when the list is empty", () => {
+ expect(renderSentInvitations(ui, { invitations: [], now })[1]).toBe(
+ " No pending invitations. Invite someone with kaneo member invite <email>.",
+ );
+ });
+});
+
+describe("renderReceivedInvitations", () => {
+ it("shows the workspace, the inviter and how to accept", () => {
+ const lines = renderReceivedInvitations(ui, {
+ invitations: [received],
+ now,
+ });
+ expect(lines).toEqual([
+ "",
+ " Side Project from Grace Hopper expires Oct 15 inv_4b1e88c2f0",
+ "",
+ " Run kaneo invitation accept <id> to join.",
+ "",
+ ]);
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(80);
+ });
+
+ it("keeps the id visible when names are long", () => {
+ const lines = renderReceivedInvitations(ui, {
+ invitations: [
+ {
+ ...received,
+ workspaceName: "The Extremely Long Workspace Name Of Many Words",
+ inviterName: "Someone With An Unusually Long Display Name",
+ },
+ ],
+ now,
+ });
+ expect(lines[1]?.endsWith("inv_4b1e88c2f0")).toBe(true);
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(80);
+ });
+});
diff --git a/packages/cli/src/admin/render-invitation-list.ts b/packages/cli/src/admin/render-invitation-list.ts
new file mode 100644
index 000000000..4bc10f19f
--- /dev/null
+++ b/packages/cli/src/admin/render-invitation-list.ts
@@ -0,0 +1,125 @@
+import { type Cell, text } from "../render/cell.js";
+import { renderTable } from "../render/table.js";
+import type { Ui } from "../render/ui.js";
+import type {
+ ReceivedInvitationJson,
+ SentInvitationJson,
+} from "./invitation-json.js";
+import { formatDay } from "./render-member-list.js";
+import { roleLabel } from "./roles.js";
+
+function expires(iso: string | null, now: Date): string {
+ const day = formatDay(iso, now);
+ return day ? `expires ${day}` : "";
+}
+
+export function renderSentInvitations(
+ ui: Ui,
+ view: {
+ readonly invitations: ReadonlyArray<SentInvitationJson>;
+ readonly now: Date;
+ },
+): string[] {
+ const { theme } = ui;
+ if (view.invitations.length === 0) {
+ return [
+ "",
+ ` ${theme.muted("No pending invitations. Invite someone with kaneo member invite <email>.")}`,
+ "",
+ ];
+ }
+ return [
+ "",
+ ...renderTable(
+ ui,
+ view.invitations,
+ [
+ {
+ header: "Email",
+ flex: true,
+ minWidth: 16,
+ cell: (invitation): Cell => [
+ text(invitation.email, theme.strong, invitation.url),
+ ],
+ },
+ {
+ header: "Role",
+ cell: (invitation): Cell => [text(roleLabel(invitation.role))],
+ },
+ {
+ header: "Expires",
+ optional: true,
+ cell: (invitation): Cell => [
+ text(expires(invitation.expiresAt, view.now), theme.muted),
+ ],
+ },
+ {
+ header: "ID",
+ optional: true,
+ cell: (invitation): Cell => [text(invitation.id, theme.muted)],
+ },
+ ],
+ { width: ui.caps.columns, indent: 2 },
+ ),
+ "",
+ ];
+}
+
+export function renderReceivedInvitations(
+ ui: Ui,
+ view: {
+ readonly invitations: ReadonlyArray<ReceivedInvitationJson>;
+ readonly now: Date;
+ },
+): string[] {
+ const { theme } = ui;
+ if (view.invitations.length === 0) {
+ return [
+ "",
+ ` ${theme.muted("You have no pending invitations.")}`,
+ ` ${theme.muted("Invitations only show here once your email address is verified.")}`,
+ "",
+ ];
+ }
+ return [
+ "",
+ ...renderTable(
+ ui,
+ view.invitations,
+ [
+ {
+ header: "Workspace",
+ flex: true,
+ minWidth: 12,
+ cell: (invitation): Cell => [
+ text(invitation.workspaceName, theme.strong),
+ ],
+ },
+ {
+ header: "From",
+ flex: true,
+ minWidth: 10,
+ optional: true,
+ cell: (invitation): Cell => [
+ text(`from ${invitation.inviterName}`, theme.muted),
+ ],
+ },
+ {
+ header: "Expires",
+ optional: true,
+ cell: (invitation): Cell => [
+ text(expires(invitation.expiresAt, view.now), theme.muted),
+ ],
+ },
+ {
+ header: "ID",
+ cell: (invitation): Cell => [text(invitation.id, theme.muted)],
+ },
+ ],
+ { width: ui.caps.columns, indent: 2 },
+ ),
+ "",
+ ` ${theme.muted("Run")} ${theme.strong("kaneo invitation accept <id>")} ${theme.muted("to join.")}`,
+ "",
+ ];
+}
diff --git a/packages/cli/src/admin/render-member-change.test.ts b/packages/cli/src/admin/render-member-change.test.ts
new file mode 100644
index 000000000..2d7298d50
--- /dev/null
+++ b/packages/cli/src/admin/render-member-change.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import {
+ renderMemberRemoved,
+ renderMemberRole,
+} from "./render-member-change.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+describe("renderMemberRemoved", () => {
+ it("names the member and their email", () => {
+ expect(
+ renderMemberRemoved(ui, {
+ name: "Grace Hopper",
+ email: "[email protected]",
+ }),
+ ).toEqual(["", " ✓ Removed Grace Hopper · [email protected]", ""]);
+ });
+});
+
+describe("renderMemberRole", () => {
+ it("shows the new and the previous role", () => {
+ expect(
+ renderMemberRole(ui, {
+ name: "Grace Hopper",
+ role: "admin",
+ previousRole: "member",
+ }),
+ ).toEqual(["", " ✓ Grace Hopper is now Admin · was Member", ""]);
+ });
+
+ it("says when nothing changed", () => {
+ expect(
+ renderMemberRole(ui, {
+ name: "Grace Hopper",
+ role: "member",
+ previousRole: "member",
+ }),
+ ).toEqual(["", " ✓ Grace Hopper is already Member", ""]);
+ });
+});
diff --git a/packages/cli/src/admin/render-member-change.ts b/packages/cli/src/admin/render-member-change.ts
new file mode 100644
index 000000000..d2c4d3217
--- /dev/null
+++ b/packages/cli/src/admin/render-member-change.ts
@@ -0,0 +1,30 @@
+import type { Ui } from "../render/ui.js";
+import { roleLabel } from "./roles.js";
+
+export function renderMemberRemoved(
+ ui: Ui,
+ member: { readonly name: string; readonly email: string },
+): string[] {
+ const { theme, glyphs } = ui;
+ return [
+ "",
+ ` ${theme.success(glyphs.tick)} Removed ${theme.strong(member.name)} ${theme.muted(`${glyphs.separator} ${member.email}`)}`,
+ "",
+ ];
+}
+
+export function renderMemberRole(
+ ui: Ui,
+ change: {
+ readonly name: string;
+ readonly role: string;
+ readonly previousRole: string;
+ },
+): string[] {
+ const { theme, glyphs } = ui;
+ const line =
+ change.role === change.previousRole
+ ? `${theme.strong(change.name)} is already ${roleLabel(change.role)}`
+ : `${theme.strong(change.name)} is now ${theme.strong(roleLabel(change.role))} ${theme.muted(`${glyphs.separator} was ${roleLabel(change.previousRole)}`)}`;
+ return ["", ` ${theme.success(glyphs.tick)} ${line}`, ""];
+}
diff --git a/packages/cli/src/admin/render-member-list.test.ts b/packages/cli/src/admin/render-member-list.test.ts
new file mode 100644
index 000000000..77216aa4a
--- /dev/null
+++ b/packages/cli/src/admin/render-member-list.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import type { MemberJson } from "./member-json.js";
+import { renderMemberList } from "./render-member-list.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+const now = new Date(2026, 9, 8, 12);
+
+const ada: MemberJson = {
+ id: "u_ada",
+ memberId: "m_ada",
+ name: "Ada Lovelace",
+ email: "[email protected]",
+ role: "owner",
+ joinedAt: new Date(2026, 2, 3, 12).toISOString(),
+};
+
+const grace: MemberJson = {
+ id: "u_grace",
+ memberId: "m_grace",
+ name: "Grace Hopper",
+ email: "[email protected]",
+ role: "member",
+ joinedAt: new Date(2026, 9, 8, 9).toISOString(),
+};
+
+describe("renderMemberList", () => {
+ it("shows name, email, role and join date in 80 columns", () => {
+ const lines = renderMemberList(ui, { members: [ada, grace], now });
+ expect(lines).toEqual([
+ "",
+ " Ada Lovelace [email protected] Owner Mar 3",
+ " Grace Hopper [email protected] Member Today",
+ "",
+ ]);
+ });
+
+ it("drops the join date and shortens long values to fit", () => {
+ const long: MemberJson = {
+ ...grace,
+ name: "Grace Brewster Murray Hopper of the United States Navy",
+ email: "[email protected]",
+ role: "admin,contractor",
+ };
+ const lines = renderMemberList(ui, { members: [ada, long], now });
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(80);
+ expect(lines[2]).toContain("Admin, Contractor");
+ expect(lines[2]).toContain("…");
+ });
+
+ it("says so when there are no members", () => {
+ expect(renderMemberList(ui, { members: [], now })).toEqual([
+ "",
+ " This workspace has no members.",
+ "",
+ ]);
+ });
+});
diff --git a/packages/cli/src/admin/render-member-list.ts b/packages/cli/src/admin/render-member-list.ts
new file mode 100644
index 000000000..717ac3647
--- /dev/null
+++ b/packages/cli/src/admin/render-member-list.ts
@@ -0,0 +1,56 @@
+import { type Cell, text } from "../render/cell.js";
+import { renderTable } from "../render/table.js";
+import { formatDue } from "../render/task-format.js";
+import type { Ui } from "../render/ui.js";
+import type { MemberJson } from "./member-json.js";
+import { roleLabel } from "./roles.js";
+
+export function formatDay(iso: string | null, now: Date): string {
+ if (!iso) return "";
+ const date = new Date(iso);
+ return Number.isNaN(date.getTime()) ? "" : formatDue(date, now);
+}
+
+export function renderMemberList(
+ ui: Ui,
+ view: { readonly members: ReadonlyArray<MemberJson>; readonly now: Date },
+): string[] {
+ const { theme } = ui;
+ if (view.members.length === 0) {
+ return ["", ` ${theme.muted("This workspace has no members.")}`, ""];
+ }
+ return [
+ "",
+ ...renderTable(
+ ui,
+ view.members,
+ [
+ {
+ header: "Name",
+ flex: true,
+ minWidth: 12,
+ cell: (member): Cell => [text(member.name, theme.strong)],
+ },
+ {
+ header: "Email",
+ flex: true,
+ minWidth: 16,
+ cell: (member): Cell => [text(member.email, theme.muted)],
+ },
+ {
+ header: "Role",
+ cell: (member): Cell => [text(roleLabel(member.role))],
+ },
+ {
+ header: "Joined",
+ optional: true,
+ cell: (member): Cell => [
+ text(formatDay(member.joinedAt, view.now), theme.muted),
+ ],
+ },
+ ],
+ { width: ui.caps.columns, indent: 2 },
+ ),
+ "",
+ ];
+}
diff --git a/packages/cli/src/admin/render-workspace-change.test.ts b/packages/cli/src/admin/render-workspace-change.test.ts
new file mode 100644
index 000000000..6bf78ceb4
--- /dev/null
+++ b/packages/cli/src/admin/render-workspace-change.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import { renderWorkspaceChange } from "./render-workspace-change.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+const acme = {
+ id: "ws_acme",
+ name: "Acme Studio",
+ slug: "acme-studio",
+ description: null,
+};
+
+describe("renderWorkspaceChange", () => {
+ it("confirms a new workspace and suggests switching to it", () => {
+ expect(
+ renderWorkspaceChange(ui, {
+ verb: "Created",
+ workspace: acme,
+ next: "Run kaneo workspace use acme-studio to make it your default.",
+ }),
+ ).toEqual([
+ "",
+ " ✓ Created Acme Studio · acme-studio",
+ "",
+ " Run kaneo workspace use acme-studio to make it your default.",
+ "",
+ ]);
+ });
+
+ it("lists what an edit changed", () => {
+ expect(
+ renderWorkspaceChange(ui, {
+ verb: "Updated",
+ workspace: acme,
+ changed: ["name", "description"],
+ }),
+ ).toEqual([
+ "",
+ " ✓ Updated Acme Studio · acme-studio",
+ " Changed name, description",
+ "",
+ ]);
+ });
+
+ it("drops the slug when leaving", () => {
+ expect(
+ renderWorkspaceChange(ui, { verb: "Left", workspace: acme }),
+ ).toEqual(["", " ✓ Left Acme Studio", ""]);
+ });
+
+ it("truncates a long name to 80 columns", () => {
+ const lines = renderWorkspaceChange(ui, {
+ verb: "Deleted",
+ workspace: { ...acme, name: "A".repeat(120) },
+ });
+ expect(lines[1]?.endsWith("… · acme-studio")).toBe(true);
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(80);
+ });
+});
diff --git a/packages/cli/src/admin/render-workspace-change.ts b/packages/cli/src/admin/render-workspace-change.ts
new file mode 100644
index 000000000..e41537a72
--- /dev/null
+++ b/packages/cli/src/admin/render-workspace-change.ts
@@ -0,0 +1,48 @@
+import type { Ui } from "../render/ui.js";
+import { stringWidth, truncate } from "../render/width.js";
+
+export type WorkspaceJson = {
+ readonly id: string;
+ readonly name: string;
+ readonly slug: string;
+ readonly description: string | null;
+};
+
+export type WorkspaceChange = {
+ readonly verb: "Created" | "Updated" | "Deleted" | "Left";
+ readonly workspace: WorkspaceJson;
+ readonly changed?: ReadonlyArray<string>;
+ readonly next?: string;
+};
+
+export function renderWorkspaceChange(
+ ui: Ui,
+ change: WorkspaceChange,
+): string[] {
+ const { theme, glyphs } = ui;
+ const head = ` ${theme.success(glyphs.tick)} ${change.verb} `;
+ const tail =
+ change.verb === "Left"
+ ? ""
+ : ` ${theme.muted(`${glyphs.separator} ${change.workspace.slug}`)}`;
+ const name = truncate(
+ change.workspace.name,
+ Math.max(ui.caps.columns - stringWidth(head) - stringWidth(tail), 8),
+ glyphs.ellipsis,
+ );
+ const lines = ["", `${head}${theme.strong(name)}${tail}`];
+ if (change.changed) {
+ lines.push(
+ ` ${theme.muted(
+ change.changed.length > 0
+ ? `Changed ${change.changed.join(", ")}`
+ : "Already up to date",
+ )}`,
+ );
+ }
+ lines.push("");
+ if (change.next) {
+ lines.push(` ${theme.muted(change.next)}`, "");
+ }
+ return lines;
+}
diff --git a/packages/cli/src/admin/resolve-role.ts b/packages/cli/src/admin/resolve-role.ts
new file mode 100644
index 000000000..44cd51186
--- /dev/null
+++ b/packages/cli/src/admin/resolve-role.ts
@@ -0,0 +1,45 @@
+import { Effect, Option } from "effect";
+import { listCustomRoles } from "../api/members.js";
+import { InvalidArgument } from "../errors/errors.js";
+import { Output } from "../output/output.js";
+import { withSpinner } from "../output/spinner.js";
+import { pick } from "../prompts/pick.js";
+import {
+ BUILT_IN_ROLES,
+ checkRole,
+ needsCustomRoles,
+ roleLabel,
+} from "./roles.js";
+
+export const resolveRole = Effect.fnUntraced(function* (
+ workspaceId: string,
+ input: Option.Option<string>,
+ options: { readonly question: string; readonly example: string },
+) {
+ const output = yield* Output;
+ if (Option.isSome(input)) {
+ const custom = needsCustomRoles(input.value)
+ ? yield* withSpinner("Loading roles")(listCustomRoles(workspaceId))
+ : [];
+ return yield* Effect.fromResult(checkRole(input.value, custom));
+ }
+ if (!output.interactive) {
+ return yield* new InvalidArgument({
+ message: "Which role?",
+ hint: `Pass owner, admin, member, viewer or a custom role, for example ${options.example}.`,
+ });
+ }
+ const custom = yield* withSpinner("Loading roles")(
+ listCustomRoles(workspaceId),
+ );
+ const roles = [
+ ...BUILT_IN_ROLES,
+ ...custom.filter(
+ (role) => !(BUILT_IN_ROLES as ReadonlyArray<string>).includes(role),
+ ),
+ ];
+ return yield* pick(
+ options.question,
+ roles.map((role) => ({ title: roleLabel(role), value: role })),
+ );
+});
diff --git a/packages/cli/src/admin/resolve-workspace.ts b/packages/cli/src/admin/resolve-workspace.ts
new file mode 100644
index 000000000..ac070d3f4
--- /dev/null
+++ b/packages/cli/src/admin/resolve-workspace.ts
@@ -0,0 +1,57 @@
+import { Effect, Option } from "effect";
+import { fromOrganizations } from "../api/from-organizations.js";
+import type { Workspace } from "../api/schemas.js";
+import {
+ listOrganizations,
+ type Organization,
+} from "../api/workspace-admin.js";
+import { matchWorkspace } from "../commands/workspace/match-workspace.js";
+import { InvalidArgument, NotFound } from "../errors/errors.js";
+import { withSpinner } from "../output/spinner.js";
+import { resolveWorkspaceId } from "../services/selection.js";
+
+export type ResolvedWorkspace = {
+ readonly workspace: Workspace;
+ readonly organization: Organization;
+};
+
+export const resolveWorkspace = Effect.fn("admin.resolveWorkspace")(function* (
+ reference: Option.Option<string>,
+) {
+ const wantedId = Option.isNone(reference)
+ ? yield* resolveWorkspaceId()
+ : undefined;
+ const organizations =
+ yield* withSpinner("Loading workspaces")(listOrganizations());
+ const workspaces = fromOrganizations(organizations);
+ const found = (workspace: Workspace) => {
+ const organization = organizations.find(
+ (candidate) => candidate.id === workspace.id,
+ );
+ return organization
+ ? Effect.succeed<ResolvedWorkspace>({ workspace, organization })
+ : Effect.fail(
+ new NotFound({ message: `Workspace ${workspace.id} not found.` }),
+ );
+ };
+ if (wantedId !== undefined) {
+ const workspace = workspaces.find((candidate) => candidate.id === wantedId);
+ if (workspace) return yield* found(workspace);
+ return yield* new NotFound({
+ message: `You are not a member of the workspace ${wantedId}.`,
+ });
+ }
+ const text = Option.getOrElse(reference, () => "");
+ const match = matchWorkspace(workspaces, text);
+ if (match.kind === "found") return yield* found(match.workspace);
+ if (match.kind === "ambiguous") {
+ return yield* new InvalidArgument({
+ message: `"${text}" matches ${match.candidates.length} workspaces.`,
+ hint: `Use a slug instead: ${match.candidates.map((workspace) => workspace.slug).join(", ")}.`,
+ });
+ }
+ return yield* new InvalidArgument({
+ message: `No workspace matches "${text}".`,
+ hint: "Run kaneo workspace list to see your workspaces.",
+ });
+});
diff --git a/packages/cli/src/admin/roles.test.ts b/packages/cli/src/admin/roles.test.ts
new file mode 100644
index 000000000..0de12b9d7
--- /dev/null
+++ b/packages/cli/src/admin/roles.test.ts
@@ -0,0 +1,85 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import {
+ checkRole,
+ isDemotion,
+ needsCustomRoles,
+ roleLabel,
+ roleRank,
+} from "./roles.js";
+
+describe("checkRole", () => {
+ it("accepts built-in roles without caring about case", () => {
+ expect(checkRole(" Admin ", [])).toEqual(Result.succeed("admin"));
+ expect(checkRole("viewer", [])).toEqual(Result.succeed("viewer"));
+ });
+
+ it("accepts custom roles of the workspace", () => {
+ expect(checkRole("Contractor", ["contractor"])).toEqual(
+ Result.succeed("contractor"),
+ );
+ });
+
+ it("names the built-in roles when nothing matches", () => {
+ const result = checkRole("boss", []);
+ expect(Result.isFailure(result) && result.failure).toMatchObject({
+ message: '"boss" is not a role in this workspace.',
+ hint: "Use owner, admin, member or viewer.",
+ });
+ });
+
+ it("lists custom roles in the hint without repeating built-in ones", () => {
+ const result = checkRole("boss", ["member", "contractor", "auditor"]);
+ expect(Result.isFailure(result) && result.failure.hint).toBe(
+ "Use owner, admin, member, viewer, or a custom role: contractor, auditor.",
+ );
+ });
+
+ it("refuses an empty role", () => {
+ const result = checkRole(" ", []);
+ expect(Result.isFailure(result) && result.failure.message).toBe(
+ "A role is required.",
+ );
+ });
+});
+
+describe("needsCustomRoles", () => {
+ it("only asks the server for roles that are not built in", () => {
+ expect(needsCustomRoles("MEMBER")).toBe(false);
+ expect(needsCustomRoles("contractor")).toBe(true);
+ });
+});
+
+describe("isDemotion", () => {
+ it("treats any change away from owner as a demotion", () => {
+ expect(isDemotion("owner", "admin")).toBe(true);
+ expect(isDemotion("owner", "owner")).toBe(false);
+ });
+
+ it("treats admin to a lower role as a demotion", () => {
+ expect(isDemotion("admin", "member")).toBe(true);
+ expect(isDemotion("admin", "contractor")).toBe(true);
+ expect(isDemotion("admin", "owner")).toBe(false);
+ });
+
+ it("does not ask when changing other roles", () => {
+ expect(isDemotion("member", "viewer")).toBe(false);
+ });
+});
+
+describe("roleLabel and roleRank", () => {
+ it("capitalizes each role in a list", () => {
+ expect(roleLabel("admin,contractor")).toBe("Admin, Contractor");
+ });
+
+ it("orders owners first and viewers last", () => {
+ const roles = ["viewer", "contractor", "member", "owner", "admin"];
+ expect([...roles].sort((a, b) => roleRank(a) - roleRank(b))).toEqual([
+ "owner",
+ "admin",
+ "member",
+ "contractor",
+ "viewer",
+ ]);
+ });
+});
diff --git a/packages/cli/src/admin/roles.ts b/packages/cli/src/admin/roles.ts
new file mode 100644
index 000000000..d65a39b7e
--- /dev/null
+++ b/packages/cli/src/admin/roles.ts
@@ -0,0 +1,70 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+
+export const BUILT_IN_ROLES = ["owner", "admin", "member", "viewer"] as const;
+
+export function roleParts(role: string): string[] {
+ return role
+ .split(",")
+ .map((part) => part.trim())
+ .filter(Boolean);
+}
+
+export function roleLabel(role: string): string {
+ return roleParts(role)
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
+ .join(", ");
+}
+
+export function hasRole(role: string, wanted: string): boolean {
+ return roleParts(role).includes(wanted);
+}
+
+export function roleRank(role: string): number {
+ if (hasRole(role, "owner")) return 0;
+ if (hasRole(role, "admin")) return 1;
+ if (hasRole(role, "member")) return 2;
+ if (hasRole(role, "viewer")) return 4;
+ return 3;
+}
+
+export function isDemotion(from: string, to: string): boolean {
+ if (hasRole(from, "owner")) return !hasRole(to, "owner");
+ if (hasRole(from, "admin")) {
+ return !hasRole(to, "owner") && !hasRole(to, "admin");
+ }
+ return false;
+}
+
+export function needsCustomRoles(input: string): boolean {
+ const role = input.trim().toLowerCase();
+ return !(BUILT_IN_ROLES as ReadonlyArray<string>).includes(role);
+}
+
+export function checkRole(
+ input: string,
+ customRoles: ReadonlyArray<string>,
+): Result.Result<string, InvalidArgument> {
+ const role = input.trim().toLowerCase();
+ const known = [
+ ...BUILT_IN_ROLES,
+ ...customRoles.filter(
+ (custom) => !(BUILT_IN_ROLES as ReadonlyArray<string>).includes(custom),
+ ),
+ ];
+ const match = known.find((candidate) => candidate.toLowerCase() === role);
+ if (match) return Result.succeed(match);
+ const custom = known.slice(BUILT_IN_ROLES.length);
+ return Result.fail(
+ new InvalidArgument({
+ message:
+ role === ""
+ ? "A role is required."
+ : `"${input.trim()}" is not a role in this workspace.`,
+ hint:
+ custom.length > 0
+ ? `Use owner, admin, member, viewer, or a custom role: ${custom.join(", ")}.`
+ : "Use owner, admin, member or viewer.",
+ }),
+ );
+}
diff --git a/packages/cli/src/admin/workspace-slug.test.ts b/packages/cli/src/admin/workspace-slug.test.ts
new file mode 100644
index 000000000..b6afb0dfa
--- /dev/null
+++ b/packages/cli/src/admin/workspace-slug.test.ts
@@ -0,0 +1,79 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import {
+ checkWorkspaceSlug,
+ deriveWorkspaceSlug,
+ slugify,
+} from "./workspace-slug.js";
+
+describe("slugify", () => {
+ it("lowercases and joins words with hyphens like the web app", () => {
+ expect(slugify(" Acme Studio ")).toBe("acme-studio");
+ expect(slugify("R&D_Team -- 2026")).toBe("rd-team-2026");
+ });
+
+ it("drops characters outside ASCII words", () => {
+ expect(slugify("Café Ünïcode!")).toBe("caf-ncode");
+ expect(slugify("日本")).toBe("");
+ });
+});
+
+describe("deriveWorkspaceSlug", () => {
+ const random = () => "abc123def456";
+
+ it("uses the plain slug when it is free", () => {
+ expect(deriveWorkspaceSlug("Acme Studio", ["side-project"], random)).toBe(
+ "acme-studio",
+ );
+ });
+
+ it("adds a random suffix when the slug is taken, ignoring case", () => {
+ expect(deriveWorkspaceSlug("Acme Studio", ["ACME-studio"], random)).toBe(
+ "acme-studio-abc123def456",
+ );
+ });
+
+ it("adds a suffix to reserved slugs", () => {
+ expect(deriveWorkspaceSlug("Dashboard", [], random)).toBe(
+ "dashboard-abc123def456",
+ );
+ });
+
+ it("falls back to workspace for names without slug characters", () => {
+ expect(deriveWorkspaceSlug("日本", [], random)).toBe("workspace");
+ });
+
+ it("draws again until the suffixed slug is free", () => {
+ const draws = ["one", "two"];
+ expect(
+ deriveWorkspaceSlug(
+ "Acme",
+ ["acme", "acme-one"],
+ () => draws.shift() ?? "",
+ ),
+ ).toBe("acme-two");
+ });
+});
+
+describe("checkWorkspaceSlug", () => {
+ it("accepts a clean slug", () => {
+ expect(checkWorkspaceSlug(" acme-studio ")).toEqual(
+ Result.succeed("acme-studio"),
+ );
+ });
+
+ it("suggests the cleaned form of an invalid slug", () => {
+ const result = checkWorkspaceSlug("Acme Studio");
+ expect(Result.isFailure(result)).toBe(true);
+ if (Result.isFailure(result)) {
+ expect(result.failure.hint).toContain("acme-studio");
+ }
+ });
+
+ it("refuses reserved slugs", () => {
+ const result = checkWorkspaceSlug("api");
+ expect(Result.isFailure(result) && result.failure.message).toBe(
+ '"api" is reserved by Kaneo.',
+ );
+ });
+});
diff --git a/packages/cli/src/admin/workspace-slug.ts b/packages/cli/src/admin/workspace-slug.ts
new file mode 100644
index 000000000..bfdb4a3c8
--- /dev/null
+++ b/packages/cli/src/admin/workspace-slug.ts
@@ -0,0 +1,80 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+
+const RANDOM_SUFFIX_LENGTH = 12;
+
+const RESERVED_SLUGS = new Set([
+ ".",
+ "..",
+ ".well-known",
+ "api",
+ "assets",
+ "auth",
+ "dashboard",
+ "device",
+ "images",
+ "invitation",
+ "invitations",
+ "mcp",
+ "onboarding",
+ "profile-setup",
+ "public-project",
+ "test-error",
+]);
+
+export function slugify(value: string): string {
+ return value
+ .toLowerCase()
+ .trim()
+ .replace(/[^\w\s-]/g, "")
+ .replace(/[\s_-]+/g, "-")
+ .replace(/^-+|-+$/g, "");
+}
+
+export function isReservedSlug(slug: string): boolean {
+ return RESERVED_SLUGS.has(slug.toLowerCase());
+}
+
+export function randomSlugSuffix(): string {
+ return crypto.randomUUID().replace(/-/g, "").slice(0, RANDOM_SUFFIX_LENGTH);
+}
+
+export function deriveWorkspaceSlug(
+ name: string,
+ taken: Iterable<string>,
+ random: () => string = randomSlugSuffix,
+): string {
+ const base = slugify(name) || "workspace";
+ const used = new Set(Array.from(taken, (slug) => slug.toLowerCase()));
+ if (!used.has(base) && !isReservedSlug(base)) return base;
+ let slug = `${base}-${random()}`;
+ while (used.has(slug)) slug = `${base}-${random()}`;
+ return slug;
+}
+
+export function checkWorkspaceSlug(
+ input: string,
+): Result.Result<string, InvalidArgument> {
+ const slug = input.trim();
+ const suggestion = slugify(slug);
+ if (slug === "" || slug !== suggestion) {
+ return Result.fail(
+ new InvalidArgument({
+ message: `"${input}" is not a valid workspace slug.`,
+ hint:
+ suggestion === ""
+ ? "Use lowercase letters, numbers and hyphens, for example acme-studio."
+ : `Use lowercase letters, numbers and hyphens, for example ${suggestion}.`,
+ }),
+ );
+ }
+ if (isReservedSlug(slug)) {
+ return Result.fail(
+ new InvalidArgument({
+ message: `"${slug}" is reserved by Kaneo.`,
+ hint: "Choose another slug.",
+ }),
+ );
+ }
+ return Result.succeed(slug);
+}
diff --git a/packages/cli/src/api/activity.ts b/packages/cli/src/api/activity.ts
new file mode 100644
index 000000000..827a378ce
--- /dev/null
+++ b/packages/cli/src/api/activity.ts
@@ -0,0 +1,32 @@
+import { Effect, Schema } from "effect";
+import { KaneoApi } from "./kaneo-api.js";
+
+export const ACTIVITY_LIMIT_MAX = 100;
+
+const NullableString = Schema.NullOr(Schema.String);
+
+export const TaskActivity = Schema.Struct({
+ id: Schema.String,
+ type: Schema.String,
+ createdAt: Schema.String,
+ userId: NullableString,
+ content: NullableString,
+ eventData: Schema.optionalKey(Schema.Unknown),
+ externalUserName: Schema.optionalKey(NullableString),
+});
+export type TaskActivity = typeof TaskActivity.Type;
+
+export const TaskActivityList = Schema.Array(TaskActivity);
+
+export const listTaskActivity = Effect.fnUntraced(function* (
+ taskId: string,
+ limit: number | undefined,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "GET",
+ `/api/activity/${encodeURIComponent(taskId)}`,
+ TaskActivityList,
+ { query: { limit } },
+ );
+});
diff --git a/packages/cli/src/api/bulk.ts b/packages/cli/src/api/bulk.ts
new file mode 100644
index 000000000..bc548a0ec
--- /dev/null
+++ b/packages/cli/src/api/bulk.ts
@@ -0,0 +1,26 @@
+import { Effect, Schema } from "effect";
+import { KaneoApi } from "./kaneo-api.js";
+
+export type BulkOperation =
+ | "updateStatus"
+ | "updatePriority"
+ | "updateAssignee"
+ | "delete"
+ | "addLabel"
+ | "removeLabel"
+ | "updateDueDate";
+
+export const BulkResult = Schema.Struct({
+ success: Schema.Boolean,
+ updatedCount: Schema.Number,
+});
+export type BulkResult = typeof BulkResult.Type;
+
+export const bulkUpdateTasks = Effect.fnUntraced(function* (body: {
+ readonly taskIds: ReadonlyArray<string>;
+ readonly operation: BulkOperation;
+ readonly value?: string | null;
+}) {
+ const api = yield* KaneoApi;
+ return yield* api.request("PATCH", "/api/task/bulk", BulkResult, { body });
+});
diff --git a/packages/cli/src/api/columns.ts b/packages/cli/src/api/columns.ts
new file mode 100644
index 000000000..0cb18140e
--- /dev/null
+++ b/packages/cli/src/api/columns.ts
@@ -0,0 +1,147 @@
+import { Effect, Schema } from "effect";
+import { KaneoApi } from "./kaneo-api.js";
+
+const NullableString = Schema.NullOr(Schema.String);
+
+export const ColumnDetail = Schema.Struct({
+ id: Schema.String,
+ projectId: Schema.String,
+ name: Schema.String,
+ slug: Schema.String,
+ position: Schema.Number,
+ icon: NullableString,
+ color: NullableString,
+ isFinal: Schema.Boolean,
+});
+export type ColumnDetail = typeof ColumnDetail.Type;
+
+const ColumnDetailList = Schema.Array(ColumnDetail);
+
+const BoardCount = Schema.Struct({
+ pagination: Schema.Struct({ total: Schema.Number }),
+});
+
+const ColumnTaskPage = Schema.Struct({
+ data: Schema.Struct({
+ columns: Schema.Array(
+ Schema.Struct({
+ slug: Schema.String,
+ tasks: Schema.Array(Schema.Struct({ id: Schema.String })),
+ }),
+ ),
+ }),
+ pagination: Schema.Struct({ totalPages: Schema.Number }),
+});
+
+export type CreateColumnBody = {
+ readonly name: string;
+ readonly icon?: string;
+ readonly color?: string;
+ readonly isFinal?: boolean;
+};
+
+export type UpdateColumnBody = {
+ readonly name?: string;
+ readonly icon?: string | null;
+ readonly color?: string | null;
+ readonly isFinal?: boolean;
+};
+
+const TASK_PAGE_SIZE = 100;
+
+export const listColumnDetails = Effect.fnUntraced(function* (
+ projectId: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "GET",
+ `/api/column/${encodeURIComponent(projectId)}`,
+ ColumnDetailList,
+ );
+});
+
+export const countColumnTasks = Effect.fnUntraced(function* (
+ projectId: string,
+ slug: string,
+) {
+ const api = yield* KaneoApi;
+ const page = yield* api.request(
+ "GET",
+ `/api/task/tasks/${encodeURIComponent(projectId)}`,
+ BoardCount,
+ { query: { status: slug, limit: 1 } },
+ );
+ return page.pagination.total;
+});
+
+export const listColumnTaskIds = Effect.fnUntraced(function* (
+ projectId: string,
+ slug: string,
+) {
+ const api = yield* KaneoApi;
+ const ids: string[] = [];
+ let page = 1;
+ let totalPages = 1;
+ while (page <= totalPages) {
+ const response = yield* api.request(
+ "GET",
+ `/api/task/tasks/${encodeURIComponent(projectId)}`,
+ ColumnTaskPage,
+ { query: { status: slug, limit: TASK_PAGE_SIZE, page } },
+ );
+ for (const column of response.data.columns) {
+ if (column.slug === slug) ids.push(...column.tasks.map((t) => t.id));
+ }
+ totalPages = response.pagination.totalPages;
+ page += 1;
+ }
+ return ids;
+});
+
+export const createColumn = Effect.fnUntraced(function* (
+ projectId: string,
+ body: CreateColumnBody,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "POST",
+ `/api/column/${encodeURIComponent(projectId)}`,
+ ColumnDetail,
+ { body },
+ );
+});
+
+export const updateColumn = Effect.fnUntraced(function* (
+ id: string,
+ body: UpdateColumnBody,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "PUT",
+ `/api/column/${encodeURIComponent(id)}`,
+ ColumnDetail,
+ { body },
+ );
+});
+
+export const reorderColumns = Effect.fnUntraced(function* (
+ projectId: string,
+ columns: ReadonlyArray<{ readonly id: string; readonly position: number }>,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "PUT",
+ `/api/column/reorder/${encodeURIComponent(projectId)}`,
+ ColumnDetailList,
+ { body: { columns } },
+ );
+});
+
+export const deleteColumn = Effect.fnUntraced(function* (id: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "DELETE",
+ `/api/column/${encodeURIComponent(id)}`,
+ ColumnDetail,
+ );
+});
diff --git a/packages/cli/src/api/comments.ts b/packages/cli/src/api/comments.ts
new file mode 100644
index 000000000..20113ae88
--- /dev/null
+++ b/packages/cli/src/api/comments.ts
@@ -0,0 +1,48 @@
+import { Effect, Schema } from "effect";
+import { KaneoApi } from "./kaneo-api.js";
+
+export const TaskComment = Schema.Struct({
+ id: Schema.String,
+ taskId: Schema.String,
+ userId: Schema.NullOr(Schema.String),
+ content: Schema.String,
+ createdAt: Schema.String,
+ updatedAt: Schema.String,
+ user: Schema.NullOr(Schema.Struct({ name: Schema.String })),
+});
+export type TaskComment = typeof TaskComment.Type;
+
+export const TaskCommentList = Schema.Array(TaskComment);
+
+export const CommentRow = Schema.Struct({
+ id: Schema.String,
+ taskId: Schema.String,
+ content: Schema.NullOr(Schema.String),
+ createdAt: Schema.String,
+ updatedAt: Schema.String,
+});
+export type CommentRow = typeof CommentRow.Type;
+
+function commentPath(id: string): string {
+ return `/api/comment/${encodeURIComponent(id)}`;
+}
+
+export const listComments = Effect.fnUntraced(function* (taskId: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request("GET", commentPath(taskId), TaskCommentList);
+});
+
+export const updateComment = Effect.fnUntraced(function* (
+ id: string,
+ content: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("PUT", commentPath(id), CommentRow, {
+ body: { content },
+ });
+});
+
+export const deleteComment = Effect.fnUntraced(function* (id: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request("DELETE", commentPath(id), CommentRow);
+});
diff --git a/packages/cli/src/api/custom-fields.ts b/packages/cli/src/api/custom-fields.ts
new file mode 100644
index 000000000..a5304a0f7
--- /dev/null
+++ b/packages/cli/src/api/custom-fields.ts
@@ -0,0 +1,84 @@
+import { Effect, Schema } from "effect";
+import { KaneoApi } from "./kaneo-api.js";
+
+const NullableString = Schema.NullOr(Schema.String);
+
+export const CustomField = Schema.Struct({
+ id: Schema.String,
+ projectId: Schema.String,
+ name: Schema.String,
+ type: Schema.String,
+ required: Schema.Boolean,
+ defaultValue: NullableString,
+ options: Schema.NullOr(Schema.Unknown),
+});
+export type CustomField = typeof CustomField.Type;
+
+const CustomFieldList = Schema.Array(CustomField);
+
+export const CustomFieldValue = Schema.Struct({
+ fieldId: Schema.String,
+ value: NullableString,
+});
+export type CustomFieldValue = typeof CustomFieldValue.Type;
+
+const CustomFieldValueList = Schema.Array(CustomFieldValue);
+
+const SavedValue = Schema.Struct({
+ fieldId: Schema.String,
+ value: NullableString,
+});
+
+export const listCustomFields = Effect.fnUntraced(function* (
+ projectId: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "GET",
+ `/api/custom-field/project/${encodeURIComponent(projectId)}`,
+ CustomFieldList,
+ );
+});
+
+export const createCustomField = Effect.fnUntraced(function* (body: {
+ readonly projectId: string;
+ readonly name: string;
+ readonly type: string;
+ readonly options?: ReadonlyArray<string>;
+}) {
+ const api = yield* KaneoApi;
+ return yield* api.request("POST", "/api/custom-field", CustomField, {
+ body,
+ });
+});
+
+export const deleteCustomField = Effect.fnUntraced(function* (id: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "DELETE",
+ `/api/custom-field/${encodeURIComponent(id)}`,
+ CustomField,
+ );
+});
+
+export const listTaskFieldValues = Effect.fnUntraced(function* (
+ taskId: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "GET",
+ `/api/custom-field/task/${encodeURIComponent(taskId)}`,
+ CustomFieldValueList,
+ );
+});
+
+export const setTaskFieldValue = Effect.fnUntraced(function* (body: {
+ readonly taskId: string;
+ readonly fieldId: string;
+ readonly value: string;
+}) {
+ const api = yield* KaneoApi;
+ return yield* api.request("PUT", "/api/custom-field/value", SavedValue, {
+ body,
+ });
+});
diff --git a/packages/cli/src/api/endpoints.ts b/packages/cli/src/api/endpoints.ts
new file mode 100644
index 000000000..b35b758e9
--- /dev/null
+++ b/packages/cli/src/api/endpoints.ts
@@ -0,0 +1,123 @@
+import { Effect } from "effect";
+import type { Credentials } from "../services/session.js";
+import { fromOrganizations } from "./from-organizations.js";
+import { KaneoApi, type Query } from "./kaneo-api.js";
+import {
+ AssignedTasks,
+ BoardPage,
+ ColumnList,
+ CurrentUser,
+ OrganizationList,
+ Project,
+ ProjectList,
+ Workspace,
+ WorkspaceList,
+ WorkspaceMemberList,
+} from "./schemas.js";
+
+export const getCurrentUser = Effect.fnUntraced(function* (
+ credentials?: Credentials,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("GET", "/api/user/me", CurrentUser, {
+ credentials,
+ });
+});
+
+export const listWorkspaces = Effect.fnUntraced(function* (
+ credentials?: Credentials,
+) {
+ const api = yield* KaneoApi;
+ return yield* api
+ .request("GET", "/api/workspace", WorkspaceList, { credentials })
+ .pipe(
+ Effect.catchTag("NotFound", () =>
+ api
+ .request("GET", "/api/auth/organization/list", OrganizationList, {
+ credentials,
+ })
+ .pipe(Effect.map(fromOrganizations)),
+ ),
+ );
+});
+
+export const getWorkspace = Effect.fnUntraced(function* (workspaceId: string) {
+ const api = yield* KaneoApi;
+ return yield* api
+ .request(
+ "GET",
+ `/api/workspace/${encodeURIComponent(workspaceId)}`,
+ Workspace,
+ )
+ .pipe(
+ Effect.catchTag("NotFound", (notFound) =>
+ api
+ .request("GET", "/api/auth/organization/list", OrganizationList)
+ .pipe(
+ Effect.map(fromOrganizations),
+ Effect.flatMap((workspaces) => {
+ const match = workspaces.find(
+ (workspace) => workspace.id === workspaceId,
+ );
+ return match ? Effect.succeed(match) : Effect.fail(notFound);
+ }),
+ ),
+ ),
+ );
+});
+
+export const listProjects = Effect.fnUntraced(function* (workspaceId: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request("GET", "/api/project", ProjectList, {
+ query: { workspaceId },
+ });
+});
+
+export const getBoardPage = Effect.fnUntraced(function* (
+ projectId: string,
+ query: Query,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "GET",
+ `/api/task/tasks/${encodeURIComponent(projectId)}`,
+ BoardPage,
+ { query },
+ );
+});
+
+export const listAssignedTasks = Effect.fnUntraced(function* (
+ workspaceId: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("GET", "/api/task/assigned", AssignedTasks, {
+ query: { workspaceId },
+ });
+});
+
+export const getProject = Effect.fnUntraced(function* (projectId: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "GET",
+ `/api/project/${encodeURIComponent(projectId)}`,
+ Project,
+ );
+});
+
+export const listColumns = Effect.fnUntraced(function* (projectId: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "GET",
+ `/api/column/${encodeURIComponent(projectId)}`,
+ ColumnList,
+ );
+});
+
+export const listMembers = Effect.fnUntraced(function* (workspaceId: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "GET",
+ `/api/workspace/${encodeURIComponent(workspaceId)}/members`,
+ WorkspaceMemberList,
+ );
+});
diff --git a/packages/cli/src/api/error-body.test.ts b/packages/cli/src/api/error-body.test.ts
new file mode 100644
index 000000000..1b729da2a
--- /dev/null
+++ b/packages/cli/src/api/error-body.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from "vite-plus/test";
+import { parseErrorBody, parseRetryAfter } from "./error-body.js";
+
+describe("parseErrorBody", () => {
+ it("reads the JSON error shape", () => {
+ expect(
+ parseErrorBody(
+ '{"message":"Insufficient permissions","code":"MISSING_PERMISSION","missingPermissions":["task:delete"]}',
+ 403,
+ ),
+ ).toEqual({
+ message: "Insufficient permissions",
+ code: "MISSING_PERMISSION",
+ missingPermissions: ["task:delete"],
+ });
+ });
+
+ it("falls back to plain text bodies from older servers", () => {
+ expect(parseErrorBody("Task not found", 404)).toEqual({
+ message: "Task not found",
+ code: null,
+ missingPermissions: [],
+ });
+ expect(parseErrorBody("", 502).message).toBe("HTTP 502");
+ });
+
+ it("reads OAuth style errors", () => {
+ expect(parseErrorBody('{"error":"invalid_token"}', 401).message).toBe(
+ "invalid_token",
+ );
+ });
+});
+
+describe("parseRetryAfter", () => {
+ it("reads seconds and dates", () => {
+ expect(parseRetryAfter("7", 0)).toBe(7);
+ expect(parseRetryAfter(new Date(30_000).toUTCString(), 0)).toBe(30);
+ expect(parseRetryAfter(undefined, 0)).toBeNull();
+ expect(parseRetryAfter("soon", 0)).toBeNull();
+ });
+});
diff --git a/packages/cli/src/api/error-body.ts b/packages/cli/src/api/error-body.ts
new file mode 100644
index 000000000..a4ae3c0cd
--- /dev/null
+++ b/packages/cli/src/api/error-body.ts
@@ -0,0 +1,47 @@
+export type ErrorBody = {
+ readonly message: string;
+ readonly code: string | null;
+ readonly missingPermissions: ReadonlyArray<string>;
+};
+
+export function parseErrorBody(text: string, status: number): ErrorBody {
+ const fallback = text.trim().slice(0, 500) || `HTTP ${status}`;
+ try {
+ const body: unknown = JSON.parse(text);
+ if (typeof body !== "object" || body === null) {
+ return { message: fallback, code: null, missingPermissions: [] };
+ }
+ const record = body as Record<string, unknown>;
+ const message =
+ typeof record.message === "string" && record.message.trim() !== ""
+ ? record.message
+ : typeof record.error === "string"
+ ? record.error
+ : fallback;
+ const missing = Array.isArray(record.missingPermissions)
+ ? record.missingPermissions.filter(
+ (value): value is string => typeof value === "string",
+ )
+ : [];
+ return {
+ message,
+ code: typeof record.code === "string" ? record.code : null,
+ missingPermissions: missing,
+ };
+ } catch {
+ return { message: fallback, code: null, missingPermissions: [] };
+ }
+}
+
+export function parseRetryAfter(
+ value: string | undefined,
+ now: number,
+): number | null {
+ if (!value) return null;
+ const seconds = Number(value);
+ if (Number.isFinite(seconds)) return Math.max(0, Math.ceil(seconds));
+ const date = Date.parse(value);
+ return Number.isNaN(date)
+ ? null
+ : Math.max(0, Math.ceil((date - now) / 1000));
+}
diff --git a/packages/cli/src/api/export-import.ts b/packages/cli/src/api/export-import.ts
new file mode 100644
index 000000000..262bca143
--- /dev/null
+++ b/packages/cli/src/api/export-import.ts
@@ -0,0 +1,84 @@
+import { Effect, Schema } from "effect";
+import { KaneoApi } from "./kaneo-api.js";
+
+const NullableString = Schema.NullOr(Schema.String);
+
+export const ExportedTask = Schema.Struct({
+ title: Schema.String,
+ description: Schema.String,
+ status: Schema.String,
+ priority: Schema.String,
+ dueDate: NullableString,
+ startDate: NullableString,
+ userId: NullableString,
+ labels: Schema.Array(
+ Schema.Struct({ name: Schema.String, color: Schema.String }),
+ ),
+});
+export type ExportedTask = typeof ExportedTask.Type;
+
+export const TaskExport = Schema.Struct({
+ project: Schema.Struct({
+ name: Schema.String,
+ slug: Schema.String,
+ description: NullableString,
+ exportedAt: Schema.String,
+ }),
+ tasks: Schema.Array(ExportedTask),
+});
+export type TaskExport = typeof TaskExport.Type;
+
+export type ImportTaskBody = {
+ readonly title: string;
+ readonly description?: string;
+ readonly status: string;
+ readonly priority?: string;
+ readonly startDate?: string | null;
+ readonly dueDate?: string | null;
+ readonly userId?: string | null;
+};
+
+export const ImportOutcome = Schema.Struct({
+ success: Schema.Boolean,
+ error: Schema.optionalKey(Schema.String),
+ warnings: Schema.optionalKey(Schema.Array(Schema.String)),
+ task: Schema.Struct({
+ id: Schema.optionalKey(Schema.String),
+ number: Schema.optionalKey(Schema.NullOr(Schema.Number)),
+ title: Schema.String,
+ status: Schema.optionalKey(Schema.String),
+ }),
+});
+export type ImportOutcome = typeof ImportOutcome.Type;
+
+export const ImportResult = Schema.Struct({
+ results: Schema.Struct({
+ total: Schema.Number,
+ successful: Schema.Number,
+ failed: Schema.Number,
+ tasks: Schema.Array(ImportOutcome),
+ }),
+});
+export type ImportResult = typeof ImportResult.Type;
+
+export const exportTasks = Effect.fnUntraced(function* (projectId: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "GET",
+ `/api/task/export/${encodeURIComponent(projectId)}`,
+ TaskExport,
+ );
+});
+
+export const importTasks = Effect.fnUntraced(function* (
+ projectId: string,
+ tasks: ReadonlyArray<ImportTaskBody>,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "POST",
+ `/api/task/import/${encodeURIComponent(projectId)}`,
+ ImportResult,
+ { body: { tasks } },
+ );
+});
diff --git a/packages/cli/src/api/external-links.ts b/packages/cli/src/api/external-links.ts
new file mode 100644
index 000000000..0d9903c49
--- /dev/null
+++ b/packages/cli/src/api/external-links.ts
@@ -0,0 +1,51 @@
+import { Effect, Schema } from "effect";
+import { KaneoApi } from "./kaneo-api.js";
+
+const NullableString = Schema.NullOr(Schema.String);
+
+export const ExternalLink = Schema.Struct({
+ id: Schema.String,
+ taskId: Schema.String,
+ integrationId: NullableString,
+ resourceType: Schema.String,
+ url: Schema.String,
+ title: NullableString,
+ createdAt: Schema.String,
+ integration: Schema.optionalKey(
+ Schema.NullOr(Schema.Struct({ id: Schema.String, type: Schema.String })),
+ ),
+});
+export type ExternalLink = typeof ExternalLink.Type;
+
+const ExternalLinkList = Schema.Array(ExternalLink);
+
+const DeletedLink = Schema.Struct({ id: Schema.String });
+
+function linksPath(taskId: string, suffix = ""): string {
+ return `/api/external-link/task/${encodeURIComponent(taskId)}${suffix}`;
+}
+
+export const listExternalLinks = Effect.fnUntraced(function* (taskId: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request("GET", linksPath(taskId), ExternalLinkList);
+});
+
+export const createExternalLink = Effect.fnUntraced(function* (
+ taskId: string,
+ body: { readonly url: string; readonly title?: string },
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("POST", linksPath(taskId), ExternalLink, { body });
+});
+
+export const deleteExternalLink = Effect.fnUntraced(function* (
+ taskId: string,
+ linkId: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "DELETE",
+ linksPath(taskId, `/${encodeURIComponent(linkId)}`),
+ DeletedLink,
+ );
+});
diff --git a/packages/cli/src/api/from-organizations.ts b/packages/cli/src/api/from-organizations.ts
new file mode 100644
index 000000000..05e968986
--- /dev/null
+++ b/packages/cli/src/api/from-organizations.ts
@@ -0,0 +1,40 @@
+import type { OrganizationList, Workspace } from "./schemas.js";
+
+function metadataDescription(metadata: unknown): string | null {
+ const parsed =
+ typeof metadata === "string"
+ ? (() => {
+ try {
+ return JSON.parse(metadata) as unknown;
+ } catch {
+ return null;
+ }
+ })()
+ : metadata;
+ const description = (parsed as { description?: unknown } | null)?.description;
+ return typeof description === "string" && description.trim() !== ""
+ ? description
+ : null;
+}
+
+export function fromOrganizations(
+ organizations: OrganizationList,
+): Workspace[] {
+ return organizations
+ .map((organization) => ({
+ id: organization.id,
+ name: organization.name,
+ slug: organization.slug,
+ logo: organization.logo ?? null,
+ description:
+ organization.description?.trim() ||
+ metadataDescription(organization.metadata),
+ createdAt: String(organization.createdAt),
+ role: null,
+ }))
+ .sort(
+ (a, b) =>
+ a.name.toLowerCase().localeCompare(b.name.toLowerCase()) ||
+ a.id.localeCompare(b.id),
+ );
+}
diff --git a/packages/cli/src/api/invitations.ts b/packages/cli/src/api/invitations.ts
new file mode 100644
index 000000000..c8b361398
--- /dev/null
+++ b/packages/cli/src/api/invitations.ts
@@ -0,0 +1,134 @@
+import { Effect, Schema } from "effect";
+import { KaneoApi } from "./kaneo-api.js";
+
+export const SentInvitation = Schema.Struct({
+ id: Schema.String,
+ email: Schema.String,
+ role: Schema.String,
+ status: Schema.String,
+ expiresAt: Schema.Unknown,
+ createdAt: Schema.Unknown,
+});
+export type SentInvitation = typeof SentInvitation.Type;
+
+const SentInvitationList = Schema.Array(SentInvitation);
+
+export const ReceivedInvitation = Schema.Struct({
+ id: Schema.String,
+ email: Schema.String,
+ workspaceId: Schema.String,
+ workspaceName: Schema.String,
+ inviterName: Schema.String,
+ expiresAt: Schema.String,
+});
+export type ReceivedInvitation = typeof ReceivedInvitation.Type;
+
+const ReceivedInvitationList = Schema.Array(ReceivedInvitation);
+
+const InvitationAnswer = Schema.Struct({
+ invitation: Schema.optionalKey(
+ Schema.NullOr(
+ Schema.Struct({ organizationId: Schema.optionalKey(Schema.String) }),
+ ),
+ ),
+});
+
+const InvitationDetails = Schema.Struct({
+ valid: Schema.Boolean,
+ invitation: Schema.optionalKey(
+ Schema.Struct({ workspaceName: Schema.String }),
+ ),
+ error: Schema.optionalKey(Schema.String),
+});
+
+const Anything = Schema.Unknown;
+
+export const getInvitationDetails = Effect.fnUntraced(function* (
+ invitationId: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "GET",
+ `/api/invitation/${encodeURIComponent(invitationId)}`,
+ InvitationDetails,
+ );
+});
+
+export const listSentInvitations = Effect.fnUntraced(function* (
+ workspaceId: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "GET",
+ "/api/auth/organization/list-invitations",
+ SentInvitationList,
+ { query: { organizationId: workspaceId } },
+ );
+});
+
+export const listReceivedInvitations = Effect.fnUntraced(function* () {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "GET",
+ "/api/invitation/pending",
+ ReceivedInvitationList,
+ );
+});
+
+export const inviteMember = Effect.fnUntraced(function* (body: {
+ readonly workspaceId: string;
+ readonly email: string;
+ readonly role: string;
+ readonly resend: boolean;
+}) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "POST",
+ "/api/auth/organization/invite-member",
+ SentInvitation,
+ {
+ body: {
+ organizationId: body.workspaceId,
+ email: body.email,
+ role: body.role,
+ ...(body.resend ? { resend: true } : {}),
+ },
+ },
+ );
+});
+
+export const acceptInvitation = Effect.fnUntraced(function* (
+ invitationId: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "POST",
+ "/api/auth/organization/accept-invitation",
+ InvitationAnswer,
+ { body: { invitationId } },
+ );
+});
+
+export const rejectInvitation = Effect.fnUntraced(function* (
+ invitationId: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "POST",
+ "/api/auth/organization/reject-invitation",
+ InvitationAnswer,
+ { body: { invitationId } },
+ );
+});
+
+export const cancelInvitation = Effect.fnUntraced(function* (
+ invitationId: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "POST",
+ "/api/auth/organization/cancel-invitation",
+ Anything,
+ { body: { invitationId } },
+ );
+});
diff --git a/packages/cli/src/api/kaneo-api.test.ts b/packages/cli/src/api/kaneo-api.test.ts
new file mode 100644
index 000000000..f09fd212e
--- /dev/null
+++ b/packages/cli/src/api/kaneo-api.test.ts
@@ -0,0 +1,230 @@
+import { Effect, Fiber, Layer, Option, Result, Schema } from "effect";
+import { TestClock } from "effect/testing";
+import { describe, expect, it } from "vite-plus/test";
+import { emptyConfig, withProfile } from "../config/format.js";
+import {
+ fakeHttpClient,
+ json,
+ memoryConfigStore,
+ type RecordedRequest,
+ type Responder,
+ testSession,
+} from "../testing/test-layers.js";
+import { KaneoApi, KaneoApiLayer } from "./kaneo-api.js";
+
+const User = Schema.Struct({ id: Schema.String, name: Schema.String });
+
+function run<A, E>(
+ effect: Effect.Effect<A, E, KaneoApi>,
+ respond: Responder,
+ options: {
+ session?: Parameters<typeof testSession>[0];
+ store?: ReturnType<typeof memoryConfigStore>;
+ } = {},
+) {
+ const recorded: RecordedRequest[] = [];
+ const store = options.store ?? memoryConfigStore();
+ const layer = KaneoApiLayer.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ fakeHttpClient(respond, recorded),
+ testSession(options.session),
+ store.layer,
+ ),
+ ),
+ );
+ return {
+ recorded,
+ result: Effect.runPromise(
+ Effect.result(effect.pipe(Effect.provide(layer))),
+ ),
+ };
+}
+
+const getUser = Effect.gen(function* () {
+ const api = yield* KaneoApi;
+ return yield* api.request("GET", "/api/user/me", User, {
+ query: { a: 1, b: undefined },
+ });
+});
+
+describe("KaneoApi", () => {
+ it("sends the bearer token and decodes the body", async () => {
+ const { recorded, result } = run(getUser, () =>
+ json({ id: "u1", name: "Ada", extra: 1 }),
+ );
+ expect(await result).toEqual(Result.succeed({ id: "u1", name: "Ada" }));
+ expect(recorded[0]).toMatchObject({
+ method: "GET",
+ url: "https://kaneo.test/api/user/me?a=1",
+ authorization: "Bearer test-token",
+ });
+ });
+
+ it("reports API drift as an unexpected response", async () => {
+ const { result } = run(getUser, () => json({ id: 42 }));
+ const outcome = await result;
+ expect(Result.isFailure(outcome) && outcome.failure._tag).toBe(
+ "UnexpectedResponse",
+ );
+ });
+
+ it("maps JSON and text errors", async () => {
+ const forbidden = await run(getUser, () =>
+ json(
+ {
+ message: "Insufficient permissions",
+ code: "MISSING_PERMISSION",
+ missingPermissions: ["task:read"],
+ },
+ 403,
+ ),
+ ).result;
+ expect(Result.isFailure(forbidden) && forbidden.failure).toMatchObject({
+ _tag: "PermissionDenied",
+ missingPermissions: ["task:read"],
+ });
+ const missing = await run(
+ getUser,
+ () => new Response("Task not found", { status: 404 }),
+ ).result;
+ expect(Result.isFailure(missing) && missing.failure).toMatchObject({
+ _tag: "NotFound",
+ message: "Task not found",
+ });
+ });
+
+ it("forgets an expired stored token", async () => {
+ const store = memoryConfigStore(
+ withProfile(emptyConfig, "default", () => ({
+ apiUrl: "https://kaneo.test",
+ token: "old",
+ })),
+ );
+ const outcome = await run(
+ getUser,
+ () => new Response("Unauthorized", { status: 401 }),
+ {
+ store,
+ },
+ ).result;
+ expect(Result.isFailure(outcome) && outcome.failure._tag).toBe(
+ "SessionExpired",
+ );
+ expect(store.read().profiles.default?.token).toBeUndefined();
+ expect(store.read().profiles.default?.apiUrl).toBe("https://kaneo.test");
+ });
+
+ it("keeps the login when a route answers 401 but the session still works", async () => {
+ const store = memoryConfigStore(
+ withProfile(emptyConfig, "default", () => ({
+ apiUrl: "https://kaneo.test",
+ token: "keep",
+ })),
+ );
+ const removeMember = Effect.gen(function* () {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "POST",
+ "/api/auth/organization/remove-member",
+ Schema.Unknown,
+ {
+ body: {},
+ },
+ );
+ });
+ const outcome = await run(
+ removeMember,
+ (request) =>
+ request.url.endsWith("/api/user/me")
+ ? json({ id: "u1", name: "Ada" })
+ : json({ message: "You are not allowed to delete this member" }, 401),
+ { store },
+ ).result;
+ expect(Result.isFailure(outcome) && outcome.failure).toMatchObject({
+ _tag: "PermissionDenied",
+ message: "You are not allowed to delete this member",
+ });
+ expect(store.read().profiles.default?.token).toBe("keep");
+ });
+
+ it("treats a rejected API key as a credentials problem, not an expired login", async () => {
+ const store = memoryConfigStore(
+ withProfile(emptyConfig, "default", () => ({
+ apiUrl: "https://kaneo.test",
+ token: "keep",
+ })),
+ );
+ const outcome = await run(
+ getUser,
+ () => new Response("Unauthorized", { status: 401 }),
+ {
+ store,
+ session: { tokenSource: "env" },
+ },
+ ).result;
+ expect(Result.isFailure(outcome) && outcome.failure._tag).toBe(
+ "CredentialsRejected",
+ );
+ expect(store.read().profiles.default?.token).toBe("keep");
+ });
+
+ it("fails without credentials before sending anything", async () => {
+ const { recorded, result } = run(getUser, () => json({}), {
+ session: { credentials: Option.none() },
+ });
+ const outcome = await result;
+ expect(Result.isFailure(outcome) && outcome.failure._tag).toBe(
+ "NotSignedIn",
+ );
+ expect(recorded).toHaveLength(0);
+ });
+
+ it("retries a 429 after Retry-After", async () => {
+ let calls = 0;
+ const recorded: RecordedRequest[] = [];
+ const layer = KaneoApiLayer.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ fakeHttpClient(() => {
+ calls += 1;
+ return calls === 1
+ ? new Response("Too many", {
+ status: 429,
+ headers: { "retry-after": "3" },
+ })
+ : json({ id: "u1", name: "Ada" });
+ }, recorded),
+ testSession(),
+ memoryConfigStore().layer,
+ ),
+ ),
+ );
+ const program = Effect.gen(function* () {
+ const fiber = yield* Effect.forkChild(getUser);
+ yield* TestClock.adjust("2 seconds");
+ expect(calls).toBe(1);
+ yield* TestClock.adjust("2 seconds");
+ return yield* Fiber.await(fiber);
+ }).pipe(Effect.provide(Layer.merge(layer, TestClock.layer())));
+ const exit = await Effect.runPromise(program);
+ expect(exit._tag).toBe("Success");
+ expect(calls).toBe(2);
+ });
+
+ it("does not wait for long Retry-After values", async () => {
+ const { result } = run(
+ getUser,
+ () =>
+ new Response("Too many", {
+ status: 429,
+ headers: { "retry-after": "120" },
+ }),
+ );
+ const outcome = await result;
+ expect(Result.isFailure(outcome) && outcome.failure).toMatchObject({
+ _tag: "RateLimited",
+ retryAfterSeconds: 120,
+ });
+ });
+});
diff --git a/packages/cli/src/api/kaneo-api.ts b/packages/cli/src/api/kaneo-api.ts
new file mode 100644
index 000000000..8f57d5efb
--- /dev/null
+++ b/packages/cli/src/api/kaneo-api.ts
@@ -0,0 +1,224 @@
+import {
+ Context,
+ Duration,
+ Effect,
+ Layer,
+ Option,
+ Redacted,
+ Schedule,
+ Schema,
+} from "effect";
+import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
+import { ConfigStore } from "../config/config-store.js";
+import { withProfile } from "../config/format.js";
+import {
+ type ApiFailure,
+ NotSignedIn,
+ PermissionDenied,
+ RateLimited,
+ ServerUnreachable,
+ UnexpectedResponse,
+} from "../errors/errors.js";
+import { type Credentials, Session } from "../services/session.js";
+import { parseErrorBody, parseRetryAfter } from "./error-body.js";
+import { toApiFailure } from "./to-api-failure.js";
+
+export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
+
+export type Query = Readonly<
+ Record<string, string | number | boolean | undefined>
+>;
+
+export type RequestOptions = {
+ readonly query?: Query;
+ readonly body?: unknown;
+ readonly credentials?: Credentials;
+};
+
+export type KaneoApiShape = {
+ readonly request: <T>(
+ method: HttpMethod,
+ path: string,
+ schema: Schema.Decoder<T>,
+ options?: RequestOptions,
+ ) => Effect.Effect<T, ApiFailure>;
+};
+
+export class KaneoApi extends Context.Service<KaneoApi, KaneoApiShape>()(
+ "kaneo/KaneoApi",
+) {}
+
+const REQUEST_TIMEOUT = Duration.seconds(15);
+const MAX_RETRY_AFTER_SECONDS = 10;
+
+const rateLimitRetry = Schedule.recurs(2).pipe(
+ Schedule.addDelay(({ input }) =>
+ Effect.succeed(
+ Duration.seconds(
+ input instanceof RateLimited ? (input.retryAfterSeconds ?? 1) : 1,
+ ),
+ ),
+ ),
+);
+
+function isRetryable(error: ApiFailure): boolean {
+ return (
+ error._tag === "RateLimited" &&
+ (error.retryAfterSeconds ?? 0) <= MAX_RETRY_AFTER_SECONDS
+ );
+}
+
+function describeTransportError(error: unknown): string {
+ const cause = (error as { cause?: unknown } | null)?.cause;
+ const code = (cause as { cause?: { code?: unknown } } | null)?.cause?.code;
+ if (typeof code === "string") return code;
+ if (cause instanceof Error) return cause.message;
+ return error instanceof Error ? error.message : String(error);
+}
+
+function toUrlParams(query: Query | undefined): Record<string, string> {
+ const params: Record<string, string> = {};
+ for (const [key, value] of Object.entries(query ?? {})) {
+ if (value !== undefined) params[key] = String(value);
+ }
+ return params;
+}
+
+export const KaneoApiLayer = Layer.effect(
+ KaneoApi,
+ Effect.gen(function* () {
+ const session = yield* Session;
+ const store = yield* ConfigStore;
+ const client = yield* HttpClient.HttpClient;
+
+ const forgetStoredToken = store.load.pipe(
+ Effect.flatMap((config) =>
+ store.save(
+ withProfile(config, session.profileName, (profile) => {
+ const { token: _token, ...rest } = profile ?? {
+ apiUrl: session.apiUrl,
+ };
+ return rest;
+ }),
+ ),
+ ),
+ Effect.ignore,
+ );
+
+ const sessionStillValid = (token: Redacted.Redacted<string>) =>
+ client
+ .execute(
+ HttpClientRequest.get(`${session.apiUrl}/api/user/me`).pipe(
+ HttpClientRequest.bearerToken(Redacted.value(token)),
+ HttpClientRequest.acceptJson,
+ ),
+ )
+ .pipe(
+ Effect.timeout(REQUEST_TIMEOUT),
+ Effect.map(
+ (response) => response.status >= 200 && response.status < 300,
+ ),
+ Effect.orElseSucceed(() => true),
+ );
+
+ const request = <T>(
+ method: HttpMethod,
+ path: string,
+ schema: Schema.Decoder<T>,
+ options: RequestOptions = {},
+ ): Effect.Effect<T, ApiFailure> => {
+ const credentials = options.credentials
+ ? Option.some(options.credentials)
+ : session.credentials;
+ if (Option.isNone(credentials)) {
+ return Option.isSome(session.configProblem)
+ ? Effect.fail(session.configProblem.value)
+ : Effect.fail(new NotSignedIn({ apiUrl: session.apiUrl }));
+ }
+ const { token, source } = credentials.value;
+ const endpoint = `${method} ${path}`;
+ const decode = Schema.decodeUnknownEffect(schema);
+
+ let httpRequest = HttpClientRequest.make(method)(
+ `${session.apiUrl}${path}`,
+ ).pipe(
+ HttpClientRequest.setUrlParams(toUrlParams(options.query)),
+ HttpClientRequest.bearerToken(Redacted.value(token)),
+ HttpClientRequest.acceptJson,
+ );
+ if (options.body !== undefined) {
+ httpRequest = HttpClientRequest.bodyJsonUnsafe(
+ httpRequest,
+ options.body,
+ );
+ }
+
+ const attempt = Effect.gen(function* () {
+ const response = yield* client.execute(httpRequest).pipe(
+ Effect.timeout(REQUEST_TIMEOUT),
+ Effect.mapError(
+ (error) =>
+ new ServerUnreachable({
+ apiUrl: session.apiUrl,
+ reason:
+ error._tag === "TimeoutError"
+ ? "timed out after 15s"
+ : describeTransportError(error),
+ }),
+ ),
+ );
+ if (response.status >= 200 && response.status < 300) {
+ const json = yield* response.json.pipe(
+ Effect.mapError(
+ () =>
+ new UnexpectedResponse({
+ endpoint,
+ detail: "the body is not JSON",
+ }),
+ ),
+ );
+ return yield* decode(json).pipe(
+ Effect.mapError(
+ (error) =>
+ new UnexpectedResponse({
+ endpoint,
+ detail: error.message.split("\n")[0] ?? "schema mismatch",
+ }),
+ ),
+ );
+ }
+ const text = yield* response.text.pipe(Effect.orElseSucceed(() => ""));
+ const failure = toApiFailure({
+ status: response.status,
+ body: parseErrorBody(text, response.status),
+ retryAfterSeconds: parseRetryAfter(
+ response.headers["retry-after"],
+ Date.now(),
+ ),
+ tokenSource: source,
+ apiUrl: session.apiUrl,
+ });
+ if (failure._tag === "SessionExpired" && path !== "/api/user/me") {
+ if (yield* sessionStillValid(token)) {
+ return yield* new PermissionDenied({
+ message: parseErrorBody(text, response.status).message,
+ missingPermissions: [],
+ });
+ }
+ }
+ if (failure._tag === "SessionExpired") yield* forgetStoredToken;
+ return yield* Effect.fail(failure);
+ });
+
+ return attempt.pipe(
+ Effect.retry({ schedule: rateLimitRetry, while: isRetryable }),
+ );
+ };
+
+ return { request };
+ }),
+);
+
+export const KaneoApiLive = KaneoApiLayer.pipe(
+ Layer.provide(FetchHttpClient.layer),
+);
diff --git a/packages/cli/src/api/labels.ts b/packages/cli/src/api/labels.ts
new file mode 100644
index 000000000..1fd6e39a1
--- /dev/null
+++ b/packages/cli/src/api/labels.ts
@@ -0,0 +1,91 @@
+import { Effect, Schema } from "effect";
+import { KaneoApi } from "./kaneo-api.js";
+
+const NullableString = Schema.NullOr(Schema.String);
+
+export const Label = Schema.Struct({
+ id: Schema.String,
+ name: Schema.String,
+ color: Schema.String,
+ taskId: NullableString,
+ workspaceId: NullableString,
+ deletionStartedAt: Schema.optionalKey(NullableString),
+});
+export type Label = typeof Label.Type;
+
+export const LabelList = Schema.Array(Label);
+
+export const LabelDeletion = Schema.Struct({
+ id: Schema.String,
+ name: Schema.String,
+ pendingDeletion: Schema.optionalKey(Schema.Boolean),
+});
+export type LabelDeletion = typeof LabelDeletion.Type;
+
+function labelPath(id: string, suffix = ""): string {
+ return `/api/label/${encodeURIComponent(id)}${suffix}`;
+}
+
+export const listWorkspaceLabels = Effect.fnUntraced(function* (
+ workspaceId: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "GET",
+ `/api/label/workspace/${encodeURIComponent(workspaceId)}`,
+ LabelList,
+ );
+});
+
+export const listTaskLabels = Effect.fnUntraced(function* (taskId: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "GET",
+ `/api/label/task/${encodeURIComponent(taskId)}`,
+ LabelList,
+ );
+});
+
+export const createLabel = Effect.fnUntraced(function* (body: {
+ readonly workspaceId: string;
+ readonly name: string;
+ readonly color: string;
+}) {
+ const api = yield* KaneoApi;
+ return yield* api.request("POST", "/api/label", Label, { body });
+});
+
+export const updateLabel = Effect.fnUntraced(function* (
+ id: string,
+ body: { readonly name: string; readonly color: string },
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("PUT", labelPath(id), Label, { body });
+});
+
+export const deleteLabelStep = Effect.fnUntraced(function* (id: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request("DELETE", labelPath(id), LabelDeletion);
+});
+
+export const attachLabelToTask = Effect.fnUntraced(function* (
+ workspaceLabelId: string,
+ taskId: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "PUT",
+ labelPath(workspaceLabelId, "/task"),
+ Label,
+ {
+ body: { taskId },
+ },
+ );
+});
+
+export const detachLabelFromTask = Effect.fnUntraced(function* (
+ taskLabelId: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("DELETE", labelPath(taskLabelId, "/task"), Label);
+});
diff --git a/packages/cli/src/api/members.ts b/packages/cli/src/api/members.ts
new file mode 100644
index 000000000..8b618096c
--- /dev/null
+++ b/packages/cli/src/api/members.ts
@@ -0,0 +1,108 @@
+import { Effect, Schema } from "effect";
+import { KaneoApi } from "./kaneo-api.js";
+
+const PAGE_SIZE = 100;
+
+export const OrganizationMember = Schema.Struct({
+ id: Schema.String,
+ userId: Schema.String,
+ role: Schema.String,
+ createdAt: Schema.Unknown,
+ user: Schema.Struct({
+ name: Schema.String,
+ email: Schema.String,
+ }),
+});
+export type OrganizationMember = typeof OrganizationMember.Type;
+
+const MemberPage = Schema.Struct({
+ members: Schema.Array(OrganizationMember),
+ total: Schema.Number,
+});
+
+const ChangedMember = Schema.Struct({ id: Schema.String, role: Schema.String });
+
+const RemovedMember = Schema.Struct({ member: ChangedMember });
+
+const PermissionCheck = Schema.Struct({ success: Schema.Boolean });
+
+const RoleList = Schema.Array(Schema.Struct({ role: Schema.String }));
+
+export const listOrganizationMembers = Effect.fnUntraced(function* (
+ workspaceId: string,
+) {
+ const api = yield* KaneoApi;
+ const members: OrganizationMember[] = [];
+ for (;;) {
+ const page = yield* api.request(
+ "GET",
+ "/api/auth/organization/list-members",
+ MemberPage,
+ {
+ query: {
+ organizationId: workspaceId,
+ limit: PAGE_SIZE,
+ offset: members.length,
+ },
+ },
+ );
+ members.push(...page.members);
+ if (page.members.length === 0 || members.length >= page.total) {
+ return members;
+ }
+ }
+});
+
+export const listCustomRoles = Effect.fnUntraced(function* (
+ workspaceId: string,
+) {
+ const api = yield* KaneoApi;
+ const roles = yield* api.request(
+ "GET",
+ "/api/auth/organization/list-roles",
+ RoleList,
+ { query: { organizationId: workspaceId } },
+ );
+ return roles.map((entry) => entry.role);
+});
+
+export const hasWorkspacePermission = Effect.fnUntraced(function* (
+ workspaceId: string,
+ permissions: Readonly<Record<string, ReadonlyArray<string>>>,
+) {
+ const api = yield* KaneoApi;
+ const result = yield* api.request(
+ "POST",
+ "/api/auth/organization/has-permission",
+ PermissionCheck,
+ { body: { organizationId: workspaceId, permissions } },
+ );
+ return result.success;
+});
+
+export const removeOrganizationMember = Effect.fnUntraced(function* (
+ workspaceId: string,
+ memberId: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "POST",
+ "/api/auth/organization/remove-member",
+ RemovedMember,
+ { body: { organizationId: workspaceId, memberIdOrEmail: memberId } },
+ );
+});
+
+export const updateOrganizationMemberRole = Effect.fnUntraced(function* (
+ workspaceId: string,
+ memberId: string,
+ role: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "POST",
+ "/api/auth/organization/update-member-role",
+ ChangedMember,
+ { body: { organizationId: workspaceId, memberId, role } },
+ );
+});
diff --git a/packages/cli/src/api/notifications.ts b/packages/cli/src/api/notifications.ts
new file mode 100644
index 000000000..94aba786c
--- /dev/null
+++ b/packages/cli/src/api/notifications.ts
@@ -0,0 +1,71 @@
+import { Effect, Schema } from "effect";
+import { KaneoApi } from "./kaneo-api.js";
+
+const NullableString = Schema.NullOr(Schema.String);
+
+export const NOTIFICATION_PAGE_CAP = 50;
+
+export const RawNotification = Schema.Struct({
+ id: Schema.String,
+ title: NullableString,
+ content: NullableString,
+ type: Schema.String,
+ eventData: Schema.optionalKey(Schema.Unknown),
+ isRead: Schema.NullOr(Schema.Boolean),
+ resourceId: NullableString,
+ resourceType: NullableString,
+ createdAt: Schema.String,
+});
+export type RawNotification = typeof RawNotification.Type;
+
+const NotificationList = Schema.Array(RawNotification);
+
+const BulkResult = Schema.Struct({ success: Schema.Boolean });
+
+const ReadNotification = Schema.Struct({ id: Schema.String });
+
+export const NotificationTask = Schema.Struct({
+ id: Schema.String,
+ projectId: Schema.String,
+ number: Schema.NullOr(Schema.Number),
+ title: Schema.String,
+});
+export type NotificationTask = typeof NotificationTask.Type;
+
+export const listNotifications = Effect.fnUntraced(function* (
+ workspaceId: string | undefined,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("GET", "/api/notification", NotificationList, {
+ query: { workspaceId },
+ });
+});
+
+export const markNotificationRead = Effect.fnUntraced(function* (id: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "PATCH",
+ `/api/notification/${encodeURIComponent(id)}/read`,
+ ReadNotification,
+ );
+});
+
+export const markAllNotificationsRead = Effect.fnUntraced(function* (
+ workspaceId: string | undefined,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("PATCH", "/api/notification/read-all", BulkResult, {
+ query: { workspaceId },
+ });
+});
+
+export const getNotificationTask = Effect.fnUntraced(function* (
+ taskId: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "GET",
+ `/api/task/${encodeURIComponent(taskId)}`,
+ NotificationTask,
+ );
+});
diff --git a/packages/cli/src/api/project-summaries.ts b/packages/cli/src/api/project-summaries.ts
new file mode 100644
index 000000000..f862f2f51
--- /dev/null
+++ b/packages/cli/src/api/project-summaries.ts
@@ -0,0 +1,34 @@
+import { Effect, Schema } from "effect";
+import { KaneoApi } from "./kaneo-api.js";
+
+const NullableString = Schema.NullOr(Schema.String);
+
+export const ProjectSummary = Schema.Struct({
+ id: Schema.String,
+ workspaceId: Schema.String,
+ slug: Schema.String,
+ name: Schema.String,
+ description: NullableString,
+ archivedAt: NullableString,
+ statistics: Schema.Struct({
+ totalTasks: Schema.Number,
+ completionPercentage: Schema.Number,
+ dueDate: NullableString,
+ }),
+});
+export type ProjectSummary = typeof ProjectSummary.Type;
+
+export const ProjectSummaryList = Schema.Array(ProjectSummary);
+
+export const listProjectSummaries = Effect.fnUntraced(function* (
+ workspaceId: string,
+ options: { readonly includeArchived: boolean },
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("GET", "/api/project", ProjectSummaryList, {
+ query: {
+ workspaceId,
+ includeArchived: options.includeArchived ? "true" : undefined,
+ },
+ });
+});
diff --git a/packages/cli/src/api/project-writes.ts b/packages/cli/src/api/project-writes.ts
new file mode 100644
index 000000000..41b5406c2
--- /dev/null
+++ b/packages/cli/src/api/project-writes.ts
@@ -0,0 +1,111 @@
+import { Effect, Schema } from "effect";
+import { KaneoApi } from "./kaneo-api.js";
+
+const NullableString = Schema.NullOr(Schema.String);
+
+export const ProjectRecord = Schema.Struct({
+ id: Schema.String,
+ workspaceId: Schema.String,
+ slug: Schema.String,
+ name: Schema.String,
+ icon: NullableString,
+ description: NullableString,
+ isPublic: Schema.NullOr(Schema.Boolean),
+ archivedAt: NullableString,
+});
+export type ProjectRecord = typeof ProjectRecord.Type;
+
+export const ProjectStatistics = Schema.Struct({
+ totalTasks: Schema.Number,
+ completionPercentage: Schema.Number,
+ dueDate: NullableString,
+});
+export type ProjectStatistics = typeof ProjectStatistics.Type;
+
+export const ProjectRecordWithStatistics = Schema.Struct({
+ ...ProjectRecord.fields,
+ statistics: ProjectStatistics,
+});
+export type ProjectRecordWithStatistics =
+ typeof ProjectRecordWithStatistics.Type;
+
+const ProjectRecordList = Schema.Array(ProjectRecordWithStatistics);
+
+export const MovedProject = Schema.Struct({
+ ...ProjectRecord.fields,
+ unassignedTaskCount: Schema.Number,
+});
+export type MovedProject = typeof MovedProject.Type;
+
+export type ProjectUpdateBody = {
+ readonly name: string;
+ readonly icon: string;
+ readonly slug: string;
+ readonly description: string;
+ readonly isPublic: boolean;
+};
+
+function projectPath(id: string, suffix = ""): string {
+ return `/api/project/${encodeURIComponent(id)}${suffix}`;
+}
+
+export const listProjectRecords = Effect.fnUntraced(function* (
+ workspaceId: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("GET", "/api/project", ProjectRecordList, {
+ query: { workspaceId, includeArchived: "true" },
+ });
+});
+
+export const getProjectRecord = Effect.fnUntraced(function* (id: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request("GET", projectPath(id), ProjectRecord);
+});
+
+export const createProject = Effect.fnUntraced(function* (body: {
+ readonly workspaceId: string;
+ readonly name: string;
+ readonly slug: string;
+ readonly icon: string;
+}) {
+ const api = yield* KaneoApi;
+ return yield* api.request("POST", "/api/project", ProjectRecord, { body });
+});
+
+export const updateProject = Effect.fnUntraced(function* (
+ id: string,
+ body: ProjectUpdateBody,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("PUT", projectPath(id), ProjectRecord, { body });
+});
+
+export const archiveProject = Effect.fnUntraced(function* (id: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request("PUT", projectPath(id, "/archive"), ProjectRecord);
+});
+
+export const unarchiveProject = Effect.fnUntraced(function* (id: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "PUT",
+ projectPath(id, "/unarchive"),
+ ProjectRecord,
+ );
+});
+
+export const deleteProject = Effect.fnUntraced(function* (id: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request("DELETE", projectPath(id), ProjectRecord);
+});
+
+export const moveProject = Effect.fnUntraced(function* (
+ id: string,
+ workspaceId: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("PUT", projectPath(id, "/move"), MovedProject, {
+ body: { workspaceId },
+ });
+});
diff --git a/packages/cli/src/api/schemas.ts b/packages/cli/src/api/schemas.ts
new file mode 100644
index 000000000..9623c55ac
--- /dev/null
+++ b/packages/cli/src/api/schemas.ts
@@ -0,0 +1,162 @@
+import { Schema } from "effect";
+
+const NullableString = Schema.NullOr(Schema.String);
+
+export const CurrentUser = Schema.Struct({
+ id: Schema.String,
+ name: Schema.String,
+ email: Schema.String,
+ image: NullableString,
+ role: NullableString,
+});
+export type CurrentUser = typeof CurrentUser.Type;
+
+export const Workspace = Schema.Struct({
+ id: Schema.String,
+ name: Schema.String,
+ slug: Schema.String,
+ logo: NullableString,
+ description: NullableString,
+ createdAt: Schema.String,
+ role: NullableString,
+});
+export type Workspace = typeof Workspace.Type;
+
+export const WorkspaceList = Schema.Array(Workspace);
+
+export const OrganizationList = Schema.Array(
+ Schema.Struct({
+ id: Schema.String,
+ name: Schema.String,
+ slug: Schema.String,
+ logo: Schema.optionalKey(NullableString),
+ description: Schema.optionalKey(NullableString),
+ metadata: Schema.optionalKey(Schema.NullOr(Schema.Unknown)),
+ createdAt: Schema.Unknown,
+ }),
+);
+export type OrganizationList = typeof OrganizationList.Type;
+
+export const Project = Schema.Struct({
+ id: Schema.String,
+ workspaceId: Schema.String,
+ slug: Schema.String,
+ name: Schema.String,
+ icon: NullableString,
+ description: NullableString,
+ archivedAt: NullableString,
+ position: Schema.Number,
+ lastTaskNumber: Schema.Number,
+});
+export type Project = typeof Project.Type;
+
+export const ProjectList = Schema.Array(Project);
+
+export const BoardLabel = Schema.Struct({
+ id: Schema.String,
+ name: Schema.String,
+ color: Schema.String,
+});
+export type BoardLabel = typeof BoardLabel.Type;
+
+export const BoardTask = Schema.Struct({
+ id: Schema.String,
+ title: Schema.String,
+ number: Schema.NullOr(Schema.Number),
+ status: Schema.String,
+ priority: Schema.String,
+ startDate: NullableString,
+ dueDate: NullableString,
+ createdAt: Schema.String,
+ assigneeId: NullableString,
+ assigneeName: NullableString,
+ projectId: Schema.String,
+ position: Schema.optionalKey(Schema.NullOr(Schema.Number)),
+ labels: Schema.optionalKey(Schema.Array(BoardLabel)),
+});
+export type BoardTask = typeof BoardTask.Type;
+
+export const BoardColumn = Schema.Struct({
+ id: Schema.String,
+ slug: Schema.String,
+ name: Schema.String,
+ isFinal: Schema.Boolean,
+ tasks: Schema.Array(BoardTask),
+});
+export type BoardColumn = typeof BoardColumn.Type;
+
+export const BoardPage = Schema.Struct({
+ data: Schema.Struct({
+ id: Schema.String,
+ name: Schema.String,
+ slug: Schema.String,
+ workspaceId: Schema.String,
+ columns: Schema.Array(BoardColumn),
+ }),
+ pagination: Schema.Struct({
+ total: Schema.Number,
+ page: Schema.Number,
+ totalPages: Schema.Number,
+ relatedTotalPages: Schema.optionalKey(Schema.Number),
+ }),
+});
+export type BoardPage = typeof BoardPage.Type;
+
+export const AssignedTask = Schema.Struct({
+ id: Schema.String,
+ projectId: Schema.String,
+ number: Schema.NullOr(Schema.Number),
+ title: Schema.String,
+ status: Schema.String,
+ statusName: NullableString,
+ priority: Schema.String,
+ dueDate: NullableString,
+ projectName: Schema.String,
+ projectSlug: Schema.String,
+});
+export type AssignedTask = typeof AssignedTask.Type;
+
+export const AssignedTasks = Schema.Struct({
+ tasks: Schema.Array(AssignedTask),
+ total: Schema.Number,
+});
+
+export const TaskDetail = Schema.Struct({
+ id: Schema.String,
+ projectId: Schema.String,
+ workspaceId: Schema.optionalKey(Schema.String),
+ number: Schema.NullOr(Schema.Number),
+ title: Schema.String,
+ description: NullableString,
+ status: Schema.String,
+ priority: Schema.String,
+ startDate: NullableString,
+ dueDate: NullableString,
+ createdAt: Schema.String,
+ assigneeId: NullableString,
+ assigneeName: NullableString,
+});
+export type TaskDetail = typeof TaskDetail.Type;
+
+export const Column = Schema.Struct({
+ id: Schema.String,
+ projectId: Schema.String,
+ name: Schema.String,
+ slug: Schema.String,
+ position: Schema.Number,
+ color: NullableString,
+ isFinal: Schema.Boolean,
+});
+export type Column = typeof Column.Type;
+
+export const ColumnList = Schema.Array(Column);
+
+export const WorkspaceMember = Schema.Struct({
+ id: Schema.String,
+ name: Schema.String,
+ email: Schema.String,
+ role: Schema.String,
+});
+export type WorkspaceMember = typeof WorkspaceMember.Type;
+
+export const WorkspaceMemberList = Schema.Array(WorkspaceMember);
diff --git a/packages/cli/src/api/search.ts b/packages/cli/src/api/search.ts
new file mode 100644
index 000000000..a84730732
--- /dev/null
+++ b/packages/cli/src/api/search.ts
@@ -0,0 +1,58 @@
+import { Effect, Schema } from "effect";
+import { KaneoApi } from "./kaneo-api.js";
+
+const OptionalString = Schema.optionalKey(Schema.String);
+
+export const SearchHit = Schema.Struct({
+ id: Schema.String,
+ type: Schema.String,
+ title: Schema.String,
+ description: OptionalString,
+ content: OptionalString,
+ projectId: OptionalString,
+ projectName: OptionalString,
+ projectSlug: OptionalString,
+ workspaceId: OptionalString,
+ userName: OptionalString,
+ createdAt: Schema.String,
+ relevanceScore: Schema.Number,
+ taskNumber: Schema.optionalKey(Schema.Number),
+ priority: OptionalString,
+ status: OptionalString,
+});
+export type SearchHit = typeof SearchHit.Type;
+
+export const SearchResponse = Schema.Struct({
+ results: Schema.Array(SearchHit),
+ totalCount: Schema.Number,
+});
+export type SearchResponse = typeof SearchResponse.Type;
+
+export const SEARCH_TYPES = [
+ "all",
+ "tasks",
+ "projects",
+ "workspaces",
+ "comments",
+ "activities",
+] as const;
+export type SearchType = (typeof SEARCH_TYPES)[number];
+
+export const searchWorkspace = Effect.fnUntraced(function* (params: {
+ readonly query: string;
+ readonly workspaceId: string;
+ readonly type: SearchType;
+ readonly projectId: string | undefined;
+ readonly limit: number;
+}) {
+ const api = yield* KaneoApi;
+ return yield* api.request("GET", "/api/search", SearchResponse, {
+ query: {
+ q: params.query,
+ type: params.type,
+ workspaceId: params.workspaceId,
+ projectId: params.projectId,
+ limit: params.limit,
+ },
+ });
+});
diff --git a/packages/cli/src/api/task-actions.ts b/packages/cli/src/api/task-actions.ts
new file mode 100644
index 000000000..3797c5752
--- /dev/null
+++ b/packages/cli/src/api/task-actions.ts
@@ -0,0 +1,93 @@
+import { Effect, Schema } from "effect";
+import { KaneoApi } from "./kaneo-api.js";
+
+const NullableString = Schema.NullOr(Schema.String);
+
+export const UpdatedTask = Schema.Struct({
+ id: Schema.String,
+ projectId: Schema.String,
+ number: Schema.NullOr(Schema.Number),
+ title: Schema.String,
+ status: Schema.String,
+ userId: NullableString,
+});
+export type UpdatedTask = typeof UpdatedTask.Type;
+
+export const MovedTask = Schema.Struct({
+ task: UpdatedTask,
+ sourceProjectId: Schema.String,
+ destinationProjectId: Schema.String,
+});
+export type MovedTask = typeof MovedTask.Type;
+
+export const CreatedComment = Schema.Struct({
+ id: Schema.String,
+ taskId: Schema.String,
+ content: NullableString,
+ createdAt: Schema.String,
+});
+export type CreatedComment = typeof CreatedComment.Type;
+
+export const COMMENT_MAX_LENGTH = 10_000;
+
+export const updateTaskStatus = Effect.fnUntraced(function* (
+ taskId: string,
+ status: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "PUT",
+ `/api/task/status/${encodeURIComponent(taskId)}`,
+ UpdatedTask,
+ { body: { status } },
+ );
+});
+
+export const moveTask = Effect.fnUntraced(function* (
+ taskId: string,
+ destination: {
+ readonly projectId: string;
+ readonly status: string | undefined;
+ },
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "PUT",
+ `/api/task/move/${encodeURIComponent(taskId)}`,
+ MovedTask,
+ {
+ body: {
+ destinationProjectId: destination.projectId,
+ ...(destination.status === undefined
+ ? {}
+ : { destinationStatus: destination.status }),
+ },
+ },
+ );
+});
+
+export const updateTaskAssignee = Effect.fnUntraced(function* (
+ taskId: string,
+ userId: string | null,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "PUT",
+ `/api/task/assignee/${encodeURIComponent(taskId)}`,
+ UpdatedTask,
+ { body: { userId } },
+ );
+});
+
+export const createComment = Effect.fnUntraced(function* (
+ taskId: string,
+ content: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "POST",
+ `/api/comment/${encodeURIComponent(taskId)}`,
+ CreatedComment,
+ { body: { content } },
+ );
+});
diff --git a/packages/cli/src/api/task-duplicate.ts b/packages/cli/src/api/task-duplicate.ts
new file mode 100644
index 000000000..51e1b3a7e
--- /dev/null
+++ b/packages/cli/src/api/task-duplicate.ts
@@ -0,0 +1,24 @@
+import { Effect, Schema } from "effect";
+import { KaneoApi } from "./kaneo-api.js";
+
+export const DuplicatedTask = Schema.Struct({
+ id: Schema.String,
+ projectId: Schema.String,
+ number: Schema.NullOr(Schema.Number),
+ title: Schema.String,
+ status: Schema.String,
+});
+export type DuplicatedTask = typeof DuplicatedTask.Type;
+
+export const duplicateTask = Effect.fnUntraced(function* (
+ taskId: string,
+ title: string | undefined,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "POST",
+ `/api/task/duplicate/${encodeURIComponent(taskId)}`,
+ DuplicatedTask,
+ { body: title === undefined ? {} : { title } },
+ );
+});
diff --git a/packages/cli/src/api/task-mutations.ts b/packages/cli/src/api/task-mutations.ts
new file mode 100644
index 000000000..4affff16e
--- /dev/null
+++ b/packages/cli/src/api/task-mutations.ts
@@ -0,0 +1,135 @@
+import { Effect, Schema } from "effect";
+import { KaneoApi } from "./kaneo-api.js";
+
+const NullableString = Schema.NullOr(Schema.String);
+
+export const CreatedTask = Schema.Struct({
+ id: Schema.String,
+ projectId: Schema.String,
+ number: Schema.NullOr(Schema.Number),
+ title: Schema.String,
+ description: NullableString,
+ status: Schema.String,
+ priority: Schema.String,
+ startDate: NullableString,
+ dueDate: NullableString,
+ createdAt: Schema.String,
+ userId: NullableString,
+});
+export type CreatedTask = typeof CreatedTask.Type;
+
+const UpdatedTask = Schema.Struct({ id: Schema.String });
+
+const EditableTask = Schema.Struct({
+ id: Schema.String,
+ projectId: Schema.String,
+ title: Schema.String,
+ status: Schema.String,
+ priority: Schema.String,
+ position: Schema.NullOr(Schema.Number),
+ userId: NullableString,
+ dueDate: NullableString,
+});
+
+export type Priority = "no-priority" | "low" | "medium" | "high" | "urgent";
+
+export type CreateTaskBody = {
+ readonly title: string;
+ readonly description: string;
+ readonly priority: Priority;
+ readonly status: string;
+ readonly userId?: string;
+ readonly dueDate?: string;
+ readonly startDate?: string;
+};
+
+function taskPath(route: string, id: string): string {
+ return `/api/task/${route}/${encodeURIComponent(id)}`;
+}
+
+export const createTask = Effect.fnUntraced(function* (
+ projectId: string,
+ body: CreateTaskBody,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "POST",
+ `/api/task/${encodeURIComponent(projectId)}`,
+ CreatedTask,
+ {
+ body,
+ },
+ );
+});
+
+export const updateTaskTitle = Effect.fnUntraced(function* (
+ id: string,
+ title: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("PUT", taskPath("title", id), UpdatedTask, {
+ body: { title },
+ });
+});
+
+export const updateTaskDescription = Effect.fnUntraced(function* (
+ id: string,
+ description: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("PUT", taskPath("description", id), UpdatedTask, {
+ body: { description },
+ });
+});
+
+export const updateTaskPriority = Effect.fnUntraced(function* (
+ id: string,
+ priority: Priority,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("PUT", taskPath("priority", id), UpdatedTask, {
+ body: { priority },
+ });
+});
+
+export const updateTaskDueDate = Effect.fnUntraced(function* (
+ id: string,
+ dueDate: string | null,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("PUT", taskPath("due-date", id), UpdatedTask, {
+ body: dueDate === null ? {} : { dueDate },
+ });
+});
+
+export const updateTaskStartDate = Effect.fnUntraced(function* (
+ id: string,
+ startDate: string | null,
+) {
+ const api = yield* KaneoApi;
+ const path = `/api/task/${encodeURIComponent(id)}`;
+ const current = yield* api.request("GET", path, EditableTask, {
+ query: { view: "detail" },
+ });
+ return yield* api.request("PUT", path, UpdatedTask, {
+ body: {
+ title: current.title,
+ status: current.status,
+ priority: current.priority || "no-priority",
+ projectId: current.projectId,
+ position: current.position ?? 0,
+ ...(current.userId ? { userId: current.userId } : {}),
+ ...(current.dueDate ? { dueDate: current.dueDate } : {}),
+ ...(startDate ? { startDate } : {}),
+ },
+ });
+});
+
+export const deleteTask = Effect.fnUntraced(function* (id: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "DELETE",
+ `/api/task/${encodeURIComponent(id)}`,
+ UpdatedTask,
+ );
+});
diff --git a/packages/cli/src/api/task-relations.ts b/packages/cli/src/api/task-relations.ts
new file mode 100644
index 000000000..cb641436f
--- /dev/null
+++ b/packages/cli/src/api/task-relations.ts
@@ -0,0 +1,68 @@
+import { Effect, Schema } from "effect";
+import { KaneoApi } from "./kaneo-api.js";
+
+export const API_RELATION_TYPES = ["subtask", "blocks", "related"] as const;
+export type ApiRelationType = (typeof API_RELATION_TYPES)[number];
+
+export const RelatedTask = Schema.Struct({
+ id: Schema.String,
+ title: Schema.String,
+ status: Schema.String,
+ isCompleted: Schema.Boolean,
+ number: Schema.NullOr(Schema.Number),
+ projectId: Schema.String,
+});
+export type RelatedTask = typeof RelatedTask.Type;
+
+export const TaskRelation = Schema.Struct({
+ id: Schema.String,
+ sourceTaskId: Schema.String,
+ targetTaskId: Schema.String,
+ relationType: Schema.String,
+});
+export type TaskRelation = typeof TaskRelation.Type;
+
+export const TaskRelationWithTasks = Schema.Struct({
+ id: Schema.String,
+ sourceTaskId: Schema.String,
+ targetTaskId: Schema.String,
+ relationType: Schema.String,
+ sourceTask: Schema.NullOr(RelatedTask),
+ targetTask: Schema.NullOr(RelatedTask),
+});
+export type TaskRelationWithTasks = typeof TaskRelationWithTasks.Type;
+
+export const TaskRelationList = Schema.Array(TaskRelationWithTasks);
+
+export type NewTaskRelation = {
+ readonly sourceTaskId: string;
+ readonly targetTaskId: string;
+ readonly relationType: ApiRelationType;
+};
+
+export const listTaskRelations = Effect.fnUntraced(function* (taskId: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "GET",
+ `/api/task-relation/${encodeURIComponent(taskId)}`,
+ TaskRelationList,
+ );
+});
+
+export const createTaskRelation = Effect.fnUntraced(function* (
+ relation: NewTaskRelation,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("POST", "/api/task-relation", TaskRelation, {
+ body: relation,
+ });
+});
+
+export const deleteTaskRelation = Effect.fnUntraced(function* (id: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "DELETE",
+ `/api/task-relation/${encodeURIComponent(id)}`,
+ TaskRelation,
+ );
+});
diff --git a/packages/cli/src/api/time-entries.ts b/packages/cli/src/api/time-entries.ts
new file mode 100644
index 000000000..5951701a4
--- /dev/null
+++ b/packages/cli/src/api/time-entries.ts
@@ -0,0 +1,80 @@
+import { Effect, Schema } from "effect";
+import { NotFound } from "../errors/errors.js";
+import { KaneoApi } from "./kaneo-api.js";
+
+const NullableString = Schema.NullOr(Schema.String);
+
+export const TimeEntry = Schema.Struct({
+ id: Schema.String,
+ taskId: Schema.String,
+ userId: NullableString,
+ description: NullableString,
+ startTime: Schema.String,
+ endTime: NullableString,
+ duration: Schema.NullOr(Schema.Number),
+});
+export type TimeEntry = typeof TimeEntry.Type;
+
+export const TimeEntryWithUser = Schema.Struct({
+ ...TimeEntry.fields,
+ userName: NullableString,
+});
+export type TimeEntryWithUser = typeof TimeEntryWithUser.Type;
+
+const TimeEntryList = Schema.Array(TimeEntryWithUser);
+
+export type CreateTimeEntryBody = {
+ readonly taskId: string;
+ readonly startTime: string;
+ readonly endTime?: string;
+ readonly description?: string;
+};
+
+export type UpdateTimeEntryBody = {
+ readonly startTime: string;
+ readonly endTime?: string;
+ readonly description?: string;
+};
+
+function entryPath(id: string): string {
+ return `/api/time-entry/${encodeURIComponent(id)}`;
+}
+
+export const listTimeEntries = Effect.fnUntraced(function* (taskId: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "GET",
+ `/api/time-entry/task/${encodeURIComponent(taskId)}`,
+ TimeEntryList,
+ );
+});
+
+export const getTimeEntry = Effect.fnUntraced(function* (id: string) {
+ const api = yield* KaneoApi;
+ const notFound = () =>
+ new NotFound({ message: `Time entry ${id} not found.` });
+ return yield* api.request("GET", entryPath(id), TimeEntry).pipe(
+ Effect.catchTags({
+ NotFound: () => Effect.fail(notFound()),
+ InvalidRequest: (error) =>
+ /could not be determined/i.test(error.message)
+ ? Effect.fail(notFound())
+ : Effect.fail(error),
+ }),
+ );
+});
+
+export const createTimeEntry = Effect.fnUntraced(function* (
+ body: CreateTimeEntryBody,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("POST", "/api/time-entry", TimeEntry, { body });
+});
+
+export const updateTimeEntry = Effect.fnUntraced(function* (
+ id: string,
+ body: UpdateTimeEntryBody,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("PUT", entryPath(id), TimeEntry, { body });
+});
diff --git a/packages/cli/src/api/to-api-failure.test.ts b/packages/cli/src/api/to-api-failure.test.ts
new file mode 100644
index 000000000..9eb33327d
--- /dev/null
+++ b/packages/cli/src/api/to-api-failure.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from "vite-plus/test";
+import { type FailedResponse, toApiFailure } from "./to-api-failure.js";
+
+function failed(
+ status: number,
+ overrides: Partial<FailedResponse> = {},
+): FailedResponse {
+ return {
+ status,
+ body: { message: "boom", code: null, missingPermissions: [] },
+ retryAfterSeconds: null,
+ tokenSource: "profile",
+ apiUrl: "https://cloud.kaneo.app",
+ ...overrides,
+ };
+}
+
+describe("toApiFailure", () => {
+ it("separates an expired login from a rejected key", () => {
+ expect(toApiFailure(failed(401))._tag).toBe("SessionExpired");
+ expect(toApiFailure(failed(401, { tokenSource: "env" }))).toMatchObject({
+ _tag: "CredentialsRejected",
+ source: "env",
+ });
+ });
+
+ it("recognizes session-only routes", () => {
+ expect(
+ toApiFailure(
+ failed(403, {
+ body: {
+ message: "A user session is required",
+ code: null,
+ missingPermissions: [],
+ },
+ }),
+ )._tag,
+ ).toBe("SessionRequired");
+ expect(
+ toApiFailure(
+ failed(403, {
+ body: {
+ message: "Nope",
+ code: "SESSION_REQUIRED",
+ missingPermissions: [],
+ },
+ }),
+ )._tag,
+ ).toBe("SessionRequired");
+ });
+
+ it("keeps missing permissions", () => {
+ expect(
+ toApiFailure(
+ failed(403, {
+ body: {
+ message: "Denied",
+ code: "MISSING_PERMISSION",
+ missingPermissions: ["task:delete"],
+ },
+ }),
+ ),
+ ).toMatchObject({
+ _tag: "PermissionDenied",
+ missingPermissions: ["task:delete"],
+ });
+ });
+
+ it("maps the remaining statuses", () => {
+ expect(toApiFailure(failed(404))._tag).toBe("NotFound");
+ expect(toApiFailure(failed(409))._tag).toBe("Conflict");
+ expect(toApiFailure(failed(400))._tag).toBe("InvalidRequest");
+ expect(toApiFailure(failed(429, { retryAfterSeconds: 12 }))).toMatchObject({
+ _tag: "RateLimited",
+ retryAfterSeconds: 12,
+ });
+ expect(toApiFailure(failed(503))._tag).toBe("ServerError");
+ });
+});
diff --git a/packages/cli/src/api/to-api-failure.ts b/packages/cli/src/api/to-api-failure.ts
new file mode 100644
index 000000000..aeca8bce8
--- /dev/null
+++ b/packages/cli/src/api/to-api-failure.ts
@@ -0,0 +1,50 @@
+import {
+ type ApiFailure,
+ Conflict,
+ CredentialsRejected,
+ InvalidRequest,
+ NotFound,
+ PermissionDenied,
+ RateLimited,
+ ServerError,
+ SessionExpired,
+ SessionRequired,
+} from "../errors/errors.js";
+import type { TokenSource } from "../services/session.js";
+import type { ErrorBody } from "./error-body.js";
+
+export type FailedResponse = {
+ readonly status: number;
+ readonly body: ErrorBody;
+ readonly retryAfterSeconds: number | null;
+ readonly tokenSource: TokenSource;
+ readonly apiUrl: string;
+};
+
+export function toApiFailure(response: FailedResponse): ApiFailure {
+ const { status, body } = response;
+ if (status === 401) {
+ return response.tokenSource === "profile"
+ ? new SessionExpired({ apiUrl: response.apiUrl })
+ : new CredentialsRejected({ source: response.tokenSource });
+ }
+ if (status === 403) {
+ if (
+ body.code === "SESSION_REQUIRED" ||
+ /user session is required/i.test(body.message)
+ ) {
+ return new SessionRequired({ message: body.message });
+ }
+ return new PermissionDenied({
+ message: body.message,
+ missingPermissions: body.missingPermissions,
+ });
+ }
+ if (status === 404) return new NotFound({ message: body.message });
+ if (status === 409) return new Conflict({ message: body.message });
+ if (status === 429) {
+ return new RateLimited({ retryAfterSeconds: response.retryAfterSeconds });
+ }
+ if (status >= 500) return new ServerError({ status, message: body.message });
+ return new InvalidRequest({ message: body.message });
+}
diff --git a/packages/cli/src/api/uploads.test.ts b/packages/cli/src/api/uploads.test.ts
new file mode 100644
index 000000000..7fa00831f
--- /dev/null
+++ b/packages/cli/src/api/uploads.test.ts
@@ -0,0 +1,118 @@
+import { Effect, Layer, Result } from "effect";
+import { HttpClient, HttpClientResponse } from "effect/http";
+import { describe, expect, it } from "vite-plus/test";
+import {
+ json,
+ memoryConfigStore,
+ testSession,
+} from "../testing/test-layers.js";
+import { KaneoApiLayer } from "./kaneo-api.js";
+import { uploadTaskFile } from "./uploads.js";
+
+type Sent = {
+ readonly method: string;
+ readonly url: string;
+ readonly authorization: string | undefined;
+ readonly contentType: string | undefined;
+ readonly body: unknown;
+};
+
+const file = {
+ name: "shot.png",
+ bytes: new Uint8Array([137, 80, 78, 71]),
+ contentType: "image/png",
+};
+
+function run(storageStatus = 200) {
+ const sent: Sent[] = [];
+ const client = Layer.succeed(
+ HttpClient.HttpClient,
+ HttpClient.make((request, url) =>
+ Effect.sync(() => {
+ const raw =
+ request.body._tag === "Uint8Array" ? request.body.body : undefined;
+ const isJson = request.headers["content-type"] === "application/json";
+ sent.push({
+ method: request.method,
+ url: url.toString(),
+ authorization: request.headers.authorization,
+ contentType: request.headers["content-type"],
+ body:
+ raw && isJson
+ ? JSON.parse(new TextDecoder().decode(raw))
+ : raw && [...raw],
+ });
+ const response = url.hostname.startsWith("bucket")
+ ? new Response(null, { status: storageStatus })
+ : url.pathname.endsWith("/finalize")
+ ? json({ id: "a1", url: "https://kaneo.test/api/asset/a1" })
+ : json({
+ key: "ws/p/t1/description/k.png",
+ uploadUrl: "https://bucket.test/k.png?X-Amz-Signature=s",
+ headers: { "Content-Type": "image/png" },
+ });
+ return HttpClientResponse.fromWeb(request, response);
+ }),
+ ),
+ );
+ const session = testSession();
+ const layer = Layer.merge(
+ KaneoApiLayer.pipe(
+ Layer.provide(Layer.mergeAll(client, session, memoryConfigStore().layer)),
+ ),
+ Layer.merge(client, session),
+ );
+ const result = Effect.runPromise(
+ Effect.result(
+ uploadTaskFile("t1", file, "description").pipe(Effect.provide(layer)),
+ ),
+ );
+ return { sent, result };
+}
+
+describe("uploadTaskFile", () => {
+ it("asks for an upload URL, sends the bytes to storage, then finalizes", async () => {
+ const { sent, result } = run();
+ expect(await result).toEqual(
+ Result.succeed({ id: "a1", url: "https://kaneo.test/api/asset/a1" }),
+ );
+ const details = {
+ filename: "shot.png",
+ contentType: "image/png",
+ size: 4,
+ surface: "description",
+ };
+ expect(sent).toEqual([
+ {
+ method: "PUT",
+ url: "https://kaneo.test/api/task/image-upload/t1",
+ authorization: "Bearer test-token",
+ contentType: "application/json",
+ body: details,
+ },
+ {
+ method: "PUT",
+ url: "https://bucket.test/k.png?X-Amz-Signature=s",
+ authorization: undefined,
+ contentType: "image/png",
+ body: [137, 80, 78, 71],
+ },
+ {
+ method: "POST",
+ url: "https://kaneo.test/api/task/image-upload/t1/finalize",
+ authorization: "Bearer test-token",
+ contentType: "application/json",
+ body: { key: "ws/p/t1/description/k.png", ...details },
+ },
+ ]);
+ });
+
+ it("fails without finalizing when storage rejects the bytes", async () => {
+ const { sent, result } = run(403);
+ const outcome = await result;
+ expect(Result.isFailure(outcome) && outcome.failure._tag).toBe(
+ "ServerError",
+ );
+ expect(sent).toHaveLength(2);
+ });
+});
diff --git a/packages/cli/src/api/uploads.ts b/packages/cli/src/api/uploads.ts
new file mode 100644
index 000000000..18ee15291
--- /dev/null
+++ b/packages/cli/src/api/uploads.ts
@@ -0,0 +1,92 @@
+import { Duration, Effect, Schema } from "effect";
+import { HttpClient, HttpClientRequest } from "effect/http";
+import { ServerError, ServerUnreachable } from "../errors/errors.js";
+import { Session } from "../services/session.js";
+import { KaneoApi } from "./kaneo-api.js";
+
+export const TaskUpload = Schema.Struct({
+ key: Schema.String,
+ uploadUrl: Schema.String,
+ headers: Schema.Record(Schema.String, Schema.String),
+});
+export type TaskUpload = typeof TaskUpload.Type;
+
+export const StoredAsset = Schema.Struct({
+ id: Schema.String,
+ url: Schema.String,
+});
+export type StoredAsset = typeof StoredAsset.Type;
+
+export type UploadSurface = "description" | "comment";
+
+export type UploadFile = {
+ readonly name: string;
+ readonly bytes: Uint8Array;
+ readonly contentType: string;
+};
+
+const STORAGE_TIMEOUT = Duration.minutes(2);
+
+function uploadPath(taskId: string, suffix = ""): string {
+ return `/api/task/image-upload/${encodeURIComponent(taskId)}${suffix}`;
+}
+
+function describe(file: UploadFile, surface: UploadSurface) {
+ return {
+ filename: file.name,
+ contentType: file.contentType,
+ size: file.bytes.byteLength,
+ surface,
+ };
+}
+
+const putToStorage = Effect.fnUntraced(function* (
+ upload: TaskUpload,
+ file: UploadFile,
+) {
+ const session = yield* Session;
+ const client = yield* HttpClient.HttpClient;
+ const target = new URL(upload.uploadUrl, `${session.apiUrl}/`);
+ const request = HttpClientRequest.put(target).pipe(
+ HttpClientRequest.bodyUint8Array(file.bytes, file.contentType),
+ HttpClientRequest.setHeaders(upload.headers),
+ );
+ const response = yield* client.execute(request).pipe(
+ Effect.timeout(STORAGE_TIMEOUT),
+ Effect.mapError(
+ (error) =>
+ new ServerUnreachable({
+ apiUrl: target.origin,
+ reason:
+ error._tag === "TimeoutError"
+ ? "the upload timed out"
+ : "the upload failed",
+ }),
+ ),
+ );
+ if (response.status < 200 || response.status >= 300) {
+ return yield* new ServerError({
+ status: response.status,
+ message: `file storage rejected ${file.name}`,
+ });
+ }
+});
+
+export const uploadTaskFile = Effect.fnUntraced(function* (
+ taskId: string,
+ file: UploadFile,
+ surface: UploadSurface,
+) {
+ const api = yield* KaneoApi;
+ const details = describe(file, surface);
+ const upload = yield* api.request("PUT", uploadPath(taskId), TaskUpload, {
+ body: details,
+ });
+ yield* putToStorage(upload, file);
+ return yield* api.request(
+ "POST",
+ uploadPath(taskId, "/finalize"),
+ StoredAsset,
+ { body: { key: upload.key, ...details } },
+ );
+});
diff --git a/packages/cli/src/api/workflow-rules.ts b/packages/cli/src/api/workflow-rules.ts
new file mode 100644
index 000000000..0a492993c
--- /dev/null
+++ b/packages/cli/src/api/workflow-rules.ts
@@ -0,0 +1,51 @@
+import { Effect, Schema } from "effect";
+import { KaneoApi } from "./kaneo-api.js";
+
+const NullableString = Schema.NullOr(Schema.String);
+
+export const WorkflowRule = Schema.Struct({
+ id: Schema.String,
+ integrationType: Schema.String,
+ eventType: Schema.String,
+ columnId: Schema.String,
+ columnName: NullableString,
+ columnSlug: NullableString,
+});
+export type WorkflowRule = typeof WorkflowRule.Type;
+
+const WorkflowRuleList = Schema.Array(WorkflowRule);
+
+const SavedRule = Schema.Struct({
+ id: Schema.String,
+ integrationType: Schema.String,
+ eventType: Schema.String,
+ columnId: Schema.String,
+});
+
+function rulePath(id: string): string {
+ return `/api/workflow-rule/${encodeURIComponent(id)}`;
+}
+
+export const listWorkflowRules = Effect.fnUntraced(function* (
+ projectId: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("GET", rulePath(projectId), WorkflowRuleList);
+});
+
+export const upsertWorkflowRule = Effect.fnUntraced(function* (
+ projectId: string,
+ body: {
+ readonly integrationType: string;
+ readonly eventType: string;
+ readonly columnId: string;
+ },
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("PUT", rulePath(projectId), SavedRule, { body });
+});
+
+export const deleteWorkflowRule = Effect.fnUntraced(function* (id: string) {
+ const api = yield* KaneoApi;
+ return yield* api.request("DELETE", rulePath(id), SavedRule);
+});
diff --git a/packages/cli/src/api/workspace-admin.ts b/packages/cli/src/api/workspace-admin.ts
new file mode 100644
index 000000000..8f687366e
--- /dev/null
+++ b/packages/cli/src/api/workspace-admin.ts
@@ -0,0 +1,96 @@
+import { Effect, Schema } from "effect";
+import { KaneoApi } from "./kaneo-api.js";
+
+const NullableString = Schema.NullOr(Schema.String);
+
+export const Organization = Schema.Struct({
+ id: Schema.String,
+ name: Schema.String,
+ slug: Schema.String,
+ description: Schema.optionalKey(NullableString),
+ metadata: Schema.optionalKey(Schema.NullOr(Schema.Unknown)),
+ createdAt: Schema.Unknown,
+});
+export type Organization = typeof Organization.Type;
+
+const OrganizationList = Schema.Array(Organization);
+
+const SlugCheck = Schema.Struct({ status: Schema.Boolean });
+
+const Anything = Schema.Unknown;
+
+export type WorkspaceChanges = {
+ readonly name?: string;
+ readonly slug?: string;
+ readonly description?: string;
+ readonly metadata?: Record<string, unknown>;
+};
+
+export const listOrganizations = Effect.fnUntraced(function* () {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "GET",
+ "/api/auth/organization/list",
+ OrganizationList,
+ );
+});
+
+export const isWorkspaceSlugFree = Effect.fnUntraced(function* (slug: string) {
+ const api = yield* KaneoApi;
+ return yield* api
+ .request("POST", "/api/auth/organization/check-slug", SlugCheck, {
+ body: { slug },
+ })
+ .pipe(
+ Effect.map((result) => result.status),
+ Effect.catchTag("InvalidRequest", (error) =>
+ /slug/i.test(error.message)
+ ? Effect.succeed(false)
+ : Effect.fail(error),
+ ),
+ );
+});
+
+export const createOrganization = Effect.fnUntraced(function* (body: {
+ readonly name: string;
+ readonly slug: string;
+}) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "POST",
+ "/api/auth/organization/create",
+ Organization,
+ { body: { ...body, keepCurrentActiveOrganization: true } },
+ );
+});
+
+export const updateOrganization = Effect.fnUntraced(function* (
+ organizationId: string,
+ data: WorkspaceChanges,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "POST",
+ "/api/auth/organization/update",
+ Organization,
+ { body: { organizationId, data } },
+ );
+});
+
+export const deleteOrganization = Effect.fnUntraced(function* (
+ organizationId: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("POST", "/api/auth/organization/delete", Anything, {
+ body: { organizationId },
+ });
+});
+
+export const leaveOrganization = Effect.fnUntraced(function* (
+ organizationId: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request("POST", "/api/auth/organization/leave", Anything, {
+ body: { organizationId },
+ });
+});
diff --git a/packages/cli/src/auth/wait-for-approval.test.ts b/packages/cli/src/auth/wait-for-approval.test.ts
new file mode 100644
index 000000000..88f3e9399
--- /dev/null
+++ b/packages/cli/src/auth/wait-for-approval.test.ts
@@ -0,0 +1,104 @@
+import type {
+ DeviceCodeResponse,
+ DeviceTokenPoll,
+} from "@kaneo/mcp/device-flow";
+import { type Duration, Effect, Fiber, Layer, Result } from "effect";
+import { TestClock } from "effect/testing";
+import { describe, expect, it } from "vite-plus/test";
+import { DeviceAuth } from "../services/device-auth.js";
+import {
+ formatUserCode,
+ waitForApproval,
+ webUrlFromVerificationUri,
+} from "./wait-for-approval.js";
+
+const code: DeviceCodeResponse = {
+ device_code: "device",
+ user_code: "ABCDEFGH",
+ verification_uri: "https://app.kaneo.test/device",
+ interval: 5,
+ expires_in: 60,
+};
+
+function scripted(results: ReadonlyArray<DeviceTokenPoll>) {
+ const polls: number[] = [];
+ let index = 0;
+ const layer = Layer.succeed(DeviceAuth, {
+ requestCode: () => Effect.succeed(code),
+ poll: () =>
+ Effect.gen(function* () {
+ polls.push(yield* Effect.clockWith((clock) => clock.currentTimeMillis));
+ const result = results[Math.min(index, results.length - 1)] ?? {
+ status: "pending",
+ };
+ index += 1;
+ return result;
+ }),
+ });
+ return { layer, polls };
+}
+
+const run = (layer: Layer.Layer<DeviceAuth>, advance: Duration.Input) =>
+ Effect.runPromise(
+ Effect.gen(function* () {
+ const fiber = yield* Effect.forkChild(
+ Effect.result(waitForApproval("https://api.test", code)),
+ );
+ yield* TestClock.adjust(advance);
+ return yield* Fiber.join(fiber);
+ }).pipe(Effect.provide(Layer.merge(layer, TestClock.layer()))),
+ );
+
+describe("waitForApproval", () => {
+ it("polls at the server interval and slows down when asked", async () => {
+ const device = scripted([
+ { status: "pending" },
+ { status: "slow_down" },
+ { status: "pending" },
+ { status: "approved", accessToken: "token" },
+ ]);
+ const result = await run(device.layer, "60 seconds");
+ expect(result).toEqual(Result.succeed("token"));
+ expect(device.polls).toEqual([0, 5_000, 15_000, 25_000]);
+ });
+
+ it("stops when the request is denied", async () => {
+ const result = await run(
+ scripted([{ status: "denied" }]).layer,
+ "1 second",
+ );
+ expect(Result.isFailure(result) && result.failure._tag).toBe(
+ "DeviceLoginDenied",
+ );
+ });
+
+ it("gives up when the code expires", async () => {
+ const result = await run(
+ scripted([{ status: "pending" }]).layer,
+ "61 seconds",
+ );
+ expect(Result.isFailure(result) && result.failure._tag).toBe(
+ "DeviceLoginExpired",
+ );
+ });
+});
+
+describe("formatUserCode", () => {
+ it("splits eight character codes", () => {
+ expect(formatUserCode("abcdefgh")).toBe("ABCD-EFGH");
+ expect(formatUserCode("ABCD-EFGH")).toBe("ABCD-EFGH");
+ expect(formatUserCode("XYZ")).toBe("XYZ");
+ });
+});
+
+describe("webUrlFromVerificationUri", () => {
+ it("strips the device path", () => {
+ expect(webUrlFromVerificationUri("https://app.kaneo.test/device")).toBe(
+ "https://app.kaneo.test",
+ );
+ expect(webUrlFromVerificationUri("https://x.test/kaneo/device/")).toBe(
+ "https://x.test/kaneo",
+ );
+ expect(webUrlFromVerificationUri("nope")).toBeUndefined();
+ });
+});
diff --git a/packages/cli/src/auth/wait-for-approval.ts b/packages/cli/src/auth/wait-for-approval.ts
new file mode 100644
index 000000000..b63ee6b20
--- /dev/null
+++ b/packages/cli/src/auth/wait-for-approval.ts
@@ -0,0 +1,63 @@
+import type { DeviceCodeResponse } from "@kaneo/mcp/device-flow";
+import { Duration, Effect, Option, Ref, Schedule } from "effect";
+import { DeviceLoginDenied, DeviceLoginExpired } from "../errors/errors.js";
+import { DeviceAuth } from "../services/device-auth.js";
+
+const SLOW_DOWN_SECONDS = 5;
+
+export const waitForApproval = Effect.fn("auth.waitForApproval")(function* (
+ apiUrl: string,
+ code: DeviceCodeResponse,
+) {
+ const device = yield* DeviceAuth;
+ const interval = yield* Ref.make(Math.max(1, code.interval));
+
+ const poll = device.poll(apiUrl, code.device_code).pipe(
+ Effect.retry({
+ schedule: Schedule.spaced("2 seconds"),
+ times: 3,
+ while: (error) => error._tag === "ServerUnreachable",
+ }),
+ Effect.tap((result) =>
+ result.status === "slow_down"
+ ? Ref.update(interval, (seconds) => seconds + SLOW_DOWN_SECONDS)
+ : Effect.void,
+ ),
+ );
+
+ const pacing = Schedule.passthrough(
+ Schedule.forever.pipe(
+ Schedule.addDelay(() => Effect.map(Ref.get(interval), Duration.seconds)),
+ ),
+ );
+
+ const outcome = yield* poll.pipe(
+ Effect.repeat({
+ schedule: pacing,
+ while: (result) =>
+ result.status === "pending" || result.status === "slow_down",
+ }),
+ Effect.timeoutOption(Duration.seconds(code.expires_in)),
+ );
+
+ if (Option.isNone(outcome)) return yield* new DeviceLoginExpired();
+ const result = outcome.value;
+ if (result.status === "approved") return result.accessToken;
+ if (result.status === "denied") return yield* new DeviceLoginDenied();
+ return yield* new DeviceLoginExpired();
+});
+
+export function formatUserCode(code: string): string {
+ const clean = code.replace(/[^A-Za-z0-9]/g, "").toUpperCase();
+ return clean.length === 8 ? `${clean.slice(0, 4)}-${clean.slice(4)}` : clean;
+}
+
+export function webUrlFromVerificationUri(uri: string): string | undefined {
+ try {
+ const url = new URL(uri);
+ const path = url.pathname.replace(/\/device\/?$/, "").replace(/\/+$/, "");
+ return `${url.protocol}//${url.host}${path}`;
+ } catch {
+ return undefined;
+ }
+}
diff --git a/packages/cli/src/bin.ts b/packages/cli/src/bin.ts
new file mode 100644
index 000000000..28a05b2ac
--- /dev/null
+++ b/packages/cli/src/bin.ts
@@ -0,0 +1,4 @@
+#!/usr/bin/env node
+import { main } from "./main.js";
+
+main(process.argv.slice(2));
diff --git a/packages/cli/src/bulk/bulk-change.test.ts b/packages/cli/src/bulk/bulk-change.test.ts
new file mode 100644
index 000000000..838da8b4a
--- /dev/null
+++ b/packages/cli/src/bulk/bulk-change.test.ts
@@ -0,0 +1,88 @@
+import { Option, Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { type BulkFlags, parseBulkChange } from "./bulk-change.js";
+
+const none: BulkFlags = {
+ status: Option.none(),
+ priority: Option.none(),
+ assignee: Option.none(),
+ unassign: false,
+ due: Option.none(),
+ addLabel: Option.none(),
+ removeLabel: Option.none(),
+ delete: false,
+};
+
+const now = new Date(2026, 9, 8, 15);
+
+describe("parseBulkChange", () => {
+ it("needs exactly one change", () => {
+ const empty = parseBulkChange(none, now);
+ expect(Result.isFailure(empty) && empty.failure.message).toBe(
+ "Nothing to change.",
+ );
+ const two = parseBulkChange(
+ { ...none, status: Option.some("done"), delete: true },
+ now,
+ );
+ expect(Result.isFailure(two) && two.failure.message).toBe(
+ "Pass one change per call, not --status and --delete.",
+ );
+ });
+
+ it("maps each flag to its change", () => {
+ expect(
+ Result.getOrThrow(
+ parseBulkChange({ ...none, status: Option.some(" done ") }, now),
+ ),
+ ).toEqual({ kind: "status", reference: "done" });
+ expect(
+ Result.getOrThrow(
+ parseBulkChange({ ...none, priority: Option.some("urgent") }, now),
+ ),
+ ).toEqual({ kind: "priority", priority: "urgent" });
+ expect(
+ Result.getOrThrow(parseBulkChange({ ...none, unassign: true }, now)),
+ ).toEqual({ kind: "unassign" });
+ expect(
+ Result.getOrThrow(
+ parseBulkChange({ ...none, addLabel: Option.some("Bug") }, now),
+ ),
+ ).toEqual({ kind: "addLabel", name: "Bug" });
+ expect(
+ Result.getOrThrow(
+ parseBulkChange({ ...none, removeLabel: Option.some("Bug") }, now),
+ ),
+ ).toEqual({ kind: "removeLabel", name: "Bug" });
+ expect(
+ Result.getOrThrow(parseBulkChange({ ...none, delete: true }, now)),
+ ).toEqual({ kind: "delete" });
+ });
+
+ it("parses due dates and none to clear", () => {
+ const due = Result.getOrThrow(
+ parseBulkChange({ ...none, due: Option.some("2026-10-20") }, now),
+ );
+ expect(due.kind === "due" && new Date(due.dueDate ?? "").getDate()).toBe(
+ 20,
+ );
+ expect(
+ Result.getOrThrow(
+ parseBulkChange({ ...none, due: Option.some("none") }, now),
+ ),
+ ).toEqual({ kind: "due", dueDate: null });
+ expect(
+ Result.isFailure(
+ parseBulkChange({ ...none, due: Option.some("soon") }, now),
+ ),
+ ).toBe(true);
+ });
+
+ it("refuses empty values", () => {
+ expect(
+ Result.isFailure(
+ parseBulkChange({ ...none, assignee: Option.some(" ") }, now),
+ ),
+ ).toBe(true);
+ });
+});
diff --git a/packages/cli/src/bulk/bulk-change.ts b/packages/cli/src/bulk/bulk-change.ts
new file mode 100644
index 000000000..0039e9ba4
--- /dev/null
+++ b/packages/cli/src/bulk/bulk-change.ts
@@ -0,0 +1,118 @@
+import { Option, Result } from "effect";
+import type { Priority } from "../api/task-mutations.js";
+import { InvalidArgument } from "../errors/errors.js";
+import { parseDateChange } from "../tasks/parse-date.js";
+
+export type BulkFlags = {
+ readonly status: Option.Option<string>;
+ readonly priority: Option.Option<Priority>;
+ readonly assignee: Option.Option<string>;
+ readonly unassign: boolean;
+ readonly due: Option.Option<string>;
+ readonly addLabel: Option.Option<string>;
+ readonly removeLabel: Option.Option<string>;
+ readonly delete: boolean;
+};
+
+export type BulkChange =
+ | { readonly kind: "status"; readonly reference: string }
+ | { readonly kind: "priority"; readonly priority: Priority }
+ | { readonly kind: "assignee"; readonly reference: string }
+ | { readonly kind: "unassign" }
+ | { readonly kind: "due"; readonly dueDate: string | null }
+ | { readonly kind: "addLabel"; readonly name: string }
+ | { readonly kind: "removeLabel"; readonly name: string }
+ | { readonly kind: "delete" };
+
+const FLAG_LIST =
+ "--status, --priority, --assignee, --unassign, --due, --add-label, --remove-label or --delete";
+
+function given(flags: BulkFlags): string[] {
+ const names: string[] = [];
+ if (Option.isSome(flags.status)) names.push("--status");
+ if (Option.isSome(flags.priority)) names.push("--priority");
+ if (Option.isSome(flags.assignee)) names.push("--assignee");
+ if (flags.unassign) names.push("--unassign");
+ if (Option.isSome(flags.due)) names.push("--due");
+ if (Option.isSome(flags.addLabel)) names.push("--add-label");
+ if (Option.isSome(flags.removeLabel)) names.push("--remove-label");
+ if (flags.delete) names.push("--delete");
+ return names;
+}
+
+function nonEmpty(
+ value: string,
+ flag: string,
+): Result.Result<string, InvalidArgument> {
+ const trimmed = value.trim();
+ return trimmed === ""
+ ? Result.fail(new InvalidArgument({ message: `${flag} needs a value.` }))
+ : Result.succeed(trimmed);
+}
+
+export function parseBulkChange(
+ flags: BulkFlags,
+ now: Date,
+): Result.Result<BulkChange, InvalidArgument> {
+ const names = given(flags);
+ if (names.length === 0) {
+ return Result.fail(
+ new InvalidArgument({
+ message: "Nothing to change.",
+ hint: `Pass one of ${FLAG_LIST}.`,
+ }),
+ );
+ }
+ if (names.length > 1) {
+ return Result.fail(
+ new InvalidArgument({
+ message: `Pass one change per call, not ${names.join(" and ")}.`,
+ hint: "Run kaneo task bulk once for each change.",
+ }),
+ );
+ }
+ if (Option.isSome(flags.status)) {
+ return Result.map(
+ nonEmpty(flags.status.value, "--status"),
+ (reference) => ({
+ kind: "status" as const,
+ reference,
+ }),
+ );
+ }
+ if (Option.isSome(flags.priority)) {
+ return Result.succeed({ kind: "priority", priority: flags.priority.value });
+ }
+ if (Option.isSome(flags.assignee)) {
+ return Result.map(
+ nonEmpty(flags.assignee.value, "--assignee"),
+ (reference) => ({ kind: "assignee" as const, reference }),
+ );
+ }
+ if (flags.unassign) return Result.succeed({ kind: "unassign" });
+ if (Option.isSome(flags.due)) {
+ return Result.map(
+ parseDateChange(flags.due.value, now, "--due"),
+ (dueDate) => ({
+ kind: "due" as const,
+ dueDate,
+ }),
+ );
+ }
+ if (Option.isSome(flags.addLabel)) {
+ return Result.map(
+ nonEmpty(flags.addLabel.value, "--add-label"),
+ (name) => ({
+ kind: "addLabel" as const,
+ name,
+ }),
+ );
+ }
+ if (Option.isSome(flags.removeLabel)) {
+ return Result.map(
+ nonEmpty(flags.removeLabel.value, "--remove-label"),
+ (name) => ({ kind: "removeLabel" as const, name }),
+ );
+ }
+ return Result.succeed({ kind: "delete" });
+}
diff --git a/packages/cli/src/bulk/bulk-status.test.ts b/packages/cli/src/bulk/bulk-status.test.ts
new file mode 100644
index 000000000..59a3da1bf
--- /dev/null
+++ b/packages/cli/src/bulk/bulk-status.test.ts
@@ -0,0 +1,64 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import type { Column } from "../api/schemas.js";
+import { resolveBulkStatus } from "./bulk-status.js";
+
+function column(slug: string, name: string, position: number): Column {
+ return {
+ id: `${slug}-id`,
+ projectId: "p",
+ slug,
+ name,
+ position,
+ color: null,
+ isFinal: slug === "done",
+ };
+}
+
+const standard = [
+ column("to-do", "To Do", 0),
+ column("in-progress", "In Progress", 1),
+ column("done", "Done", 2),
+];
+
+describe("resolveBulkStatus", () => {
+ it("matches by slug, name or alias in every project", () => {
+ const projects = [
+ { name: "Kaneo Web", columns: standard },
+ { name: "Mobile App", columns: standard },
+ ];
+ expect(Result.getOrThrow(resolveBulkStatus(projects, "wip")).slug).toBe(
+ "in-progress",
+ );
+ expect(Result.getOrThrow(resolveBulkStatus(projects, "Done")).slug).toBe(
+ "done",
+ );
+ });
+
+ it("names the project without a matching column", () => {
+ const result = resolveBulkStatus(
+ [
+ { name: "Kaneo Web", columns: standard },
+ { name: "Mobile App", columns: [column("to-do", "To Do", 0)] },
+ ],
+ "done",
+ );
+ expect(Result.isFailure(result) && result.failure.message).toBe(
+ 'No column in Mobile App matches "done".',
+ );
+ expect(Result.isFailure(result) && result.failure.hint).toBe(
+ "Use one of: to-do.",
+ );
+ });
+
+ it("refuses a name that means different slugs in different projects", () => {
+ const result = resolveBulkStatus(
+ [
+ { name: "Kaneo Web", columns: standard },
+ { name: "Mobile App", columns: [column("shipped", "Done", 0)] },
+ ],
+ "Done",
+ );
+ expect(Result.isFailure(result)).toBe(true);
+ });
+});
diff --git a/packages/cli/src/bulk/bulk-status.ts b/packages/cli/src/bulk/bulk-status.ts
new file mode 100644
index 000000000..324546399
--- /dev/null
+++ b/packages/cli/src/bulk/bulk-status.ts
@@ -0,0 +1,48 @@
+import { Result } from "effect";
+import type { Column } from "../api/schemas.js";
+import { InvalidArgument } from "../errors/errors.js";
+import { matchColumn } from "../tasks/match-column.js";
+
+export type ProjectColumns = {
+ readonly name: string;
+ readonly columns: ReadonlyArray<Column>;
+};
+
+function slugList(columns: ReadonlyArray<Column>): string {
+ return [...columns]
+ .sort((a, b) => a.position - b.position)
+ .map((column) => column.slug)
+ .join(", ");
+}
+
+export function resolveBulkStatus(
+ projects: ReadonlyArray<ProjectColumns>,
+ reference: string,
+): Result.Result<Column, InvalidArgument> {
+ let chosen: { readonly column: Column; readonly project: string } | null =
+ null;
+ for (const project of projects) {
+ const match = matchColumn(project.columns, reference);
+ if (!match) {
+ return Result.fail(
+ new InvalidArgument({
+ message: `No column in ${project.name} matches "${reference}".`,
+ hint: `Use one of: ${slugList(project.columns)}.`,
+ }),
+ );
+ }
+ if (chosen === null) {
+ chosen = { column: match, project: project.name };
+ } else if (chosen.column.slug !== match.slug) {
+ return Result.fail(
+ new InvalidArgument({
+ message: `"${reference}" is ${chosen.column.slug} in ${chosen.project} but ${match.slug} in ${project.name}.`,
+ hint: "Every task gets the same column slug, so pick tasks from projects that share it.",
+ }),
+ );
+ }
+ }
+ return chosen === null
+ ? Result.fail(new InvalidArgument({ message: "No tasks to change." }))
+ : Result.succeed(chosen.column);
+}
diff --git a/packages/cli/src/bulk/label-for-removal.test.ts b/packages/cli/src/bulk/label-for-removal.test.ts
new file mode 100644
index 000000000..703c9754f
--- /dev/null
+++ b/packages/cli/src/bulk/label-for-removal.test.ts
@@ -0,0 +1,30 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import type { Label } from "../api/labels.js";
+import { labelForRemoval } from "./label-for-removal.js";
+
+function label(id: string, name: string, taskId: string | null): Label {
+ return { id, name, color: "red", taskId, workspaceId: "w1" };
+}
+
+describe("labelForRemoval", () => {
+ it("prefers the workspace label over task copies", () => {
+ const labels = [label("t1", "Bug", "task-1"), label("w1", "Bug", null)];
+ expect(Result.getOrThrow(labelForRemoval(labels, "bug")).id).toBe("w1");
+ });
+
+ it("falls back to a task copy when the workspace label is gone", () => {
+ expect(
+ Result.getOrThrow(labelForRemoval([label("t1", "Old", "task-1")], "old"))
+ .id,
+ ).toBe("t1");
+ });
+
+ it("accepts a label id and fails for unknown names", () => {
+ expect(
+ Result.getOrThrow(labelForRemoval([label("t1", "Old", "task-1")], "t1"))
+ .name,
+ ).toBe("Old");
+ expect(Result.isFailure(labelForRemoval([], "Bug"))).toBe(true);
+ });
+});
diff --git a/packages/cli/src/bulk/label-for-removal.ts b/packages/cli/src/bulk/label-for-removal.ts
new file mode 100644
index 000000000..f04d68171
--- /dev/null
+++ b/packages/cli/src/bulk/label-for-removal.ts
@@ -0,0 +1,28 @@
+import { Result } from "effect";
+import type { Label } from "../api/labels.js";
+import { InvalidArgument } from "../errors/errors.js";
+import { normalizeLabelName } from "../labels/match-label.js";
+
+export function labelForRemoval(
+ labels: ReadonlyArray<Label>,
+ reference: string,
+): Result.Result<Label, InvalidArgument> {
+ const trimmed = reference.trim();
+ const wanted = normalizeLabelName(reference);
+ const named = labels.filter(
+ (label) =>
+ label.id === trimmed || normalizeLabelName(label.name) === wanted,
+ );
+ const match =
+ named.find((label) => label.id === trimmed) ??
+ named.find((label) => label.taskId === null) ??
+ named[0];
+ return match
+ ? Result.succeed(match)
+ : Result.fail(
+ new InvalidArgument({
+ message: `No label named "${trimmed}" in this workspace.`,
+ hint: "Run kaneo label list to see the label names.",
+ }),
+ );
+}
diff --git a/packages/cli/src/bulk/preflight.test.ts b/packages/cli/src/bulk/preflight.test.ts
new file mode 100644
index 000000000..3ed4d6b93
--- /dev/null
+++ b/packages/cli/src/bulk/preflight.test.ts
@@ -0,0 +1,53 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { checkFound, checkSameWorkspace } from "./preflight.js";
+
+describe("checkFound", () => {
+ it("changes nothing when any task is unknown and names them all", () => {
+ const result = checkFound([
+ { reference: "KAN-1", task: { id: "a" } },
+ { reference: "KAN-98", task: null },
+ { reference: "KAN-99", task: null },
+ ]);
+ expect(Result.isFailure(result) && result.failure.message).toBe(
+ "Tasks KAN-98 and KAN-99 were not found, so nothing was changed.",
+ );
+ });
+
+ it("uses the singular for one unknown task", () => {
+ const result = checkFound([{ reference: "KAN-98", task: null }]);
+ expect(Result.isFailure(result) && result.failure.message).toBe(
+ "Task KAN-98 was not found, so nothing was changed.",
+ );
+ });
+
+ it("drops tasks named twice, keeping the order", () => {
+ expect(
+ Result.getOrThrow(
+ checkFound([
+ { reference: "KAN-2", task: { id: "b" } },
+ { reference: "KAN-1", task: { id: "a" } },
+ { reference: "b", task: { id: "b" } },
+ ]),
+ ).map((task) => task.id),
+ ).toEqual(["b", "a"]);
+ });
+});
+
+describe("checkSameWorkspace", () => {
+ it("returns the shared workspace", () => {
+ expect(
+ Result.getOrThrow(
+ checkSameWorkspace([{ workspaceId: "w1" }, { workspaceId: "w1" }]),
+ ),
+ ).toBe("w1");
+ });
+
+ it("refuses tasks from two workspaces, which the API rejects", () => {
+ expect(
+ Result.isFailure(
+ checkSameWorkspace([{ workspaceId: "w1" }, { workspaceId: "w2" }]),
+ ),
+ ).toBe(true);
+ });
+});
diff --git a/packages/cli/src/bulk/preflight.ts b/packages/cli/src/bulk/preflight.ts
new file mode 100644
index 000000000..fcb5b9402
--- /dev/null
+++ b/packages/cli/src/bulk/preflight.ts
@@ -0,0 +1,56 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+
+export type Lookup<T> = {
+ readonly reference: string;
+ readonly task: T | null;
+};
+
+function list(values: ReadonlyArray<string>): string {
+ if (values.length <= 1) return values.join("");
+ return `${values.slice(0, -1).join(", ")} and ${values.at(-1)}`;
+}
+
+export function checkFound<T extends { readonly id: string }>(
+ lookups: ReadonlyArray<Lookup<T>>,
+): Result.Result<T[], InvalidArgument> {
+ const missing = lookups
+ .filter((lookup) => lookup.task === null)
+ .map((lookup) => lookup.reference.trim());
+ if (missing.length > 0) {
+ const unique = [...new Set(missing)];
+ return Result.fail(
+ new InvalidArgument({
+ message:
+ unique.length === 1
+ ? `Task ${unique[0]} was not found, so nothing was changed.`
+ : `Tasks ${list(unique)} were not found, so nothing was changed.`,
+ hint: "Check the ticket ids, or run kaneo task list to see them.",
+ }),
+ );
+ }
+ const seen = new Set<string>();
+ const tasks: T[] = [];
+ for (const lookup of lookups) {
+ if (lookup.task === null || seen.has(lookup.task.id)) continue;
+ seen.add(lookup.task.id);
+ tasks.push(lookup.task);
+ }
+ return Result.succeed(tasks);
+}
+
+export function checkSameWorkspace(
+ tasks: ReadonlyArray<{ readonly workspaceId: string }>,
+): Result.Result<string, InvalidArgument> {
+ const workspaces = [...new Set(tasks.map((task) => task.workspaceId))];
+ const [only] = workspaces;
+ if (workspaces.length === 1 && only !== undefined) {
+ return Result.succeed(only);
+ }
+ return Result.fail(
+ new InvalidArgument({
+ message: "The tasks belong to more than one workspace.",
+ hint: "Run kaneo task bulk once per workspace.",
+ }),
+ );
+}
diff --git a/packages/cli/src/bulk/render-bulk-result.test.ts b/packages/cli/src/bulk/render-bulk-result.test.ts
new file mode 100644
index 000000000..d70b25d07
--- /dev/null
+++ b/packages/cli/src/bulk/render-bulk-result.test.ts
@@ -0,0 +1,95 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import { bulkHeadline, renderBulkResult } from "./render-bulk-result.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+const tasks = [
+ { label: "KAN-1", title: "Fix login redirect", url: "https://kaneo.test/1" },
+ {
+ label: "KAN-12",
+ title:
+ "A title long enough to need shortening on an eighty column terminal",
+ url: "https://kaneo.test/12",
+ },
+];
+
+describe("bulkHeadline", () => {
+ it("describes each change", () => {
+ expect(
+ bulkHeadline({ kind: "status", columnName: "Done" }, 2, 2).text,
+ ).toBe("Moved 2 tasks to Done");
+ expect(
+ bulkHeadline({ kind: "priority", priority: "high" }, 1, 1).text,
+ ).toBe("Set priority to High on 1 task");
+ expect(
+ bulkHeadline({ kind: "priority", priority: "no-priority" }, 2, 2).text,
+ ).toBe("Cleared the priority on 2 tasks");
+ expect(bulkHeadline({ kind: "assignee", name: "Ada" }, 2, 2).text).toBe(
+ "Assigned 2 tasks to Ada",
+ );
+ expect(bulkHeadline({ kind: "unassign" }, 2, 2).text).toBe(
+ "Unassigned 2 tasks",
+ );
+ expect(bulkHeadline({ kind: "due", dueDate: null }, 2, 2).text).toBe(
+ "Cleared the due date on 2 tasks",
+ );
+ expect(
+ bulkHeadline({ kind: "due", dueDate: "2026-10-20T10:00:00.000Z" }, 2, 2)
+ .text,
+ ).toBe("Set the due date to Oct 20, 2026 on 2 tasks");
+ expect(bulkHeadline({ kind: "delete" }, 3, 3).text).toBe("Deleted 3 tasks");
+ });
+
+ it("counts label changes that did not apply", () => {
+ expect(bulkHeadline({ kind: "addLabel", labelName: "Bug" }, 3, 2)).toEqual({
+ text: "Added Bug to 2 tasks",
+ aside: "1 already had it",
+ });
+ expect(
+ bulkHeadline({ kind: "removeLabel", labelName: "Bug" }, 3, 1),
+ ).toEqual({ text: "Removed Bug from 1 task", aside: "2 did not have it" });
+ expect(
+ bulkHeadline({ kind: "addLabel", labelName: "Bug" }, 2, 0).text,
+ ).toBe("No change: all 2 tasks already had Bug");
+ expect(
+ bulkHeadline({ kind: "removeLabel", labelName: "Bug" }, 1, 0).text,
+ ).toBe("No change: the task did not have Bug");
+ });
+});
+
+describe("renderBulkResult", () => {
+ it("prints the summary and the tickets at 80 columns", () => {
+ const lines = renderBulkResult(ui, {
+ change: { kind: "addLabel", labelName: "Bug" },
+ updated: 1,
+ tasks,
+ });
+ expect(lines).toEqual([
+ "",
+ " ✓ Added Bug to 1 task (1 already had it)",
+ "",
+ " KAN-1 Fix login redirect",
+ " KAN-12 A title long enough to need shortening on an eighty column terminal",
+ "",
+ ]);
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(80);
+ });
+
+ it("truncates titles on narrow terminals", () => {
+ const narrow = makeUi({ ...ui.caps, columns: 40 });
+ const lines = renderBulkResult(narrow, {
+ change: { kind: "delete" },
+ updated: 2,
+ tasks,
+ });
+ expect(lines[4]).toBe(" KAN-12 A title long enough to need…");
+ });
+});
diff --git a/packages/cli/src/bulk/render-bulk-result.ts b/packages/cli/src/bulk/render-bulk-result.ts
new file mode 100644
index 000000000..aefb90da3
--- /dev/null
+++ b/packages/cli/src/bulk/render-bulk-result.ts
@@ -0,0 +1,125 @@
+import { type Cell, text } from "../render/cell.js";
+import { renderTable } from "../render/table.js";
+import { PRIORITY_LABELS } from "../render/task-format.js";
+import type { Ui } from "../render/ui.js";
+
+export type AppliedChange =
+ | { readonly kind: "status"; readonly columnName: string }
+ | { readonly kind: "priority"; readonly priority: string }
+ | { readonly kind: "assignee"; readonly name: string }
+ | { readonly kind: "unassign" }
+ | { readonly kind: "due"; readonly dueDate: string | null }
+ | { readonly kind: "addLabel"; readonly labelName: string }
+ | { readonly kind: "removeLabel"; readonly labelName: string }
+ | { readonly kind: "delete" };
+
+export type BulkResultView = {
+ readonly change: AppliedChange;
+ readonly updated: number;
+ readonly tasks: ReadonlyArray<{
+ readonly label: string;
+ readonly title: string;
+ readonly url: string;
+ }>;
+};
+
+function tasks(count: number): string {
+ return count === 1 ? "1 task" : `${count} tasks`;
+}
+
+function day(iso: string): string {
+ return new Date(iso).toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ });
+}
+
+export function bulkHeadline(
+ change: AppliedChange,
+ total: number,
+ updated: number,
+): { readonly text: string; readonly aside: string | null } {
+ const all = tasks(total);
+ switch (change.kind) {
+ case "status":
+ return { text: `Moved ${all} to ${change.columnName}`, aside: null };
+ case "priority": {
+ const label = PRIORITY_LABELS[change.priority];
+ return label
+ ? { text: `Set priority to ${label} on ${all}`, aside: null }
+ : { text: `Cleared the priority on ${all}`, aside: null };
+ }
+ case "assignee":
+ return { text: `Assigned ${all} to ${change.name}`, aside: null };
+ case "unassign":
+ return { text: `Unassigned ${all}`, aside: null };
+ case "due":
+ return change.dueDate === null
+ ? { text: `Cleared the due date on ${all}`, aside: null }
+ : {
+ text: `Set the due date to ${day(change.dueDate)} on ${all}`,
+ aside: null,
+ };
+ case "addLabel":
+ if (updated === 0) {
+ return {
+ text: `No change: ${total === 1 ? "the task" : `all ${all}`} already had ${change.labelName}`,
+ aside: null,
+ };
+ }
+ return {
+ text: `Added ${change.labelName} to ${tasks(updated)}`,
+ aside: updated < total ? `${total - updated} already had it` : null,
+ };
+ case "removeLabel":
+ if (updated === 0) {
+ return {
+ text:
+ total === 1
+ ? `No change: the task did not have ${change.labelName}`
+ : `No change: none of the ${all} had ${change.labelName}`,
+ aside: null,
+ };
+ }
+ return {
+ text: `Removed ${change.labelName} from ${tasks(updated)}`,
+ aside: updated < total ? `${total - updated} did not have it` : null,
+ };
+ case "delete":
+ return { text: `Deleted ${tasks(updated)}`, aside: null };
+ }
+}
+
+export function renderBulkResult(ui: Ui, view: BulkResultView): string[] {
+ const { theme, glyphs } = ui;
+ const headline = bulkHeadline(view.change, view.tasks.length, view.updated);
+ const linked = view.change.kind !== "delete";
+ return [
+ "",
+ ` ${theme.success(glyphs.tick)} ${headline.text}${headline.aside ? ` ${theme.muted(`(${headline.aside})`)}` : ""}`,
+ "",
+ ...renderTable(
+ ui,
+ view.tasks,
+ [
+ {
+ header: "ID",
+ cell: (task): Cell => [
+ text(task.label, theme.muted, linked ? task.url : undefined),
+ ],
+ },
+ {
+ header: "Title",
+ flex: true,
+ minWidth: 16,
+ cell: (task): Cell => [
+ text(task.title, undefined, linked ? task.url : undefined),
+ ],
+ },
+ ],
+ { width: ui.caps.columns, indent: 4, gap: 2 },
+ ),
+ "",
+ ];
+}
diff --git a/packages/cli/src/bulk/resolve-bulk-tasks.ts b/packages/cli/src/bulk/resolve-bulk-tasks.ts
new file mode 100644
index 000000000..903bfdbc4
--- /dev/null
+++ b/packages/cli/src/bulk/resolve-bulk-tasks.ts
@@ -0,0 +1,65 @@
+import { Effect } from "effect";
+import { getProject } from "../api/endpoints.js";
+import type { Project } from "../api/schemas.js";
+import { taskUrl } from "../render/links.js";
+import { ticketId } from "../render/task-format.js";
+import { Session } from "../services/session.js";
+import { fetchTask } from "../tasks/resolve-task.js";
+import { checkFound, checkSameWorkspace } from "./preflight.js";
+
+export type BulkTask = {
+ readonly id: string;
+ readonly title: string;
+ readonly ticketId: string | null;
+ readonly label: string;
+ readonly url: string;
+ readonly project: Project;
+ readonly workspaceId: string;
+};
+
+export const resolveBulkTasks = Effect.fn("bulk.resolveTasks")(function* (
+ references: ReadonlyArray<string>,
+) {
+ const session = yield* Session;
+ const lookups = yield* Effect.forEach(
+ references,
+ (reference) =>
+ fetchTask(reference).pipe(
+ Effect.map((task) => ({ reference, task })),
+ Effect.catchTag("NotFound", () =>
+ Effect.succeed({ reference, task: null }),
+ ),
+ ),
+ { concurrency: 6 },
+ );
+ const tasks = yield* Effect.fromResult(checkFound(lookups));
+ const projectIds = [...new Set(tasks.map((task) => task.projectId))];
+ const projects = new Map(
+ (yield* Effect.forEach(projectIds, (id) => getProject(id), {
+ concurrency: 4,
+ })).map((project) => [project.id, project]),
+ );
+ const resolved = tasks.flatMap((task): BulkTask[] => {
+ const project = projects.get(task.projectId);
+ if (!project) return [];
+ const id = ticketId(project.slug, task.number);
+ const workspaceId = task.workspaceId ?? project.workspaceId;
+ return [
+ {
+ id: task.id,
+ title: task.title,
+ ticketId: id,
+ label: id ?? task.id.slice(0, 8),
+ url: taskUrl(session.webUrl, {
+ workspaceId,
+ projectId: task.projectId,
+ id: task.id,
+ }),
+ project,
+ workspaceId,
+ },
+ ];
+ });
+ const workspaceId = yield* Effect.fromResult(checkSameWorkspace(resolved));
+ return { workspaceId, tasks: resolved };
+});
diff --git a/packages/cli/src/cli/formatter.ts b/packages/cli/src/cli/formatter.ts
new file mode 100644
index 000000000..dc9a77551
--- /dev/null
+++ b/packages/cli/src/cli/formatter.ts
@@ -0,0 +1,23 @@
+import { CliOutput } from "effect/cli";
+import type { OutputShape } from "../output/output.js";
+import { logo } from "../render/logo.js";
+
+export function makeFormatter(output: OutputShape): CliOutput.Formatter {
+ const base = CliOutput.defaultFormatter({
+ colors: output.mode === "human" && output.ui.caps.color > 0,
+ });
+ return {
+ ...base,
+ formatVersion: (name, version) => {
+ if (output.mode === "json") return JSON.stringify({ name, version });
+ const { theme, glyphs } = output.ui;
+ return [
+ "",
+ ...logo(output.ui),
+ "",
+ ` ${theme.strong(name)} ${version} ${theme.muted(`${glyphs.separator} node ${process.version}`)}`,
+ "",
+ ].join("\n");
+ },
+ };
+}
diff --git a/packages/cli/src/cli/global-flags.ts b/packages/cli/src/cli/global-flags.ts
new file mode 100644
index 000000000..c33f23ae4
--- /dev/null
+++ b/packages/cli/src/cli/global-flags.ts
@@ -0,0 +1,71 @@
+import { Flag, GlobalFlag } from "effect/cli";
+import { jqFlagValue } from "../jq/jq-flag-value.js";
+
+export const JsonFlag = GlobalFlag.Setting("json")({
+ flag: Flag.Boolean("json").pipe(
+ Flag.withDescription(
+ "Print one JSON value on stdout (the default when stdout is not a terminal)",
+ ),
+ Flag.withDefault(false),
+ ),
+});
+
+export const HumanFlag = GlobalFlag.Setting("human")({
+ flag: Flag.Boolean("human").pipe(
+ Flag.withDescription(
+ "Print styled output even when stdout is not a terminal",
+ ),
+ Flag.withDefault(false),
+ ),
+});
+
+export const TokenFlag = GlobalFlag.Setting("token")({
+ flag: Flag.Redacted("token").pipe(
+ Flag.withDescription(
+ "API key or access token to use instead of the stored login",
+ ),
+ Flag.optional,
+ ),
+});
+
+export const ApiUrlFlag = GlobalFlag.Setting("api-url")({
+ flag: Flag.String("api-url").pipe(
+ Flag.withDescription("Kaneo server URL (or KANEO_API_URL)"),
+ Flag.optional,
+ ),
+});
+
+export const WorkspaceFlag = GlobalFlag.Setting("workspace")({
+ flag: Flag.String("workspace").pipe(
+ Flag.withAlias("w"),
+ Flag.withDescription("Workspace id (or KANEO_WORKSPACE)"),
+ Flag.optional,
+ ),
+});
+
+export const ProfileFlag = GlobalFlag.Setting("profile")({
+ flag: Flag.String("profile").pipe(
+ Flag.withDescription("Stored login to use (or KANEO_PROFILE)"),
+ Flag.optional,
+ ),
+});
+
+export const JqFlag = GlobalFlag.Setting("jq")({
+ flag: Flag.String("jq").pipe(
+ Flag.withDescription(
+ "Filter the JSON output with a jq expression, for example '.[].title'",
+ ),
+ Flag.mapEffect(jqFlagValue),
+ Flag.optional,
+ ),
+});
+
+export const globalFlags = [
+ JsonFlag,
+ HumanFlag,
+ JqFlag,
+ TokenFlag,
+ ApiUrlFlag,
+ WorkspaceFlag,
+ ProfileFlag,
+] as const;
diff --git a/packages/cli/src/cli/root.ts b/packages/cli/src/cli/root.ts
new file mode 100644
index 000000000..413b9c8d2
--- /dev/null
+++ b/packages/cli/src/cli/root.ts
@@ -0,0 +1,56 @@
+import { Command } from "effect/cli";
+import { ApiLayer } from "../commands/api-layer.js";
+import { runHome } from "../commands/home.js";
+import { login } from "../commands/login.js";
+import { logout } from "../commands/logout.js";
+import { project } from "../commands/project/index.js";
+import { search } from "../commands/search.js";
+import { task } from "../commands/task/index.js";
+import { whoami } from "../commands/whoami.js";
+import { workspace } from "../commands/workspace/index.js";
+import { label } from "../commands/label/index.js";
+import { comment } from "../commands/comment/index.js";
+import { time } from "../commands/time/index.js";
+import { notification } from "../commands/notification/index.js";
+import { column } from "../commands/column/index.js";
+import { member } from "../commands/member/index.js";
+import { invitation } from "../commands/invitation/index.js";
+import { field } from "../commands/field/index.js";
+import { workflow } from "../commands/workflow/index.js";
+import { profile } from "../commands/profile/index.js";
+import { linkCommand } from "../commands/link.js";
+import { unlinkCommand } from "../commands/unlink.js";
+import { contextCommand } from "../commands/context.js";
+import { apiCommand } from "../commands/api.js";
+import { doctorCommand } from "../commands/doctor.js";
+import { globalFlags } from "./global-flags.js";
+
+export const root = Command.make("kaneo", {}, () => runHome()).pipe(
+ Command.withDescription("Kaneo from your terminal"),
+ Command.provide(ApiLayer),
+ Command.withSubcommands([
+ login,
+ logout,
+ whoami,
+ contextCommand,
+ linkCommand,
+ unlinkCommand,
+ profile,
+ workspace,
+ member,
+ invitation,
+ project,
+ column,
+ task,
+ comment,
+ label,
+ time,
+ field,
+ workflow,
+ notification,
+ search,
+ apiCommand,
+ doctorCommand,
+ ]),
+ Command.withGlobalFlags(globalFlags),
+);
diff --git a/packages/cli/src/columns/column-json.ts b/packages/cli/src/columns/column-json.ts
new file mode 100644
index 000000000..3997d7218
--- /dev/null
+++ b/packages/cli/src/columns/column-json.ts
@@ -0,0 +1,30 @@
+import type { ColumnDetail } from "../api/columns.js";
+
+export type ColumnJson = {
+ readonly id: string;
+ readonly projectId: string;
+ readonly name: string;
+ readonly slug: string;
+ readonly position: number;
+ readonly icon: string | null;
+ readonly color: string | null;
+ readonly isFinal: boolean;
+ readonly taskCount: number | null;
+};
+
+export function toColumnJson(
+ column: ColumnDetail,
+ taskCount: number | null,
+): ColumnJson {
+ return {
+ id: column.id,
+ projectId: column.projectId,
+ name: column.name,
+ slug: column.slug,
+ position: column.position,
+ icon: column.icon,
+ color: column.color,
+ isFinal: column.isFinal,
+ taskCount,
+ };
+}
diff --git a/packages/cli/src/columns/find-column.test.ts b/packages/cli/src/columns/find-column.test.ts
new file mode 100644
index 000000000..1327af7af
--- /dev/null
+++ b/packages/cli/src/columns/find-column.test.ts
@@ -0,0 +1,32 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { findColumn } from "./find-column.js";
+
+const columns = [
+ { id: "c1", slug: "to-do", name: "To Do" },
+ { id: "c2", slug: "in-progress", name: "In Progress" },
+ { id: "c3", slug: "done", name: "Done" },
+];
+
+describe("findColumn", () => {
+ it("matches ids, slugs and names", () => {
+ const id = (reference: string) => {
+ const result = findColumn(columns, reference);
+ return Result.isSuccess(result) ? result.success.id : null;
+ };
+ expect(id("c2")).toBe("c2");
+ expect(id("done")).toBe("c3");
+ expect(id("in progress")).toBe("c2");
+ });
+
+ it("lists the slugs when nothing matches", () => {
+ const result = findColumn(columns, "qa", "--before");
+ expect(Result.isFailure(result)).toBe(true);
+ if (Result.isFailure(result)) {
+ expect(result.failure.message).toBe(
+ '--before "qa" does not match a column in this project.',
+ );
+ expect(result.failure.hint).toBe("Columns: to-do, in-progress, done.");
+ }
+ });
+});
diff --git a/packages/cli/src/columns/find-column.ts b/packages/cli/src/columns/find-column.ts
new file mode 100644
index 000000000..c9238e470
--- /dev/null
+++ b/packages/cli/src/columns/find-column.ts
@@ -0,0 +1,19 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+import { type ColumnRef, matchColumn } from "../tasks/match-column.js";
+
+export function findColumn<C extends ColumnRef>(
+ columns: ReadonlyArray<C>,
+ reference: string,
+ flag?: string,
+): Result.Result<C, InvalidArgument> {
+ const match = matchColumn(columns, reference);
+ if (match) return Result.succeed(match);
+ const slugs = columns.map((column) => column.slug).join(", ");
+ return Result.fail(
+ new InvalidArgument({
+ message: `${flag ? `${flag} ` : ""}"${reference}" does not match a column in this project.`,
+ hint: slugs ? `Columns: ${slugs}.` : "This project has no columns yet.",
+ }),
+ );
+}
diff --git a/packages/cli/src/columns/parse-color.test.ts b/packages/cli/src/columns/parse-color.test.ts
new file mode 100644
index 000000000..b3c480ac0
--- /dev/null
+++ b/packages/cli/src/columns/parse-color.test.ts
@@ -0,0 +1,22 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { parseColor } from "./parse-color.js";
+
+const color = (input: string) => {
+ const result = parseColor(input);
+ return Result.isSuccess(result) ? result.success : "invalid";
+};
+
+describe("parseColor", () => {
+ it("normalizes hex colors", () => {
+ expect(color("#3B82F6")).toBe("#3b82f6");
+ expect(color("3b82f6")).toBe("#3b82f6");
+ expect(color("#abc")).toBe("#aabbcc");
+ });
+
+ it("clears with none and rejects other words", () => {
+ expect(color("none")).toBeNull();
+ expect(color("blue")).toBe("invalid");
+ expect(color("#12345")).toBe("invalid");
+ });
+});
diff --git a/packages/cli/src/columns/parse-color.ts b/packages/cli/src/columns/parse-color.ts
new file mode 100644
index 000000000..f191742e8
--- /dev/null
+++ b/packages/cli/src/columns/parse-color.ts
@@ -0,0 +1,25 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+
+const HEX = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/iu;
+
+export function parseColor(
+ input: string,
+): Result.Result<string | null, InvalidArgument> {
+ const value = input.trim();
+ if (value.toLowerCase() === "none") return Result.succeed(null);
+ const hex = HEX.exec(value)?.[1];
+ if (!hex) {
+ return Result.fail(
+ new InvalidArgument({
+ message: `--color "${input}" is not a hex color.`,
+ hint: "Use a hex color such as #3b82f6, or none to clear it.",
+ }),
+ );
+ }
+ const full =
+ hex.length === 3
+ ? [...hex].map((digit) => `${digit}${digit}`).join("")
+ : hex;
+ return Result.succeed(`#${full.toLowerCase()}`);
+}
diff --git a/packages/cli/src/columns/plan-column-move.test.ts b/packages/cli/src/columns/plan-column-move.test.ts
new file mode 100644
index 000000000..a3651eb17
--- /dev/null
+++ b/packages/cli/src/columns/plan-column-move.test.ts
@@ -0,0 +1,82 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { planColumnMove } from "./plan-column-move.js";
+
+const columns = [
+ { id: "c1", slug: "to-do", name: "To Do" },
+ { id: "c2", slug: "in-progress", name: "In Progress" },
+ { id: "c3", slug: "in-review", name: "In Review" },
+ { id: "c4", slug: "done", name: "Done" },
+];
+
+const order = (request: {
+ column: string;
+ before?: string;
+ after?: string;
+}) => {
+ const result = planColumnMove(columns, {
+ column: request.column,
+ before: request.before,
+ after: request.after,
+ });
+ return Result.isSuccess(result)
+ ? result.success.order.map((column) => column.slug)
+ : result.failure.message;
+};
+
+describe("planColumnMove", () => {
+ it("moves a column before another", () => {
+ expect(order({ column: "done", before: "in-progress" })).toEqual([
+ "to-do",
+ "done",
+ "in-progress",
+ "in-review",
+ ]);
+ });
+
+ it("moves a column after another, including to the end", () => {
+ expect(order({ column: "to-do", after: "in-review" })).toEqual([
+ "in-progress",
+ "in-review",
+ "to-do",
+ "done",
+ ]);
+ expect(order({ column: "to-do", after: "done" })).toEqual([
+ "in-progress",
+ "in-review",
+ "done",
+ "to-do",
+ ]);
+ });
+
+ it("reports when nothing changes", () => {
+ const result = planColumnMove(columns, {
+ column: "in-progress",
+ before: "in-review",
+ after: undefined,
+ });
+ expect(Result.isSuccess(result) && result.success.changed).toBe(false);
+ });
+
+ it("needs exactly one placement", () => {
+ expect(order({ column: "done" })).toBe("Say where the column goes.");
+ expect(order({ column: "done", before: "to-do", after: "to-do" })).toBe(
+ "Say where the column goes.",
+ );
+ });
+
+ it("refuses to move a column relative to itself", () => {
+ expect(order({ column: "done", after: "Done" })).toBe(
+ "Cannot move Done after itself.",
+ );
+ });
+
+ it("names the flag of an unknown anchor", () => {
+ expect(order({ column: "done", before: "qa" })).toBe(
+ '--before "qa" does not match a column in this project.',
+ );
+ expect(order({ column: "qa", before: "done" })).toBe(
+ '"qa" does not match a column in this project.',
+ );
+ });
+});
diff --git a/packages/cli/src/columns/plan-column-move.ts b/packages/cli/src/columns/plan-column-move.ts
new file mode 100644
index 000000000..d33abc00a
--- /dev/null
+++ b/packages/cli/src/columns/plan-column-move.ts
@@ -0,0 +1,75 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+import type { ColumnRef } from "../tasks/match-column.js";
+import { findColumn } from "./find-column.js";
+
+export type MoveRequest = {
+ readonly column: string;
+ readonly before: string | undefined;
+ readonly after: string | undefined;
+};
+
+export type MovePlan<C> = {
+ readonly moved: C;
+ readonly anchor: C;
+ readonly placement: "before" | "after";
+ readonly order: ReadonlyArray<C>;
+ readonly changed: boolean;
+};
+
+export type Placement = {
+ readonly placement: "before" | "after";
+ readonly anchor: string;
+};
+
+export function parsePlacement(
+ request: Pick<MoveRequest, "before" | "after">,
+): Result.Result<Placement, InvalidArgument> {
+ if (request.before !== undefined && request.after === undefined) {
+ return Result.succeed({ placement: "before", anchor: request.before });
+ }
+ if (request.after !== undefined && request.before === undefined) {
+ return Result.succeed({ placement: "after", anchor: request.after });
+ }
+ return Result.fail(
+ new InvalidArgument({
+ message: "Say where the column goes.",
+ hint: "Pass exactly one of --before <column> or --after <column>.",
+ }),
+ );
+}
+
+export function planColumnMove<C extends ColumnRef & { readonly id: string }>(
+ columns: ReadonlyArray<C>,
+ request: MoveRequest,
+): Result.Result<MovePlan<C>, InvalidArgument> {
+ const parsed = parsePlacement(request);
+ if (Result.isFailure(parsed)) return Result.fail(parsed.failure);
+ const { placement, anchor: anchorReference } = parsed.success;
+ return Result.flatMap(findColumn(columns, request.column), (moved) =>
+ Result.flatMap(
+ findColumn(columns, anchorReference, `--${placement}`),
+ (anchor) => {
+ if (anchor.id === moved.id) {
+ return Result.fail(
+ new InvalidArgument({
+ message: `Cannot move ${moved.name} ${placement} itself.`,
+ hint: `Pick another column for --${placement}.`,
+ }),
+ );
+ }
+ const rest = columns.filter((column) => column.id !== moved.id);
+ const index = rest.findIndex((column) => column.id === anchor.id);
+ const at = placement === "before" ? index : index + 1;
+ const order = [...rest.slice(0, at), moved, ...rest.slice(at)];
+ return Result.succeed({
+ moved,
+ anchor,
+ placement,
+ order,
+ changed: order.some((column, i) => column.id !== columns[i]?.id),
+ });
+ },
+ ),
+ );
+}
diff --git a/packages/cli/src/columns/render-column-change.test.ts b/packages/cli/src/columns/render-column-change.test.ts
new file mode 100644
index 000000000..75305c06e
--- /dev/null
+++ b/packages/cli/src/columns/render-column-change.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { renderColumnChange } from "./render-column-change.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+describe("renderColumnChange", () => {
+ it("prints the column with its details", () => {
+ expect(
+ renderColumnChange(ui, {
+ verb: "Created",
+ column: { name: "QA", slug: "qa", isFinal: false },
+ details: ["qa", ""],
+ }),
+ ).toEqual(["", " ✓ Created ● QA · qa", ""]);
+ });
+
+ it("describes a delete that moved tasks", () => {
+ expect(
+ renderColumnChange(ui, {
+ verb: "Deleted",
+ column: { name: "QA", slug: "qa", isFinal: false },
+ details: ["moved 3 tasks to To Do"],
+ })[1],
+ ).toBe(" ✓ Deleted ● QA · moved 3 tasks to To Do");
+ });
+});
diff --git a/packages/cli/src/columns/render-column-change.ts b/packages/cli/src/columns/render-column-change.ts
new file mode 100644
index 000000000..b77b1e18b
--- /dev/null
+++ b/packages/cli/src/columns/render-column-change.ts
@@ -0,0 +1,30 @@
+import { renderCell, text } from "../render/cell.js";
+import { statusDot } from "../render/task-format.js";
+import type { Ui } from "../render/ui.js";
+
+export type ColumnChange = {
+ readonly verb: "Created" | "Updated" | "Moved" | "Deleted";
+ readonly column: {
+ readonly name: string;
+ readonly slug: string;
+ readonly isFinal: boolean;
+ };
+ readonly details: ReadonlyArray<string>;
+};
+
+export function renderColumnChange(ui: Ui, change: ColumnChange): string[] {
+ const { theme, glyphs } = ui;
+ const name = renderCell(
+ [
+ statusDot(ui, change.column.slug, change.column.isFinal),
+ text(` ${change.column.name}`, theme.strong),
+ ],
+ ui,
+ );
+ const separator = ` ${theme.muted(glyphs.separator)} `;
+ return [
+ "",
+ ` ${theme.success(glyphs.tick)} ${change.verb} ${[name, ...change.details.filter((detail) => detail !== "")].join(separator)}`,
+ "",
+ ];
+}
diff --git a/packages/cli/src/columns/render-column-list.test.ts b/packages/cli/src/columns/render-column-list.test.ts
new file mode 100644
index 000000000..8e6ee317b
--- /dev/null
+++ b/packages/cli/src/columns/render-column-list.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import type { ColumnJson } from "./column-json.js";
+import { renderColumnList } from "./render-column-list.js";
+
+const ui = (columns: number) =>
+ makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns,
+ });
+
+const column = (
+ position: number,
+ name: string,
+ slug: string,
+ taskCount: number | null,
+ isFinal = false,
+): ColumnJson => ({
+ id: `c${position}`,
+ projectId: "p_kan",
+ name,
+ slug,
+ position,
+ icon: null,
+ color: null,
+ isFinal,
+ taskCount,
+});
+
+const view = {
+ projectName: "Kaneo Web",
+ projectSlug: "kan",
+ projectUrl: "https://kaneo.test/p",
+ columns: [
+ column(0, "To Do", "to-do", 6),
+ column(1, "In Progress", "in-progress", 1),
+ column(5, "Done", "done", 0, true),
+ ],
+};
+
+describe("renderColumnList", () => {
+ it("numbers columns in board order at 80 columns", () => {
+ expect(renderColumnList(ui(80), view)).toEqual([
+ "",
+ " Kaneo Web · KAN",
+ "",
+ " 1 ● To Do to-do 6 tasks",
+ " 2 ● In Progress in-progress 1 task",
+ " 3 ● Done done final 0 tasks",
+ "",
+ ]);
+ });
+
+ it("drops the slug and count before the name in narrow terminals", () => {
+ const lines = renderColumnList(ui(24), view);
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(24);
+ expect(lines[3]).toBe(" 1 ● To Do");
+ });
+
+ it("leaves the count blank when it was not loaded", () => {
+ const [first] = renderColumnList(ui(80), {
+ ...view,
+ columns: [column(0, "To Do", "to-do", null)],
+ }).slice(3);
+ expect(first).toBe(" 1 ● To Do to-do");
+ });
+});
diff --git a/packages/cli/src/columns/render-column-list.ts b/packages/cli/src/columns/render-column-list.ts
new file mode 100644
index 000000000..d58665984
--- /dev/null
+++ b/packages/cli/src/columns/render-column-list.ts
@@ -0,0 +1,69 @@
+import { type Cell, renderCell, text } from "../render/cell.js";
+import { renderTable } from "../render/table.js";
+import { statusDot } from "../render/task-format.js";
+import type { Ui } from "../render/ui.js";
+import type { ColumnJson } from "./column-json.js";
+
+export type ColumnListView = {
+ readonly projectName: string;
+ readonly projectSlug: string;
+ readonly projectUrl: string;
+ readonly columns: ReadonlyArray<ColumnJson>;
+};
+
+function taskCount(count: number | null): string {
+ if (count === null) return "";
+ return `${count} ${count === 1 ? "task" : "tasks"}`;
+}
+
+export function renderColumnList(ui: Ui, view: ColumnListView): string[] {
+ const { theme, glyphs } = ui;
+ const header = ` ${renderCell([text(view.projectName, theme.strong, view.projectUrl)], ui)} ${theme.muted(`${glyphs.separator} ${view.projectSlug.toUpperCase()}`)}`;
+ if (view.columns.length === 0) {
+ return ["", header, "", ` ${theme.muted("No columns yet.")}`, ""];
+ }
+ const numbered = view.columns.map((column, index) => ({
+ column,
+ number: index + 1,
+ }));
+ const rows = renderTable(
+ ui,
+ numbered,
+ [
+ {
+ header: "#",
+ align: "right",
+ cell: ({ number }): Cell => [text(String(number), theme.muted)],
+ },
+ {
+ header: "Name",
+ flex: true,
+ minWidth: 10,
+ cell: ({ column }): Cell => [
+ statusDot(ui, column.slug, column.isFinal),
+ text(` ${column.name}`),
+ ],
+ },
+ {
+ header: "Slug",
+ optional: true,
+ cell: ({ column }): Cell => [text(column.slug, theme.muted)],
+ },
+ {
+ header: "Final",
+ cell: ({ column }): Cell =>
+ column.isFinal ? [text("final", theme.success)] : [],
+ },
+ {
+ header: "Tasks",
+ align: "right",
+ optional: true,
+ cell: ({ column }): Cell => [
+ text(taskCount(column.taskCount), theme.muted),
+ ],
+ },
+ ],
+ { width: ui.caps.columns, indent: 4 },
+ );
+ return ["", header, "", ...rows, ""];
+}
diff --git a/packages/cli/src/commands/api-layer.ts b/packages/cli/src/commands/api-layer.ts
new file mode 100644
index 000000000..7cdf8e5b2
--- /dev/null
+++ b/packages/cli/src/commands/api-layer.ts
@@ -0,0 +1,5 @@
+import { Layer } from "effect";
+import { KaneoApiLive } from "../api/kaneo-api.js";
+import { SessionLive } from "../services/session.js";
+
+export const ApiLayer = KaneoApiLive.pipe(Layer.provideMerge(SessionLive));
diff --git a/packages/cli/src/commands/api.ts b/packages/cli/src/commands/api.ts
new file mode 100644
index 000000000..b03b5428e
--- /dev/null
+++ b/packages/cli/src/commands/api.ts
@@ -0,0 +1,125 @@
+import { Effect, Option, Result, Schema } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { type HttpMethod, KaneoApi } from "../api/kaneo-api.js";
+import { InvalidArgument } from "../errors/errors.js";
+import { readTextInput } from "../input/read-text-input.js";
+import { emit } from "../output/emit.js";
+import { withSpinner } from "../output/spinner.js";
+import { normalizeApiPath } from "../passthrough/normalize-api-path.js";
+import { parseFields, parseQuery } from "../passthrough/parse-fields.js";
+import { renderJson } from "../passthrough/render-json.js";
+import { ApiLayer } from "./api-layer.js";
+
+const METHODS: ReadonlyArray<HttpMethod> = [
+ "GET",
+ "POST",
+ "PUT",
+ "PATCH",
+ "DELETE",
+];
+
+function toMethod(value: string): HttpMethod | undefined {
+ const upper = value.toUpperCase();
+ return METHODS.find((method) => method === upper);
+}
+
+const readBody = Effect.fn("api.body")(function* (
+ fields: ReadonlyArray<string>,
+ input: Option.Option<string>,
+) {
+ if (fields.length > 0 && Option.isSome(input)) {
+ return yield* new InvalidArgument({
+ message: "Pass either -f fields or --input, not both.",
+ });
+ }
+ if (fields.length > 0) {
+ const parsed = parseFields(fields);
+ if (Result.isFailure(parsed)) return yield* parsed.failure;
+ return parsed.success as unknown;
+ }
+ if (Option.isNone(input)) return undefined;
+ const text = yield* readTextInput(
+ input.value === "-"
+ ? { value: input, file: Option.none(), flag: "--input" }
+ : { value: Option.none(), file: input, flag: "--input" },
+ );
+ const raw = Option.getOrElse(text, () => "");
+ if (raw.trim() === "") return undefined;
+ return yield* Effect.try({
+ try: () => JSON.parse(raw) as unknown,
+ catch: () =>
+ new InvalidArgument({
+ message: `The --input body is not valid JSON.`,
+ hint: "Pass a JSON document, or build the body with -f key=value.",
+ }),
+ });
+});
+
+export const runApi = Effect.fn("command.api")(function* (options: {
+ readonly method: string;
+ readonly path: string;
+ readonly fields: ReadonlyArray<string>;
+ readonly input: Option.Option<string>;
+ readonly query: ReadonlyArray<string>;
+}) {
+ const method = toMethod(options.method);
+ if (!method) {
+ return yield* new InvalidArgument({
+ message: `${options.method} is not a supported HTTP method.`,
+ hint: `Use one of ${METHODS.join(", ")}, for example kaneo api GET /user/me.`,
+ });
+ }
+ const target = normalizeApiPath(options.path);
+ if (Result.isFailure(target)) return yield* target.failure;
+ const query = parseQuery(options.query);
+ if (Result.isFailure(query)) return yield* query.failure;
+ const body = yield* readBody(options.fields, options.input);
+ if (method === "GET" && body !== undefined) {
+ return yield* new InvalidArgument({
+ message: "GET requests cannot have a body.",
+ hint: "Pass query parameters with --query key=value instead.",
+ });
+ }
+
+ const api = yield* KaneoApi;
+ const response = yield* withSpinner(`${method} ${target.success.path}`)(
+ api.request(method, target.success.path, Schema.Unknown, {
+ query: { ...target.success.query, ...query.success },
+ body,
+ }),
+ );
+ yield* emit(response, renderJson);
+});
+
+export const apiCommand = Command.make(
+ "api",
+ {
+ method: Argument.String("method").pipe(
+ Argument.withDescription("HTTP method: GET, POST, PUT, PATCH or DELETE"),
+ ),
+ path: Argument.String("path").pipe(
+ Argument.withDescription(
+ "Path under /api, for example /task/assigned (the /api prefix is optional)",
+ ),
+ ),
+ fields: Flag.String("field").pipe(
+ Flag.withAlias("f"),
+ Flag.withDescription(
+ "Add key=value to the JSON body; values that parse as JSON keep their type, a.b=1 nests (repeatable)",
+ ),
+ Flag.atLeast(0),
+ ),
+ input: Flag.String("input").pipe(
+ Flag.withDescription("Read the JSON body from a file, or - for stdin"),
+ Flag.optional,
+ ),
+ query: Flag.String("query").pipe(
+ Flag.withDescription("Add a key=value query parameter (repeatable)"),
+ Flag.atLeast(0),
+ ),
+ },
+ (options) => runApi(options),
+).pipe(
+ Command.withDescription("Send an authenticated request to the Kaneo API"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/column/create.ts b/packages/cli/src/commands/column/create.ts
new file mode 100644
index 000000000..6ae49b910
--- /dev/null
+++ b/packages/cli/src/commands/column/create.ts
@@ -0,0 +1,109 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag, Prompt } from "effect/cli";
+import { createColumn } from "../../api/columns.js";
+import { toColumnJson } from "../../columns/column-json.js";
+import { parseColor } from "../../columns/parse-color.js";
+import { renderColumnChange } from "../../columns/render-column-change.js";
+import { Cancelled, InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import { promptTheme } from "../../prompts/prompt-theme.js";
+import {
+ resolveProject,
+ resolveWorkspaceId,
+} from "../../services/selection.js";
+import { ApiLayer } from "../api-layer.js";
+import { projectFlag } from "./project-flag.js";
+
+const askName = Effect.fnUntraced(function* (name: Option.Option<string>) {
+ const given = name.pipe(
+ Option.map((value) => value.trim()),
+ Option.filter((value) => value !== ""),
+ );
+ if (Option.isSome(given)) return given.value;
+ const output = yield* Output;
+ if (!output.interactive) {
+ return yield* new InvalidArgument({
+ message: "A column name is required.",
+ hint: 'Pass it as the first argument, for example kaneo column create "QA".',
+ });
+ }
+ return yield* Prompt.run(
+ Prompt.String({
+ message: "Column name",
+ validate: (value) =>
+ value.trim() === ""
+ ? Effect.fail("Enter a name")
+ : Effect.succeed(value.trim()),
+ theme: promptTheme(output.ui),
+ }),
+ ).pipe(Effect.catchTag("QuitError", () => Effect.fail(new Cancelled())));
+});
+
+export const runColumnCreate = Effect.fn("command.column.create")(
+ function* (options: {
+ readonly name: Option.Option<string>;
+ readonly project: Option.Option<string>;
+ readonly final: boolean;
+ readonly icon: Option.Option<string>;
+ readonly color: Option.Option<string>;
+ }) {
+ const color = Option.isSome(options.color)
+ ? yield* Effect.fromResult(parseColor(options.color.value))
+ : null;
+ const icon = Option.getOrUndefined(options.icon)?.trim();
+ const name = yield* askName(options.name);
+ const workspaceId = yield* resolveWorkspaceId();
+ const project = yield* resolveProject(workspaceId, options.project);
+ const created = yield* withSpinner(`Creating ${name}`)(
+ createColumn(project.id, {
+ name,
+ ...(icon ? { icon } : {}),
+ ...(color ? { color } : {}),
+ ...(options.final ? { isFinal: true } : {}),
+ }),
+ );
+
+ yield* emit(toColumnJson(created, 0), (ui) =>
+ renderColumnChange(ui, {
+ verb: "Created",
+ column: created,
+ details: [
+ created.slug,
+ created.isFinal ? "final" : "",
+ `in ${project.slug.toUpperCase()}`,
+ ],
+ }),
+ );
+ },
+);
+
+export const columnCreate = Command.make(
+ "create",
+ {
+ name: Argument.String("name").pipe(
+ Argument.withDescription("Column name; the slug is derived from it"),
+ Argument.optional,
+ ),
+ project: projectFlag,
+ final: Flag.Boolean("final").pipe(
+ Flag.withDescription(
+ "Mark it as a done column, which stops overdue reminders for its tasks",
+ ),
+ Flag.withDefault(false),
+ ),
+ icon: Flag.String("icon").pipe(
+ Flag.withDescription("Lucide icon name, for example CircleDot"),
+ Flag.optional,
+ ),
+ color: Flag.String("color").pipe(
+ Flag.withDescription("Hex color, for example #3b82f6"),
+ Flag.optional,
+ ),
+ },
+ (options) => runColumnCreate(options),
+).pipe(
+ Command.withDescription("Add a column to the end of a project's board"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/column/delete.ts b/packages/cli/src/commands/column/delete.ts
new file mode 100644
index 000000000..4da6b720a
--- /dev/null
+++ b/packages/cli/src/commands/column/delete.ts
@@ -0,0 +1,147 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import {
+ countColumnTasks,
+ deleteColumn,
+ listColumnTaskIds,
+} from "../../api/columns.js";
+import { updateTaskStatus } from "../../api/task-actions.js";
+import { findColumn } from "../../columns/find-column.js";
+import { renderColumnChange } from "../../columns/render-column-change.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import { confirmDestructive } from "../../prompts/confirm-destructive.js";
+import { pick } from "../../prompts/pick.js";
+import { ApiLayer } from "../api-layer.js";
+import { loadProjectColumns } from "./load-columns.js";
+import { projectFlag } from "./project-flag.js";
+
+const tasksLabel = (count: number) =>
+ `${count} ${count === 1 ? "task" : "tasks"}`;
+
+export const runColumnDelete = Effect.fn("command.column.delete")(
+ function* (options: {
+ readonly column: string;
+ readonly project: Option.Option<string>;
+ readonly moveTasksTo: Option.Option<string>;
+ readonly yes: boolean;
+ }) {
+ const output = yield* Output;
+ const { project, columns } = yield* loadProjectColumns(options.project);
+ const column = yield* Effect.fromResult(
+ findColumn(columns, options.column),
+ );
+ const others = columns.filter((candidate) => candidate.id !== column.id);
+ const requested = yield* Option.match(options.moveTasksTo, {
+ onNone: () => Effect.succeed(undefined),
+ onSome: (reference) =>
+ Effect.fromResult(
+ findColumn(columns, reference, "--move-tasks-to"),
+ ).pipe(
+ Effect.filterOrFail(
+ (target) => target.id !== column.id,
+ () =>
+ new InvalidArgument({
+ message: `--move-tasks-to points at ${column.name}, the column being deleted.`,
+ hint: "Pick another column.",
+ }),
+ ),
+ ),
+ });
+ const count = yield* withSpinner(`Counting tasks in ${column.name}`)(
+ countColumnTasks(project.id, column.slug),
+ );
+
+ const destination =
+ count === 0
+ ? undefined
+ : (requested ??
+ (output.interactive && others.length > 0
+ ? yield* pick(
+ `${column.name} holds ${tasksLabel(count)}. Move them to`,
+ others.map((candidate) => ({
+ title: candidate.name,
+ value: candidate,
+ description: candidate.slug,
+ })),
+ )
+ : yield* new InvalidArgument({
+ message: `${column.name} still holds ${tasksLabel(count)}, and the server only deletes empty columns.`,
+ hint: "Pass --move-tasks-to <column> to move them first.",
+ })));
+
+ yield* confirmDestructive({
+ yes: options.yes,
+ action: `Deleting column ${column.name}`,
+ question: destination
+ ? `Move ${tasksLabel(count)} to ${destination.name}, then delete ${column.name}?`
+ : `Delete column ${column.name}? This cannot be undone.`,
+ });
+
+ let moved = 0;
+ if (destination) {
+ const taskIds = yield* withSpinner(`Moving tasks to ${destination.name}`)(
+ listColumnTaskIds(project.id, column.slug).pipe(
+ Effect.tap((ids) =>
+ Effect.forEach(
+ ids,
+ (taskId) => updateTaskStatus(taskId, destination.slug),
+ { concurrency: 4, discard: true },
+ ),
+ ),
+ ),
+ );
+ moved = taskIds.length;
+ }
+ yield* withSpinner(`Deleting ${column.name}`)(deleteColumn(column.id));
+
+ yield* emit(
+ {
+ id: column.id,
+ projectId: column.projectId,
+ name: column.name,
+ slug: column.slug,
+ deleted: true,
+ movedTasks: moved,
+ movedTo: destination?.slug ?? null,
+ },
+ (ui) =>
+ renderColumnChange(ui, {
+ verb: "Deleted",
+ column,
+ details: destination
+ ? [`moved ${tasksLabel(moved)} to ${destination.name}`]
+ : [],
+ }),
+ );
+ },
+);
+
+export const columnDelete = Command.make(
+ "delete",
+ {
+ column: Argument.String("column").pipe(
+ Argument.withDescription("Column slug, name or id"),
+ ),
+ project: projectFlag,
+ moveTasksTo: Flag.String("move-tasks-to").pipe(
+ Flag.withDescription(
+ "Move the column's tasks to this column first (required when it holds tasks)",
+ ),
+ Flag.optional,
+ ),
+ yes: Flag.Boolean("yes").pipe(
+ Flag.withAlias("y"),
+ Flag.withDescription("Delete without asking for confirmation"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runColumnDelete(options),
+).pipe(
+ Command.withDescription(
+ "Delete a column, moving its tasks to another column first",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/column/edit.ts b/packages/cli/src/commands/column/edit.ts
new file mode 100644
index 000000000..a8874e203
--- /dev/null
+++ b/packages/cli/src/commands/column/edit.ts
@@ -0,0 +1,125 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import {
+ type ColumnDetail,
+ type UpdateColumnBody,
+ updateColumn,
+} from "../../api/columns.js";
+import { toColumnJson } from "../../columns/column-json.js";
+import { findColumn } from "../../columns/find-column.js";
+import { parseColor } from "../../columns/parse-color.js";
+import { renderColumnChange } from "../../columns/render-column-change.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { ApiLayer } from "../api-layer.js";
+import { loadProjectColumns } from "./load-columns.js";
+import { projectFlag } from "./project-flag.js";
+
+function describeChanges(
+ before: ColumnDetail,
+ body: UpdateColumnBody,
+): string[] {
+ const details: string[] = [];
+ if (body.name !== undefined && body.name !== before.name) {
+ details.push(`renamed from ${before.name}`);
+ }
+ if (body.isFinal !== undefined && body.isFinal !== before.isFinal) {
+ details.push(body.isFinal ? "now final" : "no longer final");
+ }
+ if (body.color !== undefined && body.color !== before.color) {
+ details.push(body.color === null ? "color cleared" : `color ${body.color}`);
+ }
+ if (body.icon !== undefined && body.icon !== before.icon) {
+ details.push(body.icon === null ? "icon cleared" : `icon ${body.icon}`);
+ }
+ return details.length > 0 ? details : ["no changes"];
+}
+
+export const runColumnEdit = Effect.fn("command.column.edit")(
+ function* (options: {
+ readonly column: string;
+ readonly project: Option.Option<string>;
+ readonly name: Option.Option<string>;
+ readonly final: Option.Option<boolean>;
+ readonly color: Option.Option<string>;
+ readonly icon: Option.Option<string>;
+ }) {
+ const name = Option.getOrUndefined(options.name)?.trim();
+ if (name === "") {
+ return yield* new InvalidArgument({
+ message: "--name cannot be empty.",
+ });
+ }
+ const color = Option.isSome(options.color)
+ ? yield* Effect.fromResult(parseColor(options.color.value))
+ : undefined;
+ const iconInput = Option.getOrUndefined(options.icon)?.trim();
+ const icon =
+ iconInput === undefined
+ ? undefined
+ : iconInput === "" || iconInput.toLowerCase() === "none"
+ ? null
+ : iconInput;
+ const body: UpdateColumnBody = {
+ ...(name === undefined ? {} : { name }),
+ ...(Option.isSome(options.final) ? { isFinal: options.final.value } : {}),
+ ...(color === undefined ? {} : { color }),
+ ...(icon === undefined ? {} : { icon }),
+ };
+ if (Object.keys(body).length === 0) {
+ return yield* new InvalidArgument({
+ message: "Nothing to change.",
+ hint: "Pass --name, --final or --no-final, --color, or --icon.",
+ });
+ }
+
+ const { columns } = yield* loadProjectColumns(options.project);
+ const column = yield* Effect.fromResult(
+ findColumn(columns, options.column),
+ );
+ const updated = yield* withSpinner(`Updating ${column.name}`)(
+ updateColumn(column.id, body),
+ );
+
+ yield* emit(toColumnJson(updated, null), (ui) =>
+ renderColumnChange(ui, {
+ verb: "Updated",
+ column: updated,
+ details: describeChanges(column, body),
+ }),
+ );
+ },
+);
+
+export const columnEdit = Command.make(
+ "edit",
+ {
+ column: Argument.String("column").pipe(
+ Argument.withDescription("Column slug, name or id"),
+ ),
+ project: projectFlag,
+ name: Flag.String("name").pipe(
+ Flag.withDescription("New name; the slug and its tasks stay the same"),
+ Flag.optional,
+ ),
+ final: Flag.Boolean("final").pipe(
+ Flag.withDescription("Mark as a done column (--no-final to unmark it)"),
+ Flag.optional,
+ ),
+ color: Flag.String("color").pipe(
+ Flag.withDescription("Hex color such as #3b82f6, or none to clear it"),
+ Flag.optional,
+ ),
+ icon: Flag.String("icon").pipe(
+ Flag.withDescription("Lucide icon name, or none to clear it"),
+ Flag.optional,
+ ),
+ },
+ (options) => runColumnEdit(options),
+).pipe(
+ Command.withDescription(
+ "Rename a column, or change its done state, color or icon",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/column/index.ts b/packages/cli/src/commands/column/index.ts
new file mode 100644
index 000000000..2ab7f76b1
--- /dev/null
+++ b/packages/cli/src/commands/column/index.ts
@@ -0,0 +1,17 @@
+import { Command } from "effect/cli";
+import { columnCreate } from "./create.js";
+import { columnDelete } from "./delete.js";
+import { columnEdit } from "./edit.js";
+import { columnList } from "./list.js";
+import { columnMove } from "./move.js";
+
+export const column = Command.make("column").pipe(
+ Command.withDescription("Manage a project's columns"),
+ Command.withSubcommands([
+ columnList,
+ columnCreate,
+ columnEdit,
+ columnMove,
+ columnDelete,
+ ]),
+);
diff --git a/packages/cli/src/commands/column/list.ts b/packages/cli/src/commands/column/list.ts
new file mode 100644
index 000000000..bfbc0f31f
--- /dev/null
+++ b/packages/cli/src/commands/column/list.ts
@@ -0,0 +1,48 @@
+import { Effect } from "effect";
+import { Command } from "effect/cli";
+import type { Option } from "effect";
+import { countColumnTasks } from "../../api/columns.js";
+import { toColumnJson } from "../../columns/column-json.js";
+import { renderColumnList } from "../../columns/render-column-list.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { projectUrl } from "../../render/links.js";
+import { Session } from "../../services/session.js";
+import { ApiLayer } from "../api-layer.js";
+import { loadProjectColumns } from "./load-columns.js";
+import { projectFlag } from "./project-flag.js";
+
+export const runColumnList = Effect.fn("command.column.list")(
+ function* (options: { readonly project: Option.Option<string> }) {
+ const session = yield* Session;
+ const { project, columns } = yield* loadProjectColumns(options.project);
+ const counts = yield* withSpinner("Counting tasks")(
+ Effect.forEach(
+ columns,
+ (column) => countColumnTasks(project.id, column.slug),
+ { concurrency: 4 },
+ ),
+ );
+ const json = columns.map((column, index) =>
+ toColumnJson(column, counts[index] ?? null),
+ );
+
+ yield* emit(json, (ui) =>
+ renderColumnList(ui, {
+ projectName: project.name,
+ projectSlug: project.slug,
+ projectUrl: projectUrl(session.webUrl, project),
+ columns: json,
+ }),
+ );
+ },
+);
+
+export const columnList = Command.make(
+ "list",
+ { project: projectFlag },
+ (options) => runColumnList(options),
+).pipe(
+ Command.withDescription("List a project's columns in board order"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/column/load-columns.ts b/packages/cli/src/commands/column/load-columns.ts
new file mode 100644
index 000000000..fdaa07353
--- /dev/null
+++ b/packages/cli/src/commands/column/load-columns.ts
@@ -0,0 +1,18 @@
+import { Effect, Option } from "effect";
+import { listColumnDetails } from "../../api/columns.js";
+import { withSpinner } from "../../output/spinner.js";
+import {
+ resolveProject,
+ resolveWorkspaceId,
+} from "../../services/selection.js";
+
+export const loadProjectColumns = Effect.fnUntraced(function* (
+ project: Option.Option<string>,
+) {
+ const workspaceId = yield* resolveWorkspaceId();
+ const resolved = yield* resolveProject(workspaceId, project);
+ const columns = yield* withSpinner(`Loading ${resolved.name} columns`)(
+ listColumnDetails(resolved.id),
+ );
+ return { project: resolved, columns };
+});
diff --git a/packages/cli/src/commands/column/move.ts b/packages/cli/src/commands/column/move.ts
new file mode 100644
index 000000000..99d4b6642
--- /dev/null
+++ b/packages/cli/src/commands/column/move.ts
@@ -0,0 +1,74 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { reorderColumns } from "../../api/columns.js";
+import { toColumnJson } from "../../columns/column-json.js";
+import {
+ parsePlacement,
+ planColumnMove,
+} from "../../columns/plan-column-move.js";
+import { renderColumnChange } from "../../columns/render-column-change.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { ApiLayer } from "../api-layer.js";
+import { loadProjectColumns } from "./load-columns.js";
+import { projectFlag } from "./project-flag.js";
+
+export const runColumnMove = Effect.fn("command.column.move")(
+ function* (options: {
+ readonly column: string;
+ readonly project: Option.Option<string>;
+ readonly before: Option.Option<string>;
+ readonly after: Option.Option<string>;
+ }) {
+ const request = {
+ column: options.column,
+ before: Option.getOrUndefined(options.before),
+ after: Option.getOrUndefined(options.after),
+ };
+ yield* Effect.fromResult(parsePlacement(request));
+ const { project, columns } = yield* loadProjectColumns(options.project);
+ const plan = yield* Effect.fromResult(planColumnMove(columns, request));
+ const ordered = plan.changed
+ ? yield* withSpinner(`Moving ${plan.moved.name}`)(
+ reorderColumns(
+ project.id,
+ plan.order.map((column, position) => ({ id: column.id, position })),
+ ),
+ )
+ : columns;
+
+ yield* emit(
+ ordered.map((column) => toColumnJson(column, null)),
+ (ui) =>
+ renderColumnChange(ui, {
+ verb: "Moved",
+ column: plan.moved,
+ details: [
+ `${plan.changed ? "" : "already "}${plan.placement} ${plan.anchor.name}`,
+ ],
+ }),
+ );
+ },
+);
+
+export const columnMove = Command.make(
+ "move",
+ {
+ column: Argument.String("column").pipe(
+ Argument.withDescription("Column slug, name or id"),
+ ),
+ project: projectFlag,
+ before: Flag.String("before").pipe(
+ Flag.withDescription("Put it just before this column"),
+ Flag.optional,
+ ),
+ after: Flag.String("after").pipe(
+ Flag.withDescription("Put it just after this column"),
+ Flag.optional,
+ ),
+ },
+ (options) => runColumnMove(options),
+).pipe(
+ Command.withDescription("Move a column before or after another one"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/column/project-flag.ts b/packages/cli/src/commands/column/project-flag.ts
new file mode 100644
index 000000000..23e68b757
--- /dev/null
+++ b/packages/cli/src/commands/column/project-flag.ts
@@ -0,0 +1,7 @@
+import { Flag } from "effect/cli";
+
+export const projectFlag = Flag.String("project").pipe(
+ Flag.withAlias("p"),
+ Flag.withDescription("Project key or id, for example KAN"),
+ Flag.optional,
+);
diff --git a/packages/cli/src/commands/comment/add.ts b/packages/cli/src/commands/comment/add.ts
new file mode 100644
index 000000000..af7273233
--- /dev/null
+++ b/packages/cli/src/commands/comment/add.ts
@@ -0,0 +1,50 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { readCommentInput } from "../../comments/read-comment-input.js";
+import { ApiLayer } from "../api-layer.js";
+import { runTaskComment } from "../task/comment.js";
+
+export const runCommentAdd = Effect.fn("command.comment.add")(
+ function* (options: {
+ readonly task: string;
+ readonly text: ReadonlyArray<string>;
+ readonly file: Option.Option<string>;
+ }) {
+ const content = yield* readCommentInput({
+ words: options.text,
+ file: options.file,
+ command: `kaneo comment add ${options.task}`,
+ });
+ yield* runTaskComment({
+ task: options.task,
+ text: Option.match(content, {
+ onNone: () => [],
+ onSome: (value) => [value],
+ }),
+ });
+ },
+);
+
+export const commentAdd = Command.make(
+ "add",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or the task id"),
+ ),
+ text: Argument.String("text").pipe(
+ Argument.withDescription(
+ "The comment in Markdown, or - for stdin; read from stdin when left out",
+ ),
+ Argument.variadic(),
+ ),
+ file: Flag.String("file").pipe(
+ Flag.withAlias("F"),
+ Flag.withDescription("Read the comment from a file, or - for stdin"),
+ Flag.optional,
+ ),
+ },
+ (options) => runCommentAdd(options),
+).pipe(
+ Command.withDescription("Add a comment to a task"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/comment/delete.ts b/packages/cli/src/commands/comment/delete.ts
new file mode 100644
index 000000000..b7336e8f6
--- /dev/null
+++ b/packages/cli/src/commands/comment/delete.ts
@@ -0,0 +1,64 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { deleteComment } from "../../api/comments.js";
+import { asOwnComment } from "../../comments/own-comment.js";
+import { renderCommentChange } from "../../comments/render-comment-change.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { confirmDestructive } from "../../prompts/confirm-destructive.js";
+import { resolveTask } from "../../tasks/resolve-task.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runCommentDelete = Effect.fn("command.comment.delete")(
+ function* (options: { readonly comment: string; readonly yes: boolean }) {
+ const id = options.comment.trim();
+ yield* confirmDestructive({
+ yes: options.yes,
+ action: "Deleting a comment",
+ question: `Delete comment ${id}? This cannot be undone.`,
+ });
+
+ const deleted = yield* withSpinner("Deleting the comment")(
+ deleteComment(id).pipe(asOwnComment(id)),
+ );
+ const task = yield* resolveTask(deleted.taskId).pipe(Effect.option);
+ const resolved = Option.getOrUndefined(task);
+ const label = resolved
+ ? (resolved.ticketId ?? resolved.task.id.slice(0, 8))
+ : deleted.taskId.slice(0, 8);
+
+ yield* emit(
+ {
+ id: deleted.id,
+ taskId: deleted.taskId,
+ ticketId: resolved?.ticketId ?? null,
+ deleted: true,
+ },
+ (ui) =>
+ renderCommentChange(ui, {
+ verb: "Deleted",
+ label,
+ url: resolved?.url ?? "",
+ content: deleted.content ?? "",
+ }),
+ );
+ },
+);
+
+export const commentDelete = Command.make(
+ "delete",
+ {
+ comment: Argument.String("comment-id").pipe(
+ Argument.withDescription("The comment id, from kaneo comment list"),
+ ),
+ yes: Flag.Boolean("yes").pipe(
+ Flag.withAlias("y"),
+ Flag.withDescription("Delete without asking for confirmation"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runCommentDelete(options),
+).pipe(
+ Command.withDescription("Delete one of your comments"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/comment/edit.ts b/packages/cli/src/commands/comment/edit.ts
new file mode 100644
index 000000000..6b04b4c98
--- /dev/null
+++ b/packages/cli/src/commands/comment/edit.ts
@@ -0,0 +1,97 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { updateComment } from "../../api/comments.js";
+import { COMMENT_MAX_LENGTH } from "../../api/task-actions.js";
+import { asOwnComment } from "../../comments/own-comment.js";
+import { readCommentText } from "../../comments/read-comment-input.js";
+import { renderCommentChange } from "../../comments/render-comment-change.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { normalizeComment } from "../../tasks/comment-text.js";
+import { resolveTask } from "../../tasks/resolve-task.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runCommentEdit = Effect.fn("command.comment.edit")(
+ function* (options: {
+ readonly comment: string;
+ readonly text: ReadonlyArray<string>;
+ readonly file: Option.Option<string>;
+ }) {
+ const id = options.comment.trim();
+ const command = `kaneo comment edit ${id}`;
+ const content = normalizeComment(
+ yield* readCommentText({
+ words: options.text,
+ file: options.file,
+ command,
+ prompt: "New text for the comment",
+ }),
+ );
+ if (content === "") {
+ return yield* new InvalidArgument({
+ message: "The comment is empty.",
+ hint: `To remove it, run kaneo comment delete ${id}.`,
+ });
+ }
+ if (content.length > COMMENT_MAX_LENGTH) {
+ return yield* new InvalidArgument({
+ message: `The comment is ${content.length} characters long, and the limit is ${COMMENT_MAX_LENGTH}.`,
+ });
+ }
+
+ const updated = yield* withSpinner("Saving the comment")(
+ updateComment(id, content).pipe(asOwnComment(id)),
+ );
+ const task = yield* resolveTask(updated.taskId).pipe(Effect.option);
+ const label = Option.match(task, {
+ onNone: () => updated.taskId.slice(0, 8),
+ onSome: (resolved) => resolved.ticketId ?? resolved.task.id.slice(0, 8),
+ });
+ const url = Option.getOrUndefined(task)?.url ?? null;
+
+ yield* emit(
+ {
+ id: updated.id,
+ taskId: updated.taskId,
+ ticketId: Option.getOrUndefined(task)?.ticketId ?? null,
+ content: updated.content ?? content,
+ createdAt: updated.createdAt,
+ updatedAt: updated.updatedAt,
+ edited: true,
+ url,
+ },
+ (ui, value) =>
+ renderCommentChange(ui, {
+ verb: "Edited",
+ label,
+ url: value.url ?? "",
+ content: value.content,
+ }),
+ );
+ },
+);
+
+export const commentEdit = Command.make(
+ "edit",
+ {
+ comment: Argument.String("comment-id").pipe(
+ Argument.withDescription("The comment id, from kaneo comment list"),
+ ),
+ text: Argument.String("text").pipe(
+ Argument.withDescription(
+ "The new text in Markdown, or - for stdin; asked for when left out",
+ ),
+ Argument.variadic(),
+ ),
+ file: Flag.String("file").pipe(
+ Flag.withAlias("F"),
+ Flag.withDescription("Read the new text from a file, or - for stdin"),
+ Flag.optional,
+ ),
+ },
+ (options) => runCommentEdit(options),
+).pipe(
+ Command.withDescription("Change the text of one of your comments"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/comment/index.ts b/packages/cli/src/commands/comment/index.ts
new file mode 100644
index 000000000..186ce416a
--- /dev/null
+++ b/packages/cli/src/commands/comment/index.ts
@@ -0,0 +1,15 @@
+import { Command } from "effect/cli";
+import { commentAdd } from "./add.js";
+import { commentDelete } from "./delete.js";
+import { commentEdit } from "./edit.js";
+import { commentList } from "./list.js";
+
+export const comment = Command.make("comment").pipe(
+ Command.withDescription("Read and manage task comments"),
+ Command.withSubcommands([
+ commentList,
+ commentAdd,
+ commentEdit,
+ commentDelete,
+ ]),
+);
diff --git a/packages/cli/src/commands/comment/list.ts b/packages/cli/src/commands/comment/list.ts
new file mode 100644
index 000000000..9cb65b0b9
--- /dev/null
+++ b/packages/cli/src/commands/comment/list.ts
@@ -0,0 +1,59 @@
+import { Effect } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { listComments } from "../../api/comments.js";
+import { latest, toCommentJson } from "../../comments/comment-json.js";
+import { renderCommentList } from "../../comments/render-comment-list.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { resolveTask } from "../../tasks/resolve-task.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runCommentList = Effect.fn("command.comment.list")(
+ function* (options: { readonly task: string; readonly limit: number }) {
+ if (options.limit < 1) {
+ return yield* new InvalidArgument({
+ message: "--limit must be at least 1.",
+ });
+ }
+ const { resolved, comments } = yield* withSpinner(
+ `Loading comments on ${options.task}`,
+ )(
+ Effect.gen(function* () {
+ const resolved = yield* resolveTask(options.task);
+ const comments = yield* listComments(resolved.task.id);
+ return { resolved, comments };
+ }),
+ );
+ const shown = latest(comments, options.limit).map(toCommentJson);
+
+ yield* emit(shown, (ui, value) =>
+ renderCommentList(ui, {
+ label: resolved.ticketId ?? resolved.task.id.slice(0, 8),
+ title: resolved.task.title,
+ url: resolved.url,
+ comments: value,
+ total: comments.length,
+ now: new Date(),
+ }),
+ );
+ },
+);
+
+export const commentList = Command.make(
+ "list",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or the task id"),
+ ),
+ limit: Flag.Int("limit").pipe(
+ Flag.withAlias("L"),
+ Flag.withDescription("Show only the latest comments, up to this many"),
+ Flag.withDefault(50),
+ ),
+ },
+ (options) => runCommentList(options),
+).pipe(
+ Command.withDescription("Show the comments on a task, oldest first"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/context.ts b/packages/cli/src/commands/context.ts
new file mode 100644
index 000000000..84dc29c48
--- /dev/null
+++ b/packages/cli/src/commands/context.ts
@@ -0,0 +1,143 @@
+import { existsSync } from "node:fs";
+import { Effect, Option, Result } from "effect";
+import { Command } from "effect/cli";
+import {
+ getCurrentUser,
+ getWorkspace,
+ listProjects,
+} from "../api/endpoints.js";
+import {
+ ApiUrlFlag,
+ HumanFlag,
+ JqFlag,
+ JsonFlag,
+ ProfileFlag,
+ TokenFlag,
+ WorkspaceFlag,
+} from "../cli/global-flags.js";
+import { ConfigStore } from "../config/config-store.js";
+import type { ConfigStatus, ContextReport } from "../context/context-report.js";
+import { outputProvenance } from "../context/output-provenance.js";
+import { buildProvenance } from "../context/provenance.js";
+import { renderContext } from "../context/render-context.js";
+import { describeError } from "../errors/describe.js";
+import { emit } from "../output/emit.js";
+import { Output } from "../output/output.js";
+import { withSpinner } from "../output/spinner.js";
+import { CliEnvironment } from "../services/cli-environment.js";
+import { matchProject } from "../services/selection.js";
+import { Session } from "../services/session.js";
+import { ApiLayer } from "./api-layer.js";
+
+const loadDetails = Effect.fn("context.details")(function* (
+ workspaceId: string | null,
+ projectRef: string | null,
+) {
+ const [user, workspace, projects] = yield* Effect.all(
+ [
+ Effect.result(getCurrentUser()),
+ workspaceId
+ ? Effect.option(getWorkspace(workspaceId))
+ : Effect.succeedNone,
+ workspaceId && projectRef
+ ? Effect.option(listProjects(workspaceId))
+ : Effect.succeedNone,
+ ],
+ { concurrency: 3 },
+ );
+ const project = Option.flatMap(projects, (list) =>
+ Option.fromUndefinedOr(
+ projectRef ? matchProject(list, projectRef) : undefined,
+ ),
+ );
+ return {
+ user: Result.isSuccess(user)
+ ? {
+ id: user.success.id,
+ name: user.success.name,
+ email: user.success.email,
+ }
+ : null,
+ error: Result.isFailure(user) ? describeError(user.failure).message : null,
+ workspaceName: Option.getOrNull(
+ Option.map(workspace, (value) => value.name),
+ ),
+ project: Option.getOrNull(project),
+ };
+});
+
+export const runContext = Effect.fn("command.context")(function* () {
+ const session = yield* Session;
+ const output = yield* Output;
+ const environment = yield* CliEnvironment;
+ const store = yield* ConfigStore;
+
+ const provenance = buildProvenance({
+ flags: {
+ token: yield* TokenFlag,
+ apiUrl: yield* ApiUrlFlag,
+ workspace: yield* WorkspaceFlag,
+ profile: yield* ProfileFlag,
+ },
+ env: environment.env,
+ config: session.config,
+ configProblem: session.configProblem,
+ repo: session.repo,
+ });
+ const configStatus: ConfigStatus = Option.isSome(session.configProblem)
+ ? session.configProblem.value.reason
+ : existsSync(store.path)
+ ? "ok"
+ : "missing";
+ const mode = outputProvenance({
+ json: yield* JsonFlag,
+ human: yield* HumanFlag,
+ env: environment.env,
+ stdoutIsTTY: environment.stdout.isTTY,
+ });
+ const jq = Option.flatten(yield* Effect.serviceOption(JqFlag));
+
+ const details = Option.isSome(session.credentials)
+ ? yield* withSpinner("Checking your account")(
+ loadDetails(provenance.workspace.id, provenance.project.ref),
+ )
+ : { user: null, error: null, workspaceName: null, project: null };
+
+ yield* emit<ContextReport>(
+ {
+ server: provenance.server,
+ web: provenance.web,
+ profile: provenance.profile,
+ auth: { ...provenance.auth, error: details.error },
+ user: details.user,
+ workspace: { ...provenance.workspace, name: details.workspaceName },
+ project: {
+ ...provenance.project,
+ id: details.project?.id ?? null,
+ key: details.project ? details.project.slug.toUpperCase() : null,
+ name: details.project?.name ?? null,
+ },
+ config: { path: store.path, status: configStatus },
+ output: {
+ mode: output.mode,
+ source: mode.source,
+ jq: Option.getOrNull(Option.map(jq, (filter) => filter.expression)),
+ interactive: output.interactive,
+ stdinIsTTY: environment.stdin.isTTY,
+ stdoutIsTTY: environment.stdout.isTTY,
+ stderrIsTTY: environment.stderr.isTTY,
+ terminal: output.ui.caps,
+ },
+ },
+ renderContext,
+ );
+});
+
+export const contextCommand = Command.make("context", {}, () =>
+ runContext(),
+).pipe(
+ Command.withDescription(
+ "Show the server, account, workspace and project in use, and where each came from",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/doctor.ts b/packages/cli/src/commands/doctor.ts
new file mode 100644
index 000000000..c61bbda37
--- /dev/null
+++ b/packages/cli/src/commands/doctor.ts
@@ -0,0 +1,224 @@
+import { existsSync } from "node:fs";
+import { Effect, Option } from "effect";
+import { Command } from "effect/cli";
+import { FetchHttpClient } from "effect/http";
+import { getCurrentUser, getWorkspace } from "../api/endpoints.js";
+import { ConfigStore } from "../config/config-store.js";
+import { missingOperations } from "../doctor/compare-operations.js";
+import type { DoctorCheck } from "../doctor/doctor-check.js";
+import { fetchPublic } from "../doctor/fetch-public.js";
+import { renderDoctor } from "../doctor/render-doctor.js";
+import { REQUIRED_OPERATIONS } from "../doctor/required-operations.js";
+import { describeError } from "../errors/describe.js";
+import { emit } from "../output/emit.js";
+import { withSpinner } from "../output/spinner.js";
+import { Session, type SessionShape } from "../services/session.js";
+import { ApiLayer } from "./api-layer.js";
+
+function host(url: string): string {
+ try {
+ return new URL(url).host;
+ } catch {
+ return url;
+ }
+}
+
+const AUTH_LABELS = {
+ flag: "--token",
+ env: "KANEO_API_KEY",
+ profile: "stored login",
+} as const;
+
+const WORKSPACE_SOURCES = {
+ flag: "-w",
+ env: "KANEO_WORKSPACE",
+} as const;
+
+function skipped(name: DoctorCheck["name"], reason: string): DoctorCheck {
+ return { name, ok: false, detail: `Skipped because ${reason}` };
+}
+
+function checkConfig(session: SessionShape, path: string): DoctorCheck {
+ if (Option.isSome(session.configProblem)) {
+ return {
+ name: "config",
+ ok: false,
+ detail: describeError(session.configProblem.value).message,
+ };
+ }
+ return {
+ name: "config",
+ ok: true,
+ detail: existsSync(path) ? path : `${path} (not created yet)`,
+ };
+}
+
+const checkServer = Effect.fn("doctor.server")(function* (apiUrl: string) {
+ const response = yield* Effect.result(fetchPublic(`${apiUrl}/api/health`));
+ if (response._tag === "Failure") {
+ return {
+ name: "server",
+ ok: false,
+ detail: `Could not reach ${host(apiUrl)} (${response.failure})`,
+ } satisfies DoctorCheck;
+ }
+ const { status, milliseconds } = response.success;
+ return {
+ name: "server",
+ ok: status >= 200 && status < 300,
+ detail:
+ status >= 200 && status < 300
+ ? `${host(apiUrl)} responded in ${milliseconds} ms`
+ : `${host(apiUrl)} answered ${status} on /api/health`,
+ } satisfies DoctorCheck;
+});
+
+const checkLogin = Effect.fn("doctor.login")(function* (session: SessionShape) {
+ const credentials = Option.getOrUndefined(session.credentials);
+ if (!credentials) {
+ return {
+ name: "login",
+ ok: false,
+ detail: "Not signed in. Run kaneo login, or set KANEO_API_KEY.",
+ } satisfies DoctorCheck;
+ }
+ const user = yield* Effect.result(getCurrentUser());
+ if (user._tag === "Failure") {
+ return {
+ name: "login",
+ ok: false,
+ detail: describeError(user.failure).message,
+ } satisfies DoctorCheck;
+ }
+ return {
+ name: "login",
+ ok: true,
+ detail: `${user.success.name} (${user.success.email}) with ${AUTH_LABELS[credentials.source]}`,
+ } satisfies DoctorCheck;
+});
+
+const checkWorkspace = Effect.fn("doctor.workspace")(function* (
+ session: SessionShape,
+) {
+ const selected = Option.getOrUndefined(session.workspace);
+ if (!selected) {
+ return {
+ name: "workspace",
+ ok: true,
+ detail: "None selected. Commands ask for one, or pass -w.",
+ } satisfies DoctorCheck;
+ }
+ const source =
+ selected.source === "repo"
+ ? (session.repo?.path ?? ".kaneo.json")
+ : selected.source === "profile"
+ ? `profile ${session.profileName}`
+ : WORKSPACE_SOURCES[selected.source];
+ const workspace = yield* Effect.result(getWorkspace(selected.id));
+ if (workspace._tag === "Failure") {
+ return {
+ name: "workspace",
+ ok: false,
+ detail:
+ workspace.failure._tag === "NotFound"
+ ? `${selected.id} (from ${source}) was not found, or you are not a member`
+ : describeError(workspace.failure).message,
+ } satisfies DoctorCheck;
+ }
+ return {
+ name: "workspace",
+ ok: true,
+ detail: `${workspace.success.name} (from ${source})`,
+ } satisfies DoctorCheck;
+});
+
+const checkCompatibility = Effect.fn("doctor.compatibility")(function* (
+ apiUrl: string,
+) {
+ const response = yield* Effect.result(fetchPublic(`${apiUrl}/api/openapi`));
+ if (response._tag === "Failure") {
+ return {
+ name: "compatibility",
+ ok: false,
+ detail: `Could not load /api/openapi (${response.failure})`,
+ } satisfies DoctorCheck;
+ }
+ const missing =
+ response.success.status >= 200 && response.success.status < 300
+ ? missingOperations(REQUIRED_OPERATIONS, response.success.body)
+ : undefined;
+ if (!missing) {
+ return {
+ name: "compatibility",
+ ok: false,
+ detail:
+ "The server does not publish /api/openapi, so it is probably older than this CLI. Update the server.",
+ } satisfies DoctorCheck;
+ }
+ const total = REQUIRED_OPERATIONS.length;
+ if (missing.length === 0) {
+ return {
+ name: "compatibility",
+ ok: true,
+ detail: `All ${total} operations the CLI uses are available`,
+ } satisfies DoctorCheck;
+ }
+ const listed = missing.map(
+ (operation) => `${operation.method} ${operation.path}`,
+ );
+ return {
+ name: "compatibility",
+ ok: false,
+ detail: `Missing ${missing.length} of ${total} operations. Update the server.`,
+ missing: listed,
+ } satisfies DoctorCheck;
+});
+
+export const runDoctor = Effect.fn("command.doctor")(function* () {
+ const session = yield* Session;
+ const store = yield* ConfigStore;
+
+ const config = checkConfig(session, store.path);
+ const server = yield* withSpinner(`Checking ${host(session.apiUrl)}`)(
+ checkServer(session.apiUrl),
+ );
+ const [login, compatibility] = yield* withSpinner("Checking your account")(
+ Effect.all(
+ server.ok
+ ? [checkLogin(session), checkCompatibility(session.apiUrl)]
+ : [
+ Effect.succeed(skipped("login", "the server is unreachable")),
+ Effect.succeed(
+ skipped("compatibility", "the server is unreachable"),
+ ),
+ ],
+ { concurrency: 2 },
+ ),
+ );
+ const workspace = login.ok
+ ? yield* withSpinner("Checking the workspace")(checkWorkspace(session))
+ : skipped(
+ "workspace",
+ server.ok ? "you are not signed in" : "the server is unreachable",
+ );
+
+ const checks: ReadonlyArray<DoctorCheck> = [
+ config,
+ server,
+ login,
+ workspace,
+ compatibility,
+ ];
+ yield* emit({ checks }, renderDoctor);
+
+ if (checks.some((check) => !check.ok)) {
+ yield* Effect.sync(() => {
+ process.exitCode = 1;
+ });
+ }
+}, Effect.provide(FetchHttpClient.layer));
+
+export const doctorCommand = Command.make("doctor", {}, () => runDoctor()).pipe(
+ Command.withDescription("Check the server, your login and API compatibility"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/field/create.ts b/packages/cli/src/commands/field/create.ts
new file mode 100644
index 000000000..36d020682
--- /dev/null
+++ b/packages/cli/src/commands/field/create.ts
@@ -0,0 +1,150 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag, Prompt } from "effect/cli";
+import {
+ createCustomField,
+ listCustomFields,
+} from "../../api/custom-fields.js";
+import { Cancelled, InvalidArgument } from "../../errors/errors.js";
+import { toFieldJson } from "../../fields/field-json.js";
+import {
+ checkFieldOptions,
+ FIELD_TYPE_LABELS,
+ FIELD_TYPES,
+ parseFieldType,
+} from "../../fields/field-types.js";
+import { renderFieldChange } from "../../fields/render-field-change.js";
+import { emit } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import { pick } from "../../prompts/pick.js";
+import { promptTheme } from "../../prompts/prompt-theme.js";
+import {
+ resolveProject,
+ resolveWorkspaceId,
+} from "../../services/selection.js";
+import { ApiLayer } from "../api-layer.js";
+
+const resolveName = Effect.fnUntraced(function* (name: Option.Option<string>) {
+ const output = yield* Output;
+ const given = name.pipe(
+ Option.map((value) => value.trim()),
+ Option.filter((value) => value !== ""),
+ );
+ if (Option.isSome(given)) return given.value;
+ if (output.interactive) {
+ return yield* Prompt.run(
+ Prompt.String({
+ message: "Field name",
+ validate: (value) =>
+ value.trim() === ""
+ ? Effect.fail("Enter a name")
+ : Effect.succeed(value.trim()),
+ theme: promptTheme(output.ui),
+ }),
+ ).pipe(Effect.catchTag("QuitError", () => Effect.fail(new Cancelled())));
+ }
+ return yield* new InvalidArgument({
+ message: "A field name is required.",
+ hint: 'Pass it as the first argument, for example kaneo field create "Story points" --type number.',
+ });
+});
+
+const resolveType = Effect.fnUntraced(function* (type: Option.Option<string>) {
+ const output = yield* Output;
+ if (Option.isSome(type)) {
+ return yield* Effect.fromResult(parseFieldType(type.value));
+ }
+ if (output.interactive) {
+ return yield* pick(
+ "Field type",
+ FIELD_TYPES.map((value) => ({
+ title: FIELD_TYPE_LABELS[value],
+ value,
+ description: value,
+ })),
+ );
+ }
+ return yield* new InvalidArgument({
+ message: "A field type is required.",
+ hint: `Pass --type with one of: ${FIELD_TYPES.join(", ")}.`,
+ });
+});
+
+export const runFieldCreate = Effect.fn("command.field.create")(
+ function* (options: {
+ readonly name: Option.Option<string>;
+ readonly type: Option.Option<string>;
+ readonly options: ReadonlyArray<string>;
+ readonly project: Option.Option<string>;
+ }) {
+ const name = yield* resolveName(options.name);
+ const type = yield* resolveType(options.type);
+ const choices = yield* Effect.fromResult(
+ checkFieldOptions(type, options.options),
+ );
+ const workspaceId = yield* resolveWorkspaceId();
+ const project = yield* resolveProject(workspaceId, options.project);
+ const existing = (yield* withSpinner("Loading fields")(
+ listCustomFields(project.id),
+ )).map(toFieldJson);
+ const clash = existing.find(
+ (field) => field.name.toLowerCase() === name.toLowerCase(),
+ );
+ if (clash) {
+ return yield* new InvalidArgument({
+ message: `${project.name} already has a field named ${clash.name}.`,
+ hint: "Choose another name. Fields cannot be renamed, so delete the old one first if you want to replace it.",
+ });
+ }
+ const created = yield* withSpinner(`Creating ${name}`)(
+ createCustomField({
+ projectId: project.id,
+ name,
+ type,
+ ...(choices ? { options: choices } : {}),
+ }),
+ );
+ yield* emit(toFieldJson(created), (ui, field) =>
+ renderFieldChange(ui, {
+ verb: "Created",
+ name: field.name,
+ type: field.type,
+ }),
+ );
+ },
+);
+
+export const fieldCreate = Command.make(
+ "create",
+ {
+ name: Argument.String("name").pipe(
+ Argument.withDescription(
+ "Field name; asked for when omitted in a terminal",
+ ),
+ Argument.optional,
+ ),
+ type: Flag.String("type").pipe(
+ Flag.withAlias("t"),
+ Flag.withDescription(
+ "text, number, date, dropdown (or select), multiselect, or boolean",
+ ),
+ Flag.optional,
+ ),
+ options: Flag.String("option").pipe(
+ Flag.withAlias("o"),
+ Flag.withDescription(
+ "A choice for dropdown and multiselect fields; repeat for each choice",
+ ),
+ Flag.atLeast(0),
+ ),
+ project: Flag.String("project").pipe(
+ Flag.withAlias("p"),
+ Flag.withDescription("Project key or id, for example KAN"),
+ Flag.optional,
+ ),
+ },
+ (options) => runFieldCreate(options),
+).pipe(
+ Command.withDescription("Add a custom field to a project"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/field/delete.ts b/packages/cli/src/commands/field/delete.ts
new file mode 100644
index 000000000..644dc8482
--- /dev/null
+++ b/packages/cli/src/commands/field/delete.ts
@@ -0,0 +1,77 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import {
+ deleteCustomField,
+ listCustomFields,
+} from "../../api/custom-fields.js";
+import { chooseField } from "../../fields/choose-field.js";
+import { toFieldJson } from "../../fields/field-json.js";
+import { renderFieldChange } from "../../fields/render-field-change.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { confirmDestructive } from "../../prompts/confirm-destructive.js";
+import {
+ resolveProject,
+ resolveWorkspaceId,
+} from "../../services/selection.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runFieldDelete = Effect.fn("command.field.delete")(
+ function* (options: {
+ readonly field: Option.Option<string>;
+ readonly project: Option.Option<string>;
+ readonly yes: boolean;
+ }) {
+ const workspaceId = yield* resolveWorkspaceId();
+ const project = yield* resolveProject(workspaceId, options.project);
+ const fields = (yield* withSpinner("Loading fields")(
+ listCustomFields(project.id),
+ )).map(toFieldJson);
+ const field = yield* chooseField(fields, options.field, {
+ projectName: project.name,
+ question: "Delete which field?",
+ example: 'kaneo field delete "Story points"',
+ });
+
+ yield* confirmDestructive({
+ yes: options.yes,
+ action: `Deleting the field ${field.name}`,
+ question: `Delete the field ${field.name} from ${project.name}? Its values on every task are deleted too. This cannot be undone.`,
+ });
+
+ yield* withSpinner(`Deleting ${field.name}`)(deleteCustomField(field.id));
+ yield* emit({ id: field.id, name: field.name, deleted: true }, (ui) =>
+ renderFieldChange(ui, {
+ verb: "Deleted",
+ name: field.name,
+ type: field.type,
+ }),
+ );
+ },
+);
+
+export const fieldDelete = Command.make(
+ "delete",
+ {
+ field: Argument.String("field").pipe(
+ Argument.withDescription(
+ "Field name or id; asked for when omitted in a terminal",
+ ),
+ Argument.optional,
+ ),
+ project: Flag.String("project").pipe(
+ Flag.withAlias("p"),
+ Flag.withDescription("Project key or id, for example KAN"),
+ Flag.optional,
+ ),
+ yes: Flag.Boolean("yes").pipe(
+ Flag.withAlias("y"),
+ Flag.withDescription("Delete without asking for confirmation"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runFieldDelete(options),
+).pipe(
+ Command.withDescription("Delete a custom field and its values on every task"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/field/index.ts b/packages/cli/src/commands/field/index.ts
new file mode 100644
index 000000000..8d435cd01
--- /dev/null
+++ b/packages/cli/src/commands/field/index.ts
@@ -0,0 +1,9 @@
+import { Command } from "effect/cli";
+import { fieldCreate } from "./create.js";
+import { fieldDelete } from "./delete.js";
+import { fieldList } from "./list.js";
+
+export const field = Command.make("field").pipe(
+ Command.withDescription("Manage the custom fields of a project"),
+ Command.withSubcommands([fieldList, fieldCreate, fieldDelete]),
+);
diff --git a/packages/cli/src/commands/field/list.ts b/packages/cli/src/commands/field/list.ts
new file mode 100644
index 000000000..9e98cfe7d
--- /dev/null
+++ b/packages/cli/src/commands/field/list.ts
@@ -0,0 +1,40 @@
+import { Effect, Option } from "effect";
+import { Command, Flag } from "effect/cli";
+import { listCustomFields } from "../../api/custom-fields.js";
+import { toFieldJson } from "../../fields/field-json.js";
+import { renderFieldList } from "../../fields/render-field-list.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import {
+ resolveProject,
+ resolveWorkspaceId,
+} from "../../services/selection.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runFieldList = Effect.fn("command.field.list")(
+ function* (options: { readonly project: Option.Option<string> }) {
+ const workspaceId = yield* resolveWorkspaceId();
+ const project = yield* resolveProject(workspaceId, options.project);
+ const fields = yield* withSpinner("Loading fields")(
+ listCustomFields(project.id),
+ );
+ yield* emit(fields.map(toFieldJson), (ui, value) =>
+ renderFieldList(ui, { projectName: project.name, fields: value }),
+ );
+ },
+);
+
+export const fieldList = Command.make(
+ "list",
+ {
+ project: Flag.String("project").pipe(
+ Flag.withAlias("p"),
+ Flag.withDescription("Project key or id, for example KAN"),
+ Flag.optional,
+ ),
+ },
+ (options) => runFieldList(options),
+).pipe(
+ Command.withDescription("List the custom fields of a project"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/home.ts b/packages/cli/src/commands/home.ts
new file mode 100644
index 000000000..70ba78bf2
--- /dev/null
+++ b/packages/cli/src/commands/home.ts
@@ -0,0 +1,157 @@
+import { Effect, Option } from "effect";
+import {
+ getCurrentUser,
+ getWorkspace,
+ listAssignedTasks,
+} from "../api/endpoints.js";
+import type { AssignedTask, CurrentUser, Workspace } from "../api/schemas.js";
+import { emit } from "../output/emit.js";
+import { withSpinner } from "../output/spinner.js";
+import { type Cell, text } from "../render/cell.js";
+import { logo } from "../render/logo.js";
+import { renderTable } from "../render/table.js";
+import { dueSegments, prioritySegments } from "../render/task-format.js";
+import type { Ui } from "../render/ui.js";
+import { Session } from "../services/session.js";
+
+type HomeResult = {
+ readonly signedIn: boolean;
+ readonly apiUrl: string;
+ readonly user: CurrentUser | null;
+ readonly workspace: Workspace | null;
+ readonly tasks: ReadonlyArray<AssignedTask>;
+ readonly totalTasks: number;
+};
+
+const COMMANDS: ReadonlyArray<readonly [string, string]> = [
+ ["kaneo task list", "List tasks in a project"],
+ ["kaneo whoami", "Show your account and server"],
+ ["kaneo login", "Sign in with your browser"],
+ ["kaneo --help", "See every command"],
+];
+
+export function renderHome(
+ ui: Ui,
+ result: HomeResult,
+ now = new Date(),
+): string[] {
+ const { theme, glyphs } = ui;
+ const host = new URL(result.apiUrl).host;
+ const lines = ["", ...logo(ui), ""];
+ if (!result.user) {
+ lines.push(
+ ` ${theme.muted(glyphs.dot)} Not signed in to ${host}`,
+ "",
+ ` ${theme.muted("Run")} ${theme.strong("kaneo login")} ${theme.muted("to get started.")}`,
+ "",
+ );
+ return lines;
+ }
+ lines.push(
+ ` ${theme.strong(result.user.name)} ${theme.muted(`${glyphs.separator} ${result.workspace?.name ?? "no workspace"} ${glyphs.separator} ${host}`)}`,
+ "",
+ );
+ if (result.workspace) {
+ lines.push(` ${theme.strong("Your open tasks")}`);
+ if (result.tasks.length === 0) {
+ lines.push(` ${theme.muted("Nothing assigned to you. Nice.")}`);
+ } else {
+ lines.push(
+ ...renderTable(
+ ui,
+ result.tasks.slice(0, 8),
+ [
+ {
+ header: "ID",
+ cell: (task): Cell => [
+ text(
+ task.number !== null
+ ? `${task.projectSlug.toUpperCase()}-${task.number}`
+ : task.id.slice(0, 8),
+ theme.muted,
+ ),
+ ],
+ },
+ {
+ header: "Title",
+ flex: true,
+ minWidth: 16,
+ cell: (task): Cell => [text(task.title)],
+ },
+ {
+ header: "Priority",
+ optional: true,
+ cell: (task): Cell => prioritySegments(ui, task.priority),
+ },
+ {
+ header: "Due",
+ optional: true,
+ cell: (task): Cell => dueSegments(ui, task.dueDate, false, now),
+ },
+ ],
+ { width: ui.caps.columns, indent: 4 },
+ ),
+ );
+ const shown = Math.min(8, result.tasks.length);
+ if (result.totalTasks > shown) {
+ lines.push(
+ ` ${theme.muted(`and ${result.totalTasks - shown} more`)}`,
+ );
+ }
+ }
+ lines.push("");
+ }
+ lines.push(` ${theme.strong("Commands")}`);
+ const width = Math.max(...COMMANDS.map(([command]) => command.length));
+ for (const [command, description] of COMMANDS) {
+ lines.push(` ${command.padEnd(width)} ${theme.muted(description)}`);
+ }
+ lines.push("");
+ return lines;
+}
+
+export const runHome = Effect.fn("command.home")(function* () {
+ const session = yield* Session;
+ if (Option.isNone(session.credentials)) {
+ yield* emit<HomeResult>(
+ {
+ signedIn: false,
+ apiUrl: session.apiUrl,
+ user: null,
+ workspace: null,
+ tasks: [],
+ totalTasks: 0,
+ },
+ renderHome,
+ );
+ return;
+ }
+ const workspaceId = Option.getOrUndefined(session.workspace)?.id;
+ const [user, workspace, assigned] = yield* withSpinner("Loading")(
+ Effect.all(
+ [
+ getCurrentUser(),
+ workspaceId
+ ? getWorkspace(workspaceId).pipe(
+ Effect.catchTag("NotFound", () => Effect.succeed(null)),
+ )
+ : Effect.succeed(null),
+ workspaceId
+ ? listAssignedTasks(workspaceId)
+ : Effect.succeed({ tasks: [], total: 0 }),
+ ],
+ { concurrency: 3 },
+ ),
+ );
+ yield* emit<HomeResult>(
+ {
+ signedIn: true,
+ apiUrl: session.apiUrl,
+ user,
+ workspace,
+ tasks: assigned.tasks,
+ totalTasks: assigned.total,
+ },
+ renderHome,
+ );
+});
diff --git a/packages/cli/src/commands/invitation/accept.ts b/packages/cli/src/commands/invitation/accept.ts
new file mode 100644
index 000000000..227014477
--- /dev/null
+++ b/packages/cli/src/commands/invitation/accept.ts
@@ -0,0 +1,26 @@
+import { Effect, Option } from "effect";
+import { Argument, Command } from "effect/cli";
+import { answerInvitation } from "../../admin/answer-invitation.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runInvitationAccept = Effect.fn("command.invitation.accept")(
+ function* (options: { readonly id: Option.Option<string> }) {
+ yield* answerInvitation(options.id, true);
+ },
+);
+
+export const invitationAccept = Command.make(
+ "accept",
+ {
+ id: Argument.String("id").pipe(
+ Argument.withDescription(
+ "Invitation id; asked for when omitted in a terminal",
+ ),
+ Argument.optional,
+ ),
+ },
+ (options) => runInvitationAccept(options),
+).pipe(
+ Command.withDescription("Accept an invitation and join the workspace"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/invitation/cancel.ts b/packages/cli/src/commands/invitation/cancel.ts
new file mode 100644
index 000000000..ddbe53f0c
--- /dev/null
+++ b/packages/cli/src/commands/invitation/cancel.ts
@@ -0,0 +1,105 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import {
+ isPending,
+ toSentInvitationJson,
+} from "../../admin/invitation-json.js";
+import { renderInvitationCanceled } from "../../admin/render-invitation-change.js";
+import { roleLabel } from "../../admin/roles.js";
+import {
+ cancelInvitation,
+ listSentInvitations,
+} from "../../api/invitations.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import { confirmDestructive } from "../../prompts/confirm-destructive.js";
+import { pick } from "../../prompts/pick.js";
+import { resolveWorkspaceId } from "../../services/selection.js";
+import { Session } from "../../services/session.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runInvitationCancel = Effect.fn("command.invitation.cancel")(
+ function* (options: {
+ readonly invitation: Option.Option<string>;
+ readonly yes: boolean;
+ }) {
+ const session = yield* Session;
+ const output = yield* Output;
+ if (Option.isNone(options.invitation) && !output.interactive) {
+ return yield* new InvalidArgument({
+ message: "Which invitation should be canceled?",
+ hint: "Pass its id or email address. Run kaneo invitation list to see them.",
+ });
+ }
+ const workspaceId = yield* resolveWorkspaceId();
+ const now = new Date();
+ const pending = (yield* withSpinner("Loading invitations")(
+ listSentInvitations(workspaceId),
+ ))
+ .map((invitation) => toSentInvitationJson(invitation, session.webUrl))
+ .filter((invitation) => isPending(invitation, now));
+
+ const wanted = Option.map(options.invitation, (value) => value.trim());
+ const target = Option.isSome(wanted)
+ ? pending.find(
+ (invitation) =>
+ invitation.id === wanted.value ||
+ invitation.email === wanted.value.toLowerCase(),
+ )
+ : pending.length > 0
+ ? yield* pick(
+ "Cancel which invitation?",
+ pending.map((invitation) => ({
+ title: invitation.email,
+ value: invitation,
+ description: roleLabel(invitation.role),
+ })),
+ )
+ : undefined;
+ if (!target) {
+ return yield* new InvalidArgument({
+ message: Option.isSome(wanted)
+ ? `No pending invitation matches "${wanted.value}" in this workspace.`
+ : "This workspace has no pending invitations.",
+ hint: "Run kaneo invitation list to see the pending ones.",
+ });
+ }
+
+ yield* confirmDestructive({
+ yes: options.yes,
+ action: `Canceling the invitation for ${target.email}`,
+ question: `Cancel the invitation for ${target.email}? Its link stops working.`,
+ });
+
+ yield* withSpinner(`Canceling the invitation for ${target.email}`)(
+ cancelInvitation(target.id),
+ );
+ yield* emit(
+ { ...target, status: "canceled", canceled: true },
+ renderInvitationCanceled,
+ );
+ },
+);
+
+export const invitationCancel = Command.make(
+ "cancel",
+ {
+ invitation: Argument.String("invitation").pipe(
+ Argument.withDescription(
+ "Invitation id or invited email address; asked for when omitted in a terminal",
+ ),
+ Argument.optional,
+ ),
+ yes: Flag.Boolean("yes").pipe(
+ Flag.withAlias("y"),
+ Flag.withDescription("Cancel without asking for confirmation"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runInvitationCancel(options),
+).pipe(
+ Command.withDescription("Cancel a pending invitation you sent"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/invitation/decline.ts b/packages/cli/src/commands/invitation/decline.ts
new file mode 100644
index 000000000..e2f73975d
--- /dev/null
+++ b/packages/cli/src/commands/invitation/decline.ts
@@ -0,0 +1,26 @@
+import { Effect, Option } from "effect";
+import { Argument, Command } from "effect/cli";
+import { answerInvitation } from "../../admin/answer-invitation.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runInvitationDecline = Effect.fn("command.invitation.decline")(
+ function* (options: { readonly id: Option.Option<string> }) {
+ yield* answerInvitation(options.id, false);
+ },
+);
+
+export const invitationDecline = Command.make(
+ "decline",
+ {
+ id: Argument.String("id").pipe(
+ Argument.withDescription(
+ "Invitation id; asked for when omitted in a terminal",
+ ),
+ Argument.optional,
+ ),
+ },
+ (options) => runInvitationDecline(options),
+).pipe(
+ Command.withDescription("Decline an invitation to a workspace"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/invitation/index.ts b/packages/cli/src/commands/invitation/index.ts
new file mode 100644
index 000000000..450fd0f8e
--- /dev/null
+++ b/packages/cli/src/commands/invitation/index.ts
@@ -0,0 +1,17 @@
+import { Command } from "effect/cli";
+import { invitationAccept } from "./accept.js";
+import { invitationCancel } from "./cancel.js";
+import { invitationDecline } from "./decline.js";
+import { invitationList } from "./list.js";
+import { invitationPending } from "./pending.js";
+
+export const invitation = Command.make("invitation").pipe(
+ Command.withDescription("Manage workspace invitations"),
+ Command.withSubcommands([
+ invitationList,
+ invitationPending,
+ invitationAccept,
+ invitationDecline,
+ invitationCancel,
+ ]),
+);
diff --git a/packages/cli/src/commands/invitation/list.ts b/packages/cli/src/commands/invitation/list.ts
new file mode 100644
index 000000000..b68f0a6e0
--- /dev/null
+++ b/packages/cli/src/commands/invitation/list.ts
@@ -0,0 +1,38 @@
+import { Effect } from "effect";
+import { Command } from "effect/cli";
+import {
+ isPending,
+ toSentInvitationJson,
+} from "../../admin/invitation-json.js";
+import { renderSentInvitations } from "../../admin/render-invitation-list.js";
+import { listSentInvitations } from "../../api/invitations.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { resolveWorkspaceId } from "../../services/selection.js";
+import { Session } from "../../services/session.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runInvitationList = Effect.fn("command.invitation.list")(
+ function* () {
+ const session = yield* Session;
+ const workspaceId = yield* resolveWorkspaceId();
+ const invitations = yield* withSpinner("Loading invitations")(
+ listSentInvitations(workspaceId),
+ );
+ const now = new Date();
+ const pending = invitations
+ .map((invitation) => toSentInvitationJson(invitation, session.webUrl))
+ .filter((invitation) => isPending(invitation, now))
+ .sort((a, b) => (b.createdAt ?? "").localeCompare(a.createdAt ?? ""));
+ yield* emit(pending, (ui, value) =>
+ renderSentInvitations(ui, { invitations: value, now }),
+ );
+ },
+);
+
+export const invitationList = Command.make("list", {}, () =>
+ runInvitationList(),
+).pipe(
+ Command.withDescription("List pending invitations sent from the workspace"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/invitation/pending.ts b/packages/cli/src/commands/invitation/pending.ts
new file mode 100644
index 000000000..fbab0ed4e
--- /dev/null
+++ b/packages/cli/src/commands/invitation/pending.ts
@@ -0,0 +1,26 @@
+import { Effect } from "effect";
+import { Command } from "effect/cli";
+import { toReceivedInvitationJson } from "../../admin/invitation-json.js";
+import { renderReceivedInvitations } from "../../admin/render-invitation-list.js";
+import { listReceivedInvitations } from "../../api/invitations.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runInvitationPending = Effect.fn("command.invitation.pending")(
+ function* () {
+ const invitations = yield* withSpinner("Loading invitations")(
+ listReceivedInvitations(),
+ );
+ yield* emit(invitations.map(toReceivedInvitationJson), (ui, value) =>
+ renderReceivedInvitations(ui, { invitations: value, now: new Date() }),
+ );
+ },
+);
+
+export const invitationPending = Command.make("pending", {}, () =>
+ runInvitationPending(),
+).pipe(
+ Command.withDescription("List invitations to join other workspaces"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/label/create.ts b/packages/cli/src/commands/label/create.ts
new file mode 100644
index 000000000..e7c2a3812
--- /dev/null
+++ b/packages/cli/src/commands/label/create.ts
@@ -0,0 +1,104 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag, Prompt } from "effect/cli";
+import { createLabel, listWorkspaceLabels } from "../../api/labels.js";
+import { Cancelled, InvalidArgument } from "../../errors/errors.js";
+import {
+ defaultLabelColor,
+ parseLabelColor,
+} from "../../labels/label-colors.js";
+import { toLabelJson } from "../../labels/label-json.js";
+import { findNameClash, workspaceLabels } from "../../labels/match-label.js";
+import { nameClashError } from "../../labels/name-clash-error.js";
+import { renderLabelChange } from "../../labels/render-label-change.js";
+import { emit } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import { promptTheme } from "../../prompts/prompt-theme.js";
+import { resolveWorkspaceId } from "../../services/selection.js";
+import { ApiLayer } from "../api-layer.js";
+
+const resolveName = Effect.fnUntraced(function* (name: Option.Option<string>) {
+ const output = yield* Output;
+ const given = name.pipe(
+ Option.map((value) => value.trim()),
+ Option.filter((value) => value !== ""),
+ );
+ if (Option.isSome(given)) return given.value;
+ if (output.interactive) {
+ return yield* Prompt.run(
+ Prompt.String({
+ message: "Label name",
+ validate: (value) =>
+ value.trim() === ""
+ ? Effect.fail("Enter a name")
+ : Effect.succeed(value.trim()),
+ theme: promptTheme(output.ui),
+ }),
+ ).pipe(Effect.catchTag("QuitError", () => Effect.fail(new Cancelled())));
+ }
+ return yield* new InvalidArgument({
+ message: "A label name is required.",
+ hint: "Pass it as the first argument, for example kaneo label create Bug.",
+ });
+});
+
+export const runLabelCreate = Effect.fn("command.label.create")(
+ function* (options: {
+ readonly name: Option.Option<string>;
+ readonly color: Option.Option<string>;
+ }) {
+ const color = yield* Option.match(options.color, {
+ onNone: () => Effect.succeed(undefined),
+ onSome: (value) => Effect.fromResult(parseLabelColor(value)),
+ });
+ const workspaceId = yield* resolveWorkspaceId();
+ const name = yield* resolveName(options.name);
+ const labels = yield* withSpinner("Loading labels")(
+ listWorkspaceLabels(workspaceId),
+ );
+ const clash = findNameClash(labels, name);
+ if (clash) return yield* nameClashError(clash, name);
+ const created = yield* withSpinner(`Creating ${name}`)(
+ createLabel({
+ workspaceId,
+ name,
+ color:
+ color ??
+ defaultLabelColor(
+ name,
+ workspaceLabels(labels).map((label) => label.color),
+ ),
+ }),
+ );
+ yield* emit(toLabelJson(created), (ui, label) =>
+ renderLabelChange(ui, {
+ verb: "Created",
+ name: label.name,
+ color: label.color,
+ }),
+ );
+ },
+);
+
+export const labelCreate = Command.make(
+ "create",
+ {
+ name: Argument.String("name").pipe(
+ Argument.withDescription(
+ "Label name; asked for when omitted in a terminal",
+ ),
+ Argument.optional,
+ ),
+ color: Flag.String("color").pipe(
+ Flag.withAlias("c"),
+ Flag.withDescription(
+ "Hex color such as #e7000b, or stone, slate, lavender, sage, forest, amber, terracotta, rose or crimson (default: an unused one)",
+ ),
+ Flag.optional,
+ ),
+ },
+ (options) => runLabelCreate(options),
+).pipe(
+ Command.withDescription("Create a workspace label"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/label/delete.ts b/packages/cli/src/commands/label/delete.ts
new file mode 100644
index 000000000..010baafa8
--- /dev/null
+++ b/packages/cli/src/commands/label/delete.ts
@@ -0,0 +1,93 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { listWorkspaceLabels } from "../../api/labels.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { chooseLabel } from "../../labels/choose-label.js";
+import { deleteLabelFully } from "../../labels/delete-label-fully.js";
+import {
+ labelUsage,
+ quoteName,
+ workspaceLabels,
+} from "../../labels/match-label.js";
+import { renderLabelChange } from "../../labels/render-label-change.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { confirmDestructive } from "../../prompts/confirm-destructive.js";
+import { resolveWorkspaceId } from "../../services/selection.js";
+import { ApiLayer } from "../api-layer.js";
+
+function taskCount(count: number): string {
+ return count === 1 ? "1 task" : `${count} tasks`;
+}
+
+export const runLabelDelete = Effect.fn("command.label.delete")(
+ function* (options: {
+ readonly label: Option.Option<string>;
+ readonly yes: boolean;
+ }) {
+ const workspaceId = yield* resolveWorkspaceId();
+ const labels = yield* withSpinner("Loading labels")(
+ listWorkspaceLabels(workspaceId),
+ );
+ const target = yield* chooseLabel(
+ workspaceLabels(labels),
+ options.label,
+ "kaneo label delete Bug",
+ );
+ const used = labelUsage(labels).get(target.name) ?? 0;
+
+ yield* confirmDestructive({
+ yes: options.yes,
+ action: `Deleting the label ${target.name}`,
+ question:
+ used > 0
+ ? `Delete the label ${target.name} and remove it from ${taskCount(used)}? This cannot be undone.`
+ : `Delete the label ${target.name}? This cannot be undone.`,
+ });
+
+ yield* withSpinner(`Deleting ${target.name}`)(
+ deleteLabelFully(target.id),
+ ).pipe(
+ Effect.catchTag("RateLimited", () =>
+ Effect.fail(
+ new InvalidArgument({
+ message: `The server is still busy deleting labels, so ${target.name} is only partly deleted.`,
+ hint: `Progress is saved. Run kaneo label delete ${quoteName(target.name)} --yes again in a minute to finish.`,
+ }),
+ ),
+ ),
+ );
+
+ yield* emit({ id: target.id, name: target.name, deleted: true }, (ui) =>
+ renderLabelChange(ui, {
+ verb: "Deleted",
+ name: target.name,
+ color: target.color,
+ ...(used > 0 ? { detail: `removed from ${taskCount(used)}` } : {}),
+ }),
+ );
+ },
+);
+
+export const labelDelete = Command.make(
+ "delete",
+ {
+ label: Argument.String("label").pipe(
+ Argument.withDescription(
+ "Label name or id; asked for when omitted in a terminal",
+ ),
+ Argument.optional,
+ ),
+ yes: Flag.Boolean("yes").pipe(
+ Flag.withAlias("y"),
+ Flag.withDescription("Delete without asking for confirmation"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runLabelDelete(options),
+).pipe(
+ Command.withDescription(
+ "Delete a workspace label and remove it from every task",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/label/edit.ts b/packages/cli/src/commands/label/edit.ts
new file mode 100644
index 000000000..a61ba2031
--- /dev/null
+++ b/packages/cli/src/commands/label/edit.ts
@@ -0,0 +1,127 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { listWorkspaceLabels, updateLabel } from "../../api/labels.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { chooseLabel } from "../../labels/choose-label.js";
+import { labelColorName, parseLabelColor } from "../../labels/label-colors.js";
+import { toLabelJson } from "../../labels/label-json.js";
+import {
+ findNameClash,
+ quoteName,
+ workspaceLabels,
+} from "../../labels/match-label.js";
+import { nameClashError } from "../../labels/name-clash-error.js";
+import { renderLabelChange } from "../../labels/render-label-change.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { resolveWorkspaceId } from "../../services/selection.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runLabelEdit = Effect.fn("command.label.edit")(
+ function* (options: {
+ readonly label: Option.Option<string>;
+ readonly name: Option.Option<string>;
+ readonly color: Option.Option<string>;
+ }) {
+ if (Option.isNone(options.name) && Option.isNone(options.color)) {
+ return yield* new InvalidArgument({
+ message: "Nothing to change.",
+ hint: "Pass --name, --color, or both.",
+ });
+ }
+ const newName = Option.map(options.name, (value) => value.trim());
+ if (Option.isSome(newName) && newName.value === "") {
+ return yield* new InvalidArgument({
+ message: "The label name cannot be empty.",
+ hint: "Pass a name, for example --name Bug.",
+ });
+ }
+ const newColor = yield* Option.match(options.color, {
+ onNone: () => Effect.succeed(Option.none<string>()),
+ onSome: (value) =>
+ Effect.fromResult(parseLabelColor(value)).pipe(Effect.map(Option.some)),
+ });
+
+ const workspaceId = yield* resolveWorkspaceId();
+ const labels = yield* withSpinner("Loading labels")(
+ listWorkspaceLabels(workspaceId),
+ );
+ const target = yield* chooseLabel(
+ workspaceLabels(labels),
+ options.label,
+ "kaneo label edit Bug --color crimson",
+ );
+ if (target.deletionStartedAt) {
+ return yield* new InvalidArgument({
+ message: `The label "${target.name}" is being deleted.`,
+ hint: `Run kaneo label delete ${quoteName(target.name)} to finish deleting it.`,
+ });
+ }
+ const name = Option.getOrElse(newName, () => target.name);
+ const color = Option.getOrElse(newColor, () => target.color);
+ const renamed = name !== target.name;
+ if (renamed) {
+ const clash = findNameClash(labels, name, target);
+ if (clash) return yield* nameClashError(clash, name, target.name);
+ }
+
+ const updated = yield* withSpinner(`Updating ${target.name}`)(
+ updateLabel(target.id, { name, color }),
+ ).pipe(
+ Effect.catchTag("ServerError", (error) =>
+ Effect.fail<InvalidArgument | typeof error>(
+ renamed && error.status === 500
+ ? new InvalidArgument({
+ message: `Could not rename "${target.name}" to "${name}".`,
+ hint: `A task you cannot see may already have a label named "${name}". Pick another name.`,
+ })
+ : error,
+ ),
+ ),
+ );
+
+ const changes = [
+ ...(renamed ? [`renamed from ${target.name}`] : []),
+ ...(color !== target.color
+ ? [`color ${labelColorName(color) ?? color}`]
+ : []),
+ ];
+ yield* emit(toLabelJson(updated), (ui, label) =>
+ renderLabelChange(ui, {
+ verb: "Updated",
+ name: label.name,
+ color: label.color,
+ detail: changes.length > 0 ? changes.join(", ") : "no changes",
+ }),
+ );
+ },
+);
+
+export const labelEdit = Command.make(
+ "edit",
+ {
+ label: Argument.String("label").pipe(
+ Argument.withDescription(
+ "Label name or id; asked for when omitted in a terminal",
+ ),
+ Argument.optional,
+ ),
+ name: Flag.String("name").pipe(
+ Flag.withDescription("New name"),
+ Flag.optional,
+ ),
+ color: Flag.String("color").pipe(
+ Flag.withAlias("c"),
+ Flag.withDescription(
+ "New color: a hex color such as #e7000b, or a palette name such as crimson",
+ ),
+ Flag.optional,
+ ),
+ },
+ (options) => runLabelEdit(options),
+).pipe(
+ Command.withDescription(
+ "Rename a workspace label or change its color, on every task that uses it",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/label/index.ts b/packages/cli/src/commands/label/index.ts
new file mode 100644
index 000000000..90476bb13
--- /dev/null
+++ b/packages/cli/src/commands/label/index.ts
@@ -0,0 +1,10 @@
+import { Command } from "effect/cli";
+import { labelCreate } from "./create.js";
+import { labelDelete } from "./delete.js";
+import { labelEdit } from "./edit.js";
+import { labelList } from "./list.js";
+
+export const label = Command.make("label").pipe(
+ Command.withDescription("Manage workspace labels"),
+ Command.withSubcommands([labelList, labelCreate, labelEdit, labelDelete]),
+);
diff --git a/packages/cli/src/commands/label/list.ts b/packages/cli/src/commands/label/list.ts
new file mode 100644
index 000000000..61fc21351
--- /dev/null
+++ b/packages/cli/src/commands/label/list.ts
@@ -0,0 +1,37 @@
+import { Effect } from "effect";
+import { Command } from "effect/cli";
+import { listWorkspaceLabels } from "../../api/labels.js";
+import { toLabelJson } from "../../labels/label-json.js";
+import { labelUsage, workspaceLabels } from "../../labels/match-label.js";
+import {
+ type LabelListRow,
+ renderLabelList,
+} from "../../labels/render-label-list.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { resolveWorkspaceId } from "../../services/selection.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runLabelList = Effect.fn("command.label.list")(function* () {
+ const workspaceId = yield* resolveWorkspaceId();
+ const labels = yield* withSpinner("Loading labels")(
+ listWorkspaceLabels(workspaceId),
+ );
+ const usage = labelUsage(labels);
+ const ordered = [...workspaceLabels(labels)].sort((a, b) =>
+ a.name.localeCompare(b.name, undefined, { sensitivity: "base" }),
+ );
+ const rows: ReadonlyArray<LabelListRow> = ordered.map((label) => ({
+ id: label.id,
+ name: label.name,
+ color: label.color,
+ tasks: usage.get(label.name) ?? 0,
+ deleting: Boolean(label.deletionStartedAt),
+ }));
+ yield* emit(ordered.map(toLabelJson), (ui) => renderLabelList(ui, rows));
+});
+
+export const labelList = Command.make("list", {}, () => runLabelList()).pipe(
+ Command.withDescription("List the labels in your workspace"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/link.ts b/packages/cli/src/commands/link.ts
new file mode 100644
index 000000000..0864fa741
--- /dev/null
+++ b/packages/cli/src/commands/link.ts
@@ -0,0 +1,178 @@
+import { dirname } from "node:path";
+import { Effect, Option } from "effect";
+import { Command, Flag } from "effect/cli";
+import { listProjects, listWorkspaces } from "../api/endpoints.js";
+import type { Project, Workspace } from "../api/schemas.js";
+import {
+ linkFilePath,
+ mergeRepoLink,
+ readRepoConfigObject,
+ writeRepoConfig,
+} from "../config/repo-config.js";
+import { InvalidArgument, ProjectNotFound } from "../errors/errors.js";
+import { emit, note } from "../output/emit.js";
+import { Output } from "../output/output.js";
+import { withSpinner } from "../output/spinner.js";
+import { pick } from "../prompts/pick.js";
+import type { Ui } from "../render/ui.js";
+import { CliEnvironment } from "../services/cli-environment.js";
+import { matchProject } from "../services/selection.js";
+import { Session } from "../services/session.js";
+import { ApiLayer } from "./api-layer.js";
+import { matchWorkspace } from "./workspace/match-workspace.js";
+
+type LinkResult = {
+ readonly path: string;
+ readonly workspace: { readonly id: string; readonly name: string };
+ readonly project: {
+ readonly id: string;
+ readonly key: string;
+ readonly name: string;
+ };
+};
+
+export function renderLink(ui: Ui, result: LinkResult): string[] {
+ const { theme, glyphs } = ui;
+ return [
+ ` ${theme.success(glyphs.tick)} Linked ${dirname(result.path)} to ${result.workspace.name} ${theme.muted(glyphs.separator)} ${theme.strong(result.project.key)}`,
+ ];
+}
+
+const chooseWorkspace = Effect.fn("link.workspace")(function* (
+ reference: Option.Option<string>,
+) {
+ const workspaces = yield* withSpinner("Loading workspaces")(listWorkspaces());
+ if (Option.isSome(reference)) {
+ const match = matchWorkspace(workspaces, reference.value);
+ if (match.kind === "found") return match.workspace;
+ return yield* new InvalidArgument({
+ message:
+ match.kind === "ambiguous"
+ ? `"${reference.value}" matches ${match.candidates.length} workspaces.`
+ : `No workspace matches "${reference.value}".`,
+ hint: "Pass the workspace id or slug. Run kaneo workspace list to see them.",
+ });
+ }
+ const [only] = workspaces;
+ if (!only) {
+ return yield* new InvalidArgument({
+ message: "You are not a member of any workspace yet.",
+ hint: "Create one in the Kaneo web app, then run this again.",
+ });
+ }
+ if (workspaces.length === 1) return only;
+ return yield* pick<Workspace>(
+ "Link this repository to which workspace?",
+ workspaces.map((workspace) => ({
+ title: workspace.name,
+ value: workspace,
+ description: workspace.slug,
+ })),
+ );
+});
+
+const chooseProject = Effect.fn("link.project")(function* (
+ workspace: Workspace,
+ reference: Option.Option<string>,
+) {
+ const projects = (yield* withSpinner("Loading projects")(
+ listProjects(workspace.id),
+ )).filter((project) => project.archivedAt === null);
+ if (Option.isSome(reference)) {
+ const match = matchProject(projects, reference.value);
+ if (match) return match;
+ return yield* new ProjectNotFound({ query: reference.value, source: null });
+ }
+ const [only] = projects;
+ if (!only) {
+ return yield* new InvalidArgument({
+ message: `${workspace.name} has no projects yet.`,
+ hint: "Create one in the Kaneo web app, then run this again.",
+ });
+ }
+ if (projects.length === 1) return only;
+ return yield* pick<Project>(
+ "Link this repository to which project?",
+ projects.map((project) => ({
+ title: project.name,
+ value: project,
+ description: project.slug.toUpperCase(),
+ })),
+ );
+});
+
+export const runLink = Effect.fn("command.link")(function* (options: {
+ readonly project: Option.Option<string>;
+}) {
+ const session = yield* Session;
+ const output = yield* Output;
+ const environment = yield* CliEnvironment;
+
+ const workspaceRef = Option.flatMap(session.workspace, (workspace) =>
+ workspace.source === "flag" || workspace.source === "env"
+ ? Option.some(workspace.id)
+ : Option.none(),
+ );
+ if (!output.interactive && Option.isNone(workspaceRef)) {
+ return yield* new InvalidArgument({
+ message: "Which workspace should this repository use?",
+ hint: "Pass -w with the workspace id or slug, for example kaneo link -w acme-studio -p KAN.",
+ });
+ }
+ if (!output.interactive && Option.isNone(options.project)) {
+ return yield* new InvalidArgument({
+ message: "Which project should this repository use?",
+ hint: "Pass -p with the project key, for example kaneo link -w acme-studio -p KAN.",
+ });
+ }
+
+ const path = linkFilePath(environment.cwd);
+ const existing = yield* readRepoConfigObject(path);
+ const workspace = yield* chooseWorkspace(workspaceRef);
+ const project = yield* chooseProject(workspace, options.project);
+ const key = project.slug.toUpperCase();
+
+ yield* writeRepoConfig(
+ path,
+ mergeRepoLink(existing, { workspace: workspace.id, project: key }),
+ );
+
+ yield* emit<LinkResult>(
+ {
+ path,
+ workspace: { id: workspace.id, name: workspace.name },
+ project: { id: project.id, key, name: project.name },
+ },
+ renderLink,
+ );
+
+ const overrides = ["KANEO_WORKSPACE", "KANEO_PROJECT"].filter((name) =>
+ environment.env[name]?.trim(),
+ );
+ if (overrides.length > 0) {
+ yield* note((ui) => [
+ ...overrides.map(
+ (name) =>
+ ` ${ui.theme.warning(ui.glyphs.warning)} ${name} is set and overrides .kaneo.json until you unset it.`,
+ ),
+ "",
+ ]);
+ }
+});
+
+export const linkCommand = Command.make(
+ "link",
+ {
+ project: Flag.String("project").pipe(
+ Flag.withAlias("p"),
+ Flag.withDescription("Project key or id, for example KAN"),
+ Flag.optional,
+ ),
+ },
+ (options) => runLink(options),
+).pipe(
+ Command.withDescription(
+ "Save the workspace (-w) and project (-p) for this repository in .kaneo.json",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/login.ts b/packages/cli/src/commands/login.ts
new file mode 100644
index 000000000..3fa78d9ac
--- /dev/null
+++ b/packages/cli/src/commands/login.ts
@@ -0,0 +1,210 @@
+import { Effect, Option, Redacted } from "effect";
+import { Command, Flag } from "effect/cli";
+import { getCurrentUser, listWorkspaces } from "../api/endpoints.js";
+import type { CurrentUser, Workspace } from "../api/schemas.js";
+import {
+ formatUserCode,
+ waitForApproval,
+ webUrlFromVerificationUri,
+} from "../auth/wait-for-approval.js";
+import { ConfigStore } from "../config/config-store.js";
+import { withProfile } from "../config/format.js";
+import { emit, note } from "../output/emit.js";
+import { Output } from "../output/output.js";
+import { withSpinner } from "../output/spinner.js";
+import { pick } from "../prompts/pick.js";
+import { box } from "../render/box.js";
+import { logo } from "../render/logo.js";
+import type { Ui } from "../render/ui.js";
+import { Desktop } from "../services/desktop.js";
+import { DeviceAuth } from "../services/device-auth.js";
+import { type Credentials, Session } from "../services/session.js";
+import { ApiLayer } from "./api-layer.js";
+
+type LoginResult = {
+ readonly user: CurrentUser;
+ readonly apiUrl: string;
+ readonly profile: string;
+ readonly workspace: Workspace | null;
+};
+
+function host(url: string): string {
+ return new URL(url).host;
+}
+
+export function renderDeviceCode(
+ ui: Ui,
+ details: {
+ readonly apiUrl: string;
+ readonly code: string;
+ readonly url: string;
+ readonly copied: boolean;
+ readonly opened: boolean;
+ readonly expiresInSeconds: number;
+ },
+): string[] {
+ const { theme, glyphs } = ui;
+ const spaced = details.code.split("").join(" ");
+ const lines = [
+ "",
+ theme.muted("Enter this code in your browser"),
+ "",
+ ` ${theme.strong(spaced)}`,
+ "",
+ details.copied
+ ? `${theme.success(glyphs.tick)} ${theme.muted("Copied to your clipboard")}`
+ : theme.muted(
+ `Expires in ${Math.max(1, Math.round(details.expiresInSeconds / 60))} minutes`,
+ ),
+ "",
+ ];
+ return [
+ "",
+ ...box(ui, lines, {
+ title: `Sign in to ${host(details.apiUrl)}`,
+ minWidth: 36,
+ }).map((line) => ` ${line}`),
+ "",
+ details.opened
+ ? ` ${theme.muted(glyphs.arrow)} Opened ${theme.info(details.url)}`
+ : ` ${theme.muted(glyphs.arrow)} Open ${theme.info(details.url)}`,
+ "",
+ ];
+}
+
+export function renderWelcome(ui: Ui, result: LoginResult): string[] {
+ const { theme, glyphs } = ui;
+ const workspace = result.workspace
+ ? result.workspace.name
+ : theme.muted("none selected, run kaneo workspace use");
+ return [
+ "",
+ ...logo(ui),
+ "",
+ ` ${theme.success(glyphs.tick)} Signed in as ${theme.strong(result.user.name)} ${theme.muted(glyphs.separator)} ${result.user.email}`,
+ "",
+ ` ${theme.muted("Server".padEnd(10))} ${host(result.apiUrl)}`,
+ ` ${theme.muted("Workspace".padEnd(10))} ${workspace}`,
+ "",
+ ` ${theme.muted("Try")} ${theme.strong("kaneo task list")} ${theme.muted("or just")} ${theme.strong("kaneo")}`,
+ "",
+ ];
+}
+
+const chooseWorkspace = Effect.fn("login.chooseWorkspace")(function* (
+ workspaces: ReadonlyArray<Workspace>,
+ previous: string | undefined,
+) {
+ const output = yield* Output;
+ const kept = workspaces.find((workspace) => workspace.id === previous);
+ if (kept) return kept;
+ const [only] = workspaces;
+ if (workspaces.length === 1 && only) return only;
+ if (workspaces.length > 1 && output.interactive) {
+ return yield* pick(
+ "Choose your default workspace",
+ workspaces.map((workspace) => ({
+ title: workspace.name,
+ value: workspace,
+ description: workspace.slug,
+ })),
+ );
+ }
+ return null;
+});
+
+export const runLogin = Effect.fn("command.login")(function* (options: {
+ readonly browser: boolean;
+}) {
+ const session = yield* Session;
+ const output = yield* Output;
+ const device = yield* DeviceAuth;
+ const desktop = yield* Desktop;
+ const store = yield* ConfigStore;
+
+ if (Option.isSome(session.configProblem)) {
+ return yield* Effect.fail(session.configProblem.value);
+ }
+
+ const code = yield* withSpinner(`Connecting to ${host(session.apiUrl)}`)(
+ device.requestCode(session.apiUrl),
+ );
+ const userCode = formatUserCode(code.user_code);
+ const url = code.verification_uri_complete ?? code.verification_uri;
+ const copied = output.interactive ? yield* desktop.copy(userCode) : false;
+ const opened =
+ output.interactive && options.browser ? yield* desktop.openUrl(url) : false;
+
+ if (output.mode === "json") {
+ yield* note(() => [`Open ${url} and enter the code ${userCode}`]);
+ } else {
+ yield* output.out(
+ `${renderDeviceCode(output.ui, {
+ apiUrl: session.apiUrl,
+ code: userCode,
+ url,
+ copied,
+ opened,
+ expiresInSeconds: code.expires_in,
+ }).join("\n")}\n`,
+ );
+ }
+
+ const token = yield* withSpinner("Waiting for approval in your browser")(
+ waitForApproval(session.apiUrl, code),
+ );
+ const credentials: Credentials = {
+ token: Redacted.make(token),
+ source: "profile",
+ };
+ const [user, workspaces] = yield* withSpinner("Loading your account")(
+ Effect.all([getCurrentUser(credentials), listWorkspaces(credentials)], {
+ concurrency: 2,
+ }),
+ );
+ const workspace = yield* chooseWorkspace(
+ workspaces,
+ session.profile?.workspaceId,
+ );
+ const webUrl =
+ webUrlFromVerificationUri(code.verification_uri) ?? session.apiUrl;
+
+ yield* store.save(
+ withProfile(session.config, session.profileName, () => ({
+ apiUrl: session.apiUrl,
+ webUrl,
+ token,
+ user: { id: user.id, name: user.name, email: user.email },
+ ...(workspace ? { workspaceId: workspace.id } : {}),
+ })),
+ );
+
+ yield* emit<LoginResult>(
+ { user, apiUrl: session.apiUrl, profile: session.profileName, workspace },
+ renderWelcome,
+ );
+
+ const overriding = Option.getOrUndefined(session.credentials)?.source;
+ if (overriding === "env") {
+ yield* note((ui) => [
+ ` ${ui.theme.warning(ui.glyphs.warning)} KANEO_API_KEY is set and is used instead of this login until you unset it.`,
+ "",
+ ]);
+ }
+});
+
+export const login = Command.make(
+ "login",
+ {
+ noBrowser: Flag.Boolean("no-browser").pipe(
+ Flag.withDescription(
+ "Print the sign-in link instead of opening a browser",
+ ),
+ Flag.withDefault(false),
+ ),
+ },
+ ({ noBrowser }) => runLogin({ browser: !noBrowser }),
+).pipe(
+ Command.withDescription("Sign in with your browser"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/logout.ts b/packages/cli/src/commands/logout.ts
new file mode 100644
index 000000000..8d812b90b
--- /dev/null
+++ b/packages/cli/src/commands/logout.ts
@@ -0,0 +1,70 @@
+import { Effect, Option, Redacted, Schema } from "effect";
+import { Command } from "effect/cli";
+import { KaneoApi } from "../api/kaneo-api.js";
+import { ConfigStore } from "../config/config-store.js";
+import { withProfile } from "../config/format.js";
+import { emit } from "../output/emit.js";
+import type { Ui } from "../render/ui.js";
+import { Session } from "../services/session.js";
+import { ApiLayer } from "./api-layer.js";
+
+type LogoutResult = {
+ readonly loggedOut: boolean;
+ readonly apiUrl: string;
+ readonly profile: string;
+ readonly apiKeyStillSet: boolean;
+};
+
+export function renderLogout(ui: Ui, result: LogoutResult): string[] {
+ const { theme, glyphs } = ui;
+ const host = new URL(result.apiUrl).host;
+ const lines = result.loggedOut
+ ? [` ${theme.success(glyphs.tick)} Signed out of ${host}`]
+ : [` ${theme.muted(glyphs.dot)} You were not signed in to ${host}`];
+ if (result.apiKeyStillSet) {
+ lines.push(
+ ` ${theme.warning(glyphs.warning)} KANEO_API_KEY is still set, so commands keep using it.`,
+ );
+ }
+ return lines;
+}
+
+export const runLogout = Effect.fn("command.logout")(function* () {
+ const session = yield* Session;
+ const store = yield* ConfigStore;
+ const api = yield* KaneoApi;
+ const token = session.profile?.token;
+
+ if (token) {
+ yield* api
+ .request("POST", "/api/auth/sign-out", Schema.Unknown, {
+ body: {},
+ credentials: { token: Redacted.make(token), source: "profile" },
+ })
+ .pipe(Effect.ignore);
+ yield* store.save(
+ withProfile(session.config, session.profileName, (profile) => {
+ const { token: _token, ...rest } = profile ?? {
+ apiUrl: session.apiUrl,
+ };
+ return rest;
+ }),
+ );
+ }
+
+ yield* emit<LogoutResult>(
+ {
+ loggedOut: Boolean(token),
+ apiUrl: session.apiUrl,
+ profile: session.profileName,
+ apiKeyStillSet:
+ Option.getOrUndefined(session.credentials)?.source === "env",
+ },
+ renderLogout,
+ );
+});
+
+export const logout = Command.make("logout", {}, () => runLogout()).pipe(
+ Command.withDescription("Sign out and forget the stored token"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/member/index.ts b/packages/cli/src/commands/member/index.ts
new file mode 100644
index 000000000..942f17c0f
--- /dev/null
+++ b/packages/cli/src/commands/member/index.ts
@@ -0,0 +1,10 @@
+import { Command } from "effect/cli";
+import { memberInvite } from "./invite.js";
+import { memberList } from "./list.js";
+import { memberRemove } from "./remove.js";
+import { memberRole } from "./role.js";
+
+export const member = Command.make("member").pipe(
+ Command.withDescription("Manage workspace members"),
+ Command.withSubcommands([memberList, memberInvite, memberRole, memberRemove]),
+);
diff --git a/packages/cli/src/commands/member/invite.ts b/packages/cli/src/commands/member/invite.ts
new file mode 100644
index 000000000..3c2ed0556
--- /dev/null
+++ b/packages/cli/src/commands/member/invite.ts
@@ -0,0 +1,158 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { invitationUrl } from "../../admin/invitation-json.js";
+import { parseEmails } from "../../admin/parse-emails.js";
+import {
+ type InviteJson,
+ renderInvites,
+} from "../../admin/render-invitation-change.js";
+import { resolveRole } from "../../admin/resolve-role.js";
+import { inviteMember, listSentInvitations } from "../../api/invitations.js";
+import { listOrganizationMembers } from "../../api/members.js";
+import { describeError } from "../../errors/describe.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit, note } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { resolveWorkspaceId } from "../../services/selection.js";
+import { Session } from "../../services/session.js";
+import { ApiLayer } from "../api-layer.js";
+
+const EMAIL_FAILED = /email delivery failed/i;
+
+export const runMemberInvite = Effect.fn("command.member.invite")(
+ function* (options: {
+ readonly emails: ReadonlyArray<string>;
+ readonly role: string;
+ }) {
+ const session = yield* Session;
+ const emails = yield* Effect.fromResult(parseEmails(options.emails));
+ const workspaceId = yield* resolveWorkspaceId();
+ const role = yield* resolveRole(workspaceId, Option.some(options.role), {
+ question: "Invite as",
+ example: "--role admin",
+ });
+ const [members, sent] = yield* withSpinner("Loading members")(
+ Effect.all(
+ [
+ listOrganizationMembers(workspaceId),
+ listSentInvitations(workspaceId),
+ ],
+ { concurrency: 2 },
+ ),
+ );
+ const memberEmails = new Set(
+ members.map((member) => member.user.email.toLowerCase()),
+ );
+ const already = emails.filter((email) => memberEmails.has(email));
+ if (already.length > 0) {
+ return yield* new InvalidArgument({
+ message:
+ already.length === 1
+ ? `${already[0]} is already a member of this workspace.`
+ : `Already members of this workspace: ${already.join(", ")}.`,
+ hint: "Run kaneo member role to change what a member can do.",
+ });
+ }
+ const pending = new Set(
+ sent
+ .filter((invitation) => invitation.status === "pending")
+ .map((invitation) => invitation.email.toLowerCase()),
+ );
+
+ const invites: InviteJson[] = [];
+ for (const email of emails) {
+ const resent = pending.has(email);
+ const result = yield* withSpinner(`Inviting ${email}`)(
+ inviteMember({ workspaceId, email, role, resend: resent }),
+ ).pipe(
+ Effect.map((invitation) => ({
+ id: invitation.id as string | null,
+ role: invitation.role,
+ emailSent: true,
+ })),
+ Effect.catchTag("ServerError", (error) =>
+ error.status === 502 && EMAIL_FAILED.test(error.message)
+ ? Effect.succeed({
+ id: null as string | null,
+ role,
+ emailSent: false,
+ })
+ : Effect.fail(error),
+ ),
+ Effect.result,
+ );
+ if (result._tag === "Failure") {
+ if (invites.length === 0) return yield* Effect.fail(result.failure);
+ const reason = describeError(result.failure).message;
+ return yield* new InvalidArgument({
+ message: `Invited ${invites.map((invite) => invite.email).join(", ")}, then ${email} failed: ${reason}`,
+ hint: "Run the command again with the addresses that were not invited yet.",
+ });
+ }
+ invites.push({
+ id: result.success.id,
+ email,
+ role: result.success.role,
+ resent,
+ emailSent: result.success.emailSent,
+ url: result.success.id
+ ? invitationUrl(session.webUrl, result.success.id)
+ : null,
+ });
+ }
+
+ const missing = invites.filter((invite) => invite.id === null);
+ const completed =
+ missing.length === 0
+ ? invites
+ : yield* listSentInvitations(workspaceId).pipe(
+ Effect.map((latest) =>
+ invites.map((invite) => {
+ if (invite.id !== null) return invite;
+ const found = latest.find(
+ (invitation) =>
+ invitation.status === "pending" &&
+ invitation.email.toLowerCase() === invite.email,
+ );
+ return found
+ ? {
+ ...invite,
+ id: found.id,
+ url: invitationUrl(session.webUrl, found.id),
+ }
+ : invite;
+ }),
+ ),
+ );
+
+ yield* emit(completed, renderInvites);
+ const kept = completed.filter((invite) => invite.role !== role);
+ if (kept.length > 0) {
+ yield* note((ui) => [
+ ` ${ui.theme.warning(ui.glyphs.warning)} A resent invitation keeps its original role. To change it, run kaneo invitation cancel <id>, then invite again.`,
+ "",
+ ]);
+ }
+ },
+);
+
+export const memberInvite = Command.make(
+ "invite",
+ {
+ emails: Argument.String("email").pipe(
+ Argument.withDescription("One or more email addresses to invite"),
+ Argument.atLeast(1),
+ ),
+ role: Flag.String("role").pipe(
+ Flag.withAlias("r"),
+ Flag.withDescription(
+ "Role for the new members: owner, admin, member, viewer, or a custom role",
+ ),
+ Flag.withDefault("member"),
+ ),
+ },
+ (options) => runMemberInvite(options),
+).pipe(
+ Command.withDescription("Invite people to the workspace by email"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/member/list.ts b/packages/cli/src/commands/member/list.ts
new file mode 100644
index 000000000..787a5561a
--- /dev/null
+++ b/packages/cli/src/commands/member/list.ts
@@ -0,0 +1,24 @@
+import { Effect } from "effect";
+import { Command } from "effect/cli";
+import { sortMembers, toMemberJson } from "../../admin/member-json.js";
+import { renderMemberList } from "../../admin/render-member-list.js";
+import { listOrganizationMembers } from "../../api/members.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { resolveWorkspaceId } from "../../services/selection.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runMemberList = Effect.fn("command.member.list")(function* () {
+ const workspaceId = yield* resolveWorkspaceId();
+ const members = yield* withSpinner("Loading members")(
+ listOrganizationMembers(workspaceId),
+ );
+ yield* emit(sortMembers(members.map(toMemberJson)), (ui, value) =>
+ renderMemberList(ui, { members: value, now: new Date() }),
+ );
+});
+
+export const memberList = Command.make("list", {}, () => runMemberList()).pipe(
+ Command.withDescription("List the members of a workspace with their roles"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/member/remove.ts b/packages/cli/src/commands/member/remove.ts
new file mode 100644
index 000000000..427e41a69
--- /dev/null
+++ b/packages/cli/src/commands/member/remove.ts
@@ -0,0 +1,109 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { chooseMember } from "../../admin/choose-member.js";
+import { toMemberJson } from "../../admin/member-json.js";
+import { renderMemberRemoved } from "../../admin/render-member-change.js";
+import { hasRole } from "../../admin/roles.js";
+import { getCurrentUser } from "../../api/endpoints.js";
+import {
+ hasWorkspacePermission,
+ listOrganizationMembers,
+ removeOrganizationMember,
+} from "../../api/members.js";
+import { InvalidArgument, PermissionDenied } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { confirmDestructive } from "../../prompts/confirm-destructive.js";
+import { resolveWorkspaceId } from "../../services/selection.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runMemberRemove = Effect.fn("command.member.remove")(
+ function* (options: {
+ readonly member: Option.Option<string>;
+ readonly yes: boolean;
+ }) {
+ const workspaceId = yield* resolveWorkspaceId();
+ const [members, me, allowed] = yield* withSpinner("Loading members")(
+ Effect.all(
+ [
+ Effect.map(listOrganizationMembers(workspaceId), (list) =>
+ list.map(toMemberJson),
+ ),
+ getCurrentUser(),
+ hasWorkspacePermission(workspaceId, { member: ["delete"] }),
+ ],
+ { concurrency: 3 },
+ ),
+ );
+ const target = yield* chooseMember(members, options.member, {
+ question: "Remove which member?",
+ example: "kaneo member remove [email protected]",
+ });
+ if (target.id === me.id) {
+ return yield* new InvalidArgument({
+ message: "You cannot remove yourself.",
+ hint: "Run kaneo workspace leave <workspace> to leave it.",
+ });
+ }
+ const mine = members.find((member) => member.id === me.id);
+ if (
+ hasRole(target.role, "owner") &&
+ !(mine && hasRole(mine.role, "owner"))
+ ) {
+ return yield* new PermissionDenied({
+ message: `Only an owner can remove ${target.name}, who is an owner.`,
+ missingPermissions: [],
+ });
+ }
+ if (!allowed) {
+ return yield* new PermissionDenied({
+ message: "You are not allowed to remove members from this workspace.",
+ missingPermissions: ["member:delete"],
+ });
+ }
+
+ yield* confirmDestructive({
+ yes: options.yes,
+ action: `Removing ${target.name}`,
+ question: `Remove ${target.name} (${target.email}) from the workspace? They lose access to its projects and tasks.`,
+ });
+
+ yield* withSpinner(`Removing ${target.name}`)(
+ removeOrganizationMember(workspaceId, target.memberId),
+ ).pipe(
+ Effect.catchTag("InvalidRequest", (error) =>
+ Effect.fail(
+ /only owner/i.test(error.message)
+ ? new InvalidArgument({
+ message: `${target.name} is the only owner, so they cannot be removed.`,
+ hint: `Make another member an owner first with kaneo member role <member> owner.`,
+ })
+ : error,
+ ),
+ ),
+ );
+
+ yield* emit({ ...target, removed: true }, renderMemberRemoved);
+ },
+);
+
+export const memberRemove = Command.make(
+ "remove",
+ {
+ member: Argument.String("member").pipe(
+ Argument.withDescription(
+ "Email address, name or id; asked for when omitted in a terminal",
+ ),
+ Argument.optional,
+ ),
+ yes: Flag.Boolean("yes").pipe(
+ Flag.withAlias("y"),
+ Flag.withDescription("Remove without asking for confirmation"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runMemberRemove(options),
+).pipe(
+ Command.withDescription("Remove someone from the workspace"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/member/role.ts b/packages/cli/src/commands/member/role.ts
new file mode 100644
index 000000000..e738729d1
--- /dev/null
+++ b/packages/cli/src/commands/member/role.ts
@@ -0,0 +1,119 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { chooseMember } from "../../admin/choose-member.js";
+import { toMemberJson } from "../../admin/member-json.js";
+import { renderMemberRole } from "../../admin/render-member-change.js";
+import { resolveRole } from "../../admin/resolve-role.js";
+import { hasRole, isDemotion, roleLabel } from "../../admin/roles.js";
+import { getCurrentUser } from "../../api/endpoints.js";
+import {
+ listOrganizationMembers,
+ updateOrganizationMemberRole,
+} from "../../api/members.js";
+import { InvalidArgument, PermissionDenied } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { confirmDestructive } from "../../prompts/confirm-destructive.js";
+import { resolveWorkspaceId } from "../../services/selection.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runMemberRole = Effect.fn("command.member.role")(
+ function* (options: {
+ readonly member: Option.Option<string>;
+ readonly role: Option.Option<string>;
+ readonly yes: boolean;
+ }) {
+ const workspaceId = yield* resolveWorkspaceId();
+ const [members, me] = yield* withSpinner("Loading members")(
+ Effect.all(
+ [
+ Effect.map(listOrganizationMembers(workspaceId), (list) =>
+ list.map(toMemberJson),
+ ),
+ getCurrentUser(),
+ ],
+ { concurrency: 2 },
+ ),
+ );
+ const target = yield* chooseMember(members, options.member, {
+ question: "Change the role of",
+ example: "kaneo member role [email protected] admin",
+ });
+ const role = yield* resolveRole(workspaceId, options.role, {
+ question: `New role for ${target.name}`,
+ example: `kaneo member role ${target.email} admin`,
+ });
+ const result = { ...target, role, previousRole: target.role };
+
+ if (role !== target.role) {
+ if (isDemotion(target.role, role)) {
+ const self = target.id === me.id;
+ yield* confirmDestructive({
+ yes: options.yes,
+ action: `Changing ${self ? "your own role" : `the role of ${target.name}`} from ${roleLabel(target.role)}`,
+ question: self
+ ? `Change your own role from ${roleLabel(target.role)} to ${roleLabel(role)}? You may lose access to workspace settings.`
+ : `Change ${target.name} from ${roleLabel(target.role)} to ${roleLabel(role)}?`,
+ });
+ }
+ const ownerChange = hasRole(target.role, "owner") || role === "owner";
+ yield* withSpinner(`Updating ${target.name}`)(
+ updateOrganizationMemberRole(workspaceId, target.memberId, role),
+ ).pipe(
+ Effect.catchTags({
+ InvalidRequest: (error) =>
+ Effect.fail(
+ /without an owner/i.test(error.message)
+ ? new InvalidArgument({
+ message: "The workspace needs at least one owner.",
+ hint: "Make another member an owner first with kaneo member role <member> owner.",
+ })
+ : error,
+ ),
+ PermissionDenied: (error) =>
+ Effect.fail(
+ /not allowed to update this member/i.test(error.message)
+ ? new PermissionDenied({
+ message: ownerChange
+ ? "Only an owner can change an owner's role or make someone an owner."
+ : "You are not allowed to change roles in this workspace.",
+ missingPermissions: ownerChange ? [] : ["member:update"],
+ })
+ : error,
+ ),
+ }),
+ );
+ }
+
+ yield* emit(result, renderMemberRole);
+ },
+);
+
+export const memberRole = Command.make(
+ "role",
+ {
+ member: Argument.String("member").pipe(
+ Argument.withDescription(
+ "Email address, name or id; asked for when omitted in a terminal",
+ ),
+ Argument.optional,
+ ),
+ role: Argument.String("role").pipe(
+ Argument.withDescription(
+ "owner, admin, member, viewer, or a custom role of the workspace",
+ ),
+ Argument.optional,
+ ),
+ yes: Flag.Boolean("yes").pipe(
+ Flag.withAlias("y"),
+ Flag.withDescription(
+ "Demote an owner or admin without asking for confirmation",
+ ),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runMemberRole(options),
+).pipe(
+ Command.withDescription("Change the role of a workspace member"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/notification/index.ts b/packages/cli/src/commands/notification/index.ts
new file mode 100644
index 000000000..c2e863c18
--- /dev/null
+++ b/packages/cli/src/commands/notification/index.ts
@@ -0,0 +1,9 @@
+import { Command } from "effect/cli";
+import { notificationList } from "./list.js";
+import { notificationRead } from "./read.js";
+
+export const notification = Command.make("notification").pipe(
+ Command.withDescription("Read your notifications"),
+ Command.withAlias("inbox"),
+ Command.withSubcommands([notificationList, notificationRead]),
+);
diff --git a/packages/cli/src/commands/notification/list.ts b/packages/cli/src/commands/notification/list.ts
new file mode 100644
index 000000000..4ab636716
--- /dev/null
+++ b/packages/cli/src/commands/notification/list.ts
@@ -0,0 +1,80 @@
+import { Effect, Option } from "effect";
+import { Command, Flag } from "effect/cli";
+import {
+ listNotifications,
+ NOTIFICATION_PAGE_CAP,
+} from "../../api/notifications.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { Session } from "../../services/session.js";
+import { lookupNotificationTasks } from "../../notifications/lookup-notification-tasks.js";
+import { normalizeNotification } from "../../notifications/normalize-notification.js";
+import { toNotificationJson } from "../../notifications/notification-json.js";
+import { renderNotificationList } from "../../notifications/render-notification-list.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runNotificationList = Effect.fn("command.notification.list")(
+ function* (options: { readonly unread: boolean; readonly limit: number }) {
+ if (options.limit < 1) {
+ return yield* new InvalidArgument({
+ message: "--limit must be at least 1.",
+ });
+ }
+ const session = yield* Session;
+ const workspaceId = Option.getOrUndefined(session.workspace)?.id;
+ const { raw, shown, lookup } = yield* withSpinner("Loading notifications")(
+ Effect.gen(function* () {
+ const raw = yield* listNotifications(workspaceId);
+ const views = raw.map(normalizeNotification);
+ const matching = options.unread
+ ? views.filter((view) => !view.read)
+ : views;
+ const shown = matching.slice(0, options.limit);
+ const lookup = yield* lookupNotificationTasks(shown);
+ return { raw, shown, lookup, matching };
+ }),
+ );
+ const notifications = shown.map((view) =>
+ toNotificationJson(view, lookup, session.webUrl),
+ );
+ const matchingCount = options.unread
+ ? raw.filter((item) => item.isRead !== true).length
+ : raw.length;
+
+ yield* emit(notifications, (ui) =>
+ renderNotificationList(ui, {
+ notifications,
+ unreadOnly: options.unread,
+ unreadCount: raw.filter((item) => item.isRead !== true).length,
+ hidden: matchingCount - notifications.length,
+ capped: raw.length >= NOTIFICATION_PAGE_CAP,
+ now: new Date(),
+ }),
+ );
+ },
+);
+
+export const notificationList = Command.make(
+ "list",
+ {
+ unread: Flag.Boolean("unread").pipe(
+ Flag.withAlias("u"),
+ Flag.withDescription("Only unread notifications"),
+ Flag.withDefault(false),
+ ),
+ limit: Flag.Int("limit").pipe(
+ Flag.withAlias("L"),
+ Flag.withDescription(
+ `Maximum number to show (the server keeps the latest ${NOTIFICATION_PAGE_CAP})`,
+ ),
+ Flag.withDefault(20),
+ ),
+ },
+ (options) => runNotificationList(options),
+).pipe(
+ Command.withDescription(
+ "List your latest notifications, in the selected workspace if there is one",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/notification/read.ts b/packages/cli/src/commands/notification/read.ts
new file mode 100644
index 000000000..7e5891e17
--- /dev/null
+++ b/packages/cli/src/commands/notification/read.ts
@@ -0,0 +1,121 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import {
+ listNotifications,
+ markAllNotificationsRead,
+ markNotificationRead,
+} from "../../api/notifications.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import { pick } from "../../prompts/pick.js";
+import { matchNotificationId } from "../../notifications/match-notification.js";
+import { normalizeNotification } from "../../notifications/normalize-notification.js";
+import { relativeTime } from "../../notifications/relative-time.js";
+import { renderNotificationsRead } from "../../notifications/render-notifications-read.js";
+import { Session } from "../../services/session.js";
+import { ApiLayer } from "../api-layer.js";
+
+const markAll = Effect.fnUntraced(function* () {
+ const session = yield* Session;
+ const workspaceId = Option.getOrUndefined(session.workspace)?.id ?? null;
+ yield* withSpinner("Marking all notifications read")(
+ markAllNotificationsRead(workspaceId ?? undefined),
+ );
+ yield* emit({ all: true, ids: [] as string[], workspaceId }, (ui) =>
+ renderNotificationsRead(ui, { all: true, count: 0 }),
+ );
+});
+
+const chooseUnread = Effect.fnUntraced(function* () {
+ const session = yield* Session;
+ const raw = yield* withSpinner("Loading notifications")(
+ listNotifications(Option.getOrUndefined(session.workspace)?.id),
+ );
+ const unread = raw.map(normalizeNotification).filter((view) => !view.read);
+ if (unread.length === 0) {
+ return yield* new InvalidArgument({
+ message: "You have no unread notifications.",
+ });
+ }
+ const now = new Date();
+ const id = yield* pick(
+ "Mark which notification read",
+ unread.map((view) => ({
+ title: view.message ? `${view.title}: ${view.message}` : view.title,
+ value: view.id,
+ description: relativeTime(view.createdAt, now),
+ })),
+ );
+ return [id];
+});
+
+export const runNotificationRead = Effect.fn("command.notification.read")(
+ function* (options: {
+ readonly ids: ReadonlyArray<string>;
+ readonly all: boolean;
+ }) {
+ if (options.all && options.ids.length > 0) {
+ return yield* new InvalidArgument({
+ message: "Pass notification ids or --all, not both.",
+ });
+ }
+ if (options.all) return yield* markAll();
+ const output = yield* Output;
+ let ids: ReadonlyArray<string>;
+ if (options.ids.length > 0) {
+ const known = yield* withSpinner("Loading notifications")(
+ listNotifications(undefined),
+ );
+ ids = yield* Effect.forEach(options.ids, (reference) =>
+ Effect.fromResult(
+ matchNotificationId(
+ known.map((item) => item.id),
+ reference,
+ ),
+ ),
+ );
+ } else if (output.interactive) {
+ ids = yield* chooseUnread();
+ } else {
+ return yield* new InvalidArgument({
+ message: "Which notifications should be marked read?",
+ hint: "Pass ids from kaneo notification list, or --all.",
+ });
+ }
+ const unique = [...new Set(ids)];
+ yield* withSpinner("Marking notifications read")(
+ Effect.forEach(unique, (id) => markNotificationRead(id), {
+ concurrency: 4,
+ discard: true,
+ }),
+ );
+ yield* emit({ all: false, ids: unique, workspaceId: null }, (ui) =>
+ renderNotificationsRead(ui, { all: false, count: unique.length }),
+ );
+ },
+);
+
+export const notificationRead = Command.make(
+ "read",
+ {
+ ids: Argument.String("id").pipe(
+ Argument.withDescription(
+ "Notification ids or the short ids from kaneo notification list",
+ ),
+ Argument.variadic(),
+ ),
+ all: Flag.Boolean("all").pipe(
+ Flag.withAlias("a"),
+ Flag.withDescription(
+ "Mark every notification read, in the selected workspace if there is one",
+ ),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runNotificationRead(options),
+).pipe(
+ Command.withDescription("Mark notifications as read"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/profile/index.ts b/packages/cli/src/commands/profile/index.ts
new file mode 100644
index 000000000..d3a65ff5d
--- /dev/null
+++ b/packages/cli/src/commands/profile/index.ts
@@ -0,0 +1,15 @@
+import { Command } from "effect/cli";
+import { profileList } from "./list.js";
+import { profileRemove } from "./remove.js";
+import { profileRename } from "./rename.js";
+import { profileUse } from "./use.js";
+
+export const profile = Command.make("profile").pipe(
+ Command.withDescription("Manage stored logins"),
+ Command.withSubcommands([
+ profileList,
+ profileUse,
+ profileRename,
+ profileRemove,
+ ]),
+);
diff --git a/packages/cli/src/commands/profile/list.ts b/packages/cli/src/commands/profile/list.ts
new file mode 100644
index 000000000..303026071
--- /dev/null
+++ b/packages/cli/src/commands/profile/list.ts
@@ -0,0 +1,22 @@
+import { Effect } from "effect";
+import { Command } from "effect/cli";
+import { ConfigStore } from "../../config/config-store.js";
+import { emit } from "../../output/emit.js";
+import { Session } from "../../services/session.js";
+import { ApiLayer } from "../api-layer.js";
+import { listProfiles } from "./profile-config.js";
+import { renderProfileList } from "./render-profile-list.js";
+
+export const runProfileList = Effect.fn("command.profile.list")(function* () {
+ const session = yield* Session;
+ const store = yield* ConfigStore;
+ const config = yield* store.load;
+ yield* emit(listProfiles(config, session.profileName), renderProfileList);
+});
+
+export const profileList = Command.make("list", {}, () =>
+ runProfileList(),
+).pipe(
+ Command.withDescription("List stored logins and the server and user of each"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/profile/profile-config.test.ts b/packages/cli/src/commands/profile/profile-config.test.ts
new file mode 100644
index 000000000..e19fd42cc
--- /dev/null
+++ b/packages/cli/src/commands/profile/profile-config.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { ConfigFile } from "../../config/format.js";
+import { makeUi } from "../../render/ui.js";
+import {
+ listProfiles,
+ removeProfile,
+ renameProfile,
+ useProfile,
+} from "./profile-config.js";
+import { renderProfileList } from "./render-profile-list.js";
+
+const config: ConfigFile = {
+ kind: "kaneo-cli",
+ version: 1,
+ activeProfile: "work",
+ profiles: {
+ work: {
+ apiUrl: "https://cloud.kaneo.app",
+ token: "secret-token",
+ user: { id: "u1", name: "Ada Lovelace", email: "[email protected]" },
+ },
+ home: { apiUrl: "http://localhost:1337" },
+ },
+};
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+describe("profile config", () => {
+ it("lists profiles without tokens and marks the active one", () => {
+ const profiles = listProfiles(config, "work");
+ expect(JSON.stringify(profiles)).not.toContain("secret-token");
+ expect(
+ profiles.map((profile) => [
+ profile.name,
+ profile.active,
+ profile.signedIn,
+ ]),
+ ).toEqual([
+ ["work", true, true],
+ ["home", false, false],
+ ]);
+ expect(renderProfileList(ui, profiles)).toEqual([
+ "",
+ " ● work cloud.kaneo.app Ada Lovelace · [email protected]",
+ " home localhost:1337 signed out",
+ "",
+ ]);
+ });
+
+ it("switches only to stored profiles", () => {
+ expect(useProfile(config, "home")?.activeProfile).toBe("home");
+ expect(useProfile(config, "nope")).toBeUndefined();
+ });
+
+ it("removes a profile and moves the active one", () => {
+ const removed = removeProfile(config, "work");
+ expect(removed?.activeProfile).toBe("home");
+ expect(Object.keys(removed?.profiles ?? {})).toEqual(["home"]);
+ expect(removeProfile(config, "home")?.activeProfile).toBe("work");
+ });
+
+ it("renames in place and keeps the active profile", () => {
+ const renamed = renameProfile(config, "work", "acme");
+ expect(renamed.kind === "renamed" && renamed.config.activeProfile).toBe(
+ "acme",
+ );
+ expect(
+ renamed.kind === "renamed" && Object.keys(renamed.config.profiles),
+ ).toEqual(["acme", "home"]);
+ expect(renameProfile(config, "work", "home").kind).toBe("taken");
+ expect(renameProfile(config, "nope", "x").kind).toBe("missing");
+ });
+});
diff --git a/packages/cli/src/commands/profile/profile-config.ts b/packages/cli/src/commands/profile/profile-config.ts
new file mode 100644
index 000000000..abd77c4b1
--- /dev/null
+++ b/packages/cli/src/commands/profile/profile-config.ts
@@ -0,0 +1,92 @@
+import {
+ type ConfigFile,
+ DEFAULT_PROFILE,
+ type Profile,
+} from "../../config/format.js";
+
+export type ProfileJson = {
+ readonly name: string;
+ readonly active: boolean;
+ readonly apiUrl: string;
+ readonly webUrl: string | null;
+ readonly signedIn: boolean;
+ readonly user: {
+ readonly id: string;
+ readonly name: string;
+ readonly email: string;
+ } | null;
+ readonly workspaceId: string | null;
+};
+
+export function toProfileJson(
+ name: string,
+ profile: Profile,
+ active: boolean,
+): ProfileJson {
+ return {
+ name,
+ active,
+ apiUrl: profile.apiUrl,
+ webUrl: profile.webUrl ?? null,
+ signedIn: Boolean(profile.token),
+ user: profile.user ?? null,
+ workspaceId: profile.workspaceId ?? null,
+ };
+}
+
+export function listProfiles(
+ config: ConfigFile,
+ activeName: string,
+): ReadonlyArray<ProfileJson> {
+ return Object.entries(config.profiles).map(([name, profile]) =>
+ toProfileJson(name, profile, name === activeName),
+ );
+}
+
+export function useProfile(
+ config: ConfigFile,
+ name: string,
+): ConfigFile | undefined {
+ return config.profiles[name] ? { ...config, activeProfile: name } : undefined;
+}
+
+export function removeProfile(
+ config: ConfigFile,
+ name: string,
+): ConfigFile | undefined {
+ if (!config.profiles[name]) return undefined;
+ const { [name]: _removed, ...profiles } = config.profiles;
+ const activeProfile =
+ config.activeProfile === name
+ ? (Object.keys(profiles)[0] ?? DEFAULT_PROFILE)
+ : config.activeProfile;
+ return { ...config, activeProfile, profiles };
+}
+
+export type RenamedProfile =
+ | { readonly kind: "renamed"; readonly config: ConfigFile }
+ | { readonly kind: "missing" }
+ | { readonly kind: "taken" };
+
+export function renameProfile(
+ config: ConfigFile,
+ from: string,
+ to: string,
+): RenamedProfile {
+ if (!config.profiles[from]) return { kind: "missing" };
+ if (from !== to && config.profiles[to]) return { kind: "taken" };
+ const profiles = Object.fromEntries(
+ Object.entries(config.profiles).map(([name, profile]) => [
+ name === from ? to : name,
+ profile,
+ ]),
+ );
+ return {
+ kind: "renamed",
+ config: {
+ ...config,
+ activeProfile: config.activeProfile === from ? to : config.activeProfile,
+ profiles,
+ },
+ };
+}
diff --git a/packages/cli/src/commands/profile/remove.ts b/packages/cli/src/commands/profile/remove.ts
new file mode 100644
index 000000000..ebfce600d
--- /dev/null
+++ b/packages/cli/src/commands/profile/remove.ts
@@ -0,0 +1,96 @@
+import { Effect } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { ConfigStore } from "../../config/config-store.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { confirmDestructive } from "../../prompts/confirm-destructive.js";
+import type { Ui } from "../../render/ui.js";
+import { ApiLayer } from "../api-layer.js";
+import { removeProfile } from "./profile-config.js";
+import { signOutProfile } from "./sign-out-profile.js";
+
+type RemovedProfile = {
+ readonly removed: string;
+ readonly apiUrl: string;
+ readonly signedOut: boolean;
+ readonly activeProfile: string;
+};
+
+function host(url: string): string {
+ try {
+ return new URL(url).host;
+ } catch {
+ return url;
+ }
+}
+
+export function renderProfileRemoved(ui: Ui, result: RemovedProfile): string[] {
+ const { theme, glyphs } = ui;
+ const detail = result.signedOut
+ ? ` ${theme.muted(`${glyphs.separator} signed out of ${host(result.apiUrl)}`)}`
+ : "";
+ return [
+ ` ${theme.success(glyphs.tick)} Removed profile ${theme.strong(result.removed)}${detail}`,
+ ];
+}
+
+export const runProfileRemove = Effect.fn("command.profile.remove")(
+ function* (options: { readonly name: string; readonly yes: boolean }) {
+ const store = yield* ConfigStore;
+ const config = yield* store.load;
+ const profile = config.profiles[options.name];
+ const updated = removeProfile(config, options.name);
+ if (!profile || !updated) {
+ const names = Object.keys(config.profiles);
+ return yield* new InvalidArgument({
+ message: `There is no profile named "${options.name}".`,
+ hint:
+ names.length > 0
+ ? `Stored profiles: ${names.join(", ")}.`
+ : "There are no stored logins.",
+ });
+ }
+
+ yield* confirmDestructive({
+ yes: options.yes,
+ action: `Removing the profile ${options.name}`,
+ question: `Remove the stored login ${options.name} for ${host(profile.apiUrl)}?`,
+ });
+
+ const signedOut = profile.token
+ ? yield* withSpinner(`Signing out of ${host(profile.apiUrl)}`)(
+ signOutProfile(profile.apiUrl, profile.token),
+ )
+ : false;
+ yield* store.save(updated);
+
+ yield* emit<RemovedProfile>(
+ {
+ removed: options.name,
+ apiUrl: profile.apiUrl,
+ signedOut,
+ activeProfile: updated.activeProfile,
+ },
+ renderProfileRemoved,
+ );
+ },
+);
+
+export const profileRemove = Command.make(
+ "remove",
+ {
+ name: Argument.String("name").pipe(
+ Argument.withDescription("Profile name"),
+ ),
+ yes: Flag.Boolean("yes").pipe(
+ Flag.withAlias("y"),
+ Flag.withDescription("Remove without asking for confirmation"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runProfileRemove(options),
+).pipe(
+ Command.withDescription("Sign out of a stored login and forget it"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/profile/rename.ts b/packages/cli/src/commands/profile/rename.ts
new file mode 100644
index 000000000..e4b3cdc50
--- /dev/null
+++ b/packages/cli/src/commands/profile/rename.ts
@@ -0,0 +1,76 @@
+import { Effect } from "effect";
+import { Argument, Command } from "effect/cli";
+import { ConfigStore } from "../../config/config-store.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import type { Ui } from "../../render/ui.js";
+import { ApiLayer } from "../api-layer.js";
+import { renameProfile } from "./profile-config.js";
+
+type RenamedProfileResult = {
+ readonly from: string;
+ readonly to: string;
+ readonly active: boolean;
+};
+
+export function renderProfileRenamed(
+ ui: Ui,
+ result: RenamedProfileResult,
+): string[] {
+ const { theme, glyphs } = ui;
+ return [
+ ` ${theme.success(glyphs.tick)} Renamed profile ${result.from} to ${theme.strong(result.to)}`,
+ ];
+}
+
+export const runProfileRename = Effect.fn("command.profile.rename")(
+ function* (options: { readonly from: string; readonly to: string }) {
+ const store = yield* ConfigStore;
+ const to = options.to.trim();
+ if (to === "" || /\s/.test(to)) {
+ return yield* new InvalidArgument({
+ message: "Profile names cannot be empty or contain spaces.",
+ hint: "Use a short name such as work or acme.",
+ });
+ }
+ const config = yield* store.load;
+ const renamed = renameProfile(config, options.from, to);
+ if (renamed.kind === "missing") {
+ return yield* new InvalidArgument({
+ message: `There is no profile named "${options.from}".`,
+ hint: "Run kaneo profile list to see the stored profiles.",
+ });
+ }
+ if (renamed.kind === "taken") {
+ return yield* new InvalidArgument({
+ message: `A profile named "${to}" already exists.`,
+ hint: `Pick another name, or remove it first with kaneo profile remove ${to}.`,
+ });
+ }
+ yield* store.save(renamed.config);
+ yield* emit<RenamedProfileResult>(
+ {
+ from: options.from,
+ to,
+ active: renamed.config.activeProfile === to,
+ },
+ renderProfileRenamed,
+ );
+ },
+);
+
+export const profileRename = Command.make(
+ "rename",
+ {
+ from: Argument.String("old").pipe(
+ Argument.withDescription("Current profile name"),
+ ),
+ to: Argument.String("new").pipe(
+ Argument.withDescription("New profile name"),
+ ),
+ },
+ (options) => runProfileRename(options),
+).pipe(
+ Command.withDescription("Rename a stored login"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/profile/render-profile-list.ts b/packages/cli/src/commands/profile/render-profile-list.ts
new file mode 100644
index 000000000..ece303c36
--- /dev/null
+++ b/packages/cli/src/commands/profile/render-profile-list.ts
@@ -0,0 +1,65 @@
+import { type Cell, text } from "../../render/cell.js";
+import { type Column, renderTable } from "../../render/table.js";
+import type { Ui } from "../../render/ui.js";
+import type { ProfileJson } from "./profile-config.js";
+
+function host(url: string): string {
+ try {
+ return new URL(url).host;
+ } catch {
+ return url;
+ }
+}
+
+export function renderProfileList(
+ ui: Ui,
+ profiles: ReadonlyArray<ProfileJson>,
+): string[] {
+ const { theme, glyphs } = ui;
+ if (profiles.length === 0) {
+ return [
+ "",
+ ` ${theme.muted("No stored logins yet. Run kaneo login to add one.")}`,
+ "",
+ ];
+ }
+ const columns: Array<Column<ProfileJson>> = [
+ {
+ header: "",
+ cell: (profile): Cell =>
+ profile.active ? [text(glyphs.dot, theme.success)] : [],
+ },
+ {
+ header: "Profile",
+ cell: (profile) => [
+ text(profile.name, profile.active ? theme.strong : undefined),
+ ],
+ },
+ {
+ header: "Server",
+ optional: true,
+ cell: (profile) => [text(host(profile.apiUrl), theme.muted)],
+ },
+ {
+ header: "User",
+ flex: true,
+ minWidth: 12,
+ cell: (profile): Cell => {
+ if (!profile.signedIn) return [text("signed out", theme.muted)];
+ if (!profile.user) return [text("signed in")];
+ return [
+ text(profile.user.name),
+ text(` ${glyphs.separator} ${profile.user.email}`, theme.muted),
+ ];
+ },
+ },
+ ];
+ return [
+ "",
+ ...renderTable(ui, profiles, columns, {
+ width: ui.caps.columns,
+ indent: 2,
+ }),
+ "",
+ ];
+}
diff --git a/packages/cli/src/commands/profile/sign-out-profile.ts b/packages/cli/src/commands/profile/sign-out-profile.ts
new file mode 100644
index 000000000..4a5846388
--- /dev/null
+++ b/packages/cli/src/commands/profile/sign-out-profile.ts
@@ -0,0 +1,22 @@
+import { normalizeBaseUrl } from "@kaneo/mcp/normalize-base-url";
+import { Duration, Effect } from "effect";
+import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
+
+export const signOutProfile = (apiUrl: string, token: string) =>
+ Effect.gen(function* () {
+ const client = yield* HttpClient.HttpClient;
+ const request = HttpClientRequest.post(
+ `${normalizeBaseUrl(apiUrl)}/api/auth/sign-out`,
+ ).pipe(
+ HttpClientRequest.bearerToken(token),
+ HttpClientRequest.acceptJson,
+ HttpClientRequest.bodyJsonUnsafe({}),
+ );
+ const response = yield* client
+ .execute(request)
+ .pipe(Effect.timeout(Duration.seconds(10)));
+ return response.status >= 200 && response.status < 300;
+ }).pipe(
+ Effect.orElseSucceed(() => false),
+ Effect.provide(FetchHttpClient.layer),
+ );
diff --git a/packages/cli/src/commands/profile/use.ts b/packages/cli/src/commands/profile/use.ts
new file mode 100644
index 000000000..98587b990
--- /dev/null
+++ b/packages/cli/src/commands/profile/use.ts
@@ -0,0 +1,108 @@
+import { Effect, Option } from "effect";
+import { Argument, Command } from "effect/cli";
+import { ConfigStore } from "../../config/config-store.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit, note } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { pick } from "../../prompts/pick.js";
+import type { Ui } from "../../render/ui.js";
+import { CliEnvironment } from "../../services/cli-environment.js";
+import { ApiLayer } from "../api-layer.js";
+import {
+ listProfiles,
+ type ProfileJson,
+ toProfileJson,
+ useProfile,
+} from "./profile-config.js";
+
+function host(url: string): string {
+ try {
+ return new URL(url).host;
+ } catch {
+ return url;
+ }
+}
+
+export function renderProfileUsed(
+ ui: Ui,
+ result: { readonly profile: ProfileJson },
+): string[] {
+ const { theme, glyphs } = ui;
+ const { profile } = result;
+ const user = profile.user
+ ? ` ${theme.muted(glyphs.separator)} ${profile.user.name}`
+ : "";
+ return [
+ ` ${theme.success(glyphs.tick)} Using profile ${theme.strong(profile.name)} ${theme.muted(glyphs.separator)} ${host(profile.apiUrl)}${user}`,
+ ];
+}
+
+export const runProfileUse = Effect.fn("command.profile.use")(
+ function* (options: { readonly name: Option.Option<string> }) {
+ const store = yield* ConfigStore;
+ const output = yield* Output;
+ const environment = yield* CliEnvironment;
+ const config = yield* store.load;
+ const names = Object.keys(config.profiles);
+
+ if (names.length === 0) {
+ return yield* new InvalidArgument({
+ message: "There are no stored logins yet.",
+ hint: "Run kaneo login to add one.",
+ });
+ }
+ const name = Option.isSome(options.name)
+ ? options.name.value
+ : output.interactive
+ ? yield* pick(
+ "Switch to which profile?",
+ listProfiles(config, config.activeProfile).map((profile) => ({
+ title: profile.name,
+ value: profile.name,
+ description: profile.user
+ ? `${host(profile.apiUrl)} ${output.ui.glyphs.separator} ${profile.user.email}`
+ : host(profile.apiUrl),
+ })),
+ )
+ : yield* new InvalidArgument({
+ message: "Which profile should be used?",
+ hint: `Pass its name, for example kaneo profile use ${names[0]}. Run kaneo profile list to see them.`,
+ });
+
+ const updated = useProfile(config, name);
+ const profile = updated?.profiles[name];
+ if (!updated || !profile) {
+ return yield* new InvalidArgument({
+ message: `There is no profile named "${name}".`,
+ hint: `Stored profiles: ${names.join(", ")}.`,
+ });
+ }
+ yield* store.save(updated);
+ yield* emit(
+ { profile: toProfileJson(name, profile, true) },
+ renderProfileUsed,
+ );
+
+ const override = environment.env.KANEO_PROFILE?.trim();
+ if (override && override !== name) {
+ yield* note((ui) => [
+ ` ${ui.theme.warning(ui.glyphs.warning)} KANEO_PROFILE is set to ${override} and is used instead until you unset it.`,
+ "",
+ ]);
+ }
+ },
+);
+
+export const profileUse = Command.make(
+ "use",
+ {
+ name: Argument.String("name").pipe(
+ Argument.withDescription("Profile name"),
+ Argument.optional,
+ ),
+ },
+ (options) => runProfileUse(options),
+).pipe(
+ Command.withDescription("Switch the stored login your commands use"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/project/archive.ts b/packages/cli/src/commands/project/archive.ts
new file mode 100644
index 000000000..33e681202
--- /dev/null
+++ b/packages/cli/src/commands/project/archive.ts
@@ -0,0 +1,28 @@
+import { Effect, type Option } from "effect";
+import { Argument, Command } from "effect/cli";
+import { setArchived } from "../../projects-write/set-archived.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runProjectArchive = Effect.fn("command.project.archive")(
+ function* (options: { readonly project: Option.Option<string> }) {
+ yield* setArchived(options.project, true);
+ },
+);
+
+export const projectArchive = Command.make(
+ "archive",
+ {
+ project: Argument.String("project").pipe(
+ Argument.withDescription(
+ "Project key or id, for example KAN (default: the linked project)",
+ ),
+ Argument.optional,
+ ),
+ },
+ (options) => runProjectArchive(options),
+).pipe(
+ Command.withDescription(
+ "Hide a project from the project list without deleting it",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/project/create.ts b/packages/cli/src/commands/project/create.ts
new file mode 100644
index 000000000..39b6a96e1
--- /dev/null
+++ b/packages/cli/src/commands/project/create.ts
@@ -0,0 +1,175 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag, Prompt } from "effect/cli";
+import { createProject, updateProject } from "../../api/project-writes.js";
+import { describeError } from "../../errors/describe.js";
+import { Cancelled, InvalidArgument } from "../../errors/errors.js";
+import { readTextInput } from "../../input/read-text-input.js";
+import { emit } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import { promptTheme } from "../../prompts/prompt-theme.js";
+import { explainKeyConflict } from "../../projects-write/key-conflict.js";
+import {
+ DEFAULT_PROJECT_ICON,
+ matchProjectIcon,
+} from "../../projects-write/project-icons.js";
+import {
+ deriveProjectKey,
+ validateProjectKey,
+} from "../../projects-write/project-key.js";
+import {
+ EMPTY_STATISTICS,
+ toProjectRecordJson,
+} from "../../projects-write/project-record-json.js";
+import { renderProjectChange } from "../../projects-write/render-project-change.js";
+import { resolveWorkspaceId } from "../../services/selection.js";
+import { Session } from "../../services/session.js";
+import { ApiLayer } from "../api-layer.js";
+
+const promptName = Effect.fnUntraced(function* () {
+ const output = yield* Output;
+ return yield* Prompt.run(
+ Prompt.String({
+ message: "Project name",
+ validate: (value) =>
+ value.trim() === ""
+ ? Effect.fail("Enter a name")
+ : Effect.succeed(value.trim()),
+ theme: promptTheme(output.ui),
+ }),
+ ).pipe(Effect.catchTag("QuitError", () => Effect.fail(new Cancelled())));
+});
+
+const resolveName = Effect.fnUntraced(function* (name: Option.Option<string>) {
+ const output = yield* Output;
+ const given = name.pipe(
+ Option.map((value) => value.trim()),
+ Option.filter((value) => value !== ""),
+ );
+ if (Option.isSome(given)) return given.value;
+ if (output.interactive) return yield* promptName();
+ return yield* new InvalidArgument({
+ message: "A project name is required.",
+ hint: 'Pass it as the first argument, for example kaneo project create "Kaneo Web".',
+ });
+});
+
+const resolveKey = (name: string, key: Option.Option<string>) =>
+ Option.match(key, {
+ onSome: (value) => Effect.fromResult(validateProjectKey(value)),
+ onNone: () => {
+ const derived = deriveProjectKey(name);
+ return derived === ""
+ ? Effect.fail(
+ new InvalidArgument({
+ message: `Could not make a project key from "${name}".`,
+ hint: "Pass one with --key, for example --key WEB.",
+ }),
+ )
+ : Effect.fromResult(validateProjectKey(derived));
+ },
+ });
+
+export const runProjectCreate = Effect.fn("command.project.create")(
+ function* (options: {
+ readonly name: Option.Option<string>;
+ readonly key: Option.Option<string>;
+ readonly description: Option.Option<string>;
+ readonly descriptionFile: Option.Option<string>;
+ readonly icon: Option.Option<string>;
+ }) {
+ const session = yield* Session;
+ const icon = yield* Option.match(options.icon, {
+ onNone: () => Effect.succeed(DEFAULT_PROJECT_ICON),
+ onSome: (value) => Effect.fromResult(matchProjectIcon(value)),
+ });
+ const description = yield* readTextInput({
+ value: options.description,
+ file: options.descriptionFile,
+ flag: "--description",
+ });
+ const workspaceId = yield* resolveWorkspaceId();
+ const name = yield* resolveName(options.name);
+ const key = yield* resolveKey(name, options.key);
+
+ const created = yield* withSpinner(`Creating ${name}`)(
+ createProject({ workspaceId, name, slug: key, icon }),
+ ).pipe(
+ Effect.catchTag("Conflict", (conflict) =>
+ explainKeyConflict(conflict, { workspaceId, name, key }),
+ ),
+ );
+
+ const text = Option.getOrElse(description, () => "");
+ const project =
+ text.trim() === ""
+ ? created
+ : yield* withSpinner("Saving the description")(
+ updateProject(created.id, {
+ name: created.name,
+ icon: created.icon ?? icon,
+ slug: created.slug,
+ description: text,
+ isPublic: created.isPublic ?? false,
+ }),
+ ).pipe(
+ Effect.mapError(
+ (error) =>
+ new InvalidArgument({
+ message: `Created ${created.name} (${created.slug.toUpperCase()}), but could not save its description: ${describeError(error).message}`,
+ hint: `Set it with kaneo project edit ${created.slug.toUpperCase()} --description-file <path>.`,
+ }),
+ ),
+ );
+
+ yield* emit(
+ toProjectRecordJson(project, EMPTY_STATISTICS, session.webUrl),
+ (ui, json) =>
+ renderProjectChange(ui, {
+ verb: "Created",
+ name: json.name,
+ key: json.key,
+ url: json.url,
+ }),
+ );
+ },
+);
+
+export const projectCreate = Command.make(
+ "create",
+ {
+ name: Argument.String("name").pipe(
+ Argument.withDescription(
+ "Project name; asked for when omitted in a terminal",
+ ),
+ Argument.optional,
+ ),
+ key: Flag.String("key").pipe(
+ Flag.withAlias("k"),
+ Flag.withDescription(
+ "Task id prefix such as KAN (default: made from the name, like the web app)",
+ ),
+ Flag.optional,
+ ),
+ description: Flag.String("description").pipe(
+ Flag.withAlias("d"),
+ Flag.withDescription("Description in Markdown, or - to read stdin"),
+ Flag.optional,
+ ),
+ descriptionFile: Flag.String("description-file").pipe(
+ Flag.withAlias("F"),
+ Flag.withDescription("Read the description from a file, or - for stdin"),
+ Flag.optional,
+ ),
+ icon: Flag.String("icon").pipe(
+ Flag.withDescription(
+ "Lucide icon name from the web app, for example Rocket (default: Layout)",
+ ),
+ Flag.optional,
+ ),
+ },
+ (options) => runProjectCreate(options),
+).pipe(
+ Command.withDescription("Create a project with the default columns"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/project/delete.ts b/packages/cli/src/commands/project/delete.ts
new file mode 100644
index 000000000..f92ade7a1
--- /dev/null
+++ b/packages/cli/src/commands/project/delete.ts
@@ -0,0 +1,88 @@
+import { Effect, type Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { deleteProject } from "../../api/project-writes.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { confirmByKey } from "../../projects-write/confirm-by-key.js";
+import { toProjectRecordJson } from "../../projects-write/project-record-json.js";
+import { renderProjectChange } from "../../projects-write/render-project-change.js";
+import { resolveProjectRecord } from "../../projects-write/resolve-project-record.js";
+import { resolveWorkspaceId } from "../../services/selection.js";
+import { Session } from "../../services/session.js";
+import { ApiLayer } from "../api-layer.js";
+
+function taskCount(count: number): string {
+ return count === 1 ? "1 task" : `${count} tasks`;
+}
+
+function contents(count: number): string {
+ return count === 0
+ ? "and its columns"
+ : `with its ${taskCount(count)}, their comments and time entries, and its columns`;
+}
+
+export const runProjectDelete = Effect.fn("command.project.delete")(
+ function* (options: {
+ readonly project: Option.Option<string>;
+ readonly yes: boolean;
+ }) {
+ const session = yield* Session;
+ const workspaceId = yield* resolveWorkspaceId();
+ const project = yield* resolveProjectRecord({
+ workspaceId,
+ reference: options.project,
+ scope: "any",
+ useContext: false,
+ prompt: "Choose a project to delete",
+ missing: "Which project should be deleted?",
+ example: "kaneo project delete KAN",
+ });
+ const key = project.slug.toUpperCase();
+
+ yield* confirmByKey({
+ yes: options.yes,
+ action: `Deleting ${project.name}`,
+ key,
+ warning: `This permanently deletes ${project.name} (${key}) ${contents(project.statistics.totalTasks)}. It cannot be undone; kaneo project archive ${key} keeps the data instead.`,
+ });
+
+ const deleted = yield* withSpinner(`Deleting ${project.name}`)(
+ deleteProject(project.id),
+ );
+ yield* emit(
+ {
+ ...toProjectRecordJson(deleted, project.statistics, session.webUrl),
+ deleted: true,
+ },
+ (ui, json) =>
+ renderProjectChange(ui, {
+ verb: "Deleted",
+ name: json.name,
+ key: json.key,
+ url: "",
+ detail: json.totalTasks > 0 ? taskCount(json.totalTasks) : undefined,
+ }),
+ );
+ },
+);
+
+export const projectDelete = Command.make(
+ "delete",
+ {
+ project: Argument.String("project").pipe(
+ Argument.withDescription("Project key or id, for example KAN"),
+ Argument.optional,
+ ),
+ yes: Flag.Boolean("yes").pipe(
+ Flag.withAlias("y"),
+ Flag.withDescription("Delete without asking for confirmation"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runProjectDelete(options),
+).pipe(
+ Command.withDescription(
+ "Permanently delete a project with all its tasks, comments and columns",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/project/edit.ts b/packages/cli/src/commands/project/edit.ts
new file mode 100644
index 000000000..f4baf73ef
--- /dev/null
+++ b/packages/cli/src/commands/project/edit.ts
@@ -0,0 +1,140 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { getProjectRecord, updateProject } from "../../api/project-writes.js";
+import { readTextInput } from "../../input/read-text-input.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { explainKeyConflict } from "../../projects-write/key-conflict.js";
+import {
+ buildProjectUpdate,
+ describeEdits,
+ parseProjectEdits,
+} from "../../projects-write/project-edits.js";
+import { toProjectRecordJson } from "../../projects-write/project-record-json.js";
+import { renderProjectChange } from "../../projects-write/render-project-change.js";
+import { resolveProjectRecord } from "../../projects-write/resolve-project-record.js";
+import { resolveWorkspaceId } from "../../services/selection.js";
+import { Session } from "../../services/session.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runProjectEdit = Effect.fn("command.project.edit")(
+ function* (options: {
+ readonly project: Option.Option<string>;
+ readonly name: Option.Option<string>;
+ readonly key: Option.Option<string>;
+ readonly description: Option.Option<string>;
+ readonly descriptionFile: Option.Option<string>;
+ readonly icon: Option.Option<string>;
+ readonly public: boolean;
+ readonly private: boolean;
+ }) {
+ const session = yield* Session;
+ const description = yield* readTextInput({
+ value: options.description,
+ file: options.descriptionFile,
+ flag: "--description",
+ });
+ const edits = yield* Effect.fromResult(
+ parseProjectEdits({
+ name: options.name,
+ key: options.key,
+ description,
+ icon: options.icon,
+ public: options.public,
+ private: options.private,
+ }),
+ );
+ const workspaceId = yield* resolveWorkspaceId();
+ const target = yield* resolveProjectRecord({
+ workspaceId,
+ reference: options.project,
+ scope: "any",
+ useContext: true,
+ prompt: "Choose a project to edit",
+ missing: "Which project should be changed?",
+ example: "kaneo project edit KAN --name Web",
+ });
+ const current = yield* withSpinner(`Loading ${target.name}`)(
+ getProjectRecord(target.id),
+ );
+ const body = buildProjectUpdate(current, edits);
+ const updated = yield* withSpinner(`Updating ${current.name}`)(
+ updateProject(current.id, body),
+ ).pipe(
+ Effect.catchTag("Conflict", (conflict) =>
+ explainKeyConflict(conflict, {
+ workspaceId,
+ name: body.name,
+ key: body.slug,
+ }),
+ ),
+ );
+
+ yield* emit(
+ toProjectRecordJson(updated, target.statistics, session.webUrl),
+ (ui, json) =>
+ renderProjectChange(ui, {
+ verb: "Updated",
+ name: json.name,
+ key: json.key,
+ url: json.url,
+ detail: describeEdits(edits),
+ }),
+ );
+ },
+);
+
+export const projectEdit = Command.make(
+ "edit",
+ {
+ project: Argument.String("project").pipe(
+ Argument.withDescription(
+ "Project key or id, for example KAN (default: the linked project)",
+ ),
+ Argument.optional,
+ ),
+ name: Flag.String("name").pipe(
+ Flag.withDescription("New name"),
+ Flag.optional,
+ ),
+ key: Flag.String("key").pipe(
+ Flag.withAlias("k"),
+ Flag.withDescription(
+ "New task id prefix; existing ticket ids change with it",
+ ),
+ Flag.optional,
+ ),
+ description: Flag.String("description").pipe(
+ Flag.withAlias("d"),
+ Flag.withDescription(
+ "New description in Markdown, or - to read stdin; replaces the current one",
+ ),
+ Flag.optional,
+ ),
+ descriptionFile: Flag.String("description-file").pipe(
+ Flag.withAlias("F"),
+ Flag.withDescription("Read the description from a file, or - for stdin"),
+ Flag.optional,
+ ),
+ icon: Flag.String("icon").pipe(
+ Flag.withDescription(
+ "Lucide icon name from the web app, for example Rocket",
+ ),
+ Flag.optional,
+ ),
+ public: Flag.Boolean("public").pipe(
+ Flag.withDescription("Let anyone with the link view the board"),
+ Flag.withDefault(false),
+ ),
+ private: Flag.Boolean("private").pipe(
+ Flag.withDescription("Only workspace members can view the board"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runProjectEdit(options),
+).pipe(
+ Command.withDescription(
+ "Change a project's name, key, description, icon or visibility",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/project/index.ts b/packages/cli/src/commands/project/index.ts
new file mode 100644
index 000000000..1e9ac3fcd
--- /dev/null
+++ b/packages/cli/src/commands/project/index.ts
@@ -0,0 +1,23 @@
+import { Command } from "effect/cli";
+import { projectArchive } from "./archive.js";
+import { projectCreate } from "./create.js";
+import { projectDelete } from "./delete.js";
+import { projectEdit } from "./edit.js";
+import { projectList } from "./list.js";
+import { projectMove } from "./move.js";
+import { projectUnarchive } from "./unarchive.js";
+import { projectView } from "./view.js";
+
+export const project = Command.make("project").pipe(
+ Command.withDescription("Create, change and inspect projects"),
+ Command.withSubcommands([
+ projectList,
+ projectView,
+ projectCreate,
+ projectEdit,
+ projectArchive,
+ projectUnarchive,
+ projectMove,
+ projectDelete,
+ ]),
+);
diff --git a/packages/cli/src/commands/project/list.ts b/packages/cli/src/commands/project/list.ts
new file mode 100644
index 000000000..ee9cea8eb
--- /dev/null
+++ b/packages/cli/src/commands/project/list.ts
@@ -0,0 +1,44 @@
+import { Effect } from "effect";
+import { Command, Flag } from "effect/cli";
+import { listProjectSummaries } from "../../api/project-summaries.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { toProjectJson } from "../../projects/project-json.js";
+import { renderProjectList } from "../../projects/render-project-list.js";
+import { resolveWorkspaceId } from "../../services/selection.js";
+import { Session } from "../../services/session.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runProjectList = Effect.fn("command.project.list")(
+ function* (options: { readonly archived: boolean }) {
+ const session = yield* Session;
+ const workspaceId = yield* resolveWorkspaceId();
+ const projects = yield* withSpinner("Loading projects")(
+ listProjectSummaries(workspaceId, { includeArchived: options.archived }),
+ );
+ const json = projects.map((project) =>
+ toProjectJson(project, session.webUrl),
+ );
+ yield* emit(json, (ui) =>
+ renderProjectList(ui, {
+ projects: json,
+ includeArchived: options.archived,
+ now: new Date(),
+ }),
+ );
+ },
+);
+
+export const projectList = Command.make(
+ "list",
+ {
+ archived: Flag.Boolean("archived").pipe(
+ Flag.withDescription("Include archived projects"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runProjectList(options),
+).pipe(
+ Command.withDescription("List the projects in your workspace"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/project/move.ts b/packages/cli/src/commands/project/move.ts
new file mode 100644
index 000000000..ee51f4f92
--- /dev/null
+++ b/packages/cli/src/commands/project/move.ts
@@ -0,0 +1,118 @@
+import { Effect, type Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { listWorkspaces } from "../../api/endpoints.js";
+import { moveProject } from "../../api/project-writes.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit, note } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { confirmDestructive } from "../../prompts/confirm-destructive.js";
+import { toProjectRecordJson } from "../../projects-write/project-record-json.js";
+import { renderProjectChange } from "../../projects-write/render-project-change.js";
+import { resolveProjectRecord } from "../../projects-write/resolve-project-record.js";
+import { resolveWorkspaceId } from "../../services/selection.js";
+import { Session } from "../../services/session.js";
+import { matchWorkspace } from "../workspace/match-workspace.js";
+import { ApiLayer } from "../api-layer.js";
+
+function taskCount(count: number): string {
+ return count === 1 ? "1 task" : `${count} tasks`;
+}
+
+export const runProjectMove = Effect.fn("command.project.move")(
+ function* (options: {
+ readonly project: Option.Option<string>;
+ readonly to: string;
+ readonly yes: boolean;
+ }) {
+ const session = yield* Session;
+ const workspaceId = yield* resolveWorkspaceId();
+ const project = yield* resolveProjectRecord({
+ workspaceId,
+ reference: options.project,
+ scope: "any",
+ useContext: false,
+ prompt: "Choose a project to move",
+ missing: "Which project should be moved?",
+ example: "kaneo project move KAN --to acme",
+ });
+ const workspaces =
+ yield* withSpinner("Loading workspaces")(listWorkspaces());
+ const match = matchWorkspace(workspaces, options.to);
+ if (match.kind === "none") {
+ return yield* new InvalidArgument({
+ message: `No workspace matches "${options.to}".`,
+ hint: "Run kaneo workspace list to see the ids and slugs.",
+ });
+ }
+ if (match.kind === "ambiguous") {
+ return yield* new InvalidArgument({
+ message: `"${options.to}" matches more than one workspace.`,
+ hint: `Pass the id instead: ${match.candidates.map((candidate) => candidate.id).join(", ")}.`,
+ });
+ }
+ const destination = match.workspace;
+ if (destination.id === project.workspaceId) {
+ return yield* new InvalidArgument({
+ message: `${project.name} is already in ${destination.name}.`,
+ hint: "Pass --to with another workspace id or slug.",
+ });
+ }
+
+ const key = project.slug.toUpperCase();
+ yield* confirmDestructive({
+ yes: options.yes,
+ action: `Moving ${project.name} to ${destination.name}`,
+ question:
+ project.statistics.totalTasks === 0
+ ? `Move ${project.name} (${key}) to ${destination.name}?`
+ : `Move ${project.name} (${key}) and its ${taskCount(project.statistics.totalTasks)} to ${destination.name}? Assignees without access there are unassigned.`,
+ });
+
+ const moved = yield* withSpinner(
+ `Moving ${project.name} to ${destination.name}`,
+ )(moveProject(project.id, destination.id));
+
+ yield* emit(
+ {
+ ...toProjectRecordJson(moved, project.statistics, session.webUrl),
+ unassignedTaskCount: moved.unassignedTaskCount,
+ },
+ (ui, json) =>
+ renderProjectChange(ui, {
+ verb: "Moved",
+ name: json.name,
+ key: json.key,
+ url: json.url,
+ target: destination.name,
+ }),
+ );
+ if (moved.unassignedTaskCount > 0) {
+ yield* note((ui) => [
+ ` ${ui.theme.warning(ui.glyphs.warning)} ${taskCount(moved.unassignedTaskCount)} lost ${moved.unassignedTaskCount === 1 ? "its assignee, who" : "their assignees, who"} cannot access ${destination.name}.`,
+ "",
+ ]);
+ }
+ },
+);
+
+export const projectMove = Command.make(
+ "move",
+ {
+ project: Argument.String("project").pipe(
+ Argument.withDescription("Project key or id, for example KAN"),
+ Argument.optional,
+ ),
+ to: Flag.String("to").pipe(
+ Flag.withDescription("Destination workspace id or slug"),
+ ),
+ yes: Flag.Boolean("yes").pipe(
+ Flag.withAlias("y"),
+ Flag.withDescription("Move without asking for confirmation"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runProjectMove(options),
+).pipe(
+ Command.withDescription("Move a project and its tasks to another workspace"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/project/unarchive.ts b/packages/cli/src/commands/project/unarchive.ts
new file mode 100644
index 000000000..5ee8c9b80
--- /dev/null
+++ b/packages/cli/src/commands/project/unarchive.ts
@@ -0,0 +1,24 @@
+import { Effect, type Option } from "effect";
+import { Argument, Command } from "effect/cli";
+import { setArchived } from "../../projects-write/set-archived.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runProjectUnarchive = Effect.fn("command.project.unarchive")(
+ function* (options: { readonly project: Option.Option<string> }) {
+ yield* setArchived(options.project, false);
+ },
+);
+
+export const projectUnarchive = Command.make(
+ "unarchive",
+ {
+ project: Argument.String("project").pipe(
+ Argument.withDescription("Archived project key or id, for example KAN"),
+ Argument.optional,
+ ),
+ },
+ (options) => runProjectUnarchive(options),
+).pipe(
+ Command.withDescription("Bring an archived project back to the project list"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/project/view.ts b/packages/cli/src/commands/project/view.ts
new file mode 100644
index 000000000..b96d74c8f
--- /dev/null
+++ b/packages/cli/src/commands/project/view.ts
@@ -0,0 +1,60 @@
+import { Effect, Option } from "effect";
+import { Argument, Command } from "effect/cli";
+import { listColumns } from "../../api/endpoints.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { toProjectView } from "../../projects/project-view.js";
+import { renderProjectView } from "../../projects/render-project-view.js";
+import {
+ resolveProject,
+ resolveWorkspaceId,
+} from "../../services/selection.js";
+import { Session } from "../../services/session.js";
+import { loadBoard } from "../../tasks/load-board.js";
+import { ApiLayer } from "../api-layer.js";
+
+const TASK_LIMIT = 1000;
+
+export const runProjectView = Effect.fn("command.project.view")(
+ function* (options: { readonly project: Option.Option<string> }) {
+ const session = yield* Session;
+ const workspaceId = yield* resolveWorkspaceId();
+ const project = yield* resolveProject(workspaceId, options.project).pipe(
+ Effect.catchTag("ProjectRequired", () =>
+ Effect.fail(
+ new InvalidArgument({
+ message: "Which project should be shown?",
+ hint: "Pass its key or id, for example kaneo project view KAN.",
+ }),
+ ),
+ ),
+ );
+ const [columns, board] = yield* withSpinner(`Loading ${project.name}`)(
+ Effect.all(
+ [listColumns(project.id), loadBoard(project.id, {}, TASK_LIMIT)],
+ {
+ concurrency: 2,
+ },
+ ),
+ );
+ const view = toProjectView(project, columns, board, session.webUrl);
+ yield* emit(view, (ui) =>
+ renderProjectView(ui, { ...view, taskLimit: TASK_LIMIT }),
+ );
+ },
+);
+
+export const projectView = Command.make(
+ "view",
+ {
+ project: Argument.String("project").pipe(
+ Argument.withDescription("Project key or id, for example KAN"),
+ Argument.optional,
+ ),
+ },
+ (options) => runProjectView(options),
+).pipe(
+ Command.withDescription("Show a project with its columns and task counts"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/search.ts b/packages/cli/src/commands/search.ts
new file mode 100644
index 000000000..6f5113228
--- /dev/null
+++ b/packages/cli/src/commands/search.ts
@@ -0,0 +1,125 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { getWorkspace } from "../api/endpoints.js";
+import {
+ SEARCH_TYPES,
+ type SearchType,
+ searchWorkspace,
+} from "../api/search.js";
+import { InvalidArgument } from "../errors/errors.js";
+import { emit } from "../output/emit.js";
+import { Output } from "../output/output.js";
+import { withSpinner } from "../output/spinner.js";
+import { askQuery } from "../search/ask-query.js";
+import { renderSearch } from "../search/render-search.js";
+import { normalizeSearchResults } from "../search/search-results.js";
+import { resolveProject, resolveWorkspaceId } from "../services/selection.js";
+import { Session } from "../services/session.js";
+import { ApiLayer } from "./api-layer.js";
+
+const MAX_LIMIT = 50;
+
+const needsWorkspaceSlug = (type: SearchType) =>
+ type === "all" || type === "comments" || type === "activities";
+
+export const runSearch = Effect.fn("command.search")(function* (options: {
+ readonly query: ReadonlyArray<string>;
+ readonly type: SearchType;
+ readonly limit: number;
+ readonly project: Option.Option<string>;
+}) {
+ const session = yield* Session;
+ const output = yield* Output;
+
+ if (
+ !Number.isInteger(options.limit) ||
+ options.limit < 1 ||
+ options.limit > MAX_LIMIT
+ ) {
+ return yield* new InvalidArgument({
+ message: `--limit must be between 1 and ${MAX_LIMIT}.`,
+ hint: "Pass a smaller --limit, or narrow the search with --type or -p.",
+ });
+ }
+ const typed = options.query.join(" ").trim();
+ if (typed === "" && !output.interactive) {
+ return yield* new InvalidArgument({
+ message: "Nothing to search for.",
+ hint: 'Pass the words to search for, for example kaneo search "login redirect".',
+ });
+ }
+ const query = typed === "" ? yield* askQuery() : typed;
+
+ const workspaceId = yield* resolveWorkspaceId();
+ const projectId = Option.isSome(options.project)
+ ? (yield* resolveProject(workspaceId, options.project)).id
+ : undefined;
+
+ const [response, workspace] = yield* withSpinner("Searching")(
+ Effect.all(
+ [
+ searchWorkspace({
+ query,
+ workspaceId,
+ type: options.type,
+ projectId,
+ limit: options.limit,
+ }),
+ needsWorkspaceSlug(options.type)
+ ? getWorkspace(workspaceId).pipe(Effect.orElseSucceed(() => null))
+ : Effect.succeed(null),
+ ],
+ { concurrency: 2 },
+ ),
+ );
+
+ const results = normalizeSearchResults(response.results, {
+ type: options.type,
+ workspaceId,
+ workspaceSlug: workspace?.slug ?? null,
+ projectId,
+ webUrl: session.webUrl,
+ });
+
+ yield* emit(results, (ui) =>
+ renderSearch(ui, {
+ query,
+ results,
+ more: response.totalCount > response.results.length,
+ limit: options.limit,
+ }),
+ );
+});
+
+export const search = Command.make(
+ "search",
+ {
+ query: Argument.String("query").pipe(
+ Argument.withDescription(
+ "Words to search for, or a ticket id such as KAN-12",
+ ),
+ Argument.variadic(),
+ ),
+ type: Flag.Literals("type", SEARCH_TYPES).pipe(
+ Flag.withAlias("t"),
+ Flag.withDescription("Only results of this kind"),
+ Flag.withDefault("all" as const),
+ ),
+ limit: Flag.Int("limit").pipe(
+ Flag.withAlias("L"),
+ Flag.withDescription(`Maximum number of results, from 1 to ${MAX_LIMIT}`),
+ Flag.withDefault(20),
+ ),
+ project: Flag.String("project").pipe(
+ Flag.withAlias("p"),
+ Flag.withDescription(
+ "Only search in this project, by key or id, for example KAN",
+ ),
+ Flag.optional,
+ ),
+ },
+ (options) => runSearch(options),
+).pipe(
+ Command.withDescription("Search tasks, projects and comments"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/activity.ts b/packages/cli/src/commands/task/activity.ts
new file mode 100644
index 000000000..a1a5e59e3
--- /dev/null
+++ b/packages/cli/src/commands/task/activity.ts
@@ -0,0 +1,90 @@
+import { Effect } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { ACTIVITY_LIMIT_MAX, listTaskActivity } from "../../api/activity.js";
+import { listMembers } from "../../api/endpoints.js";
+import type { WorkspaceMember } from "../../api/schemas.js";
+import {
+ toActivityEntry,
+ toActivityJson,
+} from "../../comments/describe-activity.js";
+import { renderActivity } from "../../comments/render-activity.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { resolveTask } from "../../tasks/resolve-task.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runTaskActivity = Effect.fn("command.task.activity")(
+ function* (options: { readonly task: string; readonly limit: number }) {
+ if (options.limit < 1) {
+ return yield* new InvalidArgument({
+ message: "--limit must be at least 1.",
+ });
+ }
+ const fetchLimit =
+ options.limit < ACTIVITY_LIMIT_MAX ? options.limit + 1 : undefined;
+ const { resolved, activities, members } = yield* withSpinner(
+ `Loading activity on ${options.task}`,
+ )(
+ Effect.gen(function* () {
+ const resolved = yield* resolveTask(options.task, { columns: true });
+ const [activities, members] = yield* Effect.all(
+ [
+ listTaskActivity(resolved.task.id, fetchLimit),
+ listMembers(resolved.workspaceId).pipe(
+ Effect.catchTag("PermissionDenied", () =>
+ Effect.succeed([] as ReadonlyArray<WorkspaceMember>),
+ ),
+ ),
+ ],
+ { concurrency: 2 },
+ );
+ return { resolved, activities, members };
+ }),
+ );
+
+ const now = new Date();
+ const lookups = {
+ members: new Map(members.map((member) => [member.id, member.name])),
+ statuses: new Map(
+ resolved.columns.map((column) => [column.slug, column.name]),
+ ),
+ now,
+ };
+ const entries = activities
+ .slice(0, options.limit)
+ .reverse()
+ .map((activity) => toActivityEntry(activity, lookups));
+
+ yield* emit(entries.map(toActivityJson), (ui) =>
+ renderActivity(ui, {
+ label: resolved.ticketId ?? resolved.task.id.slice(0, 8),
+ title: resolved.task.title,
+ url: resolved.url,
+ entries,
+ more: activities.length > options.limit,
+ now,
+ }),
+ );
+ },
+);
+
+export const taskActivity = Command.make(
+ "activity",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or the task id"),
+ ),
+ limit: Flag.Int("limit").pipe(
+ Flag.withAlias("L"),
+ Flag.withDescription("Show only the latest events, up to this many"),
+ Flag.withDefault(30),
+ ),
+ },
+ (options) => runTaskActivity(options),
+).pipe(
+ Command.withDescription(
+ "Show the history of a task: status changes, assignments, comments and more",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/assign.ts b/packages/cli/src/commands/task/assign.ts
new file mode 100644
index 000000000..70a177d19
--- /dev/null
+++ b/packages/cli/src/commands/task/assign.ts
@@ -0,0 +1,117 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { listMembers } from "../../api/endpoints.js";
+import { updateTaskAssignee } from "../../api/task-actions.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import { pick } from "../../prompts/pick.js";
+import { renderAssignment } from "../../tasks/render-assignment.js";
+import {
+ type Assignee,
+ resolveAssignee,
+} from "../../tasks/resolve-assignee.js";
+import { resolveTask } from "../../tasks/resolve-task.js";
+import { ApiLayer } from "../api-layer.js";
+
+const USER_HINT =
+ 'Use "me", an email address, a name, or a user id, or pass --unassign.';
+
+export const runTaskAssign = Effect.fn("command.task.assign")(
+ function* (options: {
+ readonly task: string;
+ readonly user: Option.Option<string>;
+ readonly unassign: boolean;
+ }) {
+ const output = yield* Output;
+ if (options.unassign && Option.isSome(options.user)) {
+ return yield* new InvalidArgument({
+ message: "Pass a user or --unassign, not both.",
+ hint: USER_HINT,
+ });
+ }
+ const resolved = yield* withSpinner(`Loading ${options.task}`)(
+ resolveTask(options.task),
+ );
+ const label = resolved.ticketId ?? resolved.task.id.slice(0, 8);
+
+ const assignee: Assignee | null = options.unassign
+ ? null
+ : yield* Option.match(options.user, {
+ onSome: (reference) =>
+ withSpinner("Finding the user")(
+ resolveAssignee(resolved.workspaceId, reference),
+ ),
+ onNone: () =>
+ output.interactive
+ ? withSpinner("Loading members")(
+ listMembers(resolved.workspaceId),
+ ).pipe(
+ Effect.flatMap((members) =>
+ pick<Assignee | null>(`Assign ${label} to`, [
+ {
+ title: "Unassigned",
+ value: null,
+ description:
+ resolved.task.assigneeId === null
+ ? "current"
+ : undefined,
+ },
+ ...members.map((member) => ({
+ title: member.name,
+ value: { id: member.id, name: member.name },
+ description:
+ member.id === resolved.task.assigneeId
+ ? `${member.email}, current`
+ : member.email,
+ })),
+ ]),
+ ),
+ )
+ : Effect.fail(
+ new InvalidArgument({
+ message: `Pass the user to assign ${label} to.`,
+ hint: USER_HINT,
+ }),
+ ),
+ });
+
+ yield* withSpinner(
+ assignee ? `Assigning ${label}` : `Unassigning ${label}`,
+ )(updateTaskAssignee(resolved.task.id, assignee?.id ?? null));
+
+ yield* emit(
+ {
+ id: resolved.task.id,
+ ticketId: resolved.ticketId,
+ assignee: assignee ? { id: assignee.id, name: assignee.name } : null,
+ url: resolved.url,
+ },
+ (ui) => renderAssignment(ui, { label, url: resolved.url, assignee }),
+ );
+ },
+);
+
+export const taskAssign = Command.make(
+ "assign",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or the task id"),
+ ),
+ user: Argument.String("user").pipe(
+ Argument.withDescription('"me", an email address, a name, or a user id'),
+ Argument.optional,
+ ),
+ unassign: Flag.Boolean("unassign").pipe(
+ Flag.withDescription("Remove the assignee"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runTaskAssign(options),
+).pipe(
+ Command.withDescription(
+ "Assign a task to a workspace member, or unassign it",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/attach.ts b/packages/cli/src/commands/task/attach.ts
new file mode 100644
index 000000000..9e7a42a19
--- /dev/null
+++ b/packages/cli/src/commands/task/attach.ts
@@ -0,0 +1,243 @@
+import { readFile } from "node:fs/promises";
+import { basename } from "node:path";
+import { Effect, Layer, Option } from "effect";
+import { Argument, Command, Flag, Prompt } from "effect/cli";
+import { FetchHttpClient } from "effect/http";
+import { COMMENT_MAX_LENGTH, createComment } from "../../api/task-actions.js";
+import { updateTaskDescription } from "../../api/task-mutations.js";
+import {
+ type UploadFile,
+ type UploadSurface,
+ uploadTaskFile,
+} from "../../api/uploads.js";
+import { Cancelled, InvalidArgument } from "../../errors/errors.js";
+import {
+ appendToDescription,
+ commentWithFiles,
+ type UploadedFile,
+} from "../../images/attachment-markdown.js";
+import {
+ contentTypeFor,
+ isInlineImageType,
+} from "../../images/content-type.js";
+import { imageColumns } from "../../images/fit-image.js";
+import { imageArt } from "../../images/image-art.js";
+import { currentImageTarget } from "../../images/image-target.js";
+import { renderAttached } from "../../images/render-attached.js";
+import { renderImageBlock } from "../../images/render-image-block.js";
+import { readTextInput } from "../../input/read-text-input.js";
+import { emit } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import { promptTheme } from "../../prompts/prompt-theme.js";
+import { fetchTask, resolveTask } from "../../tasks/resolve-task.js";
+import { ApiLayer } from "../api-layer.js";
+
+const FILES_HINT = "For example: kaneo task attach KAN-12 screenshot.png";
+const INDENT = 2;
+
+const askForFile = Effect.fnUntraced(function* () {
+ const output = yield* Output;
+ return yield* Prompt.run(
+ Prompt.String({
+ message: "File to attach",
+ validate: (value) =>
+ value.trim() === ""
+ ? Effect.fail("Enter a file path, or press Ctrl+C to cancel")
+ : Effect.succeed(value.trim()),
+ theme: promptTheme(output.ui),
+ }),
+ ).pipe(Effect.catchTag("QuitError", () => Effect.fail(new Cancelled())));
+});
+
+const filePaths = Effect.fnUntraced(function* (paths: ReadonlyArray<string>) {
+ if (paths.length > 0) return paths;
+ const output = yield* Output;
+ if (output.interactive) return [yield* askForFile()];
+ return yield* new InvalidArgument({
+ message: "Pass one or more files to attach.",
+ hint: FILES_HINT,
+ });
+});
+
+const readLocalFile = Effect.fnUntraced(function* (
+ path: string,
+ comment: boolean,
+) {
+ const bytes = yield* Effect.tryPromise({
+ try: () => readFile(path),
+ catch: () =>
+ new InvalidArgument({
+ message: `Could not read ${path}.`,
+ hint: comment
+ ? "Check the path. To write text in the comment, pass it with -m."
+ : "Check the path and that the file is readable.",
+ }),
+ });
+ if (bytes.byteLength === 0) {
+ return yield* new InvalidArgument({ message: `${path} is empty.` });
+ }
+ const name = basename(path);
+ return {
+ name,
+ bytes: new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength),
+ contentType: contentTypeFor(name, bytes),
+ } satisfies UploadFile;
+});
+
+const previewLines = Effect.fnUntraced(function* (
+ files: ReadonlyArray<UploadFile>,
+ uploaded: ReadonlyArray<UploadedFile>,
+) {
+ const output = yield* Output;
+ const target = yield* currentImageTarget;
+ if (target.protocol === "none") return [];
+ const lines: string[] = [];
+ for (const [index, file] of uploaded.entries()) {
+ const bytes = files[index]?.bytes;
+ if (file.kind !== "image" || !bytes) continue;
+ const art = yield* imageArt(bytes, target, {
+ maxColumns: imageColumns(output.ui.caps.columns, INDENT),
+ });
+ if (art._tag !== "Art") continue;
+ lines.push(
+ ...renderImageBlock(
+ output.ui,
+ { url: file.url, alt: file.name },
+ art,
+ INDENT,
+ ),
+ "",
+ );
+ }
+ return lines;
+});
+
+export const runTaskAttach = Effect.fn("command.task.attach")(
+ function* (options: {
+ readonly task: string;
+ readonly files: ReadonlyArray<string>;
+ readonly comment: boolean;
+ readonly message: Option.Option<string>;
+ readonly messageFile: Option.Option<string>;
+ }) {
+ const message = yield* readTextInput({
+ value: options.message,
+ file: options.messageFile,
+ flag: "--message",
+ });
+ const target: UploadSurface =
+ options.comment || Option.isSome(message) ? "comment" : "description";
+ const text = Option.getOrElse(message, () => "");
+ if (text.length > COMMENT_MAX_LENGTH) {
+ return yield* new InvalidArgument({
+ message: `The comment is ${text.length} characters long, and the limit is ${COMMENT_MAX_LENGTH}.`,
+ });
+ }
+ const paths = yield* filePaths(options.files);
+ const files = yield* Effect.forEach(paths, (path) =>
+ readLocalFile(path, options.comment),
+ );
+ const resolved = yield* withSpinner(`Loading ${options.task.trim()}`)(
+ resolveTask(options.task),
+ );
+ const label = resolved.ticketId ?? resolved.task.id.slice(0, 8);
+
+ const uploaded: UploadedFile[] = [];
+ for (const [index, file] of files.entries()) {
+ const progress =
+ files.length > 1 ? ` (${index + 1}/${files.length})` : "";
+ const asset = yield* withSpinner(`Uploading ${file.name}${progress}`)(
+ uploadTaskFile(resolved.task.id, file, target),
+ );
+ uploaded.push({
+ name: file.name,
+ url: asset.url,
+ contentType: file.contentType,
+ size: file.bytes.byteLength,
+ kind: isInlineImageType(file.contentType) ? "image" : "attachment",
+ });
+ }
+
+ if (target === "description") {
+ yield* withSpinner(`Updating ${label}`)(
+ fetchTask(resolved.task.id).pipe(
+ Effect.flatMap((latest) =>
+ updateTaskDescription(
+ resolved.task.id,
+ appendToDescription(latest.description, uploaded),
+ ),
+ ),
+ ),
+ );
+ } else {
+ const content = commentWithFiles(text, uploaded);
+ if (content.length > COMMENT_MAX_LENGTH) {
+ return yield* new InvalidArgument({
+ message: `The comment would be ${content.length} characters long, and the limit is ${COMMENT_MAX_LENGTH}.`,
+ hint: "Attach fewer files, or shorten the message.",
+ });
+ }
+ yield* withSpinner(`Commenting on ${label}`)(
+ createComment(resolved.task.id, content),
+ );
+ }
+
+ const previews = yield* previewLines(files, uploaded);
+ yield* emit(
+ {
+ files: uploaded.map(({ name, url, kind }) => ({ name, url, kind })),
+ target,
+ },
+ (ui) => [
+ "",
+ ...previews,
+ ...renderAttached(ui, {
+ label,
+ url: resolved.url,
+ names: uploaded.map((file) => file.name),
+ target,
+ }),
+ ],
+ );
+ },
+);
+
+export const taskAttach = Command.make(
+ "attach",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or a task id"),
+ ),
+ files: Argument.String("file").pipe(
+ Argument.withDescription("Files to upload; images are shown inline"),
+ Argument.variadic(),
+ ),
+ comment: Flag.Boolean("comment").pipe(
+ Flag.withDescription(
+ "Post the files as a new comment instead of adding them to the description",
+ ),
+ Flag.withDefault(false),
+ ),
+ message: Flag.String("message").pipe(
+ Flag.withAlias("m"),
+ Flag.withDescription(
+ "Comment text to post with the files (implies --comment); - reads stdin",
+ ),
+ Flag.optional,
+ ),
+ messageFile: Flag.String("message-file").pipe(
+ Flag.withAlias("F"),
+ Flag.withDescription(
+ "Read the comment text from a file, or - for stdin (implies --comment)",
+ ),
+ Flag.optional,
+ ),
+ },
+ (options) => runTaskAttach(options),
+).pipe(
+ Command.withDescription(
+ "Upload files to a task and add them to its description or a comment",
+ ),
+ Command.provide(Layer.merge(ApiLayer, FetchHttpClient.layer)),
+);
diff --git a/packages/cli/src/commands/task/bulk.ts b/packages/cli/src/commands/task/bulk.ts
new file mode 100644
index 000000000..b45b082f3
--- /dev/null
+++ b/packages/cli/src/commands/task/bulk.ts
@@ -0,0 +1,237 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { type BulkOperation, bulkUpdateTasks } from "../../api/bulk.js";
+import { listColumns } from "../../api/endpoints.js";
+import { listWorkspaceLabels } from "../../api/labels.js";
+import type { Priority } from "../../api/task-mutations.js";
+import { type BulkChange, parseBulkChange } from "../../bulk/bulk-change.js";
+import { resolveBulkStatus } from "../../bulk/bulk-status.js";
+import { labelForRemoval } from "../../bulk/label-for-removal.js";
+import {
+ type AppliedChange,
+ renderBulkResult,
+} from "../../bulk/render-bulk-result.js";
+import {
+ type BulkTask,
+ resolveBulkTasks,
+} from "../../bulk/resolve-bulk-tasks.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { resolveLabels } from "../../labels/resolve-labels.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { confirmDestructive } from "../../prompts/confirm-destructive.js";
+import { resolveAssignee } from "../../tasks/resolve-assignee.js";
+import { ApiLayer } from "../api-layer.js";
+
+const PRIORITIES = ["no-priority", "low", "medium", "high", "urgent"] as const;
+
+type Plan = {
+ readonly operation: BulkOperation;
+ readonly value?: string | null;
+ readonly applied: AppliedChange;
+};
+
+function preview(tasks: ReadonlyArray<BulkTask>): string {
+ const labels = tasks.map((task) => task.label);
+ return labels.length > 5
+ ? `${labels.slice(0, 5).join(", ")} and ${labels.length - 5} more`
+ : labels.join(", ");
+}
+
+const planChange = Effect.fnUntraced(function* (
+ change: BulkChange,
+ workspaceId: string,
+ tasks: ReadonlyArray<BulkTask>,
+) {
+ switch (change.kind) {
+ case "status": {
+ const projects = [
+ ...new Map(
+ tasks.map((task) => [task.project.id, task.project]),
+ ).values(),
+ ];
+ const columns = yield* Effect.forEach(
+ projects,
+ (project) =>
+ Effect.map(listColumns(project.id), (list) => ({
+ name: project.name,
+ columns: list,
+ })),
+ { concurrency: 4 },
+ );
+ const column = yield* Effect.fromResult(
+ resolveBulkStatus(columns, change.reference),
+ );
+ return {
+ operation: "updateStatus",
+ value: column.slug,
+ applied: { kind: "status", columnName: column.name },
+ } satisfies Plan;
+ }
+ case "priority":
+ return {
+ operation: "updatePriority",
+ value: change.priority,
+ applied: { kind: "priority", priority: change.priority },
+ } satisfies Plan;
+ case "assignee": {
+ const assignee = yield* resolveAssignee(workspaceId, change.reference);
+ return {
+ operation: "updateAssignee",
+ value: assignee.id,
+ applied: { kind: "assignee", name: assignee.name },
+ } satisfies Plan;
+ }
+ case "unassign":
+ return {
+ operation: "updateAssignee",
+ value: null,
+ applied: { kind: "unassign" },
+ } satisfies Plan;
+ case "due":
+ return {
+ operation: "updateDueDate",
+ value: change.dueDate,
+ applied: { kind: "due", dueDate: change.dueDate },
+ } satisfies Plan;
+ case "addLabel": {
+ const [label] = yield* resolveLabels(workspaceId, [change.name]);
+ if (!label) {
+ return yield* new InvalidArgument({
+ message: `No label named "${change.name}" in this workspace.`,
+ });
+ }
+ return {
+ operation: "addLabel",
+ value: label.id,
+ applied: { kind: "addLabel", labelName: label.name },
+ } satisfies Plan;
+ }
+ case "removeLabel": {
+ const labels = yield* listWorkspaceLabels(workspaceId);
+ const label = yield* Effect.fromResult(
+ labelForRemoval(labels, change.name),
+ );
+ return {
+ operation: "removeLabel",
+ value: label.id,
+ applied: { kind: "removeLabel", labelName: label.name },
+ } satisfies Plan;
+ }
+ case "delete":
+ return {
+ operation: "delete",
+ applied: { kind: "delete" },
+ } satisfies Plan;
+ }
+});
+
+export const runTaskBulk = Effect.fn("command.task.bulk")(function* (options: {
+ readonly tasks: ReadonlyArray<string>;
+ readonly status: Option.Option<string>;
+ readonly priority: Option.Option<Priority>;
+ readonly assignee: Option.Option<string>;
+ readonly unassign: boolean;
+ readonly due: Option.Option<string>;
+ readonly addLabel: Option.Option<string>;
+ readonly removeLabel: Option.Option<string>;
+ readonly delete: boolean;
+ readonly yes: boolean;
+}) {
+ const change = yield* Effect.fromResult(parseBulkChange(options, new Date()));
+ const count =
+ options.tasks.length === 1 ? "1 task" : `${options.tasks.length} tasks`;
+ const { workspaceId, tasks } = yield* withSpinner(`Checking ${count}`)(
+ resolveBulkTasks(options.tasks),
+ );
+ const plan: Plan = yield* withSpinner("Checking the change")(
+ planChange(change, workspaceId, tasks),
+ );
+ if (plan.operation === "delete") {
+ const total = tasks.length === 1 ? "1 task" : `${tasks.length} tasks`;
+ yield* confirmDestructive({
+ yes: options.yes,
+ action: `Deleting ${total}`,
+ question: `Delete ${total} (${preview(tasks)}) with their comments and time entries? This cannot be undone.`,
+ });
+ }
+ const result = yield* withSpinner(`Updating ${count}`)(
+ bulkUpdateTasks({
+ taskIds: tasks.map((task) => task.id),
+ operation: plan.operation,
+ ...(plan.value === undefined ? {} : { value: plan.value }),
+ }),
+ );
+
+ yield* emit(
+ {
+ updated: result.updatedCount,
+ tasks: tasks.map((task) => task.ticketId ?? task.id),
+ },
+ (ui) =>
+ renderBulkResult(ui, {
+ change: plan.applied,
+ updated: result.updatedCount,
+ tasks,
+ }),
+ );
+});
+
+export const taskBulk = Command.make(
+ "bulk",
+ {
+ tasks: Argument.String("task").pipe(
+ Argument.withDescription("Ticket ids such as KAN-12, or task ids"),
+ Argument.atLeast(1),
+ ),
+ status: Flag.String("status").pipe(
+ Flag.withAlias("s"),
+ Flag.withDescription("Move every task to this column, for example done"),
+ Flag.optional,
+ ),
+ priority: Flag.Literals("priority", PRIORITIES).pipe(
+ Flag.withDescription("Set this priority on every task"),
+ Flag.optional,
+ ),
+ assignee: Flag.String("assignee").pipe(
+ Flag.withAlias("a"),
+ Flag.withDescription(
+ 'Assign every task to "me", or a member by email, name or id',
+ ),
+ Flag.optional,
+ ),
+ unassign: Flag.Boolean("unassign").pipe(
+ Flag.withDescription("Remove the assignee from every task"),
+ Flag.withDefault(false),
+ ),
+ due: Flag.String("due").pipe(
+ Flag.withDescription(
+ "Due date: YYYY-MM-DD, today, tomorrow, +3d, or none to clear",
+ ),
+ Flag.optional,
+ ),
+ addLabel: Flag.String("add-label").pipe(
+ Flag.withDescription("Add this workspace label to every task"),
+ Flag.optional,
+ ),
+ removeLabel: Flag.String("remove-label").pipe(
+ Flag.withDescription("Remove this label from every task"),
+ Flag.optional,
+ ),
+ delete: Flag.Boolean("delete").pipe(
+ Flag.withDescription("Delete every task; asks for confirmation"),
+ Flag.withDefault(false),
+ ),
+ yes: Flag.Boolean("yes").pipe(
+ Flag.withAlias("y"),
+ Flag.withDescription("Delete without asking for confirmation"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runTaskBulk(options),
+).pipe(
+ Command.withDescription(
+ "Apply one change to many tasks at once; nothing changes if a task is unknown",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/comment.ts b/packages/cli/src/commands/task/comment.ts
new file mode 100644
index 000000000..41f7145c5
--- /dev/null
+++ b/packages/cli/src/commands/task/comment.ts
@@ -0,0 +1,115 @@
+import { Effect } from "effect";
+import { Argument, Command, Prompt } from "effect/cli";
+import { COMMENT_MAX_LENGTH, createComment } from "../../api/task-actions.js";
+import { Cancelled, InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import { promptTheme } from "../../prompts/prompt-theme.js";
+import { CliEnvironment } from "../../services/cli-environment.js";
+import { normalizeComment } from "../../tasks/comment-text.js";
+import { readStream } from "../../tasks/read-stdin.js";
+import { renderCommentAdded } from "../../tasks/render-comment-added.js";
+import { resolveTask } from "../../tasks/resolve-task.js";
+import { ApiLayer } from "../api-layer.js";
+
+const TEXT_HINT = "Pass the text after the task, or pipe it on stdin.";
+
+const askForComment = Effect.fnUntraced(function* (message: string) {
+ const output = yield* Output;
+ return yield* Prompt.run(
+ Prompt.String({
+ message,
+ validate: (value) =>
+ value.trim() === ""
+ ? Effect.fail("Write a comment, or press Ctrl+C to cancel")
+ : Effect.succeed(value),
+ theme: promptTheme(output.ui),
+ }),
+ ).pipe(Effect.catchTag("QuitError", () => Effect.fail(new Cancelled())));
+});
+
+const readComment = Effect.fnUntraced(function* (
+ words: ReadonlyArray<string>,
+ label: string,
+) {
+ const output = yield* Output;
+ const environment = yield* CliEnvironment;
+ if (words.length > 0) return words.join(" ");
+ if (!environment.stdin.isTTY) {
+ return yield* Effect.tryPromise({
+ try: () => readStream(process.stdin),
+ catch: () =>
+ new InvalidArgument({
+ message: "Could not read the comment from stdin.",
+ hint: TEXT_HINT,
+ }),
+ });
+ }
+ if (output.interactive) return yield* askForComment(`Comment on ${label}`);
+ return yield* new InvalidArgument({
+ message: `Pass the comment for ${label}.`,
+ hint: TEXT_HINT,
+ });
+});
+
+export const runTaskComment = Effect.fn("command.task.comment")(
+ function* (options: {
+ readonly task: string;
+ readonly text: ReadonlyArray<string>;
+ }) {
+ const resolved = yield* withSpinner(`Loading ${options.task}`)(
+ resolveTask(options.task),
+ );
+ const label = resolved.ticketId ?? resolved.task.id.slice(0, 8);
+ const content = normalizeComment(yield* readComment(options.text, label));
+ if (content === "") {
+ return yield* new InvalidArgument({
+ message: "The comment is empty.",
+ hint: TEXT_HINT,
+ });
+ }
+ if (content.length > COMMENT_MAX_LENGTH) {
+ return yield* new InvalidArgument({
+ message: `The comment is ${content.length} characters long, and the limit is ${COMMENT_MAX_LENGTH}.`,
+ });
+ }
+
+ const comment = yield* withSpinner(`Commenting on ${label}`)(
+ createComment(resolved.task.id, content),
+ );
+
+ yield* emit(
+ {
+ id: comment.id,
+ taskId: comment.taskId,
+ content: comment.content ?? content,
+ createdAt: comment.createdAt,
+ url: resolved.url,
+ },
+ (ui) =>
+ renderCommentAdded(ui, {
+ label,
+ url: resolved.url,
+ content: comment.content ?? content,
+ }),
+ );
+ },
+);
+
+export const taskComment = Command.make(
+ "comment",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or the task id"),
+ ),
+ text: Argument.String("text").pipe(
+ Argument.withDescription("The comment; read from stdin when left out"),
+ Argument.variadic(),
+ ),
+ },
+ (options) => runTaskComment(options),
+).pipe(
+ Command.withDescription("Add a comment to a task"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/create.ts b/packages/cli/src/commands/task/create.ts
new file mode 100644
index 000000000..d1deace4b
--- /dev/null
+++ b/packages/cli/src/commands/task/create.ts
@@ -0,0 +1,285 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag, Prompt } from "effect/cli";
+import { listColumns } from "../../api/endpoints.js";
+import { attachLabelToTask, type Label } from "../../api/labels.js";
+import {
+ type CreateTaskBody,
+ createTask,
+ type Priority,
+} from "../../api/task-mutations.js";
+import { Cancelled, InvalidArgument } from "../../errors/errors.js";
+import { toTaskLabelJson } from "../../labels/label-json.js";
+import { resolveLabels } from "../../labels/resolve-labels.js";
+import { emit } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import {
+ linkToParent,
+ projectOrParent,
+ resolveParent,
+} from "../../relations/link-subtask.js";
+import { labelChip } from "../../render/label-chip.js";
+import { taskUrl } from "../../render/links.js";
+import { ticketId } from "../../render/task-format.js";
+import { themeCodes } from "../../render/theme.js";
+import {
+ resolveProject,
+ resolveWorkspaceId,
+} from "../../services/selection.js";
+import { Session } from "../../services/session.js";
+import { createStatus, FALLBACK_STATUS } from "../../tasks/create-status.js";
+import { checkDateRange } from "../../tasks/date-range.js";
+import { parseDateInput } from "../../tasks/parse-date.js";
+import { renderTaskChange } from "../../tasks/render-task-change.js";
+import { resolveAssignee } from "../../tasks/resolve-assignee.js";
+import { toTaskDetailJson } from "../../tasks/task-detail-json.js";
+import { readTextInput } from "../../input/read-text-input.js";
+import { ApiLayer } from "../api-layer.js";
+
+const PRIORITIES = ["no-priority", "low", "medium", "high", "urgent"] as const;
+
+const dateFlag = (input: Option.Option<string>, now: Date, flag: string) =>
+ Option.match(input, {
+ onNone: () => Effect.succeed(undefined),
+ onSome: (value) => Effect.fromResult(parseDateInput(value, now, flag)),
+ });
+
+const promptTitle = Effect.fnUntraced(function* () {
+ const output = yield* Output;
+ const { glyphs, caps } = output.ui;
+ const codes = themeCodes(caps.color);
+ return yield* Prompt.run(
+ Prompt.String({
+ message: "Task title",
+ validate: (value) =>
+ value.trim() === ""
+ ? Effect.fail("Enter a title")
+ : Effect.succeed(value.trim()),
+ theme: {
+ prefix: glyphs.diamond,
+ tick: glyphs.tick,
+ ellipsis: glyphs.ellipsis,
+ primaryColor: codes.bold,
+ mutedColor: codes.muted,
+ successColor: codes.success,
+ errorColor: codes.danger,
+ submittedColor: "",
+ },
+ }),
+ ).pipe(Effect.catchTag("QuitError", () => Effect.fail(new Cancelled())));
+});
+
+const resolveTitle = Effect.fnUntraced(function* (
+ title: Option.Option<string>,
+) {
+ const output = yield* Output;
+ const given = title.pipe(
+ Option.map((value) => value.trim()),
+ Option.filter((value) => value !== ""),
+ );
+ if (Option.isSome(given)) return given.value;
+ if (output.interactive) return yield* promptTitle();
+ return yield* new InvalidArgument({
+ message: "A task title is required.",
+ hint: 'Pass it as the first argument, for example kaneo task create "Fix login redirect".',
+ });
+});
+
+export const runTaskCreate = Effect.fn("command.task.create")(
+ function* (options: {
+ readonly title: Option.Option<string>;
+ readonly project: Option.Option<string>;
+ readonly description: Option.Option<string>;
+ readonly priority: Priority;
+ readonly status: Option.Option<string>;
+ readonly assignee: Option.Option<string>;
+ readonly due: Option.Option<string>;
+ readonly start: Option.Option<string>;
+ readonly label: ReadonlyArray<string>;
+ readonly parent: Option.Option<string>;
+ }) {
+ const session = yield* Session;
+ const now = new Date();
+ const dueDate = yield* dateFlag(options.due, now, "--due");
+ const startDate = yield* dateFlag(options.start, now, "--start");
+ yield* Effect.fromResult(checkDateRange(startDate, dueDate));
+
+ const workspaceId = yield* resolveWorkspaceId();
+ const parent = yield* resolveParent(options.parent, workspaceId);
+ const project = yield* resolveProject(
+ workspaceId,
+ projectOrParent(options.project, parent),
+ );
+ const title = yield* resolveTitle(options.title);
+
+ const [columns, assignee, labels] = yield* withSpinner(
+ `Loading ${project.name}`,
+ )(
+ Effect.all(
+ [
+ listColumns(project.id),
+ Option.match(options.assignee, {
+ onNone: () => Effect.succeed(null),
+ onSome: (reference) => resolveAssignee(workspaceId, reference),
+ }),
+ resolveLabels(workspaceId, options.label),
+ ],
+ { concurrency: 3 },
+ ),
+ );
+ const column = yield* Effect.fromResult(
+ createStatus(
+ columns,
+ Option.getOrUndefined(options.status),
+ project.name,
+ ),
+ );
+
+ const body: CreateTaskBody = {
+ title,
+ description: Option.getOrElse(options.description, () => ""),
+ priority: options.priority,
+ status: column?.slug ?? FALLBACK_STATUS,
+ ...(assignee ? { userId: assignee.id } : {}),
+ ...(dueDate ? { dueDate } : {}),
+ ...(startDate ? { startDate } : {}),
+ };
+ const created = yield* withSpinner("Creating task")(
+ createTask(project.id, body),
+ );
+ const attached: ReadonlyArray<Label> =
+ labels.length > 0
+ ? yield* withSpinner("Adding labels")(
+ Effect.forEach(labels, (label) =>
+ attachLabelToTask(label.id, created.id),
+ ),
+ )
+ : [];
+ const parentRef = yield* linkToParent(parent, {
+ id: created.id,
+ label: ticketId(project.slug, created.number) ?? created.id.slice(0, 8),
+ });
+
+ const json = toTaskDetailJson({
+ task: {
+ id: created.id,
+ projectId: created.projectId,
+ number: created.number,
+ title: created.title,
+ description: created.description,
+ status: created.status,
+ priority: created.priority,
+ startDate: created.startDate,
+ dueDate: created.dueDate,
+ createdAt: created.createdAt,
+ assigneeId: created.userId,
+ assigneeName: created.userId ? (assignee?.name ?? null) : null,
+ },
+ workspaceId: project.workspaceId,
+ project,
+ columns,
+ ticketId: ticketId(project.slug, created.number),
+ url: taskUrl(session.webUrl, {
+ workspaceId: project.workspaceId,
+ projectId: created.projectId,
+ id: created.id,
+ }),
+ });
+
+ yield* emit(
+ { ...json, labels: attached.map(toTaskLabelJson), parent: parentRef },
+ (ui, task) =>
+ renderTaskChange(ui, {
+ verb: "Created",
+ reference: task.ticketId ?? task.id.slice(0, 8),
+ url: task.url,
+ detail: [
+ task.title,
+ ...task.labels.map(
+ (label) => `${labelChip(ui, label.color)} ${label.name}`,
+ ),
+ ...(task.parent
+ ? [
+ ui.theme.muted(
+ `subtask of ${task.parent.ticketId ?? task.parent.id.slice(0, 8)}`,
+ ),
+ ]
+ : []),
+ ].join(" "),
+ }),
+ );
+ },
+);
+
+export const taskCreate = Command.make(
+ "create",
+ {
+ title: Argument.String("title").pipe(
+ Argument.withDescription(
+ "Task title; asked for when omitted in a terminal",
+ ),
+ Argument.optional,
+ ),
+ project: Flag.String("project").pipe(
+ Flag.withAlias("p"),
+ Flag.withDescription("Project key or id, for example KAN"),
+ Flag.optional,
+ ),
+ description: Flag.String("description").pipe(
+ Flag.withAlias("d"),
+ Flag.withDescription("Description in Markdown"),
+ Flag.optional,
+ ),
+ descriptionFile: Flag.String("description-file").pipe(
+ Flag.withAlias("F"),
+ Flag.withDescription("Read the description from a file, or - for stdin"),
+ Flag.optional,
+ ),
+ priority: Flag.Literals("priority", PRIORITIES).pipe(
+ Flag.withDescription("Task priority"),
+ Flag.withDefault("no-priority"),
+ ),
+ status: Flag.String("status").pipe(
+ Flag.withAlias("s"),
+ Flag.withDescription(
+ "Column slug, for example in-progress (default: the first column)",
+ ),
+ Flag.optional,
+ ),
+ assignee: Flag.String("assignee").pipe(
+ Flag.withAlias("a"),
+ Flag.withDescription('Assign to "me", or a member by email, name or id'),
+ Flag.optional,
+ ),
+ due: Flag.String("due").pipe(
+ Flag.withDescription("Due date: YYYY-MM-DD, today, tomorrow or +3d"),
+ Flag.optional,
+ ),
+ start: Flag.String("start").pipe(
+ Flag.withDescription("Start date: YYYY-MM-DD, today, tomorrow or +3d"),
+ Flag.optional,
+ ),
+ label: Flag.String("label").pipe(
+ Flag.withDescription("Add a workspace label by name; repeat for more"),
+ Flag.atLeast(0),
+ ),
+ parent: Flag.String("parent").pipe(
+ Flag.withDescription(
+ "Create it as a subtask of this task, for example KAN-12 (default project: the parent's)",
+ ),
+ Flag.optional,
+ ),
+ },
+ (options) =>
+ Effect.flatMap(
+ readTextInput({
+ value: options.description,
+ file: options.descriptionFile,
+ flag: "--description",
+ }),
+ (description) => runTaskCreate({ ...options, description }),
+ ),
+).pipe(
+ Command.withDescription("Create a task in a project"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/delete.ts b/packages/cli/src/commands/task/delete.ts
new file mode 100644
index 000000000..728a54e60
--- /dev/null
+++ b/packages/cli/src/commands/task/delete.ts
@@ -0,0 +1,55 @@
+import { Effect } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { deleteTask } from "../../api/task-mutations.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { confirmDestructive } from "../../prompts/confirm-destructive.js";
+import { renderTaskDeleted } from "../../tasks/render-task-deleted.js";
+import { resolveTask } from "../../tasks/resolve-task.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runTaskDelete = Effect.fn("command.task.delete")(
+ function* (options: { readonly task: string; readonly yes: boolean }) {
+ const resolved = yield* withSpinner(`Loading ${options.task}`)(
+ resolveTask(options.task),
+ );
+ const label = resolved.ticketId ?? resolved.task.id.slice(0, 8);
+
+ yield* confirmDestructive({
+ yes: options.yes,
+ action: `Deleting ${label}`,
+ question: `Delete ${label} · ${resolved.task.title}? This cannot be undone.`,
+ });
+
+ yield* withSpinner(`Deleting ${label}`)(deleteTask(resolved.task.id));
+ yield* emit(
+ {
+ id: resolved.task.id,
+ ticketId: resolved.ticketId,
+ title: resolved.task.title,
+ deleted: true,
+ },
+ (ui) => renderTaskDeleted(ui, { label, title: resolved.task.title }),
+ );
+ },
+);
+
+export const taskDelete = Command.make(
+ "delete",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or the task id"),
+ ),
+ yes: Flag.Boolean("yes").pipe(
+ Flag.withAlias("y"),
+ Flag.withDescription("Delete without asking for confirmation"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runTaskDelete(options),
+).pipe(
+ Command.withDescription(
+ "Permanently delete a task with its comments and time entries",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/duplicate.ts b/packages/cli/src/commands/task/duplicate.ts
new file mode 100644
index 000000000..aa8c39b24
--- /dev/null
+++ b/packages/cli/src/commands/task/duplicate.ts
@@ -0,0 +1,109 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { listProjects } from "../../api/endpoints.js";
+import { moveTask } from "../../api/task-actions.js";
+import { duplicateTask } from "../../api/task-duplicate.js";
+import { InvalidArgument, ProjectNotFound } from "../../errors/errors.js";
+import { emit, note } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { matchProject } from "../../services/selection.js";
+import { renderTaskDuplicated } from "../../tasks/render-task-duplicated.js";
+import { resolveTask } from "../../tasks/resolve-task.js";
+import { toTaskDetailJson } from "../../tasks/task-detail-json.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runTaskDuplicate = Effect.fn("command.task.duplicate")(
+ function* (options: {
+ readonly task: string;
+ readonly title: Option.Option<string>;
+ readonly project: Option.Option<string>;
+ }) {
+ const title = Option.map(options.title, (value) => value.trim());
+ if (Option.isSome(title) && title.value === "") {
+ return yield* new InvalidArgument({
+ message: "The title cannot be empty.",
+ hint: "Leave out --title to keep the original title.",
+ });
+ }
+ const source = yield* withSpinner(`Loading ${options.task.trim()}`)(
+ resolveTask(options.task),
+ );
+ const sourceLabel = source.ticketId ?? source.task.id.slice(0, 8);
+ const destination = yield* Option.match(options.project, {
+ onNone: () => Effect.succeed(null),
+ onSome: (reference) =>
+ withSpinner("Loading projects")(listProjects(source.workspaceId)).pipe(
+ Effect.flatMap((projects) => {
+ const match = matchProject(
+ projects.filter((project) => project.archivedAt === null),
+ reference,
+ );
+ return match
+ ? Effect.succeed(match.id === source.project.id ? null : match)
+ : Effect.fail(
+ new ProjectNotFound({ query: reference, source: null }),
+ );
+ }),
+ ),
+ });
+
+ const copy = yield* withSpinner(`Duplicating ${sourceLabel}`)(
+ duplicateTask(source.task.id, Option.getOrUndefined(title)),
+ );
+ if (destination) {
+ yield* withSpinner(`Moving the copy to ${destination.name}`)(
+ moveTask(copy.id, { projectId: destination.id, status: undefined }),
+ ).pipe(
+ Effect.tapError(() =>
+ note((ui) => [
+ ` ${ui.theme.warning(ui.glyphs.warning)} The copy was created in ${source.project.name}${copy.number === null ? "" : ` as ${source.project.slug.toUpperCase()}-${copy.number}`}, but could not be moved to ${destination.name}.`,
+ ]),
+ ),
+ );
+ }
+
+ const created = yield* withSpinner("Loading the copy")(
+ resolveTask(copy.id, { columns: true }),
+ );
+ const json = toTaskDetailJson(created);
+ yield* emit(
+ {
+ ...json,
+ source: { id: source.task.id, ticketId: source.ticketId },
+ },
+ (ui, task) =>
+ renderTaskDuplicated(ui, {
+ sourceLabel,
+ label: task.ticketId ?? task.id.slice(0, 8),
+ url: task.url,
+ title: task.title,
+ }),
+ );
+ },
+);
+
+export const taskDuplicate = Command.make(
+ "duplicate",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or the task id"),
+ ),
+ title: Flag.String("title").pipe(
+ Flag.withDescription("Title for the copy (default: the same title)"),
+ Flag.optional,
+ ),
+ project: Flag.String("project").pipe(
+ Flag.withAlias("p"),
+ Flag.withDescription(
+ "Put the copy in this project instead, for example MOB",
+ ),
+ Flag.optional,
+ ),
+ },
+ (options) => runTaskDuplicate(options),
+).pipe(
+ Command.withDescription(
+ "Copy a task with its description, labels and custom fields",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/edit.ts b/packages/cli/src/commands/task/edit.ts
new file mode 100644
index 000000000..bd1f22bc4
--- /dev/null
+++ b/packages/cli/src/commands/task/edit.ts
@@ -0,0 +1,208 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { listTaskLabels } from "../../api/labels.js";
+import {
+ type Priority,
+ updateTaskDescription,
+ updateTaskDueDate,
+ updateTaskPriority,
+ updateTaskStartDate,
+ updateTaskTitle,
+} from "../../api/task-mutations.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { toTaskLabelJson } from "../../labels/label-json.js";
+import { describeLabelChanges } from "../../labels/plan-task-labels.js";
+import {
+ applyTaskLabelEdits,
+ prepareTaskLabelEdits,
+} from "../../labels/task-label-edits.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { checkDateRange } from "../../tasks/date-range.js";
+import { parseDateChange } from "../../tasks/parse-date.js";
+import { renderTaskChange } from "../../tasks/render-task-change.js";
+import { resolveTask } from "../../tasks/resolve-task.js";
+import { toTaskDetailJson } from "../../tasks/task-detail-json.js";
+import { readTextInput } from "../../input/read-text-input.js";
+import { ApiLayer } from "../api-layer.js";
+
+const PRIORITIES = ["no-priority", "low", "medium", "high", "urgent"] as const;
+
+const dateChange = (input: Option.Option<string>, now: Date, flag: string) =>
+ Option.match(input, {
+ onNone: () => Effect.succeed(Option.none<string | null>()),
+ onSome: (value) =>
+ Effect.fromResult(parseDateChange(value, now, flag)).pipe(
+ Effect.map(Option.some),
+ ),
+ });
+
+export const runTaskEdit = Effect.fn("command.task.edit")(function* (options: {
+ readonly task: string;
+ readonly title: Option.Option<string>;
+ readonly description: Option.Option<string>;
+ readonly priority: Option.Option<Priority>;
+ readonly due: Option.Option<string>;
+ readonly start: Option.Option<string>;
+ readonly addLabel: ReadonlyArray<string>;
+ readonly removeLabel: ReadonlyArray<string>;
+}) {
+ const { title, description, priority } = options;
+ if (
+ [title, description, priority, options.due, options.start].every((flag) =>
+ Option.isNone(flag),
+ ) &&
+ options.addLabel.length === 0 &&
+ options.removeLabel.length === 0
+ ) {
+ return yield* new InvalidArgument({
+ message: "Nothing to change.",
+ hint: "Pass at least one of --title, --description, --priority, --due, --start, --add-label or --remove-label.",
+ });
+ }
+ const newTitle = Option.map(title, (value) => value.trim());
+ if (Option.isSome(newTitle) && newTitle.value === "") {
+ return yield* new InvalidArgument({
+ message: "The title cannot be empty.",
+ hint: 'Pass a title, for example --title "Fix login redirect".',
+ });
+ }
+ const now = new Date();
+ const due = yield* dateChange(options.due, now, "--due");
+ const start = yield* dateChange(options.start, now, "--start");
+
+ const resolved = yield* withSpinner(`Loading ${options.task.trim()}`)(
+ resolveTask(options.task),
+ );
+ if (Option.isSome(due) || Option.isSome(start)) {
+ yield* Effect.fromResult(
+ checkDateRange(
+ Option.getOrElse(start, () => resolved.task.startDate),
+ Option.getOrElse(due, () => resolved.task.dueDate),
+ ),
+ );
+ }
+
+ const id = resolved.task.id;
+ const label = resolved.ticketId ?? id.slice(0, 8);
+ const labelPlan = yield* withSpinner("Loading labels")(
+ prepareTaskLabelEdits({
+ workspaceId: resolved.workspaceId,
+ taskId: id,
+ taskRef: label,
+ add: options.addLabel,
+ remove: options.removeLabel,
+ }),
+ );
+ const labelChanges = describeLabelChanges(labelPlan);
+ const changed: string[] = [];
+ yield* withSpinner(`Updating ${label}`)(
+ Effect.gen(function* () {
+ if (Option.isSome(newTitle)) {
+ yield* updateTaskTitle(id, newTitle.value);
+ changed.push("title");
+ }
+ if (Option.isSome(description)) {
+ yield* updateTaskDescription(id, description.value);
+ changed.push("description");
+ }
+ if (Option.isSome(priority)) {
+ yield* updateTaskPriority(id, priority.value);
+ changed.push("priority");
+ }
+ if (Option.isSome(due)) {
+ yield* updateTaskDueDate(id, due.value);
+ changed.push("due date");
+ }
+ if (Option.isSome(start)) {
+ yield* updateTaskStartDate(id, start.value);
+ changed.push("start date");
+ }
+ if (labelChanges) {
+ yield* applyTaskLabelEdits(id, labelPlan);
+ changed.push(labelChanges);
+ }
+ }),
+ );
+
+ const [updated, taskLabels] = yield* withSpinner(`Loading ${label}`)(
+ Effect.all([resolveTask(id, { columns: true }), listTaskLabels(id)], {
+ concurrency: 2,
+ }),
+ );
+ const json = {
+ ...toTaskDetailJson(updated),
+ labels: taskLabels.map(toTaskLabelJson),
+ };
+ yield* emit(json, (ui, task) =>
+ renderTaskChange(ui, {
+ verb: "Updated",
+ reference: task.ticketId ?? label,
+ url: task.url,
+ detail: changed.join(", "),
+ }),
+ );
+});
+
+export const taskEdit = Command.make(
+ "edit",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or a task id"),
+ ),
+ title: Flag.String("title").pipe(
+ Flag.withDescription("New title"),
+ Flag.optional,
+ ),
+ description: Flag.String("description").pipe(
+ Flag.withAlias("d"),
+ Flag.withDescription(
+ "New description in Markdown; replaces the current one",
+ ),
+ Flag.optional,
+ ),
+ descriptionFile: Flag.String("description-file").pipe(
+ Flag.withAlias("F"),
+ Flag.withDescription("Read the description from a file, or - for stdin"),
+ Flag.optional,
+ ),
+ priority: Flag.Literals("priority", PRIORITIES).pipe(
+ Flag.withDescription("New priority"),
+ Flag.optional,
+ ),
+ due: Flag.String("due").pipe(
+ Flag.withDescription(
+ "Due date: YYYY-MM-DD, today, tomorrow, +3d, or none to clear",
+ ),
+ Flag.optional,
+ ),
+ start: Flag.String("start").pipe(
+ Flag.withDescription(
+ "Start date: YYYY-MM-DD, today, tomorrow, +3d, or none to clear",
+ ),
+ Flag.optional,
+ ),
+ addLabel: Flag.String("add-label").pipe(
+ Flag.withDescription("Add a workspace label by name; repeat for more"),
+ Flag.atLeast(0),
+ ),
+ removeLabel: Flag.String("remove-label").pipe(
+ Flag.withDescription("Remove a label by name; repeat for more"),
+ Flag.atLeast(0),
+ ),
+ },
+ (options) =>
+ Effect.flatMap(
+ readTextInput({
+ value: options.description,
+ file: options.descriptionFile,
+ flag: "--description",
+ }),
+ (description) => runTaskEdit({ ...options, description }),
+ ),
+).pipe(
+ Command.withDescription(
+ "Change a task's title, description, priority, dates or labels",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/export.ts b/packages/cli/src/commands/task/export.ts
new file mode 100644
index 000000000..ee14191ed
--- /dev/null
+++ b/packages/cli/src/commands/task/export.ts
@@ -0,0 +1,80 @@
+import { writeFile } from "node:fs/promises";
+import { Effect, Option } from "effect";
+import { Command, Flag } from "effect/cli";
+import { exportTasks } from "../../api/export-import.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { projectUrl } from "../../render/links.js";
+import {
+ resolveProject,
+ resolveWorkspaceId,
+} from "../../services/selection.js";
+import { Session } from "../../services/session.js";
+import { renderExported } from "../../transfer/render-exported.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runTaskExport = Effect.fn("command.task.export")(
+ function* (options: {
+ readonly project: Option.Option<string>;
+ readonly output: Option.Option<string>;
+ }) {
+ const session = yield* Session;
+ const workspaceId = yield* resolveWorkspaceId();
+ const project = yield* resolveProject(workspaceId, options.project);
+ const document = yield* withSpinner(`Exporting ${project.name}`)(
+ exportTasks(project.id),
+ );
+ const file = Option.filter(options.output, (path) => path !== "-");
+ if (Option.isNone(file)) {
+ return yield* emit(document, (_ui, value) =>
+ JSON.stringify(value, null, 2).split("\n"),
+ );
+ }
+ const path = file.value;
+ yield* Effect.tryPromise({
+ try: () => writeFile(path, `${JSON.stringify(document, null, 2)}\n`),
+ catch: () =>
+ new InvalidArgument({
+ message: `Could not write ${path}.`,
+ hint: "Check that the folder exists and is writable.",
+ }),
+ });
+ yield* emit(
+ {
+ file: path,
+ tasks: document.tasks.length,
+ exportedAt: document.project.exportedAt,
+ project: {
+ id: project.id,
+ key: project.slug.toUpperCase(),
+ name: project.name,
+ url: projectUrl(session.webUrl, project),
+ },
+ },
+ renderExported,
+ );
+ },
+);
+
+export const taskExport = Command.make(
+ "export",
+ {
+ project: Flag.String("project").pipe(
+ Flag.withAlias("p"),
+ Flag.withDescription("Project key or id, for example KAN"),
+ Flag.optional,
+ ),
+ output: Flag.String("output").pipe(
+ Flag.withAlias("o"),
+ Flag.withDescription("Write the JSON to this file instead of stdout"),
+ Flag.optional,
+ ),
+ },
+ (options) => runTaskExport(options),
+).pipe(
+ Command.withDescription(
+ "Export a project's tasks as JSON, ready for kaneo task import",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/field.ts b/packages/cli/src/commands/task/field.ts
new file mode 100644
index 000000000..42e0be086
--- /dev/null
+++ b/packages/cli/src/commands/task/field.ts
@@ -0,0 +1,161 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import {
+ listCustomFields,
+ listTaskFieldValues,
+ setTaskFieldValue,
+} from "../../api/custom-fields.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { unknownField } from "../../fields/choose-field.js";
+import { toFieldJson } from "../../fields/field-json.js";
+import {
+ fieldValueJson,
+ formatJsonValue,
+ parseFieldValue,
+} from "../../fields/field-value.js";
+import { matchField } from "../../fields/match-field.js";
+import { renderFieldValueChange } from "../../fields/render-field-change.js";
+import {
+ renderTaskFields,
+ type TaskFieldJson,
+} from "../../fields/render-task-fields.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { resolveTask } from "../../tasks/resolve-task.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runTaskField = Effect.fn("command.task.field")(
+ function* (options: {
+ readonly task: string;
+ readonly field: Option.Option<string>;
+ readonly value: Option.Option<string>;
+ readonly clear: boolean;
+ }) {
+ if (options.clear && Option.isSome(options.value)) {
+ return yield* new InvalidArgument({
+ message: "Pass a value or --clear, not both.",
+ });
+ }
+ if (options.clear && Option.isNone(options.field)) {
+ return yield* new InvalidArgument({
+ message: "Which field should be cleared?",
+ hint: 'Pass the field name, for example kaneo task field KAN-12 "Story points" --clear.',
+ });
+ }
+ const resolved = yield* withSpinner(`Loading ${options.task}`)(
+ resolveTask(options.task),
+ );
+ const label = resolved.ticketId ?? resolved.task.id.slice(0, 8);
+ const [definitions, values] = yield* withSpinner("Loading fields")(
+ Effect.all(
+ [
+ listCustomFields(resolved.task.projectId),
+ listTaskFieldValues(resolved.task.id),
+ ],
+ { concurrency: 2 },
+ ),
+ );
+ const fields = definitions.map(toFieldJson);
+ const valueOf = (fieldId: string) =>
+ values.find((value) => value.fieldId === fieldId)?.value ?? null;
+ const taskJson = {
+ id: resolved.task.id,
+ ticketId: resolved.ticketId,
+ url: resolved.url,
+ };
+
+ const field = Option.isSome(options.field)
+ ? matchField(fields, options.field.value)
+ : undefined;
+ if (Option.isSome(options.field) && !field) {
+ return yield* unknownField(
+ fields,
+ options.field.value,
+ resolved.project.name,
+ );
+ }
+
+ if (!field || (Option.isNone(options.value) && !options.clear)) {
+ const shown: TaskFieldJson[] = (field ? [field] : fields).map(
+ (entry) => ({
+ id: entry.id,
+ name: entry.name,
+ type: entry.type,
+ value: fieldValueJson(entry.type, valueOf(entry.id)),
+ }),
+ );
+ yield* emit({ ...taskJson, fields: shown }, (ui, view) =>
+ renderTaskFields(ui, {
+ label,
+ title: resolved.task.title,
+ url: resolved.url,
+ fields: view.fields,
+ }),
+ );
+ return;
+ }
+
+ if (options.clear && field.required) {
+ return yield* new InvalidArgument({
+ message: `${field.name} is required, so it cannot be cleared.`,
+ hint: "Set another value instead.",
+ });
+ }
+ const raw = Option.isSome(options.value)
+ ? yield* Effect.fromResult(
+ parseFieldValue(field, options.value.value, new Date()),
+ )
+ : "";
+ yield* withSpinner(`Updating ${label}`)(
+ setTaskFieldValue({
+ taskId: resolved.task.id,
+ fieldId: field.id,
+ value: raw,
+ }),
+ );
+ const value = fieldValueJson(field.type, raw);
+ yield* emit(
+ {
+ ...taskJson,
+ field: { id: field.id, name: field.name, type: field.type },
+ value,
+ },
+ (ui) =>
+ renderFieldValueChange(ui, {
+ label,
+ url: resolved.url,
+ field: field.name,
+ value: formatJsonValue(value),
+ }),
+ );
+ },
+);
+
+export const taskField = Command.make(
+ "field",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or the task id"),
+ ),
+ field: Argument.String("field").pipe(
+ Argument.withDescription(
+ "Custom field name or id; leave out to show every field",
+ ),
+ Argument.optional,
+ ),
+ value: Argument.String("value").pipe(
+ Argument.withDescription(
+ "New value: text, a number, a date (YYYY-MM-DD, today, +3d), yes or no, an option, or comma-separated options",
+ ),
+ Argument.optional,
+ ),
+ clear: Flag.Boolean("clear").pipe(
+ Flag.withDescription("Remove the field's value from the task"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runTaskField(options),
+).pipe(
+ Command.withDescription("Show or set the custom field values of a task"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/images.ts b/packages/cli/src/commands/task/images.ts
new file mode 100644
index 000000000..dece98b7c
--- /dev/null
+++ b/packages/cli/src/commands/task/images.ts
@@ -0,0 +1,77 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { InvalidArgument } from "../../errors/errors.js";
+import { extractImages } from "../../images/extract-images.js";
+import { absoluteImageUrl } from "../../images/image-url.js";
+import {
+ DEFAULT_MAX_IMAGES,
+ renderImages,
+} from "../../images/render-images.js";
+import { renderImagesHeading } from "../../images/render-images-heading.js";
+import { emit } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import { Session } from "../../services/session.js";
+import { resolveTask } from "../../tasks/resolve-task.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runTaskImages = Effect.fn("command.task.images")(
+ function* (options: {
+ readonly task: string;
+ readonly max: Option.Option<number>;
+ }) {
+ if (Option.isSome(options.max) && options.max.value < 1) {
+ return yield* new InvalidArgument({
+ message: "--max must be 1 or more.",
+ hint: "For example: --max 3",
+ });
+ }
+ const session = yield* Session;
+ const output = yield* Output;
+ const resolved = yield* withSpinner(`Loading ${options.task.trim()}`)(
+ resolveTask(options.task),
+ );
+ const found = extractImages(resolved.task.description ?? "").map(
+ (image) => ({
+ url: absoluteImageUrl(image.url, session.apiUrl),
+ alt: image.alt,
+ }),
+ );
+ const images =
+ output.mode === "json" && Option.isSome(options.max)
+ ? found.slice(0, options.max.value)
+ : found;
+ yield* emit(images, (ui) =>
+ renderImagesHeading(ui, {
+ label: resolved.ticketId ?? resolved.task.id.slice(0, 8),
+ title: resolved.task.title,
+ url: resolved.url,
+ count: images.length,
+ }),
+ );
+ yield* renderImages(images, {
+ max: Option.getOrElse(options.max, () => DEFAULT_MAX_IMAGES),
+ });
+ },
+);
+
+export const taskImages = Command.make(
+ "images",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or a task id"),
+ ),
+ max: Flag.Int("max").pipe(
+ Flag.withDescription(
+ `Show at most this many images (default ${DEFAULT_MAX_IMAGES}; JSON lists every image unless set)`,
+ ),
+ Flag.optional,
+ ),
+ },
+ (options) => runTaskImages(options),
+).pipe(
+ Command.withDescription(
+ "Show the images in a task description inline, or list their links",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/import.ts b/packages/cli/src/commands/task/import.ts
new file mode 100644
index 000000000..31ac21626
--- /dev/null
+++ b/packages/cli/src/commands/task/import.ts
@@ -0,0 +1,145 @@
+import { Effect, Option, Result } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { type ImportOutcome, importTasks } from "../../api/export-import.js";
+import { listColumns } from "../../api/endpoints.js";
+import { describeError } from "../../errors/describe.js";
+import { emit, note } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import { confirmDestructive } from "../../prompts/confirm-destructive.js";
+import {
+ resolveProject,
+ resolveWorkspaceId,
+} from "../../services/selection.js";
+import { Session } from "../../services/session.js";
+import { batches } from "../../transfer/batches.js";
+import { planImport } from "../../transfer/import-plan.js";
+import { buildImportReport } from "../../transfer/import-report.js";
+import { parseImportDocument } from "../../transfer/parse-import-file.js";
+import { readImportSource } from "../../transfer/read-import-source.js";
+import {
+ renderImportReport,
+ renderImportWarnings,
+} from "../../transfer/render-import-report.js";
+import { ApiLayer } from "../api-layer.js";
+
+const BATCH_SIZE = 50;
+
+function tasks(count: number): string {
+ return count === 1 ? "1 task" : `${count} tasks`;
+}
+
+export const runTaskImport = Effect.fn("command.task.import")(
+ function* (options: {
+ readonly file: string;
+ readonly project: Option.Option<string>;
+ readonly dryRun: boolean;
+ readonly yes: boolean;
+ }) {
+ const session = yield* Session;
+ const output = yield* Output;
+ const content = yield* readImportSource(options.file);
+ const candidates = yield* Effect.fromResult(
+ parseImportDocument(
+ content,
+ options.file === "-" ? "stdin" : options.file,
+ ),
+ );
+ const workspaceId = yield* resolveWorkspaceId();
+ const project = yield* resolveProject(workspaceId, options.project);
+ const columns = yield* withSpinner(`Loading ${project.name}`)(
+ listColumns(project.id),
+ );
+ const plan = planImport(candidates, columns);
+ const report = (outcomes: ReadonlyArray<ImportOutcome> | null) =>
+ buildImportReport({
+ project,
+ columns,
+ webUrl: session.webUrl,
+ plan,
+ outcomes,
+ });
+
+ if (options.dryRun) {
+ return yield* emit(report(null), renderImportReport);
+ }
+
+ const preview = report(null);
+ if (
+ output.mode === "human" &&
+ renderImportWarnings(output.errUi, preview).length > 0
+ ) {
+ yield* note((ui) => ["", ...renderImportWarnings(ui, preview), ""]);
+ }
+ const count = tasks(plan.tasks.length);
+ yield* confirmDestructive({
+ yes: options.yes,
+ action: `Importing ${count} into ${project.name}`,
+ question: `Import ${count} into ${project.name}? Running the import again creates them again.`,
+ });
+
+ const outcomes: ImportOutcome[] = [];
+ for (const batch of batches(plan.tasks, BATCH_SIZE)) {
+ const done = outcomes.length;
+ const label =
+ plan.tasks.length > BATCH_SIZE
+ ? `Importing ${done + 1} to ${done + batch.length} of ${plan.tasks.length}`
+ : `Importing ${count}`;
+ const result = yield* withSpinner(label)(
+ importTasks(project.id, batch),
+ ).pipe(Effect.result);
+ if (Result.isFailure(result)) {
+ if (done === 0) return yield* Effect.fail(result.failure);
+ const error = `Not imported: ${describeError(result.failure).message}`;
+ outcomes.push(
+ ...plan.tasks.slice(done).map((task): ImportOutcome => ({
+ success: false,
+ error,
+ task: { title: task.title },
+ })),
+ );
+ break;
+ }
+ outcomes.push(...result.success.results.tasks);
+ }
+
+ const final = report(outcomes);
+ yield* emit(final, renderImportReport);
+ if (final.failed > 0 || final.imported < final.total) {
+ yield* Effect.sync(() => {
+ process.exitCode = 1;
+ });
+ }
+ },
+);
+
+export const taskImport = Command.make(
+ "import",
+ {
+ file: Argument.String("file").pipe(
+ Argument.withDescription(
+ "JSON file from kaneo task export (or a list of tasks), or - for stdin",
+ ),
+ ),
+ project: Flag.String("project").pipe(
+ Flag.withAlias("p"),
+ Flag.withDescription("Project to import into, for example KAN"),
+ Flag.optional,
+ ),
+ dryRun: Flag.Boolean("dry-run").pipe(
+ Flag.withDescription("Check the file and show what would be imported"),
+ Flag.withDefault(false),
+ ),
+ yes: Flag.Boolean("yes").pipe(
+ Flag.withAlias("y"),
+ Flag.withDescription("Import without asking for confirmation"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runTaskImport(options),
+).pipe(
+ Command.withDescription(
+ "Create tasks in a project from a JSON file; labels are not imported",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/index.ts b/packages/cli/src/commands/task/index.ts
new file mode 100644
index 000000000..04f2ec36e
--- /dev/null
+++ b/packages/cli/src/commands/task/index.ts
@@ -0,0 +1,49 @@
+import { Command } from "effect/cli";
+import { taskActivity } from "./activity.js";
+import { taskAssign } from "./assign.js";
+import { taskAttach } from "./attach.js";
+import { taskBulk } from "./bulk.js";
+import { taskComment } from "./comment.js";
+import { taskCreate } from "./create.js";
+import { taskDelete } from "./delete.js";
+import { taskDuplicate } from "./duplicate.js";
+import { taskEdit } from "./edit.js";
+import { taskExport } from "./export.js";
+import { taskField } from "./field.js";
+import { taskImages } from "./images.js";
+import { taskImport } from "./import.js";
+import { taskLink } from "./link/index.js";
+import { taskList } from "./list.js";
+import { taskMine } from "./mine.js";
+import { taskMove } from "./move.js";
+import { taskOpen } from "./open.js";
+import { taskRelation } from "./relation.js";
+import { taskStatus } from "./status.js";
+import { taskView } from "./view.js";
+
+export const task = Command.make("task").pipe(
+ Command.withDescription("Work with tasks"),
+ Command.withSubcommands([
+ taskList,
+ taskMine,
+ taskView,
+ taskCreate,
+ taskEdit,
+ taskOpen,
+ taskStatus,
+ taskMove,
+ taskDuplicate,
+ taskBulk,
+ taskAssign,
+ taskField,
+ taskComment,
+ taskAttach,
+ taskImages,
+ taskRelation,
+ taskLink,
+ taskActivity,
+ taskDelete,
+ taskExport,
+ taskImport,
+ ]),
+);
diff --git a/packages/cli/src/commands/task/link/add.ts b/packages/cli/src/commands/task/link/add.ts
new file mode 100644
index 000000000..937e94a90
--- /dev/null
+++ b/packages/cli/src/commands/task/link/add.ts
@@ -0,0 +1,72 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { createExternalLink } from "../../../api/external-links.js";
+import {
+ validateLinkTitle,
+ validateLinkUrl,
+} from "../../../external-links/link-input.js";
+import { toLinkJson } from "../../../external-links/link-json.js";
+import { renderLinkChange } from "../../../external-links/render-link-change.js";
+import { emit } from "../../../output/emit.js";
+import { withSpinner } from "../../../output/spinner.js";
+import { resolveTask } from "../../../tasks/resolve-task.js";
+import { ApiLayer } from "../../api-layer.js";
+
+export const runTaskLinkAdd = Effect.fn("command.task.link.add")(
+ function* (options: {
+ readonly task: string;
+ readonly url: string;
+ readonly title: Option.Option<string>;
+ }) {
+ const url = yield* Effect.fromResult(validateLinkUrl(options.url));
+ const title = yield* Option.match(options.title, {
+ onNone: () => Effect.succeed(undefined),
+ onSome: (value) => Effect.fromResult(validateLinkTitle(value)),
+ });
+ const resolved = yield* withSpinner(`Loading ${options.task.trim()}`)(
+ resolveTask(options.task),
+ );
+ const label = resolved.ticketId ?? resolved.task.id.slice(0, 8);
+ const link = yield* withSpinner(`Linking ${label}`)(
+ createExternalLink(resolved.task.id, {
+ url,
+ ...(title === undefined ? {} : { title }),
+ }),
+ );
+ yield* emit(
+ {
+ ...toLinkJson(link),
+ taskId: resolved.task.id,
+ ticketId: resolved.ticketId,
+ },
+ (ui, json) =>
+ renderLinkChange(ui, {
+ verb: "Linked",
+ taskLabel: label,
+ taskUrl: resolved.url,
+ linkTitle: json.title ? `${json.title} (${json.url})` : json.url,
+ }),
+ );
+ },
+);
+
+export const taskLinkAdd = Command.make(
+ "add",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or the task id"),
+ ),
+ url: Argument.String("url").pipe(
+ Argument.withDescription("An http or https address"),
+ ),
+ title: Flag.String("title").pipe(
+ Flag.withAlias("t"),
+ Flag.withDescription("Text to show instead of the address"),
+ Flag.optional,
+ ),
+ },
+ (options) => runTaskLinkAdd(options),
+).pipe(
+ Command.withDescription("Attach a link to a task"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/link/index.ts b/packages/cli/src/commands/task/link/index.ts
new file mode 100644
index 000000000..b51f28d84
--- /dev/null
+++ b/packages/cli/src/commands/task/link/index.ts
@@ -0,0 +1,9 @@
+import { Command } from "effect/cli";
+import { taskLinkAdd } from "./add.js";
+import { taskLinkList } from "./list.js";
+import { taskLinkRemove } from "./remove.js";
+
+export const taskLink = Command.make("link").pipe(
+ Command.withDescription("List, add and remove a task's links"),
+ Command.withSubcommands([taskLinkList, taskLinkAdd, taskLinkRemove]),
+);
diff --git a/packages/cli/src/commands/task/link/list.ts b/packages/cli/src/commands/task/link/list.ts
new file mode 100644
index 000000000..06bab12ef
--- /dev/null
+++ b/packages/cli/src/commands/task/link/list.ts
@@ -0,0 +1,44 @@
+import { Effect } from "effect";
+import { Argument, Command } from "effect/cli";
+import { listExternalLinks } from "../../../api/external-links.js";
+import { toLinkJson } from "../../../external-links/link-json.js";
+import { renderLinkList } from "../../../external-links/render-link-list.js";
+import { emit } from "../../../output/emit.js";
+import { withSpinner } from "../../../output/spinner.js";
+import { resolveTask } from "../../../tasks/resolve-task.js";
+import { ApiLayer } from "../../api-layer.js";
+
+export const runTaskLinkList = Effect.fn("command.task.link.list")(
+ function* (options: { readonly task: string }) {
+ const resolved = yield* withSpinner(`Loading ${options.task.trim()}`)(
+ resolveTask(options.task),
+ );
+ const links = yield* withSpinner("Loading links")(
+ listExternalLinks(resolved.task.id),
+ );
+ const json = links.map(toLinkJson);
+ yield* emit(json, (ui) =>
+ renderLinkList(ui, {
+ taskLabel: resolved.ticketId ?? resolved.task.id.slice(0, 8),
+ taskTitle: resolved.task.title,
+ taskUrl: resolved.url,
+ links: json,
+ }),
+ );
+ },
+);
+
+export const taskLinkList = Command.make(
+ "list",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or the task id"),
+ ),
+ },
+ (options) => runTaskLinkList(options),
+).pipe(
+ Command.withDescription(
+ "List a task's links, including issues and pull requests from integrations",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/link/remove.ts b/packages/cli/src/commands/task/link/remove.ts
new file mode 100644
index 000000000..0ec252819
--- /dev/null
+++ b/packages/cli/src/commands/task/link/remove.ts
@@ -0,0 +1,98 @@
+import { Effect } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import {
+ deleteExternalLink,
+ listExternalLinks,
+} from "../../../api/external-links.js";
+import { InvalidArgument } from "../../../errors/errors.js";
+import { isManualLink, toLinkJson } from "../../../external-links/link-json.js";
+import { matchLink } from "../../../external-links/match-link.js";
+import { renderLinkChange } from "../../../external-links/render-link-change.js";
+import { emit } from "../../../output/emit.js";
+import { withSpinner } from "../../../output/spinner.js";
+import { confirmDestructive } from "../../../prompts/confirm-destructive.js";
+import { resolveTask } from "../../../tasks/resolve-task.js";
+import { ApiLayer } from "../../api-layer.js";
+
+export const runTaskLinkRemove = Effect.fn("command.task.link.remove")(
+ function* (options: {
+ readonly task: string;
+ readonly link: string;
+ readonly yes: boolean;
+ }) {
+ const resolved = yield* withSpinner(`Loading ${options.task.trim()}`)(
+ resolveTask(options.task),
+ );
+ const label = resolved.ticketId ?? resolved.task.id.slice(0, 8);
+ const links = yield* withSpinner("Loading links")(
+ listExternalLinks(resolved.task.id),
+ );
+ const match = matchLink(links, options.link);
+ if (match.kind === "none") {
+ return yield* new InvalidArgument({
+ message: `${label} has no link matching "${options.link.trim()}".`,
+ hint: `Run kaneo task link list ${label} to see the link ids.`,
+ });
+ }
+ if (match.kind === "ambiguous") {
+ return yield* new InvalidArgument({
+ message: `"${options.link.trim()}" matches ${match.candidates.length} links on ${label}.`,
+ hint: `Pass the full id: ${match.candidates.map((link) => link.id).join(", ")}.`,
+ });
+ }
+ const link = match.link;
+ if (!isManualLink(link)) {
+ return yield* new InvalidArgument({
+ message: `This link comes from the ${link.integration?.type ?? "connected"} integration, so it cannot be removed here.`,
+ hint: "Remove it on the integration's side, or disconnect the integration.",
+ });
+ }
+ const name = link.title ?? link.url;
+ yield* confirmDestructive({
+ yes: options.yes,
+ action: `Removing the link from ${label}`,
+ question: `Remove ${name} from ${label}?`,
+ });
+ yield* withSpinner(`Removing the link from ${label}`)(
+ deleteExternalLink(resolved.task.id, link.id),
+ );
+ yield* emit(
+ {
+ ...toLinkJson(link),
+ taskId: resolved.task.id,
+ ticketId: resolved.ticketId,
+ removed: true,
+ },
+ (ui) =>
+ renderLinkChange(ui, {
+ verb: "Unlinked",
+ taskLabel: label,
+ taskUrl: resolved.url,
+ linkTitle: name,
+ }),
+ );
+ },
+);
+
+export const taskLinkRemove = Command.make(
+ "remove",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or the task id"),
+ ),
+ link: Argument.String("link").pipe(
+ Argument.withDescription(
+ "Link id from kaneo task link list (the first characters are enough), or its URL",
+ ),
+ ),
+ yes: Flag.Boolean("yes").pipe(
+ Flag.withAlias("y"),
+ Flag.withDescription("Remove without asking for confirmation"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runTaskLinkRemove(options),
+).pipe(
+ Command.withDescription("Remove a link you added from a task"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/list.ts b/packages/cli/src/commands/task/list.ts
new file mode 100644
index 000000000..211063ea2
--- /dev/null
+++ b/packages/cli/src/commands/task/list.ts
@@ -0,0 +1,209 @@
+import { Effect, Option } from "effect";
+import { Command, Flag } from "effect/cli";
+import { getCurrentUser } from "../../api/endpoints.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import {
+ resolveProject,
+ resolveWorkspaceId,
+} from "../../services/selection.js";
+import { Session } from "../../services/session.js";
+import {
+ checkDueWindow,
+ dueBound,
+ filterTasks,
+ needsClientFilter,
+ SORT_FIELDS,
+ SORT_ORDERS,
+ type SortField,
+ type SortOrder,
+ sortTasks,
+ toTaskSort,
+} from "../../tasks/list-query.js";
+import { loadBoard } from "../../tasks/load-board.js";
+import { renderTaskList } from "../../tasks/render-task-list.js";
+import { toTaskJson } from "../../tasks/task-json.js";
+import { ApiLayer } from "../api-layer.js";
+
+const PRIORITIES = ["no-priority", "low", "medium", "high", "urgent"] as const;
+
+const dueFlag = (
+ input: Option.Option<string>,
+ now: Date,
+ edge: "before" | "after",
+) =>
+ Option.match(input, {
+ onNone: () => Effect.succeed(undefined),
+ onSome: (value) => Effect.fromResult(dueBound(value, now, edge)),
+ });
+
+export const runTaskList = Effect.fn("command.task.list")(function* (options: {
+ readonly project: Option.Option<string>;
+ readonly status: Option.Option<string>;
+ readonly priority: Option.Option<string>;
+ readonly assignee: Option.Option<string>;
+ readonly mine: boolean;
+ readonly label: ReadonlyArray<string>;
+ readonly open: boolean;
+ readonly sort: Option.Option<SortField>;
+ readonly order: Option.Option<SortOrder>;
+ readonly dueBefore: Option.Option<string>;
+ readonly dueAfter: Option.Option<string>;
+ readonly all: boolean;
+ readonly limit: number;
+}) {
+ const session = yield* Session;
+ if (options.mine && Option.isSome(options.assignee)) {
+ return yield* new InvalidArgument({
+ message: "Pass either --mine or --assignee, not both.",
+ hint: "--mine is the same as --assignee me.",
+ });
+ }
+ const sort = yield* Effect.fromResult(
+ toTaskSort(
+ Option.getOrUndefined(options.sort),
+ Option.getOrUndefined(options.order),
+ ),
+ );
+ const now = new Date();
+ const dueBefore = yield* dueFlag(options.dueBefore, now, "before");
+ const dueAfter = yield* dueFlag(options.dueAfter, now, "after");
+ yield* Effect.fromResult(checkDueWindow(dueAfter, dueBefore));
+ const clientFilters = { labels: options.label, open: options.open };
+ const filtered = needsClientFilter(clientFilters);
+
+ const workspaceId = yield* resolveWorkspaceId();
+ const project = yield* resolveProject(workspaceId, options.project);
+ const assignee = options.mine
+ ? Option.some("me")
+ : Option.map(options.assignee, (value) => value.trim());
+ const assigneeId = yield* Option.match(assignee, {
+ onNone: () => Effect.succeed(undefined),
+ onSome: (value) =>
+ value.toLowerCase() === "me"
+ ? Effect.map(getCurrentUser(), (user) => user.id)
+ : Effect.succeed(value),
+ });
+ const limit = options.all ? Number.POSITIVE_INFINITY : options.limit;
+ const board = yield* withSpinner(`Loading ${project.name}`)(
+ loadBoard(
+ project.id,
+ {
+ status: Option.getOrUndefined(options.status),
+ priority: Option.getOrUndefined(options.priority),
+ assigneeId,
+ sortBy: sort?.sortBy,
+ sortOrder: sort?.sortOrder,
+ dueBefore,
+ dueAfter,
+ },
+ filtered ? Number.POSITIVE_INFINITY : limit,
+ ),
+ );
+ const matching = filtered
+ ? filterTasks(board.tasks, board.columns, clientFilters)
+ : board.tasks;
+ const ordered = sort ? sortTasks(matching, sort) : matching;
+ const tasks = ordered.slice(0, limit).map((task) => ({
+ ...toTaskJson(board, task, session.webUrl),
+ labels: (task.labels ?? []).map(({ id, name, color }) => ({
+ id,
+ name,
+ color,
+ })),
+ }));
+
+ yield* emit(tasks, (ui) =>
+ renderTaskList(ui, {
+ projectName: board.projectName || project.name,
+ projectSlug: board.projectSlug || project.slug,
+ projectId: project.id,
+ workspaceId: board.workspaceId || workspaceId,
+ webUrl: session.webUrl,
+ columns: board.columns,
+ tasks,
+ total: filtered ? matching.length : board.total,
+ now,
+ }),
+ );
+});
+
+export const taskList = Command.make(
+ "list",
+ {
+ project: Flag.String("project").pipe(
+ Flag.withAlias("p"),
+ Flag.withDescription("Project key or id, for example KAN"),
+ Flag.optional,
+ ),
+ status: Flag.String("status").pipe(
+ Flag.withAlias("s"),
+ Flag.withDescription(
+ "Only tasks in this column, by slug (for example in-progress)",
+ ),
+ Flag.optional,
+ ),
+ priority: Flag.Literals("priority", PRIORITIES).pipe(
+ Flag.withDescription("Only tasks with this priority"),
+ Flag.optional,
+ ),
+ assignee: Flag.String("assignee").pipe(
+ Flag.withAlias("a"),
+ Flag.withDescription('Only tasks assigned to this user id, or "me"'),
+ Flag.optional,
+ ),
+ mine: Flag.Boolean("mine").pipe(
+ Flag.withDescription("Only tasks assigned to you, like --assignee me"),
+ Flag.withDefault(false),
+ ),
+ label: Flag.String("label").pipe(
+ Flag.withAlias("l"),
+ Flag.withDescription(
+ "Only tasks with this label; repeat to require several",
+ ),
+ Flag.atLeast(0),
+ ),
+ open: Flag.Boolean("open").pipe(
+ Flag.withDescription("Hide tasks in done columns"),
+ Flag.withDefault(false),
+ ),
+ sort: Flag.Literals("sort", SORT_FIELDS).pipe(
+ Flag.withDescription(
+ "Sort by created, priority, due, position, title or number",
+ ),
+ Flag.optional,
+ ),
+ order: Flag.Literals("order", SORT_ORDERS).pipe(
+ Flag.withDescription(
+ "Sort order (default: desc for created and priority, asc otherwise)",
+ ),
+ Flag.optional,
+ ),
+ dueBefore: Flag.String("due-before").pipe(
+ Flag.withDescription(
+ "Only tasks due on or before this day: YYYY-MM-DD, today, tomorrow or +3d",
+ ),
+ Flag.optional,
+ ),
+ dueAfter: Flag.String("due-after").pipe(
+ Flag.withDescription(
+ "Only tasks due on or after this day: YYYY-MM-DD, today, tomorrow or +3d",
+ ),
+ Flag.optional,
+ ),
+ all: Flag.Boolean("all").pipe(
+ Flag.withDescription("Show every matching task instead of --limit"),
+ Flag.withDefault(false),
+ ),
+ limit: Flag.Int("limit").pipe(
+ Flag.withAlias("L"),
+ Flag.withDescription("Maximum number of tasks to show"),
+ Flag.withDefault(50),
+ ),
+ },
+ (options) => runTaskList(options),
+).pipe(
+ Command.withDescription("List tasks in a project, grouped by column"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/mine.test.ts b/packages/cli/src/commands/task/mine.test.ts
new file mode 100644
index 000000000..378b34eff
--- /dev/null
+++ b/packages/cli/src/commands/task/mine.test.ts
@@ -0,0 +1,159 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { AssignedTask } from "../../api/schemas.js";
+import { makeUi } from "../../render/ui.js";
+import { stringWidth } from "../../render/width.js";
+import { renderMine, toMineTaskJson } from "./mine.js";
+
+const ui = (columns: number) =>
+ makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns,
+ });
+
+const now = new Date(2026, 9, 8, 12, 0);
+
+function assigned(
+ number: number,
+ title: string,
+ overrides: Partial<AssignedTask> = {},
+): AssignedTask {
+ return {
+ id: `t${number}`,
+ projectId: "p_kan",
+ number,
+ title,
+ status: "in-progress",
+ statusName: "In Progress",
+ priority: "high",
+ dueDate: new Date(2026, 9, 8, 12).toISOString(),
+ projectName: "Kaneo Web",
+ projectSlug: "kan",
+ ...overrides,
+ };
+}
+
+const webUrl = "https://kaneo.test";
+
+describe("toMineTaskJson", () => {
+ it("adds the ticket id, workspace and link", () => {
+ expect(toMineTaskJson(assigned(1, "Fix login"), "ws_1", webUrl)).toEqual({
+ id: "t1",
+ ticketId: "KAN-1",
+ number: 1,
+ title: "Fix login",
+ status: "in-progress",
+ statusName: "In Progress",
+ priority: "high",
+ dueDate: new Date(2026, 9, 8, 12).toISOString(),
+ projectId: "p_kan",
+ projectName: "Kaneo Web",
+ projectSlug: "kan",
+ workspaceId: "ws_1",
+ url: "https://kaneo.test/dashboard/workspace/ws_1/project/p_kan/task/t1",
+ });
+ });
+
+ it("falls back to the status slug without a column name", () => {
+ expect(
+ toMineTaskJson(assigned(2, "Old", { statusName: null }), "ws_1", webUrl)
+ .statusName,
+ ).toBe("in-progress");
+ });
+});
+
+describe("renderMine", () => {
+ const tasks = [
+ toMineTaskJson(
+ assigned(1, "Fix login redirect after device sign in"),
+ "ws_1",
+ webUrl,
+ ),
+ toMineTaskJson(
+ assigned(4, "Dark mode polish", {
+ status: "to-do",
+ statusName: "To Do",
+ priority: "low",
+ dueDate: null,
+ projectName: "Mobile App",
+ projectSlug: "mob",
+ }),
+ "ws_1",
+ webUrl,
+ ),
+ ];
+
+ it("shows status, priority, due and project at 80 columns", () => {
+ expect(
+ renderMine(
+ ui(80),
+ [
+ {
+ workspaceId: "ws_1",
+ workspaceName: "Acme Studio",
+ tasks,
+ total: 3,
+ },
+ ],
+ now,
+ ),
+ ).toEqual([
+ "",
+ " Acme Studio · 3 open",
+ " KAN-1 Fix login redirect after… ● In Progress ▆ High ◷ Today Kaneo Web",
+ " MOB-4 Dark mode polish ● To Do ▂ Low Mobile App",
+ " and 1 more, sorted by due date",
+ "",
+ ]);
+ });
+
+ it("drops optional columns before squeezing titles", () => {
+ for (const line of renderMine(
+ ui(50),
+ [{ workspaceId: "ws_1", workspaceName: "Acme Studio", tasks, total: 2 }],
+ now,
+ )) {
+ expect(stringWidth(line)).toBeLessThanOrEqual(50);
+ }
+ });
+
+ it("groups by workspace and skips empty ones", () => {
+ const lines = renderMine(
+ ui(80),
+ [
+ {
+ workspaceId: "ws_1",
+ workspaceName: "Acme Studio",
+ tasks: tasks.slice(0, 1),
+ total: 1,
+ },
+ {
+ workspaceId: "ws_2",
+ workspaceName: "Side Project",
+ tasks: [],
+ total: 0,
+ },
+ {
+ workspaceId: "ws_3",
+ workspaceName: "Client Work",
+ tasks: tasks.slice(1),
+ total: 1,
+ },
+ ],
+ now,
+ );
+ expect(
+ lines.filter((line) => line.startsWith(" ") && !line.startsWith(" ")),
+ ).toEqual([" Acme Studio · 1 open", " Client Work · 1 open"]);
+ });
+
+ it("celebrates an empty list", () => {
+ expect(renderMine(ui(80), [], now)).toEqual([
+ "",
+ " ● Nothing assigned to you. Nice.",
+ "",
+ ]);
+ });
+});
diff --git a/packages/cli/src/commands/task/mine.ts b/packages/cli/src/commands/task/mine.ts
new file mode 100644
index 000000000..7978607d9
--- /dev/null
+++ b/packages/cli/src/commands/task/mine.ts
@@ -0,0 +1,228 @@
+import { Effect } from "effect";
+import { Command, Flag } from "effect/cli";
+import {
+ getWorkspace,
+ listAssignedTasks,
+ listWorkspaces,
+} from "../../api/endpoints.js";
+import type { AssignedTask } from "../../api/schemas.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { type Cell, text } from "../../render/cell.js";
+import { taskUrl } from "../../render/links.js";
+import { renderTable } from "../../render/table.js";
+import {
+ dueSegments,
+ prioritySegments,
+ statusDot,
+ ticketId,
+} from "../../render/task-format.js";
+import type { Ui } from "../../render/ui.js";
+import { resolveWorkspaceId } from "../../services/selection.js";
+import { Session } from "../../services/session.js";
+import { ApiLayer } from "../api-layer.js";
+
+export type MineTaskJson = {
+ readonly id: string;
+ readonly ticketId: string | null;
+ readonly number: number | null;
+ readonly title: string;
+ readonly status: string;
+ readonly statusName: string;
+ readonly priority: string;
+ readonly dueDate: string | null;
+ readonly projectId: string;
+ readonly projectName: string;
+ readonly projectSlug: string;
+ readonly workspaceId: string;
+ readonly url: string;
+};
+
+export type MineGroup = {
+ readonly workspaceId: string;
+ readonly workspaceName: string;
+ readonly tasks: ReadonlyArray<MineTaskJson>;
+ readonly total: number;
+};
+
+export function toMineTaskJson(
+ task: AssignedTask,
+ workspaceId: string,
+ webUrl: string,
+): MineTaskJson {
+ return {
+ id: task.id,
+ ticketId: ticketId(task.projectSlug, task.number),
+ number: task.number,
+ title: task.title,
+ status: task.status,
+ statusName: task.statusName ?? task.status,
+ priority: task.priority,
+ dueDate: task.dueDate,
+ projectId: task.projectId,
+ projectName: task.projectName,
+ projectSlug: task.projectSlug,
+ workspaceId,
+ url: taskUrl(webUrl, {
+ workspaceId,
+ projectId: task.projectId,
+ id: task.id,
+ }),
+ };
+}
+
+export function renderMine(
+ ui: Ui,
+ groups: ReadonlyArray<MineGroup>,
+ now: Date,
+): string[] {
+ const { theme, glyphs } = ui;
+ const filled = groups.filter((group) => group.tasks.length > 0);
+ if (filled.length === 0) {
+ return [
+ "",
+ ` ${theme.muted(glyphs.dot)} Nothing assigned to you. Nice.`,
+ "",
+ ];
+ }
+ const rows = renderTable(
+ ui,
+ filled.flatMap((group) => group.tasks),
+ [
+ {
+ header: "ID",
+ cell: (task): Cell => [
+ text(task.ticketId ?? task.id.slice(0, 8), theme.muted, task.url),
+ ],
+ },
+ {
+ header: "Title",
+ flex: true,
+ minWidth: 16,
+ cell: (task): Cell => [text(task.title, undefined, task.url)],
+ },
+ {
+ header: "Status",
+ minWidth: 6,
+ cell: (task): Cell => [
+ statusDot(ui, task.status, false),
+ text(` ${task.statusName}`),
+ ],
+ },
+ {
+ header: "Priority",
+ optional: true,
+ cell: (task): Cell => prioritySegments(ui, task.priority),
+ },
+ {
+ header: "Due",
+ optional: true,
+ cell: (task): Cell => dueSegments(ui, task.dueDate, false, now),
+ },
+ {
+ header: "Project",
+ optional: true,
+ minWidth: 10,
+ cell: (task): Cell => [text(task.projectName, theme.muted)],
+ },
+ ],
+ { width: ui.caps.columns, indent: 4 },
+ );
+ const lines = [""];
+ let offset = 0;
+ for (const group of filled) {
+ lines.push(
+ ` ${theme.strong(group.workspaceName)} ${theme.muted(`${glyphs.separator} ${group.total} open`)}`,
+ ...rows.slice(offset, offset + group.tasks.length),
+ );
+ if (group.total > group.tasks.length) {
+ lines.push(
+ ` ${theme.muted(`and ${group.total - group.tasks.length} more, sorted by due date`)}`,
+ );
+ }
+ lines.push("");
+ offset += group.tasks.length;
+ }
+ return lines;
+}
+
+function toGroup(
+ workspace: { readonly id: string; readonly name: string },
+ assigned: {
+ readonly tasks: ReadonlyArray<AssignedTask>;
+ readonly total: number;
+ },
+ webUrl: string,
+): MineGroup {
+ return {
+ workspaceId: workspace.id,
+ workspaceName: workspace.name,
+ tasks: assigned.tasks.map((task) =>
+ toMineTaskJson(task, workspace.id, webUrl),
+ ),
+ total: assigned.total,
+ };
+}
+
+export const runTaskMine = Effect.fn("command.task.mine")(function* (options: {
+ readonly allWorkspaces: boolean;
+}) {
+ const session = yield* Session;
+ const groups = options.allWorkspaces
+ ? yield* withSpinner("Loading your tasks")(
+ listWorkspaces().pipe(
+ Effect.flatMap((workspaces) =>
+ Effect.forEach(
+ workspaces,
+ (workspace) =>
+ listAssignedTasks(workspace.id).pipe(
+ Effect.map((assigned) => [
+ toGroup(workspace, assigned, session.webUrl),
+ ]),
+ Effect.catchTag("PermissionDenied", () => Effect.succeed([])),
+ ),
+ { concurrency: 4 },
+ ),
+ ),
+ Effect.map((loaded) => loaded.flat()),
+ ),
+ )
+ : yield* Effect.gen(function* () {
+ const workspaceId = yield* resolveWorkspaceId();
+ const [workspace, assigned] = yield* withSpinner("Loading your tasks")(
+ Effect.all(
+ [
+ getWorkspace(workspaceId).pipe(
+ Effect.catchTag("NotFound", () =>
+ Effect.succeed({ id: workspaceId, name: workspaceId }),
+ ),
+ ),
+ listAssignedTasks(workspaceId),
+ ],
+ { concurrency: 2 },
+ ),
+ );
+ return [toGroup(workspace, assigned, session.webUrl)];
+ });
+
+ yield* emit(
+ groups.flatMap((group) => group.tasks),
+ (ui) => renderMine(ui, groups, new Date()),
+ );
+});
+
+export const taskMine = Command.make(
+ "mine",
+ {
+ allWorkspaces: Flag.Boolean("all-workspaces").pipe(
+ Flag.withDescription("Include every workspace you belong to"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runTaskMine(options),
+).pipe(
+ Command.withDescription(
+ "List the open tasks assigned to you, soonest due first",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/move.ts b/packages/cli/src/commands/task/move.ts
new file mode 100644
index 000000000..c69fe42f3
--- /dev/null
+++ b/packages/cli/src/commands/task/move.ts
@@ -0,0 +1,161 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { listColumns, listProjects } from "../../api/endpoints.js";
+import type { Project } from "../../api/schemas.js";
+import { moveTask } from "../../api/task-actions.js";
+import { InvalidArgument, ProjectNotFound } from "../../errors/errors.js";
+import { emit, note } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import { pick } from "../../prompts/pick.js";
+import { taskUrl } from "../../render/links.js";
+import { ticketId } from "../../render/task-format.js";
+import { matchProject } from "../../services/selection.js";
+import { Session } from "../../services/session.js";
+import { matchColumn } from "../../tasks/match-column.js";
+import { renderTaskMove } from "../../tasks/render-task-move.js";
+import { resolveTask } from "../../tasks/resolve-task.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runTaskMove = Effect.fn("command.task.move")(function* (options: {
+ readonly task: string;
+ readonly project: Option.Option<string>;
+ readonly status: Option.Option<string>;
+}) {
+ const session = yield* Session;
+ const output = yield* Output;
+ const resolved = yield* withSpinner(`Loading ${options.task}`)(
+ resolveTask(options.task),
+ );
+ const fromLabel = resolved.ticketId ?? resolved.task.id.slice(0, 8);
+ const projects = (yield* withSpinner("Loading projects")(
+ listProjects(resolved.workspaceId),
+ )).filter((project) => project.archivedAt === null);
+ const others = projects.filter(
+ (project) => project.id !== resolved.project.id,
+ );
+
+ const destination: Project = yield* Option.match(options.project, {
+ onSome: (reference) => {
+ const match = matchProject(projects, reference);
+ if (!match)
+ return Effect.fail(
+ new ProjectNotFound({ query: reference, source: null }),
+ );
+ if (match.id === resolved.project.id) {
+ return Effect.fail(
+ new InvalidArgument({
+ message: `${fromLabel} is already in ${match.name}.`,
+ hint: "Pass --project with another project key, or use kaneo task status to change its column.",
+ }),
+ );
+ }
+ return Effect.succeed(match);
+ },
+ onNone: () => {
+ if (others.length === 0) {
+ return Effect.fail(
+ new InvalidArgument({
+ message: `There is no other project to move ${fromLabel} to.`,
+ }),
+ );
+ }
+ return output.interactive
+ ? pick(
+ `Move ${fromLabel} to`,
+ others.map((project) => ({
+ title: project.name,
+ value: project,
+ description: project.slug.toUpperCase(),
+ })),
+ )
+ : Effect.fail(
+ new InvalidArgument({
+ message: `Pass the project to move ${fromLabel} to.`,
+ hint: `Pass --project with a project key, for example --project ${others[0]?.slug.toUpperCase() ?? "KAN"}.`,
+ }),
+ );
+ },
+ });
+
+ const status = yield* Option.match(options.status, {
+ onNone: () => Effect.succeed(undefined),
+ onSome: (reference) =>
+ withSpinner(`Loading ${destination.name}`)(
+ listColumns(destination.id),
+ ).pipe(
+ Effect.flatMap((columns) => {
+ const match = matchColumn(columns, reference);
+ return match
+ ? Effect.succeed(match.slug)
+ : Effect.fail(
+ new InvalidArgument({
+ message: `No column in ${destination.name} matches "${reference}".`,
+ hint: `Use one of: ${[...columns]
+ .sort((a, b) => a.position - b.position)
+ .map((column) => column.slug)
+ .join(", ")}.`,
+ }),
+ );
+ }),
+ ),
+ });
+
+ const moved = yield* withSpinner(
+ `Moving ${fromLabel} to ${destination.name}`,
+ )(moveTask(resolved.task.id, { projectId: destination.id, status }));
+ const toTicketId = ticketId(destination.slug, moved.task.number);
+ const url = taskUrl(session.webUrl, {
+ workspaceId: resolved.workspaceId,
+ projectId: moved.destinationProjectId,
+ id: moved.task.id,
+ });
+
+ yield* emit(
+ {
+ id: moved.task.id,
+ from: { ticketId: resolved.ticketId, projectId: moved.sourceProjectId },
+ to: { ticketId: toTicketId, projectId: moved.destinationProjectId },
+ url,
+ },
+ (ui) =>
+ renderTaskMove(ui, {
+ fromLabel,
+ toLabel: toTicketId ?? moved.task.id.slice(0, 8),
+ title: moved.task.title,
+ url,
+ }),
+ );
+
+ if (resolved.task.assigneeId && moved.task.userId === null) {
+ yield* note((ui) => [
+ ` ${ui.theme.warning(ui.glyphs.warning)} ${resolved.task.assigneeName ?? "The assignee"} cannot access ${destination.name}, so the task is now unassigned.`,
+ "",
+ ]);
+ }
+});
+
+export const taskMove = Command.make(
+ "move",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or the task id"),
+ ),
+ project: Flag.String("project").pipe(
+ Flag.withAlias("p"),
+ Flag.withDescription("Destination project key or id, for example MOB"),
+ Flag.optional,
+ ),
+ status: Flag.String("status").pipe(
+ Flag.withAlias("s"),
+ Flag.withDescription(
+ "Column in the destination project; defaults to the same column, or the first one",
+ ),
+ Flag.optional,
+ ),
+ },
+ (options) => runTaskMove(options),
+).pipe(
+ Command.withDescription("Move a task to another project"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/open.ts b/packages/cli/src/commands/task/open.ts
new file mode 100644
index 000000000..90c4a2c21
--- /dev/null
+++ b/packages/cli/src/commands/task/open.ts
@@ -0,0 +1,40 @@
+import { Effect } from "effect";
+import { Argument, Command } from "effect/cli";
+import { emit } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import { Desktop } from "../../services/desktop.js";
+import {
+ type OpenTaskResult,
+ renderOpenTask,
+} from "../../tasks/render-open-task.js";
+import { resolveTask } from "../../tasks/resolve-task.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runTaskOpen = Effect.fn("command.task.open")(function* (
+ reference: string,
+) {
+ const output = yield* Output;
+ const desktop = yield* Desktop;
+ const { url } = yield* withSpinner(`Finding ${reference.trim()}`)(
+ resolveTask(reference),
+ );
+ const opened =
+ output.mode === "human" && output.interactive
+ ? yield* desktop.openUrl(url)
+ : false;
+ yield* emit<OpenTaskResult>({ url, opened }, renderOpenTask);
+});
+
+export const taskOpen = Command.make(
+ "open",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or a task id"),
+ ),
+ },
+ ({ task }) => runTaskOpen(task),
+).pipe(
+ Command.withDescription("Open a task in your browser"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/relation.ts b/packages/cli/src/commands/task/relation.ts
new file mode 100644
index 000000000..02a360a6e
--- /dev/null
+++ b/packages/cli/src/commands/task/relation.ts
@@ -0,0 +1,11 @@
+import { Command } from "effect/cli";
+import { relationAdd } from "./relation/add.js";
+import { relationList } from "./relation/list.js";
+import { relationRemove } from "./relation/remove.js";
+
+export const taskRelation = Command.make("relation").pipe(
+ Command.withDescription(
+ "Work with parents, subtasks, blockers and related tasks",
+ ),
+ Command.withSubcommands([relationList, relationAdd, relationRemove]),
+);
diff --git a/packages/cli/src/commands/task/relation/add.ts b/packages/cli/src/commands/task/relation/add.ts
new file mode 100644
index 000000000..979583327
--- /dev/null
+++ b/packages/cli/src/commands/task/relation/add.ts
@@ -0,0 +1,84 @@
+import { Effect } from "effect";
+import { Argument, Command } from "effect/cli";
+import { createTaskRelation } from "../../../api/task-relations.js";
+import { InvalidArgument } from "../../../errors/errors.js";
+import { emit } from "../../../output/emit.js";
+import { withSpinner } from "../../../output/spinner.js";
+import {
+ parseRelationType,
+ RELATION_TYPES,
+ toApiRelation,
+} from "../../../relations/relation-types.js";
+import { renderRelationLinked } from "../../../relations/render-relation-change.js";
+import { resolvePair } from "../../../relations/resolve-pair.js";
+import { taskLabel, taskRef } from "../../../relations/task-ref.js";
+import { ApiLayer } from "../../api-layer.js";
+
+export const runRelationAdd = Effect.fn("command.task.relation.add")(
+ function* (options: {
+ readonly task: string;
+ readonly type: string;
+ readonly other: string;
+ }) {
+ const type = yield* Effect.fromResult(parseRelationType(options.type));
+ const pair = yield* resolvePair(options.task, options.other);
+ const task = taskRef(pair.task);
+ const other = taskRef(pair.other);
+ const label = taskLabel(task);
+ const otherLabel = taskLabel(other);
+
+ const relation = yield* withSpinner(`Linking ${label} and ${otherLabel}`)(
+ createTaskRelation(toApiRelation(type, task.id, other.id)),
+ ).pipe(
+ Effect.catchTag("Conflict", () =>
+ Effect.fail(
+ new InvalidArgument({
+ message: `${label} and ${otherLabel} are already linked this way.`,
+ hint: `Run kaneo task relation list ${label} to see how they are linked.`,
+ }),
+ ),
+ ),
+ );
+
+ yield* emit(
+ {
+ id: relation.id,
+ type,
+ relationType: relation.relationType,
+ sourceTaskId: relation.sourceTaskId,
+ targetTaskId: relation.targetTaskId,
+ task,
+ other,
+ },
+ (ui) =>
+ renderRelationLinked(ui, {
+ type,
+ task: { label, url: task.url },
+ other: { label: otherLabel, url: other.url, title: other.title },
+ }),
+ );
+ },
+);
+
+export const relationAdd = Command.make(
+ "add",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or the task id"),
+ ),
+ type: Argument.String("type").pipe(
+ Argument.withDescription(
+ `How the first task relates to the other: ${RELATION_TYPES.join(", ")}`,
+ ),
+ ),
+ other: Argument.String("other-task").pipe(
+ Argument.withDescription("The task to link to"),
+ ),
+ },
+ (options) => runRelationAdd(options),
+).pipe(
+ Command.withDescription(
+ "Link two tasks, for example kaneo task relation add KAN-3 blocked-by KAN-4",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/relation/list.ts b/packages/cli/src/commands/task/relation/list.ts
new file mode 100644
index 000000000..b7b9eda41
--- /dev/null
+++ b/packages/cli/src/commands/task/relation/list.ts
@@ -0,0 +1,63 @@
+import { Effect } from "effect";
+import { Argument, Command } from "effect/cli";
+import { listProjects } from "../../../api/endpoints.js";
+import { listTaskRelations } from "../../../api/task-relations.js";
+import { emit } from "../../../output/emit.js";
+import { withSpinner } from "../../../output/spinner.js";
+import { groupRelations } from "../../../relations/group-relations.js";
+import { renderRelationList } from "../../../relations/render-relation-list.js";
+import { Session } from "../../../services/session.js";
+import { resolveTask } from "../../../tasks/resolve-task.js";
+import { ApiLayer } from "../../api-layer.js";
+
+export const runRelationList = Effect.fn("command.task.relation.list")(
+ function* (options: { readonly task: string }) {
+ const session = yield* Session;
+ const { resolved, relations, projects } = yield* withSpinner(
+ `Loading relations of ${options.task}`,
+ )(
+ Effect.gen(function* () {
+ const resolved = yield* resolveTask(options.task);
+ const [relations, projects] = yield* Effect.all(
+ [
+ listTaskRelations(resolved.task.id),
+ listProjects(resolved.workspaceId),
+ ],
+ { concurrency: 2 },
+ );
+ return { resolved, relations, projects };
+ }),
+ );
+ const json = groupRelations(relations, resolved.task.id, {
+ projectSlugs: new Map(
+ projects.map((project) => [project.id, project.slug]),
+ ),
+ workspaceId: resolved.workspaceId,
+ webUrl: session.webUrl,
+ });
+
+ yield* emit(json, (ui, value) =>
+ renderRelationList(ui, {
+ label: resolved.ticketId ?? resolved.task.id.slice(0, 8),
+ title: resolved.task.title,
+ url: resolved.url,
+ relations: value,
+ }),
+ );
+ },
+);
+
+export const relationList = Command.make(
+ "list",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or the task id"),
+ ),
+ },
+ (options) => runRelationList(options),
+).pipe(
+ Command.withDescription(
+ "Show the parent, subtasks and linked tasks of a task",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/relation/remove.ts b/packages/cli/src/commands/task/relation/remove.ts
new file mode 100644
index 000000000..fb033f4c5
--- /dev/null
+++ b/packages/cli/src/commands/task/relation/remove.ts
@@ -0,0 +1,104 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import {
+ deleteTaskRelation,
+ listTaskRelations,
+} from "../../../api/task-relations.js";
+import { NotFound } from "../../../errors/errors.js";
+import { emit } from "../../../output/emit.js";
+import { withSpinner } from "../../../output/spinner.js";
+import { confirmDestructive } from "../../../prompts/confirm-destructive.js";
+import { relationsBetween } from "../../../relations/group-relations.js";
+import {
+ notLinkedPhrase,
+ parseRelationType,
+ perspectiveOf,
+ RELATION_TYPES,
+} from "../../../relations/relation-types.js";
+import { renderRelationsRemoved } from "../../../relations/render-relation-change.js";
+import { resolvePair } from "../../../relations/resolve-pair.js";
+import { taskLabel, taskRef } from "../../../relations/task-ref.js";
+import { ApiLayer } from "../../api-layer.js";
+
+export const runRelationRemove = Effect.fn("command.task.relation.remove")(
+ function* (options: {
+ readonly task: string;
+ readonly other: string;
+ readonly type: Option.Option<string>;
+ readonly yes: boolean;
+ }) {
+ const type = Option.isSome(options.type)
+ ? yield* Effect.fromResult(parseRelationType(options.type.value))
+ : undefined;
+ const pair = yield* resolvePair(options.task, options.other);
+ const task = taskRef(pair.task);
+ const other = taskRef(pair.other);
+ const label = taskLabel(task);
+ const otherLabel = taskLabel(other);
+
+ const relations = yield* withSpinner(`Loading relations of ${label}`)(
+ listTaskRelations(task.id),
+ );
+ const matches = relationsBetween(relations, task.id, other.id, type).map(
+ (relation) => ({
+ id: relation.id,
+ type: perspectiveOf(relation, task.id).type,
+ }),
+ );
+ if (matches.length === 0) {
+ return yield* new NotFound({
+ message: type
+ ? `${label} ${notLinkedPhrase(type)} ${otherLabel}.`
+ : `${label} and ${otherLabel} are not linked.`,
+ });
+ }
+ if (matches.length > 1) {
+ yield* confirmDestructive({
+ yes: options.yes,
+ action: `Removing ${matches.length} relations`,
+ question: `Remove ${matches.length} relations between ${label} and ${otherLabel} (${matches.map((match) => match.type).join(", ")})?`,
+ });
+ }
+
+ yield* withSpinner(`Unlinking ${label} and ${otherLabel}`)(
+ Effect.forEach(matches, (match) => deleteTaskRelation(match.id), {
+ discard: true,
+ }),
+ );
+
+ yield* emit({ task, other, removed: matches }, (ui) =>
+ renderRelationsRemoved(ui, {
+ types: matches.map((match) => match.type),
+ task: { label, url: task.url },
+ other: { label: otherLabel, url: other.url },
+ }),
+ );
+ },
+);
+
+export const relationRemove = Command.make(
+ "remove",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or the task id"),
+ ),
+ other: Argument.String("other-task").pipe(
+ Argument.withDescription("The linked task"),
+ ),
+ type: Flag.String("type").pipe(
+ Flag.withAlias("t"),
+ Flag.withDescription(
+ `Remove only this relation: ${RELATION_TYPES.join(", ")}`,
+ ),
+ Flag.optional,
+ ),
+ yes: Flag.Boolean("yes").pipe(
+ Flag.withAlias("y"),
+ Flag.withDescription(
+ "Remove several relations without asking for confirmation",
+ ),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runRelationRemove(options),
+).pipe(Command.withDescription("Unlink two tasks"), Command.provide(ApiLayer));
diff --git a/packages/cli/src/commands/task/status.ts b/packages/cli/src/commands/task/status.ts
new file mode 100644
index 000000000..24def924a
--- /dev/null
+++ b/packages/cli/src/commands/task/status.ts
@@ -0,0 +1,130 @@
+import { Effect, Option } from "effect";
+import { Argument, Command } from "effect/cli";
+import type { Column } from "../../api/schemas.js";
+import { updateTaskStatus } from "../../api/task-actions.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import { pick } from "../../prompts/pick.js";
+import { renderCell, text } from "../../render/cell.js";
+import { statusDot } from "../../render/task-format.js";
+import { matchColumn } from "../../tasks/match-column.js";
+import {
+ renderStatusChange,
+ type StatusRef,
+} from "../../tasks/render-status-change.js";
+import { resolveTask } from "../../tasks/resolve-task.js";
+import { ApiLayer } from "../api-layer.js";
+
+function statusRef(columns: ReadonlyArray<Column>, slug: string): StatusRef {
+ const column = columns.find((candidate) => candidate.slug === slug);
+ return {
+ slug,
+ name: column?.name ?? slug.charAt(0).toUpperCase() + slug.slice(1),
+ isFinal: column?.isFinal ?? false,
+ };
+}
+
+export const runTaskStatus = Effect.fn("command.task.status")(
+ function* (options: {
+ readonly task: string;
+ readonly status: Option.Option<string>;
+ }) {
+ const output = yield* Output;
+ const resolved = yield* withSpinner(`Loading ${options.task}`)(
+ resolveTask(options.task, { columns: true }),
+ );
+ const label = resolved.ticketId ?? resolved.task.id.slice(0, 8);
+ const columns = [...resolved.columns].sort(
+ (a, b) => a.position - b.position,
+ );
+ const slugs = columns.map((column) => column.slug).join(", ");
+ if (columns.length === 0) {
+ return yield* new InvalidArgument({
+ message: `${resolved.project.name} has no columns to move ${label} to.`,
+ });
+ }
+
+ const target: Column = yield* Option.match(options.status, {
+ onSome: (reference) => {
+ const match = matchColumn(columns, reference);
+ return match
+ ? Effect.succeed(match)
+ : Effect.fail(
+ new InvalidArgument({
+ message: `No column in ${resolved.project.name} matches "${reference}".`,
+ hint: `Use one of: ${slugs}.`,
+ }),
+ );
+ },
+ onNone: () =>
+ output.interactive
+ ? pick(
+ `Move ${label} to`,
+ columns.map((column) => ({
+ title: renderCell(
+ [
+ statusDot(output.ui, column.slug, column.isFinal),
+ text(` ${column.name}`),
+ ],
+ output.ui,
+ ),
+ value: column,
+ description:
+ column.slug === resolved.task.status
+ ? `${column.slug}, current`
+ : column.slug,
+ })),
+ )
+ : Effect.fail(
+ new InvalidArgument({
+ message: `Pass the column to move ${label} to.`,
+ hint: `Use one of: ${slugs}.`,
+ }),
+ ),
+ });
+
+ const from = statusRef(columns, resolved.task.status);
+ if (target.slug !== resolved.task.status) {
+ yield* withSpinner(`Moving ${label}`)(
+ updateTaskStatus(resolved.task.id, target.slug),
+ );
+ }
+ const to = {
+ slug: target.slug,
+ name: target.name,
+ isFinal: target.isFinal,
+ };
+
+ yield* emit(
+ {
+ id: resolved.task.id,
+ ticketId: resolved.ticketId,
+ from: { slug: from.slug, name: from.name },
+ to: { slug: to.slug, name: to.name },
+ url: resolved.url,
+ },
+ (ui) => renderStatusChange(ui, { label, url: resolved.url, from, to }),
+ );
+ },
+);
+
+export const taskStatus = Command.make(
+ "status",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or the task id"),
+ ),
+ status: Argument.String("status").pipe(
+ Argument.withDescription(
+ "Column slug or name, for example in-progress or Done",
+ ),
+ Argument.optional,
+ ),
+ },
+ (options) => runTaskStatus(options),
+).pipe(
+ Command.withDescription("Move a task to another column of its project"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/task/view.ts b/packages/cli/src/commands/task/view.ts
new file mode 100644
index 000000000..040c47d7b
--- /dev/null
+++ b/packages/cli/src/commands/task/view.ts
@@ -0,0 +1,123 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { InvalidArgument } from "../../errors/errors.js";
+import { extractImages } from "../../images/extract-images.js";
+import { renderImages } from "../../images/render-images.js";
+import { emit } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import { Session } from "../../services/session.js";
+import { loadTaskView } from "../../task-view/load-task-view.js";
+import { renderTaskSections } from "../../task-view/render-task-sections.js";
+import { sectionValue } from "../../task-view/section-result.js";
+import { toTaskViewJson } from "../../task-view/task-view-json.js";
+import { renderTaskDetail } from "../../tasks/render-task-detail.js";
+import { ApiLayer } from "../api-layer.js";
+
+const DEFAULT_COMMENTS = 3;
+const DEFAULT_IMAGES = 3;
+
+const checkCount = (value: Option.Option<number>, flag: string) =>
+ Option.isSome(value) && value.value < 0
+ ? Effect.fail(
+ new InvalidArgument({
+ message: `${flag} must be 0 or more.`,
+ hint: `For example: ${flag} 5, or ${flag} 0 to skip.`,
+ }),
+ )
+ : Effect.void;
+
+export const runTaskView = Effect.fn("command.task.view")(function* (options: {
+ readonly task: string;
+ readonly comments: Option.Option<number>;
+ readonly images: Option.Option<number>;
+ readonly noImages: boolean;
+ readonly full: boolean;
+}) {
+ yield* checkCount(options.comments, "--comments");
+ yield* checkCount(options.images, "--images");
+ const session = yield* Session;
+ const output = yield* Output;
+ const all = Number.POSITIVE_INFINITY;
+ const commentLimit = Option.getOrElse(options.comments, () =>
+ options.full ? all : DEFAULT_COMMENTS,
+ );
+ const imageLimit = options.noImages
+ ? 0
+ : Option.getOrElse(options.images, () =>
+ options.full ? all : DEFAULT_IMAGES,
+ );
+
+ const loaded = yield* withSpinner(`Loading ${options.task.trim()}`)(
+ loadTaskView(options.task, { comments: commentLimit > 0 }),
+ );
+ const now = new Date();
+ const json = toTaskViewJson({
+ ...loaded,
+ webUrl: session.webUrl,
+ commentLimit,
+ now,
+ });
+ const statusFinal =
+ loaded.resolved.columns.find((column) => column.slug === json.status)
+ ?.isFinal ?? false;
+
+ yield* emit(json, (ui, task) =>
+ renderTaskDetail(ui, { task, statusFinal, now, full: options.full }),
+ );
+ if (output.mode !== "human") return;
+
+ const images = imageLimit > 0 ? extractImages(json.description ?? "") : [];
+ if (images.length > 0) {
+ yield* renderImages(images, {
+ max: imageLimit,
+ indent: 4,
+ whenUnsupported: "skip",
+ whenFailed: "skip",
+ });
+ }
+ const sections = renderTaskSections(output.ui, {
+ task: json,
+ commentTotal: sectionValue(loaded.sections.comments)?.length ?? 0,
+ now,
+ full: options.full,
+ });
+ if (sections.length > 0) yield* output.out(`${sections.join("\n")}\n`);
+});
+
+export const taskView = Command.make(
+ "view",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or a task id"),
+ ),
+ comments: Flag.Int("comments").pipe(
+ Flag.withDescription(
+ `Show the latest N comments (default ${DEFAULT_COMMENTS}, 0 to skip them)`,
+ ),
+ Flag.optional,
+ ),
+ images: Flag.Int("images").pipe(
+ Flag.withDescription(
+ `Show up to N images from the description inline (default ${DEFAULT_IMAGES})`,
+ ),
+ Flag.optional,
+ ),
+ noImages: Flag.Boolean("no-images").pipe(
+ Flag.withDescription("Do not show images from the description"),
+ Flag.withDefault(false),
+ ),
+ full: Flag.Boolean("full").pipe(
+ Flag.withDescription(
+ "Show the whole description, every comment in full and every image",
+ ),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runTaskView(options),
+).pipe(
+ Command.withDescription(
+ "Show a task with its details, description, subtasks, links, fields and recent comments",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/time/edit.ts b/packages/cli/src/commands/time/edit.ts
new file mode 100644
index 000000000..f9b0e3ad5
--- /dev/null
+++ b/packages/cli/src/commands/time/edit.ts
@@ -0,0 +1,106 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { getCurrentUser } from "../../api/endpoints.js";
+import { getTimeEntry, updateTimeEntry } from "../../api/time-entries.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { resolveTask } from "../../tasks/resolve-task.js";
+import { formatDuration, parseDuration } from "../../time/duration.js";
+import { entrySeconds } from "../../time/entry-seconds.js";
+import { taskRef } from "../../time/find-running-timer.js";
+import { renderTimerChange } from "../../time/render-timer-change.js";
+import { toTimeEntryJson } from "../../time/time-entry-json.js";
+import { ApiLayer } from "../api-layer.js";
+import { noteFlag } from "./note-flag.js";
+
+export const runTimeEdit = Effect.fn("command.time.edit")(function* (options: {
+ readonly entry: string;
+ readonly duration: Option.Option<string>;
+ readonly note: Option.Option<string>;
+}) {
+ if (Option.isNone(options.duration) && Option.isNone(options.note)) {
+ return yield* new InvalidArgument({
+ message: "Nothing to change.",
+ hint: "Pass --duration, -m, or both.",
+ });
+ }
+ const seconds = Option.isSome(options.duration)
+ ? yield* Effect.fromResult(
+ parseDuration(options.duration.value, "--duration"),
+ )
+ : undefined;
+ const id = options.entry.trim();
+ const entry = yield* withSpinner("Loading the entry")(getTimeEntry(id));
+ if (seconds !== undefined && entry.endTime === null) {
+ return yield* new InvalidArgument({
+ message: "This entry is still running.",
+ hint: "Stop it with kaneo time stop, then set its duration.",
+ });
+ }
+ const description = Option.getOrUndefined(options.note)?.trim();
+
+ const { updated, resolved, user } = yield* withSpinner("Updating the entry")(
+ Effect.all(
+ {
+ updated: updateTimeEntry(entry.id, {
+ startTime: entry.startTime,
+ ...(seconds === undefined
+ ? {}
+ : {
+ endTime: new Date(
+ Date.parse(entry.startTime) + seconds * 1000,
+ ).toISOString(),
+ }),
+ ...(description === undefined ? {} : { description }),
+ }),
+ resolved: resolveTask(entry.taskId),
+ user: getCurrentUser(),
+ },
+ { concurrency: 3 },
+ ),
+ );
+ const task = taskRef(resolved);
+ const now = new Date();
+ const json = toTimeEntryJson(
+ updated,
+ task.ticketId,
+ now,
+ updated.userId === user.id ? user.name : null,
+ );
+
+ yield* emit({ ...json, taskTitle: task.title, url: task.url }, (ui) =>
+ renderTimerChange(ui, {
+ verb: "Updated",
+ label: task.ticketId ?? task.id.slice(0, 8),
+ url: task.url,
+ details: [
+ updated.endTime === null
+ ? "still running"
+ : formatDuration(entrySeconds(updated, now)),
+ json.note ?? "",
+ ],
+ }),
+ );
+});
+
+export const timeEdit = Command.make(
+ "edit",
+ {
+ entry: Argument.String("entry-id").pipe(
+ Argument.withDescription("Time entry id, from kaneo time list"),
+ ),
+ duration: Flag.String("duration").pipe(
+ Flag.withAlias("d"),
+ Flag.withDescription(
+ "New length, for example 1h30m; keeps the start time",
+ ),
+ Flag.optional,
+ ),
+ note: noteFlag,
+ },
+ (options) => runTimeEdit(options),
+).pipe(
+ Command.withDescription("Change the length or note of a time entry"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/time/index.ts b/packages/cli/src/commands/time/index.ts
new file mode 100644
index 000000000..65a504000
--- /dev/null
+++ b/packages/cli/src/commands/time/index.ts
@@ -0,0 +1,19 @@
+import { Command } from "effect/cli";
+import { timeEdit } from "./edit.js";
+import { timeList } from "./list.js";
+import { timeLog } from "./log.js";
+import { timeStart } from "./start.js";
+import { timeStatus } from "./status.js";
+import { timeStop } from "./stop.js";
+
+export const time = Command.make("time").pipe(
+ Command.withDescription("Track time on tasks"),
+ Command.withSubcommands([
+ timeStart,
+ timeStop,
+ timeStatus,
+ timeLog,
+ timeList,
+ timeEdit,
+ ]),
+);
diff --git a/packages/cli/src/commands/time/list.ts b/packages/cli/src/commands/time/list.ts
new file mode 100644
index 000000000..e5e12ab11
--- /dev/null
+++ b/packages/cli/src/commands/time/list.ts
@@ -0,0 +1,53 @@
+import { Effect, Option } from "effect";
+import { Argument, Command } from "effect/cli";
+import { listTimeEntries } from "../../api/time-entries.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { resolveTask } from "../../tasks/resolve-task.js";
+import { askTask } from "../../time/ask-task.js";
+import { renderTimeEntries } from "../../time/render-time-entries.js";
+import { toTimeEntryJson } from "../../time/time-entry-json.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runTimeList = Effect.fn("command.time.list")(function* (options: {
+ readonly task: Option.Option<string>;
+}) {
+ const reference = yield* askTask(options.task, "kaneo time list KAN-12");
+ const { resolved, entries } = yield* withSpinner(
+ `Loading time on ${reference}`,
+ )(
+ Effect.gen(function* () {
+ const resolved = yield* resolveTask(reference);
+ const entries = yield* listTimeEntries(resolved.task.id);
+ return { resolved, entries };
+ }),
+ );
+ const now = new Date();
+ const json = entries.map((entry) =>
+ toTimeEntryJson(entry, resolved.ticketId, now),
+ );
+
+ yield* emit(json, (ui) =>
+ renderTimeEntries(ui, {
+ label: resolved.ticketId ?? resolved.task.id.slice(0, 8),
+ url: resolved.url,
+ title: resolved.task.title,
+ entries: json,
+ now,
+ }),
+ );
+});
+
+export const timeList = Command.make(
+ "list",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or the task id"),
+ Argument.optional,
+ ),
+ },
+ (options) => runTimeList(options),
+).pipe(
+ Command.withDescription("List the time logged on a task, with a total"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/time/log.ts b/packages/cli/src/commands/time/log.ts
new file mode 100644
index 000000000..d828fd5eb
--- /dev/null
+++ b/packages/cli/src/commands/time/log.ts
@@ -0,0 +1,91 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { getCurrentUser } from "../../api/endpoints.js";
+import { createTimeEntry } from "../../api/time-entries.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { formatDue } from "../../render/task-format.js";
+import { resolveTask } from "../../tasks/resolve-task.js";
+import { askDuration } from "../../time/ask-duration.js";
+import { askTask } from "../../time/ask-task.js";
+import { formatDuration } from "../../time/duration.js";
+import { taskRef } from "../../time/find-running-timer.js";
+import { logRange } from "../../time/log-range.js";
+import { renderTimerChange } from "../../time/render-timer-change.js";
+import { toTimeEntryJson } from "../../time/time-entry-json.js";
+import { ApiLayer } from "../api-layer.js";
+import { noteFlag } from "./note-flag.js";
+
+export const runTimeLog = Effect.fn("command.time.log")(function* (options: {
+ readonly task: Option.Option<string>;
+ readonly duration: Option.Option<string>;
+ readonly date: string;
+ readonly note: Option.Option<string>;
+}) {
+ const reference = yield* askTask(options.task, "kaneo time log KAN-12 1h30m");
+ const seconds = yield* askDuration(
+ options.duration,
+ `kaneo time log ${reference} 1h30m`,
+ );
+ const now = new Date();
+ const range = yield* Effect.fromResult(logRange(seconds, options.date, now));
+ const [user, resolved] = yield* withSpinner(`Loading ${reference}`)(
+ Effect.all([getCurrentUser(), resolveTask(reference)], { concurrency: 2 }),
+ );
+ const task = taskRef(resolved);
+ const label = task.ticketId ?? task.id.slice(0, 8);
+ const description = Option.getOrUndefined(options.note)?.trim();
+
+ const entry = yield* withSpinner(`Logging time on ${label}`)(
+ createTimeEntry({
+ taskId: task.id,
+ startTime: range.startTime,
+ endTime: range.endTime,
+ ...(description ? { description } : {}),
+ }),
+ );
+
+ yield* emit(
+ {
+ ...toTimeEntryJson(entry, task.ticketId, now, user.name),
+ taskTitle: task.title,
+ url: task.url,
+ },
+ (ui) =>
+ renderTimerChange(ui, {
+ verb: "Logged",
+ label,
+ url: task.url,
+ details: [
+ formatDuration(seconds),
+ formatDue(new Date(range.startTime), now),
+ description ?? "",
+ ],
+ }),
+ );
+});
+
+export const timeLog = Command.make(
+ "log",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or the task id"),
+ Argument.optional,
+ ),
+ duration: Argument.String("duration").pipe(
+ Argument.withDescription("How long, for example 1h30m, 45m, 2h or 1.5h"),
+ Argument.optional,
+ ),
+ date: Flag.String("date").pipe(
+ Flag.withDescription(
+ "Day the work happened: today, yesterday, or YYYY-MM-DD",
+ ),
+ Flag.withDefault("today"),
+ ),
+ note: noteFlag,
+ },
+ (options) => runTimeLog(options),
+).pipe(
+ Command.withDescription("Log time you already spent on a task"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/time/note-flag.ts b/packages/cli/src/commands/time/note-flag.ts
new file mode 100644
index 000000000..1dd47b4b2
--- /dev/null
+++ b/packages/cli/src/commands/time/note-flag.ts
@@ -0,0 +1,7 @@
+import { Flag } from "effect/cli";
+
+export const noteFlag = Flag.String("note").pipe(
+ Flag.withAlias("m"),
+ Flag.withDescription("A short note about the work"),
+ Flag.optional,
+);
diff --git a/packages/cli/src/commands/time/start.ts b/packages/cli/src/commands/time/start.ts
new file mode 100644
index 000000000..a98080d49
--- /dev/null
+++ b/packages/cli/src/commands/time/start.ts
@@ -0,0 +1,114 @@
+import { Effect, Option } from "effect";
+import { Argument, Command } from "effect/cli";
+import { getCurrentUser } from "../../api/endpoints.js";
+import { createTimeEntry } from "../../api/time-entries.js";
+import { Cancelled, InvalidArgument } from "../../errors/errors.js";
+import { emit, note } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import { confirm } from "../../prompts/confirm.js";
+import { resolveTask } from "../../tasks/resolve-task.js";
+import { askTask } from "../../time/ask-task.js";
+import { formatDuration } from "../../time/duration.js";
+import { entrySeconds } from "../../time/entry-seconds.js";
+import { findRunningTimer, taskRef } from "../../time/find-running-timer.js";
+import { renderTimerChange } from "../../time/render-timer-change.js";
+import { stopTimer } from "../../time/stop-timer.js";
+import { toTimeEntryJson } from "../../time/time-entry-json.js";
+import { rememberTimer } from "../../time/timer-pointer-store.js";
+import { ApiLayer } from "../api-layer.js";
+import { noteFlag } from "./note-flag.js";
+
+export const runTimeStart = Effect.fn("command.time.start")(
+ function* (options: {
+ readonly task: Option.Option<string>;
+ readonly note: Option.Option<string>;
+ }) {
+ const output = yield* Output;
+ const reference = yield* askTask(options.task, "kaneo time start KAN-12");
+ const [user, resolved] = yield* withSpinner(`Loading ${reference}`)(
+ Effect.all([getCurrentUser(), resolveTask(reference)], {
+ concurrency: 2,
+ }),
+ );
+ const task = taskRef(resolved);
+ const label = task.ticketId ?? task.id.slice(0, 8);
+
+ const running = yield* withSpinner("Checking for a running timer")(
+ findRunningTimer(user.id),
+ );
+ if (Option.isSome(running)) {
+ const timer = running.value;
+ const runningLabel = timer.task.ticketId ?? timer.task.id.slice(0, 8);
+ const elapsed = formatDuration(entrySeconds(timer.entry, new Date()));
+ const message = `A timer is already running on ${runningLabel} (${elapsed}).`;
+ if (timer.task.id === task.id) {
+ return yield* new InvalidArgument({
+ message,
+ hint: "Stop it with kaneo time stop.",
+ });
+ }
+ if (!output.interactive) {
+ return yield* new InvalidArgument({
+ message,
+ hint: `Stop it first with kaneo time stop, then start ${label}.`,
+ });
+ }
+ const switching = yield* confirm(
+ `${runningLabel} · ${timer.task.title} has a timer running (${elapsed}). Stop it and start ${label}?`,
+ );
+ if (!switching) return yield* new Cancelled();
+ const stopped = yield* withSpinner(`Stopping ${runningLabel}`)(
+ stopTimer(timer, new Date()),
+ );
+ yield* note((ui) =>
+ renderTimerChange(ui, {
+ verb: "Stopped",
+ label: runningLabel,
+ url: timer.task.url,
+ details: [formatDuration(entrySeconds(stopped, new Date()))],
+ }).slice(0, -1),
+ );
+ }
+
+ const description = Option.getOrUndefined(options.note)?.trim();
+ const entry = yield* withSpinner(`Starting a timer on ${label}`)(
+ createTimeEntry({
+ taskId: task.id,
+ startTime: new Date().toISOString(),
+ ...(description ? { description } : {}),
+ }),
+ );
+ yield* rememberTimer({ entryId: entry.id, taskId: entry.taskId });
+
+ yield* emit(
+ {
+ ...toTimeEntryJson(entry, task.ticketId, new Date(), user.name),
+ taskTitle: task.title,
+ url: task.url,
+ },
+ (ui) =>
+ renderTimerChange(ui, {
+ verb: "Started",
+ label,
+ url: task.url,
+ details: [task.title],
+ }),
+ );
+ },
+);
+
+export const timeStart = Command.make(
+ "start",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription("Ticket id such as KAN-12, or the task id"),
+ Argument.optional,
+ ),
+ note: noteFlag,
+ },
+ (options) => runTimeStart(options),
+).pipe(
+ Command.withDescription("Start a timer on a task"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/time/status.ts b/packages/cli/src/commands/time/status.ts
new file mode 100644
index 000000000..fcb49b99c
--- /dev/null
+++ b/packages/cli/src/commands/time/status.ts
@@ -0,0 +1,54 @@
+import { Effect, Option } from "effect";
+import { Command } from "effect/cli";
+import { getCurrentUser } from "../../api/endpoints.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { entrySeconds } from "../../time/entry-seconds.js";
+import { findRunningTimer } from "../../time/find-running-timer.js";
+import { renderTimerStatus } from "../../time/render-timer-status.js";
+import { toTimeEntryJson } from "../../time/time-entry-json.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runTimeStatus = Effect.fn("command.time.status")(function* () {
+ const running = yield* withSpinner("Checking for a running timer")(
+ Effect.gen(function* () {
+ const user = yield* getCurrentUser();
+ const timer = yield* findRunningTimer(user.id);
+ return Option.map(timer, (value) => ({ ...value, user }));
+ }),
+ );
+ const now = new Date();
+
+ yield* emit(
+ Option.match(running, {
+ onNone: () => null,
+ onSome: ({ entry, task, user }) => ({
+ ...toTimeEntryJson(entry, task.ticketId, now, user.name),
+ taskTitle: task.title,
+ url: task.url,
+ }),
+ }),
+ (ui) =>
+ renderTimerStatus(
+ ui,
+ Option.match(running, {
+ onNone: () => null,
+ onSome: ({ entry, task }) => ({
+ label: task.ticketId ?? task.id.slice(0, 8),
+ url: task.url,
+ title: task.title,
+ startedAt: entry.startTime,
+ elapsedSeconds: entrySeconds(entry, now),
+ note: entry.description?.trim() ? entry.description : null,
+ }),
+ }),
+ ),
+ );
+});
+
+export const timeStatus = Command.make("status", {}, () =>
+ runTimeStatus(),
+).pipe(
+ Command.withDescription("Show your running timer"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/time/stop.ts b/packages/cli/src/commands/time/stop.ts
new file mode 100644
index 000000000..2509d58fc
--- /dev/null
+++ b/packages/cli/src/commands/time/stop.ts
@@ -0,0 +1,79 @@
+import { Effect, Option } from "effect";
+import { Argument, Command } from "effect/cli";
+import { getCurrentUser } from "../../api/endpoints.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { resolveTask } from "../../tasks/resolve-task.js";
+import { formatDuration } from "../../time/duration.js";
+import { entrySeconds } from "../../time/entry-seconds.js";
+import {
+ findRunningTimer,
+ findTaskTimer,
+} from "../../time/find-running-timer.js";
+import { renderTimerChange } from "../../time/render-timer-change.js";
+import { stopTimer } from "../../time/stop-timer.js";
+import { toTimeEntryJson } from "../../time/time-entry-json.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runTimeStop = Effect.fn("command.time.stop")(function* (options: {
+ readonly task: Option.Option<string>;
+}) {
+ const user = yield* withSpinner("Checking your account")(getCurrentUser());
+ const running = yield* withSpinner("Finding the running timer")(
+ Option.match(options.task, {
+ onNone: () => findRunningTimer(user.id),
+ onSome: (reference) =>
+ resolveTask(reference).pipe(
+ Effect.flatMap((resolved) => findTaskTimer(resolved, user.id)),
+ ),
+ }),
+ );
+ if (Option.isNone(running)) {
+ return yield* new InvalidArgument({
+ message: Option.isSome(options.task)
+ ? `No timer of yours is running on ${options.task.value}.`
+ : "No timer is running.",
+ hint: Option.isSome(options.task)
+ ? "Run kaneo time list to see its entries."
+ : "If you started one elsewhere on a task not assigned to you, pass the task: kaneo time stop KAN-12.",
+ });
+ }
+ const timer = running.value;
+ const label = timer.task.ticketId ?? timer.task.id.slice(0, 8);
+ const now = new Date();
+ const stopped = yield* withSpinner(`Stopping ${label}`)(
+ stopTimer(timer, now),
+ );
+
+ yield* emit(
+ {
+ ...toTimeEntryJson(stopped, timer.task.ticketId, now, user.name),
+ taskTitle: timer.task.title,
+ url: timer.task.url,
+ },
+ (ui) =>
+ renderTimerChange(ui, {
+ verb: "Stopped",
+ label,
+ url: timer.task.url,
+ details: [formatDuration(entrySeconds(stopped, now))],
+ }),
+ );
+});
+
+export const timeStop = Command.make(
+ "stop",
+ {
+ task: Argument.String("task").pipe(
+ Argument.withDescription(
+ "Only look on this task (ticket id such as KAN-12, or the task id)",
+ ),
+ Argument.optional,
+ ),
+ },
+ (options) => runTimeStop(options),
+).pipe(
+ Command.withDescription("Stop your running timer"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/unlink.ts b/packages/cli/src/commands/unlink.ts
new file mode 100644
index 000000000..25e41ba57
--- /dev/null
+++ b/packages/cli/src/commands/unlink.ts
@@ -0,0 +1,89 @@
+import { basename, dirname } from "node:path";
+import { Effect } from "effect";
+import { Command, Flag } from "effect/cli";
+import {
+ deleteRepoConfig,
+ hasRepoLink,
+ readRepoConfigObject,
+ removeRepoLink,
+ writeRepoConfig,
+} from "../config/repo-config.js";
+import { Cancelled } from "../errors/errors.js";
+import { emit } from "../output/emit.js";
+import { Output } from "../output/output.js";
+import { confirm } from "../prompts/confirm.js";
+import type { Ui } from "../render/ui.js";
+import { Session } from "../services/session.js";
+import { ApiLayer } from "./api-layer.js";
+
+type UnlinkResult = {
+ readonly path: string | null;
+ readonly unlinked: boolean;
+ readonly deleted: boolean;
+};
+
+export function renderUnlink(ui: Ui, result: UnlinkResult): string[] {
+ const { theme, glyphs } = ui;
+ if (!result.path || !result.unlinked) {
+ return [
+ ` ${theme.muted(glyphs.dot)} This directory is not linked to Kaneo`,
+ ];
+ }
+ const detail = result.deleted
+ ? `removed ${basename(result.path)}`
+ : `kept the other keys in ${basename(result.path)}`;
+ return [
+ ` ${theme.success(glyphs.tick)} Unlinked ${dirname(result.path)} ${theme.muted(`${glyphs.separator} ${detail}`)}`,
+ ];
+}
+
+export const runUnlink = Effect.fn("command.unlink")(function* (options: {
+ readonly yes: boolean;
+}) {
+ const session = yield* Session;
+ const output = yield* Output;
+ const path = session.repo?.path;
+ const existing = path ? yield* readRepoConfigObject(path) : undefined;
+
+ if (!path || !existing || !hasRepoLink(existing)) {
+ yield* emit<UnlinkResult>(
+ { path: path ?? null, unlinked: false, deleted: false },
+ renderUnlink,
+ );
+ return;
+ }
+
+ if (!options.yes && output.interactive) {
+ const confirmed = yield* confirm(
+ `Remove the Kaneo workspace and project from ${path}?`,
+ );
+ if (!confirmed) return yield* new Cancelled();
+ }
+
+ const remaining = removeRepoLink(existing);
+ if (remaining) {
+ yield* writeRepoConfig(path, remaining);
+ } else {
+ yield* deleteRepoConfig(path);
+ }
+
+ yield* emit<UnlinkResult>(
+ { path, unlinked: true, deleted: remaining === undefined },
+ renderUnlink,
+ );
+});
+
+export const unlinkCommand = Command.make(
+ "unlink",
+ {
+ yes: Flag.Boolean("yes").pipe(
+ Flag.withAlias("y"),
+ Flag.withDescription("Unlink without asking for confirmation"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runUnlink(options),
+).pipe(
+ Command.withDescription("Remove this repository's .kaneo.json settings"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/whoami.ts b/packages/cli/src/commands/whoami.ts
new file mode 100644
index 000000000..76ed8347e
--- /dev/null
+++ b/packages/cli/src/commands/whoami.ts
@@ -0,0 +1,98 @@
+import { Effect, Option } from "effect";
+import { Command } from "effect/cli";
+import { getCurrentUser, getWorkspace } from "../api/endpoints.js";
+import type { CurrentUser, Workspace } from "../api/schemas.js";
+import { type Avatar, loadAvatar } from "../images/avatar.js";
+import { placeAvatar } from "../images/avatar-layout.js";
+import { emit } from "../output/emit.js";
+import { withSpinner } from "../output/spinner.js";
+import type { Ui } from "../render/ui.js";
+import { type SessionShape, Session } from "../services/session.js";
+import { ApiLayer } from "./api-layer.js";
+
+type WhoamiResult = {
+ readonly user: CurrentUser;
+ readonly apiUrl: string;
+ readonly profile: string;
+ readonly auth: "token" | "api-key" | "login";
+ readonly workspace: Workspace | null;
+};
+
+function authLabel(session: SessionShape): WhoamiResult["auth"] {
+ const source = Option.getOrUndefined(session.credentials)?.source;
+ if (source === "flag") return "token";
+ if (source === "env") return "api-key";
+ return "login";
+}
+
+function host(url: string): string {
+ return new URL(url).host;
+}
+
+export function renderWhoami(
+ ui: Ui,
+ result: WhoamiResult,
+ avatar: Avatar | null = null,
+): string[] {
+ const { theme, glyphs } = ui;
+ const auth =
+ result.auth === "api-key"
+ ? "KANEO_API_KEY"
+ : result.auth === "token"
+ ? "--token"
+ : `login (${result.profile})`;
+ const rows: Array<[string, string]> = [
+ ["Server", host(result.apiUrl)],
+ ["Auth", auth],
+ [
+ "Workspace",
+ result.workspace
+ ? `${result.workspace.name} ${theme.muted(result.workspace.id)}`
+ : theme.muted("none selected"),
+ ],
+ ];
+ if (result.user.role?.split(",").includes("admin")) {
+ rows.push(["Role", "Instance admin"]);
+ }
+ const lines = [
+ "",
+ ` ${theme.success(glyphs.tick)} ${theme.strong(result.user.name)} ${theme.muted(glyphs.separator)} ${result.user.email}`,
+ "",
+ ...rows.map(
+ ([label, value]) => ` ${theme.muted(label.padEnd(10))} ${value}`,
+ ),
+ "",
+ ];
+ return placeAvatar(lines, avatar, ui.caps.columns);
+}
+
+export const runWhoami = Effect.fn("command.whoami")(function* () {
+ const session = yield* Session;
+ const user = yield* withSpinner("Checking your account")(getCurrentUser());
+ const [workspace, avatar] = yield* Effect.all(
+ [
+ Option.isSome(session.workspace)
+ ? getWorkspace(session.workspace.value.id).pipe(
+ Effect.catchTag("NotFound", () => Effect.succeed(null)),
+ )
+ : Effect.succeed(null),
+ loadAvatar(user.image),
+ ],
+ { concurrency: 2 },
+ );
+ yield* emit<WhoamiResult>(
+ {
+ user,
+ apiUrl: session.apiUrl,
+ profile: session.profileName,
+ auth: authLabel(session),
+ workspace,
+ },
+ (ui, result) => renderWhoami(ui, result, avatar),
+ );
+});
+
+export const whoami = Command.make("whoami", {}, () => runWhoami()).pipe(
+ Command.withDescription("Show the account and server you are using"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/workflow/delete.ts b/packages/cli/src/commands/workflow/delete.ts
new file mode 100644
index 000000000..7ac181aae
--- /dev/null
+++ b/packages/cli/src/commands/workflow/delete.ts
@@ -0,0 +1,146 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import {
+ deleteWorkflowRule,
+ listWorkflowRules,
+} from "../../api/workflow-rules.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import { confirmDestructive } from "../../prompts/confirm-destructive.js";
+import { pick } from "../../prompts/pick.js";
+import {
+ resolveProject,
+ resolveWorkspaceId,
+} from "../../services/selection.js";
+import {
+ eventLabel,
+ integrationLabel,
+ parseIntegration,
+ parseWorkflowEvent,
+} from "../../workflow/events.js";
+import { matchRule } from "../../workflow/match-rule.js";
+import { renderRuleChange } from "../../workflow/render-rules.js";
+import { type RuleJson, toRuleJson } from "../../workflow/rule-json.js";
+import { sortRules } from "../../workflow/sort-rules.js";
+import { ApiLayer } from "../api-layer.js";
+
+function ruleName(rule: RuleJson): string {
+ return `${integrationLabel(rule.integration)} ${eventLabel(rule.event).toLowerCase()}`;
+}
+
+const findRule = Effect.fnUntraced(function* (
+ rules: ReadonlyArray<RuleJson>,
+ first: Option.Option<string>,
+ second: Option.Option<string>,
+ projectName: string,
+) {
+ const output = yield* Output;
+ if (Option.isNone(first)) {
+ if (output.interactive && rules.length > 0) {
+ return yield* pick(
+ "Delete which rule?",
+ rules.map((rule) => ({
+ title: ruleName(rule),
+ value: rule,
+ description: rule.column.name ?? rule.column.id,
+ })),
+ );
+ }
+ return yield* new InvalidArgument({
+ message:
+ rules.length === 0
+ ? `${projectName} has no workflow rules.`
+ : "Which rule should be deleted?",
+ hint: "Pass the integration and the event, for example kaneo workflow delete github pr_merged, or a rule id.",
+ });
+ }
+ const target = Option.isSome(second)
+ ? {
+ integration: yield* Effect.fromResult(parseIntegration(first.value)),
+ event: yield* Effect.fromResult(parseWorkflowEvent(second.value)),
+ }
+ : rules.some((rule) => rule.id === first.value.trim())
+ ? { id: first.value.trim() }
+ : { event: yield* Effect.fromResult(parseWorkflowEvent(first.value)) };
+ const match = matchRule(rules, target);
+ if (match.kind === "found") return match.rule;
+ if (match.kind === "ambiguous") {
+ return yield* new InvalidArgument({
+ message: `${eventLabel(match.rules[0]?.event ?? "")} has rules for ${match.rules.map((rule) => integrationLabel(rule.integration)).join(" and ")}.`,
+ hint: `Name the integration too, for example kaneo workflow delete ${match.rules[0]?.integration ?? "github"} ${match.rules[0]?.event ?? ""}.`,
+ });
+ }
+ const wanted = [first.value, ...Option.toArray(second)].join(" ").trim();
+ return yield* new InvalidArgument({
+ message: `No workflow rule matches "${wanted}" in ${projectName}.`,
+ hint: "Run kaneo workflow list to see the rules.",
+ });
+});
+
+export const runWorkflowDelete = Effect.fn("command.workflow.delete")(
+ function* (options: {
+ readonly rule: Option.Option<string>;
+ readonly event: Option.Option<string>;
+ readonly project: Option.Option<string>;
+ readonly yes: boolean;
+ }) {
+ const workspaceId = yield* resolveWorkspaceId();
+ const project = yield* resolveProject(workspaceId, options.project);
+ const rules = sortRules(
+ (yield* withSpinner("Loading workflow rules")(
+ listWorkflowRules(project.id),
+ )).map(toRuleJson),
+ );
+ const rule = yield* findRule(
+ rules,
+ options.rule,
+ options.event,
+ project.name,
+ );
+
+ yield* confirmDestructive({
+ yes: options.yes,
+ action: `Deleting the rule ${ruleName(rule)}`,
+ question: `Delete the rule ${ruleName(rule)} in ${project.name}? Tasks then move to the integration's default column.`,
+ });
+
+ yield* withSpinner("Deleting the rule")(deleteWorkflowRule(rule.id));
+ yield* emit({ ...rule, deleted: true }, (ui) =>
+ renderRuleChange(ui, { verb: "Deleted", rule }),
+ );
+ },
+);
+
+export const workflowDelete = Command.make(
+ "delete",
+ {
+ rule: Argument.String("rule").pipe(
+ Argument.withDescription(
+ "Integration (github, gitlab, gitea) followed by the event, an event alone, or a rule id",
+ ),
+ Argument.optional,
+ ),
+ event: Argument.String("event").pipe(
+ Argument.withDescription(
+ "Event, when the first argument is the integration",
+ ),
+ Argument.optional,
+ ),
+ project: Flag.String("project").pipe(
+ Flag.withAlias("p"),
+ Flag.withDescription("Project key or id, for example KAN"),
+ Flag.optional,
+ ),
+ yes: Flag.Boolean("yes").pipe(
+ Flag.withAlias("y"),
+ Flag.withDescription("Delete without asking for confirmation"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runWorkflowDelete(options),
+).pipe(
+ Command.withDescription("Delete a workflow rule"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/workflow/index.ts b/packages/cli/src/commands/workflow/index.ts
new file mode 100644
index 000000000..10d2d9699
--- /dev/null
+++ b/packages/cli/src/commands/workflow/index.ts
@@ -0,0 +1,11 @@
+import { Command } from "effect/cli";
+import { workflowDelete } from "./delete.js";
+import { workflowList } from "./list.js";
+import { workflowSet } from "./set.js";
+
+export const workflow = Command.make("workflow").pipe(
+ Command.withDescription(
+ "Move tasks to a column when GitHub, GitLab or Gitea events arrive",
+ ),
+ Command.withSubcommands([workflowList, workflowSet, workflowDelete]),
+);
diff --git a/packages/cli/src/commands/workflow/list.ts b/packages/cli/src/commands/workflow/list.ts
new file mode 100644
index 000000000..c4eb117f3
--- /dev/null
+++ b/packages/cli/src/commands/workflow/list.ts
@@ -0,0 +1,43 @@
+import { Effect, Option } from "effect";
+import { Command, Flag } from "effect/cli";
+import { listWorkflowRules } from "../../api/workflow-rules.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import {
+ resolveProject,
+ resolveWorkspaceId,
+} from "../../services/selection.js";
+import { sortRules } from "../../workflow/sort-rules.js";
+import { renderRuleList } from "../../workflow/render-rules.js";
+import { toRuleJson } from "../../workflow/rule-json.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runWorkflowList = Effect.fn("command.workflow.list")(
+ function* (options: { readonly project: Option.Option<string> }) {
+ const workspaceId = yield* resolveWorkspaceId();
+ const project = yield* resolveProject(workspaceId, options.project);
+ const rules = yield* withSpinner("Loading workflow rules")(
+ listWorkflowRules(project.id),
+ );
+ yield* emit(sortRules(rules.map(toRuleJson)), (ui, value) =>
+ renderRuleList(ui, { projectName: project.name, rules: value }),
+ );
+ },
+);
+
+export const workflowList = Command.make(
+ "list",
+ {
+ project: Flag.String("project").pipe(
+ Flag.withAlias("p"),
+ Flag.withDescription("Project key or id, for example KAN"),
+ Flag.optional,
+ ),
+ },
+ (options) => runWorkflowList(options),
+).pipe(
+ Command.withDescription(
+ "List the rules that move tasks when GitHub, GitLab or Gitea events arrive",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/workflow/set.ts b/packages/cli/src/commands/workflow/set.ts
new file mode 100644
index 000000000..a2353c385
--- /dev/null
+++ b/packages/cli/src/commands/workflow/set.ts
@@ -0,0 +1,144 @@
+import { Effect, Option, Result } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { listColumns } from "../../api/endpoints.js";
+import { upsertWorkflowRule } from "../../api/workflow-rules.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import { type Choice, pick } from "../../prompts/pick.js";
+import {
+ resolveProject,
+ resolveWorkspaceId,
+} from "../../services/selection.js";
+import { matchColumn } from "../../tasks/match-column.js";
+import {
+ EVENT_LABELS,
+ EVENTS,
+ INTEGRATION_LABELS,
+ INTEGRATIONS,
+ parseIntegration,
+ parseWorkflowEvent,
+} from "../../workflow/events.js";
+import { renderRuleChange } from "../../workflow/render-rules.js";
+import type { RuleJson } from "../../workflow/rule-json.js";
+import { ApiLayer } from "../api-layer.js";
+
+const USAGE = "kaneo workflow set github pr_merged done";
+
+const choose = Effect.fnUntraced(function* <A>(
+ input: Option.Option<string>,
+ parse: (value: string) => Result.Result<A, InvalidArgument>,
+ question: string,
+ choices: ReadonlyArray<Choice<A>>,
+ missing: string,
+) {
+ const output = yield* Output;
+ if (Option.isSome(input)) return yield* Effect.fromResult(parse(input.value));
+ if (output.interactive) return yield* pick(question, choices);
+ return yield* new InvalidArgument({
+ message: missing,
+ hint: `Pass the integration, the event and the column, for example ${USAGE}.`,
+ });
+});
+
+export const runWorkflowSet = Effect.fn("command.workflow.set")(
+ function* (options: {
+ readonly integration: Option.Option<string>;
+ readonly event: Option.Option<string>;
+ readonly column: Option.Option<string>;
+ readonly project: Option.Option<string>;
+ }) {
+ const integration = yield* choose(
+ options.integration,
+ parseIntegration,
+ "Which integration?",
+ INTEGRATIONS.map((value) => ({
+ title: INTEGRATION_LABELS[value],
+ value,
+ })),
+ "Which integration does the rule listen to?",
+ );
+ const event = yield* choose(
+ options.event,
+ parseWorkflowEvent,
+ "When this happens",
+ EVENTS.map((value) => ({
+ title: EVENT_LABELS[value],
+ value,
+ description: value,
+ })),
+ "Which event should move tasks?",
+ );
+ const workspaceId = yield* resolveWorkspaceId();
+ const project = yield* resolveProject(workspaceId, options.project);
+ const columns = yield* withSpinner("Loading columns")(
+ listColumns(project.id),
+ );
+ const column = yield* choose(
+ options.column,
+ (reference) => {
+ const match = matchColumn(columns, reference);
+ return match
+ ? Result.succeed(match)
+ : Result.fail(
+ new InvalidArgument({
+ message: `No column matches "${reference}" in ${project.name}.`,
+ hint: `Columns: ${columns.map((entry) => entry.slug).join(", ")}.`,
+ }),
+ );
+ },
+ "Move the task to",
+ columns.map((entry) => ({ title: entry.name, value: entry })),
+ "Which column should tasks move to?",
+ );
+
+ const saved = yield* withSpinner("Saving the rule")(
+ upsertWorkflowRule(project.id, {
+ integrationType: integration,
+ eventType: event,
+ columnId: column.id,
+ }),
+ );
+ const rule: RuleJson = {
+ id: saved.id,
+ integration: saved.integrationType,
+ event: saved.eventType,
+ column: { id: column.id, name: column.name, slug: column.slug },
+ };
+ yield* emit(rule, (ui, value) =>
+ renderRuleChange(ui, { verb: "Set", rule: value }),
+ );
+ },
+);
+
+export const workflowSet = Command.make(
+ "set",
+ {
+ integration: Argument.String("integration").pipe(
+ Argument.withDescription("github, gitlab or gitea"),
+ Argument.optional,
+ ),
+ event: Argument.String("event").pipe(
+ Argument.withDescription(
+ "branch_push, pr_opened, pr_merged, issue_opened, issue_closed or issue_reopened",
+ ),
+ Argument.optional,
+ ),
+ column: Argument.String("column").pipe(
+ Argument.withDescription("Column slug or name, such as done"),
+ Argument.optional,
+ ),
+ project: Flag.String("project").pipe(
+ Flag.withAlias("p"),
+ Flag.withDescription("Project key or id, for example KAN"),
+ Flag.optional,
+ ),
+ },
+ (options) => runWorkflowSet(options),
+).pipe(
+ Command.withDescription(
+ "Choose the column tasks move to when an integration event arrives",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/workspace/create.ts b/packages/cli/src/commands/workspace/create.ts
new file mode 100644
index 000000000..071223ada
--- /dev/null
+++ b/packages/cli/src/commands/workspace/create.ts
@@ -0,0 +1,129 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag, Prompt } from "effect/cli";
+import {
+ type WorkspaceJson,
+ renderWorkspaceChange,
+} from "../../admin/render-workspace-change.js";
+import {
+ checkWorkspaceSlug,
+ deriveWorkspaceSlug,
+} from "../../admin/workspace-slug.js";
+import {
+ createOrganization,
+ isWorkspaceSlugFree,
+ listOrganizations,
+} from "../../api/workspace-admin.js";
+import { Cancelled, InvalidArgument } from "../../errors/errors.js";
+import { emit } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import { promptTheme } from "../../prompts/prompt-theme.js";
+import { ApiLayer } from "../api-layer.js";
+
+const SLUG_ATTEMPTS = 5;
+
+const resolveName = Effect.fnUntraced(function* (name: Option.Option<string>) {
+ const output = yield* Output;
+ const given = name.pipe(
+ Option.map((value) => value.trim()),
+ Option.filter((value) => value !== ""),
+ );
+ if (Option.isSome(given)) return given.value;
+ if (output.interactive) {
+ return yield* Prompt.run(
+ Prompt.String({
+ message: "Workspace name",
+ validate: (value) =>
+ value.trim() === ""
+ ? Effect.fail("Enter a name")
+ : Effect.succeed(value.trim()),
+ theme: promptTheme(output.ui),
+ }),
+ ).pipe(Effect.catchTag("QuitError", () => Effect.fail(new Cancelled())));
+ }
+ return yield* new InvalidArgument({
+ message: "A workspace name is required.",
+ hint: 'Pass it as the first argument, for example kaneo workspace create "Acme Studio".',
+ });
+});
+
+const chooseSlug = Effect.fnUntraced(function* (
+ name: string,
+ requested: Option.Option<string>,
+) {
+ if (Option.isSome(requested)) {
+ const slug = yield* Effect.fromResult(checkWorkspaceSlug(requested.value));
+ const free = yield* withSpinner("Checking the slug")(
+ isWorkspaceSlugFree(slug),
+ );
+ if (!free) {
+ return yield* new InvalidArgument({
+ message: `The slug ${slug} is already taken.`,
+ hint: "Pass another --slug, or leave it out to get a free one.",
+ });
+ }
+ return slug;
+ }
+ const taken = (yield* withSpinner("Loading workspaces")(
+ listOrganizations(),
+ )).map((organization) => organization.slug);
+ for (let attempt = 0; attempt < SLUG_ATTEMPTS; attempt++) {
+ const slug = deriveWorkspaceSlug(name, taken);
+ if (yield* withSpinner("Checking the slug")(isWorkspaceSlugFree(slug))) {
+ return slug;
+ }
+ taken.push(slug);
+ }
+ return yield* new InvalidArgument({
+ message: "Could not find a free slug for this workspace.",
+ hint: "Pass one with --slug.",
+ });
+});
+
+export const runWorkspaceCreate = Effect.fn("command.workspace.create")(
+ function* (options: {
+ readonly name: Option.Option<string>;
+ readonly slug: Option.Option<string>;
+ }) {
+ const name = yield* resolveName(options.name);
+ const slug = yield* chooseSlug(name, options.slug);
+ const created = yield* withSpinner(`Creating ${name}`)(
+ createOrganization({ name, slug }),
+ );
+ const workspace: WorkspaceJson = {
+ id: created.id,
+ name: created.name,
+ slug: created.slug,
+ description: created.description ?? null,
+ };
+ yield* emit(workspace, (ui, value) =>
+ renderWorkspaceChange(ui, {
+ verb: "Created",
+ workspace: value,
+ next: `Run kaneo workspace use ${value.slug} to make it your default.`,
+ }),
+ );
+ },
+);
+
+export const workspaceCreate = Command.make(
+ "create",
+ {
+ name: Argument.String("name").pipe(
+ Argument.withDescription(
+ "Workspace name; asked for when omitted in a terminal",
+ ),
+ Argument.optional,
+ ),
+ slug: Flag.String("slug").pipe(
+ Flag.withDescription(
+ "URL slug such as acme-studio (default: derived from the name)",
+ ),
+ Flag.optional,
+ ),
+ },
+ (options) => runWorkspaceCreate(options),
+).pipe(
+ Command.withDescription("Create a workspace and become its owner"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/workspace/delete.ts b/packages/cli/src/commands/workspace/delete.ts
new file mode 100644
index 000000000..4cb2c3b9d
--- /dev/null
+++ b/packages/cli/src/commands/workspace/delete.ts
@@ -0,0 +1,96 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { confirmBySlug } from "../../admin/confirm-slug.js";
+import { renderWorkspaceChange } from "../../admin/render-workspace-change.js";
+import { resolveWorkspace } from "../../admin/resolve-workspace.js";
+import { deleteOrganization } from "../../api/workspace-admin.js";
+import { InvalidArgument, PermissionDenied } from "../../errors/errors.js";
+import { emit, note } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { Session } from "../../services/session.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runWorkspaceDelete = Effect.fn("command.workspace.delete")(
+ function* (options: { readonly workspace: string; readonly yes: boolean }) {
+ const session = yield* Session;
+ const { workspace } = yield* resolveWorkspace(
+ Option.some(options.workspace),
+ );
+
+ yield* confirmBySlug({
+ yes: options.yes,
+ action: `Deleting ${workspace.name}`,
+ warning: `This permanently deletes ${workspace.name} with every project, task and comment in it, and removes all its members. It cannot be undone.`,
+ slug: workspace.slug,
+ });
+
+ yield* withSpinner(`Deleting ${workspace.name}`)(
+ deleteOrganization(workspace.id),
+ ).pipe(
+ Effect.catchTags({
+ Conflict: (error) =>
+ Effect.fail(
+ new InvalidArgument({
+ message: error.message,
+ hint: "Cancel the subscription in the web app under Settings, then Billing, and run this again.",
+ }),
+ ),
+ PermissionDenied: (error) =>
+ Effect.fail(
+ /not allowed to delete/i.test(error.message)
+ ? new PermissionDenied({
+ message: `Only an owner can delete ${workspace.name}.`,
+ missingPermissions: ["organization:delete"],
+ })
+ : error,
+ ),
+ NotFound: (error) =>
+ Effect.fail(
+ /deletion is disabled/i.test(error.message)
+ ? new InvalidArgument({
+ message: "This server does not allow deleting workspaces.",
+ })
+ : error,
+ ),
+ }),
+ );
+
+ yield* emit(
+ {
+ id: workspace.id,
+ name: workspace.name,
+ slug: workspace.slug,
+ description: workspace.description,
+ deleted: true,
+ },
+ (ui, value) =>
+ renderWorkspaceChange(ui, { verb: "Deleted", workspace: value }),
+ );
+ if (Option.getOrUndefined(session.workspace)?.id === workspace.id) {
+ yield* note((ui) => [
+ ` ${ui.theme.warning(ui.glyphs.warning)} It was your current workspace. Run kaneo workspace use to choose another.`,
+ "",
+ ]);
+ }
+ },
+);
+
+export const workspaceDelete = Command.make(
+ "delete",
+ {
+ workspace: Argument.String("workspace").pipe(
+ Argument.withDescription("Workspace slug, name or id"),
+ ),
+ yes: Flag.Boolean("yes").pipe(
+ Flag.withAlias("y"),
+ Flag.withDescription("Delete without typing the slug to confirm"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runWorkspaceDelete(options),
+).pipe(
+ Command.withDescription(
+ "Permanently delete a workspace with all its projects and tasks",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/workspace/edit.ts b/packages/cli/src/commands/workspace/edit.ts
new file mode 100644
index 000000000..35551af56
--- /dev/null
+++ b/packages/cli/src/commands/workspace/edit.ts
@@ -0,0 +1,158 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { metadataWithDescription } from "../../admin/description-metadata.js";
+import {
+ type WorkspaceJson,
+ renderWorkspaceChange,
+} from "../../admin/render-workspace-change.js";
+import { resolveWorkspace } from "../../admin/resolve-workspace.js";
+import { checkWorkspaceSlug } from "../../admin/workspace-slug.js";
+import {
+ isWorkspaceSlugFree,
+ updateOrganization,
+ type WorkspaceChanges,
+} from "../../api/workspace-admin.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { readTextInput } from "../../input/read-text-input.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runWorkspaceEdit = Effect.fn("command.workspace.edit")(
+ function* (options: {
+ readonly workspace: Option.Option<string>;
+ readonly name: Option.Option<string>;
+ readonly slug: Option.Option<string>;
+ readonly description: Option.Option<string>;
+ readonly descriptionFile: Option.Option<string>;
+ }) {
+ const description = yield* readTextInput({
+ value: options.description,
+ file: options.descriptionFile,
+ flag: "--description",
+ });
+ if (
+ Option.isNone(options.name) &&
+ Option.isNone(options.slug) &&
+ Option.isNone(description)
+ ) {
+ return yield* new InvalidArgument({
+ message: "Nothing to change.",
+ hint: "Pass --name, --slug, or --description (-d) with the new value.",
+ });
+ }
+ const name = Option.map(options.name, (value) => value.trim());
+ if (Option.isSome(name) && name.value === "") {
+ return yield* new InvalidArgument({
+ message: "--name cannot be empty.",
+ });
+ }
+ const slug = Option.isSome(options.slug)
+ ? Option.some(
+ yield* Effect.fromResult(checkWorkspaceSlug(options.slug.value)),
+ )
+ : Option.none<string>();
+
+ const { workspace, organization } = yield* resolveWorkspace(
+ options.workspace,
+ );
+ const data: {
+ -readonly [Key in keyof WorkspaceChanges]: WorkspaceChanges[Key];
+ } = {};
+ const changed: string[] = [];
+ if (Option.isSome(name) && name.value !== workspace.name) {
+ data.name = name.value;
+ changed.push("name");
+ }
+ if (Option.isSome(slug) && slug.value !== workspace.slug) {
+ const free = yield* withSpinner("Checking the slug")(
+ isWorkspaceSlugFree(slug.value),
+ );
+ if (!free) {
+ return yield* new InvalidArgument({
+ message: `The slug ${slug.value} is already taken.`,
+ hint: "Choose another slug.",
+ });
+ }
+ data.slug = slug.value;
+ changed.push("slug");
+ }
+ const text = Option.map(description, (value) => value.trim());
+ if (Option.isSome(text) && text.value !== (workspace.description ?? "")) {
+ data.description = text.value;
+ const metadata = metadataWithDescription(
+ organization.metadata,
+ text.value,
+ );
+ if (metadata) data.metadata = metadata;
+ changed.push("description");
+ }
+
+ const result: WorkspaceJson =
+ changed.length === 0
+ ? {
+ id: workspace.id,
+ name: workspace.name,
+ slug: workspace.slug,
+ description: workspace.description,
+ }
+ : yield* withSpinner(`Updating ${workspace.name}`)(
+ updateOrganization(workspace.id, data),
+ ).pipe(
+ Effect.map((updated) => ({
+ id: updated.id,
+ name: updated.name,
+ slug: updated.slug,
+ description:
+ data.description !== undefined
+ ? data.description || null
+ : workspace.description,
+ })),
+ );
+ yield* emit({ ...result, changed }, (ui, value) =>
+ renderWorkspaceChange(ui, {
+ verb: "Updated",
+ workspace: value,
+ changed: value.changed,
+ }),
+ );
+ },
+);
+
+export const workspaceEdit = Command.make(
+ "edit",
+ {
+ workspace: Argument.String("workspace").pipe(
+ Argument.withDescription(
+ "Workspace slug, name or id (default: the current workspace)",
+ ),
+ Argument.optional,
+ ),
+ name: Flag.String("name").pipe(
+ Flag.withDescription("New workspace name"),
+ Flag.optional,
+ ),
+ slug: Flag.String("slug").pipe(
+ Flag.withDescription("New URL slug, such as acme-studio"),
+ Flag.optional,
+ ),
+ description: Flag.String("description").pipe(
+ Flag.withAlias("d"),
+ Flag.withDescription(
+ 'New description, or - to read stdin; pass "" to clear it',
+ ),
+ Flag.optional,
+ ),
+ descriptionFile: Flag.String("description-file").pipe(
+ Flag.withAlias("F"),
+ Flag.withDescription("Read the description from a file, or - for stdin"),
+ Flag.optional,
+ ),
+ },
+ (options) => runWorkspaceEdit(options),
+).pipe(
+ Command.withDescription(
+ "Rename a workspace or change its slug or description",
+ ),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/workspace/index.ts b/packages/cli/src/commands/workspace/index.ts
new file mode 100644
index 000000000..dd01b3609
--- /dev/null
+++ b/packages/cli/src/commands/workspace/index.ts
@@ -0,0 +1,19 @@
+import { Command } from "effect/cli";
+import { workspaceCreate } from "./create.js";
+import { workspaceDelete } from "./delete.js";
+import { workspaceEdit } from "./edit.js";
+import { workspaceLeave } from "./leave.js";
+import { workspaceList } from "./list.js";
+import { workspaceUse } from "./use.js";
+
+export const workspace = Command.make("workspace").pipe(
+ Command.withDescription("Choose, create and manage workspaces"),
+ Command.withSubcommands([
+ workspaceList,
+ workspaceUse,
+ workspaceCreate,
+ workspaceEdit,
+ workspaceLeave,
+ workspaceDelete,
+ ]),
+);
diff --git a/packages/cli/src/commands/workspace/leave.ts b/packages/cli/src/commands/workspace/leave.ts
new file mode 100644
index 000000000..127b508c7
--- /dev/null
+++ b/packages/cli/src/commands/workspace/leave.ts
@@ -0,0 +1,77 @@
+import { Effect, Option } from "effect";
+import { Argument, Command, Flag } from "effect/cli";
+import { renderWorkspaceChange } from "../../admin/render-workspace-change.js";
+import { resolveWorkspace } from "../../admin/resolve-workspace.js";
+import { leaveOrganization } from "../../api/workspace-admin.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit, note } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { confirmDestructive } from "../../prompts/confirm-destructive.js";
+import { Session } from "../../services/session.js";
+import { ApiLayer } from "../api-layer.js";
+
+export const runWorkspaceLeave = Effect.fn("command.workspace.leave")(
+ function* (options: { readonly workspace: string; readonly yes: boolean }) {
+ const session = yield* Session;
+ const { workspace } = yield* resolveWorkspace(
+ Option.some(options.workspace),
+ );
+
+ yield* confirmDestructive({
+ yes: options.yes,
+ action: `Leaving ${workspace.name}`,
+ question: `Leave ${workspace.name}? You lose access to its projects and tasks until someone invites you again.`,
+ });
+
+ yield* withSpinner(`Leaving ${workspace.name}`)(
+ leaveOrganization(workspace.id),
+ ).pipe(
+ Effect.catchTag("InvalidRequest", (error) =>
+ Effect.fail(
+ /only owner/i.test(error.message)
+ ? new InvalidArgument({
+ message: `You are the only owner of ${workspace.name}, so you cannot leave it.`,
+ hint: `Make another member an owner first with kaneo member role <member> owner -w ${workspace.slug}, or delete the workspace with kaneo workspace delete ${workspace.slug}.`,
+ })
+ : error,
+ ),
+ ),
+ );
+
+ yield* emit(
+ {
+ id: workspace.id,
+ name: workspace.name,
+ slug: workspace.slug,
+ description: workspace.description,
+ left: true,
+ },
+ (ui, value) =>
+ renderWorkspaceChange(ui, { verb: "Left", workspace: value }),
+ );
+ if (Option.getOrUndefined(session.workspace)?.id === workspace.id) {
+ yield* note((ui) => [
+ ` ${ui.theme.warning(ui.glyphs.warning)} It was your current workspace. Run kaneo workspace use to choose another.`,
+ "",
+ ]);
+ }
+ },
+);
+
+export const workspaceLeave = Command.make(
+ "leave",
+ {
+ workspace: Argument.String("workspace").pipe(
+ Argument.withDescription("Workspace slug, name or id"),
+ ),
+ yes: Flag.Boolean("yes").pipe(
+ Flag.withAlias("y"),
+ Flag.withDescription("Leave without asking for confirmation"),
+ Flag.withDefault(false),
+ ),
+ },
+ (options) => runWorkspaceLeave(options),
+).pipe(
+ Command.withDescription("Leave a workspace you are a member of"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/workspace/list.ts b/packages/cli/src/commands/workspace/list.ts
new file mode 100644
index 000000000..8e0cf86a9
--- /dev/null
+++ b/packages/cli/src/commands/workspace/list.ts
@@ -0,0 +1,29 @@
+import { Effect, Option } from "effect";
+import { Command } from "effect/cli";
+import { listWorkspaces } from "../../api/endpoints.js";
+import { emit } from "../../output/emit.js";
+import { withSpinner } from "../../output/spinner.js";
+import { Session } from "../../services/session.js";
+import { ApiLayer } from "../api-layer.js";
+import { renderWorkspaceList } from "./render-workspace-list.js";
+import { toWorkspaceJson } from "./workspace-json.js";
+
+export const runWorkspaceList = Effect.fn("command.workspace.list")(
+ function* () {
+ const session = yield* Session;
+ const workspaces =
+ yield* withSpinner("Loading workspaces")(listWorkspaces());
+ const activeId = Option.getOrUndefined(session.workspace)?.id;
+ yield* emit(
+ workspaces.map((workspace) => toWorkspaceJson(workspace, activeId)),
+ renderWorkspaceList,
+ );
+ },
+);
+
+export const workspaceList = Command.make("list", {}, () =>
+ runWorkspaceList(),
+).pipe(
+ Command.withDescription("List the workspaces you belong to"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/workspace/match-workspace.test.ts b/packages/cli/src/commands/workspace/match-workspace.test.ts
new file mode 100644
index 000000000..05af7bf37
--- /dev/null
+++ b/packages/cli/src/commands/workspace/match-workspace.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { Workspace } from "../../api/schemas.js";
+import { matchWorkspace } from "./match-workspace.js";
+
+function workspace(id: string, name: string, slug: string): Workspace {
+ return {
+ id,
+ name,
+ slug,
+ logo: null,
+ description: null,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ role: "owner",
+ };
+}
+
+const acme = workspace("ws_acme", "Acme Studio", "acme-studio");
+const side = workspace("ws_side", "Side Project", "side-project");
+const twin = workspace("ws_twin", "Acme Studio", "acme-two");
+const all = [acme, side];
+
+describe("matchWorkspace", () => {
+ it("matches the exact id", () => {
+ expect(matchWorkspace(all, "ws_side")).toEqual({
+ kind: "found",
+ workspace: side,
+ });
+ });
+
+ it("matches the slug without caring about case", () => {
+ expect(matchWorkspace(all, "ACME-studio")).toEqual({
+ kind: "found",
+ workspace: acme,
+ });
+ });
+
+ it("matches the name without caring about case or outer spaces", () => {
+ expect(matchWorkspace(all, " side project ")).toEqual({
+ kind: "found",
+ workspace: side,
+ });
+ });
+
+ it("prefers a slug match over a name match", () => {
+ const named = workspace("ws_named", "acme-two", "named");
+ expect(matchWorkspace([named, twin], "acme-two")).toEqual({
+ kind: "found",
+ workspace: twin,
+ });
+ });
+
+ it("reports names shared by more than one workspace", () => {
+ expect(matchWorkspace([acme, twin], "acme studio")).toEqual({
+ kind: "ambiguous",
+ candidates: [acme, twin],
+ });
+ });
+
+ it("reports when nothing matches", () => {
+ expect(matchWorkspace(all, "nope")).toEqual({ kind: "none" });
+ });
+});
diff --git a/packages/cli/src/commands/workspace/match-workspace.ts b/packages/cli/src/commands/workspace/match-workspace.ts
new file mode 100644
index 000000000..ce0ff2034
--- /dev/null
+++ b/packages/cli/src/commands/workspace/match-workspace.ts
@@ -0,0 +1,34 @@
+import type { Workspace } from "../../api/schemas.js";
+
+export type WorkspaceMatch =
+ | { readonly kind: "found"; readonly workspace: Workspace }
+ | {
+ readonly kind: "ambiguous";
+ readonly candidates: ReadonlyArray<Workspace>;
+ }
+ | { readonly kind: "none" };
+
+function normalize(value: string): string {
+ return value.normalize("NFKC").trim().toLowerCase();
+}
+
+export function matchWorkspace(
+ workspaces: ReadonlyArray<Workspace>,
+ reference: string,
+): WorkspaceMatch {
+ const trimmed = reference.trim();
+ const wanted = normalize(reference);
+ const tiers = [
+ workspaces.filter((workspace) => workspace.id === trimmed),
+ workspaces.filter((workspace) => normalize(workspace.slug) === wanted),
+ workspaces.filter((workspace) => normalize(workspace.name) === wanted),
+ ];
+ for (const tier of tiers) {
+ const [first] = tier;
+ if (!first) continue;
+ return tier.length === 1
+ ? { kind: "found", workspace: first }
+ : { kind: "ambiguous", candidates: tier };
+ }
+ return { kind: "none" };
+}
diff --git a/packages/cli/src/commands/workspace/override-notice.test.ts b/packages/cli/src/commands/workspace/override-notice.test.ts
new file mode 100644
index 000000000..6ecccb6f8
--- /dev/null
+++ b/packages/cli/src/commands/workspace/override-notice.test.ts
@@ -0,0 +1,30 @@
+import { Option } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import type { WorkspaceSource } from "../../services/session.js";
+import { overrideNotice } from "./override-notice.js";
+
+const from = (source: WorkspaceSource, id = "ws_other") =>
+ Option.some({ id, source });
+
+describe("overrideNotice", () => {
+ it("stays quiet without an override", () => {
+ expect(overrideNotice(Option.none(), undefined, "ws_acme")).toBeNull();
+ expect(overrideNotice(from("profile"), undefined, "ws_acme")).toBeNull();
+ });
+
+ it("stays quiet when the override already points at the chosen workspace", () => {
+ expect(
+ overrideNotice(from("env", "ws_acme"), undefined, "ws_acme"),
+ ).toBeNull();
+ });
+
+ it("names the source that wins over the saved default", () => {
+ expect(overrideNotice(from("flag"), undefined, "ws_acme")).toContain("-w");
+ expect(overrideNotice(from("env"), undefined, "ws_acme")).toContain(
+ "KANEO_WORKSPACE",
+ );
+ expect(
+ overrideNotice(from("repo"), "/code/app/.kaneo.json", "ws_acme"),
+ ).toContain("/code/app/.kaneo.json");
+ });
+});
diff --git a/packages/cli/src/commands/workspace/override-notice.ts b/packages/cli/src/commands/workspace/override-notice.ts
new file mode 100644
index 000000000..9657019fa
--- /dev/null
+++ b/packages/cli/src/commands/workspace/override-notice.ts
@@ -0,0 +1,19 @@
+import { Option } from "effect";
+import type { WorkspaceRef } from "../../services/session.js";
+
+export function overrideNotice(
+ current: Option.Option<WorkspaceRef>,
+ repoPath: string | undefined,
+ chosenId: string,
+): string | null {
+ if (Option.isNone(current)) return null;
+ const { id, source } = current.value;
+ if (source === "profile" || id === chosenId) return null;
+ if (source === "flag") {
+ return "-w overrides this default for the commands you pass it to.";
+ }
+ if (source === "env") {
+ return "KANEO_WORKSPACE is set and is used instead of this default until you unset it.";
+ }
+ return `${repoPath ?? ".kaneo.json"} sets another workspace, which is used instead inside that folder.`;
+}
diff --git a/packages/cli/src/commands/workspace/remember-workspace.test.ts b/packages/cli/src/commands/workspace/remember-workspace.test.ts
new file mode 100644
index 000000000..e6905004c
--- /dev/null
+++ b/packages/cli/src/commands/workspace/remember-workspace.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it } from "vite-plus/test";
+import { type ConfigFile, emptyConfig } from "../../config/format.js";
+import { rememberWorkspace } from "./remember-workspace.js";
+
+const signedIn: ConfigFile = {
+ kind: "kaneo-cli",
+ version: 1,
+ activeProfile: "default",
+ profiles: {
+ default: {
+ apiUrl: "http://localhost:1337",
+ webUrl: "http://localhost:5173",
+ token: "secret",
+ workspaceId: "ws_old",
+ user: { id: "u1", name: "Ada Lovelace", email: "[email protected]" },
+ },
+ work: { apiUrl: "https://cloud.kaneo.app", token: "other" },
+ },
+};
+
+describe("rememberWorkspace", () => {
+ it("replaces only the workspace and keeps every other profile field", () => {
+ const result = rememberWorkspace(
+ signedIn,
+ "default",
+ "http://localhost:1337/",
+ "ws_new",
+ );
+ expect(result).toEqual({
+ kind: "saved",
+ config: {
+ ...signedIn,
+ profiles: {
+ ...signedIn.profiles,
+ default: { ...signedIn.profiles.default, workspaceId: "ws_new" },
+ },
+ },
+ });
+ });
+
+ it("creates a profile for the current server when none is stored", () => {
+ const result = rememberWorkspace(
+ emptyConfig,
+ "default",
+ "http://localhost:1337",
+ "ws_new",
+ );
+ expect(result).toEqual({
+ kind: "saved",
+ config: {
+ ...emptyConfig,
+ profiles: {
+ default: { apiUrl: "http://localhost:1337", workspaceId: "ws_new" },
+ },
+ },
+ });
+ });
+
+ it("updates a named profile without switching the active one", () => {
+ const result = rememberWorkspace(
+ signedIn,
+ "work",
+ "https://cloud.kaneo.app",
+ "ws_cloud",
+ );
+ expect(result.kind === "saved" && result.config.activeProfile).toBe(
+ "default",
+ );
+ expect(result.kind === "saved" && result.config.profiles.work).toEqual({
+ apiUrl: "https://cloud.kaneo.app",
+ token: "other",
+ workspaceId: "ws_cloud",
+ });
+ });
+
+ it("refuses to write into a profile that belongs to another server", () => {
+ expect(
+ rememberWorkspace(signedIn, "work", "http://localhost:1337", "ws_new"),
+ ).toEqual({
+ kind: "other-server",
+ profileApiUrl: "https://cloud.kaneo.app",
+ });
+ });
+});
diff --git a/packages/cli/src/commands/workspace/remember-workspace.ts b/packages/cli/src/commands/workspace/remember-workspace.ts
new file mode 100644
index 000000000..9a7cf976f
--- /dev/null
+++ b/packages/cli/src/commands/workspace/remember-workspace.ts
@@ -0,0 +1,26 @@
+import { normalizeBaseUrl } from "@kaneo/mcp/normalize-base-url";
+import { type ConfigFile, withProfile } from "../../config/format.js";
+
+export type RememberedWorkspace =
+ | { readonly kind: "saved"; readonly config: ConfigFile }
+ | { readonly kind: "other-server"; readonly profileApiUrl: string };
+
+export function rememberWorkspace(
+ config: ConfigFile,
+ profileName: string,
+ apiUrl: string,
+ workspaceId: string,
+): RememberedWorkspace {
+ const stored = config.profiles[profileName];
+ if (stored && normalizeBaseUrl(stored.apiUrl) !== normalizeBaseUrl(apiUrl)) {
+ return { kind: "other-server", profileApiUrl: stored.apiUrl };
+ }
+ const updated = withProfile(config, profileName, (profile) => ({
+ ...(profile ?? { apiUrl }),
+ workspaceId,
+ }));
+ return {
+ kind: "saved",
+ config: { ...updated, activeProfile: config.activeProfile },
+ };
+}
diff --git a/packages/cli/src/commands/workspace/render-workspace-list.test.ts b/packages/cli/src/commands/workspace/render-workspace-list.test.ts
new file mode 100644
index 000000000..5b7bf5de1
--- /dev/null
+++ b/packages/cli/src/commands/workspace/render-workspace-list.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../../render/ui.js";
+import { stringWidth } from "../../render/width.js";
+import { renderWorkspaceList } from "./render-workspace-list.js";
+import { renderWorkspaceUsed } from "./render-workspace-used.js";
+import type { WorkspaceJson } from "./workspace-json.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+const acme: WorkspaceJson = {
+ id: "tXNwjPJWwrkrDurpqDXi6O4q5FhiqVvC",
+ name: "Acme Studio",
+ slug: "acme-studio",
+ role: "owner",
+ description: null,
+ active: true,
+};
+
+const side: WorkspaceJson = {
+ id: "kqV6iY1NsUHx7GOWYfUo48SPnju4BGTU",
+ name: "Side Project",
+ slug: "side-project",
+ role: "member",
+ description: null,
+ active: false,
+};
+
+describe("renderWorkspaceList", () => {
+ it("marks the active workspace and fits 80 columns", () => {
+ const lines = renderWorkspaceList(ui, [acme, side]);
+ expect(lines).toEqual([
+ "",
+ " ● Acme Studio acme-studio Owner tXNwjPJWwrkrDurpqDXi6O4q5FhiqVvC",
+ " Side Project side-project Member kqV6iY1NsUHx7GOWYfUo48SPnju4BGTU",
+ "",
+ ]);
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(80);
+ });
+
+ it("drops the marker column and suggests a default when none is active", () => {
+ const lines = renderWorkspaceList(ui, [{ ...acme, active: false }, side]);
+ expect(lines[1]?.startsWith(" Acme Studio")).toBe(true);
+ expect(lines).toContain(
+ " No workspace selected. Run kaneo workspace use to choose one.",
+ );
+ });
+
+ it("leaves the role empty when the server does not report it", () => {
+ const [, row] = renderWorkspaceList(ui, [{ ...acme, role: null }]);
+ expect(row).toBe(
+ " ● Acme Studio acme-studio tXNwjPJWwrkrDurpqDXi6O4q5FhiqVvC",
+ );
+ });
+
+ it("says so when there are no workspaces", () => {
+ expect(renderWorkspaceList(ui, [])).toEqual([
+ "",
+ " You are not a member of any workspace yet.",
+ "",
+ ]);
+ });
+});
+
+describe("renderWorkspaceUsed", () => {
+ it("confirms the workspace with its id below", () => {
+ expect(renderWorkspaceUsed(ui, { workspace: acme })).toEqual([
+ "",
+ " ✓ Using Acme Studio",
+ " tXNwjPJWwrkrDurpqDXi6O4q5FhiqVvC",
+ "",
+ ]);
+ });
+});
diff --git a/packages/cli/src/commands/workspace/render-workspace-list.ts b/packages/cli/src/commands/workspace/render-workspace-list.ts
new file mode 100644
index 000000000..33b492bfe
--- /dev/null
+++ b/packages/cli/src/commands/workspace/render-workspace-list.ts
@@ -0,0 +1,84 @@
+import { type Cell, text } from "../../render/cell.js";
+import { type Column, renderTable } from "../../render/table.js";
+import type { Ui } from "../../render/ui.js";
+import type { WorkspaceJson } from "./workspace-json.js";
+
+function roleLabel(role: string | null): string {
+ if (!role) return "";
+ return role
+ .split(",")
+ .map((part) => part.trim())
+ .filter(Boolean)
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
+ .join(", ");
+}
+
+export function renderWorkspaceList(
+ ui: Ui,
+ workspaces: ReadonlyArray<WorkspaceJson>,
+): string[] {
+ const { theme, glyphs } = ui;
+ if (workspaces.length === 0) {
+ return [
+ "",
+ ` ${theme.muted("You are not a member of any workspace yet.")}`,
+ "",
+ ];
+ }
+ const hasActive = workspaces.some((workspace) => workspace.active);
+ const columns: Array<Column<WorkspaceJson>> = [
+ ...(hasActive
+ ? [
+ {
+ header: "",
+ cell: (workspace: WorkspaceJson): Cell =>
+ workspace.active ? [text(glyphs.dot, theme.success)] : [],
+ },
+ ]
+ : []),
+ {
+ header: "Name",
+ flex: true,
+ minWidth: 12,
+ cell: (workspace) => [
+ text(workspace.name, workspace.active ? theme.strong : undefined),
+ ],
+ },
+ {
+ header: "Slug",
+ optional: true,
+ cell: (workspace) => [text(workspace.slug, theme.muted)],
+ },
+ ...(workspaces.some((workspace) => workspace.role)
+ ? [
+ {
+ header: "Role",
+ optional: true,
+ cell: (workspace: WorkspaceJson): Cell => [
+ text(roleLabel(workspace.role)),
+ ],
+ },
+ ]
+ : []),
+ {
+ header: "ID",
+ optional: true,
+ cell: (workspace) => [text(workspace.id, theme.muted)],
+ },
+ ];
+ const lines = [
+ "",
+ ...renderTable(ui, workspaces, columns, {
+ width: ui.caps.columns,
+ indent: 2,
+ }),
+ "",
+ ];
+ if (!hasActive) {
+ lines.push(
+ ` ${theme.muted("No workspace selected. Run kaneo workspace use to choose one.")}`,
+ "",
+ );
+ }
+ return lines;
+}
diff --git a/packages/cli/src/commands/workspace/render-workspace-used.ts b/packages/cli/src/commands/workspace/render-workspace-used.ts
new file mode 100644
index 000000000..e98d069cb
--- /dev/null
+++ b/packages/cli/src/commands/workspace/render-workspace-used.ts
@@ -0,0 +1,22 @@
+import type { Ui } from "../../render/ui.js";
+
+export type UsedWorkspace = {
+ readonly id: string;
+ readonly name: string;
+ readonly slug: string;
+ readonly role: string | null;
+ readonly description: string | null;
+};
+
+export function renderWorkspaceUsed(
+ ui: Ui,
+ result: { readonly workspace: UsedWorkspace },
+): string[] {
+ const { theme, glyphs } = ui;
+ return [
+ "",
+ ` ${theme.success(glyphs.tick)} Using ${theme.strong(result.workspace.name)}`,
+ ` ${theme.muted(result.workspace.id)}`,
+ "",
+ ];
+}
diff --git a/packages/cli/src/commands/workspace/use.ts b/packages/cli/src/commands/workspace/use.ts
new file mode 100644
index 000000000..0c9fa5a9e
--- /dev/null
+++ b/packages/cli/src/commands/workspace/use.ts
@@ -0,0 +1,142 @@
+import { Effect, Option } from "effect";
+import { Argument, Command } from "effect/cli";
+import { listWorkspaces } from "../../api/endpoints.js";
+import type { Workspace } from "../../api/schemas.js";
+import { ConfigStore } from "../../config/config-store.js";
+import { InvalidArgument } from "../../errors/errors.js";
+import { emit, note } from "../../output/emit.js";
+import { Output } from "../../output/output.js";
+import { withSpinner } from "../../output/spinner.js";
+import { pick } from "../../prompts/pick.js";
+import { Session } from "../../services/session.js";
+import { ApiLayer } from "../api-layer.js";
+import { matchWorkspace } from "./match-workspace.js";
+import { overrideNotice } from "./override-notice.js";
+import { rememberWorkspace } from "./remember-workspace.js";
+import { renderWorkspaceUsed } from "./render-workspace-used.js";
+
+function host(url: string): string {
+ try {
+ return new URL(url).host;
+ } catch {
+ return url;
+ }
+}
+
+const chooseWorkspace = Effect.fn("workspace.use.choose")(function* (
+ workspaces: ReadonlyArray<Workspace>,
+ reference: Option.Option<string>,
+) {
+ const session = yield* Session;
+ const output = yield* Output;
+ if (Option.isSome(reference)) {
+ const match = matchWorkspace(workspaces, reference.value);
+ if (match.kind === "found") return match.workspace;
+ if (match.kind === "ambiguous") {
+ return yield* new InvalidArgument({
+ message: `"${reference.value}" matches ${match.candidates.length} workspaces.`,
+ hint: `Use a slug instead: ${match.candidates.map((workspace) => workspace.slug).join(", ")}.`,
+ });
+ }
+ return yield* new InvalidArgument({
+ message: `No workspace matches "${reference.value}".`,
+ hint: "Run kaneo workspace list to see your workspaces.",
+ });
+ }
+ const [only] = workspaces;
+ if (!only) {
+ return yield* new InvalidArgument({
+ message: "You are not a member of any workspace yet.",
+ hint: "Create one in the Kaneo web app, then run this again.",
+ });
+ }
+ if (workspaces.length === 1) return only;
+ const currentId = Option.getOrUndefined(session.workspace)?.id;
+ const { separator } = output.ui.glyphs;
+ return yield* pick(
+ "Choose your default workspace",
+ workspaces.map((workspace) => ({
+ title: workspace.name,
+ value: workspace,
+ description:
+ workspace.id === currentId
+ ? `${workspace.slug} ${separator} current`
+ : workspace.slug,
+ })),
+ );
+});
+
+export const runWorkspaceUse = Effect.fn("command.workspace.use")(
+ function* (options: { readonly workspace: Option.Option<string> }) {
+ const session = yield* Session;
+ const output = yield* Output;
+ const store = yield* ConfigStore;
+
+ if (Option.isSome(session.configProblem)) {
+ return yield* Effect.fail(session.configProblem.value);
+ }
+ if (Option.isNone(options.workspace) && !output.interactive) {
+ return yield* new InvalidArgument({
+ message: "Which workspace should be the default?",
+ hint: "Pass its slug, name or id, for example kaneo workspace use acme-studio. Run kaneo workspace list to see them.",
+ });
+ }
+
+ const workspaces =
+ yield* withSpinner("Loading workspaces")(listWorkspaces());
+ const workspace = yield* chooseWorkspace(workspaces, options.workspace);
+
+ const remembered = rememberWorkspace(
+ yield* store.load,
+ session.profileName,
+ session.apiUrl,
+ workspace.id,
+ );
+ if (remembered.kind === "other-server") {
+ return yield* new InvalidArgument({
+ message: `The profile "${session.profileName}" belongs to ${host(remembered.profileApiUrl)}, not ${host(session.apiUrl)}.`,
+ hint: "Pass --profile with another name to keep a default for this server.",
+ });
+ }
+ yield* store.save(remembered.config);
+
+ yield* emit(
+ {
+ workspace: {
+ id: workspace.id,
+ name: workspace.name,
+ slug: workspace.slug,
+ role: workspace.role,
+ description: workspace.description,
+ },
+ },
+ renderWorkspaceUsed,
+ );
+
+ const notice = overrideNotice(
+ session.workspace,
+ session.repo?.path,
+ workspace.id,
+ );
+ if (notice) {
+ yield* note((ui) => [
+ ` ${ui.theme.warning(ui.glyphs.warning)} ${notice}`,
+ "",
+ ]);
+ }
+ },
+);
+
+export const workspaceUse = Command.make(
+ "use",
+ {
+ workspace: Argument.String("workspace").pipe(
+ Argument.withDescription("Workspace slug, name or id"),
+ Argument.optional,
+ ),
+ },
+ (options) => runWorkspaceUse(options),
+).pipe(
+ Command.withDescription("Choose the default workspace for your commands"),
+ Command.provide(ApiLayer),
+);
diff --git a/packages/cli/src/commands/workspace/workspace-json.ts b/packages/cli/src/commands/workspace/workspace-json.ts
new file mode 100644
index 000000000..60fbd00ef
--- /dev/null
+++ b/packages/cli/src/commands/workspace/workspace-json.ts
@@ -0,0 +1,24 @@
+import type { Workspace } from "../../api/schemas.js";
+
+export type WorkspaceJson = {
+ readonly id: string;
+ readonly name: string;
+ readonly slug: string;
+ readonly role: string | null;
+ readonly description: string | null;
+ readonly active: boolean;
+};
+
+export function toWorkspaceJson(
+ workspace: Workspace,
+ activeId: string | undefined,
+): WorkspaceJson {
+ return {
+ id: workspace.id,
+ name: workspace.name,
+ slug: workspace.slug,
+ role: workspace.role,
+ description: workspace.description,
+ active: workspace.id === activeId,
+ };
+}
diff --git a/packages/cli/src/comments/comment-json.test.ts b/packages/cli/src/comments/comment-json.test.ts
new file mode 100644
index 000000000..eaef02394
--- /dev/null
+++ b/packages/cli/src/comments/comment-json.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from "vite-plus/test";
+import { isEdited, latest, toCommentJson } from "./comment-json.js";
+
+const comment = {
+ id: "c1",
+ taskId: "t1",
+ userId: "u1",
+ content: "Looks good",
+ createdAt: "2026-10-08T10:00:00.000Z",
+ updatedAt: "2026-10-08T10:00:00.000Z",
+ user: { name: "Ada Lovelace" },
+};
+
+describe("toCommentJson", () => {
+ it("maps the author and keeps the timestamps", () => {
+ expect(toCommentJson(comment)).toEqual({
+ id: "c1",
+ taskId: "t1",
+ author: { id: "u1", name: "Ada Lovelace" },
+ content: "Looks good",
+ createdAt: "2026-10-08T10:00:00.000Z",
+ updatedAt: "2026-10-08T10:00:00.000Z",
+ edited: false,
+ });
+ });
+
+ it("leaves the author out when the user is gone", () => {
+ expect(
+ toCommentJson({ ...comment, userId: null, user: null }).author,
+ ).toBeNull();
+ });
+});
+
+describe("isEdited", () => {
+ it("ignores timestamps written in the same moment", () => {
+ expect(
+ isEdited("2026-10-08T10:00:00.000Z", "2026-10-08T10:00:00.400Z"),
+ ).toBe(false);
+ });
+
+ it("flags a later update", () => {
+ expect(
+ isEdited("2026-10-08T10:00:00.000Z", "2026-10-08T10:05:00.000Z"),
+ ).toBe(true);
+ });
+
+ it("is false for unreadable timestamps", () => {
+ expect(isEdited("", "2026-10-08T10:05:00.000Z")).toBe(false);
+ });
+});
+
+describe("latest", () => {
+ it("keeps the newest items in their order", () => {
+ expect(latest([1, 2, 3, 4], 2)).toEqual([3, 4]);
+ });
+
+ it("keeps everything under the limit", () => {
+ expect(latest([1, 2], 5)).toEqual([1, 2]);
+ });
+});
diff --git a/packages/cli/src/comments/comment-json.ts b/packages/cli/src/comments/comment-json.ts
new file mode 100644
index 000000000..13e166a53
--- /dev/null
+++ b/packages/cli/src/comments/comment-json.ts
@@ -0,0 +1,44 @@
+import type { TaskComment } from "../api/comments.js";
+
+export type CommentAuthor = { readonly id: string; readonly name: string };
+
+export type CommentJson = {
+ readonly id: string;
+ readonly taskId: string;
+ readonly author: CommentAuthor | null;
+ readonly content: string;
+ readonly createdAt: string;
+ readonly updatedAt: string;
+ readonly edited: boolean;
+};
+
+const EDIT_GRACE_MS = 1000;
+
+export function isEdited(createdAt: string, updatedAt: string): boolean {
+ const created = Date.parse(createdAt);
+ const updated = Date.parse(updatedAt);
+ return (
+ Number.isFinite(created) &&
+ Number.isFinite(updated) &&
+ updated - created > EDIT_GRACE_MS
+ );
+}
+
+export function toCommentJson(comment: TaskComment): CommentJson {
+ return {
+ id: comment.id,
+ taskId: comment.taskId,
+ author:
+ comment.userId && comment.user
+ ? { id: comment.userId, name: comment.user.name }
+ : null,
+ content: comment.content,
+ createdAt: comment.createdAt,
+ updatedAt: comment.updatedAt,
+ edited: isEdited(comment.createdAt, comment.updatedAt),
+ };
+}
+
+export function latest<A>(items: ReadonlyArray<A>, limit: number): A[] {
+ return items.slice(Math.max(0, items.length - limit));
+}
diff --git a/packages/cli/src/comments/describe-activity.test.ts b/packages/cli/src/comments/describe-activity.test.ts
new file mode 100644
index 000000000..bcebc15bc
--- /dev/null
+++ b/packages/cli/src/comments/describe-activity.test.ts
@@ -0,0 +1,194 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { TaskActivity } from "../api/activity.js";
+import {
+ activityActor,
+ describeActivity,
+ excerpt,
+ toActivityEntry,
+ toActivityJson,
+} from "./describe-activity.js";
+
+const lookups = {
+ members: new Map([
+ ["u1", "Ada Lovelace"],
+ ["u2", "Grace Hopper"],
+ ]),
+ statuses: new Map([
+ ["to-do", "To Do"],
+ ["in-progress", "In Progress"],
+ ]),
+ now: new Date(2026, 9, 8, 15, 0),
+};
+
+const activity = (overrides: Partial<TaskActivity>): TaskActivity => ({
+ id: "a1",
+ type: "comment",
+ createdAt: "2026-10-08T10:00:00.000Z",
+ userId: "u1",
+ content: null,
+ eventData: null,
+ externalUserName: null,
+ ...overrides,
+});
+
+const summary = (overrides: Partial<TaskActivity>) =>
+ describeActivity(activity(overrides), lookups).summary;
+
+describe("describeActivity", () => {
+ it("shows a comment with a plain excerpt", () => {
+ expect(
+ describeActivity(
+ activity({ content: "**Ship** it\n\n- after review" }),
+ lookups,
+ ),
+ ).toEqual({ summary: "commented", detail: "Ship it • after review" });
+ });
+
+ it("names the columns of a status change", () => {
+ expect(
+ summary({
+ type: "status_changed",
+ eventData: { oldStatus: "to-do", newStatus: "in-progress" },
+ }),
+ ).toBe("changed status from To Do to In Progress");
+ });
+
+ it("title-cases statuses the project no longer has", () => {
+ expect(
+ summary({
+ type: "status_changed",
+ eventData: { oldStatus: "in-review", newStatus: "done" },
+ }),
+ ).toBe("changed status from In Review to Done");
+ });
+
+ it("describes priority changes", () => {
+ expect(
+ summary({
+ type: "priority_changed",
+ eventData: { oldPriority: "no-priority", newPriority: "high" },
+ }),
+ ).toBe("changed priority from No priority to High");
+ });
+
+ it("describes assignments", () => {
+ expect(
+ summary({
+ type: "assignee_changed",
+ eventData: { newAssignee: "Grace Hopper", newAssigneeId: "u2" },
+ }),
+ ).toBe("assigned Grace Hopper");
+ expect(
+ summary({
+ type: "assignee_changed",
+ eventData: { isSelfAssigned: true },
+ }),
+ ).toBe("assigned themselves");
+ expect(summary({ type: "unassigned" })).toBe("removed the assignee");
+ });
+
+ it("describes due date changes", () => {
+ expect(
+ summary({
+ type: "due_date_changed",
+ eventData: { oldDueDate: null, newDueDate: "2026-10-12T12:00:00.000Z" },
+ }),
+ ).toBe("set the due date to Oct 12");
+ expect(
+ summary({
+ type: "due_date_changed",
+ eventData: {
+ oldDueDate: "2026-10-12T12:00:00.000Z",
+ newDueDate: "2027-01-03T12:00:00.000Z",
+ },
+ }),
+ ).toBe("changed the due date from Oct 12 to Jan 3, 2027");
+ expect(
+ summary({
+ type: "due_date_changed",
+ eventData: { oldDueDate: "2026-10-12T12:00:00.000Z", newDueDate: null },
+ }),
+ ).toBe("cleared the due date");
+ });
+
+ it("describes renames, moves and creation", () => {
+ expect(
+ summary({
+ type: "title_changed",
+ eventData: { oldTitle: "Fix login", newTitle: "Fix login redirect" },
+ }),
+ ).toBe('renamed the task from "Fix login" to "Fix login redirect"');
+ expect(
+ summary({
+ type: "moved",
+ eventData: { fromProjectName: "Kaneo Web", toProjectName: "Mobile" },
+ }),
+ ).toBe("moved the task from Kaneo Web to Mobile");
+ expect(
+ summary({
+ type: "moved",
+ eventData: { fromProjectName: null, toProjectName: "Mobile" },
+ }),
+ ).toBe("moved the task from another project to Mobile");
+ expect(summary({ type: "created" })).toBe("created the task");
+ });
+
+ it("falls back to the stored text, then the type", () => {
+ expect(summary({ type: "status_changed", content: "moved it" })).toBe(
+ "moved it",
+ );
+ expect(summary({ type: "label_assigned" })).toBe("label assigned");
+ });
+});
+
+describe("activityActor", () => {
+ it("names workspace members", () => {
+ expect(activityActor(activity({}), lookups.members)).toEqual({
+ id: "u1",
+ name: "Ada Lovelace",
+ });
+ });
+
+ it("prefers the imported author", () => {
+ expect(
+ activityActor(
+ activity({ externalUserName: "octocat", userId: null }),
+ lookups.members,
+ ),
+ ).toEqual({ id: null, name: "octocat" });
+ });
+
+ it("is null without a user", () => {
+ expect(
+ activityActor(activity({ userId: null }), lookups.members),
+ ).toBeNull();
+ });
+});
+
+describe("toActivityJson", () => {
+ it("joins the summary and detail into the message", () => {
+ expect(
+ toActivityJson(
+ toActivityEntry(activity({ content: "Ship it" }), lookups),
+ ),
+ ).toEqual({
+ id: "a1",
+ type: "comment",
+ actor: { id: "u1", name: "Ada Lovelace" },
+ message: "commented: Ship it",
+ createdAt: "2026-10-08T10:00:00.000Z",
+ });
+ });
+});
+
+describe("excerpt", () => {
+ it("caps long text", () => {
+ const text = excerpt("a".repeat(300)) ?? "";
+ expect([...text]).toHaveLength(240);
+ expect(text.endsWith("…")).toBe(true);
+ });
+
+ it("is null for blank content", () => {
+ expect(excerpt(" \n ")).toBeNull();
+ });
+});
diff --git a/packages/cli/src/comments/describe-activity.ts b/packages/cli/src/comments/describe-activity.ts
new file mode 100644
index 000000000..36a957e4c
--- /dev/null
+++ b/packages/cli/src/comments/describe-activity.ts
@@ -0,0 +1,198 @@
+import type { TaskActivity } from "../api/activity.js";
+import { PRIORITY_LABELS } from "../render/task-format.js";
+import { statusLabel } from "../search/render-search.js";
+import { plainDescription } from "../tasks/plain-description.js";
+
+export type ActivityActor = {
+ readonly id: string | null;
+ readonly name: string | null;
+};
+
+export type ActivityJson = {
+ readonly id: string;
+ readonly type: string;
+ readonly actor: ActivityActor | null;
+ readonly message: string;
+ readonly createdAt: string;
+};
+
+export type ActivityEntry = ActivityJson & {
+ readonly summary: string;
+ readonly detail: string | null;
+};
+
+export type ActivityLookups = {
+ readonly members: ReadonlyMap<string, string>;
+ readonly statuses: ReadonlyMap<string, string>;
+ readonly now: Date;
+};
+
+type Description = { readonly summary: string; readonly detail: string | null };
+
+const EXCERPT_LENGTH = 240;
+
+export function excerpt(content: string | null): string | null {
+ if (!content) return null;
+ const flat = plainDescription(content, { width: 100_000, unicode: true })
+ .lines.map((line) => line.text)
+ .join(" ")
+ .replace(/\s+/gu, " ")
+ .trim();
+ if (flat === "") return null;
+ const characters = [...flat];
+ return characters.length > EXCERPT_LENGTH
+ ? `${characters
+ .slice(0, EXCERPT_LENGTH - 1)
+ .join("")
+ .trimEnd()}…`
+ : flat;
+}
+
+function eventDataOf(activity: TaskActivity): Record<string, unknown> | null {
+ const data = activity.eventData;
+ return data && typeof data === "object" && !Array.isArray(data)
+ ? (data as Record<string, unknown>)
+ : null;
+}
+
+function stringField(
+ data: Record<string, unknown>,
+ key: string,
+): string | null {
+ const value = data[key];
+ return typeof value === "string" && value !== "" ? value : null;
+}
+
+function formatDay(value: string, now: Date): string {
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime())) return value;
+ return date.toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ ...(date.getFullYear() === now.getFullYear() ? {} : { year: "numeric" }),
+ });
+}
+
+function priorityName(value: string | null): string {
+ if (!value || value === "no-priority") return "No priority";
+ return PRIORITY_LABELS[value] ?? value;
+}
+
+function fallback(activity: TaskActivity): Description {
+ return {
+ summary: excerpt(activity.content) ?? activity.type.replace(/[_-]+/gu, " "),
+ detail: null,
+ };
+}
+
+function describeEvent(
+ activity: TaskActivity,
+ data: Record<string, unknown>,
+ lookups: ActivityLookups,
+): Description | null {
+ const status = (key: string) => {
+ const slug = stringField(data, key) ?? "";
+ return lookups.statuses.get(slug) ?? statusLabel(slug);
+ };
+ const plain = (summary: string): Description => ({ summary, detail: null });
+ switch (activity.type) {
+ case "status_changed":
+ return plain(
+ `changed status from ${status("oldStatus")} to ${status("newStatus")}`,
+ );
+ case "priority_changed":
+ return plain(
+ `changed priority from ${priorityName(stringField(data, "oldPriority"))} to ${priorityName(stringField(data, "newPriority"))}`,
+ );
+ case "assignee_changed": {
+ if (data.isSelfAssigned === true) return plain("assigned themselves");
+ const name =
+ stringField(data, "newAssignee") ??
+ lookups.members.get(stringField(data, "newAssigneeId") ?? "") ??
+ "someone";
+ return plain(`assigned ${name}`);
+ }
+ case "due_date_changed": {
+ const next = stringField(data, "newDueDate");
+ const previous = stringField(data, "oldDueDate");
+ if (!next) return plain("cleared the due date");
+ return plain(
+ previous
+ ? `changed the due date from ${formatDay(previous, lookups.now)} to ${formatDay(next, lookups.now)}`
+ : `set the due date to ${formatDay(next, lookups.now)}`,
+ );
+ }
+ case "title_changed":
+ return plain(
+ `renamed the task from "${stringField(data, "oldTitle") ?? ""}" to "${stringField(data, "newTitle") ?? ""}"`,
+ );
+ case "moved": {
+ const from = stringField(data, "fromProjectName");
+ const to = stringField(data, "toProjectName");
+ if (from && to) return plain(`moved the task from ${from} to ${to}`);
+ if (to) return plain(`moved the task from another project to ${to}`);
+ return plain("moved the task");
+ }
+ default:
+ return null;
+ }
+}
+
+export function describeActivity(
+ activity: TaskActivity,
+ lookups: ActivityLookups,
+): Description {
+ switch (activity.type) {
+ case "comment":
+ return { summary: "commented", detail: excerpt(activity.content) };
+ case "created":
+ case "create":
+ case "task":
+ return { summary: "created the task", detail: null };
+ case "unassigned":
+ return { summary: "removed the assignee", detail: null };
+ case "description_changed":
+ return { summary: "updated the description", detail: null };
+ }
+ const data = eventDataOf(activity);
+ return (data && describeEvent(activity, data, lookups)) ?? fallback(activity);
+}
+
+export function activityActor(
+ activity: TaskActivity,
+ members: ReadonlyMap<string, string>,
+): ActivityActor | null {
+ const external = activity.externalUserName ?? null;
+ if (external) return { id: null, name: external };
+ if (!activity.userId) return null;
+ return {
+ id: activity.userId,
+ name: members.get(activity.userId) ?? null,
+ };
+}
+
+export function toActivityEntry(
+ activity: TaskActivity,
+ lookups: ActivityLookups,
+): ActivityEntry {
+ const { summary, detail } = describeActivity(activity, lookups);
+ return {
+ id: activity.id,
+ type: activity.type,
+ actor: activityActor(activity, lookups.members),
+ message: detail ? `${summary}: ${detail}` : summary,
+ createdAt: activity.createdAt,
+ summary,
+ detail,
+ };
+}
+
+export function toActivityJson(entry: ActivityEntry): ActivityJson {
+ return {
+ id: entry.id,
+ type: entry.type,
+ actor: entry.actor,
+ message: entry.message,
+ createdAt: entry.createdAt,
+ };
+}
diff --git a/packages/cli/src/comments/own-comment.ts b/packages/cli/src/comments/own-comment.ts
new file mode 100644
index 000000000..c4cc83cef
--- /dev/null
+++ b/packages/cli/src/comments/own-comment.ts
@@ -0,0 +1,25 @@
+import { Effect } from "effect";
+import type { ApiFailure } from "../errors/errors.js";
+import { InvalidArgument } from "../errors/errors.js";
+
+function notYours(id: string): InvalidArgument {
+ return new InvalidArgument({
+ message: `Comment ${id} was not found, or someone else wrote it.`,
+ hint: "You can only change your own comments. Run kaneo comment list <task> to see the ids.",
+ });
+}
+
+export const asOwnComment =
+ (id: string) =>
+ <A, R>(
+ effect: Effect.Effect<A, ApiFailure, R>,
+ ): Effect.Effect<A, ApiFailure | InvalidArgument, R> =>
+ effect.pipe(
+ Effect.catchTags({
+ NotFound: () => Effect.fail(notYours(id)),
+ InvalidRequest: (error) =>
+ /could not be determined|not found/iu.test(error.message)
+ ? Effect.fail(notYours(id))
+ : Effect.fail(error),
+ }),
+ );
diff --git a/packages/cli/src/comments/read-comment-input.ts b/packages/cli/src/comments/read-comment-input.ts
new file mode 100644
index 000000000..f9c8e8f58
--- /dev/null
+++ b/packages/cli/src/comments/read-comment-input.ts
@@ -0,0 +1,82 @@
+import { Effect, Option } from "effect";
+import { Prompt } from "effect/cli";
+import { Cancelled, InvalidArgument } from "../errors/errors.js";
+import { readTextInput, stripByteOrderMark } from "../input/read-text-input.js";
+import { Output } from "../output/output.js";
+import { promptTheme } from "../prompts/prompt-theme.js";
+import { CliEnvironment } from "../services/cli-environment.js";
+import { readStream } from "../tasks/read-stdin.js";
+
+export type CommentInput = {
+ readonly words: ReadonlyArray<string>;
+ readonly file: Option.Option<string>;
+ readonly command: string;
+};
+
+const readPiped = Effect.fnUntraced(function* (command: string) {
+ const environment = yield* CliEnvironment;
+ if (environment.stdin.isTTY) {
+ return yield* new InvalidArgument({
+ message: "- reads the comment from stdin, but nothing is piped in.",
+ hint: `Pipe the text in, for example: cat notes.md | ${command} -F -`,
+ });
+ }
+ const text = yield* Effect.tryPromise({
+ try: () => readStream(process.stdin),
+ catch: () =>
+ new InvalidArgument({
+ message: "Could not read the comment from stdin.",
+ }),
+ });
+ return stripByteOrderMark(text);
+});
+
+export const readCommentInput = Effect.fnUntraced(function* (
+ input: CommentInput,
+) {
+ if (input.words.length > 0 && Option.isSome(input.file)) {
+ return yield* new InvalidArgument({
+ message: "Pass the comment as text or with --file, not both.",
+ });
+ }
+ const dash =
+ (input.words.length === 1 && input.words[0] === "-") ||
+ Option.getOrUndefined(input.file) === "-";
+ if (dash) return Option.some(yield* readPiped(input.command));
+ if (Option.isSome(input.file)) {
+ return yield* readTextInput({
+ value: Option.none(),
+ file: input.file,
+ flag: "--file",
+ });
+ }
+ return input.words.length > 0
+ ? Option.some(input.words.join(" "))
+ : Option.none<string>();
+});
+
+export const readCommentText = Effect.fnUntraced(function* (
+ input: CommentInput & { readonly prompt: string },
+) {
+ const given = yield* readCommentInput(input);
+ if (Option.isSome(given)) return given.value;
+ const environment = yield* CliEnvironment;
+ const output = yield* Output;
+ if (!environment.stdin.isTTY) return yield* readPiped(input.command);
+ if (!output.interactive) {
+ return yield* new InvalidArgument({
+ message: "Pass the new text for the comment.",
+ hint: `Pass it after the id, with -F <file>, or on stdin, for example: ${input.command} "New text".`,
+ });
+ }
+ return yield* Prompt.run(
+ Prompt.String({
+ message: input.prompt,
+ validate: (value) =>
+ value.trim() === ""
+ ? Effect.fail("Write the comment, or press Ctrl+C to cancel")
+ : Effect.succeed(value),
+ theme: promptTheme(output.ui),
+ }),
+ ).pipe(Effect.catchTag("QuitError", () => Effect.fail(new Cancelled())));
+});
diff --git a/packages/cli/src/comments/relative-time.test.ts b/packages/cli/src/comments/relative-time.test.ts
new file mode 100644
index 000000000..8eb1a6063
--- /dev/null
+++ b/packages/cli/src/comments/relative-time.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from "vite-plus/test";
+import { relativeTime } from "./relative-time.js";
+
+const now = new Date(2026, 9, 8, 15, 0, 0);
+const at = (...parts: [number, number, number, number?, number?]) =>
+ new Date(parts[0], parts[1], parts[2], parts[3] ?? 0, parts[4] ?? 0);
+
+describe("relativeTime", () => {
+ it("says just now for the last minute", () => {
+ expect(relativeTime(new Date(now.getTime() - 20_000), now)).toBe(
+ "just now",
+ );
+ });
+
+ it("treats a small clock skew into the future as just now", () => {
+ expect(relativeTime(new Date(now.getTime() + 30_000), now)).toBe(
+ "just now",
+ );
+ });
+
+ it("counts minutes within the hour", () => {
+ expect(relativeTime(at(2026, 9, 8, 14, 15), now)).toBe("45m ago");
+ });
+
+ it("counts hours earlier the same day", () => {
+ expect(relativeTime(at(2026, 9, 8, 12, 0), now)).toBe("3h ago");
+ expect(relativeTime(at(2026, 9, 8, 0, 30), now)).toBe("14h ago");
+ });
+
+ it("counts hours across midnight when it was recent", () => {
+ const early = at(2026, 9, 8, 1, 0);
+ expect(relativeTime(at(2026, 9, 7, 22, 0), early)).toBe("3h ago");
+ });
+
+ it("says Yesterday for the previous day", () => {
+ expect(relativeTime(at(2026, 9, 7, 9, 0), now)).toBe("Yesterday");
+ });
+
+ it("counts days within the week", () => {
+ expect(relativeTime(at(2026, 9, 5, 9, 0), now)).toBe("3d ago");
+ });
+
+ it("shows the date after a week", () => {
+ expect(relativeTime(at(2026, 9, 1, 9, 0), now)).toBe("Oct 1");
+ expect(relativeTime(at(2026, 0, 2, 9, 0), now)).toBe("Jan 2");
+ });
+
+ it("adds the year for other years", () => {
+ expect(relativeTime(at(2025, 9, 2, 9, 0), now)).toBe("Oct 2, 2025");
+ });
+
+ it("shows the date for times well in the future", () => {
+ expect(relativeTime(at(2026, 9, 12, 9, 0), now)).toBe("Oct 12");
+ });
+
+ it("returns an empty string for an invalid date", () => {
+ expect(relativeTime(new Date("nope"), now)).toBe("");
+ });
+});
diff --git a/packages/cli/src/comments/relative-time.ts b/packages/cli/src/comments/relative-time.ts
new file mode 100644
index 000000000..88e0fe610
--- /dev/null
+++ b/packages/cli/src/comments/relative-time.ts
@@ -0,0 +1,35 @@
+const MINUTE = 60 * 1000;
+const HOUR = 60 * MINUTE;
+const DAY = 24 * HOUR;
+const RECENT_HOURS = 6;
+
+function startOfDay(date: Date): number {
+ return new Date(
+ date.getFullYear(),
+ date.getMonth(),
+ date.getDate(),
+ ).getTime();
+}
+
+function calendarDate(date: Date, now: Date): string {
+ return date.toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ ...(date.getFullYear() === now.getFullYear() ? {} : { year: "numeric" }),
+ });
+}
+
+export function relativeTime(date: Date, now: Date): string {
+ if (Number.isNaN(date.getTime())) return "";
+ const elapsed = now.getTime() - date.getTime();
+ if (elapsed < -MINUTE) return calendarDate(date, now);
+ if (elapsed < MINUTE) return "just now";
+ if (elapsed < HOUR) return `${Math.floor(elapsed / MINUTE)}m ago`;
+ const days = Math.round((startOfDay(now) - startOfDay(date)) / DAY);
+ if (days === 0 || elapsed < RECENT_HOURS * HOUR) {
+ return `${Math.floor(elapsed / HOUR)}h ago`;
+ }
+ if (days === 1) return "Yesterday";
+ if (days < 7) return `${days}d ago`;
+ return calendarDate(date, now);
+}
diff --git a/packages/cli/src/comments/render-activity.test.ts b/packages/cli/src/comments/render-activity.test.ts
new file mode 100644
index 000000000..cbfca5952
--- /dev/null
+++ b/packages/cli/src/comments/render-activity.test.ts
@@ -0,0 +1,103 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import type { ActivityEntry } from "./describe-activity.js";
+import { renderActivity } from "./render-activity.js";
+
+const ui = (columns: number) =>
+ makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns,
+ });
+
+const now = new Date(2026, 9, 8, 15, 0);
+
+const entry = (overrides: Partial<ActivityEntry>): ActivityEntry => ({
+ id: "a1",
+ type: "created",
+ actor: { id: "u1", name: "Ada Lovelace" },
+ message: "created the task",
+ summary: "created the task",
+ detail: null,
+ createdAt: new Date(2026, 9, 5, 9, 0).toISOString(),
+ ...overrides,
+});
+
+const view = {
+ label: "KAN-3",
+ title: "Fix login redirect",
+ url: "https://kaneo.test/task/1",
+ more: false,
+ now,
+};
+
+describe("renderActivity", () => {
+ it("lists events with relative times and actors", () => {
+ expect(
+ renderActivity(ui(80), {
+ ...view,
+ entries: [
+ entry({}),
+ entry({
+ id: "a2",
+ type: "status_changed",
+ summary: "changed status from To Do to In Progress",
+ createdAt: new Date(2026, 9, 7, 9, 0).toISOString(),
+ }),
+ entry({
+ id: "a3",
+ type: "comment",
+ actor: { id: "u2", name: "Grace Hopper" },
+ summary: "commented",
+ detail: "Looks good",
+ createdAt: new Date(2026, 9, 8, 12, 0).toISOString(),
+ }),
+ entry({ id: "a4", actor: null, summary: "removed the assignee" }),
+ ],
+ }),
+ ).toEqual([
+ "",
+ " KAN-3 Fix login redirect · Activity",
+ "",
+ " 3d ago Ada Lovelace created the task",
+ " Yesterday Ada Lovelace changed status from To Do to In Progress",
+ " 3h ago Grace Hopper commented: Looks good",
+ " 3d ago Someone removed the assignee",
+ "",
+ ]);
+ });
+
+ it("truncates long events to the terminal width", () => {
+ const lines = renderActivity(ui(80), {
+ ...view,
+ entries: [
+ entry({
+ type: "comment",
+ summary: "commented",
+ detail: "x ".repeat(80),
+ }),
+ ],
+ });
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(80);
+ expect(lines[3]?.endsWith("…")).toBe(true);
+ });
+
+ it("says when older events are hidden", () => {
+ expect(
+ renderActivity(ui(80), { ...view, more: true, entries: [entry({})] })[3],
+ ).toBe(" Showing the latest event. Pass --limit to see more.");
+ });
+
+ it("handles a task without activity", () => {
+ expect(renderActivity(ui(80), { ...view, entries: [] })).toEqual([
+ "",
+ " KAN-3 Fix login redirect · Activity",
+ "",
+ " No activity yet.",
+ "",
+ ]);
+ });
+});
diff --git a/packages/cli/src/comments/render-activity.ts b/packages/cli/src/comments/render-activity.ts
new file mode 100644
index 000000000..4bdd404cd
--- /dev/null
+++ b/packages/cli/src/comments/render-activity.ts
@@ -0,0 +1,59 @@
+import { type Cell, text } from "../render/cell.js";
+import { renderTable } from "../render/table.js";
+import type { Ui } from "../render/ui.js";
+import type { ActivityEntry } from "./describe-activity.js";
+import { relativeTime } from "./relative-time.js";
+import { renderTaskHeading } from "./render-task-heading.js";
+
+export type ActivityView = {
+ readonly label: string;
+ readonly title: string;
+ readonly url: string;
+ readonly entries: ReadonlyArray<ActivityEntry>;
+ readonly more: boolean;
+ readonly now: Date;
+};
+
+export function renderActivity(ui: Ui, view: ActivityView): string[] {
+ const { theme } = ui;
+ const heading = renderTaskHeading(ui, {
+ label: view.label,
+ title: view.title,
+ url: view.url,
+ meta: "Activity",
+ });
+ if (view.entries.length === 0) {
+ return ["", heading, "", ` ${theme.muted("No activity yet.")}`, ""];
+ }
+ const rows = renderTable(
+ ui,
+ view.entries,
+ [
+ {
+ header: "When",
+ cell: (entry): Cell => [
+ text(relativeTime(new Date(entry.createdAt), view.now), theme.muted),
+ ],
+ },
+ {
+ header: "Event",
+ flex: true,
+ minWidth: 16,
+ cell: (entry): Cell => [
+ text(entry.actor?.name ?? "Someone", theme.strong),
+ text(` ${entry.summary}`),
+ ...(entry.detail ? [text(`: ${entry.detail}`, theme.muted)] : []),
+ ],
+ },
+ ],
+ { width: ui.caps.columns, indent: 2, gap: 2 },
+ );
+ const lines = ["", heading, ""];
+ if (view.more) {
+ lines.push(
+ ` ${theme.muted(`Showing the latest ${view.entries.length === 1 ? "event" : `${view.entries.length} events`}. Pass --limit to see more.`)}`,
+ "",
+ );
+ }
+ return [...lines, ...rows, ""];
+}
diff --git a/packages/cli/src/comments/render-comment-change.test.ts b/packages/cli/src/comments/render-comment-change.test.ts
new file mode 100644
index 000000000..0f1729c0d
--- /dev/null
+++ b/packages/cli/src/comments/render-comment-change.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import { renderCommentChange } from "./render-comment-change.js";
+
+const ui = (columns: number) =>
+ makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns,
+ });
+const url = "https://kaneo.test/task/1";
+
+describe("renderCommentChange", () => {
+ it("shows the verb, the task and a plain preview", () => {
+ expect(
+ renderCommentChange(ui(80), {
+ verb: "Edited",
+ label: "KAN-3",
+ url,
+ content: "**Ship** it\n\nThen celebrate",
+ }),
+ ).toEqual(["", " ✓ Edited a comment on KAN-3 · Ship it …", ""]);
+ });
+
+ it("leaves out the preview for empty content", () => {
+ expect(
+ renderCommentChange(ui(80), {
+ verb: "Deleted",
+ label: "KAN-3",
+ url,
+ content: "",
+ })[1],
+ ).toBe(" ✓ Deleted a comment on KAN-3");
+ });
+
+ it("fits the preview to the terminal width", () => {
+ const [, line = ""] = renderCommentChange(ui(50), {
+ verb: "Deleted",
+ label: "KAN-3",
+ url,
+ content: "word ".repeat(40),
+ });
+ expect(stringWidth(line)).toBeLessThanOrEqual(50);
+ expect(line.endsWith("…")).toBe(true);
+ });
+});
diff --git a/packages/cli/src/comments/render-comment-change.ts b/packages/cli/src/comments/render-comment-change.ts
new file mode 100644
index 000000000..7c4514a89
--- /dev/null
+++ b/packages/cli/src/comments/render-comment-change.ts
@@ -0,0 +1,28 @@
+import { renderCell, text } from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+import { stringWidth, truncate } from "../render/width.js";
+import { firstLine } from "../tasks/comment-text.js";
+import { inlineText } from "../tasks/plain-description.js";
+
+export type CommentChange = {
+ readonly verb: "Edited" | "Deleted";
+ readonly label: string;
+ readonly url: string;
+ readonly content: string;
+};
+
+export function renderCommentChange(ui: Ui, change: CommentChange): string[] {
+ const { theme, glyphs } = ui;
+ const id = renderCell([text(change.label, theme.strong, change.url)], ui);
+ const head = ` ${theme.success(glyphs.tick)} ${change.verb} a comment on ${id}`;
+ const preview = firstLine(change.content);
+ const line = inlineText(preview.line).trim();
+ if (line === "") return ["", head, ""];
+ const room = Math.max(ui.caps.columns - stringWidth(head) - 3, 8);
+ const shown = truncate(
+ preview.more ? `${line} ${glyphs.ellipsis}` : line,
+ room,
+ glyphs.ellipsis,
+ );
+ return ["", `${head} ${theme.muted(`${glyphs.separator} ${shown}`)}`, ""];
+}
diff --git a/packages/cli/src/comments/render-comment-list.test.ts b/packages/cli/src/comments/render-comment-list.test.ts
new file mode 100644
index 000000000..79d8d4b1c
--- /dev/null
+++ b/packages/cli/src/comments/render-comment-list.test.ts
@@ -0,0 +1,111 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import type { CommentJson } from "./comment-json.js";
+import { renderCommentList } from "./render-comment-list.js";
+
+const ui = (columns: number) =>
+ makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns,
+ });
+
+const now = new Date(2026, 9, 8, 15, 0);
+
+const comment = (overrides: Partial<CommentJson>): CommentJson => ({
+ id: "c1",
+ taskId: "t1",
+ author: { id: "u1", name: "Ada Lovelace" },
+ content: "Looks good",
+ createdAt: new Date(2026, 9, 8, 12, 0).toISOString(),
+ updatedAt: new Date(2026, 9, 8, 12, 0).toISOString(),
+ edited: false,
+ ...overrides,
+});
+
+const view = {
+ label: "KAN-3",
+ title: "Fix login redirect",
+ url: "https://kaneo.test/task/1",
+ now,
+};
+
+describe("renderCommentList", () => {
+ it("lists comments oldest first with author, time and id", () => {
+ expect(
+ renderCommentList(ui(80), {
+ ...view,
+ total: 2,
+ comments: [
+ comment({
+ id: "c1",
+ createdAt: new Date(2026, 9, 7, 9, 0).toISOString(),
+ content: "First pass is up.\n\n- check the **redirect**",
+ }),
+ comment({
+ id: "c2",
+ author: { id: "u2", name: "Grace Hopper" },
+ edited: true,
+ }),
+ ],
+ }),
+ ).toEqual([
+ "",
+ " KAN-3 Fix login redirect · 2 comments",
+ "",
+ " Ada Lovelace · Yesterday c1",
+ " First pass is up.",
+ "",
+ " • check the redirect",
+ "",
+ " Grace Hopper · 3h ago · edited c2",
+ " Looks good",
+ "",
+ ]);
+ });
+
+ it("wraps long comments to the terminal width", () => {
+ const lines = renderCommentList(ui(80), {
+ ...view,
+ total: 1,
+ comments: [comment({ content: "word ".repeat(60) })],
+ });
+ expect(lines.length).toBeGreaterThan(6);
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(80);
+ });
+
+ it("says when older comments are hidden", () => {
+ expect(
+ renderCommentList(ui(80), {
+ ...view,
+ total: 5,
+ comments: [comment({})],
+ })[3],
+ ).toBe(" Showing the latest 1 of 5. Pass --limit to see more.");
+ });
+
+ it("points to comment add when there are none", () => {
+ expect(
+ renderCommentList(ui(80), { ...view, total: 0, comments: [] }),
+ ).toEqual([
+ "",
+ " KAN-3 Fix login redirect · 0 comments",
+ "",
+ " No comments yet. Add one with kaneo comment add KAN-3",
+ "",
+ ]);
+ });
+
+ it("shows Someone for a missing author", () => {
+ expect(
+ renderCommentList(ui(80), {
+ ...view,
+ total: 1,
+ comments: [comment({ author: null })],
+ })[3],
+ ).toBe(" Someone · 3h ago c1");
+ });
+});
diff --git a/packages/cli/src/comments/render-comment-list.ts b/packages/cli/src/comments/render-comment-list.ts
new file mode 100644
index 000000000..a48b58568
--- /dev/null
+++ b/packages/cli/src/comments/render-comment-list.ts
@@ -0,0 +1,91 @@
+import type { Ui } from "../render/ui.js";
+import { stringWidth, truncate } from "../render/width.js";
+import {
+ type DescriptionLine,
+ plainDescription,
+} from "../tasks/plain-description.js";
+import type { CommentJson } from "./comment-json.js";
+import { relativeTime } from "./relative-time.js";
+import { renderTaskHeading } from "./render-task-heading.js";
+
+export type CommentListView = {
+ readonly label: string;
+ readonly title: string;
+ readonly url: string;
+ readonly comments: ReadonlyArray<CommentJson>;
+ readonly total: number;
+ readonly now: Date;
+};
+
+const INDENT = " ";
+
+function countLabel(count: number): string {
+ return count === 1 ? "1 comment" : `${count} comments`;
+}
+
+function renderCommentHeader(ui: Ui, comment: CommentJson, now: Date): string {
+ const { theme, glyphs } = ui;
+ const when = relativeTime(new Date(comment.createdAt), now);
+ const meta = [when, comment.edited ? "edited" : ""]
+ .filter((part) => part !== "")
+ .map((part) => ` ${glyphs.separator} ${part}`)
+ .join("");
+ const id = ` ${comment.id}`;
+ const room = ui.caps.columns - 2 - stringWidth(meta) - stringWidth(id);
+ const name = truncate(
+ comment.author?.name ?? "Someone",
+ Math.max(room, 8),
+ glyphs.ellipsis,
+ );
+ return ` ${theme.strong(name)}${theme.muted(meta)}${theme.muted(id)}`;
+}
+
+function renderBody(ui: Ui, content: string): string[] {
+ const { theme } = ui;
+ const body = plainDescription(content, {
+ width: ui.caps.columns - INDENT.length,
+ unicode: ui.caps.unicode,
+ });
+ if (body.lines.length === 0) return [`${INDENT}${theme.muted("(empty)")}`];
+ const style = (line: DescriptionLine) =>
+ line.kind === "heading"
+ ? theme.strong(line.text)
+ : line.kind === "muted"
+ ? theme.muted(line.text)
+ : line.text;
+ return body.lines.map((line) => (line.text ? `${INDENT}${style(line)}` : ""));
+}
+
+export function renderCommentList(ui: Ui, view: CommentListView): string[] {
+ const { theme } = ui;
+ const heading = renderTaskHeading(ui, {
+ label: view.label,
+ title: view.title,
+ url: view.url,
+ meta: countLabel(view.total),
+ });
+ if (view.comments.length === 0) {
+ return [
+ "",
+ heading,
+ "",
+ ` ${theme.muted("No comments yet. Add one with")} ${theme.strong(`kaneo comment add ${view.label}`)}`,
+ "",
+ ];
+ }
+ const lines = ["", heading, ""];
+ if (view.total > view.comments.length) {
+ lines.push(
+ ` ${theme.muted(`Showing the latest ${view.comments.length} of ${view.total}. Pass --limit to see more.`)}`,
+ "",
+ );
+ }
+ for (const comment of view.comments) {
+ lines.push(
+ renderCommentHeader(ui, comment, view.now),
+ ...renderBody(ui, comment.content),
+ "",
+ );
+ }
+ return lines;
+}
diff --git a/packages/cli/src/comments/render-task-heading.ts b/packages/cli/src/comments/render-task-heading.ts
new file mode 100644
index 000000000..6e73ffc28
--- /dev/null
+++ b/packages/cli/src/comments/render-task-heading.ts
@@ -0,0 +1,20 @@
+import { renderCell, text } from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+import { stringWidth, truncate } from "../render/width.js";
+
+export type TaskHeading = {
+ readonly label: string;
+ readonly title: string;
+ readonly url: string;
+ readonly meta?: string;
+};
+
+export function renderTaskHeading(ui: Ui, heading: TaskHeading): string {
+ const { theme, glyphs } = ui;
+ const id = renderCell([text(heading.label, theme.muted, heading.url)], ui);
+ const meta = heading.meta ? ` ${glyphs.separator} ${heading.meta}` : "";
+ const room =
+ ui.caps.columns - 3 - stringWidth(heading.label) - stringWidth(meta);
+ const title = truncate(heading.title, Math.max(room, 8), glyphs.ellipsis);
+ return ` ${id} ${theme.strong(title)}${theme.muted(meta)}`;
+}
diff --git a/packages/cli/src/config/config-path.ts b/packages/cli/src/config/config-path.ts
new file mode 100644
index 000000000..1972fa21a
--- /dev/null
+++ b/packages/cli/src/config/config-path.ts
@@ -0,0 +1,8 @@
+import { join } from "node:path";
+import type { Environment } from "../render/capabilities.js";
+
+export function configPath(env: Environment, home: string): string {
+ if (env.KANEO_CONFIG) return env.KANEO_CONFIG;
+ const base = env.XDG_CONFIG_HOME || join(home, ".config");
+ return join(base, "kaneo", "config.json");
+}
diff --git a/packages/cli/src/config/config-store.test.ts b/packages/cli/src/config/config-store.test.ts
new file mode 100644
index 000000000..ee4beb3ba
--- /dev/null
+++ b/packages/cli/src/config/config-store.test.ts
@@ -0,0 +1,57 @@
+import { mkdtemp, readFile, stat, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { Effect, Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { configPath } from "./config-path.js";
+import { makeConfigStore } from "./config-store.js";
+import { emptyConfig, withProfile } from "./format.js";
+
+async function tempPath() {
+ const directory = await mkdtemp(join(tmpdir(), "kaneo-cli-"));
+ return join(directory, "kaneo", "config.json");
+}
+
+describe("configPath", () => {
+ it("honors KANEO_CONFIG, then XDG_CONFIG_HOME, then ~/.config", () => {
+ expect(configPath({ KANEO_CONFIG: "/x/c.json" }, "/home/a")).toBe(
+ "/x/c.json",
+ );
+ expect(configPath({ XDG_CONFIG_HOME: "/xdg" }, "/home/a")).toBe(
+ "/xdg/kaneo/config.json",
+ );
+ expect(configPath({}, "/home/a")).toBe("/home/a/.config/kaneo/config.json");
+ });
+});
+
+describe("makeConfigStore", () => {
+ it("returns an empty config when the file is missing", async () => {
+ const store = makeConfigStore(await tempPath());
+ expect(await Effect.runPromise(store.load)).toEqual(emptyConfig);
+ });
+
+ it("writes a private file in a private directory", async () => {
+ const path = await tempPath();
+ const store = makeConfigStore(path);
+ const config = withProfile(emptyConfig, "default", () => ({
+ apiUrl: "https://cloud.kaneo.app",
+ token: "secret",
+ }));
+ await Effect.runPromise(store.save(config));
+ expect((await stat(path)).mode & 0o777).toBe(0o600);
+ expect((await stat(join(path, ".."))).mode & 0o777).toBe(0o700);
+ expect(await Effect.runPromise(store.load)).toEqual(config);
+ });
+
+ it("never overwrites a file from another kaneo CLI", async () => {
+ const path = await tempPath();
+ const store = makeConfigStore(path);
+ await Effect.runPromise(store.save(emptyConfig));
+ await writeFile(path, '{"apiKey":"community"}');
+ const result = await Effect.runPromise(
+ Effect.result(store.save(emptyConfig)),
+ );
+ expect(Result.isFailure(result) && result.failure.reason).toBe("foreign");
+ expect(await readFile(path, "utf8")).toBe('{"apiKey":"community"}');
+ });
+});
diff --git a/packages/cli/src/config/config-store.ts b/packages/cli/src/config/config-store.ts
new file mode 100644
index 000000000..2c988c55e
--- /dev/null
+++ b/packages/cli/src/config/config-store.ts
@@ -0,0 +1,89 @@
+import { chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import { dirname } from "node:path";
+import { Context, Effect, Layer } from "effect";
+import { ConfigUnreadable } from "../errors/errors.js";
+import { CliEnvironment } from "../services/cli-environment.js";
+import { configPath } from "./config-path.js";
+import {
+ type ConfigFile,
+ emptyConfig,
+ parseConfig,
+ serializeConfig,
+} from "./format.js";
+
+export type ConfigStoreShape = {
+ readonly path: string;
+ readonly load: Effect.Effect<ConfigFile, ConfigUnreadable>;
+ readonly save: (config: ConfigFile) => Effect.Effect<void, ConfigUnreadable>;
+};
+
+export class ConfigStore extends Context.Service<
+ ConfigStore,
+ ConfigStoreShape
+>()("kaneo/ConfigStore") {}
+
+function isMissing(cause: unknown): boolean {
+ return (cause as { code?: unknown } | null)?.code === "ENOENT";
+}
+
+function ioError(path: string, cause: unknown): ConfigUnreadable {
+ return new ConfigUnreadable({
+ path,
+ reason: "io",
+ detail: cause instanceof Error ? cause.message : String(cause),
+ });
+}
+
+export function makeConfigStore(path: string): ConfigStoreShape {
+ const load = Effect.tryPromise({
+ try: () => readFile(path, "utf8"),
+ catch: (cause) => cause,
+ }).pipe(
+ Effect.matchEffect({
+ onFailure: (cause) =>
+ isMissing(cause)
+ ? Effect.succeed(emptyConfig)
+ : Effect.fail(ioError(path, cause)),
+ onSuccess: (text) => {
+ const parsed = parseConfig(text);
+ if (parsed.status === "ok") return Effect.succeed(parsed.config);
+ return Effect.fail(
+ new ConfigUnreadable({
+ path,
+ reason: parsed.status,
+ detail:
+ parsed.status === "invalid" ? parsed.detail : "unknown format",
+ }),
+ );
+ },
+ }),
+ );
+
+ const save = (config: ConfigFile) =>
+ load.pipe(
+ Effect.andThen(
+ Effect.tryPromise({
+ try: async () => {
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
+ const temporary = `${path}.${process.pid}.tmp`;
+ await writeFile(temporary, serializeConfig(config), {
+ mode: 0o600,
+ });
+ await chmod(temporary, 0o600);
+ await rename(temporary, path);
+ },
+ catch: (cause) => ioError(path, cause),
+ }),
+ ),
+ );
+
+ return { path, load, save };
+}
+
+export const ConfigStoreLive = Layer.effect(
+ ConfigStore,
+ Effect.gen(function* () {
+ const environment = yield* CliEnvironment;
+ return makeConfigStore(configPath(environment.env, environment.home));
+ }),
+);
diff --git a/packages/cli/src/config/format.test.ts b/packages/cli/src/config/format.test.ts
new file mode 100644
index 000000000..e9ec5519f
--- /dev/null
+++ b/packages/cli/src/config/format.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from "vite-plus/test";
+import {
+ emptyConfig,
+ parseConfig,
+ serializeConfig,
+ withProfile,
+} from "./format.js";
+
+describe("parseConfig", () => {
+ it("reads the official format", () => {
+ const config = withProfile(emptyConfig, "default", () => ({
+ apiUrl: "https://cloud.kaneo.app",
+ token: "secret",
+ }));
+ expect(parseConfig(serializeConfig(config))).toEqual({
+ status: "ok",
+ config,
+ });
+ });
+
+ it("treats other formats as foreign", () => {
+ expect(parseConfig('{"apiKey":"x","workspace":"y"}')).toEqual({
+ status: "foreign",
+ });
+ expect(parseConfig("api_key = x")).toEqual({ status: "foreign" });
+ expect(parseConfig("[]")).toEqual({ status: "foreign" });
+ });
+
+ it("reports a broken official file as invalid", () => {
+ const parsed = parseConfig(
+ '{"kind":"kaneo-cli","version":1,"profiles":{}}',
+ );
+ expect(parsed.status).toBe("invalid");
+ });
+});
+
+describe("withProfile", () => {
+ it("updates one profile and makes it active", () => {
+ const first = withProfile(emptyConfig, "work", () => ({
+ apiUrl: "https://a.test",
+ }));
+ const second = withProfile(first, "home", () => ({
+ apiUrl: "https://b.test",
+ }));
+ expect(second.activeProfile).toBe("home");
+ expect(Object.keys(second.profiles)).toEqual(["work", "home"]);
+ });
+});
diff --git a/packages/cli/src/config/format.ts b/packages/cli/src/config/format.ts
new file mode 100644
index 000000000..dceb2b1ad
--- /dev/null
+++ b/packages/cli/src/config/format.ts
@@ -0,0 +1,81 @@
+import { Result, Schema } from "effect";
+
+export const ProfileSchema = Schema.Struct({
+ apiUrl: Schema.String,
+ webUrl: Schema.optionalKey(Schema.String),
+ token: Schema.optionalKey(Schema.String),
+ workspaceId: Schema.optionalKey(Schema.String),
+ user: Schema.optionalKey(
+ Schema.Struct({
+ id: Schema.String,
+ name: Schema.String,
+ email: Schema.String,
+ }),
+ ),
+});
+
+export type Profile = typeof ProfileSchema.Type;
+
+export const ConfigFileSchema = Schema.Struct({
+ kind: Schema.Literal("kaneo-cli"),
+ version: Schema.Literal(1),
+ activeProfile: Schema.String,
+ profiles: Schema.Record(Schema.String, ProfileSchema),
+});
+
+export type ConfigFile = typeof ConfigFileSchema.Type;
+
+export const DEFAULT_PROFILE = "default";
+
+export const emptyConfig: ConfigFile = {
+ kind: "kaneo-cli",
+ version: 1,
+ activeProfile: DEFAULT_PROFILE,
+ profiles: {},
+};
+
+export type ParsedConfig =
+ | { readonly status: "ok"; readonly config: ConfigFile }
+ | { readonly status: "foreign" }
+ | { readonly status: "invalid"; readonly detail: string };
+
+const decodeConfig = Schema.decodeUnknownResult(ConfigFileSchema);
+
+export function parseConfig(text: string): ParsedConfig {
+ let raw: unknown;
+ try {
+ raw = JSON.parse(text);
+ } catch {
+ return { status: "foreign" };
+ }
+ if (
+ typeof raw !== "object" ||
+ raw === null ||
+ (raw as { kind?: unknown }).kind !== "kaneo-cli"
+ ) {
+ return { status: "foreign" };
+ }
+ const decoded = decodeConfig(raw);
+ return Result.isSuccess(decoded)
+ ? { status: "ok", config: decoded.success }
+ : {
+ status: "invalid",
+ detail: decoded.failure.message.split("\n")[0] ?? "",
+ };
+}
+
+export function serializeConfig(config: ConfigFile): string {
+ return `${JSON.stringify(config, null, 2)}\n`;
+}
+
+export function withProfile(
+ config: ConfigFile,
+ name: string,
+ update: (profile: Profile | undefined) => Profile,
+): ConfigFile {
+ return {
+ ...config,
+ activeProfile: name,
+ profiles: { ...config.profiles, [name]: update(config.profiles[name]) },
+ };
+}
diff --git a/packages/cli/src/config/repo-config.test.ts b/packages/cli/src/config/repo-config.test.ts
new file mode 100644
index 000000000..9e992dc75
--- /dev/null
+++ b/packages/cli/src/config/repo-config.test.ts
@@ -0,0 +1,103 @@
+import { describe, expect, it } from "vite-plus/test";
+import {
+ findRepoConfig,
+ hasRepoLink,
+ linkFilePath,
+ mergeRepoLink,
+ parseRepoConfigObject,
+ removeRepoLink,
+ serializeRepoConfig,
+} from "./repo-config.js";
+
+describe("findRepoConfig", () => {
+ const files: Record<string, string> = {
+ "/work/app/.kaneo.json": '{"workspace":"ws_1","project":"KAN"}',
+ "/broken/.kaneo.json": "{nope",
+ };
+ const read = (path: string) => files[path];
+
+ it("walks up from the working directory", () => {
+ expect(findRepoConfig("/work/app/src/deep", read)).toEqual({
+ path: "/work/app/.kaneo.json",
+ workspace: "ws_1",
+ project: "KAN",
+ });
+ });
+
+ it("returns nothing when no file exists or it is not JSON", () => {
+ expect(findRepoConfig("/elsewhere/x", read)).toBeUndefined();
+ expect(findRepoConfig("/broken/a", read)).toBeUndefined();
+ });
+});
+
+describe("linkFilePath", () => {
+ const existing = (paths: ReadonlyArray<string>) => (path: string) =>
+ paths.includes(path);
+
+ it("writes at the git repository root", () => {
+ expect(linkFilePath("/repo/packages/app", existing(["/repo/.git"]))).toBe(
+ "/repo/.kaneo.json",
+ );
+ });
+
+ it("updates a closer .kaneo.json inside the repository", () => {
+ expect(
+ linkFilePath(
+ "/repo/packages/app/src",
+ existing(["/repo/.git", "/repo/packages/app/.kaneo.json"]),
+ ),
+ ).toBe("/repo/packages/app/.kaneo.json");
+ });
+
+ it("uses the current directory outside a repository", () => {
+ expect(linkFilePath("/tmp/scratch", existing(["/tmp/.kaneo.json"]))).toBe(
+ "/tmp/scratch/.kaneo.json",
+ );
+ });
+});
+
+describe("parseRepoConfigObject", () => {
+ it("distinguishes missing, valid and invalid files", () => {
+ expect(parseRepoConfigObject(undefined)).toEqual({ kind: "missing" });
+ expect(parseRepoConfigObject("")).toEqual({ kind: "ok", value: {} });
+ expect(parseRepoConfigObject('{"a":1}')).toEqual({
+ kind: "ok",
+ value: { a: 1 },
+ });
+ expect(parseRepoConfigObject("[1]")).toEqual({ kind: "invalid" });
+ expect(parseRepoConfigObject("{nope")).toEqual({ kind: "invalid" });
+ });
+});
+
+describe("mergeRepoLink", () => {
+ it("keeps keys written by other tools and their order", () => {
+ const merged = mergeRepoLink(
+ { project: "OLD", board: "main", workspace: "ws_old" },
+ { workspace: "ws_1", project: "KAN" },
+ );
+ expect(serializeRepoConfig(merged)).toBe(
+ '{\n "project": "KAN",\n "board": "main",\n "workspace": "ws_1"\n}\n',
+ );
+ });
+
+ it("creates a new file with only the workspace and project", () => {
+ expect(
+ mergeRepoLink(undefined, { workspace: "ws_1", project: "KAN" }),
+ ).toEqual({ workspace: "ws_1", project: "KAN" });
+ });
+});
+
+describe("removeRepoLink", () => {
+ it("removes only the link keys", () => {
+ const value = { workspace: "ws_1", project: "KAN", board: "main" };
+ expect(hasRepoLink(value)).toBe(true);
+ expect(removeRepoLink(value)).toEqual({ board: "main" });
+ });
+
+ it("returns nothing when no other keys remain", () => {
+ expect(
+ removeRepoLink({ workspace: "ws_1", project: "KAN" }),
+ ).toBeUndefined();
+ expect(hasRepoLink({ board: "main" })).toBe(false);
+ });
+});
diff --git a/packages/cli/src/config/repo-config.ts b/packages/cli/src/config/repo-config.ts
new file mode 100644
index 000000000..cf793d015
--- /dev/null
+++ b/packages/cli/src/config/repo-config.ts
@@ -0,0 +1,186 @@
+import { existsSync, readFileSync } from "node:fs";
+import { readFile, rm, writeFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { Effect } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+
+export const REPO_CONFIG_FILE = ".kaneo.json";
+
+export type RepoConfig = {
+ readonly path: string;
+ readonly workspace: string | undefined;
+ readonly project: string | undefined;
+};
+
+export type RepoLink = {
+ readonly workspace: string;
+ readonly project: string;
+};
+
+export type RepoConfigObject = Readonly<Record<string, unknown>>;
+
+export type ParsedRepoConfig =
+ | { readonly kind: "missing" }
+ | { readonly kind: "ok"; readonly value: RepoConfigObject }
+ | { readonly kind: "invalid" };
+
+function readText(path: string): string | undefined {
+ try {
+ return readFileSync(path, "utf8");
+ } catch {
+ return undefined;
+ }
+}
+
+function stringField(value: unknown, key: string): string | undefined {
+ const field = (value as Record<string, unknown> | null)?.[key];
+ return typeof field === "string" && field.trim() !== ""
+ ? field.trim()
+ : undefined;
+}
+
+export function findRepoConfig(
+ cwd: string,
+ read: (path: string) => string | undefined = readText,
+): RepoConfig | undefined {
+ let directory = cwd;
+ for (;;) {
+ const path = join(directory, REPO_CONFIG_FILE);
+ const text = read(path);
+ if (text !== undefined) {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ return undefined;
+ }
+ return {
+ path,
+ workspace: stringField(parsed, "workspace"),
+ project: stringField(parsed, "project"),
+ };
+ }
+ const parent = dirname(directory);
+ if (parent === directory) return undefined;
+ directory = parent;
+ }
+}
+
+export function findRepoRoot(
+ cwd: string,
+ exists: (path: string) => boolean = existsSync,
+): string | undefined {
+ let directory = cwd;
+ for (;;) {
+ if (exists(join(directory, ".git"))) return directory;
+ const parent = dirname(directory);
+ if (parent === directory) return undefined;
+ directory = parent;
+ }
+}
+
+export function linkFilePath(
+ cwd: string,
+ exists: (path: string) => boolean = existsSync,
+): string {
+ const root = findRepoRoot(cwd, exists);
+ if (root === undefined) return join(cwd, REPO_CONFIG_FILE);
+ let directory = cwd;
+ while (directory !== root) {
+ const candidate = join(directory, REPO_CONFIG_FILE);
+ if (exists(candidate)) return candidate;
+ const parent = dirname(directory);
+ if (parent === directory) break;
+ directory = parent;
+ }
+ return join(root, REPO_CONFIG_FILE);
+}
+
+export function parseRepoConfigObject(
+ text: string | undefined,
+): ParsedRepoConfig {
+ if (text === undefined) return { kind: "missing" };
+ if (text.trim() === "") return { kind: "ok", value: {} };
+ try {
+ const parsed: unknown = JSON.parse(text);
+ return typeof parsed === "object" &&
+ parsed !== null &&
+ !Array.isArray(parsed)
+ ? { kind: "ok", value: parsed as RepoConfigObject }
+ : { kind: "invalid" };
+ } catch {
+ return { kind: "invalid" };
+ }
+}
+
+export function mergeRepoLink(
+ existing: RepoConfigObject | undefined,
+ link: RepoLink,
+): RepoConfigObject {
+ return { ...existing, workspace: link.workspace, project: link.project };
+}
+
+export function hasRepoLink(value: RepoConfigObject): boolean {
+ return "workspace" in value || "project" in value;
+}
+
+export function removeRepoLink(
+ existing: RepoConfigObject,
+): RepoConfigObject | undefined {
+ const { workspace: _workspace, project: _project, ...rest } = existing;
+ return Object.keys(rest).length > 0 ? rest : undefined;
+}
+
+export function serializeRepoConfig(value: RepoConfigObject): string {
+ return `${JSON.stringify(value, null, 2)}\n`;
+}
+
+function isMissing(cause: unknown): boolean {
+ return (cause as { code?: unknown } | null)?.code === "ENOENT";
+}
+
+export const readRepoConfigObject = Effect.fnUntraced(function* (path: string) {
+ const text = yield* Effect.tryPromise({
+ try: () => readFile(path, "utf8"),
+ catch: (cause) => cause,
+ }).pipe(
+ Effect.catch((cause) =>
+ isMissing(cause)
+ ? Effect.succeed(undefined)
+ : Effect.fail(
+ new InvalidArgument({
+ message: `Could not read ${path}.`,
+ hint: "Check that the file is readable.",
+ }),
+ ),
+ ),
+ );
+ const parsed = parseRepoConfigObject(text);
+ if (parsed.kind === "invalid") {
+ return yield* new InvalidArgument({
+ message: `${path} is not a JSON object, so it was left untouched.`,
+ hint: "Fix or delete the file, then run this again.",
+ });
+ }
+ return parsed.kind === "ok" ? parsed.value : undefined;
+});
+
+export const writeRepoConfig = (path: string, value: RepoConfigObject) =>
+ Effect.tryPromise({
+ try: () => writeFile(path, serializeRepoConfig(value), "utf8"),
+ catch: () =>
+ new InvalidArgument({
+ message: `Could not write ${path}.`,
+ hint: "Check that the directory is writable.",
+ }),
+ });
+
+export const deleteRepoConfig = (path: string) =>
+ Effect.tryPromise({
+ try: () => rm(path, { force: true }),
+ catch: () =>
+ new InvalidArgument({
+ message: `Could not delete ${path}.`,
+ hint: "Check that the directory is writable.",
+ }),
+ });
diff --git a/packages/cli/src/context/context-report.ts b/packages/cli/src/context/context-report.ts
new file mode 100644
index 000000000..9eae2d3fa
--- /dev/null
+++ b/packages/cli/src/context/context-report.ts
@@ -0,0 +1,37 @@
+import type { Capabilities } from "../render/capabilities.js";
+import type { OutputMode } from "../output/output-mode.js";
+import type { OutputSource } from "./output-provenance.js";
+import type { Provenance } from "./provenance.js";
+
+export type ConfigStatus = "ok" | "missing" | "foreign" | "invalid" | "io";
+
+export type ContextReport = {
+ readonly server: Provenance["server"];
+ readonly web: Provenance["web"];
+ readonly profile: Provenance["profile"];
+ readonly auth: Provenance["auth"] & { readonly error: string | null };
+ readonly user: {
+ readonly id: string;
+ readonly name: string;
+ readonly email: string;
+ } | null;
+ readonly workspace: Provenance["workspace"] & {
+ readonly name: string | null;
+ };
+ readonly project: Provenance["project"] & {
+ readonly id: string | null;
+ readonly key: string | null;
+ readonly name: string | null;
+ };
+ readonly config: { readonly path: string; readonly status: ConfigStatus };
+ readonly output: {
+ readonly mode: OutputMode;
+ readonly source: OutputSource;
+ readonly jq: string | null;
+ readonly interactive: boolean;
+ readonly stdinIsTTY: boolean;
+ readonly stdoutIsTTY: boolean;
+ readonly stderrIsTTY: boolean;
+ readonly terminal: Capabilities;
+ };
+};
diff --git a/packages/cli/src/context/output-provenance.ts b/packages/cli/src/context/output-provenance.ts
new file mode 100644
index 000000000..2c5241a8f
--- /dev/null
+++ b/packages/cli/src/context/output-provenance.ts
@@ -0,0 +1,20 @@
+import type { OutputMode } from "../output/output-mode.js";
+import type { Environment } from "../render/capabilities.js";
+
+export type OutputSource = "flag" | "env" | "terminal" | "pipe";
+
+export function outputProvenance(input: {
+ readonly json: boolean;
+ readonly human: boolean;
+ readonly env: Environment;
+ readonly stdoutIsTTY: boolean;
+}): { readonly mode: OutputMode; readonly source: OutputSource } {
+ if (input.json) return { mode: "json", source: "flag" };
+ if (input.human) return { mode: "human", source: "flag" };
+ if (input.env.KANEO_JSON === "true" || input.env.KANEO_JSON === "1") {
+ return { mode: "json", source: "env" };
+ }
+ return input.stdoutIsTTY
+ ? { mode: "human", source: "terminal" }
+ : { mode: "json", source: "pipe" };
+}
diff --git a/packages/cli/src/context/provenance.test.ts b/packages/cli/src/context/provenance.test.ts
new file mode 100644
index 000000000..27211e03d
--- /dev/null
+++ b/packages/cli/src/context/provenance.test.ts
@@ -0,0 +1,172 @@
+import { Option, Redacted } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { emptyConfig, withProfile } from "../config/format.js";
+import type { SessionInputs } from "../services/session.js";
+import { outputProvenance } from "./output-provenance.js";
+import { buildProvenance, fingerprint } from "./provenance.js";
+
+const config = withProfile(emptyConfig, "work", () => ({
+ apiUrl: "https://kaneo.example.com",
+ webUrl: "https://app.example.com",
+ token: "stored-session-token-1234",
+ workspaceId: "ws_profile",
+}));
+
+function inputs(overrides: Partial<SessionInputs> = {}): SessionInputs {
+ return {
+ flags: {
+ token: Option.none(),
+ apiUrl: Option.none(),
+ workspace: Option.none(),
+ profile: Option.none(),
+ },
+ env: {},
+ config,
+ configProblem: Option.none(),
+ repo: undefined,
+ ...overrides,
+ };
+}
+
+describe("buildProvenance", () => {
+ it("attributes everything to the active profile by default", () => {
+ expect(buildProvenance(inputs())).toEqual({
+ server: { url: "https://kaneo.example.com", source: "profile" },
+ web: { url: "https://app.example.com", source: "profile" },
+ profile: {
+ name: "work",
+ source: "config",
+ stored: true,
+ matchesServer: true,
+ },
+ auth: { method: "login", source: "profile", fingerprint: "1234" },
+ workspace: { id: "ws_profile", source: "profile", path: null },
+ project: { ref: null, source: "none", path: null },
+ });
+ });
+
+ it("reports flags and environment variables over the profile", () => {
+ const provenance = buildProvenance(
+ inputs({
+ flags: {
+ token: Option.some(Redacted.make("flag-token-abcdefgh")),
+ apiUrl: Option.some("http://localhost:1337/"),
+ workspace: Option.some("ws_flag"),
+ profile: Option.none(),
+ },
+ env: { KANEO_PROFILE: "work", KANEO_WEB_URL: "http://localhost:5173" },
+ }),
+ );
+ expect(provenance.server).toEqual({
+ url: "http://localhost:1337",
+ source: "flag",
+ });
+ expect(provenance.web).toEqual({
+ url: "http://localhost:5173",
+ source: "env",
+ });
+ expect(provenance.profile).toEqual({
+ name: "work",
+ source: "env",
+ stored: true,
+ matchesServer: false,
+ });
+ expect(provenance.auth).toEqual({
+ method: "token",
+ source: "flag",
+ fingerprint: "efgh",
+ });
+ expect(provenance.workspace).toEqual({
+ id: "ws_flag",
+ source: "flag",
+ path: null,
+ });
+ });
+
+ it("points at .kaneo.json for the repository link", () => {
+ const provenance = buildProvenance(
+ inputs({
+ env: { KANEO_API_KEY: "short" },
+ repo: {
+ path: "/repo/.kaneo.json",
+ workspace: "ws_repo",
+ project: "KAN",
+ },
+ }),
+ );
+ expect(provenance.auth).toEqual({
+ method: "api-key",
+ source: "env",
+ fingerprint: null,
+ });
+ expect(provenance.workspace).toEqual({
+ id: "ws_repo",
+ source: "repo",
+ path: "/repo/.kaneo.json",
+ });
+ expect(provenance.project).toEqual({
+ ref: "KAN",
+ source: "repo",
+ path: "/repo/.kaneo.json",
+ });
+ expect(
+ buildProvenance(inputs({ env: { KANEO_PROJECT: "MOB" } })).project,
+ ).toEqual({ ref: "MOB", source: "env", path: null });
+ });
+
+ it("works signed out with no config file", () => {
+ const provenance = buildProvenance(inputs({ config: emptyConfig }));
+ expect(provenance.server).toEqual({
+ url: "https://cloud.kaneo.app",
+ source: "default",
+ });
+ expect(provenance.web.source).toBe("server");
+ expect(provenance.profile).toEqual({
+ name: "default",
+ source: "default",
+ stored: false,
+ matchesServer: false,
+ });
+ expect(provenance.auth).toEqual({
+ method: null,
+ source: "none",
+ fingerprint: null,
+ });
+ expect(provenance.workspace.source).toBe("none");
+ });
+});
+
+describe("fingerprint", () => {
+ it("shows only the last four characters of long secrets", () => {
+ expect(fingerprint("kaneo_live_abcdef123456")).toBe("3456");
+ expect(fingerprint("short")).toBeNull();
+ });
+});
+
+describe("outputProvenance", () => {
+ it("follows the same order as the output mode", () => {
+ const base = { json: false, human: false, env: {}, stdoutIsTTY: true };
+ expect(outputProvenance({ ...base, json: true, human: true })).toEqual({
+ mode: "json",
+ source: "flag",
+ });
+ expect(
+ outputProvenance({ ...base, human: true, stdoutIsTTY: false }),
+ ).toEqual({
+ mode: "human",
+ source: "flag",
+ });
+ expect(outputProvenance({ ...base, env: { KANEO_JSON: "1" } })).toEqual({
+ mode: "json",
+ source: "env",
+ });
+ expect(outputProvenance(base)).toEqual({
+ mode: "human",
+ source: "terminal",
+ });
+ expect(outputProvenance({ ...base, stdoutIsTTY: false })).toEqual({
+ mode: "json",
+ source: "pipe",
+ });
+ });
+});
diff --git a/packages/cli/src/context/provenance.ts b/packages/cli/src/context/provenance.ts
new file mode 100644
index 000000000..847600219
--- /dev/null
+++ b/packages/cli/src/context/provenance.ts
@@ -0,0 +1,117 @@
+import { normalizeBaseUrl } from "@kaneo/mcp/normalize-base-url";
+import { Option, Redacted } from "effect";
+import { resolveSession, type SessionInputs } from "../services/session.js";
+
+export type ServerSource = "flag" | "env" | "profile" | "default";
+export type WebSource = "env" | "profile" | "server";
+export type ProfileSource = "flag" | "env" | "config" | "default";
+export type AuthSource = "flag" | "env" | "profile" | "none";
+export type WorkspaceSource = "flag" | "env" | "repo" | "profile" | "none";
+export type ProjectSource = "env" | "repo" | "none";
+
+export type Provenance = {
+ readonly server: { readonly url: string; readonly source: ServerSource };
+ readonly web: { readonly url: string; readonly source: WebSource };
+ readonly profile: {
+ readonly name: string;
+ readonly source: ProfileSource;
+ readonly stored: boolean;
+ readonly matchesServer: boolean;
+ };
+ readonly auth: {
+ readonly method: "token" | "api-key" | "login" | null;
+ readonly source: AuthSource;
+ readonly fingerprint: string | null;
+ };
+ readonly workspace: {
+ readonly id: string | null;
+ readonly source: WorkspaceSource;
+ readonly path: string | null;
+ };
+ readonly project: {
+ readonly ref: string | null;
+ readonly source: ProjectSource;
+ readonly path: string | null;
+ };
+};
+
+function filled(value: string | undefined): boolean {
+ return value !== undefined && value.trim() !== "";
+}
+
+export function fingerprint(token: string): string | null {
+ return token.length >= 12 ? token.slice(-4) : null;
+}
+
+const AUTH_METHODS = {
+ flag: "token",
+ env: "api-key",
+ profile: "login",
+} as const;
+
+export function buildProvenance(inputs: SessionInputs): Provenance {
+ const session = resolveSession(inputs);
+ const { flags, env, config, repo } = inputs;
+ const stored = config.profiles[session.profileName];
+
+ const profileSource: ProfileSource = Option.isSome(flags.profile)
+ ? "flag"
+ : filled(env.KANEO_PROFILE)
+ ? "env"
+ : Object.keys(config.profiles).length > 0 && filled(config.activeProfile)
+ ? "config"
+ : "default";
+
+ const serverSource: ServerSource = Option.isSome(flags.apiUrl)
+ ? "flag"
+ : filled(env.KANEO_API_URL)
+ ? "env"
+ : stored
+ ? "profile"
+ : "default";
+
+ const webSource: WebSource = env.KANEO_WEB_URL
+ ? "env"
+ : session.profile?.webUrl
+ ? "profile"
+ : "server";
+
+ const credentials = Option.getOrUndefined(session.credentials);
+ const workspace = Option.getOrUndefined(session.workspace);
+ const project = Option.getOrUndefined(session.project);
+ const projectFromEnv = project?.source === "KANEO_PROJECT";
+
+ return {
+ server: { url: session.apiUrl, source: serverSource },
+ web: { url: session.webUrl, source: webSource },
+ profile: {
+ name: session.profileName,
+ source: profileSource,
+ stored: stored !== undefined,
+ matchesServer:
+ stored !== undefined &&
+ normalizeBaseUrl(stored.apiUrl) === session.apiUrl,
+ },
+ auth: credentials
+ ? {
+ method: AUTH_METHODS[credentials.source],
+ source: credentials.source,
+ fingerprint: fingerprint(Redacted.value(credentials.token)),
+ }
+ : { method: null, source: "none", fingerprint: null },
+ workspace: workspace
+ ? {
+ id: workspace.id,
+ source: workspace.source,
+ path: workspace.source === "repo" ? (repo?.path ?? null) : null,
+ }
+ : { id: null, source: "none", path: null },
+ project: project
+ ? {
+ ref: project.ref,
+ source: projectFromEnv ? "env" : "repo",
+ path: projectFromEnv ? null : (repo?.path ?? null),
+ }
+ : { ref: null, source: "none", path: null },
+ };
+}
diff --git a/packages/cli/src/context/render-context.test.ts b/packages/cli/src/context/render-context.test.ts
new file mode 100644
index 000000000..61d3825fa
--- /dev/null
+++ b/packages/cli/src/context/render-context.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import type { ContextReport } from "./context-report.js";
+import { renderContext } from "./render-context.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+const report: ContextReport = {
+ server: { url: "http://localhost:1337", source: "env" },
+ web: { url: "http://localhost:1337", source: "server" },
+ profile: { name: "work", source: "flag", stored: true, matchesServer: true },
+ auth: { method: "api-key", source: "env", fingerprint: "a1b2", error: null },
+ user: { id: "u1", name: "Ada Lovelace", email: "[email protected]" },
+ workspace: {
+ id: "ws_1",
+ source: "repo",
+ path: "/repo/.kaneo.json",
+ name: "Acme Studio",
+ },
+ project: {
+ ref: "KAN",
+ source: "env",
+ path: null,
+ id: "p1",
+ key: "KAN",
+ name: "Kaneo Web",
+ },
+ config: { path: "/home/ada/.config/kaneo/config.json", status: "missing" },
+ output: {
+ mode: "human",
+ source: "terminal",
+ jq: null,
+ interactive: true,
+ stdinIsTTY: true,
+ stdoutIsTTY: true,
+ stderrIsTTY: true,
+ terminal: {
+ color: 3,
+ unicode: true,
+ hyperlinks: true,
+ animate: true,
+ columns: 80,
+ },
+ },
+};
+
+describe("renderContext", () => {
+ it("shows each value with where it came from, never the secret", () => {
+ expect(renderContext(ui, report)).toEqual([
+ "",
+ " Server http://localhost:1337 KANEO_API_URL",
+ " Web app http://localhost:1337 same as the server",
+ " Profile work --profile",
+ " Auth API key …a1b2 KANEO_API_KEY",
+ " User Ada Lovelace · [email protected]",
+ " Workspace Acme Studio ws_1 /repo/.kaneo.json",
+ " Project Kaneo Web KAN KANEO_PROJECT",
+ " Config /home/ada/.config/kaneo/config.json not created yet",
+ " Output human stdout is a terminal",
+ " Terminal truecolor · unicode · hyperlinks · 80 columns interactive",
+ "",
+ ]);
+ });
+
+ it("explains a failed account lookup", () => {
+ const lines = renderContext(ui, {
+ ...report,
+ user: null,
+ auth: {
+ ...report.auth,
+ error: "The API key in KANEO_API_KEY was rejected.",
+ },
+ });
+ expect(lines[5]).toBe(
+ " User ✗ The API key in KANEO_API_KEY was rejected.",
+ );
+ });
+});
diff --git a/packages/cli/src/context/render-context.ts b/packages/cli/src/context/render-context.ts
new file mode 100644
index 000000000..cfed9283c
--- /dev/null
+++ b/packages/cli/src/context/render-context.ts
@@ -0,0 +1,280 @@
+import {
+ type Cell,
+ cellWidth,
+ fitCell,
+ renderCell,
+ text,
+} from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+import type { ContextReport } from "./context-report.js";
+
+type Row = {
+ readonly label: string;
+ readonly value: Cell;
+ readonly source: string;
+};
+
+const COLOR_NAMES = ["no color", "16 colors", "256 colors", "truecolor"];
+
+const CONFIG_STATUS = {
+ ok: "",
+ missing: "not created yet",
+ foreign: "written by another kaneo CLI",
+ invalid: "invalid",
+ io: "unreadable",
+} as const;
+
+function profileLabel(report: ContextReport): string {
+ return `profile ${report.profile.name}`;
+}
+
+function serverSource(report: ContextReport): string {
+ switch (report.server.source) {
+ case "flag":
+ return "--api-url";
+ case "env":
+ return "KANEO_API_URL";
+ case "profile":
+ return profileLabel(report);
+ case "default":
+ return "default";
+ }
+}
+
+function webSource(report: ContextReport): string {
+ switch (report.web.source) {
+ case "env":
+ return "KANEO_WEB_URL";
+ case "profile":
+ return profileLabel(report);
+ case "server":
+ return "same as the server";
+ }
+}
+
+function profileSource(report: ContextReport): string {
+ switch (report.profile.source) {
+ case "flag":
+ return "--profile";
+ case "env":
+ return "KANEO_PROFILE";
+ case "config":
+ return "active in the config file";
+ case "default":
+ return "default";
+ }
+}
+
+function authSource(report: ContextReport): string {
+ switch (report.auth.source) {
+ case "flag":
+ return "--token";
+ case "env":
+ return "KANEO_API_KEY";
+ case "profile":
+ return profileLabel(report);
+ case "none":
+ return "";
+ }
+}
+
+function workspaceSource(report: ContextReport): string {
+ switch (report.workspace.source) {
+ case "flag":
+ return "-w";
+ case "env":
+ return "KANEO_WORKSPACE";
+ case "repo":
+ return report.workspace.path ?? ".kaneo.json";
+ case "profile":
+ return profileLabel(report);
+ case "none":
+ return "";
+ }
+}
+
+function projectSource(report: ContextReport): string {
+ switch (report.project.source) {
+ case "env":
+ return "KANEO_PROJECT";
+ case "repo":
+ return report.project.path ?? ".kaneo.json";
+ case "none":
+ return "";
+ }
+}
+
+function outputSource(report: ContextReport): string {
+ switch (report.output.source) {
+ case "flag":
+ return report.output.mode === "json" ? "--json" : "--human";
+ case "env":
+ return "KANEO_JSON";
+ case "terminal":
+ return "stdout is a terminal";
+ case "pipe":
+ return "stdout is not a terminal";
+ }
+}
+
+function profileValue(ui: Ui, report: ContextReport): Cell {
+ const { theme, glyphs } = ui;
+ const { profile } = report;
+ if (!profile.stored) {
+ return [
+ text(profile.name),
+ text(` ${glyphs.separator} not stored`, theme.muted),
+ ];
+ }
+ if (!profile.matchesServer) {
+ return [
+ text(profile.name),
+ text(` ${glyphs.separator} stored for another server`, theme.warning),
+ ];
+ }
+ return [text(profile.name)];
+}
+
+function authValue(ui: Ui, report: ContextReport): Cell {
+ const { theme, glyphs } = ui;
+ const { auth } = report;
+ if (auth.method === null) return [text("signed out", theme.muted)];
+ const label =
+ auth.method === "token"
+ ? "access token"
+ : auth.method === "api-key"
+ ? "API key"
+ : "stored login";
+ return [
+ text(label),
+ ...(auth.fingerprint
+ ? [text(` ${glyphs.ellipsis}${auth.fingerprint}`, theme.muted)]
+ : []),
+ ];
+}
+
+function userValue(ui: Ui, report: ContextReport): Cell {
+ const { theme, glyphs } = ui;
+ if (report.user) {
+ return [
+ text(report.user.name, theme.strong),
+ text(` ${glyphs.separator} ${report.user.email}`, theme.muted),
+ ];
+ }
+ if (report.auth.error) {
+ return [text(`${glyphs.cross} ${report.auth.error}`, theme.danger)];
+ }
+ return [text("unknown", theme.muted)];
+}
+
+function workspaceValue(ui: Ui, report: ContextReport): Cell {
+ const { theme } = ui;
+ const { workspace } = report;
+ if (!workspace.id) return [text("none selected", theme.muted)];
+ if (!workspace.name) return [text(workspace.id)];
+ return [text(workspace.name), text(` ${workspace.id}`, theme.muted)];
+}
+
+function projectValue(ui: Ui, report: ContextReport): Cell {
+ const { theme } = ui;
+ const { project } = report;
+ if (!project.ref) return [text("none selected", theme.muted)];
+ if (!project.name) return [text(project.ref)];
+ return [
+ text(project.name),
+ text(` ${project.key ?? project.ref}`, theme.muted),
+ ];
+}
+
+function terminalValue(ui: Ui, report: ContextReport): Cell {
+ const { theme, glyphs } = ui;
+ const caps = report.output.terminal;
+ const parts = [
+ COLOR_NAMES[caps.color] ?? "no color",
+ caps.unicode ? "unicode" : "ascii",
+ caps.hyperlinks ? "hyperlinks" : "no hyperlinks",
+ `${caps.columns} columns`,
+ ];
+ return [text(parts.join(` ${glyphs.separator} `), theme.muted)];
+}
+
+export function contextRows(ui: Ui, report: ContextReport): ReadonlyArray<Row> {
+ const outputMode = report.output.jq
+ ? `${report.output.mode} ${ui.glyphs.separator} jq ${report.output.jq}`
+ : report.output.mode;
+ return [
+ {
+ label: "Server",
+ value: [text(report.server.url)],
+ source: serverSource(report),
+ },
+ {
+ label: "Web app",
+ value: [text(report.web.url)],
+ source: webSource(report),
+ },
+ {
+ label: "Profile",
+ value: profileValue(ui, report),
+ source: profileSource(report),
+ },
+ { label: "Auth", value: authValue(ui, report), source: authSource(report) },
+ { label: "User", value: userValue(ui, report), source: "" },
+ {
+ label: "Workspace",
+ value: workspaceValue(ui, report),
+ source: workspaceSource(report),
+ },
+ {
+ label: "Project",
+ value: projectValue(ui, report),
+ source: projectSource(report),
+ },
+ {
+ label: "Config",
+ value: [text(report.config.path)],
+ source: CONFIG_STATUS[report.config.status],
+ },
+ {
+ label: "Output",
+ value: [text(outputMode)],
+ source: outputSource(report),
+ },
+ {
+ label: "Terminal",
+ value: terminalValue(ui, report),
+ source: report.output.interactive ? "interactive" : "not interactive",
+ },
+ ];
+}
+
+export function renderContext(ui: Ui, report: ContextReport): string[] {
+ const { theme, glyphs } = ui;
+ const rows = contextRows(ui, report);
+ const labelWidth = Math.max(...rows.map((row) => row.label.length));
+ const lineWidth = Math.max(20, ui.caps.columns - 2);
+ const valueLimit = Math.floor((lineWidth - labelWidth - 2) * 0.6);
+ const valueWidth = Math.max(
+ 0,
+ ...rows
+ .filter((row) => row.source)
+ .map((row) => cellWidth(row.value))
+ .filter((width) => width <= valueLimit),
+ );
+ return [
+ "",
+ ...rows.map((row) => {
+ const gap = Math.max(0, valueWidth - cellWidth(row.value));
+ const cell: Cell = [
+ text(row.label.padEnd(labelWidth), theme.muted),
+ text(" "),
+ ...row.value,
+ ...(row.source
+ ? [text(" ".repeat(gap + 2)), text(row.source, theme.muted)]
+ : []),
+ ];
+ return ` ${renderCell(fitCell(cell, lineWidth, glyphs.ellipsis), ui)}`;
+ }),
+ "",
+ ];
+}
diff --git a/packages/cli/src/doctor/compare-operations.test.ts b/packages/cli/src/doctor/compare-operations.test.ts
new file mode 100644
index 000000000..ac66bda80
--- /dev/null
+++ b/packages/cli/src/doctor/compare-operations.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from "vite-plus/test";
+import {
+ documentedOperations,
+ missingOperations,
+ operationKey,
+} from "./compare-operations.js";
+import { REQUIRED_OPERATIONS } from "./required-operations.js";
+
+const document = {
+ openapi: "3.1.0",
+ servers: [{ url: "https://cloud.kaneo.app/api" }],
+ paths: {
+ "/user/me": { get: {} },
+ "/task/{id}": { get: {}, put: {}, delete: {}, parameters: [] },
+ "/task/assigned": { get: {} },
+ "/project": { get: {}, post: {} },
+ },
+};
+
+describe("operationKey", () => {
+ it("ignores the /api prefix, parameter names and trailing slashes", () => {
+ expect(operationKey("get", "/api/task/{taskId}")).toBe("GET /task/{}");
+ expect(operationKey("GET", "/task/{id}/")).toBe("GET /task/{}");
+ expect(operationKey("put", "/api/task/:id")).toBe("PUT /task/{}");
+ expect(operationKey("get", "/api")).toBe("GET /");
+ });
+});
+
+describe("missingOperations", () => {
+ it("lists the operations the server does not document", () => {
+ expect(
+ missingOperations(
+ [
+ { method: "GET", path: "/api/user/me" },
+ { method: "GET", path: "/api/task/{ticketId}" },
+ { method: "PATCH", path: "/api/task/{id}" },
+ { method: "GET", path: "/api/task/assigned" },
+ { method: "DELETE", path: "/api/project/{id}" },
+ ],
+ document,
+ ),
+ ).toEqual([
+ { method: "PATCH", path: "/api/task/{id}" },
+ { method: "DELETE", path: "/api/project/{id}" },
+ ]);
+ });
+
+ it("skips keys that are not HTTP methods", () => {
+ expect(documentedOperations(document)?.has("PARAMETERS /task/{}")).toBe(
+ false,
+ );
+ });
+
+ it("returns nothing for a document without paths", () => {
+ expect(
+ missingOperations(REQUIRED_OPERATIONS, { openapi: "3.1.0" }),
+ ).toBeUndefined();
+ expect(missingOperations(REQUIRED_OPERATIONS, "<html>")).toBeUndefined();
+ });
+
+ it("lists every required operation once", () => {
+ const keys = REQUIRED_OPERATIONS.map((operation) =>
+ operationKey(operation.method, operation.path),
+ );
+ expect(new Set(keys).size).toBe(keys.length);
+ });
+});
diff --git a/packages/cli/src/doctor/compare-operations.ts b/packages/cli/src/doctor/compare-operations.ts
new file mode 100644
index 000000000..c187a107d
--- /dev/null
+++ b/packages/cli/src/doctor/compare-operations.ts
@@ -0,0 +1,50 @@
+import type { RequiredOperation } from "./required-operations.js";
+
+const HTTP_METHODS = new Set([
+ "get",
+ "post",
+ "put",
+ "patch",
+ "delete",
+ "head",
+ "options",
+ "trace",
+]);
+
+export function operationKey(method: string, path: string): string {
+ const relative = path
+ .replace(/^\/api(?=\/|$)/, "")
+ .replace(/\{[^}]*\}/g, "{}")
+ .replace(/\/:[^/]+/g, "/{}")
+ .replace(/\/+$/, "");
+ return `${method.toUpperCase()} ${relative || "/"}`;
+}
+
+export function documentedOperations(
+ document: unknown,
+): ReadonlySet<string> | undefined {
+ const paths = (document as { paths?: unknown } | null)?.paths;
+ if (typeof paths !== "object" || paths === null) return undefined;
+ const operations = new Set<string>();
+ for (const [path, item] of Object.entries(paths)) {
+ if (typeof item !== "object" || item === null) continue;
+ for (const method of Object.keys(item)) {
+ if (HTTP_METHODS.has(method.toLowerCase())) {
+ operations.add(operationKey(method, path));
+ }
+ }
+ }
+ return operations;
+}
+
+export function missingOperations(
+ required: ReadonlyArray<RequiredOperation>,
+ document: unknown,
+): ReadonlyArray<RequiredOperation> | undefined {
+ const available = documentedOperations(document);
+ if (!available) return undefined;
+ return required.filter(
+ (operation) =>
+ !available.has(operationKey(operation.method, operation.path)),
+ );
+}
diff --git a/packages/cli/src/doctor/doctor-check.ts b/packages/cli/src/doctor/doctor-check.ts
new file mode 100644
index 000000000..31a5a01b2
--- /dev/null
+++ b/packages/cli/src/doctor/doctor-check.ts
@@ -0,0 +1,21 @@
+export type DoctorCheckName =
+ | "config"
+ | "server"
+ | "login"
+ | "workspace"
+ | "compatibility";
+
+export type DoctorCheck = {
+ readonly name: DoctorCheckName;
+ readonly ok: boolean;
+ readonly detail: string;
+ readonly missing?: ReadonlyArray<string>;
+};
+
+export const CHECK_LABELS: Readonly<Record<DoctorCheckName, string>> = {
+ config: "Config file",
+ server: "Server",
+ login: "Signed in",
+ workspace: "Workspace",
+ compatibility: "API compatibility",
+};
diff --git a/packages/cli/src/doctor/fetch-public.ts b/packages/cli/src/doctor/fetch-public.ts
new file mode 100644
index 000000000..3a3de624e
--- /dev/null
+++ b/packages/cli/src/doctor/fetch-public.ts
@@ -0,0 +1,42 @@
+import { Duration, Effect } from "effect";
+import { HttpClient, HttpClientRequest } from "effect/http";
+
+export type PublicResponse = {
+ readonly status: number;
+ readonly milliseconds: number;
+ readonly body: unknown;
+};
+
+function describeFailure(error: unknown): string {
+ if ((error as { _tag?: unknown } | null)?._tag === "TimeoutError") {
+ return "timed out after 15s";
+ }
+ let current: unknown = error;
+ let message = String(error);
+ for (let depth = 0; current && depth < 8; depth++) {
+ const code = (current as { code?: unknown }).code;
+ if (typeof code === "string") return code;
+ if (current instanceof Error) message = current.message;
+ current = (current as { cause?: unknown }).cause;
+ }
+ return message;
+}
+
+export const fetchPublic = (url: string) =>
+ Effect.gen(function* () {
+ const client = yield* HttpClient.HttpClient;
+ const started = Date.now();
+ const response = yield* client
+ .execute(HttpClientRequest.get(url).pipe(HttpClientRequest.acceptJson))
+ .pipe(Effect.timeout(Duration.seconds(15)));
+ const milliseconds = Date.now() - started;
+ const body = yield* response.json.pipe(
+ Effect.orElseSucceed(() => undefined),
+ );
+ const result: PublicResponse = {
+ status: response.status,
+ milliseconds,
+ body,
+ };
+ return result;
+ }).pipe(Effect.mapError(describeFailure));
diff --git a/packages/cli/src/doctor/render-doctor.test.ts b/packages/cli/src/doctor/render-doctor.test.ts
new file mode 100644
index 000000000..83209bb41
--- /dev/null
+++ b/packages/cli/src/doctor/render-doctor.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { renderDoctor } from "./render-doctor.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+describe("renderDoctor", () => {
+ it("prints one line per check and lists missing operations", () => {
+ expect(
+ renderDoctor(ui, {
+ checks: [
+ {
+ name: "server",
+ ok: true,
+ detail: "localhost:1337 responded in 4 ms",
+ },
+ {
+ name: "compatibility",
+ ok: false,
+ detail: "Missing 1 of 80 operations",
+ missing: ["PUT /api/task/title/{id}"],
+ },
+ ],
+ }),
+ ).toEqual([
+ "",
+ " ✓ Server localhost:1337 responded in 4 ms",
+ " ✗ API compatibility Missing 1 of 80 operations",
+ " PUT /api/task/title/{id}",
+ "",
+ " ✗ 1 of 2 checks failed",
+ "",
+ ]);
+ });
+
+ it("confirms when everything passes", () => {
+ expect(
+ renderDoctor(ui, {
+ checks: [
+ {
+ name: "config",
+ ok: true,
+ detail: "/home/a/.config/kaneo/config.json",
+ },
+ ],
+ }).at(-2),
+ ).toBe(" ✓ Everything looks good");
+ });
+});
diff --git a/packages/cli/src/doctor/render-doctor.ts b/packages/cli/src/doctor/render-doctor.ts
new file mode 100644
index 000000000..4a90f2dd5
--- /dev/null
+++ b/packages/cli/src/doctor/render-doctor.ts
@@ -0,0 +1,48 @@
+import type { Ui } from "../render/ui.js";
+import { truncate } from "../render/width.js";
+import { CHECK_LABELS, type DoctorCheck } from "./doctor-check.js";
+
+const MISSING_SHOWN = 8;
+
+const LABEL_WIDTH = Math.max(
+ ...Object.values(CHECK_LABELS).map((label) => label.length),
+);
+
+export function renderDoctor(
+ ui: Ui,
+ result: { readonly checks: ReadonlyArray<DoctorCheck> },
+): string[] {
+ const { theme, glyphs } = ui;
+ const detailWidth = Math.max(16, ui.caps.columns - LABEL_WIDTH - 7);
+ const lines = [""];
+ for (const check of result.checks) {
+ const mark = check.ok
+ ? theme.success(glyphs.tick)
+ : theme.danger(glyphs.cross);
+ lines.push(
+ ` ${mark} ${CHECK_LABELS[check.name].padEnd(LABEL_WIDTH)} ${truncate(check.detail, detailWidth, glyphs.ellipsis)}`,
+ );
+ const missing = check.missing ?? [];
+ const items =
+ missing.length > MISSING_SHOWN
+ ? [
+ ...missing.slice(0, MISSING_SHOWN - 1),
+ `and ${missing.length - MISSING_SHOWN + 1} more`,
+ ]
+ : missing;
+ for (const item of items) {
+ lines.push(
+ ` ${" ".repeat(LABEL_WIDTH)} ${theme.muted(truncate(item, detailWidth, glyphs.ellipsis))}`,
+ );
+ }
+ }
+ const failed = result.checks.filter((check) => !check.ok).length;
+ lines.push(
+ "",
+ failed === 0
+ ? ` ${theme.success(glyphs.tick)} ${theme.strong("Everything looks good")}`
+ : ` ${theme.danger(glyphs.cross)} ${theme.strong(`${failed} of ${result.checks.length} checks failed`)}`,
+ "",
+ );
+ return lines;
+}
diff --git a/packages/cli/src/doctor/required-operations.ts b/packages/cli/src/doctor/required-operations.ts
new file mode 100644
index 000000000..26ee7cb62
--- /dev/null
+++ b/packages/cli/src/doctor/required-operations.ts
@@ -0,0 +1,96 @@
+import type { HttpMethod } from "../api/kaneo-api.js";
+
+export type RequiredOperation = {
+ readonly method: HttpMethod;
+ readonly path: string;
+};
+
+export const REQUIRED_OPERATIONS: ReadonlyArray<RequiredOperation> = [
+ { method: "GET", path: "/api/activity/{taskId}" },
+ { method: "POST", path: "/api/auth/organization/accept-invitation" },
+ { method: "POST", path: "/api/auth/organization/cancel-invitation" },
+ { method: "POST", path: "/api/auth/organization/check-slug" },
+ { method: "POST", path: "/api/auth/organization/create" },
+ { method: "POST", path: "/api/auth/organization/delete" },
+ { method: "POST", path: "/api/auth/organization/has-permission" },
+ { method: "POST", path: "/api/auth/organization/invite-member" },
+ { method: "POST", path: "/api/auth/organization/leave" },
+ { method: "GET", path: "/api/auth/organization/list" },
+ { method: "GET", path: "/api/auth/organization/list-invitations" },
+ { method: "GET", path: "/api/auth/organization/list-members" },
+ { method: "GET", path: "/api/auth/organization/list-roles" },
+ { method: "POST", path: "/api/auth/organization/reject-invitation" },
+ { method: "POST", path: "/api/auth/organization/remove-member" },
+ { method: "POST", path: "/api/auth/organization/update" },
+ { method: "POST", path: "/api/auth/organization/update-member-role" },
+ { method: "PUT", path: "/api/column/reorder/{projectId}" },
+ { method: "DELETE", path: "/api/column/{id}" },
+ { method: "PUT", path: "/api/column/{id}" },
+ { method: "GET", path: "/api/column/{projectId}" },
+ { method: "POST", path: "/api/column/{projectId}" },
+ { method: "DELETE", path: "/api/comment/{id}" },
+ { method: "GET", path: "/api/comment/{id}" },
+ { method: "PUT", path: "/api/comment/{id}" },
+ { method: "POST", path: "/api/comment/{taskId}" },
+ { method: "POST", path: "/api/custom-field" },
+ { method: "GET", path: "/api/custom-field/project/{projectId}" },
+ { method: "GET", path: "/api/custom-field/task/{taskId}" },
+ { method: "PUT", path: "/api/custom-field/value" },
+ { method: "DELETE", path: "/api/custom-field/{id}" },
+ { method: "GET", path: "/api/external-link/task/{taskId}" },
+ { method: "POST", path: "/api/external-link/task/{taskId}" },
+ { method: "DELETE", path: "/api/external-link/task/{taskId}/{linkId}" },
+ { method: "GET", path: "/api/invitation/pending" },
+ { method: "GET", path: "/api/invitation/{invitationId}" },
+ { method: "POST", path: "/api/label" },
+ { method: "GET", path: "/api/label/task/{taskId}" },
+ { method: "GET", path: "/api/label/workspace/{workspaceId}" },
+ { method: "DELETE", path: "/api/label/{id}" },
+ { method: "PUT", path: "/api/label/{id}" },
+ { method: "DELETE", path: "/api/label/{id}/task" },
+ { method: "PUT", path: "/api/label/{id}/task" },
+ { method: "GET", path: "/api/notification" },
+ { method: "PATCH", path: "/api/notification/read-all" },
+ { method: "PATCH", path: "/api/notification/{id}/read" },
+ { method: "GET", path: "/api/project" },
+ { method: "POST", path: "/api/project" },
+ { method: "DELETE", path: "/api/project/{id}" },
+ { method: "GET", path: "/api/project/{id}" },
+ { method: "PUT", path: "/api/project/{id}" },
+ { method: "PUT", path: "/api/project/{id}/archive" },
+ { method: "PUT", path: "/api/project/{id}/move" },
+ { method: "PUT", path: "/api/project/{id}/unarchive" },
+ { method: "GET", path: "/api/search" },
+ { method: "POST", path: "/api/task-relation" },
+ { method: "DELETE", path: "/api/task-relation/{id}" },
+ { method: "GET", path: "/api/task-relation/{taskId}" },
+ { method: "GET", path: "/api/task/assigned" },
+ { method: "PUT", path: "/api/task/assignee/{taskId}" },
+ { method: "PATCH", path: "/api/task/bulk" },
+ { method: "GET", path: "/api/task/by-ticket-id/{ticketId}" },
+ { method: "PUT", path: "/api/task/description/{id}" },
+ { method: "PUT", path: "/api/task/due-date/{id}" },
+ { method: "POST", path: "/api/task/duplicate/{taskId}" },
+ { method: "GET", path: "/api/task/export/{projectId}" },
+ { method: "PUT", path: "/api/task/image-upload/{taskId}" },
+ { method: "POST", path: "/api/task/image-upload/{taskId}/finalize" },
+ { method: "POST", path: "/api/task/import/{projectId}" },
+ { method: "PUT", path: "/api/task/move/{taskId}" },
+ { method: "PUT", path: "/api/task/priority/{id}" },
+ { method: "PUT", path: "/api/task/status/{taskId}" },
+ { method: "GET", path: "/api/task/tasks/{projectId}" },
+ { method: "PUT", path: "/api/task/title/{id}" },
+ { method: "DELETE", path: "/api/task/{id}" },
+ { method: "GET", path: "/api/task/{id}" },
+ { method: "PUT", path: "/api/task/{id}" },
+ { method: "POST", path: "/api/task/{projectId}" },
+ { method: "POST", path: "/api/time-entry" },
+ { method: "GET", path: "/api/time-entry/task/{taskId}" },
+ { method: "GET", path: "/api/time-entry/{id}" },
+ { method: "PUT", path: "/api/time-entry/{id}" },
+ { method: "GET", path: "/api/user/me" },
+ { method: "DELETE", path: "/api/workflow-rule/{id}" },
+ { method: "GET", path: "/api/workflow-rule/{id}" },
+ { method: "PUT", path: "/api/workflow-rule/{id}" },
+ { method: "GET", path: "/api/workspace/{workspaceId}/members" },
+];
diff --git a/packages/cli/src/errors/describe.test.ts b/packages/cli/src/errors/describe.test.ts
new file mode 100644
index 000000000..d78c867f4
--- /dev/null
+++ b/packages/cli/src/errors/describe.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from "vite-plus/test";
+import { describeError } from "./describe.js";
+import * as Errors from "./errors.js";
+import { isAppError } from "./is-app-error.js";
+
+const samples = [
+ new Errors.NotSignedIn({ apiUrl: "https://cloud.kaneo.app" }),
+ new Errors.SessionExpired({ apiUrl: "https://cloud.kaneo.app" }),
+ new Errors.CredentialsRejected({ source: "env" }),
+ new Errors.SessionRequired({ message: "A user session is required" }),
+ new Errors.PermissionDenied({
+ message: "Insufficient permissions",
+ missingPermissions: ["task:delete"],
+ }),
+ new Errors.NotFound({ message: "Task not found" }),
+ new Errors.Conflict({ message: "Conflict" }),
+ new Errors.InvalidRequest({ message: "title: Required" }),
+ new Errors.RateLimited({ retryAfterSeconds: 30 }),
+ new Errors.ServerError({ status: 500, message: "Internal Server Error" }),
+ new Errors.ServerUnreachable({
+ apiUrl: "https://cloud.kaneo.app",
+ reason: "ENOTFOUND",
+ }),
+ new Errors.UnexpectedResponse({
+ endpoint: "GET /api/x",
+ detail: "Expected string",
+ }),
+ new Errors.ConfigUnreadable({
+ path: "/c.json",
+ reason: "foreign",
+ detail: "",
+ }),
+ new Errors.WorkspaceRequired(),
+ new Errors.ProjectRequired(),
+ new Errors.ProjectNotFound({ query: "XYZ", source: null }),
+ new Errors.DeviceClientRejected({
+ apiUrl: "https://cloud.kaneo.app",
+ clientId: "kaneo-cli",
+ }),
+ new Errors.DeviceLoginDenied(),
+ new Errors.DeviceLoginExpired(),
+ new Errors.InvalidArgument({ message: "Bad", hint: "Pass --x" }),
+ new Errors.Cancelled(),
+];
+
+describe("describeError", () => {
+ it("has a message for every error and is recognized as an app error", () => {
+ for (const error of samples) {
+ expect(isAppError(error)).toBe(true);
+ expect(describeError(error).message.length).toBeGreaterThan(0);
+ }
+ });
+
+ it("points to the next step", () => {
+ expect(
+ describeError(
+ new Errors.NotSignedIn({ apiUrl: "https://cloud.kaneo.app" }),
+ ),
+ ).toEqual({
+ message: "You are not signed in to cloud.kaneo.app.",
+ hint: "Run kaneo login, or set KANEO_API_KEY.",
+ });
+ expect(describeError(new Errors.WorkspaceRequired()).hint).toBe(
+ "Pass -w <id>, or run kaneo workspace use.",
+ );
+ });
+
+ it("lists missing permissions", () => {
+ expect(describeError(samples[4] as Errors.PermissionDenied).message).toBe(
+ "Insufficient permissions (missing task:delete)",
+ );
+ });
+
+ it("never treats arbitrary objects as app errors", () => {
+ expect(isAppError(new Error("x"))).toBe(false);
+ expect(isAppError({ _tag: "Other" })).toBe(false);
+ });
+});
diff --git a/packages/cli/src/errors/describe.ts b/packages/cli/src/errors/describe.ts
new file mode 100644
index 000000000..b407bb564
--- /dev/null
+++ b/packages/cli/src/errors/describe.ts
@@ -0,0 +1,132 @@
+import type { AppError } from "./errors.js";
+
+export type Failure = {
+ readonly message: string;
+ readonly hint: string | null;
+};
+
+function host(apiUrl: string): string {
+ try {
+ return new URL(apiUrl).host;
+ } catch {
+ return apiUrl;
+ }
+}
+
+export function describeError(error: AppError): Failure {
+ switch (error._tag) {
+ case "NotSignedIn":
+ return {
+ message: `You are not signed in to ${host(error.apiUrl)}.`,
+ hint: "Run kaneo login, or set KANEO_API_KEY.",
+ };
+ case "SessionExpired":
+ return {
+ message: `Your session for ${host(error.apiUrl)} has expired.`,
+ hint: "Run kaneo login to sign in again.",
+ };
+ case "CredentialsRejected":
+ return error.source === "flag"
+ ? {
+ message: "The token passed with --token was rejected.",
+ hint: "Check the token, or run kaneo login.",
+ }
+ : {
+ message: "The API key in KANEO_API_KEY was rejected.",
+ hint: "Create a new key in Settings, then API keys, or unset KANEO_API_KEY.",
+ };
+ case "SessionRequired":
+ return {
+ message: error.message,
+ hint: "API keys cannot do this. Unset KANEO_API_KEY and run kaneo login.",
+ };
+ case "PermissionDenied":
+ return {
+ message:
+ error.missingPermissions.length > 0
+ ? `${error.message} (missing ${error.missingPermissions.join(", ")})`
+ : error.message,
+ hint: "Ask a workspace owner or admin for access.",
+ };
+ case "NotFound":
+ return { message: error.message, hint: null };
+ case "Conflict":
+ return { message: error.message, hint: null };
+ case "InvalidRequest":
+ return { message: error.message, hint: null };
+ case "RateLimited":
+ return {
+ message: "Too many requests to the Kaneo API.",
+ hint:
+ error.retryAfterSeconds === null
+ ? "Wait a moment and try again."
+ : `Try again in ${error.retryAfterSeconds}s.`,
+ };
+ case "ServerError":
+ return {
+ message: `The server failed with ${error.status}: ${error.message}`,
+ hint: "Try again. If it keeps failing, check the server logs.",
+ };
+ case "ServerUnreachable":
+ return {
+ message: `Could not reach ${host(error.apiUrl)} (${error.reason}).`,
+ hint: "Check your connection, or pass --api-url to use another server.",
+ };
+ case "UnexpectedResponse":
+ return {
+ message: `The server sent a response this CLI does not understand (${error.endpoint}): ${error.detail}`,
+ hint: "Update the CLI with npm i -g @kaneo/cli, or check the server version.",
+ };
+ case "WorkspaceRequired":
+ return {
+ message: "No workspace selected.",
+ hint: "Pass -w <id>, or run kaneo workspace use.",
+ };
+ case "ProjectRequired":
+ return {
+ message: "No project selected.",
+ hint: "Pass -p with a project key or id, for example -p KAN.",
+ };
+ case "ProjectNotFound":
+ return {
+ message: error.source
+ ? `No project matches "${error.query}" (from ${error.source}) in this workspace.`
+ : `No project matches "${error.query}" in this workspace.`,
+ hint: "Run kaneo project list to see the project keys.",
+ };
+ case "DeviceClientRejected":
+ return {
+ message: `${host(error.apiUrl)} does not allow browser sign-in from the Kaneo CLI (client ID ${error.clientId}).`,
+ hint: `Ask the server admin to add ${error.clientId} to DEVICE_AUTH_CLIENT_IDS, or use an API key with KANEO_API_KEY.`,
+ };
+ case "DeviceLoginDenied":
+ return {
+ message: "The sign-in request was denied in the browser.",
+ hint: "Run kaneo login to try again.",
+ };
+ case "DeviceLoginExpired":
+ return {
+ message: "The sign-in code expired before it was approved.",
+ hint: "Run kaneo login to get a new code.",
+ };
+ case "ConfigUnreadable":
+ return error.reason === "foreign"
+ ? {
+ message: `${error.path} was written by a different kaneo CLI, so it was left untouched.`,
+ hint: "Move the file aside, or set KANEO_CONFIG to use another file.",
+ }
+ : {
+ message: `Could not read ${error.path}: ${error.detail}`,
+ hint:
+ error.reason === "invalid"
+ ? "Fix or delete the file, then run kaneo login."
+ : null,
+ };
+ case "InvalidArgument":
+ return { message: error.message, hint: error.hint ?? null };
+ case "Cancelled":
+ return { message: "Cancelled.", hint: null };
+ default:
+ return error satisfies never;
+ }
+}
diff --git a/packages/cli/src/errors/errors.ts b/packages/cli/src/errors/errors.ts
new file mode 100644
index 000000000..c8fd23abf
--- /dev/null
+++ b/packages/cli/src/errors/errors.ts
@@ -0,0 +1,120 @@
+import { Data } from "effect";
+
+export class NotSignedIn extends Data.TaggedError("NotSignedIn")<{
+ readonly apiUrl: string;
+}> {}
+
+export class SessionExpired extends Data.TaggedError("SessionExpired")<{
+ readonly apiUrl: string;
+}> {}
+
+export class CredentialsRejected extends Data.TaggedError(
+ "CredentialsRejected",
+)<{
+ readonly source: "flag" | "env";
+}> {}
+
+export class SessionRequired extends Data.TaggedError("SessionRequired")<{
+ readonly message: string;
+}> {}
+
+export class PermissionDenied extends Data.TaggedError("PermissionDenied")<{
+ readonly message: string;
+ readonly missingPermissions: ReadonlyArray<string>;
+}> {}
+
+export class NotFound extends Data.TaggedError("NotFound")<{
+ readonly message: string;
+}> {}
+
+export class Conflict extends Data.TaggedError("Conflict")<{
+ readonly message: string;
+}> {}
+
+export class InvalidRequest extends Data.TaggedError("InvalidRequest")<{
+ readonly message: string;
+}> {}
+
+export class RateLimited extends Data.TaggedError("RateLimited")<{
+ readonly retryAfterSeconds: number | null;
+}> {}
+
+export class ServerError extends Data.TaggedError("ServerError")<{
+ readonly status: number;
+ readonly message: string;
+}> {}
+
+export class ServerUnreachable extends Data.TaggedError("ServerUnreachable")<{
+ readonly apiUrl: string;
+ readonly reason: string;
+}> {}
+
+export class UnexpectedResponse extends Data.TaggedError("UnexpectedResponse")<{
+ readonly endpoint: string;
+ readonly detail: string;
+}> {}
+
+export class WorkspaceRequired extends Data.TaggedError(
+ "WorkspaceRequired",
+)<{}> {}
+
+export class ProjectRequired extends Data.TaggedError("ProjectRequired")<{}> {}
+
+export class ProjectNotFound extends Data.TaggedError("ProjectNotFound")<{
+ readonly query: string;
+ readonly source: string | null;
+}> {}
+
+export class DeviceClientRejected extends Data.TaggedError(
+ "DeviceClientRejected",
+)<{
+ readonly apiUrl: string;
+ readonly clientId: string;
+}> {}
+
+export class DeviceLoginDenied extends Data.TaggedError(
+ "DeviceLoginDenied",
+)<{}> {}
+
+export class DeviceLoginExpired extends Data.TaggedError(
+ "DeviceLoginExpired",
+)<{}> {}
+
+export class ConfigUnreadable extends Data.TaggedError("ConfigUnreadable")<{
+ readonly path: string;
+ readonly reason: "foreign" | "invalid" | "io";
+ readonly detail: string;
+}> {}
+
+export class InvalidArgument extends Data.TaggedError("InvalidArgument")<{
+ readonly message: string;
+ readonly hint?: string;
+}> {}
+
+export class Cancelled extends Data.TaggedError("Cancelled")<{}> {}
+
+export type ApiFailure =
+ | NotSignedIn
+ | SessionExpired
+ | CredentialsRejected
+ | SessionRequired
+ | PermissionDenied
+ | NotFound
+ | Conflict
+ | InvalidRequest
+ | RateLimited
+ | ServerError
+ | ServerUnreachable
+ | UnexpectedResponse
+ | ConfigUnreadable;
+
+export type AppError =
+ | ApiFailure
+ | WorkspaceRequired
+ | ProjectRequired
+ | ProjectNotFound
+ | DeviceClientRejected
+ | DeviceLoginDenied
+ | DeviceLoginExpired
+ | InvalidArgument
+ | Cancelled;
diff --git a/packages/cli/src/errors/is-app-error.ts b/packages/cli/src/errors/is-app-error.ts
new file mode 100644
index 000000000..c07c7ddc4
--- /dev/null
+++ b/packages/cli/src/errors/is-app-error.ts
@@ -0,0 +1,33 @@
+import type { AppError } from "./errors.js";
+
+const TAGS: ReadonlySet<string> = new Set<AppError["_tag"]>([
+ "NotSignedIn",
+ "SessionExpired",
+ "CredentialsRejected",
+ "SessionRequired",
+ "PermissionDenied",
+ "NotFound",
+ "Conflict",
+ "InvalidRequest",
+ "RateLimited",
+ "ServerError",
+ "ServerUnreachable",
+ "UnexpectedResponse",
+ "ConfigUnreadable",
+ "WorkspaceRequired",
+ "ProjectRequired",
+ "ProjectNotFound",
+ "DeviceClientRejected",
+ "DeviceLoginDenied",
+ "DeviceLoginExpired",
+ "InvalidArgument",
+ "Cancelled",
+]);
+
+export function isAppError(value: unknown): value is AppError {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ TAGS.has((value as { _tag?: unknown })._tag as string)
+ );
+}
diff --git a/packages/cli/src/external-links/link-input.test.ts b/packages/cli/src/external-links/link-input.test.ts
new file mode 100644
index 000000000..7d257a7b4
--- /dev/null
+++ b/packages/cli/src/external-links/link-input.test.ts
@@ -0,0 +1,30 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { validateLinkTitle, validateLinkUrl } from "./link-input.js";
+
+describe("validateLinkUrl", () => {
+ it("accepts http and https addresses", () => {
+ expect(Result.getOrThrow(validateLinkUrl(" https://example.com/a "))).toBe(
+ "https://example.com/a",
+ );
+ expect(Result.isSuccess(validateLinkUrl("http://localhost:3000"))).toBe(
+ true,
+ );
+ });
+
+ it("rejects other schemes and plain words", () => {
+ const ftp = validateLinkUrl("ftp://example.com");
+ expect(Result.isFailure(ftp) && ftp.failure.message).toBe(
+ "Links must use http or https, not ftp.",
+ );
+ expect(Result.isFailure(validateLinkUrl("example"))).toBe(true);
+ });
+});
+
+describe("validateLinkTitle", () => {
+ it("drops an empty title and limits the length", () => {
+ expect(Result.getOrThrow(validateLinkTitle(" "))).toBeUndefined();
+ expect(Result.getOrThrow(validateLinkTitle(" Spec "))).toBe("Spec");
+ expect(Result.isFailure(validateLinkTitle("x".repeat(201)))).toBe(true);
+ });
+});
diff --git a/packages/cli/src/external-links/link-input.ts b/packages/cli/src/external-links/link-input.ts
new file mode 100644
index 000000000..434189726
--- /dev/null
+++ b/packages/cli/src/external-links/link-input.ts
@@ -0,0 +1,43 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+
+export const MAX_LINK_TITLE = 200;
+
+export function validateLinkUrl(
+ input: string,
+): Result.Result<string, InvalidArgument> {
+ const trimmed = input.trim();
+ let url: URL;
+ try {
+ url = new URL(trimmed);
+ } catch {
+ return Result.fail(
+ new InvalidArgument({
+ message: `"${trimmed}" is not a URL.`,
+ hint: "Pass a full address, for example https://example.com/spec.",
+ }),
+ );
+ }
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
+ return Result.fail(
+ new InvalidArgument({
+ message: `Links must use http or https, not ${url.protocol.replace(":", "")}.`,
+ }),
+ );
+ }
+ return Result.succeed(trimmed);
+}
+
+export function validateLinkTitle(
+ input: string,
+): Result.Result<string | undefined, InvalidArgument> {
+ const trimmed = input.trim();
+ if (trimmed === "") return Result.succeed(undefined);
+ return Array.from(trimmed).length > MAX_LINK_TITLE
+ ? Result.fail(
+ new InvalidArgument({
+ message: `The title is longer than ${MAX_LINK_TITLE} characters.`,
+ }),
+ )
+ : Result.succeed(trimmed);
+}
diff --git a/packages/cli/src/external-links/link-json.test.ts b/packages/cli/src/external-links/link-json.test.ts
new file mode 100644
index 000000000..bd0ea92e6
--- /dev/null
+++ b/packages/cli/src/external-links/link-json.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vite-plus/test";
+import { toLinkJson } from "./link-json.js";
+import { externalLink } from "./test-links.js";
+
+describe("toLinkJson", () => {
+ it("marks manual links as removable", () => {
+ expect(toLinkJson(externalLink({ id: "l1", title: "Spec" }))).toEqual({
+ id: "l1",
+ url: "https://example.com/l1",
+ title: "Spec",
+ source: "manual",
+ resourceType: "url",
+ removable: true,
+ createdAt: "2026-10-08T10:00:00.000Z",
+ });
+ });
+
+ it("names the integration a synced link comes from", () => {
+ expect(
+ toLinkJson(
+ externalLink({
+ id: "l2",
+ integrationId: "i1",
+ resourceType: "pull_request",
+ integration: { id: "i1", type: "github" },
+ }),
+ ),
+ ).toMatchObject({ source: "github", removable: false });
+ });
+});
diff --git a/packages/cli/src/external-links/link-json.ts b/packages/cli/src/external-links/link-json.ts
new file mode 100644
index 000000000..da60f4314
--- /dev/null
+++ b/packages/cli/src/external-links/link-json.ts
@@ -0,0 +1,29 @@
+import type { ExternalLink } from "../api/external-links.js";
+
+export type LinkJson = {
+ readonly id: string;
+ readonly url: string;
+ readonly title: string | null;
+ readonly source: string;
+ readonly resourceType: string;
+ readonly removable: boolean;
+ readonly createdAt: string;
+};
+
+export function isManualLink(link: ExternalLink): boolean {
+ return link.integrationId === null && link.resourceType === "url";
+}
+
+export function toLinkJson(link: ExternalLink): LinkJson {
+ return {
+ id: link.id,
+ url: link.url,
+ title: link.title,
+ source: isManualLink(link)
+ ? "manual"
+ : (link.integration?.type ?? "integration"),
+ resourceType: link.resourceType,
+ removable: isManualLink(link),
+ createdAt: link.createdAt,
+ };
+}
diff --git a/packages/cli/src/external-links/match-link.test.ts b/packages/cli/src/external-links/match-link.test.ts
new file mode 100644
index 000000000..49b823466
--- /dev/null
+++ b/packages/cli/src/external-links/match-link.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vite-plus/test";
+import { matchLink } from "./match-link.js";
+import { externalLink } from "./test-links.js";
+
+const links = [
+ externalLink({ id: "abcd1234xyz", url: "https://example.com/spec" }),
+ externalLink({ id: "abce9876xyz", url: "https://example.com/plan" }),
+];
+
+describe("matchLink", () => {
+ it("finds a link by id, unique id prefix or URL", () => {
+ expect(matchLink(links, "abcd1234xyz")).toMatchObject({ kind: "found" });
+ expect(matchLink(links, "abcd")).toMatchObject({
+ kind: "found",
+ link: { id: "abcd1234xyz" },
+ });
+ expect(matchLink(links, "https://example.com/plan")).toMatchObject({
+ kind: "found",
+ link: { id: "abce9876xyz" },
+ });
+ });
+
+ it("reports a shared prefix and refuses very short ones", () => {
+ expect(matchLink(links, "abc").kind).toBe("none");
+ expect(
+ matchLink([...links, externalLink({ id: "abcd5555" })], "abcd").kind,
+ ).toBe("ambiguous");
+ expect(matchLink(links, "zzzz").kind).toBe("none");
+ });
+});
diff --git a/packages/cli/src/external-links/match-link.ts b/packages/cli/src/external-links/match-link.ts
new file mode 100644
index 000000000..753c2d34c
--- /dev/null
+++ b/packages/cli/src/external-links/match-link.ts
@@ -0,0 +1,37 @@
+import type { ExternalLink } from "../api/external-links.js";
+
+export type LinkMatch =
+ | { readonly kind: "found"; readonly link: ExternalLink }
+ | {
+ readonly kind: "ambiguous";
+ readonly candidates: ReadonlyArray<ExternalLink>;
+ }
+ | { readonly kind: "none" };
+
+const MIN_PREFIX = 4;
+
+function only(matches: ReadonlyArray<ExternalLink>): LinkMatch | null {
+ const [first] = matches;
+ if (!first) return null;
+ return matches.length === 1
+ ? { kind: "found", link: first }
+ : { kind: "ambiguous", candidates: matches };
+}
+
+export function matchLink(
+ links: ReadonlyArray<ExternalLink>,
+ reference: string,
+): LinkMatch {
+ const wanted = reference.trim();
+ if (wanted === "") return { kind: "none" };
+ const exact = links.find((link) => link.id === wanted);
+ if (exact) return { kind: "found", link: exact };
+ const byUrl = only(links.filter((link) => link.url === wanted));
+ if (byUrl) return byUrl;
+ if (wanted.length < MIN_PREFIX) return { kind: "none" };
+ return (
+ only(links.filter((link) => link.id.startsWith(wanted))) ?? {
+ kind: "none",
+ }
+ );
+}
diff --git a/packages/cli/src/external-links/render-link-change.ts b/packages/cli/src/external-links/render-link-change.ts
new file mode 100644
index 000000000..ac9a036f3
--- /dev/null
+++ b/packages/cli/src/external-links/render-link-change.ts
@@ -0,0 +1,25 @@
+import { renderCell, text } from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+import { stringWidth, truncate } from "../render/width.js";
+
+export type LinkChange = {
+ readonly verb: "Linked" | "Unlinked";
+ readonly taskLabel: string;
+ readonly taskUrl: string;
+ readonly linkTitle: string;
+};
+
+export function renderLinkChange(ui: Ui, change: LinkChange): string[] {
+ const { theme, glyphs } = ui;
+ const reference = renderCell(
+ [text(change.taskLabel, theme.strong, change.taskUrl)],
+ ui,
+ );
+ const head = ` ${theme.success(glyphs.tick)} ${change.verb} ${reference} ${theme.muted(glyphs.separator)} `;
+ const title = truncate(
+ change.linkTitle,
+ Math.max(ui.caps.columns - stringWidth(head), 8),
+ glyphs.ellipsis,
+ );
+ return ["", `${head}${title}`, ""];
+}
diff --git a/packages/cli/src/external-links/render-link-list.test.ts b/packages/cli/src/external-links/render-link-list.test.ts
new file mode 100644
index 000000000..b5a80f46d
--- /dev/null
+++ b/packages/cli/src/external-links/render-link-list.test.ts
@@ -0,0 +1,91 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import { toLinkJson } from "./link-json.js";
+import { renderLinkChange } from "./render-link-change.js";
+import { renderLinkList } from "./render-link-list.js";
+import { externalLink } from "./test-links.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+const view = {
+ taskLabel: "KAN-3",
+ taskTitle: "Fix login redirect",
+ taskUrl: "https://kaneo.test/t",
+};
+
+describe("renderLinkList", () => {
+ it("lists links with short ids at 80 columns", () => {
+ const lines = renderLinkList(ui, {
+ ...view,
+ links: [
+ toLinkJson(
+ externalLink({
+ id: "tsl4l6e5rvapbu3zo2ff2lt6",
+ url: "https://example.com/spec",
+ title: "Design spec",
+ }),
+ ),
+ toLinkJson(
+ externalLink({
+ id: "eh2p47610rlk2ri520mxu5b9",
+ url: "https://github.com/usekaneo/kaneo/pull/1958",
+ integrationId: "i1",
+ resourceType: "pull_request",
+ title:
+ "fix(calendar): allow feeds without label filters, a long pull request title",
+ integration: { id: "i1", type: "github" },
+ }),
+ ),
+ ],
+ });
+ expect(lines.slice(0, 4)).toEqual([
+ "",
+ " KAN-3 · Fix login redirect",
+ "",
+ " tsl4l6e5 Design spec example.com/spec manual",
+ ]);
+ expect(lines[4]?.endsWith("github")).toBe(true);
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(80);
+ });
+
+ it("explains how to add the first link", () => {
+ expect(renderLinkList(ui, { ...view, links: [] })).toEqual([
+ "",
+ " KAN-3 · Fix login redirect",
+ "",
+ " No links yet. Add one with kaneo task link add KAN-3 <url>.",
+ "",
+ ]);
+ });
+});
+
+describe("renderLinkChange", () => {
+ it("prints the linked and unlinked task on one line", () => {
+ expect(
+ renderLinkChange(ui, {
+ verb: "Linked",
+ taskLabel: "KAN-3",
+ taskUrl: "https://kaneo.test/t",
+ linkTitle: "Design spec (https://example.com/spec)",
+ }),
+ ).toEqual([
+ "",
+ " ✓ Linked KAN-3 · Design spec (https://example.com/spec)",
+ "",
+ ]);
+ const [, line] = renderLinkChange(ui, {
+ verb: "Unlinked",
+ taskLabel: "KAN-3",
+ taskUrl: "https://kaneo.test/t",
+ linkTitle: `https://example.com/${"x".repeat(100)}`,
+ });
+ expect(stringWidth(line ?? "")).toBeLessThanOrEqual(80);
+ });
+});
diff --git a/packages/cli/src/external-links/render-link-list.ts b/packages/cli/src/external-links/render-link-list.ts
new file mode 100644
index 000000000..4adbebf1f
--- /dev/null
+++ b/packages/cli/src/external-links/render-link-list.ts
@@ -0,0 +1,71 @@
+import { type Cell, renderCell, text } from "../render/cell.js";
+import { renderTable } from "../render/table.js";
+import type { Ui } from "../render/ui.js";
+import type { LinkJson } from "./link-json.js";
+
+export type LinkListView = {
+ readonly taskLabel: string;
+ readonly taskTitle: string;
+ readonly taskUrl: string;
+ readonly links: ReadonlyArray<LinkJson>;
+};
+
+export const SHORT_ID = 8;
+
+function displayUrl(url: string): string {
+ return url.replace(/^https?:\/\//u, "").replace(/\/$/u, "");
+}
+
+export function renderLinkList(ui: Ui, view: LinkListView): string[] {
+ const { theme, glyphs } = ui;
+ const header = ` ${renderCell([text(view.taskLabel, theme.strong, view.taskUrl)], ui)} ${theme.muted(glyphs.separator)} ${view.taskTitle}`;
+ if (view.links.length === 0) {
+ return [
+ "",
+ header,
+ "",
+ ` ${theme.muted(`No links yet. Add one with kaneo task link add ${view.taskLabel} <url>.`)}`,
+ "",
+ ];
+ }
+ return [
+ "",
+ header,
+ "",
+ ...renderTable(
+ ui,
+ view.links,
+ [
+ {
+ header: "ID",
+ cell: (link): Cell => [text(link.id.slice(0, SHORT_ID), theme.muted)],
+ },
+ {
+ header: "Title",
+ flex: true,
+ minWidth: 12,
+ cell: (link): Cell => [
+ text(link.title ?? displayUrl(link.url), undefined, link.url),
+ ],
+ },
+ {
+ header: "URL",
+ flex: true,
+ optional: true,
+ minWidth: 16,
+ cell: (link): Cell =>
+ link.title
+ ? [text(displayUrl(link.url), theme.info, link.url)]
+ : [],
+ },
+ {
+ header: "Source",
+ optional: true,
+ cell: (link): Cell => [text(link.source, theme.muted)],
+ },
+ ],
+ { width: ui.caps.columns, indent: 4, gap: 2 },
+ ),
+ "",
+ ];
+}
diff --git a/packages/cli/src/external-links/test-links.ts b/packages/cli/src/external-links/test-links.ts
new file mode 100644
index 000000000..8988e7de9
--- /dev/null
+++ b/packages/cli/src/external-links/test-links.ts
@@ -0,0 +1,15 @@
+import type { ExternalLink } from "../api/external-links.js";
+
+export function externalLink(
+ overrides: Partial<ExternalLink> & { readonly id: string },
+): ExternalLink {
+ return {
+ taskId: "t1",
+ integrationId: null,
+ resourceType: "url",
+ url: `https://example.com/${overrides.id}`,
+ title: null,
+ createdAt: "2026-10-08T10:00:00.000Z",
+ ...overrides,
+ };
+}
diff --git a/packages/cli/src/fields/choose-field.ts b/packages/cli/src/fields/choose-field.ts
new file mode 100644
index 000000000..4bb6350e9
--- /dev/null
+++ b/packages/cli/src/fields/choose-field.ts
@@ -0,0 +1,58 @@
+import { Effect, Option } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+import { Output } from "../output/output.js";
+import { pick } from "../prompts/pick.js";
+import type { FieldJson } from "./field-json.js";
+import { fieldTypeLabel } from "./field-types.js";
+import { matchField } from "./match-field.js";
+
+export function unknownField(
+ fields: ReadonlyArray<FieldJson>,
+ reference: string,
+ projectName: string,
+): InvalidArgument {
+ return new InvalidArgument({
+ message: `No custom field matches "${reference}" in ${projectName}.`,
+ hint:
+ fields.length > 0
+ ? `Fields: ${fields.map((field) => field.name).join(", ")}.`
+ : "This project has no custom fields. Add one with kaneo field create.",
+ });
+}
+
+export const chooseField = Effect.fnUntraced(function* (
+ fields: ReadonlyArray<FieldJson>,
+ reference: Option.Option<string>,
+ options: {
+ readonly projectName: string;
+ readonly question: string;
+ readonly example: string;
+ },
+) {
+ const output = yield* Output;
+ if (Option.isSome(reference)) {
+ const match = matchField(fields, reference.value);
+ if (match) return match;
+ return yield* unknownField(fields, reference.value, options.projectName);
+ }
+ if (output.interactive && fields.length > 0) {
+ return yield* pick(
+ options.question,
+ fields.map((field) => ({
+ title: field.name,
+ value: field,
+ description: fieldTypeLabel(field.type),
+ })),
+ );
+ }
+ if (fields.length === 0) {
+ return yield* new InvalidArgument({
+ message: `${options.projectName} has no custom fields.`,
+ hint: "Add one with kaneo field create <name> --type text.",
+ });
+ }
+ return yield* new InvalidArgument({
+ message: "Which field?",
+ hint: `Pass its name or id, for example ${options.example}.`,
+ });
+});
diff --git a/packages/cli/src/fields/field-json.ts b/packages/cli/src/fields/field-json.ts
new file mode 100644
index 000000000..ddd78d460
--- /dev/null
+++ b/packages/cli/src/fields/field-json.ts
@@ -0,0 +1,22 @@
+import type { CustomField } from "../api/custom-fields.js";
+import { fieldOptions } from "./field-types.js";
+
+export type FieldJson = {
+ readonly id: string;
+ readonly name: string;
+ readonly type: string;
+ readonly required: boolean;
+ readonly defaultValue: string | null;
+ readonly options: ReadonlyArray<string>;
+};
+
+export function toFieldJson(field: CustomField): FieldJson {
+ return {
+ id: field.id,
+ name: field.name,
+ type: field.type,
+ required: field.required,
+ defaultValue: field.defaultValue,
+ options: fieldOptions(field.options),
+ };
+}
diff --git a/packages/cli/src/fields/field-types.test.ts b/packages/cli/src/fields/field-types.test.ts
new file mode 100644
index 000000000..7c284cd86
--- /dev/null
+++ b/packages/cli/src/fields/field-types.test.ts
@@ -0,0 +1,58 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import {
+ checkFieldOptions,
+ fieldOptions,
+ parseFieldType,
+} from "./field-types.js";
+
+describe("parseFieldType", () => {
+ it("accepts the API names and friendly aliases", () => {
+ expect(parseFieldType("Number")).toEqual(Result.succeed("number"));
+ expect(parseFieldType("select")).toEqual(Result.succeed("dropdown"));
+ expect(parseFieldType("multi-select")).toEqual(
+ Result.succeed("multiselect"),
+ );
+ expect(parseFieldType("checkbox")).toEqual(Result.succeed("boolean"));
+ });
+
+ it("lists the types when the input is unknown", () => {
+ const result = parseFieldType("color");
+ expect(Result.isFailure(result) && result.failure.hint).toBe(
+ "Use one of: text, number, date, dropdown, multiselect, boolean.",
+ );
+ });
+});
+
+describe("checkFieldOptions", () => {
+ it("trims and removes duplicate options", () => {
+ expect(checkFieldOptions("dropdown", [" iOS ", "iOS", "", "Web"])).toEqual(
+ Result.succeed(["iOS", "Web"]),
+ );
+ });
+
+ it("needs one option for a dropdown and two for a multi-select", () => {
+ expect(Result.isFailure(checkFieldOptions("dropdown", []))).toBe(true);
+ const multi = checkFieldOptions("multiselect", ["iOS", "iOS"]);
+ expect(Result.isFailure(multi) && multi.failure.message).toBe(
+ "A multi-select field needs at least two options.",
+ );
+ });
+
+ it("refuses options for types without choices", () => {
+ expect(checkFieldOptions("text", [])).toEqual(Result.succeed(undefined));
+ const result = checkFieldOptions("number", ["1"]);
+ expect(Result.isFailure(result) && result.failure.message).toBe(
+ "A number field has no options.",
+ );
+ });
+});
+
+describe("fieldOptions", () => {
+ it("reads arrays and JSON strings and ignores anything else", () => {
+ expect(fieldOptions(["a", 1, "b"])).toEqual(["a", "b"]);
+ expect(fieldOptions('["x","y"]')).toEqual(["x", "y"]);
+ expect(fieldOptions(null)).toEqual([]);
+ expect(fieldOptions("oops")).toEqual([]);
+ });
+});
diff --git a/packages/cli/src/fields/field-types.ts b/packages/cli/src/fields/field-types.ts
new file mode 100644
index 000000000..8b307cc3e
--- /dev/null
+++ b/packages/cli/src/fields/field-types.ts
@@ -0,0 +1,103 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+
+export const FIELD_TYPES = [
+ "text",
+ "number",
+ "date",
+ "dropdown",
+ "multiselect",
+ "boolean",
+] as const;
+
+export type FieldType = (typeof FIELD_TYPES)[number];
+
+export const FIELD_TYPE_LABELS: Readonly<Record<FieldType, string>> = {
+ text: "Text",
+ number: "Number",
+ date: "Date",
+ dropdown: "Dropdown",
+ multiselect: "Multi-select",
+ boolean: "Yes or no",
+};
+
+const ALIASES: Readonly<Record<string, FieldType>> = {
+ select: "dropdown",
+ "multi-select": "multiselect",
+ multi: "multiselect",
+ bool: "boolean",
+ checkbox: "boolean",
+ string: "text",
+};
+
+export function isFieldType(value: string): value is FieldType {
+ return (FIELD_TYPES as ReadonlyArray<string>).includes(value);
+}
+
+export function fieldTypeLabel(type: string): string {
+ return isFieldType(type) ? FIELD_TYPE_LABELS[type] : type;
+}
+
+export function parseFieldType(
+ input: string,
+): Result.Result<FieldType, InvalidArgument> {
+ const value = input.trim().toLowerCase();
+ if (isFieldType(value)) return Result.succeed(value);
+ const alias = ALIASES[value];
+ if (alias) return Result.succeed(alias);
+ return Result.fail(
+ new InvalidArgument({
+ message: `"${input.trim()}" is not a field type.`,
+ hint: `Use one of: ${FIELD_TYPES.join(", ")}.`,
+ }),
+ );
+}
+
+export function fieldOptions(raw: unknown): string[] {
+ const parsed =
+ typeof raw === "string"
+ ? (() => {
+ try {
+ return JSON.parse(raw) as unknown;
+ } catch {
+ return null;
+ }
+ })()
+ : raw;
+ return Array.isArray(parsed)
+ ? parsed.filter((option): option is string => typeof option === "string")
+ : [];
+}
+
+export function checkFieldOptions(
+ type: FieldType,
+ options: ReadonlyArray<string>,
+): Result.Result<ReadonlyArray<string> | undefined, InvalidArgument> {
+ const cleaned = [
+ ...new Set(options.map((option) => option.trim()).filter(Boolean)),
+ ];
+ if (type === "dropdown" || type === "multiselect") {
+ const needed = type === "dropdown" ? 1 : 2;
+ if (cleaned.length < needed) {
+ return Result.fail(
+ new InvalidArgument({
+ message:
+ type === "dropdown"
+ ? "A dropdown field needs at least one option."
+ : "A multi-select field needs at least two options.",
+ hint: "Pass each choice with --option, for example --option iOS --option Android.",
+ }),
+ );
+ }
+ return Result.succeed(cleaned);
+ }
+ if (cleaned.length > 0) {
+ return Result.fail(
+ new InvalidArgument({
+ message: `A ${FIELD_TYPE_LABELS[type].toLowerCase()} field has no options.`,
+ hint: "--option only applies to dropdown and multiselect fields.",
+ }),
+ );
+ }
+ return Result.succeed(undefined);
+}
diff --git a/packages/cli/src/fields/field-value.test.ts b/packages/cli/src/fields/field-value.test.ts
new file mode 100644
index 000000000..fd33b0c01
--- /dev/null
+++ b/packages/cli/src/fields/field-value.test.ts
@@ -0,0 +1,119 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import {
+ type FieldDefinition,
+ fieldValueJson,
+ formatFieldValue,
+ parseFieldValue,
+} from "./field-value.js";
+
+const now = new Date(2026, 9, 8, 12);
+
+function field(type: string, options: string[] = []): FieldDefinition {
+ return { name: "Field", type, options };
+}
+
+function failure(result: Result.Result<string, { readonly message: string }>) {
+ return Result.isFailure(result) ? result.failure.message : null;
+}
+
+describe("parseFieldValue", () => {
+ it("keeps text as typed, without outer spaces", () => {
+ expect(parseFieldValue(field("text"), " Hello there ", now)).toEqual(
+ Result.succeed("Hello there"),
+ );
+ });
+
+ it("accepts finite numbers only", () => {
+ expect(parseFieldValue(field("number"), "2.5", now)).toEqual(
+ Result.succeed("2.5"),
+ );
+ expect(failure(parseFieldValue(field("number"), "five", now))).toBe(
+ 'Field: "five" is not a number.',
+ );
+ expect(
+ Result.isFailure(parseFieldValue(field("number"), "Infinity", now)),
+ ).toBe(true);
+ });
+
+ it("turns yes and no words into true and false", () => {
+ expect(parseFieldValue(field("boolean"), "Yes", now)).toEqual(
+ Result.succeed("true"),
+ );
+ expect(parseFieldValue(field("boolean"), "off", now)).toEqual(
+ Result.succeed("false"),
+ );
+ expect(
+ Result.isFailure(parseFieldValue(field("boolean"), "maybe", now)),
+ ).toBe(true);
+ });
+
+ it("stores dates as YYYY-MM-DD and understands relative days", () => {
+ expect(parseFieldValue(field("date"), "2026-02-28", now)).toEqual(
+ Result.succeed("2026-02-28"),
+ );
+ expect(parseFieldValue(field("date"), "tomorrow", now)).toEqual(
+ Result.succeed("2026-10-09"),
+ );
+ expect(parseFieldValue(field("date"), "+7d", now)).toEqual(
+ Result.succeed("2026-10-15"),
+ );
+ expect(failure(parseFieldValue(field("date"), "2026-02-30", now))).toBe(
+ 'Field: "2026-02-30" is not a date.',
+ );
+ });
+
+ it("matches dropdown options without caring about case", () => {
+ const platform = field("dropdown", ["iOS", "Android"]);
+ expect(parseFieldValue(platform, "ios", now)).toEqual(
+ Result.succeed("iOS"),
+ );
+ const result = parseFieldValue(platform, "Web", now);
+ expect(Result.isFailure(result) && result.failure.hint).toBe(
+ "Use one of: iOS, Android.",
+ );
+ });
+
+ it("stores multi-select choices as a JSON array", () => {
+ const platforms = field("multiselect", ["iOS", "Android", "Web"]);
+ expect(parseFieldValue(platforms, "web, ios, Web", now)).toEqual(
+ Result.succeed('["Web","iOS"]'),
+ );
+ expect(failure(parseFieldValue(platforms, "iOS, Desktop", now))).toBe(
+ "Field: not an option: Desktop.",
+ );
+ expect(failure(parseFieldValue(platforms, " , ", now))).toBe(
+ "Field: pick at least one option.",
+ );
+ });
+
+ it("refuses an empty value and points at --clear", () => {
+ const result = parseFieldValue(field("text"), " ", now);
+ expect(Result.isFailure(result) && result.failure.hint).toBe(
+ "Pass a value, or --clear to remove it.",
+ );
+ });
+});
+
+describe("fieldValueJson and formatFieldValue", () => {
+ it("gives scripts typed values", () => {
+ expect(fieldValueJson("number", "2.5")).toBe(2.5);
+ expect(fieldValueJson("boolean", "false")).toBe(false);
+ expect(fieldValueJson("multiselect", '["iOS","Web"]')).toEqual([
+ "iOS",
+ "Web",
+ ]);
+ expect(fieldValueJson("date", "2026-10-15")).toBe("2026-10-15");
+ });
+
+ it("treats empty strings and empty arrays as not set", () => {
+ expect(fieldValueJson("text", "")).toBeNull();
+ expect(fieldValueJson("multiselect", "[]")).toBeNull();
+ expect(formatFieldValue("text", null)).toBeNull();
+ });
+
+ it("formats values for people", () => {
+ expect(formatFieldValue("boolean", "true")).toBe("Yes");
+ expect(formatFieldValue("multiselect", '["iOS","Web"]')).toBe("iOS, Web");
+ });
+});
diff --git a/packages/cli/src/fields/field-value.ts b/packages/cli/src/fields/field-value.ts
new file mode 100644
index 000000000..67c7c3e15
--- /dev/null
+++ b/packages/cli/src/fields/field-value.ts
@@ -0,0 +1,158 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+import { parseDateInput } from "../tasks/parse-date.js";
+
+export type FieldDefinition = {
+ readonly name: string;
+ readonly type: string;
+ readonly options: ReadonlyArray<string>;
+};
+
+export type FieldJsonValue = string | number | boolean | string[] | null;
+
+const TRUE_WORDS = new Set(["true", "yes", "y", "on", "1"]);
+const FALSE_WORDS = new Set(["false", "no", "n", "off", "0"]);
+
+function invalid(field: FieldDefinition, message: string, hint: string) {
+ return Result.fail(
+ new InvalidArgument({ message: `${field.name}: ${message}`, hint }),
+ );
+}
+
+function localDay(iso: string): string {
+ const date = new Date(iso);
+ const pad = (value: number) => String(value).padStart(2, "0");
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
+}
+
+function matchOption(
+ options: ReadonlyArray<string>,
+ input: string,
+): string | undefined {
+ const wanted = input.trim();
+ return (
+ options.find((option) => option === wanted) ??
+ options.find((option) => option.toLowerCase() === wanted.toLowerCase())
+ );
+}
+
+export function parseFieldValue(
+ field: FieldDefinition,
+ input: string,
+ now: Date,
+): Result.Result<string, InvalidArgument> {
+ const value = input.trim();
+ if (value === "") {
+ return invalid(
+ field,
+ "the value is empty.",
+ "Pass a value, or --clear to remove it.",
+ );
+ }
+ switch (field.type) {
+ case "number":
+ return Number.isFinite(Number(value))
+ ? Result.succeed(value)
+ : invalid(
+ field,
+ `"${value}" is not a number.`,
+ "Use a number such as 3 or 2.5.",
+ );
+ case "boolean": {
+ const word = value.toLowerCase();
+ if (TRUE_WORDS.has(word)) return Result.succeed("true");
+ if (FALSE_WORDS.has(word)) return Result.succeed("false");
+ return invalid(
+ field,
+ `"${value}" is not yes or no.`,
+ "Use true or false (or yes or no).",
+ );
+ }
+ case "date": {
+ const parsed = parseDateInput(value, now, field.name);
+ return Result.isSuccess(parsed)
+ ? Result.succeed(localDay(parsed.success))
+ : invalid(
+ field,
+ `"${value}" is not a date.`,
+ "Use YYYY-MM-DD, today, tomorrow, or +3d.",
+ );
+ }
+ case "dropdown": {
+ const option = matchOption(field.options, value);
+ return option
+ ? Result.succeed(option)
+ : invalid(
+ field,
+ `"${value}" is not one of the options.`,
+ `Use one of: ${field.options.join(", ")}.`,
+ );
+ }
+ case "multiselect": {
+ const parts = value
+ .split(",")
+ .map((part) => part.trim())
+ .filter(Boolean);
+ const unknown = parts.filter((part) => !matchOption(field.options, part));
+ if (unknown.length > 0 || parts.length === 0) {
+ return invalid(
+ field,
+ unknown.length > 0
+ ? `not an option: ${unknown.join(", ")}.`
+ : "pick at least one option.",
+ `Separate choices with commas. Options: ${field.options.join(", ")}.`,
+ );
+ }
+ const chosen = [
+ ...new Set(
+ parts.map((part) => matchOption(field.options, part) ?? part),
+ ),
+ ];
+ return Result.succeed(JSON.stringify(chosen));
+ }
+ default:
+ return Result.succeed(value);
+ }
+}
+
+export function isEmptyFieldValue(raw: string | null): boolean {
+ if (raw === null || raw.trim() === "") return true;
+ return raw.trim() === "[]";
+}
+
+export function fieldValueJson(
+ type: string,
+ raw: string | null,
+): FieldJsonValue {
+ if (raw === null || isEmptyFieldValue(raw)) return null;
+ if (type === "number") {
+ const number = Number(raw);
+ return Number.isFinite(number) ? number : raw;
+ }
+ if (type === "boolean") return raw === "true";
+ if (type === "multiselect") {
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ return Array.isArray(parsed)
+ ? parsed.filter((item): item is string => typeof item === "string")
+ : [raw];
+ } catch {
+ return [raw];
+ }
+ }
+ return raw;
+}
+
+export function formatJsonValue(value: FieldJsonValue): string | null {
+ if (value === null) return null;
+ if (typeof value === "boolean") return value ? "Yes" : "No";
+ if (Array.isArray(value)) return value.join(", ");
+ return String(value);
+}
+
+export function formatFieldValue(
+ type: string,
+ raw: string | null,
+): string | null {
+ return formatJsonValue(fieldValueJson(type, raw));
+}
diff --git a/packages/cli/src/fields/match-field.test.ts b/packages/cli/src/fields/match-field.test.ts
new file mode 100644
index 000000000..8463b2b5b
--- /dev/null
+++ b/packages/cli/src/fields/match-field.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { FieldJson } from "./field-json.js";
+import { matchField } from "./match-field.js";
+
+function field(id: string, name: string): FieldJson {
+ return {
+ id,
+ name,
+ type: "text",
+ required: false,
+ defaultValue: null,
+ options: [],
+ };
+}
+
+const estimate = field("f_est", "Story points");
+const platform = field("f_plat", "Platform");
+
+describe("matchField", () => {
+ it("matches the id, the name, or the name without spaces and case", () => {
+ expect(matchField([estimate, platform], "f_plat")).toBe(platform);
+ expect(matchField([estimate, platform], "story POINTS")).toBe(estimate);
+ expect(matchField([estimate, platform], "story-points")).toBe(estimate);
+ });
+
+ it("refuses names shared by two fields", () => {
+ const twin = field("f_twin", "platform");
+ expect(matchField([platform, twin], "Platform")).toBeUndefined();
+ expect(matchField([platform, twin], "f_twin")).toBe(twin);
+ });
+
+ it("returns nothing for blank or unknown references", () => {
+ expect(matchField([estimate], " ")).toBeUndefined();
+ expect(matchField([estimate], "Priority")).toBeUndefined();
+ });
+});
diff --git a/packages/cli/src/fields/match-field.ts b/packages/cli/src/fields/match-field.ts
new file mode 100644
index 000000000..08f3dd3b1
--- /dev/null
+++ b/packages/cli/src/fields/match-field.ts
@@ -0,0 +1,25 @@
+import type { FieldJson } from "./field-json.js";
+
+function compact(value: string): string {
+ return value
+ .normalize("NFKC")
+ .toLowerCase()
+ .replace(/[^\p{L}\p{N}]+/gu, "");
+}
+
+export function matchField(
+ fields: ReadonlyArray<FieldJson>,
+ reference: string,
+): FieldJson | undefined {
+ const trimmed = reference.trim();
+ const wanted = trimmed.toLowerCase();
+ const key = compact(trimmed);
+ if (key === "") return undefined;
+ const byName = fields.filter((field) => field.name.toLowerCase() === wanted);
+ const byKey = fields.filter((field) => compact(field.name) === key);
+ return (
+ fields.find((field) => field.id === trimmed) ??
+ (byName.length === 1 ? byName[0] : undefined) ??
+ (byKey.length === 1 ? byKey[0] : undefined)
+ );
+}
diff --git a/packages/cli/src/fields/render-field-change.ts b/packages/cli/src/fields/render-field-change.ts
new file mode 100644
index 000000000..7aeabf7c2
--- /dev/null
+++ b/packages/cli/src/fields/render-field-change.ts
@@ -0,0 +1,43 @@
+import { renderCell, text } from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+import { fieldTypeLabel } from "./field-types.js";
+
+export function renderFieldChange(
+ ui: Ui,
+ change: {
+ readonly verb: "Created" | "Deleted";
+ readonly name: string;
+ readonly type: string;
+ },
+): string[] {
+ const { theme, glyphs } = ui;
+ const detail =
+ change.verb === "Created"
+ ? fieldTypeLabel(change.type)
+ : "its values are gone from every task";
+ return [
+ "",
+ ` ${theme.success(glyphs.tick)} ${change.verb} the field ${theme.strong(change.name)} ${theme.muted(`${glyphs.separator} ${detail}`)}`,
+ "",
+ ];
+}
+
+export function renderFieldValueChange(
+ ui: Ui,
+ change: {
+ readonly label: string;
+ readonly url: string;
+ readonly field: string;
+ readonly value: string | null;
+ },
+): string[] {
+ const { theme, glyphs } = ui;
+ const id = renderCell([text(change.label, theme.strong, change.url)], ui);
+ const outcome =
+ change.value === null ? "cleared" : `set to ${theme.strong(change.value)}`;
+ return [
+ "",
+ ` ${theme.success(glyphs.tick)} ${id} ${theme.muted(glyphs.separator)} ${change.field} ${outcome}`,
+ "",
+ ];
+}
diff --git a/packages/cli/src/fields/render-field-list.ts b/packages/cli/src/fields/render-field-list.ts
new file mode 100644
index 000000000..cd105f607
--- /dev/null
+++ b/packages/cli/src/fields/render-field-list.ts
@@ -0,0 +1,56 @@
+import { type Cell, text } from "../render/cell.js";
+import { renderTable } from "../render/table.js";
+import type { Ui } from "../render/ui.js";
+import type { FieldJson } from "./field-json.js";
+import { fieldTypeLabel } from "./field-types.js";
+
+export function renderFieldList(
+ ui: Ui,
+ view: {
+ readonly projectName: string;
+ readonly fields: ReadonlyArray<FieldJson>;
+ },
+): string[] {
+ const { theme } = ui;
+ if (view.fields.length === 0) {
+ return [
+ "",
+ ` ${theme.muted(`No custom fields in ${view.projectName} yet.`)}`,
+ ` ${theme.muted("Add one with kaneo field create <name> --type text.")}`,
+ "",
+ ];
+ }
+ return [
+ "",
+ ...renderTable(
+ ui,
+ view.fields,
+ [
+ {
+ header: "Name",
+ minWidth: 10,
+ cell: (field): Cell => [text(field.name, theme.strong)],
+ },
+ {
+ header: "Type",
+ cell: (field): Cell => [text(fieldTypeLabel(field.type))],
+ },
+ {
+ header: "Options",
+ flex: true,
+ minWidth: 12,
+ optional: true,
+ cell: (field): Cell => [text(field.options.join(", "), theme.muted)],
+ },
+ {
+ header: "Required",
+ optional: true,
+ cell: (field): Cell =>
+ field.required ? [text("required", theme.warning)] : [],
+ },
+ ],
+ { width: ui.caps.columns, indent: 2 },
+ ),
+ "",
+ ];
+}
diff --git a/packages/cli/src/fields/render-fields.test.ts b/packages/cli/src/fields/render-fields.test.ts
new file mode 100644
index 000000000..04607afdc
--- /dev/null
+++ b/packages/cli/src/fields/render-fields.test.ts
@@ -0,0 +1,154 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import type { FieldJson } from "./field-json.js";
+import {
+ renderFieldChange,
+ renderFieldValueChange,
+} from "./render-field-change.js";
+import { renderFieldList } from "./render-field-list.js";
+import { renderTaskFields } from "./render-task-fields.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+const points: FieldJson = {
+ id: "f_points",
+ name: "Story points",
+ type: "number",
+ required: false,
+ defaultValue: null,
+ options: [],
+};
+
+const platform: FieldJson = {
+ id: "f_platform",
+ name: "Platform",
+ type: "multiselect",
+ required: true,
+ defaultValue: null,
+ options: ["iOS", "Android", "Web"],
+};
+
+describe("renderFieldList", () => {
+ it("shows name, type, options and required in 80 columns", () => {
+ const lines = renderFieldList(ui, {
+ projectName: "Kaneo Web",
+ fields: [points, platform],
+ });
+ expect(lines).toEqual([
+ "",
+ " Story points Number",
+ " Platform Multi-select iOS, Android, Web required",
+ "",
+ ]);
+ });
+
+ it("shortens long option lists instead of wrapping", () => {
+ const lines = renderFieldList(ui, {
+ projectName: "Kaneo Web",
+ fields: [
+ {
+ ...platform,
+ options: Array.from({ length: 20 }, (_, index) => `Option ${index}`),
+ },
+ ],
+ });
+ expect(lines[1]).toContain("…");
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(80);
+ });
+
+ it("explains how to add the first field", () => {
+ expect(
+ renderFieldList(ui, { projectName: "Kaneo Web", fields: [] }),
+ ).toEqual([
+ "",
+ " No custom fields in Kaneo Web yet.",
+ " Add one with kaneo field create <name> --type text.",
+ "",
+ ]);
+ });
+});
+
+describe("renderTaskFields", () => {
+ it("lists every field with its value or not set", () => {
+ expect(
+ renderTaskFields(ui, {
+ label: "KAN-12",
+ title: "Fix login redirect",
+ url: "http://localhost:5173/task",
+ fields: [
+ { id: "f_points", name: "Story points", type: "number", value: 5 },
+ {
+ id: "f_platform",
+ name: "Platform",
+ type: "multiselect",
+ value: null,
+ },
+ { id: "f_flag", name: "Blocked", type: "boolean", value: false },
+ ],
+ }),
+ ).toEqual([
+ "",
+ " KAN-12 · Fix login redirect",
+ "",
+ " Story points 5",
+ " Platform not set",
+ " Blocked No",
+ "",
+ ]);
+ });
+
+ it("truncates a long title to 80 columns", () => {
+ const lines = renderTaskFields(ui, {
+ label: "KAN-12",
+ title: "T".repeat(120),
+ url: "http://localhost:5173/task",
+ fields: [],
+ });
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(80);
+ expect(lines[3]).toBe(" This project has no custom fields.");
+ });
+});
+
+describe("field change lines", () => {
+ it("confirms create and delete", () => {
+ expect(
+ renderFieldChange(ui, {
+ verb: "Created",
+ name: "Platform",
+ type: "multiselect",
+ }),
+ ).toEqual(["", " ✓ Created the field Platform · Multi-select", ""]);
+ expect(
+ renderFieldChange(ui, {
+ verb: "Deleted",
+ name: "Platform",
+ type: "multiselect",
+ }),
+ ).toEqual([
+ "",
+ " ✓ Deleted the field Platform · its values are gone from every task",
+ "",
+ ]);
+ });
+
+ it("confirms setting and clearing a value", () => {
+ const base = { label: "KAN-12", url: "http://x", field: "Story points" };
+ expect(renderFieldValueChange(ui, { ...base, value: "5" })).toEqual([
+ "",
+ " ✓ KAN-12 · Story points set to 5",
+ "",
+ ]);
+ expect(renderFieldValueChange(ui, { ...base, value: null })).toEqual([
+ "",
+ " ✓ KAN-12 · Story points cleared",
+ "",
+ ]);
+ });
+});
diff --git a/packages/cli/src/fields/render-task-fields.ts b/packages/cli/src/fields/render-task-fields.ts
new file mode 100644
index 000000000..6aa41806d
--- /dev/null
+++ b/packages/cli/src/fields/render-task-fields.ts
@@ -0,0 +1,62 @@
+import { type Cell, renderCell, text } from "../render/cell.js";
+import { renderTable } from "../render/table.js";
+import type { Ui } from "../render/ui.js";
+import { stringWidth, truncate } from "../render/width.js";
+import { type FieldJsonValue, formatJsonValue } from "./field-value.js";
+
+export type TaskFieldJson = {
+ readonly id: string;
+ readonly name: string;
+ readonly type: string;
+ readonly value: FieldJsonValue;
+};
+
+export function renderTaskFields(
+ ui: Ui,
+ view: {
+ readonly label: string;
+ readonly title: string;
+ readonly url: string;
+ readonly fields: ReadonlyArray<TaskFieldJson>;
+ },
+): string[] {
+ const { theme, glyphs } = ui;
+ const head = ` ${renderCell([text(view.label, theme.strong, view.url)], ui)} ${theme.muted(glyphs.separator)} `;
+ const title = truncate(
+ view.title,
+ Math.max(ui.caps.columns - stringWidth(head), 8),
+ glyphs.ellipsis,
+ );
+ const lines = ["", `${head}${title}`, ""];
+ if (view.fields.length === 0) {
+ lines.push(` ${theme.muted("This project has no custom fields.")}`, "");
+ return lines;
+ }
+ lines.push(
+ ...renderTable(
+ ui,
+ view.fields,
+ [
+ {
+ header: "Field",
+ minWidth: 10,
+ cell: (field): Cell => [text(field.name, theme.muted)],
+ },
+ {
+ header: "Value",
+ flex: true,
+ minWidth: 12,
+ cell: (field): Cell => {
+ const value = formatJsonValue(field.value);
+ return value === null
+ ? [text("not set", theme.muted)]
+ : [text(value)];
+ },
+ },
+ ],
+ { width: ui.caps.columns, indent: 4 },
+ ),
+ "",
+ );
+ return lines;
+}
diff --git a/packages/cli/src/images/ansi-color.test.ts b/packages/cli/src/images/ansi-color.test.ts
new file mode 100644
index 000000000..0d9e7c3ce
--- /dev/null
+++ b/packages/cli/src/images/ansi-color.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from "vite-plus/test";
+import { colorParameters, nearest256 } from "./ansi-color.js";
+
+describe("nearest256", () => {
+ it("maps primaries onto the color cube", () => {
+ expect(nearest256([255, 0, 0])).toBe(196);
+ expect(nearest256([0, 0, 0])).toBe(16);
+ expect(nearest256([255, 255, 255])).toBe(231);
+ expect(nearest256([95, 135, 175])).toBe(67);
+ });
+
+ it("uses the gray ramp for grays between cube steps", () => {
+ expect(nearest256([118, 118, 118])).toBe(243);
+ expect(nearest256([238, 238, 238])).toBe(255);
+ });
+});
+
+describe("colorParameters", () => {
+ it("writes truecolor and 256 color parameters", () => {
+ expect(colorParameters("foreground", [1, 2, 3], 3)).toBe("38;2;1;2;3");
+ expect(colorParameters("background", [255, 0, 0], 2)).toBe("48;5;196");
+ });
+});
diff --git a/packages/cli/src/images/ansi-color.ts b/packages/cli/src/images/ansi-color.ts
new file mode 100644
index 000000000..2d8698951
--- /dev/null
+++ b/packages/cli/src/images/ansi-color.ts
@@ -0,0 +1,42 @@
+import type { Rgb } from "./rgba.js";
+
+const CUBE = [0, 95, 135, 175, 215, 255];
+
+function nearestCubeIndex(value: number): number {
+ let best = 0;
+ for (let index = 1; index < CUBE.length; index++) {
+ if (
+ Math.abs((CUBE[index] ?? 0) - value) < Math.abs((CUBE[best] ?? 0) - value)
+ ) {
+ best = index;
+ }
+ }
+ return best;
+}
+
+function distance(a: Rgb, b: Rgb): number {
+ return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;
+}
+
+export function nearest256(rgb: Rgb): number {
+ const [r, g, b] = rgb.map(nearestCubeIndex) as [number, number, number];
+ const cube: Rgb = [CUBE[r] ?? 0, CUBE[g] ?? 0, CUBE[b] ?? 0];
+ const average = (rgb[0] + rgb[1] + rgb[2]) / 3;
+ const step = Math.max(0, Math.min(23, Math.round((average - 8) / 10)));
+ const level = 8 + step * 10;
+ const gray: Rgb = [level, level, level];
+ return distance(rgb, gray) < distance(rgb, cube)
+ ? 232 + step
+ : 16 + 36 * r + 6 * g + b;
+}
+
+export function colorParameters(
+ layer: "foreground" | "background",
+ rgb: Rgb,
+ level: 2 | 3,
+): string {
+ const base = layer === "foreground" ? 38 : 48;
+ return level === 3
+ ? `${base};2;${rgb[0]};${rgb[1]};${rgb[2]}`
+ : `${base};5;${nearest256(rgb)}`;
+}
diff --git a/packages/cli/src/images/attachment-markdown.test.ts b/packages/cli/src/images/attachment-markdown.test.ts
new file mode 100644
index 000000000..70531144a
--- /dev/null
+++ b/packages/cli/src/images/attachment-markdown.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from "vite-plus/test";
+import {
+ altTextFor,
+ appendToDescription,
+ commentWithFiles,
+ fileMarkdown,
+ type UploadedFile,
+} from "./attachment-markdown.js";
+
+const shot: UploadedFile = {
+ name: "login_page-v2.png",
+ url: "http://localhost:1337/api/asset/a1",
+ contentType: "image/png",
+ size: 120,
+ kind: "image",
+};
+
+const spec: UploadedFile = {
+ name: 'spec "final".pdf',
+ url: "http://localhost:1337/api/asset/p1",
+ contentType: "application/pdf",
+ size: 2048,
+ kind: "attachment",
+};
+
+describe("fileMarkdown", () => {
+ it("writes images the way the editor does", () => {
+ expect(fileMarkdown(shot)).toBe(
+ "![login page v2](http://localhost:1337/api/asset/a1)",
+ );
+ expect(
+ fileMarkdown({ ...shot, name: "[draft].png", url: "http://h/a b" }),
+ ).toBe("![\\[draft\\]](<http://h/a b>)");
+ });
+
+ it("writes other files as attachment tags", () => {
+ expect(fileMarkdown(spec)).toBe(
+ '<kaneo-attachment url="http://localhost:1337/api/asset/p1" filename="spec &quot;final&quot;.pdf" mime-type="application/pdf" size="2048" />',
+ );
+ });
+});
+
+describe("altTextFor", () => {
+ it("turns a file name into readable alt text", () => {
+ expect(altTextFor("Screen_Shot-2026.png")).toBe("Screen Shot 2026");
+ });
+});
+
+describe("appendToDescription", () => {
+ it("adds the files after the existing text", () => {
+ expect(appendToDescription("Steps:\n\n1. Log in\n\n", [shot, spec])).toBe(
+ `Steps:\n\n1. Log in\n\n${fileMarkdown(shot)}\n\n${fileMarkdown(spec)}`,
+ );
+ });
+
+ it("uses the files alone for an empty description", () => {
+ expect(appendToDescription(null, [shot])).toBe(fileMarkdown(shot));
+ expect(appendToDescription(" \n", [shot])).toBe(fileMarkdown(shot));
+ });
+});
+
+describe("commentWithFiles", () => {
+ it("puts the message first", () => {
+ expect(commentWithFiles(" Broken here ", [shot])).toBe(
+ `Broken here\n\n${fileMarkdown(shot)}`,
+ );
+ expect(commentWithFiles("", [shot])).toBe(fileMarkdown(shot));
+ });
+});
diff --git a/packages/cli/src/images/attachment-markdown.ts b/packages/cli/src/images/attachment-markdown.ts
new file mode 100644
index 000000000..7a3ba0190
--- /dev/null
+++ b/packages/cli/src/images/attachment-markdown.ts
@@ -0,0 +1,56 @@
+export type UploadedFile = {
+ readonly name: string;
+ readonly url: string;
+ readonly contentType: string;
+ readonly size: number;
+ readonly kind: "image" | "attachment";
+};
+
+export function altTextFor(filename: string): string {
+ return filename
+ .replace(/\.[^/.]+$/u, "")
+ .replace(/[-_]+/gu, " ")
+ .trim();
+}
+
+function escapeHtml(value: string): string {
+ return value
+ .replace(/&/gu, "&amp;")
+ .replace(/"/gu, "&quot;")
+ .replace(/</gu, "&lt;")
+ .replace(/>/gu, "&gt;");
+}
+
+function escapeMarkdownText(value: string): string {
+ return value.replace(/[\\[\]]/gu, (character) => `\\${character}`);
+}
+
+function formatMarkdownUrl(value: string): string {
+ if (!/[\s<>]/u.test(value)) return value;
+ return `<${value.replace(/[<>]/gu, encodeURIComponent)}>`;
+}
+
+export function fileMarkdown(file: UploadedFile): string {
+ if (file.kind === "image") {
+ return `![${escapeMarkdownText(altTextFor(file.name))}](${formatMarkdownUrl(file.url)})`;
+ }
+ return `<kaneo-attachment url="${escapeHtml(file.url)}" filename="${escapeHtml(file.name)}" mime-type="${escapeHtml(file.contentType)}" size="${file.size}" />`;
+}
+
+export function appendToDescription(
+ current: string | null,
+ files: ReadonlyArray<UploadedFile>,
+): string {
+ const added = files.map(fileMarkdown).join("\n\n");
+ const existing = (current ?? "").replace(/\s+$/u, "");
+ return existing === "" ? added : `${existing}\n\n${added}`;
+}
+
+export function commentWithFiles(
+ message: string,
+ files: ReadonlyArray<UploadedFile>,
+): string {
+ return [message.trim(), ...files.map(fileMarkdown)]
+ .filter((part) => part !== "")
+ .join("\n\n");
+}
diff --git a/packages/cli/src/images/avatar-layout.test.ts b/packages/cli/src/images/avatar-layout.test.ts
new file mode 100644
index 000000000..f47ee4982
--- /dev/null
+++ b/packages/cli/src/images/avatar-layout.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { Avatar } from "./avatar.js";
+import { placeAvatar } from "./avatar-layout.js";
+
+const account = ["", " ✓ Ada", "", " Server kaneo.test", ""];
+
+const picture = (placement: Avatar["placement"]): Avatar => ({
+ lines: ["AAAA", "BBBB", "CCCC", "DDDD", "EEEE"],
+ columns: 4,
+ placement,
+});
+
+describe("placeAvatar", () => {
+ it("leaves the account alone without an avatar", () => {
+ expect(placeAvatar(account, null, 80)).toEqual(account);
+ });
+
+ it("puts block avatars to the left of the account", () => {
+ expect(placeAvatar(account, picture("beside"), 80)).toEqual([
+ "",
+ " AAAA",
+ " BBBB ✓ Ada",
+ " CCCC",
+ " DDDD Server kaneo.test",
+ " EEEE",
+ "",
+ ]);
+ });
+
+ it("stacks the avatar above in narrow terminals and for graphics", () => {
+ const above = [
+ "",
+ " AAAA",
+ " BBBB",
+ " CCCC",
+ " DDDD",
+ " EEEE",
+ ...account,
+ ];
+ expect(placeAvatar(account, picture("beside"), 40)).toEqual(above);
+ expect(placeAvatar(account, picture("above"), 120)).toEqual(above);
+ });
+});
diff --git a/packages/cli/src/images/avatar-layout.ts b/packages/cli/src/images/avatar-layout.ts
new file mode 100644
index 000000000..6ab14dd3c
--- /dev/null
+++ b/packages/cli/src/images/avatar-layout.ts
@@ -0,0 +1,25 @@
+import type { Avatar } from "./avatar.js";
+import { besidePicture } from "./side-by-side.js";
+
+const INDENT = 2;
+const GAP = 3;
+const MIN_TEXT_COLUMNS = 40;
+
+export function placeAvatar(
+ lines: ReadonlyArray<string>,
+ avatar: Avatar | null,
+ columns: number,
+): string[] {
+ if (!avatar) return [...lines];
+ const fits = columns >= INDENT + avatar.columns + GAP + MIN_TEXT_COLUMNS;
+ if (avatar.placement === "beside" && fits) {
+ const body = lines.slice(1, -1).map((line) => line.replace(/^ {2}/u, ""));
+ return [
+ "",
+ ...besidePicture(avatar, body, { indent: INDENT, gap: GAP }),
+ "",
+ ];
+ }
+ const pad = " ".repeat(INDENT);
+ return ["", ...avatar.lines.map((line) => `${pad}${line}`), ...lines];
+}
diff --git a/packages/cli/src/images/avatar.ts b/packages/cli/src/images/avatar.ts
new file mode 100644
index 000000000..d6c2b2365
--- /dev/null
+++ b/packages/cli/src/images/avatar.ts
@@ -0,0 +1,38 @@
+import { Duration, Effect } from "effect";
+import { FetchHttpClient } from "effect/http";
+import { fetchImage } from "./fetch-image.js";
+import { imageArt } from "./image-art.js";
+import { currentImageTarget } from "./image-target.js";
+import type { Picture } from "./side-by-side.js";
+
+export type Avatar = Picture & {
+ readonly placement: "beside" | "above";
+};
+
+export const AVATAR_COLUMNS = 16;
+export const AVATAR_ROWS = 8;
+const AVATAR_TIMEOUT = Duration.seconds(3);
+
+const loadAvatarArt = Effect.fnUntraced(function* (image: string | null) {
+ if (!image) return null;
+ const target = yield* currentImageTarget;
+ if (target.protocol === "none") return null;
+ const fetched = yield* fetchImage(image).pipe(
+ Effect.timeoutOption(AVATAR_TIMEOUT),
+ );
+ if (fetched._tag === "None" || fetched.value._tag !== "Fetched") return null;
+ const art = yield* imageArt(fetched.value.bytes, target, {
+ maxColumns: AVATAR_COLUMNS,
+ maxRows: AVATAR_ROWS,
+ upscale: true,
+ });
+ if (art._tag !== "Art") return null;
+ return {
+ lines: art.lines,
+ columns: art.columns,
+ placement: target.protocol === "blocks" ? "beside" : "above",
+ } satisfies Avatar;
+});
+
+export const loadAvatar = (image: string | null) =>
+ loadAvatarArt(image).pipe(Effect.provide(FetchHttpClient.layer));
diff --git a/packages/cli/src/images/blocks.test.ts b/packages/cli/src/images/blocks.test.ts
new file mode 100644
index 000000000..b9ad7fbef
--- /dev/null
+++ b/packages/cli/src/images/blocks.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it } from "vite-plus/test";
+import { compositePixel, renderBlocks } from "./blocks.js";
+
+const RED = [255, 0, 0, 255];
+const BLUE = [0, 0, 255, 255];
+const CLEAR = [0, 0, 0, 0];
+
+function image(width: number, height: number, pixels: number[][]) {
+ return { width, height, data: new Uint8Array(pixels.flat()) };
+}
+
+describe("renderBlocks", () => {
+ it("draws two pixels per cell with the upper half block", () => {
+ const lines = renderBlocks(image(2, 2, [RED, BLUE, BLUE, RED]), {
+ columns: 2,
+ rows: 1,
+ level: 3,
+ background: null,
+ });
+ expect(lines).toEqual([
+ "\u001b[38;2;255;0;0;48;2;0;0;255m▀\u001b[38;2;0;0;255;48;2;255;0;0m▀\u001b[39;49m",
+ ]);
+ });
+
+ it("uses the nearest 256 colors at level 2", () => {
+ const lines = renderBlocks(image(1, 2, [RED, BLUE]), {
+ columns: 1,
+ rows: 1,
+ level: 2,
+ background: null,
+ });
+ expect(lines).toEqual(["\u001b[38;5;196;48;5;21m▀\u001b[39;49m"]);
+ });
+
+ it("leaves transparent pixels to the terminal background", () => {
+ const lines = renderBlocks(
+ image(3, 2, [CLEAR, RED, CLEAR, CLEAR, CLEAR, BLUE]),
+ { columns: 3, rows: 1, level: 3, background: null },
+ );
+ expect(lines).toEqual([
+ " \u001b[38;2;255;0;0m▀\u001b[38;2;0;0;255m▄\u001b[39;49m",
+ ]);
+ });
+
+ it("only changes colors when the next cell needs different ones", () => {
+ const lines = renderBlocks(image(2, 2, [RED, RED, BLUE, BLUE]), {
+ columns: 2,
+ rows: 1,
+ level: 3,
+ background: null,
+ });
+ expect(lines).toEqual(["\u001b[38;2;255;0;0;48;2;0;0;255m▀▀\u001b[39;49m"]);
+ });
+
+ it("scales the picture to the requested cells", () => {
+ const pixels = Array.from({ length: 16 }, () => RED);
+ const lines = renderBlocks(image(4, 4, pixels), {
+ columns: 2,
+ rows: 1,
+ level: 3,
+ background: null,
+ });
+ expect(lines).toEqual(["\u001b[38;2;255;0;0;48;2;255;0;0m▀▀\u001b[39;49m"]);
+ });
+});
+
+describe("compositePixel", () => {
+ const half = new Uint8Array([200, 100, 0, 128]);
+
+ it("blends partial alpha over a known background", () => {
+ expect(compositePixel(half, 0, [0, 0, 0])).toEqual([100, 50, 0]);
+ });
+
+ it("keeps mostly opaque pixels and drops mostly clear ones without one", () => {
+ expect(compositePixel(half, 0, null)).toEqual([200, 100, 0]);
+ expect(compositePixel(new Uint8Array([1, 2, 3, 100]), 0, null)).toBeNull();
+ expect(
+ compositePixel(new Uint8Array([1, 2, 3, 0]), 0, [9, 9, 9]),
+ ).toBeNull();
+ });
+});
diff --git a/packages/cli/src/images/blocks.ts b/packages/cli/src/images/blocks.ts
new file mode 100644
index 000000000..6a546f205
--- /dev/null
+++ b/packages/cli/src/images/blocks.ts
@@ -0,0 +1,114 @@
+import { colorParameters } from "./ansi-color.js";
+import type { CellSize } from "./cell-size.js";
+import { resizeRgba } from "./resize-rgba.js";
+import type { Rgb, RgbaImage } from "./rgba.js";
+
+export type BlockOptions = CellSize & {
+ readonly level: 2 | 3;
+ readonly background: Rgb | null;
+};
+
+type Pen = { foreground: string | null; background: string | null };
+
+const UPPER_HALF = "▀";
+const LOWER_HALF = "▄";
+
+function mix(color: number, background: number, alpha: number): number {
+ return Math.round(color * alpha + background * (1 - alpha));
+}
+
+export function compositePixel(
+ data: Uint8Array,
+ at: number,
+ background: Rgb | null,
+): Rgb | null {
+ const alpha = data[at + 3] ?? 0;
+ if (alpha === 0) return null;
+ const rgb: Rgb = [data[at] ?? 0, data[at + 1] ?? 0, data[at + 2] ?? 0];
+ if (alpha === 255) return rgb;
+ if (background === null) return alpha >= 128 ? rgb : null;
+ const weight = alpha / 255;
+ return [
+ mix(rgb[0], background[0], weight),
+ mix(rgb[1], background[1], weight),
+ mix(rgb[2], background[2], weight),
+ ];
+}
+
+function switchPen(pen: Pen, next: Pen): string {
+ const parameters: string[] = [];
+ if (next.foreground !== pen.foreground) {
+ parameters.push(next.foreground ?? "39");
+ }
+ if (next.background !== pen.background) {
+ parameters.push(next.background ?? "49");
+ }
+ pen.foreground = next.foreground;
+ pen.background = next.background;
+ return parameters.length > 0 ? `\u001b[${parameters.join(";")}m` : "";
+}
+
+function cell(
+ top: Rgb | null,
+ bottom: Rgb | null,
+ pen: Pen,
+ level: 2 | 3,
+): { readonly pen: Pen; readonly glyph: string } {
+ if (top && bottom) {
+ return {
+ pen: {
+ foreground: colorParameters("foreground", top, level),
+ background: colorParameters("background", bottom, level),
+ },
+ glyph: UPPER_HALF,
+ };
+ }
+ if (top || bottom) {
+ return {
+ pen: {
+ foreground: colorParameters(
+ "foreground",
+ (top ?? bottom) as Rgb,
+ level,
+ ),
+ background: null,
+ },
+ glyph: top ? UPPER_HALF : LOWER_HALF,
+ };
+ }
+ return { pen: { foreground: pen.foreground, background: null }, glyph: " " };
+}
+
+export function renderBlocks(
+ image: RgbaImage,
+ options: BlockOptions,
+): string[] {
+ const scaled = resizeRgba(image, options.columns, options.rows * 2);
+ const pixel = (x: number, y: number) =>
+ y < scaled.height
+ ? compositePixel(
+ scaled.data,
+ (y * scaled.width + x) * 4,
+ options.background,
+ )
+ : null;
+ const lines: string[] = [];
+ for (let row = 0; row < options.rows; row++) {
+ const pen: Pen = { foreground: null, background: null };
+ let line = "";
+ for (let x = 0; x < scaled.width; x++) {
+ const next = cell(
+ pixel(x, row * 2),
+ pixel(x, row * 2 + 1),
+ pen,
+ options.level,
+ );
+ line += switchPen(pen, next.pen) + next.glyph;
+ }
+ if (pen.foreground !== null || pen.background !== null) {
+ line += "\u001b[39;49m";
+ }
+ lines.push(line);
+ }
+ return lines;
+}
diff --git a/packages/cli/src/images/cell-size.ts b/packages/cli/src/images/cell-size.ts
new file mode 100644
index 000000000..f0b9c84ac
--- /dev/null
+++ b/packages/cli/src/images/cell-size.ts
@@ -0,0 +1,4 @@
+export type CellSize = {
+ readonly columns: number;
+ readonly rows: number;
+};
diff --git a/packages/cli/src/images/content-type.test.ts b/packages/cli/src/images/content-type.test.ts
new file mode 100644
index 000000000..d1ba7a40a
--- /dev/null
+++ b/packages/cli/src/images/content-type.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from "vite-plus/test";
+import { contentTypeFor, isInlineImageType } from "./content-type.js";
+import { pngBytes, solid } from "./image-fixtures.js";
+
+const text = new TextEncoder().encode("hello");
+
+describe("contentTypeFor", () => {
+ it("trusts the bytes over the extension for images", () => {
+ expect(
+ contentTypeFor("shot.jpg", pngBytes(1, 1, solid(1, 1, [0, 0, 0, 255]))),
+ ).toBe("image/png");
+ });
+
+ it("falls back to the extension", () => {
+ expect(contentTypeFor("notes.PDF", text)).toBe("application/pdf");
+ expect(contentTypeFor("logo.svg", text)).toBe("image/svg+xml");
+ expect(contentTypeFor("archive.tar.gz", text)).toBe("application/gzip");
+ expect(contentTypeFor("README", text)).toBe("application/octet-stream");
+ });
+});
+
+describe("isInlineImageType", () => {
+ it("matches the image types the server shows inline", () => {
+ expect(isInlineImageType("image/png")).toBe(true);
+ expect(isInlineImageType("IMAGE/WEBP")).toBe(true);
+ expect(isInlineImageType("image/svg+xml")).toBe(false);
+ expect(isInlineImageType("application/pdf")).toBe(false);
+ });
+});
diff --git a/packages/cli/src/images/content-type.ts b/packages/cli/src/images/content-type.ts
new file mode 100644
index 000000000..abe4b2aa8
--- /dev/null
+++ b/packages/cli/src/images/content-type.ts
@@ -0,0 +1,69 @@
+import { imageInfo } from "./image-info.js";
+
+const INLINE_IMAGE_TYPES = new Set([
+ "image/apng",
+ "image/avif",
+ "image/gif",
+ "image/heic",
+ "image/heif",
+ "image/jpeg",
+ "image/jpg",
+ "image/png",
+ "image/webp",
+]);
+
+const TYPES_BY_EXTENSION: Readonly<Record<string, string>> = {
+ apng: "image/apng",
+ avif: "image/avif",
+ gif: "image/gif",
+ heic: "image/heic",
+ heif: "image/heif",
+ jpeg: "image/jpeg",
+ jpg: "image/jpeg",
+ png: "image/png",
+ webp: "image/webp",
+ svg: "image/svg+xml",
+ pdf: "application/pdf",
+ json: "application/json",
+ zip: "application/zip",
+ gz: "application/gzip",
+ csv: "text/csv",
+ md: "text/markdown",
+ txt: "text/plain",
+ log: "text/plain",
+ html: "text/html",
+ xml: "application/xml",
+ yaml: "application/yaml",
+ yml: "application/yaml",
+ mp4: "video/mp4",
+ mov: "video/quicktime",
+ webm: "video/webm",
+ mp3: "audio/mpeg",
+ wav: "audio/wav",
+ doc: "application/msword",
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ xls: "application/vnd.ms-excel",
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ ppt: "application/vnd.ms-powerpoint",
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
+};
+
+const SNIFFED_TYPES = {
+ png: "image/png",
+ jpeg: "image/jpeg",
+ gif: "image/gif",
+ webp: "image/webp",
+} as const;
+
+export function isInlineImageType(contentType: string): boolean {
+ return INLINE_IMAGE_TYPES.has(contentType.toLowerCase());
+}
+
+export function contentTypeFor(filename: string, bytes: Uint8Array): string {
+ const format = imageInfo(bytes).format;
+ if (format in SNIFFED_TYPES) {
+ return SNIFFED_TYPES[format as keyof typeof SNIFFED_TYPES];
+ }
+ const extension = /\.([^./\\]+)$/u.exec(filename)?.[1]?.toLowerCase() ?? "";
+ return TYPES_BY_EXTENSION[extension] ?? "application/octet-stream";
+}
diff --git a/packages/cli/src/images/decode-image.test.ts b/packages/cli/src/images/decode-image.test.ts
new file mode 100644
index 000000000..5cf4f935c
--- /dev/null
+++ b/packages/cli/src/images/decode-image.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from "vite-plus/test";
+import { canDecode, decodeImage } from "./decode-image.js";
+import { jpegBytes, pngBytes, solid } from "./image-fixtures.js";
+import { imageInfo } from "./image-info.js";
+
+describe("decodeImage", () => {
+ it("decodes PNG pixels, alpha included", async () => {
+ const bytes = pngBytes(2, 1, [255, 0, 0, 255, 0, 0, 255, 0]);
+ const image = await decodeImage(bytes, imageInfo(bytes));
+ expect(image.width).toBe(2);
+ expect(image.height).toBe(1);
+ expect([...image.data]).toEqual([255, 0, 0, 255, 0, 0, 255, 0]);
+ });
+
+ it("decodes JPEG pixels to RGBA", async () => {
+ const bytes = jpegBytes(8, 8, solid(8, 8, [0, 200, 0, 255]));
+ const image = await decodeImage(bytes, imageInfo(bytes));
+ expect(image.width).toBe(8);
+ expect(image.data.length).toBe(8 * 8 * 4);
+ const [r = 0, g = 0, b = 0, a = 0] = image.data;
+ expect(Math.abs(r - 0)).toBeLessThan(8);
+ expect(Math.abs(g - 200)).toBeLessThan(8);
+ expect(Math.abs(b - 0)).toBeLessThan(8);
+ expect(a).toBe(255);
+ });
+
+ it("refuses formats it cannot decode and huge images", async () => {
+ expect(canDecode({ format: "gif", width: 1, height: 1 })).toBe(false);
+ expect(canDecode({ format: "png", width: 10_000, height: 10_000 })).toBe(
+ false,
+ );
+ await expect(
+ decodeImage(new Uint8Array([1]), { format: "webp", width: 1, height: 1 }),
+ ).rejects.toThrow();
+ });
+});
diff --git a/packages/cli/src/images/decode-image.ts b/packages/cli/src/images/decode-image.ts
new file mode 100644
index 000000000..484e16950
--- /dev/null
+++ b/packages/cli/src/images/decode-image.ts
@@ -0,0 +1,50 @@
+import type { ImageInfo } from "./image-info.js";
+import type { RgbaImage } from "./rgba.js";
+
+export const MAX_DECODE_PIXELS = 40_000_000;
+
+function asBuffer(bytes: Uint8Array): Buffer {
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+}
+
+async function decodePng(bytes: Uint8Array): Promise<RgbaImage> {
+ const { PNG } = await import("pngjs");
+ const png = PNG.sync.read(asBuffer(bytes));
+ return {
+ width: png.width,
+ height: png.height,
+ data: new Uint8Array(
+ png.data.buffer,
+ png.data.byteOffset,
+ png.data.byteLength,
+ ),
+ };
+}
+
+async function decodeJpeg(bytes: Uint8Array): Promise<RgbaImage> {
+ const { decode } = await import("jpeg-js");
+ const jpeg = decode(bytes, {
+ useTArray: true,
+ formatAsRGBA: true,
+ maxResolutionInMP: MAX_DECODE_PIXELS / 1_000_000,
+ maxMemoryUsageInMB: 512,
+ });
+ return { width: jpeg.width, height: jpeg.height, data: jpeg.data };
+}
+
+export function canDecode(info: ImageInfo): boolean {
+ return (
+ (info.format === "png" || info.format === "jpeg") &&
+ info.width > 0 &&
+ info.height > 0 &&
+ info.width * info.height <= MAX_DECODE_PIXELS
+ );
+}
+
+export async function decodeImage(
+ bytes: Uint8Array,
+ info: ImageInfo,
+): Promise<RgbaImage> {
+ if (!canDecode(info)) throw new Error(`cannot decode ${info.format}`);
+ return info.format === "png" ? decodePng(bytes) : decodeJpeg(bytes);
+}
diff --git a/packages/cli/src/images/extract-images.test.ts b/packages/cli/src/images/extract-images.test.ts
new file mode 100644
index 000000000..94696e5ea
--- /dev/null
+++ b/packages/cli/src/images/extract-images.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from "vite-plus/test";
+import { extractImages } from "./extract-images.js";
+
+describe("extractImages", () => {
+ it("finds Markdown images with titles and escaped alt text", () => {
+ expect(
+ extractImages(
+ 'Intro ![Login \\[old\\] page](/api/asset/a1 "Before") and ![](https://cdn.test/b.png)',
+ ),
+ ).toEqual([
+ { url: "/api/asset/a1", alt: "Login [old] page" },
+ { url: "https://cdn.test/b.png", alt: "" },
+ ]);
+ });
+
+ it("reads angle bracket destinations and balanced parentheses", () => {
+ expect(
+ extractImages(
+ "![a](<https://cdn.test/my shot.png>) ![b](https://cdn.test/x_(1).png)",
+ ),
+ ).toEqual([
+ { url: "https://cdn.test/my shot.png", alt: "a" },
+ { url: "https://cdn.test/x_(1).png", alt: "b" },
+ ]);
+ });
+
+ it("finds resized images written as img tags", () => {
+ expect(
+ extractImages(
+ '<img src="/api/asset/a1" alt="Tom &amp; Jerry" width="320" />\n<img alt=\'x\' src=\'https://cdn.test/c.png\'>',
+ ),
+ ).toEqual([
+ { url: "/api/asset/a1", alt: "Tom & Jerry" },
+ { url: "https://cdn.test/c.png", alt: "x" },
+ ]);
+ });
+
+ it("includes image attachments and skips other files", () => {
+ expect(
+ extractImages(
+ [
+ '<kaneo-attachment url="http://localhost:1337/api/asset/p1" filename="spec.pdf" mime-type="application/pdf" size="10" />',
+ '<kaneo-attachment url="http://localhost:1337/api/asset/i1" filename="diagram.png" mime-type="image/png" size="20" />',
+ '<kaneo-attachment url="http://localhost:1337/api/asset/i2" filename="photo.JPG" />',
+ ].join("\n"),
+ ),
+ ).toEqual([
+ { url: "http://localhost:1337/api/asset/i1", alt: "diagram.png" },
+ { url: "http://localhost:1337/api/asset/i2", alt: "photo.JPG" },
+ ]);
+ });
+
+ it("keeps document order across syntaxes", () => {
+ expect(
+ extractImages(
+ '<img src="/api/asset/1">\n\n![two](/api/asset/2)\n\n<kaneo-attachment url="/api/asset/3" filename="3.png" mime-type="image/png" />',
+ ).map((image) => image.url),
+ ).toEqual(["/api/asset/1", "/api/asset/2", "/api/asset/3"]);
+ });
+
+ it("ignores code, comments, duplicates and unusable links", () => {
+ const markdown = [
+ "```md",
+ "![in a fence](/api/asset/fenced)",
+ "```",
+ "Inline `![code](/api/asset/code)` stays text.",
+ "<!-- ![hidden](/api/asset/hidden) -->",
+ "![dup](/api/asset/1) ![dup again](/api/asset/1)",
+ "![data](data:image/png;base64,AAAA) ![js](javascript:alert(1))",
+ ].join("\n");
+ expect(extractImages(markdown)).toEqual([
+ { url: "/api/asset/1", alt: "dup" },
+ ]);
+ });
+
+ it("returns nothing for text without images", () => {
+ expect(extractImages("Just [a link](https://kaneo.app).")).toEqual([]);
+ });
+});
diff --git a/packages/cli/src/images/extract-images.ts b/packages/cli/src/images/extract-images.ts
new file mode 100644
index 000000000..f920a9d63
--- /dev/null
+++ b/packages/cli/src/images/extract-images.ts
@@ -0,0 +1,121 @@
+export type ImageRef = {
+ readonly url: string;
+ readonly alt: string;
+};
+
+type Found = ImageRef & { readonly index: number };
+
+const FENCE = /^\s{0,3}(`{3,}|~{3,})/u;
+const INLINE_CODE = /(`+)[\s\S]*?\1/gu;
+const COMMENT = /<!--[\s\S]*?-->/gu;
+const MARKDOWN_IMAGE =
+ /!\[((?:\\[\s\S]|[^\\\]])*)\]\(\s*(<[^>\n]*>|(?:[^\s()]|\([^\s()]*\))+)(?:\s+(?:"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'))?\s*\)/gu;
+const IMG_TAG = /<img\b[^>]*>/giu;
+const ATTACHMENT_TAG = /<kaneo-attachment\b[^>]*>/giu;
+const LINKABLE = /^(?:https?:\/\/|\/)/iu;
+const IMAGE_EXTENSION = /\.(?:apng|avif|gif|heic|heif|jpe?g|png|webp)$/iu;
+const ENTITIES: Readonly<Record<string, string>> = {
+ amp: "&",
+ lt: "<",
+ gt: ">",
+ quot: '"',
+ apos: "'",
+ nbsp: " ",
+};
+
+function decodeEntities(text: string): string {
+ return text.replace(
+ /&(#x[0-9a-f]{1,6}|#\d{1,7}|[a-z]+);/giu,
+ (whole, name: string) => {
+ const code = /^#x/iu.test(name)
+ ? Number.parseInt(name.slice(2), 16)
+ : name.startsWith("#")
+ ? Number(name.slice(1))
+ : Number.NaN;
+ if (Number.isInteger(code) && code > 0 && code <= 0x10ffff) {
+ return String.fromCodePoint(code);
+ }
+ return ENTITIES[name.toLowerCase()] ?? whole;
+ },
+ );
+}
+
+function attribute(tag: string, name: string): string {
+ const match = new RegExp(
+ `\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>/]+))`,
+ "iu",
+ ).exec(tag);
+ return decodeEntities(match?.[1] ?? match?.[2] ?? match?.[3] ?? "").trim();
+}
+
+function withoutCode(markdown: string): string {
+ let fence: string | null = null;
+ const kept: string[] = [];
+ for (const line of markdown.replace(/\r\n?/gu, "\n").split("\n")) {
+ if (fence !== null) {
+ if (line.trim().startsWith(fence)) fence = null;
+ kept.push("");
+ continue;
+ }
+ const start = FENCE.exec(line);
+ if (start) {
+ fence = start[1] ?? "```";
+ kept.push("");
+ continue;
+ }
+ kept.push(line);
+ }
+ return kept.join("\n").replace(COMMENT, "").replace(INLINE_CODE, "");
+}
+
+function markdownUrl(destination: string): string {
+ return destination.startsWith("<")
+ ? destination.slice(1, -1).trim()
+ : destination;
+}
+
+function unescapeMarkdown(text: string): string {
+ return text.replace(/\\([\p{P}\p{S}])/gu, "$1");
+}
+
+function isImageAttachment(tag: string): boolean {
+ const mimeType = attribute(tag, "mime-type").toLowerCase();
+ if (mimeType !== "") return mimeType.startsWith("image/");
+ return IMAGE_EXTENSION.test(attribute(tag, "filename"));
+}
+
+export function extractImages(markdown: string): ImageRef[] {
+ const text = withoutCode(markdown);
+ const found: Found[] = [];
+ for (const match of text.matchAll(MARKDOWN_IMAGE)) {
+ found.push({
+ index: match.index,
+ url: markdownUrl(match[2] ?? ""),
+ alt: unescapeMarkdown(match[1] ?? "").trim(),
+ });
+ }
+ for (const match of text.matchAll(IMG_TAG)) {
+ found.push({
+ index: match.index,
+ url: attribute(match[0], "src"),
+ alt: attribute(match[0], "alt"),
+ });
+ }
+ for (const match of text.matchAll(ATTACHMENT_TAG)) {
+ if (!isImageAttachment(match[0])) continue;
+ found.push({
+ index: match.index,
+ url: attribute(match[0], "url"),
+ alt: attribute(match[0], "filename"),
+ });
+ }
+ const seen = new Set<string>();
+ return found
+ .sort((a, b) => a.index - b.index)
+ .filter(({ url }) => {
+ if (!LINKABLE.test(url) || seen.has(url)) return false;
+ seen.add(url);
+ return true;
+ })
+ .map(({ url, alt }) => ({ url, alt }));
+}
diff --git a/packages/cli/src/images/fetch-image.test.ts b/packages/cli/src/images/fetch-image.test.ts
new file mode 100644
index 000000000..e2d23d8b9
--- /dev/null
+++ b/packages/cli/src/images/fetch-image.test.ts
@@ -0,0 +1,127 @@
+import { Effect, Layer } from "effect";
+import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http";
+import { describe, expect, it } from "vite-plus/test";
+import { testSession } from "../testing/test-layers.js";
+import { fetchImage, MAX_IMAGE_BYTES } from "./fetch-image.js";
+
+type Seen = {
+ readonly url: string;
+ readonly authorization: string | undefined;
+};
+
+function image(bytes: ArrayLike<number>, type = "image/png") {
+ return new Response(new Uint8Array(bytes), {
+ headers: { "content-type": type },
+ });
+}
+
+function run(raw: string, respond: (seen: Seen) => Response | "fail") {
+ const seen: Seen[] = [];
+ const client = Layer.succeed(
+ HttpClient.HttpClient,
+ HttpClient.make((request, url) => {
+ const entry = {
+ url: url.toString(),
+ authorization: request.headers.authorization,
+ };
+ seen.push(entry);
+ const response = respond(entry);
+ return response === "fail"
+ ? Effect.fail(
+ new HttpClientError.HttpClientError({
+ reason: new HttpClientError.TransportError({ request }),
+ }),
+ )
+ : Effect.succeed(HttpClientResponse.fromWeb(request, response));
+ }),
+ );
+ const result = Effect.runPromise(
+ fetchImage(raw).pipe(Effect.provide(Layer.merge(client, testSession()))),
+ );
+ return { seen, result };
+}
+
+describe("fetchImage", () => {
+ it("sends the token to assets on the signed-in server", async () => {
+ const { seen, result } = run("/api/asset/a1", () => image([1, 2, 3]));
+ const fetched = await result;
+ expect(seen).toEqual([
+ {
+ url: "https://kaneo.test/api/asset/a1",
+ authorization: "Bearer test-token",
+ },
+ ]);
+ expect(fetched._tag).toBe("Fetched");
+ if (fetched._tag === "Fetched") {
+ expect([...fetched.bytes]).toEqual([1, 2, 3]);
+ expect(fetched.contentType).toBe("image/png");
+ }
+ });
+
+ it("never sends the token to third-party hosts", async () => {
+ const { seen, result } = run("https://cdn.test/a.png", () => image([1]));
+ expect((await result)._tag).toBe("Fetched");
+ expect(seen[0]?.authorization).toBeUndefined();
+ });
+
+ it("drops the token when a redirect leaves the server", async () => {
+ const { seen, result } = run("/api/asset/a1", ({ url }) =>
+ url.startsWith("https://kaneo.test")
+ ? new Response(null, {
+ status: 302,
+ headers: { location: "https://bucket.test/a1?sig=1" },
+ })
+ : image([7]),
+ );
+ expect((await result)._tag).toBe("Fetched");
+ expect(seen).toEqual([
+ {
+ url: "https://kaneo.test/api/asset/a1",
+ authorization: "Bearer test-token",
+ },
+ { url: "https://bucket.test/a1?sig=1", authorization: undefined },
+ ]);
+ });
+
+ it("turns failures into reasons instead of errors", async () => {
+ const reason = async (raw: string, respond: () => Response | "fail") => {
+ const fetched = await run(raw, respond).result;
+ return fetched._tag === "Unavailable" ? fetched.reason : null;
+ };
+ expect(
+ await reason("/api/asset/x", () => new Response("", { status: 404 })),
+ ).toBe("not found");
+ expect(
+ await reason("/api/asset/x", () => new Response("", { status: 403 })),
+ ).toBe("no access");
+ expect(
+ await reason(
+ "/api/asset/x",
+ () =>
+ new Response("<html>", { headers: { "content-type": "text/html" } }),
+ ),
+ ).toBe("not an image");
+ expect(await reason("/api/asset/x", () => "fail")).toBe("could not load");
+ expect(await reason("data:image/png;base64,AA", () => image([1]))).toBe(
+ "unsupported link",
+ );
+ });
+
+ it("stops reading images over 10 MB", async () => {
+ const declared = await run(
+ "/api/asset/x",
+ () =>
+ new Response(new Uint8Array(1), {
+ headers: {
+ "content-type": "image/png",
+ "content-length": String(MAX_IMAGE_BYTES + 1),
+ },
+ }),
+ ).result;
+ expect(declared).toMatchObject({ reason: "larger than 10 MB" });
+ const streamed = await run("/api/asset/x", () =>
+ image(new Uint8Array(MAX_IMAGE_BYTES + 1)),
+ ).result;
+ expect(streamed).toMatchObject({ reason: "larger than 10 MB" });
+ });
+});
diff --git a/packages/cli/src/images/fetch-image.ts b/packages/cli/src/images/fetch-image.ts
new file mode 100644
index 000000000..09672f73a
--- /dev/null
+++ b/packages/cli/src/images/fetch-image.ts
@@ -0,0 +1,136 @@
+import { Duration, Effect, Option, Redacted, Stream } from "effect";
+import {
+ FetchHttpClient,
+ HttpClient,
+ HttpClientRequest,
+ type HttpClientResponse,
+} from "effect/http";
+import { Session } from "../services/session.js";
+import { resolveImageUrl, sendsToken } from "./image-url.js";
+
+export type FetchedImage =
+ | {
+ readonly _tag: "Fetched";
+ readonly url: string;
+ readonly bytes: Uint8Array;
+ readonly contentType: string;
+ }
+ | {
+ readonly _tag: "Unavailable";
+ readonly url: string;
+ readonly reason: string;
+ };
+
+export const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
+const FETCH_TIMEOUT = Duration.seconds(15);
+const MAX_REDIRECTS = 3;
+const TOO_LARGE = "larger than 10 MB";
+
+function unavailable(url: string, reason: string): FetchedImage {
+ return { _tag: "Unavailable", url, reason };
+}
+
+function statusReason(status: number): string {
+ if (status === 401 || status === 403) return "no access";
+ if (status === 404) return "not found";
+ return `HTTP ${status}`;
+}
+
+function redirectTarget(location: string | undefined, from: URL): URL | null {
+ if (!location) return null;
+ try {
+ const next = new URL(location, from);
+ return next.protocol === "http:" || next.protocol === "https:"
+ ? next
+ : null;
+ } catch {
+ return null;
+ }
+}
+
+function concat(chunks: ReadonlyArray<Uint8Array>, total: number) {
+ const bytes = new Uint8Array(total);
+ let offset = 0;
+ for (const chunk of chunks) {
+ bytes.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return bytes;
+}
+
+const readCapped = (response: HttpClientResponse.HttpClientResponse) =>
+ Effect.gen(function* () {
+ const state = { chunks: [] as Uint8Array[], total: 0, exceeded: false };
+ yield* response.stream.pipe(
+ Stream.runForEachWhile((chunk) =>
+ Effect.sync(() => {
+ state.total += chunk.byteLength;
+ if (state.total > MAX_IMAGE_BYTES) {
+ state.exceeded = true;
+ return false;
+ }
+ state.chunks.push(chunk);
+ return true;
+ }),
+ ),
+ );
+ return state.exceeded ? null : concat(state.chunks, state.total);
+ });
+
+export const fetchImage = Effect.fnUntraced(function* (raw: string) {
+ const session = yield* Session;
+ const client = yield* HttpClient.HttpClient;
+ const resolved = resolveImageUrl(raw, session.apiUrl);
+ if (resolved === null) return unavailable(raw, "unsupported link");
+ const href = resolved.href;
+ const token = Option.getOrUndefined(session.credentials)?.token;
+
+ const load = (url: URL, hops: number): Effect.Effect<FetchedImage, unknown> =>
+ Effect.gen(function* () {
+ let request = HttpClientRequest.get(url).pipe(
+ HttpClientRequest.accept("image/*"),
+ );
+ if (token && sendsToken(url, session.apiUrl)) {
+ request = HttpClientRequest.bearerToken(request, Redacted.value(token));
+ }
+ const response = yield* client.execute(request);
+ if (response.status >= 300 && response.status < 400) {
+ const next = redirectTarget(response.headers.location, url);
+ if (next === null || hops >= MAX_REDIRECTS) {
+ return unavailable(href, "redirected too often");
+ }
+ return yield* load(next, hops + 1);
+ }
+ if (response.status < 200 || response.status >= 300) {
+ return unavailable(href, statusReason(response.status));
+ }
+ const contentType = (response.headers["content-type"] ?? "")
+ .split(";")[0]
+ ?.trim()
+ .toLowerCase();
+ if (!contentType?.startsWith("image/")) {
+ return unavailable(href, "not an image");
+ }
+ if (Number(response.headers["content-length"]) > MAX_IMAGE_BYTES) {
+ return unavailable(href, TOO_LARGE);
+ }
+ const bytes = yield* readCapped(response);
+ if (bytes === null) return unavailable(href, TOO_LARGE);
+ return { _tag: "Fetched", url: href, bytes, contentType } as const;
+ });
+
+ return yield* load(resolved, 0).pipe(
+ Effect.timeout(FETCH_TIMEOUT),
+ Effect.catch((error) =>
+ Effect.succeed(
+ unavailable(
+ href,
+ (error as { _tag?: unknown })._tag === "TimeoutError"
+ ? "timed out"
+ : "could not load",
+ ),
+ ),
+ ),
+ Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }),
+ );
+});
diff --git a/packages/cli/src/images/fit-image.test.ts b/packages/cli/src/images/fit-image.test.ts
new file mode 100644
index 000000000..464cde0bc
--- /dev/null
+++ b/packages/cli/src/images/fit-image.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from "vite-plus/test";
+import {
+ BLOCK_CELL,
+ fitImage,
+ GRAPHICS_CELL,
+ imageColumns,
+} from "./fit-image.js";
+
+const limits = { maxColumns: 64, maxRows: 20 };
+
+describe("imageColumns", () => {
+ it("caps the width at 64 columns and the space after the indent", () => {
+ expect(imageColumns(200, 2)).toBe(64);
+ expect(imageColumns(40, 4)).toBe(36);
+ expect(imageColumns(1, 4)).toBe(1);
+ });
+});
+
+describe("fitImage", () => {
+ it("keeps the aspect ratio with cells twice as tall as wide", () => {
+ expect(
+ fitImage({ width: 1600, height: 800 }, { ...limits, ...GRAPHICS_CELL }),
+ ).toEqual({ columns: 64, rows: 16 });
+ });
+
+ it("stops tall images at the row limit", () => {
+ expect(
+ fitImage({ width: 800, height: 1600 }, { ...limits, ...GRAPHICS_CELL }),
+ ).toEqual({ columns: 20, rows: 20 });
+ });
+
+ it("never scales small images up beyond their pixels in blocks", () => {
+ expect(
+ fitImage({ width: 4, height: 4 }, { ...limits, ...BLOCK_CELL }),
+ ).toEqual({ columns: 4, rows: 2 });
+ expect(
+ fitImage({ width: 1, height: 1 }, { ...limits, ...BLOCK_CELL }),
+ ).toEqual({ columns: 1, rows: 1 });
+ });
+
+ it("scales small images up to the limits when asked", () => {
+ expect(
+ fitImage(
+ { width: 32, height: 32 },
+ { maxColumns: 16, maxRows: 8, ...GRAPHICS_CELL, upscale: true },
+ ),
+ ).toEqual({ columns: 16, rows: 8 });
+ });
+
+ it("treats graphics cells as about 8 by 16 pixels", () => {
+ expect(
+ fitImage({ width: 80, height: 80 }, { ...limits, ...GRAPHICS_CELL }),
+ ).toEqual({ columns: 10, rows: 5 });
+ });
+});
diff --git a/packages/cli/src/images/fit-image.ts b/packages/cli/src/images/fit-image.ts
new file mode 100644
index 000000000..844591d5b
--- /dev/null
+++ b/packages/cli/src/images/fit-image.ts
@@ -0,0 +1,53 @@
+import type { CellSize } from "./cell-size.js";
+
+export type FitOptions = {
+ readonly maxColumns: number;
+ readonly maxRows: number;
+ readonly pixelsPerColumn: number;
+ readonly pixelsPerRow: number;
+ readonly upscale?: boolean;
+};
+
+export const MAX_IMAGE_COLUMNS = 64;
+export const MAX_IMAGE_ROWS = 20;
+
+export const BLOCK_CELL = { pixelsPerColumn: 1, pixelsPerRow: 2 } as const;
+export const GRAPHICS_CELL = { pixelsPerColumn: 8, pixelsPerRow: 16 } as const;
+
+export function imageColumns(terminalColumns: number, indent: number): number {
+ return Math.max(1, Math.min(terminalColumns - indent, MAX_IMAGE_COLUMNS));
+}
+
+export function fitImage(
+ pixels: { readonly width: number; readonly height: number },
+ options: FitOptions,
+): CellSize {
+ const width = Math.max(1, pixels.width);
+ const height = Math.max(1, pixels.height);
+ const columnLimit = Math.max(
+ 1,
+ options.upscale
+ ? options.maxColumns
+ : Math.min(
+ options.maxColumns,
+ Math.ceil(width / options.pixelsPerColumn),
+ ),
+ );
+ const rowLimit = Math.max(
+ 1,
+ options.upscale
+ ? options.maxRows
+ : Math.min(options.maxRows, Math.ceil(height / options.pixelsPerRow)),
+ );
+ const rowsPerColumn = height / width / 2;
+ let columns = columnLimit;
+ let rows = columns * rowsPerColumn;
+ if (rows > rowLimit) {
+ rows = rowLimit;
+ columns = rows / rowsPerColumn;
+ }
+ return {
+ columns: Math.min(columnLimit, Math.max(1, Math.round(columns))),
+ rows: Math.min(rowLimit, Math.max(1, Math.round(rows))),
+ };
+}
diff --git a/packages/cli/src/images/image-art.test.ts b/packages/cli/src/images/image-art.test.ts
new file mode 100644
index 000000000..469b546e7
--- /dev/null
+++ b/packages/cli/src/images/image-art.test.ts
@@ -0,0 +1,91 @@
+import { Effect } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { imageArt } from "./image-art.js";
+import { jpegBytes, pngBytes, solid } from "./image-fixtures.js";
+import type { ImageTarget } from "./image-target.js";
+
+const target = (
+ protocol: ImageTarget["protocol"],
+ tmux = false,
+): ImageTarget => ({
+ protocol,
+ tmux,
+ level: 3,
+ background: null,
+});
+
+const red = pngBytes(4, 4, solid(4, 4, [255, 0, 0, 255]));
+const gif = new Uint8Array([
+ ...Array.from("GIF89a", (character) => character.charCodeAt(0)),
+ 16,
+ 0,
+ 16,
+ 0,
+]);
+
+const run = (bytes: Uint8Array, at: ImageTarget, maxColumns = 64) =>
+ Effect.runPromise(imageArt(bytes, at, { maxColumns }));
+
+describe("imageArt", () => {
+ it("draws decoded pixels as blocks without scaling them up", async () => {
+ const art = await run(red, target("blocks"));
+ expect(art).toEqual({
+ _tag: "Art",
+ columns: 4,
+ rows: 2,
+ lines: [
+ "\u001b[38;2;255;0;0;48;2;255;0;0m▀▀▀▀\u001b[39;49m",
+ "\u001b[38;2;255;0;0;48;2;255;0;0m▀▀▀▀\u001b[39;49m",
+ ],
+ });
+ });
+
+ it("sends PNG bytes to kitty as they are", async () => {
+ const art = await run(red, target("kitty"));
+ expect(art._tag).toBe("Art");
+ if (art._tag === "Art") {
+ expect(art.lines).toHaveLength(1);
+ expect(art.lines[0]).toContain("a=T,f=100,t=d,c=1,r=1,q=2");
+ }
+ });
+
+ it("decodes JPEG for kitty and sends compressed pixels", async () => {
+ const jpeg = jpegBytes(32, 16, solid(32, 16, [0, 0, 255, 255]));
+ const art = await run(jpeg, target("kitty", true));
+ expect(art._tag).toBe("Art");
+ if (art._tag === "Art") {
+ expect(art.lines[0]).toContain("a=T,f=32,s=32,v=16,o=z,t=d,c=4,r=1");
+ expect(art.lines[0]?.startsWith("\u001bPtmux;")).toBe(true);
+ }
+ });
+
+ it("sends any common format to iTerm2", async () => {
+ const art = await run(gif, target("iterm"));
+ expect(art._tag).toBe("Art");
+ if (art._tag === "Art") {
+ expect(art.lines[0]).toContain("width=2;height=1;preserveAspectRatio=1");
+ }
+ });
+
+ it("explains formats that cannot be shown", async () => {
+ expect(await run(gif, target("blocks"))).toEqual({
+ _tag: "Unsupported",
+ reason: "GIF cannot be shown here",
+ });
+ expect(await run(gif, target("kitty"))).toMatchObject({
+ _tag: "Unsupported",
+ });
+ expect(
+ await run(new TextEncoder().encode("<svg></svg>"), target("iterm")),
+ ).toEqual({ _tag: "Unsupported", reason: "SVG cannot be shown here" });
+ });
+
+ it("reports images it cannot decode", async () => {
+ const broken = new Uint8Array(red);
+ broken.fill(0, 40);
+ expect(await run(broken, target("blocks"))).toEqual({
+ _tag: "Unsupported",
+ reason: "could not decode",
+ });
+ });
+});
diff --git a/packages/cli/src/images/image-art.ts b/packages/cli/src/images/image-art.ts
new file mode 100644
index 000000000..3c97e54dd
--- /dev/null
+++ b/packages/cli/src/images/image-art.ts
@@ -0,0 +1,125 @@
+import { Effect } from "effect";
+import { renderBlocks } from "./blocks.js";
+import type { CellSize } from "./cell-size.js";
+import { canDecode, decodeImage } from "./decode-image.js";
+import {
+ BLOCK_CELL,
+ fitImage,
+ GRAPHICS_CELL,
+ MAX_IMAGE_ROWS,
+} from "./fit-image.js";
+import { FORMAT_LABELS, type ImageInfo, imageInfo } from "./image-info.js";
+import type { ImageTarget } from "./image-target.js";
+import { encodeIterm } from "./iterm.js";
+import { encodeKitty } from "./kitty.js";
+import { resizeRgba } from "./resize-rgba.js";
+import type { RgbaImage } from "./rgba.js";
+
+export type ImageArt =
+ | ({
+ readonly _tag: "Art";
+ readonly lines: ReadonlyArray<string>;
+ } & CellSize)
+ | { readonly _tag: "Unsupported"; readonly reason: string };
+
+export type ArtOptions = {
+ readonly maxColumns: number;
+ readonly maxRows?: number;
+ readonly upscale?: boolean;
+};
+
+const ITERM_FORMATS = new Set(["png", "jpeg", "gif", "webp"]);
+const KITTY_PIXELS_PER_COLUMN = 16;
+const KITTY_PIXELS_PER_ROW = 32;
+
+function unsupported(reason: string): ImageArt {
+ return { _tag: "Unsupported", reason };
+}
+
+function art(lines: ReadonlyArray<string>, size: CellSize): ImageArt {
+ return { _tag: "Art", lines, ...size };
+}
+
+function notShown(info: ImageInfo): ImageArt {
+ return unsupported(`${FORMAT_LABELS[info.format]} cannot be shown here`);
+}
+
+const decode = (bytes: Uint8Array, info: ImageInfo) =>
+ Effect.tryPromise(() => decodeImage(bytes, info)).pipe(Effect.option);
+
+const deflate = (bytes: Uint8Array) =>
+ Effect.promise(async () => {
+ const { deflateSync } = await import("node:zlib");
+ return new Uint8Array(deflateSync(bytes));
+ });
+
+function shrinkForKitty(image: RgbaImage, size: CellSize): RgbaImage {
+ const scale = Math.min(
+ 1,
+ (size.columns * KITTY_PIXELS_PER_COLUMN) / image.width,
+ (size.rows * KITTY_PIXELS_PER_ROW) / image.height,
+ );
+ return scale < 1
+ ? resizeRgba(image, image.width * scale, image.height * scale)
+ : image;
+}
+
+export const imageArt = Effect.fnUntraced(function* (
+ bytes: Uint8Array,
+ target: ImageTarget,
+ options: ArtOptions,
+) {
+ const info = imageInfo(bytes);
+ const limits = {
+ maxColumns: options.maxColumns,
+ maxRows: options.maxRows ?? MAX_IMAGE_ROWS,
+ };
+ const graphicsSize = () =>
+ fitImage(info, { ...limits, ...GRAPHICS_CELL, upscale: options.upscale });
+ const tmux = { tmux: target.tmux };
+
+ switch (target.protocol) {
+ case "none":
+ return unsupported("images are turned off");
+ case "iterm": {
+ if (!ITERM_FORMATS.has(info.format) || info.width === 0) {
+ return notShown(info);
+ }
+ const size = graphicsSize();
+ return art([encodeIterm(bytes, size, tmux)], size);
+ }
+ case "kitty": {
+ if (info.format === "png" && info.width > 0) {
+ const size = graphicsSize();
+ return art([encodeKitty({ format: "png", bytes }, size, tmux)], size);
+ }
+ if (info.format !== "jpeg" || !canDecode(info)) return notShown(info);
+ const decoded = yield* decode(bytes, info);
+ if (decoded._tag === "None") return unsupported("could not decode");
+ const size = graphicsSize();
+ const pixels = shrinkForKitty(decoded.value, size);
+ const payload = {
+ format: "rgba",
+ width: pixels.width,
+ height: pixels.height,
+ bytes: yield* deflate(pixels.data),
+ compressed: true,
+ } as const;
+ return art([encodeKitty(payload, size, tmux)], size);
+ }
+ case "blocks": {
+ if (!canDecode(info)) return notShown(info);
+ const decoded = yield* decode(bytes, info);
+ if (decoded._tag === "None") return unsupported("could not decode");
+ const size = fitImage(decoded.value, { ...limits, ...BLOCK_CELL });
+ return art(
+ renderBlocks(decoded.value, {
+ ...size,
+ level: target.level,
+ background: target.background,
+ }),
+ size,
+ );
+ }
+ }
+});
diff --git a/packages/cli/src/images/image-fixtures.ts b/packages/cli/src/images/image-fixtures.ts
new file mode 100644
index 000000000..f674a8bb6
--- /dev/null
+++ b/packages/cli/src/images/image-fixtures.ts
@@ -0,0 +1,30 @@
+import { encode } from "jpeg-js";
+import { PNG } from "pngjs";
+
+export function pngBytes(
+ width: number,
+ height: number,
+ rgba: ReadonlyArray<number>,
+): Uint8Array<ArrayBuffer> {
+ const png = new PNG({ width, height });
+ png.data.set(rgba);
+ return new Uint8Array(PNG.sync.write(png));
+}
+
+export function jpegBytes(
+ width: number,
+ height: number,
+ rgba: ReadonlyArray<number>,
+): Uint8Array<ArrayBuffer> {
+ return new Uint8Array(
+ encode({ width, height, data: Buffer.from(rgba) }, 95).data,
+ );
+}
+
+export function solid(
+ width: number,
+ height: number,
+ pixel: readonly [number, number, number, number],
+): number[] {
+ return Array.from({ length: width * height }, () => pixel).flat();
+}
diff --git a/packages/cli/src/images/image-info.test.ts b/packages/cli/src/images/image-info.test.ts
new file mode 100644
index 000000000..813a20dcb
--- /dev/null
+++ b/packages/cli/src/images/image-info.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from "vite-plus/test";
+import { jpegBytes, pngBytes, solid } from "./image-fixtures.js";
+import { imageInfo } from "./image-info.js";
+
+function bytes(...parts: ReadonlyArray<string | ArrayLike<number>>) {
+ return new Uint8Array(
+ parts.flatMap((part) =>
+ typeof part === "string"
+ ? Array.from(part, (character) => character.charCodeAt(0))
+ : Array.from(part),
+ ),
+ );
+}
+
+describe("imageInfo", () => {
+ it("reads PNG and JPEG dimensions", () => {
+ expect(imageInfo(pngBytes(3, 2, solid(3, 2, [1, 2, 3, 255])))).toEqual({
+ format: "png",
+ width: 3,
+ height: 2,
+ });
+ expect(imageInfo(jpegBytes(17, 9, solid(17, 9, [9, 9, 9, 255])))).toEqual({
+ format: "jpeg",
+ width: 17,
+ height: 9,
+ });
+ });
+
+ it("reads GIF dimensions", () => {
+ expect(imageInfo(bytes("GIF89a", [0x40, 0x01, 0xf0, 0x00]))).toEqual({
+ format: "gif",
+ width: 320,
+ height: 240,
+ });
+ });
+
+ it("reads lossy, lossless and extended WebP dimensions", () => {
+ const header = (chunk: string) =>
+ bytes("RIFF", [0, 0, 0, 0], "WEBP", chunk);
+ expect(
+ imageInfo(
+ bytes(
+ header("VP8 "),
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0x80, 0x02, 0xe0, 0x01],
+ ),
+ ),
+ ).toEqual({ format: "webp", width: 640, height: 480 });
+ expect(
+ imageInfo(
+ bytes(header("VP8L"), [0, 0, 0, 0, 0x2f], [0x3f, 0xc0, 0x13, 0x00]),
+ ),
+ ).toEqual({ format: "webp", width: 64, height: 80 });
+ expect(
+ imageInfo(
+ bytes(header("VP8X"), [0, 0, 0, 0, 0, 0, 0, 0], [99, 0, 0, 49, 0, 0]),
+ ),
+ ).toEqual({ format: "webp", width: 100, height: 50 });
+ });
+
+ it("recognises SVG documents", () => {
+ expect(
+ imageInfo(bytes('<?xml version="1.0"?>\n<svg width="1"/>')).format,
+ ).toBe("svg");
+ expect(imageInfo(bytes("<svg xmlns='x'></svg>")).format).toBe("svg");
+ });
+
+ it("reports anything else as unknown", () => {
+ expect(imageInfo(bytes("hello"))).toEqual({
+ format: "unknown",
+ width: 0,
+ height: 0,
+ });
+ });
+});
diff --git a/packages/cli/src/images/image-info.ts b/packages/cli/src/images/image-info.ts
new file mode 100644
index 000000000..9ed1959b5
--- /dev/null
+++ b/packages/cli/src/images/image-info.ts
@@ -0,0 +1,134 @@
+export type ImageFormat = "png" | "jpeg" | "gif" | "webp" | "svg" | "unknown";
+
+export type ImageInfo = {
+ readonly format: ImageFormat;
+ readonly width: number;
+ readonly height: number;
+};
+
+const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
+
+function ascii(bytes: Uint8Array, start: number, length: number): string {
+ return String.fromCharCode(...bytes.subarray(start, start + length));
+}
+
+function be16(bytes: Uint8Array, at: number): number {
+ return ((bytes[at] ?? 0) << 8) | (bytes[at + 1] ?? 0);
+}
+
+function be32(bytes: Uint8Array, at: number): number {
+ return (be16(bytes, at) * 0x10000 + be16(bytes, at + 2)) >>> 0;
+}
+
+function le16(bytes: Uint8Array, at: number): number {
+ return (bytes[at] ?? 0) | ((bytes[at + 1] ?? 0) << 8);
+}
+
+function le24(bytes: Uint8Array, at: number): number {
+ return le16(bytes, at) | ((bytes[at + 2] ?? 0) << 16);
+}
+
+function info(format: ImageFormat, width = 0, height = 0): ImageInfo {
+ return { format, width, height };
+}
+
+function pngInfo(bytes: Uint8Array): ImageInfo | null {
+ if (!PNG_SIGNATURE.every((byte, index) => bytes[index] === byte)) return null;
+ return info("png", be32(bytes, 16), be32(bytes, 20));
+}
+
+function isStartOfFrame(marker: number): boolean {
+ return (
+ marker >= 0xc0 &&
+ marker <= 0xcf &&
+ marker !== 0xc4 &&
+ marker !== 0xc8 &&
+ marker !== 0xcc
+ );
+}
+
+function jpegInfo(bytes: Uint8Array): ImageInfo | null {
+ if (bytes[0] !== 0xff || bytes[1] !== 0xd8) return null;
+ let at = 2;
+ while (at + 3 < bytes.length) {
+ if (bytes[at] !== 0xff) {
+ at += 1;
+ continue;
+ }
+ const marker = bytes[at + 1] ?? 0;
+ if (marker === 0xff) {
+ at += 1;
+ continue;
+ }
+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) {
+ at += 2;
+ continue;
+ }
+ if (isStartOfFrame(marker)) {
+ return info("jpeg", be16(bytes, at + 7), be16(bytes, at + 5));
+ }
+ at += 2 + be16(bytes, at + 2);
+ }
+ return info("jpeg");
+}
+
+function gifInfo(bytes: Uint8Array): ImageInfo | null {
+ const signature = ascii(bytes, 0, 6);
+ if (signature !== "GIF87a" && signature !== "GIF89a") return null;
+ return info("gif", le16(bytes, 6), le16(bytes, 8));
+}
+
+function webpInfo(bytes: Uint8Array): ImageInfo | null {
+ if (ascii(bytes, 0, 4) !== "RIFF" || ascii(bytes, 8, 4) !== "WEBP") {
+ return null;
+ }
+ const chunk = ascii(bytes, 12, 4);
+ if (chunk === "VP8 ") {
+ return info("webp", le16(bytes, 26) & 0x3fff, le16(bytes, 28) & 0x3fff);
+ }
+ if (chunk === "VP8L") {
+ const b0 = bytes[21] ?? 0;
+ const b1 = bytes[22] ?? 0;
+ const b2 = bytes[23] ?? 0;
+ const b3 = bytes[24] ?? 0;
+ return info(
+ "webp",
+ 1 + (b0 | ((b1 & 0x3f) << 8)),
+ 1 + ((b1 >> 6) | (b2 << 2) | ((b3 & 0x0f) << 10)),
+ );
+ }
+ if (chunk === "VP8X") {
+ return info("webp", 1 + le24(bytes, 24), 1 + le24(bytes, 27));
+ }
+ return info("webp");
+}
+
+function svgInfo(bytes: Uint8Array): ImageInfo | null {
+ const head = new TextDecoder()
+ .decode(bytes.subarray(0, 1024))
+ .replace(/^/u, "")
+ .trimStart();
+ if (/^<svg[\s>]/iu.test(head)) return info("svg");
+ if (/^<\?xml/iu.test(head) && /<svg[\s>]/iu.test(head)) return info("svg");
+ return null;
+}
+
+export function imageInfo(bytes: Uint8Array): ImageInfo {
+ return (
+ pngInfo(bytes) ??
+ jpegInfo(bytes) ??
+ gifInfo(bytes) ??
+ webpInfo(bytes) ??
+ svgInfo(bytes) ??
+ info("unknown")
+ );
+}
+
+export const FORMAT_LABELS: Readonly<Record<ImageFormat, string>> = {
+ png: "PNG",
+ jpeg: "JPEG",
+ gif: "GIF",
+ webp: "WebP",
+ svg: "SVG",
+ unknown: "this format",
+};
diff --git a/packages/cli/src/images/image-protocol.test.ts b/packages/cli/src/images/image-protocol.test.ts
new file mode 100644
index 000000000..221567a33
--- /dev/null
+++ b/packages/cli/src/images/image-protocol.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, it } from "vite-plus/test";
+import { detectImageProtocol, type ImageContext } from "./image-protocol.js";
+
+const tty = { isTTY: true, columns: 100 };
+const piped = { isTTY: false, columns: undefined };
+const truecolor: ImageContext = { json: false, color: 3, unicode: true };
+
+describe("detectImageProtocol", () => {
+ it("uses the kitty graphics protocol in kitty and Ghostty", () => {
+ expect(detectImageProtocol({ TERM: "xterm-kitty" }, tty, truecolor)).toBe(
+ "kitty",
+ );
+ expect(detectImageProtocol({ KITTY_WINDOW_ID: "1" }, tty, truecolor)).toBe(
+ "kitty",
+ );
+ expect(
+ detectImageProtocol({ TERM_PROGRAM: "ghostty" }, tty, truecolor),
+ ).toBe("kitty");
+ expect(detectImageProtocol({ TERM: "xterm-ghostty" }, tty, truecolor)).toBe(
+ "kitty",
+ );
+ });
+
+ it("uses iTerm2 inline images in iTerm2 and WezTerm", () => {
+ expect(
+ detectImageProtocol({ TERM_PROGRAM: "iTerm.app" }, tty, truecolor),
+ ).toBe("iterm");
+ expect(detectImageProtocol({ LC_TERMINAL: "iTerm2" }, tty, truecolor)).toBe(
+ "iterm",
+ );
+ expect(
+ detectImageProtocol({ TERM_PROGRAM: "WezTerm" }, tty, truecolor),
+ ).toBe("iterm");
+ });
+
+ it("draws blocks in the VS Code terminal, where inline images are opt-in", () => {
+ expect(
+ detectImageProtocol(
+ { TERM_PROGRAM: "vscode", TERM_PROGRAM_VERSION: "1.99.0" },
+ tty,
+ truecolor,
+ ),
+ ).toBe("blocks");
+ });
+
+ it("falls back to blocks with 256 colors and to none with fewer", () => {
+ const env = { TERM: "xterm-256color" };
+ expect(detectImageProtocol(env, tty, { ...truecolor, color: 2 })).toBe(
+ "blocks",
+ );
+ expect(detectImageProtocol(env, tty, { ...truecolor, color: 1 })).toBe(
+ "none",
+ );
+ expect(
+ detectImageProtocol(env, tty, { ...truecolor, unicode: false }),
+ ).toBe("none");
+ });
+
+ it("prefers blocks inside tmux, even in kitty", () => {
+ expect(
+ detectImageProtocol(
+ { TMUX: "/tmp/tmux-501/default,1,0", TERM: "xterm-kitty" },
+ tty,
+ truecolor,
+ ),
+ ).toBe("blocks");
+ expect(
+ detectImageProtocol({ TMUX: "/tmp/tmux", LC_TERMINAL: "iTerm2" }, tty, {
+ ...truecolor,
+ color: 1,
+ }),
+ ).toBe("none");
+ });
+
+ it("shows nothing for JSON, pipes, dumb terminals and KANEO_IMAGES=off", () => {
+ const env = { TERM_PROGRAM: "iTerm.app" };
+ expect(detectImageProtocol(env, tty, { ...truecolor, json: true })).toBe(
+ "none",
+ );
+ expect(detectImageProtocol(env, piped, truecolor)).toBe("none");
+ expect(detectImageProtocol({ ...env, TERM: "dumb" }, tty, truecolor)).toBe(
+ "none",
+ );
+ for (const value of ["off", "0", "false", "OFF"]) {
+ expect(
+ detectImageProtocol({ ...env, KANEO_IMAGES: value }, tty, truecolor),
+ ).toBe("none");
+ }
+ });
+
+ it("lets KANEO_IMAGES force a protocol, except in JSON mode", () => {
+ expect(
+ detectImageProtocol(
+ { KANEO_IMAGES: "kitty", TMUX: "/tmp/tmux" },
+ tty,
+ truecolor,
+ ),
+ ).toBe("kitty");
+ expect(
+ detectImageProtocol({ KANEO_IMAGES: "iterm" }, piped, truecolor),
+ ).toBe("iterm");
+ expect(
+ detectImageProtocol({ KANEO_IMAGES: "blocks", TERM: "dumb" }, tty, {
+ ...truecolor,
+ color: 0,
+ }),
+ ).toBe("blocks");
+ expect(
+ detectImageProtocol({ KANEO_IMAGES: "kitty" }, tty, {
+ ...truecolor,
+ json: true,
+ }),
+ ).toBe("none");
+ expect(
+ detectImageProtocol(
+ { KANEO_IMAGES: "sixel", TERM_PROGRAM: "WezTerm" },
+ tty,
+ truecolor,
+ ),
+ ).toBe("iterm");
+ });
+});
diff --git a/packages/cli/src/images/image-protocol.ts b/packages/cli/src/images/image-protocol.ts
new file mode 100644
index 000000000..8f951e336
--- /dev/null
+++ b/packages/cli/src/images/image-protocol.ts
@@ -0,0 +1,67 @@
+import type {
+ ColorLevel,
+ Environment,
+ StreamInfo,
+} from "../render/capabilities.js";
+
+export type ImageProtocol = "kitty" | "iterm" | "blocks" | "none";
+
+export type ImageContext = {
+ readonly json: boolean;
+ readonly color: ColorLevel;
+ readonly unicode: boolean;
+};
+
+const OFF = new Set(["off", "0", "false", "no", "none"]);
+const FORCED = new Set<ImageProtocol>(["kitty", "iterm", "blocks"]);
+
+function forcedProtocol(env: Environment): ImageProtocol | "off" | undefined {
+ const setting = env.KANEO_IMAGES?.trim().toLowerCase();
+ if (!setting) return undefined;
+ if (OFF.has(setting)) return "off";
+ return FORCED.has(setting as ImageProtocol)
+ ? (setting as ImageProtocol)
+ : undefined;
+}
+
+export function inTmux(env: Environment): boolean {
+ return Boolean(env.TMUX);
+}
+
+function inMultiplexer(env: Environment): boolean {
+ return inTmux(env) || Boolean(env.STY) || Boolean(env.ZELLIJ);
+}
+
+function speaksKitty(env: Environment): boolean {
+ return (
+ env.TERM === "xterm-kitty" ||
+ env.TERM === "xterm-ghostty" ||
+ env.TERM_PROGRAM === "ghostty" ||
+ Boolean(env.KITTY_WINDOW_ID)
+ );
+}
+
+function speaksIterm(env: Environment): boolean {
+ return (
+ env.TERM_PROGRAM === "iTerm.app" ||
+ env.TERM_PROGRAM === "WezTerm" ||
+ env.LC_TERMINAL === "iTerm2"
+ );
+}
+
+export function detectImageProtocol(
+ env: Environment,
+ stream: StreamInfo,
+ context: ImageContext,
+): ImageProtocol {
+ if (context.json) return "none";
+ const forced = forcedProtocol(env);
+ if (forced === "off") return "none";
+ if (forced) return forced;
+ if (!stream.isTTY || env.TERM === "dumb") return "none";
+ const blocks = context.color >= 2 && context.unicode ? "blocks" : "none";
+ if (inMultiplexer(env)) return blocks;
+ if (speaksKitty(env)) return "kitty";
+ if (speaksIterm(env)) return "iterm";
+ return blocks;
+}
diff --git a/packages/cli/src/images/image-target.test.ts b/packages/cli/src/images/image-target.test.ts
new file mode 100644
index 000000000..6803ade68
--- /dev/null
+++ b/packages/cli/src/images/image-target.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from "vite-plus/test";
+import { resolveImageTarget } from "./image-target.js";
+
+const tty = { isTTY: true, columns: 80 };
+
+describe("resolveImageTarget", () => {
+ it("wraps forced graphics in tmux passthrough", () => {
+ const target = resolveImageTarget(
+ { KANEO_IMAGES: "kitty", TMUX: "/tmp/tmux" },
+ tty,
+ { json: false, color: 3, unicode: true },
+ );
+ expect(target).toMatchObject({ protocol: "kitty", tmux: true });
+ });
+
+ it("does not wrap blocks, which are plain text", () => {
+ const target = resolveImageTarget({ TMUX: "/tmp/tmux" }, tty, {
+ json: false,
+ color: 3,
+ unicode: true,
+ });
+ expect(target).toMatchObject({ protocol: "blocks", tmux: false });
+ });
+
+ it("uses 256 colors only when that is all the terminal has", () => {
+ const at = (color: 0 | 1 | 2 | 3) =>
+ resolveImageTarget({ KANEO_IMAGES: "blocks" }, tty, {
+ json: false,
+ color,
+ unicode: true,
+ }).level;
+ expect(at(2)).toBe(2);
+ expect(at(3)).toBe(3);
+ expect(at(0)).toBe(3);
+ });
+
+ it("reads the terminal background from COLORFGBG", () => {
+ const target = resolveImageTarget({ COLORFGBG: "0;15" }, tty, {
+ json: false,
+ color: 3,
+ unicode: true,
+ });
+ expect(target.background).toEqual([255, 255, 255]);
+ expect(
+ resolveImageTarget({}, tty, { json: false, color: 3, unicode: true })
+ .background,
+ ).toBeNull();
+ });
+});
diff --git a/packages/cli/src/images/image-target.ts b/packages/cli/src/images/image-target.ts
new file mode 100644
index 000000000..1ec158385
--- /dev/null
+++ b/packages/cli/src/images/image-target.ts
@@ -0,0 +1,43 @@
+import { Effect } from "effect";
+import { Output } from "../output/output.js";
+import type { Environment, StreamInfo } from "../render/capabilities.js";
+import { CliEnvironment } from "../services/cli-environment.js";
+import {
+ detectImageProtocol,
+ type ImageContext,
+ type ImageProtocol,
+ inTmux,
+} from "./image-protocol.js";
+import type { Rgb } from "./rgba.js";
+import { terminalBackground } from "./terminal-background.js";
+
+export type ImageTarget = {
+ readonly protocol: ImageProtocol;
+ readonly tmux: boolean;
+ readonly level: 2 | 3;
+ readonly background: Rgb | null;
+};
+
+export function resolveImageTarget(
+ env: Environment,
+ stream: StreamInfo,
+ context: ImageContext,
+): ImageTarget {
+ const protocol = detectImageProtocol(env, stream, context);
+ return {
+ protocol,
+ tmux: (protocol === "kitty" || protocol === "iterm") && inTmux(env),
+ level: context.color === 2 ? 2 : 3,
+ background: terminalBackground(env),
+ };
+}
+
+export const currentImageTarget = Effect.gen(function* () {
+ const output = yield* Output;
+ const environment = yield* CliEnvironment;
+ return resolveImageTarget(environment.env, environment.stdout, {
+ json: output.mode === "json",
+ color: output.ui.caps.color,
+ unicode: output.ui.caps.unicode,
+ });
+});
diff --git a/packages/cli/src/images/image-url.test.ts b/packages/cli/src/images/image-url.test.ts
new file mode 100644
index 000000000..6e8009429
--- /dev/null
+++ b/packages/cli/src/images/image-url.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from "vite-plus/test";
+import { absoluteImageUrl, resolveImageUrl, sendsToken } from "./image-url.js";
+
+const api = "https://kaneo.example.com";
+
+describe("resolveImageUrl", () => {
+ it("resolves API paths against the server URL", () => {
+ expect(resolveImageUrl("/api/user/avatar/a1", api)?.href).toBe(
+ "https://kaneo.example.com/api/user/avatar/a1",
+ );
+ expect(
+ resolveImageUrl("/api/asset/x", "https://example.com/kaneo")?.href,
+ ).toBe("https://example.com/kaneo/api/asset/x");
+ });
+
+ it("keeps absolute links and resolves protocol relative ones", () => {
+ expect(resolveImageUrl("https://cdn.test/a.png", api)?.href).toBe(
+ "https://cdn.test/a.png",
+ );
+ expect(resolveImageUrl("//cdn.test/a.png", api)?.href).toBe(
+ "https://cdn.test/a.png",
+ );
+ });
+
+ it("rejects links that are not http", () => {
+ expect(resolveImageUrl("data:image/png;base64,AAAA", api)).toBeNull();
+ expect(resolveImageUrl("javascript:alert(1)", api)).toBeNull();
+ expect(resolveImageUrl(" ", api)).toBeNull();
+ });
+
+ it("leaves unusable links as they were when making them absolute", () => {
+ expect(absoluteImageUrl("data:x", api)).toBe("data:x");
+ expect(absoluteImageUrl("/api/asset/1", api)).toBe(
+ "https://kaneo.example.com/api/asset/1",
+ );
+ });
+});
+
+describe("sendsToken", () => {
+ const url = (value: string) => new URL(value);
+
+ it("sends the token to assets on the API origin", () => {
+ expect(sendsToken(url(`${api}/api/asset/abc`), api)).toBe(true);
+ });
+
+ it("never sends it to other hosts, ports or schemes", () => {
+ expect(sendsToken(url("https://evil.test/api/asset/abc"), api)).toBe(false);
+ expect(
+ sendsToken(url("https://kaneo.example.com:8443/api/asset/abc"), api),
+ ).toBe(false);
+ expect(sendsToken(url("http://kaneo.example.com/api/asset/abc"), api)).toBe(
+ false,
+ );
+ expect(
+ sendsToken(url("https://kaneo.example.com.evil.test/api/asset/a"), api),
+ ).toBe(false);
+ });
+
+ it("keeps it off other API routes, including public avatars", () => {
+ expect(sendsToken(url(`${api}/api/user/avatar/a1`), api)).toBe(false);
+ expect(sendsToken(url(`${api}/api/task/export/p1`), api)).toBe(false);
+ });
+});
diff --git a/packages/cli/src/images/image-url.ts b/packages/cli/src/images/image-url.ts
new file mode 100644
index 000000000..62af1529e
--- /dev/null
+++ b/packages/cli/src/images/image-url.ts
@@ -0,0 +1,35 @@
+const SCHEME = /^[a-z][a-z0-9+.-]*:/iu;
+
+function parse(value: string, base?: string): URL | null {
+ try {
+ const url = base === undefined ? new URL(value) : new URL(value, base);
+ return url.protocol === "http:" || url.protocol === "https:" ? url : null;
+ } catch {
+ return null;
+ }
+}
+
+export function resolveImageUrl(raw: string, apiUrl: string): URL | null {
+ const value = raw.trim();
+ if (value === "") return null;
+ if (value.startsWith("//")) {
+ const api = parse(apiUrl);
+ return api ? parse(`${api.protocol}${value}`) : null;
+ }
+ if (SCHEME.test(value)) return parse(value);
+ if (value.startsWith("/")) return parse(`${apiUrl}${value}`);
+ return parse(value, `${apiUrl}/`);
+}
+
+export function absoluteImageUrl(raw: string, apiUrl: string): string {
+ return resolveImageUrl(raw, apiUrl)?.href ?? raw;
+}
+
+const ASSET_PATH = /\/api\/asset\/[^/]+$/u;
+
+export function sendsToken(url: URL, apiUrl: string): boolean {
+ const api = parse(apiUrl);
+ return (
+ api !== null && url.origin === api.origin && ASSET_PATH.test(url.pathname)
+ );
+}
diff --git a/packages/cli/src/images/iterm.test.ts b/packages/cli/src/images/iterm.test.ts
new file mode 100644
index 000000000..54e0f9d5b
--- /dev/null
+++ b/packages/cli/src/images/iterm.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vite-plus/test";
+import { encodeIterm } from "./iterm.js";
+
+describe("encodeIterm", () => {
+ it("sends the original bytes with the size in cells", () => {
+ expect(
+ encodeIterm(
+ new Uint8Array([1, 2, 3, 4]),
+ { columns: 12, rows: 6 },
+ {
+ tmux: false,
+ },
+ ),
+ ).toBe(
+ "\u001b]1337;File=inline=1;width=12;height=6;preserveAspectRatio=1;size=4:AQIDBA==\u0007",
+ );
+ });
+
+ it("wraps the sequence in tmux passthrough", () => {
+ const output = encodeIterm(
+ new Uint8Array([1]),
+ { columns: 1, rows: 1 },
+ {
+ tmux: true,
+ },
+ );
+ expect(output.startsWith("\u001bPtmux;\u001b\u001b]1337;File=")).toBe(true);
+ expect(output.endsWith("\u0007\u001b\\")).toBe(true);
+ });
+});
diff --git a/packages/cli/src/images/iterm.ts b/packages/cli/src/images/iterm.ts
new file mode 100644
index 000000000..97060270e
--- /dev/null
+++ b/packages/cli/src/images/iterm.ts
@@ -0,0 +1,16 @@
+import type { CellSize } from "./cell-size.js";
+import { tmuxPassthrough } from "./tmux.js";
+
+export function encodeIterm(
+ bytes: Uint8Array,
+ size: CellSize,
+ options: { readonly tmux: boolean },
+): string {
+ const data = Buffer.from(
+ bytes.buffer,
+ bytes.byteOffset,
+ bytes.byteLength,
+ ).toString("base64");
+ const sequence = `\u001b]1337;File=inline=1;width=${size.columns};height=${size.rows};preserveAspectRatio=1;size=${bytes.byteLength}:${data}\u0007`;
+ return options.tmux ? tmuxPassthrough(sequence) : sequence;
+}
diff --git a/packages/cli/src/images/kitty.test.ts b/packages/cli/src/images/kitty.test.ts
new file mode 100644
index 000000000..2c195c87b
--- /dev/null
+++ b/packages/cli/src/images/kitty.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from "vite-plus/test";
+import { encodeKitty, KITTY_CHUNK } from "./kitty.js";
+
+const ESC = "\u001b";
+const size = { columns: 10, rows: 5 };
+const COMMAND = new RegExp(`${ESC}_G([^;]*);([^${ESC}]*)${ESC}\\\\`, "gu");
+
+function commands(output: string): Array<{ keys: string; data: string }> {
+ return [...output.matchAll(COMMAND)].map((match) => ({
+ keys: match[1] ?? "",
+ data: match[2] ?? "",
+ }));
+}
+
+describe("encodeKitty", () => {
+ it("sends a small PNG in one command with the size in cells", () => {
+ const bytes = new Uint8Array([1, 2, 3]);
+ const output = encodeKitty({ format: "png", bytes }, size, { tmux: false });
+ expect(output).toBe(`${ESC}_Ga=T,f=100,t=d,c=10,r=5,q=2,m=0;AQID${ESC}\\`);
+ });
+
+ it("splits the base64 payload into 4096 byte chunks", () => {
+ const bytes = new Uint8Array(KITTY_CHUNK * 2);
+ const output = encodeKitty({ format: "png", bytes }, size, { tmux: false });
+ const parts = commands(output);
+ expect(parts.map((part) => part.data.length)).toEqual([4096, 4096, 2732]);
+ expect(parts[0]?.keys).toBe("a=T,f=100,t=d,c=10,r=5,q=2,m=1");
+ expect(parts.slice(1, -1).every((part) => part.keys === "m=1,q=2")).toBe(
+ true,
+ );
+ expect(parts[parts.length - 1]?.keys).toBe("m=0,q=2");
+ expect(parts.map((part) => part.data).join("")).toBe(
+ Buffer.from(bytes).toString("base64"),
+ );
+ });
+
+ it("describes raw RGBA pixels and zlib compression", () => {
+ const output = encodeKitty(
+ {
+ format: "rgba",
+ width: 3,
+ height: 2,
+ bytes: new Uint8Array([9]),
+ compressed: true,
+ },
+ size,
+ { tmux: false },
+ );
+ expect(commands(output)[0]?.keys).toBe(
+ "a=T,f=32,s=3,v=2,o=z,t=d,c=10,r=5,q=2,m=0",
+ );
+ });
+
+ it("wraps every chunk in tmux passthrough", () => {
+ const bytes = new Uint8Array(KITTY_CHUNK);
+ const output = encodeKitty({ format: "png", bytes }, size, { tmux: true });
+ const wrapped = output.split(`${ESC}Ptmux;`).slice(1);
+ expect(wrapped).toHaveLength(2);
+ for (const part of wrapped) {
+ expect(part.startsWith(`${ESC}${ESC}_G`)).toBe(true);
+ expect(part.endsWith(`${ESC}${ESC}\\${ESC}\\`)).toBe(true);
+ }
+ });
+});
diff --git a/packages/cli/src/images/kitty.ts b/packages/cli/src/images/kitty.ts
new file mode 100644
index 000000000..07972d54b
--- /dev/null
+++ b/packages/cli/src/images/kitty.ts
@@ -0,0 +1,48 @@
+import type { CellSize } from "./cell-size.js";
+import { tmuxPassthrough } from "./tmux.js";
+
+export type KittyPayload =
+ | { readonly format: "png"; readonly bytes: Uint8Array }
+ | {
+ readonly format: "rgba";
+ readonly width: number;
+ readonly height: number;
+ readonly bytes: Uint8Array;
+ readonly compressed: boolean;
+ };
+
+export const KITTY_CHUNK = 4096;
+
+function base64(bytes: Uint8Array): string {
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString(
+ "base64",
+ );
+}
+
+function formatKeys(payload: KittyPayload): string {
+ if (payload.format === "png") return "f=100";
+ const compression = payload.compressed ? ",o=z" : "";
+ return `f=32,s=${payload.width},v=${payload.height}${compression}`;
+}
+
+export function encodeKitty(
+ payload: KittyPayload,
+ size: CellSize,
+ options: { readonly tmux: boolean },
+): string {
+ const data = base64(payload.bytes);
+ const chunks: string[] = [];
+ for (let start = 0; start < data.length; start += KITTY_CHUNK) {
+ chunks.push(data.slice(start, start + KITTY_CHUNK));
+ }
+ if (chunks.length === 0) chunks.push("");
+ const first = `a=T,${formatKeys(payload)},t=d,c=${size.columns},r=${size.rows},q=2`;
+ return chunks
+ .map((chunk, index) => {
+ const more = index < chunks.length - 1 ? 1 : 0;
+ const keys = index === 0 ? `${first},m=${more}` : `m=${more},q=2`;
+ const sequence = `\u001b_G${keys};${chunk}\u001b\\`;
+ return options.tmux ? tmuxPassthrough(sequence) : sequence;
+ })
+ .join("");
+}
diff --git a/packages/cli/src/images/placeholder.test.ts b/packages/cli/src/images/placeholder.test.ts
new file mode 100644
index 000000000..1a929f945
--- /dev/null
+++ b/packages/cli/src/images/placeholder.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { renderCaption, renderPlaceholder } from "./placeholder.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+const image = { url: "https://kaneo.test/api/asset/a1", alt: "Diagram" };
+
+describe("renderPlaceholder", () => {
+ it("names the image and why it is not shown", () => {
+ expect(renderPlaceholder(ui, image, 60, "not found")).toBe(
+ "[image: Diagram] · not found",
+ );
+ expect(renderPlaceholder(ui, { ...image, alt: "" }, 60)).toBe("[image]");
+ });
+
+ it("links the label to the image", () => {
+ const linked = makeUi({ ...ui.caps, hyperlinks: true });
+ expect(renderPlaceholder(linked, image, 60)).toBe(
+ "\u001b]8;;https://kaneo.test/api/asset/a1\u001b\\[image: Diagram]\u001b]8;;\u001b\\",
+ );
+ });
+});
+
+describe("renderCaption", () => {
+ it("falls back to a generic caption and truncates long ones", () => {
+ expect(renderCaption(ui, { ...image, alt: "" }, 60)).toBe("Image");
+ expect(renderCaption(ui, { ...image, alt: "x".repeat(30) }, 10)).toBe(
+ "xxxxxxxxx…",
+ );
+ });
+});
diff --git a/packages/cli/src/images/placeholder.ts b/packages/cli/src/images/placeholder.ts
new file mode 100644
index 000000000..2e5d6d3c3
--- /dev/null
+++ b/packages/cli/src/images/placeholder.ts
@@ -0,0 +1,31 @@
+import { renderCell, text } from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+import { truncate } from "../render/width.js";
+import type { ImageRef } from "./extract-images.js";
+
+export function renderPlaceholder(
+ ui: Ui,
+ image: ImageRef,
+ width: number,
+ reason?: string,
+): string {
+ const { theme, glyphs } = ui;
+ const label = truncate(
+ image.alt ? `[image: ${image.alt}]` : "[image]",
+ Math.max(8, width),
+ glyphs.ellipsis,
+ );
+ const link = renderCell([text(label, theme.muted, image.url)], ui);
+ return reason
+ ? `${link} ${theme.muted(`${glyphs.separator} ${reason}`)}`
+ : link;
+}
+
+export function renderCaption(ui: Ui, image: ImageRef, width: number): string {
+ const caption = truncate(
+ image.alt || "Image",
+ Math.max(8, width),
+ ui.glyphs.ellipsis,
+ );
+ return renderCell([text(caption, ui.theme.muted, image.url)], ui);
+}
diff --git a/packages/cli/src/images/render-attached.test.ts b/packages/cli/src/images/render-attached.test.ts
new file mode 100644
index 000000000..326415753
--- /dev/null
+++ b/packages/cli/src/images/render-attached.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { renderAttached } from "./render-attached.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+describe("renderAttached", () => {
+ const attached = { label: "KAN-1", url: "https://kaneo.test/t" };
+
+ it("names one or two files and counts more", () => {
+ expect(
+ renderAttached(ui, {
+ ...attached,
+ names: ["shot.png"],
+ target: "description",
+ }),
+ ).toEqual([
+ " ✓ Attached shot.png to KAN-1 · added to the description",
+ "",
+ ]);
+ expect(
+ renderAttached(ui, {
+ ...attached,
+ names: ["a.png", "b.pdf"],
+ target: "comment",
+ })[0],
+ ).toBe(" ✓ Attached a.png and b.pdf to KAN-1 · posted as a comment");
+ expect(
+ renderAttached(ui, {
+ ...attached,
+ names: ["a", "b", "c"],
+ target: "comment",
+ })[0],
+ ).toBe(" ✓ Attached 3 files to KAN-1 · posted as a comment");
+ });
+});
diff --git a/packages/cli/src/images/render-attached.ts b/packages/cli/src/images/render-attached.ts
new file mode 100644
index 000000000..46c00f8e5
--- /dev/null
+++ b/packages/cli/src/images/render-attached.ts
@@ -0,0 +1,28 @@
+import { renderCell, text } from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+
+export type Attached = {
+ readonly label: string;
+ readonly url: string;
+ readonly names: ReadonlyArray<string>;
+ readonly target: "description" | "comment";
+};
+
+export function attachedSummary(names: ReadonlyArray<string>): string {
+ if (names.length === 1) return names[0] ?? "1 file";
+ if (names.length === 2) return `${names[0]} and ${names[1]}`;
+ return `${names.length} files`;
+}
+
+export function renderAttached(ui: Ui, attached: Attached): string[] {
+ const { theme, glyphs } = ui;
+ const id = renderCell([text(attached.label, theme.strong, attached.url)], ui);
+ const where =
+ attached.target === "comment"
+ ? "posted as a comment"
+ : "added to the description";
+ return [
+ ` ${theme.success(glyphs.tick)} Attached ${attachedSummary(attached.names)} to ${id} ${theme.muted(`${glyphs.separator} ${where}`)}`,
+ "",
+ ];
+}
diff --git a/packages/cli/src/images/render-image-block.test.ts b/packages/cli/src/images/render-image-block.test.ts
new file mode 100644
index 000000000..231aad680
--- /dev/null
+++ b/packages/cli/src/images/render-image-block.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stripAnsi } from "../render/width.js";
+import { renderImageBlock } from "./render-image-block.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+const linked = makeUi({
+ color: 3,
+ unicode: true,
+ hyperlinks: true,
+ animate: false,
+ columns: 80,
+});
+
+const image = { url: "https://kaneo.test/api/asset/a1", alt: "Login page" };
+
+describe("renderImageBlock", () => {
+ it("indents the picture and puts the caption below it", () => {
+ expect(
+ renderImageBlock(
+ ui,
+ image,
+ { _tag: "Art", lines: ["##", "##"], columns: 2, rows: 2 },
+ 2,
+ ),
+ ).toEqual([" ##", " ##", " Login page"]);
+ });
+
+ it("shows a linked placeholder with the reason", () => {
+ const [line = ""] = renderImageBlock(
+ linked,
+ image,
+ { _tag: "Unsupported", reason: "GIF cannot be shown here" },
+ 2,
+ );
+ expect(stripAnsi(line)).toBe(
+ " [image: Login page] · GIF cannot be shown here",
+ );
+ expect(line).toContain("\u001b]8;;https://kaneo.test/api/asset/a1\u001b\\");
+ });
+});
diff --git a/packages/cli/src/images/render-image-block.ts b/packages/cli/src/images/render-image-block.ts
new file mode 100644
index 000000000..30a298037
--- /dev/null
+++ b/packages/cli/src/images/render-image-block.ts
@@ -0,0 +1,21 @@
+import type { Ui } from "../render/ui.js";
+import type { ImageRef } from "./extract-images.js";
+import type { ImageArt } from "./image-art.js";
+import { renderCaption, renderPlaceholder } from "./placeholder.js";
+
+export function renderImageBlock(
+ ui: Ui,
+ image: ImageRef,
+ art: ImageArt,
+ indent: number,
+): string[] {
+ const pad = " ".repeat(indent);
+ const width = ui.caps.columns - indent;
+ if (art._tag === "Unsupported") {
+ return [`${pad}${renderPlaceholder(ui, image, width, art.reason)}`];
+ }
+ return [
+ ...art.lines.map((line) => `${pad}${line}`),
+ `${pad}${renderCaption(ui, image, width)}`,
+ ];
+}
diff --git a/packages/cli/src/images/render-image-links.test.ts b/packages/cli/src/images/render-image-links.test.ts
new file mode 100644
index 000000000..60260096d
--- /dev/null
+++ b/packages/cli/src/images/render-image-links.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { renderImageLinks } from "./render-image-links.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 40,
+});
+
+describe("renderImageLinks", () => {
+ it("numbers each image and prints its full link below", () => {
+ expect(
+ renderImageLinks(
+ ui,
+ [
+ {
+ url: "https://kaneo.test/api/asset/a-very-long-asset-identifier",
+ alt: "A screenshot with a caption that is too long",
+ },
+ ],
+ { indent: 2, hidden: 0 },
+ ),
+ ).toEqual([
+ " 1. A screenshot with a caption that i…",
+ " https://kaneo.test/api/asset/a-very-long-asset-identifier",
+ "",
+ ]);
+ });
+
+ it("aligns numbers and mentions hidden images", () => {
+ const images = Array.from({ length: 10 }, (_, index) => ({
+ url: `https://kaneo.test/${index}`,
+ alt: "",
+ }));
+ const lines = renderImageLinks(ui, images, { indent: 0, hidden: 1 });
+ expect(lines[0]).toBe(" 1. Image");
+ expect(lines[18]).toBe("10. Image");
+ expect(lines[19]).toBe(" https://kaneo.test/9");
+ expect(lines[20]).toBe("1 more image not shown");
+ });
+});
diff --git a/packages/cli/src/images/render-image-links.ts b/packages/cli/src/images/render-image-links.ts
new file mode 100644
index 000000000..702a33702
--- /dev/null
+++ b/packages/cli/src/images/render-image-links.ts
@@ -0,0 +1,29 @@
+import { renderCell, text } from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+import { truncate } from "../render/width.js";
+import type { ImageRef } from "./extract-images.js";
+
+export function moreImagesLine(ui: Ui, hidden: number): string {
+ return ui.theme.muted(
+ `${hidden} more ${hidden === 1 ? "image" : "images"} not shown`,
+ );
+}
+
+export function renderImageLinks(
+ ui: Ui,
+ images: ReadonlyArray<ImageRef>,
+ options: { readonly indent: number; readonly hidden: number },
+): string[] {
+ const { theme, glyphs } = ui;
+ const pad = " ".repeat(options.indent);
+ const numberWidth = `${images.length}.`.length;
+ const hang = " ".repeat(numberWidth + 1);
+ const width = Math.max(8, ui.caps.columns - options.indent - hang.length);
+ const lines = images.flatMap((image, index) => [
+ `${pad}${theme.muted(`${index + 1}.`.padStart(numberWidth))} ${truncate(image.alt || "Image", width, glyphs.ellipsis)}`,
+ `${pad}${hang}${renderCell([text(image.url, theme.info, image.url)], ui)}`,
+ ]);
+ if (options.hidden > 0)
+ lines.push(`${pad}${moreImagesLine(ui, options.hidden)}`);
+ return [...lines, ""];
+}
diff --git a/packages/cli/src/images/render-images-heading.test.ts b/packages/cli/src/images/render-images-heading.test.ts
new file mode 100644
index 000000000..70395d663
--- /dev/null
+++ b/packages/cli/src/images/render-images-heading.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { renderImagesHeading } from "./render-images-heading.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+describe("renderImagesHeading", () => {
+ const heading = {
+ label: "KAN-1",
+ title: "Fix login redirect",
+ url: "https://kaneo.test/t",
+ };
+
+ it("counts the images", () => {
+ expect(renderImagesHeading(ui, { ...heading, count: 2 })).toEqual([
+ "",
+ " KAN-1 Fix login redirect · 2 images",
+ "",
+ ]);
+ });
+
+ it("says when there are none", () => {
+ expect(renderImagesHeading(ui, { ...heading, count: 0 })).toEqual([
+ "",
+ " KAN-1 Fix login redirect",
+ "",
+ " No images in this task.",
+ "",
+ ]);
+ });
+});
diff --git a/packages/cli/src/images/render-images-heading.ts b/packages/cli/src/images/render-images-heading.ts
new file mode 100644
index 000000000..fccdc2a4f
--- /dev/null
+++ b/packages/cli/src/images/render-images-heading.ts
@@ -0,0 +1,27 @@
+import { renderCell, text } from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+import { stringWidth, truncate } from "../render/width.js";
+
+export type ImagesHeading = {
+ readonly label: string;
+ readonly title: string;
+ readonly url: string;
+ readonly count: number;
+};
+
+export function renderImagesHeading(ui: Ui, heading: ImagesHeading): string[] {
+ const { theme, glyphs } = ui;
+ const id = renderCell([text(heading.label, theme.muted, heading.url)], ui);
+ const count =
+ heading.count === 0
+ ? ""
+ : ` ${glyphs.separator} ${heading.count} ${heading.count === 1 ? "image" : "images"}`;
+ const room = Math.max(
+ 8,
+ ui.caps.columns - 2 - stringWidth(heading.label) - 1 - stringWidth(count),
+ );
+ const title = theme.strong(truncate(heading.title, room, glyphs.ellipsis));
+ const line = ` ${id} ${title}${theme.muted(count)}`;
+ if (heading.count > 0) return ["", line, ""];
+ return ["", line, "", ` ${theme.muted("No images in this task.")}`, ""];
+}
diff --git a/packages/cli/src/images/render-images.test.ts b/packages/cli/src/images/render-images.test.ts
new file mode 100644
index 000000000..64e8fd87c
--- /dev/null
+++ b/packages/cli/src/images/render-images.test.ts
@@ -0,0 +1,101 @@
+import { Effect, Layer } from "effect";
+import { HttpClient, HttpClientResponse } from "effect/http";
+import { describe, expect, it } from "vite-plus/test";
+import type { Environment } from "../render/capabilities.js";
+import { CliEnvironment } from "../services/cli-environment.js";
+import { captureOutput, testSession } from "../testing/test-layers.js";
+import { pngBytes, solid } from "./image-fixtures.js";
+import { showImages } from "./render-images.js";
+
+const stream = { isTTY: true, columns: 80 };
+
+function run(
+ env: Environment,
+ options: { readonly mode?: "json" | "human"; readonly max?: number } = {},
+) {
+ const requested: string[] = [];
+ const output = captureOutput(options.mode ?? "human");
+ const client = Layer.succeed(
+ HttpClient.HttpClient,
+ HttpClient.make((request, url) => {
+ requested.push(url.toString());
+ const body = url.pathname.endsWith("/missing")
+ ? new Response("", { status: 404 })
+ : new Response(pngBytes(2, 2, solid(2, 2, [0, 128, 0, 255])), {
+ headers: { "content-type": "image/png" },
+ });
+ return Effect.succeed(HttpClientResponse.fromWeb(request, body));
+ }),
+ );
+ const environment = Layer.succeed(CliEnvironment, {
+ env,
+ cwd: "/",
+ home: "/",
+ platform: "darwin",
+ stdin: stream,
+ stdout: stream,
+ stderr: stream,
+ });
+ const images = [
+ { url: "/api/asset/a1", alt: "Login page" },
+ { url: "/api/asset/missing", alt: "Gone" },
+ { url: "https://cdn.test/c.png", alt: "" },
+ ];
+ return Effect.runPromise(
+ showImages(images, { max: options.max }).pipe(
+ Effect.provide(
+ Layer.mergeAll(client, environment, output.layer, testSession()),
+ ),
+ ),
+ ).then(() => ({ text: output.stdout.join(""), requested }));
+}
+
+describe("showImages", () => {
+ it("draws each image with its caption, and placeholders for failures", async () => {
+ const { text, requested } = await run({ KANEO_IMAGES: "blocks" });
+ expect(requested).toEqual([
+ "https://kaneo.test/api/asset/a1",
+ "https://kaneo.test/api/asset/missing",
+ "https://cdn.test/c.png",
+ ]);
+ const green = "\u001b[38;2;0;128;0;48;2;0;128;0m▀▀\u001b[39;49m";
+ expect(text).toBe(
+ [
+ ` ${green}`,
+ " Login page",
+ "",
+ " [image: Gone] · not found",
+ "",
+ ` ${green}`,
+ " Image",
+ "",
+ "",
+ ].join("\n"),
+ );
+ });
+
+ it("lists links when the terminal cannot show images", async () => {
+ const { text, requested } = await run({ KANEO_IMAGES: "off" }, { max: 2 });
+ expect(requested).toEqual([]);
+ expect(text).toBe(
+ [
+ " 1. Login page",
+ " https://kaneo.test/api/asset/a1",
+ " 2. Gone",
+ " https://kaneo.test/api/asset/missing",
+ " 1 more image not shown",
+ "",
+ "",
+ ].join("\n"),
+ );
+ });
+
+ it("prints nothing in JSON mode", async () => {
+ const { text, requested } = await run(
+ { KANEO_IMAGES: "blocks" },
+ { mode: "json" },
+ );
+ expect(text).toBe("");
+ expect(requested).toEqual([]);
+ });
+});
diff --git a/packages/cli/src/images/render-images.ts b/packages/cli/src/images/render-images.ts
new file mode 100644
index 000000000..9d312b280
--- /dev/null
+++ b/packages/cli/src/images/render-images.ts
@@ -0,0 +1,81 @@
+import { Effect } from "effect";
+import { FetchHttpClient } from "effect/http";
+import { Output } from "../output/output.js";
+import { withSpinner } from "../output/spinner.js";
+import { Session } from "../services/session.js";
+import type { ImageRef } from "./extract-images.js";
+import { fetchImage } from "./fetch-image.js";
+import { imageColumns, MAX_IMAGE_ROWS } from "./fit-image.js";
+import { imageArt } from "./image-art.js";
+import { currentImageTarget } from "./image-target.js";
+import { absoluteImageUrl } from "./image-url.js";
+import { renderImageBlock } from "./render-image-block.js";
+import { moreImagesLine, renderImageLinks } from "./render-image-links.js";
+
+export type RenderImagesOptions = {
+ readonly max?: number;
+ readonly indent?: number;
+ readonly maxRows?: number;
+ readonly whenUnsupported?: "links" | "skip";
+ readonly whenFailed?: "placeholder" | "skip";
+};
+
+export const DEFAULT_MAX_IMAGES = 10;
+const CONCURRENCY = 4;
+
+export const showImages = Effect.fnUntraced(function* (
+ images: ReadonlyArray<ImageRef>,
+ options: RenderImagesOptions = {},
+) {
+ const output = yield* Output;
+ if (output.mode === "json" || images.length === 0) return;
+ const session = yield* Session;
+ const target = yield* currentImageTarget;
+ const { ui } = output;
+ const indent = options.indent ?? 2;
+ const max = Math.max(1, options.max ?? DEFAULT_MAX_IMAGES);
+ const shown = images.slice(0, max).map((image) => ({
+ url: absoluteImageUrl(image.url, session.apiUrl),
+ alt: image.alt,
+ }));
+ const hidden = images.length - shown.length;
+
+ if (target.protocol === "none") {
+ if (options.whenUnsupported === "skip") return;
+ const lines = renderImageLinks(ui, shown, { indent, hidden });
+ yield* output.out(`${lines.join("\n")}\n`);
+ return;
+ }
+
+ const fetched = yield* withSpinner(
+ shown.length === 1 ? "Loading image" : `Loading ${shown.length} images`,
+ )(
+ Effect.forEach(shown, (image) => fetchImage(image.url), {
+ concurrency: CONCURRENCY,
+ }),
+ );
+ const artOptions = {
+ maxColumns: imageColumns(ui.caps.columns, indent),
+ maxRows: options.maxRows ?? MAX_IMAGE_ROWS,
+ };
+ const lines: string[] = [];
+ for (const [index, result] of fetched.entries()) {
+ const image = shown[index] ?? { url: result.url, alt: "" };
+ const art =
+ result._tag === "Fetched"
+ ? yield* imageArt(result.bytes, target, artOptions)
+ : ({ _tag: "Unsupported", reason: result.reason } as const);
+ if (art._tag === "Unsupported" && options.whenFailed === "skip") continue;
+ lines.push(...renderImageBlock(ui, image, art, indent), "");
+ }
+ if (hidden > 0) {
+ lines.push(`${" ".repeat(indent)}${moreImagesLine(ui, hidden)}`, "");
+ }
+ if (lines.length === 0) return;
+ yield* output.out(`${lines.join("\n")}\n`);
+});
+
+export const renderImages = (
+ images: ReadonlyArray<ImageRef>,
+ options: RenderImagesOptions = {},
+) => showImages(images, options).pipe(Effect.provide(FetchHttpClient.layer));
diff --git a/packages/cli/src/images/resize-rgba.test.ts b/packages/cli/src/images/resize-rgba.test.ts
new file mode 100644
index 000000000..e96edc0fd
--- /dev/null
+++ b/packages/cli/src/images/resize-rgba.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from "vite-plus/test";
+import { resizeRgba } from "./resize-rgba.js";
+
+describe("resizeRgba", () => {
+ it("averages each block of source pixels", () => {
+ const image = {
+ width: 2,
+ height: 2,
+ data: new Uint8Array([
+ 0, 0, 0, 255, 100, 100, 100, 255, 200, 200, 200, 255, 100, 100, 100,
+ 255,
+ ]),
+ };
+ expect([...resizeRgba(image, 1, 1).data]).toEqual([100, 100, 100, 255]);
+ });
+
+ it("ignores the color of transparent pixels", () => {
+ const image = {
+ width: 2,
+ height: 1,
+ data: new Uint8Array([255, 0, 0, 255, 0, 0, 255, 0]),
+ };
+ expect([...resizeRgba(image, 1, 1).data]).toEqual([255, 0, 0, 128]);
+ });
+
+ it("repeats pixels when it has to scale up", () => {
+ const image = { width: 1, height: 1, data: new Uint8Array([1, 2, 3, 4]) };
+ expect([...resizeRgba(image, 2, 1).data]).toEqual([1, 2, 3, 4, 1, 2, 3, 4]);
+ });
+
+ it("returns the same image when the size already matches", () => {
+ const image = { width: 1, height: 1, data: new Uint8Array([1, 2, 3, 4]) };
+ expect(resizeRgba(image, 1, 1)).toBe(image);
+ });
+});
diff --git a/packages/cli/src/images/resize-rgba.ts b/packages/cli/src/images/resize-rgba.ts
new file mode 100644
index 000000000..db61d4b44
--- /dev/null
+++ b/packages/cli/src/images/resize-rgba.ts
@@ -0,0 +1,62 @@
+import type { RgbaImage } from "./rgba.js";
+
+function spans(
+ source: number,
+ target: number,
+): Array<readonly [number, number]> {
+ const scale = source / target;
+ return Array.from({ length: target }, (_, index) => {
+ const start = Math.min(source - 1, Math.floor(index * scale));
+ const end = Math.max(
+ start + 1,
+ Math.min(source, Math.floor((index + 1) * scale)),
+ );
+ return [start, end] as const;
+ });
+}
+
+export function resizeRgba(
+ image: RgbaImage,
+ width: number,
+ height: number,
+): RgbaImage {
+ const targetWidth = Math.max(1, Math.round(width));
+ const targetHeight = Math.max(1, Math.round(height));
+ if (targetWidth === image.width && targetHeight === image.height) {
+ return image;
+ }
+ const columns = spans(image.width, targetWidth);
+ const rows = spans(image.height, targetHeight);
+ const data = new Uint8Array(targetWidth * targetHeight * 4);
+ const source = image.data;
+ for (let y = 0; y < targetHeight; y++) {
+ const [top, bottom] = rows[y] ?? [0, 1];
+ for (let x = 0; x < targetWidth; x++) {
+ const [left, right] = columns[x] ?? [0, 1];
+ let red = 0;
+ let green = 0;
+ let blue = 0;
+ let alpha = 0;
+ let count = 0;
+ for (let sy = top; sy < bottom; sy++) {
+ let at = (sy * image.width + left) * 4;
+ for (let sx = left; sx < right; sx++, at += 4) {
+ const a = source[at + 3] ?? 0;
+ red += (source[at] ?? 0) * a;
+ green += (source[at + 1] ?? 0) * a;
+ blue += (source[at + 2] ?? 0) * a;
+ alpha += a;
+ count += 1;
+ }
+ }
+ const out = (y * targetWidth + x) * 4;
+ if (alpha > 0) {
+ data[out] = Math.round(red / alpha);
+ data[out + 1] = Math.round(green / alpha);
+ data[out + 2] = Math.round(blue / alpha);
+ }
+ data[out + 3] = Math.round(alpha / Math.max(1, count));
+ }
+ }
+ return { width: targetWidth, height: targetHeight, data };
+}
diff --git a/packages/cli/src/images/rgba.ts b/packages/cli/src/images/rgba.ts
new file mode 100644
index 000000000..bc26136a5
--- /dev/null
+++ b/packages/cli/src/images/rgba.ts
@@ -0,0 +1,7 @@
+export type Rgb = readonly [number, number, number];
+
+export type RgbaImage = {
+ readonly width: number;
+ readonly height: number;
+ readonly data: Uint8Array;
+};
diff --git a/packages/cli/src/images/side-by-side.test.ts b/packages/cli/src/images/side-by-side.test.ts
new file mode 100644
index 000000000..f5c6151bf
--- /dev/null
+++ b/packages/cli/src/images/side-by-side.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from "vite-plus/test";
+import { besidePicture } from "./side-by-side.js";
+
+describe("besidePicture", () => {
+ it("centers the text next to a taller picture", () => {
+ expect(
+ besidePicture(
+ { lines: ["AAAA", "BBBB", "CCCC", "DDDD"], columns: 4 },
+ ["one", "two"],
+ { indent: 2, gap: 1 },
+ ),
+ ).toEqual([" AAAA", " BBBB one", " CCCC two", " DDDD"]);
+ });
+
+ it("pads the picture column when the text is taller", () => {
+ expect(
+ besidePicture({ lines: ["AA"], columns: 2 }, ["one", "", "three"], {
+ indent: 0,
+ gap: 2,
+ }),
+ ).toEqual(["AA one", " ", " three"]);
+ });
+});
diff --git a/packages/cli/src/images/side-by-side.ts b/packages/cli/src/images/side-by-side.ts
new file mode 100644
index 000000000..d6410dbc5
--- /dev/null
+++ b/packages/cli/src/images/side-by-side.ts
@@ -0,0 +1,24 @@
+export type Picture = {
+ readonly lines: ReadonlyArray<string>;
+ readonly columns: number;
+};
+
+export function besidePicture(
+ picture: Picture,
+ text: ReadonlyArray<string>,
+ options: { readonly indent: number; readonly gap: number },
+): string[] {
+ const offset = Math.max(
+ 0,
+ Math.floor((picture.lines.length - text.length) / 2),
+ );
+ const height = Math.max(picture.lines.length, offset + text.length);
+ const pad = " ".repeat(options.indent);
+ const empty = " ".repeat(picture.columns);
+ const gap = " ".repeat(options.gap);
+ return Array.from({ length: height }, (_, row) => {
+ const art = picture.lines[row] ?? empty;
+ const words = text[row - offset] ?? "";
+ return words === "" ? `${pad}${art}` : `${pad}${art}${gap}${words}`;
+ });
+}
diff --git a/packages/cli/src/images/terminal-background.ts b/packages/cli/src/images/terminal-background.ts
new file mode 100644
index 000000000..12219128a
--- /dev/null
+++ b/packages/cli/src/images/terminal-background.ts
@@ -0,0 +1,28 @@
+import type { Environment } from "../render/capabilities.js";
+import type { Rgb } from "./rgba.js";
+
+const PALETTE: ReadonlyArray<Rgb> = [
+ [0, 0, 0],
+ [205, 0, 0],
+ [0, 205, 0],
+ [205, 205, 0],
+ [0, 0, 238],
+ [205, 0, 205],
+ [0, 205, 205],
+ [229, 229, 229],
+ [127, 127, 127],
+ [255, 0, 0],
+ [0, 255, 0],
+ [255, 255, 0],
+ [92, 92, 255],
+ [255, 0, 255],
+ [0, 255, 255],
+ [255, 255, 255],
+];
+
+export function terminalBackground(env: Environment): Rgb | null {
+ const parts = env.COLORFGBG?.split(";") ?? [];
+ const last = parts[parts.length - 1]?.trim() ?? "";
+ if (!/^\d{1,2}$/u.test(last)) return null;
+ return PALETTE[Number(last)] ?? null;
+}
diff --git a/packages/cli/src/images/tmux.test.ts b/packages/cli/src/images/tmux.test.ts
new file mode 100644
index 000000000..ab3dc3da2
--- /dev/null
+++ b/packages/cli/src/images/tmux.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from "vite-plus/test";
+import { tmuxPassthrough } from "./tmux.js";
+
+describe("tmuxPassthrough", () => {
+ it("doubles every escape and wraps the sequence in a DCS", () => {
+ expect(tmuxPassthrough("\u001b_Ga=T;AAAA\u001b\\")).toBe(
+ "\u001bPtmux;\u001b\u001b_Ga=T;AAAA\u001b\u001b\\\u001b\\",
+ );
+ });
+
+ it("leaves sequences that end with BEL intact apart from the escapes", () => {
+ expect(tmuxPassthrough("\u001b]1337;File=:QQ==\u0007")).toBe(
+ "\u001bPtmux;\u001b\u001b]1337;File=:QQ==\u0007\u001b\\",
+ );
+ });
+});
diff --git a/packages/cli/src/images/tmux.ts b/packages/cli/src/images/tmux.ts
new file mode 100644
index 000000000..e6e39fd19
--- /dev/null
+++ b/packages/cli/src/images/tmux.ts
@@ -0,0 +1,5 @@
+const ESC = "\u001b";
+
+export function tmuxPassthrough(sequence: string): string {
+ return `${ESC}Ptmux;${sequence.replaceAll(ESC, `${ESC}${ESC}`)}${ESC}\\`;
+}
diff --git a/packages/cli/src/input/read-text-input.test.ts b/packages/cli/src/input/read-text-input.test.ts
new file mode 100644
index 000000000..0148fc4aa
--- /dev/null
+++ b/packages/cli/src/input/read-text-input.test.ts
@@ -0,0 +1,9 @@
+import { describe, expect, it } from "vite-plus/test";
+import { stripByteOrderMark } from "./read-text-input.js";
+
+describe("stripByteOrderMark", () => {
+ it("removes a leading byte order mark only", () => {
+ expect(stripByteOrderMark("hello")).toBe("hello");
+ expect(stripByteOrderMark("hello")).toBe("hello");
+ });
+});
diff --git a/packages/cli/src/input/read-text-input.ts b/packages/cli/src/input/read-text-input.ts
new file mode 100644
index 000000000..b783b07ab
--- /dev/null
+++ b/packages/cli/src/input/read-text-input.ts
@@ -0,0 +1,60 @@
+import { readFile } from "node:fs/promises";
+import { Effect, Option } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+import { CliEnvironment } from "../services/cli-environment.js";
+import { readStream } from "../tasks/read-stdin.js";
+
+export type TextInput = {
+ readonly value: Option.Option<string>;
+ readonly file: Option.Option<string>;
+ readonly flag: string;
+};
+
+export function stripByteOrderMark(text: string): string {
+ return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
+}
+
+const readStdin = Effect.fnUntraced(function* (flag: string) {
+ const environment = yield* CliEnvironment;
+ if (environment.stdin.isTTY) {
+ return yield* new InvalidArgument({
+ message: `${flag} - reads from stdin, but nothing is piped in.`,
+ hint: `Pipe the text in, for example: cat notes.md | kaneo ... ${flag} -`,
+ });
+ }
+ return yield* Effect.tryPromise({
+ try: () => readStream(process.stdin),
+ catch: () => new InvalidArgument({ message: "Could not read from stdin." }),
+ });
+});
+
+export const readTextInput = Effect.fnUntraced(function* (input: TextInput) {
+ if (Option.isSome(input.value) && Option.isSome(input.file)) {
+ return yield* new InvalidArgument({
+ message: `Pass either ${input.flag} or a file, not both.`,
+ });
+ }
+ if (Option.isSome(input.file)) {
+ const path = input.file.value;
+ const text =
+ path === "-"
+ ? yield* readStdin(`${input.flag}-file`)
+ : yield* Effect.tryPromise({
+ try: () => readFile(path, "utf8"),
+ catch: () =>
+ new InvalidArgument({
+ message: `Could not read ${path}.`,
+ hint: "Check the path and that the file is readable.",
+ }),
+ });
+ return Option.some(stripByteOrderMark(text));
+ }
+ if (Option.isSome(input.value)) {
+ return Option.some(
+ input.value.value === "-"
+ ? stripByteOrderMark(yield* readStdin(input.flag))
+ : input.value.value,
+ );
+ }
+ return Option.none<string>();
+});
diff --git a/packages/cli/src/jq/apply-jq.ts b/packages/cli/src/jq/apply-jq.ts
new file mode 100644
index 000000000..f33296c5f
--- /dev/null
+++ b/packages/cli/src/jq/apply-jq.ts
@@ -0,0 +1,21 @@
+import { Effect } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+import type { JqFilter } from "./compile-jq.js";
+import { formatJqResults } from "./format-jq-output.js";
+
+export function toJsonValue(value: unknown): unknown {
+ const text = JSON.stringify(value);
+ return text === undefined ? null : JSON.parse(text);
+}
+
+export const applyJq = (filter: JqFilter, value: unknown) =>
+ filter.run(toJsonValue(value)).pipe(
+ Effect.map(formatJqResults),
+ Effect.mapError(
+ (detail) =>
+ new InvalidArgument({
+ message: `The --jq expression failed: ${detail}`,
+ hint: "Run the same command with --json to see the data the expression receives.",
+ }),
+ ),
+ );
diff --git a/packages/cli/src/jq/compile-jq.test.ts b/packages/cli/src/jq/compile-jq.test.ts
new file mode 100644
index 000000000..9e443b5c6
--- /dev/null
+++ b/packages/cli/src/jq/compile-jq.test.ts
@@ -0,0 +1,52 @@
+import { Effect, Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { applyJq } from "./apply-jq.js";
+import { compileJq } from "./compile-jq.js";
+
+const tasks = [
+ { ticketId: "KAN-1", title: "Fix login", status: "done", due: undefined },
+ { ticketId: "KAN-2", title: "Ship", status: "todo" },
+];
+
+async function jq(expression: string, input: unknown) {
+ const filter = await Effect.runPromise(compileJq(expression));
+ return Effect.runPromise(applyJq(filter, input));
+}
+
+describe("compileJq", () => {
+ it("supports paths, pipes, select, map, has, length, keys and objects", async () => {
+ expect(await jq(".[0].title", tasks)).toBe("Fix login\n");
+ expect(await jq('.[] | select(.status == "todo") | .ticketId', tasks)).toBe(
+ "KAN-2\n",
+ );
+ expect(await jq("map(.ticketId)", tasks)).toBe('["KAN-1","KAN-2"]\n');
+ expect(await jq('map(has("due"))', tasks)).toBe("[false,false]\n");
+ expect(await jq("length", tasks)).toBe("2\n");
+ expect(await jq(".[1] | keys", tasks)).toBe(
+ '["status","ticketId","title"]\n',
+ );
+ expect(await jq(".[] | {id: .ticketId}", tasks)).toBe(
+ '{"id":"KAN-1"}\n{"id":"KAN-2"}\n',
+ );
+ expect(await jq('.[] | "\\(.ticketId): \\(.title)"', tasks)).toBe(
+ "KAN-1: Fix login\nKAN-2: Ship\n",
+ );
+ });
+
+ it("rejects a bad expression with its position", async () => {
+ const result = await Effect.runPromise(Effect.result(compileJq(".[")));
+ expect(Result.isFailure(result) && result.failure).toBe(
+ "Unexpected token at column 3",
+ );
+ });
+
+ it("reports runtime errors as invalid arguments", async () => {
+ const filter = await Effect.runPromise(compileJq(".[0]"));
+ const result = await Effect.runPromise(
+ Effect.result(applyJq(filter, { a: 1 })),
+ );
+ expect(Result.isFailure(result) && result.failure.message).toBe(
+ "The --jq expression failed: Cannot index object with number",
+ );
+ });
+});
diff --git a/packages/cli/src/jq/compile-jq.ts b/packages/cli/src/jq/compile-jq.ts
new file mode 100644
index 000000000..1e3a149dd
--- /dev/null
+++ b/packages/cli/src/jq/compile-jq.ts
@@ -0,0 +1,52 @@
+import { Effect } from "effect";
+
+export type JqFilter = {
+ readonly expression: string;
+ readonly run: (
+ input: unknown,
+ ) => Effect.Effect<ReadonlyArray<unknown>, string>;
+};
+
+const LIMITS = {
+ maxSteps: Number.MAX_SAFE_INTEGER,
+ maxDepth: 1000,
+ maxOutputs: Number.MAX_SAFE_INTEGER,
+};
+
+export function describeJqError(error: unknown): string {
+ if (!(error instanceof Error)) return String(error);
+ const start = (error as { span?: { start?: unknown } }).span?.start;
+ return typeof start === "number" &&
+ (error.name === "ParseError" || error.name === "LexError")
+ ? `${error.message} at column ${start + 1}`
+ : error.message;
+}
+
+export const compileJq = Effect.fnUntraced(function* (expression: string) {
+ const jq = yield* Effect.tryPromise({
+ try: () => import("@gabrielbryk/jq-ts"),
+ catch: (error) =>
+ `could not load the jq engine (${describeJqError(error)})`,
+ });
+ const ast = yield* Effect.try({
+ try: () => {
+ const parsed = jq.parse(expression);
+ jq.validate(parsed);
+ return parsed;
+ },
+ catch: describeJqError,
+ });
+ const filter: JqFilter = {
+ expression,
+ run: (input) =>
+ Effect.try({
+ try: () =>
+ jq.runAst(ast, input as Parameters<typeof jq.runAst>[1], {
+ limits: LIMITS,
+ now: new Date(),
+ }),
+ catch: describeJqError,
+ }),
+ };
+ return filter;
+});
diff --git a/packages/cli/src/jq/format-jq-output.test.ts b/packages/cli/src/jq/format-jq-output.test.ts
new file mode 100644
index 000000000..c1d59b1a2
--- /dev/null
+++ b/packages/cli/src/jq/format-jq-output.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from "vite-plus/test";
+import { formatJqResults } from "./format-jq-output.js";
+
+describe("formatJqResults", () => {
+ it("prints strings without quotes, one result per line", () => {
+ expect(formatJqResults(["KAN-1", "Fix login"])).toBe("KAN-1\nFix login\n");
+ });
+
+ it("prints other values as compact JSON", () => {
+ expect(formatJqResults([3, true, null, { id: "a" }, ["x"]])).toBe(
+ '3\ntrue\nnull\n{"id":"a"}\n["x"]\n',
+ );
+ });
+
+ it("prints nothing when the expression yields no results", () => {
+ expect(formatJqResults([])).toBe("");
+ });
+});
diff --git a/packages/cli/src/jq/format-jq-output.ts b/packages/cli/src/jq/format-jq-output.ts
new file mode 100644
index 000000000..fc5f5808f
--- /dev/null
+++ b/packages/cli/src/jq/format-jq-output.ts
@@ -0,0 +1,8 @@
+export function formatJqResults(results: ReadonlyArray<unknown>): string {
+ return results
+ .map(
+ (value) =>
+ `${typeof value === "string" ? value : (JSON.stringify(value) ?? "null")}\n`,
+ )
+ .join("");
+}
diff --git a/packages/cli/src/jq/jq-flag-value.ts b/packages/cli/src/jq/jq-flag-value.ts
new file mode 100644
index 000000000..1a659ba9c
--- /dev/null
+++ b/packages/cli/src/jq/jq-flag-value.ts
@@ -0,0 +1,16 @@
+import { Effect } from "effect";
+import { CliError } from "effect/cli";
+import { compileJq } from "./compile-jq.js";
+
+export const jqFlagValue = (expression: string) =>
+ compileJq(expression).pipe(
+ Effect.mapError(
+ (detail) =>
+ new CliError.InvalidValue({
+ option: "jq",
+ value: expression,
+ expected: `a jq expression (${detail})`,
+ kind: "flag",
+ }),
+ ),
+ );
diff --git a/packages/cli/src/labels/choose-label.ts b/packages/cli/src/labels/choose-label.ts
new file mode 100644
index 000000000..9a48a228f
--- /dev/null
+++ b/packages/cli/src/labels/choose-label.ts
@@ -0,0 +1,49 @@
+import { Effect, Option } from "effect";
+import type { Label } from "../api/labels.js";
+import { InvalidArgument } from "../errors/errors.js";
+import { Output } from "../output/output.js";
+import { pick } from "../prompts/pick.js";
+import { labelColorName } from "./label-colors.js";
+import { matchLabel } from "./match-label.js";
+
+export const chooseLabel = Effect.fn("labels.choose")(function* (
+ labels: ReadonlyArray<Label>,
+ reference: Option.Option<string>,
+ example: string,
+) {
+ const output = yield* Output;
+ if (Option.isNone(reference)) {
+ if (labels.length === 0) {
+ return yield* new InvalidArgument({
+ message: "This workspace has no labels yet.",
+ hint: "Create one with kaneo label create <name>.",
+ });
+ }
+ if (output.interactive) {
+ return yield* pick(
+ "Choose a label",
+ labels.map((label) => ({
+ title: label.name,
+ value: label,
+ description: labelColorName(label.color) ?? label.color,
+ })),
+ );
+ }
+ return yield* new InvalidArgument({
+ message: "A label is required.",
+ hint: `Pass a label name or id, for example ${example}.`,
+ });
+ }
+ const match = matchLabel(labels, reference.value);
+ if (match.kind === "found") return match.label;
+ if (match.kind === "ambiguous") {
+ return yield* new InvalidArgument({
+ message: `"${reference.value.trim()}" matches ${match.candidates.length} labels.`,
+ hint: `Pass the label id instead: ${match.candidates.map((label) => `${label.name} (${label.id})`).join(", ")}.`,
+ });
+ }
+ return yield* new InvalidArgument({
+ message: `No label named "${reference.value.trim()}" in this workspace.`,
+ hint: "Run kaneo label list to see the labels.",
+ });
+});
diff --git a/packages/cli/src/labels/delete-label-fully.test.ts b/packages/cli/src/labels/delete-label-fully.test.ts
new file mode 100644
index 000000000..15bed2107
--- /dev/null
+++ b/packages/cli/src/labels/delete-label-fully.test.ts
@@ -0,0 +1,80 @@
+import { Effect, Fiber, Layer, Result, Schema } from "effect";
+import { TestClock } from "effect/testing";
+import { describe, expect, it } from "vite-plus/test";
+import { KaneoApi } from "../api/kaneo-api.js";
+import { RateLimited } from "../errors/errors.js";
+import { deleteLabelFully } from "./delete-label-fully.js";
+
+type Reply =
+ | { readonly status: 200 | 202 }
+ | { readonly status: 429; readonly retryAfter: number | null };
+
+function scripted(replies: ReadonlyArray<Reply>) {
+ const calls: Array<{ method: string; path: string; at: number }> = [];
+ let index = 0;
+ const layer = Layer.succeed(KaneoApi, {
+ request: (method, path, schema) =>
+ Effect.gen(function* () {
+ const at = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
+ calls.push({ method, path, at });
+ const reply = replies[Math.min(index, replies.length - 1)] ?? {
+ status: 200,
+ };
+ index += 1;
+ if (reply.status === 429) {
+ return yield* new RateLimited({
+ retryAfterSeconds: reply.retryAfter,
+ });
+ }
+ return yield* Schema.decodeUnknownEffect(schema)({
+ id: "l_bug",
+ name: "Bug",
+ ...(reply.status === 202 ? { pendingDeletion: true } : {}),
+ }).pipe(Effect.orDie);
+ }),
+ });
+ return { layer, calls };
+}
+
+const run = (layer: Layer.Layer<KaneoApi>, advance: string) =>
+ Effect.runPromise(
+ Effect.gen(function* () {
+ const fiber = yield* Effect.forkChild(
+ Effect.result(deleteLabelFully("l_bug")),
+ );
+ yield* TestClock.adjust(advance as "1 second");
+ return yield* Fiber.join(fiber);
+ }).pipe(Effect.provide(Layer.merge(layer, TestClock.layer()))),
+ );
+
+describe("deleteLabelFully", () => {
+ it("repeats the DELETE after 202 until the server answers 200", async () => {
+ const api = scripted([{ status: 202 }, { status: 202 }, { status: 200 }]);
+ const result = await run(api.layer, "1 second");
+ expect(result).toEqual(Result.succeed({ id: "l_bug", name: "Bug" }));
+ expect(api.calls).toEqual([
+ { method: "DELETE", path: "/api/label/l_bug", at: 0 },
+ { method: "DELETE", path: "/api/label/l_bug", at: 0 },
+ { method: "DELETE", path: "/api/label/l_bug", at: 0 },
+ ]);
+ });
+
+ it("sleeps for Retry-After when the deletion lock is busy", async () => {
+ const api = scripted([
+ { status: 202 },
+ { status: 429, retryAfter: 20 },
+ { status: 429, retryAfter: null },
+ { status: 200 },
+ ]);
+ const result = await run(api.layer, "30 seconds");
+ expect(Result.isSuccess(result)).toBe(true);
+ expect(api.calls.map((call) => call.at)).toEqual([0, 0, 20_000, 21_000]);
+ });
+
+ it("gives up after about a minute of waiting", async () => {
+ const api = scripted([{ status: 429, retryAfter: 30 }]);
+ const result = await run(api.layer, "5 minutes");
+ expect(Result.isFailure(result) && result.failure._tag).toBe("RateLimited");
+ expect(api.calls.map((call) => call.at)).toEqual([0, 30_000, 60_000]);
+ });
+});
diff --git a/packages/cli/src/labels/delete-label-fully.ts b/packages/cli/src/labels/delete-label-fully.ts
new file mode 100644
index 000000000..fcbde9fd1
--- /dev/null
+++ b/packages/cli/src/labels/delete-label-fully.ts
@@ -0,0 +1,40 @@
+import { Duration, Effect } from "effect";
+import { deleteLabelStep, type LabelDeletion } from "../api/labels.js";
+import type { RateLimited } from "../errors/errors.js";
+import { type DeletionOutcome, nextDeletionStep } from "./deletion-step.js";
+
+type Attempt =
+ | {
+ readonly outcome: DeletionOutcome;
+ readonly deletion: LabelDeletion;
+ }
+ | { readonly outcome: DeletionOutcome; readonly busy: RateLimited };
+
+export const deleteLabelFully = Effect.fn("labels.deleteFully")(function* (
+ id: string,
+) {
+ let waited = 0;
+ for (;;) {
+ const attempt: Attempt = yield* deleteLabelStep(id).pipe(
+ Effect.map((deletion): Attempt => ({
+ outcome: { kind: deletion.pendingDeletion ? "pending" : "deleted" },
+ deletion,
+ })),
+ Effect.catchTag("RateLimited", (busy) =>
+ Effect.succeed<Attempt>({
+ outcome: { kind: "busy", retryAfterSeconds: busy.retryAfterSeconds },
+ busy,
+ }),
+ ),
+ );
+ const step = nextDeletionStep(attempt.outcome, waited);
+ if (step.kind === "done" && "deletion" in attempt) return attempt.deletion;
+ if (step.kind === "give-up" && "busy" in attempt) {
+ return yield* Effect.fail(attempt.busy);
+ }
+ if (step.kind === "wait") {
+ waited += step.seconds;
+ yield* Effect.sleep(Duration.seconds(step.seconds));
+ }
+ }
+});
diff --git a/packages/cli/src/labels/deletion-step.test.ts b/packages/cli/src/labels/deletion-step.test.ts
new file mode 100644
index 000000000..3a0438c40
--- /dev/null
+++ b/packages/cli/src/labels/deletion-step.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from "vite-plus/test";
+import { nextDeletionStep } from "./deletion-step.js";
+
+describe("nextDeletionStep", () => {
+ it("finishes on 200 and repeats on 202", () => {
+ expect(nextDeletionStep({ kind: "deleted" }, 0)).toEqual({ kind: "done" });
+ expect(nextDeletionStep({ kind: "pending" }, 59)).toEqual({
+ kind: "repeat",
+ });
+ });
+
+ it("waits for Retry-After, at least one second", () => {
+ expect(
+ nextDeletionStep({ kind: "busy", retryAfterSeconds: 15 }, 0),
+ ).toEqual({ kind: "wait", seconds: 15 });
+ expect(
+ nextDeletionStep({ kind: "busy", retryAfterSeconds: null }, 0),
+ ).toEqual({ kind: "wait", seconds: 1 });
+ expect(nextDeletionStep({ kind: "busy", retryAfterSeconds: 0 }, 0)).toEqual(
+ { kind: "wait", seconds: 1 },
+ );
+ });
+
+ it("caps the total wait and then gives up", () => {
+ expect(
+ nextDeletionStep({ kind: "busy", retryAfterSeconds: 120 }, 20),
+ ).toEqual({ kind: "wait", seconds: 40 });
+ expect(
+ nextDeletionStep({ kind: "busy", retryAfterSeconds: 1 }, 60),
+ ).toEqual({ kind: "give-up" });
+ });
+});
diff --git a/packages/cli/src/labels/deletion-step.ts b/packages/cli/src/labels/deletion-step.ts
new file mode 100644
index 000000000..609300fee
--- /dev/null
+++ b/packages/cli/src/labels/deletion-step.ts
@@ -0,0 +1,25 @@
+export const MAX_BUSY_WAIT_SECONDS = 60;
+
+export type DeletionOutcome =
+ | { readonly kind: "deleted" }
+ | { readonly kind: "pending" }
+ | { readonly kind: "busy"; readonly retryAfterSeconds: number | null };
+
+export type DeletionStep =
+ | { readonly kind: "done" }
+ | { readonly kind: "repeat" }
+ | { readonly kind: "wait"; readonly seconds: number }
+ | { readonly kind: "give-up" };
+
+export function nextDeletionStep(
+ outcome: DeletionOutcome,
+ waitedSeconds: number,
+ maxWaitSeconds = MAX_BUSY_WAIT_SECONDS,
+): DeletionStep {
+ if (outcome.kind === "deleted") return { kind: "done" };
+ if (outcome.kind === "pending") return { kind: "repeat" };
+ const seconds = Math.max(1, outcome.retryAfterSeconds ?? 1);
+ const remaining = maxWaitSeconds - waitedSeconds;
+ if (remaining <= 0) return { kind: "give-up" };
+ return { kind: "wait", seconds: Math.min(seconds, remaining) };
+}
diff --git a/packages/cli/src/labels/label-colors.test.ts b/packages/cli/src/labels/label-colors.test.ts
new file mode 100644
index 000000000..e0e25bf67
--- /dev/null
+++ b/packages/cli/src/labels/label-colors.test.ts
@@ -0,0 +1,91 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import {
+ defaultLabelColor,
+ FALLBACK_LABEL_HEX,
+ LABEL_PALETTE,
+ labelColorHex,
+ labelColorName,
+ parseLabelColor,
+} from "./label-colors.js";
+
+const parsed = (input: string) => {
+ const result = parseLabelColor(input);
+ return Result.isSuccess(result) ? result.success : result.failure.message;
+};
+
+describe("labelColorHex", () => {
+ it("maps the web palette keys and names to hex", () => {
+ expect(labelColorHex("gray")).toBe("#79716b");
+ expect(labelColorHex("red")).toBe("#e7000b");
+ expect(labelColorHex("Crimson")).toBe("#e7000b");
+ expect(labelColorHex("dark-gray")).toBe("#62748e");
+ });
+
+ it("normalizes hex colors and drops alpha", () => {
+ expect(labelColorHex("#FF6600")).toBe("#ff6600");
+ expect(labelColorHex("#f60")).toBe("#ff6600");
+ expect(labelColorHex("#f60c")).toBe("#ff6600");
+ expect(labelColorHex("#ff660080")).toBe("#ff6600");
+ expect(labelColorHex("ff6600")).toBe("#ff6600");
+ });
+
+ it("falls back for colors it cannot read", () => {
+ expect(labelColorHex("blue")).toBe(FALLBACK_LABEL_HEX);
+ expect(labelColorHex("#12345")).toBe(FALLBACK_LABEL_HEX);
+ expect(labelColorHex("")).toBe(FALLBACK_LABEL_HEX);
+ });
+});
+
+describe("labelColorName", () => {
+ it("names palette colors and leaves hex alone", () => {
+ expect(labelColorName("purple")).toBe("lavender");
+ expect(labelColorName("#8e51ff")).toBeNull();
+ });
+});
+
+describe("parseLabelColor", () => {
+ it("stores palette names as the keys the web app uses", () => {
+ expect(parsed("crimson")).toBe("red");
+ expect(parsed(" Lavender ")).toBe("purple");
+ expect(parsed("red")).toBe("red");
+ expect(parsed("dark-gray")).toBe("dark-gray");
+ });
+
+ it("accepts hex with or without the hash", () => {
+ expect(parsed("#E7000B")).toBe("#e7000b");
+ expect(parsed("e7000b")).toBe("#e7000b");
+ expect(parsed("#abc")).toBe("#aabbcc");
+ });
+
+ it("rejects anything else with the accepted names in the hint", () => {
+ const result = parseLabelColor("blurple");
+ expect(Result.isFailure(result) && result.failure.message).toBe(
+ '"blurple" is not a label color.',
+ );
+ expect(Result.isFailure(result) && result.failure.hint).toContain(
+ "stone, slate, lavender",
+ );
+ expect(parsed("#12345")).toBe('"#12345" is not a label color.');
+ expect(parsed("#ff660080")).toBe('"#ff660080" is not a label color.');
+ });
+});
+
+describe("defaultLabelColor", () => {
+ it("is stable for the same name", () => {
+ expect(defaultLabelColor("Bug", [])).toBe(defaultLabelColor("bug", []));
+ });
+
+ it("prefers palette colors no label uses yet", () => {
+ const used = LABEL_PALETTE.slice(1).map((color) => color.key);
+ expect(defaultLabelColor("Anything", used)).toBe("gray");
+ expect(defaultLabelColor("Else", [...used.slice(1), "#79716b"])).toBe(
+ LABEL_PALETTE[1]?.key,
+ );
+ });
+
+ it("still picks a palette color when every one is taken", () => {
+ const all = LABEL_PALETTE.map((color) => color.key);
+ expect(all).toContain(defaultLabelColor("Bug", all));
+ });
+});
diff --git a/packages/cli/src/labels/label-colors.ts b/packages/cli/src/labels/label-colors.ts
new file mode 100644
index 000000000..d7d1de32b
--- /dev/null
+++ b/packages/cli/src/labels/label-colors.ts
@@ -0,0 +1,89 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+
+export type PaletteColor = {
+ readonly key: string;
+ readonly name: string;
+ readonly hex: string;
+};
+
+export const LABEL_PALETTE: ReadonlyArray<PaletteColor> = [
+ { key: "gray", name: "Stone", hex: "#79716b" },
+ { key: "dark-gray", name: "Slate", hex: "#62748e" },
+ { key: "purple", name: "Lavender", hex: "#8e51ff" },
+ { key: "teal", name: "Sage", hex: "#009966" },
+ { key: "green", name: "Forest", hex: "#00a63e" },
+ { key: "yellow", name: "Amber", hex: "#e17100" },
+ { key: "orange", name: "Terracotta", hex: "#f54900" },
+ { key: "pink", name: "Rose", hex: "#ec003f" },
+ { key: "red", name: "Crimson", hex: "#e7000b" },
+];
+
+export const FALLBACK_LABEL_HEX = "#a1a1a1";
+
+const HEX = /^#?([\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i;
+
+function findPalette(value: string): PaletteColor | undefined {
+ const wanted = value.trim().toLowerCase();
+ return LABEL_PALETTE.find(
+ (color) => color.key === wanted || color.name.toLowerCase() === wanted,
+ );
+}
+
+function expandHex(digits: string): string {
+ const short = digits.length <= 4;
+ const rgb = short
+ ? digits
+ .slice(0, 3)
+ .split("")
+ .map((digit) => digit + digit)
+ .join("")
+ : digits.slice(0, 6);
+ return `#${rgb.toLowerCase()}`;
+}
+
+export function labelColorHex(color: string): string {
+ const palette = findPalette(color);
+ if (palette) return palette.hex;
+ const match = HEX.exec(color.trim());
+ return match?.[1] ? expandHex(match[1]) : FALLBACK_LABEL_HEX;
+}
+
+export function labelColorName(color: string): string | null {
+ return findPalette(color)?.name.toLowerCase() ?? null;
+}
+
+const COLOR_INPUT = /^#?([\da-f]{3}|[\da-f]{6})$/i;
+
+export function parseLabelColor(
+ input: string,
+): Result.Result<string, InvalidArgument> {
+ const palette = findPalette(input);
+ if (palette) return Result.succeed(palette.key);
+ const match = COLOR_INPUT.exec(input.trim());
+ if (match?.[1]) return Result.succeed(expandHex(match[1]));
+ return Result.fail(
+ new InvalidArgument({
+ message: `"${input}" is not a label color.`,
+ hint: `Use a hex color such as #e7000b, or one of ${LABEL_PALETTE.map((color) => color.name.toLowerCase()).join(", ")}.`,
+ }),
+ );
+}
+
+function hash(value: string): number {
+ let result = 0;
+ for (const char of value.normalize("NFKC").toLowerCase()) {
+ result = (result * 31 + (char.codePointAt(0) ?? 0)) >>> 0;
+ }
+ return result;
+}
+
+export function defaultLabelColor(
+ name: string,
+ usedColors: ReadonlyArray<string>,
+): string {
+ const used = new Set(usedColors.map((color) => labelColorHex(color)));
+ const unused = LABEL_PALETTE.filter((color) => !used.has(color.hex));
+ const pool = unused.length > 0 ? unused : LABEL_PALETTE;
+ return pool[hash(name) % pool.length]?.key ?? "gray";
+}
diff --git a/packages/cli/src/labels/label-json.ts b/packages/cli/src/labels/label-json.ts
new file mode 100644
index 000000000..4b17269b9
--- /dev/null
+++ b/packages/cli/src/labels/label-json.ts
@@ -0,0 +1,20 @@
+import type { Label } from "../api/labels.js";
+
+export type LabelJson = {
+ readonly id: string;
+ readonly name: string;
+ readonly color: string;
+};
+
+export type TaskLabelJson = {
+ readonly name: string;
+ readonly color: string;
+};
+
+export function toLabelJson(label: Label): LabelJson {
+ return { id: label.id, name: label.name, color: label.color };
+}
+
+export function toTaskLabelJson(label: Label): TaskLabelJson {
+ return { name: label.name, color: label.color };
+}
diff --git a/packages/cli/src/labels/match-label.test.ts b/packages/cli/src/labels/match-label.test.ts
new file mode 100644
index 000000000..95b83d491
--- /dev/null
+++ b/packages/cli/src/labels/match-label.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from "vite-plus/test";
+import {
+ findNameClash,
+ labelUsage,
+ matchLabel,
+ quoteName,
+ workspaceLabels,
+} from "./match-label.js";
+import { taskLabel, workspaceLabel } from "./test-labels.js";
+
+const bug = workspaceLabel("l_bug", "Bug", { color: "red" });
+const docs = workspaceLabel("l_docs", "Docs");
+const feature = workspaceLabel("l_feature", "Feature request");
+
+describe("matchLabel", () => {
+ it("matches by id, then by name ignoring case and spaces", () => {
+ expect(matchLabel([bug, docs], "l_docs")).toEqual({
+ kind: "found",
+ label: docs,
+ });
+ expect(matchLabel([bug, docs], " bug ")).toEqual({
+ kind: "found",
+ label: bug,
+ });
+ expect(matchLabel([feature], "FEATURE REQUEST")).toEqual({
+ kind: "found",
+ label: feature,
+ });
+ });
+
+ it("prefers the exact spelling when names differ only by case", () => {
+ const lower = workspaceLabel("l_bug2", "bug");
+ expect(matchLabel([bug, lower], "bug")).toEqual({
+ kind: "found",
+ label: lower,
+ });
+ expect(matchLabel([bug, lower], "BUG")).toEqual({
+ kind: "ambiguous",
+ candidates: [bug, lower],
+ });
+ });
+
+ it("reports no match", () => {
+ expect(matchLabel([bug], "Docs")).toEqual({ kind: "none" });
+ });
+});
+
+describe("workspaceLabels and labelUsage", () => {
+ const labels = [
+ bug,
+ docs,
+ taskLabel("c1", "Bug", "t1"),
+ taskLabel("c2", "Bug", "t2"),
+ taskLabel("c3", "Docs", "t1"),
+ taskLabel("c4", "legacy", "t3"),
+ ];
+
+ it("keeps only workspace level labels", () => {
+ expect(workspaceLabels(labels)).toEqual([bug, docs]);
+ });
+
+ it("counts the task copies per name", () => {
+ const usage = labelUsage(labels);
+ expect(usage.get("Bug")).toBe(2);
+ expect(usage.get("Docs")).toBe(1);
+ expect(usage.get("Feature")).toBeUndefined();
+ });
+});
+
+describe("findNameClash", () => {
+ it("finds another workspace label with the same name in any case", () => {
+ expect(findNameClash([bug, docs], "docs", bug)).toEqual({
+ kind: "workspace",
+ label: docs,
+ });
+ expect(findNameClash([bug, docs], "BUG")).toEqual({
+ kind: "workspace",
+ label: bug,
+ });
+ });
+
+ it("allows a label to keep or recase its own name", () => {
+ expect(findNameClash([bug, docs], "Bug", bug)).toBeNull();
+ expect(findNameClash([bug, docs], "bug", bug)).toBeNull();
+ });
+
+ it("finds tasks that already carry the new name next to the old one", () => {
+ const labels = [
+ bug,
+ taskLabel("c1", "Bug", "t1"),
+ taskLabel("c2", "Defect", "t1"),
+ taskLabel("c3", "Defect", "t2"),
+ ];
+ expect(findNameClash(labels, "Defect", bug)).toEqual({ kind: "task" });
+ expect(findNameClash(labels, "Issue", bug)).toBeNull();
+ });
+});
+
+describe("quoteName", () => {
+ it("quotes names a shell would split", () => {
+ expect(quoteName("Bug")).toBe("Bug");
+ expect(quoteName("needs-review")).toBe("needs-review");
+ expect(quoteName("Feature request")).toBe('"Feature request"');
+ });
+});
diff --git a/packages/cli/src/labels/match-label.ts b/packages/cli/src/labels/match-label.ts
new file mode 100644
index 000000000..b1c1e4543
--- /dev/null
+++ b/packages/cli/src/labels/match-label.ts
@@ -0,0 +1,83 @@
+import type { Label } from "../api/labels.js";
+
+export type LabelMatch =
+ | { readonly kind: "found"; readonly label: Label }
+ | { readonly kind: "ambiguous"; readonly candidates: ReadonlyArray<Label> }
+ | { readonly kind: "none" };
+
+export function normalizeLabelName(name: string): string {
+ return name.normalize("NFKC").trim().toLowerCase();
+}
+
+export function workspaceLabels(
+ labels: ReadonlyArray<Label>,
+): ReadonlyArray<Label> {
+ return labels.filter((label) => label.taskId === null);
+}
+
+export function matchLabel(
+ labels: ReadonlyArray<Label>,
+ reference: string,
+): LabelMatch {
+ const trimmed = reference.trim();
+ const byId = labels.find((label) => label.id === trimmed);
+ if (byId) return { kind: "found", label: byId };
+ const wanted = normalizeLabelName(reference);
+ const named = labels.filter(
+ (label) => normalizeLabelName(label.name) === wanted,
+ );
+ const exact = named.filter((label) => label.name.trim() === trimmed);
+ const [first] = named;
+ if (!first) return { kind: "none" };
+ if (named.length === 1) return { kind: "found", label: first };
+ const [exactOnly] = exact;
+ if (exact.length === 1 && exactOnly) {
+ return { kind: "found", label: exactOnly };
+ }
+ return { kind: "ambiguous", candidates: named };
+}
+
+export function labelUsage(
+ labels: ReadonlyArray<Label>,
+): ReadonlyMap<string, number> {
+ const counts = new Map<string, number>();
+ for (const label of labels) {
+ if (label.taskId === null) continue;
+ counts.set(label.name, (counts.get(label.name) ?? 0) + 1);
+ }
+ return counts;
+}
+
+export type NameClash =
+ | { readonly kind: "workspace"; readonly label: Label }
+ | { readonly kind: "task" };
+
+export function findNameClash(
+ labels: ReadonlyArray<Label>,
+ name: string,
+ except?: Label,
+): NameClash | null {
+ const wanted = normalizeLabelName(name);
+ const clash = workspaceLabels(labels).find(
+ (label) =>
+ label.id !== except?.id && normalizeLabelName(label.name) === wanted,
+ );
+ if (clash) return { kind: "workspace", label: clash };
+ if (!except || except.name === name) return null;
+ const tasksWithOld = new Set(
+ labels
+ .filter((label) => label.taskId !== null && label.name === except.name)
+ .map((label) => label.taskId),
+ );
+ const sharesTask = labels.some(
+ (label) =>
+ label.taskId !== null &&
+ label.name === name &&
+ tasksWithOld.has(label.taskId),
+ );
+ return sharesTask ? { kind: "task" } : null;
+}
+
+export function quoteName(name: string): string {
+ return /^[\p{L}\p{N}._-]+$/u.test(name) ? name : `"${name}"`;
+}
diff --git a/packages/cli/src/labels/name-clash-error.ts b/packages/cli/src/labels/name-clash-error.ts
new file mode 100644
index 000000000..97b985453
--- /dev/null
+++ b/packages/cli/src/labels/name-clash-error.ts
@@ -0,0 +1,26 @@
+import { InvalidArgument } from "../errors/errors.js";
+import { type NameClash, quoteName } from "./match-label.js";
+
+export function nameClashError(
+ clash: NameClash,
+ name: string,
+ currentName?: string,
+): InvalidArgument {
+ if (clash.kind === "task") {
+ return new InvalidArgument({
+ message: `Some tasks already have a label named "${name}" next to "${currentName ?? name}".`,
+ hint: `Remove one of the two from those tasks first, or pick another name.`,
+ });
+ }
+ const existing = quoteName(clash.label.name);
+ if (clash.label.deletionStartedAt) {
+ return new InvalidArgument({
+ message: `The label "${clash.label.name}" is still being deleted.`,
+ hint: `Run kaneo label delete ${existing} to finish, then try again.`,
+ });
+ }
+ return new InvalidArgument({
+ message: `A label named "${clash.label.name}" already exists.`,
+ hint: `Pick another name, or change the existing one with kaneo label edit ${existing}.`,
+ });
+}
diff --git a/packages/cli/src/labels/pick-labels.test.ts b/packages/cli/src/labels/pick-labels.test.ts
new file mode 100644
index 000000000..9f85587d7
--- /dev/null
+++ b/packages/cli/src/labels/pick-labels.test.ts
@@ -0,0 +1,57 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { pickLabels } from "./pick-labels.js";
+import { taskLabel, workspaceLabel } from "./test-labels.js";
+
+const bug = workspaceLabel("l_bug", "Bug");
+const docs = workspaceLabel("l_docs", "Docs");
+const labels = [docs, bug, taskLabel("c1", "Bug", "t1")];
+
+const failure = <A>(
+ result: Result.Result<A, { message: string; hint?: string }>,
+) =>
+ Result.isFailure(result)
+ ? { message: result.failure.message, hint: result.failure.hint }
+ : null;
+
+describe("pickLabels", () => {
+ it("returns workspace labels in the order asked, without duplicates", () => {
+ expect(pickLabels(labels, ["docs", "BUG", "Docs"])).toEqual(
+ Result.succeed([docs, bug]),
+ );
+ });
+
+ it("never picks a task copy", () => {
+ expect(pickLabels(labels, ["c1"])).toEqual(Result.fail(expect.anything()));
+ });
+
+ it("lists every unknown name and the existing labels", () => {
+ expect(
+ failure(pickLabels(labels, ["Bug", "Urgent", "Needs review"])),
+ ).toEqual({
+ message: 'No labels named "Urgent", "Needs review" in this workspace.',
+ hint: "Existing labels: Bug, Docs. Create one with kaneo label create Urgent.",
+ });
+ expect(failure(pickLabels([], ["Needs review"]))).toEqual({
+ message: 'No label named "Needs review" in this workspace.',
+ hint: 'This workspace has no labels yet. Create one with kaneo label create "Needs review".',
+ });
+ });
+
+ it("refuses labels that are being deleted", () => {
+ const deleting = workspaceLabel("l_old", "Old", {
+ deletionStartedAt: "2026-10-01T00:00:00.000Z",
+ });
+ expect(failure(pickLabels([deleting], ["old"]))).toEqual({
+ message: "The label Old is being deleted.",
+ hint: "Run kaneo label delete Old to finish deleting it.",
+ });
+ });
+
+ it("asks for an id when a name is ambiguous", () => {
+ const lower = workspaceLabel("l_bug2", "bug");
+ expect(failure(pickLabels([bug, lower], ["BUG"]))?.hint).toBe(
+ "Pass the label id instead: Bug (l_bug), bug (l_bug2).",
+ );
+ });
+});
diff --git a/packages/cli/src/labels/pick-labels.ts b/packages/cli/src/labels/pick-labels.ts
new file mode 100644
index 000000000..2671cedc4
--- /dev/null
+++ b/packages/cli/src/labels/pick-labels.ts
@@ -0,0 +1,61 @@
+import { Result } from "effect";
+import type { Label } from "../api/labels.js";
+import { InvalidArgument } from "../errors/errors.js";
+import { matchLabel, quoteName, workspaceLabels } from "./match-label.js";
+
+function existingHint(labels: ReadonlyArray<Label>): string {
+ if (labels.length === 0) return "This workspace has no labels yet.";
+ const names = labels
+ .map((label) => label.name)
+ .sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
+ const shown = names.slice(0, 10).join(", ");
+ return names.length > 10
+ ? `Existing labels: ${shown}, and ${names.length - 10} more.`
+ : `Existing labels: ${shown}.`;
+}
+
+export function pickLabels(
+ labels: ReadonlyArray<Label>,
+ names: ReadonlyArray<string>,
+): Result.Result<ReadonlyArray<Label>, InvalidArgument> {
+ const available = workspaceLabels(labels);
+ const picked: Label[] = [];
+ const missing: string[] = [];
+ for (const name of names) {
+ const match = matchLabel(available, name);
+ if (match.kind === "none") {
+ if (!missing.includes(name.trim())) missing.push(name.trim());
+ continue;
+ }
+ if (match.kind === "ambiguous") {
+ return Result.fail(
+ new InvalidArgument({
+ message: `"${name.trim()}" matches ${match.candidates.length} labels.`,
+ hint: `Pass the label id instead: ${match.candidates.map((label) => `${label.name} (${label.id})`).join(", ")}.`,
+ }),
+ );
+ }
+ if (match.label.deletionStartedAt) {
+ return Result.fail(
+ new InvalidArgument({
+ message: `The label ${match.label.name} is being deleted.`,
+ hint: `Run kaneo label delete ${quoteName(match.label.name)} to finish deleting it.`,
+ }),
+ );
+ }
+ if (!picked.some((label) => label.id === match.label.id)) {
+ picked.push(match.label);
+ }
+ }
+ const [first] = missing;
+ if (first === undefined) return Result.succeed(picked);
+ return Result.fail(
+ new InvalidArgument({
+ message:
+ missing.length === 1
+ ? `No label named "${first}" in this workspace.`
+ : `No labels named ${missing.map((name) => `"${name}"`).join(", ")} in this workspace.`,
+ hint: `${existingHint(available)} Create one with kaneo label create ${quoteName(first)}.`,
+ }),
+ );
+}
diff --git a/packages/cli/src/labels/plan-task-labels.test.ts b/packages/cli/src/labels/plan-task-labels.test.ts
new file mode 100644
index 000000000..c480a3b88
--- /dev/null
+++ b/packages/cli/src/labels/plan-task-labels.test.ts
@@ -0,0 +1,57 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { describeLabelChanges, planTaskLabels } from "./plan-task-labels.js";
+import { taskLabel, workspaceLabel } from "./test-labels.js";
+
+const bug = workspaceLabel("l_bug", "Bug");
+const docsCopy = taskLabel("c_docs", "Docs", "t1");
+const bugCopy = taskLabel("c_bug", "Bug", "t1");
+
+describe("planTaskLabels", () => {
+ it("removes the task copies by name", () => {
+ expect(
+ planTaskLabels({
+ taskRef: "KAN-1",
+ taskLabels: [docsCopy],
+ add: [bug],
+ removeNames: ["docs", "Docs"],
+ }),
+ ).toEqual(Result.succeed({ add: [bug], remove: [docsCopy] }));
+ });
+
+ it("fails when the task does not have the label", () => {
+ const result = planTaskLabels({
+ taskRef: "KAN-1",
+ taskLabels: [docsCopy],
+ add: [],
+ removeNames: ["Bug"],
+ });
+ expect(Result.isFailure(result) && result.failure.message).toBe(
+ 'KAN-1 has no label named "Bug".',
+ );
+ expect(Result.isFailure(result) && result.failure.hint).toBe(
+ "Its labels: Docs.",
+ );
+ });
+
+ it("refuses to add and remove the same label", () => {
+ const result = planTaskLabels({
+ taskRef: "KAN-1",
+ taskLabels: [bugCopy],
+ add: [bug],
+ removeNames: ["bug"],
+ });
+ expect(Result.isFailure(result) && result.failure.message).toBe(
+ "Bug is both added and removed.",
+ );
+ });
+});
+
+describe("describeLabelChanges", () => {
+ it("lists additions then removals", () => {
+ expect(describeLabelChanges({ add: [bug], remove: [docsCopy] })).toBe(
+ "labels +Bug -Docs",
+ );
+ expect(describeLabelChanges({ add: [], remove: [] })).toBeNull();
+ });
+});
diff --git a/packages/cli/src/labels/plan-task-labels.ts b/packages/cli/src/labels/plan-task-labels.ts
new file mode 100644
index 000000000..862c548f5
--- /dev/null
+++ b/packages/cli/src/labels/plan-task-labels.ts
@@ -0,0 +1,59 @@
+import { Result } from "effect";
+import type { Label } from "../api/labels.js";
+import { InvalidArgument } from "../errors/errors.js";
+import { matchLabel, normalizeLabelName } from "./match-label.js";
+
+export type TaskLabelPlan = {
+ readonly add: ReadonlyArray<Label>;
+ readonly remove: ReadonlyArray<Label>;
+};
+
+export function planTaskLabels(options: {
+ readonly taskRef: string;
+ readonly taskLabels: ReadonlyArray<Label>;
+ readonly add: ReadonlyArray<Label>;
+ readonly removeNames: ReadonlyArray<string>;
+}): Result.Result<TaskLabelPlan, InvalidArgument> {
+ const remove: Label[] = [];
+ for (const name of options.removeNames) {
+ const match = matchLabel(options.taskLabels, name);
+ if (match.kind !== "found") {
+ const names = options.taskLabels.map((label) => label.name);
+ return Result.fail(
+ new InvalidArgument({
+ message: `${options.taskRef} has no label named "${name.trim()}".`,
+ hint:
+ names.length > 0
+ ? `Its labels: ${names.join(", ")}.`
+ : "It has no labels.",
+ }),
+ );
+ }
+ if (!remove.some((label) => label.id === match.label.id)) {
+ remove.push(match.label);
+ }
+ }
+ const removed = new Set(
+ remove.map((label) => normalizeLabelName(label.name)),
+ );
+ const both = options.add.find((label) =>
+ removed.has(normalizeLabelName(label.name)),
+ );
+ if (both) {
+ return Result.fail(
+ new InvalidArgument({
+ message: `${both.name} is both added and removed.`,
+ hint: "Pass it to --add-label or --remove-label, not both.",
+ }),
+ );
+ }
+ return Result.succeed({ add: options.add, remove });
+}
+
+export function describeLabelChanges(plan: TaskLabelPlan): string | null {
+ const parts = [
+ ...plan.add.map((label) => `+${label.name}`),
+ ...plan.remove.map((label) => `-${label.name}`),
+ ];
+ return parts.length > 0 ? `labels ${parts.join(" ")}` : null;
+}
diff --git a/packages/cli/src/labels/render-label-change.test.ts b/packages/cli/src/labels/render-label-change.test.ts
new file mode 100644
index 000000000..69ec9f1cf
--- /dev/null
+++ b/packages/cli/src/labels/render-label-change.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { renderLabelChange } from "./render-label-change.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+describe("renderLabelChange", () => {
+ it("confirms a created label with its chip", () => {
+ expect(
+ renderLabelChange(ui, { verb: "Created", name: "Bug", color: "red" }),
+ ).toEqual(["", " ✓ Created label ● Bug", ""]);
+ });
+
+ it("adds the detail after a separator", () => {
+ expect(
+ renderLabelChange(ui, {
+ verb: "Updated",
+ name: "Defect",
+ color: "red",
+ detail: "renamed from Bug, color crimson",
+ })[1],
+ ).toBe(" ✓ Updated label ● Defect · renamed from Bug, color crimson");
+ expect(
+ renderLabelChange(ui, {
+ verb: "Deleted",
+ name: "Bug",
+ color: "red",
+ detail: "removed from 3 tasks",
+ })[1],
+ ).toBe(" ✓ Deleted label ● Bug · removed from 3 tasks");
+ });
+});
diff --git a/packages/cli/src/labels/render-label-change.ts b/packages/cli/src/labels/render-label-change.ts
new file mode 100644
index 000000000..088136615
--- /dev/null
+++ b/packages/cli/src/labels/render-label-change.ts
@@ -0,0 +1,21 @@
+import { labelChip } from "../render/label-chip.js";
+import type { Ui } from "../render/ui.js";
+
+export type LabelChange = {
+ readonly verb: "Created" | "Updated" | "Deleted";
+ readonly name: string;
+ readonly color: string;
+ readonly detail?: string;
+};
+
+export function renderLabelChange(ui: Ui, change: LabelChange): string[] {
+ const { theme, glyphs } = ui;
+ const detail = change.detail
+ ? ` ${theme.muted(glyphs.separator)} ${change.detail}`
+ : "";
+ return [
+ "",
+ ` ${theme.success(glyphs.tick)} ${change.verb} label ${labelChip(ui, change.color)} ${theme.strong(change.name)}${detail}`,
+ "",
+ ];
+}
diff --git a/packages/cli/src/labels/render-label-list.test.ts b/packages/cli/src/labels/render-label-list.test.ts
new file mode 100644
index 000000000..780d85f7f
--- /dev/null
+++ b/packages/cli/src/labels/render-label-list.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import { type LabelListRow, renderLabelList } from "./render-label-list.js";
+
+const ui = (columns = 80) =>
+ makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns,
+ });
+
+const rows: ReadonlyArray<LabelListRow> = [
+ { id: "l1", name: "Bug", color: "red", tasks: 3, deleting: false },
+ { id: "l2", name: "Docs", color: "#00ff00", tasks: 1, deleting: false },
+ { id: "l3", name: "Old", color: "gray", tasks: 0, deleting: true },
+];
+
+describe("renderLabelList", () => {
+ it("shows a chip, the name and how many tasks use it", () => {
+ expect(renderLabelList(ui(), rows)).toEqual([
+ "",
+ " ● Bug 3 tasks",
+ " ● Docs 1 task",
+ " ● Old · deleting no tasks",
+ "",
+ ]);
+ });
+
+ it("drops the count before truncating names on narrow terminals", () => {
+ const lines = renderLabelList(ui(20), rows);
+ expect(lines[1]).toBe(" ● Bug");
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(20);
+ });
+
+ it("colors the chip at truecolor", () => {
+ const colored = makeUi({
+ color: 3,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+ });
+ expect(renderLabelList(colored, rows)[1]).toContain(
+ "\u001b[38;2;231;0;11m●\u001b[39m",
+ );
+ });
+
+ it("points to label create when there are none", () => {
+ expect(renderLabelList(ui(), [])).toEqual([
+ "",
+ " No labels in this workspace yet. Create one with kaneo label create <name>.",
+ "",
+ ]);
+ });
+});
diff --git a/packages/cli/src/labels/render-label-list.ts b/packages/cli/src/labels/render-label-list.ts
new file mode 100644
index 000000000..8bc4c9c40
--- /dev/null
+++ b/packages/cli/src/labels/render-label-list.ts
@@ -0,0 +1,68 @@
+import { type Cell, text } from "../render/cell.js";
+import { labelChipSegment } from "../render/label-chip.js";
+import { renderTable } from "../render/table.js";
+import type { Ui } from "../render/ui.js";
+
+export type LabelListRow = {
+ readonly id: string;
+ readonly name: string;
+ readonly color: string;
+ readonly tasks: number;
+ readonly deleting: boolean;
+};
+
+function taskCount(count: number): string {
+ if (count === 0) return "no tasks";
+ return count === 1 ? "1 task" : `${count} tasks`;
+}
+
+export function renderLabelList(
+ ui: Ui,
+ rows: ReadonlyArray<LabelListRow>,
+): string[] {
+ const { theme, glyphs } = ui;
+ if (rows.length === 0) {
+ return [
+ "",
+ ` ${theme.muted("No labels in this workspace yet. Create one with kaneo label create <name>.")}`,
+ "",
+ ];
+ }
+ return [
+ "",
+ ...renderTable(
+ ui,
+ rows,
+ [
+ {
+ header: "",
+ cell: (row): Cell => [labelChipSegment(ui, row.color)],
+ },
+ {
+ header: "Name",
+ flex: true,
+ minWidth: 12,
+ cell: (row): Cell => [
+ text(row.name, row.deleting ? theme.muted : undefined),
+ ...(row.deleting
+ ? [text(` ${glyphs.separator} deleting`, theme.warning)]
+ : []),
+ ],
+ },
+ {
+ header: "Tasks",
+ align: "right",
+ optional: true,
+ cell: (row): Cell => [
+ text(
+ taskCount(row.tasks),
+ row.tasks === 0 ? theme.muted : undefined,
+ ),
+ ],
+ },
+ ],
+ { width: ui.caps.columns, indent: 2, gap: 2 },
+ ),
+ "",
+ ];
+}
diff --git a/packages/cli/src/labels/resolve-labels.ts b/packages/cli/src/labels/resolve-labels.ts
new file mode 100644
index 000000000..b75544174
--- /dev/null
+++ b/packages/cli/src/labels/resolve-labels.ts
@@ -0,0 +1,12 @@
+import { Effect } from "effect";
+import { type Label, listWorkspaceLabels } from "../api/labels.js";
+import { pickLabels } from "./pick-labels.js";
+
+export const resolveLabels = Effect.fn("labels.resolve")(function* (
+ workspaceId: string,
+ names: ReadonlyArray<string>,
+) {
+ if (names.length === 0) return [] as ReadonlyArray<Label>;
+ const labels = yield* listWorkspaceLabels(workspaceId);
+ return yield* Effect.fromResult(pickLabels(labels, names));
+});
diff --git a/packages/cli/src/labels/task-label-edits.ts b/packages/cli/src/labels/task-label-edits.ts
new file mode 100644
index 000000000..c81cd5c28
--- /dev/null
+++ b/packages/cli/src/labels/task-label-edits.ts
@@ -0,0 +1,46 @@
+import { Effect } from "effect";
+import {
+ attachLabelToTask,
+ detachLabelFromTask,
+ listTaskLabels,
+} from "../api/labels.js";
+import { planTaskLabels, type TaskLabelPlan } from "./plan-task-labels.js";
+import { resolveLabels } from "./resolve-labels.js";
+
+const emptyPlan: TaskLabelPlan = { add: [], remove: [] };
+
+export const prepareTaskLabelEdits = Effect.fn("labels.prepareTaskEdits")(
+ function* (options: {
+ readonly workspaceId: string;
+ readonly taskId: string;
+ readonly taskRef: string;
+ readonly add: ReadonlyArray<string>;
+ readonly remove: ReadonlyArray<string>;
+ }) {
+ if (options.add.length === 0 && options.remove.length === 0) {
+ return emptyPlan;
+ }
+ const [add, taskLabels] = yield* Effect.all(
+ [
+ resolveLabels(options.workspaceId, options.add),
+ listTaskLabels(options.taskId),
+ ],
+ { concurrency: 2 },
+ );
+ return yield* Effect.fromResult(
+ planTaskLabels({
+ taskRef: options.taskRef,
+ taskLabels,
+ add,
+ removeNames: options.remove,
+ }),
+ );
+ },
+);
+
+export const applyTaskLabelEdits = Effect.fn("labels.applyTaskEdits")(
+ function* (taskId: string, plan: TaskLabelPlan) {
+ for (const label of plan.remove) yield* detachLabelFromTask(label.id);
+ for (const label of plan.add) yield* attachLabelToTask(label.id, taskId);
+ },
+);
diff --git a/packages/cli/src/labels/test-labels.ts b/packages/cli/src/labels/test-labels.ts
new file mode 100644
index 000000000..f93d354e6
--- /dev/null
+++ b/packages/cli/src/labels/test-labels.ts
@@ -0,0 +1,21 @@
+import type { Label } from "../api/labels.js";
+
+export function workspaceLabel(
+ id: string,
+ name: string,
+ overrides: Partial<Label> = {},
+): Label {
+ return {
+ id,
+ name,
+ color: "gray",
+ taskId: null,
+ workspaceId: "ws_1",
+ deletionStartedAt: null,
+ ...overrides,
+ };
+}
+
+export function taskLabel(id: string, name: string, taskId: string): Label {
+ return workspaceLabel(id, name, { taskId });
+}
diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts
new file mode 100644
index 000000000..2d5a64efd
--- /dev/null
+++ b/packages/cli/src/main.ts
@@ -0,0 +1,73 @@
+import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { Console, Effect, Layer } from "effect";
+import { CliConfig, CliOutput, Command, GlobalFlag } from "effect/cli";
+import packageJson from "../package.json" with { type: "json" };
+import { makeFormatter } from "./cli/formatter.js";
+import { root } from "./cli/root.js";
+import { ConfigStoreLive } from "./config/config-store.js";
+import { exitOnClosedPipe } from "./output/exit-on-closed-pipe.js";
+import { layerOutput, makeOutput, processSinks } from "./output/output.js";
+import { resolveOutputMode } from "./output/output-mode.js";
+import { classifyFailure, reportOutcome } from "./output/report-failure.js";
+import {
+ CliEnvironment,
+ processEnvironment,
+} from "./services/cli-environment.js";
+import { DesktopLive } from "./services/desktop.js";
+import { DeviceAuthLive } from "./services/device-auth.js";
+
+function capturingConsole(lines: string[]): Console.Console {
+ const push = (...args: ReadonlyArray<unknown>) => {
+ lines.push(args.map(String).join(" "));
+ };
+ return Object.assign(Object.create(globalThis.console), {
+ log: push,
+ info: push,
+ warn: push,
+ error: push,
+ debug: () => {},
+ });
+}
+
+export function main(argv: ReadonlyArray<string>): void {
+ exitOnClosedPipe([process.stdout, process.stderr]);
+ const environment = processEnvironment();
+ const mode = resolveOutputMode(
+ argv,
+ environment.env,
+ environment.stdout.isTTY,
+ );
+ const output = makeOutput(mode, environment, processSinks);
+ const captured: string[] = [];
+ const flush = () => (captured.length > 0 ? `${captured.join("\n")}\n` : "");
+
+ const environmentLayer = Layer.succeed(CliEnvironment, environment);
+ const services = Layer.mergeAll(
+ layerOutput(output),
+ environmentLayer,
+ ConfigStoreLive,
+ DesktopLive,
+ DeviceAuthLive,
+ CliOutput.layer(makeFormatter(output)),
+ CliConfig.layer({
+ builtIns: [GlobalFlag.Help, GlobalFlag.Version, GlobalFlag.Completions],
+ }),
+ NodeServices.layer,
+ ).pipe(Layer.provide(environmentLayer));
+
+ const program = Command.runWith(root, {
+ version: packageJson.version,
+ renderErrors: false,
+ })(argv).pipe(
+ Effect.provideService(Console.Console, capturingConsole(captured)),
+ Effect.matchCauseEffect({
+ onSuccess: () => output.out(flush()),
+ onFailure: (cause) =>
+ reportOutcome(output, classifyFailure(cause, flush())),
+ }),
+ Effect.provide(services),
+ );
+
+ NodeRuntime.runMain(program, { disableErrorReporting: true });
+}
diff --git a/packages/cli/src/notifications/lookup-notification-tasks.ts b/packages/cli/src/notifications/lookup-notification-tasks.ts
new file mode 100644
index 000000000..6312b8267
--- /dev/null
+++ b/packages/cli/src/notifications/lookup-notification-tasks.ts
@@ -0,0 +1,51 @@
+import { Effect } from "effect";
+import { listProjects } from "../api/endpoints.js";
+import { getNotificationTask } from "../api/notifications.js";
+import type { NotificationView } from "./normalize-notification.js";
+import type { TaskLookup } from "./notification-json.js";
+
+const unique = (values: ReadonlyArray<string | null>) => [
+ ...new Set(values.filter((value): value is string => value !== null)),
+];
+
+export const lookupNotificationTasks = Effect.fn("notifications.lookupTasks")(
+ function* (views: ReadonlyArray<NotificationView>) {
+ const related = views.filter((view) => view.taskId !== null);
+ const [tasks, projects] = yield* Effect.all(
+ [
+ Effect.forEach(
+ unique(related.map((view) => view.taskId)),
+ (taskId) =>
+ getNotificationTask(taskId).pipe(
+ Effect.map((task) => [task]),
+ Effect.catchTags({
+ NotFound: () => Effect.succeed([]),
+ PermissionDenied: () => Effect.succeed([]),
+ InvalidRequest: () => Effect.succeed([]),
+ }),
+ ),
+ { concurrency: 6 },
+ ),
+ Effect.forEach(
+ unique(related.map((view) => view.workspaceId)),
+ (workspaceId) =>
+ listProjects(workspaceId).pipe(
+ Effect.catchTags({
+ NotFound: () => Effect.succeed([]),
+ PermissionDenied: () => Effect.succeed([]),
+ InvalidRequest: () => Effect.succeed([]),
+ }),
+ ),
+ { concurrency: 3 },
+ ),
+ ],
+ { concurrency: 2 },
+ );
+ return {
+ tasks: new Map(tasks.flat().map((task) => [task.id, task])),
+ projectSlugs: new Map(
+ projects.flat().map((project) => [project.id, project.slug]),
+ ),
+ } satisfies TaskLookup;
+ },
+);
diff --git a/packages/cli/src/notifications/match-notification.test.ts b/packages/cli/src/notifications/match-notification.test.ts
new file mode 100644
index 000000000..7d9d111b2
--- /dev/null
+++ b/packages/cli/src/notifications/match-notification.test.ts
@@ -0,0 +1,31 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { matchNotificationId } from "./match-notification.js";
+
+const known = [
+ "abcd1234efgh5678ijkl9012",
+ "abcd9999efgh5678ijkl9012",
+ "zyxw1234efgh5678ijkl9012",
+];
+
+const match = (reference: string) => {
+ const result = matchNotificationId(known, reference);
+ return Result.isSuccess(result) ? result.success : result.failure.message;
+};
+
+describe("matchNotificationId", () => {
+ it("accepts full ids and unique prefixes", () => {
+ expect(match("abcd1234efgh5678ijkl9012")).toBe("abcd1234efgh5678ijkl9012");
+ expect(match("zyxw")).toBe("zyxw1234efgh5678ijkl9012");
+ expect(match("abcd1")).toBe("abcd1234efgh5678ijkl9012");
+ });
+
+ it("refuses ambiguous and too-short prefixes", () => {
+ expect(match("abcd")).toBe('"abcd" matches 2 notifications.');
+ expect(match("zyx")).toBe('No recent notification matches "zyx".');
+ });
+
+ it("passes older full ids through to the server", () => {
+ expect(match("qqqq1234efgh5678ijkl9012")).toBe("qqqq1234efgh5678ijkl9012");
+ });
+});
diff --git a/packages/cli/src/notifications/match-notification.ts b/packages/cli/src/notifications/match-notification.ts
new file mode 100644
index 000000000..60568c9e1
--- /dev/null
+++ b/packages/cli/src/notifications/match-notification.ts
@@ -0,0 +1,34 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+
+const MIN_PREFIX = 4;
+const FULL_ID_LENGTH = 20;
+
+export function matchNotificationId(
+ known: ReadonlyArray<string>,
+ reference: string,
+): Result.Result<string, InvalidArgument> {
+ const wanted = reference.trim();
+ if (known.includes(wanted)) return Result.succeed(wanted);
+ const matches =
+ wanted.length >= MIN_PREFIX
+ ? known.filter((id) => id.startsWith(wanted))
+ : [];
+ const [only] = matches;
+ if (matches.length === 1 && only) return Result.succeed(only);
+ if (matches.length > 1) {
+ return Result.fail(
+ new InvalidArgument({
+ message: `"${wanted}" matches ${matches.length} notifications.`,
+ hint: "Type more of the id.",
+ }),
+ );
+ }
+ if (wanted.length >= FULL_ID_LENGTH) return Result.succeed(wanted);
+ return Result.fail(
+ new InvalidArgument({
+ message: `No recent notification matches "${wanted}".`,
+ hint: "Run kaneo notification list to see the ids.",
+ }),
+ );
+}
diff --git a/packages/cli/src/notifications/normalize-notification.test.ts b/packages/cli/src/notifications/normalize-notification.test.ts
new file mode 100644
index 000000000..463fe6d04
--- /dev/null
+++ b/packages/cli/src/notifications/normalize-notification.test.ts
@@ -0,0 +1,140 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { RawNotification } from "../api/notifications.js";
+import { normalizeNotification } from "./normalize-notification.js";
+
+function raw(overrides: Partial<RawNotification> = {}): RawNotification {
+ return {
+ id: "n1",
+ title: null,
+ content: null,
+ type: "task_assignee_changed",
+ eventData: {
+ taskTitle: "Fix login redirect",
+ projectId: "p1",
+ workspaceId: "ws_1",
+ },
+ isRead: false,
+ resourceId: "t1",
+ resourceType: "task",
+ createdAt: "2026-10-08T10:00:00.000Z",
+ ...overrides,
+ };
+}
+
+describe("normalizeNotification", () => {
+ it("writes generated notifications from their type and event data", () => {
+ expect(normalizeNotification(raw())).toEqual({
+ id: "n1",
+ type: "task_assignee_changed",
+ title: "Task assigned to you",
+ message: "Fix login redirect",
+ read: false,
+ createdAt: "2026-10-08T10:00:00.000Z",
+ workspaceId: "ws_1",
+ projectId: "p1",
+ taskId: "t1",
+ taskTitle: "Fix login redirect",
+ });
+ });
+
+ it("describes status changes with readable column names", () => {
+ const view = normalizeNotification(
+ raw({
+ type: "task_status_changed",
+ eventData: {
+ taskTitle: "Ship it",
+ oldStatus: "in-progress",
+ newStatus: "done",
+ },
+ }),
+ );
+ expect(view.title).toBe("Task status changed");
+ expect(view.message).toBe('"Ship it" moved from In progress to Done');
+ });
+
+ it("names the person behind mentions and comments", () => {
+ expect(
+ normalizeNotification(
+ raw({
+ type: "task_comment",
+ eventData: {
+ taskTitle: "Ship it",
+ commenterName: "Grace",
+ commentPreview: "Looks good,\nmerging",
+ },
+ }),
+ ),
+ ).toMatchObject({
+ title: "Grace commented on your task",
+ message: "Ship it: Looks good, merging",
+ });
+ expect(
+ normalizeNotification(
+ raw({ type: "task_mention", eventData: { taskTitle: "Ship it" } }),
+ ).title,
+ ).toBe("Someone mentioned you");
+ });
+
+ it("formats reminder lead times", () => {
+ expect(
+ normalizeNotification(
+ raw({
+ type: "due_date_reminder",
+ eventData: { taskTitle: "Ship it", leadTimeMinutes: 120 },
+ }),
+ ).message,
+ ).toBe("Ship it is due in 2 hours");
+ });
+
+ it("falls back to the stored title and content", () => {
+ expect(
+ normalizeNotification(
+ raw({
+ type: "info",
+ title: "Heads up",
+ content: "Maintenance tonight",
+ eventData: null,
+ isRead: null,
+ resourceId: null,
+ resourceType: null,
+ }),
+ ),
+ ).toEqual({
+ id: "n1",
+ type: "info",
+ title: "Heads up",
+ message: "Maintenance tonight",
+ read: false,
+ createdAt: "2026-10-08T10:00:00.000Z",
+ workspaceId: null,
+ projectId: null,
+ taskId: null,
+ taskTitle: null,
+ });
+ });
+
+ it("names unknown types when there is no title", () => {
+ expect(
+ normalizeNotification(
+ raw({ type: "custom_event", eventData: undefined, resourceType: null }),
+ ).title,
+ ).toBe("Custom event");
+ });
+
+ it("points workspace notifications at their workspace", () => {
+ expect(
+ normalizeNotification(
+ raw({
+ type: "workspace_created",
+ eventData: { workspaceName: "Acme Studio" },
+ resourceId: "ws_9",
+ resourceType: "workspace",
+ }),
+ ),
+ ).toMatchObject({
+ workspaceId: "ws_9",
+ taskId: null,
+ message: 'Your workspace "Acme Studio" has been created',
+ });
+ });
+});
diff --git a/packages/cli/src/notifications/normalize-notification.ts b/packages/cli/src/notifications/normalize-notification.ts
new file mode 100644
index 000000000..92957e5e4
--- /dev/null
+++ b/packages/cli/src/notifications/normalize-notification.ts
@@ -0,0 +1,120 @@
+import type { RawNotification } from "../api/notifications.js";
+
+export type NotificationView = {
+ readonly id: string;
+ readonly type: string;
+ readonly title: string;
+ readonly message: string | null;
+ readonly read: boolean;
+ readonly createdAt: string;
+ readonly workspaceId: string | null;
+ readonly projectId: string | null;
+ readonly taskId: string | null;
+ readonly taskTitle: string | null;
+};
+
+type EventData = Readonly<Record<string, unknown>>;
+
+function record(value: unknown): EventData | null {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? (value as EventData)
+ : null;
+}
+
+function field(data: EventData | null, key: string): string | null {
+ const value = data?.[key];
+ if (typeof value === "string" && value.trim() !== "") return value;
+ if (typeof value === "number") return String(value);
+ return null;
+}
+
+function statusLabel(slug: string | null): string {
+ if (!slug) return "unknown";
+ const words = slug.replace(/[-_]+/gu, " ").trim();
+ return words.charAt(0).toUpperCase() + words.slice(1);
+}
+
+function leadTime(data: EventData): string {
+ const minutes = Number(data.leadTimeMinutes ?? 1440);
+ const plural = (count: number, unit: string) =>
+ `${count} ${unit}${count === 1 ? "" : "s"}`;
+ if (minutes % 1440 === 0) return plural(minutes / 1440, "day");
+ if (minutes % 60 === 0) return plural(minutes / 60, "hour");
+ return plural(minutes, "minute");
+}
+
+function describe(
+ raw: RawNotification,
+ data: EventData,
+): { readonly title: string; readonly message: string | null } | null {
+ const task = field(data, "taskTitle");
+ const named = task ?? "a task";
+ switch (raw.type) {
+ case "task_created":
+ return { title: "New task created", message: named };
+ case "workspace_created":
+ return {
+ title: "Workspace created",
+ message: `Your workspace "${field(data, "workspaceName") ?? ""}" has been created`,
+ };
+ case "task_status_changed":
+ return {
+ title: "Task status changed",
+ message: `"${named}" moved from ${statusLabel(field(data, "oldStatus"))} to ${statusLabel(field(data, "newStatus"))}`,
+ };
+ case "task_assignee_changed":
+ return { title: "Task assigned to you", message: named };
+ case "task_mention": {
+ const who = field(data, "mentionerName") ?? "Someone";
+ return { title: `${who} mentioned you`, message: named };
+ }
+ case "task_comment": {
+ const who = field(data, "commenterName") ?? "Someone";
+ const preview = field(data, "commentPreview");
+ return {
+ title: `${who} commented on your task`,
+ message: preview ? `${named}: ${preview}` : named,
+ };
+ }
+ case "due_date_reminder":
+ return {
+ title: "Task due soon",
+ message: `${named} is due in ${leadTime(data)}`,
+ };
+ case "task_overdue":
+ return {
+ title: "Task overdue",
+ message: `${named} is past its due date`,
+ };
+ case "time_entry_created":
+ return { title: "Time tracking started", message: named };
+ default:
+ return null;
+ }
+}
+
+function singleLine(value: string | null): string | null {
+ if (value === null) return null;
+ const line = value.replace(/\s+/gu, " ").trim();
+ return line === "" ? null : line;
+}
+
+export function normalizeNotification(raw: RawNotification): NotificationView {
+ const data = record(raw.eventData);
+ const described = data ? describe(raw, data) : null;
+ const isTask = raw.resourceType === "task" && raw.resourceId !== null;
+ return {
+ id: raw.id,
+ type: raw.type,
+ title: singleLine(described?.title ?? raw.title) ?? statusLabel(raw.type),
+ message: singleLine(described?.message ?? raw.content),
+ read: raw.isRead === true,
+ createdAt: raw.createdAt,
+ workspaceId:
+ field(data, "workspaceId") ??
+ (raw.resourceType === "workspace" ? raw.resourceId : null),
+ projectId: field(data, "projectId"),
+ taskId: isTask ? raw.resourceId : null,
+ taskTitle: isTask ? field(data, "taskTitle") : null,
+ };
+}
diff --git a/packages/cli/src/notifications/notification-json.test.ts b/packages/cli/src/notifications/notification-json.test.ts
new file mode 100644
index 000000000..cece2c4a0
--- /dev/null
+++ b/packages/cli/src/notifications/notification-json.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { NotificationView } from "./normalize-notification.js";
+import { toNotificationJson } from "./notification-json.js";
+
+const view: NotificationView = {
+ id: "n1",
+ type: "task_assignee_changed",
+ title: "Task assigned to you",
+ message: "Fix login",
+ read: false,
+ createdAt: "2026-10-08T10:00:00.000Z",
+ workspaceId: "ws_1",
+ projectId: "p1",
+ taskId: "t1",
+ taskTitle: "Fix login",
+};
+
+describe("toNotificationJson", () => {
+ it("adds the ticket id and link of the related task", () => {
+ expect(
+ toNotificationJson(
+ view,
+ {
+ tasks: new Map([
+ [
+ "t1",
+ {
+ id: "t1",
+ projectId: "p1",
+ number: 12,
+ title: "Fix login redirect",
+ },
+ ],
+ ]),
+ projectSlugs: new Map([["p1", "kan"]]),
+ },
+ "https://kaneo.test",
+ ).task,
+ ).toEqual({
+ id: "t1",
+ ticketId: "KAN-12",
+ title: "Fix login redirect",
+ url: "https://kaneo.test/dashboard/workspace/ws_1/project/p1/task/t1",
+ });
+ });
+
+ it("keeps the task without a ticket id when it could not be loaded", () => {
+ expect(
+ toNotificationJson(
+ view,
+ { tasks: new Map(), projectSlugs: new Map() },
+ "https://kaneo.test",
+ ).task,
+ ).toEqual({
+ id: "t1",
+ ticketId: null,
+ title: "Fix login",
+ url: "https://kaneo.test/dashboard/workspace/ws_1/project/p1/task/t1",
+ });
+ });
+
+ it("has no task for workspace notifications", () => {
+ expect(
+ toNotificationJson(
+ { ...view, taskId: null, taskTitle: null, projectId: null },
+ { tasks: new Map(), projectSlugs: new Map() },
+ "https://kaneo.test",
+ ).task,
+ ).toBeNull();
+ });
+});
diff --git a/packages/cli/src/notifications/notification-json.ts b/packages/cli/src/notifications/notification-json.ts
new file mode 100644
index 000000000..475cfc4e4
--- /dev/null
+++ b/packages/cli/src/notifications/notification-json.ts
@@ -0,0 +1,61 @@
+import type { NotificationTask } from "../api/notifications.js";
+import { taskUrl } from "../render/links.js";
+import { ticketId } from "../render/task-format.js";
+import type { NotificationView } from "./normalize-notification.js";
+
+export type NotificationJson = {
+ readonly id: string;
+ readonly type: string;
+ readonly title: string;
+ readonly message: string | null;
+ readonly read: boolean;
+ readonly createdAt: string;
+ readonly workspaceId: string | null;
+ readonly task: {
+ readonly id: string;
+ readonly ticketId: string | null;
+ readonly title: string | null;
+ readonly url: string | null;
+ } | null;
+};
+
+export type TaskLookup = {
+ readonly tasks: ReadonlyMap<string, NotificationTask>;
+ readonly projectSlugs: ReadonlyMap<string, string>;
+};
+
+export function toNotificationJson(
+ view: NotificationView,
+ lookup: TaskLookup,
+ webUrl: string,
+): NotificationJson {
+ const base = {
+ id: view.id,
+ type: view.type,
+ title: view.title,
+ message: view.message,
+ read: view.read,
+ createdAt: view.createdAt,
+ workspaceId: view.workspaceId,
+ };
+ if (view.taskId === null) return { ...base, task: null };
+ const found = lookup.tasks.get(view.taskId);
+ const projectId = found?.projectId ?? view.projectId;
+ const slug = projectId ? lookup.projectSlugs.get(projectId) : undefined;
+ return {
+ ...base,
+ task: {
+ id: view.taskId,
+ ticketId: found && slug ? ticketId(slug, found.number) : null,
+ title: found?.title ?? view.taskTitle,
+ url:
+ projectId && view.workspaceId
+ ? taskUrl(webUrl, {
+ workspaceId: view.workspaceId,
+ projectId,
+ id: view.taskId,
+ })
+ : null,
+ },
+ };
+}
diff --git a/packages/cli/src/notifications/relative-time.test.ts b/packages/cli/src/notifications/relative-time.test.ts
new file mode 100644
index 000000000..286961464
--- /dev/null
+++ b/packages/cli/src/notifications/relative-time.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vite-plus/test";
+import { relativeTime } from "./relative-time.js";
+
+const now = new Date(2026, 9, 8, 12, 0, 0);
+const ago = (ms: number) => new Date(now.getTime() - ms).toISOString();
+
+describe("relativeTime", () => {
+ it("counts recent minutes, hours and days", () => {
+ expect(relativeTime(ago(20 * 1000), now)).toBe("just now");
+ expect(relativeTime(ago(5 * 60 * 1000), now)).toBe("5m ago");
+ expect(relativeTime(ago(3 * 60 * 60 * 1000), now)).toBe("3h ago");
+ expect(relativeTime(ago(2 * 24 * 60 * 60 * 1000), now)).toBe("2d ago");
+ });
+
+ it("switches to a date after a week", () => {
+ expect(relativeTime(new Date(2026, 8, 20, 9).toISOString(), now)).toBe(
+ "Sep 20",
+ );
+ expect(relativeTime(new Date(2025, 11, 31, 9).toISOString(), now)).toBe(
+ "Dec 31, 2025",
+ );
+ });
+
+ it("treats clock skew as just now", () => {
+ expect(relativeTime(ago(-30 * 1000), now)).toBe("just now");
+ });
+});
diff --git a/packages/cli/src/notifications/relative-time.ts b/packages/cli/src/notifications/relative-time.ts
new file mode 100644
index 000000000..79ee03cf3
--- /dev/null
+++ b/packages/cli/src/notifications/relative-time.ts
@@ -0,0 +1,18 @@
+const MINUTE = 60 * 1000;
+const HOUR = 60 * MINUTE;
+const DAY = 24 * HOUR;
+
+export function relativeTime(iso: string, now: Date): string {
+ const then = new Date(iso);
+ const elapsed = now.getTime() - then.getTime();
+ if (Number.isNaN(elapsed)) return "";
+ if (elapsed < MINUTE) return "just now";
+ if (elapsed < HOUR) return `${Math.floor(elapsed / MINUTE)}m ago`;
+ if (elapsed < DAY) return `${Math.floor(elapsed / HOUR)}h ago`;
+ if (elapsed < 7 * DAY) return `${Math.floor(elapsed / DAY)}d ago`;
+ return then.toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ ...(then.getFullYear() === now.getFullYear() ? {} : { year: "numeric" }),
+ });
+}
diff --git a/packages/cli/src/notifications/render-notification-list.test.ts b/packages/cli/src/notifications/render-notification-list.test.ts
new file mode 100644
index 000000000..ead17e0b9
--- /dev/null
+++ b/packages/cli/src/notifications/render-notification-list.test.ts
@@ -0,0 +1,129 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import type { NotificationJson } from "./notification-json.js";
+import { renderNotificationList } from "./render-notification-list.js";
+
+const ui = (columns: number) =>
+ makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns,
+ });
+
+const now = new Date(2026, 9, 8, 12, 0);
+
+const item = (
+ id: string,
+ minutesAgo: number,
+ read: boolean,
+ ticketId: string | null,
+ title: string,
+ message: string | null,
+): NotificationJson => ({
+ id,
+ type: "task_assignee_changed",
+ title,
+ message,
+ read,
+ createdAt: new Date(now.getTime() - minutesAgo * 60 * 1000).toISOString(),
+ workspaceId: "ws_1",
+ task: ticketId
+ ? { id: "t1", ticketId, title: message, url: "https://kaneo.test/t1" }
+ : null,
+});
+
+const notifications = [
+ item(
+ "abcd1234efgh5678ijkl9012",
+ 5,
+ false,
+ "KAN-12",
+ "Task assigned to you",
+ "Fix login redirect after device sign in",
+ ),
+ item(
+ "zyxw1234efgh5678ijkl9012",
+ 26 * 60,
+ true,
+ "KAN-3",
+ "Task status changed",
+ '"Add shortcuts" moved from To do to In progress',
+ ),
+ item(
+ "qrst1234efgh5678ijkl9012",
+ 3 * 24 * 60,
+ true,
+ null,
+ "Workspace created",
+ null,
+ ),
+];
+
+describe("renderNotificationList", () => {
+ it("marks unread rows and fits 80 columns", () => {
+ expect(
+ renderNotificationList(ui(80), {
+ notifications,
+ unreadOnly: false,
+ unreadCount: 1,
+ hidden: 0,
+ capped: false,
+ now,
+ }),
+ ).toEqual([
+ "",
+ " ● 5m ago KAN-12 Task assigned to you · Fix login redirect after… abcd1234",
+ ' 1d ago KAN-3 Task status changed · "Add shortcuts" moved from… zyxw1234',
+ " 3d ago Workspace created qrst1234",
+ "",
+ " 1 unread",
+ " Mark them read with kaneo notification read <id> or --all",
+ "",
+ ]);
+ });
+
+ it("says when the list is capped or trimmed", () => {
+ const lines = renderNotificationList(ui(80), {
+ notifications: notifications.slice(1),
+ unreadOnly: false,
+ unreadCount: 0,
+ hidden: 4,
+ capped: true,
+ now,
+ });
+ expect(lines.slice(-3)).toEqual([
+ " 0 unread · showing the latest 50",
+ " 4 more. Pass --limit to see them.",
+ "",
+ ]);
+ });
+
+ it("stays inside narrow terminals", () => {
+ for (const line of renderNotificationList(ui(50), {
+ notifications,
+ unreadOnly: false,
+ unreadCount: 1,
+ hidden: 0,
+ capped: false,
+ now,
+ }).slice(0, 4)) {
+ expect(stringWidth(line)).toBeLessThanOrEqual(50);
+ }
+ });
+
+ it("explains an empty unread list", () => {
+ expect(
+ renderNotificationList(ui(80), {
+ notifications: [],
+ unreadOnly: true,
+ unreadCount: 0,
+ hidden: 0,
+ capped: true,
+ now,
+ }),
+ ).toEqual(["", " ● No unread notifications in the latest 50.", ""]);
+ });
+});
diff --git a/packages/cli/src/notifications/render-notification-list.ts b/packages/cli/src/notifications/render-notification-list.ts
new file mode 100644
index 000000000..c2a31e9ee
--- /dev/null
+++ b/packages/cli/src/notifications/render-notification-list.ts
@@ -0,0 +1,102 @@
+import { NOTIFICATION_PAGE_CAP } from "../api/notifications.js";
+import { type Cell, text } from "../render/cell.js";
+import { renderTable } from "../render/table.js";
+import type { Ui } from "../render/ui.js";
+import type { NotificationJson } from "./notification-json.js";
+import { relativeTime } from "./relative-time.js";
+
+export const SHORT_ID_LENGTH = 8;
+
+export type NotificationListView = {
+ readonly notifications: ReadonlyArray<NotificationJson>;
+ readonly unreadOnly: boolean;
+ readonly unreadCount: number;
+ readonly hidden: number;
+ readonly capped: boolean;
+ readonly now: Date;
+};
+
+export function renderNotificationList(
+ ui: Ui,
+ view: NotificationListView,
+): string[] {
+ const { theme, glyphs } = ui;
+ const latest = `the latest ${NOTIFICATION_PAGE_CAP}`;
+ if (view.notifications.length === 0) {
+ const empty = view.unreadOnly
+ ? "No unread notifications"
+ : "No notifications";
+ return [
+ "",
+ ` ${theme.muted(glyphs.dot)} ${empty}${view.capped ? ` in ${latest}` : ""}.`,
+ "",
+ ];
+ }
+ const rows = renderTable(
+ ui,
+ view.notifications,
+ [
+ {
+ header: "",
+ cell: (item): Cell => [
+ item.read ? text(" ") : text(glyphs.dot, theme.info),
+ ],
+ },
+ {
+ header: "When",
+ cell: (item): Cell => [
+ text(relativeTime(item.createdAt, view.now), theme.muted),
+ ],
+ },
+ {
+ header: "Task",
+ optional: true,
+ cell: (item): Cell =>
+ item.task?.ticketId
+ ? [
+ text(
+ item.task.ticketId,
+ theme.muted,
+ item.task.url ?? undefined,
+ ),
+ ]
+ : [],
+ },
+ {
+ header: "Notification",
+ flex: true,
+ minWidth: 16,
+ cell: (item): Cell => [
+ text(item.title, item.read ? undefined : theme.strong),
+ ...(item.message
+ ? [text(` ${glyphs.separator} ${item.message}`, theme.muted)]
+ : []),
+ ],
+ },
+ {
+ header: "ID",
+ cell: (item): Cell => [
+ text(item.id.slice(0, SHORT_ID_LENGTH), theme.muted),
+ ],
+ },
+ ],
+ { width: ui.caps.columns, indent: 2 },
+ );
+ const summary = [
+ `${view.unreadCount} unread`,
+ ...(view.capped ? [`showing ${latest}`] : []),
+ ].join(` ${glyphs.separator} `);
+ const lines = ["", ...rows, "", ` ${theme.muted(summary)}`];
+ if (view.hidden > 0) {
+ lines.push(
+ ` ${theme.muted(`${view.hidden} more. Pass --limit to see them.`)}`,
+ );
+ }
+ if (view.unreadCount > 0) {
+ lines.push(
+ ` ${theme.muted("Mark them read with")} ${theme.strong("kaneo notification read <id>")} ${theme.muted("or")} ${theme.strong("--all")}`,
+ );
+ }
+ lines.push("");
+ return lines;
+}
diff --git a/packages/cli/src/notifications/render-notifications-read.test.ts b/packages/cli/src/notifications/render-notifications-read.test.ts
new file mode 100644
index 000000000..a6b7c0f6f
--- /dev/null
+++ b/packages/cli/src/notifications/render-notifications-read.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { renderNotificationsRead } from "./render-notifications-read.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+describe("renderNotificationsRead", () => {
+ it("counts the notifications it marked", () => {
+ expect(renderNotificationsRead(ui, { all: false, count: 1 })).toEqual([
+ "",
+ " ✓ Marked 1 notification read",
+ "",
+ ]);
+ expect(renderNotificationsRead(ui, { all: false, count: 3 })[1]).toBe(
+ " ✓ Marked 3 notifications read",
+ );
+ });
+
+ it("covers marking everything", () => {
+ expect(renderNotificationsRead(ui, { all: true, count: 0 })[1]).toBe(
+ " ✓ Marked all notifications read",
+ );
+ });
+});
diff --git a/packages/cli/src/notifications/render-notifications-read.ts b/packages/cli/src/notifications/render-notifications-read.ts
new file mode 100644
index 000000000..ed8bd8844
--- /dev/null
+++ b/packages/cli/src/notifications/render-notifications-read.ts
@@ -0,0 +1,12 @@
+import type { Ui } from "../render/ui.js";
+
+export function renderNotificationsRead(
+ ui: Ui,
+ result: { readonly all: boolean; readonly count: number },
+): string[] {
+ const { theme, glyphs } = ui;
+ const what = result.all
+ ? "all notifications"
+ : `${result.count} ${result.count === 1 ? "notification" : "notifications"}`;
+ return ["", ` ${theme.success(glyphs.tick)} Marked ${what} read`, ""];
+}
diff --git a/packages/cli/src/output/emit.ts b/packages/cli/src/output/emit.ts
new file mode 100644
index 000000000..36de76bf2
--- /dev/null
+++ b/packages/cli/src/output/emit.ts
@@ -0,0 +1,29 @@
+import { Effect, Option } from "effect";
+import { JqFlag } from "../cli/global-flags.js";
+import { applyJq } from "../jq/apply-jq.js";
+import type { Ui } from "../render/ui.js";
+import { Output } from "./output.js";
+
+export const emit = Effect.fnUntraced(function* <A>(
+ value: A,
+ render: (ui: Ui, value: A) => ReadonlyArray<string>,
+) {
+ const output = yield* Output;
+ const jq = Option.flatten(yield* Effect.serviceOption(JqFlag));
+ if (Option.isSome(jq)) {
+ yield* output.out(yield* applyJq(jq.value, value));
+ return;
+ }
+ if (output.mode === "json") {
+ yield* output.out(`${JSON.stringify(value)}\n`);
+ return;
+ }
+ yield* output.out(`${render(output.ui, value).join("\n")}\n`);
+});
+
+export const note = Effect.fnUntraced(function* (
+ render: (ui: Ui) => ReadonlyArray<string>,
+) {
+ const output = yield* Output;
+ yield* output.err(`${render(output.errUi).join("\n")}\n`);
+});
diff --git a/packages/cli/src/output/exit-on-closed-pipe.test.ts b/packages/cli/src/output/exit-on-closed-pipe.test.ts
new file mode 100644
index 000000000..21b2999c5
--- /dev/null
+++ b/packages/cli/src/output/exit-on-closed-pipe.test.ts
@@ -0,0 +1,27 @@
+import { EventEmitter } from "node:events";
+import { describe, expect, it } from "vite-plus/test";
+import { exitOnClosedPipe } from "./exit-on-closed-pipe.js";
+
+function failingStream(code: string) {
+ const stream = new EventEmitter();
+ return {
+ stream,
+ fail: () => stream.emit("error", Object.assign(new Error(code), { code })),
+ };
+}
+
+describe("exitOnClosedPipe", () => {
+ it("exits quietly when the reader closes the pipe", () => {
+ const exits: number[] = [];
+ const { stream, fail } = failingStream("EPIPE");
+ exitOnClosedPipe([stream], (code) => exits.push(code));
+ fail();
+ expect(exits).toEqual([0]);
+ });
+
+ it("rethrows other stream errors", () => {
+ const { stream, fail } = failingStream("EIO");
+ exitOnClosedPipe([stream], () => {});
+ expect(fail).toThrow("EIO");
+ });
+});
diff --git a/packages/cli/src/output/exit-on-closed-pipe.ts b/packages/cli/src/output/exit-on-closed-pipe.ts
new file mode 100644
index 000000000..57c31a279
--- /dev/null
+++ b/packages/cli/src/output/exit-on-closed-pipe.ts
@@ -0,0 +1,15 @@
+type Writable = {
+ on(event: "error", listener: (error: NodeJS.ErrnoException) => void): unknown;
+};
+
+export function exitOnClosedPipe(
+ streams: ReadonlyArray<Writable>,
+ exit: (code: number) => void = (code) => process.exit(code),
+): void {
+ for (const stream of streams) {
+ stream.on("error", (error) => {
+ if (error.code === "EPIPE") exit(0);
+ else throw error;
+ });
+ }
+}
diff --git a/packages/cli/src/output/output-mode.test.ts b/packages/cli/src/output/output-mode.test.ts
new file mode 100644
index 000000000..b0973e2ff
--- /dev/null
+++ b/packages/cli/src/output/output-mode.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from "vite-plus/test";
+import { resolveOutputMode } from "./output-mode.js";
+
+describe("resolveOutputMode", () => {
+ it("defaults to human on a terminal and JSON otherwise", () => {
+ expect(resolveOutputMode([], {}, true)).toBe("human");
+ expect(resolveOutputMode([], {}, false)).toBe("json");
+ });
+
+ it("lets flags override the environment and the terminal", () => {
+ expect(resolveOutputMode(["--human"], {}, false)).toBe("human");
+ expect(resolveOutputMode(["--json"], {}, true)).toBe("json");
+ expect(resolveOutputMode(["--human"], { KANEO_JSON: "true" }, true)).toBe(
+ "human",
+ );
+ expect(resolveOutputMode([], { KANEO_JSON: "true" }, true)).toBe("json");
+ });
+
+ it("treats --jq as JSON mode", () => {
+ expect(resolveOutputMode(["task", "list", "--jq", ".[0]"], {}, true)).toBe(
+ "json",
+ );
+ expect(resolveOutputMode(["--jq=.id"], {}, true)).toBe("json");
+ });
+
+ it("ignores flags after --", () => {
+ expect(resolveOutputMode(["task", "--", "--json"], {}, true)).toBe("human");
+ });
+});
diff --git a/packages/cli/src/output/output-mode.ts b/packages/cli/src/output/output-mode.ts
new file mode 100644
index 000000000..10581b3a7
--- /dev/null
+++ b/packages/cli/src/output/output-mode.ts
@@ -0,0 +1,18 @@
+import type { Environment } from "../render/capabilities.js";
+
+export type OutputMode = "json" | "human";
+
+export function resolveOutputMode(
+ argv: ReadonlyArray<string>,
+ env: Environment,
+ stdoutIsTTY: boolean,
+): OutputMode {
+ const end = argv.indexOf("--");
+ const flags = end === -1 ? argv : argv.slice(0, end);
+ if (flags.includes("--json")) return "json";
+ if (flags.some((flag) => flag === "--jq" || flag.startsWith("--jq=")))
+ return "json";
+ if (flags.includes("--human")) return "human";
+ if (env.KANEO_JSON === "true" || env.KANEO_JSON === "1") return "json";
+ return stdoutIsTTY ? "human" : "json";
+}
diff --git a/packages/cli/src/output/output.ts b/packages/cli/src/output/output.ts
new file mode 100644
index 000000000..1393c3fed
--- /dev/null
+++ b/packages/cli/src/output/output.ts
@@ -0,0 +1,59 @@
+import { Context, Effect, Layer } from "effect";
+import {
+ type Capabilities,
+ detectCapabilities,
+ plainCapabilities,
+} from "../render/capabilities.js";
+import { makeUi, type Ui } from "../render/ui.js";
+import type { CliEnvironmentShape } from "../services/cli-environment.js";
+import type { OutputMode } from "./output-mode.js";
+
+export type OutputShape = {
+ readonly mode: OutputMode;
+ readonly ui: Ui;
+ readonly errUi: Ui;
+ readonly interactive: boolean;
+ readonly out: (text: string) => Effect.Effect<void>;
+ readonly err: (text: string) => Effect.Effect<void>;
+};
+
+export class Output extends Context.Service<Output, OutputShape>()(
+ "kaneo/Output",
+) {}
+
+export type OutputSinks = {
+ readonly out: (text: string) => void;
+ readonly err: (text: string) => void;
+};
+
+export const processSinks: OutputSinks = {
+ out: (text) => {
+ process.stdout.write(text);
+ },
+ err: (text) => {
+ process.stderr.write(text);
+ },
+};
+
+export function makeOutput(
+ mode: OutputMode,
+ environment: CliEnvironmentShape,
+ sinks: OutputSinks,
+): OutputShape {
+ const capabilities = (stream: CliEnvironmentShape["stdout"]): Capabilities =>
+ mode === "json"
+ ? { ...plainCapabilities, columns: stream.columns ?? 80 }
+ : detectCapabilities(environment.env, stream, environment.platform);
+ return {
+ mode,
+ ui: makeUi(capabilities(environment.stdout)),
+ errUi: makeUi(capabilities(environment.stderr)),
+ interactive:
+ mode === "human" && environment.stdin.isTTY && environment.stdout.isTTY,
+ out: (text) => Effect.sync(() => sinks.out(text)),
+ err: (text) => Effect.sync(() => sinks.err(text)),
+ };
+}
+
+export const layerOutput = (output: OutputShape) =>
+ Layer.succeed(Output, output);
diff --git a/packages/cli/src/output/report-failure.test.ts b/packages/cli/src/output/report-failure.test.ts
new file mode 100644
index 000000000..e8f20da8e
--- /dev/null
+++ b/packages/cli/src/output/report-failure.test.ts
@@ -0,0 +1,96 @@
+import { Cause, Effect } from "effect";
+import { CliError } from "effect/cli";
+import { describe, expect, it } from "vite-plus/test";
+import { NotSignedIn } from "../errors/errors.js";
+import { makeUi } from "../render/ui.js";
+import { captureOutput } from "../testing/test-layers.js";
+import { Output } from "./output.js";
+import {
+ classifyFailure,
+ renderFailure,
+ reportOutcome,
+} from "./report-failure.js";
+
+describe("classifyFailure", () => {
+ it("shows requested help as normal output", () => {
+ const cause = Cause.fail(
+ new CliError.ShowHelp({ commandPath: ["kaneo"], errors: [] }),
+ );
+ expect(classifyFailure(cause, "USAGE")).toEqual({
+ kind: "help",
+ text: "USAGE",
+ });
+ });
+
+ it("turns parse errors into a failure with a help hint", () => {
+ const cause = Cause.fail(
+ new CliError.ShowHelp({
+ commandPath: ["kaneo", "task", "list"],
+ errors: [
+ new CliError.UnrecognizedOption({
+ option: "--bogus",
+ command: ["kaneo", "task", "list"],
+ suggestions: [],
+ }),
+ ],
+ }),
+ );
+ const outcome = classifyFailure(cause, "USAGE");
+ expect(outcome.kind).toBe("failure");
+ expect(outcome.kind === "failure" && outcome.failure.hint).toBe(
+ "Run kaneo task list --help to see the options.",
+ );
+ });
+
+ it("describes app errors and unexpected defects", () => {
+ const signedOut = classifyFailure(
+ Cause.fail(new NotSignedIn({ apiUrl: "https://x.test" })),
+ "",
+ );
+ expect(signedOut.kind === "failure" && signedOut.failure.message).toBe(
+ "You are not signed in to x.test.",
+ );
+ const defect = classifyFailure(Cause.die(new Error("boom")), "");
+ expect(defect.kind === "failure" && defect.failure.message).toBe(
+ "Unexpected error: boom",
+ );
+ });
+
+ it("recognizes Ctrl+C", () => {
+ expect(classifyFailure(Cause.interrupt(), "").kind).toBe("interrupted");
+ });
+});
+
+describe("reportOutcome", () => {
+ it("prints exactly the JSON error contract on stdout", async () => {
+ const output = captureOutput("json");
+ await Effect.runPromise(
+ Effect.gen(function* () {
+ const shape = yield* Output;
+ yield* reportOutcome(shape, {
+ kind: "failure",
+ failure: { message: "Nope", hint: "Try x" },
+ });
+ }).pipe(Effect.provide(output.layer)),
+ );
+ expect(output.stdout.join("")).toBe('{"error":"Nope"}\n');
+ expect(output.stderr).toEqual([]);
+ expect(process.exitCode).toBe(1);
+ process.exitCode = 0;
+ });
+});
+
+describe("renderFailure", () => {
+ it("styles the message and hint", () => {
+ const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+ });
+ expect(
+ renderFailure(ui, { message: "Nope", hint: "Run kaneo login" }),
+ ).toEqual(["✗ Nope", " → Run kaneo login"]);
+ });
+});
diff --git a/packages/cli/src/output/report-failure.ts b/packages/cli/src/output/report-failure.ts
new file mode 100644
index 000000000..5c099dbfb
--- /dev/null
+++ b/packages/cli/src/output/report-failure.ts
@@ -0,0 +1,78 @@
+import { Cause, Effect } from "effect";
+import { CliError } from "effect/cli";
+import { describeError, type Failure } from "../errors/describe.js";
+import { isAppError } from "../errors/is-app-error.js";
+import type { Ui } from "../render/ui.js";
+import type { OutputShape } from "./output.js";
+
+export type Outcome =
+ | { readonly kind: "help"; readonly text: string }
+ | { readonly kind: "interrupted" }
+ | { readonly kind: "failure"; readonly failure: Failure };
+
+export function classifyFailure(
+ cause: Cause.Cause<unknown>,
+ captured: string,
+): Outcome {
+ if (Cause.hasInterruptsOnly(cause)) return { kind: "interrupted" };
+ const error = Cause.squash(cause);
+ if (CliError.isCliError(error)) {
+ if (error._tag === "ShowHelp") {
+ const [first] = error.errors;
+ if (!first) return { kind: "help", text: captured };
+ return {
+ kind: "failure",
+ failure: {
+ message: first.message,
+ hint: `Run ${error.commandPath.join(" ")} --help to see the options.`,
+ },
+ };
+ }
+ return { kind: "failure", failure: { message: error.message, hint: null } };
+ }
+ if (isAppError(error))
+ return { kind: "failure", failure: describeError(error) };
+ const message = error instanceof Error ? error.message : String(error);
+ return {
+ kind: "failure",
+ failure: {
+ message: `Unexpected error: ${message}`,
+ hint: "Please report this at https://github.com/usekaneo/kaneo/issues",
+ },
+ };
+}
+
+export function renderFailure(ui: Ui, failure: Failure): string[] {
+ const { theme, glyphs } = ui;
+ const lines = [`${theme.danger(glyphs.cross)} ${failure.message}`];
+ if (failure.hint)
+ lines.push(` ${theme.muted(`${glyphs.arrow} ${failure.hint}`)}`);
+ return lines;
+}
+
+export const reportOutcome = (output: OutputShape, outcome: Outcome) =>
+ Effect.gen(function* () {
+ if (outcome.kind === "help") {
+ yield* output.out(outcome.text);
+ return;
+ }
+ if (outcome.kind === "interrupted") {
+ if (output.mode === "human") yield* output.err("\n");
+ yield* Effect.sync(() => {
+ process.exitCode = 130;
+ });
+ return;
+ }
+ if (output.mode === "json") {
+ yield* output.out(
+ `${JSON.stringify({ error: outcome.failure.message })}\n`,
+ );
+ } else {
+ yield* output.err(
+ `${renderFailure(output.errUi, outcome.failure).join("\n")}\n`,
+ );
+ }
+ yield* Effect.sync(() => {
+ process.exitCode = 1;
+ });
+ });
diff --git a/packages/cli/src/output/spinner.ts b/packages/cli/src/output/spinner.ts
new file mode 100644
index 000000000..6f675e8da
--- /dev/null
+++ b/packages/cli/src/output/spinner.ts
@@ -0,0 +1,39 @@
+import { Effect, Fiber } from "effect";
+import { Output } from "./output.js";
+
+const SHOW_AFTER = "150 millis";
+const FRAME = "80 millis";
+
+export const withSpinner =
+ (label: string) =>
+ <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R | Output> =>
+ Effect.gen(function* () {
+ const output = yield* Output;
+ const { caps, glyphs, theme } = output.errUi;
+ if (output.mode === "json" || !caps.animate) return yield* self;
+
+ let started = false;
+ const animation = Effect.gen(function* () {
+ yield* Effect.sleep(SHOW_AFTER);
+ started = true;
+ yield* output.err("\u001b[?25l");
+ for (let frame = 0; ; frame++) {
+ const glyph = glyphs.spinner[frame % glyphs.spinner.length] ?? "";
+ yield* output.err(`\r${theme.muted(glyph)} ${label}\u001b[K`);
+ yield* Effect.sleep(FRAME);
+ }
+ });
+
+ return yield* Effect.acquireUseRelease(
+ Effect.forkDetach(animation),
+ () => self,
+ (fiber) =>
+ Fiber.interrupt(fiber).pipe(
+ Effect.andThen(
+ Effect.suspend(() =>
+ started ? output.err("\r\u001b[K\u001b[?25h") : Effect.void,
+ ),
+ ),
+ ),
+ );
+ });
diff --git a/packages/cli/src/passthrough/normalize-api-path.test.ts b/packages/cli/src/passthrough/normalize-api-path.test.ts
new file mode 100644
index 000000000..4911d0437
--- /dev/null
+++ b/packages/cli/src/passthrough/normalize-api-path.test.ts
@@ -0,0 +1,36 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { normalizeApiPath } from "./normalize-api-path.js";
+
+function target(input: string) {
+ const parsed = normalizeApiPath(input);
+ return Result.isSuccess(parsed) ? parsed.success : parsed.failure.message;
+}
+
+describe("normalizeApiPath", () => {
+ it("accepts paths with or without the /api prefix", () => {
+ expect(target("/task/assigned")).toEqual({
+ path: "/api/task/assigned",
+ query: {},
+ });
+ expect(target("/api/task/assigned")).toEqual({
+ path: "/api/task/assigned",
+ query: {},
+ });
+ expect(target("user/me")).toEqual({ path: "/api/user/me", query: {} });
+ expect(target("/apiary")).toEqual({ path: "/api/apiary", query: {} });
+ });
+
+ it("moves an inline query string into query parameters", () => {
+ expect(target("/project?workspaceId=ws_1&x=a%20b")).toEqual({
+ path: "/api/project",
+ query: { workspaceId: "ws_1", x: "a b" },
+ });
+ });
+
+ it("rejects full URLs", () => {
+ expect(target("https://cloud.kaneo.app/api/user/me")).toBe(
+ "https://cloud.kaneo.app/api/user/me is a full URL.",
+ );
+ });
+});
diff --git a/packages/cli/src/passthrough/normalize-api-path.ts b/packages/cli/src/passthrough/normalize-api-path.ts
new file mode 100644
index 000000000..5af21a7eb
--- /dev/null
+++ b/packages/cli/src/passthrough/normalize-api-path.ts
@@ -0,0 +1,35 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+
+export type ApiTarget = {
+ readonly path: string;
+ readonly query: Readonly<Record<string, string>>;
+};
+
+export function normalizeApiPath(
+ input: string,
+): Result.Result<ApiTarget, InvalidArgument> {
+ const trimmed = input.trim();
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) {
+ return Result.fail(
+ new InvalidArgument({
+ message: `${trimmed} is a full URL.`,
+ hint: "Pass the path under /api, for example /task/assigned. Use --api-url to pick the server.",
+ }),
+ );
+ }
+ const [pathPart = "", ...rest] = trimmed.split("?");
+ const withSlash = pathPart.startsWith("/") ? pathPart : `/${pathPart}`;
+ const relative =
+ withSlash === "/api" || withSlash.startsWith("/api/")
+ ? withSlash.slice(4)
+ : withSlash;
+ const query: Record<string, string> = {};
+ for (const [key, value] of new URLSearchParams(rest.join("?"))) {
+ query[key] = value;
+ }
+ return Result.succeed({
+ path: `/api${relative === "" ? "/" : relative}`,
+ query,
+ });
+}
diff --git a/packages/cli/src/passthrough/parse-fields.test.ts b/packages/cli/src/passthrough/parse-fields.test.ts
new file mode 100644
index 000000000..95edf28ef
--- /dev/null
+++ b/packages/cli/src/passthrough/parse-fields.test.ts
@@ -0,0 +1,66 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { parseFields, parseQuery } from "./parse-fields.js";
+
+function body(fields: ReadonlyArray<string>) {
+ const parsed = parseFields(fields);
+ return Result.isSuccess(parsed) ? parsed.success : parsed.failure.message;
+}
+
+describe("parseFields", () => {
+ it("parses JSON values and keeps everything else as strings", () => {
+ expect(
+ body([
+ "title=Fix login",
+ "count=3",
+ "done=true",
+ "due=null",
+ 'labels=["bug"]',
+ 'quoted="3"',
+ "empty=",
+ "url=https://a.test/?x=1",
+ ]),
+ ).toEqual({
+ title: "Fix login",
+ count: 3,
+ done: true,
+ due: null,
+ labels: ["bug"],
+ quoted: "3",
+ empty: "",
+ url: "https://a.test/?x=1",
+ });
+ });
+
+ it("nests dotted keys", () => {
+ expect(body(["a.b=1", "a.c.d=x", "e=2"])).toEqual({
+ a: { b: 1, c: { d: "x" } },
+ e: 2,
+ });
+ });
+
+ it("rejects pairs without a key and conflicting nesting", () => {
+ expect(body(["title"])).toBe("-f title is not a key=value pair.");
+ expect(body(["=x"])).toBe("-f =x is not a key=value pair.");
+ expect(body(["a=1", "a.b=2"])).toBe(
+ "-f a.b=2 conflicts with an earlier value for a.",
+ );
+ expect(body(["a..b=1"])).toBe("-f a..b=1 has an empty key segment.");
+ });
+
+ it("keeps special keys as plain properties", () => {
+ const parsed = body(["__proto__.polluted=1"]) as Record<string, unknown>;
+ expect(JSON.stringify(parsed)).toBe('{"__proto__":{"polluted":1}}');
+ expect(({} as Record<string, unknown>).polluted).toBeUndefined();
+ });
+});
+
+describe("parseQuery", () => {
+ it("keeps values as strings", () => {
+ const parsed = parseQuery(["limit=10", "q=a=b"]);
+ expect(Result.isSuccess(parsed) && parsed.success).toEqual({
+ limit: "10",
+ q: "a=b",
+ });
+ });
+});
diff --git a/packages/cli/src/passthrough/parse-fields.ts b/packages/cli/src/passthrough/parse-fields.ts
new file mode 100644
index 000000000..c34de664e
--- /dev/null
+++ b/packages/cli/src/passthrough/parse-fields.ts
@@ -0,0 +1,99 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+
+type JsonObject = Record<string, unknown>;
+
+function splitAssignment(
+ raw: string,
+ flag: string,
+): Result.Result<readonly [string, string], InvalidArgument> {
+ const index = raw.indexOf("=");
+ const key = index === -1 ? "" : raw.slice(0, index).trim();
+ if (key === "") {
+ return Result.fail(
+ new InvalidArgument({
+ message: `${flag} ${raw} is not a key=value pair.`,
+ hint: `Pass it as key=value, for example ${flag} title=Hello.`,
+ }),
+ );
+ }
+ return Result.succeed([key, raw.slice(index + 1)] as const);
+}
+
+export function parseFieldValue(raw: string): unknown {
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return raw;
+ }
+}
+
+function isObject(value: unknown): value is JsonObject {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function setOwn(target: JsonObject, key: string, value: unknown): void {
+ Object.defineProperty(target, key, {
+ value,
+ enumerable: true,
+ writable: true,
+ configurable: true,
+ });
+}
+
+export function parseFields(
+ fields: ReadonlyArray<string>,
+): Result.Result<JsonObject, InvalidArgument> {
+ const body: JsonObject = {};
+ for (const raw of fields) {
+ const pair = splitAssignment(raw, "-f");
+ if (Result.isFailure(pair)) return Result.fail(pair.failure);
+ const [key, value] = pair.success;
+ const segments = key.split(".");
+ if (segments.some((segment) => segment === "")) {
+ return Result.fail(
+ new InvalidArgument({
+ message: `-f ${raw} has an empty key segment.`,
+ hint: "Nest keys with dots, for example -f settings.color=blue.",
+ }),
+ );
+ }
+ let target = body;
+ for (const segment of segments.slice(0, -1)) {
+ const existing = Object.hasOwn(target, segment)
+ ? target[segment]
+ : undefined;
+ if (existing === undefined) {
+ const next: JsonObject = {};
+ setOwn(target, segment, next);
+ target = next;
+ } else if (isObject(existing)) {
+ target = existing;
+ } else {
+ return Result.fail(
+ new InvalidArgument({
+ message: `-f ${raw} conflicts with an earlier value for ${segment}.`,
+ }),
+ );
+ }
+ }
+ setOwn(
+ target,
+ segments[segments.length - 1] ?? key,
+ parseFieldValue(value),
+ );
+ }
+ return Result.succeed(body);
+}
+
+export function parseQuery(
+ pairs: ReadonlyArray<string>,
+): Result.Result<Record<string, string>, InvalidArgument> {
+ const query: Record<string, string> = {};
+ for (const raw of pairs) {
+ const pair = splitAssignment(raw, "--query");
+ if (Result.isFailure(pair)) return Result.fail(pair.failure);
+ setOwn(query, pair.success[0], pair.success[1]);
+ }
+ return Result.succeed(query);
+}
diff --git a/packages/cli/src/passthrough/render-json.ts b/packages/cli/src/passthrough/render-json.ts
new file mode 100644
index 000000000..74f83b3f0
--- /dev/null
+++ b/packages/cli/src/passthrough/render-json.ts
@@ -0,0 +1,5 @@
+import type { Ui } from "../render/ui.js";
+
+export function renderJson(_ui: Ui, value: unknown): string[] {
+ return (JSON.stringify(value, null, 2) ?? "null").split("\n");
+}
diff --git a/packages/cli/src/projects-write/confirm-by-key.ts b/packages/cli/src/projects-write/confirm-by-key.ts
new file mode 100644
index 000000000..37f3fa943
--- /dev/null
+++ b/packages/cli/src/projects-write/confirm-by-key.ts
@@ -0,0 +1,44 @@
+import { Effect } from "effect";
+import { Prompt } from "effect/cli";
+import { Cancelled, InvalidArgument } from "../errors/errors.js";
+import { note } from "../output/emit.js";
+import { Output } from "../output/output.js";
+import { promptTheme } from "../prompts/prompt-theme.js";
+
+function same(a: string, b: string): boolean {
+ return (
+ a.normalize("NFKC").trim().toLowerCase() ===
+ b.normalize("NFKC").trim().toLowerCase()
+ );
+}
+
+export const confirmByKey = Effect.fnUntraced(function* (options: {
+ readonly yes: boolean;
+ readonly action: string;
+ readonly key: string;
+ readonly warning: string;
+}) {
+ if (options.yes) return;
+ const output = yield* Output;
+ if (!output.interactive) {
+ return yield* new InvalidArgument({
+ message: `${options.action} needs confirmation.`,
+ hint: "Pass --yes to skip the prompt.",
+ });
+ }
+ yield* note((ui) => [
+ "",
+ ` ${ui.theme.warning(ui.glyphs.warning)} ${options.warning}`,
+ "",
+ ]);
+ yield* Prompt.run(
+ Prompt.String({
+ message: `Type ${options.key} to confirm`,
+ validate: (value) =>
+ same(value, options.key)
+ ? Effect.succeed(value)
+ : Effect.fail(`Type ${options.key}, or press Ctrl+C to cancel`),
+ theme: promptTheme(output.ui),
+ }),
+ ).pipe(Effect.catchTag("QuitError", () => Effect.fail(new Cancelled())));
+});
diff --git a/packages/cli/src/projects-write/key-conflict.test.ts b/packages/cli/src/projects-write/key-conflict.test.ts
new file mode 100644
index 000000000..5a47c0133
--- /dev/null
+++ b/packages/cli/src/projects-write/key-conflict.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from "vite-plus/test";
+import { keyConflictHint } from "./key-conflict.js";
+
+describe("keyConflictHint", () => {
+ it("suggests a free key for create and edit", () => {
+ expect(keyConflictHint("KANE", undefined)).toBe(
+ "Pick another key, for example --key KANE.",
+ );
+ expect(keyConflictHint(undefined, undefined)).toBe(
+ "Pick another key with --key.",
+ );
+ });
+
+ it("points at kaneo project edit when the key has to change first", () => {
+ expect(keyConflictHint("KAN2", "kaneo project edit p1")).toBe(
+ "Give it another key first, for example kaneo project edit p1 --key KAN2.",
+ );
+ });
+});
diff --git a/packages/cli/src/projects-write/key-conflict.ts b/packages/cli/src/projects-write/key-conflict.ts
new file mode 100644
index 000000000..3c7d48e51
--- /dev/null
+++ b/packages/cli/src/projects-write/key-conflict.ts
@@ -0,0 +1,39 @@
+import { Effect } from "effect";
+import { listProjectRecords } from "../api/project-writes.js";
+import { type Conflict, InvalidArgument } from "../errors/errors.js";
+import { suggestProjectKey } from "./project-key.js";
+
+export function keyConflictHint(
+ suggestion: string | undefined,
+ retry: string | undefined,
+): string {
+ if (retry) {
+ return `Give it another key first, for example ${retry} --key ${suggestion ?? "NEW"}.`;
+ }
+ return suggestion
+ ? `Pick another key, for example --key ${suggestion}.`
+ : "Pick another key with --key.";
+}
+
+export const explainKeyConflict = Effect.fnUntraced(function* (
+ conflict: Conflict,
+ options: {
+ readonly workspaceId: string;
+ readonly name: string;
+ readonly key: string;
+ readonly retry?: string;
+ },
+) {
+ const projects = yield* listProjectRecords(options.workspaceId).pipe(
+ Effect.orElseSucceed(() => []),
+ );
+ const suggestion = suggestProjectKey(
+ options.name,
+ options.key,
+ projects.map((project) => project.slug),
+ );
+ return yield* new InvalidArgument({
+ message: conflict.message,
+ hint: keyConflictHint(suggestion, options.retry),
+ });
+});
diff --git a/packages/cli/src/projects-write/match-project.test.ts b/packages/cli/src/projects-write/match-project.test.ts
new file mode 100644
index 000000000..e86962025
--- /dev/null
+++ b/packages/cli/src/projects-write/match-project.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from "vite-plus/test";
+import { matchProjectRecord } from "./match-project.js";
+
+const projects = [
+ { id: "p1", slug: "KAN", name: "Kaneo Web" },
+ { id: "p2", slug: "mob", name: "Mobile App" },
+];
+
+describe("matchProjectRecord", () => {
+ it("matches by id, key and name without regard to case", () => {
+ expect(matchProjectRecord(projects, "p2")?.id).toBe("p2");
+ expect(matchProjectRecord(projects, "MOB")?.id).toBe("p2");
+ expect(matchProjectRecord(projects, " kan ")?.id).toBe("p1");
+ expect(matchProjectRecord(projects, "kaneo web")?.id).toBe("p1");
+ });
+
+ it("returns nothing for an unknown project", () => {
+ expect(matchProjectRecord(projects, "XYZ")).toBeUndefined();
+ });
+});
diff --git a/packages/cli/src/projects-write/match-project.ts b/packages/cli/src/projects-write/match-project.ts
new file mode 100644
index 000000000..f0cee7431
--- /dev/null
+++ b/packages/cli/src/projects-write/match-project.ts
@@ -0,0 +1,20 @@
+type ProjectRef = {
+ readonly id: string;
+ readonly slug: string;
+ readonly name: string;
+};
+
+export function matchProjectRecord<P extends ProjectRef>(
+ projects: ReadonlyArray<P>,
+ reference: string,
+): P | undefined {
+ const trimmed = reference.trim();
+ const normalized = trimmed.normalize("NFKC").toLowerCase();
+ return (
+ projects.find((project) => project.id === trimmed) ??
+ projects.find(
+ (project) => project.slug.normalize("NFKC").toLowerCase() === normalized,
+ ) ??
+ projects.find((project) => project.name.toLowerCase() === normalized)
+ );
+}
diff --git a/packages/cli/src/projects-write/project-edits.test.ts b/packages/cli/src/projects-write/project-edits.test.ts
new file mode 100644
index 000000000..76b5bdb20
--- /dev/null
+++ b/packages/cli/src/projects-write/project-edits.test.ts
@@ -0,0 +1,116 @@
+import { Option, Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import type { ProjectRecord } from "../api/project-writes.js";
+import {
+ buildProjectUpdate,
+ describeEdits,
+ parseProjectEdits,
+} from "./project-edits.js";
+
+const none = {
+ name: Option.none<string>(),
+ key: Option.none<string>(),
+ description: Option.none<string>(),
+ icon: Option.none<string>(),
+ public: false,
+ private: false,
+};
+
+const current: ProjectRecord = {
+ id: "p1",
+ workspaceId: "w1",
+ slug: "KAN",
+ name: "Kaneo Web",
+ icon: "Rocket",
+ description: "Board",
+ isPublic: false,
+ archivedAt: null,
+};
+
+describe("parseProjectEdits", () => {
+ it("needs at least one change", () => {
+ const result = parseProjectEdits(none);
+ expect(Result.isFailure(result) && result.failure.message).toBe(
+ "Nothing to change.",
+ );
+ });
+
+ it("refuses --public with --private", () => {
+ expect(
+ Result.isFailure(
+ parseProjectEdits({ ...none, public: true, private: true }),
+ ),
+ ).toBe(true);
+ });
+
+ it("validates the key and the icon", () => {
+ expect(
+ Result.isFailure(parseProjectEdits({ ...none, key: Option.some("a b") })),
+ ).toBe(true);
+ expect(
+ Result.isFailure(
+ parseProjectEdits({ ...none, icon: Option.some("nope") }),
+ ),
+ ).toBe(true);
+ expect(
+ Result.getOrThrow(
+ parseProjectEdits({
+ ...none,
+ key: Option.some("web"),
+ icon: Option.some("folder-kanban"),
+ }),
+ ),
+ ).toEqual({ key: "WEB", icon: "FolderKanban" });
+ });
+
+ it("refuses an empty name", () => {
+ expect(
+ Result.isFailure(parseProjectEdits({ ...none, name: Option.some(" ") })),
+ ).toBe(true);
+ });
+
+ it("keeps an empty description, which clears it", () => {
+ expect(
+ Result.getOrThrow(
+ parseProjectEdits({ ...none, description: Option.some("") }),
+ ),
+ ).toEqual({ description: "" });
+ });
+});
+
+describe("buildProjectUpdate", () => {
+ it("sends every field back unchanged except the edited ones", () => {
+ expect(
+ buildProjectUpdate(current, { name: "Web", isPublic: true }),
+ ).toEqual({
+ name: "Web",
+ icon: "Rocket",
+ slug: "KAN",
+ description: "Board",
+ isPublic: true,
+ });
+ });
+
+ it("fills the fields the API requires when they are null", () => {
+ expect(
+ buildProjectUpdate(
+ { ...current, icon: null, description: null, isPublic: null },
+ { key: "WEB" },
+ ),
+ ).toEqual({
+ name: "Kaneo Web",
+ icon: "Layout",
+ slug: "WEB",
+ description: "",
+ isPublic: false,
+ });
+ });
+});
+
+describe("describeEdits", () => {
+ it("lists the changed fields", () => {
+ expect(describeEdits({ name: "Web", key: "WEB", isPublic: false })).toBe(
+ "name, key, now private",
+ );
+ });
+});
diff --git a/packages/cli/src/projects-write/project-edits.ts b/packages/cli/src/projects-write/project-edits.ts
new file mode 100644
index 000000000..ffeba7faf
--- /dev/null
+++ b/packages/cli/src/projects-write/project-edits.ts
@@ -0,0 +1,105 @@
+import { Option, Result } from "effect";
+import type {
+ ProjectRecord,
+ ProjectUpdateBody,
+} from "../api/project-writes.js";
+import { InvalidArgument } from "../errors/errors.js";
+import { DEFAULT_PROJECT_ICON, matchProjectIcon } from "./project-icons.js";
+import { validateProjectKey } from "./project-key.js";
+
+export type ProjectEdits = {
+ readonly name?: string;
+ readonly key?: string;
+ readonly description?: string;
+ readonly icon?: string;
+ readonly isPublic?: boolean;
+};
+
+export type ProjectEditFlags = {
+ readonly name: Option.Option<string>;
+ readonly key: Option.Option<string>;
+ readonly description: Option.Option<string>;
+ readonly icon: Option.Option<string>;
+ readonly public: boolean;
+ readonly private: boolean;
+};
+
+export function parseProjectEdits(
+ flags: ProjectEditFlags,
+): Result.Result<ProjectEdits, InvalidArgument> {
+ if (flags.public && flags.private) {
+ return Result.fail(
+ new InvalidArgument({
+ message: "Pass either --public or --private, not both.",
+ }),
+ );
+ }
+ const edits: {
+ name?: string;
+ key?: string;
+ description?: string;
+ icon?: string;
+ isPublic?: boolean;
+ } = {};
+ if (Option.isSome(flags.name)) {
+ const name = flags.name.value.trim();
+ if (name === "") {
+ return Result.fail(
+ new InvalidArgument({
+ message: "The project name cannot be empty.",
+ hint: 'Pass a name, for example --name "Kaneo Web".',
+ }),
+ );
+ }
+ edits.name = name;
+ }
+ if (Option.isSome(flags.key)) {
+ const key = validateProjectKey(flags.key.value);
+ if (Result.isFailure(key)) return Result.fail(key.failure);
+ edits.key = key.success;
+ }
+ if (Option.isSome(flags.description)) {
+ edits.description = flags.description.value;
+ }
+ if (Option.isSome(flags.icon)) {
+ const icon = matchProjectIcon(flags.icon.value);
+ if (Result.isFailure(icon)) return Result.fail(icon.failure);
+ edits.icon = icon.success;
+ }
+ if (flags.public) edits.isPublic = true;
+ if (flags.private) edits.isPublic = false;
+ if (Object.keys(edits).length === 0) {
+ return Result.fail(
+ new InvalidArgument({
+ message: "Nothing to change.",
+ hint: "Pass at least one of --name, --key, --description, --icon, --public or --private.",
+ }),
+ );
+ }
+ return Result.succeed(edits);
+}
+
+export function buildProjectUpdate(
+ current: ProjectRecord,
+ edits: ProjectEdits,
+): ProjectUpdateBody {
+ return {
+ name: edits.name ?? current.name,
+ icon: edits.icon ?? current.icon ?? DEFAULT_PROJECT_ICON,
+ slug: edits.key ?? current.slug,
+ description: edits.description ?? current.description ?? "",
+ isPublic: edits.isPublic ?? current.isPublic ?? false,
+ };
+}
+
+export function describeEdits(edits: ProjectEdits): string {
+ const fields: string[] = [];
+ if (edits.name !== undefined) fields.push("name");
+ if (edits.key !== undefined) fields.push("key");
+ if (edits.description !== undefined) fields.push("description");
+ if (edits.icon !== undefined) fields.push("icon");
+ if (edits.isPublic !== undefined) {
+ fields.push(edits.isPublic ? "now public" : "now private");
+ }
+ return fields.join(", ");
+}
diff --git a/packages/cli/src/projects-write/project-icons.ts b/packages/cli/src/projects-write/project-icons.ts
new file mode 100644
index 000000000..9492c76f0
--- /dev/null
+++ b/packages/cli/src/projects-write/project-icons.ts
@@ -0,0 +1,87 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+
+export const DEFAULT_PROJECT_ICON = "Layout";
+
+export const PROJECT_ICONS = [
+ "Layout",
+ "Briefcase",
+ "FolderKanban",
+ "Target",
+ "Rocket",
+ "Code",
+ "Box",
+ "Boxes",
+ "BookOpen",
+ "Bookmark",
+ "Building2",
+ "Calendar",
+ "CircuitBoard",
+ "Cog",
+ "Database",
+ "FileText",
+ "Flag",
+ "FlaskConical",
+ "Folder",
+ "GitBranch",
+ "Globe",
+ "Heart",
+ "Home",
+ "Image",
+ "Layers",
+ "Lightbulb",
+ "Link2",
+ "List",
+ "MessageSquare",
+ "Music",
+ "Package",
+ "Palette",
+ "PenTool",
+ "Phone",
+ "PieChart",
+ "Puzzle",
+ "Radio",
+ "ScrollText",
+ "Search",
+ "Settings",
+ "Share2",
+ "Shield",
+ "ShoppingBag",
+ "Smile",
+ "Star",
+ "Table",
+ "Tags",
+ "Terminal",
+ "ThumbsUp",
+ "Timer",
+ "Tool",
+ "Trash2",
+ "Trophy",
+ "Tv2",
+ "User",
+ "Users",
+ "Video",
+ "Wallet",
+ "Wand2",
+ "Watch",
+ "Zap",
+] as const;
+
+function compact(value: string): string {
+ return value.toLowerCase().replace(/[^a-z0-9]/g, "");
+}
+
+export function matchProjectIcon(
+ input: string,
+): Result.Result<string, InvalidArgument> {
+ const wanted = compact(input);
+ const match = PROJECT_ICONS.find((icon) => compact(icon) === wanted);
+ return match
+ ? Result.succeed(match)
+ : Result.fail(
+ new InvalidArgument({
+ message: `"${input}" is not a project icon.`,
+ hint: `Use one of the Lucide names the web app offers, for example ${PROJECT_ICONS.slice(0, 6).join(", ")}.`,
+ }),
+ );
+}
diff --git a/packages/cli/src/projects-write/project-key.test.ts b/packages/cli/src/projects-write/project-key.test.ts
new file mode 100644
index 000000000..2587a05c9
--- /dev/null
+++ b/packages/cli/src/projects-write/project-key.test.ts
@@ -0,0 +1,81 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import {
+ deriveProjectKey,
+ suggestProjectKey,
+ validateProjectKey,
+} from "./project-key.js";
+
+describe("deriveProjectKey", () => {
+ it("takes the first three letters of a single word, like the web app", () => {
+ expect(deriveProjectKey("Kaneo")).toBe("KAN");
+ });
+
+ it("takes the initials of the first three words", () => {
+ expect(deriveProjectKey("Kaneo Web")).toBe("KW");
+ expect(deriveProjectKey("Alpha Beta Gamma Delta")).toBe("ABG");
+ });
+
+ it("ignores punctuation and leading separators", () => {
+ expect(deriveProjectKey(" - Alpha Beta Gamma")).toBe("ABG");
+ expect(deriveProjectKey("[Alpha] Beta Gamma")).toBe("ABG");
+ expect(deriveProjectKey("Sprint 2")).toBe("S2");
+ });
+
+ it("keeps non-Latin scripts and counts code points", () => {
+ expect(deriveProjectKey("Проект Альфа")).toBe("ПА");
+ expect(deriveProjectKey("测试项目")).toBe("测试项");
+ expect(deriveProjectKey("𠀀𠀁𠀂𠀃")).toBe("𠀀𠀁𠀂");
+ });
+
+ it("folds full-width characters", () => {
+ expect(deriveProjectKey("ABC")).toBe("ABC");
+ });
+
+ it("returns an empty key when the name has no letters or numbers", () => {
+ expect(deriveProjectKey("!!!")).toBe("");
+ });
+});
+
+describe("validateProjectKey", () => {
+ it("upper-cases and trims the key", () => {
+ expect(Result.getOrThrow(validateProjectKey(" web "))).toBe("WEB");
+ });
+
+ it("rejects empty, long and punctuated keys", () => {
+ expect(Result.isFailure(validateProjectKey(" "))).toBe(true);
+ expect(Result.isFailure(validateProjectKey("ABCDEFGHI"))).toBe(true);
+ expect(Result.isFailure(validateProjectKey("WEB-2"))).toBe(true);
+ expect(Result.isFailure(validateProjectKey("WE B"))).toBe(true);
+ });
+
+ it("accepts eight letters and digits", () => {
+ expect(Result.getOrThrow(validateProjectKey("abcd1234"))).toBe("ABCD1234");
+ });
+
+ it("explains which rule failed", () => {
+ const result = validateProjectKey("a-b");
+ expect(Result.isFailure(result) && result.failure.message).toBe(
+ 'The project key "A-B" can only contain letters and numbers.',
+ );
+ });
+});
+
+describe("suggestProjectKey", () => {
+ it("first tries a longer prefix of the name", () => {
+ expect(suggestProjectKey("Kaneo Mobile", "KM", ["KM", "kan"])).toBe("KANE");
+ });
+
+ it("falls back to a numbered key", () => {
+ expect(suggestProjectKey("Kaneo", "KAN", ["KAN", "KANE"])).toBe("KAN2");
+ expect(suggestProjectKey("Kaneo", "KAN", ["kan", "kane", "kan2"])).toBe(
+ "KAN3",
+ );
+ });
+
+ it("stays within eight characters", () => {
+ expect(
+ suggestProjectKey("Abcdefgh", "ABCDEFGH", ["ABCDEFGH", "ABCD"]),
+ ).toBe("ABCDEFG2");
+ });
+});
diff --git a/packages/cli/src/projects-write/project-key.ts b/packages/cli/src/projects-write/project-key.ts
new file mode 100644
index 000000000..9cb99114b
--- /dev/null
+++ b/packages/cli/src/projects-write/project-key.ts
@@ -0,0 +1,98 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+
+export const MAX_KEY_LENGTH = 8;
+
+const LETTER_OR_NUMBER = /[\p{L}\p{N}]/u;
+const KEY_PATTERN = /^[\p{L}\p{N}][\p{L}\p{M}\p{N}]*$/u;
+
+function firstLetterOrNumber(word: string): string {
+ for (const char of word) {
+ if (LETTER_OR_NUMBER.test(char)) return char;
+ }
+ return "";
+}
+
+export function deriveProjectKey(name: string): string {
+ const words = name
+ .normalize("NFKC")
+ .toUpperCase()
+ .replace(/[^\p{L}\p{M}\p{N}\s]/gu, "")
+ .split(/\s+/)
+ .filter((word) => LETTER_OR_NUMBER.test(word));
+ const [first] = words;
+ if (first === undefined) return "";
+ if (words.length === 1) {
+ const codePoints = Array.from(first);
+ const start = codePoints.findIndex((char) => LETTER_OR_NUMBER.test(char));
+ return codePoints.slice(start, start + 3).join("");
+ }
+ return words.slice(0, 3).map(firstLetterOrNumber).join("");
+}
+
+export function validateProjectKey(
+ input: string,
+ flag = "--key",
+): Result.Result<string, InvalidArgument> {
+ const key = input.normalize("NFKC").trim().toUpperCase();
+ if (key === "") {
+ return Result.fail(
+ new InvalidArgument({
+ message: "The project key cannot be empty.",
+ hint: `Pass ${flag} with a short key, for example ${flag} KAN.`,
+ }),
+ );
+ }
+ if (Array.from(key).length > MAX_KEY_LENGTH) {
+ return Result.fail(
+ new InvalidArgument({
+ message: `The project key "${key}" is longer than ${MAX_KEY_LENGTH} characters.`,
+ hint: `Pick a key of at most ${MAX_KEY_LENGTH} letters or numbers.`,
+ }),
+ );
+ }
+ if (!KEY_PATTERN.test(key)) {
+ return Result.fail(
+ new InvalidArgument({
+ message: `The project key "${key}" can only contain letters and numbers.`,
+ hint: "Task ids look like KEY-12, so leave out spaces, dashes and punctuation.",
+ }),
+ );
+ }
+ return Result.succeed(key);
+}
+
+function normalized(key: string): string {
+ return key.normalize("NFKC").toLowerCase();
+}
+
+export function suggestProjectKey(
+ name: string,
+ key: string,
+ taken: ReadonlyArray<string>,
+): string | undefined {
+ const used = new Set(taken.map(normalized));
+ const free = (candidate: string) =>
+ KEY_PATTERN.test(candidate) && !used.has(normalized(candidate));
+ const letters = Array.from(
+ name
+ .normalize("NFKC")
+ .toUpperCase()
+ .replace(/[^\p{L}\p{M}\p{N}]/gu, ""),
+ );
+ const keyLength = Array.from(key).length;
+ for (let length = keyLength + 1; length <= 4; length++) {
+ const candidate = letters.slice(0, length).join("");
+ if (Array.from(candidate).length === length && free(candidate)) {
+ return candidate;
+ }
+ }
+ const stem = Array.from(key);
+ for (let suffix = 2; suffix < 100; suffix++) {
+ const digits = String(suffix);
+ const candidate =
+ stem.slice(0, MAX_KEY_LENGTH - digits.length).join("") + digits;
+ if (free(candidate)) return candidate;
+ }
+ return undefined;
+}
diff --git a/packages/cli/src/projects-write/project-record-json.ts b/packages/cli/src/projects-write/project-record-json.ts
new file mode 100644
index 000000000..5e1565cf5
--- /dev/null
+++ b/packages/cli/src/projects-write/project-record-json.ts
@@ -0,0 +1,30 @@
+import type {
+ ProjectRecord,
+ ProjectStatistics,
+} from "../api/project-writes.js";
+import { type ProjectJson, toProjectJson } from "../projects/project-json.js";
+
+export type ProjectRecordJson = ProjectJson & {
+ readonly description: string | null;
+ readonly icon: string | null;
+ readonly isPublic: boolean;
+};
+
+export const EMPTY_STATISTICS: ProjectStatistics = {
+ totalTasks: 0,
+ completionPercentage: 0,
+ dueDate: null,
+};
+
+export function toProjectRecordJson(
+ project: ProjectRecord,
+ statistics: ProjectStatistics,
+ webUrl: string,
+): ProjectRecordJson {
+ return {
+ ...toProjectJson({ ...project, statistics }, webUrl),
+ description: project.description,
+ icon: project.icon,
+ isPublic: project.isPublic ?? false,
+ };
+}
diff --git a/packages/cli/src/projects-write/render-project-change.test.ts b/packages/cli/src/projects-write/render-project-change.test.ts
new file mode 100644
index 000000000..8acfa009a
--- /dev/null
+++ b/packages/cli/src/projects-write/render-project-change.test.ts
@@ -0,0 +1,92 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import {
+ renderProjectChange,
+ renderProjectUnchanged,
+} from "./render-project-change.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+describe("renderProjectChange", () => {
+ it("prints the created project on one line", () => {
+ expect(
+ renderProjectChange(ui, {
+ verb: "Created",
+ name: "Kaneo Web",
+ key: "KAN",
+ url: "https://kaneo.test/p",
+ }),
+ ).toEqual(["", " ✓ Created project Kaneo Web · KAN", ""]);
+ });
+
+ it("adds the changed fields and the move target", () => {
+ expect(
+ renderProjectChange(ui, {
+ verb: "Updated",
+ name: "Kaneo Web",
+ key: "WEB",
+ url: "https://kaneo.test/p",
+ detail: "name, key",
+ })[1],
+ ).toBe(" ✓ Updated project Kaneo Web · WEB · name, key");
+ expect(
+ renderProjectChange(ui, {
+ verb: "Moved",
+ name: "Kaneo Web",
+ key: "KAN",
+ url: "https://kaneo.test/p",
+ target: "Side Project",
+ })[1],
+ ).toBe(" ✓ Moved project Kaneo Web · KAN → Side Project");
+ });
+
+ it("shortens a long name to fit 80 columns", () => {
+ const [, line] = renderProjectChange(ui, {
+ verb: "Archived",
+ name: "A very long project name ".repeat(5).trim(),
+ key: "LONG",
+ url: "https://kaneo.test/p",
+ });
+ expect(stringWidth(line ?? "")).toBeLessThanOrEqual(80);
+ expect(line).toContain("… · LONG");
+ });
+
+ it("uses ASCII glyphs when the terminal needs them", () => {
+ const ascii = makeUi({
+ color: 0,
+ unicode: false,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+ });
+ expect(
+ renderProjectChange(ascii, {
+ verb: "Deleted",
+ name: "Kaneo Web",
+ key: "KAN",
+ url: "",
+ detail: "12 tasks",
+ })[1],
+ ).toBe(" + Deleted project Kaneo Web - KAN - 12 tasks");
+ });
+});
+
+describe("renderProjectUnchanged", () => {
+ it("says the project was already in that state", () => {
+ expect(
+ renderProjectUnchanged(ui, {
+ name: "Kaneo Web",
+ key: "KAN",
+ url: "https://kaneo.test/p",
+ state: "archived",
+ }),
+ ).toEqual(["", " ✓ Kaneo Web · KAN is already archived", ""]);
+ });
+});
diff --git a/packages/cli/src/projects-write/render-project-change.ts b/packages/cli/src/projects-write/render-project-change.ts
new file mode 100644
index 000000000..1e4b7f221
--- /dev/null
+++ b/packages/cli/src/projects-write/render-project-change.ts
@@ -0,0 +1,60 @@
+import { renderCell, text } from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+import { stringWidth, truncate } from "../render/width.js";
+
+export type ProjectChange = {
+ readonly verb: string;
+ readonly name: string;
+ readonly key: string;
+ readonly url: string;
+ readonly detail?: string | undefined;
+ readonly target?: string | undefined;
+};
+
+export function renderProjectChange(ui: Ui, change: ProjectChange): string[] {
+ const { theme, glyphs } = ui;
+ const head = ` ${glyphs.tick} ${change.verb} project `;
+ const tail = [
+ ` ${glyphs.separator} ${change.key}`,
+ change.target ? ` ${glyphs.arrow} ${change.target}` : "",
+ change.detail ? ` ${glyphs.separator} ${change.detail}` : "",
+ ].join("");
+ const room = Math.max(8, ui.caps.columns - stringWidth(head + tail));
+ const name = renderCell(
+ [
+ text(
+ truncate(change.name, room, glyphs.ellipsis),
+ theme.strong,
+ change.url,
+ ),
+ ],
+ ui,
+ );
+ const line = [
+ ` ${theme.success(glyphs.tick)} ${change.verb} project ${name}`,
+ ` ${theme.muted(glyphs.separator)} ${change.key}`,
+ change.target
+ ? ` ${theme.muted(glyphs.arrow)} ${theme.strong(change.target)}`
+ : "",
+ change.detail ? ` ${theme.muted(glyphs.separator)} ${change.detail}` : "",
+ ].join("");
+ return ["", line, ""];
+}
+
+export function renderProjectUnchanged(
+ ui: Ui,
+ project: {
+ readonly name: string;
+ readonly key: string;
+ readonly url: string;
+ readonly state: string;
+ },
+): string[] {
+ const { theme, glyphs } = ui;
+ const name = renderCell([text(project.name, theme.strong, project.url)], ui);
+ return [
+ "",
+ ` ${theme.success(glyphs.tick)} ${name} ${theme.muted(glyphs.separator)} ${project.key} ${theme.muted(`is already ${project.state}`)}`,
+ "",
+ ];
+}
diff --git a/packages/cli/src/projects-write/resolve-project-record.ts b/packages/cli/src/projects-write/resolve-project-record.ts
new file mode 100644
index 000000000..603a51ea1
--- /dev/null
+++ b/packages/cli/src/projects-write/resolve-project-record.ts
@@ -0,0 +1,76 @@
+import { Effect, Option } from "effect";
+import {
+ listProjectRecords,
+ type ProjectRecordWithStatistics,
+} from "../api/project-writes.js";
+import { InvalidArgument, ProjectNotFound } from "../errors/errors.js";
+import { Output } from "../output/output.js";
+import { withSpinner } from "../output/spinner.js";
+import { pick } from "../prompts/pick.js";
+import { Session } from "../services/session.js";
+import { matchProjectRecord } from "./match-project.js";
+
+export type ProjectScope = "active" | "archived" | "any";
+
+function inScope(project: ProjectRecordWithStatistics, scope: ProjectScope) {
+ if (scope === "any") return true;
+ return scope === "archived"
+ ? project.archivedAt !== null
+ : project.archivedAt === null;
+}
+
+export const resolveProjectRecord = Effect.fn("projects.resolveRecord")(
+ function* (options: {
+ readonly workspaceId: string;
+ readonly reference: Option.Option<string>;
+ readonly scope: ProjectScope;
+ readonly useContext: boolean;
+ readonly prompt: string;
+ readonly missing: string;
+ readonly example: string;
+ }) {
+ const session = yield* Session;
+ const output = yield* Output;
+ const projects = yield* withSpinner("Loading projects")(
+ listProjectRecords(options.workspaceId),
+ );
+ const wanted = Option.orElse(
+ Option.map(options.reference, (ref) => ({
+ ref,
+ source: null as string | null,
+ })),
+ () =>
+ options.useContext
+ ? Option.map(session.project, (project) => ({
+ ref: project.ref,
+ source: project.source as string | null,
+ }))
+ : Option.none(),
+ );
+ if (Option.isSome(wanted)) {
+ const match = matchProjectRecord(projects, wanted.value.ref);
+ if (match) return match;
+ return yield* new ProjectNotFound({
+ query: wanted.value.ref,
+ source: wanted.value.source,
+ });
+ }
+ const candidates = projects.filter((project) =>
+ inScope(project, options.scope),
+ );
+ if (candidates.length > 0 && output.interactive) {
+ return yield* pick(
+ options.prompt,
+ candidates.map((project) => ({
+ title: project.name,
+ value: project,
+ description: project.slug.toUpperCase(),
+ })),
+ );
+ }
+ return yield* new InvalidArgument({
+ message: options.missing,
+ hint: `Pass its key or id, for example ${options.example}.`,
+ });
+ },
+);
diff --git a/packages/cli/src/projects-write/set-archived.ts b/packages/cli/src/projects-write/set-archived.ts
new file mode 100644
index 000000000..2e6c990ec
--- /dev/null
+++ b/packages/cli/src/projects-write/set-archived.ts
@@ -0,0 +1,75 @@
+import { Effect, type Option } from "effect";
+import { archiveProject, unarchiveProject } from "../api/project-writes.js";
+import { emit } from "../output/emit.js";
+import { withSpinner } from "../output/spinner.js";
+import { resolveWorkspaceId } from "../services/selection.js";
+import { Session } from "../services/session.js";
+import { explainKeyConflict } from "./key-conflict.js";
+import { toProjectRecordJson } from "./project-record-json.js";
+import {
+ renderProjectChange,
+ renderProjectUnchanged,
+} from "./render-project-change.js";
+import { resolveProjectRecord } from "./resolve-project-record.js";
+
+export const setArchived = Effect.fn("projects.setArchived")(function* (
+ reference: Option.Option<string>,
+ archived: boolean,
+) {
+ const session = yield* Session;
+ const workspaceId = yield* resolveWorkspaceId();
+ const verb = archived ? "archive" : "unarchive";
+ const project = yield* resolveProjectRecord({
+ workspaceId,
+ reference,
+ scope: archived ? "active" : "archived",
+ useContext: true,
+ prompt: `Choose a project to ${verb}`,
+ missing: `Which project should be ${verb}d?`,
+ example: `kaneo project ${verb} KAN`,
+ });
+
+ if ((project.archivedAt !== null) === archived) {
+ const json = toProjectRecordJson(
+ project,
+ project.statistics,
+ session.webUrl,
+ );
+ return yield* emit(json, (ui) =>
+ renderProjectUnchanged(ui, {
+ name: json.name,
+ key: json.key,
+ url: json.url,
+ state: archived ? "archived" : "active",
+ }),
+ );
+ }
+
+ const updated = archived
+ ? yield* withSpinner(`Archiving ${project.name}`)(
+ archiveProject(project.id),
+ )
+ : yield* withSpinner(`Restoring ${project.name}`)(
+ unarchiveProject(project.id),
+ ).pipe(
+ Effect.catchTag("Conflict", (conflict) =>
+ explainKeyConflict(conflict, {
+ workspaceId,
+ name: project.name,
+ key: project.slug,
+ retry: `kaneo project edit ${project.id}`,
+ }),
+ ),
+ );
+
+ yield* emit(
+ toProjectRecordJson(updated, project.statistics, session.webUrl),
+ (ui, json) =>
+ renderProjectChange(ui, {
+ verb: archived ? "Archived" : "Restored",
+ name: json.name,
+ key: json.key,
+ url: json.url,
+ }),
+ );
+});
diff --git a/packages/cli/src/projects/description-preview.test.ts b/packages/cli/src/projects/description-preview.test.ts
new file mode 100644
index 000000000..8d24a4d31
--- /dev/null
+++ b/packages/cli/src/projects/description-preview.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from "vite-plus/test";
+import { descriptionPreview, plainText } from "./description-preview.js";
+
+describe("plainText", () => {
+ it("leaves plain text alone", () => {
+ expect(plainText("Use <3 and a < b")).toBe("Use <3 and a < b");
+ });
+
+ it("turns simple HTML into lines of text", () => {
+ expect(plainText("<p>Hello &amp; welcome</p><p>Second<br/>line</p>")).toBe(
+ "Hello & welcome\nSecond\nline\n",
+ );
+ });
+});
+
+describe("descriptionPreview", () => {
+ it("is empty without a description", () => {
+ expect(descriptionPreview(null)).toEqual({ lines: [], more: false });
+ expect(descriptionPreview(" \n\n ")).toEqual({ lines: [], more: false });
+ });
+
+ it("trims blank edges and collapses repeated blank lines", () => {
+ expect(descriptionPreview("\n\nFirst line\r\n\n\n\nSecond\n\n")).toEqual({
+ lines: ["First line", "", "Second"],
+ more: false,
+ });
+ });
+
+ it("keeps the first lines and reports the rest", () => {
+ const preview = descriptionPreview("1\n2\n3\n4\n5\n6\n7", 5);
+ expect(preview).toEqual({ lines: ["1", "2", "3", "4", "5"], more: true });
+ });
+});
diff --git a/packages/cli/src/projects/description-preview.ts b/packages/cli/src/projects/description-preview.ts
new file mode 100644
index 000000000..730818694
--- /dev/null
+++ b/packages/cli/src/projects/description-preview.ts
@@ -0,0 +1,45 @@
+const BLOCK_BREAK =
+ /<\s*(?:br\s*\/?|\/\s*(?:p|div|li|h[1-6]|blockquote|pre|tr))\s*>/giu;
+const TAG = /<[^>]+>/gu;
+const ENTITIES: Readonly<Record<string, string>> = {
+ "&amp;": "&",
+ "&lt;": "<",
+ "&gt;": ">",
+ "&quot;": '"',
+ "&#39;": "'",
+ "&nbsp;": " ",
+};
+
+export function plainText(value: string): string {
+ const looksLikeHtml = /<\/?[a-z][^>]*>/iu.test(value);
+ const text = looksLikeHtml
+ ? value
+ .replace(BLOCK_BREAK, "\n")
+ .replace(TAG, "")
+ .replace(
+ /&(?:amp|lt|gt|quot|#39|nbsp);/gu,
+ (entity) => ENTITIES[entity] ?? entity,
+ )
+ : value;
+ return text.replace(/\r\n?/gu, "\n");
+}
+
+export type DescriptionPreview = {
+ readonly lines: ReadonlyArray<string>;
+ readonly more: boolean;
+};
+
+export function descriptionPreview(
+ description: string | null,
+ maxLines = 5,
+): DescriptionPreview {
+ if (!description) return { lines: [], more: false };
+ const lines: string[] = [];
+ for (const raw of plainText(description).split("\n")) {
+ const line = raw.replace(/\s+/gu, " ").trim();
+ if (line === "" && (lines.length === 0 || lines.at(-1) === "")) continue;
+ lines.push(line);
+ }
+ while (lines.at(-1) === "") lines.pop();
+ return { lines: lines.slice(0, maxLines), more: lines.length > maxLines };
+}
diff --git a/packages/cli/src/projects/progress-bar.test.ts b/packages/cli/src/projects/progress-bar.test.ts
new file mode 100644
index 000000000..393f08152
--- /dev/null
+++ b/packages/cli/src/projects/progress-bar.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from "vite-plus/test";
+import { renderCell } from "../render/cell.js";
+import { makeUi } from "../render/ui.js";
+import { barSegments, progressSegments } from "./progress-bar.js";
+
+const unicode = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+const ascii = makeUi({
+ color: 0,
+ unicode: false,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+const colored = makeUi({
+ color: 1,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+const bar = (ratio: number, width = 10) =>
+ renderCell(barSegments(unicode, ratio, width), unicode);
+
+describe("barSegments", () => {
+ it("fills in proportion to the ratio", () => {
+ expect(bar(0)).toBe("▱▱▱▱▱▱▱▱▱▱");
+ expect(bar(0.5)).toBe("▰▰▰▰▰▱▱▱▱▱");
+ expect(bar(1)).toBe("▰▰▰▰▰▰▰▰▰▰");
+ });
+
+ it("shows any progress at all and keeps a gap until it is complete", () => {
+ expect(bar(0.01)).toBe("▰▱▱▱▱▱▱▱▱▱");
+ expect(bar(0.99)).toBe("▰▰▰▰▰▰▰▰▰▱");
+ });
+
+ it("clamps odd input", () => {
+ expect(bar(-1)).toBe("▱▱▱▱▱▱▱▱▱▱");
+ expect(bar(3)).toBe("▰▰▰▰▰▰▰▰▰▰");
+ expect(bar(Number.NaN)).toBe("▱▱▱▱▱▱▱▱▱▱");
+ expect(bar(0.5, 0)).toBe("");
+ });
+
+ it("falls back to ASCII", () => {
+ expect(renderCell(barSegments(ascii, 0.3, 10), ascii)).toBe("###-------");
+ });
+});
+
+describe("progressSegments", () => {
+ it("adds an aligned percentage", () => {
+ expect(renderCell(progressSegments(unicode, 14), unicode)).toBe(
+ "▰▱▱▱▱▱▱▱▱▱ 14%",
+ );
+ expect(renderCell(progressSegments(unicode, 100), unicode)).toBe(
+ "▰▰▰▰▰▰▰▰▰▰ 100%",
+ );
+ });
+
+ it("uses the success color only when complete", () => {
+ const done = renderCell(progressSegments(colored, 100), colored);
+ const partial = renderCell(progressSegments(colored, 50), colored);
+ expect(done).toContain("\u001b[32m▰▰▰▰▰▰▰▰▰▰");
+ expect(partial).not.toContain("\u001b[32m");
+ });
+});
diff --git a/packages/cli/src/projects/progress-bar.ts b/packages/cli/src/projects/progress-bar.ts
new file mode 100644
index 000000000..551f57206
--- /dev/null
+++ b/packages/cli/src/projects/progress-bar.ts
@@ -0,0 +1,47 @@
+import type { Segment } from "../render/cell.js";
+import type { Style } from "../render/theme.js";
+import type { Ui } from "../render/ui.js";
+
+function clampRatio(ratio: number): number {
+ return Number.isFinite(ratio) ? Math.min(1, Math.max(0, ratio)) : 0;
+}
+
+export function barSegments(
+ ui: Ui,
+ ratio: number,
+ width: number,
+ style?: Style,
+): Segment[] {
+ if (width <= 0) return [];
+ const value = clampRatio(ratio);
+ let filled = Math.round(value * width);
+ if (value > 0 && filled === 0) filled = 1;
+ if (value < 1 && filled === width) filled = width - 1;
+ const [on, off] = ui.caps.unicode ? ["▰", "▱"] : ["#", "-"];
+ const segments: Segment[] = [];
+ if (filled > 0) segments.push({ text: on.repeat(filled), style });
+ if (filled < width)
+ segments.push({ text: off.repeat(width - filled), style: ui.theme.muted });
+ return segments;
+}
+
+export function progressSegments(
+ ui: Ui,
+ percent: number,
+ width = 10,
+): Segment[] {
+ const value = Math.round(clampRatio(percent / 100) * 100);
+ const complete = value === 100;
+ return [
+ ...barSegments(
+ ui,
+ value / 100,
+ width,
+ complete ? ui.theme.success : ui.theme.info,
+ ),
+ {
+ text: ` ${String(value).padStart(3)}%`,
+ style: complete ? ui.theme.success : undefined,
+ },
+ ];
+}
diff --git a/packages/cli/src/projects/project-json.ts b/packages/cli/src/projects/project-json.ts
new file mode 100644
index 000000000..9d3bf3345
--- /dev/null
+++ b/packages/cli/src/projects/project-json.ts
@@ -0,0 +1,33 @@
+import type { ProjectSummary } from "../api/project-summaries.js";
+import { projectUrl } from "../render/links.js";
+
+export type ProjectJson = {
+ readonly id: string;
+ readonly key: string;
+ readonly name: string;
+ readonly slug: string;
+ readonly workspaceId: string;
+ readonly archived: boolean;
+ readonly totalTasks: number;
+ readonly completion: number;
+ readonly dueDate: string | null;
+ readonly url: string;
+};
+
+export function toProjectJson(
+ project: ProjectSummary,
+ webUrl: string,
+): ProjectJson {
+ return {
+ id: project.id,
+ key: project.slug.toUpperCase(),
+ name: project.name,
+ slug: project.slug,
+ workspaceId: project.workspaceId,
+ archived: project.archivedAt !== null,
+ totalTasks: project.statistics.totalTasks,
+ completion: project.statistics.completionPercentage,
+ dueDate: project.statistics.dueDate,
+ url: projectUrl(webUrl, project),
+ };
+}
diff --git a/packages/cli/src/projects/project-view.ts b/packages/cli/src/projects/project-view.ts
new file mode 100644
index 000000000..78d6770a9
--- /dev/null
+++ b/packages/cli/src/projects/project-view.ts
@@ -0,0 +1,56 @@
+import type { Column, Project } from "../api/schemas.js";
+import { projectUrl } from "../render/links.js";
+
+export type ColumnCountJson = {
+ readonly slug: string;
+ readonly name: string;
+ readonly isFinal: boolean;
+ readonly taskCount: number;
+};
+
+export type ProjectViewJson = {
+ readonly id: string;
+ readonly key: string;
+ readonly name: string;
+ readonly description: string | null;
+ readonly url: string;
+ readonly columns: ReadonlyArray<ColumnCountJson>;
+ readonly totalTasks: number;
+};
+
+export function countByColumn(
+ columns: ReadonlyArray<Column>,
+ tasks: ReadonlyArray<{ readonly status: string }>,
+): ColumnCountJson[] {
+ const counts = new Map<string, number>();
+ for (const task of tasks)
+ counts.set(task.status, (counts.get(task.status) ?? 0) + 1);
+ return [...columns]
+ .sort((a, b) => a.position - b.position)
+ .map((column) => ({
+ slug: column.slug,
+ name: column.name,
+ isFinal: column.isFinal,
+ taskCount: counts.get(column.slug) ?? 0,
+ }));
+}
+
+export function toProjectView(
+ project: Project,
+ columns: ReadonlyArray<Column>,
+ board: {
+ readonly tasks: ReadonlyArray<{ readonly status: string }>;
+ readonly total: number;
+ },
+ webUrl: string,
+): ProjectViewJson {
+ return {
+ id: project.id,
+ key: project.slug.toUpperCase(),
+ name: project.name,
+ description: project.description,
+ url: projectUrl(webUrl, project),
+ columns: countByColumn(columns, board.tasks),
+ totalTasks: board.total,
+ };
+}
diff --git a/packages/cli/src/projects/render-project-list.test.ts b/packages/cli/src/projects/render-project-list.test.ts
new file mode 100644
index 000000000..0edce06c1
--- /dev/null
+++ b/packages/cli/src/projects/render-project-list.test.ts
@@ -0,0 +1,113 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { ProjectSummary } from "../api/project-summaries.js";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import { type ProjectJson, toProjectJson } from "./project-json.js";
+import { renderProjectList } from "./render-project-list.js";
+
+const ui = (columns: number) =>
+ makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns,
+ });
+
+const now = new Date(2026, 9, 7, 12);
+
+function summary(overrides: Partial<ProjectSummary> = {}): ProjectSummary {
+ return {
+ id: "p_kan",
+ workspaceId: "ws_acme",
+ slug: "kan",
+ name: "Kaneo Web",
+ description: null,
+ archivedAt: null,
+ statistics: { totalTasks: 7, completionPercentage: 14, dueDate: null },
+ ...overrides,
+ };
+}
+
+const kan = toProjectJson(
+ summary({
+ statistics: {
+ totalTasks: 7,
+ completionPercentage: 14,
+ dueDate: new Date(2026, 9, 20, 12).toISOString(),
+ },
+ }),
+ "https://kaneo.test",
+);
+const mob = toProjectJson(
+ summary({
+ id: "p_mob",
+ slug: "mob",
+ name: "Mobile App",
+ statistics: { totalTasks: 0, completionPercentage: 0, dueDate: null },
+ }),
+ "https://kaneo.test",
+);
+const old = toProjectJson(
+ summary({
+ id: "p_old",
+ slug: "old",
+ name: "Old Site",
+ archivedAt: "2026-01-01T00:00:00.000Z",
+ statistics: { totalTasks: 1, completionPercentage: 100, dueDate: null },
+ }),
+ "https://kaneo.test",
+);
+
+describe("toProjectJson", () => {
+ it("exposes a stable shape with the key and board link", () => {
+ expect(kan).toEqual({
+ id: "p_kan",
+ key: "KAN",
+ name: "Kaneo Web",
+ slug: "kan",
+ workspaceId: "ws_acme",
+ archived: false,
+ totalTasks: 7,
+ completion: 14,
+ dueDate: new Date(2026, 9, 20, 12).toISOString(),
+ url: "https://kaneo.test/dashboard/workspace/ws_acme/project/p_kan/board",
+ } satisfies ProjectJson);
+ expect(old.archived).toBe(true);
+ });
+});
+
+describe("renderProjectList", () => {
+ it("renders key, name, tasks, progress and due date at 80 columns", () => {
+ const lines = renderProjectList(ui(80), {
+ projects: [old, kan, mob],
+ includeArchived: true,
+ now,
+ });
+ expect(lines).toEqual([
+ "",
+ " KAN Kaneo Web 7 tasks ▰▱▱▱▱▱▱▱▱▱ 14% ◷ Oct 20",
+ " MOB Mobile App no tasks",
+ " OLD Old Site · archived 1 task ▰▰▰▰▰▰▰▰▰▰ 100%",
+ "",
+ ]);
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(80);
+ });
+
+ it("drops the optional columns on a narrow terminal instead of wrapping", () => {
+ const lines = renderProjectList(ui(30), {
+ projects: [kan, mob],
+ includeArchived: false,
+ now,
+ });
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(30);
+ expect(lines[1]).toContain("KAN");
+ expect(lines[1]).not.toContain("◷");
+ });
+
+ it("explains an empty list", () => {
+ expect(
+ renderProjectList(ui(80), { projects: [], includeArchived: false, now }),
+ ).toEqual(["", " No active projects in this workspace.", ""]);
+ });
+});
diff --git a/packages/cli/src/projects/render-project-list.ts b/packages/cli/src/projects/render-project-list.ts
new file mode 100644
index 000000000..f3c6d9f56
--- /dev/null
+++ b/packages/cli/src/projects/render-project-list.ts
@@ -0,0 +1,107 @@
+import { type Cell, type Segment, text } from "../render/cell.js";
+import { renderTable } from "../render/table.js";
+import { dueSegments } from "../render/task-format.js";
+import type { Ui } from "../render/ui.js";
+import { progressSegments } from "./progress-bar.js";
+import type { ProjectJson } from "./project-json.js";
+
+export type ProjectListView = {
+ readonly projects: ReadonlyArray<ProjectJson>;
+ readonly includeArchived: boolean;
+ readonly now: Date;
+};
+
+function taskCount(count: number): string {
+ if (count === 0) return "no tasks";
+ return count === 1 ? "1 task" : `${count} tasks`;
+}
+
+export function renderProjectList(ui: Ui, view: ProjectListView): string[] {
+ const { theme, glyphs } = ui;
+ const quiet = (
+ project: ProjectJson,
+ segments: ReadonlyArray<Segment>,
+ ): Cell =>
+ project.archived
+ ? segments.map((segment) => ({ ...segment, style: theme.muted }))
+ : segments;
+ if (view.projects.length === 0) {
+ return [
+ "",
+ ` ${theme.muted(view.includeArchived ? "No projects in this workspace yet." : "No active projects in this workspace.")}`,
+ "",
+ ];
+ }
+ const ordered = [
+ ...view.projects.filter((project) => !project.archived),
+ ...view.projects.filter((project) => project.archived),
+ ];
+ return [
+ "",
+ ...renderTable(
+ ui,
+ ordered,
+ [
+ {
+ header: "Key",
+ cell: (project): Cell => [
+ text(
+ project.key,
+ project.archived ? theme.muted : theme.strong,
+ project.url,
+ ),
+ ],
+ },
+ {
+ header: "Name",
+ flex: true,
+ minWidth: 12,
+ cell: (project): Cell => [
+ text(
+ project.name,
+ project.archived ? theme.muted : undefined,
+ project.url,
+ ),
+ ...(project.archived
+ ? [text(` ${glyphs.separator} archived`, theme.muted)]
+ : []),
+ ],
+ },
+ {
+ header: "Tasks",
+ align: "right",
+ optional: true,
+ cell: (project): Cell => [
+ text(
+ taskCount(project.totalTasks),
+ project.archived || project.totalTasks === 0
+ ? theme.muted
+ : undefined,
+ ),
+ ],
+ },
+ {
+ header: "Progress",
+ optional: true,
+ cell: (project): Cell =>
+ project.totalTasks > 0
+ ? quiet(project, progressSegments(ui, project.completion))
+ : [],
+ },
+ {
+ header: "Due",
+ optional: true,
+ cell: (project): Cell =>
+ dueSegments(
+ ui,
+ project.dueDate,
+ project.archived || project.completion === 100,
+ view.now,
+ ),
+ },
+ ],
+ { width: ui.caps.columns, indent: 2, gap: 3 },
+ ),
+ "",
+ ];
+}
diff --git a/packages/cli/src/projects/render-project-view.test.ts b/packages/cli/src/projects/render-project-view.test.ts
new file mode 100644
index 000000000..da8c8a155
--- /dev/null
+++ b/packages/cli/src/projects/render-project-view.test.ts
@@ -0,0 +1,160 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { Column, Project } from "../api/schemas.js";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import { countByColumn, toProjectView } from "./project-view.js";
+import { renderProjectView } from "./render-project-view.js";
+
+const ui = (columns: number) =>
+ makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns,
+ });
+
+const project: Project = {
+ id: "p_kan",
+ workspaceId: "ws_acme",
+ slug: "kan",
+ name: "Kaneo Web",
+ icon: null,
+ description: "The web app.\n\nShip the board first.",
+ archivedAt: null,
+ position: 0,
+ lastTaskNumber: 7,
+};
+
+function column(
+ slug: string,
+ name: string,
+ position: number,
+ isFinal = false,
+): Column {
+ return {
+ id: `c_${slug}`,
+ projectId: "p_kan",
+ name,
+ slug,
+ position,
+ color: null,
+ isFinal,
+ };
+}
+
+const columns = [
+ column("done", "Done", 3, true),
+ column("to-do", "To Do", 0),
+ column("in-progress", "In Progress", 1),
+ column("in-review", "In Review", 2),
+];
+
+const statuses = [
+ "to-do",
+ "to-do",
+ "in-progress",
+ "in-progress",
+ "in-review",
+ "done",
+ "done",
+];
+const tasks = statuses.map((status) => ({ status }));
+
+describe("countByColumn", () => {
+ it("counts tasks per column in board order and ignores unknown statuses", () => {
+ expect(countByColumn(columns, [...tasks, { status: "planned" }])).toEqual([
+ { slug: "to-do", name: "To Do", isFinal: false, taskCount: 2 },
+ {
+ slug: "in-progress",
+ name: "In Progress",
+ isFinal: false,
+ taskCount: 2,
+ },
+ { slug: "in-review", name: "In Review", isFinal: false, taskCount: 1 },
+ { slug: "done", name: "Done", isFinal: true, taskCount: 2 },
+ ]);
+ });
+});
+
+describe("toProjectView", () => {
+ it("builds the JSON shape with the board link and total", () => {
+ const view = toProjectView(
+ project,
+ columns,
+ { tasks, total: 9 },
+ "https://kaneo.test",
+ );
+ expect(view).toMatchObject({
+ id: "p_kan",
+ key: "KAN",
+ name: "Kaneo Web",
+ description: "The web app.\n\nShip the board first.",
+ url: "https://kaneo.test/dashboard/workspace/ws_acme/project/p_kan/board",
+ totalTasks: 9,
+ });
+ expect(view.columns).toHaveLength(4);
+ });
+});
+
+describe("renderProjectView", () => {
+ const view = toProjectView(
+ project,
+ columns,
+ { tasks, total: 9 },
+ "https://kaneo.test",
+ );
+
+ it("shows the header, description, and one bar per column at 80 columns", () => {
+ const lines = renderProjectView(ui(80), { ...view, taskLimit: 1000 });
+ expect(lines).toEqual([
+ "",
+ " Kaneo Web · KAN · 9 tasks",
+ " https://kaneo.test/dashboard/workspace/ws_acme/project/p_kan/board",
+ "",
+ " The web app.",
+ "",
+ " Ship the board first.",
+ "",
+ " ● To Do 2 ▰▰▰▰▰▰▱▱▱▱▱▱▱▱▱▱▱▱▱▱",
+ " ● In Progress 2 ▰▰▰▰▰▰▱▱▱▱▱▱▱▱▱▱▱▱▱▱",
+ " ● In Review 1 ▰▰▰▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱",
+ " ● Done 2 ▰▰▰▰▰▰▱▱▱▱▱▱▱▱▱▱▱▱▱▱",
+ "",
+ " 2 more tasks are planned or archived.",
+ "",
+ ]);
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(80);
+ });
+
+ it("drops the bars when the terminal is too narrow", () => {
+ const lines = renderProjectView(ui(20), { ...view, taskLimit: 1000 });
+ expect(lines).toContain(" ● In Progress 2");
+ });
+
+ it("says when the counts stop at the task limit", () => {
+ const lines = renderProjectView(ui(80), {
+ ...view,
+ totalTasks: 1500,
+ taskLimit: 1000,
+ });
+ expect(lines).toContain(" Counts cover the first 1000 tasks.");
+ });
+
+ it("handles a project without columns", () => {
+ const lines = renderProjectView(ui(80), {
+ ...view,
+ description: null,
+ columns: [],
+ totalTasks: 0,
+ taskLimit: 1000,
+ });
+ expect(lines.slice(1)).toEqual([
+ " Kaneo Web · KAN · 0 tasks",
+ " https://kaneo.test/dashboard/workspace/ws_acme/project/p_kan/board",
+ "",
+ " This project has no columns yet.",
+ "",
+ ]);
+ });
+});
diff --git a/packages/cli/src/projects/render-project-view.ts b/packages/cli/src/projects/render-project-view.ts
new file mode 100644
index 000000000..42c520899
--- /dev/null
+++ b/packages/cli/src/projects/render-project-view.ts
@@ -0,0 +1,113 @@
+import { type Cell, renderCell, text } from "../render/cell.js";
+import { type Column, renderTable } from "../render/table.js";
+import { statusDot, statusStyle } from "../render/task-format.js";
+import type { Ui } from "../render/ui.js";
+import { stringWidth, truncate } from "../render/width.js";
+import { descriptionPreview } from "./description-preview.js";
+import { barSegments } from "./progress-bar.js";
+import type { ColumnCountJson, ProjectViewJson } from "./project-view.js";
+
+export type ProjectViewScreen = ProjectViewJson & {
+ readonly taskLimit: number;
+};
+
+const MAX_BAR = 20;
+
+function taskCount(count: number): string {
+ return count === 1 ? "1 task" : `${count} tasks`;
+}
+
+function columnLines(
+ ui: Ui,
+ columns: ReadonlyArray<ColumnCountJson>,
+): string[] {
+ const { theme } = ui;
+ const counted = columns.reduce((sum, column) => sum + column.taskCount, 0);
+ const nameWidth =
+ Math.max(...columns.map((column) => stringWidth(column.name))) + 2;
+ const countWidth = Math.max(
+ ...columns.map((column) => String(column.taskCount).length),
+ );
+ const barWidth = Math.min(
+ MAX_BAR,
+ ui.caps.columns - 2 - nameWidth - countWidth - 4,
+ );
+ const table: Array<Column<ColumnCountJson>> = [
+ {
+ header: "Column",
+ flex: true,
+ minWidth: 6,
+ cell: (column): Cell => [
+ statusDot(ui, column.slug, column.isFinal),
+ text(" "),
+ text(column.name),
+ ],
+ },
+ {
+ header: "Tasks",
+ align: "right",
+ cell: (column): Cell => [
+ text(
+ String(column.taskCount),
+ column.taskCount === 0 ? theme.muted : undefined,
+ ),
+ ],
+ },
+ ];
+ if (barWidth >= 4) {
+ table.push({
+ header: "Share",
+ optional: true,
+ cell: (column): Cell =>
+ barSegments(
+ ui,
+ counted > 0 ? column.taskCount / counted : 0,
+ barWidth,
+ statusStyle(ui, column.slug, column.isFinal),
+ ),
+ });
+ }
+ return renderTable(ui, columns, table, { width: ui.caps.columns, indent: 2 });
+}
+
+export function renderProjectView(ui: Ui, view: ProjectViewScreen): string[] {
+ const { theme, glyphs } = ui;
+ const lines = [
+ "",
+ ` ${renderCell([text(view.name, theme.strong, view.url)], ui)} ${theme.muted(`${glyphs.separator} ${view.key} ${glyphs.separator} ${taskCount(view.totalTasks)}`)}`,
+ ` ${renderCell([text(view.url, theme.muted, view.url)], ui)}`,
+ "",
+ ];
+
+ const preview = descriptionPreview(view.description);
+ if (preview.lines.length > 0) {
+ const width = Math.max(10, ui.caps.columns - 2);
+ for (const line of preview.lines) {
+ lines.push(line ? ` ${truncate(line, width, glyphs.ellipsis)}` : "");
+ }
+ if (preview.more) lines.push(` ${theme.muted(glyphs.ellipsis)}`);
+ lines.push("");
+ }
+
+ if (view.columns.length === 0) {
+ lines.push(` ${theme.muted("This project has no columns yet.")}`, "");
+ return lines;
+ }
+
+ lines.push(...columnLines(ui, view.columns), "");
+ const counted = view.columns.reduce(
+ (sum, column) => sum + column.taskCount,
+ 0,
+ );
+ const hidden = view.totalTasks - counted;
+ if (view.totalTasks > view.taskLimit) {
+ lines.push(
+ ` ${theme.muted(`Counts cover the first ${view.taskLimit} tasks.`)}`,
+ "",
+ );
+ } else if (hidden > 0) {
+ const more = hidden === 1 ? "1 more task is" : `${hidden} more tasks are`;
+ lines.push(` ${theme.muted(`${more} planned or archived.`)}`, "");
+ }
+ return lines;
+}
diff --git a/packages/cli/src/prompts/confirm-destructive.ts b/packages/cli/src/prompts/confirm-destructive.ts
new file mode 100644
index 000000000..85eedb934
--- /dev/null
+++ b/packages/cli/src/prompts/confirm-destructive.ts
@@ -0,0 +1,21 @@
+import { Effect } from "effect";
+import { Cancelled, InvalidArgument } from "../errors/errors.js";
+import { Output } from "../output/output.js";
+import { confirm } from "./confirm.js";
+
+export const confirmDestructive = Effect.fnUntraced(function* (options: {
+ readonly yes: boolean;
+ readonly action: string;
+ readonly question: string;
+}) {
+ if (options.yes) return;
+ const output = yield* Output;
+ if (!output.interactive) {
+ return yield* new InvalidArgument({
+ message: `${options.action} needs confirmation.`,
+ hint: "Pass --yes to skip the prompt.",
+ });
+ }
+ const confirmed = yield* confirm(options.question);
+ if (!confirmed) return yield* new Cancelled();
+});
diff --git a/packages/cli/src/prompts/confirm.ts b/packages/cli/src/prompts/confirm.ts
new file mode 100644
index 000000000..5c420a04c
--- /dev/null
+++ b/packages/cli/src/prompts/confirm.ts
@@ -0,0 +1,12 @@
+import { Effect } from "effect";
+import { Prompt } from "effect/cli";
+import { Cancelled } from "../errors/errors.js";
+import { Output } from "../output/output.js";
+import { promptTheme } from "./prompt-theme.js";
+
+export const confirm = Effect.fnUntraced(function* (message: string) {
+ const output = yield* Output;
+ return yield* Prompt.run(
+ Prompt.Confirm({ message, initial: false, theme: promptTheme(output.ui) }),
+ ).pipe(Effect.catchTag("QuitError", () => Effect.fail(new Cancelled())));
+});
diff --git a/packages/cli/src/prompts/pick.ts b/packages/cli/src/prompts/pick.ts
new file mode 100644
index 000000000..742e98997
--- /dev/null
+++ b/packages/cli/src/prompts/pick.ts
@@ -0,0 +1,32 @@
+import { Effect } from "effect";
+import { Prompt } from "effect/cli";
+import { Cancelled } from "../errors/errors.js";
+import { Output } from "../output/output.js";
+import { promptTheme } from "./prompt-theme.js";
+
+export type Choice<A> = {
+ readonly title: string;
+ readonly value: A;
+ readonly description?: string;
+};
+
+export const pick = Effect.fnUntraced(function* <A>(
+ message: string,
+ choices: ReadonlyArray<Choice<A>>,
+) {
+ const output = yield* Output;
+ return yield* Prompt.run(
+ Prompt.AutoComplete({
+ message,
+ choices: choices.map((choice) => ({
+ title: choice.title,
+ value: choice.value,
+ description: choice.description,
+ })),
+ filterPlaceholder: "Type to search",
+ emptyMessage: "No matches",
+ maxPerPage: 8,
+ theme: promptTheme(output.ui),
+ }),
+ ).pipe(Effect.catchTag("QuitError", () => Effect.fail(new Cancelled())));
+});
diff --git a/packages/cli/src/prompts/prompt-theme.ts b/packages/cli/src/prompts/prompt-theme.ts
new file mode 100644
index 000000000..7303e37b5
--- /dev/null
+++ b/packages/cli/src/prompts/prompt-theme.ts
@@ -0,0 +1,18 @@
+import type { Prompt } from "effect/cli";
+import { themeCodes } from "../render/theme.js";
+import type { Ui } from "../render/ui.js";
+
+export function promptTheme(ui: Ui): Partial<Prompt.Theme> {
+ const codes = themeCodes(ui.caps.color);
+ return {
+ prefix: ui.glyphs.diamond,
+ pointer: ui.caps.unicode ? "❯" : ">",
+ tick: ui.glyphs.tick,
+ ellipsis: ui.glyphs.ellipsis,
+ primaryColor: codes.bold,
+ mutedColor: codes.muted,
+ successColor: codes.success,
+ errorColor: codes.danger,
+ submittedColor: "",
+ };
+}
diff --git a/packages/cli/src/relations/group-relations.test.ts b/packages/cli/src/relations/group-relations.test.ts
new file mode 100644
index 000000000..fa9847a75
--- /dev/null
+++ b/packages/cli/src/relations/group-relations.test.ts
@@ -0,0 +1,137 @@
+import { describe, expect, it } from "vite-plus/test";
+import type {
+ RelatedTask,
+ TaskRelationWithTasks,
+} from "../api/task-relations.js";
+import { groupRelations, relationsBetween } from "./group-relations.js";
+
+const task = (id: string, number: number, done = false): RelatedTask => ({
+ id,
+ title: `Task ${id}`,
+ status: done ? "done" : "to-do",
+ isCompleted: done,
+ number,
+ projectId: "p1",
+});
+
+const tasks = {
+ me: task("me", 3),
+ parent: task("parent", 1),
+ child1: task("child1", 10),
+ child2: task("child2", 4, true),
+ blocker: task("blocker", 7),
+ blocked: task("blocked", 8),
+ related: task("related", 9),
+};
+
+let next = 0;
+const relation = (
+ source: RelatedTask,
+ target: RelatedTask,
+ relationType: string,
+): TaskRelationWithTasks => ({
+ id: `r${++next}`,
+ sourceTaskId: source.id,
+ targetTaskId: target.id,
+ relationType,
+ sourceTask: source,
+ targetTask: target,
+});
+
+const context = {
+ projectSlugs: new Map([["p1", "kan"]]),
+ workspaceId: "w1",
+ webUrl: "https://kaneo.test",
+};
+
+const all = [
+ relation(tasks.related, tasks.me, "related"),
+ relation(tasks.me, tasks.child1, "subtask"),
+ relation(tasks.blocker, tasks.me, "blocks"),
+ relation(tasks.parent, tasks.me, "subtask"),
+ relation(tasks.me, tasks.blocked, "blocks"),
+ relation(tasks.me, tasks.child2, "subtask"),
+];
+
+describe("groupRelations", () => {
+ it("splits the parent, subtasks and other relations", () => {
+ const grouped = groupRelations(all, "me", context);
+ expect(grouped.parent).toEqual({
+ id: "parent",
+ ticketId: "KAN-1",
+ title: "Task parent",
+ status: "to-do",
+ completed: false,
+ url: "https://kaneo.test/dashboard/workspace/w1/project/p1/task/parent",
+ });
+ expect(grouped.subtasks.map((item) => item.ticketId)).toEqual([
+ "KAN-4",
+ "KAN-10",
+ ]);
+ expect(
+ grouped.relations.map((item) => [
+ item.type,
+ item.direction,
+ item.task.ticketId,
+ ]),
+ ).toEqual([
+ ["blocks", "outgoing", "KAN-8"],
+ ["blocked-by", "incoming", "KAN-7"],
+ ["relates-to", "incoming", "KAN-9"],
+ ]);
+ });
+
+ it("keeps extra parents as subtask-of relations", () => {
+ const second = task("second", 2);
+ const grouped = groupRelations(
+ [
+ relation(tasks.parent, tasks.me, "subtask"),
+ relation(second, tasks.me, "subtask"),
+ ],
+ "me",
+ context,
+ );
+ expect(grouped.parent?.id).toBe("parent");
+ expect(grouped.relations).toEqual([
+ expect.objectContaining({ type: "subtask-of", direction: "incoming" }),
+ ]);
+ });
+
+ it("leaves the ticket id null for unknown projects", () => {
+ const grouped = groupRelations(
+ [relation(tasks.me, { ...tasks.related, projectId: "p2" }, "related")],
+ "me",
+ context,
+ );
+ expect(grouped.relations[0]?.task.ticketId).toBeNull();
+ });
+
+ it("is empty without relations", () => {
+ expect(groupRelations([], "me", context)).toEqual({
+ parent: null,
+ subtasks: [],
+ relations: [],
+ });
+ });
+});
+
+describe("relationsBetween", () => {
+ const pair = [
+ relation(tasks.me, tasks.blocked, "blocks"),
+ relation(tasks.blocked, tasks.me, "related"),
+ relation(tasks.me, tasks.related, "related"),
+ ];
+
+ it("finds every relation between two tasks in either direction", () => {
+ expect(relationsBetween(pair, "me", "blocked", undefined)).toHaveLength(2);
+ });
+
+ it("narrows to one type from the first task's side", () => {
+ expect(
+ relationsBetween(pair, "me", "blocked", "blocks").map(
+ (item) => item.relationType,
+ ),
+ ).toEqual(["blocks"]);
+ expect(relationsBetween(pair, "me", "blocked", "blocked-by")).toEqual([]);
+ });
+});
diff --git a/packages/cli/src/relations/group-relations.ts b/packages/cli/src/relations/group-relations.ts
new file mode 100644
index 000000000..4fc2eba2e
--- /dev/null
+++ b/packages/cli/src/relations/group-relations.ts
@@ -0,0 +1,120 @@
+import type {
+ RelatedTask,
+ TaskRelationWithTasks,
+} from "../api/task-relations.js";
+import { taskUrl } from "../render/links.js";
+import { ticketId } from "../render/task-format.js";
+import {
+ perspectiveOf,
+ type RelationDirection,
+ relationOrder,
+} from "./relation-types.js";
+
+export type RelatedTaskJson = {
+ readonly id: string;
+ readonly ticketId: string | null;
+ readonly title: string;
+ readonly status: string;
+ readonly completed: boolean;
+ readonly url: string;
+};
+
+export type RelationJson = {
+ readonly type: string;
+ readonly direction: RelationDirection;
+ readonly task: RelatedTaskJson;
+};
+
+export type RelationsJson = {
+ readonly parent: RelatedTaskJson | null;
+ readonly subtasks: ReadonlyArray<RelatedTaskJson>;
+ readonly relations: ReadonlyArray<RelationJson>;
+};
+
+export type TaskContext = {
+ readonly projectSlugs: ReadonlyMap<string, string>;
+ readonly workspaceId: string;
+ readonly webUrl: string;
+};
+
+export function relatedTaskJson(
+ task: RelatedTask,
+ context: TaskContext,
+): RelatedTaskJson {
+ const slug = context.projectSlugs.get(task.projectId);
+ return {
+ id: task.id,
+ ticketId: slug ? ticketId(slug, task.number) : null,
+ title: task.title,
+ status: task.status,
+ completed: task.isCompleted,
+ url: taskUrl(context.webUrl, {
+ workspaceId: context.workspaceId,
+ projectId: task.projectId,
+ id: task.id,
+ }),
+ };
+}
+
+function byTicket(a: RelatedTaskJson, b: RelatedTaskJson): number {
+ return (a.ticketId ?? a.title).localeCompare(b.ticketId ?? b.title, "en", {
+ numeric: true,
+ });
+}
+
+export function groupRelations(
+ relations: ReadonlyArray<TaskRelationWithTasks>,
+ taskId: string,
+ context: TaskContext,
+): RelationsJson {
+ const parents: RelatedTaskJson[] = [];
+ const subtasks: RelatedTaskJson[] = [];
+ const others: RelationJson[] = [];
+ for (const relation of relations) {
+ const outgoing = relation.sourceTaskId === taskId;
+ const linked = outgoing ? relation.targetTask : relation.sourceTask;
+ if (!linked || linked.id === taskId) continue;
+ const task = relatedTaskJson(linked, context);
+ const perspective = perspectiveOf(relation, taskId);
+ if (perspective.type === "parent-of") subtasks.push(task);
+ else if (perspective.type === "subtask-of") parents.push(task);
+ else others.push({ ...perspective, task });
+ }
+ parents.sort(byTicket);
+ const [parent = null, ...extraParents] = parents;
+ const relationsJson = [
+ ...extraParents.map((task): RelationJson => ({
+ type: "subtask-of",
+ direction: "incoming",
+ task,
+ })),
+ ...others,
+ ].sort(
+ (a, b) =>
+ relationOrder(a.type) - relationOrder(b.type) ||
+ a.type.localeCompare(b.type) ||
+ byTicket(a.task, b.task),
+ );
+ return {
+ parent,
+ subtasks: subtasks.sort(byTicket),
+ relations: relationsJson,
+ };
+}
+
+export function relationsBetween(
+ relations: ReadonlyArray<TaskRelationWithTasks>,
+ taskId: string,
+ otherId: string,
+ type: string | undefined,
+): TaskRelationWithTasks[] {
+ return relations.filter((relation) => {
+ const linked =
+ (relation.sourceTaskId === taskId && relation.targetTaskId === otherId) ||
+ (relation.sourceTaskId === otherId && relation.targetTaskId === taskId);
+ return (
+ linked &&
+ (type === undefined || perspectiveOf(relation, taskId).type === type)
+ );
+ });
+}
diff --git a/packages/cli/src/relations/link-subtask.test.ts b/packages/cli/src/relations/link-subtask.test.ts
new file mode 100644
index 000000000..8f6f330b6
--- /dev/null
+++ b/packages/cli/src/relations/link-subtask.test.ts
@@ -0,0 +1,147 @@
+import { Effect, Layer, Option, Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { KaneoApiLayer } from "../api/kaneo-api.js";
+import type { ResolvedTask } from "../tasks/resolve-task.js";
+import {
+ captureOutput,
+ fakeHttpClient,
+ json,
+ memoryConfigStore,
+ type RecordedRequest,
+ type Responder,
+ testSession,
+} from "../testing/test-layers.js";
+import { linkToParent, projectOrParent } from "./link-subtask.js";
+
+const parent: ResolvedTask = {
+ task: {
+ id: "parent",
+ projectId: "p1",
+ number: 1,
+ title: "Auth overhaul",
+ description: null,
+ status: "to-do",
+ priority: "no-priority",
+ startDate: null,
+ dueDate: null,
+ createdAt: "2026-10-08T10:00:00.000Z",
+ assigneeId: null,
+ assigneeName: null,
+ },
+ workspaceId: "ws_1",
+ project: {
+ id: "p1",
+ workspaceId: "ws_1",
+ slug: "kan",
+ name: "Kaneo Web",
+ icon: null,
+ description: null,
+ archivedAt: null,
+ position: 0,
+ lastTaskNumber: 9,
+ },
+ columns: [],
+ ticketId: "KAN-1",
+ url: "https://kaneo.test/task/parent",
+};
+
+function run(respond: Responder) {
+ const recorded: RecordedRequest[] = [];
+ const api = KaneoApiLayer.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ fakeHttpClient(respond, recorded),
+ testSession(),
+ memoryConfigStore().layer,
+ ),
+ ),
+ );
+ const effect = linkToParent(parent, { id: "child", label: "KAN-9" }).pipe(
+ Effect.provide(Layer.mergeAll(api, captureOutput().layer)),
+ );
+ return { recorded, result: Effect.runPromise(Effect.result(effect)) };
+}
+
+describe("linkToParent", () => {
+ it("links the new task as a subtask of the parent", async () => {
+ const { recorded, result } = run(() =>
+ json({
+ id: "r1",
+ sourceTaskId: "parent",
+ targetTaskId: "child",
+ relationType: "subtask",
+ }),
+ );
+ expect(await result).toEqual(
+ Result.succeed({
+ id: "parent",
+ ticketId: "KAN-1",
+ title: "Auth overhaul",
+ url: "https://kaneo.test/task/parent",
+ }),
+ );
+ expect(recorded[0]).toMatchObject({
+ method: "POST",
+ url: "https://kaneo.test/api/task-relation",
+ body: {
+ sourceTaskId: "parent",
+ targetTaskId: "child",
+ relationType: "subtask",
+ },
+ });
+ });
+
+ it("says the task was created but not linked when the link fails", async () => {
+ const { result } = run(() => json({ message: "Missing permission" }, 403));
+ const outcome = await result;
+ expect(Result.isFailure(outcome)).toBe(true);
+ if (Result.isFailure(outcome)) {
+ expect(outcome.failure).toMatchObject({
+ _tag: "InvalidArgument",
+ message:
+ "Created KAN-9, but could not make it a subtask of KAN-1: Missing permission",
+ hint: "Link it with kaneo task relation add KAN-9 subtask-of KAN-1",
+ });
+ }
+ });
+
+ it("does nothing without a parent", async () => {
+ const effect = linkToParent(undefined, { id: "child", label: "KAN-9" });
+ expect(
+ await Effect.runPromise(
+ effect.pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ KaneoApiLayer.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ fakeHttpClient(() => json({})),
+ testSession(),
+ memoryConfigStore().layer,
+ ),
+ ),
+ ),
+ captureOutput().layer,
+ ),
+ ),
+ ),
+ ),
+ ).toBeNull();
+ });
+});
+
+describe("projectOrParent", () => {
+ it("prefers the -p flag", () => {
+ expect(projectOrParent(Option.some("MOB"), parent)).toEqual(
+ Option.some("MOB"),
+ );
+ });
+
+ it("uses the parent's project without -p", () => {
+ expect(projectOrParent(Option.none(), parent)).toEqual(Option.some("p1"));
+ });
+
+ it("leaves the project open without a parent", () => {
+ expect(projectOrParent(Option.none(), undefined)).toEqual(Option.none());
+ });
+});
diff --git a/packages/cli/src/relations/link-subtask.ts b/packages/cli/src/relations/link-subtask.ts
new file mode 100644
index 000000000..9551c3b30
--- /dev/null
+++ b/packages/cli/src/relations/link-subtask.ts
@@ -0,0 +1,55 @@
+import { Effect, Option } from "effect";
+import { createTaskRelation } from "../api/task-relations.js";
+import { describeError } from "../errors/describe.js";
+import { InvalidArgument } from "../errors/errors.js";
+import { withSpinner } from "../output/spinner.js";
+import { type ResolvedTask, resolveTask } from "../tasks/resolve-task.js";
+import { toApiRelation } from "./relation-types.js";
+import { type TaskRef, taskLabel, taskRef } from "./task-ref.js";
+
+export const resolveParent = Effect.fn("relations.resolveParent")(function* (
+ reference: Option.Option<string>,
+ workspaceId: string,
+) {
+ if (Option.isNone(reference)) return undefined;
+ const parent = yield* withSpinner(`Loading ${reference.value}`)(
+ resolveTask(reference.value),
+ );
+ if (parent.workspaceId !== workspaceId) {
+ return yield* new InvalidArgument({
+ message: `${taskLabel(taskRef(parent))} is in another workspace.`,
+ hint: "A subtask must be in the same workspace as its parent. Pass -w with the parent's workspace.",
+ });
+ }
+ return parent;
+});
+
+export function projectOrParent(
+ project: Option.Option<string>,
+ parent: ResolvedTask | undefined,
+): Option.Option<string> {
+ return Option.isSome(project) || !parent
+ ? project
+ : Option.some(parent.project.id);
+}
+
+export const linkToParent = Effect.fn("relations.linkToParent")(function* (
+ parent: ResolvedTask | undefined,
+ child: { readonly id: string; readonly label: string },
+) {
+ if (!parent) return null;
+ const ref: TaskRef = taskRef(parent);
+ const parentLabel = taskLabel(ref);
+ yield* withSpinner(`Linking to ${parentLabel}`)(
+ createTaskRelation(toApiRelation("subtask-of", child.id, parent.task.id)),
+ ).pipe(
+ Effect.mapError(
+ (error) =>
+ new InvalidArgument({
+ message: `Created ${child.label}, but could not make it a subtask of ${parentLabel}: ${describeError(error).message}`,
+ hint: `Link it with kaneo task relation add ${child.label} subtask-of ${parentLabel}`,
+ }),
+ ),
+ );
+ return ref;
+});
diff --git a/packages/cli/src/relations/relation-types.test.ts b/packages/cli/src/relations/relation-types.test.ts
new file mode 100644
index 000000000..f5d86be74
--- /dev/null
+++ b/packages/cli/src/relations/relation-types.test.ts
@@ -0,0 +1,120 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import {
+ notLinkedPhrase,
+ parseRelationType,
+ perspectiveOf,
+ relationHeading,
+ toApiRelation,
+ unlinkedPhrase,
+} from "./relation-types.js";
+
+describe("parseRelationType", () => {
+ it("accepts the friendly words in any case or spacing", () => {
+ expect(Result.getOrThrow(parseRelationType("blocks"))).toBe("blocks");
+ expect(Result.getOrThrow(parseRelationType("Blocked by"))).toBe(
+ "blocked-by",
+ );
+ expect(Result.getOrThrow(parseRelationType("subtask_of"))).toBe(
+ "subtask-of",
+ );
+ expect(Result.getOrThrow(parseRelationType("related"))).toBe("relates-to");
+ expect(Result.getOrThrow(parseRelationType("child-of"))).toBe("subtask-of");
+ });
+
+ it("lists the valid types for an unknown word", () => {
+ const result = parseRelationType("follows");
+ expect(Result.isFailure(result)).toBe(true);
+ if (Result.isFailure(result)) {
+ expect(result.failure.message).toBe('"follows" is not a relation type.');
+ expect(result.failure.hint).toBe(
+ "Use one of: subtask-of, parent-of, blocks, blocked-by, relates-to.",
+ );
+ }
+ });
+
+ it("explains that duplicates is not supported", () => {
+ const result = parseRelationType("duplicates");
+ expect(Result.isFailure(result)).toBe(true);
+ if (Result.isFailure(result)) {
+ expect(result.failure.message).toBe(
+ 'Kaneo has no "duplicates" relation.',
+ );
+ expect(result.failure.hint).toContain("relates-to is the closest match");
+ }
+ });
+});
+
+describe("toApiRelation", () => {
+ it("makes the parent the source of a subtask relation", () => {
+ expect(toApiRelation("subtask-of", "child", "parent")).toEqual({
+ sourceTaskId: "parent",
+ targetTaskId: "child",
+ relationType: "subtask",
+ });
+ expect(toApiRelation("parent-of", "parent", "child")).toEqual({
+ sourceTaskId: "parent",
+ targetTaskId: "child",
+ relationType: "subtask",
+ });
+ });
+
+ it("makes the blocker the source of a blocks relation", () => {
+ expect(toApiRelation("blocks", "a", "b")).toEqual({
+ sourceTaskId: "a",
+ targetTaskId: "b",
+ relationType: "blocks",
+ });
+ expect(toApiRelation("blocked-by", "a", "b")).toEqual({
+ sourceTaskId: "b",
+ targetTaskId: "a",
+ relationType: "blocks",
+ });
+ });
+
+ it("maps relates-to to related", () => {
+ expect(toApiRelation("relates-to", "a", "b").relationType).toBe("related");
+ });
+});
+
+describe("perspectiveOf", () => {
+ it("reads every API type from either side", () => {
+ const relation = (relationType: string) => ({
+ sourceTaskId: "a",
+ relationType,
+ });
+ expect(perspectiveOf(relation("subtask"), "a")).toEqual({
+ type: "parent-of",
+ direction: "outgoing",
+ });
+ expect(perspectiveOf(relation("subtask"), "b")).toEqual({
+ type: "subtask-of",
+ direction: "incoming",
+ });
+ expect(perspectiveOf(relation("blocks"), "a").type).toBe("blocks");
+ expect(perspectiveOf(relation("blocks"), "b").type).toBe("blocked-by");
+ expect(perspectiveOf(relation("related"), "b")).toEqual({
+ type: "relates-to",
+ direction: "incoming",
+ });
+ expect(perspectiveOf(relation("duplicates"), "a").type).toBe("duplicates");
+ });
+});
+
+describe("labels", () => {
+ it("names groups and unknown types", () => {
+ expect(relationHeading("blocked-by")).toBe("Blocked by");
+ expect(relationHeading("relates-to")).toBe("Related");
+ expect(relationHeading("duplicates")).toBe("Duplicates");
+ });
+
+ it("has no unlink phrase for unknown types", () => {
+ expect(unlinkedPhrase("blocks")).toBe("no longer blocks");
+ expect(unlinkedPhrase("duplicates")).toBeNull();
+ });
+
+ it("phrases a missing relation", () => {
+ expect(notLinkedPhrase("blocks")).toBe("does not block");
+ expect(notLinkedPhrase("subtask-of")).toBe("is not a subtask of");
+ });
+});
diff --git a/packages/cli/src/relations/relation-types.ts b/packages/cli/src/relations/relation-types.ts
new file mode 100644
index 000000000..75f19026c
--- /dev/null
+++ b/packages/cli/src/relations/relation-types.ts
@@ -0,0 +1,189 @@
+import { Result } from "effect";
+import type { NewTaskRelation } from "../api/task-relations.js";
+import { InvalidArgument } from "../errors/errors.js";
+
+export const RELATION_TYPES = [
+ "subtask-of",
+ "parent-of",
+ "blocks",
+ "blocked-by",
+ "relates-to",
+] as const;
+export type RelationType = (typeof RELATION_TYPES)[number];
+
+export type RelationDirection = "outgoing" | "incoming";
+
+const ALIASES: Readonly<Record<string, RelationType>> = {
+ "subtask-of": "subtask-of",
+ "child-of": "subtask-of",
+ "parent-of": "parent-of",
+ blocks: "blocks",
+ "blocked-by": "blocked-by",
+ "relates-to": "relates-to",
+ "related-to": "relates-to",
+ related: "relates-to",
+};
+
+const UNSUPPORTED = new Set(["duplicates", "duplicate-of", "duplicated-by"]);
+
+const TYPE_HINT = `Use one of: ${RELATION_TYPES.join(", ")}.`;
+
+export function normalizeRelationWord(input: string): string {
+ return input
+ .trim()
+ .toLowerCase()
+ .replace(/[\s_]+/gu, "-");
+}
+
+export function parseRelationType(
+ input: string,
+): Result.Result<RelationType, InvalidArgument> {
+ const word = normalizeRelationWord(input);
+ const type = ALIASES[word];
+ if (type) return Result.succeed(type);
+ return Result.fail(
+ new InvalidArgument({
+ message: UNSUPPORTED.has(word)
+ ? `Kaneo has no "${input.trim()}" relation.`
+ : `"${input.trim()}" is not a relation type.`,
+ hint: UNSUPPORTED.has(word)
+ ? `${TYPE_HINT} relates-to is the closest match.`
+ : TYPE_HINT,
+ }),
+ );
+}
+
+export function toApiRelation(
+ type: RelationType,
+ taskId: string,
+ otherId: string,
+): NewTaskRelation {
+ switch (type) {
+ case "subtask-of":
+ return {
+ sourceTaskId: otherId,
+ targetTaskId: taskId,
+ relationType: "subtask",
+ };
+ case "parent-of":
+ return {
+ sourceTaskId: taskId,
+ targetTaskId: otherId,
+ relationType: "subtask",
+ };
+ case "blocks":
+ return {
+ sourceTaskId: taskId,
+ targetTaskId: otherId,
+ relationType: "blocks",
+ };
+ case "blocked-by":
+ return {
+ sourceTaskId: otherId,
+ targetTaskId: taskId,
+ relationType: "blocks",
+ };
+ case "relates-to":
+ return {
+ sourceTaskId: taskId,
+ targetTaskId: otherId,
+ relationType: "related",
+ };
+ }
+}
+
+export type Perspective = {
+ readonly type: string;
+ readonly direction: RelationDirection;
+};
+
+export function perspectiveOf(
+ relation: {
+ readonly sourceTaskId: string;
+ readonly relationType: string;
+ },
+ taskId: string,
+): Perspective {
+ const outgoing = relation.sourceTaskId === taskId;
+ const direction: RelationDirection = outgoing ? "outgoing" : "incoming";
+ switch (relation.relationType) {
+ case "subtask":
+ return { type: outgoing ? "parent-of" : "subtask-of", direction };
+ case "blocks":
+ return { type: outgoing ? "blocks" : "blocked-by", direction };
+ case "related":
+ return { type: "relates-to", direction };
+ default:
+ return { type: relation.relationType, direction };
+ }
+}
+
+type Phrases = {
+ readonly now: string;
+ readonly noLonger: string;
+ readonly not: string;
+};
+
+const PHRASES: Readonly<Record<RelationType, Phrases>> = {
+ "subtask-of": {
+ now: "is now a subtask of",
+ noLonger: "is no longer a subtask of",
+ not: "is not a subtask of",
+ },
+ "parent-of": {
+ now: "is now the parent of",
+ noLonger: "is no longer the parent of",
+ not: "is not the parent of",
+ },
+ blocks: {
+ now: "now blocks",
+ noLonger: "no longer blocks",
+ not: "does not block",
+ },
+ "blocked-by": {
+ now: "is now blocked by",
+ noLonger: "is no longer blocked by",
+ not: "is not blocked by",
+ },
+ "relates-to": {
+ now: "now relates to",
+ noLonger: "no longer relates to",
+ not: "is not related to",
+ },
+};
+
+export function isRelationType(type: string): type is RelationType {
+ return (RELATION_TYPES as ReadonlyArray<string>).includes(type);
+}
+
+export function linkedPhrase(type: RelationType): string {
+ return PHRASES[type].now;
+}
+
+export function notLinkedPhrase(type: RelationType): string {
+ return PHRASES[type].not;
+}
+
+export function unlinkedPhrase(type: string): string | null {
+ return isRelationType(type) ? PHRASES[type].noLonger : null;
+}
+
+const HEADINGS: Readonly<Record<string, string>> = {
+ "subtask-of": "Also a subtask of",
+ "parent-of": "Parent of",
+ blocks: "Blocks",
+ "blocked-by": "Blocked by",
+ "relates-to": "Related",
+};
+
+export function relationHeading(type: string): string {
+ const known = HEADINGS[type];
+ if (known) return known;
+ const words = type.replace(/[-_]+/gu, " ").trim();
+ return words.charAt(0).toUpperCase() + words.slice(1);
+}
+
+export function relationOrder(type: string): number {
+ const index = (RELATION_TYPES as ReadonlyArray<string>).indexOf(type);
+ return index === -1 ? RELATION_TYPES.length : index;
+}
diff --git a/packages/cli/src/relations/render-relation-change.test.ts b/packages/cli/src/relations/render-relation-change.test.ts
new file mode 100644
index 000000000..7a8bb0dfb
--- /dev/null
+++ b/packages/cli/src/relations/render-relation-change.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import {
+ renderRelationLinked,
+ renderRelationsRemoved,
+} from "./render-relation-change.js";
+
+const ui = (columns: number) =>
+ makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns,
+ });
+
+const task = { label: "KAN-3", url: "https://kaneo.test/3" };
+const other = { label: "KAN-4", url: "https://kaneo.test/4" };
+
+describe("renderRelationLinked", () => {
+ it("reads as a sentence from the first task", () => {
+ expect(
+ renderRelationLinked(ui(80), {
+ type: "blocked-by",
+ task,
+ other: { ...other, title: "Session timeout" },
+ }),
+ ).toEqual(["", " ✓ KAN-3 is now blocked by KAN-4 · Session timeout", ""]);
+ });
+
+ it("truncates the other title to the terminal width", () => {
+ const [, line = ""] = renderRelationLinked(ui(80), {
+ type: "subtask-of",
+ task,
+ other: { ...other, title: "B".repeat(100) },
+ });
+ expect(stringWidth(line)).toBe(80);
+ expect(line.endsWith("…")).toBe(true);
+ });
+});
+
+describe("renderRelationsRemoved", () => {
+ it("describes a single removed relation", () => {
+ expect(
+ renderRelationsRemoved(ui(80), { types: ["parent-of"], task, other })[1],
+ ).toBe(" ✓ KAN-3 is no longer the parent of KAN-4");
+ });
+
+ it("counts several removed relations", () => {
+ expect(
+ renderRelationsRemoved(ui(80), {
+ types: ["blocks", "relates-to"],
+ task,
+ other,
+ })[1],
+ ).toBe(" ✓ Removed 2 relations between KAN-3 and KAN-4");
+ });
+
+ it("falls back for unknown types", () => {
+ expect(
+ renderRelationsRemoved(ui(80), { types: ["duplicates"], task, other })[1],
+ ).toBe(" ✓ Unlinked KAN-3 and KAN-4");
+ });
+});
diff --git a/packages/cli/src/relations/render-relation-change.ts b/packages/cli/src/relations/render-relation-change.ts
new file mode 100644
index 000000000..d5da91516
--- /dev/null
+++ b/packages/cli/src/relations/render-relation-change.ts
@@ -0,0 +1,58 @@
+import { renderCell, text } from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+import { stringWidth, truncate } from "../render/width.js";
+import {
+ linkedPhrase,
+ type RelationType,
+ unlinkedPhrase,
+} from "./relation-types.js";
+
+export type TaskLabel = {
+ readonly label: string;
+ readonly url: string;
+};
+
+function reference(ui: Ui, task: TaskLabel): string {
+ return renderCell([text(task.label, ui.theme.strong, task.url)], ui);
+}
+
+export function renderRelationLinked(
+ ui: Ui,
+ change: {
+ readonly type: RelationType;
+ readonly task: TaskLabel;
+ readonly other: TaskLabel & { readonly title: string };
+ },
+): string[] {
+ const { theme, glyphs } = ui;
+ const head = ` ${theme.success(glyphs.tick)} ${reference(ui, change.task)} ${linkedPhrase(change.type)} ${reference(ui, change.other)} ${theme.muted(glyphs.separator)} `;
+ const title = truncate(
+ change.other.title,
+ Math.max(ui.caps.columns - stringWidth(head), 8),
+ glyphs.ellipsis,
+ );
+ return ["", `${head}${title}`, ""];
+}
+
+export function renderRelationsRemoved(
+ ui: Ui,
+ change: {
+ readonly types: ReadonlyArray<string>;
+ readonly task: TaskLabel;
+ readonly other: TaskLabel;
+ },
+): string[] {
+ const { theme, glyphs } = ui;
+ const tick = theme.success(glyphs.tick);
+ const task = reference(ui, change.task);
+ const other = reference(ui, change.other);
+ const [only] = change.types;
+ const phrase =
+ change.types.length === 1 && only ? unlinkedPhrase(only) : null;
+ const line = phrase
+ ? ` ${tick} ${task} ${phrase} ${other}`
+ : change.types.length > 1
+ ? ` ${tick} Removed ${change.types.length} relations between ${task} and ${other}`
+ : ` ${tick} Unlinked ${task} and ${other}`;
+ return ["", line, ""];
+}
diff --git a/packages/cli/src/relations/render-relation-list.test.ts b/packages/cli/src/relations/render-relation-list.test.ts
new file mode 100644
index 000000000..3fd67a28d
--- /dev/null
+++ b/packages/cli/src/relations/render-relation-list.test.ts
@@ -0,0 +1,116 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import type { RelatedTaskJson } from "./group-relations.js";
+import { renderRelationList } from "./render-relation-list.js";
+
+const ui = (columns: number) =>
+ makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns,
+ });
+
+const task = (
+ ticketId: string,
+ title: string,
+ status = "to-do",
+ completed = false,
+): RelatedTaskJson => ({
+ id: ticketId.toLowerCase(),
+ ticketId,
+ title,
+ status,
+ completed,
+ url: `https://kaneo.test/${ticketId}`,
+});
+
+const view = {
+ label: "KAN-3",
+ title: "Fix login redirect",
+ url: "https://kaneo.test/KAN-3",
+};
+
+describe("renderRelationList", () => {
+ it("groups the parent, subtasks and other relations", () => {
+ expect(
+ renderRelationList(ui(80), {
+ ...view,
+ relations: {
+ parent: task("KAN-1", "Auth overhaul", "in-progress"),
+ subtasks: [
+ task("KAN-4", "Write tests", "done", true),
+ task("KAN-10", "Update docs"),
+ ],
+ relations: [
+ {
+ type: "blocks",
+ direction: "outgoing",
+ task: task("KAN-7", "Release 2.0"),
+ },
+ {
+ type: "blocked-by",
+ direction: "incoming",
+ task: task("MOB-2", "API change", "in-review"),
+ },
+ {
+ type: "relates-to",
+ direction: "incoming",
+ task: task("KAN-6", "Session timeout"),
+ },
+ ],
+ },
+ }),
+ ).toEqual([
+ "",
+ " KAN-3 Fix login redirect · Relations",
+ "",
+ " Parent",
+ " ● KAN-1 Auth overhaul In Progress",
+ "",
+ " Subtasks 1 of 2 done",
+ " ● KAN-4 Write tests Done",
+ " ● KAN-10 Update docs To Do",
+ "",
+ " Blocks",
+ " ● KAN-7 Release 2.0 To Do",
+ "",
+ " Blocked by",
+ " ● MOB-2 API change In Review",
+ "",
+ " Related",
+ " ● KAN-6 Session timeout To Do",
+ "",
+ ]);
+ });
+
+ it("fits long titles to the terminal width", () => {
+ const lines = renderRelationList(ui(80), {
+ ...view,
+ relations: {
+ parent: null,
+ subtasks: [task("KAN-4", "A".repeat(120))],
+ relations: [],
+ },
+ });
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(80);
+ expect(lines[4]).toContain("…");
+ });
+
+ it("explains how to link when there is nothing", () => {
+ expect(
+ renderRelationList(ui(80), {
+ ...view,
+ relations: { parent: null, subtasks: [], relations: [] },
+ }),
+ ).toEqual([
+ "",
+ " KAN-3 Fix login redirect · Relations",
+ "",
+ " No linked tasks. Link one with kaneo task relation add KAN-3 <type> <task>",
+ "",
+ ]);
+ });
+});
diff --git a/packages/cli/src/relations/render-relation-list.ts b/packages/cli/src/relations/render-relation-list.ts
new file mode 100644
index 000000000..8309ff0f3
--- /dev/null
+++ b/packages/cli/src/relations/render-relation-list.ts
@@ -0,0 +1,103 @@
+import { type Cell, text } from "../render/cell.js";
+import { renderTable } from "../render/table.js";
+import { statusDot } from "../render/task-format.js";
+import type { Ui } from "../render/ui.js";
+import { renderTaskHeading } from "../comments/render-task-heading.js";
+import { statusLabel } from "../search/render-search.js";
+import type { RelatedTaskJson, RelationsJson } from "./group-relations.js";
+import { relationHeading } from "./relation-types.js";
+
+export type RelationListView = {
+ readonly label: string;
+ readonly title: string;
+ readonly url: string;
+ readonly relations: RelationsJson;
+};
+
+type Group = {
+ readonly title: string;
+ readonly meta: string | null;
+ readonly tasks: ReadonlyArray<RelatedTaskJson>;
+};
+
+function groupsOf(relations: RelationsJson): Group[] {
+ const groups: Group[] = [];
+ if (relations.parent) {
+ groups.push({ title: "Parent", meta: null, tasks: [relations.parent] });
+ }
+ if (relations.subtasks.length > 0) {
+ const done = relations.subtasks.filter((task) => task.completed).length;
+ groups.push({
+ title: "Subtasks",
+ meta: `${done} of ${relations.subtasks.length} done`,
+ tasks: relations.subtasks,
+ });
+ }
+ const byType = new Map<string, RelatedTaskJson[]>();
+ for (const relation of relations.relations) {
+ const tasks = byType.get(relation.type) ?? [];
+ tasks.push(relation.task);
+ byType.set(relation.type, tasks);
+ }
+ for (const [type, tasks] of byType) {
+ groups.push({ title: relationHeading(type), meta: null, tasks });
+ }
+ return groups;
+}
+
+export function renderRelationList(ui: Ui, view: RelationListView): string[] {
+ const { theme } = ui;
+ const heading = renderTaskHeading(ui, {
+ label: view.label,
+ title: view.title,
+ url: view.url,
+ meta: "Relations",
+ });
+ const groups = groupsOf(view.relations);
+ if (groups.length === 0) {
+ return [
+ "",
+ heading,
+ "",
+ ` ${theme.muted("No linked tasks. Link one with")} ${theme.strong(`kaneo task relation add ${view.label} <type> <task>`)}`,
+ "",
+ ];
+ }
+ const rows = renderTable(
+ ui,
+ groups.flatMap((group) => group.tasks),
+ [
+ {
+ header: "ID",
+ cell: (task): Cell => [
+ statusDot(ui, task.status, task.completed),
+ text(" "),
+ text(task.ticketId ?? task.id.slice(0, 8), theme.muted, task.url),
+ ],
+ },
+ {
+ header: "Title",
+ flex: true,
+ minWidth: 16,
+ cell: (task): Cell => [text(task.title, undefined, task.url)],
+ },
+ {
+ header: "Status",
+ optional: true,
+ cell: (task): Cell => [text(statusLabel(task.status), theme.muted)],
+ },
+ ],
+ { width: ui.caps.columns, indent: 4, gap: 2 },
+ );
+ const lines = ["", heading, ""];
+ let offset = 0;
+ for (const group of groups) {
+ lines.push(
+ ` ${theme.strong(group.title)}${group.meta ? ` ${theme.muted(group.meta)}` : ""}`,
+ ...rows.slice(offset, offset + group.tasks.length),
+ "",
+ );
+ offset += group.tasks.length;
+ }
+ return lines;
+}
diff --git a/packages/cli/src/relations/resolve-pair.ts b/packages/cli/src/relations/resolve-pair.ts
new file mode 100644
index 000000000..888b3d277
--- /dev/null
+++ b/packages/cli/src/relations/resolve-pair.ts
@@ -0,0 +1,30 @@
+import { Effect } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+import { withSpinner } from "../output/spinner.js";
+import { resolveTask } from "../tasks/resolve-task.js";
+import { taskLabel, taskRef } from "./task-ref.js";
+
+export const resolvePair = Effect.fn("relations.resolvePair")(function* (
+ taskReference: string,
+ otherReference: string,
+) {
+ const [task, other] = yield* withSpinner(
+ `Loading ${taskReference} and ${otherReference}`,
+ )(
+ Effect.all([resolveTask(taskReference), resolveTask(otherReference)], {
+ concurrency: 2,
+ }),
+ );
+ if (task.task.id === other.task.id) {
+ return yield* new InvalidArgument({
+ message: `${taskLabel(taskRef(task))} cannot be linked to itself.`,
+ });
+ }
+ if (task.workspaceId !== other.workspaceId) {
+ return yield* new InvalidArgument({
+ message: `${taskLabel(taskRef(other))} is in another workspace than ${taskLabel(taskRef(task))}.`,
+ hint: "Tasks can only be linked within one workspace.",
+ });
+ }
+ return { task, other };
+});
diff --git a/packages/cli/src/relations/task-ref.ts b/packages/cli/src/relations/task-ref.ts
new file mode 100644
index 000000000..918ff3416
--- /dev/null
+++ b/packages/cli/src/relations/task-ref.ts
@@ -0,0 +1,21 @@
+import type { ResolvedTask } from "../tasks/resolve-task.js";
+
+export type TaskRef = {
+ readonly id: string;
+ readonly ticketId: string | null;
+ readonly title: string;
+ readonly url: string;
+};
+
+export function taskRef(resolved: ResolvedTask): TaskRef {
+ return {
+ id: resolved.task.id,
+ ticketId: resolved.ticketId,
+ title: resolved.task.title,
+ url: resolved.url,
+ };
+}
+
+export function taskLabel(task: TaskRef): string {
+ return task.ticketId ?? task.id.slice(0, 8);
+}
diff --git a/packages/cli/src/render/box.test.ts b/packages/cli/src/render/box.test.ts
new file mode 100644
index 000000000..0b43cace3
--- /dev/null
+++ b/packages/cli/src/render/box.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vite-plus/test";
+import { box } from "./box.js";
+import { makeUi } from "./ui.js";
+import { stringWidth } from "./width.js";
+
+const make = (unicode: boolean, columns = 80) =>
+ makeUi({ color: 0, unicode, hyperlinks: false, animate: false, columns });
+
+describe("box", () => {
+ it("draws a rounded box with a title and equal line widths", () => {
+ const lines = box(make(true), ["one", "two words"], { title: "Sign in" });
+ expect(lines[0]?.startsWith("╭─ Sign in ")).toBe(true);
+ expect(lines.at(-1)?.startsWith("╰")).toBe(true);
+ const widths = new Set(lines.map(stringWidth));
+ expect(widths.size).toBe(1);
+ });
+
+ it("falls back to ascii borders", () => {
+ const lines = box(make(false), ["x"]);
+ expect(lines[0]?.startsWith("+-")).toBe(true);
+ expect(lines[1]?.startsWith("|")).toBe(true);
+ });
+
+ it("fits the terminal width", () => {
+ const lines = box(make(true, 20), [
+ "a very long line that does not fit in twenty columns",
+ ]);
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(20);
+ });
+});
diff --git a/packages/cli/src/render/box.ts b/packages/cli/src/render/box.ts
new file mode 100644
index 000000000..81c3d7100
--- /dev/null
+++ b/packages/cli/src/render/box.ts
@@ -0,0 +1,57 @@
+import type { Ui } from "./ui.js";
+import { padEnd, stringWidth, truncate } from "./width.js";
+
+export type BoxOptions = {
+ readonly title?: string;
+ readonly paddingX?: number;
+ readonly paddingY?: number;
+ readonly minWidth?: number;
+};
+
+export function box(
+ ui: Ui,
+ lines: ReadonlyArray<string>,
+ options: BoxOptions = {},
+): string[] {
+ const { box: chars, ellipsis } = ui.glyphs;
+ const paddingX = options.paddingX ?? 2;
+ const paddingY = options.paddingY ?? 0;
+ const border = ui.theme.border;
+ const title = options.title ? ` ${options.title} ` : "";
+ const maxInner = Math.max(4, ui.caps.columns - 2);
+ const contentWidth = Math.max(
+ options.minWidth ?? 0,
+ stringWidth(title) + 2 - paddingX * 2,
+ ...lines.map((line) => stringWidth(line)),
+ );
+ const inner = Math.min(maxInner, contentWidth + paddingX * 2);
+ const usable = inner - paddingX * 2;
+ const pad = " ".repeat(paddingX);
+ const blank =
+ border(chars.vertical) + " ".repeat(inner) + border(chars.vertical);
+ const fittedTitle = title ? truncate(title, inner - 2, ellipsis) : "";
+ const top =
+ border(chars.topLeft + chars.horizontal) +
+ (fittedTitle ? ui.theme.strong(fittedTitle) : "") +
+ border(
+ chars.horizontal.repeat(
+ Math.max(0, inner - 1 - stringWidth(fittedTitle)),
+ ) + chars.topRight,
+ );
+ const body = lines.map((line) => {
+ const fitted =
+ stringWidth(line) > usable ? truncate(line, usable, ellipsis) : line;
+ return (
+ border(chars.vertical) +
+ pad +
+ padEnd(fitted, usable) +
+ pad +
+ border(chars.vertical)
+ );
+ });
+ const spacer = Array.from({ length: paddingY }, () => blank);
+ const bottom = border(
+ chars.bottomLeft + chars.horizontal.repeat(inner) + chars.bottomRight,
+ );
+ return [top, ...spacer, ...body, ...spacer, bottom];
+}
diff --git a/packages/cli/src/render/capabilities.test.ts b/packages/cli/src/render/capabilities.test.ts
new file mode 100644
index 000000000..9ae8eabd6
--- /dev/null
+++ b/packages/cli/src/render/capabilities.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it } from "vite-plus/test";
+import {
+ detectCapabilities,
+ detectColorLevel,
+ detectHyperlinks,
+ detectUnicode,
+} from "./capabilities.js";
+
+const tty = { isTTY: true, columns: 100 };
+const pipe = { isTTY: false, columns: undefined };
+
+describe("detectColorLevel", () => {
+ it("is off for pipes", () => {
+ expect(detectColorLevel({}, pipe, "darwin")).toBe(0);
+ });
+
+ it("respects NO_COLOR", () => {
+ expect(
+ detectColorLevel(
+ { NO_COLOR: "1", COLORTERM: "truecolor" },
+ tty,
+ "darwin",
+ ),
+ ).toBe(0);
+ });
+
+ it("lets FORCE_COLOR win over NO_COLOR and pipes", () => {
+ expect(
+ detectColorLevel({ NO_COLOR: "1", FORCE_COLOR: "3" }, pipe, "darwin"),
+ ).toBe(3);
+ expect(detectColorLevel({ FORCE_COLOR: "0" }, tty, "darwin")).toBe(0);
+ expect(detectColorLevel({ FORCE_COLOR: "" }, pipe, "darwin")).toBe(1);
+ });
+
+ it("is off for TERM=dumb", () => {
+ expect(detectColorLevel({ TERM: "dumb" }, tty, "linux")).toBe(0);
+ });
+
+ it("detects truecolor and 256 colors", () => {
+ expect(detectColorLevel({ COLORTERM: "truecolor" }, tty, "linux")).toBe(3);
+ expect(detectColorLevel({ TERM_PROGRAM: "ghostty" }, tty, "darwin")).toBe(
+ 3,
+ );
+ expect(detectColorLevel({ TERM: "xterm-256color" }, tty, "linux")).toBe(2);
+ expect(detectColorLevel({ TERM: "xterm" }, tty, "linux")).toBe(1);
+ });
+});
+
+describe("detectUnicode", () => {
+ it("falls back to ascii for dumb terminals and non UTF-8 locales", () => {
+ expect(detectUnicode({ TERM: "dumb" }, "linux")).toBe(false);
+ expect(detectUnicode({ LANG: "C" }, "linux")).toBe(false);
+ expect(detectUnicode({ LANG: "en_US.UTF-8" }, "linux")).toBe(true);
+ expect(detectUnicode({}, "darwin")).toBe(true);
+ });
+
+ it("needs a modern Windows terminal", () => {
+ expect(detectUnicode({}, "win32")).toBe(false);
+ expect(detectUnicode({ WT_SESSION: "1" }, "win32")).toBe(true);
+ });
+});
+
+describe("detectHyperlinks", () => {
+ it("only enables known terminals", () => {
+ expect(detectHyperlinks({ TERM_PROGRAM: "iTerm.app" }, tty)).toBe(true);
+ expect(detectHyperlinks({ TERM_PROGRAM: "Apple_Terminal" }, tty)).toBe(
+ false,
+ );
+ expect(detectHyperlinks({ TERM: "xterm-kitty" }, tty)).toBe(true);
+ expect(detectHyperlinks({ TERM_PROGRAM: "iTerm.app" }, pipe)).toBe(false);
+ });
+
+ it("can be forced either way", () => {
+ expect(detectHyperlinks({ FORCE_HYPERLINK: "1" }, pipe)).toBe(true);
+ expect(
+ detectHyperlinks(
+ { FORCE_HYPERLINK: "0", TERM_PROGRAM: "iTerm.app" },
+ tty,
+ ),
+ ).toBe(false);
+ });
+});
+
+describe("detectCapabilities", () => {
+ it("never animates on CI or pipes", () => {
+ expect(detectCapabilities({ CI: "true" }, tty, "linux").animate).toBe(
+ false,
+ );
+ expect(detectCapabilities({}, pipe, "linux").animate).toBe(false);
+ expect(detectCapabilities({}, tty, "linux").animate).toBe(true);
+ });
+
+ it("uses COLUMNS when the stream has no width", () => {
+ expect(detectCapabilities({ COLUMNS: "132" }, pipe, "linux").columns).toBe(
+ 132,
+ );
+ expect(detectCapabilities({}, pipe, "linux").columns).toBe(80);
+ });
+});
diff --git a/packages/cli/src/render/capabilities.ts b/packages/cli/src/render/capabilities.ts
new file mode 100644
index 000000000..cd951a795
--- /dev/null
+++ b/packages/cli/src/render/capabilities.ts
@@ -0,0 +1,109 @@
+export type ColorLevel = 0 | 1 | 2 | 3;
+
+export type Capabilities = {
+ readonly color: ColorLevel;
+ readonly unicode: boolean;
+ readonly hyperlinks: boolean;
+ readonly animate: boolean;
+ readonly columns: number;
+};
+
+export type Environment = Readonly<Record<string, string | undefined>>;
+
+export type StreamInfo = {
+ readonly isTTY: boolean;
+ readonly columns: number | undefined;
+};
+
+const TRUECOLOR_PROGRAMS = new Set([
+ "iTerm.app",
+ "WezTerm",
+ "vscode",
+ "ghostty",
+]);
+
+const HYPERLINK_PROGRAMS = new Set([
+ "iTerm.app",
+ "WezTerm",
+ "vscode",
+ "ghostty",
+ "Hyper",
+ "Tabby",
+]);
+
+const HYPERLINK_TERMS = new Set([
+ "xterm-kitty",
+ "xterm-ghostty",
+ "alacritty",
+ "foot",
+ "wezterm",
+]);
+
+export function detectColorLevel(
+ env: Environment,
+ stream: StreamInfo,
+ platform: string,
+): ColorLevel {
+ const forced = env.FORCE_COLOR;
+ if (forced !== undefined) {
+ if (forced === "0" || forced === "false") return 0;
+ if (forced === "2") return 2;
+ if (forced === "3") return 3;
+ return 1;
+ }
+ if (env.NO_COLOR) return 0;
+ if (env.TERM === "dumb") return 0;
+ if (!stream.isTTY) return 0;
+ if (env.COLORTERM === "truecolor" || env.COLORTERM === "24bit") return 3;
+ if (env.TERM_PROGRAM && TRUECOLOR_PROGRAMS.has(env.TERM_PROGRAM)) return 3;
+ if (platform === "win32") return env.WT_SESSION ? 3 : 1;
+ if (env.TERM && /-256(color)?$/i.test(env.TERM)) return 2;
+ return 1;
+}
+
+export function detectUnicode(env: Environment, platform: string): boolean {
+ if (env.TERM === "dumb") return false;
+ if (platform === "win32") {
+ return Boolean(env.WT_SESSION || env.TERM_PROGRAM || env.ConEmuTask);
+ }
+ const locale = env.LC_ALL || env.LC_CTYPE || env.LANG;
+ if (!locale) return true;
+ return /utf-?8/i.test(locale);
+}
+
+export function detectHyperlinks(
+ env: Environment,
+ stream: StreamInfo,
+): boolean {
+ const forced = env.FORCE_HYPERLINK;
+ if (forced !== undefined) return forced !== "0" && forced !== "false";
+ if (!stream.isTTY || env.TERM === "dumb") return false;
+ if (env.TERM_PROGRAM && HYPERLINK_PROGRAMS.has(env.TERM_PROGRAM)) return true;
+ if (env.TERM && HYPERLINK_TERMS.has(env.TERM)) return true;
+ if (env.WT_SESSION || env.KONSOLE_VERSION || env.KITTY_WINDOW_ID) return true;
+ const vte = Number(env.VTE_VERSION);
+ return Number.isFinite(vte) && vte >= 5000;
+}
+
+export function detectCapabilities(
+ env: Environment,
+ stream: StreamInfo,
+ platform: string,
+): Capabilities {
+ const columns = stream.columns ?? Number(env.COLUMNS);
+ return {
+ color: detectColorLevel(env, stream, platform),
+ unicode: detectUnicode(env, platform),
+ hyperlinks: detectHyperlinks(env, stream),
+ animate: stream.isTTY && env.TERM !== "dumb" && !env.CI,
+ columns: Number.isFinite(columns) && columns > 0 ? columns : 80,
+ };
+}
+
+export const plainCapabilities: Capabilities = {
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+};
diff --git a/packages/cli/src/render/cell.ts b/packages/cli/src/render/cell.ts
new file mode 100644
index 000000000..48aa95395
--- /dev/null
+++ b/packages/cli/src/render/cell.ts
@@ -0,0 +1,51 @@
+import { hyperlink } from "./link.js";
+import type { Style } from "./theme.js";
+import type { Ui } from "./ui.js";
+import { stringWidth, truncate } from "./width.js";
+
+export type Segment = {
+ readonly text: string;
+ readonly style?: Style | undefined;
+ readonly href?: string | undefined;
+};
+
+export type Cell = ReadonlyArray<Segment>;
+
+export function text(value: string, style?: Style, href?: string): Segment {
+ return { text: value, style, href };
+}
+
+export function cellWidth(cell: Cell): number {
+ return cell.reduce((width, segment) => width + stringWidth(segment.text), 0);
+}
+
+export function fitCell(cell: Cell, width: number, ellipsis: string): Cell {
+ if (cellWidth(cell) <= width) return cell;
+ const fitted: Segment[] = [];
+ let remaining = width;
+ for (const segment of cell) {
+ const segmentWidth = stringWidth(segment.text);
+ if (segmentWidth < remaining) {
+ fitted.push(segment);
+ remaining -= segmentWidth;
+ continue;
+ }
+ fitted.push({
+ ...segment,
+ text: truncate(segment.text, remaining, ellipsis),
+ });
+ break;
+ }
+ return fitted;
+}
+
+export function renderCell(cell: Cell, ui: Ui): string {
+ return cell
+ .map((segment) => {
+ const styled = segment.style ? segment.style(segment.text) : segment.text;
+ return segment.href
+ ? hyperlink(styled, segment.href, ui.caps.hyperlinks)
+ : styled;
+ })
+ .join("");
+}
diff --git a/packages/cli/src/render/glyphs.ts b/packages/cli/src/render/glyphs.ts
new file mode 100644
index 000000000..13c3ac339
--- /dev/null
+++ b/packages/cli/src/render/glyphs.ts
@@ -0,0 +1,87 @@
+export type Glyphs = {
+ readonly tick: string;
+ readonly cross: string;
+ readonly dot: string;
+ readonly diamond: string;
+ readonly arrow: string;
+ readonly ellipsis: string;
+ readonly separator: string;
+ readonly warning: string;
+ readonly due: string;
+ readonly priority: {
+ readonly empty: string;
+ readonly low: string;
+ readonly medium: string;
+ readonly high: string;
+ readonly urgent: string;
+ };
+ readonly box: {
+ readonly topLeft: string;
+ readonly topRight: string;
+ readonly bottomLeft: string;
+ readonly bottomRight: string;
+ readonly horizontal: string;
+ readonly vertical: string;
+ };
+ readonly spinner: ReadonlyArray<string>;
+};
+
+export const unicodeGlyphs: Glyphs = {
+ tick: "✓",
+ cross: "✗",
+ dot: "●",
+ diamond: "◆",
+ arrow: "→",
+ ellipsis: "…",
+ separator: "·",
+ warning: "▲",
+ due: "◷",
+ priority: {
+ empty: "▁",
+ low: "▂",
+ medium: "▄",
+ high: "▆",
+ urgent: "▲",
+ },
+ box: {
+ topLeft: "╭",
+ topRight: "╮",
+ bottomLeft: "╰",
+ bottomRight: "╯",
+ horizontal: "─",
+ vertical: "│",
+ },
+ spinner: ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"],
+};
+
+export const asciiGlyphs: Glyphs = {
+ tick: "+",
+ cross: "x",
+ dot: "*",
+ diamond: "#",
+ arrow: "->",
+ ellipsis: "...",
+ separator: "-",
+ warning: "!",
+ due: "",
+ priority: {
+ empty: ".",
+ low: "_",
+ medium: "=",
+ high: "#",
+ urgent: "!",
+ },
+ box: {
+ topLeft: "+",
+ topRight: "+",
+ bottomLeft: "+",
+ bottomRight: "+",
+ horizontal: "-",
+ vertical: "|",
+ },
+ spinner: ["|", "/", "-", "\\"],
+};
+
+export function glyphsFor(unicode: boolean): Glyphs {
+ return unicode ? unicodeGlyphs : asciiGlyphs;
+}
diff --git a/packages/cli/src/render/label-chip.test.ts b/packages/cli/src/render/label-chip.test.ts
new file mode 100644
index 000000000..4136684b8
--- /dev/null
+++ b/packages/cli/src/render/label-chip.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { ColorLevel } from "./capabilities.js";
+import { labelChip, labelChipSegment, nearest256 } from "./label-chip.js";
+import { makeUi } from "./ui.js";
+
+const ui = (color: ColorLevel, unicode = true) =>
+ makeUi({ color, unicode, hyperlinks: false, animate: false, columns: 80 });
+
+describe("labelChip", () => {
+ it("prints a plain dot without color support", () => {
+ expect(labelChip(ui(0), "red")).toBe("●");
+ expect(labelChip(ui(1), "#ff6600")).toBe("●");
+ });
+
+ it("uses the nearest 256 color at level 2", () => {
+ expect(labelChip(ui(2), "#ff6600")).toBe("\u001b[38;5;208m●\u001b[39m");
+ expect(labelChip(ui(2), "#808080")).toBe("\u001b[38;5;244m●\u001b[39m");
+ });
+
+ it("uses the exact color at truecolor", () => {
+ expect(labelChip(ui(3), "#ff6600")).toBe(
+ "\u001b[38;2;255;102;0m●\u001b[39m",
+ );
+ expect(labelChip(ui(3), "red")).toBe("\u001b[38;2;231;0;11m●\u001b[39m");
+ });
+
+ it("falls back to ascii and a neutral color", () => {
+ expect(labelChip(ui(0, false), "red")).toBe("*");
+ expect(labelChip(ui(3), "nonsense")).toBe(
+ "\u001b[38;2;161;161;161m●\u001b[39m",
+ );
+ });
+
+ it("exposes a table segment", () => {
+ const segment = labelChipSegment(ui(3), "#ff6600");
+ expect(segment.text).toBe("●");
+ expect(segment.style?.("x")).toBe("\u001b[38;2;255;102;0mx\u001b[39m");
+ });
+});
+
+describe("nearest256", () => {
+ it("maps grays to the gray ramp and colors to the cube", () => {
+ expect(nearest256([0, 0, 0])).toBe(16);
+ expect(nearest256([255, 255, 255])).toBe(231);
+ expect(nearest256([255, 0, 0])).toBe(196);
+ });
+});
diff --git a/packages/cli/src/render/label-chip.ts b/packages/cli/src/render/label-chip.ts
new file mode 100644
index 000000000..4e0bb3b89
--- /dev/null
+++ b/packages/cli/src/render/label-chip.ts
@@ -0,0 +1,40 @@
+import { labelColorHex } from "../labels/label-colors.js";
+import type { ColorLevel } from "./capabilities.js";
+import type { Segment } from "./cell.js";
+import type { Style } from "./theme.js";
+import type { Ui } from "./ui.js";
+
+type Rgb = readonly [number, number, number];
+
+function hexToRgb(hex: string): Rgb {
+ const value = Number.parseInt(hex.slice(1, 7), 16);
+ return [(value >> 16) & 255, (value >> 8) & 255, value & 255];
+}
+
+export function nearest256([r, g, b]: Rgb): number {
+ if (r === g && g === b) {
+ if (r < 8) return 16;
+ if (r > 248) return 231;
+ return Math.round(((r - 8) / 247) * 24) + 232;
+ }
+ const level = (value: number) => Math.round((value / 255) * 5);
+ return 16 + 36 * level(r) + 6 * level(g) + level(b);
+}
+
+export function labelStyle(level: ColorLevel, color: string): Style {
+ if (level < 2) return (text) => text;
+ const rgb = hexToRgb(labelColorHex(color));
+ const open =
+ level === 3
+ ? `\u001b[38;2;${rgb.join(";")}m`
+ : `\u001b[38;5;${nearest256(rgb)}m`;
+ return (text) => (text ? `${open}${text}\u001b[39m` : text);
+}
+
+export function labelChipSegment(ui: Ui, color: string): Segment {
+ return { text: ui.glyphs.dot, style: labelStyle(ui.caps.color, color) };
+}
+
+export function labelChip(ui: Ui, color: string): string {
+ return labelStyle(ui.caps.color, color)(ui.glyphs.dot);
+}
diff --git a/packages/cli/src/render/link.ts b/packages/cli/src/render/link.ts
new file mode 100644
index 000000000..f81f0ad19
--- /dev/null
+++ b/packages/cli/src/render/link.ts
@@ -0,0 +1,4 @@
+export function hyperlink(text: string, url: string, enabled: boolean): string {
+ if (!enabled || !text) return text;
+ return `\u001b]8;;${url}\u001b\\${text}\u001b]8;;\u001b\\`;
+}
diff --git a/packages/cli/src/render/links.ts b/packages/cli/src/render/links.ts
new file mode 100644
index 000000000..5c9a19747
--- /dev/null
+++ b/packages/cli/src/render/links.ts
@@ -0,0 +1,17 @@
+export function taskUrl(
+ webUrl: string,
+ task: {
+ readonly workspaceId: string;
+ readonly projectId: string;
+ readonly id: string;
+ },
+): string {
+ return `${webUrl}/dashboard/workspace/${task.workspaceId}/project/${task.projectId}/task/${task.id}`;
+}
+
+export function projectUrl(
+ webUrl: string,
+ project: { readonly workspaceId: string; readonly id: string },
+): string {
+ return `${webUrl}/dashboard/workspace/${project.workspaceId}/project/${project.id}/board`;
+}
diff --git a/packages/cli/src/render/logo.test.ts b/packages/cli/src/render/logo.test.ts
new file mode 100644
index 000000000..af18d08dd
--- /dev/null
+++ b/packages/cli/src/render/logo.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from "vite-plus/test";
+import { LOGO_LINES, LOGO_WIDTH, logo } from "./logo.js";
+import { makeUi } from "./ui.js";
+
+const make = (unicode: boolean, columns: number) =>
+ makeUi({ color: 0, unicode, hyperlinks: false, animate: false, columns });
+
+describe("logo", () => {
+ it("is at most six lines tall", () => {
+ expect(LOGO_LINES.length).toBeLessThanOrEqual(6);
+ });
+
+ it("uses the full art when it fits", () => {
+ expect(logo(make(true, 80))).toHaveLength(LOGO_LINES.length);
+ });
+
+ it("collapses to one line on narrow terminals", () => {
+ expect(LOGO_WIDTH).toBeGreaterThan(40);
+ expect(logo(make(true, 40))).toEqual([" ▅▆▇ kaneo"]);
+ });
+
+ it("uses plain text without unicode", () => {
+ expect(logo(make(false, 120))).toEqual([" kaneo"]);
+ });
+});
diff --git a/packages/cli/src/render/logo.ts b/packages/cli/src/render/logo.ts
new file mode 100644
index 000000000..f49792117
--- /dev/null
+++ b/packages/cli/src/render/logo.ts
@@ -0,0 +1,23 @@
+import type { Ui } from "./ui.js";
+
+export const LOGO_LINES: ReadonlyArray<string> = [
+ " ▄▄▄ ███ ▐█ ▗▟█▀",
+ "███ ███ █▛▘ ▐█▄█▛ ▗▄██▙▟█ ▟█▟██▙ ▄███▄▖ ▄▟██▙▄",
+ "███ ███ █▖ ▐█▜█▄ ██ ▜█ ██ ▝█▌▟█▄▄▄██▐█▌ ▝█▌",
+ "███ ███ ██▙ ▐█ ▀█▙▖▜█▄ ▄▟█ ██ █▌▐█▙ ▗▄▖▝█▙▖▗▟█▘",
+ "███ ███ ▀▀▀ ▝▀ ▀▀ ▝▀▀▀▝▀ ▀▀ ▀▘ ▝▀▀▀▀ ▀▀▀▀",
+ "▀▀▀",
+];
+
+export const LOGO_WIDTH = Math.max(
+ ...LOGO_LINES.map((line) => [...line].length),
+);
+
+export function logo(ui: Ui, indent = 2): string[] {
+ const prefix = " ".repeat(indent);
+ if (!ui.caps.unicode) return [`${prefix}${ui.theme.strong("kaneo")}`];
+ if (ui.caps.columns < LOGO_WIDTH + indent + 2) {
+ return [`${prefix}${ui.theme.strong("▅▆▇ kaneo")}`];
+ }
+ return LOGO_LINES.map((line) => `${prefix}${line}`);
+}
diff --git a/packages/cli/src/render/table.test.ts b/packages/cli/src/render/table.test.ts
new file mode 100644
index 000000000..a8f47a72b
--- /dev/null
+++ b/packages/cli/src/render/table.test.ts
@@ -0,0 +1,95 @@
+import { describe, expect, it } from "vite-plus/test";
+import { text } from "./cell.js";
+import { layoutColumns, renderTable } from "./table.js";
+import { makeUi } from "./ui.js";
+import { stringWidth } from "./width.js";
+
+const ui = (columns: number) =>
+ makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns,
+ });
+
+type Row = { id: string; title: string; owner: string };
+
+const rows: Row[] = [
+ {
+ id: "KAN-1",
+ title: "Fix login redirect after device approval",
+ owner: "Ada Lovelace",
+ },
+ { id: "KAN-22", title: "Dark mode", owner: "Grace Hopper" },
+];
+
+const columns = [
+ { header: "ID", cell: (row: Row) => [text(row.id)] },
+ {
+ header: "Title",
+ flex: true,
+ minWidth: 10,
+ cell: (row: Row) => [text(row.title)],
+ },
+ { header: "Owner", optional: true, cell: (row: Row) => [text(row.owner)] },
+];
+
+describe("layoutColumns", () => {
+ it("keeps natural widths when they fit", () => {
+ expect(layoutColumns([5, 20, 10], columns, 80, 2).widths).toEqual([
+ 5, 20, 10,
+ ]);
+ });
+
+ it("shrinks the flexible column first", () => {
+ const layout = layoutColumns([5, 40, 12], columns, 40, 2);
+ expect(layout.visible).toEqual([0, 1, 2]);
+ expect(layout.widths[1]).toBe(19);
+ });
+
+ it("drops optional columns when the flexible one hits its minimum", () => {
+ const layout = layoutColumns([5, 40, 12], columns, 20, 2);
+ expect(layout.visible).toEqual([0, 1]);
+ });
+});
+
+describe("renderTable", () => {
+ it("aligns cells and never exceeds the width", () => {
+ for (const width of [30, 50, 80, 120]) {
+ const lines = renderTable(ui(width), rows, columns, { width, indent: 2 });
+ expect(lines).toHaveLength(2);
+ for (const line of lines)
+ expect(stringWidth(line)).toBeLessThanOrEqual(width);
+ }
+ });
+
+ it("truncates with an ellipsis instead of wrapping", () => {
+ const [first] = renderTable(ui(40), rows, columns, { width: 40 });
+ expect(first).toContain("…");
+ });
+
+ it("renders a muted header when asked", () => {
+ const lines = renderTable(ui(80), rows, columns, {
+ width: 80,
+ header: true,
+ });
+ expect(lines[0]).toMatch(/^ID\s+Title\s+Owner$/);
+ });
+
+ it("right aligns numeric columns", () => {
+ const lines = renderTable(
+ ui(80),
+ [{ n: 3 }, { n: 120 }],
+ [
+ {
+ header: "N",
+ align: "right" as const,
+ cell: (row: { n: number }) => [text(String(row.n))],
+ },
+ ],
+ { width: 80 },
+ );
+ expect(lines).toEqual([" 3", "120"]);
+ });
+});
diff --git a/packages/cli/src/render/table.ts b/packages/cli/src/render/table.ts
new file mode 100644
index 000000000..d7638e412
--- /dev/null
+++ b/packages/cli/src/render/table.ts
@@ -0,0 +1,120 @@
+import { type Cell, cellWidth, fitCell, renderCell } from "./cell.js";
+import type { Ui } from "./ui.js";
+import { padEnd, padStart, stringWidth } from "./width.js";
+
+export type Column<Row> = {
+ readonly header: string;
+ readonly cell: (row: Row) => Cell;
+ readonly align?: "left" | "right";
+ readonly flex?: boolean;
+ readonly minWidth?: number;
+ readonly optional?: boolean;
+};
+
+export type TableOptions = {
+ readonly width: number;
+ readonly gap?: number;
+ readonly indent?: number;
+ readonly header?: boolean;
+};
+
+export type TableLayout = {
+ readonly visible: ReadonlyArray<number>;
+ readonly widths: ReadonlyArray<number>;
+};
+
+export function layoutColumns(
+ natural: ReadonlyArray<number>,
+ columns: ReadonlyArray<Pick<Column<never>, "flex" | "minWidth" | "optional">>,
+ available: number,
+ gap: number,
+): TableLayout {
+ const widths = [...natural];
+ const visible = columns.map((_, index) => index);
+ const total = () =>
+ visible.reduce((sum, index) => sum + (widths[index] ?? 0), 0) +
+ gap * Math.max(0, visible.length - 1);
+ const minWidth = (index: number) =>
+ Math.min(natural[index] ?? 0, columns[index]?.minWidth ?? 8);
+
+ const shrink = (indexes: ReadonlyArray<number>) => {
+ for (const index of indexes) {
+ const excess = total() - available;
+ if (excess <= 0) return;
+ const current = widths[index] ?? 0;
+ widths[index] = Math.max(minWidth(index), current - excess);
+ }
+ };
+
+ const flexible = () => visible.filter((index) => columns[index]?.flex);
+ shrink(flexible());
+ while (total() > available) {
+ const optional = [...visible]
+ .reverse()
+ .find((index) => columns[index]?.optional);
+ if (optional === undefined) break;
+ visible.splice(visible.indexOf(optional), 1);
+ shrink(flexible());
+ }
+ if (total() > available) {
+ shrink([...visible].sort((a, b) => (widths[b] ?? 0) - (widths[a] ?? 0)));
+ }
+ return { visible, widths };
+}
+
+export function renderTable<Row>(
+ ui: Ui,
+ rows: ReadonlyArray<Row>,
+ columns: ReadonlyArray<Column<Row>>,
+ options: TableOptions,
+): string[] {
+ const gap = options.gap ?? 2;
+ const indent = options.indent ?? 0;
+ const showHeader = options.header ?? false;
+ const cells = rows.map((row) => columns.map((column) => column.cell(row)));
+ const natural = columns.map((column, index) =>
+ Math.max(
+ showHeader ? stringWidth(column.header) : 0,
+ ...cells.map((row) => cellWidth(row[index] ?? [])),
+ ),
+ );
+ const { visible, widths } = layoutColumns(
+ natural,
+ columns,
+ options.width - indent,
+ gap,
+ );
+ const separator = " ".repeat(gap);
+ const prefix = " ".repeat(indent);
+
+ const line = (rendered: ReadonlyArray<string>) =>
+ (prefix + rendered.join(separator)).trimEnd();
+
+ const renderRow = (row: ReadonlyArray<Cell>) =>
+ line(
+ visible.map((index) => {
+ const width = widths[index] ?? 0;
+ const fitted = fitCell(row[index] ?? [], width, ui.glyphs.ellipsis);
+ const rendered = renderCell(fitted, ui);
+ return columns[index]?.align === "right"
+ ? padStart(rendered, width)
+ : padEnd(rendered, width);
+ }),
+ );
+
+ const header = showHeader
+ ? [
+ line(
+ visible.map((index) => {
+ const width = widths[index] ?? 0;
+ const title = ui.theme.muted(columns[index]?.header ?? "");
+ return columns[index]?.align === "right"
+ ? padStart(title, width)
+ : padEnd(title, width);
+ }),
+ ),
+ ]
+ : [];
+
+ return [...header, ...cells.map(renderRow)];
+}
diff --git a/packages/cli/src/render/task-format.ts b/packages/cli/src/render/task-format.ts
new file mode 100644
index 000000000..8de0670e6
--- /dev/null
+++ b/packages/cli/src/render/task-format.ts
@@ -0,0 +1,104 @@
+import type { Segment } from "./cell.js";
+import type { Style } from "./theme.js";
+import type { Ui } from "./ui.js";
+
+export function ticketId(
+ projectSlug: string,
+ number: number | null,
+): string | null {
+ return number === null ? null : `${projectSlug.toUpperCase()}-${number}`;
+}
+
+export function statusStyle(ui: Ui, slug: string, isFinal: boolean): Style {
+ if (isFinal || slug === "done") return ui.theme.done;
+ if (slug === "in-progress") return ui.theme.progress;
+ if (slug === "in-review") return ui.theme.review;
+ if (slug === "to-do" || slug === "todo" || slug === "backlog")
+ return ui.theme.todo;
+ return ui.theme.muted;
+}
+
+export function statusDot(ui: Ui, slug: string, isFinal: boolean): Segment {
+ return { text: ui.glyphs.dot, style: statusStyle(ui, slug, isFinal) };
+}
+
+export const PRIORITY_LABELS: Readonly<Record<string, string>> = {
+ urgent: "Urgent",
+ high: "High",
+ medium: "Medium",
+ low: "Low",
+};
+
+export function prioritySegments(ui: Ui, priority: string): Segment[] {
+ const label = PRIORITY_LABELS[priority];
+ if (!label) return [];
+ const { glyphs, theme } = ui;
+ const style =
+ priority === "urgent"
+ ? theme.danger
+ : priority === "high" || priority === "medium"
+ ? theme.warning
+ : theme.info;
+ const glyph = glyphs.priority[priority as keyof typeof glyphs.priority];
+ return [
+ { text: `${glyph} `, style },
+ { text: label, style },
+ ];
+}
+
+const DAY = 24 * 60 * 60 * 1000;
+
+function startOfDay(date: Date): number {
+ return new Date(
+ date.getFullYear(),
+ date.getMonth(),
+ date.getDate(),
+ ).getTime();
+}
+
+export type DueState = "overdue" | "today" | "soon" | "later";
+
+export function dueState(due: Date, now: Date): DueState {
+ const days = Math.round((startOfDay(due) - startOfDay(now)) / DAY);
+ if (days < 0) return "overdue";
+ if (days === 0) return "today";
+ if (days <= 2) return "soon";
+ return "later";
+}
+
+export function formatDue(due: Date, now: Date): string {
+ const days = Math.round((startOfDay(due) - startOfDay(now)) / DAY);
+ if (days === 0) return "Today";
+ if (days === 1) return "Tomorrow";
+ if (days === -1) return "Yesterday";
+ if (days > 1 && days < 7) {
+ return due.toLocaleDateString("en-US", { weekday: "short" });
+ }
+ const sameYear = due.getFullYear() === now.getFullYear();
+ return due.toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ ...(sameYear ? {} : { year: "numeric" }),
+ });
+}
+
+export function dueSegments(
+ ui: Ui,
+ dueDate: string | null,
+ done: boolean,
+ now: Date,
+): Segment[] {
+ if (!dueDate) return [];
+ const due = new Date(dueDate);
+ if (Number.isNaN(due.getTime())) return [];
+ const state = dueState(due, now);
+ const style = done
+ ? ui.theme.muted
+ : state === "overdue"
+ ? ui.theme.danger
+ : state === "today"
+ ? ui.theme.warning
+ : undefined;
+ const prefix = ui.glyphs.due ? `${ui.glyphs.due} ` : "";
+ return [{ text: `${prefix}${formatDue(due, now)}`, style }];
+}
diff --git a/packages/cli/src/render/theme.test.ts b/packages/cli/src/render/theme.test.ts
new file mode 100644
index 000000000..333d323ea
--- /dev/null
+++ b/packages/cli/src/render/theme.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeTheme, themeCodes } from "./theme.js";
+
+describe("makeTheme", () => {
+ it("is plain text without color", () => {
+ const theme = makeTheme(0);
+ expect(theme.danger("late")).toBe("late");
+ expect(theme.strong("bold")).toBe("bold");
+ });
+
+ it("uses basic ansi colors at level 1", () => {
+ expect(makeTheme(1).danger("late")).toBe("\u001b[31mlate\u001b[39m");
+ expect(makeTheme(1).muted("x")).toBe("\u001b[90mx\u001b[39m");
+ });
+
+ it("uses the web palette at truecolor", () => {
+ expect(makeTheme(3).success("ok")).toBe(
+ "\u001b[38;2;5;150;105mok\u001b[39m",
+ );
+ });
+
+ it("maps to the 256 color cube", () => {
+ const styled = makeTheme(2).info("x");
+ expect(styled.startsWith("\u001b[38;5;")).toBe(true);
+ expect(styled.endsWith("mx\u001b[39m")).toBe(true);
+ });
+
+ it("closes only what it opens so styles nest", () => {
+ const theme = makeTheme(1);
+ expect(theme.strong(`a ${theme.danger("b")} c`)).toBe(
+ "\u001b[1ma \u001b[31mb\u001b[39m c\u001b[22m",
+ );
+ });
+
+ it("leaves empty strings untouched", () => {
+ expect(makeTheme(3).accent("")).toBe("");
+ });
+});
+
+describe("themeCodes", () => {
+ it("is empty without color", () => {
+ expect(themeCodes(0)).toEqual({
+ bold: "",
+ muted: "",
+ success: "",
+ danger: "",
+ });
+ });
+});
diff --git a/packages/cli/src/render/theme.ts b/packages/cli/src/render/theme.ts
new file mode 100644
index 000000000..bd02e0371
--- /dev/null
+++ b/packages/cli/src/render/theme.ts
@@ -0,0 +1,96 @@
+import type { ColorLevel } from "./capabilities.js";
+
+export type Style = (text: string) => string;
+
+type Rgb = readonly [number, number, number];
+
+type Swatch = { readonly rgb: Rgb; readonly ansi16: number };
+
+const swatches = {
+ neutral: { rgb: [115, 115, 115], ansi16: 90 },
+ slate: { rgb: [100, 116, 139], ansi16: 90 },
+ blue: { rgb: [59, 130, 246], ansi16: 34 },
+ amber: { rgb: [217, 119, 6], ansi16: 33 },
+ emerald: { rgb: [5, 150, 105], ansi16: 32 },
+ red: { rgb: [239, 68, 68], ansi16: 31 },
+} satisfies Record<string, Swatch>;
+
+export type Theme = {
+ readonly level: ColorLevel;
+ readonly accent: Style;
+ readonly strong: Style;
+ readonly muted: Style;
+ readonly border: Style;
+ readonly success: Style;
+ readonly warning: Style;
+ readonly danger: Style;
+ readonly info: Style;
+ readonly todo: Style;
+ readonly progress: Style;
+ readonly review: Style;
+ readonly done: Style;
+};
+
+const identity: Style = (text) => text;
+
+function rgbTo256([r, g, b]: Rgb): number {
+ if (r === g && g === b) {
+ if (r < 8) return 16;
+ if (r > 248) return 231;
+ return Math.round(((r - 8) / 247) * 24) + 232;
+ }
+ const level = (value: number) => Math.round((value / 255) * 5);
+ return 16 + 36 * level(r) + 6 * level(g) + level(b);
+}
+
+function openCode(swatch: Swatch, level: ColorLevel): string {
+ if (level === 0) return "";
+ if (level === 3) return `\u001b[38;2;${swatch.rgb.join(";")}m`;
+ if (level === 2) return `\u001b[38;5;${rgbTo256(swatch.rgb)}m`;
+ return `\u001b[${swatch.ansi16}m`;
+}
+
+function foreground(swatch: Swatch, level: ColorLevel): Style {
+ if (level === 0) return identity;
+ const open = openCode(swatch, level);
+ return (text) => (text ? `${open}${text}\u001b[39m` : text);
+}
+
+export type ThemeCodes = {
+ readonly bold: string;
+ readonly muted: string;
+ readonly success: string;
+ readonly danger: string;
+};
+
+export function themeCodes(level: ColorLevel): ThemeCodes {
+ return {
+ bold: level === 0 ? "" : "\u001b[1m",
+ muted: openCode(swatches.neutral, level),
+ success: openCode(swatches.emerald, level),
+ danger: openCode(swatches.red, level),
+ };
+}
+
+function bold(level: ColorLevel): Style {
+ if (level === 0) return identity;
+ return (text) => (text ? `\u001b[1m${text}\u001b[22m` : text);
+}
+
+export function makeTheme(level: ColorLevel): Theme {
+ return {
+ level,
+ accent: bold(level),
+ strong: bold(level),
+ muted: foreground(swatches.neutral, level),
+ border: foreground(swatches.neutral, level),
+ success: foreground(swatches.emerald, level),
+ warning: foreground(swatches.amber, level),
+ danger: foreground(swatches.red, level),
+ info: foreground(swatches.blue, level),
+ todo: foreground(swatches.slate, level),
+ progress: foreground(swatches.blue, level),
+ review: foreground(swatches.amber, level),
+ done: foreground(swatches.emerald, level),
+ };
+}
diff --git a/packages/cli/src/render/ui.ts b/packages/cli/src/render/ui.ts
new file mode 100644
index 000000000..fd4177240
--- /dev/null
+++ b/packages/cli/src/render/ui.ts
@@ -0,0 +1,17 @@
+import type { Capabilities } from "./capabilities.js";
+import { type Glyphs, glyphsFor } from "./glyphs.js";
+import { makeTheme, type Theme } from "./theme.js";
+
+export type Ui = {
+ readonly caps: Capabilities;
+ readonly theme: Theme;
+ readonly glyphs: Glyphs;
+};
+
+export function makeUi(caps: Capabilities): Ui {
+ return {
+ caps,
+ theme: makeTheme(caps.color),
+ glyphs: glyphsFor(caps.unicode),
+ };
+}
diff --git a/packages/cli/src/render/width.test.ts b/packages/cli/src/render/width.test.ts
new file mode 100644
index 000000000..e5874f65d
--- /dev/null
+++ b/packages/cli/src/render/width.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from "vite-plus/test";
+import { padEnd, stringWidth, stripAnsi, truncate } from "./width.js";
+
+describe("stringWidth", () => {
+ it("counts plain ascii", () => {
+ expect(stringWidth("Fix login")).toBe(9);
+ });
+
+ it("ignores SGR and OSC 8 sequences", () => {
+ const styled =
+ "\u001b[1m\u001b]8;;https://x.test\u001b\\KAN-1\u001b]8;;\u001b\\\u001b[22m";
+ expect(stringWidth(styled)).toBe(5);
+ expect(stripAnsi(styled)).toBe("KAN-1");
+ });
+
+ it("counts wide characters and emoji as two cells", () => {
+ expect(stringWidth("日本")).toBe(4);
+ expect(stringWidth("🚀 ship")).toBe(7);
+ });
+
+ it("counts combining marks as zero", () => {
+ expect(stringWidth("é")).toBe(1);
+ });
+});
+
+describe("truncate", () => {
+ it("keeps text that fits", () => {
+ expect(truncate("short", 10, "…")).toBe("short");
+ });
+
+ it("cuts to the width including the ellipsis", () => {
+ const result = truncate("Board performance with 5000 tasks", 12, "…");
+ expect(result).toBe("Board perfo…");
+ expect(stringWidth(result)).toBe(12);
+ });
+
+ it("never splits a wide character", () => {
+ expect(
+ stringWidth(truncate("日本語のタイトル", 5, "…")),
+ ).toBeLessThanOrEqual(5);
+ });
+
+ it("uses an ascii ellipsis when asked", () => {
+ expect(truncate("abcdefghij", 6, "...")).toBe("abc...");
+ });
+});
+
+describe("padEnd", () => {
+ it("pads by display width", () => {
+ expect(padEnd("日本", 6)).toBe("日本 ");
+ });
+});
diff --git a/packages/cli/src/render/width.ts b/packages/cli/src/render/width.ts
new file mode 100644
index 000000000..d9d4923ce
--- /dev/null
+++ b/packages/cli/src/render/width.ts
@@ -0,0 +1,87 @@
+const ESC = "\u001b";
+const BEL = "\u0007";
+const ANSI_PATTERN = new RegExp(
+ `${ESC}\\[[0-9;?]*[ -/]*[@-~]|${ESC}\\][^${BEL}${ESC}]*(?:${BEL}|${ESC}\\\\)`,
+ "g",
+);
+
+const ZERO_WIDTH = /^(?:\p{Mark}|\p{Control}|\p{Format})+$/u;
+const EMOJI = /\p{Emoji_Presentation}|\p{Extended_Pictographic}\uFE0F/u;
+
+const WIDE_RANGES: ReadonlyArray<readonly [number, number]> = [
+ [0x1100, 0x115f],
+ [0x2e80, 0x303e],
+ [0x3041, 0x33ff],
+ [0x3400, 0x4dbf],
+ [0x4e00, 0x9fff],
+ [0xa000, 0xa4cf],
+ [0xac00, 0xd7a3],
+ [0xf900, 0xfaff],
+ [0xfe30, 0xfe4f],
+ [0xff00, 0xff60],
+ [0xffe0, 0xffe6],
+ [0x20000, 0x3fffd],
+];
+
+let segmenter: Intl.Segmenter | undefined;
+
+function graphemes(text: string): Iterable<string> {
+ segmenter ??= new Intl.Segmenter(undefined, { granularity: "grapheme" });
+ return Array.from(segmenter.segment(text), (part) => part.segment);
+}
+
+function isWide(codePoint: number): boolean {
+ return WIDE_RANGES.some(
+ ([start, end]) => codePoint >= start && codePoint <= end,
+ );
+}
+
+function graphemeWidth(grapheme: string): number {
+ if (ZERO_WIDTH.test(grapheme)) return 0;
+ if (EMOJI.test(grapheme)) return 2;
+ const codePoint = grapheme.codePointAt(0) ?? 0;
+ return isWide(codePoint) ? 2 : 1;
+}
+
+export function stripAnsi(text: string): string {
+ return text.replace(ANSI_PATTERN, "");
+}
+
+export function stringWidth(text: string): number {
+ const plain = stripAnsi(text);
+ if (/^[\x20-\x7e]*$/.test(plain)) return plain.length;
+ let width = 0;
+ for (const grapheme of graphemes(plain)) width += graphemeWidth(grapheme);
+ return width;
+}
+
+export function truncate(
+ text: string,
+ maxWidth: number,
+ ellipsis: string,
+): string {
+ if (maxWidth <= 0) return "";
+ if (stringWidth(text) <= maxWidth) return text;
+ const ellipsisWidth = stringWidth(ellipsis);
+ if (maxWidth <= ellipsisWidth) return ellipsis.slice(0, maxWidth);
+ const budget = maxWidth - ellipsisWidth;
+ let width = 0;
+ let result = "";
+ for (const grapheme of graphemes(text)) {
+ const next = graphemeWidth(grapheme);
+ if (width + next > budget) break;
+ result += grapheme;
+ width += next;
+ }
+ return `${result.trimEnd()}${ellipsis}`;
+}
+
+export function padEnd(text: string, width: number): string {
+ const gap = width - stringWidth(text);
+ return gap > 0 ? text + " ".repeat(gap) : text;
+}
+
+export function padStart(text: string, width: number): string {
+ const gap = width - stringWidth(text);
+ return gap > 0 ? " ".repeat(gap) + text : text;
+}
diff --git a/packages/cli/src/screens/__snapshots__/screens.test.ts.snap b/packages/cli/src/screens/__snapshots__/screens.test.ts.snap
new file mode 100644
index 000000000..21ea9aa92
--- /dev/null
+++ b/packages/cli/src/screens/__snapshots__/screens.test.ts.snap
@@ -0,0 +1,566 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`screens > error at 80 columns, no color 1`] = `
+"
+✗ You are not signed in to cloud.kaneo.app.
+ → Run kaneo login, or set KANEO_API_KEY.
+"
+`;
+
+exports[`screens > error at 80 columns, truecolor 1`] = `
+"
+✗ You are not signed in to cloud.kaneo.app.
+ → Run kaneo login, or set KANEO_API_KEY.
+"
+`;
+
+exports[`screens > error at 120 columns, no color 1`] = `
+"
+✗ You are not signed in to cloud.kaneo.app.
+ → Run kaneo login, or set KANEO_API_KEY.
+"
+`;
+
+exports[`screens > error at 120 columns, truecolor 1`] = `
+"
+✗ You are not signed in to cloud.kaneo.app.
+ → Run kaneo login, or set KANEO_API_KEY.
+"
+`;
+
+exports[`screens > home at 80 columns, no color 1`] = `
+"
+
+ ▄▄▄ ███ ▐█ ▗▟█▀
+ ███ ███ █▛▘ ▐█▄█▛ ▗▄██▙▟█ ▟█▟██▙ ▄███▄▖ ▄▟██▙▄
+ ███ ███ █▖ ▐█▜█▄ ██ ▜█ ██ ▝█▌▟█▄▄▄██▐█▌ ▝█▌
+ ███ ███ ██▙ ▐█ ▀█▙▖▜█▄ ▄▟█ ██ █▌▐█▙ ▗▄▖▝█▙▖▗▟█▘
+ ███ ███ ▀▀▀ ▝▀ ▀▀ ▝▀▀▀▝▀ ▀▀ ▀▘ ▝▀▀▀▀ ▀▀▀▀
+ ▀▀▀
+
+ Ada Lovelace · Acme Studio · cloud.kaneo.app
+
+ Your open tasks
+ KAN-1 Fix login redirect after device approval ▲ Urgent ◷ Oct 5
+ KAN-2 Board performance with 5000 tasks ▆ High ◷ Today
+ KAN-6 Review API error shape ▆ High
+
+ Commands
+ kaneo task list List tasks in a project
+ kaneo whoami Show your account and server
+ kaneo login Sign in with your browser
+ kaneo --help See every command
+
+"
+`;
+
+exports[`screens > home at 80 columns, truecolor 1`] = `
+"
+
+ ▄▄▄ ███ ▐█ ▗▟█▀
+ ███ ███ █▛▘ ▐█▄█▛ ▗▄██▙▟█ ▟█▟██▙ ▄███▄▖ ▄▟██▙▄
+ ███ ███ █▖ ▐█▜█▄ ██ ▜█ ██ ▝█▌▟█▄▄▄██▐█▌ ▝█▌
+ ███ ███ ██▙ ▐█ ▀█▙▖▜█▄ ▄▟█ ██ █▌▐█▙ ▗▄▖▝█▙▖▗▟█▘
+ ███ ███ ▀▀▀ ▝▀ ▀▀ ▝▀▀▀▝▀ ▀▀ ▀▘ ▝▀▀▀▀ ▀▀▀▀
+ ▀▀▀
+
+ Ada Lovelace · Acme Studio · cloud.kaneo.app
+
+ Your open tasks
+ KAN-1 Fix login redirect after device approval ▲ Urgent ◷ Oct 5
+ KAN-2 Board performance with 5000 tasks ▆ High ◷ Today
+ KAN-6 Review API error shape ▆ High
+
+ Commands
+ kaneo task list List tasks in a project
+ kaneo whoami Show your account and server
+ kaneo login Sign in with your browser
+ kaneo --help See every command
+
+"
+`;
+
+exports[`screens > home at 120 columns, no color 1`] = `
+"
+
+ ▄▄▄ ███ ▐█ ▗▟█▀
+ ███ ███ █▛▘ ▐█▄█▛ ▗▄██▙▟█ ▟█▟██▙ ▄███▄▖ ▄▟██▙▄
+ ███ ███ █▖ ▐█▜█▄ ██ ▜█ ██ ▝█▌▟█▄▄▄██▐█▌ ▝█▌
+ ███ ███ ██▙ ▐█ ▀█▙▖▜█▄ ▄▟█ ██ █▌▐█▙ ▗▄▖▝█▙▖▗▟█▘
+ ███ ███ ▀▀▀ ▝▀ ▀▀ ▝▀▀▀▝▀ ▀▀ ▀▘ ▝▀▀▀▀ ▀▀▀▀
+ ▀▀▀
+
+ Ada Lovelace · Acme Studio · cloud.kaneo.app
+
+ Your open tasks
+ KAN-1 Fix login redirect after device approval ▲ Urgent ◷ Oct 5
+ KAN-2 Board performance with 5000 tasks ▆ High ◷ Today
+ KAN-6 Review API error shape ▆ High
+
+ Commands
+ kaneo task list List tasks in a project
+ kaneo whoami Show your account and server
+ kaneo login Sign in with your browser
+ kaneo --help See every command
+
+"
+`;
+
+exports[`screens > home at 120 columns, truecolor 1`] = `
+"
+
+ ▄▄▄ ███ ▐█ ▗▟█▀
+ ███ ███ █▛▘ ▐█▄█▛ ▗▄██▙▟█ ▟█▟██▙ ▄███▄▖ ▄▟██▙▄
+ ███ ███ █▖ ▐█▜█▄ ██ ▜█ ██ ▝█▌▟█▄▄▄██▐█▌ ▝█▌
+ ███ ███ ██▙ ▐█ ▀█▙▖▜█▄ ▄▟█ ██ █▌▐█▙ ▗▄▖▝█▙▖▗▟█▘
+ ███ ███ ▀▀▀ ▝▀ ▀▀ ▝▀▀▀▝▀ ▀▀ ▀▘ ▝▀▀▀▀ ▀▀▀▀
+ ▀▀▀
+
+ Ada Lovelace · Acme Studio · cloud.kaneo.app
+
+ Your open tasks
+ KAN-1 Fix login redirect after device approval ▲ Urgent ◷ Oct 5
+ KAN-2 Board performance with 5000 tasks ▆ High ◷ Today
+ KAN-6 Review API error shape ▆ High
+
+ Commands
+ kaneo task list List tasks in a project
+ kaneo whoami Show your account and server
+ kaneo login Sign in with your browser
+ kaneo --help See every command
+
+"
+`;
+
+exports[`screens > home signed out at 80 columns, no color 1`] = `
+"
+
+ ▄▄▄ ███ ▐█ ▗▟█▀
+ ███ ███ █▛▘ ▐█▄█▛ ▗▄██▙▟█ ▟█▟██▙ ▄███▄▖ ▄▟██▙▄
+ ███ ███ █▖ ▐█▜█▄ ██ ▜█ ██ ▝█▌▟█▄▄▄██▐█▌ ▝█▌
+ ███ ███ ██▙ ▐█ ▀█▙▖▜█▄ ▄▟█ ██ █▌▐█▙ ▗▄▖▝█▙▖▗▟█▘
+ ███ ███ ▀▀▀ ▝▀ ▀▀ ▝▀▀▀▝▀ ▀▀ ▀▘ ▝▀▀▀▀ ▀▀▀▀
+ ▀▀▀
+
+ ● Not signed in to cloud.kaneo.app
+
+ Run kaneo login to get started.
+
+"
+`;
+
+exports[`screens > home signed out at 80 columns, truecolor 1`] = `
+"
+
+ ▄▄▄ ███ ▐█ ▗▟█▀
+ ███ ███ █▛▘ ▐█▄█▛ ▗▄██▙▟█ ▟█▟██▙ ▄███▄▖ ▄▟██▙▄
+ ███ ███ █▖ ▐█▜█▄ ██ ▜█ ██ ▝█▌▟█▄▄▄██▐█▌ ▝█▌
+ ███ ███ ██▙ ▐█ ▀█▙▖▜█▄ ▄▟█ ██ █▌▐█▙ ▗▄▖▝█▙▖▗▟█▘
+ ███ ███ ▀▀▀ ▝▀ ▀▀ ▝▀▀▀▝▀ ▀▀ ▀▘ ▝▀▀▀▀ ▀▀▀▀
+ ▀▀▀
+
+ ● Not signed in to cloud.kaneo.app
+
+ Run kaneo login to get started.
+
+"
+`;
+
+exports[`screens > home signed out at 120 columns, no color 1`] = `
+"
+
+ ▄▄▄ ███ ▐█ ▗▟█▀
+ ███ ███ █▛▘ ▐█▄█▛ ▗▄██▙▟█ ▟█▟██▙ ▄███▄▖ ▄▟██▙▄
+ ███ ███ █▖ ▐█▜█▄ ██ ▜█ ██ ▝█▌▟█▄▄▄██▐█▌ ▝█▌
+ ███ ███ ██▙ ▐█ ▀█▙▖▜█▄ ▄▟█ ██ █▌▐█▙ ▗▄▖▝█▙▖▗▟█▘
+ ███ ███ ▀▀▀ ▝▀ ▀▀ ▝▀▀▀▝▀ ▀▀ ▀▘ ▝▀▀▀▀ ▀▀▀▀
+ ▀▀▀
+
+ ● Not signed in to cloud.kaneo.app
+
+ Run kaneo login to get started.
+
+"
+`;
+
+exports[`screens > home signed out at 120 columns, truecolor 1`] = `
+"
+
+ ▄▄▄ ███ ▐█ ▗▟█▀
+ ███ ███ █▛▘ ▐█▄█▛ ▗▄██▙▟█ ▟█▟██▙ ▄███▄▖ ▄▟██▙▄
+ ███ ███ █▖ ▐█▜█▄ ██ ▜█ ██ ▝█▌▟█▄▄▄██▐█▌ ▝█▌
+ ███ ███ ██▙ ▐█ ▀█▙▖▜█▄ ▄▟█ ██ █▌▐█▙ ▗▄▖▝█▙▖▗▟█▘
+ ███ ███ ▀▀▀ ▝▀ ▀▀ ▝▀▀▀▝▀ ▀▀ ▀▘ ▝▀▀▀▀ ▀▀▀▀
+ ▀▀▀
+
+ ● Not signed in to cloud.kaneo.app
+
+ Run kaneo login to get started.
+
+"
+`;
+
+exports[`screens > login code at 80 columns, no color 1`] = `
+"
+
+ ╭─ Sign in to cloud.kaneo.app ───────────╮
+ │ │
+ │ Enter this code in your browser │
+ │ │
+ │ W D J B - M J H T │
+ │ │
+ │ ✓ Copied to your clipboard │
+ │ │
+ ╰────────────────────────────────────────╯
+
+ → Opened https://cloud.kaneo.app/device?user_code=WDJBMJHT
+
+"
+`;
+
+exports[`screens > login code at 80 columns, truecolor 1`] = `
+"
+
+ ╭─ Sign in to cloud.kaneo.app ───────────╮
+ │ │
+ │ Enter this code in your browser │
+ │ │
+ │ W D J B - M J H T │
+ │ │
+ │ ✓ Copied to your clipboard │
+ │ │
+ ╰────────────────────────────────────────╯
+
+ → Opened https://cloud.kaneo.app/device?user_code=WDJBMJHT
+
+"
+`;
+
+exports[`screens > login code at 120 columns, no color 1`] = `
+"
+
+ ╭─ Sign in to cloud.kaneo.app ───────────╮
+ │ │
+ │ Enter this code in your browser │
+ │ │
+ │ W D J B - M J H T │
+ │ │
+ │ ✓ Copied to your clipboard │
+ │ │
+ ╰────────────────────────────────────────╯
+
+ → Opened https://cloud.kaneo.app/device?user_code=WDJBMJHT
+
+"
+`;
+
+exports[`screens > login code at 120 columns, truecolor 1`] = `
+"
+
+ ╭─ Sign in to cloud.kaneo.app ───────────╮
+ │ │
+ │ Enter this code in your browser │
+ │ │
+ │ W D J B - M J H T │
+ │ │
+ │ ✓ Copied to your clipboard │
+ │ │
+ ╰────────────────────────────────────────╯
+
+ → Opened https://cloud.kaneo.app/device?user_code=WDJBMJHT
+
+"
+`;
+
+exports[`screens > login welcome at 80 columns, no color 1`] = `
+"
+
+ ▄▄▄ ███ ▐█ ▗▟█▀
+ ███ ███ █▛▘ ▐█▄█▛ ▗▄██▙▟█ ▟█▟██▙ ▄███▄▖ ▄▟██▙▄
+ ███ ███ █▖ ▐█▜█▄ ██ ▜█ ██ ▝█▌▟█▄▄▄██▐█▌ ▝█▌
+ ███ ███ ██▙ ▐█ ▀█▙▖▜█▄ ▄▟█ ██ █▌▐█▙ ▗▄▖▝█▙▖▗▟█▘
+ ███ ███ ▀▀▀ ▝▀ ▀▀ ▝▀▀▀▝▀ ▀▀ ▀▘ ▝▀▀▀▀ ▀▀▀▀
+ ▀▀▀
+
+ ✓ Signed in as Ada Lovelace · [email protected]
+
+ Server cloud.kaneo.app
+ Workspace Acme Studio
+
+ Try kaneo task list or just kaneo
+
+"
+`;
+
+exports[`screens > login welcome at 80 columns, truecolor 1`] = `
+"
+
+ ▄▄▄ ███ ▐█ ▗▟█▀
+ ███ ███ █▛▘ ▐█▄█▛ ▗▄██▙▟█ ▟█▟██▙ ▄███▄▖ ▄▟██▙▄
+ ███ ███ █▖ ▐█▜█▄ ██ ▜█ ██ ▝█▌▟█▄▄▄██▐█▌ ▝█▌
+ ███ ███ ██▙ ▐█ ▀█▙▖▜█▄ ▄▟█ ██ █▌▐█▙ ▗▄▖▝█▙▖▗▟█▘
+ ███ ███ ▀▀▀ ▝▀ ▀▀ ▝▀▀▀▝▀ ▀▀ ▀▘ ▝▀▀▀▀ ▀▀▀▀
+ ▀▀▀
+
+ ✓ Signed in as Ada Lovelace · [email protected]
+
+ Server  cloud.kaneo.app
+ Workspace  Acme Studio
+
+ Try kaneo task list or just kaneo
+
+"
+`;
+
+exports[`screens > login welcome at 120 columns, no color 1`] = `
+"
+
+ ▄▄▄ ███ ▐█ ▗▟█▀
+ ███ ███ █▛▘ ▐█▄█▛ ▗▄██▙▟█ ▟█▟██▙ ▄███▄▖ ▄▟██▙▄
+ ███ ███ █▖ ▐█▜█▄ ██ ▜█ ██ ▝█▌▟█▄▄▄██▐█▌ ▝█▌
+ ███ ███ ██▙ ▐█ ▀█▙▖▜█▄ ▄▟█ ██ █▌▐█▙ ▗▄▖▝█▙▖▗▟█▘
+ ███ ███ ▀▀▀ ▝▀ ▀▀ ▝▀▀▀▝▀ ▀▀ ▀▘ ▝▀▀▀▀ ▀▀▀▀
+ ▀▀▀
+
+ ✓ Signed in as Ada Lovelace · [email protected]
+
+ Server cloud.kaneo.app
+ Workspace Acme Studio
+
+ Try kaneo task list or just kaneo
+
+"
+`;
+
+exports[`screens > login welcome at 120 columns, truecolor 1`] = `
+"
+
+ ▄▄▄ ███ ▐█ ▗▟█▀
+ ███ ███ █▛▘ ▐█▄█▛ ▗▄██▙▟█ ▟█▟██▙ ▄███▄▖ ▄▟██▙▄
+ ███ ███ █▖ ▐█▜█▄ ██ ▜█ ██ ▝█▌▟█▄▄▄██▐█▌ ▝█▌
+ ███ ███ ██▙ ▐█ ▀█▙▖▜█▄ ▄▟█ ██ █▌▐█▙ ▗▄▖▝█▙▖▗▟█▘
+ ███ ███ ▀▀▀ ▝▀ ▀▀ ▝▀▀▀▝▀ ▀▀ ▀▘ ▝▀▀▀▀ ▀▀▀▀
+ ▀▀▀
+
+ ✓ Signed in as Ada Lovelace · [email protected]
+
+ Server  cloud.kaneo.app
+ Workspace  Acme Studio
+
+ Try kaneo task list or just kaneo
+
+"
+`;
+
+exports[`screens > task list at 80 columns in ascii 1`] = `
+"
+
+ Kaneo Web - KAN
+
+ * To Do 3
+ KAN-3 Add keyboard shortcuts for moving... = Medium Sun
+ KAN-4 Dark mode polish _ Low Ada Lovelace
+ KAN-5 Write CLI docs Oct 27
+
+ * In Progress 2
+ KAN-1 Fix login redirect after device ap... ! Urgent Ada Lovelace Oct 5
+ KAN-2 Board performance with 5000 tasks # High Grace Hopper Today
+
+ * In Review 1
+ KAN-6 Review API error shape # High Ada Lovelace
+
+ * Done 1
+ KAN-7 Ship v2.35 = Medium Oct 2
+
+ Showing 7 of 12 tasks. Pass --limit to see more.
+
+"
+`;
+
+exports[`screens > task list at 80 columns, no color 1`] = `
+"
+
+ Kaneo Web · KAN
+
+ ● To Do 3
+ KAN-3 Add keyboard shortcuts for moving… ▄ Medium ◷ Sun
+ KAN-4 Dark mode polish ▂ Low Ada Lovelace
+ KAN-5 Write CLI docs ◷ Oct 27
+
+ ● In Progress 2
+ KAN-1 Fix login redirect after device ap… ▲ Urgent Ada Lovelace ◷ Oct 5
+ KAN-2 Board performance with 5000 tasks ▆ High Grace Hopper ◷ Today
+
+ ● In Review 1
+ KAN-6 Review API error shape ▆ High Ada Lovelace
+
+ ● Done 1
+ KAN-7 Ship v2.35 ▄ Medium ◷ Oct 2
+
+ Showing 7 of 12 tasks. Pass --limit to see more.
+
+"
+`;
+
+exports[`screens > task list at 80 columns, truecolor 1`] = `
+"
+
+ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/board\\Kaneo Web]8;;\\ · KAN
+
+ ● To Do 3
+ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t3\\KAN-3]8;;\\ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t3\\Add keyboard shortcuts for moving…]8;;\\ ▄ Medium ◷ Sun
+ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t4\\KAN-4]8;;\\ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t4\\Dark mode polish]8;;\\ ▂ Low Ada Lovelace
+ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t5\\KAN-5]8;;\\ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t5\\Write CLI docs]8;;\\ ◷ Oct 27
+
+ ● In Progress 2
+ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t1\\KAN-1]8;;\\ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t1\\Fix login redirect after device ap…]8;;\\ ▲ Urgent Ada Lovelace ◷ Oct 5
+ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t2\\KAN-2]8;;\\ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t2\\Board performance with 5000 tasks]8;;\\ ▆ High Grace Hopper ◷ Today
+
+ ● In Review 1
+ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t6\\KAN-6]8;;\\ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t6\\Review API error shape]8;;\\ ▆ High Ada Lovelace
+
+ ● Done 1
+ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t7\\KAN-7]8;;\\ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t7\\Ship v2.35]8;;\\ ▄ Medium ◷ Oct 2
+
+ Showing 7 of 12 tasks. Pass --limit to see more.
+
+"
+`;
+
+exports[`screens > task list at 120 columns, no color 1`] = `
+"
+
+ Kaneo Web · KAN
+
+ ● To Do 3
+ KAN-3 Add keyboard shortcuts for moving cards between columns on the board view ▄ Medium ◷ Sun
+ KAN-4 Dark mode polish ▂ Low Ada Lovelace
+ KAN-5 Write CLI docs ◷ Oct 27
+
+ ● In Progress 2
+ KAN-1 Fix login redirect after device approval ▲ Urgent Ada Lovelace ◷ Oct 5
+ KAN-2 Board performance with 5000 tasks ▆ High Grace Hopper ◷ Today
+
+ ● In Review 1
+ KAN-6 Review API error shape ▆ High Ada Lovelace
+
+ ● Done 1
+ KAN-7 Ship v2.35 ▄ Medium ◷ Oct 2
+
+ Showing 7 of 12 tasks. Pass --limit to see more.
+
+"
+`;
+
+exports[`screens > task list at 120 columns, truecolor 1`] = `
+"
+
+ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/board\\Kaneo Web]8;;\\ · KAN
+
+ ● To Do 3
+ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t3\\KAN-3]8;;\\ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t3\\Add keyboard shortcuts for moving cards between columns on the board view]8;;\\ ▄ Medium ◷ Sun
+ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t4\\KAN-4]8;;\\ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t4\\Dark mode polish]8;;\\ ▂ Low Ada Lovelace
+ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t5\\KAN-5]8;;\\ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t5\\Write CLI docs]8;;\\ ◷ Oct 27
+
+ ● In Progress 2
+ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t1\\KAN-1]8;;\\ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t1\\Fix login redirect after device approval]8;;\\ ▲ Urgent Ada Lovelace ◷ Oct 5
+ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t2\\KAN-2]8;;\\ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t2\\Board performance with 5000 tasks]8;;\\ ▆ High Grace Hopper ◷ Today
+
+ ● In Review 1
+ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t6\\KAN-6]8;;\\ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t6\\Review API error shape]8;;\\ ▆ High Ada Lovelace
+
+ ● Done 1
+ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t7\\KAN-7]8;;\\ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t7\\Ship v2.35]8;;\\ ▄ Medium ◷ Oct 2
+
+ Showing 7 of 12 tasks. Pass --limit to see more.
+
+"
+`;
+
+exports[`screens > task list empty at 80 columns, no color 1`] = `
+"
+
+ Kaneo Web · KAN
+
+ No tasks match.
+
+"
+`;
+
+exports[`screens > task list empty at 80 columns, truecolor 1`] = `
+"
+
+ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/board\\Kaneo Web]8;;\\ · KAN
+
+ No tasks match.
+
+"
+`;
+
+exports[`screens > task list empty at 120 columns, no color 1`] = `
+"
+
+ Kaneo Web · KAN
+
+ No tasks match.
+
+"
+`;
+
+exports[`screens > task list empty at 120 columns, truecolor 1`] = `
+"
+
+ ]8;;https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/board\\Kaneo Web]8;;\\ · KAN
+
+ No tasks match.
+
+"
+`;
+
+exports[`screens > whoami at 80 columns, no color 1`] = `
+"
+
+ ✓ Ada Lovelace · [email protected]
+
+ Server cloud.kaneo.app
+ Auth login (default)
+ Workspace Acme Studio ws_1
+
+"
+`;
+
+exports[`screens > whoami at 80 columns, truecolor 1`] = `
+"
+
+ ✓ Ada Lovelace · [email protected]
+
+ Server  cloud.kaneo.app
+ Auth  login (default)
+ Workspace  Acme Studio ws_1
+
+"
+`;
+
+exports[`screens > whoami at 120 columns, no color 1`] = `
+"
+
+ ✓ Ada Lovelace · [email protected]
+
+ Server cloud.kaneo.app
+ Auth login (default)
+ Workspace Acme Studio ws_1
+
+"
+`;
+
+exports[`screens > whoami at 120 columns, truecolor 1`] = `
+"
+
+ ✓ Ada Lovelace · [email protected]
+
+ Server  cloud.kaneo.app
+ Auth  login (default)
+ Workspace  Acme Studio ws_1
+
+"
+`;
diff --git a/packages/cli/src/screens/__snapshots__/task-view.test.ts.snap b/packages/cli/src/screens/__snapshots__/task-view.test.ts.snap
new file mode 100644
index 000000000..7fe675353
--- /dev/null
+++ b/packages/cli/src/screens/__snapshots__/task-view.test.ts.snap
@@ -0,0 +1,249 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`task view screen > fully loaded task at 80 columns, no color 1`] = `
+"
+
+ KAN-12 Fix login redirect after device approval
+
+ Status ● In Progress
+ Priority ▲ Urgent
+ Assignee Ada Lovelace
+ Labels ● bug ● auth
+ Due ◷ Fri
+ Start Oct 1
+ Created Sep 29
+ Time 3h · ● Timer running (Ada Lovelace)
+ Project Kaneo Web · KAN
+ Parent ● KAN-4 Auth overhaul
+
+ Steps
+
+ 1. Sign in with the device flow
+ 2. Approve in the browser
+
+ [image: Redirect loop]
+
+ Subtasks 2 of 5 done
+ ● KAN-13 Reproduce on Safari ✓
+ ● KAN-14 Add a regression test ✓
+ ● KAN-15 Handle expired device codes
+ ● KAN-16 Update the login docs
+ ● KAN-17 Clean up the redirect helper and its callers
+
+ Relations
+ Blocks ● KAN-20 Release 2.36
+ Blocked by ● KAN-9 Session cookie on the API domain
+ Related ● MOB-3 Mobile sign in
+
+ Links
+ fix(auth): keep state on devic… github.com/usekaneo/kaneo/pull/1960 github
+ sentry.io/issues/4211
+
+ Custom fields
+ Story points 5
+ Platforms Web, CLI
+
+ Recent comments
+ Grace Hopper · Yesterday
+ It started with the cookie change.
+ The callback URL drops the state param when the device page redirects, so
+ the CLI never sees the approval and keeps polling until the code expires.
+
+ Ada Lovelace · 3h ago · edited
+ First pass is up, please review.
+
+ Grace Hopper · 1h ago
+ Looks good. One question:
+ • do we still need the fallback?
+ • can we drop the retry? …
+
+ and 2 more, run kaneo comment list KAN-12
+
+"
+`;
+
+exports[`task view screen > fully loaded task at 80 columns, truecolor 1`] = `
+"
+
+ ]8;;https://kaneo.test/dashboard/workspace/ws_1/project/p1/task/t12\\KAN-12]8;;\\ Fix login redirect after device approval
+
+ Status  ● In Progress
+ Priority  ▲ Urgent
+ Assignee  Ada Lovelace
+ Labels  ● bug ● auth
+ Due  ◷ Fri
+ Start  Oct 1
+ Created  Sep 29
+ Time  3h · ● Timer running (Ada Lovelace)
+ Project  Kaneo Web · KAN
+ Parent  ● ]8;;https://kaneo.test/dashboard/workspace/ws_1/project/p1/task/t4\\KAN-4]8;;\\ Auth overhaul
+
+ Steps
+
+ 1. Sign in with the device flow
+ 2. Approve in the browser
+
+ [image: Redirect loop]
+
+ Subtasks 2 of 5 done
+ ● ]8;;https://kaneo.test/dashboard/workspace/ws_1/project/p1/task/t13\\KAN-13]8;;\\ Reproduce on Safari ✓
+ ● ]8;;https://kaneo.test/dashboard/workspace/ws_1/project/p1/task/t14\\KAN-14]8;;\\ Add a regression test ✓
+ ● ]8;;https://kaneo.test/dashboard/workspace/ws_1/project/p1/task/t15\\KAN-15]8;;\\ Handle expired device codes
+ ● ]8;;https://kaneo.test/dashboard/workspace/ws_1/project/p1/task/t16\\KAN-16]8;;\\ Update the login docs
+ ● ]8;;https://kaneo.test/dashboard/workspace/ws_1/project/p1/task/t17\\KAN-17]8;;\\ Clean up the redirect helper and its callers
+
+ Relations
+ Blocks ● ]8;;https://kaneo.test/dashboard/workspace/ws_1/project/p1/task/t20\\KAN-20]8;;\\ Release 2.36
+ Blocked by ● ]8;;https://kaneo.test/dashboard/workspace/ws_1/project/p1/task/t9\\KAN-9]8;;\\ Session cookie on the API domain
+ Related ● ]8;;https://kaneo.test/dashboard/workspace/ws_1/project/p2/task/m3\\MOB-3]8;;\\ Mobile sign in
+
+ Links
+ ]8;;https://github.com/usekaneo/kaneo/pull/1960\\fix(auth): keep state on devic…]8;;\\ ]8;;https://github.com/usekaneo/kaneo/pull/1960\\github.com/usekaneo/kaneo/pull/1960]8;;\\ github
+ ]8;;https://sentry.io/issues/4211/\\sentry.io/issues/4211]8;;\\
+
+ Custom fields
+ Story points 5
+ Platforms Web, CLI
+
+ Recent comments
+ Grace Hopper · Yesterday
+ It started with the cookie change.
+ The callback URL drops the state param when the device page redirects, so
+ the CLI never sees the approval and keeps polling until the code expires.
+
+ Ada Lovelace · 3h ago · edited
+ First pass is up, please review.
+
+ Grace Hopper · 1h ago
+ Looks good. One question:
+ • do we still need the fallback?
+ • can we drop the retry? …
+
+ and 2 more, run kaneo comment list KAN-12
+
+"
+`;
+
+exports[`task view screen > fully loaded task at 120 columns, no color 1`] = `
+"
+
+ KAN-12 Fix login redirect after device approval
+
+ Status ● In Progress
+ Priority ▲ Urgent
+ Assignee Ada Lovelace
+ Labels ● bug ● auth
+ Due ◷ Fri
+ Start Oct 1
+ Created Sep 29
+ Time 3h · ● Timer running (Ada Lovelace)
+ Project Kaneo Web · KAN
+ Parent ● KAN-4 Auth overhaul
+
+ Steps
+
+ 1. Sign in with the device flow
+ 2. Approve in the browser
+
+ [image: Redirect loop]
+
+ Subtasks 2 of 5 done
+ ● KAN-13 Reproduce on Safari ✓
+ ● KAN-14 Add a regression test ✓
+ ● KAN-15 Handle expired device codes
+ ● KAN-16 Update the login docs
+ ● KAN-17 Clean up the redirect helper and its callers
+
+ Relations
+ Blocks ● KAN-20 Release 2.36
+ Blocked by ● KAN-9 Session cookie on the API domain
+ Related ● MOB-3 Mobile sign in
+
+ Links
+ fix(auth): keep state on device redirect github.com/usekaneo/kaneo/pull/1960 github
+ sentry.io/issues/4211
+
+ Custom fields
+ Story points 5
+ Platforms Web, CLI
+
+ Recent comments
+ Grace Hopper · Yesterday
+ It started with the cookie change.
+ The callback URL drops the state param when the device page redirects, so the CLI never sees the approval and
+ keeps polling until the code expires.
+
+ Ada Lovelace · 3h ago · edited
+ First pass is up, please review.
+
+ Grace Hopper · 1h ago
+ Looks good. One question:
+ • do we still need the fallback?
+ • can we drop the retry? …
+
+ and 2 more, run kaneo comment list KAN-12
+
+"
+`;
+
+exports[`task view screen > fully loaded task at 120 columns, truecolor 1`] = `
+"
+
+ ]8;;https://kaneo.test/dashboard/workspace/ws_1/project/p1/task/t12\\KAN-12]8;;\\ Fix login redirect after device approval
+
+ Status  ● In Progress
+ Priority  ▲ Urgent
+ Assignee  Ada Lovelace
+ Labels  ● bug ● auth
+ Due  ◷ Fri
+ Start  Oct 1
+ Created  Sep 29
+ Time  3h · ● Timer running (Ada Lovelace)
+ Project  Kaneo Web · KAN
+ Parent  ● ]8;;https://kaneo.test/dashboard/workspace/ws_1/project/p1/task/t4\\KAN-4]8;;\\ Auth overhaul
+
+ Steps
+
+ 1. Sign in with the device flow
+ 2. Approve in the browser
+
+ [image: Redirect loop]
+
+ Subtasks 2 of 5 done
+ ● ]8;;https://kaneo.test/dashboard/workspace/ws_1/project/p1/task/t13\\KAN-13]8;;\\ Reproduce on Safari ✓
+ ● ]8;;https://kaneo.test/dashboard/workspace/ws_1/project/p1/task/t14\\KAN-14]8;;\\ Add a regression test ✓
+ ● ]8;;https://kaneo.test/dashboard/workspace/ws_1/project/p1/task/t15\\KAN-15]8;;\\ Handle expired device codes
+ ● ]8;;https://kaneo.test/dashboard/workspace/ws_1/project/p1/task/t16\\KAN-16]8;;\\ Update the login docs
+ ● ]8;;https://kaneo.test/dashboard/workspace/ws_1/project/p1/task/t17\\KAN-17]8;;\\ Clean up the redirect helper and its callers
+
+ Relations
+ Blocks ● ]8;;https://kaneo.test/dashboard/workspace/ws_1/project/p1/task/t20\\KAN-20]8;;\\ Release 2.36
+ Blocked by ● ]8;;https://kaneo.test/dashboard/workspace/ws_1/project/p1/task/t9\\KAN-9]8;;\\ Session cookie on the API domain
+ Related ● ]8;;https://kaneo.test/dashboard/workspace/ws_1/project/p2/task/m3\\MOB-3]8;;\\ Mobile sign in
+
+ Links
+ ]8;;https://github.com/usekaneo/kaneo/pull/1960\\fix(auth): keep state on device redirect]8;;\\ ]8;;https://github.com/usekaneo/kaneo/pull/1960\\github.com/usekaneo/kaneo/pull/1960]8;;\\ github
+ ]8;;https://sentry.io/issues/4211/\\sentry.io/issues/4211]8;;\\
+
+ Custom fields
+ Story points 5
+ Platforms Web, CLI
+
+ Recent comments
+ Grace Hopper · Yesterday
+ It started with the cookie change.
+ The callback URL drops the state param when the device page redirects, so the CLI never sees the approval and
+ keeps polling until the code expires.
+
+ Ada Lovelace · 3h ago · edited
+ First pass is up, please review.
+
+ Grace Hopper · 1h ago
+ Looks good. One question:
+ • do we still need the fallback?
+ • can we drop the retry? …
+
+ and 2 more, run kaneo comment list KAN-12
+
+"
+`;
diff --git a/packages/cli/src/screens/screens.test.ts b/packages/cli/src/screens/screens.test.ts
new file mode 100644
index 000000000..b2ec16a88
--- /dev/null
+++ b/packages/cli/src/screens/screens.test.ts
@@ -0,0 +1,204 @@
+import { describe, expect, it } from "vite-plus/test";
+import { renderHome } from "../commands/home.js";
+import { renderDeviceCode, renderWelcome } from "../commands/login.js";
+import { renderWhoami } from "../commands/whoami.js";
+import { renderFailure } from "../output/report-failure.js";
+import type { ColorLevel } from "../render/capabilities.js";
+import { makeUi } from "../render/ui.js";
+import {
+ renderTaskList,
+ type TaskListView,
+} from "../tasks/render-task-list.js";
+import type { TaskJson } from "../tasks/task-json.js";
+
+const now = new Date(2026, 9, 7, 12, 0, 0);
+const day = (offset: number) =>
+ new Date(2026, 9, 7 + offset, 12, 0, 0).toISOString();
+
+const user = {
+ id: "u1",
+ name: "Ada Lovelace",
+ email: "[email protected]",
+ image: null,
+ role: null,
+};
+
+const workspace = {
+ id: "ws_1",
+ name: "Acme Studio",
+ slug: "acme-studio",
+ logo: null,
+ description: null,
+ createdAt: day(-30),
+ role: "owner",
+};
+
+function task(
+ number: number,
+ title: string,
+ status: string,
+ priority: string,
+ options: { due?: number; assignee?: string } = {},
+): TaskJson {
+ return {
+ id: `t${number}`,
+ ticketId: `KAN-${number}`,
+ number,
+ title,
+ status,
+ statusName: status,
+ priority,
+ assignee: options.assignee ? { id: "u1", name: options.assignee } : null,
+ dueDate: options.due === undefined ? null : day(options.due),
+ startDate: null,
+ createdAt: day(-10),
+ projectId: "p1",
+ workspaceId: "ws_1",
+ url: `https://cloud.kaneo.app/dashboard/workspace/ws_1/project/p1/task/t${number}`,
+ };
+}
+
+const board: TaskListView = {
+ projectName: "Kaneo Web",
+ projectSlug: "kan",
+ projectId: "p1",
+ workspaceId: "ws_1",
+ webUrl: "https://cloud.kaneo.app",
+ columns: [
+ { slug: "to-do", name: "To Do", isFinal: false },
+ { slug: "in-progress", name: "In Progress", isFinal: false },
+ { slug: "in-review", name: "In Review", isFinal: false },
+ { slug: "done", name: "Done", isFinal: true },
+ ],
+ tasks: [
+ task(
+ 3,
+ "Add keyboard shortcuts for moving cards between columns on the board view",
+ "to-do",
+ "medium",
+ { due: 4 },
+ ),
+ task(4, "Dark mode polish", "to-do", "low", { assignee: "Ada Lovelace" }),
+ task(5, "Write CLI docs", "to-do", "no-priority", { due: 20 }),
+ task(
+ 1,
+ "Fix login redirect after device approval",
+ "in-progress",
+ "urgent",
+ { due: -2, assignee: "Ada Lovelace" },
+ ),
+ task(2, "Board performance with 5000 tasks", "in-progress", "high", {
+ due: 0,
+ assignee: "Grace Hopper",
+ }),
+ task(6, "Review API error shape", "in-review", "high", {
+ assignee: "Ada Lovelace",
+ }),
+ task(7, "Ship v2.35", "done", "medium", { due: -5 }),
+ ],
+ total: 12,
+ now,
+};
+
+const screens = {
+ "task list": (ui: ReturnType<typeof makeUi>) => renderTaskList(ui, board),
+ "task list empty": (ui: ReturnType<typeof makeUi>) =>
+ renderTaskList(ui, { ...board, tasks: [], total: 0 }),
+ home: (ui: ReturnType<typeof makeUi>) =>
+ renderHome(
+ ui,
+ {
+ signedIn: true,
+ apiUrl: "https://cloud.kaneo.app",
+ user,
+ workspace,
+ tasks: board.tasks.slice(3, 6).map((item) => ({
+ id: item.id,
+ projectId: "p1",
+ number: item.number,
+ title: item.title,
+ status: item.status,
+ statusName: item.statusName,
+ priority: item.priority,
+ dueDate: item.dueDate,
+ projectName: "Kaneo Web",
+ projectSlug: "kan",
+ })),
+ totalTasks: 3,
+ },
+ now,
+ ),
+ "home signed out": (ui: ReturnType<typeof makeUi>) =>
+ renderHome(ui, {
+ signedIn: false,
+ apiUrl: "https://cloud.kaneo.app",
+ user: null,
+ workspace: null,
+ tasks: [],
+ totalTasks: 0,
+ }),
+ "login code": (ui: ReturnType<typeof makeUi>) =>
+ renderDeviceCode(ui, {
+ apiUrl: "https://cloud.kaneo.app",
+ code: "WDJB-MJHT",
+ url: "https://cloud.kaneo.app/device?user_code=WDJBMJHT",
+ copied: true,
+ opened: true,
+ expiresInSeconds: 1800,
+ }),
+ "login welcome": (ui: ReturnType<typeof makeUi>) =>
+ renderWelcome(ui, {
+ user,
+ apiUrl: "https://cloud.kaneo.app",
+ profile: "default",
+ workspace,
+ }),
+ whoami: (ui: ReturnType<typeof makeUi>) =>
+ renderWhoami(ui, {
+ user,
+ apiUrl: "https://cloud.kaneo.app",
+ profile: "default",
+ auth: "login",
+ workspace,
+ }),
+ error: (ui: ReturnType<typeof makeUi>) =>
+ renderFailure(ui, {
+ message: "You are not signed in to cloud.kaneo.app.",
+ hint: "Run kaneo login, or set KANEO_API_KEY.",
+ }),
+};
+
+const variants: ReadonlyArray<{ columns: number; color: ColorLevel }> = [
+ { columns: 80, color: 0 },
+ { columns: 120, color: 0 },
+ { columns: 80, color: 3 },
+ { columns: 120, color: 3 },
+];
+
+describe("screens", () => {
+ for (const [name, render] of Object.entries(screens)) {
+ for (const { columns, color } of variants) {
+ it(`${name} at ${columns} columns, ${color === 0 ? "no color" : "truecolor"}`, () => {
+ const ui = makeUi({
+ color,
+ unicode: true,
+ hyperlinks: color > 0,
+ animate: false,
+ columns,
+ });
+ expect(`\n${render(ui).join("\n")}\n`).toMatchSnapshot();
+ });
+ }
+ }
+
+ it("task list at 80 columns in ascii", () => {
+ const ui = makeUi({
+ color: 0,
+ unicode: false,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+ });
+ expect(`\n${renderTaskList(ui, board).join("\n")}\n`).toMatchSnapshot();
+ });
+});
diff --git a/packages/cli/src/screens/task-view.test.ts b/packages/cli/src/screens/task-view.test.ts
new file mode 100644
index 000000000..4bc8cf073
--- /dev/null
+++ b/packages/cli/src/screens/task-view.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { ColorLevel } from "../render/capabilities.js";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import { renderTaskView } from "../task-view/render-task-view.js";
+import { toTaskViewJson } from "../task-view/task-view-json.js";
+import {
+ projectSlugsFixture,
+ resolvedTask,
+ sectionsFixture,
+ viewNow,
+ webUrl,
+} from "../task-view/test-task-view.js";
+
+const task = toTaskViewJson({
+ resolved: resolvedTask,
+ sections: sectionsFixture,
+ projectSlugs: projectSlugsFixture,
+ webUrl,
+ commentLimit: 3,
+ now: viewNow,
+});
+
+const variants: ReadonlyArray<{ columns: number; color: ColorLevel }> = [
+ { columns: 80, color: 0 },
+ { columns: 120, color: 0 },
+ { columns: 80, color: 3 },
+ { columns: 120, color: 3 },
+];
+
+describe("task view screen", () => {
+ for (const { columns, color } of variants) {
+ it(`fully loaded task at ${columns} columns, ${color === 0 ? "no color" : "truecolor"}`, () => {
+ const ui = makeUi({
+ color,
+ unicode: true,
+ hyperlinks: color > 0,
+ animate: false,
+ columns,
+ });
+ const lines = renderTaskView(ui, {
+ task,
+ statusFinal: false,
+ now: viewNow,
+ commentTotal: 5,
+ });
+ for (const line of lines) {
+ expect(stringWidth(line)).toBeLessThanOrEqual(columns);
+ }
+ expect(`\n${lines.join("\n")}\n`).toMatchSnapshot();
+ });
+ }
+});
diff --git a/packages/cli/src/search/ask-query.ts b/packages/cli/src/search/ask-query.ts
new file mode 100644
index 000000000..2b05c27b3
--- /dev/null
+++ b/packages/cli/src/search/ask-query.ts
@@ -0,0 +1,30 @@
+import { Effect } from "effect";
+import { Prompt } from "effect/cli";
+import { Cancelled } from "../errors/errors.js";
+import { Output } from "../output/output.js";
+import { themeCodes } from "../render/theme.js";
+
+export const askQuery = Effect.fnUntraced(function* () {
+ const output = yield* Output;
+ const { glyphs, caps } = output.ui;
+ const codes = themeCodes(caps.color);
+ return yield* Prompt.run(
+ Prompt.String({
+ message: "Search for",
+ validate: (value) =>
+ value.trim() === ""
+ ? Effect.fail("Type a few words to search for")
+ : Effect.succeed(value.trim()),
+ theme: {
+ prefix: glyphs.diamond,
+ tick: glyphs.tick,
+ ellipsis: glyphs.ellipsis,
+ primaryColor: codes.bold,
+ mutedColor: codes.muted,
+ successColor: codes.success,
+ errorColor: codes.danger,
+ submittedColor: "",
+ },
+ }),
+ ).pipe(Effect.catchTag("QuitError", () => Effect.fail(new Cancelled())));
+});
diff --git a/packages/cli/src/search/render-search.test.ts b/packages/cli/src/search/render-search.test.ts
new file mode 100644
index 000000000..a4c385099
--- /dev/null
+++ b/packages/cli/src/search/render-search.test.ts
@@ -0,0 +1,126 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import { renderSearch, statusLabel } from "./render-search.js";
+import type { SearchResultJson } from "./search-results.js";
+
+const ui = (columns: number) =>
+ makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns,
+ });
+
+function result(overrides: Partial<SearchResultJson>): SearchResultJson {
+ return {
+ type: "task",
+ id: "t1",
+ title: "Fix login redirect after device approval",
+ ticketId: "KAN-1",
+ status: "in-progress",
+ priority: "high",
+ snippet: null,
+ projectId: "p_kan",
+ projectKey: "KAN",
+ projectName: "Kaneo Web",
+ workspaceId: "ws_acme",
+ assignee: null,
+ author: null,
+ createdAt: "2026-10-07T19:19:55.746Z",
+ url: "https://kaneo.test/task/t1",
+ ...overrides,
+ };
+}
+
+const results: SearchResultJson[] = [
+ result({}),
+ result({
+ type: "project",
+ id: "p_kan",
+ title: "Kaneo Web",
+ ticketId: null,
+ status: null,
+ }),
+ result({
+ type: "comment",
+ id: "a1",
+ title: "Comment on Fix login redirect after device approval",
+ status: null,
+ snippet: "Still broken on Safari",
+ author: "Grace Hopper",
+ }),
+ result({
+ id: "t2",
+ ticketId: "KAN-6",
+ title: "Review API error shape",
+ status: "in-review",
+ }),
+];
+
+describe("statusLabel", () => {
+ it("turns a column slug into words", () => {
+ expect(statusLabel("in-progress")).toBe("In Progress");
+ expect(statusLabel("to_do")).toBe("To Do");
+ });
+});
+
+describe("renderSearch", () => {
+ it("groups results by kind at 80 columns", () => {
+ const lines = renderSearch(ui(80), {
+ query: "login",
+ results,
+ more: false,
+ limit: 20,
+ });
+ expect(lines).toEqual([
+ "",
+ " Tasks 2",
+ " KAN-1 Fix login redirect after device approval ● In Progress",
+ " KAN-6 Review API error shape ● In Review",
+ "",
+ " Projects 1",
+ " KAN Kaneo Web",
+ "",
+ " Comments 1",
+ " KAN-1 Still broken on Safari Grace Hopper",
+ "",
+ ]);
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(80);
+ });
+
+ it("never wraps on a narrow terminal", () => {
+ for (const line of renderSearch(ui(32), {
+ query: "login",
+ results,
+ more: false,
+ limit: 20,
+ })) {
+ expect(stringWidth(line)).toBeLessThanOrEqual(32);
+ }
+ });
+
+ it("points at --limit when there are more matches", () => {
+ const lines = renderSearch(ui(80), {
+ query: "login",
+ results,
+ more: true,
+ limit: 20,
+ });
+ expect(lines).toContain(
+ " There are more matches. Pass --limit (up to 50) to see more.",
+ );
+ });
+
+ it("says when nothing matched", () => {
+ expect(
+ renderSearch(ui(80), {
+ query: "zebra",
+ results: [],
+ more: false,
+ limit: 20,
+ }),
+ ).toEqual(["", ' No results for "zebra".', ""]);
+ });
+});
diff --git a/packages/cli/src/search/render-search.ts b/packages/cli/src/search/render-search.ts
new file mode 100644
index 000000000..f7024c3ea
--- /dev/null
+++ b/packages/cli/src/search/render-search.ts
@@ -0,0 +1,151 @@
+import { type Cell, text } from "../render/cell.js";
+import { type Column, renderTable } from "../render/table.js";
+import { statusDot } from "../render/task-format.js";
+import type { Ui } from "../render/ui.js";
+import {
+ RESULT_TYPES,
+ type SearchResultJson,
+ type SearchResultType,
+} from "./search-results.js";
+
+export type SearchScreen = {
+ readonly query: string;
+ readonly results: ReadonlyArray<SearchResultJson>;
+ readonly more: boolean;
+ readonly limit: number;
+};
+
+const HEADINGS: Readonly<Record<SearchResultType, string>> = {
+ task: "Tasks",
+ project: "Projects",
+ comment: "Comments",
+ activity: "Activity",
+ workspace: "Workspaces",
+};
+
+export function statusLabel(slug: string): string {
+ return slug
+ .split(/[-_\s]+/u)
+ .filter(Boolean)
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
+ .join(" ");
+}
+
+function columnsFor(
+ ui: Ui,
+ type: SearchResultType,
+): Array<Column<SearchResultJson>> {
+ const { theme } = ui;
+ const reference: Column<SearchResultJson> = {
+ header: "ID",
+ cell: (result): Cell => [
+ text(
+ result.ticketId ?? result.projectKey ?? result.id.slice(0, 8),
+ theme.muted,
+ result.url ?? undefined,
+ ),
+ ],
+ };
+ switch (type) {
+ case "task":
+ return [
+ reference,
+ {
+ header: "Title",
+ flex: true,
+ minWidth: 16,
+ cell: (result) => [
+ text(result.title, undefined, result.url ?? undefined),
+ ],
+ },
+ {
+ header: "Status",
+ optional: true,
+ cell: (result) =>
+ result.status
+ ? [
+ statusDot(ui, result.status, false),
+ text(` ${statusLabel(result.status)}`, theme.muted),
+ ]
+ : [],
+ },
+ ];
+ case "project":
+ return [
+ reference,
+ {
+ header: "Name",
+ flex: true,
+ minWidth: 16,
+ cell: (result) => [
+ text(result.title, undefined, result.url ?? undefined),
+ ],
+ },
+ ];
+ case "workspace":
+ return [
+ {
+ header: "Name",
+ flex: true,
+ minWidth: 16,
+ cell: (result) => [
+ text(result.title, undefined, result.url ?? undefined),
+ ],
+ },
+ ];
+ case "comment":
+ case "activity":
+ return [
+ reference,
+ {
+ header: "Text",
+ flex: true,
+ minWidth: 16,
+ cell: (result) => [
+ text(
+ result.snippet ?? result.title,
+ undefined,
+ result.url ?? undefined,
+ ),
+ ],
+ },
+ {
+ header: "By",
+ optional: true,
+ cell: (result) =>
+ result.author ? [text(result.author, theme.muted)] : [],
+ },
+ ];
+ }
+}
+
+export function renderSearch(ui: Ui, screen: SearchScreen): string[] {
+ const { theme } = ui;
+ if (screen.results.length === 0) {
+ return ["", ` ${theme.muted(`No results for "${screen.query}".`)}`, ""];
+ }
+ const lines = [""];
+ for (const type of RESULT_TYPES) {
+ const group = screen.results.filter((result) => result.type === type);
+ if (group.length === 0) continue;
+ lines.push(
+ ` ${theme.strong(HEADINGS[type])} ${theme.muted(String(group.length))}`,
+ ...renderTable(ui, group, columnsFor(ui, type), {
+ width: ui.caps.columns,
+ indent: 4,
+ }),
+ "",
+ );
+ }
+ if (screen.more) {
+ lines.push(
+ ` ${theme.muted(
+ screen.limit < 50
+ ? "There are more matches. Pass --limit (up to 50) to see more."
+ : "There are more matches. Pass --type or -p to narrow the search.",
+ )}`,
+ "",
+ );
+ }
+ return lines;
+}
diff --git a/packages/cli/src/search/search-results.test.ts b/packages/cli/src/search/search-results.test.ts
new file mode 100644
index 000000000..b51fe472d
--- /dev/null
+++ b/packages/cli/src/search/search-results.test.ts
@@ -0,0 +1,199 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { SearchHit } from "../api/search.js";
+import {
+ normalizeSearchResults,
+ type SearchContext,
+ snippet,
+} from "./search-results.js";
+
+const context: SearchContext = {
+ type: "all",
+ workspaceId: "ws_acme",
+ workspaceSlug: "acme-studio",
+ webUrl: "https://kaneo.test",
+};
+
+const base = { createdAt: "2026-10-07T19:19:55.746Z", relevanceScore: 3 };
+
+const task: SearchHit = {
+ ...base,
+ id: "t1",
+ type: "task",
+ title: "Fix login redirect",
+ description: "<p>After the device approval</p>",
+ projectId: "p_kan",
+ projectName: "Kaneo Web",
+ projectSlug: "kan",
+ workspaceId: "ws_acme",
+ userName: "Ada Lovelace",
+ taskNumber: 1,
+ priority: "high",
+ status: "in-progress",
+};
+
+const project: SearchHit = {
+ ...base,
+ id: "p_kan",
+ type: "project",
+ title: "Kaneo Web",
+ projectId: "p_kan",
+ projectSlug: "kan",
+ workspaceId: "ws_acme",
+};
+
+const comment: SearchHit = {
+ ...base,
+ id: "a1",
+ type: "comment",
+ title: "Comment on Fix login redirect",
+ content: "Still broken on Safari",
+ projectId: "p_kan",
+ projectSlug: "kan",
+ workspaceId: "ws_acme",
+ userName: "Grace Hopper",
+ taskNumber: 1,
+};
+
+const activity: SearchHit = {
+ ...base,
+ id: "a2",
+ type: "activity",
+ title: "status_changed on Fix login redirect",
+ content: "changed status from To Do to In Progress",
+ projectId: "p_kan",
+ projectSlug: "kan",
+ workspaceId: "ws_acme",
+ userName: "Ada Lovelace",
+ taskNumber: 1,
+};
+
+const ownWorkspace: SearchHit = {
+ ...base,
+ id: "ws_acme",
+ type: "workspace",
+ title: "Acme Studio",
+ workspaceId: "ws_acme",
+};
+
+const otherWorkspace: SearchHit = {
+ ...base,
+ id: "ws_side",
+ type: "workspace",
+ title: "Side Project",
+ workspaceId: "ws_side",
+};
+
+describe("normalizeSearchResults", () => {
+ it("maps a task to the stable result shape", () => {
+ expect(normalizeSearchResults([task], context)).toEqual([
+ {
+ type: "task",
+ id: "t1",
+ title: "Fix login redirect",
+ ticketId: "KAN-1",
+ status: "in-progress",
+ priority: "high",
+ snippet: "After the device approval",
+ projectId: "p_kan",
+ projectKey: "KAN",
+ projectName: "Kaneo Web",
+ workspaceId: "ws_acme",
+ assignee: "Ada Lovelace",
+ author: null,
+ createdAt: "2026-10-07T19:19:55.746Z",
+ url: "https://kaneo.test/dashboard/workspace/ws_acme/project/p_kan/task/t1",
+ },
+ ]);
+ });
+
+ it("drops results from other workspaces and duplicates", () => {
+ const results = normalizeSearchResults(
+ [task, ownWorkspace, otherWorkspace, ownWorkspace, task],
+ context,
+ );
+ expect(results.map((result) => `${result.type}:${result.id}`)).toEqual([
+ "task:t1",
+ "workspace:ws_acme",
+ ]);
+ });
+
+ it("keeps only the requested kind, even when the server mixes comments into activity", () => {
+ const results = normalizeSearchResults([task, comment, activity], {
+ ...context,
+ type: "activities",
+ });
+ expect(results.map((result) => result.id)).toEqual(["a2"]);
+ });
+
+ it("links comments and activity to the task through its ticket id", () => {
+ const [first, second] = normalizeSearchResults(
+ [comment, activity],
+ context,
+ );
+ expect(first).toMatchObject({
+ ticketId: "KAN-1",
+ snippet: "Still broken on Safari",
+ author: "Grace Hopper",
+ assignee: null,
+ url: "https://kaneo.test/acme-studio/task/KAN-1",
+ });
+ expect(second?.snippet).toBe("changed status from To Do to In Progress");
+ });
+
+ it("falls back to the project board when the workspace slug is unknown", () => {
+ const [result] = normalizeSearchResults([comment], {
+ ...context,
+ workspaceSlug: null,
+ });
+ expect(result?.url).toBe(
+ "https://kaneo.test/dashboard/workspace/ws_acme/project/p_kan/board",
+ );
+ });
+
+ it("links projects and workspaces", () => {
+ const results = normalizeSearchResults([project, ownWorkspace], context);
+ expect(results.map((result) => result.url)).toEqual([
+ "https://kaneo.test/dashboard/workspace/ws_acme/project/p_kan/board",
+ "https://kaneo.test/dashboard/workspace/ws_acme",
+ ]);
+ expect(results[0]).toMatchObject({ projectKey: "KAN", ticketId: null });
+ });
+
+ it("keeps only results from the project passed with -p", () => {
+ const elsewhere: SearchHit = {
+ ...project,
+ id: "p_mob",
+ projectId: "p_mob",
+ projectSlug: "mob",
+ };
+ const results = normalizeSearchResults(
+ [task, project, elsewhere, ownWorkspace, comment],
+ {
+ ...context,
+ projectId: "p_kan",
+ },
+ );
+ expect(results.map((result) => `${result.type}:${result.id}`)).toEqual([
+ "task:t1",
+ "project:p_kan",
+ "comment:a1",
+ ]);
+ });
+
+ it("ignores result kinds this CLI does not know yet", () => {
+ expect(
+ normalizeSearchResults([{ ...task, type: "document" }], context),
+ ).toEqual([]);
+ });
+});
+
+describe("snippet", () => {
+ it("flattens text and cuts long values", () => {
+ expect(snippet(undefined)).toBeNull();
+ expect(snippet(" \n ")).toBeNull();
+ expect(snippet("one\n\ntwo")).toBe("one two");
+ const long = snippet("x".repeat(300));
+ expect(long).toHaveLength(200);
+ expect(long?.endsWith("…")).toBe(true);
+ });
+});
diff --git a/packages/cli/src/search/search-results.ts b/packages/cli/src/search/search-results.ts
new file mode 100644
index 000000000..3af58b108
--- /dev/null
+++ b/packages/cli/src/search/search-results.ts
@@ -0,0 +1,155 @@
+import type { SearchHit, SearchType } from "../api/search.js";
+import { plainText } from "../projects/description-preview.js";
+import { projectUrl, taskUrl } from "../render/links.js";
+import { ticketId } from "../render/task-format.js";
+
+export const RESULT_TYPES = [
+ "task",
+ "project",
+ "comment",
+ "activity",
+ "workspace",
+] as const;
+export type SearchResultType = (typeof RESULT_TYPES)[number];
+
+export type SearchResultJson = {
+ readonly type: SearchResultType;
+ readonly id: string;
+ readonly title: string;
+ readonly ticketId: string | null;
+ readonly status: string | null;
+ readonly priority: string | null;
+ readonly snippet: string | null;
+ readonly projectId: string | null;
+ readonly projectKey: string | null;
+ readonly projectName: string | null;
+ readonly workspaceId: string;
+ readonly assignee: string | null;
+ readonly author: string | null;
+ readonly createdAt: string;
+ readonly url: string | null;
+};
+
+export type SearchContext = {
+ readonly type: SearchType;
+ readonly workspaceId: string;
+ readonly workspaceSlug: string | null;
+ readonly projectId?: string | undefined;
+ readonly webUrl: string;
+};
+
+const ALLOWED: Readonly<Record<SearchType, ReadonlyArray<SearchResultType>>> = {
+ all: RESULT_TYPES,
+ tasks: ["task"],
+ projects: ["project"],
+ workspaces: ["workspace"],
+ comments: ["comment"],
+ activities: ["activity"],
+};
+
+const SNIPPET_LENGTH = 200;
+
+export function snippet(value: string | undefined): string | null {
+ if (!value) return null;
+ const flat = plainText(value).replace(/\s+/gu, " ").trim();
+ if (flat === "") return null;
+ const characters = [...flat];
+ return characters.length > SNIPPET_LENGTH
+ ? `${characters
+ .slice(0, SNIPPET_LENGTH - 1)
+ .join("")
+ .trimEnd()}…`
+ : flat;
+}
+
+function isResultType(type: string): type is SearchResultType {
+ return (RESULT_TYPES as ReadonlyArray<string>).includes(type);
+}
+
+function resultUrl(
+ type: SearchResultType,
+ hit: SearchHit,
+ ticket: string | null,
+ context: SearchContext,
+): string | null {
+ const { webUrl, workspaceId, workspaceSlug } = context;
+ switch (type) {
+ case "task":
+ return hit.projectId
+ ? taskUrl(webUrl, { workspaceId, projectId: hit.projectId, id: hit.id })
+ : null;
+ case "project":
+ return projectUrl(webUrl, { workspaceId, id: hit.id });
+ case "workspace":
+ return `${webUrl}/dashboard/workspace/${hit.id}`;
+ case "comment":
+ case "activity":
+ if (ticket && workspaceSlug) {
+ return `${webUrl}/${encodeURIComponent(workspaceSlug)}/task/${encodeURIComponent(ticket)}`;
+ }
+ return hit.projectId
+ ? projectUrl(webUrl, { workspaceId, id: hit.projectId })
+ : null;
+ }
+}
+
+function inProject(
+ type: SearchResultType,
+ hit: SearchHit,
+ projectId: string | undefined,
+): boolean {
+ if (projectId === undefined) return true;
+ if (type === "workspace") return false;
+ return (type === "project" ? hit.id : hit.projectId) === projectId;
+}
+
+export function normalizeSearchResults(
+ hits: ReadonlyArray<SearchHit>,
+ context: SearchContext,
+): SearchResultJson[] {
+ const allowed = ALLOWED[context.type];
+ const seen = new Set<string>();
+ const results: SearchResultJson[] = [];
+ for (const hit of hits) {
+ const { type } = hit;
+ if (!isResultType(type) || !allowed.includes(type)) continue;
+ if (
+ hit.workspaceId !== undefined &&
+ hit.workspaceId !== context.workspaceId
+ )
+ continue;
+ if (!inProject(type, hit, context.projectId)) continue;
+ const key = `${type}:${hit.id}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ const ticket =
+ type === "project" || type === "workspace" || !hit.projectSlug
+ ? null
+ : ticketId(hit.projectSlug, hit.taskNumber ?? null);
+ results.push({
+ type,
+ id: hit.id,
+ title: hit.title,
+ ticketId: ticket,
+ status: hit.status ?? null,
+ priority: hit.priority ?? null,
+ snippet: snippet(
+ type === "comment" || type === "activity"
+ ? hit.content
+ : hit.description,
+ ),
+ projectId: hit.projectId ?? null,
+ projectKey: hit.projectSlug ? hit.projectSlug.toUpperCase() : null,
+ projectName: hit.projectName ?? null,
+ workspaceId: context.workspaceId,
+ assignee: type === "task" ? (hit.userName ?? null) : null,
+ author:
+ type === "comment" || type === "activity"
+ ? (hit.userName ?? null)
+ : null,
+ createdAt: hit.createdAt,
+ url: resultUrl(type, hit, ticket, context),
+ });
+ }
+ return results;
+}
diff --git a/packages/cli/src/services/cli-environment.ts b/packages/cli/src/services/cli-environment.ts
new file mode 100644
index 000000000..5fb169fae
--- /dev/null
+++ b/packages/cli/src/services/cli-environment.ts
@@ -0,0 +1,41 @@
+import { homedir } from "node:os";
+import { Context, Layer } from "effect";
+import type { Environment, StreamInfo } from "../render/capabilities.js";
+
+export type CliEnvironmentShape = {
+ readonly env: Environment;
+ readonly cwd: string;
+ readonly home: string;
+ readonly platform: string;
+ readonly stdin: StreamInfo;
+ readonly stdout: StreamInfo;
+ readonly stderr: StreamInfo;
+};
+
+export class CliEnvironment extends Context.Service<
+ CliEnvironment,
+ CliEnvironmentShape
+>()("kaneo/CliEnvironment") {}
+
+export function processEnvironment(): CliEnvironmentShape {
+ return {
+ env: process.env,
+ cwd: process.cwd(),
+ home: homedir(),
+ platform: process.platform,
+ stdin: { isTTY: process.stdin.isTTY === true, columns: undefined },
+ stdout: {
+ isTTY: process.stdout.isTTY === true,
+ columns: process.stdout.columns,
+ },
+ stderr: {
+ isTTY: process.stderr.isTTY === true,
+ columns: process.stderr.columns,
+ },
+ };
+}
+
+export const CliEnvironmentLive = Layer.sync(
+ CliEnvironment,
+ processEnvironment,
+);
diff --git a/packages/cli/src/services/desktop.ts b/packages/cli/src/services/desktop.ts
new file mode 100644
index 000000000..4dab23371
--- /dev/null
+++ b/packages/cli/src/services/desktop.ts
@@ -0,0 +1,91 @@
+import { spawn } from "node:child_process";
+import { Context, Effect, Layer } from "effect";
+import { CliEnvironment } from "./cli-environment.js";
+
+export type DesktopShape = {
+ readonly openUrl: (url: string) => Effect.Effect<boolean>;
+ readonly copy: (text: string) => Effect.Effect<boolean>;
+};
+
+export class Desktop extends Context.Service<Desktop, DesktopShape>()(
+ "kaneo/Desktop",
+) {}
+
+type Launch = {
+ readonly command: string;
+ readonly args: ReadonlyArray<string>;
+};
+
+function run(launch: Launch, input?: string): Promise<boolean> {
+ return new Promise((resolve) => {
+ try {
+ const child = spawn(launch.command, launch.args, {
+ stdio: [input === undefined ? "ignore" : "pipe", "ignore", "ignore"],
+ detached: input === undefined,
+ });
+ child.once("error", () => resolve(false));
+ if (input === undefined) {
+ child.unref();
+ resolve(true);
+ return;
+ }
+ child.once("close", (code) => resolve(code === 0));
+ child.stdin?.end(input);
+ } catch {
+ resolve(false);
+ }
+ });
+}
+
+async function firstSuccessful(
+ candidates: ReadonlyArray<Launch>,
+ input: string,
+): Promise<boolean> {
+ for (const candidate of candidates) {
+ if (await run(candidate, input)) return true;
+ }
+ return false;
+}
+
+export const DesktopLive = Layer.effect(
+ Desktop,
+ Effect.gen(function* () {
+ const { env, platform } = yield* CliEnvironment;
+ const remote = Boolean(env.SSH_CONNECTION || env.SSH_TTY);
+ const headlessLinux =
+ platform === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY;
+
+ const opener: Launch | undefined =
+ remote || headlessLinux
+ ? undefined
+ : platform === "darwin"
+ ? { command: "open", args: [] }
+ : platform === "win32"
+ ? { command: "cmd", args: ["/c", "start", '""'] }
+ : { command: "xdg-open", args: [] };
+
+ const clipboards: ReadonlyArray<Launch> =
+ platform === "darwin"
+ ? [{ command: "pbcopy", args: [] }]
+ : platform === "win32"
+ ? [{ command: "clip", args: [] }]
+ : [
+ { command: "wl-copy", args: [] },
+ { command: "xclip", args: ["-selection", "clipboard"] },
+ { command: "xsel", args: ["--clipboard", "--input"] },
+ ];
+
+ return {
+ openUrl: (url) =>
+ opener
+ ? Effect.promise(() =>
+ run({ command: opener.command, args: [...opener.args, url] }),
+ )
+ : Effect.succeed(false),
+ copy: (text) =>
+ remote || headlessLinux
+ ? Effect.succeed(false)
+ : Effect.promise(() => firstSuccessful(clipboards, text)),
+ };
+ }),
+);
diff --git a/packages/cli/src/services/device-auth.test.ts b/packages/cli/src/services/device-auth.test.ts
new file mode 100644
index 000000000..769e729d5
--- /dev/null
+++ b/packages/cli/src/services/device-auth.test.ts
@@ -0,0 +1,36 @@
+import { DeviceCodeRequestError } from "@kaneo/mcp/device-flow";
+import { describe, expect, it } from "vite-plus/test";
+import { toDeviceFailure } from "./device-auth.js";
+
+const toFailure = toDeviceFailure(
+ "https://cloud.kaneo.app",
+ "POST /api/auth/device/code",
+);
+
+describe("toDeviceFailure", () => {
+ it("explains a server that does not allow the CLI client", () => {
+ const failure = toFailure(
+ new DeviceCodeRequestError(400, {
+ error: "invalid_client",
+ error_description: "Invalid client ID",
+ }),
+ );
+ expect(failure).toMatchObject({
+ _tag: "DeviceClientRejected",
+ clientId: "kaneo-cli",
+ });
+ });
+
+ it("reports other device errors as unexpected responses", () => {
+ expect(
+ toFailure(new DeviceCodeRequestError(500, { error: "server_error" }))
+ ._tag,
+ ).toBe("UnexpectedResponse");
+ });
+
+ it("reports network failures as an unreachable server", () => {
+ expect(toFailure(new TypeError("fetch failed"))._tag).toBe(
+ "ServerUnreachable",
+ );
+ });
+});
diff --git a/packages/cli/src/services/device-auth.ts b/packages/cli/src/services/device-auth.ts
new file mode 100644
index 000000000..3bfc3f317
--- /dev/null
+++ b/packages/cli/src/services/device-auth.ts
@@ -0,0 +1,71 @@
+import {
+ type DeviceCodeResponse,
+ DeviceCodeRequestError,
+ type DeviceTokenPoll,
+ pollDeviceTokenOnce,
+ requestDeviceCode,
+} from "@kaneo/mcp/device-flow";
+import { Context, Effect, Layer } from "effect";
+import {
+ DeviceClientRejected,
+ ServerUnreachable,
+ UnexpectedResponse,
+} from "../errors/errors.js";
+
+export const DEVICE_CLIENT_ID = "kaneo-cli";
+
+export type DeviceAuthShape = {
+ readonly requestCode: (
+ apiUrl: string,
+ ) => Effect.Effect<
+ DeviceCodeResponse,
+ DeviceClientRejected | ServerUnreachable | UnexpectedResponse
+ >;
+ readonly poll: (
+ apiUrl: string,
+ deviceCode: string,
+ ) => Effect.Effect<DeviceTokenPoll, ServerUnreachable | UnexpectedResponse>;
+};
+
+export class DeviceAuth extends Context.Service<DeviceAuth, DeviceAuthShape>()(
+ "kaneo/DeviceAuth",
+) {}
+
+export function toDeviceFailure(apiUrl: string, endpoint: string) {
+ return (cause: unknown) => {
+ if (
+ cause instanceof DeviceCodeRequestError &&
+ cause.error === "invalid_client"
+ ) {
+ return new DeviceClientRejected({ apiUrl, clientId: DEVICE_CLIENT_ID });
+ }
+ const message = cause instanceof Error ? cause.message : String(cause);
+ return message.startsWith("device/")
+ ? new UnexpectedResponse({ endpoint, detail: message })
+ : new ServerUnreachable({ apiUrl, reason: message });
+ };
+}
+
+export const DeviceAuthLive = Layer.succeed(DeviceAuth, {
+ requestCode: (apiUrl) =>
+ Effect.tryPromise({
+ try: () => requestDeviceCode(apiUrl, DEVICE_CLIENT_ID),
+ catch: toDeviceFailure(apiUrl, "POST /api/auth/device/code"),
+ }),
+ poll: (apiUrl, deviceCode) =>
+ Effect.tryPromise({
+ try: () => pollDeviceTokenOnce(apiUrl, DEVICE_CLIENT_ID, deviceCode),
+ catch: (cause) => {
+ const failure = toDeviceFailure(
+ apiUrl,
+ "POST /api/auth/device/token",
+ )(cause);
+ return failure._tag === "DeviceClientRejected"
+ ? new UnexpectedResponse({
+ endpoint: "POST /api/auth/device/token",
+ detail: String(cause),
+ })
+ : failure;
+ },
+ }),
+});
diff --git a/packages/cli/src/services/selection.ts b/packages/cli/src/services/selection.ts
new file mode 100644
index 000000000..7e71ac1bb
--- /dev/null
+++ b/packages/cli/src/services/selection.ts
@@ -0,0 +1,89 @@
+import { Effect, Option } from "effect";
+import { listProjects, listWorkspaces } from "../api/endpoints.js";
+import type { Project } from "../api/schemas.js";
+import {
+ ProjectNotFound,
+ ProjectRequired,
+ WorkspaceRequired,
+} from "../errors/errors.js";
+import { Output } from "../output/output.js";
+import { withSpinner } from "../output/spinner.js";
+import { pick } from "../prompts/pick.js";
+import { Session } from "./session.js";
+
+export const resolveWorkspaceId = Effect.fn("selection.workspace")(
+ function* () {
+ const session = yield* Session;
+ if (Option.isSome(session.workspace)) return session.workspace.value.id;
+ const output = yield* Output;
+ const workspaces =
+ yield* withSpinner("Loading workspaces")(listWorkspaces());
+ const [only] = workspaces;
+ if (workspaces.length === 1 && only) return only.id;
+ if (workspaces.length > 1 && output.interactive) {
+ return yield* pick(
+ "Choose a workspace",
+ workspaces.map((workspace) => ({
+ title: workspace.name,
+ value: workspace.id,
+ description: workspace.slug,
+ })),
+ );
+ }
+ return yield* new WorkspaceRequired();
+ },
+);
+
+export function matchProject(
+ projects: ReadonlyArray<Project>,
+ reference: string,
+): Project | undefined {
+ const normalized = reference.normalize("NFKC").toLowerCase();
+ return (
+ projects.find((project) => project.id === reference) ??
+ projects.find(
+ (project) => project.slug.normalize("NFKC").toLowerCase() === normalized,
+ ) ??
+ projects.find((project) => project.name.toLowerCase() === normalized)
+ );
+}
+
+export const resolveProject = Effect.fn("selection.project")(function* (
+ workspaceId: string,
+ reference: Option.Option<string>,
+) {
+ const session = yield* Session;
+ const output = yield* Output;
+ const projects = (yield* withSpinner("Loading projects")(
+ listProjects(workspaceId),
+ )).filter((project) => project.archivedAt === null);
+ const wanted = Option.orElse(
+ Option.map(reference, (ref) => ({ ref, source: null as string | null })),
+ () =>
+ Option.map(session.project, (project) => ({
+ ref: project.ref,
+ source: project.source,
+ })),
+ );
+ if (Option.isSome(wanted)) {
+ const match = matchProject(projects, wanted.value.ref);
+ if (match) return match;
+ return yield* new ProjectNotFound({
+ query: wanted.value.ref,
+ source: wanted.value.source,
+ });
+ }
+ const [only] = projects;
+ if (projects.length === 1 && only) return only;
+ if (projects.length > 1 && output.interactive) {
+ return yield* pick(
+ "Choose a project",
+ projects.map((project) => ({
+ title: project.name,
+ value: project,
+ description: project.slug.toUpperCase(),
+ })),
+ );
+ }
+ return yield* new ProjectRequired();
+});
diff --git a/packages/cli/src/services/session.test.ts b/packages/cli/src/services/session.test.ts
new file mode 100644
index 000000000..73209473d
--- /dev/null
+++ b/packages/cli/src/services/session.test.ts
@@ -0,0 +1,106 @@
+import { Option, Redacted } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { emptyConfig, withProfile } from "../config/format.js";
+import {
+ DEFAULT_API_URL,
+ resolveSession,
+ type SessionInputs,
+} from "./session.js";
+
+const config = withProfile(emptyConfig, "default", () => ({
+ apiUrl: "https://kaneo.example.com/api/",
+ webUrl: "https://app.example.com",
+ token: "profile-token",
+ workspaceId: "ws_profile",
+}));
+
+function inputs(overrides: Partial<SessionInputs> = {}): SessionInputs {
+ return {
+ flags: {
+ token: Option.none(),
+ apiUrl: Option.none(),
+ workspace: Option.none(),
+ profile: Option.none(),
+ },
+ env: {},
+ config,
+ configProblem: Option.none(),
+ repo: undefined,
+ ...overrides,
+ };
+}
+
+const token = (session: ReturnType<typeof resolveSession>) =>
+ Option.map(session.credentials, (credentials) => [
+ Redacted.value(credentials.token),
+ credentials.source,
+ ]);
+
+describe("resolveSession", () => {
+ it("uses the stored profile by default", () => {
+ const session = resolveSession(inputs());
+ expect(session.apiUrl).toBe("https://kaneo.example.com");
+ expect(session.webUrl).toBe("https://app.example.com");
+ expect(token(session)).toEqual(Option.some(["profile-token", "profile"]));
+ expect(Option.getOrUndefined(session.workspace)).toEqual({
+ id: "ws_profile",
+ source: "profile",
+ });
+ });
+
+ it("prefers --token, then KANEO_API_KEY, then the profile", () => {
+ expect(
+ token(
+ resolveSession(
+ inputs({
+ flags: {
+ ...inputs().flags,
+ token: Option.some(Redacted.make("flag")),
+ },
+ env: { KANEO_API_KEY: "env" },
+ }),
+ ),
+ ),
+ ).toEqual(Option.some(["flag", "flag"]));
+ expect(
+ token(resolveSession(inputs({ env: { KANEO_API_KEY: "env" } }))),
+ ).toEqual(Option.some(["env", "env"]));
+ });
+
+ it("never sends a stored token to a different server", () => {
+ const session = resolveSession(
+ inputs({
+ flags: { ...inputs().flags, apiUrl: Option.some("https://evil.test") },
+ }),
+ );
+ expect(session.apiUrl).toBe("https://evil.test");
+ expect(Option.isNone(session.credentials)).toBe(true);
+ expect(Option.isNone(session.workspace)).toBe(true);
+ });
+
+ it("resolves the workspace from flag, env, repo file, then profile", () => {
+ const repo = {
+ path: "/r/.kaneo.json",
+ workspace: "ws_repo",
+ project: undefined,
+ };
+ expect(
+ Option.getOrUndefined(
+ resolveSession(inputs({ env: { KANEO_WORKSPACE: "ws_env" }, repo }))
+ .workspace,
+ ),
+ ).toEqual({ id: "ws_env", source: "env" });
+ expect(
+ Option.getOrUndefined(resolveSession(inputs({ repo })).workspace),
+ ).toEqual({
+ id: "ws_repo",
+ source: "repo",
+ });
+ });
+
+ it("falls back to the cloud with no configuration", () => {
+ const session = resolveSession(inputs({ config: emptyConfig }));
+ expect(session.apiUrl).toBe(DEFAULT_API_URL);
+ expect(Option.isNone(session.credentials)).toBe(true);
+ });
+});
diff --git a/packages/cli/src/services/session.ts b/packages/cli/src/services/session.ts
new file mode 100644
index 000000000..f25845372
--- /dev/null
+++ b/packages/cli/src/services/session.ts
@@ -0,0 +1,173 @@
+import { Context, Effect, Layer, Option, Redacted } from "effect";
+import {
+ ApiUrlFlag,
+ ProfileFlag,
+ TokenFlag,
+ WorkspaceFlag,
+} from "../cli/global-flags.js";
+import { ConfigStore } from "../config/config-store.js";
+import {
+ type ConfigFile,
+ DEFAULT_PROFILE,
+ emptyConfig,
+ type Profile,
+} from "../config/format.js";
+import { findRepoConfig, type RepoConfig } from "../config/repo-config.js";
+import type { ConfigUnreadable } from "../errors/errors.js";
+import { normalizeBaseUrl } from "@kaneo/mcp/normalize-base-url";
+import type { Environment } from "../render/capabilities.js";
+import { CliEnvironment } from "./cli-environment.js";
+
+export const DEFAULT_API_URL = "https://cloud.kaneo.app";
+
+export type TokenSource = "flag" | "env" | "profile";
+
+export type Credentials = {
+ readonly token: Redacted.Redacted<string>;
+ readonly source: TokenSource;
+};
+
+export type WorkspaceSource = "flag" | "env" | "repo" | "profile";
+
+export type WorkspaceRef = {
+ readonly id: string;
+ readonly source: WorkspaceSource;
+};
+
+export type ProjectRef = {
+ readonly ref: string;
+ readonly source: string;
+};
+
+export type SessionShape = {
+ readonly apiUrl: string;
+ readonly webUrl: string;
+ readonly profileName: string;
+ readonly config: ConfigFile;
+ readonly configProblem: Option.Option<ConfigUnreadable>;
+ readonly profile: Profile | undefined;
+ readonly credentials: Option.Option<Credentials>;
+ readonly workspace: Option.Option<WorkspaceRef>;
+ readonly project: Option.Option<ProjectRef>;
+ readonly repo: RepoConfig | undefined;
+};
+
+export class Session extends Context.Service<Session, SessionShape>()(
+ "kaneo/Session",
+) {}
+
+export type SessionInputs = {
+ readonly flags: {
+ readonly token: Option.Option<Redacted.Redacted<string>>;
+ readonly apiUrl: Option.Option<string>;
+ readonly workspace: Option.Option<string>;
+ readonly profile: Option.Option<string>;
+ };
+ readonly env: Environment;
+ readonly config: ConfigFile;
+ readonly configProblem: Option.Option<ConfigUnreadable>;
+ readonly repo: RepoConfig | undefined;
+};
+
+function nonEmpty(value: string | undefined): Option.Option<string> {
+ return value && value.trim() !== ""
+ ? Option.some(value.trim())
+ : Option.none();
+}
+
+export function resolveSession(inputs: SessionInputs): SessionShape {
+ const { flags, env, config, repo } = inputs;
+ const profileName = Option.getOrElse(
+ Option.orElse(flags.profile, () => nonEmpty(env.KANEO_PROFILE)),
+ () => config.activeProfile || DEFAULT_PROFILE,
+ );
+ const profile = config.profiles[profileName];
+ const apiUrl = normalizeBaseUrl(
+ Option.getOrElse(
+ Option.orElse(flags.apiUrl, () => nonEmpty(env.KANEO_API_URL)),
+ () => profile?.apiUrl ?? DEFAULT_API_URL,
+ ),
+ );
+ const profileMatches =
+ profile !== undefined && normalizeBaseUrl(profile.apiUrl) === apiUrl;
+ const webUrl = normalizeBaseUrl(
+ env.KANEO_WEB_URL ||
+ (profileMatches ? profile.webUrl : undefined) ||
+ apiUrl,
+ );
+
+ const credentials: Option.Option<Credentials> = Option.firstSomeOf([
+ Option.map(flags.token, (token) => ({ token, source: "flag" as const })),
+ Option.map(nonEmpty(env.KANEO_API_KEY), (token) => ({
+ token: Redacted.make(token),
+ source: "env" as const,
+ })),
+ profileMatches && profile.token
+ ? Option.some({
+ token: Redacted.make(profile.token),
+ source: "profile" as const,
+ })
+ : Option.none(),
+ ]);
+
+ const workspace: Option.Option<WorkspaceRef> = Option.firstSomeOf([
+ Option.map(flags.workspace, (id) => ({ id, source: "flag" as const })),
+ Option.map(nonEmpty(env.KANEO_WORKSPACE), (id) => ({
+ id,
+ source: "env" as const,
+ })),
+ Option.map(Option.fromUndefinedOr(repo?.workspace), (id) => ({
+ id,
+ source: "repo" as const,
+ })),
+ profileMatches && profile.workspaceId
+ ? Option.some({ id: profile.workspaceId, source: "profile" as const })
+ : Option.none(),
+ ]);
+
+ const project: Option.Option<ProjectRef> = Option.firstSomeOf([
+ Option.map(nonEmpty(env.KANEO_PROJECT), (ref) => ({
+ ref,
+ source: "KANEO_PROJECT",
+ })),
+ Option.map(Option.fromUndefinedOr(repo?.project), (ref) => ({
+ ref,
+ source: repo?.path ?? ".kaneo.json",
+ })),
+ ]);
+
+ return {
+ apiUrl,
+ webUrl,
+ profileName,
+ config,
+ configProblem: inputs.configProblem,
+ profile: profileMatches ? profile : undefined,
+ credentials,
+ workspace,
+ project,
+ repo,
+ };
+}
+
+export const SessionLive = Layer.effect(
+ Session,
+ Effect.gen(function* () {
+ const environment = yield* CliEnvironment;
+ const store = yield* ConfigStore;
+ const loaded = yield* Effect.result(store.load);
+ return resolveSession({
+ flags: {
+ token: yield* TokenFlag,
+ apiUrl: yield* ApiUrlFlag,
+ workspace: yield* WorkspaceFlag,
+ profile: yield* ProfileFlag,
+ },
+ env: environment.env,
+ config: loaded._tag === "Success" ? loaded.success : emptyConfig,
+ configProblem:
+ loaded._tag === "Failure" ? Option.some(loaded.failure) : Option.none(),
+ repo: findRepoConfig(environment.cwd),
+ });
+ }),
+);
diff --git a/packages/cli/src/task-view/label-chips.test.ts b/packages/cli/src/task-view/label-chips.test.ts
new file mode 100644
index 000000000..35d7f0d84
--- /dev/null
+++ b/packages/cli/src/task-view/label-chips.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from "vite-plus/test";
+import { renderCell } from "../render/cell.js";
+import { makeUi } from "../render/ui.js";
+import { labelChips } from "./label-chips.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+const labels = ["bug", "auth", "frontend", "needs-design"].map((name) => ({
+ name,
+ color: "red",
+}));
+
+const chips = (width: number, count = labels.length) =>
+ renderCell(labelChips(ui, labels.slice(0, count), width), ui);
+
+describe("labelChips", () => {
+ it("shows every label when they fit", () => {
+ expect(chips(80)).toBe("● bug ● auth ● frontend ● needs-design");
+ });
+
+ it("drops whole chips and counts the rest when space runs out", () => {
+ expect(chips(30)).toBe("● bug ● auth ● frontend +1");
+ expect(chips(20)).toBe("● bug ● auth +2");
+ });
+
+ it("cuts a single label that is wider than the row", () => {
+ expect(chips(5, 1)).toBe("● bug");
+ expect(chips(4, 1)).toBe("● b…");
+ });
+
+ it("colors each chip with its label color", () => {
+ const truecolor = makeUi({ ...ui.caps, color: 3 });
+ expect(
+ renderCell(labelChips(truecolor, labels.slice(0, 1), 80), truecolor),
+ ).toBe("\u001b[38;2;231;0;11m●\u001b[39m bug");
+ });
+});
diff --git a/packages/cli/src/task-view/label-chips.ts b/packages/cli/src/task-view/label-chips.ts
new file mode 100644
index 000000000..09880a558
--- /dev/null
+++ b/packages/cli/src/task-view/label-chips.ts
@@ -0,0 +1,38 @@
+import type { TaskLabelJson } from "../labels/label-json.js";
+import { type Cell, cellWidth, fitCell, text } from "../render/cell.js";
+import { labelChipSegment } from "../render/label-chip.js";
+import type { Ui } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+
+const GAP = " ";
+
+export function labelChips(
+ ui: Ui,
+ labels: ReadonlyArray<TaskLabelJson>,
+ width: number,
+): Cell {
+ const chips = labels.map((label) => [
+ labelChipSegment(ui, label.color),
+ text(` ${label.name}`),
+ ]);
+ const shown: Cell[] = [];
+ let used = 0;
+ for (const [index, chip] of chips.entries()) {
+ const hidden = chips.length - index - 1;
+ const more = hidden > 0 ? stringWidth(`${GAP}+${hidden}`) : 0;
+ const next = (shown.length > 0 ? GAP.length : 0) + cellWidth(chip);
+ if (used + next + more > width) break;
+ shown.push(chip);
+ used += next;
+ }
+ if (shown.length === 0) {
+ return fitCell(chips[0] ?? [], width, ui.glyphs.ellipsis);
+ }
+ const hidden = chips.length - shown.length;
+ return [
+ ...shown.flatMap((chip, index) =>
+ index > 0 ? [text(GAP), ...chip] : chip,
+ ),
+ ...(hidden > 0 ? [text(`${GAP}+${hidden}`, ui.theme.muted)] : []),
+ ];
+}
diff --git a/packages/cli/src/task-view/load-task-view.test.ts b/packages/cli/src/task-view/load-task-view.test.ts
new file mode 100644
index 000000000..8531d1b71
--- /dev/null
+++ b/packages/cli/src/task-view/load-task-view.test.ts
@@ -0,0 +1,145 @@
+import { Effect, Layer, Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { KaneoApiLayer } from "../api/kaneo-api.js";
+import {
+ fakeHttpClient,
+ json,
+ memoryConfigStore,
+ type RecordedRequest,
+ testSession,
+} from "../testing/test-layers.js";
+import { loadTaskView } from "./load-task-view.js";
+import { sectionValue } from "./section-result.js";
+import {
+ commentsFixture,
+ relationsFixture,
+ resolvedTask,
+ sectionsFixture,
+ timeFixture,
+} from "./test-task-view.js";
+
+type Routes = Readonly<Record<string, () => Response>>;
+
+const baseRoutes: Routes = {
+ "/api/task/by-ticket-id/KAN-12": () => json(resolvedTask.task),
+ "/api/project/p1": () => json(resolvedTask.project),
+ "/api/column/p1": () => json(resolvedTask.columns),
+ "/api/label/task/t12": () => json(sectionValue(sectionsFixture.labels)),
+ "/api/task-relation/t12": () => json(relationsFixture.slice(0, 8)),
+ "/api/external-link/task/t12": () =>
+ json(sectionValue(sectionsFixture.links)),
+ "/api/custom-field/task/t12": () =>
+ json(sectionValue(sectionsFixture.fields)),
+ "/api/time-entry/task/t12": () => json(timeFixture),
+ "/api/comment/t12": () => json(commentsFixture),
+ "/api/project": () =>
+ json([
+ resolvedTask.project,
+ { ...resolvedTask.project, id: "p2", slug: "mob" },
+ ]),
+ "/api/user/me": () => json({ message: "Unauthorized" }, 401),
+};
+
+function run(
+ routes: Routes = {},
+ options: { readonly comments: boolean } = { comments: true },
+) {
+ const recorded: RecordedRequest[] = [];
+ const all = { ...baseRoutes, ...routes };
+ const layer = KaneoApiLayer.pipe(
+ Layer.provideMerge(
+ Layer.mergeAll(
+ fakeHttpClient((request) => {
+ const route = all[new URL(request.url).pathname];
+ return route ? route() : json({ message: "Not found" }, 404);
+ }, recorded),
+ testSession(),
+ memoryConfigStore().layer,
+ ),
+ ),
+ );
+ const result = Effect.runPromise(
+ Effect.result(loadTaskView("KAN-12", options).pipe(Effect.provide(layer))),
+ );
+ const paths = () =>
+ recorded.map((request) => new URL(request.url).pathname).sort();
+ return { result, paths };
+}
+
+describe("loadTaskView", () => {
+ it("loads the task and every section", async () => {
+ const { result, paths } = run();
+ const loaded = Result.getOrThrow(await result);
+ expect(loaded.resolved).toEqual(resolvedTask);
+ expect(loaded.sections.labels._tag).toBe("Loaded");
+ expect(sectionValue(loaded.sections.relations)).toHaveLength(8);
+ expect(sectionValue(loaded.sections.comments)).toHaveLength(5);
+ expect(loaded.projectSlugs).toEqual(new Map([["p1", "kan"]]));
+ expect(paths()).toEqual([
+ "/api/column/p1",
+ "/api/comment/t12",
+ "/api/custom-field/task/t12",
+ "/api/external-link/task/t12",
+ "/api/label/task/t12",
+ "/api/project/p1",
+ "/api/task-relation/t12",
+ "/api/task/by-ticket-id/KAN-12",
+ "/api/time-entry/task/t12",
+ ]);
+ });
+
+ it("skips the comments request when no comments are wanted", async () => {
+ const { result, paths } = run({}, { comments: false });
+ const loaded = Result.getOrThrow(await result);
+ expect(sectionValue(loaded.sections.comments)).toEqual([]);
+ expect(paths()).not.toContain("/api/comment/t12");
+ });
+
+ it("looks up project keys only for tasks linked from other projects", async () => {
+ const { result, paths } = run({
+ "/api/task-relation/t12": () => json(relationsFixture),
+ });
+ const loaded = Result.getOrThrow(await result);
+ expect(loaded.projectSlugs.get("p2")).toBe("mob");
+ expect(paths()).toContain("/api/project");
+ });
+
+ it("keeps going when a section fails", async () => {
+ const { result } = run({
+ "/api/external-link/task/t12": () => json({ message: "boom" }, 500),
+ "/api/time-entry/task/t12": () =>
+ json({ message: "You cannot see time entries" }, 403),
+ });
+ const loaded = Result.getOrThrow(await result);
+ expect(loaded.sections.links).toEqual({
+ _tag: "Failed",
+ message: "The server failed with 500: boom",
+ });
+ expect(loaded.sections.time).toEqual({
+ _tag: "Failed",
+ message: "You cannot see time entries",
+ });
+ expect(loaded.sections.fields._tag).toBe("Loaded");
+ });
+
+ it("fails as usual when the session has expired", async () => {
+ const { result } = run({
+ "/api/comment/t12": () => json({ message: "Unauthorized" }, 401),
+ });
+ const failure = await result;
+ expect(Result.isFailure(failure) && failure.failure._tag).toBe(
+ "SessionExpired",
+ );
+ });
+
+ it("fails as usual when the task does not exist", async () => {
+ const { result } = run({
+ "/api/task/by-ticket-id/KAN-12": () => json({ message: "nope" }, 404),
+ });
+ const failure = await result;
+ expect(Result.isFailure(failure) && failure.failure).toMatchObject({
+ _tag: "NotFound",
+ message: "Task KAN-12 not found.",
+ });
+ });
+});
diff --git a/packages/cli/src/task-view/load-task-view.ts b/packages/cli/src/task-view/load-task-view.ts
new file mode 100644
index 000000000..025338b0c
--- /dev/null
+++ b/packages/cli/src/task-view/load-task-view.ts
@@ -0,0 +1,107 @@
+import { Effect } from "effect";
+import { listComments } from "../api/comments.js";
+import { getProject, listColumns, listProjects } from "../api/endpoints.js";
+import { listExternalLinks } from "../api/external-links.js";
+import { listTaskLabels } from "../api/labels.js";
+import type { Project } from "../api/schemas.js";
+import { listTaskRelations } from "../api/task-relations.js";
+import { listTimeEntries } from "../api/time-entries.js";
+import { taskUrl } from "../render/links.js";
+import { ticketId } from "../render/task-format.js";
+import { Session } from "../services/session.js";
+import { fetchTask, type ResolvedTask } from "../tasks/resolve-task.js";
+import {
+ loaded,
+ optionalSection,
+ type SectionResult,
+ sectionValue,
+} from "./section-result.js";
+import { listTaskFieldValuesWithNames } from "./task-field-values.js";
+import type { TaskViewSections } from "./task-view-sections.js";
+
+const SECTION_CONCURRENCY = 6;
+
+export type LoadedTaskView = {
+ readonly resolved: ResolvedTask;
+ readonly sections: TaskViewSections;
+ readonly projectSlugs: ReadonlyMap<string, string>;
+};
+
+export const loadTaskSections = (
+ taskId: string,
+ options: { readonly comments: boolean },
+) =>
+ Effect.all(
+ {
+ labels: optionalSection(listTaskLabels(taskId)),
+ relations: optionalSection(listTaskRelations(taskId)),
+ links: optionalSection(listExternalLinks(taskId)),
+ fields: optionalSection(listTaskFieldValuesWithNames(taskId)),
+ time: optionalSection(listTimeEntries(taskId)),
+ comments: options.comments
+ ? optionalSection(listComments(taskId))
+ : Effect.succeed(loaded([])),
+ },
+ { concurrency: SECTION_CONCURRENCY },
+ );
+
+function foreignProjectIds(
+ relations: TaskViewSections["relations"],
+ known: ReadonlyMap<string, string>,
+): boolean {
+ return (sectionValue(relations) ?? []).some((relation) =>
+ [relation.sourceTask, relation.targetTask].some(
+ (task) => task !== null && !known.has(task.projectId),
+ ),
+ );
+}
+
+const relatedProjectSlugs = Effect.fnUntraced(function* (
+ relations: TaskViewSections["relations"],
+ project: Project,
+ workspaceId: string,
+) {
+ const known = new Map([[project.id, project.slug]]);
+ if (!foreignProjectIds(relations, known)) return known;
+ const projects: SectionResult<ReadonlyArray<Project>> =
+ yield* optionalSection(listProjects(workspaceId));
+ for (const other of sectionValue(projects) ?? []) {
+ known.set(other.id, other.slug);
+ }
+ return known;
+});
+
+export const loadTaskView = Effect.fn("taskView.load")(function* (
+ reference: string,
+ options: { readonly comments: boolean },
+) {
+ const session = yield* Session;
+ const task = yield* fetchTask(reference);
+ const [project, columns, sections] = yield* Effect.all(
+ [
+ getProject(task.projectId),
+ listColumns(task.projectId),
+ loadTaskSections(task.id, options),
+ ],
+ { concurrency: 3 },
+ );
+ const workspaceId = task.workspaceId ?? project.workspaceId;
+ const resolved: ResolvedTask = {
+ task,
+ workspaceId,
+ project,
+ columns,
+ ticketId: ticketId(project.slug, task.number),
+ url: taskUrl(session.webUrl, {
+ workspaceId,
+ projectId: task.projectId,
+ id: task.id,
+ }),
+ };
+ const projectSlugs = yield* relatedProjectSlugs(
+ sections.relations,
+ project,
+ workspaceId,
+ );
+ return { resolved, sections, projectSlugs } satisfies LoadedTaskView;
+});
diff --git a/packages/cli/src/task-view/related-task-columns.ts b/packages/cli/src/task-view/related-task-columns.ts
new file mode 100644
index 000000000..62cb726b2
--- /dev/null
+++ b/packages/cli/src/task-view/related-task-columns.ts
@@ -0,0 +1,36 @@
+import { type Cell, text } from "../render/cell.js";
+import type { Column } from "../render/table.js";
+import { statusDot } from "../render/task-format.js";
+import type { Ui } from "../render/ui.js";
+import type { RelatedTaskJson } from "../relations/group-relations.js";
+
+export function relatedTaskColumns<Row>(
+ ui: Ui,
+ taskOf: (row: Row) => RelatedTaskJson,
+): Array<Column<Row>> {
+ const { theme, glyphs } = ui;
+ return [
+ {
+ header: "ID",
+ cell: (row): Cell => {
+ const task = taskOf(row);
+ return [
+ statusDot(ui, task.status, task.completed),
+ text(" "),
+ text(task.ticketId ?? task.id.slice(0, 8), theme.muted, task.url),
+ ];
+ },
+ },
+ {
+ header: "Title",
+ flex: true,
+ minWidth: 16,
+ cell: (row): Cell => [text(taskOf(row).title)],
+ },
+ {
+ header: "Done",
+ cell: (row): Cell =>
+ taskOf(row).completed ? [text(glyphs.tick, theme.success)] : [],
+ },
+ ];
+}
diff --git a/packages/cli/src/task-view/render-comments.ts b/packages/cli/src/task-view/render-comments.ts
new file mode 100644
index 000000000..cdfcdcfc5
--- /dev/null
+++ b/packages/cli/src/task-view/render-comments.ts
@@ -0,0 +1,99 @@
+import type { CommentJson } from "../comments/comment-json.js";
+import { relativeTime } from "../comments/relative-time.js";
+import type { Ui } from "../render/ui.js";
+import { stringWidth, truncate } from "../render/width.js";
+import {
+ type DescriptionLine,
+ plainDescription,
+} from "../tasks/plain-description.js";
+import { sectionTitle } from "./section-title.js";
+
+export type CommentsView = {
+ readonly comments: ReadonlyArray<CommentJson>;
+ readonly total: number;
+ readonly reference: string;
+ readonly now: Date;
+ readonly full?: boolean;
+};
+
+const PREVIEW_LINES = 3;
+const HEAD = " ";
+const BODY = " ";
+
+function renderAuthor(ui: Ui, comment: CommentJson, now: Date): string {
+ const { theme, glyphs } = ui;
+ const meta = [
+ relativeTime(new Date(comment.createdAt), now),
+ comment.edited ? "edited" : "",
+ ]
+ .filter((part) => part !== "")
+ .map((part) => ` ${glyphs.separator} ${part}`)
+ .join("");
+ const room = ui.caps.columns - HEAD.length - stringWidth(meta);
+ const name = truncate(
+ comment.author?.name ?? "Someone",
+ Math.max(room, 8),
+ glyphs.ellipsis,
+ );
+ return `${HEAD}${theme.strong(name)}${theme.muted(meta)}`;
+}
+
+function renderBody(ui: Ui, content: string, full: boolean): string[] {
+ const { theme, glyphs } = ui;
+ const width = ui.caps.columns - BODY.length;
+ const parsed = plainDescription(content, {
+ width,
+ unicode: ui.caps.unicode,
+ }).lines;
+ const style = (line: DescriptionLine, text: string) =>
+ line.kind === "heading"
+ ? theme.strong(text)
+ : line.kind === "muted"
+ ? theme.muted(text)
+ : text;
+ if (parsed.length === 0) return [`${BODY}${theme.muted("(empty)")}`];
+ if (full) {
+ return parsed.map((line) =>
+ line.text ? `${BODY}${style(line, line.text)}` : "",
+ );
+ }
+ const lines = parsed.filter((line) => line.text.trim() !== "");
+ const shown = lines.slice(0, PREVIEW_LINES);
+ return shown.map((line, index) => {
+ const cut = index === shown.length - 1 && lines.length > shown.length;
+ if (!cut) return `${BODY}${style(line, line.text)}`;
+ const marker = ` ${glyphs.ellipsis}`;
+ return stringWidth(line.text) + stringWidth(marker) <= width
+ ? `${BODY}${style(line, line.text)}${theme.muted(marker)}`
+ : `${BODY}${style(line, truncate(line.text, width, glyphs.ellipsis))}`;
+ });
+}
+
+export function renderComments(ui: Ui, view: CommentsView): string[] {
+ if (view.comments.length === 0) return [];
+ const { theme } = ui;
+ const hidden = view.total - view.comments.length;
+ const lines = [sectionTitle(ui, hidden > 0 ? "Recent comments" : "Comments")];
+ for (const [index, comment] of view.comments.entries()) {
+ if (index > 0) lines.push("");
+ lines.push(
+ renderAuthor(ui, comment, view.now),
+ ...renderBody(ui, comment.content, view.full ?? false),
+ );
+ }
+ if (hidden > 0) {
+ const more = `and ${hidden} more, run`;
+ const command = `kaneo comment list ${view.reference}`;
+ const fits =
+ HEAD.length + stringWidth(more) + 1 + stringWidth(command) <=
+ ui.caps.columns;
+ lines.push(
+ "",
+ ...(fits
+ ? [`${HEAD}${theme.muted(more)} ${theme.strong(command)}`]
+ : [`${HEAD}${theme.muted(more)}`, `${HEAD}${theme.strong(command)}`]),
+ );
+ }
+ lines.push("");
+ return lines;
+}
diff --git a/packages/cli/src/task-view/render-fields.ts b/packages/cli/src/task-view/render-fields.ts
new file mode 100644
index 000000000..8a41ee7c0
--- /dev/null
+++ b/packages/cli/src/task-view/render-fields.ts
@@ -0,0 +1,37 @@
+import { formatJsonValue } from "../fields/field-value.js";
+import type { TaskFieldJson } from "../fields/render-task-fields.js";
+import { type Cell, text } from "../render/cell.js";
+import { renderTable } from "../render/table.js";
+import type { Ui } from "../render/ui.js";
+import { sectionTitle } from "./section-title.js";
+
+export function renderFields(
+ ui: Ui,
+ fields: ReadonlyArray<TaskFieldJson>,
+): string[] {
+ if (fields.length === 0) return [];
+ return [
+ sectionTitle(ui, "Custom fields"),
+ ...renderTable(
+ ui,
+ fields,
+ [
+ {
+ header: "Field",
+ minWidth: 10,
+ cell: (field): Cell => [text(field.name, ui.theme.muted)],
+ },
+ {
+ header: "Value",
+ flex: true,
+ minWidth: 12,
+ cell: (field): Cell => [
+ text((formatJsonValue(field.value) ?? "").replace(/\s+/gu, " ")),
+ ],
+ },
+ ],
+ { width: ui.caps.columns, indent: 4, gap: 2 },
+ ),
+ "",
+ ];
+}
diff --git a/packages/cli/src/task-view/render-links.ts b/packages/cli/src/task-view/render-links.ts
new file mode 100644
index 000000000..3e4c80e98
--- /dev/null
+++ b/packages/cli/src/task-view/render-links.ts
@@ -0,0 +1,49 @@
+import type { LinkJson } from "../external-links/link-json.js";
+import { type Cell, text } from "../render/cell.js";
+import { renderTable } from "../render/table.js";
+import type { Ui } from "../render/ui.js";
+import { sectionTitle } from "./section-title.js";
+
+function displayUrl(url: string): string {
+ return url.replace(/^https?:\/\//u, "").replace(/\/$/u, "");
+}
+
+export function renderLinks(ui: Ui, links: ReadonlyArray<LinkJson>): string[] {
+ if (links.length === 0) return [];
+ const { theme } = ui;
+ return [
+ sectionTitle(ui, "Links"),
+ ...renderTable(
+ ui,
+ links,
+ [
+ {
+ header: "Title",
+ flex: true,
+ minWidth: 12,
+ cell: (link): Cell => [
+ text(link.title ?? displayUrl(link.url), undefined, link.url),
+ ],
+ },
+ {
+ header: "URL",
+ flex: true,
+ optional: true,
+ minWidth: 16,
+ cell: (link): Cell =>
+ link.title
+ ? [text(displayUrl(link.url), theme.info, link.url)]
+ : [],
+ },
+ {
+ header: "Source",
+ optional: true,
+ cell: (link): Cell =>
+ link.source === "manual" ? [] : [text(link.source, theme.muted)],
+ },
+ ],
+ { width: ui.caps.columns, indent: 4, gap: 2 },
+ ),
+ "",
+ ];
+}
diff --git a/packages/cli/src/task-view/render-relations.ts b/packages/cli/src/task-view/render-relations.ts
new file mode 100644
index 000000000..101b21856
--- /dev/null
+++ b/packages/cli/src/task-view/render-relations.ts
@@ -0,0 +1,49 @@
+import type {
+ RelatedTaskJson,
+ RelationJson,
+} from "../relations/group-relations.js";
+import { relationHeading } from "../relations/relation-types.js";
+import { type Cell, text } from "../render/cell.js";
+import { renderTable } from "../render/table.js";
+import type { Ui } from "../render/ui.js";
+import { relatedTaskColumns } from "./related-task-columns.js";
+import { sectionTitle } from "./section-title.js";
+
+type RelationRow = {
+ readonly heading: string | null;
+ readonly task: RelatedTaskJson;
+};
+
+function relationRows(relations: ReadonlyArray<RelationJson>): RelationRow[] {
+ return relations.map((relation, index) => ({
+ heading:
+ relations[index - 1]?.type === relation.type
+ ? null
+ : relationHeading(relation.type),
+ task: relation.task,
+ }));
+}
+
+export function renderRelations(
+ ui: Ui,
+ relations: ReadonlyArray<RelationJson>,
+): string[] {
+ if (relations.length === 0) return [];
+ return [
+ sectionTitle(ui, "Relations"),
+ ...renderTable(
+ ui,
+ relationRows(relations),
+ [
+ {
+ header: "Type",
+ cell: (row): Cell =>
+ row.heading ? [text(row.heading, ui.theme.muted)] : [],
+ },
+ ...relatedTaskColumns(ui, (row: RelationRow) => row.task),
+ ],
+ { width: ui.caps.columns, indent: 4, gap: 2 },
+ ),
+ "",
+ ];
+}
diff --git a/packages/cli/src/task-view/render-subtasks.ts b/packages/cli/src/task-view/render-subtasks.ts
new file mode 100644
index 000000000..8b80cda75
--- /dev/null
+++ b/packages/cli/src/task-view/render-subtasks.ts
@@ -0,0 +1,23 @@
+import type { RelatedTaskJson } from "../relations/group-relations.js";
+import { renderTable } from "../render/table.js";
+import type { Ui } from "../render/ui.js";
+import { relatedTaskColumns } from "./related-task-columns.js";
+import { sectionTitle } from "./section-title.js";
+
+export function renderSubtasks(
+ ui: Ui,
+ subtasks: ReadonlyArray<RelatedTaskJson>,
+): string[] {
+ if (subtasks.length === 0) return [];
+ const done = subtasks.filter((task) => task.completed).length;
+ return [
+ sectionTitle(ui, "Subtasks", `${done} of ${subtasks.length} done`),
+ ...renderTable(
+ ui,
+ subtasks,
+ relatedTaskColumns(ui, (task: RelatedTaskJson) => task),
+ { width: ui.caps.columns, indent: 4, gap: 2 },
+ ),
+ "",
+ ];
+}
diff --git a/packages/cli/src/task-view/render-task-sections.test.ts b/packages/cli/src/task-view/render-task-sections.test.ts
new file mode 100644
index 000000000..a50a8a5bd
--- /dev/null
+++ b/packages/cli/src/task-view/render-task-sections.test.ts
@@ -0,0 +1,210 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import { renderTaskSections } from "./render-task-sections.js";
+import { failed, loaded } from "./section-result.js";
+import { type TaskViewJson, toTaskViewJson } from "./task-view-json.js";
+import type { TaskViewSections } from "./task-view-sections.js";
+import {
+ commentsFixture,
+ projectSlugsFixture,
+ resolvedTask,
+ sectionsFixture,
+ viewNow,
+ webUrl,
+} from "./test-task-view.js";
+
+const ui = (columns = 80) =>
+ makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns,
+ });
+
+const json = (
+ sections: Partial<TaskViewSections> = {},
+ commentLimit = 3,
+): TaskViewJson =>
+ toTaskViewJson({
+ resolved: resolvedTask,
+ sections: { ...sectionsFixture, ...sections },
+ projectSlugs: projectSlugsFixture,
+ webUrl,
+ commentLimit,
+ now: viewNow,
+ });
+
+const render = (task: TaskViewJson, commentTotal = 5, columns = 80) =>
+ renderTaskSections(ui(columns), { task, commentTotal, now: viewNow });
+
+const titles = (lines: ReadonlyArray<string>) =>
+ lines.filter((line) => /^ {2}\S/u.test(line));
+
+describe("renderTaskSections", () => {
+ it("renders the sections in order, each followed by a blank line", () => {
+ const lines = render(json());
+ expect(titles(lines)).toEqual([
+ " Subtasks 2 of 5 done",
+ " Relations",
+ " Links",
+ " Custom fields",
+ " Recent comments",
+ ]);
+ for (const title of titles(lines).slice(1)) {
+ expect(lines[lines.indexOf(title) - 1]).toBe("");
+ }
+ expect(lines.at(-1)).toBe("");
+ });
+
+ it("groups subtasks and relations with status dots and done markers", () => {
+ const lines = render(json());
+ expect(lines.slice(0, 11)).toEqual([
+ " Subtasks 2 of 5 done",
+ " ● KAN-13 Reproduce on Safari ✓",
+ " ● KAN-14 Add a regression test ✓",
+ " ● KAN-15 Handle expired device codes",
+ " ● KAN-16 Update the login docs",
+ " ● KAN-17 Clean up the redirect helper and its callers",
+ "",
+ " Relations",
+ " Blocks ● KAN-20 Release 2.36",
+ " Blocked by ● KAN-9 Session cookie on the API domain",
+ " Related ● MOB-3 Mobile sign in",
+ ]);
+ });
+
+ it("lists links and the custom fields that have a value", () => {
+ const lines = render(json(), 5, 100);
+ const links = lines.indexOf(" Links");
+ expect(lines.slice(links, links + 7)).toEqual([
+ " Links",
+ " fix(auth): keep state on device redirect github.com/usekaneo/kaneo/pull/1960 github",
+ " sentry.io/issues/4211",
+ "",
+ " Custom fields",
+ " Story points 5",
+ " Platforms Web, CLI",
+ ]);
+ });
+
+ it("previews the latest comments and points to the rest", () => {
+ const lines = render(json());
+ const comments = lines.indexOf(" Recent comments");
+ expect(lines.slice(comments)).toEqual([
+ " Recent comments",
+ " Grace Hopper · Yesterday",
+ " It started with the cookie change.",
+ " The callback URL drops the state param when the device page redirects, so",
+ " the CLI never sees the approval and keeps polling until the code expires.",
+ "",
+ " Ada Lovelace · 3h ago · edited",
+ " First pass is up, please review.",
+ "",
+ " Grace Hopper · 1h ago",
+ " Looks good. One question:",
+ " • do we still need the fallback?",
+ " • can we drop the retry? …",
+ "",
+ " and 2 more, run kaneo comment list KAN-12",
+ "",
+ ]);
+ });
+
+ it("titles the section Comments when every comment is shown", () => {
+ const lines = render(json({}, Number.POSITIVE_INFINITY));
+ expect(lines).toContain(" Comments");
+ expect(lines.some((line) => line.includes("more, run"))).toBe(false);
+ });
+
+ it("shows whole comment bodies in full mode", () => {
+ const lines = renderTaskSections(ui(), {
+ task: json({}, Number.POSITIVE_INFINITY),
+ commentTotal: 5,
+ now: viewNow,
+ full: true,
+ });
+ const last = lines.lastIndexOf(" Grace Hopper · 1h ago");
+ expect(lines.slice(last)).toEqual([
+ " Grace Hopper · 1h ago",
+ " Looks good. One question:",
+ "",
+ " • do we still need the fallback?",
+ " • can we drop the retry?",
+ " • what about older servers?",
+ " • and API keys?",
+ "",
+ ]);
+ });
+
+ it("leaves out sections without content", () => {
+ expect(
+ render(
+ json({
+ relations: loaded([]),
+ links: loaded([]),
+ fields: loaded([
+ {
+ fieldId: "f1",
+ value: "[]",
+ fieldName: "Platforms",
+ fieldType: "multiselect",
+ fieldPosition: 0,
+ },
+ ]),
+ comments: loaded([]),
+ }),
+ 0,
+ ),
+ ).toEqual([]);
+ });
+
+ it("shows one muted line for each section that could not load", () => {
+ expect(
+ render(
+ json({
+ relations: failed("boom"),
+ links: failed("boom"),
+ fields: failed("boom"),
+ comments: failed("boom"),
+ }),
+ 0,
+ ),
+ ).toEqual([
+ " Relations could not load",
+ "",
+ " Links could not load",
+ "",
+ " Custom fields could not load",
+ "",
+ " Comments could not load",
+ "",
+ ]);
+ });
+
+ it("marks empty comments and cuts long ones with an ellipsis", () => {
+ const comment = commentsFixture[0];
+ if (!comment) throw new Error("missing fixture");
+ const lines = render(
+ json({
+ comments: loaded([
+ { ...comment, id: "e", content: " " },
+ { ...comment, id: "l", content: "x".repeat(200) },
+ ]),
+ }),
+ 2,
+ 40,
+ );
+ expect(lines).toContain(" (empty)");
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(40);
+ });
+
+ it("fits every line at narrow widths", () => {
+ for (const columns of [40, 60, 80, 120]) {
+ for (const line of render(json(), 5, columns)) {
+ expect(stringWidth(line)).toBeLessThanOrEqual(columns);
+ }
+ }
+ });
+});
diff --git a/packages/cli/src/task-view/render-task-sections.ts b/packages/cli/src/task-view/render-task-sections.ts
new file mode 100644
index 000000000..59fbfc04c
--- /dev/null
+++ b/packages/cli/src/task-view/render-task-sections.ts
@@ -0,0 +1,42 @@
+import type { Ui } from "../render/ui.js";
+import { renderComments } from "./render-comments.js";
+import { renderFields } from "./render-fields.js";
+import { renderLinks } from "./render-links.js";
+import { renderRelations } from "./render-relations.js";
+import { renderSubtasks } from "./render-subtasks.js";
+import { failedSection } from "./section-title.js";
+import type { TaskViewJson } from "./task-view-json.js";
+
+export type TaskSectionsView = {
+ readonly task: TaskViewJson;
+ readonly commentTotal: number;
+ readonly now: Date;
+ readonly full?: boolean;
+};
+
+export function renderTaskSections(ui: Ui, view: TaskSectionsView): string[] {
+ const { task } = view;
+ return [
+ ...(task.subtasks === null
+ ? failedSection(ui, "Relations")
+ : [
+ ...renderSubtasks(ui, task.subtasks),
+ ...renderRelations(ui, task.relations ?? []),
+ ]),
+ ...(task.links === null
+ ? failedSection(ui, "Links")
+ : renderLinks(ui, task.links)),
+ ...(task.fields === null
+ ? failedSection(ui, "Custom fields")
+ : renderFields(ui, task.fields)),
+ ...(task.comments === null
+ ? failedSection(ui, "Comments")
+ : renderComments(ui, {
+ comments: task.comments,
+ total: view.commentTotal,
+ reference: task.ticketId ?? task.id,
+ now: view.now,
+ full: view.full ?? false,
+ })),
+ ];
+}
diff --git a/packages/cli/src/task-view/render-task-view.ts b/packages/cli/src/task-view/render-task-view.ts
new file mode 100644
index 000000000..430e299ca
--- /dev/null
+++ b/packages/cli/src/task-view/render-task-view.ts
@@ -0,0 +1,12 @@
+import type { Ui } from "../render/ui.js";
+import {
+ renderTaskDetail,
+ type TaskDetailView,
+} from "../tasks/render-task-detail.js";
+import { renderTaskSections } from "./render-task-sections.js";
+
+export type TaskView = TaskDetailView & { readonly commentTotal: number };
+
+export function renderTaskView(ui: Ui, view: TaskView): string[] {
+ return [...renderTaskDetail(ui, view), ...renderTaskSections(ui, view)];
+}
diff --git a/packages/cli/src/task-view/section-result.test.ts b/packages/cli/src/task-view/section-result.test.ts
new file mode 100644
index 000000000..7acef9f49
--- /dev/null
+++ b/packages/cli/src/task-view/section-result.test.ts
@@ -0,0 +1,54 @@
+import { Effect, Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { NotSignedIn, ServerError, SessionExpired } from "../errors/errors.js";
+import {
+ failed,
+ loaded,
+ mapSection,
+ optionalSection,
+ sectionValue,
+} from "./section-result.js";
+
+const run = <A, E>(effect: Effect.Effect<A, E>) =>
+ Effect.runPromise(Effect.result(effect));
+
+describe("optionalSection", () => {
+ it("wraps a loaded value", async () => {
+ expect(await run(optionalSection(Effect.succeed([1, 2])))).toEqual(
+ Result.succeed(loaded([1, 2])),
+ );
+ });
+
+ it("turns other API failures into a failed section with the message", async () => {
+ expect(
+ await run(
+ optionalSection(
+ Effect.fail(new ServerError({ status: 502, message: "Bad gateway" })),
+ ),
+ ),
+ ).toEqual(
+ Result.succeed(failed("The server failed with 502: Bad gateway")),
+ );
+ });
+
+ it("lets sign-in failures through", async () => {
+ const apiUrl = "https://kaneo.test";
+ for (const error of [
+ new NotSignedIn({ apiUrl }),
+ new SessionExpired({ apiUrl }),
+ ]) {
+ expect(await run(optionalSection(Effect.fail(error)))).toEqual(
+ Result.fail(error),
+ );
+ }
+ });
+});
+
+describe("mapSection and sectionValue", () => {
+ it("map loaded values and keep failures", () => {
+ expect(sectionValue(mapSection(loaded(2), (n) => n * 2))).toBe(4);
+ expect(sectionValue(mapSection(failed<number>("x"), (n) => n * 2))).toBe(
+ null,
+ );
+ });
+});
diff --git a/packages/cli/src/task-view/section-result.ts b/packages/cli/src/task-view/section-result.ts
new file mode 100644
index 000000000..79ad9d5a3
--- /dev/null
+++ b/packages/cli/src/task-view/section-result.ts
@@ -0,0 +1,47 @@
+import { Effect } from "effect";
+import type {
+ ApiFailure,
+ NotSignedIn,
+ SessionExpired,
+} from "../errors/errors.js";
+import { describeError } from "../errors/describe.js";
+
+export type SectionResult<A> =
+ | { readonly _tag: "Loaded"; readonly value: A }
+ | { readonly _tag: "Failed"; readonly message: string };
+
+type SignedOut = NotSignedIn | SessionExpired;
+
+function isSignedOut(error: ApiFailure): error is SignedOut {
+ return error._tag === "NotSignedIn" || error._tag === "SessionExpired";
+}
+
+export function loaded<A>(value: A): SectionResult<A> {
+ return { _tag: "Loaded", value };
+}
+
+export function failed<A>(message: string): SectionResult<A> {
+ return { _tag: "Failed", message };
+}
+
+export function mapSection<A, B>(
+ section: SectionResult<A>,
+ f: (value: A) => B,
+): SectionResult<B> {
+ return section._tag === "Loaded" ? loaded(f(section.value)) : section;
+}
+
+export function sectionValue<A>(section: SectionResult<A>): A | null {
+ return section._tag === "Loaded" ? section.value : null;
+}
+
+export const optionalSection = <A, R>(
+ effect: Effect.Effect<A, ApiFailure, R>,
+): Effect.Effect<SectionResult<A>, SignedOut, R> =>
+ effect.pipe(
+ Effect.map(loaded),
+ Effect.catchIf(
+ (error): error is Exclude<ApiFailure, SignedOut> => !isSignedOut(error),
+ (error) => Effect.succeed(failed<A>(describeError(error).message)),
+ ),
+ );
diff --git a/packages/cli/src/task-view/section-title.ts b/packages/cli/src/task-view/section-title.ts
new file mode 100644
index 000000000..505b2db53
--- /dev/null
+++ b/packages/cli/src/task-view/section-title.ts
@@ -0,0 +1,10 @@
+import type { Ui } from "../render/ui.js";
+
+export function sectionTitle(ui: Ui, title: string, meta?: string): string {
+ const { theme } = ui;
+ return ` ${theme.strong(title)}${meta ? ` ${theme.muted(meta)}` : ""}`;
+}
+
+export function failedSection(ui: Ui, title: string): string[] {
+ return [sectionTitle(ui, title, "could not load"), ""];
+}
diff --git a/packages/cli/src/task-view/task-field-values.ts b/packages/cli/src/task-view/task-field-values.ts
new file mode 100644
index 000000000..8e9118818
--- /dev/null
+++ b/packages/cli/src/task-view/task-field-values.ts
@@ -0,0 +1,24 @@
+import { Effect, Schema } from "effect";
+import { KaneoApi } from "../api/kaneo-api.js";
+
+export const TaskFieldValue = Schema.Struct({
+ fieldId: Schema.String,
+ value: Schema.NullOr(Schema.String),
+ fieldName: Schema.String,
+ fieldType: Schema.String,
+ fieldPosition: Schema.Number,
+});
+export type TaskFieldValue = typeof TaskFieldValue.Type;
+
+const TaskFieldValueList = Schema.Array(TaskFieldValue);
+
+export const listTaskFieldValuesWithNames = Effect.fnUntraced(function* (
+ taskId: string,
+) {
+ const api = yield* KaneoApi;
+ return yield* api.request(
+ "GET",
+ `/api/custom-field/task/${encodeURIComponent(taskId)}`,
+ TaskFieldValueList,
+ );
+});
diff --git a/packages/cli/src/task-view/task-fields-json.test.ts b/packages/cli/src/task-view/task-fields-json.test.ts
new file mode 100644
index 000000000..ed294c750
--- /dev/null
+++ b/packages/cli/src/task-view/task-fields-json.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { TaskFieldValue } from "./task-field-values.js";
+import { toTaskFieldsJson } from "./task-fields-json.js";
+
+const value = (
+ fieldId: string,
+ fieldName: string,
+ fieldType: string,
+ raw: string | null,
+ fieldPosition: number,
+): TaskFieldValue => ({
+ fieldId,
+ fieldName,
+ fieldType,
+ value: raw,
+ fieldPosition,
+});
+
+describe("toTaskFieldsJson", () => {
+ it("orders fields like the project, parses values and drops empty ones", () => {
+ expect(
+ toTaskFieldsJson([
+ value("f3", "Shipped", "boolean", "true", 2),
+ value("f1", "Points", "number", "3", 0),
+ value("f4", "Platforms", "multiselect", "[]", 3),
+ value("f2", "Customer", "text", " ", 1),
+ value("f5", "Due in", "date", null, 4),
+ ]),
+ ).toEqual([
+ { id: "f1", name: "Points", type: "number", value: 3 },
+ { id: "f3", name: "Shipped", type: "boolean", value: true },
+ ]);
+ });
+});
diff --git a/packages/cli/src/task-view/task-fields-json.ts b/packages/cli/src/task-view/task-fields-json.ts
new file mode 100644
index 000000000..d44f32bed
--- /dev/null
+++ b/packages/cli/src/task-view/task-fields-json.ts
@@ -0,0 +1,21 @@
+import { fieldValueJson } from "../fields/field-value.js";
+import type { TaskFieldJson } from "../fields/render-task-fields.js";
+import type { TaskFieldValue } from "./task-field-values.js";
+
+export function toTaskFieldsJson(
+ values: ReadonlyArray<TaskFieldValue>,
+): TaskFieldJson[] {
+ return [...values]
+ .sort(
+ (a, b) =>
+ a.fieldPosition - b.fieldPosition ||
+ a.fieldName.localeCompare(b.fieldName),
+ )
+ .map((value) => ({
+ id: value.fieldId,
+ name: value.fieldName,
+ type: value.fieldType,
+ value: fieldValueJson(value.fieldType, value.value),
+ }))
+ .filter((field) => field.value !== null);
+}
diff --git a/packages/cli/src/task-view/task-view-json.test.ts b/packages/cli/src/task-view/task-view-json.test.ts
new file mode 100644
index 000000000..86c38d3b5
--- /dev/null
+++ b/packages/cli/src/task-view/task-view-json.test.ts
@@ -0,0 +1,184 @@
+import { describe, expect, it } from "vite-plus/test";
+import { toTaskDetailJson } from "../tasks/task-detail-json.js";
+import { failed, loaded } from "./section-result.js";
+import {
+ projectSlugsFixture,
+ resolvedTask,
+ sectionsFixture,
+ viewNow,
+ webUrl,
+} from "./test-task-view.js";
+import { toTaskViewJson } from "./task-view-json.js";
+
+const build = (overrides: Partial<Parameters<typeof toTaskViewJson>[0]> = {}) =>
+ toTaskViewJson({
+ resolved: resolvedTask,
+ sections: sectionsFixture,
+ projectSlugs: projectSlugsFixture,
+ webUrl,
+ commentLimit: 3,
+ now: viewNow,
+ ...overrides,
+ });
+
+const taskUrl = (projectId: string, id: string) =>
+ `${webUrl}/dashboard/workspace/ws_1/project/${projectId}/task/${id}`;
+
+describe("toTaskViewJson", () => {
+ it("keeps every task detail key and adds the loaded sections", () => {
+ const json = build();
+ expect(json).toMatchObject(toTaskDetailJson(resolvedTask));
+ expect(json.labels).toEqual([
+ { name: "bug", color: "red" },
+ { name: "auth", color: "#8e51ff" },
+ ]);
+ expect(json.parent).toEqual({
+ id: "t4",
+ ticketId: "KAN-4",
+ title: "Auth overhaul",
+ status: "to-do",
+ completed: false,
+ url: taskUrl("p1", "t4"),
+ });
+ expect(
+ json.subtasks?.map((task) => [task.ticketId, task.completed]),
+ ).toEqual([
+ ["KAN-13", true],
+ ["KAN-14", true],
+ ["KAN-15", false],
+ ["KAN-16", false],
+ ["KAN-17", false],
+ ]);
+ expect(
+ json.relations?.map((relation) => [
+ relation.type,
+ relation.direction,
+ relation.task.ticketId,
+ ]),
+ ).toEqual([
+ ["blocks", "outgoing", "KAN-20"],
+ ["blocked-by", "incoming", "KAN-9"],
+ ["relates-to", "outgoing", "MOB-3"],
+ ]);
+ expect(json.links).toEqual([
+ {
+ id: "x1",
+ url: "https://github.com/usekaneo/kaneo/pull/1960",
+ title: "fix(auth): keep state on device redirect",
+ source: "github",
+ resourceType: "pull_request",
+ removable: false,
+ createdAt: "2026-10-08T10:00:00.000Z",
+ },
+ {
+ id: "x2",
+ url: "https://sentry.io/issues/4211/",
+ title: null,
+ source: "manual",
+ resourceType: "url",
+ removable: true,
+ createdAt: "2026-10-08T10:00:00.000Z",
+ },
+ ]);
+ expect(json.fields).toEqual([
+ { id: "f1", name: "Story points", type: "number", value: 5 },
+ {
+ id: "f2",
+ name: "Platforms",
+ type: "multiselect",
+ value: ["Web", "CLI"],
+ },
+ ]);
+ expect(json.time).toEqual({
+ totalSeconds: 10800,
+ running: [
+ {
+ user: { id: "u1", name: "Ada Lovelace" },
+ startedAt: new Date(2026, 9, 7, 11).toISOString(),
+ },
+ ],
+ });
+ expect(json.comments?.map((comment) => comment.id)).toEqual([
+ "c3",
+ "c4",
+ "c5",
+ ]);
+ expect(json.comments?.[1]).toEqual({
+ id: "c4",
+ taskId: "t12",
+ author: { id: "u1", name: "Ada Lovelace" },
+ content: "First pass is up, please review.",
+ createdAt: new Date(2026, 9, 7, 9).toISOString(),
+ updatedAt: new Date(2026, 9, 7, 10).toISOString(),
+ edited: true,
+ });
+ expect(json).not.toHaveProperty("errors");
+ });
+
+ it("puts the new keys after the existing ones", () => {
+ expect(Object.keys(build()).slice(-8)).toEqual([
+ "labels",
+ "parent",
+ "subtasks",
+ "relations",
+ "links",
+ "fields",
+ "time",
+ "comments",
+ ]);
+ });
+
+ it("returns null and an error message for each section that failed", () => {
+ const json = build({
+ sections: {
+ ...sectionsFixture,
+ relations: failed("The server failed with 500: boom"),
+ time: failed("Time tracking is off."),
+ },
+ });
+ expect(json.parent).toBeNull();
+ expect(json.subtasks).toBeNull();
+ expect(json.relations).toBeNull();
+ expect(json.time).toBeNull();
+ expect(json.labels).not.toBeNull();
+ expect(json.errors).toEqual({
+ relations: "The server failed with 500: boom",
+ time: "Time tracking is off.",
+ });
+ });
+
+ it("returns every comment when the limit is unbounded and none at zero", () => {
+ expect(
+ build({ commentLimit: Number.POSITIVE_INFINITY }).comments,
+ ).toHaveLength(5);
+ expect(build({ commentLimit: 0 }).comments).toEqual([]);
+ });
+
+ it("leaves the ticket id empty for tasks in projects it could not look up", () => {
+ const json = build({ projectSlugs: new Map([["p1", "kan"]]) });
+ expect(json.relations?.at(-1)?.task.ticketId).toBeNull();
+ });
+
+ it("reports empty sections as empty lists", () => {
+ const json = build({
+ sections: {
+ labels: loaded([]),
+ relations: loaded([]),
+ links: loaded([]),
+ fields: loaded([]),
+ time: loaded([]),
+ comments: loaded([]),
+ },
+ });
+ expect(json).toMatchObject({
+ labels: [],
+ parent: null,
+ subtasks: [],
+ relations: [],
+ links: [],
+ fields: [],
+ time: { totalSeconds: 0, running: [] },
+ comments: [],
+ });
+ });
+});
diff --git a/packages/cli/src/task-view/task-view-json.ts b/packages/cli/src/task-view/task-view-json.ts
new file mode 100644
index 000000000..c21b7665b
--- /dev/null
+++ b/packages/cli/src/task-view/task-view-json.ts
@@ -0,0 +1,96 @@
+import {
+ type CommentJson,
+ latest,
+ toCommentJson,
+} from "../comments/comment-json.js";
+import { type LinkJson, toLinkJson } from "../external-links/link-json.js";
+import type { TaskFieldJson } from "../fields/render-task-fields.js";
+import { type TaskLabelJson, toTaskLabelJson } from "../labels/label-json.js";
+import {
+ groupRelations,
+ type RelatedTaskJson,
+ type RelationJson,
+} from "../relations/group-relations.js";
+import type { ResolvedTask } from "../tasks/resolve-task.js";
+import {
+ type TaskDetailJson,
+ toTaskDetailJson,
+} from "../tasks/task-detail-json.js";
+import { mapSection, sectionValue } from "./section-result.js";
+import { toTaskFieldsJson } from "./task-fields-json.js";
+import type {
+ TaskViewSectionName,
+ TaskViewSections,
+} from "./task-view-sections.js";
+import { summarizeTime, type TimeSummaryJson } from "./time-summary.js";
+
+export type TaskViewErrors = Readonly<
+ Partial<Record<TaskViewSectionName, string>>
+>;
+
+export type TaskViewJson = TaskDetailJson & {
+ readonly labels: ReadonlyArray<TaskLabelJson> | null;
+ readonly parent: RelatedTaskJson | null;
+ readonly subtasks: ReadonlyArray<RelatedTaskJson> | null;
+ readonly relations: ReadonlyArray<RelationJson> | null;
+ readonly links: ReadonlyArray<LinkJson> | null;
+ readonly fields: ReadonlyArray<TaskFieldJson> | null;
+ readonly time: TimeSummaryJson | null;
+ readonly comments: ReadonlyArray<CommentJson> | null;
+ readonly errors?: TaskViewErrors;
+};
+
+export type TaskViewInput = {
+ readonly resolved: ResolvedTask;
+ readonly sections: TaskViewSections;
+ readonly projectSlugs: ReadonlyMap<string, string>;
+ readonly webUrl: string;
+ readonly commentLimit: number;
+ readonly now: Date;
+};
+
+function sectionErrors(sections: TaskViewSections): TaskViewErrors {
+ const errors: Partial<Record<TaskViewSectionName, string>> = {};
+ for (const [name, section] of Object.entries(sections)) {
+ if (section._tag === "Failed") {
+ errors[name as TaskViewSectionName] = section.message;
+ }
+ }
+ return errors;
+}
+
+export function toTaskViewJson(input: TaskViewInput): TaskViewJson {
+ const { resolved, sections } = input;
+ const relations = sectionValue(
+ mapSection(sections.relations, (value) =>
+ groupRelations(value, resolved.task.id, {
+ projectSlugs: input.projectSlugs,
+ workspaceId: resolved.workspaceId,
+ webUrl: input.webUrl,
+ }),
+ ),
+ );
+ const errors = sectionErrors(sections);
+ return {
+ ...toTaskDetailJson(resolved),
+ labels: sectionValue(
+ mapSection(sections.labels, (labels) => labels.map(toTaskLabelJson)),
+ ),
+ parent: relations?.parent ?? null,
+ subtasks: relations?.subtasks ?? null,
+ relations: relations?.relations ?? null,
+ links: sectionValue(
+ mapSection(sections.links, (links) => links.map(toLinkJson)),
+ ),
+ fields: sectionValue(mapSection(sections.fields, toTaskFieldsJson)),
+ time: sectionValue(
+ mapSection(sections.time, (entries) => summarizeTime(entries, input.now)),
+ ),
+ comments: sectionValue(
+ mapSection(sections.comments, (comments) =>
+ latest(comments, input.commentLimit).map(toCommentJson),
+ ),
+ ),
+ ...(Object.keys(errors).length > 0 ? { errors } : {}),
+ };
+}
diff --git a/packages/cli/src/task-view/task-view-sections.ts b/packages/cli/src/task-view/task-view-sections.ts
new file mode 100644
index 000000000..d31af8eb4
--- /dev/null
+++ b/packages/cli/src/task-view/task-view-sections.ts
@@ -0,0 +1,18 @@
+import type { TaskComment } from "../api/comments.js";
+import type { ExternalLink } from "../api/external-links.js";
+import type { Label } from "../api/labels.js";
+import type { TaskRelationWithTasks } from "../api/task-relations.js";
+import type { TimeEntryWithUser } from "../api/time-entries.js";
+import type { SectionResult } from "./section-result.js";
+import type { TaskFieldValue } from "./task-field-values.js";
+
+export type TaskViewSections = {
+ readonly labels: SectionResult<ReadonlyArray<Label>>;
+ readonly relations: SectionResult<ReadonlyArray<TaskRelationWithTasks>>;
+ readonly links: SectionResult<ReadonlyArray<ExternalLink>>;
+ readonly fields: SectionResult<ReadonlyArray<TaskFieldValue>>;
+ readonly time: SectionResult<ReadonlyArray<TimeEntryWithUser>>;
+ readonly comments: SectionResult<ReadonlyArray<TaskComment>>;
+};
+
+export type TaskViewSectionName = keyof TaskViewSections;
diff --git a/packages/cli/src/task-view/test-task-view.ts b/packages/cli/src/task-view/test-task-view.ts
new file mode 100644
index 000000000..e869011ba
--- /dev/null
+++ b/packages/cli/src/task-view/test-task-view.ts
@@ -0,0 +1,268 @@
+import type { TaskComment } from "../api/comments.js";
+import type { Column, Project } from "../api/schemas.js";
+import type {
+ RelatedTask,
+ TaskRelationWithTasks,
+} from "../api/task-relations.js";
+import type { TimeEntryWithUser } from "../api/time-entries.js";
+import { externalLink } from "../external-links/test-links.js";
+import type { ResolvedTask } from "../tasks/resolve-task.js";
+import { loaded } from "./section-result.js";
+import type { TaskViewSections } from "./task-view-sections.js";
+
+export const viewNow = new Date(2026, 9, 7, 12, 0, 0);
+
+const at = (days: number, hours = 0) =>
+ new Date(2026, 9, 7 + days, 12 + hours, 0, 0).toISOString();
+
+export const webUrl = "https://kaneo.test";
+
+const project: Project = {
+ id: "p1",
+ workspaceId: "ws_1",
+ slug: "kan",
+ name: "Kaneo Web",
+ icon: null,
+ description: null,
+ archivedAt: null,
+ position: 0,
+ lastTaskNumber: 30,
+};
+
+const columns: ReadonlyArray<Column> = [
+ {
+ id: "c1",
+ projectId: "p1",
+ name: "To Do",
+ slug: "to-do",
+ position: 0,
+ color: null,
+ isFinal: false,
+ },
+ {
+ id: "c2",
+ projectId: "p1",
+ name: "In Progress",
+ slug: "in-progress",
+ position: 1,
+ color: null,
+ isFinal: false,
+ },
+ {
+ id: "c3",
+ projectId: "p1",
+ name: "Done",
+ slug: "done",
+ position: 2,
+ color: null,
+ isFinal: true,
+ },
+];
+
+export const resolvedTask: ResolvedTask = {
+ task: {
+ id: "t12",
+ projectId: "p1",
+ workspaceId: "ws_1",
+ number: 12,
+ title: "Fix login redirect after device approval",
+ description: [
+ "## Steps",
+ "",
+ "1. Sign in with the **device** flow",
+ "2. Approve in the browser",
+ "",
+ "![Redirect loop](/api/asset/redirect.png)",
+ ].join("\n"),
+ status: "in-progress",
+ priority: "urgent",
+ startDate: at(-6),
+ dueDate: at(2),
+ createdAt: at(-8),
+ assigneeId: "u1",
+ assigneeName: "Ada Lovelace",
+ },
+ workspaceId: "ws_1",
+ project,
+ columns,
+ ticketId: "KAN-12",
+ url: `${webUrl}/dashboard/workspace/ws_1/project/p1/task/t12`,
+};
+
+const related = (
+ id: string,
+ number: number,
+ title: string,
+ status = "to-do",
+ projectId = "p1",
+): RelatedTask => ({
+ id,
+ title,
+ status,
+ isCompleted: status === "done",
+ number,
+ projectId,
+});
+
+const me = related("t12", 12, "Fix login redirect after device approval");
+
+let relationId = 0;
+const relation = (
+ source: RelatedTask,
+ target: RelatedTask,
+ relationType: string,
+): TaskRelationWithTasks => ({
+ id: `r${++relationId}`,
+ sourceTaskId: source.id,
+ targetTaskId: target.id,
+ relationType,
+ sourceTask: source,
+ targetTask: target,
+});
+
+export const relationsFixture: ReadonlyArray<TaskRelationWithTasks> = [
+ relation(related("t4", 4, "Auth overhaul"), me, "subtask"),
+ relation(me, related("t13", 13, "Reproduce on Safari", "done"), "subtask"),
+ relation(me, related("t14", 14, "Add a regression test", "done"), "subtask"),
+ relation(
+ me,
+ related("t15", 15, "Handle expired device codes", "in-progress"),
+ "subtask",
+ ),
+ relation(me, related("t16", 16, "Update the login docs"), "subtask"),
+ relation(
+ me,
+ related("t17", 17, "Clean up the redirect helper and its callers"),
+ "subtask",
+ ),
+ relation(related("t9", 9, "Session cookie on the API domain"), me, "blocks"),
+ relation(me, related("t20", 20, "Release 2.36"), "blocks"),
+ relation(me, related("m3", 3, "Mobile sign in", "to-do", "p2"), "related"),
+];
+
+const comment = (
+ id: string,
+ name: string,
+ content: string,
+ createdAt: string,
+ updatedAt = createdAt,
+): TaskComment => ({
+ id,
+ taskId: "t12",
+ userId: name === "Ada Lovelace" ? "u1" : "u2",
+ content,
+ createdAt,
+ updatedAt,
+ user: { name },
+});
+
+export const commentsFixture: ReadonlyArray<TaskComment> = [
+ comment("c1", "Grace Hopper", "Seeing this on staging too.", at(-5)),
+ comment("c2", "Ada Lovelace", "Bisecting now.", at(-4)),
+ comment(
+ "c3",
+ "Grace Hopper",
+ "It started with the cookie change.\n\nThe callback URL drops the **state** param when the device page redirects, so the CLI never sees the approval and keeps polling until the code expires.",
+ at(-1),
+ ),
+ comment(
+ "c4",
+ "Ada Lovelace",
+ "First pass is up, please review.",
+ at(0, -3),
+ at(0, -2),
+ ),
+ comment(
+ "c5",
+ "Grace Hopper",
+ "Looks good. One question:\n\n- do we still need the fallback?\n- can we drop the retry?\n- what about older servers?\n- and API keys?",
+ at(0, -1),
+ ),
+];
+
+const entry = (
+ id: string,
+ startTime: string,
+ endTime: string | null,
+ duration: number | null,
+): TimeEntryWithUser => ({
+ id,
+ taskId: "t12",
+ userId: "u1",
+ description: null,
+ startTime,
+ endTime,
+ duration,
+ userName: "Ada Lovelace",
+});
+
+export const timeFixture: ReadonlyArray<TimeEntryWithUser> = [
+ entry("e1", at(-2), at(-2, 2), 7200),
+ entry("e2", at(0, -1), null, null),
+];
+
+export const sectionsFixture: TaskViewSections = {
+ labels: loaded([
+ {
+ id: "l1",
+ name: "bug",
+ color: "red",
+ taskId: "t12",
+ workspaceId: "ws_1",
+ },
+ {
+ id: "l2",
+ name: "auth",
+ color: "#8e51ff",
+ taskId: "t12",
+ workspaceId: "ws_1",
+ },
+ ]),
+ relations: loaded(relationsFixture),
+ links: loaded([
+ externalLink({
+ id: "x1",
+ taskId: "t12",
+ url: "https://github.com/usekaneo/kaneo/pull/1960",
+ title: "fix(auth): keep state on device redirect",
+ resourceType: "pull_request",
+ integrationId: "i1",
+ integration: { id: "i1", type: "github" },
+ }),
+ externalLink({
+ id: "x2",
+ taskId: "t12",
+ url: "https://sentry.io/issues/4211/",
+ }),
+ ]),
+ fields: loaded([
+ {
+ fieldId: "f2",
+ value: '["Web","CLI"]',
+ fieldName: "Platforms",
+ fieldType: "multiselect",
+ fieldPosition: 1,
+ },
+ {
+ fieldId: "f1",
+ value: "5",
+ fieldName: "Story points",
+ fieldType: "number",
+ fieldPosition: 0,
+ },
+ {
+ fieldId: "f3",
+ value: "",
+ fieldName: "Customer",
+ fieldType: "text",
+ fieldPosition: 2,
+ },
+ ]),
+ time: loaded(timeFixture),
+ comments: loaded(commentsFixture),
+};
+
+export const projectSlugsFixture: ReadonlyMap<string, string> = new Map([
+ ["p1", "kan"],
+ ["p2", "mob"],
+]);
diff --git a/packages/cli/src/task-view/time-summary.test.ts b/packages/cli/src/task-view/time-summary.test.ts
new file mode 100644
index 000000000..a394bc0db
--- /dev/null
+++ b/packages/cli/src/task-view/time-summary.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { TimeEntryWithUser } from "../api/time-entries.js";
+import { summarizeTime } from "./time-summary.js";
+
+const now = new Date("2026-10-07T12:00:00.000Z");
+
+const entry = (
+ overrides: Partial<TimeEntryWithUser> & { readonly id: string },
+): TimeEntryWithUser => ({
+ taskId: "t1",
+ userId: "u1",
+ userName: "Ada Lovelace",
+ description: null,
+ startTime: "2026-10-07T08:00:00.000Z",
+ endTime: "2026-10-07T09:00:00.000Z",
+ duration: 3600,
+ ...overrides,
+});
+
+describe("summarizeTime", () => {
+ it("adds up finished entries and the time on running timers", () => {
+ expect(
+ summarizeTime(
+ [
+ entry({ id: "e1" }),
+ entry({
+ id: "e2",
+ userId: "u2",
+ userName: "Grace Hopper",
+ startTime: "2026-10-07T11:30:00.000Z",
+ endTime: null,
+ duration: null,
+ }),
+ entry({
+ id: "e3",
+ startTime: "2026-10-07T11:00:00.000Z",
+ endTime: null,
+ duration: null,
+ }),
+ ],
+ now,
+ ),
+ ).toEqual({
+ totalSeconds: 3600 + 1800 + 3600,
+ running: [
+ {
+ user: { id: "u1", name: "Ada Lovelace" },
+ startedAt: "2026-10-07T11:00:00.000Z",
+ },
+ {
+ user: { id: "u2", name: "Grace Hopper" },
+ startedAt: "2026-10-07T11:30:00.000Z",
+ },
+ ],
+ });
+ });
+
+ it("reports nothing tracked for a task without entries", () => {
+ expect(summarizeTime([], now)).toEqual({ totalSeconds: 0, running: [] });
+ });
+
+ it("keeps a running timer without a user", () => {
+ expect(
+ summarizeTime(
+ [entry({ id: "e1", userId: null, endTime: null, duration: null })],
+ now,
+ ).running,
+ ).toEqual([{ user: null, startedAt: "2026-10-07T08:00:00.000Z" }]);
+ });
+});
diff --git a/packages/cli/src/task-view/time-summary.ts b/packages/cli/src/task-view/time-summary.ts
new file mode 100644
index 000000000..7622b4d1f
--- /dev/null
+++ b/packages/cli/src/task-view/time-summary.ts
@@ -0,0 +1,31 @@
+import type { TimeEntryWithUser } from "../api/time-entries.js";
+import { entrySeconds } from "../time/entry-seconds.js";
+
+export type RunningTimerJson = {
+ readonly user: { readonly id: string; readonly name: string | null } | null;
+ readonly startedAt: string;
+};
+
+export type TimeSummaryJson = {
+ readonly totalSeconds: number;
+ readonly running: ReadonlyArray<RunningTimerJson>;
+};
+
+export function summarizeTime(
+ entries: ReadonlyArray<TimeEntryWithUser>,
+ now: Date,
+): TimeSummaryJson {
+ return {
+ totalSeconds: entries.reduce(
+ (sum, entry) => sum + entrySeconds(entry, now),
+ 0,
+ ),
+ running: entries
+ .filter((entry) => entry.endTime === null)
+ .sort((a, b) => Date.parse(a.startTime) - Date.parse(b.startTime))
+ .map((entry) => ({
+ user: entry.userId ? { id: entry.userId, name: entry.userName } : null,
+ startedAt: entry.startTime,
+ })),
+ };
+}
diff --git a/packages/cli/src/task-view/time-value.test.ts b/packages/cli/src/task-view/time-value.test.ts
new file mode 100644
index 000000000..b4f860aa8
--- /dev/null
+++ b/packages/cli/src/task-view/time-value.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from "vite-plus/test";
+import { renderCell } from "../render/cell.js";
+import { makeUi } from "../render/ui.js";
+import { hasTrackedTime, timeValue } from "./time-value.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+const timer = (name: string | null) => ({
+ user: name ? { id: name, name } : null,
+ startedAt: "2026-10-07T11:00:00.000Z",
+});
+
+describe("timeValue", () => {
+ it("shows the total on its own when nothing is running", () => {
+ expect(
+ renderCell(timeValue(ui, { totalSeconds: 5400, running: [] }), ui),
+ ).toBe("1h 30m");
+ });
+
+ it("names everyone with a running timer once", () => {
+ expect(
+ renderCell(
+ timeValue(ui, {
+ totalSeconds: 600,
+ running: [timer("Ada"), timer("Grace"), timer("Ada"), timer(null)],
+ }),
+ ui,
+ ),
+ ).toBe("10m · ● Timer running (Ada, Grace, someone)");
+ });
+});
+
+describe("hasTrackedTime", () => {
+ it("is true with logged time or a timer that just started", () => {
+ expect(hasTrackedTime({ totalSeconds: 0, running: [] })).toBe(false);
+ expect(hasTrackedTime({ totalSeconds: 60, running: [] })).toBe(true);
+ expect(hasTrackedTime({ totalSeconds: 0, running: [timer("Ada")] })).toBe(
+ true,
+ );
+ });
+});
diff --git a/packages/cli/src/task-view/time-value.ts b/packages/cli/src/task-view/time-value.ts
new file mode 100644
index 000000000..0bd90cc69
--- /dev/null
+++ b/packages/cli/src/task-view/time-value.ts
@@ -0,0 +1,23 @@
+import { type Cell, text } from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+import { formatDuration } from "../time/duration.js";
+import type { TimeSummaryJson } from "./time-summary.js";
+
+export function hasTrackedTime(time: TimeSummaryJson): boolean {
+ return time.totalSeconds > 0 || time.running.length > 0;
+}
+
+export function timeValue(ui: Ui, time: TimeSummaryJson): Cell {
+ const { theme, glyphs } = ui;
+ const total = text(formatDuration(time.totalSeconds));
+ if (time.running.length === 0) return [total];
+ const names = [
+ ...new Set(time.running.map((timer) => timer.user?.name ?? "someone")),
+ ];
+ return [
+ total,
+ text(` ${glyphs.separator} `, theme.muted),
+ text(`${glyphs.dot} Timer running`, theme.success),
+ text(` (${names.join(", ")})`, theme.muted),
+ ];
+}
diff --git a/packages/cli/src/tasks/comment-text.test.ts b/packages/cli/src/tasks/comment-text.test.ts
new file mode 100644
index 000000000..6d50d7c92
--- /dev/null
+++ b/packages/cli/src/tasks/comment-text.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from "vite-plus/test";
+import { firstLine, normalizeComment } from "./comment-text.js";
+
+describe("normalizeComment", () => {
+ it("drops leading blank lines and trailing whitespace", () => {
+ expect(normalizeComment("\n \nShipped in v2\n\n")).toBe("Shipped in v2");
+ });
+
+ it("keeps indentation on the first line and inner blank lines", () => {
+ expect(normalizeComment(" code\n\nmore \n")).toBe(" code\n\nmore");
+ });
+
+ it("returns an empty string for whitespace", () => {
+ expect(normalizeComment(" \n\t\n ")).toBe("");
+ });
+});
+
+describe("firstLine", () => {
+ it("returns the first non-empty line and whether more follow", () => {
+ expect(firstLine("\n Looks good \n\nShip it")).toEqual({
+ line: "Looks good",
+ more: true,
+ });
+ expect(firstLine("Done")).toEqual({ line: "Done", more: false });
+ });
+});
diff --git a/packages/cli/src/tasks/comment-text.ts b/packages/cli/src/tasks/comment-text.ts
new file mode 100644
index 000000000..dd0f188a7
--- /dev/null
+++ b/packages/cli/src/tasks/comment-text.ts
@@ -0,0 +1,14 @@
+export function normalizeComment(text: string): string {
+ return text.replace(/^(?:[ \t]*\r?\n)+/u, "").trimEnd();
+}
+
+export function firstLine(text: string): {
+ readonly line: string;
+ readonly more: boolean;
+} {
+ const lines = text
+ .split(/\r?\n/u)
+ .map((line) => line.trim())
+ .filter((line) => line !== "");
+ return { line: lines[0] ?? "", more: lines.length > 1 };
+}
diff --git a/packages/cli/src/tasks/create-status.test.ts b/packages/cli/src/tasks/create-status.test.ts
new file mode 100644
index 000000000..8bd176016
--- /dev/null
+++ b/packages/cli/src/tasks/create-status.test.ts
@@ -0,0 +1,60 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import type { Column } from "../api/schemas.js";
+import { createStatus } from "./create-status.js";
+
+const column = (slug: string, name: string, position: number): Column => ({
+ id: `column-${slug}`,
+ projectId: "project-1",
+ slug,
+ name,
+ position,
+ color: null,
+ isFinal: slug === "done",
+});
+
+const columns = [
+ column("done", "Done", 3),
+ column("in-progress", "In Progress", 1),
+ column("to-do", "To Do", 0),
+];
+
+const slugOf = (result: Result.Result<Column | null, unknown>) =>
+ Result.isSuccess(result) ? (result.success?.slug ?? null) : "failed";
+
+describe("createStatus", () => {
+ it("defaults to the first column by position", () => {
+ expect(slugOf(createStatus(columns, undefined, "Kaneo Web"))).toBe("to-do");
+ });
+
+ it("has no default without columns", () => {
+ expect(slugOf(createStatus([], undefined, "Kaneo Web"))).toBeNull();
+ });
+
+ it("matches slugs and names without case", () => {
+ expect(slugOf(createStatus(columns, "IN-PROGRESS", "Kaneo Web"))).toBe(
+ "in-progress",
+ );
+ expect(slugOf(createStatus(columns, " in progress ", "Kaneo Web"))).toBe(
+ "in-progress",
+ );
+ });
+
+ it("accepts the same aliases as kaneo task status", () => {
+ const result = createStatus(columns, "doing", "Kaneo Web");
+ expect(Result.isSuccess(result) && result.success?.slug).toBe(
+ "in-progress",
+ );
+ });
+
+ it("lists the columns when nothing matches", () => {
+ const result = createStatus(columns, "blocked", "Kaneo Web");
+ expect(Result.isFailure(result)).toBe(true);
+ if (Result.isFailure(result)) {
+ expect(result.failure.message).toBe('Kaneo Web has no column "blocked".');
+ expect(result.failure.hint).toBe(
+ "Pass -s with one of: to-do, in-progress, done.",
+ );
+ }
+ });
+});
diff --git a/packages/cli/src/tasks/create-status.ts b/packages/cli/src/tasks/create-status.ts
new file mode 100644
index 000000000..a06d21fe0
--- /dev/null
+++ b/packages/cli/src/tasks/create-status.ts
@@ -0,0 +1,27 @@
+import { Result } from "effect";
+import type { Column } from "../api/schemas.js";
+import { InvalidArgument } from "../errors/errors.js";
+import { matchColumn } from "./match-column.js";
+
+export const FALLBACK_STATUS = "to-do";
+
+export function createStatus(
+ columns: ReadonlyArray<Column>,
+ wanted: string | undefined,
+ projectName: string,
+): Result.Result<Column | null, InvalidArgument> {
+ const ordered = [...columns].sort((a, b) => a.position - b.position);
+ if (wanted === undefined) return Result.succeed(ordered[0] ?? null);
+ const match = matchColumn(ordered, wanted);
+ if (match) return Result.succeed(match);
+ return Result.fail(
+ new InvalidArgument({
+ message: `${projectName} has no column "${wanted}".`,
+ ...(ordered.length > 0
+ ? {
+ hint: `Pass -s with one of: ${ordered.map((column) => column.slug).join(", ")}.`,
+ }
+ : {}),
+ }),
+ );
+}
diff --git a/packages/cli/src/tasks/date-range.test.ts b/packages/cli/src/tasks/date-range.test.ts
new file mode 100644
index 000000000..a41b9279c
--- /dev/null
+++ b/packages/cli/src/tasks/date-range.test.ts
@@ -0,0 +1,26 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { checkDateRange } from "./date-range.js";
+
+const at = (day: number, hour: number) =>
+ new Date(2026, 9, day, hour).toISOString();
+
+describe("checkDateRange", () => {
+ it("accepts missing dates", () => {
+ expect(Result.isSuccess(checkDateRange(null, null))).toBe(true);
+ expect(Result.isSuccess(checkDateRange(at(9, 12), undefined))).toBe(true);
+ expect(Result.isSuccess(checkDateRange(undefined, at(9, 12)))).toBe(true);
+ });
+
+ it("accepts a start on or before the due day", () => {
+ expect(Result.isSuccess(checkDateRange(at(8, 12), at(9, 12)))).toBe(true);
+ expect(Result.isSuccess(checkDateRange(at(9, 23), at(9, 1)))).toBe(true);
+ });
+
+ it("rejects a start after the due day", () => {
+ const result = checkDateRange(at(10, 0), at(9, 23));
+ expect(Result.isFailure(result) && result.failure.message).toBe(
+ "The start date is after the due date.",
+ );
+ });
+});
diff --git a/packages/cli/src/tasks/date-range.ts b/packages/cli/src/tasks/date-range.ts
new file mode 100644
index 000000000..5984388e4
--- /dev/null
+++ b/packages/cli/src/tasks/date-range.ts
@@ -0,0 +1,25 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+
+function localDay(value: string): number | null {
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime())) return null;
+ return date.getFullYear() * 10_000 + date.getMonth() * 100 + date.getDate();
+}
+
+export function checkDateRange(
+ start: string | null | undefined,
+ due: string | null | undefined,
+): Result.Result<void, InvalidArgument> {
+ const startDay = start ? localDay(start) : null;
+ const dueDay = due ? localDay(due) : null;
+ if (startDay !== null && dueDay !== null && startDay > dueDay) {
+ return Result.fail(
+ new InvalidArgument({
+ message: "The start date is after the due date.",
+ hint: "Pick a start date on or before the due date, or move the due date with --due.",
+ }),
+ );
+ }
+ return Result.succeed(undefined);
+}
diff --git a/packages/cli/src/tasks/list-query.test.ts b/packages/cli/src/tasks/list-query.test.ts
new file mode 100644
index 000000000..364cbc105
--- /dev/null
+++ b/packages/cli/src/tasks/list-query.test.ts
@@ -0,0 +1,191 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import type { BoardTask } from "../api/schemas.js";
+import {
+ checkDueWindow,
+ dueBound,
+ filterTasks,
+ hasLabels,
+ needsClientFilter,
+ sortTasks,
+ toTaskSort,
+} from "./list-query.js";
+
+function task(overrides: Partial<BoardTask> & { readonly id: string }) {
+ return {
+ title: overrides.id,
+ number: 1,
+ status: "to-do",
+ priority: "no-priority",
+ startDate: null,
+ dueDate: null,
+ createdAt: "2026-10-01T10:00:00.000Z",
+ assigneeId: null,
+ assigneeName: null,
+ projectId: "p1",
+ ...overrides,
+ } satisfies BoardTask;
+}
+
+const columns = [
+ { slug: "to-do", name: "To Do", isFinal: false },
+ { slug: "done", name: "Done", isFinal: true },
+];
+
+describe("toTaskSort", () => {
+ it("maps the flag names to the API sort fields", () => {
+ expect(Result.getOrThrow(toTaskSort("due", undefined))).toEqual({
+ sortBy: "dueDate",
+ sortOrder: "asc",
+ });
+ expect(Result.getOrThrow(toTaskSort("created", "asc"))).toEqual({
+ sortBy: "createdAt",
+ sortOrder: "asc",
+ });
+ expect(Result.getOrThrow(toTaskSort("title", "desc"))).toEqual({
+ sortBy: "title",
+ sortOrder: "desc",
+ });
+ });
+
+ it("puts urgent and newest first unless an order is given", () => {
+ expect(Result.getOrThrow(toTaskSort("priority", undefined))).toEqual({
+ sortBy: "priority",
+ sortOrder: "desc",
+ });
+ expect(Result.getOrThrow(toTaskSort("created", undefined))?.sortOrder).toBe(
+ "desc",
+ );
+ });
+
+ it("keeps the server order without --sort", () => {
+ expect(Result.getOrThrow(toTaskSort(undefined, undefined))).toBeUndefined();
+ });
+
+ it("refuses --order without --sort", () => {
+ const result = toTaskSort(undefined, "desc");
+ expect(Result.isFailure(result)).toBe(true);
+ });
+});
+
+describe("dueBound", () => {
+ const now = new Date(2026, 9, 8, 15, 0, 0);
+
+ it("covers the whole day for --due-before", () => {
+ const bound = new Date(
+ Result.getOrThrow(dueBound("2026-10-10", now, "before")),
+ );
+ expect([bound.getDate(), bound.getHours(), bound.getMinutes()]).toEqual([
+ 10, 23, 59,
+ ]);
+ });
+
+ it("starts at midnight for --due-after", () => {
+ const bound = new Date(
+ Result.getOrThrow(dueBound("tomorrow", now, "after")),
+ );
+ expect([bound.getDate(), bound.getHours(), bound.getMinutes()]).toEqual([
+ 9, 0, 0,
+ ]);
+ });
+
+ it("names the flag when the date is invalid", () => {
+ const result = dueBound("someday", now, "after");
+ expect(Result.isFailure(result)).toBe(true);
+ if (Result.isFailure(result)) {
+ expect(result.failure.message).toBe(
+ '--due-after "someday" is not a date.',
+ );
+ }
+ });
+
+ it("rejects a window that ends before it starts", () => {
+ const after = Result.getOrThrow(dueBound("2026-10-12", now, "after"));
+ const before = Result.getOrThrow(dueBound("2026-10-10", now, "before"));
+ expect(Result.isFailure(checkDueWindow(after, before))).toBe(true);
+ expect(Result.isSuccess(checkDueWindow(before, before))).toBe(true);
+ });
+});
+
+describe("client filters", () => {
+ const bug = { id: "l1", name: "Bug", color: "#f00" };
+ const ui = { id: "l2", name: "UI", color: "#00f" };
+
+ it("matches label names without regard to case and requires all of them", () => {
+ expect(hasLabels(task({ id: "a", labels: [bug, ui] }), ["bug", "ui"])).toBe(
+ true,
+ );
+ expect(hasLabels(task({ id: "a", labels: [bug] }), ["bug", "ui"])).toBe(
+ false,
+ );
+ expect(hasLabels(task({ id: "a" }), [])).toBe(true);
+ expect(hasLabels(task({ id: "a" }), ["bug"])).toBe(false);
+ });
+
+ it("hides tasks in final columns with --open", () => {
+ const tasks = [
+ task({ id: "a", status: "to-do", labels: [bug] }),
+ task({ id: "b", status: "done", labels: [bug] }),
+ task({ id: "c", status: "to-do" }),
+ ];
+ expect(
+ filterTasks(tasks, columns, { labels: ["Bug"], open: true }).map(
+ (item) => item.id,
+ ),
+ ).toEqual(["a"]);
+ expect(
+ filterTasks(tasks, columns, { labels: [], open: true }).map(
+ (item) => item.id,
+ ),
+ ).toEqual(["a", "c"]);
+ });
+
+ it("only loads the whole board when a client filter is set", () => {
+ expect(needsClientFilter({ labels: [], open: false })).toBe(false);
+ expect(needsClientFilter({ labels: ["bug"], open: false })).toBe(true);
+ expect(needsClientFilter({ labels: [], open: true })).toBe(true);
+ });
+});
+
+describe("sortTasks", () => {
+ it("orders by priority rank, not by name", () => {
+ const tasks = [
+ task({ id: "a", priority: "low" }),
+ task({ id: "b", priority: "urgent" }),
+ task({ id: "c", priority: "no-priority" }),
+ task({ id: "d", priority: "high" }),
+ ];
+ expect(
+ sortTasks(tasks, { sortBy: "priority", sortOrder: "desc" }).map(
+ (item) => item.id,
+ ),
+ ).toEqual(["b", "d", "a", "c"]);
+ });
+
+ it("puts tasks without a due date last when ascending, like the API", () => {
+ const tasks = [
+ task({ id: "a" }),
+ task({ id: "b", dueDate: "2026-10-12T12:00:00.000Z" }),
+ task({ id: "c", dueDate: "2026-10-09T12:00:00.000Z" }),
+ ];
+ expect(
+ sortTasks(tasks, { sortBy: "dueDate", sortOrder: "asc" }).map(
+ (item) => item.id,
+ ),
+ ).toEqual(["c", "b", "a"]);
+ expect(
+ sortTasks(tasks, { sortBy: "dueDate", sortOrder: "desc" }).map(
+ (item) => item.id,
+ ),
+ ).toEqual(["a", "b", "c"]);
+ });
+
+ it("breaks ties by id", () => {
+ const tasks = [task({ id: "b", number: 2 }), task({ id: "a", number: 2 })];
+ expect(
+ sortTasks(tasks, { sortBy: "number", sortOrder: "desc" }).map(
+ (item) => item.id,
+ ),
+ ).toEqual(["a", "b"]);
+ });
+});
diff --git a/packages/cli/src/tasks/list-query.ts b/packages/cli/src/tasks/list-query.ts
new file mode 100644
index 000000000..6d8dbe13e
--- /dev/null
+++ b/packages/cli/src/tasks/list-query.ts
@@ -0,0 +1,185 @@
+import { Result } from "effect";
+import type { BoardTask } from "../api/schemas.js";
+import { InvalidArgument } from "../errors/errors.js";
+import type { BoardColumnSummary, TaskSortField } from "./load-board.js";
+import { parseDateInput } from "./parse-date.js";
+
+export const SORT_FIELDS = [
+ "created",
+ "priority",
+ "due",
+ "position",
+ "title",
+ "number",
+] as const;
+export type SortField = (typeof SORT_FIELDS)[number];
+
+export const SORT_ORDERS = ["asc", "desc"] as const;
+export type SortOrder = (typeof SORT_ORDERS)[number];
+
+const API_SORT: Readonly<Record<SortField, TaskSortField>> = {
+ created: "createdAt",
+ priority: "priority",
+ due: "dueDate",
+ position: "position",
+ title: "title",
+ number: "number",
+};
+
+export type TaskSort = {
+ readonly sortBy: TaskSortField;
+ readonly sortOrder: SortOrder;
+};
+
+export function toTaskSort(
+ field: SortField | undefined,
+ order: SortOrder | undefined,
+): Result.Result<TaskSort | undefined, InvalidArgument> {
+ if (field === undefined) {
+ return order === undefined
+ ? Result.succeed(undefined)
+ : Result.fail(
+ new InvalidArgument({
+ message: "--order needs --sort.",
+ hint: "Pass --sort created, priority, due, position, title or number.",
+ }),
+ );
+ }
+ const fallback: SortOrder =
+ field === "priority" || field === "created" ? "desc" : "asc";
+ return Result.succeed({
+ sortBy: API_SORT[field],
+ sortOrder: order ?? fallback,
+ });
+}
+
+export function dueBound(
+ input: string,
+ now: Date,
+ edge: "before" | "after",
+): Result.Result<string, InvalidArgument> {
+ const flag = edge === "before" ? "--due-before" : "--due-after";
+ return Result.map(parseDateInput(input, now, flag), (iso) => {
+ const day = new Date(iso);
+ const bound =
+ edge === "before"
+ ? new Date(
+ day.getFullYear(),
+ day.getMonth(),
+ day.getDate(),
+ 23,
+ 59,
+ 59,
+ 999,
+ )
+ : new Date(day.getFullYear(), day.getMonth(), day.getDate());
+ return bound.toISOString();
+ });
+}
+
+export function checkDueWindow(
+ after: string | undefined,
+ before: string | undefined,
+): Result.Result<void, InvalidArgument> {
+ if (after && before && new Date(after) > new Date(before)) {
+ return Result.fail(
+ new InvalidArgument({
+ message: "--due-after is later than --due-before.",
+ hint: "Pick a --due-after date on or before the --due-before date.",
+ }),
+ );
+ }
+ return Result.succeed(undefined);
+}
+
+function normalizeLabel(name: string): string {
+ return name.normalize("NFKC").trim().toLowerCase();
+}
+
+export function hasLabels(
+ task: Pick<BoardTask, "labels">,
+ wanted: ReadonlyArray<string>,
+): boolean {
+ if (wanted.length === 0) return true;
+ const names = new Set(
+ (task.labels ?? []).map((label) => normalizeLabel(label.name)),
+ );
+ return wanted.every((name) => names.has(normalizeLabel(name)));
+}
+
+export type ClientFilters = {
+ readonly labels: ReadonlyArray<string>;
+ readonly open: boolean;
+};
+
+export function needsClientFilter(filters: ClientFilters): boolean {
+ return filters.labels.length > 0 || filters.open;
+}
+
+export function filterTasks(
+ tasks: ReadonlyArray<BoardTask>,
+ columns: ReadonlyArray<BoardColumnSummary>,
+ filters: ClientFilters,
+): BoardTask[] {
+ const finalSlugs = new Set(
+ columns.filter((column) => column.isFinal).map((column) => column.slug),
+ );
+ return tasks.filter(
+ (task) =>
+ hasLabels(task, filters.labels) &&
+ !(filters.open && finalSlugs.has(task.status)),
+ );
+}
+
+const PRIORITY_RANK: Readonly<Record<string, number>> = {
+ urgent: 4,
+ high: 3,
+ medium: 2,
+ low: 1,
+};
+
+function sortKey(
+ task: BoardTask,
+ field: TaskSortField,
+): number | string | null {
+ switch (field) {
+ case "priority":
+ return PRIORITY_RANK[task.priority] ?? 0;
+ case "dueDate":
+ return task.dueDate ? new Date(task.dueDate).getTime() : null;
+ case "createdAt":
+ return new Date(task.createdAt).getTime();
+ case "title":
+ return task.title.toLowerCase();
+ case "number":
+ return task.number;
+ case "position":
+ return task.position ?? null;
+ }
+}
+
+function compareKeys(
+ a: number | string | null,
+ b: number | string | null,
+ order: SortOrder,
+): number {
+ if (a === b) return 0;
+ if (a === null) return order === "asc" ? 1 : -1;
+ if (b === null) return order === "asc" ? -1 : 1;
+ const base = a < b ? -1 : 1;
+ return order === "asc" ? base : -base;
+}
+
+export function sortTasks(
+ tasks: ReadonlyArray<BoardTask>,
+ sort: TaskSort,
+): BoardTask[] {
+ return [...tasks].sort(
+ (a, b) =>
+ compareKeys(
+ sortKey(a, sort.sortBy),
+ sortKey(b, sort.sortBy),
+ sort.sortOrder,
+ ) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0),
+ );
+}
diff --git a/packages/cli/src/tasks/load-board.ts b/packages/cli/src/tasks/load-board.ts
new file mode 100644
index 000000000..b97a824a1
--- /dev/null
+++ b/packages/cli/src/tasks/load-board.ts
@@ -0,0 +1,126 @@
+import { Effect } from "effect";
+import { getBoardPage } from "../api/endpoints.js";
+import type { Query } from "../api/kaneo-api.js";
+import type { BoardLabel, BoardTask } from "../api/schemas.js";
+
+export type TaskSortField =
+ | "createdAt"
+ | "priority"
+ | "dueDate"
+ | "position"
+ | "title"
+ | "number";
+
+export type TaskFilters = {
+ readonly status?: string | undefined;
+ readonly priority?: string | undefined;
+ readonly assigneeId?: string | undefined;
+ readonly sortBy?: TaskSortField | undefined;
+ readonly sortOrder?: "asc" | "desc" | undefined;
+ readonly dueBefore?: string | undefined;
+ readonly dueAfter?: string | undefined;
+};
+
+export type BoardColumnSummary = {
+ readonly slug: string;
+ readonly name: string;
+ readonly isFinal: boolean;
+};
+
+export type LoadedBoard = {
+ readonly projectId: string;
+ readonly workspaceId: string;
+ readonly projectSlug: string;
+ readonly projectName: string;
+ readonly columns: ReadonlyArray<BoardColumnSummary>;
+ readonly tasks: ReadonlyArray<BoardTask>;
+ readonly total: number;
+};
+
+const PAGE_SIZE = 100;
+
+const loadExtraLabels = Effect.fnUntraced(function* (
+ projectId: string,
+ query: Query,
+ relatedTotalPages: number,
+) {
+ const labels = new Map<string, BoardLabel[]>();
+ for (let relatedPage = 2; relatedPage <= relatedTotalPages; relatedPage++) {
+ const response = yield* getBoardPage(projectId, { ...query, relatedPage });
+ for (const column of response.data.columns) {
+ for (const task of column.tasks) {
+ if (!task.labels || task.labels.length === 0) continue;
+ labels.set(task.id, [...(labels.get(task.id) ?? []), ...task.labels]);
+ }
+ }
+ }
+ return labels;
+});
+
+export const loadBoard = Effect.fn("tasks.loadBoard")(function* (
+ projectId: string,
+ filters: TaskFilters,
+ limit: number,
+) {
+ const columns = new Map<string, BoardColumnSummary>();
+ const tasks: BoardTask[] = [];
+ let page = 1;
+ let totalPages = 1;
+ let total = 0;
+ let meta = { workspaceId: "", slug: "", name: "" };
+
+ while (page <= totalPages && tasks.length < limit) {
+ const query: Query = {
+ page,
+ limit: Math.min(PAGE_SIZE, limit),
+ status: filters.status,
+ priority: filters.priority,
+ assigneeId: filters.assigneeId,
+ sortBy: filters.sortBy,
+ sortOrder: filters.sortOrder,
+ dueBefore: filters.dueBefore,
+ dueAfter: filters.dueAfter,
+ };
+ const response = yield* getBoardPage(projectId, query);
+ meta = {
+ workspaceId: response.data.workspaceId,
+ slug: response.data.slug,
+ name: response.data.name,
+ };
+ const relatedTotalPages = response.pagination.relatedTotalPages ?? 1;
+ const extraLabels =
+ relatedTotalPages > 1
+ ? yield* loadExtraLabels(projectId, query, relatedTotalPages)
+ : new Map<string, BoardLabel[]>();
+ for (const column of response.data.columns) {
+ if (!columns.has(column.slug)) {
+ columns.set(column.slug, {
+ slug: column.slug,
+ name: column.name,
+ isFinal: column.isFinal,
+ });
+ }
+ for (const task of column.tasks) {
+ const extra = extraLabels.get(task.id);
+ tasks.push(
+ extra
+ ? { ...task, labels: [...(task.labels ?? []), ...extra] }
+ : task,
+ );
+ }
+ }
+ total = response.pagination.total;
+ totalPages = response.pagination.totalPages;
+ page += 1;
+ }
+
+ return {
+ projectId,
+ workspaceId: meta.workspaceId,
+ projectSlug: meta.slug,
+ projectName: meta.name,
+ columns: [...columns.values()],
+ tasks: tasks.slice(0, limit),
+ total,
+ } satisfies LoadedBoard;
+});
diff --git a/packages/cli/src/tasks/match-column.test.ts b/packages/cli/src/tasks/match-column.test.ts
new file mode 100644
index 000000000..997a8cef6
--- /dev/null
+++ b/packages/cli/src/tasks/match-column.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from "vite-plus/test";
+import { matchColumn } from "./match-column.js";
+
+const columns = [
+ { id: "c1", slug: "to-do", name: "To Do" },
+ { id: "c2", slug: "in-progress", name: "In Progress" },
+ { id: "c3", slug: "in-review", name: "In Review" },
+ { id: "c4", slug: "done", name: "Done" },
+];
+
+const slugOf = (reference: string) => matchColumn(columns, reference)?.slug;
+
+describe("matchColumn", () => {
+ it("matches the slug in any case", () => {
+ expect(slugOf("in-progress")).toBe("in-progress");
+ expect(slugOf("IN-PROGRESS")).toBe("in-progress");
+ });
+
+ it("matches the column id", () => {
+ expect(slugOf("c3")).toBe("in-review");
+ });
+
+ it("matches the name in any case", () => {
+ expect(slugOf("in review")).toBe("in-review");
+ expect(slugOf(" Done ")).toBe("done");
+ });
+
+ it("ignores spaces, dashes and underscores", () => {
+ expect(slugOf("todo")).toBe("to-do");
+ expect(slugOf("to_do")).toBe("to-do");
+ expect(slugOf("InProgress")).toBe("in-progress");
+ });
+
+ it("accepts common aliases", () => {
+ expect(slugOf("doing")).toBe("in-progress");
+ expect(slugOf("wip")).toBe("in-progress");
+ expect(slugOf("review")).toBe("in-review");
+ expect(slugOf("completed")).toBe("done");
+ });
+
+ it("prefers a real column over an alias", () => {
+ const custom = [...columns, { id: "c5", slug: "doing", name: "Doing" }];
+ expect(matchColumn(custom, "doing")?.id).toBe("c5");
+ });
+
+ it("rejects aliases that map to more than one column", () => {
+ const custom = [
+ { slug: "in-progress", name: "In Progress" },
+ { slug: "wip", name: "In progress" },
+ ];
+ expect(matchColumn(custom, "doing")).toBeUndefined();
+ });
+
+ it("rejects loose matches that hit more than one column", () => {
+ const custom = [
+ { slug: "todo", name: "Later" },
+ { slug: "to-do-now", name: "To Do" },
+ ];
+ expect(matchColumn(custom, "to do")?.slug).toBe("to-do-now");
+ expect(matchColumn(custom, "to_do")).toBeUndefined();
+ });
+
+ it("returns nothing for unknown or empty input", () => {
+ expect(slugOf("shipped")).toBeUndefined();
+ expect(slugOf(" ")).toBeUndefined();
+ expect(slugOf("-")).toBeUndefined();
+ });
+});
diff --git a/packages/cli/src/tasks/match-column.ts b/packages/cli/src/tasks/match-column.ts
new file mode 100644
index 000000000..b7f7ffe01
--- /dev/null
+++ b/packages/cli/src/tasks/match-column.ts
@@ -0,0 +1,57 @@
+export type ColumnRef = {
+ readonly id?: string;
+ readonly slug: string;
+ readonly name: string;
+};
+
+const ALIASES: Readonly<Record<string, ReadonlyArray<string>>> = {
+ doing: ["inprogress"],
+ started: ["inprogress"],
+ wip: ["inprogress"],
+ progress: ["inprogress"],
+ review: ["inreview"],
+ reviewing: ["inreview"],
+ complete: ["done"],
+ completed: ["done"],
+ finished: ["done"],
+ closed: ["done"],
+};
+
+function lower(value: string): string {
+ return value.normalize("NFKC").trim().toLowerCase();
+}
+
+function compact(value: string): string {
+ return lower(value).replace(/[^\p{L}\p{N}]+/gu, "");
+}
+
+function only<C>(matches: ReadonlyArray<C>): C | undefined {
+ return matches.length === 1 ? matches[0] : undefined;
+}
+
+export function matchColumn<C extends ColumnRef>(
+ columns: ReadonlyArray<C>,
+ reference: string,
+): C | undefined {
+ const trimmed = reference.trim();
+ const wanted = lower(reference);
+ const key = compact(reference);
+ if (key === "") return undefined;
+ const compactOf = (column: C) => [compact(column.slug), compact(column.name)];
+ const exact =
+ columns.find((column) => column.id === trimmed) ??
+ columns.find((column) => lower(column.slug) === wanted) ??
+ only(columns.filter((column) => lower(column.name) === wanted));
+ if (exact) return exact;
+ const loose = only(
+ columns.filter((column) => compactOf(column).includes(key)),
+ );
+ if (loose) return loose;
+ const targets = ALIASES[key];
+ if (!targets) return undefined;
+ return only(
+ columns.filter((column) =>
+ compactOf(column).some((form) => targets.includes(form)),
+ ),
+ );
+}
diff --git a/packages/cli/src/tasks/match-member.ts b/packages/cli/src/tasks/match-member.ts
new file mode 100644
index 000000000..e75da616e
--- /dev/null
+++ b/packages/cli/src/tasks/match-member.ts
@@ -0,0 +1,13 @@
+import type { WorkspaceMember } from "../api/schemas.js";
+
+export function matchMember(
+ members: ReadonlyArray<WorkspaceMember>,
+ reference: string,
+): WorkspaceMember | undefined {
+ const wanted = reference.trim().toLowerCase();
+ return (
+ members.find((member) => member.id === reference.trim()) ??
+ members.find((member) => member.email.toLowerCase() === wanted) ??
+ members.find((member) => member.name.toLowerCase() === wanted)
+ );
+}
diff --git a/packages/cli/src/tasks/parse-date.test.ts b/packages/cli/src/tasks/parse-date.test.ts
new file mode 100644
index 000000000..51547f65d
--- /dev/null
+++ b/packages/cli/src/tasks/parse-date.test.ts
@@ -0,0 +1,83 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { parseDateChange, parseDateInput } from "./parse-date.js";
+
+const now = new Date(2026, 9, 7, 23, 45);
+const noon = (year: number, month: number, day: number) =>
+ new Date(year, month - 1, day, 12).toISOString();
+
+const success = <A, E>(result: Result.Result<A, E>) =>
+ Result.isSuccess(result) ? result.success : "failed";
+
+describe("parseDateInput", () => {
+ it("reads calendar days at local noon", () => {
+ expect(success(parseDateInput("2026-12-24", now))).toBe(noon(2026, 12, 24));
+ expect(new Date(success(parseDateInput("2026-12-24", now))).getDate()).toBe(
+ 24,
+ );
+ });
+
+ it("reads today, tomorrow and relative days", () => {
+ expect(success(parseDateInput("today", now))).toBe(noon(2026, 10, 7));
+ expect(success(parseDateInput(" Tomorrow ", now))).toBe(noon(2026, 10, 8));
+ expect(success(parseDateInput("+3d", now))).toBe(noon(2026, 10, 10));
+ expect(success(parseDateInput("+0d", now))).toBe(noon(2026, 10, 7));
+ });
+
+ it("rolls relative days over month and year ends", () => {
+ const newYearsEve = new Date(2026, 11, 31, 9);
+ expect(success(parseDateInput("tomorrow", newYearsEve))).toBe(
+ noon(2027, 1, 1),
+ );
+ expect(success(parseDateInput("+30d", newYearsEve))).toBe(
+ noon(2027, 1, 30),
+ );
+ });
+
+ it("rejects impossible days and other text with a hint", () => {
+ for (const input of [
+ "2026-02-30",
+ "2026-13-01",
+ "0050-01-01",
+ "next week",
+ "3d",
+ "",
+ "2026-1-5",
+ ]) {
+ const result = parseDateInput(input, now, "--start");
+ expect(Result.isFailure(result)).toBe(true);
+ if (Result.isFailure(result)) {
+ expect(result.failure._tag).toBe("InvalidArgument");
+ expect(result.failure.message).toBe(
+ `--start "${input}" is not a date.`,
+ );
+ expect(result.failure.hint).toBe(
+ "Use YYYY-MM-DD, today, tomorrow, or +3d.",
+ );
+ }
+ }
+ });
+
+ it("does not treat none as a date", () => {
+ expect(Result.isFailure(parseDateInput("none", now))).toBe(true);
+ });
+});
+
+describe("parseDateChange", () => {
+ it("clears with none", () => {
+ expect(success(parseDateChange("none", now))).toBeNull();
+ expect(success(parseDateChange(" NONE ", now))).toBeNull();
+ });
+
+ it("reads the same inputs as parseDateInput", () => {
+ expect(success(parseDateChange("2027-03-01", now))).toBe(noon(2027, 3, 1));
+ expect(success(parseDateChange("+1d", now))).toBe(noon(2026, 10, 8));
+ });
+
+ it("mentions none in the hint", () => {
+ const result = parseDateChange("soon", now, "--due");
+ expect(Result.isFailure(result) && result.failure.hint).toBe(
+ "Use YYYY-MM-DD, today, tomorrow, +3d, or none to clear it.",
+ );
+ });
+});
diff --git a/packages/cli/src/tasks/parse-date.ts b/packages/cli/src/tasks/parse-date.ts
new file mode 100644
index 000000000..e926d2e3d
--- /dev/null
+++ b/packages/cli/src/tasks/parse-date.ts
@@ -0,0 +1,76 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+
+const ISO_DAY = /^(\d{4})-(\d{2})-(\d{2})$/u;
+const RELATIVE_DAYS = /^\+(\d{1,4})d$/u;
+
+function localNoon(year: number, monthIndex: number, day: number): Date {
+ return new Date(year, monthIndex, day, 12, 0, 0, 0);
+}
+
+function invalid(
+ input: string,
+ flag: string,
+ allowNone: boolean,
+): InvalidArgument {
+ return new InvalidArgument({
+ message: `${flag} "${input}" is not a date.`,
+ hint: allowNone
+ ? "Use YYYY-MM-DD, today, tomorrow, +3d, or none to clear it."
+ : "Use YYYY-MM-DD, today, tomorrow, or +3d.",
+ });
+}
+
+function parseDay(value: string, now: Date): Date | null {
+ if (value === "today")
+ return localNoon(now.getFullYear(), now.getMonth(), now.getDate());
+ if (value === "tomorrow") {
+ return localNoon(now.getFullYear(), now.getMonth(), now.getDate() + 1);
+ }
+ const relative = RELATIVE_DAYS.exec(value);
+ if (relative) {
+ return localNoon(
+ now.getFullYear(),
+ now.getMonth(),
+ now.getDate() + Number(relative[1]),
+ );
+ }
+ const iso = ISO_DAY.exec(value);
+ if (!iso) return null;
+ const year = Number(iso[1]);
+ const month = Number(iso[2]);
+ const day = Number(iso[3]);
+ const date = localNoon(year, month - 1, day);
+ if (
+ date.getFullYear() !== year ||
+ date.getMonth() !== month - 1 ||
+ date.getDate() !== day
+ ) {
+ return null;
+ }
+ return date;
+}
+
+export function parseDateInput(
+ input: string,
+ now: Date,
+ flag = "--due",
+): Result.Result<string, InvalidArgument> {
+ const date = parseDay(input.trim().toLowerCase(), now);
+ return date
+ ? Result.succeed(date.toISOString())
+ : Result.fail(invalid(input, flag, false));
+}
+
+export function parseDateChange(
+ input: string,
+ now: Date,
+ flag = "--due",
+): Result.Result<string | null, InvalidArgument> {
+ const value = input.trim().toLowerCase();
+ if (value === "none") return Result.succeed(null);
+ const date = parseDay(value, now);
+ return date
+ ? Result.succeed(date.toISOString())
+ : Result.fail(invalid(input, flag, true));
+}
diff --git a/packages/cli/src/tasks/plain-description.test.ts b/packages/cli/src/tasks/plain-description.test.ts
new file mode 100644
index 000000000..7c92ff41c
--- /dev/null
+++ b/packages/cli/src/tasks/plain-description.test.ts
@@ -0,0 +1,241 @@
+import { describe, expect, it } from "vite-plus/test";
+import { stringWidth } from "../render/width.js";
+import { inlineText, plainDescription, wrapText } from "./plain-description.js";
+
+const plain = (source: string, width = 80, maxLines?: number) =>
+ plainDescription(source, { width, unicode: true, maxLines }).lines.map(
+ (line) => line.text,
+ );
+
+describe("inlineText", () => {
+ it("drops emphasis markers", () => {
+ expect(
+ inlineText(
+ "**bold** and *italic* and _under_ and ~~gone~~ and ++under++",
+ ),
+ ).toBe("bold and italic and under and gone and under");
+ });
+
+ it("keeps snake_case words and lone stars", () => {
+ expect(inlineText("set max_retry_count to 2 * 3 * 4")).toBe(
+ "set max_retry_count to 2 * 3 * 4",
+ );
+ });
+
+ it("shows code spans literally", () => {
+ expect(inlineText("run `pnpm **dev**` now")).toBe("run pnpm **dev** now");
+ });
+
+ it("unescapes markdown punctuation without formatting it", () => {
+ expect(inlineText("\\*not italic\\* and \\[x\\] and a\\_b")).toBe(
+ "*not italic* and [x] and a_b",
+ );
+ });
+
+ it("decodes entities", () => {
+ expect(inlineText("Option&lt;string&gt; &amp; &#x1F600; &#99999999;")).toBe(
+ "Option<string> & \u{1F600} &#99999999;",
+ );
+ });
+
+ it("writes links as text and url", () => {
+ expect(
+ inlineText(
+ "see [the docs](https://kaneo.app/docs_page_x) or <https://kaneo.app>",
+ ),
+ ).toBe("see the docs (https://kaneo.app/docs_page_x) or https://kaneo.app");
+ expect(inlineText("[https://kaneo.app](https://kaneo.app)")).toBe(
+ "https://kaneo.app",
+ );
+ expect(inlineText("[[email protected]](mailto:[email protected])")).toBe(
+ );
+ });
+
+ it("names images and attachments", () => {
+ expect(
+ inlineText("![diagram](https://cdn/x.png) ![](https://cdn/y.png)"),
+ ).toBe("[image: diagram] [image]");
+ expect(
+ inlineText('<img src="https://cdn/x.png" alt="wide" width="320" />'),
+ ).toBe("[image: wide]");
+ expect(
+ inlineText(
+ '<kaneo-attachment url="https://cdn/r.pdf" filename="report.pdf" mime-type="application/pdf" size="10" />',
+ ),
+ ).toBe("[attachment: report.pdf]");
+ });
+
+ it("reads Kaneo mentions, issue links and embeds", () => {
+ expect(
+ inlineText(
+ 'ping <kaneo-mention id="u1" label="Ada Lovelace"></kaneo-mention>',
+ ),
+ ).toBe("ping @Ada Lovelace");
+ expect(
+ inlineText(
+ '<kaneo-issue-link url="https://app/task/1" issue-key="KAN-3" task-id="1" />',
+ ),
+ ).toBe("KAN-3");
+ expect(
+ inlineText('<kaneo-embed url="https://youtu.be/x" mode="embed" />'),
+ ).toBe("https://youtu.be/x");
+ });
+
+ it("strips known html tags but keeps generic angle brackets", () => {
+ expect(inlineText("<strong>Hi</strong><br>there, Vec<String> stays")).toBe(
+ "Hi there, Vec<String> stays",
+ );
+ });
+});
+
+describe("wrapText", () => {
+ it("wraps on words with a hanging prefix", () => {
+ expect(wrapText("one two three four five", 12, "- ", " ")).toEqual([
+ "- one two",
+ " three four",
+ " five",
+ ]);
+ });
+
+ it("splits words longer than the line", () => {
+ expect(wrapText("https://example.com/a/very/long/path", 12)).toEqual([
+ "https://exam",
+ "ple.com/a/ve",
+ "ry/long/path",
+ ]);
+ });
+});
+
+describe("plainDescription", () => {
+ it("returns nothing for an empty description", () => {
+ expect(plain("")).toEqual([]);
+ expect(plain("\n\n \n")).toEqual([]);
+ });
+
+ it("renders headings, paragraphs and lists", () => {
+ const source = [
+ "## Steps",
+ "",
+ "Open the **board** and drag a card.",
+ "",
+ "- First",
+ " - Nested",
+ "1. Numbered",
+ "- [ ] Todo",
+ "- [x] Done",
+ ].join("\n");
+ const result = plainDescription(source, { width: 80, unicode: true });
+ expect(result.lines.map((line) => line.text)).toEqual([
+ "Steps",
+ "",
+ "Open the board and drag a card.",
+ "",
+ "• First",
+ " • Nested",
+ "1. Numbered",
+ "[ ] Todo",
+ "[x] Done",
+ ]);
+ expect(result.lines[0]?.kind).toBe("heading");
+ });
+
+ it("uses ascii bullets without unicode", () => {
+ expect(
+ plainDescription("- item", { width: 80, unicode: false }).lines.map(
+ (line) => line.text,
+ ),
+ ).toEqual(["- item"]);
+ });
+
+ it("keeps hard breaks as separate lines", () => {
+ expect(plain("first line \nsecond line\\\nthird")).toEqual([
+ "first line",
+ "second line",
+ "third",
+ ]);
+ });
+
+ it("collapses runs of blank lines", () => {
+ expect(plain("a\n\n\n\nb")).toEqual(["a", "", "b"]);
+ });
+
+ it("wraps prose to the width with hanging list indents", () => {
+ const lines = plain(
+ "- This list item is long enough that it needs to wrap onto a second line here.",
+ 40,
+ );
+ expect(lines).toEqual([
+ "• This list item is long enough that it",
+ " needs to wrap onto a second line here.",
+ ]);
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(40);
+ });
+
+ it("keeps code blocks verbatim and truncates instead of wrapping", () => {
+ const source = [
+ "```ts",
+ "const value = **not bold**;",
+ "const long = 'abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz';",
+ "```",
+ ].join("\n");
+ expect(plain(source, 40)).toEqual([
+ " const value = **not bold**;",
+ " const long = 'abcdefghijklmnopqrstuvw…",
+ ]);
+ });
+
+ it("aligns tables and never wraps them", () => {
+ const source = [
+ "| Name | Role |",
+ "| --- | --- |",
+ "| Ada Lovelace | Engineer |",
+ "| Grace \\| Hopper | Admiral of the fleet with a very long title |",
+ ].join("\n");
+ const lines = plain(source, 40);
+ expect(lines).toEqual([
+ "Name Role",
+ "────────────── ───────────────────────…",
+ "Ada Lovelace Engineer",
+ "Grace | Hopper Admiral of the fleet wi…",
+ ]);
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(40);
+ });
+
+ it("marks quotes and rules", () => {
+ const result = plainDescription("> quoted *text*\n\n---", {
+ width: 80,
+ unicode: true,
+ });
+ expect(result.lines.map((line) => [line.text, line.kind])).toEqual([
+ ["│ quoted text", "muted"],
+ ["", "text"],
+ ["────────────────────────", "muted"],
+ ]);
+ });
+
+ it("drops html comments", () => {
+ expect(plain("before <!-- hidden\nstill hidden --> after")).toEqual([
+ "before after",
+ ]);
+ });
+
+ it("stops at maxLines and reports the cut", () => {
+ const source = Array.from(
+ { length: 60 },
+ (_, index) => `line ${index + 1}`,
+ ).join("\n");
+ const result = plainDescription(source, {
+ width: 80,
+ unicode: true,
+ maxLines: 40,
+ });
+ expect(result.truncated).toBe(true);
+ expect(result.lines).toHaveLength(40);
+ expect(result.lines[39]?.text).toBe("line 40");
+ expect(
+ plainDescription("short", { width: 80, unicode: true, maxLines: 40 })
+ .truncated,
+ ).toBe(false);
+ });
+});
diff --git a/packages/cli/src/tasks/plain-description.ts b/packages/cli/src/tasks/plain-description.ts
new file mode 100644
index 000000000..e3d9bfcf4
--- /dev/null
+++ b/packages/cli/src/tasks/plain-description.ts
@@ -0,0 +1,356 @@
+import { stringWidth, truncate } from "../render/width.js";
+
+export type DescriptionLine = {
+ readonly text: string;
+ readonly kind: "text" | "heading" | "muted";
+};
+
+export type PlainDescription = {
+ readonly lines: ReadonlyArray<DescriptionLine>;
+ readonly truncated: boolean;
+};
+
+export type PlainDescriptionOptions = {
+ readonly width: number;
+ readonly unicode: boolean;
+ readonly maxLines?: number;
+};
+
+const FENCE = /^\s*(`{3,}|~{3,})/u;
+const HEADING = /^\s{0,3}(#{1,6})\s+(.*?)(?:\s+#+)?\s*$/u;
+const RULE = /^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/u;
+const QUOTE = /^\s{0,3}>\s?/u;
+const LIST_ITEM =
+ /^(\s*)([-*+]|\d{1,9}[.)]|[a-zA-Z][.)]|[ivxlcdmIVXLCDM]{1,8}[.)])\s+(.*)$/u;
+const TASK_BOX = /^\[([ xX])\]\s+(.*)$/u;
+const TABLE_DIVIDER = /^\s*\|?\s*:?-+:?\s*(?:\|\s*:?-+:?\s*)*\|?\s*$/u;
+const HARD_BREAK = /(?:\\| {2,})$/u;
+const HTML_TAGS =
+ "a|abbr|b|big|blockquote|br|center|code|del|details|div|em|font|h[1-6]|hr|i|ins|kbd|li|mark|ol|p|pre|s|small|span|strike|strong|sub|summary|sup|table|tbody|td|tfoot|th|thead|tr|u|ul";
+const KNOWN_TAG = new RegExp(`</?(?:${HTML_TAGS})(?:\\s[^<>]*)?/?>`, "giu");
+const OPEN = String.fromCharCode(0xe000);
+const CLOSE = String.fromCharCode(0xe001);
+const PLACEHOLDER = new RegExp(`${OPEN}(\\d+)${CLOSE}`, "gu");
+const ENTITIES: Readonly<Record<string, string>> = {
+ amp: "&",
+ lt: "<",
+ gt: ">",
+ quot: '"',
+ apos: "'",
+ nbsp: " ",
+};
+
+function attribute(tag: string, name: string): string {
+ const match = new RegExp(`\\s${name}="([^"]*)"`, "u").exec(tag);
+ return match?.[1] ?? "";
+}
+
+function codePoint(value: number, fallback: string): string {
+ return Number.isInteger(value) && value > 0 && value <= 0x10ffff
+ ? String.fromCodePoint(value)
+ : fallback;
+}
+
+function decodeEntities(text: string): string {
+ return text.replace(
+ /&(#x[0-9a-f]{1,6}|#\d{1,7}|[a-z]+);/giu,
+ (whole, name: string) => {
+ if (/^#x/iu.test(name))
+ return codePoint(Number.parseInt(name.slice(2), 16), whole);
+ if (name.startsWith("#")) return codePoint(Number(name.slice(1)), whole);
+ return ENTITIES[name.toLowerCase()] ?? whole;
+ },
+ );
+}
+
+export function inlineText(source: string): string {
+ const kept: string[] = [];
+ const keep = (value: string) => `${OPEN}${kept.push(value) - 1}${CLOSE}`;
+ const linkText = (label: string, url: string) => {
+ const target = keep(url.replace(/^mailto:/iu, ""));
+ return label === "" || label === url || `mailto:${label}` === url
+ ? target
+ : `${label} (${target})`;
+ };
+ const text = source
+ .replace(
+ /\\([\p{P}\p{S}])|(`+)(.+?)\2/gu,
+ (_, escaped?: string, _ticks?: string, code?: string) =>
+ keep(escaped ?? code?.trim() ?? ""),
+ )
+ .replace(/<kaneo-mention\b[^>]*>(?:<\/kaneo-mention>)?/giu, (tag) =>
+ keep(`@${decodeEntities(attribute(tag, "label"))}`),
+ )
+ .replace(/<kaneo-issue-link\b[^>]*>/giu, (tag) =>
+ keep(
+ decodeEntities(attribute(tag, "issue-key") || attribute(tag, "url")),
+ ),
+ )
+ .replace(/<kaneo-embed\b[^>]*>/giu, (tag) =>
+ keep(decodeEntities(attribute(tag, "url"))),
+ )
+ .replace(/<kaneo-attachment\b[^>]*>/giu, (tag) => {
+ const name = decodeEntities(attribute(tag, "filename"));
+ return keep(name ? `[attachment: ${name}]` : "[attachment]");
+ })
+ .replace(/<img\b[^>]*>/giu, (tag) => {
+ const alt = decodeEntities(attribute(tag, "alt"));
+ return keep(alt ? `[image: ${alt}]` : "[image]");
+ })
+ .replace(
+ /!\[([^\]]*)\]\((?:<[^>]*>|[^)\s]*)(?:\s+"[^"]*")?\)/gu,
+ (_, alt: string) => keep(alt ? `[image: ${alt}]` : "[image]"),
+ )
+ .replace(
+ /\[([^\]]*)\]\((?:<([^>]*)>|([^)\s]*))(?:\s+"[^"]*")?\)/gu,
+ (
+ _,
+ label: string,
+ bracketed: string | undefined,
+ bare: string | undefined,
+ ) => linkText(label, bracketed ?? bare ?? ""),
+ )
+ .replace(/<a\b[^>]*>([\s\S]*?)<\/a>/giu, (tag, label: string) =>
+ linkText(label, decodeEntities(attribute(tag, "href"))),
+ )
+ .replace(/<((?:https?|mailto):[^\s<>]+)>/giu, (_, url: string) =>
+ linkText("", url),
+ )
+ .replace(/<br\s*\/?>/giu, " ")
+ .replace(KNOWN_TAG, "")
+ .replace(/\*\*(?=\S)(.+?)(?<=\S)\*\*/gu, "$1")
+ .replace(/(^|[^\w])__(?=\S)(.+?)(?<=\S)__(?=[^\w]|$)/gu, "$1$2")
+ .replace(/~~(?=\S)(.+?)(?<=\S)~~/gu, "$1")
+ .replace(/\+\+(?=\S)(.+?)(?<=\S)\+\+/gu, "$1")
+ .replace(/\*(?=\S)(.+?)(?<=\S)\*/gu, "$1")
+ .replace(/(^|[^\w])_(?=\S)(.+?)(?<=\S)_(?=[^\w]|$)/gu, "$1$2");
+ return decodeEntities(text).replace(
+ PLACEHOLDER,
+ (_, index: string) => kept[Number(index)] ?? "",
+ );
+}
+
+function splitWord(word: string, width: number): string[] {
+ const parts: string[] = [];
+ let current = "";
+ for (const character of word) {
+ if (current !== "" && stringWidth(current + character) > width) {
+ parts.push(current);
+ current = "";
+ }
+ current += character;
+ }
+ if (current !== "") parts.push(current);
+ return parts;
+}
+
+export function wrapText(
+ text: string,
+ width: number,
+ firstPrefix = "",
+ restPrefix = firstPrefix,
+): string[] {
+ const words = text.split(/\s+/u).filter((word) => word !== "");
+ const lines: string[] = [];
+ let line = firstPrefix;
+ let empty = true;
+ for (const word of words) {
+ const prefix = empty ? line : `${line} `;
+ if (stringWidth(prefix + word) <= width) {
+ line = prefix + word;
+ empty = false;
+ continue;
+ }
+ if (!empty) {
+ lines.push(line);
+ line = restPrefix;
+ empty = true;
+ }
+ const room = Math.max(1, width - stringWidth(line));
+ const parts = stringWidth(word) > room ? splitWord(word, room) : [word];
+ for (const [index, part] of parts.entries()) {
+ if (index < parts.length - 1) {
+ lines.push(line + part);
+ line = restPrefix;
+ } else {
+ line += part;
+ }
+ }
+ empty = false;
+ }
+ if (!empty) lines.push(line);
+ return lines;
+}
+
+function tableCells(row: string): string[] {
+ const trimmed = row
+ .trim()
+ .replace(/^\|/u, "")
+ .replace(/(?<!\\)\|$/u, "");
+ return trimmed.split(/(?<!\\)\|/u).map((cell) => inlineText(cell.trim()));
+}
+
+function renderTable(
+ rows: ReadonlyArray<string>,
+ width: number,
+ ellipsis: string,
+ rule: string,
+) {
+ const [head = "", , ...body] = rows;
+ const cells = [tableCells(head), ...body.map(tableCells)];
+ const count = Math.max(...cells.map((row) => row.length));
+ const widths = Array.from({ length: count }, (_, column) =>
+ Math.max(1, ...cells.map((row) => stringWidth(row[column] ?? ""))),
+ );
+ const line = (row: ReadonlyArray<string>) =>
+ truncate(
+ widths
+ .map((columnWidth, column) => {
+ const cell = row[column] ?? "";
+ return (
+ cell + " ".repeat(Math.max(0, columnWidth - stringWidth(cell)))
+ );
+ })
+ .join(" ")
+ .trimEnd(),
+ width,
+ ellipsis,
+ );
+ const [header = [], ...rest] = cells;
+ return [
+ { text: line(header), kind: "heading" as const },
+ {
+ text: truncate(
+ widths.map((columnWidth) => rule.repeat(columnWidth)).join(" "),
+ width,
+ ellipsis,
+ ),
+ kind: "muted" as const,
+ },
+ ...rest.map((row) => ({ text: line(row), kind: "text" as const })),
+ ];
+}
+
+function leadingIndent(line: string): string {
+ const match = /^\s*/u.exec(line.replace(/\t/gu, " "));
+ return match?.[0] ?? "";
+}
+
+export function plainDescription(
+ source: string,
+ options: PlainDescriptionOptions,
+): PlainDescription {
+ const width = Math.max(20, options.width);
+ const maxLines = options.maxLines ?? Number.POSITIVE_INFINITY;
+ const bullet = options.unicode ? "•" : "-";
+ const bar = options.unicode ? "│" : "|";
+ const rule = options.unicode ? "─" : "-";
+ const ellipsis = options.unicode ? "…" : "...";
+ const lines: DescriptionLine[] = [];
+ const blank = () => {
+ if (lines.length > 0 && lines[lines.length - 1]?.text !== "") {
+ lines.push({ text: "", kind: "text" });
+ }
+ };
+ const push = (
+ texts: ReadonlyArray<string>,
+ kind: DescriptionLine["kind"],
+ ) => {
+ for (const text of texts) lines.push({ text, kind });
+ };
+
+ const sourceLines = source
+ .replace(/\r\n?/gu, "\n")
+ .replace(/<!--[\s\S]*?-->/gu, "")
+ .split("\n");
+ let fence: string | null = null;
+
+ for (
+ let index = 0;
+ index < sourceLines.length && lines.length <= maxLines;
+ index++
+ ) {
+ const raw = sourceLines[index] ?? "";
+ if (fence !== null) {
+ if (raw.trim().startsWith(fence)) {
+ fence = null;
+ continue;
+ }
+ push(
+ [truncate(` ${raw.replace(/\t/gu, " ")}`.trimEnd(), width, ellipsis)],
+ "text",
+ );
+ continue;
+ }
+ const fenceStart = FENCE.exec(raw);
+ if (fenceStart) {
+ fence = fenceStart[1] ?? "```";
+ continue;
+ }
+ const line = raw.replace(HARD_BREAK, "").trimEnd();
+ if (line.trim() === "") {
+ blank();
+ continue;
+ }
+ const heading = HEADING.exec(line);
+ if (heading) {
+ blank();
+ push(wrapText(inlineText(heading[2] ?? ""), width), "heading");
+ continue;
+ }
+ if (RULE.test(line)) {
+ push([rule.repeat(Math.min(width, 24))], "muted");
+ continue;
+ }
+ const next = sourceLines[index + 1] ?? "";
+ if (
+ line.trim().startsWith("|") &&
+ TABLE_DIVIDER.test(next) &&
+ next.includes("-")
+ ) {
+ const rows = [line, next];
+ index += 2;
+ while (
+ index < sourceLines.length &&
+ (sourceLines[index] ?? "").trim().startsWith("|")
+ ) {
+ rows.push(sourceLines[index] ?? "");
+ index += 1;
+ }
+ index -= 1;
+ lines.push(...renderTable(rows, width, ellipsis, rule));
+ continue;
+ }
+ if (QUOTE.test(line)) {
+ let content = line;
+ while (QUOTE.test(content)) content = content.replace(QUOTE, "");
+ push(wrapText(inlineText(content), width, `${bar} `), "muted");
+ continue;
+ }
+ const item = LIST_ITEM.exec(line);
+ if (item) {
+ const indent = leadingIndent(item[1] ?? "");
+ const body = item[3] ?? "";
+ const task = TASK_BOX.exec(body);
+ const marker = task
+ ? task[1] === " "
+ ? "[ ]"
+ : "[x]"
+ : /^[-*+]$/u.test(item[2] ?? "")
+ ? bullet
+ : (item[2] ?? "");
+ const text = inlineText(task ? (task[2] ?? "") : body);
+ const hanging = `${indent}${" ".repeat(stringWidth(marker) + 1)}`;
+ push(wrapText(text, width, `${indent}${marker} `, hanging), "text");
+ continue;
+ }
+ const indent = leadingIndent(line);
+ push(wrapText(inlineText(line.trim()), width, indent), "text");
+ }
+
+ while (lines.length > 0 && lines[lines.length - 1]?.text === "") lines.pop();
+ const truncated = lines.length > maxLines;
+ const shown = truncated ? lines.slice(0, maxLines) : lines;
+ while (shown.length > 0 && shown[shown.length - 1]?.text === "") shown.pop();
+ return { lines: shown, truncated };
+}
diff --git a/packages/cli/src/tasks/read-stdin.test.ts b/packages/cli/src/tasks/read-stdin.test.ts
new file mode 100644
index 000000000..e85636ad1
--- /dev/null
+++ b/packages/cli/src/tasks/read-stdin.test.ts
@@ -0,0 +1,21 @@
+import { Readable } from "node:stream";
+import { describe, expect, it } from "vite-plus/test";
+import { readStream } from "./read-stdin.js";
+
+describe("readStream", () => {
+ it("joins string chunks", async () => {
+ expect(await readStream(Readable.from(["Looks ", "good\n"]))).toBe(
+ "Looks good\n",
+ );
+ });
+
+ it("decodes UTF-8 split across byte chunks", async () => {
+ const bytes = new TextEncoder().encode("Café ✓");
+ const chunks = [bytes.slice(0, 4), bytes.slice(4, 6), bytes.slice(6)];
+ expect(await readStream(Readable.from(chunks))).toBe("Café ✓");
+ });
+
+ it("returns an empty string for an empty stream", async () => {
+ expect(await readStream(Readable.from([]))).toBe("");
+ });
+});
diff --git a/packages/cli/src/tasks/read-stdin.ts b/packages/cli/src/tasks/read-stdin.ts
new file mode 100644
index 000000000..b4bc3985c
--- /dev/null
+++ b/packages/cli/src/tasks/read-stdin.ts
@@ -0,0 +1,13 @@
+export async function readStream(
+ stream: AsyncIterable<string | Uint8Array>,
+): Promise<string> {
+ const decoder = new TextDecoder();
+ let text = "";
+ for await (const chunk of stream) {
+ text +=
+ typeof chunk === "string"
+ ? chunk
+ : decoder.decode(chunk, { stream: true });
+ }
+ return text + decoder.decode();
+}
diff --git a/packages/cli/src/tasks/render-assignment.test.ts b/packages/cli/src/tasks/render-assignment.test.ts
new file mode 100644
index 000000000..55ebeb0c7
--- /dev/null
+++ b/packages/cli/src/tasks/render-assignment.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { renderAssignment } from "./render-assignment.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+const url = "https://kaneo.test/task/1";
+
+describe("renderAssignment", () => {
+ it("names the new assignee", () => {
+ expect(
+ renderAssignment(ui, {
+ label: "KAN-12",
+ url,
+ assignee: { name: "Ada Lovelace" },
+ }),
+ ).toEqual(["", " ✓ KAN-12 assigned to Ada Lovelace", ""]);
+ });
+
+ it("says when the task was unassigned", () => {
+ expect(
+ renderAssignment(ui, { label: "KAN-12", url, assignee: null })[1],
+ ).toBe(" ✓ KAN-12 unassigned");
+ });
+});
diff --git a/packages/cli/src/tasks/render-assignment.ts b/packages/cli/src/tasks/render-assignment.ts
new file mode 100644
index 000000000..2d3ed67ca
--- /dev/null
+++ b/packages/cli/src/tasks/render-assignment.ts
@@ -0,0 +1,20 @@
+import { renderCell, text } from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+
+export type Assignment = {
+ readonly label: string;
+ readonly url: string;
+ readonly assignee: { readonly name: string } | null;
+};
+
+export function renderAssignment(ui: Ui, assignment: Assignment): string[] {
+ const { theme, glyphs } = ui;
+ const id = renderCell(
+ [text(assignment.label, theme.strong, assignment.url)],
+ ui,
+ );
+ const outcome = assignment.assignee
+ ? `assigned to ${theme.strong(assignment.assignee.name)}`
+ : "unassigned";
+ return ["", ` ${theme.success(glyphs.tick)} ${id} ${outcome}`, ""];
+}
diff --git a/packages/cli/src/tasks/render-comment-added.test.ts b/packages/cli/src/tasks/render-comment-added.test.ts
new file mode 100644
index 000000000..5d14f6f35
--- /dev/null
+++ b/packages/cli/src/tasks/render-comment-added.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import { renderCommentAdded } from "./render-comment-added.js";
+
+const ui = (columns: number) =>
+ makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns,
+ });
+const url = "https://kaneo.test/task/1";
+
+describe("renderCommentAdded", () => {
+ it("shows the first line of the comment", () => {
+ expect(
+ renderCommentAdded(ui(80), {
+ label: "KAN-12",
+ url,
+ content: "Looks good",
+ }),
+ ).toEqual(["", " ✓ Commented on KAN-12 · Looks good", ""]);
+ });
+
+ it("marks comments with more lines", () => {
+ expect(
+ renderCommentAdded(ui(80), {
+ label: "KAN-12",
+ url,
+ content: "Looks good\n\nShip it",
+ })[1],
+ ).toBe(" ✓ Commented on KAN-12 · Looks good …");
+ });
+
+ it("fits a long first line to the terminal width", () => {
+ const [, line = ""] = renderCommentAdded(ui(40), {
+ label: "KAN-12",
+ url,
+ content: "word ".repeat(30),
+ });
+ expect(stringWidth(line)).toBeLessThanOrEqual(40);
+ expect(line.endsWith("…")).toBe(true);
+ });
+
+ it("leaves out the preview when the content is blank", () => {
+ expect(
+ renderCommentAdded(ui(80), { label: "KAN-12", url, content: "" })[1],
+ ).toBe(" ✓ Commented on KAN-12");
+ });
+});
diff --git a/packages/cli/src/tasks/render-comment-added.ts b/packages/cli/src/tasks/render-comment-added.ts
new file mode 100644
index 000000000..30db08311
--- /dev/null
+++ b/packages/cli/src/tasks/render-comment-added.ts
@@ -0,0 +1,25 @@
+import { renderCell, text } from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+import { stringWidth, truncate } from "../render/width.js";
+import { firstLine } from "./comment-text.js";
+
+export type CommentAdded = {
+ readonly label: string;
+ readonly url: string;
+ readonly content: string;
+};
+
+export function renderCommentAdded(ui: Ui, comment: CommentAdded): string[] {
+ const { theme, glyphs } = ui;
+ const id = renderCell([text(comment.label, theme.strong, comment.url)], ui);
+ const head = ` ${theme.success(glyphs.tick)} Commented on ${id}`;
+ const preview = firstLine(comment.content);
+ if (preview.line === "") return ["", head, ""];
+ const room = Math.max(ui.caps.columns - stringWidth(head) - 3, 8);
+ const shown = truncate(
+ preview.more ? `${preview.line} ${glyphs.ellipsis}` : preview.line,
+ room,
+ glyphs.ellipsis,
+ );
+ return ["", `${head} ${theme.muted(`${glyphs.separator} ${shown}`)}`, ""];
+}
diff --git a/packages/cli/src/tasks/render-open-task.test.ts b/packages/cli/src/tasks/render-open-task.test.ts
new file mode 100644
index 000000000..2ffd99ffa
--- /dev/null
+++ b/packages/cli/src/tasks/render-open-task.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { renderOpenTask } from "./render-open-task.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+const url = "https://kaneo.test/dashboard/workspace/w/project/p/task/t";
+
+describe("renderOpenTask", () => {
+ it("confirms the opened url", () => {
+ expect(renderOpenTask(ui, { url, opened: true })).toEqual([
+ "",
+ ` → Opened ${url}`,
+ "",
+ ]);
+ });
+
+ it("prints the url to open by hand", () => {
+ expect(renderOpenTask(ui, { url, opened: false })).toEqual([
+ "",
+ ` → Open ${url}`,
+ "",
+ ]);
+ });
+
+ it("falls back to ascii", () => {
+ const ascii = makeUi({
+ color: 0,
+ unicode: false,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+ });
+ expect(renderOpenTask(ascii, { url, opened: true })[1]).toBe(
+ ` -> Opened ${url}`,
+ );
+ });
+});
diff --git a/packages/cli/src/tasks/render-open-task.ts b/packages/cli/src/tasks/render-open-task.ts
new file mode 100644
index 000000000..b91bae073
--- /dev/null
+++ b/packages/cli/src/tasks/render-open-task.ts
@@ -0,0 +1,16 @@
+import type { Ui } from "../render/ui.js";
+
+export type OpenTaskResult = {
+ readonly url: string;
+ readonly opened: boolean;
+};
+
+export function renderOpenTask(ui: Ui, result: OpenTaskResult): string[] {
+ const { theme, glyphs } = ui;
+ const verb = result.opened ? "Opened" : "Open";
+ return [
+ "",
+ ` ${theme.muted(glyphs.arrow)} ${verb} ${theme.info(result.url)}`,
+ "",
+ ];
+}
diff --git a/packages/cli/src/tasks/render-status-change.test.ts b/packages/cli/src/tasks/render-status-change.test.ts
new file mode 100644
index 000000000..7dd2bcc89
--- /dev/null
+++ b/packages/cli/src/tasks/render-status-change.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { renderStatusChange } from "./render-status-change.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+const todo = { slug: "to-do", name: "To Do", isFinal: false };
+const progress = { slug: "in-progress", name: "In Progress", isFinal: false };
+const url = "https://kaneo.test/task/1";
+
+describe("renderStatusChange", () => {
+ it("shows the move between columns", () => {
+ expect(
+ renderStatusChange(ui, {
+ label: "KAN-12",
+ url,
+ from: todo,
+ to: progress,
+ }),
+ ).toEqual(["", " ✓ KAN-12 · ● To Do → ● In Progress", ""]);
+ });
+
+ it("says when the task is already in the column", () => {
+ expect(
+ renderStatusChange(ui, {
+ label: "KAN-12",
+ url,
+ from: progress,
+ to: progress,
+ })[1],
+ ).toBe(" ✓ KAN-12 · already in ● In Progress");
+ });
+
+ it("links the ticket id when the terminal supports it", () => {
+ const linked = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: true,
+ animate: false,
+ columns: 80,
+ });
+ const [, line] = renderStatusChange(linked, {
+ label: "KAN-12",
+ url,
+ from: todo,
+ to: progress,
+ });
+ expect(line).toContain(`\u001b]8;;${url}\u001b\\KAN-12\u001b]8;;\u001b\\`);
+ });
+});
diff --git a/packages/cli/src/tasks/render-status-change.ts b/packages/cli/src/tasks/render-status-change.ts
new file mode 100644
index 000000000..dcb653cd9
--- /dev/null
+++ b/packages/cli/src/tasks/render-status-change.ts
@@ -0,0 +1,35 @@
+import { renderCell, text } from "../render/cell.js";
+import { statusDot } from "../render/task-format.js";
+import type { Ui } from "../render/ui.js";
+
+export type StatusRef = {
+ readonly slug: string;
+ readonly name: string;
+ readonly isFinal: boolean;
+};
+
+export type StatusChange = {
+ readonly label: string;
+ readonly url: string;
+ readonly from: StatusRef;
+ readonly to: StatusRef;
+};
+
+export function renderStatusChange(ui: Ui, change: StatusChange): string[] {
+ const { theme, glyphs } = ui;
+ const status = (ref: StatusRef) =>
+ renderCell(
+ [statusDot(ui, ref.slug, ref.isFinal), text(` ${ref.name}`)],
+ ui,
+ );
+ const id = renderCell([text(change.label, theme.strong, change.url)], ui);
+ const movement =
+ change.from.slug === change.to.slug
+ ? `${theme.muted("already in")} ${status(change.to)}`
+ : `${status(change.from)} ${theme.muted(glyphs.arrow)} ${status(change.to)}`;
+ return [
+ "",
+ ` ${theme.success(glyphs.tick)} ${id} ${theme.muted(glyphs.separator)} ${movement}`,
+ "",
+ ];
+}
diff --git a/packages/cli/src/tasks/render-task-change.test.ts b/packages/cli/src/tasks/render-task-change.test.ts
new file mode 100644
index 000000000..6b5e40293
--- /dev/null
+++ b/packages/cli/src/tasks/render-task-change.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { renderTaskChange } from "./render-task-change.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+describe("renderTaskChange", () => {
+ it("prints the created task on one line", () => {
+ expect(
+ renderTaskChange(ui, {
+ verb: "Created",
+ reference: "KAN-124",
+ url: "https://kaneo.test/task/1",
+ detail: "Fix login redirect",
+ }),
+ ).toEqual(["", " ✓ Created KAN-124 · Fix login redirect", ""]);
+ });
+
+ it("lists the updated fields", () => {
+ expect(
+ renderTaskChange(ui, {
+ verb: "Updated",
+ reference: "KAN-12",
+ url: "https://kaneo.test/task/1",
+ detail: "title, priority",
+ }),
+ ).toEqual(["", " ✓ Updated KAN-12 · title, priority", ""]);
+ });
+
+ it("links the ticket id when the terminal supports it", () => {
+ const linked = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: true,
+ animate: false,
+ columns: 80,
+ });
+ const [, line] = renderTaskChange(linked, {
+ verb: "Created",
+ reference: "KAN-1",
+ url: "https://kaneo.test/task/1",
+ detail: "Title",
+ });
+ expect(line).toContain(
+ "\u001b]8;;https://kaneo.test/task/1\u001b\\KAN-1\u001b]8;;\u001b\\",
+ );
+ });
+});
diff --git a/packages/cli/src/tasks/render-task-change.ts b/packages/cli/src/tasks/render-task-change.ts
new file mode 100644
index 000000000..bdd74d6a3
--- /dev/null
+++ b/packages/cli/src/tasks/render-task-change.ts
@@ -0,0 +1,22 @@
+import { renderCell, text } from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+
+export type TaskChange = {
+ readonly verb: "Created" | "Updated";
+ readonly reference: string;
+ readonly url: string;
+ readonly detail: string;
+};
+
+export function renderTaskChange(ui: Ui, change: TaskChange): string[] {
+ const { theme, glyphs } = ui;
+ const reference = renderCell(
+ [text(change.reference, theme.strong, change.url)],
+ ui,
+ );
+ return [
+ "",
+ ` ${theme.success(glyphs.tick)} ${change.verb} ${reference} ${theme.muted(glyphs.separator)} ${change.detail}`,
+ "",
+ ];
+}
diff --git a/packages/cli/src/tasks/render-task-deleted.test.ts b/packages/cli/src/tasks/render-task-deleted.test.ts
new file mode 100644
index 000000000..5ded98427
--- /dev/null
+++ b/packages/cli/src/tasks/render-task-deleted.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { renderTaskDeleted } from "./render-task-deleted.js";
+
+describe("renderTaskDeleted", () => {
+ it("prints a one-line result", () => {
+ const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+ });
+ expect(
+ renderTaskDeleted(ui, { label: "KAN-12", title: "Fix login" }),
+ ).toEqual(["", " ✓ Deleted KAN-12 · Fix login", ""]);
+ });
+});
diff --git a/packages/cli/src/tasks/render-task-deleted.ts b/packages/cli/src/tasks/render-task-deleted.ts
new file mode 100644
index 000000000..cf4cae01b
--- /dev/null
+++ b/packages/cli/src/tasks/render-task-deleted.ts
@@ -0,0 +1,14 @@
+import { renderCell, text } from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+
+export function renderTaskDeleted(
+ ui: Ui,
+ deleted: { readonly label: string; readonly title: string },
+): string[] {
+ const { theme, glyphs } = ui;
+ return [
+ "",
+ ` ${theme.success(glyphs.tick)} Deleted ${renderCell([text(deleted.label, theme.strong)], ui)} ${theme.muted(glyphs.separator)} ${deleted.title}`,
+ "",
+ ];
+}
diff --git a/packages/cli/src/tasks/render-task-detail.test.ts b/packages/cli/src/tasks/render-task-detail.test.ts
new file mode 100644
index 000000000..db692988e
--- /dev/null
+++ b/packages/cli/src/tasks/render-task-detail.test.ts
@@ -0,0 +1,213 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import type { TaskViewJson } from "../task-view/task-view-json.js";
+import { renderTaskDetail } from "./render-task-detail.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+const now = new Date(2026, 9, 7, 10);
+
+const task: TaskViewJson = {
+ id: "task-1",
+ ticketId: "KAN-12",
+ number: 12,
+ title: "Fix login redirect after device approval",
+ description:
+ "## Steps\n\n1. Sign in with **device** flow\n2. See [the bug](https://kaneo.test/b)",
+ status: "in-progress",
+ statusName: "In Progress",
+ priority: "urgent",
+ assignee: { id: "user-1", name: "Ada Lovelace" },
+ dueDate: new Date(2026, 9, 6, 12).toISOString(),
+ startDate: new Date(2026, 9, 1, 12).toISOString(),
+ createdAt: new Date(2026, 8, 30, 9).toISOString(),
+ projectId: "project-1",
+ projectKey: "KAN",
+ projectName: "Kaneo Web",
+ workspaceId: "workspace-1",
+ url: "https://kaneo.test/dashboard/workspace/workspace-1/project/project-1/task/task-1",
+ labels: [],
+ parent: null,
+ subtasks: [],
+ relations: [],
+ links: [],
+ fields: [],
+ time: { totalSeconds: 0, running: [] },
+ comments: [],
+};
+
+describe("renderTaskDetail", () => {
+ it("renders the card and the description at 80 columns", () => {
+ expect(renderTaskDetail(ui, { task, statusFinal: false, now })).toEqual([
+ "",
+ " KAN-12 Fix login redirect after device approval",
+ "",
+ " Status ● In Progress",
+ " Priority ▲ Urgent",
+ " Assignee Ada Lovelace",
+ " Labels None",
+ " Due ◷ Yesterday",
+ " Start Oct 1",
+ " Created Sep 30",
+ " Project Kaneo Web · KAN",
+ "",
+ " Steps",
+ "",
+ " 1. Sign in with device flow",
+ " 2. See the bug (https://kaneo.test/b)",
+ "",
+ ]);
+ });
+
+ it("shows empty fields as muted placeholders", () => {
+ const lines = renderTaskDetail(ui, {
+ task: {
+ ...task,
+ ticketId: null,
+ priority: "no-priority",
+ assignee: null,
+ dueDate: null,
+ startDate: null,
+ description: "",
+ },
+ statusFinal: false,
+ now,
+ });
+ expect(lines).toEqual([
+ "",
+ " task-1 Fix login redirect after device approval",
+ "",
+ " Status ● In Progress",
+ " Priority No priority",
+ " Assignee Unassigned",
+ " Labels None",
+ " Due None",
+ " Start None",
+ " Created Sep 30",
+ " Project Kaneo Web · KAN",
+ "",
+ " No description.",
+ "",
+ ]);
+ });
+
+ it("wraps long prose to the terminal and cuts long descriptions", () => {
+ const paragraph = "word ".repeat(40).trim();
+ const description = Array.from(
+ { length: 50 },
+ (_, index) => `${index + 1}. ${paragraph}`,
+ ).join("\n");
+ const lines = renderTaskDetail(ui, {
+ task: { ...task, description },
+ statusFinal: false,
+ now,
+ });
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(80);
+ const body = lines.slice(12);
+ expect(body.filter((line) => line !== "").length).toBe(41);
+ expect(lines.at(-2)).toBe(
+ " Run kaneo task open KAN-12 to read the rest.",
+ );
+ const full = renderTaskDetail(ui, {
+ task: { ...task, description },
+ statusFinal: false,
+ now,
+ full: true,
+ });
+ expect(full).toContain(` 50. ${"word ".repeat(14).trim()}`);
+ expect(full.some((line) => line.includes("to read the rest"))).toBe(false);
+ });
+});
+
+describe("renderTaskDetail rows", () => {
+ const rows = (overrides: Partial<TaskViewJson>, columns = 80) => {
+ const lines = renderTaskDetail(
+ makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns,
+ }),
+ { task: { ...task, ...overrides }, statusFinal: false, now },
+ );
+ return lines.slice(3, lines.indexOf("", 3));
+ };
+
+ it("shows labels as chips, tracked time with the running timer, and the parent", () => {
+ expect(
+ rows({
+ labels: [
+ { name: "bug", color: "red" },
+ { name: "auth", color: "purple" },
+ ],
+ time: {
+ totalSeconds: 9000,
+ running: [
+ {
+ user: { id: "user-1", name: "Ada Lovelace" },
+ startedAt: now.toISOString(),
+ },
+ ],
+ },
+ parent: {
+ id: "task-4",
+ ticketId: "KAN-4",
+ title: "Auth overhaul",
+ status: "to-do",
+ completed: false,
+ url: "https://kaneo.test/task-4",
+ },
+ }),
+ ).toEqual([
+ " Status ● In Progress",
+ " Priority ▲ Urgent",
+ " Assignee Ada Lovelace",
+ " Labels ● bug ● auth",
+ " Due ◷ Yesterday",
+ " Start Oct 1",
+ " Created Sep 30",
+ " Time 2h 30m · ● Timer running (Ada Lovelace)",
+ " Project Kaneo Web · KAN",
+ " Parent ● KAN-4 Auth overhaul",
+ ]);
+ });
+
+ it("hides the time row without tracked time and marks sections that failed", () => {
+ const lines = rows({ labels: null, time: null });
+ expect(lines).toContain(" Labels could not load");
+ expect(lines).toContain(" Time could not load");
+ expect(rows({}).some((line) => line.includes("Time"))).toBe(false);
+ });
+
+ it("cuts long label and parent rows to the terminal width", () => {
+ const lines = rows(
+ {
+ labels: Array.from({ length: 12 }, (_, index) => ({
+ name: `label-${index}`,
+ color: "gray",
+ })),
+ parent: {
+ id: "task-4",
+ ticketId: "KAN-4",
+ title: "A parent task with a title that is much longer than the row",
+ status: "to-do",
+ completed: false,
+ url: "https://kaneo.test/task-4",
+ },
+ },
+ 60,
+ );
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(60);
+ expect(lines.find((line) => line.includes("Labels"))).toBe(
+ " Labels ● label-0 ● label-1 ● label-2 +9",
+ );
+ expect(lines.find((line) => line.includes("Parent"))).toMatch(/…$/u);
+ });
+});
diff --git a/packages/cli/src/tasks/render-task-detail.ts b/packages/cli/src/tasks/render-task-detail.ts
new file mode 100644
index 000000000..2d3e3353e
--- /dev/null
+++ b/packages/cli/src/tasks/render-task-detail.ts
@@ -0,0 +1,133 @@
+import { type Cell, fitCell, renderCell, text } from "../render/cell.js";
+import {
+ dueSegments,
+ formatDue,
+ prioritySegments,
+ statusDot,
+} from "../render/task-format.js";
+import type { Ui } from "../render/ui.js";
+import { labelChips } from "../task-view/label-chips.js";
+import type { TaskViewJson } from "../task-view/task-view-json.js";
+import { hasTrackedTime, timeValue } from "../task-view/time-value.js";
+import { type DescriptionLine, plainDescription } from "./plain-description.js";
+
+export type TaskDetailView = {
+ readonly task: TaskViewJson;
+ readonly statusFinal: boolean;
+ readonly now: Date;
+ readonly full?: boolean;
+};
+
+const DESCRIPTION_LINES = 40;
+const INDENT = " ";
+const LABEL_WIDTH = 10;
+
+function formatDay(value: string | null, now: Date): string | null {
+ if (!value) return null;
+ const date = new Date(value);
+ return Number.isNaN(date.getTime()) ? null : formatDue(date, now);
+}
+
+export function renderTaskDetail(ui: Ui, view: TaskDetailView): string[] {
+ const { theme, glyphs } = ui;
+ const { task, now } = view;
+ const reference = task.ticketId ?? task.id;
+ const none = (label: string) => theme.muted(label);
+ const unavailable = none("could not load");
+ const valueWidth = ui.caps.columns - INDENT.length - LABEL_WIDTH - 1;
+ const fit = (cell: Cell) =>
+ renderCell(fitCell(cell, valueWidth, glyphs.ellipsis), ui);
+ const priority = prioritySegments(ui, task.priority);
+ const due = dueSegments(ui, task.dueDate, view.statusFinal, now);
+ const labels =
+ task.labels === null
+ ? unavailable
+ : task.labels.length > 0
+ ? renderCell(labelChips(ui, task.labels, valueWidth), ui)
+ : none("None");
+ const time =
+ task.time === null
+ ? unavailable
+ : hasTrackedTime(task.time)
+ ? fit(timeValue(ui, task.time))
+ : null;
+ const parent = task.parent
+ ? fit([
+ statusDot(ui, task.parent.status, task.parent.completed),
+ text(" "),
+ text(
+ task.parent.ticketId ?? task.parent.id.slice(0, 8),
+ theme.muted,
+ task.parent.url,
+ ),
+ text(` ${task.parent.title}`),
+ ])
+ : null;
+ const rows: ReadonlyArray<readonly [string, string | null]> = [
+ [
+ "Status",
+ `${renderCell([statusDot(ui, task.status, view.statusFinal)], ui)} ${task.statusName}`,
+ ],
+ [
+ "Priority",
+ priority.length > 0 ? renderCell(priority, ui) : none("No priority"),
+ ],
+ [
+ "Assignee",
+ task.assignee
+ ? (task.assignee.name ?? task.assignee.id)
+ : none("Unassigned"),
+ ],
+ ["Labels", labels],
+ ["Due", due.length > 0 ? renderCell(due, ui) : none("None")],
+ ["Start", formatDay(task.startDate, now) ?? none("None")],
+ ["Created", formatDay(task.createdAt, now) ?? none("Unknown")],
+ ["Time", time],
+ [
+ "Project",
+ `${task.projectName} ${theme.muted(`${glyphs.separator} ${task.projectKey}`)}`,
+ ],
+ ["Parent", parent],
+ ];
+
+ const lines = [
+ "",
+ ` ${renderCell([text(task.ticketId ?? task.id.slice(0, 8), theme.muted, task.url)], ui)} ${theme.strong(task.title)}`,
+ "",
+ ...rows.flatMap(([label, value]) =>
+ value === null
+ ? []
+ : [`${INDENT}${theme.muted(label.padEnd(LABEL_WIDTH))} ${value}`],
+ ),
+ "",
+ ];
+
+ const description = plainDescription(task.description ?? "", {
+ width: ui.caps.columns - INDENT.length,
+ unicode: ui.caps.unicode,
+ maxLines: view.full ? Number.POSITIVE_INFINITY : DESCRIPTION_LINES,
+ });
+ if (description.lines.length === 0) {
+ lines.push(`${INDENT}${theme.muted("No description.")}`, "");
+ return lines;
+ }
+ const style = (line: DescriptionLine) =>
+ line.kind === "heading"
+ ? theme.strong(line.text)
+ : line.kind === "muted"
+ ? theme.muted(line.text)
+ : line.text;
+ lines.push(
+ ...description.lines.map((line) =>
+ line.text ? `${INDENT}${style(line)}` : "",
+ ),
+ );
+ if (description.truncated) {
+ lines.push(
+ "",
+ `${INDENT}${theme.muted("Run")} ${theme.strong(`kaneo task open ${reference}`)} ${theme.muted("to read the rest.")}`,
+ );
+ }
+ lines.push("");
+ return lines;
+}
diff --git a/packages/cli/src/tasks/render-task-duplicated.test.ts b/packages/cli/src/tasks/render-task-duplicated.test.ts
new file mode 100644
index 000000000..c84e61c20
--- /dev/null
+++ b/packages/cli/src/tasks/render-task-duplicated.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import { renderTaskDuplicated } from "./render-task-duplicated.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+describe("renderTaskDuplicated", () => {
+ it("shows the source and the copy", () => {
+ expect(
+ renderTaskDuplicated(ui, {
+ sourceLabel: "KAN-3",
+ label: "KAN-19",
+ url: "https://kaneo.test/t",
+ title: "Fix login redirect",
+ }),
+ ).toEqual(["", " ✓ Duplicated KAN-3 → KAN-19 · Fix login redirect", ""]);
+ });
+
+ it("fits a long title into 80 columns", () => {
+ const [, line] = renderTaskDuplicated(ui, {
+ sourceLabel: "KAN-3",
+ label: "MOB-120",
+ url: "https://kaneo.test/t",
+ title: "A very long task title ".repeat(6),
+ });
+ expect(stringWidth(line ?? "")).toBeLessThanOrEqual(80);
+ });
+});
diff --git a/packages/cli/src/tasks/render-task-duplicated.ts b/packages/cli/src/tasks/render-task-duplicated.ts
new file mode 100644
index 000000000..a6aa4d65f
--- /dev/null
+++ b/packages/cli/src/tasks/render-task-duplicated.ts
@@ -0,0 +1,22 @@
+import { renderCell, text } from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+import { stringWidth, truncate } from "../render/width.js";
+
+export type TaskDuplicated = {
+ readonly sourceLabel: string;
+ readonly label: string;
+ readonly url: string;
+ readonly title: string;
+};
+
+export function renderTaskDuplicated(ui: Ui, copy: TaskDuplicated): string[] {
+ const { theme, glyphs } = ui;
+ const reference = renderCell([text(copy.label, theme.strong, copy.url)], ui);
+ const head = ` ${theme.success(glyphs.tick)} Duplicated ${theme.muted(copy.sourceLabel)} ${theme.muted(glyphs.arrow)} ${reference} ${theme.muted(glyphs.separator)} `;
+ const title = truncate(
+ copy.title,
+ Math.max(ui.caps.columns - stringWidth(head), 8),
+ glyphs.ellipsis,
+ );
+ return ["", `${head}${title}`, ""];
+}
diff --git a/packages/cli/src/tasks/render-task-list.ts b/packages/cli/src/tasks/render-task-list.ts
new file mode 100644
index 000000000..06bcd93c2
--- /dev/null
+++ b/packages/cli/src/tasks/render-task-list.ts
@@ -0,0 +1,113 @@
+import { type Cell, renderCell, text } from "../render/cell.js";
+import { projectUrl } from "../render/links.js";
+import { renderTable } from "../render/table.js";
+import {
+ dueSegments,
+ prioritySegments,
+ statusDot,
+} from "../render/task-format.js";
+import type { Ui } from "../render/ui.js";
+import type { BoardColumnSummary } from "./load-board.js";
+import type { TaskJson } from "./task-json.js";
+
+export type TaskListView = {
+ readonly projectName: string;
+ readonly projectSlug: string;
+ readonly projectId: string;
+ readonly workspaceId: string;
+ readonly webUrl: string;
+ readonly columns: ReadonlyArray<BoardColumnSummary>;
+ readonly tasks: ReadonlyArray<TaskJson>;
+ readonly total: number;
+ readonly now: Date;
+};
+
+export function renderTaskList(ui: Ui, view: TaskListView): string[] {
+ const { theme, glyphs } = ui;
+ const link = projectUrl(view.webUrl, {
+ workspaceId: view.workspaceId,
+ id: view.projectId,
+ });
+ const header = ` ${renderCell([text(view.projectName, theme.strong, link)], ui)} ${theme.muted(`${glyphs.separator} ${view.projectSlug.toUpperCase()}`)}`;
+ if (view.tasks.length === 0) {
+ return ["", header, "", ` ${theme.muted("No tasks match.")}`, ""];
+ }
+
+ const groups = view.columns
+ .map((column) => ({
+ column,
+ tasks: view.tasks.filter((task) => task.status === column.slug),
+ }))
+ .filter((group) => group.tasks.length > 0);
+ const known = new Set(view.columns.map((column) => column.slug));
+ const orphans = view.tasks.filter((task) => !known.has(task.status));
+ if (orphans.length > 0) {
+ groups.push({
+ column: { slug: "other", name: "Other", isFinal: false },
+ tasks: orphans,
+ });
+ }
+
+ const ordered = groups.flatMap((group) => group.tasks);
+ const finalSlugs = new Set(
+ view.columns
+ .filter((column) => column.isFinal)
+ .map((column) => column.slug),
+ );
+ const lines = renderTable(
+ ui,
+ ordered,
+ [
+ {
+ header: "ID",
+ cell: (task): Cell => [
+ text(task.ticketId ?? task.id.slice(0, 8), theme.muted, task.url),
+ ],
+ },
+ {
+ header: "Title",
+ flex: true,
+ minWidth: 16,
+ cell: (task): Cell => [text(task.title, undefined, task.url)],
+ },
+ {
+ header: "Priority",
+ optional: true,
+ cell: (task): Cell => prioritySegments(ui, task.priority),
+ },
+ {
+ header: "Assignee",
+ optional: true,
+ minWidth: 10,
+ cell: (task): Cell =>
+ task.assignee?.name ? [text(task.assignee.name)] : [],
+ },
+ {
+ header: "Due",
+ optional: true,
+ cell: (task): Cell =>
+ dueSegments(ui, task.dueDate, finalSlugs.has(task.status), view.now),
+ },
+ ],
+ { width: ui.caps.columns, indent: 4, gap: 2 },
+ );
+
+ const output = ["", header, ""];
+ let offset = 0;
+ for (const group of groups) {
+ const dot = statusDot(ui, group.column.slug, group.column.isFinal);
+ output.push(
+ ` ${dot.style ? dot.style(dot.text) : dot.text} ${theme.strong(group.column.name)} ${theme.muted(String(group.tasks.length))}`,
+ );
+ output.push(...lines.slice(offset, offset + group.tasks.length));
+ output.push("");
+ offset += group.tasks.length;
+ }
+ if (view.total > view.tasks.length) {
+ output.push(
+ ` ${theme.muted(`Showing ${view.tasks.length} of ${view.total} tasks. Pass --limit to see more.`)}`,
+ "",
+ );
+ }
+ return output;
+}
diff --git a/packages/cli/src/tasks/render-task-move.test.ts b/packages/cli/src/tasks/render-task-move.test.ts
new file mode 100644
index 000000000..b641d5e81
--- /dev/null
+++ b/packages/cli/src/tasks/render-task-move.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import { renderTaskMove } from "./render-task-move.js";
+
+const ui = (columns: number) =>
+ makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns,
+ });
+
+const move = {
+ fromLabel: "KAN-12",
+ toLabel: "MOB-4",
+ title: "Fix login redirect",
+ url: "https://kaneo.test/task/1",
+};
+
+describe("renderTaskMove", () => {
+ it("shows the old and new ticket ids with the title", () => {
+ expect(renderTaskMove(ui(80), move)).toEqual([
+ "",
+ " ✓ Moved KAN-12 → MOB-4 · Fix login redirect",
+ "",
+ ]);
+ });
+
+ it("truncates a long title to the terminal width", () => {
+ const [, line = ""] = renderTaskMove(ui(40), {
+ ...move,
+ title: "A".repeat(60),
+ });
+ expect(stringWidth(line)).toBe(40);
+ expect(line.endsWith("…")).toBe(true);
+ });
+});
diff --git a/packages/cli/src/tasks/render-task-move.ts b/packages/cli/src/tasks/render-task-move.ts
new file mode 100644
index 000000000..f429b70fc
--- /dev/null
+++ b/packages/cli/src/tasks/render-task-move.ts
@@ -0,0 +1,22 @@
+import { renderCell, text } from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+import { stringWidth, truncate } from "../render/width.js";
+
+export type TaskMove = {
+ readonly fromLabel: string;
+ readonly toLabel: string;
+ readonly title: string;
+ readonly url: string;
+};
+
+export function renderTaskMove(ui: Ui, move: TaskMove): string[] {
+ const { theme, glyphs } = ui;
+ const to = renderCell([text(move.toLabel, theme.strong, move.url)], ui);
+ const head = ` ${theme.success(glyphs.tick)} Moved ${theme.muted(move.fromLabel)} ${theme.muted(glyphs.arrow)} ${to} ${theme.muted(glyphs.separator)} `;
+ const title = truncate(
+ move.title,
+ Math.max(ui.caps.columns - stringWidth(head), 8),
+ glyphs.ellipsis,
+ );
+ return ["", `${head}${title}`, ""];
+}
diff --git a/packages/cli/src/tasks/resolve-assignee.ts b/packages/cli/src/tasks/resolve-assignee.ts
new file mode 100644
index 000000000..56386148d
--- /dev/null
+++ b/packages/cli/src/tasks/resolve-assignee.ts
@@ -0,0 +1,25 @@
+import { Effect } from "effect";
+import { getCurrentUser, listMembers } from "../api/endpoints.js";
+import { InvalidArgument } from "../errors/errors.js";
+import { matchMember } from "./match-member.js";
+
+export type Assignee = { readonly id: string; readonly name: string };
+
+export const resolveAssignee = Effect.fn("tasks.resolveAssignee")(function* (
+ workspaceId: string,
+ reference: string,
+) {
+ if (reference.trim().toLowerCase() === "me") {
+ const user = yield* getCurrentUser();
+ return { id: user.id, name: user.name } satisfies Assignee;
+ }
+ const members = yield* listMembers(workspaceId);
+ const member = matchMember(members, reference);
+ if (!member) {
+ return yield* new InvalidArgument({
+ message: `No workspace member matches "${reference}".`,
+ hint: 'Use "me", an email address, a name, or a user id.',
+ });
+ }
+ return { id: member.id, name: member.name } satisfies Assignee;
+});
diff --git a/packages/cli/src/tasks/resolve-task.ts b/packages/cli/src/tasks/resolve-task.ts
new file mode 100644
index 000000000..6993c34c8
--- /dev/null
+++ b/packages/cli/src/tasks/resolve-task.ts
@@ -0,0 +1,111 @@
+import { Effect, Option } from "effect";
+import { getProject, listColumns } from "../api/endpoints.js";
+import { KaneoApi } from "../api/kaneo-api.js";
+import {
+ type Column,
+ type Project,
+ type TaskDetail,
+ TaskDetail as TaskDetailSchema,
+} from "../api/schemas.js";
+import { InvalidArgument, NotFound } from "../errors/errors.js";
+import { taskUrl } from "../render/links.js";
+import { ticketId } from "../render/task-format.js";
+import { Session } from "../services/session.js";
+
+const TICKET_ID = /^(\S+)-(\d+)$/u;
+
+export type ResolvedTask = {
+ readonly task: TaskDetail;
+ readonly workspaceId: string;
+ readonly project: Project;
+ readonly columns: ReadonlyArray<Column>;
+ readonly ticketId: string | null;
+ readonly url: string;
+};
+
+export function isTicketId(reference: string): boolean {
+ return TICKET_ID.test(reference.trim());
+}
+
+export const fetchTask = Effect.fn("tasks.fetch")(function* (
+ reference: string,
+) {
+ const session = yield* Session;
+ const api = yield* KaneoApi;
+ const trimmed = reference.trim();
+ const notFound = () =>
+ new NotFound({ message: `Task ${trimmed} not found.` });
+
+ if (isTicketId(trimmed)) {
+ return yield* api
+ .request(
+ "GET",
+ `/api/task/by-ticket-id/${encodeURIComponent(trimmed.toUpperCase())}`,
+ TaskDetailSchema,
+ {
+ query: { workspaceId: Option.getOrUndefined(session.workspace)?.id },
+ },
+ )
+ .pipe(
+ Effect.catchTags({
+ NotFound: () => Effect.fail(notFound()),
+ Conflict: () =>
+ Effect.fail(
+ new InvalidArgument({
+ message: `${trimmed.toUpperCase()} matches tasks in more than one workspace.`,
+ hint: "Pass -w <workspace id> to choose one.",
+ }),
+ ),
+ }),
+ );
+ }
+
+ return yield* api
+ .request(
+ "GET",
+ `/api/task/${encodeURIComponent(trimmed)}`,
+ TaskDetailSchema,
+ {
+ query: { view: "detail" },
+ },
+ )
+ .pipe(
+ Effect.catchTags({
+ NotFound: () => Effect.fail(notFound()),
+ InvalidRequest: (error) =>
+ /could not be determined/i.test(error.message)
+ ? Effect.fail(notFound())
+ : Effect.fail(error),
+ }),
+ );
+});
+
+export const resolveTask = Effect.fn("tasks.resolve")(function* (
+ reference: string,
+ options: { readonly columns?: boolean } = {},
+) {
+ const session = yield* Session;
+ const task = yield* fetchTask(reference);
+ const [project, columns] = yield* Effect.all(
+ [
+ getProject(task.projectId),
+ options.columns
+ ? listColumns(task.projectId)
+ : Effect.succeed([] as ReadonlyArray<Column>),
+ ],
+ { concurrency: 2 },
+ );
+ const workspaceId = task.workspaceId ?? project.workspaceId;
+ return {
+ task,
+ workspaceId,
+ project,
+ columns,
+ ticketId: ticketId(project.slug, task.number),
+ url: taskUrl(session.webUrl, {
+ workspaceId,
+ projectId: task.projectId,
+ id: task.id,
+ }),
+ } satisfies ResolvedTask;
+});
diff --git a/packages/cli/src/tasks/task-detail-json.test.ts b/packages/cli/src/tasks/task-detail-json.test.ts
new file mode 100644
index 000000000..3851f255f
--- /dev/null
+++ b/packages/cli/src/tasks/task-detail-json.test.ts
@@ -0,0 +1,92 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { Column, Project, TaskDetail } from "../api/schemas.js";
+import { toTaskDetailJson } from "./task-detail-json.js";
+
+const task: TaskDetail = {
+ id: "task-1",
+ projectId: "project-1",
+ number: 12,
+ title: "Fix login redirect",
+ description: "Steps",
+ status: "in-progress",
+ priority: "high",
+ startDate: null,
+ dueDate: "2026-10-08T10:00:00.000Z",
+ createdAt: "2026-10-01T10:00:00.000Z",
+ assigneeId: "user-1",
+ assigneeName: "Ada Lovelace",
+};
+
+const project: Project = {
+ id: "project-1",
+ workspaceId: "workspace-1",
+ slug: "kan",
+ name: "Kaneo Web",
+ icon: null,
+ description: null,
+ archivedAt: null,
+ position: 0,
+ lastTaskNumber: 12,
+};
+
+const column: Column = {
+ id: "column-1",
+ projectId: "project-1",
+ name: "In Progress",
+ slug: "in-progress",
+ position: 1,
+ color: null,
+ isFinal: false,
+};
+
+describe("toTaskDetailJson", () => {
+ it("flattens the task, project and column", () => {
+ expect(
+ toTaskDetailJson({
+ task,
+ project,
+ columns: [column],
+ workspaceId: "workspace-1",
+ ticketId: "KAN-12",
+ url: "https://kaneo.test/task-1",
+ }),
+ ).toEqual({
+ id: "task-1",
+ ticketId: "KAN-12",
+ number: 12,
+ title: "Fix login redirect",
+ description: "Steps",
+ status: "in-progress",
+ statusName: "In Progress",
+ priority: "high",
+ assignee: { id: "user-1", name: "Ada Lovelace" },
+ dueDate: "2026-10-08T10:00:00.000Z",
+ startDate: null,
+ createdAt: "2026-10-01T10:00:00.000Z",
+ projectId: "project-1",
+ projectKey: "KAN",
+ projectName: "Kaneo Web",
+ workspaceId: "workspace-1",
+ url: "https://kaneo.test/task-1",
+ });
+ });
+
+ it("falls back to the slug without a matching column and to null without an assignee", () => {
+ const json = toTaskDetailJson({
+ task: {
+ ...task,
+ assigneeId: null,
+ assigneeName: null,
+ status: "planned",
+ },
+ project,
+ columns: [column],
+ workspaceId: "workspace-1",
+ ticketId: null,
+ url: "https://kaneo.test/task-1",
+ });
+ expect(json.statusName).toBe("planned");
+ expect(json.assignee).toBeNull();
+ expect(json.ticketId).toBeNull();
+ });
+});
diff --git a/packages/cli/src/tasks/task-detail-json.ts b/packages/cli/src/tasks/task-detail-json.ts
new file mode 100644
index 000000000..ee30c00cd
--- /dev/null
+++ b/packages/cli/src/tasks/task-detail-json.ts
@@ -0,0 +1,52 @@
+import type { ResolvedTask } from "./resolve-task.js";
+
+export type TaskDetailJson = {
+ readonly id: string;
+ readonly ticketId: string | null;
+ readonly number: number | null;
+ readonly title: string;
+ readonly description: string | null;
+ readonly status: string;
+ readonly statusName: string;
+ readonly priority: string;
+ readonly assignee: {
+ readonly id: string;
+ readonly name: string | null;
+ } | null;
+ readonly dueDate: string | null;
+ readonly startDate: string | null;
+ readonly createdAt: string;
+ readonly projectId: string;
+ readonly projectKey: string;
+ readonly projectName: string;
+ readonly workspaceId: string;
+ readonly url: string;
+};
+
+export function toTaskDetailJson(resolved: ResolvedTask): TaskDetailJson {
+ const { task, project } = resolved;
+ const column = resolved.columns.find(
+ (candidate) => candidate.slug === task.status,
+ );
+ return {
+ id: task.id,
+ ticketId: resolved.ticketId,
+ number: task.number,
+ title: task.title,
+ description: task.description,
+ status: task.status,
+ statusName: column?.name ?? task.status,
+ priority: task.priority,
+ assignee: task.assigneeId
+ ? { id: task.assigneeId, name: task.assigneeName }
+ : null,
+ dueDate: task.dueDate,
+ startDate: task.startDate,
+ createdAt: task.createdAt,
+ projectId: task.projectId,
+ projectKey: project.slug.toUpperCase(),
+ projectName: project.name,
+ workspaceId: resolved.workspaceId,
+ url: resolved.url,
+ };
+}
diff --git a/packages/cli/src/tasks/task-json.ts b/packages/cli/src/tasks/task-json.ts
new file mode 100644
index 000000000..06a967a41
--- /dev/null
+++ b/packages/cli/src/tasks/task-json.ts
@@ -0,0 +1,56 @@
+import type { BoardTask } from "../api/schemas.js";
+import { taskUrl } from "../render/links.js";
+import { ticketId } from "../render/task-format.js";
+import type { LoadedBoard } from "./load-board.js";
+
+export type TaskJson = {
+ readonly id: string;
+ readonly ticketId: string | null;
+ readonly number: number | null;
+ readonly title: string;
+ readonly status: string;
+ readonly statusName: string;
+ readonly priority: string;
+ readonly assignee: {
+ readonly id: string;
+ readonly name: string | null;
+ } | null;
+ readonly dueDate: string | null;
+ readonly startDate: string | null;
+ readonly createdAt: string;
+ readonly projectId: string;
+ readonly workspaceId: string;
+ readonly url: string;
+};
+
+export function toTaskJson(
+ board: LoadedBoard,
+ task: BoardTask,
+ webUrl: string,
+): TaskJson {
+ const column = board.columns.find(
+ (candidate) => candidate.slug === task.status,
+ );
+ return {
+ id: task.id,
+ ticketId: ticketId(board.projectSlug, task.number),
+ number: task.number,
+ title: task.title,
+ status: task.status,
+ statusName: column?.name ?? task.status,
+ priority: task.priority,
+ assignee: task.assigneeId
+ ? { id: task.assigneeId, name: task.assigneeName }
+ : null,
+ dueDate: task.dueDate,
+ startDate: task.startDate,
+ createdAt: task.createdAt,
+ projectId: task.projectId,
+ workspaceId: board.workspaceId,
+ url: taskUrl(webUrl, {
+ workspaceId: board.workspaceId,
+ projectId: task.projectId,
+ id: task.id,
+ }),
+ };
+}
diff --git a/packages/cli/src/testing/test-layers.ts b/packages/cli/src/testing/test-layers.ts
new file mode 100644
index 000000000..c68af1077
--- /dev/null
+++ b/packages/cli/src/testing/test-layers.ts
@@ -0,0 +1,119 @@
+import { Effect, Layer, Option, Redacted } from "effect";
+import { HttpClient, HttpClientResponse } from "effect/http";
+import { ConfigStore, type ConfigStoreShape } from "../config/config-store.js";
+import { type ConfigFile, emptyConfig } from "../config/format.js";
+import { Output, type OutputShape } from "../output/output.js";
+import { makeUi } from "../render/ui.js";
+import {
+ Session,
+ type SessionShape,
+ type TokenSource,
+} from "../services/session.js";
+
+export type RecordedRequest = {
+ readonly method: string;
+ readonly url: string;
+ readonly authorization: string | undefined;
+ readonly body: unknown;
+};
+
+export type Responder = (request: RecordedRequest) => Response;
+
+export function fakeHttpClient(
+ respond: Responder,
+ recorded: RecordedRequest[] = [],
+) {
+ return Layer.succeed(
+ HttpClient.HttpClient,
+ HttpClient.make((request, url) =>
+ Effect.sync(() => {
+ const body =
+ request.body._tag === "Uint8Array"
+ ? JSON.parse(new TextDecoder().decode(request.body.body))
+ : undefined;
+ const entry: RecordedRequest = {
+ method: request.method,
+ url: url.toString(),
+ authorization: request.headers.authorization,
+ body,
+ };
+ recorded.push(entry);
+ return HttpClientResponse.fromWeb(request, respond(entry));
+ }),
+ ),
+ );
+}
+
+export function json(
+ body: unknown,
+ status = 200,
+ headers: Record<string, string> = {},
+) {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "content-type": "application/json", ...headers },
+ });
+}
+
+export function testSession(
+ overrides: Partial<SessionShape> & {
+ token?: string;
+ tokenSource?: TokenSource;
+ } = {},
+) {
+ const { token = "test-token", tokenSource = "profile", ...rest } = overrides;
+ const session: SessionShape = {
+ apiUrl: "https://kaneo.test",
+ webUrl: "https://kaneo.test",
+ profileName: "default",
+ config: emptyConfig,
+ configProblem: Option.none(),
+ profile: undefined,
+ credentials: Option.some({
+ token: Redacted.make(token),
+ source: tokenSource,
+ }),
+ workspace: Option.some({ id: "ws_1", source: "flag" }),
+ project: Option.none(),
+ repo: undefined,
+ ...rest,
+ };
+ return Layer.succeed(Session, session);
+}
+
+export function memoryConfigStore(initial: ConfigFile = emptyConfig) {
+ let current = initial;
+ const store: ConfigStoreShape = {
+ path: "/memory/config.json",
+ load: Effect.sync(() => current),
+ save: (config) =>
+ Effect.sync(() => {
+ current = config;
+ }),
+ };
+ return { layer: Layer.succeed(ConfigStore, store), read: () => current };
+}
+
+export function captureOutput(
+ mode: OutputShape["mode"] = "json",
+ options: { readonly interactive?: boolean; readonly columns?: number } = {},
+) {
+ const stdout: string[] = [];
+ const stderr: string[] = [];
+ const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: options.columns ?? 80,
+ });
+ const output: OutputShape = {
+ mode,
+ ui,
+ errUi: ui,
+ interactive: options.interactive ?? false,
+ out: (text) => Effect.sync(() => void stdout.push(text)),
+ err: (text) => Effect.sync(() => void stderr.push(text)),
+ };
+ return { layer: Layer.succeed(Output, output), stdout, stderr };
+}
diff --git a/packages/cli/src/time/ask-duration.ts b/packages/cli/src/time/ask-duration.ts
new file mode 100644
index 000000000..a135ddd75
--- /dev/null
+++ b/packages/cli/src/time/ask-duration.ts
@@ -0,0 +1,37 @@
+import { Effect, Option, Result } from "effect";
+import { Prompt } from "effect/cli";
+import { Cancelled, InvalidArgument } from "../errors/errors.js";
+import { Output } from "../output/output.js";
+import { promptTheme } from "../prompts/prompt-theme.js";
+import { parseDuration } from "./duration.js";
+
+export const askDuration = Effect.fnUntraced(function* (
+ input: Option.Option<string>,
+ example: string,
+) {
+ if (Option.isSome(input)) {
+ return yield* Effect.fromResult(parseDuration(input.value));
+ }
+ const output = yield* Output;
+ if (!output.interactive) {
+ return yield* new InvalidArgument({
+ message: "A duration is required.",
+ hint: `Pass it after the task, for example ${example}.`,
+ });
+ }
+ return yield* Prompt.run(
+ Prompt.String({
+ message: "How long (for example 1h30m)",
+ validate: (value) => {
+ const parsed = parseDuration(value);
+ return Result.isSuccess(parsed)
+ ? Effect.succeed(String(parsed.success))
+ : Effect.fail(parsed.failure.hint ?? parsed.failure.message);
+ },
+ theme: promptTheme(output.ui),
+ }),
+ ).pipe(
+ Effect.map(Number),
+ Effect.catchTag("QuitError", () => Effect.fail(new Cancelled())),
+ );
+});
diff --git a/packages/cli/src/time/ask-task.ts b/packages/cli/src/time/ask-task.ts
new file mode 100644
index 000000000..831ccff61
--- /dev/null
+++ b/packages/cli/src/time/ask-task.ts
@@ -0,0 +1,37 @@
+import { Effect, Option } from "effect";
+import { listAssignedTasks } from "../api/endpoints.js";
+import { InvalidArgument } from "../errors/errors.js";
+import { Output } from "../output/output.js";
+import { withSpinner } from "../output/spinner.js";
+import { pick } from "../prompts/pick.js";
+import { ticketId } from "../render/task-format.js";
+import { resolveWorkspaceId } from "../services/selection.js";
+
+export const askTask = Effect.fnUntraced(function* (
+ reference: Option.Option<string>,
+ example: string,
+) {
+ if (Option.isSome(reference)) return reference.value;
+ const output = yield* Output;
+ const missing = new InvalidArgument({
+ message: "A task is required.",
+ hint: `Pass a ticket id, for example ${example}.`,
+ });
+ if (!output.interactive) return yield* missing;
+ const workspaceId = yield* resolveWorkspaceId();
+ const { tasks } = yield* withSpinner("Loading your tasks")(
+ listAssignedTasks(workspaceId),
+ );
+ if (tasks.length === 0) return yield* missing;
+ return yield* pick(
+ "Choose a task",
+ tasks.map((task) => {
+ const id = ticketId(task.projectSlug, task.number);
+ return {
+ title: id ? `${id} ${task.title}` : task.title,
+ value: id ?? task.id,
+ description: task.projectName,
+ };
+ }),
+ );
+});
diff --git a/packages/cli/src/time/duration.test.ts b/packages/cli/src/time/duration.test.ts
new file mode 100644
index 000000000..518f96d24
--- /dev/null
+++ b/packages/cli/src/time/duration.test.ts
@@ -0,0 +1,71 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { formatDuration, parseDuration } from "./duration.js";
+
+const seconds = (input: string) => {
+ const parsed = parseDuration(input);
+ return Result.isSuccess(parsed) ? parsed.success : null;
+};
+
+describe("parseDuration", () => {
+ it("reads hours, minutes and both", () => {
+ expect(seconds("1h30m")).toBe(5400);
+ expect(seconds("45m")).toBe(2700);
+ expect(seconds("2h")).toBe(7200);
+ expect(seconds("1h 30m")).toBe(5400);
+ expect(seconds("2H")).toBe(7200);
+ });
+
+ it("reads decimal hours and clock times", () => {
+ expect(seconds("1.5h")).toBe(5400);
+ expect(seconds("0.25h")).toBe(900);
+ expect(seconds("1:30")).toBe(5400);
+ expect(seconds("0:45")).toBe(2700);
+ });
+
+ it("rejects input without a unit or with junk", () => {
+ expect(seconds("90")).toBeNull();
+ expect(seconds("")).toBeNull();
+ expect(seconds("1h30")).toBeNull();
+ expect(seconds("abc")).toBeNull();
+ expect(seconds("1:75")).toBeNull();
+ expect(seconds("-1h")).toBeNull();
+ });
+
+ it("rejects durations under a minute or over 31 days", () => {
+ expect(seconds("0m")).toBeNull();
+ expect(seconds("0.001h")).toBeNull();
+ expect(seconds("745h")).toBeNull();
+ expect(seconds("744h")).toBe(744 * 3600);
+ });
+
+ it("names the flag and gives a hint", () => {
+ const parsed = parseDuration("soon", "--duration");
+ expect(Result.isFailure(parsed)).toBe(true);
+ if (Result.isFailure(parsed)) {
+ expect(parsed.failure.message).toBe(
+ '--duration "soon" is not a duration.',
+ );
+ expect(parsed.failure.hint).toContain("1h30m");
+ }
+ });
+});
+
+describe("formatDuration", () => {
+ it("prints hours and minutes, dropping empty parts", () => {
+ expect(formatDuration(5100)).toBe("1h 25m");
+ expect(formatDuration(2700)).toBe("45m");
+ expect(formatDuration(7200)).toBe("2h");
+ expect(formatDuration(0)).toBe("0m");
+ });
+
+ it("rounds down and marks sub-minute time", () => {
+ expect(formatDuration(5159)).toBe("1h 25m");
+ expect(formatDuration(42)).toBe("<1m");
+ expect(formatDuration(-5)).toBe("0m");
+ });
+
+ it("keeps long totals in hours", () => {
+ expect(formatDuration(30 * 3600 + 60)).toBe("30h 1m");
+ });
+});
diff --git a/packages/cli/src/time/duration.ts b/packages/cli/src/time/duration.ts
new file mode 100644
index 000000000..6d0807ddf
--- /dev/null
+++ b/packages/cli/src/time/duration.ts
@@ -0,0 +1,61 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+
+const UNITS = /^(?:(\d+(?:\.\d+)?)h)?(?:(\d+(?:\.\d+)?)m)?$/u;
+const CLOCK = /^(\d+):([0-5]\d)$/u;
+const MAX_SECONDS = 24 * 60 * 60 * 31;
+
+function invalid(input: string, flag: string): InvalidArgument {
+ return new InvalidArgument({
+ message: `${flag} "${input}" is not a duration.`,
+ hint: "Use hours and minutes, for example 1h30m, 45m, 2h, 1.5h or 1:30.",
+ });
+}
+
+function toSeconds(input: string): number | null {
+ const value = input.trim().toLowerCase().replace(/\s+/gu, "");
+ const clock = CLOCK.exec(value);
+ if (clock) return Number(clock[1]) * 3600 + Number(clock[2]) * 60;
+ const units = UNITS.exec(value);
+ if (!units || (units[1] === undefined && units[2] === undefined)) {
+ return null;
+ }
+ const hours = Number(units[1] ?? 0);
+ const minutes = Number(units[2] ?? 0);
+ return Math.round(hours * 3600 + minutes * 60);
+}
+
+export function parseDuration(
+ input: string,
+ flag = "Duration",
+): Result.Result<number, InvalidArgument> {
+ const seconds = toSeconds(input);
+ if (seconds === null) return Result.fail(invalid(input, flag));
+ if (seconds < 60) {
+ return Result.fail(
+ new InvalidArgument({
+ message: `${flag} "${input}" is shorter than a minute.`,
+ hint: "Log at least 1m.",
+ }),
+ );
+ }
+ if (seconds > MAX_SECONDS) {
+ return Result.fail(
+ new InvalidArgument({
+ message: `${flag} "${input}" is longer than 31 days.`,
+ hint: "Split it into several entries.",
+ }),
+ );
+ }
+ return Result.succeed(seconds);
+}
+
+export function formatDuration(totalSeconds: number): string {
+ const seconds = Math.max(0, Math.floor(totalSeconds));
+ if (seconds > 0 && seconds < 60) return "<1m";
+ const hours = Math.floor(seconds / 3600);
+ const minutes = Math.floor((seconds % 3600) / 60);
+ if (hours === 0) return `${minutes}m`;
+ if (minutes === 0) return `${hours}h`;
+ return `${hours}h ${minutes}m`;
+}
diff --git a/packages/cli/src/time/entry-seconds.test.ts b/packages/cli/src/time/entry-seconds.test.ts
new file mode 100644
index 000000000..b8091ab3c
--- /dev/null
+++ b/packages/cli/src/time/entry-seconds.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from "vite-plus/test";
+import { entrySeconds } from "./entry-seconds.js";
+
+const now = new Date("2026-10-08T12:00:00.000Z");
+
+describe("entrySeconds", () => {
+ it("uses the stored duration of a finished entry", () => {
+ expect(
+ entrySeconds(
+ {
+ startTime: "2026-10-08T09:00:00.000Z",
+ endTime: "2026-10-08T10:00:00.000Z",
+ duration: 3600,
+ },
+ now,
+ ),
+ ).toBe(3600);
+ });
+
+ it("counts a running entry up to now", () => {
+ expect(
+ entrySeconds(
+ {
+ startTime: "2026-10-08T10:35:00.000Z",
+ endTime: null,
+ duration: null,
+ },
+ now,
+ ),
+ ).toBe(5100);
+ });
+
+ it("falls back to the time range and never goes negative", () => {
+ expect(
+ entrySeconds(
+ {
+ startTime: "2026-10-08T09:00:00.000Z",
+ endTime: "2026-10-08T09:30:00.000Z",
+ duration: null,
+ },
+ now,
+ ),
+ ).toBe(1800);
+ expect(
+ entrySeconds(
+ {
+ startTime: "2026-10-08T13:00:00.000Z",
+ endTime: null,
+ duration: null,
+ },
+ now,
+ ),
+ ).toBe(0);
+ });
+});
diff --git a/packages/cli/src/time/entry-seconds.ts b/packages/cli/src/time/entry-seconds.ts
new file mode 100644
index 000000000..c0e518a55
--- /dev/null
+++ b/packages/cli/src/time/entry-seconds.ts
@@ -0,0 +1,14 @@
+export type TimedEntry = {
+ readonly startTime: string;
+ readonly endTime: string | null;
+ readonly duration: number | null;
+};
+
+export function entrySeconds(entry: TimedEntry, now: Date): number {
+ if (entry.duration !== null) return entry.duration;
+ const start = Date.parse(entry.startTime);
+ const end =
+ entry.endTime === null ? now.getTime() : Date.parse(entry.endTime);
+ if (Number.isNaN(start) || Number.isNaN(end)) return 0;
+ return Math.max(0, Math.floor((end - start) / 1000));
+}
diff --git a/packages/cli/src/time/find-running-timer.ts b/packages/cli/src/time/find-running-timer.ts
new file mode 100644
index 000000000..aae26bac1
--- /dev/null
+++ b/packages/cli/src/time/find-running-timer.ts
@@ -0,0 +1,132 @@
+import { Effect, Option } from "effect";
+import { listAssignedTasks, listWorkspaces } from "../api/endpoints.js";
+import {
+ getTimeEntry,
+ listTimeEntries,
+ type TimeEntry,
+} from "../api/time-entries.js";
+import { taskUrl } from "../render/links.js";
+import { ticketId } from "../render/task-format.js";
+import { Session } from "../services/session.js";
+import { type ResolvedTask, resolveTask } from "../tasks/resolve-task.js";
+import { runningEntries } from "./running-entries.js";
+import {
+ forgetTimer,
+ recallTimer,
+ rememberTimer,
+} from "./timer-pointer-store.js";
+
+export type TaskRef = {
+ readonly id: string;
+ readonly ticketId: string | null;
+ readonly title: string;
+ readonly url: string;
+};
+
+export type RunningTimer = {
+ readonly entry: TimeEntry;
+ readonly task: TaskRef;
+};
+
+const SCAN_CONCURRENCY = 8;
+
+export function taskRef(resolved: ResolvedTask): TaskRef {
+ return {
+ id: resolved.task.id,
+ ticketId: resolved.ticketId,
+ title: resolved.task.title,
+ url: resolved.url,
+ };
+}
+
+const latest = (timers: ReadonlyArray<RunningTimer>) =>
+ Option.fromUndefinedOr(
+ [...timers].sort(
+ (left, right) =>
+ Date.parse(right.entry.startTime) - Date.parse(left.entry.startTime),
+ )[0],
+ );
+
+export const findTaskTimer = Effect.fn("time.findTaskTimer")(function* (
+ resolved: ResolvedTask,
+ userId: string,
+) {
+ const entries = yield* listTimeEntries(resolved.task.id);
+ const [entry] = runningEntries(entries, userId);
+ return entry
+ ? Option.some<RunningTimer>({ entry, task: taskRef(resolved) })
+ : Option.none<RunningTimer>();
+});
+
+const fromPointer = Effect.fnUntraced(function* (userId: string) {
+ const pointer = yield* recallTimer;
+ if (Option.isNone(pointer)) return Option.none<RunningTimer>();
+ const entry = yield* getTimeEntry(pointer.value.entryId).pipe(
+ Effect.map((value): TimeEntry | null => value),
+ Effect.catchTags({
+ NotFound: () => Effect.succeed(null),
+ PermissionDenied: () => Effect.succeed(null),
+ }),
+ );
+ if (entry === null || entry.endTime !== null) {
+ yield* forgetTimer(pointer.value.entryId);
+ return Option.none<RunningTimer>();
+ }
+ if (entry.userId !== userId) return Option.none<RunningTimer>();
+ const resolved = yield* resolveTask(entry.taskId);
+ return Option.some<RunningTimer>({ entry, task: taskRef(resolved) });
+});
+
+const scanAssignedTasks = Effect.fnUntraced(function* (userId: string) {
+ const session = yield* Session;
+ const workspaceIds = Option.isSome(session.workspace)
+ ? [session.workspace.value.id]
+ : (yield* listWorkspaces()).map((workspace) => workspace.id);
+ const assigned = yield* Effect.forEach(
+ workspaceIds,
+ (workspaceId) =>
+ listAssignedTasks(workspaceId).pipe(
+ Effect.map(({ tasks }) => tasks.map((task) => ({ task, workspaceId }))),
+ Effect.catchTag("PermissionDenied", () => Effect.succeed([])),
+ ),
+ { concurrency: 4 },
+ );
+ const found = yield* Effect.forEach(
+ assigned.flat(),
+ ({ task, workspaceId }) =>
+ listTimeEntries(task.id).pipe(
+ Effect.map((entries) =>
+ runningEntries(entries, userId).map((entry): RunningTimer => ({
+ entry,
+ task: {
+ id: task.id,
+ ticketId: ticketId(task.projectSlug, task.number),
+ title: task.title,
+ url: taskUrl(session.webUrl, {
+ workspaceId,
+ projectId: task.projectId,
+ id: task.id,
+ }),
+ },
+ })),
+ ),
+ ),
+ { concurrency: SCAN_CONCURRENCY },
+ );
+ const timer = latest(found.flat());
+ if (Option.isSome(timer)) {
+ yield* rememberTimer({
+ entryId: timer.value.entry.id,
+ taskId: timer.value.task.id,
+ });
+ }
+ return timer;
+});
+
+export const findRunningTimer = Effect.fn("time.findRunningTimer")(function* (
+ userId: string,
+) {
+ const remembered = yield* fromPointer(userId);
+ if (Option.isSome(remembered)) return remembered;
+ return yield* scanAssignedTasks(userId);
+});
diff --git a/packages/cli/src/time/log-range.test.ts b/packages/cli/src/time/log-range.test.ts
new file mode 100644
index 000000000..4064aa53e
--- /dev/null
+++ b/packages/cli/src/time/log-range.test.ts
@@ -0,0 +1,45 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { logRange } from "./log-range.js";
+
+const now = new Date(2026, 9, 8, 15, 30, 0);
+
+const range = (seconds: number, day: string) => {
+ const result = logRange(seconds, day, now);
+ return Result.isSuccess(result) ? result.success : null;
+};
+
+describe("logRange", () => {
+ it("ends today's entries now", () => {
+ expect(range(5400, "today")).toEqual({
+ startTime: new Date(2026, 9, 8, 14, 0, 0).toISOString(),
+ endTime: now.toISOString(),
+ });
+ expect(range(5400, "2026-10-08")).toEqual(range(5400, "today"));
+ });
+
+ it("starts earlier days at 9:00 local time", () => {
+ expect(range(2700, "yesterday")).toEqual({
+ startTime: new Date(2026, 9, 7, 9, 0, 0).toISOString(),
+ endTime: new Date(2026, 9, 7, 9, 45, 0).toISOString(),
+ });
+ expect(range(3600, "2026-09-30")).toEqual({
+ startTime: new Date(2026, 8, 30, 9, 0, 0).toISOString(),
+ endTime: new Date(2026, 8, 30, 10, 0, 0).toISOString(),
+ });
+ });
+
+ it("rejects future days and impossible dates", () => {
+ expect(range(3600, "2026-10-09")).toBeNull();
+ expect(range(3600, "2026-02-31")).toBeNull();
+ expect(range(3600, "last week")).toBeNull();
+ });
+
+ it("explains a bad date", () => {
+ const result = logRange(3600, "someday", now);
+ expect(Result.isFailure(result)).toBe(true);
+ if (Result.isFailure(result)) {
+ expect(result.failure.hint).toBe("Use today, yesterday, or YYYY-MM-DD.");
+ }
+ });
+});
diff --git a/packages/cli/src/time/log-range.ts b/packages/cli/src/time/log-range.ts
new file mode 100644
index 000000000..6443debe6
--- /dev/null
+++ b/packages/cli/src/time/log-range.ts
@@ -0,0 +1,79 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+
+const ISO_DAY = /^(\d{4})-(\d{2})-(\d{2})$/u;
+const WORKDAY_START_HOUR = 9;
+
+export type LogRange = {
+ readonly startTime: string;
+ readonly endTime: string;
+};
+
+function sameDay(left: Date, right: Date): boolean {
+ return (
+ left.getFullYear() === right.getFullYear() &&
+ left.getMonth() === right.getMonth() &&
+ left.getDate() === right.getDate()
+ );
+}
+
+function parseDay(value: string, now: Date): Date | null {
+ if (value === "today") return now;
+ if (value === "yesterday") {
+ return new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
+ }
+ const iso = ISO_DAY.exec(value);
+ if (!iso) return null;
+ const year = Number(iso[1]);
+ const month = Number(iso[2]) - 1;
+ const day = Number(iso[3]);
+ const date = new Date(year, month, day);
+ if (
+ date.getFullYear() !== year ||
+ date.getMonth() !== month ||
+ date.getDate() !== day
+ ) {
+ return null;
+ }
+ return date;
+}
+
+export function logRange(
+ seconds: number,
+ dayInput: string,
+ now: Date,
+): Result.Result<LogRange, InvalidArgument> {
+ const day = parseDay(dayInput.trim().toLowerCase(), now);
+ if (!day) {
+ return Result.fail(
+ new InvalidArgument({
+ message: `--date "${dayInput}" is not a date.`,
+ hint: "Use today, yesterday, or YYYY-MM-DD.",
+ }),
+ );
+ }
+ if (sameDay(day, now)) {
+ return Result.succeed({
+ startTime: new Date(now.getTime() - seconds * 1000).toISOString(),
+ endTime: now.toISOString(),
+ });
+ }
+ if (day.getTime() > now.getTime()) {
+ return Result.fail(
+ new InvalidArgument({
+ message: `--date ${dayInput} is in the future.`,
+ hint: "Log time for today or an earlier day.",
+ }),
+ );
+ }
+ const start = new Date(
+ day.getFullYear(),
+ day.getMonth(),
+ day.getDate(),
+ WORKDAY_START_HOUR,
+ );
+ return Result.succeed({
+ startTime: start.toISOString(),
+ endTime: new Date(start.getTime() + seconds * 1000).toISOString(),
+ });
+}
diff --git a/packages/cli/src/time/render-time-entries.test.ts b/packages/cli/src/time/render-time-entries.test.ts
new file mode 100644
index 000000000..b7d67600d
--- /dev/null
+++ b/packages/cli/src/time/render-time-entries.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import { renderTimeEntries } from "./render-time-entries.js";
+import type { TimeEntryJson } from "./time-entry-json.js";
+
+const ui = (columns: number) =>
+ makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns,
+ });
+
+const now = new Date(2026, 9, 8, 12, 0);
+
+const entry = (
+ id: string,
+ day: number,
+ seconds: number,
+ options: { note?: string; running?: boolean } = {},
+): TimeEntryJson => ({
+ id,
+ taskId: "t12",
+ ticketId: "KAN-12",
+ user: { id: "u1", name: "Ada Lovelace" },
+ startedAt: new Date(2026, 9, day, 9, 0).toISOString(),
+ endedAt: options.running ? null : new Date(2026, 9, day, 10, 0).toISOString(),
+ durationSeconds: seconds,
+ note: options.note ?? null,
+ running: options.running ?? false,
+});
+
+const view = {
+ label: "KAN-12",
+ url: "https://kaneo.test/t12",
+ title: "Fix login redirect",
+ now,
+ entries: [
+ entry("a0b1c2d3e4f5g6h7i8j9k0l1", 6, 5400, {
+ note: "Pairing on the device flow",
+ }),
+ entry("m2n3o4p5q6r7s8t9u0v1w2x3", 8, 1500, { running: true }),
+ ],
+};
+
+describe("renderTimeEntries", () => {
+ it("lists entries with a total at 80 columns", () => {
+ expect(renderTimeEntries(ui(80), view)).toEqual([
+ "",
+ " KAN-12 · Fix login redirect",
+ "",
+ " Oct 6 1h 30m Ada Lovelace Pairing on the devic… a0b1c2d3e4f5g6h7i8j9k0l1",
+ " Today ● 25m Ada Lovelace m2n3o4p5q6r7s8t9u0v1w2x3",
+ "",
+ " Total 1h 55m · 2 entries",
+ "",
+ ]);
+ });
+
+ it("keeps every line within narrow terminals", () => {
+ for (const line of renderTimeEntries(ui(60), view)) {
+ expect(stringWidth(line)).toBeLessThanOrEqual(60);
+ }
+ });
+
+ it("explains an empty list", () => {
+ expect(renderTimeEntries(ui(80), { ...view, entries: [] })).toEqual([
+ "",
+ " KAN-12 · Fix login redirect",
+ "",
+ " No time logged yet.",
+ "",
+ " Log some with kaneo time log KAN-12 1h",
+ "",
+ ]);
+ });
+});
diff --git a/packages/cli/src/time/render-time-entries.ts b/packages/cli/src/time/render-time-entries.ts
new file mode 100644
index 000000000..b1b03b8d0
--- /dev/null
+++ b/packages/cli/src/time/render-time-entries.ts
@@ -0,0 +1,85 @@
+import { type Cell, renderCell, text } from "../render/cell.js";
+import { renderTable } from "../render/table.js";
+import { formatDue } from "../render/task-format.js";
+import type { Ui } from "../render/ui.js";
+import { formatDuration } from "./duration.js";
+import type { TimeEntryJson } from "./time-entry-json.js";
+
+export type TimeEntriesView = {
+ readonly label: string;
+ readonly url: string;
+ readonly title: string;
+ readonly entries: ReadonlyArray<TimeEntryJson>;
+ readonly now: Date;
+};
+
+export function totalSeconds(entries: ReadonlyArray<TimeEntryJson>): number {
+ return entries.reduce((sum, entry) => sum + entry.durationSeconds, 0);
+}
+
+export function renderTimeEntries(ui: Ui, view: TimeEntriesView): string[] {
+ const { theme, glyphs } = ui;
+ const header = ` ${renderCell([text(view.label, theme.strong, view.url)], ui)} ${theme.muted(glyphs.separator)} ${view.title}`;
+ if (view.entries.length === 0) {
+ return [
+ "",
+ header,
+ "",
+ ` ${theme.muted("No time logged yet.")}`,
+ "",
+ ` ${theme.muted("Log some with")} ${theme.strong(`kaneo time log ${view.label} 1h`)}`,
+ "",
+ ];
+ }
+ const rows = renderTable(
+ ui,
+ view.entries,
+ [
+ {
+ header: "Date",
+ cell: (entry): Cell => [
+ text(formatDue(new Date(entry.startedAt), view.now)),
+ ],
+ },
+ {
+ header: "Duration",
+ align: "right",
+ cell: (entry): Cell =>
+ entry.running
+ ? [
+ text(`${glyphs.dot} `, theme.success),
+ text(formatDuration(entry.durationSeconds)),
+ ]
+ : [text(formatDuration(entry.durationSeconds))],
+ },
+ {
+ header: "User",
+ optional: true,
+ minWidth: 10,
+ cell: (entry): Cell =>
+ entry.user ? [text(entry.user.name ?? "Unknown", theme.muted)] : [],
+ },
+ {
+ header: "Note",
+ flex: true,
+ minWidth: 8,
+ cell: (entry): Cell => (entry.note ? [text(entry.note)] : []),
+ },
+ {
+ header: "ID",
+ cell: (entry): Cell => [text(entry.id, theme.muted)],
+ },
+ ],
+ { width: ui.caps.columns, indent: 4 },
+ );
+ const count = view.entries.length;
+ return [
+ "",
+ header,
+ "",
+ ...rows,
+ "",
+ ` ${theme.muted("Total")} ${theme.strong(formatDuration(totalSeconds(view.entries)))} ${theme.muted(`${glyphs.separator} ${count} ${count === 1 ? "entry" : "entries"}`)}`,
+ "",
+ ];
+}
diff --git a/packages/cli/src/time/render-timer-change.test.ts b/packages/cli/src/time/render-timer-change.test.ts
new file mode 100644
index 000000000..a08a789b8
--- /dev/null
+++ b/packages/cli/src/time/render-timer-change.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { renderTimerChange } from "./render-timer-change.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+describe("renderTimerChange", () => {
+ it("prints a stopped timer with its duration", () => {
+ expect(
+ renderTimerChange(ui, {
+ verb: "Stopped",
+ label: "KAN-12",
+ url: "https://kaneo.test/t",
+ details: ["1h 25m"],
+ }),
+ ).toEqual(["", " ✓ Stopped KAN-12 · 1h 25m", ""]);
+ });
+
+ it("skips empty details", () => {
+ expect(
+ renderTimerChange(ui, {
+ verb: "Logged",
+ label: "KAN-3",
+ url: "https://kaneo.test/t",
+ details: ["45m", "Yesterday", ""],
+ }),
+ ).toEqual(["", " ✓ Logged KAN-3 · 45m · Yesterday", ""]);
+ });
+});
diff --git a/packages/cli/src/time/render-timer-change.ts b/packages/cli/src/time/render-timer-change.ts
new file mode 100644
index 000000000..9c29faf67
--- /dev/null
+++ b/packages/cli/src/time/render-timer-change.ts
@@ -0,0 +1,21 @@
+import { renderCell, text } from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+
+export type TimerChange = {
+ readonly verb: "Started" | "Stopped" | "Logged" | "Updated";
+ readonly label: string;
+ readonly url: string;
+ readonly details: ReadonlyArray<string>;
+};
+
+export function renderTimerChange(ui: Ui, change: TimerChange): string[] {
+ const { theme, glyphs } = ui;
+ const separator = ` ${theme.muted(glyphs.separator)} `;
+ const label = renderCell([text(change.label, theme.strong, change.url)], ui);
+ const details = change.details.filter((detail) => detail !== "");
+ return [
+ "",
+ ` ${theme.success(glyphs.tick)} ${change.verb} ${[label, ...details].join(separator)}`,
+ "",
+ ];
+}
diff --git a/packages/cli/src/time/render-timer-status.test.ts b/packages/cli/src/time/render-timer-status.test.ts
new file mode 100644
index 000000000..7a6468918
--- /dev/null
+++ b/packages/cli/src/time/render-timer-status.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { renderTimerStatus } from "./render-timer-status.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+describe("renderTimerStatus", () => {
+ it("shows the running timer with elapsed time and note", () => {
+ const startedAt = new Date(2026, 9, 8, 9, 5).toISOString();
+ expect(
+ renderTimerStatus(ui, {
+ label: "KAN-12",
+ url: "https://kaneo.test/t",
+ title: "Fix login redirect",
+ startedAt,
+ elapsedSeconds: 5100,
+ note: "Pairing",
+ }),
+ ).toEqual([
+ "",
+ " ● KAN-12 · Fix login redirect",
+ " 1h 25m since 09:05 · Pairing",
+ "",
+ ]);
+ });
+
+ it("says when nothing is running", () => {
+ expect(renderTimerStatus(ui, null)).toEqual([
+ "",
+ " ● No timer running",
+ "",
+ " Start one with kaneo time start <task>",
+ "",
+ ]);
+ });
+});
diff --git a/packages/cli/src/time/render-timer-status.ts b/packages/cli/src/time/render-timer-status.ts
new file mode 100644
index 000000000..2d395c088
--- /dev/null
+++ b/packages/cli/src/time/render-timer-status.ts
@@ -0,0 +1,41 @@
+import { renderCell, text } from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+import { formatDuration } from "./duration.js";
+
+export type TimerStatusView = {
+ readonly label: string;
+ readonly url: string;
+ readonly title: string;
+ readonly startedAt: string;
+ readonly elapsedSeconds: number;
+ readonly note: string | null;
+} | null;
+
+function clock(iso: string): string {
+ return new Date(iso).toLocaleTimeString("en-US", {
+ hour: "2-digit",
+ minute: "2-digit",
+ hourCycle: "h23",
+ });
+}
+
+export function renderTimerStatus(ui: Ui, view: TimerStatusView): string[] {
+ const { theme, glyphs } = ui;
+ if (view === null) {
+ return [
+ "",
+ ` ${theme.muted(glyphs.dot)} No timer running`,
+ "",
+ ` ${theme.muted("Start one with")} ${theme.strong("kaneo time start <task>")}`,
+ "",
+ ];
+ }
+ const label = renderCell([text(view.label, theme.strong, view.url)], ui);
+ const since = `${theme.muted("since")} ${clock(view.startedAt)}`;
+ return [
+ "",
+ ` ${theme.success(glyphs.dot)} ${label} ${theme.muted(glyphs.separator)} ${view.title}`,
+ ` ${theme.strong(formatDuration(view.elapsedSeconds))} ${since}${view.note ? ` ${theme.muted(glyphs.separator)} ${view.note}` : ""}`,
+ "",
+ ];
+}
diff --git a/packages/cli/src/time/running-entries.test.ts b/packages/cli/src/time/running-entries.test.ts
new file mode 100644
index 000000000..bf63b103f
--- /dev/null
+++ b/packages/cli/src/time/running-entries.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from "vite-plus/test";
+import { runningEntries } from "./running-entries.js";
+
+const entry = (
+ id: string,
+ userId: string | null,
+ startTime: string,
+ endTime: string | null,
+) => ({ id, userId, startTime, endTime });
+
+describe("runningEntries", () => {
+ it("keeps only my open entries, newest first", () => {
+ const entries = [
+ entry(
+ "done",
+ "me",
+ "2026-10-08T08:00:00.000Z",
+ "2026-10-08T09:00:00.000Z",
+ ),
+ entry("older", "me", "2026-10-08T09:00:00.000Z", null),
+ entry("theirs", "someone", "2026-10-08T11:00:00.000Z", null),
+ entry("newer", "me", "2026-10-08T10:00:00.000Z", null),
+ entry("orphan", null, "2026-10-08T11:30:00.000Z", null),
+ ];
+ expect(runningEntries(entries, "me").map((e) => e.id)).toEqual([
+ "newer",
+ "older",
+ ]);
+ });
+
+ it("finds nothing when every entry is closed", () => {
+ expect(
+ runningEntries(
+ [
+ entry(
+ "a",
+ "me",
+ "2026-10-08T08:00:00.000Z",
+ "2026-10-08T08:30:00.000Z",
+ ),
+ ],
+ "me",
+ ),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/cli/src/time/running-entries.ts b/packages/cli/src/time/running-entries.ts
new file mode 100644
index 000000000..5cd6b0f2a
--- /dev/null
+++ b/packages/cli/src/time/running-entries.ts
@@ -0,0 +1,16 @@
+export type OwnedEntry = {
+ readonly userId: string | null;
+ readonly startTime: string;
+ readonly endTime: string | null;
+};
+
+export function runningEntries<E extends OwnedEntry>(
+ entries: ReadonlyArray<E>,
+ userId: string,
+): E[] {
+ return entries
+ .filter((entry) => entry.endTime === null && entry.userId === userId)
+ .sort(
+ (left, right) => Date.parse(right.startTime) - Date.parse(left.startTime),
+ );
+}
diff --git a/packages/cli/src/time/stop-timer.ts b/packages/cli/src/time/stop-timer.ts
new file mode 100644
index 000000000..a83d80e90
--- /dev/null
+++ b/packages/cli/src/time/stop-timer.ts
@@ -0,0 +1,17 @@
+import { Effect } from "effect";
+import { updateTimeEntry } from "../api/time-entries.js";
+import type { RunningTimer } from "./find-running-timer.js";
+import { forgetTimer } from "./timer-pointer-store.js";
+
+export const stopTimer = Effect.fn("time.stopTimer")(function* (
+ timer: RunningTimer,
+ now: Date,
+) {
+ const end = Math.max(now.getTime(), Date.parse(timer.entry.startTime));
+ const stopped = yield* updateTimeEntry(timer.entry.id, {
+ startTime: timer.entry.startTime,
+ endTime: new Date(end).toISOString(),
+ });
+ yield* forgetTimer(timer.entry.id);
+ return stopped;
+});
diff --git a/packages/cli/src/time/time-entry-json.test.ts b/packages/cli/src/time/time-entry-json.test.ts
new file mode 100644
index 000000000..22c2f6a4c
--- /dev/null
+++ b/packages/cli/src/time/time-entry-json.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it } from "vite-plus/test";
+import { toTimeEntryJson } from "./time-entry-json.js";
+
+const now = new Date("2026-10-08T12:00:00.000Z");
+
+describe("toTimeEntryJson", () => {
+ it("shapes a finished entry", () => {
+ expect(
+ toTimeEntryJson(
+ {
+ id: "e1",
+ taskId: "t1",
+ userId: "u1",
+ userName: "Ada Lovelace",
+ description: "Pairing",
+ startTime: "2026-10-08T09:00:00.000Z",
+ endTime: "2026-10-08T10:30:00.000Z",
+ duration: 5400,
+ },
+ "KAN-12",
+ now,
+ ),
+ ).toEqual({
+ id: "e1",
+ taskId: "t1",
+ ticketId: "KAN-12",
+ user: { id: "u1", name: "Ada Lovelace" },
+ startedAt: "2026-10-08T09:00:00.000Z",
+ endedAt: "2026-10-08T10:30:00.000Z",
+ durationSeconds: 5400,
+ note: "Pairing",
+ running: false,
+ });
+ });
+
+ it("counts a running entry to now and turns an empty note into null", () => {
+ const json = toTimeEntryJson(
+ {
+ id: "e2",
+ taskId: "t1",
+ userId: "u1",
+ description: "",
+ startTime: "2026-10-08T11:00:00.000Z",
+ endTime: null,
+ duration: null,
+ },
+ null,
+ now,
+ "Ada Lovelace",
+ );
+ expect(json.running).toBe(true);
+ expect(json.durationSeconds).toBe(3600);
+ expect(json.note).toBeNull();
+ expect(json.user).toEqual({ id: "u1", name: "Ada Lovelace" });
+ });
+
+ it("keeps entries whose user was removed", () => {
+ expect(
+ toTimeEntryJson(
+ {
+ id: "e3",
+ taskId: "t1",
+ userId: null,
+ description: null,
+ startTime: "2026-10-08T09:00:00.000Z",
+ endTime: "2026-10-08T09:10:00.000Z",
+ duration: 600,
+ },
+ "KAN-12",
+ now,
+ ).user,
+ ).toBeNull();
+ });
+});
diff --git a/packages/cli/src/time/time-entry-json.ts b/packages/cli/src/time/time-entry-json.ts
new file mode 100644
index 000000000..e0cbb9105
--- /dev/null
+++ b/packages/cli/src/time/time-entry-json.ts
@@ -0,0 +1,36 @@
+import type { TimeEntry } from "../api/time-entries.js";
+import { entrySeconds } from "./entry-seconds.js";
+
+export type TimeEntryJson = {
+ readonly id: string;
+ readonly taskId: string;
+ readonly ticketId: string | null;
+ readonly user: { readonly id: string; readonly name: string | null } | null;
+ readonly startedAt: string;
+ readonly endedAt: string | null;
+ readonly durationSeconds: number;
+ readonly note: string | null;
+ readonly running: boolean;
+};
+
+export function toTimeEntryJson(
+ entry: TimeEntry & { readonly userName?: string | null },
+ ticketId: string | null,
+ now: Date,
+ userName: string | null = null,
+): TimeEntryJson {
+ const note = entry.description?.trim() ? entry.description : null;
+ return {
+ id: entry.id,
+ taskId: entry.taskId,
+ ticketId,
+ user: entry.userId
+ ? { id: entry.userId, name: entry.userName ?? userName }
+ : null,
+ startedAt: entry.startTime,
+ endedAt: entry.endTime,
+ durationSeconds: entrySeconds(entry, now),
+ note,
+ running: entry.endTime === null,
+ };
+}
diff --git a/packages/cli/src/time/timer-pointer-store.ts b/packages/cli/src/time/timer-pointer-store.ts
new file mode 100644
index 000000000..bd895fce7
--- /dev/null
+++ b/packages/cli/src/time/timer-pointer-store.ts
@@ -0,0 +1,57 @@
+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { Effect, Option } from "effect";
+import { ConfigStore } from "../config/config-store.js";
+import { Session } from "../services/session.js";
+import {
+ parseTimerPointers,
+ serializeTimerPointers,
+ type TimerPointer,
+ type TimerPointers,
+ withTimerPointer,
+} from "./timer-pointers.js";
+
+const pointerPath = Effect.gen(function* () {
+ const store = yield* ConfigStore;
+ return join(dirname(store.path), "timer.json");
+});
+
+const load = (path: string) =>
+ Effect.tryPromise(() => readFile(path, "utf8")).pipe(
+ Effect.map(parseTimerPointers),
+ Effect.orElseSucceed((): TimerPointers => ({})),
+ );
+
+const update = (
+ change: (current: TimerPointers, apiUrl: string) => TimerPointers,
+) =>
+ Effect.gen(function* () {
+ const session = yield* Session;
+ const path = yield* pointerPath;
+ const current = yield* load(path);
+ const next = change(current, session.apiUrl);
+ if (next === current) return;
+ yield* Effect.tryPromise(async () => {
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
+ const temporary = `${path}.${process.pid}.tmp`;
+ await writeFile(temporary, serializeTimerPointers(next), { mode: 0o600 });
+ await rename(temporary, path);
+ }).pipe(Effect.ignore);
+ });
+
+export const recallTimer = Effect.gen(function* () {
+ const session = yield* Session;
+ const path = yield* pointerPath;
+ const pointers = yield* load(path);
+ return Option.fromUndefinedOr(pointers[session.apiUrl]);
+});
+
+export const rememberTimer = (pointer: TimerPointer) =>
+ update((current, apiUrl) => withTimerPointer(current, apiUrl, pointer));
+
+export const forgetTimer = (entryId: string) =>
+ update((current, apiUrl) =>
+ current[apiUrl]?.entryId === entryId
+ ? withTimerPointer(current, apiUrl, null)
+ : current,
+ );
diff --git a/packages/cli/src/time/timer-pointers.test.ts b/packages/cli/src/time/timer-pointers.test.ts
new file mode 100644
index 000000000..f1b58b4b8
--- /dev/null
+++ b/packages/cli/src/time/timer-pointers.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from "vite-plus/test";
+import {
+ parseTimerPointers,
+ serializeTimerPointers,
+ withTimerPointer,
+} from "./timer-pointers.js";
+
+describe("timer pointers", () => {
+ it("round-trips through the file format", () => {
+ const pointers = withTimerPointer({}, "https://kaneo.test", {
+ entryId: "e1",
+ taskId: "t1",
+ });
+ expect(parseTimerPointers(serializeTimerPointers(pointers))).toEqual({
+ "https://kaneo.test": { entryId: "e1", taskId: "t1" },
+ });
+ });
+
+ it("keeps one pointer per server and clears it", () => {
+ const first = withTimerPointer({}, "https://a.test", {
+ entryId: "e1",
+ taskId: "t1",
+ });
+ const both = withTimerPointer(first, "https://b.test", {
+ entryId: "e2",
+ taskId: "t2",
+ });
+ expect(withTimerPointer(both, "https://a.test", null)).toEqual({
+ "https://b.test": { entryId: "e2", taskId: "t2" },
+ });
+ });
+
+ it("ignores broken or foreign content", () => {
+ expect(parseTimerPointers("not json")).toEqual({});
+ expect(parseTimerPointers('{"timers":[1]}')).toEqual({});
+ expect(
+ parseTimerPointers('{"timers":{"https://a.test":{"entryId":1}}}'),
+ ).toEqual({});
+ });
+});
diff --git a/packages/cli/src/time/timer-pointers.ts b/packages/cli/src/time/timer-pointers.ts
new file mode 100644
index 000000000..c6b6be12c
--- /dev/null
+++ b/packages/cli/src/time/timer-pointers.ts
@@ -0,0 +1,47 @@
+export type TimerPointer = {
+ readonly entryId: string;
+ readonly taskId: string;
+};
+
+export type TimerPointers = Readonly<Record<string, TimerPointer>>;
+
+function isPointer(value: unknown): value is TimerPointer {
+ if (!value || typeof value !== "object") return false;
+ const record = value as Record<string, unknown>;
+ return (
+ typeof record.entryId === "string" && typeof record.taskId === "string"
+ );
+}
+
+export function parseTimerPointers(text: string): TimerPointers {
+ try {
+ const parsed: unknown = JSON.parse(text);
+ const timers =
+ parsed && typeof parsed === "object"
+ ? (parsed as { timers?: unknown }).timers
+ : undefined;
+ if (!timers || typeof timers !== "object") return {};
+ const pointers: Record<string, TimerPointer> = {};
+ for (const [apiUrl, value] of Object.entries(timers)) {
+ if (isPointer(value)) {
+ pointers[apiUrl] = { entryId: value.entryId, taskId: value.taskId };
+ }
+ }
+ return pointers;
+ } catch {
+ return {};
+ }
+}
+
+export function serializeTimerPointers(pointers: TimerPointers): string {
+ return `${JSON.stringify({ version: 1, timers: pointers }, null, 2)}\n`;
+}
+
+export function withTimerPointer(
+ pointers: TimerPointers,
+ apiUrl: string,
+ pointer: TimerPointer | null,
+): TimerPointers {
+ const { [apiUrl]: _previous, ...rest } = pointers;
+ return pointer ? { ...rest, [apiUrl]: pointer } : rest;
+}
diff --git a/packages/cli/src/transfer/batches.test.ts b/packages/cli/src/transfer/batches.test.ts
new file mode 100644
index 000000000..389973d24
--- /dev/null
+++ b/packages/cli/src/transfer/batches.test.ts
@@ -0,0 +1,9 @@
+import { describe, expect, it } from "vite-plus/test";
+import { batches } from "./batches.js";
+
+describe("batches", () => {
+ it("splits a list into chunks of at most the given size", () => {
+ expect(batches([1, 2, 3, 4, 5], 2)).toEqual([[1, 2], [3, 4], [5]]);
+ expect(batches([], 50)).toEqual([]);
+ });
+});
diff --git a/packages/cli/src/transfer/batches.ts b/packages/cli/src/transfer/batches.ts
new file mode 100644
index 000000000..8f237a466
--- /dev/null
+++ b/packages/cli/src/transfer/batches.ts
@@ -0,0 +1,10 @@
+export function batches<A>(
+ items: ReadonlyArray<A>,
+ size: number,
+): ReadonlyArray<ReadonlyArray<A>> {
+ const result: A[][] = [];
+ for (let start = 0; start < items.length; start += size) {
+ result.push(items.slice(start, start + size));
+ }
+ return result;
+}
diff --git a/packages/cli/src/transfer/import-plan.test.ts b/packages/cli/src/transfer/import-plan.test.ts
new file mode 100644
index 000000000..347245ca5
--- /dev/null
+++ b/packages/cli/src/transfer/import-plan.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { Column } from "../api/schemas.js";
+import { planImport } from "./import-plan.js";
+
+function column(slug: string, name: string, position: number): Column {
+ return {
+ id: slug,
+ projectId: "p",
+ slug,
+ name,
+ position,
+ color: null,
+ isFinal: false,
+ };
+}
+
+const columns = [
+ column("in-progress", "In Progress", 1),
+ column("to-do", "To Do", 0),
+ column("done", "Done", 2),
+];
+
+describe("planImport", () => {
+ it("keeps known statuses and matches names to column slugs", () => {
+ const plan = planImport(
+ [
+ { title: "a", status: "to-do", labels: 0 },
+ { title: "b", status: "Done", labels: 0 },
+ { title: "c", status: "planned", labels: 0 },
+ ],
+ columns,
+ );
+ expect(plan.tasks.map((task) => task.status)).toEqual([
+ "to-do",
+ "done",
+ "planned",
+ ]);
+ expect(plan.remapped).toEqual([{ from: "Done", to: "done" }]);
+ expect(plan.unknown).toEqual([]);
+ });
+
+ it("reports unknown statuses before importing", () => {
+ const plan = planImport(
+ [
+ { title: "a", status: "backlog", labels: 0 },
+ { title: "b", status: "backlog", labels: 0 },
+ { title: "c", status: "icebox", labels: 0 },
+ ],
+ columns,
+ );
+ expect(plan.unknown).toEqual([
+ { status: "backlog", count: 2 },
+ { status: "icebox", count: 1 },
+ ]);
+ expect(plan.tasks.map((task) => task.status)).toEqual([
+ "backlog",
+ "backlog",
+ "icebox",
+ ]);
+ });
+
+ it("puts tasks without a status in the first column", () => {
+ expect(
+ planImport([{ title: "a", labels: 0 }], columns).tasks[0]?.status,
+ ).toBe("to-do");
+ });
+
+ it("counts tasks whose labels will be dropped", () => {
+ expect(
+ planImport(
+ [
+ { title: "a", labels: 2 },
+ { title: "b", labels: 0 },
+ ],
+ columns,
+ ).withLabels,
+ ).toBe(1);
+ });
+
+ it("only sends the fields the file has", () => {
+ expect(
+ planImport(
+ [
+ {
+ title: "a",
+ status: "done",
+ dueDate: null,
+ userId: "u1",
+ labels: 0,
+ },
+ ],
+ columns,
+ ).tasks[0],
+ ).toEqual({ title: "a", status: "done", dueDate: null, userId: "u1" });
+ });
+});
diff --git a/packages/cli/src/transfer/import-plan.ts b/packages/cli/src/transfer/import-plan.ts
new file mode 100644
index 000000000..6d9a860b7
--- /dev/null
+++ b/packages/cli/src/transfer/import-plan.ts
@@ -0,0 +1,76 @@
+import type { ImportTaskBody } from "../api/export-import.js";
+import type { Column } from "../api/schemas.js";
+import { matchColumn } from "../tasks/match-column.js";
+import type { ImportCandidate } from "./parse-import-file.js";
+
+const VIRTUAL_STATUSES = ["planned", "archived"];
+
+export type StatusRemap = { readonly from: string; readonly to: string };
+
+export type ImportPlan = {
+ readonly tasks: ReadonlyArray<ImportTaskBody>;
+ readonly remapped: ReadonlyArray<StatusRemap>;
+ readonly unknown: ReadonlyArray<{
+ readonly status: string;
+ readonly count: number;
+ }>;
+ readonly withLabels: number;
+};
+
+function resolveStatus(
+ status: string | undefined,
+ columns: ReadonlyArray<Column>,
+ fallback: string,
+): { readonly slug: string; readonly known: boolean } {
+ if (status === undefined) return { slug: fallback, known: true };
+ if (
+ VIRTUAL_STATUSES.includes(status) ||
+ columns.some((column) => column.slug === status)
+ ) {
+ return { slug: status, known: true };
+ }
+ const match = matchColumn(columns, status);
+ return match
+ ? { slug: match.slug, known: true }
+ : { slug: status, known: false };
+}
+
+export function planImport(
+ candidates: ReadonlyArray<ImportCandidate>,
+ columns: ReadonlyArray<Column>,
+): ImportPlan {
+ const ordered = [...columns].sort((a, b) => a.position - b.position);
+ const fallback = ordered[0]?.slug ?? "planned";
+ const remapped = new Map<string, string>();
+ const unknown = new Map<string, number>();
+ const tasks = candidates.map((candidate): ImportTaskBody => {
+ const { slug, known } = resolveStatus(candidate.status, ordered, fallback);
+ if (!known) unknown.set(slug, (unknown.get(slug) ?? 0) + 1);
+ else if (candidate.status !== undefined && slug !== candidate.status) {
+ remapped.set(candidate.status, slug);
+ }
+ return {
+ title: candidate.title,
+ status: slug,
+ ...(candidate.description === undefined
+ ? {}
+ : { description: candidate.description }),
+ ...(candidate.priority === undefined
+ ? {}
+ : { priority: candidate.priority }),
+ ...(candidate.startDate === undefined
+ ? {}
+ : { startDate: candidate.startDate }),
+ ...(candidate.dueDate === undefined
+ ? {}
+ : { dueDate: candidate.dueDate }),
+ ...(candidate.userId === undefined ? {} : { userId: candidate.userId }),
+ };
+ });
+ return {
+ tasks,
+ remapped: [...remapped].map(([from, to]) => ({ from, to })),
+ unknown: [...unknown].map(([status, count]) => ({ status, count })),
+ withLabels: candidates.filter((candidate) => candidate.labels > 0).length,
+ };
+}
diff --git a/packages/cli/src/transfer/import-report.test.ts b/packages/cli/src/transfer/import-report.test.ts
new file mode 100644
index 000000000..e3480833a
--- /dev/null
+++ b/packages/cli/src/transfer/import-report.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { Column } from "../api/schemas.js";
+import { planImport } from "./import-plan.js";
+import { buildImportReport } from "./import-report.js";
+
+const columns: Column[] = [
+ {
+ id: "c1",
+ projectId: "p1",
+ slug: "to-do",
+ name: "To Do",
+ position: 0,
+ color: null,
+ isFinal: false,
+ },
+];
+
+const project = {
+ id: "p1",
+ slug: "kan",
+ name: "Kaneo Web",
+ workspaceId: "w1",
+};
+
+const plan = planImport(
+ [
+ { title: "One", status: "to-do", labels: 1 },
+ { title: "Two", status: "backlog", labels: 0 },
+ ],
+ columns,
+);
+
+describe("buildImportReport", () => {
+ it("describes a dry run without results", () => {
+ const report = buildImportReport({
+ project,
+ columns,
+ webUrl: "https://kaneo.test",
+ plan,
+ outcomes: null,
+ });
+ expect(report).toMatchObject({
+ project: { id: "p1", key: "KAN", name: "Kaneo Web" },
+ dryRun: true,
+ total: 2,
+ imported: 0,
+ failed: 0,
+ unknownStatuses: ["backlog"],
+ tasksWithLabels: 1,
+ });
+ expect(
+ report.tasks.map((task) => [task.statusName, task.imported]),
+ ).toEqual([
+ ["To Do", null],
+ ["Planned", null],
+ ]);
+ });
+
+ it("reports each task's outcome with its ticket id", () => {
+ const report = buildImportReport({
+ project,
+ columns,
+ webUrl: "https://kaneo.test",
+ plan,
+ outcomes: [
+ {
+ success: true,
+ task: { id: "t1", number: 7, title: "One", status: "to-do" },
+ },
+ { success: false, error: "Not a member", task: { title: "Two" } },
+ ],
+ });
+ expect(report.imported).toBe(1);
+ expect(report.failed).toBe(1);
+ expect(report.tasks[0]).toMatchObject({
+ imported: true,
+ ticketId: "KAN-7",
+ url: "https://kaneo.test/dashboard/workspace/w1/project/p1/task/t1",
+ });
+ expect(report.tasks[1]).toMatchObject({
+ imported: false,
+ ticketId: null,
+ error: "Not a member",
+ });
+ });
+});
diff --git a/packages/cli/src/transfer/import-report.ts b/packages/cli/src/transfer/import-report.ts
new file mode 100644
index 000000000..df128cebf
--- /dev/null
+++ b/packages/cli/src/transfer/import-report.ts
@@ -0,0 +1,106 @@
+import type { ImportOutcome } from "../api/export-import.js";
+import type { Column } from "../api/schemas.js";
+import { projectUrl, taskUrl } from "../render/links.js";
+import { ticketId } from "../render/task-format.js";
+import type { ImportPlan, StatusRemap } from "./import-plan.js";
+
+export type ImportTaskReport = {
+ readonly index: number;
+ readonly title: string;
+ readonly status: string;
+ readonly statusName: string;
+ readonly imported: boolean | null;
+ readonly id: string | null;
+ readonly ticketId: string | null;
+ readonly url: string | null;
+ readonly error: string | null;
+ readonly warnings: ReadonlyArray<string>;
+};
+
+export type ImportReportJson = {
+ readonly project: {
+ readonly id: string;
+ readonly key: string;
+ readonly name: string;
+ readonly url: string;
+ };
+ readonly dryRun: boolean;
+ readonly total: number;
+ readonly imported: number;
+ readonly failed: number;
+ readonly unknownStatuses: ReadonlyArray<string>;
+ readonly remappedStatuses: ReadonlyArray<StatusRemap>;
+ readonly tasksWithLabels: number;
+ readonly tasks: ReadonlyArray<ImportTaskReport>;
+};
+
+export type ImportTarget = {
+ readonly id: string;
+ readonly slug: string;
+ readonly name: string;
+ readonly workspaceId: string;
+};
+
+function statusName(columns: ReadonlyArray<Column>, slug: string): string {
+ const column = columns.find((candidate) => candidate.slug === slug);
+ if (column) return column.name;
+ return slug === "archived" ? "Archived" : "Planned";
+}
+
+export function buildImportReport(input: {
+ readonly project: ImportTarget;
+ readonly columns: ReadonlyArray<Column>;
+ readonly webUrl: string;
+ readonly plan: ImportPlan;
+ readonly outcomes: ReadonlyArray<ImportOutcome> | null;
+}): ImportReportJson {
+ const { project, plan, outcomes } = input;
+ const tasks = plan.tasks.map((task, index): ImportTaskReport => {
+ const outcome = outcomes?.[index];
+ const id = outcome?.success ? (outcome.task.id ?? null) : null;
+ const status = outcome?.success
+ ? (outcome.task.status ?? task.status)
+ : task.status;
+ return {
+ index: index + 1,
+ title: task.title,
+ status,
+ statusName: statusName(input.columns, status),
+ imported: outcome === undefined ? null : outcome.success,
+ id,
+ ticketId:
+ outcome?.success && outcome.task.number !== undefined
+ ? ticketId(project.slug, outcome.task.number)
+ : null,
+ url: id
+ ? taskUrl(input.webUrl, {
+ workspaceId: project.workspaceId,
+ projectId: project.id,
+ id,
+ })
+ : null,
+ error:
+ outcome && !outcome.success
+ ? (outcome.error ?? "The server did not import this task.")
+ : null,
+ warnings: outcome?.warnings ?? [],
+ };
+ });
+ const imported = tasks.filter((task) => task.imported === true).length;
+ return {
+ project: {
+ id: project.id,
+ key: project.slug.toUpperCase(),
+ name: project.name,
+ url: projectUrl(input.webUrl, project),
+ },
+ dryRun: outcomes === null,
+ total: tasks.length,
+ imported,
+ failed: tasks.filter((task) => task.imported === false).length,
+ unknownStatuses: plan.unknown.map((entry) => entry.status),
+ remappedStatuses: plan.remapped,
+ tasksWithLabels: plan.withLabels,
+ tasks,
+ };
+}
diff --git a/packages/cli/src/transfer/parse-import-file.test.ts b/packages/cli/src/transfer/parse-import-file.test.ts
new file mode 100644
index 000000000..3ad70b956
--- /dev/null
+++ b/packages/cli/src/transfer/parse-import-file.test.ts
@@ -0,0 +1,72 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import { parseImportDocument } from "./parse-import-file.js";
+
+describe("parseImportDocument", () => {
+ it("reads the document written by kaneo task export", () => {
+ const content = JSON.stringify({
+ project: { name: "Kaneo Web", slug: "kan" },
+ tasks: [
+ {
+ title: "Fix login",
+ description: "",
+ status: "in-progress",
+ priority: "urgent",
+ dueDate: "2026-10-05T19:19:55.960Z",
+ startDate: null,
+ userId: null,
+ labels: [{ name: "Bug", color: "red" }],
+ },
+ ],
+ });
+ expect(
+ Result.getOrThrow(parseImportDocument(content, "tasks.json")),
+ ).toEqual([
+ {
+ title: "Fix login",
+ description: "",
+ status: "in-progress",
+ priority: "urgent",
+ dueDate: "2026-10-05T19:19:55.960Z",
+ startDate: null,
+ userId: null,
+ labels: 1,
+ },
+ ]);
+ });
+
+ it("accepts a bare list with only titles", () => {
+ expect(
+ Result.getOrThrow(parseImportDocument('[{"title":" Write docs "}]', "-")),
+ ).toEqual([
+ {
+ title: "Write docs",
+ description: undefined,
+ status: undefined,
+ priority: undefined,
+ startDate: undefined,
+ dueDate: undefined,
+ userId: undefined,
+ labels: 0,
+ },
+ ]);
+ });
+
+ it("explains what is wrong with the file", () => {
+ const message = (content: string) => {
+ const result = parseImportDocument(content, "tasks.json");
+ return Result.isFailure(result) ? result.failure.message : null;
+ };
+ expect(message("{")).toBe("tasks.json is not valid JSON.");
+ expect(message('{"items": []}')).toBe("tasks.json has no list of tasks.");
+ expect(message("[]")).toBe("tasks.json has no tasks to import.");
+ expect(message('[{"title":"a"}, 3]')).toBe("Task 2 is not an object.");
+ expect(message('[{"status":"done"}]')).toBe("Task 1 has no title.");
+ expect(message('[{"title":"a","status":3}]')).toBe(
+ "Task 1 (a) has a status that is not text.",
+ );
+ expect(message('[{"title":"a","dueDate":"soon"}]')).toBe(
+ 'Task 1 (a) has an invalid dueDate "soon".',
+ );
+ });
+});
diff --git a/packages/cli/src/transfer/parse-import-file.ts b/packages/cli/src/transfer/parse-import-file.ts
new file mode 100644
index 000000000..4e40f3488
--- /dev/null
+++ b/packages/cli/src/transfer/parse-import-file.ts
@@ -0,0 +1,128 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+
+export type ImportCandidate = {
+ readonly title: string;
+ readonly description?: string | undefined;
+ readonly status?: string | undefined;
+ readonly priority?: string | undefined;
+ readonly startDate?: string | null | undefined;
+ readonly dueDate?: string | null | undefined;
+ readonly userId?: string | null | undefined;
+ readonly labels: number;
+};
+
+const SHAPE_HINT =
+ "Use the output of kaneo task export, or a JSON array of tasks with at least a title.";
+
+type Fields = Readonly<Record<string, unknown>>;
+
+function isRecord(value: unknown): value is Fields {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function invalid(message: string): InvalidArgument {
+ return new InvalidArgument({ message, hint: SHAPE_HINT });
+}
+
+function readTasks(document: unknown): unknown[] | null {
+ if (Array.isArray(document)) return document;
+ if (isRecord(document) && Array.isArray(document.tasks)) {
+ return document.tasks;
+ }
+ return null;
+}
+
+function text(
+ fields: Fields,
+ key: string,
+ where: string,
+): Result.Result<string | undefined, InvalidArgument> {
+ const value = fields[key];
+ if (value === undefined || value === null) return Result.succeed(undefined);
+ return typeof value === "string"
+ ? Result.succeed(value)
+ : Result.fail(invalid(`${where} has a ${key} that is not text.`));
+}
+
+function nullableText(
+ fields: Fields,
+ key: string,
+ where: string,
+): Result.Result<string | null | undefined, InvalidArgument> {
+ if (fields[key] === null) return Result.succeed(null);
+ return text(fields, key, where);
+}
+
+function date(
+ fields: Fields,
+ key: string,
+ where: string,
+): Result.Result<string | null | undefined, InvalidArgument> {
+ return Result.flatMap(nullableText(fields, key, where), (value) => {
+ if (typeof value !== "string") return Result.succeed(value);
+ if (value.trim() === "") return Result.succeed(null);
+ return Number.isNaN(Date.parse(value))
+ ? Result.fail(invalid(`${where} has an invalid ${key} "${value}".`))
+ : Result.succeed(value);
+ });
+}
+
+function parseTask(
+ item: unknown,
+ index: number,
+): Result.Result<ImportCandidate, InvalidArgument> {
+ const where = `Task ${index + 1}`;
+ if (!isRecord(item)) {
+ return Result.fail(invalid(`${where} is not an object.`));
+ }
+ const title = typeof item.title === "string" ? item.title.trim() : "";
+ if (title === "") {
+ return Result.fail(invalid(`${where} has no title.`));
+ }
+ const named = `${where} (${title})`;
+ return Result.all({
+ description: text(item, "description", named),
+ status: text(item, "status", named),
+ priority: text(item, "priority", named),
+ startDate: date(item, "startDate", named),
+ dueDate: date(item, "dueDate", named),
+ userId: nullableText(item, "userId", named),
+ }).pipe(
+ Result.map((fields) => ({
+ title,
+ ...fields,
+ status: fields.status?.trim() || undefined,
+ priority: fields.priority?.trim() || undefined,
+ labels: Array.isArray(item.labels) ? item.labels.length : 0,
+ })),
+ );
+}
+
+export function parseImportDocument(
+ content: string,
+ source: string,
+): Result.Result<ImportCandidate[], InvalidArgument> {
+ let document: unknown;
+ try {
+ document = JSON.parse(content);
+ } catch {
+ return Result.fail(invalid(`${source} is not valid JSON.`));
+ }
+ const items = readTasks(document);
+ if (items === null) {
+ return Result.fail(invalid(`${source} has no list of tasks.`));
+ }
+ if (items.length === 0) {
+ return Result.fail(
+ new InvalidArgument({ message: `${source} has no tasks to import.` }),
+ );
+ }
+ const tasks: ImportCandidate[] = [];
+ for (const [index, item] of items.entries()) {
+ const parsed = parseTask(item, index);
+ if (Result.isFailure(parsed)) return Result.fail(parsed.failure);
+ tasks.push(parsed.success);
+ }
+ return Result.succeed(tasks);
+}
diff --git a/packages/cli/src/transfer/read-import-source.ts b/packages/cli/src/transfer/read-import-source.ts
new file mode 100644
index 000000000..24f9108b1
--- /dev/null
+++ b/packages/cli/src/transfer/read-import-source.ts
@@ -0,0 +1,32 @@
+import { readFile } from "node:fs/promises";
+import { Effect } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+import { stripByteOrderMark } from "../input/read-text-input.js";
+import { CliEnvironment } from "../services/cli-environment.js";
+import { readStream } from "../tasks/read-stdin.js";
+
+export const readImportSource = Effect.fnUntraced(function* (path: string) {
+ if (path !== "-") {
+ const content = yield* Effect.tryPromise({
+ try: () => readFile(path, "utf8"),
+ catch: () =>
+ new InvalidArgument({
+ message: `Could not read ${path}.`,
+ hint: "Check the path and that the file is readable.",
+ }),
+ });
+ return stripByteOrderMark(content);
+ }
+ const environment = yield* CliEnvironment;
+ if (environment.stdin.isTTY) {
+ return yield* new InvalidArgument({
+ message: "- reads the tasks from stdin, but nothing is piped in.",
+ hint: "Pipe the file in, for example: kaneo task export -p KAN | kaneo task import - -p MOB --yes",
+ });
+ }
+ const content = yield* Effect.tryPromise({
+ try: () => readStream(process.stdin),
+ catch: () => new InvalidArgument({ message: "Could not read from stdin." }),
+ });
+ return stripByteOrderMark(content);
+});
diff --git a/packages/cli/src/transfer/render-exported.test.ts b/packages/cli/src/transfer/render-exported.test.ts
new file mode 100644
index 000000000..b7e545fe2
--- /dev/null
+++ b/packages/cli/src/transfer/render-exported.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { renderExported } from "./render-exported.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+describe("renderExported", () => {
+ it("names the project, the count and the file", () => {
+ expect(
+ renderExported(ui, {
+ file: "kan.json",
+ tasks: 15,
+ project: { name: "Kaneo Web", key: "KAN", url: "https://kaneo.test/p" },
+ }),
+ ).toEqual([
+ "",
+ " ✓ Exported 15 tasks from Kaneo Web · KAN → kan.json",
+ "",
+ ]);
+ });
+});
diff --git a/packages/cli/src/transfer/render-exported.ts b/packages/cli/src/transfer/render-exported.ts
new file mode 100644
index 000000000..8082381fb
--- /dev/null
+++ b/packages/cli/src/transfer/render-exported.ts
@@ -0,0 +1,26 @@
+import { renderCell, text } from "../render/cell.js";
+import type { Ui } from "../render/ui.js";
+
+export type Exported = {
+ readonly file: string;
+ readonly tasks: number;
+ readonly project: {
+ readonly name: string;
+ readonly key: string;
+ readonly url: string;
+ };
+};
+
+export function renderExported(ui: Ui, exported: Exported): string[] {
+ const { theme, glyphs } = ui;
+ const count = exported.tasks === 1 ? "1 task" : `${exported.tasks} tasks`;
+ const project = renderCell(
+ [text(exported.project.name, theme.strong, exported.project.url)],
+ ui,
+ );
+ return [
+ "",
+ ` ${theme.success(glyphs.tick)} Exported ${count} from ${project} ${theme.muted(glyphs.separator)} ${exported.project.key} ${theme.muted(glyphs.arrow)} ${exported.file}`,
+ "",
+ ];
+}
diff --git a/packages/cli/src/transfer/render-import-report.test.ts b/packages/cli/src/transfer/render-import-report.test.ts
new file mode 100644
index 000000000..8ef0bde2b
--- /dev/null
+++ b/packages/cli/src/transfer/render-import-report.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { Column } from "../api/schemas.js";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import { planImport } from "./import-plan.js";
+import { buildImportReport } from "./import-report.js";
+import {
+ renderImportReport,
+ renderImportWarnings,
+} from "./render-import-report.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+const columns: Column[] = [
+ {
+ id: "c1",
+ projectId: "p1",
+ slug: "to-do",
+ name: "To Do",
+ position: 0,
+ color: null,
+ isFinal: false,
+ },
+];
+
+const project = { id: "p1", slug: "kan", name: "Kaneo Web", workspaceId: "w1" };
+
+const plan = planImport(
+ [
+ { title: "Fix login redirect", status: "To Do", labels: 2 },
+ { title: "Old idea", status: "backlog", labels: 0 },
+ ],
+ columns,
+);
+
+describe("renderImportWarnings", () => {
+ it("lists unknown statuses, matched statuses and dropped labels", () => {
+ const report = buildImportReport({
+ project,
+ columns,
+ webUrl: "https://kaneo.test",
+ plan,
+ outcomes: null,
+ });
+ expect(renderImportWarnings(ui, report)).toEqual([
+ " ▲ 1 task uses a status Kaneo Web does not have (backlog); it lands in Planned.",
+ " ● Statuses matched to columns: To Do → to-do",
+ " ▲ Labels are not imported; 1 task in the file has labels.",
+ ]);
+ });
+});
+
+describe("renderImportReport", () => {
+ it("shows a dry run at 80 columns", () => {
+ const lines = renderImportReport(
+ ui,
+ buildImportReport({
+ project,
+ columns,
+ webUrl: "https://kaneo.test",
+ plan,
+ outcomes: null,
+ }),
+ );
+ expect(lines).toEqual([
+ "",
+ " ● Dry run: 2 tasks would be imported into Kaneo Web · KAN",
+ "",
+ " ▲ 1 task uses a status Kaneo Web does not have (backlog); it lands in Planned.",
+ " ● Statuses matched to columns: To Do → to-do",
+ " ▲ Labels are not imported; 1 task in the file has labels.",
+ "",
+ " 1 To Do Fix login redirect",
+ " 2 Planned Old idea",
+ "",
+ " Nothing was imported. Run it again without --dry-run to import.",
+ "",
+ ]);
+ });
+
+ it("marks each imported and failed task", () => {
+ const lines = renderImportReport(
+ ui,
+ buildImportReport({
+ project,
+ columns,
+ webUrl: "https://kaneo.test",
+ plan,
+ outcomes: [
+ {
+ success: true,
+ task: {
+ id: "t1",
+ number: 7,
+ title: "Fix login redirect",
+ status: "to-do",
+ },
+ },
+ {
+ success: false,
+ error:
+ "Assignee is not a member of this workspace, and the rest of this long message",
+ task: { title: "Old idea" },
+ },
+ ],
+ }),
+ );
+ expect(lines[1]).toBe(
+ " ✗ Imported 1 of 2 tasks into Kaneo Web · KAN; 1 failed",
+ );
+ expect(lines[3]).toBe(" ✓ KAN-7 To Do Fix login redirect");
+ expect(lines[4]).toBe(
+ " ✗ Planned Old idea Assignee is not a member of this wor…",
+ );
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(80);
+ });
+});
diff --git a/packages/cli/src/transfer/render-import-report.ts b/packages/cli/src/transfer/render-import-report.ts
new file mode 100644
index 000000000..2e8de9f59
--- /dev/null
+++ b/packages/cli/src/transfer/render-import-report.ts
@@ -0,0 +1,121 @@
+import { type Cell, renderCell, text } from "../render/cell.js";
+import { type Column, renderTable } from "../render/table.js";
+import type { Ui } from "../render/ui.js";
+import type { ImportReportJson, ImportTaskReport } from "./import-report.js";
+
+function tasks(count: number): string {
+ return count === 1 ? "1 task" : `${count} tasks`;
+}
+
+function tasksDo(count: number, singular: string, plural: string): string {
+ return `${tasks(count)} ${count === 1 ? singular : plural}`;
+}
+
+export function renderImportWarnings(
+ ui: Ui,
+ report: ImportReportJson,
+): string[] {
+ const { theme, glyphs } = ui;
+ const lines: string[] = [];
+ const unknown = report.tasks.filter((task) =>
+ report.unknownStatuses.includes(task.status),
+ ).length;
+ if (report.unknownStatuses.length > 0) {
+ lines.push(
+ ` ${theme.warning(glyphs.warning)} ${tasksDo(unknown, "uses a status", "use statuses")} ${report.project.name} does not have (${report.unknownStatuses.join(", ")}); ${unknown === 1 ? "it lands" : "they land"} in Planned.`,
+ );
+ }
+ if (report.remappedStatuses.length > 0) {
+ lines.push(
+ ` ${theme.muted(glyphs.dot)} ${theme.muted(`Statuses matched to columns: ${report.remappedStatuses.map((remap) => `${remap.from} ${glyphs.arrow} ${remap.to}`).join(", ")}`)}`,
+ );
+ }
+ if (report.tasksWithLabels > 0) {
+ lines.push(
+ ` ${theme.warning(glyphs.warning)} Labels are not imported; ${tasksDo(report.tasksWithLabels, "in the file has", "in the file have")} labels.`,
+ );
+ }
+ return lines;
+}
+
+function noteCell(ui: Ui, task: ImportTaskReport): Cell {
+ if (task.error) return [text(task.error, ui.theme.danger)];
+ if (task.warnings.length > 0) {
+ return [text(task.warnings.join("; "), ui.theme.warning)];
+ }
+ return [];
+}
+
+function markCell(ui: Ui, task: ImportTaskReport): Cell {
+ if (task.imported === true) return [text(ui.glyphs.tick, ui.theme.success)];
+ if (task.imported === false) return [text(ui.glyphs.cross, ui.theme.danger)];
+ return [text(String(task.index), ui.theme.muted)];
+}
+
+export function renderImportReport(ui: Ui, report: ImportReportJson): string[] {
+ const { theme, glyphs } = ui;
+ const project = `${renderCell([text(report.project.name, theme.strong, report.project.url)], ui)} ${theme.muted(glyphs.separator)} ${report.project.key}`;
+ const headline = report.dryRun
+ ? ` ${theme.muted(glyphs.dot)} Dry run: ${tasks(report.total)} would be imported into ${project}`
+ : report.failed === 0
+ ? ` ${theme.success(glyphs.tick)} Imported ${tasks(report.imported)} into ${project}`
+ : ` ${theme.danger(glyphs.cross)} Imported ${report.imported} of ${tasks(report.total)} into ${project}; ${report.failed} failed`;
+ const warnings = report.dryRun ? renderImportWarnings(ui, report) : [];
+ const withIds = report.tasks.some((task) => task.ticketId !== null);
+ const idColumn: Column<ImportTaskReport> = {
+ header: "ID",
+ optional: true,
+ cell: (task): Cell =>
+ task.ticketId
+ ? [text(task.ticketId, theme.muted, task.url ?? undefined)]
+ : [],
+ };
+ const table = renderTable(
+ ui,
+ report.tasks,
+ [
+ {
+ header: "",
+ align: "right",
+ cell: (task): Cell => markCell(ui, task),
+ },
+ ...(withIds ? [idColumn] : []),
+ {
+ header: "Status",
+ optional: true,
+ minWidth: 6,
+ cell: (task): Cell => [text(task.statusName, theme.muted)],
+ },
+ {
+ header: "Title",
+ flex: true,
+ minWidth: 24,
+ cell: (task): Cell => [
+ text(task.title, undefined, task.url ?? undefined),
+ ],
+ },
+ {
+ header: "Note",
+ flex: true,
+ optional: true,
+ minWidth: 12,
+ cell: (task): Cell => noteCell(ui, task),
+ },
+ ],
+ { width: ui.caps.columns, indent: 4, gap: 2 },
+ );
+ return [
+ "",
+ headline,
+ ...(warnings.length > 0 ? ["", ...warnings] : []),
+ "",
+ ...table,
+ "",
+ ...(report.dryRun
+ ? [
+ ` ${theme.muted("Nothing was imported. Run it again without --dry-run to import.")}`,
+ "",
+ ]
+ : []),
+ ];
+}
diff --git a/packages/cli/src/workflow/events.test.ts b/packages/cli/src/workflow/events.test.ts
new file mode 100644
index 000000000..1a2ae61c5
--- /dev/null
+++ b/packages/cli/src/workflow/events.test.ts
@@ -0,0 +1,61 @@
+import { Result } from "effect";
+import { describe, expect, it } from "vite-plus/test";
+import {
+ eventLabel,
+ integrationLabel,
+ parseIntegration,
+ parseWorkflowEvent,
+} from "./events.js";
+
+describe("parseWorkflowEvent", () => {
+ it("accepts the API name with hyphens, spaces or any case", () => {
+ expect(parseWorkflowEvent("pr_merged")).toEqual(
+ Result.succeed("pr_merged"),
+ );
+ expect(parseWorkflowEvent("PR-Merged")).toEqual(
+ Result.succeed("pr_merged"),
+ );
+ expect(parseWorkflowEvent("issue closed")).toEqual(
+ Result.succeed("issue_closed"),
+ );
+ });
+
+ it("accepts the readable label and a few aliases", () => {
+ expect(parseWorkflowEvent("Pull request opened")).toEqual(
+ Result.succeed("pr_opened"),
+ );
+ expect(parseWorkflowEvent("push")).toEqual(Result.succeed("branch_push"));
+ expect(parseWorkflowEvent("mr-merged")).toEqual(
+ Result.succeed("pr_merged"),
+ );
+ });
+
+ it("lists the events when nothing matches", () => {
+ const result = parseWorkflowEvent("deploy");
+ expect(Result.isFailure(result) && result.failure.hint).toBe(
+ "Use one of: branch_push, pr_opened, pr_merged, issue_opened, issue_closed, issue_reopened.",
+ );
+ });
+});
+
+describe("parseIntegration", () => {
+ it("accepts the three git providers", () => {
+ expect(parseIntegration("GitHub")).toEqual(Result.succeed("github"));
+ expect(parseIntegration(" gitlab ")).toEqual(Result.succeed("gitlab"));
+ });
+
+ it("refuses other integrations", () => {
+ const result = parseIntegration("slack");
+ expect(Result.isFailure(result) && result.failure.hint).toBe(
+ "Use github, gitlab or gitea.",
+ );
+ });
+});
+
+describe("labels", () => {
+ it("names known values and passes unknown ones through", () => {
+ expect(integrationLabel("gitea")).toBe("Gitea");
+ expect(eventLabel("branch_push")).toBe("Branch pushed");
+ expect(eventLabel("custom_event")).toBe("custom_event");
+ });
+});
diff --git a/packages/cli/src/workflow/events.ts b/packages/cli/src/workflow/events.ts
new file mode 100644
index 000000000..de9d5a102
--- /dev/null
+++ b/packages/cli/src/workflow/events.ts
@@ -0,0 +1,89 @@
+import { Result } from "effect";
+import { InvalidArgument } from "../errors/errors.js";
+
+export const INTEGRATIONS = ["github", "gitlab", "gitea"] as const;
+export type Integration = (typeof INTEGRATIONS)[number];
+
+export const INTEGRATION_LABELS: Readonly<Record<Integration, string>> = {
+ github: "GitHub",
+ gitlab: "GitLab",
+ gitea: "Gitea",
+};
+
+export const EVENTS = [
+ "branch_push",
+ "pr_opened",
+ "pr_merged",
+ "issue_opened",
+ "issue_closed",
+ "issue_reopened",
+] as const;
+export type WorkflowEvent = (typeof EVENTS)[number];
+
+export const EVENT_LABELS: Readonly<Record<WorkflowEvent, string>> = {
+ branch_push: "Branch pushed",
+ pr_opened: "Pull request opened",
+ pr_merged: "Pull request merged",
+ issue_opened: "Issue opened",
+ issue_closed: "Issue closed",
+ issue_reopened: "Issue reopened",
+};
+
+const EVENT_ALIASES: Readonly<Record<string, WorkflowEvent>> = {
+ push: "branch_push",
+ mr_opened: "pr_opened",
+ mr_merged: "pr_merged",
+};
+
+function key(value: string): string {
+ return value
+ .trim()
+ .toLowerCase()
+ .replace(/[\s-]+/g, "_");
+}
+
+export function isIntegration(value: string): value is Integration {
+ return (INTEGRATIONS as ReadonlyArray<string>).includes(value);
+}
+
+export function isWorkflowEvent(value: string): value is WorkflowEvent {
+ return (EVENTS as ReadonlyArray<string>).includes(value);
+}
+
+export function integrationLabel(value: string): string {
+ return isIntegration(value) ? INTEGRATION_LABELS[value] : value;
+}
+
+export function eventLabel(value: string): string {
+ return isWorkflowEvent(value) ? EVENT_LABELS[value] : value;
+}
+
+export function parseIntegration(
+ input: string,
+): Result.Result<Integration, InvalidArgument> {
+ const value = key(input);
+ if (isIntegration(value)) return Result.succeed(value);
+ return Result.fail(
+ new InvalidArgument({
+ message: `"${input.trim()}" is not an integration with workflow rules.`,
+ hint: "Use github, gitlab or gitea.",
+ }),
+ );
+}
+
+export function parseWorkflowEvent(
+ input: string,
+): Result.Result<WorkflowEvent, InvalidArgument> {
+ const value = key(input);
+ if (isWorkflowEvent(value)) return Result.succeed(value);
+ const alias = EVENT_ALIASES[value];
+ if (alias) return Result.succeed(alias);
+ const byLabel = EVENTS.find((event) => key(EVENT_LABELS[event]) === value);
+ if (byLabel) return Result.succeed(byLabel);
+ return Result.fail(
+ new InvalidArgument({
+ message: `"${input.trim()}" is not a workflow event.`,
+ hint: `Use one of: ${EVENTS.join(", ")}.`,
+ }),
+ );
+}
diff --git a/packages/cli/src/workflow/match-rule.test.ts b/packages/cli/src/workflow/match-rule.test.ts
new file mode 100644
index 000000000..9fa3e27c7
--- /dev/null
+++ b/packages/cli/src/workflow/match-rule.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from "vite-plus/test";
+import { matchRule } from "./match-rule.js";
+import type { RuleJson } from "./rule-json.js";
+
+function rule(id: string, integration: string, event: string): RuleJson {
+ return {
+ id,
+ integration,
+ event,
+ column: { id: "col_done", name: "Done", slug: "done" },
+ };
+}
+
+const githubMerged = rule("r1", "github", "pr_merged");
+const gitlabMerged = rule("r2", "gitlab", "pr_merged");
+const githubPush = rule("r3", "github", "branch_push");
+const rules = [githubMerged, gitlabMerged, githubPush];
+
+describe("matchRule", () => {
+ it("finds a rule by id", () => {
+ expect(matchRule(rules, { id: "r2" })).toEqual({
+ kind: "found",
+ rule: gitlabMerged,
+ });
+ });
+
+ it("finds the only rule for an event", () => {
+ expect(matchRule(rules, { event: "branch_push" })).toEqual({
+ kind: "found",
+ rule: githubPush,
+ });
+ });
+
+ it("asks for the integration when an event has several rules", () => {
+ expect(matchRule(rules, { event: "pr_merged" })).toEqual({
+ kind: "ambiguous",
+ rules: [githubMerged, gitlabMerged],
+ });
+ expect(
+ matchRule(rules, { event: "pr_merged", integration: "gitlab" }),
+ ).toEqual({ kind: "found", rule: gitlabMerged });
+ });
+
+ it("reports when nothing matches", () => {
+ expect(matchRule(rules, { event: "issue_closed" })).toEqual({
+ kind: "none",
+ });
+ expect(matchRule(rules, { id: "nope" })).toEqual({ kind: "none" });
+ });
+});
diff --git a/packages/cli/src/workflow/match-rule.ts b/packages/cli/src/workflow/match-rule.ts
new file mode 100644
index 000000000..b924deebe
--- /dev/null
+++ b/packages/cli/src/workflow/match-rule.ts
@@ -0,0 +1,31 @@
+import type { RuleJson } from "./rule-json.js";
+
+export type RuleMatch =
+ | { readonly kind: "found"; readonly rule: RuleJson }
+ | { readonly kind: "ambiguous"; readonly rules: ReadonlyArray<RuleJson> }
+ | { readonly kind: "none" };
+
+export function matchRule(
+ rules: ReadonlyArray<RuleJson>,
+ target: {
+ readonly id?: string;
+ readonly event?: string;
+ readonly integration?: string;
+ },
+): RuleMatch {
+ const byId = target.id
+ ? rules.find((rule) => rule.id === target.id)
+ : undefined;
+ if (byId) return { kind: "found", rule: byId };
+ if (!target.event) return { kind: "none" };
+ const matches = rules.filter(
+ (rule) =>
+ rule.event === target.event &&
+ (!target.integration || rule.integration === target.integration),
+ );
+ const [first] = matches;
+ if (!first) return { kind: "none" };
+ return matches.length === 1
+ ? { kind: "found", rule: first }
+ : { kind: "ambiguous", rules: matches };
+}
diff --git a/packages/cli/src/workflow/render-rules.test.ts b/packages/cli/src/workflow/render-rules.test.ts
new file mode 100644
index 000000000..69ddb2a9d
--- /dev/null
+++ b/packages/cli/src/workflow/render-rules.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, it } from "vite-plus/test";
+import { makeUi } from "../render/ui.js";
+import { stringWidth } from "../render/width.js";
+import { renderRuleChange, renderRuleList } from "./render-rules.js";
+import type { RuleJson } from "./rule-json.js";
+
+const ui = makeUi({
+ color: 0,
+ unicode: true,
+ hyperlinks: false,
+ animate: false,
+ columns: 80,
+});
+
+const merged: RuleJson = {
+ id: "r1",
+ integration: "github",
+ event: "pr_merged",
+ column: { id: "col_done", name: "Done", slug: "done" },
+};
+
+const opened: RuleJson = {
+ id: "r2",
+ integration: "gitlab",
+ event: "pr_opened",
+ column: { id: "col_review", name: "In review", slug: "in-review" },
+};
+
+describe("renderRuleList", () => {
+ it("shows integration, event, column and key in 80 columns", () => {
+ const lines = renderRuleList(ui, {
+ projectName: "Kaneo Web",
+ rules: [merged, opened],
+ });
+ expect(lines).toEqual([
+ "",
+ " GitHub Pull request merged → ● Done github pr_merged",
+ " GitLab Pull request opened → ● In review gitlab pr_opened",
+ "",
+ ]);
+ for (const line of lines) expect(stringWidth(line)).toBeLessThanOrEqual(80);
+ });
+
+ it("flags a rule whose column is gone", () => {
+ const lines = renderRuleList(ui, {
+ projectName: "Kaneo Web",
+ rules: [{ ...merged, column: { id: "col_x", name: null, slug: null } }],
+ });
+ expect(lines[1]).toContain("missing column");
+ });
+
+ it("explains the defaults when there are no rules", () => {
+ expect(renderRuleList(ui, { projectName: "Kaneo Web", rules: [] })).toEqual(
+ [
+ "",
+ " No workflow rules in Kaneo Web. Integrations use their default columns.",
+ " Add one with kaneo workflow set github pr_merged done.",
+ "",
+ ],
+ );
+ });
+});
+
+describe("renderRuleChange", () => {
+ it("describes a new or changed rule", () => {
+ expect(renderRuleChange(ui, { verb: "Set", rule: merged })).toEqual([
+ "",
+ " ✓ GitHub pull request merged → moves tasks to Done",
+ "",
+ ]);
+ });
+
+ it("describes a deleted rule", () => {
+ expect(renderRuleChange(ui, { verb: "Deleted", rule: opened })).toEqual([
+ "",
+ " ✓ Deleted the rule GitLab pull request opened · was In review",
+ "",
+ ]);
+ });
+});
diff --git a/packages/cli/src/workflow/render-rules.ts b/packages/cli/src/workflow/render-rules.ts
new file mode 100644
index 000000000..86bbd031d
--- /dev/null
+++ b/packages/cli/src/workflow/render-rules.ts
@@ -0,0 +1,90 @@
+import { type Cell, text } from "../render/cell.js";
+import { renderTable } from "../render/table.js";
+import { statusDot } from "../render/task-format.js";
+import type { Ui } from "../render/ui.js";
+import { eventLabel, integrationLabel } from "./events.js";
+import type { RuleJson } from "./rule-json.js";
+
+function columnCell(ui: Ui, rule: RuleJson): Cell {
+ if (!rule.column.name) {
+ return [text("missing column", ui.theme.danger)];
+ }
+ return [
+ statusDot(ui, rule.column.slug ?? "", false),
+ text(` ${rule.column.name}`),
+ ];
+}
+
+export function renderRuleList(
+ ui: Ui,
+ view: {
+ readonly projectName: string;
+ readonly rules: ReadonlyArray<RuleJson>;
+ },
+): string[] {
+ const { theme, glyphs } = ui;
+ if (view.rules.length === 0) {
+ return [
+ "",
+ ` ${theme.muted(`No workflow rules in ${view.projectName}. Integrations use their default columns.`)}`,
+ ` ${theme.muted("Add one with kaneo workflow set github pr_merged done.")}`,
+ "",
+ ];
+ }
+ return [
+ "",
+ ...renderTable(
+ ui,
+ view.rules,
+ [
+ {
+ header: "Integration",
+ cell: (rule): Cell => [
+ text(integrationLabel(rule.integration), theme.strong),
+ ],
+ },
+ {
+ header: "Event",
+ flex: true,
+ minWidth: 12,
+ cell: (rule): Cell => [text(eventLabel(rule.event))],
+ },
+ {
+ header: "",
+ cell: (): Cell => [text(glyphs.arrow, theme.muted)],
+ },
+ {
+ header: "Column",
+ flex: true,
+ minWidth: 8,
+ cell: (rule): Cell => columnCell(ui, rule),
+ },
+ {
+ header: "Key",
+ optional: true,
+ cell: (rule): Cell => [
+ text(`${rule.integration} ${rule.event}`, theme.muted),
+ ],
+ },
+ ],
+ { width: ui.caps.columns, indent: 2 },
+ ),
+ "",
+ ];
+}
+
+export function renderRuleChange(
+ ui: Ui,
+ change: { readonly verb: "Set" | "Deleted"; readonly rule: RuleJson },
+): string[] {
+ const { theme, glyphs } = ui;
+ const name = `${integrationLabel(change.rule.integration)} ${eventLabel(change.rule.event).toLowerCase()}`;
+ const column = change.rule.column.name ?? change.rule.column.id;
+ return [
+ "",
+ change.verb === "Set"
+ ? ` ${theme.success(glyphs.tick)} ${theme.strong(name)} ${theme.muted(glyphs.arrow)} moves tasks to ${theme.strong(column)}`
+ : ` ${theme.success(glyphs.tick)} Deleted the rule ${theme.strong(name)} ${theme.muted(`${glyphs.separator} was ${column}`)}`,
+ "",
+ ];
+}
diff --git a/packages/cli/src/workflow/rule-json.ts b/packages/cli/src/workflow/rule-json.ts
new file mode 100644
index 000000000..228e6a386
--- /dev/null
+++ b/packages/cli/src/workflow/rule-json.ts
@@ -0,0 +1,21 @@
+import type { WorkflowRule } from "../api/workflow-rules.js";
+
+export type RuleJson = {
+ readonly id: string;
+ readonly integration: string;
+ readonly event: string;
+ readonly column: {
+ readonly id: string;
+ readonly name: string | null;
+ readonly slug: string | null;
+ };
+};
+
+export function toRuleJson(rule: WorkflowRule): RuleJson {
+ return {
+ id: rule.id,
+ integration: rule.integrationType,
+ event: rule.eventType,
+ column: { id: rule.columnId, name: rule.columnName, slug: rule.columnSlug },
+ };
+}
diff --git a/packages/cli/src/workflow/sort-rules.ts b/packages/cli/src/workflow/sort-rules.ts
new file mode 100644
index 000000000..06dff1afe
--- /dev/null
+++ b/packages/cli/src/workflow/sort-rules.ts
@@ -0,0 +1,16 @@
+import { EVENTS, INTEGRATIONS } from "./events.js";
+import type { RuleJson } from "./rule-json.js";
+
+function rank(list: ReadonlyArray<string>, value: string): number {
+ const index = list.indexOf(value);
+ return index === -1 ? list.length : index;
+}
+
+export function sortRules(rules: ReadonlyArray<RuleJson>): RuleJson[] {
+ return [...rules].sort(
+ (a, b) =>
+ rank(INTEGRATIONS, a.integration) - rank(INTEGRATIONS, b.integration) ||
+ rank(EVENTS, a.event) - rank(EVENTS, b.event) ||
+ a.id.localeCompare(b.id),
+ );
+}
diff --git a/packages/cli/tsconfig.json b/packages/cli/tsconfig.json
new file mode 100644
index 000000000..522708597
--- /dev/null
+++ b/packages/cli/tsconfig.json
@@ -0,0 +1,10 @@
+{
+ "extends": "../typescript-config/base.json",
+ "compilerOptions": {
+ "noEmit": true,
+ "declaration": false,
+ "declarationMap": false,
+ "types": ["node"]
+ },
+ "include": ["src/**/*.ts", "vite.config.ts", "vitest.config.ts"]
+}
diff --git a/packages/cli/vite.config.ts b/packages/cli/vite.config.ts
new file mode 100644
index 000000000..b9e0e07c7
--- /dev/null
+++ b/packages/cli/vite.config.ts
@@ -0,0 +1,55 @@
+import { defineConfig } from "vite-plus";
+
+export default defineConfig({
+ pack: {
+ entry: { kaneo: "src/bin.ts" },
+ format: "esm",
+ platform: "node",
+ target: "node20",
+ outDir: "dist",
+ clean: true,
+ dts: false,
+ fixedExtension: true,
+ minify: true,
+ report: false,
+ deps: {
+ onlyBundle: [
+ "effect",
+ "@effect/platform-node",
+ "@effect/platform-node-shared",
+ "@kaneo/mcp",
+ "@gabrielbryk/jq-ts",
+ "pngjs",
+ "jpeg-js",
+ ],
+ },
+ },
+ run: {
+ tasks: {
+ compile: {
+ command: "vp pack",
+ dependsOn: [
+ { task: "build", from: ["dependencies", "devDependencies"] },
+ ],
+ cache: {
+ input: [{ auto: true }, "src/**", "tsconfig.json", "package.json"],
+ output: ["dist/**"],
+ },
+ },
+ "check:types": {
+ command: "tsc -p tsconfig.json",
+ dependsOn: [
+ { task: "build", from: ["dependencies", "devDependencies"] },
+ ],
+ cache: false,
+ },
+ "test:run": {
+ command: "vp test run --config vitest.config.ts",
+ dependsOn: [
+ { task: "build", from: ["dependencies", "devDependencies"] },
+ ],
+ cache: false,
+ },
+ },
+ },
+});
diff --git a/packages/cli/vitest.config.ts b/packages/cli/vitest.config.ts
new file mode 100644
index 000000000..685015850
--- /dev/null
+++ b/packages/cli/vitest.config.ts
@@ -0,0 +1,9 @@
+import { defineConfig } from "vite-plus";
+
+export default defineConfig({
+ test: {
+ globals: false,
+ environment: "node",
+ include: ["src/**/*.test.ts"],
+ },
+});
diff --git a/packages/mcp/package.json b/packages/mcp/package.json
index 089f89780..f860ffee6 100644
--- a/packages/mcp/package.json
+++ b/packages/mcp/package.json
@@ -23,6 +23,14 @@
"./tools": {
"types": "./dist/tools/register.d.ts",
"import": "./dist/tools/register.js"
+ },
+ "./device-flow": {
+ "types": "./dist/auth/device-flow.d.ts",
+ "import": "./dist/auth/device-flow.js"
+ },
+ "./normalize-base-url": {
+ "types": "./dist/utils/normalize-base-url.d.ts",
+ "import": "./dist/utils/normalize-base-url.js"
}
},
"publishConfig": {
diff --git a/packages/mcp/src/auth/device-flow.test.ts b/packages/mcp/src/auth/device-flow.test.ts
index 1d550514c..2027f651e 100644
--- a/packages/mcp/src/auth/device-flow.test.ts
+++ b/packages/mcp/src/auth/device-flow.test.ts
@@ -6,7 +6,12 @@ import {
it,
vi,
} from "vite-plus/test";
-import { pollDeviceAccessToken, requestDeviceCode } from "./device-flow.js";
+import {
+ DeviceCodeRequestError,
+ pollDeviceAccessToken,
+ pollDeviceTokenOnce,
+ requestDeviceCode,
+} from "./device-flow.js";
describe("requestDeviceCode", () => {
const originalFetch = globalThis.fetch;
@@ -47,6 +52,27 @@ describe("requestDeviceCode", () => {
);
});
+ it("throws a typed error with the OAuth error code when the client is rejected", async () => {
+ globalThis.fetch = vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ error: "invalid_client",
+ error_description: "Invalid client ID",
+ }),
+ { status: 400 },
+ ),
+ ) as typeof fetch;
+
+ const failure = await requestDeviceCode(
+ "https://api.example.com",
+ "kaneo-cli",
+ ).catch((error: unknown) => error);
+
+ expect(failure).toBeInstanceOf(DeviceCodeRequestError);
+ expect(failure).toMatchObject({ status: 400, error: "invalid_client" });
+ expect((failure as Error).message).toMatch(/device\/code failed \(400\)/);
+ });
+
it("throws when the response body is missing the device code", async () => {
globalThis.fetch = vi.fn().mockResolvedValue(
new Response(JSON.stringify({ user_code: "missing-device-code" }), {
@@ -60,6 +86,51 @@ describe("requestDeviceCode", () => {
});
});
+describe("pollDeviceTokenOnce", () => {
+ const originalFetch = globalThis.fetch;
+
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ });
+
+ function respondWith(body: unknown, status: number) {
+ globalThis.fetch = vi
+ .fn()
+ .mockResolvedValue(
+ new Response(JSON.stringify(body), { status }),
+ ) as typeof fetch;
+ }
+
+ it("returns the access token once approved", async () => {
+ respondWith({ access_token: "token-123" }, 200);
+
+ await expect(
+ pollDeviceTokenOnce("https://api.example.com", "kaneo-cli", "device"),
+ ).resolves.toEqual({ status: "approved", accessToken: "token-123" });
+ });
+
+ it.each([
+ ["authorization_pending", "pending"],
+ ["slow_down", "slow_down"],
+ ["access_denied", "denied"],
+ ["expired_token", "expired"],
+ ])("maps %s to %s", async (error, status) => {
+ respondWith({ error }, 400);
+
+ await expect(
+ pollDeviceTokenOnce("https://api.example.com", "kaneo-cli", "device"),
+ ).resolves.toEqual({ status });
+ });
+
+ it("throws on an unknown error", async () => {
+ respondWith({ error: "invalid_grant" }, 400);
+
+ await expect(
+ pollDeviceTokenOnce("https://api.example.com", "kaneo-cli", "device"),
+ ).rejects.toThrow(/device\/token failed \(400\)/);
+ });
+});
+
describe("pollDeviceAccessToken", () => {
const originalFetch = globalThis.fetch;
diff --git a/packages/mcp/src/auth/device-flow.ts b/packages/mcp/src/auth/device-flow.ts
index 766273488..e2067aa22 100644
--- a/packages/mcp/src/auth/device-flow.ts
+++ b/packages/mcp/src/auth/device-flow.ts
@@ -12,6 +12,18 @@ export type DeviceTokenErrorBody = {
error_description?: string;
};
+export class DeviceCodeRequestError extends Error {
+ readonly status: number;
+ readonly error: string | undefined;
+
+ constructor(status: number, body: Record<string, unknown>) {
+ super(`device/code failed (${status}): ${JSON.stringify(body)}`);
+ this.name = "DeviceCodeRequestError";
+ this.status = status;
+ this.error = typeof body.error === "string" ? body.error : undefined;
+ }
+}
+
const REQUEST_TIMEOUT_MS = 10_000;
function sleep(ms: number): Promise<void> {
@@ -67,9 +79,7 @@ export async function requestDeviceCode(
}
const body = parsedBody;
if (!res.ok) {
- throw new Error(
- `device/code failed (${res.status}): ${JSON.stringify(body)}`,
- );
+ throw new DeviceCodeRequestError(res.status, body);
}
if (typeof body.device_code !== "string") {
throw new Error(`device/code: unexpected response ${JSON.stringify(body)}`);
@@ -109,6 +119,59 @@ function toFiniteNumber(v: unknown): number | undefined {
return undefined;
}
+export type DeviceTokenPoll =
+ | { status: "approved"; accessToken: string }
+ | { status: "pending" }
+ | { status: "slow_down" }
+ | { status: "denied" }
+ | { status: "expired" };
+
+export async function pollDeviceTokenOnce(
+ baseUrl: string,
+ clientId: string,
+ deviceCode: string,
+): Promise<DeviceTokenPoll> {
+ const res = await fetchWithTimeout(`${baseUrl}/api/auth/device/token`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
+ device_code: deviceCode,
+ client_id: clientId,
+ }),
+ });
+
+ const parsedBody: unknown = await res.json().catch(() => ({}));
+ if (!isObjectRecord(parsedBody)) {
+ throw new Error(
+ `device/token failed (${res.status}): ${JSON.stringify(parsedBody)}`,
+ );
+ }
+ const body = parsedBody;
+
+ if (res.ok && typeof body.access_token === "string") {
+ return { status: "approved", accessToken: body.access_token };
+ }
+
+ const err = typeof body.error === "string" ? body.error : undefined;
+ if (err === "authorization_pending") {
+ return { status: "pending" };
+ }
+ if (err === "slow_down") {
+ return { status: "slow_down" };
+ }
+ if (err === "access_denied") {
+ return { status: "denied" };
+ }
+ if (err === "expired_token") {
+ return { status: "expired" };
+ }
+
+ throw new Error(
+ `device/token failed (${res.status}): ${JSON.stringify(body)}`,
+ );
+}
+
/**
* Polls `/api/auth/device/token` until success or terminal error.
* First attempt is immediate; subsequent attempts wait `interval` seconds (increased on `slow_down`).
@@ -133,17 +196,9 @@ export async function pollDeviceAccessToken(
}
}
- let res: Response;
+ let poll: DeviceTokenPoll;
try {
- res = await fetchWithTimeout(`${baseUrl}/api/auth/device/token`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
- device_code: deviceCode,
- client_id: clientId,
- }),
- });
+ poll = await pollDeviceTokenOnce(baseUrl, clientId, deviceCode);
} catch (err) {
if (isAbortError(err)) {
log("Device token poll request timed out; retrying.");
@@ -156,38 +211,22 @@ export async function pollDeviceAccessToken(
throw new Error("Device authorization timed out waiting for approval.");
}
- const parsedBody: unknown = await res.json().catch(() => ({}));
- if (!isObjectRecord(parsedBody)) {
- throw new Error(
- `device/token failed (${res.status}): ${JSON.stringify(parsedBody)}`,
- );
- }
- const body = parsedBody;
-
- if (res.ok && typeof body.access_token === "string") {
- return body.access_token;
+ if (poll.status === "approved") {
+ return poll.accessToken;
}
-
- const err = typeof body.error === "string" ? body.error : undefined;
- if (err === "authorization_pending") {
+ if (poll.status === "pending") {
log("Waiting for device approval…");
continue;
}
- if (err === "slow_down") {
+ if (poll.status === "slow_down") {
intervalMs += 5000;
log(`Rate limited (slow_down); polling every ${intervalMs / 1000}s`);
continue;
}
- if (err === "access_denied") {
+ if (poll.status === "denied") {
throw new Error("Device authorization was denied.");
}
- if (err === "expired_token") {
- throw new Error("Device code expired; start login again.");
- }
-
- throw new Error(
- `device/token failed (${res.status}): ${JSON.stringify(body)}`,
- );
+ throw new Error("Device code expired; start login again.");
}
throw new Error("Device authorization timed out waiting for approval.");
diff --git a/packages/mcp/vite.config.ts b/packages/mcp/vite.config.ts
index f42b17cb3..aeaa2a4e2 100644
--- a/packages/mcp/vite.config.ts
+++ b/packages/mcp/vite.config.ts
@@ -11,6 +11,8 @@ export default defineConfig({
cache: {
input: [
{ auto: true },
+ "src/**",
+ "tsconfig.json",
".env*",
{ pattern: ".env*", base: "workspace" },
],
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d0c8cb9fb..dd191ec07 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -32,7 +32,7 @@ overrides:
minimatch: 10.2.3
rollup: 4.59.0
seroval: '>=1.5.3'
- effect: '>=3.20.0'
+ effect@<4.0.0-0: '>=3.20.0'
fast-xml-parser: '>=5.5.7'
socket.io-parser: '>=4.2.7'
picomatch: '>=4.0.4'
@@ -105,7 +105,7 @@ importers:
version: 7.0.2
vite-plus:
specifier: 'catalog:'
apps/api:
dependencies:
@@ -223,7 +223,7 @@ importers:
vitest:
specifier: 'catalog:'
apps/site:
dependencies:
@@ -332,7 +332,7 @@ importers:
version: 5.3.0
'@hookform/resolvers':
specifier: ^5.9.1
'@radix-ui/react-accordion':
specifier: ^1.2.20
@@ -631,6 +631,45 @@ importers:
vite:
specifier: 'catalog:'
+ vite-plus:
+ specifier: 'catalog:'
+
+ packages/cli:
+ devDependencies:
+ '@effect/platform-node':
+ specifier: 4.0.2
+ version: 4.0.2([email protected])([email protected](@opentelemetry/[email protected]))
+ '@gabrielbryk/jq-ts':
+ specifier: ^1.7.0
+ version: 1.7.0([email protected])
+ '@kaneo/mcp':
+ specifier: workspace:*
+ version: link:../mcp
+ '@kaneo/typescript-config':
+ specifier: workspace:*
+ version: link:../typescript-config
+ '@types/node':
+ specifier: ^26.6.2
+ version: 26.6.3
+ '@types/pngjs':
+ specifier: ^6.0.5
+ version: 6.0.5
+ effect:
+ specifier: 4.0.2
+ version: 4.0.2
+ jpeg-js:
+ specifier: ^0.4.4
+ version: 0.4.4
+ pngjs:
+ specifier: ^7.0.0
+ version: 7.0.0
+ tsx:
+ specifier: ^4.23.15
+ version: 4.23.15
+ typescript:
+ specifier: ^7.0.2
+ version: 7.0.2
vite-plus:
specifier: 'catalog:'
@@ -703,7 +742,7 @@ importers:
vite-plus:
specifier: 'catalog:'
packages/mcp:
dependencies:
@@ -756,7 +795,7 @@ importers:
vite-plus:
specifier: 'catalog:'
packages/planka-import:
dependencies:
@@ -1362,6 +1401,19 @@ packages:
peerDependencies:
'@noble/ciphers': ^1.0.0
+ '@effect/[email protected]':
+ resolution: {integrity: sha512-xn8aDw9p/QUPt1Yi0C3HUMcycT+MjHfAe19FDUDrUuzcwq0xxskkamVSqbdykF/Dsuus4aZTsCBZA/vkhHIfbQ==}
+ engines: {node: '>=18.0.0'}
+ peerDependencies:
+ effect: ^4.0.2
+
+ '@effect/[email protected]':
+ resolution: {integrity: sha512-RWesXBQStnFHdD465gR5thFKgXO7FSyCKRZ56nWXB7PedNVzr8vV0nb/3MULLdri493sMz/b/pmGBTb6K8cBjQ==}
+ engines: {node: '>=18.0.0'}
+ peerDependencies:
+ effect: ^4.0.2
+ redis: '>=5.0.0 <7.0.0'
+
'@electric-sql/[email protected]':
resolution: {integrity: sha512-J5nLGsicnD9wJHnno9r+DGxfcZWh+YJMCe0q/aCgtG6XOm9Z7fKeite8IZSNXgZeGltSigM9U/vAWZQWdgcSFg==}
hasBin: true
@@ -1573,6 +1625,12 @@ packages:
'@fontsource-variable/[email protected]':
resolution: {integrity: sha512-j0m+vLQuG5XAYoHtGCVu0spvlGreR3EzpECUVzkFmI1mTVnAO38l/NEPDCFgZ177JxzYJCLSmTQibIiYPilGrA==}
+ '@gabrielbryk/[email protected]':
+ resolution: {integrity: sha512-zGi4yjqLP0XvXRJs/OfQ/EKAk4vJDnV7pq0DMbaiQg3Vfy6LA2tECEiU7STaRH6TbUdAzJZYpldpb0kwsnvCcg==}
+ engines: {node: '>=20'}
+ peerDependencies:
+ typescript: ^5.0.0
+
resolution: {integrity: sha512-eWpQYr67tqJLeaSUl0Q+TquuYfUdTibpOJlUMV2FfUP7+KqCC5TufnwnlXL6mobZBJbGAYRd7ZvEBDCbLInjhg==}
engines: {node: '>=20'}
@@ -3613,6 +3671,42 @@ packages:
peerDependencies:
react: ^18.0 || ^19.0 || ^19.0.0-rc
+ '@redis/[email protected]':
+ resolution: {integrity: sha512-NQ5poYpZr0jv6zazN1cy6JY5kIipKFZ3R9GTL4kOUTX3a9YAfY29U8bsE4lWhVQEM+G4V0BXVC57mubIdDijeA==}
+ engines: {node: '>= 20.0.0'}
+ peerDependencies:
+ '@redis/client': ^6.3.0
+
+ '@redis/[email protected]':
+ resolution: {integrity: sha512-fHrjwGCBvAANGi+TuRuwKi83sIOzgHr8eh+Uf48w3fSX7Hhrz174NrWqfJhAC2vnN0d/tfaZpdr6+o6JC3QHwg==}
+ engines: {node: '>= 20.0.0'}
+ peerDependencies:
+ '@node-rs/xxhash': ^1.1.0
+ '@opentelemetry/api': '>=1 <2'
+ peerDependenciesMeta:
+ '@node-rs/xxhash':
+ optional: true
+ '@opentelemetry/api':
+ optional: true
+
+ '@redis/[email protected]':
+ resolution: {integrity: sha512-yt6vRfPBXtW/3qm53cF81TSQpLMjWdW4/2E9WQ2GgbvsKkuCKCFQIcMiKlil1ZMnezK+IQuS795xKU5psbaegw==}
+ engines: {node: '>= 20.0.0'}
+ peerDependencies:
+ '@redis/client': ^6.3.0
+
+ '@redis/[email protected]':
+ resolution: {integrity: sha512-RPXAZmKjZZG7Tm7m1w9keFdXzbL91PiSHQBfQRe9xwW40jNsTRbG0FwhIz4QlHPU4gKDAsCy8IQHj4yZl4H9rw==}
+ engines: {node: '>= 20.0.0'}
+ peerDependencies:
+ '@redis/client': ^6.3.0
+
+ '@redis/[email protected]':
+ resolution: {integrity: sha512-+fJOB8mN1z5WRakCJNh5lVdz1KqvHGSOistsKeitD24QsCtPwyRQXWC0iq6T/i/ubLE/YcguZqPm8F598MKk4A==}
+ engines: {node: '>= 20.0.0'}
+ peerDependencies:
+ '@redis/client': ^6.3.0
+
'@rolldown/[email protected]':
resolution: {integrity: sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -4849,6 +4943,9 @@ packages:
resolution: {integrity: sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-0k5eKfrA83JOZPppLtS2C7OUtyNAl2wKNxfyYl9Q5g9lPkgBl/9hNyAu6HuEH2J4XmIv2znEpkDd0SaZVxW6iQ==}
+
resolution: {integrity: sha512-qTxFi6Buiu8+50/+3DGIWLHM6QuWsEKugJnnP6iv2Mc4ncxE4A/OJkjuVOA+5X0X1S/nq5VJRa8Lu+nwcvbrKA==}
@@ -4887,6 +4984,9 @@ packages:
resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==}
+
'@typescript/[email protected]':
resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==}
engines: {node: '>=16.20.0'}
@@ -6419,8 +6519,8 @@ packages:
resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}
- resolution: {integrity: sha512-ooc1TG5t+FfzgYnFz2ff6BBKyZ7EwBRVXC7c4RhQUAD6/TZ2gTXXMeb4WX7a19ozQo4J73/QW+S00YAIresoMQ==}
+ resolution: {integrity: sha512-YeYnLqSFrL4+tCOXRrfNP03w8FILoF/wDl+ukraJAGzXrjcS383W7LAAvGBbLatEyktmLxRq+9xJinx7QzXW5A==}
resolution: {integrity: sha512-AN9xMU1hJiT65LkCUPL1DZm5TCbOPb2Qsm5pYwFLEXp6/qj9SdT4yMiqs7Qqstwvkn1zF7l36SRGt+s6XcJ0FA==}
@@ -7149,6 +7249,9 @@ packages:
resolution: {integrity: sha512-Bsdjwm3Qsd/P0jR+BHDe3LytDfY7WBq2HmCCLIwuVRHMuEC9ae7/R474GIUdF1NgCyZjzVo/A9DOiOBtXq8ZoQ==}
+ resolution: {integrity: sha512-WZzeDOEtTOBK4Mdsar0IqEU5sMr3vSV2RqkAIzUEV2BHnUfKGyswWFPFwK5EeDo93K3FohSHbLAjj0s1Wzd+dg==}
+
resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==}
@@ -8565,6 +8668,10 @@ packages:
resolution: {integrity: sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==}
engines: {node: '>=4'}
+ resolution: {integrity: sha512-XFQbPie1lGpKeUZ8ySYY43yLnQy/iIQtHNvIr/1XdaABpb96rUSdm3Mfl+98FEVbv9ZJIzINMno5s0Nh8E5LEw==}
+ engines: {node: '>= 20.0.0'}
+
resolution: {integrity: sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==}
@@ -10456,6 +10563,25 @@ snapshots:
dependencies:
'@noble/ciphers': 1.3.0
+ dependencies:
+ '@types/ws': 8.18.2
+ effect: 4.0.2
+ ws: 8.21.3
+ transitivePeerDependencies:
+ - bufferutil
+ - utf-8-validate
+
+ dependencies:
+ '@effect/platform-node-shared': 4.0.2([email protected])
+ effect: 4.0.2
+ redis: 6.3.0(@opentelemetry/[email protected])
+ undici: 7.29.0
+ transitivePeerDependencies:
+ - bufferutil
+ - utf-8-validate
+
'@electric-sql/[email protected](@electric-sql/[email protected])':
dependencies:
'@electric-sql/pglite': 0.3.15
@@ -10587,6 +10713,10 @@ snapshots:
'@fontsource-variable/[email protected]': {}
+ dependencies:
+ typescript: 7.0.2
+
dependencies:
hono: 4.13.8
@@ -10617,14 +10747,14 @@ snapshots:
hono: 4.13.8
zod: 4.6.5
dependencies:
'@standard-schema/utils': 0.3.0
react-hook-form: 7.89.0(@types/[email protected])([email protected])
optionalDependencies:
'@standard-schema/spec': 1.1.0
ajv: 8.18.0
- effect: 4.0.0
+ effect: 4.0.2
valibot: 1.5.0([email protected])
zod: 4.6.5
@@ -11385,7 +11515,7 @@ snapshots:
dependencies:
c12: 3.1.0
deepmerge-ts: 8.0.2
- effect: 4.0.0
+ effect: 4.0.2
empathic: 2.0.0
transitivePeerDependencies:
- magicast
@@ -12373,6 +12503,26 @@ snapshots:
dependencies:
react: 19.3.0
+ '@redis/[email protected](@redis/[email protected](@opentelemetry/[email protected]))':
+ dependencies:
+ '@redis/client': 6.3.0(@opentelemetry/[email protected])
+
+ '@redis/[email protected](@opentelemetry/[email protected])':
+ optionalDependencies:
+ '@opentelemetry/api': 1.9.1
+
+ '@redis/[email protected](@redis/[email protected](@opentelemetry/[email protected]))':
+ dependencies:
+ '@redis/client': 6.3.0(@opentelemetry/[email protected])
+
+ '@redis/[email protected](@redis/[email protected](@opentelemetry/[email protected]))':
+ dependencies:
+ '@redis/client': 6.3.0(@opentelemetry/[email protected])
+
+ '@redis/[email protected](@redis/[email protected](@opentelemetry/[email protected]))':
+ dependencies:
+ '@redis/client': 6.3.0(@opentelemetry/[email protected])
+
'@rolldown/[email protected]':
optional: true
@@ -13197,7 +13347,7 @@ snapshots:
picocolors: 1.1.1
redent: 3.0.0
optionalDependencies:
dependencies:
@@ -13645,6 +13795,10 @@ snapshots:
pg-protocol: 1.15.0
pg-types: 2.2.0
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 26.6.3
+
dependencies:
'@types/node': 26.6.3
@@ -13684,6 +13838,10 @@ snapshots:
dependencies:
'@types/node': 26.6.3
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 26.6.3
+
'@typescript/[email protected]':
optional: true
@@ -13764,7 +13922,7 @@ snapshots:
'@testing-library/dom': 10.4.1
'@testing-library/user-event': 14.6.7(@testing-library/[email protected])
transitivePeerDependencies:
- bufferutil
- msw
@@ -13781,7 +13939,7 @@ snapshots:
pngjs: 7.0.0
sirv: 3.0.2
tinyrainbow: 3.1.1
ws: 8.21.3
transitivePeerDependencies:
- bufferutil
@@ -13799,7 +13957,7 @@ snapshots:
obug: 2.2.1
std-env: 4.2.0
tinyrainbow: 3.1.1
'@vitest/[email protected]': {}
@@ -13860,7 +14018,7 @@ snapshots:
pathe: 2.0.3
sirv: 3.0.2
tinyrainbow: 3.1.1
'@vitest/[email protected]':
dependencies:
@@ -14179,7 +14337,7 @@ snapshots:
react: 19.3.0
react-dom: 19.3.0([email protected])
solid-js: 1.9.15
transitivePeerDependencies:
- '@cloudflare/workers-types'
- '@opentelemetry/api'
@@ -14215,7 +14373,7 @@ snapshots:
react: 19.3.0
react-dom: 19.3.0([email protected])
solid-js: 1.9.15
transitivePeerDependencies:
- '@cloudflare/workers-types'
- '@opentelemetry/api'
@@ -14956,8 +15114,7 @@ snapshots:
- optional: true
@@ -15717,6 +15874,8 @@ snapshots:
+
@@ -17332,6 +17491,17 @@ snapshots:
+ dependencies:
+ '@redis/bloom': 6.3.0(@redis/[email protected](@opentelemetry/[email protected]))
+ '@redis/client': 6.3.0(@opentelemetry/[email protected])
+ '@redis/json': 6.3.0(@redis/[email protected](@opentelemetry/[email protected]))
+ '@redis/search': 6.3.0(@redis/[email protected](@opentelemetry/[email protected]))
+ '@redis/time-series': 6.3.0(@redis/[email protected](@opentelemetry/[email protected]))
+ transitivePeerDependencies:
+ - '@node-rs/xxhash'
+ - '@opentelemetry/api'
+
dependencies:
regex-utilities: 2.3.0
@@ -18305,7 +18475,7 @@ snapshots:
oxlint-tsgolint: 7.0.2003
optionalDependencies:
'@voidzero-dev/vite-plus-darwin-arm64': 1.0.0
'@voidzero-dev/vite-plus-darwin-x64': 1.0.0
@@ -18360,7 +18530,7 @@ snapshots:
oxlint-tsgolint: 7.0.2003
optionalDependencies:
'@voidzero-dev/vite-plus-darwin-arm64': 1.0.0
'@voidzero-dev/vite-plus-darwin-x64': 1.0.0
@@ -18415,7 +18585,7 @@ snapshots:
tsx: 4.23.15
yaml: 2.9.0
dependencies:
'@types/chai': 5.2.3
@@ -18440,7 +18610,7 @@ snapshots:
transitivePeerDependencies:
- msw
dependencies:
'@types/chai': 5.2.3
@@ -18459,7 +18629,6 @@ snapshots:
optionalDependencies:
'@opentelemetry/api': 1.9.1
'@types/node': 26.6.3
'@vitest/coverage-v8': 5.0.3([email protected])
jsdom: 30.1.1(@noble/[email protected])
transitivePeerDependencies:
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 1f788af52..b9e8945ae 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -14,7 +14,7 @@ overrides:
minimatch: 10.2.3
rollup: 4.59.0
seroval: ">=1.5.3"
- effect: ">=3.20.0"
+ "effect@<4.0.0-0": ">=3.20.0"
fast-xml-parser: ">=5.5.7"
socket.io-parser: ">=4.2.7"
picomatch: ">=4.0.4"