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
10.5 KB
Raw Blame
/**
 * Hygiene apply - execute an explicit remediation plan
 * (continuity-hygiene-freshness suite; kanban t_698db8f7).
 *
 * Routing by proposed action, every executor an existing primitive:
 *
 *   - `merge`     -> `mergePreferences` (keep = first target);
 *   - `supersede` -> append the resolver-chosen winning claim with
 *                    hygiene provenance (the conflict's slot then
 *                    reads the winner as current truth);
 *   - `recompile` -> the targeted-recompile executor, scoped to the
 *                    finding's page;
 *   - `archive` / `forget` -> move the page into a dated
 *                    `Brain/.snapshots/` directory - never delete;
 *   - `retire`    -> the document retirement core: a near-duplicate
 *                    copy is deleted, its manifest entry marked
 *                    retired into the canonical, and its removal
 *                    audited (destructive by design, so the plan
 *                    builder only selects it attended); the applied
 *                    detail carries the per-copy link counts.
 *
 * Dry-run previews the routed actions with zero writes. Per-finding
 * fail-soft; one audit record per non-dry run.
 */

import { join } from "node:path";

import { appendAuditRecord } from "../../reliability/audit.ts";
import { HYGIENE_AUDIT_DIR } from "../audit-dirs.ts";
import { retireDocumentCopies } from "../document-retire.ts";
import { mergePreferences } from "../merge.ts";
import { brainDirsForWrite } from "../paths.ts";
import { archivePage, executeRecompile, planRecompile } from "../recompile.ts";
import { appendClaimEvent } from "../truth/store.ts";
import { assertVaultIdentityForWrite } from "../vault-identity.ts";
import type { WriteSubject } from "../write-disposition.ts";
import type { HygienePlan } from "./plan.ts";
import type { HygieneFinding } from "./types.ts";

export interface HygieneApplyOptions {
  readonly dryRun?: boolean;
  readonly agent: string;
  readonly now: Date;
  /**
   * Credential subject for the destructive routes' deny consult. Only
   * the `retire` executor consults a permissions document today (through
   * the retirement core, the same ladder deleteBySource climbs); with no
   * subject the consult falls back to the ambient agent, so a surface
   * holding a request identity must pass it here or a rule naming that
   * identity is silently bypassed on this route.
   */
  readonly subject?: WriteSubject;
}

export interface HygieneAppliedAction {
  readonly finding_id: string;
  readonly action: string;
  readonly detail: string;
}

export interface HygieneApplyResult {
  readonly dry_run: boolean;
  /** Dry-run preview of what would execute. */
  readonly planned: ReadonlyArray<HygieneAppliedAction>;
  readonly applied: ReadonlyArray<HygieneAppliedAction>;
  readonly errors: ReadonlyArray<{ finding_id: string; message: string }>;
}

function plannedAction(finding: HygieneFinding): HygieneAppliedAction {
  return Object.freeze({
    finding_id: finding.id,
    action: finding.proposed_action,
    detail: finding.targets.join(", "),
  });
}

async function executeFinding(
  vault: string,
  finding: HygieneFinding,
  opts: HygieneApplyOptions,
): Promise<HygieneAppliedAction> {
  switch (finding.proposed_action) {
    case "merge": {
      const [keep, drop] = finding.targets;
      if (keep === undefined || drop === undefined) {
        throw new Error("merge finding must carry exactly two targets");
      }
      const plan = mergePreferences(vault, keep, drop, {
        now: opts.now,
        agentName: opts.agent,
      });
      return Object.freeze({
        finding_id: finding.id,
        action: "merge",
        detail: `kept ${plan.keep_id}, retired ${plan.drop_id}`,
      });
    }
    case "supersede": {
      const resolver = finding.evidence["resolver"] as { winner_value?: unknown } | undefined;
      const winner = resolver !== undefined ? resolver.winner_value : undefined;
      const slot = finding.targets[0] ?? "";
      // Entities/aspects are normalized names (no '#'), so the first
      // '#' is always the slot separator.
      const separator = slot.indexOf("#");
      if (typeof winner !== "string" || winner.length === 0 || separator <= 0) {
        throw new Error("supersede finding lacks a resolver winner or a valid entity#aspect slot");
      }
      appendClaimEvent(vault, {
        ts: opts.now.toISOString(),
        agent: opts.agent,
        entity: slot.slice(0, separator),
        aspect: slot.slice(separator + 1),
        value: winner,
        source: "[[hygiene-resolver]]",
      });
      return Object.freeze({
        finding_id: finding.id,
        action: "supersede",
        detail: `${slot} -> ${winner}`,
      });
    }
    case "recompile": {
      const page = finding.targets[0];
      const plan = planRecompile(vault);
      const scoped = Object.freeze({
        entries: Object.freeze(plan.entries.filter((entry) => entry.page === page)),
      });
      const result = await executeRecompile(vault, scoped, {
        agent: opts.agent,
        now: opts.now,
      });
      if (result.errors.length > 0) throw new Error(result.errors[0]!.message);
      return Object.freeze({
        finding_id: finding.id,
        action: "recompile",
        detail: `rederived ${result.rederived.length}, archived ${result.archived.length}, manual ${result.manual.length}`,
      });
    }
    case "archive":
    case "forget": {
      const page = finding.targets[0];
      if (page === undefined) throw new Error("archive finding carries no target page");
      const target = archivePage(vault, page, opts.now);
      return Object.freeze({
        finding_id: finding.id,
        action: finding.proposed_action,
        detail: `archived to ${target}`,
      });
    }
    case "retire": {
      // The evidence contract is the document-dedup detector's: the
      // canonical page lives in `evidence.canonical`, and every other
      // target is a stale copy to retire into it. Re-derived here so a
      // hand-built plan answers to the same shape a scan produced.
      const canonical = finding.evidence["canonical"];
      if (typeof canonical !== "string" || canonical.length === 0) {
        throw new Error("retire finding lacks a canonical page in its evidence");
      }
      const copies = finding.targets
        .filter((target) => target !== canonical)
        .map((path) => ({ path, canonical }));
      if (copies.length === 0) {
        throw new Error("retire finding names no retired copy besides the canonical");
      }
      const result = retireDocumentCopies(vault, copies, {
        agent: opts.agent,
        now: opts.now,
        ...(opts.subject !== undefined ? { subject: opts.subject } : {}),
      });
      // A per-copy failure BEFORE the removal leaves the copy on disk;
      // one after it reports the page as removed in its own message.
      // Surfacing the first failure through the finding's error keeps
      // the applied/errors split honest (the recompile executor's rule).
      if (result.failed.length > 0) {
        const first = result.failed[0]!;
        throw new Error(
          `retired ${result.retired.length}, failed ${result.failed.length}: ` +
            `${first.path}: ${first.message}`,
        );
      }
      // The per-copy link accounting rides the detail (review M7): the
      // counts used to be dropped here, so an apply that rewrote ten
      // inbound links reported only "retired N" and one whose rewrite
      // was refused looked like every other.
      const links = result.retired.reduce(
        (acc, copy) => ({
          rewritten: acc.rewritten + copy.wikilinks.rewritten.length,
          failed: acc.failed + copy.wikilinks.failed.length,
        }),
        { rewritten: 0, failed: 0 },
      );
      // The disk accounting rides it too (review M6, retire half): the
      // snapshot archive lands in a counted surface before the removals
      // free anything, so the detail states the net, not only the shrink.
      const disk = result.disk;
      const net = disk.netBytes ?? 0;
      return Object.freeze({
        finding_id: finding.id,
        action: "retire",
        detail:
          `retired ${result.retired.length} near-duplicate cop${
            result.retired.length === 1 ? "y" : "ies"
          } into ${canonical}; links: ${links.rewritten} rewritten, ${links.failed} failed; ` +
          `disk: snapshot ${disk.snapshotBytes ?? 0} bytes, removed ${disk.removedBytes} bytes, ` +
          `net ${net >= 0 ? "+" : ""}${net} bytes`,
      });
    }
    default:
      throw new Error(`no executor for action '${finding.proposed_action}'`);
  }
}

export async function applyHygienePlan(
  vault: string,
  plan: HygienePlan,
  opts: HygieneApplyOptions,
): Promise<HygieneApplyResult> {
  const dryRun = opts.dryRun === true;
  // Vault-identity write guard (context-integrity-gates, Unit J), placed
  // per the one rule the three appliers now share: at the entry point,
  // before any other work, and only when the call will write. See the
  // write-guard section of `applier-capability.ts` for why. The "before
  // any other work" half is this applier's own rationale - the per-finding
  // loop below is fail-soft, so an assertion reached from inside an
  // executor would be filed as one finding's error instead of refusing.
  if (!dryRun) assertVaultIdentityForWrite(vault);

  if (dryRun) {
    return Object.freeze({
      dry_run: true,
      planned: Object.freeze(plan.selected.map(plannedAction)),
      applied: Object.freeze([]),
      errors: Object.freeze([]),
    });
  }

  const applied: HygieneAppliedAction[] = [];
  const errors: { finding_id: string; message: string }[] = [];
  for (const finding of plan.selected) {
    try {
      applied.push(await executeFinding(vault, finding, opts));
    } catch (error) {
      errors.push({
        finding_id: finding.id,
        message: error instanceof Error ? error.message : "apply failed",
      });
    }
  }

  if (applied.length > 0 || errors.length > 0) {
    appendAuditRecord(
      join(brainDirsForWrite(vault).log, HYGIENE_AUDIT_DIR),
      {
        timestamp: opts.now.toISOString(),
        actor: opts.agent,
        action: "hygiene_apply",
        target: "Brain",
        ok: errors.length === 0,
        details: {
          applied: applied.length,
          errors: errors.length,
          actions: applied.map((action) => `${action.action}:${action.finding_id}`),
        },
      },
      vault,
    );
  }

  return Object.freeze({
    dry_run: false,
    planned: Object.freeze([]),
    applied: Object.freeze(applied),
    errors: Object.freeze(errors),
  });
}