Graphden documentation

Versioning

Branches, history, diff, and merge for the fn graph. The storage decorator that backs all of this (VersionedStorage) was the original deliverable of the versioning effort — this document describes what landed on top of it in feat/versioning: the HTTP surface, the per-branch executor routing, the editor UI, and the dev-loop ergonomics.

For the underlying schema + branch resolution algorithm, see ROADMAP.md § Git-like Versioning.

Mental model

The bare VersionedStorage decorator already knew how to:

What was missing was anyone HOLDING a VersionedStorage pointed at the right branch when an HTTP request came in. The executor’s compiled closures close ctx in at compile time ((impl args ctx) — executor/compile_eager.clj), and that ctx carries one specific VersionedStorage. So serving a request on branch X requires its OWN compiled registry, bound to a VersionedStorage whose branch-id is X’s.

feat/versioning adds the routing layer that builds + caches those per-branch contexts on demand, and the HTTP / editor surface that exercises it.

HTTP request
  │
  │ X-Graphden-Branch: feature-x        (or ?branch=feature-x, or absent)
  ▼
:_branch-routed-handler (compiled main fn-graph)
  │
  ▼
graphden.system.branch-router/dispatch
  │
  │ resolve branch-id from header/query → atom lookup
  ▼
per-branch Ring callable
  │
  │ re-reads (registry branch-ctx) on every call so
  │ post-write invalidation propagates without re-attach
  ▼
per-branch compiled closure
  │ ctx baked in → reads + writes go through
  │ VersionedStorage bound to feature-x
  ▼
PG storage

The branch model in plain words

Everything below the routing layer follows from three rules. They are what a user of the branch popover can rely on, and what versioning.storage.resolution / versioning.storage.merge implement (merge-semantics-test pins each one as a scenario).

A branch is a live view of its base for everything it has not touched. Forking copies nothing. Reading X on feat finds feat’s own version of X if feat ever wrote one; otherwise it shows whatever its base shows right now — an edit, a deletion or a new fn on main is visible on feat the moment it lands, with no action on feat’s side. Only the entities feat edited (or deleted, or resolved in a conflict — those are edits too) are pinned to feat’s own rows.

A merge carries one branch’s own changes onto another, and from then on they are the target’s changes. Merging feat into main writes one branch_merge record; feat’s own rows now resolve on main (and on every branch that follows main). Nothing is copied, which is why a merged branch cannot be deleted. Two consequences:

A conflict is one entity changed on both sides since the fork to different content. “Changed on a side” means the side’s winning version arrived there after the fork point — written there, or landed there by a merge. Identical content on both sides is not a conflict (the same edit made twice, both sides deleting, the one inherited row both branches show). Different fields of one entity still conflict — the row is the unit you resolve — and the conflict payload names which fields differ with each side’s value (:fields, in the editor’s display form), plus the slot a binding row belongs to (:slot-name). A branch-local fn is never a conflict: its rows do not cross branches at all.

Per-branch routing

Lifecycle

  1. :exec/branch-router init-key runs after :exec/compiled-registry, so main’s registry is already populated.
  2. Construction seeds the atom with the default-branch entry ({branch-id → {:ctx :handler :built-at}}). Reuses the existing base-ctx — no extra compile pass for main.
  3. On a request, dispatch extracts the branch ref (header wins over query param; both must be non-blank to count), resolves to a branch-id via base storage.
  4. If the branch-id has a cached entry, use it. Otherwise call build-and-cache!:
    • Construct a fresh ExecutionContext with (VersionedStorage. base-storage branch-id) and FRESH atoms for :compiled-registry, :graph-cache, :compile-deps.
    • Call cr/rebuild! — full compile pass against the branch’s resolved view.
    • Build a Ring callable that re-reads (registry branch-ctx) on EVERY invocation, so a subsequent write that clears the registry atom is visible to the next request without our cache having to be invalidated too.

Invalidation

The standard invalidate-graph-cache! flow still applies to the written branch. branch-router/invalidate-affected-ctxs! also invalidates cached branches whose resolved view inherits from it. A write on a feature branch leaves main and unrelated branches warm; a write on main can affect its inheriting branches. Known fn-id seeds trigger delta recompilation; an unknown write shape clears the affected caches. Uncached branches are not built just to invalidate them.

Cost model

Why singleton atom, not on ctx

graphden.system.branch-router/active-router-global is a process-wide atom set by the init-key (read through active-router-atom, which prefers the per-thread *active-router-override* when a test binds one for isolation). The wrap base-fn impl (web.branch-router/branch-routing-wrap) runs inside a compiled closure that already closed over a fixed ctx — the wrap CAN’T reach into the running router via ctx, because the router didn’t exist when the closure was built.

Branch selection

Per request:

  1. X-Graphden-Branch: <name> header (wins)
  2. ?branch=<name> URL query param (URL-decoded)
  3. neither → default branch (main)

Both name and stringified UUID are accepted; the router normalises via the base storage’s :branch table. Unknown ref → 400 with an {"ok":false,"error":"Unknown branch: <ref>"} body (caught at the dispatcher, never reaches the per-branch handler).

The editor’s window.fetch is wrapped at module load (editor-branches.js) so every /api/* call picks up the current branch header automatically — individual call sites stay unaware. The branch state lives in three coordinated places:

Switching branches mutates BOTH localStorage and the URL, then calls location.reload() — the simplest “invalidate every cached view” strategy.

HTTP API

All endpoints are JSON. Auth is the standard bearer-token middleware; read endpoints sit behind it too (matches /api/services).

Verb Path Body Returns
GET /api/branches   {ok, count, branches: [{id, name, base-branch-id, created-at, owner-id, write-policy}]}
GET /api/branches/:ref   {ok, branch} or {ok: false, error}
POST /api/branches {name, base-branch-id?, forbid-invalid??, write-policy?, require-merge??} {ok, branch} — the creating principal’s stable id is stamped as owner-id
POST /api/branches/:ref/policy {write-policy} ∈ open/owner/admins {ok, write-policy} (open clears to null) — WHO may flip is the tenancy authorize-writer’s call
POST /api/branches/:ref/protect {require-merge} boolean {ok, require-merge?} — the open-core “push only via merge” toggle; direct writes then 409 :branch/merge-required, merges still land
POST /api/branches/:ref/propose {proposed} boolean (absent ≡ true) {ok, review-state} — mark/withdraw the branch as a change proposal for review into its base (open-core); the reviewer list = branches with review-state "proposed"
POST /api/branches/:ref/archive {archived} boolean (absent ≡ true) {ok, archived} — fold a finished branch into the popover’s “Merged” group / bring it back (:archived-at). A merge into the branch’s OWN base archives it automatically; opening it from the popover un-archives it. A merged source cannot be deleted (below), so this is how the list stays short
POST /api/branches/:ref/review-policy {required-approvals, allow-self-approval, approver-ids} {ok, policy} — set the branch’s review requirements (on the merge target); enforced open-core by the merge gate
POST / DELETE /api/branches/:ref/approve (empty) {ok, approver} / {ok, removed} — record / withdraw the caller’s approval of a proposal; POST is :authz/forbidden (403) if the caller may not approve merges into the target
GET /api/branches/:ref/approvals   {ok, required, have, satisfied, approvers:[{approver-id, counted, reason, stale}]} — the proposal’s approval status; a row the merge gate ignores has counted: false + a reason (stale / other-target / not-an-approver / author)
DELETE /api/branches/:ref   {ok, id, name} or {ok: false, reason, error, child-branch-ids?}. Rejected when the branch has children (:reason :branch-has-children) or is a live merge SOURCE (:constraint-violation/branch-is-merge-source — deleting it would revert every target it merged into, since merge is by-reference; delete those targets first). Everything the branch created goes with it — identity rows left with no version on any branch are purged in the same transaction (with the slots only its fn-slots exposed, and the type-rows those slots named), and the vault values of secrets bound only on the branch are reclaimed after the commit; the type-rows it declared stop resolving
GET /api/branches/:ref/diff?against=<ref>   {ok, target, source, count, diffs}
GET /api/branches/:ref/conflicts?source=…   {ok, target, source, fork-point, count, conflicts} — each conflict is {entity-name, entity-id, source-version, target-version, slot-name, fields}; a side that deleted the entity is null, fields is the per-field diff [{field, source, target}] in display form (fn refs as :name, empty when a side is a deletion). See § The branch model for what counts as a conflict
POST /api/branches/:ref/merge {source, conflict-resolutions?} {ok, merge}, {ok: false, reason: :merge-conflict, conflicts}, or {ok: false, reason: :merge-protection-violation, error, invalid-fns} (409 — target’s forbid-invalid? policy over recorded type diagnostics)
POST /api/import/graph?target=<branch>[&create=true][&prune=true] application/edn bundle ({:fns […]} or a bare fn-def vector) {ok, branch, fn-ids, skipped-owned, pruned?} — apply an exported bundle to a NAMED branch (registry package; ?target= because ?branch= is the request-scope selector; create forks it stamping the caller owner/owner-policy; prune = snapshot semantics; see PACKAGE_DISTRIBUTION § 13). The imported branch then rides this table’s normal diff → merge flow
GET /api/fns/:fn-id/versions   {ok, fn-id, count, versions} — each entry carries :execution-count (runs that anchored to that exact version row); 404 for a fn the viewer’s storage cannot read (another org’s private fn reads like a missing one), and no anonymous-hash / base-fn-id for one whose composition is concealed
GET /api/executions?fn-id=X   {ok, executions} — runs of X as it resolves on the current branch (not all-versions). Defaults to 20 rows, capped at 100
GET /api/executions?fn-version-id=Y   {ok, executions} — runs of the SPECIFIC version row (drives the ⌛ panel’s per-version expand)

Diff shape (wire, v1) and the display model (v2)

Each diffs[] entry:

{
  "entity-name": "fn",
  "entity-id": "<uuid>",
  "change": "added-in-source" | "added-in-target" | "modified",
  "source-version": { … } | null,
  "target-version": { … } | null
}

Filters out identity-only rows so a fn that exists on one branch but not the other reports :added-* rather than spurious :modified. created-at is dissoc’d before comparison. Note there is no removed change kind: deletion is a tombstone, and a tombstoned entity resolves to nil exactly like one that never existed on that branch — so “deleted on source” surfaces as added-in-target. The editor therefore phrases those as “only on " (the − badge / ghost-row tooltip), which is always true, instead of "added", which sometimes isn't.

Reviving a tombstone. core/revive-entity! (HTTP: POST /api/entities/:type/:id/revive, the editor’s undo of ⋯ → Delete) writes a fresh live version from the tombstone’s own data — the row tombstone-version! copied the pre-delete state into — on the current branch. Append-only like every write: the tombstone stays in history and the revival is one more version on top. A revived fn passes the same (namespace, name) collision check as a create (the name may have been reused since), and once the tombstone GC has purged the row there is nothing to revive (404). Natural-key entities revive on their own: a :binding / :fn-slot is identified by (fn-id, slot-id), UNIQUE at the base table, so creating one whose identity is tombstoned on the branch re-uses that identity (tombstoned-natural-key-id) and the new version is the live one — “unbind, then bind the slot again” used to bounce off the index with a 409.

Version authorship. New version rows carry a server-stamped stable author-id and a display-safe author-label; request payloads cannot set either field. Direct edits and explicit conflict resolutions are attributed to the acting account, while an inherited version surfaced by a merge keeps its original author. Old rows remain unattributed and appear as “unknown author” in the history panel.

Undo and branches. The editor’s 30-second Undo (editor-undo.js) is a per-tab journal of inverse WRITES, and every inverse lands on the branch the tab is on — the same branch the gesture landed on, since a branch switch is a page load that empties the journal. So an undo never crosses branches, never touches a merge that already happened (a fn created on a feature branch, merged, then undone is tombstoned on the feature branch only — the target keeps its copy, as any branch write would), and on a merge-protected branch it is refused like any other write, with the reason shown. One consequence worth knowing: deleting an INHERITED entity on a branch tombstones it there, and undoing that writes a branch-local version from the tombstone’s data — content-identical to the ancestor’s, so diff-branches (data-only comparison) does not list it and a merge carries nothing new, but the branch now holds its own version row of that entity.

The editor does NOT render this flat wire shape. It renders the GROUPED display model composed by app.branches/:diff-branches-view over the native graphden.versioning.storage.diff-view/diff-branches-view-facts read boundary (exposed behind GET /api/branches/:ref/diff-view?against=; the client renderer in editor-diff-mode.js consumes it for the inspector diff panel and the Review dialog’s change list):

{:count 3
 :groups [{:fn-id "<uuid>" :fn-name "web-server" :fn-label ":web-server"
           :change :modified          ; the OWNING fn's own change,
                                      ; or :modified when only parts moved
           :branch-local? false
           :entries [{:entity-name :fn :entity-id "<uuid>" :change :modified
                      :fields [{:field "description"
                                :source "new" :target "old"}]}
                     {:entity-name :binding :entity-id "<uuid>"
                      :change :modified :slot-name "port"
                      :fields [{:field "value" :source "9090" :target "8080"}]}]}]}

Bindings / fn-slots / list-items are grouped under the fn that owns them (list-items chain through their binding); slot names and fn-typed ref values (ref-fn-id, type-override-fn-id, …) are resolved to names batch-wise. One-sided entries carry a :preview string instead of :fields. The JSON API keeps serving the flat v1 shape above.

Conflict resolution shape

The merge endpoint’s conflict-resolutions is an array (JSON can’t key by [entity-name entity-id]):

[
  {"entity-name": "fn", "entity-id": "<uuid>", "choice": "source"},
  {"entity-name": "binding", "entity-id": "<uuid>", "choice": "target"}
]

Coerced to the Clojure-side {[entity-name entity-id] :source|:target} internally. Unknown choices are silently dropped — matches the merge core’s case matcher.

Editor UI

Affordance Where What it does
Branch chip context bar (#gd-ctxbar → #branch-mount, between the view chip and the packages chip) Shows current branch. Inverted style when off main.
Branch popover click chip Branch list + inline create; branches already merged into their base sit under a collapsed “Merged · N” group at the bottom (auto-archived by the merge — a merge source cannot be deleted; clicking one reopens it). Per row: Δ compare, ✅ approve (on proposed rows) and ⇢ merge inline (instant data-tip tooltips), everything administrative under the row’s ⋯ menu with text labels — 📤 propose/withdraw, 📦 Archive / Reopen (fold a finished branch into the Merged group by hand, or bring one back; reopening from the group’s row asks first), ⚙ Protection (require-merge + required-approvals 0…3 segmented control + count-self-approval), ⛨ write-policy (tenancy only), × delete; a 🔒 marks write-policy-protected rows, an accented ⋯ marks a proposed / protected row. Propose/approve/require-merge/required-approvals are all open-core
Compare mode Δ on a branch row (lit on the picked one; click again = exit) THE diff surface (editor-diff-mode.js) — there is no diff modal. Explorer rows badge +/−/± vs the compared branch (namespace headers aggregate counts), changed fn CARDS and their args ring on the canvas — and the diff reads as a GRAPH: fns whose own rows are equal but which inherit a change (an ancestor, a ref target or a type in the diff — the server’s :affected walk over the compiler’s reverse-deps index) carry a dashed CHANGED-INSIDE ring with a ∿ badge that reveals the ancestor in the card (or opens the ref target); a changed value / type / description is written ON the node (there: 2, struck through — also on a placeholder the other branch binds), a rename shows the other name on the card, an arg bound only here rings green; and a REPLACED REF draws the compared branch’s side beside the card as a dashed GHOST SUBTREE (its root and what it composes, read-only, foldable, dashed elbow from the arg) so “this branch of the graph was swapped for that one” is a picture. Each changed Explorer row carries a one-line digest (a: 1 (there 2) · b → :x (there :y); ∿ via <fn> on changed-inside rows; namespaces add ∿n). A Δ vs <branch> · N chip counts the changed fns and marks the mode (visible/total while filtered; its × exits). A LENS BAR under the Explorer kind-chips filters the tree by change type: “only changed” (changed-inside rows included) plus added / modified / only-there / ∿ inside toggles, “substantive only” (hides name/description-only edits), “effects touched only” and “💬 notes” (mark fns whose changes carry anchored review comments) — persisted as graphden.diffLens; any active diff filter dashes the chip and switches its count to visible/total. Selecting a changed fn shows an inspector DIFF PANEL: change marker, per-field old → new entries (client-rendered from /api/branches/:ref/diff-view?against=), an effects-delta chip, 📍 branch-local badge, and per-element 💬 anchored-comment threads inline. Groups whose effect SET differs are annotated “effects: pure here · time there” (full per-branch registry comparison — the registry is branch-scoped; anonymous fns fall back to a structural “effects touched: +x” signal). Fns existing only on the compared branch render as dimmed GHOST ROWS in expanded Explorer groups (click = switch there). The chip menu is the review cockpit — 💬 Review & comments, 📤 propose-current-for-review, ⇢ merge-compared-in. Mode persists across reloads (localStorage). Annotations only — reads/writes stay on the current branch
Review dialog ⋯ menu → 💬 Review & comments (also the compare-mode chip menu) The CONVERSATION surface for a branch, framed source → its base: a collapsible “What changed” summary (same grouped renderer, read-only), a “Verified on " digest (`GET /partials/branch-verification?branch=` — the branch's test statuses and its newest runs, ✓/✗ per run, `traced` when the call tree was captured; evidence of what the author actually executed, not a claim), the general comment thread (anchored orphans get an `[on fn …]` chip), and Suggestions — proposed CHILD branches of the source with a lazy Δ preview + one-click apply (= merge into the proposal), plus "+ Suggest a change" (fork-and-switch)
Conflict modal merge fails with :reason :merge-conflict Per-entity source/target radio, retry merge with :conflict-resolutions
Fn-card ⌛ action per fn-card row-actions Version timeline + per-version (N runs) badge; click a row → inline-expand its executions (lazy fetch); switch button jumps to that version’s branch

Push branches (cross-install review)

A branch is also the unit of CROSS-INSTALL flow: a local (offline) instance pushes a snapshot of its work to the hub as a branch named push/<name> (graphden.cli push → POST /api/import/graph?target=…), and review happens with everything in this document — diff against main, resolve conflicts, merge, with forbid-invalid? and the write-policy applying as usual. Note on slash-named branches (push/<x>): a name with / cannot ride a /api/branches/:ref/* PATH segment — address such branches by their UUID (every :ref accepts one; the editor’s row ops do this automatically via data-branch-id). The convention rests on machinery, not new entities:

Protected branches

A branch may carry a write-policy (nullable text on the :branch identity row, next to owner-id — the creating principal’s stable :user-id, stamped whenever one is bound):

“Write” covers every content mutation ON the branch — the version-plane rows all carry :branch-id, so edits, creates, deletes AND merges INTO the branch hit the same check. Enforcement lives in the tenancy addon’s authorize-writer (violations throw :authz/branch-protected → 403); core stores the fields, serves the API and renders the UI, but without principals the policy is inert — which is why the editor shows the ⛨ / Advanced affordances only under body.gd-tenancy. Flipping a policy (or deleting a protected branch) is itself gated on owner / :manage-grants.

Protected branches: push only via merge

write-policy above answers who may write a branch and is enforced by the tenancy addon. Its sibling require-merge? (nullable boolean on the same :branch identity row) answers a different, open-core question: how the branch may change at all.

Unlike write-policy, this needs no tenancy addon: enforcement lives in VersionedStorage itself (assert-not-merge-protected!, armed per-request by branch_router via *enforce-require-merge?*; merge runs outside that arming, so it is structurally exempt). The editor surfaces it as an always-visible 🔀 toggle on each branch row in the branch popover (dim = off, accented = on), hidden only for a read-only viewer (gd-no-write). Flip it over HTTP with POST /api/branches/:ref/protect {require-merge: true|false}, or at create time with POST /api/branches {require-merge: true}.

Merge invalidation footnote: the post-merge graph-cache invalidation targets the merge’s TARGET ctx. It captures the active router on the request thread (dynamic/per-thread router state does not convey to the raw post-commit thread), so a merge into a NON-main protected branch becomes visible immediately — see merge-post-commit! in app/branches/impls.clj.

Change proposals (review handoff)

require-merge? above forces changes onto a side branch; a proposal is how that side branch is handed to a reviewer. A nullable :review-state on the :branch row (nil ≡ ordinary working branch; "proposed" ≡ its owner submitted it for review into its base-branch-id) carries the async handoff — no separate merge-request entity. The reviewer’s proposal list is simply the branches whose :review-state is "proposed".

Review policy (configurable approvals)

A proposal is reviewed by recording approvals against it and gating the merge on their count — configurable per target branch, GitHub-style.

Policy fields (nullable, on the merge-TARGET :branch row; :required-approvals / :approver-ids default off — but see the :allow-self-approval? default below):

Approvals are :branch-approval rows (one per approval; mirrors :branch-merge): {source-branch-id, target-branch-id, approver-id, content-stamp, created-at}. content-stamp is the source’s content fingerprint (merge.core/branch-content-stamp — count + max version created-at) at approval time; a later edit advances it, so the approval is auto-dismissed as stale (counted only while the stamp matches — GitHub “dismiss stale approvals”). target-branch-id records the branch the approval was AUTHORIZED for (the proposal’s base at approval time); the merge gate counts an approval only when this equals the ACTUAL merge target, so approvals gathered on a proposal off an open decoy branch cannot be redirected to satisfy a merge into a protected one.

The merge gate (merge.core/validate-approval-policy!, called on the live merge path right after the forbid-invalid? gate) counts DISTINCT, non-stale approvals that are bound to the actual merge target (target-branch-id = current branch) and — when the target sets a restrictive :approver-ids — in that allow-list, excluding the author unless self-approval is allowed, and throws :branch/approval-required (409) when short. WHO may approve is enforced when the approval is WRITTEN (approve-proposal! — restrictive approver-ids else target write-policy), and re-verified against target + allow-list at merge time, so a policy that tightened after approvals were gathered isn’t satisfied by a now-unauthorized or wrong-target approval.

HTTP: POST /api/branches/:ref/review-policy {required-approvals, allow-self-approval, approver-ids}; POST|DELETE /api/branches/:ref/approve (record / withdraw the caller’s approval); GET /api/branches/:ref/approvals → {required, have, satisfied, approvers:[{approver-id, counted, reason, stale}]} — each row judged by the merge gate’s own rule (merge.core/approval-rejection), so the author’s own approval under a strict target reads counted: false, reason: "author".

Comments: each proposal carries a review-comment thread — :branch-comment rows ({source-branch-id, author-id, body, created-at, entity-name?, entity-id?}, org-scoped like approvals, cascaded on branch delete). POST|GET|DELETE /api/branches/:ref/comments ({body} to add, optionally {entity-name, entity-id} to ANCHOR the comment to one diffed element — fn / fn-slot / binding / binding-list-item; a half-anchor or unknown kind is a 400. Two caps, both clean 400s: a body over 10 000 chars (:validation-error/comment-too-long) and a branch thread over 500 rows (:validation-error/comment-limit — comments carry no fairness quota and the client downloads the whole thread); {id} to delete — the author’s own only). The editor renders anchored comments as inline threads on their element — in compare mode, under the inspector diff panel of the fn they anchor to (💬); unanchored ones (and orphans, with an [on fn …] chip) as the general thread in the branch’s 💬 Review dialog — the conversation lives next to the change it reviews.

Editor (branch popover, open-core): a ✅ Approve button on proposed rows (with an n/N progress badge), a “N proposals awaiting review” inbox header, and a ⚙ protection menu per row (require-merge / required-approvals / count-self-approval). approver-ids is the only policy field still API/MCP-only (advanced, rarely changed); a partial /review-policy POST (the ⚙ menu) leaves it untouched (:keep patch semantics). Without the tenancy addon there are no principals, so on a solo self-host the flow degrades to “propose → self-approve → merge”. A merged proposal’s review-state clears automatically, dropping it off the review list.

Demo seeder

:exec/demo-branches init-key (in system-{dev,prod}.edn) pre-bakes a small set of branches every startup so the UI has something to demo without manual setup. Idempotent — already-existing branches are left untouched.

Toggle

# enable (default in dev system + local docker via .env)
GRAPHDEN_DEMO_BRANCHES_ENABLED=1

# disable (default in real prod)
GRAPHDEN_DEMO_BRANCHES_ENABLED=      # unset / empty / 0 / false / no / off

Accepts 1 / true / yes / on case-insensitive. The init-key logs [demo-branches] disabled — set GRAPHDEN_DEMO_BRANCHES_ENABLED=1 … when off so the silence isn’t mysterious.

Re-seed

The seeder skips a branch whose :name already exists. To re-seed:

Mutation vocabulary

Each branch declaration has a :mutations vector. Currently shipped:

Adding more is one defmethod of graphden.system.demo-branches/apply-mutation!.

Files

Path What
src/graphden/system/branch_router.clj Per-branch ctx registry + Ring dispatcher + singleton hook
src/graphden/system/branch_router/request.clj What a request asks for — branch ref (header / ?branch=), page-load test, stale-?branch= redirect URL, /livez
src/graphden/system/branch_router/cache.clj Dropping cached entries (invalidate! / invalidate-all!, ref-cache sweep) + the pinned-branches seam
src/graphden/system/branch_router/epoch.clj Graph-epoch validation on ctx fetch + the self-heal; note-graph-epoch-* tails for eager paths
src/graphden/system/branch_router/recheck.clj Re-recording types into a ctx’s own rich-types slice (call-with-ctx-slices, recheck-ctx-types!, ctx-build diagnostics recompute)
resources/packages/web/branch-router/ branch-routing-wrap base-fn (the wrap installed in front of _app-ring-response)
src/graphden/crud/branches.clj Two read-side helpers only: base-storage + resolve-branch-ref (the list / create / delete / merge / diff / conflicts orchestration now lives in graph fn-defs over atomic base-fns)
resources/packages/app/branches/ HTTP fn-defs + impls over the atomic base-fns (:create-branch! / :delete-branch! / :diff-branches / :detect-conflicts / :merge-branch!)
src/graphden/system/demo_branches.clj Idempotent demo seeder + :apply-mutation! multimethod
resources/packages/app/editor/editor-branches.js Branch chip + popover + fetch wrap + conflict-modal overlay chrome & radio/apply lifecycle
resources/packages/app/editor/fns.edn (:_partial-mc-*) POST /partials/merge-conflicts — the conflict-modal card rendered as hiccup (route :partial-merge-conflicts)
resources/packages/app/editor/editor-fn-versions.js ⌛ history popover for fn-card

Subtleties worth knowing

Parent-set edits require a converged fn (gated)

:parent-ids is a :ref-many junction on the IDENTITY row — it is NOT versioned, so a re-parent is visible to EVERY branch the moment it commits, while the re-parent cascade’s binding migration writes version rows on the request branch only. Ungated, a re-parent from a feature branch left every other branch resolving NEW parents over OLD bindings (bindings whose slots fell out of the new inheritance closure silently unbind — prod behaviour changes with no prod-visible edit).

validation/reparent-cross-branch-rej therefore rejects a parent-set change whenever any OTHER branch holds its own live :fn-version / :binding-version / :fn-slot-version rows for this fn (the reject names the diverging branches — merge or delete them first; off-root it additionally points at the root branch as the place to converge). The two allowed shapes are exactly the non-corrupting ones:

Parent-PRESERVING updates and non-versioned storages are unaffected. This is option (b) of the two coherent designs, now DECIDED as the permanent semantic — the alternative (a), versioning the parent-set itself, is rejected (the parent-set defines the slot closure, and the closure is identity; branch-varying closures would re-architect fn-slot/MI/free-args and put version resolution on the compile hot path). Full rationale + the copy-on-write revisit door: ADR-parent-set-identity.md.

:fn-version ≠ “functional behaviour”

Only the :fn row itself is anchored when you make a change to its top-level fields (name, description, return-type, constraint, anonymous-hash, expects-effects). Edits to bindings (values, refs, type-overrides, list items, fn-slot positions) create separate :binding-version / :binding-list-item-version / :fn-slot-version rows; the :fn row’s :fn-version-id is UNCHANGED.

The editor labels this timeline as field versions. Restore copies the historic description, constraint, type/base metadata and expected effects; it leaves names, argument bindings and inherited structure unchanged. The action is disabled when those visible fields already match the effective current branch, including an older equal state or an inherited version.

The Graph changes section also lists bounded transaction groups for the fn row, its fn-slot membership, bindings, and binding list items. Each new version row carries a server-generated change-id; all version rows written in one storage transaction share it. The page groups by that ID, so a binding edit and its related writes appear together. Existing rows without an ID remain separate and are labelled partial history. This section currently shows metadata only; it does not claim to reconstruct an old graph or offer whole-graph restore. The storage read is paginated (maximum 100 groups per page) and checks visibility of the fn and branches before returning metadata.

New graph version rows also carry change-revision: the first graph-epoch number assigned to their transaction under the semantic writer lock. All rows in that transaction share it, and revisions for one graph owner follow commit order. The history feed orders such groups by revision. Older rows without a revision remain visible as incomplete history; their timestamps cannot establish a coherent cross-entity snapshot. A revision by itself also does not reconstruct unversioned parent identities, so the graph restore action is still unavailable.

The historical read resolves a fn and its owned fn-slots, bindings and list items on one branch at a positive revision. It uses one read-only, repeatable-read transaction for the whole view, includes merge records up to that revision, and refuses to invent an exact result when legacy rows lack revision provenance. It also pins readable referenced fns to their historical version IDs. Current namespace, parent and branch topology are labelled as current, because those links are not versioned. Resolver-bound values are redacted. Reads are bounded to 2,000 owned identities and 10,000 historical versions or merge records per query; an oversized graph is refused rather than truncated into a misleading diff (HTTP 413 on the diff route).

GET /api/fns/:fn-id/history/diff?branch-id=<uuid>&from=<revision>&to=<revision> returns a bounded field diff for this owned graph. A deleted binding or list item appears as removed; changed values and references are displayed with short, historically safe labels. The route checks source-disclosure permission inside the same storage snapshot, then returns an incomplete result instead of a fabricated diff when legacy provenance prevents reconstruction. It does not restore state.

Merge records carry the same revision as any conflict-resolution versions written in that merge transaction. Resolution rows receive the same server-owned change identity and author stamp as ordinary graph edits.

Consequence: two :fn-execution rows pointing at the same :fn-version-id can have produced different results if a binding changed in between. The history filter (“show me runs of the current version”) groups by :fn-version-id, so binding-only edits don’t visually split the timeline — they all share one bucket.

The forensic answer to “what exactly was running when this row was produced” is the row’s second anchor, :graph-hash: a SHA-256 over the RESOLVED execution graph at submit time — every fn, slot, fn-slot, binding and list item the run could reach, as the branch saw them (crud.fn-execution.lookup/graph-hash; content only — no version ids, timestamps or descriptions — so the same graph on two branches hashes the same and a prose edit does not split a history). A binding edit anywhere below the root changes it while :fn-version-id stays put. It is stamped on every persisted run (submitted, traced, captured), cached per graph epoch like the free-arg map, and indexed: GET /api/executions?fn-id=X&graph-hash=H narrows the history to the runs of one exact graph, and the Runs tab’s ⌗ chip on each row does the same click-wise. Rows written before the field carry nil and no chip.

Asset overrides are branch-scoped (:resource-override)

:resource-override (an in-DB override of a shipped frontend asset — path → content) IS in entity-config, so it resolves per branch like the fn graph: a fork inherits the parent’s overrides, a merge carries them, and a soft-delete on a branch reverts that path to the classpath baseline on that branch only. It is the first versioned entity that is not part of the fn graph. See PHILOSOPHY § UI as Graph.

Services CAN now run per-branch (:service.branch-id)

:service is still NOT in versioning.storage.resolution/ entity-config — the row is global — but each row carries a :branch-id ref that the reconciler routes against. The production reconciler (graphden.services.reconciler/reconcile- once!) groups enabled services by :branch-id, asks branch-router/ctx-for for each branch’s ExecutionContext, and starts the service against THAT ctx. Same fn-id can run with branch-specific bindings (dev port + prod port live side-by-side).

Open gaps: port allocation is OS-level (two branches binding 8080 fight; the loser records :start-failed-at); cron collision detection across branches isn’t implemented; the running-atom is a single in-process map (no multi-pod coordination beyond the existing advisory locks).

:forbid-invalid? — branch merge policy (error-tolerance Phase 5)

The :branch row carries a nullable boolean :forbid-invalid? (non-versioned entity — a plain column, no version mirror). When set on the merge TARGET, versioning.merge.core/validate-branch-policy! (run inside the live :merge-branch! atomic core after the target switch, and by validate-merge!) refuses the merge while recorded type diagnostics (graphden.types.diagnostics) exist on either the source or the target branch — :merge-protection-violation, 409, message naming the broken fns. The store is DERIVED (in-memory): the gate judges what is recorded, absence = allow. Set at create time via POST /api/branches {forbid-invalid?: true}; no editor UI yet (backend only — the branch popover may expose it later).

:branch-local? — runtime-config that doesn’t propagate on merge

Some fn-defs encode environment-specific runtime config (web- server port, vault path, cron cadence, env-var indirection). For those, an :branch-local? identity-level flag on :fn short-circuits the cross-branch overlay: foreign-branch version rows are dropped from merge-candidates (online + batch paths) so a sticky-local fn version stays scoped to the branch that produced it.

The filter applies to MERGE propagation, NOT to parent-branch INHERITANCE. A branch B that was forked from A (:base-branch- id = A) inherits A’s branch-local fn versions as part of normal inheritance — that’s the user’s choice when they forked B from A. The asymmetry is intentional: merge says “fold sibling’s history in”, inheritance says “I’m a child of this branch, give me its state”. Branch-local blocks the first but not the second.

The flag is monotonic-OR over :parent-ids: any ancestor true ⇒ effective true forever. Sync-time type-check rejects descendant :branch-local? false when an ancestor is true (mirror of the :required widening guard).

Seeded defaults: :http-server, :secret-leaf, :schedule, :interval, :env. NOT seeded: :pg-query (admins may want portable queries), :future (transitively reaches :schedule).

Implementation:

Merge audit log

POST /api/branches/:ref/merge returns the merge record plus a :skipped block enumerating entities the resolver kept scoped to their origin branch:

{
  "ok": true,
  "merge": { /* :branch-merge row */ },
  "skipped": {
    "branch-local": [
      {"entity-name": "fn", "entity-id": "uuid…", "fn-name": "my-server"}
    ]
  },
  "merged-first": [{"id": "uuid…", "name": "feature-base"}],
  "review-state-cleared": true
}

merged-first lists the branches the target lacked that were merged in before the source (a stacked or cross-base merge — see § Known gaps, transitive merge); [] for a fork off the target or a sibling.

review-state-cleared reports stage 2b — whether the merged proposal’s review-state marker was cleared. false means the clear was refused (the source is protected and the merger may not write it; the merge itself is committed regardless): the proposal stays in the review inbox until someone who may write the source withdraws it. It is reported in the envelope rather than logged because the merge handler runs inside the cloud’s request-level effect gate, where a log line (:io) would itself fail the request.

The shape is forward-compatible: new categories (:conflict-deferred, :protected-by-trait) can land alongside :branch-local without breaking existing consumers. The editor’s post-merge alert summarises the skipped count; the inspector diff panel keeps its inline 📍 badge on the same rows.

Known gaps and non-obvious invariants