Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript
17.9 KB
Raw Blame
/**
 * Proactive active-memory budget-pressure watermark
 * (context-pack-economics-observability, C4 / t_dfda8adb).
 *
 * `computeActiveBudgetPressure` measures active.md fill-rate against its
 * injection byte budget, classifies health, and - only above the warn
 * threshold - lists ranked eviction CANDIDATES (retired before
 * confirmed) reusing the reactive drop order. "Empty output = healthy":
 * the doctor surface stays quiet on healthy vaults. Suggestions only;
 * nothing is mutated.
 */

import { describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

import {
  CRITICAL_THRESHOLD,
  ELEVATED_THRESHOLD,
  computeActiveBudgetPressure,
} from "../../../src/core/brain/active-budget-pressure.ts";
import { budgetActiveBody } from "../../../src/core/brain/active-budget.ts";
import { runDoctor } from "../../../src/core/brain/doctor.ts";
import { brainActivePath, brainDirs } from "../../../src/core/brain/paths.ts";

/** A full rendered active.md body across every known section. */
function body(): string {
  return [
    "# Active Brain Preferences",
    "",
    "Auto-generated by `dream`. Do not edit β€” changes will be overwritten.",
    "",
    "## Confirmed (2)",
    "",
    "- `pref-a` (confidence: high (0.95)) β€” Rule A",
    "- `pref-b` (confidence: medium (0.50)) β€” Rule B",
    "",
    "## Most-applied (30d) (1)",
    "",
    "- `pref-a` (applied_in_window: 4)",
    "",
    "## Quarantine (1)",
    "",
    "_Probationary rules β€” still active._",
    "",
    "- `pref-q` (applied: 0 / violated: 2) β€” Quarantined rule",
    "",
    "## Recently retired (last 1)",
    "",
    "- `pref-r` β€” low_confidence on 2026-05-01",
  ].join("\n");
}

describe("computeActiveBudgetPressure", () => {
  test("healthy: fillRate <= threshold yields status healthy and NO candidates", () => {
    const input = body();
    // Budget far larger than the body -> low fill-rate.
    const p = computeActiveBudgetPressure(input, input.length * 10);
    expect(p.status).toBe("healthy");
    expect(p.candidates).toHaveLength(0);
    expect(p.fillRate).toBeLessThanOrEqual(ELEVATED_THRESHOLD);
  });

  test("fillRate is bytes / budget", () => {
    const input = body();
    const p = computeActiveBudgetPressure(input, input.length * 2);
    expect(p.fillRate).toBeCloseTo(0.5, 10);
    expect(p.bytes).toBe(input.length);
  });

  test("elevated band sits between the two thresholds", () => {
    const input = body();
    // Choose a budget so fillRate lands strictly between the thresholds.
    const mid = (ELEVATED_THRESHOLD + CRITICAL_THRESHOLD) / 2;
    const budget = Math.round(input.length / mid);
    const p = computeActiveBudgetPressure(input, budget);
    expect(p.status).toBe("elevated");
    expect(p.candidates.length).toBeGreaterThan(0);
  });

  test("over budget: status critical, candidates ranked retired before quarantine before most-applied", () => {
    const input = body();
    const p = computeActiveBudgetPressure(input, input.length - 40);
    expect(p.status).toBe("critical");
    // Confirmed / preamble (keep-guard) never appear as candidates.
    for (const c of p.candidates) {
      expect(c.priority).toBeGreaterThan(0);
      expect(c.sectionKey).not.toContain("Confirmed");
      expect(c.sectionKey).not.toBe("preamble");
    }
    // Ranked highest-priority-to-drop first: retired (4) > quarantine (3) > most-applied (1).
    const keys = p.candidates.map((c) => c.sectionKey);
    const retiredAt = keys.findIndex((k) => k.startsWith("## Recently retired"));
    const quarantineAt = keys.findIndex((k) => k.startsWith("## Quarantine"));
    const mostAppliedAt = keys.findIndex((k) => k.startsWith("## Most-applied"));
    expect(retiredAt).toBeGreaterThanOrEqual(0);
    expect(retiredAt).toBeLessThan(quarantineAt);
    expect(quarantineAt).toBeLessThan(mostAppliedAt);
    // Priority is non-increasing down the ranked list.
    for (let i = 1; i < p.candidates.length; i++) {
      expect(p.candidates[i - 1]!.priority).toBeGreaterThanOrEqual(p.candidates[i]!.priority);
    }
  });

  test("non-positive / non-finite budget is fully saturated -> critical", () => {
    expect(computeActiveBudgetPressure(body(), 0).status).toBe("critical");
    expect(computeActiveBudgetPressure(body(), 0).fillRate).toBe(Infinity);
    expect(computeActiveBudgetPressure(body(), Number.NaN).status).toBe("critical");
    // An empty body against a zero budget is still healthy (nothing overflows).
    expect(computeActiveBudgetPressure("", 0).status).toBe("healthy");
    expect(computeActiveBudgetPressure("", 0).fillRate).toBe(0);
  });

  test("deterministic", () => {
    const a = computeActiveBudgetPressure(body(), 400);
    const b = computeActiveBudgetPressure(body(), 400);
    expect(a).toEqual(b);
  });

  test("distinct term: does NOT collide with the WatermarkState cursor", () => {
    const src = readFileSync(
      join(import.meta.dir, "../../../src/core/brain/active-budget-pressure.ts"),
      "utf8",
    );
    // The unrelated last-processed cursor lives in skill-proposals.ts;
    // this module must not reuse that identifier.
    expect(src).not.toMatch(/\bWatermarkState\b/);
    expect(src).toContain("active budget pressure");
  });
});

// ----- Headline tier mirror (context-injection-pipeline, C3) -----------------

/**
 * A body whose non-guard sections hold more bullets than the tier
 * keeps. The probe must model the reactive headline tier with the same
 * exemptions and the same top-N, so the doctor's advance warning
 * describes what the inject-time truncation would actually do.
 */
function tieredFixture(): string {
  return [
    "# Active Brain Preferences",
    "",
    "Auto-generated by `dream`. Do not edit β€” changes will be overwritten.",
    "",
    "## Most-applied (30d) (4)",
    "",
    "- `ma0` (applied_in_window: 8)",
    "- `ma1` (applied_in_window: 6)",
    "- `ma2` (applied_in_window: 9)",
    "- `ma3` (applied_in_window: 2)",
    "",
    "## Recently retired (last 4)",
    "",
    "- `r0` β€” retired for low_confidence stale history",
    "- `r1` β€” retired for low_confidence stale history",
    "- `r2` β€” retired for low_confidence stale history",
    "- `r3` β€” retired for low_confidence stale history",
  ].join("\n");
}

/** The tiered Most-applied section: top three by `applied_in_window`, render order restored. */
const MOST_APPLIED_TIERED = [
  "## Most-applied (30d) (4)",
  "",
  "- `ma0` (applied_in_window: 8)",
  "- `ma1` (applied_in_window: 6)",
  "- `ma2` (applied_in_window: 9)",
].join("\n");

/** The tiered Recently retired section: ties keep the first three in render order. */
const RETIRED_TIERED = [
  "## Recently retired (last 4)",
  "",
  "- `r0` β€” retired for low_confidence stale history",
  "- `r1` β€” retired for low_confidence stale history",
  "- `r2` β€” retired for low_confidence stale history",
].join("\n");

describe("computeActiveBudgetPressure: the headline tier mirror", () => {
  test("the tier threshold is the budget itself: over it tierFires, at or below it never", () => {
    const input = tieredFixture();
    expect(computeActiveBudgetPressure(input, input.length - 1).tierFires).toBe(true);
    expect(computeActiveBudgetPressure(input, input.length).tierFires).toBe(false);
    expect(computeActiveBudgetPressure(input, input.length * 10).tierFires).toBe(false);
  });

  test("at the tier threshold the reactive path leaves the body byte-identical", () => {
    const input = tieredFixture();
    expect(budgetActiveBody(input, input.length)).toBe(input);
  });

  test("candidates carry the tiered footprint the reactive path degrades to", () => {
    const input = tieredFixture();
    const p = computeActiveBudgetPressure(input, input.length - 40);
    expect(p.tierFires).toBe(true);
    const byKey = new Map(p.candidates.map((c) => [c.sectionKey, c]));
    const retired = byKey.get("## Recently retired (last 4)");
    const mostApplied = byKey.get("## Most-applied (30d) (4)");
    expect(retired).toBeDefined();
    expect(mostApplied).toBeDefined();
    // Measured on the exact tier output: same top-N, same exemptions.
    expect(retired!.tieredBytes).toBe(RETIRED_TIERED.length);
    expect(retired!.tieredBytes).toBeLessThan(retired!.bytes);
    expect(mostApplied!.tieredBytes).toBe(MOST_APPLIED_TIERED.length);
  });

  test("probe and reactive path agree on which section degrades first and on the tier output", () => {
    const input = tieredFixture();
    const p = computeActiveBudgetPressure(input, input.length - 40);
    // First degradation candidate: the same section the reactive ladder
    // drops first (retired, highest priority-to-drop).
    expect(p.candidates[0]!.sectionKey).toBe("## Recently retired (last 4)");
    // A budget the tiered body exactly fits: the reactive output holds
    // precisely the sections the probe measured.
    const tieredTotal = [
      [
        "# Active Brain Preferences",
        "",
        "Auto-generated by `dream`. Do not edit β€” changes will be overwritten.",
      ].join("\n"),
      MOST_APPLIED_TIERED,
      RETIRED_TIERED,
    ].join("\n\n");
    const budgeted = budgetActiveBody(input, tieredTotal.length);
    expect(budgeted).toContain(MOST_APPLIED_TIERED);
    expect(budgeted).toContain(RETIRED_TIERED);
    expect(budgeted).not.toContain("`r3`");
    expect(budgeted).toContain("Headlines kept to fit the injection budget");
  });

  test("sequential tier order: the probe's first candidate is the section the reactive ladder compacts first", () => {
    // The review scenario: a small overflow the least important section's
    // tier alone can close. The reactive ladder now tiers sequentially,
    // least important first, and stops as soon as the body fits - so the
    // section the probe ranks as the first eviction candidate must be the
    // ONLY section the reactive path compacts.
    const mostApplied = Array.from(
      { length: 10 },
      (_, i) => `- \`m${i}\` (applied_in_window: ${20 - i})`,
    ).join("\n");
    const retired = [
      "- `r0` β€” low_confidence on 2026-05-01",
      "- `r1` β€” low_confidence on 2026-05-02",
      "- `r2` β€” low_confidence on 2026-05-03",
      "- `r3` β€” low_confidence on 2026-05-04",
    ].join("\n");
    const input = [
      "# Active Brain Preferences",
      "",
      "Auto-generated by `dream`. Do not edit β€” changes will be overwritten.",
      "",
      "## Confirmed (1)",
      "",
      "- `c0` (confidence: high (0.95)) β€” Rule C",
      "",
      "## Most-applied (30d) (10)",
      "",
      mostApplied,
      "",
      "## Recently retired (last 4)",
      "",
      retired,
    ].join("\n");

    const p = computeActiveBudgetPressure(input, input.length - 5);
    expect(p.tierFires).toBe(true);
    expect(p.candidates[0]!.sectionKey).toBe("## Recently retired (last 4)");
    expect(p.candidates[0]!.tieredBytes).toBeLessThan(p.candidates[0]!.bytes);

    // The never-disagree property under the sequential semantics: the
    // reactive path compacts exactly the probe's first candidate and
    // stops - the higher-value candidate keeps every bullet.
    const out = budgetActiveBody(input, input.length - 5);
    expect(out.split("(applied_in_window:").length - 1).toBe(10);
    expect(out).not.toContain("`r3`");
    expect(out).toContain("Headlines kept to fit the injection budget: Recently retired (last 4)");
  });
});

// ----- doctor integration ---------------------------------------------------

function makeVault(): string {
  const vault = mkdtempSync(join(tmpdir(), "o2b-budget-pressure-"));
  const dirs = brainDirs(vault);
  mkdirSync(dirs.brain, { recursive: true });
  mkdirSync(dirs.preferences, { recursive: true });
  mkdirSync(dirs.log, { recursive: true });
  writeFileSync(join(dirs.brain, "_BRAIN.md"), "---\ntitle: Brain\n---\n", "utf8");
  return vault;
}

function writeBrainConfig(vault: string, injectBudgetChars: number): void {
  const dirs = brainDirs(vault);
  writeFileSync(
    join(dirs.brain, "_brain.yaml"),
    `schema_version: 1
primary_agent: null
dream:
  candidate_threshold: 2
  unconfirmed_window_days: 7
  contradiction_window_days: 14
retire:
  stale_evidence_days: 90
confidence:
  low_max_applied: 2
  medium_min: 0.4
  high_min: 0.7
snapshots:
  retention_count: 10
active:
  inject_budget_chars: ${injectBudgetChars}
`,
    "utf8",
  );
}

/**
 * A rendered body comfortably larger than the minimum injection budget
 * (500 chars) so the doctor check can exercise real over-budget
 * pressure. Extra retired lines pad the tail - the section an operator
 * archives first.
 */
function largeBody(): string {
  const lines = [
    "# Active Brain Preferences",
    "",
    "Auto-generated by `dream`. Do not edit β€” changes will be overwritten.",
    "",
    "## Confirmed (2)",
    "",
    "- `pref-a` (confidence: high (0.95)) β€” Keep this live rule around always",
    "- `pref-b` (confidence: medium (0.50)) β€” Another live confirmed rule kept",
    "",
    "## Quarantine (1)",
    "",
    "- `pref-q` (applied: 0 / violated: 2) β€” A probationary quarantined rule here",
    "",
    "## Recently retired (last 6)",
    "",
  ];
  for (let i = 0; i < 6; i++) {
    lines.push(`- \`pref-r${i}\` β€” retired for low_confidence stale history on 2026-05-0${i + 1}`);
  }
  return lines.join("\n");
}

function writeActive(vault: string, bodyText: string): void {
  writeFileSync(
    brainActivePath(vault),
    `---\nkind: brain-active\ngenerated_at: "2026-06-01T00:00:00Z"\n---\n\n${bodyText}\n`,
    "utf8",
  );
}

describe("runDoctor active-budget-pressure check", () => {
  test("quiet on healthy vaults: no warning when under budget", () => {
    const vault = makeVault();
    try {
      writeBrainConfig(vault, 100_000);
      writeActive(vault, body());
      const result = runDoctor(vault);
      expect(result.warnings.some((w) => w.code === "active-budget-pressure")).toBe(false);
    } finally {
      rmSync(vault, { recursive: true, force: true });
    }
  });

  test("over budget: one warning naming ranked candidates, vault unmutated", () => {
    const vault = makeVault();
    try {
      const bodyText = largeBody();
      // Minimum permitted injection budget (500); the body overflows it.
      writeBrainConfig(vault, 500);
      writeActive(vault, bodyText);
      const before = readFileSync(brainActivePath(vault), "utf8");

      const result = runDoctor(vault);
      const hits = result.warnings.filter((w) => w.code === "active-budget-pressure");
      expect(hits).toHaveLength(1);
      expect(hits[0]!.message).toContain("active.md is at");
      // Retired is the first archive candidate named.
      expect(hits[0]!.message).toMatch(/Recently retired/);
      // The retired section holds six bullets, so the headline tier CAN
      // compact it - the promise about headline reduction is honest here.
      expect(hits[0]!.message).toContain("reduced to headlines");

      // Suggestions only β€” the probe never rewrites active.md.
      expect(readFileSync(brainActivePath(vault), "utf8")).toBe(before);
    } finally {
      rmSync(vault, { recursive: true, force: true });
    }
  });

  test("over budget but every non-guard section is untierable: the message says headlines cannot help", () => {
    const vault = makeVault();
    try {
      // The retired section holds only two bullets - at or below the
      // tier's top-N - so its tieredBytes equals its bytes and tiering
      // cannot shrink anything. The doctor must not promise a headline
      // reduction that never happens.
      const bodyText = [
        "# Active Brain Preferences",
        "",
        "Auto-generated by `dream`. Do not edit β€” changes will be overwritten.",
        "",
        "## Confirmed (40)",
        "",
        Array.from(
          { length: 40 },
          (_, i) => `- \`pref-c${i}\` (confidence: high (0.90)) β€” Confirmed rule number ${i}`,
        ).join("\n"),
        "",
        "## Recently retired (last 2)",
        "",
        "- `pref-r0` β€” retired for low_confidence stale history on 2026-05-01",
        "- `pref-r1` β€” retired for low_confidence stale history on 2026-05-02",
      ].join("\n");
      writeBrainConfig(vault, 500);
      writeActive(vault, bodyText);

      const result = runDoctor(vault);
      const hits = result.warnings.filter((w) => w.code === "active-budget-pressure");
      expect(hits).toHaveLength(1);
      expect(hits[0]!.message).toContain("headlines cannot help");
      expect(hits[0]!.message).not.toContain("reduced to headlines");
    } finally {
      rmSync(vault, { recursive: true, force: true });
    }
  });

  test("the keep-guard section alone overflows: the message says headlines cannot help", () => {
    const vault = makeVault();
    try {
      // Only the preamble and Confirmed: no non-guard section exists at
      // all, so there is nothing the tier could ever compact.
      const bodyText = [
        "# Active Brain Preferences",
        "",
        "Auto-generated by `dream`. Do not edit β€” changes will be overwritten.",
        "",
        "## Confirmed (60)",
        "",
        Array.from(
          { length: 60 },
          (_, i) => `- \`pref-c${i}\` (confidence: high (0.90)) β€” Confirmed rule number ${i}`,
        ).join("\n"),
      ].join("\n");
      writeBrainConfig(vault, 500);
      writeActive(vault, bodyText);

      const result = runDoctor(vault);
      const hits = result.warnings.filter((w) => w.code === "active-budget-pressure");
      expect(hits).toHaveLength(1);
      expect(hits[0]!.message).toContain("headlines cannot help");
      expect(hits[0]!.message).not.toContain("reduced to headlines");
      expect(hits[0]!.message).toContain("trim the confirmed rule set");
    } finally {
      rmSync(vault, { recursive: true, force: true });
    }
  });

  test("missing active.md: silent", () => {
    const vault = makeVault();
    try {
      writeBrainConfig(vault, 500);
      const result = runDoctor(vault);
      expect(result.warnings.some((w) => w.code === "active-budget-pressure")).toBe(false);
    } finally {
      rmSync(vault, { recursive: true, force: true });
    }
  });
});