@zinn-dev/cli 0.42.0 → 0.44.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 (69) hide show
  1. package/README.md +1 -1
  2. package/index.js +3 -3
  3. package/package.json +6 -4
  4. package/skills/zinn/SKILL.md +1 -1
  5. package/src/actor.d.ts +8 -0
  6. package/src/actor.js +5 -1
  7. package/src/capabilities-schema.d.ts +4 -4
  8. package/src/column-hint.js +3 -4
  9. package/src/errors.d.ts +40 -3
  10. package/src/errors.js +93 -21
  11. package/src/failure-log.d.ts +6 -0
  12. package/src/failure-log.js +167 -0
  13. package/src/input.d.ts +11 -0
  14. package/src/input.js +25 -1
  15. package/src/lib.d.ts +21 -10
  16. package/src/lib.js +116 -62
  17. package/src/list-continuation.d.ts +11 -0
  18. package/src/list-continuation.js +18 -0
  19. package/src/list-limit.d.ts +11 -0
  20. package/src/list-limit.js +17 -0
  21. package/src/overview.d.ts +10 -0
  22. package/src/overview.js +41 -0
  23. package/src/presentation/activity-presentation.d.ts +2 -0
  24. package/src/presentation/activity-presentation.js +112 -38
  25. package/src/presentation/column-presentation.d.ts +17 -2
  26. package/src/presentation/column-presentation.js +45 -6
  27. package/src/presentation/description-presentation.d.ts +3 -16
  28. package/src/presentation/description-presentation.js +22 -21
  29. package/src/presentation/info-presentation.js +36 -6
  30. package/src/presentation/project-presentation.d.ts +6 -2
  31. package/src/presentation/project-presentation.js +9 -1
  32. package/src/presentation/relation-presentation.d.ts +12 -3
  33. package/src/presentation/relation-presentation.js +50 -26
  34. package/src/presentation/row-layout.d.ts +1 -1
  35. package/src/presentation/row-layout.js +6 -5
  36. package/src/presentation/task-blame-presentation.d.ts +11 -0
  37. package/src/presentation/task-blame-presentation.js +56 -0
  38. package/src/presentation/task-presentation.d.ts +6 -1
  39. package/src/presentation/task-presentation.js +28 -10
  40. package/src/presentation/text-width.d.ts +2 -0
  41. package/src/presentation/text-width.js +43 -0
  42. package/src/presentation/time.d.ts +3 -1
  43. package/src/presentation/time.js +5 -2
  44. package/src/result-schemas.d.ts +529 -18
  45. package/src/result-schemas.js +66 -4
  46. package/src/routes/activity-router.d.ts +53 -1
  47. package/src/routes/activity-router.js +126 -15
  48. package/src/routes/info-router.js +3 -2
  49. package/src/routes/migrate-router.js +2 -2
  50. package/src/routes/project-router.d.ts +41 -1
  51. package/src/routes/project-router.js +76 -24
  52. package/src/routes/relation-router.d.ts +7 -3
  53. package/src/routes/relation-router.js +73 -56
  54. package/src/routes/restore-router.js +10 -7
  55. package/src/routes/router.js +77 -37
  56. package/src/routes/routes.d.ts +213 -8
  57. package/src/routes/task-router.d.ts +119 -6
  58. package/src/routes/task-router.js +177 -32
  59. package/src/routes/whoami-router.js +1 -1
  60. package/src/run-facts.d.ts +14 -0
  61. package/src/run-facts.js +14 -0
  62. package/src/store-folder.d.ts +5 -0
  63. package/src/store-folder.js +16 -0
  64. package/src/telemetry.d.ts +31 -0
  65. package/src/telemetry.js +329 -0
  66. package/src/text-input.js +1 -5
  67. package/src/timestamp-input.d.ts +3 -0
  68. package/src/timestamp-input.js +31 -0
  69. package/src/types.d.ts +4 -4
@@ -1,12 +1,12 @@
1
1
  import { jsonResult } from "../results.js";
2
2
  import { parseArgs } from "node:util";
3
- import { column, project, columnOrderSchema, projectCreateSchema, projectEditSchema, } from "@zinn-dev/core";
3
+ import { column, project, columnOrderSchema, columnDeleteSchema, projectCreateSchema, projectEditSchema, } from "@zinn-dev/core";
4
4
  import { CliError } from "../errors.js";
5
5
  import { generateCommandUsage, getOptionInputs, noInput, violatesConstraint } from "../input.js";
6
6
  import { confirmationDescription, canPrompt, confirmAction, dashValueHelp, diagnostic, output, outputChanges, quit, validatePositionals, validateOrderForms, requireStringOption, validateUniqueOptions, } from "../lib.js";
7
7
  import { resolveTextEdit, textEditHelp, textEditOptions, textEditConstraints, } from "../text-edit.js";
8
8
  import { checkFieldsBeforeText, resolveTextInput, textFileHelp, textFileOption, textSourceConstraint, } from "../text-input.js";
9
- import { formatColumnList, presentColumn } from "../presentation/column-presentation.js";
9
+ import { formatColumnList, presentColumn, presentColumnTaskCounts, } from "../presentation/column-presentation.js";
10
10
  import { formatProjectList, presentProject } from "../presentation/project-presentation.js";
11
11
  import { formatSection } from "../presentation/section.js";
12
12
  import { currentActor } from "../actor.js";
@@ -110,6 +110,19 @@ const projectInputs = {
110
110
  ],
111
111
  constraints: [],
112
112
  },
113
+ column_delete: {
114
+ options: { yes: { type: "boolean" } },
115
+ forms: [
116
+ {
117
+ id: "default",
118
+ positionals: [
119
+ { name: "project-key", min: 1, max: 1, value: { kind: "project-key" } },
120
+ { name: "column-name", min: 1, max: 1, value: { kind: "column-name" } },
121
+ ],
122
+ },
123
+ ],
124
+ constraints: [],
125
+ },
113
126
  column_order: {
114
127
  options: {},
115
128
  forms: [
@@ -187,7 +200,7 @@ ${dashValueHelp("--description")}
187
200
  Example: zinn project create MDR --name 'Macrodata Refinement'`,
188
201
  },
189
202
  list: {
190
- summary: "List projects, their keys, and truncated description previews.",
203
+ summary: "List projects with active and archived task counts.",
191
204
  effects: { domain: "read", storage: "normal-open" },
192
205
  confirmation: { kind: "none" },
193
206
  input: projectInputs.list,
@@ -200,12 +213,16 @@ Example: zinn project create MDR --name 'Macrodata Refinement'`,
200
213
  strict: true,
201
214
  });
202
215
  validatePositionals(positionals, projectInputs.list.forms[0]);
203
- const projects = project.getAll();
204
- output(projects.map(presentProject), formatProjectList);
216
+ const projects = project
217
+ .getAllWithTaskCounts()
218
+ .map((entry) => ({ ...presentProject(entry), taskCounts: entry.taskCounts }));
219
+ output(projects, (entries) => formatProjectList(entries, { showsTaskCounts: true }));
205
220
  },
206
221
  help: `${generateCommandUsage("project list", projectInputs.list)}
207
222
 
208
- List projects, their keys, and truncated description previews.
223
+ List projects with active and archived task counts.
224
+ Active tasks are unarchived tasks in any column, including Done.
225
+ With --json, each project includes taskCounts: { active, archived }, including zeros.
209
226
 
210
227
  Example: zinn project list`,
211
228
  },
@@ -226,16 +243,12 @@ Example: zinn project list`,
226
243
  const projectKey = resolveProjectKey(positionals[0], { required: true });
227
244
  const projectMatch = project.getByKey(projectKey);
228
245
  if (projectMatch == null) {
229
- throw new CliError(`Project with key "${project.standardizeKey(projectKey)}" does not exist!`, "not_found", { entity: "project", key: project.standardizeKey(projectKey), source: "explicit" });
246
+ throw new CliError(`Project with key "${project.standardizeKey(projectKey)}" does not exist`, "not_found", { entity: "project", key: project.standardizeKey(projectKey), source: "explicit" });
230
247
  }
231
248
  const taskCounts = column.getTaskCountsByProjectKey(projectMatch.key);
232
249
  const presentedProject = {
233
250
  ...presentProject(projectMatch),
234
- columns: taskCounts.columns.map((columnCount) => ({
235
- id: columnCount.column.id,
236
- name: columnCount.column.name,
237
- taskCount: columnCount.taskCount,
238
- })),
251
+ columns: presentColumnTaskCounts(taskCounts),
239
252
  archivedTaskCount: taskCounts.archivedTaskCount,
240
253
  };
241
254
  output(presentedProject, (viewedProject) => {
@@ -244,11 +257,13 @@ Example: zinn project list`,
244
257
  if (viewedProject.description != null) {
245
258
  sections.push(formatSection("Description", viewedProject.description));
246
259
  }
247
- const columnTaskCounts = formatColumnList(viewedProject.columns, {
248
- showsTaskCounts: true,
249
- archivedTaskCount: viewedProject.archivedTaskCount,
250
- });
251
- sections.push(formatSection("Columns", columnTaskCounts));
260
+ if (viewedProject.columns.length > 0) {
261
+ const columnTaskCounts = formatColumnList(viewedProject.columns, {
262
+ showsTaskCounts: true,
263
+ archivedTaskCount: viewedProject.archivedTaskCount,
264
+ });
265
+ sections.push(formatSection("Columns", columnTaskCounts));
266
+ }
252
267
  return sections.join("\n\n");
253
268
  });
254
269
  },
@@ -332,7 +347,7 @@ Examples:
332
347
  try {
333
348
  const projectMatch = project.getByKey(projectKey);
334
349
  if (projectMatch == null) {
335
- throw new CliError(`Project with key "${projectKey}" does not exist!`, "not_found", {
350
+ throw new CliError(`Project with key "${projectKey}" does not exist`, "not_found", {
336
351
  entity: "project",
337
352
  key: projectKey,
338
353
  source: "explicit",
@@ -417,12 +432,7 @@ Example: zinn project column create MDR Boardlog`,
417
432
  });
418
433
  validatePositionals(positionals, projectInputs.column_list.forms[0]);
419
434
  const projectKey = resolveProjectKey(positionals[0], { required: true });
420
- const taskCounts = column.getTaskCountsByProjectKey(projectKey);
421
- const columns = taskCounts.columns.map((columnCount) => ({
422
- id: columnCount.column.id,
423
- name: columnCount.column.name,
424
- taskCount: columnCount.taskCount,
425
- }));
435
+ const columns = presentColumnTaskCounts(column.getTaskCountsByProjectKey(projectKey));
426
436
  output(columns, (presentedColumns) => formatColumnList(presentedColumns, {
427
437
  showsTaskCounts: true,
428
438
  }));
@@ -514,5 +524,47 @@ With --json, changed is false when the column was already in that position.
514
524
 
515
525
  Example: zinn project column order MDR Review before 'In Progress'`,
516
526
  },
527
+ delete: {
528
+ summary: "Delete an empty project column after confirmation.",
529
+ effects: { domain: "delete", storage: "normal-open" },
530
+ confirmation: { kind: "prompt", description: confirmationDescription },
531
+ input: projectInputs.column_delete,
532
+ results: [jsonResult("Column")],
533
+ run: async (args) => {
534
+ const { values, positionals, tokens } = parseArgs({
535
+ args,
536
+ options: projectInputs.column_delete.options,
537
+ allowPositionals: true,
538
+ strict: true,
539
+ tokens: true,
540
+ });
541
+ validateUniqueOptions(tokens, projectInputs.column_delete.options);
542
+ validatePositionals(positionals, projectInputs.column_delete.forms[0]);
543
+ const props = columnDeleteSchema.parse({
544
+ projectKey: positionals[0],
545
+ columnName: positionals[1],
546
+ });
547
+ const columnMatch = column.getByName(props.projectKey, props.columnName);
548
+ const presentedColumn = presentColumn(columnMatch);
549
+ const canDelete = await confirmAction(`Are you sure you want to delete column "${columnMatch.name}" from ${presentedColumn.project}?`, values.yes === true);
550
+ if (!canDelete) {
551
+ output(presentedColumn, (entry) => `Deletion cancelled for ${formatColumnList([entry], { showsProject: true })}`);
552
+ return;
553
+ }
554
+ const deletedColumn = column.delete(props, currentActor());
555
+ output(presentColumn(deletedColumn), (entry) => `Deleted ${formatColumnList([entry], { showsProject: true })}`);
556
+ },
557
+ help: `${generateCommandUsage("project column delete", projectInputs.column_delete)}
558
+
559
+ Delete an empty project column after confirmation.
560
+ Columns are matched by name, and matching is case-insensitive.
561
+ A column must hold no active or archived tasks. Use task move or task delete to clear it.
562
+ New tasks enter the project's first column unless --column selects another.
563
+ A project may have no columns. Add one with project column create before creating tasks.
564
+
565
+ Use --yes to skip the confirmation prompt, including with --json.
566
+
567
+ Example: zinn project column delete MDR Review`,
568
+ },
517
569
  },
518
570
  };
@@ -2,14 +2,18 @@ export declare const relationRouter: {
2
2
  create: {
3
3
  summary: string;
4
4
  effects: {
5
- domain: "create";
5
+ domain: "replace";
6
6
  storage: "normal-open";
7
7
  };
8
8
  confirmation: {
9
- kind: "none";
9
+ kind: "prompt";
10
+ description: string;
10
11
  };
11
12
  input: {
12
13
  readonly options: {
14
+ readonly yes: {
15
+ readonly type: "boolean";
16
+ };
13
17
  readonly type: {
14
18
  readonly type: "string";
15
19
  readonly required: true;
@@ -43,7 +47,7 @@ export declare const relationRouter: {
43
47
  guessedFlags: {
44
48
  [k: string]: (args: Array<string>) => string[] | undefined;
45
49
  };
46
- run: (args: string[]) => void;
50
+ run: (args: string[]) => Promise<void>;
47
51
  help: string;
48
52
  };
49
53
  list: {
@@ -2,9 +2,9 @@ import { parseArgs } from "node:util";
2
2
  import { relation, relationTypeSchema, task } from "@zinn-dev/core";
3
3
  import { jsonResult } from "../results.js";
4
4
  import { generateCommandUsage, taskKeyPositional } from "../input.js";
5
- import { output, quit, requireStringOption, validatePositionals, validateUniqueOptions, } from "../lib.js";
5
+ import { output, diagnostic, confirmAction, confirmationDescription, quit, requireStringOption, validatePositionals, validateUniqueOptions, } from "../lib.js";
6
6
  import { currentActor } from "../actor.js";
7
- import { formatRelationChange, formatRelationList, presentRelations, } from "../presentation/relation-presentation.js";
7
+ import { formatRelationChange, formatRelationList, presentRelations, presentRelationChange, } from "../presentation/relation-presentation.js";
8
8
  const guessedRelationTypes = new Map([
9
9
  ["depends-on", "dependency"],
10
10
  ["parent", "subtask"],
@@ -13,7 +13,7 @@ const guessedRelationTypes = new Map([
13
13
  ]);
14
14
  function relationFlagSuggestions(action) {
15
15
  const options = {
16
- ...relationInputs.create.options,
16
+ ...relationInputs[action].options,
17
17
  ...Object.fromEntries([...guessedRelationTypes.keys()].map((name) => [name, { type: "string" }])),
18
18
  };
19
19
  const suggest = (args) => {
@@ -44,17 +44,18 @@ function relationFlagSuggestions(action) {
44
44
  };
45
45
  return Object.fromEntries([...guessedRelationTypes.keys()].map((name) => [`--${name}`, suggest]));
46
46
  }
47
- function parseRelationArgs(args) {
47
+ function parseRelationArgs(args, action) {
48
+ const input = relationInputs[action];
48
49
  const { values, positionals, tokens } = parseArgs({
49
50
  args,
50
- options: relationInputs.create.options,
51
+ options: input.options,
51
52
  allowPositionals: true,
52
53
  strict: true,
53
54
  tokens: true,
54
55
  });
55
- validateUniqueOptions(tokens, relationInputs.create.options);
56
- validatePositionals(positionals, relationInputs.create.forms[0]);
57
- const type = requireStringOption(relationInputs.create.options.type, values.type, "type", `--type must be one of these: ${relationInputs.create.options.type.value.choices.join(", ")}`);
56
+ validateUniqueOptions(tokens, input.options);
57
+ validatePositionals(positionals, input.forms[0]);
58
+ const type = requireStringOption(relationPairInput.options.type, values.type, "type", `--type must be one of these: ${relationPairInput.options.type.value.choices.join(", ")}`);
58
59
  const typeResult = relationTypeSchema.safeParse(type);
59
60
  if (!typeResult.success) {
60
61
  quit(`--type must be one of these: ${relationTypeSchema.options.join(", ")}`, undefined, {
@@ -63,31 +64,39 @@ function parseRelationArgs(args) {
63
64
  }
64
65
  const sourceTaskKey = positionals[0];
65
66
  const targetTaskKey = positionals[1];
66
- return { sourceTaskKey, targetTaskKey, relation_type: typeResult.data };
67
+ return {
68
+ props: { sourceTaskKey, targetTaskKey, relation_type: typeResult.data },
69
+ isPreconfirmed: "yes" in values && values.yes === true,
70
+ };
67
71
  }
68
- const relationInputs = {
69
- create: {
70
- options: {
71
- type: {
72
- type: "string",
73
- required: true,
74
- value: {
75
- kind: "enum",
76
- choices: relationTypeSchema.options,
77
- },
72
+ const relationPairInput = {
73
+ options: {
74
+ type: {
75
+ type: "string",
76
+ required: true,
77
+ value: {
78
+ kind: "enum",
79
+ choices: relationTypeSchema.options,
78
80
  },
79
81
  },
80
- forms: [
81
- {
82
- id: "default",
83
- positionals: [
84
- { ...taskKeyPositional, name: "source-task-key" },
85
- { ...taskKeyPositional, name: "target-task-key" },
86
- ],
87
- },
88
- ],
89
- constraints: [],
90
82
  },
83
+ forms: [
84
+ {
85
+ id: "default",
86
+ positionals: [
87
+ { ...taskKeyPositional, name: "source-task-key" },
88
+ { ...taskKeyPositional, name: "target-task-key" },
89
+ ],
90
+ },
91
+ ],
92
+ constraints: [],
93
+ };
94
+ const relationInputs = {
95
+ create: {
96
+ ...relationPairInput,
97
+ options: { ...relationPairInput.options, yes: { type: "boolean" } },
98
+ },
99
+ delete: relationPairInput,
91
100
  list: {
92
101
  options: {},
93
102
  forms: [
@@ -101,31 +110,45 @@ const relationInputs = {
101
110
  };
102
111
  export const relationRouter = {
103
112
  create: {
104
- summary: "Create a relation between two tasks.",
105
- effects: { domain: "create", storage: "normal-open" },
106
- confirmation: { kind: "none" },
113
+ summary: "Create a relation, confirming replacement of conflicting links.",
114
+ effects: { domain: "replace", storage: "normal-open" },
115
+ confirmation: {
116
+ kind: "prompt",
117
+ description: `Only asks when replacing existing relations. ${confirmationDescription}`,
118
+ },
107
119
  input: relationInputs.create,
108
120
  results: [jsonResult("RelationChange")],
109
121
  guessedFlags: relationFlagSuggestions("create"),
110
- run: (args) => {
111
- const props = parseRelationArgs(args);
122
+ run: async (args) => {
123
+ const { props, isPreconfirmed } = parseRelationArgs(args, "create");
112
124
  const { sourceTaskKey, targetTaskKey } = props;
113
- const createdRelation = relation.create(props, currentActor());
114
125
  const source = task.getByKey(sourceTaskKey);
115
126
  const target = task.getByKey(targetTaskKey);
116
- const created = {
117
- id: createdRelation.id,
118
- type: props.relation_type,
119
- source: source.key,
120
- source_task_id: source.id,
121
- target: target.key,
122
- target_task_id: target.id,
123
- };
127
+ let replace = isPreconfirmed;
128
+ if (!isPreconfirmed) {
129
+ const conflicts = relation.getConflicts(props);
130
+ if (conflicts.length > 0) {
131
+ const canReplace = await confirmAction(formatRelationChange({ type: props.relation_type, source: source.key, target: target.key }, {
132
+ action: "replace",
133
+ replaced: conflicts.map((entry) => presentRelationChange(entry, entry.source, entry.target)),
134
+ }), false);
135
+ if (!canReplace) {
136
+ diagnostic("Relation creation cancelled");
137
+ return;
138
+ }
139
+ replace = conflicts.map((entry) => entry.id);
140
+ }
141
+ }
142
+ const createdRelation = relation.create({ ...props, replace }, currentActor());
143
+ const created = presentRelationChange(createdRelation, source, target);
124
144
  output(created, (entry) => formatRelationChange(entry, { action: "create" }));
125
145
  },
126
146
  help: `${generateCommandUsage("task relation create", relationInputs.create)}
127
147
 
128
148
  Create a relation between two tasks.
149
+ Each pair may have one relation. Changing its type or direction asks to replace the existing links.
150
+ Use --yes to authorize replacement without a prompt, including with --json or without a terminal.
151
+ An exact existing relation is an error, including with --yes.
129
152
 
130
153
  Types:
131
154
  related Connect two tasks, with any order provided to indicate relation.
@@ -133,8 +156,9 @@ Types:
133
156
  duplicate Source is a duplicate of target.
134
157
  subtask Source is a subtask of target (child -> parent).
135
158
 
136
- A task may have one parent and many subtasks. Nesting is allowed; cycles are rejected.
137
- Remove an existing subtask relation before assigning a different parent.
159
+ A task may have one parent and many subtasks. Nesting is allowed. Cycles are rejected.
160
+ Assigning a different parent asks to replace the previous parent link and any conflicting link to the new parent.
161
+ One confirmation covers every removed link. If those links change while confirmation is open, the command fails.
138
162
 
139
163
  Relations do not automatically move, complete, or archive tasks.
140
164
  Deleting a parent removes its links and preserves its subtasks.
@@ -170,25 +194,18 @@ Example: zinn task relation list APP-1`,
170
194
  summary: "Remove only the specified relation. No confirmation is required.",
171
195
  effects: { domain: "delete", storage: "normal-open" },
172
196
  confirmation: { kind: "none" },
173
- input: relationInputs.create,
197
+ input: relationInputs.delete,
174
198
  results: [jsonResult("RelationChange")],
175
199
  guessedFlags: relationFlagSuggestions("delete"),
176
200
  run: (args) => {
177
- const props = parseRelationArgs(args);
201
+ const { props } = parseRelationArgs(args, "delete");
178
202
  const deletedRelation = relation.delete(props, currentActor());
179
203
  const source = task.getByKey(props.sourceTaskKey);
180
204
  const target = task.getByKey(props.targetTaskKey);
181
- const deleted = {
182
- id: deletedRelation.id,
183
- type: props.relation_type,
184
- source: source.key,
185
- source_task_id: source.id,
186
- target: target.key,
187
- target_task_id: target.id,
188
- };
205
+ const deleted = presentRelationChange(deletedRelation, source, target);
189
206
  output(deleted, (entry) => formatRelationChange(entry, { action: "delete" }));
190
207
  },
191
- help: `${generateCommandUsage("task relation delete", relationInputs.create)}
208
+ help: `${generateCommandUsage("task relation delete", relationInputs.delete)}
192
209
 
193
210
  Remove only the specified relation. No confirmation is required.
194
211
 
@@ -1,6 +1,6 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { resolve } from "node:path";
3
- import { backup, RestoreRefusedError, getStorage } from "@zinn-dev/core";
3
+ import { backup, RestoreRefusedError, getBackupStorage, isSqliteErrorFamily } from "@zinn-dev/core";
4
4
  import { jsonResult } from "../results.js";
5
5
  import { reportLockWait } from "../database.js";
6
6
  import { confirmationDescription } from "../lib.js";
@@ -34,7 +34,8 @@ export const restoreCommand = {
34
34
  validateUniqueOptions(tokens, restoreInputs.command.options);
35
35
  validatePositionals(positionals, restoreInputs.command.forms[0]);
36
36
  const path = resolve(positionals[0]);
37
- const { databasePath, backupDirectory } = getStorage();
37
+ const storage = getBackupStorage();
38
+ const { databasePath, backupDirectory } = storage;
38
39
  const isPreconfirmed = values.yes === true;
39
40
  // A backup that would be refused is refused before the prompt.
40
41
  if (!isPreconfirmed) {
@@ -46,7 +47,12 @@ export const restoreCommand = {
46
47
  return;
47
48
  }
48
49
  try {
49
- const result = backup.restore({ ...build, path, onWait: reportLockWait });
50
+ const result = backup.restore({
51
+ ...build,
52
+ path,
53
+ storage,
54
+ onWait: reportLockWait,
55
+ });
50
56
  output(result, (r) => {
51
57
  const restored = `Restored the database from ${path} at schema version ${r.restoredVersion}.`;
52
58
  return r.backupPath == null
@@ -57,10 +63,7 @@ export const restoreCommand = {
57
63
  catch (error) {
58
64
  // A refusal attempted nothing, so only a failed restore points at the backups.
59
65
  if (!(error instanceof RestoreRefusedError)) {
60
- const isDamagedDatabase = error instanceof Error &&
61
- "code" in error &&
62
- typeof error.code === "string" &&
63
- error.code.startsWith("SQLITE_CORRUPT");
66
+ const isDamagedDatabase = isSqliteErrorFamily(error, "SQLITE_CORRUPT");
64
67
  if (isDamagedDatabase) {
65
68
  diagnostic(`The database at ${databasePath} is damaged. Nothing was changed. To restore it:\n` +
66
69
  `1. Close every program that has the database open.\n` +
@@ -1,13 +1,12 @@
1
1
  import { parseArgs } from "node:util";
2
- import { routerOptions, helpSpellings, versionSpellings, usageLabel } from "../input.js";
2
+ import { routerOptions, helpSpellings, versionSpellings, usageLabel, isAllowLegacyReadFlag, isHelpFlag, isRouterFlag, splitAtOptionSeparator, } from "../input.js";
3
3
  import { getCommandAliases } from "./aliases.js";
4
4
  import { classifyFailure, CliError } from "../errors.js";
5
5
  import { quotedColumnHint } from "../column-hint.js";
6
- import { dashValueHelp, diagnostic, failureMessage, flushDiagnostics, isAllowLegacyReadFlag, isHelpFlag, isRouterFlag, parseArgsMessage, prepareOutput, quit, renderFailure, setLegacyReadAllowed, UsageError, validateUniqueOptions, } from "../lib.js";
7
- // ZINN_DEBUG=1 prints routing detail on stderr, so stdout and `--json` results stay unchanged.
8
- function isDebugOutputEnabled() {
9
- return process.env.ZINN_DEBUG === "1";
10
- }
6
+ import { formatCell } from "../presentation/row-layout.js";
7
+ import { formatOverview } from "../overview.js";
8
+ import { boundParserMessage, dashValueHelp, diagnostic, failureMessage, finishRun, isDebugOutputEnabled, isParseArgsError, parseArgsFailure, prepareOutput, quit, renderFailure, setLegacyReadAllowed, UsageError, validateUniqueOptions, } from "../lib.js";
9
+ import { noteMatchedRun, noteParseArgsThrew, noteUnmatchedRun } from "../telemetry.js";
11
10
  function getIsRunnable(obj) {
12
11
  return Object.hasOwn(obj, "run");
13
12
  }
@@ -36,11 +35,18 @@ function getCommandHelp(help, aliases) {
36
35
  function toCommand(args) {
37
36
  return args.join(" ");
38
37
  }
39
- // Groups sibling commands into one line, e.g. " comment {create|list|edit|delete}".
40
- // A command without siblings is not a choice, so it gets no braces, e.g. " backup".
41
- // Top-level commands in the root help are unrelated to each other, so each gets its own line.
38
+ // Namespace help describes each command. Root help groups sibling names into choices.
42
39
  function formatCommands(parsedRoutes, prefix) {
43
40
  const isRootHelp = prefix === "";
41
+ if (!isRootHelp) {
42
+ const commands = parsedRoutes
43
+ .filter(({ command }) => command.startsWith(prefix))
44
+ .map(({ command, summary }) => ({ name: command.slice(prefix.length), summary }));
45
+ const nameWidth = Math.max(0, ...commands.map(({ name }) => name.length));
46
+ return commands
47
+ .map(({ name, summary }) => ` ${formatCell({ text: name }, nameWidth)} ${summary}`)
48
+ .join("\n");
49
+ }
44
50
  const siblingsByParent = new Map();
45
51
  for (const { command } of parsedRoutes) {
46
52
  if (!command.startsWith(prefix)) {
@@ -76,6 +82,9 @@ Options:
76
82
  Commands:
77
83
  ${formatCommands(parsedRoutes, "")}
78
84
 
85
+ What Zinn can do:
86
+ ${formatOverview()}
87
+
79
88
  Run zinn <namespace> --help or zinn <command> --help for more information.
80
89
  --help shows help for the command words before it and runs nothing. The rest of the line is ignored.
81
90
  -- ends the options; every word after it is positional, even if it starts with a dash.
@@ -104,20 +113,38 @@ function routeToNamespace(parsedRoutes, words, isHelpRequest) {
104
113
  const { namespace, wordCount, help } = findNearestNamespace(parsedRoutes, words);
105
114
  const unknownWord = words[wordCount];
106
115
  const commandName = namespace === "" ? "zinn" : `zinn ${namespace}`;
116
+ noteUnmatchedRun({
117
+ namespace,
118
+ help: isHelpRequest,
119
+ ...(unknownWord == null ? {} : { unmatchedWord: unknownWord }),
120
+ });
107
121
  if (unknownWord == null && isHelpRequest) {
108
122
  console.info(help);
109
123
  return;
110
124
  }
111
125
  if (unknownWord == null) {
112
- quit(`Missing a command for "${commandName}"`, help, { argument: "command" });
126
+ quit(`Missing a command for "${commandName}"`, help, {
127
+ argument: "command",
128
+ reason: "missing_command",
129
+ });
113
130
  }
114
131
  const reason = `Unrecognized command "${unknownWord}" for "${commandName}"`;
115
132
  if (isHelpRequest) {
116
- quit(reason, help, { argument: "command" });
133
+ quit(boundParserMessage(reason), help, { argument: "command", reason: "unknown_command" });
117
134
  }
118
- quit(`${reason}. Run \`${commandName} --help\` for a list of available commands`, undefined, {
119
- argument: "command",
120
- });
135
+ const guidance = `Run \`${commandName} --help\` for a list of available commands`;
136
+ throw new CliError(boundParserMessage(`${reason}. ${guidance}`, { reason, guidance }), "invalid_input", { argument: "command", reason: "unknown_command" }, undefined, namespace === "" ? [] : namespace.split(" "));
137
+ }
138
+ /** Resolves the longest canonical or alias command prefix. */
139
+ function findCommand(parsedRoutes, args) {
140
+ for (let endIndex = args.length; endIndex >= 0; endIndex--) {
141
+ const command = toCommand(args.slice(0, endIndex));
142
+ const match = parsedRoutes.find((route) => route.command === command || route.aliases.some((path) => toCommand(path) === command));
143
+ if (match !== undefined) {
144
+ return { match, nestingLevel: endIndex };
145
+ }
146
+ }
147
+ return undefined;
121
148
  }
122
149
  export function parseRoutes(routesDef, prefix) {
123
150
  const routeDefinitions = [];
@@ -147,9 +174,7 @@ export function parseRoutes(routesDef, prefix) {
147
174
  async function route(parsedRoutes, rawArgs, beforeRun) {
148
175
  prepareOutput(rawArgs);
149
176
  // Anything after "--" belongs to the command, so "--json" there is search text, not a flag.
150
- const separatorIndex = rawArgs.indexOf("--");
151
- const routableArgs = separatorIndex === -1 ? rawArgs : rawArgs.slice(0, separatorIndex);
152
- const passthroughArgs = separatorIndex === -1 ? [] : rawArgs.slice(separatorIndex);
177
+ const { optionWords: routableArgs, passthroughWords: passthroughArgs } = splitAtOptionSeparator(rawArgs);
153
178
  const filteredRoutableArgs = routableArgs.filter((arg) => !isRouterFlag(arg));
154
179
  if (routableArgs.some(isAllowLegacyReadFlag)) {
155
180
  setLegacyReadAllowed(true);
@@ -160,17 +185,10 @@ async function route(parsedRoutes, rawArgs, beforeRun) {
160
185
  const args = isHelpRequest
161
186
  ? filteredRoutableArgs.slice(0, helpFlagIndex)
162
187
  : [...filteredRoutableArgs, ...passthroughArgs];
163
- let match = null;
164
- let nestingLevel = 0;
165
- for (let endIndex = args.length; endIndex >= 0; endIndex--) {
166
- const command = toCommand(args.slice(0, endIndex));
167
- const matchedRoute = parsedRoutes.find((r) => r.command === command || r.aliases.some((path) => toCommand(path) === command));
168
- if (matchedRoute) {
169
- match = matchedRoute;
170
- nestingLevel = endIndex;
171
- break;
172
- }
173
- }
188
+ const { match, nestingLevel } = findCommand(parsedRoutes, args) ?? {
189
+ match: null,
190
+ nestingLevel: 0,
191
+ };
174
192
  if (isDebugOutputEnabled()) {
175
193
  diagnostic(`::router.route ${match?.command ?? "namespace"}`);
176
194
  }
@@ -178,24 +196,37 @@ async function route(parsedRoutes, rawArgs, beforeRun) {
178
196
  routeToNamespace(parsedRoutes, args, isHelpRequest);
179
197
  return;
180
198
  }
199
+ const commandArgs = args.slice(nestingLevel);
200
+ noteMatchedRun({
201
+ match,
202
+ typedRoute: toCommand(args.slice(0, nestingLevel)),
203
+ commandArgs,
204
+ help: isHelpRequest,
205
+ });
181
206
  if (isHelpRequest) {
182
207
  console.info(match.help);
183
208
  return;
184
209
  }
185
210
  validateRouterFlags(routableArgs);
186
- const commandArgs = args.slice(nestingLevel);
187
211
  try {
188
212
  await beforeRun?.(match);
189
213
  await match.run(commandArgs);
190
214
  }
191
215
  catch (err) {
216
+ if (isParseArgsError(err)) {
217
+ noteParseArgsThrew();
218
+ }
192
219
  if (err instanceof UsageError) {
193
220
  err.help = getUsage(match.help);
194
221
  }
195
222
  const columnHint = quotedColumnHint(err, match, rawArgs, nestingLevel);
196
223
  if (columnHint !== undefined) {
197
224
  const failure = classifyFailure(err);
198
- throw new CliError(`${failureMessage(err, "Command failed")}. Did you mean: ${columnHint}`, failure.code, failure.details, failure.help ?? getUsage(match.help));
225
+ const reason = failureMessage(err, "Command failed");
226
+ throw new CliError(boundParserMessage(`${reason}. Did you mean: ${columnHint}`, {
227
+ reason,
228
+ guidance: "Quote each column name containing spaces. Full command omitted because it is long.",
229
+ }), failure.code, { ...failure.details, reason: "unquoted_column" }, failure.help ?? getUsage(match.help), match.command.split(" "));
199
230
  }
200
231
  if (err instanceof UsageError) {
201
232
  throw err;
@@ -204,14 +235,23 @@ async function route(parsedRoutes, rawArgs, beforeRun) {
204
235
  const failure = classifyFailure(err);
205
236
  const isMissingProject = failure.code === "not_found" && failure.details?.entity === "project";
206
237
  if (isMissingProject) {
207
- throw new CliError(failureMessage(err, "Search failed"), failure.code, failure.details, getUsage(match.help));
238
+ throw new CliError(failureMessage(err, "Search failed"), failure.code, failure.details, getUsage(match.help), failure.suggestedRoute);
208
239
  }
209
240
  }
210
- const suggestFor = (flag) => match.guessedFlags?.[flag]?.(commandArgs);
211
- const parseArgsReason = parseArgsMessage(err, rawArgs, suggestFor);
212
- if (parseArgsReason != null) {
213
- const argument = /(?:Unknown option|Option) '(-[^' ]+)/.exec(err.message)?.[1];
214
- quit(parseArgsReason, getUsage(match.help), argument === undefined ? undefined : { argument });
241
+ const suggestFor = (flag) => {
242
+ const suggestion = match.guessedFlags?.[flag]?.(commandArgs);
243
+ if (suggestion === undefined) {
244
+ return undefined;
245
+ }
246
+ const target = findCommand(parsedRoutes, suggestion);
247
+ return target === undefined
248
+ ? undefined
249
+ : { args: suggestion, route: target.match.command.split(" ") };
250
+ };
251
+ const parserFailure = parseArgsFailure(err, rawArgs, suggestFor, match.command.split(" "));
252
+ if (parserFailure !== null) {
253
+ parserFailure.help = getUsage(match.help);
254
+ throw parserFailure;
215
255
  }
216
256
  throw err;
217
257
  }
@@ -222,7 +262,7 @@ export function createRouter(routesDef, beforeRun) {
222
262
  route: async (args) => {
223
263
  try {
224
264
  await route(parsedRoutes, args, beforeRun);
225
- flushDiagnostics();
265
+ finishRun();
226
266
  }
227
267
  catch (error) {
228
268
  renderFailure(error);