Repository navigation
fix: Claude CLI empty output in IDE context & project-switching bugs - #71
Conversation
- Strip inherited IDE nesting markers (CLAUDECODE, VSCODE_*, CURSOR_*) from server-spawner env and use spawn with detached:true + clean minimal env in runClaude() - Add retry logic with user-friendly error messages for available plugins - Add ops logging and enhanced debug endpoint for CLI diagnostics - Fix project-switching: stale worktree data, terminal crashes, API staleness detection Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
The latest updates on your projects. Learn more about Vercel for GitHub. |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughSanitizes child-process envs, replaces Claude CLI exec with a spawn-based runner (streaming, timeouts, retries, diagnostics), implements a centralized Go-based logger sink with Node/Python/Zig/WASM bindings and a client log ingestion endpoint, hardens terminal/worktree flows, expands tests, and adds TinyGo CI support. Changes
Sequence Diagram(s)sequenceDiagram
participant Client as rgba(30,144,255,0.5)
participant Server as rgba(34,139,34,0.5)
participant ClaudeCLI as rgba(255,165,0,0.5)
participant FS as rgba(128,0,128,0.5)
Client->>Server: POST /api/claude/plugins (list/debug)
Server->>FS: stat/locate Claude binary
Server->>Server: sanitize env (strip CLAUDE_*, CURSOR_*, VSCODE_*)
Server->>ClaudeCLI: spawn Claude CLI (cwd, cleanEnv)
ClaudeCLI-->>Server: stream stdout / stderr
Server->>Server: buffer streams, emit start/progress logs
alt timeout reached
Server->>ClaudeCLI: send SIGTERM
end
ClaudeCLI-->>Server: exit code + collected output
Server-->>Client: JSON result / diagnostics
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
📝 Coding Plan
Comment |
|
/package |
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (2)
apps/web-app/src/App.tsx (1)
582-586: Consider usingconsole.logorconsole.debuginstead ofconsole.warnfor diagnostic logs.These log statements are informational debugging aids for project-switching, not actual warnings. Using
console.warnmay clutter warning logs and trigger false positives in monitoring systems that track console warnings.♻️ Suggested refactor
- console.warn("[PROJECT-SWITCH] workspaceStorageScope changed, clearing selection", { + console.log("[PROJECT-SWITCH] workspaceStorageScope changed, clearing selection", { prev: prevWorkspaceScopeRef.current, next: workspaceStorageScope, staleSelection: selection, });Apply similarly to the other
console.warncalls at lines 829, 1269, and 1277.Also applies to: 829-832, 1269-1271, 1277-1281
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web-app/src/App.tsx` around lines 582 - 586, The diagnostic messages using console.warn should be downgraded to non-warning logs: replace console.warn(...) with console.debug(...) (or console.log(...)) in the project-switching diagnostic statements so they don't appear as warnings; specifically update the call that logs "[PROJECT-SWITCH] workspaceStorageScope changed, clearing selection" (which references prevWorkspaceScopeRef.current, workspaceStorageScope, and selection) and apply the same change to the other similar calls in this file (the console.warn usages around the other project-switch messages at the locations noted). Ensure the log signature and interpolated data remain unchanged, only swapping the console method.apps/desktop-app/src/server-spawner.ts (1)
46-59: Broaden IDE env stripping to full-prefix checks.Using selective
CURSOR_*sub-prefixes can miss other Cursor variables and reintroduce nested-context behavior.Suggested fix
([k]) => !k.startsWith("CLAUDECODE") && !k.startsWith("CLAUDE_CODE_") && !k.startsWith("CLAUDE_AGENT_") && - !k.startsWith("CURSOR_SPAWN") && - !k.startsWith("CURSOR_TRACE") && - !k.startsWith("CURSOR_EXTENSION") && - !k.startsWith("CURSOR_WORKSPACE") && + !k.startsWith("CURSOR_") && !k.startsWith("VSCODE_"),🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/desktop-app/src/server-spawner.ts` around lines 46 - 59, The environment-cleaning filter in cleanEnv is too narrow (it only checks specific CLAUDE_* and CURSOR_* sub-prefixes) and can miss other IDE-related vars; update the Object.entries(process.env).filter callback used to build cleanEnv so it excludes any env key that starts with the broader prefixes "CLAUDE", "CURSOR", and "VSCODE" (instead of only "CLAUDECODE", "CLAUDE_CODE_", "CLAUDE_AGENT_" and individual "CURSOR_*" names), preserving the other exclusions (if any) so child processes can't detect nested IDE/agent contexts.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@apps/server/src/routes/claude-plugins.ts`:
- Around line 487-503: The opsLog.addEvent calls (e.g., opsLog.addEvent in
claude-plugins.ts) are exposing sensitive environment fields and raw command
fragments; remove HOME, SHELL, TERM from metadata and avoid logging raw command
output or arg fragments—log only non-sensitive indicators (e.g., binaryExists
boolean, cwd existence, and a list of CLAUDE_ variable names) or mask values
(e.g., replace values with "<redacted>" or hashed placeholders) and ensure any
other addEvent usages at the other locations (lines referenced) follow the same
pattern; update the metadata construction to filter out sensitive keys and mask
values instead of including raw env values or command fragments.
- Around line 1093-1106: The route currently returns HTTP 200 for CLI failures
and empty CLI output; change both error branches that call c.json(...) to return
a non-2xx status (e.g., c.status(502).json(...)) so clients can detect failures;
specifically update the branches checking result (!result || !result.success)
and the branch checking result.stdout.length === 0 to use c.status(502).json
with the same payload and logging, ensuring the path handling plugins/available
returns an appropriate error status.
- Around line 473-486: The current allowlist in withAugmentedPathEnv()/env
creation (PATH, HOME, USER, SHELL, TERM, LANG, TMPDIR, NO_COLOR, XDG_*) is too
restrictive and strips important runtime networking/auth vars; update the env
construction in apps/server/src/routes/claude-plugins.ts to preserve relevant
proxy/cert/auth variables by either merging process.env into baseEnv (while
still ensuring PATH/HOME overrides) or explicitly adding common passthrough
names such as HTTP_PROXY, http_proxy, HTTPS_PROXY, https_proxy, NO_PROXY,
no_proxy, SSL_CERT_DIR, NODE_EXTRA_CA_CERTS, REQUESTS_CA_BUNDLE, AWS_*
(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, AWS_REGION), and
any CLI-specific vars used by Claude; keep withAugmentedPathEnv and existing
XDG_* handling but ensure these additional vars are copied from
baseEnv/process.env into env so CLI networking and auth work in non-default
environments.
- Around line 524-526: The current timeout only sends SIGTERM
(child.kill("SIGTERM")) which can leave the promise waiting if the child ignores
it; modify the shutdown logic around the timer/child to add a short SIGKILL
fallback: after sending SIGTERM via child.kill("SIGTERM"), start a secondary
timer (e.g. killFallbackTimer) that sends child.kill("SIGKILL") after a brief
delay (e.g. 500ms) and ensure both timers are cleared when the child's "close"
or "exit" event fires; update the logic surrounding the timer, child, and
timeout variables so the fallback is started only once and cleaned up to avoid
leaks.
In `@apps/web-app/src/components/detail/DetailPanel.tsx`:
- Around line 412-416: The console.warn in DetailPanel that logs detailScopeKey
and scopeCache.openClaudeTabs/openCodexTabs must be gated by a debug/dev flag to
avoid flooding and leaking internal IDs in production; update the logging calls
in DetailPanel (both the block using scopeCache/openClaudeTabs/openCodexTabs
around the detailScopeKey and the similar block at 1311-1316) to only execute
when a clearly named runtime flag or env check (e.g., isDebugEnabled or NODE_ENV
!== 'production') returns true, or replace with a helper like
shouldLogProjectSwitchDiagnostics(), and ensure production paths either omit
sensitive IDs or redact them before logging.
In `@apps/web-app/src/components/detail/TerminalView.tsx`:
- Around line 294-305: The passive-restore branch currently only clears booting
state when payload.length>0, leaving isAgentBooting true if the restore yielded
an empty string; change the logic in the block guarded by isAgentVariant and
(bootingRequestIdRef.current !== null || awaitingPassiveRestoreRef.current) so
that when awaitingPassiveRestoreRef.current is true you clear
awaitingPassiveRestoreRef.current, bootingRequestIdRef.current,
awaitingOutputRef.current and call setIsAgentBooting(false) regardless of
payload.length, while still setting hasOutputForRequestRef.current =
payload.length > 0 and preserving the existing behavior when only
awaitingOutputRef.current or isAgentBooting should be cleared after non-empty
output.
- Around line 595-606: The effect in TerminalView currently auto-closes agent
tabs for any error once pendingLaunchRequest/launchRequest are cleared; change
it to only auto-close for passive reconnect failures by adding a specific
predicate (e.g., isPassiveReconnectFailure(error)) and gating the onAgentExit
call with that predicate; implement the predicate (or inline check) to detect
the passive reconnect failure shape your app uses (for example an
error.type/status/code/flag that denotes passive reconnect) and update the
effect to: if (!isPassiveReconnectFailure(error)) return; before calling
onAgentExit, keeping the existing checks for isAgentVariant,
pendingLaunchRequest, and launchRequest.
---
Nitpick comments:
In `@apps/desktop-app/src/server-spawner.ts`:
- Around line 46-59: The environment-cleaning filter in cleanEnv is too narrow
(it only checks specific CLAUDE_* and CURSOR_* sub-prefixes) and can miss other
IDE-related vars; update the Object.entries(process.env).filter callback used to
build cleanEnv so it excludes any env key that starts with the broader prefixes
"CLAUDE", "CURSOR", and "VSCODE" (instead of only "CLAUDECODE", "CLAUDE_CODE_",
"CLAUDE_AGENT_" and individual "CURSOR_*" names), preserving the other
exclusions (if any) so child processes can't detect nested IDE/agent contexts.
In `@apps/web-app/src/App.tsx`:
- Around line 582-586: The diagnostic messages using console.warn should be
downgraded to non-warning logs: replace console.warn(...) with
console.debug(...) (or console.log(...)) in the project-switching diagnostic
statements so they don't appear as warnings; specifically update the call that
logs "[PROJECT-SWITCH] workspaceStorageScope changed, clearing selection" (which
references prevWorkspaceScopeRef.current, workspaceStorageScope, and selection)
and apply the same change to the other similar calls in this file (the
console.warn usages around the other project-switch messages at the locations
noted). Ensure the log signature and interpolated data remain unchanged, only
swapping the console method.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 36fc3463-9ec6-496e-97d7-41773287d7ff
📒 Files selected for processing (12)
apps/desktop-app/src/server-spawner.tsapps/server/src/routes/claude-plugins.tsapps/server/src/terminal-manager.test.tsapps/server/src/terminal-manager.tsapps/web-app/src/App.tsxapps/web-app/src/components/detail/DetailPanel.tsxapps/web-app/src/components/detail/TerminalView.test.tsxapps/web-app/src/components/detail/TerminalView.tsxapps/web-app/src/hooks/useApi.tsapps/web-app/src/hooks/useTerminal.tsapps/web-app/src/hooks/useWorktrees.test.tsapps/web-app/src/hooks/useWorktrees.ts
| opsLog.addEvent({ | ||
| source: "claude-cli", | ||
| action: "cli.exec", | ||
| message: `Starting: claude ${args.join(" ")}`, | ||
| level: "debug", | ||
| status: "started", | ||
| command: { command: resolvedPath, args, cwd }, | ||
| metadata: { | ||
| binaryExists, | ||
| HOME: env.HOME, | ||
| SHELL: env.SHELL, | ||
| TERM: env.TERM, | ||
| claudeEnvVars: Object.fromEntries( | ||
| Object.entries(env).filter(([k]) => k.startsWith("CLAUDE_")), | ||
| ), | ||
| }, | ||
| }); |
There was a problem hiding this comment.
Ops/debug responses currently expose sensitive local environment details.
Logging/returning fields like HOME and raw command output fragments can leak user-identifying or sensitive machine context.
Suggested fix
- metadata: {
- binaryExists,
- HOME: env.HOME,
- SHELL: env.SHELL,
- TERM: env.TERM,
- claudeEnvVars: Object.fromEntries(
- Object.entries(env).filter(([k]) => k.startsWith("CLAUDE_")),
- ),
- },
+ metadata: {
+ binaryExists,
+ shellConfigured: Boolean(env.SHELL),
+ termConfigured: Boolean(env.TERM),
+ },
...
- stdout: trimmedOut.slice(0, 500),
- stderr: trimmedErr.slice(0, 500),
+ stdoutBytes: trimmedOut.length,
+ stderrBytes: trimmedErr.length,
...
- HOME: env.HOME ?? null,
- SHELL: env.SHELL ?? null,
- TERM: env.TERM ?? null,
- claudeEnvVars: Object.fromEntries(
- Object.entries(env).filter(([k]) => k.startsWith("CLAUDE_")),
- ),
+ shellConfigured: Boolean(env.SHELL),
+ termConfigured: Boolean(env.TERM),Also applies to: 546-548, 617-625
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server/src/routes/claude-plugins.ts` around lines 487 - 503, The
opsLog.addEvent calls (e.g., opsLog.addEvent in claude-plugins.ts) are exposing
sensitive environment fields and raw command fragments; remove HOME, SHELL, TERM
from metadata and avoid logging raw command output or arg fragments—log only
non-sensitive indicators (e.g., binaryExists boolean, cwd existence, and a list
of CLAUDE_ variable names) or mask values (e.g., replace values with
"<redacted>" or hashed placeholders) and ensure any other addEvent usages at the
other locations (lines referenced) follow the same pattern; update the metadata
construction to filter out sensitive keys and mask values instead of including
raw env values or command fragments.
| const timer = setTimeout(() => { | ||
| child.kill("SIGTERM"); | ||
| }, timeout); |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify timeout path currently has SIGTERM but no SIGKILL fallback in runClaude().
rg -n "setTimeout\\(\\(\\) => \\{|child\\.kill\\(\"SIGTERM\"\\)|child\\.kill\\(\"SIGKILL\"\\)" apps/server/src/routes/claude-plugins.ts -n -C2Repository: fum4/openkit
Length of output: 180
🏁 Script executed:
sed -n '450,560p' apps/server/src/routes/claude-plugins.tsRepository: fum4/openkit
Length of output: 3669
🏁 Script executed:
sed -n '555,575p' apps/server/src/routes/claude-plugins.tsRepository: fum4/openkit
Length of output: 663
🏁 Script executed:
rg -n "runClaude\(" apps/server/src/routes/claude-plugins.ts | head -20Repository: fum4/openkit
Length of output: 1482
🏁 Script executed:
sed -n '580,605p' apps/server/src/routes/claude-plugins.tsRepository: fum4/openkit
Length of output: 964
🏁 Script executed:
sed -n '601,620p' apps/server/src/routes/claude-plugins.tsRepository: fum4/openkit
Length of output: 703
Add SIGKILL fallback to prevent promise deadlock when child process ignores SIGTERM.
If the Claude CLI process ignores SIGTERM, the close event never fires and the promise hangs indefinitely. This causes the HTTP response to stall and processes to leak on the server. Add a hard-stop fallback using SIGKILL after a brief delay.
Suggested fix
+ let killTimer: ReturnType<typeof setTimeout> | null = null;
const timer = setTimeout(() => {
- child.kill("SIGTERM");
+ try {
+ child.kill("SIGTERM");
+ } catch {
+ /* ignore */
+ }
+ // Hard-stop fallback so the promise cannot hang forever.
+ killTimer = setTimeout(() => {
+ try {
+ child.kill("SIGKILL");
+ } catch {
+ /* ignore */
+ }
+ }, 2_000);
}, timeout);
child.on("close", (code) => {
clearTimeout(timer);
+ if (killTimer) clearTimeout(killTimer);
const durationMs = Date.now() - startMs;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const timer = setTimeout(() => { | |
| child.kill("SIGTERM"); | |
| }, timeout); | |
| let killTimer: ReturnType<typeof setTimeout> | null = null; | |
| const timer = setTimeout(() => { | |
| try { | |
| child.kill("SIGTERM"); | |
| } catch { | |
| /* ignore */ | |
| } | |
| // Hard-stop fallback so the promise cannot hang forever. | |
| killTimer = setTimeout(() => { | |
| try { | |
| child.kill("SIGKILL"); | |
| } catch { | |
| /* ignore */ | |
| } | |
| }, 2_000); | |
| }, timeout); | |
| child.on("close", (code) => { | |
| clearTimeout(timer); | |
| if (killTimer) clearTimeout(killTimer); | |
| const durationMs = Date.now() - startMs; |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server/src/routes/claude-plugins.ts` around lines 524 - 526, The current
timeout only sends SIGTERM (child.kill("SIGTERM")) which can leave the promise
waiting if the child ignores it; modify the shutdown logic around the
timer/child to add a short SIGKILL fallback: after sending SIGTERM via
child.kill("SIGTERM"), start a secondary timer (e.g. killFallbackTimer) that
sends child.kill("SIGKILL") after a brief delay (e.g. 500ms) and ensure both
timers are cleared when the child's "close" or "exit" event fires; update the
logic surrounding the timer, child, and timeout variables so the fallback is
started only once and cleaned up to avoid leaks.
| if (!result || !result.success) { | ||
| console.error("[OpenKit] claude plugin list --available failed:", result?.stderr); | ||
| return c.json({ | ||
| available: [], | ||
| error: "Failed to load available plugins from the Claude CLI. Please try again.", | ||
| }); | ||
| } | ||
|
|
||
| if (result.stdout.length === 0) { | ||
| console.warn("[OpenKit] claude plugin list --available returned empty output"); | ||
| return c.json({ | ||
| available: [], | ||
| error: "The Claude CLI returned no plugin data. Please try again.", | ||
| }); |
There was a problem hiding this comment.
Return a non-2xx status for CLI failures on /plugins/available.
This path currently sends error payloads with HTTP 200, which makes client-side error handling ambiguous.
Suggested fix
- return c.json({
+ return c.json({
available: [],
error: "Failed to load available plugins from the Claude CLI. Please try again.",
- });
+ }, 502);
...
- return c.json({
+ return c.json({
available: [],
error: "The Claude CLI returned no plugin data. Please try again.",
- });
+ }, 502);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (!result || !result.success) { | |
| console.error("[OpenKit] claude plugin list --available failed:", result?.stderr); | |
| return c.json({ | |
| available: [], | |
| error: "Failed to load available plugins from the Claude CLI. Please try again.", | |
| }); | |
| } | |
| if (result.stdout.length === 0) { | |
| console.warn("[OpenKit] claude plugin list --available returned empty output"); | |
| return c.json({ | |
| available: [], | |
| error: "The Claude CLI returned no plugin data. Please try again.", | |
| }); | |
| if (!result || !result.success) { | |
| console.error("[OpenKit] claude plugin list --available failed:", result?.stderr); | |
| return c.json({ | |
| available: [], | |
| error: "Failed to load available plugins from the Claude CLI. Please try again.", | |
| }, 502); | |
| } | |
| if (result.stdout.length === 0) { | |
| console.warn("[OpenKit] claude plugin list --available returned empty output"); | |
| return c.json({ | |
| available: [], | |
| error: "The Claude CLI returned no plugin data. Please try again.", | |
| }, 502); |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server/src/routes/claude-plugins.ts` around lines 1093 - 1106, The route
currently returns HTTP 200 for CLI failures and empty CLI output; change both
error branches that call c.json(...) to return a non-2xx status (e.g.,
c.status(502).json(...)) so clients can detect failures; specifically update the
branches checking result (!result || !result.success) and the branch checking
result.stdout.length === 0 to use c.status(502).json with the same payload and
logging, ensuring the path handling plugins/available returns an appropriate
error status.
| if ( | ||
| isAgentVariant && | ||
| (bootingRequestIdRef.current !== null || awaitingPassiveRestoreRef.current) | ||
| ) { | ||
| hasOutputForRequestRef.current = payload.length > 0; | ||
| if (payload.length > 0 && (awaitingOutputRef.current || isAgentBooting)) { | ||
| awaitingOutputRef.current = false; | ||
| bootingRequestIdRef.current = null; | ||
| awaitingPassiveRestoreRef.current = false; | ||
| setIsAgentBooting(false); | ||
| } | ||
| } |
There was a problem hiding this comment.
Clear passive-restore booting even when the restore buffer is empty.
A successful passive reconnect can legitimately restore "". In that case this branch leaves isAgentBooting true until the 30s timeout, so the tab stays in the booting overlay with the cursor hidden even though the session is already attached.
💡 Narrow fix
if (
isAgentVariant &&
(bootingRequestIdRef.current !== null || awaitingPassiveRestoreRef.current)
) {
+ const passiveRestore = awaitingPassiveRestoreRef.current;
hasOutputForRequestRef.current = payload.length > 0;
- if (payload.length > 0 && (awaitingOutputRef.current || isAgentBooting)) {
+ if (
+ passiveRestore ||
+ (payload.length > 0 && (awaitingOutputRef.current || isAgentBooting))
+ ) {
awaitingOutputRef.current = false;
bootingRequestIdRef.current = null;
awaitingPassiveRestoreRef.current = false;
setIsAgentBooting(false);
}
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/web-app/src/components/detail/TerminalView.tsx` around lines 294 - 305,
The passive-restore branch currently only clears booting state when
payload.length>0, leaving isAgentBooting true if the restore yielded an empty
string; change the logic in the block guarded by isAgentVariant and
(bootingRequestIdRef.current !== null || awaitingPassiveRestoreRef.current) so
that when awaitingPassiveRestoreRef.current is true you clear
awaitingPassiveRestoreRef.current, bootingRequestIdRef.current,
awaitingOutputRef.current and call setIsAgentBooting(false) regardless of
payload.length, while still setting hasOutputForRequestRef.current =
payload.length > 0 and preserving the existing behavior when only
awaitingOutputRef.current or isAgentBooting should be cleared after non-empty
output.
| useEffect(() => { | ||
| if (!isAgentVariant) return; | ||
| if (pendingLaunchRequest || launchRequest) return; | ||
| if (!error) return; | ||
| console.warn("[PROJECT-SWITCH] Silently closing stale agent tab", { | ||
| worktreeId, | ||
| variant, | ||
| error, | ||
| visible, | ||
| }); | ||
| onAgentExit?.(); | ||
| }, [error, isAgentVariant, launchRequest, onAgentExit, pendingLaunchRequest]); |
There was a problem hiding this comment.
Scope the silent auto-close to passive reconnect failures only.
This effect currently fires on any agent error once the request objects are cleared. That includes explicit launch failures right after markLaunchRequestHandled(..., "failed"), which contradicts the comment here and can silently dismiss the very error the user should see.
💡 Narrow fix
useEffect(() => {
if (!isAgentVariant) return;
if (pendingLaunchRequest || launchRequest) return;
+ if (!awaitingPassiveRestoreRef.current) return;
if (!error) return;
+ agentExitNotifiedRef.current = true;
console.warn("[PROJECT-SWITCH] Silently closing stale agent tab", {
worktreeId,
variant,
error,
visible,
});
onAgentExit?.();
}, [error, isAgentVariant, launchRequest, onAgentExit, pendingLaunchRequest]);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/web-app/src/components/detail/TerminalView.tsx` around lines 595 - 606,
The effect in TerminalView currently auto-closes agent tabs for any error once
pendingLaunchRequest/launchRequest are cleared; change it to only auto-close for
passive reconnect failures by adding a specific predicate (e.g.,
isPassiveReconnectFailure(error)) and gating the onAgentExit call with that
predicate; implement the predicate (or inline check) to detect the passive
reconnect failure shape your app uses (for example an
error.type/status/code/flag that denotes passive reconnect) and update the
effect to: if (!isPassiveReconnectFailure(error)) return; before calling
onAgentExit, keeping the existing checks for isAgentVariant,
pendingLaunchRequest, and launchRequest.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
apps/server/src/routes/claude-plugins.ts (1)
507-513: Consider the implications ofdetached: truewithchild.unref().Using
detached: truecreates a new process group, andchild.unref()allows the parent to exit without waiting. This combination can lead to orphan process accumulation if:
- The parent exits mid-execution (child continues as orphan)
- The timeout fires but
SIGTERMdoesn't terminate the detached process groupSince the environment filtering (lines 473-485) already strips IDE-related variables that cause the nesting issue, consider whether
detached: trueis still necessary. If it is, you may want to useprocess.kill(-child.pid, signal)to signal the entire process group on timeout.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server/src/routes/claude-plugins.ts` around lines 507 - 513, The spawn call creating the child process with detached: true and immediately calling child.unref() (spawn using resolvedPath, args, env, cwd, child.unref) can leave orphaned processes; either remove detached: true (and child.unref()) if a separate process group is unnecessary, or keep detached but update the timeout/cleanup logic to signal the whole group via process.kill(-child.pid, signal) so the entire process group is terminated on timeout; locate the spawn invocation and the timeout/cleanup code that references child and implement one of these two fixes consistently.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@apps/server/src/routes/claude-plugins.ts`:
- Around line 507-513: The spawn call creating the child process with detached:
true and immediately calling child.unref() (spawn using resolvedPath, args, env,
cwd, child.unref) can leave orphaned processes; either remove detached: true
(and child.unref()) if a separate process group is unnecessary, or keep detached
but update the timeout/cleanup logic to signal the whole group via
process.kill(-child.pid, signal) so the entire process group is terminated on
timeout; locate the spawn invocation and the timeout/cleanup code that
references child and implement one of these two fixes consistently.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 5f79254d-2a79-46f2-bf8a-6163a563ac8c
📒 Files selected for processing (1)
apps/server/src/routes/claude-plugins.ts
There was a problem hiding this comment.
Actionable comments posted: 16
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
libs/logger/python/logger.pyi (1)
35-60:⚠️ Potential issue | 🟠 MajorAdd
set_sinkandclose_sinkstatic methods to the.pyistub.The runtime
logger.pyexposes these sink lifecycle APIs at lines 113 and 118, but they are missing from the stub. Typed callers will get false type errors when using these methods.Proposed stub update
class Logger(_LoggerProtocol): @@ def __init__( self, system: str, subsystem: Optional[str] = None, level: Optional[LogLevel] = None, format: Optional[LogFormat] = None, ) -> None: ... + + `@staticmethod` + def set_sink(server_url: str, project_name: str) -> None: ... + + `@staticmethod` + def close_sink() -> None: ...🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@libs/logger/python/logger.pyi` around lines 35 - 60, The Logger stub is missing the static sink lifecycle APIs present at runtime; add staticmethod declarations for set_sink and close_sink to the Logger class in the .pyi so typed callers don't error. Specifically, declare `@staticmethod` def set_sink(path: str) -> None: ... and `@staticmethod` def close_sink() -> None: ... inside the Logger class (matching the runtime function names set_sink and close_sink) with appropriate return types.
♻️ Duplicate comments (4)
apps/server/src/routes/claude-plugins.ts (4)
1091-1108:⚠️ Potential issue | 🟡 MinorReturn a non-2xx status for CLI failures on
/plugins/available.Both error branches return HTTP 200 with an error payload, making client-side error detection ambiguous. Consider returning 502 (Bad Gateway) to indicate upstream CLI failure.
🔧 Suggested fix
if (!result || !result.success) { log.error("claude plugin list --available failed", { domain: "claude", stderr: result?.stderr, }); return c.json({ available: [], error: "Failed to load available plugins from the Claude CLI. Please try again.", - }); + }, 502); } if (result.stdout.length === 0) { log.warn("claude plugin list --available returned empty output", { domain: "claude" }); return c.json({ available: [], error: "The Claude CLI returned no plugin data. Please try again.", - }); + }, 502); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server/src/routes/claude-plugins.ts` around lines 1091 - 1108, The handler for the /plugins/available route currently returns c.json(...) with a 200 status on CLI failures (checked via result and result.stdout), which hides upstream errors; update both failure branches that log errors (the branches checking if (!result || !result.success) and if (result.stdout.length === 0)) to return a 502 response by calling c.status(502).json(...) with the same error payload so clients receive a non-2xx status indicating a Bad Gateway/CLI upstream failure.
522-527:⚠️ Potential issue | 🟠 MajorAdd SIGKILL fallback to prevent promise deadlock when child process ignores SIGTERM.
If the Claude CLI process ignores
SIGTERM, thecloseevent never fires and the promise hangs indefinitely, causing the HTTP response to stall and processes to leak.🔧 Suggested fix with SIGKILL fallback
+ let killTimer: ReturnType<typeof setTimeout> | null = null; const timer = setTimeout(() => { - child.kill("SIGTERM"); + try { + child.kill("SIGTERM"); + } catch { + /* ignore */ + } + killTimer = setTimeout(() => { + try { + child.kill("SIGKILL"); + } catch { + /* ignore */ + } + }, 2_000); }, timeout); child.on("close", (code) => { clearTimeout(timer); + if (killTimer) clearTimeout(killTimer); const durationMs = Date.now() - startMs;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server/src/routes/claude-plugins.ts` around lines 522 - 527, The child process timeout currently only sends SIGTERM and waits for the "close" event, which can hang if the process ignores SIGTERM; update the timeout handler (the timer created where child.kill("SIGTERM") is called) to schedule a secondary fallback (e.g., sigkillTimer) that forcefully kills the child with SIGKILL if it hasn't exited within a short grace period, ensure both timers are cleared in the child.on("close", ...) handler and any listeners removed to avoid leaks, and reference the existing timer variable, child, child.on("close", ...) handler, and the timeout constant so the SIGKILL fallback integrates cleanly with the existing logic.
614-633:⚠️ Potential issue | 🟡 MinorDebug endpoint exposes environment details including HOME path.
The
/api/claude/plugins/debugendpoint returnsHOME,SHELL,TERM, andclaudeEnvVarswhich may leak user-identifying information. Consider whether this endpoint should be restricted or sanitized in production.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server/src/routes/claude-plugins.ts` around lines 614 - 633, The debug endpoint currently returns sensitive environment fields (HOME, SHELL, TERM) and raw CLAUDE_ env vars in the diagnostic payload; update the handler in claude-plugins.ts that constructs the response so it either omits or masks HOME/SHELL/TERM and only returns a whitelisted or masked subset of CLAUDE_* variables (e.g., keys mapped to boolean existence or redacted values), and ensure the endpoint is gated in production (e.g., require admin auth or only enable when NODE_ENV !== "production" or a DEBUG feature flag) so the diagnostic object no longer exposes user-identifying environment data.
485-501:⚠️ Potential issue | 🟠 MajorOps/debug responses expose sensitive local environment details.
The logging includes
HOME,SHELL, and raw stdout/stderr fragments which can leak user-identifying or machine-specific information. This was flagged in a prior review and remains unaddressed.🛡️ Suggested fix to reduce sensitive data exposure
opsLog.addEvent({ source: "claude-cli", action: "cli.exec", message: `Starting: claude ${args.join(" ")}`, level: "debug", status: "started", command: { command: resolvedPath, args, cwd }, metadata: { binaryExists, - HOME: env.HOME, - SHELL: env.SHELL, - TERM: env.TERM, - claudeEnvVars: Object.fromEntries( - Object.entries(env).filter(([k]) => k.startsWith("CLAUDE_")), - ), + shellConfigured: Boolean(env.SHELL), + termConfigured: Boolean(env.TERM), }, }); // ... in close handler ... opsLog.addEvent({ source: "claude-cli", action: "cli.exec", message: `${code === 0 ? "Succeeded" : "Failed"}: claude ${args.join(" ")} (${durationMs}ms, stdout=${trimmedOut.length}b, stderr=${trimmedErr.length}b)`, level: code === 0 && trimmedOut.length === 0 ? "warning" : code === 0 ? "info" : "error", status: code === 0 ? "succeeded" : "failed", command: { command: resolvedPath, args, cwd, durationMs, exitCode: code ?? null, - stdout: trimmedOut.slice(0, 500), - stderr: trimmedErr.slice(0, 500), + stdoutBytes: trimmedOut.length, + stderrBytes: trimmedErr.length, }, });Also applies to: 532-548
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server/src/routes/claude-plugins.ts` around lines 485 - 501, The opsLog.addEvent call in apps/server/src/routes/claude-plugins.ts is logging sensitive local environment details (HOME, SHELL, TERM) and potentially raw stdout/stderr fragments; remove these raw env values from metadata and replace them with non-identifying indicators (e.g., boolean flags like hasHome, hasShell, termType or redacted placeholders) and for claudeEnvVars either only log keys or log values redacted/truncated; also sanitize any stdout/stderr captured elsewhere in the same file (the other opsLog.addEvent usage around the claude execution flow) by omitting raw fragments or truncating/redacting them before adding to metadata. Ensure changes are applied to the opsLog.addEvent invocations associated with the claude execution (e.g., the block that constructs metadata with binaryExists, HOME, SHELL, TERM, claudeEnvVars) and the similar later logging call so no sensitive local env values or large raw output are emitted.
🧹 Nitpick comments (9)
apps/web-app/src/hooks/useWorktrees.test.ts (1)
148-184: Guarantee fake-timer restoration even when assertions fail.Line 149 enables fake timers, but restoration only happens at Line 183. If any assertion throws before that, later tests may run under fake timers.
♻️ Proposed hardening
it("clears retry timeout when serverUrl changes", async () => { vi.useFakeTimers({ shouldAdvanceTime: true }); + try { mockFetchWorktrees.mockResolvedValue({ worktrees: [worktreeA] }); const { result, rerender } = renderHook(() => useWorktrees()); @@ for (const call of callsAfterTimer) { expect(call[0]).not.toBe("http://localhost:3000"); } - - vi.useRealTimers(); + } finally { + vi.useRealTimers(); + } });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web-app/src/hooks/useWorktrees.test.ts` around lines 148 - 184, The test enabling fake timers via vi.useFakeTimers(...) can leave timers mocked if an assertion throws; wrap the test's body so vi.useRealTimers() is always called (e.g., place the test logic inside try { ... } finally { vi.useRealTimers(); }) or add a dedicated afterEach that calls vi.useRealTimers(); update the test referencing useWorktrees, mockFetchWorktrees, latestEventSource.onerror, setServerUrl, renderHook/rerender to ensure restoration happens even on failure.libs/logger/wasm/build.sh (1)
1-13: Consider adding defensive checks for robustness.The script could fail silently or with unclear errors if TinyGo isn't installed or if run from an unexpected directory.
🛠️ Suggested improvements
#!/bin/bash -set -e +set -euo pipefail + +# Ensure script runs from its directory +cd "$(dirname "$0")" echo "Building WASM logger..." +if ! command -v tinygo &> /dev/null; then + echo "Error: tinygo is not installed or not in PATH" >&2 + exit 1 +fi + tinygo build -o ../browser/src/logger.wasm -target=wasm -no-debug -opt=2 . # Copy TinyGo's wasm_exec.js shim (needed to load the WASM module in browsers) TINYGOROOT=$(tinygo env TINYGOROOT) cp "$TINYGOROOT/targets/wasm_exec.js" ../browser/src/wasm_exec.js🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@libs/logger/wasm/build.sh` around lines 1 - 13, The build script build.sh lacks defensive checks and can fail with unclear errors; add explicit checks before running tinygo build: verify tinygo exists (e.g., ensure `tinygo` is on PATH), ensure the script is executed from the repository root or check that target output directories (../browser/src) exist and are writable, and confirm `tinygo env TINYGOROOT` returns a valid path before attempting to copy wasm_exec.js; update the script to exit with clear error messages if any check fails and only run `tinygo build` and `cp "$TINYGOROOT/targets/wasm_exec.js"` after validations succeed.libs/logger/wasm/main.go (2)
48-51: Silent JSON unmarshal failure is acceptable but could benefit from debug logging.The silent discard of malformed context JSON is reasonable since context is optional. For debugging purposes, consider adding a warning log when unmarshal fails, though this is low priority.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@libs/logger/wasm/main.go` around lines 48 - 51, The code silently ignores errors from json.Unmarshal when decoding contextJSON into the local variable context; update the block that declares context and calls json.Unmarshal so that it captures the returned error (from json.Unmarshal([]byte(contextJSON), &context)) and, if non-nil, emits a warning via the package logger (or process logger) including the contextJSON and the error; keep behaviour of leaving context nil/empty on error but log the failure for debugging.
11-15: Consider potential integer overflow for logger IDs in long-running sessions.The
nextIDcounter is anintthat increments monotonically. While unlikely in practice, extremely long-running browser sessions with frequent logger creation could theoretically overflow. Consider usinguint64or implementing ID recycling if this is a concern.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@libs/logger/wasm/main.go` around lines 11 - 15, The nextID counter currently typed as int can overflow in extremely long-running sessions; change nextID to a larger unsigned type (e.g., uint64) and update the loggers map key type from map[int]*logger.Logger to map[uint64]*logger.Logger, adjusting all uses of nextID, loggers, and loggersMu accordingly (or alternatively implement an ID pool/recycle mechanism: maintain a freeIDs slice/stack and pop/push IDs when creating/destroying loggers inside the protected loggersMu critical section) so IDs never wrap unexpectedly.libs/logger/logger.go (1)
102-104: Prefer scopeddeferunlock for panic safety.On Line 103 and Line 138, direct unlock works in normal flow, but a panic in emit/format leaves the mutex locked. A scoped
deferkeeps this robust.♻️ Suggested patch
l.mu.Lock() - emitOutput(l.formatter, entry) - l.mu.Unlock() + func() { + defer l.mu.Unlock() + emitOutput(l.formatter, entry) + }() @@ l.mu.Lock() @@ - emitPlain(message, contextStr) - l.mu.Unlock() + func() { + defer l.mu.Unlock() + emitPlain(message, contextStr) + }()Also applies to: 132-140
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@libs/logger/logger.go` around lines 102 - 104, The mutex lock/unlock in the logging path should use a scoped defer to ensure the mutex is released if emitOutput or formatting panics: right after l.mu.Lock() in the functions using l.formatter and emitOutput (the block around l.mu.Lock(); emitOutput(l.formatter, entry); l.mu.Unlock()), change to call defer l.mu.Unlock() immediately after acquiring the lock so the mutex is always released; apply the same change to the other similar block around the code referenced in the 132-140/138 region to replace manual Unlock() with a deferred Unlock() for panic safety.libs/logger/post_native.go (1)
13-18: Drain response body before close to improve connection reuse.On Line 17, closing without draining can reduce keep-alive reuse on some transports. Prefer discarding the body first.
♻️ Suggested patch
import ( "bytes" + "io" "net/http" "time" ) @@ resp, err := client.Post(url, "application/json", bytes.NewReader(body)) if err != nil { return } - resp.Body.Close() + _, _ = io.Copy(io.Discard, resp.Body) + _ = resp.Body.Close() }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@libs/logger/post_native.go` around lines 13 - 18, The response body is closed without draining which can hurt HTTP keep-alive reuse; in the Post request handling (the client.Post call and the resp.Body.Close usage in post_native.go) first read/discard the response body (e.g. io.Copy(io.Discard, resp.Body) or io.ReadAll) and then close the body (or use defer after checking err) so the connection can be reused; ensure you perform the discard even when you don't need the body and still close resp.Body to avoid leaks.libs/logger/browser/src/index.ts (2)
39-62: WASM load failure is swallowed silently.When WASM fails to load, the catch block swallows the error. This is intentional for graceful degradation, but consider logging the failure in development mode so developers can diagnose issues.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@libs/logger/browser/src/index.ts` around lines 39 - 62, The catch in loadWasm silences WASM load errors; update the catch to log the error in development so failures are visible: inside the async IIFE's catch for wasmReadyPromise (in the loadWasm function referencing wasm_exec.js, logger.wasm, go.run, wasmReadyPromise, and wasmReady) capture the caught error and emit a dev-only message (e.g., using console.warn/console.error when in dev via import.meta.env.DEV or NODE_ENV !== 'production') while still keeping the graceful no-op behavior in production.
157-165:setSink/closeSinksilently fail when WASM is unavailable.If WASM loading fails (e.g., test environment),
setSinkreturns without any indication that the sink wasn't configured. Callers cannot distinguish between success and failure. Consider returning a boolean or logging a warning.💡 Optional: Return success status
- static setSink(serverUrl: string, projectName: string): void { - if (!wasmReady) return; + static setSink(serverUrl: string, projectName: string): boolean { + if (!wasmReady) { + console.warn("[Logger] setSink called before WASM initialized"); + return false; + } getApi().LoggerSetSink(serverUrl, projectName); + return true; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@libs/logger/browser/src/index.ts` around lines 157 - 165, setSink and closeSink silently no-op when wasmReady is false, making callers unaware the sink wasn't configured; update the methods (static setSink and static closeSink) to return a boolean indicating success and/or emit a warning when wasmReady is false (e.g., return false and call console.warn or logger.warn) and return true after calling getApi().LoggerSetSink(...) / getApi().LoggerCloseSink(); ensure the method signatures reflect the boolean return and that callers are updated or documented to handle the false case.libs/logger/sink.go (1)
133-151: Silent failure on HTTP POST errors.
postToServererrors are silently ignored. While best-effort logging is acceptable, consider at least logging the failure to stderr in development mode so developers can diagnose sink connectivity issues.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@libs/logger/sink.go` around lines 133 - 151, The doFlush function currently ignores errors from postToServer; change the call to capture its error return and, when a non-nil error occurs, write a concise diagnostic to stderr (or use the existing logger if available) including sinkURL and the error and only suppress printing in production mode; update the call site in doFlush to: err := postToServer(url, body) and handle err by logging to stderr/dev logger so sink connectivity issues are visible (references: doFlush, postToServer, sinkURL, sinkPayload, sinkBuffer).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In @.github/actions/setup-deps/action.yml:
- Around line 16-19: Replace the non-existent action
nicolo-ribaudo/setup-tinygo@v1 with the maintained acifani/setup-tinygo@v1 in
the workflow definition referenced by the tinygo input (update the action string
used where nicolo-ribaudo/setup-tinygo@v1 appears so the deps setup uses
acifani/setup-tinygo@v1 or a pinned acifani version).
In @.github/workflows/claude-pr-review.yml:
- Around line 19-20: The "Restore Claude auth" step writes the secret with echo
which can leak on shell errors; replace the echo command with a safer write
using a heredoc or printf and restrict file permissions. Specifically, in the
Restore Claude auth step (name: "Restore Claude auth") write the secret via a
heredoc: cat > ~/.claude.json <<'EOF' "${{ secrets.CLAUDE_AUTH_JSON }}" EOF (or
printf '%s' "${{ secrets.CLAUDE_AUTH_JSON }}" > ~/.claude.json) and immediately
chmod 600 ~/.claude.json (or set umask 077 before writing) to ensure the file is
created with tight permissions and avoid shell interpolation that could expose
the secret.
- Around line 22-32: Replace the inline DIFF variable with a file-based approach
and add strict error handling: write the diff to a temp file (e.g.,
DIFF_FILE=/tmp/pr_diff.txt using git diff "origin/$BASE_REF"...HEAD >
"$DIFF_FILE"), enable safe shell options (set -euo pipefail) in the Run Claude
review step, invoke claude reading from that file via stdin (claude --print
--max-turns 5 "Review this pull request diff..." < "$DIFF_FILE" >
/tmp/review-output.txt) and check claude's exit status (if non-zero, echo an
error to stderr and exit 1) to avoid ARG_MAX, escaping issues, and silent
failures; reference the DIFF variable, claude --print invocation, and
/tmp/review-output.txt when making the changes.
In `@apps/server/src/manager.ts`:
- Around line 1434-1437: The ops-log is storing raw Error objects in metadata
which can break JSON serialization; update the two calls to logDeletePhase (the
one with phase "destroy-terminals-for-target-worktree-only" and the other around
lines 1518–1521) to pass a string by converting the error via
toErrorMessage(error) instead of the raw error object (keep worktreeId and other
metadata as-is); locate the logDeletePhase(...) invocations and replace the
error field with toErrorMessage(error).
In `@apps/server/src/routes/logs.ts`:
- Around line 94-113: Validate and normalize each incoming entry before calling
manager.getOpsLog().addEvent: ensure entry.system is a non-empty string and
entry.message is a string (reject or skip entries that fail), coerce
entry.subsystem if present to a string, normalize entry.level to a known set
(map incoming values like "warn" => "warning", accept only
["debug","info","warning","error"], default to "info") and derive status from
the normalized level (e.g., "error" => "failed", others => "info"), build source
as subsystem present ? `${system}.${subsystem}` : system, ensure metadata is a
plain object (fall back to undefined if not an object or empty), and only then
call opsLog.addEvent with the sanitized fields; update any casting of
entry.level to OpsLogLevel to use the normalized value so invalid values can't
pollute OpsLog.
In `@apps/web-app/src/components/detail/TerminalView.tsx`:
- Around line 544-556: The timeout handler in the useEffect that watches
isAgentBooting clears internal boot state but doesn't notify the parent; update
the timeout callback inside the useEffect (the block that checks
bootingRequestIdRef.current and awaitingPassiveRestoreRef.current) to also call
onAgentExit?.() after clearing refs and calling setIsAgentBooting(false) so the
parent/tab is informed the agent has exited/timed out; reference the existing
symbols bootingRequestIdRef, awaitingPassiveRestoreRef, awaitingOutputRef,
setIsAgentBooting, and onAgentExit when making the change.
In `@apps/web-app/src/hooks/useWorktrees.test.ts`:
- Around line 57-64: The test file overwrites globalThis.EventSource with
FakeEventSource and never restores it; save the original (e.g., const
originalEventSource = (globalThis as Record<string, unknown>).EventSource)
before assigning FakeEventSource, perform the replacement in a beforeAll or at
module setup, and restore the saved original in an afterAll (or afterEach) hook
so globalThis.EventSource is returned to its prior value after the suite;
reference the existing FakeEventSource and the globalThis.EventSource assignment
to locate where to add the save/restore hooks.
In `@docs/superpowers/plans/2026-03-14-centralized-logger-sink.md`:
- Line 20: Several fenced code blocks in this markdown (notably the snippet
containing the symbol "sinkProjectName string" and the other example snippets)
are missing language identifiers; update each triple-backtick fence that
contains code (including the blocks around the sinkProjectName declaration and
the two other flagged examples) to include an explicit language tag (for example
go, ts, or bash) so markdownlint MD040 is satisfied and readability improves.
In `@docs/superpowers/specs/2026-03-14-extension-system-design.md`:
- Line 330: The prose uses the lowercase platform name `github:owner/repo`;
update it to use the official capitalization `GitHub:owner/repo` (e.g., change
`github:owner/repo` to `GitHub:owner/repo`) in the spec line that reads "If
`github:owner/repo` → clone/pull to `~/.openkit/extension-cache/<name>/`" so the
platform name is capitalized consistently.
- Around line 280-287: Add blank lines before and after the markdown tables so
they are surrounded by empty lines to satisfy markdownlint MD058; specifically
update the table containing rows with `detail:header`, `detail:description`,
`detail:metadata`, `detail:comments`, `detail:attachments`, and `detail:actions`
so there is an empty line immediately above and below the table, and apply the
same change to the other nearby table (the one referenced in the comment) so
both tables are each preceded and followed by a blank line.
- Around line 132-133: Update the extension source spec entries that list
`github:<owner>/<repo>` and the Absolute local path resolution to mandate
minimum integrity/trust controls: require an explicit immutable pin (commit SHA
or signed release tag) or checksum in the extension manifest, verify
signatures/checksums on fetch, define a trust/allowlist policy and an opt-in
prompt for unpinned sources, and specify failure behavior (fail-closed) and
update/refresh semantics; add a short section describing required manifest
fields (pin, checksum, signature, allowed scopes) and verification steps to
perform when resolving `~/.openkit/extension-cache/<name>/` and when accepting
Absolute local paths so the spec enforces commit verification and allowlist
checks.
- Around line 51-53: Several fenced code blocks in
docs/superpowers/specs/2026-03-14-extension-system-design.md are missing
language identifiers; find triple-backtick blocks that match snippets such as
"Web UI → GET /api/trackers/:id/issues → Extension Host →
emit('issues:list'...)", the manifest tree starting "openkit-ext-example/", the
UI pseudocode "For each section in the detail/list UI:", the API list starting
"GET /api/trackers → List all registered
trackers...", and the CLI examples beginning "dawg ext add
<github-url|local-path>" and add the appropriate language tags (e.g., text for
flow/pseudocode blocks, bash for CLI examples) to each opening ``` so
markdownlint MD040 is satisfied; search the file for other ``` blocks without a
language and apply the same fix to the occurrences noted in the review (lines
63-71, 314-318, 385-411, 415-418, 432-437).
In `@libs/logger/node/src/index.ts`:
- Around line 81-85: Create a serializeContext helper on the logger class that
wraps JSON.stringify(ctx || {}) in a try-catch and returns the serialized string
or "{}" on any error, then update the six methods info, warn, error, debug,
success, and plain to call
bindings.LoggerInfo/LoggerWarn/LoggerError/LoggerDebug/LoggerSuccess/LoggerPlain
with this.serializeContext(ctx) instead of direct JSON.stringify(ctx || {});
reference the existing method names (info, warn, error, debug, success, plain)
and the binding calls (LoggerInfo, LoggerWarn, LoggerError, LoggerDebug,
LoggerSuccess, LoggerPlain) when making the replacements.
In `@libs/logger/project.json`:
- Around line 20-21: The build target's inputs list (targets.build.inputs) is
missing the wasm build script, so edits to wasm/build.sh won't invalidate the
cache; add "{projectRoot}/wasm/build.sh" to targets.build.inputs alongside the
existing wasm files so that changes to that script trigger rebuilds for the
build target (look for the targets.build.inputs array in project.json and
include the wasm/build.sh path).
In `@libs/logger/sink.go`:
- Around line 78-91: CloseSink currently closes sinkDone and returns immediately
while the background goroutine may still be running doFlush, risking an
incomplete HTTP POST; update CloseSink to wait for the goroutine to finish the
final flush (e.g., add a done channel or a sync.WaitGroup that the goroutine
signals after doFlush completes) before unlocking and returning, keep using
sinkDone to trigger the shutdown, and then stop sinkTicker and clear
sinkURL/sinkDone/sinkTicker only after the waiter confirms the goroutine has
exited.
In `@libs/logger/zig/logger.zig`:
- Around line 137-145: setSink and closeSink currently return silently if
`resolved` is not available; change them to record the requested action when
symbols aren't resolved: in `setSink`, if `resolved` is null save `server_url`
and `project_name` into module-level pending variables and return, and when
`resolved` is later populated call `syms.set_sink` with those saved values; in
`closeSink`, if `resolved` is null set a pending_close boolean (or similar) so
that when `resolved` is set the code will invoke `syms.close_sink()`; ensure the
code path that initializes `resolved` applies any pending set_sink or close_sink
actions after resolution.
---
Outside diff comments:
In `@libs/logger/python/logger.pyi`:
- Around line 35-60: The Logger stub is missing the static sink lifecycle APIs
present at runtime; add staticmethod declarations for set_sink and close_sink to
the Logger class in the .pyi so typed callers don't error. Specifically, declare
`@staticmethod` def set_sink(path: str) -> None: ... and `@staticmethod` def
close_sink() -> None: ... inside the Logger class (matching the runtime function
names set_sink and close_sink) with appropriate return types.
---
Duplicate comments:
In `@apps/server/src/routes/claude-plugins.ts`:
- Around line 1091-1108: The handler for the /plugins/available route currently
returns c.json(...) with a 200 status on CLI failures (checked via result and
result.stdout), which hides upstream errors; update both failure branches that
log errors (the branches checking if (!result || !result.success) and if
(result.stdout.length === 0)) to return a 502 response by calling
c.status(502).json(...) with the same error payload so clients receive a non-2xx
status indicating a Bad Gateway/CLI upstream failure.
- Around line 522-527: The child process timeout currently only sends SIGTERM
and waits for the "close" event, which can hang if the process ignores SIGTERM;
update the timeout handler (the timer created where child.kill("SIGTERM") is
called) to schedule a secondary fallback (e.g., sigkillTimer) that forcefully
kills the child with SIGKILL if it hasn't exited within a short grace period,
ensure both timers are cleared in the child.on("close", ...) handler and any
listeners removed to avoid leaks, and reference the existing timer variable,
child, child.on("close", ...) handler, and the timeout constant so the SIGKILL
fallback integrates cleanly with the existing logic.
- Around line 614-633: The debug endpoint currently returns sensitive
environment fields (HOME, SHELL, TERM) and raw CLAUDE_ env vars in the
diagnostic payload; update the handler in claude-plugins.ts that constructs the
response so it either omits or masks HOME/SHELL/TERM and only returns a
whitelisted or masked subset of CLAUDE_* variables (e.g., keys mapped to boolean
existence or redacted values), and ensure the endpoint is gated in production
(e.g., require admin auth or only enable when NODE_ENV !== "production" or a
DEBUG feature flag) so the diagnostic object no longer exposes user-identifying
environment data.
- Around line 485-501: The opsLog.addEvent call in
apps/server/src/routes/claude-plugins.ts is logging sensitive local environment
details (HOME, SHELL, TERM) and potentially raw stdout/stderr fragments; remove
these raw env values from metadata and replace them with non-identifying
indicators (e.g., boolean flags like hasHome, hasShell, termType or redacted
placeholders) and for claudeEnvVars either only log keys or log values
redacted/truncated; also sanitize any stdout/stderr captured elsewhere in the
same file (the other opsLog.addEvent usage around the claude execution flow) by
omitting raw fragments or truncating/redacting them before adding to metadata.
Ensure changes are applied to the opsLog.addEvent invocations associated with
the claude execution (e.g., the block that constructs metadata with
binaryExists, HOME, SHELL, TERM, claudeEnvVars) and the similar later logging
call so no sensitive local env values or large raw output are emitted.
---
Nitpick comments:
In `@apps/web-app/src/hooks/useWorktrees.test.ts`:
- Around line 148-184: The test enabling fake timers via vi.useFakeTimers(...)
can leave timers mocked if an assertion throws; wrap the test's body so
vi.useRealTimers() is always called (e.g., place the test logic inside try { ...
} finally { vi.useRealTimers(); }) or add a dedicated afterEach that calls
vi.useRealTimers(); update the test referencing useWorktrees,
mockFetchWorktrees, latestEventSource.onerror, setServerUrl, renderHook/rerender
to ensure restoration happens even on failure.
In `@libs/logger/browser/src/index.ts`:
- Around line 39-62: The catch in loadWasm silences WASM load errors; update the
catch to log the error in development so failures are visible: inside the async
IIFE's catch for wasmReadyPromise (in the loadWasm function referencing
wasm_exec.js, logger.wasm, go.run, wasmReadyPromise, and wasmReady) capture the
caught error and emit a dev-only message (e.g., using console.warn/console.error
when in dev via import.meta.env.DEV or NODE_ENV !== 'production') while still
keeping the graceful no-op behavior in production.
- Around line 157-165: setSink and closeSink silently no-op when wasmReady is
false, making callers unaware the sink wasn't configured; update the methods
(static setSink and static closeSink) to return a boolean indicating success
and/or emit a warning when wasmReady is false (e.g., return false and call
console.warn or logger.warn) and return true after calling
getApi().LoggerSetSink(...) / getApi().LoggerCloseSink(); ensure the method
signatures reflect the boolean return and that callers are updated or documented
to handle the false case.
In `@libs/logger/logger.go`:
- Around line 102-104: The mutex lock/unlock in the logging path should use a
scoped defer to ensure the mutex is released if emitOutput or formatting panics:
right after l.mu.Lock() in the functions using l.formatter and emitOutput (the
block around l.mu.Lock(); emitOutput(l.formatter, entry); l.mu.Unlock()), change
to call defer l.mu.Unlock() immediately after acquiring the lock so the mutex is
always released; apply the same change to the other similar block around the
code referenced in the 132-140/138 region to replace manual Unlock() with a
deferred Unlock() for panic safety.
In `@libs/logger/post_native.go`:
- Around line 13-18: The response body is closed without draining which can hurt
HTTP keep-alive reuse; in the Post request handling (the client.Post call and
the resp.Body.Close usage in post_native.go) first read/discard the response
body (e.g. io.Copy(io.Discard, resp.Body) or io.ReadAll) and then close the body
(or use defer after checking err) so the connection can be reused; ensure you
perform the discard even when you don't need the body and still close resp.Body
to avoid leaks.
In `@libs/logger/sink.go`:
- Around line 133-151: The doFlush function currently ignores errors from
postToServer; change the call to capture its error return and, when a non-nil
error occurs, write a concise diagnostic to stderr (or use the existing logger
if available) including sinkURL and the error and only suppress printing in
production mode; update the call site in doFlush to: err := postToServer(url,
body) and handle err by logging to stderr/dev logger so sink connectivity issues
are visible (references: doFlush, postToServer, sinkURL, sinkPayload,
sinkBuffer).
In `@libs/logger/wasm/build.sh`:
- Around line 1-13: The build script build.sh lacks defensive checks and can
fail with unclear errors; add explicit checks before running tinygo build:
verify tinygo exists (e.g., ensure `tinygo` is on PATH), ensure the script is
executed from the repository root or check that target output directories
(../browser/src) exist and are writable, and confirm `tinygo env TINYGOROOT`
returns a valid path before attempting to copy wasm_exec.js; update the script
to exit with clear error messages if any check fails and only run `tinygo build`
and `cp "$TINYGOROOT/targets/wasm_exec.js"` after validations succeed.
In `@libs/logger/wasm/main.go`:
- Around line 48-51: The code silently ignores errors from json.Unmarshal when
decoding contextJSON into the local variable context; update the block that
declares context and calls json.Unmarshal so that it captures the returned error
(from json.Unmarshal([]byte(contextJSON), &context)) and, if non-nil, emits a
warning via the package logger (or process logger) including the contextJSON and
the error; keep behaviour of leaving context nil/empty on error but log the
failure for debugging.
- Around line 11-15: The nextID counter currently typed as int can overflow in
extremely long-running sessions; change nextID to a larger unsigned type (e.g.,
uint64) and update the loggers map key type from map[int]*logger.Logger to
map[uint64]*logger.Logger, adjusting all uses of nextID, loggers, and loggersMu
accordingly (or alternatively implement an ID pool/recycle mechanism: maintain a
freeIDs slice/stack and pop/push IDs when creating/destroying loggers inside the
protected loggersMu critical section) so IDs never wrap unexpectedly.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: e7d59208-2652-4378-bcab-89351994590e
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (84)
.github/actions/setup-deps/action.yml.github/workflows/build.yml.github/workflows/claude-pr-review.yml.github/workflows/package-pull-request.yml.github/workflows/package-release.yml.github/workflows/test.yml.gitignoreAGENTS.mdCLAUDE.mdapps/cli/src/config.tsapps/cli/src/index.tsapps/cli/src/logger.tsapps/cli/tsconfig.jsonapps/desktop-app/package.jsonapps/desktop-app/src/logger.tsapps/desktop-app/src/main.tsapps/desktop-app/tsconfig.jsonapps/desktop-app/tsup.config.tsapps/server/src/index.tsapps/server/src/logger.tsapps/server/src/manager.tsapps/server/src/routes/claude-plugins.tsapps/server/src/routes/logs.tsapps/server/src/standalone.tsapps/server/tsconfig.jsonapps/server/vitest.config.tsapps/web-app/src/App.tsxapps/web-app/src/components/PanelErrorBoundary.tsxapps/web-app/src/components/detail/CustomTaskDetailPanel.tsxapps/web-app/src/components/detail/DetailPanel.tsxapps/web-app/src/components/detail/JiraDetailPanel.tsxapps/web-app/src/components/detail/TerminalView.test.tsxapps/web-app/src/components/detail/TerminalView.tsxapps/web-app/src/hooks/useTerminal.tsapps/web-app/src/hooks/useWorktrees.test.tsapps/web-app/src/logger.tsapps/web-app/tsconfig.jsonapps/web-app/vite.config.tsapps/website/package.jsondocs/superpowers/plans/2026-03-14-centralized-logger-sink.mddocs/superpowers/specs/2026-03-14-centralized-logger-sink-design.mddocs/superpowers/specs/2026-03-14-extension-system-design.mdlibs/agents/package.jsonlibs/agents/tsconfig.jsonlibs/integrations/package.jsonlibs/integrations/src/github/logger.tslibs/integrations/src/jira/logger.tslibs/integrations/src/linear/logger.tslibs/integrations/tsconfig.jsonlibs/logger/browser/package.jsonlibs/logger/browser/src/.gitignorelibs/logger/browser/src/index.tslibs/logger/browser/src/types.tslibs/logger/browser/src/wasm_exec.d.tslibs/logger/browser/tsconfig.jsonlibs/logger/cgo/exports.golibs/logger/logger.golibs/logger/node/package.jsonlibs/logger/node/src/bindings.tslibs/logger/node/src/index.test.tslibs/logger/node/src/index.tslibs/logger/node/src/types.tslibs/logger/node/tsconfig.jsonlibs/logger/output_native.golibs/logger/output_wasm.golibs/logger/post_native.golibs/logger/post_wasm.golibs/logger/project.jsonlibs/logger/python/bindings.pylibs/logger/python/logger.pylibs/logger/python/logger.pyilibs/logger/sink.golibs/logger/wasm/build.shlibs/logger/wasm/go.modlibs/logger/wasm/main.golibs/logger/zig/logger.ziglibs/shared/src/errors.tslibs/shared/src/index.tslibs/shared/tsconfig.jsonnx.jsonpackage.jsontsconfig.apps.jsontsconfig.libs.jsontsconfig.workspace.json
💤 Files with no reviewable changes (6)
- nx.json
- apps/web-app/src/components/detail/CustomTaskDetailPanel.tsx
- tsconfig.libs.json
- tsconfig.workspace.json
- apps/web-app/src/components/detail/JiraDetailPanel.tsx
- tsconfig.apps.json
✅ Files skipped from review due to trivial changes (6)
- libs/integrations/package.json
- libs/logger/browser/src/wasm_exec.d.ts
- libs/logger/browser/package.json
- libs/logger/browser/src/.gitignore
- libs/logger/browser/tsconfig.json
- libs/logger/wasm/go.mod
🚧 Files skipped from review as they are similar to previous changes (2)
- apps/web-app/src/App.tsx
- apps/web-app/src/components/detail/TerminalView.test.tsx
| - name: Restore Claude auth | ||
| run: echo '${{ secrets.CLAUDE_AUTH_JSON }}' > ~/.claude.json |
There was a problem hiding this comment.
Secret handling could be more secure.
Using echo with the secret as a string literal could expose the secret in logs if there's a shell parsing error. Consider using a heredoc or writing via a more secure method:
🛡️ Proposed fix for safer secret handling
- name: Restore Claude auth
- run: echo '${{ secrets.CLAUDE_AUTH_JSON }}' > ~/.claude.json
+ run: |
+ cat > ~/.claude.json << 'EOF'
+ ${{ secrets.CLAUDE_AUTH_JSON }}
+ EOF
+ chmod 600 ~/.claude.json📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| - name: Restore Claude auth | |
| run: echo '${{ secrets.CLAUDE_AUTH_JSON }}' > ~/.claude.json | |
| - name: Restore Claude auth | |
| run: | | |
| cat > ~/.claude.json << 'EOF' | |
| ${{ secrets.CLAUDE_AUTH_JSON }} | |
| EOF | |
| chmod 600 ~/.claude.json |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In @.github/workflows/claude-pr-review.yml around lines 19 - 20, The "Restore
Claude auth" step writes the secret with echo which can leak on shell errors;
replace the echo command with a safer write using a heredoc or printf and
restrict file permissions. Specifically, in the Restore Claude auth step (name:
"Restore Claude auth") write the secret via a heredoc: cat > ~/.claude.json
<<'EOF' "${{ secrets.CLAUDE_AUTH_JSON }}" EOF (or printf '%s' "${{
secrets.CLAUDE_AUTH_JSON }}" > ~/.claude.json) and immediately chmod 600
~/.claude.json (or set umask 077 before writing) to ensure the file is created
with tight permissions and avoid shell interpolation that could expose the
secret.
| - name: Run Claude review | ||
| env: | ||
| BASE_REF: ${{ github.event.pull_request.base.ref }} | ||
| run: | | ||
| DIFF=$(git diff "origin/$BASE_REF"...HEAD) | ||
| claude --print \ | ||
| --max-turns 5 \ | ||
| "Review this pull request diff for code quality, bugs, security issues, and adherence to project conventions. Be concise and actionable. | ||
|
|
||
| ${DIFF}" \ | ||
| > /tmp/review-output.txt |
There was a problem hiding this comment.
Shell injection and argument length risks with inline diff.
Embedding the entire diff as a shell variable inside the prompt has several risks:
- Argument length limits: Large diffs may exceed
ARG_MAX(~2MB on Linux), causing the command to fail silently. - Shell escaping issues: Special characters in the diff (backticks,
$, quotes) could break shell parsing or be interpreted. - Missing error handling: If
claudefails, the workflow continues and may post empty/corrupted output.
🔧 Proposed fix using file-based input and error handling
- name: Run Claude review
env:
BASE_REF: ${{ github.event.pull_request.base.ref }}
run: |
- DIFF=$(git diff "origin/$BASE_REF"...HEAD)
- claude --print \
+ git diff "origin/$BASE_REF"...HEAD > /tmp/pr-diff.txt
+
+ if [ ! -s /tmp/pr-diff.txt ]; then
+ echo "No diff found" > /tmp/review-output.txt
+ exit 0
+ fi
+
+ claude --print \
--max-turns 5 \
- "Review this pull request diff for code quality, bugs, security issues, and adherence to project conventions. Be concise and actionable.
-
- ${DIFF}" \
- > /tmp/review-output.txt
+ "Review this pull request diff for code quality, bugs, security issues, and adherence to project conventions. Be concise and actionable. The diff is in the file /tmp/pr-diff.txt" \
+ < /tmp/pr-diff.txt \
+ > /tmp/review-output.txt || {
+ echo "Claude review failed with exit code $?" > /tmp/review-output.txt
+ }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In @.github/workflows/claude-pr-review.yml around lines 22 - 32, Replace the
inline DIFF variable with a file-based approach and add strict error handling:
write the diff to a temp file (e.g., DIFF_FILE=/tmp/pr_diff.txt using git diff
"origin/$BASE_REF"...HEAD > "$DIFF_FILE"), enable safe shell options (set -euo
pipefail) in the Run Claude review step, invoke claude reading from that file
via stdin (claude --print --max-turns 5 "Review this pull request diff..." <
"$DIFF_FILE" > /tmp/review-output.txt) and check claude's exit status (if
non-zero, echo an error to stderr and exit 1) to avoid ARG_MAX, escaping issues,
and silent failures; reference the DIFF variable, claude --print invocation, and
/tmp/review-output.txt when making the changes.
| logDeletePhase("destroy-terminals-for-target-worktree-only", "failure", { | ||
| worktreeId, | ||
| error: error instanceof Error ? error.message : String(error), | ||
| error, | ||
| }); |
There was a problem hiding this comment.
Normalize phase-failure error metadata to string values.
At Line 1436 and Line 1520, storing the raw error object can collapse during JSON serialization. Use toErrorMessage(error) so ops-log metadata is consistently searchable.
💡 Proposed fix
} catch (error) {
logDeletePhase("destroy-terminals-for-target-worktree-only", "failure", {
worktreeId,
- error,
+ error: toErrorMessage(error),
});
return finalize({
success: false,
code: "WORKTREE_REMOVE_FAILED",
@@
} catch (error) {
logDeletePhase("remove-worktree-from-git/filesystem", "failure", {
worktreeId,
- error,
+ error: toErrorMessage(error),
});
return finalize({
success: false,
code: "WORKTREE_REMOVE_FAILED",Also applies to: 1518-1521
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server/src/manager.ts` around lines 1434 - 1437, The ops-log is storing
raw Error objects in metadata which can break JSON serialization; update the two
calls to logDeletePhase (the one with phase
"destroy-terminals-for-target-worktree-only" and the other around lines
1518–1521) to pass a string by converting the error via toErrorMessage(error)
instead of the raw error object (keep worktreeId and other metadata as-is);
locate the logDeletePhase(...) invocations and replace the error field with
toErrorMessage(error).
| if (!Array.isArray(body.entries)) { | ||
| return c.json({ success: false, error: "entries must be an array" }, 400); | ||
| } | ||
|
|
||
| const opsLog = manager.getOpsLog(); | ||
| const projectName = manager.getProjectName() ?? undefined; | ||
|
|
||
| for (const entry of body.entries) { | ||
| const metadata: Record<string, unknown> = { ...entry.metadata }; | ||
| if (entry.domain) metadata.domain = entry.domain; | ||
|
|
||
| opsLog.addEvent({ | ||
| source: entry.subsystem ? `${entry.system}.${entry.subsystem}` : entry.system, | ||
| action: "log", | ||
| message: entry.message, | ||
| level: entry.level === "warn" ? "warning" : (entry.level as OpsLogLevel), | ||
| status: entry.level === "error" ? "failed" : "info", | ||
| projectName, | ||
| metadata: Object.keys(metadata).length > 0 ? metadata : undefined, | ||
| }); |
There was a problem hiding this comment.
Validate and normalize each client log entry before ingesting.
Line 94 only checks array shape; Lines 101-110 still trust entry fields and cast arbitrary entry.level to OpsLogLevel. Invalid payloads can pollute OpsLog (source, message, level) and reduce reliability of filters/alerts.
Suggested hardening patch
if (!Array.isArray(body.entries)) {
return c.json({ success: false, error: "entries must be an array" }, 400);
}
+ if (body.entries.length > 500) {
+ return c.json({ success: false, error: "entries batch too large" }, 400);
+ }
const opsLog = manager.getOpsLog();
const projectName = manager.getProjectName() ?? undefined;
- for (const entry of body.entries) {
+ for (const [index, entry] of body.entries.entries()) {
+ const system = typeof entry.system === "string" ? entry.system.trim() : "";
+ const subsystem = typeof entry.subsystem === "string" ? entry.subsystem.trim() : "";
+ const message = typeof entry.message === "string" ? entry.message.trim() : "";
+ const rawLevel = typeof entry.level === "string" ? entry.level.trim().toLowerCase() : "";
+
+ if (!system || !message) {
+ return c.json({ success: false, error: `invalid entry at index ${index}` }, 400);
+ }
+
+ const normalizedLevel: OpsLogLevel =
+ rawLevel === "warn" || rawLevel === "warning"
+ ? "warning"
+ : rawLevel === "debug"
+ ? "debug"
+ : rawLevel === "error"
+ ? "error"
+ : "info";
+
const metadata: Record<string, unknown> = { ...entry.metadata };
if (entry.domain) metadata.domain = entry.domain;
opsLog.addEvent({
- source: entry.subsystem ? `${entry.system}.${entry.subsystem}` : entry.system,
+ source: subsystem ? `${system}.${subsystem}` : system,
action: "log",
- message: entry.message,
- level: entry.level === "warn" ? "warning" : (entry.level as OpsLogLevel),
- status: entry.level === "error" ? "failed" : "info",
+ message,
+ level: normalizedLevel,
+ status: normalizedLevel === "error" ? "failed" : "info",
projectName,
metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
});
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (!Array.isArray(body.entries)) { | |
| return c.json({ success: false, error: "entries must be an array" }, 400); | |
| } | |
| const opsLog = manager.getOpsLog(); | |
| const projectName = manager.getProjectName() ?? undefined; | |
| for (const entry of body.entries) { | |
| const metadata: Record<string, unknown> = { ...entry.metadata }; | |
| if (entry.domain) metadata.domain = entry.domain; | |
| opsLog.addEvent({ | |
| source: entry.subsystem ? `${entry.system}.${entry.subsystem}` : entry.system, | |
| action: "log", | |
| message: entry.message, | |
| level: entry.level === "warn" ? "warning" : (entry.level as OpsLogLevel), | |
| status: entry.level === "error" ? "failed" : "info", | |
| projectName, | |
| metadata: Object.keys(metadata).length > 0 ? metadata : undefined, | |
| }); | |
| if (!Array.isArray(body.entries)) { | |
| return c.json({ success: false, error: "entries must be an array" }, 400); | |
| } | |
| if (body.entries.length > 500) { | |
| return c.json({ success: false, error: "entries batch too large" }, 400); | |
| } | |
| const opsLog = manager.getOpsLog(); | |
| const projectName = manager.getProjectName() ?? undefined; | |
| for (const [index, entry] of body.entries.entries()) { | |
| const system = typeof entry.system === "string" ? entry.system.trim() : ""; | |
| const subsystem = typeof entry.subsystem === "string" ? entry.subsystem.trim() : ""; | |
| const message = typeof entry.message === "string" ? entry.message.trim() : ""; | |
| const rawLevel = typeof entry.level === "string" ? entry.level.trim().toLowerCase() : ""; | |
| if (!system || !message) { | |
| return c.json({ success: false, error: `invalid entry at index ${index}` }, 400); | |
| } | |
| const normalizedLevel: OpsLogLevel = | |
| rawLevel === "warn" || rawLevel === "warning" | |
| ? "warning" | |
| : rawLevel === "debug" | |
| ? "debug" | |
| : rawLevel === "error" | |
| ? "error" | |
| : "info"; | |
| const metadata: Record<string, unknown> = { ...entry.metadata }; | |
| if (entry.domain) metadata.domain = entry.domain; | |
| opsLog.addEvent({ | |
| source: subsystem ? `${system}.${subsystem}` : system, | |
| action: "log", | |
| message, | |
| level: normalizedLevel, | |
| status: normalizedLevel === "error" ? "failed" : "info", | |
| projectName, | |
| metadata: Object.keys(metadata).length > 0 ? metadata : undefined, | |
| }); | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server/src/routes/logs.ts` around lines 94 - 113, Validate and normalize
each incoming entry before calling manager.getOpsLog().addEvent: ensure
entry.system is a non-empty string and entry.message is a string (reject or skip
entries that fail), coerce entry.subsystem if present to a string, normalize
entry.level to a known set (map incoming values like "warn" => "warning", accept
only ["debug","info","warning","error"], default to "info") and derive status
from the normalized level (e.g., "error" => "failed", others => "info"), build
source as subsystem present ? `${system}.${subsystem}` : system, ensure metadata
is a plain object (fall back to undefined if not an object or empty), and only
then call opsLog.addEvent with the sanitized fields; update any casting of
entry.level to OpsLogLevel to use the normalized value so invalid values can't
pollute OpsLog.
| 2. Read `extensions` array from project config (`.openkit/config.json`) | ||
| 3. Merge: project extensions add to global; `disabledExtensions` excludes by name | ||
| 4. For each extension source: | ||
| a. If `github:owner/repo` → clone/pull to `~/.openkit/extension-cache/<name>/` |
There was a problem hiding this comment.
Use official capitalization: GitHub.
Line 330 uses github:owner/repo in prose; the platform name should be capitalized for consistency and professionalism.
🧰 Tools
🪛 LanguageTool
[uncategorized] ~330-330: The official name of this software platform is spelled with a capital “H”./.openkit...
Context: ... 4. For each extension source: a. If github:owner/repo → clone/pull to `
(GITHUB)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@docs/superpowers/specs/2026-03-14-extension-system-design.md` at line 330,
The prose uses the lowercase platform name `github:owner/repo`; update it to use
the official capitalization `GitHub:owner/repo` (e.g., change
`github:owner/repo` to `GitHub:owner/repo`) in the spec line that reads "If
`github:owner/repo` → clone/pull to `~/.openkit/extension-cache/<name>/`" so the
platform name is capitalized consistently.
| info(message: string, context?: LogContext): void { | ||
| const ctx = normalizeContext(context); | ||
| const bindings = getBindings(); | ||
| bindings.LoggerInfo(this.handle, message, JSON.stringify(ctx || {})); | ||
|
|
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify current unguarded serialization callsites.
rg -n -C1 'JSON\.stringify\(ctx \|\| \{\}\)' libs/logger/node/src/index.tsRepository: fum4/openkit
Length of output: 808
Wrap context serialization in error handler to prevent logging failures.
Six methods (info, warn, error, debug, success, plain) call JSON.stringify(ctx || {}) without error handling. This can throw on circular references, BigInt values, or other non-serializable objects, breaking the logging pipeline. Logging should degrade gracefully.
Extract a serializeContext() helper that wraps JSON.stringify in a try-catch, returning "{}" on serialization failure:
Suggested implementation
+ private serializeContext(context?: Record<string, unknown>): string {
+ if (!context) return "{}";
+ try {
+ return JSON.stringify(context);
+ } catch {
+ return "{}";
+ }
+ }Then replace all six callsites:
- Line 84:
bindings.LoggerInfo(this.handle, message, this.serializeContext(ctx)); - Line 96:
bindings.LoggerWarn(this.handle, message, this.serializeContext(ctx)); - Line 108:
bindings.LoggerError(this.handle, message, this.serializeContext(ctx)); - Line 120:
bindings.LoggerDebug(this.handle, message, this.serializeContext(ctx)); - Line 132:
bindings.LoggerSuccess(this.handle, message, this.serializeContext(ctx)); - Line 144:
bindings.LoggerPlain(this.handle, message, this.serializeContext(ctx));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@libs/logger/node/src/index.ts` around lines 81 - 85, Create a
serializeContext helper on the logger class that wraps JSON.stringify(ctx || {})
in a try-catch and returns the serialized string or "{}" on any error, then
update the six methods info, warn, error, debug, success, and plain to call
bindings.LoggerInfo/LoggerWarn/LoggerError/LoggerDebug/LoggerSuccess/LoggerPlain
with this.serializeContext(ctx) instead of direct JSON.stringify(ctx || {});
reference the existing method names (info, warn, error, debug, success, plain)
and the binding calls (LoggerInfo, LoggerWarn, LoggerError, LoggerDebug,
LoggerSuccess, LoggerPlain) when making the replacements.
| "{projectRoot}/wasm/**/*.go", | ||
| "{projectRoot}/wasm/go.mod", |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Checking whether wasm build script exists and is tracked by Nx inputs..."
fd -a '^build\.sh$' libs/logger/wasm || true
python - <<'PY'
import json
from pathlib import Path
project = Path("libs/logger/project.json")
cfg = json.loads(project.read_text())
inputs = cfg["targets"]["build"]["inputs"]
expected = "{projectRoot}/wasm/build.sh"
exists = Path("libs/logger/wasm/build.sh").exists()
tracked = expected in inputs
print(f"wasm_build_sh_exists={exists}")
print(f"wasm_build_sh_tracked_in_inputs={tracked}")
if exists and not tracked:
print("RESULT: mismatch confirmed (cache invalidation risk).")
else:
print("RESULT: no mismatch detected for this check.")
PYRepository: fum4/openkit
Length of output: 291
Add wasm/build.sh to build inputs to prevent stale cache.
The build target executes cd wasm && ./build.sh, but {projectRoot}/wasm/build.sh is not listed in targets.build.inputs. Changes to this script will not trigger cache invalidation.
Suggested fix
"inputs": [
"{projectRoot}/*.go",
"{projectRoot}/go.mod",
"{projectRoot}/cgo/**/*.go",
"{projectRoot}/cgo/go.mod",
"{projectRoot}/cgo/build.sh",
"{projectRoot}/node/src/**/*.ts",
"{projectRoot}/wasm/**/*.go",
"{projectRoot}/wasm/go.mod",
+ "{projectRoot}/wasm/build.sh",
"{projectRoot}/zig/**/*.zig"
],📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| "{projectRoot}/wasm/**/*.go", | |
| "{projectRoot}/wasm/go.mod", | |
| "{projectRoot}/wasm/**/*.go", | |
| "{projectRoot}/wasm/go.mod", | |
| "{projectRoot}/wasm/build.sh", |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@libs/logger/project.json` around lines 20 - 21, The build target's inputs
list (targets.build.inputs) is missing the wasm build script, so edits to
wasm/build.sh won't invalidate the cache; add "{projectRoot}/wasm/build.sh" to
targets.build.inputs alongside the existing wasm files so that changes to that
script trigger rebuilds for the build target (look for the targets.build.inputs
array in project.json and include the wasm/build.sh path).
| // CloseSink flushes remaining entries and stops the background goroutine. | ||
| func CloseSink() { | ||
| sinkMu.Lock() | ||
| if sinkDone != nil { | ||
| close(sinkDone) | ||
| sinkDone = nil | ||
| } | ||
| if sinkTicker != nil { | ||
| sinkTicker.Stop() | ||
| sinkTicker = nil | ||
| } | ||
| sinkURL = "" | ||
| sinkMu.Unlock() | ||
| } |
There was a problem hiding this comment.
CloseSink doesn't wait for the final flush to complete.
After closing sinkDone, the goroutine receives the signal and calls doFlush(), but CloseSink returns immediately without waiting. If the process exits right after CloseSink(), the HTTP POST may not complete.
💡 Suggested fix using a done channel or WaitGroup
var (
sinkURL string
sinkProjectName string
sinkBuffer []sinkEntry
sinkMu sync.Mutex
sinkTicker *time.Ticker
sinkDone chan struct{}
+ sinkExited chan struct{}
)
// In SetSink, after starting goroutine:
+ sinkExited = make(chan struct{})
go func() {
+ defer close(sinkExited)
for {
select {
case <-sinkTicker.C:
doFlush()
case <-sinkDone:
doFlush()
return
}
}
}()
// CloseSink waits for goroutine to exit:
func CloseSink() {
sinkMu.Lock()
+ done := sinkDone
+ exited := sinkExited
if sinkDone != nil {
close(sinkDone)
sinkDone = nil
}
if sinkTicker != nil {
sinkTicker.Stop()
sinkTicker = nil
}
sinkURL = ""
sinkMu.Unlock()
+
+ if done != nil && exited != nil {
+ <-exited // wait for final flush
+ }
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@libs/logger/sink.go` around lines 78 - 91, CloseSink currently closes
sinkDone and returns immediately while the background goroutine may still be
running doFlush, risking an incomplete HTTP POST; update CloseSink to wait for
the goroutine to finish the final flush (e.g., add a done channel or a
sync.WaitGroup that the goroutine signals after doFlush completes) before
unlocking and returning, keep using sinkDone to trigger the shutdown, and then
stop sinkTicker and clear sinkURL/sinkDone/sinkTicker only after the waiter
confirms the goroutine has exited.
| pub fn setSink(server_url: [*:0]const u8, project_name: [*:0]const u8) void { | ||
| const syms = resolved orelse return; | ||
| syms.set_sink(server_url, project_name); | ||
| } | ||
|
|
||
| /// Flush remaining entries and stop the sink. | ||
| pub fn closeSink() void { | ||
| const syms = resolved orelse return; | ||
| syms.close_sink(); |
There was a problem hiding this comment.
setSink/closeSink can silently no-op before symbol resolution.
At Line 138 and Line 144, these methods use resolved directly. If no logger was initialized yet, sink configuration never applies even when the library is available.
🔧 Proposed fix
pub const Logger = struct {
@@
/// Configure the Go logger to POST entries to a server endpoint.
pub fn setSink(server_url: [*:0]const u8, project_name: [*:0]const u8) void {
- const syms = resolved orelse return;
+ const syms = resolveSymbols() orelse return;
syms.set_sink(server_url, project_name);
}
@@
/// Flush remaining entries and stop the sink.
pub fn closeSink() void {
- const syms = resolved orelse return;
+ const syms = resolveSymbols() orelse return;
syms.close_sink();
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| pub fn setSink(server_url: [*:0]const u8, project_name: [*:0]const u8) void { | |
| const syms = resolved orelse return; | |
| syms.set_sink(server_url, project_name); | |
| } | |
| /// Flush remaining entries and stop the sink. | |
| pub fn closeSink() void { | |
| const syms = resolved orelse return; | |
| syms.close_sink(); | |
| pub fn setSink(server_url: [*:0]const u8, project_name: [*:0]const u8) void { | |
| const syms = resolveSymbols() orelse return; | |
| syms.set_sink(server_url, project_name); | |
| } | |
| /// Flush remaining entries and stop the sink. | |
| pub fn closeSink() void { | |
| const syms = resolveSymbols() orelse return; | |
| syms.close_sink(); | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@libs/logger/zig/logger.zig` around lines 137 - 145, setSink and closeSink
currently return silently if `resolved` is not available; change them to record
the requested action when symbols aren't resolved: in `setSink`, if `resolved`
is null save `server_url` and `project_name` into module-level pending variables
and return, and when `resolved` is later populated call `syms.set_sink` with
those saved values; in `closeSink`, if `resolved` is null set a pending_close
boolean (or similar) so that when `resolved` is set the code will invoke
`syms.close_sink()`; ensure the code path that initializes `resolved` applies
any pending set_sink or close_sink actions after resolution.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
.github/actions/setup-deps/action.yml (1)
47-49: Pinacifani/setup-tinygoto a commit SHA for supply-chain safety.Using
@v2is mutable. Pinning to a resolved commit SHA hardens CI reproducibility and trust.🔐 Proposed hardening
- uses: acifani/setup-tinygo@v2 + uses: acifani/setup-tinygo@db56321a62b9a67922bb9ac8f9d085e218807bb3🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.github/actions/setup-deps/action.yml around lines 47 - 49, The workflow currently uses the mutable tag acifani/setup-tinygo@v2; replace that with a specific commit SHA to pin the action for supply-chain safety (e.g., change the reference in the action invocation where acifani/setup-tinygo@v2 appears to acifani/setup-tinygo@<commit-sha>), keeping the existing inputs (tinygo-version: ${{ inputs.tinygo }}) unchanged so behavior is identical but the dependency is immutable and reproducible.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In @.github/actions/setup-deps/action.yml:
- Around line 46-49: The if conditions use contains(inputs.deps, '...') which
does substring matching (so 'go' matches 'tinygo'); update each condition (e.g.,
contains(inputs.deps, 'tinygo'), contains(inputs.deps, 'go'), etc.) to use
delimiter-safe matching by wrapping the deps string and token with spaces and
searching for the space-padded token (e.g., use contains(concat(' ',
inputs.deps, ' '), ' tinygo ') for every deps check) so tokens are matched
exactly when comma/space separated.
---
Nitpick comments:
In @.github/actions/setup-deps/action.yml:
- Around line 47-49: The workflow currently uses the mutable tag
acifani/setup-tinygo@v2; replace that with a specific commit SHA to pin the
action for supply-chain safety (e.g., change the reference in the action
invocation where acifani/setup-tinygo@v2 appears to
acifani/setup-tinygo@<commit-sha>), keeping the existing inputs (tinygo-version:
${{ inputs.tinygo }}) unchanged so behavior is identical but the dependency is
immutable and reproducible.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: fe2c647a-b7dc-4619-87ff-ef71187698d0
📒 Files selected for processing (1)
.github/actions/setup-deps/action.yml
Summary
claudeCLI binary detects inherited nesting markers in the environment and suppresses all output. This PR strips IDE-specific env vars (CLAUDECODE*,VSCODE_*,CURSOR_*,CLAUDE_CODE_*,CLAUDE_AGENT_*) from the server spawner and usesspawnwithdetached: true+ a minimal clean env in the plugin routes to break the nesting detection chain./api/claude/plugins/debugdiagnostic endpoint with timing and env inspection.Changes
Claude CLI & Server Spawner
apps/desktop-app/src/server-spawner.ts— strip inherited IDE/Claude Code nesting env vars before spawning the server processapps/server/src/routes/claude-plugins.ts— replaceexecFilewithspawn+detached: true, minimal clean env, ops logging, retry logic, enhanced debug endpointProject-Switching Fixes
apps/web-app/src/App.tsx— reset state properly when active project changesapps/web-app/src/components/detail/DetailPanel.tsx— guard against stale worktree referencesapps/web-app/src/components/detail/TerminalView.tsx— fix terminal crash on project switchapps/web-app/src/hooks/useApi.ts— staleness detection for previous project dataapps/web-app/src/hooks/useTerminal.ts— terminal hook cleanup and re-initializationapps/web-app/src/hooks/useWorktrees.ts— reset worktree cache on project changeTests
apps/server/src/terminal-manager.test.ts— terminal session lifecycle and scoped reuse testsapps/web-app/src/components/detail/TerminalView.test.tsx— terminal view project-switching testsapps/web-app/src/hooks/useWorktrees.test.ts— worktree fetching staleness testsTest plan
pnpm run dev:desktop-appfrom Cursorpnpm test— all tests pass🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes
Documentation