Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ CLI `spawn` and `resume` detach a per-turn supervisor, so the one-shot invocatio

## How it works

**Core** (`src/core`) has five functions, one per verb. Admission runs before any quota is spent: a persisted per-harness pin (binary path and version, self-healing on staleness) and a cheap auth check that never launches the harness (Codex's `auth.json` tokens, the macOS keychain item for Claude Code, Grok's and OpenCode's auth files). A spawn that dies before the harness produces a session id throws a plain error carrying the auth result, argv, stderr, and exit inline. Model ids are never gated: a wrong one fails inside the harness and comes back as evidence.
**Core** (`src/core`) has five functions, one per verb. Admission runs before any quota is spent: a persisted per-harness pin (the newest copy of the binary on PATH or in the usual install dirs, re-probed when that set of files changes) and a cheap auth check that never launches the harness (Codex's `auth.json` tokens, the macOS keychain item for Claude Code, Grok's and OpenCode's auth files). A spawn that dies before the harness produces a session id throws a plain error carrying the auth result, argv, stderr, and exit inline. Model ids are never gated: a wrong one fails inside the harness and comes back as evidence.

**Sessions** live under `~/.local/state/subturn/sessions/<session-id>/` (`SUBTURN_STATE_DIR` overrides). The directory holds the record, the prompt, the spawn command, the event stream as it happens, stderr, the acknowledged bundle where the harness echoes one, and the final text, so `inspect` works on a running session. Retention is 7 days after the last turn (`SUBTURN_RETENTION_DAYS`), swept on each spawn or on demand by `prune`; the resume window is the retention window, because the harness state needed for resume lives in the same directory. The deadline default is 3600 s (`SUBTURN_DEADLINE_S`), the maximum six hours.

Expand Down
111 changes: 82 additions & 29 deletions src/core/discovery.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,34 @@
// core/discovery.ts — discovery is a mechanism, not a tool (AGENTS.md).
// A persisted per-harness pin (binary path + version) makes launch admit and
// spawn without a PATH hunt; the cache self-heals — a stale or missing entry
// triggers one probe, never a refusal.
// Every copy of the binary on PATH and in the well-known dirs is a
// candidate; the newest `--version` is launched. The persisted per-harness
// pin is keyed on that candidate set (paths, mtimes, sizes): while the set
// is unchanged, admission reuses the pin without a probe. A shim that
// dispatches to another file at run time does not change when its target
// does, so a pin also expires after PIN_TTL_MS and is probed again.

import { spawn } from "node:child_process";
import { accessSync, constants, mkdirSync, readFileSync, statSync, writeFileSync, renameSync } from "node:fs";
import { accessSync, constants, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync, renameSync } from "node:fs";
import { homedir } from "node:os";
import path from "node:path";

import { stateDir } from "./state.ts";
import type { DetectHints } from "../plugins/types.ts";

export interface Candidate {
binPath: string;
/** First line of `--version`; "unknown" when it printed nothing. */
version: string;
/** mtime + size of the file the path resolves to. */
fingerprint: string;
}

export interface Pin {
binPath: string;
version: string;
/** mtime of the binary at probe time — a rewritten binary invalidates. */
binMtimeMs: number;
checkedAt: string;
/** Every distinct executable found, in hunt order; the pin is the newest
* of them. CLI `status` lists the rest. */
candidates: Candidate[];
}

type Cache = Record<string, Pin>;
Expand Down Expand Up @@ -53,20 +65,38 @@ function isExecutable(p: string): boolean {
}
}

/** PATH + well-known dirs hunt. Returns the first executable hit. */
function findBinary(hints: DetectHints): string | null {
function fingerprintOf(p: string): string {
try {
const st = statSync(p);
return `${st.mtimeMs}:${st.size}`;
Comment thread
eshatalov marked this conversation as resolved.
Resolved
} catch {
return "gone";
}
}

/** PATH + well-known dirs hunt. Every executable hit, in hunt order, one
* per real file; the first spelling of a file is kept. */
function findCandidates(hints: DetectHints): Array<{ binPath: string; fingerprint: string }> {
const pathDirs = (process.env["PATH"] ?? "").split(path.delimiter).filter((d) => d !== "");
const extraDirs = hints.wellKnownDirs.map((d) => d.replace(/^~(?=\/|$)/, homedir()));
const seen = new Set<string>();
const found: Array<{ binPath: string; fingerprint: string }> = [];
for (const name of hints.binaryNames) {
for (const dir of [...pathDirs, ...extraDirs]) {
const candidate = path.join(dir, name);
if (isExecutable(candidate)) return candidate;
if (!isExecutable(candidate)) continue;
let real = candidate;
try { real = realpathSync(candidate); } catch { /* keep the spelling */ }
if (seen.has(real)) continue;
seen.add(real);
found.push({ binPath: candidate, fingerprint: fingerprintOf(candidate) });
}
}
return null;
return found;
}

const VERSION_TIMEOUT_MS = 10_000;
const PIN_TTL_MS = 24 * 60 * 60 * 1000;

/** `<bin> --version`, first line, 10 s cap. Never throws. */
function captureVersion(binPath: string): Promise<string | null> {
Expand Down Expand Up @@ -99,37 +129,60 @@ function captureVersion(binPath: string): Promise<string | null> {
});
}

/** The first dotted number in a version line ("codex-cli 0.159.0",
* "2.1.283 (Claude Code)", "grok 1.0.44 (abc) [stable]"). Null when none. */
function parseVersion(line: string): number[] | null {
const m = /(\d+)\.(\d+)(?:\.(\d+))?/.exec(line);
if (m === null) return null;
return [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)];
}

/** >0 when a is newer than b. Unparsable loses to parsed; two unparsable tie. */
function compareVersions(a: string, b: string): number {
const pa = parseVersion(a);
const pb = parseVersion(b);
if (pa === null || pb === null) return (pa === null ? 0 : 1) - (pb === null ? 0 : 1);
for (let i = 0; i < 3; i++) {
const d = (pa[i] ?? 0) - (pb[i] ?? 0);
if (d !== 0) return d;
}
return 0;
}

function sameSet(
cached: Candidate[] | undefined,
found: Array<{ binPath: string; fingerprint: string }>,
): boolean {
if (cached === undefined || cached.length !== found.length) return false;
return cached.every((c, i) => c.binPath === found[i]?.binPath && c.fingerprint === found[i]?.fingerprint);
}

/**
* Resolve the pin for one harness: cached when the binary is still the same
* file, re-probed otherwise. Null = the harness is not installed.
* Resolve the pin for one harness: cached while the installed set is
* unchanged and the pin is younger than PIN_TTL_MS, re-probed otherwise.
* Null = the harness is not installed.
*/
export async function resolvePin(name: string, hints: DetectHints): Promise<Pin | null> {
const cache = readCache();
const cached = cache[name];
if (cached !== undefined) {
try {
const st = statSync(cached.binPath);
if (st.isFile() && st.mtimeMs === cached.binMtimeMs) return cached;
} catch {
/* stale — fall through to re-probe */
}
}
const binPath = findBinary(hints);
if (binPath === null) {
const found = findCandidates(hints);
if (cached !== undefined && sameSet(cached.candidates, found)
&& Date.now() - Date.parse(cached.checkedAt) < PIN_TTL_MS) return cached;
if (found.length === 0) {
if (cached !== undefined) {
delete cache[name];
writeCache(cache);
}
return null;
}
const version = (await captureVersion(binPath)) ?? "unknown";
let binMtimeMs = 0;
try {
binMtimeMs = statSync(binPath).mtimeMs;
} catch {
/* keep 0: next resolve re-probes */
const versions = await Promise.all(found.map((c) => captureVersion(c.binPath)));
const candidates: Candidate[] = found.map((c, i) => ({ ...c, version: versions[i] ?? "unknown" }));
// Newest wins; a tie keeps hunt order.
let best = candidates[0] as Candidate;
for (const c of candidates.slice(1)) {
if (compareVersions(c.version, best.version) > 0) best = c;
}
const pin: Pin = { binPath, version, binMtimeMs, checkedAt: new Date().toISOString() };
const pin: Pin = { binPath: best.binPath, version: best.version, checkedAt: new Date().toISOString(), candidates };
cache[name] = pin;
writeCache(cache);
return pin;
Expand Down
5 changes: 5 additions & 0 deletions src/faces/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,14 @@ async function cmdStatus(): Promise<void> {
? `\n${" ".repeat(10)}models: ${models.join(", ")}`
: `\n${" ".repeat(10)}models: (no cheap advertisement for this harness)`;
}
const others = pin.candidates.filter((c) => c.binPath !== pin.binPath);
const othersLine = others.length > 0
? `${" ".repeat(10)}also installed, older: ${others.map((c) => `${c.binPath} (${c.version})`).join(", ")}\n`
: "";
rows.push(
`${name.padEnd(9)} ${pin.version}\n` +
`${" ".repeat(10)}binary: ${pin.binPath}\n` +
othersLine +
`${" ".repeat(10)}auth: ${auth.ok ? "ok" : "NOT AUTHORIZED"} — ${auth.detail}` +
modelsLine,
);
Expand Down
3 changes: 2 additions & 1 deletion src/plugins/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
import type { Usage } from "../core/state.ts";

export interface DetectHints {
/** Binary name(s) to hunt on PATH. */
/** Binary name(s) to hunt on PATH and in wellKnownDirs. Every hit is a
* candidate; the newest version is launched. */
binaryNames: string[];
/** Extra directories to search beyond PATH (installers love ~/.x/bin). */
wellKnownDirs: string[];
Expand Down
112 changes: 112 additions & 0 deletions test/discovery.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
// test/discovery.test.ts — binary discovery against scripted binaries: the
// newest copy wins regardless of PATH order; the pin is reused while the
// candidate set is unchanged and re-probed on install, upgrade or removal;
// aliases of one file are one candidate; a pin older than a day is probed
// again even when the set is unchanged.

import test from "node:test";
import assert from "node:assert/strict";
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";

const root = mkdtempSync(path.join(tmpdir(), "subturn-discovery-"));
process.env["SUBTURN_STATE_DIR"] = path.join(root, "state");

const { resolvePin } = await import("../src/core/discovery.ts");

test.after(() => {
rmSync(root, { recursive: true, force: true });
});

let tick = 1_000_000_000; // distinct mtimes without sleeping
function install(dir: string, version: string): string {
mkdirSync(dir, { recursive: true });
const bin = path.join(dir, "fakex");
writeFileSync(bin, `#!/bin/sh\necho "fakex-cli ${version}"\n`);
chmodSync(bin, 0o755);
tick += 10;
utimesSync(bin, tick, tick);
return bin;
}

const nvmDir = path.join(root, "nvm", "bin");
const localDir = path.join(root, "local", "bin");
const brewDir = path.join(root, "brew", "bin");
const hints = { binaryNames: ["fakex"], wellKnownDirs: [brewDir] };

test("the newest installed copy wins over PATH order, and the pin caches the installed set", async () => {
const old = install(nvmDir, "0.147.0");
const fresh = install(localDir, "0.159.0");
// The older copy comes first on PATH; one dir is listed twice.
process.env["PATH"] = [nvmDir, localDir, localDir].join(path.delimiter);

const pin = await resolvePin("fakex", hints);
assert.ok(pin !== null);
assert.equal(pin.binPath, fresh);
assert.equal(pin.version, "fakex-cli 0.159.0");
assert.deepEqual(pin.candidates.map((c) => c.binPath), [old, fresh], "duplicates collapse, hunt order kept");

// Nothing changed: the cached pin comes back unchanged.
const again = await resolvePin("fakex", hints);
assert.ok(again !== null);
assert.equal(again.checkedAt, pin.checkedAt);

// A day-old pin is probed again even though nothing changed.
const cacheFile = path.join(root, "state", "discovery.json");
const cache = JSON.parse(readFileSync(cacheFile, "utf8")) as Record<string, { checkedAt: string }>;
(cache["fakex"] as { checkedAt: string }).checkedAt = new Date(Date.now() - 25 * 60 * 60 * 1000).toISOString();
writeFileSync(cacheFile, JSON.stringify(cache));
const expired = await resolvePin("fakex", hints);
assert.ok(expired !== null);
assert.equal(expired.binPath, fresh);
assert.notEqual(expired.checkedAt, cache["fakex"]?.checkedAt);

// A newer copy in a well-known dir that is not on PATH wins.
const brew = install(brewDir, "0.160.2");
const third = await resolvePin("fakex", hints);
assert.ok(third !== null);
assert.equal(third.binPath, brew);
assert.notEqual(third.checkedAt, pin.checkedAt);

// The older copy is upgraded in place past the others.
install(nvmDir, "1.0.0");
const upgraded = await resolvePin("fakex", hints);
assert.ok(upgraded !== null);
assert.equal(upgraded.binPath, old);
assert.equal(upgraded.version, "fakex-cli 1.0.0");

// The winner is removed: next newest.
rmSync(old);
const afterRemove = await resolvePin("fakex", hints);
assert.ok(afterRemove !== null);
assert.equal(afterRemove.binPath, brew);

// Everything removed: not installed, pin dropped.
rmSync(fresh);
rmSync(brew);
assert.equal(await resolvePin("fakex", hints), null);
});

test("a symlink alias is the same candidate; a tie keeps PATH order; unparsable versions lose", async () => {
const a = path.join(root, "tie-a");
const b = path.join(root, "tie-b");
const c = path.join(root, "tie-c");
const first = install(a, "2.0.0");
install(b, "2.0.0");
mkdirSync(c, { recursive: true });
symlinkSync(first, path.join(c, "fakex"));
const junkDir = path.join(root, "junk");
mkdirSync(junkDir, { recursive: true });
const junk = path.join(junkDir, "fakex");
writeFileSync(junk, "#!/bin/sh\necho 'development build'\n");
chmodSync(junk, 0o755);
process.env["PATH"] = [junkDir, c, a, b].join(path.delimiter);

const pin = await resolvePin("tie", { binaryNames: ["fakex"], wellKnownDirs: [] });
assert.ok(pin !== null);
// The symlink in c is the first spelling of the file in a; b is a distinct file of the same version.
assert.equal(pin.candidates.length, 3, "junk, c(=a), b");
assert.equal(pin.binPath, path.join(c, "fakex"), "first spelling of the newest, in PATH order");
assert.equal(pin.candidates[0]?.version, "development build");
});
Loading