wachiman 1.15.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 (54) hide show
  1. package/README.md +1 -0
  2. package/package.json +1 -1
  3. package/src/accounts/commands.ts +3 -2
  4. package/src/accounts/confirm.ts +1 -1
  5. package/src/accounts/profile-list.ts +24 -0
  6. package/src/cli.ts +54 -20
  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 +280 -97
  12. package/src/help.ts +85 -3
  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 +204 -24
  18. package/src/init/settings.ts +127 -0
  19. package/src/init/write.ts +16 -102
  20. package/src/local-ask.ts +5 -4
  21. package/src/local.ts +55 -10
  22. package/src/loop/command.ts +5 -5
  23. package/src/pr-template/adopt.ts +434 -0
  24. package/src/pr-template/catalog.ts +429 -0
  25. package/src/pr-template/check-run.ts +328 -0
  26. package/src/pr-template/check.ts +338 -0
  27. package/src/pr-template/describe.ts +368 -0
  28. package/src/pr-template/format.ts +399 -0
  29. package/src/pr-template/gh.ts +159 -0
  30. package/src/pr-template/install.ts +288 -0
  31. package/src/pr-template/legacy-guides.ts +50 -0
  32. package/src/pr-template/pr-risk.ts +426 -0
  33. package/src/pr-template/render.ts +302 -0
  34. package/src/pr-template/resolve.ts +65 -0
  35. package/src/pr-template/run.ts +88 -0
  36. package/src/pr-template/strip.ts +171 -0
  37. package/src/pr-template/write.ts +139 -0
  38. package/src/providers/claude-code.ts +7 -8
  39. package/src/providers/codex.ts +4 -4
  40. package/src/providers/spawn.ts +95 -0
  41. package/src/providers/types.ts +5 -2
  42. package/src/repo-settings.ts +159 -0
  43. package/src/setup/prompt.ts +49 -33
  44. package/src/setup/run.ts +31 -6
  45. package/src/sinks/common.ts +10 -3
  46. package/src/sinks/markdown.ts +3 -2
  47. package/src/sinks/terminal.ts +3 -2
  48. package/src/upgrade/command.ts +286 -0
  49. package/src/upgrade/pin.ts +112 -0
  50. package/src/wizard/mascot.ts +56 -51
  51. package/src/wizard/prompt-fancy.ts +10 -2
  52. package/src/wizard/prompt.ts +17 -4
  53. package/src/wizard/ui.ts +2 -0
  54. package/templates/pr/sections.json +163 -0
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";
@@ -13,11 +21,18 @@ import { repositoryKey } from "../history/store";
13
21
  import { isInteractive, type TerminalStreams } from "../wizard/interactive";
14
22
  import { loadTerminalUi } from "../wizard/load";
15
23
  import type { Outcome, Prompter, PromptIO } from "../wizard/prompt";
24
+ import type { Ui } from "../wizard/ui";
16
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,22 +47,41 @@ 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
80
  const openSession = async (deps: InitDeps, env: Record<string, string | undefined>, ui: Awaited<ReturnType<typeof loadTerminalUi>>) => {
48
- if (deps.prompter) return { prompter: deps.prompter, close: (_outcome: Outcome) => {} };
49
- const prompter = await ui.openPrompter(deps.promptIO ?? { input: process.stdin, output: process.stderr }, env);
50
- return { prompter, close: (outcome: Outcome) => prompter.close(outcome) };
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
 
53
87
  /** How a finished run ends the session: 0 is done, 130 a cancel, anything else a stop. */
@@ -64,6 +98,7 @@ export async function runInitCommand(flags: RawInitFlags, env: Record<string, st
64
98
  const session = ui ? await openSession(deps, env, ui) : undefined;
65
99
  if (ui) io = ui.wizardIo(io, (deps.promptIO?.output ?? process.stderr) as { isTTY?: boolean }, env, session?.prompter);
66
100
  let outcome: Outcome = "failed";
101
+ const closing: SessionClosing = {};
67
102
  try {
68
103
  let answered = flags;
69
104
  if (session) {
@@ -73,7 +108,7 @@ export async function runInitCommand(flags: RawInitFlags, env: Record<string, st
73
108
  if (!deps.prompter) await session.prompter.intro(deps.version ?? "unknown", "Let's put a watch post on this repo.");
74
109
  session.prompter.step("Project", 1);
75
110
  session.prompter.say(root, "muted");
76
- const asked = await promptForInit(flags, { defaultWorkflowRef }, session.prompter);
111
+ const asked = await promptForInit(flags, { defaultWorkflowRef, githubLogin: deps.githubLogin }, session.prompter);
77
112
  if (asked === null) {
78
113
  io.stderr("cancelled: nothing was written.");
79
114
  outcome = "cancelled";
@@ -83,11 +118,12 @@ export async function runInitCommand(flags: RawInitFlags, env: Record<string, st
83
118
  }
84
119
  const resolved = resolveInitOptions(answered, { interactive, defaultWorkflowRef });
85
120
  if (!resolved.ok) throw new UsageError(resolved.error);
86
- const code = await runInit(resolved.options, io, { ...deps, prompter: session?.prompter });
87
- outcome = outcomeOf(code);
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);
88
124
  return code;
89
125
  } finally {
90
- session?.close(outcome);
126
+ session?.close(outcome, closing.warning);
91
127
  }
92
128
  }
93
129
 
@@ -99,6 +135,104 @@ export async function runInit(options: InitOptions, io: CommandIo, deps: InitDep
99
135
  const { github } = options;
100
136
  const prompter = options.interactive ? deps.prompter : undefined;
101
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
+ };
102
236
 
103
237
  if (github) {
104
238
  const now = (deps.now ?? (() => new Date().toISOString()))();
@@ -109,16 +243,27 @@ export async function runInit(options: InitOptions, io: CommandIo, deps: InitDep
109
243
  });
110
244
  const inspected = inspectTarget(root, github.path);
111
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);
112
248
 
113
249
  if (github.dryRun) {
114
- 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.");
115
253
  io.stdout(rendered);
116
254
  return 0;
117
255
  }
118
- if (inspected.exists && !github.force) {
256
+ if (inspected.exists && !github.force && !prompter && !unchanged) {
119
257
  throw new UsageError(`A workflow already exists at ${shown}. Re-run with --force to replace it (a .bak copy is kept).`);
120
258
  }
121
- if (prompter) {
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) {
122
267
  const preview = rendered.replace(/\n$/, "");
123
268
  // On a terminal the preview is a titled note in the session frame; otherwise it is the lines it always was.
124
269
  if (prompter.fancy) prompter.note(preview, `${shown} (${inspected.exists ? "would overwrite" : "new"})`);
@@ -126,44 +271,79 @@ export async function runInit(options: InitOptions, io: CommandIo, deps: InitDep
126
271
  io.stderr(`--- ${shown} (${inspected.exists ? "would overwrite" : "new"})`);
127
272
  io.stderr(preview);
128
273
  }
129
- const answer = await prompter.confirm("Write it?", true);
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);
130
282
  if (answer === null) {
131
283
  io.stderr("cancelled: nothing was written.");
132
284
  return 130;
133
285
  }
134
286
  if (!answer) {
135
287
  io.stderr("not written.");
288
+ const templateIn = installTemplate();
136
289
  // The closing line of a terminal session says what happened, not "All set".
137
- if (prompter.fancy) prompter.close("done", "Nothing was written.");
290
+ if (prompter.fancy) prompter.close("done", templateIn ? "The workflow was not written; the PR description template is in place." : "Nothing was written.");
138
291
  return 0;
139
292
  }
140
293
  } else {
141
294
  io.stderr(`writing ${shown} (${inspected.exists ? "replacing the existing file; a .bak copy is kept" : "new"}).`);
142
295
  }
143
- const result = writeWorkflow({ repoDir: root, relativePath: github.path, content: rendered, inspected, now, hooks: deps.hooks });
144
- written = shown;
145
- io.stderr(`wrote ${shown}${result.backup ? `; the earlier file is kept as ${join(dirname(github.path), basename(result.backup))}` : ""}.`);
146
- if (options.mode === "github") prompter?.step("Checks and next actions", 4, 4);
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);
147
311
  if (prompter?.fancy) {
148
312
  // The same two things, as the closing "Next steps" box with the commands to run.
149
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"]);
150
- prompter.nextAction(`Open a pull request that adds ${shown}. init does not commit, push or open one.`, [`git add ${quoteArgument(shown, "posix")}`, 'git commit -m "Add the Wachiman review workflow"', "git push"]);
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
+ ]);
151
320
  prompter.say("Local runs use your signed-in claude, never this key.", "muted");
152
321
  } else {
153
322
  io.stderr("Two things are left to do in GitHub:");
154
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.");
155
- io.stderr(` 2. Open a pull request that adds ${shown}. init does not commit, push or open one.`);
324
+ io.stderr(` 2. Open a pull request that adds ${settingsWritten ? `${shown} and ${SETTINGS_PATH}` : shown}. init does not commit, push or open one.`);
156
325
  io.stderr("Local runs use your signed-in claude, never this key.");
157
326
  }
158
327
  }
159
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.`);
337
+ }
338
+ installTemplate();
339
+
160
340
  if (options.mode === "github") {
161
341
  io.stderr("github: pending; workflow written, add the secret and submit the workflow. Remote readiness was not checked.");
162
342
  return 0;
163
343
  }
164
344
  if (prompter && deps.bindNow) {
165
345
  try {
166
- const code = await deps.bindNow(prompter, options.mode);
346
+ const code = await deps.bindNow(prompter, options.mode, deps.closing ?? {});
167
347
  if (code === 130 && written) io.stderr(`${written} was written before setup was cancelled and stays in place.`);
168
348
  if (code !== 130 && written) io.stderr(`github: pending; ${written} is written. Secret and workflow submission still require action in GitHub.`);
169
349
  return code;
@@ -0,0 +1,127 @@
1
+ /**
2
+ * The repository settings file `.wachiman.yml`, written by `init` (ADR 0048). `init` records one
3
+ * key, `kind`, and a new file carries `model` and `effort` commented out (ADR 0049); the engine reads
4
+ * the file through `parseRepoSettings` in `src/repo-settings.ts`. It never chooses an account, a
5
+ * profile or a binary. Writing is plain string handling on purpose: init only ever creates the file
6
+ * or replaces the one top-level `kind:` line, and keeps every other line as it was.
7
+ *
8
+ * It lives at the repository root so it is visible in every mode, including local mode where there
9
+ * is no workflow and no `.github/` folder. It is never inside `.github/workflows/`: GitHub parses
10
+ * every YAML file there as a workflow.
11
+ */
12
+ import { randomBytes } from "node:crypto";
13
+ import { linkSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
14
+ import { basename, dirname, join } from "node:path";
15
+ import { UsageError } from "../config";
16
+ import { parseRepoSettings, SETTINGS_PATH } from "../repo-settings";
17
+ import type { ProjectKind } from "./options";
18
+ import { inspectTarget, type TargetState } from "./write";
19
+
20
+ export { SETTINGS_PATH };
21
+
22
+ const KIND_LINE = /^kind:[^\r\n]*/m;
23
+
24
+ /** The content of a new settings file. */
25
+ export const settingsContent = (kind: ProjectKind) =>
26
+ [
27
+ "# Wachiman settings for this repository, written by `wachiman init`. Commit it like any file.",
28
+ '# kind: the shape of the repository, "monorepo" or "single". Metadata only for now.',
29
+ `kind: ${kind}`,
30
+ "",
31
+ "# Optional. Wachiman's defaults are what its benchmarks measure; change them knowing that.",
32
+ "# model: claude-sonnet-5-5",
33
+ "# effort: high",
34
+ "",
35
+ ].join("\n");
36
+
37
+ /** The value of the top-level `kind:` line (quotes and a trailing comment removed), or undefined when there is none. */
38
+ export function readKind(content: string): string | undefined {
39
+ const line = KIND_LINE.exec(content);
40
+ if (!line) return undefined;
41
+ let value = line[0].slice("kind:".length).trim();
42
+ const quoted = /^(["'])(.*?)\1/.exec(value);
43
+ value = quoted ? quoted[2] : value.replace(/(^|\s+)#.*$/, "").trim();
44
+ return value === "" ? undefined : value;
45
+ }
46
+
47
+ /** Any top-level line that names the key, however it is written (`kind:`, `"kind":`, `'kind' :`). */
48
+ const ANY_KIND_KEY = /^(?:kind|"kind"|'kind')[ \t]*:/gm;
49
+
50
+ /**
51
+ * The file with only its top-level `kind:` line replaced (or `kind: X` appended when there is none).
52
+ * Plain string handling can miss a differently written key (a quoted key, a flow mapping) and leave
53
+ * a duplicate or invalid result, so the result is checked before it is returned: it must parse with
54
+ * the engine's own parser, name `kind` exactly once and say `kind: X`. Otherwise this refuses, and
55
+ * the person edits the file by hand.
56
+ */
57
+ export function withKind(content: string, kind: ProjectKind): string {
58
+ let next: string;
59
+ if (KIND_LINE.test(content)) next = content.replace(KIND_LINE, `kind: ${kind}`);
60
+ else {
61
+ const separator = content === "" || content.endsWith("\n") ? "" : "\n";
62
+ next = `${content}${separator}kind: ${kind}\n`;
63
+ }
64
+ const byHand = `Edit ${SETTINGS_PATH} by hand to say \`kind: ${kind}\`; init will not rewrite it.`;
65
+ let parsed: ReturnType<typeof parseRepoSettings>;
66
+ try {
67
+ parsed = parseRepoSettings(next);
68
+ } catch (error) {
69
+ throw new UsageError(`${SETTINGS_PATH} cannot be updated safely (${error instanceof Error ? error.message : error}) ${byHand}`);
70
+ }
71
+ if ((next.match(ANY_KIND_KEY) ?? []).length !== 1 || parsed.kind !== kind) {
72
+ throw new UsageError(`${SETTINGS_PATH} has a \`kind\` key that init cannot rewrite as a plain top-level line (a quoted key, a flow mapping or a duplicate). ${byHand}`);
73
+ }
74
+ return next;
75
+ }
76
+
77
+ export type SettingsPlan =
78
+ | { action: "create"; kind: ProjectKind; content: string; inspected: TargetState }
79
+ | { action: "same"; kind: ProjectKind }
80
+ | { action: "change"; kind: ProjectKind; from: string | undefined; content: string; inspected: TargetState };
81
+
82
+ /** Looks at the file without writing: what writing `kind` would do. Refuses a link or a non-file like the workflow does. */
83
+ export function planSettings(repoDir: string, kind: ProjectKind): SettingsPlan {
84
+ const inspected = inspectTarget(repoDir, SETTINGS_PATH);
85
+ if (!inspected.exists) return { action: "create", kind, content: settingsContent(kind), inspected };
86
+ const current = readFileSync(inspected.target, "utf8");
87
+ const from = readKind(current);
88
+ if (from === kind) return { action: "same", kind };
89
+ return { action: "change", kind, from, content: withKind(current, kind), inspected };
90
+ }
91
+
92
+ /** Writes a planned create or change: an exclusive temporary file, then a link (new) or a rename (only if the file is unchanged since the plan). */
93
+ export function writeSettings(repoDir: string, plan: Exclude<SettingsPlan, { action: "same" }>, hooks?: { beforeCommit?: () => void }): string {
94
+ const { inspected } = plan;
95
+ const dir = dirname(inspected.target);
96
+ const again = inspectTarget(repoDir, SETTINGS_PATH);
97
+ if (again.exists !== inspected.exists || again.identity !== inspected.identity) {
98
+ throw new UsageError(`${inspected.target} changed while init was running; nothing was written. Run it again.`);
99
+ }
100
+ const tmp = join(dir, `.${basename(inspected.target)}.${process.pid}-${randomBytes(4).toString("hex")}.tmp`);
101
+ writeFileSync(tmp, plan.content, { flag: "wx", mode: 0o644 });
102
+ try {
103
+ hooks?.beforeCommit?.();
104
+ if (inspected.exists) {
105
+ // Checked again right before the rename: an edit made since the plan is never overwritten.
106
+ if (inspectTarget(repoDir, SETTINGS_PATH).identity !== inspected.identity) {
107
+ throw new UsageError(`${inspected.target} changed while init was running; it was not replaced. Run it again.`);
108
+ }
109
+ renameSync(tmp, inspected.target);
110
+ }
111
+ else {
112
+ try {
113
+ linkSync(tmp, inspected.target);
114
+ } catch (error) {
115
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") throw new UsageError(`${inspected.target} appeared while init was running; nothing was written.`);
116
+ throw error;
117
+ }
118
+ }
119
+ } finally {
120
+ try {
121
+ unlinkSync(tmp);
122
+ } catch {
123
+ // Renamed into place, or already gone.
124
+ }
125
+ }
126
+ return inspected.target;
127
+ }
package/src/init/write.ts CHANGED
@@ -1,61 +1,16 @@
1
1
  /**
2
- * Writing the workflow file safely (contract section 5.5): no symbolic link may stand in for
3
- * `.github`, `workflows` or the target, an existing file is copied to a backup that never
4
- * overwrites another backup, and the new content goes in through an exclusive temporary file and a
5
- * rename after the target is found unchanged since it was inspected.
2
+ * Writing the workflow file safely (contract section 5.5). The mechanism is shared with
3
+ * `wachiman pr-template` and lives in `../pr-template/write.ts`; this file keeps the names and the
4
+ * behaviour `init` relies on: a backup of an existing file on every write, and messages that say
5
+ * `init`.
6
6
  */
7
- import { randomBytes } from "node:crypto";
8
- import { constants, copyFileSync, linkSync, lstatSync, mkdirSync, realpathSync, renameSync, unlinkSync, writeFileSync, type Stats } from "node:fs";
9
- import { basename, dirname, join, sep } from "node:path";
10
- import { UsageError } from "../config";
7
+ import { backupStamp, inspectManagedTarget, writeManagedFile, type TargetState, type WriteHooks } from "../pr-template/write";
11
8
 
12
- export interface TargetState {
13
- /** The real path the file is written to: the real repository root plus the relative path. */
14
- target: string;
15
- exists: boolean;
16
- identity?: string;
17
- }
18
-
19
- const identityOf = (s: Stats) => `${s.dev}:${s.ino}:${s.size}:${s.mtimeMs}`;
20
-
21
- const lstatOrNull = (path: string) => {
22
- try {
23
- return lstatSync(path);
24
- } catch (error) {
25
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
26
- throw error;
27
- }
28
- };
9
+ export { backupStamp };
10
+ export type { TargetState, WriteHooks };
29
11
 
30
12
  /** Looks at the target and its ancestors without following a link; refuses anything that is not a plain directory chain and a plain file. */
31
- export function inspectTarget(repoDir: string, relativePath: string): TargetState {
32
- const root = realpathSync(repoDir);
33
- let current = root;
34
- const parts = relativePath.split("/");
35
- for (const part of parts.slice(0, -1)) {
36
- current = join(current, part);
37
- const stat = lstatOrNull(current);
38
- if (stat === null) break;
39
- if (stat.isSymbolicLink()) throw new UsageError(`${current} is a symbolic link; init does not write through links. Replace it with a real directory.`);
40
- if (!stat.isDirectory()) throw new UsageError(`${current} is not a directory; init cannot write ${relativePath}.`);
41
- const real = realpathSync(current);
42
- if (real !== root && !real.startsWith(root + sep)) throw new UsageError(`${current} resolves outside the repository (${real}); init refuses it.`);
43
- }
44
- const target = join(root, relativePath);
45
- const stat = lstatOrNull(target);
46
- if (stat === null) return { target, exists: false };
47
- if (stat.isSymbolicLink()) throw new UsageError(`${target} is a symbolic link; init does not write through links.`);
48
- if (!stat.isFile()) throw new UsageError(`${target} exists and is not a regular file.`);
49
- return { target, exists: true, identity: identityOf(stat) };
50
- }
51
-
52
- /** `YYYYMMDD-HHMMSS` in UTC, from an ISO timestamp. */
53
- export const backupStamp = (iso: string) => iso.replace(/[-:]/g, "").replace("T", "-").slice(0, 15);
54
-
55
- export interface WriteHooks {
56
- /** Runs after the temporary file is complete and before it replaces the target; a test changes the target here. */
57
- beforeCommit?: () => void;
58
- }
13
+ export const inspectTarget = (repoDir: string, relativePath: string): TargetState => inspectManagedTarget(repoDir, relativePath, "init");
59
14
 
60
15
  /**
61
16
  * Writes `content` to the inspected target. An existing file is copied to `<target>.bak-<stamp>`
@@ -63,52 +18,11 @@ export interface WriteHooks {
63
18
  * inspected. A new file is linked into place, which fails if one appeared meanwhile. Returns the
64
19
  * backup path when one was made.
65
20
  */
66
- export function writeWorkflow(p: { repoDir: string; relativePath: string; content: string; inspected: TargetState; now: string; hooks?: WriteHooks }): { target: string; backup?: string } {
67
- const { inspected } = p;
68
- const dir = dirname(inspected.target);
69
- mkdirSync(dir, { recursive: true });
70
- // The directories exist now: look again, so a link planted between the first look and the mkdir is still refused.
71
- const again = inspectTarget(p.repoDir, p.relativePath);
72
- if (again.exists !== inspected.exists || again.identity !== inspected.identity) {
73
- throw new UsageError(`${inspected.target} changed while init was running; nothing was written. Run it again.`);
74
- }
75
- let backup: string | undefined;
76
- if (inspected.exists) {
77
- const stamp = backupStamp(p.now);
78
- for (let n = 1; backup === undefined; n++) {
79
- const candidate = `${inspected.target}.bak-${stamp}${n === 1 ? "" : `-${n}`}`;
80
- try {
81
- copyFileSync(inspected.target, candidate, constants.COPYFILE_EXCL);
82
- backup = candidate;
83
- } catch (error) {
84
- if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
85
- }
86
- }
87
- }
88
- const tmp = join(dir, `.${basename(inspected.target)}.${process.pid}-${randomBytes(4).toString("hex")}.tmp`);
89
- writeFileSync(tmp, p.content, { flag: "wx", mode: 0o644 });
90
- try {
91
- p.hooks?.beforeCommit?.();
92
- if (inspected.exists) {
93
- const now = lstatOrNull(inspected.target);
94
- if (now === null || now.isSymbolicLink() || identityOf(now) !== inspected.identity) {
95
- throw new UsageError(`${inspected.target} changed while init was running; it was not replaced.${backup ? ` A copy of the earlier file is at ${backup}.` : ""}`);
96
- }
97
- renameSync(tmp, inspected.target);
98
- } else {
99
- try {
100
- linkSync(tmp, inspected.target);
101
- } catch (error) {
102
- if ((error as NodeJS.ErrnoException).code === "EEXIST") throw new UsageError(`${inspected.target} appeared while init was running; nothing was written.`);
103
- throw error;
104
- }
105
- }
106
- } finally {
107
- try {
108
- unlinkSync(tmp);
109
- } catch {
110
- // Renamed into place, or already gone.
111
- }
112
- }
113
- return { target: inspected.target, ...(backup ? { backup } : {}) };
114
- }
21
+ export const writeWorkflow = (p: { repoDir: string; relativePath: string; content: string; inspected: TargetState; now: string; hooks?: WriteHooks }): { target: string; backup?: string } =>
22
+ writeManagedFile({ ...p, label: "init", backup: true });
23
+
24
+ /** The generated first line carries a version and a date; a re-run on another day still writes the same workflow. */
25
+ const withoutHeader = (text: string) => text.replace(/^# Generated by wachiman init [^\n]*\n/, "");
26
+
27
+ /** True when `existing` is what `rendered` would write, apart from the generated header line. */
28
+ export const sameWorkflow = (existing: string, rendered: string) => withoutHeader(existing) === withoutHeader(rendered);
package/src/local-ask.ts CHANGED
@@ -77,7 +77,7 @@ export function storedReviewOf(
77
77
  return undefined;
78
78
  }
79
79
 
80
- export function runAsk(
80
+ export async function runAsk(
81
81
  args: AskArgs,
82
82
  repoDir: string,
83
83
  env: Record<string, string | undefined>,
@@ -87,7 +87,7 @@ export function runAsk(
87
87
  engineVersion: string;
88
88
  },
89
89
  deps: LocalDeps = {},
90
- ): number {
90
+ ): Promise<number> {
91
91
  // The account, the provider and the settings are checked before the change is read, as `local` does.
92
92
  const { config, provider, state } = openLocalSession({
93
93
  profile: args.profile,
@@ -96,6 +96,7 @@ export function runAsk(
96
96
  env,
97
97
  stderr: io.stderr,
98
98
  deps,
99
+ scope: { workingTree: args.workingTree, base: args.base, commit: args.commit, from: args.from, maxDepth: args.maxDepth },
99
100
  });
100
101
  const onSigint = () => {
101
102
  state.interrupted = true;
@@ -159,10 +160,10 @@ export function runAsk(
159
160
  });
160
161
 
161
162
  // One call, read-only, in the snapshot of the head: the same place the review reads from.
162
- let result: ReturnType<typeof runProvider> | undefined;
163
+ let result: Awaited<ReturnType<typeof runProvider>> | undefined;
163
164
  let failure = "";
164
165
  try {
165
- result = runProvider(
166
+ result = await runProvider(
166
167
  { provider, log: io.stderr, warn: io.stderr },
167
168
  config,
168
169
  input.headDir,