--- part_of: '[prov](/README.md)' --- # Next steps — working notes Deferred items from the identity / wikilink / link-syntax work, so we don't lose them. Not curated design (that's `DESIGN.md`); this is a scratch backlog. ## What the property tests turned up `proptest` is a dev-dependency, and five modules carry a `mod properties` beside their example tests: `link` (reference round-trips, path arithmetic), `mutate` (sequences of verbs against `check`), `index` (the id↔path bijection), `identity` (the check character), and `textdist` (the metric axioms). Each states a claim the prose already made and quantifies it. A sixth, `fixity::cache` (the hand-rolled binary frame), went with the cache itself. Five defects found, **all fixed**: - **Both canonical link styles failed `resolve ∘ format = id`** — not just `plain_canonical`, which is what this file had said for months. `PathStyle` is now `root | relative`; see the link-syntax section below. - **`delete`/`recycle` on a separated node's body** stranded its `content:` pointer silently. Both now refuse a body as a subject and name the node instead; `--force` proceeds and reports the pointer it stranded, which the dangler census could never see (`content` is neither a relation nor a body link). `maintain::content_owner` answers "whose body is this", bounded to the body's own directory — every body prov authors sits beside its node. - **A displaced id was forgotten rather than tombstoned,** so `is_known` — the mint-by-rejection predicate — went true → false and the id became reissuable while the displaced document still spelled it. Two operations reached it. `FileIndex::register` now retires what it displaces. - **A re-registered id was held live *and* tombstoned** (the `restore`-from-bin path), disagreeing with what `render` writes. `register` now clears the tombstone — safe only because of the fix above, without which a restored id that was later displaced would have had no tombstone left. The two had to land together; the first attempt at this one alone regressed the other, and the property caught it in three operations. - **`recycle` resurrected a parentless document.** Found while fixing the separated-body guard, and older than it: the bin bootstrap wrote its pointer into `spanning_root(subject)`, which for a document with no parent *is the subject*, so the change set renamed the file into the bin and then wrote it straight back — `prov rm` on an orphan left it in place carrying a `recycle_bin:` key, beside a copy in the bin. Orphans are exactly what a user bins, since `check` reports them as the onboarding signal. Two behaviours the laws had to be told about, both correct as they stand: `delete` reports rather than rewrites the references it strands (so the law is "introduces nothing it did not report", which also tests that the report is *complete*), and `duplicate` leaves a parentless copy unattached by its own documented contract. The `mutate` law is still scoped to the spanning tree's **nodes** rather than every file on disk. With the separated-body guard in place a body subject is now refused rather than mishandled, so widening the domain is mostly a question of what `rename` and `retitle` owe a file that is content but not a node — worth trying, and likely to surface a `rename`-shaped sibling of the `delete` finding. Not yet done: `journal`/`change` have no properties, and they are the obvious next site — replay idempotence, and "an interrupted set resolves fully-before or fully-after" quantified over generated change sets rather than the hand-placed `FailAtWrite` fixtures. ## Identity & backlinks - **Step 4 — gated malformed-id autofix.** The one document-repairing heal: when the census finds a malformed `id:` near an edge the registry resolves uniquely, offer to restore it. Directional invariant: forward links are ground truth; the index heals *toward* them; it rewrites a document *only* for a dangling id it can resolve from its own record. Everything else: report. - **Route C — persist the backlink map.** Where "id-backlink registration" finally has a home. Store the census-derived backlink map in the index's *derived* section (structurally separate from the authoritative `id → path` registry, per DESIGN §5), plus a `Reconciled` report (backlink added/dropped, out-of-band id-link registered). The census is its self-heal. - **Frontmatter id-shadow (DESIGN §5 escape hatch).** Stamp a forward id-link's id into the *source's* frontmatter so the forward-link truth is complete in the nodes: backlinks become fully derivable, the §4 out-of-band hazard becomes recoverable, and self-healing goes total — no central authoritative residue. The thesis-aligned alternative to Route C. - **Authoring `[[prov:id]]` wikilinks.** The write side of the original idea #2: mint via `Trigger::Link`, drop the target into body prose. Closes the loop — the whole census/rename/backlink stack was built to support this. ## Autofix (DESIGN §8 — the sleeper feature) Lives in **`prov/src/remedy.rs`**, carved out of `validate.rs`: a finding says what is wrong, a remedy says what could be done about it, and only the second knows how to change a document. `validate.rs` is now a findings view and nothing else — `Finding`, `CheckDiff`, `check` and its eight sub-passes — which is the same line that keeps `graph` ignorant of `Finding`, drawn one layer up. It also retires the precondition `graph/mod.rs` had recorded for a `Graph` carve-out; that split is unblocked, and still unwarranted (a `Graph` handle would have to thread through every mutation verb, and each of them reads and writes in the same breath). Principle **restated**: a repair edits structure — frontmatter, or a span *twig's own parser* reported as a link — and never ordinary prose; and it never deletes a file. The old formulation ("metadata only, never body prose") was a proxy for the real objection, which is that a `[[…]]` may be code (`[[inf] * n for _ in range(m)]]`) and a lexical scan cannot tell. `link::parsed_link_spans` can, so `[label](target)` in prose is now repairable while `[[…]]` stays diagnosis-only — twig has no wikilink concept, so a wikilink span is lexical either way. - ✅ **Remedies replace the one-answer signature.** `suggest_fix`'s `&Finding -> Option` could hold one repair, so a finding with two defensible ones got none — and the split that created tracked how settled each repair was, not any property of findings. `remedies() -> Vec` is the general surface; `suggest_fix` survives as a view over it (the first non-destructive remedy). Each remedy carries a `RemedyKind` slug and a `Warrant`: `Derived` (a pure function of an authority — safe unattended), `Judgment` (rivals exist), `Destructive` (removes something authored). - ✅ **Contested containment**, both ends of it — `DuplicateContainment` and a `MissingInverse` whose child claims another parent — now offer (a) make this the real parent (delegating to `reparent`, which repoints the child *and* drops the rival's entry in one change set) and (b) drop this container's entry. Option (c), demoting a spanning link to an overlay relation, is still unbuilt. - ✅ **Broken frontmatter link** — a retarget per directory-local near-match, plus removal. Body links too, under the twig rule above. - ✅ **`Orphan` is a remedy like any other**, offering every container above it nearest-first, which retires the CLI's hardcoded "adopt under the root" — that literal existed only because a `-> Option` had nowhere to ask. - ✅ **Non-interactive `--fix mechanical`** applies every `Derived` remedy and prompts for nothing. Bare `--fix` is still interactive (EOF → skip). - ✅ Also gained remedies: `CaseMismatch` (`Derived` — the on-disk name is in the finding), `MalformedId`/`DanglingId`, `AmbiguousAlias` (one per candidate), `IdMismatch` (both sides — "trust the document" was already implemented as `Fix::RegisterId` and simply unreachable), `UnknownTerm`/`TermNearMiss` (respell, or widen the vocabulary — never over a *retired* term, which would un-retire it and destroy its id and gloss), and `ConfigIssue`. Still open here: - **Restore-from-backup for `FixityMismatch`.** Restoring is the arm prov cannot decide, and a version-control store beside the workspace can actually perform it — but prov no longer knows such a store exists, so the honest shape is a finding message that names the situation rather than a `Fix` that shells out to a tool prov cannot see. Until then `FixityMismatch` offers only the re-stamp, marked `Judgment`. - **`DemoteEntry`** — spanning → overlay, contested containment's third answer. - **`MalformedStore`** — migrating a markdown store to a whole-file carrier creates a file and rewrites a pointer, so it is a mutation verb, not a fix. - **The `link_strings` index skew.** `Value::link_strings` filters non-string sequence items, so a position taken from it is not the fig index — `[a, 3, b]` yields `["a", "b"]`, and `remove_item(key, 1)` would delete `3`. `entry_index` + `remove_item` carry that skew at three sites (`delete`/`reparent`); harmless while relation sequences hold only strings. The new `written_entry_index` enumerates the raw sequence instead. - **A persisted fix policy.** "All of this kind" lasts one run. A `fix:` block in the workspace config mapping finding kind → remedy kind would make a choice durable, in the same self-describing way every other knob works. ## Body parsing (`twig`) The library prov was waiting on to parse file bodies now exists: [`twig`](https://github.com/diaryx-org/twig), a sister Zig-backed project (document formats, the way `fig` is for config formats). Wired in as a path dependency for now (`../twig/bindings/rust/twig` from the workspace root) — switch to a published version once `twig`'s Rust bindings have proven out. - ✅ **`content.rs` + `ContentFormat`.** `ContentFormat::from_extension` (`.md`/`.markdown` → Markdown, `.dj`/`.djot` → Djot) needs no feature; it's the type the deferred `content_format` config knob (below) will store. - ✅ **`content` feature — real FFI, both `render_html` and `code_spans`.** `twig`'s C ABI gained `twig_document_code_spans` alongside `twig_document_render_html` (a `TwigSpan{start,end}` array, one entry per `verbatim`/`code_block`/`raw_inline`/`raw_block` AST node — `twig/src/c_abi.zig`, header at `twig/bindings/c/include/twig.h`), and its Rust bindings a matching `Document::code_spans() -> Vec>` (`twig/bindings/rust/twig/src/lib.rs`). prov's `content::render_html`/ `code_spans` are direct calls into that — no subprocess. `prov render ` (prov-cli, same feature) exercises rendering end-to-end. - ✅ **Wired into `census`/`check`/rename — and it had to be more than a post-filter.** `link::scan_wikilinks(path, body)` is the one entry point `validate.rs`'s `walk` and `mutate.rs`'s two rename-time body-rewrite helpers call (never `parse_wikilinks` directly). A real vault turned up why a simple "filter matches that overlap a code span" post-filter (`exclude_code_spans`, kept as a narrower utility with its caveat spelled out) can't do this alone: `parse_wikilinks`'s greedy "next `]]` wins, code or not" scan lets one stray `[[` inside a fenced Python block (`[[float('inf')] * width for _ in range(m + 1)]`) eat every `]]` *after* it in the document — including a real `[[gone.md]]` further down — merging them into one bogus match that swallows the real link whole before any span-overlap filter ever sees it separately. `scan_wikilinks` fixes this at the source: it treats each code span as opaque *before* scanning, running `parse_wikilinks` independently on each prose run between (and around) code spans and stitching the results back into `body`-relative spans, so a code-block bracket can never be in the same scan as prose that follows it. `validate::tests::check_does_not_flag_python_list_comprehensions_in_a_code_ block_as_broken_links` reproduces the real report life-sized. No config knob was added — it's automatic whenever `content` is compiled in and the extension is recognized, degrading silently to the old unfiltered scan otherwise (feature off, unrecognized extension, or a twig failure). Still not done: needs a `prov-cli` rebuilt with `--features content` to actually take effect — not a default feature yet, since it pulls in the path-dependent `twig` (no released version to depend on by default). Whether it should become default once `twig` is published is open. - ✅ **`twig`'s generic query surface is now exposed at the C boundary** — the hoped-for selector export landed. `twig_document_query` (Rust: `Document::query(selector)`, a CSS-lite selector reaching *every* node kind, returning `QueryMatch { span, kind }`) replaced the code-kind-specific accessor `code_spans` used to bind; `code_spans` now selects the code kinds itself over the generic API. Crucially for link ownership, twig also exposes a flat-node array (`Editor::nodes() -> [FlatNode]`) whose `destination: Option` carries each `link`/`image` node's target. ✅ **Consumed:** `content::link_spans` queries `link` nodes for their spans, and `link::scan_body_links` slices each span and parses it with `Link::parse` (the span is authoritative, so no `destination` lookup is needed and no balanced-paren scan can over-reach). This is what made link-syntax **Stage 2** land (see below). Still unused from this surface: `image` nodes and the `destination`/reference-link path — a follow-up when non-inline links matter. ## Workspace config (the `config` relation) Established: **workspace config is a reachable, self-describing document linked from the root via a well-known `config` relation** — the registry's §6 reachability move, applied to policy. Lazily materialized (`prov config ` creates + links `prov.yaml` on first write); absent config = all defaults. `link_format` precedence: config doc > root frontmatter (diaryx compat) > default. - ✅ `config` relation + `config_path`/`config_get`; CLI `config` get/set/print with `ensure_config` bootstrap; autofix + `find_root` read from it. - ✅ **Typed `WorkspaceConfig`** (`config.rs`): `link_format`, `identity`, `id_links`, `embed_format`, with `paths_only()`/`stable_ids()` presets and `apply`/`from_meta`/`to_mapping` round-trip. The CLI builds the whole workspace from it, so **Diaryx and Obsidian are each just a config** — verified: `prov id` refuses under Diaryx / mints under Obsidian; `prov new` authors id links under Obsidian and a move leaves them untouched (registry does the maintenance). `prov config` prints all knobs. - ✅ **id-link authoring** (`Workspace::authored_target`): `create` and autofix author `id:` (registering the target) when `id_links` is on and identity registers on a link, else a path in the link style. `create` mints IDs → `cmd_new` bootstraps the registry first when it will mint. - ✅ **`default_embed_format`** wired into `create` (new-doc archetype default). - ✅ **`content_format`** — the body-prose grammar, a full `WorkspaceConfig` field (`markdown`/`djot`/`html`), persisted by `init` (from `--content`) and read back like every other knob. `ContentFormat::extension()` gives the canonical file extension, so **title-primary `prov new "A Title"`** derives a readable filename (`link::slug(title).`) beside the parent while recording the real title in metadata; `--as ` / `--ext ` override the derived name (DESIGN §1 legibility — a slug, never an opaque `note-3.md`). The title-primary library seam is `Workspace::create_with_title`. Existing documents are reconciled by `convert content_format ` (engine 3 below) — the knob governs what gets *written next*, the convert governs what is already there, and the two are deliberately independent (a mixed-grammar workspace is valid, since every reader takes the grammar from the file's own extension). - **More config knobs.** `vocabulary` (a named `RelationSet` preset, later a full spec). - **`prov config preset diaryx|obsidian`** — write a whole preset via `WorkspaceConfig::to_mapping` (the round-trip is already there). - **Route `rename`'s path rewrites through the link style too.** `create` and autofix now author via the style/id seam; rename's inbound path rewrites still emit relative. Fold them through `format_link` for full consistency. - ✅ **Builder threading smell — fixed by `Settings`.** Each knob (`link_style`, `id_links`, `default_embed_format`, …) had been hand-threaded through four field lists that all had to agree: `WorkspaceBuilder::identity`, `::index`, `::build`, and `Workspace`'s hand-written `Clone`. Ten of them now live in a `Settings` struct the type-flipping methods carry whole, so those four sites no longer mention any knob and `Workspace` went from 17 fields to 8. Note what the risk actually was: an *omitted* field was always a compile error, so the hazard was a line reading `workspace_id: String::new()` where it meant `self.workspace_id` — same type, no error, one knob silently defaulted for whoever called that method. `every_setting_survives_the_builder_type_flips` pins it. `Settings::from(&WorkspaceConfig)` is the payoff: the CLI's workspace construction went from ten builder calls to one, and a knob added to the config now reaches the workspace without touching `prov-cli`. It lives in `workspace.rs` because `workspace` already depends on `config`, and the reverse edge would be a cycle for no gain. - **Custom registration combos.** `identity` serializes as `off`/`lazy`/`eager`; a non-preset trigger set falls back to `lazy` on write. Represent as a sub-mapping if custom combos ever matter. - **Config doc's own `part_of` style.** On first creation it's written in the link style active *before* the setting applies (default markdown-root), which can differ from the value just set. Cosmetic; rewrite it in the final style. - **Generalize "workspace resource via well-known relation."** Registry + config are the same shape (reachable, self-describing, lazily materialized). Codify a small reserved-relation spine; a derived-index cache (Route C) is the next instance. Also: refactor `ensure_registry` to share this bootstrap shape. ## Config conversion (per-file `convert`) Established: setting a config axis governs *new* documents; a parallel **`convert` mutation** reconciles *existing* ones — the workspace can "restate itself" in a different style/format/grammar while structure is preserved (§6 reachability + §7 format-agnosticism, made an action). Decided this session: - **Per-file by default (DESIGN §8), not workspace-wide.** `convert ` restyles only what *that* document declares; `-r` extends to its spanning subtree (so `convert … -r` is the whole-workspace case). No `--all`. `-f`/force is reserved for the lossy/destructive directions. A mixed style across the tree is valid and `check`-clean. - **One command surface over ~4 distinct engines** (not one uniform transform): 1. ✅ **Reference re-authoring** (`link_format`, and later `reference_wrapper/ target/label`, `relation_styles`) — re-spell links, frontmatter *and* body, destination/label/wrapper preserved, id/external/alias skipped. `Workspace::convert_link_style` + `restyle_frontmatter_links`/ `restyle_body_links`; CLI `convert link_format