diff --git a/apps/host/server/engine-install.mjs b/apps/host/server/engine-install.mjs index c49a48d1..97a1a893 100644 --- a/apps/host/server/engine-install.mjs +++ b/apps/host/server/engine-install.mjs @@ -11,6 +11,7 @@ import { Readable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; import { exec } from './util.mjs'; import { HOME } from './store.mjs'; +import { tarBinary } from './platform-paths.mjs'; import { nowIso } from './util.mjs'; const ENGINE_DIR = join(HOME, 'engine'); @@ -153,7 +154,7 @@ export async function install({ force = false } = {}) { state.stage = 'Unpacking the engine'; emit(); - await exec('/usr/bin/tar', ['-xf', archive, '-C', ENGINE_DIR], { timeout: 180_000 }); + await exec(tarBinary(), ['-xf', archive, '-C', ENGINE_DIR], { timeout: 180_000 }); rmSync(archive, { force: true }); const binary = findInstalledBinary(); diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index 3a3b4117..3b5a46a4 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -10,6 +10,7 @@ import { createTaskService, validateTask } from './tasks.mjs'; import { migrateSetup } from './setup.mjs'; import { skillEdit } from './skill-edits.mjs'; import { systemFonts } from './fonts.mjs'; +import { tuningDir } from './platform-paths.mjs'; /** * Strata engine host. * @@ -574,8 +575,7 @@ const TIMESKIP_REVISE = process.env.STRATA_TIMESKIP_REVISE */ function createTuning({ repoRoot, python, pythonArgs = [], env = process.env } = {}) { const cli = join(repoRoot, 'strata.py'); - const stateDir = () => env.STRATA_TUNE_DIR - || join(env.XDG_STATE_HOME || join(env.HOME || '.', '.local', 'state'), 'strata', 'tuning'); + const stateDir = () => tuningDir(env); function runCli(args) { return new Promise((resolve) => { diff --git a/apps/host/server/platform-paths.mjs b/apps/host/server/platform-paths.mjs new file mode 100644 index 00000000..a72d8556 --- /dev/null +++ b/apps/host/server/platform-paths.mjs @@ -0,0 +1,48 @@ +/** + * Where things live, and which system tool to call, per platform. + * + * The host used to assume POSIX in three places: it called /usr/bin/tar and /usr/bin/env, and it kept the tuning + * and Time-skip state under $HOME/.local/state. On Windows those paths do not exist. State goes to + * %LOCALAPPDATA%\Strata (the same place the Python side uses: strata_control/paths.py), and the system tools are + * the ones Windows ships (System32\tar.exe, System32\where.exe). POSIX behavior is unchanged. + * + * Every function takes the environment and platform as arguments so tests can exercise both without a second OS. + */ +import { homedir } from 'node:os'; +import { posix } from 'node:path'; + +const winPath = (...parts) => parts.join('\\'); + +/** The folder under which Strata keeps per-user state (tuning jobs, Time-skip runs). */ +export function stateRoot(env = process.env, platform = process.platform, home = homedir()) { + if (platform === 'win32') { + const local = env.LOCALAPPDATA || winPath(env.USERPROFILE || home, 'AppData', 'Local'); + return winPath(local, 'Strata'); + } + return posix.join(env.XDG_STATE_HOME || posix.join(env.HOME || '.', '.local', 'state'), 'strata'); +} + +const under = (root, platform, name) => (platform === 'win32' ? winPath(root, name) : posix.join(root, name)); + +export function tuningDir(env = process.env, platform = process.platform, home = homedir()) { + return env.STRATA_TUNE_DIR || under(stateRoot(env, platform, home), platform, 'tuning'); +} + +export function timeSkipDir(env = process.env, platform = process.platform, home = homedir()) { + return env.STRATA_TIMESKIP_DIR || under(stateRoot(env, platform, home), platform, 'time-skip'); +} + +function systemRoot(env) { + return env.SystemRoot || env.SYSTEMROOT || env.windir || 'C:\\Windows'; +} + +/** The archive tool: Windows 10+ ships bsdtar as System32\tar.exe (it reads .zip and .tar.*); POSIX has /usr/bin/tar. */ +export function tarBinary(env = process.env, platform = process.platform) { + return platform === 'win32' ? winPath(systemRoot(env), 'System32', 'tar.exe') : '/usr/bin/tar'; +} + +/** The command that prints where a program is on PATH. */ +export function whichCommand(binary, env = process.env, platform = process.platform) { + if (platform === 'win32') return { command: winPath(systemRoot(env), 'System32', 'where.exe'), args: [binary] }; + return { command: '/usr/bin/env', args: ['which', binary] }; +} diff --git a/apps/host/server/timeskip.mjs b/apps/host/server/timeskip.mjs index f156df23..1b8804ef 100644 --- a/apps/host/server/timeskip.mjs +++ b/apps/host/server/timeskip.mjs @@ -20,12 +20,11 @@ import { spawn } from 'node:child_process'; import { existsSync, readFileSync, readdirSync } from 'node:fs'; import { join } from 'node:path'; +import { timeSkipDir } from './platform-paths.mjs'; /** Where runs are recorded. Mirrors the CLI's own default resolution. */ function stateDir(env = process.env) { - if (env.STRATA_TIMESKIP_DIR) return env.STRATA_TIMESKIP_DIR; - const base = env.XDG_STATE_HOME || join(env.HOME || '.', '.local', 'state'); - return join(base, 'strata', 'time-skip'); + return timeSkipDir(env); } function readRun(root, id) { diff --git a/apps/host/server/util.mjs b/apps/host/server/util.mjs index 51eb7ca1..434d4ac0 100644 --- a/apps/host/server/util.mjs +++ b/apps/host/server/util.mjs @@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto'; import { execFile } from 'node:child_process'; import { promisify } from 'node:util'; +import { whichCommand } from './platform-paths.mjs'; export const exec = promisify(execFile); export const uid = (prefix = 'id') => `${prefix}_${randomUUID().slice(0, 8)}`; @@ -50,9 +51,11 @@ export async function probe(cmd, args = [], timeout = 4000) { } } -export async function which(binary) { - const out = await probe('/usr/bin/env', ['which', binary]); - return out || null; +/** Where `binary` is on PATH, or null. `/usr/bin/env which` on POSIX, System32\where.exe on Windows (first match). */ +export async function which(binary, { env = process.env, platform = process.platform, run = probe } = {}) { + const { command, args } = whichCommand(binary, env, platform); + const out = await run(command, args); + return out.split(/\r?\n/)[0].trim() || null; } /** Minimal SSE hub. */ diff --git a/apps/host/tests/platform-paths.test.mjs b/apps/host/tests/platform-paths.test.mjs new file mode 100644 index 00000000..e262a926 --- /dev/null +++ b/apps/host/tests/platform-paths.test.mjs @@ -0,0 +1,59 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { stateRoot, tuningDir, timeSkipDir, tarBinary, whichCommand } from '../server/platform-paths.mjs'; +import { which } from '../server/util.mjs'; + +const read = (rel) => readFileSync(fileURLToPath(new URL(rel, import.meta.url)), 'utf8'); + +test('Windows keeps tuning and Time-skip state under %LOCALAPPDATA%\\Strata, never HOME/.local/state', () => { + const env = { LOCALAPPDATA: 'C:\\Users\\me\\AppData\\Local', HOME: '/home/ignored', XDG_STATE_HOME: '/ignored' }; + assert.equal(stateRoot(env, 'win32'), 'C:\\Users\\me\\AppData\\Local\\Strata'); + assert.equal(tuningDir(env, 'win32'), 'C:\\Users\\me\\AppData\\Local\\Strata\\tuning'); + assert.equal(timeSkipDir(env, 'win32'), 'C:\\Users\\me\\AppData\\Local\\Strata\\time-skip'); +}); + +test('without LOCALAPPDATA, Windows falls back to the profile folder', () => { + assert.equal(stateRoot({ USERPROFILE: 'C:\\Users\\me' }, 'win32', 'C:\\Users\\other'), 'C:\\Users\\me\\AppData\\Local\\Strata'); + assert.equal(stateRoot({}, 'win32', 'C:\\Users\\other'), 'C:\\Users\\other\\AppData\\Local\\Strata'); +}); + +test('explicit directories win on every platform', () => { + assert.equal(tuningDir({ STRATA_TUNE_DIR: 'D:\\tune' }, 'win32'), 'D:\\tune'); + assert.equal(timeSkipDir({ STRATA_TIMESKIP_DIR: '/t/ts' }, 'linux'), '/t/ts'); +}); + +test('POSIX is unchanged: XDG_STATE_HOME, else ~/.local/state', () => { + assert.equal(stateRoot({ XDG_STATE_HOME: '/x' }, 'linux'), '/x/strata'); + assert.equal(tuningDir({ HOME: '/home/me' }, 'linux'), '/home/me/.local/state/strata/tuning'); + assert.equal(timeSkipDir({ HOME: '/home/me' }, 'darwin'), '/home/me/.local/state/strata/time-skip'); +}); + +test('the archive tool is the one the platform ships', () => { + assert.equal(tarBinary({ SystemRoot: 'C:\\Windows' }, 'win32'), 'C:\\Windows\\System32\\tar.exe'); + assert.equal(tarBinary({}, 'win32'), 'C:\\Windows\\System32\\tar.exe'); + assert.equal(tarBinary({}, 'linux'), '/usr/bin/tar'); + assert.equal(tarBinary({}, 'darwin'), '/usr/bin/tar'); +}); + +test('which asks where.exe on Windows (first match) and /usr/bin/env which elsewhere', async () => { + assert.deepEqual(whichCommand('llama-server', { SystemRoot: 'C:\\Windows' }, 'win32'), + { command: 'C:\\Windows\\System32\\where.exe', args: ['llama-server'] }); + assert.deepEqual(whichCommand('llama-server', {}, 'linux'), { command: '/usr/bin/env', args: ['which', 'llama-server'] }); + const seen = []; + const win = await which('cloudflared', { platform: 'win32', env: { SystemRoot: 'C:\\Windows' }, + run: async (command, args) => { seen.push([command, args]); return 'C:\\tools\\cloudflared.exe\r\nC:\\other\\cloudflared.exe'; } }); + assert.equal(win, 'C:\\tools\\cloudflared.exe'); + assert.deepEqual(seen[0], ['C:\\Windows\\System32\\where.exe', ['cloudflared']]); + assert.equal(await which('nothing', { platform: 'linux', run: async () => '' }), null); + assert.equal(await which('sh', { platform: 'linux', run: async () => '/usr/bin/sh' }), '/usr/bin/sh'); +}); + +test('the host no longer hard-codes /usr/bin/tar, /usr/bin/env or HOME/.local/state', () => { + assert.ok(!read('../server/engine-install.mjs').includes('/usr/bin/tar')); + assert.ok(!read('../server/util.mjs').includes("'/usr/bin/env'")); + assert.ok(!read('../server/timeskip.mjs').includes('.local')); + assert.ok(!read('../server/index.mjs').includes("'.local', 'state'")); + assert.match(read('../server/engine-install.mjs'), /tarBinary\(\)/); +}); diff --git a/strata_cli/cli.py b/strata_cli/cli.py index c0a486a4..b405aa62 100644 --- a/strata_cli/cli.py +++ b/strata_cli/cli.py @@ -305,7 +305,7 @@ def parser() -> argparse.ArgumentParser: "a fabricated improvement.") ts_run.add_argument("--state-dir", default=None, help="where runs are recorded (default: $STRATA_TIMESKIP_DIR or " - "$XDG_STATE_HOME/strata/time-skip)") + "$XDG_STATE_HOME/strata/time-skip, %%LOCALAPPDATA%%\\Strata\\time-skip on Windows)") ts_run.add_argument("--output", choices=("human", "json"), default="human") ts_status = timeskip_sp.add_parser("status", help="read a run's durable state and evidence") @@ -1131,8 +1131,8 @@ def _timeskip(a: argparse.Namespace) -> int: env = os.environ.get("STRATA_TIMESKIP_DIR") if env: return Path(env) - base = os.environ.get("XDG_STATE_HOME") or str(Path.home() / ".local" / "state") - return Path(base) / "strata" / "time-skip" + from strata_control.paths import state_base + return state_base() / "time-skip" store = time_skip.TimeSkipStore(state_root()) @@ -1287,8 +1287,8 @@ def _tune(a: argparse.Namespace) -> int: env = os.environ.get("STRATA_TUNE_DIR") if env: return Path(env) - base = os.environ.get("XDG_STATE_HOME") or str(Path.home() / ".local" / "state") - return Path(base) / "strata" / "tuning" + from strata_control.paths import state_base + return state_base() / "tuning" if a.tune_command == "list": root = state_root() diff --git a/strata_control/paths.py b/strata_control/paths.py new file mode 100644 index 00000000..db7b578f --- /dev/null +++ b/strata_control/paths.py @@ -0,0 +1,21 @@ +"""Per-user state locations, one rule for the terminal and the host. + +POSIX keeps $XDG_STATE_HOME (default ~/.local/state) under ``strata/``. Windows has no such place: state goes to +``%LOCALAPPDATA%\\Strata``. The Node host (apps/host/server/platform-paths.mjs) resolves the same folders. +""" + +from __future__ import annotations + +import os +from pathlib import Path + + +def state_base(environ=None, *, windows: bool | None = None, home: Path | None = None) -> Path: + """The folder that holds Strata's per-user state: runtime/, tuning/, time-skip/.""" + environ = os.environ if environ is None else environ + windows = os.name == "nt" if windows is None else windows + home = Path.home() if home is None else home + if windows: + local = environ.get("LOCALAPPDATA") or str(home / "AppData" / "Local") + return Path(local) / "Strata" + return Path(environ.get("XDG_STATE_HOME") or str(home / ".local" / "state")) / "strata" diff --git a/strata_control/runtime.py b/strata_control/runtime.py index bc2654f4..893df828 100644 --- a/strata_control/runtime.py +++ b/strata_control/runtime.py @@ -37,7 +37,7 @@ try: except ImportError: # Windows has no qualified owner transport yet. fcntl = None -from strata_control import owner_transport, private_files, profiles, readiness, winproc +from strata_control import owner_transport, paths, private_files, profiles, readiness, winproc from serve import launch_identity from strata_control.profiles import ProfileError @@ -102,10 +102,8 @@ def runtime_dir() -> Path: override = os.environ.get("STRATA_RUNTIME_DIR") if override: base = Path(override).expanduser() - elif WINDOWS: - base = Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData" / "Local") / "Strata" / "runtime" else: - base = Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local" / "state") / "strata" / "runtime" + base = paths.state_base() / "runtime" if not base.is_absolute(): raise ProfileError("STRATA_RUNTIME_DIR must be absolute") existed = base.exists() diff --git a/tests/terminal/test_state_paths.py b/tests/terminal/test_state_paths.py new file mode 100644 index 00000000..9c9122c7 --- /dev/null +++ b/tests/terminal/test_state_paths.py @@ -0,0 +1,47 @@ +"""Per-user state locations: %LOCALAPPDATA%\\Strata on Windows, $XDG_STATE_HOME/strata elsewhere.""" + +import os +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from strata_cli.cli import main +from strata_control import paths, runtime + + +class StatePaths(unittest.TestCase): + def test_windows_uses_localappdata(self): + env = {"LOCALAPPDATA": "C:\\Users\\me\\AppData\\Local", "XDG_STATE_HOME": "/ignored"} + self.assertEqual(paths.state_base(env, windows=True, home=Path("C:\\Users\\other")), + Path("C:\\Users\\me\\AppData\\Local") / "Strata") + + def test_windows_without_localappdata_falls_back_to_the_profile(self): + self.assertEqual(paths.state_base({}, windows=True, home=Path("C:\\Users\\me")), + Path("C:\\Users\\me") / "AppData" / "Local" / "Strata") + + def test_posix_is_unchanged(self): + self.assertEqual(paths.state_base({"XDG_STATE_HOME": "/x"}, windows=False), Path("/x") / "strata") + self.assertEqual(paths.state_base({}, windows=False, home=Path("/home/me")), + Path("/home/me") / ".local" / "state" / "strata") + + def test_runtime_dir_default_lives_under_the_state_base(self): + with tempfile.TemporaryDirectory() as d: + env = {"LOCALAPPDATA": d, "XDG_STATE_HOME": d} + with mock.patch.dict(os.environ, env): + os.environ.pop("STRATA_RUNTIME_DIR", None) + self.assertEqual(runtime.runtime_dir(), paths.state_base() / "runtime") + self.assertEqual(runtime.runtime_dir().parent.parent, Path(d)) + + def test_cli_defaults_for_tuning_and_timeskip_follow_the_same_base(self): + with tempfile.TemporaryDirectory() as d: + env = {"LOCALAPPDATA": d, "XDG_STATE_HOME": d} + with mock.patch.dict(os.environ, env): + for var in ("STRATA_TUNE_DIR", "STRATA_TIMESKIP_DIR"): + os.environ.pop(var, None) + self.assertEqual(main(["tune", "list", "--output", "json"]), 0) + self.assertEqual(main(["timeskip", "list", "--output", "json"]), 0) + + +if __name__ == "__main__": + unittest.main()