From b86cce27277a74fe34eccbdf43dd16319ef60361 Mon Sep 17 00:00:00 2001 From: r Date: Sat, 28 Nov 2026 16:28:16 -0500 Subject: [PATCH] fix(helpers): close home-delete gap and harden generated helpers (#5176) - pre-bash (shipped helpers, generated fallback, ruflo-mods guard): a recursive delete of ~, ~/, ~user, $HOME, ${HOME} or "$HOME"/* is now read as a root delete and blocked (exit 2). Paths below home are unaffected. ruflo-mods 0.17.5 -> 0.17.6. - statusline: sqlite3/sh/npx resolve only from absolute PATH entries outside the project, children get that filtered PATH, git runs via execFileSync(sh, ['-c', script]), and a non-numeric total_cost_usd no longer throws. - hook-handler: post-edit dedup falls back to session_id only for session-end; "Updated error handling" is no longer a failed edit. - intelligence.cjs (and the generated stub): a corrupt store is kept as .corrupt, writes are temp+rename, consolidate() claims pending-insights.jsonl by rename instead of truncating it. - session.cjs (both copies and both generators): guarded JSON.parse, missing metrics/startedAt, CLAUDE_PROJECT_DIR, CLI only when require.main === module. - auto-commit.sh: AUTO_PUSH defaults to false, stages tracked files only (git add -u; file mode still commits the named file), no hardcoded Co-Authored-By trailer. helpers.manifest.json is intentionally not re-signed; the maintainer re-signs it. Co-Authored-By: RuFlo --- .claude/helpers/auto-commit.sh | 45 +-- .claude/helpers/hook-handler.cjs | 14 +- .claude/helpers/intelligence.cjs | 55 +++- .claude/helpers/session.cjs | 72 ++++- .claude/helpers/statusline.cjs | 84 +++-- plugins/ruflo-mods/.claude-plugin/plugin.json | 2 +- plugins/ruflo-mods/CHANGELOG.md | 3 + .../hooks/guard/dangerous-command.ts | 5 +- .../cli/.claude/helpers/auto-commit.sh | 45 +-- .../cli/.claude/helpers/hook-handler.cjs | 14 +- .../cli/.claude/helpers/intelligence.cjs | 55 +++- .../cli/.claude/helpers/session.cjs | 110 +++++-- .../cli/.claude/helpers/statusline.cjs | 84 +++-- .../issue-5176-generated-helpers.test.ts | 304 ++++++++++++++++++ .../cli/__tests__/mods/mods-guard.test.ts | 7 +- .../cli/src/init/helpers-generator.ts | 282 ++++++++++++---- 16 files changed, 959 insertions(+), 222 deletions(-) create mode 100644 v3/@claude-flow/cli/__tests__/issue-5176-generated-helpers.test.ts diff --git a/.claude/helpers/auto-commit.sh b/.claude/helpers/auto-commit.sh index cdecccff88..acc86e4a89 100755 --- a/.claude/helpers/auto-commit.sh +++ b/.claude/helpers/auto-commit.sh @@ -13,7 +13,8 @@ NC='\033[0m' # Configuration MIN_CHANGES=${MIN_CHANGES:-1} COMMIT_PREFIX=${COMMIT_PREFIX:-"checkpoint"} -AUTO_PUSH=${AUTO_PUSH:-true} +# #5176: pushing is opt-in (AUTO_PUSH=true); a local checkpoint never leaves the machine by default. +AUTO_PUSH=${AUTO_PUSH:-false} log() { echo -e "${GREEN}[auto-commit]${NC} $1" @@ -27,17 +28,17 @@ error() { echo -e "${RED}[auto-commit]${NC} $1" } -# Check if there are changes to commit +# Check if there are changes to commit. Untracked files are not counted: they +# are never staged automatically (#5176). has_changes() { - ! git diff --quiet HEAD 2>/dev/null || ! git diff --cached --quiet 2>/dev/null || [ -n "$(git ls-files --others --exclude-standard)" ] + ! git diff --quiet HEAD 2>/dev/null || ! git diff --cached --quiet 2>/dev/null } -# Count changes +# Count changes to tracked files count_changes() { local staged=$(git diff --cached --numstat | wc -l) local unstaged=$(git diff --numstat | wc -l) - local untracked=$(git ls-files --others --exclude-standard | wc -l) - echo $((staged + unstaged + untracked)) + echo $((staged + unstaged)) } # Main auto-commit function @@ -51,13 +52,21 @@ auto_commit() { return 1 fi - # Check for changes - if ! has_changes; then - log "No changes to commit" - return 0 + # Check for changes. A file named explicitly (file mode) may be new: it counts by itself. + local change_count + if [ -n "$file" ] && [ -f "$file" ]; then + if [ -z "$(git status --porcelain -- "$file")" ]; then + log "No changes to commit" + return 0 + fi + change_count=1 + else + if ! has_changes; then + log "No changes to commit" + return 0 + fi + change_count=$(count_changes) fi - - local change_count=$(count_changes) if [ "$change_count" -lt "$MIN_CHANGES" ]; then log "Only $change_count change(s), skipping (min: $MIN_CHANGES)" return 0 @@ -68,8 +77,10 @@ auto_commit() { git add "$file" log "Staged: $file" else - git add -A - log "Staged all changes ($change_count files)" + # #5176: tracked files only. `git add -A` also staged untracked files, + # such as a new .env or key file, into an automatic commit. + git add -u + log "Staged tracked changes ($change_count files)" fi # Create commit message @@ -88,9 +99,7 @@ Automatic checkpoint created by Claude Code - Timestamp: $timestamp - Changes: $change_count file(s) -🤖 Generated with [Claude Code](https://claude.com/claude-code) - -Co-Authored-By: Claude Opus 4.5 " --quiet 2>/dev/null; then +🤖 Generated with [Claude Code](https://claude.com/claude-code)" --quiet 2>/dev/null; then log "Created commit: $message" # Push if enabled @@ -169,7 +178,7 @@ case "${1:-batch}" in echo "Usage: $0 {batch|file|push|check} [args]" echo "" echo "Commands:" - echo " batch [message] Commit all changes with optional message" + echo " batch [message] Commit changes to tracked files with optional message" echo " file [msg] Commit specific file" echo " push Push without committing" echo " check Check if there are uncommitted changes" diff --git a/.claude/helpers/hook-handler.cjs b/.claude/helpers/hook-handler.cjs index d02c5518d4..2d613f2b78 100755 --- a/.claude/helpers/hook-handler.cjs +++ b/.claude/helpers/hook-handler.cjs @@ -793,8 +793,10 @@ function claimSideEffectEvent(family, stdinData, event) { if (/^(1|true|yes|on)$/i.test(process.env.RUFLO_DISABLE_HOOK_DEDUP || '')) return true; try { const crypto = require('crypto'); - const eventId = event?.tool_use_id || event?.toolUseId || - event?.session_id || event?.sessionId || event?.hook_event_id; + // #5176: a session id names one event only for session-end. Keyed on it, every post-edit after + // the first in a session (a payload without a tool_use_id) was dropped as a duplicate. + const sessionKey = family === 'session-end' ? (event?.session_id || event?.sessionId) : undefined; + const eventId = event?.tool_use_id || event?.toolUseId || sessionKey || event?.hook_event_id; const payloadIdentity = eventId ? `event:${eventId}` : `payload:${(stdinData || '').trim()}|bucket:${Math.floor(Date.now() / 2000)}`; @@ -882,7 +884,8 @@ async function main() { if (!hi || typeof hi !== 'object') return false; const tr = hi.tool_response != null ? hi.tool_response : (hi.toolResponse != null ? hi.toolResponse : hi.result); if (tr == null) return false; - if (typeof tr === 'string') return /\b(error|failed|failure|exception|not found|no such|permission denied|traceback)\b/i.test(tr); + // #5176: a leading error word, or an OS message; "Updated error handling" is a success. + if (typeof tr === 'string') return /^\s*(?:error|failed|failure|fatal|exception|traceback)\b||\b(?:command not found|no such file or directory|permission denied)\b/i.test(tr); if (typeof tr === 'object') { if (tr.is_error === true || tr.isError === true || tr.success === false || tr.error != null) return true; const code = tr.exit_code != null ? tr.exit_code : (tr.exitCode != null ? tr.exitCode : tr.code); @@ -1019,7 +1022,10 @@ const handlers = { let word = '', mask = '', quote = '', started = false, redirect = false let ansiNul = false // a NUL inside $'...' ends that string, as in bash let inRm = false, optionsEnded = false, recursive = false, force = false, root = false - const isRoot = (operand) => { + // A home-wide operand is a root too (#5176): ~, ~user, $home and ${home} name a directory the shell + // fills in, so a recursive delete of ~, ~/ or "$HOME"/* reads as one of /, / or /*. A path below it (~/build) is not. + const isRoot = (raw) => { + const operand = raw.replace(/^(?:~[^/]*|\$home(?![a-z0-9_])|\$\{home\})/, '/') if (!operand.startsWith('/')) return false const parts = [] for (const part of operand.split('/')) { diff --git a/.claude/helpers/intelligence.cjs b/.claude/helpers/intelligence.cjs index 797cf7c14c..06bc9fa8bb 100755 --- a/.claude/helpers/intelligence.cjs +++ b/.claude/helpers/intelligence.cjs @@ -120,12 +120,41 @@ function readJSON(filePath) { return null; } } catch { /* file may not exist yet */ } + let text; try { - if (fs.existsSync(filePath)) return JSON.parse(fs.readFileSync(filePath, 'utf-8')); - } catch { /* corrupt file — start fresh */ } + if (!fs.existsSync(filePath)) return null; + text = fs.readFileSync(filePath, 'utf-8'); + return JSON.parse(text); + } catch { + // #5176: a corrupt store starts fresh, but the next write would replace it, so keep + // its bytes as .corrupt first. + if (text !== undefined && text.trim()) backupCorrupt(filePath, text); + } return null; } +function backupCorrupt(filePath, text) { + try { + // Once per corruption: every read sees the same bytes until a write replaces them. + try { if (fs.statSync(filePath + '.corrupt').size === Buffer.byteLength(text)) return; } catch { /* no copy yet */ } + atomicWrite(filePath + '.corrupt', text); + process.stderr.write('[INTELLIGENCE] WARN: ' + path.basename(filePath) + ' is not valid JSON; kept a copy as ' + path.basename(filePath) + '.corrupt\n'); + } catch { /* best effort */ } +} + +// Temp file + rename: a reader never sees a half-written file, and two writers +// never interleave their bytes in one file. +function atomicWrite(filePath, text, mode) { + const tmp = filePath + '.' + process.pid + '.' + Math.random().toString(36).slice(2, 8) + '.tmp'; + try { + fs.writeFileSync(tmp, text, mode ? { encoding: 'utf-8', mode, flag: 'wx' } : { encoding: 'utf-8', flag: 'wx' }); + fs.renameSync(tmp, filePath); + } catch (e) { + try { fs.unlinkSync(tmp); } catch { /* nothing to clean */ } + throw e; + } +} + // Atomic (temp + rename): auto-memory-hook.mjs reads and writes the same store // from the session hooks, and a reader must never see a half-written file (#4058). function writeJSON(filePath, data) { @@ -302,7 +331,8 @@ function sessionSet(key, value) { if (!session.context) session.context = {}; session.context[key] = value; session.updatedAt = new Date().toISOString(); - fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2), 'utf-8'); + // #5176: temp + rename, so session.cjs never reads a half-written current.json. + atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2)); } catch { /* best effort */ } } @@ -891,7 +921,7 @@ function recordEdit(file, success) { try { if (fs.statSync(PENDING_PATH).size > 512 * 1024) { const lines = fs.readFileSync(PENDING_PATH, 'utf-8').split('\n').filter(Boolean); - if (lines.length > 2000) fs.writeFileSync(PENDING_PATH, lines.slice(-2000).join('\n') + '\n', 'utf-8'); + if (lines.length > 2000) atomicWrite(PENDING_PATH, lines.slice(-2000).join('\n') + '\n'); } } catch (e) { /* non-fatal */ } } @@ -960,8 +990,17 @@ function consolidate() { // 1. Process pending insights let newEntries = 0; - if (fs.existsSync(PENDING_PATH)) { - const lines = fs.readFileSync(PENDING_PATH, 'utf-8').trim().split('\n').filter(Boolean); + // #5176: claim the pending log by renaming it, then read the claimed copy. Reading and then + // truncating in place lost every line a concurrent recordEdit appended in between; a + // writer that appends after the rename starts a fresh file for the next consolidation. + const claimed = PENDING_PATH + '.' + process.pid + '.' + Date.now() + '.claimed'; + let claimedText = null; + try { + fs.renameSync(PENDING_PATH, claimed); + claimedText = fs.readFileSync(claimed, 'utf-8'); + } catch { /* nothing pending, or another consolidation claimed it */ } + if (claimedText !== null) { + const lines = claimedText.trim().split('\n').filter(Boolean); const editCounts = {}; for (const line of lines) { try { @@ -994,8 +1033,8 @@ function consolidate() { } } - // Clear pending - fs.writeFileSync(PENDING_PATH, '', 'utf-8'); + // The claimed lines are processed: drop the claimed copy. + try { fs.unlinkSync(claimed); } catch { /* already gone */ } } // 2. Confidence decay for unaccessed entries diff --git a/.claude/helpers/session.cjs b/.claude/helpers/session.cjs index 4a63c3d977..b534820485 100644 --- a/.claude/helpers/session.cjs +++ b/.claude/helpers/session.cjs @@ -11,9 +11,12 @@ const os = require('os'); const platform = os.platform(); const homeDir = os.homedir(); +// #5176: hooks run with CLAUDE_PROJECT_DIR set; the cwd may be a subdirectory. +const PROJECT_ROOT = process.env.CLAUDE_PROJECT_DIR || process.cwd(); +const DEFAULT_METRICS = { edits: 0, commands: 0, tasks: 0, errors: 0 }; function getDataDir() { - const localDir = path.join(process.cwd(), '.claude-flow', 'sessions'); + const localDir = path.join(PROJECT_ROOT, '.claude-flow', 'sessions'); if (fs.existsSync(path.dirname(localDir))) { return localDir; } @@ -48,8 +51,8 @@ function archiveId(id) { // The project session directory must resolve inside the project (no // symlinked escape). The per-user fallback directory is not project-owned. function assertSessionDirContained() { - if (SESSION_DIR !== path.join(process.cwd(), '.claude-flow', 'sessions')) return; - const root = fs.realpathSync(process.cwd()); + if (SESSION_DIR !== path.join(PROJECT_ROOT, '.claude-flow', 'sessions')) return; + const root = fs.realpathSync(PROJECT_ROOT); // Resolve the deepest part of the path that exists (lstat: a symlink counts), // so a symlinked .claude-flow is refused before anything is created under it. let dir = SESSION_DIR; @@ -74,6 +77,31 @@ function atomicWrite(file, data) { fs.renameSync(tmp, file); } +// #5176: current.json may be corrupt or partial; read it as null instead of throwing out of a hook. +function readSession() { + try { + const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); + return session && typeof session === 'object' && !Array.isArray(session) ? session : null; + } catch { return null; } +} + +// A corrupt current.json is kept as current.json.corrupt, so the next session starts clean. +function setAsideCorrupt() { + try { + assertSessionDirContained(); + fs.renameSync(SESSION_FILE, SESSION_FILE + '.corrupt'); + } catch { /* best effort */ } +} + +function elapsedMs(startedAt) { + const started = Date.parse(startedAt); + return Number.isFinite(started) ? Date.now() - started : null; +} + +function formatMinutes(ms) { + return ms === null ? 'unknown' : `${Math.round(ms / 1000 / 60)} minutes`; +} + function ensureDir(dir) { if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); @@ -89,9 +117,9 @@ const commands = { id: sessionId, startedAt: new Date().toISOString(), platform: platform, - cwd: process.cwd(), + cwd: PROJECT_ROOT, context: {}, - metrics: { edits: 0, commands: 0, tasks: 0, errors: 0 } + metrics: { ...DEFAULT_METRICS } }; atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2)); console.log(`Session started: ${sessionId}`); @@ -103,7 +131,12 @@ const commands = { console.log('No session to restore'); return null; } - const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); + const session = readSession(); + if (!session) { + console.log('Session file corrupted; starting fresh'); + setAsideCorrupt(); + return commands.start(); + } session.restoredAt = new Date().toISOString(); atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2)); console.log(`Session restored: ${session.id}`); @@ -115,9 +148,14 @@ const commands = { console.log('No active session'); return null; } - const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); + const session = readSession(); + if (!session) { + console.log('Session file corrupted; set aside as current.json.corrupt'); + setAsideCorrupt(); + return null; + } session.endedAt = new Date().toISOString(); - session.duration = Date.now() - new Date(session.startedAt).getTime(); + session.duration = elapsedMs(session.startedAt); // Archive under a validated name; a crafted id cannot pick the path. const id = archiveId(session.id); @@ -125,7 +163,7 @@ const commands = { fs.unlinkSync(SESSION_FILE); console.log(`Session ended: ${id}`); - console.log(`Duration: ${Math.round(session.duration / 1000 / 60)} minutes`); + console.log(`Duration: ${formatMinutes(session.duration)}`); return session; }, @@ -134,12 +172,16 @@ const commands = { console.log('No active session'); return null; } - const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); - const duration = Date.now() - new Date(session.startedAt).getTime(); + const session = readSession(); + if (!session) { + console.log('Session file corrupted'); + return null; + } + const duration = elapsedMs(session.startedAt); console.log(`Session: ${session.id}`); console.log(`Platform: ${session.platform}`); console.log(`Started: ${session.startedAt}`); - console.log(`Duration: ${Math.round(duration / 1000 / 60)} minutes`); + console.log(`Duration: ${formatMinutes(duration)}`); return session; }, @@ -147,8 +189,10 @@ const commands = { if (!hasSessionFile()) { return null; } - const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); - if (session.metrics[name] !== undefined) { + const session = readSession(); + if (!session) return null; + if (!session.metrics || typeof session.metrics !== 'object') session.metrics = { ...DEFAULT_METRICS }; + if (typeof session.metrics[name] === 'number') { session.metrics[name]++; atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2)); } diff --git a/.claude/helpers/statusline.cjs b/.claude/helpers/statusline.cjs index 4b8d7348ca..ac2fce3ebc 100755 --- a/.claude/helpers/statusline.cjs +++ b/.claude/helpers/statusline.cjs @@ -245,12 +245,18 @@ function getStatuslineData() { .filter((bin) => shellSafe(bin) && shellSafe(process.execPath)) .map((bin) => '"' + process.execPath + '" "' + bin + '" hooks statusline --json') // --prefix: npx resolves the package from HELPER_ROOT, not the project. - .concat(shellSafe(HELPER_ROOT) ? ['npx --prefer-offline --prefix "' + HELPER_ROOT + '" @claude-flow/cli hooks statusline --json'] : []); + .concat((() => { + // #5176: npx from an absolute PATH entry outside the project, never a project-local npx.cmd. + const npx = resolveExecutable('npx'); + return npx && shellSafe(npx) && shellSafe(HELPER_ROOT) + ? ['"' + npx + '" --prefer-offline --prefix "' + HELPER_ROOT + '" @claude-flow/cli hooks statusline --json'] + : []; + })()); for (const cmd of cmds) { try { const raw = execSync( cmd, - { encoding: 'utf-8', timeout: 8000, stdio: ['pipe', 'pipe', 'pipe'], cwd: CWD, windowsHide: true } + { encoding: 'utf-8', timeout: 8000, stdio: ['pipe', 'pipe', 'pipe'], cwd: CWD, env: getSafeEnv(), windowsHide: true } ).trim(); // The CLI may emit preamble lines before the JSON — find the first '{'. const jsonStart = raw.indexOf('{'); @@ -670,28 +676,63 @@ const c = { brightWhite: '\x1b[1;37m', }; -// Safe execSync with strict timeout (returns empty string on failure) -function safeExec(cmd, timeoutMs) { - try { - return execSync(cmd, { - encoding: 'utf-8', - timeout: timeoutMs || 2000, - stdio: ['pipe', 'pipe', 'pipe'], - // Windows: without this, every execSync spawns cmd.exe /d /s /c which - // flashes a visible console window every render (~1/min via the 60s - // cache TTL). windowsHide runs the child in a hidden window instead. - // No-op on POSIX. Fix for #2XXX (user report: "cmd prompt keeps opening"). - windowsHide: true, - }).trim(); - } catch { - return ''; +// #5176: a bare program name is looked up only in absolute PATH entries outside the project. +// Windows searches the current directory (the project) before PATH, and a POSIX PATH with an +// empty or relative entry does the same, so a sqlite3.exe, sh.exe or npx.cmd committed to a +// repository would otherwise run on every render. Children get the same filtered PATH +// (SAFE_ENV), so the git that sh runs, or what the CLI spawns, is not a project file either. +let safePathEntries = null; +function getSafePathEntries() { + if (safePathEntries) return safePathEntries; + const project = path.resolve(CWD); + const inProject = (dir) => { + const rel = path.relative(project, dir); + return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel)); + }; + safePathEntries = (process.env.PATH || '').split(path.delimiter) + .filter((dir) => dir && path.isAbsolute(dir) && !inProject(path.resolve(dir))); + return safePathEntries; +} +let safeEnv = null; +function getSafeEnv() { + if (safeEnv) return safeEnv; + safeEnv = {}; + for (const [key, value] of Object.entries(process.env)) { + if (key.toUpperCase() !== 'PATH') safeEnv[key] = value; } + safeEnv.PATH = getSafePathEntries().join(path.delimiter); + return safeEnv; +} +// Returns an absolute path, or null. +const resolvedExecutables = new Map(); +function resolveExecutable(name) { + if (resolvedExecutables.has(name)) return resolvedExecutables.get(name); + const isWin = process.platform === 'win32'; + const exts = isWin ? (process.env.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean) : ['']; + let found = null; + for (const dir of getSafePathEntries()) { + if (found) break; + for (const ext of exts) { + const candidate = path.join(dir, name + ext); + try { + if (!fs.statSync(candidate).isFile()) continue; + if (!isWin) fs.accessSync(candidate, fs.constants.X_OK); + found = candidate; + break; + } catch { /* not here */ } + } + } + resolvedExecutables.set(name, found); + return found; } // safeExec without a shell: the path in args is never parsed as shell syntax. function safeExecFile(file, args, timeoutMs) { + const resolved = path.isAbsolute(file) ? file : resolveExecutable(file); + if (!resolved) return ''; try { - return execFileSync(file, args, { + return execFileSync(resolved, args, { + env: getSafeEnv(), encoding: 'utf-8', timeout: timeoutMs || 2000, stdio: ['pipe', 'pipe', 'pipe'], @@ -778,7 +819,9 @@ function getGitInfo() { 'git rev-list --left-right --count HEAD...@{upstream} 2>/dev/null || echo "0 0"', ].join('; '); - const raw = safeExec("sh -c '" + script + "'", 3000); + // #5176: sh gets the script as one argument. Through a shell, cmd.exe read the single quotes + // literally, so the branch never showed on Windows. + const raw = safeExecFile('sh', ['-c', script], 3000); if (!raw) { // Cache even the empty result — if git is slow/unavailable, we don't want // to re-attempt on every render either. @@ -897,7 +940,8 @@ function getCostFromStdin() { const mins = Math.floor(durationMs / 60000); const secs = Math.floor((durationMs % 60000) / 1000); return { - costUsd: data.cost.total_cost_usd || 0, + // #5176: a string or other non-number cost must not reach .toFixed() and blank the line. + costUsd: Number.isFinite(Number(data.cost.total_cost_usd)) ? Number(data.cost.total_cost_usd) : 0, duration: mins > 0 ? mins + 'm' + secs + 's' : secs + 's', }; } diff --git a/plugins/ruflo-mods/.claude-plugin/plugin.json b/plugins/ruflo-mods/.claude-plugin/plugin.json index 87a27c680c..1a844ccc99 100644 --- a/plugins/ruflo-mods/.claude-plugin/plugin.json +++ b/plugins/ruflo-mods/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "ruflo-mods", "description": "ruflo as a Claude Code mod (function hooks, ADR-404): in-process prompt routing, edit learning signals, tighten-only tool checks from ruflo policy, the cost-tracker budget ladder, a mod trust gate for newly installed mods, and the $.ruflo noun other mods compose their status with. Opt-in and removable: the classic hook-handler hooks stay the default and take every event back whenever the mod is not loaded.", - "version": "0.17.5", + "version": "0.17.6", "repository": "https://github.com/ruvnet/ruflo", "author": { "name": "ruvnet", diff --git a/plugins/ruflo-mods/CHANGELOG.md b/plugins/ruflo-mods/CHANGELOG.md index fcb819d39e..fa59b7899c 100644 --- a/plugins/ruflo-mods/CHANGELOG.md +++ b/plugins/ruflo-mods/CHANGELOG.md @@ -2,6 +2,9 @@ Newest first. One `## — ` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; older versions: `git log -- plugins/ruflo-mods`. +## 0.17.6 — 2026-11-28 +- fix: the dangerous-command guard reads a home-wide operand as a root (#5176): a recursive force delete of `~`, `~/`, `~user`, `$HOME`, `${HOME}` or `"$HOME"/*` is refused, as `/` and `/*` already were. A path below home (`~/build`) is still allowed. Same change in both classic `hook-handler.cjs` copies and the generated fallback. + ## 0.17.5 — 2026-11-22 - fix: a test, build or lint command that exits 0 without checking anything is no longer a learning-loop verifier, so the turn is not recorded as verified-success (#5067): help and version (`npm test --help`, `tsc -v`), listings (`npx vitest list`, `npx jest --listTests`, `pytest --collect-only`, `cargo nextest list`, `go test -list`, `dotnet test -t`), dry runs and config dumps (`make -n`, `tsc -b --dry`, `eslint --env-info`), compile-only runs (`cargo test --no-run`, `go test -c`) and `--if-present` scripts. Commands are read as bash splits them, so a real run whose quoted arguments contain those words still verifies, and a command with a shell comment is refused (`npm run build # && npm test` runs only the build). - fix: the verifier command kept as evidence is screened for secret shapes, as given and as stored; one that carries a secret keeps its kind and outcome and is stored as `[redacted]`. diff --git a/plugins/ruflo-mods/hooks/guard/dangerous-command.ts b/plugins/ruflo-mods/hooks/guard/dangerous-command.ts index 736444dc2f..1042b70ba5 100644 --- a/plugins/ruflo-mods/hooks/guard/dangerous-command.ts +++ b/plugins/ruflo-mods/hooks/guard/dangerous-command.ts @@ -15,7 +15,10 @@ function hasRootDelete(command: string, depth = 0): boolean { let word = '', mask = '', quote = '', started = false, redirect = false let ansiNul = false // a NUL inside $'...' ends that string, as in bash let inRm = false, optionsEnded = false, recursive = false, force = false, root = false - const isRoot = (operand: string) => { + // A home-wide operand is a root too (#5176): ~, ~user, $home and ${home} name a directory the shell + // fills in, so a recursive delete of ~, ~/ or "$HOME"/* reads as one of /, / or /*. A path below it (~/build) is not. + const isRoot = (raw: string) => { + const operand = raw.replace(/^(?:~[^/]*|\$home(?![a-z0-9_])|\$\{home\})/, '/') if (!operand.startsWith('/')) return false const parts: string[] = [] for (const part of operand.split('/')) { diff --git a/v3/@claude-flow/cli/.claude/helpers/auto-commit.sh b/v3/@claude-flow/cli/.claude/helpers/auto-commit.sh index 19266bed1a..acc86e4a89 100755 --- a/v3/@claude-flow/cli/.claude/helpers/auto-commit.sh +++ b/v3/@claude-flow/cli/.claude/helpers/auto-commit.sh @@ -13,7 +13,8 @@ NC='\033[0m' # Configuration MIN_CHANGES=${MIN_CHANGES:-1} COMMIT_PREFIX=${COMMIT_PREFIX:-"checkpoint"} -AUTO_PUSH=${AUTO_PUSH:-true} +# #5176: pushing is opt-in (AUTO_PUSH=true); a local checkpoint never leaves the machine by default. +AUTO_PUSH=${AUTO_PUSH:-false} log() { echo -e "${GREEN}[auto-commit]${NC} $1" @@ -27,17 +28,17 @@ error() { echo -e "${RED}[auto-commit]${NC} $1" } -# Check if there are changes to commit +# Check if there are changes to commit. Untracked files are not counted: they +# are never staged automatically (#5176). has_changes() { - ! git diff --quiet HEAD 2>/dev/null || ! git diff --cached --quiet 2>/dev/null || [ -n "$(git ls-files --others --exclude-standard)" ] + ! git diff --quiet HEAD 2>/dev/null || ! git diff --cached --quiet 2>/dev/null } -# Count changes +# Count changes to tracked files count_changes() { local staged=$(git diff --cached --numstat | wc -l) local unstaged=$(git diff --numstat | wc -l) - local untracked=$(git ls-files --others --exclude-standard | wc -l) - echo $((staged + unstaged + untracked)) + echo $((staged + unstaged)) } # Main auto-commit function @@ -51,13 +52,21 @@ auto_commit() { return 1 fi - # Check for changes - if ! has_changes; then - log "No changes to commit" - return 0 + # Check for changes. A file named explicitly (file mode) may be new: it counts by itself. + local change_count + if [ -n "$file" ] && [ -f "$file" ]; then + if [ -z "$(git status --porcelain -- "$file")" ]; then + log "No changes to commit" + return 0 + fi + change_count=1 + else + if ! has_changes; then + log "No changes to commit" + return 0 + fi + change_count=$(count_changes) fi - - local change_count=$(count_changes) if [ "$change_count" -lt "$MIN_CHANGES" ]; then log "Only $change_count change(s), skipping (min: $MIN_CHANGES)" return 0 @@ -68,8 +77,10 @@ auto_commit() { git add "$file" log "Staged: $file" else - git add -A - log "Staged all changes ($change_count files)" + # #5176: tracked files only. `git add -A` also staged untracked files, + # such as a new .env or key file, into an automatic commit. + git add -u + log "Staged tracked changes ($change_count files)" fi # Create commit message @@ -88,9 +99,7 @@ Automatic checkpoint created by Claude Code - Timestamp: $timestamp - Changes: $change_count file(s) -🤖 Generated with [Claude Code](https://claude.com/claude-code) - -Co-Authored-By: Claude Opus 4.6 " --quiet 2>/dev/null; then +🤖 Generated with [Claude Code](https://claude.com/claude-code)" --quiet 2>/dev/null; then log "Created commit: $message" # Push if enabled @@ -169,7 +178,7 @@ case "${1:-batch}" in echo "Usage: $0 {batch|file|push|check} [args]" echo "" echo "Commands:" - echo " batch [message] Commit all changes with optional message" + echo " batch [message] Commit changes to tracked files with optional message" echo " file [msg] Commit specific file" echo " push Push without committing" echo " check Check if there are uncommitted changes" diff --git a/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs b/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs index d02c5518d4..2d613f2b78 100755 --- a/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs +++ b/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs @@ -793,8 +793,10 @@ function claimSideEffectEvent(family, stdinData, event) { if (/^(1|true|yes|on)$/i.test(process.env.RUFLO_DISABLE_HOOK_DEDUP || '')) return true; try { const crypto = require('crypto'); - const eventId = event?.tool_use_id || event?.toolUseId || - event?.session_id || event?.sessionId || event?.hook_event_id; + // #5176: a session id names one event only for session-end. Keyed on it, every post-edit after + // the first in a session (a payload without a tool_use_id) was dropped as a duplicate. + const sessionKey = family === 'session-end' ? (event?.session_id || event?.sessionId) : undefined; + const eventId = event?.tool_use_id || event?.toolUseId || sessionKey || event?.hook_event_id; const payloadIdentity = eventId ? `event:${eventId}` : `payload:${(stdinData || '').trim()}|bucket:${Math.floor(Date.now() / 2000)}`; @@ -882,7 +884,8 @@ async function main() { if (!hi || typeof hi !== 'object') return false; const tr = hi.tool_response != null ? hi.tool_response : (hi.toolResponse != null ? hi.toolResponse : hi.result); if (tr == null) return false; - if (typeof tr === 'string') return /\b(error|failed|failure|exception|not found|no such|permission denied|traceback)\b/i.test(tr); + // #5176: a leading error word, or an OS message; "Updated error handling" is a success. + if (typeof tr === 'string') return /^\s*(?:error|failed|failure|fatal|exception|traceback)\b||\b(?:command not found|no such file or directory|permission denied)\b/i.test(tr); if (typeof tr === 'object') { if (tr.is_error === true || tr.isError === true || tr.success === false || tr.error != null) return true; const code = tr.exit_code != null ? tr.exit_code : (tr.exitCode != null ? tr.exitCode : tr.code); @@ -1019,7 +1022,10 @@ const handlers = { let word = '', mask = '', quote = '', started = false, redirect = false let ansiNul = false // a NUL inside $'...' ends that string, as in bash let inRm = false, optionsEnded = false, recursive = false, force = false, root = false - const isRoot = (operand) => { + // A home-wide operand is a root too (#5176): ~, ~user, $home and ${home} name a directory the shell + // fills in, so a recursive delete of ~, ~/ or "$HOME"/* reads as one of /, / or /*. A path below it (~/build) is not. + const isRoot = (raw) => { + const operand = raw.replace(/^(?:~[^/]*|\$home(?![a-z0-9_])|\$\{home\})/, '/') if (!operand.startsWith('/')) return false const parts = [] for (const part of operand.split('/')) { diff --git a/v3/@claude-flow/cli/.claude/helpers/intelligence.cjs b/v3/@claude-flow/cli/.claude/helpers/intelligence.cjs index 797cf7c14c..06bc9fa8bb 100755 --- a/v3/@claude-flow/cli/.claude/helpers/intelligence.cjs +++ b/v3/@claude-flow/cli/.claude/helpers/intelligence.cjs @@ -120,12 +120,41 @@ function readJSON(filePath) { return null; } } catch { /* file may not exist yet */ } + let text; try { - if (fs.existsSync(filePath)) return JSON.parse(fs.readFileSync(filePath, 'utf-8')); - } catch { /* corrupt file — start fresh */ } + if (!fs.existsSync(filePath)) return null; + text = fs.readFileSync(filePath, 'utf-8'); + return JSON.parse(text); + } catch { + // #5176: a corrupt store starts fresh, but the next write would replace it, so keep + // its bytes as .corrupt first. + if (text !== undefined && text.trim()) backupCorrupt(filePath, text); + } return null; } +function backupCorrupt(filePath, text) { + try { + // Once per corruption: every read sees the same bytes until a write replaces them. + try { if (fs.statSync(filePath + '.corrupt').size === Buffer.byteLength(text)) return; } catch { /* no copy yet */ } + atomicWrite(filePath + '.corrupt', text); + process.stderr.write('[INTELLIGENCE] WARN: ' + path.basename(filePath) + ' is not valid JSON; kept a copy as ' + path.basename(filePath) + '.corrupt\n'); + } catch { /* best effort */ } +} + +// Temp file + rename: a reader never sees a half-written file, and two writers +// never interleave their bytes in one file. +function atomicWrite(filePath, text, mode) { + const tmp = filePath + '.' + process.pid + '.' + Math.random().toString(36).slice(2, 8) + '.tmp'; + try { + fs.writeFileSync(tmp, text, mode ? { encoding: 'utf-8', mode, flag: 'wx' } : { encoding: 'utf-8', flag: 'wx' }); + fs.renameSync(tmp, filePath); + } catch (e) { + try { fs.unlinkSync(tmp); } catch { /* nothing to clean */ } + throw e; + } +} + // Atomic (temp + rename): auto-memory-hook.mjs reads and writes the same store // from the session hooks, and a reader must never see a half-written file (#4058). function writeJSON(filePath, data) { @@ -302,7 +331,8 @@ function sessionSet(key, value) { if (!session.context) session.context = {}; session.context[key] = value; session.updatedAt = new Date().toISOString(); - fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2), 'utf-8'); + // #5176: temp + rename, so session.cjs never reads a half-written current.json. + atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2)); } catch { /* best effort */ } } @@ -891,7 +921,7 @@ function recordEdit(file, success) { try { if (fs.statSync(PENDING_PATH).size > 512 * 1024) { const lines = fs.readFileSync(PENDING_PATH, 'utf-8').split('\n').filter(Boolean); - if (lines.length > 2000) fs.writeFileSync(PENDING_PATH, lines.slice(-2000).join('\n') + '\n', 'utf-8'); + if (lines.length > 2000) atomicWrite(PENDING_PATH, lines.slice(-2000).join('\n') + '\n'); } } catch (e) { /* non-fatal */ } } @@ -960,8 +990,17 @@ function consolidate() { // 1. Process pending insights let newEntries = 0; - if (fs.existsSync(PENDING_PATH)) { - const lines = fs.readFileSync(PENDING_PATH, 'utf-8').trim().split('\n').filter(Boolean); + // #5176: claim the pending log by renaming it, then read the claimed copy. Reading and then + // truncating in place lost every line a concurrent recordEdit appended in between; a + // writer that appends after the rename starts a fresh file for the next consolidation. + const claimed = PENDING_PATH + '.' + process.pid + '.' + Date.now() + '.claimed'; + let claimedText = null; + try { + fs.renameSync(PENDING_PATH, claimed); + claimedText = fs.readFileSync(claimed, 'utf-8'); + } catch { /* nothing pending, or another consolidation claimed it */ } + if (claimedText !== null) { + const lines = claimedText.trim().split('\n').filter(Boolean); const editCounts = {}; for (const line of lines) { try { @@ -994,8 +1033,8 @@ function consolidate() { } } - // Clear pending - fs.writeFileSync(PENDING_PATH, '', 'utf-8'); + // The claimed lines are processed: drop the claimed copy. + try { fs.unlinkSync(claimed); } catch { /* already gone */ } } // 2. Confidence decay for unaccessed entries diff --git a/v3/@claude-flow/cli/.claude/helpers/session.cjs b/v3/@claude-flow/cli/.claude/helpers/session.cjs index 34c45c773a..03f389f6c0 100644 --- a/v3/@claude-flow/cli/.claude/helpers/session.cjs +++ b/v3/@claude-flow/cli/.claude/helpers/session.cjs @@ -8,11 +8,14 @@ const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); -const SESSION_DIR = path.join(process.cwd(), '.claude-flow', 'sessions'); +// #5176: hooks run with CLAUDE_PROJECT_DIR set; the cwd may be a subdirectory. +const PROJECT_ROOT = process.env.CLAUDE_PROJECT_DIR || process.cwd(); +const SESSION_DIR = path.join(PROJECT_ROOT, '.claude-flow', 'sessions'); const SESSION_FILE = path.join(SESSION_DIR, 'current.json'); // Archive names are generated by start(); anything else in current.json is // untrusted project content and must never pick a path. const SESSION_ID = /^session-\d+$/; +const DEFAULT_METRICS = { edits: 0, commands: 0, tasks: 0, errors: 0 }; // current.json lives in the opened project. A symlink there must never be read // or written through, so only a regular file counts as an active session. @@ -26,7 +29,7 @@ function archiveId(id) { // The session directory must resolve inside the project (no symlinked escape). function assertSessionDirContained() { - const root = fs.realpathSync(process.cwd()); + const root = fs.realpathSync(PROJECT_ROOT); // Resolve the deepest part of the path that exists (lstat: a symlink counts), // so a symlinked .claude-flow is refused before anything is created under it. let dir = SESSION_DIR; @@ -59,20 +62,42 @@ function atomicWrite(file, data) { fs.renameSync(tmp, file); } +// #5176: current.json is project content. A corrupt or non-object file reads as +// null instead of throwing out of a hook. +function readSession() { + try { + const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); + return session && typeof session === 'object' && !Array.isArray(session) ? session : null; + } catch { return null; } +} + +// A corrupt current.json is moved aside (kept as current.json.corrupt), so the +// next session starts clean and the bytes are not lost. +function setAsideCorrupt() { + try { + assertSessionDirContained(); + fs.renameSync(SESSION_FILE, SESSION_FILE + '.corrupt'); + } catch { /* best effort */ } +} + +function elapsedMs(startedAt) { + const started = Date.parse(startedAt); + return Number.isFinite(started) ? Date.now() - started : null; +} + +function formatMinutes(ms) { + return ms === null ? 'unknown' : `${Math.round(ms / 1000 / 60)} minutes`; +} + const commands = { start: () => { const sessionId = `session-${Date.now()}`; const session = { id: sessionId, startedAt: new Date().toISOString(), - cwd: process.cwd(), + cwd: PROJECT_ROOT, context: {}, - metrics: { - edits: 0, - commands: 0, - tasks: 0, - errors: 0, - }, + metrics: { ...DEFAULT_METRICS }, }; assertSessionDirContained(); @@ -89,13 +114,12 @@ const commands = { return null; } - let session; - try { - session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); - } catch (e) { + const session = readSession(); + if (!session) { // #2307: corrupted session file (e.g. from a pre-atomic-write race). // Don't throw — start a fresh session so the hook recovers cleanly. - console.log(`Session file corrupted (${e.message}); starting fresh`); + console.log('Session file corrupted; starting fresh'); + setAsideCorrupt(); return commands.start(); } session.restoredAt = new Date().toISOString(); @@ -111,9 +135,14 @@ const commands = { return null; } - const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); + const session = readSession(); + if (!session) { + console.log('Session file corrupted; set aside as current.json.corrupt'); + setAsideCorrupt(); + return null; + } session.endedAt = new Date().toISOString(); - session.duration = Date.now() - new Date(session.startedAt).getTime(); + session.duration = elapsedMs(session.startedAt); // Archive session under a validated name; a crafted id cannot pick the path. const id = archiveId(session.id); @@ -121,8 +150,8 @@ const commands = { fs.unlinkSync(SESSION_FILE); console.log(`Session ended: ${id}`); - console.log(`Duration: ${Math.round(session.duration / 1000 / 60)} minutes`); - console.log(`Metrics: ${JSON.stringify(session.metrics)}`); + console.log(`Duration: ${formatMinutes(session.duration)}`); + console.log(`Metrics: ${JSON.stringify(session.metrics || {})}`); return session; }, @@ -133,13 +162,16 @@ const commands = { return null; } - const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); - const duration = Date.now() - new Date(session.startedAt).getTime(); + const session = readSession(); + if (!session) { + console.log('Session file corrupted'); + return null; + } console.log(`Session: ${session.id}`); console.log(`Started: ${session.startedAt}`); - console.log(`Duration: ${Math.round(duration / 1000 / 60)} minutes`); - console.log(`Metrics: ${JSON.stringify(session.metrics)}`); + console.log(`Duration: ${formatMinutes(elapsedMs(session.startedAt))}`); + console.log(`Metrics: ${JSON.stringify(session.metrics || {})}`); return session; }, @@ -150,7 +182,12 @@ const commands = { return null; } - const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); + const session = readSession(); + if (!session) { + console.log('Session file corrupted'); + return null; + } + if (!session.context || typeof session.context !== 'object') session.context = {}; session.context[key] = value; session.updatedAt = new Date().toISOString(); atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2)); @@ -160,10 +197,9 @@ const commands = { get: (key) => { if (!hasSessionFile()) return null; - try { - const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); - return key ? (session.context || {})[key] : session.context; - } catch { return null; } + const session = readSession(); + if (!session) return null; + return key ? (session.context || {})[key] : session.context; }, metric: (name) => { @@ -171,8 +207,10 @@ const commands = { return null; } - const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); - if (session.metrics[name] !== undefined) { + const session = readSession(); + if (!session) return null; + if (!session.metrics || typeof session.metrics !== 'object') session.metrics = { ...DEFAULT_METRICS }; + if (typeof session.metrics[name] === 'number') { session.metrics[name]++; atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2)); } @@ -181,13 +219,15 @@ const commands = { }, }; -// CLI -const [,, command, ...args] = process.argv; +// CLI — only when run directly (#5176): require() must not dispatch on the parent's argv. +if (require.main === module) { + const [,, command, ...args] = process.argv; -if (command && commands[command]) { - commands[command](...args); -} else { - console.log('Usage: session.cjs [args]'); + if (command && commands[command]) { + commands[command](...args); + } else { + console.log('Usage: session.cjs [args]'); + } } module.exports = commands; diff --git a/v3/@claude-flow/cli/.claude/helpers/statusline.cjs b/v3/@claude-flow/cli/.claude/helpers/statusline.cjs index e7e50426d9..b6d10cc186 100755 --- a/v3/@claude-flow/cli/.claude/helpers/statusline.cjs +++ b/v3/@claude-flow/cli/.claude/helpers/statusline.cjs @@ -249,12 +249,18 @@ function getStatuslineData() { .filter((bin) => shellSafe(bin) && shellSafe(process.execPath)) .map((bin) => '"' + process.execPath + '" "' + bin + '" hooks statusline --json') // --prefix: npx resolves the package from HELPER_ROOT, not the project. - .concat(shellSafe(HELPER_ROOT) ? ['npx --prefer-offline --prefix "' + HELPER_ROOT + '" @claude-flow/cli hooks statusline --json'] : []); + .concat((() => { + // #5176: npx from an absolute PATH entry outside the project, never a project-local npx.cmd. + const npx = resolveExecutable('npx'); + return npx && shellSafe(npx) && shellSafe(HELPER_ROOT) + ? ['"' + npx + '" --prefer-offline --prefix "' + HELPER_ROOT + '" @claude-flow/cli hooks statusline --json'] + : []; + })()); for (const cmd of cmds) { try { const raw = execSync( cmd, - { encoding: 'utf-8', timeout: 8000, stdio: ['pipe', 'pipe', 'pipe'], cwd: CWD, windowsHide: true } + { encoding: 'utf-8', timeout: 8000, stdio: ['pipe', 'pipe', 'pipe'], cwd: CWD, env: getSafeEnv(), windowsHide: true } ).trim(); // The CLI may emit preamble lines before the JSON — find the first '{'. const jsonStart = raw.indexOf('{'); @@ -674,28 +680,63 @@ const c = { brightWhite: '\x1b[1;37m', }; -// Safe execSync with strict timeout (returns empty string on failure) -function safeExec(cmd, timeoutMs) { - try { - return execSync(cmd, { - encoding: 'utf-8', - timeout: timeoutMs || 2000, - stdio: ['pipe', 'pipe', 'pipe'], - // Windows: without this, every execSync spawns cmd.exe /d /s /c which - // flashes a visible console window every render (~1/min via the 60s - // cache TTL). windowsHide runs the child in a hidden window instead. - // No-op on POSIX. Fix for #2XXX (user report: "cmd prompt keeps opening"). - windowsHide: true, - }).trim(); - } catch { - return ''; +// #5176: a bare program name is looked up only in absolute PATH entries outside the project. +// Windows searches the current directory (the project) before PATH, and a POSIX PATH with an +// empty or relative entry does the same, so a sqlite3.exe, sh.exe or npx.cmd committed to a +// repository would otherwise run on every render. Children get the same filtered PATH +// (SAFE_ENV), so the git that sh runs, or what the CLI spawns, is not a project file either. +let safePathEntries = null; +function getSafePathEntries() { + if (safePathEntries) return safePathEntries; + const project = path.resolve(CWD); + const inProject = (dir) => { + const rel = path.relative(project, dir); + return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel)); + }; + safePathEntries = (process.env.PATH || '').split(path.delimiter) + .filter((dir) => dir && path.isAbsolute(dir) && !inProject(path.resolve(dir))); + return safePathEntries; +} +let safeEnv = null; +function getSafeEnv() { + if (safeEnv) return safeEnv; + safeEnv = {}; + for (const [key, value] of Object.entries(process.env)) { + if (key.toUpperCase() !== 'PATH') safeEnv[key] = value; } + safeEnv.PATH = getSafePathEntries().join(path.delimiter); + return safeEnv; +} +// Returns an absolute path, or null. +const resolvedExecutables = new Map(); +function resolveExecutable(name) { + if (resolvedExecutables.has(name)) return resolvedExecutables.get(name); + const isWin = process.platform === 'win32'; + const exts = isWin ? (process.env.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean) : ['']; + let found = null; + for (const dir of getSafePathEntries()) { + if (found) break; + for (const ext of exts) { + const candidate = path.join(dir, name + ext); + try { + if (!fs.statSync(candidate).isFile()) continue; + if (!isWin) fs.accessSync(candidate, fs.constants.X_OK); + found = candidate; + break; + } catch { /* not here */ } + } + } + resolvedExecutables.set(name, found); + return found; } // safeExec without a shell: the path in args is never parsed as shell syntax. function safeExecFile(file, args, timeoutMs) { + const resolved = path.isAbsolute(file) ? file : resolveExecutable(file); + if (!resolved) return ''; try { - return execFileSync(file, args, { + return execFileSync(resolved, args, { + env: getSafeEnv(), encoding: 'utf-8', timeout: timeoutMs || 2000, stdio: ['pipe', 'pipe', 'pipe'], @@ -742,7 +783,9 @@ function getGitInfo() { 'git rev-list --left-right --count HEAD...@{upstream} 2>/dev/null || echo "0 0"', ].join('; '); - const raw = safeExec("sh -c '" + script + "'", 3000); + // #5176: sh gets the script as one argument. Through a shell, cmd.exe read the single quotes + // literally, so the branch never showed on Windows. + const raw = safeExecFile('sh', ['-c', script], 3000); if (!raw) return result; const parts = raw.split('---SEP---').map(function(s) { return s.trim(); }); @@ -855,7 +898,8 @@ function getCostFromStdin() { const mins = Math.floor(durationMs / 60000); const secs = Math.floor((durationMs % 60000) / 1000); return { - costUsd: data.cost.total_cost_usd || 0, + // #5176: a string or other non-number cost must not reach .toFixed() and blank the line. + costUsd: Number.isFinite(Number(data.cost.total_cost_usd)) ? Number(data.cost.total_cost_usd) : 0, duration: mins > 0 ? mins + 'm' + secs + 's' : secs + 's', }; } diff --git a/v3/@claude-flow/cli/__tests__/issue-5176-generated-helpers.test.ts b/v3/@claude-flow/cli/__tests__/issue-5176-generated-helpers.test.ts new file mode 100644 index 0000000000..1a5dc65eae --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/issue-5176-generated-helpers.test.ts @@ -0,0 +1,304 @@ +/** Regression coverage for issue #5176 (generated helpers). + * + * 1. pre-bash let a home-wide delete through: rm -rf ~, ~/, $HOME, "${HOME}"/*. + * 2. statusline ran bare sqlite3/sh/npx found in the project, quoted `sh -c` for + * a shell cmd.exe does not speak, and threw on a string total_cost_usd. + * 3. post-edit dedup keyed on session_id dropped every edit after the first, and + * "Updated error handling" counted as a failed edit. + * 4. intelligence.cjs overwrote a corrupt store and truncated pending insights + * in place; session.cjs threw on a corrupt or partial current.json, ignored + * CLAUDE_PROJECT_DIR and dispatched its CLI on require(). + * 5. auto-commit.sh pushed by default, staged untracked files and carried a + * hardcoded Co-Authored-By trailer. + * + * Every helper runs as a real child process in a temporary project; every + * command string below is inert stdin JSON data. */ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { execFileSync, spawnSync } from 'node:child_process'; +import { + chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { + generateCrossPlatformSessionManager, generateHookHandler, generateIntelligenceStub, generateSessionManager, isToolFailure, +} from '../src/init/helpers-generator'; +import { dangerousCommandVerdict } from '../../../../plugins/ruflo-mods/hooks/guard/dangerous-command'; + +const REPO = path.resolve(__dirname, '../../../..'); +const CLI_HELPERS = path.resolve(__dirname, '../.claude/helpers'); +const ROOT_HELPERS = path.join(REPO, '.claude/helpers'); +const HELPER_DIRS = [CLI_HELPERS, ROOT_HELPERS]; +const rel = (p: string) => path.relative(REPO, p); + +let scratch: string; +let fallback: string; +beforeAll(() => { + scratch = mkdtempSync(path.join(tmpdir(), 'ruflo-5176-')); + fallback = path.join(scratch, 'fallback-hook-handler.cjs'); + writeFileSync(fallback, generateHookHandler()); +}); +afterAll(() => rmSync(scratch, { recursive: true, force: true })); + +function project(name: string): string { + const dir = path.join(scratch, name); + mkdirSync(dir, { recursive: true }); + return dir; +} + +function run(file: string, args: string[], opts: { cwd: string; input?: string; env?: Record }) { + return spawnSync(process.execPath, [file, ...args], { + cwd: opts.cwd, input: opts.input ?? '', encoding: 'utf8', timeout: 15_000, + env: { + PATH: process.env.PATH ?? '', HOME: opts.cwd, CI: '1', RUFLO_MODS_OWNS: '', + CLAUDE_PROJECT_DIR: opts.cwd, ...opts.env, + }, + }); +} + +describe('pre-bash refuses a home-wide delete — mod, shipped helpers and fallback agree (#5176)', () => { + const cases: Array<[string, boolean]> = [ + ['rm -rf ~', true], + ['rm -rf ~/', true], + ['rm -rf ~/*', true], + ['rm -rf ~/..', true], + ['rm -rf ~root', true], + ['rm -rf $HOME', true], + ['rm -rf $HOME/', true], + ['rm -rf ${HOME}', true], + ['rm -rf "$HOME"/*', true], + ['rm -rf "${HOME}"/*', true], + ['cd /tmp && rm -fr -- ~', true], + ['rm -rf ~/build', false], + ['rm -rf $HOME/projects/app/node_modules', false], + ['rm -rf ${HOME}/.cache/tmp', false], + ['rm -rf $HOMEDIR', false], + ['rm ~/notes.txt', false], + ['ls -la ~', false], + ]; + const hook = (helper: string, command: string) => run(helper, ['pre-bash'], { + cwd: project('pre-bash'), input: JSON.stringify({ tool_name: 'Bash', tool_input: { command } }), + }); + it.each(cases)('%j: denied=%s', (command, denied) => { + expect(dangerousCommandVerdict('Bash', { command })?.decision === 'deny').toBe(denied); + for (const helper of [...HELPER_DIRS.map((d) => path.join(d, 'hook-handler.cjs')), fallback]) { + const r = hook(helper, command); + expect(r.error, helper).toBeUndefined(); + expect(r.status, `${helper}: ${r.stderr}`).toBe(denied ? 2 : 0); + } + }); +}); + +describe('statusline does not run project binaries and survives odd input (#5176)', () => { + const posixOnly = process.platform === 'win32' ? it.skip : it; + + posixOnly.each(HELPER_DIRS.map((d) => [rel(d), d]))('%s: sh/sqlite3/npx in the project never run', (_n, dir) => { + const proj = project(`statusline-${path.basename(path.dirname(path.dirname(dir)))}-${Math.random().toString(36).slice(2, 6)}`); + const marker = path.join(proj, 'planted-binary-ran'); + const bin = path.join(proj, 'bin'); + mkdirSync(bin); + for (const name of ['sh', 'sqlite3', 'npx', 'git']) { + writeFileSync(path.join(bin, name), `#!/bin/sh\necho ${name} >> "${marker}"\n`); + chmodSync(path.join(bin, name), 0o755); + } + mkdirSync(path.join(proj, '.swarm')); + writeFileSync(path.join(proj, '.swarm', 'memory.db'), ''); + execFileSync('git', ['init', '-q', '-b', 'issue-5176-branch'], { cwd: proj }); + // An npx outside the project, which must be the one chosen: it exits 1, so no real npx runs either. + const outside = mkdtempSync(path.join(scratch, 'outside-bin-')); + const outsideMarker = path.join(outside, 'outside-npx-ran'); + writeFileSync(path.join(outside, 'npx'), `#!/bin/sh\necho npx >> "${outsideMarker}"\nexit 1\n`); + chmodSync(path.join(outside, 'npx'), 0o755); + // An absolute PATH entry inside the project and relative ones ("." and "bin") all point at the planted binaries. + const r = run(path.join(dir, 'statusline.cjs'), [], { + cwd: proj, input: JSON.stringify({ cost: { total_cost_usd: '1.5' } }), + env: { PATH: [bin, '.', 'bin', outside, process.env.PATH ?? ''].join(path.delimiter), NO_COLOR: '1' }, + }); + expect(r.status, r.stderr).toBe(0); + expect(existsSync(marker), existsSync(marker) ? readFileSync(marker, 'utf8') : '').toBe(false); + expect(existsSync(outsideMarker)).toBe(true); + // sh -c receives the script as one argument, so the branch still renders. + expect(r.stdout).toContain('issue-5176-branch'); + // A numeric string cost is shown, not thrown on. + expect(r.stdout).toContain('1.50'); + }); + + it.each(HELPER_DIRS.map((d) => [rel(d), d]))('%s: a non-numeric cost does not blank the line', (_n, dir) => { + const proj = project(`statusline-cost-${Math.random().toString(36).slice(2, 6)}`); + for (const cost of ['abc', '{}', 'NaN']) { + const r = run(path.join(dir, 'statusline.cjs'), [], { + cwd: proj, input: JSON.stringify({ cost: { total_cost_usd: cost === '{}' ? {} : cost } }), + env: { PATH: '/nonexistent', NO_COLOR: '1' }, + }); + expect(r.status, r.stderr).toBe(0); + expect(r.stdout).toMatch(/RuFlo/); + } + }); +}); + +describe('post-edit records every edit and reads failures conservatively (#5176)', () => { + it.each(HELPER_DIRS.map((d) => [rel(d), d]))('%s', (_n, dir) => { + const proj = project(`post-edit-${Math.random().toString(36).slice(2, 6)}`); + const dedup = path.join(proj, 'dedup'); + const env = { RUFLO_HOOK_DEDUP_DIR: dedup }; + const edit = (file: string, extra: Record = {}) => run(path.join(dir, 'hook-handler.cjs'), ['post-edit'], { + cwd: proj, env, + input: JSON.stringify({ session_id: 'sess-1', tool_name: 'Edit', tool_input: { file_path: file }, ...extra }), + }); + // Same session, no tool_use_id: each edit is its own event. + expect(edit('a.ts').stdout).toContain('[OK] Edit recorded'); + expect(edit('b.ts').stdout).toContain('[OK] Edit recorded'); + // A delivered-twice event (same tool_use_id) is still deduplicated. + expect(edit('c.ts', { tool_use_id: 'tu-1' }).stdout).toContain('Edit recorded'); + expect(edit('c.ts', { tool_use_id: 'tu-1' }).stdout).not.toContain('Edit recorded'); + // A success that mentions an error is a success; a leading error is a failure. + expect(edit('d.ts', { tool_response: 'Updated error handling in d.ts' }).stdout).toContain('[OK] Edit recorded'); + expect(edit('e.ts', { tool_response: 'Error: String to replace not found' }).stdout).toContain('[LEARN] Edit FAILURE recorded'); + expect(edit('f.ts', { tool_response: 'File has not been read yet' }).stdout) + .toContain('[LEARN] Edit FAILURE recorded'); + }); + + it('isToolFailure (the generated fallback predicate) agrees', () => { + expect(isToolFailure({ tool_response: 'Updated error handling' })).toBe(false); + expect(isToolFailure({ tool_response: 'Removed the failed retry path' })).toBe(false); + expect(isToolFailure({ tool_response: 'Error: boom' })).toBe(true); + expect(isToolFailure({ tool_response: 'nope' })).toBe(true); + expect(isToolFailure({ tool_response: 'cat: x: No such file or directory' })).toBe(true); + }); +}); + +describe('intelligence.cjs keeps a corrupt store and claims pending insights (#5176)', () => { + it.each(HELPER_DIRS.map((d) => [rel(d), d]))('%s', (_n, dir) => { + const proj = project(`intel-${Math.random().toString(36).slice(2, 6)}`); + const data = path.join(proj, '.claude-flow', 'data'); + mkdirSync(data, { recursive: true }); + const store = path.join(data, 'auto-memory-store.json'); + const corrupt = '[{"id":"keep-me", "content": "half-written'; + writeFileSync(store, corrupt); + const lines = Array.from({ length: 4 }, (_, i) => JSON.stringify({ type: 'edit', file: 'hot.ts', n: i })); + writeFileSync(path.join(data, 'pending-insights.jsonl'), lines.join('\n') + '\n'); + const script = path.join(proj, 'drive.cjs'); + writeFileSync(script, `const i = require(${JSON.stringify(path.join(dir, 'intelligence.cjs'))}); + i.consolidate(); + require('fs').writeFileSync(${JSON.stringify(store)}, JSON.stringify([{ id: 'x', content: 'y', namespace: 'n' }])); + i.consolidate();`); + const r = run(script, [], { cwd: proj }); + expect(r.status, r.stderr).toBe(0); + expect(readFileSync(store + '.corrupt', 'utf8')).toBe(corrupt); + // The pending log was claimed and consumed; no claimed copy or temp file is left behind. + expect(readdirSync(data).filter((f) => f.endsWith('.claimed') || f.endsWith('.tmp'))).toEqual([]); + expect(existsSync(path.join(data, 'pending-insights.jsonl'))).toBe(false); + }); +}); + +describe('session.cjs survives bad sessions, uses CLAUDE_PROJECT_DIR and is inert on require (#5176)', () => { + const variants: Array<[string, () => string]> = [ + ['cli shipped', () => path.join(CLI_HELPERS, 'session.cjs')], + ['root shipped', () => path.join(ROOT_HELPERS, 'session.cjs')], + ['generated', () => { const f = path.join(scratch, 'gen-session.cjs'); writeFileSync(f, generateSessionManager()); return f; }], + ['generated cross-platform', () => { + const f = path.join(scratch, 'gen-xsession.cjs'); writeFileSync(f, generateCrossPlatformSessionManager()); return f; + }], + ]; + it.each(variants)('%s', (_n, make) => { + const helper = make(); + const proj = project(`session-${Math.random().toString(36).slice(2, 6)}`); + const sub = path.join(proj, 'packages', 'app'); + mkdirSync(sub, { recursive: true }); + const sessions = path.join(proj, '.claude-flow', 'sessions'); + mkdirSync(sessions, { recursive: true }); + const current = path.join(sessions, 'current.json'); + const session = (cmd: string) => run(helper, [cmd], { cwd: sub, env: { CLAUDE_PROJECT_DIR: proj } }); + + // CLAUDE_PROJECT_DIR, not the cwd, picks the session directory. + expect(session('start').status).toBe(0); + expect(existsSync(current)).toBe(true); + expect(existsSync(path.join(sub, '.claude-flow'))).toBe(false); + + // A partial session: no metrics, no startedAt. + writeFileSync(current, JSON.stringify({ id: 'session-1' })); + for (const cmd of ['status', 'metric']) expect(session(cmd).status, cmd).toBe(0); + const ended = session('end'); + expect(ended.status, ended.stderr).toBe(0); + expect(ended.stdout).not.toContain('NaN'); + + // A corrupt session is set aside, not thrown on. + writeFileSync(current, '{"id": "session-2", "metr'); + for (const cmd of ['status', 'metric']) expect(session(cmd).status, cmd).toBe(0); + const r = session('end'); + expect(r.status, r.stderr).toBe(0); + expect(readFileSync(current + '.corrupt', 'utf8')).toBe('{"id": "session-2", "metr'); + + // require() runs nothing: no usage text, no session started. + rmSync(current, { force: true }); + const loader = path.join(proj, 'load.cjs'); + writeFileSync(loader, `require(${JSON.stringify(helper)});`); + const loaded = run(loader, ['start'], { cwd: proj }); + expect(loaded.status, loaded.stderr).toBe(0); + expect(loaded.stdout).toBe(''); + expect(existsSync(current)).toBe(false); + }); +}); + +describe('auto-commit.sh is local and tracked-only by default (#5176)', () => { + const posixOnly = process.platform === 'win32' ? it.skip : it; + posixOnly.each(HELPER_DIRS.map((d) => [rel(d), d]))('%s', (_n, dir) => { + const proj = project(`auto-commit-${Math.random().toString(36).slice(2, 6)}`); + const remote = project(`auto-commit-remote-${Math.random().toString(36).slice(2, 6)}`); + const gitEnv = { + ...process.env, GIT_AUTHOR_NAME: 't', GIT_AUTHOR_EMAIL: 't@example.invalid', + GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@example.invalid', GIT_CONFIG_GLOBAL: '/dev/null', + }; + const git = (args: string[], cwd = proj) => execFileSync('git', args, { cwd, env: gitEnv, encoding: 'utf8' }).trim(); + git(['init', '-q', '--bare'], remote); + git(['init', '-q', '-b', 'main']); + git(['remote', 'add', 'origin', remote]); + writeFileSync(path.join(proj, 'tracked.txt'), 'one\n'); + git(['add', 'tracked.txt']); + git(['commit', '-q', '-m', 'init']); + writeFileSync(path.join(proj, 'tracked.txt'), 'two\n'); + writeFileSync(path.join(proj, '.env'), 'SECRET=not-a-real-secret\n'); + + const r = spawnSync('bash', [path.join(dir, 'auto-commit.sh'), 'batch', 'checkpoint: test'], { + cwd: proj, env: { ...gitEnv, AUTO_PUSH: '' }, encoding: 'utf8', timeout: 15_000, + }); + expect(r.status, r.stdout + r.stderr).toBe(0); + expect(git(['show', '--name-only', '--format=', 'HEAD'])).toBe('tracked.txt'); + expect(git(['status', '--porcelain'])).toBe('?? .env'); + expect(git(['log', '-1', '--format=%B'])).not.toMatch(/Co-Authored-By/i); + // Nothing was pushed. + expect(git(['for-each-ref'], remote)).toBe(''); + + // file mode still commits a new file it is given by name, and only that file. + writeFileSync(path.join(proj, 'new.txt'), 'new\n'); + const f = spawnSync('bash', [path.join(dir, 'auto-commit.sh'), 'file', 'new.txt'], { + cwd: proj, env: { ...gitEnv, AUTO_PUSH: '' }, encoding: 'utf8', timeout: 15_000, + }); + expect(f.status, f.stdout + f.stderr).toBe(0); + expect(git(['show', '--name-only', '--format=', 'HEAD'])).toBe('new.txt'); + expect(git(['status', '--porcelain'])).toBe('?? .env'); + }); +}); + +describe('the generated intelligence stub keeps a corrupt store and claims pending insights (#5176)', () => { + it('backs up once, writes atomically and consumes the pending log by rename', () => { + const proj = project(`intel-stub-${Math.random().toString(36).slice(2, 6)}`); + const stub = path.join(proj, 'intelligence-stub.cjs'); + writeFileSync(stub, generateIntelligenceStub()); + const data = path.join(proj, '.claude-flow', 'data'); + mkdirSync(data, { recursive: true }); + const sessions = path.join(proj, '.claude-flow', 'sessions'); + mkdirSync(sessions, { recursive: true }); + const current = path.join(sessions, 'current.json'); + writeFileSync(current, '{"context": {"a": 1'); + writeFileSync(path.join(data, 'pending-insights.jsonl'), '{"type":"edit"}\n{"type":"edit"}\n'); + const script = path.join(proj, 'drive.cjs'); + writeFileSync(script, `const i = require(${JSON.stringify(stub)}); + const r = i.consolidate(); + if (r.entries !== 2) throw new Error('expected 2 pending entries, got ' + r.entries);`); + const r = run(script, [], { cwd: proj }); + expect(r.status, r.stderr).toBe(0); + expect(existsSync(path.join(data, 'pending-insights.jsonl'))).toBe(false); + expect(readdirSync(data).filter((f) => f.endsWith('.claimed') || f.endsWith('.tmp'))).toEqual([]); + }); +}); diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-guard.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-guard.test.ts index 1338f48ca2..bcba226068 100644 --- a/v3/@claude-flow/cli/__tests__/mods/mods-guard.test.ts +++ b/v3/@claude-flow/cli/__tests__/mods/mods-guard.test.ts @@ -388,9 +388,10 @@ describe('#3698 root deletion guard parity', () => { ['git rm -r --cached /tmp/x', false], ['ls -rf /', false], ['printf "%s" `date` > /tmp/x; ls /', false], - // Documented limits: nothing is evaluated (variables, brace expansion, find), so these are not caught. - ['rm -rf "$HOME"', false], - ['rm -rf ${HOME}/..', false], + // #5176: home itself is read as a root, so a delete of home (or above it) is caught. + ['rm -rf "$HOME"', true], + ['rm -rf ${HOME}/..', true], + // Documented limits: nothing else is evaluated (other variables, brace expansion, find), so these are not caught. ['rm -rf $x', false], ['rm -rf /${x}', false], ['find / -delete', false], diff --git a/v3/@claude-flow/cli/src/init/helpers-generator.ts b/v3/@claude-flow/cli/src/init/helpers-generator.ts index de35e6fd99..a7a45eb793 100644 --- a/v3/@claude-flow/cli/src/init/helpers-generator.ts +++ b/v3/@claude-flow/cli/src/init/helpers-generator.ts @@ -36,7 +36,9 @@ export function isToolFailure(hookInput: unknown): boolean { const tr = (h.tool_response ?? h.toolResponse ?? h.result) as unknown; if (tr == null) return false; if (typeof tr === 'string') { - return /\b(error|failed|failure|exception|not found|no such|permission denied|traceback)\b/i.test(tr); + // #5176: a leading error word, Claude Code's wrapper or an explicit OS message. + // Anywhere in the text, "error" also matched a success such as "Updated error handling". + return /^\s*(?:error|failed|failure|fatal|exception|traceback)\b||\b(?:command not found|no such file or directory|permission denied)\b/i.test(tr); } if (typeof tr === 'object') { const o = tr as Record; @@ -57,7 +59,7 @@ const TOOL_FAILURE_EXPR = 'if(!hi||typeof hi!=="object")return false;' + 'var tr=hi.tool_response!=null?hi.tool_response:(hi.toolResponse!=null?hi.toolResponse:hi.result);' + 'if(tr==null)return false;' + - 'if(typeof tr==="string")return /\\b(error|failed|failure|exception|not found|no such|permission denied|traceback)\\b/i.test(tr);' + + 'if(typeof tr==="string")return /^\\s*(?:error|failed|failure|fatal|exception|traceback)\\b||\\b(?:command not found|no such file or directory|permission denied)\\b/i.test(tr);' + 'if(typeof tr==="object"){' + 'if(tr.is_error===true||tr.isError===true||tr.success===false||tr.error!=null)return true;' + 'var code=tr.exit_code!=null?tr.exit_code:(tr.exitCode!=null?tr.exitCode:tr.code);' + @@ -135,12 +137,14 @@ const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); -const SESSION_DIR = path.join(process.cwd(), '.claude-flow', 'sessions'); +// #5176: hooks run with CLAUDE_PROJECT_DIR set; the cwd may be a subdirectory. +const PROJECT_ROOT = process.env.CLAUDE_PROJECT_DIR || process.cwd(); +const SESSION_DIR = path.join(PROJECT_ROOT, '.claude-flow', 'sessions'); const SESSION_FILE = path.join(SESSION_DIR, 'current.json'); - // Archive names are generated by start(); anything else in current.json is // untrusted project content and must never pick a path. const SESSION_ID = /^session-\\d+$/; +const DEFAULT_METRICS = { edits: 0, commands: 0, tasks: 0, errors: 0 }; // current.json lives in the opened project. A symlink there must never be read // or written through, so only a regular file counts as an active session. @@ -154,7 +158,7 @@ function archiveId(id) { // The session directory must resolve inside the project (no symlinked escape). function assertSessionDirContained() { - const root = fs.realpathSync(process.cwd()); + const root = fs.realpathSync(PROJECT_ROOT); // Resolve the deepest part of the path that exists (lstat: a symlink counts), // so a symlinked .claude-flow is refused before anything is created under it. let dir = SESSION_DIR; @@ -170,8 +174,16 @@ function assertSessionDirContained() { } } -// Exclusive temp file + rename: never writes through a planted symlink, and -// rename() replaces a symlinked target instead of following it. +// #2307: Atomic write — serialize to a per-process temp file, then rename() +// into place. rename() is atomic on the same filesystem, so concurrent writers +// (session-restore, metric, daemon workers, teammates) can't interleave partial +// content. Without this, two non-atomic writeFileSync calls can race so that a +// shorter payload overwrites a longer one in place, leaving the longer payload's +// tail dangling past the end (valid JSON + trailing garbage = parse error). +// Temp name includes process.pid so concurrent writers don't collide on it. +// Same class as #1707 (metrics) / #1637 (daemon-state) — session.js was missed. +// The temp file is created exclusively (never through a planted symlink) and +// rename() replaces a symlinked target instead of writing through it. function atomicWrite(file, data) { assertSessionDirContained(); const tmp = \`\${file}.tmp.\${process.pid}.\${crypto.randomBytes(6).toString('hex')}\`; @@ -179,20 +191,42 @@ function atomicWrite(file, data) { fs.renameSync(tmp, file); } +// #5176: current.json is project content. A corrupt or non-object file reads as +// null instead of throwing out of a hook. +function readSession() { + try { + const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); + return session && typeof session === 'object' && !Array.isArray(session) ? session : null; + } catch { return null; } +} + +// A corrupt current.json is moved aside (kept as current.json.corrupt), so the +// next session starts clean and the bytes are not lost. +function setAsideCorrupt() { + try { + assertSessionDirContained(); + fs.renameSync(SESSION_FILE, SESSION_FILE + '.corrupt'); + } catch { /* best effort */ } +} + +function elapsedMs(startedAt) { + const started = Date.parse(startedAt); + return Number.isFinite(started) ? Date.now() - started : null; +} + +function formatMinutes(ms) { + return ms === null ? 'unknown' : \`\${Math.round(ms / 1000 / 60)} minutes\`; +} + const commands = { start: () => { const sessionId = \`session-\${Date.now()}\`; const session = { id: sessionId, startedAt: new Date().toISOString(), - cwd: process.cwd(), + cwd: PROJECT_ROOT, context: {}, - metrics: { - edits: 0, - commands: 0, - tasks: 0, - errors: 0, - }, + metrics: { ...DEFAULT_METRICS }, }; assertSessionDirContained(); @@ -209,7 +243,14 @@ const commands = { return null; } - const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); + const session = readSession(); + if (!session) { + // #2307: corrupted session file (e.g. from a pre-atomic-write race). + // Don't throw — start a fresh session so the hook recovers cleanly. + console.log('Session file corrupted; starting fresh'); + setAsideCorrupt(); + return commands.start(); + } session.restoredAt = new Date().toISOString(); atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2)); @@ -223,9 +264,14 @@ const commands = { return null; } - const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); + const session = readSession(); + if (!session) { + console.log('Session file corrupted; set aside as current.json.corrupt'); + setAsideCorrupt(); + return null; + } session.endedAt = new Date().toISOString(); - session.duration = Date.now() - new Date(session.startedAt).getTime(); + session.duration = elapsedMs(session.startedAt); // Archive session under a validated name; a crafted id cannot pick the path. const id = archiveId(session.id); @@ -233,8 +279,8 @@ const commands = { fs.unlinkSync(SESSION_FILE); console.log(\`Session ended: \${id}\`); - console.log(\`Duration: \${Math.round(session.duration / 1000 / 60)} minutes\`); - console.log(\`Metrics: \${JSON.stringify(session.metrics)}\`); + console.log(\`Duration: \${formatMinutes(session.duration)}\`); + console.log(\`Metrics: \${JSON.stringify(session.metrics || {})}\`); return session; }, @@ -245,13 +291,16 @@ const commands = { return null; } - const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); - const duration = Date.now() - new Date(session.startedAt).getTime(); + const session = readSession(); + if (!session) { + console.log('Session file corrupted'); + return null; + } console.log(\`Session: \${session.id}\`); console.log(\`Started: \${session.startedAt}\`); - console.log(\`Duration: \${Math.round(duration / 1000 / 60)} minutes\`); - console.log(\`Metrics: \${JSON.stringify(session.metrics)}\`); + console.log(\`Duration: \${formatMinutes(elapsedMs(session.startedAt))}\`); + console.log(\`Metrics: \${JSON.stringify(session.metrics || {})}\`); return session; }, @@ -262,7 +311,12 @@ const commands = { return null; } - const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); + const session = readSession(); + if (!session) { + console.log('Session file corrupted'); + return null; + } + if (!session.context || typeof session.context !== 'object') session.context = {}; session.context[key] = value; session.updatedAt = new Date().toISOString(); atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2)); @@ -270,13 +324,22 @@ const commands = { return session; }, + get: (key) => { + if (!hasSessionFile()) return null; + const session = readSession(); + if (!session) return null; + return key ? (session.context || {})[key] : session.context; + }, + metric: (name) => { if (!hasSessionFile()) { return null; } - const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); - if (session.metrics[name] !== undefined) { + const session = readSession(); + if (!session) return null; + if (!session.metrics || typeof session.metrics !== 'object') session.metrics = { ...DEFAULT_METRICS }; + if (typeof session.metrics[name] === 'number') { session.metrics[name]++; atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2)); } @@ -285,13 +348,15 @@ const commands = { }, }; -// CLI -const [,, command, ...args] = process.argv; +// CLI — only when run directly (#5176): require() must not dispatch on the parent's argv. +if (require.main === module) { + const [,, command, ...args] = process.argv; -if (command && commands[command]) { - commands[command](...args); -} else { - console.log('Usage: session.cjs [args]'); + if (command && commands[command]) { + commands[command](...args); + } else { + console.log('Usage: session.cjs [args]'); + } } module.exports = commands; @@ -492,7 +557,10 @@ const ROOT_DELETE_CHECK_SOURCE = String.raw`function hasRootDelete(command, dept let word = '', mask = '', quote = '', started = false, redirect = false let ansiNul = false // a NUL inside $'...' ends that string, as in bash let inRm = false, optionsEnded = false, recursive = false, force = false, root = false - const isRoot = (operand) => { + // A home-wide operand is a root too (#5176): ~, ~user, $home and dollar-brace home name a directory the shell + // fills in, so a recursive delete of ~, ~/ or "$HOME"/* reads as one of /, / or /*. A path below it (~/build) is not. + const isRoot = (raw) => { + const operand = raw.replace(/^(?:~[^/]*|\$home(?![a-z0-9_])|\$\{home\})/, '/') if (!operand.startsWith('/')) return false const parts = [] for (const part of operand.split('/')) { @@ -1224,14 +1292,36 @@ export function generateIntelligenceStub(): string { '', 'function readJSON(p) {', ' if (isRepoTracked(p)) return null;', - ' try { return fs.existsSync(p) ? JSON.parse(fs.readFileSync(p, "utf-8")) : null; }', - ' catch { return null; }', + ' var text;', + ' try {', + ' if (!fs.existsSync(p)) return null;', + ' text = fs.readFileSync(p, "utf-8");', + ' return JSON.parse(text);', + ' } catch {', + ' // #5176: keep a corrupt file as .corrupt (once) before a later write replaces it.', + ' if (text && text.trim() && !fs.existsSync(p + ".corrupt")) {', + ' try { atomicWrite(p + ".corrupt", text); } catch { /* best effort */ }', + ' }', + ' return null;', + ' }', + '}', + '', + '// Temp file + rename: a reader never sees a half-written file.', + 'function atomicWrite(p, text) {', + ' var tmp = p + "." + process.pid + "." + Math.random().toString(36).slice(2, 8) + ".tmp";', + ' try {', + ' fs.writeFileSync(tmp, text, { encoding: "utf-8", flag: "wx" });', + ' fs.renameSync(tmp, p);', + ' } catch (e) {', + ' try { fs.unlinkSync(tmp); } catch { /* nothing to clean */ }', + ' throw e;', + ' }', '}', '', 'function writeJSON(p, data) {', ' if (isRepoTracked(p)) return;', ' ensureDir(path.dirname(p));', - ' fs.writeFileSync(p, JSON.stringify(data, null, 2), "utf-8");', + ' atomicWrite(p, JSON.stringify(data, null, 2));', '}', '', '// Read session context key', @@ -1401,13 +1491,14 @@ export function generateIntelligenceStub(): string { '', ' consolidate: function() {', ' var count = 0;', - ' if (fs.existsSync(PENDING_PATH)) {', - ' try {', - ' var content = fs.readFileSync(PENDING_PATH, "utf-8").trim();', - ' count = content ? content.split("\\n").length : 0;', - ' fs.writeFileSync(PENDING_PATH, "", "utf-8");', - ' } catch (e) { /* skip */ }', - ' }', + ' // #5176: claim the log by renaming it, so a line appended meanwhile is not truncated away.', + ' var claimed = PENDING_PATH + "." + process.pid + "." + Date.now() + ".claimed";', + ' try {', + ' fs.renameSync(PENDING_PATH, claimed);', + ' var content = fs.readFileSync(claimed, "utf-8").trim();', + ' count = content ? content.split("\\n").length : 0;', + ' fs.unlinkSync(claimed);', + ' } catch (e) { /* nothing pending */ }', ' return { entries: count, edges: 0, newEntries: 0 };', ' },', '};', @@ -1732,13 +1823,14 @@ const path = require('path'); const crypto = require('crypto'); const os = require('os'); -// Platform-specific paths const platform = os.platform(); const homeDir = os.homedir(); +// #5176: hooks run with CLAUDE_PROJECT_DIR set; the cwd may be a subdirectory. +const PROJECT_ROOT = process.env.CLAUDE_PROJECT_DIR || process.cwd(); +const DEFAULT_METRICS = { edits: 0, commands: 0, tasks: 0, errors: 0 }; -// Get data directory based on platform function getDataDir() { - const localDir = path.join(process.cwd(), '.claude-flow', 'sessions'); + const localDir = path.join(PROJECT_ROOT, '.claude-flow', 'sessions'); if (fs.existsSync(path.dirname(localDir))) { return localDir; } @@ -1773,8 +1865,8 @@ function archiveId(id) { // The project session directory must resolve inside the project (no // symlinked escape). The per-user fallback directory is not project-owned. function assertSessionDirContained() { - if (SESSION_DIR !== path.join(process.cwd(), '.claude-flow', 'sessions')) return; - const root = fs.realpathSync(process.cwd()); + if (SESSION_DIR !== path.join(PROJECT_ROOT, '.claude-flow', 'sessions')) return; + const root = fs.realpathSync(PROJECT_ROOT); // Resolve the deepest part of the path that exists (lstat: a symlink counts), // so a symlinked .claude-flow is refused before anything is created under it. let dir = SESSION_DIR; @@ -1799,7 +1891,31 @@ function atomicWrite(file, data) { fs.renameSync(tmp, file); } -// Ensure directory exists +// #5176: current.json may be corrupt or partial; read it as null instead of throwing out of a hook. +function readSession() { + try { + const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); + return session && typeof session === 'object' && !Array.isArray(session) ? session : null; + } catch { return null; } +} + +// A corrupt current.json is kept as current.json.corrupt, so the next session starts clean. +function setAsideCorrupt() { + try { + assertSessionDirContained(); + fs.renameSync(SESSION_FILE, SESSION_FILE + '.corrupt'); + } catch { /* best effort */ } +} + +function elapsedMs(startedAt) { + const started = Date.parse(startedAt); + return Number.isFinite(started) ? Date.now() - started : null; +} + +function formatMinutes(ms) { + return ms === null ? 'unknown' : \`\${Math.round(ms / 1000 / 60)} minutes\`; +} + function ensureDir(dir) { if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); @@ -1815,9 +1931,9 @@ const commands = { id: sessionId, startedAt: new Date().toISOString(), platform: platform, - cwd: process.cwd(), + cwd: PROJECT_ROOT, context: {}, - metrics: { edits: 0, commands: 0, tasks: 0, errors: 0 } + metrics: { ...DEFAULT_METRICS } }; atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2)); console.log(\`Session started: \${sessionId}\`); @@ -1829,7 +1945,12 @@ const commands = { console.log('No session to restore'); return null; } - const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); + const session = readSession(); + if (!session) { + console.log('Session file corrupted; starting fresh'); + setAsideCorrupt(); + return commands.start(); + } session.restoredAt = new Date().toISOString(); atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2)); console.log(\`Session restored: \${session.id}\`); @@ -1841,9 +1962,14 @@ const commands = { console.log('No active session'); return null; } - const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); + const session = readSession(); + if (!session) { + console.log('Session file corrupted; set aside as current.json.corrupt'); + setAsideCorrupt(); + return null; + } session.endedAt = new Date().toISOString(); - session.duration = Date.now() - new Date(session.startedAt).getTime(); + session.duration = elapsedMs(session.startedAt); // Archive under a validated name; a crafted id cannot pick the path. const id = archiveId(session.id); @@ -1851,7 +1977,7 @@ const commands = { fs.unlinkSync(SESSION_FILE); console.log(\`Session ended: \${id}\`); - console.log(\`Duration: \${Math.round(session.duration / 1000 / 60)} minutes\`); + console.log(\`Duration: \${formatMinutes(session.duration)}\`); return session; }, @@ -1860,27 +1986,47 @@ const commands = { console.log('No active session'); return null; } - const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); - const duration = Date.now() - new Date(session.startedAt).getTime(); + const session = readSession(); + if (!session) { + console.log('Session file corrupted'); + return null; + } + const duration = elapsedMs(session.startedAt); console.log(\`Session: \${session.id}\`); console.log(\`Platform: \${session.platform}\`); console.log(\`Started: \${session.startedAt}\`); - console.log(\`Duration: \${Math.round(duration / 1000 / 60)} minutes\`); + console.log(\`Duration: \${formatMinutes(duration)}\`); + return session; + }, + + metric: (name) => { + if (!hasSessionFile()) { + return null; + } + const session = readSession(); + if (!session) return null; + if (!session.metrics || typeof session.metrics !== 'object') session.metrics = { ...DEFAULT_METRICS }; + if (typeof session.metrics[name] === 'number') { + session.metrics[name]++; + atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2)); + } return session; } }; -// CLI -const [,, command, ...args] = process.argv; -if (command && commands[command]) { - commands[command](...args); -} else { - console.log('Usage: session.cjs '); - console.log(\`Platform: \${platform}\`); - console.log(\`Data dir: \${SESSION_DIR}\`); -} - module.exports = commands; + +// CLI - only run when executed directly +if (require.main === module) { + const [,, command, ...args] = process.argv; + if (command && commands[command]) { + commands[command](...args); + } else { + console.log('Usage: session.cjs '); + console.log(\`Platform: \${platform}\`); + console.log(\`Data dir: \${SESSION_DIR}\`); + } +} `; }