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
6.9 KB
Raw Blame
/**
 * `o2b brain hygiene` - scan / apply over the hygiene findings
 * pipeline (continuity-hygiene-freshness suite).
 *
 *   o2b brain hygiene scan  [--detectors a,b] [--json]
 *   o2b brain hygiene apply --ids id1,id2 [--dry-run] [--json]
 *
 * Scan is read-only; apply executes only explicitly selected finding
 * ids, and review findings never execute. The conflict resolver
 * command comes from `_brain.yaml` (`hygiene.resolver_cmd`) only.
 */

import { applyHygienePlan } from "../../../core/brain/hygiene/apply.ts";
import { annotateDedupFindings } from "../../../core/brain/hygiene/dedup-verdicts.ts";
import { verdictFields, verdictLine } from "../../../core/decision-model/pair-verdict.ts";
import { buildHygienePlan } from "../../../core/brain/hygiene/plan.ts";
import { assertExpectedCount } from "../../../core/brain/count-guard.ts";
import { resolveConflictFindings } from "../../../core/brain/hygiene/resolve-conflicts.ts";
import { runHygieneScan } from "../../../core/brain/hygiene/scan.ts";
import {
  HYGIENE_DETECTOR_IDS,
  isHygieneDetectorId,
  type HygieneDetectorId,
  type HygieneScanReport,
} from "../../../core/brain/hygiene/types.ts";
import { loadBrainConfig } from "../../../core/brain/policy.ts";
import { brainVerbContext, fail, parse, resolveBrainAgent } from "../helpers.ts";

function parseDetectors(raw: string | undefined): HygieneDetectorId[] | undefined {
  if (raw === undefined || raw.trim() === "") return undefined;
  const parts = raw.split(",").map((part) => part.trim());
  const detectors = parts.filter(isHygieneDetectorId);
  if (detectors.length !== parts.length) {
    throw new Error(`--detectors entries must be: ${HYGIENE_DETECTOR_IDS.join(", ")}`);
  }
  return detectors;
}

function scanReport(vault: string, detectors: HygieneDetectorId[] | undefined): HygieneScanReport {
  const report = runHygieneScan(vault, {
    ...(detectors !== undefined && detectors.length > 0 ? { detectors } : {}),
    now: new Date(),
  });
  let resolverCmd: string | undefined;
  try {
    resolverCmd = loadBrainConfig(vault).hygiene?.resolver_cmd;
  } catch {
    resolverCmd = undefined;
  }
  if (resolverCmd === undefined) return report;
  return Object.freeze({
    ...report,
    findings: resolveConflictFindings(vault, report.findings, { resolverCmd }),
  });
}

export async function cmdBrainHygiene(argv: string[]): Promise<number> {
  const sub = argv[0];
  if (sub !== "scan" && sub !== "apply") {
    return fail("usage: o2b brain hygiene <scan|apply> [options]");
  }
  const { flags } = parse(argv.slice(1), {
    vault: { type: "string" },
    agent: { type: "string" },
    detectors: { type: "string" },
    ids: { type: "string" },
    "dry-run": { type: "boolean" },
    expect: { type: "string" },
    strict: { type: "boolean" },
    json: { type: "boolean" },
  });
  const { config, vault } = brainVerbContext(flags);

  const expectRaw = flags["expect"] as string | undefined;
  let expect: number | null = null;
  if (expectRaw !== undefined) {
    const n = Number(expectRaw);
    if (!Number.isInteger(n) || n < 0) return fail("--expect must be a non-negative integer");
    expect = n;
  }
  const strict = flags["strict"] === true;

  let detectors: HygieneDetectorId[] | undefined;
  try {
    detectors = parseDetectors(flags["detectors"] as string | undefined);
  } catch (exc) {
    return fail((exc as Error).message);
  }

  let report: HygieneScanReport;
  try {
    report = scanReport(vault, detectors);
  } catch (exc) {
    return fail(`hygiene scan failed: ${(exc as Error).message ?? exc}`);
  }

  if (sub === "scan") {
    const verdictLines = new Map<string, string>();
    // Optional decision-model verdicts on dedup findings (use `dedup`);
    // null while the use is off, and the output below is unchanged.
    const annotated = await annotateDedupFindings(vault, report.findings, {
      configPath: config,
    });
    if (annotated !== null) {
      const findings = annotated.map((a) => ({ ...a.item, ...verdictFields(a) }));
      if (flags["json"]) {
        process.stdout.write(JSON.stringify({ ...report, findings }, null, 2) + "\n");
        return 0;
      }
      report = Object.freeze({ ...report, findings: annotated.map((a) => a.item) });
      for (const a of annotated) {
        if (a.verdict !== null) verdictLines.set(a.item.id, verdictLine(a));
      }
    }
    if (flags["json"]) {
      process.stdout.write(JSON.stringify(report, null, 2) + "\n");
      return 0;
    }
    process.stdout.write(`Hygiene scan @ ${report.generated_at}\n`);
    for (const [detector, count] of Object.entries(report.counts)) {
      process.stdout.write(`  ${detector}: ${count} finding(s)\n`);
    }
    if (report.counts["tags"] !== undefined) {
      process.stdout.write(
        "  scope: inline body tags only; frontmatter tags: arrays are not audited\n",
      );
    }
    for (const finding of report.findings) {
      process.stdout.write(
        `- [${finding.detector}] ${finding.id} -> ${finding.proposed_action}\n    ${finding.title}\n`,
      );
      const verdict = verdictLines.get(finding.id);
      if (verdict !== undefined) process.stdout.write(`    ${verdict}\n`);
    }
    for (const error of report.errors) {
      process.stdout.write(`! ${error.detector}: ${error.message}\n`);
    }
    return 0;
  }

  const idsRaw = flags["ids"] as string | undefined;
  const ids = idsRaw
    ?.split(",")
    .map((id) => id.trim())
    .filter((id) => id.length > 0);
  if (ids === undefined || ids.length === 0) {
    return fail("apply requires --ids <finding-id,...> from a prior scan");
  }
  const plan = buildHygienePlan(report, { ids });
  try {
    assertExpectedCount({
      matched: plan.selected.length,
      expect,
      strict,
      willMutate: !flags["dry-run"],
      matchList: plan.selected.map((finding) => finding.id),
    });
  } catch (exc) {
    return fail((exc as Error).message);
  }
  let result;
  try {
    result = await applyHygienePlan(vault, plan, {
      dryRun: Boolean(flags["dry-run"]),
      agent: resolveBrainAgent(flags, config),
      now: new Date(),
    });
  } catch (exc) {
    return fail(`hygiene apply failed: ${(exc as Error).message ?? exc}`);
  }

  if (flags["json"]) {
    process.stdout.write(JSON.stringify({ plan, result }, null, 2) + "\n");
    return result.errors.length === 0 ? 0 : 1;
  }
  for (const action of result.planned) {
    process.stdout.write(`would ${action.action}: ${action.detail} (${action.finding_id})\n`);
  }
  for (const action of result.applied) {
    process.stdout.write(`${action.action}: ${action.detail} (${action.finding_id})\n`);
  }
  for (const id of plan.excluded_review) {
    process.stdout.write(`skipped review-only finding ${id}\n`);
  }
  for (const id of plan.unknown_ids) {
    process.stdout.write(`unknown finding id ${id}\n`);
  }
  for (const error of result.errors) {
    process.stdout.write(`error on ${error.finding_id}: ${error.message}\n`);
  }
  return result.errors.length === 0 ? 0 : 1;
}