Skip to content

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

fix: compare Stop findings without their order, cap open loops on raw age (#255)

Brenno Ferraric9052e03c8a9
diff --git a/.claude/scripts/lib/active-hygiene.ts b/.claude/scripts/lib/active-hygiene.ts
index eaf9771..3293174 100644
--- a/.claude/scripts/lib/active-hygiene.ts
+++ b/.claude/scripts/lib/active-hygiene.ts
@@ -250,6 +250,8 @@ function findOpenLoops(
}
const out: OpenLoop[] = [];
+ // Raw timestamps for the sort below: floored day counts tie and then swap.
+ const mtimes = new Map<string, number>();
// Overlapping configured dirs (e.g. "work" + "work/meetings") must not
// scan a file twice — duplicates would crowd the cap.
for (const rel of [...new Set(candidates)]) {
@@ -274,10 +276,11 @@ function findOpenLoops(
if (ageDays < OPEN_LOOP_DAYS) continue;
const openItems = countOpenLoops(content, config.sectionRe);
if (openItems === 0) continue;
+ mtimes.set(rel, mtimeMs);
out.push({ path: rel, ageDays, openItems });
}
// Oldest first, capped — surface the longest-dead loops, stay quiet-ish.
- return out.sort((a, b) => b.ageDays - a.ageDays).slice(0, OPEN_LOOP_CAP);
+ return out.sort((a, b) => (mtimes.get(a.path) ?? 0) - (mtimes.get(b.path) ?? 0) || a.path.localeCompare(b.path)).slice(0, OPEN_LOOP_CAP);
}
// ---------------------------------------------------------------------------
diff --git a/.claude/scripts/lib/project-dir.ts b/.claude/scripts/lib/project-dir.ts
index 1469698..96e1be3 100644
--- a/.claude/scripts/lib/project-dir.ts
+++ b/.claude/scripts/lib/project-dir.ts
@@ -13,7 +13,7 @@
* all if cwd is the vault. Not to be confused with qmd-refresh.ts's
* resolveVaultRoot, which ignores these variables on purpose (a detached
* worker anchors to its own location), or with mcp-context.ts's, which
- * reads OM_VAULT_PATH for the MCP server.
+ * reads the MCP server's own vault-path override.
*/
const PROJECT_DIR_VARS = [
diff --git a/.claude/scripts/lib/report-key.ts b/.claude/scripts/lib/report-key.ts
new file mode 100644
index 0000000..8f7385f
--- /dev/null
+++ b/.claude/scripts/lib/report-key.ts
@@ -0,0 +1,49 @@
+/**
+ * A stable identity for a hook's report, so a hook that fires every turn can
+ * tell "the same findings" from "new findings" (#252).
+ *
+ * Two things change with no new drift to act on, and both are removed before
+ * hashing:
+ *
+ * - Volatile values, named by the caller: a note's size, an item's age. They
+ * stay in the message the user reads, but not in its identity, or a note
+ * the agent keeps appending to would re-show the report every turn.
+ * - The ORDER those values impose. The scans sort findings by size or age,
+ * so dropping the value alone is not enough: with two oversized notes,
+ * growing the smaller one past the larger reorders the list and changes
+ * the hash all the same. Every array is put in a canonical order first.
+ *
+ * Objects lose their volatile keys and are key-sorted; arrays are sorted by
+ * the canonical text of their elements. Two reports with the same findings in
+ * any order, at any size or age, hash the same.
+ */
+
+import { createHash } from "node:crypto";
+
+/** `value` with volatile keys removed and every object and array in canonical order. */
+export function canonical(value: unknown, volatile: ReadonlySet<string>): unknown {
+ if (Array.isArray(value)) {
+ return value
+ .map((item) => canonical(item, volatile))
+ .map((item) => [JSON.stringify(item), item] as const)
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
+ .map(([, item]) => item);
+ }
+ if (value !== null && typeof value === "object") {
+ const out: Record<string, unknown> = {};
+ for (const key of Object.keys(value).sort()) {
+ if (volatile.has(key)) continue;
+ out[key] = canonical((value as Record<string, unknown>)[key], volatile);
+ }
+ return out;
+ }
+ return value;
+}
+
+/** A short hash of `value`'s canonical form: equal for reports with the same findings. */
+export function reportKey(value: unknown, volatile: ReadonlySet<string>): string {
+ return createHash("sha256")
+ .update(JSON.stringify(canonical(value, volatile)))
+ .digest("hex")
+ .slice(0, 16);
+}
diff --git a/.claude/scripts/stop-checklist.ts b/.claude/scripts/stop-checklist.ts
index a2edfef..82ff338 100644
--- a/.claude/scripts/stop-checklist.ts
+++ b/.claude/scripts/stop-checklist.ts
@@ -28,7 +28,6 @@
* agent-specific argument.
*/
-import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { dirname, join, resolve as resolvePath } from "node:path";
import { fileURLToPath } from "node:url";
@@ -46,6 +45,7 @@ import {
} from "./lib/active-hygiene.ts";
import { parseInfraRootFilenames } from "./lib/session-start.ts";
import { claimChanged } from "./lib/hint-state.ts";
+import { reportKey } from "./lib/report-key.ts";
import { resolveProjectDir } from "./lib/project-dir.ts";
const DEBOUNCE_MS = 30_000;
@@ -119,16 +119,11 @@ const message =
// Numbers that move with no new drift to act on: a note growing past the
// threshold, an item a day older. They stay in the message but not in the
-// comparison, or a note the agent keeps appending to would re-show the report
-// every turn — the #252 repeat by another route.
+// report's identity, and neither does the order they sort findings into
+// (lib/report-key.ts), or a note the agent keeps appending to would re-show
+// the report every turn — the #252 repeat by another route.
const VOLATILE_FIELDS = new Set(["sizeKb", "ageDays", "oldestDays"]);
-/** What identifies a report: the checklist and which findings exist, not their ages or sizes. */
-function reportKey(): string {
- const findings = JSON.stringify(report, (k, v) => (VOLATILE_FIELDS.has(k) ? undefined : v));
- return createHash("sha256").update(checklist + "\n" + findings).digest("hex").slice(0, 16);
-}
-
// SessionEnd (and any input without a recognisable event, the safe default)
// always reports. Stop reports when the findings differ from the last report
// this session was shown: the first Stop, and any change since, including
@@ -139,7 +134,7 @@ const show =
input?.hook_event_name !== "Stop" ||
typeof sessionId !== "string" ||
!sessionId ||
- claimChanged(STATE_PATH, sessionId, reportKey());
+ claimChanged(STATE_PATH, sessionId, reportKey({ checklist, report }, VOLATILE_FIELDS));
if (show) writeSystemMessage(message);
else writeSilentHookOutput();
diff --git a/.claude/scripts/tests/active-hygiene.test.ts b/.claude/scripts/tests/active-hygiene.test.ts
index f2bfce0..e703ad6 100644
--- a/.claude/scripts/tests/active-hygiene.test.ts
+++ b/.claude/scripts/tests/active-hygiene.test.ts
@@ -8,12 +8,13 @@
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import {
- mkdtempSync,
mkdirSync,
- writeFileSync,
+ mkdtempSync,
+ rmSync,
utimesSync,
+ writeFileSync,
} from "node:fs";
-import { join } from "node:path";
+import { dirname, join } from "node:path";
import { tmpdir } from "node:os";
import {
MONOLITH_BYTES,
@@ -513,3 +514,31 @@ describe("formatActiveHygiene", () => {
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 });
+ }
+ });
+});
diff --git a/.claude/scripts/tests/report-key.test.ts b/.claude/scripts/tests/report-key.test.ts
new file mode 100644
index 0000000..c05ee62
--- /dev/null
+++ b/.claude/scripts/tests/report-key.test.ts
@@ -0,0 +1,43 @@
+/**
+ * Unit tests for lib/report-key.ts — a report's identity ignores sizes, ages,
+ * and the order those impose, and changes with anything else.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { canonical, reportKey } from "../lib/report-key.ts";
+
+const VOLATILE = new Set(["sizeKb", "ageDays"]);
+
+describe("reportKey", () => {
+ test("volatile values do not change the key", () => {
+ const a = { notes: [{ path: "a.md", sizeKb: 26 }] };
+ const b = { notes: [{ path: "a.md", sizeKb: 40 }] };
+ assert.equal(reportKey(a, VOLATILE), reportKey(b, VOLATILE));
+ });
+
+ test("the order a volatile value sorts findings into does not change the key", () => {
+ // Sorted by size, largest first: growing b.md past a.md reorders them.
+ const before = { notes: [{ path: "a.md", sizeKb: 30 }, { path: "b.md", sizeKb: 26 }] };
+ const after = { notes: [{ path: "b.md", sizeKb: 34 }, { path: "a.md", sizeKb: 30 }] };
+ assert.equal(reportKey(before, VOLATILE), reportKey(after, VOLATILE));
+ });
+
+ test("a new, removed or renamed finding changes the key", () => {
+ const base = reportKey({ notes: [{ path: "a.md", sizeKb: 26 }] }, VOLATILE);
+ assert.notEqual(reportKey({ notes: [{ path: "a.md" }, { path: "b.md" }] }, VOLATILE), base);
+ assert.notEqual(reportKey({ notes: [] }, VOLATILE), base);
+ assert.notEqual(reportKey({ notes: [{ path: "c.md", sizeKb: 26 }] }, VOLATILE), base);
+ });
+
+ test("non-volatile numbers still count", () => {
+ const a = { loops: [{ path: "x.md", openItems: 1, ageDays: 20 }] };
+ const b = { loops: [{ path: "x.md", openItems: 2, ageDays: 20 }] };
+ assert.notEqual(reportKey(a, VOLATILE), reportKey(b, VOLATILE));
+ });
+
+ test("canonical drops volatile keys at any depth and sorts object keys", () => {
+ assert.deepEqual(canonical({ b: 1, a: { ageDays: 3, path: "p" } }, VOLATILE), { a: { path: "p" }, b: 1 });
+ assert.deepEqual(Object.keys(canonical({ z: 1, a: 2 }, VOLATILE) as object), ["a", "z"]);
+ });
+});
diff --git a/.claude/scripts/tests/stop-checklist.test.ts b/.claude/scripts/tests/stop-checklist.test.ts
index ac37054..8d046f0 100644
--- a/.claude/scripts/tests/stop-checklist.test.ts
+++ b/.claude/scripts/tests/stop-checklist.test.ts
@@ -196,6 +196,21 @@ describe("stop-checklist", () => {
assert.deepEqual(envelopeOf(second.stdout), {});
});
+ test("two oversized notes trading places by size does not re-show the report", () => {
+ // The scan lists oversized notes largest first. Growing the smaller one
+ // past the larger reorders the list; the findings are the same notes.
+ const root = vault("two-growing");
+ mkdirSync(join(root, "notes"), { recursive: true });
+ writeFileSync(join(root, "notes/A.md"), "x".repeat(30_000));
+ writeFileSync(join(root, "notes/B.md"), "x".repeat(26_000));
+ const state = freshState();
+ const first = run(stop("s-two-grow"), { vault: root, state });
+ writeFileSync(join(root, "notes/B.md"), "x".repeat(34_000));
+ const second = run(stop("s-two-grow"), { vault: root, state });
+ assert.match(systemMessageOf(first.stdout), /notes\/A\.md \(30KB\)[\s\S]*notes\/B\.md \(26KB\)/);
+ assert.deepEqual(envelopeOf(second.stdout), {});
+ });
+
test("a new session reports again even when nothing changed", () => {
const root = vault("new-session", "Done.md");
const state = freshState();