# demarkus-library — Debugging & Gotchas Bugs, gotchas, and investigations. Highest-recall file — check here first when something behaves strangely. ## OAuth Basic auth vs the broker: form-urlencode BEFORE Basic-encoding RFC 6749 §2.3.1: token-endpoint Basic credentials are `client_id` and `client_secret` **form-urlencoded first**, then joined and base64'd. The broker enforces this (`client_auth.go` QueryUnescapes both halves after decoding). A naive `req.SetBasicAuth(clientID, secret)` works only while the secret has no reserved characters — a secret containing `:` or `%` silently desyncs and the broker sees a different secret → `401 invalid_client` that looks like a wrong secret in config. The library client escapes both halves (`oauth.Client.setBasicAuth`), and the test secret deliberately contains `:` and `%` to pin it. ## Broker refresh does not rotate refresh tokens Refresh responses omit `refresh_token` (omitempty). If client code treats an empty `refresh_token` in the response as "clear the stored one", every session dies on first refresh. `session.Manager` only overwrites when non-empty. ## Broker invalid_grant on token exchange does not consume the code on client errors Wrong client_id / redirect_uri / verifier keep the code redeemable for the 60-second window (broker's keep-code-on-client-error semantics) — retrying a misconfigured exchange can still succeed after a config fix within the window. But a *consumed* or expired code is permanently `invalid_grant` → fresh login. ## 429s on page reads behind the broker: stateless MCP client × rate limiter First live e2e (2026-06-11): login fine, page reads 429'd. Cause: the broker MCP gateway runs every HTTP request through the per-subject limiter (`rateLimit.tokens`, chart defaults 10/min burst 5), and the library's stateless-per-call gateway makes **~3 requests per read** (initialize → notifications/initialized → tools/call). Two page loads exhausted the burst. Deploy mitigation: broker AppSet values raised to 60/min burst 30 (fix/broker-rate-limit-web). Real fix is library-side: reuse the MCP session across reads (pooled client keyed by reader session, header-from-ctx bearer) — cuts request volume 3x and drops the initialize round trip from page latency. Then the broker limit can come back down. ## demarkus modules are not go-gettable — CI needs a sibling clone (2026-06-12) CI typecheck failure: `replacement directory ../demarkus/client does not exist`. Root cause is deeper than the missing dir: demarkus's modules declare `module github.com/latebit/demarkus/{client,protocol}` but the repo lives at `github.com/latebit-io/demarkus` — the proxy/`go get` path 404s, so the replace directives aren't a Phase-0 convenience, they're load-bearing. Any consumer outside the demarkus monorepo must materialize the source tree at `../demarkus`. Fix in both workflows: `git clone --depth 1 https://github.com/latebit-io/demarkus "$GITHUB_WORKSPACE/../demarkus"` before any Go step (lint, test, goreleaser). Plain `git clone`, not actions/checkout — checkout refuses paths outside the workspace. Clone lands outside the repo so goreleaser's dirty-tree check stays clean. Floats on demarkus main, same as the local sibling layout. Real fix someday: rename demarkus module paths to `latebit-io` (breaking, touches every import) or vendor. ## Federation agent → root hub publishes are unauthorized: token mismatch (2026-06-14) Floor-edges rollout surfaced it (first consumer that NEEDS hub publishes to work): the demarkus-agent's publishes to the `root` hub return `unauthorized` — BOTH the hash index (`/index/.md`) AND the new graph export (`/graph.md`). So it is NOT the floor feature; it predates it and the hash index has been failing silently (nothing consumed it). Diagnosis (no secret values leaked — compared hashes only): - root enforces its admin token as a stored **hash**: `root-tokens` secret (ns root) → `tokens.toml` → `[tokens.admin] hash = "sha256-bb7a07…"`, `operations=["publish"]`, `paths=["/**"]` (so `/graph.md` IS in scope). - the agent SENDS a raw token from `demarkus-agent-hub-tokens` (ns demarkus-agent), ESO-materialized from `root-token-values` (ClusterSecretStore `in-cluster-root`), keyed `["root.root.svc.cluster.local:6309"]` — host key matches the agent's `hubs` address, so the token IS sent. - `sha256(agent_raw_token) != root stored hash` (tested as-is/strip/±newline — none match). **The two secrets hold DIFFERENT tokens.** `root-token-values` (raw, → agent) was never the preimage of `root-tokens` (hash, ← server). Both secrets are install-vintage (2026-06-01); the 06-13 root StatefulSet orphan-recreate preserved the PVC, so it did not rotate anything — the mismatch has existed since install. Fix (operational, sensitive — do NOT auto-rotate prod auth): set `root-token-values` (the OpenBao/in-cluster-root source) to the RAW admin token whose sha256 is root's stored hash. The server only keeps the hash, so the raw value must come from where it was generated (the world chart bootstrap that wrote root's tokens.toml). If the raw is lost, rotate as a set: choose a new admin token, update root's `tokens.toml` hash (root-tokens) AND `root-token-values` raw together, restart root + agent. Verify with the hash-compare snippet (sha256(raw) == stored "sha256-…"). Until fixed: the floor degrades to the per-pod observed-links map (works, just sparse) — DEMARKUS_HUB=root reads a `/graph.md` that 404s, so no durable edges. The library side (0.1.9, DEMARKUS_HUB=root) and agent side (0.12.43, --publish-graph) are both correctly deployed; only the token blocks it. ### ↑ root cause of that token mismatch: root-tokens has two writers (2026-06-14) Traced `root-token-values`'s source and why it diverged from `root-tokens`: **Sourcing chain (no OpenBao for this one):** `root-token-values` is a plain K8s Secret in ns `root` (key `admin` = raw token), emitted by the **demarkus-server chart** (`deploy/helm/demarkus-server/templates/tokens.yaml`, gated on `tokens.emitRawValues`). The raw comes from `resolveAdminToken` (_helpers.tpl): explicit `.Values.tokens.admin.token` → else lookup the existing values Secret → else `randAlphaNum 64`. The same `$rawToken` is hashed into `root-tokens` (`[tokens.admin] hash`, the file the server mounts + enforces) — so within ONE render they always agree. ESO `in-cluster-root` (kubernetes provider, `remoteNamespace: root`, SA `agent-token-reader`) copies `root-token-values.admin` → the agent's `tokens.toml`. **Why they diverged:** `root-tokens` managedFields list TWO writers — `demarkus-broker@2026-06-03` and `argocd-controller@2026-06-13` — while `root-token-values` is argocd-only. The broker persists into `root-tokens`, and the 06-13 orphan-recreate had ArgoCD server-side-apply re-apply it; the enforced admin hash changed but the agent-facing raw (`root-token-values`, untouched since 06-01 15:54) did not. Hash storage is one-way, so the chart can't re-derive the raw to keep them in sync — the mismatch is silent. **Fix (prod auth — operator executes):** - *Minimal/unblock now:* set `root-tokens` `[tokens.admin] hash = sha256-` (keep paths `["/**"]` + operations `["publish"]` and any other token sections), then restart root-0 to reload the mounted tokens.toml. Makes the agent's existing token valid — no agent/ ESO change. Risk: the broker/argocd co-writer can re-diverge. - *Durable:* pin the world chart's `tokens.admin.token` to ONE managed secret value so hash+raw always derive from a single source (kills the randAlphaNum fallback), and settle who owns `root-tokens` (chart intends the broker as sole post-install writer, but ArgoCD SSA is contending — reconcile the field-manager / resource-policy so SSA stops rewriting the broker's tokens). - Verify either way: `sha256(root-token-values.admin) == root-tokens admin hash`, then watch agent logs for `publish-graph: complete` and confirm `root/graph.md` exists → floor edges light up. ### ArgoCD prunes a chart-tracked Secret when the chart stops rendering it — `helm.sh/resource-policy: keep` does NOT save it (2026-06-14) Rolling demarkus-server 0.17.18→0.17.19 (the token-bootstrap-Job change that stops templating the token Secrets) DELETED `root-tokens`/`root-token-values` and `world-a-*` — both world pods stuck ContainerCreating on the missing token mount. Root cause: those Secrets were originally helm-templated, so ArgoCD TRACKED them; when 0.17.19 no longer rendered them, ArgoCD pruned them. **ArgoCD does not honor the helm `helm.sh/resource-policy: keep` annotation** (that's a helm-only hint; ArgoCD wants `argocd.argoproj.io/sync-options: Prune=false` / `Delete=false`). My pre-merge assumption that `keep` would protect them was wrong. Ordering made it worse: the PreSync bootstrap Job ran BEFORE the prune, saw the Secret still present → no-op'd → then the sync pruned. ArgoCD then read "Synced", so it would not re-fire the PreSync Job on its own → deadlock (pods down, no Job to recreate the Secret). Recovery (POC, prod unused): manually created a consistent pair per world (64-char token, tokens.toml `[tokens.admin] hash=sha256(token) paths=["/**"] operations=["publish"]` + token-values `admin=`), verified sha256(raw)==hash, pods came Ready, restarted broker (re-provisions its `broker-write-` entry) + agent + forced the ESO refresh, restarted the agent again so it loaded the synced token (agent loads tokens ONCE at start — ordering vs ESO matters). Agent then logged `publish: complete` AND `publish-graph: complete`. The manual Secrets are kubectl-created → untracked by ArgoCD → never pruned; the bootstrap Job no-ops on them. Steady state is now exactly the design's intent — the prune pain was a ONE-TIME tracked→untracked transition. Lesson for the next chart that hands a resource off to runtime owners: the tracked→untracked transition needs a migration step — either pre-delete from ArgoCD's tracking with `Prune=false`/an ignore, or accept a one-time recreate. Fresh installs are clean (the Job creates untracked Secrets from the start). ## External federation blocked by cluster UDP/QUIC egress (not a library bug) (2026-06-14) Clicking the floor's `soul.demarkus.io` portal → library 502 "reading room is unreachable". Cause is cluster networking, NOT the trail URL or the library: - Library log: `read failed world=soul.demarkus.io path=/ err="dial soul.demarkus.io:6309: timeout: no recent network activity"` — it parsed the trail (`/t/u/~/soul.demarkus.io/d/`), routed to a federated read, dialed soul, and the QUIC/UDP handshake never completed. (A bad URL would 400/404, not a 502 timeout — the timeout proves federation engaged.) - Reproduced with the BARE fetch client, no library: `demarkus-agent crawl --seeds mark://soul.demarkus.io --insecure` from an in-cluster pod → identical `dial soul.demarkus.io:6309: timeout`. So it's not URL/library. - soul.demarkus.io is public and reachable from outside (used all session). - Config layers all permissive: federation on; library NetworkPolicy egress allows UDP 6309 to ALL; Cloud NAT `demarkus-net-nat` = all subnets, all protocols; no egress-deny firewall rules / firewall policies. Nodes have no external IP (private GKE cluster → egress via Cloud NAT). Conclusion: outbound UDP/QUIC to the public internet doesn't traverse from this private cluster despite permissive visible config — a GKE/VPC infra issue (Cloud NAT UDP behavior, an org/Shared-VPC constraint, or MTU/QUIC), to chase infra-side. In-cluster federation (world↔world UDP 6309) + the whole floor feature work; only reaching EXTERNAL public worlds fails. The portal is honest either way ("this host is linked from here"); the network path is the gap. ### ↑ CORRECTION: external UDP/QUIC egress DOES work — soul is just residential-hosted (2026-06-14) The above "cluster UDP egress blocked" conclusion was wrong. Probing a second public world from the cluster: `demarkus-agent crawl --seeds mark://docs.demarkus.io` → **14 docs, 0 errors, 4.3s**. So the cluster reaches external public worlds over QUIC fine; the floor's external portals work. soul is the exception, and DNS explains it (identical from cluster + laptop): - docs.demarkus.io → 209.38.174.226 (DigitalOcean / cloud) — reachable. - soul.demarkus.io → 70.53.56.221 (a residential IP — the self-hosted soul). The cluster's QUIC to the residential 70.53.56.221:6309 is dropped by the home network (NAT/firewall not accepting inbound from a cloud egress IP); a laptop on/near that network reaches it. Nothing in library/floor/cluster-egress is broken. For a live external-portal demo, link a CLOUD-hosted public world (docs.demarkus.io) — it renders AND resolves. soul-as-portal only resolves from networks its home firewall admits. ### ↑ RESOLVED: soul reachable from the cluster after a home-network fix (2026-06-14) Fritz adjusted the soul's home network/firewall. Re-probe from the cluster: `demarkus-agent crawl --seeds mark://soul.demarkus.io` → **101 docs, 0 errors, 13s** (was a 25s timeout). The cluster's QUIC now reaches 70.53.56.221:6309, so the floor's soul portal resolves and renders soul's content. Confirms the whole chain: the only blocker was ever the soul's residential ingress, never the library/floor/cluster-egress. External federation to public worlds (cloud or now-reachable self-hosted) works end to end. ## Reader overlay coupled to focus — a presentation lens must use orthogonal URL state (2026-06-15) R4 reader mode (the `?reader=` focus overlay). The original codec decision had `parseTrail` set `Focus := reader` so the overlay could reuse the focused pane's already-rendered live document. Symptom in live use: in a two-column trail, opening reader on the LEFT (non-focused) doc re-focused it — collapsing the right pane to a spine. The overlay was mutating the canvas behind it. Root cause: a *presentation lens* was coupled to *navigation/layout state* ("reuse the focused thing" leaked the coupling). The single-live-read invariant I thought I was protecting was never at risk — EVERY pane is already read in the trail handler loop (focused live, the rest `ReadCached`), so the overlay can address ANY pane for free by capturing the doc at `i == t.Reader`. Fix (PR #26, 0.1.16): reader orthogonal to focus. `parseTrail` doesn't touch Focus; overlay built from the reader pane's loop-fetched doc; margin guard `(focused || reader)`; `trailReaderURL` preserves a non-default `focus=` alongside `reader=`; close = `trailURL(t)` (keeps focus). Rule: **when a feature is pure presentation, its URL state must be orthogonal to the state that drives layout — don't reuse the "convenient" already-rendered object, or you inherit its coupling.** Bonus gotcha (smoke): the fix looked broken in a curl smoke because a stale server held the reused port (`bind: address already in use` in the log) and served the OLD binary. Always `lsof -ti :PORT | xargs kill -9` and confirm the new process bound before trusting a local smoke. ## Universe floor empty/portals-only for some logins — read-discovery was gated by the WRITE allowlist (2026-06-15) Symptom: the universe floor showed "just a straight line to each library" (all nodes dashed portals, no world satellites) for one login but the full floor for another. Reads of individual docs/maps worked fine for the broken login. Root cause: the broker's `mark_worlds` tool (which the floor enumerates to draw worlds) filtered by `authorizedWorlds` → `worldAllows(WorldConfig.Allow, claims)`. But **`WorldConfig.Allow` is the WRITER allowlist** (the MCP write gate uses the same predicate), and the deploy chart sets every world's `allow.emails` to the **admin** list. Actual reads (fetch/lookup/list) check NO Allow — only the broker SSO org gate — so a valid non-admin login could read docs but `mark_worlds` returned **zero worlds**. With no real worlds, the floor fell back to drawing the hub `graph.md` edge endpoints as portals → the straight line. Signature: zero `.floor-world` nodes, only `.floor-portal-node`, no satellites, worlds shown by raw cluster address. A 429/rate-limit makes mark_worlds *error* (→ "unreachable"); **zero worlds is an authorization result, not a transport error** — that distinction is the key to telling them apart. Fix: broker — list `readableWorlds` (all worlds, SSO-gated) in `mark_worlds`, decoupled from the writer `Allow` (broker 0.1.38). Library defense-in-depth — render the empty-state and skip topology enrichment when zero worlds, so an unauthorized identity isn't leaked world names + internal DNS (library 0.1.19). Lessons: - **A read-discovery list gated by a write predicate is a trap.** If reads are open but *discovery* (list/enumerate) reuses the write/admin allowlist, non-writers get an empty—but-not-erroring view. Keep read-discovery and write authz on separate predicates. - **"Works for me, broken for them" + you changed account AND machine = a confound.** Isolate one variable (same machine, swap account) before theorizing about proxies/caches. We burned several turns on a corporate-proxy theory (the injected `browsing-topics` Permissions-Policy header was a real but irrelevant proxy fingerprint) before the rendered HTML showed zero worlds. - **Get the actual rendered output early.** One paste of the floor SVG ended the guessing instantly. - The deployed broker config (a Secret) had per-world `allow.emails` that `deployment.yaml`'s `worlds:` block didn't show — the chart injects it. When config and intent diverge, read the *running* config (the Secret), not just the source yaml. ## Hover shifts the page down — global htmx:afterSettle hook (2026-07-03) "Hovering a link shifts the page down" was NOT the preview card's CSS (the upward-opening card fix was correct for what it fixed). It was islands.js: a global `htmx:afterSettle` listener ran `showFocusedPane()` after EVERY swap — and a hover preview, a palette keystroke, and a librarian exchange are all swaps. Worse, `scrollIntoView(block:"nearest")` on a pane taller than the viewport aligns its top with the viewport top, scrolling the page down past the nav. Rules of thumb: - A body-level `htmx:afterSettle`/`afterSwap` hook fires for every fragment and extension swap on the page — gate it by swap target (does the settled subtree contain what you care about?) or every new htmx feature silently inherits the side effect. - `scrollIntoView` is two-axis; if the intent is one axis (canvas x), adjust the scroller's `scrollLeft` from bounding rects instead. - When "hover moves the page", grep the JS event hooks before blaming CSS overflow — abspos display toggles can't shift layout; scripts can. ## Related documents - [Reader mode plan](/demarkus-library/plans/reader-mode.md): R4 reader overlay whose focus coupling is debugged above - [ADR 0004 broker web SSO](/demarkus-library/adr/0004-broker-web-sso.md): OAuth flow behind the Basic auth and refresh gotchas - [Journal 2026-06-14](/demarkus-library/journal/2026-06-14.md): session where the token mismatch and egress items were traced - [Journal 2026-06-15](/demarkus-library/journal/2026-06-15.md): session for the reader overlay and floor allowlist fixes ## Pinned editions became "referenced by" entries (2026-08-18) The margin's referenced-by block on `/demarkus-library/plans/reading-room.md` listed real sources interleaved with runs of bare `v1`, `v2`, `v12` ... `v26`. The soul contained no links to version paths: a scan of all 195 documents, the published `/graph.md`, and the local graph store all came back clean. The entries were minted by the library itself. Cause: the document route is a catch-all, so `/w//d/.md/v17` is a valid document URL and the demarkus server really does serve that edition. The pane rendered it as an ordinary document and then fed the observed-links map, recording `/…/reading-room.md/v17` as an edge source. Old editions carry the same links as the current document, so every edition anyone opened became a permanent backlink. The labels read as bare `vN` because `refTitle` names a source by its last path segment. The guards at both render paths already excluded listings and tag pages, with comments saying only real documents are edge sources. Editions had simply never been considered. Fixed in #66 (library 0.23.2) with `domain.IsVersionPath` beside `IsListingPath`, excluded at both renderers. An edition still renders in full; it just never becomes an edge. The predicate requires the parent segment to end in `.md`, so a document genuinely named `/notes/v2` stays a document. Notes for next time: - A catch-all route makes a version path indistinguishable from a document path. Any code that treats "not a listing" as "is a document" has this hole. - The observed-links map is per-pod and in-memory, so the deploy that shipped the fix also cleared the entries already accumulated. There was nothing to migrate. - When verifying a mutation-based test (remove the guard, expect a failure), assert the mutation actually applied. Mine silently missed after gofmt rewrapped the condition, and the test passed for the wrong reason. ## SVG paint server inside a hidden overlay (2026-10-09) Symptom: `fill: url(#ganglion)` painted on the inline map page but left aggregate circles empty inside the map overlay. Cause: every SVG carried its own ``, ids resolve document-wide to the first match, and the first match sat in the `hidden` graph overlay; Chrome does not paint a `` whose ancestor is `display:none`. Fix: a single always-rendered `svg.svg-defs` block in the `nav` template holds every shared marker and pattern. Rule: never put shared `` in fragments that can land inside a hidden container. ## 2026-10-13 — company room lost its branding after library 0.38.0 Symptom: custom styling gone on library.knowledge.demarkus.io after the 0.38.0 rollout. Not a library bug. The room is branded from hub-world documents (`root:/.well-known/library/`, [ADR 0008](/demarkus-library/adr/0008-branding-layers.md) amendment), never from a ConfigMap on this deploy (no ReplicaSet since 0.28.0 carried branding env or volumes). The knowledge system was restarted from genesis on 2026-10-05 with the commit-log store; the branding docs published 2026-09-23 on root, latebit, ontehfritz, music were never republished, and root's `/index.md` is missing too. No PVC snapshots exist any more, so the originals are gone. Triage order that worked: live page head links and `/theme/*` statuses → pod env and volumes across ReplicaSet revisions → hub docs via the broker → world listing → hub index text. Check the world before the library when branding vanishes. Correction, same day: the cluster inspected above was the latebit knowledge system, not the company deploy. The company bug is issue #90: cold pods and the sign-in page read the private hub without a bearer, so the hub stylesheet 404s per pod until a signed-in render lands there, and an anonymous failure is cached as absence for a TTL. Fixed on `fix/hub-branding-cold-pod`; see ADR 0008's 2026-10-13 amendment. Lesson: confirm which deploy the report is about before reading infrastructure. ## Listing links dead behind a proxy: `//` in trail URLs (2026-10-14) - Symptom: company deployment, open world card → `/` listing; clicking its links does nothing. Local build fine. - Cause: listing chunks end in `/`, so `/~/` joins minted `d//~/`. A slash-merging proxy sends `d/~/` → 400; `hx-status:4xx swap:none` makes the 400 invisible. - Fix: [ADR 0011](/demarkus-library/adr/0011-trail-listing-separator.md) — `~~/` after slash-ending chunks; parse at segment level, legacy `//~/` still accepted. - Lesson: "click does nothing" in the room = check for a swallowed 4xx first. Never mint `//` in a URL.