selftune 0.2.14 → 0.2.15

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 (41) hide show
  1. package/apps/local-dashboard/dist/assets/index-DOu3iLD9.js +16 -0
  2. package/apps/local-dashboard/dist/assets/vendor-ui-DIwlrGlb.js +12 -0
  3. package/apps/local-dashboard/dist/index.html +2 -2
  4. package/cli/selftune/analytics.ts +13 -11
  5. package/cli/selftune/badge/badge.ts +13 -9
  6. package/cli/selftune/canonical-export.ts +6 -6
  7. package/cli/selftune/contribute/contribute.ts +2 -1
  8. package/cli/selftune/cron/setup.ts +3 -1
  9. package/cli/selftune/dashboard-contract.ts +10 -0
  10. package/cli/selftune/dashboard.ts +10 -5
  11. package/cli/selftune/eval/baseline.ts +20 -30
  12. package/cli/selftune/eval/hooks-to-evals.ts +22 -12
  13. package/cli/selftune/eval/import-skillsbench.ts +21 -8
  14. package/cli/selftune/eval/unit-test-cli.ts +22 -11
  15. package/cli/selftune/evolution/description-quality.ts +224 -0
  16. package/cli/selftune/evolution/evolve-body.ts +17 -10
  17. package/cli/selftune/evolution/evolve.ts +70 -57
  18. package/cli/selftune/evolution/rollback.ts +7 -6
  19. package/cli/selftune/grading/auto-grade.ts +24 -22
  20. package/cli/selftune/grading/grade-session.ts +21 -17
  21. package/cli/selftune/hooks/auto-activate.ts +12 -3
  22. package/cli/selftune/hooks/prompt-log.ts +7 -1
  23. package/cli/selftune/index.ts +66 -69
  24. package/cli/selftune/ingestors/claude-replay.ts +29 -14
  25. package/cli/selftune/ingestors/codex-rollout.ts +6 -1
  26. package/cli/selftune/init.ts +14 -9
  27. package/cli/selftune/monitoring/watch.ts +32 -16
  28. package/cli/selftune/orchestrate.ts +18 -17
  29. package/cli/selftune/routes/skill-report.ts +17 -0
  30. package/cli/selftune/schedule.ts +23 -9
  31. package/cli/selftune/sync.ts +7 -3
  32. package/cli/selftune/types.ts +44 -10
  33. package/cli/selftune/utils/cli-error.ts +102 -0
  34. package/cli/selftune/workflows/workflows.ts +23 -17
  35. package/package.json +1 -1
  36. package/skill/SKILL.md +1 -1
  37. package/skill/Workflows/Evolve.md +4 -0
  38. package/skill/Workflows/Initialize.md +8 -8
  39. package/skill/settings_snippet.json +29 -6
  40. package/apps/local-dashboard/dist/assets/index-DIrdlu2_.js +0 -16
  41. package/apps/local-dashboard/dist/assets/vendor-ui-7xD7fNEU.js +0 -12
@@ -28,6 +28,7 @@ import type {
28
28
  SessionTelemetryRecord,
29
29
  SkillUsageRecord,
30
30
  } from "../types.js";
31
+ import { CLIError, handleCLIError } from "../utils/cli-error.js";
31
32
  import {
32
33
  detectAgent as _detectAgent,
33
34
  stripMarkdownFences as _stripMarkdownFences,
@@ -743,8 +744,7 @@ Options:
743
744
 
744
745
  const skill = values.skill;
745
746
  if (!skill) {
746
- console.error("[ERROR] --skill is required");
747
- process.exit(1);
747
+ throw new CLIError("--skill is required", "MISSING_FLAG", "selftune grade --skill <name>");
748
748
  }
749
749
 
750
750
  // --- Determine agent ---
@@ -752,10 +752,11 @@ Options:
752
752
  const validAgents = [...AGENT_CANDIDATES];
753
753
  if (values.agent) {
754
754
  if (!validAgents.includes(values.agent)) {
755
- console.error(
756
- `[ERROR] Invalid --agent '${values.agent}'. Expected one of: ${validAgents.join(", ")}`,
755
+ throw new CLIError(
756
+ `Invalid --agent '${values.agent}'. Expected one of: ${validAgents.join(", ")}`,
757
+ "INVALID_FLAG",
758
+ `selftune grade --skill <name> --agent ${validAgents[0]}`,
757
759
  );
758
- process.exit(1);
759
760
  }
760
761
  agent = values.agent;
761
762
  } else {
@@ -763,11 +764,11 @@ Options:
763
764
  }
764
765
 
765
766
  if (!agent) {
766
- console.error(
767
- `[ERROR] No supported agent CLI (${AGENT_CANDIDATES.join("/")}) found in PATH.\n` +
768
- "Install one of the supported agent CLIs.",
767
+ throw new CLIError(
768
+ `No supported agent CLI (${AGENT_CANDIDATES.join("/")}) found in PATH`,
769
+ "AGENT_NOT_FOUND",
770
+ "Install claude, codex, or opencode CLI, then retry",
769
771
  );
770
- process.exit(1);
771
772
  }
772
773
 
773
774
  console.error(`[INFO] Grading via agent: ${agent}`);
@@ -777,8 +778,11 @@ Options:
777
778
  if (values["evals-json"] && values["eval-id"] != null) {
778
779
  const evalIdNum = Number(values["eval-id"]);
779
780
  if (!Number.isFinite(evalIdNum) || !Number.isInteger(evalIdNum)) {
780
- console.error(`[ERROR] --eval-id must be a finite integer, got: ${values["eval-id"]}`);
781
- process.exit(1);
781
+ throw new CLIError(
782
+ `--eval-id must be a finite integer, got: ${values["eval-id"]}`,
783
+ "INVALID_FLAG",
784
+ "selftune grade --eval-id <integer>",
785
+ );
782
786
  }
783
787
  expectations = loadExpectationsFromEvalsJson(values["evals-json"], evalIdNum);
784
788
  } else if (values.expectations?.length) {
@@ -863,8 +867,11 @@ Options:
863
867
  agent,
864
868
  });
865
869
  } catch (err) {
866
- console.error(`[ERROR] ${err instanceof Error ? err.message : String(err)}`);
867
- process.exit(1);
870
+ throw new CLIError(
871
+ `Grading failed: ${err instanceof Error ? err.message : String(err)}`,
872
+ "OPERATION_FAILED",
873
+ "Check agent availability and try again",
874
+ );
868
875
  }
869
876
 
870
877
  const outputPath = values.output ?? buildDefaultGradingOutputPath(sessionId);
@@ -888,8 +895,5 @@ Options:
888
895
 
889
896
  // Guard: only run when invoked directly
890
897
  if (import.meta.main) {
891
- cliMain().catch((err) => {
892
- console.error(`[FATAL] ${err}`);
893
- process.exit(1);
894
- });
898
+ cliMain().catch(handleCLIError);
895
899
  }
@@ -179,9 +179,18 @@ if (import.meta.main) {
179
179
  const statePath = sessionStatePath(sessionId);
180
180
  const suggestions = evaluateRules(DEFAULT_RULES, ctx, statePath);
181
181
 
182
- for (const s of suggestions) {
183
- // Output to stderr — Claude Code shows stderr as system messages
184
- process.stderr.write(`[selftune] 💡 Suggestion: ${s}\n`);
182
+ if (suggestions.length > 0) {
183
+ // Output as JSON with additionalContext — Claude Code adds this to
184
+ // Claude's context on UserPromptSubmit (more reliable than stderr)
185
+ const context = suggestions.map((s) => `[selftune] Suggestion: ${s}`).join("\n");
186
+ process.stdout.write(
187
+ JSON.stringify({
188
+ hookSpecificOutput: {
189
+ hookEventName: "UserPromptSubmit",
190
+ additionalContext: context,
191
+ },
192
+ }),
193
+ );
185
194
  }
186
195
  }
187
196
  } catch {
@@ -154,7 +154,13 @@ export async function processPrompt(
154
154
  promptStatePath?: string,
155
155
  _signalLogPath?: string,
156
156
  ): Promise<QueryLogRecord | null> {
157
- const query = (payload.user_prompt ?? "").trim();
157
+ const rawPrompt =
158
+ typeof payload.prompt === "string"
159
+ ? payload.prompt
160
+ : typeof payload.user_prompt === "string"
161
+ ? payload.user_prompt
162
+ : "";
163
+ const query = rawPrompt.trim();
158
164
 
159
165
  if (!query) return null;
160
166
 
@@ -29,6 +29,11 @@
29
29
  * selftune hook <name> — Run a hook by name (prompt-log, session-stop, etc.)
30
30
  */
31
31
 
32
+ import { CLIError, handleCLIError } from "./utils/cli-error.js";
33
+
34
+ process.on("uncaughtException", handleCLIError);
35
+ process.on("unhandledRejection", handleCLIError);
36
+
32
37
  const command = process.argv[2];
33
38
 
34
39
  if (command === "--help" || command === "-h") {
@@ -84,6 +89,7 @@ if (!command) {
84
89
  // Show status by default — same as `selftune status`
85
90
  const { cliMain: statusMain } = await import("./status.js");
86
91
  statusMain();
92
+ process.exit(0);
87
93
  }
88
94
 
89
95
  // Route to the appropriate subcommand module.
@@ -142,10 +148,11 @@ Run 'selftune ingest <agent> --help' for agent-specific options.`);
142
148
  break;
143
149
  }
144
150
  default:
145
- console.error(
146
- `Unknown ingest agent: ${sub}\nRun 'selftune ingest --help' for available agents.`,
151
+ throw new CLIError(
152
+ `Unknown ingest agent: ${sub}`,
153
+ "UNKNOWN_COMMAND",
154
+ "selftune ingest --help",
147
155
  );
148
- process.exit(1);
149
156
  }
150
157
  break;
151
158
  }
@@ -182,10 +189,11 @@ Run 'selftune grade <subcommand> --help' for subcommand-specific options.`);
182
189
  break;
183
190
  }
184
191
  default:
185
- console.error(
186
- `Unknown grade mode: ${sub}\nRun 'selftune grade --help' for available modes.`,
192
+ throw new CLIError(
193
+ `Unknown grade mode: ${sub}`,
194
+ "UNKNOWN_COMMAND",
195
+ "selftune grade --help",
187
196
  );
188
- process.exit(1);
189
197
  }
190
198
  }
191
199
  break;
@@ -223,10 +231,11 @@ Run 'selftune evolve <subcommand> --help' for subcommand-specific options.`);
223
231
  break;
224
232
  }
225
233
  default:
226
- console.error(
227
- `Unknown evolve target: ${sub}\nRun 'selftune evolve --help' for available targets.`,
234
+ throw new CLIError(
235
+ `Unknown evolve target: ${sub}`,
236
+ "UNKNOWN_COMMAND",
237
+ "selftune evolve --help",
228
238
  );
229
- process.exit(1);
230
239
  }
231
240
  }
232
241
  break;
@@ -289,13 +298,18 @@ Run 'selftune eval <action> --help' for action-specific options.`);
289
298
  }));
290
299
  } catch (error) {
291
300
  const message = error instanceof Error ? error.message : String(error);
292
- console.error(`Invalid arguments: ${message}`);
293
- console.error("Run 'selftune eval composability --help' for usage.");
294
- process.exit(1);
301
+ throw new CLIError(
302
+ `Invalid arguments: ${message}`,
303
+ "INVALID_FLAG",
304
+ "selftune eval composability --help",
305
+ );
295
306
  }
296
307
  if (!values.skill) {
297
- console.error("[ERROR] --skill <name> is required.");
298
- process.exit(1);
308
+ throw new CLIError(
309
+ "--skill <name> is required.",
310
+ "MISSING_FLAG",
311
+ "selftune eval composability --skill <name>",
312
+ );
299
313
  }
300
314
  const logPath = values["telemetry-log"] ?? TELEMETRY_LOG;
301
315
  let telemetry: unknown[];
@@ -316,8 +330,11 @@ Run 'selftune eval <action> --help' for action-specific options.`);
316
330
  }
317
331
  const rawWindow = values.window as string | undefined;
318
332
  if (rawWindow !== undefined && !/^[1-9]\d*$/.test(rawWindow)) {
319
- console.error("Invalid --window value. Use a positive integer number of days.");
320
- process.exit(1);
333
+ throw new CLIError(
334
+ "Invalid --window value. Use a positive integer number of days.",
335
+ "INVALID_FLAG",
336
+ "selftune eval composability --skill <name> --window 30",
337
+ );
321
338
  }
322
339
  const windowSize = rawWindow === undefined ? undefined : Number(rawWindow);
323
340
  const report = analyzeComposability(values.skill, telemetry, windowSize);
@@ -325,10 +342,11 @@ Run 'selftune eval <action> --help' for action-specific options.`);
325
342
  break;
326
343
  }
327
344
  default:
328
- console.error(
329
- `Unknown eval action: ${sub}\nRun 'selftune eval --help' for available actions.`,
345
+ throw new CLIError(
346
+ `Unknown eval action: ${sub}`,
347
+ "UNKNOWN_COMMAND",
348
+ "selftune eval --help",
330
349
  );
331
- process.exit(1);
332
350
  }
333
351
  break;
334
352
  }
@@ -457,10 +475,11 @@ Run 'selftune cron <subcommand> --help' for subcommand-specific options.`);
457
475
  break;
458
476
  }
459
477
  default:
460
- console.error(
461
- `Unknown cron subcommand: ${sub}\nRun 'selftune cron --help' for available subcommands.`,
478
+ throw new CLIError(
479
+ `Unknown cron subcommand: ${sub}`,
480
+ "UNKNOWN_COMMAND",
481
+ "selftune cron --help",
462
482
  );
463
- process.exit(1);
464
483
  }
465
484
  break;
466
485
  }
@@ -505,9 +524,7 @@ Run 'selftune cron <subcommand> --help' for subcommand-specific options.`);
505
524
  }));
506
525
  } catch (error) {
507
526
  const message = error instanceof Error ? error.message : String(error);
508
- console.error(`Invalid arguments: ${message}`);
509
- console.error("Run 'selftune export --help' for usage.");
510
- process.exit(1);
527
+ throw new CLIError(`Invalid arguments: ${message}`, "INVALID_FLAG", "selftune export --help");
511
528
  }
512
529
  if (values.help) {
513
530
  console.log(`selftune export — Export SQLite data to JSONL files
@@ -544,9 +561,7 @@ Options:
544
561
  }
545
562
  } catch (err: unknown) {
546
563
  const message = err instanceof Error ? err.message : String(err);
547
- console.error(`Export failed: ${message}`);
548
- console.error("Ensure the SQLite database exists. Run 'selftune sync' first if needed.");
549
- process.exit(1);
564
+ throw new CLIError(`Export failed: ${message}`, "OPERATION_FAILED", "selftune sync");
550
565
  }
551
566
  break;
552
567
  }
@@ -590,8 +605,11 @@ Run 'selftune alpha <subcommand> --help' for subcommand-specific options.`);
590
605
  }));
591
606
  } catch (error) {
592
607
  const message = error instanceof Error ? error.message : String(error);
593
- console.error(`Invalid arguments: ${message}`);
594
- process.exit(1);
608
+ throw new CLIError(
609
+ `Invalid arguments: ${message}`,
610
+ "INVALID_FLAG",
611
+ "selftune alpha upload --help",
612
+ );
595
613
  }
596
614
  if (values.help) {
597
615
  console.log(`selftune alpha upload — Run a manual alpha data upload cycle
@@ -619,44 +637,20 @@ Output:
619
637
  const identity = readAlphaIdentity(SELFTUNE_CONFIG_PATH);
620
638
  if (!identity?.enrolled) {
621
639
  const guidance = getAlphaGuidance(identity);
622
- console.log(
623
- JSON.stringify(
624
- {
625
- enrolled: false,
626
- prepared: 0,
627
- sent: 0,
628
- failed: 0,
629
- skipped: 0,
630
- guidance,
631
- },
632
- null,
633
- 2,
634
- ),
640
+ throw new CLIError(
641
+ `[alpha upload] ${guidance.message}`,
642
+ "OPERATION_FAILED",
643
+ guidance.next_command,
635
644
  );
636
- console.error(`[alpha upload] ${guidance.message}`);
637
- console.error(`[alpha upload] Next: ${guidance.next_command}`);
638
- process.exit(1);
639
645
  }
640
646
 
641
647
  if (!identity.user_id?.trim() || !identity.api_key?.trim()) {
642
648
  const guidance = getAlphaGuidance(identity);
643
- console.log(
644
- JSON.stringify(
645
- {
646
- enrolled: true,
647
- prepared: 0,
648
- sent: 0,
649
- failed: 0,
650
- skipped: 0,
651
- guidance,
652
- },
653
- null,
654
- 2,
655
- ),
649
+ throw new CLIError(
650
+ `[alpha upload] ${guidance.message}`,
651
+ "OPERATION_FAILED",
652
+ guidance.next_command,
656
653
  );
657
- console.error(`[alpha upload] ${guidance.message}`);
658
- console.error(`[alpha upload] Next: ${guidance.next_command}`);
659
- process.exit(1);
660
654
  }
661
655
 
662
656
  const db = getDb();
@@ -742,10 +736,11 @@ Output:
742
736
  break;
743
737
  }
744
738
  default:
745
- console.error(
746
- `Unknown alpha subcommand: ${sub}\nRun 'selftune alpha --help' for available subcommands.`,
739
+ throw new CLIError(
740
+ `Unknown alpha subcommand: ${sub}`,
741
+ "UNKNOWN_COMMAND",
742
+ "selftune alpha --help",
747
743
  );
748
- process.exit(1);
749
744
  }
750
745
  break;
751
746
  }
@@ -767,8 +762,11 @@ Output:
767
762
  };
768
763
  if (!hookName || !HOOK_MAP[hookName]) {
769
764
  const available = Object.keys(HOOK_MAP).join(", ");
770
- console.error(`Unknown hook: ${hookName ?? "(none)"}\nAvailable hooks: ${available}`);
771
- process.exit(1);
765
+ throw new CLIError(
766
+ `Unknown hook: ${hookName ?? "(none)"}. Available: ${available}`,
767
+ "UNKNOWN_COMMAND",
768
+ "selftune hook prompt-log",
769
+ );
772
770
  }
773
771
  const { resolve, dirname } = await import("node:path");
774
772
  const { fileURLToPath } = await import("node:url");
@@ -782,6 +780,5 @@ Output:
782
780
  break;
783
781
  }
784
782
  default:
785
- console.error(`Unknown command: ${command}\nRun 'selftune --help' for available commands.`);
786
- process.exit(1);
783
+ throw new CLIError(`Unknown command: ${command}`, "UNKNOWN_COMMAND", "selftune --help");
787
784
  }
@@ -55,6 +55,7 @@ import type {
55
55
  SessionTelemetryRecord,
56
56
  TranscriptMetrics,
57
57
  } from "../types.js";
58
+ import { CLIError, handleCLIError } from "../utils/cli-error.js";
58
59
  import { loadMarker, saveMarker } from "../utils/jsonl.js";
59
60
  import { isActionableQueryText } from "../utils/query-filter.js";
60
61
  import {
@@ -326,26 +327,36 @@ export function buildCanonicalRecordsFromReplay(session: ParsedSession): Canonic
326
327
 
327
328
  // --- CLI main ---
328
329
  export function cliMain(): void {
329
- const { values } = parseArgs({
330
- options: {
331
- "projects-dir": { type: "string", default: CLAUDE_CODE_PROJECTS_DIR },
332
- since: { type: "string" },
333
- "dry-run": { type: "boolean", default: false },
334
- force: { type: "boolean", default: false },
335
- verbose: { type: "boolean", short: "v", default: false },
336
- },
337
- strict: true,
338
- });
330
+ let values: Record<string, string | boolean | undefined>;
331
+ try {
332
+ ({ values } = parseArgs({
333
+ options: {
334
+ "projects-dir": { type: "string", default: CLAUDE_CODE_PROJECTS_DIR },
335
+ since: { type: "string" },
336
+ "dry-run": { type: "boolean", default: false },
337
+ force: { type: "boolean", default: false },
338
+ verbose: { type: "boolean", short: "v", default: false },
339
+ },
340
+ strict: true,
341
+ }));
342
+ } catch (err) {
343
+ throw new CLIError(
344
+ err instanceof Error ? err.message : String(err),
345
+ "INVALID_FLAG",
346
+ "selftune ingest claude --since 2026-01-01",
347
+ );
348
+ }
339
349
 
340
350
  const projectsDir = values["projects-dir"] ?? CLAUDE_CODE_PROJECTS_DIR;
341
351
  let since: Date | undefined;
342
352
  if (values.since) {
343
353
  since = new Date(values.since);
344
354
  if (Number.isNaN(since.getTime())) {
345
- console.error(
346
- `Error: Invalid --since date: "${values.since}". Use a valid date format (e.g., 2026-01-01).`,
355
+ throw new CLIError(
356
+ `Invalid --since date: "${values.since}"`,
357
+ "INVALID_FLAG",
358
+ "selftune ingest claude --since 2026-01-01",
347
359
  );
348
- process.exit(1);
349
360
  }
350
361
  }
351
362
 
@@ -401,5 +412,9 @@ export function cliMain(): void {
401
412
  }
402
413
 
403
414
  if (import.meta.main) {
404
- cliMain();
415
+ try {
416
+ cliMain();
417
+ } catch (err) {
418
+ handleCLIError(err);
419
+ }
405
420
  }
@@ -49,6 +49,7 @@ import type {
49
49
  SessionTelemetryRecord,
50
50
  SkillUsageRecord,
51
51
  } from "../types.js";
52
+ import { handleCLIError } from "../utils/cli-error.js";
52
53
  import { loadMarker, saveMarker } from "../utils/jsonl.js";
53
54
  import { extractActionableQueryText } from "../utils/query-filter.js";
54
55
  import {
@@ -717,5 +718,9 @@ export function cliMain(): void {
717
718
  }
718
719
 
719
720
  if (import.meta.main) {
720
- cliMain();
721
+ try {
722
+ cliMain();
723
+ } catch (err) {
724
+ handleCLIError(err);
725
+ }
721
726
  }
@@ -44,6 +44,7 @@ import {
44
44
  import { installAgentFiles } from "./claude-agents.js";
45
45
  import { CLAUDE_CODE_HOOK_KEYS, SELFTUNE_CONFIG_DIR, SELFTUNE_CONFIG_PATH } from "./constants.js";
46
46
  import type { AgentCommandGuidance, AlphaIdentity, SelftuneConfig } from "./types.js";
47
+ import { CLIError, handleCLIError } from "./utils/cli-error.js";
47
48
  import { hookKeyHasSelftuneEntry } from "./utils/hooks.js";
48
49
  import { detectAgent } from "./utils/llm-call.js";
49
50
 
@@ -692,8 +693,11 @@ export async function cliMain(): Promise<void> {
692
693
  try {
693
694
  validateAlphaMetadataFlags(values.alpha, values["alpha-email"], values["alpha-name"]);
694
695
  } catch (error) {
695
- console.error(error instanceof Error ? error.message : String(error));
696
- process.exit(1);
696
+ throw new CLIError(
697
+ error instanceof Error ? error.message : String(error),
698
+ "INVALID_FLAG",
699
+ "Pass --alpha along with --alpha-email and --alpha-name.",
700
+ );
697
701
  }
698
702
 
699
703
  // Check for existing config without force
@@ -890,10 +894,11 @@ export async function cliMain(): Promise<void> {
890
894
  });
891
895
 
892
896
  if (!scheduleResult.activated) {
893
- console.error(
894
- "Failed to activate the autonomous scheduler. Re-run with --schedule-format or use `selftune schedule --install --dry-run` to inspect the generated artifacts first.",
897
+ throw new CLIError(
898
+ "Failed to activate the autonomous scheduler.",
899
+ "OPERATION_FAILED",
900
+ "Re-run with --schedule-format or use `selftune schedule --install --dry-run` to inspect the generated artifacts first.",
895
901
  );
896
- process.exit(1);
897
902
  }
898
903
 
899
904
  console.log(
@@ -906,10 +911,11 @@ export async function cliMain(): Promise<void> {
906
911
  }),
907
912
  );
908
913
  } catch (err) {
909
- console.error(
914
+ throw new CLIError(
910
915
  `Failed to enable autonomy: ${err instanceof Error ? err.message : String(err)}`,
916
+ "OPERATION_FAILED",
917
+ "Re-run with --schedule-format or use `selftune schedule --install --dry-run` to inspect artifacts.",
911
918
  );
912
- process.exit(1);
913
919
  }
914
920
  }
915
921
  }
@@ -947,7 +953,6 @@ if (isMain) {
947
953
  console.error(JSON.stringify(err.payload));
948
954
  process.exit(1);
949
955
  }
950
- console.error(`[FATAL] ${err}`);
951
- process.exit(1);
956
+ handleCLIError(err);
952
957
  });
953
958
  }
@@ -26,6 +26,7 @@ import type {
26
26
  SessionTelemetryRecord,
27
27
  SkillUsageRecord,
28
28
  } from "../types.js";
29
+ import { CLIError, handleCLIError } from "../utils/cli-error.js";
29
30
  import {
30
31
  filterActionableQueryRecords,
31
32
  filterActionableSkillUsageRecords,
@@ -354,34 +355,52 @@ Options:
354
355
  }
355
356
 
356
357
  if (!values.skill || !values["skill-path"]) {
357
- console.error("[ERROR] --skill and --skill-path are required");
358
- process.exit(1);
358
+ throw new CLIError(
359
+ "--skill and --skill-path are required.",
360
+ "MISSING_FLAG",
361
+ "Usage: selftune watch --skill <name> --skill-path <path>",
362
+ );
359
363
  }
360
364
  if ((values["sync-force"] ?? false) && !(values["sync-first"] ?? false)) {
361
- console.error("[ERROR] --sync-force requires --sync-first");
362
- process.exit(1);
365
+ throw new CLIError(
366
+ "--sync-force requires --sync-first.",
367
+ "INVALID_FLAG",
368
+ "Add --sync-first when using --sync-force.",
369
+ );
363
370
  }
364
371
 
365
372
  const rawWindow = values.window ?? "20";
366
373
  if (!/^\d+$/.test(rawWindow)) {
367
- console.error("[ERROR] --window must be a positive integer >= 1");
368
- process.exit(1);
374
+ throw new CLIError(
375
+ "--window must be a positive integer >= 1.",
376
+ "INVALID_FLAG",
377
+ "selftune watch --window 20",
378
+ );
369
379
  }
370
380
  const windowSessions = Number.parseInt(rawWindow, 10);
371
381
  if (windowSessions < 1) {
372
- console.error("[ERROR] --window must be a positive integer >= 1");
373
- process.exit(1);
382
+ throw new CLIError(
383
+ "--window must be a positive integer >= 1.",
384
+ "INVALID_FLAG",
385
+ "selftune watch --window 20",
386
+ );
374
387
  }
375
388
 
376
389
  const rawThreshold = values.threshold ?? "0.1";
377
390
  if (!/^\d+(\.\d+)?$/.test(rawThreshold)) {
378
- console.error("[ERROR] --threshold must be a finite number between 0 and 1");
379
- process.exit(1);
391
+ throw new CLIError(
392
+ "--threshold must be a finite number between 0 and 1.",
393
+ "INVALID_FLAG",
394
+ "selftune watch --threshold 0.1",
395
+ );
380
396
  }
381
397
  const regressionThreshold = Number.parseFloat(rawThreshold);
382
398
  if (regressionThreshold < 0 || regressionThreshold > 1) {
383
- console.error("[ERROR] --threshold must be a finite number between 0 and 1");
384
- process.exit(1);
399
+ throw new CLIError(
400
+ "--threshold must be a finite number between 0 and 1.",
401
+ "INVALID_FLAG",
402
+ "selftune watch --threshold 0.1",
403
+ );
385
404
  }
386
405
 
387
406
  const result = await watch({
@@ -399,8 +418,5 @@ Options:
399
418
  }
400
419
 
401
420
  if (import.meta.main) {
402
- cliMain().catch((err) => {
403
- console.error(`[FATAL] ${err}`);
404
- process.exit(1);
405
- });
421
+ cliMain().catch(handleCLIError);
406
422
  }