Skip to content

A self-organizing Obsidian vault that gives AI coding agents persistent memory.

36.4 KB
Raw Blame
/**
 * Unit tests for lib/active-hygiene.ts — the drift detectors behind the
 * SessionStart/Stop hygiene section and validate-write's write-time flags.
 * Temp-dir fixtures with utimesSync-backdated mtimes; `now` is injected so
 * age thresholds are deterministic.
 */

import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import {
	existsSync,
	mkdirSync,
	readdirSync,
	mkdtempSync,
	rmSync,
	symlinkSync,
	utimesSync,
	writeFileSync,
} from "node:fs";
import { dirname, join } from "node:path";
import { tmpdir } from "node:os";
import {
	HYGIENE_LIST_CAP,
	HYGIENE_VOLATILE_FIELDS,
	MONOLITH_BYTES,
	OPEN_LOOP_DAYS,
	countOpenLoops,
	formatActiveHygiene,
	formatClusterHint,
	formatMonolithHint,
	namesCapped,
	isMonolithExempt,
	newNoteClusterCandidate,
	parseMemoryRoot,
	parseOpenLoopConfig,
	scanActiveHygiene,
	stripJsonComments,
	walkMarkdown,
} from "../lib/active-hygiene.ts";

import { AGENTS_MD_FLAG_BYTES, AGENTS_MD_MAX_BYTES } from "../lib/instruction-files.ts";
import { reportKey } from "../lib/report-key.ts";
import { rmTemp } from "./_helpers.ts";

const DAY_MS = 24 * 60 * 60 * 1000;
const NOW = Date.UTC(2026, 6, 13);
const DEFAULTS = parseOpenLoopConfig(null);

let ROOT: string;

function writeAged(rel: string, content: string, ageDays: number): void {
	const full = join(ROOT, rel);
	writeFileSync(full, content);
	const t = new Date(NOW - ageDays * DAY_MS);
	utimesSync(full, t, t);
}

before(() => {
	ROOT = mkdtempSync(join(tmpdir(), "active-hygiene-test-"));
	for (const d of [
		"work/active/Grouped Topic",
		"work/1-1",
		"work/meetings",
		"work/incidents",
		"templates",
	]) {
		mkdirSync(join(ROOT, d), { recursive: true });
	}
});

after(() => {
	rmTemp(ROOT);
});

describe("parseOpenLoopConfig", () => {
	test("defaults when manifest is null or lacks the fields", () => {
		const cfg = parseOpenLoopConfig(null);
		assert.deepEqual(cfg.dirs, ["work/1-1", "work/meetings", "work/incidents"]);
		assert.equal(cfg.sectionRe.test("## Action Items"), true);
		assert.equal(cfg.sectionRe.test("### What to Watch"), true);
		assert.equal(cfg.sectionRe.test("## Notes"), false);
	});
	test("manifest overrides both dirs and sections", () => {
		const cfg = parseOpenLoopConfig(
			JSON.stringify({
				open_loop_dirs: ["people", "outreach"],
				open_loop_sections: ["next steps"],
			}),
		);
		assert.deepEqual(cfg.dirs, ["people", "outreach"]);
		assert.equal(cfg.sectionRe.test("## Next Steps"), true);
		assert.equal(cfg.sectionRe.test("## Action Items"), false);
	});
	test("rejects traversal-shaped dirs: absolute, dot-dot, backslash, drive-letter", () => {
		const cfg = parseOpenLoopConfig(
			JSON.stringify({
				open_loop_dirs: ["../outside", "/etc", "C:evil", "ok/dir", "a\\b", "x/../y"],
			}),
		);
		assert.deepEqual(cfg.dirs, ["ok/dir"]);
		const allBad = parseOpenLoopConfig(
			JSON.stringify({ open_loop_dirs: ["../a", "/b"] }),
		);
		assert.deepEqual(allBad.dirs, ["work/1-1", "work/meetings", "work/incidents"]);
	});

	test("malformed values fall back to defaults (incl. regex metachars escaped)", () => {
		const cfg = parseOpenLoopConfig(
			JSON.stringify({ open_loop_dirs: [], open_loop_sections: [42] }),
		);
		assert.deepEqual(cfg.dirs, ["work/1-1", "work/meetings", "work/incidents"]);
		const meta = parseOpenLoopConfig(
			JSON.stringify({ open_loop_sections: ["a.b (c)"] }),
		);
		assert.equal(meta.sectionRe.test("## a.b (c)"), true);
		assert.equal(meta.sectionRe.test("## aXb (c)"), false);
	});
});

describe("countOpenLoops", () => {
	test("counts unchecked boxes only inside configured sections", () => {
		const note = [
			"# 1:1",
			"## Action Items",
			"- [ ] chase reply",
			"- [x] done thing",
			"## Notes",
			"- [ ] checkbox outside a follow-up section",
		].join("\n");
		assert.equal(countOpenLoops(note, DEFAULTS.sectionRe), 1);
	});
	test("counts waiting-on / watch-for phrase lines anywhere", () => {
		assert.equal(
			countOpenLoops("waiting on legal\nWatch for the rollout\n", DEFAULTS.sectionRe),
			2,
		);
	});
	test("clean note counts zero", () => {
		assert.equal(countOpenLoops("# all wrapped\n", DEFAULTS.sectionRe), 0);
	});
});

describe("scanActiveHygiene — detectors", () => {
	test("flags completed notes in active/ (recursively), ignores active ones", () => {
		writeAged(
			"work/active/Live Project.md",
			"---\nstatus: active\n---\n# live\n",
			1,
		);
		writeAged(
			"work/active/Grouped Topic/Done Sub.md",
			"---\nstatus: completed\n---\n# done\n",
			1,
		);
		const report = scanActiveHygiene(ROOT, NOW, DEFAULTS);
		assert.deepEqual(report.completedInActive, [
			"work/active/Grouped Topic/Done Sub.md",
		]);
	});

	test("clusters loose root notes sharing a distinctive token; DF guard rejects common words", () => {
		for (const f of [
			"Payments Migration.md",
			"Payments Rollout.md",
			"Hiring Loop.md",
			"Vendor Selection.md",
			"Quarterly Budget.md",
		]) {
			writeAged(`work/active/${f}`, "# x\n", 1);
		}
		const report = scanActiveHygiene(ROOT, NOW, DEFAULTS);
		const tokens = report.ungroupedClusters.map((c) => c.token);
		assert.ok(tokens.includes("payments"), `expected payments in ${tokens}`);
		// Subfoldered notes never cluster; a token in >half the root is rejected.
		for (const c of report.ungroupedClusters) {
			assert.ok(!c.files.some((f) => f.includes("/")));
		}
	});

	test("flags oversized notes vault-wide, exempts Archive names and skip dirs", () => {
		writeAged("work/Fat Log.md", "x".repeat(MONOLITH_BYTES + 1000), 1);
		writeAged("work/Fat Log Archive.md", "x".repeat(60_000), 1);
		writeAged("templates/Huge Template.md", "x".repeat(60_000), 1);
		const report = scanActiveHygiene(ROOT, NOW, DEFAULTS);
		const paths = report.oversizedNotes.map((o) => o.path);
		assert.ok(paths.includes("work/Fat Log.md"));
		assert.ok(!paths.some((p) => p.includes("Archive")));
		assert.ok(!paths.some((p) => p.startsWith("templates/")));
	});

	test("open loops: quiet notes with live signals flagged; 1:1 dirs reduce to latest per person", () => {
		writeAged(
			"work/1-1/Alice 2026-05-01.md",
			"## Action Items\n- [ ] old carried item\n",
			70,
		);
		writeAged(
			"work/1-1/Alice 2026-06-20.md",
			"## Action Items\n- [ ] current item\n",
			23,
		);
		writeAged("work/incidents/Payment Outage.md", "watch for regression\n", 30);
		writeAged("work/meetings/Fresh Sync.md", "waiting on vendor\n", 2);
		const report = scanActiveHygiene(ROOT, NOW, DEFAULTS);
		const paths = report.openLoops.map((l) => l.path);
		assert.ok(paths.includes("work/1-1/Alice 2026-06-20.md"));
		assert.ok(!paths.includes("work/1-1/Alice 2026-05-01.md")); // older 1:1 skipped
		assert.ok(paths.includes("work/incidents/Payment Outage.md"));
		assert.ok(!paths.includes("work/meetings/Fresh Sync.md")); // too fresh
		// Oldest first.
		const ages = report.openLoops.map((l) => l.ageDays);
		assert.deepEqual(ages, [...ages].sort((a, b) => b - a));
	});

	test("overlapping configured dirs do not double-count a file", () => {
		const cfg = parseOpenLoopConfig(
			JSON.stringify({ open_loop_dirs: ["work", "work/incidents"] }),
		);
		const report = scanActiveHygiene(ROOT, NOW, cfg);
		const hits = report.openLoops.filter(
			(l) => l.path === "work/incidents/Payment Outage.md",
		);
		assert.equal(hits.length, 1);
	});

	test("meetings-inbox pressure counts week-old raw exports", () => {
		writeAged("work/meetings/2026-06-01 Raw Export.md", "raw dump", 40);
		const report = scanActiveHygiene(ROOT, NOW, DEFAULTS);
		assert.ok(report.inboxPressure !== null);
		assert.ok(report.inboxPressure!.count >= 1);
		assert.ok(report.inboxPressure!.oldestDays >= 40);
	});

	test("the shipped inbox README never counts as pressure (#155)", () => {
		// Isolated root: the shared fixture already holds a real export, and
		// the point here is what an *untouched* inbox reports.
		const solo = mkdtempSync(join(tmpdir(), "active-hygiene-scaffold-"));
		try {
			mkdirSync(join(solo, "work/meetings"), { recursive: true });
			const scaffold = join(solo, "work/meetings/README.md");
			writeFileSync(scaffold, "# Meeting Notes Inbox\n\nDrop exports here.\n");
			// Well past the 7-day threshold — the age the flag kept climbing to.
			const t = new Date(NOW - 96 * DAY_MS);
			utimesSync(scaffold, t, t);

			// The bug: an inbox holding nothing but its own scaffold flagged
			// forever, and /om-intake could never clear it.
			assert.equal(scanActiveHygiene(solo, NOW, DEFAULTS).inboxPressure, null);

			// …while a genuine export beside it still counts, and counts once.
			const real = join(solo, "work/meetings/2026-04-01 Standup.md");
			writeFileSync(real, "raw dump");
			utimesSync(real, t, t);
			const withExport = scanActiveHygiene(solo, NOW, DEFAULTS).inboxPressure;
			assert.ok(withExport !== null);
			assert.equal(withExport!.count, 1);
		} finally {
			rmTemp(solo);
		}
	});

	test("the cross-repo memory inbox is counted, nested under year and month", () => {
		const solo = mkdtempSync(join(tmpdir(), "active-hygiene-memories-"));
		try {
			mkdirSync(join(solo, "memories/2026/07"), { recursive: true });
			const a = join(solo, "memories/2026/07/a lesson.md");
			writeFileSync(a, "captured");
			const t = new Date(NOW - 3 * DAY_MS);
			utimesSync(a, t, t);

			// The defect this closes: every other scan here is flat, and the server
			// writes two levels down, so a flat walk reports an empty inbox forever.
			const found = scanActiveHygiene(solo, NOW, DEFAULTS).memoryInbox;
			assert.ok(found !== null);
			assert.equal(found!.count, 1);
			assert.equal(found!.oldestDays, 3);
		} finally {
			rmTemp(solo);
		}
	});

	test("a memory capture counts the moment it lands — no age threshold", () => {
		const solo = mkdtempSync(join(tmpdir(), "active-hygiene-memories-fresh-"));
		try {
			mkdirSync(join(solo, "memories/2026/07"), { recursive: true });
			writeFileSync(join(solo, "memories/2026/07/brand new.md"), "captured");
			// Undrained because nobody has judged it, which is true immediately.
			assert.equal(scanActiveHygiene(solo, NOW, DEFAULTS).memoryInbox?.count, 1);
		} finally {
			rmTemp(solo);
		}
	});

	test("a shipped README in the memory tree is not a capture", () => {
		const solo = mkdtempSync(join(tmpdir(), "active-hygiene-memories-readme-"));
		try {
			mkdirSync(join(solo, "memories/2026/07"), { recursive: true });
			writeFileSync(join(solo, "memories/2026/07/README.md"), "how this folder works");
			// Same permanently-unclearable trap the meetings scaffold already fixed.
			assert.equal(scanActiveHygiene(solo, NOW, DEFAULTS).memoryInbox, null);
		} finally {
			rmTemp(solo);
		}
	});

	test("a declared memory_root is honoured, and the default is not hard-coded", () => {
		const solo = mkdtempSync(join(tmpdir(), "active-hygiene-memories-root-"));
		try {
			mkdirSync(join(solo, "elsewhere/2026/07"), { recursive: true });
			writeFileSync(join(solo, "elsewhere/2026/07/a lesson.md"), "captured");
			assert.equal(scanActiveHygiene(solo, NOW, DEFAULTS).memoryInbox, null);
			assert.equal(
				scanActiveHygiene(solo, NOW, DEFAULTS, [], parseMemoryRoot('{"memory_root":"elsewhere"}'))
					.memoryInbox?.count,
				1,
			);
		} finally {
			rmTemp(solo);
		}
	});

	// The flag has to be able to reach zero. Promotion is additive, so the entry
	// stays; without a marker the count could only ever grow, which is the
	// permanently-unclearable failure #155 already fixed once.
	test("a promoted capture stops counting, so the flag can clear", () => {
		const solo = mkdtempSync(join(tmpdir(), "active-hygiene-memories-promoted-"));
		try {
			mkdirSync(join(solo, "memories/2026/07"), { recursive: true });
			const rel = "memories/2026/07/a lesson.md";
			writeFileSync(join(solo, rel), "---\nscope: general\n---\n\n# a lesson\n");
			assert.equal(scanActiveHygiene(solo, NOW, DEFAULTS).memoryInbox?.count, 1);

			writeFileSync(
				join(solo, rel),
				'---\nscope: general\npromoted: "brain/Gotchas"\n---\n\n# a lesson\n',
			);
			assert.equal(scanActiveHygiene(solo, NOW, DEFAULTS).memoryInbox, null);
		} finally {
			rmTemp(solo);
		}
	});

	/**
	 * The gradient the count creates (#183).
	 *
	 * Clearing the flag and SERVING the lesson are different achievements, and a
	 * bare marker buys the first for less work than the second. Hygiene reports
	 * the split so the cheaper form is visible — but it must never gate on it, or
	 * the flag stops being able to reach zero.
	 */
	test("a bare marker is counted as named-only, and never revives the flag", () => {
		const solo = mkdtempSync(join(tmpdir(), "active-hygiene-memories-namedonly-"));
		try {
			mkdirSync(join(solo, "memories/2026/07"), { recursive: true });
			writeFileSync(
				join(solo, "memories/2026/07/bare.md"),
				'---\nscope: general\npromoted: "brain/Gotchas"\n---\n\n# bare\n',
			);
			writeFileSync(
				join(solo, "memories/2026/07/anchored.md"),
				'---\nscope: general\npromoted: "brain/Gotchas#^om-a1b2c3"\n---\n\n# anchored\n',
			);

			// Both are promoted, so there is no pressure at all — the flag reaches
			// zero exactly as before, which is the invariant #155 established.
			assert.equal(scanActiveHygiene(solo, NOW, DEFAULTS).memoryInbox, null);

			// Add one UNpromoted capture: the flag fires, and the split rides on it
			// as a detail rather than as a second warning of its own.
			writeFileSync(join(solo, "memories/2026/07/fresh.md"), "---\nscope: general\n---\n\n# fresh\n");
			const inbox = scanActiveHygiene(solo, NOW, DEFAULTS).memoryInbox;
			assert.equal(inbox?.count, 1, "only the unpromoted capture is pressure");
			assert.equal(inbox?.namedOnly, 1, "the bare marker counts, the anchored one does not");

			const text = formatActiveHygiene(scanActiveHygiene(solo, NOW, DEFAULTS)).join("\n");
			assert.match(text, /1 already-promoted capture\(s\) here carry a bare marker/);
		} finally {
			rmTemp(solo);
		}
	});

	test("quoting does not change the verdict — the writer stamps a YAML scalar", () => {
		// The capture writer emits `promoted: 'brain/X#^id'`, and hand-promotion
		// writes all three forms below. The count must not depend on which.
		//
		// This does NOT prove the quote stripping in `promotionOf`: an unstripped
		// `"brain/G#^om-a1"` still splits at the `#` and still reads as anchored,
		// so the verdict is identical either way. The stripping is there so the
		// returned ref's `note` is a real path rather than `"brain/G` — which no
		// caller reads today and every caller would assume tomorrow. What this
		// guards is the count, across the forms actually written.
		const solo = mkdtempSync(join(tmpdir(), "active-hygiene-memories-quoted-"));
		try {
			mkdirSync(join(solo, "memories/2026/07"), { recursive: true });
			writeFileSync(join(solo, "memories/2026/07/x.md"), "---\nscope: general\n---\n\n# x\n");
			for (const marker of ["'brain/G#^om-a1'", '"brain/G#^om-a1"', "brain/G#^om-a1"]) {
				writeFileSync(
					join(solo, "memories/2026/07/q.md"),
					`---\nscope: general\npromoted: ${marker}\n---\n\n# q\n`,
				);
				assert.equal(
					scanActiveHygiene(solo, NOW, DEFAULTS).memoryInbox?.namedOnly,
					0,
					`anchored, however quoted: ${marker}`,
				);
			}
		} finally {
			rmTemp(solo);
		}
	});

	test("an empty or misplaced promoted marker does not silence a capture", () => {
		const solo = mkdtempSync(join(tmpdir(), "active-hygiene-memories-badmark-"));
		try {
			mkdirSync(join(solo, "memories/2026/07"), { recursive: true });
			// A bare key with no value is not a promotion record and must not hide
			// a capture from review.
			writeFileSync(join(solo, "memories/2026/07/x.md"), "---\npromoted:\n---\n\n# x\n");
			assert.equal(scanActiveHygiene(solo, NOW, DEFAULTS).memoryInbox?.count, 1);
			// Nor may the word appearing in the BODY rather than the frontmatter.
			writeFileSync(join(solo, "memories/2026/07/y.md"), "# y\n\npromoted: brain/Thing\n");
			assert.equal(scanActiveHygiene(solo, NOW, DEFAULTS).memoryInbox?.count, 2);
		} finally {
			rmTemp(solo);
		}
	});

	test("the memory-inbox line says COPY, never delete", () => {
		const lines = formatActiveHygiene({
			completedInActive: [],
			ungroupedClusters: [],
			oversizedNotes: [],
			openLoops: [],
			inboxPressure: null,
			memoryInbox: { count: 4, oldestDays: 2, namedOnly: 0 },
			leftoverInstructionFiles: [],
			geminiSettingsBroken: false,
			agentsMd: null,
		});
		const text = lines.join("\n");
		assert.match(text, /COPYING it/);
		// The ANCHORED form is what the prompt must teach: a bare marker clears
		// this very count while serving nothing, so a warning that showed only
		// the bare form would be steering the reader to the useless one.
		assert.match(text, /promoted: "brain\/Note#\^om-a1b2c3"/);
		assert.match(text, /a bare `promoted: <note>` clears this count but serves nothing/);
		assert.doesNotMatch(text, /om-intake/);
	});

	test("each previously uncapped hygiene list prints ten entries, then a count of the rest (#254)", () => {
		const report = (n: number) =>
			formatActiveHygiene({
				completedInActive: Array.from({ length: n }, (_, i) => `work/active/Done ${i}.md`),
				ungroupedClusters: Array.from({ length: n }, (_, i) => ({ token: `topic${i}`, files: ["a.md", "b.md"] })),
				oversizedNotes: Array.from({ length: n }, (_, i) => ({ path: `notes/Big ${i}.md`, sizeKb: 30 })),
				openLoops: [],
				inboxPressure: null,
				memoryInbox: null,
				leftoverInstructionFiles: [],
				geminiSettingsBroken: false,
				agentsMd: null,
			});
		const atCap = report(HYGIENE_LIST_CAP);
		assert.equal(atCap.filter((l) => l.startsWith("   - ")).length, 3 * HYGIENE_LIST_CAP);
		assert.ok(!atCap.some((l) => l.includes("more")), "a full list at the cap gets no count line");

		const over = report(HYGIENE_LIST_CAP + 1).join("\n");
		assert.match(over, /11 note\(s\) marked done/, "the headline keeps the full count");
		assert.match(over, /11 note\(s\) past the/);
		assert.equal(over.match(/^ {3}- … and 1 more$/gm)?.length, 3, "one count line per list");
		assert.doesNotMatch(over, /Done 10\.md|topic10|Big 10\.md/);
	});

	test("a cluster's file names are capped on its line and in the write-time hint (#254)", () => {
		const files = Array.from({ length: HYGIENE_LIST_CAP + 3 }, (_, i) => `n${i}.md`);
		assert.equal(namesCapped(files.slice(0, HYGIENE_LIST_CAP)), files.slice(0, HYGIENE_LIST_CAP).join(", "));
		assert.match(namesCapped(files), /, n9\.md, … and 3 more$/);
		const hint = formatClusterHint({ token: "topic", files });
		assert.match(hint, /joins 12 loose sibling\(s\)/, "the count stays whole");
		assert.match(hint, /… and 3 more\./);
		assert.doesNotMatch(hint, /n10\.md/);
	});

	test("missing folders produce an empty report, not errors", () => {
		const empty = mkdtempSync(join(tmpdir(), "active-hygiene-empty-"));
		try {
			const report = scanActiveHygiene(empty, NOW, DEFAULTS);
			assert.deepEqual(report.completedInActive, []);
			assert.deepEqual(report.ungroupedClusters, []);
			assert.deepEqual(report.oversizedNotes, []);
			assert.deepEqual(report.openLoops, []);
			assert.equal(report.inboxPressure, null);
			assert.deepEqual(formatActiveHygiene(report), []);
		} finally {
			rmTemp(empty);
		}
	});
});

describe("write-time detectors", () => {
	test("newNoteClusterCandidate fires for a loose root note in a cluster, not for subfoldered or outside paths", () => {
		const hit = newNoteClusterCandidate(
			join(ROOT, "work/active/Payments Migration.md"),
			ROOT,
		);
		assert.ok(hit !== null && hit.token === "payments");
		assert.equal(
			newNoteClusterCandidate(
				join(ROOT, "work/active/Grouped Topic/Done Sub.md"),
				ROOT,
			),
			null,
		);
		assert.equal(
			newNoteClusterCandidate(join(ROOT, "brain/Patterns.md"), ROOT),
			null,
		);
	});

	test("hints carry the judgment framing", () => {
		const hint = formatClusterHint({
			token: "payments",
			files: ["Payments A.md", "Payments B.md"],
		});
		assert.match(hint, /Token overlap is BLIND/);
		assert.match(hint, /active\/<Topic>\//);
		const mono = formatMonolithHint("work/Fat.md", 42_000);
		assert.match(mono, /Do NOT trim/);
		assert.match(mono, /42KB/);
	});

	test("isMonolithExempt covers Archive names only", () => {
		assert.equal(isMonolithExempt("Delivery Log Archive.md"), true);
		assert.equal(isMonolithExempt("Delivery Log.md"), false);
	});
});

describe("walkMarkdown", () => {
	test("recurses into subfolders and tolerates missing dirs", () => {
		const files = walkMarkdown(ROOT, "work/active");
		assert.ok(files.includes("work/active/Grouped Topic/Done Sub.md"));
		assert.deepEqual(walkMarkdown(ROOT, "no/such/dir"), []);
	});
});

describe("formatActiveHygiene", () => {
	test("renders one block per drift mode, silent segments omitted", () => {
		const lines = formatActiveHygiene({
			completedInActive: ["work/active/Done.md"],
			ungroupedClusters: [],
			oversizedNotes: [{ path: "work/Fat.md", sizeKb: 40 }],
			openLoops: [{ path: "work/1-1/A 2026-01-01.md", ageDays: 20, openItems: 2 }],
			inboxPressure: null,
			memoryInbox: null,
			leftoverInstructionFiles: [],
			geminiSettingsBroken: false,
			agentsMd: null,
		});
		const text = lines.join("\n");
		assert.match(text, /marked done but still in active\//);
		assert.match(text, /SPLIT/);
		assert.match(text, new RegExp(`${OPEN_LOOP_DAYS}\\+ days`));
		assert.doesNotMatch(text, /om-intake/); // silent segment omitted
	});
});

describe("open loops — a capped list keeps its membership as time passes", () => {
	test("two loops that floor to the same day do not swap across the cap hours later", () => {
		// Ages 20.9d and 20.1d both floor to 20 and tie; twelve hours later they
		// floor to 21 and 20. Sorted on floored days, which loop takes the last
		// slot flips with nothing new; on raw time the older one always wins.
		const root = mkdtempSync(join(tmpdir(), "open-loop-cap-"));
		try {
			const day = 24 * 60 * 60 * 1000;
			const now = Date.UTC(2026, 6, 13);
			const aged = (rel: string, ageDays: number) => {
				const full = join(root, rel);
				mkdirSync(dirname(full), { recursive: true });
				writeFileSync(full, "watch for regression\n");
				const t = new Date(now - ageDays * day);
				utimesSync(full, t, t);
			};
			for (const n of ["One", "Two", "Three", "Four"]) aged(`work/incidents/${n}.md`, 40);
			aged(`work/incidents/Zed.md`, 20.9);
			aged(`work/incidents/Abe.md`, 20.1);
			const at = (t: number) => ((r: string, t: number) => scanActiveHygiene(r, t, DEFAULTS))(root, t).openLoops.map((l) => l.path).sort();
			assert.deepEqual(at(now), at(now + day / 2));
			assert.ok(at(now).includes(`work/incidents/Zed.md`));
		} finally {
			rmSync(root, { recursive: true, force: true });
		}
	});
});

describe("leftover CLAUDE.md beside AGENTS.md (#321)", () => {
	// A vault upgraded past the single-instruction-file release keeps a
	// CLAUDE.md the user edited (their bytes survive the update). Claude Code
	// then reads CLAUDE.md and silently skips AGENTS.md, so the hygiene scan
	// says so at every session boundary until it is moved out.
	const withFiles = (names: readonly string[], run: (root: string) => void): void => {
		const root = mkdtempSync(join(tmpdir(), "leftover-claude-md-"));
		try {
			for (const n of names) writeFileSync(join(root, n), "# Vault\n");
			run(root);
		} finally {
			rmTemp(root);
		}
	};

	test("flags a CLAUDE.md sitting beside AGENTS.md, with what to do about it", () => {
		withFiles(["AGENTS.md", "CLAUDE.md"], (root) => {
			const report = scanActiveHygiene(root, NOW, DEFAULTS);
			assert.equal(report.leftoverInstructionFiles.includes("CLAUDE.md"), true);
			const text = formatActiveHygiene(report).join("\n");
			assert.match(
				text,
				/CLAUDE\.md present beside AGENTS\.md — Claude Code reads CLAUDE\.md and skips AGENTS\.md; move your additions to \.claude\/rules\/ and delete it\./,
			);
		});
	});

	/** Write .gemini/settings.json with the given context.fileName (or none). */
	const geminiSettings = (root: string, fileName?: string[]): void => {
		mkdirSync(join(root, ".gemini"), { recursive: true });
		writeFileSync(join(root, ".gemini/settings.json"), JSON.stringify(fileName ? { context: { fileName } } : { hooks: {} }));
	};

	test("flags a GEMINI.md beside AGENTS.md once Gemini's settings point it at AGENTS.md, so GEMINI.md is never loaded", () => {
		withFiles(["AGENTS.md", "GEMINI.md"], (root) => {
			geminiSettings(root, ["AGENTS.md"]);
			const report = scanActiveHygiene(root, NOW, DEFAULTS);
			assert.deepEqual(report.leftoverInstructionFiles, ["GEMINI.md"], "a GEMINI.md is not a leftover CLAUDE.md");
			assert.match(formatActiveHygiene(report).join("\n"), /GEMINI\.md present beside AGENTS\.md — Gemini no longer reads GEMINI\.md/);
		});
		withFiles(["AGENTS.md", "CLAUDE.md"], (root) => {
			geminiSettings(root, ["AGENTS.md"]);
			assert.deepEqual(scanActiveHygiene(root, NOW, DEFAULTS).leftoverInstructionFiles, ["CLAUDE.md"]);
		});
	});

	test("silent about a GEMINI.md that Gemini still reads: its settings name no AGENTS.md, or there are none", () => {
		// A vault that kept its own older settings: Gemini reads GEMINI.md as its
		// only context file, so telling the user to delete it would cut Gemini off.
		withFiles(["AGENTS.md", "GEMINI.md"], (root) => {
			geminiSettings(root);
			assert.deepEqual(scanActiveHygiene(root, NOW, DEFAULTS).leftoverInstructionFiles, []);
		});
		withFiles(["AGENTS.md", "GEMINI.md"], (root) => {
			geminiSettings(root, ["GEMINI.md"]);
			assert.deepEqual(scanActiveHygiene(root, NOW, DEFAULTS).leftoverInstructionFiles, []);
		});
		withFiles(["AGENTS.md", "GEMINI.md"], (root) => {
			assert.deepEqual(scanActiveHygiene(root, NOW, DEFAULTS).leftoverInstructionFiles, []);
		});
		// Both named: Gemini loads GEMINI.md as well, so it is not a leftover.
		withFiles(["AGENTS.md", "GEMINI.md"], (root) => {
			geminiSettings(root, ["AGENTS.md", "GEMINI.md"]);
			assert.deepEqual(scanActiveHygiene(root, NOW, DEFAULTS).leftoverInstructionFiles, []);
		});
	});

	// As Gemini loads its settings (geminiContextFiles cites the source): comments
	// are fine and count as whitespace; a BOM or a trailing comma is fatal (#374).
	const rawSettings = (root: string, text: string): void => {
		mkdirSync(join(root, ".gemini"), { recursive: true });
		writeFileSync(join(root, ".gemini/settings.json"), text);
	};
	const scanWith = (text: string) => {
		let report: ReturnType<typeof scanActiveHygiene> | undefined;
		withFiles(["AGENTS.md", "GEMINI.md"], (root) => {
			rawSettings(root, text);
			report = scanActiveHygiene(root, NOW, DEFAULTS);
		});
		return report!;
	};

	test("Gemini settings with comments and CRLF, which Gemini accepts, are still read", () => {
		const report = scanWith('{\r\n  // where Gemini looks\r\n  "context": { "fileName": ["AGENTS.md"] },\r\n  /* hooks */ "hooks": {}\r\n}\r\n');
		assert.deepEqual(report.leftoverInstructionFiles, ["GEMINI.md"]);
		assert.equal(report.geminiSettingsBroken, false);
	});

	for (const [name, text] of [
		["a BOM", '{ "context": { "fileName": "AGENTS.md" } }'],
		["a missing brace", '{ "context": { "fileName": "AGENTS.md" }'],
		["a trailing comma", '{ "context": { "fileName": "AGENTS.md", }, }'],
		["a comment inside a token, which is whitespace", '{ "debug": tr/**/ue, "context": { "fileName": "AGENTS.md" } }'],
		["an unterminated block comment swallowing the closing brace", '{ "context": { "fileName": "AGENTS.md" } /* never closed'],
		["a JSON value that is not an object", '["AGENTS.md"]'],
	] as const) {
		test(`settings Gemini cannot load (${name}) name nothing, and are reported as broken`, () => {
			const report = scanWith(text);
			assert.deepEqual(report.leftoverInstructionFiles, [], "GEMINI.md is not retired by a file Gemini never applies");
			assert.equal(report.geminiSettingsBroken, true);
		});
	}

	test("a broken settings file says to fix it and keep GEMINI.md, never to delete GEMINI.md", () => {
		const text = formatActiveHygiene(scanWith('{ "context": { "fileName": "AGENTS.md", } }')).join("\n");
		assert.match(text, /\.gemini\/settings\.json doesn't parse — Gemini refuses to start until it does/);
		assert.match(text, /keep GEMINI\.md/);
		assert.doesNotMatch(text, /delete it/);
	});

	test("an unterminated block comment after a complete object still parses", () => {
		const report = scanWith('{ "context": { "fileName": "AGENTS.md" } } /* never closed');
		assert.deepEqual(report.leftoverInstructionFiles, ["GEMINI.md"]);
	});

	test("a commented-out fileName doesn't count, and a // inside a string is no comment", () => {
		assert.deepEqual(
			scanWith('{\n  // was: "fileName": "AGENTS.md"\n  /* "context": { "fileName": ["AGENTS.md"] } */\n  "context": { "fileName": "GEMINI.md" }\n}\n').leftoverInstructionFiles,
			[],
		);
		assert.deepEqual(
			scanWith('{ "$schema": "https://example.com/s.json", "context": { "fileName": "AGENTS.md" } }').leftoverInstructionFiles,
			["GEMINI.md"],
		);
		// An escaped quote doesn't end the string, so the // after it is still inside it.
		assert.deepEqual(
			scanWith(String.raw`{ "note": "a 12\" ruler // not a comment", "context": { "fileName": "AGENTS.md" } }`).leftoverInstructionFiles,
			["GEMINI.md"],
		);
	});

	test("only the top-level context counts, and the v1 contextFileName where context.fileName is absent", () => {
		assert.deepEqual(scanWith('{ "mcpServers": { "x": { "context": { "fileName": "AGENTS.md" } } } }').leftoverInstructionFiles, []);
		assert.deepEqual(scanWith('{ "contextFileName": "AGENTS.md" }').leftoverInstructionFiles, ["GEMINI.md"]);
		assert.deepEqual(
			scanWith('{ "contextFileName": "AGENTS.md", "context": { "fileName": "GEMINI.md" } }').leftoverInstructionFiles,
			[],
			"context.fileName wins over the v1 key",
		);
	});

	test("no broken flag without AGENTS.md: a vault that hasn't upgraded gets no instruction-file findings", () => {
		withFiles(["GEMINI.md"], (root) => {
			rawSettings(root, "{ broken");
			assert.equal(scanActiveHygiene(root, NOW, DEFAULTS).geminiSettingsBroken, false);
		});
	});

	test("silent with AGENTS.md alone", () => {
		withFiles(["AGENTS.md"], (root) => {
			const report = scanActiveHygiene(root, NOW, DEFAULTS);
			assert.equal(report.leftoverInstructionFiles.includes("CLAUDE.md"), false);
			assert.deepEqual(formatActiveHygiene(report), []);
		});
	});

	test("a large leftover CLAUDE.md is the leftover flag only, never a note to SPLIT", () => {
		// CLAUDE.md left the manifest's infrastructure list in the same release,
		// so the root-infra exemption no longer covers it. Telling the user to
		// split a file the other flag says to move out and delete would be two
		// contradictory instructions about one file.
		withFiles(["AGENTS.md"], (root) => {
			writeFileSync(join(root, "CLAUDE.md"), "x".repeat(MONOLITH_BYTES + 1000));
			const report = scanActiveHygiene(root, NOW, DEFAULTS, ["AGENTS.md"]);
			assert.equal(report.leftoverInstructionFiles.includes("CLAUDE.md"), true);
			assert.deepEqual(report.oversizedNotes, []);
		});
	});

	test("a differently cased claude.md flags exactly where the filesystem resolves it as CLAUDE.md", () => {
		// Windows and macOS resolve names case-insensitively, so Claude Code
		// finds a `claude.md` there as CLAUDE.md, and the flag must say so; on
		// a case-sensitive filesystem neither finds it.
		withFiles(["AGENTS.md", "claude.md"], (root) => {
			const resolves = existsSync(join(root, "CLAUDE.md"));
			assert.equal(scanActiveHygiene(root, NOW, DEFAULTS).leftoverInstructionFiles.includes("CLAUDE.md"), resolves);
		});
	});

	test("a large claude.md is the leftover flag where it resolves as CLAUDE.md, and an oversized note where it does not", () => {
		withFiles(["AGENTS.md"], (root) => {
			writeFileSync(join(root, "claude.md"), "x".repeat(MONOLITH_BYTES + 1000));
			const report = scanActiveHygiene(root, NOW, DEFAULTS, ["AGENTS.md"]);
			if (existsSync(join(root, "CLAUDE.md"))) {
				// Windows, macOS: Claude Code loads it, so it is a leftover, never a note to split.
				assert.equal(report.leftoverInstructionFiles.includes("CLAUDE.md"), true);
				assert.deepEqual(report.oversizedNotes, []);
			} else {
				// A case-sensitive filesystem: no agent loads it, so it is a plain note, and still seen.
				assert.equal(report.leftoverInstructionFiles.includes("CLAUDE.md"), false);
				assert.deepEqual(report.oversizedNotes.map((n) => n.path), ["claude.md"]);
			}
		});
	});

	test("AGENTS.md near where Antigravity stops reading is flagged, with the agent that cuts it off", () => {
		withFiles([], (root) => {
			writeFileSync(join(root, "AGENTS.md"), "x".repeat(AGENTS_MD_FLAG_BYTES));
			const report = scanActiveHygiene(root, NOW, DEFAULTS, ["AGENTS.md"]);
			assert.deepEqual(report.agentsMd, { sizeKb: 23 });
			assert.match(formatActiveHygiene(report).join("\n"), /AGENTS\.md is 23KB[\s\S]*Antigravity stopped reading it at ~24,000 bytes/);
		});
		withFiles([], (root) => {
			writeFileSync(join(root, "AGENTS.md"), "x".repeat(AGENTS_MD_FLAG_BYTES - 1));
			assert.equal(scanActiveHygiene(root, NOW, DEFAULTS, ["AGENTS.md"]).agentsMd, null);
		});
	});

	test("a vault's AGENTS.md has room to grow past the template's own cap before it is flagged", () => {
		// The template's test holds the shipped file under AGENTS_MD_MAX_BYTES;
		// the vault flag sits nearer the measured cutoff (byte 23,860 was still
		// read), so a user's first additions are not a finding.
		assert.ok(AGENTS_MD_FLAG_BYTES >= AGENTS_MD_MAX_BYTES + 1000);
		assert.ok(AGENTS_MD_FLAG_BYTES < 23_860);
	});

	test("editing an AGENTS.md that is already flagged is not a new finding (#252)", () => {
		const keyAt = (bytes: number) =>
			withScan(bytes, (report) => reportKey({ report }, HYGIENE_VOLATILE_FIELDS));
		const withScan = <T,>(bytes: number, run: (r: ReturnType<typeof scanActiveHygiene>) => T): T => {
			let out!: T;
			withFiles([], (root) => {
				writeFileSync(join(root, "AGENTS.md"), "x".repeat(bytes));
				out = run(scanActiveHygiene(root, NOW, DEFAULTS, ["AGENTS.md"]));
			});
			return out;
		};
		assert.equal(keyAt(AGENTS_MD_FLAG_BYTES + 10), keyAt(AGENTS_MD_FLAG_BYTES + 900));
		assert.notEqual(keyAt(AGENTS_MD_FLAG_BYTES - 1), keyAt(AGENTS_MD_FLAG_BYTES + 10));
	});

	test("a CLAUDE.md symlinked to a large claude.md is the leftover flag only, never a note to SPLIT", () => {
		withFiles(["AGENTS.md"], (root) => {
			writeFileSync(join(root, "claude.md"), "x".repeat(MONOLITH_BYTES + 1000));
			try {
				symlinkSync("claude.md", join(root, "CLAUDE.md"));
			} catch {
				return; // no symlink rights (Windows without developer mode), or the name is taken (case-insensitive)
			}
			const report = scanActiveHygiene(root, NOW, DEFAULTS, ["AGENTS.md"]);
			assert.equal(report.leftoverInstructionFiles.includes("CLAUDE.md"), true);
			assert.deepEqual(report.oversizedNotes, []);
		});
	});

	test("on a case-sensitive filesystem, a claude.md beside a real CLAUDE.md is still a note that can be oversized", () => {
		withFiles(["AGENTS.md", "CLAUDE.md"], (root) => {
			writeFileSync(join(root, "claude.md"), "x".repeat(MONOLITH_BYTES + 1000));
			const caseSensitive = readdirSync(root).includes("claude.md") && readdirSync(root).includes("CLAUDE.md");
			if (!caseSensitive) return; // Windows, macOS: the write above went to CLAUDE.md itself
			const report = scanActiveHygiene(root, NOW, DEFAULTS, ["AGENTS.md"]);
			assert.deepEqual(report.oversizedNotes.map((n) => n.path), ["claude.md"]);
		});
	});

	test("silent for a vault that has not upgraded yet (CLAUDE.md, no AGENTS.md)", () => {
		withFiles(["CLAUDE.md"], (root) => {
			assert.equal(scanActiveHygiene(root, NOW, DEFAULTS).leftoverInstructionFiles.includes("CLAUDE.md"), false);
		});
	});
});

/**
 * stripJsonComments matches strip-json-comments 3.1.1, the version gemini-cli
 * pins, character for character (#380), not only in whether JSON.parse then
 * accepts the result. Expected outputs are 3.1.1's own, as of 2026-10-13.
 */
describe("stripJsonComments, as strip-json-comments 3.1.1", () => {
	test("an unterminated string runs to the end: a // after it is string, not comment", () => {
		assert.equal(stripJsonComments('{ "a": "unterminated // x'), '{ "a": "unterminated // x');
	});

	test("comments become spaces, line breaks kept, CRLF included", () => {
		assert.equal(stripJsonComments('{ // c\r\n"a": 1 /* b */ }'), '{     \r\n"a": 1         }');
		assert.equal(stripJsonComments('{ "a": 1 } /* open'), '{ "a": 1 }        ');
	});

	test("a quote after an odd run of backslashes doesn't end the string", () => {
		assert.equal(stripJsonComments(String.raw`{ "a": "12\" // in" }`), String.raw`{ "a": "12\" // in" }`);
		assert.equal(stripJsonComments(String.raw`{ "a": "x\\" // out` + "\n}"), String.raw`{ "a": "x\\"       ` + "\n}");
	});

	test("one pass: an unterminated string of escaped quotes stays linear", () => {
		// The regex form took 61.6 ms at 8,000 and grows with the square, so about
		// 10 s here; the scan takes a few ms, so the bound holds on a slow runner.
		const text = '{ "a": "' + '\\"'.repeat(100_000);
		const start = performance.now();
		assert.equal(stripJsonComments(text), text);
		assert.ok(performance.now() - start < 500);
	});
});