From dee0fead4b82f6515398f7e3c1284e15904418d9 Mon Sep 17 00:00:00 2001 From: rebuildup Date: Sun, 29 Nov 2026 21:07:28 +0900 Subject: [PATCH] feat(res): converge res observation config and agent plugins (#257) --- .github/workflows/ci.yml | 4 +- README.md | 28 ++++ mise.toml | 4 + script/bootstrap | 4 + script/res.test.ts | 150 +++++++++++++++++ script/res.ts | 337 +++++++++++++++++++++++++++++++++++++++ 6 files changed, 525 insertions(+), 2 deletions(-) create mode 100644 script/res.test.ts create mode 100644 script/res.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 94ac908..f834731 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -59,7 +59,7 @@ jobs: bun script/agent.ts models opencode-go > /dev/null bun script/agent.ts shortcuts > /dev/null - name: Test agent launcher (mock harnesses) - run: bun test script/agent.test.ts script/claude-settings.test.ts script/devices.test.ts + run: bun test script/agent.test.ts script/claude-settings.test.ts script/devices.test.ts script/res.test.ts - name: Test agent router modules run: bun test $(ls script/agent.*.test.ts script/agent/*.test.ts 2>/dev/null | grep -v windows) - name: Guard secret material @@ -78,7 +78,7 @@ jobs: - name: Validate agent launcher config (Windows) run: bun script/agent.ts check - name: Test Windows layers (batch shims, .cmd shortcuts, PowerShell wrapper) - run: bun test script/agent.test.ts script/agent.windows.test.ts script/agent.entrypoint.windows.test.ts script/devices.test.ts + run: bun test script/agent.test.ts script/agent.windows.test.ts script/agent.entrypoint.windows.test.ts script/devices.test.ts script/res.test.ts - name: Test Windows link adapter (adoption-first symlinks) run: bun test script/link.windows.test.ts - name: Parse-check PowerShell scripts diff --git a/README.md b/README.md index 6dbef2f..d41a78d 100644 --- a/README.md +++ b/README.md @@ -128,6 +128,7 @@ git submodule status --recursive │ ├── test-workflow # bootstrap / Infisical regression test │ ├── secrets-doctor # validate Infisical project access │ ├── with-secrets # process-scoped Infisical runtime injection +│ ├── res.ts # res observation config + agent plugin convergence │ └── check-secrets # reject secret material / legacy SOPS state in Git ├── docs/ │ ├── adr/ @@ -381,3 +382,30 @@ SSH公開鍵の失効ではない。失効は接続先のSSH認可を別途変 旧lockは稼働中devicesプロセスがないことを手動確認してからlockディレクトリだけを整理する。 Windowsの非管理SSH configや秘密鍵のACLは同期で変更しない。不適合は事前に エラーとし、所有者が必要な権限修正を別途行う。 + +### res (Device Resource Utility) の導入 + +`res` はデバイスのリソース観測 CLI(rebuildup/res)。バイナリ導入は +`pc-setup` の machine-global mise baseline(`cargo:device-resource-utility`)が所有し、 +dotfiles は `res` が PATH にあるデバイスだけを対象に収束させる。 + +```sh +bun script/res.ts sync # 手動同期(mise run res-sync でも同じ) +res doctor # 導入・scheduler・観測の健全性確認 +``` + +`script/bootstrap` 末尾でも自動実行される。`res` 非搭載のデバイスでは何もせず終了する。 +実行内容(すべて冪等): + +- `res doctor` が config / scheduler / DB の欠落を報告した場合のみ `res setup` を実行 +- `config.toml` の `[[inventory.roots]]` に、実在する canonical 候補 + (`~/src`、`~/Desktop`、`~/work`、各種 toolchain/cache、`~/AppData`、VM 領域)を追加。 + 既存 entry とユーザー追加分は保持し、存在しない path と他 root に包含される path は追加しない +- `[[ssh.hosts]]` に `~/.ssh/devices.conf`(devices sync 管理)の `device-*` alias を追加。 + `rex-*` は同一 endpoint のため対象外。probe は `echo ok`(cmd/PowerShell/sh 共通) +- 検出された agent runtime(claude / codex / opencode / pi)へ res plugin を install + +res の `config.toml` は device identity を含む per-device ファイルであり `home/` では配布しない。 +デバイス固有の追加 roots / hosts は machine-local overlay +`~/.config/dotfiles/res/observe.local.toml`(commit しない、`[[inventory.roots]]` / +`[[ssh.hosts]]` と同じブロック形式)へ記述する。 diff --git a/mise.toml b/mise.toml index 877b460..4c752d3 100644 --- a/mise.toml +++ b/mise.toml @@ -19,6 +19,10 @@ bunx skills@1.9.1 add rebuildup/aude-skills --skill \ --agent claude-code --agent codex -y """ +[tasks.res-sync] +description = "Converge res observation config and agent plugins on this device" +run = "bun script/res.ts sync" + [tasks.skills-update] description = "Update tracked project-local Agent Skills non-interactively" run = "bunx skills@1.9.1 update -p -y" diff --git a/script/bootstrap b/script/bootstrap index 5597bad..a4af458 100755 --- a/script/bootstrap +++ b/script/bootstrap @@ -354,4 +354,8 @@ fi "$repo_root/script/check-secrets" +# res (Device Resource Utility) convergence is per-device opt-in: the script +# exits quietly when res is not on PATH and never fails bootstrap. +bun "$repo_root/script/res.ts" sync + printf '\nbootstrap complete\n' diff --git a/script/res.test.ts b/script/res.test.ts new file mode 100644 index 0000000..37087e6 --- /dev/null +++ b/script/res.test.ts @@ -0,0 +1,150 @@ +import { describe, expect, test } from 'bun:test'; +import { platform } from 'node:os'; +import { join, resolve } from 'node:path'; +import { + deviceHostsFromSshConfig, + doctorProblems, + existingKeys, + mergeConfig, + parseOverlay, + selectInventoryRoots, +} from './res.ts'; + +const HOME = platform() === 'win32' ? 'C:\\home\\tester' : '/home/tester'; +const homePath = (...segs: string[]) => resolve(join(HOME, ...segs)); + +describe('selectInventoryRoots', () => { + test('keeps only existing directories and drops nested duplicates', () => { + const existing = new Set([ + homePath('src'), + homePath('AppData'), + homePath('AppData', 'Local', 'mise'), + ]); + const roots = selectInventoryRoots(HOME, [ + { path: '~/src', label: 'src' }, + { path: '~/Desktop', label: 'desktop' }, + { path: '~/AppData', label: 'appdata' }, + { path: '~/AppData/Local/mise', label: 'mise' }, + ], (p) => existing.has(p)); + expect(roots.map((r) => r.path)).toEqual(['~/src', '~/AppData']); + }); + + test('returns empty when nothing exists', () => { + expect(selectInventoryRoots(HOME, [{ path: '~/nope' }], () => false)).toEqual([]); + }); +}); + +describe('deviceHostsFromSshConfig', () => { + test('collects device-* aliases and excludes rex-* duplicates', () => { + const conf = [ + 'Host device-mac', + ' HostName 100.83.203.34', + 'Host rex-mac', + ' HostName 100.83.203.34', + 'Host device-windows device-wsl', + 'Host *', + ].join('\n'); + expect(deviceHostsFromSshConfig(conf)).toEqual(['device-mac', 'device-windows', 'device-wsl']); + }); +}); + +describe('mergeConfig', () => { + const base = [ + 'schema_version = 1', + '', + '[identity]', + 'device_id = "abc"', + '', + '[[inventory.roots]]', + 'path = "~/Desktop"', + 'label = "desktop"', + '', + '[[ssh.hosts]]', + 'host = "wsl-ubuntu"', + 'probe_command = "true"', + '', + ].join('\n'); + + test('appends missing entries and preserves existing content', () => { + const { text, added } = mergeConfig(base, [ + { kind: 'inventory.roots', path: '~/src', label: 'src' }, + { kind: 'inventory.roots', path: '~/Desktop', label: 'desktop' }, + { kind: 'ssh.hosts', host: 'device-mac', probe_command: 'echo ok' }, + { kind: 'ssh.hosts', host: 'wsl-ubuntu' }, + ], HOME); + expect(added).toHaveLength(2); + expect(text).toContain('device_id = "abc"'); + expect(text).toContain('path = "~/Desktop"'); + expect(text).toContain('[[inventory.roots]]\npath = "~/src"\nlabel = "src"'); + expect(text).toContain('[[ssh.hosts]]\nhost = "device-mac"\nprobe_command = "echo ok"'); + // existing wsl-ubuntu host not duplicated + expect(text.match(/host = "wsl-ubuntu"/g)).toHaveLength(1); + }); + + test('is idempotent on second merge', () => { + const once = mergeConfig(base, [ + { kind: 'inventory.roots', path: '~/src' }, + { kind: 'ssh.hosts', host: 'device-mac' }, + ], HOME); + const twice = mergeConfig(once.text, [ + { kind: 'inventory.roots', path: '~/src' }, + { kind: 'ssh.hosts', host: 'device-mac' }, + ], HOME); + expect(twice.added).toHaveLength(0); + expect(twice.text).toBe(once.text); + }); + + test('matches existing roots written as absolute paths', () => { + const abs = homePath('src'); + const cfg = `schema_version = 1\n\n[[inventory.roots]]\npath = "${abs}"\n`; + const { added } = mergeConfig(cfg, [{ kind: 'inventory.roots', path: '~/src' }], HOME); + expect(added).toHaveLength(0); + }); +}); + +describe('parseOverlay', () => { + test('parses inventory and ssh blocks', () => { + const frag = [ + '[[inventory.roots]]', + 'path = "D:/extra/projects"', + 'label = "extra"', + '', + '[[ssh.hosts]]', + 'host = "xserver"', + 'probe_command = "hostname"', + ].join('\n'); + expect(parseOverlay(frag)).toEqual([ + { kind: 'inventory.roots', path: 'D:/extra/projects', label: 'extra' }, + { kind: 'ssh.hosts', host: 'xserver', probe_command: 'hostname' }, + ]); + }); +}); + +describe('doctorProblems', () => { + test('reports non-ok checks', () => { + const json = JSON.stringify({ data: { checks: [ + { name: 'cli_version', status: 'ok' }, + { name: 'scheduler', status: 'missing' }, + ] } }); + expect(doctorProblems(json)).toEqual(['scheduler']); + }); + + test('tolerates malformed output', () => { + expect(doctorProblems('not json')).toEqual([]); + }); +}); + +describe('existingKeys', () => { + test('scopes keys to their section', () => { + const cfg = [ + '[[inventory.roots]]', + 'path = "~/a"', + '[[ssh.hosts]]', + 'host = "h1"', + '[[collection.system]]', + 'enabled = true', + ].join('\n'); + expect([...existingKeys(cfg, 'inventory.roots')]).toEqual(['~/a']); + expect([...existingKeys(cfg, 'ssh.hosts')]).toEqual(['h1']); + }); +}); diff --git a/script/res.ts b/script/res.ts new file mode 100644 index 0000000..b8f53a1 --- /dev/null +++ b/script/res.ts @@ -0,0 +1,337 @@ +#!/usr/bin/env bun +// res (Device Resource Utility) device convergence. +// +// Devices opt in simply by having `res` on PATH (installed via the +// machine-global mise baseline, rebuildup/pc-setup). For those devices this +// script converges, idempotently: +// 1. `res setup` when doctor reports missing config/scheduler registration +// 2. `[[inventory.roots]]` / `[[ssh.hosts]]` entries in res config.toml, +// merged without touching per-device identity or user additions +// 3. agent plugin installs for detected runtimes (claude/codex/opencode/pi) +// +// res config is per-device and never shipped through home/; this script only +// merges candidate entries into the live config. Device-specific extras belong +// in the machine-local overlay ~/.config/dotfiles/res/observe.local.toml +// (same block format, never committed). + +import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs'; +import { homedir, platform } from 'node:os'; +import { join, resolve, sep } from 'node:path'; + +export type DesiredEntry = + | { kind: 'inventory.roots'; path: string; label?: string } + | { kind: 'ssh.hosts'; host: string; probe_command?: string }; + +// Canonical inventory candidates, all ~ relative so they apply on every OS. +// Entries are filtered by existence at sync time and nested paths inside an +// already-selected root are dropped (res would otherwise count them twice). +const INVENTORY_CANDIDATES: { path: string; label?: string }[] = [ + // development checkouts + { path: '~/src', label: 'src' }, + { path: '~/Desktop', label: 'desktop' }, + { path: '~/work', label: 'work' }, + { path: '~/repos', label: 'repos' }, + { path: '~/dev', label: 'dev' }, + { path: '~/projects', label: 'projects' }, + { path: '~/code', label: 'code' }, + { path: '~/git', label: 'git' }, + // toolchains and package caches + { path: '~/.cargo', label: 'cargo' }, + { path: '~/.rustup', label: 'rustup' }, + { path: '~/.local/share/mise', label: 'mise' }, + { path: '~/.bun', label: 'bun' }, + { path: '~/.npm', label: 'npm-cache' }, + { path: '~/.cache', label: 'cache' }, + { path: '~/.deno', label: 'deno' }, + { path: '~/.nvm', label: 'nvm' }, + { path: '~/.pyenv', label: 'pyenv' }, + { path: '~/.local/share/pnpm', label: 'pnpm-store' }, + { path: '~/Library/Caches', label: 'library-caches' }, + // per-OS broad buckets validated on real devices (res#60: AppData surfaces + // the multi-GiB WSL vhdx as the largest artifact on Windows) + { path: '~/AppData', label: 'appdata' }, + // virtual disks / VM estates + { path: '~/VirtualBox VMs', label: 'virtualbox' }, + { path: '~/Documents/Virtual Machines.localized', label: 'vmware' }, + { path: '~/Parallels', label: 'parallels' }, + { path: '~/.vagrant.d', label: 'vagrant' }, + { path: '~/.lima', label: 'lima' }, + { path: '~/.colima', label: 'colima' }, +]; + +// `echo ok` exits 0 under cmd/PowerShell/sh alike, unlike `true` which only +// exists on POSIX remotes. Fleet aliases come from the dotfiles devices sync +// (~/.ssh/devices.conf, Infisical /devices); rex-* aliases point at the same +// endpoints and are deliberately excluded to avoid double probing. +const SSH_PROBE_COMMAND = 'echo ok'; + +const RUNTIMES: { bin: string; argv: string[][] }[] = [ + { bin: 'claude', argv: [ + ['plugin', 'marketplace', 'add', 'rebuildup/res'], + ['plugin', 'install', 'res@rebuildup'], + ]}, + { bin: 'codex', argv: [ + ['plugin', 'marketplace', 'add', 'rebuildup/res'], + ['plugin', 'add', 'res@rebuildup'], + ]}, + { bin: 'opencode', argv: [ + ['plugin', 'add', 'github:rebuildup/res#main::path:plugins/opencode'], + ]}, + { bin: 'pi', argv: [ + ['install', 'git:github.com/rebuildup/res'], + ]}, +]; + +function expandPath(p: string, home: string): string { + if (p === '~') return home; + if (p.startsWith('~/') || p.startsWith('~\\')) return join(home, p.slice(2)); + return p; +} + +function toResPath(p: string, home: string): string { + const expanded = resolve(expandPath(p, home)); + const homeResolved = resolve(home); + const relative = expanded.startsWith(homeResolved + sep) + ? expanded.slice(homeResolved.length + 1) + : null; + const display = relative !== null ? `~/${relative.split(sep).join('/')}` : expanded.split(sep).join('/'); + return display; +} + +function isDirectory(p: string): boolean { + try { + return statSync(p).isDirectory(); + } catch { + return false; + } +} + +export function selectInventoryRoots( + home: string, + candidates: { path: string; label?: string }[] = INVENTORY_CANDIDATES, + exists: (p: string) => boolean = (p) => isDirectory(p), +): { path: string; label?: string }[] { + const kept: { path: string; label?: string; resolved: string }[] = []; + const sorted = [...candidates].sort( + (a, b) => a.path.split(/[\\/]/).length - b.path.split(/[\\/]/).length, + ); + for (const c of sorted) { + const expanded = resolve(expandPath(c.path, home)); + if (!exists(expanded)) continue; + const nested = kept.some((k) => expanded === k.resolved || expanded.startsWith(k.resolved + sep)); + if (nested) continue; + kept.push({ path: c.path, label: c.label, resolved: expanded }); + } + return kept.map(({ path, label }) => ({ path, label })); +} + +export function deviceHostsFromSshConfig( + devicesConf: string, + rexPrefix = 'rex-', +): string[] { + const hosts = new Set(); + for (const line of devicesConf.split(/\r?\n/)) { + const m = line.match(/^\s*Host\s+(.+)$/); + if (!m) continue; + for (const alias of m[1].trim().split(/\s+/)) { + if (alias.startsWith('device-') && !alias.startsWith(rexPrefix)) hosts.add(alias); + } + } + return [...hosts].sort(); +} + +function tomlString(s: string): string { + return `"${s.replaceAll('\\', '/').replaceAll('"', '\\"')}"`; +} + +// Extracts keys already present in the config so merge never duplicates. +// `path` only appears under [[inventory.roots]] and `host` only under +// [[ssh.hosts]] in the res config schema, so a scoped scan is sufficient. +export function existingKeys(configText: string, section: 'inventory.roots' | 'ssh.hosts'): Set { + const keys = new Set(); + const header = `[[${section}]]`; + let inSection = false; + for (const line of configText.split(/\r?\n/)) { + const trimmed = line.trim(); + if (trimmed.startsWith('[[')) { + inSection = trimmed === header; + continue; + } + if (!inSection) continue; + const m = trimmed.match(/^(path|host)\s*=\s*"([^"]+)"/); + if (m) keys.add(m[2]); + } + return keys; +} + +function normalizeForCompare(p: string, home: string): string { + const resolved = resolve(expandPath(p, home)).replaceAll('\\', '/'); + return platform() === 'win32' ? resolved.toLowerCase() : resolved; +} + +export function mergeConfig( + configText: string, + desired: DesiredEntry[], + home: string, +): { text: string; added: DesiredEntry[] } { + const existingRoots = existingKeys(configText, 'inventory.roots'); + const existingHosts = existingKeys(configText, 'ssh.hosts'); + const existingRootNorm = new Set([...existingRoots].map((p) => normalizeForCompare(p, home))); + const added: DesiredEntry[] = []; + const blocks: string[] = []; + + for (const d of desired) { + if (d.kind === 'inventory.roots') { + const norm = normalizeForCompare(d.path, home); + if (existingRootNorm.has(norm) || existingRoots.has(d.path)) continue; + const label = d.label ? `\nlabel = ${tomlString(d.label)}` : ''; + blocks.push(`[[inventory.roots]]\npath = ${tomlString(toResPath(d.path, home))}${label}`); + added.push(d); + } else { + if (existingHosts.has(d.host)) continue; + const probe = d.probe_command ? `\nprobe_command = ${tomlString(d.probe_command)}` : ''; + blocks.push(`[[ssh.hosts]]\nhost = ${tomlString(d.host)}${probe}`); + added.push(d); + } + } + + if (blocks.length === 0) return { text: configText, added }; + const sep = configText.endsWith('\n') || configText === '' ? '' : '\n'; + return { text: `${configText}${sep}\n${blocks.join('\n\n')}\n`, added }; +} + +// Parses the machine-local overlay fragment (same [[...]] block format). +export function parseOverlay(fragment: string): DesiredEntry[] { + const entries: DesiredEntry[] = []; + let kind: 'inventory.roots' | 'ssh.hosts' | null = null; + let path = ''; + let label = ''; + let host = ''; + let probe = ''; + const flush = () => { + if (kind === 'inventory.roots' && path) entries.push({ kind, path, label: label || undefined }); + if (kind === 'ssh.hosts' && host) entries.push({ kind, host, probe_command: probe || undefined }); + path = label = host = probe = ''; + kind = null; + }; + for (const line of fragment.split(/\r?\n/)) { + const t = line.trim(); + if (t.startsWith('[[')) { + flush(); + if (t === '[[inventory.roots]]') kind = 'inventory.roots'; + else if (t === '[[ssh.hosts]]') kind = 'ssh.hosts'; + continue; + } + const m = t.match(/^(path|label|host|probe_command)\s*=\s*"([^"]*)"/); + if (!m || !kind) continue; + if (m[1] === 'path') path = m[2]; + else if (m[1] === 'label') label = m[2]; + else if (m[1] === 'host') host = m[2]; + else if (m[1] === 'probe_command') probe = m[2]; + } + flush(); + return entries; +} + +function which(bin: string): boolean { + const cmd = platform() === 'win32' ? 'where' : 'which'; + const p = Bun.spawnSync([cmd, bin], { stdout: 'pipe', stderr: 'pipe' }); + return p.exitCode === 0; +} + +function run(argv: string[]): { code: number; out: string } { + const p = Bun.spawnSync(argv, { stdout: 'pipe', stderr: 'pipe' }); + return { code: p.exitCode ?? 1, out: `${p.stdout.toString()}${p.stderr.toString()}`.trim() }; +} + +export function doctorProblems(jsonText: string): string[] { + try { + const doc = JSON.parse(jsonText); + const checks = doc?.data?.checks; + if (!Array.isArray(checks)) return []; + return checks.filter((c: { status?: string }) => c.status !== 'ok').map((c: { name?: string }) => c.name ?? '?'); + } catch { + return []; + } +} + +function resConfigPath(home: string, env: Record): string { + if (platform() === 'win32') { + return join(env.APPDATA ?? join(home, 'AppData', 'Roaming'), 'res', 'config.toml'); + } + return join(env.XDG_CONFIG_HOME ?? join(home, '.config'), 'res', 'config.toml'); +} + +export function sync(home: string = homedir(), log: (msg: string) => void = console.log): void { + if (!which('res')) { + log('res: not on PATH; skipping (device opt-in via pc-setup mise baseline)'); + return; + } + + // 1. setup: idempotent; only needed when doctor reports missing pieces. + const doctor = run(['res', 'doctor', '--json']); + if (doctor.code !== 0) { + log(`res: doctor failed (${doctor.out.split('\n')[0] ?? 'unknown'}); attempting res setup`); + } + const problems = doctorProblems(doctor.out); + const needsSetup = problems.some((p) => ['config', 'scheduler', 'db_usable'].includes(p)); + if (needsSetup || !existsSync(resConfigPath(home, process.env))) { + const r = run(['res', 'setup']); + log(`res: setup -> exit ${r.code}${r.code === 0 ? '' : ` (${r.out.split('\n')[0]})`}`); + } + + const configPath = resConfigPath(home, process.env); + if (!existsSync(configPath)) { + log(`res: config not found at ${configPath}; skipping observation merge`); + return; + } + + // 2. observation config merge + let devicesConf = ''; + try { + devicesConf = readFileSync(join(home, '.ssh', 'devices.conf'), 'utf8'); + } catch { + // devices sync has not run on this device; ssh.hosts stay empty unless the + // machine-local overlay provides them. + } + const desired: DesiredEntry[] = [ + ...selectInventoryRoots(home).map((r) => ({ kind: 'inventory.roots' as const, path: r.path, label: r.label })), + ...deviceHostsFromSshConfig(devicesConf) + .map((host) => ({ kind: 'ssh.hosts' as const, host, probe_command: SSH_PROBE_COMMAND })), + ]; + + const overlayPath = join(home, '.config', 'dotfiles', 'res', 'observe.local.toml'); + if (existsSync(overlayPath)) { + desired.push(...parseOverlay(readFileSync(overlayPath, 'utf8'))); + } + + if (desired.length > 0) { + const current = readFileSync(configPath, 'utf8'); + const { text, added } = mergeConfig(current, desired, home); + if (added.length > 0) { + writeFileSync(configPath, text); + log(`res: config merged +${added.length} entr${added.length === 1 ? 'y' : 'ies'} (${configPath})`); + } else { + log('res: observation config already converged'); + } + } + + // 3. agent plugin installs (per-runtime, fail-open) + for (const rt of RUNTIMES) { + if (!which(rt.bin)) continue; + for (const args of rt.argv) { + const r = run([rt.bin, ...args]); + const first = r.out.split('\n')[0] ?? ''; + log(`res: ${rt.bin} ${args.join(' ')} -> exit ${r.code}${r.code === 0 ? '' : ` (${first.slice(0, 120)})`}`); + } + } +} + +if (import.meta.main) { + try { + sync(); + } catch (e) { + // Convergence must never break bootstrap; report and exit 0. + console.log(`res: sync skipped (${e instanceof Error ? e.message : e})`); + } +}