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
3.7 KB
Raw Blame
/**
 * Derived-fact synthesis tool (Knowledge Provenance suite).
 *
 * The calling agent reasons a second-order conclusion from existing premise
 * preferences and submits it here. OSB runs no model: it validates that each
 * premise exists and commits the conclusion as an unconfirmed preference
 * carrying a `deduced`/`inferred` provenance level and premise wikilinks.
 *
 * Opt-in: gated by the `derived_fact_synthesis` guardrail. With the flag off
 * the tool refuses (the feature is not enabled), so no derived facts are
 * produced and the brain is unchanged.
 */

import {
  deriveFact,
  DeriveFactError,
  parseDeriveFactInput,
} from "../../core/brain/derived-fact.ts";
import { loadGuardrailsConfigSafe } from "../../core/brain/policy.ts";
import { ResponseShapeError } from "../../core/brain/response-shape.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { readableAtContextReachOrUndefined } from "./reach-readable.ts";
import { wrapToolErrors } from "./shared.ts";

const TOOL = "brain_derive_fact";

async function toolBrainDeriveFact(
  ctx: ServerContext,
  args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
  return wrapToolErrors(TOOL, [DeriveFactError, ResponseShapeError], async () => {
    if (!loadGuardrailsConfigSafe(ctx.vault).derived_fact_synthesis) {
      throw new MCPError(
        INVALID_PARAMS,
        `${TOOL}: derived-fact synthesis is off; the operator enables it with ` +
          "`o2b brain settings set guardrails.derived_fact_synthesis true`",
      );
    }

    // Shape first: the payload is validated before any field is read, so a
    // structurally wrong request never reaches the premise lookup or a write.
    const input = parseDeriveFactInput(args);
    // A premise the caller may not read is refused as a missing one.
    const readable = readableAtContextReachOrUndefined(ctx);
    const res = deriveFact(ctx.vault, input, {
      now: new Date(),
      ...(readable !== undefined ? { readable } : {}),
      // The ownership stamp resolves the writing identity from the
      // server's own config, not from anything the caller sent.
      ...(ctx.configPath !== null ? { configPath: ctx.configPath } : {}),
    });
    return { id: res.id, level: input.level, premises: input.premises };
  });
}

export const DERIVE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
  {
    name: TOOL,
    kind: "write",
    description:
      "Commit a derived fact (a conclusion the agent reasoned from premises) as an unconfirmed preference with premise provenance. Supply `slug`, `topic`, `principle`, `premises` (ids), and `level` (deduced/inferred). OSB validates each premise exists. Opt-in: requires guardrails.derived_fact_synthesis.",
    inputSchema: {
      type: "object",
      properties: {
        slug: { type: "string", description: "Kebab slug for the derived preference." },
        topic: { type: "string", description: "Topic anchor for the derived fact." },
        principle: { type: "string", description: "The conclusion, in imperative voice." },
        premises: {
          type: "array",
          items: { type: "string" },
          description: "Premise preference ids (`pref-<slug>` or bare `<slug>`); at least one.",
        },
        level: {
          type: "string",
          enum: ["deduced", "inferred"],
          description: "'deduced' = logically entailed; 'inferred' = a generalized pattern.",
        },
        agent: {
          type: "string",
          description: "Optional agent identity override; defaults to the server-resolved name.",
        },
      },
      required: ["slug", "topic", "principle", "premises", "level"],
      additionalProperties: false,
    },
    handler: toolBrainDeriveFact,
  },
]);