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
package/src/formats.ts CHANGED
@@ -9,6 +9,8 @@ import { UsageError } from "./config";
9
9
  import type { Contract } from "./contracts";
10
10
  import type { TokenUsage } from "./cost";
11
11
  import type { Fidelity } from "./fidelity/types";
12
+ import type { MemoryRecord } from "./memory/load";
13
+ import type { MutedFinding } from "./memory/mute";
12
14
  import type {
13
15
  BaseInstructions,
14
16
  BatchReport,
@@ -21,6 +23,8 @@ import type {
21
23
  Unreviewable,
22
24
  } from "./engine";
23
25
  import type { ProviderErrorClass } from "./providers/errors";
26
+ import type { Arm, Priority } from "./priority";
27
+ import type { PathRule } from "./repo-settings";
24
28
  import type { RiskMap } from "./risk";
25
29
 
26
30
  export const REVIEW_INPUT_FORMAT = "wachiman.review-input/1";
@@ -73,6 +77,17 @@ export interface ReviewInput {
73
77
  since?: { sha: string; rebased: boolean; commits?: string[]; carried?: string[] };
74
78
  /** Open threads for the model to answer. */
75
79
  conversation?: Thread[];
80
+ /**
81
+ * The repository's path rules (`paths` in `.wachiman.yml`, ADR 0058), read by the connector from
82
+ * `change.base.sha`, never from the head. Absent when the repository has none.
83
+ */
84
+ pathRules?: PathRule[];
85
+ /**
86
+ * The change edits the path rules (or `.wachiman.yml` no longer parses), so `pathRules` also
87
+ * holds the rule that makes `.wachiman.yml` a critical path for this review, and the review says
88
+ * its policy changed (ADR 0058 decision 5). Set by the connector; absent otherwise.
89
+ */
90
+ pathPolicyChanged?: true;
76
91
  }
77
92
 
78
93
  /** Which Claude Code profile ran the review; every GitHub-mode run is "ci". */
@@ -177,8 +192,15 @@ export interface VerifiedFields {
177
192
  originReason?: string;
178
193
  originEvidence?: Citation[];
179
194
  verification: FindingVerification;
180
- /** Derived by `tierWord`, never trusted from a model. */
195
+ /** Derived by `tierWord`, never trusted from a model. Deprecated beside `priority`; `/3` drops it (ADR 0059). */
181
196
  tier: Tier;
197
+ /**
198
+ * The finding priority (ADR 0059), derived by `priorityOf` from the final severity, confidence
199
+ * and topic, after verification; never trusted from a model. Optional: a result written before it existed has none.
200
+ */
201
+ priority?: Priority;
202
+ /** 0-100, recorded for each finding and not used to order findings yet; never displayed and never a gate. Present with `priority`. */
203
+ rank?: number;
182
204
  }
183
205
 
184
206
  export interface ResultFindingV2 extends Finding, VerifiedFields {
@@ -263,10 +285,29 @@ export interface ReviewResultV2 {
263
285
  batches: BatchReport[];
264
286
  threadReplies: ReviewOutput["thread_replies"];
265
287
  instructionChanges: { files: string[]; baseSha: string };
288
+ /** The change edits the path rules; the review ran under the base's. Only `/2` has it: `toResultV1` leaves it out. */
289
+ pathPolicyChanged?: true;
290
+ /**
291
+ * The repository's memory this review loaded (ADR 0056): the base commit it was read at, the files
292
+ * loaded, what was left out and whether it was over budget. Absent when the repository has none.
293
+ * Only `/2` has it: `toResultV1` leaves it out.
294
+ */
295
+ memory?: MemoryRecord;
296
+ /**
297
+ * The findings a memory exception muted (ADR 0057): not posted as comments, listed in the summary
298
+ * under "Muted by memory" with the id of the entry. Absent when nothing was muted. Only `/2` has it.
299
+ */
300
+ muted?: MutedFinding[];
266
301
  /** Totals include the coverage calls and the verifier call. */
267
302
  execution: Execution;
268
303
  /** Absent when verification was off. */
269
304
  verification?: ResultVerificationV2;
305
+ /**
306
+ * The trial arm of this pull request (ADR 0059 decision 10): `word` renders today's Important/Nit
307
+ * word, `priority` the priority row. Only a pull request review under `WACHIMAN_PRIORITY_TRIAL=1`
308
+ * has it; `toResultV1` leaves it out.
309
+ */
310
+ arm?: Arm;
270
311
  }
271
312
 
272
313
  /** What the core returns and every sink renders: the `/2` result. `toResultV1` makes the `/1` form. */
@@ -313,7 +354,7 @@ function verificationNotice(result: ReviewResultV2, v: ResultVerificationV2) {
313
354
  /**
314
355
  * The `/1` form of a result, for committed-change JSON (ADR 0030). Pure. It keeps the surviving
315
356
  * findings and every `/1` field, drops what `/1` has no place for (the account, the root
316
- * verification, each finding's origin, verification and tier) and says in one notice what the
357
+ * verification, each finding's origin, verification, tier, priority and rank, the trial arm) and says in one notice what the
317
358
  * verifier did. A working-tree result has no `/1` form: its head is a tree id, and a tree id must
318
359
  * never pass for a commit.
319
360
  */
@@ -322,7 +363,7 @@ export function toResultV1(result: ReviewResultV2): ReviewResultV1 {
322
363
  throw new UsageError("A working-tree review has no result /1: its head is a tree id, not a commit. Use --result-version 2.");
323
364
  }
324
365
  const { account: _account, ...provider } = result.provider;
325
- const { verification, riskMap: _riskMap, fidelity: _fidelity, ...rest } = result;
366
+ const { verification, riskMap: _riskMap, fidelity: _fidelity, pathPolicyChanged: _pathPolicyChanged, arm: _arm, memory: _memory, muted: _muted, ...rest } = result;
326
367
  return {
327
368
  ...rest,
328
369
  format: REVIEW_RESULT_V1,
package/src/help.ts CHANGED
@@ -65,6 +65,7 @@ const GH_EXIT: readonly Row[] = [
65
65
  const GH_ENV: readonly Row[] = [
66
66
  ["GH_TOKEN", "Token for gh. Never given to the agent"],
67
67
  ["GITHUB_REPOSITORY", "owner/name of the repository"],
68
+ ["WACHIMAN_PRIORITY_TRIAL", "Set to 1 to run the finding priority A/B: each pull request shows the Important/Nit word or the Priority row, by a hash of repository and number"],
68
69
  ["ANTHROPIC_API_KEY", "The claude-code provider needs this or CLAUDE_CODE_OAUTH_TOKEN (not in a dry run)"],
69
70
  ["CLAUDE_CODE_OAUTH_TOKEN", "A Claude subscription token (`claude setup-token`); when set it wins and the API key never reaches the agent"],
70
71
  OTHER_ENV,
@@ -135,6 +136,7 @@ const localPage: Page = {
135
136
  ["--verify | --no-verify", "One more call tries to refute each finding above info. Default: follows WACHIMAN_VERIFY (off)"],
136
137
  ["--result-version 1|2", "With --format json only. Default: 1 for committed changes, 2 for --working-tree"],
137
138
  ["--history", "Save the run under ~/.wachiman/history and label each finding new or open. Default: off (or WACHIMAN_HISTORY=1)"],
139
+ ["--no-memory", "Ignore .wachiman/memory/ for this run, as if the repository had none (the control arm of the memory replay). Default: off"],
138
140
  REPO_DIR,
139
141
  ],
140
142
  env: [
@@ -211,7 +213,7 @@ const historyPage: Page = {
211
213
  ["--since <n>d", "Only findings seen in the last n days"],
212
214
  ["--all-repos", "Every repository in the history, not just this clone's"],
213
215
  ["--json", "The replayed state as wachiman.history-state/1"],
214
- ["--verdict <id> correct|partial|wrong", "Record your judgement of a finding (the id is in the report and the listing)"],
216
+ ["--verdict <id> correct|partial|wrong|intentional|not-important", "Record your judgement of a finding (the id is in the report and the listing)"],
215
217
  ["--reason <text>", "With --verdict: why"],
216
218
  ["--forget [--all]", "Delete this repository's history, or all of it with --all. Takes no --all-repos, --json or --since"],
217
219
  REPO_DIR,
@@ -295,7 +297,7 @@ const setupPage: Page = {
295
297
 
296
298
  const initPage: Page = {
297
299
  usage: initUsage,
298
- summary: "Write the GitHub Actions caller workflow (.github/workflows/wachiman-review.yml), or, with --mode local, write no workflow and hand over to setup. With a repository kind, also write .wachiman.yml. It can also install the PR description template.",
300
+ summary: "Write the GitHub Actions caller workflow (.github/workflows/wachiman-review.yml), or, with --mode local, write no workflow and hand over to setup. With a repository kind, also write .wachiman.yml. It writes a pointer to the wachiman-loop skill into AGENTS.md (or CLAUDE.md). It can also install the PR description template.",
299
301
  options: [
300
302
  ["--mode github|local|both", "What to set up. Required without a terminal"],
301
303
  ["--operator <login>", "The GitHub login allowed to command the reviewer. Required for github and both without a terminal"],
@@ -303,15 +305,17 @@ const initPage: Page = {
303
305
  ["--path <file>", "Default: .github/workflows/wachiman-review.yml; a .yml or .yaml file directly in .github/workflows/"],
304
306
  ["--project-kind monorepo|single", "The kind of repository, recorded in .wachiman.yml (metadata only). Asked on a terminal; without one, the file is left alone"],
305
307
  ["--force", "Replace an existing workflow after copying it to <file>.bak-<timestamp>; with --project-kind, also change a different kind"],
306
- ["--dry-run", "Print the file to stdout and write nothing"],
308
+ ["--dry-run", "Write nothing. github and both print the rendered workflow to stdout; local reports on stderr what it would write (.wachiman.yml, the PR template)"],
307
309
  ["--pr-template", "Also install the PR description template (`wachiman pr-template install`, files only, never a commit). A refusal is reported and does not fail init"],
308
310
  ["--no-pr-template", "Do not install it and do not ask. Without either flag a terminal asks (default yes) and a script gets none"],
311
+ ["--no-agent-pointer", "Do not write the wachiman pointer into AGENTS.md or CLAUDE.md. A failure to write it never fails init"],
309
312
  ["--yes", "No prompts"],
313
+ ["--json", "Never prompt, and print one wachiman.init/1 document on stdout (files and their actions, local and GitHub readiness, error). Status lines go to stderr"],
310
314
  REPO_DIR,
311
315
  ],
312
316
  env: [HOME_ENV, ["CI", "true or 1 turns the prompts off"], ["NO_COLOR", "Turns styling off"]],
313
- exit: [["0", "Done (including a \"no\" answer)"], ["1", "Engine error"], ["2", "Usage error: an unknown flag, an existing file without --force, --mode local with a workflow flag"], ["130", "Cancelled; nothing is written"]],
314
- examples: ["wachiman init --mode both", "wachiman init --mode github --operator octocat --dry-run"],
317
+ exit: [["0", "Done (including a \"no\" answer)"], ["1", "Engine error"], ["2", "Usage error: an unknown flag, an existing file without --force, --mode local with a workflow flag (not --dry-run); with --json it is printed as the document"], ["130", "Cancelled; nothing is written"]],
318
+ examples: ["wachiman init --mode both", "wachiman init --mode github --operator octocat --dry-run", "wachiman init --mode local --project-kind single --json"],
315
319
  docs: `${DOCS}/cli.md#init`,
316
320
  };
317
321
 
@@ -472,13 +476,123 @@ const prTemplatePageRoot: Page = {
472
476
  },
473
477
  };
474
478
 
479
+ const MEMORY_DOCS = `${DOCS}/cli.md#memory`;
480
+ const MEMORY_EXIT: readonly Row[] = [
481
+ ["0", "Done: the memory is clean (or the repository has no .wachiman/memory/ folder; suggestions do not count), the entry was recorded, or the entry was archived"],
482
+ ["1", "check found a problem; archive could not move the entry (no such entry, already archived, no memory folder, or a symbolic link in the way) and wrote nothing; or propose or remember refused or failed and wrote nothing (not proposable, text does not match the id, pull request closed, push failed), or it recorded the entry but could not open the draft pull request"],
483
+ ["2", "Usage or configuration error: an unknown subcommand, an unknown id, a bad flag, or an invalid .wachiman.yml"],
484
+ ];
485
+ const MEMORY_USAGE = [
486
+ "wachiman memory check [--repo-dir <dir>]",
487
+ "wachiman memory archive <id> [--repo-dir <dir>]",
488
+ "wachiman memory report [--since <date>] [--format terminal|json] [--repo-dir <dir>]",
489
+ "wachiman memory candidates [--format terminal|json] [--repo-dir <dir>]",
490
+ "wachiman memory add --kind convention|exception --scope <glob> --rule <text> --why <text> [options]",
491
+ "wachiman memory show <id> [--repo-dir <dir>]",
492
+ "wachiman memory propose <id> [--personal | --team] [--repo-dir <dir>]",
493
+ "wachiman memory propose --from-personal [<id>...] [--repo-dir <dir>]",
494
+ "wachiman memory remember <pr> [--repo-dir <dir>]",
495
+ ].join("\n");
496
+ const memoryPage: Page = {
497
+ usage: MEMORY_USAGE,
498
+ summary: "Check the repository memory in .wachiman/memory/ (Markdown files that teach Wachiman how code is written here), and propose new entries from the laptop. No model is called. `add` writes only a file under the Wachiman home; `propose` is the only subcommand that writes to a remote, and only a branch on origin and a draft pull request. A review loads this memory from the base commit: conventions go into the review prompt, and findings an exception covers are muted after discovery (see the docs).",
499
+ options: [REPO_DIR],
500
+ exit: MEMORY_EXIT,
501
+ examples: ["wachiman memory check", "wachiman memory candidates", "wachiman memory show 4c1e9a2", "wachiman memory propose 4c1e9a2"],
502
+ docs: MEMORY_DOCS,
503
+ subs: {
504
+ report: {
505
+ usage: "wachiman memory report [--since <date>] [--format terminal|json] [--repo-dir <dir>]",
506
+ summary: "Print, per month and in total, what the local review history says about memory: comments by outcome (fixed, wrong, intentional, not important, unjudged), findings muted by memory with the entry ids, the memory's size in the working tree, and the entries no review used. Outcomes come from `wachiman local --history` runs and `wachiman history --verdict`; with no history it says so and exits 0. No model is called.",
507
+ options: [
508
+ ["--since <date>", "Only runs saved on or after this day (YYYY-MM-DD)"],
509
+ ["--format terminal|json", "Default: terminal. json prints wachiman.memory-report/1"],
510
+ REPO_DIR,
511
+ ],
512
+ exit: MEMORY_EXIT,
513
+ examples: ["wachiman memory report", "wachiman memory report --since 2026-11-01 --format json"],
514
+ docs: MEMORY_DOCS,
515
+ },
516
+ check: {
517
+ usage: "wachiman memory check [--repo-dir <dir>]",
518
+ summary: "Read .wachiman/memory/ from the working tree and print every problem as <path>:<line>: <message>: a malformed entry, an entry id that is not its digest, a glob that matches no file, an index row that names a missing file, an area file index.md does not list, and a line-budget overrun (memory.max_index_lines, memory.max_loaded_lines). After the problems it prints suggestions, which never change the exit code: likely duplicates (same kind, overlapping scopes, rules at least 80% alike by word overlap; contradictions are not detected) and entries not used in memory.archive_after_days (from the laptop's record of use; not made in GitHub Actions, nor when that record is missing or unreadable, where a note says use is unknown).",
519
+ options: [REPO_DIR],
520
+ exit: MEMORY_EXIT,
521
+ examples: ["wachiman memory check"],
522
+ docs: MEMORY_DOCS,
523
+ },
524
+ archive: {
525
+ usage: "wachiman memory archive <id> [--repo-dir <dir>]",
526
+ summary: "Move one entry from its file to .wachiman/memory/archive.md, which no review loads. It changes the working tree only: nothing is committed or pushed, so commit the change yourself. Wachiman only ever suggests archiving; this runs only when you ask.",
527
+ options: [REPO_DIR],
528
+ exit: MEMORY_EXIT,
529
+ examples: ["wachiman memory archive 4c1e9a2"],
530
+ docs: MEMORY_DOCS,
531
+ },
532
+ candidates: {
533
+ usage: "wachiman memory candidates [--format terminal|json] [--repo-dir <dir>]",
534
+ summary: "List the memory candidates kept on this laptop for the repository, and which can be proposed. A candidate found by the tool needs memory.min_evidence pieces of evidence from different pull requests or branches; an explicit instruction needs one. A fix supports only a convention.",
535
+ options: [["--format terminal|json", "Default: terminal. json prints wachiman.memory-candidates/1 with the evidence counts and the reason a candidate is not proposable"], REPO_DIR],
536
+ exit: MEMORY_EXIT,
537
+ examples: ["wachiman memory candidates --format json"],
538
+ docs: MEMORY_DOCS,
539
+ },
540
+ add: {
541
+ usage: "wachiman memory add --kind convention|exception --scope <glob> --rule <text> --why <text> [options]",
542
+ summary: "Record a drafted entry as a candidate, with its first piece of evidence. This is how a coding agent hands over the entry it drafted from the code and the owner's intent; no model is called here. The same entry again (same kind, scope, rule, why and holds-while) only adds evidence.",
543
+ options: [
544
+ ["--kind <kind>", "convention or exception"],
545
+ ["--scope <glob>", "The paths it applies to; several globs separated by commas"],
546
+ ["--rule <text>", "What to do, or what not to report"],
547
+ ["--why <text>", "The reason the owner gave"],
548
+ ["--holds-while <paths>", "The paths a fact the reason depends on lives in; for an exception whose reason is a fact about the code"],
549
+ ["--title <text>", "A short heading. Default: the start of the rule"],
550
+ ["--file <path>", "A JSON object with the same fields (kind, scope, rule, why, holdsWhile, title); flags override it"],
551
+ ["--source <source>", "instruction (default), judged or fixed. judged and fixed need --finding"],
552
+ ["--finding <id>", "A finding id from the local loop history. judged needs a `wrong` verdict with a reason; fixed needs the loop to have marked it probably fixed"],
553
+ ["--pr <n>", "The pull request the evidence came from. Default: the current branch"],
554
+ ["--branch <name>", "The branch the evidence came from, for an instruction"],
555
+ ["--agent", "A coding agent wrote the instruction or reply on the owner's behalf; recorded in the evidence"],
556
+ REPO_DIR,
557
+ ],
558
+ exit: MEMORY_EXIT,
559
+ examples: ['wachiman memory add --kind convention --scope "src/**" --rule "Prefer named exports." --why "Renames then show in every importer." --pr 709'],
560
+ docs: MEMORY_DOCS,
561
+ },
562
+ show: {
563
+ usage: "wachiman memory show <id> [--repo-dir <dir>]",
564
+ summary: "Print the exact entry text of a candidate: what `propose` writes, byte for byte. Show it to the owner and propose only what they approved.",
565
+ options: [REPO_DIR],
566
+ exit: MEMORY_EXIT,
567
+ examples: ["wachiman memory show 4c1e9a2"],
568
+ docs: MEMORY_DOCS,
569
+ },
570
+ propose: {
571
+ usage: "wachiman memory propose <id> [--personal | --team] [--repo-dir <dir>]\nwachiman memory propose --from-personal [<id>...] [--repo-dir <dir>]",
572
+ summary: "Add the entry to the branch wachiman/memory on origin as one commit, and open the draft pull request `chore(wachiman): memory` if none is open. It builds the commit in a temporary worktree, so your branch, index and uncommitted changes are untouched; it never force-pushes and writes only under .wachiman/memory/. It uses your own git credentials and `gh`. It runs none of your git hooks in that worktree. A pull request closed without merging stops it. It says `recorded` only after the push succeeded. `--personal` instead writes the entry to your personal memory for this repository (under the Wachiman home, keyed by the URL of origin) with no commit and no push; an explicit `--personal` also makes no network call, while a plain `propose` may fetch from origin to learn whether the team has memory; only your laptop reviews of that repository load it. In a repository whose default branch has no .wachiman/memory/, a first `propose` without a flag asks which of the two you want (or exits 1 when it cannot ask): use `--personal` or `--team` to choose. `--from-personal` sends your personal entries (all, or the ids given) to the team's pull request.",
573
+ options: [["--personal", "Write to your personal memory instead of the team's branch"], ["--team", "Propose to the team's branch without the first-time question"], ["--from-personal", "Send personal entries (all, or the ids given) to the team's memory pull request"], REPO_DIR],
574
+ exit: MEMORY_EXIT,
575
+ examples: ["wachiman memory propose 4c1e9a2"],
576
+ docs: MEMORY_DOCS,
577
+ },
578
+ remember: {
579
+ usage: "wachiman memory remember <pr> [--repo-dir <dir>]",
580
+ summary: "The write job of memory in GitHub Actions: it records the entry an operator approved with `/wachiman remember <id>` in a thread. It reads the comment from REQUEST, WACHIMAN_COMMENT_AUTHOR and WACHIMAN_COMMENT_IN_REPLY_TO, finds the reply of Wachiman in that thread that showed the id, and writes the text shown with the same one commit on wachiman/memory and draft pull request as `propose`. It writes nothing unless the commenter is WACHIMAN_OPERATOR and the digest of the text shown is the id. It replies in the thread and never resolves it. Needs GH_TOKEN and GITHUB_REPOSITORY, and a token with contents: write and pull-requests: write; opening the pull request also needs the repository setting \"Allow GitHub Actions to create and approve pull requests\". No model is called.",
581
+ options: [REPO_DIR],
582
+ exit: MEMORY_EXIT,
583
+ examples: ["wachiman memory remember 709"],
584
+ docs: MEMORY_DOCS,
585
+ },
586
+ },
587
+ };
588
+
475
589
  /** The commands a GitHub Actions run uses; they are not in the root help. */
476
590
  export const CI_COMMANDS = ["review", "comment", "threads", "reset-confidence"] as const;
477
591
 
478
592
  const PAGES: Readonly<Record<string, Page>> = {
479
593
  local: localPage, loop: loopPage, ask: askPage,
480
594
  history: historyPage, status: statusPage, dashboard: dashboardPage, ledger: ledgerPageWithSubs,
481
- setup: setupPage, init: initPage, doctor: doctorPage, profile: profilePage, project: projectPage, skills: skillsPage, upgrade: upgradePage, "pr-template": prTemplatePageRoot,
595
+ setup: setupPage, init: initPage, doctor: doctorPage, profile: profilePage, project: projectPage, skills: skillsPage, upgrade: upgradePage, "pr-template": prTemplatePageRoot, memory: memoryPage,
482
596
  review: reviewPage, comment: commentPage, threads: threadsPage, "reset-confidence": resetConfidencePage,
483
597
  };
484
598
 
@@ -559,6 +673,7 @@ export function rootHelp(paint: Paint = plain): string {
559
673
  ["project", "Show or remove this repository's binding"],
560
674
  ["skills", "Install or remove the agent skills"],
561
675
  ["pr-template", "Install and check the PR description template"],
676
+ ["memory", "Check and propose repository memory (.wachiman/memory)"],
562
677
  ["upgrade", "Update the CLI and the workflow pin in this repository"],
563
678
  ]),
564
679
  "",
@@ -6,7 +6,7 @@
6
6
  import { UsageError } from "../config";
7
7
  import { SEVERITY, TOPIC } from "../engine";
8
8
  import { location, sha7 } from "../sinks/common";
9
- import { replay, type Replayed, type ReplayedFinding } from "./match";
9
+ import { countVerdicts, replay, type Replayed, type ReplayedFinding } from "./match";
10
10
  import { wachimanHome } from "../accounts/config";
11
11
  import { appendVerdict, forget, historyRoot, listKeys, readRuns, readVerdicts, repositoryKey } from "./store";
12
12
  import { VERDICT_WORDS, type HistoryRun, type VerdictWord } from "./types";
@@ -14,7 +14,7 @@ import { VERDICT_WORDS, type HistoryRun, type VerdictWord } from "./types";
14
14
  export const HISTORY_STATE_FORMAT = "wachiman.history-state/1";
15
15
 
16
16
  export const historyUsage = `wachiman history [--repo-dir <dir>] [--since <n>d] [--all-repos] [--json]
17
- [--verdict <id> correct|partial|wrong [--reason <text>]]
17
+ [--verdict <id> correct|partial|wrong|intentional|not-important [--reason <text>]]
18
18
  [--forget [--all]]`;
19
19
 
20
20
  export interface HistoryArgs {
@@ -104,7 +104,8 @@ function table(l: Listed) {
104
104
  lines.push(` ${pad(r.status, ws)} ${pad(r.first, wf)} ${pad(r.last, wl)} ${pad(r.runs, wr)} ${pad(r.id, wi)} ${r.text}${r.verdict}`);
105
105
  }
106
106
  const c = l.state.counts;
107
- lines.push(`verdicts: ${c.correct} correct, ${c.partial} partial, ${c.wrong} wrong, ${c.unjudged} unjudged`);
107
+ const extra = [c.intentional ? `${c.intentional} intentional` : "", c.notImportant ? `${c.notImportant} not-important` : ""].filter(Boolean);
108
+ lines.push(`verdicts: ${[`${c.correct} correct`, `${c.partial} partial`, `${c.wrong} wrong`, `${c.unjudged} unjudged`, ...extra].join(", ")}`);
108
109
  return lines.join("\n");
109
110
  }
110
111
 
@@ -142,8 +143,7 @@ export function runHistory(
142
143
  const state = replay(runs, readVerdicts(root, key));
143
144
  if (cutoff !== undefined) {
144
145
  state.findings = state.findings.filter((f) => Date.parse(f.lastSeenAt) >= cutoff);
145
- state.counts = { correct: 0, partial: 0, wrong: 0, unjudged: 0 };
146
- for (const f of state.findings) state.counts[f.verdict?.verdict ?? "unjudged"]++;
146
+ state.counts = countVerdicts(state.findings);
147
147
  }
148
148
  listed.push({ key, runs, state });
149
149
  }
@@ -133,9 +133,31 @@ export interface ReplayedFinding extends TrackedFinding {
133
133
  verdict?: VerdictLine;
134
134
  }
135
135
 
136
+ /** `intentional` and `notImportant` appear only once a verdict of that word exists, so older output is unchanged. */
137
+ export interface VerdictCounts {
138
+ correct: number;
139
+ partial: number;
140
+ wrong: number;
141
+ unjudged: number;
142
+ intentional?: number;
143
+ notImportant?: number;
144
+ }
145
+
136
146
  export interface Replayed {
137
147
  findings: ReplayedFinding[];
138
- counts: { correct: number; partial: number; wrong: number; unjudged: number };
148
+ counts: VerdictCounts;
149
+ }
150
+
151
+ const COUNT_KEY = { correct: "correct", partial: "partial", wrong: "wrong", intentional: "intentional", "not-important": "notImportant" } as const;
152
+
153
+ /** Counts the findings' verdicts; the same rule for the whole listing and for a `--since` slice. */
154
+ export function countVerdicts(findings: ReplayedFinding[]): VerdictCounts {
155
+ const counts: VerdictCounts = { correct: 0, partial: 0, wrong: 0, unjudged: 0 };
156
+ for (const f of findings) {
157
+ const key = f.verdict ? COUNT_KEY[f.verdict.verdict] : "unjudged";
158
+ counts[key] = (counts[key] ?? 0) + 1;
159
+ }
160
+ return counts;
139
161
  }
140
162
 
141
163
  /** The state after `runs` (in `savedAt` order) and the developer's verdicts. */
@@ -175,7 +197,5 @@ export function replay(runs: HistoryRun[], verdicts: Map<string, VerdictLine>):
175
197
  }
176
198
  }
177
199
  const findings = [...state.values()].map((t): ReplayedFinding => ({ ...t, verdict: verdicts.get(t.firstId) }));
178
- const counts = { correct: 0, partial: 0, wrong: 0, unjudged: 0 };
179
- for (const f of findings) counts[f.verdict?.verdict ?? "unjudged"]++;
180
- return { findings, counts };
200
+ return { findings, counts: countVerdicts(findings) };
181
201
  }
@@ -69,7 +69,7 @@ const GIT_TIMEOUT_MS = 30_000;
69
69
  * can carry a credential through the fallback. The host is lowercased; no `.git`, no trailing `/`.
70
70
  * `parsed` is false when the stripped text is not a URL: it still keys the history, but is not stored.
71
71
  */
72
- function normaliseRemote(raw: string): { text: string; parsed: boolean } {
72
+ export function normaliseRemote(raw: string): { text: string; parsed: boolean } {
73
73
  let url = raw.trim();
74
74
  const scheme = url.match(/^([a-z][a-z0-9+.-]*:\/\/)[^/?#]*@/i);
75
75
  if (scheme) url = scheme[1] + url.slice(scheme[0].length);
@@ -58,8 +58,13 @@ export interface HistoryRun {
58
58
  unknownIds: string[];
59
59
  }
60
60
 
61
- export type VerdictWord = "correct" | "partial" | "wrong";
62
- export const VERDICT_WORDS: readonly VerdictWord[] = ["correct", "partial", "wrong"];
61
+ /**
62
+ * `intentional` (the code is meant to be that way) and `not-important` (right, but not worth
63
+ * acting on) were added for the memory report (layer 7). A verdicts file written before them has
64
+ * only the first three words and reads as before.
65
+ */
66
+ export type VerdictWord = "correct" | "partial" | "wrong" | "intentional" | "not-important";
67
+ export const VERDICT_WORDS: readonly VerdictWord[] = ["correct", "partial", "wrong", "intentional", "not-important"];
63
68
 
64
69
  export interface VerdictLine {
65
70
  at: string;
@@ -0,0 +1,135 @@
1
+ /**
2
+ * The pointer `wachiman init` writes into the repository's agent instruction file (decision 13 of
3
+ * the repository memory design). It is two or three lines between stable markers: a re-run replaces
4
+ * the block between them and never adds a second one, and text outside the markers is kept byte for
5
+ * byte. The file is `AGENTS.md` when it exists, else `CLAUDE.md` when it exists, else a new
6
+ * `AGENTS.md`. The skill itself is not in the repository; `wachiman skills install` puts it on the
7
+ * developer's machine.
8
+ */
9
+ import { lstatSync, readFileSync, realpathSync } from "node:fs";
10
+ import { relative, sep } from "node:path";
11
+ import { UsageError } from "../config";
12
+ import { inspectTarget, type TargetState } from "./write";
13
+
14
+ export const POINTER_BEGIN = "<!-- wachiman:begin -->";
15
+ export const POINTER_END = "<!-- wachiman:end -->";
16
+
17
+ const POINTER_TEXT = [
18
+ "Reviews in this repository are run with the `wachiman-loop` skill, which `wachiman skills install` puts in place.",
19
+ "Repository memory lives in `.wachiman/memory/`; the `wachiman-loop` skill says how to change it.",
20
+ ];
21
+
22
+ /** The block as the file holds it, with a final newline. */
23
+ export const pointerBlock = () => [POINTER_BEGIN, ...POINTER_TEXT, POINTER_END].join("\n") + "\n";
24
+
25
+ /**
26
+ * `file` is the name shown to the person; `writePath` is where the write lands, relative to the
27
+ * repository root (the link's target when `file` is a link that stays inside the repository).
28
+ * `skip` is a pointer that cannot be written, with the reason; it never fails `init`.
29
+ */
30
+ export type PointerPlan =
31
+ | { action: "create"; file: string; writePath: string; content: string; inspected: TargetState }
32
+ | { action: "append"; file: string; writePath: string; content: string; inspected: TargetState }
33
+ | { action: "replace"; file: string; writePath: string; content: string; inspected: TargetState }
34
+ | { action: "same"; file: string }
35
+ | { action: "skip"; file: string; reason: string };
36
+
37
+ const stripCr = (line: string) => line.replace(/\r$/, "");
38
+
39
+ /**
40
+ * The file with the pointer block in its final form. Markers must each sit alone on a line, and
41
+ * there must be one pair in order; anything else is refused, because a guessed edit could delete
42
+ * the person's own text or leave two blocks.
43
+ */
44
+ export function withPointer(current: string, file: string): string {
45
+ const lines = current.split("\n");
46
+ // A file that uses CRLF gets the block with CRLF, so its endings stay uniform.
47
+ const crlf = current.includes("\r\n");
48
+ const eol = crlf ? "\r\n" : "\n";
49
+ const block = pointerBlock().trimEnd().split("\n").join(eol) + eol;
50
+ const begins = lines.flatMap((line, i) => (stripCr(line) === POINTER_BEGIN ? [i] : []));
51
+ const ends = lines.flatMap((line, i) => (stripCr(line) === POINTER_END ? [i] : []));
52
+ if (begins.length === 0 && ends.length === 0) {
53
+ if (current.includes(POINTER_BEGIN) || current.includes(POINTER_END)) {
54
+ throw new UsageError(`${file} has a wachiman marker that is not alone on its line; init will not guess where the pointer goes. Put each marker on its own line, or remove it, and run init again.`);
55
+ }
56
+ if (current === "") return block;
57
+ return `${current}${current.endsWith("\n") ? eol : eol + eol}${block}`;
58
+ }
59
+ if (begins.length !== 1 || ends.length !== 1 || ends[0] < begins[0]) {
60
+ throw new UsageError(`${file} has ${begins.length} wachiman begin marker(s) and ${ends.length} end marker(s); init needs one pair, begin first. Keep one pair, or remove the block by hand, and run init again.`);
61
+ }
62
+ const before = lines.slice(0, begins[0]);
63
+ const after = lines.slice(ends[0] + 1);
64
+ const endHadCr = lines[ends[0]].endsWith("\r");
65
+ const inner = pointerBlock().trimEnd().split("\n").map((line, i, all) => (i < all.length - 1 ? line + (crlf ? "\r" : "") : line + (endHadCr ? "\r" : "")));
66
+ return [...before, ...inner, ...after].join("\n");
67
+ }
68
+
69
+ /** A dry run does not print the lines when the file is skipped, so the hint carries them. */
70
+ export const manualHint = () => `Add this block by hand, or skip it with --no-agent-pointer:\n${pointerBlock().trimEnd()}`;
71
+
72
+ /**
73
+ * Looks at the file that would hold the pointer, without writing. It never throws: a link out of
74
+ * the repository, a malformed block or any other problem is a `skip` with the reason. A link that
75
+ * stays inside the repository is written through to its target.
76
+ */
77
+ export function planPointer(repoDir: string): PointerPlan {
78
+ let file = "AGENTS.md";
79
+ try {
80
+ const exists = (name: string) => {
81
+ try {
82
+ lstatSync(`${repoDir}${sep}${name}`);
83
+ return true;
84
+ } catch {
85
+ return false;
86
+ }
87
+ };
88
+ file = ["AGENTS.md", "CLAUDE.md"].find(exists) ?? "AGENTS.md";
89
+ let writePath = file;
90
+ if (exists(file) && lstatSync(`${repoDir}${sep}${file}`).isSymbolicLink()) {
91
+ const root = realpathSync(repoDir);
92
+ let real: string;
93
+ try {
94
+ real = realpathSync(`${root}${sep}${file}`);
95
+ } catch {
96
+ return { action: "skip", file, reason: `${file} is a symbolic link that does not resolve; init leaves it alone. ${manualHint()}` };
97
+ }
98
+ if (real !== root && !real.startsWith(root + sep)) {
99
+ return { action: "skip", file, reason: `${file} is a symbolic link to ${real}, outside the repository; init does not write there. ${manualHint()}` };
100
+ }
101
+ writePath = relative(root, real).split(sep).join("/");
102
+ }
103
+ const inspected = inspectTarget(repoDir, writePath);
104
+ if (!inspected.exists) return { action: "create", file, writePath, content: withPointer("", file), inspected };
105
+ let current: string;
106
+ try {
107
+ // Strict decoding: a file in another encoding must not be rewritten with replacement characters.
108
+ current = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(readFileSync(inspected.target));
109
+ } catch {
110
+ return { action: "skip", file, reason: `${file} is not valid UTF-8; init does not rewrite it. ${manualHint()}` };
111
+ }
112
+ const content = withPointer(current, file);
113
+ if (content === current) return { action: "same", file };
114
+ return { action: current.includes(POINTER_BEGIN) ? "replace" : "append", file, writePath, content, inspected };
115
+ } catch (error) {
116
+ return { action: "skip", file, reason: `${error instanceof Error ? error.message : String(error)} ${manualHint()}` };
117
+ }
118
+ }
119
+
120
+ /** What a dry run says the plan would do, on stderr. */
121
+ export function describePointer(plan: PointerPlan): string[] {
122
+ const block = pointerBlock().replace(/\n$/, "").split("\n");
123
+ switch (plan.action) {
124
+ case "create":
125
+ return [`would create ${plan.file} with the wachiman pointer:`, ...block.map((l) => ` ${l}`)];
126
+ case "append":
127
+ return [`would add the wachiman pointer to the end of ${plan.file}`];
128
+ case "replace":
129
+ return [`would replace the wachiman pointer in ${plan.file}`];
130
+ case "same":
131
+ return [`${plan.file} already has the wachiman pointer; nothing to write.`];
132
+ case "skip":
133
+ return [`the wachiman pointer would not be written: ${plan.reason}`];
134
+ }
135
+ }
package/src/init/args.ts CHANGED
@@ -3,14 +3,14 @@ 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] [--project-kind monorepo|single] [--operator <login>] [--version <tag>] [--path <file>] [--force] [--dry-run] [--pr-template | --no-pr-template] [--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] [--no-agent-pointer] [--yes] [--json] [--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", "--project-kind", "--operator", "--version", "--path"], booleans: ["--force", "--dry-run", "--yes", "--pr-template", "--no-pr-template"] },
13
+ { values: ["--mode", "--project-kind", "--operator", "--version", "--path"], booleans: ["--force", "--dry-run", "--yes", "--json", "--pr-template", "--no-pr-template", "--no-agent-pointer"] },
14
14
  "init",
15
15
  );
16
16
  if (positionals.length > 0) throw new UsageError(`init takes no argument "${positionals[0]}".`);
@@ -24,7 +24,9 @@ export function parseInitFlags(argv: string[], repoDir: string): RawInitFlags {
24
24
  ...(booleans["--force"] ? { force: true } : {}),
25
25
  ...(booleans["--dry-run"] ? { dryRun: true } : {}),
26
26
  ...(booleans["--yes"] ? { yes: true } : {}),
27
+ ...(booleans["--json"] ? { json: true } : {}),
27
28
  ...(booleans["--pr-template"] ? { prTemplate: true } : booleans["--no-pr-template"] ? { prTemplate: false } : {}),
29
+ ...(booleans["--no-agent-pointer"] ? { agentPointer: false } : {}),
28
30
  repoDir,
29
31
  };
30
32
  }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * The `wachiman.init/1` document that `wachiman init --json` prints on stdout: one JSON object, for
3
+ * a result and for a failure alike, so a program (a coding agent) never has to parse human text.
4
+ * Every human status line goes to stderr in that mode. See docs/specs/2026-11-18-agent-operated-setup-design.md.
5
+ */
6
+ import { quoteArgument } from "../wizard/command";
7
+ import type { InitMode } from "./options";
8
+
9
+ export const INIT_FORMAT = "wachiman.init/1";
10
+
11
+ export type FileAction = "created" | "replaced" | "unchanged" | "would-create" | "would-replace" | "refused";
12
+
13
+ export interface InitFile {
14
+ /** Relative to the repository top level. */
15
+ path: string;
16
+ action: FileAction;
17
+ /** Where the earlier file was kept, relative to the repository when it is inside it. */
18
+ backup?: string;
19
+ /** The rendered workflow, only in a dry run (stdout stays one document). */
20
+ content?: string;
21
+ }
22
+
23
+ /** What `runInit` records as it works; `buildDocument` turns it into the file list. */
24
+ export interface InitReport {
25
+ workflow?: InitFile;
26
+ settings?: InitFile;
27
+ template?: InitFile[];
28
+ agentPointer?: InitFile;
29
+ }
30
+
31
+ /** `init` alone never makes a side ready: binding is `setup`, and GitHub needs a secret and a merge. */
32
+ export type Readiness = "pending" | "not-used";
33
+
34
+ export interface InitDocument {
35
+ format: typeof INIT_FORMAT;
36
+ ok: boolean;
37
+ mode: InitMode | null;
38
+ dryRun: boolean;
39
+ repoDir: string;
40
+ files: InitFile[];
41
+ local: { status: Readiness; pending: string[] };
42
+ github: { status: Readiness; pending: string[] };
43
+ error: { code: "usage" | "failed"; message: string } | null;
44
+ }
45
+
46
+ const filesOf = (report: InitReport): InitFile[] => [report.workflow, report.settings, ...(report.template ?? []), report.agentPointer].filter((f): f is InitFile => f !== undefined);
47
+
48
+ /** `init` never binds without a terminal and never touches GitHub, so a mode that includes either leaves it pending. */
49
+ export function buildDocument(p: { mode: InitMode; dryRun: boolean; repoDir: string; report: InitReport }): InitDocument {
50
+ const { mode } = p;
51
+ return {
52
+ format: INIT_FORMAT,
53
+ ok: true,
54
+ mode,
55
+ dryRun: p.dryRun,
56
+ repoDir: p.repoDir,
57
+ files: filesOf(p.report),
58
+ local:
59
+ mode === "github"
60
+ ? { status: "not-used", pending: [] }
61
+ : { status: "pending", pending: [`wachiman setup --profile <name> --yes --repo-dir ${quoteArgument(p.repoDir, "posix")}`] },
62
+ github: mode === "local" ? { status: "not-used", pending: [] } : { status: "pending", pending: ["add ANTHROPIC_API_KEY secret", "commit and open a PR"] },
63
+ error: null,
64
+ };
65
+ }
66
+
67
+ /** A failure: `files` holds what was already written or refused, and the other fields say what is known. */
68
+ export function failureDocument(p: { mode: InitMode | null; dryRun: boolean; repoDir: string; report: InitReport; code: "usage" | "failed"; message: string }): InitDocument {
69
+ return {
70
+ format: INIT_FORMAT,
71
+ ok: false,
72
+ mode: p.mode,
73
+ dryRun: p.dryRun,
74
+ repoDir: p.repoDir,
75
+ files: filesOf(p.report),
76
+ local: { status: "not-used", pending: [] },
77
+ github: { status: "not-used", pending: [] },
78
+ error: { code: p.code, message: p.message },
79
+ };
80
+ }
81
+
82
+ export const printDocument = (stdout: (text: string) => void, doc: InitDocument) => stdout(`${JSON.stringify(doc, null, 2)}\n`);