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
26.9 KB
Raw Blame
/**
 * The per-view brief handlers (task 3.19): the morning brief, the
 * compiled digest, the daily, weekly and monthly reviews, the operator
 * summary and the today view, each answered at the caller's reach. Split
 * from `brief-tools.ts`; registration happens through that module's
 * dispatcher and registry, which preserve the public BRIEF_TOOLS
 * surface.
 */

import { resolveLinkOutputFormat, resolveTriggerCooldownDays } from "../../core/config.ts";
import { buildMorningBrief } from "../../core/brain/morning-brief.ts";
import {
  deliverBriefTriggers,
  renderTriggerBriefSection,
} from "../../core/brain/triggers/brief.ts";
import {
  readTriggerQueueFailures,
  renderTriggerQueueFailures,
  unreadableTriggerJson,
  type TriggerQueueFailures,
} from "../../core/brain/triggers/store.ts";
import { renderOpenDecisionsBriefSection } from "../../core/brain/decisions/brief.ts";
import { buildTimelineIndex } from "../../core/brain/temporal/build-index.ts";
import {
  collectSourcePointers,
  computeVaultDelta,
  countByKind,
  type PeriodStatusTransition,
} from "../../core/brain/temporal/period-common.ts";
import { selectEvents } from "../../core/brain/temporal/select-events.ts";
import type { TimelineIndex } from "../../core/brain/temporal/types.ts";
import { type ArtifactRef, type ArtifactRefView } from "../../core/brain/artifact-ref-view.ts";
import { PREF_ID_PREFIX } from "../../core/brain/dream-plan.ts";
import { buildTodayDashboard } from "../../core/brain/today-dashboard.ts";
import { buildDailyBrief } from "../../core/brain/temporal/daily-brief.ts";
import { buildWeeklySynthesis } from "../../core/brain/temporal/weekly-brief.ts";
import { loadTemporalConfigSafe } from "../../core/brain/policy.ts";
import { resolveOwnerScopeDelivery } from "../../core/brain/preferences-collect.ts";
import { renderDigest, type DigestFormat } from "../../core/brain/digest.ts";
import { dream } from "../../core/brain/dream.ts";
import {
  buildMonthlyReview,
  normalizeMonthlyReviewMonth,
} from "../../core/brain/monthly-review.ts";
import { buildOperatorSummary } from "../../core/brain/trust/operator-summary.ts";
import type { VerificationDeltaEntry } from "../../core/brain/trust/compute-verification-delta.ts";
import { everyArtifactRefView } from "../../core/brain/artifact-ref-view.ts";
import { doctorIssueRefs, type DoctorIssueNaming } from "../../core/brain/diagnostics.ts";
import type { ActionItem } from "../../core/brain/maintenance/action-scorer.ts";
import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";
import { reachView } from "../../core/brain/reach-view.ts";
import { isoDate } from "../../core/brain/time.ts";
import { captureReportDelta } from "../../core/brain/report-snapshot.ts";
import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import { contextReach, type ServerContext } from "../tool-contract.ts";
import { readableAtContextReachOrUndefined } from "./reach-readable.ts";
import { eventAtReach, eventsAtReach, recordRefs, requestRefView } from "./reach-events.ts";
import { vaultPathField } from "../vault-path-field.ts";
import { coerceAgentScope, coerceIsoDate, coerceFormat } from "../coerce.ts";
import {
  coerceIsoTimestampOrDate,
  coerceNonNegativeInteger,
  coercePositiveInteger,
  toolSafeguard,
} from "./shared.ts";
import type { ProgressSink } from "../../core/brain/progress.ts";
import { OPERATION } from "../../core/brain/safeguard.ts";

export const NO_TRIGGER_QUEUE_FAILURES: TriggerQueueFailures = Object.freeze({
  unreadable: Object.freeze([]),
  queueError: null,
});

export async function toolBrainMorningBrief(
  ctx: ServerContext,
  args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
  const topK = coercePositiveInteger("brain_brief view=morning", "top_k", args["top_k"]) ?? 10;
  const lookbackDays =
    coercePositiveInteger("brain_brief view=morning", "lookback_days", args["lookback_days"]) ?? 7;
  const maxCharsPerMemory = coercePositiveInteger(
    "brain_brief view=morning",
    "max_chars_per_memory",
    args["max_chars_per_memory"],
  );
  const maxTotalChars = coercePositiveInteger(
    "brain_brief view=morning",
    "max_total_chars",
    args["max_total_chars"],
  );
  const now = new Date();
  const agentScope = coerceAgentScope(ctx, args, true);
  const readable = readableAtContextReachOrUndefined(ctx);
  const brief = buildMorningBrief(ctx.vault, {
    now,
    topK,
    ...(agentScope !== undefined ? { agentScope } : {}),
    ...(readable !== undefined ? { readable } : {}),
    withholdsPrivate: contextReach(ctx) !== TRANSPORT_REACH.local,
    lookbackDays,
    ...(maxCharsPerMemory !== undefined ? { maxCharsPerMemory } : {}),
    ...(maxTotalChars !== undefined ? { maxTotalChars } : {}),
  });
  // Pending-trigger section (t_cd1fee79): renders only when a trigger
  // scan persisted surfaceable triggers; included triggers are marked
  // delivered so a prompt shows once per cooldown window.
  //
  // Still fail-soft - a broken queue must not cost the operator the rest
  // of the brief - but no longer silent. The bare catch this replaces set
  // the section to null, so a refusal rendered exactly like an empty
  // queue: the one outcome the anti-nag ledger exists to rule out. The
  // records that could not be read are collected first and reported
  // alongside whatever did render.
  //
  // The queue and its delivery state belong to the local operator: a
  // reader below local reach is shown no trigger, no queue failure, and
  // marks nothing delivered.
  const operatorQueue = contextReach(ctx) === TRANSPORT_REACH.local;
  const triggerFailures: TriggerQueueFailures = operatorQueue
    ? readTriggerQueueFailures(ctx.vault, now)
    : NO_TRIGGER_QUEUE_FAILURES;
  let triggerSection: ReturnType<typeof renderTriggerBriefSection> | null = null;
  let triggerQueueError = triggerFailures.queueError;
  if (operatorQueue) {
    try {
      triggerSection = renderTriggerBriefSection(ctx.vault, {
        now,
        cooldownDays: resolveTriggerCooldownDays(ctx.configPath ?? undefined),
      });
      if (triggerSection.triggers.length > 0) deliverBriefTriggers(ctx.vault, triggerSection, now);
    } catch (err) {
      triggerSection = null;
      triggerQueueError = (err as Error).message ?? String(err);
    }
  }
  const failureText = renderTriggerQueueFailures({
    unreadable: triggerFailures.unreadable,
    queueError: triggerQueueError,
  });
  // Open-decisions section (write-side-trust wave, Task 10): render-only
  // - unlike the trigger section there is no delivery marking, because a
  // parked question is a standing question with no cooldown. Same
  // operator-queue boundary as the triggers: a reader below local reach
  // is shown neither the questions nor the unreadable records.
  const openDecisions = operatorQueue
    ? renderOpenDecisionsBriefSection(ctx.vault)
    : { text: "", records: [], unreadable: [] };
  const sections = [
    brief.text,
    triggerSection !== null ? triggerSection.text : "",
    failureText,
    openDecisions.text,
  ].filter((section) => section !== "");
  return {
    text: sections.join("\n\n"),
    preferences: brief.preferences,
    open_questions: brief.openQuestions,
    recent_notes: brief.recentNotes,
    total_chars: brief.totalChars,
    ...(triggerSection !== null && triggerSection.triggers.length > 0
      ? {
          triggers: triggerSection.triggers.map((t) => ({
            id: t.id,
            kind: t.kind,
            urgency: t.urgency,
            reason: t.reason,
          })),
        }
      : {}),
    ...(triggerFailures.unreadable.length > 0
      ? { triggers_unreadable: triggerFailures.unreadable.map(unreadableTriggerJson) }
      : {}),
    ...(triggerQueueError !== null ? { trigger_queue_error: triggerQueueError } : {}),
    ...(openDecisions.records.length > 0
      ? {
          open_decisions: openDecisions.records.map((r) => ({
            id: r.id,
            question: r.question,
            status: r.status,
          })),
        }
      : {}),
    ...(openDecisions.unreadable.length > 0
      ? { open_decisions_unreadable: openDecisions.unreadable }
      : {}),
  };
}

export async function toolBrainDigest(
  ctx: ServerContext,
  args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
  const since = coerceIsoDate(args, "since");
  const until = coerceIsoDate(args, "until");
  const format = coerceFormat(args) satisfies DigestFormat;

  // Pin ONE effective until instant so the rendered content, the
  // snapshot render, and the snapshot date key all describe the same
  // window even when the caller omitted `until`.
  const effectiveUntil = until ?? new Date();
  const agentScope = coerceAgentScope(ctx, args, true);
  // The digest is rendered for this reader whenever any rule is live: a
  // record below the caller's reach, or withheld by the enforced ownership
  // scope, is absent from every row and count. Passing the predicate
  // whenever it would withhold anything - rather than only below local
  // reach - is the view the `osb://digest/latest` resource renders the
  // same caller with, so the agent summary, the backlink counts and the
  // connection health cannot count the events and records those sections
  // beside them already withhold. With no rule live the predicate is
  // absent and the render stays byte-identical to the unfiltered one.
  const restricted = contextReach(ctx) !== TRANSPORT_REACH.local;
  // The enforced ownership scope (null unless
  // `integrity.owner_scope_delivery` is `fail` with a resolved identity)
  // decides the snapshot boundary below, beside the reach.
  const enforcedScope = resolveOwnerScopeDelivery(ctx.vault, agentScope).enforcedScope;
  const renderFor = (renderFormat: DigestFormat, readable?: (rel: string) => boolean) =>
    renderDigest(ctx.vault, {
      ...(since ? { since } : {}),
      until: effectiveUntil,
      format: renderFormat,
      linkOutputFormat: resolveLinkOutputFormat(ctx.configPath ?? undefined),
      ...(agentScope !== undefined ? { agentScope } : {}),
      ...(readable !== undefined ? { readable } : {}),
      ...(restricted ? { withholdsPrivate: true } : {}),
      ...(ctx.configPath ? { configPath: ctx.configPath } : {}),
    });
  const result = renderFor(format, readableAtContextReachOrUndefined(ctx));

  const envelope: Record<string, unknown> = {
    format,
    empty: result.empty,
    content: result.content,
  };
  // The snapshot is the vault's own run-over-run record, diffed over the
  // digest every record feeds, so a reader below local reach neither
  // takes one nor is shown the delta. The same holds for a caller the
  // enforced ownership scope narrows: its render is one owner's slice of
  // the vault, and persisting that slice under the shared date key would
  // hand the next caller a delta whose key paths were computed against
  // it - key paths naming artifact ids that caller was never shown.
  if (restricted || enforcedScope !== null) return envelope;
  // Snapshot the structured summary, not the rendered string: render
  // a JSON digest for the snapshot regardless of the caller's format
  // so the run-over-run diff keys on data.
  const digestDate = isoDate(effectiveUntil);
  const snapshotSource = format === "json" ? result.content : renderFor("json").content;
  let parsedSnapshot: unknown = null;
  try {
    parsedSnapshot = JSON.parse(snapshotSource);
  } catch {
    parsedSnapshot = null;
  }
  const delta =
    parsedSnapshot !== null
      ? captureReportDelta(
          ctx.vault,
          "digest",
          digestDate,
          parsedSnapshot,
          ctx.configPath ? { configPath: ctx.configPath } : {},
        )
      : null;
  return delta !== null ? { ...envelope, delta } : envelope;
}

// ----- brain_query ---------------------------------------------------------

/**
 * The rows of a daily or weekly envelope this request may see, or
 * `null` when no rule is live - local reach with the ownership gate off -
 * and the envelope is the builder's own (the digest precedent: a reader
 * below local reach is shown only what it may read, and takes no report
 * snapshot).
 *
 * Two rules are asked, through the one adapter the digest's actions rows
 * use: the enforced ownership rule (`gatedOwnerScopeView`, live only
 * under `integrity.owner_scope_delivery: fail` with a resolved identity)
 * and the request's reach-and-readability view. Local reach no longer
 * short-circuits past the ownership rule - an enforced identity on the
 * operator's own transport is exactly the caller that gate exists to
 * scope, and its envelope was otherwise the builder's unfiltered own.
 *
 * Status transitions, retirements and contradictions are dropped when a
 * record they name is withheld. Source pointers are deduplicated
 * artifacts with no record left on them, so they are recollected from
 * the window's events the reader may see: an artifact cited only by
 * evidence on a withheld preference is absent. The counts
 * (`events_by_kind`, `vault_delta`) are recomputed from the same
 * selection, so a withheld record moves no count either. Because a live
 * rule means the envelope is one caller's slice, no report snapshot is
 * taken for it - the shared date key must not hold one caller's slice
 * for the next caller's delta to diff against.
 */
export function periodRowsAtReach(
  ctx: ServerContext,
  index: TimelineIndex,
  window: { readonly since: string; readonly until: string },
): PeriodRowsView | null {
  const refs = everyArtifactRefView(
    gatedOwnerScopeView(ctx.vault, ctx.agentName),
    requestRefView(ctx),
  );
  if (refs.filtersNothing) return null;
  const events = eventsAtReach(refs, selectEvents(index, window));
  return {
    refs,
    sourcePointers: collectSourcePointers(events),
    eventsByKind: countByKind(events),
    vaultDelta: (transitions) => computeVaultDelta(events, transitions),
  };
}

export interface PeriodRowsView {
  readonly refs: ArtifactRefView;
  readonly sourcePointers: ReadonlyArray<string>;
  readonly eventsByKind: ReturnType<typeof countByKind>;
  /** The window's delta over the visible events and the transitions kept for the reader. */
  readonly vaultDelta: (
    transitions: ReadonlyArray<PeriodStatusTransition>,
  ) => ReturnType<typeof computeVaultDelta>;
}

/** A transition or retirement row: the record id and the link it was logged with. */
export function transitionRefs(row: {
  readonly prefId: string;
  readonly link: string;
}): ReadonlyArray<ArtifactRef> {
  return [row.link, ...recordRefs(row.prefId)];
}

/** A contradiction row: its record, the topic's record and its evidence artifact. */
export function contradictionRefs(row: {
  readonly prefId?: string;
  readonly topic?: string;
  readonly artifact?: string;
}): ReadonlyArray<ArtifactRef> {
  return [
    row.artifact,
    ...recordRefs(row.prefId),
    ...(row.topic !== undefined ? recordRefs(`${PREF_ID_PREFIX}${row.topic}`) : []),
  ];
}

/**
 * `brain_daily_brief` - structured counters + transitions + source
 * pointers for one day. Defaults `date` to today UTC when omitted.
 */
export async function toolBrainDailyBrief(
  ctx: ServerContext,
  args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
  const dateRaw = args["date"];
  const dateCoerced = coerceIsoTimestampOrDate("brain_daily_brief", "date", dateRaw, "date-only");
  const date = dateCoerced ?? new Date().toISOString().slice(0, 10);
  const cfg = loadTemporalConfigSafe(ctx.vault);
  const index = buildTimelineIndex(ctx.vault, {
    withholdsPrivate: requestRefView(ctx).withholdsPrivate === true,
  });
  const brief = buildDailyBrief(index, ctx.vault, date, {
    offsetHours: cfg.daily_window_offset_hours,
  });
  const atReach = periodRowsAtReach(ctx, index, brief.window);
  const statusTransitions =
    atReach?.refs.keep(brief.statusTransitions, transitionRefs) ?? brief.statusTransitions;
  const envelope: Record<string, unknown> = {
    vault_path: vaultPathField(ctx),
    date: brief.date,
    window: brief.window,
    events_by_kind: atReach?.eventsByKind ?? brief.eventsByKind,
    status_transitions: statusTransitions,
    vault_delta: atReach?.vaultDelta(statusTransitions) ?? brief.vaultDelta,
    source_pointers: atReach?.sourcePointers ?? brief.sourcePointers,
    generated_at: brief.generatedAt,
  };
  // When any rule is live - below local reach, or an enforced owner
  // scope - the envelope is this caller's slice: no snapshot is taken
  // under the shared date key and no delta is reported.
  if (atReach !== null) return envelope;
  // Dual-output: persist a machine snapshot and report the run-over-run
  // delta when report snapshots are enabled.
  const delta = captureReportDelta(
    ctx.vault,
    "daily",
    brief.date,
    envelope,
    ctx.configPath ? { configPath: ctx.configPath } : {},
  );
  return delta !== null ? { ...envelope, delta } : envelope;
}

/**
 * `brain_weekly_synthesis` - 7-day deterministic summary plus retired
 * and contradictions lists.
 */
export async function toolBrainWeeklySynthesis(
  ctx: ServerContext,
  args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
  const weekEndRaw = args["week_end"];
  const weekEndCoerced = coerceIsoTimestampOrDate(
    "brain_weekly_synthesis",
    "week_end",
    weekEndRaw,
    "date-only",
  );
  const weekEnd = weekEndCoerced ?? new Date().toISOString().slice(0, 10);
  const cfg = loadTemporalConfigSafe(ctx.vault);
  const index = buildTimelineIndex(ctx.vault, {
    withholdsPrivate: requestRefView(ctx).withholdsPrivate === true,
  });
  const synth = buildWeeklySynthesis(index, ctx.vault, weekEnd, cfg);
  const atReach = periodRowsAtReach(ctx, index, {
    since: synth.windowStart,
    until: synth.windowEnd,
  });
  const statusTransitions =
    atReach?.refs.keep(synth.statusTransitions, transitionRefs) ?? synth.statusTransitions;
  const envelope: Record<string, unknown> = {
    vault_path: vaultPathField(ctx),
    window_start: synth.windowStart,
    window_end: synth.windowEnd,
    events_by_kind: atReach?.eventsByKind ?? synth.eventsByKind,
    status_transitions: statusTransitions,
    retired: atReach?.refs.keep(synth.retired, transitionRefs) ?? synth.retired,
    contradictions:
      atReach?.refs.keep(synth.contradictions, contradictionRefs) ?? synth.contradictions,
    vault_delta: atReach?.vaultDelta(statusTransitions) ?? synth.vaultDelta,
    source_pointers: atReach?.sourcePointers ?? synth.sourcePointers,
    generated_at: synth.generatedAt,
  };
  // When any rule is live - below local reach, or an enforced owner
  // scope - the envelope is this caller's slice: no snapshot is taken
  // under the shared date key and no delta is reported.
  if (atReach !== null) return envelope;
  const delta = captureReportDelta(
    ctx.vault,
    "weekly",
    weekEnd,
    envelope,
    ctx.configPath ? { configPath: ctx.configPath } : {},
  );
  return delta !== null ? { ...envelope, delta } : envelope;
}

// ----- brain_intention (Agent Surface Suite) --------------------------------

export async function toolBrainMonthlyReview(
  ctx: ServerContext,
  args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
  const monthRaw = args["month"];
  let month: string | undefined;
  if (monthRaw !== undefined && monthRaw !== null) {
    if (typeof monthRaw !== "string") {
      throw new MCPError(INVALID_PARAMS, "brain_brief view=monthly: month must be YYYY-MM");
    }
    try {
      month = normalizeMonthlyReviewMonth(monthRaw);
    } catch {
      throw new MCPError(INVALID_PARAMS, "brain_brief view=monthly: month must be YYYY-MM");
    }
  }
  // Below local reach (or under the ownership gate) the month is counted
  // over the events this caller may see, in the form it may see them.
  const refs = requestRefView(ctx);
  const report = buildMonthlyReview(ctx.vault, {
    ...(month ? { month } : {}),
    ...(refs.filtersNothing ? {} : { eventAtReach: (ev) => eventAtReach(refs, ev) }),
  });
  return {
    schema_version: report.schema_version,
    generated_at: report.generated_at,
    month: report.month,
    window: report.window,
    summary: report.summary,
  };
}

/**
 * Aggregate operator dashboard: trust verdict, doctor / dream
 * counts, verification delta summary, ranked maintenance actions,
 * and instruction-file ceiling warnings - one read-only call so an
 * operator does not run `brain_digest` + `brain_doctor` separately.
 */
export async function toolBrainOperatorSummary(
  ctx: ServerContext,
  args: Record<string, unknown>,
  onProgress?: ProgressSink,
): Promise<Record<string, unknown>> {
  const topRaw = args["top_actions"];
  let topActionsN: number | undefined;
  if (topRaw !== undefined && topRaw !== null) {
    // Strict integer coercion: reject `"3abc"`, `"2.5"`, and other
    // shapes `Number.parseInt` would silently accept. Only a pure
    // integer literal is allowed.
    if (typeof topRaw === "number") {
      if (!Number.isInteger(topRaw) || topRaw < 0) {
        throw new MCPError(
          INVALID_PARAMS,
          "brain_brief view=operator: top_actions must be a non-negative integer",
        );
      }
      topActionsN = topRaw;
    } else if (typeof topRaw === "string") {
      const trimmed = topRaw.trim();
      if (trimmed === "" || !/^[0-9]+$/.test(trimmed)) {
        throw new MCPError(
          INVALID_PARAMS,
          "brain_brief view=operator: top_actions must be a non-negative integer",
        );
      }
      topActionsN = Number.parseInt(trimmed, 10);
    } else {
      throw new MCPError(
        INVALID_PARAMS,
        "brain_brief view=operator: top_actions must be a non-negative integer",
      );
    }
  }

  const includeDreamRaw = args["include_dream"];
  let includeDream: boolean;
  if (includeDreamRaw === undefined || includeDreamRaw === null) {
    includeDream = true;
  } else if (typeof includeDreamRaw === "boolean") {
    includeDream = includeDreamRaw;
  } else {
    throw new MCPError(
      INVALID_PARAMS,
      "brain_brief view=operator: include_dream must be a boolean",
    );
  }

  let dreamSummary;
  let dreamError: string | undefined;
  if (includeDream) {
    try {
      // The one view behind this dispatcher that runs a consolidation
      // pass. It is a DRY RUN, and it still walks the whole Brain tree,
      // so it is the slow half of an operator summary on a large vault.
      dreamSummary = dream(ctx.vault, {
        dryRun: true,
        // A dry run is still a full synchronous pass over the Brain tree,
        // so it is bounded on the same terms as `brain_dream` itself -
        // the budget the operator set for `dream` governs every MCP call
        // that reaches one, not just the tool that carries its name.
        safeguard: toolSafeguard(ctx, OPERATION.dream),
        ...(onProgress !== undefined ? { onProgress } : {}),
      });
    } catch (err) {
      // Surface the failure so callers know the dashboard is missing
      // verification + dream signals; do not silently produce a
      // partial envelope.
      dreamError = (err as Error).message ?? String(err);
    }
  }
  // The doctor, digest and top-action fields - and the trust verdict over
  // them - answer at the caller's reach, through the view brain_doctor
  // filters its own findings and actions by, and so do the verification
  // entries, which name the records the dream claimed. The dry-run
  // dream's own warning, uncertain and quarantined counts are taken over
  // the whole Brain layer and name no record.
  const view = everyArtifactRefView(
    gatedOwnerScopeView(ctx.vault, ctx.agentName),
    reachView(ctx.vault, contextReach(ctx)),
  );
  const readable = readableAtContextReachOrUndefined(ctx);
  const summary = buildOperatorSummary(ctx.vault, {
    ...(dreamSummary ? { dreamSummary } : {}),
    ...(topActionsN !== undefined ? { topActionsN } : {}),
    ...(readable !== undefined ? { readable } : {}),
    withholdsPrivate: view.withholdsPrivate === true,
    ...(view.filtersNothing
      ? {}
      : {
          keepIssue: (issue: DoctorIssueNaming) => view.row(...doctorIssueRefs(ctx.vault, issue)),
          keepAction: (action: ActionItem) => view.row(action.target),
          // Candidate-level visibility for the maintenance collector:
          // applied before the scorer caps, so a hidden top-ranked
          // action takes no slot a visible one could fill - the same
          // question brain_doctor's suggested_actions and the digest's
          // actions ask over the same collector output.
          visibleRef: view.visible,
          keepVerification: (entry: VerificationDeltaEntry) =>
            view.row(...recordRefs(entry.id), entry.path),
        }),
  });
  return {
    vault_path: vaultPathField(ctx),
    trust_verdict: summary.trust_verdict,
    digest_summary: summary.digest_summary,
    doctor_summary: {
      warning_count: summary.doctor_summary.warning_count,
      error_count: summary.doctor_summary.error_count,
    },
    dream_summary: summary.dream_summary,
    verification_delta: {
      summary: summary.verification_delta.summary,
      entries: summary.verification_delta.entries,
    },
    top_actions: summary.top_actions,
    instruction_file_warnings: summary.instruction_file_warnings,
    ...(dreamError !== undefined ? { dream_error: dreamError } : {}),
  };
}

// ----- brain_unlinked_mentions (v0.10.17) ----------------------------------

/**
 * `brain_brief view=today` - the today operator dashboard: due/overdue
 * obligations, one-off pledges, open loops, merged recent activity, and
 * a totals rollup. Read-only; the clock is resolved at the tool boundary
 * so the core builder stays deterministic. Write-back (the `@osb set`
 * engine) stays CLI-only in this release and is deliberately not
 * exposed here.
 */
export async function toolBrainToday(
  ctx: ServerContext,
  args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
  // Non-negative (0 allowed): the core `buildTodayDashboard` and the CLI
  // both accept a zero-day window and a zero-entry limit, so the MCP surface
  // must not reject what they honour.
  const lookbackDays = coerceNonNegativeInteger(
    "brain_brief view=today",
    "lookback_days",
    args["lookback_days"],
  );
  const limit = coerceNonNegativeInteger("brain_brief view=today", "limit", args["limit"]);
  // The recent-activity section renders log events; below local reach
  // (or under the ownership gate) it shows them as this caller may see
  // them, before the limit and the totals.
  const refs = requestRefView(ctx);
  // Obligation pages, pledge pages and open-loop notes are listed only
  // when the caller may read them, before the totals.
  const readable = readableAtContextReachOrUndefined(ctx);
  const dashboard = buildTodayDashboard(ctx.vault, {
    now: new Date(),
    ...(refs.filtersNothing ? {} : { eventAtReach: (ev) => eventAtReach(refs, ev) }),
    ...(readable === undefined ? {} : { readable }),
    ...(lookbackDays !== undefined ? { activityLookbackDays: lookbackDays } : {}),
    ...(limit !== undefined ? { activityLimit: limit } : {}),
  });
  return {
    vault_path: vaultPathField(ctx),
    text: dashboard.text,
    obligations: dashboard.obligations,
    pledges: dashboard.pledges,
    open_loops: dashboard.openLoops,
    recent_activity: dashboard.recentActivity,
    totals: dashboard.totals,
    errors: dashboard.errors,
  };
}