wachiman 1.14.0 → 1.16.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 (72) hide show
  1. package/README.md +2 -1
  2. package/package.json +4 -2
  3. package/src/accounts/commands.ts +3 -2
  4. package/src/accounts/confirm.ts +63 -4
  5. package/src/accounts/profile-list.ts +24 -0
  6. package/src/cli.ts +161 -142
  7. package/src/config.ts +19 -6
  8. package/src/connectors/local-git.ts +47 -0
  9. package/src/doctor/checks.ts +106 -1
  10. package/src/doctor/run.ts +9 -1
  11. package/src/engine.ts +294 -97
  12. package/src/help.ts +637 -0
  13. package/src/init/args.ts +5 -2
  14. package/src/init/github-login.ts +13 -0
  15. package/src/init/options.ts +31 -3
  16. package/src/init/prompt.ts +46 -15
  17. package/src/init/run.ts +238 -32
  18. package/src/init/settings.ts +127 -0
  19. package/src/init/write.ts +16 -102
  20. package/src/ledger-read/command.ts +106 -0
  21. package/src/ledger-read/credentials.ts +103 -0
  22. package/src/ledger-read/files.ts +141 -0
  23. package/src/ledger-read/pull.ts +69 -0
  24. package/src/ledger-read/rows.ts +60 -0
  25. package/src/ledger-read/types.ts +127 -0
  26. package/src/ledger.ts +34 -18
  27. package/src/local-ask.ts +5 -4
  28. package/src/local.ts +55 -10
  29. package/src/loop/command.ts +5 -5
  30. package/src/pr-template/adopt.ts +434 -0
  31. package/src/pr-template/catalog.ts +429 -0
  32. package/src/pr-template/check-run.ts +328 -0
  33. package/src/pr-template/check.ts +338 -0
  34. package/src/pr-template/describe.ts +368 -0
  35. package/src/pr-template/format.ts +399 -0
  36. package/src/pr-template/gh.ts +159 -0
  37. package/src/pr-template/install.ts +288 -0
  38. package/src/pr-template/legacy-guides.ts +50 -0
  39. package/src/pr-template/pr-risk.ts +426 -0
  40. package/src/pr-template/render.ts +302 -0
  41. package/src/pr-template/resolve.ts +65 -0
  42. package/src/pr-template/run.ts +88 -0
  43. package/src/pr-template/strip.ts +171 -0
  44. package/src/pr-template/write.ts +139 -0
  45. package/src/providers/claude-code.ts +7 -8
  46. package/src/providers/codex.ts +4 -4
  47. package/src/providers/spawn.ts +95 -0
  48. package/src/providers/types.ts +5 -2
  49. package/src/repo-settings.ts +159 -0
  50. package/src/setup/prompt.ts +49 -33
  51. package/src/setup/run.ts +58 -16
  52. package/src/sinks/common.ts +10 -3
  53. package/src/sinks/markdown.ts +3 -2
  54. package/src/sinks/terminal.ts +3 -2
  55. package/src/spend/report.ts +349 -0
  56. package/src/status/command.ts +150 -36
  57. package/src/store/command.ts +20 -3
  58. package/src/store/html.ts +205 -8
  59. package/src/store/index.ts +64 -5
  60. package/src/store/rows.ts +103 -0
  61. package/src/upgrade/command.ts +286 -0
  62. package/src/upgrade/pin.ts +112 -0
  63. package/src/wizard/interactive.ts +11 -0
  64. package/src/wizard/launcher.ts +340 -0
  65. package/src/wizard/load.ts +30 -0
  66. package/src/wizard/mascot.ts +228 -0
  67. package/src/wizard/prompt-fancy.ts +135 -0
  68. package/src/wizard/prompt.ts +108 -61
  69. package/src/wizard/style.ts +93 -13
  70. package/src/wizard/tone.ts +11 -0
  71. package/src/wizard/ui.ts +80 -0
  72. package/templates/pr/sections.json +163 -0
@@ -0,0 +1,135 @@
1
+ /**
2
+ * The terminal session of the wizards, on Clack through the `Ui` seam. It keeps the contract of the
3
+ * plain session in `./prompt.ts` (defaults, `null` on cancel, an earlier cancel ends the whole
4
+ * session) and adds what only a terminal can show: the mascot intro, a framed session, a spinner,
5
+ * notes and an outro. It never reads or writes a file and holds no wizard logic.
6
+ */
7
+ import { playIntro } from "./mascot";
8
+ import type { Choice, Outcome, Prompter, PromptIO } from "./prompt";
9
+ import { describeCommand, terminalStyle, withoutShell, type Tone } from "./style";
10
+ import type { LogKind, Ui } from "./ui";
11
+
12
+ type Terminal = NodeJS.ReadableStream & { isTTY?: boolean; isRaw?: boolean; setRawMode?: (mode: boolean) => unknown };
13
+ type TerminalOut = NodeJS.WritableStream & { isTTY?: boolean; columns?: number };
14
+
15
+ const toOptions = <T>(choices: Choice<T>[]) =>
16
+ choices.map((c, i) => ({ value: i, label: c.disabled ? `${c.label} (coming soon)` : c.label, hint: c.description, ...(c.disabled ? { disabled: true } : {}) }));
17
+
18
+ /** The requested default, or the first choice that can be picked when it points at a disabled one. */
19
+ export function usableDefault<T>(choices: Choice<T>[], index: number): number {
20
+ if (!choices[index]?.disabled) return index;
21
+ const first = choices.findIndex((c) => !c.disabled);
22
+ return first === -1 ? index : first;
23
+ }
24
+
25
+ export function createFancyPrompter(io: PromptIO, env: Record<string, string | undefined>, ui: Ui): Prompter {
26
+ const output = io.output as TerminalOut;
27
+ const paint = terminalStyle(output, env);
28
+ const next: { note: string; commands: string[] }[] = [];
29
+ let cancelled = false;
30
+ let closed = false;
31
+
32
+ const log = (kind: LogKind, text: string) => ui.log(kind, text);
33
+ const say = (line: string, tone?: Tone) => {
34
+ // The frame puts its own space between blocks, so an empty line would only widen it.
35
+ if (line === "") return;
36
+ if (tone === "success") return log("success", line);
37
+ if (tone === "warning") return log("warn", line);
38
+ if (tone === "error") return log("error", line);
39
+ log("message", tone ? paint(line, tone) : line);
40
+ };
41
+
42
+ const pick = async <T>(ask: typeof ui.select, label: string, choices: Choice<T>[], defaultIndex: number): Promise<T | null> => {
43
+ // An earlier Ctrl-C (also during the intro) ends the whole session.
44
+ if (cancelled) return null;
45
+ const index = await ask({ message: label, options: toOptions(choices), initial: usableDefault(choices, defaultIndex) });
46
+ if (index === null) {
47
+ cancelled = true;
48
+ return null;
49
+ }
50
+ return choices[index].value;
51
+ };
52
+
53
+ return {
54
+ fancy: true,
55
+ say,
56
+ report: (line, kind) => log(kind === "success" ? "success" : kind === "warning" ? "warn" : "message", line),
57
+ note: (body, title) => ui.note(body, title),
58
+ step(label, index, total) {
59
+ log("step", `${label} ${paint(`step ${index}${total === undefined ? "" : ` of ${total}`}`, "muted")}`);
60
+ },
61
+ // Clack owns the terminal only while a question is open, so there is nothing to hand back.
62
+ suspend() {},
63
+ select: (label, choices, defaultIndex) => pick((o) => ui.select(o), label, choices, defaultIndex),
64
+ autocomplete: (label, choices, defaultIndex) => pick((o) => ui.autocomplete({ ...o, placeholder: "Type to filter" }), label, choices, defaultIndex),
65
+ async text(label, defaultValue, validate) {
66
+ if (cancelled) return null;
67
+ const answer = await ui.text({
68
+ message: label,
69
+ placeholder: defaultValue ? defaultValue : undefined,
70
+ defaultValue,
71
+ validate: (value) => validate?.(value),
72
+ });
73
+ if (answer === null) {
74
+ cancelled = true;
75
+ return null;
76
+ }
77
+ return answer.trim() === "" && defaultValue !== undefined ? defaultValue : answer.trim();
78
+ },
79
+ async confirm(label, defaultYes) {
80
+ if (cancelled) return null;
81
+ const answer = await ui.confirm({ message: label, initial: defaultYes });
82
+ if (answer === null) cancelled = true;
83
+ return answer;
84
+ },
85
+ async intro(version, line) {
86
+ // A caller that already played it (the launcher, before it dispatches) marks the environment.
87
+ if (env.WACHIMAN_INTRO_DONE) return;
88
+ const result = await playIntro({ ui, term: { input: io.input as Terminal, output }, env, version, line });
89
+ if (result === "interrupted") {
90
+ output.write("\n");
91
+ cancelled = true;
92
+ }
93
+ },
94
+ async task(label, work, ok) {
95
+ const spinner = ui.spinner();
96
+ spinner.start(label);
97
+ try {
98
+ const result = await work();
99
+ if (ok ? ok(result) : true) spinner.stop(label);
100
+ else spinner.fail(`${label}: needs attention`);
101
+ return result;
102
+ } catch (error) {
103
+ spinner.fail(label);
104
+ throw error;
105
+ }
106
+ },
107
+ nextStep(command, note) {
108
+ // On Windows one step arrives once per shell: keep it as one step with both commands.
109
+ const last = next.at(-1);
110
+ if (!note && last && last.commands.length > 0 && withoutShell(last.commands[0]) === withoutShell(command) && last.commands[0] !== command) {
111
+ last.commands.push(command);
112
+ return;
113
+ }
114
+ next.push({ note: note ? note[0].toUpperCase() + note.slice(1) : describeCommand(command), commands: [command] });
115
+ },
116
+ nextAction(note, commands = []) {
117
+ next.push({ note, commands });
118
+ },
119
+ close(outcome: Outcome = "done", message?: string) {
120
+ if (closed) return;
121
+ closed = true;
122
+ if (next.length > 0) {
123
+ ui.note(
124
+ next
125
+ .flatMap((n, i) => [`${i + 1}. ${n.note}`, ...n.commands.map((c) => ` ${paint(c, "accent")}`)])
126
+ .join("\n"),
127
+ "Next steps",
128
+ );
129
+ }
130
+ next.length = 0;
131
+ if (outcome === "done") ui.outro(message ?? `${paint("Wachi:", "brand")} All set. I'll keep the watch.`);
132
+ else ui.cancel(message ?? (outcome === "cancelled" ? "Cancelled." : "Stopped."));
133
+ },
134
+ };
135
+ }
@@ -1,15 +1,24 @@
1
1
  /**
2
- * Plain prompts on `node:readline` (design section 6): one question at a time, no repaint, no
3
- * dependency (ADR 0002). `select`, `text` and `confirm` print their default, take Enter as that
4
- * default, and return `null` when the person cancels with Escape, Ctrl-C or Ctrl-D.
2
+ * The prompt wrapper of the wizards (design section 6): `select`, `text` and `confirm` print their
3
+ * default, take Enter as that default, and return `null` when the person cancels.
5
4
  *
6
- * The streams are injectable. A test feeds the lines a person would type; on a real terminal the
7
- * input is a TTY, Escape and Ctrl-C come as key events, and Ctrl-D ends the input. On a piped
8
- * stream a line that is only Escape (U+001B) or Ctrl-C (U+0003) cancels as well, which is how a
9
- * script says it.
5
+ * There are two sessions behind one `Prompter`:
6
+ *
7
+ * - On a real terminal (stdin and the prompt output are both TTYs) the session is "fancy" and runs
8
+ * on Clack (`./prompt-fancy.ts`, through the `Ui` seam in `./ui.ts`): the mascot intro, arrow-key
9
+ * menus, a spinner, notes and an outro. `openPrompter` loads Clack for it.
10
+ * - Everywhere else, and for every test that feeds lines, the session is the plain one below on
11
+ * `node:readline`: the numbered list and one-line questions, byte for byte as they always were.
12
+ * No prompt, color or animation is ever drawn outside a terminal.
13
+ *
14
+ * The streams are injectable. A test feeds the lines a person would type; a piped line that is only
15
+ * Escape (U+001B) or Ctrl-C (U+0003) cancels, which is how a script says it, and so does the stream
16
+ * ending (Ctrl-D). A test of the fancy session passes its own `Ui` and scripts the answers.
10
17
  */
11
- import { createInterface, emitKeypressEvents, type Interface } from "node:readline";
12
- import { terminalStyle, type Tone } from "./style";
18
+ import { createInterface, type Interface } from "node:readline";
19
+ import { createFancyPrompter, usableDefault } from "./prompt-fancy";
20
+ import { terminalStyle, type NextStepSink, type Tone } from "./style";
21
+ import { loadUi, type Ui } from "./ui";
13
22
 
14
23
  export interface PromptIO {
15
24
  input: NodeJS.ReadableStream;
@@ -21,33 +30,63 @@ export interface Choice<T> {
21
30
  label: string;
22
31
  value: T;
23
32
  description?: string;
33
+ /** Shown with "(coming soon)" and never pickable. A default index never lands on one. */
34
+ disabled?: boolean;
24
35
  }
25
36
 
26
- export interface Prompter {
27
- /** Numbered list; Enter takes `defaultIndex` (0-based), which is printed with `(default)`. */
37
+ export type Outcome = "done" | "cancelled" | "failed";
38
+
39
+ export interface Prompter extends NextStepSink {
40
+ /** Numbered list; Enter takes `defaultIndex` (0-based), which is printed with `(default)`. On a terminal: an arrow-key menu that starts on it. */
28
41
  select<T>(label: string, choices: Choice<T>[], defaultIndex: number): Promise<T | null>;
42
+ /** A long list. On a terminal the person types to filter it; without one it is the numbered list of `select`. */
43
+ autocomplete<T>(label: string, choices: Choice<T>[], defaultIndex: number): Promise<T | null>;
29
44
  /** `defaultValue` is printed in brackets and taken on Enter; `validate` returns an error text, or undefined when valid. Asks again until valid or cancelled. */
30
45
  text(label: string, defaultValue: string | undefined, validate?: (value: string) => string | undefined): Promise<string | null>;
31
46
  confirm(label: string, defaultYes: boolean): Promise<boolean | null>;
32
- /** Prints a line to the prompt output (a preview, a summary, an error). */
47
+ /** Prints a line to the prompt output (a preview, a summary, an error). On a terminal it sits inside the session frame; an empty line prints nothing there. */
33
48
  say(line: string, tone?: Tone): void;
49
+ /** A boxed block with a title (a summary, a file preview). Without a terminal: the title, then the lines. */
50
+ note(body: string, title?: string): void;
34
51
  /** A stage can start before the route (and therefore the total) is known. */
35
52
  step(label: string, index: number, total?: number): void;
53
+ /** True when the session is a terminal one. Only then are the extras below active. */
54
+ readonly fancy: boolean;
55
+ /** The chip, "On watch." and Wachi with a line typed out (`line`), or the same scene printed at once. Does nothing without a terminal. A Ctrl-C during it cancels the next question. */
56
+ intro(version: string, line?: string): Promise<void>;
57
+ /** Runs slow work behind a spinner that ends in a check mark (or a warning when `ok` says the result is bad). Without a terminal it only runs the work. The spinner turns only while `work` yields to the event loop. */
58
+ task<T>(label: string, work: () => T | Promise<T>, ok?: (result: T) => boolean): Promise<T>;
59
+ /** A closing step that is more than one command, for the "Next steps" note printed by `close`. */
60
+ nextAction(note: string, commands?: string[]): void;
36
61
  /** Gives the terminal back (raw mode off, input paused) so a child process can use it; the next question takes it again. Typed-ahead answers are kept. */
37
62
  suspend(): void;
38
- close(): void;
63
+ /** Ends the session: the "Next steps" note when there is one, then the outro (or the cancel line), then `suspend`. Only the first call prints. */
64
+ close(outcome?: Outcome, message?: string): void;
65
+ }
66
+
67
+ type Terminal = NodeJS.ReadableStream & { isTTY?: boolean };
68
+ type TerminalOut = NodeJS.WritableStream & { isTTY?: boolean };
69
+
70
+ /** Stdin and the prompt output are both terminals. */
71
+ export const isTerminal = (io: PromptIO) => (io.input as Terminal).isTTY === true && (io.output as TerminalOut).isTTY === true;
72
+
73
+ /**
74
+ * The session for a command that opens one: a fancy one (Clack loaded here) on a terminal, the
75
+ * plain one anywhere else. `deps.ui` replaces Clack, for a test.
76
+ */
77
+ export async function openPrompter(io: PromptIO, env: Record<string, string | undefined> = process.env, deps: { ui?: Ui } = {}): Promise<Prompter> {
78
+ if (deps.ui) return createPrompter(io, env, deps.ui);
79
+ return isTerminal(io) ? createPrompter(io, env, await loadUi(io)) : createPrompter(io, env);
39
80
  }
40
81
 
41
82
  const CANCEL_LINES = new Set(["\u001b", "\u0003", "\u0004"]);
42
83
 
43
- export function createPrompter(io: PromptIO, env: Record<string, string | undefined> = process.env): Prompter {
84
+ /** The plain session, or the fancy one when a `Ui` is given. */
85
+ export function createPrompter(io: PromptIO, env: Record<string, string | undefined> = process.env, ui?: Ui): Prompter {
86
+ if (ui) return createFancyPrompter(io, env, ui);
44
87
  const paint = terminalStyle(io.output as { isTTY?: boolean }, env);
45
- // readline's cursor editing also emits ANSI; a redirected prompt output must
46
- // stay plain even when stdin itself is still a terminal.
47
- const terminal = (io.input as { isTTY?: boolean }).isTTY === true && (io.output as { isTTY?: boolean }).isTTY === true;
48
88
  const queue: string[] = [];
49
89
  let rl: Interface | undefined;
50
- let onKey: ((text: string, key?: { name?: string }) => void) | undefined;
51
90
  let waiter: ((line: string | null) => void) | undefined;
52
91
  let ended = false;
53
92
  let cancelled = false;
@@ -64,10 +103,9 @@ export function createPrompter(io: PromptIO, env: Record<string, string | undefi
64
103
  if (waiter) cancel();
65
104
  });
66
105
 
67
- /** The terminal belongs to the prompts only while a question is open; a child that needs it calls `suspend` first. */
68
106
  const open = () => {
69
107
  if (rl) return;
70
- const mine = createInterface({ input: io.input, ...(terminal ? { output: io.output } : {}), terminal, crlfDelay: Infinity });
108
+ const mine = createInterface({ input: io.input, terminal: false, crlfDelay: Infinity });
71
109
  rl = mine;
72
110
  mine.on("line", (line) => {
73
111
  if (waiter) {
@@ -81,27 +119,11 @@ export function createPrompter(io: PromptIO, env: Record<string, string | undefi
81
119
  ended = true;
82
120
  if (waiter) cancel();
83
121
  });
84
- mine.on("SIGINT", () => {
85
- io.output.write("\n");
86
- cancel();
87
- });
88
- if (terminal) {
89
- emitKeypressEvents(io.input, mine);
90
- onKey = (_text, key) => {
91
- if (key?.name === "escape") {
92
- io.output.write("\n");
93
- cancel();
94
- }
95
- };
96
- io.input.on("keypress", onKey);
97
- }
98
122
  };
99
123
  const suspend = () => {
100
124
  const mine = rl;
101
125
  if (!mine) return;
102
126
  rl = undefined;
103
- if (onKey) io.input.off("keypress", onKey);
104
- onKey = undefined;
105
127
  mine.close();
106
128
  };
107
129
 
@@ -133,40 +155,66 @@ export function createPrompter(io: PromptIO, env: Record<string, string | undefi
133
155
  const say = (line: string, tone?: Tone) => void io.output.write(`${tone ? paint(line, tone) : line}\n`);
134
156
  const ask = (question: string) => {
135
157
  open();
136
- // On a terminal readline owns the prompt, so its line refresh (Backspace, cursor keys) redraws the question too.
137
- if (terminal && rl) {
138
- rl.setPrompt(question);
139
- rl.prompt();
140
- } else io.output.write(question);
158
+ io.output.write(question);
141
159
  return nextLine();
142
160
  };
143
161
 
162
+ /** The numbered list and `Choice [n]:` line. A disabled choice is listed but cannot be picked. */
163
+ async function numberedSelect<T>(label: string, choices: Choice<T>[], requestedDefault: number): Promise<T | null> {
164
+ const defaultIndex = usableDefault(choices, requestedDefault);
165
+ say(label, "accent");
166
+ choices.forEach((c, i) => {
167
+ if (c.disabled) {
168
+ say(` ${i + 1}. ${c.label} (coming soon)`, "muted");
169
+ return;
170
+ }
171
+ say(` ${i + 1}. ${c.label}${i === defaultIndex ? " (default)" : ""}`, i === defaultIndex ? "accent" : undefined);
172
+ if (c.description) say(` ${c.description}`, "muted");
173
+ });
174
+ for (;;) {
175
+ const line = await ask(`Choice [${defaultIndex + 1}]: `);
176
+ if (line === null) return null;
177
+ const answer = line.trim();
178
+ if (answer === "") return choices[defaultIndex].value;
179
+ const n = Number(answer);
180
+ if (/^\d+$/.test(answer) && n >= 1 && n <= choices.length) {
181
+ if (choices[n - 1].disabled) {
182
+ say(`Option ${n} is not available yet. Pick another number, or press Enter for ${defaultIndex + 1}.`, "error");
183
+ continue;
184
+ }
185
+ return choices[n - 1].value;
186
+ }
187
+ say(`Enter a number from 1 to ${choices.length}, or press Enter for ${defaultIndex + 1}.`, "error");
188
+ }
189
+ }
190
+
144
191
  return {
145
192
  say,
193
+ fancy: false,
146
194
  step(label, index, total) {
147
195
  say(`\nStep ${index}${total === undefined ? "" : `/${total}`} ${label}`, "accent");
148
196
  },
197
+ note(body, title) {
198
+ if (title) say(title, "accent");
199
+ for (const line of body.split("\n")) say(` ${line}`);
200
+ },
149
201
  suspend,
150
- close: suspend,
151
- async select(label, choices, defaultIndex) {
152
- say(label, "accent");
153
- choices.forEach((c, i) => {
154
- say(` ${i + 1}. ${c.label}${i === defaultIndex ? " (default)" : ""}`, i === defaultIndex ? "accent" : undefined);
155
- if (c.description) say(` ${c.description}`, "muted");
156
- });
157
- for (;;) {
158
- const line = await ask(`Choice [${defaultIndex + 1}]: `);
159
- if (line === null) return null;
160
- const answer = line.trim();
161
- if (answer === "") return choices[defaultIndex].value;
162
- const n = Number(answer);
163
- if (/^\d+$/.test(answer) && n >= 1 && n <= choices.length) return choices[n - 1].value;
164
- say(`Enter a number from 1 to ${choices.length}, or press Enter for ${defaultIndex + 1}.`, "error");
165
- }
202
+ close() {
203
+ suspend();
204
+ },
205
+ // The plain session keeps its closing `next:` lines as they were printed; only a terminal session gathers them into a note.
206
+ nextStep() {},
207
+ nextAction() {},
208
+ async intro() {},
209
+ async task(_label, work) {
210
+ return work();
166
211
  },
212
+ select: numberedSelect,
213
+ autocomplete: numberedSelect,
167
214
  async text(label, defaultValue, validate) {
168
215
  for (;;) {
169
- const line = await ask(defaultValue !== undefined && defaultValue !== "" ? `${label} [${defaultValue}]: ` : `${label}: `);
216
+ const hint = defaultValue !== undefined && defaultValue !== "" ? `[${defaultValue}]` : "";
217
+ const line = await ask(`${label}${hint ? ` ${hint}` : ""}: `);
170
218
  if (line === null) return null;
171
219
  const answer = line.trim() === "" && defaultValue !== undefined ? defaultValue : line.trim();
172
220
  const problem = validate?.(answer);
@@ -179,9 +227,8 @@ export function createPrompter(io: PromptIO, env: Record<string, string | undefi
179
227
  const line = await ask(`${label} ${defaultYes ? "[Y/n]" : "[y/N]"} `);
180
228
  if (line === null) return null;
181
229
  const answer = line.trim().toLowerCase();
182
- if (answer === "") return defaultYes;
183
- if (answer === "y" || answer === "yes") return true;
184
- if (answer === "n" || answer === "no") return false;
230
+ const decided = answer === "" ? defaultYes : answer === "y" || answer === "yes" ? true : answer === "n" || answer === "no" ? false : undefined;
231
+ if (decided !== undefined) return decided;
185
232
  say("Answer y or n.", "error");
186
233
  }
187
234
  },
@@ -1,19 +1,99 @@
1
- /** Terminal colors are an enhancement: labels carry the meaning in plain output. */
2
- export type Tone = "accent" | "muted" | "success" | "warning" | "error";
1
+ /**
2
+ * Colors and the glyph set of the terminal UI. This is a presentation module: it is the one place
3
+ * the terminal's colors come from (`chalk`), and it is only loaded through a dynamic `import()` in `src/cli.ts` and `src/wizard/load.ts`, never by
4
+ * the review engine (ADR 0002, amendment 2026-11-13).
5
+ *
6
+ * Color is an enhancement: labels carry the meaning in plain output. chalk 5.6 does not read
7
+ * `NO_COLOR` (it only honors `FORCE_COLOR`), so the level is decided here, from the stream and the
8
+ * environment, and handed to chalk.
9
+ */
10
+ import { Chalk, type ChalkInstance } from "chalk";
11
+ import type { Paint, Tone } from "./tone";
3
12
 
4
- const CODES: Record<Tone, number> = { accent: 36, muted: 2, success: 32, warning: 33, error: 31 };
13
+ export type { Paint, Tone } from "./tone";
5
14
 
6
- export function terminalStyle(output: { isTTY?: boolean }, env: Record<string, string | undefined>) {
7
- const color = output.isTTY === true && !env.NO_COLOR && env.TERM !== "dumb";
8
- return (text: string, tone: Tone) => color ? `\x1b[${CODES[tone]}m${text}\x1b[0m` : text;
15
+ /** The brand color: the blue of the guard's uniform. */
16
+ export const BRAND_HEX = "#4d8dff";
17
+
18
+ /**
19
+ * 0 means no color: the output is not a terminal, `TERM` is `dumb`, or `NO_COLOR` is set and not
20
+ * empty (an empty value is ignored, as no-color.org says). Otherwise 3 for a truecolor terminal,
21
+ * 2 for a 256-color one, 1 for the rest.
22
+ */
23
+ export function colorLevel(output: { isTTY?: boolean }, env: Record<string, string | undefined>): 0 | 1 | 2 | 3 {
24
+ if (output.isTTY !== true || env.TERM === "dumb" || (env.NO_COLOR !== undefined && env.NO_COLOR !== "")) return 0;
25
+ if (env.COLORTERM === "truecolor" || env.COLORTERM === "24bit") return 3;
26
+ return /256color/.test(env.TERM ?? "") ? 2 : 1;
27
+ }
28
+
29
+ export function makeChalk(output: { isTTY?: boolean }, env: Record<string, string | undefined>): ChalkInstance {
30
+ return new Chalk({ level: colorLevel(output, env) });
31
+ }
32
+
33
+ export function terminalStyle(output: { isTTY?: boolean }, env: Record<string, string | undefined>): Paint {
34
+ const c = makeChalk(output, env);
35
+ const tones: Record<Tone, ChalkInstance> = {
36
+ accent: c.cyan,
37
+ muted: c.dim,
38
+ success: c.green,
39
+ warning: c.yellow,
40
+ error: c.red,
41
+ strong: c.bold,
42
+ highlight: c.bold.cyan,
43
+ brand: c.bold.hex(BRAND_HEX),
44
+ };
45
+ return (text, tone) => tones[tone](text);
46
+ }
47
+
48
+ /** The glyphs of the terminal UI; a `dumb` terminal gets ASCII. Each glyph has words next to it, so none carries meaning alone. */
49
+ export function symbols(env: Record<string, string | undefined>) {
50
+ return env.TERM === "dumb" ? { done: "+", failed: "x", warn: "!", bar: "|" } : { done: "✔", failed: "✖", warn: "▲", bar: "│" };
9
51
  }
10
52
 
11
- /** Only human-facing stderr is decorated; stdout remains byte-for-byte data. */
12
- export function wizardIo<T extends { stderr: (line: string) => void }>(io: T, output: { isTTY?: boolean }, env: Record<string, string | undefined>): T {
53
+ const ANSI = /\x1b\[[0-9;?]*[A-Za-z]/g;
54
+ export const stripAnsi = (text: string) => text.replace(ANSI, "");
55
+
56
+ /** What a terminal session offers `wizardIo`: whether it is a real terminal, and a place to collect the closing hints. */
57
+ export interface NextStepSink {
58
+ fancy: boolean;
59
+ nextStep: (command: string, note?: string) => void;
60
+ /** On a terminal session a status line is drawn inside the session frame instead of loose on stderr. */
61
+ report?: (line: string, kind: "success" | "warning" | "info") => void;
62
+ }
63
+
64
+ /** A Windows hint names its shell first ("PowerShell: wachiman setup"); this drops that label. */
65
+ export function withoutShell(command: string): string {
66
+ return command.replace(/^(PowerShell|Git Bash): /, "");
67
+ }
68
+
69
+ /** What a closing hint is for, when the hint itself only names the command. */
70
+ export function describeCommand(command: string): string {
71
+ command = withoutShell(command);
72
+ if (/^wachiman local\b/.test(command)) return "Review your branch on your signed-in Claude";
73
+ if (/^wachiman doctor\b/.test(command)) return "See which checks need attention";
74
+ if (/^wachiman setup\b/.test(command)) return "Bind this repository to a Claude account";
75
+ return "Run";
76
+ }
77
+
78
+ const SUCCESS = /^(bound:|wrote |account: signed in|All required checks passed|local: ready)/;
79
+ const WARNING = /^(warning:|cancelled:|not written|nothing saved|These already happened|local: not ready|github: pending)/;
80
+
81
+ /**
82
+ * Only human-facing stderr is decorated; stdout remains byte-for-byte data. With a terminal
83
+ * session the closing `next:` hints are collected into the session's "Next steps" note, and every
84
+ * other line is drawn inside the session frame.
85
+ */
86
+ export function wizardIo<T extends { stderr: (line: string) => void }>(io: T, output: { isTTY?: boolean }, env: Record<string, string | undefined>, session?: NextStepSink): T {
13
87
  const paint = terminalStyle(output, env);
14
- return { ...io, stderr: (line: string) => {
15
- const tone = /^(bound:|wrote |account: signed in|All required checks passed|local: ready)/.test(line) ? "success"
16
- : /^(warning:|cancelled:|not written|nothing saved|These already happened|local: not ready|github: pending)/.test(line) ? "warning" : undefined;
17
- io.stderr(tone ? paint(line, tone) : line);
18
- } };
88
+ return {
89
+ ...io,
90
+ stderr: (line: string) => {
91
+ const next = session?.fancy ? /^(?:next|Next, on this machine): (\S.*?)(?: {3}\((.*)\))?$/.exec(line) : null;
92
+ if (next) return session!.nextStep(next[1], next[2]);
93
+ const kind = SUCCESS.test(line) ? "success" : WARNING.test(line) ? "warning" : "info";
94
+ if (session?.fancy && session.report) return session.report(line, kind);
95
+ const tone = kind === "success" ? "success" : kind === "warning" ? "warning" : undefined;
96
+ io.stderr(tone ? paint(line, tone) : line);
97
+ },
98
+ };
19
99
  }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The names of the colors the terminal UI uses, with no import: `src/help.ts` and `src/cli.ts` take
3
+ * these types without loading `chalk`. The painter that turns a tone into escape codes is
4
+ * `terminalStyle` in `./style.ts`.
5
+ */
6
+ export type Tone = "accent" | "muted" | "success" | "warning" | "error" | "strong" | "highlight" | "brand";
7
+
8
+ /** Paints plain text in a tone; the identity function when the output has no color. */
9
+ export type Paint = (text: string, tone: Tone) => string;
10
+
11
+ export const plain: Paint = (text) => text;
@@ -0,0 +1,80 @@
1
+ /**
2
+ * The seam between the prompt wrapper (`./prompt.ts`) and Clack (`@clack/prompts`). `Ui` is the small
3
+ * surface the wrapper needs; `loadUi` implements it over Clack, loaded with a dynamic `import()` so
4
+ * that nothing outside a person's terminal session ever loads the package (ADR 0002, amendment
5
+ * 2026-11-13). A test passes its own `Ui` and scripts the answers, with no terminal involved.
6
+ *
7
+ * Answers are option indexes, never the caller's values: a value may be a symbol or an object, and
8
+ * Clack compares and prints values. A cancelled prompt (Escape, Ctrl-C) is `null`.
9
+ */
10
+
11
+ export interface UiOption {
12
+ /** The index of the choice in the caller's list. */
13
+ value: number;
14
+ label: string;
15
+ hint?: string;
16
+ /** Shown but not pickable. */
17
+ disabled?: boolean;
18
+ }
19
+
20
+ export type LogKind = "message" | "info" | "success" | "warn" | "error" | "step";
21
+
22
+ export interface UiSpinner {
23
+ start(message: string): void;
24
+ /** Ends the line with a check mark. */
25
+ stop(message: string): void;
26
+ /** Ends the line as needing attention. */
27
+ fail(message: string): void;
28
+ }
29
+
30
+ export interface Ui {
31
+ intro(title: string): void;
32
+ outro(message: string): void;
33
+ cancel(message: string): void;
34
+ select(o: { message: string; options: UiOption[]; initial: number }): Promise<number | null>;
35
+ /** A list the person filters by typing. */
36
+ autocomplete(o: { message: string; options: UiOption[]; initial: number; placeholder?: string }): Promise<number | null>;
37
+ /** `validate` gets the typed text; an empty answer with a `defaultValue` is validated as that default. */
38
+ text(o: { message: string; placeholder?: string; defaultValue?: string; validate: (value: string) => string | undefined }): Promise<string | null>;
39
+ confirm(o: { message: string; initial: boolean }): Promise<boolean | null>;
40
+ note(message: string, title?: string): void;
41
+ log(kind: LogKind, message: string): void;
42
+ spinner(): UiSpinner;
43
+ }
44
+
45
+ export interface UiStreams {
46
+ input: NodeJS.ReadableStream;
47
+ /** stderr: prompts never go to stdout, which belongs to a command's result. */
48
+ output: NodeJS.WritableStream;
49
+ }
50
+
51
+ export async function loadUi(streams: UiStreams): Promise<Ui> {
52
+ const clack = await import("@clack/prompts");
53
+ const io = { input: streams.input as NodeJS.ReadStream, output: streams.output as NodeJS.WriteStream };
54
+ const answer = <T>(value: T | symbol): T | null => (clack.isCancel(value) ? null : (value as T));
55
+ return {
56
+ intro: (title) => clack.intro(title, io),
57
+ outro: (message) => clack.outro(message, io),
58
+ cancel: (message) => clack.cancel(message, io),
59
+ select: async (o) => answer(await clack.select<number>({ message: o.message, options: o.options, initialValue: o.initial, ...io })),
60
+ autocomplete: async (o) =>
61
+ answer(await clack.autocomplete<number>({ message: o.message, options: o.options, initialValue: o.initial, placeholder: o.placeholder, maxItems: 8, ...io })),
62
+ text: async (o) =>
63
+ answer(
64
+ await clack.text({
65
+ message: o.message,
66
+ placeholder: o.placeholder,
67
+ defaultValue: o.defaultValue,
68
+ validate: (value) => o.validate(value === undefined || (value.trim() === "" && o.defaultValue !== undefined) ? (o.defaultValue ?? "") : value.trim()),
69
+ ...io,
70
+ }),
71
+ ),
72
+ confirm: async (o) => answer(await clack.confirm({ message: o.message, initialValue: o.initial, ...io })),
73
+ note: (message, title) => clack.note(message, title, io),
74
+ log: (kind, message) => clack.log[kind](message, io),
75
+ spinner: () => {
76
+ const s = clack.spinner(io);
77
+ return { start: (m) => s.start(m), stop: (m) => s.stop(m), fail: (m) => s.error(m) };
78
+ },
79
+ };
80
+ }