# 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).