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
11.9 KB
Raw Blame
import { readFileSync } from "node:fs";
import { relative } from "node:path";

import { canonicalNotePath } from "../../../core/path-safety.ts";
import {
  mirrorReportFields,
  mirrorSignal,
  resolveSharedNamespace,
} from "../../../core/brain/shared-namespace.ts";
import { resolveEffectiveScope, writeSignal } from "../../../core/brain/signal.ts";
import {
  adviseIncomingFeedback,
  adviseUnroutableCapture,
  captureRoutingHintField,
} from "../../../core/brain/write-advisory.ts";
import { emitNextStep, type AdvisoryStream } from "../../advisory-rail.ts";
import { loadFeedbackDefaultScopeSafe } from "../../../core/brain/policy.ts";
import { appendLogEvent } from "../../../core/brain/log.ts";
import { writePreference } from "../../../core/brain/preference.ts";
import { normalizeExpirationDate } from "../../../core/brain/expiration.ts";
import { isoDate, isoSecond } from "../../../core/brain/time.ts";
import {
  BRAIN_LOG_EVENT_KIND,
  BRAIN_PREFERENCE_STATUS,
  BRAIN_SIGNAL_SIGN,
} from "../../../core/brain/types.ts";
import { renderPrefLink } from "../../../core/brain/wikilink.ts";
import { isStoreOnly } from "../../../core/store/store-only.ts";
import { brainVerbContext, fail, ok, okJson, parse, resolveBrainAgent } from "../helpers.ts";

/** How a store-only machine names a record in this verb's output. */
const STORE_RECORD_PREFIX = "store:";

export async function cmdBrainFeedback(argv: string[]): Promise<number> {
  const { flags } = parse(argv, {
    vault: { type: "string" },
    topic: { type: "string" },
    signal: { type: "string" },
    principle: { type: "string" },
    scope: { type: "string" },
    source: { type: "string-array" },
    agent: { type: "string" },
    raw: { type: "string" },
    "raw-file": { type: "string" },
    "force-confirmed": { type: "boolean" },
    date: { type: "string" },
    slug: { type: "string" },
    expires: { type: "string" },
    json: { type: "boolean" },
  });

  for (const field of ["topic", "signal", "principle"] as const) {
    if (typeof flags[field] !== "string" || (flags[field] as string).trim() === "") {
      return fail(`brain feedback missing required flag: --${field}`);
    }
  }

  const signalSign = String(flags["signal"]);
  if (signalSign !== BRAIN_SIGNAL_SIGN.positive && signalSign !== BRAIN_SIGNAL_SIGN.negative) {
    return fail(`--signal must be 'positive' or 'negative'; got ${JSON.stringify(signalSign)}`);
  }

  const context = brainVerbContext(flags, { vault: "optional" });
  const { config } = context;
  // `null` with no vault configured: the signal (and a force-confirmed
  // preference) are store records then (design D14).
  const { vault } = context;
  const agent = resolveBrainAgent(flags, config);

  // Vault-configured fallback scope (`feedback.default_scope`). Applied
  // only when the call passes no explicit --scope. Compute one effective
  // scope so the signal, its mirror, and any force-confirmed preference
  // all land on the same scope.
  const defaultScope = loadFeedbackDefaultScopeSafe(vault);
  const effectiveScope = resolveEffectiveScope(flags["scope"] as string | undefined, defaultScope);
  const writeOpts = defaultScope !== undefined ? { defaultScope } : {};

  let raw: string | undefined;
  const rawFile = flags["raw-file"] as string | undefined;
  if (rawFile) {
    try {
      raw = readFileSync(rawFile, "utf8");
    } catch (exc) {
      return fail(`cannot read --raw-file: ${(exc as Error).message ?? exc}`);
    }
  } else if (flags["raw"]) {
    raw = String(flags["raw"]);
  }

  // Creation-time expiration (unit 3c). Validated HERE, before the
  // signal write, so an unparseable date refuses the whole call by name
  // instead of landing a signal and then failing on the preference.
  // `normalizeExpirationDate` is the one door: the writers call it too,
  // and this pre-check exists so the refusal reaches the operator as a
  // usage error rather than as a write failure halfway through.
  let expires: string | undefined;
  if (flags["expires"] !== undefined) {
    try {
      expires = normalizeExpirationDate(String(flags["expires"]));
    } catch (exc) {
      return fail(`brain feedback --expires: ${(exc as Error).message ?? exc}`);
    }
  }

  const now = new Date();
  const date = (flags["date"] as string | undefined) ?? isoDate(now);
  const slug = (flags["slug"] as string | undefined) ?? String(flags["topic"]);

  const signalInput = {
    topic: String(flags["topic"]),
    signal: signalSign as "positive" | "negative",
    agent,
    principle: String(flags["principle"]),
    created_at: now.toISOString(),
    date,
    slug,
    ...(flags["scope"] ? { scope: String(flags["scope"]) } : {}),
    ...(flags["source"] ? { source: flags["source"] as string[] } : {}),
    ...(raw !== undefined ? { raw } : {}),
    ...(expires !== undefined ? { expiration_date: expires } : {}),
  };
  let sigResult;
  try {
    sigResult = writeSignal(vault, signalInput, writeOpts);
  } catch (exc) {
    const message = `failed to write signal: ${(exc as Error).message ?? exc}`;
    // The ok:false twin a --json caller parses, matching the sibling verbs
    // (capture, design-note); bare text on stdout-starved --json leaves
    // automation with nothing machine-parseable.
    if (flags["json"]) {
      okJson({ ok: false, message });
      return 1;
    }
    return fail(message);
  }
  // t_936a1a61: fail-soft mirror into the shared namespace AFTER the
  // primary write; surfaced only when the key is configured.
  const sharedNamespace = resolveSharedNamespace(config);
  // The mirror copies from a vault, so there is none without one.
  const mirror =
    sharedNamespace === null || vault === null
      ? undefined
      : mirrorSignal(sharedNamespace, vault, signalInput, writeOpts, config);

  try {
    appendLogEvent(
      vault,
      {
        timestamp: isoSecond(now),
        eventType: BRAIN_LOG_EVENT_KIND.feedback,
        body: {
          signal: `[[${sigResult.id}]]`,
          topic: String(flags["topic"]),
          sign: signalSign,
          agent,
        },
      },
      { failOpen: true },
    );
  } catch (err) {
    process.stderr.write(`warning: append feedback log failed: ${(err as Error).message}\n`);
  }

  // Write-time conflict advisory (A4): non-blocking, computed BEFORE any
  // force-confirmed write so it never matches the pref this call creates.
  const advisory = adviseIncomingFeedback(vault, {
    principle: String(flags["principle"]),
    ...(effectiveScope !== undefined ? { scope: effectiveScope } : {}),
    agent,
    now,
  });

  // Unroutable-capture routing hint (unit 4): the signal above landed
  // with no scope, so no scoped recall reaches it. Non-blocking, and
  // silent unless this vault already uses scopes to suggest.
  const routingHint = adviseUnroutableCapture(vault, {
    ...(effectiveScope !== undefined ? { scope: effectiveScope } : {}),
    agent,
    now,
  });

  let prefResult: { path: string; id: string } | null = null;
  if (flags["force-confirmed"]) {
    try {
      prefResult = writePreference(
        vault,
        {
          slug,
          topic: String(flags["topic"]),
          principle: String(flags["principle"]),
          created_at: now.toISOString(),
          unconfirmed_until: now.toISOString(),
          confirmed_at: now.toISOString(),
          status: BRAIN_PREFERENCE_STATUS.confirmed,
          evidenced_by: [`[[${sigResult.id}]]`],
          // Issue #149: an explicit zero, not an absent value. The
          // on-disk encoding of "absent" is the literal `null`, and two
          // ranking surfaces (`pre-compress-pack`, `morning-brief`) map
          // `null` to negative infinity before sorting - so a rule
          // force-confirmed a second ago would sort BELOW every rule
          // that has a number, including one measured at zero. Zero is
          // also the true Wilson lower bound on no evidence, which is
          // why the dream pass already pre-seeds it for new
          // preferences. This writer now matches it.
          confidence_value: 0,
          ...(effectiveScope !== undefined ? { scope: effectiveScope } : {}),
          // The same lifetime the signal carries: a rule confirmed from
          // an observation that expires on a date does not outlive it.
          ...(expires !== undefined ? { expiration_date: expires } : {}),
        },
        // Ownership is resolved by the writer from the CLI's own config,
        // never echoed from `--agent`: the flag is caller-supplied, and a
        // caller must not be able to name whose memory this becomes.
        { overwrite: false, configPath: config },
      );
    } catch (exc) {
      const message = `failed to force-confirm preference: ${(exc as Error).message ?? exc}`;
      if (flags["json"]) {
        okJson({ ok: false, message });
        return 1;
      }
      return fail(message);
    }
    try {
      appendLogEvent(
        vault,
        {
          timestamp: isoSecond(new Date(now.getTime() + 1000)),
          eventType: BRAIN_LOG_EVENT_KIND.forceConfirmed,
          body: {
            preference: renderPrefLink({
              id: prefResult.id,
              principle: String(flags["principle"]),
            }),
            agent,
          },
        },
        { failOpen: true },
      );
    } catch (err) {
      process.stderr.write(
        `warning: append force-confirmed log failed: ${(err as Error).message}\n`,
      );
    }
  }

  // A store-only machine wrote records, not files: name them by id
  // (`store:<id>`), never by the legacy path the writer still composes.
  const storeOnly = vault === null || isStoreOnly({ vault, configPath: config });
  const named = (path: string, id: string): string =>
    storeOnly ? `${STORE_RECORD_PREFIX}${id}` : path;
  // The text form: vault-relative, matching the distill house style (the
  // absolute host path is the operator-supplied vault prefix composed with
  // a machine-derived subtree); a record by id.
  const shown = (path: string, id: string): string =>
    vault === null || storeOnly
      ? `${STORE_RECORD_PREFIX}${id}`
      : canonicalNotePath(relative(vault, path));
  if (flags["json"]) {
    okJson({
      signal_path: named(sigResult.path, sigResult.id),
      signal_id: sigResult.id,
      ...mirrorReportFields(mirror),
      ...(advisory !== null ? { advisory } : {}),
      // The machine stream carries the exit as a field, which is where a
      // forward pointer belongs on a payload the caller parses. The key
      // and the resolution come from the one composer both surfaces use.
      ...captureRoutingHintField(routingHint),
      ...(prefResult
        ? { preference_path: named(prefResult.path, prefResult.id), preference_id: prefResult.id }
        : {}),
    });
    return 0;
  }
  ok(`signal: ${shown(sigResult.path, sigResult.id)}`);
  ok(`id: ${sigResult.id}`);
  if (mirror !== undefined) {
    ok(`mirror: ${mirror.outcome}`);
    // A fail-soft outcome without its reason is a bit nobody can act on,
    // and the mirror is the one path an operator cannot inspect otherwise.
    if (mirror.reason !== undefined) ok(`mirror-reason: ${mirror.reason}`);
  }
  if (advisory !== null) {
    const where = advisory.scope ?? "(unscoped)";
    ok(
      `advisory: incoming principle resembles ${advisory.conflicts.length} confirmed ${where} preference(s)`,
    );
    for (const c of advisory.conflicts) {
      ok(`  - ${c.pref_id} (jaccard ${c.jaccard.toFixed(3)})`);
    }
  }
  if (routingHint !== null) {
    ok(`routing-hint: no ${routingHint.missing_signal} resolved for this signal`);
    ok(
      `  ${routingHint.missing_signal} values in this vault: ` +
        routingHint.candidates.map((c) => `${c.scope} (${c.documents})`).join(", "),
    );
    // The exit is resolved from the registry by the rail; this verb
    // never assembles a command of its own.
    const stream: AdvisoryStream = {
      command: "brain",
      argv,
      jsonRequested: Boolean(flags["json"]),
    };
    emitNextStep(routingHint.code, stream);
  }
  if (prefResult) {
    ok(`preference: ${shown(prefResult.path, prefResult.id)}`);
    ok(`status: confirmed`);
  }
  return 0;
}