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
61.1 KB
Raw Blame
/**
 * Note-file lifecycle: rename, move, delete, archive (B2).
 *
 * Before this module there was no rename, no move, no delete and no
 * archive on ANY surface. `brain_create_note`, `brain_update_note` and
 * `brain_append_note` were the whole of it: a note could be brought into
 * existence and edited, and after that it was immovable and undeletable
 * through everything this project ships. The remedy an agent actually had
 * was to write the correctly-named note and abandon the wrong one, which
 * is how a vault grows the duplicates the dedup pass then has to reason
 * about.
 *
 * ## Nothing here is new machinery
 *
 * The path envelope is {@link resolveNoteTarget} - the same nine-step
 * refusal ladder `createNote` runs - and BOTH the source and the
 * destination go through it, so a destination cannot reach somewhere a
 * create could not. The relocation is the write-then-unlink-then-assert
 * pattern `signal-retire.ts:141-152` establishes. The confirmation ladder
 * is `deleteBySource`'s: dry-run by default, an explicit confirm, and the
 * shared {@link assertExpectedCount} guard. The recovery point is
 * `withDestructiveSnapshot`, and its verdict is the R1a classifier.
 *
 * ## The honesty requirement, which is the hard part
 *
 * A rename that reports success and stops is a lie, and it is worth being
 * precise about which lie. The Brain backlink index (`backlinks.ts`) is a
 * full scan and Brain-scoped. The vault-wide `links` table is only as
 * fresh as the last `indexVault` pass. An applied relocation or delete
 * now CLAIMS one detached, claim-guarded refresh of that index - the
 * freshen-on-read machinery run at force - so the window in which the
 * index still holds the old paths starts closing at the write itself,
 * and the claim rides the report beside the evidence. The claim is not
 * an invariant: until the detached run lands, a search can still answer
 * from the old paths. So a rename can truthfully say only this: of the
 * Markdown files it READ during this call, these are the ones whose
 * `[[...]]` spellings it rewrote, and the derived index holds the old
 * path until the claimed run - or the command on the report - lands.
 *
 * Three consequences are load-bearing and each is reported rather than
 * assumed:
 *
 *   - the bare-basename spelling `[[Old]]` is rewritten whenever it
 *     uniquely resolved to the source before the move - the source is
 *     the basename's only carrier, or the source is top-level and owns
 *     the spelling through the exact-path rung - and the rewrite aims at
 *     the minimal spelling of the destination, which is unambiguous by
 *     construction whatever note count the move creates. Two nested
 *     notes named `Old.md` in different folders still withhold it:
 *     there `[[Old]]` named whichever one Obsidian resolves, and
 *     rewriting it would re-point a link that never pointed here. The
 *     verdict token says which of the three happened.
 *   - the search index's state travels back on the result as an
 *     {@link IndexEvidence}, with the instant of its last pass and the
 *     command that makes it agree with the vault again.
 *   - a delete rewrites NOTHING and reports the inbound references it is
 *     about to strand, because a delete that silently repaired its own
 *     inbound links would be erasing the evidence that it happened. This
 *     holds under `--delete-linked` too, and the flag is narrower than
 *     its name suggests for exactly that reason - see "What
 *     --delete-linked may remove" below.
 *   - a rewrite that could not be written is NAMED. The operation is not
 *     rolled back, and the result says where it split - see
 *     {@link noteLifecycle} for why one half-state is preferable to the
 *     other and why a silent one is preferable to neither.
 *   - the recoverability verdict covers the rewrite and not only the
 *     move. Relocating bytes destroys nothing; overwriting a
 *     hand-authored note's `[[...]]` spellings in place does, and nothing
 *     in this project regenerates a user's prose.
 *
 * ## What the collateral writes may reach, and what they may not
 *
 * The reference scan walks the vault, and three exclusions define what
 * that means. Two belong to `retargetWikilinks` and apply to every
 * caller: nothing whose realpath leaves the vault, and nothing
 * `vault.ignore_paths` / `include_paths` refuses - the same scope this
 * surface's own endpoints are judged by, so a write is refused wherever a
 * walk would be.
 *
 * The third is this module's: `Brain/log` is read and reported but never
 * rewritten. `Brain/` is the one tree `resolveNoteTarget` refuses to let
 * this surface ADDRESS, and it was nevertheless entirely in range of the
 * surface's collateral writes - a user-note rename edited the observation
 * log, which is an append-only record of what an agent said at a time.
 * The rest of `Brain/` stays in range on purpose: an artifact citing a
 * note by path holds an ordinary reference, and it dangles exactly like a
 * user note's would.
 *
 * ## What `--delete-linked` may remove, and what it may not
 *
 * The commitment above - a delete repairs nothing and reports what it
 * strands - is not weakened by the cascade, because the cascade never
 * REPAIRS anything either. It removes a second class of file: the
 * single-purpose derived artifact whose entire content is a restatement
 * of the note, and which therefore has no meaning once the note is gone.
 * The rule deciding membership is not this module's; it is
 * `source-cleanup.ts`'s, called through {@link traceNoteDerivations}, so
 * "derived solely from" means one thing in this project rather than two.
 *
 * Membership additionally requires DECLARED provenance, and only on this
 * path: the page's own frontmatter has to name the note as what it was
 * derived from. See {@link planCascade} for why the shared rule is not
 * sufficient here.
 *
 * Four consequences follow and each is on the response:
 *
 *   - a page that only MENTIONS the note - a `[[Note]]` in prose, with no
 *     `source:` array naming it - is reported and left alone, however
 *     derived-looking the page's directory is;
 *   - a page citing a SECOND source - a signal naming another note, a
 *     preference folded from a foreign signal - is reported and left
 *     alone, exactly as it is by `deleteBySource`;
 *   - everything the inbound probe found that is not in the deletion set
 *     is reported and left alone, including every user note. The two
 *     lists are disjoint and both are returned, so a caller never has to
 *     subtract one from the other to find out what survives;
 *   - the fold walks {@link DERIVED_SET_SCOPE} and the response says so.
 *     A user note is outside it by construction and no scan widening
 *     would change that - nothing outside `Brain/` is a derivation this
 *     project generated - but an empty derived set must be legible as a
 *     measurement rather than as an unstated scope limit.
 *
 * ## Where an archived note goes, and why
 *
 * `NOTE_ARCHIVE_ROOT` - a top-level `Archive/` directory mirroring the
 * note's original path. The precedents are `Brain/retired/` for
 * preferences, `Brain/processed/` for signals, and the `archive/` sibling
 * `obligations.ts:366` writes into. Two things carry over from them and
 * one cannot:
 *
 *   - the SHAPE carries: a sibling directory named for the terminal
 *     state, holding the file under a name that cannot collide, with an
 *     occupied destination refused rather than overwritten.
 *   - the PATH-MIRRORING is this surface's own, and it is forced. Those
 *     three precedents are flat because their subjects carry unique ids;
 *     a note is addressed by path and two notes in different folders may
 *     share a basename, so flattening would collide by construction.
 *   - the LOCATION cannot carry. `resolveNoteTarget` refuses the `Brain/`
 *     machinery root for every note path, source and destination alike,
 *     so `Brain/retired/`'s own location is unreachable from here - and
 *     making an exception for it would put the one surface that moves
 *     user notes outside the envelope every other note write obeys.
 */

import {
  constants,
  copyFileSync,
  existsSync,
  linkSync,
  mkdirSync,
  statSync,
  unlinkSync,
  type BigIntStats,
  type Stats,
} from "node:fs";
import { dirname, join, posix } from "node:path";

import { isFileAlreadyExists, renameWithRetry } from "../../fs-atomic.ts";
import { ensureInsideVault } from "../../path-safety.ts";
import { pathCovers } from "../../vault-scope/defaults.ts";
import { assertExpectedCount } from "../count-guard.ts";
import { DERIVATION_SCAN_SCOPE, traceNoteDerivations } from "../source-cleanup.ts";
import { BRAIN_LOG_REL, BRAIN_ROOT_REL } from "../path-constants.ts";
import { classifyRecoverability, type RecoverabilityVerdict } from "../gates/recoverability.ts";
import { retargetWikilinks, type WikilinkRetarget } from "../page-dedup.ts";
import { minimalSpellingFor } from "../link-graph/minimal-spelling.ts";
import { withDestructiveSnapshot } from "../snapshot-gate.ts";
import { BRAIN_SNAPSHOT_REASON } from "../types.ts";
import { assertNoteVaultForWrite } from "../../vault-adapter/index.ts";
import { resolveNoteTarget, type ResolvedNoteTarget } from "./create-note.ts";

// ----- What a caller may ask for --------------------------------------------

/**
 * The six operations. `rename` and `move` are one relocation under the
 * hood and are kept apart at the surface deliberately: a caller that
 * meant to change a note's NAME and accidentally changed its FOLDER has
 * made a mistake no path check would catch, because both spellings are
 * perfectly legal destinations. Declaring which one was intended lets the
 * other be refused. The folder actions (`move-folder`, `rename-folder`)
 * split the same way at folder granularity - see
 * `./folder-lifecycle.ts`, the module that runs them - so a caller that
 * meant to rename a folder and accidentally moved it across parents is
 * caught by the same discipline instead of by the consequences.
 */
export const NOTE_LIFECYCLE_ACTION = Object.freeze({
  /** Change the filename, keeping the note in its directory. */
  rename: "rename",
  /** Change the directory, keeping the filename. */
  move: "move",
  /** Displace the note under {@link NOTE_ARCHIVE_ROOT}, path mirrored. */
  archive: "archive",
  /** Remove the note. The one operation here that destroys bytes. */
  delete: "delete",
  /**
   * Move a whole folder under a destination parent. A file action
   * (`rename`/`move`/`archive`/`delete`) refuses a folder subject, and
   * this action runs in `./folder-lifecycle.ts`.
   */
  moveFolder: "move-folder",
  /**
   * Rename a whole folder within its parent. Split from `move-folder`
   * for the same reason `rename` is split from `move`.
   */
  renameFolder: "rename-folder",
} as const);

/** Closed union over {@link NOTE_LIFECYCLE_ACTION}. */
export type NoteLifecycleAction =
  (typeof NOTE_LIFECYCLE_ACTION)[keyof typeof NOTE_LIFECYCLE_ACTION];

/** Membership list, least destructive first. */
export const NOTE_LIFECYCLE_ACTIONS: ReadonlyArray<NoteLifecycleAction> = Object.freeze(
  Object.values(NOTE_LIFECYCLE_ACTION),
);

/**
 * `unknown` rather than `string`: the value arrives as an untyped MCP
 * argument or a raw CLI positional, and the vocabulary census probes
 * every guard with `null`, `42` and `{}`.
 */
export function isNoteLifecycleAction(value: unknown): value is NoteLifecycleAction {
  return (
    typeof value === "string" && (NOTE_LIFECYCLE_ACTIONS as ReadonlyArray<string>).includes(value)
  );
}

// ----- What happened to the bare-basename spelling --------------------------

/**
 * What this call did about `[[Old]]` - the spelling Obsidian writes by
 * default and the only one of the three that is not unique by
 * construction.
 */
export const BASENAME_REWRITE = Object.freeze({
  /**
   * The bare spelling uniquely resolved to the source before the move,
   * so it was rewritten - onto the minimal spelling of the destination,
   * which is unambiguous by construction whatever the destination
   * basename's carrier count became.
   */
  applied: "applied",
  /** The basename did not change, so no bare spelling needed rewriting. */
  notNeeded: "not_needed",
  /**
   * The bare spelling never uniquely named the source: a nested source
   * with several same-basename carriers resolved, by the ladder's
   * basename rung, to whichever one the resolver picked, and rewriting
   * it could re-point a link that never pointed here.
   */
  ambiguous: "ambiguous",
} as const);

/** Closed union over {@link BASENAME_REWRITE}. */
export type BasenameRewrite = (typeof BASENAME_REWRITE)[keyof typeof BASENAME_REWRITE];

/** Membership list, in declaration order. */
export const BASENAME_REWRITES: ReadonlyArray<BasenameRewrite> = Object.freeze(
  Object.values(BASENAME_REWRITE),
);

/** See {@link isNoteLifecycleAction} for why the parameter is `unknown`. */
export function isBasenameRewrite(value: unknown): value is BasenameRewrite {
  return typeof value === "string" && (BASENAME_REWRITES as ReadonlyArray<string>).includes(value);
}

// ----- How stale the derived index is ---------------------------------------
//
// The vocabulary, the evidence read and the refresh claim live in
// `./index-refresh.ts` - lifted out of this module so the note create and
// content-update writers could claim the SAME refresh without importing
// the lifecycle back (this module already imports their path envelope,
// and a second copy of the claim is how two surfaces come to report two
// different refusals). This module re-exports the vocabulary unchanged:
// every report this module builds answers in the same tokens it always
// answered in, with the refusal's reason now on the report itself.

export {
  INDEX_EVIDENCE_STATES,
  INDEX_REFRESHES,
  isIndexEvidenceState,
  isIndexRefresh,
  type IndexEvidenceState,
  type IndexRefresh,
  type PostWriteRefreshClaim,
} from "./index-refresh.ts";
export { INDEX_EVIDENCE, INDEX_REFRESH, readIndexEvidence, type IndexEvidence };

import {
  claimPostWriteRefresh,
  INDEX_EVIDENCE,
  INDEX_REFRESH,
  readIndexEvidence,
  type IndexEvidence,
  type IndexRefresh,
} from "./index-refresh.ts";

/**
 * What a lifecycle call did to the vault's inbound references, and on
 * what evidence.
 *
 * `filesScanned` is the honest denominator: it is the number of Markdown
 * files this call actually opened, so `filesRewritten` is a fraction of a
 * population the caller can see rather than a bare count implying a
 * complete graph.
 */
export interface NoteReferenceReport {
  /** Markdown files read during this call. */
  readonly filesScanned: number;
  /**
   * Files holding at least one reference to the subject, vault-relative,
   * sorted.
   *
   * For a RELOCATION this includes the note itself when the note carries
   * a reference to its own old path, because the rewrite pass rewrites
   * that file too and {@link NoteLifecycleInput.expect} guards the number
   * of files this call will write. Excluding it made `expect: 0` pass and
   * then report `filesRewritten: 1`.
   *
   * For a DELETE the note itself is excluded, because a reference living
   * inside the file being removed strands nothing.
   */
  readonly inboundFiles: ReadonlyArray<string>;
  /** Files whose bytes this call rewrote. Zero for a dry run and for a delete. */
  readonly filesRewritten: number;
  /**
   * Files whose spellings this call meant to rewrite and could not, with
   * the filesystem's reason. Non-empty means the operation is
   * HALF-APPLIED: the note is at its new path and these files still name
   * the old one. See {@link noteLifecycle} for why that is reported
   * rather than rolled back.
   */
  readonly rewriteFailures: ReadonlyArray<{ readonly path: string; readonly reason: string }>;
  /** Old spellings rewritten to new ones, in the order they were applied. */
  readonly rewrittenSpellings: ReadonlyArray<{ readonly from: string; readonly to: string }>;
  /** What happened to the bare `[[Basename]]` spelling. */
  readonly basename: BasenameRewrite;
  /** How fresh the derived index is with respect to this call. */
  readonly index: IndexEvidence;
  /**
   * Whether this write started the detached index refresh. `claimed`
   * says a run is IN FLIGHT, never that it has landed - the index
   * evidence beside it still describes the index as this call left it.
   */
  readonly refresh: IndexRefresh;
  /**
   * Why `refresh` is `not_claimed`: the freshen machinery's own skip
   * token, or the message of an error it raised. `null` when a run was
   * started, and when no claim was attempted (a plan-only run refused
   * nothing). Rendered on every report, so `not_claimed` never has to be
   * guessed at - a deliberate config-off reads differently from a
   * `writer_lock`, a held claim or a broken spawn, and in a multi-vault
   * server the reason is THIS call's own decision, never another vault's.
   */
  readonly refreshReason: string | null;
}

/**
 * The subtree {@link NoteLifecycleInput.deleteLinked}'s fold walks.
 *
 * Re-exported from the module that owns the fold rather than spelled
 * again here: the response promises a caller which scope was scanned, and
 * a second copy of that string is a promise that can go stale.
 */
export const DERIVED_SET_SCOPE = DERIVATION_SCAN_SCOPE;

/**
 * What a `--delete-linked` run found, split into the two lists that
 * matter: what it will remove, and what it will leave standing.
 *
 * Both are returned on the dry run and on the confirmed run, and they are
 * disjoint. A caller reading only one of them still gets a complete
 * answer to the question it asked; a caller reading both never has to
 * compute the difference itself, which is where a report and a deletion
 * come to disagree.
 */
export interface NoteDeleteCascade {
  /**
   * Exactly what a confirmed run removes: the note first, then the
   * solely-derived files, sorted. This is also the list the count guard
   * asserts over, so `--expect` counts the same things the response
   * printed.
   */
  readonly deletionSet: ReadonlyArray<string>;
  /**
   * Everything else that references the note: inbound wikilinks from
   * anywhere in the vault, plus the Brain pages the fold classified as
   * shared rather than derived. Reported, never deleted, never rewritten.
   */
  readonly reportedFiles: ReadonlyArray<string>;
  /**
   * The subtree the derived-set fold walked, always
   * {@link DERIVED_SET_SCOPE}. On the response because an empty
   * `deletionSet` tail has two readings and only one of them is a
   * measurement.
   */
  readonly scannedScope: string;
}

/** Machine-readable reason a {@link noteLifecycle} call was refused. */
export type NoteLifecycleErrorCode =
  /** The source note does not exist. */
  | "source_missing"
  /** A destination is required for this action, or forbidden for it. */
  | "destination_required"
  | "destination_forbidden"
  /** The destination is already occupied. */
  | "destination_occupied"
  /** Source and destination are the same path. */
  | "destination_unchanged"
  /** A move whose destination directory sits inside the source subtree. */
  | "destination_inside_source"
  /** The move set is empty while the source folder is not. */
  | "move_set_empty"
  /** A `rename` that changes the directory, or a `move` that does not. */
  | "wrong_action"
  /** A delete reached the mutating path without an explicit confirmation. */
  | "not_confirmed"
  /** The subject already sits under the archive root. */
  | "already_archived"
  /** `deleteLinked` was passed to an action that removes nothing. */
  | "cascade_forbidden";

export class NoteLifecycleError extends Error {
  readonly code: NoteLifecycleErrorCode;
  constructor(code: NoteLifecycleErrorCode, message: string) {
    super(message);
    this.name = "NoteLifecycleError";
    this.code = code;
  }
}

export interface NoteLifecycleInput {
  readonly action: NoteLifecycleAction;
  /** Vault-relative path of the subject note; must end in `.md`. */
  readonly path: string;
  /** Vault-relative destination. Required for rename/move, forbidden otherwise. */
  readonly to?: string;
  /** False (the default) walks, counts and writes nothing. */
  readonly apply?: boolean;
  /** Required by `delete` before it will remove anything. */
  readonly confirm?: boolean;
  /**
   * `--delete-linked`: extend a `delete` to the single-purpose derived
   * files that trace SOLELY to this note. Refused on every other action.
   * Absent (the default) leaves the delete byte-identical to before.
   */
  readonly deleteLinked?: boolean;
  /** `--expect N`: assert the inbound-reference count before any write. */
  readonly expect?: number | null;
  /** `--strict`: refuse a mutation carrying no `--expect` guard. */
  readonly strict?: boolean;
  /** Injected clock, forwarded to the recovery point so a run stays reproducible. */
  readonly now?: Date;
  /**
   * May the caller read the subject note at this vault-relative path? One
   * it may not read is refused as `source_missing`, the refusal a path
   * with no note gets, before the note is stat-ed. The same test decides
   * which files the reference report names and counts (`inboundFiles`,
   * `filesScanned`, `filesRewritten`, `rewriteFailures`, the cascade
   * lists and the recoverability derived from the rewrite): a file it
   * rejects is reported as a vault without it would be, and a cascade
   * never deletes it. The link rewrite of an applied relocation still
   * edits it, so the readers who can see it are not left with links to a
   * path that no longer exists - and the same holds for a bare-name
   * repair derived from a page it rejects: the repair runs, but names no
   * pair in `rewrittenSpellings`. Absent, every file counts (the CLI,
   * which reads the vault directly).
   */
  readonly readable?: (rel: string) => boolean;
  /**
   * Test seam: replaces the detached spawn of the post-write index
   * refresh, the same seam shape the freshen-on-read callers inject.
   * Absent, the spawn is the real detached one, and a short-lived CLI
   * process is not its parent for long - which is why the child is
   * detached in the first place.
   */
  readonly refreshSpawn?: (argv: string[]) => void;
  /**
   * The config file the post-write refresh resolves the search config
   * through - the caller's `--config` (or the MCP server's config path),
   * so the claim reads the same index and spawns the child with the same
   * freshen settings the rest of the invocation used. Absent, the config
   * resolves from the environment alone.
   */
  readonly refreshConfigPath?: string;
}

export interface NoteLifecycleResult {
  readonly action: NoteLifecycleAction;
  /** Vault-relative path the note was at. */
  readonly from: string;
  /** Vault-relative path it is at now; `null` for a delete. */
  readonly to: string | null;
  /** False when this was a plan-only run. */
  readonly applied: boolean;
  /** What the recovery point (if any) is worth for THIS operation. */
  readonly recoverability: RecoverabilityVerdict;
  /** The recovery point taken, when one was; `null` otherwise. */
  readonly snapshot: { readonly runId: string; readonly path: string } | null;
  /** What happened to inbound references, and on what evidence. */
  readonly references: NoteReferenceReport;
  /**
   * What `--delete-linked` computed, or `null` when the flag was absent.
   *
   * `null` and an empty {@link NoteDeleteCascade.deletionSet} are
   * different answers: the first says no cascade was asked for, the
   * second says one was and it found nothing beyond the note.
   */
  readonly cascade: NoteDeleteCascade | null;
}

/**
 * Top-level directory an archived note is displaced into, its original
 * path mirrored beneath. See the module header for why here and not
 * under `Brain/`.
 */
export const NOTE_ARCHIVE_ROOT = "Archive";

/**
 * The vault-relative root the reference scan walks: the whole vault.
 *
 * "The whole vault" is narrower than it sounds, and the narrowings are
 * `retargetWikilinks`'s: nothing whose realpath leaves the vault, nothing
 * `vault.ignore_paths` / `include_paths` excludes, and nothing inside a
 * fenced block or a code span. What is left is every place a `[[...]]`
 * naming this note can live - user notes on one side of the `Brain/`
 * boundary and Brain artifacts on the other - which is the population a
 * rewrite has to see for its count to mean coverage.
 */
const VAULT_ROOT_REL = "";

/**
 * Subtrees the reference scan READS and REPORTS but never rewrites.
 *
 * One entry, and it is `Brain/log`. The observation log is an
 * append-only record of what an agent said at an instant; a live
 * wikilink elsewhere in the vault is a navigation aid that goes stale
 * when a note moves and wants repairing, but a log line is testimony,
 * and repairing testimony changes what it says was said. `Brain/` is the
 * one tree `resolveNoteTarget` refuses to let this surface ADDRESS, and
 * leaving the whole of it inside the range of the surface's collateral
 * writes was the hole; excluding all of `Brain/` instead would be the
 * opposite error, because a Brain artifact that cites a note by path is
 * an ordinary reference and goes dangling exactly like a user note's.
 *
 * The log is still read and still named in `inboundFiles`: withholding
 * the disclosure that the record mentions this note would be a second
 * defect wearing the first one's clothes.
 */
const APPEND_ONLY_REL: ReadonlyArray<string> = Object.freeze([BRAIN_LOG_REL]);

/** The `.md` suffix, matched case-insensitively by the path envelope. */
const MARKDOWN_SUFFIX = ".md";

/** `Projects/Old.md` -> `Old`. */
function basenameOf(relPath: string): string {
  const last = relPath.split(posix.sep).at(-1) ?? relPath;
  return last.toLowerCase().endsWith(MARKDOWN_SUFFIX)
    ? last.slice(0, -MARKDOWN_SUFFIX.length)
    : last;
}

/** `Projects/Old.md` -> `Projects`, and `Old.md` -> `""`. */
function directoryOf(relPath: string): string {
  const cut = relPath.lastIndexOf(posix.sep);
  return cut < 0 ? "" : relPath.slice(0, cut);
}

/** `Projects/Old.md` -> `Projects/Old`. */
function withoutSuffix(relPath: string): string {
  return relPath.toLowerCase().endsWith(MARKDOWN_SUFFIX)
    ? relPath.slice(0, -MARKDOWN_SUFFIX.length)
    : relPath;
}

/**
 * The three spellings an inbound `[[...]]` can use for one note. Ordered
 * longest-first is {@link retargetWikilinks}'s job, not this one's; what
 * matters here is that all three are named, because a rename that fixed
 * only the one spelling it happened to think of would report a rewrite
 * count that read as coverage.
 */
function spellingsOf(relPath: string): ReadonlyArray<string> {
  return [relPath, withoutSuffix(relPath), basenameOf(relPath)];
}

/**
 * Resolve the destination this action implies, running it through the
 * same envelope as the source. Returns `null` for a delete, which has no
 * destination by definition.
 */
function resolveDestination(
  vault: string,
  input: NoteLifecycleInput,
  source: ResolvedNoteTarget,
): ResolvedNoteTarget | null {
  const action = input.action;
  if (action === NOTE_LIFECYCLE_ACTION.delete) {
    if (input.to !== undefined) {
      throw new NoteLifecycleError(
        "destination_forbidden",
        `${action} takes no destination; it removes ${source.relPath}`,
      );
    }
    return null;
  }

  if (action === NOTE_LIFECYCLE_ACTION.archive) {
    if (input.to !== undefined) {
      throw new NoteLifecycleError(
        "destination_forbidden",
        `${action} chooses its own destination under ${NOTE_ARCHIVE_ROOT}/; drop 'to'`,
      );
    }
    if (
      source.relPath === NOTE_ARCHIVE_ROOT ||
      source.relPath.startsWith(`${NOTE_ARCHIVE_ROOT}/`)
    ) {
      throw new NoteLifecycleError(
        "already_archived",
        `${source.relPath} is already under ${NOTE_ARCHIVE_ROOT}/`,
      );
    }
    return resolveNoteTarget(vault, posix.join(NOTE_ARCHIVE_ROOT, source.relPath));
  }

  if (input.to === undefined) {
    throw new NoteLifecycleError(
      "destination_required",
      `${action} requires a destination path ('to')`,
    );
  }
  const destination = resolveNoteTarget(vault, input.to);
  if (destination.relPath === source.relPath) {
    throw new NoteLifecycleError(
      "destination_unchanged",
      `${action} destination is the source path: ${source.relPath}`,
    );
  }
  const sameDirectory = directoryOf(destination.relPath) === directoryOf(source.relPath);
  if (action === NOTE_LIFECYCLE_ACTION.rename && !sameDirectory) {
    throw new NoteLifecycleError(
      "wrong_action",
      `rename keeps the note in ${directoryOf(source.relPath) || "the vault root"}; ` +
        `${destination.relPath} is in another directory - use move`,
    );
  }
  if (action === NOTE_LIFECYCLE_ACTION.move && sameDirectory) {
    throw new NoteLifecycleError(
      "wrong_action",
      `move changes the directory; ${destination.relPath} shares one with ` +
        `${source.relPath} - use rename`,
    );
  }
  return destination;
}

/**
 * Decide what to do about the bare `[[Old]]` spelling, from the
 * population the rewrite would act on.
 *
 * `files` is the list the counting pass just walked, which is exactly the
 * set of notes whose links are candidates for rewriting - deriving the
 * answer from a second walk under a second rule set is how the count and
 * the rewrite would come to disagree.
 *
 * The question is whether `[[Old]]` uniquely resolved to the SOURCE
 * before the move, because that is the link this operation would
 * otherwise strand. The rewrite target is no longer the bare new
 * basename but {@link minimalSpellingFor}'s answer over the post-move
 * population, which is unambiguous by construction - so the DESTINATION
 * side of the old count, which withheld the rewrite whenever any other
 * note carried the destination basename, no longer withholds anything:
 * with `A/Old.md`, `B/Foo.md` and a third page's `[[Old]]`, renaming
 * `A/Old.md` to `A/Foo.md` rewrites the link to `[[A/Foo]]`, which
 * resolves to the same note `[[Old]]` did. What still withholds is a
 * bare spelling that never uniquely named the source: a NESTED source
 * with several same-basename carriers answered, by the ladder's
 * basename rung, to whichever one Obsidian picked - rewriting it would
 * re-point a link that never pointed here - while a TOP-LEVEL source
 * owns its bare spelling outright through the exact-path rung whatever
 * the nested count.
 */
function decideBasename(
  files: ReadonlyArray<string>,
  sourceRel: string,
  destinationRel: string,
): BasenameRewrite {
  const from = basenameOf(sourceRel);
  const to = basenameOf(destinationRel);
  if (from === to) return BASENAME_REWRITE.notNeeded;
  const carriersOfFrom = files.filter((rel) => basenameOf(rel) === from).length;
  const sourceIsTopLevel = directoryOf(sourceRel) === "";
  return carriersOfFrom > 1 && !sourceIsTopLevel
    ? BASENAME_REWRITE.ambiguous
    : BASENAME_REWRITE.applied;
}

/** The errno `link(2)` sets when source and destination are on different devices. */
const CROSS_DEVICE_CODE = "EXDEV";

/** `statSync`, or `null` when the path is not there or cannot be read. */
function statOrNull(target: string): Stats | null {
  try {
    return statSync(target);
  } catch {
    return null;
  }
}

/**
 * True when two paths name the SAME directory entry's inode.
 *
 * This is what a case-only rename looks like on a case-insensitive
 * filesystem: on macOS and Windows `Old.md` and `OLD.md` are one file, so
 * `existsSync(destination)` is true and the occupied-destination guard
 * refused the single most common reason anyone reaches for a rename -
 * fixing a capitalisation typo. Asking about inode identity rather than
 * about the platform means the guard is decided by the filesystem in
 * front of it rather than by a `process.platform` string, and the branch
 * is reachable on Linux too, where a hardlinked destination has exactly
 * this shape.
 *
 * Exported for the folder lifecycle, whose occupancy pre-flight asks the
 * same question of the destination FOLDER and of every destination FILE
 * in a case-only folder rename.
 */
export function namesSameEntry(a: string, b: string): boolean {
  const left = bigintStatOrNull(a);
  const right = bigintStatOrNull(b);
  if (left === null || right === null) return false;
  return left.dev === right.dev && left.ino === right.ino;
}

/**
 * `statSync` with exact `dev` and `ino`. NTFS file IDs are 64-bit, and as a
 * `number` two distinct files can round to the same `ino` above 2^53, which
 * made {@link namesSameEntry} take an occupied destination for the source.
 */
function bigintStatOrNull(target: string): BigIntStats | null {
  try {
    return statSync(target, { bigint: true });
  } catch {
    return null;
  }
}

/**
 * Attach `from`'s inode to the name `to`, refusing an occupied name.
 *
 * `link(2)` rather than a read-then-write, and that is the fix for a note
 * whose bytes are not valid UTF-8. Reading with `"utf8"` and writing the
 * string back replaced every unpaired byte with U+FFFD - `68 69 20 ff fe
 * 0a` landed as `68 69 20 ef bf bd ef bf bd 0a` - and the source was then
 * unlinked, with relocations deliberately not snapshotted, so the
 * original bytes were unrecoverable. A link moves no bytes at all, which
 * makes byte-preservation a property of the operation rather than of the
 * encoding a reader guessed at. It is also exclusive, so the
 * refuse-to-overwrite guarantee stays race-free.
 *
 * The `EXDEV` arm is for a vault with a mount point inside it, where no
 * hard link can span the boundary. `copyFileSync` with `COPYFILE_EXCL`
 * has the same two properties that matter here - byte-exact and
 * refuse-if-present - and differs only in doing real work.
 */
function linkOneName(from: string, to: string, label: string): void {
  try {
    try {
      linkSync(from, to);
      return;
    } catch (err) {
      if ((err as NodeJS.ErrnoException | null)?.code !== CROSS_DEVICE_CODE) throw err;
      copyFileSync(from, to, constants.COPYFILE_EXCL);
    }
  } catch (err) {
    if (isFileAlreadyExists(err)) {
      throw new NoteLifecycleError("destination_occupied", `destination already exists: ${label}`);
    }
    throw err;
  }
}

/**
 * Move one note's BYTES from `source` to `destination`: attach the
 * inode to the destination name, re-confirm it landed, then drop the
 * source name.
 *
 * The pattern is `signal-retire.ts:141-152`'s, and the ordering is the
 * whole of its value - the note exists under two names at the instant the
 * first goes and never under zero. It relinks rather than re-rendering,
 * so a note's own formatting, its comments, any frontmatter key this
 * project's parser does not model, and its exact bytes whatever their
 * encoding survive the move; the preference retire re-renders and loses
 * the original prose, which is the arm of that precedent deliberately not
 * taken here.
 *
 * `sameEntry` is the case-only rename, where the destination name IS the
 * source name as far as the filesystem is concerned. It cannot be done in
 * two steps in the usual order, because unlinking the source would remove
 * the destination with it; so the inode gets a third, private name first,
 * the source name goes, and the rename attaches the staged name to the
 * destination. Under both orders the bytes are reachable under some name
 * at every instant.
 */
function relocateBytes(
  source: ResolvedNoteTarget,
  destination: ResolvedNoteTarget,
  sameEntry: boolean,
): void {
  relocateFileBytes(source.abs, destination.abs, destination.relPath, sameEntry);
}

/**
 * The byte relocation itself, on absolute paths - the exact machinery
 * {@link relocateBytes} runs, shared with the folder lifecycle, which
 * relocates whole sets of files that never went through
 * {@link resolveNoteTarget} (a folder path has no `.md` rung to pass).
 * One implementation, so the byte-preservation and refuse-to-overwrite
 * guarantees cannot come to mean two things on the two surfaces.
 */
export function relocateFileBytes(
  fromAbs: string,
  toAbs: string,
  label: string,
  sameEntry: boolean,
): void {
  mkdirSync(dirname(toAbs), { recursive: true });
  if (sameEntry) {
    const staged = `${toAbs}.${process.pid}.${Date.now()}.relocating`;
    linkOneName(fromAbs, staged, label);
    // Destroys nothing: `staged` is a second name for this very inode,
    // so the bytes outlive the name being dropped here. Declared for the
    // destructive-site census, which reads sites and not files.
    unlinkSync(fromAbs);
    renameWithRetry(staged, toAbs);
  } else {
    linkOneName(fromAbs, toAbs, label);
    if (!existsSync(toAbs)) {
      throw new Error(`noteLifecycle: write of ${label} reported success but the file is absent`);
    }
    // Destroys nothing: the assertion above has just confirmed the same
    // bytes are reachable at the destination, so this drops a name and
    // not a file. Declared for the destructive-site census.
    unlinkSync(fromAbs);
  }
  if (!existsSync(toAbs)) {
    throw new Error(
      `noteLifecycle: relocation of ${label} reported success but the file is absent`,
    );
  }
}

/**
 * Run one note-file lifecycle operation.
 *
 * Ordering is load-bearing throughout. The envelope judges both paths
 * before anything is read; the counting pass establishes the blast radius
 * before the count guard runs; the count guard runs before any byte
 * moves; and the index evidence is read at the END, so the instant it
 * reports is the one a caller comparing it against the relocation will
 * actually reason about, with the refresh claim trailing it - the claim
 * starts a detached run, and the evidence must stay the description of
 * the index as this call left it.
 */
export async function noteLifecycle(
  vault: string,
  input: NoteLifecycleInput,
): Promise<NoteLifecycleResult> {
  const apply = input.apply === true;
  // Vault-identity write guard (context-integrity-gates, Unit J). Asserted
  // on the planning path too: a plan names real vault paths, and computing
  // one against a vault this process was not pointed at is already the
  // confusion the guard exists to refuse.
  // Through the vault adapter (design D14 items 8, 13): a vault is
  // required, and the vault identity guard holds.
  assertNoteVaultForWrite(vault, "the note lifecycle");

  const action = input.action;
  if (
    action === NOTE_LIFECYCLE_ACTION.moveFolder ||
    action === NOTE_LIFECYCLE_ACTION.renameFolder
  ) {
    // Refused rather than dispatched, the mirror of the folder surface's
    // refusal of the file actions: the vocabulary is ONE constant (the
    // CLI guard, the MCP enum and the manifest read it together), but the
    // machinery is two modules, and a folder action that fell through to
    // the file envelope would report a one-file result for a many-file
    // operation. The caller that owns the dispatch - the verb surface,
    // the MCP tool - sends folder actions to `./folder-lifecycle.ts`.
    throw new NoteLifecycleError(
      "wrong_action",
      `the note-file lifecycle runs rename | move | archive | delete; ` +
        `'${action}' is a folder action and runs in the folder lifecycle`,
    );
  }
  const source = resolveNoteTarget(vault, input.path);
  // `isFile`, not merely `exists`: a DIRECTORY named `Notes.md` is a
  // perfectly legal thing for a vault to contain, and checking existence
  // alone let it through to `readFileSync`, which raised a bare `EISDIR`
  // that left MCP as an internal fault. There is no note at that path,
  // which is what `source_missing` says.
  const sourceStat = input.readable?.(source.relPath) === false ? null : statOrNull(source.abs);
  if (sourceStat === null || !sourceStat.isFile()) {
    throw new NoteLifecycleError("source_missing", `no note file at ${source.relPath}`);
  }
  const destination = resolveDestination(vault, input, source);
  // A destination that names the SAME entry as the source is not
  // occupied by anything - see {@link namesSameEntry}. That is the
  // case-only rename on a case-insensitive filesystem, and refusing it
  // here made a capitalisation fix impossible on macOS and Windows.
  const sameEntry = destination !== null && namesSameEntry(source.abs, destination.abs);
  if (destination !== null && !sameEntry && existsSync(destination.abs)) {
    throw new NoteLifecycleError(
      "destination_occupied",
      `destination already exists: ${destination.relPath}`,
    );
  }
  const deleteLinked = input.deleteLinked === true;
  if (deleteLinked && action !== NOTE_LIFECYCLE_ACTION.delete) {
    // Refused rather than ignored. A relocation has no deletion set to
    // extend, so honouring the flag silently would tell a caller that
    // asked for a cascade that it got one.
    throw new NoteLifecycleError(
      "cascade_forbidden",
      `delete-linked extends a delete's blast radius; ${action} removes nothing`,
    );
  }
  if (action === NOTE_LIFECYCLE_ACTION.delete && input.confirm !== true && apply) {
    throw new NoteLifecycleError(
      "not_confirmed",
      `delete removes ${source.relPath} and no archive covers a note outside Brain/; ` +
        "pass an explicit confirmation to proceed",
    );
  }

  // Pass one: walk, count, write nothing. This is both the blast radius
  // the count guard asserts against and the population the basename
  // decision is made from.
  const probe = retargetWikilinks(
    vault,
    spellingsOf(source.relPath).map((from) => ({ from })),
    { root: VAULT_ROOT_REL, apply: false },
  );
  const reported = (rel: string): boolean => input.readable?.(rel) ?? true;
  const basename =
    destination === null
      ? BASENAME_REWRITE.notNeeded
      : decideBasename(probe.files, source.relPath, destination.relPath);
  const mainRetargets =
    destination === null ? [] : mainRetargetsFor(probe.files, source, destination, basename);
  const repairs =
    destination === null ? [] : bareNameRepairs(probe.files, source.relPath, destination.relPath);
  // The repair pass writes files the moved note's own spellings can
  // never match: a file mentioning ONLY the contested bare basename
  // matches none of them, yet the repair rewrites it. Its spellings
  // therefore run through a match-only probe of their own, and the
  // files they hit join `inbound_files` and the count guard - the plan
  // names every file the apply will write, and `--expect` counts the
  // same set. A delete has no destination and so no repairs; the union
  // below is its plain probe then.
  const repairMatched =
    repairs.length > 0
      ? retargetWikilinks(
          vault,
          repairs.map((r) => ({ from: r.from })),
          { root: VAULT_ROOT_REL, apply: false },
        ).matched
      : [];
  const matched = [...new Set([...probe.matched, ...repairMatched])].toSorted();
  // A delete drops its own file, so a reference living inside it strands
  // nothing and is not counted. A relocation REWRITES its own file when
  // the note names its own old path, so that file is one of the writes
  // `--expect` guards and has to be in the number.
  // A file the caller may not read is absent from every list and count
  // below; see `NoteLifecycleInput.readable`.
  const inboundFiles = (
    action === NOTE_LIFECYCLE_ACTION.delete
      ? matched.filter((rel) => rel !== source.relPath)
      : matched
  ).filter(reported);
  const filesScanned = probe.files.filter(reported).length;

  const cascade = deleteLinked ? planCascade(vault, source.relPath, inboundFiles, reported) : null;

  // The guard asserts what the operation will REMOVE. Without a cascade
  // that is one file and the number worth guarding is the collateral -
  // how many inbound references the delete will strand - which is what
  // `--expect` has meant here since it shipped. With a cascade the set
  // itself is variable, so the guard moves onto it: `--expect` counts the
  // paths the response just listed as the deletion set, and a stale plan
  // aborts before the first unlink instead of removing a file the
  // operator never saw.
  const guarded = cascade === null ? inboundFiles : cascade.deletionSet;
  assertExpectedCount({
    matched: guarded.length,
    expect: input.expect ?? null,
    strict: input.strict === true,
    willMutate: apply,
    matchList: guarded,
  });

  let snapshot: NoteLifecycleResult["snapshot"] = null;
  let rewritten: ReadonlyArray<string> = [];
  let rewriteFailures: ReadonlyArray<{ readonly path: string; readonly reason: string }> = [];

  if (apply) {
    if (action === NOTE_LIFECYCLE_ACTION.delete) {
      // The gate takes the recovery point BEFORE the unlink and returns
      // the verdict that says what it is worth. The archive holds the
      // Brain tree - the log, the backlink sources, the continuity
      // records that name this note - and never the note itself, because
      // `resolveNoteTarget` refuses `Brain/` for every note path. That is
      // `partial` coverage stated as `unproven`, and stating it is the
      // point: the previous shape of this problem returned a snapshot
      // path with nothing beside it, which every caller reads as "this is
      // reversible".
      //
      // ONE gate over the WHOLE set, not one per file: the set is a
      // single decision the operator authorised and a per-file recovery
      // point would leave them choosing which of five archives to roll
      // back to. The derived half lives under `Brain/` and IS in the
      // archive, so a cascade's verdict is `partial` where a bare
      // delete's is `unproven` - the note is still uncovered, and the
      // blockers say so.
      const derivedFiles = cascade === null ? [] : cascade.deletionSet.slice(1);
      const gated = withDestructiveSnapshot(
        vault,
        BRAIN_SNAPSHOT_REASON.noteDelete,
        () => {
          // The note goes FIRST, and the order is the choice between two
          // half-states. A derived file whose note is already gone is a
          // dangling derivation - the exact state every delete before
          // this flag left behind, and one the operator can re-run into.
          // The reverse - derivations removed while the note they restate
          // survives - destroys the only copies of material nothing will
          // regenerate.
          unlinkSync(source.abs);
          for (const rel of derivedFiles) {
            unlinkSync(ensureInsideVault(join(vault, rel), vault));
          }
        },
        {
          blastRadius: {
            outsideBrainRoot: true,
            ...(derivedFiles.length > 0 ? { brainTopLevel: true } : {}),
          },
          ...(input.now !== undefined ? { now: input.now } : {}),
        },
      );
      snapshot = Object.freeze({ runId: gated.snapshot.runId, path: gated.snapshot.path });
      const index = await readIndexEvidence(vault, true, input.refreshConfigPath);
      const claim = await claimPostWriteRefresh(
        vault,
        index,
        input.refreshSpawn,
        input.now,
        input.refreshConfigPath,
      );
      return finish(
        action,
        source.relPath,
        null,
        true,
        gated.recoverability,
        snapshot,
        filesScanned,
        inboundFiles,
        0,
        [],
        [],
        basename,
        index,
        claim.refresh,
        claim.refreshReason,
        cascade,
      );
    }
    relocateBytes(source, destination!, sameEntry);
    // The rewrite pass reports its write failures instead of throwing,
    // and this arm keeps going rather than rolling the move back. The
    // choice is deliberate and it is between two half-states, not
    // between a half-state and a clean one: by the time one file cannot
    // be written, others have already been rewritten to name the new
    // path, and putting the note back at its old path would strand THOSE
    // - while un-rewriting them is exactly the write the filesystem just
    // refused. So the operation stands and the report names the split
    // point: `to` is where the note is, `filesRewritten` is what agrees
    // with it, and `rewriteFailures` is what still names the old path.
    // What is not on the table is the previous behaviour, where the raw
    // error propagated and the caller got no result at all - no `from`,
    // no `to`, no evidence - leaving a half-applied rename
    // indistinguishable from one that never started.
    //
    // TWO passes, in this order. The repairs go FIRST, over each file's
    // original link texts: a repair's `from` is the destination's own
    // bare basename, which is exactly what the destination-collapsing
    // pass rewrites links TO, so chaining the two rule sets through one
    // ordered reduce let the repair rule consume the spellings the main
    // pass had just written - repointing the renamed note's own inbound
    // links at the third-party note the repair belonged to. With the
    // repairs ahead of the main pass, each original link is rewritten by
    // the one rule that names it and no rule ever sees another rule's
    // output. Both passes obey the same never-rewrite scope.
    const repairPass =
      repairs.length > 0
        ? retargetWikilinks(vault, repairs, {
            root: VAULT_ROOT_REL,
            apply: true,
            neverRewrite: APPEND_ONLY_REL,
          })
        : null;
    const mainPass = retargetWikilinks(vault, mainRetargets, {
      root: VAULT_ROOT_REL,
      apply: true,
      neverRewrite: APPEND_ONLY_REL,
    });
    rewritten = [...new Set([...(repairPass?.rewritten ?? []), ...mainPass.rewritten])]
      .toSorted()
      .filter(reported);
    const failureByPath = new Map<string, string>();
    for (const failure of [...(repairPass?.failed ?? []), ...mainPass.failed]) {
      if (!failureByPath.has(failure.path)) failureByPath.set(failure.path, failure.reason);
    }
    rewriteFailures = [...failureByPath]
      .filter(([rel]) => reported(rel))
      .map(([path, reason]) => ({ path, reason }))
      .toSorted((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
  }

  // The MOVE destroys nothing - the bytes are reachable under the
  // destination name before the source name goes, and the assertion
  // between the two makes that a fact rather than an intention. The link
  // REWRITE is a different matter, and reporting the pair as
  // `nothing_at_risk` was the defect: it overwrites hand-authored files
  // in place, outside `Brain/` as often as inside it, and nothing
  // regenerates a user's prose. So the blast radius is declared from the
  // files this call actually rewrote, in the regions the archive is
  // defined over.
  //
  // A plan-only run rewrote nothing and therefore genuinely risks
  // nothing; the warning a caller needs before applying is `inboundFiles`,
  // which names every file the apply would write. Declaring a radius for
  // writes that did not happen would be the same class of false statement
  // as reporting a stale index after a dry run.
  const recoverability = classifyRecoverability({
    recoveryPoint: false,
    blastRadius: {
      ...(rewritten.some((rel) => pathCovers(BRAIN_ROOT_REL, rel)) ? { brainTopLevel: true } : {}),
      ...(rewritten.some((rel) => !pathCovers(BRAIN_ROOT_REL, rel))
        ? { outsideBrainRoot: true }
        : {}),
    },
  });

  const index = await readIndexEvidence(vault, apply, input.refreshConfigPath);
  // The refresh claim trails the evidence read on purpose: the evidence
  // must describe the index as this call left it, and the claim starts a
  // DETACHED run that will not have landed by any instant this call can
  // observe. A plan-only run aged nothing and claims nothing - and
  // refused nothing, so its reason is null rather than a borrowed token.
  const claim = apply
    ? await claimPostWriteRefresh(
        vault,
        index,
        input.refreshSpawn,
        input.now,
        input.refreshConfigPath,
      )
    : { refresh: INDEX_REFRESH.notClaimed, refreshReason: null };

  return finish(
    action,
    source.relPath,
    destination === null ? null : destination.relPath,
    apply,
    recoverability,
    snapshot,
    filesScanned,
    inboundFiles,
    rewritten.length,
    // A bare-name repair derived from a page the caller may not read is
    // applied (the readers who can see that page keep a working link)
    // but names no pair, exactly like the rewrites inside withheld
    // pages: the report answers as a vault without the page would. The
    // main pairs are derived solely from the paths this call was given,
    // so no pair of theirs can name a page the caller chose not to see.
    // The repairs are listed first because they are applied first.
    [...repairs, ...mainRetargets].flatMap((r) =>
      r.to === undefined || (r.carrierRel !== undefined && !reported(r.carrierRel))
        ? []
        : [{ from: r.from, to: r.to }],
    ),
    rewriteFailures,
    basename,
    index,
    claim.refresh,
    claim.refreshReason,
    cascade,
  );
}

/**
 * Split everything that references the note into the two lists
 * {@link NoteDeleteCascade} promises.
 *
 * The classification is `source-cleanup.ts`'s: {@link traceNoteDerivations}
 * runs it - a single-purpose derived page in a derivation directory,
 * citing no second source, folded from no foreign signal - and this
 * function sorts the verdict into the two lists and unions the mentions
 * with the vault-wide inbound probe.
 *
 * One condition is added on top of it, and only on this path. That rule
 * was written for an IMPORTED source, where "cites no second source" is
 * decisive because the pages in range are ones the import generated. A
 * note is different: any Brain page may write `[[Note]]` in prose, and
 * such a page carries no `source:` array to contradict - so the
 * solely-derived test passes vacuously and somebody's paragraph enters a
 * deletion set. The cascade therefore requires explicit structured
 * provenance (`structuredProvenance`) as well: a page is deletable only
 * when its frontmatter NAMES the note as what it was derived from. A
 * prose mention is always reported and never deleted. `deleteBySource`
 * is untouched - its subject brings index artifacts of its own and its
 * rule is long-settled.
 *
 * Two populations meet here and the union is the point. The probe reads
 * `[[...]]` spellings anywhere in the vault, which is where user notes
 * live; the fold reads Brain frontmatter provenance, which the probe
 * cannot see because `source_path: Imports/Note.md` is not a wikilink.
 * Reporting only one of them would silently drop the other's findings.
 */
function planCascade(
  vault: string,
  sourceRel: string,
  inboundFiles: ReadonlyArray<string>,
  readable: (rel: string) => boolean,
): NoteDeleteCascade {
  // A page the caller may not read is neither deleted nor reported, as in
  // a vault without it.
  const traced = traceNoteDerivations(vault, sourceRel).filter((entry) => readable(entry.path));
  const derived = traced
    .filter((entry) => entry.deletable && entry.structuredProvenance)
    .map((entry) => entry.path)
    // The note itself is never a Brain page, but a fold that ever
    // returned it would otherwise put it in the set twice.
    .filter((rel) => rel !== sourceRel)
    .toSorted();
  const deletionSet = Object.freeze([sourceRel, ...derived]);
  const deleting = new Set(deletionSet);
  const reported = new Set<string>();
  for (const rel of inboundFiles) if (!deleting.has(rel)) reported.add(rel);
  for (const entry of traced) if (!deleting.has(entry.path)) reported.add(entry.path);
  return Object.freeze({
    deletionSet,
    reportedFiles: Object.freeze([...reported].toSorted()),
    scannedScope: DERIVED_SET_SCOPE,
  });
}

/**
 * The walked population as the relocation leaves it: the source path
 * gone, the destination present. Every judgement about the POST state -
 * the minimal destination spelling, the basename carrier counts - is
 * derived from this list rather than from a second walk, so the decision
 * and the rewrite pass can never see two different vaults.
 */
function postRelocationPopulation(
  files: ReadonlyArray<string>,
  sourceRel: string,
  destinationRel: string,
): ReadonlyArray<string> {
  return [...files.filter((rel) => rel !== sourceRel), destinationRel].toSorted();
}

/**
 * One retarget pair plus, for a bare-name repair, the third-party page
 * the pair was derived from. The carrier travels with the pair so the
 * report can ask the caller's reach predicate about the page a withheld
 * carrier would otherwise name - the pair itself spells only a basename
 * and a minimal spelling, and the spelling derived from a page the
 * caller may not read must contribute no reported pair.
 */
type AnnotatedRetarget = WikilinkRetarget & { readonly carrierRel?: string };

/**
 * The bare-name spellings this rename PROVABLY breaks for links that
 * never mentioned it, and the spelling each should carry instead.
 *
 * The casualty is the bare spelling whose carrier count the move turns
 * from exactly one into several: before it, the ladder's
 * unique-carrier rung resolved that spelling to one note; after it,
 * there are two carriers and the spelling resolves to NEITHER - the
 * rename silently broke a third-party link. Those links are repaired to
 * the minimal unambiguous spelling of their PRE-rename target, the
 * chooser applied to the note that never moved. Everything else stays
 * untouched, because nothing is provable about it: a spelling carried
 * by several notes before the move was already ambiguous, a spelling
 * with no carrier was already dangling (adopting it would be a guess),
 * and a single TOP-LEVEL carrier keeps owning its spelling through the
 * exact-path rung whatever the nested count becomes - which is why the
 * repair target is computed through the same chooser and ladder as the
 * main rewrite, and why a repair that comes out identical to the
 * spelling it would "repair" is dropped as a no-op. The pre-state is
 * the counting probe's walked population; the post-state is derived,
 * the move relocating exactly one carrier.
 */
function bareNameRepairs(
  files: ReadonlyArray<string>,
  sourceRel: string,
  destinationRel: string,
): ReadonlyArray<AnnotatedRetarget> {
  const from = basenameOf(sourceRel);
  const to = basenameOf(destinationRel);
  const post = postRelocationPopulation(files, sourceRel, destinationRel);
  const repairs: AnnotatedRetarget[] = [];
  for (const spelling of new Set([from, to])) {
    const preCarriers = files.filter((rel) => basenameOf(rel) === spelling);
    const delta = (spelling === to ? 1 : 0) - (spelling === from ? 1 : 0);
    if (preCarriers.length !== 1 || preCarriers.length + delta < 2) continue;
    const repairedTo = minimalSpellingFor(preCarriers[0]!, post);
    if (repairedTo !== spelling) {
      repairs.push({ from: spelling, to: repairedTo, carrierRel: preCarriers[0]! });
    }
  }
  return repairs;
}

/**
 * The destination-collapsing spellings of this relocation, aimed at the
 * MINIMAL spelling the destination resolves under once the move has
 * landed ({@link minimalSpellingFor} over the post-move population):
 * every old spelling of the source collapses onto the one shortest form
 * that stays unambiguous, so `[[Projects/Old]]` comes out `[[New]]`
 * when `New` is unique and `[[Projects/New]]` only when it is not. A
 * link comes out no longer than the vault still needs, and never
 * longer than it went in. The bare basename of the SOURCE is included
 * only when {@link decideBasename} cleared it, so the
 * `rewrittenSpellings` a caller reads back is the list that was applied
 * and not the list that was considered.
 *
 * The repairs {@link bareNameRepairs} derives are NOT in this list, and
 * that is the point: a repair's `from` is the destination's own bare
 * basename - exactly what these pairs rewrite links TO - so one ordered
 * reduce over both would let the repair rule consume the spellings the
 * main pass had just written, repointing the renamed note's own inbound
 * links at the repaired third-party note. The repairs run as a pass of
 * their own, FIRST, over each file's original link texts, so one rule's
 * output is never another rule's input. The separate pass obeys the
 * same never-rewrite scope as this one.
 */
function mainRetargetsFor(
  files: ReadonlyArray<string>,
  source: ResolvedNoteTarget,
  destination: ResolvedNoteTarget,
  basename: BasenameRewrite,
): ReadonlyArray<AnnotatedRetarget> {
  const to = minimalSpellingFor(
    destination.relPath,
    postRelocationPopulation(files, source.relPath, destination.relPath),
  );
  const pairs: AnnotatedRetarget[] = [
    { from: source.relPath, to },
    { from: withoutSuffix(source.relPath), to },
  ];
  if (basename === BASENAME_REWRITE.applied) {
    pairs.push({ from: basenameOf(source.relPath), to });
  }
  return Object.freeze(pairs);
}

/** Compose the frozen result. One place, so no arm can omit a field. */
function finish(
  action: NoteLifecycleAction,
  from: string,
  to: string | null,
  applied: boolean,
  recoverability: RecoverabilityVerdict,
  snapshot: NoteLifecycleResult["snapshot"],
  filesScanned: number,
  inboundFiles: ReadonlyArray<string>,
  filesRewritten: number,
  rewrittenSpellings: ReadonlyArray<{ readonly from: string; readonly to: string }>,
  rewriteFailures: ReadonlyArray<{ readonly path: string; readonly reason: string }>,
  basename: BasenameRewrite,
  index: IndexEvidence,
  refresh: IndexRefresh,
  refreshReason: string | null,
  cascade: NoteDeleteCascade | null,
): NoteLifecycleResult {
  return Object.freeze({
    action,
    from,
    to,
    applied,
    recoverability,
    snapshot,
    cascade,
    references: Object.freeze({
      filesScanned,
      inboundFiles: Object.freeze([...inboundFiles]),
      filesRewritten,
      rewrittenSpellings: Object.freeze([...rewrittenSpellings]),
      rewriteFailures: Object.freeze([...rewriteFailures]),
      basename,
      index,
      refresh,
      // Rendered on every report, null included: a caller reading the
      // field is reading an answer (nothing was refused, or nothing was
      // attempted) rather than inferring one from an absent key.
      refreshReason,
    }),
  });
}