@zinn-dev/cli 0.38.0 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +47 -9
  2. package/index.d.ts +2 -0
  3. package/index.js +23 -0
  4. package/package.json +22 -18
  5. package/src/actor.d.ts +6 -0
  6. package/src/actor.js +62 -0
  7. package/src/database.d.ts +6 -0
  8. package/src/database.js +27 -0
  9. package/src/lib.d.ts +31 -0
  10. package/src/lib.js +137 -0
  11. package/src/presentation/activity-presentation.d.ts +23 -0
  12. package/src/presentation/activity-presentation.js +389 -0
  13. package/src/presentation/color.d.ts +9 -0
  14. package/src/presentation/color.js +21 -0
  15. package/src/presentation/column-presentation.d.ts +16 -0
  16. package/src/presentation/column-presentation.js +29 -0
  17. package/src/presentation/description-presentation.d.ts +3 -0
  18. package/src/presentation/description-presentation.js +11 -0
  19. package/src/presentation/row-layout.d.ts +22 -0
  20. package/src/presentation/row-layout.js +58 -0
  21. package/src/presentation/section.d.ts +4 -0
  22. package/src/presentation/section.js +9 -0
  23. package/src/presentation/task-presentation.d.ts +17 -0
  24. package/src/presentation/task-presentation.js +62 -0
  25. package/src/presentation/time.d.ts +1 -0
  26. package/src/presentation/time.js +13 -0
  27. package/src/project.d.ts +6 -0
  28. package/src/project.js +31 -0
  29. package/src/release-identity.d.ts +2 -0
  30. package/src/release-identity.js +1 -0
  31. package/src/routes/activity-router.d.ts +10 -0
  32. package/src/routes/activity-router.js +71 -0
  33. package/src/routes/backup-router.d.ts +4 -0
  34. package/src/routes/backup-router.js +18 -0
  35. package/src/routes/comment-router.d.ts +24 -0
  36. package/src/routes/comment-router.js +134 -0
  37. package/src/routes/label-router.d.ts +18 -0
  38. package/src/routes/label-router.js +136 -0
  39. package/src/routes/migrate-router.d.ts +4 -0
  40. package/src/routes/migrate-router.js +37 -0
  41. package/src/routes/project-router.d.ts +40 -0
  42. package/src/routes/project-router.js +328 -0
  43. package/src/routes/reindex-router.d.ts +4 -0
  44. package/src/routes/reindex-router.js +21 -0
  45. package/src/routes/relation-router.d.ts +28 -0
  46. package/src/routes/relation-router.js +163 -0
  47. package/src/routes/restore-router.d.ts +4 -0
  48. package/src/routes/restore-router.js +71 -0
  49. package/src/routes/router.d.ts +6 -0
  50. package/src/routes/router.js +185 -0
  51. package/src/routes/routes.d.ts +170 -0
  52. package/src/routes/routes.js +19 -0
  53. package/src/routes/task-router.d.ts +84 -0
  54. package/src/routes/task-router.js +533 -0
  55. package/src/text-edit.d.ts +25 -0
  56. package/src/text-edit.js +45 -0
  57. package/src/types.d.ts +10 -0
  58. package/src/types.js +1 -0
  59. package/index.ts +0 -26
  60. package/release-stamp.json +0 -1
  61. package/src/actor.test.ts +0 -41
  62. package/src/actor.ts +0 -78
  63. package/src/database.test.ts +0 -70
  64. package/src/database.ts +0 -41
  65. package/src/lib.test.ts +0 -86
  66. package/src/lib.ts +0 -145
  67. package/src/presentation/activity-presentation.test.ts +0 -71
  68. package/src/presentation/activity-presentation.ts +0 -489
  69. package/src/presentation/color.ts +0 -29
  70. package/src/presentation/column-presentation.ts +0 -48
  71. package/src/presentation/description-presentation.ts +0 -18
  72. package/src/presentation/row-layout.ts +0 -77
  73. package/src/presentation/section.ts +0 -16
  74. package/src/presentation/task-presentation.ts +0 -92
  75. package/src/presentation/time.ts +0 -17
  76. package/src/routes/activity-router.ts +0 -77
  77. package/src/routes/backup-router.ts +0 -24
  78. package/src/routes/comment-router.ts +0 -171
  79. package/src/routes/label-router.ts +0 -168
  80. package/src/routes/migrate-router.test.ts +0 -31
  81. package/src/routes/migrate-router.ts +0 -48
  82. package/src/routes/project-router.ts +0 -387
  83. package/src/routes/reindex-router.ts +0 -27
  84. package/src/routes/relation-router.ts +0 -194
  85. package/src/routes/restore-router.test.ts +0 -44
  86. package/src/routes/restore-router.ts +0 -90
  87. package/src/routes/router.test.ts +0 -136
  88. package/src/routes/router.ts +0 -248
  89. package/src/routes/routes.ts +0 -20
  90. package/src/routes/task-router.ts +0 -594
  91. package/src/text-edit.ts +0 -68
  92. package/src/types.ts +0 -6
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @zinn-dev/cli
2
2
 
3
- The `zinn` command-line interface. Requires [Bun](https://bun.sh).
3
+ The `zinn` command-line interface.
4
4
 
5
5
  > [!IMPORTANT]
6
6
  > **Experimental.** Commands, output, and the database schema will likely change often between releases until stable.
@@ -9,9 +9,11 @@ The `zinn` command-line interface. Requires [Bun](https://bun.sh).
9
9
  ## Install
10
10
 
11
11
  ```sh
12
- bun add --global @zinn-dev/cli
12
+ npm i -g @zinn-dev/cli
13
13
  ```
14
14
 
15
+ Requires [Node.js](https://nodejs.org/) 24.15.0 or newer.
16
+
15
17
  For a first project and task, see the [quick start](../../README.md#quick-start).
16
18
 
17
19
  Zinn stores projects and tasks in the shared local database at `~/.zinn/data/zinn.sqlite`.
@@ -19,27 +21,37 @@ Set `ZINN_DIR` to use another Zinn directory and keep using the same value for c
19
21
 
20
22
  ## Settings files
21
23
 
22
- Zinn reads two optional settings files:
24
+ With `ZINN_DIR` set, Zinn uses `data/zinn.sqlite`, `backups/`, and `settings.json` inside that directory. That `settings.json` is the sole configuration file for the invocation, which means its `defaultProject` applies to that store. `ZINN_DIR` also takes precedence over `storage.directory` in that file.
25
+
26
+ Without `ZINN_DIR`, Zinn reads two optional settings files:
23
27
 
24
- - `settings.json` in the Zinn directory (`~/.zinn`, or `ZINN_DIR` when it is set) holds the global settings.
28
+ - `settings.json` in `~/.zinn` holds the global settings.
25
29
  - `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.
26
30
 
27
- `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.
31
+ `zinn.local.json` is personal, since it holds paths from one machine, and is not meant to be committed. Without `ZINN_DIR`, Zinn reads it whether or not git ignores it and merges it over the global file, field by field. A missing file is fine, and Zinn creates no settings file.
28
32
 
29
33
  The files are plain JSON, without comments:
30
34
 
31
35
  ```json
32
36
  {
37
+ "$schema": "https://zinn.sh/schemas/settings/v1.json",
38
+ "defaultProject": "MDR",
33
39
  "storage": {
34
40
  "directory": "~/work/zinn-data"
35
41
  }
36
42
  }
37
43
  ```
38
44
 
39
- `$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.
45
+ `$schema` is optional and lets editors handle autocomplete and check the file, but Zinn itself ignores it. New settings are added to the same number; only a change that would make existing files invalid gets a new number. An unknown key, a value of the wrong type or invalid JSON in a selected settings file stops every command with an error that names the file. Zinn _does not fall back to the defaults_.
40
46
 
41
47
  `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.
42
48
 
49
+ `defaultProject` names the project used when its key is omitted from `task create`, `task list`, `task search`, `project view`, `project column list`, `project edit`, or `project delete`. Project keys are matched case-insensitively. A key typed in the command wins, then the local setting, then the global setting. A local file that omits this field keeps the global value; `null` is not accepted.
50
+
51
+ Without a default, `task list` and `task search` cover every project, and the other commands require a key. When a configured default names a missing project, commands using it fail with an error naming the key and its settings file.
52
+
53
+ On `task list` and `task search`, `--all-projects` covers every project, overriding the default, and works with `--all` or `--archived`. It cannot be combined with a typed project key. Commands taking a task key use the project named by that key. Column creation, editing, and ordering require an explicit project key.
54
+
43
55
  ## Editing conventions
44
56
 
45
57
  Edit commands change only the fields you supply, whereas 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.
@@ -143,6 +155,8 @@ zinn project column list MDR
143
155
 
144
156
  `project view` shows the project's description and task counts. Use `zinn task list <project-key>` to read its tasks.
145
157
 
158
+ `project view` and `project column list` accept an omitted project key when [defaultProject](#settings-files) is configured.
159
+
146
160
  `project column list` counts unarchived tasks. With `--json`, it returns `[{ "name": "Backlog", "taskCount": 3 }, ...]`.
147
161
 
148
162
  Edit a project:
@@ -154,6 +168,7 @@ zinn project edit MDR --description ""
154
168
  ```
155
169
 
156
170
  Provide `--name`, `--description`, or both.
171
+ The project key can be omitted when [defaultProject](#settings-files) is configured.
157
172
  See [Text values](#text-values) for values that begin with a dash and multi-line text.
158
173
 
159
174
  Add another column at the end of the board:
@@ -184,7 +199,7 @@ zinn project column order MDR Review after Done
184
199
  Directions follow board order: `first` is the start of the board and `last` is its end.
185
200
  Moving a column to the position it already has, or before or after itself, does nothing. Tasks stay in their columns.
186
201
 
187
- `zinn project delete MDR` asks for confirmation, then permanently deletes the project and all of its columns and tasks. `--yes` skips the confirmation (see [Confirmations](#confirmations)).
202
+ `zinn project delete MDR` asks for confirmation, then permanently deletes the project and all of its columns and tasks. `--yes` skips confirmation when the project key is **typed**. With an _omitted_ key and [defaultProject](#settings-files), it always asks: `--yes` is ignored with a warning, and without a terminal the command refuses with exit code 1. With `--json`, type the key and pass `--yes` (see [Confirmations](#confirmations)).
188
203
 
189
204
  ## Create and read tasks
190
205
 
@@ -195,6 +210,8 @@ zinn task create MDR --title "Refine 75% of the numbers"
195
210
  zinn task create MDR --title "Review the employee handbook" --description "Prepare for a 75% Dance Experience"
196
211
  ```
197
212
 
213
+ The project key can be omitted when [defaultProject](#settings-files) is configured.
214
+
198
215
  `--column <name>` starts the task at the bottom of a specific column. The column name matching is case insensitive:
199
216
 
200
217
  ```sh
@@ -206,13 +223,23 @@ Tasks are created with keys such as `MDR-1`. Task numbers increase in creation o
206
223
  ```sh
207
224
  zinn task list
208
225
  zinn task list MDR
226
+ zinn task list --all-projects
209
227
  zinn task list MDR --label CLI --label Groom
210
228
  zinn task list MDR --column "In Progress"
211
229
  zinn task list --column Done --all
212
230
  zinn task view MDR-1
231
+ zinn task view MDR-1 --history
213
232
  ```
214
233
 
215
- Task lists are previews, so they omit descriptions, but `task view` prints the full description.
234
+ Task lists are previews, so they _omit_ descriptions, but `task view` prints the full description.
235
+
236
+ An omitted project key uses [defaultProject](#settings-files), or every project when none is configured. `--all-projects` overrides the default.
237
+
238
+ `task view --history` includes the inspected task's recorded activity, newest first by time, then event ID. Reorders and comment changes are included. Use `activity view <activity-id>` for full recorded changes. See [Activity](#activity) for timestamps, event IDs, and record fields.
239
+
240
+ With `--history --json`, the task gains an `activity` array of full activity records. It returns `[]` when no events are recorded. Without `--history`, this field is _omitted_.
241
+
242
+ If a project is deleted and recreated with the same key, `task view --history` shows only the _current_ task’s history. `activity list --task <key>` can also show history for **deleted tasks** that previously had that same key.
216
243
 
217
244
  Repeat `--label <name>` to require every specified label. Matching ignores case.
218
245
 
@@ -224,6 +251,7 @@ Search task titles, descriptions, and comments, optionally in one project:
224
251
 
225
252
  ```sh
226
253
  zinn task search refine
254
+ zinn task search refine --all-projects
227
255
  zinn task search "quarterly quota" MDR
228
256
  zinn task search MDR-1
229
257
  zinn task search auth --all --limit 5
@@ -232,8 +260,12 @@ zinn task search auth MDR --label cli
232
260
 
233
261
  Each query matches the start of a word, ignoring case and accents, so `cafe` finds "Café" and `auth` finds "Authentication". Every word must match somewhere in the task: its title, its description, or any of its comments. A comment match lists the task the comment belongs to.
234
262
 
263
+ The query comes first, then the optional project key. An omitted key uses [defaultProject](#settings-files), or every project when none is configured. `--all-projects` overrides the default.
264
+
235
265
  If the whole query is an existing task key, such as `mdr-1`, that task comes first. Other results follow by relevance, with title matches weighted highest. Equally relevant tasks are ordered by project key, then task number.
236
266
 
267
+ An exact task-key query overrides the configured default project. A project key supplied after the query still filters the search.
268
+
237
269
  Search defaults to active tasks. `--archived` searches archived tasks and `--all` searches both. A note on stderr reports hidden archived matches. This is purely a convenience hint and it is _omitted_ from JSON. `--limit <n>` caps the results.
238
270
 
239
271
  `--label` works as it does for `task list`: repeat it to require every specified label. Label filtering happens before `--limit` and before archived matches are counted.
@@ -440,6 +472,9 @@ zinn activity view 019abcdf-1234-7
440
472
 
441
473
  With `--json`, list returns an array and view returns one event object. Both include `id`, `created_at` (epoch milliseconds), `actor_name`, `actor_email`, `actor_kind`, `entity_type`, `entity_id`, `action`, and `changes` (parsed JSON or `null`). Payloads and IDs are preserved in full, including after deletion.
442
474
 
475
+ > [!WARNING]
476
+ > A readable task key can identify different tasks after a project is deleted and recreated. Group JSON records by (`entity_type`, `entity_id`) to keep their histories distinct. The `id` identifies the activity event itself. Project deletion events keep the project's `entity_id`, with removed task IDs in `changes.tasks`.
477
+
443
478
  When a coding agent performs a mutation with `zinn`, the change is recorded under that agent's name.
444
479
 
445
480
  Zinn recognizes Claude Code, Codex, OpenCode, Gemini CLI, Cline, Cursor, Copilot's coding agent, Crush, Amp, and any tool that sets `AI_AGENT`. If you are using a tool that Zinn does not recognize, you can set `AI_AGENT` in that tool's environment settings, for example `AI_AGENT=hermes`. Otherwise, Zinn uses your git `user.name` and `user.email`, and if that's also not set, it falls to your system username.
@@ -521,7 +556,10 @@ zinn task delete MDR-1 --yes --json
521
556
  ```
522
557
 
523
558
  - With `--json`, `--yes` is **required**. Without it, the command exits with an error and changes nothing.
524
- - 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`.
559
+ - Project deletion also requires a typed project key to skip confirmation; a configured default always needs confirmation and cannot be deleted with `--json`.
560
+ - Without a terminal, when stdin or stdout is redirected as in CI or a pipe, a command without `--yes` refuses before asking: it changes nothing and exits with code 1. Piped input such as `echo y` does not answer the prompt, so scripts that delete or restore must use `--yes`.
561
+ - Declining the prompt in a terminal changes nothing and exits with code 0.
562
+ - Confirmation prompts are written to stderr. Press Enter to decline; only `y` or `Y` confirms.
525
563
  - `task relation delete` never asks for confirmation and does not accept `--yes`.
526
564
 
527
565
  ## Help
package/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env bun
2
+ export {};
package/index.js ADDED
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env node
2
+ import packageJson from "./package.json" with { type: "json" };
3
+ const args = process.argv.slice(2);
4
+ const isVersionRequest = args.length === 1 && ["-v", "--version"].includes(args[0]);
5
+ if (isVersionRequest) {
6
+ console.info(packageJson.version);
7
+ }
8
+ else {
9
+ const { isHelpFlag } = await import("./src/lib.js");
10
+ const { createRouter } = await import("./src/routes/router.js");
11
+ const { routes } = await import("./src/routes/routes.js");
12
+ const router = createRouter(routes);
13
+ if (args.length === 0 || isHelpFlag(args[0])) {
14
+ console.info(router.help);
15
+ }
16
+ else {
17
+ const { configureDatabase } = await import("@zinn-dev/core");
18
+ const { cliOpenPolicy } = await import("./src/database.js");
19
+ // Only records the policy. core then opens the database when a command first uses it.
20
+ configureDatabase(cliOpenPolicy());
21
+ await router.route(args);
22
+ }
23
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zinn-dev/cli",
3
- "version": "0.38.0",
3
+ "version": "0.40.0",
4
4
  "description": "A kanban workflow in the terminal. Experimental.",
5
5
  "license": "MIT",
6
6
  "bugs": {
@@ -22,28 +22,32 @@
22
22
  "terminal",
23
23
  "bun"
24
24
  ],
25
- "module": "index.ts",
26
- "exports": {
27
- ".": {
28
- "types": "./index.ts",
29
- "import": "./index.ts"
30
- }
31
- },
32
25
  "files": [
33
- "index.ts",
34
- "src",
35
- "LICENSE",
36
- "release-stamp.json"
26
+ "index.js",
27
+ "index.d.ts",
28
+ "src/**/*.js",
29
+ "src/**/*.d.ts",
30
+ "LICENSE"
37
31
  ],
38
32
  "type": "module",
33
+ "engines": {
34
+ "node": ">=24.15.0"
35
+ },
36
+ "dependencies": {
37
+ "@zinn-dev/core": "0.29.0"
38
+ },
39
39
  "bin": {
40
- "zinn": "./index.ts"
40
+ "zinn": "./index.js"
41
+ },
42
+ "module": "index.js",
43
+ "types": "./index.d.ts",
44
+ "exports": {
45
+ ".": {
46
+ "types": "./index.d.ts",
47
+ "import": "./index.js"
48
+ }
41
49
  },
42
50
  "publishConfig": {
43
51
  "access": "public"
44
- },
45
- "dependencies": {
46
- "@zinn-dev/core": "0.27.0"
47
- },
48
- "scripts": {}
52
+ }
49
53
  }
package/src/actor.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ import type { Actor } from "@zinn-dev/core";
2
+ type Env = Record<string, string | undefined>;
3
+ /** A marker without a fixed name records the variable's own value, e.g. `AI_AGENT=claude-code_2-1-280_agent`. */
4
+ export declare function detectAgent(env: Env): Actor | null;
5
+ export declare function currentActor(): Actor;
6
+ export {};
package/src/actor.js ADDED
@@ -0,0 +1,62 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { userInfo } from "node:os";
3
+ /**
4
+ * Environment variables that coding agents set in the shells they run.
5
+ * Undetected tools can set `AI_AGENT` through their own env configuration.
6
+ */
7
+ const AGENT_MARKERS = [
8
+ { variables: ["AI_AGENT"], name: null },
9
+ { variables: ["AGENT"], name: null },
10
+ { variables: ["CLAUDECODE"], name: "claude-code" },
11
+ { variables: ["CODEX_THREAD_ID", "CODEX_SANDBOX"], name: "codex" },
12
+ { variables: ["OPENCODE"], name: "opencode" },
13
+ { variables: ["GEMINI_CLI"], name: "gemini-cli" },
14
+ { variables: ["CLINE_ACTIVE"], name: "cline" },
15
+ { variables: ["CURSOR_AGENT"], name: "cursor" },
16
+ { variables: ["COPILOT_AGENT_SESSION_ID"], name: "copilot" },
17
+ { variables: ["CRUSH"], name: "crush" },
18
+ ];
19
+ /** A marker without a fixed name records the variable's own value, e.g. `AI_AGENT=claude-code_2-1-280_agent`. */
20
+ export function detectAgent(env) {
21
+ for (const marker of AGENT_MARKERS) {
22
+ for (const variable of marker.variables) {
23
+ const value = env[variable]?.trim();
24
+ if (value == null || value.length === 0) {
25
+ continue;
26
+ }
27
+ return { name: marker.name ?? value, email: null, kind: "agent" };
28
+ }
29
+ }
30
+ return null;
31
+ }
32
+ function readGitConfig(key) {
33
+ try {
34
+ const value = execFileSync("git", ["config", key], {
35
+ encoding: "utf-8",
36
+ stdio: ["ignore", "pipe", "ignore"],
37
+ }).trim();
38
+ return value.length > 0 ? value : null;
39
+ }
40
+ catch {
41
+ // git is missing or the key is unset
42
+ return null;
43
+ }
44
+ }
45
+ function resolveActor() {
46
+ const agent = detectAgent(process.env);
47
+ if (agent != null) {
48
+ return agent;
49
+ }
50
+ const gitName = readGitConfig("user.name");
51
+ if (gitName != null) {
52
+ return { name: gitName, email: readGitConfig("user.email"), kind: "human" };
53
+ }
54
+ return { name: userInfo().username, email: null, kind: "human" };
55
+ }
56
+ let actor = null;
57
+ export function currentActor() {
58
+ if (actor == null) {
59
+ actor = resolveActor();
60
+ }
61
+ return actor;
62
+ }
@@ -0,0 +1,6 @@
1
+ import type { DatabaseFacts, LockWait, OpenPolicy } from "@zinn-dev/core";
2
+ /** Says once on stderr that the command waits for another process to finish with the database. */
3
+ export declare function reportLockWait({ budgetMs }: LockWait): void;
4
+ export declare function reportLegacyRead({ databasePath }: DatabaseFacts): void;
5
+ /** How the CLI asks core to open the database. */
6
+ export declare function cliOpenPolicy(): OpenPolicy;
@@ -0,0 +1,27 @@
1
+ import packageJson from "../package.json" with { type: "json" };
2
+ import { isLegacyReadAllowed } from "./lib.js";
3
+ import { RELEASE_MODE } from "./release-identity.js";
4
+ const MS_PER_SECOND = 1000;
5
+ /** Says once on stderr that the command waits for another process to finish with the database. */
6
+ export function reportLockWait({ budgetMs }) {
7
+ console.error(`Another process is using the database. Waiting up to ${budgetMs / MS_PER_SECOND} seconds for it to finish.`);
8
+ }
9
+ export function reportLegacyRead({ databasePath }) {
10
+ console.error(`Warning: the database at ${databasePath} has no schema version. Reads are best effort and may fail or omit data.`);
11
+ }
12
+ /** How the CLI asks core to open the database. */
13
+ export function cliOpenPolicy() {
14
+ return {
15
+ client: "cli",
16
+ version: packageJson.version,
17
+ // The script the CLI runs from; the runtime itself when there is none.
18
+ executable: process.argv[1] ?? process.execPath,
19
+ release: RELEASE_MODE,
20
+ // Read when the database opens, after the router has handled `--allow-legacy-read`
21
+ get allowsLegacyRead() {
22
+ return isLegacyReadAllowed();
23
+ },
24
+ onWait: reportLockWait,
25
+ onLegacyRead: reportLegacyRead,
26
+ };
27
+ }
package/src/lib.d.ts ADDED
@@ -0,0 +1,31 @@
1
+ import type { parseArgs } from "node:util";
2
+ type ParsedTokens = NonNullable<ReturnType<typeof parseArgs>["tokens"]>;
3
+ type OutputMode = "text" | "json";
4
+ export declare function setOutputMode(mode: OutputMode): void;
5
+ export declare function isJsonFlag(flag: string): flag is "--json";
6
+ export declare function isAllowLegacyReadFlag(flag: string): flag is "--allow-legacy-read";
7
+ export declare function setLegacyReadAllowed(allowed: boolean): void;
8
+ export declare function isLegacyReadAllowed(): boolean;
9
+ export declare function output<T>(data: T, transformToString: (data: T) => string): void;
10
+ /** Asks before a change that cannot be undone, unless --yes already confirmed it. */
11
+ export declare function confirmAction(message: string, isPreconfirmed: boolean, jsonRefusal?: string): Promise<boolean>;
12
+ /** Like confirmAction, without opening the database, for commands that bypass the open policy. */
13
+ export declare function askConfirmation(message: string, isPreconfirmed: boolean, jsonRefusal?: string): Promise<boolean>;
14
+ /** Whether someone can answer a prompt: stdin and stdout are both terminals, like how gh decides it. */
15
+ export declare function canPrompt(): boolean;
16
+ /** The message to report for a failed command, or fallback when the error has none. */
17
+ export declare function failureMessage(error: any, fallback: string): any;
18
+ /** Prints the reason as an error, followed by help when given, and exits with code 1. */
19
+ export declare function quit(reason: string, help?: string): never;
20
+ /** A command was given the wrong words. The router prints the message with the command's usage lines. */
21
+ export declare class UsageError extends Error {
22
+ }
23
+ /**
24
+ * Checks a command's words against its usage line, with the words written the same way:
25
+ * `<task-key>` is required, `[<project-key>]` is optional and `<task-key>...` repeats.
26
+ * Optional words go last.
27
+ */
28
+ export declare function validatePositionals(positionals: Array<string>, words: Array<string>): void;
29
+ export declare function validateUniqueOptions(tokens: ParsedTokens, repeatableOptions?: Array<string>): void;
30
+ export declare function isHelpFlag(flag: string): boolean;
31
+ export {};
package/src/lib.js ADDED
@@ -0,0 +1,137 @@
1
+ import { createInterface } from "node:readline/promises";
2
+ import { assertWritable, ReadOnlyDatabaseError, TextEditMatchError, UnmarkedDatabaseError, } from "@zinn-dev/core";
3
+ let outputMode = "text";
4
+ let legacyReadAllowed = false;
5
+ export function setOutputMode(mode) {
6
+ outputMode = mode;
7
+ }
8
+ export function isJsonFlag(flag) {
9
+ return flag === "--json";
10
+ }
11
+ export function isAllowLegacyReadFlag(flag) {
12
+ return flag === "--allow-legacy-read";
13
+ }
14
+ export function setLegacyReadAllowed(allowed) {
15
+ legacyReadAllowed = allowed;
16
+ }
17
+ export function isLegacyReadAllowed() {
18
+ return legacyReadAllowed;
19
+ }
20
+ export function output(data, transformToString) {
21
+ if (outputMode === "json") {
22
+ console.info(JSON.stringify(data, null, 2));
23
+ return;
24
+ }
25
+ const dataText = transformToString(data);
26
+ if (dataText.length > 0) {
27
+ console.info(dataText);
28
+ }
29
+ }
30
+ /** Asks before a change that cannot be undone, unless --yes already confirmed it. */
31
+ export async function confirmAction(message, isPreconfirmed, jsonRefusal) {
32
+ // Throws on a read-only database, to avoid asking for confirmation to an already refused action
33
+ assertWritable();
34
+ return askConfirmation(message, isPreconfirmed, jsonRefusal);
35
+ }
36
+ /** Like confirmAction, without opening the database, for commands that bypass the open policy. */
37
+ export async function askConfirmation(message, isPreconfirmed, jsonRefusal = "Commands that ask for confirmation need --yes when used with --json") {
38
+ if (isPreconfirmed) {
39
+ return true;
40
+ }
41
+ if (outputMode === "json") {
42
+ quit(jsonRefusal);
43
+ }
44
+ // Refuses rather than treating an unanswered prompt as declined, so scripts do not see a false success
45
+ if (!canPrompt()) {
46
+ quit("Commands that ask for confirmation need --yes when not running in a terminal");
47
+ }
48
+ const prompt = createInterface({ input: process.stdin, output: process.stderr });
49
+ const closed = new AbortController();
50
+ prompt.once("close", () => closed.abort());
51
+ prompt.once("SIGINT", () => process.kill(process.pid, "SIGINT"));
52
+ try {
53
+ const answer = await prompt.question(`${message} [y/N] `, { signal: closed.signal });
54
+ return answer === "y" || answer === "Y";
55
+ }
56
+ catch (error) {
57
+ if (closed.signal.aborted) {
58
+ return false;
59
+ }
60
+ throw error;
61
+ }
62
+ finally {
63
+ // Readline echoes a newline in a terminal; redirected stderr and EOF need one explicitly.
64
+ if (!process.stderr.isTTY || closed.signal.aborted) {
65
+ process.stderr.write("\n");
66
+ }
67
+ prompt.close();
68
+ }
69
+ }
70
+ /** Whether someone can answer a prompt: stdin and stdout are both terminals, like how gh decides it. */
71
+ export function canPrompt() {
72
+ return process.stdin.isTTY === true && process.stdout.isTTY === true;
73
+ }
74
+ /** The message to report for a failed command, or fallback when the error has none. */
75
+ export function failureMessage(error, fallback) {
76
+ const isOlderReadOnly = error instanceof ReadOnlyDatabaseError && error.reason === "older";
77
+ if (isOlderReadOnly) {
78
+ return `${error.message}. Run \`zinn migrate\` to upgrade it.`;
79
+ }
80
+ if (error instanceof UnmarkedDatabaseError) {
81
+ return `${error.message}. Add --allow-legacy-read to read it anyway.`;
82
+ }
83
+ if (error instanceof TextEditMatchError && error.matchCount > 1) {
84
+ return `${error.message} Use --all to replace every match.`;
85
+ }
86
+ if (error?.message === "no such table: task_search") {
87
+ return `${error.message}. Run \`zinn reindex\` to rebuild the search index.`;
88
+ }
89
+ return error?.message ?? fallback;
90
+ }
91
+ /** Prints the reason as an error, followed by help when given, and exits with code 1. */
92
+ export function quit(reason, help) {
93
+ if (outputMode === "json") {
94
+ const error = help == null ? { message: reason } : { message: reason, help };
95
+ console.error(JSON.stringify({ error }, null, 2));
96
+ }
97
+ else {
98
+ console.error(help == null ? reason : `${reason}\n\n${help}`);
99
+ }
100
+ process.exit(1);
101
+ }
102
+ /** A command was given the wrong words. The router prints the message with the command's usage lines. */
103
+ export class UsageError extends Error {
104
+ }
105
+ /**
106
+ * Checks a command's words against its usage line, with the words written the same way:
107
+ * `<task-key>` is required, `[<project-key>]` is optional and `<task-key>...` repeats.
108
+ * Optional words go last.
109
+ */
110
+ export function validatePositionals(positionals, words) {
111
+ const requiredWords = words.filter((word) => !word.startsWith("["));
112
+ const missingWord = requiredWords[positionals.length];
113
+ if (missingWord !== undefined) {
114
+ throw new UsageError(`Missing argument ${missingWord}`);
115
+ }
116
+ const hasRepeatingWord = words.some((word) => word.endsWith("..."));
117
+ const extraWord = positionals[words.length];
118
+ if (!hasRepeatingWord && extraWord !== undefined) {
119
+ throw new UsageError(`Unexpected argument "${extraWord}"`);
120
+ }
121
+ }
122
+ export function validateUniqueOptions(tokens, repeatableOptions = []) {
123
+ const parsedArgs = new Set();
124
+ for (const token of tokens) {
125
+ if (token.kind !== "option") {
126
+ continue;
127
+ }
128
+ const isRepeatable = repeatableOptions.includes(token.name);
129
+ if (parsedArgs.has(token.name) && !isRepeatable) {
130
+ quit(`Option "--${token.name}" can only be specified once`);
131
+ }
132
+ parsedArgs.add(token.name);
133
+ }
134
+ }
135
+ export function isHelpFlag(flag) {
136
+ return ["-h", "--help"].includes(flag);
137
+ }
@@ -0,0 +1,23 @@
1
+ import type { Activity, ActivityTaskIdentity } from "@zinn-dev/core";
2
+ type NavigationIdentity = {
3
+ /** Undefined when the entity no longer exists and this event recorded no name for it. */
4
+ name?: string;
5
+ status: "current" | "archived" | "deleted";
6
+ distinguishesTaskId?: boolean;
7
+ };
8
+ export type PresentedActivity = {
9
+ event: Activity;
10
+ displayId: string;
11
+ navigation: NavigationIdentity;
12
+ removedTasks: Array<ActivityTaskIdentity>;
13
+ };
14
+ /** Neighbors in sorted UUID order determine the shortest globally unique left prefix. */
15
+ export declare function abbreviateActivityIds(ids: Array<string>): Map<string, string>;
16
+ export declare function presentActivities(events: Array<Activity>, options?: {
17
+ taskKey?: string;
18
+ showsFullIds?: boolean;
19
+ }): Array<PresentedActivity>;
20
+ export declare function formatActivityList(entries: Array<PresentedActivity>, options?: {
21
+ showsDetails?: boolean;
22
+ }): string;
23
+ export {};