wachiman 1.15.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.
- package/README.md +13 -0
- package/package.json +1 -1
- package/skills/wachiman-loop/SKILL.md +43 -0
- package/src/accounts/commands.ts +3 -2
- package/src/accounts/confirm.ts +1 -1
- package/src/accounts/profile-list.ts +24 -0
- package/src/cli.ts +91 -26
- package/src/config.ts +40 -8
- package/src/connectors/local-git.ts +128 -0
- package/src/connectors/working-tree.ts +23 -1
- package/src/doctor/checks.ts +106 -1
- package/src/doctor/run.ts +9 -1
- package/src/engine.ts +1126 -222
- package/src/formats.ts +44 -3
- package/src/help.ts +204 -7
- package/src/history/command.ts +5 -5
- package/src/history/match.ts +24 -4
- package/src/history/store.ts +1 -1
- package/src/history/types.ts +7 -2
- package/src/init/agents.ts +135 -0
- package/src/init/args.ts +7 -2
- package/src/init/github-login.ts +13 -0
- package/src/init/json.ts +82 -0
- package/src/init/options.ts +42 -4
- package/src/init/prompt.ts +46 -15
- package/src/init/render.ts +3 -1
- package/src/init/run.ts +362 -28
- package/src/init/settings.ts +137 -0
- package/src/init/write.ts +16 -102
- package/src/json-schema.ts +8 -0
- package/src/ledger.ts +2 -2
- package/src/local-ask.ts +5 -4
- package/src/local.ts +90 -17
- package/src/loop/command.ts +29 -7
- package/src/memory/candidates.ts +425 -0
- package/src/memory/capture.ts +298 -0
- package/src/memory/command.ts +195 -0
- package/src/memory/entries.ts +213 -0
- package/src/memory/hygiene.ts +291 -0
- package/src/memory/inspect.ts +74 -0
- package/src/memory/load.ts +283 -0
- package/src/memory/mute.ts +259 -0
- package/src/memory/personal.ts +253 -0
- package/src/memory/proposal.ts +92 -0
- package/src/memory/propose.ts +414 -0
- package/src/memory/remember.ts +187 -0
- package/src/memory/report.ts +250 -0
- package/src/memory/settings.ts +20 -0
- package/src/pr-template/adopt.ts +434 -0
- package/src/pr-template/catalog.ts +429 -0
- package/src/pr-template/check-run.ts +328 -0
- package/src/pr-template/check.ts +338 -0
- package/src/pr-template/describe.ts +368 -0
- package/src/pr-template/format.ts +399 -0
- package/src/pr-template/gh.ts +159 -0
- package/src/pr-template/install.ts +311 -0
- package/src/pr-template/legacy-guides.ts +50 -0
- package/src/pr-template/pr-risk.ts +426 -0
- package/src/pr-template/render.ts +302 -0
- package/src/pr-template/resolve.ts +65 -0
- package/src/pr-template/run.ts +88 -0
- package/src/pr-template/strip.ts +171 -0
- package/src/pr-template/write.ts +139 -0
- package/src/precision.ts +10 -2
- package/src/priority.ts +106 -0
- package/src/providers/claude-code.ts +7 -8
- package/src/providers/codex.ts +4 -4
- package/src/providers/spawn.ts +95 -0
- package/src/providers/types.ts +5 -2
- package/src/repo-settings.ts +322 -0
- package/src/risk.ts +38 -9
- package/src/setup/prompt.ts +49 -33
- package/src/setup/run.ts +31 -6
- package/src/sinks/common.ts +22 -9
- package/src/sinks/markdown.ts +6 -2
- package/src/sinks/terminal.ts +6 -2
- package/src/store/figures.ts +5 -4
- package/src/store/html.ts +1 -1
- package/src/upgrade/command.ts +286 -0
- package/src/upgrade/pin.ts +112 -0
- package/src/verify.ts +20 -2
- package/src/wizard/mascot.ts +56 -51
- package/src/wizard/prompt-fancy.ts +10 -2
- package/src/wizard/prompt.ts +17 -4
- package/src/wizard/ui.ts +2 -0
- package/templates/pr/sections.json +163 -0
- 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
|
|
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
|
@@ -15,7 +15,11 @@ import { localUsage } from "./local";
|
|
|
15
15
|
import { loopUsage } from "./loop/command";
|
|
16
16
|
import { profileUsage, projectUsage, setupUsage } from "./accounts/commands";
|
|
17
17
|
import { skillsUsage } from "./skills/install";
|
|
18
|
+
import { checkUsage, riskUsage, stripUsage } from "./pr-template/check-run";
|
|
19
|
+
import { formatUsage } from "./pr-template/format";
|
|
20
|
+
import { installUsage, showUsage, statusUsage as prTemplateStatusUsage } from "./pr-template/install";
|
|
18
21
|
import { statusUsage } from "./status/command";
|
|
22
|
+
import { upgradeUsage } from "./upgrade/command";
|
|
19
23
|
|
|
20
24
|
export const DOCS = "https://github.com/niway-dev/wachiman/blob/main/docs";
|
|
21
25
|
|
|
@@ -61,6 +65,7 @@ const GH_EXIT: readonly Row[] = [
|
|
|
61
65
|
const GH_ENV: readonly Row[] = [
|
|
62
66
|
["GH_TOKEN", "Token for gh. Never given to the agent"],
|
|
63
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"],
|
|
64
69
|
["ANTHROPIC_API_KEY", "The claude-code provider needs this or CLAUDE_CODE_OAUTH_TOKEN (not in a dry run)"],
|
|
65
70
|
["CLAUDE_CODE_OAUTH_TOKEN", "A Claude subscription token (`claude setup-token`); when set it wins and the API key never reaches the agent"],
|
|
66
71
|
OTHER_ENV,
|
|
@@ -131,6 +136,7 @@ const localPage: Page = {
|
|
|
131
136
|
["--verify | --no-verify", "One more call tries to refute each finding above info. Default: follows WACHIMAN_VERIFY (off)"],
|
|
132
137
|
["--result-version 1|2", "With --format json only. Default: 1 for committed changes, 2 for --working-tree"],
|
|
133
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"],
|
|
134
140
|
REPO_DIR,
|
|
135
141
|
],
|
|
136
142
|
env: [
|
|
@@ -207,7 +213,7 @@ const historyPage: Page = {
|
|
|
207
213
|
["--since <n>d", "Only findings seen in the last n days"],
|
|
208
214
|
["--all-repos", "Every repository in the history, not just this clone's"],
|
|
209
215
|
["--json", "The replayed state as wachiman.history-state/1"],
|
|
210
|
-
["--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)"],
|
|
211
217
|
["--reason <text>", "With --verdict: why"],
|
|
212
218
|
["--forget [--all]", "Delete this repository's history, or all of it with --all. Takes no --all-repos, --json or --since"],
|
|
213
219
|
REPO_DIR,
|
|
@@ -291,20 +297,25 @@ const setupPage: Page = {
|
|
|
291
297
|
|
|
292
298
|
const initPage: Page = {
|
|
293
299
|
usage: initUsage,
|
|
294
|
-
summary: "Write the GitHub Actions caller workflow (.github/workflows/wachiman-review.yml), or, with --mode local, write
|
|
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.",
|
|
295
301
|
options: [
|
|
296
302
|
["--mode github|local|both", "What to set up. Required without a terminal"],
|
|
297
303
|
["--operator <login>", "The GitHub login allowed to command the reviewer. Required for github and both without a terminal"],
|
|
298
304
|
["--version <tag>", "vX.Y.Z or a 40-character commit SHA written after review.yml@. Default: the release bundled in this build"],
|
|
299
305
|
["--path <file>", "Default: .github/workflows/wachiman-review.yml; a .yml or .yaml file directly in .github/workflows/"],
|
|
300
|
-
["--
|
|
301
|
-
["--
|
|
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"],
|
|
307
|
+
["--force", "Replace an existing workflow after copying it to <file>.bak-<timestamp>; with --project-kind, also change a different kind"],
|
|
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)"],
|
|
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"],
|
|
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"],
|
|
302
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"],
|
|
303
314
|
REPO_DIR,
|
|
304
315
|
],
|
|
305
316
|
env: [HOME_ENV, ["CI", "true or 1 turns the prompts off"], ["NO_COLOR", "Turns styling off"]],
|
|
306
|
-
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"]],
|
|
307
|
-
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"],
|
|
308
319
|
docs: `${DOCS}/cli.md#init`,
|
|
309
320
|
};
|
|
310
321
|
|
|
@@ -324,6 +335,21 @@ const doctorPage: Page = {
|
|
|
324
335
|
docs: `${DOCS}/cli.md#setup-doctor-profile-and-project`,
|
|
325
336
|
};
|
|
326
337
|
|
|
338
|
+
const upgradePage: Page = {
|
|
339
|
+
usage: upgradeUsage,
|
|
340
|
+
summary: "Update the CLI to the latest release, then move the Wachiman workflow pin in this repository to it. Rewrites the files and prints the git commands; it never commits. A clone or a wachiman-dev build is not upgraded.",
|
|
341
|
+
options: [
|
|
342
|
+
["--check", "Print the installed and the latest version and change nothing"],
|
|
343
|
+
["--repo-only", "Rewrite the pins to the installed version (or --to) and leave the CLI alone"],
|
|
344
|
+
["--to <version>", "Install this release (v1.2.3) and pin it. It never downgrades the CLI: when the CLI is already on that version or newer, nothing is installed and the pins move. If the install fails the pins stay and the exit is 1; with --repo-only no install is attempted"],
|
|
345
|
+
REPO_DIR,
|
|
346
|
+
],
|
|
347
|
+
env: [HOME_ENV],
|
|
348
|
+
exit: [["0", "Done, nothing to do, or the CLI is a clone or a dev build and was not upgraded"], ["1", "The package manager failed, a version could not be read, or a workflow file could not be read or written"], ["2", "Usage error"]],
|
|
349
|
+
examples: ["wachiman upgrade --check", "wachiman upgrade", "wachiman upgrade --repo-only"],
|
|
350
|
+
docs: `${DOCS}/cli.md#upgrade`,
|
|
351
|
+
};
|
|
352
|
+
|
|
327
353
|
const ACCOUNT_ENV: readonly Row[] = [HOME_ENV, ["CI", "true or 1 means no terminal: confirmations need --yes"]];
|
|
328
354
|
const accountPage = (usage: string, summary: string, options: readonly Row[], examples: string[]): Page => ({
|
|
329
355
|
usage, summary, options, env: ACCOUNT_ENV, exit: CONFIRMATION_EXIT, examples, docs: `${DOCS}/cli.md#setup-doctor-profile-and-project`,
|
|
@@ -392,13 +418,181 @@ const skillsPage: Page = {
|
|
|
392
418
|
},
|
|
393
419
|
};
|
|
394
420
|
|
|
421
|
+
const PR_TEMPLATE_DOCS = `${DOCS}/pr-template.md`;
|
|
422
|
+
const PR_TEMPLATE_EXIT: readonly Row[] = [
|
|
423
|
+
["0", "Done, the description passes, or the template is current"],
|
|
424
|
+
["1", "check found a problem; status is anything but current; a git commit made by install --commit failed"],
|
|
425
|
+
["2", "Usage or configuration error: an unknown flag or section, an invalid .github/pr-template.json, a refused install, a missing tool"],
|
|
426
|
+
];
|
|
427
|
+
const prTemplatePage = (usage: string, summary: string, options: readonly Row[], examples: string[]): Page => ({
|
|
428
|
+
usage, summary, options, exit: PR_TEMPLATE_EXIT, examples, docs: PR_TEMPLATE_DOCS,
|
|
429
|
+
});
|
|
430
|
+
|
|
431
|
+
const prTemplatePageRoot: Page = {
|
|
432
|
+
usage: "wachiman pr-template <show|install|status|check|format|risk|strip> [options]",
|
|
433
|
+
summary: "Install the PR description template, report its state, and check, reorder and strip a description. The template is generated from a section catalog plus an optional .github/pr-template.json; no model is called. Run `wachiman pr-template <subcommand> --help` for one of them.",
|
|
434
|
+
options: [REPO_DIR],
|
|
435
|
+
exit: PR_TEMPLATE_EXIT,
|
|
436
|
+
examples: ["wachiman pr-template install", "wachiman pr-template check --pr 42"],
|
|
437
|
+
docs: PR_TEMPLATE_DOCS,
|
|
438
|
+
subs: {
|
|
439
|
+
show: prTemplatePage(showUsage, "Print the template this repository would get: the default, or the one .github/pr-template.json describes. Writes nothing.", [
|
|
440
|
+
["--from <json>", "Preview a definition from this file instead of .github/pr-template.json"],
|
|
441
|
+
REPO_DIR,
|
|
442
|
+
], ["wachiman pr-template show", "wachiman pr-template show --from ./pr-template.json"]),
|
|
443
|
+
install: prTemplatePage(installUsage, "Write .github/pull_request_template.md, generated from the catalog and .github/pr-template.json. Files only: it never pushes. An existing template without the Wachiman stamp is adopted and backed up; a hand-edited one is refused.", [
|
|
444
|
+
["--from <json>", "Copy this definition into .github/pr-template.json before generating"],
|
|
445
|
+
["--force", "Replace a hand-edited template, or an existing, different .github/pr-template.json, after a backup in the git directory (wachiman/backups)"],
|
|
446
|
+
["--commit", "Make one commit with only the files written; hooks run, nothing is pushed"],
|
|
447
|
+
REPO_DIR,
|
|
448
|
+
], ["wachiman pr-template install", "wachiman pr-template install --commit"]),
|
|
449
|
+
status: prTemplatePage(prTemplateStatusUsage, "Print the state of the installed template: missing, current, outdated, edited by hand, unmanaged or invalid. Exits 0 only for current.", [
|
|
450
|
+
["--json", "Print {state, version, installedVersion}"],
|
|
451
|
+
REPO_DIR,
|
|
452
|
+
], ["wachiman pr-template status", "wachiman pr-template status --json"]),
|
|
453
|
+
check: prTemplatePage(checkUsage, "Check a PR description against the template: headings and their order, the status rows, Needs you, the Risk floor, the footer commit, and the breaking-change marker. Findings go to stderr.", [
|
|
454
|
+
["<file>", "A description on disk; needs --title. The template is read from the working tree"],
|
|
455
|
+
["--pr <n>", "Read title, body, head, commits and files through gh; the template is read at the PR's head commit"],
|
|
456
|
+
["--repo <owner/name>", "With --pr: the repository on GitHub. Default: the one gh finds in the directory"],
|
|
457
|
+
["--title <t>", "With a file: the pull request title"],
|
|
458
|
+
["--head <sha>", "With a file: the commit the footer must name. Default: HEAD"],
|
|
459
|
+
["--base <ref>", "With a file: compare with this branch for the Risk floor. Default: origin/main"],
|
|
460
|
+
["--allow-breaking", "Allow a breaking-change marker or a `!` title"],
|
|
461
|
+
REPO_DIR,
|
|
462
|
+
], ["wachiman pr-template check body.md --title 'feat: add x'", "wachiman pr-template check --pr 42"]),
|
|
463
|
+
format: prTemplatePage(formatUsage, "Print a description reordered to the template: sections and status rows in template order, missing required headings added empty, unknown sections moved into Notes. No text is deleted. It never edits a pull request on GitHub.", [
|
|
464
|
+
["[<file>]", "The description. Default: standard input"],
|
|
465
|
+
["--write", "Rewrite the file instead of printing"],
|
|
466
|
+
REPO_DIR,
|
|
467
|
+
], ["wachiman pr-template format body.md", "wachiman pr-template format body.md --write"]),
|
|
468
|
+
risk: prTemplatePage(riskUsage, "Compute the risk floor of this branch from the files it changed, as 🟢 Low, 🟡 Medium or 🔴 High. A .github/pr-risk.toml on the base can only raise it.", [
|
|
469
|
+
["--base <ref>", "Compare with this branch. Default: origin/main"],
|
|
470
|
+
REPO_DIR,
|
|
471
|
+
], ["wachiman pr-template risk", "wachiman pr-template risk --base origin/develop"]),
|
|
472
|
+
strip: prTemplatePage(stripUsage, "Print a description without its guide comments and the stamp, keeping the Wachiman block markers. Run it before posting.", [
|
|
473
|
+
["<file>", "The description to clean"],
|
|
474
|
+
REPO_DIR,
|
|
475
|
+
], ["wachiman pr-template strip body.md"]),
|
|
476
|
+
},
|
|
477
|
+
};
|
|
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
|
+
|
|
395
589
|
/** The commands a GitHub Actions run uses; they are not in the root help. */
|
|
396
590
|
export const CI_COMMANDS = ["review", "comment", "threads", "reset-confidence"] as const;
|
|
397
591
|
|
|
398
592
|
const PAGES: Readonly<Record<string, Page>> = {
|
|
399
593
|
local: localPage, loop: loopPage, ask: askPage,
|
|
400
594
|
history: historyPage, status: statusPage, dashboard: dashboardPage, ledger: ledgerPageWithSubs,
|
|
401
|
-
setup: setupPage, init: initPage, doctor: doctorPage, profile: profilePage, project: projectPage, skills: skillsPage,
|
|
595
|
+
setup: setupPage, init: initPage, doctor: doctorPage, profile: profilePage, project: projectPage, skills: skillsPage, upgrade: upgradePage, "pr-template": prTemplatePageRoot, memory: memoryPage,
|
|
402
596
|
review: reviewPage, comment: commentPage, threads: threadsPage, "reset-confidence": resetConfidencePage,
|
|
403
597
|
};
|
|
404
598
|
|
|
@@ -478,6 +672,9 @@ export function rootHelp(paint: Paint = plain): string {
|
|
|
478
672
|
["profile", "List, create, add, log in, remove and default profiles"],
|
|
479
673
|
["project", "Show or remove this repository's binding"],
|
|
480
674
|
["skills", "Install or remove the agent skills"],
|
|
675
|
+
["pr-template", "Install and check the PR description template"],
|
|
676
|
+
["memory", "Check and propose repository memory (.wachiman/memory)"],
|
|
677
|
+
["upgrade", "Update the CLI and the workflow pin in this repository"],
|
|
481
678
|
]),
|
|
482
679
|
"",
|
|
483
680
|
`Help: wachiman <command> --help · wachiman help ci · docs: ${DOCS}/cli.md`,
|
package/src/history/command.ts
CHANGED
|
@@ -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
|
-
|
|
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 =
|
|
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
|
}
|
package/src/history/match.ts
CHANGED
|
@@ -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:
|
|
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
|
-
|
|
179
|
-
for (const f of findings) counts[f.verdict?.verdict ?? "unjudged"]++;
|
|
180
|
-
return { findings, counts };
|
|
200
|
+
return { findings, counts: countVerdicts(findings) };
|
|
181
201
|
}
|
package/src/history/store.ts
CHANGED
|
@@ -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);
|
package/src/history/types.ts
CHANGED
|
@@ -58,8 +58,13 @@ export interface HistoryRun {
|
|
|
58
58
|
unknownIds: string[];
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
-
|
|
62
|
-
|
|
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
|
+
}
|