Skip to content

feat(cli): add squirrel channel to push cloud audit events into Claude Code - #571

Merged
nc9 merged 7 commits into
mainfrom
claude/pub-569-squirrel-channel
Oct 8, 2026
Merged

nc9 merged 7 commits into
mainfrom
claude/pub-569-squirrel-channel

Conversation

@nc9

@nc9 nc9 commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

What changed and why

Adds squirrel channel, a stdio MCP server that Claude Code registers as a channel. It polls the logged-in org's cloud notification feed (GET /v1/notifications) and pushes audit_complete, audit_failed and issues_detected events into a running session, so the agent can triage without being asked.

  • Lives in apps/cli/src/channel/, separate from apps/cli/src/mcp/server.ts. It uses the low-level Server from @modelcontextprotocol/sdk v1, which negotiates up to 2025-11-25 (Claude Code refuses channels that negotiate 2026-07-28), so a later migration of squirrel mcp leaves it alone.
  • Declares capabilities.experimental['claude/channel'] only. No permission relay.
  • Event content is built from category and validated ids, counts and fixed strings. Titles and bodies are dropped at parse time, so crawled text never reaches the agent. Meta keys are category, website_id, run_id, audit_id, domain, notification_id, reason_code.
  • State (cursor plus a bounded seen-set) is persisted per org in ~/.squirrel/channel/<org id>.json. First run starts from now and replays nothing.
  • No login: one login_required event, then the server keeps running and picks up a later login without a restart.
  • --interval (default 30s, min 5) and --categories are configurable. 429, 5xx and network errors back off exponentially up to 10 minutes.
  • Registered in the citty tree, help, shell completions (bash, zsh, fish) and the no-startup-extras list (stdout is JSON-RPC).
  • Docs: docs/developers/channel.mdx (including the allowlist and development-flag caveats) and docs/cli/channel.mdx.

Cloud cursor dependency

The cloud feed is gaining an after=<cursor> parameter and a next_cursor on every response, which is tracked on the cloud side. The channel supports both shapes:

  • Cursor feed: one call without after to get a starting cursor, then after=next_cursor (oldest first).
  • No next_cursor in the response (today): it reads the newest-first page and de-dupes by notification id and by run (a run produces a user-scoped and an org-scoped row) with a bounded persisted seen-set. In this mode, more than 50 new notifications between polls can be missed.

It switches between the two automatically.

Acceptance criteria

  • squirrel channel starts a stdio server registered as a channel: tests/channel/server.test.ts (capabilities), tests/channel/e2e.test.ts (real CLI over stdio).
  • A new audit event reaches the session with category, website_id, run_id, domain meta and a one-line summary: tests/channel/e2e.test.ts, tests/channel/events.test.ts. Latency is one poll interval (default 30s).
  • audit_failed and issues_detected are delivered and categories are configurable (--categories): events.test.ts, poller.test.ts, parseCategories test.
  • Events missed while closed are delivered exactly once: poller.test.ts ("a restart catches up exactly once", legacy de-dupe tests).
  • No crawled text in content: events.test.ts ("never echoes title, body or free text").
  • No login emits one event and does not crash: server.test.ts ("no login").
  • Configurable interval, backoff on 429/5xx: server.test.ts ("backoff", "429 and 5xx").
  • Completions updated: src/self/completion.ts.
  • Docs, including allowlist and development-flag caveats: docs/developers/channel.mdx.

Verification

In apps/cli: bun run typecheck, bun run lint, bun run format:check all clean. bun test tests/channel tests/cli tests/self/completion.test.ts tests/mcp: 314 pass, 0 fail. In docs/: make validate passes. The compiled binary (bun run build) was driven by an MCP client against a mocked feed and emitted a notifications/claude/channel event for the mocked row after the bootstrap poll, and persisted the cursor.

Notes for reviewers

  • The login command is squirrel auth login (there is no top-level squirrel login), so the event text uses that.
  • The feed is login-only (API keys are rejected), so a 401 or 403 produces the same login_required event.
  • compare_audits is named in the channel instructions as "when your squirrelscan server offers it": it is not a tool on the local or hosted servers today.

Agent skill

The squirrelscan agent skill needs a change (a new command and what the events mean). This is tracked privately.


Generated by Claude Code

@nc9
nc9 marked this pull request as ready for review October 8, 2026 09:54
@claude

claude Bot commented Oct 8, 2026

Copy link
Copy Markdown

Review of the new squirrel channel command. I read the source files in full. The diff was truncated partway through the test files, so I didn't read server.test.ts, the rest of poller.test.ts, or the docs. I didn't run the tests.

The design is sound. The injection defence is good: events are built only from re-validated ids, counts and fixed strings, titles and bodies are dropped at parse time, and events.test.ts and the e2e test both cover it. I found nothing that should block a merge.

  • (medium) apps/cli/src/channel/poller.ts:251-263 If emit throws partway through a page, store.save is never reached. On the next poll the whole page is re-delivered, so earlier rows in that page repeat. Going the other way, a row is marked seen before emit runs, so a row whose own emit fails is dropped once any later save succeeds. Consider marking a row seen only after its emit resolves, and saving per row or per page.
  • (low) apps/cli/src/channel/poller.ts:273-276 On a cursor-capable feed that returns next_cursor: null at first run, the state stays unbootstrapped. Anything created before the first poll that gets a cursor is then treated as history. This is acceptable but worth a comment.
  • (low) apps/cli/src/channel/poller.ts:298-302 If the server returns a full page with next_cursor: null, the cursor doesn't advance. The loop re-fetches the same page up to 10 times per poll (deduped, but wasteful). Break when the cursor doesn't change.
  • (low) apps/cli/src/cli/commands/channel.ts:718-724 There is no upper bound on --interval. A value above about 2^31 ms (~24.8 days, so --interval 3000000 or more) makes setTimeout fire after 1 ms, and that turns the loop into a tight poll against the API. Clamp the value, or reject it above a sensible maximum such as 1 day.
  • (low) apps/cli/src/channel/server.ts:465-472 On 401 or 403 the failure count is held at 1, so the retry delay stays at 2× the interval. That is fine. It also re-resolves the org on every retry, which costs an extra /v1/hydrate call each time. This is acceptable, but note it.
  • (low) apps/cli/src/channel/state.ts:652 mkdirSync is called without mode: 0o700. The state holds only a cursor and ids, so this is hygiene rather than a leak, but ~/.squirrel elsewhere is probably locked down.
  • (nit) apps/cli/src/channel/server.ts:561 export { FEED_PAGE_SIZE } re-exports a symbol nothing seems to need. Drop it if it's unused.
  • (nit) Test coverage is good. A poller test for "emit throws mid-page" would pin down the medium finding above.

nc9 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Pushed e061a26 addressing the review (one push, merged main in first so the branch is no longer behind).

Medium, fixed: deliver() in poller.ts now marks a row seen only after its emit resolves and saves state per row. If an emit throws mid-page, the cursor and later rows stay put, so the next poll retries from that row without repeating earlier ones. Test: "a throwing emit keeps the cursor and retries without repeating earlier rows".

Lows and nits:

  • A full page with an unchanged next_cursor now ends the poll instead of refetching (test added).
  • --interval is rejected above 86400 seconds, well below the setTimeout overflow.
  • The state directory is created with mode 0o700.
  • Dropped the unused FEED_PAGE_SIZE re-export.
  • Added a comment on the next_cursor: null first-run case.
  • Left as is: the extra /v1/hydrate call per retry after a 401 or 403 (retries are already at twice the interval).

Local gates on the merged tree: typecheck, lint and format clean, 316 tests pass (channel, cli, completions, mcp), make validate passes in docs/.

@claude

claude Bot commented Oct 8, 2026

Copy link
Copy Markdown

Review of squirrel channel. The design is solid and the security posture is good: titles and bodies are dropped at parse time, every id, domain and count is re-validated, the permission relay is not declared, and state files are written 0600 via an atomic rename. I found nothing blocking.

  • (medium) channel/server.ts runPollLoop: orgId and store are resolved once and cached until a login loss or a 401/403. If the user runs squirrel org switch while the session is open, events and state stay on the old org. Re-resolving the org periodically, or documenting the limitation, would avoid surprising cross-org delivery.
  • (low) channel/poller.ts deliver: if emit keeps throwing for one row (for example an oversized meta value rejected by the client), the cursor never advances past it and the channel is stuck on that row. The backoff caps at 10 minutes but never skips. Consider skipping a row after N consecutive failures.
  • (low) channel/poller.ts: in the legacy feed, a row that is not in the seen-set and falls off the 50-row page is lost, as the PR notes. The MAX_SEEN_KEYS limit of 500 is fine. A log line (debug or stderr) when a poll returns a full page of unseen rows would make this visible.
  • (low) channel/events.ts buildInstructions: the "fix the ones that live in this project's code" guidance does run a prompt-injection risk, because issue details are fetched through tools from crawled content. The closing "untrusted data" caveat helps. Consider wording it as "propose fixes" rather than directing edits.
  • (nit) cli/commands/channel.ts: the error says "between 1 and N" but the effective minimum is 5 (the value is silently clamped). Say so, or reject values below 5.
  • (nit) state.ts: join(path, "..") is better written with dirname(path).
  • (nit) Test coverage looks good (events, poller, server, e2e). There is no dedicated test for state.ts (corrupt file, seen-set truncation, atomic save) or for nextDelayMs/runPollLoop 401 recovery. I did not check whether the poller or server tests already cover these.

nc9 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Pushed to address the second review.

Medium, fixed: the channel now re-resolves the active org every 10 polls. On a switch it opens that org's own state and starts from now, so there is no cross-org delivery and no replay. A failed lookup keeps the current org. Tests: org switch, failed lookup, and 401 recovery without a restart. Docs no longer tell users to restart after switching.

Lows and nits:

  • Fixed: the instructions now say to "propose fixes" for findings that apply to the project, instead of directing edits.
  • Fixed: a debug line when a legacy poll returns a full page of unseen rows.
  • Fixed: --interval below 5 is now rejected with an accurate message (5 to 86400). dirname(path) replaces join(path, ".."). Added a state test for an oversized saved seen-set.
  • Not changed: skipping a row after repeated emit failures. Every meta value is validated and length-bounded, so no real input makes a single row fail forever, and skipping would silently drop an event.

Local gates: typecheck, lint, format clean; 320 tests pass; make validate passes in docs/.

@claude

claude Bot commented Oct 8, 2026

Copy link
Copy Markdown

Reviewed the diff for squirrel channel. I didn't run the tests locally, and I only read the first part of poller.test.ts. The design is sound. Content is built only from validated ids and counts plus fixed strings, the permission-relay capability is not declared, and the e2e test checks that title/body text never reaches the agent. I found nothing that should block merge.

  • (low) apps/cli/src/channel/events.ts safeDomain: the hostname regex accepts any DNS-shaped string, so a crawled page's domain can contain up to 253 characters of attacker-chosen words, e.g. ignore-previous-instructions.run-rm.evil.com. This is a much narrower channel than free text, and the instructions already say to treat site data as untrusted. If the server always supplies the domain from the website record, consider also capping the length (e.g. 100) or checking it against website_id.
  • (low) apps/cli/src/channel/state.ts save: persistence failures are only logged at debug level. If the state directory is unwritable, every restart or poll will re-deliver recent events, because the seen-set and cursor are never stored. Consider a one-time stderr warning.
  • (low) apps/cli/src/channel/server.ts runPollLoop: for a 401/403 with a valid credential, such as an API key, announcedLogin is only reset on success. The slow retry is fine, but the user sees the login message once per process, and failures is pinned at 1 or more. That looks intended, but please add a test for the 401, then login, then recovery sequence if one doesn't already exist.
  • (low) apps/cli/src/channel/poller.ts bootstrap: when the server returns next_cursor: null on the first poll, the poller stays unbootstrapped. Any events created before a cursor is eventually issued are silently treated as history. This is documented in a comment, but a user could reasonably expect those events.
  • (nit) MIN_POLL_INTERVAL_SECONDS is defined in both cli/commands/channel.ts and channel/server.ts. Import it from one place. The command file imports server lazily, so you may want to put the constants in events.ts or a small shared module.
  • (nit) process.exit(0) in the .finally() of runPollLoop skips any pending flush. It's fine for stdio, but an explicit comment saying so would help.
  • (nit) buildInstructions refers to compare_audits as available "when your squirrelscan server offers it". Consider confirming that name matches the actual MCP tool.

@claude

claude Bot commented Oct 8, 2026

Copy link
Copy Markdown

Reviewed the channel server, poller, state store, events and CLI wiring. I didn't run the tests. The design is sound: event text is built only from validated ids and counts, delivery is marked per row, and the poll loop backs off on failure. I found nothing that should block merge.

  • (low) apps/cli/src/channel/poller.ts (parseFeedPage): rows that fail validation are dropped before the rows.length < FEED_PAGE_SIZE check. A full server page containing a malformed row looks like a short page, so the poll stops early. The next poll picks the remaining rows up, so this only adds latency. Consider recording the raw page length.
  • (low) apps/cli/src/channel/events.ts: domain passes the hostname regex but is still free-form text from the cloud row, for example ignore-previous-instructions.example.com. The exposure is small and the length is capped. Still, the SECURITY note says content is built only from validated fields, and a hostname can carry a sentence. Consider also emitting it only through meta, or say in the docs that it is lightly constrained.
  • (nit) apps/cli/src/cli/commands/channel.ts and apps/cli/src/channel/server.ts both define MIN_POLL_INTERVAL_SECONDS. Import it from one place.
  • (nit) apps/cli/src/channel/state.ts (save): if renameSync fails, the .tmp file is left behind. Best-effort cleanup would avoid that. Two channel processes for the same org also race on the state file, but only duplicate events are possible, not data loss.
  • (nit) apps/cli/src/channel/server.ts: runPollLoop(...).finally(() => process.exit(0)) skips any transport flush on shutdown. This is probably fine for a stdio server.

Test coverage looks good: events, poller, server loop and an e2e test are all included. A poller test for a page with some malformed rows would cover the first point.

nc9 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Pushed 993b866 to fix the red "Format, lint, and typecheck" check on 1157391.

Cause: the squirrel mcp move to SDK v2 (#572) removed @modelcontextprotocol/sdk v1 from apps/cli, but the channel server must stay on v1 so it negotiates the legacy handshake (Claude Code does not register a channel that negotiates 2026-07-28). On a clean install the channel's imports no longer resolved, so typecheck failed on src/channel/server.ts and the channel tests.

Fix: restored @modelcontextprotocol/sdk ^1.31.0 in apps/cli/package.json next to the v2 packages, with the lockfile and third-party notices regenerated (bun run notices:generate, notices:check clean). No channel code changed.

Local gates on the merged head: typecheck, lint and format clean; 327 tests pass across channel, mcp, cli and completions.

The latest review (all lows and nits, none blocking) is not addressed in this push: the raw page length when rows are malformed, hostname text in domain, the duplicated minimum interval constant, the leftover .tmp file on a failed rename, and process.exit skipping flush. I can fold the cheap ones into a follow-up push if wanted.

@github-actions

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

PR too large for auto-review

This PR is 6062 changed lines (limit 6000), so the automated reviewer was skipped: past that size it runs out of turns mid-session and posts nothing, which is worse than saying so.

Run it manually (/review, or a focused review per area) before merging, or split the PR.

Diff measured: 19 reviewable files, 6062 changed lines (1 generated files ignored).

@nc9
nc9 merged commit 4892263 into main Oct 8, 2026
15 checks passed
@nc9
nc9 deleted the claude/pub-569-squirrel-channel branch October 8, 2026 11:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants