Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix: improve Linux compatibility by hardening file permissions, implementing process row repair for locale-mangled bytes, and adding sqlite3 availability checks.

0xken15f63acaff11c3
diff --git a/README.md b/README.md
index 4d875be60..4bc6f258a 100644
--- a/README.md
+++ b/README.md
@@ -65,6 +65,9 @@ curl -fsSL https://harness.autonomous.ai/install.sh | bash -s -- <token>
harness join
```
+Runs on **macOS and Linux** (Ubuntu 22.04+ verified). Node ≥ 20 and tmux and/or Herdr are the
+prerequisites — see [`cli/README.md`](cli/README.md#supported-platforms).
+
In the code these are named `engine` (CLI) and `provider` (API) — the folder names you'll see:
```bash
diff --git a/cli/README.md b/cli/README.md
index 6a870d6b9..b64a4958b 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -14,6 +14,20 @@ folder per agent, and yours can join them.
- The browser channel is end-to-end encrypted (see `src/lib/e2ee/`).
- One self-contained bundle with no Node native dependencies. Node ≥ 20 plus tmux and/or Herdr 0.8.x is required.
+## Supported platforms
+
+**macOS** and **Linux** (Ubuntu 22.04+ verified, bare metal and containers alike). The published
+artifact is one pure-JS bundle run by your own Node, so there is no per-OS build to pick and no
+native module to compile — the same `cli.js` runs everywhere.
+
+| Requirement | Notes |
+|---|---|
+| **Node ≥ 20** | On Ubuntu the distro `nodejs` package is too old (24.04 ships 18.19, 22.04 ships 12.22). Install from [NodeSource](https://github.com/nodesource/distributions) or `nvm install 20`. |
+| **tmux and/or Herdr 0.8.x** | How agents are discovered. Neither is preinstalled on Ubuntu Server: `sudo apt install tmux`. |
+| **`sqlite3` CLI** | Only for the store-backed engines (`opencode`, `kilo`, `hermes`, `devin`), which keep conversations in SQLite instead of a transcript file. Present by default on macOS, **not** on Ubuntu: `sudo apt install sqlite3`. Every other engine works without it, and the daemon says so at startup if it is missing. |
+
+Windows is not supported.
+
## Install & run (`harness`)
Prerequisite: **Node ≥ 20**. Create or open a remote machine in the web UI first, then copy its connect
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjs
index 01d37e96b..ffe5467a4 100644
--- a/cli/hook/notify.mjs
+++ b/cli/hook/notify.mjs
@@ -361,16 +361,40 @@ function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
-function execFileText(cmd, args, timeout) {
+function execFileText(cmd, args, timeout, env) {
return new Promise((resolve) => {
const budget = Math.min(timeout, remainingBudget())
if (budget < 50) { resolve(null); return }
- execFile(cmd, args, { timeout: budget }, (err, stdout) => {
+ execFile(cmd, args, { timeout: budget, ...(env && { env }) }, (err, stdout) => {
resolve(err ? null : stdout)
})
})
}
+/**
+ * Mirrors PS_ENV in src/lib/tmux.ts. Linux procps substitutes `?` for every byte it cannot print in the
+ * current locale, and a hook child launched by an engine under systemd/docker/ssh usually has no locale
+ * at all. Measured on Ubuntu 24.04 + procps-ng 4.0.4: `⌘ <title>` reads back as `??? <title>` in BOTH
+ * comm and args, which kills both halves of the Command Code marker in processMatchScore. macOS never
+ * substitutes, so this is Linux-only and cannot regress it.
+ */
+const PS_ENV = process.platform === 'linux' ? { ...process.env, LC_ALL: 'C.UTF-8' } : undefined
+
+/** Second line of defence: /proc is raw bytes, so a glibc without C.UTF-8 still resolves correctly. */
+function repairMangledRows(rows) {
+ if (process.platform !== 'linux') return rows
+ return rows.map((row) => {
+ if (!row.executable.includes('?') && !row.args.includes('?')) return row
+ const args = readProcField(row.pid, 'cmdline')?.replace(/\0/g, ' ').trimEnd()
+ const executable = readProcField(row.pid, 'comm')?.trimEnd()
+ return { ...row, ...(executable && { executable }), ...(args && { args }) }
+ })
+}
+
+function readProcField(pid, field) {
+ try { return readFileSync(`/proc/${pid}/${field}`, 'utf8') } catch { return null }
+}
+
async function panePid(pane) {
const stdout = await execFileText('tmux', ['display-message', '-p', '-t', pane, '#{pane_pid}'], 2000)
if (stdout === null) return undefined
@@ -467,6 +491,12 @@ function hookFileOwner(fileKey, ownership) {
return 'unknown'
}
+/** Mirrors commTruncatedPrefixOf in src/lib/tmux.ts: Linux caps `comm` at 15 bytes (TASK_COMM_LEN). */
+function commTruncatedPrefixOf(seen, want) {
+ if (process.platform !== 'linux' || !seen || !want) return false
+ return Buffer.byteLength(seen) === 15 && want.length > seen.length && want.startsWith(seen)
+}
+
function processMatchScore(row, engine, ownership, allowAgentHint = false) {
const executable = basename(row.executable).toLowerCase()
const entrypoint = processEntrypoint(row.args).toLowerCase()
@@ -475,7 +505,8 @@ function processMatchScore(row, engine, ownership, allowAgentHint = false) {
const configured = String(explicit || ENGINE_COMMANDS[engine] || '').toLowerCase()
const configuredBase = basename(configured).toLowerCase()
if (configuredBase && configuredBase !== 'agent' && (row.executable.toLowerCase() === configured
- || entrypoint === configured || executable === configuredBase || entrybase === configuredBase)) return 4
+ || entrypoint === configured || executable === configuredBase || entrybase === configuredBase
+ || commTruncatedPrefixOf(executable, configuredBase))) return 4
if (engine === 'codex') return /@openai[\/\\]codex[\/\\]bin[\/\\]codex(?:\.js)?$/.test(entrypoint) ? 2 : 0
if (engine === 'cursor') {
if (executable === 'cursor-agent' || entrybase === 'cursor-agent') return 3
@@ -517,7 +548,7 @@ function processMatchScore(row, engine, ownership, allowAgentHint = false) {
}
async function processRows() {
- const stdout = await execFileText('ps', ['-axo', 'pid=,ppid=,comm=,lstart=,args='], 3000)
+ const stdout = await execFileText('ps', ['-axo', 'pid=,ppid=,comm=,lstart=,args='], 3000, PS_ENV)
if (stdout === null) return null
const rows = []
for (const line of stdout.split('\n')) {
@@ -531,7 +562,7 @@ async function processRows() {
args: match[5],
})
}
- return rows
+ return repairMangledRows(rows)
}
function aliasRows(rows) {
diff --git a/cli/scripts/upload-cli.sh b/cli/scripts/upload-cli.sh
index d5c6f86b5..c5f2f4e3a 100755
--- a/cli/scripts/upload-cli.sh
+++ b/cli/scripts/upload-cli.sh
@@ -96,8 +96,15 @@ CLI_GCS="harness/cli/${VER}/cli.js"
NOTIFY_GCS="harness/cli/${VER}/notify.mjs"
CLI_URL="${GCS_PUBLIC_BASE_URL%/}/${CLI_GCS}"
NOTIFY_URL="${GCS_PUBLIC_BASE_URL%/}/${NOTIFY_GCS}"
-CLI_SHA="$(shasum -a 256 "$CLI" | awk '{print $1}')"; CLI_SIZE="$(wc -c < "$CLI" | tr -d ' ')"
-NOTIFY_SHA="$(shasum -a 256 "$NOTIFY" | awk '{print $1}')"; NOTIFY_SIZE="$(wc -c < "$NOTIFY" | tr -d ' ')"
+# `shasum` is a Perl script and is absent from minimal Linux images (only perl-base is installed);
+# `sha256sum` is coreutils and is always there. Prefer it so a release can also be cut from Ubuntu.
+sha256_of() {
+ if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | awk '{print $1}'
+ else shasum -a 256 "$1" | awk '{print $1}'
+ fi
+}
+CLI_SHA="$(sha256_of "$CLI")"; CLI_SIZE="$(wc -c < "$CLI" | tr -d ' ')"
+NOTIFY_SHA="$(sha256_of "$NOTIFY")"; NOTIFY_SIZE="$(wc -c < "$NOTIFY" | tr -d ' ')"
echo ">> uploading cli.js ($CLI_SIZE bytes) + notify.mjs ($NOTIFY_SIZE bytes)"
gsutil -h "Cache-Control:no-cache, no-store, must-revalidate" cp "$CLI" "gs://${GCS_BUCKET}/${CLI_GCS}"
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 43a64d742..abfadf09a 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -23,6 +23,7 @@ import { createHash, randomUUID } from 'crypto'
import { homedir } from 'os'
import { env } from './config/env.js'
import { VERSION } from './version.js'
+import { sqlitePreflightMessage } from './lib/sqliteAvailability.js'
import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'
import { installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCursorHooks, installDevinHooks, installGrokHooks, installAgyHooks, installCopilotHooks, installHermesHooks, installKiloPlugin, installOpencodePlugin, installPiExtension, installSessionHooks } from './lib/hooks.js'
import { PID_FILE, TOKEN_FILE, daemonPort, isAlive, readPid } from './lib/daemonState.js'
@@ -218,7 +219,7 @@ function readSavedToken(): string | null {
}
function saveToken(token: string): void {
- mkdirSync(env.ADAPTER_DATA_DIR, { recursive: true })
+ mkdirSync(env.ADAPTER_DATA_DIR, { recursive: true, mode: 0o700 })
writeFileSync(TOKEN_FILE, token + '\n', { mode: 0o600 })
}
@@ -231,7 +232,7 @@ function computerId(): string {
if (saved) return saved
} catch { /* create below */ }
const id = randomUUID()
- mkdirSync(env.ADAPTER_DATA_DIR, { recursive: true })
+ mkdirSync(env.ADAPTER_DATA_DIR, { recursive: true, mode: 0o700 })
writeFileSync(COMPUTER_ID_FILE, id + '\n', { mode: 0o600 })
return id
}
@@ -603,6 +604,8 @@ async function runForeground(token: string): Promise<void> {
? '[terminal] tmux: available'
: `[terminal] tmux: ${tmuxStartup.state} (${tmuxStartup.reason})`)
}
+ const sqliteWarning = sqlitePreflightMessage()
+ if (sqliteWarning) console.warn(sqliteWarning)
for (const target of herdrStartup) {
console.log(target.state === 'available'
? `[terminal] Herdr session ${target.sessionName}: available`
@@ -2714,7 +2717,7 @@ async function launch(token: string, foreground: boolean): Promise<'deauth' | vo
process.exit(0)
}
- mkdirSync(env.ADAPTER_DATA_DIR, { recursive: true })
+ mkdirSync(env.ADAPTER_DATA_DIR, { recursive: true, mode: 0o700 })
prepareLogFile(LOG_FILE, LEGACY_LOG_FILE) // adopt an older name + enforce the cap before we tail from here
const logOffset = existsSync(LOG_FILE) ? readFileSync(LOG_FILE).length : 0
const logFd = openSync(LOG_FILE, 'a')
diff --git a/cli/src/config/env.ts b/cli/src/config/env.ts
index 7a0535167..85dc945a6 100644
--- a/cli/src/config/env.ts
+++ b/cli/src/config/env.ts
@@ -68,7 +68,7 @@ function migrateLegacyAdapterState(): void {
const strayDataDir = join(homedir(), '.machine', 'cli', 'data')
if (existsSync(strayDataDir)) {
- mkdirSync(adapterDataDir, { recursive: true })
+ mkdirSync(adapterDataDir, { recursive: true, mode: 0o700 })
for (const entry of readdirSync(strayDataDir)) {
if (forceMove(join(adapterDataDir, entry), join(strayDataDir, entry))) moved++
}
@@ -153,13 +153,19 @@ const envSchema = z.object({
COMMANDCODE_HOME: z.string().default(join(homedir(), '.commandcode')),
// Devin CLI state root — history is the SQLite store <DEVIN_HOME>/sessions.db (WAL, no transcript file
// unless the user passes --export) and <DEVIN_HOME>/session_locks/<id>.lock holds the owning PID.
- DEVIN_HOME: z.string().default(join(homedir(), '.local', 'share', 'devin', 'cli')),
+ DEVIN_HOME: z
+ .string()
+ .default(join(process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share'), 'devin', 'cli')),
// Muse Code state root. Transcripts are JSONL but the layout is DATE-SHARDED, not hashed by project
// path: <MUSE_HOME>/sessions/YYYY/MM/DD/<session-uuid>/session.jsonl, with sub-agents one level deeper
// under `subagent/<child-uuid>/`. The only link back to a project is `workspace_root`, carried in the
// FIRST record of each file — which is why this engine is discovered by scanning rather than by a hook.
- MUSE_HOME: z.string().default(join(homedir(), '.local', 'share', 'muse')),
- MUSE_CONFIG_DIR: z.string().default(join(homedir(), '.config', 'muse')),
+ MUSE_HOME: z
+ .string()
+ .default(join(process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share'), 'muse')),
+ MUSE_CONFIG_DIR: z
+ .string()
+ .default(join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'muse')),
// Amp plugin dir the adapter drops its discovery plugin into (honors XDG_CONFIG_HOME). Amp calls these
// "system plugins" and loads every `*.ts` there for EVERY thread, which is what makes one install cover
// all projects — the project-local `.amp/plugins/` alternative would need one copy per repo.
@@ -181,7 +187,9 @@ const envSchema = z.object({
.default(join(process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share'), 'amp')),
// Devin's user-level config, where the adapter merges its hooks under a "hooks" key. Devin reads
// Claude's hook schema verbatim, so the installed block is shaped exactly like ~/.claude/settings.json.
- DEVIN_CONFIG_PATH: z.string().default(join(homedir(), '.config', 'devin', 'config.json')),
+ DEVIN_CONFIG_PATH: z
+ .string()
+ .default(join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'devin', 'config.json')),
// Where the tmux-session registry + connect token are persisted.
ADAPTER_DATA_DIR: z.string().default(adapterDataDir),
// ---- Harness Analytics (see autonomous-code docs/design/harness-analytics.md) ----
diff --git a/cli/src/engines/devin/reader.spec.ts b/cli/src/engines/devin/reader.spec.ts
index 8313b277a..235b2464d 100644
--- a/cli/src/engines/devin/reader.spec.ts
+++ b/cli/src/engines/devin/reader.spec.ts
@@ -51,7 +51,15 @@ const userRow = (id: string, text: string, at = '2026-07-28T06:38:21.000000Z') =
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
-describe('DevinReader turn close', () => {
+// macOS ships the sqlite3 CLI in the base system; Ubuntu (and most slim images) do not. These cases
+// drive a REAL database on purpose, so skip rather than fail where the binary is genuinely absent —
+// the same guard opencode/reader.spec.ts and hermes/reader.spec.ts already use.
+const hasSqlite = (() => {
+ try { execFileSync('sqlite3', ['-version'], { stdio: 'ignore' }); return true } catch { return false }
+})()
+const d = hasSqlite ? describe : describe.skip
+
+d('DevinReader turn close', () => {
it('deduplicates the repeated rows Devin writes per inference', async () => {
const f = fixture()
const user = userRow('m-user', 'hi')
diff --git a/cli/src/engines/kilo/reader.spec.ts b/cli/src/engines/kilo/reader.spec.ts
index e8e8cc7e2..d4c8144e5 100644
--- a/cli/src/engines/kilo/reader.spec.ts
+++ b/cli/src/engines/kilo/reader.spec.ts
@@ -62,7 +62,15 @@ const finished = {
parts: [{ type: 'text', text: 'done' }, { type: 'step-finish', reason: 'stop' }],
}
-describe('KiloReader attaching mid-turn', () => {
+// macOS ships the sqlite3 CLI in the base system; Ubuntu (and most slim images) do not. These cases
+// drive a REAL database on purpose, so skip rather than fail where the binary is genuinely absent —
+// the same guard opencode/reader.spec.ts and hermes/reader.spec.ts already use.
+const hasSqlite = (() => {
+ try { execFileSync('sqlite3', ['-version'], { stdio: 'ignore' }); return true } catch { return false }
+})()
+const d = hasSqlite ? describe : describe.skip
+
+d('KiloReader attaching mid-turn', () => {
/**
* The shape that broke a first message. The plugin posts the moment the user row lands, which is
* BEFORE kilo has written any assistant row — so the old check ("is the tail an unfinished
diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.ts
index 01cf49500..53a1250d5 100644
--- a/cli/src/hookNotify.spec.ts
+++ b/cli/src/hookNotify.spec.ts
@@ -7,6 +7,8 @@ import { join } from 'path'
import { fileURLToPath } from 'url'
import { afterEach, describe, expect, it, vi } from 'vitest'
+const isRoot = typeof process.getuid === 'function' && process.getuid() === 0
+
// Every case here spawns the real hook as a child process, and several spawn shell shims for tmux, ps
// and sqlite3 on top of that. On a loaded machine — this file runs alongside 88 others — that chain
// takes well over vitest's 5s default, and the failure looks like a product bug rather than what it is.
@@ -512,7 +514,14 @@ describe('hook notify terminal scope', () => {
expect(registry).toMatchObject([{ sessionId: 'codex-session', engine: 'codex', tmuxPane: '%8' }])
})
- it('uses only a configured, validated Herdr endpoint for daemon-down registration', async () => {
+ /**
+ * Skipped when the suite itself runs as root (common in a container). `checkedSocket` rejects a
+ * root-OWNED directory that is group-writable — `(stat.uid === 0 && permissions & 0o020)` — because
+ * under root ownership the group bit really does let another account plant a socket. The rule is
+ * correct; it is this case's premise ("the owner is a normal account") that does not hold as root.
+ * Same precedent as the getuid()===0 guard in lib/fsBrowse.spec.ts.
+ */
+ it.skipIf(isRoot)('uses only a configured, validated Herdr endpoint for daemon-down registration', async () => {
const dir = mkdtempSync(join(homedir(), '.adapter-hook-herdr-'))
tmpDirs.push(dir)
chmodSync(dir, 0o775)
diff --git a/cli/src/lib/commander.ts b/cli/src/lib/commander.ts
index ff11495a2..c3cec1bca 100644
--- a/cli/src/lib/commander.ts
+++ b/cli/src/lib/commander.ts
@@ -656,7 +656,7 @@ export class CommanderMirror {
private save(): void {
try {
- mkdirSync(this.opts.dataDir, { recursive: true })
+ mkdirSync(this.opts.dataDir, { recursive: true, mode: 0o700 })
writeFileSync(this.file, JSON.stringify(Object.fromEntries(this.summaries), null, 2))
} catch (err) {
console.error('[commander] save summaries failed:', err)
diff --git a/cli/src/lib/e2ee/store.ts b/cli/src/lib/e2ee/store.ts
index 7fb2d82b8..8968dd4e0 100644
--- a/cli/src/lib/e2ee/store.ts
+++ b/cli/src/lib/e2ee/store.ts
@@ -21,7 +21,7 @@ export interface PairedClient {
role: PairRole // old records without this field are treated as web
}
function writeSecure(file: string, data: unknown): void {
- mkdirSync(DIR, { recursive: true })
+ mkdirSync(DIR, { recursive: true, mode: 0o700 })
writeFileSync(file, JSON.stringify(data, null, 2), { mode: 0o600 })
}
diff --git a/cli/src/lib/herdrApiClient.spec.ts b/cli/src/lib/herdrApiClient.spec.ts
index 355c5a8f3..887e92a29 100644
--- a/cli/src/lib/herdrApiClient.spec.ts
+++ b/cli/src/lib/herdrApiClient.spec.ts
@@ -3,6 +3,8 @@ import { chmod, lstat, mkdir, mkdtemp, rm, symlink } from 'node:fs/promises'
import { homedir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
+
+const isRoot = typeof process.getuid === 'function' && process.getuid() === 0
import {
HERDR_API_PROTOCOL,
HERDR_API_SCHEMA_VERSION,
@@ -172,7 +174,14 @@ describe('HerdrApiClient', () => {
expect(requests).toBe(0)
})
- it('accepts an owner-owned 0775 socket parent under the local account-owner trust model', async () => {
+ /**
+ * Skipped when the suite itself runs as root (common in a container). `checkedSocket` rejects a
+ * root-OWNED directory that is group-writable — `(stat.uid === 0 && permissions & 0o020)` — because
+ * under root ownership the group bit really does let another account plant a socket. The rule is
+ * correct; it is this case's premise ("the owner is a normal account") that does not hold as root.
+ * Same precedent as the getuid()===0 guard in lib/fsBrowse.spec.ts.
+ */
+ it.skipIf(isRoot)('accepts an owner-owned 0775 socket parent under the local account-owner trust model', async () => {
const root = await tempDir()
const parent = join(root, 'herdr')
await mkdir(parent, { mode: 0o775 })
diff --git a/cli/src/lib/herdrSessions.spec.ts b/cli/src/lib/herdrSessions.spec.ts
index c3e3888c7..6839f54b4 100644
--- a/cli/src/lib/herdrSessions.spec.ts
+++ b/cli/src/lib/herdrSessions.spec.ts
@@ -1,4 +1,7 @@
-import { describe, expect, it, vi } from 'vitest'
+import { afterAll, describe, expect, it, vi } from 'vitest'
+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
import {
discoverRunningHerdrSessions,
herdrBinaryAvailable,
@@ -7,6 +10,9 @@ import {
resolveConfiguredHerdrSessions,
} from './herdrSessions.js'
+const stubDirs: string[] = []
+afterAll(() => { for (const dir of stubDirs) rmSync(dir, { recursive: true, force: true }) })
+
describe('configured Herdr session bootstrap', () => {
it('parses bounded session-list output without treating pane content as CLI data', () => {
expect(parseHerdrSessionList(JSON.stringify({ sessions: [{
@@ -63,11 +69,27 @@ describe('Herdr auto-discovery (no configuration)', () => {
sessionName, socketPath, endpointId: `id:${socketPath}`, generation: { device: 1, inode: 1 },
})
+ /**
+ * `discoverRunningHerdrSessions` short-circuits to [] unless the binary really exists, so passing the
+ * bare name `'herdr'` made these cases depend on whether the DEVELOPER happened to have Herdr
+ * installed. On this machine (`~/.local/bin/herdr`) they passed; on any clean one they returned [] —
+ * which the adoption case fails on and the two negative cases pass VACUOUSLY, proving nothing. Caught
+ * on Ubuntu; a fresh macOS behaves identically. Point them at an executable we create instead.
+ */
+ const herdrBin = (() => {
+ const dir = mkdtempSync(join(tmpdir(), 'herdr-bin-'))
+ stubDirs.push(dir)
+ const bin = join(dir, 'herdr')
+ writeFileSync(bin, '#!/bin/sh\nexit 0\n')
+ chmodSync(bin, 0o755)
+ return bin
+ })()
+
it('adopts every RUNNING session, whatever it is called', async () => {
// The point of auto-detection: the user starts a session with a name we were never told about, and
// its panes are watched on the next pass. A stopped session is not a target.
const result = await discoverRunningHerdrSessions(
- 'herdr',
+ herdrBin,
async () => [
{ name: 'scratch', running: true, session_dir: '/a', socket_path: '/a/herdr.sock' },
{ name: 'default', running: true, session_dir: '/b', socket_path: '/b/herdr.sock' },
@@ -91,15 +113,15 @@ describe('Herdr auto-discovery (no configuration)', () => {
it('stays quiet when an installed Herdr cannot answer', async () => {
// Installed but broken, or a build whose `session list --json` shape moved. Nobody asked for Herdr,
// so there is nothing to report and nothing to adopt — never a startup failure.
- await expect(discoverRunningHerdrSessions('herdr', async () => { throw new Error('exit 1') }, endpoint))
+ await expect(discoverRunningHerdrSessions(herdrBin, async () => { throw new Error('exit 1') }, endpoint))
.resolves.toEqual([])
- await expect(discoverRunningHerdrSessions('herdr', async () => [], endpoint)).resolves.toEqual([])
+ await expect(discoverRunningHerdrSessions(herdrBin, async () => [], endpoint)).resolves.toEqual([])
})
it('still refuses two discovered sessions that alias one endpoint', async () => {
// Discovery must not become a way around the alias rule the configured path enforces.
const result = await discoverRunningHerdrSessions(
- 'herdr',
+ herdrBin,
async () => [
{ name: 'one', running: true, session_dir: '/same', socket_path: '/same/herdr.sock' },
{ name: 'two', running: true, session_dir: '/same', socket_path: '/same/herdr.sock' },
diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.ts
index 625fbb5c6..ada444284 100644
--- a/cli/src/lib/hooks.ts
+++ b/cli/src/lib/hooks.ts
@@ -817,7 +817,7 @@ export default function (amp: any) {
const line = (record: any) => {
try {
- mkdirSync(SESSIONS_DIR, { recursive: true })
+ mkdirSync(SESSIONS_DIR, { recursive: true, mode: 0o700 })
appendFileSync(file, JSON.stringify(record) + '\\n')
} catch {}
}
@@ -1007,7 +1007,7 @@ export function installAmpPlugin(port: number): void {
} catch { /* unreadable — rewrite it */ }
try {
mkdirSync(dirname(AMP_PLUGIN_PATH), { recursive: true })
- mkdirSync(env.AMP_SESSIONS_DIR, { recursive: true })
+ mkdirSync(env.AMP_SESSIONS_DIR, { recursive: true, mode: 0o700 })
const tmp = `${AMP_PLUGIN_PATH}.${process.pid}.tmp`
writeFileSync(tmp, source)
renameSync(tmp, AMP_PLUGIN_PATH)
diff --git a/cli/src/lib/oneshot.ts b/cli/src/lib/oneshot.ts
index 885cea625..ae065edbf 100644
--- a/cli/src/lib/oneshot.ts
+++ b/cli/src/lib/oneshot.ts
@@ -498,7 +498,7 @@ class OpencodeWorker extends ProcessWorker {
// `opencode run` reads the prompt from stdin (pipe → EOF), so the worker can be pre-warmed and fed
// the prompt later. `--pure` skips external plugins (so the machine discovery plugin never
// self-registers this ephemeral recap session). `--format json` streams `{type:'text',part:{text}}`.
- mkdirSync(OPENCODE_RECAP_DATA_DIR, { recursive: true })
+ mkdirSync(OPENCODE_RECAP_DATA_DIR, { recursive: true, mode: 0o700 })
const args = ['run', '--pure', '--format', 'json', ...(model ? ['--model', model] : [])]
const processEnv = scrubTerminalContext({ ...process.env })
processEnv.OPENCODE_DATA_DIR = OPENCODE_RECAP_DATA_DIR
@@ -643,7 +643,7 @@ class KiloWorker extends ProcessWorker {
// recap that returns nothing is the failure this flag prevents. Note the asymmetry that makes this
// easy to get wrong: `--auto` is a valid flag of the `run` SUBCOMMAND, while the bare TUI rejects it
// — the interactive TUI remains entirely under the user's own permission configuration.
- mkdirSync(KILO_RECAP_DATA_DIR, { recursive: true })
+ mkdirSync(KILO_RECAP_DATA_DIR, { recursive: true, mode: 0o700 })
// `--dir` pins the workspace explicitly. Do NOT rely on the spawn `cwd` alone: kilo resolves its
// project from `$PWD`, and `spawn({cwd})` does not rewrite that variable — the child inherits the
// DAEMON's `PWD`. Measured in production: the worker logged
diff --git a/cli/src/lib/openrouter.ts b/cli/src/lib/openrouter.ts
index cd12231a2..b457a9d03 100644
--- a/cli/src/lib/openrouter.ts
+++ b/cli/src/lib/openrouter.ts
@@ -12,7 +12,7 @@
* from every message this module can produce.
*/
-import { readFile, stat } from 'node:fs/promises'
+import { readFile } from 'node:fs/promises'
import { env } from '../config/env.js'
import type { GatewayRuntime } from './gatewayRuntime.js'
@@ -35,26 +35,28 @@ interface OriCredentials {
key?: unknown
}
-let fileCache: { path: string; mtimeMs: number; key: string | null } | null = null
-
/** Strip anything that looks like a key from text that may be logged. */
export function redactKeys(text: string): string {
return text.replace(/sk-[A-Za-z0-9_-]{8,}/g, 'sk-…')
}
+/**
+ * Read `ori login`'s credentials, every time.
+ *
+ * This used to cache the parsed key and re-read only when `mtimeMs` changed. That is safe on APFS,
+ * whose mtime has nanosecond resolution — 8 rapid rewrites produce 8 distinct stamps — and unsafe
+ * everywhere else: the same probe on overlayfs yields 4 distinct stamps out of 8, and on tmpfs exactly
+ * 1. So on Linux a key rotation written within the filesystem's timestamp granularity was invisible,
+ * and the daemon went on spending a revoked key until something else touched the file. There is nothing
+ * to trade away by dropping the cache: both callers follow this with an HTTPS request whose timeout is
+ * 60 SECONDS, so re-reading a ~100-byte file costs nothing measurable.
+ */
async function keyFromCredentialsFile(): Promise<string | null> {
- const path = env.ORI_CREDENTIALS_PATH
try {
- const { mtimeMs } = await stat(path)
- // Re-read on change so `ori login` (or a key rotation) is picked up without restarting the daemon.
- if (fileCache && fileCache.path === path && fileCache.mtimeMs === mtimeMs) return fileCache.key
- const parsed = JSON.parse(await readFile(path, 'utf8')) as OriCredentials
- const key = typeof parsed.key === 'string' && parsed.key.trim() ? parsed.key.trim() : null
- fileCache = { path, mtimeMs, key }
- return key
+ const parsed = JSON.parse(await readFile(env.ORI_CREDENTIALS_PATH, 'utf8')) as OriCredentials
+ return typeof parsed.key === 'string' && parsed.key.trim() ? parsed.key.trim() : null
} catch {
// Absent, unreadable or corrupt is a normal state (no ori installed) — not an error worth logging.
- fileCache = null
return null
}
}
diff --git a/cli/src/lib/secureState.spec.ts b/cli/src/lib/secureState.spec.ts
new file mode 100644
index 000000000..d6614bcfb
--- /dev/null
+++ b/cli/src/lib/secureState.spec.ts
@@ -0,0 +1,89 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { readPrivateStateFile, secureStateDirectory } from './secureState.js'
+
+const dirs: string[] = []
+afterEach(() => {
+ vi.restoreAllMocks()
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
+})
+
+function scratch(mode: number): string {
+ const root = mkdtempSync(join(tmpdir(), 'secure-state-'))
+ dirs.push(root)
+ const dir = join(root, 'data')
+ mkdirSync(dir)
+ chmodSync(dir, mode)
+ return dir
+}
+
+const modeOf = (dir: string) => statSync(dir).mode & 0o777
+
+describe('secureStateDirectory', () => {
+ it('creates a private directory regardless of the ambient umask', () => {
+ const root = mkdtempSync(join(tmpdir(), 'secure-state-'))
+ dirs.push(root)
+ const dir = join(root, 'a', 'b')
+ const previous = process.umask(0o002) // Ubuntu's default
+ try { secureStateDirectory(dir) } finally { process.umask(previous) }
+ expect(modeOf(dir)).toBe(0o700)
+ })
+
+ /**
+ * A group-writable directory is refused, NOT tightened — if another account could write here it could
+ * already have planted the registry or the token, and chmod-then-trust would keep the planted copy.
+ * registry.spec.ts, hookAuth.spec.ts and terminalConfigSnapshot.spec.ts pin the same rule.
+ *
+ * What Ubuntu changed is where the mode comes from, not what to do about it: umask 0002 meant the
+ * daemon's OWN `mkdirSync(..., { recursive: true })` produced 0775 and then refused to start on it —
+ * measured on 24.04, on every entry point. The fix is above, at creation time. A pre-existing 0775
+ * directory from an older build still lands here, so the message must be actionable.
+ */
+ it('refuses a group-writable directory and says how to fix it', () => {
+ const dir = scratch(0o775)
+ expect(() => secureStateDirectory(dir, false)).toThrow(/group\/world writable/)
+ expect(() => secureStateDirectory(dir, false)).toThrow(new RegExp(`chmod 700 ${dir}`))
+ expect(modeOf(dir)).toBe(0o775) // untouched: the caller decides, we do not paper over it
+ })
+
+ it('refuses a world-writable directory too', () => {
+ expect(() => secureStateDirectory(scratch(0o707), false)).toThrow(/group\/world writable/)
+ })
+
+ it('leaves an already-private directory alone', () => {
+ const dir = scratch(0o700)
+ secureStateDirectory(dir, false)
+ expect(modeOf(dir)).toBe(0o700)
+ })
+
+ it('tightens a group/other-readable directory too', () => {
+ const dir = scratch(0o755)
+ secureStateDirectory(dir, false)
+ expect(modeOf(dir)).toBe(0o700)
+ })
+})
+
+describe('readPrivateStateFile', () => {
+ function file(mode: number): string {
+ const root = mkdtempSync(join(tmpdir(), 'secure-state-'))
+ dirs.push(root)
+ const path = join(root, 'token')
+ writeFileSync(path, 'secret')
+ chmodSync(path, mode)
+ return path
+ }
+
+ // Same rule as the directory: refuse, never chmod-then-trust. Every writer under ADAPTER_DATA_DIR
+ // passes mode 0o600, so Ubuntu's umask 0002 cannot produce a 0664 state file in the first place.
+ it('refuses a group-writable state file rather than tightening it', () => {
+ const path = file(0o664)
+ expect(() => readPrivateStateFile(path)).toThrow(/group\/world writable/)
+ expect(statSync(path).mode & 0o777).toBe(0o664)
+ })
+
+ it('reads a private state file', () => {
+ expect(readPrivateStateFile(file(0o600))).toBe('secret')
+ })
+})
diff --git a/cli/src/lib/secureState.ts b/cli/src/lib/secureState.ts
index 7746de583..b40144798 100644
--- a/cli/src/lib/secureState.ts
+++ b/cli/src/lib/secureState.ts
@@ -32,7 +32,17 @@ export function secureStateDirectory(directory: string, create = true): void {
throw new Error('state directory has unsafe owner or type')
}
const mode = stat.mode & 0o777
- if ((mode & 0o022) !== 0) throw new Error('state directory is group/world writable')
+ // Refuse — deliberately do NOT chmod and carry on. If another account could write here, it could
+ // already have planted the registry, the token or the hook credential, and tightening afterwards
+ // would leave us trusting whatever it left behind. Three tests pin this (registry.spec.ts,
+ // hookAuth.spec.ts, terminalConfigSnapshot.spec.ts); the fix belongs at creation time, and every
+ // site that makes a directory under ADAPTER_DATA_DIR now passes mode 0o700 so Ubuntu's default
+ // umask 0002 can no longer produce a 0775 one. This branch is what a PRE-EXISTING 0775 directory
+ // (made by an older build on Ubuntu) lands in, so the message has to say what to do about it.
+ if ((mode & 0o022) !== 0) {
+ throw new Error(`state directory ${directory} is group/world writable, so its contents cannot be`
+ + ` trusted. If you did not set that mode yourself, delete it; otherwise: chmod 700 ${directory}`)
+ }
if (mode !== PRIVATE_DIRECTORY_MODE) {
fchmodSync(fd, PRIVATE_DIRECTORY_MODE)
if ((fstatSync(fd).mode & 0o777) !== PRIVATE_DIRECTORY_MODE) {
@@ -52,6 +62,8 @@ function inspectPrivateStateFile(fd: number, maxBytes: number): void {
}
if (stat.size > maxBytes) throw new Error('state file exceeds its size limit')
const mode = stat.mode & 0o777
+ // Same reasoning as secureStateDirectory: a file another account could have rewritten is not made
+ // trustworthy by tightening it now. Every writer under ADAPTER_DATA_DIR already passes mode 0o600.
if ((mode & 0o022) !== 0) throw new Error('state file is group/world writable')
if (mode !== PRIVATE_FILE_MODE) {
fchmodSync(fd, PRIVATE_FILE_MODE)
diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.ts
index 69b329376..d64e3fb13 100644
--- a/cli/src/lib/sessionRepair.ts
+++ b/cli/src/lib/sessionRepair.ts
@@ -24,6 +24,7 @@ import type { AgentEngine } from '../engines/types.js'
import { readCodexRolloutMeta } from '../engines/codex/rollout.js'
import { agyConversationForPid, findAgyTranscript } from '../engines/agy/session.js'
import { copilotSessionCwd, copilotSessionForPid, findCopilotTranscript } from '../engines/copilot/session.js'
+import { sqlitePreflightMessage } from './sqliteAvailability.js'
const execFileAsync = promisify(execFile)
@@ -172,6 +173,15 @@ async function fileEngineSession(
return wrote.length === 1 ? wrote[0] : null
}
+let missingSqliteReported = false
+
+/** The store-backed repair branch cannot work without the `sqlite3` CLI; warn on the first miss only. */
+function reportMissingSqliteOnce(): void {
+ if (missingSqliteReported) return
+ missingSqliteReported = true
+ console.warn(sqlitePreflightMessage() ?? '[preflight] sqlite3 CLI not found on PATH')
+}
+
async function dbEngineSession(dbPath: string, sql: string): Promise<RepairedSession | null> {
let stdout: string
try {
@@ -182,7 +192,12 @@ async function dbEngineSession(dbPath: string, sql: string): Promise<RepairedSes
['-json', '-cmd', '.timeout 3000', '-cmd', 'PRAGMA query_only=1', dbPath, sql],
{ maxBuffer: 1024 * 1024 },
))
- } catch { return null }
+ } catch (err) {
+ // A missing binary is not a transient DB lock, and repair returning null forever with no signal is
+ // how "my opencode agents never appear on Ubuntu" looks from the outside. Say it once.
+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') reportMissingSqliteOnce()
+ return null
+ }
const trimmed = stdout.trim()
if (!trimmed) return null
let rows: Array<Record<string, unknown>>
diff --git a/cli/src/lib/sqliteAvailability.spec.ts b/cli/src/lib/sqliteAvailability.spec.ts
new file mode 100644
index 000000000..19d066815
--- /dev/null
+++ b/cli/src/lib/sqliteAvailability.spec.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it, afterEach } from 'vitest'
+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { delimiter, join } from 'node:path'
+import { hasSqliteCli, resetSqliteAvailabilityCache, sqlitePreflightMessage } from './sqliteAvailability.js'
+
+const dirs: string[] = []
+const realPath = process.env.PATH
+
+afterEach(() => {
+ process.env.PATH = realPath
+ resetSqliteAvailabilityCache()
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
+})
+
+function pathWith(executable: boolean): string {
+ const dir = mkdtempSync(join(tmpdir(), 'sqlite-probe-'))
+ dirs.push(dir)
+ if (executable) {
+ const bin = join(dir, 'sqlite3')
+ writeFileSync(bin, '#!/bin/sh\nexit 0\n')
+ chmodSync(bin, 0o755)
+ }
+ return dir
+}
+
+describe('sqlite3 preflight', () => {
+ it('stays silent when the CLI is on PATH', () => {
+ process.env.PATH = pathWith(true)
+ resetSqliteAvailabilityCache()
+ expect(hasSqliteCli()).toBe(true)
+ expect(sqlitePreflightMessage()).toBeNull()
+ })
+
+ // Ubuntu does not ship sqlite3 (measured on a stock ubuntu:24.04 image), so on Linux this is the
+ // default state, not an exotic one. The line must name the affected engines AND the fix — a bare
+ // "sqlite3 not found" leaves the user with four engines that mirror nothing and no idea why.
+ it('names the affected engines and the fix when it is absent', () => {
+ process.env.PATH = pathWith(false)
+ resetSqliteAvailabilityCache()
+ expect(hasSqliteCli()).toBe(false)
+ const message = sqlitePreflightMessage()
+ expect(message).toContain('sqlite3')
+ for (const engine of ['opencode', 'kilo', 'hermes', 'devin']) expect(message).toContain(engine)
+ expect(message).toMatch(/apt install sqlite3|on PATH/)
+ })
+
+ it('ignores a non-executable file of the same name', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'sqlite-probe-'))
+ dirs.push(dir)
+ writeFileSync(join(dir, 'sqlite3'), 'not executable')
+ chmodSync(join(dir, 'sqlite3'), 0o644)
+ process.env.PATH = dir
+ resetSqliteAvailabilityCache()
+ expect(hasSqliteCli()).toBe(false)
+ })
+
+ it('tolerates empty entries in PATH', () => {
+ process.env.PATH = `${delimiter}${pathWith(true)}${delimiter}`
+ resetSqliteAvailabilityCache()
+ expect(hasSqliteCli()).toBe(true)
+ })
+})
diff --git a/cli/src/lib/sqliteAvailability.ts b/cli/src/lib/sqliteAvailability.ts
new file mode 100644
index 000000000..0e955f90f
--- /dev/null
+++ b/cli/src/lib/sqliteAvailability.ts
@@ -0,0 +1,44 @@
+/**
+ * Is the `sqlite3` CLI present?
+ *
+ * Four engines keep their conversations in SQLite rather than in a transcript file and are read by
+ * shelling out to `sqlite3` (`engines/{opencode,kilo,hermes,devin}/reader.ts`), as is one branch of
+ * session repair. macOS ships `/usr/bin/sqlite3` in the base system, so this has never had to be
+ * checked; a stock `ubuntu:24.04` does NOT ship it (measured), and neither does a slim Node image, so
+ * on Linux those four engines silently mirror nothing until the user installs it.
+ *
+ * Resolved from PATH directly rather than by spawning: this runs on the startup path and the answer is
+ * only used for one advisory log line.
+ */
+import { accessSync, constants } from 'node:fs'
+import { delimiter, join } from 'node:path'
+
+/** Engines that cannot be mirrored without the CLI. Keep in sync with the readers listed above. */
+export const SQLITE_BACKED_ENGINES = ['opencode', 'kilo', 'hermes', 'devin'] as const
+
+let cached: boolean | null = null
+
+export function hasSqliteCli(): boolean {
+ if (cached !== null) return cached
+ const exts = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : ['']
+ cached = (process.env.PATH ?? '').split(delimiter).some((dir) => {
+ if (!dir) return false
+ return exts.some((ext) => {
+ try { accessSync(join(dir, `sqlite3${ext}`), constants.X_OK); return true } catch { return false }
+ })
+ })
+ return cached
+}
+
+/** One advisory line at startup. Says what is affected and exactly how to fix it — never throws. */
+export function sqlitePreflightMessage(): string | null {
+ if (hasSqliteCli()) return null
+ const install = process.platform === 'linux'
+ ? 'sudo apt install sqlite3 (or your distro\'s equivalent)'
+ : 'install the sqlite3 CLI and make sure it is on PATH'
+ return `[preflight] sqlite3 CLI not found on PATH — ${SQLITE_BACKED_ENGINES.join(', ')}`
+ + ` agents cannot be mirrored. Every other engine is unaffected. Fix: ${install}`
+}
+
+/** Test seam: forget the cached answer. */
+export function resetSqliteAvailabilityCache(): void { cached = null }
diff --git a/cli/src/lib/summarize.ts b/cli/src/lib/summarize.ts
index 633840c78..6a4656578 100644
--- a/cli/src/lib/summarize.ts
+++ b/cli/src/lib/summarize.ts
@@ -43,7 +43,7 @@ const MAX_INPUT_CHARS = 50_000
const SUMMARY_SCRATCH = join(env.ADAPTER_DATA_DIR, 'summary-scratch')
function ensureSummaryScratch(): string {
- if (!existsSync(SUMMARY_SCRATCH)) mkdirSync(SUMMARY_SCRATCH, { recursive: true })
+ if (!existsSync(SUMMARY_SCRATCH)) mkdirSync(SUMMARY_SCRATCH, { recursive: true, mode: 0o700 })
return SUMMARY_SCRATCH
}
diff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.ts
index 98db8410e..691746070 100644
--- a/cli/src/lib/tmux.spec.ts
+++ b/cli/src/lib/tmux.spec.ts
@@ -33,6 +33,51 @@ describe('tmux process primitives', () => {
})
})
+ /**
+ * Real `ps -axo pid=,ppid=,comm=,lstart=,args=` output captured on Ubuntu 24.04 (procps-ng 4.0.4),
+ * not a macOS-shaped invention. Two things differ from macOS and both are load-bearing:
+ * - `comm` is a bare name, never a path (`/sbin/docker-init` reads back as `docker-init`);
+ * - `comm` is hard-capped at 15 bytes by TASK_COMM_LEN, so the binary really named
+ * `a-very-long-engine-name-binary` reads back as `a-very-long-eng`.
+ * `tmux: server` also proves comm can still carry a space on Linux, which is why the parser anchors
+ * on lstart rather than splitting comm as one token.
+ */
+ it('parses real Linux procps rows, including a 15-byte-truncated comm', () => {
+ expect(parseProcessRow(' 1 0 docker-init Fri Aug 21 09:28:14 2026 /sbin/docker-init -- bash -lc')).toEqual({
+ pid: 1,
+ parentPid: 0,
+ executable: 'docker-init',
+ startMarker: 'Fri Aug 21 09:28:14 2026',
+ args: '/sbin/docker-init -- bash -lc',
+ })
+ expect(parseProcessRow(' 15 1 tmux: server Fri Aug 21 09:28:14 2026 tmux new-session -d -s probe sleep 400')).toEqual({
+ pid: 15,
+ parentPid: 1,
+ executable: 'tmux: server',
+ startMarker: 'Fri Aug 21 09:28:14 2026',
+ args: 'tmux new-session -d -s probe sleep 400',
+ })
+ const truncated = parseProcessRow(
+ ' 12 7 a-very-long-eng Fri Aug 21 09:28:14 2026 /tmp/a-very-long-engine-name-binary -e x')
+ expect(truncated?.executable).toBe('a-very-long-eng')
+ expect(Buffer.byteLength(truncated!.executable)).toBe(15)
+ })
+
+ /**
+ * Linux procps substitutes `?` for any byte it cannot print in the current locale, and a daemon under
+ * systemd/docker/ssh usually has no locale at all. Measured on Ubuntu 24.04: a Command Code pane reads
+ * back as `??? <title>` in BOTH comm and args, so both halves of its marker fail and the reaper evicts
+ * the live pane. processRows() now reads ps under LC_ALL=C.UTF-8 and repairs any surviving `?` row from
+ * /proc, which is raw bytes. These two cases pin the before and the after.
+ */
+ it('scores Command Code from the real bytes, and cannot from the mangled ones', () => {
+ const mangled = parseProcessRow(' 185 178 ??? harness-cli Fri Aug 21 09:34:20 2026 ??? harness-cli ubuntu probe')
+ expect(engineProcessMatchScore(mangled!, 'commandcode')).toBe(0)
+
+ const repaired = parseProcessRow(' 185 178 ⌘ harness-cli Fri Aug 21 09:34:20 2026 ⌘ harness-cli ubuntu probe')
+ expect(engineProcessMatchScore(repaired!, 'commandcode')).toBe(3)
+ })
+
it('recognises stable installed binary forms', () => {
expect(engineProcessMatchScore({ executable: 'devin', args: 'devin' }, 'devin')).toBe(3)
expect(engineProcessMatchScore({ executable: 'muse-bin-0.1.0-R708.1', args: 'muse-bin-0.1.0-R708.1' }, 'muse')).toBe(3)
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index c6940b1a4..f950c3be7 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -1,6 +1,7 @@
/** tmux process matching, runtime validation, pane capture, and input injection. */
import { execFile, spawn } from 'child_process'
+import { readFileSync } from 'node:fs'
import { readlink } from 'node:fs/promises'
import { platform } from 'node:os'
import { basename } from 'path'
@@ -142,10 +143,51 @@ export function parseProcessRow(line: string): ProcessRow | null {
}
}
+/**
+ * Second line of defence for the locale substitution described on PS_ENV: a glibc build with no
+ * `C.UTF-8` locale falls back to POSIX and `ps` mangles again. `/proc` is raw bytes and cannot be
+ * mangled by anything, so re-read the two fields from there — but only for the rows that actually show
+ * a `?`, which under a working locale is none. Measured cost of reading every `/proc/<pid>/cmdline` on
+ * a 63-process container: 0.48ms, so even the degenerate "every row" case is free.
+ *
+ * No-op off Linux: macOS has no /proc and does not substitute in the first place.
+ */
+function repairMangledRows(rows: ProcessRow[]): ProcessRow[] {
+ if (process.platform !== 'linux') return rows
+ return rows.map((row) => {
+ if (!row.executable.includes('?') && !row.args.includes('?')) return row
+ // cmdline is NUL-separated; node's process.title rewrite space-pads the tail of the argv region.
+ const args = readProcField(row.pid, 'cmdline')?.replace(/\0/g, ' ').trimEnd()
+ const executable = readProcField(row.pid, 'comm')?.trimEnd()
+ return { ...row, ...(executable && { executable }), ...(args && { args }) }
+ })
+}
+
+function readProcField(pid: number, field: 'cmdline' | 'comm'): string | null {
+ try { return readFileSync(`/proc/${pid}/${field}`, 'utf8') } catch { return null }
+}
+
+/**
+ * The environment `ps` is read under.
+ *
+ * Linux procps replaces every byte it cannot print in the current locale with `?`, and a daemon
+ * frequently has NO locale at all — `LANG` is unset under systemd, under `docker run`, and in an ssh
+ * session that forwards nothing, which makes `LC_CTYPE` fall back to POSIX. Measured on Ubuntu 24.04
+ * (procps-ng 4.0.4): a process whose argv is `⌘ <session title>` prints as `??? <session title>` in
+ * BOTH `comm` and `args`, so both halves of the Command Code marker below fail and every live cmd pane
+ * is evicted by the reaper. Under `LC_ALL=C.UTF-8` the same read returns the real bytes.
+ *
+ * macOS never substitutes (verified: default, C.UTF-8 and POSIX all pass ⌘ through), so this is applied
+ * only where it is needed and cannot regress the platform that already works.
+ */
+const PS_ENV = process.platform === 'linux'
+ ? { ...process.env, LC_ALL: 'C.UTF-8' }
+ : process.env
+
/** The process table, or null when `ps` itself failed — "we could not look" is not "nothing is there". */
export async function processRows(): Promise<ProcessRow[] | null> {
const rows = await new Promise<ProcessRow[] | null>((resolve) => {
- execFile('ps', ['-axo', 'pid=,ppid=,comm=,lstart=,args='], { timeout: 3000 }, (err, stdout) => {
+ execFile('ps', ['-axo', 'pid=,ppid=,comm=,lstart=,args='], { timeout: 3000, env: PS_ENV }, (err, stdout) => {
if (err) { resolve(null); return }
const rows: ProcessRow[] = []
for (const line of stdout.split('\n')) {
@@ -155,7 +197,7 @@ export async function processRows(): Promise<ProcessRow[] | null> {
resolve(rows)
})
})
- return rows ? enrichProcessRows(rows) : null
+ return rows ? enrichProcessRows(repairMangledRows(rows)) : null
}
function execText(command: string, args: string[], timeout: number): Promise<string | null> {
@@ -232,6 +274,18 @@ function panePid(pane: string): Promise<number | null> {
})
}
+/**
+ * Linux caps `comm` at 15 bytes (TASK_COMM_LEN) and never prints a path there, while macOS prints the
+ * full executable path. Measured on Ubuntu 24.04: a binary named `a-very-long-engine-name-binary` reads
+ * back as `a-very-long-eng`. So on Linux the full-path clause can never fire, and an override whose
+ * basename is longer than the cap can only ever be seen truncated — accept that prefix as evidence.
+ * No supported engine's own basename reaches the cap; this covers a user-set `*_PATH` override.
+ */
+function commTruncatedPrefixOf(seen: string, want: string): boolean {
+ if (process.platform !== 'linux' || !seen || !want) return false
+ return Buffer.byteLength(seen) === 15 && want.length > seen.length && want.startsWith(seen)
+}
+
export function engineProcessMatchScore(
row: Pick<ProcessRow, 'executable' | 'args' | 'imageFileKey' | 'entrypointFileKey'>,
engine: RegisteredSession['engine'],
@@ -245,7 +299,8 @@ export function engineProcessMatchScore(
const configured = enginePathOverride(engine)?.toLowerCase()
const configuredBase = basename(configured ?? '').toLowerCase()
if (configured && configuredBase !== 'agent' && (row.executable.toLowerCase() === configured
- || entrypoint === configured || executable === configuredBase || entrybase === configuredBase)) return 4
+ || entrypoint === configured || executable === configuredBase || entrybase === configuredBase
+ || commTruncatedPrefixOf(executable, configuredBase))) return 4
if (engine === 'codex') {
if (executable === 'codex' || entrybase === 'codex') return 3
// npm/pnpm/bun global installs may leave node as `comm`; match the package entrypoint without
diff --git a/cli/src/lib/voiceRouter.ts b/cli/src/lib/voiceRouter.ts
index 1cd0d978c..60ea4ecf9 100644
--- a/cli/src/lib/voiceRouter.ts
+++ b/cli/src/lib/voiceRouter.ts
@@ -74,7 +74,7 @@ let routerEngine: RouterEngine | null = null
// With --no-session-persistence the one-shot writes nothing here; the dir just has to exist as the cwd.
function ensureRouteScratch(): string {
- if (!existsSync(ROUTE_SCRATCH)) mkdirSync(ROUTE_SCRATCH, { recursive: true })
+ if (!existsSync(ROUTE_SCRATCH)) mkdirSync(ROUTE_SCRATCH, { recursive: true, mode: 0o700 })
return ROUTE_SCRATCH
}