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
34.8 KB
Raw Blame
/**
 * Why a doctor finding has no next command (no-dead-ends, phase 3).
 *
 * `o2b brain doctor` resolves each reported code through the diagnostics
 * registry and prints `next: <command>` when one is registered. About two
 * thirds of its codes are not, and nothing said why - so an operator
 * reading a finding with no exit could not tell "no command resolves
 * this" from "someone forgot to register it". Silence carried both
 * meanings, which makes it worth nothing.
 *
 * This table removes the second meaning. Every code the doctor spells is
 * either in `DIAGNOSTIC_SIGNALS` with a structural command, or here with
 * the reason there is none. `tests/core/brain/doctor-exit-census.test.ts`
 * enumerates the population out of `doctor.ts` and fails on a code in
 * neither table, or in both.
 *
 * ## What earns an entry here rather than a registration
 *
 * Two shapes, and only these two:
 *
 *   - the repair is a JUDGEMENT over content - which of two contradicting
 *     rules survives, which of two files keeps a duplicated id, whether a
 *     pin is still intended. A command that picked one would be making
 *     the operator's decision and recording it as a repair.
 *   - the repair is an EDIT to a file whose target shape is not derivable
 *     from the finding - a malformed timestamp does not say what instant
 *     it meant, a failed regular expression does not say what it was
 *     meant to match. Writing a plausible value would turn an unreadable
 *     record into a confidently wrong one.
 *
 * A code with a real single command belongs in the registry instead, and
 * the census enforces that direction too: a reason here may not name an
 * `o2b` invocation. If one fits, it is a registration, not an excuse.
 *
 * ## Related, and deliberately separate
 *
 * `applier-capability.ts` answers a different question - whether a
 * MECHANICAL repair exists - and the answers do not coincide. A finding
 * can have no automatic fixer and still have an exact next command
 * (`contradictory-preferences` has both a refusal there and a command in
 * the registry), so folding the two tables together would force one
 * verdict onto two independent axes.
 */

import { resolveNextStep } from "./next-step.ts";

/** One doctor code with no single command, and the reason it has none. */
export interface DoctorExitExclusion {
  readonly code: string;
  /** Why no one command resolves the finding. Never empty. */
  readonly reason: string;
}

const EXCLUSIONS: ReadonlyArray<DoctorExitExclusion> = [
  // --- The brain store (task 1.11, a phase 1 trial) ------------------------
  {
    code: "store-dual-write-failures",
    reason:
      "a failed dual write names a cause outside the store itself (a full disk, a partition this " +
      "machine does not hold, a refused root), and the legacy write it shadowed was kept; the " +
      "fix is to remove that cause, which differs per failure and is named in the finding",
  },
  {
    code: "store-write-fail-open",
    reason:
      "a fail-open store write (a hook, telemetry) names a cause outside the store itself (no " +
      "store yet, no device id, a partition this machine does not hold), and its caller went on; " +
      "the fix is to remove that cause, which differs per failure and is named in the finding",
  },
  {
    code: "store-dual-write-skipped",
    reason:
      "the store needs a device id this machine has not been given; choosing one is a decision " +
      "about how this machine is named among the user's devices, which no command can make for them",
  },
  {
    code: "store-root-invalid",
    reason:
      "the configured store root cannot be used (inside the vault, or holding partitions of two " +
      "stores); where the store should live, and which store is the real one, is the user's choice",
  },
  {
    code: "store-partition-lost",
    reason:
      "a partition this machine has held lost its identity file while its records may still be " +
      "there; the store id it must carry comes only from sync or a backup of that file, and " +
      "writing a guessed one could join the records to the wrong store",
  },
  {
    code: "store-digest-divergent",
    reason:
      "two machines folded identical records into different state, which is a defect in the " +
      "release that computed one of them; repairing it by rewriting records would destroy the " +
      "evidence, so the finding asks for both store folders to be kept and the bug reported",
  },
  {
    code: "store-digest-silent",
    reason:
      "a device that stopped publishing digests is either offline, waiting for sync, or gone for " +
      "good; only the user knows which, and only a human device-retire record takes it off the roster",
  },
  {
    code: "store-device-retired-returned",
    reason:
      "a retired device wrote again, which is either a machine brought back on purpose or a " +
      "device id reused by mistake; only the user knows which, and retiring it again would " +
      "hide a machine that is alive",
  },
  {
    code: "store-removed-awaiting-compaction",
    reason:
      "removed content stays in the append-only shards until store compaction exists, a later " +
      "phase; no command shrinks it today, and the finding only says how many lines still wait",
  },
  {
    code: "store-record-id-conflict",
    reason:
      "a record id arrived with two different contents, so a shard was edited or a writer is " +
      "broken; every machine already keeps the same version, and deciding which content was " +
      "meant needs a person reading both",
  },
  {
    code: "store-dual-write-no-store",
    reason:
      "the skipped records never reached the store and no command can recreate them from the " +
      "legacy tree; creating the store stops new skips, and the counter is reset by deleting a " +
      "device-local file once the user has seen it",
  },
  {
    code: "store-clock-ahead",
    reason:
      "the records carry the clock of the device that wrote them; the fix is the clock of that " +
      "machine, which is outside the vault, and records already written are never rewritten",
  },
  {
    code: "store-device-dir-reserved",
    reason:
      "a peer machine's device id is a name Windows reserves for a device, so its shard folder " +
      "cannot exist on this Windows machine; the fix is that peer's device id, which is outside " +
      "this machine",
  },
  {
    code: "store-mode-loose",
    reason:
      "the looser mode was set outside Open Second Brain (a sync client, a restore, a manual " +
      "chmod); the finding names the exact chmod command, and changing permissions on the " +
      "user's files is left to the user",
  },
  {
    code: "store-record-id-cross-partition",
    reason:
      "a record id appears in both partitions, so a peer copied or forged a record; the index " +
      "keeps the first copy, and deciding which copy is genuine needs a person reading both",
  },
  {
    code: "store-shard-tail-held",
    reason:
      "the held bytes are the unfinished last line of another device's shard; only that device's " +
      "next append or a completed sync closes it, and no command on this machine can",
  },
  {
    code: "store-shard-newer-format",
    reason:
      "the shard holds a record of a format this release does not know; upgrading Open Second " +
      "Brain on this machine reads it, and setting the line aside would hide a valid record",
  },
  {
    code: "store-shard-blob-pending",
    reason:
      "a record's body blob has not arrived yet; a sync tool may still deliver it, and setting " +
      "the record aside is allowed only once it is old enough and never for a settings shard, " +
      "which the finding itself says per record",
  },
  {
    code: "store-shard-line-too-long",
    reason:
      "the bad line runs past the longest line a quarantine can name, so it cannot be set aside " +
      "on this machine; only repairing or removing it in the shard of the device that wrote it " +
      "resolves it",
  },
  {
    code: "store-shard-unreadable",
    reason:
      "a shard file this machine holds could not be read (permissions, a disk error, a sync " +
      "client holding a lock); the cause is named in the finding and differs per machine",
  },
  // --- The store migration (task 2.12) -------------------------------------
  {
    code: "machine-state-adopt-conflicts",
    reason:
      "a switch kept a fresh vault's file aside because the live folder held another copy; " +
      "which of the two is still needed only the user can tell, so the remedy is to compare, " +
      "copy over and delete the folder by hand",
  },
  {
    code: "lane-folder-unimportable",
    reason:
      "which name each folder of the user's own legacy tree should take is the user's choice, " +
      "and renaming a folder moves the user's files, so the remedy is a rename by hand",
  },
  {
    code: "lane-id-misfiled",
    reason:
      "the repair runs only on a machine that holds the private partition, which may be " +
      "another machine than the one running doctor, and on a store where none holds it the " +
      "partition must first be added on one; the finding names which of the two applies",
  },
  {
    code: "store-device-state-foreign",
    reason:
      "another machine's clock and locks reached this machine's device-local state because a " +
      "sync tool was pointed at it; the fix is that tool's folder list, which is outside Open " +
      "Second Brain, and which entries to delete afterwards depends on what the sync copied",
  },
  {
    code: "store-partition-unreadable",
    reason:
      "a partition folder this machine holds could not be read (permissions, a disk error, a " +
      "sync client holding a lock); the cause is named in the finding and differs per machine",
  },
  // --- Judgements over content -------------------------------------------
  {
    code: "active-budget-pressure",
    reason:
      "active.md is rendered from the preference set, so it shrinks by retiring, merging or " +
      "unpinning rules rather than by editing the file; which rule to drop is a statement about " +
      "what the operator still believes, and the finding already ranks the candidates",
  },
  {
    code: "batch-concept-inflation",
    reason:
      "the finding is that a batch was confirmed together without a dedup pass, not that any " +
      "particular pair duplicates. Whether two principles say the same thing is a reading of " +
      "their content, and merging the wrong pair destroys a rule nobody decided to drop",
  },
  {
    code: "broken-entity-relation",
    reason:
      "the edge names an entity id the registry does not hold. Repairing it means either " +
      "creating that entity or correcting the edge, and which was intended is only in the " +
      "author's head - the two produce different graphs",
  },
  {
    code: "chunk-holds-active",
    reason:
      "the hold is a consequence of the embedding configuration, not a defect in the page or " +
      "the index: the configured model provably cannot take the chunk inside its declared " +
      "input window, and the two ways to change that - chunking the source more finely, or " +
      "leaving the page unembedded - are per-page editorial decisions, which the finding " +
      "names together so the operator can make them",
  },
  {
    code: "concept-gap",
    reason:
      "the repair is to write a preference that does not exist yet, which is authoring content " +
      "rather than repairing a record; the same reason applier-capability.ts refuses it a fixer",
  },
  {
    code: "duplicate-entity",
    reason:
      "two entity files claim one identity, and lookups already resolve to the first claimant. " +
      "Merging them or archiving one decides which history survives, which needs both files " +
      "read rather than a rule applied",
  },
  {
    code: "duplicate-id",
    reason:
      "two records carry the same id and either could be the one that keeps it. Renaming a file " +
      "breaks every wikilink that resolved to it, so the choice is a judgement about which " +
      "record the rest of the vault means",
  },
  {
    code: "entity-alias-candidate",
    reason:
      "a nomination, never a drop: the finding is that two names MIGHT denote one entity. " +
      "Confirming it means adding an alias to the surviving entity, which is a claim about the " +
      "world the lexical detector is not entitled to make",
  },
  {
    code: "id-filename-mismatch",
    reason:
      "the id and the basename disagree and neither is authoritative. Renaming the file breaks " +
      "inbound wikilinks, rewriting the id breaks outbound ones, and the finding cannot tell " +
      "which of the two was the typo",
  },
  {
    // The dangling `merged_into` pointer (t_ff8bb8a8). The pointer is the
    // record of a merge decision, and the canonical it names is gone; three
    // different acts restore the page to a resolvable state, and they do
    // NOT agree on what the vault ends up saying.
    code: "merge-chain-dangling",
    reason:
      "the canonical the pointer names is gone, and three different acts restore the page: " +
      "re-pointing it at a surviving canonical, removing the pointer to un-merge, or restoring " +
      "the deleted file. Which of the three is right depends on what the original merge was " +
      "meant to keep, and a mechanical pick would overwrite the record of a decision it never " +
      "read",
  },
  {
    code: "pinned-without-recent-evidence",
    reason:
      "the pin is doing exactly what a pin does - holding a rule back from automatic retire. " +
      "Whether that is still intended is the operator's call, and asking the question is the " +
      "entire content of the warning",
  },
  {
    code: "removed-tool-reference",
    reason:
      "the reference sits in prose an operator or another tool wrote, and the replacement " +
      "mapping is already printed in the finding. Rewriting someone else's note is an edit to " +
      "their content, not a repair of a record this store owns",
  },
  {
    // The informal privacy marker (write-honesty, F1). The marker is a
    // claim about audience, and the vocabulary is the author's: `access:`
    // can mean a narrower group than one token states. The restamp is
    // preview-first for exactly that reason.
    code: "privacy-marker-unstamped",
    reason:
      "the informal marker is a claim about audience written in the author's own vocabulary, " +
      "which can mean a narrower group than any single token states, and the additive restamp " +
      "is preview-first by contract: it writes only after an operator has read each would-be " +
      "visibility line, so no one command resolves the class without deciding for pages nobody " +
      "reviewed",
  },
  {
    // The delivery-trust wave's unknown-provenance count (t_1af24938). The fence already
    // does the safe thing at every read; the warning exists so the widening stays
    // observable, and resolving it is a per-page editorial decision.
    code: "delivery-provenance-unknown",
    reason:
      "the fence already does the safe thing at every read; the warning exists so the " +
      "widening is observable, and resolving it means deciding, page by page, which entry " +
      "point authored each record - a judgment the stamps deliberately leave to the " +
      "operator's next write, since both stamp modules forbid a bulk backfill",
  },
  {
    // The planted-structure-rows audit (t_c2ac4fc8). The rows are
    // third-party text already in the vault; un-planting them means
    // rewriting content nobody here authored, which the audit refuses to
    // do and no single command can do for an operator.
    code: "planted-structure-rows",
    reason:
      "the rows are third-party text already written into the vault, and un-planting them means " +
      "rewriting or re-capturing content nobody here authored; the audit is read-only by " +
      "contract, and the enforce-mode gate prevents the next write rather than repairing the " +
      "last one, so the exit is the operator's decision to re-capture specific pages or to run " +
      "a later repair pass",
  },
  {
    code: "stale-lock",
    reason:
      "the lock primitive is a single-attempt exclusive create, so no timeout distinguishes a " +
      "crashed writer from a slow live one and nothing may remove the file automatically. The " +
      "exit is the operator's judgement followed by a manual deletion",
  },
  {
    code: "status-folder-mismatch",
    reason:
      "the status field and the containing folder disagree, and either could be the true one. " +
      "Moving the file and rewriting the field are different repairs with different lifecycle " +
      "consequences, and the record does not say which happened",
  },
  {
    code: "symlink-escape",
    reason:
      "a link leaving the vault is removed or repointed depending on what it was for, and " +
      "following it to find out is exactly what this check refuses to do - a reader that " +
      "follows it has already left the store",
  },
  {
    code: "vault-include-missing-path",
    reason:
      "the allowlist names a root that is not at the vault root. Creating the folder and " +
      "correcting the spelling are different intents with different indexes as their result, " +
      "and the finding cannot tell which the operator meant - deleting the entry, the only " +
      "mechanical option, would silently widen the boundary they wrote",
  },
  {
    code: "vault-include-admits-nothing",
    reason:
      "the allowlist as a whole matches no file in this vault, so the index would be empty. " +
      "Which of the declared roots is wrong, and whether the answer is to fix a spelling, add " +
      "a root or create the folder, is a question about what the operator meant to index; a " +
      "mechanical repair would have to pick one of those on their behalf",
  },
  {
    code: "vault-ignore-missing-path",
    reason:
      "the ignore rule names a path that is not in this vault. It is usually a typo, but it can " +
      "also be a path not created yet, and silently deleting a rule the operator wrote is worse " +
      "than reporting that it currently matches nothing",
  },

  // --- Edits whose target shape the finding cannot supply ------------------
  {
    code: "config-warning",
    reason:
      "the resolver reports a key in Brain/_brain.yaml it could not honour. The repair is an " +
      "edit to that file and the value to write is a policy choice; the resolver fell back to " +
      "a default rather than guessing, and so does this",
  },
  {
    code: "invalid-capture-pattern",
    reason:
      "a regular expression in the capture configuration failed to compile. What it was meant " +
      "to match is not recoverable from a pattern that does not parse, so the repair is an edit " +
      "by whoever wrote it",
  },
  {
    code: "person-nicknames-unreadable",
    reason:
      "the operator's person nickname map exists but cannot be used - it does not parse or " +
      "violates its shape. The repair is an edit to that file by whoever wrote it: the map it " +
      "was meant to hold is not derivable from the error, and minting nickname data would put " +
      "words in the operator's mouth about who knows whom",
  },
  {
    code: "person-nicknames-entry-skipped",
    reason:
      "one entry of an otherwise usable person nickname map resolves nobody - the nickname " +
      "normalizes to nothing, every value it lists normalizes to nothing, or the nickname " +
      "equals a name it stands for. The repair is an edit to that entry by whoever wrote it: " +
      "which real-world nickname was meant, and for whom, is their knowledge and is not " +
      "derivable from the finding, so the doctor names the entry's position and stops there",
  },
  {
    code: "iso-invalid",
    reason:
      "a timestamp field is not ISO-8601. The instant it meant is not recoverable from the " +
      "malformed text, and writing today's date would make a record that lost its time look " +
      "like one that was written now",
  },
  {
    code: "log-malformed",
    reason:
      "a log line the parser has no branch for. The log is append-only history, so rewriting a " +
      "line to fit the grammar changes what was recorded - the finding names the file and the " +
      "line number precisely so a human can read the original",
  },
  {
    code: "malformed-evidence-range",
    reason:
      "the line range on a logged artifact reference does not parse. The range the author meant " +
      "is not derivable from the malformed text, and the event itself stays valid, so nothing " +
      "is lost by leaving it reported",
  },
  {
    code: "embedding-model-sunset-unsurveyed",
    reason:
      "the configured model is outside the shipped decommission survey, and the repair is for " +
      "somebody to look up whether its provider has announced anything - a question about the " +
      "world, answered by reading a vendor's notice rather than by any edit to this vault. The " +
      "finding says only that no statement was made, which is deliberately not the same as " +
      "saying no decommission exists",
  },
  {
    code: "embedding-model-sunset-undetermined",
    reason:
      "the check ran and reached no verdict, for one of three reasons it names in the finding: " +
      "the configuration resolved no model, the survey is older than its horizon so its record " +
      "of no announcement has expired, or a shipped survey entry carries an unparseable date. " +
      "The first is an edit to a config file whose intended value only the operator knows, and " +
      "the other two are defects in this build rather than in the vault being examined",
  },
  {
    code: "rerank-model-sunset-unsurveyed",
    reason:
      "the configured rerank model is outside the shipped rerank decommission survey, and the " +
      "repair is for somebody to look up whether its provider has announced anything - a " +
      "question about the world, answered by reading a vendor's notice rather than by any edit " +
      "to this vault. The finding says only that no statement was made, which is deliberately " +
      "not the same as saying no decommission exists",
  },
  {
    code: "rerank-model-sunset-undetermined",
    reason:
      "the check reached no sunset verdict for the rerank model, for a reason it names in the " +
      "finding: the search configuration could not be resolved, the survey is older than its " +
      "horizon so its record of no announcement has expired, or a shipped survey entry carries " +
      "an unparseable date. The first is a config file whose intended content only the operator " +
      "knows, and the other two are defects in this build rather than in the vault examined",
  },
  {
    code: "embeddings-census-unrecorded",
    reason:
      "the pending-vector count could not be taken: the index file is absent or would not open, " +
      "and the finding says which. What restores it depends on which - an absent index is a " +
      "first-run state an operator reaches deliberately, while a file that will not open is " +
      "replaced, not repaired in place, and replacing it is a decision about the derived copy " +
      "rather than about the vault it indexes. Reporting a count of zero here would read as a " +
      "fully embedded index, which is precisely the failed-read-as-healthy the check refuses",
  },
  {
    code: "attestation-state-unmeasured",
    reason:
      "the attestation family is there and the read over it was refused - the records would " +
      "not list, the newest one would not parse, or the verification walk threw - so whether " +
      "the signed point still holds is unknown rather than fine. What restores it depends on " +
      "which read failed and why, and the records themselves must never be rewritten to make " +
      "a check succeed, since they are the signed evidence the family exists to keep",
  },
  {
    code: "embeddings-health-unmeasured",
    reason:
      "the check ran and could observe too little to say anything: the search configuration " +
      "would not resolve, the index probe threw, or the count half of the read failed after the " +
      "census half succeeded. Which half failed changes what restores it, and the finding names " +
      "the one that did - so the honest exit is the reason rather than a command guessed for a " +
      "state nobody observed",
  },
  {
    code: "payload-missing",
    reason:
      "the exact bytes a placeholder stands for are gone from the payload store. Nothing in this " +
      "vault can regenerate them - the source transcript may be deleted or rotated - and which " +
      "recovery point still holds them is a choice between archives that also roll back " +
      "everything else written since, which only the operator can weigh",
  },
  {
    code: "continuity-row-oversized",
    reason:
      "the rows were appended before the payload registry bounded session text. The continuity " +
      "ledger is append-only history that other devices merge by content id, so rewriting a " +
      "shard in place would re-identify its rows on every peer. The finding measures weight " +
      "rather than damage - every row still reads - so whether that cost is worth a rewrite is " +
      "the operator's call, and no command makes it for them",
  },
  {
    // The blank-session-identity count (t_22d58fa7). A session no writer
    // stamped cannot be restored from the record: assigning one would
    // fabricate provenance over append-only history.
    code: "blank-session-identity",
    reason:
      "the finding is a count of records whose payload names no session, which is a fact about " +
      "the writers, not a defect in any one row. Stamping an identity after the fact would " +
      "fabricate provenance over append-only history that peers merge by content id, so the " +
      "only honest exit is the count itself - the condition is worth knowing about, and any " +
      "rewrite belongs to a restore from backup, not to a command this table could name",
  },
  {
    code: "recovery-point-unmeasured",
    reason:
      "the recovery-point history is there and the walk over it was refused. What repairs that " +
      "depends on why - a permission an operator has to decide to grant, a directory owned by " +
      "another user after a sync that preserved ownership, or storage that has started failing - " +
      "and the archives themselves must never be removed to make a listing succeed, since they " +
      "are the only way back from a mistake",
  },
  {
    code: "recall-channel-unmeasured",
    reason:
      "the finding is that the install side of a recall channel could not be READ - a config gate " +
      "that would not resolve, or an audit root that denied the walk. What repairs it depends on " +
      "which, and on why: a permission an operator has to decide to grant, a config file to fix, " +
      "or a path that belongs to another user entirely. Guessing one would act on a state this " +
      "pass never managed to observe",
  },
  {
    code: "receipt-content-drift-unmeasured",
    reason:
      "the receipt ledgers are there and the re-hash over them was refused, so whether recent " +
      "receipts still match the vault is unknown rather than fine. What restores it depends on " +
      "why - a permission an operator has to decide to grant, or a ledger replaced by a file " +
      "that will not open - and the ledgers must never be edited to make a scan succeed, " +
      "since they are the record the verify verdicts are issued from",
  },
  {
    code: "receipt-ledger-unmeasured",
    reason:
      "the receipt ledgers are there and the scan over them was refused, so whether they grow " +
      "unbounded is unknown rather than fine. What repairs that depends on why - a permission " +
      "an operator has to decide to grant, or a regular file that replaced the ledger directory - " +
      "and the ledgers themselves must never be removed to make a scan succeed, since they are " +
      "the continuity history any fold would be rewriting",
  },
  {
    code: "storage-capacity-unmeasured",
    reason:
      "the vault is capped and the census over its surfaces was refused, so fullness is unknown " +
      "rather than fine. What repairs that depends on why - a permission an operator has to " +
      "decide to grant, a surface owned by another user after a sync that preserved ownership, " +
      "or storage that has started failing - and the surfaces themselves must never be removed " +
      "to make a census succeed, since the reading they hold is the fact the cap is judged " +
      "against",
  },
  {
    code: "preference-missing-field",
    reason:
      "a required frontmatter field is absent and its value is not recoverable from the rest of " +
      "the record. Writing a placeholder would make an unreadable preference read as a true " +
      "one, which is worse than a record the doctor keeps naming",
  },
  {
    code: "preference-invalid",
    reason:
      "the preference could not be parsed, for a reason the parser reports verbatim in the " +
      "finding. The repair is an edit whose target shape depends on which part of the grammar " +
      "broke, so there is no one command that covers the class",
  },
  {
    code: "retired-missing-field",
    reason:
      "a required frontmatter field is absent from a retired record and its value is not " +
      "recoverable from the rest of the file. A placeholder would fabricate lifecycle " +
      "provenance, which is the one thing a retired record exists to hold",
  },
  {
    code: "retired-invalid",
    reason:
      "the retired record could not be parsed, for a reason the parser reports verbatim in the " +
      "finding. As with its preference twin, the repair is an edit whose shape depends on which " +
      "part of the grammar broke",
  },
  {
    code: "secrets-sync-exposed",
    reason:
      "the repair is one line in the Syncthing folder's root .stignore, which the finding " +
      "names verbatim. That file is the operator's sync configuration and is shared with every " +
      "peer, so no verb here edits it: whether a machine the operator owns should hold the " +
      "keyfile is their decision, not a repair this tool can make for them",
  },
  {
    code: "signal-invalid",
    reason:
      "the signal file could not be parsed. A signal is a captured observation, so what it was " +
      "meant to say exists only in the source it was captured from - reconstructing it here " +
      "would be inventing the observation",
  },
  {
    // The lessons-block readiness family (t_1e952e43, task C3). All four
    // are operator advisories over derived state the refresh verb heals;
    // each finding already names the exact verb (approve for a missing
    // block, refresh for a stale or diverged one), so a registry command
    // would repeat what the finding carries.
    code: "lessons-block-absent",
    reason:
      "an approval names a rules file that carries no lessons block; creation sits behind the " +
      "approve verb's consent ladder, which the finding itself names, so nothing here is healable " +
      "without the operator's explicit consent and no single command belongs in the registry",
  },
  {
    code: "lessons-block-drifted",
    reason:
      "a managed lessons block is behind the canonical body; the refresh verb converges it and " +
      "the finding names that verb including the force wording for a hand-edited block, so a " +
      "registry row would only duplicate what the finding already says",
  },
  {
    code: "lessons-block-stale-lessons",
    reason:
      "a managed block still carries a lesson whose approval went stale; the refresh drops it " +
      "until the operator approves the moved text again, which the finding names - the decision " +
      "is the operator's own re-approval, not a command the doctor can carry",
  },
  {
    code: "legacy-devices-pending",
    reason:
      "the remedy is on the other machines: each one upgrades and runs its own migration, or the " +
      "user retires the ones that are gone; nothing this machine runs moves another machine",
  },
  {
    code: "migration-done-twice",
    reason:
      "two first migrations already ran; the store keeps both imports and no command undoes one " +
      "without losing the other, so the finding names the machines and the rule that prevents it",
  },
  {
    code: "legacy-tree-reappeared",
    reason:
      "the directory is evidence of a writer that still follows the legacy layout; the user stops " +
      "that writer and moves the directory out, and nothing here can tell what in it they want kept",
  },
  {
    code: "lessons-approvals-unreadable",
    reason:
      "the approvals ledger is damaged; every approval is lifted only by the operator moving or " +
      "deleting the file, which the finding spells out with the fail-closed direction - there is " +
      "no mechanical repair a registry row could offer",
  },
];

/** Two entries claimed one code - the table would silently lose one. */
export class DuplicateDoctorExitExclusionError extends Error {
  constructor(code: string) {
    super(`DOCTOR_EXIT_EXCLUSIONS declares doctor code ${JSON.stringify(code)} more than once`);
    this.name = "DuplicateDoctorExitExclusionError";
  }
}

/**
 * The published table, code to reason. Built eagerly so a duplicate fails
 * at import rather than silently losing an entry.
 */
export const DOCTOR_EXIT_EXCLUSIONS: ReadonlyMap<string, string> = (() => {
  const table = new Map<string, string>();
  for (const entry of EXCLUSIONS) {
    if (table.has(entry.code)) throw new DuplicateDoctorExitExclusionError(entry.code);
    table.set(entry.code, entry.reason);
  }
  return table;
})();

/**
 * The published reason `code` has no next command, or `null` when the
 * table publishes none. `null` is also what a code WITH a registered
 * command yields: the two questions are asked in that order by every
 * caller, and a code cannot honestly answer both.
 */
export function doctorExitReason(code: string): string | null {
  if (resolveNextStep(code) !== null) return null;
  return DOCTOR_EXIT_EXCLUSIONS.get(code) ?? null;
}

/**
 * The additive JSON key a machine-readable surface carries the reasons
 * in. Named once here for the same reason `NEXT_COMMAND_KEY` is: the CLI
 * `--json` renderer and its MCP twin must not drift on the spelling.
 */
export const NO_EXIT_KEY = "no_exit";

/**
 * The published reasons for `codes`, deduplicated, in the order the codes
 * were reported.
 *
 * Deduplicated by code rather than by reason, because unlike a next
 * command - which two codes can share - a reason is about one class. A
 * registered code contributes nothing, and neither does one the table
 * does not know: an empty result is what a report whose every code has an
 * exit produces, which is what keeps both surfaces byte-identical on the
 * vaults that had no gap to explain.
 */
export function noExitReasons(codes: Iterable<string>): ReadonlyMap<string, string> {
  const out = new Map<string, string>();
  for (const code of codes) {
    if (out.has(code)) continue;
    const reason = doctorExitReason(code);
    if (reason === null) continue;
    out.set(code, reason);
  }
  return out;
}