@stupify/cli 0.0.9 โ†’ 0.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/ui.js ADDED
@@ -0,0 +1,143 @@
1
+ import { confirm as clackConfirm, intro as clackIntro, isCancel, log, note, outro as clackOutro, progress, spinner, } from "@clack/prompts";
2
+ import { createReadStream, createWriteStream } from "node:fs";
3
+ import { platform } from "node:os";
4
+ import { stdin, stderr, stdout } from "node:process";
5
+ import pc from "picocolors";
6
+ export function createCliUi(options = {}) {
7
+ const quiet = options.quiet ?? false;
8
+ const output = stderr;
9
+ function shouldWrite(logOptions) {
10
+ return logOptions?.force === true || !quiet;
11
+ }
12
+ function withPromptIo(run) {
13
+ const io = promptIo();
14
+ return run(io).finally(() => io.close());
15
+ }
16
+ return {
17
+ intro(title, logOptions) {
18
+ if (shouldWrite(logOptions))
19
+ clackIntro(title, { output });
20
+ },
21
+ outro(message, logOptions) {
22
+ if (shouldWrite(logOptions))
23
+ clackOutro(message, { output });
24
+ },
25
+ note(message, title, logOptions) {
26
+ if (shouldWrite(logOptions))
27
+ note(message, title, { output });
28
+ },
29
+ info(message, logOptions) {
30
+ if (shouldWrite(logOptions))
31
+ log.info(message, { output });
32
+ },
33
+ step(message, logOptions) {
34
+ if (shouldWrite(logOptions))
35
+ log.step(message, { output });
36
+ },
37
+ success(message, logOptions) {
38
+ if (shouldWrite(logOptions))
39
+ log.success(message, { output });
40
+ },
41
+ warn(message, logOptions) {
42
+ if (shouldWrite(logOptions))
43
+ log.warn(message, { output });
44
+ },
45
+ error(message, logOptions) {
46
+ if (shouldWrite(logOptions))
47
+ log.error(message, { output });
48
+ },
49
+ debug(message) {
50
+ if (!quiet)
51
+ log.message(message, { output, symbol: pc.dim("trace") });
52
+ },
53
+ async confirm(message) {
54
+ return withPromptIo(async (io) => {
55
+ const result = await clackConfirm({
56
+ message,
57
+ active: "Yes",
58
+ inactive: "No",
59
+ initialValue: false,
60
+ input: io.input,
61
+ output: io.output,
62
+ });
63
+ if (isCancel(result))
64
+ return false;
65
+ return result;
66
+ });
67
+ },
68
+ spinner(message, logOptions) {
69
+ if (!shouldWrite(logOptions))
70
+ return silentSpinner();
71
+ const active = spinner({ output });
72
+ active.start(message);
73
+ return active;
74
+ },
75
+ progress(message, max, logOptions) {
76
+ if (!shouldWrite(logOptions))
77
+ return silentProgress();
78
+ const active = progress({ output, max });
79
+ active.start(message);
80
+ return active;
81
+ },
82
+ writeStdout(text) {
83
+ stdout.write(text.endsWith("\n") ? text : `${text}\n`);
84
+ },
85
+ };
86
+ }
87
+ export const format = {
88
+ heading: (value) => pc.bold(value),
89
+ label: (value) => pc.cyan(value),
90
+ muted: (value) => pc.dim(value),
91
+ success: (value) => pc.green(value),
92
+ warn: (value) => pc.yellow(value),
93
+ error: (value) => pc.red(value),
94
+ };
95
+ export function diagnostic(message) {
96
+ log.message(message, {
97
+ output: stderr,
98
+ symbol: pc.dim("ยท"),
99
+ spacing: 0,
100
+ withGuide: false,
101
+ });
102
+ }
103
+ export function diagnosticError(message) {
104
+ log.error(message, { output: stderr, spacing: 0, withGuide: false });
105
+ }
106
+ function promptIo() {
107
+ if (stdin.isTTY && stderr.isTTY) {
108
+ return { input: stdin, output: stderr, close: () => undefined };
109
+ }
110
+ if (platform() === "win32") {
111
+ throw new Error("No interactive terminal found. Run `stupify` once in an interactive terminal to set up the model.");
112
+ }
113
+ const input = createReadStream("/dev/tty");
114
+ const output = createWriteStream("/dev/tty");
115
+ return {
116
+ input,
117
+ output,
118
+ close: () => closePromptIo(input, output),
119
+ };
120
+ }
121
+ function closePromptIo(input, output) {
122
+ input.destroy();
123
+ output.end();
124
+ }
125
+ function silentSpinner() {
126
+ return {
127
+ start: () => undefined,
128
+ stop: () => undefined,
129
+ cancel: () => undefined,
130
+ error: () => undefined,
131
+ message: () => undefined,
132
+ clear: () => undefined,
133
+ get isCancelled() {
134
+ return false;
135
+ },
136
+ };
137
+ }
138
+ function silentProgress() {
139
+ return {
140
+ ...silentSpinner(),
141
+ advance: () => undefined,
142
+ };
143
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stupify/cli",
3
- "version": "0.0.9",
3
+ "version": "0.0.10",
4
4
  "description": "Local-only diagnostic CLI for checking whether AI is making you dumber.",
5
5
  "private": false,
6
6
  "type": "module",
@@ -44,6 +44,8 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@ataraxy-labs/sem": "^0.3.24",
47
+ "@clack/prompts": "^1.2.0",
48
+ "picocolors": "^1.1.1",
47
49
  "repomix": "^1.14.0"
48
50
  }
49
51
  }
package/src/analysis.ts CHANGED
@@ -2,6 +2,7 @@ import { cachedJson, fingerprint } from "./cache.ts";
2
2
  import type { LocalModel } from "./model.ts";
3
3
  import { searchPrompt } from "./prompts.ts";
4
4
  import type { SearchMatch, SemChangeSet, SemContext, SemContextPack, StupifyCheck } from "./types.ts";
5
+ import { diagnostic, diagnosticError } from "./ui.ts";
5
6
 
6
7
  export async function runSearch(
7
8
  model: LocalModel,
@@ -150,8 +151,8 @@ Your previous response was not valid JSON. Return the requested JSON object only
150
151
  const retryParsed = parseJson(retry);
151
152
  if (retryParsed.ok) return retryParsed.value;
152
153
 
153
- console.error("Raw model output:");
154
- console.error(retry);
154
+ diagnosticError("Raw model output:");
155
+ diagnostic(retry);
155
156
  throw new Error("Model returned invalid JSON.");
156
157
  }
157
158
 
package/src/constants.ts CHANGED
@@ -1,4 +1,4 @@
1
- export const VERSION = "0.0.9";
1
+ export const VERSION = "0.0.10";
2
2
  import type { ModelConfig, ModelId } from "./types.ts";
3
3
 
4
4
  export const DEFAULT_MODEL_ID: ModelId = "gemma-4-e2b";
package/src/model.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import { execFile, spawn } from "node:child_process";
2
- import { createReadStream, createWriteStream } from "node:fs";
3
2
  import {
4
3
  mkdir,
5
4
  open,
@@ -10,16 +9,11 @@ import {
10
9
  writeFile,
11
10
  } from "node:fs/promises";
12
11
  import { homedir, platform } from "node:os";
13
- import {
14
- stdin as input,
15
- stderr as statusOutput,
16
- stdout as output,
17
- } from "node:process";
18
- import { createInterface } from "node:readline/promises";
19
12
  import path from "node:path";
20
13
  import { promisify } from "node:util";
21
14
  import { MODEL_REGISTRY } from "./constants.ts";
22
15
  import type { ModelId } from "./types.ts";
16
+ import type { CliUi } from "./ui.ts";
23
17
 
24
18
  const execFileAsync = promisify(execFile);
25
19
  const LLAMA_SERVER_HOST = "127.0.0.1";
@@ -51,22 +45,23 @@ export type LocalModel = Readonly<{
51
45
 
52
46
  export async function firstRunModelBootstrap(
53
47
  modelId: ModelId,
48
+ ui: CliUi,
54
49
  ): Promise<string> {
55
50
  const selectedModel = MODEL_REGISTRY[modelId];
56
51
  const modelDir = path.join(cacheDir(), "models");
57
52
  const modelPath = path.join(modelDir, selectedModel.file);
58
53
  if (await exists(modelPath)) return modelPath;
59
54
 
60
- console.error(`No local Stupify model found.
55
+ ui.note(`No local Stupify model found.
61
56
  Stupify runs locally.
62
57
  Download this model now?
63
58
  Model: ${selectedModel.name}
64
- Size: ${selectedModel.size}`);
59
+ Size: ${selectedModel.size}`, "Setup", { force: true });
65
60
 
66
- if (!(await confirm("Continue? y/N "))) throw new Error("Setup cancelled.");
61
+ if (!(await ui.confirm("Continue?"))) throw new Error("Setup cancelled.");
67
62
 
68
63
  await mkdir(modelDir, { recursive: true });
69
- await downloadModel(modelPath, selectedModel.url);
64
+ await downloadModel(modelPath, selectedModel.url, ui);
70
65
  if (!(await exists(modelPath)))
71
66
  throw new Error("Model download failed: file was not created.");
72
67
  return modelPath;
@@ -75,18 +70,17 @@ Size: ${selectedModel.size}`);
75
70
  export async function loadLocalModel(
76
71
  modelPath: string,
77
72
  modelId: ModelId,
78
- profile: ModelProfile = "scout",
73
+ profile: ModelProfile,
74
+ ui: CliUi,
79
75
  ): Promise<LocalModel> {
80
76
  const selectedModel = MODEL_REGISTRY[modelId];
81
77
  const runtime = modelRuntime(profile);
82
78
  const runningModel = await runningServerModel(runtime.baseUrl);
83
79
 
84
80
  if (runningModel) {
85
- if (runningModel !== modelId) await stopManagedServer(runtime);
81
+ if (runningModel !== modelId) await stopManagedServer(runtime, ui);
86
82
  if (runningModel === modelId) {
87
- console.error(
88
- `Using local model: ${selectedModel.name}`,
89
- );
83
+ ui.info(`Using local model: ${selectedModel.name}`);
90
84
  return {
91
85
  id: modelId,
92
86
  name: selectedModel.name,
@@ -97,8 +91,15 @@ export async function loadLocalModel(
97
91
  }
98
92
 
99
93
  await ensureLlamaServerBinary();
100
- await startLlamaServer(modelPath, modelId, selectedModel.name, runtime);
101
- await waitForServer(runtime.baseUrl, modelId);
94
+ await startLlamaServer(modelPath, modelId, selectedModel.name, runtime, ui);
95
+ const ready = ui.spinner(`Waiting for local ${profile} model`);
96
+ try {
97
+ await waitForServer(runtime.baseUrl, modelId);
98
+ ready.stop(`Local ${profile} model ready`);
99
+ } catch (error) {
100
+ ready.error(`Local ${profile} model failed to start`);
101
+ throw error;
102
+ }
102
103
  return {
103
104
  id: modelId,
104
105
  name: selectedModel.name,
@@ -159,6 +160,7 @@ async function startLlamaServer(
159
160
  modelId: ModelId,
160
161
  modelName: string,
161
162
  runtime: ModelRuntime,
163
+ ui: CliUi,
162
164
  ): Promise<void> {
163
165
  const logDir = path.join(cacheDir(), "logs");
164
166
  await mkdir(logDir, { recursive: true });
@@ -166,8 +168,8 @@ async function startLlamaServer(
166
168
  const out = await open(logPath, "a");
167
169
  const err = await open(logPath, "a");
168
170
 
169
- console.error(`Starting local model server: ${modelName}`);
170
- console.error(`llama-server log: ${logPath}`);
171
+ ui.step(`Starting local model server: ${modelName}`);
172
+ ui.info(`llama-server log: ${logPath}`);
171
173
 
172
174
  const args = [
173
175
  "-m",
@@ -206,7 +208,7 @@ async function startLlamaServer(
206
208
  await err.close();
207
209
  }
208
210
 
209
- async function stopManagedServer(runtime: ModelRuntime): Promise<void> {
211
+ async function stopManagedServer(runtime: ModelRuntime, ui: CliUi): Promise<void> {
210
212
  const pid = await managedServerPid(runtime);
211
213
  if (!pid) {
212
214
  const runningModel = await runningServerModel(runtime.baseUrl);
@@ -214,9 +216,7 @@ async function stopManagedServer(runtime: ModelRuntime): Promise<void> {
214
216
  Stop it before switching models, or use STUPIFY_LLAMA_SERVER_URL for that server.`);
215
217
  }
216
218
 
217
- console.error(
218
- "Restarting local model server for selected model.",
219
- );
219
+ ui.step("Restarting local model server for selected model.");
220
220
  try {
221
221
  process.kill(pid, "SIGTERM");
222
222
  } catch {
@@ -279,11 +279,13 @@ function sleep(ms: number): Promise<void> {
279
279
  async function downloadModel(
280
280
  modelPath: string,
281
281
  modelUrl: string,
282
+ ui: CliUi,
282
283
  ): Promise<void> {
283
284
  const tempPath = `${modelPath}.download`;
284
285
  await rm(tempPath, { force: true });
285
286
 
286
- console.error("Downloading model...");
287
+ const downloadSpinner = ui.spinner("Downloading model");
288
+ let downloadProgress: ReturnType<CliUi["progress"]> | null = null;
287
289
  try {
288
290
  const response = await fetch(modelUrl);
289
291
  if (!response.ok || !response.body)
@@ -292,8 +294,13 @@ async function downloadModel(
292
294
  const total = Number(response.headers.get("content-length") ?? 0);
293
295
  let received = 0;
294
296
  let lastPrint = 0;
297
+ let lastProgressBytes = 0;
295
298
  const reader = response.body.getReader();
296
299
  const file = await open(tempPath, "wx");
300
+ if (total > 0) {
301
+ downloadSpinner.clear();
302
+ downloadProgress = ui.progress("Downloading model", total);
303
+ }
297
304
 
298
305
  try {
299
306
  while (true) {
@@ -304,51 +311,38 @@ async function downloadModel(
304
311
  const now = Date.now();
305
312
  if (total > 0 && now - lastPrint > 500) {
306
313
  lastPrint = now;
307
- statusOutput.write(
308
- `\r${formatBytes(received)} / ${formatBytes(total)}`,
314
+ downloadProgress?.advance(
315
+ received - lastProgressBytes,
316
+ `${formatBytes(received)} / ${formatBytes(total)}`,
309
317
  );
318
+ lastProgressBytes = received;
310
319
  }
311
320
  }
312
321
  } finally {
313
322
  await file.close();
314
323
  }
315
324
 
316
- if (total > 0)
317
- statusOutput.write(
318
- `\r${formatBytes(received)} / ${formatBytes(total)}\n`,
325
+ if (downloadProgress && received > lastProgressBytes) {
326
+ downloadProgress.advance(
327
+ received - lastProgressBytes,
328
+ `${formatBytes(received)} / ${formatBytes(total)}`,
319
329
  );
330
+ }
331
+ const activeProgress = downloadProgress ?? downloadSpinner;
332
+ activeProgress.stop(
333
+ total > 0
334
+ ? `Downloaded ${formatBytes(received)} / ${formatBytes(total)}`
335
+ : "Downloaded model",
336
+ );
320
337
  await rename(tempPath, modelPath);
321
338
  } catch (error) {
339
+ const activeProgress = downloadProgress ?? downloadSpinner;
340
+ activeProgress.error("Model download failed");
322
341
  await rm(tempPath, { force: true });
323
342
  throw error;
324
343
  }
325
344
  }
326
345
 
327
- async function confirm(question: string): Promise<boolean> {
328
- const rl = createInterface(terminalIo());
329
- try {
330
- const answer = (await rl.question(question)).trim().toLowerCase();
331
- return answer === "y" || answer === "yes";
332
- } finally {
333
- rl.close();
334
- }
335
- }
336
-
337
- function terminalIo(): {
338
- input: NodeJS.ReadableStream;
339
- output: NodeJS.WritableStream;
340
- } {
341
- if (input.isTTY) return { input, output };
342
- if (platform() !== "win32")
343
- return {
344
- input: createReadStream("/dev/tty"),
345
- output: createWriteStream("/dev/tty"),
346
- };
347
- throw new Error(
348
- "No local Stupify model found. Run `stupify` once in an interactive terminal to set up the model.",
349
- );
350
- }
351
-
352
346
  function cacheDir(): string {
353
347
  if (process.env.STUPIFY_CACHE_DIR) return process.env.STUPIFY_CACHE_DIR;
354
348
  if (process.env.XDG_CACHE_HOME)
package/src/render.ts CHANGED
@@ -1,45 +1,42 @@
1
1
  import { VERSION } from "./constants.ts";
2
2
  import type { SearchCommand, SearchRunJson } from "./types.ts";
3
+ import { format } from "./ui.ts";
3
4
 
4
5
  export function renderSearchRun(run: SearchRunJson, command: SearchCommand): string {
5
6
  if (command.json) return JSON.stringify(run, null, 2);
6
7
 
7
8
  if (run.stats.skipped && run.stats.skipReason === "input_too_large") {
8
- return `๐Ÿง™ stupify ๐Ÿช„
9
- Search input is too large for precise local search.
10
- Size:
9
+ return `${format.heading("Search input is too large for precise local search.")}
10
+ ${format.heading("Size:")}
11
11
  ~${run.stats.inputTokens ?? "unknown"} tokens
12
- Limit:
12
+ ${format.heading("Limit:")}
13
13
  ${run.stats.inputTokenCap ?? "unknown"} tokens
14
14
  Stupify skipped the search rather than review truncated context.
15
15
  Nothing was blocked.
16
- Try:
16
+ ${format.heading("Try:")}
17
17
  rerun with ${sourceHint(command)} --max-search-input-tokens ${Math.max((run.stats.inputTokens ?? 12_000) + 1, (run.stats.inputTokenCap ?? 12_000) * 2)}`;
18
18
  }
19
19
 
20
20
  if (run.stats.skipped && run.stats.skipReason === "no_candidates") {
21
- return `๐Ÿง™ stupify ๐Ÿช„
22
- Search complete.
23
- Patterns: ${run.patterns.join(", ")}
24
- No search targets found.`;
21
+ return `${format.heading("Search complete.")}
22
+ ${format.label("Patterns:")} ${run.patterns.join(", ")}
23
+ ${format.success("No search targets found.")}`;
25
24
  }
26
25
 
27
26
  if (run.matches.length === 0) {
28
- return `๐Ÿง™ stupify ๐Ÿช„
29
- Search complete.
30
- Patterns: ${run.patterns.join(", ")}
31
- No judgment-offload signals found.`;
27
+ return `${format.heading("Search complete.")}
28
+ ${format.label("Patterns:")} ${run.patterns.join(", ")}
29
+ ${format.success("No judgment-offload signals found.")}`;
32
30
  }
33
31
 
34
- return `๐Ÿง™ stupify ๐Ÿช„
35
- AI SLOP DETECTED
32
+ return `${format.warn("AI SLOP DETECTED")}
36
33
  ${run.matches.map((match, index) => `${index + 1}.
37
- who: ${committerLabel(run)}
38
- what: ${match.patternId} - ${match.reason}
39
- when: ${sourceLabel(command)}
40
- where: ${match.proof}
41
- why: ${match.checkWhy ?? "This pattern may indicate judgment-offload."}`).join("\n")}
42
- Search mode is warn-only.`;
34
+ ${format.muted("who:")} ${committerLabel(run)}
35
+ ${format.muted("what:")} ${match.patternId} - ${match.reason}
36
+ ${format.muted("when:")} ${sourceLabel(command)}
37
+ ${format.muted("where:")} ${match.proof}
38
+ ${format.muted("why:")} ${match.checkWhy ?? "This pattern may indicate judgment-offload."}`).join("\n")}
39
+ ${format.muted("Search mode is warn-only.")}`;
43
40
  }
44
41
 
45
42
  export function helpText(): string {
@@ -13,6 +13,7 @@ import {
13
13
  sourceRangeSince,
14
14
  stagedDiff,
15
15
  } from "./git.ts";
16
+ import { diagnostic } from "./ui.ts";
16
17
  import type {
17
18
  SearchCommand,
18
19
  SemChange,
@@ -153,14 +154,14 @@ async function withContextWorkspace(changeSet: SemChangeSet, debugSem: boolean):
153
154
  }
154
155
 
155
156
  async function runSem(args: readonly string[], debugSem: boolean, cwd = process.cwd()): Promise<unknown> {
156
- if (debugSem) console.error(`sem ${args.join(" ")}`);
157
+ if (debugSem) diagnostic(`sem ${args.join(" ")}`);
157
158
  const { command, commandArgs } = resolveSemCommand(args);
158
159
  try {
159
160
  const { stdout, stderr } = await execFileAsync(command, commandArgs, {
160
161
  cwd,
161
162
  maxBuffer: 128 * 1024 * 1024,
162
163
  });
163
- if (debugSem && stderr.trim()) console.error(stderr.trim());
164
+ if (debugSem && stderr.trim()) diagnostic(stderr.trim());
164
165
  return JSON.parse(stdout);
165
166
  } catch (error) {
166
167
  const message = error instanceof Error ? error.message : String(error);
@@ -169,7 +170,7 @@ async function runSem(args: readonly string[], debugSem: boolean, cwd = process.
169
170
  }
170
171
 
171
172
  async function runSemWithInput(args: readonly string[], stdin: string, debugSem: boolean): Promise<unknown> {
172
- if (debugSem) console.error(`sem ${args.join(" ")}`);
173
+ if (debugSem) diagnostic(`sem ${args.join(" ")}`);
173
174
  const { command, commandArgs } = resolveSemCommand(args);
174
175
  return new Promise((resolve, reject) => {
175
176
  const child = spawn(command, commandArgs, { stdio: ["pipe", "pipe", "pipe"] });
@@ -180,7 +181,7 @@ async function runSemWithInput(args: readonly string[], stdin: string, debugSem:
180
181
  child.on("error", (error) => reject(error));
181
182
  child.on("close", (code) => {
182
183
  const stderrText = Buffer.concat(stderr).toString("utf8");
183
- if (debugSem && stderrText.trim()) console.error(stderrText.trim());
184
+ if (debugSem && stderrText.trim()) diagnostic(stderrText.trim());
184
185
  if (code !== 0) {
185
186
  reject(new Error(`sem failed with exit code ${code}${stderrText ? `: ${stderrText.trim()}` : ""}`));
186
187
  return;
@@ -196,7 +197,7 @@ async function runSemWithInput(args: readonly string[], stdin: string, debugSem:
196
197
  }
197
198
 
198
199
  async function git(args: readonly string[], debugSem: boolean): Promise<void> {
199
- if (debugSem) console.error(`git ${args.join(" ")}`);
200
+ if (debugSem) diagnostic(`git ${args.join(" ")}`);
200
201
  await execFileAsync("git", [...args], { maxBuffer: 128 * 1024 * 1024 });
201
202
  }
202
203
 
package/src/stupify.ts CHANGED
@@ -20,46 +20,49 @@ import {
20
20
  } from "./search-profile.ts";
21
21
  import { semChangeSetForCommand } from "./sem-provider.ts";
22
22
  import { createTracer } from "./trace.ts";
23
+ import { createCliUi, type CliUi } from "./ui.ts";
23
24
  import type { SearchCommand, SearchMatch, SearchProfile, SearchRunJson, SemContext, SemContextPack, StupifyCheck } from "./types.ts";
24
25
 
25
26
  export async function main(argv = process.argv.slice(2)): Promise<number> {
26
27
  const startedAt = Date.now();
28
+ let ui = createCliUi();
27
29
  try {
28
30
  const command = parseCommand(argv);
29
31
  if (command.kind === "help") {
30
- console.log(helpText());
32
+ ui.writeStdout(helpText());
31
33
  return 0;
32
34
  }
33
35
  if (command.kind === "hook") {
34
- console.log(await runHookCommand(command.action));
36
+ ui.writeStdout(await runHookCommand(command.action));
35
37
  return 0;
36
38
  }
37
39
  if (command.kind === "doctor") {
38
40
  const result = await runDoctor();
39
- console.log(result.text);
41
+ ui.writeStdout(result.text);
40
42
  return result.exitCode;
41
43
  }
42
44
  if (command.kind === "bench-search") {
43
45
  const { runSearchBench } = await import("./search-bench.ts");
44
- console.log(await runSearchBench(command.configPath));
46
+ ui.writeStdout(await runSearchBench(command.configPath));
45
47
  return 0;
46
48
  }
47
49
 
48
- const run = await runSearchCommand(command, startedAt);
49
- console.log(renderSearchRun(run, command));
50
+ ui = createCliUi({ quiet: command.json });
51
+ const run = await runSearchCommand(command, startedAt, ui);
52
+ ui.writeStdout(renderSearchRun(run, command));
50
53
  return 0;
51
54
  } catch (error) {
52
- console.error(error instanceof Error ? error.message : String(error));
55
+ ui.error(error instanceof Error ? error.message : String(error), { force: true });
53
56
  return 1;
54
57
  }
55
58
  }
56
59
 
57
- export async function runSearchCommand(command: SearchCommand, startedAt: number): Promise<SearchRunJson> {
60
+ export async function runSearchCommand(command: SearchCommand, startedAt: number, ui = createCliUi({ quiet: command.json })): Promise<SearchRunJson> {
58
61
  const t = createTracer({
59
62
  writeLine: () => undefined,
60
63
  onEvent: (event) => {
61
64
  if (command.json) return;
62
- console.error(formatStep(event.name, event.ms, event.count, event.detail));
65
+ ui.step(formatStep(event.name, event.ms, event.count, event.detail));
63
66
  },
64
67
  });
65
68
 
@@ -68,7 +71,7 @@ export async function runSearchCommand(command: SearchCommand, startedAt: number
68
71
  const patternIds = checks.map((check) => check.id);
69
72
  const maxCandidates = effectiveMaxCandidates(command.maxCandidates, profile);
70
73
  const maxSearchInputTokens = effectiveMaxSearchInputTokens(command.maxSearchInputTokens, profile);
71
- printRunPlan(command, patternIds);
74
+ printRunPlan(command, patternIds, ui);
72
75
  const { value: changeSet } = await t.trace(
73
76
  "entity.diff",
74
77
  () => semChangeSetForCommand(command),
@@ -200,14 +203,14 @@ export async function runSearchCommand(command: SearchCommand, startedAt: number
200
203
  }
201
204
 
202
205
  if (batches.wasSplit && !command.json) {
203
- console.error(`Search input is large; queued ${batches.batches.length} smaller search batches.`);
206
+ ui.warn(`Search input is large; queued ${batches.batches.length} smaller search batches.`);
204
207
  if (batches.skippedTargets > 0) {
205
- console.error(`Skipped ${batches.skippedTargets} oversized targets that could not fit alone.`);
208
+ ui.warn(`Skipped ${batches.skippedTargets} oversized targets that could not fit alone.`);
206
209
  }
207
210
  }
208
211
 
209
- const modelPath = await firstRunModelBootstrap(command.model);
210
- const model = await loadLocalModel(modelPath, command.model, "scout");
212
+ const modelPath = await firstRunModelBootstrap(command.model, ui);
213
+ const model = await loadLocalModel(modelPath, command.model, "scout", ui);
211
214
  const matches = [];
212
215
  let modelCalls = 0;
213
216
  let inputTokens = 0;
@@ -218,7 +221,7 @@ export async function runSearchCommand(command: SearchCommand, startedAt: number
218
221
  if (batchInputTokens > maxSearchInputTokens) {
219
222
  exactSkippedTargets += batch.contexts.length;
220
223
  if (!command.json) {
221
- console.error(`Skipped ${batch.contexts.length} targets after exact token count exceeded the limit.`);
224
+ ui.warn(`Skipped ${batch.contexts.length} targets after exact token count exceeded the limit.`);
222
225
  }
223
226
  continue;
224
227
  }
@@ -419,11 +422,17 @@ function buildSearchRequest(
419
422
  function printRunPlan(
420
423
  command: SearchCommand,
421
424
  patternIds: readonly string[],
425
+ ui: CliUi,
422
426
  ): void {
423
427
  if (command.json) return;
424
- console.error("๐Ÿง™ stupify ๐Ÿช„");
425
- console.error(`Search: ${sourceLabel(command)}`);
426
- console.error(`Patterns: ${patternIds.join(", ")}`);
428
+ ui.intro("stupify");
429
+ ui.note(
430
+ [
431
+ `Search: ${sourceLabel(command)}`,
432
+ `Patterns: ${patternIds.join(", ")}`,
433
+ ].join("\n"),
434
+ "Run",
435
+ );
427
436
  }
428
437
 
429
438
  function formatStep(name: string, ms: number, count?: number, detail?: string): string {