Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.
Shell agent-teamsai-agentai-automationanthropicautonomous-agentawsbusiness-operationsclaudeclaude-codeclaude-code-plugindevopsecommerceinbox-zeroklaviyomarketingmcpmorning-briefingpr-automationshopifyterminal
feat(cross-os): foundation — os-detect + credential-store helpers + CI matrix
Claudefb32d4e1350d
diff --git a/claude-ops/.github/workflows/cross-os.yml b/claude-ops/.github/workflows/cross-os.ymlnew file mode 100644index 00000000..2b9c1251--- /dev/null+++ b/claude-ops/.github/workflows/cross-os.yml@@ -0,0 +1,122 @@+name: Cross-OS++# Exercise claude-ops cross-OS helpers (lib/os-detect.*, lib/credential-store.*)+# across Linux, macOS, and Windows to catch portability regressions early.++on:+ push:+ branches: ['**']+ pull_request:+ branches: [main, dev]++# Cancel in-flight runs on the same ref when a new push arrives.+concurrency:+ group: cross-os-${{ github.ref }}+ cancel-in-progress: true++jobs:+ lint-and-probe:+ name: lint-and-probe (${{ matrix.os }} / ${{ matrix.runtime }})+ runs-on: ${{ matrix.os }}+ strategy:+ fail-fast: false+ matrix:+ os: [ubuntu-latest, macos-latest, windows-latest]+ runtime: [bash, node]+ # Route every `run:` step through bash. On windows-latest this resolves to+ # Git Bash, which GitHub Actions provisions automatically.+ defaults:+ run:+ shell: bash+ steps:+ - uses: actions/checkout@v4++ # Node 22 is used for both the node matrix leg and the `node --check`+ # syntax validation performed in every leg. No cache: no package-lock.json+ # at the repo root (telegram-server has its own, but that is out of scope).+ - uses: actions/setup-node@v4+ with:+ node-version: '22'++ # --- OS-native keyring setup -------------------------------------------++ # Ubuntu: install libsecret CLI + gnome-keyring, then bring up a dbus+ # session and unlock an empty keyring so credential-store can round-trip.+ # gnome-keyring on headless CI is known to be flaky; continue-on-error+ # keeps the job green and downstream steps can detect its absence.+ - name: Install keyring (Ubuntu)+ if: runner.os == 'Linux'+ continue-on-error: true+ run: |+ sudo apt-get update+ sudo apt-get install -y libsecret-tools gnome-keyring dbus-x11+ eval "$(dbus-launch --sh-syntax)"+ echo -n '' | gnome-keyring-daemon --components=secrets --daemonize --unlock || true++ # macOS: `security` is built in. Unlocking the login keychain with an+ # empty password mirrors the default CI image state; tolerate failure.+ - name: Unlock login keychain (macOS)+ if: runner.os == 'macOS'+ continue-on-error: true+ run: security unlock-keychain -p "" login.keychain++ # Windows: cmdkey ships with Windows itself, so there is nothing to+ # install. Step left here as a documented no-op for future contributors.+ - name: Keyring setup (Windows)+ if: runner.os == 'Windows'+ run: echo "cmdkey is built into Windows; no install required"++ # --- Probes ------------------------------------------------------------++ - name: Probe os-detect.sh+ run: |+ bash lib/os-detect.sh+ echo "---"+ bash lib/os-detect.sh | head -c 2048++ - name: Probe os-detect.mjs+ run: |+ node lib/os-detect.mjs+ echo "---"+ node lib/os-detect.mjs | head -c 2048++ # Smoke tests are authored in a parallel PR; guard so this workflow is+ # green before tests/lib/smoke.sh lands.+ - name: Smoke tests+ run: |+ if [ -f tests/lib/smoke.sh ]; then+ bash tests/lib/smoke.sh+ else+ echo "tests/lib/smoke.sh not present yet; skipping"+ fi++ # --- Syntax validation -------------------------------------------------++ - name: node --check credential-store.mjs+ run: node --check lib/credential-store.mjs++ - name: bash -n credential-store.sh+ run: bash -n lib/credential-store.sh++ # --- shellcheck (best-effort) -----------------------------------------++ - name: Install shellcheck (Ubuntu)+ if: runner.os == 'Linux'+ continue-on-error: true+ run: sudo apt-get install -y shellcheck++ - name: Install shellcheck (macOS)+ if: runner.os == 'macOS'+ continue-on-error: true+ run: brew install shellcheck++ # Windows has no first-class shellcheck path we want to maintain; skip.+ - name: Run shellcheck+ if: runner.os != 'Windows'+ continue-on-error: true+ run: |+ if command -v shellcheck >/dev/null 2>&1; then+ shellcheck lib/*.sh+ else+ echo "shellcheck not available; skipping"+ fidiff --git a/claude-ops/lib/credential-store.mjs b/claude-ops/lib/credential-store.mjsnew file mode 100644index 00000000..79574522--- /dev/null+++ b/claude-ops/lib/credential-store.mjs@@ -0,0 +1,454 @@+// lib/credential-store.mjs — cascading cross-OS credential store (Node ESM).+// Mirrors the bash helper lib/credential-store.sh.+//+// Cascade (in priority order):+// 1. OS-native keyring — macOS `security`, Linux `secret-tool`, Windows `cmdkey`+// 2. keytar (dynamically imported if installed)+// 3. Encrypted JSON — AES-256-GCM via node:crypto+// 4. Plaintext JSON — 0600 perms, last-resort fallback with warning+//+// API:+// import { setCredential, getCredential, deleteCredential,+// backendsAvailable, backendFor } from './lib/credential-store.mjs';+//+// Override the cascade in tests:+// CLAUDE_OPS_CRED_BACKEND=plaintext-json node ...++import { spawnSync, spawn } from 'node:child_process';+import { promises as fs, constants as fsConst } from 'node:fs';+import path from 'node:path';+import os from 'node:os';+import crypto from 'node:crypto';+import { fileURLToPath } from 'node:url';++import { osId, keyringBackend } from './os-detect.mjs';++// ─── Paths ───────────────────────────────────────────────────────────────────+const DATA_DIR = process.env.XDG_DATA_HOME+ ? path.join(process.env.XDG_DATA_HOME, 'claude-ops')+ : path.join(os.homedir(), '.local', 'share', 'claude-ops');+const ENC_FILE = path.join(DATA_DIR, 'secrets.enc.json');+const PLAIN_FILE = path.join(DATA_DIR, 'secrets.plain.json');+const MASTERKEY_FILE = path.join(DATA_DIR, '.masterkey');++let __plaintextWarned = false;++const log = (...args) => console.error('credential-store:', ...args);++async function ensureDataDir() {+ await fs.mkdir(DATA_DIR, { recursive: true, mode: 0o700 });+}++// ─── 1. OS-native backends ───────────────────────────────────────────────────++function runSync(cmd, args, opts = {}) {+ return spawnSync(cmd, args, { encoding: 'utf8', ...opts });+}++// --- macOS Keychain (security) ---+function macSet(service, account, secret) {+ const r = runSync('security', ['add-generic-password', '-U', '-s', service, '-a', account, '-w', secret]);+ return r.status === 0;+}+function macGet(service, account) {+ const r = runSync('security', ['find-generic-password', '-s', service, '-a', account, '-w']);+ if (r.status === 0) return (r.stdout || '').replace(/\n$/, '');+ // exit 44 means "not found" — treat as normal+ return null;+}+function macDelete(service, account) {+ runSync('security', ['delete-generic-password', '-s', service, '-a', account]);+ return true;+}++// --- Linux libsecret (secret-tool) ---+function hasSecretTool() {+ return runSync('sh', ['-c', 'command -v secret-tool']).status === 0;+}+function stSet(service, account, secret) {+ if (!hasSecretTool()) return false;+ const r = spawnSync('secret-tool',+ ['store', '--label=' + service + '/' + account, 'service', service, 'account', account],+ { input: secret, encoding: 'utf8' }+ );+ return r.status === 0;+}+function stGet(service, account) {+ if (!hasSecretTool()) return null;+ const r = runSync('secret-tool', ['lookup', 'service', service, 'account', account]);+ if (r.status === 0 && r.stdout) return r.stdout.replace(/\n$/, '');+ return null;+}+function stDelete(service, account) {+ if (!hasSecretTool()) return true;+ runSync('secret-tool', ['clear', 'service', service, 'account', account]);+ return true;+}++// --- Windows Credential Manager (cmdkey — write-only from CLI) ---+function hasCmd() {+ return runSync('sh', ['-c', 'command -v cmd.exe || which cmd.exe']).status === 0+ || process.platform === 'win32';+}+function wincredSet(service, account, secret) {+ if (!hasCmd()) return false;+ // Windows: direct invocation; elsewhere: through cmd.exe //c+ if (process.platform === 'win32') {+ const r = runSync('cmdkey',+ ['/generic:claude-ops:' + service + ':' + account, '/user:' + account, '/pass:' + secret]);+ return r.status === 0;+ }+ // MSYS/WSL path — shell through cmd.exe+ const r = runSync('cmd.exe',+ ['/c', 'cmdkey /generic:claude-ops:' + service + ':' + account ++ ' /user:' + account + ' /pass:' + secret]);+ return r.status === 0;+}+function wincredGet(_service, _account) {+ // cmdkey cannot read passwords back from the CLI — skip+ return null;+}+function wincredDelete(service, account) {+ if (!hasCmd()) return true;+ if (process.platform === 'win32') {+ runSync('cmdkey', ['/delete:claude-ops:' + service + ':' + account]);+ } else {+ runSync('cmd.exe', ['/c', 'cmdkey /delete:claude-ops:' + service + ':' + account]);+ }+ return true;+}++function nativeBackend() {+ // Prefer os-detect's answer but fall back to process.platform heuristics+ const b = keyringBackend();+ if (b) return b;+ if (process.platform === 'darwin') return 'security';+ if (process.platform === 'linux' && hasSecretTool()) return 'secret-tool';+ if (process.platform === 'win32') return 'wincred';+ return null;+}++// ─── 2. keytar (optional) ────────────────────────────────────────────────────+let __keytarCache;+async function loadKeytar() {+ if (__keytarCache !== undefined) return __keytarCache;+ try {+ const mod = await import('keytar');+ __keytarCache = mod.default || mod;+ } catch {+ __keytarCache = null;+ }+ return __keytarCache;+}+async function keytarSet(service, account, secret) {+ const k = await loadKeytar();+ if (!k) return false;+ try { await k.setPassword(service, account, secret); return true; } catch { return false; }+}+async function keytarGet(service, account) {+ const k = await loadKeytar();+ if (!k) return null;+ try { return await k.getPassword(service, account); } catch { return null; }+}+async function keytarDelete(service, account) {+ const k = await loadKeytar();+ if (!k) return true;+ try { await k.deletePassword(service, account); } catch { /* ignore */ }+ return true;+}++// ─── 3. Encrypted JSON (AES-256-GCM) ─────────────────────────────────────────+async function masterKey() {+ if (process.env.CLAUDE_OPS_MASTER_KEY) return process.env.CLAUDE_OPS_MASTER_KEY;+ await ensureDataDir();+ try {+ return (await fs.readFile(MASTERKEY_FILE, 'utf8')).trim();+ } catch {+ const key = crypto.randomBytes(32).toString('base64');+ await fs.writeFile(MASTERKEY_FILE, key, { mode: 0o600 });+ return key;+ }+}++async function readJson(file) {+ try {+ const raw = await fs.readFile(file, 'utf8');+ return JSON.parse(raw);+ } catch (e) {+ if (e.code === 'ENOENT') return {};+ throw e;+ }+}++async function writeJson(file, obj) {+ await ensureDataDir();+ const tmp = file + '.tmp.' + process.pid;+ await fs.writeFile(tmp, JSON.stringify(obj, null, 2), { mode: 0o600 });+ await fs.rename(tmp, file);+ await fs.chmod(file, 0o600);+}++function encrypt(plaintext, keyB64) {+ const salt = crypto.randomBytes(16);+ const iv = crypto.randomBytes(12);+ const key = crypto.scryptSync(keyB64, salt, 32);+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);+ const ct = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);+ const tag = cipher.getAuthTag();+ return {+ iv: iv.toString('base64'),+ salt: salt.toString('base64'),+ tag: tag.toString('base64'),+ ct: ct.toString('base64'),+ };+}++function decrypt(entry, keyB64) {+ try {+ const salt = Buffer.from(entry.salt, 'base64');+ const iv = Buffer.from(entry.iv, 'base64');+ const tag = Buffer.from(entry.tag, 'base64');+ const ct = Buffer.from(entry.ct, 'base64');+ const key = crypto.scryptSync(keyB64, salt, 32);+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);+ decipher.setAuthTag(tag);+ const pt = Buffer.concat([decipher.update(ct), decipher.final()]);+ return pt.toString('utf8');+ } catch {+ return null;+ }+}++async function encJsonSet(service, account, secret) {+ const k = await masterKey();+ const entry = encrypt(secret, k);+ entry.service = service;+ entry.account = account;+ const store = await readJson(ENC_FILE);+ store[service + '/' + account] = entry;+ await writeJson(ENC_FILE, store);+ return true;+}+async function encJsonGet(service, account) {+ const key = service + '/' + account;+ const store = await readJson(ENC_FILE);+ if (!store[key]) return null;+ const k = await masterKey();+ const pt = decrypt(store[key], k);+ if (pt === null) log('decrypt failed for enc-json/' + key);+ return pt;+}+async function encJsonDelete(service, account) {+ const key = service + '/' + account;+ const store = await readJson(ENC_FILE);+ if (store[key]) {+ delete store[key];+ await writeJson(ENC_FILE, store);+ }+ return true;+}++// ─── 4. Plaintext JSON fallback ──────────────────────────────────────────────+function plaintextWarnOnce() {+ if (__plaintextWarned) return;+ __plaintextWarned = true;+ log('⚠ using plaintext JSON fallback — install secret-tool (linux) or cmdkey (windows) for better security');+}+async function plainSet(service, account, secret) {+ plaintextWarnOnce();+ const store = await readJson(PLAIN_FILE);+ store[service + '/' + account] = secret;+ await writeJson(PLAIN_FILE, store);+ return true;+}+async function plainGet(service, account) {+ const store = await readJson(PLAIN_FILE);+ return store[service + '/' + account] ?? null;+}+async function plainDelete(service, account) {+ const store = await readJson(PLAIN_FILE);+ const key = service + '/' + account;+ if (store[key]) {+ delete store[key];+ await writeJson(PLAIN_FILE, store);+ }+ return true;+}++// ─── Public API ──────────────────────────────────────────────────────────────++/**+ * List backends available on this host in priority order.+ * @returns {Promise<string[]>}+ */+export async function backendsAvailable() {+ const backends = [];+ const nb = nativeBackend();+ if (nb) backends.push(nb);+ if (await loadKeytar()) backends.push('keytar');+ backends.push('enc-json');+ backends.push('plaintext-json');+ return backends;+}++/**+ * Store a secret via the cascade. Honors CLAUDE_OPS_CRED_BACKEND override.+ * @returns {Promise<{backend: string, ok: boolean}>}+ */+export async function setCredential(service, account, secret) {+ const forced = process.env.CLAUDE_OPS_CRED_BACKEND;+ const tryBackend = async (name) => {+ let ok = false;+ switch (name) {+ case 'security': ok = macSet(service, account, secret); break;+ case 'secret-tool': ok = stSet(service, account, secret); break;+ case 'wincred': ok = wincredSet(service, account, secret); break;+ case 'keytar': ok = await keytarSet(service, account, secret); break;+ case 'enc-json': ok = await encJsonSet(service, account, secret); break;+ case 'plaintext-json': ok = await plainSet(service, account, secret); break;+ }+ if (ok) log('stored via=' + name);+ return ok;+ };++ if (forced) {+ const ok = await tryBackend(forced);+ if (!ok) log('forced backend=' + forced + ' failed');+ return { backend: forced, ok };+ }++ const cascade = [];+ const nb = nativeBackend();+ if (nb) cascade.push(nb);+ cascade.push('keytar', 'enc-json', 'plaintext-json');+ for (const name of cascade) {+ if (await tryBackend(name)) return { backend: name, ok: true };+ }+ log('all backends failed');+ return { backend: null, ok: false };+}++/**+ * Retrieve a secret. Cascades through backends.+ * @returns {Promise<{backend: string, secret: string} | null>}+ */+export async function getCredential(service, account) {+ const forced = process.env.CLAUDE_OPS_CRED_BACKEND;+ const tryBackend = async (name) => {+ let v = null;+ switch (name) {+ case 'security': v = macGet(service, account); break;+ case 'secret-tool': v = stGet(service, account); break;+ case 'wincred': v = wincredGet(service, account); break;+ case 'keytar': v = await keytarGet(service, account); break;+ case 'enc-json': v = await encJsonGet(service, account); break;+ case 'plaintext-json': v = await plainGet(service, account); break;+ }+ return v == null ? null : { backend: name, secret: v };+ };++ if (forced) return await tryBackend(forced);++ const cascade = [];+ const nb = nativeBackend();+ if (nb) cascade.push(nb);+ cascade.push('keytar', 'enc-json', 'plaintext-json');+ for (const name of cascade) {+ const hit = await tryBackend(name);+ if (hit) return hit;+ }+ return null;+}++/**+ * Delete a secret from all backends (best-effort).+ * @returns {Promise<{deletedFrom: string[]}>}+ */+export async function deleteCredential(service, account) {+ const deletedFrom = [];+ const nb = nativeBackend();+ try {+ if (nb === 'security') { macDelete(service, account); deletedFrom.push('security'); }+ if (nb === 'secret-tool') { stDelete(service, account); deletedFrom.push('secret-tool'); }+ if (nb === 'wincred') { wincredDelete(service, account); deletedFrom.push('wincred'); }+ } catch { /* ignore */ }+ try { await keytarDelete(service, account); deletedFrom.push('keytar'); } catch { /* ignore */ }+ try { await encJsonDelete(service, account); deletedFrom.push('enc-json'); } catch { /* ignore */ }+ try { await plainDelete(service, account); deletedFrom.push('plaintext-json'); } catch { /* ignore */ }+ return { deletedFrom };+}++/**+ * Which backend currently holds this credential?+ * @returns {Promise<string | null>}+ */+export async function backendFor(service, account) {+ const hit = await getCredential(service, account);+ return hit ? hit.backend : null;+}++// ─── CLI entry ───────────────────────────────────────────────────────────────+const isCli = import.meta.url === `file://${process.argv[1]}`;+if (isCli) {+ const [, , sub, ...rest] = process.argv;+ const dispatch = async () => {+ switch (sub) {+ case 'set': {+ const [service, account, secret] = rest;+ const r = await setCredential(service, account, secret);+ process.exit(r.ok ? 0 : 1);+ }+ case 'get': {+ const [service, account] = rest;+ const r = await getCredential(service, account);+ if (!r) process.exit(1);+ process.stdout.write(r.secret);+ process.exit(0);+ }+ case 'delete': {+ const [service, account] = rest;+ await deleteCredential(service, account);+ process.exit(0);+ }+ case 'backends': {+ const r = await backendsAvailable();+ process.stdout.write(r.join(' ') + '\n');+ process.exit(0);+ }+ case 'backend-for': {+ const [service, account] = rest;+ const r = await backendFor(service, account);+ if (!r) process.exit(1);+ process.stdout.write(r + '\n');+ process.exit(0);+ }+ // Helpers called by lib/credential-store.sh+ case 'set-keytar': {+ const [service, account, secret] = rest;+ const ok = await keytarSet(service, account, secret);+ process.exit(ok ? 0 : 1);+ }+ case 'get-keytar': {+ const [service, account] = rest;+ const v = await keytarGet(service, account);+ if (v == null) process.exit(1);+ process.stdout.write(v);+ process.exit(0);+ }+ case 'delete-keytar': {+ const [service, account] = rest;+ await keytarDelete(service, account);+ process.exit(0);+ }+ default: {+ process.stderr.write(+ 'usage: credential-store.mjs {set|get|delete|backends|backend-for|set-keytar|get-keytar|delete-keytar} ...\n'+ );+ process.exit(2);+ }+ }+ };+ dispatch().catch((e) => { log('fatal:', e.message); process.exit(1); });+}++export default { setCredential, getCredential, deleteCredential, backendsAvailable, backendFor };diff --git a/claude-ops/lib/credential-store.sh b/claude-ops/lib/credential-store.shnew file mode 100755index 00000000..1fd14ea7--- /dev/null+++ b/claude-ops/lib/credential-store.sh@@ -0,0 +1,617 @@+#!/usr/bin/env bash+# credential-store.sh — Cross-OS secret storage with a cascading backend chain.+#+# This file is a SOURCED library, not a standalone executable. The shebang+# above exists purely so editors pick the right syntax highlighter. Source+# it from other scripts via:+# source "$(dirname "$0")/../lib/credential-store.sh"+#+# It abstracts credential storage across OSes so that callers never have to+# care whether the host has macOS Keychain, libsecret, Windows Credential+# Manager, keytar, or nothing at all. The same API works everywhere; backends+# are tried in priority order and the first that succeeds wins.+#+# Public API (all idempotent, all return 0/1 without leaking secrets to logs):+# ops_cred_set <service> <account> <secret>+# ops_cred_get <service> <account>+# ops_cred_delete <service> <account>+# ops_cred_backends_available+# ops_cred_backend_for <service> <account>+#+# Direct-execution CLI (for the .mjs helper to shell out to):+# credential-store.sh set|get|delete|backends|backend-for ...++# ─── Re-source guard ────────────────────────────────────────────────────────+if [[ -n "${__OPS_CREDENTIAL_STORE_SH_LOADED__:-}" ]]; then+ return 0 2>/dev/null || exit 0+fi+__OPS_CREDENTIAL_STORE_SH_LOADED__=1++# Only clobber shell options when run directly; sourced callers keep their own.+if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then+ set -euo pipefail+fi++# ─── Dependency: os-detect.sh ───────────────────────────────────────────────+if ! declare -F ops_keyring_backend >/dev/null 2>&1; then+ # shellcheck source=./os-detect.sh+ . "$(dirname "${BASH_SOURCE[0]}")/os-detect.sh"+fi++# ─── Paths & constants ──────────────────────────────────────────────────────+__OPS_CRED_DATA_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/claude-ops"+__OPS_CRED_ENC_FILE="$__OPS_CRED_DATA_DIR/secrets.enc.json"+__OPS_CRED_PLAIN_FILE="$__OPS_CRED_DATA_DIR/secrets.plain.json"+__OPS_CRED_MASTERKEY_FILE="$__OPS_CRED_DATA_DIR/.masterkey"+__OPS_CRED_MJS_HELPER="$(dirname "${BASH_SOURCE[0]}")/credential-store.mjs"+__OPS_CRED_WIN_PREFIX="claude-ops"+__OPS_CRED_PLAIN_WARNED=0++# ─── 1. Logging helpers ─────────────────────────────────────────────────────+# Never echoes the secret itself — only backend names and service/account.+_ops_cred_log() {+ printf 'credential-store: %s\n' "$*" >&2+}++_ops_cred_warn_plaintext_once() {+ if [[ "$__OPS_CRED_PLAIN_WARNED" == "0" ]]; then+ printf '⚠ credential-store: using plaintext JSON fallback — install secret-tool (linux) or cmdkey (windows) for better security\n' >&2+ __OPS_CRED_PLAIN_WARNED=1+ fi+}++# ─── 2. JSON helpers (jq-optional) ──────────────────────────────────────────+# Flat shape: {"service_account": {"service":"...", "account":"...", "secret":"..."}}+_ops_cred_json_escape() {+ local s="$1"+ s="${s//\\/\\\\}"+ s="${s//\"/\\\"}"+ s="${s//$'\n'/\\n}"+ s="${s//$'\r'/\\r}"+ s="${s//$'\t'/\\t}"+ printf '%s' "$s"+}++_ops_cred_key() { printf '%s\x1f%s' "$1" "$2"; }+_ops_cred_jkey() {+ # JSON-safe composite key: "service\u001faccount" collapsed to service_account.+ local svc acc+ svc="$(_ops_cred_json_escape "$1")"+ acc="$(_ops_cred_json_escape "$2")"+ printf '%s__%s' "$svc" "$acc"+}++# Reads field from a flat JSON blob on stdin. Writes value to stdout or empty.+# _ops_cred_json_get <json> <key> <field>+_ops_cred_json_get() {+ local blob="$1" key="$2" field="$3"+ if command -v jq >/dev/null 2>&1; then+ printf '%s' "$blob" | jq -r --arg k "$key" --arg f "$field" \+ '.[$k][$f] // empty' 2>/dev/null+ return 0+ fi+ # Hand-rolled: match "key":{ ... "field":"value" ... }+ # This parser is deliberately tolerant but assumes we wrote the file ourselves.+ local esc_key esc_field+ esc_key="$(_ops_cred_json_escape "$key")"+ esc_field="$(_ops_cred_json_escape "$field")"+ local py+ py="$(printf '%s' "$blob" | awk -v k="$esc_key" -v f="$esc_field" '+ BEGIN { RS="\0" }+ {+ # Find "k":{...}+ idx = index($0, "\"" k "\":{")+ if (!idx) exit 0+ rest = substr($0, idx)+ # Find enclosing object end — naive: first } after the opening {+ brace = index(rest, "{")+ if (!brace) exit 0+ obj_start = brace + 1+ depth = 1+ i = obj_start + 1+ n = length(rest)+ while (i <= n && depth > 0) {+ c = substr(rest, i, 1)+ if (c == "{") depth+++ else if (c == "}") depth--+ i+++ }+ obj = substr(rest, obj_start, i - obj_start - 1)+ fidx = index(obj, "\"" f "\":\"")+ if (!fidx) exit 0+ val_start = fidx + length(f) + 4+ # Read until unescaped quote.+ out = ""+ j = val_start+ m = length(obj)+ while (j <= m) {+ c = substr(obj, j, 1)+ if (c == "\\") { out = out substr(obj, j, 2); j += 2; continue }+ if (c == "\"") break+ out = out c; j+++ }+ print out+ }')"+ # Unescape minimal sequences we wrote.+ py="${py//\\n/$'\n'}"+ py="${py//\\r/$'\r'}"+ py="${py//\\t/$'\t'}"+ py="${py//\\\"/\"}"+ py="${py//\\\\/\\}"+ printf '%s' "$py"+}++# Writes a single entry into a flat JSON blob on stdin, emitting the updated+# blob on stdout. If `secret` is empty, deletes the key.+# _ops_cred_json_set <blob> <key> <service> <account> <secret>+_ops_cred_json_set() {+ local blob="${1:-}" key="$2" svc="$3" acc="$4" sec="$5"+ [[ -z "$blob" ]] && blob='{}'+ if command -v jq >/dev/null 2>&1; then+ if [[ -z "$sec" ]]; then+ printf '%s' "$blob" | jq --arg k "$key" 'del(.[$k])'+ else+ printf '%s' "$blob" | jq --arg k "$key" --arg s "$svc" \+ --arg a "$acc" --arg v "$sec" \+ '.[$k] = {service:$s, account:$a, secret:$v}'+ fi+ return 0+ fi+ # Hand-rolled: collect existing keys by scanning top-level entries, then+ # reassemble. Because we always round-trip through this writer, the shape+ # is predictable.+ local -a pairs=()+ if command -v jq >/dev/null 2>&1; then :; fi+ # Extract existing keys via a crude tokenizer.+ local keys_line+ keys_line="$(printf '%s' "$blob" | tr -d '\n' | grep -oE '"[^"]+":\{[^}]*\}' || true)"+ local entry ekey existing_svc existing_acc existing_sec+ while IFS= read -r entry; do+ [[ -z "$entry" ]] && continue+ ekey="${entry%%\":*}"; ekey="${ekey#\"}"+ if [[ "$ekey" == "$key" ]]; then+ continue # Will be replaced below.+ fi+ existing_svc="$(printf '%s' "$blob" | _ops_cred_json_get_inline "$ekey" service)"+ existing_acc="$(printf '%s' "$blob" | _ops_cred_json_get_inline "$ekey" account)"+ existing_sec="$(printf '%s' "$blob" | _ops_cred_json_get_inline "$ekey" secret)"+ pairs+=("$(_ops_cred_json_emit_pair "$ekey" "$existing_svc" "$existing_acc" "$existing_sec")")+ done <<<"$keys_line"+ if [[ -n "$sec" ]]; then+ pairs+=("$(_ops_cred_json_emit_pair "$key" "$svc" "$acc" "$sec")")+ fi+ local out="{"+ local i+ for i in "${!pairs[@]}"; do+ [[ "$i" -gt 0 ]] && out+=","+ out+="${pairs[$i]}"+ done+ out+="}"+ printf '%s' "$out"+}++# Inline helper for the hand-rolled path above: reads a field value from blob+# on stdin for the given key.+_ops_cred_json_get_inline() {+ local blob key field+ blob="$(cat)"+ key="$1"; field="$2"+ _ops_cred_json_get "$blob" "$key" "$field"+}++_ops_cred_json_emit_pair() {+ local key svc acc sec+ key="$(_ops_cred_json_escape "$1")"+ svc="$(_ops_cred_json_escape "$2")"+ acc="$(_ops_cred_json_escape "$3")"+ sec="$(_ops_cred_json_escape "$4")"+ printf '"%s":{"service":"%s","account":"%s","secret":"%s"}' \+ "$key" "$svc" "$acc" "$sec"+}++# ─── 3. Master-key management ───────────────────────────────────────────────+_ops_cred_ensure_masterkey() {+ local umask_saved+ umask_saved="$(umask)"+ umask 077+ mkdir -p "$__OPS_CRED_DATA_DIR" 2>/dev/null || { umask "$umask_saved"; return 1; }++ if [[ -n "${CLAUDE_OPS_MASTER_KEY:-}" ]]; then+ umask "$umask_saved"+ printf '%s' "$CLAUDE_OPS_MASTER_KEY"+ return 0+ fi++ if [[ ! -s "$__OPS_CRED_MASTERKEY_FILE" ]]; then+ local rand=""+ if command -v openssl >/dev/null 2>&1; then+ rand="$(openssl rand -base64 48 2>/dev/null | tr -d '\n')"+ fi+ if [[ -z "$rand" ]] && [[ -r /dev/urandom ]]; then+ rand="$(head -c 48 /dev/urandom 2>/dev/null | base64 2>/dev/null | tr -d '\n')"+ fi+ if [[ -z "$rand" ]]; then+ umask "$umask_saved"+ return 1+ fi+ printf '%s' "$rand" >"$__OPS_CRED_MASTERKEY_FILE" 2>/dev/null || {+ umask "$umask_saved"; return 1; }+ chmod 0600 "$__OPS_CRED_MASTERKEY_FILE" 2>/dev/null || true+ fi+ umask "$umask_saved"+ cat "$__OPS_CRED_MASTERKEY_FILE" 2>/dev/null+}++# ─── 4. Encrypted JSON read/write ───────────────────────────────────────────+_ops_cred_enc_read() {+ # Emits the decrypted JSON blob on stdout. Empty string on miss/failure.+ [[ -s "$__OPS_CRED_ENC_FILE" ]] || { printf ''; return 0; }+ command -v openssl >/dev/null 2>&1 || { printf ''; return 1; }+ local key+ key="$(_ops_cred_ensure_masterkey)" || { printf ''; return 1; }+ [[ -n "$key" ]] || { printf ''; return 1; }+ openssl enc -aes-256-cbc -d -salt -pbkdf2 -pass env:__OPS_CRED_PASS \+ -in "$__OPS_CRED_ENC_FILE" 2>/dev/null <<<"" >/dev/null 2>&1 || true+ # Run properly via env var (avoid putting the key on a cmdline).+ __OPS_CRED_PASS="$key" openssl enc -aes-256-cbc -d -salt -pbkdf2 \+ -pass env:__OPS_CRED_PASS -in "$__OPS_CRED_ENC_FILE" 2>/dev/null || printf ''+}++_ops_cred_enc_write() {+ # Writes the given blob (stdin) encrypted to the enc file.+ local umask_saved+ umask_saved="$(umask)"+ umask 077+ mkdir -p "$__OPS_CRED_DATA_DIR" 2>/dev/null || { umask "$umask_saved"; return 1; }+ command -v openssl >/dev/null 2>&1 || { umask "$umask_saved"; return 1; }+ local key+ key="$(_ops_cred_ensure_masterkey)" || { umask "$umask_saved"; return 1; }+ [[ -n "$key" ]] || { umask "$umask_saved"; return 1; }+ local tmp="$__OPS_CRED_ENC_FILE.tmp.$$"+ if __OPS_CRED_PASS="$key" openssl enc -aes-256-cbc -salt -pbkdf2 \+ -pass env:__OPS_CRED_PASS -out "$tmp" 2>/dev/null; then+ chmod 0600 "$tmp" 2>/dev/null || true+ mv -f "$tmp" "$__OPS_CRED_ENC_FILE" 2>/dev/null || {+ rm -f "$tmp" 2>/dev/null; umask "$umask_saved"; return 1; }+ umask "$umask_saved"+ return 0+ fi+ rm -f "$tmp" 2>/dev/null+ umask "$umask_saved"+ return 1+}++# ─── 5. Plaintext JSON fallback ─────────────────────────────────────────────+_ops_cred_plain_read() {+ [[ -s "$__OPS_CRED_PLAIN_FILE" ]] || { printf ''; return 0; }+ cat "$__OPS_CRED_PLAIN_FILE" 2>/dev/null || printf ''+}++_ops_cred_plain_write() {+ local umask_saved+ umask_saved="$(umask)"+ umask 077+ mkdir -p "$__OPS_CRED_DATA_DIR" 2>/dev/null || { umask "$umask_saved"; return 1; }+ local tmp="$__OPS_CRED_PLAIN_FILE.tmp.$$"+ cat >"$tmp" 2>/dev/null || { rm -f "$tmp" 2>/dev/null; umask "$umask_saved"; return 1; }+ chmod 0600 "$tmp" 2>/dev/null || true+ mv -f "$tmp" "$__OPS_CRED_PLAIN_FILE" 2>/dev/null || {+ rm -f "$tmp" 2>/dev/null; umask "$umask_saved"; return 1; }+ umask "$umask_saved"+ return 0+}++# ─── 6. Per-backend primitive operations ────────────────────────────────────+# Each returns 0 on success, 1 on failure or "not supported here".+# None of them ever print the secret to stdout (except `*_get`, which prints+# only the retrieved value).++# ── 6a. OS-native keyring ──+_ops_cred_native_available() {+ local backend; backend="$(ops_keyring_backend)"+ [[ -n "$backend" ]]+}++_ops_cred_native_set() {+ local svc="$1" acc="$2" sec="$3" backend+ backend="$(ops_keyring_backend)"+ case "$backend" in+ security)+ command -v security >/dev/null 2>&1 || return 1+ security add-generic-password -U -s "$svc" -a "$acc" -w "$sec" 2>/dev/null ;;+ secret-tool)+ command -v secret-tool >/dev/null 2>&1 || return 1+ printf '%s' "$sec" | secret-tool store --label="$svc/$acc" \+ service "$svc" account "$acc" 2>/dev/null ;;+ wincred)+ local cmdkey_bin=""+ if command -v cmd.exe >/dev/null 2>&1; then+ cmd.exe //c "cmdkey /generic:${__OPS_CRED_WIN_PREFIX}:${svc}:${acc} /user:${acc} /pass:${sec}" >/dev/null 2>&1+ elif command -v cmdkey.exe >/dev/null 2>&1; then+ cmdkey.exe "/generic:${__OPS_CRED_WIN_PREFIX}:${svc}:${acc}" "/user:${acc}" "/pass:${sec}" >/dev/null 2>&1+ elif command -v cmdkey >/dev/null 2>&1; then+ cmdkey "/generic:${__OPS_CRED_WIN_PREFIX}:${svc}:${acc}" "/user:${acc}" "/pass:${sec}" >/dev/null 2>&1+ else+ return 1+ fi ;;+ *) return 1 ;;+ esac+}++_ops_cred_native_get() {+ local svc="$1" acc="$2" backend out+ backend="$(ops_keyring_backend)"+ case "$backend" in+ security)+ command -v security >/dev/null 2>&1 || return 1+ out="$(security find-generic-password -s "$svc" -a "$acc" -w 2>/dev/null)" || return 1+ [[ -n "$out" ]] || return 1+ printf '%s' "$out" ;;+ secret-tool)+ command -v secret-tool >/dev/null 2>&1 || return 1+ out="$(secret-tool lookup service "$svc" account "$acc" 2>/dev/null)" || return 1+ [[ -n "$out" ]] || return 1+ printf '%s' "$out" ;;+ wincred)+ # cmdkey cannot read passwords back; treat as write-only.+ return 1 ;;+ *) return 1 ;;+ esac+}++_ops_cred_native_delete() {+ local svc="$1" acc="$2" backend+ backend="$(ops_keyring_backend)"+ case "$backend" in+ security)+ command -v security >/dev/null 2>&1 || return 1+ security delete-generic-password -s "$svc" -a "$acc" >/dev/null 2>&1 ;;+ secret-tool)+ command -v secret-tool >/dev/null 2>&1 || return 1+ secret-tool clear service "$svc" account "$acc" >/dev/null 2>&1 ;;+ wincred)+ if command -v cmd.exe >/dev/null 2>&1; then+ cmd.exe //c "cmdkey /delete:${__OPS_CRED_WIN_PREFIX}:${svc}:${acc}" >/dev/null 2>&1+ elif command -v cmdkey.exe >/dev/null 2>&1; then+ cmdkey.exe "/delete:${__OPS_CRED_WIN_PREFIX}:${svc}:${acc}" >/dev/null 2>&1+ elif command -v cmdkey >/dev/null 2>&1; then+ cmdkey "/delete:${__OPS_CRED_WIN_PREFIX}:${svc}:${acc}" >/dev/null 2>&1+ else+ return 1+ fi ;;+ *) return 1 ;;+ esac+}++# ── 6b. keytar via node (optional tier) ──+_ops_cred_keytar_available() {+ command -v node >/dev/null 2>&1 && [[ -f "$__OPS_CRED_MJS_HELPER" ]]+}++_ops_cred_keytar_set() {+ _ops_cred_keytar_available || return 1+ node "$__OPS_CRED_MJS_HELPER" set-keytar "$1" "$2" "$3" >/dev/null 2>&1+}++_ops_cred_keytar_get() {+ local out+ _ops_cred_keytar_available || return 1+ out="$(node "$__OPS_CRED_MJS_HELPER" get-keytar "$1" "$2" 2>/dev/null)" || return 1+ [[ -n "$out" ]] || return 1+ printf '%s' "$out"+}++_ops_cred_keytar_delete() {+ _ops_cred_keytar_available || return 1+ node "$__OPS_CRED_MJS_HELPER" delete-keytar "$1" "$2" >/dev/null 2>&1+}++# ── 6c. Encrypted JSON ──+_ops_cred_enc_available() {+ command -v openssl >/dev/null 2>&1+}++_ops_cred_enc_set() {+ _ops_cred_enc_available || return 1+ local svc="$1" acc="$2" sec="$3" blob key new_blob+ key="$(_ops_cred_jkey "$svc" "$acc")"+ blob="$(_ops_cred_enc_read)" || blob=""+ new_blob="$(_ops_cred_json_set "$blob" "$key" "$svc" "$acc" "$sec")" || return 1+ printf '%s' "$new_blob" | _ops_cred_enc_write+}++_ops_cred_enc_get() {+ _ops_cred_enc_available || return 1+ local svc="$1" acc="$2" blob key out+ key="$(_ops_cred_jkey "$svc" "$acc")"+ blob="$(_ops_cred_enc_read)" || return 1+ [[ -n "$blob" ]] || return 1+ out="$(_ops_cred_json_get "$blob" "$key" secret)"+ [[ -n "$out" ]] || return 1+ printf '%s' "$out"+}++_ops_cred_enc_delete() {+ _ops_cred_enc_available || return 1+ local svc="$1" acc="$2" blob key new_blob+ [[ -s "$__OPS_CRED_ENC_FILE" ]] || return 0+ key="$(_ops_cred_jkey "$svc" "$acc")"+ blob="$(_ops_cred_enc_read)" || return 1+ [[ -n "$blob" ]] || return 0+ new_blob="$(_ops_cred_json_set "$blob" "$key" "$svc" "$acc" "")" || return 1+ printf '%s' "$new_blob" | _ops_cred_enc_write+}++# ── 6d. Plaintext JSON ──+_ops_cred_plain_set() {+ _ops_cred_warn_plaintext_once+ local svc="$1" acc="$2" sec="$3" blob key new_blob+ key="$(_ops_cred_jkey "$svc" "$acc")"+ blob="$(_ops_cred_plain_read)" || blob=""+ new_blob="$(_ops_cred_json_set "$blob" "$key" "$svc" "$acc" "$sec")" || return 1+ printf '%s' "$new_blob" | _ops_cred_plain_write+}++_ops_cred_plain_get() {+ local svc="$1" acc="$2" blob key out+ key="$(_ops_cred_jkey "$svc" "$acc")"+ blob="$(_ops_cred_plain_read)" || return 1+ [[ -n "$blob" ]] || return 1+ out="$(_ops_cred_json_get "$blob" "$key" secret)"+ [[ -n "$out" ]] || return 1+ printf '%s' "$out"+}++_ops_cred_plain_delete() {+ local svc="$1" acc="$2" blob key new_blob+ [[ -s "$__OPS_CRED_PLAIN_FILE" ]] || return 0+ key="$(_ops_cred_jkey "$svc" "$acc")"+ blob="$(_ops_cred_plain_read)" || return 1+ [[ -n "$blob" ]] || return 0+ new_blob="$(_ops_cred_json_set "$blob" "$key" "$svc" "$acc" "")" || return 1+ printf '%s' "$new_blob" | _ops_cred_plain_write+}++# ─── 7. Public API ──────────────────────────────────────────────────────────+ops_cred_backends_available() {+ local -a out=()+ _ops_cred_native_available && out+=("native:$(ops_keyring_backend)")+ _ops_cred_keytar_available && out+=("keytar")+ _ops_cred_enc_available && out+=("encrypted-json")+ out+=("plaintext-json") # always available as last-resort+ printf '%s' "${out[*]}"+}++ops_cred_set() {+ if [[ $# -ne 3 ]]; then+ _ops_cred_log "ops_cred_set: usage: ops_cred_set <service> <account> <secret>"+ return 1+ fi+ local svc="$1" acc="$2" sec="$3"++ if _ops_cred_native_available && _ops_cred_native_set "$svc" "$acc" "$sec"; then+ _ops_cred_log "stored via=native:$(ops_keyring_backend) service=$svc account=$acc"+ return 0+ fi+ if _ops_cred_keytar_available && _ops_cred_keytar_set "$svc" "$acc" "$sec"; then+ _ops_cred_log "stored via=keytar service=$svc account=$acc"+ return 0+ fi+ if _ops_cred_enc_available && _ops_cred_enc_set "$svc" "$acc" "$sec"; then+ _ops_cred_log "stored via=encrypted-json service=$svc account=$acc"+ return 0+ fi+ if _ops_cred_plain_set "$svc" "$acc" "$sec"; then+ _ops_cred_log "stored via=plaintext-json service=$svc account=$acc"+ return 0+ fi+ _ops_cred_log "stored via=NONE service=$svc account=$acc (all backends failed)"+ return 1+}++ops_cred_get() {+ if [[ $# -ne 2 ]]; then+ _ops_cred_log "ops_cred_get: usage: ops_cred_get <service> <account>"+ return 1+ fi+ local svc="$1" acc="$2" out=""++ if _ops_cred_native_available; then+ out="$(_ops_cred_native_get "$svc" "$acc" 2>/dev/null || true)"+ if [[ -n "$out" ]]; then printf '%s' "$out"; return 0; fi+ fi+ if _ops_cred_keytar_available; then+ out="$(_ops_cred_keytar_get "$svc" "$acc" 2>/dev/null || true)"+ if [[ -n "$out" ]]; then printf '%s' "$out"; return 0; fi+ fi+ if _ops_cred_enc_available; then+ out="$(_ops_cred_enc_get "$svc" "$acc" 2>/dev/null || true)"+ if [[ -n "$out" ]]; then printf '%s' "$out"; return 0; fi+ fi+ out="$(_ops_cred_plain_get "$svc" "$acc" 2>/dev/null || true)"+ if [[ -n "$out" ]]; then printf '%s' "$out"; return 0; fi+ return 1+}++ops_cred_delete() {+ if [[ $# -ne 2 ]]; then+ _ops_cred_log "ops_cred_delete: usage: ops_cred_delete <service> <account>"+ return 1+ fi+ local svc="$1" acc="$2"+ local any_err=0++ # Best-effort on each: missing-key is NOT an error.+ _ops_cred_native_available && _ops_cred_native_delete "$svc" "$acc" >/dev/null 2>&1 || true+ _ops_cred_keytar_available && _ops_cred_keytar_delete "$svc" "$acc" >/dev/null 2>&1 || true+ if _ops_cred_enc_available; then+ _ops_cred_enc_delete "$svc" "$acc" >/dev/null 2>&1 || any_err=1+ fi+ _ops_cred_plain_delete "$svc" "$acc" >/dev/null 2>&1 || any_err=1++ # Only fail catastrophically if BOTH writable-file backends errored AND the+ # files existed (otherwise "nothing to delete" is fine).+ if [[ "$any_err" == "1" ]] \+ && [[ ! -s "$__OPS_CRED_ENC_FILE" ]] \+ && [[ ! -s "$__OPS_CRED_PLAIN_FILE" ]]; then+ any_err=0+ fi+ return $any_err+}++ops_cred_backend_for() {+ if [[ $# -ne 2 ]]; then+ _ops_cred_log "ops_cred_backend_for: usage: ops_cred_backend_for <service> <account>"+ return 1+ fi+ local svc="$1" acc="$2"+ if _ops_cred_native_available && _ops_cred_native_get "$svc" "$acc" >/dev/null 2>&1; then+ printf 'native:%s' "$(ops_keyring_backend)"; return 0+ fi+ if _ops_cred_keytar_available && _ops_cred_keytar_get "$svc" "$acc" >/dev/null 2>&1; then+ printf 'keytar'; return 0+ fi+ if _ops_cred_enc_available && _ops_cred_enc_get "$svc" "$acc" >/dev/null 2>&1; then+ printf 'encrypted-json'; return 0+ fi+ if _ops_cred_plain_get "$svc" "$acc" >/dev/null 2>&1; then+ printf 'plaintext-json'; return 0+ fi+ printf ''+ return 0+}++# ─── 8. Direct-execution CLI ────────────────────────────────────────────────+# Lets the .mjs helper (or a human) shell out for cross-language testing.+if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then+ cmd="${1:-}"; shift || true+ case "$cmd" in+ set)+ [[ $# -eq 3 ]] || { echo "usage: credential-store.sh set <service> <account> <secret>" >&2; exit 2; }+ ops_cred_set "$@" ;;+ get)+ [[ $# -eq 2 ]] || { echo "usage: credential-store.sh get <service> <account>" >&2; exit 2; }+ ops_cred_get "$@" ;;+ delete)+ [[ $# -eq 2 ]] || { echo "usage: credential-store.sh delete <service> <account>" >&2; exit 2; }+ ops_cred_delete "$@" ;;+ backends)+ ops_cred_backends_available; echo ;;+ backend-for)+ [[ $# -eq 2 ]] || { echo "usage: credential-store.sh backend-for <service> <account>" >&2; exit 2; }+ ops_cred_backend_for "$@"; echo ;;+ ""|-h|--help|help)+ cat >&2 <<EOF+credential-store.sh — cross-OS secret storage with cascading backends+Usage:+ credential-store.sh set <service> <account> <secret>+ credential-store.sh get <service> <account>+ credential-store.sh delete <service> <account>+ credential-store.sh backends+ credential-store.sh backend-for <service> <account>+EOF+ exit 0 ;;+ *)+ echo "unknown subcommand: $cmd (try --help)" >&2; exit 2 ;;+ esac+fidiff --git a/claude-ops/lib/os-detect.mjs b/claude-ops/lib/os-detect.mjsnew file mode 100644index 00000000..ad059fbf--- /dev/null+++ b/claude-ops/lib/os-detect.mjs@@ -0,0 +1,372 @@+// os-detect.mjs+//+// Node.js ESM mirror of lib/os-detect.sh. Provides a small, dependency-free+// toolkit for detecting the host OS family, architecture, preferred package+// manager, keyring backend, URL opener, shell, and browser profile+// directories. Field names and return values are kept in sync with the bash+// helper so consumers can mix-and-match between shell and Node contexts.+//+// Design goals:+// - Zero npm deps (built-ins only: os, fs, path, child_process, process, url)+// - Sync, cheap helpers for the common cases; async only where fs probing+// benefits from it (browser profile discovery, aggregate JSON dump)+// - Never throw on missing files — degrade to null/false/[]+// - Runnable directly (`node lib/os-detect.mjs`) for debugging++import { readFileSync, promises as fsp } from "node:fs";+import { spawnSync } from "node:child_process";+import { homedir } from "node:os";+import path from "node:path";+import process from "node:process";+import { fileURLToPath } from "node:url";++// ---------------------------------------------------------------------------+// Internal helpers+// ---------------------------------------------------------------------------++/**+ * Read a file synchronously, returning "" on any error. Used for the small+ * /proc and /etc files we probe — we never want a missing file to throw.+ * @param {string} p+ * @returns {string}+ */+function safeRead(p) {+ try {+ return readFileSync(p, "utf8");+ } catch {+ return "";+ }+}++/**+ * Parse a shell-style KEY=value file (e.g. /etc/os-release) into a plain+ * object. Strips surrounding single/double quotes from values.+ * @param {string} contents+ * @returns {Record<string, string>}+ */+function parseEnvFile(contents) {+ /** @type {Record<string, string>} */+ const out = {};+ for (const rawLine of contents.split("\n")) {+ const line = rawLine.trim();+ if (!line || line.startsWith("#")) continue;+ const eq = line.indexOf("=");+ if (eq < 0) continue;+ const key = line.slice(0, eq).trim();+ let value = line.slice(eq + 1).trim();+ if (+ (value.startsWith('"') && value.endsWith('"')) ||+ (value.startsWith("'") && value.endsWith("'"))+ ) {+ value = value.slice(1, -1);+ }+ out[key] = value;+ }+ return out;+}++/**+ * Check whether a binary is resolvable on PATH. Uses `where.exe` on Windows+ * and `command -v` under /bin/sh everywhere else so we respect shell+ * builtins and aliases to hashed commands.+ * @param {string} name+ * @returns {boolean}+ */+function hasBin(name) {+ try {+ if (process.platform === "win32") {+ const r = spawnSync("where.exe", [name], { stdio: "ignore" });+ return r.status === 0;+ }+ const r = spawnSync("/bin/sh", ["-c", `command -v ${name}`], {+ stdio: "ignore",+ });+ return r.status === 0;+ } catch {+ return false;+ }+}++// ---------------------------------------------------------------------------+// Public: basic detectors+// ---------------------------------------------------------------------------++/**+ * Returns true when running inside Windows Subsystem for Linux. Detected via+ * the "microsoft" marker Microsoft injects into /proc/version on WSL1/WSL2.+ * @returns {boolean}+ */+export function isWsl() {+ if (process.platform !== "linux") return false;+ const procVersion = safeRead("/proc/version").toLowerCase();+ return procVersion.includes("microsoft");+}++/**+ * High-level OS family identifier.+ * @returns {"macos"|"debian"|"fedora"|"arch"|"suse"|"alpine"|"linux"|"wsl"|"windows"|"unknown"}+ */+export function osId() {+ if (process.platform === "darwin") return "macos";+ if (process.platform === "win32") return "windows";+ if (process.platform !== "linux") return "unknown";++ if (isWsl()) return "wsl";++ const release = parseEnvFile(safeRead("/etc/os-release"));+ const candidates = [release.ID, ...(release.ID_LIKE || "").split(/\s+/)]+ .map((s) => (s || "").toLowerCase())+ .filter(Boolean);++ for (const id of candidates) {+ if (id === "debian" || id === "ubuntu") return "debian";+ if (+ id === "fedora" ||+ id === "rhel" ||+ id === "centos" ||+ id === "rocky" ||+ id === "almalinux"+ ) {+ return "fedora";+ }+ if (id === "arch" || id === "manjaro") return "arch";+ if (id.startsWith("opensuse") || id === "sles") return "suse";+ if (id === "alpine") return "alpine";+ }+ return "linux";+}++/**+ * Normalized CPU architecture string.+ * @returns {"x86_64"|"arm64"|"armv7"|"i686"|"unknown"}+ */+export function arch() {+ switch (process.arch) {+ case "x64":+ return "x86_64";+ case "arm64":+ return "arm64";+ case "arm":+ return "armv7";+ case "ia32":+ return "i686";+ default:+ return "unknown";+ }+}++/**+ * First package manager found on PATH, in preference order. Mirrors the+ * cascade used by the bash helper so recommended install commands are+ * consistent across shells.+ * @returns {"brew"|"apt-get"|"dnf"|"pacman"|"zypper"|"apk"|"winget"|"scoop"|"choco"|null}+ */+export function pkgMgr() {+ // Homebrew wins everywhere it's installed (macOS and Linuxbrew).+ if (hasBin("brew")) return "brew";++ if (process.platform === "linux") {+ for (const m of ["apt-get", "dnf", "pacman", "zypper", "apk"]) {+ if (hasBin(m)) return m;+ }+ }++ if (process.platform === "win32") {+ for (const m of ["winget", "scoop", "choco"]) {+ if (hasBin(m)) return m;+ }+ }++ return null;+}++/**+ * Full shell command string to install `pkg` via the detected package+ * manager, or null when nothing suitable is available.+ * @param {string} pkg+ * @returns {string|null}+ */+export function pkgInstallCmd(pkg) {+ const mgr = pkgMgr();+ switch (mgr) {+ case "brew":+ return `brew install ${pkg}`;+ case "apt-get":+ return `sudo apt-get install -y ${pkg}`;+ case "dnf":+ return `sudo dnf install -y ${pkg}`;+ case "pacman":+ return `sudo pacman -S --noconfirm ${pkg}`;+ case "zypper":+ return `sudo zypper install -y ${pkg}`;+ case "apk":+ return `sudo apk add ${pkg}`;+ case "winget":+ return `winget install -e --id ${pkg}`;+ case "scoop":+ return `scoop install ${pkg}`;+ case "choco":+ return `choco install -y ${pkg}`;+ default:+ return null;+ }+}++/**+ * Preferred secret-storage backend identifier.+ * - macOS: Keychain via `security`+ * - Linux: libsecret via `secret-tool` (if present on PATH)+ * - Windows / WSL-with-cmd.exe: Windows Credential Manager+ * @returns {"security"|"secret-tool"|"wincred"|null}+ */+export function keyringBackend() {+ if (process.platform === "darwin") return "security";+ if (process.platform === "win32") return "wincred";+ if (isWsl() && hasBin("cmd.exe")) return "wincred";+ if (process.platform === "linux" && hasBin("secret-tool")) return "secret-tool";+ return null;+}++/**+ * Best-effort command for opening URLs/files in the host GUI.+ * @returns {"open"|"xdg-open"|"wslview"|"cmd.exe /c start"|null}+ */+export function opener() {+ if (process.platform === "darwin") return "open";+ if (process.platform === "win32") return "cmd.exe /c start";+ if (isWsl()) {+ if (hasBin("wslview")) return "wslview";+ if (hasBin("cmd.exe")) return "cmd.exe /c start";+ }+ if (hasBin("xdg-open")) return "xdg-open";+ return null;+}++/**+ * Basename of the user's interactive shell, with platform-aware fallbacks.+ * @returns {string}+ */+export function shell() {+ const s = process.env.SHELL;+ if (s) return path.basename(s);+ if (process.platform === "win32") return "pwsh";+ return "bash";+}++// ---------------------------------------------------------------------------+// Public: async probes+// ---------------------------------------------------------------------------++/**+ * Candidate Chrome/Chromium/Brave/Arc user-data directories for this host.+ * Paths that don't exist are filtered out.+ * @returns {Promise<string[]>}+ */+export async function browserProfileDirs() {+ const home = homedir();+ /** @type {string[]} */+ const candidates = [];++ if (process.platform === "darwin") {+ const sup = path.join(home, "Library", "Application Support");+ candidates.push(+ path.join(sup, "Google", "Chrome"),+ path.join(sup, "Chromium"),+ path.join(sup, "BraveSoftware", "Brave-Browser"),+ path.join(sup, "Arc", "User Data"),+ );+ } else if (process.platform === "linux") {+ const config = path.join(home, ".config");+ candidates.push(+ path.join(config, "google-chrome"),+ path.join(config, "chromium"),+ path.join(config, "BraveSoftware", "Brave-Browser"),+ );+ // On WSL, also probe the Windows-side profile under /mnt/c.+ if (isWsl()) {+ const winUser = process.env.USER || process.env.USERNAME || "";+ if (winUser) {+ const winLocal = `/mnt/c/Users/${winUser}/AppData/Local`;+ candidates.push(+ path.join(winLocal, "Google", "Chrome", "User Data"),+ path.join(winLocal, "Chromium", "User Data"),+ path.join(winLocal, "BraveSoftware", "Brave-Browser", "User Data"),+ );+ }+ }+ } else if (process.platform === "win32") {+ const localAppData =+ process.env.LOCALAPPDATA ||+ (process.env.USERPROFILE+ ? path.join(process.env.USERPROFILE, "AppData", "Local")+ : "");+ if (localAppData) {+ candidates.push(+ path.join(localAppData, "Google", "Chrome", "User Data"),+ path.join(localAppData, "Chromium", "User Data"),+ path.join(localAppData, "BraveSoftware", "Brave-Browser", "User Data"),+ );+ }+ }++ const checks = await Promise.all(+ candidates.map(async (p) => {+ try {+ await fsp.access(p);+ return p;+ } catch {+ return null;+ }+ }),+ );+ return checks.filter((p) => p !== null);+}++/**+ * Aggregate OS summary — same schema as the bash helper's JSON output.+ * @returns {Promise<{+ * os: string,+ * distro_id: string,+ * arch: string,+ * pkg_mgr: string|null,+ * keyring_backend: string|null,+ * opener: string|null,+ * shell: string,+ * is_wsl: boolean,+ * browser_profiles: string[]+ * }>}+ */+export async function osJson() {+ const release = parseEnvFile(safeRead("/etc/os-release"));+ return {+ os: osId(),+ distro_id: release.ID || "",+ arch: arch(),+ pkg_mgr: pkgMgr(),+ keyring_backend: keyringBackend(),+ opener: opener(),+ shell: shell(),+ is_wsl: isWsl(),+ browser_profiles: await browserProfileDirs(),+ };+}++// ---------------------------------------------------------------------------+// CLI entrypoint: `node lib/os-detect.mjs` prints the full JSON report.+// ---------------------------------------------------------------------------++const invokedDirectly =+ process.argv[1] && import.meta.url === `file://${process.argv[1]}`;+// Also handle symlinks and realpath differences that can trip the naive check.+const invokedViaRealpath =+ process.argv[1] &&+ import.meta.url === `file://${fileURLToPath(import.meta.url)}`.replace(+ /^file:\/\//,+ "file://",+ ) &&+ process.argv[1].endsWith("os-detect.mjs");++if (invokedDirectly || invokedViaRealpath) {+ const obj = await osJson();+ process.stdout.write(JSON.stringify(obj, null, 2) + "\n");+}diff --git a/claude-ops/lib/os-detect.sh b/claude-ops/lib/os-detect.shnew file mode 100755index 00000000..7eb95444--- /dev/null+++ b/claude-ops/lib/os-detect.sh@@ -0,0 +1,325 @@+#!/usr/bin/env bash+# os-detect.sh — Cross-OS detection helpers for the claude-ops plugin.+#+# This file is a SOURCED library, not a standalone executable. The shebang+# above exists purely so editors (vim/VS Code/etc.) pick the right syntax+# highlighter and LSP. Source it from other scripts via:+# source "$(dirname "$0")/../lib/os-detect.sh"+#+# It exposes a handful of `ops_*` functions that normalize host OS, CPU arch,+# package manager, keyring backend, URL opener, shell, and browser-profile+# locations across macOS, Linux (incl. WSL), and Windows (Git Bash/MSYS/Cygwin).+#+# Running this file directly (e.g. `bash os-detect.sh`) emits the full+# detection result as JSON — handy for debugging (see guard at EOF).+#+# Design notes:+# - Idempotent: gated by __OPS_OS_DETECT_SH_LOADED__ so repeat sourcing is free.+# - Non-invasive: we only enable `set -euo pipefail` if invoked directly; when+# sourced we leave the caller's shell options untouched.+# - No hard dependency on jq — we fall back to a hand-rolled JSON emitter.++# ─── Re-source guard ────────────────────────────────────────────────────────+if [[ -n "${__OPS_OS_DETECT_SH_LOADED__:-}" ]]; then+ return 0 2>/dev/null || exit 0+fi+__OPS_OS_DETECT_SH_LOADED__=1++# Only clobber shell options when run directly; sourced callers keep their own.+if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then+ set -euo pipefail+fi++# ─── ops_os: normalized OS/distro identifier ────────────────────────────────+# Echoes: macos | debian | fedora | arch | suse | alpine | linux | wsl | windows | unknown+ops_os() {+ local uname_s+ uname_s="$(uname -s 2>/dev/null || echo unknown)"+ case "$uname_s" in+ Darwin) echo "macos"; return 0 ;;+ MINGW*|MSYS*|CYGWIN*) echo "windows"; return 0 ;;+ Linux)+ # WSL advertises itself in /proc/version.+ if [[ -r /proc/version ]] && grep -qi microsoft /proc/version 2>/dev/null; then+ echo "wsl"; return 0+ fi+ if [[ -r /etc/os-release ]]; then+ # shellcheck disable=SC1091+ local ID="" ID_LIKE=""+ ID="$(. /etc/os-release 2>/dev/null; echo "${ID:-}")"+ ID_LIKE="$(. /etc/os-release 2>/dev/null; echo "${ID_LIKE:-}")"+ case " $ID $ID_LIKE " in+ *" debian "*|*" ubuntu "*|*" linuxmint "*|*" pop "*|*" raspbian "*) echo "debian"; return 0 ;;+ *" fedora "*|*" rhel "*|*" centos "*|*" rocky "*|*" almalinux "*|*" amzn "*) echo "fedora"; return 0 ;;+ *" arch "*|*" manjaro "*|*" endeavouros "*) echo "arch"; return 0 ;;+ *" suse "*|*" opensuse "*|*" sles "*|*" opensuse-leap "*|*" opensuse-tumbleweed "*) echo "suse"; return 0 ;;+ *" alpine "*) echo "alpine"; return 0 ;;+ esac+ fi+ echo "linux"; return 0+ ;;+ *) echo "unknown"; return 0 ;;+ esac+}++# ─── ops_arch: normalized CPU architecture ──────────────────────────────────+# Echoes: x86_64 | arm64 | armv7 | i686 | unknown+ops_arch() {+ local m+ m="$(uname -m 2>/dev/null || echo unknown)"+ case "$m" in+ x86_64|amd64) echo "x86_64" ;;+ aarch64|arm64) echo "arm64" ;;+ armv7l|armv7|armhf) echo "armv7" ;;+ i386|i686) echo "i686" ;;+ *) echo "unknown" ;;+ esac+}++# ─── ops_pkg_mgr: first-available package manager in priority order ─────────+# Cascade: brew > (distro-native on Linux) > (winget > scoop > choco on Windows).+ops_pkg_mgr() {+ # brew wins everywhere it exists (macOS, Linuxbrew, WSL with brew installed).+ if command -v brew >/dev/null 2>&1; then echo "brew"; return 0; fi++ local os; os="$(ops_os)"+ case "$os" in+ debian|wsl)+ command -v apt-get >/dev/null 2>&1 && { echo "apt-get"; return 0; } ;;+ fedora)+ command -v dnf >/dev/null 2>&1 && { echo "dnf"; return 0; }+ command -v yum >/dev/null 2>&1 && { echo "dnf"; return 0; } ;;+ arch)+ command -v pacman >/dev/null 2>&1 && { echo "pacman"; return 0; } ;;+ suse)+ command -v zypper >/dev/null 2>&1 && { echo "zypper"; return 0; } ;;+ alpine)+ command -v apk >/dev/null 2>&1 && { echo "apk"; return 0; } ;;+ linux)+ # Generic Linux — probe in order.+ for m in apt-get dnf pacman zypper apk; do+ command -v "$m" >/dev/null 2>&1 && { echo "$m"; return 0; }+ done ;;+ windows)+ for m in winget scoop choco; do+ command -v "$m" >/dev/null 2>&1 && { echo "$m"; return 0; }+ done ;;+ esac++ # WSL may also surface Windows managers via interop — try them last.+ if [[ "$os" == "wsl" ]]; then+ for m in winget.exe scoop choco.exe; do+ command -v "$m" >/dev/null 2>&1 && { echo "${m%.exe}"; return 0; }+ done+ fi++ echo ""+ return 0+}++# ─── ops_pkg_install_cmd: the full install invocation for a given package ───+# Prints empty + exits 1 when no package manager is available.+ops_pkg_install_cmd() {+ local pkg="${1:-}"+ if [[ -z "$pkg" ]]; then echo ""; return 1; fi+ local mgr; mgr="$(ops_pkg_mgr)"+ case "$mgr" in+ brew) echo "brew install $pkg" ;;+ apt-get) echo "sudo apt-get install -y $pkg" ;;+ dnf) echo "sudo dnf install -y $pkg" ;;+ pacman) echo "sudo pacman -S --noconfirm $pkg" ;;+ zypper) echo "sudo zypper install -y $pkg" ;;+ apk) echo "sudo apk add --no-cache $pkg" ;;+ winget) echo "winget install -e --id $pkg" ;;+ scoop) echo "scoop install $pkg" ;;+ choco) echo "choco install -y $pkg" ;;+ *) echo ""; return 1 ;;+ esac+}++# ─── ops_keyring_backend: which secret-store CLI to prefer ──────────────────+# Echoes: security | secret-tool | wincred | "" (unsupported).+ops_keyring_backend() {+ local os; os="$(ops_os)"+ case "$os" in+ macos) echo "security" ;;+ windows)+ command -v cmdkey >/dev/null 2>&1 && { echo "wincred"; return 0; }+ command -v cmdkey.exe >/dev/null 2>&1 && { echo "wincred"; return 0; }+ echo "" ;;+ wsl)+ # Prefer Linux libsecret when present; otherwise reach over to Windows cmdkey.+ if command -v secret-tool >/dev/null 2>&1; then echo "secret-tool"+ elif command -v cmdkey.exe >/dev/null 2>&1; then echo "wincred"+ else echo ""; fi ;;+ debian|fedora|arch|suse|alpine|linux)+ command -v secret-tool >/dev/null 2>&1 && { echo "secret-tool"; return 0; }+ echo "" ;;+ *) echo "" ;;+ esac+}++# ─── ops_opener: URL / file opener command ──────────────────────────────────+# Echoes the full command string (may contain spaces, e.g. "cmd.exe /c start").+ops_opener() {+ local os; os="$(ops_os)"+ case "$os" in+ macos) echo "open" ;;+ wsl)+ command -v wslview >/dev/null 2>&1 && { echo "wslview"; return 0; }+ command -v xdg-open >/dev/null 2>&1 && { echo "xdg-open"; return 0; }+ echo "cmd.exe /c start" ;;+ windows) echo "cmd.exe /c start" ;;+ debian|fedora|arch|suse|alpine|linux)+ command -v xdg-open >/dev/null 2>&1 && { echo "xdg-open"; return 0; }+ echo "" ;;+ *) echo "" ;;+ esac+}++# ─── ops_shell: basename of the user's login/current shell ──────────────────+# Echoes: bash | zsh | fish | sh | pwsh | cmd | unknown+ops_shell() {+ local s=""+ if [[ -n "${SHELL:-}" ]]; then+ s="$(basename "$SHELL")"+ fi+ if [[ -z "$s" ]] || [[ "$s" == "unknown" ]]; then+ s="$(ps -p $$ -o comm= 2>/dev/null | tr -d ' ' | sed 's|^-||')"+ s="$(basename "${s:-unknown}")"+ fi+ case "$s" in+ bash|zsh|fish|sh|pwsh|cmd) echo "$s" ;;+ powershell|powershell.exe|pwsh.exe) echo "pwsh" ;;+ cmd.exe) echo "cmd" ;;+ *) echo "unknown" ;;+ esac+}++# ─── ops_browser_profile_dirs: existing Chromium-family profile roots ───────+# Emits one absolute path per line; only paths that actually exist on disk.+ops_browser_profile_dirs() {+ local os; os="$(ops_os)"+ local -a candidates=()+ case "$os" in+ macos)+ candidates+=("$HOME/Library/Application Support/Google/Chrome")+ candidates+=("$HOME/Library/Application Support/Chromium")+ candidates+=("$HOME/Library/Application Support/BraveSoftware/Brave-Browser")+ candidates+=("$HOME/Library/Application Support/Arc/User Data")+ ;;+ debian|fedora|arch|suse|alpine|linux)+ candidates+=("$HOME/.config/google-chrome")+ candidates+=("$HOME/.config/chromium")+ candidates+=("$HOME/.config/BraveSoftware/Brave-Browser")+ ;;+ wsl)+ candidates+=("$HOME/.config/google-chrome")+ candidates+=("$HOME/.config/chromium")+ candidates+=("$HOME/.config/BraveSoftware/Brave-Browser")+ # Windows-side profiles are reachable via /mnt/c when DrvFs is mounted.+ local win_user="${USER:-$(id -un 2>/dev/null || echo user)}"+ candidates+=("/mnt/c/Users/$win_user/AppData/Local/Google/Chrome/User Data")+ candidates+=("/mnt/c/Users/$win_user/AppData/Local/Chromium/User Data")+ candidates+=("/mnt/c/Users/$win_user/AppData/Local/BraveSoftware/Brave-Browser/User Data")+ ;;+ windows)+ local lad="${LOCALAPPDATA:-$HOME/AppData/Local}"+ candidates+=("$lad\\Google\\Chrome\\User Data")+ candidates+=("$lad\\Chromium\\User Data")+ candidates+=("$lad\\BraveSoftware\\Brave-Browser\\User Data")+ ;;+ esac+ local p+ for p in "${candidates[@]}"; do+ [[ -d "$p" ]] && echo "$p"+ done+ return 0+}++# ─── JSON helpers ───────────────────────────────────────────────────────────+# Minimal string escaper for the fallback JSON emitter (no jq path).+__ops_json_escape() {+ local s="$1"+ s="${s//\\/\\\\}"+ s="${s//\"/\\\"}"+ s="${s//$'\n'/\\n}"+ s="${s//$'\r'/\\r}"+ s="${s//$'\t'/\\t}"+ printf '%s' "$s"+}++# ─── ops_os_json: flat JSON blob of all the fields above ────────────────────+ops_os_json() {+ local os distro_id arch pkg_mgr keyring opener shell is_wsl+ os="$(ops_os)"+ arch="$(ops_arch)"+ pkg_mgr="$(ops_pkg_mgr)"+ keyring="$(ops_keyring_backend)"+ opener="$(ops_opener)"+ shell="$(ops_shell)"+ if [[ "$os" == "wsl" ]]; then is_wsl="true"; else is_wsl="false"; fi++ # distro_id is the distro-specific bucket on Linux/WSL; mirrors `os` elsewhere.+ case "$os" in+ debian|fedora|arch|suse|alpine|linux) distro_id="$os" ;;+ wsl)+ distro_id="linux"+ if [[ -r /etc/os-release ]]; then+ local _id=""; _id="$(. /etc/os-release 2>/dev/null; echo "${ID:-}")"+ [[ -n "$_id" ]] && distro_id="$_id"+ fi ;;+ *) distro_id="$os" ;;+ esac++ # Gather profile dirs into an array (portable; no mapfile required).+ local -a profiles=()+ local line+ while IFS= read -r line; do+ [[ -n "$line" ]] && profiles+=("$line")+ done < <(ops_browser_profile_dirs)++ if command -v jq >/dev/null 2>&1; then+ # Prefer jq — handles escaping for us.+ local profiles_json="[]"+ if ((${#profiles[@]} > 0)); then+ profiles_json="$(printf '%s\n' "${profiles[@]}" | jq -R . | jq -s .)"+ fi+ jq -n \+ --arg os "$os" --arg distro_id "$distro_id" --arg arch "$arch" \+ --arg pkg_mgr "$pkg_mgr" --arg keyring "$keyring" --arg opener "$opener" \+ --arg shell "$shell" --argjson is_wsl "$is_wsl" \+ --argjson profiles "$profiles_json" \+ '{os:$os, distro_id:$distro_id, arch:$arch, pkg_mgr:$pkg_mgr,+ keyring_backend:$keyring, opener:$opener, shell:$shell,+ is_wsl:$is_wsl, browser_profiles:$profiles}'+ return 0+ fi++ # Fallback: hand-rolled emitter.+ local profiles_out="["+ local i+ for i in "${!profiles[@]}"; do+ [[ "$i" -gt 0 ]] && profiles_out+=", "+ profiles_out+="\"$(__ops_json_escape "${profiles[$i]}")\""+ done+ profiles_out+="]"++ printf '{'+ printf '"os":"%s",' "$(__ops_json_escape "$os")"+ printf '"distro_id":"%s",' "$(__ops_json_escape "$distro_id")"+ printf '"arch":"%s",' "$(__ops_json_escape "$arch")"+ printf '"pkg_mgr":"%s",' "$(__ops_json_escape "$pkg_mgr")"+ printf '"keyring_backend":"%s",' "$(__ops_json_escape "$keyring")"+ printf '"opener":"%s",' "$(__ops_json_escape "$opener")"+ printf '"shell":"%s",' "$(__ops_json_escape "$shell")"+ printf '"is_wsl":%s,' "$is_wsl"+ printf '"browser_profiles":%s' "$profiles_out"+ printf '}\n'+}++# ─── Direct-execution entry point ───────────────────────────────────────────+# `bash os-detect.sh` prints the full detection blob; sourcing is a no-op here.+if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then+ ops_os_json+fidiff --git a/claude-ops/tests/lib/smoke.sh b/claude-ops/tests/lib/smoke.shnew file mode 100755index 00000000..679434a0--- /dev/null+++ b/claude-ops/tests/lib/smoke.sh@@ -0,0 +1,242 @@+#!/usr/bin/env bash+# =============================================================================+# claude-ops foundation smoke tests+# =============================================================================+#+# Purpose:+# Exercise the cross-OS foundation helpers (OS detection + credential store)+# for both the Bash and Node (ESM) implementations without requiring bats or+# any other test framework. This is a smoke suite: it verifies the happy+# path, basic contracts, and parity between the two implementations.+#+# How to run:+# From the repo root:+# bash tests/lib/smoke.sh+#+# What it covers:+# - lib/os-detect.sh : sourced export surface + JSON output+# - lib/os-detect.mjs : Node equivalent, JSON output+# - parity : .os field matches across both+# - lib/credential-store.sh: backends list + plaintext + enc-json roundtrips,+# best-effort native keyring roundtrip+# - lib/credential-store.mjs: CLI surface (backends)+#+# Isolation:+# XDG_DATA_HOME is redirected to a per-run temp dir and removed on exit so+# the host's real secrets.json is never touched. No network access required.+#+# Exit: 0 if no FAIL, non-zero otherwise. SKIPs do not fail the suite.+# =============================================================================++set -euo pipefail++# ---- locate repo root (realpath with readlink -f fallback) -------------------+_resolve() {+ if command -v realpath >/dev/null 2>&1; then+ realpath "$1"+ else+ readlink -f "$1"+ fi+}+SCRIPT_PATH="$(_resolve "${BASH_SOURCE[0]}")"+REPO_ROOT="$(cd "$(dirname "$SCRIPT_PATH")/../.." && pwd)"++# ---- isolated environment ----------------------------------------------------+XDG_DATA_HOME="$(mktemp -d)"+export XDG_DATA_HOME+TMP_WORK="$(mktemp -d)"+trap 'rm -rf "$XDG_DATA_HOME" "$TMP_WORK"' EXIT++# ---- counters / reporting ----------------------------------------------------+PASS=0+FAIL=0+SKIP=0+TOTAL=0++pass() { printf 'PASS: %s\n' "$1"; PASS=$((PASS+1)); TOTAL=$((TOTAL+1)); }+fail() { printf 'FAIL: %s -- %s\n' "$1" "$2"; FAIL=$((FAIL+1)); TOTAL=$((TOTAL+1)); }+skip() { printf 'SKIP: %s -- %s\n' "$1" "$2"; SKIP=$((SKIP+1)); TOTAL=$((TOTAL+1)); }++have() { command -v "$1" >/dev/null 2>&1; }++# ---- test helpers ------------------------------------------------------------+VALID_OS_RE='^(macos|debian|fedora|arch|suse|alpine|linux|wsl|windows|freebsd|openbsd|netbsd|unknown)$'++rand_suffix() {+ # portable-ish random suffix: pid + nanoseconds-or-seconds+ local n+ n="$(date +%N 2>/dev/null || date +%s)"+ printf '%s-%s' "$$" "${n:-0}"+}++# ---- individual tests --------------------------------------------------------++test_os_detect_sh() {+ local name="test_os_detect_sh"+ # shellcheck disable=SC1091+ if ! source "$REPO_ROOT/lib/os-detect.sh" 2>/tmp/os-detect-sh.err; then+ fail "$name" "sourcing lib/os-detect.sh failed: $(cat /tmp/os-detect-sh.err)"+ return+ fi+ local os arch json+ os="$(ops_os || true)"+ arch="$(ops_arch || true)"+ json="$(ops_os_json || true)"+ if ! [[ "$os" =~ $VALID_OS_RE ]]; then+ fail "$name" "ops_os returned unexpected value: '$os'"; return+ fi+ if [[ -z "$arch" ]]; then+ fail "$name" "ops_arch was empty"; return+ fi+ if ! printf '%s' "$json" | grep -q '"os":'; then+ fail "$name" "ops_os_json missing \"os\" key"; return+ fi+ if have jq && ! printf '%s' "$json" | jq . >/dev/null 2>&1; then+ fail "$name" "ops_os_json is not valid JSON"; return+ fi+ pass "$name"+}++test_os_detect_mjs() {+ local name="test_os_detect_mjs"+ if ! have node; then skip "$name" "node not installed"; return; fi+ local out+ if ! out="$(node "$REPO_ROOT/lib/os-detect.mjs" 2>/dev/null)"; then+ fail "$name" "node lib/os-detect.mjs exited non-zero"; return+ fi+ case "$out" in+ '{'*) ;;+ *) fail "$name" "stdout does not start with '{'"; return ;;+ esac+ if ! printf '%s' "$out" | grep -q '"os"'; then+ fail "$name" "stdout missing \"os\" key"; return+ fi+ pass "$name"+}++test_os_detect_parity() {+ local name="test_os_detect_parity"+ if ! have jq; then skip "$name" "jq not installed"; return; fi+ if ! have node; then skip "$name" "node not installed"; return; fi+ local sh_os mjs_os+ # shellcheck disable=SC1091+ source "$REPO_ROOT/lib/os-detect.sh"+ sh_os="$(ops_os_json | jq -r .os 2>/dev/null || true)"+ mjs_os="$(node "$REPO_ROOT/lib/os-detect.mjs" 2>/dev/null | jq -r .os 2>/dev/null || true)"+ if [[ -z "$sh_os" || -z "$mjs_os" ]]; then+ fail "$name" "could not extract .os (sh='$sh_os', mjs='$mjs_os')"; return+ fi+ if [[ "$sh_os" != "$mjs_os" ]]; then+ fail "$name" "parity mismatch: sh='$sh_os' mjs='$mjs_os'"; return+ fi+ pass "$name"+}++test_credential_backends_available() {+ local name="test_credential_backends_available"+ local out+ if ! out="$(bash "$REPO_ROOT/lib/credential-store.sh" backends 2>/dev/null)"; then+ fail "$name" "credential-store.sh backends exited non-zero"; return+ fi+ if [[ -z "${out//[[:space:]]/}" ]]; then+ fail "$name" "no backends printed"; return+ fi+ if ! printf '%s' "$out" | grep -q 'plaintext-json'; then+ fail "$name" "plaintext-json fallback missing from backends list"; return+ fi+ pass "$name"+}++_roundtrip() {+ # _roundtrip <test-name> <backend> [extra-env-assignment]+ local name="$1" backend="$2" extra_env="${3:-}"+ local svc="claude-ops-test" acct="smoke-$(rand_suffix)"+ local secret="s3cr3t-$(rand_suffix)"+ local store="$REPO_ROOT/lib/credential-store.sh"+ local env_prefix="CLAUDE_OPS_CRED_BACKEND=$backend"+ [[ -n "$extra_env" ]] && env_prefix="$env_prefix $extra_env"++ if ! eval "$env_prefix bash \"$store\" set \"$svc\" \"$acct\" \"$secret\"" \+ >/dev/null 2>"$TMP_WORK/err"; then+ fail "$name" "set failed: $(cat "$TMP_WORK/err")"; return+ fi+ local got+ if ! got="$(eval "$env_prefix bash \"$store\" get \"$svc\" \"$acct\"" 2>"$TMP_WORK/err")"; then+ fail "$name" "get failed: $(cat "$TMP_WORK/err")"; return+ fi+ if [[ "$got" != "$secret" ]]; then+ fail "$name" "roundtrip mismatch: expected '$secret' got '$got'"; return+ fi+ if ! eval "$env_prefix bash \"$store\" delete \"$svc\" \"$acct\"" \+ >/dev/null 2>"$TMP_WORK/err"; then+ fail "$name" "delete failed: $(cat "$TMP_WORK/err")"; return+ fi+ pass "$name"+}++test_credential_roundtrip_plaintext() {+ _roundtrip "test_credential_roundtrip_plaintext" "plaintext-json"+}++test_credential_roundtrip_encjson() {+ _roundtrip "test_credential_roundtrip_encjson" "enc-json" "CLAUDE_OPS_MASTER_KEY=test-key-$$"+}++test_credential_native_if_available() {+ local name="test_credential_native_if_available"+ # shellcheck disable=SC1091+ source "$REPO_ROOT/lib/os-detect.sh" 2>/dev/null || true+ local backend+ backend="$(ops_keyring_backend 2>/dev/null || true)"+ if [[ -z "$backend" || "$backend" == "none" ]]; then+ skip "$name" "no native keyring backend on this host"; return+ fi+ local svc="claude-ops-test" acct="smoke-native-$(rand_suffix)"+ local secret="native-$(rand_suffix)"+ local store="$REPO_ROOT/lib/credential-store.sh"+ if ! CLAUDE_OPS_CRED_BACKEND="$backend" bash "$store" set "$svc" "$acct" "$secret" \+ >/dev/null 2>"$TMP_WORK/err"; then+ skip "$name" "native backend '$backend' unavailable/locked on CI: $(cat "$TMP_WORK/err")"; return+ fi+ local got+ if ! got="$(CLAUDE_OPS_CRED_BACKEND="$backend" bash "$store" get "$svc" "$acct" 2>"$TMP_WORK/err")"; then+ CLAUDE_OPS_CRED_BACKEND="$backend" bash "$store" delete "$svc" "$acct" >/dev/null 2>&1 || true+ skip "$name" "native get failed (likely locked keyring): $(cat "$TMP_WORK/err")"; return+ fi+ CLAUDE_OPS_CRED_BACKEND="$backend" bash "$store" delete "$svc" "$acct" >/dev/null 2>&1 || true+ if [[ "$got" != "$secret" ]]; then+ fail "$name" "native roundtrip mismatch: expected '$secret' got '$got'"; return+ fi+ pass "$name"+}++test_credential_mjs_cli() {+ local name="test_credential_mjs_cli"+ if ! have node; then skip "$name" "node not installed"; return; fi+ local out+ if ! out="$(node "$REPO_ROOT/lib/credential-store.mjs" backends 2>/dev/null)"; then+ fail "$name" "node credential-store.mjs backends exited non-zero"; return+ fi+ if [[ -z "${out//[[:space:]]/}" ]]; then+ fail "$name" "mjs backends output is empty"; return+ fi+ pass "$name"+}++# ---- run ---------------------------------------------------------------------+printf '# claude-ops smoke suite (XDG_DATA_HOME=%s)\n' "$XDG_DATA_HOME"++test_os_detect_sh+test_os_detect_mjs+test_os_detect_parity+test_credential_backends_available+test_credential_roundtrip_plaintext+test_credential_roundtrip_encjson+test_credential_native_if_available+test_credential_mjs_cli++printf '\n# %d PASSED / %d TOTAL (skipped: %d, failed: %d)\n' \+ "$PASS" "$TOTAL" "$SKIP" "$FAIL"++[[ "$FAIL" -eq 0 ]] || exit 1+exit 0