@zinn-dev/cli 0.38.0 → 0.39.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
@@ -19,27 +19,37 @@ Set `ZINN_DIR` to use another Zinn directory and keep using the same value for c
19
19
 
20
20
  ## Settings files
21
21
 
22
- Zinn reads two optional settings files:
22
+ 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.
23
23
 
24
- - `settings.json` in the Zinn directory (`~/.zinn`, or `ZINN_DIR` when it is set) holds the global settings.
24
+ Without `ZINN_DIR`, Zinn reads two optional settings files:
25
+
26
+ - `settings.json` in `~/.zinn` holds the global settings.
25
27
  - `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
28
 
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.
29
+ `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
30
 
29
31
  The files are plain JSON, without comments:
30
32
 
31
33
  ```json
32
34
  {
35
+ "$schema": "https://zinn.sh/schemas/settings/v1.json",
36
+ "defaultProject": "MDR",
33
37
  "storage": {
34
38
  "directory": "~/work/zinn-data"
35
39
  }
36
40
  }
37
41
  ```
38
42
 
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.
43
+ `$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
44
 
41
45
  `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
46
 
47
+ `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.
48
+
49
+ 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.
50
+
51
+ 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.
52
+
43
53
  ## Editing conventions
44
54
 
45
55
  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 +153,8 @@ zinn project column list MDR
143
153
 
144
154
  `project view` shows the project's description and task counts. Use `zinn task list <project-key>` to read its tasks.
145
155
 
156
+ `project view` and `project column list` accept an omitted project key when [defaultProject](#settings-files) is configured.
157
+
146
158
  `project column list` counts unarchived tasks. With `--json`, it returns `[{ "name": "Backlog", "taskCount": 3 }, ...]`.
147
159
 
148
160
  Edit a project:
@@ -154,6 +166,7 @@ zinn project edit MDR --description ""
154
166
  ```
155
167
 
156
168
  Provide `--name`, `--description`, or both.
169
+ The project key can be omitted when [defaultProject](#settings-files) is configured.
157
170
  See [Text values](#text-values) for values that begin with a dash and multi-line text.
158
171
 
159
172
  Add another column at the end of the board:
@@ -184,7 +197,7 @@ zinn project column order MDR Review after Done
184
197
  Directions follow board order: `first` is the start of the board and `last` is its end.
185
198
  Moving a column to the position it already has, or before or after itself, does nothing. Tasks stay in their columns.
186
199
 
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)).
200
+ `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
201
 
189
202
  ## Create and read tasks
190
203
 
@@ -195,6 +208,8 @@ zinn task create MDR --title "Refine 75% of the numbers"
195
208
  zinn task create MDR --title "Review the employee handbook" --description "Prepare for a 75% Dance Experience"
196
209
  ```
197
210
 
211
+ The project key can be omitted when [defaultProject](#settings-files) is configured.
212
+
198
213
  `--column <name>` starts the task at the bottom of a specific column. The column name matching is case insensitive:
199
214
 
200
215
  ```sh
@@ -206,13 +221,23 @@ Tasks are created with keys such as `MDR-1`. Task numbers increase in creation o
206
221
  ```sh
207
222
  zinn task list
208
223
  zinn task list MDR
224
+ zinn task list --all-projects
209
225
  zinn task list MDR --label CLI --label Groom
210
226
  zinn task list MDR --column "In Progress"
211
227
  zinn task list --column Done --all
212
228
  zinn task view MDR-1
229
+ zinn task view MDR-1 --history
213
230
  ```
214
231
 
215
- Task lists are previews, so they omit descriptions, but `task view` prints the full description.
232
+ Task lists are previews, so they _omit_ descriptions, but `task view` prints the full description.
233
+
234
+ An omitted project key uses [defaultProject](#settings-files), or every project when none is configured. `--all-projects` overrides the default.
235
+
236
+ `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.
237
+
238
+ 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_.
239
+
240
+ 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
241
 
217
242
  Repeat `--label <name>` to require every specified label. Matching ignores case.
218
243
 
@@ -224,6 +249,7 @@ Search task titles, descriptions, and comments, optionally in one project:
224
249
 
225
250
  ```sh
226
251
  zinn task search refine
252
+ zinn task search refine --all-projects
227
253
  zinn task search "quarterly quota" MDR
228
254
  zinn task search MDR-1
229
255
  zinn task search auth --all --limit 5
@@ -232,8 +258,12 @@ zinn task search auth MDR --label cli
232
258
 
233
259
  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
260
 
261
+ 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.
262
+
235
263
  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
264
 
265
+ An exact task-key query overrides the configured default project. A project key supplied after the query still filters the search.
266
+
237
267
  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
268
 
239
269
  `--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 +470,9 @@ zinn activity view 019abcdf-1234-7
440
470
 
441
471
  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
472
 
473
+ > [!WARNING]
474
+ > 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`.
475
+
443
476
  When a coding agent performs a mutation with `zinn`, the change is recorded under that agent's name.
444
477
 
445
478
  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 +554,9 @@ zinn task delete MDR-1 --yes --json
521
554
  ```
522
555
 
523
556
  - 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`.
557
+ - Project deletion also requires a typed project key to skip confirmation; a configured default always needs confirmation and cannot be deleted with `--json`.
558
+ - 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`.
559
+ - Declining the prompt in a terminal changes nothing and exits with code 0.
525
560
  - `task relation delete` never asks for confirmation and does not accept `--yes`.
526
561
 
527
562
  ## Help
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zinn-dev/cli",
3
- "version": "0.38.0",
3
+ "version": "0.39.0",
4
4
  "description": "A kanban workflow in the terminal. Experimental.",
5
5
  "license": "MIT",
6
6
  "bugs": {
@@ -43,7 +43,7 @@
43
43
  "access": "public"
44
44
  },
45
45
  "dependencies": {
46
- "@zinn-dev/core": "0.27.0"
46
+ "@zinn-dev/core": "0.28.0"
47
47
  },
48
48
  "scripts": {}
49
49
  }
package/src/lib.ts CHANGED
@@ -47,26 +47,40 @@ export function output<T>(data: T, transformToString: (data: T) => string) {
47
47
  }
48
48
 
49
49
  /** Asks before a change that cannot be undone, unless --yes already confirmed it. */
50
- export function confirmAction(message: string, isPreconfirmed: boolean) {
50
+ export function confirmAction(message: string, isPreconfirmed: boolean, jsonRefusal?: string) {
51
51
  // Throws on a read-only database, to avoid asking for confirmation to an already refused action
52
52
  assertWritable();
53
53
 
54
- return askConfirmation(message, isPreconfirmed);
54
+ return askConfirmation(message, isPreconfirmed, jsonRefusal);
55
55
  }
56
56
 
57
57
  /** Like confirmAction, without opening the database, for commands that bypass the open policy. */
58
- export function askConfirmation(message: string, isPreconfirmed: boolean) {
58
+ export function askConfirmation(
59
+ message: string,
60
+ isPreconfirmed: boolean,
61
+ jsonRefusal = "Commands that ask for confirmation need --yes when used with --json",
62
+ ) {
59
63
  if (isPreconfirmed) {
60
64
  return true;
61
65
  }
62
66
 
63
67
  if (outputMode === "json") {
64
- quit("Commands that ask for confirmation need --yes when used with --json");
68
+ quit(jsonRefusal);
69
+ }
70
+
71
+ // Refuses rather than treating an unanswered prompt as declined, so scripts do not see a false success
72
+ if (!canPrompt()) {
73
+ quit("Commands that ask for confirmation need --yes when not running in a terminal");
65
74
  }
66
75
 
67
76
  return confirm(message);
68
77
  }
69
78
 
79
+ /** Whether someone can answer a prompt: stdin and stdout are both terminals, like how gh decides it. */
80
+ export function canPrompt() {
81
+ return process.stdin.isTTY === true && process.stdout.isTTY === true;
82
+ }
83
+
70
84
  /** The message to report for a failed command, or fallback when the error has none. */
71
85
  export function failureMessage(error: any, fallback: string) {
72
86
  const isOlderReadOnly = error instanceof ReadOnlyDatabaseError && error.reason === "older";
@@ -37,7 +37,8 @@ test("activity details keep explicit empty containers distinct from null changes
37
37
  entity_type: "task", entity_id: "019abcdf-1234-7000-8000-123456abcde2",
38
38
  action: "create", changes: { labels: [], column: {} },
39
39
  };
40
- const entry = { event, displayId: event.id, removedTasks: [] };
40
+ const entry = { event, displayId: event.id, removedTasks: [],
41
+ navigation: { name: "APP-1", status: "current" as const } };
41
42
  const text = formatActivityList([entry], { showsDetails: true });
42
43
  expect(text).toContain("labels:\n[]");
43
44
  expect(text).toContain("column:\n{}");
@@ -45,6 +46,46 @@ test("activity details keep explicit empty containers distinct from null changes
45
46
  .toContain("Changes:\nnull");
46
47
  });
47
48
 
49
+ test("task rows for a shared key mark only deleted tasks and keep every task ID", () => {
50
+ const event: Activity = {
51
+ id: "019abcdf-1234-7000-8000-123456abcde1", created_at: 1,
52
+ actor_name: "Test", actor_email: null, actor_kind: "human",
53
+ entity_type: "task", entity_id: "current-task", action: "edit", changes: null,
54
+ };
55
+ const identities = [
56
+ { id: "current-task", status: "current" as const },
57
+ { id: "archived-task", status: "archived" as const },
58
+ { id: "first-deleted-task", status: "deleted" as const },
59
+ { id: "second-deleted-task", status: "deleted" as const },
60
+ ];
61
+ for (const identity of identities) {
62
+ const entry = {
63
+ event: { ...event, entity_id: identity.id }, displayId: event.id, removedTasks: [],
64
+ navigation: { name: "APP-1", status: identity.status, distinguishesTaskId: true },
65
+ };
66
+ const text = formatActivityList([entry]);
67
+ expect(text.split("\n")[0]!.split(" · ")[0]!.includes("deleted")).toBe(identity.status === "deleted");
68
+ expect(text).toContain(identity.id);
69
+ }
70
+ });
71
+
72
+ test("project deletion keeps its project and removed-task identities visible", () => {
73
+ const event: Activity = {
74
+ id: "019abcdf-1234-7000-8000-123456abcde1", created_at: 1,
75
+ actor_name: "Test", actor_email: null, actor_kind: "human",
76
+ entity_type: "project", entity_id: "old-project", action: "delete",
77
+ changes: { key: "APP", tasks: [{ id: "old-task", key: "APP-1", title: "Old task" }] },
78
+ };
79
+ const text = formatActivityList([{
80
+ event, displayId: event.id,
81
+ navigation: { name: "APP", status: "deleted" },
82
+ removedTasks: [{ id: "old-task", key: "APP-1", title: "Old task", status: "deleted" }],
83
+ }]);
84
+ expect(text.split("\n")[0]!.split(" · ")[0]).toContain("deleted");
85
+ expect(text).toContain("APP-1");
86
+ expect(text).toContain("old-task");
87
+ });
88
+
48
89
  test("long entity identities do not pad neighboring activity descriptions", () => {
49
90
  const event: Activity = {
50
91
  id: "019abcdf-1234-7000-8000-123456abcde1", created_at: 1,
@@ -57,7 +98,7 @@ test("long entity identities do not pad neighboring activity descriptions", () =
57
98
  const outlier = { ...short, displayId: "019abcda",
58
99
  event: { ...event, id: "019abcda-1234-7000-8000-123456abcde1", entity_type: "project" as const,
59
100
  action: "delete" as const, changes: { key: longKey, name: "Active ordering tail" } },
60
- navigation: { name: longKey, status: "recorded" as const } };
101
+ navigation: { name: longKey, status: "deleted" as const } };
61
102
  const alone = formatActivityList([short]);
62
103
  const together = formatActivityList([short, outlier]);
63
104
  expect(together.split("\n")[0]).toBe(alone);
@@ -15,15 +15,16 @@ import { formatSection } from "./section";
15
15
  import { formatLocalTime } from "./time";
16
16
 
17
17
  type NavigationIdentity = {
18
- name: string;
19
- status: "current" | "archived" | "deleted" | "recorded";
18
+ /** Undefined when the entity no longer exists and this event recorded no name for it. */
19
+ name?: string;
20
+ status: "current" | "archived" | "deleted";
20
21
  distinguishesTaskId?: boolean;
21
22
  };
22
23
 
23
24
  export type PresentedActivity = {
24
25
  event: Activity;
25
26
  displayId: string;
26
- navigation?: NavigationIdentity;
27
+ navigation: NavigationIdentity;
27
28
  removedTasks: Array<ActivityTaskIdentity>;
28
29
  };
29
30
 
@@ -231,14 +232,17 @@ export function presentActivities(
231
232
  const isSnapshot = event.action === "create" || event.action === "delete";
232
233
  const recordedName = event.changes?.key ?? event.changes?.name;
233
234
 
234
- if (navigation === undefined && isSnapshot && typeof recordedName === "string") {
235
- navigation = { name: recordedName, status: "recorded" };
235
+ // Every existing entity was found above, so it means that a missing one has been *deleted*.
236
+ if (navigation === undefined) {
237
+ navigation = {
238
+ name: isSnapshot && typeof recordedName === "string" ? recordedName : undefined,
239
+ status: "deleted",
240
+ };
236
241
  }
237
242
 
243
+ const isProjectDeletion = event.entity_type === "project" && event.action === "delete";
238
244
  const removedTaskIds =
239
- event.entity_type === "project" &&
240
- event.action === "delete" &&
241
- Array.isArray(event.changes?.tasks)
245
+ isProjectDeletion && Array.isArray(event.changes?.tasks)
242
246
  ? new Set(event.changes.tasks.filter(isRecord).map((snapshot) => snapshot.id))
243
247
  : new Set();
244
248
 
@@ -256,12 +260,13 @@ export function presentActivities(
256
260
 
257
261
  function formatNavigation(entry: PresentedActivity, options: { showsFullNames?: boolean } = {}) {
258
262
  const { event, navigation } = entry;
259
- if (navigation === undefined) {
260
- return `${event.entity_type} ${event.entity_id}`;
261
- }
262
-
263
263
  const identity = navigation.distinguishesTaskId ? `; ${event.entity_id}` : "";
264
- const name = options.showsFullNames ? navigation.name : formatDescriptionPreview(navigation.name);
264
+ const name =
265
+ navigation.name === undefined
266
+ ? event.entity_id
267
+ : options.showsFullNames
268
+ ? navigation.name
269
+ : formatDescriptionPreview(navigation.name);
265
270
  return `${event.entity_type} ${name} [${navigation.status}${identity}]`;
266
271
  }
267
272
 
@@ -312,7 +317,7 @@ function formatChangeSummary(
312
317
  options.omitsIdentity &&
313
318
  isSnapshot &&
314
319
  (field === "key" || field === "name") &&
315
- value === entry.navigation?.name;
320
+ value === entry.navigation.name;
316
321
  if (repeatsIdentity) {
317
322
  return null;
318
323
  }
@@ -362,36 +367,32 @@ function formatChangeSummary(
362
367
 
363
368
  function formatActivityContent(entry: PresentedActivity) {
364
369
  const { event, navigation } = entry;
365
- const name = navigation?.name ?? event.entity_id;
370
+ const name = navigation.name ?? event.entity_id;
366
371
  const shortName = formatDescriptionPreview(name, { maxLength: ENTITY_PREVIEW_LENGTH });
367
372
  const entityType =
368
- event.entity_type === "task" && navigation !== undefined ? "" : `${event.entity_type} `;
373
+ event.entity_type === "task" && navigation.name !== undefined ? "" : `${event.entity_type} `;
369
374
  const isMutableCurrentName =
370
- navigation?.status === "current" &&
375
+ navigation.status === "current" &&
371
376
  (event.entity_type === "label" || event.entity_type === "column");
372
- const provenance =
373
- navigation?.status === "recorded"
374
- ? " [recorded]"
375
- : isMutableCurrentName
376
- ? " [current name]"
377
- : "";
377
+ const marker =
378
+ navigation.status === "deleted" ? " [deleted]" : isMutableCurrentName ? " [current name]" : "";
378
379
  const action = ACTION_LABELS[event.action] ?? event.action;
379
380
  const summary = formatChangeSummary(entry, { showsRemovedTasks: false, omitsIdentity: true });
380
381
  const lines = [
381
- `${entityType}${shortName}${provenance} · ${action}${summary === "-" ? "" : `: ${summary}`}`,
382
+ `${entityType}${shortName}${marker} · ${action}${summary === "-" ? "" : `: ${summary}`}`,
382
383
  ];
383
384
 
384
385
  if (shortName !== name) {
385
386
  const nameLabel =
386
- navigation === undefined
387
+ navigation.name === undefined
387
388
  ? "Entity ID"
388
389
  : event.entity_type === "task" || event.entity_type === "project"
389
390
  ? `Full ${event.entity_type} key`
390
391
  : `Full ${event.entity_type} name`;
391
392
  lines.push(`${nameLabel}: ${name}`);
392
393
  }
393
- if (navigation?.distinguishesTaskId) {
394
- lines.push(`Task identity: ${navigation.status}; ${event.entity_id}`);
394
+ if (navigation.distinguishesTaskId) {
395
+ lines.push(`Task ID: ${event.entity_id}`);
395
396
  }
396
397
  lines.push(...formatRemovedTasks(entry));
397
398
  return lines.join("\n");
@@ -475,7 +476,7 @@ export function formatActivityList(
475
476
  [
476
477
  formatRows([rows[index]!]),
477
478
  formatSection("Entity", `${entry.event.entity_type} ${entry.event.entity_id}`),
478
- ...(entry.navigation === undefined
479
+ ...(entry.navigation.name === undefined
479
480
  ? []
480
481
  : [formatSection("Navigation", formatNavigation(entry, { showsFullNames: true }))]),
481
482
  formatSection(
@@ -0,0 +1,479 @@
1
+ import { expect, test } from "bun:test";
2
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+
6
+ import { runCliInTerminal } from "../testing";
7
+
8
+ const PREFIX = join(tmpdir(), "zinndefaulttest-");
9
+ // Each precedence matrix starts several dozen CLI processes.
10
+ const COMMAND_MATRIX_TIMEOUT_MS = 30_000;
11
+
12
+ function withTestDirectory(run: (directory: string) => void) {
13
+ const directory = mkdtempSync(PREFIX);
14
+
15
+ try {
16
+ run(directory);
17
+ } finally {
18
+ removeTestDirectory(directory);
19
+ }
20
+ }
21
+
22
+ // Same as withTestDirectory, but removes the directory only after an async run settles.
23
+ async function withTestDirectoryAsync(run: (directory: string) => Promise<void>) {
24
+ const directory = mkdtempSync(PREFIX);
25
+
26
+ try {
27
+ await run(directory);
28
+ } finally {
29
+ removeTestDirectory(directory);
30
+ }
31
+ }
32
+
33
+ function removeTestDirectory(directory: string) {
34
+ if (!directory.startsWith(PREFIX)) {
35
+ throw new Error(`Refusing to delete "${directory}": not a ${PREFIX}* directory`);
36
+ }
37
+
38
+ rmSync(directory, { recursive: true, force: true });
39
+ }
40
+
41
+ function runZinn(args: Array<string>, zinnDirectory: string) {
42
+ const proc = Bun.spawnSync(["bun", join(import.meta.dir, "..", "index.ts"), ...args], {
43
+ env: { ...process.env, ZINN_DIR: zinnDirectory },
44
+ });
45
+
46
+ return { stdout: proc.stdout.toString(), stderr: proc.stderr.toString(), code: proc.exitCode };
47
+ }
48
+
49
+ function runZinnFrom(
50
+ args: Array<string>,
51
+ directory: string,
52
+ cwd: string,
53
+ additionalEnv: Record<string, string> = {},
54
+ ) {
55
+ const env: Record<string, string | undefined> = { ...process.env, HOME: join(directory, "home") };
56
+ delete env.ZINN_DIR;
57
+ Object.assign(env, additionalEnv);
58
+ const cliPath = join(import.meta.dir, "..", "index.ts");
59
+ const proc = Bun.spawnSync(["bun", cliPath, ...args], { cwd, env });
60
+
61
+ return { stdout: proc.stdout.toString(), stderr: proc.stderr.toString(), code: proc.exitCode };
62
+ }
63
+
64
+ function runZinnWithPipedYes(args: Array<string>, directory: string, cwd: string) {
65
+ const env: Record<string, string | undefined> = { ...process.env, HOME: join(directory, "home") };
66
+ delete env.ZINN_DIR;
67
+ const cliPath = join(import.meta.dir, "..", "index.ts");
68
+ const proc = Bun.spawnSync(
69
+ ["/bin/sh", "-c", 'printf "y\\n" | exec bun "$@"', "zinn-confirm", cliPath, ...args],
70
+ { cwd, env },
71
+ );
72
+
73
+ return { stdout: proc.stdout.toString(), stderr: proc.stderr.toString(), code: proc.exitCode };
74
+ }
75
+
76
+ /** Runs the CLI attached to a pseudo-terminal and types the input; stdout and stderr arrive together. */
77
+ function runZinnInTerminal(args: Array<string>, directory: string, cwd: string, input: string) {
78
+ const env: Record<string, string | undefined> = { ...process.env, HOME: join(directory, "home") };
79
+ delete env.ZINN_DIR;
80
+
81
+ return runCliInTerminal(args, { cwd, env, input });
82
+ }
83
+
84
+ function makeRepository(directory: string, localSettings: Record<string, unknown> = {}) {
85
+ const repository = join(directory, "repository");
86
+ const globalDirectory = join(directory, "home", ".zinn");
87
+ mkdirSync(join(repository, ".git"), { recursive: true });
88
+ mkdirSync(globalDirectory, { recursive: true });
89
+ writeFileSync(join(globalDirectory, "settings.json"), JSON.stringify({ storage: { directory: join(directory, "store") } }));
90
+ writeFileSync(join(repository, "zinn.local.json"), JSON.stringify(localSettings));
91
+
92
+ return { repository, globalSettingsPath: join(globalDirectory, "settings.json"), localSettingsPath: join(repository, "zinn.local.json") };
93
+ }
94
+
95
+ function writeGlobalSettings(directory: string, settings: Record<string, unknown>) {
96
+ const globalSettingsPath = join(directory, "home", ".zinn", "settings.json");
97
+ writeFileSync(globalSettingsPath, JSON.stringify({ storage: { directory: join(directory, "store") }, ...settings }));
98
+ }
99
+
100
+ function seedProjects(directory: string, store = join(directory, "store")) {
101
+ expect(runZinn(["project", "create", "DEF", "--name", "Default"], store).code).toBe(0);
102
+ expect(runZinn(["project", "create", "ALT", "--name", "Alternate"], store).code).toBe(0);
103
+ expect(runZinn(["task", "create", "DEF", "--title", "needle default"], store).code).toBe(0);
104
+ expect(runZinn(["task", "create", "ALT", "--title", "needle alternate"], store).code).toBe(0);
105
+ expect(runZinn(["project", "column", "create", "DEF", "Only DEF"], store).code).toBe(0);
106
+ expect(runZinn(["project", "column", "create", "ALT", "Only ALT"], store).code).toBe(0);
107
+ }
108
+
109
+ test("ZINN_DIR selects an empty or populated store without applying the repository default", () => {
110
+ withTestDirectory((directory) => {
111
+ const { repository } = makeRepository(directory, { defaultProject: "DEF" });
112
+ const emptyStore = join(directory, "empty-store");
113
+ const emptyRun = (...args: Array<string>) => runZinnFrom(args, directory, repository, { ZINN_DIR: emptyStore });
114
+
115
+ for (const args of [["task", "list"], ["task", "search", "needle"]]) {
116
+ const result = emptyRun(...args, "--json");
117
+ expect(result.code).toBe(0);
118
+ expect(JSON.parse(result.stdout)).toEqual([]);
119
+ }
120
+
121
+ const populatedStore = join(directory, "populated-store");
122
+ seedProjects(directory, populatedStore);
123
+ const populatedRun = (...args: Array<string>) => runZinnFrom(args, directory, repository, { ZINN_DIR: populatedStore });
124
+ expect(JSON.parse(populatedRun("task", "list", "--json").stdout).map((task: { key: string }) => task.key).sort()).toEqual([
125
+ "ALT-1",
126
+ "DEF-1",
127
+ ]);
128
+ expect(JSON.parse(populatedRun("task", "search", "needle", "--json").stdout).map((task: { key: string }) => task.key).sort()).toEqual([
129
+ "ALT-1",
130
+ "DEF-1",
131
+ ]);
132
+ });
133
+ });
134
+
135
+ test("ZINN_DIR uses its own default and reports unknown defaults from its settings file", () => {
136
+ withTestDirectory((directory) => {
137
+ const { repository } = makeRepository(directory, { defaultProject: "DEF" });
138
+ const store = join(directory, "store");
139
+ mkdirSync(store, { recursive: true });
140
+ writeFileSync(join(store, "settings.json"), JSON.stringify({ defaultProject: "ALT" }));
141
+ seedProjects(directory, store);
142
+ const invoke = (...args: Array<string>) => runZinnFrom(args, directory, repository, { ZINN_DIR: store });
143
+
144
+ expect(JSON.parse(invoke("task", "list", "--json").stdout).map((task: { key: string }) => task.key)).toEqual(["ALT-1"]);
145
+ expect(JSON.parse(invoke("task", "search", "needle", "--json").stdout).map((task: { key: string }) => task.key)).toEqual(["ALT-1"]);
146
+
147
+ writeFileSync(join(store, "settings.json"), JSON.stringify({ defaultProject: "NOPE" }));
148
+ const unknown = invoke("task", "list", "--json");
149
+ expect(unknown.code).toBe(1);
150
+ expect(unknown.stderr).toContain("NOPE");
151
+ expect(unknown.stderr).toContain(join(store, "settings.json"));
152
+
153
+ expect(JSON.parse(invoke("task", "list", "ALT", "--json").stdout).map((task: { key: string }) => task.key)).toEqual(["ALT-1"]);
154
+ expect(JSON.parse(invoke("task", "list", "--all-projects", "--json").stdout)).toHaveLength(2);
155
+ expect(JSON.parse(invoke("task", "search", " alt-1 ", "--json").stdout).map((task: { key: string }) => task.key)).toEqual(["ALT-1"]);
156
+ });
157
+ });
158
+
159
+ test("ZINN_DIR ignores malformed repository and home settings but validates its own settings", () => {
160
+ withTestDirectory((directory) => {
161
+ const { repository, localSettingsPath, globalSettingsPath } = makeRepository(directory);
162
+ const store = join(directory, "store");
163
+ writeFileSync(localSettingsPath, "{");
164
+ writeFileSync(globalSettingsPath, "{");
165
+ const invoke = (...args: Array<string>) => runZinnFrom(args, directory, repository, { ZINN_DIR: store });
166
+
167
+ const ignoredMalformedFiles = invoke("task", "list", "--json");
168
+ expect(ignoredMalformedFiles.code).toBe(0);
169
+ expect(JSON.parse(ignoredMalformedFiles.stdout)).toEqual([]);
170
+ expect(ignoredMalformedFiles.stderr).not.toContain(localSettingsPath);
171
+ expect(ignoredMalformedFiles.stderr).not.toContain(globalSettingsPath);
172
+
173
+ const selectedStoreSettingsPath = join(store, "settings.json");
174
+ writeFileSync(selectedStoreSettingsPath, JSON.stringify({ defaultProject: 42 }));
175
+ const invalidSelectedStoreSettings = invoke("task", "list", "--json");
176
+ expect(invalidSelectedStoreSettings.code).toBe(1);
177
+ expect(invalidSelectedStoreSettings.stderr).toContain(selectedStoreSettingsPath);
178
+ expect(invalidSelectedStoreSettings.stderr).toContain("defaultProject");
179
+ });
180
+ });
181
+
182
+ async function expectDefaultCommands(directory: string, repository: string, expectedKey: string, otherKey: string) {
183
+ const invoke = (...args: Array<string>) => runZinnFrom(args, directory, repository);
184
+ const list = invoke("task", "list", "--json");
185
+ const search = invoke("task", "search", "needle", "--json");
186
+ const created = invoke("task", "create", "--title", "created by default", "--json");
187
+ const viewed = invoke("project", "view", "--json");
188
+ const columns = invoke("project", "column", "list", "--json");
189
+ const edited = invoke("project", "edit", "--name", "Edited by default", "--json");
190
+
191
+ expect(list.code).toBe(0);
192
+ expect(JSON.parse(list.stdout).map((task: { key: string }) => task.key)).toEqual([`${expectedKey}-1`]);
193
+ expect(search.code).toBe(0);
194
+ expect(JSON.parse(search.stdout).map((task: { key: string }) => task.key)).toEqual([`${expectedKey}-1`]);
195
+ expect(created.code).toBe(0);
196
+ expect(JSON.parse(created.stdout).key).toBe(`${expectedKey}-2`);
197
+ expect(viewed.code).toBe(0);
198
+ expect(JSON.parse(viewed.stdout).key).toBe(expectedKey);
199
+ expect(columns.code).toBe(0);
200
+ expect(JSON.parse(columns.stdout).map((column: { name: string }) => column.name)).toContain(`Only ${expectedKey}`);
201
+ expect(edited.code).toBe(0);
202
+ expect(JSON.parse(edited.stdout)).toMatchObject({ key: expectedKey, name: "Edited by default" });
203
+
204
+ const explicitList = invoke("task", "list", otherKey, "--json");
205
+ const explicitSearch = invoke("task", "search", "needle", otherKey, "--json");
206
+ const explicitCreate = invoke("task", "create", otherKey, "--title", "created explicitly", "--json");
207
+ const explicitView = invoke("project", "view", otherKey, "--json");
208
+ const explicitColumns = invoke("project", "column", "list", otherKey, "--json");
209
+ const explicitEdit = invoke("project", "edit", otherKey, "--name", "Edited explicitly", "--json");
210
+
211
+ expect(JSON.parse(explicitList.stdout).map((task: { key: string }) => task.key)).toEqual([`${otherKey}-1`]);
212
+ expect(JSON.parse(explicitSearch.stdout).map((task: { key: string }) => task.key)).toEqual([`${otherKey}-1`]);
213
+ expect(JSON.parse(explicitCreate.stdout).key).toBe(`${otherKey}-2`);
214
+ expect(JSON.parse(explicitView.stdout).key).toBe(otherKey);
215
+ expect(JSON.parse(explicitColumns.stdout).map((column: { name: string }) => column.name)).toContain(`Only ${otherKey}`);
216
+ expect(JSON.parse(explicitEdit.stdout)).toMatchObject({ key: otherKey, name: "Edited explicitly" });
217
+ expect(JSON.parse(invoke("task", "view", `${otherKey}-1`, "--json").stdout).key).toBe(`${otherKey}-1`);
218
+
219
+ const deleted = await runZinnInTerminal(["project", "delete"], directory, repository, "y\n");
220
+ expect(deleted.code).toBe(0);
221
+ expect(deleted.output).toContain(expectedKey);
222
+ expect(JSON.parse(invoke("project", "list", "--json").stdout).map((project: { key: string }) => project.key)).toEqual([otherKey]);
223
+ const explicitDelete = runZinnFrom(["project", "delete", otherKey, "--yes", "--json"], directory, repository);
224
+ expect(explicitDelete.code).toBe(0);
225
+ expect(JSON.parse(explicitDelete.stdout).key).toBe(otherKey);
226
+ }
227
+
228
+ test("each default-project command uses local settings, overrides global settings and yields to a typed key", async () => {
229
+ await withTestDirectoryAsync(async (directory) => {
230
+ makeRepository(directory, { defaultProject: "def" });
231
+ writeGlobalSettings(directory, { defaultProject: "ALT" });
232
+ seedProjects(directory);
233
+
234
+ await expectDefaultCommands(directory, join(directory, "repository"), "DEF", "ALT");
235
+ });
236
+ }, COMMAND_MATRIX_TIMEOUT_MS);
237
+
238
+ test("each default-project command falls back to global settings when local settings omit the field", async () => {
239
+ await withTestDirectoryAsync(async (directory) => {
240
+ makeRepository(directory, {});
241
+ writeGlobalSettings(directory, { defaultProject: "DEF" });
242
+ seedProjects(directory);
243
+
244
+ await expectDefaultCommands(directory, join(directory, "repository"), "DEF", "ALT");
245
+ });
246
+ }, COMMAND_MATRIX_TIMEOUT_MS);
247
+
248
+ test("commands without a default keep their existing project behavior, and task-key commands stay project-specific", () => {
249
+ withTestDirectory((directory) => {
250
+ const { repository } = makeRepository(directory);
251
+ seedProjects(directory);
252
+ const invoke = (...args: Array<string>) => runZinnFrom(args, directory, repository);
253
+
254
+ expect(JSON.parse(invoke("task", "list", "--json").stdout)).toHaveLength(2);
255
+ expect(JSON.parse(invoke("task", "search", "needle", "--json").stdout)).toHaveLength(2);
256
+ expect(JSON.parse(invoke("task", "list", "--all-projects", "--json").stdout)).toHaveLength(2);
257
+ expect(JSON.parse(invoke("task", "search", "needle", "--all-projects", "--json").stdout)).toHaveLength(2);
258
+ expect(invoke("task", "create", "--title", "needs a project").code).toBe(1);
259
+ expect(invoke("project", "view").code).toBe(1);
260
+ expect(invoke("project", "column", "list").code).toBe(1);
261
+ expect(invoke("project", "edit", "--name", "No project").code).toBe(1);
262
+ expect(invoke("project", "delete").code).toBe(1);
263
+ expect(JSON.parse(invoke("task", "view", "ALT-1", "--json").stdout).key).toBe("ALT-1");
264
+ });
265
+ });
266
+
267
+ test("all-projects bypasses an unknown default, conflicts with typed keys, and keeps list filters", () => {
268
+ withTestDirectory((directory) => {
269
+ const { repository } = makeRepository(directory, { defaultProject: "NOPE" });
270
+ seedProjects(directory);
271
+ const invoke = (...args: Array<string>) => runZinnFrom(args, directory, repository);
272
+
273
+ for (const args of [["task", "list"], ["task", "search", "needle"]]) {
274
+ const allProjects = invoke(...args, "--all-projects", "--json");
275
+ expect(allProjects.code).toBe(0);
276
+ expect(JSON.parse(allProjects.stdout)).toHaveLength(2);
277
+ const typedConflict = args[1] === "list"
278
+ ? invoke("task", "list", "ALT", "--all-projects", "--json")
279
+ : invoke("task", "search", "needle", "ALT", "--all-projects", "--json");
280
+ expect(typedConflict.code).toBe(1);
281
+ }
282
+
283
+ const defaultUnknown = invoke("task", "list", "--json");
284
+ expect(defaultUnknown.code).toBe(1);
285
+ expect(defaultUnknown.stderr).toContain("NOPE");
286
+ expect(defaultUnknown.stderr).toContain(join(repository, "zinn.local.json"));
287
+
288
+ writeFileSync(join(repository, "zinn.local.json"), JSON.stringify({ defaultProject: "DEF" }));
289
+ expect(runZinn(["task", "archive", "DEF-1"], join(directory, "store")).code).toBe(0);
290
+ const active = invoke("task", "list", "--all-projects", "--json");
291
+ const all = invoke("task", "list", "--all-projects", "--all", "--json");
292
+ const archived = invoke("task", "list", "--all-projects", "--archived", "--json");
293
+ const searchAll = invoke("task", "search", "needle", "--all-projects", "--all", "--json");
294
+ const searchArchived = invoke("task", "search", "needle", "--all-projects", "--archived", "--json");
295
+ expect(JSON.parse(active.stdout)).toHaveLength(1);
296
+ expect(JSON.parse(all.stdout)).toHaveLength(2);
297
+ expect(JSON.parse(archived.stdout).map((task: { key: string }) => task.key)).toEqual(["DEF-1"]);
298
+ expect(JSON.parse(searchAll.stdout)).toHaveLength(2);
299
+ expect(JSON.parse(searchArchived.stdout).map((task: { key: string }) => task.key)).toEqual(["DEF-1"]);
300
+ });
301
+ });
302
+
303
+ test("task-key search queries use the matching project instead of a default and keep an explicit project filter", () => {
304
+ withTestDirectory((directory) => {
305
+ const { repository } = makeRepository(directory, { defaultProject: "DEF" });
306
+ seedProjects(directory);
307
+ const invoke = (...args: Array<string>) => runZinnFrom(args, directory, repository);
308
+
309
+ expect(JSON.parse(invoke("task", "search", "needle", "--json").stdout).map((task: { key: string }) => task.key)).toEqual(["DEF-1"]);
310
+ expect(JSON.parse(invoke("task", "search", "ALT-1", "--json").stdout).map((task: { key: string }) => task.key)).toEqual(["ALT-1"]);
311
+
312
+ writeFileSync(join(repository, "zinn.local.json"), JSON.stringify({ defaultProject: "NOPE" }));
313
+ expect(JSON.parse(invoke("task", "search", " alt-1 ", "--json").stdout).map((task: { key: string }) => task.key)).toEqual(["ALT-1"]);
314
+
315
+ const filtered = invoke("task", "search", " ALT-1 ", "DEF", "--json");
316
+ expect(filtered.code).toBe(0);
317
+ expect(JSON.parse(filtered.stdout)).toEqual([]);
318
+
319
+ const conflict = invoke("task", "search", "ALT-1", "DEF", "--all-projects", "--json");
320
+ expect(conflict.code).toBe(1);
321
+ expect(conflict.stdout).toBe("");
322
+ expect(conflict.stderr).toContain("--all-projects");
323
+ });
324
+ });
325
+
326
+ test("task list and search report conflicting archive flags before resolving an unknown default", () => {
327
+ withTestDirectory((directory) => {
328
+ const { repository, localSettingsPath } = makeRepository(directory, { defaultProject: "NOPE" });
329
+ seedProjects(directory);
330
+ const invoke = (...args: Array<string>) => runZinnFrom(args, directory, repository);
331
+
332
+ for (const args of [["task", "list"], ["task", "search", "needle"]]) {
333
+ const result = invoke(...args, "--archived", "--all", "--json");
334
+ expect(result.code).toBe(1);
335
+ expect(result.stdout).toBe("");
336
+ expect(result.stderr).toContain("--archived");
337
+ expect(result.stderr).toContain("--all");
338
+ expect(result.stderr).not.toContain("NOPE");
339
+ expect(result.stderr).not.toContain(localSettingsPath);
340
+ }
341
+ });
342
+ });
343
+
344
+ test("a missing conditional project key reports its value and optional usage", () => {
345
+ withTestDirectory((directory) => {
346
+ const { repository } = makeRepository(directory);
347
+ seedProjects(directory);
348
+ const result = runZinnFrom(["project", "view", "--json"], directory, repository);
349
+
350
+ expect(result.code).toBe(1);
351
+ expect(result.stdout).toBe("");
352
+ const error = JSON.parse(result.stderr).error;
353
+ expect(error.message).toContain("<project-key>");
354
+ expect(error.message).toContain("defaultProject");
355
+ expect(error.help).toContain("Usage: zinn project view [<project-key>]");
356
+ });
357
+ });
358
+
359
+ test("unknown defaults identify their key and settings file", () => {
360
+ withTestDirectory((directory) => {
361
+ const { repository, globalSettingsPath, localSettingsPath } = makeRepository(directory, { defaultProject: "NOPE" });
362
+ seedProjects(directory);
363
+ const invoke = (...args: Array<string>) => runZinnFrom(args, directory, repository);
364
+ const assertUnknownDefaultDoesNotMutate = (settingsPath: string) => {
365
+ for (const args of [
366
+ ["project", "view", "--json"],
367
+ ["task", "create", "--title", "must not be created", "--json"],
368
+ ["project", "edit", "--name", "Must not be applied", "--json"],
369
+ ["project", "delete", "--yes"],
370
+ ]) {
371
+ const result = invoke(...args);
372
+ expect(result.code).toBe(1);
373
+ expect(result.stderr).toContain("NOPE");
374
+ expect(result.stderr).toContain(settingsPath);
375
+ }
376
+
377
+ expect(JSON.parse(invoke("project", "view", "DEF", "--json").stdout).name).toBe("Default");
378
+ expect(JSON.parse(invoke("task", "list", "DEF", "--json").stdout)).toHaveLength(1);
379
+ };
380
+
381
+ assertUnknownDefaultDoesNotMutate(localSettingsPath);
382
+
383
+ const explicitList = invoke("task", "list", "ALT", "--json");
384
+ const explicitSearch = invoke("task", "search", "needle", "ALT", "--json");
385
+ const explicitCreate = invoke("task", "create", "ALT", "--title", "typed key bypasses unknown default", "--json");
386
+ const explicitView = invoke("project", "view", "ALT", "--json");
387
+ const explicitColumns = invoke("project", "column", "list", "ALT", "--json");
388
+ const explicitEdit = invoke("project", "edit", "ALT", "--name", "Edited explicitly", "--json");
389
+ const explicitDelete = invoke("project", "delete", "ALT", "--yes", "--json");
390
+ expect(explicitList.code).toBe(0);
391
+ expect(explicitSearch.code).toBe(0);
392
+ expect(JSON.parse(explicitCreate.stdout).key).toBe("ALT-2");
393
+ expect(JSON.parse(explicitView.stdout).key).toBe("ALT");
394
+ expect(explicitColumns.code).toBe(0);
395
+ expect(JSON.parse(explicitEdit.stdout).name).toBe("Edited explicitly");
396
+ expect(JSON.parse(explicitDelete.stdout).key).toBe("ALT");
397
+ expect(JSON.parse(invoke("project", "view", "DEF", "--json").stdout).name).toBe("Default");
398
+
399
+ writeFileSync(join(repository, "zinn.local.json"), "{}");
400
+ writeGlobalSettings(directory, { defaultProject: "NOPE" });
401
+ assertUnknownDefaultDoesNotMutate(globalSettingsPath);
402
+ });
403
+ });
404
+
405
+ test("project delete with a default prompts despite --yes, and refuses without a terminal or with JSON", async () => {
406
+ const directory = mkdtempSync(PREFIX);
407
+
408
+ try {
409
+ const { repository } = makeRepository(directory, { defaultProject: "DEF" });
410
+ seedProjects(directory);
411
+ const jsonRefusal = runZinnFrom(["project", "delete", "--yes", "--json"], directory, repository);
412
+ expect(jsonRefusal.code).toBe(1);
413
+ expect(jsonRefusal.stdout).toBe("");
414
+ const refusal = JSON.parse(jsonRefusal.stderr);
415
+ expect(Object.keys(refusal)).toEqual(["error"]);
416
+ expect(Object.keys(refusal.error)).toEqual(["message"]);
417
+ expect(typeof refusal.error.message).toBe("string");
418
+ expect(JSON.parse(runZinnFrom(["project", "list", "--json"], directory, repository).stdout)).toHaveLength(2);
419
+
420
+ const noInput = runZinnFrom(["project", "delete", "--yes"], directory, repository);
421
+ const pipedInput = runZinnWithPipedYes(["project", "delete", "--yes"], directory, repository);
422
+ for (const result of [noInput, pipedInput]) {
423
+ expect(result.code).toBe(1);
424
+ expect(result.stdout).toBe("");
425
+ expect(result.stderr).toContain("zinn project delete DEF --yes");
426
+ }
427
+ expect(JSON.parse(runZinnFrom(["project", "list", "--json"], directory, repository).stdout)).toHaveLength(2);
428
+
429
+ const prompted = await runZinnInTerminal(["project", "delete", "--yes"], directory, repository, "y\n");
430
+ expect(prompted.code).toBe(0);
431
+ expect(prompted.output).toContain("--yes");
432
+ expect(prompted.output).toContain("Default");
433
+ expect(JSON.parse(runZinnFrom(["project", "list", "--json"], directory, repository).stdout).map((project: { key: string }) => project.key)).toEqual(["ALT"]);
434
+ } finally {
435
+ removeTestDirectory(directory);
436
+ }
437
+ });
438
+
439
+ test("malformed defaultProject settings still fail with a typed key or --all-projects", () => {
440
+ withTestDirectory((directory) => {
441
+ const { repository, localSettingsPath } = makeRepository(directory, { defaultProject: 42 });
442
+ seedProjects(directory);
443
+ const typed = runZinnFrom(["task", "list", "ALT", "--json"], directory, repository);
444
+ const allProjects = runZinnFrom(["task", "list", "--all-projects", "--json"], directory, repository);
445
+
446
+ for (const result of [typed, allProjects]) {
447
+ expect(result.code).toBe(1);
448
+ expect(result.stderr).toContain(localSettingsPath);
449
+ expect(result.stderr).toContain("defaultProject");
450
+ }
451
+ });
452
+ });
453
+
454
+ test("project delete with a typed key and --yes deletes without prompting", () => {
455
+ withTestDirectory((directory) => {
456
+ const { repository } = makeRepository(directory, { defaultProject: "DEF" });
457
+ seedProjects(directory);
458
+
459
+ const result = runZinnFrom(["project", "delete", "ALT", "--yes", "--json"], directory, repository);
460
+ expect(result.code).toBe(0);
461
+ expect(JSON.parse(result.stdout).key).toBe("ALT");
462
+ expect(JSON.parse(runZinnFrom(["project", "list", "--json"], directory, repository).stdout).map((project: { key: string }) => project.key)).toEqual(["DEF"]);
463
+ });
464
+ });
465
+
466
+ test("column writes still require an explicit project key when a default is set", () => {
467
+ withTestDirectory((directory) => {
468
+ const { repository } = makeRepository(directory, { defaultProject: "DEF" });
469
+ seedProjects(directory);
470
+ const invoke = (...args: Array<string>) => runZinnFrom(args, directory, repository);
471
+
472
+ expect(invoke("project", "column", "create", "Later", "--json").code).toBe(1);
473
+ expect(invoke("project", "column", "edit", "Backlog", "--name", "Later", "--json").code).toBe(1);
474
+ expect(invoke("project", "column", "order", "Backlog", "first", "--json").code).toBe(1);
475
+ const listedColumns = invoke("project", "column", "list", "--json");
476
+ expect(listedColumns.code).toBe(0);
477
+ expect(JSON.parse(listedColumns.stdout).map((column: { name: string }) => column.name)).toContain("Only DEF");
478
+ });
479
+ });
package/src/project.ts ADDED
@@ -0,0 +1,53 @@
1
+ import { homedir } from "node:os";
2
+ import { project, resolveSettings } from "@zinn-dev/core";
3
+ import { UsageError } from "./lib";
4
+
5
+ /** Chooses the explicit project or the configured default, retaining unscoped list/search behavior. */
6
+ export function resolveProjectKey(
7
+ typedKey: string | undefined,
8
+ {
9
+ required = false,
10
+ allProjects = false,
11
+ useDefault = true,
12
+ }: {
13
+ required?: boolean;
14
+ allProjects?: boolean;
15
+ useDefault?: boolean;
16
+ } = {},
17
+ ): string | undefined {
18
+ if (allProjects) {
19
+ if (typedKey !== undefined) {
20
+ throw new UsageError("--all-projects cannot be combined with a project key");
21
+ }
22
+ return undefined;
23
+ }
24
+
25
+ if (typedKey !== undefined) {
26
+ return typedKey;
27
+ }
28
+
29
+ if (!useDefault) {
30
+ return undefined;
31
+ }
32
+
33
+ const settings = resolveSettings({ cwd: process.cwd(), env: process.env, home: homedir() });
34
+ const defaultProject = settings.merged.defaultProject;
35
+ if (defaultProject === undefined) {
36
+ if (required) {
37
+ throw new UsageError(
38
+ "Missing argument <project-key>. Supply a key or configure defaultProject",
39
+ );
40
+ }
41
+ return undefined;
42
+ }
43
+
44
+ const settingsFile =
45
+ settings.local?.settings.defaultProject === undefined ? settings.global! : settings.local;
46
+ if (project.getByKey(defaultProject) == null) {
47
+ throw new Error(
48
+ `Default project "${defaultProject}" from settings file ${settingsFile.path} does not exist`,
49
+ );
50
+ }
51
+
52
+ return defaultProject;
53
+ }
@@ -46,6 +46,9 @@ Text times are local dates/times with a UTC offset.
46
46
  Event IDs are the shortest globally unique left prefixes of at least eight hex digits.
47
47
  Use activity view for full recorded changes; full IDs are durable, short prefixes may become ambiguous.
48
48
  With --json, output is an array of full activity records, with parsed changes or null.
49
+ Group JSON records by entity_type and entity_id to distinguish tasks sharing a readable key.
50
+ id identifies the activity event.
51
+ A project deletion event's entity_id is the project ID and removed task IDs are in changes.tasks.
49
52
 
50
53
  Examples:
51
54
  zinn activity list --limit 10
@@ -71,6 +74,7 @@ Accept a full UUID or unique left prefix with at least eight hexadecimal digits.
71
74
  Matching ignores case and accepts canonical hyphens or uninterrupted hexadecimal digits.
72
75
  An ambiguous prefix lists candidate IDs and requires more characters.
73
76
  With --json, output is one full activity record, with parsed changes or null.
77
+ id identifies this event itself, while entity_type and entity_id identify its affected entity.
74
78
 
75
79
  Example: zinn activity view 019abcdf-1234-7`,
76
80
  },
@@ -8,6 +8,7 @@ import { parseArgs } from "node:util";
8
8
 
9
9
  import { column, project } from "@zinn-dev/core";
10
10
  import {
11
+ canPrompt,
11
12
  confirmAction,
12
13
  failureMessage,
13
14
  output,
@@ -22,6 +23,7 @@ import { formatDescriptionPreview } from "../presentation/description-presentati
22
23
  import { formatCellSeparator, formatRows } from "../presentation/row-layout";
23
24
  import { formatSection } from "../presentation/section";
24
25
  import { currentActor } from "../actor";
26
+ import { resolveProjectKey } from "../project";
25
27
 
26
28
  type PresentedProject = { key: string; name: string; description: string | null };
27
29
  type PresentedProjectView = PresentedProject & {
@@ -120,9 +122,9 @@ Example: zinn project list`,
120
122
  view: {
121
123
  run: (args: Array<string>) => {
122
124
  const { positionals } = parseArgs({ args, allowPositionals: true, strict: true });
123
- validatePositionals(positionals, ["<project-key>"]);
125
+ validatePositionals(positionals, ["[<project-key>]"]);
124
126
 
125
- const projectKey = positionals[0]!;
127
+ const projectKey = resolveProjectKey(positionals[0], { required: true })!;
126
128
  const projectMatch = project.getByKey(projectKey);
127
129
 
128
130
  if (projectMatch == null) {
@@ -156,9 +158,11 @@ Example: zinn project list`,
156
158
  return sections.join("\n\n");
157
159
  });
158
160
  },
159
- help: `Usage: zinn project view <project-key>
161
+ help: `Usage: zinn project view [<project-key>]
160
162
 
161
163
  Show a project with its description and the number of tasks in each column.
164
+ An omitted project key uses defaultProject from settings, if present.
165
+ If no default project is set, the key is required.
162
166
  The description prints in full, keeping its line breaks. Archived tasks are counted as one total.
163
167
 
164
168
  Example: zinn project view MDR`,
@@ -174,9 +178,9 @@ Example: zinn project view MDR`,
174
178
  });
175
179
 
176
180
  validateUniqueOptions(tokens);
177
- validatePositionals(positionals, ["<project-key>"]);
181
+ validatePositionals(positionals, ["[<project-key>]"]);
178
182
 
179
- const projectKey = positionals[0]!;
183
+ const projectKey = resolveProjectKey(positionals[0], { required: true })!;
180
184
  const description = resolveTextEdit(values.description, values, "--description");
181
185
 
182
186
  if (values.name === undefined && description === undefined) {
@@ -189,9 +193,11 @@ Example: zinn project view MDR`,
189
193
  );
190
194
  output(presentProject(editedProject), formatProject);
191
195
  },
192
- help: `Usage: zinn project edit <project-key> [--name <text>] [--description <text> ${textEditUsage}]
196
+ help: `Usage: zinn project edit [<project-key>] [--name <text>] [--description <text> ${textEditUsage}]
193
197
 
194
198
  Change the supplied project fields. At least one edit flag is required.
199
+ An omitted project key uses defaultProject from settings, if present.
200
+ If no default project is set, the key is required.
195
201
  Use --description "" to clear the description.
196
202
 
197
203
  ${textEditHelp("--description")}
@@ -210,9 +216,10 @@ Examples:
210
216
  tokens: true,
211
217
  });
212
218
  validateUniqueOptions(tokens);
213
- validatePositionals(positionals, ["<project-key>"]);
219
+ validatePositionals(positionals, ["[<project-key>]"]);
214
220
 
215
- const projectKey = positionals[0]!;
221
+ const typedProjectKey = positionals[0];
222
+ const projectKey = resolveProjectKey(typedProjectKey, { required: true })!;
216
223
 
217
224
  try {
218
225
  const projectMatch = project.getByKey(projectKey);
@@ -221,9 +228,24 @@ Examples:
221
228
  throw new Error(`Project with key "${projectKey}" does not exist!`);
222
229
  }
223
230
 
231
+ // Like `gh repo delete`: --yes never skips the prompt for a project the command did not name
232
+ const isYesIgnored = values.yes === true && typedProjectKey === undefined;
233
+ if (isYesIgnored && !canPrompt()) {
234
+ quit(
235
+ `Cannot delete the default project ${projectMatch.key} without a terminal. Type its key to use --yes: zinn project delete ${projectMatch.key} --yes`,
236
+ );
237
+ }
238
+
239
+ if (isYesIgnored) {
240
+ console.error("Warning: --yes is ignored because no project key was typed");
241
+ }
242
+
224
243
  const canDelete = confirmAction(
225
244
  `Are you sure you want to delete ${projectMatch.key} and all of its columns and tasks?`,
226
- values.yes === true,
245
+ values.yes === true && typedProjectKey !== undefined,
246
+ typedProjectKey === undefined
247
+ ? "Project deletion with --json needs a typed <project-key> and --yes"
248
+ : undefined,
227
249
  );
228
250
 
229
251
  if (canDelete) {
@@ -236,10 +258,13 @@ Examples:
236
258
  quit(failureMessage(err, "Something went wrong"));
237
259
  }
238
260
  },
239
- help: `Usage: zinn project delete <project-key> [--yes]
261
+ help: `Usage: zinn project delete [<project-key>] [--yes]
240
262
 
241
263
  Permanently delete a project and all of its columns and tasks after confirmation.
242
- Use --yes to skip the confirmation prompt, for example in scripts or with --json.
264
+ An omitted project key uses defaultProject from settings, if present.
265
+ If no default project is set, the key is required.
266
+ With the default, confirmation is always required: --yes is ignored, and without a terminal the command refuses.
267
+ Use a typed project key and --yes to skip the prompt, including with --json.
243
268
 
244
269
  Example: zinn project delete MDR`,
245
270
  },
@@ -269,9 +294,10 @@ Example: zinn project column create MDR "Boardlog"`,
269
294
  list: {
270
295
  run: (args: Array<string>) => {
271
296
  const { positionals } = parseArgs({ args, allowPositionals: true, strict: true });
272
- validatePositionals(positionals, ["<project-key>"]);
297
+ validatePositionals(positionals, ["[<project-key>]"]);
273
298
 
274
- const taskCounts = column.getTaskCountsByProjectKey(positionals[0]!);
299
+ const projectKey = resolveProjectKey(positionals[0], { required: true })!;
300
+ const taskCounts = column.getTaskCountsByProjectKey(projectKey);
275
301
  const columns = taskCounts.columns.map((columnCount) => ({
276
302
  name: columnCount.column.name,
277
303
  taskCount: columnCount.taskCount,
@@ -282,9 +308,11 @@ Example: zinn project column create MDR "Boardlog"`,
282
308
  }),
283
309
  );
284
310
  },
285
- help: `Usage: zinn project column list <project-key>
311
+ help: `Usage: zinn project column list [<project-key>]
286
312
 
287
313
  List a project's columns in board order with their unarchived task counts.
314
+ An omitted project key uses defaultProject from settings, if present.
315
+ If no default project is set, the key is required.
288
316
 
289
317
  Example: zinn project column list MDR`,
290
318
  },
@@ -3,7 +3,13 @@ import type { RouteDef } from "../types";
3
3
  import type { PresentedTask } from "../presentation/task-presentation";
4
4
 
5
5
  import { parseArgs } from "node:util";
6
- import { task, project, positiveIntegerPattern, searchLimitMessage } from "@zinn-dev/core";
6
+ import {
7
+ task,
8
+ project,
9
+ positiveIntegerPattern,
10
+ searchLimitMessage,
11
+ parseTaskKey,
12
+ } from "@zinn-dev/core";
7
13
 
8
14
  import {
9
15
  confirmAction,
@@ -18,7 +24,9 @@ import { resolveTextEdit, textEditHelp, textEditOptions, textEditUsage } from ".
18
24
  import { formatRelations, presentRelations, relationRouter } from "./relation-router";
19
25
  import { commentRouter, formatComments, presentComments } from "./comment-router";
20
26
  import { currentActor } from "../actor";
27
+ import { resolveProjectKey } from "../project";
21
28
  import { formatSection } from "../presentation/section";
29
+ import { formatActivityList, presentActivities } from "../presentation/activity-presentation";
22
30
  import {
23
31
  formatTaskList,
24
32
  formatTaskListWithStatus,
@@ -47,9 +55,9 @@ export const taskRouter = {
47
55
  tokens: true,
48
56
  });
49
57
  validateUniqueOptions(tokens, ["label", "depends-on", "related"]);
50
- validatePositionals(positionals, ["<project-key>"]);
58
+ validatePositionals(positionals, ["[<project-key>]"]);
51
59
 
52
- const projectKey = positionals[0]!;
60
+ const projectKey = resolveProjectKey(positionals[0], { required: true })!;
53
61
  if (values.title === undefined) {
54
62
  quit("A task needs at least a title: use --title");
55
63
  }
@@ -71,9 +79,13 @@ export const taskRouter = {
71
79
  );
72
80
  output(presentTask(createdTask), formatTaskRow);
73
81
  },
74
- help: `Usage: zinn task create <project-key> --title <text> [--description <text>] [--priority {low|medium|high|urgent|none}] [--label <name>] [--column <name>] [--parent <task-key>] [--depends-on <task-key>] [--duplicate-of <task-key>] [--related <task-key>]
82
+ help: `Usage: zinn task create [<project-key>] --title <text> [--description <text>] [--priority {low|medium|high|urgent|none}] [--label <name>] [--column <name>] [--parent <task-key>] [--depends-on <task-key>] [--duplicate-of <task-key>] [--related <task-key>]
75
83
 
76
84
  Create a task at the bottom of a column. Without --column, it starts in the project's first column.
85
+
86
+ An omitted project key uses defaultProject from settings, if present.
87
+ If no default project is set, the key is required.
88
+
77
89
  Column names are matched case-insensitively. An unknown column is an error and creates nothing.
78
90
  Priority defaults to none (unassigned).
79
91
  Repeat --label to attach multiple existing labels. Unknown labels are errors.
@@ -97,6 +109,7 @@ Examples:
97
109
  options: {
98
110
  archived: { type: "boolean" },
99
111
  all: { type: "boolean" },
112
+ "all-projects": { type: "boolean" },
100
113
  label: { type: "string", multiple: true },
101
114
  column: { type: "string" },
102
115
  },
@@ -112,7 +125,7 @@ Examples:
112
125
  quit('Use either "--archived" or "--all", not both');
113
126
  }
114
127
 
115
- const projectKey = positionals[0];
128
+ const projectKey = resolveProjectKey(positionals[0], { allProjects: values["all-projects"] });
116
129
  const archive = values.all ? "all" : values.archived ? "archived" : "active";
117
130
 
118
131
  const tasks = task.getAll({
@@ -126,9 +139,12 @@ Examples:
126
139
  formatTaskList(presentedTasks, { showsStatus: values.all }),
127
140
  );
128
141
  },
129
- help: `Usage: zinn task list [<project-key>] [--archived|--all] [--label <name>] [--column <name>]
142
+ help: `Usage: zinn task list [<project-key>] [--all-projects] [--archived|--all] [--label <name>] [--column <name>]
130
143
 
131
144
  List active tasks by default.
145
+ An omitted project key uses defaultProject from settings, if present.
146
+ If no default project is set, the command lists every project.
147
+ Use --all-projects to list every project, overriding the default. It cannot be combined with a typed project key.
132
148
  Use --archived to list archived tasks or --all to list both.
133
149
  Use --label to filter for tasks with a specific label, no case-sensitivity is applied for matching.
134
150
  Use --column to filter by an exact column name without case sensitivty.
@@ -147,6 +163,7 @@ Example: zinn task list MDR --label cli`,
147
163
  options: {
148
164
  archived: { type: "boolean" },
149
165
  all: { type: "boolean" },
166
+ "all-projects": { type: "boolean" },
150
167
  limit: { type: "string" },
151
168
  label: { type: "string", multiple: true },
152
169
  },
@@ -159,7 +176,6 @@ Example: zinn task list MDR --label cli`,
159
176
  validatePositionals(positionals, ["<query>", "[<project-key>]"]);
160
177
 
161
178
  const query = positionals[0]!;
162
- const projectKey = positionals[1];
163
179
 
164
180
  if (values.archived && values.all) {
165
181
  quit('Use either "--archived" or "--all", not both');
@@ -172,6 +188,11 @@ Example: zinn task list MDR --label cli`,
172
188
  quit(searchLimitMessage);
173
189
  }
174
190
 
191
+ const isTaskKeyQuery = parseTaskKey(query.trim()) !== null;
192
+ const projectKey = resolveProjectKey(positionals[1], {
193
+ allProjects: values["all-projects"],
194
+ useDefault: !isTaskKeyQuery,
195
+ });
175
196
  const limit = values.limit === undefined ? undefined : Number(values.limit);
176
197
  const result = task.search({
177
198
  query,
@@ -191,13 +212,17 @@ Example: zinn task list MDR --label cli`,
191
212
  console.error(`${count} archived ${noun} hidden, use --all to include them`);
192
213
  }
193
214
  },
194
- help: `Usage: zinn task search <query> [<project-key>] [--archived|--all] [--limit <n>] [--label <name>]
215
+ help: `Usage: zinn task search <query> [<project-key>] [--all-projects] [--archived|--all] [--limit <n>] [--label <name>]
195
216
 
196
217
  Search task titles, descriptions, and comments. A comment match lists the task it belongs to.
218
+ An omitted project key uses defaultProject from settings, if present.
219
+ If no default project is set, the command searches every project.
220
+ Use --all-projects to search every project, overriding the default. It cannot be combined with a typed project key.
197
221
  Each word matches the start of a word, ignoring case and accents: e.g. "auth" finds "Authentication".
198
222
  Every word must match. Quote a query with several words.
199
223
 
200
224
  A query that is exactly a task key, such as MDR-1, lists that task first.
225
+ If given, a task key query overrides the configured default, and a typed project key still filters the search.
201
226
  Other results are ordered by relevance, with title matches weighted highest.
202
227
  Equally relevant tasks are ordered by project key, then task number.
203
228
 
@@ -211,7 +236,14 @@ Example: zinn task search "refinement quota" MDR --limit 5`,
211
236
  },
212
237
  view: {
213
238
  run: (args) => {
214
- const { positionals } = parseArgs({ args, allowPositionals: true, strict: true });
239
+ const { values, positionals, tokens } = parseArgs({
240
+ args,
241
+ options: { history: { type: "boolean" } },
242
+ allowPositionals: true,
243
+ strict: true,
244
+ tokens: true,
245
+ });
246
+ validateUniqueOptions(tokens);
215
247
  validatePositionals(positionals, ["<task-key>"]);
216
248
 
217
249
  const taskMatch = task.getByKey(positionals[0]!);
@@ -219,6 +251,16 @@ Example: zinn task search "refinement quota" MDR --limit 5`,
219
251
  ...presentTask(taskMatch),
220
252
  relations: presentRelations(taskMatch),
221
253
  comments: presentComments(taskMatch.key),
254
+ ...(values.history === true
255
+ ? {
256
+ activity: task
257
+ .activity(taskMatch.key)
258
+ .sort(
259
+ (left, right) =>
260
+ right.created_at - left.created_at || right.id.localeCompare(left.id),
261
+ ),
262
+ }
263
+ : {}),
222
264
  };
223
265
 
224
266
  output(viewedTask, (t) => {
@@ -249,15 +291,28 @@ Example: zinn task search "refinement quota" MDR --limit 5`,
249
291
  sections.push(formatSection("Comments", comments, sectionOptions));
250
292
  }
251
293
 
294
+ if (t.activity !== undefined) {
295
+ const history = formatActivityList(presentActivities(t.activity));
296
+ if (history.length > 0) {
297
+ sections.push(formatSection("History", history, sectionOptions));
298
+ }
299
+ }
300
+
252
301
  return sections.join("\n\n");
253
302
  });
254
303
  },
255
- help: `Usage: zinn task view <task-key>
304
+ help: `Usage: zinn task view <task-key> [--history]
256
305
 
257
306
  Show a task with its description, relations, and comments.
258
307
  A section is shown when the task has that content. The description prints in full, keeping its line breaks.
308
+ Use --history to include this task's recorded activity, newest first, including reorders and comment changes.
309
+ Use activity view <activity-id> for full recorded changes. Text times are local with a UTC offset.
310
+ With --history --json, the activity field contains full activity records, or [] when none are recorded.
311
+ Without --history, JSON omits activity.
259
312
 
260
- Example: zinn task view MDR-1`,
313
+ Examples:
314
+ zinn task view MDR-1
315
+ zinn task view MDR-1 --history`,
261
316
  },
262
317
  edit: {
263
318
  run: (args) => {