Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

fix(ruflo-console): Windows fixes from running every view on a real Windows machine (console 0.49.1, cost-tracker 0.28.3) (#4490)

Mario Jauvin3a650ce7476e
diff --git a/plugins/ruflo-console/.claude-plugin/plugin.json b/plugins/ruflo-console/.claude-plugin/plugin.json
index 6fbb54d67a..ca1dec8b96 100644
--- a/plugins/ruflo-console/.claude-plugin/plugin.json
+++ b/plugins/ruflo-console/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "ruflo-console",
"description": "ruflo's cockpit inside Claude Code and the one /ruflo command for every ruflo mod (function hooks, early access). Views: overview with health alerts, swarm topology graph, claims flow with TTL rings, federation map, plugin health matrix, learning curve and pipeline, MetaHarness radar and audit trend, memory, cost gauge, agent timeline, approvals queue, event stream, a main menu, an x.ruv.io federation board, an AI terminal (codex, claude or both in remembered sessions, streamed), Skills (npx skills), a Hive-Mind view, a MetaHarness lab, agent drill-down; a command palette for confirm-gated actions through the ruflo CLI; a band above the prompt. Reads ruflo's files and the CLI's local JSON; anything not measured reads n/a. The one network call it makes by itself is a daily read of the published plugin.json at github.com/ruvnet/ruflo to offer an update (Settings \u2192 Updates: ask, auto, or off); it installs only through Claude Code's own claude plugin update, and never a new major version without asking.",
- "version": "0.49.0",
+ "version": "0.49.1",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
diff --git a/plugins/ruflo-console/CHANGELOG.md b/plugins/ruflo-console/CHANGELOG.md
index 3e29d84d05..0264f13a58 100644
--- a/plugins/ruflo-console/CHANGELOG.md
+++ b/plugins/ruflo-console/CHANGELOG.md
@@ -2,6 +2,27 @@
Newest first. One `## <version> — <date>` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; older versions: `git log -- plugins/ruflo-console`.
+## 0.49.1 — 2026-10-25
+- fix: the Plugin Catalog reads the marketplace clone on Windows. The clone's location is a drive path (`C:\Users\…\marketplaces\ruflo`), and the catalog refused anything not starting with `/`, so it said "the clone's marketplace.json is not readable" while the file was there. The catalog, each plugin's folder, and the plugins view's freshness row now use the shared path helpers (`paths.ts`).
+- fix: **forget history** (Events) and **forget saved views** (Workflows) work on Windows. They ran `rm -f`, which Windows does not have; there the files are emptied through the host file API (saved views as a valid empty document) and the result is verified by what the file holds. Linux and macOS are unchanged.
+- fix: ADR status changes on records with CRLF line endings (git autocrlf on Windows). A MADR record failed with "the front matter is not closed", and other formats got mixed endings; records are now edited as LF text and written back with their own endings.
+- fix: the standalone terminal (`ruflo tui`) draws in colour on Windows. It treated an unset `TERM` as "no terminal", but Windows Terminal, PowerShell and cmd leave `TERM` unset; only `TERM=dumb` or `NO_COLOR` turn colour off there.
+- fix: the Conversation board finds codex on Windows with `where` (there is no `which`).
+- fix: mission spend works on Windows (needs ruflo-cost-tracker 0.28.3, which fixes the ledger script itself).
+- fix: the autopilot's text checks know Windows (groundwork: a start is still refused there). A task naming `C:\…`, `\\share\…`, `..\…`, `%USERPROFILE%\…` or `$env:USERPROFILE\…` is checked against the envelope folders; `rmdir /s`, `del C:\`, `format C:`, `Remove-Item -Recurse` and `rm -rf C:\` are hard denies; a verify command may not be `cmd`, `powershell`, `pwsh`, `wsl`, `bash.exe` and the like, by basename under either separator and without `.exe`. These only park or refuse more.
+- fix: the Overview heading names the last two folders of a Windows project (`ruflo state in x/proj`), where it printed the whole `C:\…` path because it split on `/` only.
+- fix: stopping or messaging a workflow run on Windows finds its task id in a session transcript over 2 MB. The search used `grep`; Windows now uses PowerShell's `Select-String` (path and pattern passed as base64, never parsed as PowerShell).
+- fix: on Windows, which has no `printenv`, the OpenRouter key (`$OPENROUTER_API_KEY`) is read through the engine's environment read. The engine allows only a literal variable name there (`claude plugin validate` refuses a computed one, and the mod then does not load, so `/ruflo` is missing), so another endpoint's key cannot be read on Windows and the send says so instead of claiming the variable is unset.
+- chore: the smoke runs Claude Code's own `claude plugin validate` on the plugin (step 21, skipped without the CLI), and a spec checks that every `$.env.get/set` takes a literal name.
+- fix: a send to a federation peer on Windows says why nothing was sent. The helper is a bash script, and `bash` on a Windows PATH is the WSL launcher, which cannot open a `C:…` path.
+- fix: for a resumed run, the task id from a search is the latest launch, not the first. The search prints matches with no closing brace between them, so the pattern ran across both (any platform).
+- fix: the standalone terminal (`ruflo tui`) reads the installed plugins, the marketplaces and the workflow runs when `CLAUDE_CONFIG_DIR` is not set. Its config folder was left empty; it now falls back to `<home>/.claude` as the engine does (any platform; found by running every view against a real Windows machine).
+- fix: three folder guards (run folders, run files, cost paths) saw `..` only between slashes, so a `..` segment passed on Windows; a config folder ending in a backslash did not match. They use the shared Windows-aware path helpers.
+- fix: the Research section finds ruflo-goals on Windows (it had its own POSIX-only install-path check), and the menu and boot screen name the project by its last folder instead of the whole `C:…` path.
+- fix: the version and install folder the console shows for a plugin installed for several projects are those of the install that applies to this project (the project record, else the user one), not the first record in `installed_plugins.json`, which could be another project's. The updater uses the same Windows-aware comparison, so a session in a subfolder of the project, or with a different drive-letter case, no longer leaves the project's own install stale.
+- chore: `views/pane` reads `menuView` at call time (a cycle through mission-control and model-tools left it undefined when a test loaded the menu first), and `tui-actions` waits for the outcome it checks instead of a fixed 1.2 s. The whole spec set passes on Windows.
+- chore: the real-disk POSIX write specs (modes, FIFOs) are skipped on Windows, which writes through the host file API; one `ruflo tui --plain` spec no longer needs a runnable fake codex there.
+
## 0.49.0 — 2026-10-24
- feat: exact managed session controls in the model palette with existing confirmation and permission gates
- fix: a rescheduling session shows as running, and a session stopped at its budget, waiting on a required action or holding an open tool request shows as active instead of finished
diff --git a/plugins/ruflo-console/hooks/data/adr-write.ts b/plugins/ruflo-console/hooks/data/adr-write.ts
index 3bdf624aa8..647d0c6d34 100644
--- a/plugins/ruflo-console/hooks/data/adr-write.ts
+++ b/plugins/ruflo-console/hooks/data/adr-write.ts
@@ -145,6 +145,24 @@ export function initialRecord(style: Style, date: string): { file: string; text:
export type Edit = { ok: true; text: string } | { ok: false; why: string }
+/**
+ * A record with CRLF line endings (git's autocrlf on Windows) is edited as LF text and written back with CRLF: the front-matter and
+ * line checks below compare whole lines, so a trailing carriage return made a MADR record "not closed" and left mixed endings elsewhere.
+ */
+function keepLineEnds(text: string, edit: (lf: string) => Edit): Edit {
+ if (!text.includes('\r\n')) return edit(text)
+
+ const done = edit(text.replace(/\r\n/g, '\n'))
+
+ return done.ok ? { ok: true, text: done.text.replace(/\n/g, '\r\n') } : done
+}
+
+/** The record with its status changed to `to`: one line replaced where the record has a status, one inserted where it has none. */
+export const withStatus = (text: string, doc: AdrDoc, style: Style, to: AdrStatus, by: { number: number; title: string; file: string } | null = null): Edit => keepLineEnds(text, lf => statusIn(lf, doc, style, to, by))
+
+/** The newer record names what it replaces: a `Supersedes` line after its status (or title), unless it already says so. */
+export const withSupersedes = (text: string, doc: AdrDoc, style: Style, old: { number: number; title: string; file: string }): Edit => keepLineEnds(text, lf => supersedesIn(lf, doc, style, old))
+
const lineIndexOf = (lines: readonly string[], test: (line: string) => boolean): number => lines.findIndex(test)
const INLINE_STATUS = /^(\s*(?:[-*]\s*)?\**\s*status\s*\**\s*:\s*\**\s*)(.*?)(\**\s*)$/i
@@ -160,7 +178,7 @@ export function statusText(style: Style, to: AdrStatus, by: { number: number; ti
}
/** The record with its status changed to `to`: one line replaced where the record has a status, one inserted where it has none. */
-export function withStatus(text: string, doc: AdrDoc, style: Style, to: AdrStatus, by: { number: number; title: string; file: string } | null = null): Edit {
+function statusIn(text: string, doc: AdrDoc, style: Style, to: AdrStatus, by: { number: number; title: string; file: string } | null): Edit {
if (to === 'unknown') return { ok: false, why: 'unknown is not a status to set' }
if (to === 'superseded' && by === null) return { ok: false, why: 'superseded needs the record that supersedes it' }
@@ -215,7 +233,7 @@ export function withStatus(text: string, doc: AdrDoc, style: Style, to: AdrStatu
}
/** The newer record names what it replaces: a `Supersedes` line after its status (or title), unless it already says so. */
-export function withSupersedes(text: string, doc: AdrDoc, style: Style, old: { number: number; title: string; file: string }): Edit {
+function supersedesIn(text: string, doc: AdrDoc, style: Style, old: { number: number; title: string; file: string }): Edit {
if (doc.supersedes.includes(old.number)) return { ok: true, text }
const lines = text.split('\n')
diff --git a/plugins/ruflo-console/hooks/data/ap-envelope.ts b/plugins/ruflo-console/hooks/data/ap-envelope.ts
index 2da27806b1..2289ca7f7a 100644
--- a/plugins/ruflo-console/hooks/data/ap-envelope.ts
+++ b/plugins/ruflo-console/hooks/data/ap-envelope.ts
@@ -21,7 +21,8 @@ export const DENY_PATTERNS: readonly [HardDeny, RegExp][] = [
['deploy', /\b(deploy(s|ed|ing)?\b|gcloud\s+run\s+deploy|firebase\s+deploy|kubectl\s+apply|terraform\s+apply)/i],
['force-push', /(push\s+(--force|-f\b|--force-with-lease)|force[- ]push)/i],
['secret-access', /\b(api[_ -]?key|secret|credential|password|private\s+key|\.env\b|gcloud\s+secrets|token)\b/i],
- ['delete-outside-worktree', /\b(rm\s+-rf?\s+(\/|~|\$HOME)|delete\s+(the\s+)?(home|root|\/)|drop\s+database|mkfs|dd\s+of=\/dev)/i],
+ // The second line is the Windows forms: cmd's `rmdir /s`, `del C:\`, `format C:`, PowerShell's `Remove-Item -Recurse`, and rm on a drive or a variable.
+ ['delete-outside-worktree', /\b(rm\s+-rf?\s+(\/|~|\$HOME)|delete\s+(the\s+)?(home|root|\/)|drop\s+database|mkfs|dd\s+of=\/dev|(rmdir|rd)\s+\/s\b|(del|erase)\s+(\/[a-z]+\s+)*[A-Za-z]:[\\/]|format\s+[A-Za-z]:|Remove-Item\b[^\n]{0,120}-Recurse|rm\s+-rf?\s+([A-Za-z]:|%|\$env:))/i],
['envelope-edit', /\b(autopilot\s+(envelope|scope|settings)|widen\s+(the\s+)?(envelope|scope)|raise\s+(the\s+)?(spend|budget)\s+(cap|ceiling)|grant\s+(itself|autopilot))|\.claude-flow\/(console\/autopilot|protector-mod)|autopilot\/(envelope|journal|kill)|protector-mod|\b(clear|remove|delete|rm|unset|touch)\b[^\n]{0,40}\bkill\s*(flag|switch|file)\b/i],
]
@@ -38,13 +39,16 @@ export const isProtectedPath = (path: string): boolean => {
/** Programs a verify command may not run: shells and wrappers (they turn an argv into a shell line), privilege and network tools, and destructive ones. */
const VERIFY_BANNED = new Set(['sh', 'bash', 'zsh', 'dash', 'fish', 'ksh', 'csh', 'tcsh', 'env', 'xargs', 'sudo', 'doas', 'su', 'eval', 'exec', 'nohup', 'setsid', 'timeout', 'time', 'watch', 'rm', 'rmdir', 'dd', 'mkfs', 'shred', 'chmod', 'chown', 'mv', 'ln', 'curl', 'wget', 'nc', 'ncat', 'socat', 'ssh', 'scp', 'sftp', 'rsync', 'ftp', 'telnet', 'python', 'python3', 'perl', 'ruby', 'php', 'osascript', 'crontab', 'systemctl', 'kill', 'pkill', 'killall', 'tee', 'cp', 'install', 'truncate'])
+/** The same for Windows (an argv starts a program, never a cmd builtin like del or move, so cmd itself is what is banned): its shells and script hosts, and the tools that delete, copy, fetch or change the system. */
+const WINDOWS_BANNED = new Set(['cmd', 'powershell', 'pwsh', 'wsl', 'wscript', 'cscript', 'mshta', 'rundll32', 'regsvr32', 'conhost', 'invoke-expression', 'iex', 'format', 'diskpart', 'reg', 'regedit', 'taskkill', 'takeown', 'icacls', 'cacls', 'attrib', 'certutil', 'bitsadmin', 'schtasks', 'sc', 'net', 'netsh', 'runas', 'msiexec', 'robocopy', 'xcopy'])
const hasCmdSubstitution = (part: string): boolean => /[`\n]|\$\(|;|&&|\|\||\|/.test(part)
/** Why a verify argv is refused, or null. The program is its basename; a shell metacharacter in any part, a banned program or a hard-deny word refuses it. */
export function verifyProblem(argv: readonly string[]): string | null {
- const program = (argv[0] ?? '').split('/').at(-1)?.toLowerCase() ?? ''
+ // The basename under either separator, without a Windows executable suffix: `C:\Windows\System32\cmd.exe` is `cmd`, `bash.exe` is `bash`.
+ const program = (argv[0] ?? '').split(/[\\/]/).at(-1)?.toLowerCase().replace(/\.(exe|com|cmd|bat|ps1)$/, '') ?? ''
- if (VERIFY_BANNED.has(program)) return `"${program.slice(0, 20)}" is a shell, a wrapper or a destructive or network tool and cannot be a verify command`
+ if (VERIFY_BANNED.has(program) || WINDOWS_BANNED.has(program)) return `"${program.slice(0, 20)}" is a shell, a wrapper or a destructive or network tool and cannot be a verify command`
if (argv.some(hasCmdSubstitution)) return 'a verify part holds a shell metacharacter (; | & ` $( newline): give a program and its arguments only'
const joined = argv.join(' ')
diff --git a/plugins/ruflo-console/hooks/data/ap-guard.ts b/plugins/ruflo-console/hooks/data/ap-guard.ts
index a5f9208155..13e158c72c 100644
--- a/plugins/ruflo-console/hooks/data/ap-guard.ts
+++ b/plugins/ruflo-console/hooks/data/ap-guard.ts
@@ -28,8 +28,13 @@ const CLASS_WORDS: readonly [ToolClass, RegExp][] = [
]
const PATH = /(?:^|[\s"'`(=:])(\/(?:[A-Za-z0-9._@-]+\/)*[A-Za-z0-9._@-]+)/g
-/** A path that is not absolute (home, a variable, a parent): it is never inside the envelope's folders, so a task naming one is parked. */
-const RELATIVE_PATH = /(?:^|[\s"'`(=:])(~\/\S*|~(?=\s|$)|\$\{?HOME\}?(?:\/\S*)?|\.\.\/\S*|\.\.(?=\s|$))/g
+/** An absolute Windows path: a drive (`C:\proj\x`, `C:/proj`, `C:\`) or a share (`\\srv\share\x`). It is checked against the envelope's folders like a POSIX one. */
+const WINDOWS_PATH = /(?:^|[\s"'`(=])([A-Za-z]:[\\/](?:(?:[A-Za-z0-9._@-]+[\\/])*[A-Za-z0-9._@-]+)?|\\\\[A-Za-z0-9._-]+\\[A-Za-z0-9._$-]+(?:\\[A-Za-z0-9._@-]+)*)/g
+/**
+ * A path that is not absolute (home, a variable, a parent): it is never inside the envelope's folders, so a task naming one is parked.
+ * Either separator, and the Windows variables (`%USERPROFILE%\x`, `$env:USERPROFILE\x`) next to `~` and `$HOME`.
+ */
+const RELATIVE_PATH = /(?:^|[\s"'`(=:])(~[\\/]\S*|~(?=\s|$)|\$\{?HOME\}?(?:\/\S*)?|%[A-Za-z_]{1,24}%(?:[\\/]\S*)?|\$env:[A-Za-z_]{1,24}(?:[\\/]\S*)?|\.\.[\\/]\S*|\.\.(?=\s|$))/g
/** Verbs whose effect the class words do not capture (they leave the machine, change the system or run arbitrary code): a task using one is parked instead of guessed. */
const UNPLACED = /\b(push(es|ed|ing)?|install(s|ed|ing)?|uninstall|upload|send|post|e-?mail|ssh|scp|rsync|sudo|execute|exec|kill|chmod|chown|shred|wipe|systemctl|crontab)\b/i
@@ -50,7 +55,7 @@ export function classifyTask(id: string, title: string, requirement = ''): TaskF
const hardDeny = DENIES.find(([, pattern]) => pattern.test(text))?.[0] ?? null
const hits = CLASS_WORDS.filter(([, pattern]) => pattern.test(text)).map(([cls]) => cls)
const cls = hits.length === 0 || UNPLACED.test(text) ? null : (hits.at(-1) as ToolClass)
- const paths = [...new Set([...[...text.matchAll(PATH)].map(m => m[1] as string), ...[...text.matchAll(RELATIVE_PATH)].map(m => m[1] as string)])].slice(0, 12)
+ const paths = [...new Set([...[...text.matchAll(PATH)], ...[...text.matchAll(WINDOWS_PATH)], ...[...text.matchAll(RELATIVE_PATH)]].map(m => m[1] as string))].slice(0, 12)
const urls = [...text.matchAll(URLS)]
const hosts = [...new Set(urls.map(match => (match[1] as string).toLowerCase()))].slice(0, 8)
const repos = [...new Set(urls.flatMap(match => ((match[1] as string).toLowerCase() === 'github.com' ? [repoOf(match[2] as string)] : []).filter((name): name is string => name !== null)))].slice(0, 8)
diff --git a/plugins/ruflo-console/hooks/data/facts.ts b/plugins/ruflo-console/hooks/data/facts.ts
index 9badced230..7308367b59 100644
--- a/plugins/ruflo-console/hooks/data/facts.ts
+++ b/plugins/ruflo-console/hooks/data/facts.ts
@@ -4,7 +4,7 @@
* every string cleaned. A value a file does not hold is absent, and the view says n/a.
*/
import { jsonObject, msOf, plain, recordOf, stringOf } from './parse'
-import { hasParentSegment, isAbsolutePath } from './paths'
+import { hasParentSegment, insideOrSame, isAbsolutePath } from './paths'
import { countOf, ratioOf } from './safe'
export type NeuralStats = { trajectories?: number; patterns?: number; signals?: number; lastAdaptationMs?: number }
@@ -160,8 +160,20 @@ export function parseHelpers(text: string | null): { version: string; files: str
export type Installed = { id: string; name: string; marketplace: string; version: string; scope: string; updatedMs?: number; installPath?: string }
-/** `~/.claude/plugins/installed_plugins.json` (version 2): every installed plugin, `name@marketplace`. */
-export function parseInstalled(text: string | null): Installed[] | null {
+/**
+ * The install record that applies to a session in `cwd`: a project or local one whose `projectPath` is `cwd` or holds it (Windows paths compare
+ * ignoring case and separator style), else the user-scope one, else the first. A plugin installed for several projects has one record each; taking
+ * the first showed another project's version and install folder.
+ */
+function entryFor(entries: unknown, cwd: string | undefined): Record<string, unknown> | null {
+ const list = (Array.isArray(entries) ? entries : [entries]).flatMap(entry => recordOf(entry) ?? [])
+ const applies = (entry: Record<string, unknown>): boolean => cwd !== undefined && typeof entry.projectPath === 'string' && insideOrSame(entry.projectPath, cwd)
+
+ return list.find(entry => (entry.scope === 'project' || entry.scope === 'local') && applies(entry)) ?? list.find(entry => entry.scope === 'user') ?? list[0] ?? null
+}
+
+/** `~/.claude/plugins/installed_plugins.json` (version 2): every installed plugin, `name@marketplace`. `cwd` picks the record of a plugin installed more than once. */
+export function parseInstalled(text: string | null, cwd?: string): Installed[] | null {
const value = jsonObject(text)
const plugins = recordOf(value?.plugins)
@@ -173,7 +185,7 @@ export function parseInstalled(text: string | null): Installed[] | null {
.slice(0, 400)
.flatMap(([id, entries]) => {
const [name, marketplace] = id.split('@')
- const entry = recordOf(Array.isArray(entries) ? entries[0] : entries)
+ const entry = entryFor(entries, cwd)
if (entry === null || name === undefined || marketplace === undefined || !/^[A-Za-z0-9._-]{1,80}$/.test(name) || !/^[A-Za-z0-9._-]{1,80}$/.test(marketplace)) {
return []
diff --git a/plugins/ruflo-console/hooks/data/files.ts b/plugins/ruflo-console/hooks/data/files.ts
index f2cc42e1b2..e231f0285c 100644
--- a/plugins/ruflo-console/hooks/data/files.ts
+++ b/plugins/ruflo-console/hooks/data/files.ts
@@ -6,6 +6,7 @@
* Never listed here, never read: `.claude-flow/federation/key-*.json`, `~/.ruflo/nostr.key` and `~/.ruflo/channels.json`
* hold private keys. The console names the first by listing the folder and stats the second only with federation enabled.
*/
+import { trimTrailing } from './paths'
/** The `$.fs` calls a reader makes; each may reject. */
export type ReaderFs = {
@@ -115,7 +116,7 @@ export async function readBounded(fs: ReaderFs, cache: ReadCache, path: string,
}
/** Joins a root and a relative path with one slash. */
-export const under = (root: string, path: string): string => `${root.replace(/\/+$/, '')}/${path}`
+export const under = (root: string, path: string): string => `${trimTrailing(root)}/${path}`
/** Every file the console reads, as text or the reason it has none, and how many changed since the last pass. */
export type DiskRead = { project: Record<ProjectKey, Read>; home: Record<keyof typeof HOME, Read>; changed: number; federationNodes: string[] | null; hasNostrKey: boolean | null }
diff --git a/plugins/ruflo-console/hooks/data/paths.ts b/plugins/ruflo-console/hooks/data/paths.ts
index 5ff818d95b..df1f2ee09c 100644
--- a/plugins/ruflo-console/hooks/data/paths.ts
+++ b/plugins/ruflo-console/hooks/data/paths.ts
@@ -24,6 +24,15 @@ export function joinPath(base: string, ...parts: string[]): string {
return [trimTrailing(base), ...rest].join(sep)
}
+/** True when `path` is `root` or a folder inside it. Windows paths compare ignoring case and separator style (`samePath`, `below`); POSIX paths exactly. */
+export const insideOrSame = (root: string, path: string): boolean => root !== '' && (samePath(root, path) || below(root, path) !== null)
+
+/** The last non-empty segment of a path under either separator: the project folder's name (`/a/b/` and `C:\a\b` both give `b`). */
+export const baseOf = (p: string): string => p.split(/[\\/]/).filter(part => part !== '').at(-1) ?? ''
+
+/** The last `count` segments of a path joined with `/`, for a heading: `/a/b/c` and `C:\a\b\c` both give `b/c`. */
+export const tailOf = (p: string, count = 2): string => p.split(/[\\/]/).slice(-count).join('/')
+
/** Windows paths compare ignoring case, separator style and a trailing separator; POSIX paths compare exactly. */
export function samePath(a: string, b: string): boolean {
if (isWindowsPath(a) || isWindowsPath(b)) {
diff --git a/plugins/ruflo-console/hooks/data/plugin-catalog.ts b/plugins/ruflo-console/hooks/data/plugin-catalog.ts
index 5454ae1fc3..4d8db8ccba 100644
--- a/plugins/ruflo-console/hooks/data/plugin-catalog.ts
+++ b/plugins/ruflo-console/hooks/data/plugin-catalog.ts
@@ -75,17 +75,23 @@ async function pluginOf(fs: ReaderFs, location: string, entry: Record<string, un
if (typeof name !== 'string' || !NAME.test(name) || (source === null && external === null)) return null
- const dir = source !== null ? `${location}/${source}` : (installed.get(name) ?? '')
+ const dir = source !== null ? joinPath(location, source) : (installed.get(name) ?? '')
if (dir === '') {
return { name, options: [], description: plain(typeof entry.description === 'string' ? entry.description : '', 400), version: null, dir, skills: [], agents: [], commands: [], hasMcp: false, isMod: false, ...(external !== null && { external }) }
}
- const manifest = await fs.read(`${dir}/.claude-plugin/plugin.json`).then(
+ const manifest = await fs.read(joinPath(dir, '.claude-plugin', 'plugin.json')).then(
text => recordOf(JSON.parse(text)),
() => null,
)
- const [skills, agents, commands, hasMcp, isMod] = await Promise.all([namesIn(fs, `${dir}/skills`, 'dir'), namesIn(fs, `${dir}/agents`, 'md'), namesIn(fs, `${dir}/commands`, 'md'), exists(fs, `${dir}/.mcp.json`), exists(fs, `${dir}/hooks/register.ts`)])
+ const [skills, agents, commands, hasMcp, isMod] = await Promise.all([
+ namesIn(fs, joinPath(dir, 'skills'), 'dir'),
+ namesIn(fs, joinPath(dir, 'agents'), 'md'),
+ namesIn(fs, joinPath(dir, 'commands'), 'md'),
+ exists(fs, joinPath(dir, '.mcp.json')),
+ exists(fs, joinPath(dir, 'hooks', 'register.ts')),
+ ])
const version = typeof manifest?.version === 'string' ? plain(manifest.version, 30) : typeof entry.version === 'string' ? plain(entry.version, 30) : null
const options = Object.keys(recordOf(manifest?.userConfig) ?? {}).filter(key => NAME.test(key)).slice(0, 60)
@@ -98,7 +104,7 @@ async function pluginOf(fs: ReaderFs, location: string, entry: Record<string, un
* its install path (absolute, already checked by the caller): an external plugin is read from there.
*/
export async function readCatalog(fs: ReaderFs, location: string, installed: ReadonlyMap<string, string> = new Map()): Promise<CatalogPlugin[] | null> {
- if (!location.startsWith('/') || location.split('/').includes('..')) return null
+ if (!isAbsolutePath(location) || hasParentSegment(location)) return null
const raw = await fs.read(joinPath(location, '.claude-plugin', 'marketplace.json')).catch(() => null)
let list: unknown[] = []
@@ -135,7 +141,7 @@ export async function readCatalog(fs: ReaderFs, location: string, installed: Rea
export async function readDoc(fs: ReaderFs, plugin: CatalogPlugin, kind: 'skill' | 'agent' | 'command', name: string): Promise<{ description: string; lines: string[] } | null> {
if (!NAME.test(name) || plugin.dir === '') return null
- const path = kind === 'skill' ? `${plugin.dir}/skills/${name}/SKILL.md` : `${plugin.dir}/${kind === 'agent' ? 'agents' : 'commands'}/${name}.md`
+ const path = kind === 'skill' ? joinPath(plugin.dir, 'skills', name, 'SKILL.md') : joinPath(plugin.dir, kind === 'agent' ? 'agents' : 'commands', `${name}.md`)
const stat = await fs.stat(path).catch(() => undefined)
if (stat === undefined || (stat.size ?? 0) > DOC_BYTES) return null
diff --git a/plugins/ruflo-console/hooks/data/research.ts b/plugins/ruflo-console/hooks/data/research.ts
index c3d7c6387a..ce8e92bb30 100644
--- a/plugins/ruflo-console/hooks/data/research.ts
+++ b/plugins/ruflo-console/hooks/data/research.ts
@@ -4,6 +4,7 @@
* document. Local only: nothing here reaches the network, and the script path comes from `installed_plugins.json`,
* validated, never from typed text. Read-only: the section stores and starts nothing.
*/
+import { safeInstallPath } from './cost-ledger'
import type { Probe } from './cli'
import { jsonObject, msOf, recordOf, stringOf } from './parse'
import { measureOf } from './safe'
@@ -32,12 +33,8 @@ const STATUSES: readonly string[] = ['done', 'truncated', 'failed']
const MAX_RECORDS = 8
const MAX_FINDINGS = 500
-/** An absolute POSIX path of a plugin's install directory: no `..`, no control characters, no shell-looking text. */
-export const safeInstallPath = (value: unknown): string | undefined => {
- const path = typeof value === 'string' ? value : ''
-
- return /^\/[A-Za-z0-9._@+/ -]{1,300}$/.test(path) && !path.split('/').includes('..') ? path : undefined
-}
+/** An absolute path of a plugin's install directory (POSIX, or drive-lettered on Windows): data/cost-ledger.ts holds the one check. */
+export { safeInstallPath }
const countGrades = (findings: readonly unknown[]): Record<Grade, number> => {
const grades: Record<Grade, number> = { High: 0, Medium: 0, Low: 0 }
diff --git a/plugins/ruflo-console/hooks/data/snapshot.ts b/plugins/ruflo-console/hooks/data/snapshot.ts
index 79d0a82653..680dd7cd19 100644
--- a/plugins/ruflo-console/hooks/data/snapshot.ts
+++ b/plugins/ruflo-console/hooks/data/snapshot.ts
@@ -30,6 +30,7 @@ import { readBounded, readDisk, textOf, type ProjectKey, type Read, type ReadCac
import { parseAgentdbMod, type AgentdbMod } from './agentdb-mod'
import { readMods, type ModsFacts } from './mods'
import { readManaged, type ManagedFacts, type ManagedLearning } from './managed'
+import { joinPath } from './paths'
import {
parseAgents,
parseClaims,
@@ -113,7 +114,7 @@ export async function readSnapshot(fs: ReaderFs, cache: ReadCache, cwd: string,
stored ?? (pointer !== null ? { id: pointer.id, topology: pointer.topology ?? 'unknown', status: pointer.status ?? 'unknown', agentIds: [], ...(pointer.strategy !== undefined && { strategy: pointer.strategy }) } : null)
const markets = parseMarketplaces(textOf(disk.home.marketplaces))
const location = markets?.find(market => market.name === RUFLO_MARKET)?.location
- const offered = location === undefined ? null : parseMarketplaceManifest(textOf(await readBounded(fs, cache, `${location}/.claude-plugin/marketplace.json`)))
+ const offered = location === undefined ? null : parseMarketplaceManifest(textOf(await readBounded(fs, cache, joinPath(location, '.claude-plugin', 'marketplace.json'))))
const reads = Object.fromEntries((Object.keys(disk.project) as ProjectKey[]).map(key => [key, statusOf(disk.project[key])])) as Snapshot['reads']
const managed = await readManaged(fs, cache, cwd)
@@ -141,7 +142,7 @@ export async function readSnapshot(fs: ReaderFs, cache: ReadCache, cwd: string,
federationNodes: disk.federationNodes,
hasNostrKey: disk.hasNostrKey,
plugins: {
- installed: parseInstalled(textOf(disk.home.installed)),
+ installed: parseInstalled(textOf(disk.home.installed), cwd),
enabled: enabledOf(settings),
enabledKnown: typeof (settings as { enabledPlugins?: unknown } | null)?.enabledPlugins === 'object' && (settings as { enabledPlugins?: unknown }).enabledPlugins !== null,
markets,
diff --git a/plugins/ruflo-console/hooks/data/wf-control.ts b/plugins/ruflo-console/hooks/data/wf-control.ts
index b9e266c03c..7b91c2e103 100644
--- a/plugins/ruflo-console/hooks/data/wf-control.ts
+++ b/plugins/ruflo-console/hooks/data/wf-control.ts
@@ -86,7 +86,25 @@ export function taskIdOf(text: string, runId: string): string | null {
const hits = [...text.matchAll(new RegExp(taskPattern(runId), 'g'))]
const last = hits.at(-1)
- return last === undefined ? null : (/"taskId":"([A-Za-z0-9]{6,40})"/.exec(last[0])?.[1] ?? null)
+ // A search prints only the matches, with no closing brace between two launches of one run, so one match can hold both: the last task id in it wins.
+ return last === undefined ? null : ([...last[0].matchAll(/"taskId":"([A-Za-z0-9]{6,40})"/g)].at(-1)?.[1] ?? null)
+}
+
+const utf8Base64 = (text: string): string => btoa(Array.from(new TextEncoder().encode(text), byte => String.fromCharCode(byte)).join(''))
+
+/**
+ * The transcript search for Windows, which has no `grep`: PowerShell's Select-String reads the file line by line and prints only what
+ * matched (`grep -o`). The path and the pattern ride inside the script as base64 and are decoded there, so no character of either is ever
+ * parsed as PowerShell (a path with a space, a quote or a `$` is only data); the script itself has no double quote. Null for a run id that is
+ * not one, a path with a NUL, or a host without TextEncoder/btoa.
+ */
+export function windowsSearchArgv(path: string, runId: string): readonly string[] | null {
+ if (!RUN_ID.test(runId) || path === '' || path.includes('\0') || typeof TextEncoder !== 'function' || typeof btoa !== 'function') return null
+
+ const text = (value: string): string => `[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${utf8Base64(value)}'))`
+ const script = `$p=${text(path)};$q=${text(taskPattern(runId))};Select-String -LiteralPath $p -Pattern $q -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value }`
+
+ return ['powershell', '-NoProfile', '-NonInteractive', '-Command', script]
}
/** The session transcript that launched a run: the run's directory (`<session>/subagents/workflows/<run>`) without its tail, plus `.jsonl`. Null when the path is not a run path. */
diff --git a/plugins/ruflo-console/hooks/data/wf-drill-io.ts b/plugins/ruflo-console/hooks/data/wf-drill-io.ts
index 80f4df3709..e63ac64328 100644
--- a/plugins/ruflo-console/hooks/data/wf-drill-io.ts
+++ b/plugins/ruflo-console/hooks/data/wf-drill-io.ts
@@ -48,9 +48,9 @@ export function resetDrillIo(): void {
/** True for a path under `<configDir>/projects/` with no `..` part and no NUL: the only place a run's files live. */
export function isRunFile(path: string, configDir: string | null): boolean {
- if (configDir === null || path.includes('\0') || path.includes('\n') || path.split('/').includes('..')) return false
+ if (configDir === null || path.includes('\0') || path.includes('\n') || hasParentSegment(path)) return false
- return path.startsWith(`${configDir.replace(/\/+$/, '')}/projects/`)
+ return path.startsWith(`${trimTrailing(configDir)}/projects/`)
}
/** True for an absolute path inside the project's working directory (where Claude Code puts an agent's worktree), with no `..` part. */
diff --git a/plugins/ruflo-console/hooks/data/wf-send.ts b/plugins/ruflo-console/hooks/data/wf-send.ts
index ed611afcef..c3eeb78f0e 100644
--- a/plugins/ruflo-console/hooks/data/wf-send.ts
+++ b/plugins/ruflo-console/hooks/data/wf-send.ts
@@ -13,6 +13,7 @@ import { callTool, permissionOf } from './wf-control'
import { cleanText } from './wf-clean'
import { guardText } from './wf-guide'
import { idOf, plain, type HiveInfo } from './parse'
+import { isWindowsPath } from './paths'
import { endpointsOf, type Config, type Endpoint, type Target } from './wf-targets'
export type SendDeps = Pick<Host, 'toolCall' | 'toolCheck' | 'run' | 'httpSend' | 'submitPrompt'> & {
@@ -24,6 +25,8 @@ export type SendDeps = Pick<Host, 'toolCall' | 'toolCheck' | 'run' | 'httpSend'
cwd: string
hive: HiveInfo | null
config: Config
+ /** Reads a model key from the environment. Set on Windows, which has no `printenv` (and where the engine allows only a literal variable name, so only $OPENROUTER_API_KEY); where absent a key is read with `printenv`. */
+ readEnv?: (name: string) => Promise<string | undefined>
}
export type SendState = 'reply' | 'queued' | 'sent' | 'error' | 'refused'
@@ -178,6 +181,9 @@ export async function sendTo(deps: SendDeps, target: Target, raw: string): Promi
case 'x-channel':
return viaCli(deps, 'x_federation_channel_publish', { channel: target.ref, msgType: 'Status', payload: { text: body, from: 'ruflo-console' } })
case 'peer': {
+ // The helper is a shell script. Windows has no bash of its own on the PATH (`bash` there is the WSL launcher, which cannot open a C:... script path), so nothing is run.
+ if (isWindowsPath(deps.helper)) return err('refused', 'a peer is reached through a bash helper script (federation.sh), which Windows cannot run from here: nothing was sent. Use a BBS room or a channel instead.')
+
const result = await deps.run(['bash', deps.helper, 'dispatch', target.ref, body, ...(deps.trustedPeers.has(target.ref) ? [] : ['--confirm'])], WAIT.peer).catch((error: unknown) => ({ exitCode: -1, stdout: '', stderr: error instanceof Error ? error.message : 'refused' }))
return result.exitCode === 0 && result.stdout.trim() !== '' ? { ok: true, state: 'reply', text: tidy(result.stdout).trim() } : err('error', result.stderr.trim() !== '' ? result.stderr : `the peer answered nothing (exit ${result.exitCode})`)
@@ -197,11 +203,17 @@ export async function sendTo(deps: SendDeps, target: Target, raw: string): Promi
let key: string | undefined
if (endpoint.keyEnv !== 'NONE') {
- const read = await deps.run(['printenv', endpoint.keyEnv], 5_000).catch(() => undefined)
+ if (deps.readEnv !== undefined) key = (await deps.readEnv(endpoint.keyEnv).catch(() => undefined))?.trim()
+ else {
+ const read = await deps.run(['printenv', endpoint.keyEnv], 5_000).catch(() => undefined)
+
+ key = read !== undefined && read.exitCode === 0 ? read.stdout.trim() : undefined
+ }
- key = read !== undefined && read.exitCode === 0 ? read.stdout.trim() : undefined
+ // Where the environment read stands in for printenv (Windows) it can name only the OpenRouter key: the engine lists the variables a module reads.
+ const unreadable = deps.readEnv !== undefined && endpoint.keyEnv !== 'OPENROUTER_API_KEY'
- if (key === undefined || key === '') return err('refused', `$${endpoint.keyEnv} is not set in the environment Claude Code runs in: nothing was sent`)
+ if (key === undefined || key === '') return err('refused', unreadable ? `$${endpoint.keyEnv} cannot be read here: on Windows the console can read only $OPENROUTER_API_KEY from the environment. Nothing was sent` : `$${endpoint.keyEnv} is not set in the environment Claude Code runs in: nothing was sent`)
}
const response = await deps.httpSend(`${endpoint.baseUrl}/chat/completions`, { method: 'POST', headers: { 'content-type': 'application/json', ...(key !== undefined && { authorization: `Bearer ${key}` }) }, body: chatBody(endpoint, body) }).catch((error: unknown) => ({ ok: false, status: 0, text: error instanceof Error ? error.message : 'refused' }))
diff --git a/plugins/ruflo-console/hooks/data/write-via.ts b/plugins/ruflo-console/hooks/data/write-via.ts
index 849d8fb9a9..9ff5d9c046 100644
--- a/plugins/ruflo-console/hooks/data/write-via.ts
+++ b/plugins/ruflo-console/hooks/data/write-via.ts
@@ -75,6 +75,22 @@ export function argvOf(flavor: Exclude<WriteFlavor, 'host-fs'>, op: WriteOp): re
}
}
+/**
+ * "Forget" on Windows (host-fs), which has no delete: each of `paths` that is there is replaced by `text` (empty by default). A file that
+ * is not there is left alone, so nothing is created. Resolves to the first refusal's reason, or null when every file took it.
+ */
+export async function emptyFiles(host: WriteHost, paths: readonly string[], text = ''): Promise<string | null> {
+ for (const path of paths) {
+ if ((await host.fs.stat(path).catch(() => undefined)) === undefined) continue
+
+ const done = await writeVia('host-fs', host, { kind: 'replace', path, text, hasDir: true })
+
+ if (done.exitCode !== 0) return done.stderr.trim() !== '' ? done.stderr.trim() : `the write exited ${done.exitCode}`
+ }
+
+ return null
+}
+
/** Carries out one write, the way the machine's flavor says. */
export async function writeVia(flavor: WriteFlavor, host: WriteHost, op: WriteOp): Promise<WriteResult> {
if (flavor !== 'host-fs') return host.run(argvOf(flavor, op), op.timeoutMs ?? 10_000, op.text)
diff --git a/plugins/ruflo-console/hooks/events-forget.ts b/plugins/ruflo-console/hooks/events-forget.ts
new file mode 100644
index 0000000000..c0efa1aa39
--- /dev/null
+++ b/plugins/ruflo-console/hooks/events-forget.ts
@@ -0,0 +1,45 @@
+/**
+ * The confirm-gated "forget the Events and Timeline history" action. Linux and macOS remove the two history files with `rm -f`; Windows
+ * (host-fs, data/write-flavor.ts) has no rm and no delete, so there each file is emptied through the host's file API instead.
+ */
+import type { ActionSpec } from './actions'
+import { plain } from './data/parse'
+import type { WriteFlavor } from './data/write-flavor'
+import { emptyFiles, type WriteHost } from './data/write-via'
+
+const LABEL = 'forget the Events and Timeline history'
+const NOTE = "only the console's own history files for this project; saved searches, pins and rules stay"
+
+/** `forgotten` runs once the files are gone (or emptied): the page drops what it holds in memory. */
+export function forgetEventsSpec(flavor: WriteFlavor, paths: { events: string; lanes: string }, host: WriteHost, forgotten: () => void): ActionSpec {
+ if (flavor !== 'host-fs') {
+ return {
+ label: LABEL,
+ args: [],
+ argv: ['rm', '-f', '--', paths.events, paths.lanes],
+ expect: 'events.jsonl and lanes.jsonl removed',
+ declared: 'delete',
+ shows: `rm -f -- ${paths.events} ${paths.lanes}`,
+ note: `deletes ${NOTE}`,
+ timeoutMs: 10_000,
+ onOutput: forgotten,
+ verifyLocal: async h => (await h.fs.stat(paths.events).catch(() => undefined)) === undefined,
+ }
+ }
+
+ return {
+ label: LABEL,
+ args: [],
+ expect: 'events.jsonl and lanes.jsonl emptied',
+ declared: 'delete',
+ shows: `empty ${paths.events} and ${paths.lanes} (no delete on Windows: the files stay, with no history in them)`,
+ note: `empties ${NOTE}`,
+ run: async () => {
+ const problem = await emptyFiles(host, [paths.events, paths.lanes])
+
+ if (problem === null) forgotten()
+
+ return { label: LABEL, ok: problem === null, detail: problem === null ? 'events.jsonl and lanes.jsonl emptied' : `the write failed: ${plain(problem, 120)}` }
+ },
+ }
+}
diff --git a/plugins/ruflo-console/hooks/events-ui.ts b/plugins/ruflo-console/hooks/events-ui.ts
index 8ca2769c91..47ebf5c5e8 100644
--- a/plugins/ruflo-console/hooks/events-ui.ts
+++ b/plugins/ruflo-console/hooks/events-ui.ts
@@ -5,6 +5,8 @@
* (data/activity-store.ts Prefs) which go through hooks/activity-live.ts.
*/
import { isoOf } from './data/safe'
+import { writeFlavorReady } from './data/write-flavor'
+import { forgetEventsSpec } from './events-forget'
import { activityOf, clearMemory, markPrefsDirty, pathsOf, seqOf, takeRing } from './activity-live'
import { MAX_PINS, MAX_RULES, MAX_SEARCHES, type Pin } from './data/activity-store'
import { exportSpecFor, eventsText, formatOf } from './data/event-export'
@@ -449,26 +451,12 @@ export function eventsActions(state: State, host: Host, invalidate: () => void,
askSpec(made.spec, 'that export cannot run here')
},
forget: () => {
- const paths = pathsOf(state.cwd)
-
- askSpec(
- {
- label: 'forget the Events and Timeline history',
- args: [],
- argv: ['rm', '-f', '--', paths.events, paths.lanes],
- expect: 'events.jsonl and lanes.jsonl removed',
- declared: 'delete',
- shows: `rm -f -- ${paths.events} ${paths.lanes}`,
- note: 'deletes only the console\'s own history files for this project; saved searches, pins and rules stay',
- timeoutMs: 10_000,
- onOutput: () => {
- clearMemory(state)
- say(ui, 'history forgotten')
- },
- verifyLocal: async h => (await h.fs.stat(paths.events).catch(() => undefined)) === undefined,
- },
- 'that cannot run here',
- )
+ const forgotten = () => {
+ clearMemory(state)
+ say(ui, 'history forgotten')
+ }
+
+ void writeFlavorReady().then(flavor => askSpec(forgetEventsSpec(flavor, pathsOf(state.cwd), host, forgotten), 'that cannot run here'))
},
ask: event => askClaude(`This event appeared in my ruflo console: "${maskLine(event.text, 200)}" (kind ${event.kind}, level ${levelOfEvent(event)}). What does it mean, and should I do anything?`),
page: by => {
diff --git a/plugins/ruflo-console/hooks/host.ts b/plugins/ruflo-console/hooks/host.ts
index 8f27f2a1b2..15e17b17e9 100644
--- a/plugins/ruflo-console/hooks/host.ts
+++ b/plugins/ruflo-console/hooks/host.ts
@@ -44,6 +44,8 @@ export type Host = {
settings: () => Promise<unknown>
home: () => Promise<string | undefined>
configDir: () => Promise<string | undefined>
+ /** One environment variable of the engine's process, or undefined when unset. Windows has no `printenv`, so a key is read through this there. */
+ env?: (name: string) => Promise<string | undefined>
/** This plugin's folder: where its own files (the command catalog) are. */
pluginRoot: string
rufloSnapshot: () => Promise<RufloSnapshot>
diff --git a/plugins/ruflo-console/hooks/register.ts b/plugins/ruflo-console/hooks/register.ts
index c20a4ac380..b10e777cbe 100644
--- a/plugins/ruflo-console/hooks/register.ts
+++ b/plugins/ruflo-console/hooks/register.ts
@@ -126,6 +126,9 @@ function hostOf($: EngineInterface, cwd: string, toasts: { prefs: () => ToastPre
return homeOf(k => envVars[k])
},
configDir: async () => $.env.get('CLAUDE_CONFIG_DIR'),
+ // The engine lists the variables a module reads, so $.env.get takes a literal name (`claude plugin validate` refuses a computed one, and the mod then does not load):
+ // the one model key the console's own OpenRouter target names is readable here; any other name is not.
+ env: async name => (name === 'OPENROUTER_API_KEY' ? $.env.get('OPENROUTER_API_KEY') : undefined),
pluginRoot: $.plugin.root,
// `$.ruflo` exists only where ruflo-mods is seated; validate refuses feature-detecting a noun, so these are
// async: a missing noun throws inside the promise and every caller's catch sees a rejection.
diff --git a/plugins/ruflo-console/hooks/updates.ts b/plugins/ruflo-console/hooks/updates.ts
index 742d61b180..88b0ae4347 100644
--- a/plugins/ruflo-console/hooks/updates.ts
+++ b/plugins/ruflo-console/hooks/updates.ts
@@ -6,6 +6,7 @@
* confirmation for a marketplace-declared command is never bypassed (no `-y`, no `--accept-command`).
*/
import { ESCAPES, HIDDEN } from './data/parse'
+import { insideOrSame } from './data/paths'
import { RUFLO_MARKET } from './data/snapshot'
export type UpdatesMode = 'ask' | 'auto' | 'off'
@@ -116,7 +117,7 @@ export function installedEntries(listJson: string, cwd: string, id: string = PLU
if (!Array.isArray(list)) return []
const ours = list.filter((entry): entry is { id: string; version?: unknown; scope?: unknown; projectPath?: unknown } => typeof entry === 'object' && entry !== null && (entry as { id?: unknown }).id === id)
- const here = (entry: { projectPath?: unknown }) => typeof entry.projectPath === 'string' && entry.projectPath !== '' && (cwd === entry.projectPath || cwd.startsWith(`${entry.projectPath.replace(/\/+$/, '')}/`))
+ const here = (entry: { projectPath?: unknown }) => typeof entry.projectPath === 'string' && entry.projectPath !== '' && insideOrSame(entry.projectPath, cwd)
const applies = ours.filter(entry => entry.scope === 'user' || ((entry.scope === 'project' || entry.scope === 'local') && here(entry)))
const valid = applies.flatMap(entry => (typeof entry.version === 'string' && typeof entry.scope === 'string' ? [{ version: entry.version, scope: entry.scope }] : []))
diff --git a/plugins/ruflo-console/hooks/version.ts b/plugins/ruflo-console/hooks/version.ts
index abcb2125ea..fec277af46 100644
--- a/plugins/ruflo-console/hooks/version.ts
+++ b/plugins/ruflo-console/hooks/version.ts
@@ -2,4 +2,4 @@
* The console's version, shown on the header so a person can tell which build is running. Kept equal to the plugin's manifest
* (`.claude-plugin/plugin.json`); tests/version.spec.ts fails if the two drift.
*/
-export const CONSOLE_VERSION = '0.49.0'
+export const CONSOLE_VERSION = '0.49.1'
diff --git a/plugins/ruflo-console/hooks/views/frames.ts b/plugins/ruflo-console/hooks/views/frames.ts
index bde510e50c..e2645ef901 100644
--- a/plugins/ruflo-console/hooks/views/frames.ts
+++ b/plugins/ruflo-console/hooks/views/frames.ts
@@ -14,6 +14,7 @@ import { bootFacts } from '../boot-facts'
import { getBuild } from '../build'
import { PALETTE, rgb } from '../menu-colors'
import { CONSOLE_VERSION } from '../version'
+import { baseOf } from '../data/paths'
import type { Snapshot } from '../data/snapshot'
import type { Channels, Peers, Roster } from '../data/cli'
import { pipelinePicture, radarPicture, samplesPicture, trendPicture, gaugePicture, type Stage } from '../gfx/charts'
@@ -192,7 +193,7 @@ export function picturesOf(state: State, columns: number, nowMs: number, t: numb
// The selected boot screen owns the pane for its first seconds; nothing else is drawn under it.
if (isBooting(state, nowMs)) {
- pictures.set('boot', state.options.look === 'orbital' ? orbitalBoot(state.cwd.split('/').filter(Boolean).at(-1) ?? '', Math.max(1, Math.min(columns, width, 90)), state.options.fps > 0 ? (nowMs - state.pane.bootAtMs) * theme.motion.speed : 0, getBootChecks(), state.pane.rows > 0 ? state.pane.rows : 30, theme) : bootPicture(state.cwd.split('/').filter(Boolean).at(-1) ?? '', Math.min(width, 90), nowMs - state.pane.bootAtMs, state.probes.size, PROBES.length, state.pane.rows, getBootChecks(), bootFacts(state, CONSOLE_VERSION, getBuild())))
+ pictures.set('boot', state.options.look === 'orbital' ? orbitalBoot(baseOf(state.cwd), Math.max(1, Math.min(columns, width, 90)), state.options.fps > 0 ? (nowMs - state.pane.bootAtMs) * theme.motion.speed : 0, getBootChecks(), state.pane.rows > 0 ? state.pane.rows : 30, theme) : bootPicture(baseOf(state.cwd), Math.min(width, 90), nowMs - state.pane.bootAtMs, state.probes.size, PROBES.length, state.pane.rows, getBootChecks(), bootFacts(state, CONSOLE_VERSION, getBuild())))
return pictures
}
@@ -202,7 +203,7 @@ export function picturesOf(state: State, columns: number, nowMs: number, t: numb
const headerAge = moving ? Math.min(sinceSwitch, entryAge({ look: state.options.look, boot: state.options.boot, ...state.pane }, nowMs, BOOT_MIN_MS) ?? Infinity) : Infinity
if (state.view === 'menu') {
- const project = state.cwd.split('/').filter(Boolean).at(-1) ?? ''
+ const project = baseOf(state.cwd)
pictures.set('header', state.options.look === 'bbs' ? fitHeader(columns, size => bannerPicture(project, size, light, headerAge), 72) : headerPicture(`◆ ruflo v${CONSOLE_VERSION}${getBuild() === '' ? '' : ` · ${getBuild()}`} · ${project}`, Math.min(width, 64), light))
// The palette strip above the menu's groups moves while the frame loop runs; with fps 0 it is the still strip (the light is off it).
diff --git a/plugins/ruflo-console/hooks/views/menu.ts b/plugins/ruflo-console/hooks/views/menu.ts
index 82d386a884..ba9691b81e 100644
--- a/plugins/ruflo-console/hooks/views/menu.ts
+++ b/plugins/ruflo-console/hooks/views/menu.ts
@@ -8,6 +8,7 @@ import { VIEWS, type ViewId } from '../state'
import { barParts } from './bar'
import { art, button, clip, col, isBbs, isOrbital, row, text, THEME, type Ctx } from './common'
import { missionStrip } from './mission-control'
+import { baseOf } from '../data/paths'
type Item = { label: string; go: string }
@@ -73,7 +74,7 @@ export function menuView(ctx: Ctx): RenderElement {
const { state, nowMs } = ctx
// While the entry plays (menu-entry.ts) the cards light up in turn; null once it is over, or when there is none.
const entry = entryAge({ look: state.options.look, boot: state.options.boot, ...state.pane }, nowMs, BOOT_MIN_MS)
- const project = state.cwd.split('/').filter(Boolean).at(-1) ?? 'ruflo'
+ const project = baseOf(state.cwd) || 'ruflo'
const go = (item: Item) => () => (item.go === 'palette' ? ctx.act.palette('all') : item.go === 'help' ? ctx.act.help() : item.go === 'close' ? ctx.act.close() : ctx.act.view(item.go as ViewId))
const isShown = (item: Item) => COMMANDS.has(item.go) || VIEWS.some(view => view.id === item.go)
// Two boxes a row where the pane is wide enough, else one; each box is a group with its own border.
diff --git a/plugins/ruflo-console/hooks/views/overview.ts b/plugins/ruflo-console/hooks/views/overview.ts
index 1e9fd253bb..9a80dcf89f 100644
--- a/plugins/ruflo-console/hooks/views/overview.ts
+++ b/plugins/ruflo-console/hooks/views/overview.ts
@@ -5,6 +5,7 @@ import type { MemoryStats } from '../data/cli'
import type { StartId } from '../starts'
import { brainStatusOf, BRAIN_REPO, statusLine as groundingLine } from '../grounding'
import { settingsOf } from '../settings'
+import { tailOf } from '../data/paths'
import { controlRows, isControlActive } from './control'
import { optimizerRows } from './optimizer'
import { uniqueAgents } from '../data/swarm-status'
@@ -31,7 +32,7 @@ export function overviewView(ctx: Ctx): RenderElement {
kv(
ctx,
'project',
- snap === null ? 'reading…' : snap.isRufloProject ? `ruflo state in ${state.cwd.split('/').slice(-2).join('/')}` : 'n/a — no .claude-flow here (see Get going below)',
+ snap === null ? 'reading…' : snap.isRufloProject ? `ruflo state in ${tailOf(state.cwd)}` : 'n/a — no .claude-flow here (see Get going below)',
snap?.isRufloProject === true ? THEME.ok : undefined,
),
)
diff --git a/plugins/ruflo-console/hooks/views/pane.ts b/plugins/ruflo-console/hooks/views/pane.ts
index e35a735d64..c6c9880a34 100644
--- a/plugins/ruflo-console/hooks/views/pane.ts
+++ b/plugins/ruflo-console/hooks/views/pane.ts
@@ -70,7 +70,9 @@ const NETWORKS: readonly (readonly [string, ViewId])[] = [['x.ruv.io', 'xruv'],
const WIDE_TABS = 140
export const BODIES: Record<ViewId, (ctx: Ctx) => RenderElement> = {
- menu: menuView,
+ // Read at call time: views/menu reaches this module through mission-control > model-tools, so loading menu first (a test does) would otherwise
+ // find `menuView` not yet defined when this table is built.
+ menu: ctx => menuView(ctx),
overview: overviewView,
swarm: swarmView,
workflows: workflowsPage,
diff --git a/plugins/ruflo-console/hooks/views/wf-control.ts b/plugins/ruflo-console/hooks/views/wf-control.ts
index a93e83b8a6..a04d699c70 100644
--- a/plugins/ruflo-console/hooks/views/wf-control.ts
+++ b/plugins/ruflo-console/hooks/views/wf-control.ts
@@ -8,8 +8,9 @@
import type { RenderElement } from 'claude-code'
import { cleanText } from '../data/wf-clean'
-import { controlActions, taskIdOf, taskPattern, transcriptOf, type ControlAction, type ControlInput, type TaskRef } from '../data/wf-control'
+import { controlActions, taskIdOf, taskPattern, transcriptOf, windowsSearchArgv, type ControlAction, type ControlInput, type TaskRef } from '../data/wf-control'
import { tidy } from '../data/wf-send'
+import { writeFlavorReady } from '../data/write-flavor'
import type { Host } from '../host'
import type { State } from '../state'
import type { WfRun } from '../data/workflows'
@@ -70,7 +71,12 @@ async function findTask(state: State, host: Host, run: Pick<WfRun, 'id' | 'dir'>
/** A transcript too large to read whole: grep prints only the launch result's task and run ids (argv, no shell; the path is a checked run path). */
async function searchTask(host: Host, path: string, runId: string): Promise<string | null> {
- const result = await host.run(['grep', '-o', '-E', taskPattern(runId), path], 10_000)
+ // Windows has no grep: the same search through PowerShell (data/wf-control.ts); null where it cannot be built.
+ const argv = (await writeFlavorReady()) === 'host-fs' ? windowsSearchArgv(path, runId) : ['grep', '-o', '-E', taskPattern(runId), path]
+
+ if (argv === null) return null
+
+ const result = await host.run(argv, 10_000)
return result.exitCode === 0 ? taskIdOf(result.stdout, runId) : null
}
diff --git a/plugins/ruflo-console/hooks/views/wf-saved.ts b/plugins/ruflo-console/hooks/views/wf-saved.ts
index 927414c172..83d898e542 100644
--- a/plugins/ruflo-console/hooks/views/wf-saved.ts
+++ b/plugins/ruflo-console/hooks/views/wf-saved.ts
@@ -7,6 +7,7 @@ import type { RenderElement } from 'claude-code'
import { MAX_PINS, SAVED_FILE, SAVED_MAX_BYTES, isPinned, pinsIn, togglePin } from '../data/wf-saved'
import { currentPhase, type WfRun } from '../data/workflows'
+import { writeFlavorReady } from '../data/write-flavor'
import { forgetSpec, savedFor, updateSaved } from '../wf-saved-live'
import { ago, button, clip, row, text, THEME } from './common'
import { fold, redraw } from './wf-fold'
@@ -36,7 +37,7 @@ export function savedBody(env: SlotEnv, run: WfRun | null): RenderElement[] {
text(ctx, ` search: ${own.saved.search === '' ? 'none' : `"${clip(own.saved.search, 40)}"`} · filters: ${filters === '' ? 'none' : filters}`, { dimColor: true }),
row(ctx, [
...(run === null ? [] : [button(ctx, 'wf-saved-pin', isPinned(own.saved, run.id) ? 'Unpin this run' : 'Pin this run', pin)]),
- button(ctx, 'wf-saved-forget', 'Forget saved views', () => ctx.act.workflows.ask(forgetSpec(cwd))),
+ button(ctx, 'wf-saved-forget', 'Forget saved views', () => void writeFlavorReady().then(flavor => ctx.act.workflows.ask(forgetSpec(cwd, flavor)))),
], 'wf-saved-controls'),
...(own.said === null ? [] : [text(ctx, ` ${own.said}`, { color: THEME.info })]),
...(pins.length === 0 ? [text(ctx, ` No pinned runs (up to ${MAX_PINS}).`, { dimColor: true })] : pins.map(entry => (entry.index === null || entry.run === null ? text(ctx, ` ◌ ${clip(entry.pin.name, 40)} · not among the runs read now`, { dimColor: true }) : row(ctx, [button(ctx, `wf-saved-go-${entry.index}`, `▸ ${clip(entry.pin.name, 28)}`, () => jump(env, entry.index as number, entry.run as WfRun)), text(ctx, ` ${entry.run.state} · ${entry.run.done}/${entry.run.total} agents`, { dimColor: true })], `wf-saved-pin-${entry.index}`)))),
diff --git a/plugins/ruflo-console/hooks/wf-actions.ts b/plugins/ruflo-console/hooks/wf-actions.ts
index c40e387a71..be74680ffc 100644
--- a/plugins/ruflo-console/hooks/wf-actions.ts
+++ b/plugins/ruflo-console/hooks/wf-actions.ts
@@ -4,6 +4,7 @@
* Nothing in THIS file stops or messages a running Claude Code workflow: that is the control tab (views/wf-control.ts, ADR-465), which calls the engine's own tools through the host.
*/
import type { ActionSpec } from './actions'
+import { hasParentSegment, trimTrailing } from './data/paths'
import { walk, type WfKey, type WfUi } from './data/workflows-nav'
import type { Host } from './host'
import type { Runner } from './runner'
@@ -32,9 +33,9 @@ export type WorkflowsActions = {
/** True for a path under `<configDir>/projects/` with no `..` part: the only place a run's files live. */
export function isRunPath(path: string, configDir: string | null): boolean {
- if (configDir === null || path.includes('\0') || path.split('/').includes('..')) return false
+ if (configDir === null || path.includes('\0') || hasParentSegment(path)) return false
- return path.startsWith(`${configDir.replace(/\/+$/, '')}/projects/`)
+ return path.startsWith(`${trimTrailing(configDir)}/projects/`)
}
export function workflowsActions(state: State, host: Host, runner: Runner): WorkflowsActions {
diff --git a/plugins/ruflo-console/hooks/wf-convo-live.ts b/plugins/ruflo-console/hooks/wf-convo-live.ts
index ace3627746..2db76114ca 100644
--- a/plugins/ruflo-console/hooks/wf-convo-live.ts
+++ b/plugins/ruflo-console/hooks/wf-convo-live.ts
@@ -14,6 +14,7 @@ import { payloadOf, sendTo, type SendDeps, tidy } from './data/wf-send'
import { parseConfig, peersOf, targetsOf, type Config, type PeerRef, type Target } from './data/wf-targets'
import { jsonAfter } from './data/cli'
import { plain } from './data/parse'
+import { isWindowsPath } from './data/paths'
import type { WfRun } from './data/workflows'
import type { Host } from './host'
import { CLI_PREFIXES, type State } from './state'
@@ -80,7 +81,9 @@ export async function refreshFacts(state: State, nowMs: number): Promise<void> {
if (live.home !== null) live.peers = peersOf(await host.fs.read(`${live.home}/.claude/federation/peers.json`).then(text => (text.length > 200_000 ? null : text), () => null))
- const found = await host.run(['which', 'codex'], 3000).catch(() => undefined)
+ // `where` is Windows' `which`; the home folder tells the two apart (a drive-lettered or share path is a Windows one).
+ const finder = live.home !== null && isWindowsPath(live.home) ? 'where' : 'which'
+ const found = await host.run([finder, 'codex'], 3000).catch(() => undefined)
live.hasCodex = found !== undefined && found.exitCode === 0
host.invalidate()
@@ -113,6 +116,8 @@ export function depsOf(state: State): SendDeps | null {
cwd: state.cwd,
hive: state.snapshot?.hive ?? null,
config: live.config,
+ // Windows has no printenv: the engine's own environment read supplies a model key there.
+ ...(host.env !== undefined && live.home !== null && isWindowsPath(live.home) && { readEnv: host.env }),
}
}
diff --git a/plugins/ruflo-console/hooks/wf-cost-live.ts b/plugins/ruflo-console/hooks/wf-cost-live.ts
index 5a17229e76..7d9e5dfdd1 100644
--- a/plugins/ruflo-console/hooks/wf-cost-live.ts
+++ b/plugins/ruflo-console/hooks/wf-cost-live.ts
@@ -12,6 +12,7 @@ import { agentKey, evaluateGuards, NO_RULES, parseGuardRules, trackProgress, typ
import { costRun, parsePriceBook, spendOf, usageOfTranscript, type AgentUsage, type PriceBook, type RunCost } from './data/wf-cost'
import { trackerOf } from './data/cost-ledger'
import { cleanText } from './data/wf-clean'
+import { hasParentSegment, trimTrailing } from './data/paths'
import { readBounded, under } from './data/files'
import { TAIL_BYTES, TRANSCRIPT_CAP, type WorkflowFs } from './data/workflows-read'
import type { WfRun } from './data/workflows'
@@ -60,7 +61,7 @@ const parsed = new Map<string, Parsed>()
const PARSED_MAX = 800
/** True for a path under `root` with no `..` part and no control character. */
-export const isUnder = (path: string, root: string | null): boolean => root !== null && !/[\u0000-\u001f]/.test(path) && !path.split('/').includes('..') && path.startsWith(`${root.replace(/\/+$/, '')}/`)
+export const isUnder = (path: string, root: string | null): boolean => root !== null && !/[\u0000-\u001f]/.test(path) && !hasParentSegment(path) && path.startsWith(`${trimTrailing(root)}/`)
const rememberParsed = (path: string, entry: Parsed): void => {
parsed.delete(path)
diff --git a/plugins/ruflo-console/hooks/wf-saved-live.ts b/plugins/ruflo-console/hooks/wf-saved-live.ts
index d0d254e24a..9ab514bad8 100644
--- a/plugins/ruflo-console/hooks/wf-saved-live.ts
+++ b/plugins/ruflo-console/hooks/wf-saved-live.ts
@@ -11,7 +11,7 @@ import type { ActionSpec } from './actions'
import { decodeSaved, emptySaved, encodeSaved, captureDrill, restoreDrill, sameDrill, SAVED_FILE, SAVED_MAX_BYTES, type Saved } from './data/wf-saved'
import { cleanText } from './data/wf-clean'
import { checkNoLinks, dirOf, removeFileArgv } from './data/wf-file'
-import { writeFlavorReady } from './data/write-flavor'
+import { writeFlavorReady, type WriteFlavor } from './data/write-flavor'
import { writeVia } from './data/write-via'
import { readBounded } from './data/files'
import type { Host } from './host'
@@ -157,17 +157,20 @@ export async function syncSavedViews(state: State, host: SavedHost, nowMs: numbe
}
/** The confirm-gated removal of the saved views file; once it ran the held copy is emptied and the cursor is not saved again until a pin or filter is set. */
-export function forgetSpec(cwd: string): ActionSpec {
+export function forgetSpec(cwd: string, flavor: WriteFlavor = 'gnu'): ActionSpec {
const path = savedPathOf(cwd)
+ const isHostFs = flavor === 'host-fs'
return {
label: 'forget saved Workflows views',
args: [],
argv: removeFileArgv(path),
- expect: `${path} removed`,
+ // Windows has no rm here: the file is rewritten as an empty (valid) saved-views document through the host's file API.
+ ...(isHostFs && { write: { kind: 'replace', path, text: encodeSaved(emptySaved(), Date.now()), hasDir: true } as const }),
+ expect: `${path} ${isHostFs ? 'emptied' : 'removed'}`,
declared: 'delete',
- shows: `rm -f -- ${path}`,
- note: 'deletes the console\'s own saved cursor, filters and pins for this project; runs and their files are not touched',
+ shows: isHostFs ? `empty ${path} (no delete on Windows: the file stays, with no views in it)` : `rm -f -- ${path}`,
+ note: `${isHostFs ? 'empties' : 'deletes'} the console's own saved cursor, filters and pins for this project; runs and their files are not touched`,
timeoutMs: 10_000,
onOutput: () => {
const own = savedFor(cwd)
@@ -179,6 +182,13 @@ export function forgetSpec(cwd: string): ActionSpec {
own.restored = null
own.said = 'saved views forgotten'
},
- verifyLocal: async host => (await host.fs.stat(path).catch(() => undefined)) === undefined,
+ verifyLocal: async host => {
+ if ((await host.fs.stat(path).catch(() => undefined)) === undefined) return true
+ if (!isHostFs) return false
+
+ const kept = decodeSaved(await host.fs.read(path).catch(() => null)).saved
+
+ return kept.pins.length === 0 && kept.drill === null && kept.search === '' && Object.keys(kept.filters).length === 0
+ },
}
}
diff --git a/plugins/ruflo-console/scripts/smoke.sh b/plugins/ruflo-console/scripts/smoke.sh
index 2871b7b5b6..7c8318f3bc 100755
--- a/plugins/ruflo-console/scripts/smoke.sh
+++ b/plugins/ruflo-console/scripts/smoke.sh
@@ -11,9 +11,9 @@ step() { printf "→ %s ... " "$1"; }
ok() { printf "PASS\n"; PASS=$((PASS+1)); }
bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }
-step "1. plugin.json declares ruflo-console 0.49.0"
+step "1. plugin.json declares ruflo-console 0.49.1"
grep -q '"name": "ruflo-console"' "$ROOT/.claude-plugin/plugin.json" \
- && grep -q '"version": "0.49.0"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"
+ && grep -q '"version": "0.49.1"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"
step "2. hooks.json names exactly one module and no classic hook commands"
grep -q '"modules": \["./register.ts"\]' "$HOOKS/hooks.json" && ! grep -q '"command"' "$HOOKS/hooks.json" \
@@ -133,5 +133,13 @@ brain_ids=$(grep -rnE "mcp__plugin_ruvnet|plugin_ruvnet-brain" "$HOOKS" || true)
brain_files=$(find "$ROOT" -iname '*ruvnet-brain*' -not -path '*/node_modules/*' 2>/dev/null || true)
[[ -z "$brain_calls" && -z "$brain_ids" && -z "$brain_files" ]] && ok || bad "calls: $brain_calls ids: $brain_ids files: $brain_files"
+step "21. Claude Code's own plugin validator accepts the plugin (a module it refuses, such as a computed \$.env.get name, stops the mod from loading and /ruflo is missing); skipped where the CLI is not installed"
+if command -v claude >/dev/null 2>&1; then
+ validate_out=$(claude plugin validate "$ROOT" 2>&1 | sed 's/\x1b\[[0-9;]*m//g' || true)
+ if printf '%s\n' "$validate_out" | grep -q 'Validation passed'; then ok; else bad "$(printf '%s\n' "$validate_out" | grep -m1 -E '✘|error' | cut -c1-200)"; fi
+else
+ printf "SKIP (no claude CLI) "; ok
+fi
+
printf "\n%d passed, %d failed\n" "$PASS" "$FAIL"
[[ $FAIL -eq 0 ]]
diff --git a/plugins/ruflo-console/tests/adr.spec.ts b/plugins/ruflo-console/tests/adr.spec.ts
index db4a2da421..3457ca11fe 100644
--- a/plugins/ruflo-console/tests/adr.spec.ts
+++ b/plugins/ruflo-console/tests/adr.spec.ts
@@ -276,6 +276,43 @@ describe('style, numbering and the records written', () => {
}
})
+ it('a record checked out with CRLF line endings (git autocrlf on Windows) takes the same edit and keeps its CRLF', () => {
+ const cases: [string, string, string, 'accepted' | 'deprecated'][] = [
+ ['madr', 'docs/decisions', '0001-use-markdown-architectural-decision-records.md', 'deprecated'],
+ ['nygard', 'doc/adr', '0003-use-graphql.md', 'deprecated'],
+ ['ruflo-style', 'docs/adrs', 'ADR-002-retries.md', 'accepted'],
+ ]
+
+ for (const [name, folder, target, to] of cases) {
+ const lf = readFileSync(join(FIXTURES, name, folder, target), 'utf8').replace(/\r\n/g, '\n')
+ const crlf = lf.replace(/\n/g, '\r\n')
+ const style = detectStyle(docsOf(name, folder))
+ const expected = withStatus(lf, parseAdr(target, lf), style, to)
+ const edit = withStatus(crlf, parseAdr(target, crlf), style, to)
+
+ expect(edit.ok, name).toBe(true)
+ if (!edit.ok || !expected.ok) continue
+
+ expect(edit.text.replace(/\r\n/g, '\n'), name).toBe(expected.text)
+ expect(edit.text.replace(/\r\n/g, ''), name).not.toContain('\n')
+ expect(parseAdr(target, edit.text).status, name).toBe(to)
+ }
+ })
+
+ it('supersede keeps a CRLF record’s line endings, and a MADR record with CRLF front matter is not "not closed"', () => {
+ const style = detectStyle(docsOf('madr', 'docs/decisions'))
+ const lf = renderNew(style, { number: 4, title: 'X', date: TODAY })
+ const crlf = lf.replace(/\n/g, '\r\n')
+ const newer = parseAdr('0004-x.md', crlf)
+ const linked = withSupersedes(crlf, newer, style, { number: 1, title: 'Old', file: '0001-old.md' })
+ const status = withStatus(crlf, newer, style, 'accepted')
+
+ expect(linked.ok && linked.text.replace(/\r\n/g, '')).not.toContain('\n')
+ expect(linked.ok && linked.text).toContain('supersedes: ')
+ expect(status).toMatchObject({ ok: true })
+ expect(status.ok && status.text.replace(/\r\n/g, '')).not.toContain('\n')
+ })
+
it('supersede edits the old record’s status and adds the link to the new one; a record with no status gets a status line', () => {
const style = detectStyle(docsOf('nygard', 'doc/adr'))
const old = parseAdr('0001-record-architecture-decisions.md', readFileSync(join(FIXTURES, 'nygard', 'doc/adr', '0001-record-architecture-decisions.md'), 'utf8'))
diff --git a/plugins/ruflo-console/tests/ap-windows-guard.spec.ts b/plugins/ruflo-console/tests/ap-windows-guard.spec.ts
new file mode 100644
index 0000000000..16dbe2a622
--- /dev/null
+++ b/plugins/ruflo-console/tests/ap-windows-guard.spec.ts
@@ -0,0 +1,78 @@
+/**
+ * The autopilot's text checks know Windows (groundwork for the Windows-aware path checks that ap-windows-gate.spec.ts names as the follow-up:
+ * a start is still refused there). Each rule here only ever parks or refuses more; none lets anything through that was refused before.
+ */
+import { describe, expect, it } from 'vitest'
+
+import { classifyTask } from '../hooks/data/ap-guard'
+import { pathAllowed, verifyProblem, type Envelope } from '../hooks/data/ap-envelope'
+
+const pathsOf = (title: string): string[] => classifyTask('t1', title).paths ?? []
+const denyOf = (title: string): string | null => classifyTask('t1', title).hardDeny
+
+describe('a task that names a Windows path is checked against the envelope folders', () => {
+ const env = { paths: ['C:\\proj'] } as unknown as Envelope
+
+ it('finds drive paths in either separator style, a drive root and a share', () => {
+ expect(pathsOf('edit C:\\Windows\\System32\\drivers\\etc\\hosts')).toContain('C:\\Windows\\System32\\drivers\\etc\\hosts')
+ expect(pathsOf('edit C:/proj/src/a.ts please')).toContain('C:/proj/src/a.ts')
+ expect(pathsOf('review "D:\\data\\x.csv"')).toContain('D:\\data\\x.csv')
+ expect(pathsOf('wipe C:\\')).toContain('C:\\')
+ expect(pathsOf('copy to \\\\srv\\share\\out')).toContain('\\\\srv\\share\\out')
+ })
+
+ it('finds a parent, home or variable path written the Windows way', () => {
+ expect(pathsOf('read ..\\..\\secrets.txt')).toContain('..\\..\\secrets.txt')
+ expect(pathsOf('review ~\\notes.md')).toContain('~\\notes.md')
+ expect(pathsOf('review %USERPROFILE%\\Documents\\x')).toContain('%USERPROFILE%\\Documents\\x')
+ expect(pathsOf('review $env:USERPROFILE\\Documents')).toContain('$env:USERPROFILE\\Documents')
+ })
+
+ it('leaves the POSIX reading exactly as it was', () => {
+ expect(pathsOf('edit /work/proj/a.ts')).toEqual(['/work/proj/a.ts'])
+ expect(pathsOf('read ../secrets and ~/notes')).toEqual(expect.arrayContaining(['../secrets', '~/notes']))
+ expect(pathsOf('refactor the parser, add tests')).toEqual([])
+ })
+
+ it('what is found is then refused outside the envelope and allowed inside it', () => {
+ expect(pathAllowed(env, 'C:\\proj\\src\\a.ts')).toBe(true)
+ expect(pathAllowed(env, 'c:/PROJ/src')).toBe(true)
+ expect(pathAllowed(env, 'C:\\Windows\\System32')).toBe(false)
+ expect(pathAllowed(env, '..\\..\\secrets.txt')).toBe(false)
+ expect(pathAllowed(env, '%USERPROFILE%\\Documents')).toBe(false)
+ expect(pathAllowed(env, 'C:\\proj\\..\\Windows')).toBe(false)
+ })
+})
+
+describe('the destructive-command deny covers the Windows forms', () => {
+ it('denies rmdir /s, del on a drive, format, Remove-Item -Recurse and rm on a drive', () => {
+ for (const task of ['run rmdir /s /q C:\\Users\\me', 'then rd /s /q build', 'del /f /q C:\\*.*', 'erase C:\\temp\\x', 'format D: now', 'Remove-Item -Recurse -Force C:\\proj', 'rm -rf C:\\proj', 'rm -rf %USERPROFILE%']) {
+ expect(denyOf(task), task).toBe('delete-outside-worktree')
+ }
+ })
+
+ it('does not deny ordinary Windows text', () => {
+ for (const task of ['update the formatting docs', 'format the code with prettier', 'remove the unused import from src\\a.ts', 'explain what del does in cmd']) {
+ expect(denyOf(task), task).not.toBe('delete-outside-worktree')
+ }
+ })
+})
+
+describe('a verify command cannot be a Windows shell or a destructive Windows tool', () => {
+ it('refuses a program by its basename under either separator and without .exe', () => {
+ for (const argv of [['C:\\Windows\\System32\\cmd.exe', '/c', 'dir'], ['cmd', '/c', 'dir'], ['powershell', '-Command', 'x'], ['pwsh.exe', '-c', 'x'], ['bash.exe', '-c', 'x'], ['C:/Program Files/Git/bin/bash.exe', '-c', 'x'], ['taskkill', '/f', '/im', 'node.exe'], ['wsl', 'ls'], ['reg', 'delete', 'HKCU\\x']]) {
+ expect(verifyProblem(argv), argv.join(' ')).toMatch(/cannot be a verify command/)
+ }
+ })
+
+ it('still accepts the programs a verify command is for, on either platform', () => {
+ for (const argv of [['node', 'a.js'], ['C:\\Program Files\\nodejs\\node.exe', 'a.js'], ['pnpm.cmd', 'test'], ['npx', 'vitest', 'run'], ['/usr/bin/git', 'status']]) {
+ expect(verifyProblem(argv), argv.join(' ')).toBeNull()
+ }
+ })
+
+ it('keeps refusing the POSIX shells and metacharacters', () => {
+ expect(verifyProblem(['/usr/bin/bash', '-c', 'x'])).toMatch(/cannot be a verify command/)
+ expect(verifyProblem(['npm', 'test', ';', 'x'])).toMatch(/shell metacharacter/)
+ })
+})
diff --git a/plugins/ruflo-console/tests/events-review-query.spec.ts b/plugins/ruflo-console/tests/events-review-query.spec.ts
index 08e5c8fd77..ac2f38cf91 100644
--- a/plugins/ruflo-console/tests/events-review-query.spec.ts
+++ b/plugins/ruflo-console/tests/events-review-query.spec.ts
@@ -54,11 +54,16 @@ describe('query language: bounded time on hostile patterns', () => {
ui.parsed = parseQuery('/.*.*x/')
+ // The scan is CPU-bound, so what it costs is its CPU time; wall-clock time also counts every other worker of a parallel run (and the machine's other
+ // work) and failed this spec only in full runs. The wall-clock bound stays as a guard against a hang.
const started = performance.now()
+ const cpuBefore = process.cpuUsage()
const model = eventsModel(w.state, T + 20_000_000)
+ const cpu = process.cpuUsage(cpuBefore)
const took = performance.now() - started
- expect(took).toBeLessThan(2500)
+ expect((cpu.user + cpu.system) / 1000).toBeLessThan(2500)
+ expect(took).toBeLessThan(30_000)
// Either it was quick enough to search everything, or it stopped and said so; never a silent partial answer.
expect(model.skipped === 0 || model.shown.length > 0).toBe(true)
diff --git a/plugins/ruflo-console/tests/events-review.spec.ts b/plugins/ruflo-console/tests/events-review.spec.ts
index abda4d58e1..8394f01e04 100644
--- a/plugins/ruflo-console/tests/events-review.spec.ts
+++ b/plugins/ruflo-console/tests/events-review.spec.ts
@@ -14,6 +14,7 @@ import type { ConsoleEvent } from '../hooks/data/events'
import { eventsActions, eventsUi } from '../hooks/events-ui'
import type { Host } from '../hooks/host'
import { newState } from '../hooks/state'
+import { setWriteFlavor } from '../hooks/data/write-flavor'
import { hostOn, newDisk, type Disk } from './fixtures/activity-fs'
@@ -189,6 +190,7 @@ describe('what reaches the disk (privacy)', () => {
expect(disk.files.get(`${CWD}/${EVENTS_FILE}`)).toContain('keep me out')
actions.forget()
+ await new Promise<void>(resolve => setTimeout(resolve, 0)) // the flavor is awaited before the ask is built
const spec = asked[0] as { argv: readonly string[]; onOutput: (out: string) => void }
@@ -205,6 +207,59 @@ describe('what reaches the disk (privacy)', () => {
expect(activityOf(state).log).toHaveLength(0)
})
+ it('on Windows (host-fs, no rm) forget empties the two files through the host file API and runs no command', async () => {
+ setWriteFlavor('host-fs')
+
+ try {
+ const disk = newDisk()
+ const { state, host: base } = consoleOn(disk)
+ const host = { ...base, fs: { ...base.fs, write: async (path: string, text: string) => void disk.files.set(path, text) } } as unknown as Host
+ const asked: { argv?: readonly string[]; run?: () => Promise<{ ok: boolean; detail: string }> }[] = []
+ const actions = eventsActions(state, host, () => undefined, spec => void asked.push(spec as never), () => undefined)
+
+ disk.files.set(`${CWD}/${EVENTS_FILE}`, '{"v":1}\n')
+ disk.files.set(`${CWD}/${LANES_FILE}`, '{"v":1}\n')
+ actions.forget()
+ await new Promise<void>(resolve => setTimeout(resolve, 0))
+
+ const spec = asked[0]
+
+ expect(spec?.argv).toBeUndefined()
+ expect(spec?.run).toBeTypeOf('function')
+
+ const report = await (spec?.run as () => Promise<{ ok: boolean; detail: string }>)()
+
+ expect(report.ok).toBe(true)
+ expect(disk.files.get(`${CWD}/${EVENTS_FILE}`)).toBe('')
+ expect(disk.files.get(`${CWD}/${LANES_FILE}`)).toBe('')
+ expect(disk.runs.filter(argv => argv[0] === 'rm')).toHaveLength(0)
+ } finally {
+ setWriteFlavor(null)
+ }
+ })
+
+ it('on Windows forget leaves a missing file missing, and says why when the host refuses the write', async () => {
+ setWriteFlavor('host-fs')
+
+ try {
+ const disk = newDisk({ [`${CWD}/${EVENTS_FILE}`]: 'x\n' })
+ const { state, host: base } = consoleOn(disk)
+ const refusing = { ...base, fs: { ...base.fs, write: async () => { throw new Error('EPERM: file is locked') } } } as unknown as Host
+ const asked: { run?: () => Promise<{ ok: boolean; detail: string }> }[] = []
+
+ eventsActions(state, refusing, () => undefined, spec => void asked.push(spec as never), () => undefined).forget()
+ await new Promise<void>(resolve => setTimeout(resolve, 0))
+
+ const report = await (asked[0]?.run as () => Promise<{ ok: boolean; detail: string }>)()
+
+ expect(report.ok).toBe(false)
+ expect(report.detail).toContain('EPERM')
+ expect(disk.files.has(`${CWD}/${LANES_FILE}`)).toBe(false)
+ } finally {
+ setWriteFlavor(null)
+ }
+ })
+
it('a hostile history file is masked when it is read, and a poisoned prefs file cannot pollute prototypes', async () => {
const line = `${JSON.stringify({ v: 1, t: T, kind: 'swarm', level: 'info', text: `leaked ${SECRETS[0]} [email protected]`, agent: SECRETS[1] })}\n`
const disk = newDisk({ [`${CWD}/${EVENTS_FILE}`]: line, [`${CWD}/${PREFS_FILE}`]: '{"v":1,"__proto__":{"polluted":1},"constructor":{"prototype":{"polluted":2}},"searches":[{"name":"__proto__","q":"x"},{"name":"constructor","q":"y"}],"pins":[{"__proto__":{"polluted":3},"atMs":1,"text":"t","kind":"__proto__"}]}' })
diff --git a/plugins/ruflo-console/tests/fixtures/rm-tree.ts b/plugins/ruflo-console/tests/fixtures/rm-tree.ts
new file mode 100644
index 0000000000..efe7438d65
--- /dev/null
+++ b/plugins/ruflo-console/tests/fixtures/rm-tree.ts
@@ -0,0 +1,8 @@
+import { rm } from 'node:fs/promises'
+
+/**
+ * Removes a spec's temporary folder, waiting out `EBUSY`. On Windows a folder cannot be deleted while a process started in it (a stand-in CLI,
+ * a spawned reader) is still exiting, and that failed a whole spec file after all its tests had passed. Only the async `rm` retries that error:
+ * `rmSync` fails at once whatever `maxRetries` says (measured on Node 22). Up to about 5 s of waiting; on Linux and macOS it returns at once.
+ */
+export const removeTree = (path: string): Promise<void> => rm(path, { recursive: true, force: true, maxRetries: 50, retryDelay: 100 })
diff --git a/plugins/ruflo-console/tests/paths.spec.ts b/plugins/ruflo-console/tests/paths.spec.ts
index 3ccc9d0b93..256c594739 100644
--- a/plugins/ruflo-console/tests/paths.spec.ts
+++ b/plugins/ruflo-console/tests/paths.spec.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'
import { isProtectedPath, validateEnvelope } from '../hooks/data/ap-envelope'
-import { below, hasParentSegment, isAbsolutePath, joinPath, normalizePath, samePath, trimTrailing } from '../hooks/data/paths'
+import { below, hasParentSegment, isAbsolutePath, joinPath, normalizePath, samePath, tailOf, trimTrailing } from '../hooks/data/paths'
describe('paths', () => {
it('absolute forms', () => {
@@ -78,4 +78,11 @@ describe('paths', () => {
expect(samePath('\\\\srv\\share\\x', '\\\\SRV\\share\\x\\')).toBe(true)
expect(samePath('\\\\srv\\share\\x', '\\\\srv\\share\\y')).toBe(false)
})
+ it('tailOf names the last folders of a project path under either separator (the overview heading)', () => {
+ expect(tailOf('/work/proj/app')).toBe('proj/app')
+ expect(tailOf('C:\\Users\\x\\proj')).toBe('x/proj')
+ expect(tailOf('C:/Users/x/proj')).toBe('x/proj')
+ expect(tailOf('\\\\srv\\share\\proj')).toBe('share/proj')
+ expect(tailOf('/a/b/c', 1)).toBe('c')
+ })
})
diff --git a/plugins/ruflo-console/tests/rm-tree.spec.ts b/plugins/ruflo-console/tests/rm-tree.spec.ts
new file mode 100644
index 0000000000..e8529c6d8b
--- /dev/null
+++ b/plugins/ruflo-console/tests/rm-tree.spec.ts
@@ -0,0 +1,37 @@
+import { spawn } from 'node:child_process'
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { describe, expect, it } from 'vitest'
+
+import { removeTree } from './fixtures/rm-tree'
+
+const exited = (child: ReturnType<typeof spawn>): Promise<void> => new Promise(resolve => (child.exitCode !== null ? resolve() : void child.once('exit', () => resolve())))
+
+describe('removeTree', () => {
+ it('removes a folder and everything in it, and a folder that is already gone', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'rm-tree-'))
+
+ mkdirSync(join(root, 'a', 'b'), { recursive: true })
+ writeFileSync(join(root, 'a', 'b', 'f.txt'), 'x')
+ await removeTree(root)
+ expect(existsSync(root)).toBe(false)
+ await expect(removeTree(root)).resolves.toBeUndefined()
+ })
+
+ // Windows only: there a folder cannot be removed while a process started in it is still running.
+ it.skipIf(process.platform !== 'win32')('waits out a process still running in the folder, which makes rmSync fail with EBUSY', { timeout: 30_000 }, async () => {
+ const root = mkdtempSync(join(tmpdir(), 'rm-tree-'))
+ const project = join(root, 'project')
+
+ mkdirSync(project)
+
+ const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 1200)'], { cwd: project, stdio: 'ignore' })
+
+ await new Promise(resolve => setTimeout(resolve, 300))
+ expect(() => rmSync(root, { recursive: true, force: true, maxRetries: 30, retryDelay: 100 })).toThrow(/EBUSY/)
+ await removeTree(root)
+ expect(existsSync(root)).toBe(false)
+ await exited(child)
+ })
+})
diff --git a/plugins/ruflo-console/tests/tui-actions.spec.ts b/plugins/ruflo-console/tests/tui-actions.spec.ts
index 21da36c273..2aefc79281 100644
--- a/plugins/ruflo-console/tests/tui-actions.spec.ts
+++ b/plugins/ruflo-console/tests/tui-actions.spec.ts
@@ -4,10 +4,11 @@
* on screen. A paste, a half-drawn card, another key or a different card never run it. Run with
* npx vitest run plugins/ruflo-console/tests/tui-actions.spec.ts
*/
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { removeTree } from './fixtures/rm-tree'
import { runTui, type TuiIO } from '../tui/run'
import { RUFLO_FILES } from './fixtures/ruflo-run'
@@ -30,9 +31,15 @@ beforeAll(() => {
cli = join(root, 'cli.js')
writeFileSync(cli, `require('node:fs').appendFileSync(${JSON.stringify(log)}, JSON.stringify(process.argv.slice(2)) + '\\n'); console.log('stub ran: ' + process.argv.slice(2).join(' '))\n`)
})
-afterAll(() => rmSync(root, { recursive: true, force: true }))
+afterAll(() => removeTree(root))
const settle = (ms = 250) => new Promise(resolve => setTimeout(resolve, ms))
+/** Polls until `done` holds, at most `limit` ms (the assertion that follows says what was missing). */
+const until = async (done: () => boolean, limit = 10_000): Promise<void> => {
+ const end = Date.now() + limit
+
+ while (!done() && Date.now() < end) await settle(50)
+}
const strip = (text: string) => text.replace(/\u001b\[[0-9;?<]*[A-Za-z]/g, '')
/** The commands the CLI stand-in was given, minus the console's own background reads (--version, memory stats, doctor …). */
const ran = (): string[][] => (existsSync(log) ? readFileSync(log, 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line) as string[]) : []).filter(argv => argv.some(word => word === 'stop' || (word === 'worker' && argv.includes('list'))))
@@ -92,8 +99,9 @@ describe('a change asked for by name', () => {
t.press('y')
// runner.ts re-checks the verify once at VERIFY_RETRY_MS (1 s) when a confirmed action's start
// succeeded but its state file is not on disk yet (#4036 bullet 2); the stand-in CLI's state
- // never changes here, so the whole re-check window has to resolve before the verdict is drawn.
- await settle(1200)
+ // never changes here, so the whole re-check window has to resolve before the verdict is drawn. Wait for the verdict itself, not for a fixed
+ // 1.2 s: under CPU contention (a full parallel run) the 1 s retry plus the redraw outlasts it.
+ await until(() => t.screen().includes('stop the swarm: ruflo answered ok'))
const after = ran().slice(before)
@@ -172,7 +180,7 @@ describe('what is not an action', () => {
const { t, running } = await started()
await ask(t, 'auto-workers-list')
- await settle(500)
+ await until(() => ran().length > before) // the stand-in CLI is a process start: slower than a fixed 500 ms on a loaded or Windows machine
expect(t.screen()).not.toContain('CONFIRM NEEDED')
expect(ran().slice(before)[0]).toEqual(expect.arrayContaining(['worker', 'list']))
t.press('q')
diff --git a/plugins/ruflo-console/tests/tui-ai-host.spec.ts b/plugins/ruflo-console/tests/tui-ai-host.spec.ts
index 7b5959dfb3..c809ec8c15 100644
--- a/plugins/ruflo-console/tests/tui-ai-host.spec.ts
+++ b/plugins/ruflo-console/tests/tui-ai-host.spec.ts
@@ -3,10 +3,11 @@
* (an injected fetch), a model key read by NAME. Nothing reaches the real network or a real Codex.
* npx vitest run plugins/ruflo-console/tests/tui-ai-host.spec.ts
*/
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, chmodSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync, chmodSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+import { removeTree } from './fixtures/rm-tree'
import { createNodeHost, resolveCodex } from '../tui/node-host'
@@ -22,9 +23,7 @@ beforeAll(() => {
mkdirSync(join(root, 'project'), { recursive: true })
mkdirSync(codexHome, { recursive: true })
})
-afterAll(() => {
- rmSync(root, { recursive: true, force: true })
-})
+afterAll(() => removeTree(root))
const host = (ai: Parameters<typeof createNodeHost>[0]['ai'] = { codexBin: FAKE, allowedHosts: ['openrouter.ai'], keyEnvs: ['OPENROUTER_API_KEY'] }) => createNodeHost({ cwd: join(root, 'project'), home: root, ai })
diff --git a/plugins/ruflo-console/tests/tui-ai-page.spec.ts b/plugins/ruflo-console/tests/tui-ai-page.spec.ts
index 0a6fabc5c1..b8f543eb97 100644
--- a/plugins/ruflo-console/tests/tui-ai-page.spec.ts
+++ b/plugins/ruflo-console/tests/tui-ai-page.spec.ts
@@ -3,10 +3,11 @@
* Codex. Every send waits for a card that was drawn; a key is read by name and never reaches a frame; the reply's cost is the provider's.
* npx vitest run plugins/ruflo-console/tests/tui-ai-page.spec.ts
*/
-import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import { removeTree } from './fixtures/rm-tree'
import { widthOf } from '../tui/ansi'
import { runTui, type TuiIO } from '../tui/run'
@@ -27,7 +28,7 @@ beforeAll(() => {
mkdirSync(project, { recursive: true })
mkdirSync(codexHome, { recursive: true })
})
-afterAll(() => rmSync(root, { recursive: true, force: true }))
+afterAll(() => removeTree(root))
beforeEach(() => void (process.env.OPENROUTER_API_KEY = KEY))
afterEach(() => {
delete process.env.OPENROUTER_API_KEY
@@ -305,7 +306,8 @@ describe('the page', () => {
const io = (): TuiIO => ({ stdin: { on: () => undefined, off: () => undefined, resume: () => undefined, pause: () => undefined }, stdout: { columns: 100, rows: 30, write: text => void out.push(text) }, stderr: { write: () => undefined }, env: {} })
expect(await runTui({ look: 'plain', fps: 0, cwd: project, home: root, plain: true, view: 'ai', aiPage: { codexBin: FAKE } }, io())).toBe(0)
- expect(out.join('')).toMatch(/codex .*ready|codex .*pinned/)
+ // The fake codex is a script with a shebang, which Windows cannot run: there the page can only say it is not ready.
+ expect(out.join('')).toMatch(isWin ? /codex/ : /codex .*ready|codex .*pinned/)
expect(out.join('')).toContain('openrouter')
expect(out.join('')).not.toContain(KEY)
out.length = 0
diff --git a/plugins/ruflo-console/tests/tui-boundary.spec.ts b/plugins/ruflo-console/tests/tui-boundary.spec.ts
index eb5c021880..7e77a3d218 100644
--- a/plugins/ruflo-console/tests/tui-boundary.spec.ts
+++ b/plugins/ruflo-console/tests/tui-boundary.spec.ts
@@ -11,7 +11,18 @@ import { createRequire } from 'node:module'
import { describe, expect, it } from 'vitest'
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
-const walk = (dir: string): string[] => readdirSync(dir).flatMap(name => (statSync(join(dir, name)).isDirectory() ? walk(join(dir, name)) : name.endsWith('.ts') ? [join(dir, name)] : []))
+// `.mut-*.ts` are the mutation specs' temporary copies of hooks modules, made and deleted while other specs run in parallel: they are not part of hooks/, and a
+// listed one can be gone before it is stat'ed or read.
+const walk = (dir: string): string[] =>
+ readdirSync(dir).flatMap(name => {
+ if (name.startsWith('.mut-')) return []
+
+ try {
+ return statSync(join(dir, name)).isDirectory() ? walk(join(dir, name)) : name.endsWith('.ts') ? [join(dir, name)] : []
+ } catch {
+ return []
+ }
+ })
const bare = (file: string): string => readFileSync(file, 'utf8').replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '')
/** Every `import … from 'x'` / `export … from 'x'` statement as [is it type-only, the specifier]; a statement cannot cross a quote, so none runs into the next. */
const importsOf = (text: string): Array<[boolean, string]> => [...text.matchAll(/^(import|export)\b([^'";]*?)from\s+'([^']+)'/gm)].map(match => [/^\s*type\b/.test(match[2] ?? ''), match[3] as string])
@@ -34,6 +45,10 @@ describe('hooks/ is host-neutral', () => {
expect(offenders).toEqual([])
})
+ it('names every environment variable it reads or writes with a literal: the engine lists them, and `claude plugin validate` refuses a computed name (the mod then does not load)', () => {
+ expect(hooks.filter(({ text }) => /\$\.env\.(get|set)\(\s*(?!['"])/.test(text)).map(({ file }) => file)).toEqual([])
+ })
+
it('reaches the engine only from register.ts and model-tools.ts', () => {
expect(hooks.filter(({ text }) => ENGINE.test(text)).map(({ file }) => file).sort()).toEqual(ENGINE_ONLY)
})
diff --git a/plugins/ruflo-console/tests/tui-host.spec.ts b/plugins/ruflo-console/tests/tui-host.spec.ts
index b63c0490f7..b8c6ff19d1 100644
--- a/plugins/ruflo-console/tests/tui-host.spec.ts
+++ b/plugins/ruflo-console/tests/tui-host.spec.ts
@@ -3,10 +3,11 @@
* program that runs is the ruflo CLI by argv; everything that needs the Claude Code engine is refused. Run with
* npx vitest run plugins/ruflo-console/tests/tui-host.spec.ts
*/
-import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { removeTree } from './fixtures/rm-tree'
import { cliArgv, createNodeHost } from '../tui/node-host'
@@ -30,7 +31,7 @@ beforeAll(() => {
// A CLI stand-in: prints its argv and whether a parent secret reached its environment.
writeFileSync(join(root, 'cli.mjs'), 'console.log(JSON.stringify({ argv: process.argv.slice(2), leaked: process.env.OPENROUTER_API_KEY ?? null, cwd: process.cwd() }))')
})
-afterAll(() => rmSync(root, { recursive: true, force: true }))
+afterAll(() => removeTree(root))
const hostOf = (extra = {}) => createNodeHost({ cwd: project, home, cliEntry: join(root, 'cli.mjs'), ...extra })
diff --git a/plugins/ruflo-console/tests/tui-nav.spec.ts b/plugins/ruflo-console/tests/tui-nav.spec.ts
index 8c41aaa621..7fa88df41e 100644
--- a/plugins/ruflo-console/tests/tui-nav.spec.ts
+++ b/plugins/ruflo-console/tests/tui-nav.spec.ts
@@ -3,10 +3,11 @@
* be drawn on a host with no Claude session and no mouse. Real ruflo files on disk, an injected terminal, no engine.
* npx vitest run plugins/ruflo-console/tests/tui-nav.spec.ts
*/
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { removeTree } from './fixtures/rm-tree'
import { widthOf } from '../tui/ansi'
import { keyLine, keyOf, MIN_COLUMNS, navLine, runTui, type TuiIO } from '../tui/run'
@@ -41,7 +42,7 @@ beforeAll(() => {
}),
})
})
-afterAll(() => rmSync(root, { recursive: true, force: true }))
+afterAll(() => removeTree(root))
function terminal(columns = 100, rows = 30) {
const out: string[] = []
diff --git a/plugins/ruflo-console/tests/tui-pagebar.spec.ts b/plugins/ruflo-console/tests/tui-pagebar.spec.ts
index f35c9c174d..dcfb147725 100644
--- a/plugins/ruflo-console/tests/tui-pagebar.spec.ts
+++ b/plugins/ruflo-console/tests/tui-pagebar.spec.ts
@@ -3,10 +3,11 @@
* console view the session last showed, and the AI page is not a console view, so on page 6 the bar kept the previous page lit.
* npx vitest run plugins/ruflo-console/tests/tui-pagebar.spec.ts
*/
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { removeTree } from './fixtures/rm-tree'
import { runTui, type TuiIO } from '../tui/run'
import { TUI_VIEWS } from '../tui/session'
@@ -25,7 +26,7 @@ beforeAll(() => {
writeFileSync(join(project, path), body)
}
})
-afterAll(() => rmSync(root, { recursive: true, force: true }))
+afterAll(() => removeTree(root))
function terminal(columns = 100, rows = 30) {
const out: string[] = []
diff --git a/plugins/ruflo-console/tests/tui-parity.spec.ts b/plugins/ruflo-console/tests/tui-parity.spec.ts
index 60a5afd848..b452e96554 100644
--- a/plugins/ruflo-console/tests/tui-parity.spec.ts
+++ b/plugins/ruflo-console/tests/tui-parity.spec.ts
@@ -3,10 +3,11 @@
* main-menu keys, Back and the mouse reach them. Run with
* npx vitest run plugins/ruflo-console/tests/tui-parity.spec.ts
*/
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { removeTree } from './fixtures/rm-tree'
import { VIEWS } from '../hooks/state'
import { navHit, navLine, runTui, type TuiIO } from '../tui/run'
@@ -27,7 +28,7 @@ beforeAll(() => {
writeFileSync(join(project, path), body)
}
})
-afterAll(() => rmSync(root, { recursive: true, force: true }))
+afterAll(() => removeTree(root))
const settle = (ms = 150) => new Promise(resolve => setTimeout(resolve, ms))
const strip = (text: string) => text.replace(/\u001b\[[0-9;?<]*[A-Za-z]/g, '')
diff --git a/plugins/ruflo-console/tests/tui-pictures.spec.ts b/plugins/ruflo-console/tests/tui-pictures.spec.ts
index 27844857fe..8f10839c21 100644
--- a/plugins/ruflo-console/tests/tui-pictures.spec.ts
+++ b/plugins/ruflo-console/tests/tui-pictures.spec.ts
@@ -4,10 +4,11 @@
* and in words alone where there is no colour or no room. Run with
* npx vitest run plugins/ruflo-console/tests/tui-pictures.spec.ts
*/
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { removeTree } from './fixtures/rm-tree'
import { fpsOf, keyOf, runTui, type TuiIO } from '../tui/run'
import { LOOKS, openSession } from '../tui/session'
@@ -26,9 +27,25 @@ beforeAll(() => {
writeFileSync(join(project, path), body)
}
})
-afterAll(() => rmSync(root, { recursive: true, force: true }))
+afterAll(() => removeTree(root))
const settle = (ms = 120) => new Promise(resolve => setTimeout(resolve, ms))
+/** Waits until `count()` stops changing for `ms` (a frame already in flight when something happened has landed), at most `limit` ms. */
+const quiet = async (count: () => number, ms = 150, limit = 3_000): Promise<void> => {
+ const end = Date.now() + limit
+ let last = -1
+
+ while (Date.now() < end && count() !== last) {
+ last = count()
+ await settle(ms)
+ }
+}
+/** Waits until `done()` holds, at most `limit` ms. */
+const until = async (done: () => boolean, limit = 5_000): Promise<void> => {
+ const end = Date.now() + limit
+
+ while (!done() && Date.now() < end) await settle(25)
+}
const strip = (text: string) => text.replace(/\u001b\[[0-9;?]*[A-Za-z]/g, '')
async function opened(options: Record<string, unknown> = {}) {
@@ -175,14 +192,14 @@ describe('the loop', () => {
await settle(400)
t.press(`${ESC}[O`)
- await settle(60)
+ await quiet(() => t.out.length) // a frame already in flight when focus was lost still lands; what follows must be silence
const mark = t.out.length
await settle(500)
expect(t.out.length).toBe(mark)
t.press(`${ESC}[I`)
- await settle(300)
+ await until(() => t.out.length > mark)
expect(t.out.length).toBeGreaterThan(mark)
t.press('q')
await running
diff --git a/plugins/ruflo-console/tests/tui-session.spec.ts b/plugins/ruflo-console/tests/tui-session.spec.ts
index 4e573e34c2..1b262b6b3b 100644
--- a/plugins/ruflo-console/tests/tui-session.spec.ts
+++ b/plugins/ruflo-console/tests/tui-session.spec.ts
@@ -3,10 +3,11 @@
* host, drawn by the mod's own page bodies in the standalone pane, headless and with an injected terminal. Run with
* npx vitest run plugins/ruflo-console/tests/tui-session.spec.ts
*/
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { removeTree } from './fixtures/rm-tree'
import { depthOf, keyOf, NOT_A_TERMINAL_HINT, runTui, type TuiIO } from '../tui/run'
import { openSession } from '../tui/session'
@@ -32,7 +33,7 @@ beforeAll(() => {
// The same project with an escape sequence and a token where a swarm id and topology are read from disk (both files that name it).
put(hostile, { ...RUFLO_FILES, '.swarm/state.json': JSON.stringify({ id: `swarm-\u001b]0;pwned\u0007-1`, topology: 'ghp_abcdefghijklmnopqrstuvwxyz0123456789', status: 'running' }), '.claude-flow/swarm/swarm-state.json': JSON.stringify({ swarms: { 'swarm-1': { swarmId: `swarm-\u001b]0;pwned\u0007-1`, topology: 'ghp_abcdefghijklmnopqrstuvwxyz0123456789', status: 'running', agents: [] } } }) })
})
-afterAll(() => rmSync(root, { recursive: true, force: true }))
+afterAll(() => removeTree(root))
function fakeIO(isTTY: boolean) {
const out: string[] = []
@@ -50,6 +51,20 @@ function fakeIO(isTTY: boolean) {
}
describe('the same views over real ruflo files', () => {
+ it('the config folder is <home>/.claude when CLAUDE_CONFIG_DIR is not given, so the plugin, marketplace and run reads have somewhere to look', async () => {
+ const session = openSession({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home') })
+
+ await session.refresh()
+ expect(session.state.configDir).toBe(`${join(root, 'home')}/.claude`)
+ session.stop()
+
+ const explicit = openSession({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home'), configDir: join(root, 'elsewhere') })
+
+ await explicit.refresh()
+ expect(explicit.state.configDir).toBe(join(root, 'elsewhere'))
+ explicit.stop()
+ })
+
it('Overview shows the swarm, the daemon and the helpers read from disk', async () => {
const session = openSession({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home') })
@@ -230,4 +245,13 @@ describe('keys and colour depth', () => {
expect(depthOf({ TERM: 'xterm-256color' })).toBe('256')
expect(depthOf({ TERM: 'xterm', COLORTERM: 'truecolor' })).toBe('truecolor')
})
+
+ it('keeps colour on Windows, where TERM is unset in Windows Terminal, PowerShell and cmd', () => {
+ expect(depthOf({ OS: 'Windows_NT' })).toBe('256')
+ expect(depthOf({ OS: 'Windows_NT', TERM: '' })).toBe('256')
+ expect(depthOf({ OS: 'Windows_NT', COLORTERM: 'truecolor' })).toBe('truecolor')
+ expect(depthOf({ OS: 'Windows_NT', TERM: 'dumb' })).toBe('none')
+ expect(depthOf({ OS: 'Windows_NT', NO_COLOR: '1', COLORTERM: 'truecolor' })).toBe('none')
+ expect(depthOf({ COLORTERM: 'truecolor' })).toBe('none')
+ })
})
diff --git a/plugins/ruflo-console/tests/wf-control-windows.spec.ts b/plugins/ruflo-console/tests/wf-control-windows.spec.ts
new file mode 100644
index 0000000000..f5a175f687
--- /dev/null
+++ b/plugins/ruflo-console/tests/wf-control-windows.spec.ts
@@ -0,0 +1,76 @@
+import { execFile } from 'node:child_process'
+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterAll, describe, expect, it } from 'vitest'
+import { removeTree } from './fixtures/rm-tree'
+
+import { taskIdOf, windowsSearchArgv } from '../hooks/data/wf-control'
+
+// Finding a run's task id in a session transcript too large to read whole: `grep -o` on Linux and macOS, PowerShell's Select-String on Windows.
+const LAUNCH = (task: string, run: string): string => `{"type":"tool","content":"{\\"taskId\\":\\"${task}\\",\\"taskType\\":\\"local_workflow\\",\\"runId\\":\\"${run}\\"}"}`.replace(/\\"/g, '"')
+
+describe('windowsSearchArgv', () => {
+ it('is a PowerShell command whose script has no double quote, and carries the path and the pattern only as base64', () => {
+ const argv = windowsSearchArgv('C:\\Users\\John Smith\\.claude\\projects\\a$b\'c;d&e\\s.jsonl', 'wf_abc12345') as readonly string[]
+
+ expect(argv.slice(0, 4)).toEqual(['powershell', '-NoProfile', '-NonInteractive', '-Command'])
+ expect(argv).toHaveLength(5)
+ expect(argv[4]).not.toContain('"')
+ expect(argv[4]).not.toContain('John Smith')
+ expect(argv[4]).not.toContain('wf_abc12345')
+ expect(argv[4]).toContain('Select-String -LiteralPath $p -Pattern $q -AllMatches')
+ })
+
+ it('refuses a run id that is not one, an empty path and a NUL', () => {
+ expect(windowsSearchArgv('C:\\s.jsonl', 'wf_x"; Remove-Item *')).toBeNull()
+ expect(windowsSearchArgv('C:\\s.jsonl', 'not-a-run')).toBeNull()
+ expect(windowsSearchArgv('', 'wf_abc12345')).toBeNull()
+ expect(windowsSearchArgv('C:\\s\0.jsonl', 'wf_abc12345')).toBeNull()
+ })
+})
+
+describe('taskIdOf on what a search printed (any platform)', () => {
+ it('takes the latest launch when the output holds two of one run (a resume), as the whole-file reader does', () => {
+ const printed = [`"taskId":"first0task","taskType":"local_workflow","runId":"wf_abc12345"`, `"taskId":"resumed9tk","taskType":"local_workflow","runId":"wf_abc12345"`].join('\n')
+
+ expect(taskIdOf(printed, 'wf_abc12345')).toBe('resumed9tk')
+ expect(taskIdOf(printed.split('\n')[0] as string, 'wf_abc12345')).toBe('first0task')
+ })
+})
+
+describe.skipIf(process.platform !== 'win32')('the Windows search, through a real PowerShell', () => {
+ const root = mkdtempSync(join(tmpdir(), 'wf search '))
+ const folder = join(root, "o'brien $x & y; z")
+
+ mkdirSync(folder)
+ afterAll(() => removeTree(root))
+
+ const file = join(folder, 's.jsonl')
+ const filler = Array.from({ length: 20_000 }, (_unused, i) => JSON.stringify({ type: 'user', i, pad: 'x'.repeat(120) }))
+
+ writeFileSync(file, [...filler.slice(0, 50), LAUNCH('first0task', 'wf_abc12345'), ...filler.slice(50, 900), LAUNCH('resumed9tk', 'wf_abc12345'), LAUNCH('other1task', 'wf_zzz99999'), ...filler.slice(900)].join('\r\n'))
+
+ const search = (path: string, runId: string): Promise<{ code: number; stdout: string }> =>
+ new Promise(resolve => {
+ const argv = windowsSearchArgv(path, runId) as readonly string[]
+
+ execFile(argv[0] as string, argv.slice(1), { timeout: 30_000, windowsHide: true }, (error, stdout) => resolve({ code: error === null ? 0 : 1, stdout }))
+ })
+
+ it('prints only the launch lines of that run, through a path with a space, a quote, $, & and ;', { timeout: 30_000 }, async () => {
+ const found = await search(file, 'wf_abc12345')
+
+ expect(found.code).toBe(0)
+ expect(found.stdout).toContain('first0task')
+ expect(found.stdout).toContain('resumed9tk')
+ expect(found.stdout).not.toContain('other1task')
+ expect(found.stdout).not.toContain('"user"')
+ })
+
+ it('gives the same answer as the in-process reader: the last launch of the run wins (a resume), another run is not found', { timeout: 30_000 }, async () => {
+ expect(taskIdOf((await search(file, 'wf_abc12345')).stdout, 'wf_abc12345')).toBe('resumed9tk')
+ expect(taskIdOf((await search(file, 'wf_zzz99999')).stdout, 'wf_zzz99999')).toBe('other1task')
+ expect(taskIdOf((await search(file, 'wf_missing00')).stdout, 'wf_missing00')).toBeNull()
+ })
+})
diff --git a/plugins/ruflo-console/tests/wf-convo-finder.spec.ts b/plugins/ruflo-console/tests/wf-convo-finder.spec.ts
new file mode 100644
index 0000000000..aae9860024
--- /dev/null
+++ b/plugins/ruflo-console/tests/wf-convo-finder.spec.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest'
+
+import type { Host } from '../hooks/host'
+import { newState } from '../hooks/state'
+import { wireWfConvo } from '../hooks/views/wf-convo'
+import { liveOf, refreshFacts, resetConvo } from '../hooks/wf-convo-live'
+
+// The Conversation board offers codex only where it is on the PATH. `which` does that on Linux and macOS; Windows has no `which`, only `where`.
+const found = (exitCode: number) => ({ exitCode, stdout: '', stderr: '', isStdoutTruncated: false, isStderrTruncated: false })
+
+async function factsFor(home: string, hasCodex: boolean): Promise<{ finders: string[]; hasCodex: boolean }> {
+ const state = newState({})
+ const finders: string[] = []
+ const host = {
+ home: async () => home,
+ fs: { read: async () => Promise.reject(new Error('ENOENT')), stat: async () => undefined, list: async () => [] },
+ run: async (argv: readonly string[]) => {
+ finders.push(`${argv[0]} ${argv[1]}`)
+
+ // Only the finder the platform has answers; the other "is not recognised".
+ const platformFinder = home.startsWith('/') ? 'which' : 'where'
+
+ return found(argv[0] === platformFinder && hasCodex ? 0 : 127)
+ },
+ invalidate: () => undefined,
+ every: () => ({ cancel: () => undefined }),
+ } as unknown as Host
+
+ resetConvo(state)
+ wireWfConvo(state, host, '')
+ await refreshFacts(state, 1_700_000_000_000)
+
+ return { finders, hasCodex: liveOf(state).hasCodex }
+}
+
+describe('finding codex for the Conversation board', () => {
+ it('uses `where` on a Windows home (drive path) and finds codex', async () => {
+ expect(await factsFor('C:\\Users\\u', true)).toEqual({ finders: ['where codex'], hasCodex: true })
+ })
+
+ it('uses `where` on a share home too, and says no codex when it is not there', async () => {
+ expect(await factsFor('\\\\srv\\home\\u', false)).toEqual({ finders: ['where codex'], hasCodex: false })
+ })
+
+ it('keeps `which` on a POSIX home', async () => {
+ expect(await factsFor('/home/u', true)).toEqual({ finders: ['which codex'], hasCodex: true })
+ })
+})
diff --git a/plugins/ruflo-console/tests/wf-replay-views.spec.ts b/plugins/ruflo-console/tests/wf-replay-views.spec.ts
index 518e4fb856..13b7620d07 100644
--- a/plugins/ruflo-console/tests/wf-replay-views.spec.ts
+++ b/plugins/ruflo-console/tests/wf-replay-views.spec.ts
@@ -223,11 +223,12 @@ describe('saved views', () => {
expect(savedFor('/work/proj').saved.pins).toEqual([])
})
- it('forgets only through the confirm card', () => {
+ it('forgets only through the confirm card', async () => {
const w = world()
press(w.page(), 'wf-saved-fold')
press(w.page(), 'wf-saved-forget')
+ await new Promise<void>(resolve => setTimeout(resolve, 0)) // the write flavor is awaited before the card is built
expect(asked[0]).toMatchObject({ argv: ['rm', '-f', '--', '/work/proj/.claude-flow/console/wf-views.json'], declared: 'delete' })
})
diff --git a/plugins/ruflo-console/tests/wf-saved.spec.ts b/plugins/ruflo-console/tests/wf-saved.spec.ts
index 49b47e753b..006b7fee94 100644
--- a/plugins/ruflo-console/tests/wf-saved.spec.ts
+++ b/plugins/ruflo-console/tests/wf-saved.spec.ts
@@ -254,4 +254,30 @@ describe('live: load, restore, write', () => {
await syncSavedViews(w.state, w.host, 60_000)
expect(w.writes).toHaveLength(1)
})
+
+ it('on Windows (host-fs, no rm) forgetting rewrites the file as an empty, valid saved-views document', async () => {
+ const spec = forgetSpec(CWD, 'host-fs')
+
+ expect(spec.write).toMatchObject({ kind: 'replace', path: PATH, hasDir: true })
+ expect(spec).toMatchObject({ declared: 'delete', expect: `${PATH} emptied` })
+ expect(spec.shows).not.toContain('rm ')
+
+ const emptied = decodeSaved(spec.write?.text ?? null)
+
+ expect(emptied.problem).toBeNull()
+ expect(emptied.saved).toMatchObject({ drill: null, search: '', pins: [], filters: {} })
+ })
+
+ it('on Windows the forget is verified by what the file holds: gone or empty passes, a pinned run left in it fails', async () => {
+ const spec = forgetSpec(CWD, 'host-fs')
+ const hostFor = (file: string | undefined) => ({ fs: { stat: async () => (file === undefined ? undefined : { kind: 'file', size: file.length }), read: async () => file ?? '' }, home: async () => undefined }) as never
+ const pinned = encodeSaved(togglePin(emptySaved(), a, 1).saved, 1)
+
+ expect(await spec.verifyLocal?.(hostFor(undefined))).toBe(true)
+ expect(await spec.verifyLocal?.(hostFor(spec.write?.text))).toBe(true)
+ expect(await spec.verifyLocal?.(hostFor(pinned))).toBe(false)
+ // the Linux and macOS form is still the rm, verified by the file being gone
+ expect(forgetSpec(CWD)).toMatchObject({ argv: ['rm', '-f', '--', PATH] })
+ expect(await forgetSpec(CWD).verifyLocal?.(hostFor(spec.write?.text))).toBe(false)
+ })
})
diff --git a/plugins/ruflo-console/tests/wf-send-env.spec.ts b/plugins/ruflo-console/tests/wf-send-env.spec.ts
new file mode 100644
index 0000000000..5c3ebf225c
--- /dev/null
+++ b/plugins/ruflo-console/tests/wf-send-env.spec.ts
@@ -0,0 +1,118 @@
+import { describe, expect, it } from 'vitest'
+
+import { sendTo, type SendDeps } from '../hooks/data/wf-send'
+import { parseConfig, targetsOf, type Target } from '../hooks/data/wf-targets'
+
+// A model key is read from the environment of the process Claude Code runs in. `printenv` does that on Linux and macOS; Windows has none, so
+// there the engine's own environment read (host.env) supplies it and no program is run.
+const CONFIG = 'endpoint:a=https://a.example.com/v1|KEY_A|m1'
+
+function rig(env?: (name: string) => Promise<string | undefined>) {
+ const ran: string[][] = []
+ const headers: Record<string, string>[] = []
+ const deps = {
+ cli: [],
+ helper: '',
+ trustedPeers: new Set<string>(),
+ cwd: 'C:\\proj',
+ hive: null,
+ config: parseConfig(CONFIG),
+ run: async (argv: readonly string[]) => {
+ ran.push([...argv])
+
+ return argv[0] === 'printenv' ? { exitCode: 0, stdout: 'from-printenv\n', stderr: '' } : { exitCode: 127, stdout: '', stderr: 'not found' }
+ },
+ httpSend: async (_url: string, init: { headers: Record<string, string> }) => {
+ headers.push(init.headers)
+
+ return { ok: true, status: 200, text: JSON.stringify({ model: 'm1', choices: [{ message: { content: 'hello' } }], usage: { prompt_tokens: 1, completion_tokens: 1 } }) }
+ },
+ submitPrompt: async () => undefined,
+ ...(env !== undefined && { readEnv: env }),
+ } as unknown as SendDeps
+ const target = targetsOf({ agents: [], peers: [], config: deps.config, hasHive: false, hasCodex: false }).find(candidate => candidate.id === 'a') as Target
+
+ return { deps, target, ran, headers }
+}
+
+describe('reading a model key for an endpoint send', () => {
+ it('uses the engine environment read where it is given (Windows) and runs no program', async () => {
+ const r = rig(async name => (name === 'KEY_A' ? ' win-secret ' : undefined))
+ const result = await sendTo(r.deps, r.target, 'hello')
+
+ expect(result.ok).toBe(true)
+ expect(r.headers[0]?.authorization).toBe('Bearer win-secret')
+ expect(r.ran).toEqual([])
+ })
+
+ it('refuses, sending nothing, when that read finds no key or fails', async () => {
+ for (const env of [async () => undefined, async () => '', async (): Promise<string | undefined> => Promise.reject(new Error('refused'))]) {
+ const r = rig(env)
+ const result = await sendTo(r.deps, r.target, 'hello')
+
+ expect(result.state).toBe('refused')
+ // KEY_A is a custom name: the engine allows only literal variable names, so it says it cannot be read here, not that it is unset
+ expect(result.text).toContain('KEY_A cannot be read here')
+ expect(result.text).toContain('only $OPENROUTER_API_KEY')
+ expect(r.headers).toEqual([])
+ }
+ })
+
+ it('says the OpenRouter key is not set when that read finds none', async () => {
+ const r = rig(async () => undefined)
+ const openrouter = targetsOf({ agents: [], peers: [], config: r.deps.config, hasHive: false, hasCodex: false }).find(candidate => candidate.id === 'openrouter') as Target
+ const result = await sendTo(r.deps, openrouter, 'hello')
+
+ expect(result).toMatchObject({ ok: false, state: 'refused' })
+ expect(result.text).toContain('OPENROUTER_API_KEY is not set')
+ expect(r.headers).toEqual([])
+ })
+
+ it('keeps `printenv` where no environment read is given (Linux, macOS)', async () => {
+ const r = rig()
+ const result = await sendTo(r.deps, r.target, 'hello')
+
+ expect(result.ok).toBe(true)
+ expect(r.ran).toEqual([['printenv', 'KEY_A']])
+ expect(r.headers[0]?.authorization).toBe('Bearer from-printenv')
+ })
+})
+
+describe('sending to a federation peer', () => {
+ const peerRig = (helper: string) => {
+ const ran: string[][] = []
+ const deps = {
+ cli: [],
+ helper,
+ trustedPeers: new Set(['zenbook']),
+ cwd: '/work',
+ hive: null,
+ config: parseConfig(''),
+ run: async (argv: readonly string[]) => (ran.push([...argv]), { exitCode: 0, stdout: 'peer says hi', stderr: '' }),
+ httpSend: async () => ({ ok: true, status: 200, text: '' }),
+ submitPrompt: async () => undefined,
+ } as unknown as SendDeps
+ const target = targetsOf({ agents: [], peers: [{ host: 'zenbook', trusted: true }], config: deps.config, hasHive: false, hasCodex: false }).find(candidate => candidate.id === 'peer-zenbook') as Target
+
+ return { deps, target, ran }
+ }
+
+ it('is refused on Windows, running nothing: the helper is a bash script and `bash` there is the WSL launcher', async () => {
+ for (const helper of ['C:\\Users\\u/.claude/helpers/federation.sh', 'C:/Users/u/.claude/helpers/federation.sh']) {
+ const r = peerRig(helper)
+ const result = await sendTo(r.deps, r.target, 'hello')
+
+ expect(result).toMatchObject({ ok: false, state: 'refused' })
+ expect(result.text).toContain('cannot run from here')
+ expect(r.ran).toEqual([])
+ }
+ })
+
+ it('still runs the helper with bash on a POSIX home', async () => {
+ const r = peerRig('/home/u/.claude/helpers/federation.sh')
+ const result = await sendTo(r.deps, r.target, 'hello')
+
+ expect(result).toMatchObject({ ok: true, state: 'reply', text: 'peer says hi' })
+ expect(r.ran).toEqual([['bash', '/home/u/.claude/helpers/federation.sh', 'dispatch', 'zenbook', 'hello']])
+ })
+})
diff --git a/plugins/ruflo-console/tests/windows-drive-path-sites.spec.ts b/plugins/ruflo-console/tests/windows-drive-path-sites.spec.ts
index 8d21493a6a..1cf2212552 100644
--- a/plugins/ruflo-console/tests/windows-drive-path-sites.spec.ts
+++ b/plugins/ruflo-console/tests/windows-drive-path-sites.spec.ts
@@ -3,6 +3,7 @@ import { discover } from '../hooks/adr'
import { resolveTarget } from '../hooks/data/event-export'
import { resolveExportPath } from '../hooks/data/wf-file'
import type { ReaderFs } from '../hooks/data/files'
+import { readCatalog, readDoc } from '../hooks/data/plugin-catalog'
// #4356: on Windows `state.cwd` is a drive path (`C:\Users\...`), not `/...`. Each of these
// three sites hardcoded `base.startsWith('/')` (or `root.startsWith('/')`) as its "do we know
@@ -92,3 +93,65 @@ describe('wf-convo-live.ts calls resolveExportPath with a relative name, not a p
expect(source).not.toMatch(/resolveExportPath\(`\$\{state\.cwd/)
})
})
+
+describe('plugin-catalog.ts reads a Windows marketplace clone', () => {
+ // Claude Code records the clone's installLocation as a drive path; the catalog used to refuse anything not starting with `/`
+ // and drew "the clone's marketplace.json is not readable" with the file in place.
+ const CLONE = 'C:\\Users\\dev\\.claude\\plugins\\marketplaces\\ruflo'
+ const files: Record<string, string> = {
+ '.claude-plugin/marketplace.json': JSON.stringify({ plugins: [{ name: 'a-plugin', source: './plugins/a-plugin', description: 'Does A things' }] }),
+ 'plugins/a-plugin/.claude-plugin/plugin.json': '{"version":"1.2.3"}',
+ 'plugins/a-plugin/skills/alpha/SKILL.md': '---\nname: alpha\ndescription: "Alpha does a"\n---\nbody\n',
+ 'plugins/a-plugin/commands/go.md': 'x',
+ 'plugins/a-plugin/.mcp.json': '{}',
+ }
+ // Keyed by the path below the clone with `/` separators, so the test holds whichever separator a join produces.
+ const below = (path: string): string | undefined => {
+ const norm = normSeps(path)
+ const root = normSeps(CLONE) + '/'
+
+ return norm.startsWith(root) ? norm.slice(root.length) : undefined
+ }
+ const fs: ReaderFs = {
+ read: async path => {
+ const key = below(path)
+
+ if (key === undefined || !(key in files)) throw new Error('ENOENT')
+
+ return files[key] as string
+ },
+ stat: async path => {
+ const key = below(path)
+
+ return key !== undefined && key in files ? { size: (files[key] as string).length, kind: 'file' } : undefined
+ },
+ list: async path => {
+ const key = below(path)
+ const prefix = key === undefined ? undefined : `${key}/`
+ const names = prefix === undefined ? [] : Object.keys(files).filter(file => file.startsWith(prefix)).map(file => file.slice(prefix.length))
+
+ if (names.length === 0) throw new Error('ENOENT')
+
+ return [...new Set(names.map(name => name.split('/')[0] as string))].map(name => ({ name, kind: names.includes(name) ? 'file' : 'dir' }))
+ },
+ }
+
+ it('lists the plugins and what each ships', async () => {
+ const plugins = await readCatalog(fs, CLONE)
+
+ expect(plugins).not.toBeNull()
+ expect(plugins?.[0]).toMatchObject({ name: 'a-plugin', version: '1.2.3', skills: ['alpha'], commands: ['go'], hasMcp: true })
+ })
+
+ it('reads a skill file from a Windows plugin folder', async () => {
+ const [plugin] = (await readCatalog(fs, CLONE)) ?? []
+ const doc = plugin === undefined ? null : await readDoc(fs, plugin, 'skill', 'alpha')
+
+ expect(doc?.description).toBe('Alpha does a')
+ })
+
+ it('still refuses a relative location and one that climbs out', async () => {
+ expect(await readCatalog(fs, 'marketplaces\\ruflo')).toBeNull()
+ expect(await readCatalog(fs, 'C:\\Users\\dev\\..\\other')).toBeNull()
+ })
+})
diff --git a/plugins/ruflo-console/tests/windows-path-guards.spec.ts b/plugins/ruflo-console/tests/windows-path-guards.spec.ts
new file mode 100644
index 0000000000..3741a52581
--- /dev/null
+++ b/plugins/ruflo-console/tests/windows-path-guards.spec.ts
@@ -0,0 +1,122 @@
+import { describe, expect, it } from 'vitest'
+
+import { under } from '../hooks/data/files'
+import { parseInstalled } from '../hooks/data/facts'
+import { baseOf, insideOrSame } from '../hooks/data/paths'
+import { safeInstallPath } from '../hooks/data/research'
+import { isRunFile } from '../hooks/data/wf-drill-io'
+import { isUnder } from '../hooks/wf-cost-live'
+import { installedEntries } from '../hooks/updates'
+import { isRunPath } from '../hooks/wf-actions'
+
+// The console builds paths as `<root>/<name>` even when the root is `C:\Users\x\.claude`, so a run's folder is `C:\Users\x\.claude/projects/...`.
+// Its guards must see `..` under either separator, and a config folder that ends in a backslash must still match.
+const CONFIG = 'C:\\Users\\x\\.claude'
+const RUN = `${CONFIG}/projects/-C--proj/sess/subagents/workflows/wf_1`
+
+describe('the run-path guards on a Windows config folder', () => {
+ it('accept a run folder and file under projects/', () => {
+ expect(isRunPath(RUN, CONFIG)).toBe(true)
+ expect(isRunFile(`${RUN}/agent.jsonl`, CONFIG)).toBe(true)
+ expect(isUnder(`${CONFIG}/projects/x`, CONFIG)).toBe(true)
+ })
+
+ it('refuse a .. segment written with a backslash, which the old "/"-only split missed', () => {
+ for (const path of [`${CONFIG}/projects/..\\..\\secret.txt`, `${CONFIG}/projects/a\\..\\b`, `${CONFIG}/projects/../x`]) {
+ expect(isRunPath(path, CONFIG), path).toBe(false)
+ expect(isRunFile(path, CONFIG), path).toBe(false)
+ expect(isUnder(path, CONFIG), path).toBe(false)
+ }
+ })
+
+ it('still match when the config folder ends in a backslash or a slash', () => {
+ for (const config of [`${CONFIG}\\`, `${CONFIG}/`]) {
+ expect(isRunPath(RUN, config), config).toBe(true)
+ expect(isRunFile(`${RUN}/a.jsonl`, config), config).toBe(true)
+ expect(isUnder(`${config.replace(/[\\/]+$/, '')}/projects/x`, config), config).toBe(true)
+ expect(under(config, 'projects/x'), config).toBe(`${CONFIG}/projects/x`)
+ }
+ })
+
+ it('keep the POSIX rules exactly', () => {
+ expect(isRunPath('/h/.claude/projects/a/wf_1', '/h/.claude')).toBe(true)
+ expect(isRunPath('/h/.claude/projects/../x', '/h/.claude')).toBe(false)
+ expect(isRunPath('/h/.claude-other/projects/a', '/h/.claude')).toBe(false)
+ expect(under('/h/.claude/', 'projects')).toBe('/h/.claude/projects')
+ expect(isUnder('/h/.claude/projects/a..b/c', '/h/.claude')).toBe(true)
+ })
+})
+
+describe('a plugin install path on Windows (the research reader)', () => {
+ it('accepts a drive path and refuses a climbing, relative or shell-looking one, as on POSIX', () => {
+ expect(safeInstallPath('C:\\Users\\x\\.claude\\plugins\\cache\\ruflo\\ruflo-goals\\0.3.0')).toBeDefined()
+ expect(safeInstallPath('/home/u/.claude/plugins/cache/ruflo/ruflo-goals/0.3.0')).toBeDefined()
+
+ for (const bad of ['relative', 'C:\\a\\..\\b', 'C:\\x; calc', 'C:\\x$(id)', '', undefined, 42]) expect(safeInstallPath(bad), String(bad)).toBeUndefined()
+ })
+})
+
+describe('the project name shown on the menu and boot screen', () => {
+ it('is the last folder under either separator, a trailing separator included', () => {
+ expect(baseOf('/work/proj')).toBe('proj')
+ expect(baseOf('/work/proj/')).toBe('proj')
+ expect(baseOf('C:\\Users\\x\\proj')).toBe('proj')
+ expect(baseOf('C:\\Users\\x\\proj\\')).toBe('proj')
+ expect(baseOf('C:/Users/x/proj')).toBe('proj')
+ expect(baseOf('\\\\srv\\share\\proj')).toBe('proj')
+ expect(baseOf('')).toBe('')
+ })
+})
+
+// installed_plugins.json records one entry per install; a project-scope entry names the project it was installed for (a Windows path there).
+const record = (version: string, scope: string, projectPath?: string) => ({ scope, version, installPath: `C:\\cache\\ruflo-console\\${version}`, ...(projectPath !== undefined && { projectPath }) })
+const INSTALLED = JSON.stringify({
+ version: 2,
+ plugins: {
+ 'ruflo-console@ruflo': [record('0.44.7', 'project', 'C:\\Users\\x\\git\\other'), record('0.46.0', 'project', 'C:\\Users\\x\\git\\proj'), record('0.47.0', 'user')],
+ 'ruflo-swarm@ruflo': [record('0.3.7', 'project', 'C:\\Users\\x\\git\\other')],
+ },
+})
+const versionFor = (cwd?: string, id = 'ruflo-console@ruflo'): string | undefined => parseInstalled(INSTALLED, cwd)?.find(entry => entry.id === id)?.version
+
+describe('which install record applies to a session', () => {
+ it('is the project record for this folder, under any separator style, letter case, or a folder inside the project', () => {
+ for (const cwd of ['C:\\Users\\x\\git\\proj', 'c:/users/X/git/PROJ', 'C:\\Users\\x\\git\\proj\\packages\\app', 'C:\\Users\\x\\git\\proj\\']) expect(versionFor(cwd), cwd).toBe('0.46.0')
+ })
+
+ it("is the user record when no project record is for this folder, and never another project's", () => {
+ expect(versionFor('C:\\Users\\x\\git\\elsewhere')).toBe('0.47.0')
+ expect(versionFor('C:\\Users\\x\\git\\project-two')).toBe('0.47.0')
+ expect(versionFor('C:\\Users\\x\\git\\proj-extra')).toBe('0.47.0')
+ expect(versionFor()).toBe('0.47.0')
+ })
+
+ it('falls back to the first record when there is no user record, as before', () => {
+ expect(versionFor('C:\\Users\\x\\git\\elsewhere', 'ruflo-swarm@ruflo')).toBe('0.3.7')
+ expect(parseInstalled(JSON.stringify({ plugins: { 'a@b': { version: '1.0.0', scope: 'user' } } }))?.[0]?.version).toBe('1.0.0')
+ })
+
+ it('the updater applies the same rule: a session in a subfolder of the project updates the project install', () => {
+ const list = JSON.stringify([
+ { id: 'ruflo-console@ruflo', version: '0.46.0', scope: 'project', projectPath: 'C:\\Users\\x\\git\\proj' },
+ { id: 'ruflo-console@ruflo', version: '0.44.7', scope: 'project', projectPath: 'C:\\Users\\x\\git\\other' },
+ { id: 'ruflo-console@ruflo', version: '0.47.0', scope: 'user' },
+ ])
+ const seen = (cwd: string): string[] => installedEntries(list, cwd).map(entry => `${entry.scope}:${entry.version}`).sort()
+
+ expect(seen('C:\\Users\\x\\git\\proj')).toEqual(['project:0.46.0', 'user:0.47.0'])
+ expect(seen('c:/users/x/git/proj/sub')).toEqual(['project:0.46.0', 'user:0.47.0'])
+ expect(seen('C:\\Users\\x\\git\\elsewhere')).toEqual(['user:0.47.0'])
+ })
+})
+
+describe('insideOrSame', () => {
+ it('holds for the folder itself and what is below it, never for a sibling that shares the prefix', () => {
+ expect(insideOrSame('C:\\a\\b', 'C:/A/B/c')).toBe(true)
+ expect(insideOrSame('C:\\a\\b', 'C:\\a\\b')).toBe(true)
+ expect(insideOrSame('C:\\a\\b', 'C:\\a\\bc')).toBe(false)
+ expect(insideOrSame('/a/b', '/a/b/c')).toBe(true)
+ expect(insideOrSame('/a/b', '/a/B/c')).toBe(false)
+ expect(insideOrSame('', '/a')).toBe(false)
+ })
+})
diff --git a/plugins/ruflo-console/tests/write-argv.spec.ts b/plugins/ruflo-console/tests/write-argv.spec.ts
index d731cd6cad..cee25e98b6 100644
--- a/plugins/ruflo-console/tests/write-argv.spec.ts
+++ b/plugins/ruflo-console/tests/write-argv.spec.ts
@@ -186,7 +186,8 @@ describe('the POSIX argv (macOS, BSD): a fixed set of constant scripts, the path
})
})
-describe('the POSIX scripts on a real disk (sh and dd as this machine has them)', () => {
+// Windows writes through the host file API (host-fs), never these scripts; NTFS has no mode bits or FIFOs to check them against.
+describe.skipIf(process.platform === 'win32')('the POSIX scripts on a real disk (sh and dd as this machine has them)', () => {
let dir = ''
afterEach(() => {
diff --git a/plugins/ruflo-console/tui/run.ts b/plugins/ruflo-console/tui/run.ts
index c79ade2548..cf27ed750e 100644
--- a/plugins/ruflo-console/tui/run.ts
+++ b/plugins/ruflo-console/tui/run.ts
@@ -32,10 +32,17 @@ export const isTuiView = (value: unknown): value is TuiView => typeof value ===
/** Any page the shell can open, which is every console view and the AI page (`--view`, the go prompt). */
export const isPage = (value: unknown): value is Page => typeof value === 'string' && (PAGE_IDS as readonly string[]).includes(value)
-/** Colour depth from the environment: NO_COLOR and a dumb terminal get none, COLORTERM truecolor/24bit gets 24-bit, the rest 256. */
+/**
+ * Colour depth from the environment: NO_COLOR and a dumb terminal get none, COLORTERM truecolor/24bit gets 24-bit, the rest 256.
+ * An unset TERM means no terminal on Unix, but not on Windows: Windows Terminal, PowerShell and cmd leave TERM unset (`OS` is
+ * Windows_NT there) while drawing ANSI, so only an explicit `dumb` turns colour off.
+ */
export function depthOf(env: Record<string, string | undefined>): Depth {
if (env.NO_COLOR !== undefined && env.NO_COLOR !== '') return 'none'
- if (env.TERM === 'dumb' || env.TERM === undefined || env.TERM === '') return 'none'
+
+ const isWindows = env.OS === 'Windows_NT'
+
+ if (env.TERM === 'dumb' || ((env.TERM === undefined || env.TERM === '') && !isWindows)) return 'none'
return env.COLORTERM === 'truecolor' || env.COLORTERM === '24bit' ? 'truecolor' : '256'
}
diff --git a/plugins/ruflo-console/tui/session.ts b/plugins/ruflo-console/tui/session.ts
index 1f46664c40..7167bf065b 100644
--- a/plugins/ruflo-console/tui/session.ts
+++ b/plugins/ruflo-console/tui/session.ts
@@ -120,7 +120,10 @@ export function openSession(options: SessionOptions, host?: Host): Session {
let cardFits = false
let isMoving = false
- const ready = Promise.all([node.home().then(home => void (state.home = home ?? null), () => undefined), node.configDir().then(dir => void (state.configDir = dir ?? null), () => undefined)])
+ // The config folder is $CLAUDE_CONFIG_DIR, else <home>/.claude, as in the engine (register.ts); with neither known the plugin, marketplace and run reads have nowhere to look.
+ const ready = Promise.all([node.home().then(home => void (state.home = home ?? null), () => undefined), node.configDir().then(dir => void (state.configDir = dir ?? null), () => undefined)]).then(() => {
+ if (state.configDir === null && state.home !== null) state.configDir = `${state.home}/.claude`
+ })
return {
state,
diff --git a/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json b/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json
index e160227d8f..bebe6cad12 100644
--- a/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json
+++ b/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "ruflo-cost-tracker",
"description": "Token usage tracking, model cost attribution per agent, budget alerts, and optimization recommendations — uses memory_* (namespace-routed) for cost-tracking and cost-patterns; pairs with federation budget circuit breaker (ADR-097)",
- "version": "0.28.2",
+ "version": "0.28.3",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
diff --git a/plugins/ruflo-cost-tracker/CHANGELOG.md b/plugins/ruflo-cost-tracker/CHANGELOG.md
index 53ba2cb753..feaad32ed2 100644
--- a/plugins/ruflo-cost-tracker/CHANGELOG.md
+++ b/plugins/ruflo-cost-tracker/CHANGELOG.md
@@ -2,6 +2,11 @@
Newest first. One `## <version> — <date>` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; older versions: `git log -- plugins/ruflo-cost-tracker`.
+## 0.28.3 — 2026-10-24
+- fix: `ledger.mjs`, `advise.mjs` and `local-cost.mjs` do nothing on Windows: they ran only when `import.meta.url === "file://" + argv[1]`, which is never true there (`file:///C:/…` against `C:…`), so every call exited 0 with no output. They now compare against `pathToFileURL(argv[1])`.
+- fix: `ledger.mjs --project` takes a drive-lettered path, and the project filter matches Windows paths ignoring separator style and drive-letter case, so the ruflo console's mission spend works on Windows.
+- chore: `scripts/smoke.sh` builds its root with `pwd -W` under Git Bash, so a Windows `node` can open the paths it is given (5 steps failed there before).
+
## 0.28.2 — 2026-10-12
- fix: a failed Stop-hook telemetry write is logged to ~/.claude-flow/logs/cost-tracker-failures.log (capped at 512 KB, rotated to the newest 200 lines) instead of being discarded; the hook still never blocks a turn (#3227, #4078, thanks @nicholas-ruest)
diff --git a/plugins/ruflo-cost-tracker/scripts/_ledger.mjs b/plugins/ruflo-cost-tracker/scripts/_ledger.mjs
index 5f51a054dc..a34d69f4c5 100644
--- a/plugins/ruflo-cost-tracker/scripts/_ledger.mjs
+++ b/plugins/ruflo-cost-tracker/scripts/_ledger.mjs
@@ -241,9 +241,20 @@ export const READERS = { claude: claudeRows, codex: codexRows, grok: grokRows };
/** True when `row.project` is `project` itself or a directory inside it (a trailing slash on `project` is ignored). */
export function inProject(row, project) {
- const root = project.length > 1 ? project.replace(/\/+$/, '') : project;
const at = typeof row.project === 'string' ? row.project : '';
+ // A Windows path (drive-lettered; either separator, any letter case) compares as `c:/users/x`: transcripts write `C:\Users\x`,
+ // and the caller may pass `C:/Users/x` or a different drive-letter case.
+ if (/^[A-Za-z]:[\\/]/.test(project) || /^[A-Za-z]:[\\/]/.test(at)) {
+ const flat = path => path.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase();
+ const here = flat(at);
+ const there = flat(project);
+
+ return here === there || here.startsWith(`${there}/`);
+ }
+
+ const root = project.length > 1 ? project.replace(/\/+$/, '') : project;
+
return at === root || at.startsWith(`${root}/`);
}
diff --git a/plugins/ruflo-cost-tracker/scripts/advise.mjs b/plugins/ruflo-cost-tracker/scripts/advise.mjs
index d7aad0202c..c215960733 100644
--- a/plugins/ruflo-cost-tracker/scripts/advise.mjs
+++ b/plugins/ruflo-cost-tracker/scripts/advise.mjs
@@ -10,6 +10,7 @@
import { collect } from './_ledger.mjs';
import { priceUsage, downshift, lookup } from './_pricebook.mjs';
import { parseDurationMs } from './_sessions.mjs';
+import { pathToFileURL } from 'node:url';
const arg = (name, fallback) => { const i = process.argv.indexOf(`--${name}`); return i > 0 ? process.argv[i + 1] : fallback; };
const sum = (rows, pick) => rows.reduce((total, row) => total + pick(row), 0);
@@ -71,7 +72,8 @@ export function advise(rows) {
const fmt = f => (f.saving === null ? 'saving n/a' : `up to ${f.unit === 'usd' ? '$' : ''}${f.saving.toFixed(2)}${f.unit === 'usd' ? '' : ' credits'} over the window`);
-if (import.meta.url === `file://${process.argv[1]}`) {
+// pathToFileURL, not `file://${argv[1]}`: on Windows import.meta.url is file:///C:/... and argv[1] is C:..., so the string never matched and the script printed nothing.
+if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
const spec = arg('since', '7d');
const sinceMs = spec === 'all' ? 0 : Date.now() - (parseDurationMs(spec) ?? 7 * 86_400_000);
const providers = arg('provider', 'all') === 'all' ? undefined : [arg('provider')];
diff --git a/plugins/ruflo-cost-tracker/scripts/ledger.mjs b/plugins/ruflo-cost-tracker/scripts/ledger.mjs
index 7d32e3fefe..defebb0e4d 100644
--- a/plugins/ruflo-cost-tracker/scripts/ledger.mjs
+++ b/plugins/ruflo-cost-tracker/scripts/ledger.mjs
@@ -14,6 +14,7 @@ import { collect } from './_ledger.mjs';
import { priceUsage, bookDate } from './_pricebook.mjs';
import { parseDurationMs } from './_sessions.mjs';
import { advise } from './advise.mjs';
+import { pathToFileURL } from 'node:url';
const arg = (name, fallback) => { const i = process.argv.indexOf(`--${name}`); return i > 0 ? process.argv[i + 1] : fallback; };
@@ -79,15 +80,17 @@ function isoMs(name) {
return Date.parse(value);
}
-/** An absolute POSIX path with no control characters or `..`; anything else exits 2. */
+/** An absolute path (POSIX, or drive-lettered on Windows) with no control characters or `..`; anything else exits 2. */
function absolutePath(name) {
const value = arg(name);
- if (typeof value !== 'string' || !value.startsWith('/') || /[\u0000-\u001f\u007f]/.test(value) || value.split('/').includes('..')) bad(`--${name} needs an absolute path with no '..'`);
+ const isWindows = typeof value === 'string' && /^[A-Za-z]:[\\/]/.test(value);
+ if (typeof value !== 'string' || !(value.startsWith('/') || isWindows) || /[\u0000-\u001f\u007f]/.test(value) || value.split(isWindows ? /[\\/]/ : '/').includes('..')) bad(`--${name} needs an absolute path with no '..'`);
return value;
}
-if (import.meta.url === `file://${process.argv[1]}`) {
+// pathToFileURL, not `file://${argv[1]}`: on Windows import.meta.url is file:///C:/... and argv[1] is C:..., so the string never matched and the script printed nothing.
+if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
const given = name => process.argv.includes(`--${name}`);
const fromMs = given('from') ? isoMs('from') : null;
const toMs = given('to') ? isoMs('to') : null;
diff --git a/plugins/ruflo-cost-tracker/scripts/local-cost.mjs b/plugins/ruflo-cost-tracker/scripts/local-cost.mjs
index a9ed835357..8399f7b901 100644
--- a/plugins/ruflo-cost-tracker/scripts/local-cost.mjs
+++ b/plugins/ruflo-cost-tracker/scripts/local-cost.mjs
@@ -11,6 +11,7 @@
// answer is utilisation, so it is always shown at several busy fractions.
import { lookup } from './_pricebook.mjs';
+import { pathToFileURL } from 'node:url';
const arg = (name, fallback) => { const i = process.argv.indexOf(`--${name}`); return i > 0 ? Number(process.argv[i + 1]) : fallback; };
const text = name => { const i = process.argv.indexOf(`--${name}`); return i > 0 ? process.argv[i + 1] : undefined; };
@@ -33,7 +34,8 @@ export function breakEvenBusy(config, apiPerMtok) {
return denominator > 0 && fixedPerHour / denominator <= 1 ? fixedPerHour / denominator : null;
}
-if (import.meta.url === `file://${process.argv[1]}`) {
+// pathToFileURL, not `file://${argv[1]}`: on Windows import.meta.url is file:///C:/... and argv[1] is C:..., so the string never matched and the script printed nothing.
+if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
const config = { wattsIdle: arg('watts-idle', 80), wattsActive: arg('watts-active', 350), kwh: arg('kwh', 0.15), hwPrice: arg('hw-price', 3000), lifeYears: arg('life-years', 3), resale: arg('resale', 0.2), tokPerS: arg('tok-per-s', NaN) };
if (!Number.isFinite(config.tokPerS) || config.tokPerS <= 0) { console.error('usage: local-cost.mjs --tok-per-s <measured generation speed> [options]'); process.exit(2); }
const busy = arg('busy', 0.25);
diff --git a/plugins/ruflo-cost-tracker/scripts/smoke.sh b/plugins/ruflo-cost-tracker/scripts/smoke.sh
index 6aec6146a1..0f1078b1cb 100755
--- a/plugins/ruflo-cost-tracker/scripts/smoke.sh
+++ b/plugins/ruflo-cost-tracker/scripts/smoke.sh
@@ -1,17 +1,18 @@
#!/usr/bin/env bash
-# Structural smoke test for ruflo-cost-tracker v0.28.2.
+# Structural smoke test for ruflo-cost-tracker v0.28.3.
set -u
-ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+# `pwd -W` (Git Bash on Windows) gives C:/Users/...; plain pwd gives /c/Users/..., which a Windows node cannot open. Elsewhere -W fails and pwd answers.
+ROOT="$(cd "$(dirname "$0")/.." && { pwd -W 2>/dev/null || pwd; })"
PASS=0
FAIL=0
step() { printf "→ %s ... " "$1"; }
ok() { printf "PASS\n"; PASS=$((PASS+1)); }
bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }
-step "1. plugin.json declares 0.28.2 with new keywords"
+step "1. plugin.json declares 0.28.3 with new keywords"
v=$(grep -E '"version"' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
-if [[ "$v" != "0.28.2" ]]; then
- bad "expected 0.28.2, got '$v'"
+if [[ "$v" != "0.28.3" ]]; then
+ bad "expected 0.28.3, got '$v'"
else
miss=""
for k in namespace-routing mcp agentic-flow agent-booster tier1-routing model-routing benchmarking verified telemetry budget projection forecast counterfactual drift-detection trend-alert anomaly-detection outlier-detection health-check composite-gate auto-track stop-hook snapshot-diff pr-regression git-context traceability drill-down per-message; do
diff --git a/plugins/ruflo-cost-tracker/scripts/test-ledger.mjs b/plugins/ruflo-cost-tracker/scripts/test-ledger.mjs
index ac62c8ab51..ddbff5aab1 100644
--- a/plugins/ruflo-cost-tracker/scripts/test-ledger.mjs
+++ b/plugins/ruflo-cost-tracker/scripts/test-ledger.mjs
@@ -21,7 +21,7 @@ mkdirSync(join(process.env.CODEX_HOME, 'archived_sessions'), { recursive: true }
const grokSession = join(process.env.GROK_HOME, 'sessions', encodeURIComponent('/proj/g'), 'gs1');
mkdirSync(grokSession, { recursive: true });
-const { collect } = await import('./_ledger.mjs');
+const { collect, inProject } = await import('./_ledger.mjs');
const { priceUsage, lookup } = await import('./_pricebook.mjs');
const { summarise } = await import('./ledger.mjs');
const { advise } = await import('./advise.mjs');
@@ -202,5 +202,35 @@ test('window: an invalid ISO time, a missing value, or a relative path exits 2 w
}
});
+// ── Windows: transcripts record `C:\Users\x\proj`, and the caller may pass either separator or another drive-letter case.
+const winRows = mkdtempSync(join(tmpdir(), 'ledger-winpaths-'));
+mkdirSync(join(winRows, 'claude', 'projects', 'q'), { recursive: true });
+mkdirSync(join(winRows, 'codex'), { recursive: true });
+mkdirSync(join(winRows, 'grok', 'sessions'), { recursive: true });
+jsonl(join(winRows, 'claude', 'projects', 'q', 'w.jsonl'), [
+ at('2026-10-02T06:00:00.000Z', 'in-a', 'C:\\Users\\x\\proj'),
+ at('2026-10-02T07:00:00.000Z', 'in-sub', 'C:\\Users\\x\\proj\\sub'),
+ at('2026-10-02T08:00:00.000Z', 'sibling', 'C:\\Users\\x\\proj-other'),
+ at('2026-10-02T09:00:00.000Z', 'other-drive', 'D:\\Users\\x\\proj'),
+]);
+const ledgerWin = (...flags) => {
+ const r = spawnSync(process.execPath, [join(HERE, 'ledger.mjs'), '--format', 'json', ...flags], { encoding: 'utf-8', env: { PATH: process.env.PATH, CLAUDE_CONFIG_DIR: join(winRows, 'claude'), CODEX_HOME: join(winRows, 'codex'), GROK_HOME: join(winRows, 'grok') } });
+
+ return { ...r, json: r.status === 0 ? JSON.parse(r.stdout) : null };
+};
+test('windows: --project takes a drive path in either separator style and any drive-letter case, and matches the folder and its subfolders only', () => {
+ for (const project of ['C:\\Users\\x\\proj', 'C:/Users/x/proj', 'c:\\users\\X\\PROJ\\', 'C:/Users/x/proj/']) {
+ assert.equal(ledgerWin('--from', FROM, '--to', TO, '--project', project).json?.rows, 2, project); // in-a and in-sub; not proj-other, not drive D
+ }
+});
+test('windows: a relative or climbing drive path still exits 2', () => {
+ for (const project of ['C:proj', 'C:\\Users\\x\\..\\y', 'C:/Users/x/../y']) assert.equal(ledgerWin('--project', project).status, 2, project);
+});
+test('windows: inProject keeps the POSIX rule exact (case-sensitive, directory boundary)', () => {
+ assert.equal(inProject({ project: '/proj/A' }, '/proj/a'), false);
+ assert.equal(inProject({ project: '/proj/ab' }, '/proj/a'), false);
+ assert.equal(inProject({ project: '/proj/a/sub' }, '/proj/a'), true);
+});
+
if (failed > 0) { console.log(`\n${failed} failed`); process.exit(1); }
console.log('\nall passed');