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.
The bare VersionedStorage decorator already knew how to:
branch.base_branch_id → branch.base_branch_id → …),branch_merge records.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
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 and B both edit X; A merges
first; B’s merge is asked about X, with A’s version as the
target side — it does not silently replace it. The same holds in the
sync direction: syncing main into feat asks about what main
took from a sibling if feat edited it too.feat already follows main live, so the merge record
adds no view; what a sync does is ask about the entities BOTH sides
edited since the fork (or the last sync) and let you keep yours or
take the base’s, then advance the fork point so the next sync asks
only about newer edits. After the sync feat keeps following main
for everything else — it does not freeze at the sync-time state.
Taking the base’s side in a conflict writes that value as feat’s own
row: from then on feat has touched the entity and a later change on
main to it is a conflict again, not a silent update.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.
:exec/branch-router init-key runs after :exec/compiled-registry,
so main’s registry is already populated.{branch-id → {:ctx :handler :built-at}}). Reuses the existing
base-ctx — no extra compile pass for main.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.build-and-cache!:
ExecutionContext with
(VersionedStorage. base-storage branch-id) and FRESH atoms for
:compiled-registry, :graph-cache, :compile-deps.cr/rebuild! — full compile pass against the branch’s
resolved view.(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.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.
default-max-cached-branches, default 16; tune per deployment
via GRAPHDEN_MAX_CACHED_BRANCHES); a cached entry idle for 15 min
(*ctx-idle-ttl-ms*) is dropped on the next request’s sweep and
rebuilt when its branch is next used. Adding a branch beyond the cap
evicts the least-recently-used non-default entry, so a multi-tenant pod
churning through many branches keeps a bounded working set.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.
Per request:
X-Graphden-Branch: <name> header (wins)?branch=<name> URL query param (URL-decoded)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:
?branch= is the shareable truth,Switching branches mutates BOTH localStorage and the URL, then
calls location.reload() — the simplest “invalidate every cached
view” strategy.
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) |
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
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.
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.
| 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 |
| 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 |
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:
owner-id and the owner write-policy, so only its author updates it;?prune=true —
deletions travel);hub/main
(graphden.cli pull), merged with the same local merge flow;GRAPHDEN_HUB_URL +
GRAPHDEN_HUB_TOKEN set on the local instance, the branch popover’s
Hub section drives POST /api/sync/push / POST /api/sync/pull
(registry package; GET /api/sync/status is the reveal probe). The
hub coordinates are server config only — never caller-supplied, so
the instance’s hub bearer can’t be pointed at an attacker’s host;branch-local? fns (ports, cron, vault paths) never propagate through
the merge, so local runtime wiring can’t leak into the hub’s main —
exactly the same guarantee in-instance branches already have.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):
nil / "open" — anyone the ordinary namespace grants admit
(the default; behaviour unchanged)."owner" — only the branch owner writes; the org’s
:manage-grants holders (and the org owner, via owner-implies-all)
pass too, so a departed owner can’t fossilize a branch."admins" — :manage-grants holders only.“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.
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.
nil / false — direct writes allowed (the default; unchanged).true — the branch accepts changes only via merge, the
GitHub-style “push only via merge requests” toggle. Any DIRECT
content mutation (create / update / delete of a versioned graph
entity through the editor, /api/entities/*, or the MCP upsert
path) is refused with :branch/merge-required → 409 and the
message “This branch accepts changes only via merge…”. A merge
into the branch is exempt — that is the entire point — so the flow
becomes: work on a child branch, then merge it in.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!inapp/branches/impls.clj.
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".
POST /api/branches/:ref/propose {proposed: true|false}
(body absent ≡ true); the state is surfaced by as-json-branch and in
GET /api/branches.set-review-state! (app/branches/impls.clj).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):
:required-approvals (int) — how many valid approvals a proposal needs
before a merge INTO this branch is allowed.:allow-self-approval? (bool) — DEFAULT (nil) is TRUE: the proposal
author’s own approval counts, so a solo user / small team isn’t locked
out. Set it explicitly false for genuine four-eyes review — then the
author’s own approval does not count (GitHub “require review from someone
else”). (merge.core/self-approval-allowed? is the single source of the
nil→true default, shared by the gate and the status projection.):approver-ids (jsonb list of :user-id) — an explicit reviewer
allow-list. When non-empty it is RESTRICTIVE, not additive: ONLY
those users (∪ org-admins, as an escalation unlock) may approve —
regardless of :write-policy. This is GitHub’s “require review from
these users”, and the whole point of naming reviewers: an ADDITIVE list
OR’d with the ⚙-menu’s open write-policy default restricted no one, so a
named-reviewer requirement was silently a no-op. With :approver-ids
empty, “who may approve” falls back to the target’s :write-policy
roles (owner / org-admins / open).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.
: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.
# 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.
The seeder skips a branch whose :name already exists. To re-seed:
DELETE /api/branches/<name>, then restart the pod.bb deploy (clean DB) — sync re-runs, branches reappear.Each branch declaration has a :mutations vector. Currently
shipped:
:update-fn-description — set the fn’s :description on this
branch. Looks the fn up by :fn-name.:create-fn — create a composed fn (:parent-based, optional
:description, no bindings yet). Names the new fn via :name.Adding more is one defmethod of
graphden.system.demo-branches/apply-mutation!.
| 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 |
: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:
:base-branch-id nil), every other branch converged
on this fn;tutorial-* scratch branch, then assign its parent).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.
: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.
: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).
:service via the editor’s ⚙ popover offers a
branch picker (default = the editor’s current branch). The
reconciler picks up the row immediately and starts it inside
the chosen branch’s ctx.recon/restart-services-depending-on!);
a merge does the same for its target, seeded by the merged fn-ids
(:merge-post-commit!), so post-merge cron loops pick up the fresh
closures. The branch-WIDE restart-services-on-branch! is reserved
for branch delete — on the cloud every org’s main is the shared
main, so a branch-wide restart on merge bounced the platform’s own
web-server.:branch-id fall back to the reconciler’s
base ctx (= main behavior), so the migration is transparent.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 mergeSome 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:
graphden.versioning.branch-local
(effective-branch-local?, and branch-local-seed over an
already-loaded fn map). The cache is cleared by VersionedStorage
after every :fn write, and on the cross-pod fn:invalidate NOTIFY /
graph-epoch heal.versioning.storage.resolution/merge-
candidates(-from-cache) drops foreign-branch candidates when
effective-branch-local? is true for the fn-id; resolve-
version’s parent-branch recursion is also gated.types.check/check-branch-local-monotonicity!
throws :types/branch-local-widening-forbidden on widening.branch-local/branch-local-seed, server-side). On an editable root
card it is a TOGGLE (editor-edit-modes-flags.js): “merges across
branches” (dimmed) ↔ “branch-local”; under a sticky-local ancestor it
is read-only and names the seed. The write goes through
PUT /api/entities/fn/:id with branch-local=true|false
(parse-fn-from-form), and crud.validation/branch-local-rej
refuses false under a true ancestor
(:constraint-violation/branch-local-widening) — the write-time
twin of the sync-time guard. 📍 badge + dimmed rows in the
inspector diff panel and the Review dialog’s change list.:skipped-as-branch-local list with
entity-ids (see “Merge audit log” below) so API consumers can
see what didn’t propagate.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.
The rich-types registry is branch-scoped via per-ctx slices. The default branch
keeps the boot-populated global atom; every other branch ctx forks a
private copy at build (registry-core/fork-rich-types-atom, seeded
from its base’s view) and both the ctx BUILD and every dispatched
request bind it as *rich-types-override* — so /api/types,
type-check writes and effect-gate lookups all answer per branch
(covered by rich-types-registry-branch-scope-test). The
per-ORG rich-types cousin (per-org-rich-types) is branch-scoped the
same way : branch ctxs fork it at build
(fork-per-org-rich-atom) and every bind site pairs the two
overrides, so a tenant’s same-named fns on two branches keep separate
per-org name indexes (per-org-rich-slice-is-branch-scoped-test).
A merge’s targeted type recheck is asynchronous and shares recovery
admission with startup sweeps. Its terminal log receipt distinguishes
admission delay, checker diagnostics, missing entries, cancellation and
exceptions. :status :checked means the pass completed; inspect
:outcome as well, since an old rich entry can remain present after a
failed check. Presence alone does not prove a fresh publication.
S.base = R, R edited) used to be refused
with :merge/inherited-content-not-transferable and a plan to click
through. merge.core/merge-transitively! — behind both the merge
handler and safe-merge-branch! — now runs that plan itself: the
branches the target lacks (inherited-merge-plan, root-most first) are
merged in first, each through the same policy gates a direct merge of
that branch would face (:forbid-invalid?, required approvals,
protected transfers), then the source. The response carries
merged-first ([{id name} …]); a step that conflicts or is refused
throws its own error with :step and :merged-first, the steps before
it stay committed, and re-running the merge with the conflict resolved
continues from there. The storage layer’s refusal remains as the guard
for a caller that reaches storage.merge/merge-branch! directly.
(Re-merging the SAME source is also safe: a re-merge carries only the
source’s changes SINCE the prior merge, so an unchanged re-merge cannot
revert a target edit made in between — merge-candidates-from-cache’s
per-source eligible window, regression-tested by
re-merge-does-not-silently-revert-target-edit.)resolution/winning-candidates’ :effective-ts): a
row a merge landed on the target after the fork is the target’s
change. Before 2026-09-25 the target was scanned for its OWN version
rows only, so the second of two siblings editing the same entity merged
with no conflict and silently replaced the first’s landed edit; and a
base → feature sync surfaced the base’s rows with the merge’s timestamp,
freezing the synced entities on the feature (while untouched ones kept
following the base) and reverting the feature’s own older edit to the
base’s pre-fork row. A merge whose source is an ancestor of the target
now surfaces nothing (the chain walk shows the ancestor live); what it
keeps is its resolutions and the fork point. merge-semantics-test.
The approval stamp (branch-content-stamp) counts merges INTO the
proposal for the same reason — content can reach it that way too.default-max-cached-branches = 16,
evict-lru-if-full keyed on :last-used); tune via the
GRAPHDEN_MAX_CACHED_BRANCHES env var (read by :exec/branch-router
into create-router’s :max-size). A branch with a running service is
pinned (the reconciler’s set-pinned-branches-fn!): the cap, the idle
sweep and the epoch heal all leave its ctx in place (the heal refreshes
it), so the cache may exceed the cap by the number of such branches.resolve-branch-id re-reads AFTER its ref-cache write (one extra read
per cache miss only). This closes a TOCTOU: without the recheck, a
branch deleted between the first (uncached) resolution’s DB read and
its cache write leaves the dead id cached, because the delete’s
value-sweep has already run. A delete landing before the recheck is
seen (entry dropped, nil/new id returned); one landing after it sees
the now-present entry and sweeps it. Covered by the
ref-cache-toctou-* tests in branch_router_test. The cache holds
only refs that RESOLVED, and a ref that resolved by id is keyed by the
canonical id — UUID/fromString accepts any case mix and short groups,
so keying by the raw text let request input grow it without bound. It
is therefore bounded by the number of branches.?%zz=1) never fails
the request: a malformed key is not branch, a malformed branch
value is taken literally (→ the unknown-branch 400, or a redirect to
the default branch for a page load).:exec/branch-router is unit-tested at
the dispatcher level (branch-router-test: header / query parsing,
default fallback, unknown-ref rejection, invalidate) AND the full
middleware-through-storage path — a request through the wrap into a
per-branch ExecutionContext and back through the branch’s storage view —
is covered end-to-end by
graphden.integration.branches-lifecycle-test: it dispatches through
br/dispatch (the same closure http-kit feeds real /api requests into)
with explicit X-Graphden-Branch headers, creates a branch, writes a :fn
on it, and asserts the isolation split (the fn resolves under the
branch header yet is absent on main), then diffs + merges. The socket
layer itself (http-kit request parsing over TCP) is exercised separately by
the BYO / remote-storage e2e tests and is not a branch-router concern.