Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Copy buttons on published code blocks, and one-click Cursor and Claude links from mcp expose (#9564)

Garry Tanc143a9b177e3
diff --git a/.gstack/pregate.json b/.gstack/pregate.json
index 38d86f8217..f133cbcd66 100644
--- a/.gstack/pregate.json
+++ b/.gstack/pregate.json
@@ -1,5 +1,8 @@
{
"dependencies": {
+ "admin/e2e/publish-copy-button.pw.ts": [
+ "test/publish.test.ts"
+ ],
"test/**/*.serial.test.ts": [
"test/scripts/serial-files.test.ts"
],
diff --git a/admin/e2e/publish-copy-button.pw.ts b/admin/e2e/publish-copy-button.pw.ts
new file mode 100644
index 0000000000..8364cf94cb
--- /dev/null
+++ b/admin/e2e/publish-copy-button.pw.ts
@@ -0,0 +1,111 @@
+import { test, expect, type Page } from '@playwright/test';
+import { generateHtml, encryptContent } from '../../src/commands/publish.ts';
+
+// gbrain publish pages render their markdown in the browser. Each fenced code
+// block gets a copy button that puts the block's exact text on the clipboard.
+// These tests run the generated page in Chromium from a localhost origin, so
+// the async Clipboard API is available.
+
+const ORIGIN = 'http://localhost:4817';
+const SHELL = 'gbrain sync --dry-run';
+const PROMPT = [
+ 'Summarise today\'s meetings for alice-example.',
+ ' - keep <angle brackets> & "quotes" exactly',
+ '\tand a tab-indented line',
+].join('\n');
+const MARKDOWN = [
+ '# Notes', '',
+ 'Inline `code` stays plain.', '',
+ '```text', PROMPT, '```', '',
+ '```bash', SHELL, '```', '',
+].join('\n');
+
+async function open(page: Page, html: string) {
+ await page.route(`${ORIGIN}/page.html`, route => route.fulfill({ status: 200, contentType: 'text/html', body: html }));
+ await page.goto(`${ORIGIN}/page.html`);
+}
+
+const clipboard = (page: Page) => page.evaluate(() => navigator.clipboard.readText());
+
+test.use({ permissions: ['clipboard-read', 'clipboard-write'] });
+
+test('every fenced code block gets one copy button that copies its exact text', async ({ page }) => {
+ await open(page, generateHtml({ title: 'Notes', markdown: MARKDOWN }));
+ const buttons = page.getByRole('button', { name: 'Copy code block' });
+ await expect(buttons).toHaveCount(2);
+ await expect(page.locator('p > code')).toHaveCount(1);
+ await expect(page.locator('p button')).toHaveCount(0);
+
+ await buttons.nth(0).click();
+ expect(await clipboard(page)).toBe(PROMPT);
+ await expect(page.getByRole('button', { name: 'Copied' })).toHaveCount(1);
+
+ await page.getByRole('button', { name: 'Copy code block' }).last().click();
+ expect(await clipboard(page)).toBe(SHELL);
+ await expect(page.getByRole('button', { name: 'Copy code block' })).toHaveCount(2, { timeout: 5_000 });
+});
+
+test('the copy button works from the keyboard', async ({ page }) => {
+ await open(page, generateHtml({ title: 'Notes', markdown: MARKDOWN }));
+ const first = page.getByRole('button', { name: 'Copy code block' }).first();
+ await first.focus();
+ await page.keyboard.press('Enter');
+ expect(await clipboard(page)).toBe(PROMPT);
+ await page.evaluate(() => navigator.clipboard.writeText(''));
+ const second = page.getByRole('button', { name: 'Copy code block' }).last();
+ await second.focus();
+ await page.keyboard.press('Space');
+ expect(await clipboard(page)).toBe(SHELL);
+});
+
+test('a password-protected page gets its copy buttons after unlocking', async ({ page }) => {
+ const encrypted = encryptContent(MARKDOWN, 'pw-example');
+ await open(page, generateHtml({ title: 'Locked', markdown: '', encrypted }));
+ await expect(page.getByRole('button', { name: 'Copy code block' })).toHaveCount(0);
+ await page.getByPlaceholder('Enter password').fill('pw-example');
+ await page.getByRole('button', { name: 'Unlock' }).click();
+ const buttons = page.getByRole('button', { name: 'Copy code block' });
+ await expect(buttons).toHaveCount(2);
+ await buttons.first().click();
+ expect(await clipboard(page)).toBe(PROMPT);
+});
+
+test('the sanitizer still has the last word on page content, locked or not', async ({ page }) => {
+ const hostile = [
+ '<img src="x" onerror="window.__hit = 1">',
+ '<script>window.__hit = 2</script>',
+ '<pre><code onclick="window.__hit = 3">raw html block</code></pre>',
+ '<button class="copy-btn" onclick="window.__hit = 4">fake</button>',
+ '', '```', SHELL, '```', '',
+ ].join('\n');
+ for (const encrypted of [null, encryptContent(hostile, 'pw-example')]) {
+ await open(page, generateHtml({ title: 'Hostile', markdown: encrypted ? '' : hostile, encrypted }));
+ if (encrypted) {
+ await page.getByPlaceholder('Enter password').fill('pw-example');
+ await page.getByRole('button', { name: 'Unlock' }).click();
+ }
+ await expect(page.getByRole('button', { name: 'Copy code block' })).toHaveCount(2);
+ await page.locator('#content img').evaluate(el => el.dispatchEvent(new Event('error')));
+ await page.locator('#content button', { hasText: 'fake' }).click();
+ await page.locator('#content code', { hasText: 'raw html block' }).click();
+ expect(await page.evaluate(() => (window as unknown as { __hit?: number }).__hit)).toBeUndefined();
+ expect(await page.locator('#content [onerror], #content [onclick], #content script').count()).toBe(0);
+ }
+});
+
+test('a code block that shows a closing script tag stays inside the page script', async ({ page }) => {
+ const snippet = '</script><img src="x" onerror="window.__hit = 5"><script>window.__hit = 6</script>';
+ await open(page, generateHtml({ title: 'Snippet', markdown: ['```html', snippet, '```', ''].join('\n') }));
+ const buttons = page.getByRole('button', { name: 'Copy code block' });
+ await expect(buttons).toHaveCount(1);
+ await buttons.click();
+ expect(await clipboard(page)).toBe(snippet);
+ expect(await page.evaluate(() => (window as unknown as { __hit?: number }).__hit)).toBeUndefined();
+ await expect(page.locator('body > img')).toHaveCount(0);
+});
+
+test('a page with no fenced code block renders the same content with no buttons', async ({ page }) => {
+ await open(page, generateHtml({ title: 'Plain', markdown: '# Plain\n\nJust text with `inline` code.' }));
+ await expect(page.locator('#content button')).toHaveCount(0);
+ expect(await page.locator('#content').innerHTML()).toBe('<h1>Plain</h1>\n<p>Just text with <code>inline</code> code.</p>\n');
+});
diff --git a/changelog.d/gbra583-pierre-bouquet-rebuild.md b/changelog.d/gbra583-pierre-bouquet-rebuild.md
new file mode 100644
index 0000000000..2d2aca3439
--- /dev/null
+++ b/changelog.d/gbra583-pierre-bouquet-rebuild.md
@@ -0,0 +1,12 @@
+**Code blocks on pages made with `gbrain publish` get a Copy button, and `gbrain mcp expose` prints one-click links that add the brain to Cursor and, for a public brain, to Claude.**
+
+### Added
+- Every code block on a published page, including a password-protected page once it is unlocked, shows a Copy button in its top-right corner. It copies the block's exact text, works from the keyboard, and reads "Copied" for a moment. Pages opened from a file or a plain-http host fall back to the browser's older copy command. Code blocks also get a bordered panel that scrolls sideways, so long lines no longer stretch the page. Contributed by @Pierre-Bouquet (#9453).
+- `gbrain mcp expose` ends its `Next` block with a `Cursor` line: Cursor's install link, which opens Cursor's MCP install prompt with the brain's URL filled in. With `--funnel` a `Claude` line comes first: Anthropic's custom connector install link, which opens claude.ai's add-connector form the same way. A tailnet-only publish gets no Claude line, because claude.ai connects from Anthropic's servers and can't reach the tailnet. `--status` repeats the links when everything verifies, and `--json` adds them as `install_links` (only when there is at least one). The links carry no credential, and a URL that isn't plain https gets none.
+- docs/mcp/README.md has a "One-click client links" section with ready links for hosted gbrain.io, docs/mcp/CLAUDE_DESKTOP.md puts the Claude shortcut above its manual steps, and docs/guides/remote-mcp.md shows the new line in its example output.
+
+### Fixed
+- A published page whose markdown contains a closing `</script>` tag, such as a code block that shows HTML, now renders that text instead of breaking the page. Before, the tag ended the page's script early, so the rest of the page was lost and any HTML after it skipped the sanitizer.
+- The password-protected page now renders unlocked content through the same sanitizing function as an open page, instead of patching its unlock script by string replacement.
+
+Contributed by @Pierre-Bouquet
diff --git a/docs/architecture/key-files/google-and-loops-more.md b/docs/architecture/key-files/google-and-loops-more.md
index f355409527..124a744e53 100644
--- a/docs/architecture/key-files/google-and-loops-more.md
+++ b/docs/architecture/key-files/google-and-loops-more.md
@@ -5,5 +5,6 @@
- `src/core/harness/oauth-setup.ts` + `client-setup.ts` — explicit client metadata projection, flow selection, native OAuth setup/private-file validation, and live-row-locked secret delivery recovery. Public PKCE needs no journal; confidential exports validate the retained secret against current registration, and machine exports discard cached tokens. Unknown/mixed flows refuse until an explicit supported flow is selected.
- `src/core/harness/capabilities.ts` + `src/mcp/capabilities.ts` — Shared effective-grant orientation for OAuth whoami and authenticated `gbrain://capabilities`. A stored client token lifetime outside 60 to 7,776,000 seconds (`AuthInfo.tokenTtlSeconds`) reports `token_ttl_invalid`, and the delegation repair template then includes a `--token-ttl <APPROVED_TTL_SECONDS>` choice, since every grant write validates the merged lifetime. The resource preserves the exact seven-tool surface; source, operation, scope, fence and server-gate restrictions remain enforced at dispatch. `grant_diagnosis` (shared with doctor `grant_new_ops_available` through `grantOperationGaps`, `grantAge` and `grantRescopeArgvs`) counts the operations the grant's scopes allow but its operation snapshot, its client pin or the server ceiling block, names none of them, keeps inferred grant age apart (`intent_unknown` without catalog provenance), and builds host commands only from the verifier's principal. No worker probe or per-tool database query during discovery (one audit read for provenance when a snapshot excludes operations). Shared administration guidance explains separate owner authority, links the MCP admin runbook, and exposes an admin URL only for a configured credential-free HTTP MCP endpoint. Stdio never infers an HTTP address. D4 in band: `grantBlockedNotice(diagnosis, {refused})` builds the `grant_blocked_operations` notice (blocker counts, grant age apart, missing scope only when refused) and `grantRepairAction` the host-owned repair (preview argv, `then` apply, verify = doctor `grant_new_ops_available` or `whoami`; server ceiling alone → the read-only doctor check). Dispatch (`grantBlockedNotices`) delivers it once per (principal, session) or, stateless, per (principal, grant revision).
- `src/commands/mcp.ts` + `mcp-provision.ts` + `harness-connect.ts` — Host-side grant/preview/CAS and recoverable private delivery, followed by installation inside the intended harness. Codex, Claude Code and opencode installs (`src/core/harness/install.ts`) store the bearer token inline in the harness config; `inlineTokenReceipt` adds `token_storage`, `config_path`, `renew_command`, `if_exposed` (invalidate-tokens preview/apply, renew, reload; `renew_command` carries `--fresh-token` for renewable handoffs so it always exchanges a new token) and a `token_warning` when a Git working tree would commit the file, and `harness-connect.ts` repeats them on stderr in human mode without printing the token (#5775; `test/harness-token-receipt.test.ts`). Running PGLite hosts are administered through their authenticated API, never by opening a second database process. CLI status uses the delivery-aware exit verdict. `mcp-admin.ts` and `mcp-admin-http.ts` provide engine-free owner commands with explicit-file/env credential precedence, in-memory sessions, private native exports, versioned lifecycle previews, and safe stage/outcome/remedy receipts. Unknown mutation outcomes require inspection instead of automatic repetition. `runMcp` also dispatches `gbrain mcp expose` to `runMcpExpose` (dynamic import of `./mcp-expose.ts`; HELP carries the expose lines so the flag registry harvests them) and sets the CLI exit verdict from its returned code. `mcpNeedsEngine(args)` is true only for `grant` without an owner credential (`--admin-token-file` or `GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) and outside help; `admin`, `expose`, and `verify` never open the database.
-- `src/commands/mcp-expose.ts` — `gbrain mcp expose [--port N] [--funnel] [--surface] [--enable-dcr] [--no-tailscale] [--no-service] [--no-install] [--force] [--dry-run] [--yes] [--json]` / `--status` / `--remove`: publishes `gbrain serve --http` on the user's Tailscale tailnet (Serve by default, Funnel only with the explicit flag) and keeps it running as a user service. `runMcpExpose(args, deps?)` returns the exit code (0 done, 1 failed, 2 needs `--yes`, the prompt was declined, or a step is pending — a tailnet feature to enable, Tailscale login, tailnet certificate). Arg validation via `validateHarnessArguments` (exclusive pairs `--status`/`--remove`, `--funnel`/`--no-tailscale`, `--dry-run`/`--status`); the help text names every flag and the `verify.local` / `verify.tailnet` checks. Ordered named checks — `plan` (platform, execution environment, engine kind from `loadConfig()`; thin clients are refused with "run on the brain host"; `engine === 'unknown'` — no config or an unreadable one — without `--no-service` is refused as `no_brain_config` / exit 1 with next action `gbrain init` BEFORE consent, because a service around a missing brain only crash-loops, while `--dry-run` still prints the plan with the refusal marked and exits 0; on a PGLite engine `deps.pgliteHolder` (default `probeLivePgliteHolder` from `src/core/bootstrap/uninstall.ts`, a read-only lock-file probe) is consulted with `cfg.database_path`, and a live holder that is not our own managed service — receipt present with `service.state` `running`/`loaded` — adds a `Lock` plan line plus a `pglite_lock` check with status `warn` (never a stop); `--no-tailscale` over an existing receipt whose `tailscale.dns_name` is set (a live Serve/Funnel mapping) is refused BEFORE consent as `tailscale_receipt_present` / exit 1 with next actions `gbrain mcp expose --remove --yes` and the re-run without the flag — `--dry-run` marks it `WOULD BE REFUSED`; then probes `127.0.0.1:<port>` with `probeOccupied(d, port, url)` — occupied when EITHER the injectable `deps.tcpProbe` (default `defaultTcpProbe`, one `node:net` connect, socket destroyed on every outcome; true on connect, false on refusal / timeout / throw) accepts a TCP connect OR the `/health` fetch RESOLVES with ANY status (2xx, 404, 500), so a non-HTTP listener counts too; only both rejecting is free — and refuses a foreign listener with no receipt claiming that port as `foreign_listener` BEFORE anything is published unless `--no-service`; the message names the interrupted-run escape hatch `gbrain mcp expose --remove --yes`; `probeHealth` (`res.ok`) stays the bar for `verify.local` / `verify.tailnet` / `--status`), `consent` (shared `confirmOrFinish` for publish and `--remove`: one stderr y/N prompt on a TTY; declining is `pending` / exit 2 / `declined` with "Nothing changed. Re-run with --yes to confirm."; non-interactive without `--yes` prints the plan and exits 2 / `confirmation_required`; every re-run hint is rendered by `rerunCommand(opts)` — the user's publish flags + `--yes`), `tailscale.binary` (install plan: brew cask on macOS — then `open -a Tailscale` and a bounded poll of `tailscale status --json`, up to 20 attempts 1s apart, breaking as soon as the app's daemon answers and otherwise falling through to the login step's daemon-not-running handling — official installer on Linux, `--no-install` → exit 1), `tailscale.login` (Linux `sudo tailscale set --operator=<user>` non-fatal then flagless `sudo tailscale up` — `sudo` is put in front of the binary ONLY when `isSystemTailscaleBinary(binary)` holds (one of `TAILSCALE_BINARY_CANDIDATES`, literally or via `realpathSync`); a user-writable `tailscale` found on PATH stops the step as `pending` / exit 2 / `tailscale_login_manual` with the message "tailscale at <path> is not a system install, so gbrain will not run it with sudo. If you trust that binary, sign in yourself (this runs it as root): `sudo <path> set --operator=$USER && sudo <path> up`, then re-run: <rerun>" — the command is `tailscaleManualLoginCommand(binary)`, naming the discovered path shell-quoted, because a binary outside sudo's `secure_path` is exactly this case — and never spawns `sudo`; macOS `tailscale up`; bounded wait via `GBRAIN_TAILSCALE_LOGIN_TIMEOUT_MS`), `tailscale.identity` (MagicDNS name → `public_url`; pre-checks so `tailscale serve`/`funnel` — which wait interactively instead of failing when a feature is off — are never started blind: empty `CertDomains` → `pending` / exit 2 / `tailscale_https_not_enabled` with `TAILSCALE_ADMIN_DNS_URL`; `--funnel` with `funnelCapable === false` → `tailscale_funnel_not_enabled` with the ACL admin + Funnel KB URLs; `funnelCapable === null` proceeds), `tailscale.publish` (reads the serve config through `readServeView`, which FAILS CLOSED — it returns `{ view: ServeStatusView | null, stderr, status }` with `view: null` when `tailscale serve status --json` exits non-zero / is killed (`status: null`) or when stdout is not a JSON object per `parseServeStatusStrict`; an empty document / `{}` / `null` from exit 0 is the legitimately empty view — a null view before `--bg` is described once by `describeServeReadFailure` (`{ kind, detail, fix }` from one `classifyTailscaleError` call), records `tailscale.publish` = fail and returns exit 1 with reason `tailscale_<kind>` without publishing; a null view after `--bg` is `tailscale_publish_unconfirmed` naming the read failure; refuses a `/` handler proxying a different port, a foreground session or a raw TCP forward without `--force` as `foreign_serve_config` — `next_actions` says `tailscale serve status`, only `message` explains `--force`; `PUBLISH_TIMEOUT_MS` (60s) bounds `--bg`, `SERVE_OFF_TIMEOUT_MS` (30s) every `--https=443 --set-path=/ off` and `STATUS_READ_TIMEOUT_MS` (15s) both status reads; a `status: null` timeout is `unknown` with a run-by-hand hint; stderr classified by `classifyTailscaleError` as the second line of defense; switching our own handler's shape pre-clears ONLY in the funnel → tailnet direction (`funnel --https=443 --set-path=/ off` before `serve --bg`, because `serve --bg` over a Funnel mount keeps `AllowFunnel`; tailnet → funnel is one atomic `funnel --bg`), and when that pre-off was followed by a failed publish (non-zero, timeout, or unconfirmed) `restorePrevious` best-effort re-publishes the previous shape with `tailscaleServeArgv(port, { funnel: true })`, re-reads the view, and appends to the `tailscale.publish` detail whether "the previous funnel handler was restored" or "could NOT be restored"; the existing receipt is never touched on those paths), `admin_token` (ensure the 0600 token file, never printed), `service` (launchd / systemd user unit / `manual` fallback with the exact foreground and `nohup` commands; a `--no-service` re-run carries the existing receipt's service block unchanged and does not rewrite the wrapper; `service_install_failed` still writes the receipt with `service.state: 'stopped'` before exit 1 so `--status`/`--remove` can clean up the published handler; the receipt is ALSO written right after a successful service step — service state as probed at that moment — before verify runs, so a kill during verify always leaves `--status`/`--remove` something to find), `verify.local` (wall-clock `/health` polling up to 20s, timeout → `warn`, exit 2, `verify.tailnet` skipped), `verify.tailnet` (up to 30s, `pending` is exit 2 — EXCEPT when the last probe's rejection was a name-resolution failure per `mcp-expose-probe.ts`: Bun's `fetch` rejects an unresolvable host and a refused connection with the same "Unable to connect. Is the computer able to access the url?" / `ConnectionRefused`, so after a rejected fetch the URL's hostname (never an IP literal or `localhost`) is handed to `deps.lookup` — default `dns.promises.lookup`, bounded by the probe timeout — and a rejection with code `ENOTFOUND` / `EAI_AGAIN` / `EAI_NONAME` / `EAI_NODATA` / `DNS_ENOTFOUND` (or a message naming one) is the verdict, the fetch-message regex staying a secondary hint; a name that resolves but does not answer stays `pending`: then the check is `warn` with `unresolvedDetail(dnsName)` — "this host cannot resolve <name> (MagicDNS may be off here: `tailscale set --accept-dns=true`); devices that do resolve it may already reach the server" — and the run exits 0, since this host's resolver says nothing about the server), `receipt` (rewrites the early receipt with the settled state — the supervisor is re-probed once verify.local ran — keeping `created_at`). The admin-token, service and verify steps run inside one try: a THROW there after this run's `--bg` succeeded but BEFORE the early receipt is rolled back by `rollbackAfterThrow(d, s, opts, published, error, receiptWritten)` — the fresh handler is turned off again with `tailscaleServeOffArgv({ funnel })` only when no `/` handler for our port existed before the run (a pre-existing one is left in place), a `rollback` check records what happened — "turned off again" is claimed only when a re-read of the serve view after an exit-0 `off` no longer shows our port; an exit-0 `off` whose re-read still shows it is a `warn` "NOT turned off (… the handler is still present)", an unreadable re-read is a `warn` "state unknown", and an `off` that exits non-zero or throws is a `warn` whose message says the handler was NOT turned off — no receipt is written, and the error is re-thrown so the outer catch reports `mcp_expose_failed` with a message naming the handler state; once the early receipt is on disk (`receiptWritten`, checked first) a throw tears nothing down (`rollback` = skipped pointing at `--status` / `--remove --yes`), because the receipt makes everything findable (the non-throwing `service_install_failed` path keeps its partial receipt). Success banner and `next_actions` gate the local-agent line on the engine: Postgres → `gbrain bootstrap harness --yes --port N`; PGLite → pre-mint (`gbrain auth create … --scopes read,write` before the service runs) + `--token`, or the scoped `mcp grant … --url http://127.0.0.1:N/mcp --admin-token-file …` + `gbrain connect … --install` path, and "host-side commands fail with `live_serve` — administer through the running server". `--json` emits one stdout document `{ status, receipt, checks[], next_actions, reason?, message? }` with prose on stderr; every `inherit` subprocess redirects its stdout to stderr under `--json`. `--status` and `--remove` read the receipt through `readExposeReceipt`'s shape guard (a partial receipt is `not_exposed` / "nothing to remove", never a crash) and execute the tailscale binary from `resolveReceiptBinary`: the receipt's recorded path is honored only when it still exists AND is either what `findTailscaleBinary` finds now or one of `TAILSCALE_BINARY_CANDIDATES`, otherwise discovery wins — a path in a receipt is data, never a licence to run it. the probes — `probeHealth` (`res.ok`), `probeOccupied` (any response, or an accepted TCP connect), the bounded never-throwing `tryFetch` → `FetchOutcome { res, unresolved }`, `pollHealth` → `{ ok, unresolved }` with the LAST probe's resolution verdict, `unresolvedDetail`, `defaultTcpProbe`, `defaultLookup` — live in `src/commands/mcp-expose-probe.ts` and take the narrow `ProbeDeps` slice of the resolved deps (`fetch`, `tcpProbe`, `lookup`, `now`, `sleep`, `healthIntervalMs`); `defaultTcpProbe` is re-exported here so its import site never moved; `isLiveService(state)` is the one definition of "the supervisor reports our service" (`running` or `loaded`) used by the lock-holder exemption, the service check, `--status` and both `--remove` paths; `serviceLabel` builds on `serviceKindLabel` (`launchd <label>` / `systemd (user) <unit>`). `--status` runs its four independent probes (serve config, supervisor state, local and tailnet `/health`) concurrently with `Promise.all` and still reports the checks in the fixed order `receipt`, `tailscale.publish`, `service`, `verify.local`, `verify.tailnet`; an unreadable serve config (null view) is a FAILED `tailscale.publish` check / exit 1, never "handler present"; a tailnet `/health` rejected for name resolution is `verify.tailnet` = warn (same `unresolvedDetail`), not `pending`, and does not by itself make the exit non-zero. `--status` with NO receipt is `runStatusWithoutReceipt`: it runs the read-only `probeLeftovers(d, opts.port)` (`--port` is honored) and, when the wrapper, the plist / unit or a live service, or a `/` handler on `:443` proxying the port is found, emits one `warn` check per artifact (`receipt`, `service`, `tailscale.publish`, `files`), pushes `recoveryCommand(port, force)` (`gbrain mcp expose --remove --yes`, `--force` only when a handler stands alone with no wrapper / service corroborating it, `--port N` when non-default) to `next_actions`, and finishes `error` / exit 1 / `leftovers_without_receipt` (also under `--json`); an unreadable serve status alone is a caveat warn, not a leftover; nothing found keeps the `not_exposed` answer (exit 0, `--json` exit 2). `--remove` (consent; decline is `pending` / exit 2) probes the supervisor and removes a service that exists even when the receipt says skipped — `recordServiceUninstall` prints the uninstall notes, and when `launchdBootoutFailed(result)` (a `launchctl bootout failed: …` / `unload failed: …` note, i.e. a non-"not loaded" failure) the `service` check is `warn` pointing at `launchctl print gui/$(id -u)/com.gbrain.serve` and "the launchd job (bootout failed)" is added to "Left in place"; it returns the one-line service summary quoted below — then clears only gbrain's own serve/funnel handler through `turnOffOurHandler` (Funnel off first; every `off` is `--https=443 --set-path=/ off`, scoped to our `/` mount; the serve config is re-read only after an `off` command ran, otherwise the view already read is reused; a failed re-read is reported as `unknown` — a warn, never "gone"; a foreign port on `:443` gets "nothing to turn off"). `--remove` never reports success while our handler survives: when `turnOffOurHandler` returns `remaining` as a handler (`tailscale.publish` = fail) or `'unknown'` (= warn), `finishHandlerNotRemoved` keeps the receipt AND the wrapper (mirroring the unreadable-status branch), records `receipt` = skipped "kept: …", pushes `tailscale serve status` + the re-run to `next_actions`, says which service outcome already happened, and exits 1 with reason `handler_not_removed`; `--remove` never runs `tailscale serve reset`, never uninstalls or logs out, keeps the admin token unless `--force` (deleted through the same `unlinkQuietly` as the wrapper and receipt), and unlinks the wrapper / receipt / token ONLY when the path's directory is the serve directory — a receipt path elsewhere is left untouched and named in "Left in place" (also in the plan). The receipt's recorded `plist_path` / `unit_path` are data, never a licence: `uninstallServeService` is always handed the computed `d.plistPath` / `d.unitPath` (home + the fixed label / unit name), and a recorded path that differs is not touched and is named in "Left in place" as "recorded in the receipt but not the expected location". A null serve view during `--remove` fails closed: `tailscale.publish` = fail "could not read tailscale serve status; handler left as is", reason `tailscale_serve_status_unreadable`, exit 1, and the receipt AND wrapper are kept so a re-run finishes the job. With NO receipt, `runRemoveWithoutReceipt` recovers from what is on disk through the same `probeLeftovers` `--status` uses (`wrapperPath(serveDir)`, the launchd plist / systemd unit or a `running`/`loaded` service, a `/` handler on `:443` proxying `opts.port` — `--port` may accompany `--remove`, default 3131); inside it the supervisor chain (`probeServiceTarget` → `serveServiceState`) and the `readServeView` read run concurrently under `Promise.all` (the binary is resolved synchronously first) and the plan / checks are emitted in the fixed order afterwards; the re-run hints come from `recoveryCommand`. The handler is turned off only with corroborating gbrain evidence — the wrapper present, our unit/plist present, or the supervisor reporting our service live — or with `--force`, because another tool may proxy `:443` to the same port: a handler standing alone is reported (`tailscale.publish` = warn naming the proxy target and `--force`, next action `gbrain mcp expose --remove --yes --force`) and left in place on the "not exposed — nothing to remove" exit-0 path; with `--force` the plan line says so. Otherwise it prints a "Recovering without a receipt" plan (`receipt` check = warn), takes consent as usual, removes exactly those artifacts (service via the supervisor — the same `recordServiceUninstall` bootout-failure warn applies — wrapper, the handler — funnel off first when `AllowFunnel` lists the host), leaves the admin token file, and finishes `removed` with reason `recovered_without_receipt`; a handler that survives the `off` is `handler_not_removed` / exit 1 here too, with the wrapper deliberately KEPT as the corroboration the re-run needs (`files` = skipped "kept: the wrapper"; the re-run hint carries `--force` when no wrapper is left); an unreadable serve status on this path (gbrain evidence present, `serveUnreadable` set) fails closed exactly like the receipt path — the service, when found, is still uninstalled, the plan says the handler cannot be checked and the wrapper is kept, `tailscale.publish` = fail "…; handler state unknown", `files` = skipped "kept: the wrapper" (or "nothing (no wrapper was found)"), `next_actions` = `tailscale serve status --json` + the recovery command (`--force` when no wrapper is left), exit 1 with reason `tailscale_serve_status_unreadable` and message "could not read tailscale serve status; handler state unknown"; when nothing of ours is found the answer stays "not exposed — nothing to remove", exit 0 (an unreadable serve status is then only the caveat warn — there is nothing to keep and a handler alone would not be touched anyway). Every filesystem/exec effect goes through injectable deps so tests run against a fake runner in a tmpdir. Success guidance separates owner login, native OAuth registration, and machine grant/install. It uses the expose-managed owner file only when installing or keeping that service; publication with `--no-service` and no managed service instead requires the existing server's independently configured owner credential. Publishing receipts and health checks do not certify client authorization or native activation.
+- `src/commands/mcp-expose.ts` — `gbrain mcp expose [--port N] [--funnel] [--surface] [--enable-dcr] [--no-tailscale] [--no-service] [--no-install] [--force] [--dry-run] [--yes] [--json]` / `--status` / `--remove`: publishes `gbrain serve --http` on the user's Tailscale tailnet (Serve by default, Funnel only with the explicit flag) and keeps it running as a user service. `runMcpExpose(args, deps?)` returns the exit code (0 done, 1 failed, 2 needs `--yes`, the prompt was declined, or a step is pending — a tailnet feature to enable, Tailscale login, tailnet certificate). Arg validation via `validateHarnessArguments` (exclusive pairs `--status`/`--remove`, `--funnel`/`--no-tailscale`, `--dry-run`/`--status`); the help text names every flag and the `verify.local` / `verify.tailnet` checks. Ordered named checks — `plan` (platform, execution environment, engine kind from `loadConfig()`; thin clients are refused with "run on the brain host"; `engine === 'unknown'` — no config or an unreadable one — without `--no-service` is refused as `no_brain_config` / exit 1 with next action `gbrain init` BEFORE consent, because a service around a missing brain only crash-loops, while `--dry-run` still prints the plan with the refusal marked and exits 0; on a PGLite engine `deps.pgliteHolder` (default `probeLivePgliteHolder` from `src/core/bootstrap/uninstall.ts`, a read-only lock-file probe) is consulted with `cfg.database_path`, and a live holder that is not our own managed service — receipt present with `service.state` `running`/`loaded` — adds a `Lock` plan line plus a `pglite_lock` check with status `warn` (never a stop); `--no-tailscale` over an existing receipt whose `tailscale.dns_name` is set (a live Serve/Funnel mapping) is refused BEFORE consent as `tailscale_receipt_present` / exit 1 with next actions `gbrain mcp expose --remove --yes` and the re-run without the flag — `--dry-run` marks it `WOULD BE REFUSED`; then probes `127.0.0.1:<port>` with `probeOccupied(d, port, url)` — occupied when EITHER the injectable `deps.tcpProbe` (default `defaultTcpProbe`, one `node:net` connect, socket destroyed on every outcome; true on connect, false on refusal / timeout / throw) accepts a TCP connect OR the `/health` fetch RESOLVES with ANY status (2xx, 404, 500), so a non-HTTP listener counts too; only both rejecting is free — and refuses a foreign listener with no receipt claiming that port as `foreign_listener` BEFORE anything is published unless `--no-service`; the message names the interrupted-run escape hatch `gbrain mcp expose --remove --yes`; `probeHealth` (`res.ok`) stays the bar for `verify.local` / `verify.tailnet` / `--status`), `consent` (shared `confirmOrFinish` for publish and `--remove`: one stderr y/N prompt on a TTY; declining is `pending` / exit 2 / `declined` with "Nothing changed. Re-run with --yes to confirm."; non-interactive without `--yes` prints the plan and exits 2 / `confirmation_required`; every re-run hint is rendered by `rerunCommand(opts)` — the user's publish flags + `--yes`), `tailscale.binary` (install plan: brew cask on macOS — then `open -a Tailscale` and a bounded poll of `tailscale status --json`, up to 20 attempts 1s apart, breaking as soon as the app's daemon answers and otherwise falling through to the login step's daemon-not-running handling — official installer on Linux, `--no-install` → exit 1), `tailscale.login` (Linux `sudo tailscale set --operator=<user>` non-fatal then flagless `sudo tailscale up` — `sudo` is put in front of the binary ONLY when `isSystemTailscaleBinary(binary)` holds (one of `TAILSCALE_BINARY_CANDIDATES`, literally or via `realpathSync`); a user-writable `tailscale` found on PATH stops the step as `pending` / exit 2 / `tailscale_login_manual` with the message "tailscale at <path> is not a system install, so gbrain will not run it with sudo. If you trust that binary, sign in yourself (this runs it as root): `sudo <path> set --operator=$USER && sudo <path> up`, then re-run: <rerun>" — the command is `tailscaleManualLoginCommand(binary)`, naming the discovered path shell-quoted, because a binary outside sudo's `secure_path` is exactly this case — and never spawns `sudo`; macOS `tailscale up`; bounded wait via `GBRAIN_TAILSCALE_LOGIN_TIMEOUT_MS`), `tailscale.identity` (MagicDNS name → `public_url`; pre-checks so `tailscale serve`/`funnel` — which wait interactively instead of failing when a feature is off — are never started blind: empty `CertDomains` → `pending` / exit 2 / `tailscale_https_not_enabled` with `TAILSCALE_ADMIN_DNS_URL`; `--funnel` with `funnelCapable === false` → `tailscale_funnel_not_enabled` with the ACL admin + Funnel KB URLs; `funnelCapable === null` proceeds), `tailscale.publish` (reads the serve config through `readServeView`, which FAILS CLOSED — it returns `{ view: ServeStatusView | null, stderr, status }` with `view: null` when `tailscale serve status --json` exits non-zero / is killed (`status: null`) or when stdout is not a JSON object per `parseServeStatusStrict`; an empty document / `{}` / `null` from exit 0 is the legitimately empty view — a null view before `--bg` is described once by `describeServeReadFailure` (`{ kind, detail, fix }` from one `classifyTailscaleError` call), records `tailscale.publish` = fail and returns exit 1 with reason `tailscale_<kind>` without publishing; a null view after `--bg` is `tailscale_publish_unconfirmed` naming the read failure; refuses a `/` handler proxying a different port, a foreground session or a raw TCP forward without `--force` as `foreign_serve_config` — `next_actions` says `tailscale serve status`, only `message` explains `--force`; `PUBLISH_TIMEOUT_MS` (60s) bounds `--bg`, `SERVE_OFF_TIMEOUT_MS` (30s) every `--https=443 --set-path=/ off` and `STATUS_READ_TIMEOUT_MS` (15s) both status reads; a `status: null` timeout is `unknown` with a run-by-hand hint; stderr classified by `classifyTailscaleError` as the second line of defense; switching our own handler's shape pre-clears ONLY in the funnel → tailnet direction (`funnel --https=443 --set-path=/ off` before `serve --bg`, because `serve --bg` over a Funnel mount keeps `AllowFunnel`; tailnet → funnel is one atomic `funnel --bg`), and when that pre-off was followed by a failed publish (non-zero, timeout, or unconfirmed) `restorePrevious` best-effort re-publishes the previous shape with `tailscaleServeArgv(port, { funnel: true })`, re-reads the view, and appends to the `tailscale.publish` detail whether "the previous funnel handler was restored" or "could NOT be restored"; the existing receipt is never touched on those paths), `admin_token` (ensure the 0600 token file, never printed), `service` (launchd / systemd user unit / `manual` fallback with the exact foreground and `nohup` commands; a `--no-service` re-run carries the existing receipt's service block unchanged and does not rewrite the wrapper; `service_install_failed` still writes the receipt with `service.state: 'stopped'` before exit 1 so `--status`/`--remove` can clean up the published handler; the receipt is ALSO written right after a successful service step — service state as probed at that moment — before verify runs, so a kill during verify always leaves `--status`/`--remove` something to find), `verify.local` (wall-clock `/health` polling up to 20s, timeout → `warn`, exit 2, `verify.tailnet` skipped), `verify.tailnet` (up to 30s, `pending` is exit 2 — EXCEPT when the last probe's rejection was a name-resolution failure per `mcp-expose-probe.ts`: Bun's `fetch` rejects an unresolvable host and a refused connection with the same "Unable to connect. Is the computer able to access the url?" / `ConnectionRefused`, so after a rejected fetch the URL's hostname (never an IP literal or `localhost`) is handed to `deps.lookup` — default `dns.promises.lookup`, bounded by the probe timeout — and a rejection with code `ENOTFOUND` / `EAI_AGAIN` / `EAI_NONAME` / `EAI_NODATA` / `DNS_ENOTFOUND` (or a message naming one) is the verdict, the fetch-message regex staying a secondary hint; a name that resolves but does not answer stays `pending`: then the check is `warn` with `unresolvedDetail(dnsName)` — "this host cannot resolve <name> (MagicDNS may be off here: `tailscale set --accept-dns=true`); devices that do resolve it may already reach the server" — and the run exits 0, since this host's resolver says nothing about the server), `receipt` (rewrites the early receipt with the settled state — the supervisor is re-probed once verify.local ran — keeping `created_at`). The admin-token, service and verify steps run inside one try: a THROW there after this run's `--bg` succeeded but BEFORE the early receipt is rolled back by `rollbackAfterThrow(d, s, opts, published, error, receiptWritten)` — the fresh handler is turned off again with `tailscaleServeOffArgv({ funnel })` only when no `/` handler for our port existed before the run (a pre-existing one is left in place), a `rollback` check records what happened — "turned off again" is claimed only when a re-read of the serve view after an exit-0 `off` no longer shows our port; an exit-0 `off` whose re-read still shows it is a `warn` "NOT turned off (… the handler is still present)", an unreadable re-read is a `warn` "state unknown", and an `off` that exits non-zero or throws is a `warn` whose message says the handler was NOT turned off — no receipt is written, and the error is re-thrown so the outer catch reports `mcp_expose_failed` with a message naming the handler state; once the early receipt is on disk (`receiptWritten`, checked first) a throw tears nothing down (`rollback` = skipped pointing at `--status` / `--remove --yes`), because the receipt makes everything findable (the non-throwing `service_install_failed` path keeps its partial receipt). Success banner and `next_actions` gate the local-agent line on the engine: Postgres → `gbrain bootstrap harness --yes --port N`; PGLite → pre-mint (`gbrain auth create … --scopes read,write` before the service runs) + `--token`, or the scoped `mcp grant … --url http://127.0.0.1:N/mcp --admin-token-file …` + `gbrain connect … --install` path, and "host-side commands fail with `live_serve` — administer through the running server". `--json` emits one stdout document `{ status, receipt, checks[], next_actions, reason?, message? }` with prose on stderr; every `inherit` subprocess redirects its stdout to stderr under `--json`. `--status` and `--remove` read the receipt through `readExposeReceipt`'s shape guard (a partial receipt is `not_exposed` / "nothing to remove", never a crash) and execute the tailscale binary from `resolveReceiptBinary`: the receipt's recorded path is honored only when it still exists AND is either what `findTailscaleBinary` finds now or one of `TAILSCALE_BINARY_CANDIDATES`, otherwise discovery wins — a path in a receipt is data, never a licence to run it. the probes — `probeHealth` (`res.ok`), `probeOccupied` (any response, or an accepted TCP connect), the bounded never-throwing `tryFetch` → `FetchOutcome { res, unresolved }`, `pollHealth` → `{ ok, unresolved }` with the LAST probe's resolution verdict, `unresolvedDetail`, `defaultTcpProbe`, `defaultLookup` — live in `src/commands/mcp-expose-probe.ts` and take the narrow `ProbeDeps` slice of the resolved deps (`fetch`, `tcpProbe`, `lookup`, `now`, `sleep`, `healthIntervalMs`); `defaultTcpProbe` is re-exported here so its import site never moved; `isLiveService(state)` is the one definition of "the supervisor reports our service" (`running` or `loaded`) used by the lock-holder exemption, the service check, `--status` and both `--remove` paths; `serviceLabel` builds on `serviceKindLabel` (`launchd <label>` / `systemd (user) <unit>`). `--status` runs its four independent probes (serve config, supervisor state, local and tailnet `/health`) concurrently with `Promise.all` and still reports the checks in the fixed order `receipt`, `tailscale.publish`, `service`, `verify.local`, `verify.tailnet`; an unreadable serve config (null view) is a FAILED `tailscale.publish` check / exit 1, never "handler present"; a tailnet `/health` rejected for name resolution is `verify.tailnet` = warn (same `unresolvedDetail`), not `pending`, and does not by itself make the exit non-zero. `--status` with NO receipt is `runStatusWithoutReceipt`: it runs the read-only `probeLeftovers(d, opts.port)` (`--port` is honored) and, when the wrapper, the plist / unit or a live service, or a `/` handler on `:443` proxying the port is found, emits one `warn` check per artifact (`receipt`, `service`, `tailscale.publish`, `files`), pushes `recoveryCommand(port, force)` (`gbrain mcp expose --remove --yes`, `--force` only when a handler stands alone with no wrapper / service corroborating it, `--port N` when non-default) to `next_actions`, and finishes `error` / exit 1 / `leftovers_without_receipt` (also under `--json`); an unreadable serve status alone is a caveat warn, not a leftover; nothing found keeps the `not_exposed` answer (exit 0, `--json` exit 2). `--remove` (consent; decline is `pending` / exit 2) probes the supervisor and removes a service that exists even when the receipt says skipped — `recordServiceUninstall` prints the uninstall notes, and when `launchdBootoutFailed(result)` (a `launchctl bootout failed: …` / `unload failed: …` note, i.e. a non-"not loaded" failure) the `service` check is `warn` pointing at `launchctl print gui/$(id -u)/com.gbrain.serve` and "the launchd job (bootout failed)" is added to "Left in place"; it returns the one-line service summary quoted below — then clears only gbrain's own serve/funnel handler through `turnOffOurHandler` (Funnel off first; every `off` is `--https=443 --set-path=/ off`, scoped to our `/` mount; the serve config is re-read only after an `off` command ran, otherwise the view already read is reused; a failed re-read is reported as `unknown` — a warn, never "gone"; a foreign port on `:443` gets "nothing to turn off"). `--remove` never reports success while our handler survives: when `turnOffOurHandler` returns `remaining` as a handler (`tailscale.publish` = fail) or `'unknown'` (= warn), `finishHandlerNotRemoved` keeps the receipt AND the wrapper (mirroring the unreadable-status branch), records `receipt` = skipped "kept: …", pushes `tailscale serve status` + the re-run to `next_actions`, says which service outcome already happened, and exits 1 with reason `handler_not_removed`; `--remove` never runs `tailscale serve reset`, never uninstalls or logs out, keeps the admin token unless `--force` (deleted through the same `unlinkQuietly` as the wrapper and receipt), and unlinks the wrapper / receipt / token ONLY when the path's directory is the serve directory — a receipt path elsewhere is left untouched and named in "Left in place" (also in the plan). The receipt's recorded `plist_path` / `unit_path` are data, never a licence: `uninstallServeService` is always handed the computed `d.plistPath` / `d.unitPath` (home + the fixed label / unit name), and a recorded path that differs is not touched and is named in "Left in place" as "recorded in the receipt but not the expected location". A null serve view during `--remove` fails closed: `tailscale.publish` = fail "could not read tailscale serve status; handler left as is", reason `tailscale_serve_status_unreadable`, exit 1, and the receipt AND wrapper are kept so a re-run finishes the job. With NO receipt, `runRemoveWithoutReceipt` recovers from what is on disk through the same `probeLeftovers` `--status` uses (`wrapperPath(serveDir)`, the launchd plist / systemd unit or a `running`/`loaded` service, a `/` handler on `:443` proxying `opts.port` — `--port` may accompany `--remove`, default 3131); inside it the supervisor chain (`probeServiceTarget` → `serveServiceState`) and the `readServeView` read run concurrently under `Promise.all` (the binary is resolved synchronously first) and the plan / checks are emitted in the fixed order afterwards; the re-run hints come from `recoveryCommand`. The handler is turned off only with corroborating gbrain evidence — the wrapper present, our unit/plist present, or the supervisor reporting our service live — or with `--force`, because another tool may proxy `:443` to the same port: a handler standing alone is reported (`tailscale.publish` = warn naming the proxy target and `--force`, next action `gbrain mcp expose --remove --yes --force`) and left in place on the "not exposed — nothing to remove" exit-0 path; with `--force` the plan line says so. Otherwise it prints a "Recovering without a receipt" plan (`receipt` check = warn), takes consent as usual, removes exactly those artifacts (service via the supervisor — the same `recordServiceUninstall` bootout-failure warn applies — wrapper, the handler — funnel off first when `AllowFunnel` lists the host), leaves the admin token file, and finishes `removed` with reason `recovered_without_receipt`; a handler that survives the `off` is `handler_not_removed` / exit 1 here too, with the wrapper deliberately KEPT as the corroboration the re-run needs (`files` = skipped "kept: the wrapper"; the re-run hint carries `--force` when no wrapper is left); an unreadable serve status on this path (gbrain evidence present, `serveUnreadable` set) fails closed exactly like the receipt path — the service, when found, is still uninstalled, the plan says the handler cannot be checked and the wrapper is kept, `tailscale.publish` = fail "…; handler state unknown", `files` = skipped "kept: the wrapper" (or "nothing (no wrapper was found)"), `next_actions` = `tailscale serve status --json` + the recovery command (`--force` when no wrapper is left), exit 1 with reason `tailscale_serve_status_unreadable` and message "could not read tailscale serve status; handler state unknown"; when nothing of ours is found the answer stays "not exposed — nothing to remove", exit 0 (an unreadable serve status is then only the caveat warn — there is nothing to keep and a handler alone would not be touched anyway). Every filesystem/exec effect goes through injectable deps so tests run against a fake runner in a tmpdir. Success guidance separates owner login, native OAuth registration, and machine grant/install. It uses the expose-managed owner file only when installing or keeping that service; publication with `--no-service` and no managed service instead requires the existing server's independently configured owner credential. Publishing receipts and health checks do not certify client authorization or native activation. The `Next` block, and a fully verified `--status`, add one-click client lines from `connector-install-links.ts` (Cursor always, Claude only for a Funnel receipt); `--json` carries them as `install_links` only when at least one link exists.
+- `src/core/connector-install-links.ts` — pure builders for one-click client links: `cursorInstallLink(mcpUrl, name='gbrain')` (Cursor's documented `cursor://anysphere.cursor-deeplink/mcp/install?name=…&config=…`, config = base64 of `JSON.stringify({ url })`, then `encodeURIComponent`), `claudeConnectorLink(mcpUrl, name='GBrain')` (Anthropic's documented custom connector install link, `https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=…&connectorUrl=…`), `connectorInstallLinks(mcpUrl, isPublic)` (Claude only when `isPublic`, since claude.ai connects from Anthropic's cloud) `installLinkLines(links, isPublic)` (the two-column human lines) and `printInstallLinks(mcpUrl, isPublic, say)` (builds, prints, returns the links for `--json`). Every builder returns null unless the URL parses as absolute `https:` with a hostname and no userinfo, so a link never carries a credential. `test/connector-install-links.test.ts` pins the docs' gbrain.io links to these builders.
- `src/commands/mcp-expose-probe.ts` — the health / occupancy probes `mcp-expose.ts` runs, peeled out behind a narrow `ProbeDeps` (`fetch`, `tcpProbe`, `lookup`, `now`, `sleep`, `healthIntervalMs`) rather than the whole resolved-deps bag: `tryFetch(d, url, timeoutMs)` (one bounded fetch, `redirect: 'manual'`, never throws → `FetchOutcome { res, unresolved }`), `probeHealth` (`res.ok` — the `verify.*` / `--status` bar), `probeOccupied` (an accepted TCP connect OR any HTTP answer — the foreign-listener bar), `pollHealth` (wall-clock budget from `d.now()`, per-probe timeout `min(1500, remaining)`, attempt cap `ceil(budget / healthIntervalMs)` as the frozen-clock backstop, `unresolved` = the LAST probe's verdict), `unresolvedDetail(dnsName)`, `defaultTcpProbe` (one `node:net` connect, socket destroyed on every outcome) and `defaultLookup` (local RFC 6761 `.invalid` rejection, otherwise `dns.promises.lookup`). The name-resolution verdict is the reason the module exists: Bun's `fetch` rejects an unresolvable host with the SAME error as a refused connection ("Unable to connect. Is the computer able to access the url?", code `ConnectionRefused`), so a message match alone never fires in production. After a rejection `nameUnresolved` takes `new URL(url).hostname`, skips IP literals (`isIP`) and `localhost`, and otherwise awaits `d.lookup(host)` raced against the probe's `timeoutMs` (a lookup that does not answer in time proves nothing; the race keeps a late rejection handled); `isUnresolvedLookupError` classifies the lookup rejection by `code` — `ENOTFOUND`, `EAI_AGAIN`, `EAI_NONAME`, `EAI_NODATA`, `DNS_ENOTFOUND` (a resolver outage counts: the verdict is about THIS host) — or by those tokens in its message, and the fetch-message regex (`ENOTFOUND|getaddrinfo|EAI_AGAIN|failed to resolve|Unable to connect.*resolve`) is OR-ed in afterwards as the secondary hint. Tests inject a fake fetch, TCP probe and resolver (`test/mcp-expose.test.ts`; the fixture's default `lookup` resolves every name, reserved-name and label-boundary cases do not query external DNS, and the real `defaultLookup` resolves localhost). `statusOnlyHealthDetail(port)` reads this host's live status-only marker for the port so `verify.local` reads "status-only (<reason>)" instead of a timeout or "no answer".
diff --git a/docs/guides/remote-mcp.md b/docs/guides/remote-mcp.md
index 3b244f6987..ff829ff16c 100644
--- a/docs/guides/remote-mcp.md
+++ b/docs/guides/remote-mcp.md
@@ -120,9 +120,19 @@ Next — choose the connection method supported by the intended client
then gbrain bootstrap harness --yes --port 3131 --token <value>; or grant a scoped client with
gbrain mcp grant … --url http://127.0.0.1:3131/mcp --admin-token-file ~/.gbrain/serve/admin-token
and gbrain connect http://127.0.0.1:3131/mcp --harness <id> --credentials-file … --install
+ Cursor cursor://anysphere.cursor-deeplink/mcp/install?name=gbrain&config=eyJ1cmwiOiJodHRwczovL3lvdXItbWFjaGluZS55b3VyLXRhaWxuZXQudHMubmV0L21jcCJ9
+ Opens Cursor's MCP install prompt with this URL filled in; the Cursor machine must be on your tailnet.
Check gbrain mcp expose --status
```
+The `Cursor` line is a one-click link: it opens Cursor's install prompt with
+this MCP URL filled in. With `--funnel`, a `Claude` line comes first, which
+opens claude.ai's add-connector form the same way. Tailnet-only publishes get
+no Claude line, because claude.ai connects from Anthropic's servers. You still
+confirm and sign in inside the client. `--status` repeats the links and
+`--json` returns them as `install_links`. See [one-click client
+links](../mcp/README.md#one-click-client-links).
+
The `Engine` and `Local agents` lines depend on the engine the receipt
recorded: a Postgres brain prints `Local agents gbrain bootstrap harness
--yes --port 3131` because minting works while the server runs.
diff --git a/docs/mcp/CLAUDE_DESKTOP.md b/docs/mcp/CLAUDE_DESKTOP.md
index 6903263991..1165b63671 100644
--- a/docs/mcp/CLAUDE_DESKTOP.md
+++ b/docs/mcp/CLAUDE_DESKTOP.md
@@ -20,6 +20,22 @@ host, the `remote-mcp` skill publishes with `gbrain mcp expose` when needed,
then [MCP administration](ADMIN.md) supplies the URL and setup for your chosen
authentication method. You finish in the Claude Desktop GUI below.
+## Shortcut: one link
+
+If your brain has a public HTTPS address, one link opens Claude's **Add custom
+connector** form with the address filled in. Check it, click **Add**, then sign
+in. The connector lands in your Claude account, so Claude Desktop and claude.ai
+both get it.
+
+- Hosted GBrain: `https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=GBrain&connectorUrl=https%3A%2F%2Fgbrain.io%2Fmcp`
+- Your own brain: `gbrain mcp expose --funnel` prints the link for your URL
+ (the `Claude` line under `Next`).
+
+A tailnet-only brain (plain `gbrain mcp expose`) gets no Claude link, because
+claude.ai connects from Anthropic's servers. If the form opens empty (today
+the filled-in values are lost after a sign-in redirect and on iPhone Safari),
+use the manual steps below.
+
## 1. Publish the brain (host side)
Claude Desktop runs on your own device, so the tailnet-only default is enough
diff --git a/docs/mcp/README.md b/docs/mcp/README.md
index 3d45902a4a..f9eddb1d0a 100644
--- a/docs/mcp/README.md
+++ b/docs/mcp/README.md
@@ -42,6 +42,32 @@ Client-specific details: [ChatGPT](CHATGPT.md), [Claude Code](CLAUDE_CODE.md),
[opencode](OPENCODE.md), [Perplexity](PERPLEXITY.md),
[OpenClaw](OPENCLAW.md), and the [adapter reference](../guides/harness-adapters.md).
+## One-click client links
+
+Claude and Cursor can each add GBrain from one link. The link opens the
+client's own "add server" form with the MCP URL already filled in. You check
+it, confirm, and sign in there as usual. The link holds no password or token.
+
+**Hosted GBrain** (MCP URL `https://gbrain.io/mcp`):
+
+- Claude (claude.ai and Claude Desktop), open in a browser:
+ `https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=GBrain&connectorUrl=https%3A%2F%2Fgbrain.io%2Fmcp`
+- Cursor, open in a browser or click where links work:
+ `cursor://anysphere.cursor-deeplink/mcp/install?name=gbrain&config=eyJ1cmwiOiJodHRwczovL2dicmFpbi5pby9tY3AifQ%3D%3D`
+
+**Your own brain:** `gbrain mcp expose` prints these links for your URL in
+its `Next` block, `gbrain mcp expose --status` repeats them, and `--json`
+returns them as `install_links`. The Cursor link is always printed, because
+Cursor connects from your own computer (on a tailnet-only brain, that computer
+must be on your tailnet). The Claude link is printed only with `--funnel`,
+because claude.ai connects from Anthropic's servers, which can't reach a
+tailnet-only address.
+
+If the form opens empty, add the server by hand: [Claude
+Desktop](CLAUDE_DESKTOP.md#2-add-the-integration). Today Claude's form loses
+the filled-in values after a sign-in redirect and on iPhone Safari. ChatGPT
+and Perplexity have no such link, so follow their pages.
+
## A tool call returned an error
Every gbrain tool error is one content block holding a JSON envelope. Read
diff --git a/llms-full.txt b/llms-full.txt
index df1d06b0c2..f1dc972e5c 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -133,9 +133,19 @@ Next — choose the connection method supported by the intended client
then gbrain bootstrap harness --yes --port 3131 --token <value>; or grant a scoped client with
gbrain mcp grant … --url http://127.0.0.1:3131/mcp --admin-token-file ~/.gbrain/serve/admin-token
and gbrain connect http://127.0.0.1:3131/mcp --harness <id> --credentials-file … --install
+ Cursor cursor://anysphere.cursor-deeplink/mcp/install?name=gbrain&config=eyJ1cmwiOiJodHRwczovL3lvdXItbWFjaGluZS55b3VyLXRhaWxuZXQudHMubmV0L21jcCJ9
+ Opens Cursor's MCP install prompt with this URL filled in; the Cursor machine must be on your tailnet.
Check gbrain mcp expose --status
```
+The `Cursor` line is a one-click link: it opens Cursor's install prompt with
+this MCP URL filled in. With `--funnel`, a `Claude` line comes first, which
+opens claude.ai's add-connector form the same way. Tailnet-only publishes get
+no Claude line, because claude.ai connects from Anthropic's servers. You still
+confirm and sign in inside the client. `--status` repeats the links and
+`--json` returns them as `install_links`. See [one-click client
+links](../mcp/README.md#one-click-client-links).
+
The `Engine` and `Local agents` lines depend on the engine the receipt
recorded: a Postgres brain prints `Local agents gbrain bootstrap harness
--yes --port 3131` because minting works while the server runs.
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index 65a0504768..b43bfd7f12 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -19,7 +19,7 @@ src/commands/eval-longmemeval.ts runEvalLongMemEval 740 seed: W5 baseline, refac
src/commands/extract-conversation-facts.ts runExtractConversationFactsCore 355 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5757: managed flag threaded into ExtractCoreState; +4 #5823: shared default-cap wiring and structured budget reason/model; decision logic is in facts/conversation-budget.ts; +2 #5330: strict-eligibility read and the enumeration filter through the shared predicate (rule lives in facts/conversation-types.ts); lowered to 355 at the wave-9 follow-ups merge (zero result via emptyExtractConversationFactsResult)
src/commands/extract.ts runExtract 398 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/import.ts runImport 978 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 GBRA-40 F4b: planner-stats refresh every import.analyze_every_pages files (logic in planner-stats.ts); +6 #5988: onFileResult hook so full sync holds content refusals (logic in commands/sync/holds.ts); +3 #5988: heldPaths skip so a full sync never imports a rename destination it held this run (logic in commands/sync/holds.ts); +1 Wave B lane 1d (TODO wave-b PR 1): reads the segmented-storage policy once per run for the streamed import of files over the single-string ceiling; +1 GBRA-218 A2: the import barrier installs the tree's folder rules before any page (logic in access/policy-transfer.ts); +4 GST-2462: the noticeRun option, the privacy_label_ignored notice call and its JSON and result fields (logic in core/search/ignored-privacy-labels.ts)
-src/commands/mcp-expose.ts runPublish 443 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
+src/commands/mcp-expose.ts runPublish 444 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 GBRA-583: one printInstallLinks call in the Next block (link building and lines live in core/connector-install-links.ts)
src/commands/migrate-engine.ts runMigrateEngine 405 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/sources.ts runAdd 365 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 fix wave 4 #5673: connector sources print that autopilot keeps them synced after the first sync
src/core/bootstrap/harness.ts applyHarness 1167 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 7fddaac9a5..63a6eab8c9 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -48,7 +48,7 @@ src/commands/eval-longmemeval.ts 1545 ratchet new row: crossed the 1500 unlisted
src/commands/doctor/checks/extraction-sync.ts 1503 ratchet +7 GBRA-130 A-1: links_extraction_lag held bucket and its retry fix (logic in core/extraction-lag.ts heldExtractionReport); +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge); +1 #7145: content_hash_duplicates reads one group past its list to report a floor ("at least 50"); +3 #7462: atom_provenance_drift resolves a renamed source page through its rename alias (one join; the alias rule lives in core/persistence/atom-origin.ts)
src/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)
src/commands/config.ts 1546 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal); +4 GBRA-377 PR B: skills.resolver.* file-plane routing (doc line, the one-line router and its two dispatch lines; logic in core/setup/skill-resolver-config.ts); +8 train C: #8921 #7346 nested credential redaction on top of master's config growth; +1 train C: #9145 config.ts edit on top of #8921 #7346; +7 #8920: plural, acronym and credential secret words with the count-word exception (isSensitiveConfigKey) and URL userinfo masking (redactConfigValue)
-src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)
+src/commands/mcp-expose.ts 1524 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts); +5 GBRA-583: one-click Cursor/Claude link lines in the Next block and verified --status, and install_links in --json (builders live in core/connector-install-links.ts)
src/core/behavior-change-notice.ts 1774 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7); +1 GST-2228 recreated_takes_section_keeps_stored_takes_gst2228 row (since TBD; re-summed at the keep-takes-and-link-dates train merge: 1713 + 1); +1 GST-2228 links_rows_keep_own_dates_gst2228 row (since TBD; re-summed at the same train merge: 1714 + 1); +2 the W1 + memory proposals train (#9133): attest_every_page_write_deferred_gst2249 and memory_proposals_owner_http_gst2407 rows (rows are data and cannot move), re-summed at the #9138 v0.60.661.0 stack merge: 1715 + 2 = 1717 measured; +1 #8903 effect_git_secret_gate_gst1923 row (rows are data and cannot move), re-summed at the 0.60.664.0 stack on #9142 3931adb4: 1717 + 1; +1 GST-2407 PR 3: qm_recall_own_page_contract_v4 row (rows are data and cannot move), re-summed at the 0.60.666.0 stack on #9148 69c12917: 1718 + 1; +2 GST-363 PR 1 and PR 3 (#9135): the serves_several_labels_gst363 and stdio_member_per_harness_gst363 rows; +3 #9134 train rows member_forget_names_host_9101, refresh_fence_retry_id_gst2353 and recorded_read_view_args_gst2214 (rows are data and cannot move), re-summed at the #9134 slot merge onto #8829 dfc24954: 1721 + 3; +3 source-checkouts wave rows (autopilot_git_reconcile_gbra386, unknown_drift_history_rescreen, refresh_abandon_members_gst1465), re-summed at the #9137 stack merge: 1724 + 3; persistence train 13 at 0.60.676.0: its five rows on top of 0.60.675.0; +1 GST-2250 reconcile_publish_opt_out_gst2250 row (since TBD until the merge slot; rows are data and cannot move); +1 #8902 unmanaged_push_history_scan_8902 row (re-summed at the 0.60.678.0 stack on 501742d9: 1733 + 1); +1 GST-2246 maintain_safe_free_phases_gst2246 row (since TBD until the merge slot; rows are data and cannot move), re-summed on the doctor/dream/enrich train at the 0.60.679.0 slot merge onto #9170 82932eda: 1734 + 1; +2 GST-2462 privacy_label_ignored_gst2462 and access_page_rules_gst2462 rows (rows are data and cannot move), re-summed at the #9173 slot merge onto 49a922ef: 1735 + 2; +1 GST-2107 follow-up write_capacity_low_not_refusal_gst2107 row (rows are data and cannot move), re-summed at the 0.60.681.0 slot merge onto #9173 c08d0c8b: 1737 + 1; +1 GST-2490: owner_reads_derived_gst2490 row (rows are data and cannot move); +1 GST-2468: the label_only_operator_repairs_gst2468 row (a BEHAVIOR_CHANGES row cannot move); +1 GST-2446 remember_pageless_reply_gst2446, +1 GST-2492 strict_held_facts_gst2492 and +1 GST-2346 D1 owner_facts_shared_gst2346 rows (rows are data and cannot move), re-summed at the 0.60.685.0 train merge onto #9181 405ea4cf: 1740 + 3; +1 GST-2476: the readers_label_setter_gst2476 row (rows are data and cannot move), re-summed at the #9184 slot merge onto the #9179 train 361d57c6: 1743 + 1; +1 GST-2487: the fence_fact_private_in_place_gst2487 row (rows are data and cannot move), at the same slot merge of #9188 0075f09a: 1744 + 1; +1 GST-2515: the sync_status_commits_waiting_gst2515 row (rows are data and cannot move), at the 0.60.688.0 slot merge onto 599b1234: 1745 + 1; +3 GST-2519: commit_push_untrack_gst2519, db_only_labels_kept_gst2519 and git_ignored_label_repair_gst2519 rows (rows are data and cannot move), re-summed at the 0.60.691.0 slot merge onto #9167 ad4f0aef: 1746 + 3; +3 GST-2492 PR 2: the remember_pageless_ask, strict_fact_writers_held and sync_strict_requires_managed rows (rows are data and cannot move), re-summed at the master v0.60.691.0 merge: 1749 + 3; +3 GST-2346 rows owner_forget_private, owner_forget_readers_page and member_save_withdrawn_scope (rows are data and cannot move), re-summed at the 0.60.693.0 slot merge onto #9202 840858e9: 1752 + 3; +2 GST-2518 page_label_widening_held_gst2518 and GST-2521 owner_labels_guarded_gst2521 rows and +1 GST-2511 fence_fact_widening_held_gst2511 row (rows are data and cannot move), re-summed at the 0.60.694.0 slot merge onto master 2c8320d7: 1755 + 3; +3 the GST-2515/GST-2520 notifier_retry_unwatched_gst2515 and strict_skip_mode_refusal_gst2520 rows and the GST-2456 unmanaged_push_every_site_gst2456 row, re-summed at the 0.60.698.0 slot merge onto #9217 887398f0: 1758 + 3; +2 GST-2407: context_pack scope read and attestRead over the owner route; +9 releases per batch: the generated-table import, the releasedIn helper and its comment, the spread of RELEASED_BEHAVIOR_CHANGES; new rows now live in behavior-changes.d/ and stop growing this file (re-summed at the master v0.60.704.0 merge: 1763 + 9 = 1772 measured); +2 #7646 (GBRA-404 salvage): the disclosure lists releases oldest first whatever the table order
src/core/git/commit-push.ts 1615 ratchet GST-2519: --untrack (#7753 port: untrackTargets, untrackPaths; untrackAdmitted, the managed-worktree storage.db_only admission; previewUntrack) and the staged-removal hint in skippedPathsError grow the commit door past the 1500 default (master 1487 + 140); GST-2456 (#9174): crossed the 1500 unlisted cap at the GST-2456 merge of master v0.60.678.0: pushBase (the scan base and lease read live from every push URL, #5138) and the scan budget and progress options; Ctx and publish internals keep it in this file (1487 + 31), re-summed at the master 0c577834 merge into #9198: 1627 + 31; +47 #8928 salvage rebuild (GBRA-404) #7752: previewPaths (the dry run asks git against a copied index), admitPaths/flaggedEntries/previewRoots split out of commitPaths and shared with it, settlePending exported (re-summed on master v0.60.699.0: 1658 + 47); +1 GBRA-404 /ship round 2: the dry run stages into its temporary index copy for real (staged-rename partner refusal); GST-2767: the git runner (git-run.ts) and the skipped-path checks with their reasons (skipped-paths.ts) moved out, 1600; +14 GST-2767 staged_for_removal refusal and dry-run skipped-path parity; +1 commit_paths_unmerged: admitPaths calls assertNoUnmergedPaths (skipped-paths.ts)
src/commands/auth.ts 1512 ratchet new row: crossed the 1500 unlisted cap at the v0.60.595.0 merge: GST-1113 --attest-sources help lines plus GST-1158 F3 --attest-read help lines (3); CLI help lines cannot move; re-measured at the Train A merge onto master v0.60.708.0: 1503 + 2 (the #8930 shared-token notice) = 1505; re-measured at the Train C merge onto Train B (#9246 onto #9223): 1505 -> 1509, both sides' growth; +3 Wakeshift PR 2 (#8709), one line each: revoke (by name) calls forgetWakePrincipal for every token row its UPDATE returned (RETURNING 1 became RETURNING id, so no line added there), revokeById calls it for the revoked token id, and revokeClient calls it for the revoked OAuth client id; each call ends that principal's open watches and queues its Wakeshift forget (logic in core/wakeshift/forget.ts) after the command's own UPDATE/DELETE; master 1509 + 3 = 1512
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 071c8ac5f8..bf4589f08e 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -94,6 +94,7 @@ test/compile-view.test.ts compileView — determinism 3 readFileSync
test/compile-view.test.ts compileView — source isolation + read errors 3 readFileSync
test/config.test.ts config source correctness 1 readFileSync
test/connection-resilience.test.ts Eng-review D3 — executeRaw has no per-call retry wrapper 3 readFileSync,source-surface-helper
+test/connector-install-links.test.ts docs carry the hosted gbrain.io links the helpers build 2 readFileSync
test/context-audit-skill.test.ts #4988 context-audit skill token estimate 2 readFileSync
test/contextual-retrieval-service-pure.test.ts inline import contextual synopsis containment 1 readFileSync
test/conversation-facts-type-allowlist-drift.test.ts (file-level) 18 readFileSync
diff --git a/src/commands/mcp-expose.ts b/src/commands/mcp-expose.ts
index ffbbc5b8ae..e2e60b4b74 100644
--- a/src/commands/mcp-expose.ts
+++ b/src/commands/mcp-expose.ts
@@ -48,6 +48,7 @@ import {
type ExposeReceipt, type ServiceState, type ServiceTarget, type UninstallServiceResult,
} from '../core/serve-service.ts';
import { registrationAdvertise, shellQuote } from '../core/mcp-registration.ts';
+import { connectorInstallLinks, installLinkLines, printInstallLinks, type ConnectorInstallLinks } from '../core/connector-install-links.ts';
import { cliRenderContext, renderNotice } from '../core/agent-output.ts';
import { EXPOSE_FRICTION_REASONS, hostedOptionLine, hostedOptionMuted, hostedOptionNotice } from '../core/onboard/hosted-option.ts';
@@ -323,7 +324,7 @@ class Session {
this.checks.push(c);
return c;
}
- finish(status: ExposeStatus, code: number, extra: { receipt?: ExposeReceipt | null; reason?: string; message?: string; plan?: string[]; consent?: Record<string, unknown> } = {}): number {
+ finish(status: ExposeStatus, code: number, extra: { receipt?: ExposeReceipt | null; reason?: string; message?: string; plan?: string[]; consent?: Record<string, unknown>; installLinks?: ConnectorInstallLinks } = {}): number {
const where = EXPOSE_FRICTION_REASONS.has(extra.reason ?? '') ? 'mcp_expose_friction'
: this.firstPublish && (status === 'exposed' || status === 'pending') ? 'mcp_expose' : null;
const hosted = where ? hostedOptionNotice(where, this.d.mutedNotices()) : null;
@@ -333,7 +334,7 @@ class Session {
this.d.out(JSON.stringify({
status, receipt: extra.receipt ?? null, checks: this.checks, next_actions: this.nextActions,
...(extra.reason ? { reason: extra.reason } : {}), ...(extra.message ? { message: extra.message } : {}), ...(extra.plan ? { plan: extra.plan } : {}),
- ...(extra.consent ?? {}), ...(hosted ? { notices: [renderNotice(hosted, cliRenderContext())] } : {}),
+ ...(extra.consent ?? {}), ...(hosted ? { notices: [renderNotice(hosted, cliRenderContext())] } : {}), ...(extra.installLinks?.cursor ? { install_links: extra.installLinks } : {}),
}));
}
return code;
@@ -1044,6 +1045,7 @@ async function runPublish(d: Resolved, s: Session, opts: ExposeOptions): Promise
const local = localAgentGuidance(engine, opts.port, ownerCredential);
s.say(` Local agents ${local.lines[0]}`);
for (const line of local.lines.slice(1)) s.say(` ${line}`);
+ const installLinks = printInstallLinks(receipt.mcp_url, mode === 'funnel', (line) => s.say(line));
s.say(' Check gbrain mcp expose --status');
s.nextActions.push(
`gbrain mcp grant <name> --harness <id> --profile memory-writer --source default --url ${receipt.mcp_url} --admin-token-file ${ownerCredential} --credentials-out /private/<name>.json`,
@@ -1053,7 +1055,7 @@ async function runPublish(d: Resolved, s: Session, opts: ExposeOptions): Promise
'gbrain mcp expose --status',
);
const pending = tailnetHealth === 'pending' || localHealth === 'timeout';
- return s.finish(pending ? 'pending' : 'exposed', pending ? 2 : 0, { receipt, ...(pending ? { reason: tailnetHealth === 'pending' ? 'tailnet_health_pending' : 'local_health_timeout' } : {}) });
+ return s.finish(pending ? 'pending' : 'exposed', pending ? 2 : 0, { receipt, installLinks, ...(pending ? { reason: tailnetHealth === 'pending' ? 'tailnet_health_pending' : 'local_health_timeout' } : {}) });
}
/** The user's publish flags, for a re-run hint or the approved command (never --yes/--json/--dry-run). */
@@ -1141,7 +1143,10 @@ async function runStatus(d: Resolved, s: Session, opts: ExposeOptions): Promise<
// certificate is reported as `pending` (not `error`) so callers can tell
// "wait a minute" from "broken", but it is still a non-zero exit.
if (pending) { s.nextActions.push('gbrain mcp expose --status'); return s.finish('pending', 1, { receipt, reason: 'tailnet_health_pending', message: 'tailnet health still pending (first certificate issuance can take a minute) — re-run --status shortly.' }); }
- return s.finish('exposed', 0, { receipt });
+ const installLinks = connectorInstallLinks(receipt.mcp_url, receipt.mode === 'funnel');
+ const linkLines = installLinkLines(installLinks, receipt.mode === 'funnel');
+ for (const line of linkLines.length ? ['', ...linkLines] : []) s.say(line);
+ return s.finish('exposed', 0, { receipt, installLinks });
}
interface Leftovers {
diff --git a/src/commands/publish.ts b/src/commands/publish.ts
index 54498ab555..06d8743713 100644
--- a/src/commands/publish.ts
+++ b/src/commands/publish.ts
@@ -125,6 +125,17 @@ const CSS = `
a:hover { text-decoration: underline; }
strong { font-weight: 600; }
code { background: var(--code-bg); padding: 2px 6px; border-radius: 4px; font-size: 0.9em; }
+ pre { background: var(--code-bg); border: 1px solid var(--border); border-radius: 8px; padding: 0.75rem 1rem; margin: 1rem 0; overflow-x: auto; line-height: 1.5; }
+ pre code { background: none; padding: 0; border-radius: 0; font-size: 0.85em; }
+ .code-block { position: relative; margin: 1rem 0; }
+ .code-block pre { margin: 0; padding-right: 4.5rem; }
+ .copy-btn {
+ position: absolute; top: 0.5rem; right: 0.5rem;
+ font: inherit; font-size: 12px; line-height: 1; padding: 0.35rem 0.6rem;
+ color: var(--muted); background: var(--card-bg); border: 1px solid var(--border); border-radius: 6px; cursor: pointer;
+ }
+ .copy-btn:hover, .copy-btn:focus-visible { color: var(--fg); border-color: var(--accent); }
+ .copy-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
hr { border: none; border-top: 1px solid var(--border); margin: 2rem 0; }
table { width: 100%; border-collapse: collapse; margin: 1rem 0; font-size: 14px; }
th, td { padding: 8px 12px; border: 1px solid var(--border); text-align: left; }
@@ -210,7 +221,7 @@ async function unlock(pw, remember) {
try { localStorage.setItem(STORAGE_KEY, pw); } catch {}
}
document.getElementById('pw-overlay').remove();
- document.getElementById('content').innerHTML = marked.parse(result);
+ renderPage(result);
return true;
}
return false;
@@ -247,6 +258,62 @@ async function unlock(pw, remember) {
})();
`;
+// Runs in the published page. Renders markdown through the sanitizer, then adds
+// a copy button to every code block. The buttons are built with DOM calls and
+// wired with addEventListener after sanitizing, so no page content can reach
+// them and the sanitizer never has to allow an inline handler.
+const RENDER_JS = `
+function copyText(text) {
+ if (navigator.clipboard && window.isSecureContext) return navigator.clipboard.writeText(text);
+ return new Promise((resolve, reject) => {
+ const area = document.createElement('textarea');
+ area.value = text;
+ area.setAttribute('readonly', '');
+ area.style.position = 'fixed';
+ area.style.opacity = '0';
+ document.body.appendChild(area);
+ area.select();
+ let copied = false;
+ try { copied = document.execCommand('copy'); } catch {}
+ area.remove();
+ copied ? resolve() : reject(new Error('copy failed'));
+ });
+}
+
+function addCopyButtons(root) {
+ for (const pre of root.querySelectorAll('pre')) {
+ const code = pre.querySelector('code');
+ if (!code) continue;
+ const block = document.createElement('div');
+ block.className = 'code-block';
+ pre.replaceWith(block);
+ block.appendChild(pre);
+ const button = document.createElement('button');
+ button.type = 'button';
+ button.className = 'copy-btn';
+ const show = (text, label) => { button.textContent = text; button.setAttribute('aria-label', label); };
+ show('Copy', 'Copy code block');
+ let reset;
+ button.addEventListener('click', () => {
+ copyText(code.textContent.replace(/\\n$/, '')).then(
+ () => show('Copied', 'Copied'),
+ () => show('Select and copy', 'Copy failed, select the text and copy it'),
+ ).finally(() => {
+ clearTimeout(reset);
+ reset = setTimeout(() => show('Copy', 'Copy code block'), 1500);
+ });
+ });
+ block.appendChild(button);
+ }
+}
+
+function renderPage(markdown) {
+ const content = document.getElementById('content');
+ content.innerHTML = sanitizeHtml(marked.parse(markdown));
+ addCopyButtons(content);
+}
+`;
+
function escapeHtml(str: string): string {
return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
@@ -298,13 +365,9 @@ export function generateHtml({ title, markdown, encrypted }: GenerateHtmlOptions
`;
const contentScript = encrypted
- ? `<script>${sanitizeScript}${DECRYPT_JS.replace(
- 'document.getElementById(\'content\').innerHTML = marked.parse(result)',
- 'document.getElementById(\'content\').innerHTML = sanitizeHtml(marked.parse(result))'
- )}<\/script>`
- : `<script>${sanitizeScript}
- const md = ${JSON.stringify(markdown)};
- document.getElementById('content').innerHTML = sanitizeHtml(marked.parse(md));
+ ? `<script>${sanitizeScript}${RENDER_JS}${DECRYPT_JS}<\/script>`
+ : `<script>${sanitizeScript}${RENDER_JS}
+ renderPage(${JSON.stringify(markdown).replace(/</g, '\\u003c')});
<\/script>`;
return `<!DOCTYPE html>
diff --git a/src/core/connector-install-links.ts b/src/core/connector-install-links.ts
new file mode 100644
index 0000000000..dd105d1bdc
--- /dev/null
+++ b/src/core/connector-install-links.ts
@@ -0,0 +1,64 @@
+/**
+ * One-click links that open an MCP client's own "add server" step with this
+ * brain's MCP URL already filled in. The user still reviews the form and signs
+ * in inside the client; a link never carries a credential.
+ *
+ * Cursor: its documented install deeplink (cursor.com/docs/mcp/install-links).
+ * Cursor connects from the user's own machine, so a tailnet-only URL works.
+ *
+ * Claude: the add-custom-connector form on claude.ai, documented by Anthropic
+ * as the custom connector install link
+ * (claude.com/docs/connectors/building/directory-vs-custom). claude.ai connects
+ * from Anthropic's cloud, so the link is offered only for a public URL.
+ */
+
+export interface ConnectorInstallLinks {
+ claude?: string;
+ cursor?: string;
+}
+
+function linkableUrl(mcpUrl: string): string | null {
+ let url: URL;
+ try {
+ url = new URL(mcpUrl);
+ } catch {
+ return null;
+ }
+ if (url.protocol !== 'https:' || !url.hostname || url.username || url.password) return null;
+ return url.href;
+}
+
+export function cursorInstallLink(mcpUrl: string, name = 'gbrain'): string | null {
+ const url = linkableUrl(mcpUrl);
+ if (!url) return null;
+ const config = Buffer.from(JSON.stringify({ url })).toString('base64');
+ return `cursor://anysphere.cursor-deeplink/mcp/install?name=${encodeURIComponent(name)}&config=${encodeURIComponent(config)}`;
+}
+
+export function claudeConnectorLink(mcpUrl: string, name = 'GBrain'): string | null {
+ const url = linkableUrl(mcpUrl);
+ if (!url) return null;
+ return `https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=${encodeURIComponent(name)}&connectorUrl=${encodeURIComponent(url)}`;
+}
+
+/** Claude only when `isPublic` (claude.ai cannot reach a tailnet-only URL); Cursor whenever the URL is linkable. */
+export function connectorInstallLinks(mcpUrl: string, isPublic: boolean): ConnectorInstallLinks {
+ const claude = isPublic ? claudeConnectorLink(mcpUrl) : null;
+ const cursor = cursorInstallLink(mcpUrl);
+ return { ...(claude ? { claude } : {}), ...(cursor ? { cursor } : {}) };
+}
+
+/** The human lines for `gbrain mcp expose` and `--status`, in the Next block's two-column layout. */
+export function installLinkLines(links: ConnectorInstallLinks, isPublic: boolean): string[] {
+ const lines: string[] = [];
+ if (links.claude) lines.push(` Claude ${links.claude}`, ' Opens Claude\'s add-connector form with this URL filled in; review it and sign in there.');
+ if (links.cursor) lines.push(` Cursor ${links.cursor}`, ` Opens Cursor's MCP install prompt with this URL filled in${isPublic ? '.' : '; the Cursor machine must be on your tailnet.'}`);
+ return lines;
+}
+
+/** Builds the links, prints their lines through `say`, and returns the links for the JSON document. */
+export function printInstallLinks(mcpUrl: string, isPublic: boolean, say: (line: string) => void): ConnectorInstallLinks {
+ const links = connectorInstallLinks(mcpUrl, isPublic);
+ for (const line of installLinkLines(links, isPublic)) say(line);
+ return links;
+}
diff --git a/test/connector-install-links.test.ts b/test/connector-install-links.test.ts
new file mode 100644
index 0000000000..3b0a109bf2
--- /dev/null
+++ b/test/connector-install-links.test.ts
@@ -0,0 +1,103 @@
+import { describe, expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { claudeConnectorLink, connectorInstallLinks, cursorInstallLink, installLinkLines } from '../src/core/connector-install-links.ts';
+
+const HOSTED = 'https://gbrain.io/mcp';
+const TAILNET = 'https://your-machine.your-tailnet.ts.net/mcp';
+const HOSTED_CLAUDE = 'https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=GBrain&connectorUrl=https%3A%2F%2Fgbrain.io%2Fmcp';
+const HOSTED_CURSOR = 'cursor://anysphere.cursor-deeplink/mcp/install?name=gbrain&config=eyJ1cmwiOiJodHRwczovL2dicmFpbi5pby9tY3AifQ%3D%3D';
+const UNLINKABLE = [
+ 'http://your-machine.your-tailnet.ts.net/mcp',
+ 'http://127.0.0.1:3131/mcp',
+ 'file:///etc/passwd',
+ 'javascript:alert(1)',
+ 'not a url',
+ '',
+ ['https://alice-example', '[email protected]/mcp'].join(':'),
+ 'https://[email protected]/mcp',
+ 'https://:[email protected]/mcp',
+];
+
+describe('cursorInstallLink', () => {
+ test('is Cursor\'s documented deeplink with base64(JSON {url}) as config', () => {
+ expect(cursorInstallLink(HOSTED)).toBe(HOSTED_CURSOR);
+ });
+
+ test('base64-encodes first, then URL-encodes, so + / = never reach the query raw', () => {
+ const url = 'https://brain.example.com/mcp?q=a~aa?';
+ const raw = Buffer.from(JSON.stringify({ url })).toString('base64');
+ expect(raw).toMatch(/\+/);
+ expect(raw).toMatch(/\//);
+ expect(raw).toMatch(/=/);
+ const link = cursorInstallLink(url)!;
+ const config = link.slice(link.indexOf('&config=') + '&config='.length);
+ expect(config).toBe(encodeURIComponent(raw));
+ expect(config).not.toMatch(/[+/=]/);
+ expect(JSON.parse(Buffer.from(decodeURIComponent(config), 'base64').toString('utf-8'))).toEqual({ url });
+ });
+
+ test('a space in the name is %20', () => {
+ expect(cursorInstallLink(HOSTED, 'my brain')).toStartWith('cursor://anysphere.cursor-deeplink/mcp/install?name=my%20brain&config=');
+ });
+
+ test('no link for anything but a credential-free absolute https URL', () => {
+ for (const url of UNLINKABLE) expect(cursorInstallLink(url)).toBeNull();
+ });
+});
+
+describe('claudeConnectorLink', () => {
+ test('is the claude.ai add-custom-connector form with name and URL filled in', () => {
+ expect(claudeConnectorLink(HOSTED)).toBe(HOSTED_CLAUDE);
+ });
+
+ test('a space in the name is %20, and URL query characters stay inside connectorUrl', () => {
+ const url = 'https://brain.example.com/mcp?a=1&modal=other';
+ const link = claudeConnectorLink(url, 'My Brain')!;
+ expect(link).toBe(`https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=My%20Brain&connectorUrl=${encodeURIComponent(url)}`);
+ const params = new URL(link).searchParams;
+ expect(params.getAll('modal')).toEqual(['add-custom-connector']);
+ expect(params.get('connectorUrl')).toBe(url);
+ });
+
+ test('no link for anything but a credential-free absolute https URL', () => {
+ for (const url of UNLINKABLE) expect(claudeConnectorLink(url)).toBeNull();
+ });
+});
+
+describe('connectorInstallLinks', () => {
+ test('public URL: Claude and Cursor; tailnet-only: Cursor only; unlinkable: nothing', () => {
+ expect(connectorInstallLinks(TAILNET, true)).toEqual({ claude: claudeConnectorLink(TAILNET)!, cursor: cursorInstallLink(TAILNET)! });
+ expect(connectorInstallLinks(TAILNET, false)).toEqual({ cursor: cursorInstallLink(TAILNET)! });
+ for (const url of UNLINKABLE) {
+ expect(connectorInstallLinks(url, true)).toEqual({});
+ expect(connectorInstallLinks(url, false)).toEqual({});
+ }
+ });
+
+ test('installLinkLines prints one labelled line per link plus a short note, and nothing for no links', () => {
+ const pub = installLinkLines(connectorInstallLinks(TAILNET, true), true);
+ expect(pub[0]).toBe(` Claude ${claudeConnectorLink(TAILNET)}`);
+ expect(pub).toContain(` Cursor ${cursorInstallLink(TAILNET)}`);
+ expect(pub.join('\n')).not.toContain('must be on your tailnet');
+ const tailnet = installLinkLines(connectorInstallLinks(TAILNET, false), false);
+ expect(tailnet[0]).toBe(` Cursor ${cursorInstallLink(TAILNET)}`);
+ expect(tailnet.join('\n')).toContain('the Cursor machine must be on your tailnet');
+ expect(tailnet.join('\n')).not.toContain('claude.ai');
+ expect(installLinkLines({}, true)).toEqual([]);
+ });
+});
+
+describe('docs carry the hosted gbrain.io links the helpers build', () => {
+ const doc = (p: string) => readFileSync(join(import.meta.dir, '..', p), 'utf-8');
+ test('docs/mcp/README.md has both hosted links', () => {
+ expect(doc('docs/mcp/README.md')).toContain(claudeConnectorLink(HOSTED)!);
+ expect(doc('docs/mcp/README.md')).toContain(cursorInstallLink(HOSTED)!);
+ });
+ test('docs/mcp/CLAUDE_DESKTOP.md has the hosted Claude link above its manual steps', () => {
+ const text = doc('docs/mcp/CLAUDE_DESKTOP.md');
+ const at = text.indexOf(claudeConnectorLink(HOSTED)!);
+ expect(at).toBeGreaterThan(-1);
+ expect(at).toBeLessThan(text.indexOf('## 2. Add the integration'));
+ });
+});
diff --git a/test/mcp-expose.test.ts b/test/mcp-expose.test.ts
index ee278e7d37..3eb1a3f8ce 100644
--- a/test/mcp-expose.test.ts
+++ b/test/mcp-expose.test.ts
@@ -1388,6 +1388,69 @@ describe('--status edges', () => {
});
});
+describe('one-click client links', () => {
+ const MCP = `https://${DNS}/mcp`;
+ const CLAUDE_LINE = ` Claude https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=GBrain&connectorUrl=${encodeURIComponent(MCP)}`;
+ const CURSOR_LINK = `cursor://anysphere.cursor-deeplink/mcp/install?name=gbrain&config=${encodeURIComponent(Buffer.from(JSON.stringify({ url: MCP })).toString('base64'))}`;
+ const CLAUDE_LINK = CLAUDE_LINE.trim().slice('Claude'.length).trim();
+ test('a Funnel publish prints the Claude and Cursor lines in the Next block', async () => {
+ const f = fakeTailnet();
+ expect(await runMcpExpose(['--yes', '--funnel'], f.deps)).toBe(0);
+ const out = f.stdout.join('\n');
+ const next = out.slice(out.indexOf('Next — choose the connection method'));
+ expect(next).toContain(CLAUDE_LINE);
+ expect(next).toContain(` Cursor ${CURSOR_LINK}`);
+ expect(next).not.toContain('must be on your tailnet');
+ expect(out).not.toContain(TOKEN);
+ });
+ test('a tailnet-only publish prints the Cursor line only, with the tailnet note', async () => {
+ const f = fakeTailnet();
+ expect(await runMcpExpose(['--yes'], f.deps)).toBe(0);
+ const out = f.stdout.join('\n');
+ expect(out).toContain(` Cursor ${CURSOR_LINK}`);
+ expect(out).toContain('the Cursor machine must be on your tailnet');
+ expect(out).not.toContain('claude.ai/customize');
+ });
+ test('--json carries install_links (Claude only with Funnel), and --status --json repeats them', async () => {
+ const f = fakeTailnet();
+ expect(await runMcpExpose(['--yes', '--funnel', '--json'], f.deps)).toBe(0);
+ expect(jsonDoc(f).install_links).toEqual({ claude: CLAUDE_LINK, cursor: CURSOR_LINK });
+ f.stdout.length = 0;
+ expect(await runMcpExpose(['--status', '--json'], f.deps)).toBe(0);
+ expect(jsonDoc(f).install_links).toEqual({ claude: CLAUDE_LINK, cursor: CURSOR_LINK });
+ const g = fakeTailnet();
+ expect(await runMcpExpose(['--yes', '--json'], g.deps)).toBe(0);
+ expect(jsonDoc(g).install_links).toEqual({ cursor: CURSOR_LINK });
+ g.stdout.length = 0;
+ expect(await runMcpExpose(['--status', '--json'], g.deps)).toBe(0);
+ expect(jsonDoc(g).install_links).toEqual({ cursor: CURSOR_LINK });
+ });
+ test('human --status prints the link lines when everything verifies', async () => {
+ const f = fakeTailnet();
+ expect(await runMcpExpose(['--yes', '--funnel'], f.deps)).toBe(0);
+ f.stdout.length = 0;
+ expect(await runMcpExpose(['--status'], f.deps)).toBe(0);
+ const out = f.stdout.join('\n');
+ expect(out).toContain(CLAUDE_LINE);
+ expect(out).toContain(` Cursor ${CURSOR_LINK}`);
+ });
+ test('a non-https receipt URL (--no-tailscale) prints no link lines and no install_links key', async () => {
+ const f = fakeTailnet();
+ expect(await runMcpExpose(['--yes', '--no-tailscale'], f.deps)).toBe(0);
+ expect(f.stdout.join('\n')).not.toMatch(/cursor:\/\/|claude\.ai|^ {2}(Claude|Cursor) /m);
+ f.stdout.length = 0;
+ expect(await runMcpExpose(['--status'], f.deps)).toBe(0);
+ expect(f.stdout.join('\n')).not.toMatch(/cursor:\/\/|claude\.ai/);
+ const g = fakeTailnet();
+ expect(await runMcpExpose(['--yes', '--no-tailscale', '--json'], g.deps)).toBe(0);
+ expect(jsonDoc(g).receipt.mcp_url).toBe('http://127.0.0.1:3131/mcp');
+ expect('install_links' in jsonDoc(g)).toBe(false);
+ g.stdout.length = 0;
+ expect(await runMcpExpose(['--status', '--json'], g.deps)).toBe(0);
+ expect('install_links' in jsonDoc(g)).toBe(false);
+ });
+});
+
describe('--remove edges', () => {
test('binary gone → handler left with a warning; a --no-tailscale receipt has nothing to undo; a skipped receipt with no service → none installed (interactive yes); an undeletable wrapper is a note', async () => {
const f = fakeTailnet();
diff --git a/test/publish.test.ts b/test/publish.test.ts
index 962d954485..c730d7fe0c 100644
--- a/test/publish.test.ts
+++ b/test/publish.test.ts
@@ -210,6 +210,24 @@ describe('generateHtml', () => {
expect(html).toContain('prefers-color-scheme: dark');
});
+ test('markdown that contains a closing script tag cannot end the page script', () => {
+ const html = generateHtml({ title: 'T', markdown: '```html\n</script><img src=x onerror=alert(1)>\n```' });
+ const body = html.slice(html.lastIndexOf('<script>'));
+ expect(body.match(/<\/script>/gi)?.length).toBe(1);
+ expect(body).toContain('\\u003c/script>\\u003cimg src=x onerror=alert(1)>');
+ });
+
+ test('both page kinds render through the sanitizer with no inline handlers or outside resources', () => {
+ for (const encrypted of [null, encryptContent('# x', 'pw')]) {
+ const html = generateHtml({ title: 'T', markdown: '# x', encrypted });
+ expect(html).toContain('content.innerHTML = sanitizeHtml(marked.parse(markdown))');
+ expect(html).not.toMatch(/innerHTML = marked\.parse/);
+ expect(html).toContain("addEventListener('click'");
+ expect(html).not.toMatch(/<[a-z]+[^>]*\son[a-z]+=/i);
+ expect(html).not.toMatch(/\s(src|href)=["']?https?:/i);
+ }
+ });
+
test('inlines marked.js (no CDN dependency)', () => {
const html = generateHtml({ title: 'T', markdown: 'x' });
expect(html).not.toContain('cdn.jsdelivr.net');