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
@@ -0,0 +1,298 @@
1
+ /**
2
+ * `wachiman memory candidates | add | show | propose` (layer 3, laptop capture). No model is called
3
+ * here: the developer's coding agent drafts the entry from the code and the owner's intent and hands
4
+ * it over with `add`. `propose` is the only subcommand that writes to a remote (`propose.ts`).
5
+ */
6
+ import { readFileSync } from "node:fs";
7
+ import { wachimanHome } from "../accounts/config";
8
+ import { UsageError } from "../config";
9
+ import { spawnGit } from "../evidence";
10
+ import { historyRoot, repositoryKey } from "../history/store";
11
+ import { loadMemorySettings, repositoryRoot } from "./settings";
12
+ import {
13
+ candidateProblem,
14
+ evidenceFromFinding,
15
+ EVIDENCE_SOURCES,
16
+ newCandidate,
17
+ proposability,
18
+ readCandidate,
19
+ readCandidates,
20
+ renderEntry,
21
+ today,
22
+ withCandidateLock,
23
+ withEvidence,
24
+ writeCandidate,
25
+ type Candidate,
26
+ type Evidence,
27
+ type EvidenceSource,
28
+ } from "./candidates";
29
+ import type { GhFn } from "../engine";
30
+ import { proposeCandidate, teamHasMemory, type ProposeDeps } from "./propose";
31
+ import { candidatesFromPersonal, FIRST_PROPOSE_QUESTION, parseMemoryChoice, personalMemoryDir, proposePersonal, readMemoryChoice, writeMemoryChoice } from "./personal";
32
+
33
+ export const CAPTURE_SUBCOMMANDS = ["candidates", "add", "show", "propose"] as const;
34
+
35
+ /** The options each capture subcommand accepts: the parser below reads this, and the loop skill's commands are tested against it. */
36
+ export const CAPTURE_OPTIONS: Record<(typeof CAPTURE_SUBCOMMANDS)[number], { values: readonly string[]; flags: readonly string[] }> = {
37
+ candidates: { values: ["--format"], flags: [] },
38
+ show: { values: [], flags: [] },
39
+ propose: { values: [], flags: ["--personal", "--team", "--from-personal"] },
40
+ add: { values: ["--file", "--kind", "--scope", "--rule", "--why", "--holds-while", "--title", "--source", "--finding", "--pr", "--branch"], flags: ["--agent"] },
41
+ };
42
+
43
+ export interface CaptureIo {
44
+ stdout: (text: string) => void;
45
+ stderr: (line: string) => void;
46
+ }
47
+
48
+ export interface CaptureContext {
49
+ env?: Record<string, string | undefined>;
50
+ /** The GitHub calls of `memory remember`; tests pass a fake. Default: the `gh` binary. */
51
+ gh?: GhFn;
52
+ now?: () => Date;
53
+ deps?: ProposeDeps;
54
+ /** Asks the developer a question and returns the answer; absent when nobody can answer (no terminal). */
55
+ ask?: (question: string) => string | undefined;
56
+ }
57
+
58
+ interface Parsed {
59
+ values: Map<string, string>;
60
+ flags: Set<string>;
61
+ positional: string[];
62
+ }
63
+
64
+ /** `--x v`, `--x=v` and bare flags; anything else starting with `--` is a usage error. */
65
+ function parseOptions(argv: string[], sub: string, valueOptions: readonly string[], flagOptions: readonly string[]): Parsed {
66
+ const out: Parsed = { values: new Map(), flags: new Set(), positional: [] };
67
+ for (let i = 0; i < argv.length; i++) {
68
+ const arg = argv[i];
69
+ if (!arg.startsWith("--")) {
70
+ out.positional.push(arg);
71
+ continue;
72
+ }
73
+ const eq = arg.indexOf("=");
74
+ const name = eq === -1 ? arg : arg.slice(0, eq);
75
+ if (flagOptions.includes(name)) {
76
+ if (eq !== -1) throw new UsageError(`${name} takes no value.`);
77
+ out.flags.add(name);
78
+ } else if (valueOptions.includes(name)) {
79
+ if (out.values.has(name)) throw new UsageError(`${name} was given twice.`);
80
+ const v = eq === -1 ? argv[++i] : arg.slice(eq + 1);
81
+ if (v === undefined) throw new UsageError(`${name} needs a value.`);
82
+ if (eq === -1 && v.startsWith("--")) throw new UsageError(`${name} needs a value, and "${v}" looks like another option. A value that starts with "--" is written ${name}=${v}.`);
83
+ out.values.set(name, v);
84
+ } else {
85
+ throw new UsageError(`Unknown option "${name}" for wachiman memory ${sub}.`);
86
+ }
87
+ }
88
+ return out;
89
+ }
90
+
91
+ const oneId = (p: Parsed, sub: string) => {
92
+ if (p.positional.length !== 1) throw new UsageError(`wachiman memory ${sub} takes one entry id.`);
93
+ return p.positional[0];
94
+ };
95
+
96
+ function currentBranch(repoDir: string): string | undefined {
97
+ const r = spawnGit(["symbolic-ref", "--short", "-q", "HEAD"], { cwd: repoDir, timeoutMs: 30_000 });
98
+ return r.status === 0 && r.stdout.trim() !== "" ? r.stdout.trim() : undefined;
99
+ }
100
+
101
+ function parsePr(v: string | undefined): number | undefined {
102
+ if (v === undefined) return undefined;
103
+ if (!/^[1-9]\d*$/.test(v) || !Number.isSafeInteger(Number(v))) throw new UsageError(`--pr must be a pull request number, got "${v}".`);
104
+ return Number(v);
105
+ }
106
+
107
+ const need = (c: Candidate, minEvidence: number) => proposability(c, minEvidence);
108
+
109
+ /**
110
+ * Marks a candidate after its entry was written: `proposed` once the team's pull request has it, `personal` when it only went to
111
+ * this machine. Read again under the candidate's lock, so evidence added by `memory add` while the push was in flight is not
112
+ * overwritten. A failure is said, never thrown: the entry is already written, and a second propose is idempotent.
113
+ */
114
+ function markCandidate(home: string, key: string, id: string, fallback: Candidate | undefined, mark: "proposed" | "personal", at: string, io: CaptureIo) {
115
+ try {
116
+ withCandidateLock(home, key, id, () => {
117
+ const latest = readCandidate(home, key, id) ?? fallback;
118
+ if (latest) writeCandidate(home, key, { ...latest, [mark]: { at } });
119
+ });
120
+ } catch (error) {
121
+ io.stderr(`memory propose: the entry was recorded, but candidate ${id} could not be marked as ${mark === "personal" ? "written to personal memory" : "proposed"} (${(error as Error).message}).`);
122
+ }
123
+ }
124
+
125
+ /** `propose --from-personal [<id>...]`: the personal entries (or those ids) go to the team's memory pull request through the same write path as `propose <id>`. Personal memory is left as it is. */
126
+ function sendPersonal(ids: string[], repoDir: string, home: string, key: string, io: CaptureIo, ctx: CaptureContext): number {
127
+ for (const id of ids) if (!/^[0-9a-f]{7}$/.test(id)) throw new UsageError(`"${id}" is not a memory entry id (seven hex characters).`);
128
+ const dir = personalMemoryDir(home, repoDir);
129
+ if (dir === undefined) {
130
+ io.stderr("memory propose: this repository has no remote named origin with a host, an owner and a repository, so it has no personal memory; nothing was sent.");
131
+ return 1;
132
+ }
133
+ const { candidates, unknown, skipped } = candidatesFromPersonal(dir, ids);
134
+ if (unknown.length > 0) throw new UsageError(`No personal memory entry ${unknown.join(", ")} for this repository.`);
135
+ for (const line of skipped) io.stderr(`memory propose: skipped personal entry ${line}`);
136
+ if (candidates.length === 0) {
137
+ io.stdout("no personal memory entries to send.\n");
138
+ return skipped.length > 0 ? 1 : 0;
139
+ }
140
+ let failed = skipped.length > 0;
141
+ for (const c of candidates) {
142
+ io.stdout(`sending ${c.id} to the team's memory pull request:\n${renderEntry(c)}`);
143
+ const result = proposeCandidate(c, repoDir, io, ctx.deps);
144
+ if (!result.recorded || result.pullRequestFailed) failed = true;
145
+ // As after a team propose: the local candidate of this entry, if there is one, is marked as proposed.
146
+ if (result.recorded) markCandidate(home, key, c.id, undefined, "proposed", (ctx.now ?? (() => new Date()))().toISOString(), io);
147
+ }
148
+ return failed ? 1 : 0;
149
+ }
150
+
151
+ export function runCapture(sub: (typeof CAPTURE_SUBCOMMANDS)[number], rest: string[], repoDir: string, io: CaptureIo, ctx: CaptureContext = {}): number {
152
+ const env = ctx.env ?? process.env;
153
+ const home = wachimanHome(env);
154
+ const key = repositoryKey(repoDir).key;
155
+ const date = today((ctx.now ?? (() => new Date()))());
156
+ // `show` prints stored text and needs no setting, so a broken `.wachiman.yml` must not stop it.
157
+ const minEvidence = sub === "show" ? 0 : loadMemorySettings(repoDir, (n) => io.stderr(`note: ${n}`)).minEvidence;
158
+
159
+ if (sub === "candidates") {
160
+ const p = parseOptions(rest, sub, CAPTURE_OPTIONS.candidates.values, CAPTURE_OPTIONS.candidates.flags);
161
+ if (p.positional.length > 0) throw new UsageError(`wachiman memory candidates takes no argument, got "${p.positional[0]}".`);
162
+ const format = p.values.get("--format") ?? "terminal";
163
+ if (format !== "terminal" && format !== "json") throw new UsageError(`--format must be terminal or json, got "${format}".`);
164
+ const list = readCandidates(home, key, (name, why) => io.stderr(`note: ${name} is not listed: ${why}; remove it to start that candidate again.`));
165
+ if (format === "json") {
166
+ const candidates = list.map((c) => {
167
+ const q = need(c, minEvidence);
168
+ return { id: c.id, title: c.title, kind: c.kind, scope: c.scope, evidence: q.counted, distinct: q.distinct, needed: q.needed, proposable: q.proposable, ...(q.why ? { why: q.why } : {}), ...(c.proposed ? { proposed: c.proposed.at } : {}), ...(c.personal && !c.proposed ? { personal: c.personal.at } : {}) };
169
+ });
170
+ io.stdout(`${JSON.stringify({ format: "wachiman.memory-candidates/1", candidates }, null, 2)}\n`);
171
+ return 0;
172
+ }
173
+ if (list.length === 0) {
174
+ io.stdout("no memory candidates for this repository.\n");
175
+ return 0;
176
+ }
177
+ for (const c of list) {
178
+ const q = need(c, minEvidence);
179
+ const state = c.proposed ? `proposed ${c.proposed.at.slice(0, 10)}` : c.personal ? `personal ${c.personal.at.slice(0, 10)}${q.proposable ? ", proposable to the team" : ""}` : q.proposable ? "proposable" : `not proposable: ${q.why}`;
180
+ io.stdout(`${c.id} ${c.kind} ${c.scope} ${c.title}\n ${state}\n`);
181
+ }
182
+ return 0;
183
+ }
184
+
185
+ if (sub === "show") {
186
+ const id = oneId(parseOptions(rest, sub, [], []), sub);
187
+ const c = readCandidate(home, key, id);
188
+ if (!c) throw new UsageError(`No memory candidate ${id} for this repository; list them with \`wachiman memory candidates\`.`);
189
+ io.stdout(renderEntry(c));
190
+ return 0;
191
+ }
192
+
193
+ if (sub === "propose") {
194
+ const parsed = parseOptions(rest, sub, CAPTURE_OPTIONS.propose.values, CAPTURE_OPTIONS.propose.flags);
195
+ if (parsed.flags.has("--from-personal")) {
196
+ if (parsed.flags.has("--personal") || parsed.flags.has("--team")) throw new UsageError("--from-personal already sends to the team's memory pull request; it cannot be combined with --personal or --team.");
197
+ return sendPersonal(parsed.positional, repoDir, home, key, io, ctx);
198
+ }
199
+ const id = oneId(parsed, sub);
200
+ if (parsed.flags.has("--personal") && parsed.flags.has("--team")) throw new UsageError("--personal and --team exclude each other: choose where the entry goes.");
201
+ let personal = parsed.flags.has("--personal");
202
+ const c = readCandidate(home, key, id);
203
+ if (!c) throw new UsageError(`No memory candidate ${id} for this repository; list them with \`wachiman memory candidates\`.`);
204
+ const q = need(c, minEvidence);
205
+ if (!q.proposable) {
206
+ io.stderr(`memory propose: candidate ${id} is not proposable: ${q.why}. Nothing was written.`);
207
+ return 1;
208
+ }
209
+ if (!personal && !parsed.flags.has("--team")) {
210
+ // Spec decision 16: a repository whose team has not adopted memory is never pushed to unasked.
211
+ let choice = readMemoryChoice(home, key);
212
+ // The probe fetches from origin, so it runs only when the answer depends on it: a stored `team` answer goes to the team whatever the team has.
213
+ const teamMemory = choice === "team" ? undefined : (ctx.deps?.teamMemory ?? teamHasMemory)(repositoryRoot(repoDir));
214
+ if (choice === "personal" && teamMemory === true) {
215
+ // The team adopted memory after the answer was given: the entry goes to the team again.
216
+ io.stdout("this repository's team now has .wachiman/memory/, so this entry goes to the team's memory pull request; pass --personal to keep it on this machine.\n");
217
+ choice = "team";
218
+ }
219
+ if (!choice && teamMemory === false) {
220
+ choice = parseMemoryChoice(ctx.ask?.(FIRST_PROPOSE_QUESTION));
221
+ if (!choice) {
222
+ io.stderr(`memory propose: this repository's default branch has no .wachiman/memory/, so nothing was pushed or written. Run it again with --personal (keep the entry on this machine) or --team (propose it to the team's repository).`);
223
+ return 1;
224
+ }
225
+ writeMemoryChoice(home, key, choice, (ctx.now ?? (() => new Date()))());
226
+ }
227
+ personal = choice === "personal";
228
+ }
229
+ const result = personal ? proposePersonal(c, repoDir, home, io) : proposeCandidate(c, repoDir, io, ctx.deps);
230
+ if (result.recorded) {
231
+ // A personal write is kept on this machine: the team never received it, so it stays proposable (`--from-personal`).
232
+ markCandidate(home, key, id, c, personal ? "personal" : "proposed", (ctx.now ?? (() => new Date()))().toISOString(), io);
233
+ }
234
+ return result.recorded ? (result.pullRequestFailed ? 1 : 0) : 1;
235
+ }
236
+
237
+ // add
238
+ const p = parseOptions(rest, sub, CAPTURE_OPTIONS.add.values, CAPTURE_OPTIONS.add.flags);
239
+ if (p.positional.length > 0) throw new UsageError(`wachiman memory add takes no argument, got "${p.positional[0]}".`);
240
+ let base: Record<string, string> = {};
241
+ const file = p.values.get("--file");
242
+ if (file !== undefined) {
243
+ try {
244
+ base = JSON.parse(readFileSync(file, "utf8"));
245
+ } catch (error) {
246
+ throw new UsageError(`--file ${file} is not a readable JSON entry (${error instanceof Error ? error.message : error}).`);
247
+ }
248
+ if (!base || typeof base !== "object" || Array.isArray(base)) throw new UsageError(`--file ${file} must hold a JSON object with kind, scope, rule and why.`);
249
+ }
250
+ for (const name of ["kind", "scope", "rule", "why", "holdsWhile", "holds while", "title"]) {
251
+ const v = (base as Record<string, unknown>)[name];
252
+ if (v !== undefined && typeof v !== "string") throw new UsageError(`--file ${file}: "${name}" must be a string, got ${Array.isArray(v) ? "an array" : v === null ? "null" : typeof v}.`);
253
+ }
254
+ const field = (flag: string, name: string) => p.values.get(flag) ?? (typeof base[name] === "string" ? base[name] : undefined);
255
+ const sourceText = p.values.get("--source") ?? "instruction";
256
+ if (!(EVIDENCE_SOURCES as readonly string[]).includes(sourceText)) throw new UsageError(`--source must be one of: ${EVIDENCE_SOURCES.join(", ")}. A reaction or silence is never evidence.`);
257
+ const source = sourceText as EvidenceSource;
258
+ const kind = field("--kind", "kind");
259
+ if (kind === "exception" && source === "fixed") throw new UsageError("A fix supports only a convention, never an exception.");
260
+ const finding = p.values.get("--finding");
261
+ const pr = parsePr(p.values.get("--pr"));
262
+ const agent = p.flags.has("--agent");
263
+
264
+ let first: Evidence;
265
+ if (source === "instruction") {
266
+ if (finding !== undefined) throw new UsageError("--finding is for --source judged or fixed.");
267
+ const branch = p.values.get("--branch") ?? currentBranch(repoDir);
268
+ if (pr === undefined && branch === undefined) throw new UsageError("HEAD is detached: say where the instruction came from with --pr <n> or --branch <name>.");
269
+ first = { date, source, agent, ...(pr !== undefined ? { pr } : { branch }) };
270
+ } else {
271
+ if (finding === undefined) throw new UsageError(`--source ${source} needs --finding <id>: the evidence is read from the local history, not taken on trust.`);
272
+ first = evidenceFromFinding(key, historyRoot(home), finding, source, { ...(pr !== undefined ? { pr } : {}), agent, date });
273
+ }
274
+
275
+ const fresh = newCandidate(
276
+ {
277
+ kind: kind ?? "",
278
+ scope: field("--scope", "scope") ?? "",
279
+ rule: field("--rule", "rule") ?? "",
280
+ why: field("--why", "why") ?? "",
281
+ holdsWhile: field("--holds-while", "holdsWhile") ?? field("--holds-while", "holds while"),
282
+ title: field("--title", "title"),
283
+ },
284
+ first,
285
+ date,
286
+ );
287
+ const saved = withCandidateLock(home, key, fresh.id, () => {
288
+ const existing = readCandidate(home, key, fresh.id);
289
+ const next = existing ? withEvidence(existing, [first]) : fresh;
290
+ const problem = candidateProblem(next);
291
+ if (problem) throw new UsageError(problem);
292
+ writeCandidate(home, key, next);
293
+ return next;
294
+ });
295
+ const q = need(saved, minEvidence);
296
+ io.stdout(`candidate ${saved.id} saved: ${saved.title}\n${q.proposable ? "proposable: show it to the owner with `wachiman memory show " + saved.id + "`, then `wachiman memory propose " + saved.id + "`." : `not proposable yet: ${q.why}.`}\n`);
297
+ return 0;
298
+ }
@@ -0,0 +1,195 @@
1
+ /**
2
+ * `wachiman memory <subcommand>`: the one entry that `src/cli.ts` calls. `check` (layer 1) reads
3
+ * `.wachiman/memory/` from the working tree and reports every defect with its file and line: a malformed entry, an entry id that is not its digest, a glob that
4
+ * matches no file, an index row that names a missing file, an area file the index does not list, and
5
+ * a budget overrun. No model is called and nothing is written. Exit 0 when clean, 1 on problems.
6
+ * After the problems, `check` prints hygiene suggestions (likely duplicates, entries not used in
7
+ * `memory.archive_after_days`); they never change the exit code. `archive <id>` (layer 6) moves one
8
+ * entry to `archive.md` in the working tree, only when the developer runs it.
9
+ * `report` (layer 7) prints what the local history says about memory (`report.ts`). `candidates`, `add`, `show` and
10
+ * `propose` (layer 3, laptop capture) are in `capture.ts`.
11
+ */
12
+ import { existsSync, lstatSync, readdirSync, readFileSync, statSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import { wachimanHome } from "../accounts/config";
15
+ import { UsageError } from "../config";
16
+ import { spawnGit } from "../evidence";
17
+ import { commandHelp } from "../help";
18
+ import { historyRoot, readRuns, readVerdicts, repositoryKey } from "../history/store";
19
+ import { parseRepoSettings, resolveMemorySettings, SETTINGS_PATH } from "../repo-settings";
20
+ import { parseMemoryFile, type MemoryEntry, type MemoryProblem } from "./entries";
21
+ import { inspectMemory, type CheckInput, type CheckResult } from "./inspect";
22
+ import { CAPTURE_SUBCOMMANDS, runCapture, type CaptureContext } from "./capture";
23
+ import { runRemember } from "./remember";
24
+ import { repositoryRoot } from "./settings";
25
+ import { archiveEntry, archiveSuggestions, findDuplicates, readMemoryUse, writeFileAtomically, type MemoryUse } from "./hygiene";
26
+ import { personalMemoryDir, readPersonalFiles } from "./personal";
27
+ import { buildReport, parseReportArgs, renderReport } from "./report";
28
+ import { ARCHIVE_FILE, MEMORY_DIR } from "./load";
29
+
30
+ export { inspectMemory, type CheckInput, type CheckResult };
31
+
32
+ export const MEMORY_SUBCOMMANDS = ["check", "archive", "report", ...CAPTURE_SUBCOMMANDS, "remember"] as const;
33
+
34
+ export interface MemoryIo {
35
+ stdout: (text: string) => void;
36
+ stderr: (line: string) => void;
37
+ }
38
+
39
+ /** Every problem of a memory folder, sorted by file and line. Pure: `runMemory` supplies the files. */
40
+ export function checkMemory(input: CheckInput): MemoryProblem[] {
41
+ return inspectMemory(input).problems;
42
+ }
43
+
44
+ /** The checked-out tree is untrusted: every git call here has a time limit and the engine's hardened environment. */
45
+ const GIT_TIMEOUT_MS = 30_000;
46
+
47
+ /** Tracked files plus untracked files that are not ignored; a plain directory walk when `root` is not a git repository. */
48
+ function listRepoFiles(root: string): string[] {
49
+ const r = spawnGit(["ls-files", "-z", "--cached", "--others", "--exclude-standard"], { cwd: root, timeoutMs: GIT_TIMEOUT_MS, maxBytes: 256 * 1024 * 1024 });
50
+ if (r.status === 0) return r.stdout.split("\0").filter(Boolean);
51
+ const out: string[] = [];
52
+ const walk = (rel: string) => {
53
+ for (const entry of readdirSync(join(root, rel), { withFileTypes: true })) {
54
+ if (entry.name === ".git" || entry.name === "node_modules") continue;
55
+ const path = rel === "" ? entry.name : `${rel}/${entry.name}`;
56
+ if (entry.isDirectory()) walk(path);
57
+ else if (entry.isFile()) out.push(path);
58
+ }
59
+ };
60
+ walk("");
61
+ return out;
62
+ }
63
+
64
+ function readMemoryFolder(root: string): Record<string, string> | undefined {
65
+ const dir = join(root, MEMORY_DIR);
66
+ if (!existsSync(dir) || !lstatSync(dir).isDirectory()) return undefined;
67
+ const files: Record<string, string> = {};
68
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
69
+ if (entry.isFile() && entry.name.endsWith(".md")) files[entry.name] = readFileSync(join(dir, entry.name), "utf8");
70
+ }
71
+ return files;
72
+ }
73
+
74
+ /** `argv` is what follows `memory`. Returns the exit code: 0 clean, 1 problems found; usage errors throw `UsageError` (exit 2). */
75
+ export function runMemory(argv: string[], repoDir: string, io: MemoryIo, ctx: CaptureContext = {}): number {
76
+ const [first, ...rest] = argv;
77
+ if (first === undefined || first === "--help" || first === "-h") return (io.stdout(commandHelp(["memory"])!), 0);
78
+ if (!(MEMORY_SUBCOMMANDS as readonly string[]).includes(first)) throw new UsageError(`Unknown memory subcommand "${first}". Use one of: ${MEMORY_SUBCOMMANDS.join(", ")}.`);
79
+ if (first === "archive") {
80
+ if (rest.includes("--help") || rest.includes("-h")) return (io.stdout(commandHelp(["memory", "archive"])!), 0);
81
+ return runArchive(rest, repoDir, io);
82
+ }
83
+ if (first === "report") {
84
+ if (rest.includes("--help") || rest.includes("-h")) return (io.stdout(commandHelp(["memory", "report"])!), 0);
85
+ const args = parseReportArgs(rest);
86
+ const root = repositoryRoot(repoDir);
87
+ const key = repositoryKey(repoDir).key;
88
+ const home = historyRoot(wachimanHome(ctx.env ?? process.env));
89
+ const personalDir = personalMemoryDir(wachimanHome(ctx.env ?? process.env), repoDir);
90
+ const report = buildReport({ runs: readRuns(home, key, (line) => io.stderr(line)), verdicts: readVerdicts(home, key), files: readMemoryFolder(root), personalFiles: personalDir === undefined ? undefined : readPersonalFiles(personalDir, (line) => io.stderr(line)), use: readMemoryUse(wachimanHome(ctx.env ?? process.env), key), since: args.since });
91
+ io.stdout(args.format === "json" ? `${JSON.stringify(report, null, 2)}\n` : renderReport(report));
92
+ return 0;
93
+ }
94
+ if (first !== "check") {
95
+ if (rest.includes("--help") || rest.includes("-h")) return (io.stdout(commandHelp(["memory", first])!), 0);
96
+ // The Actions write job (layer 5): reads the comment from the workflow's environment, calls `gh`.
97
+ if (first === "remember") return runRemember(rest, repoDir, io, { env: ctx.env, gh: ctx.gh, pulls: ctx.deps?.pulls });
98
+ return runCapture(first as (typeof CAPTURE_SUBCOMMANDS)[number], rest, repoDir, io, ctx);
99
+ }
100
+ if (rest.includes("--help") || rest.includes("-h")) return (io.stdout(commandHelp(["memory", "check"])!), 0);
101
+ if (rest.length > 0) throw new UsageError(`wachiman memory check takes no arguments, got "${rest[0]}".`);
102
+
103
+ const root = repositoryRoot(repoDir);
104
+ const files = readMemoryFolder(root);
105
+ if (files === undefined) {
106
+ io.stdout(`no ${MEMORY_DIR}/ folder in ${root}; nothing to check.\n`);
107
+ return 0;
108
+ }
109
+ // The settings file as the author has it now; a review reads the base commit's copy.
110
+ const settingsPath = join(root, SETTINGS_PATH);
111
+ const settings = existsSync(settingsPath) ? parseRepoSettings(readFileSync(settingsPath, "utf8")) : undefined;
112
+ const result = inspectMemory({ files, repoFiles: listRepoFiles(root), settings });
113
+ for (const notice of result.notices) io.stderr(`note: ${notice}`);
114
+ for (const p of result.problems) io.stderr(`${MEMORY_DIR}/${p.file}:${p.line}: ${p.message}`);
115
+ const resolved = resolveMemorySettings(settings).settings;
116
+ if (result.problems.length > 0) {
117
+ io.stdout(`memory check: ${result.problems.length} problem${result.problems.length === 1 ? "" : "s"} in ${MEMORY_DIR}/\n`);
118
+ printSuggestions(files, resolved, root, io, ctx);
119
+ return 1;
120
+ }
121
+ io.stdout(`memory ok: ${Object.keys(files).length} file${Object.keys(files).length === 1 ? "" : "s"}, ${result.entries} entr${result.entries === 1 ? "y" : "ies"}\n`);
122
+ printSuggestions(files, resolved, root, io, ctx);
123
+ return 0;
124
+ }
125
+
126
+ const where = (e: MemoryEntry) => `${e.file}:${e.line}`;
127
+ const plural = (n: number) => `${n} day${n === 1 ? "" : "s"}`;
128
+
129
+ /**
130
+ * Hygiene suggestions, printed after the problems on stdout. They never change the exit code and
131
+ * nothing is applied. Duplicates are found by the text of two rules; contradictions are not found
132
+ * at all (that needs a model). Archive suggestions need the laptop's record of last use, so they are
133
+ * not made in GitHub Actions, where no record persists, and need history on to be recorded (ADR 0020).
134
+ */
135
+ function printSuggestions(files: Record<string, string>, settings: { archiveAfterDays: number }, root: string, io: MemoryIo, ctx: CaptureContext) {
136
+ const env = ctx.env ?? process.env;
137
+ const entries = Object.keys(files).sort().flatMap((name) => parseMemoryFile(name, files[name]).entries);
138
+ const lines: string[] = [];
139
+ for (const { a, b, similarity } of findDuplicates(entries)) {
140
+ lines.push(`suggestion: ${a.id} and ${b.id} look like duplicates (same kind, overlapping scopes, rules ${Math.round(similarity * 100)}% alike): "${a.title}" (${where(a)}) and "${b.title}" (${where(b)}). Keep one; \`wachiman memory archive <id>\` moves the other to ${ARCHIVE_FILE}.`);
141
+ }
142
+ if (env.GITHUB_ACTIONS !== "true") {
143
+ let use: MemoryUse;
144
+ try {
145
+ use = readMemoryUse(wachimanHome(env), repositoryKey(root).key);
146
+ } catch (error) {
147
+ use = { known: false, reason: `this checkout has no repository key (${error instanceof Error ? error.message : error})` };
148
+ }
149
+ const date = (ctx.now ?? (() => new Date()))().toISOString().slice(0, 10);
150
+ if (!use.known) {
151
+ // Without a record nothing is known about use: an entry must not be called unused, so none is suggested. Said only when some entry is old enough for the answer to matter.
152
+ const old = archiveSuggestions(entries, {}, settings.archiveAfterDays, date).length;
153
+ if (old > 0) lines.push(`note: ${old} entr${old === 1 ? "y is" : "ies are"} older than memory.archive_after_days (${settings.archiveAfterDays}) by added date, but whether ${old === 1 ? "it was" : "they were"} used is unknown, so no archive suggestion is made: ${use.reason}.`);
154
+ } else {
155
+ for (const s of archiveSuggestions(entries, use.used, settings.archiveAfterDays, date, use.since)) {
156
+ const last = s.usedEver ? `last used ${s.since}` : `no use recorded on this laptop since ${s.since}`;
157
+ lines.push(`suggestion: ${s.entry.id} ${last} (${plural(s.days)} ago), over memory.archive_after_days (${settings.archiveAfterDays}): "${s.entry.title}" (${where(s.entry)}). \`wachiman memory archive ${s.entry.id}\` moves it to ${ARCHIVE_FILE}.`);
158
+ }
159
+ }
160
+ }
161
+ if (lines.length === 0) return;
162
+ io.stdout(`${lines.join("\n")}\nsuggestions only: nothing was changed. Only likely duplicates are detected without a model; contradictions are not. Use is recorded on this laptop only.\n`);
163
+ }
164
+
165
+ /** `wachiman memory archive <id>`: moves the entry to archive.md in the working tree. Nothing is committed or pushed. */
166
+ function runArchive(rest: string[], repoDir: string, io: MemoryIo): number {
167
+ const flag = rest.find((a) => a.startsWith("-"));
168
+ if (flag !== undefined) throw new UsageError(`Unknown option "${flag}" for wachiman memory archive.`);
169
+ if (rest.length !== 1) throw new UsageError("wachiman memory archive takes one entry id.");
170
+ const root = repositoryRoot(repoDir);
171
+ const files = readMemoryFolder(root);
172
+ if (files === undefined) {
173
+ io.stderr(`memory archive: no ${MEMORY_DIR}/ folder in ${root}; nothing was changed.`);
174
+ return 1;
175
+ }
176
+ const moved = archiveEntry(files, rest[0]);
177
+ if (!moved.ok) {
178
+ io.stderr(`memory archive: ${moved.reason} Nothing was changed.`);
179
+ return 1;
180
+ }
181
+ for (const part of [join(root, ".wachiman"), join(root, MEMORY_DIR), join(root, MEMORY_DIR, ARCHIVE_FILE)]) {
182
+ if (existsSync(part) && lstatSync(part).isSymbolicLink()) {
183
+ io.stderr(`memory archive: ${part.slice(root.length + 1)} is a symbolic link; nothing was changed.`);
184
+ return 1;
185
+ }
186
+ }
187
+ // archive.md first, then the source: a failure in between leaves the entry in both files, never in neither.
188
+ for (const [name, text] of Object.entries(moved.files).sort(([a], [b]) => Number(b === ARCHIVE_FILE) - Number(a === ARCHIVE_FILE))) {
189
+ const path = join(root, MEMORY_DIR, name);
190
+ // A new randomly named temporary file in the same directory, renamed over the target: a symbolic link planted at a guessable temporary name is never followed.
191
+ writeFileAtomically(path, text, existsSync(path) ? statSync(path).mode & 0o777 : 0o644);
192
+ }
193
+ io.stdout(`archived: ${rest[0]} moved from ${moved.from} to ${ARCHIVE_FILE} in ${MEMORY_DIR}/ (working tree only, not committed). Commit it, or leave it out of the change.\n`);
194
+ return 0;
195
+ }