@zinn-dev/cli 0.36.1 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,6 +2,11 @@
2
2
 
3
3
  The `zinn` command-line interface. Requires [Bun](https://bun.sh).
4
4
 
5
+ > [!IMPORTANT]
6
+ > **Experimental.** Commands, output and the database schema _can_ and **will** change between releases.
7
+ > A newer Zinn upgrades an older database. Read ([how](#upgrade-the-database)).
8
+ > Run `zinn backup` before upgrading.
9
+
5
10
  ## Install
6
11
 
7
12
  ```sh
@@ -9,11 +14,53 @@ bun add --global @zinn-dev/cli
9
14
  ```
10
15
 
11
16
  Zinn stores projects and tasks in the shared local database at `~/.zinn/data/zinn.sqlite`.
12
- Set `ZINN_DIR` to use another Zinn directory and keep using the same value for commands that should share that database.
17
+ Set `ZINN_DIR` to use another Zinn directory and keep using the same value for commands that should share that database. A relative `ZINN_DIR` stays relative to the current folder. A settings file can also choose the directory (see [Settings files](#settings-files)).
18
+
19
+ ## Settings files
20
+
21
+ Zinn reads two optional settings files:
22
+
23
+ - `settings.json` in the Zinn directory (`~/.zinn`, or `ZINN_DIR` when it is set) holds the global settings.
24
+ - `zinn.local.json` holds the settings for one codebase. Zinn uses the nearest one, from the current folder up to the Git root. Outside a Git repository it checks only the current folder.
25
+
26
+ `zinn.local.json` is personal, since it holds paths from one machine, and is not meant to be committed. Zinn reads it whether or not git ignores it. It is merged over the global file, field by field. A missing file is fine, and Zinn creates no settings file.
27
+
28
+ The files are plain JSON, without comments:
29
+
30
+ ```json
31
+ {
32
+ "storage": {
33
+ "directory": "~/work/zinn-data"
34
+ }
35
+ }
36
+ ```
37
+
38
+ `$schema` (a string, ignored by Zinn) and `storage.directory` are the only fields. An unknown key, a value of the wrong type or invalid JSON stops every command with an error that names the file. Zinn does not fall back to the defaults.
39
+
40
+ `storage.directory` names a Zinn directory with the same layout as `ZINN_DIR`: `data/zinn.sqlite` and `backups/`. The first of these that is set decides the directory: `ZINN_DIR`, `storage.directory` in `zinn.local.json`, `storage.directory` in the global `settings.json`, then `~/.zinn`. A relative path is relative to the folder of the file that sets it. A leading `~` or `~/` means your home folder.
41
+
42
+ ## Editing conventions
43
+
44
+ Edit commands change only the fields you supply; omitted fields keep their current values. At least one edit field is required. After input normalization, a valid edit that leaves all values unchanged succeeds without writing changes, updating modification timestamps, or recording activity.
45
+
46
+ Move, order, archive, unarchive, and task-label attachment commands also succeed without changes when the requested state is already satisfied. This does not apply to creation: creating an existing relation, for example, is an error.
47
+
48
+ Project and column names cannot be blank or contain line breaks or control characters, such as tabs. Column names are trimmed; project names retain surrounding spaces. Label names are trimmed and cannot be blank; task titles cannot be blank. Labels and task titles do not currently enforce the project/column single-line rule.
49
+
50
+ Project, task, and label descriptions may contain multiple lines. Omitted descriptions on creation, empty strings, and whitespace-only strings are stored as `null`. Text containing a non-whitespace character is preserved exactly, including leading and trailing whitespace. Use `--description ""` on an edit to clear a description. JSON returns the full text or `null`.
51
+
52
+ ## Changing tasks in bulk
53
+
54
+ `task move`, `task archive` and `task unarchive` accept multiple task keys, so several tasks can be changed in one command:
55
+
56
+ - Tasks are changed in the order given.
57
+ - If any task fails, for example because of an unknown key, none change.
58
+ - A task already in the requested state is listed as usual, with a note on stderr, such as `MDR-1 was already archived`. This includes a key given twice: by its second occurrence, the task is already in the requested state.
59
+ - With `--json`, one task prints an object and several print an array. Each task has a `changed` field, which is `false` when the task was already in the requested state.
13
60
 
14
61
  ## Concurrent access
15
62
 
16
- Commands on the same machine can share a database on a local filesystem. Zinn waits up to 30 seconds each time the database is locked by another command. If the lock is still held after that wait, the command fails. The command's total running time can exceed 30 seconds. Zinn also briefly retries specific initialization races internally. Initialization errors include the underlying message and code. Existing settings are preserved when several commands initialize the directory together.
63
+ Commands on the same machine can share a database on a local filesystem. Zinn waits up to 30 seconds each time the database is locked by another command. If the lock is still held after that wait, the command _fails_. The command's total running time can exceed 30 seconds. Zinn also briefly retries specific initialization races internally. Initialization errors include the underlying message and code.
17
64
 
18
65
  ## Start a project
19
66
 
@@ -24,9 +71,8 @@ zinn project create MDR --name "Macrodata Refinement" --description "Refine macr
24
71
  ```
25
72
 
26
73
  Project keys are stored in **uppercase**. You can create a project without a project name, like `zinn project create MDR`, which will just default to having the key as the project name too.
27
- Intetionally empty or whitespace project names are rejected.
28
74
 
29
- Project descriptions are optional and may contain multiple lines. An omitted, empty or whitespace-only description is stored as `null`. Text containing a non-whitespace character is preserved exactly, including leading and trailing whitespace; the same rule applies to task and label descriptions. Clear an existing description with `zinn project edit <project-key> --description ""`. Project list, view and mutation text show truncated inline description previews. Project JSON includes the full description or `null`.
75
+ Project list and mutation text show truncated inline description previews, while `project view` prints the description in full. See [Editing conventions](#editing-conventions) for description storage and clearing.
30
76
 
31
77
  Each project starts with _Backlog_, _TODO_, _In Progress_, _Review_, and _Done_ columns.
32
78
 
@@ -38,7 +84,7 @@ zinn project view MDR
38
84
  zinn project column list MDR
39
85
  ```
40
86
 
41
- `project view` prints the project and its unarchived tasks. It's the same list as you would get with `zinn task list <project-key>`.
87
+ `project view` prints the project with its full description and the number of unarchived tasks in each column. Archived tasks are counted as one total. Use `zinn task list <project-key>` to list the tasks themselves.
42
88
 
43
89
  Edit a project:
44
90
 
@@ -48,8 +94,7 @@ zinn project edit MDR --description "Meet the quarterly quota"
48
94
  zinn project edit MDR --description ""
49
95
  ```
50
96
 
51
- At least one of `--name` or `--description` is required. Names must contain printable text on a single line.
52
- Only supplied fields change; unchanged values leave the modification timestamp unchanged.
97
+ Provide `--name`, `--description`, or both.
53
98
  Use `--name="--example"` when a value begins with a dash.
54
99
 
55
100
  Add another column at the end of the board:
@@ -105,6 +150,10 @@ zinn task view MDR-1
105
150
 
106
151
  The list follows the project's column order and the task order within each column. Without a project key, projects are listed one after another, sorted by key.
107
152
 
153
+ Each row shows the task's key, column, priority marker, title, and labels, such as `MDR-1 | TODO | H | Refine the numbers | bug, cli`. Preview lists _do not_ contain the descriptions. To see everything, `task view` should be used.
154
+
155
+ `task view` prints the description in full, keeping its line breaks.
156
+
108
157
  Use `--label <name>` to list tasks with a label. You can provide multiple `--label` flags to refine your filter further down to more specific task results. Label names matching ignores casing. An unknown label causes an error to be raised.
109
158
 
110
159
  ## Search tasks
@@ -130,7 +179,13 @@ Note that by default only the active tasks are searched.
130
179
 
131
180
  Results use the same rows and `--json` shape as `task list`. A search with no results prints nothing and exits successfully. Put `--` before a query that begins with a dash: `zinn task search -- -flag`.
132
181
 
133
- Search uses an index that Zinn keeps up to date as tasks and comments change.
182
+ Search uses an index that Zinn keeps up to date as tasks and comments change. `zinn reindex` rebuilds it from the tasks and their comments, archived tasks included:
183
+
184
+ ```sh
185
+ zinn reindex
186
+ ```
187
+
188
+ Only the index changes, completely or not at all, so no backup is saved. With `--json`, it prints `{ "databasePath": "...", "taskCount": 12 }`. The command fails without changing anything when there is no database yet, or when Zinn refuses changes to the database, such as one with a newer schema version (see [Upgrade the database](#upgrade-the-database)).
134
189
 
135
190
  ## Labels
136
191
 
@@ -156,16 +211,16 @@ For adding or removing multiple labels at the same time, repeat `--label` on cre
156
211
  Each value is considered as the label name: `--label "needs review"`, so if you have commas, then they are considered parts of names.
157
212
  Label names preserve their stored casing, but matching and uniqueness are case-insensitive. For example, `BUG` can match to a label stored as `Bug`, `Bug` or `bug`, but all three canno exist at the same time as three different label entries. Changing only the casing of an existing label is allowed. Whitespace around label names is trimmed.
158
213
 
159
- Descriptions are `null` by default, and empty or whitespace-only strings are also interpreted as `null`. Clear a label description with `zinn label edit <name> --description ""`. Label colors default to white. Available colors are _red_, _green_, _yellow_, _blue_, _magenta_, _cyan_, _white_, and _gray_.
214
+ Label colors default to white. Available colors are _red_, _green_, _yellow_, _blue_, _magenta_, _cyan_, _white_, and _gray_.
160
215
 
161
216
  `label create`, `label edit` and `label list` print each label name in its color. When color is off (see [Scripting and JSON output](#scripting-and-json-output)), they name the color instead, such as `bug | red | Broken`. `--json` output always shows the color as a value.
162
217
 
163
- `label edit` changes only the supplied name, color, or description. Renaming preserves every task attachment because attachments refer to the label's internal ID. Also, updating a label does not affect any tasks' timestamps that it is attached to.
218
+ `label edit` accepts name, color, and description. Renaming preserves every task attachment because attachments refer to the label's internal ID. Updating a label definition does not affect attached tasks' timestamps.
164
219
 
165
220
  Task creation and edits apply content and label changes together, or roll back together on failure.
166
- Note that label changes also update the task's modification timestamp. Archived tasks can also have their labels edited.
221
+ Changing a task's label attachments updates that task's modification timestamp. Archived tasks can also have their labels edited.
167
222
 
168
- Commands like `task view` and task mutation output show attached labels.
223
+ Commands like `task list`, `task view` and task mutation output show attached labels, printing each label name in its color (see [Scripting and JSON output](#scripting-and-json-output) for when color appears). `--json` output lists a task's labels as names.
169
224
 
170
225
  `zinn label delete urgent` asks for confirmation, then deletes the definition and removes it from every task. Declining confirmation leaves the label and its attachments unchanged. `--yes` skips the confirmation (see [Confirmations](#confirmations)).
171
226
  Use `task label remove` to remove a label attachment from one task instead. Task/project deletion cleans up label attachments, but does not affect labels themselves.
@@ -227,9 +282,9 @@ zinn task edit MDR-1 --description "Complete refinement before the waffle party"
227
282
  zinn task edit MDR-1 --title "Meet the quarterly refinement quota" --description ""
228
283
  ```
229
284
 
230
- Only the explicitly specified fields are modified and the rest are untouched. Use `--description ""` to clear a description. It is stored and returned in JSON as `null`. If a description during task creation is omitted, it is treated as `null` by default, and if a _falsy_ value is provided, then it's also interpreted as `null`.
285
+ See [Editing conventions](#editing-conventions) for partial edits and clearing descriptions.
231
286
 
232
- At least one flag is required and task titles cannot be blank. Archived tasks can be edited without unarchiving them. Supplying unchanged values does not change the modification timestamp.
287
+ Archived tasks can be edited without unarchiving them.
233
288
  Use `--title="--example"` when a value begins with a dash.
234
289
 
235
290
  ## Move and order tasks
@@ -241,7 +296,14 @@ zinn task move MDR-1 "In Progress"
241
296
  ```
242
297
 
243
298
  A moved task appears at the bottom of its destination column. Moving it to its current column does nothing. Archived tasks must be unarchived before they can be moved.
244
- Moving prints only the task's key and new column, such as `MDR-1 | In Progress`, while `--json` prints the full task details.
299
+
300
+ Move multiple tasks at once by giving their keys before the column. They land at the bottom of the column in the order given, unless of course a task was _already_ in that column, in which case they stay as they were. Tasks from different projects can be moved together, and each one's column is looked up in its own project:
301
+
302
+ ```sh
303
+ zinn task move MDR-1 MDR-2 APP-4 "In Progress"
304
+ ```
305
+
306
+ See [Changing tasks in bulk](#changing-tasks-in-bulk).
245
307
 
246
308
  Change a task's position within its current column:
247
309
 
@@ -259,10 +321,11 @@ The task being reordered and the target of `before` or `after` must be active ta
259
321
 
260
322
  ## Archive and delete tasks
261
323
 
262
- Active tasks are shown by default. Archive a task to hide it from active lists, then list archived tasks or all tasks:
324
+ Active tasks are shown by default. Archive one or more tasks to hide them from active lists, then list archived tasks or all tasks:
263
325
 
264
326
  ```sh
265
327
  zinn task archive MDR-1
328
+ zinn task archive MDR-2 MDR-3
266
329
  zinn task list MDR --archived
267
330
  zinn task list MDR --all
268
331
  ```
@@ -273,8 +336,11 @@ Unarchiving puts a task at the bottom of its previous column:
273
336
 
274
337
  ```sh
275
338
  zinn task unarchive MDR-1
339
+ zinn task unarchive MDR-2 MDR-3
276
340
  ```
277
341
 
342
+ Archive or unarchive multiple tasks by giving several keys. Unarchived tasks land in the order given. See [Changing tasks in bulk](#changing-tasks-in-bulk).
343
+
278
344
  Delete a task permanently with `zinn task delete MDR-1`. It asks for confirmation before performing the action, unless `--yes` is used (see [Confirmations](#confirmations)).
279
345
 
280
346
  ## Back up the database
@@ -285,7 +351,49 @@ It is recommended to save a copy of the database before installing a new version
285
351
  zinn backup
286
352
  ```
287
353
 
288
- The copy goes to `~/.zinn/backups/` (or `backups/` in `ZINN_DIR`), in a file named after the UTC time and the CLI version that made it, like `2026-09-29T12-30-05Z-cli-0.32.0.sqlite`. It is a single file with every change made so far, and it is safe to take while Zinn is in use. Existing backups are never overwritten. With `--json`, the command prints `{ "path": "..." }`. It fails when there is no database yet.
354
+ The copy goes to the `backups/` folder next to `data/`, in a file named after the UTC time and the CLI version that made it, with an eight-character random suffix to distinguish backups made at the same time, like `2026-09-29T12-30-05Z-cli-0.32.0-b38178c0.sqlite`. It is a single file with every change made so far, and it is safe to take while Zinn is in use. Existing backups are never overwritten. With `--json`, the command prints `{ "path": "..." }`. It fails when there is no database yet.
355
+
356
+ ## Restore the database
357
+
358
+ Put back the board from a backup file, such as one saved by `zinn backup` or by an upgrade:
359
+
360
+ ```sh
361
+ zinn restore ~/.zinn/backups/2026-09-29T12-30-05Z-cli-0.32.0-b38178c0.sqlite
362
+ ```
363
+
364
+ The command asks for confirmation, unless `--yes` is used (see [Confirmations](#confirmations)). It saves the current board as a backup first, in the same folder as `zinn backup`, then replaces the board with the backup's, completely or not at all. Restoring onto a missing database creates it. With `--json`, it prints `{ "databasePath": "...", "previousVersion": 1, "restoredVersion": 1, "backupPath": "..." }`, where `backupPath` is the saved copy of the replaced board, or `null` when there was no board to save.
365
+
366
+ A backup with an older schema version is restored at that version, and Zinn then upgrades it like any older database (see [Upgrade the database](#upgrade-the-database)). The restore works whatever the version of the database it replaces, so you can go back to an older Zinn and restore the backup an upgrade saved.
367
+
368
+ The command fails without changing anything when the backup has a newer schema version than your Zinn (the error names the Zinn version that made the backup if its file name carries one), when it has no schema version, when it is **damaged**, or when it is not a Zinn database. If the restore fails after that, the database is unchanged, and any backup saved before the attempt stays in the `backups/` folder.
369
+
370
+ If the database being replaced is damaged, restore leaves it unchanged and prints recovery steps.
371
+
372
+ ## Upgrade the database
373
+
374
+ The database records a schema version, and a newer Zinn upgrades an older database to its own version. The upgrade is applied completely or not at all, and a backup is saved first, in the same folder as `zinn backup`.
375
+
376
+ A published release of Zinn upgrades the database by itself the first time it opens it. Run `zinn migrate` to upgrade it yourself, for example right after installing a newer Zinn, or when Zinn refuses a change because the database is older. A build run from a source checkout upgrades only a `ZINN_DIR` database by itself, and refuses changes to any other older database until you do:
377
+
378
+ ```sh
379
+ zinn migrate
380
+ ```
381
+
382
+ The command saves a backup, upgrades the database and reports the backup's path with the schema versions before and after. When the database is already up to date, it changes nothing and saves no backup. With `--json`, it prints `{ "databasePath": "...", "previousVersion": 1, "finalVersion": 2, "changed": true, "backupPath": "..." }`, where `backupPath` is `null` when nothing changed.
383
+
384
+ If the upgrade fails, the database is unchanged. The backups taken before each attempt stay in the `backups/` folder. The command fails without attempting anything when there is no database with data yet, when the database has no schema version, or when it is newer than your Zinn.
385
+
386
+ A database with a newer schema version than your Zinn can be read, but changes are refused. Use a newer Zinn to change it.
387
+
388
+ ### Databases without a schema version
389
+
390
+ A database created before Zinn recorded schema versions has none. Zinn refuses to open it, and `zinn migrate` does not upgrade it. Add `--allow-legacy-read` to a command to read it anyway:
391
+
392
+ ```sh
393
+ zinn task list MDR --allow-legacy-read
394
+ ```
395
+
396
+ Reads are best effort and may fail or omit data, and Zinn warns about it on stderr once per command. The flag never lets a command change the database, and it applies only to the command that carries it. Like `--json`, it can go anywhere in the command, except after `--`, where it is treated as a regular argument. `zinn backup` works on such a database without the flag.
289
397
 
290
398
  ## Scripting and JSON output
291
399
 
@@ -304,15 +412,15 @@ Text output is mainly for _visual_ consumption. Colors appear only when the outp
304
412
 
305
413
  ### Confirmations
306
414
 
307
- Commands like `project delete`, `task delete`, etc. ask for confirmation before deleting. Use `--yes` to skip the prompt:
415
+ Commands like `project delete`, `task delete`, etc. ask for confirmation before deleting, and `restore` asks before replacing the board. Use `--yes` to skip the prompt:
308
416
 
309
417
  ```sh
310
418
  zinn task delete MDR-1 --yes
311
419
  zinn task delete MDR-1 --yes --json
312
420
  ```
313
421
 
314
- - With `--json`, `--yes` is **required**. Without it, the command exits with an error and deletes nothing.
315
- - When nothing answers the prompt, as in CI or with input redirected from an empty source, a delete without `--yes` counts as declined: it prints `Deletion cancelled …` and exits with code 0. Scripts that delete should always use `--yes`.
422
+ - With `--json`, `--yes` is **required**. Without it, the command exits with an error and changes nothing.
423
+ - When nothing answers the prompt, as in CI or with input redirected from an empty source, a command without `--yes` counts as declined: it prints `Deletion cancelled …` (or `Restore cancelled …`) and exits with code 0. Scripts that delete or restore should always use `--yes`.
316
424
  - `task relation delete` is consider a low consequence action, so it never asks for confirmation and does not accept `--yes`.
317
425
 
318
426
  ## Help
@@ -341,7 +449,7 @@ zinn task edit MDR-1 --priority urgent
341
449
  zinn task edit MDR-1 --priority none
342
450
  ```
343
451
 
344
- Use `none` to clear priority. Omitting `--priority` on edits preserves it. Task lists show priority in a compact column after the board column: `-` for unassigned and `L`, `M`, `H`, or `U` for low, medium, high, or urgent. Task views show the full priority value. Priority does not affect board ordering.
452
+ Use `none` to clear priority. Task lists show priority in a compact column after the board column: `-` for unassigned and `L`, `M`, `H`, or `U` for low, medium, high, or urgent. Priority does not affect board ordering.
345
453
 
346
454
  ## Activity
347
455
 
package/index.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  #!/usr/bin/env bun
2
2
 
3
- import { isHelpFlag } from "./src/lib";
4
3
  import packageJson from "./package.json";
5
4
 
6
5
  const args = process.argv.slice(2);
@@ -9,6 +8,7 @@ const isVersionRequest = args.length === 1 && ["-v", "--version"].includes(args[
9
8
  if (isVersionRequest) {
10
9
  console.info(packageJson.version);
11
10
  } else {
11
+ const { isHelpFlag } = await import("./src/lib");
12
12
  const { createRouter } = await import("./src/routes/router");
13
13
  const { routes } = await import("./src/routes/routes");
14
14
  const router = createRouter(routes);
@@ -22,6 +22,7 @@ Options:
22
22
  -h, --help Show help
23
23
  -v, --version Show version
24
24
  --json Print command output as JSON
25
+ --allow-legacy-read Read a database without a schema version, best effort and read-only
25
26
 
26
27
  Commands:
27
28
  ${router.commands}
@@ -29,6 +30,11 @@ ${router.commands}
29
30
  Run zinn <namespace> --help or zinn <command> --help for more information.
30
31
  Running zinn without a command shows this help.`);
31
32
  } else {
33
+ const { configureDatabase } = await import("@zinn-dev/core");
34
+ const { cliOpenPolicy } = await import("./src/database");
35
+
36
+ // Only records the policy. core then opens the database when a command first uses it.
37
+ configureDatabase(cliOpenPolicy());
32
38
  router.route(args);
33
39
  }
34
40
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zinn-dev/cli",
3
- "version": "0.36.1",
4
- "description": "A kanban workflow in the terminal.",
3
+ "version": "0.37.0",
4
+ "description": "A kanban workflow in the terminal. Experimental.",
5
5
  "license": "MIT",
6
6
  "bugs": {
7
7
  "url": "https://github.com/yethranayeh/zinn/issues"
@@ -32,7 +32,8 @@
32
32
  "files": [
33
33
  "index.ts",
34
34
  "src",
35
- "LICENSE"
35
+ "LICENSE",
36
+ "release-stamp.json"
36
37
  ],
37
38
  "type": "module",
38
39
  "bin": {
@@ -42,6 +43,7 @@
42
43
  "access": "public"
43
44
  },
44
45
  "dependencies": {
45
- "@zinn-dev/core": "0.25.1"
46
- }
46
+ "@zinn-dev/core": "0.26.0"
47
+ },
48
+ "scripts": {}
47
49
  }
@@ -0,0 +1 @@
1
+ {"release":"published"}
@@ -0,0 +1,70 @@
1
+ import { expect, spyOn, test } from "bun:test";
2
+ import { existsSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ import packageJson from "../package.json";
7
+ import { cliOpenPolicy, reportLegacyRead, reportLockWait } from "./database";
8
+ import { setLegacyReadAllowed } from "./lib";
9
+
10
+ const CLI_DIRECTORY = fileURLToPath(new URL("..", import.meta.url));
11
+ // The file name core's release reading looks for.
12
+ const RELEASE_STAMP_FILE = "release-stamp.json";
13
+
14
+ test("the CLI opens the database as the cli client of its own release mode, without legacy reads", () => {
15
+ const { onWait, onLegacyRead, ...policy } = cliOpenPolicy();
16
+ const stderr = spyOn(console, "error").mockImplementation(() => {});
17
+
18
+ try {
19
+ onWait?.({ databasePath: "/data/zinn.sqlite", budgetMs: 30000 });
20
+
21
+ expect(policy).toEqual({
22
+ client: "cli",
23
+ version: packageJson.version,
24
+ executable: process.argv[1] ?? process.execPath,
25
+ release: "source",
26
+ allowsLegacyRead: false,
27
+ });
28
+ expect(onWait).toBe(reportLockWait);
29
+ expect(stderr.mock.calls).toEqual([
30
+ ["Another process is using the database. Waiting up to 30 seconds for it to finish."],
31
+ ]);
32
+ } finally {
33
+ stderr.mockRestore();
34
+ }
35
+ });
36
+
37
+ test("the policy allows legacy reads only once --allow-legacy-read was handled", () => {
38
+ const policy = cliOpenPolicy();
39
+
40
+ try {
41
+ expect(policy.allowsLegacyRead).toBe(false);
42
+ setLegacyReadAllowed(true);
43
+ expect(policy.allowsLegacyRead).toBe(true);
44
+ } finally {
45
+ setLegacyReadAllowed(false);
46
+ }
47
+ });
48
+
49
+ test("the policy warns on stderr about the unmarked database that opened for reading", () => {
50
+ const stderr = spyOn(console, "error").mockImplementation(() => {});
51
+
52
+ try {
53
+ expect(cliOpenPolicy().onLegacyRead).toBe(reportLegacyRead);
54
+ reportLegacyRead({ databasePath: "/data/zinn.sqlite", version: 0, latestVersion: 1 });
55
+
56
+ expect(stderr.mock.calls).toHaveLength(1);
57
+ expect(stderr.mock.calls[0]![0]).toContain("/data/zinn.sqlite");
58
+ expect(stderr.mock.calls[0]![0]).toContain("no schema version");
59
+ } finally {
60
+ stderr.mockRestore();
61
+ }
62
+ });
63
+
64
+ test("this source folder has no stamp", () => {
65
+ expect(existsSync(join(CLI_DIRECTORY, RELEASE_STAMP_FILE))).toBe(false);
66
+ });
67
+
68
+ test("the published package includes the stamp", () => {
69
+ expect(packageJson.files).toContain(RELEASE_STAMP_FILE);
70
+ });
@@ -0,0 +1,41 @@
1
+ import type { DatabaseFacts, LockWait, OpenPolicy } from "@zinn-dev/core";
2
+
3
+ import { fileURLToPath } from "node:url";
4
+ import { readReleaseMode } from "@zinn-dev/core";
5
+
6
+ import packageJson from "../package.json";
7
+ import { isLegacyReadAllowed } from "./lib";
8
+
9
+ const MS_PER_SECOND = 1000;
10
+ /** The CLI's package folder, which holds its release stamp once it is packed. */
11
+ const PACKAGE_DIRECTORY = fileURLToPath(new URL("..", import.meta.url));
12
+
13
+ /** Says once on stderr that the command waits for another process to finish with the database. */
14
+ export function reportLockWait({ budgetMs }: LockWait) {
15
+ console.error(
16
+ `Another process is using the database. Waiting up to ${budgetMs / MS_PER_SECOND} seconds for it to finish.`,
17
+ );
18
+ }
19
+
20
+ export function reportLegacyRead({ databasePath }: DatabaseFacts) {
21
+ console.error(
22
+ `Warning: the database at ${databasePath} has no schema version. Reads are best effort and may fail or omit data.`,
23
+ );
24
+ }
25
+
26
+ /** How the CLI asks core to open the database. */
27
+ export function cliOpenPolicy(): OpenPolicy {
28
+ return {
29
+ client: "cli",
30
+ version: packageJson.version,
31
+ // The script the CLI runs from; the runtime itself when there is none.
32
+ executable: process.argv[1] ?? process.execPath,
33
+ release: readReleaseMode(PACKAGE_DIRECTORY),
34
+ // Read when the database opens, after the router has handled `--allow-legacy-read`
35
+ get allowsLegacyRead() {
36
+ return isLegacyReadAllowed();
37
+ },
38
+ onWait: reportLockWait,
39
+ onLegacyRead: reportLegacyRead,
40
+ };
41
+ }
@@ -0,0 +1,60 @@
1
+ import type { OpenPolicy } from "@zinn-dev/core";
2
+
3
+ import { expect, test } from "bun:test";
4
+ import { ReadOnlyDatabaseError, UnmarkedDatabaseError } from "@zinn-dev/core";
5
+
6
+ import { failureMessage } from "./lib";
7
+
8
+ const FALLBACK = "Something went wrong";
9
+ const POLICY: OpenPolicy = {
10
+ client: "cli",
11
+ version: "1.0.0",
12
+ executable: "/test/zinn",
13
+ release: "source",
14
+ allowsLegacyRead: false,
15
+ };
16
+
17
+ function readOnlyError(reason: "older" | "newer" | "unmarked") {
18
+ const versions = { older: 1, newer: 3, unmarked: 0 };
19
+ const version = versions[reason];
20
+ return new ReadOnlyDatabaseError(
21
+ reason,
22
+ { databasePath: "/data/zinn.sqlite", version, latestVersion: 2 },
23
+ POLICY,
24
+ );
25
+ }
26
+
27
+ test("an older database that stays read-only points at zinn migrate in the same line", () => {
28
+ const error = readOnlyError("older");
29
+
30
+ expect(failureMessage(error, FALLBACK)).toBe(
31
+ `${error.message}. Run \`zinn migrate\` to upgrade it.`,
32
+ );
33
+ });
34
+
35
+ test("other failures keep their own message, or the fallback when they have none", () => {
36
+ const newer = readOnlyError("newer");
37
+
38
+ expect(failureMessage(newer, FALLBACK)).toBe(newer.message);
39
+ expect(failureMessage(new Error("Task does not exist"), FALLBACK)).toBe("Task does not exist");
40
+ expect(failureMessage(undefined, FALLBACK)).toBe(FALLBACK);
41
+ });
42
+
43
+ test("an unmarked database that was not opened names --allow-legacy-read", () => {
44
+ const error = new UnmarkedDatabaseError({
45
+ databasePath: "/data/zinn.sqlite",
46
+ version: 0,
47
+ latestVersion: 2,
48
+ });
49
+ const message = failureMessage(error, FALLBACK);
50
+
51
+ expect(message).toStartWith(error.message);
52
+ expect(message).toContain("/data/zinn.sqlite");
53
+ expect(message).toContain("--allow-legacy-read");
54
+ });
55
+
56
+ test("an unmarked database opened for reading refuses changes without pointing at the flag", () => {
57
+ const error = readOnlyError("unmarked");
58
+
59
+ expect(failureMessage(error, FALLBACK)).toBe(error.message);
60
+ });
package/src/lib.ts CHANGED
@@ -1,9 +1,12 @@
1
1
  import type { parseArgs } from "node:util";
2
2
 
3
+ import { assertWritable, ReadOnlyDatabaseError, UnmarkedDatabaseError } from "@zinn-dev/core";
4
+
3
5
  type ParsedTokens = NonNullable<ReturnType<typeof parseArgs>["tokens"]>;
4
6
  type OutputMode = "text" | "json";
5
7
 
6
8
  let outputMode: OutputMode = "text";
9
+ let legacyReadAllowed = false;
7
10
 
8
11
  export function setOutputMode(mode: OutputMode) {
9
12
  outputMode = mode;
@@ -13,6 +16,18 @@ export function isJsonFlag(flag: string) {
13
16
  return flag === "--json";
14
17
  }
15
18
 
19
+ export function isAllowLegacyReadFlag(flag: string) {
20
+ return flag === "--allow-legacy-read";
21
+ }
22
+
23
+ export function setLegacyReadAllowed(allowed: boolean) {
24
+ legacyReadAllowed = allowed;
25
+ }
26
+
27
+ export function isLegacyReadAllowed() {
28
+ return legacyReadAllowed;
29
+ }
30
+
16
31
  export function output<T>(data: T, transformToString: (data: T) => string) {
17
32
  if (outputMode === "json") {
18
33
  console.info(JSON.stringify(data, null, 2));
@@ -26,7 +41,16 @@ export function output<T>(data: T, transformToString: (data: T) => string) {
26
41
  }
27
42
  }
28
43
 
44
+ /** Asks before a change that cannot be undone, unless --yes already confirmed it. */
29
45
  export function confirmAction(message: string, isPreconfirmed: boolean) {
46
+ // Throws on a read-only database, to avoid asking for confirmation to an already refused action
47
+ assertWritable();
48
+
49
+ return askConfirmation(message, isPreconfirmed);
50
+ }
51
+
52
+ /** Like confirmAction, without opening the database, for commands that bypass the open policy. */
53
+ export function askConfirmation(message: string, isPreconfirmed: boolean) {
30
54
  if (isPreconfirmed) {
31
55
  return true;
32
56
  }
@@ -38,6 +62,24 @@ export function confirmAction(message: string, isPreconfirmed: boolean) {
38
62
  return confirm(message);
39
63
  }
40
64
 
65
+ /** The message to report for a failed command, or fallback when the error has none. */
66
+ export function failureMessage(error: any, fallback: string) {
67
+ const isOlderReadOnly = error instanceof ReadOnlyDatabaseError && error.reason === "older";
68
+ if (isOlderReadOnly) {
69
+ return `${error.message}. Run \`zinn migrate\` to upgrade it.`;
70
+ }
71
+
72
+ if (error instanceof UnmarkedDatabaseError) {
73
+ return `${error.message}. Add --allow-legacy-read to read it anyway.`;
74
+ }
75
+
76
+ if (error?.message === "no such table: task_search") {
77
+ return `${error.message}. Run \`zinn reindex\` to rebuild the search index.`;
78
+ }
79
+
80
+ return error?.message ?? fallback;
81
+ }
82
+
41
83
  export function quit(reason: string): never {
42
84
  if (outputMode === "json") {
43
85
  console.error(JSON.stringify({ error: { message: reason } }, null, 2));
@@ -1,6 +1,6 @@
1
1
  import { styleText } from "node:util";
2
2
 
3
- type StyleFormat = Parameters<typeof styleText>[0];
3
+ export type StyleFormat = Parameters<typeof styleText>[0];
4
4
 
5
5
  /**
6
6
  * Bun's styleText emits ANSI even when stdout is piped or NO_COLOR is set, so Zinn decides when to color.
@@ -0,0 +1,38 @@
1
+ import type { RowCell } from "./row-layout";
2
+
3
+ import { formatRows } from "./row-layout";
4
+
5
+ export type PresentedColumnTaskCount = { name: string; taskCount: number };
6
+
7
+ /** Archived tasks are off the board, so they share one row below the columns instead of a column of their own. */
8
+ const ARCHIVED_ROW_LABEL = "Archived";
9
+
10
+ export function columnNameCell(columnName: string): RowCell {
11
+ // TODO: Derive column colors from column roles once roles exist instead of relying on names.
12
+ if (columnName === "Backlog") {
13
+ return { text: columnName, style: "gray" };
14
+ }
15
+
16
+ if (columnName === "Done") {
17
+ return { text: columnName, style: "green" };
18
+ }
19
+
20
+ return { text: columnName };
21
+ }
22
+
23
+ /** The archived row is left out when there are no archived tasks. */
24
+ export function formatColumnTaskCounts(
25
+ presentedColumns: Array<PresentedColumnTaskCount>,
26
+ options: { archivedTaskCount: number },
27
+ ) {
28
+ const rows: Array<Array<RowCell>> = presentedColumns.map((presentedColumn) => [
29
+ columnNameCell(presentedColumn.name),
30
+ { text: String(presentedColumn.taskCount) },
31
+ ]);
32
+
33
+ if (options.archivedTaskCount > 0) {
34
+ rows.push([{ text: ARCHIVED_ROW_LABEL }, { text: String(options.archivedTaskCount) }]);
35
+ }
36
+
37
+ return formatRows(rows);
38
+ }