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
12.9 KB
Raw Blame
/**
 * Output renderers for `o2b install` / `o2b install --check`.
 *
 * Two surfaces: human-readable text (default) and JSON (`--json`).
 * Both forms describe the same data so the agent can switch on
 * `--json` without losing detail.
 *
 * ## One envelope, because there used to be four
 *
 * This verb has four modes and each built its own `--json` payload. Three
 * declared `schema_version: 1`; apply - the only mode that CHANGES the
 * machine - declared none, and the plan payload was assembled inline in
 * `install.ts` rather than here at all. No test asserted a field name in
 * any of them, while the human `--check` table is pinned byte-for-byte
 * against the `install/<runtime>.md` documents.
 *
 * {@link installJson} is the single exit now, so a payload cannot be
 * emitted without a version, and `tests/cli/install-json-shape.test.ts`
 * pins the key set of all four.
 */

import type { DataOwnership } from "../../core/install/ownership.ts";
import type { FrictionDiff, FrictionMatrix } from "../../core/install/friction.ts";
import type { LaneConsentVerdict } from "../../core/brain/diagnostics.ts";
import type {
  ApplyResult,
  DetectResult,
  InstallPlan,
  VerifyResult,
} from "../../core/install/types.ts";

/**
 * The version every payload below declares.
 *
 * Still 1 after apply gained the key: the field is ADDITIVE on a payload
 * that previously had no version to compare against, and the three modes
 * that already said 1 describe the same shapes they always did. A consumer
 * pinning `=== 1` keeps working, which a bump would have broken to
 * announce a change that took nothing away.
 */
export const INSTALL_JSON_SCHEMA_VERSION = 1;

/**
 * The machine-readable half of the ownership close.
 *
 * Named once, for the reason `NEXT_COMMAND_KEY` is: the CLI renderer and
 * anything that reads the payload back must not drift on the spelling.
 * NOT `handoff` - that name already means the operator-readable session
 * notes under `Brain/handoffs/`, and one word for two records is how a
 * field becomes unsearchable.
 */
export const DATA_OWNERSHIP_KEY = "data_ownership";

/**
 * Serialise one `--json` payload.
 *
 * The version is prepended here rather than spelled at each call site -
 * the whole reason the apply payload could ship without one.
 */
export function installJson(payload: Readonly<Record<string, unknown>>): string {
  return (
    JSON.stringify({ schema_version: INSTALL_JSON_SCHEMA_VERSION, ...payload }, null, 2) + "\n"
  );
}

export interface DetectTableRow {
  readonly target: string;
  readonly status: string;
  readonly configPath: string | null;
  readonly notes: ReadonlyArray<string>;
}

export function renderDetectTable(rows: ReadonlyArray<DetectResult>): string {
  if (rows.length === 0) return "o2b install — no adapters registered\n";
  const lines: string[] = ["o2b install — detected runtimes", "-".repeat(35)];
  let installed = 0;
  let drift = 0;
  let notInstalled = 0;
  for (const r of rows) {
    const status = r.status.padEnd(14);
    const target = r.target.padEnd(14);
    const where = r.configPath ?? "";
    lines.push(`  ${target}${status}${where}`);
    if (r.notes.length > 0) {
      for (const n of r.notes) lines.push(`                              ${n}`);
    }
    if (r.status === "installed") installed += 1;
    else if (r.status === "drift") drift += 1;
    else if (r.status === "not-installed") notInstalled += 1;
  }
  lines.push("");
  const summary = `${rows.length} runtime(s) in registry; ${installed} installed, ${drift} drift, ${notInstalled} not-installed.`;
  lines.push(summary);
  if (drift > 0 || notInstalled > 0) {
    lines.push("");
    lines.push("To install or repair, run:");
    for (const r of rows) {
      if (r.status === "drift" || r.status === "not-installed") {
        lines.push(`  o2b install --target ${r.target} --apply`);
      }
    }
  }
  lines.push("");
  return lines.join("\n");
}

export function renderDetectJson(rows: ReadonlyArray<DetectResult>): string {
  return installJson({
    targets: rows.map((r) => ({
      target: r.target,
      status: r.status,
      config_path: r.configPath,
      notes: r.notes,
    })),
  });
}

/**
 * The plan payload. It lived inline in `install.ts` and moves here so all
 * four `--json` shapes are readable in one file - the arrangement that
 * would have made the missing version on apply obvious.
 */
export function renderPlanJson(plan: InstallPlan): string {
  return installJson({ plan });
}

/**
 * The plan, as text.
 *
 * Two modes: the plain print-only dry run (default) keeps its
 * "dry-run; pass --apply to execute" header, and the consent render
 * (`{ consent: true }`) drops the dry-run wording - M15, it is asking
 * for APPLY consent, and a header that says dry-run misnames the
 * question. The consent render rides stderr beside the prompt (the
 * caller's job), where it cannot corrupt a payload on stdout.
 */
export function renderPlan(plan: InstallPlan, opts: { readonly consent?: boolean } = {}): string {
  const lines: string[] = [];
  lines.push(
    opts.consent === true
      ? `o2b install --target ${plan.target} — plan (nothing written until you confirm)`
      : `o2b install --target ${plan.target} — plan (dry-run; pass --apply to execute)`,
  );
  lines.push("-".repeat(60));
  for (const [i, step] of plan.steps.entries()) {
    lines.push(`  step ${i + 1}: [${step.kind}] ${step.preview}`);
    if (step.path) lines.push(`             path: ${step.path}`);
    // t_b6bcd984: the consent flow shows the operator the file diff, not
    // just the one-line summary. Indented under the step it belongs to.
    if (step.diff) {
      lines.push("");
      for (const d of step.diff.split("\n")) lines.push(`  ${d}`);
    }
  }
  if (plan.postNotes.length > 0) {
    lines.push("");
    lines.push("Post-install notes:");
    for (const n of plan.postNotes) lines.push(`  - ${n}`);
  }
  lines.push("");
  return lines.join("\n");
}

export function renderApplyResult(result: ApplyResult, consent: LaneConsentVerdict): string {
  const m = result.manifest;
  const lines: string[] = [];
  lines.push(`o2b install --target ${result.target} --apply — done`);
  lines.push(`  operation:   ${m.operation}`);
  lines.push(`  config path: ${m.config_path ?? "(none)"}`);
  lines.push(`  consent:     ${consent}`);
  if (m.owned_keys?.length) {
    lines.push(`  owned keys:`);
    for (const k of m.owned_keys) lines.push(`    - ${k}`);
  }
  if (m.owned_paths?.length) {
    lines.push(`  owned paths:`);
    for (const p of m.owned_paths) lines.push(`    - ${p}`);
  }
  lines.push(`  applied at:  ${m.applied_at}`);
  lines.push(`  steps:       ${result.steps_executed}`);
  lines.push("");
  return lines.join("\n");
}

/**
 * The apply payload.
 *
 * The version is added BESIDE the result's own fields rather than nesting
 * the result under a key: a consumer reading `.manifest` or
 * `.steps_executed` keeps working and gains a version it never had, which
 * a re-nesting would have broken to announce a change that took nothing
 * away.
 *
 * `consent` (t_b6bcd984) rides the same envelope, additive under
 * schema_version 1: it records how the write was authorised. The verdict
 * is the derived {@link LaneConsentVerdict} (M3) - `yes-flag` or
 * `interactive-yes` for a real consent, in the one vocabulary every
 * guarded lane records - not a hard-coded `confirmed`, which made an
 * operator's yes and an automatic run indistinguishable. The verdict
 * deliberately does NOT go into the sidecar manifest - that is a
 * schema'd document with `applied_at` semantics; the receipt for consent
 * is this CLI payload.
 */
/**
 * What the consented managed-block step did on an apply, as the apply
 * payload's `instruction_block` field. The uninstall payload has carried
 * the same-named field since its step shipped; the apply receipt carries
 * it too so a headless consumer that consented to a plan showing the
 * step can read the outcome of that step from the payload it parses,
 * instead of the write being reported only on the human path. The shape
 * mirrors the uninstall field: snake_case keys, a null `file` and a
 * `skipped_reason` sentence when the target maps no instruction file in
 * `HOST_INSTRUCTION_PRECEDENCE`.
 */
export interface ApplyInstructionBlockOutcome {
  /** The vault-root file the step wrote, or null on a named skip. */
  readonly file: string | null;
  /** True when the apply created the file (a first install takes no backup). */
  readonly created: boolean;
  /** True when the apply changed the file's bytes (or would, under dry-run). */
  readonly changed: boolean;
  /** The exclusive-create backup of the prior bytes; null when none was taken. */
  readonly backup_path: string | null;
  /** Why nothing was written, or null when the step ran. */
  readonly skipped_reason: string | null;
}

export function renderApplyJson(
  result: ApplyResult,
  ownership: DataOwnership,
  consent: LaneConsentVerdict,
  instructionBlock: ApplyInstructionBlockOutcome,
): string {
  return installJson({
    consent,
    ...result,
    instruction_block: instructionBlock,
    [DATA_OWNERSHIP_KEY]: ownership,
  });
}

export function renderVerifyTable(rows: ReadonlyArray<VerifyResult>): string {
  if (rows.length === 0) return "o2b install --check — no targets verified\n";
  const lines: string[] = ["o2b install --check", "-".repeat(20)];
  for (const v of rows) {
    const status = v.status.padEnd(18);
    lines.push(`  ${v.target.padEnd(14)}${status}${v.details.join("; ")}`);
    if (v.fix_hint) {
      lines.push(`                              fix: ${v.fix_hint}`);
    }
  }
  lines.push("");
  return lines.join("\n");
}

export function renderVerifyJson(
  rows: ReadonlyArray<VerifyResult>,
  ownership: DataOwnership | null,
): string {
  return installJson({
    targets: rows,
    ...(ownership === null ? {} : { [DATA_OWNERSHIP_KEY]: ownership }),
  });
}

/** Column widths shared by the friction table and its diff. */
const FRICTION_TARGET_WIDTH = 14;
const FRICTION_DIMENSION_WIDTH = 22;
/** Where a citation continuation line starts: past both columns. */
const FRICTION_DETAIL_INDENT = " ".repeat(2 + FRICTION_TARGET_WIDTH + FRICTION_DIMENSION_WIDTH);

/**
 * The friction matrix: one line per host per dimension, with the
 * citation on a continuation line beneath it.
 *
 * The citation is printed rather than reserved for `--json` because the
 * answers it explains are one word each - `unknown`, `none ships` - and a
 * one-word answer with no source is the shape of claim this whole verb
 * spent a release removing.
 */
export function renderFrictionTable(matrix: FrictionMatrix): string {
  if (matrix.rows.length === 0) return "o2b install --friction — no adapters registered\n";
  const lines: string[] = ["o2b install --friction", "-".repeat(22)];
  for (const row of matrix.rows) {
    for (const cell of row.cells) {
      lines.push(
        `  ${row.target.padEnd(FRICTION_TARGET_WIDTH)}` +
          `${cell.dimension.padEnd(FRICTION_DIMENSION_WIDTH)}${cell.value}`,
      );
      if (cell.detail !== null) lines.push(`${FRICTION_DETAIL_INDENT}${cell.detail}`);
    }
    lines.push("");
  }
  lines.push(
    `${matrix.rows.length} runtime(s) × ${matrix.dimensions.length} dimension(s), ` +
      `derived from the fact table and the live adapter registry.`,
  );
  lines.push("");
  return lines.join("\n");
}

export function renderFrictionJson(matrix: FrictionMatrix): string {
  return installJson({
    friction: {
      dimensions: matrix.dimensions,
      targets: matrix.rows.map((row) => ({
        target: row.target,
        label: row.label,
        cells: row.cells,
      })),
    },
  });
}

/**
 * The diff: the dimensions the two hosts answer differently, and a count
 * of the ones they do not. The shared dimensions are counted rather than
 * printed - a diff that reprints everything is the table the reader
 * already has - and the count is what keeps the silence from reading as
 * "there was nothing else to compare".
 */
export function renderFrictionDiff(diff: FrictionDiff): string {
  const lines: string[] = [
    `o2b install --friction --base ${diff.base} --compare ${diff.compare}`,
    "-".repeat(52),
  ];
  for (const difference of diff.differing) {
    lines.push(`  ${difference.dimension}`);
    lines.push(`    ${diff.base.padEnd(FRICTION_TARGET_WIDTH)}${difference.baseValue}`);
    lines.push(`    ${diff.compare.padEnd(FRICTION_TARGET_WIDTH)}${difference.compareValue}`);
  }
  lines.push("");
  lines.push(
    `${diff.differing.length} dimension(s) differ; ` +
      `the other ${diff.shared} are answered identically and are not listed.`,
  );
  lines.push("");
  return lines.join("\n");
}

export function renderFrictionDiffJson(diff: FrictionDiff): string {
  return installJson({
    friction_diff: {
      base: diff.base,
      compare: diff.compare,
      shared: diff.shared,
      differing: diff.differing.map((difference) => ({
        dimension: difference.dimension,
        base_value: difference.baseValue,
        compare_value: difference.compareValue,
      })),
    },
  });
}