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
package/src/init/args.ts CHANGED
@@ -3,25 +3,28 @@ import { parseFlags } from "../flags";
3
3
  import type { RawInitFlags } from "./options";
4
4
 
5
5
  export const initUsage =
6
- "wachiman init [--mode github|local|both] [--operator <login>] [--version <tag>] [--path <file>] [--force] [--dry-run] [--yes] [--repo-dir <dir>]";
6
+ "wachiman init [--mode github|local|both] [--project-kind monorepo|single] [--operator <login>] [--version <tag>] [--path <file>] [--force] [--dry-run] [--pr-template | --no-pr-template] [--yes] [--repo-dir <dir>]";
7
7
 
8
8
  /** The arguments after `init` (`--repo-dir` is already taken out and arrives as `repoDir`). Pure; an unknown flag is a usage error. */
9
9
  export function parseInitFlags(argv: string[], repoDir: string): RawInitFlags {
10
10
  if (argv.includes("--help") || argv.includes("-h")) return { help: true, repoDir };
11
11
  const { positionals, values, booleans } = parseFlags(
12
12
  argv,
13
- { values: ["--mode", "--operator", "--version", "--path"], booleans: ["--force", "--dry-run", "--yes"] },
13
+ { values: ["--mode", "--project-kind", "--operator", "--version", "--path"], booleans: ["--force", "--dry-run", "--yes", "--pr-template", "--no-pr-template"] },
14
14
  "init",
15
15
  );
16
16
  if (positionals.length > 0) throw new UsageError(`init takes no argument "${positionals[0]}".`);
17
+ if (booleans["--pr-template"] && booleans["--no-pr-template"]) throw new UsageError("--pr-template and --no-pr-template contradict each other; give one.");
17
18
  return {
18
19
  ...(values["--mode"] !== undefined ? { mode: values["--mode"] } : {}),
20
+ ...(values["--project-kind"] !== undefined ? { projectKind: values["--project-kind"] } : {}),
19
21
  ...(values["--operator"] !== undefined ? { operator: values["--operator"] } : {}),
20
22
  ...(values["--version"] !== undefined ? { version: values["--version"] } : {}),
21
23
  ...(values["--path"] !== undefined ? { path: values["--path"] } : {}),
22
24
  ...(booleans["--force"] ? { force: true } : {}),
23
25
  ...(booleans["--dry-run"] ? { dryRun: true } : {}),
24
26
  ...(booleans["--yes"] ? { yes: true } : {}),
27
+ ...(booleans["--pr-template"] ? { prTemplate: true } : booleans["--no-pr-template"] ? { prTemplate: false } : {}),
25
28
  repoDir,
26
29
  };
27
30
  }
@@ -0,0 +1,13 @@
1
+ import { spawnSync } from "node:child_process";
2
+
3
+ /** The login of the account `gh` is signed in as, or undefined when `gh` is missing, signed out or fails. Only ever a suggestion. */
4
+ export function ghLogin(): string | undefined {
5
+ try {
6
+ const run = spawnSync("gh", ["api", "user", "--jq", ".login"], { encoding: "utf8", timeout: 10_000, stdio: ["ignore", "pipe", "ignore"] });
7
+ if (run.error || run.status !== 0) return undefined;
8
+ const login = run.stdout.trim();
9
+ return login === "" ? undefined : login;
10
+ } catch {
11
+ return undefined;
12
+ }
13
+ }
@@ -6,14 +6,28 @@ import { posix } from "node:path";
6
6
 
7
7
  export type InitMode = "github" | "local" | "both";
8
8
 
9
+ /** The shape of the repository. Metadata only for now: nothing else in Wachiman reads it. */
10
+ export type ProjectKind = "monorepo" | "single";
11
+ export const projectKinds: readonly ProjectKind[] = ["monorepo", "single"];
12
+
13
+ /** Why `kind` cannot be recorded, or undefined when it can. */
14
+ export function projectKindProblem(kind: string): string | undefined {
15
+ if (projectKinds.includes(kind as ProjectKind)) return undefined;
16
+ if (kind === "distributed") return '--project-kind distributed is not available yet; use monorepo or single.';
17
+ return `--project-kind must be monorepo or single, got "${kind}".`;
18
+ }
19
+
9
20
  export interface RawInitFlags {
10
21
  mode?: string;
11
22
  operator?: string;
12
23
  version?: string;
13
24
  path?: string;
25
+ projectKind?: string;
14
26
  force?: boolean;
15
27
  dryRun?: boolean;
16
28
  yes?: boolean;
29
+ /** `--pr-template` is true, `--no-pr-template` is false; absent means not given. */
30
+ prTemplate?: boolean;
17
31
  repoDir?: string;
18
32
  help?: boolean;
19
33
  }
@@ -22,6 +36,10 @@ export interface InitOptions {
22
36
  mode: InitMode;
23
37
  /** Present iff mode !== "local". */
24
38
  github?: { operator: string; tag: string; path: string; force: boolean; dryRun: boolean };
39
+ /** Install the PR description template after the workflow work. Absent means no: a script that did not ask gets no new file. */
40
+ prTemplate?: boolean;
41
+ /** Present iff the kind was given (flag or answer); then `.wachiman.yml` is written or checked. `force` allows changing a different `kind:` without asking. */
42
+ settings?: { kind: ProjectKind; force: boolean };
25
43
  repoDir: string;
26
44
  interactive: boolean;
27
45
  }
@@ -34,7 +52,7 @@ export type ResolveResult<T> = { ok: true; options: T } | { ok: false; error: st
34
52
  * docs/releasing.md); the CLI's own version is never a substitute,
35
53
  * because an unreleased or unrelated version would pin a workflow that does not exist.
36
54
  */
37
- export const DEFAULT_WORKFLOW_REF: string | undefined = "v1.14.0"; // x-release-please-version
55
+ export const DEFAULT_WORKFLOW_REF: string | undefined = "v1.16.0"; // x-release-please-version
38
56
 
39
57
  export const DEFAULT_WORKFLOW_PATH = ".github/workflows/wachiman-review.yml";
40
58
  const WORKFLOWS_DIR = ".github/workflows/";
@@ -86,11 +104,19 @@ export function resolveInitOptions(
86
104
  if (!initModes.includes(flags.mode as InitMode)) return fail(`--mode must be github, local or both, got "${flags.mode}".`);
87
105
  const mode = flags.mode as InitMode;
88
106
  const repoDir = flags.repoDir ?? ".";
107
+ const templateOption = flags.prTemplate === true ? { prTemplate: true } : {};
108
+ if (flags.projectKind !== undefined) {
109
+ const kindError = projectKindProblem(flags.projectKind);
110
+ if (kindError) return fail(kindError);
111
+ }
112
+ const settings = flags.projectKind === undefined ? undefined : { kind: flags.projectKind as ProjectKind, force: flags.force === true };
89
113
 
90
114
  if (mode === "local") {
91
- const given = GITHUB_ONLY_FLAGS.filter(([key]) => flags[key] !== undefined && flags[key] !== false).map(([, name]) => name);
115
+ // With a kind, --force means "change a different kind in the settings file", which local mode does write.
116
+ const given = GITHUB_ONLY_FLAGS.filter(([key]) => flags[key] !== undefined && flags[key] !== false && !(key === "force" && settings))
117
+ .map(([, name]) => name);
92
118
  if (given.length > 0) return fail(`${given.join(", ")} only apply to a workflow; --mode local writes none. Drop them, or use --mode github or both.`);
93
- return { ok: true, options: { mode, repoDir, interactive: ctx.interactive } };
119
+ return { ok: true, options: { mode, ...templateOption, ...(settings ? { settings } : {}), repoDir, interactive: ctx.interactive } };
94
120
  }
95
121
 
96
122
  if (flags.operator === undefined) return fail(`init --mode ${mode} needs --operator <github login> when it cannot ask: the one person whose /wachiman comments start a run.`);
@@ -117,6 +143,8 @@ export function resolveInitOptions(
117
143
  options: {
118
144
  mode,
119
145
  github: { operator: flags.operator, tag, path: path.path, force: flags.force === true, dryRun: flags.dryRun === true },
146
+ ...templateOption,
147
+ ...(settings ? { settings } : {}),
120
148
  repoDir,
121
149
  interactive: ctx.interactive,
122
150
  },
@@ -1,11 +1,12 @@
1
1
  import { UsageError } from "../config";
2
2
  import type { Prompter } from "../wizard/prompt";
3
- import { DEFAULT_WORKFLOW_PATH, initModes, normaliseWorkflowPath, operatorProblem, tagProblem, type InitMode, type RawInitFlags } from "./options";
3
+ import { DEFAULT_WORKFLOW_PATH, initModes, normaliseWorkflowPath, operatorProblem, projectKindProblem, tagProblem, type InitMode, type ProjectKind, type RawInitFlags } from "./options";
4
4
 
5
5
  /** The values given on the command line are held to the same rules as answers: a bad one is exit 2, never silently asked again. */
6
6
  export function checkSupplied(flags: RawInitFlags) {
7
7
  if (flags.mode !== undefined && !initModes.includes(flags.mode as InitMode)) throw new UsageError(`--mode must be github, local or both, got "${flags.mode}".`);
8
8
  const problem =
9
+ (flags.projectKind !== undefined ? projectKindProblem(flags.projectKind) : undefined) ??
9
10
  (flags.operator !== undefined ? operatorProblem(flags.operator) : undefined) ??
10
11
  (flags.version !== undefined ? tagProblem(flags.version) : undefined) ??
11
12
  (flags.path !== undefined ? (() => { const p = normaliseWorkflowPath(flags.path!); return p.ok ? undefined : p.problem; })() : undefined);
@@ -17,9 +18,26 @@ export function checkSupplied(flags: RawInitFlags) {
17
18
  * (`null`: the person cancelled). Answers are validated as they are typed; the pure resolver
18
19
  * validates everything again.
19
20
  */
20
- export async function promptForInit(flags: RawInitFlags, ctx: { defaultWorkflowRef?: string }, prompter: Prompter): Promise<RawInitFlags | null> {
21
+ export async function promptForInit(flags: RawInitFlags, ctx: { defaultWorkflowRef?: string; githubLogin?: () => string | undefined }, prompter: Prompter): Promise<RawInitFlags | null> {
21
22
  checkSupplied(flags);
22
- prompter.step("Review mode", 2);
23
+ prompter.step("Project type", 2);
24
+ let projectKind = flags.projectKind as ProjectKind | undefined;
25
+ if (projectKind === undefined) {
26
+ const picked = await prompter.select<ProjectKind | "distributed">(
27
+ "What kind of repository is this?",
28
+ [
29
+ { label: "Monorepo", value: "monorepo" },
30
+ { label: "Single project", value: "single" },
31
+ { label: "Distributed repository", value: "distributed", disabled: true },
32
+ ],
33
+ 0,
34
+ );
35
+ if (picked === null) return null;
36
+ projectKind = picked as ProjectKind;
37
+ }
38
+ flags = { ...flags, projectKind };
39
+
40
+ prompter.step("Review mode", 3);
23
41
  let mode = flags.mode as InitMode | undefined;
24
42
  if (mode === undefined) {
25
43
  const picked = await prompter.select<InitMode>(
@@ -34,21 +52,34 @@ export async function promptForInit(flags: RawInitFlags, ctx: { defaultWorkflowR
34
52
  if (picked === null) return null;
35
53
  mode = picked;
36
54
  }
37
- if (mode === "local") return { ...flags, mode };
55
+ if (mode === "local") {
56
+ const prTemplate = await askPrTemplate(flags, prompter);
57
+ return prTemplate === null ? null : { ...flags, mode, prTemplate };
58
+ }
38
59
 
39
- prompter.step("GitHub workflow", 3, mode === "both" ? 6 : 4);
60
+ prompter.step("GitHub workflow", 4, mode === "both" ? 6 : 5);
40
61
 
62
+ // The signed-in `gh` user is the likely answer; a login that fails the same rule is not offered.
63
+ // `gh` is only spawned when the operator is going to be asked: `--operator` makes the guess useless.
64
+ const guess = flags.operator === undefined ? ctx.githubLogin?.() : undefined;
65
+ const suggested = guess !== undefined && operatorProblem(guess) === undefined ? guess : undefined;
66
+ if (suggested !== undefined) prompter.say(`Signed in to GitHub as https://github.com/${suggested}; press Enter to use it.`, "muted");
41
67
  const operator =
42
- flags.operator ?? (await prompter.text("GitHub login of the operator (the one person whose /wachiman comments start a run)", undefined, (v) => operatorProblem(v)));
68
+ flags.operator ??
69
+ (await prompter.text("Your GitHub username, as in https://github.com/<username>: only this person's /wachiman comments start a paid run", suggested, (v) => operatorProblem(v)));
43
70
  if (operator === null) return null;
44
- const version = flags.version ?? (await prompter.text("Release tag to pin", ctx.defaultWorkflowRef, (v) => tagProblem(v)));
71
+ // The release this CLI was published as, and the standard workflow path: neither is asked. `--version` and `--path` still override them.
72
+ const version = flags.version ?? ctx.defaultWorkflowRef ?? (await prompter.text("Release tag to pin", undefined, (v) => tagProblem(v)));
45
73
  if (version === null) return null;
46
- const path =
47
- flags.path ??
48
- (await prompter.text("Workflow file", DEFAULT_WORKFLOW_PATH, (v) => {
49
- const p = normaliseWorkflowPath(v);
50
- return p.ok ? undefined : p.problem;
51
- }));
52
- if (path === null) return null;
53
- return { ...flags, mode, operator, version, path };
74
+ const path = flags.path ?? DEFAULT_WORKFLOW_PATH;
75
+ const prTemplate = await askPrTemplate(flags, prompter);
76
+ return prTemplate === null ? null : { ...flags, mode, operator, version, path, prTemplate };
77
+ }
78
+
79
+ /** The flag when it was given; otherwise the question (`null`: cancelled). Asked once, in every mode, because the template belongs to the repository, not to a review mode. */
80
+ async function askPrTemplate(flags: RawInitFlags, prompter: Prompter): Promise<boolean | null> {
81
+ if (flags.prTemplate !== undefined) return flags.prTemplate;
82
+ // A dry run writes nothing, so it asks nothing about a file.
83
+ if (flags.dryRun) return false;
84
+ return prompter.confirm("Also install the PR description template? An existing .github/pull_request_template.md is adopted and replaced (a backup is kept); nothing is committed.", true);
54
85
  }
package/src/init/run.ts CHANGED
@@ -1,8 +1,16 @@
1
1
  /**
2
2
  * `wachiman init` (command contract section 5.5): parse, prompt, resolve, then the one impure
3
- * half. It writes only the chosen workflow file and its `.bak` copy, after the person has seen
4
- * what will be written (or named `--yes` or no terminal with every mandatory flag). It never
5
- * commits, pushes, opens a pull request or creates a secret, and it makes no network request.
3
+ * half. It writes the chosen workflow file and its `.bak` copy and, when the repository kind is
4
+ * given or answered, the settings file `.wachiman.yml` (ADR 0048), after the person has seen what
5
+ * will be written (or named `--yes` or no terminal with every mandatory flag). With
6
+ * `--pr-template` (or a yes to the question) it also installs the PR description template, files
7
+ * only, as `wachiman pr-template install` does: `.github/pull_request_template.md` and, when there
8
+ * is something to keep, `.github/pr-template.json`. An existing unmanaged template is adopted and
9
+ * replaced (a `.bak` copy is kept). A refusal or failure there is reported, saying what was and
10
+ * was not written, and does not fail the rest of init. It never commits, pushes, opens a pull
11
+ * request or creates a secret. Its only network use is one optional `gh api user`
12
+ * (src/init/github-login.ts, up to 10 s) to suggest the operator, and only on a terminal in github
13
+ * or both mode; Wachiman itself makes no request (no `fetch`).
6
14
  */
7
15
  import { readFileSync } from "node:fs";
8
16
  import { basename, dirname, join } from "node:path";
@@ -11,13 +19,20 @@ import { UsageError } from "../config";
11
19
  import { spawnGit, type GitRunner } from "../evidence";
12
20
  import { repositoryKey } from "../history/store";
13
21
  import { isInteractive, type TerminalStreams } from "../wizard/interactive";
14
- import { createPrompter, type Prompter, type PromptIO } from "../wizard/prompt";
15
- import { wizardIo } from "../wizard/style";
16
- import { projectCommands } from "../wizard/command";
22
+ import { loadTerminalUi } from "../wizard/load";
23
+ import type { Outcome, Prompter, PromptIO } from "../wizard/prompt";
24
+ import type { Ui } from "../wizard/ui";
25
+ import { projectCommands, quoteArgument } from "../wizard/command";
26
+ import { runInstall, type Deps as PrTemplateDeps } from "../pr-template/install";
27
+ import { CHOICE_FILE } from "../pr-template/catalog";
17
28
  import { DEFAULT_WORKFLOW_REF, resolveInitOptions, type InitOptions, type RawInitFlags } from "./options";
18
29
  import { checkSupplied, promptForInit } from "./prompt";
30
+ import { planSettings, SETTINGS_PATH, writeSettings, type SettingsPlan } from "./settings";
19
31
  import { callerHeader, renderCallerWorkflow } from "./render";
20
- import { inspectTarget, writeWorkflow, type WriteHooks } from "./write";
32
+ import { inspectTarget, sameWorkflow, writeWorkflow, type WriteHooks } from "./write";
33
+
34
+ /** What `pr-template install` can write; the report names the ones a failed install did not reach. */
35
+ const PR_TEMPLATE_FILES = [CHOICE_FILE, ".github/pull_request_template.md"];
21
36
 
22
37
  export interface InitDeps {
23
38
  /** The caller template. Default: `templates/wachiman-review-caller.yml` of this install. */
@@ -32,50 +47,83 @@ export interface InitDeps {
32
47
  interactive?: boolean;
33
48
  streams?: TerminalStreams;
34
49
  promptIO?: PromptIO;
50
+ /** A scripted terminal `Ui`, for a test of the terminal session. Not set: Clack, on a terminal. */
51
+ ui?: Ui;
35
52
  /** An open prompt session; the caller closes it. Otherwise one is opened over `promptIO` or the terminal. */
36
53
  prompter?: Prompter;
37
54
  /** What `wachiman setup` means from here: runs the setup wizard in the same process, sharing `prompter`. */
38
- bindNow?: (prompter: Prompter, mode: "local" | "both") => Promise<number>;
55
+ bindNow?: (prompter: Prompter, mode: "local" | "both", closing: SessionClosing) => Promise<number>;
56
+ /** The login of the signed-in `gh` user, offered as the default operator. Not set: no default. */
57
+ githubLogin?: () => string | undefined;
39
58
  /** The directory a relative `--repo-dir` was resolved against, for the `setup` line. Default: `process.cwd()`. */
40
59
  cwd?: string;
41
60
  hooks?: WriteHooks;
61
+ /** Dependencies of the PR description template install (`wachiman pr-template install`). */
62
+ prTemplate?: PrTemplateDeps;
63
+ /** Filled by a later stage; read by `runInitCommand` when it closes the session. */
64
+ closing?: SessionClosing;
65
+ /** The same hook for the settings file, for a test. */
66
+ settingsHooks?: WriteHooks;
67
+ }
68
+
69
+ /**
70
+ * What a later stage (setup) wants the session to say when it ends. `warning` closes the session
71
+ * without the red "Stopped.": the work is saved and one named step is left.
72
+ */
73
+ export interface SessionClosing {
74
+ warning?: string;
42
75
  }
43
76
 
44
77
  const TEMPLATE = join(import.meta.dir, "..", "..", "templates", "wachiman-review-caller.yml");
45
78
  const readDefaultTemplate = () => readFileSync(TEMPLATE, "utf8");
46
79
 
47
- const openSession = (deps: InitDeps, env: Record<string, string | undefined>) => {
48
- if (deps.prompter) return { prompter: deps.prompter, close: () => {} };
49
- const prompter = createPrompter(deps.promptIO ?? { input: process.stdin, output: process.stderr }, env);
50
- return { prompter, close: () => prompter.close() };
80
+ const openSession = async (deps: InitDeps, env: Record<string, string | undefined>, ui: Awaited<ReturnType<typeof loadTerminalUi>>) => {
81
+ if (deps.prompter) return { prompter: deps.prompter, close: (_outcome: Outcome, _message?: string) => {} };
82
+ const prompter = await ui.openPrompter(deps.promptIO ?? { input: process.stdin, output: process.stderr }, env, deps.ui ? { ui: deps.ui } : undefined);
83
+ // The message is the last line of the session: without it a saved run with one step left would end as "Stopped.".
84
+ return { prompter, close: (outcome: Outcome, message?: string) => prompter.close(outcome, message) };
51
85
  };
52
86
 
87
+ /** How a finished run ends the session: 0 is done, 130 a cancel, anything else a stop. */
88
+ const outcomeOf = (code: number): Outcome => (code === 0 ? "done" : code === 130 ? "cancelled" : "failed");
89
+
53
90
  /** From the parsed flags: asks what is missing when a person can be asked, resolves, and runs. */
54
91
  export async function runInitCommand(flags: RawInitFlags, env: Record<string, string | undefined>, io: CommandIo, deps: InitDeps = {}): Promise<number> {
55
92
  // Fail before asking for an operator or account in an unusable target.
56
93
  const root = worktreeRoot(flags.repoDir ?? ".", deps.git);
57
94
  const interactive = deps.interactive ?? isInteractive(flags, env, deps.streams ?? { stdin: process.stdin, stdout: process.stdout });
58
- if (interactive) io = wizardIo(io, (deps.promptIO?.output ?? process.stderr) as { isTTY?: boolean }, env);
59
95
  const defaultWorkflowRef = "defaultWorkflowRef" in deps ? deps.defaultWorkflowRef : DEFAULT_WORKFLOW_REF;
60
- const session = interactive ? openSession(deps, env) : undefined;
96
+ // The terminal UI (chalk and Clack) is loaded only when questions are asked.
97
+ const ui = interactive ? await loadTerminalUi() : undefined;
98
+ const session = ui ? await openSession(deps, env, ui) : undefined;
99
+ if (ui) io = ui.wizardIo(io, (deps.promptIO?.output ?? process.stderr) as { isTTY?: boolean }, env, session?.prompter);
100
+ let outcome: Outcome = "failed";
101
+ const closing: SessionClosing = {};
61
102
  try {
62
103
  let answered = flags;
63
104
  if (session) {
64
105
  checkSupplied(flags);
106
+ // Only the command that opened the session plays the intro; a caller that passed its own prompter did already,
107
+ // and the launcher marks WACHIMAN_INTRO_DONE, which `prompter.intro` honors.
108
+ if (!deps.prompter) await session.prompter.intro(deps.version ?? "unknown", "Let's put a watch post on this repo.");
65
109
  session.prompter.step("Project", 1);
66
110
  session.prompter.say(root, "muted");
67
- const asked = await promptForInit(flags, { defaultWorkflowRef }, session.prompter);
111
+ const asked = await promptForInit(flags, { defaultWorkflowRef, githubLogin: deps.githubLogin }, session.prompter);
68
112
  if (asked === null) {
69
113
  io.stderr("cancelled: nothing was written.");
114
+ outcome = "cancelled";
70
115
  return 130;
71
116
  }
72
117
  answered = asked;
73
118
  }
74
119
  const resolved = resolveInitOptions(answered, { interactive, defaultWorkflowRef });
75
120
  if (!resolved.ok) throw new UsageError(resolved.error);
76
- return await runInit(resolved.options, io, { ...deps, prompter: session?.prompter });
121
+ const code = await runInit(resolved.options, io, { ...deps, prompter: session?.prompter, closing });
122
+ // A saved run with one step left (a failed sign-in) ends neutrally, not as "Stopped.". The exit code is unchanged.
123
+ outcome = code !== 0 && code !== 130 && closing.warning !== undefined ? "done" : outcomeOf(code);
124
+ return code;
77
125
  } finally {
78
- session?.close();
126
+ session?.close(outcome, closing.warning);
79
127
  }
80
128
  }
81
129
 
@@ -87,6 +135,104 @@ export async function runInit(options: InitOptions, io: CommandIo, deps: InitDep
87
135
  const { github } = options;
88
136
  const prompter = options.interactive ? deps.prompter : undefined;
89
137
  let written: string | undefined;
138
+ let templateDone = false;
139
+ let templateInstalled = false;
140
+ /** Installs the PR description template once, at the end of the workflow work. A refusal or a failure is a report, not a failure of init. Returns whether it is in place. */
141
+ const installTemplate = (): boolean => {
142
+ if (!options.prTemplate) return false;
143
+ if (templateDone) return templateInstalled;
144
+ templateDone = true;
145
+ // `install` says "wrote <file>" for each file it writes; listening to it tells a failure that wrote nothing from one that stopped halfway.
146
+ const wrote: string[] = [];
147
+ const watching = {
148
+ stdout: (text: string) => io.stdout(text),
149
+ stderr: (line: string) => {
150
+ const file = /^wrote (.+?)(?:;|\.$)/.exec(line)?.[1];
151
+ if (file !== undefined) wrote.push(file);
152
+ io.stderr(line);
153
+ },
154
+ };
155
+ try {
156
+ // Same semantics as `pr-template install` with no --force and no --commit: init never commits.
157
+ runInstall({ force: false, commit: false }, root, watching, deps.prTemplate);
158
+ templateInstalled = true;
159
+ } catch (error) {
160
+ const reason = error instanceof Error ? error.message : String(error);
161
+ if (wrote.length === 0) {
162
+ io.stderr(`pr-template: not installed: ${reason}`);
163
+ } else {
164
+ const missing = PR_TEMPLATE_FILES.filter((f) => !wrote.includes(f));
165
+ io.stderr(`pr-template: only part of the install was done: ${reason}`);
166
+ io.stderr(`pr-template: written: ${wrote.join(", ")}; not written: ${missing.length > 0 ? missing.join(", ") : "nothing else"}.`);
167
+ }
168
+ io.stderr("The rest of init is unaffected. See `wachiman pr-template status`.");
169
+ }
170
+ return templateInstalled;
171
+ };
172
+
173
+ // The settings file: planned first (a link or a non-file in the way fails before anything is written), written under the same confirm.
174
+ const plan = options.settings ? planSettings(root, options.settings.kind) : undefined;
175
+ let settingsToWrite = plan && plan.action !== "same" ? plan : undefined;
176
+ let settingsWritten = false;
177
+ if (plan?.action === "same") io.stderr(`${SETTINGS_PATH} already says kind: ${plan.kind}.`);
178
+ if (settingsToWrite && github?.dryRun) {
179
+ io.stderr(`would write ${SETTINGS_PATH} (kind: ${settingsToWrite.kind})`);
180
+ if (settingsToWrite.action === "change" && !options.settings?.force) {
181
+ io.stderr(`note: ${SETTINGS_PATH} says kind: ${settingsToWrite.from ?? "(none)"}; a real run needs --force to change it.`);
182
+ }
183
+ }
184
+ if (settingsToWrite?.action === "change" && !github?.dryRun && !prompter && !options.settings?.force) {
185
+ throw new UsageError(`${SETTINGS_PATH} says kind: ${settingsToWrite.from ?? "(none)"}, not ${settingsToWrite.kind}. Re-run with --force to change it.`);
186
+ }
187
+ const settingsTitle = (p: Exclude<SettingsPlan, { action: "same" }>) => (p.action === "create" ? `${SETTINGS_PATH} (new)` : `${SETTINGS_PATH} (kind: ${p.from ?? "none"} to ${p.kind})`);
188
+ const showSettings = (p: Exclude<SettingsPlan, { action: "same" }>) => {
189
+ const body = p.action === "create" ? p.content.replace(/\n$/, "") : `kind: ${p.kind}`;
190
+ if (prompter?.fancy) prompter.note(body, settingsTitle(p));
191
+ else {
192
+ io.stderr(`--- ${settingsTitle(p)}`);
193
+ io.stderr(body);
194
+ }
195
+ };
196
+ /** Asks before replacing a different `kind:`; false: kept as it is, null: cancelled. */
197
+ const confirmChange = async (): Promise<boolean | null> => {
198
+ if (!prompter || settingsToWrite?.action !== "change") return true;
199
+ const { from, kind } = settingsToWrite;
200
+ const answer = await prompter.confirm(from === undefined ? `Add kind: ${kind} to ${SETTINGS_PATH}?` : `Change kind from ${from} to ${kind} in ${SETTINGS_PATH}?`, true);
201
+ if (answer === false) {
202
+ io.stderr(`${SETTINGS_PATH} left as it is.`);
203
+ settingsToWrite = undefined;
204
+ }
205
+ return answer;
206
+ };
207
+ const commitSettings = () => {
208
+ if (!settingsToWrite) return;
209
+ writeSettings(root, settingsToWrite, deps.settingsHooks);
210
+ settingsWritten = true;
211
+ io.stderr(`wrote ${SETTINGS_PATH} (kind: ${settingsToWrite.kind}).`);
212
+ };
213
+
214
+ /** The settings file alone, with no workflow to write: shows it, asks what needs asking. Returns an exit code to stop with, or undefined to go on. */
215
+ const askSettingsAlone = async (): Promise<number | undefined> => {
216
+ if (!prompter || !settingsToWrite) return undefined;
217
+ showSettings(settingsToWrite);
218
+ const changeAnswer = await confirmChange();
219
+ if (changeAnswer === null) {
220
+ io.stderr("cancelled: nothing was written.");
221
+ return 130;
222
+ }
223
+ if (settingsToWrite) {
224
+ const answer = settingsToWrite.action === "create" ? await prompter.confirm(`Write ${SETTINGS_PATH}?`, true) : true;
225
+ if (answer === null) {
226
+ io.stderr("cancelled: nothing was written.");
227
+ return 130;
228
+ }
229
+ if (!answer) {
230
+ io.stderr("not written.");
231
+ settingsToWrite = undefined;
232
+ }
233
+ }
234
+ return undefined;
235
+ };
90
236
 
91
237
  if (github) {
92
238
  const now = (deps.now ?? (() => new Date().toISOString()))();
@@ -97,39 +243,99 @@ export async function runInit(options: InitOptions, io: CommandIo, deps: InitDep
97
243
  });
98
244
  const inspected = inspectTarget(root, github.path);
99
245
  const shown = github.path;
246
+ // A re-run after a failure finds its own earlier output: the same workflow, not a conflict.
247
+ const unchanged = inspected.exists && sameWorkflow(readFileSync(inspected.target, "utf8"), rendered);
100
248
 
101
249
  if (github.dryRun) {
102
- if (inspected.exists && !github.force) io.stderr(`note: ${shown} exists; a real run needs --force to replace it (a .bak copy is kept).`);
250
+ if (unchanged) io.stderr(`note: ${shown} is unchanged.`);
251
+ else if (inspected.exists && !github.force && !prompter) io.stderr(`note: ${shown} exists; a real run needs --force to replace it (a .bak copy is kept).`);
252
+ if (options.prTemplate) io.stderr("note: --dry-run writes nothing, so the PR description template is not installed; `wachiman pr-template show` prints it.");
103
253
  io.stdout(rendered);
104
254
  return 0;
105
255
  }
106
- if (inspected.exists && !github.force) {
256
+ if (inspected.exists && !github.force && !prompter && !unchanged) {
107
257
  throw new UsageError(`A workflow already exists at ${shown}. Re-run with --force to replace it (a .bak copy is kept).`);
108
258
  }
109
- if (prompter) {
110
- io.stderr(`--- ${shown} (${inspected.exists ? "would overwrite" : "new"})`);
111
- io.stderr(rendered.replace(/\n$/, ""));
112
- const answer = await prompter.confirm("Write it?", true);
259
+ if (unchanged) {
260
+ io.stderr(`${shown} is unchanged: it already holds what init would write.`);
261
+ if (prompter && settingsToWrite) {
262
+ const code = await askSettingsAlone();
263
+ if (code !== undefined) return code;
264
+ }
265
+ written = shown;
266
+ } else if (prompter) {
267
+ const preview = rendered.replace(/\n$/, "");
268
+ // On a terminal the preview is a titled note in the session frame; otherwise it is the lines it always was.
269
+ if (prompter.fancy) prompter.note(preview, `${shown} (${inspected.exists ? "would overwrite" : "new"})`);
270
+ else {
271
+ io.stderr(`--- ${shown} (${inspected.exists ? "would overwrite" : "new"})`);
272
+ io.stderr(preview);
273
+ }
274
+ if (settingsToWrite) showSettings(settingsToWrite);
275
+ const changeAnswer = await confirmChange();
276
+ if (changeAnswer === null) {
277
+ io.stderr("cancelled: nothing was written.");
278
+ return 130;
279
+ }
280
+ // A re-run asks to replace, and the default is yes: the person is running init again on purpose, and the earlier file is kept as a .bak copy.
281
+ const answer = await prompter.confirm(inspected.exists ? "Replace the existing workflow? A .bak copy is kept." : "Write it?", true);
113
282
  if (answer === null) {
114
283
  io.stderr("cancelled: nothing was written.");
115
284
  return 130;
116
285
  }
117
286
  if (!answer) {
118
287
  io.stderr("not written.");
288
+ const templateIn = installTemplate();
289
+ // The closing line of a terminal session says what happened, not "All set".
290
+ if (prompter.fancy) prompter.close("done", templateIn ? "The workflow was not written; the PR description template is in place." : "Nothing was written.");
119
291
  return 0;
120
292
  }
121
293
  } else {
122
294
  io.stderr(`writing ${shown} (${inspected.exists ? "replacing the existing file; a .bak copy is kept" : "new"}).`);
123
295
  }
124
- const result = writeWorkflow({ repoDir: root, relativePath: github.path, content: rendered, inspected, now, hooks: deps.hooks });
125
- written = shown;
126
- io.stderr(`wrote ${shown}${result.backup ? `; the earlier file is kept as ${join(dirname(github.path), basename(result.backup))}` : ""}.`);
127
- if (options.mode === "github") prompter?.step("Checks and next actions", 4, 4);
128
- io.stderr("Two things are left to do in GitHub:");
129
- io.stderr(" 1. Add the repository secret ANTHROPIC_API_KEY (a Console key; Actions runs are billed to it): Settings, Secrets and variables, Actions.");
130
- io.stderr(` 2. Open a pull request that adds ${shown}. init does not commit, push or open one.`);
131
- io.stderr("Local runs use your signed-in claude, never this key.");
296
+ if (!unchanged) {
297
+ // The workflow first: it is what the run is for. If the settings file then fails, the error says the workflow stays.
298
+ const result = writeWorkflow({ repoDir: root, relativePath: github.path, content: rendered, inspected, now, hooks: deps.hooks });
299
+ written = shown;
300
+ io.stderr(`wrote ${shown}${result.backup ? `; the earlier file is kept as ${join(dirname(github.path), basename(result.backup))}` : ""}.`);
301
+ }
302
+ // The template is reported and never fails init, so it goes before the settings file, which can throw.
303
+ installTemplate();
304
+ try {
305
+ commitSettings();
306
+ } catch (error) {
307
+ io.stderr(`${shown} was written before ${SETTINGS_PATH} failed and stays in place.`);
308
+ throw error;
309
+ }
310
+ if (options.mode === "github") prompter?.step("Checks and next actions", 5, 5);
311
+ if (prompter?.fancy) {
312
+ // The same two things, as the closing "Next steps" box with the commands to run.
313
+ prompter.nextAction("Add the repository secret ANTHROPIC_API_KEY (a Console key; Actions runs are billed to it): Settings, Secrets and variables, Actions.", ["gh secret set ANTHROPIC_API_KEY"]);
314
+ const added = settingsWritten ? `${shown} and ${SETTINGS_PATH}` : shown;
315
+ prompter.nextAction(`Open a pull request that adds ${added}. init does not commit, push or open one.`, [
316
+ `git add ${quoteArgument(shown, "posix")}${settingsWritten ? ` ${SETTINGS_PATH}` : ""}`,
317
+ `git commit -m "Add the Wachiman review workflow${settingsWritten ? " and settings" : ""}"`,
318
+ "git push",
319
+ ]);
320
+ prompter.say("Local runs use your signed-in claude, never this key.", "muted");
321
+ } else {
322
+ io.stderr("Two things are left to do in GitHub:");
323
+ io.stderr(" 1. Add the repository secret ANTHROPIC_API_KEY (a Console key; Actions runs are billed to it): Settings, Secrets and variables, Actions.");
324
+ io.stderr(` 2. Open a pull request that adds ${settingsWritten ? `${shown} and ${SETTINGS_PATH}` : shown}. init does not commit, push or open one.`);
325
+ io.stderr("Local runs use your signed-in claude, never this key.");
326
+ }
327
+ }
328
+
329
+ if (!github && settingsToWrite && prompter) {
330
+ const code = await askSettingsAlone();
331
+ if (code !== undefined) return code;
332
+ commitSettings();
333
+ } else if (!github) commitSettings();
334
+ if (!github && settingsWritten) {
335
+ if (prompter?.fancy) prompter.nextAction(`Commit ${SETTINGS_PATH} so the repository kind travels with it. init does not commit.`, [`git add ${SETTINGS_PATH}`, 'git commit -m "Record the repository kind for Wachiman"']);
336
+ else io.stderr(`Commit ${SETTINGS_PATH} like any file; init does not commit.`);
132
337
  }
338
+ installTemplate();
133
339
 
134
340
  if (options.mode === "github") {
135
341
  io.stderr("github: pending; workflow written, add the secret and submit the workflow. Remote readiness was not checked.");
@@ -137,7 +343,7 @@ export async function runInit(options: InitOptions, io: CommandIo, deps: InitDep
137
343
  }
138
344
  if (prompter && deps.bindNow) {
139
345
  try {
140
- const code = await deps.bindNow(prompter, options.mode);
346
+ const code = await deps.bindNow(prompter, options.mode, deps.closing ?? {});
141
347
  if (code === 130 && written) io.stderr(`${written} was written before setup was cancelled and stays in place.`);
142
348
  if (code !== 130 && written) io.stderr(`github: pending; ${written} is written. Secret and workflow submission still require action in GitHub.`);
143
349
  return code;