Repository navigation
Conversation
…lines budget The four daemon modules, the local-PTY shell-ready provider, three runtime RPC method files, and the orchestration coordinator each carried a file-level `eslint-disable max-lines` and ran 373-785 counted lines against a 300-line budget. AGENTS.md calls for splitting rather than suppressing, and config/max-lines-baseline.txt is a shrink-only ratchet, so this removes all nine suppressions and prunes their entries (341 -> 332). Pure move, no behavior change. session.ts is cut into the pieces it already had -- subprocess handle, options, pending-output buffer, output plane, shell-ready barrier, termination controller, producer pause, exit finalizer, and the Windows ConPTY prompt repaint; client.ts into endpoint identity, socket connect, hello handshake, pending requests, and NDJSON readers; shell-ready into a dependency-free wrapper contract plus per-shell rcfile builders, so the module graph stays a DAG with SHELL_READY_MARKER at the root. Per-session and per-connection state is preserved as such throughout: nothing that was instance or closure state became module-level, so two sessions cannot share a buffer, barrier, or pending-request map. This is the largest blast radius in the series -- session.ts alone has ~33 importers -- and every one of those edits is import-path-only. Verified: oxlint clean, ratchet passes, typecheck clean, full unit suite green (the one remaining failure is a pre-existing load flake in an untouched file, green when re-run serially), no new runtime import cycles, and no lint suppression added anywhere.
|
Too many files changed for review (113 files, 100 file limit). Bypass the limit by tagging |
📝 WalkthroughWalkthroughThe change extracts daemon client transport, handshake, request, identity, health, and stale-process logic into dedicated modules. Session output, shell readiness, producer flow control, termination, and exit finalization move into focused controllers. Shell wrapper generation and installation are separated from launch configuration. Coordinator reconciliation and task dispatch move into standalone modules. File, Git, and GitHub RPC schemas and handlers are grouped into dedicated registries. Imports and tests are updated to use the new module boundaries. Merge Risk: 🟠 High · up to This refactor changes daemon connection handoff and shell-wrapper file handling, and the current implementation can lose stream events, allow unsafe local replacement of shell-sourced wrapper files, or truncate wrappers during startup; invalid legacy PID records can also block daemon recovery. These concrete correctness, security, and availability risks should be fixed before merging. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 2📝 Generate docstrings 💡
⚔️ Resolve merge conflicts 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (13)
src/main/runtime/rpc/methods/git-source-control-ai-methods.ts (1)
19-20: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove this redundant comment.
buildCommitMessageGenerationOverrideand its conditional already describe this behavior. As per coding guidelines: “Comments must be concise, non-obvious, and brief—prefer one line.”Source: Coding guidelines
src/main/runtime/orchestration/coordinator-task-dispatch.ts (1)
189-191: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winLog the swallowed
listTerminalserror.The catch block returns an empty list without any log. The caller then treats the tick as having no terminals and tries
createTerminal. A runtime transport failure therefore produces no direct signal aboutlistTerminals.♻️ Proposed change
- } catch { + } catch (err) { + ctx.opts.onLog(`listTerminals failed: ${String(err)}`) return [] }src/main/runtime/rpc/methods/github-project-methods.ts (1)
66-127: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReuse
SlugRepoinstead of re-declaring the owner/repo/host triple.Six schemas repeat
owner,repo, andhostwith the same error messages thatSlugRepoalready declares. The repeated 2-line host comment is then also duplicated six times.SlugRepo.extend(...)produces the same validation result, so the change is behavior-preserving and removes the risk of the message set drifting between schemas.The same pattern applies at lines 13-24:
ProjectViewTablerepeats every field ofProjectViewsand can extend it.♻️ Proposed refactor
-const SlugIssueUpdate = z.object({ - owner: requiredString('Missing owner'), - repo: requiredString('Missing repo'), - // Why: Enterprise host identity must survive RPC parsing; Zod strips - // undeclared fields before the runtime can host-qualify gh requests. - host: OptionalString, +const SlugIssueUpdate = SlugRepo.extend({ number: z.number().int().positive(), updates: IssueUpdate })Apply the same change to
SlugPullRequestUpdate,SlugIssueTypeUpdate,SlugIssueComment,SlugIssueCommentEdit, andSlugIssueCommentDelete, and deriveProjectViewTablefromProjectViews:-const ProjectViewTable = z.object({ - owner: requiredString('Missing owner'), - // Why: Enterprise host identity must survive RPC parsing; Zod strips - // undeclared fields before the runtime can host-qualify gh requests. - host: OptionalString, - ownerType: ProjectOwnerType, - projectNumber: z.number().int().positive(), +const ProjectViewTable = ProjectViews.extend({ viewId: OptionalString, viewNumber: z.number().int().positive().optional(), viewName: OptionalString, queryOverride: OptionalString })
ProjectViewsmust be declared beforeProjectViewTableafter this change.src/main/runtime/rpc/methods/github-pull-request-update-methods.ts (1)
42-52: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider one shared reviewer schema.
RequestPrReviewersandRemovePrReviewersdeclare identical fields. A singlePrReviewersschema used by both methods keeps the two RPC contracts in step.♻️ Proposed refactor
-const RequestPrReviewers = RepoSelector.extend({ - prNumber: z.number().int().positive(), - prRepo: SlugRepo.nullable().optional(), - reviewers: z.array(z.string()).min(1) -}) - -const RemovePrReviewers = RepoSelector.extend({ +const PrReviewers = RepoSelector.extend({ prNumber: z.number().int().positive(), prRepo: SlugRepo.nullable().optional(), reviewers: z.array(z.string()).min(1) })Then reference
PrReviewersat lines 98 and 109.src/main/daemon/os-process-identity.ts (1)
13-36: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winCache the
CLK_TCKvalue instead of spawninggetconfon every call.
getLinuxProcessStartedAtMsspawnsgetconfsynchronously on each invocation.startTimeMatchescalls it during every daemon identity inspection, andkillStaleDaemoninspects identity up to twice per attempt. The clock tick rate is constant for the life of the process, so the repeated synchronous spawn blocks the Electron main thread without new information. The comment at lines 173-179 shows the same cost concern for the Windows path.♻️ Proposed refactor
+let cachedTicksPerSecond: number | null = null + +function getClockTicksPerSecond(): number { + if (cachedTicksPerSecond === null) { + cachedTicksPerSecond = Number( + execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8', timeout: 1_000 }).trim() + ) + } + return cachedTicksPerSecond +} + function getLinuxProcessStartedAtMs(pid: number): number | null { try { const stat = readFileSync(`/proc/${pid}/stat`, 'utf8') const startTicks = parseLinuxProcStartTicks(stat) const bootTimeSeconds = parseLinuxBootTimeSeconds(readFileSync('/proc/stat', 'utf8')) - const ticksPerSecond = Number( - execFileSync('getconf', ['CLK_TCK'], { - encoding: 'utf8', - timeout: 1_000 - }).trim() - ) + const ticksPerSecond = getClockTicksPerSecond()src/main/daemon/stale-daemon-kill.ts (1)
109-119: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReuse
waitForProcessExitfor the SIGTERM wait.Lines 109-119 reimplement the poll loop that
waitForProcessExitalready provides. Two copies of the exit-wait semantics can diverge, and the SIGKILL confirmation at line 154 already uses the helper.♻️ Proposed refactor
- const deadline = Date.now() + KILL_WAIT_MS - let exited = false - while (Date.now() < deadline) { - try { - process.kill(pid, 0) - } catch { - exited = true - break - } - await new Promise((resolve) => setTimeout(resolve, KILL_POLL_MS)) - } + let exited = await waitForProcessExit(pid, KILL_WAIT_MS)src/main/daemon/windows-conpty-prompt-repaint.ts (1)
4-7: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winShorten the new comments.
Replace each multi-line implementation explanation with one concise rationale. As per coding guidelines, comments must be concise, non-obvious, and brief.
Also applies to: 16-17
Source: Coding guidelines
src/main/daemon/session-exit-finalizer.ts (1)
66-71: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMove the ordering comment next to the statement it protects.
The comment describes the
wasTerminatingcapture on Line 71. It sits abovereleaseDeviceAttributes()on Line 68, so a later edit can move the capture without noticing the constraint.♻️ Proposed comment relocation
- // Why: `wasTerminating` below must be read BEFORE the `_state = 'exited'` flip — it guards the - // "dispose while kill() in flight" case and the invariant needs the pre-flip `_state`; do NOT move it down. this.opts.barrier.releaseDeviceAttributes() this.opts.barrier.releaseHeldBytes() this.opts.startupIngress.drainAndClose() + // Read before the `_state = 'exited'` flip: guards "dispose while kill() in flight" and needs the pre-flip state. const wasTerminating = this.opts.termination.isTerminating && this.opts.getState() !== 'exited'src/main/daemon/session-termination-controller.ts (1)
31-33: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDrop the duplicated
subprocessfield.The class stores
optsand a separatethis.subprocessthat points atopts.subprocess. Two names for one dependency invite divergence during later edits. Readthis.opts.subprocessas the other members do.src/main/daemon/shell-ready-wrapper-contract.ts (1)
15-23: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider deriving this list and the writer's file list from one source.
shell-ready-wrapper-files.tsbuilds the same five wrapper paths independently at lines 60-66. The two lists must stay in sync. If a wrapper file is added to the writer only,shellReadyWrappersExiststill reportstrueand the stale-wrapper repair path never runs. Export the relative path list from this module and let the writer map over it.src/main/daemon/shell-ready-wrapper-files.ts (1)
39-57: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider extracting the inline
.zloginbody to a dedicated module.
.zshrcandbash/rcfilecome fromshell-ready-zsh-rcfile.tsandshell-ready-bash-rcfile.ts, but.zprofileand.zloginstay inline here. The__orca_restore_agent_teams_pathfunction at lines 41-48 is also byte-identical to lines 22-29 ofshell-ready-bash-rcfile.ts. Move the.zloginbody next to the other generators and share the PATH-restore snippet through one template.src/main/daemon/shell-ready-zsh-rcfile.ts (1)
5-47: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider sharing one zsh rcfile builder between daemon and providers.
getDaemonZshShellReadyRcfileContentrenders the same script text asgetZshShellReadyRcfileContentinsrc/main/providers/shell-ready-wrapper-rcfiles.ts(lines 138-181). The OSC 133 hooks,__orca_restore_agent_teams_path, the env restore block, and the final ZDOTDIR restore are duplicated. A future fix applied to one copy will silently miss the other.If the daemon fork must not import from
src/main/providers, move the shared builder into a neutral module that both sides import. If the two copies must stay separate, add a comment in each that states why.src/main/providers/shell-ready-wrapper-paths.ts (1)
8-22: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueBuild these paths with
path.posix.joininstead of/literals.Lines 11 and 16-20 concatenate path segments with a hardcoded
/. The coding guidelines require Node path utilities. The generated rcfiles need POSIX separators, sopath.posix.joinkeeps the shell text valid and removes the assumption about the separator.shellReadyWrappersExistalso runs on Windows, whereexistsSyncreceives these strings.As per coding guidelines: "Use
path.joinor Electron/Node path utilities for file paths; never assume/or\."Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: bc6f8dba-95ad-408f-997e-5210fe736669
📒 Files selected for processing (113)
config/max-lines-baseline.txtsrc/main/daemon/client.test.tssrc/main/daemon/client.tssrc/main/daemon/daemon-authenticated-client-activity.test.tssrc/main/daemon/daemon-bundle-identity.tssrc/main/daemon/daemon-bundle-staleness.test.tssrc/main/daemon/daemon-client-hello-handshake.tssrc/main/daemon/daemon-client-ndjson-readers.tssrc/main/daemon/daemon-client-pending-requests.tssrc/main/daemon/daemon-client-socket-connect.tssrc/main/daemon/daemon-endpoint-identity.tssrc/main/daemon/daemon-endpoint-ownership.test.tssrc/main/daemon/daemon-health-endpoint-entry.test.tssrc/main/daemon/daemon-health-socket-cleanup.test.tssrc/main/daemon/daemon-health.test.tssrc/main/daemon/daemon-health.tssrc/main/daemon/daemon-host-relocation.tssrc/main/daemon/daemon-idle-shutdown.test.tssrc/main/daemon/daemon-incarnation-evidence.tssrc/main/daemon/daemon-init.test.tssrc/main/daemon/daemon-init.tssrc/main/daemon/daemon-pid-identity.tssrc/main/daemon/daemon-pid-record.tssrc/main/daemon/daemon-preflight-client-replacement.test.tssrc/main/daemon/daemon-process-inspection.tssrc/main/daemon/daemon-pty-adapter-history-recovery.test.tssrc/main/daemon/daemon-pty-adapter.test.tssrc/main/daemon/daemon-pty-adapter.tssrc/main/daemon/daemon-pty-router-history-handoff.test.tssrc/main/daemon/daemon-pty-upgrade-adoption.test.tssrc/main/daemon/daemon-reattach-checkpoint-isolation.test.tssrc/main/daemon/daemon-restore-scrollback-depth.test.tssrc/main/daemon/daemon-self-retirement-respawn.test.tssrc/main/daemon/daemon-server-attach-only.test.tssrc/main/daemon/daemon-server-attachment-lifecycle.test.tssrc/main/daemon/daemon-server-error-handling.test.tssrc/main/daemon/daemon-server.test.tssrc/main/daemon/daemon-server.tssrc/main/daemon/daemon-session-scrollback-window.test.tssrc/main/daemon/daemon-shutdown-final-checkpoint-caller-deadline.test.tssrc/main/daemon/daemon-spawner.test.tssrc/main/daemon/daemon-stream-droppability-lifecycle.test.tssrc/main/daemon/daemon-tcc-attribution-main-thread.test.tssrc/main/daemon/daemon-tcc-attribution.test.tssrc/main/daemon/daemon-transport-attachment-release.test.tssrc/main/daemon/issue-6814-daemon-failure-classification.test.tssrc/main/daemon/mac-daemon-tcc-attribution.tssrc/main/daemon/os-process-identity.tssrc/main/daemon/pty-subprocess.tssrc/main/daemon/reattach-snapshot.test.tssrc/main/daemon/session-exit-finalizer.tssrc/main/daemon/session-ingest-throughput.bench.test.tssrc/main/daemon/session-options.tssrc/main/daemon/session-output-plane.tssrc/main/daemon/session-pending-output-buffer.tssrc/main/daemon/session-producer-pause.tssrc/main/daemon/session-shell-ready-barrier.tssrc/main/daemon/session-subprocess-handle.tssrc/main/daemon/session-terminal-control.test.tssrc/main/daemon/session-termination-controller.tssrc/main/daemon/session.test.tssrc/main/daemon/session.tssrc/main/daemon/shell-ready-bash-rcfile.tssrc/main/daemon/shell-ready-wrapper-contract.tssrc/main/daemon/shell-ready-wrapper-files.tssrc/main/daemon/shell-ready-zsh-rcfile.tssrc/main/daemon/shell-ready.test.tssrc/main/daemon/shell-ready.tssrc/main/daemon/slow-daemon-session-verification.test.tssrc/main/daemon/stale-daemon-kill.tssrc/main/daemon/terminal-host-agent-session.test.tssrc/main/daemon/terminal-host-attach-only.test.tssrc/main/daemon/terminal-host-options.tssrc/main/daemon/terminal-host-pty-owner-backend.test.tssrc/main/daemon/terminal-host-session-reaping-leak.test.tssrc/main/daemon/terminal-host-startup.test.tssrc/main/daemon/terminal-host-wsl-context.test.tssrc/main/daemon/terminal-host.test.tssrc/main/daemon/windows-conpty-prompt-repaint.tssrc/main/ipc/pty-management.tssrc/main/ipc/pty.tssrc/main/providers/local-pty-shell-ready.test.tssrc/main/providers/local-pty-shell-ready.tssrc/main/providers/shell-ready-wrapper-paths.tssrc/main/providers/shell-ready-wrapper-rcfiles.tssrc/main/providers/shell-ready-wrapper-writer.tssrc/main/providers/windows-shell-args.tssrc/main/pty/codex-preflight-profile-path-rewrite.test.tssrc/main/runtime/orchestration/coordinator-drift-probe-coalescing.test.tssrc/main/runtime/orchestration/coordinator-inbox-reconciliation.tssrc/main/runtime/orchestration/coordinator-run-context.tssrc/main/runtime/orchestration/coordinator-runtime-port.tssrc/main/runtime/orchestration/coordinator-task-dispatch.tssrc/main/runtime/orchestration/coordinator.test.tssrc/main/runtime/orchestration/coordinator.tssrc/main/runtime/remote-agent-session-host-authority.integration.test.tssrc/main/runtime/rpc/methods/file-watch-rpc-methods.tssrc/main/runtime/rpc/methods/files-mutation-rpc-methods.tssrc/main/runtime/rpc/methods/files-params.tssrc/main/runtime/rpc/methods/files-remote-content-budget.tssrc/main/runtime/rpc/methods/files-terminal-artifact-rpc-methods.tssrc/main/runtime/rpc/methods/files.tssrc/main/runtime/rpc/methods/git-diff-compare-methods.tssrc/main/runtime/rpc/methods/git-source-control-ai-methods.tssrc/main/runtime/rpc/methods/git-stage-discard-methods.tssrc/main/runtime/rpc/methods/git.tssrc/main/runtime/rpc/methods/github-issue-update-schema.tssrc/main/runtime/rpc/methods/github-project-methods.tssrc/main/runtime/rpc/methods/github-pull-request-review-methods.tssrc/main/runtime/rpc/methods/github-pull-request-update-methods.tssrc/main/runtime/rpc/methods/github-repo-target-schemas.tssrc/main/runtime/rpc/methods/github.tstests/e2e/fixtures/daemon-lifecycle-entry.ts
💤 Files with no reviewable changes (2)
- config/max-lines-baseline.txt
- src/main/daemon/daemon-health.ts
| const onData = (chunk: Buffer): void => { | ||
| buffer += decoder.write(chunk) | ||
| const newlineIdx = buffer.indexOf('\n') | ||
| if (newlineIdx === -1) { | ||
| return | ||
| } | ||
|
|
||
| const line = buffer.slice(0, newlineIdx) | ||
| try { | ||
| const response = JSON.parse(line) as HelloResponse | ||
| if (response.ok) { | ||
| const identity = parseDaemonEndpointIdentity(response.daemonIdentity) | ||
| if ( | ||
| (protocolVersion >= CLEAN_DISCONNECT_PROTOCOL_VERSION && identity === null) || | ||
| (response.daemonIdentity !== undefined && identity === null) | ||
| ) { | ||
| finish(new DaemonProtocolError('Invalid daemon identity')) | ||
| return | ||
| } | ||
| finish(undefined, identity) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- target file ---'
cat -n src/main/daemon/daemon-client-hello-handshake.ts | sed -n '1,180p'
printf '%s\n' '--- related symbols and call sites ---'
rg -n -C 4 'sendDaemonHello|attachStreamEventReader|DaemonClient|HelloResponse|parseDaemonEndpointIdentity' src/main/daemonRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- client handoff ---'
sed -n '120,185p' src/main/daemon/client.ts
printf '%s\n' '--- NDJSON readers ---'
cat -n src/main/daemon/daemon-client-ndjson-readers.ts | sed -n '1,240p'
printf '%s\n' '--- stream-related tests ---'
sed -n '450,535p' src/main/daemon/client.test.ts
printf '%s\n' '--- daemon-side hello and stream writes ---'
rg -n -C 5 'role|hello|stream|encodeNdjson|socket\.write' src/main/daemon/daemon-server.ts src/main/daemon -g '*.ts' | head -n 260Repository: stablyai/orca
Length of output: 26646
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- server stream setup ---'
sed -n '690,825p' src/main/daemon/daemon-server.ts
printf '%s\n' '--- stream batcher output path ---'
rg -n -C 6 'streamDataBatcher|setupStreamSocket|streamSocket\.write|write\(encodeNdjson' src/main/daemon/daemon-server.ts src/main/daemon/daemon-stream-data-batcher.ts
printf '%s\n' '--- parser behavior ---'
cat -n src/main/daemon/ndjson.ts | sed -n '1,180p'
printf '%s\n' '--- handshake-specific tests ---'
rg -n -C 8 'sendDaemonHello|hello response|hello.*event|same chunk|single.*write|combined' src/main/daemon -g '*.test.ts'Repository: stablyai/orca
Length of output: 39835
🏁 Script executed:
#!/bin/bash
set -eu
node - <<'JS'
const { EventEmitter } = require('node:events')
const { StringDecoder } = require('node:string_decoder')
const socket = new EventEmitter()
let handshakeBuffer = ''
let handshakeResolved = false
let receivedByStreamReader = []
const decoder = new StringDecoder('utf8')
const onHandshakeData = (chunk) => {
handshakeBuffer += decoder.write(chunk)
const newlineIdx = handshakeBuffer.indexOf('\n')
if (newlineIdx === -1) return
const line = handshakeBuffer.slice(0, newlineIdx)
JSON.parse(line)
handshakeResolved = true
socket.removeListener('data', onHandshakeData)
}
socket.on('data', onHandshakeData)
// This models the reader installed by attachStreamEventReader after the promise resolves.
const hello = JSON.stringify({ type: 'hello', ok: true }) + '\n'
const event = JSON.stringify({ type: 'event', event: 'data', payload: { data: 'x' } }) + '\n'
socket.emit('data', Buffer.from(hello + event, 'utf8'))
if (!handshakeResolved) throw new Error('handshake did not resolve')
socket.on('data', (chunk) => {
receivedByStreamReader.push(...chunk.toString('utf8').trim().split('\n').map(JSON.parse))
})
// The second frame was in the same data event, so no later data event delivers it.
if (receivedByStreamReader.length !== 0) {
throw new Error(`unexpectedly received ${receivedByStreamReader.length} frame(s)`)
}
console.log(JSON.stringify({
handshakeResolved,
trailingBytesDiscarded: handshakeBuffer.slice(handshakeBuffer.indexOf('\n') + 1),
streamReaderFramesAfterHandoff: receivedByStreamReader.length
}, null, 2))
JSRepository: stablyai/orca
Length of output: 324
Preserve trailing data during the hello handoff.
When the hello response and a stream event arrive in one data chunk, sendDaemonHello removes its listener after parsing the first line and discards the remaining bytes. attachStreamEventReader is installed too late to receive that event.
Preserve the decoder and parser state across the handoff, or forward all trailing data to attachStreamEventReader. Add a test that writes both frames in one socket.write() call.
| const pid = Number(trimmed) | ||
| return Number.isFinite(pid) | ||
| ? { | ||
| pid, | ||
| startedAtMs: null, | ||
| entryPath: null, | ||
| appVersion: null, | ||
| launchNonce: null, | ||
| linuxStartTicks: null, | ||
| bootId: null, | ||
| spawnerExecPath: null | ||
| } | ||
| : null |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Reject non-positive and non-integer PIDs in the legacy branch.
Number(trimmed) returns 0 for an empty or whitespace-only pid file, and Number.isFinite(0) is true. The function then returns { pid: 0, ... }. stale-daemon-kill.ts treats that as a recorded owner and fences cleanup to pid 0 at line 180 (unlinkOwnedDaemonPidFile(pidPath, 0, null)), so it never reaches the unparseable-record reclaim path at line 186. An empty pid file can therefore stay in place and fail the next daemon's exclusive publish. Negative and fractional values pass the same check.
🛠️ Proposed fix
const pid = Number(trimmed)
- return Number.isFinite(pid)
+ return Number.isInteger(pid) && pid > 0
? {
pid,📝 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 pid = Number(trimmed) | |
| return Number.isFinite(pid) | |
| ? { | |
| pid, | |
| startedAtMs: null, | |
| entryPath: null, | |
| appVersion: null, | |
| launchNonce: null, | |
| linuxStartTicks: null, | |
| bootId: null, | |
| spawnerExecPath: null | |
| } | |
| : null | |
| const pid = Number(trimmed) | |
| return Number.isInteger(pid) && pid > 0 | |
| ? { | |
| pid, | |
| startedAtMs: null, | |
| entryPath: null, | |
| appVersion: null, | |
| launchNonce: null, | |
| linuxStartTicks: null, | |
| bootId: null, | |
| spawnerExecPath: null | |
| } | |
| : null |
| export function getShellReadyWrapperRoot(): string { | ||
| const userDataPath = process.env[ORCA_USER_DATA_PATH_ENV] | ||
| // Why: older/test launchers may not seed ORCA_USER_DATA_PATH. Keep a | ||
| // fallback so daemon startup does not fail before the parent can be fixed. | ||
| return join(userDataPath || tmpdir(), userDataPath ? 'shell-ready' : 'orca-shell-ready') | ||
| } |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
Consider hardening the tmpdir() fallback root.
When ORCA_USER_DATA_PATH is absent, the wrapper root becomes a fixed, predictable path inside a world-writable directory on POSIX systems. Every file under that root is later written by ensureShellReadyWrappers and then sourced by the launched login shell. Another local user can pre-create orca-shell-ready/bash/rcfile or replace a path component with a symlink. shellReadyWrappersExist then reports success, and the shell sources content this process did not write.
Two options reduce the exposure:
- Include the current UID in the fallback directory name, and create the root with mode
0o700. - Verify ownership and mode of the resolved root before you treat existing wrappers as valid.
🔒 Proposed fallback hardening
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { existsSync } from 'node:fs'
const ORCA_USER_DATA_PATH_ENV = 'ORCA_USER_DATA_PATH'
export const SHELL_READY_MARKER = '\\033]777;orca-shell-ready\\007'
export function getShellReadyWrapperRoot(): string {
const userDataPath = process.env[ORCA_USER_DATA_PATH_ENV]
- // Why: older/test launchers may not seed ORCA_USER_DATA_PATH. Keep a
- // fallback so daemon startup does not fail before the parent can be fixed.
- return join(userDataPath || tmpdir(), userDataPath ? 'shell-ready' : 'orca-shell-ready')
+ if (userDataPath) {
+ return join(userDataPath, 'shell-ready')
+ }
+ // Why: older/test launchers may not seed ORCA_USER_DATA_PATH. Keep a fallback so
+ // daemon startup does not fail; scope it per-uid so a shared tmpdir is not hijackable.
+ const uid = typeof process.getuid === 'function' ? process.getuid() : 'shared'
+ return join(tmpdir(), `orca-shell-ready-${uid}`)
}The writer must also create this root with mode 0o700.
| export function ensureShellReadyWrappers(): void { | ||
| if (process.platform === 'win32') { | ||
| return | ||
| } | ||
| if (didEnsureShellReadyWrappers && shellReadyWrappersExist()) { | ||
| return | ||
| } | ||
| didEnsureShellReadyWrappers = true |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Compare daemon and provider shell-ready wrapper root resolution and writers.
set -euo pipefail
fd -t f 'shell-ready-wrapper-paths.ts' src/main --exec cat -n {}
fd -t f 'shell-ready-wrapper-writer.ts' src/main --exec cat -n {}
# Locate every definition and caller of the root resolver and the ensure function.
rg -n -C 3 'function getShellReadyWrapperRoot|function ensureShellReadyWrappers' src/main
rg -n 'getShellReadyWrapperRoot\(|ensureShellReadyWrappers\(' src/main --glob '!*.test.ts'Repository: stablyai/orca
Length of output: 11253
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- daemon contract ---'
cat -n src/main/daemon/shell-ready-wrapper-contract.ts
printf '%s\n' '--- daemon writer ---'
cat -n src/main/daemon/shell-ready-wrapper-files.ts | sed -n '1,40p'
printf '%s\n' '--- provider path resolver ---'
cat -n src/main/providers/shell-ready-wrapper-paths.ts
printf '%s\n' '--- provider writer ---'
cat -n src/main/providers/shell-ready-wrapper-writer.ts | sed -n '1,100p'
printf '%s\n' '--- local provider imports and calls ---'
cat -n src/main/providers/local-pty-shell-ready.ts | sed -n '1,90p'
printf '%s\n' '--- resolver imports ---'
rg -n -C 3 'shell-ready-wrapper-(contract|paths|writer)|ensureShellReadyWrappers' src/main/daemon src/main/providers --glob '*.{ts,tsx}'
printf '%s\n' '--- deterministic resolver comparison ---'
python3 - <<'PY'
from pathlib import Path
import re
def body(path):
return Path(path).read_text()
daemon = body("src/main/daemon/shell-ready-wrapper-contract.ts")
provider = body("src/main/providers/shell-ready-wrapper-paths.ts")
for label, text in [("daemon", daemon), ("provider", provider)]:
print(label, "uses ORCA_USER_DATA_PATH:", "ORCA_USER_DATA_PATH" in text)
print(label, "fallback:", "tmpdir()" if "tmpdir()" in text else "none shown")
print(label, "root expression:", next((line.strip() for line in text.splitlines() if "return " in line and ("shell-ready" in line or "userDataPath" in line)), "not found"))
print("same resolver module:", daemon == provider)
print("same conceptual root suffix:", "/shell-ready" in daemon and "/shell-ready" in provider)
PYRepository: stablyai/orca
Length of output: 22003
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- ORCA_USER_DATA_PATH assignments ---'
rg -n -C 4 'ORCA_USER_DATA_PATH' src config --glob '*.{ts,tsx,js,jsx,mjs,json}' || true
printf '%s\n' '--- daemon and local-provider entry points ---'
rg -n -C 5 'ensureShellReadyWrappers\(|getWrappedShellLaunchConfig|build.*Shell|shell-ready' \
src/main/daemon src/main/providers --glob '*.{ts,tsx}'
printf '%s\n' '--- related tests and fixtures ---'
rg -n -C 4 'shell-ready-wrapper|ORCA_USER_DATA_PATH|ensureShellReadyWrappersAt|shellReadyWrappersExist' \
src --glob '*.{test,spec}.{ts,tsx}' || true
printf '%s\n' '--- exact root-equivalence probe ---'
node - <<'JS'
const path = require('node:path');
const os = require('node:os');
function daemonRoot(env) {
const userDataPath = env.ORCA_USER_DATA_PATH;
return path.join(userDataPath || os.tmpdir(), userDataPath ? 'shell-ready' : 'orca-shell-ready');
}
function providerRoot(env) {
const userDataPath = env.ORCA_USER_DATA_PATH ?? os.tmpdir();
return `${userDataPath}/shell-ready`;
}
for (const env of [
{ label: 'configured', ORCA_USER_DATA_PATH: '/data/orca' },
{ label: 'unset' },
{ label: 'empty', ORCA_USER_DATA_PATH: '' },
{ label: 'trailing slash', ORCA_USER_DATA_PATH: '/data/orca/' },
]) {
console.log(env.label, { daemon: daemonRoot(env), provider: providerRoot(env), same: daemonRoot(env) === providerRoot(env) });
}
JSRepository: stablyai/orca
Length of output: 50370
Use one shared shell-ready wrapper writer. When ORCA_USER_DATA_PATH is set, both resolvers return the same shell-ready directory. Both writers use writeFileSync on the same rcfiles, so one startup can truncate a file while a shell sources it and misses the ready marker. Route both callers through one writer or use an atomic replacement sequence.
| function normalizeOriginalZdotdirCandidate(value: string | undefined): string | null { | ||
| if (!value) { | ||
| return null | ||
| } | ||
| // Why: strip trailing slashes so wrapper paths match; `/` falls back to HOME. | ||
| const normalized = value.replace(/\/+$/, '') | ||
| if (!normalized || normalized.endsWith('/shell-ready/zsh')) { | ||
| return null | ||
| } | ||
| return value | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
normalizeOriginalZdotdirCandidate returns the un-normalized value.
Line 34 computes normalized with trailing slashes stripped, but line 38 returns value. The comment states the goal is to strip trailing slashes so wrapper paths match. Callers therefore still receive /some/dir/, and any later equality check against HOME or a wrapper path fails for that input.
Proposed fix
- return value
+ return normalized📝 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.
| function normalizeOriginalZdotdirCandidate(value: string | undefined): string | null { | |
| if (!value) { | |
| return null | |
| } | |
| // Why: strip trailing slashes so wrapper paths match; `/` falls back to HOME. | |
| const normalized = value.replace(/\/+$/, '') | |
| if (!normalized || normalized.endsWith('/shell-ready/zsh')) { | |
| return null | |
| } | |
| return value | |
| } | |
| function normalizeOriginalZdotdirCandidate(value: string | undefined): string | null { | |
| if (!value) { | |
| return null | |
| } | |
| // Why: strip trailing slashes so wrapper paths match; `/` falls back to HOME. | |
| const normalized = value.replace(/\/+$/, '') | |
| if (!normalized || normalized.endsWith('/shell-ready/zsh')) { | |
| return null | |
| } | |
| return normalized | |
| } |
| try { | ||
| for (const [path, content] of files) { | ||
| const dir = path.slice(0, path.lastIndexOf('/')) | ||
| mkdirSync(dir, { recursive: true }) | ||
| writeFileSync(path, content, 'utf8') | ||
| chmodSync(path, 0o644) | ||
| } | ||
| } catch (error) { | ||
| // Why: degrade gracefully — a failed wrapper (read-only FS, perms, disk) just means no ready marker, PTY stays usable. | ||
| const errorMessage = | ||
| error instanceof Error | ||
| ? `${error.message} (${(error as NodeJS.ErrnoException).code || 'unknown'})` | ||
| : String(error) | ||
| console.error(`[shell-ready] Failed to create wrapper files in ${root}: ${errorMessage}`) | ||
| console.error('[shell-ready] Shell will launch without wrapper (no shell-ready marker)') | ||
| // Reset the flag so next attempt will try again | ||
| didEnsureShellReadyWrappers = false | ||
| } |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Find every place ORCA_USER_DATA_PATH is set and every caller of the wrapper writer.
rg -nP -C3 'ORCA_USER_DATA_PATH'
rg -nP -C3 '\bensureShellReadyWrappers(At)?\s*\('Repository: stablyai/orca
Length of output: 151
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- candidate files ---'
git ls-files | rg 'shell-ready|provider|daemon' | head -200
printf '%s\n' '--- symbol search ---'
rg -n -i -C3 'shell.?ready|USER_DATA_PATH|ensure.*Wrapper|Wrapper.*ensure' . --glob '!node_modules' --glob '!dist' --glob '!build' | head -300Repository: stablyai/orca
Length of output: 38085
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- exact filenames ---'
find . -type f \( -name 'shell-ready-wrapper-writer.ts' -o -name 'shell-ready-wrapper-paths.ts' \) -print
printf '%s\n' '--- exact symbol matches ---'
rg -n -F 'ensureShellReadyWrappers' . --glob '!node_modules' --glob '!dist' --glob '!build' || true
rg -n -F 'getShellReadyWrapperRoot' . --glob '!node_modules' --glob '!dist' --glob '!build' || true
printf '%s\n' '--- shell-ready source files ---'
git ls-files | rg -i 'shell.*ready|ready.*shell' | tail -100Repository: stablyai/orca
Length of output: 4234
🏁 Script executed:
#!/bin/bash
set -e
for f in \
src/main/providers/shell-ready-wrapper-paths.ts \
src/main/providers/shell-ready-wrapper-writer.ts \
src/main/daemon/shell-ready-wrapper-contract.ts \
src/main/daemon/shell-ready-wrapper-files.ts \
src/main/daemon/shell-ready.ts \
src/main/providers/local-pty-shell-ready.ts \
src/main/providers/windows-shell-args.ts
do
printf '\n--- %s ---\n' "$f"
cat -n "$f"
done
printf '\n--- environment propagation references ---\n'
rg -n -C4 'ORCA_USER_DATA_PATH|spawn\(|fork\(|execFile\(|env:' src/main/daemon src/main/providers src/main --glob '*.ts' | head -500Repository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- daemon fork context ---'
sed -n '620,715p' src/main/daemon/daemon-init.ts
printf '%s\n' '--- provider call graph ---'
rg -n -C5 'getShellReadyLaunchConfig|getMarkerlessShellLaunchConfig|ensureShellReadyWrappersAt|ensureShellReadyWrappers\(' \
src/main --glob '*.ts' --glob '!**/*.test.ts'
printf '%s\n' '--- ORCA_USER_DATA_PATH assignments in runtime sources ---'
rg -n -C3 'ORCA_USER_DATA_PATH\s*[:=]|process\.env\.ORCA_USER_DATA_PATH|ORCA_USER_DATA_PATH_ENV' \
src/main config --glob '*.{ts,tsx,js,mjs,cjs}' | head -300
printf '%s\n' '--- relevant daemon entry imports ---'
sed -n '1,180p' src/main/daemon/daemon-entry.ts
sed -n '1,120p' src/main/daemon/daemon-main.tsRepository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -e
node - <<'JS'
'use strict'
const fs = require('node:fs')
const os = require('node:os')
const path = require('node:path')
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orca-shell-ready-probe-'))
const wrapperDir = path.join(root, 'shell-ready', 'zsh')
const target = path.join(root, 'attacker-controlled-rcfile')
const wrapper = path.join(wrapperDir, '.zshenv')
fs.mkdirSync(wrapperDir, { recursive: true })
fs.writeFileSync(target, 'attacker content\n', 'utf8')
fs.symlinkSync(target, wrapper)
fs.writeFileSync(wrapper, 'generated wrapper\n', 'utf8')
fs.chmodSync(wrapper, 0o644)
const targetContent = fs.readFileSync(target, 'utf8')
const wrapperIsSymlink = fs.lstatSync(wrapper).isSymbolicLink()
console.log(JSON.stringify({ targetContent, wrapperIsSymlink }, null, 2))
fs.rmSync(root, { recursive: true, force: true })
JS
printf '%s\n' '--- main bootstrap candidates ---'
git ls-files | rg 'src/main/.*(index|main|entry|bootstrap|app).*\.(ts|tsx)$' | head -100
printf '%s\n' '--- environment initialization in main sources ---'
rg -n -C3 'ORCA_USER_DATA_PATH|app\.setPath|app\.getPath\(' src/main --glob '*.ts' --glob '!**/*.test.ts' | head -300Repository: stablyai/orca
Length of output: 26666
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- src/main/index.ts ---'
cat -n src/main/index.ts | head -240
printf '%s\n' '--- direct environment writes across tracked source ---'
rg -n -C2 'process\.env(?:\[|\.)(?:ORCA_USER_DATA_PATH)|ORCA_USER_DATA_PATH\s*:' . \
--glob '!node_modules' --glob '!dist' --glob '!build' \
--glob '*.{ts,tsx,js,jsx,mjs,cjs,sh,cmd,ps1}' | head -300Repository: stablyai/orca
Length of output: 35609
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- configure process helper ---'
rg -n -C8 'configureOrcaUserDataPathEnv' src/main/startup/configure-process.ts src/main/index.ts
printf '%s\n' '--- startup invocation context ---'
rg -n -C12 'configureOrcaUserDataPathEnv\(' src/main/index.tsRepository: stablyai/orca
Length of output: 4643
Remove the predictable /tmp fallback and harden wrapper writes.
ORCA_USER_DATA_PATH is set in the main process and normal daemon fork, but both implementations still support unset environments and fall back to predictable /tmp paths. writeFileSync follows pre-planted symlinks before chmodSync runs. Use a per-user or unique fallback, enforce owner-only directories, and reject symlinks before writing in both provider and daemon writers.
What
Splits the four oversized daemon modules, the local-PTY shell-ready provider, three runtime RPC method files, and the orchestration coordinator into focused modules; removes their
eslint-disable max-linessuppressions; prunes the nine corresponding ratchet-baseline entries (341 → 332).No behavior change.
Why
Each file carried a file-level
max-linessuppression and ran 373–785 counted lines against a 300-line budget. PerAGENTS.md→ "Do Not Disable Max Lines", the fix is to split, not suppress;config/max-lines-baseline.txtis a shrink-only ratchet.How it was split
daemon/daemon-health.tsdaemon/session.tssession-subprocess-handle,session-options,session-pending-output-buffer,session-output-plane,session-shell-ready-barrier,session-termination-controller,session-producer-pause,session-exit-finalizer,windows-conpty-prompt-repaintruntime/rpc/methods/github.tsdaemon/client.tsdaemon-endpoint-identity,daemon-client-socket-connect,daemon-client-hello-handshake,daemon-client-pending-requests,daemon-client-ndjson-readersruntime/rpc/methods/files.tsruntime/orchestration/coordinator.tsproviders/local-pty-shell-ready.tsshell-ready-wrapper-paths,shell-ready-wrapper-rcfiles,shell-ready-wrapper-writerruntime/rpc/methods/git.tsdaemon/shell-ready.tsshell-ready-wrapper-contract,shell-ready-bash-rcfile,shell-ready-zsh-rcfile,shell-ready-wrapper-filesshell-readyis deliberately layered soSHELL_READY_MARKERlives in a dependency-free contract module at the root of the graph — contract ← {bash-rcfile, zsh-rcfile} ← wrapper-files ← shell-ready — keeping it a DAG.No barrel exports; every new module owns real logic and importers point at the owner.
Verification
npx oxlint(whole repo) — cleanpnpm check:max-lines-ratchet— passes; baseline 341 → 332pnpm typecheck(node + cli + web) — clean, 0 errorspnpm test— full suite green; the one remaining failure is a pre-existing load-induced timeout in a file this branch does not touch, verified passing when re-run seriallyeslint/oxlint-disabledirective added anywhere, confirmed by diff grepThe invariant that matters most here: per-session and per-connection state stayed per-instance. Nothing that was instance or closure state became module-level, so two sessions cannot share an output buffer, a shell-ready barrier, a producer-pause flag, or a pending-request map. Every split was independently reviewed by an adversarial reviewer instructed to refute the "pure move" claim, with that specific failure mode called out as the priority check.
This is the largest blast radius in the series —
session.tsalone has ~33 importers, and every one of those edits is import-path-only, with no test assertion changed.One test in
client.test.tsneeded a structural adaptation rather than a path change: it previously reached a private method via(client as unknown as {…}).sendHello.bind(client), and now calls the exportedsendDaemonHello({…})directly. All six assertions are byte-identical.Pre-existing issues found and deliberately NOT changed
daemon/shell-ready.ts:ensureShellReadyWrapperssetsdidEnsureShellReadyWrappers = truebefore writing, so a partial write is only retried because the catch resets the flag; a success that later loses one file re-runs all five writes.daemon/client.ts:notify()swallowsNdjsonLineTooLongErroridentically to a real write failure. This is intentional per its own test, and was moved verbatim.