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
39.1 KB
Raw Blame
/**
 * createNote primitive (Brain Portability & Interop suite, Unit D;
 * authoring modes from provenance-at-the-boundary, Unit C).
 *
 * The single write primitive behind the `brain_create_note` MCP tool and
 * the SDK `createNote` method. It writes one Markdown note atomically,
 * funnelled through `ensureInsideVault`, and refuses - with a typed
 * {@link CreateNoteError}, never a silent skip - any path that is not a
 * `.md` file, traverses outside the vault, spells its separators in a
 * way this host would read differently, lands in the Brain machinery
 * root, is excluded by the vault scope, falls outside the operator's
 * declared write binding, or would clobber an existing file. A vault
 * whose own `Brain/_brain.yaml` does not load is refused the same way
 * rather than raising an untyped fault. Refusing loudly is deliberate: a
 * connected agent must learn its write was rejected rather than believe
 * a note exists when it does not.
 *
 * The path this primitive REPORTS is the path the bytes are at. That is
 * a property of the envelope, not a coincidence: the reported string is
 * the one `inspectPath` normalised and the one every guard judged, and
 * the two shapes that used to break it - a caller separator rewritten on
 * the way out, and a symlinked directory redirecting the write past the
 * binding - are refused rather than reported.
 *
 * Three opt-in authoring modes sit on top of that envelope, each inert
 * when its field is absent:
 *
 *   - `ifExists: "skip"` turns the existing-target refusal into a
 *     DISCRIMINATED no-op. The result says `outcome: "skipped"`, so a
 *     caller that skipped can never read as a caller that created -
 *     returning the same shape for both would be precisely the silent
 *     fallback this project spent two releases removing. The default
 *     stays `"refuse"`.
 *   - `strict` runs the shared write-session artifact validator over the
 *     document that would be written and reports its coded violations.
 *     It is wiring, not new machinery: the validator and its schema
 *     vocabulary binding already exist.
 *   - `template` + `templateVariables` author the body through the
 *     closed two-construct grammar in `./note-template.ts`.
 *
 * The batch surface (`../write-batch.ts`) deliberately exposes NONE of
 * these. A batch is all-or-nothing, and a per-operation skip would make
 * one `applied` count mean two different things in one result list.
 */

import { existsSync, mkdirSync } from "node:fs";
import { loadPermissionsDocumentFor } from "../permissions/document-source.ts";
import { dirname, join, posix, sep, win32 } from "node:path";

import { resolveAgentName } from "../../config.ts";
import type { FrontmatterMap } from "../../types.ts";
import { normalizeAgentArgument } from "../../agent-identity.ts";
import { normalizeAgentScope } from "../../graph/agent-scope.ts";
import { GATE_MODE } from "../../integrity/stamp.ts";
import { ensureInsideVault, realVaultRelative } from "../../path-safety.ts";
import {
  ORIGIN_CHANNEL_FIELD,
  originChannelStamp,
  type OriginChannelStamp,
} from "../../origin-channel.ts";
import {
  CONTENT_CLASS_FIELD,
  contentClassCreationStamp,
  withoutCallerContentClass,
} from "../provenance/content-class.ts";
import { isFileAlreadyExists } from "../../fs-atomic.ts";
import { formatFrontmatter, writeFrontmatterAtomic } from "../../vault.ts";
import {
  inspectPath,
  resolveVaultScope,
  type InspectResult,
  type VaultScope,
} from "../../vault-scope/index.ts";
import { BRAIN_CONFIG_FILE, BRAIN_ROOT_REL, isUnderBrainRoot } from "../paths.ts";
import { viewFolderRefusal } from "../../view/vault-guard.ts";
import { requireNextStep } from "../next-step.ts";
import { BrainConfigError, loadIntegrityConfigSafe } from "../policy.ts";
import { appendDecisionLedger } from "../permissions/ledger.ts";
import { OWNER_SCOPE_WRITES_KEY, refuseCrossOwnerWrite } from "../trust/owner-write-gate.ts";
import { loadSchemaPack } from "../schema-pack.ts";
import { assertNoteVaultForWrite } from "../../vault-adapter/index.ts";
import { checkWriteBinding } from "../../write-binding/index.ts";
import { validateArtifact } from "../write-session/validate.ts";
import type { WriteSessionError } from "../write-session/types.ts";
import {
  NoteTemplateError,
  renderNoteTemplate,
  type NoteTemplateVariables,
} from "./note-template.ts";
import { NOTE_WRITE_OP, recordNoteWrite } from "./write-record.ts";
import type { PrivacyVerdict } from "../../store/operation-privacy.ts";
import { withOperationPrivacy } from "../../store/operation-scope.ts";
import { createNotePrivacy } from "./create-note-privacy.ts";
import { ROUTE_STAGE, timeStageSync } from "../../route-scope.ts";
import { REVIEW_LANE } from "../write-gate.ts";
import { resolveWriteDisposition, stageForReview } from "../pending/pending-lanes.ts";
import { substrateSubject, type WriteSubject } from "../write-disposition.ts";

/** Machine-readable reason a {@link createNote} call was refused. */
export type CreateNoteErrorCode =
  | "invalid_path"
  | "excluded"
  | "exists"
  | "outside_vault"
  | "invalid_document"
  | "invalid_template"
  // provenance-at-the-boundary, unit B. The operator's declared
  // boundary over caller-named destinations, kept distinct from
  // `excluded` on purpose: vault scope says a path is not part of the
  // vault at all, the binding says it is a real vault path that this
  // write surface may not author into.
  | "write_binding"
  // The vault's own `Brain/_brain.yaml` exists and does not validate, so
  // neither the vault scope nor the write binding can be determined.
  // Distinct from every other code here because it is NOT about the path
  // the caller named: no argument the caller could send would succeed,
  // and the operator - not the caller - holds the fix.
  | "config_invalid"
  // write-side-trust, Task 13. The caller's frontmatter names an `owner`
  // the owner-write gate refuses: a foreign token under
  // `integrity.owner_scope_writes: fail`, or an `owner_write` verdict the
  // permissions document resolved to deny/ask. Distinct from every other
  // code because it is about the OWNERSHIP CLAIM, not the path - the
  // guard runs before any existence check, so the refusal cannot answer
  // whether the target exists.
  | "owner_write_refused";

export class CreateNoteError extends Error {
  readonly code: CreateNoteErrorCode;
  /**
   * Coded validator violations. Populated only for `invalid_document`,
   * where the caller needs the fix list rather than one sentence; empty
   * for every other code.
   */
  readonly violations: ReadonlyArray<WriteSessionError>;
  constructor(
    code: CreateNoteErrorCode,
    message: string,
    violations: ReadonlyArray<WriteSessionError> = [],
  ) {
    super(message);
    this.name = "CreateNoteError";
    this.code = code;
    this.violations = violations;
  }
}

/** What to do when the target path is already occupied. */
export const CREATE_NOTE_IF_EXISTS = Object.freeze(["refuse", "skip"] as const);

/** Policy for an occupied target; `refuse` is the default and the pre-existing behaviour. */
export type CreateNoteIfExists = (typeof CREATE_NOTE_IF_EXISTS)[number];

export interface CreateNoteInput {
  /** Vault-relative target path; must end in `.md`. */
  readonly path: string;
  /** Optional frontmatter map written above the body. */
  readonly frontmatter?: FrontmatterMap;
  /** Optional Markdown body. Mutually exclusive with `template`. */
  readonly content?: string;
  /** Occupied-target policy; absent means `refuse`. */
  readonly ifExists?: CreateNoteIfExists;
  /** Run the shared artifact validator before writing. Absent means no validation. */
  readonly strict?: boolean;
  /** Body template rendered through the closed two-construct grammar. */
  readonly template?: string;
  /** Variables the template may reference; requires `template`. */
  readonly templateVariables?: NoteTemplateVariables;
  /**
   * Config file that names the writing agent, for the note-write record
   * (who-wrote-what, Task A). Absent falls back to the same discovery
   * every other Brain writer uses; a caller that KNOWS which config it
   * is running under passes it, so the record names the agent the caller
   * is, not the one the machine default happens to name.
   */
  readonly configPath?: string;
  /**
   * The credential-minted subject of the caller (write-side-trust, Task
   * 7), when the transport resolved one. When present it WINS over the
   * config resolution in both gates this primitive consults - the
   * owner-write gate's resolved identity and the review disposition's
   * permission subject - so a token whose agent a document denies is
   * refused, and the decision ledger names the token's agent, whatever
   * the process config says. Absent (stdio, the CLI) keeps the
   * config-derived subject.
   */
  readonly subject?: WriteSubject;
  /**
   * Brain store dual write: the privacy verdict of an enclosing operation
   * (a write batch), which the note-write event's store record inherits.
   */
  readonly storePrivate?: PrivacyVerdict;
}

/** What a {@link createNote} call actually did. `staged` means the review gate parked the bytes in the queue. */
export type CreateNoteOutcome = "created" | "skipped" | "staged";

/** A note written by this call. */
export interface CreatedNoteResult {
  /** Vault-relative POSIX path of the created note. */
  readonly path: string;
  readonly outcome: "created";
  readonly created: true;
  /**
   * Id of the `note-write` event that attributes this write, or null when
   * the event could not be appended (who-wrote-what, Task A).
   *
   * The bytes land first and the event is appended second, so a log
   * failure costs the audit line and never the note. `null` is therefore
   * a real state a caller has to be able to see, and it never arrives
   * alone: {@link audit_reason} names what went wrong.
   */
  readonly write_id: string | null;
  /** Why {@link write_id} is null. Absent when it is not. */
  readonly audit_reason?: string;
}

/**
 * An occupied target left exactly as it was, under `ifExists: "skip"`.
 *
 * Deliberately WITHOUT a `write_id`: a skip authored no bytes, so there
 * is no write to attribute and nothing a revert could undo. Carrying
 * `write_id: null` here would spell "the audit line was lost" for a call
 * that never had one to lose - the same conflation between "nothing
 * happened" and "something failed" the `outcome` discriminant exists to
 * prevent.
 */
export interface SkippedNoteResult {
  /** Vault-relative POSIX path of the note that was left alone. */
  readonly path: string;
  readonly outcome: "skipped";
  readonly created: false;
}

/**
 * A create STAGED into the review queue instead of published (write-side
 * trust, Task 9). The notes lane's disposition resolved to `stage`, so
 * the exact bytes this call would have published sit in
 * `Brain/pending/notes/` under a `note-` id; nothing exists at the
 * target yet.
 *
 * Deliberately WITHOUT a `write_id`, for the same reason the skip is: no
 * note was written, so there is no write to attribute. The pending id is
 * the handle an operator (or the applying agent's operator) uses to
 * publish or reject the staged bytes.
 */
export interface StagedNoteResult {
  /** Vault-relative POSIX path the note will land at when applied. */
  readonly path: string;
  readonly outcome: "staged";
  readonly created: false;
  /** Id of the pending queue entry holding the staged bytes. */
  readonly pendingId: string;
  /** Absolute path of the staged document. */
  readonly pendingPath: string;
}

/**
 * Discriminated on `outcome`. `created` is the boolean the MCP surface
 * has returned since the tool shipped and is kept in lockstep with it;
 * `outcome` is what new callers should branch on, because it stays
 * readable if a third disposition is ever added.
 */
export type CreateNoteResult = CreatedNoteResult | SkippedNoteResult | StagedNoteResult;

/** A note path resolved through the shared write safety envelope. */
export interface ResolvedNoteTarget {
  /**
   * Normalised vault-relative path, POSIX. `inspectPath` joins its
   * segments with `/` on every platform, and {@link resolveNoteTarget}
   * refuses any caller path this host would read differently, so this is
   * the path the surfaces report AND the path the bytes are at — the two
   * cannot diverge.
   */
  readonly relPath: string;
  /** Absolute filesystem path, guaranteed inside the vault. */
  readonly abs: string;
  /**
   * Server-derived channel of the process resolving this target (Unit C).
   * Resolved HERE, in the one envelope all four caller-named note tools
   * share, so no arm can reach a write without having been handed the
   * channel, and no arm can be given a different one.
   *
   * It is a resolution output, not an input: nothing on
   * {@link CreateNoteInput} names it, and `src/core/origin-channel.ts`
   * says why a caller-nameable channel would be worthless.
   */
  readonly originChannel: OriginChannelStamp;
}

/**
 * The separator that is structure on Windows and an ordinary filename
 * character everywhere else. Named once because the reason it matters is
 * that this host's answer differs from the other host's.
 */
const WINDOWS_SEP = win32.sep;

/**
 * Registry code for a vault whose Brain config does not load, resolved
 * at module scope so registry drift fails at import rather than inside
 * the refusal it was meant to explain (same rule as the write binding's
 * own exit).
 */
export const NOTE_CONFIG_INVALID_CODE = "config-invalid";
const CONFIG_INVALID_EXIT = requireNextStep(NOTE_CONFIG_INVALID_CODE).nextCommand;

/** Vault-relative spelling of the config file every refusal here names. */
const BRAIN_CONFIG_REL = posix.join(BRAIN_ROOT_REL, BRAIN_CONFIG_FILE);

/**
 * Refuse a caller-named path whose separators this host does not read
 * the way the caller wrote them.
 *
 * THE DECISION, and why it is a refusal rather than a normalisation.
 * On POSIX a backslash is an ordinary filename character, and three
 * layers of this envelope disagreed about that: the write-binding
 * matcher split on it (so a binding on `Projects` admitted
 * `Projects\evil.md`), the result renderer rewrote it to `/` (so the
 * tool reported `Projects/evil.md`), and `inspectPath`, the `..`
 * traversal guard, the `Brain/` machinery-root check and every
 * POSIX-written vault-scope ignore rule treated it as literal (so the
 * bytes landed in ONE file at the vault ROOT, named `Projects\evil.md`).
 *
 * Picking a reading is the tempting fix and the wrong one. Normalising
 * `\` to `/` silently reinterprets the caller's string into a different
 * path than the one it sent, and treating it as literal leaves a
 * boundary that a caller can talk past. This repository forbids the
 * quiet reinterpretation, so the path is refused and the caller is told
 * which character made it ambiguous. A caller that meant a subdirectory
 * re-sends it with `/`; a caller that genuinely meant a backslash in a
 * filename has asked for something no surface here can report
 * faithfully.
 *
 * On Windows this never fires: `\` IS the separator there, and
 * `inspectPath` converts it to POSIX before anything downstream sees it.
 */
function assertHostPathSeparators(path: string): void {
  if (WINDOWS_SEP === sep) return;
  if (!path.includes(WINDOWS_SEP)) return;
  throw new CreateNoteError(
    "invalid_path",
    `note path must use '${posix.sep}' to separate segments; on this host ` +
      `'${WINDOWS_SEP}' is an ordinary filename character, so the path would not ` +
      `mean what it looks like: ${path}`,
  );
}

/**
 * Translate a Brain config failure into this surface's typed refusal.
 *
 * The raw {@link BrainConfigError} names the config by its ABSOLUTE host
 * path, which is the one thing no other refusal on this surface leaks
 * and which a connected agent cannot act on. The re-raised error keeps
 * the validator's own diagnosis, renames the source to its vault-
 * relative spelling, and appends the registered exit, so a caller that
 * hits it learns what to run instead of receiving a bare fault.
 */
function configFault(err: BrainConfigError): CreateNoteError {
  const source = err.source;
  const prefix = source === null ? null : `${source}: `;
  const detail =
    prefix !== null && err.message.startsWith(prefix)
      ? err.message.slice(prefix.length)
      : err.message;
  return new CreateNoteError(
    "config_invalid",
    `${BRAIN_CONFIG_REL}: ${detail}; ${CONFIG_INVALID_EXIT}`,
  );
}

/**
 * The refusal sentence for a path vault scope rejects, naming the key
 * the operator has to open and the declaration that decided it.
 *
 * The two polarities read differently on purpose: an exclusion names
 * the single entry that fired, because that entry is the thing to
 * delete; an allowlist names the whole list, because nothing in it
 * fired and the fix is to add a root.
 */
function scopeRefusal(scope: VaultScope, inspected: InspectResult): string {
  if (inspected.reason === "not-included") {
    return `path is outside vault.include_paths (${(scope.includePaths ?? []).join(", ")})`;
  }
  return `path is excluded by vault.ignore_paths (${inspected.rule?.raw ?? "rule"})`;
}

/**
 * Run `read`, translating a Brain config failure into {@link configFault}.
 * Shared by the two config-backed checks in the envelope — the vault
 * scope and the write binding — so a malformed config reads the same on
 * whichever of them reaches it first.
 */
function withConfigFault<T>(read: () => T): T {
  try {
    return read();
  } catch (err) {
    if (err instanceof BrainConfigError) throw configFault(err);
    throw err;
  }
}

/**
 * Resolve and safety-check a vault-relative note path - the exact
 * envelope enforced by {@link createNote}: `.md` suffix, vault-relative
 * (no absolute path), separators this host reads the way the caller
 * wrote them, no `..` traversal, not the Brain machinery root, not a
 * vault-scope-excluded location, inside the operator's declared write
 * binding, and inside the vault. Every refusal is a typed
 * {@link CreateNoteError} - including the one case that is not about the
 * path at all, a `Brain/_brain.yaml` that does not load. Extracted so the
 * atomic write-batch core (kernel 2) reuses the same envelope for update
 * and append operations rather than re-deriving it.
 *
 * Order is load-bearing. The separator check runs FIRST, before anything
 * normalises the string, because every guard after it reads segments and
 * they must all be reading the same segments the caller meant.
 */
export function resolveNoteTarget(vault: string, path: string): ResolvedNoteTarget {
  if (!path.toLowerCase().endsWith(".md")) {
    throw new CreateNoteError("invalid_path", `note path must end in .md: ${path}`);
  }
  // The tool addresses notes by a vault-relative path; an absolute path is
  // ambiguous (which root?) and is refused rather than silently re-rooted.
  if (path.startsWith(posix.sep) || path.startsWith(WINDOWS_SEP)) {
    throw new CreateNoteError("invalid_path", `note path must be vault-relative: ${path}`);
  }
  // Before any normalisation reads the string: refuse a separator this
  // host would not read the way the caller wrote it. See the function.
  assertHostPathSeparators(path);

  // inspectPath normalises the relative path and throws on `..` traversal;
  // an absolute path also has no place here. Translate both into a typed
  // CreateNoteError so callers get one error surface.
  const scope = withConfigFault(() => resolveVaultScope(vault));
  let inspected;
  try {
    inspected = inspectPath(path, scope, vault);
  } catch (err) {
    throw new CreateNoteError("invalid_path", err instanceof Error ? err.message : String(err));
  }
  const relPath = inspected.relPath;
  if (relPath === "") {
    throw new CreateNoteError("invalid_path", `empty note path: ${path}`);
  }

  // The Brain machinery root is owned by the brain's own writers; a
  // free-form note tool must never author into it (default vault-scope
  // rules ignore Brain/.snapshots only, not the whole Brain root). The
  // segment is compared case-insensitively: `brain/standing-rules.md`
  // opens the same file on the case-insensitive macOS and Windows
  // defaults, so a case-sensitive compare let an update rewrite it there.
  if (isUnderBrainRoot(relPath)) {
    throw new CreateNoteError(
      "excluded",
      `the Brain machinery root is not writable via create_note: ${relPath}`,
    );
  }
  // The lexical check reads the path as spelled; a vault folder or note
  // that is a symbolic link into `Brain/` carries the bytes there anyway.
  // Re-read where they land. A path that cannot be resolved (a file used
  // as a folder, a link loop, an unreadable folder) is refused, never
  // guessed at, and so is one that lands outside the vault.
  let landsAt: string | null;
  try {
    landsAt = realVaultRelative(vault, relPath);
  } catch (err) {
    const code = (err as NodeJS.ErrnoException)?.code ?? "unknown";
    throw new CreateNoteError("invalid_path", `note path cannot be resolved (${code}): ${relPath}`);
  }
  if (landsAt === null) {
    throw new CreateNoteError("outside_vault", `note path resolves outside the vault: ${relPath}`);
  }
  if (isUnderBrainRoot(landsAt)) {
    throw new CreateNoteError(
      "excluded",
      `the Brain machinery root is not writable via create_note: ${relPath} resolves to ${landsAt}`,
    );
  }
  // The human view folder, when it sits in the vault, is the view
  // writer's: a page edited there is read back with human authority
  // (`core/view/vault-guard.ts`), so a note tool must not write it.
  for (const rel of new Set([relPath, landsAt])) {
    const viewRefusal = viewFolderRefusal(vault, rel, "the note tools");
    if (viewRefusal !== null) throw new CreateNoteError("excluded", viewRefusal);
  }

  // Vault scope is ONE policy every consumer obeys, so a write is
  // refused wherever a walk would be refused - a note authored outside
  // the operator's declared `include_paths` would never be indexed,
  // never be recalled, and never be found again, which is a worse
  // outcome than being told no. The message names WHICH polarity
  // refused, because "excluded by vault scope" sends an operator to
  // read the wrong list: an entry they wrote under `ignore_paths` is a
  // different fix from a root missing from `include_paths`.
  if (inspected.excluded) {
    throw new CreateNoteError("excluded", `${scopeRefusal(scope, inspected)}: ${relPath}`);
  }

  // The operator's declared write binding (provenance-at-the-boundary,
  // unit B). This function is the ONE envelope every caller-named NOTE
  // write shares - `createNote` and the batch core's create / update / append
  // arms all resolve their target here - so the boundary is checked
  // exactly once, before any directory is created or byte written. The
  // refusal is composed in the binding module, never here; absent
  // declaration returns null and this whole branch is inert.
  const refusal = withConfigFault(() => checkWriteBinding(vault, relPath));
  if (refusal !== null) {
    throw new CreateNoteError("write_binding", refusal.message);
  }

  let abs: string;
  try {
    abs = ensureInsideVault(join(vault, relPath), vault);
  } catch (err) {
    throw new CreateNoteError("outside_vault", err instanceof Error ? err.message : String(err));
  }
  return { relPath, abs, originChannel: originChannelStamp() };
}

/**
 * The one no-op result. Built in a single place because it is reached
 * from two arms - the pre-write existence check and the exclusive-link
 * refusal that closes the race behind it - and the two must not be able
 * to drift into reporting a skip differently.
 *
 * `relPath` is reported verbatim. It used to be re-split on `[\\/]` and
 * re-joined with `/`, which was the only place the reported path could
 * differ from the path that holds the bytes: on POSIX that rewrote a
 * file literally named `Projects\evil.md` at the vault root into the
 * report `Projects/evil.md`. Such a path is now refused at the envelope,
 * and {@link ResolvedNoteTarget.relPath} is already POSIX, so there is
 * nothing left to convert.
 */
function skippedResult(relPath: string): SkippedNoteResult {
  return { path: relPath, outcome: "skipped", created: false };
}

/**
 * Resolve the body to write. Exactly one of `content` and `template` may
 * be supplied; providing both, or variables with no template, is a
 * caller fault named rather than resolved by letting one win.
 */
function resolveBody(input: CreateNoteInput): string {
  if (input.template === undefined) {
    if (input.templateVariables !== undefined) {
      throw new CreateNoteError(
        "invalid_template",
        "templateVariables requires 'template'; supply a template or drop the variables",
      );
    }
    return input.content ?? "";
  }
  if (input.content !== undefined) {
    throw new CreateNoteError(
      "invalid_template",
      "provide either 'content' or 'template', not both",
    );
  }
  try {
    return renderNoteTemplate(input.template, input.templateVariables ?? {});
  } catch (err) {
    if (err instanceof NoteTemplateError) {
      throw new CreateNoteError("invalid_template", `${err.code}: ${err.message}`);
    }
    throw err;
  }
}

/**
 * Run the shared write-session artifact validator over the document that
 * would be written. The schema type is whatever the frontmatter itself
 * declares, checked against the vault's `page_types` vocabulary - the
 * same binding `validateArtifactForSession` uses, so `strict` here and a
 * write session there judge a document identically.
 *
 * Note this is the CLI's `--strict` in name only: there it escalates
 * warnings into an exit code, here it is a pre-write gate. The two never
 * meet, because no command-line verb reaches this primitive.
 */
function assertValidDocument(vault: string, frontmatter: FrontmatterMap, body: string): void {
  const declaredType = frontmatter["type"];
  const schemaType = typeof declaredType === "string" ? declaredType : null;
  const violations = validateArtifact(formatFrontmatter(frontmatter, body), {
    schemaType,
    vocabulary: loadSchemaPack(vault).vocabulary,
  });
  if (violations.length > 0) {
    throw new CreateNoteError(
      "invalid_document",
      `note failed strict validation: ${violations.map((v) => v.code).join(", ")}`,
      violations,
    );
  }
}

/**
 * The `owner:` frontmatter key a caller may name on a note - gated, not
 * reserved: under `integrity.owner_scope_writes: off` it writes exactly
 * as it always did, and the gate (`../trust/owner-write-gate.ts`)
 * decides when it refuses. Named once here because both note-lane call
 * sites - this create guard and the batch's update guard - read the same
 * key.
 */
export const NOTE_OWNER_FRONTMATTER_KEY = "owner";

/** The outcome of the note-lane owner gate. `refused` carries `reason`. */
export interface NoteOwnerGateResult {
  readonly refused: boolean;
  /** The predicate's verdict sentence, present only on a refusal. */
  readonly reason?: string;
}

/**
 * What the gate decided about one caller-named `owner:` claim, before any
 * row is logged: the two-state answer a PROJECTION phase needs, so an
 * all-or-nothing caller can refuse before any byte and still log the warn
 * row exactly once, at the commit.
 */
export interface NoteOwnerGateOutcome extends NoteOwnerGateResult {
  /** True when the mode is `warn` and the claim is one `fail` would refuse. */
  readonly watch: boolean;
  /** The owner token as the caller named it, when one was named. */
  readonly named: string;
  /** The identity the process resolved for the caller. */
  readonly resolvedIdentity: string;
}

/**
 * Consult the owner-write gate for the note lane (write-side-trust,
 * Task 13), shared by every call site that takes caller-authored note
 * frontmatter. A caller-named `owner:` is the same claim on a note that
 * it is on a preference, and one lane honouring what the other refuses
 * would be an isolation boundary with a door in it.
 *
 * Gate off with no owner named refuses nothing and reads nothing - not
 * one byte of legacy behavior moves, and no config or document read is
 * spent on it. With an owner named, the gate mode reads through the safe
 * integrity loader (absent config resolves `off`; an UNREADABLE one
 * resolves the strict `fail`, which can close this gate but never open
 * it) and the permissions document through the permissions loader
 * (absent is null; unreadable raises with the field named - that
 * document's own fail-closed contract).
 *
 * Writes nothing: a caller can run this ahead of every existence check
 * and refuse a foreign claim without ever answering whether the target
 * exists.
 */
export function noteOwnerGateVerdict(
  vault: string,
  frontmatter: FrontmatterMap | undefined,
  configPath: string | undefined,
  subject?: WriteSubject,
): NoteOwnerGateOutcome {
  const claim = frontmatter?.[NOTE_OWNER_FRONTMATTER_KEY];
  if (claim === undefined || claim === null) {
    return { refused: false, watch: false, named: "", resolvedIdentity: "" };
  }
  const named = typeof claim === "string" ? claim : String(claim);
  // The credential-minted subject wins over the config resolution
  // (write-side-trust, Task 7): a token's owner gate answers for the
  // token's agent, never for whoever the process config names.
  const resolved = subject?.agent ?? resolveAgentName(configPath);
  const gateMode = loadIntegrityConfigSafe(vault).owner_scope_writes;
  const { document } = loadPermissionsDocumentFor(vault, configPath);
  const verdict = refuseCrossOwnerWrite({
    frontmatterOwner: named,
    resolvedIdentity: resolved,
    gateMode,
    document,
    subject: substrateSubject(subject ?? { agent: resolved, via: "config" }),
  });
  if (verdict.refused)
    return {
      refused: true,
      reason: verdict.reason,
      watch: false,
      named,
      resolvedIdentity: resolved,
    };
  return {
    refused: false,
    watch: gateMode === GATE_MODE.warn,
    named,
    resolvedIdentity: resolved,
  };
}

/**
 * The note-lane owner gate for a single writer: consult, refuse, and -
 * under `warn` - log the one decision-ledger row with the gate key as
 * its source, so the operator can watch what `fail` would refuse. The
 * write this call guards proceeds only when the result says so.
 */
export function gateNoteOwnerFrontmatter(
  vault: string,
  relPath: string,
  frontmatter: FrontmatterMap | undefined,
  configPath: string | undefined,
  subject?: WriteSubject,
): NoteOwnerGateResult {
  const outcome = noteOwnerGateVerdict(vault, frontmatter, configPath, subject);
  if (outcome.refused) return { refused: true, reason: outcome.reason };
  if (outcome.watch) {
    logWatchedNoteOwnerWrite(
      vault,
      relPath,
      outcome.named,
      outcome.resolvedIdentity,
      subject?.via ?? "config",
    );
  }
  return { refused: false };
}

/**
 * The one `warn` ledger row for an owner-carrying note write, or nothing
 * when the named owner agrees with the resolved identity (the one case
 * `fail` would not refuse is the one case there is nothing to watch).
 * The comparison is the same normalised token comparison the predicate
 * makes; the predicate module stays pure, so the row lives with its
 * callers. Exported for the batch kernel, which consults the verdict at
 * projection and logs at the commit so a later operation's refusal never
 * leaves a row behind for a write that never happened.
 */
export function logWatchedNoteOwnerWrite(
  vault: string,
  target: string,
  named: string,
  resolved: string,
  via: WriteSubject["via"] = "config",
): void {
  const token = normalizeAgentScope(named);
  const identity = normalizeAgentScope(normalizeAgentArgument(resolved) ?? undefined);
  if (token === null || identity === null || token === identity) return;
  appendDecisionLedger(vault, {
    ts: new Date().toISOString(),
    actor: resolved,
    via,
    action: "owner_write",
    target,
    verdict: GATE_MODE.warn,
    source: OWNER_SCOPE_WRITES_KEY,
    reason:
      `frontmatter owner ${JSON.stringify(named)} allowed under ${GATE_MODE.warn}; ` +
      `${OWNER_SCOPE_WRITES_KEY}=${GATE_MODE.fail} would refuse it ` +
      `(resolved identity ${JSON.stringify(resolved)})`,
  });
}

/**
 * Create one Markdown note in the vault. Returns a discriminated
 * {@link CreateNoteResult}; throws {@link CreateNoteError} on any
 * refusal.
 */
export function createNote(vault: string, input: CreateNoteInput): CreateNoteResult {
  // One operation: every store record written below (the owner-write
  // decision row, the review gate's row, the note-write event) carries the
  // create's verdict (`store/operation-scope.ts`).
  return withOperationPrivacy(createNotePrivacy(vault, input), () =>
    createNoteInScope(vault, input),
  );
}

function createNoteInScope(vault: string, input: CreateNoteInput): CreateNoteResult {
  // Vault-identity write guard (context-integrity-gates, Unit J). This
  // backs `brain_create_note`, `brain_append_note`, and
  // `brain_update_note` - the headline note writers.
  // Through the vault adapter (design D14 items 8, 13): a vault is
  // required, and the vault identity guard holds.
  assertNoteVaultForWrite(vault, "note writes");
  const { relPath, abs, originChannel } = resolveNoteTarget(vault, input.path);
  const callerFrontmatter = input.frontmatter ?? {};
  // The owner-write gate runs BEFORE the body resolves, before validation,
  // and before any existence or staging decision: a refused claim must
  // cost no bytes anywhere - the publish target, the pending queue, and
  // the refusal's own information content included. The refusal reads the
  // same whether the target is free, occupied or already staged-for-
  // review, so a caller probing foreign owners learns nothing about which
  // paths are real.
  const ownerGate = gateNoteOwnerFrontmatter(
    vault,
    relPath,
    callerFrontmatter,
    input.configPath,
    input.subject,
  );
  if (ownerGate.refused) {
    throw new CreateNoteError(
      "owner_write_refused",
      `note create at ${relPath}: ${ownerGate.reason}`,
    );
  }
  const body = resolveBody(input);
  // Validation judges the INPUT, so it runs before the target is
  // consulted: a caller must not learn that its document is invalid
  // only on the runs where the path happened to be free.
  //
  // It also runs before the origin-channel stamp is merged, and that
  // ordering is load-bearing rather than incidental: the validator's
  // `frontmatter-missing` violation asks whether the CALLER wrote a
  // frontmatter block, and a server-derived key merged first would
  // satisfy it on every document, silently retiring a refusal that
  // exists.
  if (input.strict === true) assertValidDocument(vault, callerFrontmatter, body);

  // The server-derived stamps (Unit C, and the content class beside it)
  // go on LAST, so a caller that supplied a key of either name loses to
  // the process that actually wrote the note. A caller-named
  // `content_class` is not merely outranked but dropped: on an unmarked
  // write the honest byte is NO key, and letting the caller's through
  // would let an mcp-transport caller forge an exclusion that ripples
  // all the way to the export boundary.
  //
  // Stamped on CREATION only. `update_note` and `append_note` rewrite a
  // note this call did not author and keep the creating channel - the same
  // objection that refuses backfilling the field onto existing records -
  // with the one delivery-trust exception the mutation seam itself applies
  // (`write-batch.ts`, `mutationChannelStamp`): a writer whose own channel
  // differs never keeps an inherited `cli` stamp, because the delivery
  // side reads that stamp as operator-authorship of the words the
  // mutation left behind.
  const callerFrontmatterWithoutClass = withoutCallerContentClass(callerFrontmatter);
  const contentClass = contentClassCreationStamp(originChannel);
  const frontmatter: FrontmatterMap = {
    ...callerFrontmatterWithoutClass,
    [ORIGIN_CHANNEL_FIELD]: originChannel,
    ...(contentClass !== null ? { [CONTENT_CLASS_FIELD]: contentClass } : {}),
  };

  const skipOccupied = input.ifExists === "skip";
  // Return before mkdirSync so a no-op leaves no parent directories
  // behind. The authoritative decision is still the exclusive-link
  // refusal below, which closes the residual TOCTOU race race-free.
  if (skipOccupied && existsSync(abs)) {
    return skippedResult(relPath);
  }

  // Review gate (write-side trust, Tasks 9 and 12). A CREATE stages under
  // the notes lane's disposition; updates and appends never reach this
  // primitive. The review boundary is ENTRY, not mutation: a target that
  // already exists was admitted when it was published, so the ordinary
  // refusal stands and only a first publish can be staged. The staged
  // bytes are byte-for-byte what the write below would have published -
  // the origin-channel stamp included - so apply reproduces the published
  // document exactly. Under a permissions document the document alone
  // decides for the caller the write record would have named, and a deny
  // refuses here as a typed WriteRefusedError before any byte exists.
  const disposition = resolveWriteDisposition(
    vault,
    REVIEW_LANE.notes,
    // The credential-minted subject wins over the config resolution
    // (write-side-trust, Task 7); resolveAgentName stays the stdio and
    // CLI fallback.
    input.subject ?? { agent: resolveAgentName(input.configPath), via: "config" },
    // The no-subject fallback (unused while a subject always arrives, and
    // honest if that ever changes) resolves through this caller's config.
    { target: relPath, configPath: input.configPath },
  );
  if (disposition.verdict === "stage") {
    if (existsSync(abs)) {
      throw new CreateNoteError("exists", `note already exists: ${relPath}`);
    }
    const bytes = formatFrontmatter(frontmatter, body);
    const staged = stageForReview(vault, REVIEW_LANE.notes, relPath, () => bytes);
    return {
      path: relPath,
      outcome: "staged",
      created: false,
      pendingId: staged.pendingId,
      pendingPath: staged.path,
    };
  }

  mkdirSync(dirname(abs), { recursive: true });
  try {
    timeStageSync(ROUTE_STAGE.documentWrite, () =>
      writeFrontmatterAtomic(abs, frontmatter, body, {
        overwrite: false,
        existsErrorKind: "note",
        vaultForRelativePath: vault,
      }),
    );
  } catch (err) {
    // One predicate for "the name was taken", shared with every other
    // collision-aware call site. The hand-rolled pair it replaces read
    // the errno OR matched the wording of the message - and a message
    // match is a coupling to prose that nothing stops anyone rewording.
    if (isFileAlreadyExists(err)) {
      if (skipOccupied) {
        return skippedResult(relPath);
      }
      throw new CreateNoteError("exists", `note already exists: ${relPath}`);
    }
    throw err;
  }

  // The bytes are on disk. Record the write LAST and never let the
  // recording fail it: `recordNoteWrite` returns its failure instead of
  // throwing, and the reason rides out on the result rather than being
  // swallowed here (who-wrote-what, Task A). A create replaces nothing,
  // so there is no before-image to store and `hash_before` is `absent`.
  const receipt = timeStageSync(ROUTE_STAGE.writeReceipt, () =>
    recordNoteWrite(vault, {
      op: NOTE_WRITE_OP.create,
      target: relPath,
      before: null,
      after: { bytes: formatFrontmatter(frontmatter, body) },
      ...(input.configPath !== undefined ? { configPath: input.configPath } : {}),
      ...(input.storePrivate !== undefined ? { storePrivate: input.storePrivate } : {}),
    }),
  );
  return { path: relPath, outcome: "created", created: true, ...receipt };
}