@zinn-dev/cli 0.41.0 → 0.43.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 (81) hide show
  1. package/README.md +11 -689
  2. package/index.js +2 -2
  3. package/package.json +4 -4
  4. package/skills/zinn/SKILL.md +1 -1
  5. package/src/capabilities-schema.d.ts +25 -26
  6. package/src/capabilities-schema.js +17 -82
  7. package/src/capabilities.d.ts +11 -3
  8. package/src/capabilities.js +12 -4
  9. package/src/column-hint.d.ts +3 -0
  10. package/src/column-hint.js +225 -0
  11. package/src/database.js +1 -4
  12. package/src/errors.d.ts +31 -3
  13. package/src/errors.js +77 -20
  14. package/src/input.d.ts +154 -43
  15. package/src/input.js +86 -13
  16. package/src/lib.d.ts +43 -6
  17. package/src/lib.js +134 -38
  18. package/src/list-continuation.d.ts +11 -0
  19. package/src/list-continuation.js +18 -0
  20. package/src/list-limit.d.ts +11 -0
  21. package/src/list-limit.js +17 -0
  22. package/src/presentation/activity-presentation.d.ts +9 -1
  23. package/src/presentation/activity-presentation.js +124 -28
  24. package/src/presentation/capabilities-presentation.d.ts +2 -0
  25. package/src/presentation/capabilities-presentation.js +3 -0
  26. package/src/presentation/column-presentation.d.ts +6 -0
  27. package/src/presentation/column-presentation.js +10 -0
  28. package/src/presentation/comment-presentation.d.ts +15 -0
  29. package/src/presentation/comment-presentation.js +29 -0
  30. package/src/presentation/description-presentation.d.ts +4 -0
  31. package/src/presentation/description-presentation.js +28 -5
  32. package/src/presentation/label-presentation.d.ts +8 -0
  33. package/src/presentation/label-presentation.js +28 -0
  34. package/src/presentation/project-presentation.d.ts +11 -0
  35. package/src/presentation/project-presentation.js +27 -0
  36. package/src/presentation/relation-presentation.d.ts +12 -0
  37. package/src/presentation/relation-presentation.js +87 -0
  38. package/src/presentation/row-layout.d.ts +1 -1
  39. package/src/presentation/row-layout.js +6 -5
  40. package/src/presentation/task-presentation.d.ts +3 -3
  41. package/src/presentation/task-presentation.js +29 -19
  42. package/src/presentation/text-width.d.ts +2 -0
  43. package/src/presentation/text-width.js +43 -0
  44. package/src/presentation/time.d.ts +3 -1
  45. package/src/presentation/time.js +5 -2
  46. package/src/project.d.ts +14 -5
  47. package/src/project.js +18 -6
  48. package/src/result-schemas.d.ts +279 -26
  49. package/src/result-schemas.js +72 -4
  50. package/src/results.d.ts +34 -17
  51. package/src/results.js +19 -0
  52. package/src/routes/activity-router.d.ts +79 -2
  53. package/src/routes/activity-router.js +209 -38
  54. package/src/routes/aliases.d.ts +2 -0
  55. package/src/routes/aliases.js +11 -0
  56. package/src/routes/capabilities-router.js +9 -3
  57. package/src/routes/comment-router.d.ts +41 -18
  58. package/src/routes/comment-router.js +65 -48
  59. package/src/routes/label-router.d.ts +57 -7
  60. package/src/routes/label-router.js +84 -39
  61. package/src/routes/project-router.d.ts +74 -12
  62. package/src/routes/project-router.js +131 -66
  63. package/src/routes/relation-router.d.ts +13 -9
  64. package/src/routes/relation-router.js +116 -116
  65. package/src/routes/restore-router.js +3 -6
  66. package/src/routes/router.d.ts +1 -1
  67. package/src/routes/router.js +88 -32
  68. package/src/routes/routes.d.ts +420 -50
  69. package/src/routes/routes.js +4 -0
  70. package/src/routes/task-router.d.ts +189 -30
  71. package/src/routes/task-router.js +254 -158
  72. package/src/routes/whoami-router.d.ts +21 -0
  73. package/src/routes/whoami-router.js +31 -0
  74. package/src/text-edit.d.ts +13 -9
  75. package/src/text-edit.js +23 -18
  76. package/src/text-input.d.ts +47 -0
  77. package/src/text-input.js +187 -0
  78. package/src/timestamp-input.d.ts +3 -0
  79. package/src/timestamp-input.js +31 -0
  80. package/src/types.d.ts +32 -9
  81. package/src/types.js +9 -1
@@ -1,76 +1,61 @@
1
- import { jsonResult } from "../results.js";
2
1
  import { parseArgs } from "node:util";
3
- import { column, relation, relationTypeSchema, task } from "@zinn-dev/core";
2
+ import { relation, relationTypeSchema, task } from "@zinn-dev/core";
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 { formatCellSeparator, formatRows } from "../presentation/row-layout.js";
8
- import { columnNameCell } from "../presentation/column-presentation.js";
9
- export function presentRelations(taskMatch) {
10
- return relation.getAll(taskMatch.key, { include: { tasks: true } }).map((entry) => {
11
- const isSource = entry.source_task_id === taskMatch.id;
12
- const other = isSource ? entry.target : entry.source;
13
- if (other == null) {
14
- throw new Error("Connected task details were not included in the relation");
7
+ import { formatRelationChange, formatRelationList, presentRelations, presentRelationChange, } from "../presentation/relation-presentation.js";
8
+ const guessedRelationTypes = new Map([
9
+ ["depends-on", "dependency"],
10
+ ["parent", "subtask"],
11
+ ["duplicate-of", "duplicate"],
12
+ ["related", "related"],
13
+ ]);
14
+ function relationFlagSuggestions(action) {
15
+ const options = {
16
+ ...relationInputs[action].options,
17
+ ...Object.fromEntries([...guessedRelationTypes.keys()].map((name) => [name, { type: "string" }])),
18
+ };
19
+ const suggest = (args) => {
20
+ const { positionals, tokens } = parseArgs({
21
+ args,
22
+ options,
23
+ allowPositionals: true,
24
+ strict: false,
25
+ tokens: true,
26
+ });
27
+ const relationFlags = tokens.filter((token) => token.kind === "option" && guessedRelationTypes.has(token.name));
28
+ const guessed = relationFlags[0];
29
+ if (positionals.length !== 1 || relationFlags.length !== 1 || guessed?.kind !== "option") {
30
+ return undefined;
15
31
  }
16
- let direction = null;
17
- if (entry.relation_type !== "related") {
18
- direction = isSource ? "outgoing" : "incoming";
32
+ const type = guessedRelationTypes.get(guessed.name);
33
+ const typeFlags = tokens.filter((token) => token.kind === "option" && token.name === "type");
34
+ const hasConflictingType = typeFlags.some((token) => token.kind === "option" && token.value !== type);
35
+ const hasOtherOption = tokens.some((token) => token.kind === "option" && token.name !== "type" && !guessedRelationTypes.has(token.name));
36
+ const cannotSuggestRelation = typeof guessed.value !== "string" ||
37
+ typeFlags.length > 1 ||
38
+ hasConflictingType ||
39
+ hasOtherOption;
40
+ if (cannotSuggestRelation) {
41
+ return undefined;
19
42
  }
20
- return {
21
- type: entry.relation_type,
22
- direction,
23
- task: {
24
- key: other.key,
25
- column: column.getById(other.column_id).name,
26
- title: other.title,
27
- status: other.archived_at == null ? "Active" : "Archived",
28
- },
29
- };
30
- });
43
+ return ["task", "relation", action, positionals[0], guessed.value, "--type", type];
44
+ };
45
+ return Object.fromEntries([...guessedRelationTypes.keys()].map((name) => [`--${name}`, suggest]));
31
46
  }
32
- export function formatRelations(relations) {
33
- return formatRows(relations.map((entry) => {
34
- const isOutgoing = entry.direction === "outgoing";
35
- let label = entry.type;
36
- switch (entry.type) {
37
- case "related": {
38
- label = "Related to";
39
- break;
40
- }
41
- case "dependency": {
42
- label = isOutgoing ? "Depends on" : "Depended on by";
43
- break;
44
- }
45
- case "subtask": {
46
- label = isOutgoing ? "Parent" : "Subtask";
47
- break;
48
- }
49
- case "duplicate": {
50
- label = isOutgoing ? "Duplicate of" : "Duplicated by";
51
- break;
52
- }
53
- }
54
- const archived = entry.task.status === "Archived" ? `${formatCellSeparator()}Archived` : "";
55
- return [
56
- { text: label },
57
- { text: entry.task.key },
58
- columnNameCell(entry.task.column),
59
- { text: `${entry.task.title}${archived}` },
60
- ];
61
- }));
62
- }
63
- function parseRelationArgs(args) {
47
+ function parseRelationArgs(args, action) {
48
+ const input = relationInputs[action];
64
49
  const { values, positionals, tokens } = parseArgs({
65
50
  args,
66
- options: relationInputs.create.options,
51
+ options: input.options,
67
52
  allowPositionals: true,
68
53
  strict: true,
69
54
  tokens: true,
70
55
  });
71
- validateUniqueOptions(tokens, relationInputs.create.options);
72
- validatePositionals(positionals, relationInputs.create.forms[0]);
73
- 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(", ")}`);
74
59
  const typeResult = relationTypeSchema.safeParse(type);
75
60
  if (!typeResult.success) {
76
61
  quit(`--type must be one of these: ${relationTypeSchema.options.join(", ")}`, undefined, {
@@ -79,32 +64,39 @@ function parseRelationArgs(args) {
79
64
  }
80
65
  const sourceTaskKey = positionals[0];
81
66
  const targetTaskKey = positionals[1];
82
- 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
+ };
83
71
  }
84
- const relationInputs = {
85
- create: {
86
- options: {
87
- type: {
88
- type: "string",
89
- required: true,
90
- value: {
91
- kind: "enum",
92
- name: "type",
93
- choices: relationTypeSchema.options,
94
- },
72
+ const relationPairInput = {
73
+ options: {
74
+ type: {
75
+ type: "string",
76
+ required: true,
77
+ value: {
78
+ kind: "enum",
79
+ choices: relationTypeSchema.options,
95
80
  },
96
81
  },
97
- forms: [
98
- {
99
- id: "default",
100
- positionals: [
101
- { ...taskKeyPositional, name: "source-task-key" },
102
- { ...taskKeyPositional, name: "target-task-key" },
103
- ],
104
- },
105
- ],
106
- constraints: [],
107
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,
108
100
  list: {
109
101
  options: {},
110
102
  forms: [
@@ -118,35 +110,45 @@ const relationInputs = {
118
110
  };
119
111
  export const relationRouter = {
120
112
  create: {
121
- summary: "Create a relation between two tasks.",
122
- effects: { domain: "create", storage: "normal-open" },
123
- 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
+ },
124
119
  input: relationInputs.create,
125
120
  results: [jsonResult("RelationChange")],
126
- run: (args) => {
127
- const props = parseRelationArgs(args);
121
+ guessedFlags: relationFlagSuggestions("create"),
122
+ run: async (args) => {
123
+ const { props, isPreconfirmed } = parseRelationArgs(args, "create");
128
124
  const { sourceTaskKey, targetTaskKey } = props;
129
- relation.create(props, currentActor());
130
125
  const source = task.getByKey(sourceTaskKey);
131
126
  const target = task.getByKey(targetTaskKey);
132
- const created = {
133
- type: props.relation_type,
134
- source: source.key,
135
- target: target.key,
136
- };
137
- output(created, (r) => {
138
- const label = {
139
- related: "related to",
140
- dependency: "depends on",
141
- duplicate: "is a duplicate of",
142
- subtask: "is a subtask of",
143
- }[r.type];
144
- return `${r.source} ${label} ${r.target}`;
145
- });
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);
144
+ output(created, (entry) => formatRelationChange(entry, { action: "create" }));
146
145
  },
147
146
  help: `${generateCommandUsage("task relation create", relationInputs.create)}
148
147
 
149
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.
150
152
 
151
153
  Types:
152
154
  related Connect two tasks, with any order provided to indicate relation.
@@ -154,8 +156,9 @@ Types:
154
156
  duplicate Source is a duplicate of target.
155
157
  subtask Source is a subtask of target (child -> parent).
156
158
 
157
- A task may have one parent and many subtasks. Nesting is allowed; cycles are rejected.
158
- 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.
159
162
 
160
163
  Relations do not automatically move, complete, or archive tasks.
161
164
  Deleting a parent removes its links and preserves its subtasks.
@@ -177,7 +180,7 @@ Example: zinn task relation create APP-1 APP-2 --type dependency`,
177
180
  strict: true,
178
181
  });
179
182
  validatePositionals(positionals, relationInputs.list.forms[0]);
180
- output(presentRelations(task.getByKey(positionals[0])), formatRelations);
183
+ output(presentRelations(task.getByKey(positionals[0])), formatRelationList);
181
184
  },
182
185
  help: `${generateCommandUsage("task relation list", relationInputs.list)}
183
186
 
@@ -191,21 +194,18 @@ Example: zinn task relation list APP-1`,
191
194
  summary: "Remove only the specified relation. No confirmation is required.",
192
195
  effects: { domain: "delete", storage: "normal-open" },
193
196
  confirmation: { kind: "none" },
194
- input: relationInputs.create,
197
+ input: relationInputs.delete,
195
198
  results: [jsonResult("RelationChange")],
199
+ guessedFlags: relationFlagSuggestions("delete"),
196
200
  run: (args) => {
197
- const props = parseRelationArgs(args);
198
- relation.delete(props, currentActor());
201
+ const { props } = parseRelationArgs(args, "delete");
202
+ const deletedRelation = relation.delete(props, currentActor());
199
203
  const source = task.getByKey(props.sourceTaskKey);
200
204
  const target = task.getByKey(props.targetTaskKey);
201
- const deleted = {
202
- type: props.relation_type,
203
- source: source.key,
204
- target: target.key,
205
- };
206
- output(deleted, (r) => `Deleted ${r.type} relation from ${r.source} to ${r.target}`);
205
+ const deleted = presentRelationChange(deletedRelation, source, target);
206
+ output(deleted, (entry) => formatRelationChange(entry, { action: "delete" }));
207
207
  },
208
- help: `${generateCommandUsage("task relation delete", relationInputs.create)}
208
+ help: `${generateCommandUsage("task relation delete", relationInputs.delete)}
209
209
 
210
210
  Remove only the specified relation. No confirmation is required.
211
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, getStorage, 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";
@@ -57,10 +57,7 @@ export const restoreCommand = {
57
57
  catch (error) {
58
58
  // A refusal attempted nothing, so only a failed restore points at the backups.
59
59
  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");
60
+ const isDamagedDatabase = isSqliteErrorFamily(error, "SQLITE_CORRUPT");
64
61
  if (isDamagedDatabase) {
65
62
  diagnostic(`The database at ${databasePath} is damaged. Nothing was changed. To restore it:\n` +
66
63
  `1. Close every program that has the database open.\n` +
@@ -80,7 +77,7 @@ Replace the database with the one in a backup file, such as one saved by \`zinn
80
77
 
81
78
  The current database is saved first, in the same place as \`zinn backup\`, and the restore is applied completely or not at all.
82
79
  A backup with an older schema version is restored at that version. Zinn then upgrades it like any older database: by itself, except for ~/.zinn run from a source checkout, which needs \`zinn migrate\`.
83
- Restoring onto a missing database creates it.
80
+ Restoring onto a missing database creates it inside an existing Zinn folder.
84
81
  Fails, leaving the database as it is, when the backup has a newer schema version than this Zinn or none at all, is damaged, or is not a Zinn database.
85
82
  Use --yes to skip the confirmation prompt, for example in scripts or with --json.
86
83
 
@@ -1,6 +1,6 @@
1
1
  import type { ParsedRoute, RouteDef } from "../types.js";
2
2
  export declare function parseRoutes(routesDef: RouteDef, prefix?: string): ParsedRoute[];
3
- export declare function createRouter(routesDef: RouteDef, beforeRun?: (command: ParsedRoute) => void | Promise<void>): {
3
+ export declare function createRouter(routesDef: RouteDef | Array<ParsedRoute>, beforeRun?: (command: ParsedRoute) => void | Promise<void>): {
4
4
  route: (args: Array<string>) => Promise<void>;
5
5
  help: string;
6
6
  };
@@ -1,6 +1,10 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { routerOptions, helpSpellings, versionSpellings, usageLabel } from "../input.js";
3
- import { dashValueHelp, diagnostic, flushDiagnostics, isAllowLegacyReadFlag, isHelpFlag, isRouterFlag, parseArgsMessage, prepareOutput, quit, renderFailure, setLegacyReadAllowed, UsageError, validateUniqueOptions, } from "../lib.js";
3
+ import { getCommandAliases } from "./aliases.js";
4
+ import { classifyFailure, CliError } from "../errors.js";
5
+ import { quotedColumnHint } from "../column-hint.js";
6
+ import { formatCell } from "../presentation/row-layout.js";
7
+ import { boundParserMessage, dashValueHelp, diagnostic, failureMessage, flushDiagnostics, isAllowLegacyReadFlag, isHelpFlag, isRouterFlag, parseArgsFailure, prepareOutput, quit, renderFailure, setLegacyReadAllowed, UsageError, validateUniqueOptions, } from "../lib.js";
4
8
  // ZINN_DEBUG=1 prints routing detail on stderr, so stdout and `--json` results stay unchanged.
5
9
  function isDebugOutputEnabled() {
6
10
  return process.env.ZINN_DEBUG === "1";
@@ -22,14 +26,29 @@ function validateRouterFlags(routableArgs) {
22
26
  function getUsage(help) {
23
27
  return help.split("\n\n")[0];
24
28
  }
29
+ function getCommandHelp(help, aliases) {
30
+ if (aliases.length === 0) {
31
+ return help;
32
+ }
33
+ const [usage, ...details] = help.split("\n\n");
34
+ const aliasLine = `Alias: ${aliases.map((path) => `zinn ${path.join(" ")}`).join(", ")}`;
35
+ return [usage, aliasLine, ...details].join("\n\n");
36
+ }
25
37
  function toCommand(args) {
26
38
  return args.join(" ");
27
39
  }
28
- // Groups sibling commands into one line, e.g. " comment {create|list|edit|delete}".
29
- // A command without siblings is not a choice, so it gets no braces, e.g. " backup".
30
- // Top-level commands in the root help are unrelated to each other, so each gets its own line.
40
+ // Namespace help describes each command. Root help groups sibling names into choices.
31
41
  function formatCommands(parsedRoutes, prefix) {
32
42
  const isRootHelp = prefix === "";
43
+ if (!isRootHelp) {
44
+ const commands = parsedRoutes
45
+ .filter(({ command }) => command.startsWith(prefix))
46
+ .map(({ command, summary }) => ({ name: command.slice(prefix.length), summary }));
47
+ const nameWidth = Math.max(0, ...commands.map(({ name }) => name.length));
48
+ return commands
49
+ .map(({ name, summary }) => ` ${formatCell({ text: name }, nameWidth)} ${summary}`)
50
+ .join("\n");
51
+ }
33
52
  const siblingsByParent = new Map();
34
53
  for (const { command } of parsedRoutes) {
35
54
  if (!command.startsWith(prefix)) {
@@ -52,7 +71,7 @@ function formatCommands(parsedRoutes, prefix) {
52
71
  }
53
72
  function getRootHelp(parsedRoutes) {
54
73
  // TODO: maybe "brand" text that is exported and used here for title and desc
55
- return `ZINN - A kanban workflow in the terminal
74
+ return `ZINN - A kanban workflow in the terminal. Experimental.
56
75
 
57
76
  ${usageLabel}zinn <command>
58
77
 
@@ -67,10 +86,8 @@ ${formatCommands(parsedRoutes, "")}
67
86
 
68
87
  Run zinn <namespace> --help or zinn <command> --help for more information.
69
88
  --help shows help for the command words before it and runs nothing. The rest of the line is ignored.
70
- -- ends the options: everything after it is considered a plain word, even if it starts with a dash (e.g. 'zinn project column create SHOP -- -later').
71
- Flags after it are not read.
72
- ${dashValueHelp("--description")}
73
- Running zinn without a command shows this help.`;
89
+ -- ends the options; every word after it is positional, even if it starts with a dash.
90
+ ${dashValueHelp("--description")}`;
74
91
  }
75
92
  function getNamespaceHelp(parsedRoutes, namespace) {
76
93
  const commands = formatCommands(parsedRoutes, `${namespace} `);
@@ -100,15 +117,28 @@ function routeToNamespace(parsedRoutes, words, isHelpRequest) {
100
117
  return;
101
118
  }
102
119
  if (unknownWord == null) {
103
- quit(`Missing a command for "${commandName}"`, help, { argument: "command" });
120
+ quit(`Missing a command for "${commandName}"`, help, {
121
+ argument: "command",
122
+ reason: "missing_command",
123
+ });
104
124
  }
105
125
  const reason = `Unrecognized command "${unknownWord}" for "${commandName}"`;
106
126
  if (isHelpRequest) {
107
- quit(reason, help, { argument: "command" });
127
+ quit(boundParserMessage(reason), help, { argument: "command", reason: "unknown_command" });
108
128
  }
109
- quit(`${reason}. Run \`${commandName} --help\` for a list of available commands`, undefined, {
110
- argument: "command",
111
- });
129
+ const guidance = `Run \`${commandName} --help\` for a list of available commands`;
130
+ throw new CliError(boundParserMessage(`${reason}. ${guidance}`, { reason, guidance }), "invalid_input", { argument: "command", reason: "unknown_command" }, undefined, namespace === "" ? [] : namespace.split(" "));
131
+ }
132
+ /** Resolves the longest canonical or alias command prefix. */
133
+ function findCommand(parsedRoutes, args) {
134
+ for (let endIndex = args.length; endIndex >= 0; endIndex--) {
135
+ const command = toCommand(args.slice(0, endIndex));
136
+ const match = parsedRoutes.find((route) => route.command === command || route.aliases.some((path) => toCommand(path) === command));
137
+ if (match !== undefined) {
138
+ return { match, nestingLevel: endIndex };
139
+ }
140
+ }
141
+ return undefined;
112
142
  }
113
143
  export function parseRoutes(routesDef, prefix) {
114
144
  const routeDefinitions = [];
@@ -120,7 +150,13 @@ export function parseRoutes(routesDef, prefix) {
120
150
  const isRunnable = getIsRunnable(definition);
121
151
  const combinedRoute = prefix ? `${prefix} ${key}` : key;
122
152
  if (isRunnable) {
123
- routeDefinitions.push({ command: combinedRoute, ...definition });
153
+ const aliases = getCommandAliases(combinedRoute);
154
+ routeDefinitions.push({
155
+ ...definition,
156
+ command: combinedRoute,
157
+ aliases,
158
+ help: getCommandHelp(definition.help, aliases),
159
+ });
124
160
  }
125
161
  else {
126
162
  const result = parseRoutes(definition, combinedRoute);
@@ -145,17 +181,10 @@ async function route(parsedRoutes, rawArgs, beforeRun) {
145
181
  const args = isHelpRequest
146
182
  ? filteredRoutableArgs.slice(0, helpFlagIndex)
147
183
  : [...filteredRoutableArgs, ...passthroughArgs];
148
- let match = null;
149
- let nestingLevel = 0;
150
- for (let endIndex = args.length; endIndex >= 0; endIndex--) {
151
- const command = toCommand(args.slice(0, endIndex));
152
- const matchedRoute = parsedRoutes.find((r) => r.command === command);
153
- if (matchedRoute) {
154
- match = matchedRoute;
155
- nestingLevel = endIndex;
156
- break;
157
- }
158
- }
184
+ const { match, nestingLevel } = findCommand(parsedRoutes, args) ?? {
185
+ match: null,
186
+ nestingLevel: 0,
187
+ };
159
188
  if (isDebugOutputEnabled()) {
160
189
  diagnostic(`::router.route ${match?.command ?? "namespace"}`);
161
190
  }
@@ -176,19 +205,46 @@ async function route(parsedRoutes, rawArgs, beforeRun) {
176
205
  catch (err) {
177
206
  if (err instanceof UsageError) {
178
207
  err.help = getUsage(match.help);
208
+ }
209
+ const columnHint = quotedColumnHint(err, match, rawArgs, nestingLevel);
210
+ if (columnHint !== undefined) {
211
+ const failure = classifyFailure(err);
212
+ const reason = failureMessage(err, "Command failed");
213
+ throw new CliError(boundParserMessage(`${reason}. Did you mean: ${columnHint}`, {
214
+ reason,
215
+ guidance: "Quote each column name containing spaces. Full command omitted because it is long.",
216
+ }), failure.code, { ...failure.details, reason: "unquoted_column" }, failure.help ?? getUsage(match.help), match.command.split(" "));
217
+ }
218
+ if (err instanceof UsageError) {
179
219
  throw err;
180
220
  }
181
- const suggestFor = (flag) => match.guessedFlags?.[flag]?.(commandArgs);
182
- const parseArgsReason = parseArgsMessage(err, rawArgs, suggestFor);
183
- if (parseArgsReason != null) {
184
- const argument = /(?:Unknown option|Option) '(-[^' ]+)/.exec(err.message)?.[1];
185
- quit(parseArgsReason, getUsage(match.help), argument === undefined ? undefined : { argument });
221
+ if (match.command === "task search") {
222
+ const failure = classifyFailure(err);
223
+ const isMissingProject = failure.code === "not_found" && failure.details?.entity === "project";
224
+ if (isMissingProject) {
225
+ throw new CliError(failureMessage(err, "Search failed"), failure.code, failure.details, getUsage(match.help), failure.suggestedRoute);
226
+ }
227
+ }
228
+ const suggestFor = (flag) => {
229
+ const suggestion = match.guessedFlags?.[flag]?.(commandArgs);
230
+ if (suggestion === undefined) {
231
+ return undefined;
232
+ }
233
+ const target = findCommand(parsedRoutes, suggestion);
234
+ return target === undefined
235
+ ? undefined
236
+ : { args: suggestion, route: target.match.command.split(" ") };
237
+ };
238
+ const parserFailure = parseArgsFailure(err, rawArgs, suggestFor, match.command.split(" "));
239
+ if (parserFailure !== null) {
240
+ parserFailure.help = getUsage(match.help);
241
+ throw parserFailure;
186
242
  }
187
243
  throw err;
188
244
  }
189
245
  }
190
246
  export function createRouter(routesDef, beforeRun) {
191
- const parsedRoutes = parseRoutes(routesDef);
247
+ const parsedRoutes = Array.isArray(routesDef) ? routesDef : parseRoutes(routesDef);
192
248
  return {
193
249
  route: async (args) => {
194
250
  try {