wachiman 1.16.0 → 1.17.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 (51) hide show
  1. package/README.md +12 -0
  2. package/package.json +1 -1
  3. package/skills/wachiman-loop/SKILL.md +43 -0
  4. package/src/cli.ts +37 -6
  5. package/src/config.ts +21 -2
  6. package/src/connectors/local-git.ts +82 -1
  7. package/src/connectors/working-tree.ts +23 -1
  8. package/src/engine.ts +848 -127
  9. package/src/formats.ts +44 -3
  10. package/src/help.ts +121 -6
  11. package/src/history/command.ts +5 -5
  12. package/src/history/match.ts +24 -4
  13. package/src/history/store.ts +1 -1
  14. package/src/history/types.ts +7 -2
  15. package/src/init/agents.ts +135 -0
  16. package/src/init/args.ts +4 -2
  17. package/src/init/json.ts +82 -0
  18. package/src/init/options.ts +15 -5
  19. package/src/init/render.ts +3 -1
  20. package/src/init/run.ts +172 -18
  21. package/src/init/settings.ts +10 -0
  22. package/src/json-schema.ts +8 -0
  23. package/src/ledger.ts +2 -2
  24. package/src/local.ts +37 -9
  25. package/src/loop/command.ts +24 -2
  26. package/src/memory/candidates.ts +425 -0
  27. package/src/memory/capture.ts +298 -0
  28. package/src/memory/command.ts +195 -0
  29. package/src/memory/entries.ts +213 -0
  30. package/src/memory/hygiene.ts +291 -0
  31. package/src/memory/inspect.ts +74 -0
  32. package/src/memory/load.ts +283 -0
  33. package/src/memory/mute.ts +259 -0
  34. package/src/memory/personal.ts +253 -0
  35. package/src/memory/proposal.ts +92 -0
  36. package/src/memory/propose.ts +414 -0
  37. package/src/memory/remember.ts +187 -0
  38. package/src/memory/report.ts +250 -0
  39. package/src/memory/settings.ts +20 -0
  40. package/src/pr-template/install.ts +23 -0
  41. package/src/precision.ts +10 -2
  42. package/src/priority.ts +106 -0
  43. package/src/repo-settings.ts +166 -3
  44. package/src/risk.ts +38 -9
  45. package/src/sinks/common.ts +12 -6
  46. package/src/sinks/markdown.ts +3 -0
  47. package/src/sinks/terminal.ts +3 -0
  48. package/src/store/figures.ts +5 -4
  49. package/src/store/html.ts +1 -1
  50. package/src/verify.ts +20 -2
  51. package/templates/wachiman-review-caller.yml +7 -7
@@ -25,9 +25,13 @@ export interface RawInitFlags {
25
25
  projectKind?: string;
26
26
  force?: boolean;
27
27
  dryRun?: boolean;
28
+ /** Print one `wachiman.init/1` document on stdout; never prompt. */
29
+ json?: boolean;
28
30
  yes?: boolean;
29
31
  /** `--pr-template` is true, `--no-pr-template` is false; absent means not given. */
30
32
  prTemplate?: boolean;
33
+ /** `--no-agent-pointer` is false; absent means the pointer is written. */
34
+ agentPointer?: boolean;
31
35
  repoDir?: string;
32
36
  help?: boolean;
33
37
  }
@@ -38,8 +42,12 @@ export interface InitOptions {
38
42
  github?: { operator: string; tag: string; path: string; force: boolean; dryRun: boolean };
39
43
  /** Install the PR description template after the workflow work. Absent means no: a script that did not ask gets no new file. */
40
44
  prTemplate?: boolean;
45
+ /** False (`--no-agent-pointer`) skips the pointer in AGENTS.md or CLAUDE.md; absent means write it. */
46
+ agentPointer?: false;
41
47
  /** 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
48
  settings?: { kind: ProjectKind; force: boolean };
49
+ /** Set only in local mode (github mode carries it in `github.dryRun`): preview `.wachiman.yml` and the PR template, write nothing. */
50
+ dryRun?: true;
43
51
  repoDir: string;
44
52
  interactive: boolean;
45
53
  }
@@ -52,7 +60,7 @@ export type ResolveResult<T> = { ok: true; options: T } | { ok: false; error: st
52
60
  * docs/releasing.md); the CLI's own version is never a substitute,
53
61
  * because an unreleased or unrelated version would pin a workflow that does not exist.
54
62
  */
55
- export const DEFAULT_WORKFLOW_REF: string | undefined = "v1.16.0"; // x-release-please-version
63
+ export const DEFAULT_WORKFLOW_REF: string | undefined = "v1.17.0"; // x-release-please-version
56
64
 
57
65
  export const DEFAULT_WORKFLOW_PATH = ".github/workflows/wachiman-review.yml";
58
66
  const WORKFLOWS_DIR = ".github/workflows/";
@@ -64,7 +72,6 @@ const GITHUB_ONLY_FLAGS = [
64
72
  ["version", "--version"],
65
73
  ["path", "--path"],
66
74
  ["force", "--force"],
67
- ["dryRun", "--dry-run"],
68
75
  ] as const;
69
76
 
70
77
  export const initModes: readonly InitMode[] = ["github", "local", "both"];
@@ -104,7 +111,10 @@ export function resolveInitOptions(
104
111
  if (!initModes.includes(flags.mode as InitMode)) return fail(`--mode must be github, local or both, got "${flags.mode}".`);
105
112
  const mode = flags.mode as InitMode;
106
113
  const repoDir = flags.repoDir ?? ".";
107
- const templateOption = flags.prTemplate === true ? { prTemplate: true } : {};
114
+ const optionalFiles = {
115
+ ...(flags.prTemplate === true ? { prTemplate: true } : {}),
116
+ ...(flags.agentPointer === false ? { agentPointer: false as const } : {}),
117
+ };
108
118
  if (flags.projectKind !== undefined) {
109
119
  const kindError = projectKindProblem(flags.projectKind);
110
120
  if (kindError) return fail(kindError);
@@ -116,7 +126,7 @@ export function resolveInitOptions(
116
126
  const given = GITHUB_ONLY_FLAGS.filter(([key]) => flags[key] !== undefined && flags[key] !== false && !(key === "force" && settings))
117
127
  .map(([, name]) => name);
118
128
  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.`);
119
- return { ok: true, options: { mode, ...templateOption, ...(settings ? { settings } : {}), repoDir, interactive: ctx.interactive } };
129
+ return { ok: true, options: { mode, ...optionalFiles, ...(settings ? { settings } : {}), ...(flags.dryRun ? { dryRun: true as const } : {}), repoDir, interactive: ctx.interactive } };
120
130
  }
121
131
 
122
132
  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.`);
@@ -143,7 +153,7 @@ export function resolveInitOptions(
143
153
  options: {
144
154
  mode,
145
155
  github: { operator: flags.operator, tag, path: path.path, force: flags.force === true, dryRun: flags.dryRun === true },
146
- ...templateOption,
156
+ ...optionalFiles,
147
157
  ...(settings ? { settings } : {}),
148
158
  repoDir,
149
159
  interactive: ctx.interactive,
@@ -26,6 +26,8 @@ export function renderCallerWorkflow(template: string, p: { operator: string; ta
26
26
  }
27
27
  const body = template
28
28
  .replace(OPERATOR_ANCHOR, () => `operator: "${p.operator}"`)
29
- .replace(PIN_ANCHOR, (_match, prefix: string) => `${prefix}${p.tag}`);
29
+ .replace(PIN_ANCHOR, (_match, prefix: string) => `${prefix}${p.tag}`)
30
+ // The template marks its pin for release-please; that marker is not for the file the user gets.
31
+ .replace(/[ \t]+# x-release-please-version$/m, "");
30
32
  return p.header === undefined ? body : `${p.header}\n${body}`;
31
33
  }
package/src/init/run.ts CHANGED
@@ -2,7 +2,8 @@
2
2
  * `wachiman init` (command contract section 5.5): parse, prompt, resolve, then the one impure
3
3
  * half. It writes the chosen workflow file and its `.bak` copy and, when the repository kind is
4
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
5
+ * will be written (or named `--yes` or no terminal with every mandatory flag). In every mode it also
6
+ * adds the pointer to the wachiman-loop skill to `AGENTS.md` or `CLAUDE.md` (src/init/agents.ts). With
6
7
  * `--pr-template` (or a yes to the question) it also installs the PR description template, files
7
8
  * only, as `wachiman pr-template install` does: `.github/pull_request_template.md` and, when there
8
9
  * is something to keep, `.github/pr-template.json`. An existing unmanaged template is adopted and
@@ -12,8 +13,8 @@
12
13
  * (src/init/github-login.ts, up to 10 s) to suggest the operator, and only on a terminal in github
13
14
  * or both mode; Wachiman itself makes no request (no `fetch`).
14
15
  */
15
- import { readFileSync } from "node:fs";
16
- import { basename, dirname, join } from "node:path";
16
+ import { existsSync, readFileSync } from "node:fs";
17
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
17
18
  import type { CommandIo } from "../accounts/commands";
18
19
  import { UsageError } from "../config";
19
20
  import { spawnGit, type GitRunner } from "../evidence";
@@ -23,16 +24,20 @@ import { loadTerminalUi } from "../wizard/load";
23
24
  import type { Outcome, Prompter, PromptIO } from "../wizard/prompt";
24
25
  import type { Ui } from "../wizard/ui";
25
26
  import { projectCommands, quoteArgument } from "../wizard/command";
26
- import { runInstall, type Deps as PrTemplateDeps } from "../pr-template/install";
27
+ import { previewInstall, runInstall, TEMPLATE_FILE, type Deps as PrTemplateDeps } from "../pr-template/install";
27
28
  import { CHOICE_FILE } from "../pr-template/catalog";
28
- import { DEFAULT_WORKFLOW_REF, resolveInitOptions, type InitOptions, type RawInitFlags } from "./options";
29
+ import { parseInitFlags } from "./args";
30
+ import { buildDocument, failureDocument, printDocument, type FileAction, type InitReport } from "./json";
31
+ import { DEFAULT_WORKFLOW_REF, initModes, resolveInitOptions, type InitMode, type InitOptions, type RawInitFlags } from "./options";
29
32
  import { checkSupplied, promptForInit } from "./prompt";
30
33
  import { planSettings, SETTINGS_PATH, writeSettings, type SettingsPlan } from "./settings";
31
34
  import { callerHeader, renderCallerWorkflow } from "./render";
32
35
  import { inspectTarget, sameWorkflow, writeWorkflow, type WriteHooks } from "./write";
36
+ import { describePointer, manualHint, planPointer, pointerBlock, type PointerPlan } from "./agents";
37
+ import { writeManagedFile } from "../pr-template/write";
33
38
 
34
39
  /** 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"];
40
+ const PR_TEMPLATE_FILES = [CHOICE_FILE, TEMPLATE_FILE];
36
41
 
37
42
  export interface InitDeps {
38
43
  /** The caller template. Default: `templates/wachiman-review-caller.yml` of this install. */
@@ -64,6 +69,8 @@ export interface InitDeps {
64
69
  closing?: SessionClosing;
65
70
  /** The same hook for the settings file, for a test. */
66
71
  settingsHooks?: WriteHooks;
72
+ /** Set by `--json`: `runInit` records what it did to each file here, and prints no rendered workflow. */
73
+ report?: InitReport;
67
74
  }
68
75
 
69
76
  /**
@@ -87,8 +94,52 @@ const openSession = async (deps: InitDeps, env: Record<string, string | undefine
87
94
  /** How a finished run ends the session: 0 is done, 130 a cancel, anything else a stop. */
88
95
  const outcomeOf = (code: number): Outcome => (code === 0 ? "done" : code === 130 ? "cancelled" : "failed");
89
96
 
97
+ /** `init` as `cli.ts` runs it. A parse failure under `--json` is still one JSON document with exit 2. */
98
+ export async function runInitFromArgv(argv: string[], repoDir: string, env: Record<string, string | undefined>, io: CommandIo, deps: InitDeps = {}): Promise<number> {
99
+ let flags: RawInitFlags;
100
+ try {
101
+ flags = parseInitFlags(argv, repoDir);
102
+ } catch (error) {
103
+ if (!(error instanceof UsageError) || !argv.includes("--json")) throw error;
104
+ const at = argv.indexOf("--mode");
105
+ const named = at >= 0 ? argv[at + 1] : undefined;
106
+ const mode = initModes.includes(named as InitMode) ? (named as InitMode) : null;
107
+ io.stderr(error.message);
108
+ printDocument(io.stdout, failureDocument({ mode, dryRun: argv.includes("--dry-run"), repoDir: resolve(deps.cwd ?? process.cwd(), repoDir), report: {}, code: "usage", message: error.message }));
109
+ return 2;
110
+ }
111
+ return runInitCommand(flags, env, io, deps);
112
+ }
113
+
114
+ /** `--json`: never asks, prints one document, and sends every human line to stderr. */
115
+ async function runInitJson(flags: RawInitFlags, io: CommandIo, deps: InitDeps): Promise<number> {
116
+ const report: InitReport = {};
117
+ const defaultWorkflowRef = "defaultWorkflowRef" in deps ? deps.defaultWorkflowRef : DEFAULT_WORKFLOW_REF;
118
+ let repoDir = resolve(deps.cwd ?? process.cwd(), flags.repoDir ?? ".");
119
+ const named = flags.mode as InitMode;
120
+ let mode: InitMode | null = initModes.includes(named) ? named : null;
121
+ // Anything else init would print on stdout is a human line here.
122
+ const quiet: CommandIo = { stdout: (text) => io.stderr(text.replace(/\n$/, "")), stderr: io.stderr };
123
+ try {
124
+ repoDir = worktreeRoot(flags.repoDir ?? ".", deps.git);
125
+ const resolved = resolveInitOptions(flags, { interactive: false, defaultWorkflowRef });
126
+ if (!resolved.ok) throw new UsageError(resolved.error);
127
+ mode = resolved.options.mode;
128
+ await runInit(resolved.options, quiet, { ...deps, prompter: undefined, report });
129
+ printDocument(io.stdout, buildDocument({ mode, dryRun: resolved.options.github?.dryRun ?? resolved.options.dryRun === true, repoDir, report }));
130
+ return 0;
131
+ } catch (error) {
132
+ const message = error instanceof Error ? error.message : String(error);
133
+ const usage = error instanceof UsageError;
134
+ io.stderr(message);
135
+ printDocument(io.stdout, failureDocument({ mode, dryRun: flags.dryRun === true, repoDir, report, code: usage ? "usage" : "failed", message }));
136
+ return usage ? 2 : 1;
137
+ }
138
+ }
139
+
90
140
  /** From the parsed flags: asks what is missing when a person can be asked, resolves, and runs. */
91
141
  export async function runInitCommand(flags: RawInitFlags, env: Record<string, string | undefined>, io: CommandIo, deps: InitDeps = {}): Promise<number> {
142
+ if (flags.json) return runInitJson(flags, io, deps);
92
143
  // Fail before asking for an operator or account in an unusable target.
93
144
  const root = worktreeRoot(flags.repoDir ?? ".", deps.git);
94
145
  const interactive = deps.interactive ?? isInteractive(flags, env, deps.streams ?? { stdin: process.stdin, stdout: process.stdout });
@@ -132,7 +183,11 @@ export async function runInit(options: InitOptions, io: CommandIo, deps: InitDep
132
183
  const cwd = deps.cwd ?? process.cwd();
133
184
  // Before anything is rendered or written: this must be a git repository.
134
185
  const root = worktreeRoot(options.repoDir, deps.git);
186
+ // The pointer is planned here and never refuses the run: a problem becomes a "skip" that is reported at the end.
187
+ const pointer: PointerPlan | undefined = options.agentPointer === false ? undefined : planPointer(root);
135
188
  const { github } = options;
189
+ const dryRun = github?.dryRun ?? options.dryRun === true;
190
+ const report = deps.report;
136
191
  const prompter = options.interactive ? deps.prompter : undefined;
137
192
  let written: string | undefined;
138
193
  let templateDone = false;
@@ -142,19 +197,17 @@ export async function runInit(options: InitOptions, io: CommandIo, deps: InitDep
142
197
  if (!options.prTemplate) return false;
143
198
  if (templateDone) return templateInstalled;
144
199
  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.
200
+ const existed = new Set(PR_TEMPLATE_FILES.filter((f) => existsSync(join(root, f))));
201
+ const backups = new Map<string, string>();
202
+ // `install` reports each file it writes through `onWrite`; that tells a failure that wrote nothing from one that stopped halfway.
146
203
  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
- },
204
+ const record = (file: string, backup?: string) => {
205
+ wrote.push(file);
206
+ if (backup !== undefined) backups.set(file, isAbsolute(backup) && !relative(root, backup).startsWith("..") ? relative(root, backup) : backup);
154
207
  };
155
208
  try {
156
209
  // 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);
210
+ runInstall({ force: false, commit: false }, root, io, { ...deps.prTemplate, onWrite: record });
158
211
  templateInstalled = true;
159
212
  } catch (error) {
160
213
  const reason = error instanceof Error ? error.message : String(error);
@@ -167,21 +220,50 @@ export async function runInit(options: InitOptions, io: CommandIo, deps: InitDep
167
220
  }
168
221
  io.stderr("The rest of init is unaffected. See `wachiman pr-template status`.");
169
222
  }
223
+ if (report) {
224
+ const entry = (path: string): { path: string; action: FileAction; backup?: string } => {
225
+ if (wrote.includes(path)) return { path, action: existed.has(path) ? "replaced" : "created", ...(backups.has(path) ? { backup: backups.get(path) } : {}) };
226
+ return { path, action: templateInstalled ? "unchanged" : "refused" };
227
+ };
228
+ report.template = [entry(TEMPLATE_FILE), ...(wrote.includes(CHOICE_FILE) ? [entry(CHOICE_FILE)] : [])];
229
+ }
170
230
  return templateInstalled;
171
231
  };
172
232
 
233
+ /** A dry run: what installing the template would do, without writing. */
234
+ const previewTemplate = () => {
235
+ if (!report || !options.prTemplate) return;
236
+ const preview = previewInstall(root, deps.prTemplate);
237
+ report.template = [{ path: TEMPLATE_FILE, action: { create: "would-create", replace: "would-replace", unchanged: "unchanged", refused: "refused" }[preview] as FileAction }];
238
+ };
239
+
240
+ /** Records the pointer file in the report: a dry run says what would happen, a real run what did (a skip is a refusal). */
241
+ const reportPointer = (outcome: "plan" | "written" | "failed") => {
242
+ if (!report || !pointer) return;
243
+ const path = pointer.action === "skip" || pointer.action === "same" ? pointer.file : pointer.writePath;
244
+ const action: FileAction =
245
+ pointer.action === "skip" || outcome === "failed" ? "refused"
246
+ : pointer.action === "same" ? "unchanged"
247
+ : outcome === "plan" ? (pointer.action === "create" ? "would-create" : "would-replace")
248
+ : pointer.action === "create" ? "created" : "replaced";
249
+ report.agentPointer = { path, action };
250
+ };
251
+
173
252
  // 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
253
  const plan = options.settings ? planSettings(root, options.settings.kind) : undefined;
175
254
  let settingsToWrite = plan && plan.action !== "same" ? plan : undefined;
176
255
  let settingsWritten = false;
177
256
  if (plan?.action === "same") io.stderr(`${SETTINGS_PATH} already says kind: ${plan.kind}.`);
178
- if (settingsToWrite && github?.dryRun) {
257
+ if (report && plan?.action === "same") report.settings = { path: SETTINGS_PATH, action: "unchanged" };
258
+ else if (report && plan && dryRun) report.settings = { path: SETTINGS_PATH, action: plan.action === "create" ? "would-create" : options.settings?.force ? "would-replace" : "refused" };
259
+ if (settingsToWrite && dryRun) {
179
260
  io.stderr(`would write ${SETTINGS_PATH} (kind: ${settingsToWrite.kind})`);
180
261
  if (settingsToWrite.action === "change" && !options.settings?.force) {
181
262
  io.stderr(`note: ${SETTINGS_PATH} says kind: ${settingsToWrite.from ?? "(none)"}; a real run needs --force to change it.`);
182
263
  }
183
264
  }
184
- if (settingsToWrite?.action === "change" && !github?.dryRun && !prompter && !options.settings?.force) {
265
+ if (settingsToWrite?.action === "change" && !dryRun && !prompter && !options.settings?.force) {
266
+ if (report) report.settings = { path: SETTINGS_PATH, action: "refused" };
185
267
  throw new UsageError(`${SETTINGS_PATH} says kind: ${settingsToWrite.from ?? "(none)"}, not ${settingsToWrite.kind}. Re-run with --force to change it.`);
186
268
  }
187
269
  const settingsTitle = (p: Exclude<SettingsPlan, { action: "same" }>) => (p.action === "create" ? `${SETTINGS_PATH} (new)` : `${SETTINGS_PATH} (kind: ${p.from ?? "none"} to ${p.kind})`);
@@ -208,9 +290,55 @@ export async function runInit(options: InitOptions, io: CommandIo, deps: InitDep
208
290
  if (!settingsToWrite) return;
209
291
  writeSettings(root, settingsToWrite, deps.settingsHooks);
210
292
  settingsWritten = true;
293
+ if (report) report.settings = { path: SETTINGS_PATH, action: settingsToWrite.action === "create" ? "created" : "replaced" };
211
294
  io.stderr(`wrote ${SETTINGS_PATH} (kind: ${settingsToWrite.kind}).`);
212
295
  };
213
296
 
297
+ /** The pointer to the wachiman-loop skill, last among the files: a run refused or cancelled above writes none of them. */
298
+ const writePointer = async (): Promise<number | undefined> => {
299
+ if (!pointer) return undefined;
300
+ if (pointer.action === "skip") {
301
+ reportPointer("failed");
302
+ io.stderr(`wachiman pointer not written: ${pointer.reason}`);
303
+ return undefined;
304
+ }
305
+ if (pointer.action === "same") {
306
+ reportPointer("written");
307
+ io.stderr(`${pointer.file} already has the wachiman pointer; unchanged.`);
308
+ return undefined;
309
+ }
310
+ if (prompter) {
311
+ // Like every other file init writes: shown first, written only on a yes.
312
+ const shown = pointerBlock().trimEnd();
313
+ const title = `${pointer.file} (${pointer.action === "create" ? "new" : "would change"})`;
314
+ if (prompter.fancy) prompter.note(shown, title);
315
+ else {
316
+ io.stderr(`--- ${title}`);
317
+ io.stderr(shown);
318
+ }
319
+ const answer = await prompter.confirm(`Add the wachiman pointer to ${pointer.file}?`, true);
320
+ if (answer === null) {
321
+ io.stderr("cancelled: the pointer was not written.");
322
+ return 130;
323
+ }
324
+ if (!answer) {
325
+ io.stderr("wachiman pointer not written.");
326
+ return undefined;
327
+ }
328
+ }
329
+ try {
330
+ writeManagedFile({ repoDir: root, relativePath: pointer.writePath, content: pointer.content, inspected: pointer.inspected, now: (deps.now ?? (() => new Date().toISOString()))(), label: "init", backup: false, hooks: deps.hooks });
331
+ } catch (error) {
332
+ reportPointer("failed");
333
+ io.stderr(`wachiman pointer not written: ${error instanceof Error ? error.message : String(error)} The rest of init is unaffected. ${manualHint()}`);
334
+ return undefined;
335
+ }
336
+ reportPointer("written");
337
+ const how = pointer.action === "create" ? "created" : pointer.action === "append" ? "added to" : "replaced in";
338
+ io.stderr(`wrote the wachiman pointer: ${how} ${pointer.file}${pointer.writePath !== pointer.file ? ` (through the link, to ${pointer.writePath})` : ""}.`);
339
+ return undefined;
340
+ };
341
+
214
342
  /** 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
343
  const askSettingsAlone = async (): Promise<number | undefined> => {
216
344
  if (!prompter || !settingsToWrite) return undefined;
@@ -249,11 +377,19 @@ export async function runInit(options: InitOptions, io: CommandIo, deps: InitDep
249
377
  if (github.dryRun) {
250
378
  if (unchanged) io.stderr(`note: ${shown} is unchanged.`);
251
379
  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).`);
380
+ if (pointer) for (const line of describePointer(pointer)) io.stderr(line);
381
+ else io.stderr("note: --no-agent-pointer: no wachiman pointer would be written to AGENTS.md or CLAUDE.md.");
382
+ reportPointer("plan");
252
383
  if (options.prTemplate) io.stderr("note: --dry-run writes nothing, so the PR description template is not installed; `wachiman pr-template show` prints it.");
253
- io.stdout(rendered);
384
+ if (report) {
385
+ const refused = inspected.exists && !unchanged && !github.force;
386
+ report.workflow = { path: shown, action: unchanged ? "unchanged" : refused ? "refused" : inspected.exists ? "would-replace" : "would-create", content: rendered };
387
+ previewTemplate();
388
+ } else io.stdout(rendered);
254
389
  return 0;
255
390
  }
256
391
  if (inspected.exists && !github.force && !prompter && !unchanged) {
392
+ if (report) report.workflow = { path: shown, action: "refused" };
257
393
  throw new UsageError(`A workflow already exists at ${shown}. Re-run with --force to replace it (a .bak copy is kept).`);
258
394
  }
259
395
  if (unchanged) {
@@ -263,6 +399,7 @@ export async function runInit(options: InitOptions, io: CommandIo, deps: InitDep
263
399
  if (code !== undefined) return code;
264
400
  }
265
401
  written = shown;
402
+ if (report) report.workflow = { path: shown, action: "unchanged" };
266
403
  } else if (prompter) {
267
404
  const preview = rendered.replace(/\n$/, "");
268
405
  // On a terminal the preview is a titled note in the session frame; otherwise it is the lines it always was.
@@ -297,6 +434,7 @@ export async function runInit(options: InitOptions, io: CommandIo, deps: InitDep
297
434
  // The workflow first: it is what the run is for. If the settings file then fails, the error says the workflow stays.
298
435
  const result = writeWorkflow({ repoDir: root, relativePath: github.path, content: rendered, inspected, now, hooks: deps.hooks });
299
436
  written = shown;
437
+ if (report) report.workflow = { path: shown, action: inspected.exists ? "replaced" : "created", ...(result.backup ? { backup: join(dirname(github.path), basename(result.backup)) } : {}) };
300
438
  io.stderr(`wrote ${shown}${result.backup ? `; the earlier file is kept as ${join(dirname(github.path), basename(result.backup))}` : ""}.`);
301
439
  }
302
440
  // The template is reported and never fails init, so it goes before the settings file, which can throw.
@@ -326,6 +464,20 @@ export async function runInit(options: InitOptions, io: CommandIo, deps: InitDep
326
464
  }
327
465
  }
328
466
 
467
+ if (!github && dryRun) {
468
+ // A local dry run previews the files init would write and writes none (decision 4 of the agent-operated setup spec).
469
+ if (options.prTemplate) io.stderr("note: --dry-run writes nothing, so the PR description template is not installed; `wachiman pr-template show` prints it.");
470
+ previewTemplate();
471
+ if (pointer) for (const line of describePointer(pointer)) io.stderr(line);
472
+ else io.stderr("note: --no-agent-pointer: no wachiman pointer would be written to AGENTS.md or CLAUDE.md.");
473
+ reportPointer("plan");
474
+ const pointerWrites = pointer?.action === "create" || pointer?.action === "append" || pointer?.action === "replace";
475
+ if (!options.settings && !options.prTemplate && !pointerWrites) {
476
+ io.stderr("dry run: nothing would be written. Local mode has no workflow; a project kind, the PR template or the agent pointer are the only files it writes.");
477
+ for (const command of projectCommands("setup", options.repoDir, cwd)) io.stderr(`Next, on this machine: ${command} (binds this repository to a Claude account)`);
478
+ }
479
+ return 0;
480
+ }
329
481
  if (!github && settingsToWrite && prompter) {
330
482
  const code = await askSettingsAlone();
331
483
  if (code !== undefined) return code;
@@ -336,6 +488,8 @@ export async function runInit(options: InitOptions, io: CommandIo, deps: InitDep
336
488
  else io.stderr(`Commit ${SETTINGS_PATH} like any file; init does not commit.`);
337
489
  }
338
490
  installTemplate();
491
+ const pointerCode = await writePointer();
492
+ if (pointerCode !== undefined) return pointerCode;
339
493
 
340
494
  if (options.mode === "github") {
341
495
  io.stderr("github: pending; workflow written, add the secret and submit the workflow. Remote readiness was not checked.");
@@ -32,6 +32,16 @@ export const settingsContent = (kind: ProjectKind) =>
32
32
  "# model: claude-sonnet-5-5",
33
33
  "# effort: high",
34
34
  "",
35
+ "# Optional. Path rules: files a rule matches are read first, the review quotes your reason, and for",
36
+ "# critical and high it says a person should approve the change. Wachiman never approves or blocks.",
37
+ "# Rules are read from the base branch, so a pull request cannot change its own rules.",
38
+ "# Inspired by the Claude Code team's review process:",
39
+ "# https://claude.dev/blog/solving-code-review-at-anthropic/#the-life-of-a-change",
40
+ "# paths:",
41
+ '# - match: ".github/workflows/**"',
42
+ "# severity: critical",
43
+ "# reason: CI can publish releases and read secrets",
44
+ "",
35
45
  ].join("\n");
36
46
 
37
47
  /** The value of the top-level `kind:` line (quotes and a trailing comment removed), or undefined when there is none. */
@@ -9,6 +9,8 @@ const CHECKED = new Set([
9
9
  "const",
10
10
  "enum",
11
11
  "minimum",
12
+ "maximum",
13
+ "minLength",
12
14
  "properties",
13
15
  "required",
14
16
  "additionalProperties",
@@ -70,6 +72,12 @@ export function validate(schema: Schema, value: unknown, rootSchema: Schema = sc
70
72
  if (typeof schema.minimum === "number" && typeof value === "number" && value < schema.minimum) {
71
73
  problems.push(`${path}: ${value} is below ${schema.minimum}`);
72
74
  }
75
+ if (typeof schema.maximum === "number" && typeof value === "number" && value > schema.maximum) {
76
+ problems.push(`${path}: ${value} is above ${schema.maximum}`);
77
+ }
78
+ if (typeof schema.minLength === "number" && typeof value === "string" && value.length < schema.minLength) {
79
+ problems.push(`${path}: is shorter than ${schema.minLength}`);
80
+ }
73
81
  if (Array.isArray(schema.oneOf)) {
74
82
  const matching = (schema.oneOf as Schema[]).filter((s) => validate(s, value, rootSchema, path).length === 0).length;
75
83
  if (matching !== 1) problems.push(`${path}: matches ${matching} of oneOf, expected exactly 1`);
package/src/ledger.ts CHANGED
@@ -171,7 +171,7 @@ const post = (ledgerUrl: string, route: string, token: string, payload: unknown,
171
171
 
172
172
  /**
173
173
  * A GitHub OIDC token for `audience`. Needs `id-token: write` in the job, which only
174
- * `review-platform.yml` grants; without the request variables there is nothing to retry.
174
+ * `wachiman-platform.yml` grants; without the request variables there is nothing to retry.
175
175
  */
176
176
  export function requestIdToken(env: LedgerEnv, audience: string, curl: CurlFn): string {
177
177
  const url = env.ACTIONS_ID_TOKEN_REQUEST_URL;
@@ -182,7 +182,7 @@ export function requestIdToken(env: LedgerEnv, audience: string, curl: CurlFn):
182
182
  if (status !== 200 || typeof value !== "string" || value === "") {
183
183
  if (isOutage(status)) throw new LedgerUnavailable(`GitHub did not issue an id token (HTTP ${status}).`);
184
184
  throw new LedgerBadAnswer(
185
- `GitHub did not issue an OIDC token for the ledger (HTTP ${status}). Check that the job has \`id-token: write\` and calls review-platform.yml.`,
185
+ `GitHub did not issue an OIDC token for the ledger (HTTP ${status}). Check that the job has \`id-token: write\` and calls wachiman-platform.yml.`,
186
186
  );
187
187
  }
188
188
  return value;
package/src/local.ts CHANGED
@@ -18,6 +18,7 @@ import {
18
18
  buildLocalInput,
19
19
  DEFAULT_MAX_DEPTH,
20
20
  EMPTY_TREE_LABEL,
21
+ localMemory,
21
22
  localRepoSettings,
22
23
  localSettingsCommit,
23
24
  type LocalRefs,
@@ -26,17 +27,19 @@ import {
26
27
  snapshotHead,
27
28
  warnSnapshotDifferences,
28
29
  } from "./connectors/local-git";
29
- import { DEFAULT_EXCLUDE, estimateFor, filterFiles, planBatches, reviewChange, reviewOptionsOf, type ReviewInput, type ReviewResult } from "./engine";
30
+ import { DEFAULT_EXCLUDE, estimateFor, filterFiles, planBatches, reviewChange, reviewOptionsOf, splitUnreviewable, type ReviewInput, type ReviewResult } from "./engine";
30
31
  import { sizeGate, type ReviewEstimate } from "./estimate";
31
32
  import { spawnGit } from "./evidence";
33
+ import { personalSourceFor } from "./memory/personal";
32
34
  import { assertReviewInputFormat, REVIEW_INPUT_V2 } from "./formats";
33
- import { applyRepoSettings, fileSettingsNote, ignoredSettingsNote, wantsRepoSettings, type RepoSettings } from "./repo-settings";
35
+ import { applyRepoSettings, fileSettingsNote, ignoredSettingsNote, parsePathRules, wantsRepoSettings, type RepoSettings } from "./repo-settings";
34
36
  import { workingTreeInput, snapshotWorkingTree } from "./connectors/working-tree";
35
37
  import { historyRoot, historySettings, saveRun } from "./history";
36
38
  import { readConfig, wachimanHome } from "./accounts/config";
37
39
  import { confirmProfile, type SpawnFn } from "./accounts/confirm";
38
40
  import { failureText, profileLine, resolveProfile, type ResolvedProfile } from "./accounts/resolve";
39
41
  import { repositoryKey } from "./history/store";
42
+ import { entriesUsed, recordMemoryUse } from "./memory/hygiene";
40
43
  import { inspectIsolatedProfile, parseProfile, populatedProfileError, profileDir } from "./profiles";
41
44
  import { getProvider as defaultGetProvider, type ProviderAdapter } from "./providers";
42
45
  import { InterruptedError, SUBSCRIPTION_KEY_REFUSAL } from "./providers/claude-code";
@@ -63,6 +66,8 @@ export interface LocalArgs {
63
66
  history: boolean;
64
67
  /** `--verify` forces the verifier on, `--no-verify` off; unset follows `WACHIMAN_VERIFY` (off by default, ADR 0027). */
65
68
  verify: boolean | undefined;
69
+ /** `--no-memory`: review as a repository without a `.wachiman/memory/` folder (the control arm of the memory replay). */
70
+ noMemory?: boolean;
66
71
  /** `--result-version`: with `--format json`, which result version to write (default 1 for a committed change). */
67
72
  resultVersion?: 1 | 2;
68
73
  input?: string;
@@ -70,7 +75,7 @@ export interface LocalArgs {
70
75
 
71
76
  export const localUsage = `wachiman local [paths…] [--base <ref> | --from <commit> | --commit <commit>] [--max-depth <n>] [--repo-dir <dir>]
72
77
  [--input <file>] [--format terminal|markdown|json] [--output <file>]
73
- [--profile <name>] [--agent-prompt] [--history] [--verify | --no-verify]
78
+ [--profile <name>] [--agent-prompt] [--history] [--verify | --no-verify] [--no-memory]
74
79
  [--result-version 1|2] [--working-tree staged|all]`;
75
80
 
76
81
  /** Every flag `local` takes. `ask` takes the subset it names in `ask-command`. */
@@ -79,6 +84,7 @@ export const LOCAL_FLAGS = [
79
84
  "--history",
80
85
  "--verify",
81
86
  "--no-verify",
87
+ "--no-memory",
82
88
  "--result-version",
83
89
  "--working-tree",
84
90
  "--base",
@@ -131,6 +137,7 @@ export function parseFlags(argv: string[], command: string, accepted: readonly s
131
137
  };
132
138
  if (name === "--agent-prompt" && eq === -1) args.agentPrompt = true;
133
139
  else if (name === "--history" && eq === -1) args.history = true;
140
+ else if (name === "--no-memory" && eq === -1) args.noMemory = true;
134
141
  else if (name === "--verify" && eq === -1) {
135
142
  args.verify = true;
136
143
  sawVerify = true;
@@ -230,6 +237,9 @@ export function readInputFile(path: string): Omit<ReviewInput, "headDir"> {
230
237
  if (!instr || !isString(instr.baseSha) || !Array.isArray(instr.files)) problems.push("instructions");
231
238
  if (!Array.isArray(input.scope) || input.scope.some((s: unknown) => !isString(s))) problems.push("scope");
232
239
  if (problems.length > 0) throw new UsageError(`--input ${path} is missing or mistypes: ${problems.join(", ")}.`);
240
+ // Optional, and checked as `.wachiman.yml` is: an entry that names no severity is not guessed at.
241
+ if (input.pathRules !== undefined) input.pathRules = parsePathRules(input.pathRules, `--input ${path}`);
242
+ if (input.pathPolicyChanged !== undefined && input.pathPolicyChanged !== true) throw new UsageError(`--input ${path}: pathPolicyChanged must be true when present.`);
233
243
  // In memory only (docs/formats): the head the agent reads is always the engine's own snapshot.
234
244
  if ("headDir" in input) throw new UsageError(`--input ${path} carries headDir, which a review input file never holds.`);
235
245
  return input as Omit<ReviewInput, "headDir">;
@@ -558,13 +568,17 @@ export async function runLocal(
558
568
  io.stderr(`head: ${short(head)}`);
559
569
  }
560
570
  const { kept, dropped } = filterFiles(input.files, [...DEFAULT_EXCLUDE, ...config.exclude], input.scope);
561
- const batches = planBatches(kept, {
562
- maxLines: config.batchLines,
563
- maxChars: config.batchChars,
564
- });
571
+ const batches = planBatches(
572
+ kept,
573
+ {
574
+ maxLines: config.batchLines,
575
+ maxChars: config.batchChars,
576
+ },
577
+ input.pathRules,
578
+ );
565
579
  io.stderr(`files: ${kept.length} (${dropped.length} excluded)`);
566
580
  io.stderr(`batches: ${batches.length}`);
567
- const warning = sizeWarning(estimateFor(kept, config), sizeGate(config, false), config.budgetUsd, config.model);
581
+ const warning = sizeWarning(estimateFor(kept, config, input.pathRules), sizeGate(config, false), config.budgetUsd, config.model);
568
582
  if (warning) io.stderr(warning);
569
583
  io.stderr(
570
584
  config.verify
@@ -572,7 +586,13 @@ export async function runLocal(
572
586
  : "verify: off",
573
587
  );
574
588
 
575
- const result = await reviewChange(input, reviewOptionsOf(config, config.budgetUsd, profile.kind === "managed" ? "isolated" : "default"), {
589
+ // The memory of the commit the diff starts at (the merge-base), selected by the files this run reviews, binaries
590
+ // excluded as the Actions path does (ADR 0056).
591
+ const reviewable = splitUnreviewable(kept, input.headDir).reviewable;
592
+ if (args.noMemory) io.stderr("memory: off (--no-memory)");
593
+ // The developer's personal memory for this repository (keyed by `origin`) is loaded after it, on the laptop only.
594
+ const memory = args.noMemory ? undefined : localMemory(repoDir, input.change.base.sha, reviewable.map((f) => f.filename), io.stderr, spawnGit, personalSourceFor(home, repoDir, spawnGit, io.stderr));
595
+ const result = await reviewChange(input, { ...reviewOptionsOf(config, config.budgetUsd, profile.kind === "managed" ? "isolated" : "default"), ...(memory ? { memory } : {}) }, {
576
596
  provider,
577
597
  ...(verifier ? { verifier } : {}),
578
598
  // The verifier reads the code before the change too; made once, only when there is something to check.
@@ -597,6 +617,14 @@ export async function runLocal(
597
617
  io.stderr("Interrupted: the review stopped and its snapshot was removed.");
598
618
  return 130;
599
619
  }
620
+ // The laptop's record of which memory entries a review used (`memory check` suggests archiving the unused). It lives in the history store, so it is written only when history is on (ADR 0020); it never leaves the laptop and never fails a review.
621
+ if (memory && history.enabled) {
622
+ try {
623
+ recordMemoryUse(home, repositoryKey(repoDir).key, entriesUsed(memory, reviewable.map((f) => f.filename), result.muted ?? []), new Date().toISOString().slice(0, 10));
624
+ } catch (error) {
625
+ io.stderr(`memory: this run's use of memory was not recorded (${error instanceof Error ? error.message : error})`);
626
+ }
627
+ }
600
628
  // After the review and before the snapshot goes: the cited lines are read from it.
601
629
  let annotation: HistoryAnnotation | undefined;
602
630
  if (history.enabled) {