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
@@ -20,6 +20,8 @@ import { MIN_LINE_CHARS, stripWhitespace, titleKey } from "../history/fingerprin
20
20
  import { replay, type ReplayedFinding } from "../history/match";
21
21
  import { historyRoot, readRuns, readVerdicts, repositoryKey } from "../history/store";
22
22
  import { LOCAL_FLAGS, parseFlags, runLocal, type LocalArgs, type LocalDeps } from "../local";
23
+ import { candidatesForRound } from "../memory/candidates";
24
+ import { loadMemorySettings } from "../memory/settings";
23
25
  import { location, sha7 } from "../sinks/common";
24
26
  import { LOOP_STATE_FORMAT, readLoop, writeLoop, type LedgerEntry, type LoopState } from "./state";
25
27
  import { evaluate, isRefutedBy, roundCapReached, type Decision, type LoopFinding, type LoopStatus, type OpenFinding, type Released } from "./stop-rule";
@@ -92,6 +94,8 @@ export interface RoundReport {
92
94
  notes: LoopFinding[];
93
95
  outcome: { status: "converged" | "open" | "stopped"; reason?: Why; message: string };
94
96
  exitCode: 0 | 10 | 11;
97
+ /** Proposable memory candidates that cite a finding of this loop or whose scope matches its files. Absent when there are none. */
98
+ memoryCandidates?: { id: string; title: string }[];
95
99
  }
96
100
 
97
101
  const GIT_TIMEOUT_MS = 30_000;
@@ -189,7 +193,8 @@ const withVerdicts = (ledger: LedgerEntry[], verdicts: ReturnType<typeof readVer
189
193
  ledger.map((e) => ({ ...e, ...(verdicts.get(e.id) ? { verdict: { verdict: verdicts.get(e.id)!.verdict, reason: verdicts.get(e.id)!.reason } } : {}) }));
190
194
 
191
195
  export async function runLoop(args: LoopArgs, repoDir: string, env: Record<string, string | undefined>, io: LoopIo, deps: LoopDeps = {}): Promise<number> {
192
- const root = historyRoot(wachimanHome(env));
196
+ const home = wachimanHome(env);
197
+ const root = historyRoot(home);
193
198
  const key = repositoryKey(repoDir).key;
194
199
  const branch = currentBranch(repoDir);
195
200
  const head = headOf(repoDir);
@@ -214,7 +219,9 @@ export async function runLoop(args: LoopArgs, repoDir: string, env: Record<strin
214
219
  const verdicts = () => readVerdicts(root, key);
215
220
  const roundsRun = state.rounds.length;
216
221
  const render = (report: RoundReport) => {
217
- io.stdout(args.format === "json" ? renderJson(report) : renderTerminal(report));
222
+ const candidates = memoryCandidatesOf(state, home, key, repoDir);
223
+ const full: RoundReport = candidates.length > 0 ? { ...report, memoryCandidates: candidates } : report;
224
+ io.stdout(args.format === "json" ? renderJson(full) : renderTerminal(full));
218
225
  return report.exitCode;
219
226
  };
220
227
 
@@ -290,6 +297,16 @@ export async function runLoop(args: LoopArgs, repoDir: string, env: Record<strin
290
297
  return render(report(state, round, args, result.change.head.sha, range, decision.decision, decision.decision.converged ? 0 : 10, finish(decision.decision, round, args)));
291
298
  }
292
299
 
300
+ /** The memory candidates worth asking the owner about after this round; none when memory is not in use. */
301
+ function memoryCandidatesOf(state: LoopState, home: string, key: string, repoDir: string) {
302
+ try {
303
+ const min = loadMemorySettings(repoDir).minEvidence;
304
+ return candidatesForRound(home, key, min, state.ledger);
305
+ } catch {
306
+ return [];
307
+ }
308
+ }
309
+
293
310
  /**
294
311
  * The new ledger and the decision after a round. The loop decides from the round's own result and the
295
312
  * code, never from the history's settled map (a review outside the loop writes to the same history).
@@ -413,6 +430,7 @@ export function renderJson(r: RoundReport): string {
413
430
  open: r.open.map((f) => ({ ...cleanFinding(f), ...(f.unreasonedWrong ? { unreasonedWrong: true } : {}) })),
414
431
  released: r.released.map((x) => ({ ...cleanFinding(x.finding), why: x.why, ...(x.reason ? { reason: x.reason } : {}) })),
415
432
  notes: r.notes.map(cleanFinding),
433
+ ...(r.memoryCandidates ? { memoryCandidates: r.memoryCandidates } : {}),
416
434
  };
417
435
  return `${JSON.stringify(doc, null, 2)}\n`;
418
436
  }
@@ -436,6 +454,10 @@ export function renderTerminal(r: RoundReport): string {
436
454
  lines.push("", `Notes, never counted (${r.notes.length}):`);
437
455
  for (const f of r.notes) lines.push(` ${row(f)}`);
438
456
  if (r.notes.length === 0) lines.push(" none");
457
+ if (r.memoryCandidates) {
458
+ lines.push("", `Memory candidates the owner could approve (${r.memoryCandidates.length}); show one with \`wachiman memory show <id>\`:`);
459
+ for (const c of r.memoryCandidates) lines.push(` ${c.id} ${neutralise(c.title).replace(/\s+/g, " ")}`);
460
+ }
439
461
  lines.push("", `Outcome (exit ${r.exitCode}): ${r.outcome.message}`);
440
462
  return `${lines.join("\n")}\n`;
441
463
  }
@@ -0,0 +1,425 @@
1
+ /**
2
+ * Memory candidates kept on the laptop (spec decisions 6 and 7). A candidate is an entry somebody
3
+ * drafted, with the evidence for it. It lives under the Wachiman home, per repository, keyed like the
4
+ * local history, and becomes repository memory only through `wachiman memory propose`.
5
+ *
6
+ * The id is the entry digest (`entryId`), so a candidate is the exact text the developer is shown:
7
+ * `renderEntry` produces that text, `show` prints it and `propose` writes it. Evidence and the added
8
+ * date are not part of the id, so evidence can grow without changing what was approved.
9
+ *
10
+ * Reactions and silence are never evidence; there is no source for them.
11
+ */
12
+ import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import { UsageError } from "../config";
15
+ import { loopFiles, readVerdicts } from "../history/store";
16
+ import { entryId, parseMemoryFile, type MemoryKind } from "./entries";
17
+ import { matchesGlob } from "./load";
18
+
19
+ export const CANDIDATE_FORMAT = "wachiman.memory-candidate/1";
20
+
21
+ export type EvidenceSource = "instruction" | "judged" | "fixed";
22
+ export const EVIDENCE_SOURCES: readonly EvidenceSource[] = ["instruction", "judged", "fixed"];
23
+
24
+ const SOURCE_LABEL: Record<EvidenceSource, string> = {
25
+ instruction: "operator instruction",
26
+ judged: "finding judged wrong or intentional",
27
+ fixed: "finding fixed",
28
+ };
29
+
30
+ export interface Evidence {
31
+ /** `YYYY-MM-DD`. */
32
+ date: string;
33
+ source: EvidenceSource;
34
+ /** The pull request it came from, or else the branch (a laptop review has no pull request number). */
35
+ pr?: number;
36
+ branch?: string;
37
+ /** An agent wrote the reply or the instruction on the owner's behalf (spec open question 1). */
38
+ agent: boolean;
39
+ /** The local history id of the finding, for `judged` and `fixed`. Never written into the repository. */
40
+ finding?: string;
41
+ /**
42
+ * The evidence line verbatim, for an entry that already exists as text (one read back from personal
43
+ * memory by `propose --from-personal`). Never stored in a candidate file.
44
+ */
45
+ text?: string;
46
+ }
47
+
48
+ export interface Candidate {
49
+ format: typeof CANDIDATE_FORMAT;
50
+ id: string;
51
+ title: string;
52
+ kind: MemoryKind;
53
+ scope: string;
54
+ rule: string;
55
+ why: string;
56
+ holdsWhile?: string;
57
+ /** `YYYY-MM-DD` of the first sighting; it is the entry's `added` line. */
58
+ added: string;
59
+ evidence: Evidence[];
60
+ /** Sent to the team's memory pull request. */
61
+ proposed?: { at: string };
62
+ /** Kept in personal memory only; the team never received it. */
63
+ personal?: { at: string };
64
+ }
65
+
66
+ const squash = (text: string) => text.replace(/\s+/g, " ").trim();
67
+ export const today = (now: Date = new Date()) => now.toISOString().slice(0, 10);
68
+
69
+ const refKey = (e: Evidence) => (e.pr !== undefined ? `pr:${e.pr}` : `branch:${e.branch ?? ""}`);
70
+ const evidenceKey = (e: Evidence) => `${e.source}|${refKey(e)}|${e.finding ?? ""}|${e.text ?? ""}`;
71
+
72
+ /** The evidence line as it is written in the entry. */
73
+ export function evidenceLine(e: Evidence): string {
74
+ if (e.text !== undefined) return squash(e.text);
75
+ const ref = e.pr !== undefined ? `pull request ${e.pr}` : `branch ${squash(e.branch ?? "")}`;
76
+ return `${e.date} ${SOURCE_LABEL[e.source]}, ${ref}${e.agent ? ", written by an agent" : ""}`;
77
+ }
78
+
79
+ /**
80
+ * The evidence `evidenceLine` wrote, read back; undefined for a line it did not write. `finding` is
81
+ * never written into the repository, so it is never read back.
82
+ */
83
+ export function parseEvidenceLine(line: string): Evidence | undefined {
84
+ const labels = Object.entries(SOURCE_LABEL) as [EvidenceSource, string][];
85
+ const m = /^(\d{4}-\d{2}-\d{2}) (.+?), (?:pull request ([1-9]\d*)|branch (.+?))(, written by an agent)?$/.exec(line);
86
+ const source = labels.find(([, label]) => label === m?.[2])?.[0];
87
+ if (!m || !source) return undefined;
88
+ const pr = m[3] !== undefined ? Number(m[3]) : undefined;
89
+ if (pr !== undefined && !Number.isSafeInteger(pr)) return undefined;
90
+ return { date: m[1], source, agent: m[5] !== undefined, ...(pr !== undefined ? { pr } : { branch: m[4] }) };
91
+ }
92
+
93
+ export interface EntryFields {
94
+ kind: string;
95
+ scope: string;
96
+ rule: string;
97
+ why: string;
98
+ holdsWhile?: string;
99
+ title?: string;
100
+ }
101
+
102
+ const MAX_TITLE = 80;
103
+ const defaultTitle = (rule: string) => {
104
+ const t = squash(rule);
105
+ return t.length <= MAX_TITLE ? t : `${t.slice(0, MAX_TITLE - 1).trimEnd()}…`;
106
+ };
107
+
108
+ /** The exact text of the entry: what `show` prints and `propose` writes. Ends with one newline. */
109
+ export function renderEntry(c: Candidate): string {
110
+ const lines = [
111
+ `### ${c.id} ${squash(c.title)}`,
112
+ "",
113
+ `- kind: ${c.kind}`,
114
+ `- scope: ${squash(c.scope)}`,
115
+ `- rule: ${squash(c.rule)}`,
116
+ `- why: ${squash(c.why)}`,
117
+ ...(c.holdsWhile ? [`- holds while: ${squash(c.holdsWhile)}`] : []),
118
+ "- evidence:",
119
+ ...c.evidence.map((e) => ` - ${evidenceLine(e)}`),
120
+ `- added: ${c.added}`,
121
+ ];
122
+ return `${lines.join("\n")}\n`;
123
+ }
124
+
125
+ /**
126
+ * Characters a terminal acts on or a reader cannot see: control characters (an escape sequence can
127
+ * rewrite what `show` appears to print), zero-width, direction-changing and other format characters (category Cf, line and paragraph separators, variation selectors, filler characters). Whitespace is
128
+ * already folded away by `squash`, so none of these is legitimate in an entry.
129
+ */
130
+ const UNSAFE_CHARACTER = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\u034F\u115F\u1160\u3164\uFFA0\uFE00-\uFE0F\u{E0100}-\u{E01EF}]/u;
131
+
132
+ /**
133
+ * Why `c` cannot be shown and committed as the same bytes, or undefined when it can: a character the
134
+ * terminal would interpret, an id that is not the digest of the fields, or text that does not read
135
+ * back as exactly this one entry (the text `propose` writes is what `memory check` must accept).
136
+ */
137
+ export function candidateProblem(c: Candidate): string | undefined {
138
+ const texts: [string, string | undefined][] = [
139
+ ["title", c.title],
140
+ ["kind", c.kind],
141
+ ["scope", c.scope],
142
+ ["rule", c.rule],
143
+ ["why", c.why],
144
+ ["holds while", c.holdsWhile],
145
+ ["added", c.added],
146
+ ...c.evidence.flatMap((e, i): [string, string | undefined][] => [[`evidence ${i + 1} date`, e.date], [`evidence ${i + 1} branch`, e.branch], [`evidence ${i + 1} text`, e.text]]),
147
+ ];
148
+ for (const [name, value] of texts) {
149
+ const bad = value === undefined ? undefined : UNSAFE_CHARACTER.exec(value);
150
+ if (bad) {
151
+ const code = (bad[0].codePointAt(0) ?? 0).toString(16).toUpperCase().padStart(4, "0");
152
+ return `The ${name} holds the control or invisible character U+${code}, which a terminal would not show as written; remove it.`;
153
+ }
154
+ }
155
+ const digest = entryId({ kind: c.kind, scope: c.scope, rule: c.rule, why: c.why, ...(c.holdsWhile ? { holdsWhile: c.holdsWhile } : {}) });
156
+ if (digest !== c.id) return `The id ${c.id} is not the digest ${digest} of the entry's fields, so the text shown would not be the text recorded.`;
157
+ const parsed = parseMemoryFile("index.md", renderEntry(c));
158
+ if (parsed.problems.length > 0 || parsed.entries.length !== 1 || parsed.entries[0].id !== c.id) {
159
+ return `The entry does not read back as one valid memory entry (${parsed.problems[0]?.message ?? "unreadable"}).`;
160
+ }
161
+ return undefined;
162
+ }
163
+
164
+ /** A new candidate from entry fields and its first evidence. Throws a `UsageError` for a field the format cannot carry. */
165
+ export function newCandidate(fields: EntryFields, first: Evidence, date: string): Candidate {
166
+ const need = (name: string, value: string | undefined) => {
167
+ if (value === undefined || squash(value) === "") throw new UsageError(`The entry needs a ${name}.`);
168
+ return squash(value);
169
+ };
170
+ const kind = need("kind", fields.kind);
171
+ if (kind !== "convention" && kind !== "exception") throw new UsageError(`kind must be "convention" or "exception", got "${kind}".`);
172
+ const scope = need("scope", fields.scope);
173
+ const rule = need("rule", fields.rule);
174
+ const why = need("why (the reason an owner gave)", fields.why);
175
+ const holdsWhile = fields.holdsWhile !== undefined && squash(fields.holdsWhile) !== "" ? squash(fields.holdsWhile) : undefined;
176
+ const id = entryId({ kind, scope, rule, why, ...(holdsWhile ? { holdsWhile } : {}) });
177
+ const title = squash(fields.title ?? "") || defaultTitle(rule);
178
+ const candidate: Candidate = {
179
+ format: CANDIDATE_FORMAT,
180
+ id,
181
+ title,
182
+ kind,
183
+ scope,
184
+ rule,
185
+ why,
186
+ ...(holdsWhile ? { holdsWhile } : {}),
187
+ added: date,
188
+ evidence: [first],
189
+ };
190
+ const problem = candidateProblem(candidate);
191
+ if (problem) throw new UsageError(problem);
192
+ return candidate;
193
+ }
194
+
195
+ /** `candidate` with `more` evidence added once: the same source, reference and finding is not counted twice. */
196
+ export function withEvidence(candidate: Candidate, more: Evidence[]): Candidate {
197
+ const seen = new Set(candidate.evidence.map(evidenceKey));
198
+ const added: Evidence[] = [];
199
+ for (const e of more) {
200
+ if (seen.has(evidenceKey(e))) continue;
201
+ seen.add(evidenceKey(e));
202
+ added.push(e);
203
+ }
204
+ return { ...candidate, evidence: [...candidate.evidence, ...added] };
205
+ }
206
+
207
+ export interface Proposability {
208
+ proposable: boolean;
209
+ /** Evidence that counts for this kind of entry. */
210
+ counted: number;
211
+ /** Distinct pull requests or branches among it. */
212
+ distinct: number;
213
+ needed: number;
214
+ /** Why not, when it is not proposable. */
215
+ why?: string;
216
+ }
217
+
218
+ /**
219
+ * Spec decision 6: an explicit instruction is enough alone; a finding judged wrong or intentional, or
220
+ * fixed, needs `minEvidence` pieces from different pull requests or branches; a fix supports only a
221
+ * convention.
222
+ */
223
+ export function proposability(c: Candidate, minEvidence: number): Proposability {
224
+ const eligible = c.evidence.filter((e) => e.source !== "fixed" || c.kind === "convention");
225
+ const distinct = new Set(eligible.map(refKey)).size;
226
+ const base = { counted: eligible.length, distinct, needed: minEvidence };
227
+ if (eligible.some((e) => e.source === "instruction")) return { ...base, proposable: true };
228
+ if (distinct >= minEvidence) return { ...base, proposable: true };
229
+ const ignored = c.evidence.length - eligible.length;
230
+ const why = `needs evidence from ${minEvidence} different pull requests or branches, has ${distinct}${ignored > 0 ? "; a fix supports only a convention, so it does not count for an exception" : ""}`;
231
+ return { ...base, proposable: false, why };
232
+ }
233
+
234
+ const ID = /^[0-9a-f]{7}$/;
235
+
236
+ /** `<home>/memory-candidates/<repo key>`; the key is `repositoryKey(repoDir).key`. */
237
+ export const candidatesDir = (home: string, key: string) => join(home, "memory-candidates", key);
238
+
239
+ function privateDirs(...dirs: string[]) {
240
+ for (const dir of dirs) {
241
+ if (existsSync(dir)) continue;
242
+ mkdirSync(dir, { mode: 0o700 });
243
+ chmodSync(dir, 0o700);
244
+ }
245
+ }
246
+
247
+ const LOCK_WAIT_MS = 5_000;
248
+ const LOCK_STALE_MS = 30_000;
249
+
250
+ /**
251
+ * Runs `fn` while holding a lock on one candidate, so two runs that read, change and write the same
252
+ * candidate (`add` with new evidence, the `proposed` mark of `propose`) cannot drop each other's
253
+ * change. The lock is a directory made with `mkdir`, which is atomic; one left by a run that died is
254
+ * taken over after 30 seconds. Waiting longer than 5 seconds is a usage error, never a silent write.
255
+ */
256
+ export function withCandidateLock<T>(home: string, key: string, id: string, fn: () => T): T {
257
+ const dir = candidatesDir(home, key);
258
+ privateDirs(home, join(home, "memory-candidates"), dir);
259
+ const lock = join(dir, `${id}.lock`);
260
+ const deadline = Date.now() + LOCK_WAIT_MS;
261
+ for (;;) {
262
+ try {
263
+ mkdirSync(lock, { mode: 0o700 });
264
+ break;
265
+ } catch (error) {
266
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
267
+ try {
268
+ if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) rmSync(lock, { recursive: true, force: true });
269
+ } catch {
270
+ // Released between the two calls: try again.
271
+ }
272
+ if (Date.now() > deadline) throw new UsageError(`Another wachiman memory command is changing candidate ${id}; try again in a moment.`);
273
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);
274
+ }
275
+ }
276
+ try {
277
+ return fn();
278
+ } finally {
279
+ rmSync(lock, { recursive: true, force: true });
280
+ }
281
+ }
282
+
283
+ export function writeCandidate(home: string, key: string, c: Candidate): void {
284
+ const dir = candidatesDir(home, key);
285
+ privateDirs(home, join(home, "memory-candidates"), dir);
286
+ const path = join(dir, `${c.id}.json`);
287
+ const tmp = `${path}.tmp`;
288
+ const fd = openSync(tmp, "w", 0o600);
289
+ try {
290
+ writeSync(fd, `${JSON.stringify(c, null, 2)}\n`);
291
+ fsyncSync(fd);
292
+ } finally {
293
+ closeSync(fd);
294
+ }
295
+ chmodSync(tmp, 0o600);
296
+ renameSync(tmp, path);
297
+ }
298
+
299
+ function validCandidate(v: any): v is Candidate {
300
+ return (
301
+ v &&
302
+ typeof v === "object" &&
303
+ v.format === CANDIDATE_FORMAT &&
304
+ typeof v.id === "string" &&
305
+ ID.test(v.id) &&
306
+ typeof v.title === "string" &&
307
+ (v.kind === "convention" || v.kind === "exception") &&
308
+ typeof v.scope === "string" &&
309
+ typeof v.rule === "string" &&
310
+ typeof v.why === "string" &&
311
+ (v.holdsWhile === undefined || typeof v.holdsWhile === "string") &&
312
+ typeof v.added === "string" &&
313
+ Array.isArray(v.evidence) &&
314
+ v.evidence.every((e: any) => e && EVIDENCE_SOURCES.includes(e.source) && typeof e.date === "string" && typeof e.agent === "boolean" && (typeof e.pr === "number" || typeof e.branch === "string"))
315
+ );
316
+ }
317
+
318
+ /** The candidate with this id, or undefined. A malformed id is a usage error: it never reaches a path. */
319
+ export function readCandidate(home: string, key: string, id: string): Candidate | undefined {
320
+ if (!ID.test(id)) throw new UsageError(`"${id}" is not a memory entry id (seven hex characters).`);
321
+ const path = join(candidatesDir(home, key), `${id}.json`);
322
+ if (!existsSync(path)) return undefined;
323
+ let text: string;
324
+ try {
325
+ text = readFileSync(path, "utf8");
326
+ } catch (error) {
327
+ throw new UsageError(`cannot read ${path} (${error instanceof Error ? error.message : error}); check its permissions.`);
328
+ }
329
+ try {
330
+ const parsed = JSON.parse(text);
331
+ if (validCandidate(parsed) && parsed.id === id) {
332
+ const problem = candidateProblem(parsed);
333
+ if (problem) throw new UsageError(`${path}: ${problem}`);
334
+ return parsed;
335
+ }
336
+ } catch (error) {
337
+ if (error instanceof UsageError) throw error;
338
+ // fall through
339
+ }
340
+ throw new UsageError(`${path} is not a memory candidate; remove it to start that candidate again.`);
341
+ }
342
+
343
+ /**
344
+ * Every usable candidate of the repository, by id: the same checks `readCandidate` makes (the id is the
345
+ * file name, the text is terminal-safe and reads back as one entry). A file that fails them is not
346
+ * listed, so `candidates` never offers what `show` and `propose` refuse; `skipped` is told which files
347
+ * were left out and why, so that the listing can say so instead of hiding them.
348
+ */
349
+ export function readCandidates(home: string, key: string, skipped: (name: string, why: string) => void = () => {}): Candidate[] {
350
+ const dir = candidatesDir(home, key);
351
+ if (!existsSync(dir)) return [];
352
+ const out: Candidate[] = [];
353
+ for (const name of readdirSync(dir).sort()) {
354
+ if (!/^[0-9a-f]{7}\.json$/.test(name)) continue;
355
+ let parsed: unknown;
356
+ try {
357
+ parsed = JSON.parse(readFileSync(join(dir, name), "utf8"));
358
+ } catch (error) {
359
+ skipped(name, error instanceof SyntaxError ? "it is not JSON" : `it cannot be read (${error instanceof Error ? error.message : error})`);
360
+ continue;
361
+ }
362
+ if (!validCandidate(parsed)) {
363
+ skipped(name, "it is not a memory candidate");
364
+ continue;
365
+ }
366
+ if (`${parsed.id}.json` !== name) {
367
+ skipped(name, "its id is not its file name");
368
+ continue;
369
+ }
370
+ const problem = candidateProblem(parsed);
371
+ if (problem) {
372
+ skipped(name, problem);
373
+ continue;
374
+ }
375
+ out.push(parsed);
376
+ }
377
+ return out;
378
+ }
379
+
380
+ /**
381
+ * The evidence a finding in the local loop history supports, checked against the history rather than
382
+ * taken on trust: `judged` needs a `wrong` verdict with a reason; `fixed` needs the loop to have marked
383
+ * the finding probably fixed. The reference is `pr` when given, else the branch of the loop that saw it.
384
+ */
385
+ export function evidenceFromFinding(key: string, historyRoot: string, finding: string, source: "judged" | "fixed", opts: { pr?: number; agent: boolean; date: string }): Evidence {
386
+ let found: { branch: string; status: string } | undefined;
387
+ for (const path of loopFiles(historyRoot, key)) {
388
+ try {
389
+ const state = JSON.parse(readFileSync(path, "utf8"));
390
+ const entry = Array.isArray(state?.ledger) ? state.ledger.find((e: any) => e?.id === finding) : undefined;
391
+ if (entry && typeof state.branch === "string") {
392
+ found = { branch: state.branch, status: String(entry.status) };
393
+ if (source === "fixed" ? entry.status === "probably-fixed" : true) break;
394
+ }
395
+ } catch {
396
+ // an unreadable loop file is not evidence
397
+ }
398
+ }
399
+ if (!found) throw new UsageError(`No finding ${finding} in the loop history of this repository; run \`wachiman history\` to list the ids.`);
400
+ if (source === "judged") {
401
+ const verdict = readVerdicts(historyRoot, key).get(finding);
402
+ if (verdict?.verdict !== "wrong" || !verdict.reason?.trim()) {
403
+ throw new UsageError(`Finding ${finding} has no verdict "wrong" with a reason; record one first: wachiman history --verdict ${finding} wrong --reason "<why>".`);
404
+ }
405
+ } else if (found.status !== "probably-fixed") {
406
+ throw new UsageError(`The loop did not mark finding ${finding} as fixed (its status is ${found.status}), so it is not evidence.`);
407
+ }
408
+ return { date: opts.date, source, ...(opts.pr !== undefined ? { pr: opts.pr } : { branch: found.branch }), agent: opts.agent, finding };
409
+ }
410
+
411
+ /**
412
+ * Proposable candidates relevant to a loop round: one cites a finding of the round's ledger, or its
413
+ * scope matches the path of one. Never throws: the round's report does not depend on memory.
414
+ */
415
+ export function candidatesForRound(home: string, key: string, minEvidence: number, ledger: { id: string; path: string }[]): { id: string; title: string }[] {
416
+ try {
417
+ const ids = new Set(ledger.map((e) => e.id));
418
+ return readCandidates(home, key)
419
+ .filter((c) => !c.proposed && !c.personal && proposability(c, minEvidence).proposable)
420
+ .filter((c) => c.evidence.some((e) => e.finding !== undefined && ids.has(e.finding)) || ledger.some((e) => matchesGlob(c.scope, e.path)))
421
+ .map((c) => ({ id: c.id, title: c.title }));
422
+ } catch {
423
+ return [];
424
+ }
425
+ }