@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
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @zinn-dev/cli
2
2
 
3
- The `zinn` command-line interface for Zinn.
3
+ The command-line interface for [Zinn](https://zinn.sh), local kanban and task management for developers and coding agents.
4
4
 
5
5
  > [!IMPORTANT]
6
6
  > **Experimental.** Commands, output, and the database schema may change between releases. Save a backup with `zinn backup` before upgrading.
package/index.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  import packageJson from "./package.json" with { type: "json" };
3
- import { versionSpellings } from "./src/input.js";
3
+ import { isHelpFlag, versionSpellings } from "./src/input.js";
4
4
  const args = process.argv.slice(2);
5
5
  const isVersionRequest = args.length === 1 && versionSpellings.includes(args[0]);
6
6
  if (isVersionRequest) {
7
7
  console.info(packageJson.version);
8
8
  }
9
9
  else {
10
- const { isHelpFlag, prepareOutput, flushDiagnostics, renderFailure } = await import("./src/lib.js");
10
+ const { prepareOutput, finishRun, renderFailure } = await import("./src/lib.js");
11
11
  prepareOutput(args);
12
12
  try {
13
13
  const { createRouter } = await import("./src/routes/router.js");
@@ -22,7 +22,7 @@ else {
22
22
  });
23
23
  if (args.length === 0 || isHelpFlag(args[0])) {
24
24
  console.info(router.help);
25
- flushDiagnostics();
25
+ finishRun();
26
26
  }
27
27
  else {
28
28
  await router.route(args);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zinn-dev/cli",
3
- "version": "0.42.0",
3
+ "version": "0.44.0",
4
4
  "description": "A kanban workflow in the terminal. Experimental.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://zinn.sh",
@@ -21,7 +21,9 @@
21
21
  "kanban",
22
22
  "cli",
23
23
  "terminal",
24
- "bun"
24
+ "task-management",
25
+ "task-tracker",
26
+ "coding-agents"
25
27
  ],
26
28
  "files": [
27
29
  "index.js",
@@ -36,8 +38,8 @@
36
38
  "node": ">=24.15.0"
37
39
  },
38
40
  "dependencies": {
39
- "zod": "4.6.4",
40
- "@zinn-dev/core": "0.31.0"
41
+ "zod": "4.6.7",
42
+ "@zinn-dev/core": "0.33.0"
41
43
  },
42
44
  "devDependencies": {
43
45
  "ajv": "8.20.0"
@@ -7,7 +7,7 @@ description: >-
7
7
  it, repository instructions mention it, zinn.local.json exists, or a Zinn task
8
8
  key is referenced.
9
9
  metadata:
10
- zinn-cli-reviewed-version: "0.42.0"
10
+ zinn-cli-reviewed-version: "0.44.0"
11
11
  ---
12
12
 
13
13
  # Work with a Zinn board
package/src/actor.d.ts CHANGED
@@ -1,5 +1,13 @@
1
1
  import type { Actor } from "@zinn-dev/core";
2
2
  type Env = Record<string, string | undefined>;
3
+ export declare function readExecutionIdentity(env: Env): {
4
+ sessionId: string | null;
5
+ threadId: string | null;
6
+ agent: string | null;
7
+ model: string | null;
8
+ effort: string | null;
9
+ client: string;
10
+ };
3
11
  /** Generic flags establish an unnamed agent only when no identifying marker follows. */
4
12
  export declare function detectAgent(env: Env): Actor | null;
5
13
  export declare function resolveActor(env: Env): Actor;
package/src/actor.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import { userInfo } from "node:os";
3
+ import packageJson from "../package.json" with { type: "json" };
3
4
  /**
4
5
  * Environment variables that coding agents set in the shells they run.
5
6
  * Undetected tools can set `AI_AGENT` through their own env configuration.
@@ -27,7 +28,9 @@ function readDeclaration(env, variable) {
27
28
  const value = variable === null ? undefined : env[variable]?.trim();
28
29
  return value == null || value.length === 0 ? null : value;
29
30
  }
30
- function readExecutionIdentity(env) {
31
+ export function readExecutionIdentity(env) {
32
+ const ownClient = `zinn-cli/${packageJson.version}`;
33
+ const declaredClient = readDeclaration(env, "ZINN_CLIENT");
31
34
  let sessionId = null;
32
35
  let threadId = null;
33
36
  for (const declaration of SESSION_DECLARATIONS) {
@@ -46,6 +49,7 @@ function readExecutionIdentity(env) {
46
49
  agent: readDeclaration(env, "ZINN_AGENT"),
47
50
  model: readDeclaration(env, "ZINN_MODEL"),
48
51
  effort: readDeclaration(env, "ZINN_EFFORT"),
52
+ client: declaredClient === null ? ownClient : `${ownClient} ${declaredClient}`,
49
53
  };
50
54
  }
51
55
  /** Generic flags establish an unnamed agent only when no identifying marker follows. */
@@ -106,8 +106,8 @@ export declare const capabilitiesSchema: z.ZodObject<{
106
106
  }, z.core.$strict>;
107
107
  effects: z.ZodObject<{
108
108
  domain: z.ZodEnum<{
109
- read: "read";
110
109
  create: "create";
110
+ read: "read";
111
111
  update: "update";
112
112
  delete: "delete";
113
113
  replace: "replace";
@@ -115,18 +115,18 @@ export declare const capabilitiesSchema: z.ZodObject<{
115
115
  }>;
116
116
  storage: z.ZodEnum<{
117
117
  backup: "backup";
118
+ migrate: "migrate";
119
+ reindex: "reindex";
118
120
  none: "none";
119
121
  "normal-open": "normal-open";
120
122
  restore: "restore";
121
- migrate: "migrate";
122
- reindex: "reindex";
123
123
  inspect: "inspect";
124
124
  }>;
125
125
  }, z.core.$strict>;
126
126
  confirmation: z.ZodObject<{
127
127
  kind: z.ZodEnum<{
128
- prompt: "prompt";
129
128
  none: "none";
129
+ prompt: "prompt";
130
130
  "project-delete": "project-delete";
131
131
  }>;
132
132
  description: z.ZodOptional<z.ZodString>;
@@ -1,8 +1,8 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { column, columnCreateSchema, parseTaskKey } from "@zinn-dev/core";
3
3
  import { classifyFailure } from "./errors.js";
4
- import { routerOptions, getOptionInputs, violatesConstraint } from "./input.js";
5
- import { formatCommand, isAllowLegacyReadFlag, isRouterFlag, UsageError, validateUniqueOptions, } from "./lib.js";
4
+ import { routerOptions, getOptionInputs, isAllowLegacyReadFlag, isRouterFlag, splitAtOptionSeparator, violatesConstraint, } from "./input.js";
5
+ import { formatCommand, UsageError, validateUniqueOptions } from "./lib.js";
6
6
  import { chooseProjectKey } from "./project.js";
7
7
  function isEligible(error, command) {
8
8
  const failure = classifyFailure(error);
@@ -76,8 +76,7 @@ export function quotedColumnHint(error, route, rawArgs, routeWordCount) {
76
76
  }
77
77
  }
78
78
  const args = rawArgs.slice(argumentStart);
79
- const separatorIndex = rawArgs.indexOf("--");
80
- const optionArgs = separatorIndex === -1 ? rawArgs : rawArgs.slice(0, separatorIndex);
79
+ const { optionWords: optionArgs } = splitAtOptionSeparator(rawArgs);
81
80
  const options = { ...route.input.options, ...routerOptions };
82
81
  const { tokens, values } = parseArgs({
83
82
  args,
package/src/errors.d.ts CHANGED
@@ -28,18 +28,31 @@ export declare const errorDetailsSchema: z.ZodObject<{
28
28
  settingsPath: z.ZodOptional<z.ZodString>;
29
29
  reason: z.ZodOptional<z.ZodEnum<{
30
30
  archived: "archived";
31
+ dash_value: "dash_value";
32
+ unknown_option: "unknown_option";
33
+ unknown_command: "unknown_command";
34
+ missing_command: "missing_command";
35
+ missing_argument: "missing_argument";
36
+ unexpected_argument: "unexpected_argument";
37
+ unquoted_column: "unquoted_column";
31
38
  confirmation_required: "confirmation_required";
32
39
  invalid_json: "invalid_json";
33
40
  invalid_settings: "invalid_settings";
34
41
  invalid_storage: "invalid_storage";
35
42
  already_exists: "already_exists";
36
43
  parent_exists: "parent_exists";
44
+ relation_changed: "relation_changed";
37
45
  cycle: "cycle";
38
46
  different_project: "different_project";
39
47
  different_column: "different_column";
40
48
  ambiguous_reference: "ambiguous_reference";
49
+ invalid_cursor: "invalid_cursor";
50
+ cursor_version: "cursor_version";
51
+ different_sort: "different_sort";
52
+ task_id_cursor: "task_id_cursor";
41
53
  text_match_count: "text_match_count";
42
54
  no_columns: "no_columns";
55
+ has_tasks: "has_tasks";
43
56
  unmarked_database: "unmarked_database";
44
57
  newer_database: "newer_database";
45
58
  older_database: "older_database";
@@ -62,6 +75,7 @@ export declare const errorDetailsSchema: z.ZodObject<{
62
75
  backupPath: z.ZodOptional<z.ZodString>;
63
76
  schemaVersion: z.ZodOptional<z.ZodNumber>;
64
77
  supportedSchemaVersion: z.ZodOptional<z.ZodNumber>;
78
+ logPath: z.ZodOptional<z.ZodString>;
65
79
  cause: z.ZodOptional<z.ZodObject<{
66
80
  code: z.ZodOptional<z.ZodString>;
67
81
  errcode: z.ZodOptional<z.ZodNumber>;
@@ -101,18 +115,31 @@ export declare const errorDocumentSchema: z.ZodObject<{
101
115
  settingsPath: z.ZodOptional<z.ZodString>;
102
116
  reason: z.ZodOptional<z.ZodEnum<{
103
117
  archived: "archived";
118
+ dash_value: "dash_value";
119
+ unknown_option: "unknown_option";
120
+ unknown_command: "unknown_command";
121
+ missing_command: "missing_command";
122
+ missing_argument: "missing_argument";
123
+ unexpected_argument: "unexpected_argument";
124
+ unquoted_column: "unquoted_column";
104
125
  confirmation_required: "confirmation_required";
105
126
  invalid_json: "invalid_json";
106
127
  invalid_settings: "invalid_settings";
107
128
  invalid_storage: "invalid_storage";
108
129
  already_exists: "already_exists";
109
130
  parent_exists: "parent_exists";
131
+ relation_changed: "relation_changed";
110
132
  cycle: "cycle";
111
133
  different_project: "different_project";
112
134
  different_column: "different_column";
113
135
  ambiguous_reference: "ambiguous_reference";
136
+ invalid_cursor: "invalid_cursor";
137
+ cursor_version: "cursor_version";
138
+ different_sort: "different_sort";
139
+ task_id_cursor: "task_id_cursor";
114
140
  text_match_count: "text_match_count";
115
141
  no_columns: "no_columns";
142
+ has_tasks: "has_tasks";
116
143
  unmarked_database: "unmarked_database";
117
144
  newer_database: "newer_database";
118
145
  older_database: "older_database";
@@ -135,6 +162,7 @@ export declare const errorDocumentSchema: z.ZodObject<{
135
162
  backupPath: z.ZodOptional<z.ZodString>;
136
163
  schemaVersion: z.ZodOptional<z.ZodNumber>;
137
164
  supportedSchemaVersion: z.ZodOptional<z.ZodNumber>;
165
+ logPath: z.ZodOptional<z.ZodString>;
138
166
  cause: z.ZodOptional<z.ZodObject<{
139
167
  code: z.ZodOptional<z.ZodString>;
140
168
  errcode: z.ZodOptional<z.ZodNumber>;
@@ -147,12 +175,21 @@ export declare const errorDocumentSchema: z.ZodObject<{
147
175
  export type ErrorCode = z.infer<typeof errorCodeSchema>;
148
176
  export type ErrorDetails = z.infer<typeof errorDetailsSchema>;
149
177
  export type CliFailure = z.infer<typeof errorDocumentSchema>["error"];
150
- /** A failure detected by the CLI, with only facts intended for its public output. */
178
+ export type ClassifiedFailure = Omit<CliFailure, "message"> & {
179
+ suggestedRoute?: Array<string>;
180
+ };
181
+ /** A CLI failure with public facts and an internal recovery route. */
151
182
  export declare class CliError extends Error {
152
183
  readonly code: ErrorCode;
153
184
  readonly details?: ErrorDetails | undefined;
154
185
  help?: string | undefined;
155
- constructor(message: string, code?: ErrorCode, details?: ErrorDetails | undefined, help?: string | undefined);
186
+ readonly suggestedRoute?: Array<string> | undefined;
187
+ constructor(message: string, code?: ErrorCode, details?: ErrorDetails | undefined, help?: string | undefined, suggestedRoute?: Array<string> | undefined, cause?: unknown);
156
188
  }
189
+ /** Recovery text and its single suggested route, when one is identified. */
190
+ export declare function recoveryHint(error: unknown): {
191
+ suffix: string;
192
+ suggestedRoute?: Array<string>;
193
+ } | undefined;
157
194
  /** Finds causes of initialization wrappers without serializing their error chains. */
158
- export declare function classifyFailure(error: unknown): Omit<CliFailure, "message">;
195
+ export declare function classifyFailure(error: unknown): ClassifiedFailure;
package/src/errors.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { CoreError, SqliteError } from "@zinn-dev/core";
2
+ import { CoreError, ReadOnlyDatabaseError, SqliteError, TextEditMatchError, UnmarkedDatabaseError, isSqliteErrorFamily, } from "@zinn-dev/core";
3
3
  export const errorCodeSchema = z.enum([
4
4
  "invalid_input",
5
5
  "not_found",
@@ -28,6 +28,13 @@ export const errorDetailsSchema = z.strictObject({
28
28
  settingsPath: z.string().optional(),
29
29
  reason: z
30
30
  .enum([
31
+ "dash_value",
32
+ "unknown_option",
33
+ "unknown_command",
34
+ "missing_command",
35
+ "missing_argument",
36
+ "unexpected_argument",
37
+ "unquoted_column",
31
38
  "confirmation_required",
32
39
  "invalid_json",
33
40
  "invalid_settings",
@@ -35,12 +42,18 @@ export const errorDetailsSchema = z.strictObject({
35
42
  "already_exists",
36
43
  "archived",
37
44
  "parent_exists",
45
+ "relation_changed",
38
46
  "cycle",
39
47
  "different_project",
40
48
  "different_column",
41
49
  "ambiguous_reference",
50
+ "invalid_cursor",
51
+ "cursor_version",
52
+ "different_sort",
53
+ "task_id_cursor",
42
54
  "text_match_count",
43
55
  "no_columns",
56
+ "has_tasks",
44
57
  "unmarked_database",
45
58
  "newer_database",
46
59
  "older_database",
@@ -64,6 +77,7 @@ export const errorDetailsSchema = z.strictObject({
64
77
  backupPath: z.string().optional(),
65
78
  schemaVersion: z.number().int().nonnegative().optional(),
66
79
  supportedSchemaVersion: z.number().int().nonnegative().optional(),
80
+ logPath: z.string().optional(),
67
81
  cause: z
68
82
  .strictObject({
69
83
  code: z.string().optional(),
@@ -81,19 +95,69 @@ export const errorDocumentSchema = z.strictObject({
81
95
  diagnostics: z.array(z.string()).optional(),
82
96
  }),
83
97
  });
84
- /** A failure detected by the CLI, with only facts intended for its public output. */
98
+ /** A CLI failure with public facts and an internal recovery route. */
85
99
  export class CliError extends Error {
86
100
  code;
87
101
  details;
88
102
  help;
89
- constructor(message, code = "invalid_input", details, help) {
90
- super(message);
103
+ suggestedRoute;
104
+ constructor(message, code = "invalid_input", details, help, suggestedRoute, cause) {
105
+ super(message, cause === undefined ? undefined : { cause });
91
106
  this.code = code;
92
107
  this.details = details;
93
108
  this.help = help;
109
+ this.suggestedRoute = suggestedRoute;
94
110
  this.name = "CliError";
95
111
  }
96
112
  }
113
+ const taskCursorRecovery = {
114
+ invalid_cursor: ". Copy the cursor from the continuation command that zinn task list prints, or list again without --starting-after.",
115
+ cursor_version: ". Run zinn task list again without --starting-after to get a current cursor.",
116
+ different_sort: ". Keep the --sort of the zinn task list command that printed the cursor, or start again without --starting-after.",
117
+ task_id_cursor: ". When more tasks remain, zinn task list prints a continuation command with the cursor on stderr. Run that command.",
118
+ };
119
+ /** Recovery text and its single suggested route, when one is identified. */
120
+ export function recoveryHint(error) {
121
+ if (error instanceof ReadOnlyDatabaseError && error.reason === "older") {
122
+ return { suffix: ". Run `zinn migrate` to upgrade it.", suggestedRoute: ["migrate"] };
123
+ }
124
+ if (error instanceof UnmarkedDatabaseError) {
125
+ return { suffix: ". Add --allow-legacy-read to read it anyway." };
126
+ }
127
+ if (error instanceof TextEditMatchError && error.matchCount > 1) {
128
+ return { suffix: " Use --all to replace every match." };
129
+ }
130
+ if (error instanceof CoreError && error.kind === "missing" && error.facts.entity === "database") {
131
+ return {
132
+ suffix: ". Create one with `zinn project create`.",
133
+ suggestedRoute: ["project", "create"],
134
+ };
135
+ }
136
+ if (error instanceof CoreError && error.facts.reason === "no_columns") {
137
+ return {
138
+ suffix: `. Add a column with zinn project column create ${error.facts.key} <name>.`,
139
+ suggestedRoute: ["project", "column", "create"],
140
+ };
141
+ }
142
+ if (error instanceof CoreError && error.facts.reason === "has_tasks") {
143
+ return {
144
+ suffix: ". Use zinn task move or zinn task delete to clear the column. Archived tasks must be unarchived before moving.",
145
+ };
146
+ }
147
+ const cursorRecovery = error instanceof CoreError && error.facts.reason !== undefined
148
+ ? taskCursorRecovery[error.facts.reason]
149
+ : undefined;
150
+ if (cursorRecovery !== undefined) {
151
+ return { suffix: cursorRecovery, suggestedRoute: ["task", "list"] };
152
+ }
153
+ if (error instanceof Error && error.message === "no such table: task_search") {
154
+ return {
155
+ suffix: ". Run `zinn reindex` to rebuild the search index.",
156
+ suggestedRoute: ["reindex"],
157
+ };
158
+ }
159
+ return undefined;
160
+ }
97
161
  const coreCodes = {
98
162
  input: "invalid_input",
99
163
  missing: "not_found",
@@ -120,19 +184,19 @@ const osReasons = {
120
184
  ENODEV: "io",
121
185
  EEXIST: "io",
122
186
  };
123
- const sqliteReasons = {
124
- SQLITE_BUSY: "busy",
125
- SQLITE_LOCKED: "locked",
126
- SQLITE_PERM: "permission_denied",
127
- SQLITE_AUTH: "permission_denied",
128
- SQLITE_READONLY: "read_only",
129
- SQLITE_FULL: "disk_full",
130
- SQLITE_CORRUPT: "corrupt",
131
- SQLITE_NOTADB: "not_database",
132
- SQLITE_IOERR: "io",
133
- SQLITE_CANTOPEN: "io",
134
- SQLITE_NOLFS: "io",
135
- };
187
+ const sqliteReasons = [
188
+ ["SQLITE_BUSY", "busy"],
189
+ ["SQLITE_LOCKED", "locked"],
190
+ ["SQLITE_PERM", "permission_denied"],
191
+ ["SQLITE_AUTH", "permission_denied"],
192
+ ["SQLITE_READONLY", "read_only"],
193
+ ["SQLITE_FULL", "disk_full"],
194
+ ["SQLITE_CORRUPT", "corrupt"],
195
+ ["SQLITE_NOTADB", "not_database"],
196
+ ["SQLITE_IOERR", "io"],
197
+ ["SQLITE_CANTOPEN", "io"],
198
+ ["SQLITE_NOLFS", "io"],
199
+ ];
136
200
  /** Selects public facts explicitly
137
201
  * Error properties and submitted objects do not go to output
138
202
  */
@@ -162,7 +226,7 @@ function nativeFailure(error) {
162
226
  return undefined;
163
227
  }
164
228
  const reason = error instanceof SqliteError
165
- ? Object.entries(sqliteReasons).find(([primary]) => code === primary || code.startsWith(`${primary}_`))?.[1]
229
+ ? sqliteReasons.find(([primary]) => isSqliteErrorFamily(error, primary))?.[1]
166
230
  : osReasons[code];
167
231
  if (reason === undefined) {
168
232
  return undefined;
@@ -179,13 +243,21 @@ function nativeFailure(error) {
179
243
  }
180
244
  /** Finds causes of initialization wrappers without serializing their error chains. */
181
245
  export function classifyFailure(error) {
246
+ const suggestedRoute = recoveryHint(error)?.suggestedRoute;
247
+ const recovery = suggestedRoute === undefined ? {} : { suggestedRoute };
182
248
  const visited = new Set();
183
249
  let current = error;
184
250
  let classified;
185
251
  while (current instanceof Error && !visited.has(current)) {
186
252
  visited.add(current);
187
253
  if (current instanceof CliError) {
188
- return { code: current.code, details: current.details, help: current.help };
254
+ return {
255
+ code: current.code,
256
+ details: current.details,
257
+ help: current.help,
258
+ ...recovery,
259
+ ...(current.suggestedRoute === undefined ? {} : { suggestedRoute: current.suggestedRoute }),
260
+ };
189
261
  }
190
262
  if (current instanceof CoreError && classified === undefined) {
191
263
  const details = publicDetails(current.facts);
@@ -213,7 +285,7 @@ export function classifyFailure(error) {
213
285
  }
214
286
  if (native !== undefined) {
215
287
  if (classified === undefined) {
216
- return { code: "storage", details: native };
288
+ return { code: "storage", details: native, ...recovery };
217
289
  }
218
290
  if (classified.code === "storage") {
219
291
  classified.details = { ...native, ...classified.details, cause: native.cause };
@@ -222,5 +294,5 @@ export function classifyFailure(error) {
222
294
  }
223
295
  current = current.cause;
224
296
  }
225
- return classified ?? { code: "internal" };
297
+ return { ...(classified ?? { code: "internal" }), ...recovery };
226
298
  }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Writes what a failure leaves out of its error message to a new file in the store's `logs` folder.
3
+ * Returns the file's path, or undefined when none was written. It never throws,
4
+ * so logging cannot hide the failure it reports.
5
+ */
6
+ export declare function writeFailureLog(error: unknown, notices: ReadonlyArray<string>): string | undefined;
@@ -0,0 +1,167 @@
1
+ import { closeSync, openSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { arch, platform, release } from "node:os";
3
+ import { join } from "node:path";
4
+ import { createOutputFileName, getConfiguredStorage, getStorage, readOutputFileName, readSchemaVersionWithoutWaiting, } from "@zinn-dev/core";
5
+ import packageJson from "../package.json" with { type: "json" };
6
+ import { currentRuntime, readRunClock } from "./run-facts.js";
7
+ import { ensureFolderInStore } from "./store-folder.js";
8
+ const LOG_EXTENSION = ".log";
9
+ /** Logs kept in the folder. Including ones written by a failing run */
10
+ const MAX_LOG_FILES = 10;
11
+ /** One thrown value as text. An error keeps its stack, and its code and `errcode` when it has them */
12
+ function describeValue(value) {
13
+ if (!(value instanceof Error)) {
14
+ return String(value);
15
+ }
16
+ const lines = [typeof value.stack === "string" ? value.stack : `${value.name}: ${value.message}`];
17
+ const { code, errcode } = value;
18
+ if (code !== undefined) {
19
+ lines.push(`code: ${String(code)}`);
20
+ }
21
+ if (errcode !== undefined) {
22
+ lines.push(`errcode: ${String(errcode)}`);
23
+ }
24
+ return lines.join("\n");
25
+ }
26
+ /** The thrown error, then each cause and suppressed error, stopping at one already shown */
27
+ function describeErrors(error) {
28
+ const shown = new Set();
29
+ const entries = [];
30
+ const add = (value, label) => {
31
+ if (shown.has(value)) {
32
+ return;
33
+ }
34
+ shown.add(value);
35
+ entries.push(label === null ? describeValue(value) : `${label}\n${describeValue(value)}`);
36
+ if (!(value instanceof Error)) {
37
+ return;
38
+ }
39
+ const { suppressed } = value;
40
+ if (value.cause !== undefined) {
41
+ add(value.cause, "Caused by:");
42
+ }
43
+ if (suppressed !== undefined) {
44
+ add(suppressed, "Suppressed:");
45
+ }
46
+ };
47
+ add(error, null);
48
+ return entries.join("\n\n");
49
+ }
50
+ function describeRuntime() {
51
+ const { name, version } = currentRuntime();
52
+ return `${name} ${version}`;
53
+ }
54
+ function section(title, lines) {
55
+ return [title, ...lines].join("\n");
56
+ }
57
+ /** The resolved database path and its schema version, or the configured path when it cannot be resolved. */
58
+ function readDatabaseFacts(configuredPath) {
59
+ try {
60
+ const { databasePath } = getStorage();
61
+ return { databasePath, schemaVersion: readSchemaVersionWithoutWaiting(databasePath) };
62
+ }
63
+ catch {
64
+ return { databasePath: configuredPath, schemaVersion: null };
65
+ }
66
+ }
67
+ function formatLog(error, notices, storage) {
68
+ const { databasePath, schemaVersion } = readDatabaseFacts(storage.databasePath);
69
+ const { now: failedAt, elapsedMs, startedAt } = readRunClock();
70
+ const sections = [
71
+ section("Error", [describeErrors(error)]),
72
+ section("Run", [
73
+ `Process id: ${process.pid}`,
74
+ `Zinn version: ${packageJson.version}`,
75
+ `Runtime: ${describeRuntime()}`,
76
+ `Operating system: ${platform()} ${release()} ${arch()}`,
77
+ ]),
78
+ section("Store", [
79
+ `Directory: ${storage.directory}`,
80
+ `Database: ${databasePath}`,
81
+ `Schema version: ${schemaVersion ?? "unknown"}`,
82
+ ]),
83
+ section("Arguments", [JSON.stringify(process.argv.slice(2))]),
84
+ section("Timings", [
85
+ `Started: ${startedAt.toISOString()}`,
86
+ `Failed: ${failedAt.toISOString()}`,
87
+ `Elapsed: ${elapsedMs} ms`,
88
+ ]),
89
+ ];
90
+ if (notices.length > 0) {
91
+ sections.push(section("Notices", [...notices]));
92
+ }
93
+ return `${sections.join("\n\n")}\n`;
94
+ }
95
+ /** Creates a file that does not exist yet, and removes it again when its text cannot be written */
96
+ function createFile(path, text) {
97
+ const descriptor = openSync(path, "wx");
98
+ let isWritten = false;
99
+ try {
100
+ try {
101
+ writeFileSync(descriptor, text);
102
+ }
103
+ finally {
104
+ closeSync(descriptor);
105
+ }
106
+ isWritten = true;
107
+ }
108
+ finally {
109
+ if (!isWritten) {
110
+ rmSync(path, { force: true });
111
+ }
112
+ }
113
+ }
114
+ /** Other runs' logs, oldest first by modification time, then by name */
115
+ function listOtherLogs(logDirectory, ownName) {
116
+ return readdirSync(logDirectory)
117
+ .filter((name) => name !== ownName && readOutputFileName(name, LOG_EXTENSION) !== null)
118
+ .flatMap((name) => {
119
+ try {
120
+ return [{ name, modifiedMs: statSync(join(logDirectory, name)).mtimeMs }];
121
+ }
122
+ catch {
123
+ // Another run may have removed it since the listing
124
+ return [];
125
+ }
126
+ })
127
+ .sort((a, b) => a.modifiedMs - b.modifiedMs || a.name.localeCompare(b.name))
128
+ .map(({ name }) => name);
129
+ }
130
+ /** Removes the oldest logs so that at most `MAX_LOG_FILES` remain. Other files stay */
131
+ function removeOldLogs(logDirectory, ownName) {
132
+ try {
133
+ const others = listOtherLogs(logDirectory, ownName);
134
+ const excess = others.length - (MAX_LOG_FILES - 1);
135
+ for (const name of others.slice(0, Math.max(excess, 0))) {
136
+ try {
137
+ rmSync(join(logDirectory, name), { force: true });
138
+ }
139
+ catch {
140
+ // Another run may have removed it, and a leftover only keeps one more file
141
+ }
142
+ }
143
+ }
144
+ catch {
145
+ // The new log is already written, so a failed listing only skips the cleanup
146
+ }
147
+ }
148
+ /**
149
+ * Writes what a failure leaves out of its error message to a new file in the store's `logs` folder.
150
+ * Returns the file's path, or undefined when none was written. It never throws,
151
+ * so logging cannot hide the failure it reports.
152
+ */
153
+ export function writeFailureLog(error, notices) {
154
+ try {
155
+ const storage = getConfiguredStorage();
156
+ const name = createOutputFileName({ client: "cli", version: packageJson.version }, LOG_EXTENSION);
157
+ const path = join(storage.logDirectory, name);
158
+ const text = formatLog(error, notices, storage);
159
+ ensureFolderInStore(storage.logDirectory);
160
+ createFile(path, text);
161
+ removeOldLogs(storage.logDirectory, name);
162
+ return path;
163
+ }
164
+ catch {
165
+ return undefined;
166
+ }
167
+ }
package/src/input.d.ts CHANGED
@@ -185,6 +185,17 @@ export declare const routerOptions: {
185
185
  };
186
186
  export declare const helpSpellings: readonly string[];
187
187
  export declare const versionSpellings: readonly string[];
188
+ export declare const OPTION_SEPARATOR = "--";
189
+ export declare function isJsonFlag(flag: string): boolean;
190
+ export declare function isAllowLegacyReadFlag(flag: string): boolean;
191
+ /** A flag the router reads wherever it appears before --, for every command. */
192
+ export declare function isRouterFlag(flag: string): boolean;
193
+ export declare function isHelpFlag(flag: string): boolean;
194
+ /** The words before the first `--`, and the rest starting with that `--` */
195
+ export declare function splitAtOptionSeparator(words: Array<string>): {
196
+ optionWords: string[];
197
+ passthroughWords: string[];
198
+ };
188
199
  export declare const invocation: {
189
200
  readonly routerOptions: {
190
201
  readonly json: {