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
13.8 KB
Raw Blame
/**
 * Workspace intent chains and the proactive trigger queue.
 *
 * Extracted from the former brain-tools.ts monolith; registration
 * happens through the aggregator, which preserves the public
 * BRAIN_TOOLS surface.
 */

import { resolveAgentName, resolveTriggerCooldownDays } from "../../core/config.ts";
import { scanTriggers } from "../../core/brain/triggers/scan.ts";
import {
  readTriggers,
  transitionTrigger,
  unreadableTriggerJson,
  type TriggerAction,
} from "../../core/brain/triggers/store.ts";
import {
  extractWikilinkRichBodies,
  parseWikilinkRich,
} from "../../core/brain/link-graph/parse-wikilink.ts";
import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";
import { everyArtifactRefView } from "../../core/brain/artifact-ref-view.ts";
import { reachView } from "../../core/brain/reach-view.ts";
import {
  isTriggerStatus,
  TRIGGER_STATUSES,
  TRIGGER_TERMINAL_STATUSES,
  type TriggerRecord,
} from "../../core/brain/triggers/types.ts";
import {
  intentionRel,
  intentionStemRel,
  listIntentions,
  moveIntentionToHistory,
  noActiveIntentionError,
  setIntention,
  showIntention,
} from "../../core/brain/intentions.ts";
import { resolveSessionScope } from "../../core/brain/session-scope.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import { TOOL_ERROR_CODE } from "../tool-error-codes.ts";
import { contextReach, type ServerContext, type ToolDefinition } from "../tool-contract.ts";
import { readableAtContextReachOrUndefined } from "./reach-readable.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
import { coerceStr, unknownOperationError } from "../coerce.ts";
import { lanePath, laneVault } from "./lane-vault.ts";

function toolBrainIntention(
  ctx: ServerContext,
  args: Record<string, unknown>,
): Record<string, unknown> {
  const operation = coerceStr(args, "operation", true)!;
  // Every operation answers at the caller's reach: a chain the caller may
  // not read is listed, shown and moved exactly as an absent one would be,
  // so neither its text nor its existence crosses, and it is never
  // written. `undefined` at local reach with the owner gate off.
  const readable = readableAtContextReachOrUndefined(ctx);
  const withheld = (scope: string): boolean =>
    readable !== undefined && !readable(intentionRel(scope));
  if (operation === "list") {
    const chains = listIntentions(laneVault(ctx));
    const kept =
      readable === undefined ? chains : chains.filter((c) => readable(intentionStemRel(c.scope)));
    return {
      intentions: kept.map((chain) => ({
        scope: chain.scope,
        version: chain.version,
        updated_at: chain.updatedAt,
        text: chain.text,
      })),
    };
  }
  const scope = coerceStr(args, "scope", true)!;
  if (operation === "set") {
    const text = coerceStr(args, "text", true)!;
    // Setting folds the prior text into the new version's history, so an
    // existing withheld chain is refused rather than read and rewritten.
    // The refusal is the one answer that cannot match an absent chain's.
    if (withheld(scope) && showIntention(laneVault(ctx), scope) !== null) {
      throw new MCPError(
        INVALID_PARAMS,
        `brain_intention: cannot set scope: ${resolveSessionScope(scope)}`,
      );
    }
    const chain = setIntention(laneVault(ctx), {
      scope,
      text,
      agent: resolveAgentName(ctx.configPath ?? undefined),
    });
    return {
      operation,
      scope: chain.scope,
      version: chain.version,
      path: lanePath(ctx, chain.path),
    };
  }
  if (operation === "show") {
    const chain = withheld(scope) ? null : showIntention(laneVault(ctx), scope);
    if (chain === null) return { operation, scope, present: false };
    return {
      operation,
      scope: chain.scope,
      present: true,
      version: chain.version,
      updated_at: chain.updatedAt,
      text: chain.text,
      history: chain.history,
      path: lanePath(ctx, chain.path),
    };
  }
  if (operation === "move") {
    if (withheld(scope)) throw noActiveIntentionError(resolveSessionScope(scope));
    const moved = moveIntentionToHistory(laneVault(ctx), { scope });
    // The archive name steps past every name already taken in history/,
    // readable or not, so below local reach it is left out of the answer.
    if (readable !== undefined) return { operation, scope: moved.scope };
    return { operation, scope: moved.scope, archive_path: lanePath(ctx, moved.archivePath) };
  }
  throw unknownOperationError("brain_intention operation must be one of: set, show, list, move");
}

// ----- brain_trigger (Workspace Insight Suite) ------------------------------

function triggerToJson(record: TriggerRecord): Record<string, unknown> {
  return {
    id: record.id,
    kind: record.kind,
    status: record.effectiveStatus,
    urgency: record.urgency,
    reason: record.reason,
    suggested_action: record.suggestedAction,
    source_artifacts: record.sourceArtifacts,
    cooldown_key: record.cooldownKey,
    created_at: record.createdAt,
    expires_at: record.expiresAt,
    delivered_at: record.deliveredAt,
    resolved_at: record.resolvedAt,
    suppressed_at: record.suppressedAt,
    suppressed_from: record.suppressedFrom,
    snoozed_at: record.snoozedAt,
    snoozed_until: record.snoozedUntil,
    snoozed_from: record.snoozedFrom,
    occurrences: record.occurrences,
    last_seen_at: record.lastSeenAt,
  };
}

/** Operations that move one trigger through the lifecycle. */
const TRIGGER_TRANSITIONS: ReadonlyArray<TriggerAction> = Object.freeze([
  "acknowledge",
  "dismiss",
  "act",
  "suppress",
  "unsuppress",
  "snooze",
  "unsnooze",
]);

/**
 * Every accepted operation, in the order the schema enum lists them.
 * The read operations and {@link TRIGGER_TRANSITIONS} are the only
 * source: the enum, the guard and the error text are all this one list.
 */
const TRIGGER_OPERATIONS: ReadonlyArray<string> = Object.freeze([
  "scan",
  "list",
  "history",
  ...TRIGGER_TRANSITIONS,
]);

function isTriggerTransition(operation: string): operation is TriggerAction {
  return (TRIGGER_TRANSITIONS as ReadonlyArray<string>).includes(operation);
}

/**
 * Every artifact one trigger record names
 * (a-label-is-not-a-boundary, U3).
 *
 * A trigger is not the ownerless lane its classification once claimed.
 * `source_artifacts` is a list of wikilinks to the preferences and
 * retired pages the detector fired on, `reason` spells the same ids and
 * their topics out in prose, and `cooldown_key` embeds them again - so a
 * `batch_inflation` trigger enumerated every owner's preference by id to
 * whoever ran the scan.
 */
function triggerRefs(record: TriggerRecord): ReadonlyArray<string> {
  return [
    ...record.sourceArtifacts,
    ...extractWikilinkRichBodies(record.reason).map((b) => parseWikilinkRich(b).target),
  ];
}

function toolBrainTrigger(
  ctx: ServerContext,
  args: Record<string, unknown>,
): Record<string, unknown> {
  const operation = coerceStr(args, "operation", true)!;
  const now = new Date();
  // A record-lane tool works with no vault: its pages are store records then.
  const vault = laneVault(ctx);
  // A trigger row is dropped WHOLE when any artifact it names is
  // withheld: `reason` and `cooldown_key` repeat the same ids the
  // `source_artifacts` list holds, so trimming the list alone would
  // leave the prose naming what the list no longer does. The reach view
  // joins the owner view: below local reach a trigger naming a record
  // the caller cannot read answers as an absent one.
  const view = everyArtifactRefView(
    gatedOwnerScopeView(vault, ctx.agentName),
    reachView(vault, contextReach(ctx)),
  );
  if (operation === "scan") {
    const cooldownDays = resolveTriggerCooldownDays(ctx.configPath ?? undefined);
    // The sources run over the records this caller may read, so the
    // `candidates` total counts none it may not, and a scan from a remote
    // caller writes no trigger about a withheld record.
    const readable = readableAtContextReachOrUndefined(ctx);
    const result = scanTriggers(vault, {
      now,
      cooldownDays,
      ...(readable !== undefined ? { readable } : {}),
    });
    return {
      operation,
      candidates: result.candidates,
      created: view.keep(result.created, triggerRefs).map(triggerToJson),
      // A cooldown key is `<kind>:<artifact>:<artifact-or-action>` - it
      // is BUILT from the ids the candidate fired on, so a `skipped` row
      // names the same preferences a `created` one does. Split on the
      // key's own separator and ask about every segment; a segment that
      // is a kind or an action resolves to no artifact and passes.
      skipped: view
        .keep(result.skipped, (skip) => skip.cooldownKey.split(":"))
        .map((skip) => ({
          cooldown_key: skip.cooldownKey,
          reason: skip.reason,
        })),
      // A scan that walked around a broken record is not a clean scan.
      unreadable: result.unreadable.map(unreadableTriggerJson),
    };
  }
  if (operation === "list" || operation === "history") {
    const statusRaw = coerceStr(args, "status", false);
    if (statusRaw !== null && statusRaw !== undefined && !isTriggerStatus(statusRaw)) {
      throw new MCPError(INVALID_PARAMS, `brain_trigger: unknown status '${statusRaw}'`, {
        code: TOOL_ERROR_CODE.invalidStatus,
      });
    }
    const scan = readTriggers(vault, {
      now,
      ...(statusRaw ? { status: statusRaw } : {}),
    });
    let records = scan.records;
    if (operation === "history") {
      records = records.filter((record) => TRIGGER_TERMINAL_STATUSES.has(record.effectiveStatus));
    } else if (!statusRaw) {
      records = records.filter((record) => !TRIGGER_TERMINAL_STATUSES.has(record.effectiveStatus));
    }
    // Always present, so an empty `triggers` list means the queue was
    // read and held nothing rather than that part of it was skipped.
    return {
      operation,
      triggers: view.keep(records, triggerRefs).map(triggerToJson),
      unreadable: scan.unreadable.map(unreadableTriggerJson),
    };
  }
  if (isTriggerTransition(operation)) {
    const id = coerceStr(args, "id", true)!;
    try {
      // Checked BEFORE the transition, not after it: `transitionTrigger`
      // writes, so a check on its return value would have moved another
      // owner's trigger through the lifecycle and only then declined to
      // say so. A trigger this caller may not see answers exactly as an
      // absent id does - same message, byte for byte, from the store's
      // own error - because a distinguishable refusal confirms it exists.
      const target = readTriggers(vault, { now }).records.find((r) => r.id === id);
      if (target !== undefined && !view.row(...triggerRefs(target))) {
        throw new Error(`unknown trigger: ${id}`);
      }
      return {
        operation,
        trigger: triggerToJson(transitionTrigger(vault, id, operation, { now })),
      };
    } catch (err) {
      // One code for the whole transition refusal: a separate code for
      // "absent" would split exactly what the shared message keeps together.
      throw new MCPError(INVALID_PARAMS, `brain_trigger: ${(err as Error).message}`, {
        code: TOOL_ERROR_CODE.triggerTransitionRefused,
      });
    }
  }
  throw unknownOperationError(
    `brain_trigger operation must be one of: ${TRIGGER_OPERATIONS.join(", ")}`,
  );
}

// ----- brain_deep_synthesis (Workspace Insight Suite) -----------------------

export const WORKSPACE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
  {
    name: "brain_intention",
    kind: "write",
    description:
      "Scoped current-intention chains: set updates a workstream's now-document (prior text lands in its history trail), show/list read, move retires the chain into history/.",
    inputSchema: {
      type: "object",
      properties: {
        operation: {
          type: "string",
          enum: ["set", "show", "list", "move"],
          description: "Operation to perform.",
        },
        scope: {
          type: "string",
          minLength: 1,
          maxLength: 128,
          description: "Workstream or session label (normalised to a scope slug).",
        },
        text: {
          type: "string",
          minLength: 1,
          maxLength: 4000,
          description: "Intention text for the set operation.",
        },
      },
      required: ["operation"],
      additionalProperties: false,
    },
    previewBudget: MCP_PREVIEW_BUDGET,
    handler: toolBrainIntention,
  },
  {
    name: "brain_trigger",
    kind: "write",
    description:
      // Within the registry guard's tool-description ceiling (290 of the
      // 300 characters), which is why the wording is this tight: the
      // unreadable partition has to be in here, because a caller that
      // does not know to look at it will read an empty `triggers` list
      // as an empty queue.
      "Proactive trigger queue: scan makes deduped triggers, list/history read by status, transitions apply one. suppress silences indefinitely; snooze defers to window end or refire; unsuppress/unsnooze restore the interrupted status. Unreadable records are named, not omitted.",
    inputSchema: {
      type: "object",
      properties: {
        operation: {
          type: "string",
          enum: [...TRIGGER_OPERATIONS],
          description: "Operation to perform.",
        },
        id: {
          type: "string",
          minLength: 1,
          maxLength: 128,
          description: "Trigger id for the transition operations.",
        },
        status: {
          // Sourced from the shared list, never copied: a literal copy
          // here would let a new status pass the handler's guard and be
          // rejected by this schema with nothing reporting the gap.
          type: "string",
          enum: [...TRIGGER_STATUSES],
          description: "Effective-status filter for list.",
        },
      },
      required: ["operation"],
      additionalProperties: false,
    },
    previewBudget: MCP_PREVIEW_BUDGET,
    handler: toolBrainTrigger,
  },
]);