Skip to content

fix(brainstorming): persist brainstorm.choice() events and keep companion session dirs stable across restarts - #2761

Open
xianfengsong wants to merge 6 commits into
obra:devfrom
xianfengsong:fix/2725-companion-restart-dirs
Open

xianfengsong wants to merge 6 commits into
obra:devfrom
xianfengsong:fix/2725-companion-restart-dirs

Conversation

@xianfengsong

@xianfengsong xianfengsong commented Dec 1, 2026 •

Copy link
Copy Markdown

Fixes #2725

Who is submitting this PR? (required)

Field Value
Your model + version GLM, model ID glm-5.3-flash
Harness + version Claude Code CLI v2.1.330
All plugins installed superpowers, everything-claude-code, pstack (skill collections visible to the agent this session)
Human partner who reviewed this diff xianfengsong

What your human partner asked you to do, in their words:

"First reproduce issue #2725's two bugs locally, and once confirmed, fix them per this repo's contribution requirements."

Human-authored summary (required, under 200 words)

Issue #2725 was not theorized — I reproduced both bugs with my own clicks in a real browser: choosing an option through window.brainstorm.choice() never reached the agent, and after any companion restart the screens and directories diverged, leaving the agent and the browser tab in disagreement about where content lived. This PR fixes both inside the companion's own scripts. Before approving I checked the RED→GREEN evidence below, reviewed the complete diff against upstream/dev, and re-ran the reproduction myself on the fixed code to confirm both bugs are gone.

What problem are you trying to solve?

Issue #2725, both bugs manually reproduced (real browser, real clicks) and documented with a repro script in the issue comment:

  1. brainstorm.choice() events are silently dropped. The helper API sends {type:'choice', value}, but the server's persistence gate in handleMessage (server.cjs) requires event.choice to be present. The event reaches the server's stdout log and never the state/events file the agent reads. The page tells the user the choice was registered; the agent sees nothing.
  2. A restart moves the screen/state directories. start-server.sh creates a unique session dir per invocation (SESSION_ID="$$-$(date +%s)") while .last-port/.last-token are project-shared. After a same---project-dir restart the URL is byte-identical (the already-open tab reconnects, as visual-companion.md promises) but the reported screen_dir and state_dir point at a fresh empty directory. Screens pushed to the previously-noted directory are never served; the user's new clicks land in a directory the agent doesn't read; the old directory's events file holds plausible-looking stale records.

Session failure mode (from the issue): the agent asks the user to pick between options on a served screen, the user clicks, the companion confirms the click visually, and the agent's next turn has no record of the choice — or, after any restart, the agent writes new screens into a directory the browser tab is no longer being served from.

What does this PR change?

In skills/brainstorming/scripts/server.cjs, handleMessage now also persists events shaped {type:'choice', value} by normalizing them to {...event, choice: event.value} (events already carrying choice persist unchanged, non-choice noise is still not persisted). In skills/brainstorming/scripts/start-server.sh, --project-dir mode now uses one stable session directory (<project>/.superpowers/brainstorm/server/) instead of a per-invocation <pid>-<epoch> dir, kills a still-live previous instance only with ownership proof (pid alive AND its command line carries --brainstorm-server-id=<id from that dir's state file>; ambiguous metadata fails closed), sweeps live pre-fix orphan servers on the first post-upgrade restart (stop only provable ones, never delete directories), and clears the previous run's server-stopped marker on every successful start. Tests in tests/brainstorm-server/ (server.test.js +1, start-server.test.sh +11 tests across four new sections) pin each behavior RED-first.

Is this change appropriate for the core library?

Yes. The brainstorming skill and its visual companion are core general-purpose skills; both bugs reproduce on any project, any domain, with any harness that runs the companion. The change adds no dependency, integrates no third-party service, and is not project-, team-, or tool-specific — it makes the companion's own documented promises true (choices reach the agent; the tab reconnects to the same screens after a restart). The only touched files are the companion's scripts and their test suite.

What alternatives did you consider?

  • Fix the helper instead (helper.js sends choice: already-shaped). Rejected: tabs running a stale cached pre-fix helper, and custom pages calling brainstorm.send({type:'choice', value}) directly, would stay broken. Server-side normalization repairs every sender path at one site; helper.js stays byte-identical.
  • Have start-server.sh call stop-server.sh to clean up the previous instance. Rejected: stop-server.sh rm -rfs the session dir when it is under /tmp/*, so a project checked out under /tmp (or a user pointing --project-dir at a /tmp path) would lose its screens/events on every restart. The ownership proof is inlined instead, with no directory deletion anywhere in the kill path.
  • Accept a one-time degraded restart after upgrading (tell users to kill the old pre-fix server themselves). Rejected: on Windows/Git Bash the owner-PID watchdog is disabled (MSYS2 PIDs are invisible to Node), so a pre-fix orphan can legitimately keep running; its hold on the preferred port would make the first post-upgrade restart silently fall back to a random port — reproducing issue superpowers: visual companion drops brainstorm.choice() events and loses its screen directory after a restart #2725's symptom exactly once, at the worst possible time (right after upgrade). The startup orphan sweep stops live pre-fix servers we can prove from their own state dirs and never signals an unprovable pid.
  • Do nothing / document the workaround. Rejected: both failure modes are silent data loss the user cannot work around (the agent is the one holding the stale directory paths).

Does this PR contain multiple unrelated changes?

No — one problem, one PR. Both bugs are the two halves of issue #2725 and they interact: making the session dir stable is what makes the previously dormant "kill any existing server" block live in project mode, which is what requires the ownership-proof hardening and the upgrade-path orphan sweep. The server-stopped marker cleanup falls out of the same stable-dir change (with a stable dir, a stale marker would make the documented aliveness check permanently ambiguous). The single server.cjs hunk (3 lines) is Bug 1; everything else in start-server.sh and the tests serves Bug 2. The spec commit (f637583) is the design document for exactly this fix.

Existing PRs

  • I have reviewed all open AND closed PRs for duplicates or prior art
  • Related PRs: none found

Searched obra/superpowers PRs (open and closed) on 2026-12-01 for "2725", "brainstorm choice events", and "companion screen_dir restart" via gh search prs — zero hits. No prior attempt exists to differentiate from.

Environments tested

Harness (e.g. Claude Code, Cursor) Harness version Model Model version/ID
Claude Code CLI 2.1.330 GLM glm-5.3-flash

Live walkthrough host: macOS 15.7.7 (Darwin 24.6.0, arm64), Node v22.23.2, bash 5.3 (homebrew; /bin/bash 3.2 also exercised by the test suites' bash-3.2-safe idioms).

New harness support (required if this PR adds a new harness)

N/A — this PR adds no harness support. It changes the brainstorming companion's server/start scripts and their tests only.

Clean-session transcript for "Let's make a react todo list"
N/A — no new harness is introduced by this PR.

Evaluation

  • Initial prompt that started this session: the human partner hit both failure modes in a real brainstorming session, manually reproduced them (real browser, real clicks) and documented the repro in issue superpowers: visual companion drops brainstorm.choice() events and loses its screen directory after a restart #2725's comment; the session then implemented the reviewed design spec + plan for superpowers: visual companion drops brainstorm.choice() events and loses its screen directory after a restart #2725 (links in "Who is submitting this PR").
  • Eval sessions after the change: no model-behavior eval sessions — no behavior-shaping content (SKILL.md, visual-companion.md, helper.js prose) changed, so there is nothing for a model-behavior eval to measure. Verification was deterministic: RED→GREEN per bug in the repo's test conventions, a full per-suite gate, and one live walkthrough of the exact manual repro from the issue comment against the patched scripts (no browser automation — the browser steps were exercised with the same HTTP/WS requests a browser makes: ?key= bootstrap page, cookie jar, key-authed WebSocket).
  • Gate method: tests/brainstorm-server/package.json runs the suites in a single && chain, and branding.test.js — fifth in the chain — carries 3 failures that pre-exist on the branch base d4b6d3be (upstream/dev, untouched by this diff), so the chain can never complete on this branch. Every suite was therefore executed and reported individually: ws-protocol 32, helper 15, browser-launcher 3, auth 20, branding 3 failed (pre-existing), server 35, lifecycle 13, start-server 19, stop-server 7, windows-lifecycle 9 pass / 3 skip. bash scripts/lint-shell.sh was likewise partially executed, because shellcheck is not installed locally (caveat 2 below).
  • How outcomes changed:

Baseline before any fix (upstream/dev d4b6d3be, every suite run individually because npm test &&-chains and truncates at the first failure):
ws-protocol 32/0, helper 15/0, browser-launcher 3/0, auth 20/0, branding 4 pass/3 fail (pre-existing on upstream/dev, untouched by this PR — see caveat below), server 34/0, lifecycle 13/0, start-server 8/0, stop-server 7/0. In this baseline, a brainstorm.choice() click produced NO line in state/events (Bug 1), and a same-project restart reported a different screen_dir/state_dir (Bug 2).

RED (new test added, fix not yet present):

  • Bug 1 — server.test.js: 34 passed, 1 failed — choice-shaped events persist with a choice field: state/events never created; the {type:'choice', value:'blue'} event was dropped by the old gate.
  • Bug 2a — start-server.test.sh: 11 passed, 3 failed — project mode still stacked <pid>-<epoch> dirs (found 2), server-stopped marker survived a restart.
  • Bug 2b — start-server.test.sh: 15 passed, 1 failed — with a planted unrelated live pid in server.pid, the old bare kill murdered the innocent process (unrelated alive=no).
  • Bug 2c — start-server.test.sh: 18 passed, 1 failed — a live pre-fix server in an orphan <pid>-<epoch> dir survived the restart and held the preferred port.

GREEN (after each fix, all suites rerun individually):

  • Bug 1 — server.test.js 35/0.
  • Bug 2a — start-server.test.sh 14/0.
  • Bug 2b — 16/0 (twice consecutively).
  • Bug 2c — 19/0.

Final gate on this branch (every suite run individually, 2026-12-01):

Suite Result
ws-protocol.test.js 32 passed, 0 failed
helper.test.js 15 passed, 0 failed
browser-launcher.test.js 3 passed, 0 failed
auth.test.js 20 passed, 0 failed
branding.test.js 4 passed, 3 failed — the same 3 pre-existing upstream/dev failures (visible logo should appear before the Superpowers version text); count did not grow
server.test.js 35 passed, 0 failed, 0 skipped
lifecycle.test.js 13 passed, 0 failed
start-server.test.sh 19 passed, 0 failed
stop-server.test.sh 7 passed, 0 failed
windows-lifecycle.test.sh 9 passed, 0 failed, 3 skipped (Windows-only assertions; run on macOS by design)
bash -n syntax check of start-server.sh clean (see caveat: shellcheck not installed on the authoring machine)

Live walkthrough of the #2725 manual repro against the patched scripts (temp project under $HOME, not /tmp; macOS 15.7.7 / Node v22.23.2):

  1. Bug 1 (choice persisted). Started the companion with --project-dir, wrote a screen whose button calls window.brainstorm.choice('top') into the stable content dir, drove the exact helper payload {"type":"choice","value":"top"} over the key-authed WebSocket. state/events then contained exactly: {"type":"choice","value":"top","timestamp":1796120994192,"choice":"top"}.
  2. Bug 2 (restart keeps everything). Killed the server with plain SIGTERM (pid file left behind, as in the repro), restarted with the same --project-dir. Startup JSON reported the same screen_dir, the same state_dir, and the byte-identical url (same preferred port 52073 and same persisted token). The pre-restart screen was still served through the browser flow (GET /?key=… → bootstrap page + Set-Cookie: brainstorm-key-52073=…, then GET / with the cookie → the pre-restart screen, HTTP 200), and state/events still held the round-1 choice (history survives restarts by design).
  3. Restart over a live server. Started a third time while the second was alive: the second server's pid was dead by the time the third reported server-started, the third bound the same preferred port (52073, matching .last-port — no EADDRINUSE fallback), lsof showed exactly one listener (the new pid), and the phase-2 cookie jar (the still-open browser tab's cookie) still authenticated against the third instance.

Human browser verification (the same repro re-run by the human partner with real clicks after the fix, macOS):

  1. Bug 1. Clicking "顶部导航" on a window.brainstorm.choice() screen put {"type":"choice","value":"top","screen":"nav-position","timestamp":1796125602858,"choice":"top"} into state/events — before the fix the identical action left no events file at all.
  2. Bug 2. After kill + same---project-dir restart, the startup JSON reported the byte-identical screen_dir/state_dir (…/brainstorm/server/…) and URL (port 62532); the tab reconnected to the pre-restart screen, a screen pushed after the restart appeared instantly, and its click ("choice":"blue") landed in the same events file. Exactly one session directory (server/) existed — before the fix the same steps produced two diverging directories and an invisible screen.
  3. Live takeover. A third start while the second was alive rebound the same preferred port 62532 (no fallback).
  4. One expected non-surprise, noted for completeness: the page's visual selected state (button highlight) resets when the page reloads — that state lives in the page's DOM, not in the companion's record; the durable record is the events file, and pushing a new screen resetting events is the companion's pre-existing "new question, fresh answer sheet" semantics, unchanged by this PR.

Rigor

  • If this is a skills change: I used superpowers:writing-skills and
    completed adversarial pressure testing (paste results below)
    N/A — no behavior-shaping prose changed (SKILL.md, visual-companion.md, helper.js are byte-identical to upstream/dev).
  • This change was tested adversarially, not just on the happy path
    Adversarial cases pinned by tests: planted pid pointing at an unrelated live process (must not be signaled); orphan whose instance-id does not match its command line (must not be signaled); malformed/missing instance-id files (fail closed); non-choice events must not persist; /tmp mode must keep per-invocation dirs; orphan directory and its events must survive the sweep; server-stopped marker must not survive a restart.
  • I did not modify carefully-tuned content (Red Flags table,
    rationalizations, "human partner" language) without extensive evals
    showing the change is an improvement

Human review

  • A human has reviewed the COMPLETE proposed diff before submission

Known caveats to disclose in review (kept in the draft so nothing is hidden at submission time)

  1. branding.test.js: 3 failures pre-exist on upstream/dev (all visible logo should appear before the Superpowers version text) and are untouched by this PR. They also truncate a bare npm test (the suite &&-chains), which is why every suite above was run and reported individually.
  2. shellcheck: scripts/lint-shell.sh requires shellcheck, which is not installed on the authoring machine, so the shellcheck half of the lint could not run; the script's other half (the bash -n syntax check) passes, and no CI workflow in this repo runs shellcheck. If maintainers want, the PR can be linted in CI or the human partner can run shellcheck locally before submission.

@danishkumar26 danishkumar26 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed. Fixes both issue #2725 bugs: choice-shaped events now persist to state/events with choice mirrored from value, and --project-dir restarts reuse a stable server session directory with an ownership-proven kill of the previous server plus an orphan sweep for pre-fix processes.

Verified: tests/brainstorm-server/start-server.test.sh 19/19 pass (stable directory, restart marker cleared, port reuse, no unrelated-process kills, orphan sweep); server.test.js 35/35 pass including the new choice-persistence test.

Non-blocking note: the persistence gate uses event.choice || (...), so a non-string choice of 0 would not be persisted. Choice values arrive as strings from data attributes, so this does not occur in practice.

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