A self-organizing Obsidian vault that gives AI coding agents persistent memory.
TypeScript ai-agentsclaude-codecodex-cligemini-cliknowledge-managementobsidianobsidian-vaultpersistent-memorysecond-braintemplate
fix: report tidy-fix moves as fixed only when they succeed (#292)
Brenno Ferrarib8575bb12bd4
diff --git a/.claude/scripts/tests/tidy-fix.test.ts b/.claude/scripts/tests/tidy-fix.test.tsindex c74d4b3..9d9e702 100644--- a/.claude/scripts/tests/tidy-fix.test.ts+++ b/.claude/scripts/tests/tidy-fix.test.ts@@ -30,7 +30,11 @@ const SCRIPT = resolve(let ROOT = "";let MEMDIR = "";-function run(args: string[]): { stdout: string; code: number } {+function run(+ args: string[],+ root = ROOT,+ memDir = MEMDIR,+): { stdout: string; code: number } {const r = spawnSync(process.execPath,["--disable-warning=ExperimentalWarning", "--experimental-strip-types", SCRIPT, ...args],@@ -38,16 +42,29 @@ function run(args: string[]): { stdout: string; code: number } {encoding: "utf-8",env: {...process.env,- CLAUDE_PROJECT_DIR: ROOT,- TIDY_FIX_MEMORY_DIR: MEMDIR,+ CLAUDE_PROJECT_DIR: root,+ TIDY_FIX_MEMORY_DIR: memDir,},},);return { stdout: r.stdout ?? "", code: r.status ?? -1 };}-function note(rel: string, status: string, date: string): void {- const full = join(ROOT, rel);+/** The lines under one report heading, up to the next blank line. */+function section(stdout: string, heading: RegExp): string[] {+ const lines = stdout.split(/\r?\n/);+ const at = lines.findIndex((l) => heading.test(l));+ if (at === -1) return [];+ const out: string[] = [];+ for (const l of lines.slice(at + 1)) {+ if (l.trim() === "") break;+ out.push(l.trim());+ }+ return out;+}++function note(rel: string, status: string, date: string, root = ROOT): void {+ const full = join(root, rel);mkdirSync(dirname(full), { recursive: true });writeFileSync(full,@@ -145,3 +162,69 @@ describe("tidy-fix", () => {assert.match(stdout, /Refused \(judgment — run \/om-tidy\)/);});});++/**+ * "Fixed:" under --apply used to be written before the action ran and never+ * corrected, so a move that failed — or a stray that could not be read —+ * still printed as fixed, and an unreadable stray threw and ended the run.+ */+describe("tidy-fix — failures are reported as failed, never fixed", () => {+ let root = "";+ let mem = "";++ before(() => {+ root = mkdtempSync(join(tmpdir(), "tidy-fix-fail-"));+ mem = mkdtempSync(join(tmpdir(), "tidy-fix-fail-mem-"));+ note("work/active/Blocked.md", "completed", "2025-06-01", root);+ note("work/active/Movable.md", "completed", "2025-06-01", root);+ // The destination is a non-empty directory: neither git mv (no repo+ // here) nor a plain rename can put the note there.+ mkdirSync(join(root, "work/archive/2025/Blocked.md"), { recursive: true });+ writeFileSync(join(root, "work/archive/2025/Blocked.md/keep.txt"), "x");+ mkdirSync(join(root, "brain"), { recursive: true });+ writeFileSync(join(mem, "MEMORY.md"), "old index\n");+ // A directory with a markdown name: listed as a stray, unreadable.+ mkdirSync(join(mem, "unreadable.md"));+ writeFileSync(join(mem, "good.md"), "# good\n");+ });++ after(() => {+ rmTemp(root);+ rmTemp(mem);+ });++ test("a failed move and an unreadable stray land under Failed, the rest still go", () => {+ const { stdout, code } = run(["--apply"], root, mem);+ const fixed = section(stdout, /^Fixed:$/);+ const failed = section(stdout, /^Failed/);++ assert.ok(failed.some((l) => l.startsWith("work/active/Blocked.md →")), stdout);+ assert.ok(!fixed.some((l) => l.includes("Blocked.md")), stdout);+ assert.ok(existsSync(join(root, "work/active/Blocked.md")));++ assert.ok(failed.some((l) => l.startsWith("memory/unreadable.md →")), stdout);+ assert.ok(!fixed.some((l) => l.includes("unreadable.md")), stdout);++ // The run did not stop at the first failure.+ assert.ok(fixed.some((l) => l.startsWith("work/active/Movable.md →")), stdout);+ assert.ok(existsSync(join(root, "work/archive/2025/Movable.md")));+ assert.ok(fixed.some((l) => l.startsWith("memory/good.md →")), stdout);+ assert.equal(readFileSync(join(root, "brain/good.md"), "utf-8"), "# good\n");++ assert.equal(code, 1, "a failed fix must not exit clean");+ });++ test("dry-run still lists every planned fix and exits 0", () => {+ const r = mkdtempSync(join(tmpdir(), "tidy-fix-dry-"));+ try {+ note("work/active/Blocked.md", "completed", "2025-06-01", r);+ mkdirSync(join(r, "work/archive/2025/Blocked.md"), { recursive: true });+ const { stdout, code } = run([], r, mem);+ assert.equal(code, 0);+ assert.ok(section(stdout, /^Would fix:$/).some((l) => l.startsWith("work/active/Blocked.md →")));+ assert.deepEqual(section(stdout, /^Failed/), []);+ } finally {+ rmTemp(r);+ }+ });+});diff --git a/.claude/scripts/tidy-fix.ts b/.claude/scripts/tidy-fix.tsindex 3e0f002..74532a0 100644--- a/.claude/scripts/tidy-fix.ts+++ b/.claude/scripts/tidy-fix.ts@@ -27,6 +27,10 @@* Dry-run by default; pass --apply to act. Idempotent: fixed findings stop* being findings, so a second run reports nothing.*+ * Under --apply, "Fixed:" lists only actions that succeeded. One that failed+ * is listed under "Failed:", its source left in place, and the process exits+ * 1 — cron output must never read as clean when something was not done.+ ** Usage:* node --experimental-strip-types .claude/scripts/tidy-fix.ts [--apply]*@@ -66,11 +70,29 @@ import { resolveProjectDir } from "./lib/project-dir.ts";const ACTIVE_REL = "work/active";type Report = {+ /** Dry-run: what would be done. Apply: what WAS done, verified. */readonly fixed: string[];+ /** Apply only: attempted and not done; the source is left in place. */+ readonly failed: string[];readonly refused: string[];readonly notes: string[];};+/**+ * Record one deterministic fix. In dry-run the line is a plan; under+ * --apply it is an outcome, so it is filed by what `act` actually returned.+ */+function recordFix(+ report: Report,+ apply: boolean,+ line: string,+ act: () => boolean,+): void {+ if (!apply) report.fixed.push(line);+ else if (act()) report.fixed.push(line);+ else report.failed.push(line);+}+/** Claude Code's project slug: POSIX path with separators dashed. */function deriveMemoryDir(vaultRoot: string): string | null {const override = process.env["TIDY_FIX_MEMORY_DIR"];@@ -88,7 +110,12 @@ function moveTracked(relDest: string,notes: string[],): boolean {- mkdirSync(join(vaultRoot, dirname(relDest)), { recursive: true });+ try {+ mkdirSync(join(vaultRoot, dirname(relDest)), { recursive: true });+ } catch {+ notes.push(` could not create ${dirname(relDest)}/ — ${relSrc} left in place`);+ return false;+ }const git = spawnSync("git", ["mv", relSrc, relDest], {cwd: vaultRoot,encoding: "utf-8",@@ -135,8 +162,9 @@ function fixCompletedInActive(if (slash === -1) {const year = archiveYear(vaultRoot, rel);const dest = `work/archive/${year}/${inside}`;- report.fixed.push(`${rel} → ${dest}`);- if (apply) moveTracked(vaultRoot, rel, dest, report.notes);+ recordFix(report, apply, `${rel} → ${dest}`, () =>+ moveTracked(vaultRoot, rel, dest, report.notes),+ );report.notes.push(` move its row in work/Index.md (${basename(rel)})`);continue;}@@ -165,8 +193,9 @@ function fixCompletedInActive(}const year = [...years][0] as string;const dest = `work/archive/${year}/${topic}`;- report.fixed.push(`${clusterRel}/ → ${dest}/ (whole cluster)`);- if (apply) moveTracked(vaultRoot, clusterRel, dest, report.notes);+ recordFix(report, apply, `${clusterRel}/ → ${dest}/ (whole cluster)`, () =>+ moveTracked(vaultRoot, clusterRel, dest, report.notes),+ );report.notes.push(` move its row in work/Index.md (${topic})`);}}@@ -202,22 +231,29 @@ function fixMisplacedMemory();continue;}- report.fixed.push(`memory/${stray} → brain/${stray} (copy, verify, remove)`);report.notes.push(` review brain/${stray} before committing — auto-memory content can be personal, and brain/ is repo-tracked`,);- if (!apply) continue;- const content = readFileSync(join(memDir, stray), "utf-8");- mkdirSync(join(vaultRoot, "brain"), { recursive: true });- writeFileSync(target, content);- const copied = readFileSync(target, "utf-8");- if (copied !== content) {- report.notes.push(- ` VERIFY FAILED for ${stray} — stray left in place, copy left for inspection`,- );- continue;- }- migrated++;+ // Each stray is its own unit: one that cannot be read or written is+ // reported as failed, and the rest still migrate.+ recordFix(report, apply, `memory/${stray} → brain/${stray} (copy, verify, remove)`, () => {+ try {+ const content = readFileSync(join(memDir, stray), "utf-8");+ mkdirSync(join(vaultRoot, "brain"), { recursive: true });+ writeFileSync(target, content);+ if (readFileSync(target, "utf-8") !== content) {+ report.notes.push(+ ` VERIFY FAILED for ${stray} — stray left in place, copy left for inspection`,+ );+ return false;+ }+ } catch {+ report.notes.push(` could not copy memory/${stray} — stray left in place`);+ return false;+ }+ migrated++;+ return true;+ });}if (apply && migrated > 0) {// Regenerate the index from brain/ (now including the migrated notes),@@ -281,7 +317,7 @@ function main(): void {parseMemoryRoot(manifestJson),);- const report: Report = { fixed: [], refused: [], notes: [] };+ const report: Report = { fixed: [], failed: [], refused: [], notes: [] };fixCompletedInActive(vaultRoot, scan.completedInActive, apply, report);fixMisplacedMemory(vaultRoot, apply, report);@@ -308,7 +344,11 @@ function main(): void {const mode = apply ? "APPLIED" : "DRY-RUN (pass --apply to act)";console.log(`tidy-fix — ${mode}`);- if (report.fixed.length === 0 && report.refused.length === 0) {+ if (+ report.fixed.length === 0 &&+ report.failed.length === 0 &&+ report.refused.length === 0+ ) {console.log("nothing to do — vault is clean.");return;}@@ -316,6 +356,11 @@ function main(): void {console.log(apply ? "\nFixed:" : "\nWould fix:");for (const f of report.fixed) console.log(` ${f}`);}+ if (report.failed.length > 0) {+ console.log("\nFailed (left in place — see Notes):");+ for (const f of report.failed) console.log(` ${f}`);+ process.exitCode = 1;+ }if (report.refused.length > 0) {console.log("\nRefused (judgment — run /om-tidy):");for (const r of report.refused) console.log(` ${r}`);