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 writes go through the host filesystem (#4433) (#4434)

rUvea25a05abecd
diff --git a/plugins/ruflo-console/.claude-plugin/plugin.json b/plugins/ruflo-console/.claude-plugin/plugin.json
index edd50371c1..a674c0d141 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 → 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.45.0",
+ "version": "0.45.1",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
diff --git a/plugins/ruflo-console/CHANGELOG.md b/plugins/ruflo-console/CHANGELOG.md
index b18eff85be..95df67db21 100644
--- a/plugins/ruflo-console/CHANGELOG.md
+++ b/plugins/ruflo-console/CHANGELOG.md
@@ -2,6 +2,16 @@
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.45.1 — 2026-10-23
+- fix: broader Windows parity for the console (#4036, thanks @socrates6969) — the narrow 0.44.2 and 0.44.7 fixes extended across the whole plugin. The path helpers are consolidated into `hooks/data/paths.ts` (`isWindowsPath`, `isAbsolutePath`, `trimTrailing`, `joinPath`, `samePath`, `hasParentSegment`, `below`, `normalizePath`, `homeOf`) and the earlier narrower `abs-path.ts` is removed (its two sites move to the consolidated module).
+- fix: workspace keys ignore drive-letter case and trailing-separator differences, so `c:\work\app\` and `C:\Work\app` are one workspace with one remembered page and one terminal history.
+- fix: any confirmed action whose on-disk check fails is re-checked once after one second (new `VERIFY_RETRY_MS = 1_000` in `runner.ts`), so a hive started from the console shows at once instead of reading "not verified".
+- fix: no Linux-only process probe off Linux (macOS, Windows), and the probe timers are cleared when the session ends.
+- fix: autopilot's kill flag can be cleared on Windows. Starting autopilot on Windows is refused with a plain message until a follow-up: its journal needs atomic appends and its folder fence needs Windows-aware path checks. Stop works as before.
+- fix: disk writes (settings, journal, envelope, exports) work on Windows through the host's file API (`$.fs.write` / `$.fs.exists`); Linux and macOS keep their exact commands.
+- fix: the home folder is found on Windows via `USERPROFILE` or `HOMEDRIVE` + `HOMEPATH`, so sessions, plugin health and What's new read it.
+- fix: Windows project folders (`C:\work\app`, `\\server\share\app`) and UNC shares are recognised across the remaining sites (plugin catalog, workflow drill I/O, event export, ADR discovery, workflow file resolution); protected autopilot folders match ignoring case.
+
## 0.45.0 — 2026-10-23
- feat: a **ruRE** page in the TOOLS group (ADR-494): static reverse engineering of a file in your project through the six `rure_*` tools — a JS/Electron app (APP MAP, FIND FEATURE, UNPACK .ASAR), a native binary (ELF, PE, Mach-O), a .NET assembly and EVM bytecode. The tools parse and never run the file. Five rows are `$0` reads that run at once; UNPACK .ASAR writes to a temp folder and asks first. The file is named by a new *sample* field that takes only a path inside the project. Every row is a palette id (`/ruflo run dt-re-bin <path>`). Names and strings from the analyzed file are shown cleaned, so a hostile binary cannot put a terminal escape on the screen. On a ruflo CLI without the tools (3.59.17 and older) the rows say to update.
- chore: Enter in a field on a page of its own can run that page’s row (the ruRE page); the same `query` field on the Plugins page still runs the plugin search. The boot specs now derive the finish time from the number of areas instead of a fixed 5.4 s.
diff --git a/plugins/ruflo-console/hooks/actions.ts b/plugins/ruflo-console/hooks/actions.ts
index 403d320f39..e3396ea82a 100644
--- a/plugins/ruflo-console/hooks/actions.ts
+++ b/plugins/ruflo-console/hooks/actions.ts
@@ -7,6 +7,7 @@ import { idOf, type AgentRecord, type ClaimRecord, type Claimant, type TaskRecor
import type { Snapshot } from './data/snapshot'
import type { Findings } from './data/failure'
import type { Host } from './host'
+import type { WriteOp } from './data/write-via'
export type ActionSpec = {
label: string
@@ -14,6 +15,8 @@ export type ActionSpec = {
/** A fixed command outside ruflo, or an offline read, with optional JSON on stdin. */
argv?: readonly string[]
stdin?: string
+ /** A disk write that goes through the host's file API instead of `argv` (the Windows write flavor, data/write-via.ts); `argv` then is only a stand-in the runner never executes. */
+ write?: WriteOp
expect: string
verify?: (snapshot: Snapshot) => boolean
/** A local check after a confirmed action succeeds; never part of background refreshes. */
diff --git a/plugins/ruflo-console/hooks/activity-io.ts b/plugins/ruflo-console/hooks/activity-io.ts
index a62782f35d..fe7a1a1f4e 100644
--- a/plugins/ruflo-console/hooks/activity-io.ts
+++ b/plugins/ruflo-console/hooks/activity-io.ts
@@ -8,8 +8,9 @@
*/
import { checkNoLinks } from './data/wf-file'
import { appendArgv } from './data/append-argv'
-import { dirOf, newFileArgv, replaceFileArgv } from './data/wf-file'
+import { dirOf } from './data/wf-file'
import { writeFlavorReady } from './data/write-flavor'
+import { writeVia } from './data/write-via'
import { keepNewestHalf, READ_MAX } from './data/activity-store'
import type { Host } from './host'
@@ -68,7 +69,7 @@ async function ensureIgnored(host: IoHost, dir: string): Promise<void> {
if (ignored.has(dir)) return
ignored.add(dir)
- await host.run(newFileArgv(`${dir}/.gitignore`, true, await writeFlavorReady()), WRITE_TIMEOUT_MS, IGNORE_BODY).catch(() => undefined)
+ await writeVia(await writeFlavorReady(), host, { kind: 'create-excl', path: `${dir}/.gitignore`, text: IGNORE_BODY, timeoutMs: WRITE_TIMEOUT_MS }).catch(() => undefined)
}
async function rotate(host: IoHost, channel: Channel): Promise<void> {
@@ -78,10 +79,24 @@ async function rotate(host: IoHost, channel: Channel): Promise<void> {
const size = stat.size ?? channel.size ?? 0
const kept = size > READ_MAX ? '' : keepNewestHalf(await host.fs.read(channel.path).catch(() => ''), channel.cap)
+ const flavor = await writeFlavorReady()
+
+ // Windows (host-fs): no rm, mv or temporary file; the host's write replaces the file with its newest half in one call.
+ if (flavor === 'host-fs') {
+ const replaced = await writeVia(flavor, host, { kind: 'replace', path: channel.path, text: kept, hasDir: true })
+
+ if (replaced.exitCode === 0) {
+ channel.size = kept.length
+ channel.rotations++
+ }
+
+ return
+ }
+
await host.run(['rm', '-f', '--', tmpOf(channel.path)], WRITE_TIMEOUT_MS)
// The flavor is awaited before the first flavored write; the rm, mv and mkdir argv are the same on GNU and BSD, so they need none.
- const written = await host.run(newFileArgv(tmpOf(channel.path), true, await writeFlavorReady()), WRITE_TIMEOUT_MS, kept)
+ const written = await writeVia(flavor, host, { kind: 'create-excl', path: tmpOf(channel.path), text: kept, timeoutMs: WRITE_TIMEOUT_MS })
if (written.exitCode !== 0) return
@@ -118,7 +133,8 @@ export async function flush(host: IoHost, cwd: string, path: string, nowMs: numb
if (!clear.ok) throw new Error(clear.why)
- if (!channel.isDirReady) {
+ // host-fs: the host's write makes the folders, and there is no mkdir to run.
+ if (!channel.isDirReady && (await writeFlavorReady()) !== 'host-fs') {
const made = await host.run(['mkdir', '-p', '--', dirOf(path)], WRITE_TIMEOUT_MS)
if (made.exitCode !== 0) throw new Error(`the folder could not be made (exit ${made.exitCode})`)
@@ -129,7 +145,7 @@ export async function flush(host: IoHost, cwd: string, path: string, nowMs: numb
if (channel.size === null) channel.size = (await host.fs.stat(path).catch(() => undefined))?.size ?? 0
- const result = await host.run(appendArgv(path, await writeFlavorReady()), WRITE_TIMEOUT_MS, batch.join(''))
+ const result = await writeVia(await writeFlavorReady(), host, { kind: 'append', path, text: batch.join(''), timeoutMs: WRITE_TIMEOUT_MS })
if (result.exitCode !== 0) throw new Error(`the write exited ${result.exitCode}`)
@@ -155,7 +171,7 @@ export async function replaceFile(host: IoHost, cwd: string, path: string, conte
if (!clear.ok) return clear.why.slice(0, 80)
const hasDir = (await host.fs.stat(dirOf(path)).catch(() => undefined)) !== undefined
- const result = await host.run(replaceFileArgv(path, hasDir, await writeFlavorReady()), WRITE_TIMEOUT_MS, content)
+ const result = await writeVia(await writeFlavorReady(), host, { kind: 'replace', path, text: content, hasDir, timeoutMs: WRITE_TIMEOUT_MS })
if (result.exitCode === 0) await ensureIgnored(host, dirOf(path))
diff --git a/plugins/ruflo-console/hooks/adr.ts b/plugins/ruflo-console/hooks/adr.ts
index 626416a467..5f0818aa91 100644
--- a/plugins/ruflo-console/hooks/adr.ts
+++ b/plugins/ruflo-console/hooks/adr.ts
@@ -13,9 +13,10 @@ import { adrDirText, detectStyle, draftFromMission, fileNameFor, initialRecord,
import { record as recordEvents } from './data/events'
import { readBounded, type ReadCache } from './data/files'
import { plain } from './data/parse'
-import { isAbsolutePath } from './data/abs-path'
+import { isAbsolutePath, joinPath } from './data/paths'
import { checkNoLinks, dirOf, newFileArgv, replaceFileArgv } from './data/wf-file'
import { writeFlavorReady } from './data/write-flavor'
+import { writeVia } from './data/write-via'
import type { Host } from './host'
import { activeMission, mcOf, record, saveLedger } from './mission-control'
import type { MissionRecord } from './mission-types'
@@ -85,12 +86,12 @@ export async function discover(host: Pick<Host, 'fs'>, cwd: string, setting: str
if (base === '' || !isAbsolutePath(base)) return { dir: null, why: 'no project folder is known' }
for (const candidate of tries) {
- const stat = await host.fs.stat(`${base}/${candidate}`).catch(() => undefined)
+ const stat = await host.fs.stat(joinPath(base, candidate)).catch(() => undefined)
if (stat === undefined) continue
// Every folder on the way down must be a real one: a link could lead out of the project.
- const safe = await checkNoLinks(host.fs, `${base}/${candidate}/.adr-probe`, { cwd: base }, { allowExisting: true })
+ const safe = await checkNoLinks(host.fs, joinPath(base, candidate, '.adr-probe'), { cwd: base }, { allowExisting: true })
if (!safe.ok) {
refused = refused === '' ? `${candidate}: ${safe.why}` : refused
@@ -206,7 +207,7 @@ async function writeNew(state: State, host: Pick<Host, 'fs' | 'run'>, dir: strin
if (!safe.ok) return safe.why
const hasDir = (await host.fs.stat(dirOf(path)).catch(() => undefined)) !== undefined
- const result = await host.run(newFileArgv(path, hasDir, await writeFlavorReady()), 10_000, text).catch((error: unknown) => ({ exitCode: null, stdout: '', stderr: error instanceof Error ? error.message : 'the command could not start' }))
+ const result = await writeVia(await writeFlavorReady(), host, { kind: hasDir ? 'create-excl' : 'create-dirs', path, text }).catch((error: unknown) => ({ exitCode: null, stdout: '', stderr: error instanceof Error ? error.message : 'the command could not start' }))
if (result.exitCode !== 0) return writeFailure(result.exitCode, result.stderr)
@@ -371,7 +372,7 @@ export async function statusSpec(state: State, host: Pick<Host, 'fs' | 'run' | '
if (now !== change.before) return failed([...done, `${change.file} changed since the diff was shown: nothing was written to it. Ask again.`])
- const result = await host.run(replaceFileArgv(path, true, await writeFlavorReady()), 10_000, change.after).catch(() => null)
+ const result = await writeVia(await writeFlavorReady(), host, { kind: 'replace', path, text: change.after, hasDir: true }).catch(() => null)
const back = await host.fs.read(path).catch(() => null)
if (result === null || result.exitCode !== 0 || back !== change.after) return failed([...done, `${change.file} could not be written as shown`])
diff --git a/plugins/ruflo-console/hooks/ap-live.ts b/plugins/ruflo-console/hooks/ap-live.ts
index bd478d9c8a..2d96e8b725 100644
--- a/plugins/ruflo-console/hooks/ap-live.ts
+++ b/plugins/ruflo-console/hooks/ap-live.ts
@@ -13,17 +13,18 @@ import { activeMission, dispatchSpec, startable, type LedgerTask, type MissionRe
import type { Host } from './host'
import type { State } from './state'
import { readBounded, under } from './data/files'
-import { checkNoLinks, dirOf, removeFileArgv, replaceFileArgv } from './data/wf-file'
+import { checkNoLinks, dirOf, removeFileArgv } from './data/wf-file'
import { writeFlavorReady } from './data/write-flavor'
+import { writeVia } from './data/write-via'
import { cleanText } from './data/wf-clean'
import { tierOf, tunablesFrom } from './data/ap-adapt'
import { adaptPass, rotate } from './ap-maint'
import { checkPin, type Pin } from './data/ap-pin'
import { loadPin, setPin } from './ap-pin-live'
-import { AUTOPILOT_DIR, ENVELOPE_FILE, KILL_FILE, open, type Envelope, type Sealed, type Spend } from './data/ap-envelope'
+import { AUTOPILOT_DIR, ENVELOPE_FILE, KILL_CLEARED, KILL_FILE, open, type Envelope, type Sealed, type Spend } from './data/ap-envelope'
import { anatoleFact, killSeen, preflightAll, type ToolCheck } from './data/ap-guard'
import { effectsOf, pickTask, readSpend } from './ap-pick'
-import { appendArgv, encodeLine, JOURNAL_FILE, JOURNAL_MAX_BYTES, REFUSED_WHY, startedCount, touchArgv, type JournalEvent } from './data/ap-journal'
+import { encodeLine, JOURNAL_FILE, JOURNAL_MAX_BYTES, REFUSED_WHY, startedCount, type JournalEvent } from './data/ap-journal'
import { digestText, emptyLoop, foldJournal, replayJournal, skipSet, tick, type EffectFact, type Facts, type LoopState, type TaskFact } from './data/ap-loop'
import type { Preflight } from './data/ap-loop'
import type { NoticeDraft } from './notices'
@@ -89,6 +90,9 @@ export const hostOf = (state: State): Host | undefined => hosts.get(state)
const pathOf = (state: State, rel: string): string => `${state.cwd.replace(/\/+$/, '')}/${rel}`
+/** What a start says where the write flavor is host-fs (Windows): see the gate in views/ap-panel.ts. */
+export const AUTOPILOT_WINDOWS_REFUSAL = 'Autopilot is not yet available on Windows: its journal and path fence need atomic appends and Windows-aware path checks (follow-up).'
+
/** Wires the host and, when the engine offers one, its permission check (`$.tool.check`); starts the tick timer once. */
export function wireAutopilot(state: State, host: Host, deps: { toolCheck?: ToolCheck } = {}): void {
hosts.set(state, host)
@@ -167,9 +171,9 @@ export function appendEvents(state: State, host: Host, events: readonly JournalE
return false
}
- if ((await host.fs.stat(path).catch(() => undefined)) === undefined) await host.run(touchArgv(path, await writeFlavorReady()), 10_000)
+ if ((await host.fs.stat(path).catch(() => undefined)) === undefined) await writeVia(await writeFlavorReady(), host, { kind: 'touch', path })
- const result = await host.run(appendArgv(path, await writeFlavorReady()), 10_000, events.map(encodeLine).join(''))
+ const result = await writeVia(await writeFlavorReady(), host, { kind: 'append', path, text: events.map(encodeLine).join('') })
if (result.exitCode !== 0) {
store.error = `the journal write exited ${result.exitCode}`
@@ -223,7 +227,9 @@ export async function stopNow(state: State, host: Host, reason = 'stopped by you
host.invalidate()
const clear = await checkNoLinks(host.fs, flag, { cwd: state.cwd }, { allowExisting: true }).catch(() => ({ ok: false as const, why: 'unchecked' }))
- const flagged = clear.ok ? await host.run(touchArgv(flag, await writeFlavorReady()), 10_000).then(result => result.exitCode === 0, () => false) : false
+ const flavor = await writeFlavorReady()
+ // host-fs: a touch would keep a cleared flag's marker, so the flag is rewritten empty (anything but the marker is a stop).
+ const flagged = clear.ok ? await writeVia(flavor, host, flavor === 'host-fs' ? { kind: 'replace', path: flag, text: '', hasDir: true } : { kind: 'touch', path: flag }).then(result => result.exitCode === 0, () => false) : false
const journaled = await appendEvents(state, host, [{ t: 'stop', at: Date.now(), reason }])
// Neither write landed (a full disk, a read-only folder): the stop is held in memory so a re-read of the files cannot undo it, and it is said.
@@ -245,9 +251,12 @@ export async function answerParked(state: State, host: Host, id: string, answer:
}
/** Clears the kill flag; part of the confirmed start, never a button of its own. */
-export function clearKill(state: State, host: Host): Promise<unknown> {
+export async function clearKill(state: State, host: Host): Promise<unknown> {
storeOf(state).heldStop = null
+ // host-fs has no delete: the flag is rewritten as cleared (killSeen reads it so); everywhere else it is removed.
+ if ((await writeFlavorReady()) === 'host-fs') return writeVia('host-fs', host, { kind: 'replace', path: pathOf(state, KILL_FILE), text: KILL_CLEARED, hasDir: true }).catch(() => undefined)
+
return host.run(removeFileArgv(pathOf(state, KILL_FILE)), 10_000).catch(() => undefined)
}
@@ -263,7 +272,7 @@ export async function writeEnvelope(state: State, host: Host, sealed: Sealed): P
}
const hasDir = (await host.fs.stat(dirOf(path)).catch(() => undefined)) !== undefined
- const result = await host.run(replaceFileArgv(path, hasDir, await writeFlavorReady()), 10_000, `${JSON.stringify(sealed, null, 2)}\n`)
+ const result = await writeVia(await writeFlavorReady(), host, { kind: 'replace', path, text: `${JSON.stringify(sealed, null, 2)}\n`, hasDir })
if (result.exitCode === 0) {
state.cache.delete(path)
diff --git a/plugins/ruflo-console/hooks/ap-maint.ts b/plugins/ruflo-console/hooks/ap-maint.ts
index fd32408d8f..f744ea83b8 100644
--- a/plugins/ruflo-console/hooks/ap-maint.ts
+++ b/plugins/ruflo-console/hooks/ap-maint.ts
@@ -4,8 +4,9 @@
*/
import type { Host } from './host'
import type { Store } from './ap-live'
-import { checkNoLinks, copyExclusiveArgv, replaceFileArgv } from './data/wf-file'
+import { checkNoLinks } from './data/wf-file'
import { writeFlavorReady } from './data/write-flavor'
+import { writeVia } from './data/write-via'
import { evaluate, lastHash, outcomesOf, promote, propose, reviewTrials, tunablesFrom, verifyReceipts } from './data/ap-adapt'
import type { Envelope } from './data/ap-envelope'
import { encodeLine, JOURNAL_FILE, type JournalEvent } from './data/ap-journal'
@@ -43,7 +44,7 @@ export async function rotate(store: Store, host: Host, cwd: string, nowMs: numbe
// The archive must be a new name with no link on the way: a pre-made link there would make the no-clobber copy skip and the old journal be lost.
const clear = await checkNoLinks(host.fs, archive, { cwd: cwd }).catch(() => ({ ok: false as const }))
- const copied = clear.ok ? await host.run(copyExclusiveArgv(path, archive, await writeFlavorReady()), 30_000).catch(() => ({ exitCode: 1 })) : { exitCode: 1 }
+ const copied = clear.ok ? await writeVia(await writeFlavorReady(), host, { kind: 'copy-no-clobber', from: path, path: archive, timeoutMs: 30_000 }).catch(() => ({ exitCode: 1 })) : { exitCode: 1 }
const saved = (await host.fs.stat(archive).catch(() => undefined)) !== undefined
if (copied.exitCode !== 0 || !saved) return
@@ -55,7 +56,7 @@ export async function rotate(store: Store, host: Host, cwd: string, nowMs: numbe
try {
if (pin !== null) await setPin(store, host, cwd, { ...pin, starts: 1 })
- const wrote = await host.run(replaceFileArgv(path, true, await writeFlavorReady()), 10_000, lines).catch(() => ({ exitCode: 1 }))
+ const wrote = await writeVia(await writeFlavorReady(), host, { kind: 'replace', path, text: lines, hasDir: true }).catch(() => ({ exitCode: 1 }))
if (wrote.exitCode !== 0 && pin !== null) await setPin(store, host, cwd, pin)
} finally {
diff --git a/plugins/ruflo-console/hooks/data/abs-path.ts b/plugins/ruflo-console/hooks/data/abs-path.ts
deleted file mode 100644
index 8fa494c03f..0000000000
--- a/plugins/ruflo-console/hooks/data/abs-path.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-/** Absolute on either family: `/posix`, a drive path (`C:\x` or `C:/x`) or a UNC share (`\\server\share`). A bare `C:` or `C:x` is drive-relative, so it is not. */
-export const isAbsolutePath = (path: string): boolean => path.startsWith('/') || path.startsWith('\\\\') || /^[A-Za-z]:[\\/]/.test(path)
-
-/** The path under the working directory unless it already is absolute (`under()` builds `C:\dev\app/.claude-flow/...` on Windows: prefixing that again was #4175). */
-export const rootedPath = (cwd: string, path: string): string => (isAbsolutePath(path) ? path : `${cwd.replace(/[\\/]+$/, '')}/${path}`)
diff --git a/plugins/ruflo-console/hooks/data/ap-envelope.ts b/plugins/ruflo-console/hooks/data/ap-envelope.ts
index 5ff32f50a9..bf48300d86 100644
--- a/plugins/ruflo-console/hooks/data/ap-envelope.ts
+++ b/plugins/ruflo-console/hooks/data/ap-envelope.ts
@@ -4,6 +4,7 @@
* hash does not match its body is treated as tampered and the loop refuses to run on it. Hard denies are not part of the envelope: they
* are a constant of this file, and an envelope that names one as allowed is rejected, never trimmed.
*/
+import { hasParentSegment, isAbsolutePath, isWindowsPath } from './paths'
/** Classes of action an envelope can allow. Each task is classified (data/ap-guard.ts) into exactly one, or is parked. */
export const TOOL_CLASSES = ['read', 'edit', 'test', 'git-local', 'git-branch', 'network', 'spawn', 'mcp'] as const
@@ -27,7 +28,8 @@ export const DENY_PATTERNS: readonly [HardDeny, RegExp][] = [
/** Folders the autopilot's own steps may never be pointed at: its envelope, journal and kill flag, and Project Anatole's status. A task or envelope that names one is refused, not trimmed. */
export const PROTECTED_DIRS = ['.claude-flow/console', '.claude-flow/protector-mod'] as const
export const isProtectedPath = (path: string): boolean => {
- const flat = path.replace(/\/+/g, '/').replace(/\/\.\//g, '/')
+ // Windows file systems ignore case, so a drive-lettered path is compared lower-cased; a POSIX path stays exact.
+ const flat = (isWindowsPath(path) ? path.toLowerCase() : path).replace(/\/+/g, '/').replace(/\/\.\//g, '/')
return PROTECTED_DIRS.some(dir => flat.includes(dir)) || flat.endsWith('/.claude-flow') || flat.endsWith('/.claude-flow/')
}
@@ -118,7 +120,7 @@ export function validateEnvelope(raw: unknown): Checked {
if (paths === null || paths.length === 0) errors.push('paths: at least one absolute folder')
for (const path of paths ?? []) {
- if (!path.startsWith('/') || path === '/' || path.length > 300 || BAD_CHARS.test(path) || path.split('/').includes('..') || path.includes('\\')) errors.push(`paths: "${path.slice(0, 40)}" is not an absolute folder below the root with no ..`)
+ if (!isAbsolutePath(path) || path === '/' || /^[A-Za-z]:\/?$/.test(path) || path.length > 300 || BAD_CHARS.test(path) || hasParentSegment(path) || path.includes('\\')) errors.push(`paths: "${path.slice(0, 40)}" is not an absolute folder below the root with no ..`)
else if (isProtectedPath(path)) errors.push(`paths: "${path.slice(0, 40)}" is the autopilot's or Project Anatole's own folder: steps are never pointed at it`)
}
@@ -344,3 +346,5 @@ export const classAllowed = (envelope: Envelope, toolClass: string): boolean =>
export const AUTOPILOT_DIR = '.claude-flow/console/autopilot'
export const ENVELOPE_FILE = `${AUTOPILOT_DIR}/envelope.json`
export const KILL_FILE = `${AUTOPILOT_DIR}/KILL`
+/** Windows (host-fs) has no delete, so clearing the kill flag there rewrites the file with exactly this; a KILL file with any other content (an empty one included) is a stop. */
+export const KILL_CLEARED = 'cleared'
diff --git a/plugins/ruflo-console/hooks/data/ap-guard.ts b/plugins/ruflo-console/hooks/data/ap-guard.ts
index e7369df71b..a5f9208155 100644
--- a/plugins/ruflo-console/hooks/data/ap-guard.ts
+++ b/plugins/ruflo-console/hooks/data/ap-guard.ts
@@ -4,7 +4,8 @@
* reader and the (optional) permission check. Nothing here widens anything: a task it cannot place is `cls: null` and is parked.
*/
import { missionCostArgv, parseMissionCost } from './mission-cost'
-import { DENY_PATTERNS, KILL_FILE, TOOL_CLASSES, type ToolClass } from './ap-envelope'
+import { writeFlavorReady } from './write-flavor'
+import { DENY_PATTERNS, KILL_CLEARED, KILL_FILE, TOOL_CLASSES, type ToolClass } from './ap-envelope'
import { ESCAPES, HIDDEN, INVISIBLE } from './parse'
import { ANATOLE_STALE_MS } from './anatole'
import type { EffectFact, Preflight, TaskFact } from './ap-loop'
@@ -76,10 +77,18 @@ export function anatoleFact(facts: AnatoleFacts | undefined, nowMs?: number): 'o
return 'on'
}
-/** True when the kill flag exists. A stat that throws means no flag (a missing file is how stat says it). Checked on every tick. */
-export async function killSeen(fs: Pick<ReaderFs, 'stat'>, cwd: string): Promise<boolean> {
+/**
+ * True when the kill flag exists. A stat that throws means no flag (a missing file is how stat says it). Checked on every tick. On host-fs
+ * (Windows, no delete) a flag whose content is exactly KILL_CLEARED is a cleared one, not a stop; any other content, empty included, is a stop.
+ */
+export async function killSeen(fs: Pick<ReaderFs, 'stat'> & { read?: ReaderFs['read'] }, cwd: string): Promise<boolean> {
try {
- return (await fs.stat(`${cwd.replace(/\/+$/, '')}/${KILL_FILE}`)) !== undefined
+ const path = `${cwd.replace(/\/+$/, '')}/${KILL_FILE}`
+
+ if ((await fs.stat(path)) === undefined) return false
+ if ((await writeFlavorReady()) !== 'host-fs' || fs.read === undefined) return true
+
+ return (await fs.read(path).catch(() => '')) !== KILL_CLEARED
} catch {
return false
}
diff --git a/plugins/ruflo-console/hooks/data/ap-journal.ts b/plugins/ruflo-console/hooks/data/ap-journal.ts
index 6442168fba..d72a733dd1 100644
--- a/plugins/ruflo-console/hooks/data/ap-journal.ts
+++ b/plugins/ruflo-console/hooks/data/ap-journal.ts
@@ -9,7 +9,7 @@ import { ESCAPES, HIDDEN, INVISIBLE } from './parse'
import { maskSecrets } from './workflows'
import { AUTOPILOT_DIR } from './ap-envelope'
import { appendArgv } from './append-argv'
-import { posixTouch, type WriteFlavor } from './write-flavor'
+import { hostFsArgv, posixTouch, type WriteFlavor } from './write-flavor'
export const JOURNAL_FILE = `${AUTOPILOT_DIR}/journal.jsonl`
/** A journal over this is read no further (the cap is drawn): the loop then compacts by checkpoint (data/ap-loop.ts `compactState`). */
@@ -181,7 +181,7 @@ export { appendArgv }
* unchanged. POSIX (BSD install has no -D): the guarded touch in write-flavor.ts: makes the folder, refuses a link or a non-regular
* target, creates the file with `set -C` under umask 077 where none is, then `chmod 600`.
*/
-export const touchArgv = (path: string, flavor: WriteFlavor): readonly string[] => (flavor === 'gnu' ? ['install', '-D', '-m', '600', '/dev/null', path] : posixTouch(path))
+export const touchArgv = (path: string, flavor: WriteFlavor): readonly string[] => (flavor === 'host-fs' ? hostFsArgv('touch', path) : flavor === 'gnu' ? ['install', '-D', '-m', '600', '/dev/null', path] : posixTouch(path))
/** How many valid `step.started` lines for this step id the text holds. Two sessions that both picked a task each write one; a step is handed over only when it is exactly one. */
export const startedCount = (text: string, stepId: string): number => parseJournal(text).events.filter(e => e.t === 'step.started' && e.id === stepId).length
diff --git a/plugins/ruflo-console/hooks/data/append-argv.ts b/plugins/ruflo-console/hooks/data/append-argv.ts
index a0b0218572..d4c7476ba6 100644
--- a/plugins/ruflo-console/hooks/data/append-argv.ts
+++ b/plugins/ruflo-console/hooks/data/append-argv.ts
@@ -13,7 +13,7 @@
* over 1 MiB (several blocks; the callers stay far below, BATCH_MAX in activity-io.ts), or a short write(2) that dd completes with a second
* call (the kernel may do that, e.g. on a full disk or a signal). This is not claimed to be atomic beyond that.
*/
-import { posixAppend, type WriteFlavor } from './write-flavor'
+import { hostFsArgv, posixAppend, type WriteFlavor } from './write-flavor'
export const appendArgv = (path: string, flavor: WriteFlavor): readonly string[] =>
- flavor === 'gnu' ? ['dd', `of=${path}`, 'oflag=append', 'conv=notrunc', 'bs=1M', 'iflag=fullblock', 'status=none'] : posixAppend(path)
+ flavor === 'gnu' ? ['dd', `of=${path}`, 'oflag=append', 'conv=notrunc', 'bs=1M', 'iflag=fullblock', 'status=none'] : flavor === 'posix' ? posixAppend(path) : hostFsArgv('append', path)
diff --git a/plugins/ruflo-console/hooks/data/cost-ledger.ts b/plugins/ruflo-console/hooks/data/cost-ledger.ts
index 8101b688ab..53a3d8a553 100644
--- a/plugins/ruflo-console/hooks/data/cost-ledger.ts
+++ b/plugins/ruflo-console/hooks/data/cost-ledger.ts
@@ -6,6 +6,7 @@
*/
import { jsonAfter, type Probe } from './cli'
import { numberOf, plain, recordOf, stringOf } from './parse'
+import { hasParentSegment } from './paths'
import type { State } from '../state'
@@ -34,11 +35,11 @@ const moneyOf = (value: unknown): Money => {
return { ...(usd !== undefined && { usd }), ...(credits !== undefined && { credits }) }
}
-/** An absolute POSIX path of a plugin's install directory: no `..`, no control characters, no shell-looking text. */
+/** An absolute path of a plugin's install directory (POSIX, or drive-lettered on Windows): 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
+ return (/^\/[A-Za-z0-9._@+/ -]{1,300}$/.test(path) || /^[A-Za-z]:[\\/][A-Za-z0-9._@+\\/ -]{1,300}$/.test(path)) && !hasParentSegment(path) ? path : undefined
}
/** The ledger JSON `ledger.mjs --format json --advise` prints. */
diff --git a/plugins/ruflo-console/hooks/data/event-export.ts b/plugins/ruflo-console/hooks/data/event-export.ts
index 189a3c8364..254ef66c9c 100644
--- a/plugins/ruflo-console/hooks/data/event-export.ts
+++ b/plugins/ruflo-console/hooks/data/event-export.ts
@@ -3,7 +3,6 @@
* target is a name under `.claude-flow/console/exports/` or a path inside the project; `..`, a link on the way, a bad extension and an
* existing file are all refused, and the text is washed and capped before it is built. The write itself is a confirm-gated fixed argv.
*/
-import { isAbsolutePath } from './abs-path'
import { isoOf } from './safe'
import type { ActionSpec } from '../actions'
import { levelOf } from './event-severity'
@@ -11,6 +10,7 @@ import { maskLine } from './event-mask'
import type { ConsoleEvent } from './events'
import { refOf } from './events'
import { EXPORT_DIR } from './activity-store'
+import { below, hasParentSegment, isAbsolutePath, isWindowsPath, normalizePath, trimTrailing } from './paths'
import { checkNoLinks, dirOf, newFileArgv, type PathCheck } from './wf-file'
import { writeFlavorReady } from './write-flavor'
import { clockOf, type Concurrency, type LaneView } from './timeline-model'
@@ -28,7 +28,7 @@ export const formatOf = (path: string): Format | null => (/\.md$/.test(path) ? '
/** The absolute path a name or relative path means (a bare file name goes under the exports folder), or why it is refused. Lexical only; see `checkNoLinks` for the disk half. */
export function resolveTarget(input: string, cwd: string, allowed: readonly Format[]): PathCheck {
const raw = input.trim()
- const root = cwd.replace(/\/+$/, '')
+ const root = trimTrailing(cwd)
if (raw === '') return { ok: false, why: 'give a file name ending in .md, .jsonl or .csv' }
if (raw.length > 300) return { ok: false, why: 'a path over 300 characters is refused' }
@@ -48,10 +48,12 @@ export function resolveTarget(input: string, cwd: string, allowed: readonly Form
if (!NAME.test(name) || format === null) return { ok: false, why: 'the file name must be letters, digits, dots, dashes, underscores or spaces, and end in .md, .jsonl or .csv' }
if (!allowed.includes(format)) return { ok: false, why: `this export can be ${allowed.map(item => `.${item}`).join(' or ')}, not .${format}` }
- if (!path.startsWith(`${root}/`)) return { ok: false, why: `outside the project: only paths under ${root} are written` }
+ const inside = below(root, path)
+
+ if (inside === null) return { ok: false, why: `outside the project: only paths under ${root} are written` }
// A markdown file is a command, an agent or a skill when it lands in `.claude/`, and a hook sample in `.git/`: event words are agent output, so those folders are not export targets.
- const hidden = path.slice(root.length + 1).split('/').slice(0, -1).find(part => part.startsWith('.') && part !== '.claude-flow')
+ const hidden = inside.slice(0, -1).find(part => part.startsWith('.') && part !== '.claude-flow')
if (hidden !== undefined) return { ok: false, why: `${hidden} is a hidden folder: exports go to .claude-flow/console/exports/ or a visible folder in the project` }
@@ -129,19 +131,21 @@ export async function exportSpecFor(fs: Pick<ReaderFs, 'stat'>, cwd: string, tar
if (!placed.ok) return placed
- const clear = await checkNoLinks(fs, placed.path, { cwd: cwd.replace(/\/+$/, '') })
+ const clear = await checkNoLinks(fs, placed.path, { cwd: trimTrailing(cwd) })
if (!clear.ok) return clear
const hasDir = (await fs.stat(dirOf(placed.path)).catch(() => undefined)) !== undefined
+ const flavor = await writeFlavorReady()
return {
ok: true,
spec: {
label: `write ${label}`,
args: [],
- argv: newFileArgv(placed.path, hasDir, await writeFlavorReady()),
+ argv: newFileArgv(placed.path, hasDir, flavor),
stdin: content,
+ ...(flavor === 'host-fs' && { write: { kind: hasDir ? 'create-excl' : 'create-dirs', path: placed.path, text: content } as const }),
expect: `a new file at ${placed.path}`,
declared: 'write',
shows: `write ${placed.path} (${bytes(content)} bytes; never overwrites)`,
diff --git a/plugins/ruflo-console/hooks/data/facts.ts b/plugins/ruflo-console/hooks/data/facts.ts
index f4400d7e0e..9badced230 100644
--- a/plugins/ruflo-console/hooks/data/facts.ts
+++ b/plugins/ruflo-console/hooks/data/facts.ts
@@ -4,6 +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 { countOf, ratioOf } from './safe'
export type NeuralStats = { trajectories?: number; patterns?: number; signals?: number; lastAdaptationMs?: number }
@@ -202,7 +203,7 @@ export function parseMarketplaces(text: string | null): Marketplace[] | null {
const location = typeof market?.installLocation === 'string' ? market.installLocation : undefined
const updatedMs = msOf(market?.lastUpdated)
// Only an absolute path with no `..` is followed to the clone's manifest.
- const safeLocation = location !== undefined && location.startsWith('/') && !location.split('/').includes('..') && location.length < 400 ? location : undefined
+ const safeLocation = location !== undefined && isAbsolutePath(location) && !hasParentSegment(location) && location.length < 400 ? location : undefined
return market === null || !/^[A-Za-z0-9._-]{1,80}$/.test(name)
? []
diff --git a/plugins/ruflo-console/hooks/data/mission-cost.ts b/plugins/ruflo-console/hooks/data/mission-cost.ts
index 0ed4159653..bf6f3b0bc6 100644
--- a/plugins/ruflo-console/hooks/data/mission-cost.ts
+++ b/plugins/ruflo-console/hooks/data/mission-cost.ts
@@ -8,16 +8,17 @@ import { budgetAmount, ladderDollars } from '../cost'
import { jsonAfter } from './cli'
import { safeInstallPath } from './cost-ledger'
import { numberOf, plain, recordOf } from './parse'
+import { hasParentSegment, isAbsolutePath, joinPath } from './paths'
export type MissionCost = { usd: number | null; credits: number | null; unpriced: string[]; rows: number; /** The window's start the ledger reports back: it says which mission the reading is for. */ fromMs: number | null }
export type CapLevel = 'none' | 'OK' | 'INFO' | 'WARNING' | 'CRITICAL' | 'HARD_STOP'
export type CapState = { level: CapLevel; percent: number | null }
-/** An absolute POSIX path: no control characters, no `..` segment. It is one argv element, never part of a shell line. */
+/** An absolute path (POSIX, drive-lettered or UNC): no control characters, no `..` segment. It is one argv element, never part of a shell line. */
const safeProject = (value: unknown): string | undefined => {
const path = typeof value === 'string' ? value : ''
- return path.startsWith('/') && path.length <= 500 && !/[\u0000-\u001f\u007f-\u009f]/.test(path) && !path.split('/').includes('..') ? path : undefined
+ return isAbsolutePath(path) && path.length <= 500 && !/[\u0000-\u001f\u007f-\u009f]/.test(path) && !hasParentSegment(path) ? path : undefined
}
/**
@@ -35,7 +36,7 @@ export function missionCostArgv(root: string, fromMs: number, toMs: number | nul
if (base === undefined || where === undefined || from === undefined || to === undefined) return null
if (to !== null && Date.parse(to) < Date.parse(from)) return null
- return ['node', `${base}/scripts/ledger.mjs`, '--format', 'json', '--from', from, ...(to === null ? [] : ['--to', to]), '--project', where]
+ return ['node', joinPath(base, 'scripts', 'ledger.mjs'), '--format', 'json', '--from', from, ...(to === null ? [] : ['--to', to]), '--project', where]
}
/** What `ledger.mjs --format json` printed for the window. A total that is missing is `null` (unknown), not zero. */
diff --git a/plugins/ruflo-console/hooks/data/paths.ts b/plugins/ruflo-console/hooks/data/paths.ts
new file mode 100644
index 0000000000..5ff818d95b
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/paths.ts
@@ -0,0 +1,81 @@
+/**
+ * Path helpers that are pure string functions: hook modules run without Node's `path`. A path is absolute when it is POSIX (`/x`),
+ * drive-lettered (`C:\x`, `c:/x`) or a UNC share (`\\srv\share`); `C:x` and `.\x` are relative. A POSIX path is handled exactly as a
+ * plain `/` string always was: only a drive-lettered or UNC path takes the Windows rules (either separator, case-insensitive compare).
+ */
+
+const DRIVE = /^[A-Za-z]:[\\/]/
+const UNC = /^\\\\[^\\/]/
+
+/** True for a drive-lettered or UNC path (the Windows forms). */
+export const isWindowsPath = (p: string): boolean => DRIVE.test(p) || UNC.test(p)
+
+/** True for a POSIX, drive-letter or UNC path. */
+export const isAbsolutePath = (p: string): boolean => p.startsWith('/') || isWindowsPath(p)
+
+/** `p` without trailing separators (both kinds for a Windows path, `/` only for a POSIX one). */
+export const trimTrailing = (p: string): string => p.replace(isWindowsPath(p) ? /[\\/]+$/ : /\/+$/, '')
+
+/** Joins onto `base` using the base's own separator (`\` for a Windows base that uses it), without doubling a trailing separator. */
+export function joinPath(base: string, ...parts: string[]): string {
+ const sep = isWindowsPath(base) && base.includes('\\') ? '\\' : '/'
+ const rest = parts.map(part => (sep === '\\' ? part.replace(/\//g, '\\') : part)).filter(part => part !== '')
+
+ return [trimTrailing(base), ...rest].join(sep)
+}
+
+/** 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)) {
+ const norm = (p: string): string => p.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
+
+ return norm(a) === norm(b)
+ }
+
+ return a === b
+}
+
+/** True when the path has a `..` segment (either separator for a Windows path). Callers refuse it themselves. */
+export const hasParentSegment = (p: string): boolean => (isWindowsPath(p) ? p.split(/[\\/]/) : p.split('/')).includes('..')
+
+/**
+ * The path with empty and `.` segments and a trailing separator dropped. A POSIX path comes back as `/a/b`; a Windows path keeps the
+ * separators it was written with (`C:\a\b`, `C:\a/b`, `\\srv\share\a`), so a base followed by `/name` stays recognisable.
+ */
+export function normalizePath(p: string): string {
+ if (!isWindowsPath(p)) return `/${p.split('/').filter(part => part !== '' && part !== '.').join('/')}`
+
+ const unc = UNC.test(p)
+ const body = (unc ? p.slice(2) : p).replace(/([\\/])[\\/]+/g, '$1').replace(/[\\/]\.(?=[\\/]|$)/g, '').replace(/[\\/]+$/, '')
+
+ return `${unc ? '\\\\' : ''}${body}`
+}
+
+/** The segments of `path` strictly below `root`, or null when it is not inside it. Windows paths compare ignoring case and separator style. */
+export function below(root: string, path: string): string[] | null {
+ if (isWindowsPath(root) || isWindowsPath(path)) {
+ const r = root.replace(/\\/g, '/').replace(/\/+$/, '')
+ const p = path.replace(/\\/g, '/')
+
+ return r !== '' && p.toLowerCase().startsWith(`${r.toLowerCase()}/`) ? p.slice(r.length + 1).split('/').filter(part => part !== '') : null
+ }
+
+ const r = root.replace(/\/+$/, '')
+
+ return r !== '' && path.startsWith(`${r}/`) ? path.slice(r.length + 1).split('/') : null
+}
+
+/** The user's home directory: HOME (preferred), else USERPROFILE, else HOMEDRIVE+HOMEPATH, else null. Empty values are treated as unset. */
+export function homeOf(get: (k: string) => string | undefined): string | null {
+ const home = get('HOME')
+ if (home) return home
+
+ const userProfile = get('USERPROFILE')
+ if (userProfile) return userProfile
+
+ const drive = get('HOMEDRIVE')
+ const path = get('HOMEPATH')
+ if (drive && path) return drive + path
+
+ return null
+}
diff --git a/plugins/ruflo-console/hooks/data/plugin-catalog.ts b/plugins/ruflo-console/hooks/data/plugin-catalog.ts
index fdc4f5a91b..5454ae1fc3 100644
--- a/plugins/ruflo-console/hooks/data/plugin-catalog.ts
+++ b/plugins/ruflo-console/hooks/data/plugin-catalog.ts
@@ -7,6 +7,7 @@
*/
import type { ReaderFs } from './files'
import { plain } from './parse'
+import { hasParentSegment, isAbsolutePath, joinPath } from './paths'
export type CatalogPlugin = {
name: string
@@ -99,7 +100,7 @@ async function pluginOf(fs: ReaderFs, location: string, entry: Record<string, un
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
- const raw = await fs.read(`${location}/.claude-plugin/marketplace.json`).catch(() => null)
+ const raw = await fs.read(joinPath(location, '.claude-plugin', 'marketplace.json')).catch(() => null)
let list: unknown[] = []
try {
diff --git a/plugins/ruflo-console/hooks/data/wf-drill-io.ts b/plugins/ruflo-console/hooks/data/wf-drill-io.ts
index af45fbf240..80f4df3709 100644
--- a/plugins/ruflo-console/hooks/data/wf-drill-io.ts
+++ b/plugins/ruflo-console/hooks/data/wf-drill-io.ts
@@ -12,6 +12,7 @@
*/
import { readBounded, type ReadCache } from './files'
import { filterGuarded } from './git-filters'
+import { below, hasParentSegment, isAbsolutePath, samePath, trimTrailing } from './paths'
import { cleanLine, cleanPath, journalResult, type Capped, type Parsed } from './wf-activity'
import { activityOf, parsedStats, PARSED_BUDGET_CHARS, resetStore } from './wf-incr-store'
import { TAIL_BYTES, TRANSCRIPT_CAP, type WorkflowFs } from './workflows-read'
@@ -54,11 +55,11 @@ export function isRunFile(path: string, configDir: string | null): boolean {
/** True for an absolute path inside the project's working directory (where Claude Code puts an agent's worktree), with no `..` part. */
export function isProjectDir(path: string, cwd: string): boolean {
- if (!path.startsWith('/') || path.includes('\0') || path.includes('\n') || path.split('/').includes('..')) return false
+ if (!isAbsolutePath(path) || path.includes('\0') || path.includes('\n') || hasParentSegment(path)) return false
- const root = cwd.replace(/\/+$/, '')
+ const root = trimTrailing(cwd)
- return root !== '' && (path === root || path.startsWith(`${root}/`))
+ return root !== '' && (samePath(path, root) || below(root, path) !== null)
}
export type Note = { phase: 'loading' | 'ok' | 'none' | 'failed'; why?: string }
diff --git a/plugins/ruflo-console/hooks/data/wf-export.ts b/plugins/ruflo-console/hooks/data/wf-export.ts
index 74fa6e8f9a..fa61224857 100644
--- a/plugins/ruflo-console/hooks/data/wf-export.ts
+++ b/plugins/ruflo-console/hooks/data/wf-export.ts
@@ -88,6 +88,7 @@ export function exportSpec(path: string, markdown: string, label: string, hasDir
args: [],
argv: newFileArgv(path, hasDir, flavor),
stdin: markdown,
+ ...(flavor === 'host-fs' && { write: { kind: hasDir ? 'create-excl' : 'create-dirs', path, text: markdown } as const }),
expect: `a new file at ${path}`,
declared: 'write',
shows: `write ${path} (${BYTES(markdown)} bytes; never overwrites)`,
diff --git a/plugins/ruflo-console/hooks/data/wf-file.ts b/plugins/ruflo-console/hooks/data/wf-file.ts
index af40a8b997..72d5b78704 100644
--- a/plugins/ruflo-console/hooks/data/wf-file.ts
+++ b/plugins/ruflo-console/hooks/data/wf-file.ts
@@ -9,9 +9,9 @@
* A path is accepted only if, after normalising, it sits under an allowed root (the project, or the scratchpad where one is known)
* with no `..`, no link on the way down to it and, for a summary, no file already there to overwrite.
*/
-import { isAbsolutePath } from './abs-path'
import type { ReaderFs } from './files'
-import { posixCopyExclusive, posixCreateExclusive, posixCreateExclusiveWithDirs, posixReplace, posixReplaceWithDirs, type WriteFlavor } from './write-flavor'
+import { below, hasParentSegment, isAbsolutePath, isWindowsPath, joinPath, normalizePath, trimTrailing } from './paths'
+import { hostFsArgv, posixCopyExclusive, posixCreateExclusive, posixCreateExclusiveWithDirs, posixReplace, posixReplaceWithDirs, type WriteFlavor } from './write-flavor'
export type Roots = { cwd: string; /** The session scratchpad, when the host tells the console where it is. */ scratch?: string | null }
export type PathCheck = { ok: true; path: string } | { ok: false; why: string }
@@ -22,7 +22,7 @@ export const EXPORT_DIR = '.claude-flow/console/exports'
const NAME = /^[A-Za-z0-9][A-Za-z0-9._ -]{0,99}\.md$/
const MAX_PATH = 300
-const trimRoot = (root: string): string => root.replace(/\/+$/, '')
+const trimRoot = trimTrailing
/** The normalised absolute path of a markdown file the person named, or why it cannot be written. Lexical only: see `checkNoLinks` for the disk half. */
export function resolveExportPath(input: string, roots: Roots): PathCheck {
@@ -33,7 +33,7 @@ export function resolveExportPath(input: string, roots: Roots): PathCheck {
// eslint-disable-next-line no-control-regex
if (/[\u0000-\u001f\u007f-\u009f\\]/.test(raw)) return { ok: false, why: 'a path with control characters or a backslash is refused' }
if (raw.startsWith('~')) return { ok: false, why: 'write the path out: ~ is not expanded here' }
- if (raw.split('/').includes('..')) return { ok: false, why: 'a path with .. is refused: name the file inside the project or the scratchpad' }
+ if (hasParentSegment(raw)) return { ok: false, why: 'a path with .. is refused: name the file inside the project or the scratchpad' }
const base = trimRoot(roots.cwd)
@@ -58,15 +58,15 @@ export function resolveExportPath(input: string, roots: Roots): PathCheck {
* no file is already there. A path that does not exist yet is fine; `stat` refusing is "missing".
*/
export async function checkNoLinks(fs: Pick<ReaderFs, 'stat'>, path: string, roots: Roots, options: { allowExisting?: boolean } = {}): Promise<PathCheck> {
- const root = [roots.cwd, roots.scratch ?? ''].map(trimRoot).find(entry => entry !== '' && path.startsWith(`${entry}/`))
+ const root = [roots.cwd, roots.scratch ?? ''].map(trimRoot).find(entry => entry !== '' && below(entry, path) !== null)
if (root === undefined) return { ok: false, why: 'outside the allowed folders' }
- const parts = path.slice(root.length + 1).split('/')
+ const parts = below(root, path) ?? []
let at = root
for (const [index, part] of parts.entries()) {
- at = `${at}/${part}`
+ at = joinPath(at, part)
const stat = await fs.stat(at).catch(() => undefined)
@@ -84,12 +84,14 @@ export async function checkNoLinks(fs: Pick<ReaderFs, 'stat'>, path: string, roo
* `install -D` (makes the folders) where it is not. POSIX: refuses a link or a non-regular target, then `set -C` makes the shell open the
* file O_CREAT|O_EXCL, so an existing file fails the write; the folders are made first where they are missing (write-flavor.ts).
*
+ * Windows (host-fs): the host API has no O_EXCL, so the create is exists-then-write (write-via.ts): a file created between the two is overwritten.
+ *
* Known gap, GNU only, unchanged here: `install -D` replaces its target. If the folder was missing at the check and both the folder and the
* file appear before the write runs, that file is replaced. `checkNoLinks` refuses a file that is there at the check, so this takes a second
* writer creating that exact folder and file inside the window.
*/
export const newFileArgv = (path: string, hasDir: boolean, flavor: WriteFlavor): readonly string[] =>
- flavor === 'gnu' ? (hasDir ? ['dd', `of=${path}`, 'conv=excl', 'status=none'] : INSTALL(path)) : hasDir ? posixCreateExclusive(path) : posixCreateExclusiveWithDirs(path)
+ flavor === 'host-fs' ? hostFsArgv('create', path) : flavor === 'gnu' ? (hasDir ? ['dd', `of=${path}`, 'conv=excl', 'status=none'] : INSTALL(path)) : hasDir ? posixCreateExclusive(path) : posixCreateExclusiveWithDirs(path)
/**
* The page's own state file, content on stdin: replaced in place where the folder is there, created (with its folders) where it is not. A
@@ -97,14 +99,14 @@ export const newFileArgv = (path: string, hasDir: boolean, flavor: WriteFlavor):
* write-flavor.ts (a link or a non-regular target is refused; umask 022).
*/
export const replaceFileArgv = (path: string, hasDir: boolean, flavor: WriteFlavor): readonly string[] =>
- flavor === 'gnu' ? (hasDir ? ['dd', `of=${path}`, 'status=none'] : INSTALL(path)) : hasDir ? posixReplace(path) : posixReplaceWithDirs(path)
+ flavor === 'host-fs' ? hostFsArgv('replace', path) : flavor === 'gnu' ? (hasDir ? ['dd', `of=${path}`, 'status=none'] : INSTALL(path)) : hasDir ? posixReplace(path) : posixReplaceWithDirs(path)
/**
* Copies a regular file to a new name, never replacing one (the journal's archive). GNU: `cp --no-clobber`, unchanged. POSIX: BSD cp has no
* `--no-clobber`, so the guarded copy in write-flavor.ts (an O_EXCL create of the target, the source refused if a link or not regular).
*/
export const copyExclusiveArgv = (source: string, path: string, flavor: WriteFlavor): readonly string[] =>
- flavor === 'gnu' ? ['cp', '--no-clobber', '--', source, path] : posixCopyExclusive(source, path)
+ flavor === 'host-fs' ? hostFsArgv('copy', path) : flavor === 'gnu' ? ['cp', '--no-clobber', '--', source, path] : posixCopyExclusive(source, path)
const INSTALL = (path: string): readonly string[] => ['install', '-D', '-m', '0644', '/dev/stdin', '--', path]
diff --git a/plugins/ruflo-console/hooks/data/wf-worktrees.ts b/plugins/ruflo-console/hooks/data/wf-worktrees.ts
index df066ca1f7..b79e5c16db 100644
--- a/plugins/ruflo-console/hooks/data/wf-worktrees.ts
+++ b/plugins/ruflo-console/hooks/data/wf-worktrees.ts
@@ -14,6 +14,8 @@
*/
import { filterGuarded } from './git-filters'
import { plain } from './parse'
+import { flavorOfPlatform } from './write-flavor'
+import { hasParentSegment, isAbsolutePath } from './paths'
import { cleanText } from './wf-clean'
import type { WfRun } from './workflows'
@@ -65,7 +67,7 @@ export const PROCS_ARGV: readonly string[] = ['/usr/bin/find', '/proc', '-maxdep
const CONTROL = /[\u0000-\u001f\u007f-\u009f]/
/** An absolute path with no control character and no `..` part: the only kind that reaches a command. */
-export const isSafePath = (path: string): boolean => path.length > 1 && path.length <= 1024 && path.startsWith('/') && !CONTROL.test(path) && !path.split('/').includes('..')
+export const isSafePath = (path: string): boolean => path.length > 1 && path.length <= 1024 && isAbsolutePath(path) && !CONTROL.test(path) && !hasParentSegment(path)
const SECRETISH_NAME = /^(?:\.env(?:\..+)?|\.npmrc|\.netrc|\.pgpass|\.secrets?|secrets?(?:\..+)?|credentials(?:\..+)?|id_(?:rsa|dsa|ecdsa|ed25519)|.+\.(?:pem|key|p12|pfx|jks|keystore|secret))\/?$/i
@@ -234,7 +236,10 @@ export async function readWorktrees(io: WtIo, input: { cwd: string; nowMs: numbe
}
/** The process check for these paths; never throws: a probe that fails is a blind check. */
-export async function checkProcs(io: WtIo, paths: readonly string[], nowMs: number): Promise<ProcCheck> {
+export async function checkProcs(io: WtIo, paths: readonly string[], nowMs: number, platform?: unknown): Promise<ProcCheck> {
+ // /proc is Linux-only: on Windows (no find, no /proc) the answer is "not available" and nothing is spawned. macOS got "did not answer" from the failed spawn; it now gets this.
+ if ((platform === undefined ? flavorOfPlatform() : flavorOfPlatform(platform)) !== 'gnu') return { atMs: nowMs, ok: false, seen: 0, counts: new Map(), paths: new Set(paths), why: 'the live-process check is not available on this system' }
+
const result = await io.run(PROCS_ARGV, 30_000).catch(() => null)
if (result === null || result.stdout === '') return { atMs: nowMs, ok: false, seen: 0, counts: new Map(), paths: new Set(paths), why: 'the process listing did not answer' }
diff --git a/plugins/ruflo-console/hooks/data/write-flavor.ts b/plugins/ruflo-console/hooks/data/write-flavor.ts
index 1cb76a91a8..cb86c267aa 100644
--- a/plugins/ruflo-console/hooks/data/write-flavor.ts
+++ b/plugins/ruflo-console/hooks/data/write-flavor.ts
@@ -13,18 +13,26 @@
* controller exists). Every write path awaits `writeFlavorReady()` before it builds an argv, and the builders take the flavor as a required
* argument, so no write can be built with a guessed flavor. Detection has its own deadline (DETECT_DEADLINE_MS), independent of the host's
* timeout, so a runner that never settles cannot hold a write (the kill switch flag included) forever. Where `uname` fails, answers
- * nothing or misses the deadline, the engine's own `process.platform` decides (darwin and the BSDs: posix; anything else: gnu), because
- * the GNU argv is known to fail on macOS. A leaf: no imports.
+ * nothing or misses the deadline, the engine's own `process.platform` decides (darwin and the BSDs: posix; Windows: host-fs; anything
+ * else: gnu), because the GNU argv is known to fail on macOS.
+ *
+ * Windows is the third flavor, `host-fs`: Claude Code's process environment there has none of uname, dd, sh, install, mkdir or cp, so no
+ * argv can write. The writes go through the host's own file API instead (`$.fs.write` makes the folders; `$.fs.read`, `$.fs.exists` and
+ * `$.fs.stat` check what is there); see write-via.ts. On a Windows engine no `uname` is run at all (`startWriteFlavor`). A leaf but for paths.ts.
*/
-export type WriteFlavor = 'gnu' | 'posix'
+import { isWindowsPath } from './paths'
+
+export type WriteFlavor = 'gnu' | 'posix' | 'host-fs'
let detection: Promise<WriteFlavor> | null = null
/** How long detection may take before the platform fallback answers. */
export const DETECT_DEADLINE_MS = 3_000
-/** The engine's own platform (`process.platform` where the runtime exposes it), to a flavor: darwin and *bsd are posix, the rest gnu. */
+/** The engine's own platform (`process.platform` where the runtime exposes it), to a flavor: win32 is host-fs, darwin and *bsd are posix, the rest gnu. */
export function flavorOfPlatform(platform: unknown = (globalThis as { process?: { platform?: unknown } }).process?.platform): WriteFlavor {
+ if (platform === 'win32') return 'host-fs'
+
return typeof platform === 'string' && (platform === 'darwin' || platform.endsWith('bsd')) ? 'posix' : 'gnu'
}
@@ -53,6 +61,21 @@ export function startWriteFlavorDetection(run: Run, deadlineMs: number = DETECT_
return detection
}
+/**
+ * What the session starts: on a Windows engine the flavor is host-fs and no command is run; anywhere else the one `uname` detection.
+ * `platform` is the engine's own (a test passes one). Where the runtime does not expose it, a session whose working directory is a
+ * Windows path (a drive letter or a share) is a Windows engine all the same.
+ */
+export function startWriteFlavor(run: Run, platform: unknown = (globalThis as { process?: { platform?: unknown } }).process?.platform, cwd?: string): Promise<WriteFlavor> {
+ if (flavorOfPlatform(platform) === 'host-fs' || (cwd !== undefined && isWindowsPath(cwd))) {
+ detection = Promise.resolve('host-fs')
+
+ return detection
+ }
+
+ return startWriteFlavorDetection(run, DETECT_DEADLINE_MS, () => flavorOfPlatform(platform))
+}
+
/** The flavor every write awaits before it builds its argv: the detection's answer, or `gnu` where none was started (a test host, a build without a session). */
export const writeFlavorReady = (): Promise<WriteFlavor> => detection ?? Promise.resolve('gnu')
@@ -61,7 +84,7 @@ export const setWriteFlavor = (flavor: WriteFlavor | null): void => {
detection = flavor === null ? null : Promise.resolve(flavor)
}
-/** `uname -s` output to a flavor: Linux keeps the GNU argv; every other kernel (Darwin, the BSDs) takes the sh scripts. */
+/** `uname -s` output to a flavor: Linux keeps the GNU argv; every other kernel (Darwin, the BSDs) takes the sh scripts. A Windows engine never asks (`startWriteFlavor`). */
export const flavorOfKernel = (kernel: string): WriteFlavor => (kernel.trim() === 'Linux' ? 'gnu' : 'posix')
/** Refuses a target that is a link (dangling or not) or exists and is not a regular file. */
@@ -103,3 +126,9 @@ export const posixReplaceWithDirs = (path: string): readonly string[] => posix('
export const posixTouch = (path: string): readonly string[] => posix('touch', path)
/** Copies the regular file `source` to a new file `path`; fails if anything is at `path` (BSD cp has no --no-clobber; `cp -n` exits 0 when it skips). */
export const posixCopyExclusive = (source: string, path: string): readonly string[] => posix('copyExclusive', path, source)
+
+/**
+ * What an argv builder answers for host-fs: not a command. Every write of that flavor goes through `writeVia` (write-via.ts), which never
+ * runs it; a caller that did run it would get "cannot start" for a program that does not exist, never a guessed GNU or sh write.
+ */
+export const hostFsArgv = (op: string, path: string): readonly string[] => ['ruflo-console:host-fs', op, path]
diff --git a/plugins/ruflo-console/hooks/data/write-via.ts b/plugins/ruflo-console/hooks/data/write-via.ts
new file mode 100644
index 0000000000..849d8fb9a9
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/write-via.ts
@@ -0,0 +1,145 @@
+/**
+ * The one place the console's disk writes are carried out, whatever the machine has. `writeVia(flavor, host, op)` runs one of the
+ * enumerated operations: on Linux (`gnu`) and macOS/BSD (`posix`) it is exactly the fixed argv it always was (append-argv.ts, wf-file.ts,
+ * write-flavor.ts), through `host.run` with the content on stdin; on Windows (`host-fs`), where none of dd, sh, install, mkdir or cp is on
+ * the engine's PATH, it goes through the host's file API: `fs.read`, `fs.write` and `fs.exists`.
+ *
+ * What `host-fs` does, and where it differs:
+ * - The host's `fs.write` makes the folders and replaces the whole file, so a missing folder needs nothing ('create-dirs'), and an
+ * append is read-then-write of the whole text. Both the read and the write are refused past 4 MiB, so an append whose result would pass
+ * that is refused with a reason rather than cut; the callers that grow a file (the Events and Timeline files, the autopilot journal)
+ * rotate long before (2 MiB, 1 MiB, 1.5 MiB) exactly where they did with dd.
+ * - An append is not atomic: two consoles appending to one file at once can lose a batch (dd's O_APPEND kept both).
+ * - A target that is a link, or exists and is not a regular file (a folder), is refused as the sh scripts refuse it (exit 73).
+ * - An exclusive create or copy refuses a path where anything exists; it says so in the same words the pre-write check uses.
+ * - No file mode is set (Windows has none to set).
+ * - The host API has no O_EXCL. 'create-excl', 'create-dirs' and 'copy-no-clobber' are check-then-write: a file that appears between the
+ * `exists` check and the `fs.write` is overwritten (GNU `dd conv=excl` and the POSIX `set -C` fail instead). Callers run `checkNoLinks`
+ * first, so this takes a second writer creating that exact path inside the window.
+ * - Windows has no delete here: callers that removed a file (the autopilot KILL flag) rewrite it with a marker instead.
+ * Never rejects on host-fs: a refusal is `{ exitCode: <non-zero>, stderr: <the reason> }`, like a command that exited non-zero.
+ */
+import { appendArgv } from './append-argv'
+import { touchArgv } from './ap-journal'
+import type { ReaderFs } from './files'
+import { copyExclusiveArgv, newFileArgv, replaceFileArgv } from './wf-file'
+import type { WriteFlavor } from './write-flavor'
+
+/** The host file API refuses to read or write more than this. */
+export const HOST_FS_MAX = 4 * 1024 * 1024
+
+/** The host's fs as a write needs it: the reads of `ReaderFs`, and the write and exists calls (a test host may leave them out). */
+export type WriterFs = ReaderFs & { write?: (path: string, text: string) => Promise<void>; exists?: (path: string) => Promise<boolean> }
+
+export type WriteResult = { exitCode: number; stdout: string; stderr: string }
+
+export type WriteHost = {
+ fs: WriterFs
+ run: (argv: readonly string[], timeoutMs: number, stdin?: string) => Promise<WriteResult>
+}
+
+export type WriteOp = {
+ /**
+ * append: add `text` to the file (created if none). create-excl: a new file, `text` in it, failing if anything is at the path, in a
+ * folder that is there. create-dirs: the same, the folders made first. replace: the file becomes `text` (`hasDir`: its folder exists).
+ * touch: an empty file where none is. copy-no-clobber: the file `from` copied to a new `path`.
+ */
+ kind: 'append' | 'create-excl' | 'create-dirs' | 'replace' | 'touch' | 'copy-no-clobber'
+ path: string
+ text?: string
+ from?: string
+ hasDir?: boolean
+ timeoutMs?: number
+}
+
+export const ALREADY_EXISTS = 'already exists: the console does not overwrite a file; pick another name'
+
+const bytesOf = (text: string): number => (typeof TextEncoder === 'function' ? new TextEncoder().encode(text).length : text.length * 3)
+const refuse = (stderr: string, exitCode = 1): WriteResult => ({ exitCode, stdout: '', stderr })
+
+/** The argv form of an op, for `gnu` and `posix` (the stdin is the op's text). */
+export function argvOf(flavor: Exclude<WriteFlavor, 'host-fs'>, op: WriteOp): readonly string[] {
+ switch (op.kind) {
+ case 'append':
+ return appendArgv(op.path, flavor)
+ case 'create-excl':
+ return newFileArgv(op.path, true, flavor)
+ case 'create-dirs':
+ return newFileArgv(op.path, false, flavor)
+ case 'replace':
+ return replaceFileArgv(op.path, op.hasDir ?? true, flavor)
+ case 'touch':
+ return touchArgv(op.path, flavor)
+ case 'copy-no-clobber':
+ return copyExclusiveArgv(op.from ?? '', op.path, flavor)
+ }
+}
+
+/** 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)
+
+ try {
+ return await viaHostFs(host.fs, op)
+ } catch (error) {
+ return refuse((error instanceof Error ? error.message : 'the write was refused').slice(0, 160))
+ }
+}
+
+async function viaHostFs(fs: WriterFs, op: WriteOp): Promise<WriteResult> {
+ const write = fs.write
+
+ if (write === undefined) return refuse('the host file API cannot write here')
+
+ const exists = async (path: string): Promise<boolean> => (fs.exists !== undefined ? fs.exists(path) : (await fs.stat(path).catch(() => undefined)) !== undefined)
+ const put = (path: string, text: string): Promise<void> => write(path, text)
+
+ // The same refusal the sh scripts make: a link, or something that is not a regular file (a folder), is never written through.
+ const target = await fs.stat(op.path).catch(() => undefined)
+
+ if (target !== undefined && (target.isLink === true || (target.kind !== undefined && target.kind !== 'file'))) {
+ return refuse('refused: the target is a link or not a regular file', 73)
+ }
+
+ const text = op.text ?? ''
+
+ switch (op.kind) {
+ case 'append': {
+ const before = target === undefined && !(await exists(op.path)) ? '' : await fs.read(op.path)
+
+ if (bytesOf(before) + bytesOf(text) > HOST_FS_MAX) return refuse('refused: the file would pass 4 MiB, which the host file API cannot write')
+ await put(op.path, before + text)
+
+ return refuse('', 0)
+ }
+ case 'create-excl':
+ case 'create-dirs': {
+ if (target !== undefined || (await exists(op.path))) return refuse(ALREADY_EXISTS)
+ if (bytesOf(text) > HOST_FS_MAX) return refuse('refused: the file would pass 4 MiB, which the host file API cannot write')
+ await put(op.path, text)
+
+ return refuse('', 0)
+ }
+ case 'replace': {
+ if (bytesOf(text) > HOST_FS_MAX) return refuse('refused: the file would pass 4 MiB, which the host file API cannot write')
+ await put(op.path, text)
+
+ return refuse('', 0)
+ }
+ case 'touch': {
+ if (target === undefined && !(await exists(op.path))) await put(op.path, '')
+
+ return refuse('', 0)
+ }
+ case 'copy-no-clobber': {
+ const from = op.from ?? ''
+ const source = await fs.stat(from).catch(() => undefined)
+
+ if (source === undefined || source.isLink === true || (source.kind !== undefined && source.kind !== 'file')) return refuse('refused: the source is a link or not a regular file', 73)
+ if (target !== undefined || (await exists(op.path))) return refuse(ALREADY_EXISTS)
+ await put(op.path, await fs.read(from))
+
+ return refuse('', 0)
+ }
+ }
+}
diff --git a/plugins/ruflo-console/hooks/dispatch.ts b/plugins/ruflo-console/hooks/dispatch.ts
index 806961e8a3..023452570f 100644
--- a/plugins/ruflo-console/hooks/dispatch.ts
+++ b/plugins/ruflo-console/hooks/dispatch.ts
@@ -46,6 +46,17 @@ async function open(control: Controller, state: State, label: string): Promise<{
const DUMP_WAIT_MS = 8_000
+/** Waits for `work` for at most `ms`; the timer is cleared as soon as either side settles, so a fast probe leaves nothing pending. */
+export async function settleWithin(work: Promise<unknown>, ms: number): Promise<void> {
+ let timer: ReturnType<typeof setTimeout> | undefined
+
+ try {
+ await Promise.race([work, new Promise(resolve => { timer = setTimeout(resolve, ms) })])
+ } finally {
+ clearTimeout(timer)
+ }
+}
+
/** The catalog this plugin ships (read once per session), or the built-in mod list when it is missing or another contract. */
async function loadCatalog(control: Controller): Promise<Catalog> {
control.catalog ??= control.host.fs
@@ -66,7 +77,7 @@ async function dumpOf(control: Controller, state: State, view: State['view']): P
try {
await control.refresh()
- await Promise.race([control.probe(true), new Promise(resolve => setTimeout(resolve, DUMP_WAIT_MS))])
+ await settleWithin(control.probe(true), DUMP_WAIT_MS)
// Self-Evolution draws from its own file read, which opening the view starts: a dump waits for it too.
if (view === 'evolve') await loadEvolve(state, control.host)
if (view === 'workflows') await refreshWorkflows(state, control.host, true)
diff --git a/plugins/ruflo-console/hooks/host.ts b/plugins/ruflo-console/hooks/host.ts
index a9219739a6..8f27f2a1b2 100644
--- a/plugins/ruflo-console/hooks/host.ts
+++ b/plugins/ruflo-console/hooks/host.ts
@@ -1,6 +1,6 @@
import type { CommandSpec, HookStream, PaneOpenArgs, ProcessRunResult, ProcessSpawnChunk, ProcessSpawnResult, Timer, UiBlitArgs } from 'claude-code'
-import type { ReaderFs } from './data/files'
+import type { WriterFs } from './data/write-via'
import type { ToastLevel } from './toast-policy'
import type { RufloRoute, RufloSnapshot } from '../types'
@@ -13,7 +13,7 @@ export type OpenResult = { isPlaced: boolean; reason?: string } | void
* removed the affordance, a policy mod said no): every caller catches, and a refusal is a missing fact, never a crash.
*/
export type Host = {
- fs: ReaderFs
+ fs: WriterFs
every: (ms: number, fn: () => void) => Timer
after: (ms: number, fn: () => void) => Timer
storeGet: (key: string) => Promise<unknown>
diff --git a/plugins/ruflo-console/hooks/register.ts b/plugins/ruflo-console/hooks/register.ts
index a91838642c..c20a4ac380 100644
--- a/plugins/ruflo-console/hooks/register.ts
+++ b/plugins/ruflo-console/hooks/register.ts
@@ -1,11 +1,11 @@
import type { EngineInterface, PluginOptions, Register } from 'claude-code'
import { tolerantPress } from './press-guard'
import { ANSWER_KEYS } from './views/attention'
-import { rootedPath } from './data/abs-path'
import { createController, type Controller } from './controller'
import { startSessions } from './sessions'
import { record } from './data/events'
import { plain } from './data/parse'
+import { homeOf, isAbsolutePath, joinPath } from './data/paths'
import { dispatch } from './dispatch'
import { markPicture } from './gfx/pictures'
import type { Host } from './host'
@@ -14,15 +14,13 @@ import { newState, PANE_ID, restore, restoreSessions, storeKeyOf, termStoreKeyOf
import { BAR_KEY, barView } from './views/bar'
import { addNotice, dismissNotices } from './notices'
import { setBootChecks } from './boot-checks'
-import { startWriteFlavorDetection } from './data/write-flavor'
+import { startWriteFlavor } from './data/write-flavor'
import { buildOf, isOurCheckout, setBuild } from './build'
-import { runUpdateCheck } from './update-flow'
import { announceModelTools, parseControlEnv, serveModelTools } from './model-tools'
import { loadAiPrefs, setControlCap } from './settings'
-import { hydrateWhatsNew } from './whatsnew'
-import { prefsFromStore, recordToast, saveToastPrefs, TOASTS_KEY } from './toasts'
+import { loadAtStart } from './startup-loads'
+import { recordToast } from './toasts'
import { contextSection, onPromptSubmit, onTurnComplete } from './mission-claude'
-import { parseMode, RECHECK_EVERY_MS, UPDATES_KEY } from './updates'
import { selfCheckResults } from './self-check'
import { kitForSurface, type Kit } from './views/common'
import { createToaster, type Digest, type ToastLevel, type ToastPrefs } from './toast-policy'
@@ -40,7 +38,7 @@ const RUFLO_TOOL = /^mcp__(claude-flow|ruflo|plugin_ruflo[\w-]*)__/
let isResettingScroll = false
function hostOf($: EngineInterface, cwd: string, toasts: { prefs: () => ToastPrefs; record: (digest: Digest) => void }): Host {
- const rooted = (path: string) => rootedPath(cwd, path)
+ const rooted = (path: string) => (isAbsolutePath(path) ? path : joinPath(cwd, path))
const quietly = (fn: () => unknown) => {
try {
const result = fn()
@@ -63,7 +61,14 @@ function hostOf($: EngineInterface, cwd: string, toasts: { prefs: () => ToastPre
})
return {
- fs: { read: async path => $.fs.read(rooted(path)), stat: async path => $.fs.stat(rooted(path)), list: async path => $.fs.list(rooted(path)) },
+ fs: {
+ read: async path => $.fs.read(rooted(path)),
+ stat: async path => $.fs.stat(rooted(path)),
+ list: async path => $.fs.list(rooted(path)),
+ // The Windows write flavor (write-via.ts): the host's own file API, since no dd, sh, install, mkdir or cp is on the engine's PATH there.
+ write: async (path, text) => $.fs.write(rooted(path), text),
+ exists: async path => $.fs.exists(rooted(path)),
+ },
every: (ms, fn) => $.clock.every(ms, fn),
after: (ms, fn) => $.clock.after(ms, fn),
storeGet: async key => $.store.get(key),
@@ -109,7 +114,17 @@ function hostOf($: EngineInterface, cwd: string, toasts: { prefs: () => ToastPre
return { tools: names.length, servers: [...new Set(names)].sort() }
},
settings: async () => $.settings.read(),
- home: async () => $.env.get('HOME'),
+ home: async () => {
+ const [home, userProfile, homeDrive, homePath] = await Promise.all([
+ $.env.get('HOME'),
+ $.env.get('USERPROFILE'),
+ $.env.get('HOMEDRIVE'),
+ $.env.get('HOMEPATH'),
+ ])
+ const envVars: { [key: string]: string | undefined } = { HOME: home, USERPROFILE: userProfile, HOMEDRIVE: homeDrive, HOMEPATH: homePath }
+
+ return homeOf(k => envVars[k])
+ },
configDir: async () => $.env.get('CLAUDE_CONFIG_DIR'),
pluginRoot: $.plugin.root,
// `$.ruflo` exists only where ruflo-mods is seated; validate refuses feature-detecting a noun, so these are
@@ -167,10 +182,10 @@ export const register: Register = (on, raw: PluginOptions) => {
on('session.start', async ($, e, next) => {
control?.stop()
host = hostOf($, e.cwd, { prefs: () => state.toastPrefs, record: digest => recordToast(state, digest) })
- // Which write argv the host takes (GNU dd/install on Linux, the constant sh scripts on macOS/BSD). Started before the controller (whose
- // timers write) exists; every write awaits it (writeFlavorReady), so none is built with a guessed flavor.
+ // Which write the host takes (GNU dd/install on Linux, the constant sh scripts on macOS/BSD, the host's file API on Windows). Started
+ // before the controller (whose timers write) exists; every write awaits it (writeFlavorReady), so none is built with a guessed flavor.
const detecting = host
- void startWriteFlavorDetection((argv, timeoutMs) => detecting.run(argv, timeoutMs))
+ void startWriteFlavor((argv, timeoutMs) => detecting.run(argv, timeoutMs), undefined, e.cwd)
state.cwd = e.cwd
state.nostrKeyVerifiedAtMs = null
state.isInteractive = e.isInteractive !== false
@@ -190,37 +205,7 @@ export const register: Register = (on, raw: PluginOptions) => {
})
.catch(() => undefined)
- // The update mode is the person's, kept in the plugin's store; then, once the build is known (a development checkout is never offered
- // an update) and the screen has settled, one check for a newer published version. It never throws and never blocks the console.
- const moded = here.storeGet(UPDATES_KEY).then(
- value => {
- state.updates = parseMode(value)
- here.invalidate()
- },
- () => undefined,
- )
-
- // The Toasts setting is the person's, kept in the plugin's store and mirrored to a file the other plugins read (ADR-477).
- const toasted = here.storeGet(TOASTS_KEY).then(
- value => {
- state.toastPrefs = prefsFromStore(value)
- if (state.toastPrefs.mode !== 'all' || state.toastPrefs.muted.length > 0) void saveToastPrefs(state, here)
- },
- () => undefined,
- )
-
- // What's new (ADR-478): the record of what was looked at, read once; the controller's first disk read then takes the baseline.
- const looked = hydrateWhatsNew(state, here).catch(() => undefined)
-
- void toasted
- void looked
- void Promise.all([built, moded]).then(() => {
- if (!state.isInteractive) return
-
- here.after(2_500, () => void runUpdateCheck(state, here))
- // A session left open for days re-asks too, quietly (no dialog mid-work); the daily gate keeps the network to once a day.
- state.timers.set('update-recheck', here.every(RECHECK_EVERY_MS, () => void runUpdateCheck(state, here, { quiet: true })))
- })
+ loadAtStart(state, here, built)
const bound = host
diff --git a/plugins/ruflo-console/hooks/remember.ts b/plugins/ruflo-console/hooks/remember.ts
index d945e8ca97..90453933e2 100644
--- a/plugins/ruflo-console/hooks/remember.ts
+++ b/plugins/ruflo-console/hooks/remember.ts
@@ -20,7 +20,7 @@ const RISKY_WORD = /(^|[_\s-])(delete|rm|remove|purge|reset|shutdown|terminate|s
/** The kind of action a spec is, when it may be remembered; null when it must always ask. */
export function rememberKey(spec: ActionSpec): string | null {
- if (spec.argv !== undefined || spec.run !== undefined || spec.isReadOnly === true || spec.stdin !== undefined) return null
+ if (spec.argv !== undefined || spec.write !== undefined || spec.run !== undefined || spec.isReadOnly === true || spec.stdin !== undefined) return null
const words = spec.args.join(' ')
diff --git a/plugins/ruflo-console/hooks/runner.ts b/plugins/ruflo-console/hooks/runner.ts
index a5eb6a09c3..88234be944 100644
--- a/plugins/ruflo-console/hooks/runner.ts
+++ b/plugins/ruflo-console/hooks/runner.ts
@@ -11,6 +11,7 @@ import { record } from './data/events'
import { plain } from './data/parse'
import { answerFailed, failureReason, judgeFindings } from './data/failure'
import type { Host } from './host'
+import { writeVia } from './data/write-via'
import { labLines } from './mh-lab'
import { outputLines } from './ops'
import { filterPalette, paletteEntries, textOfQuery, type PaletteEntry } from './palette'
@@ -28,6 +29,8 @@ export const UNBOUND_REPLACED_MS = 10_000
/** Claude may withdraw at most this many asks per minute, and may not re-ask the same label this soon after withdrawing it. */
export const WITHDRAW_MAX_PER_MIN = 3
export const REASK_COOLDOWN_MS = 10_000
+/** A confirmed action whose on-disk check fails is read once more this long after: the CLI can return before its state file lands. */
+export const VERIFY_RETRY_MS = 1_000
/** True when a waiting card has outlived its window: a Yes for it would be refused, so it only blocks the next ask. */
export const isStale = (pending: Pick<Pending, 'askedAtMs'>, nowMs = Date.now()): boolean => nowMs - pending.askedAtMs >= PENDING_TTL_MS
@@ -122,7 +125,9 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
lastArgv = argv
if (isCold) say(spec.label, true, FIRST_RUN_LABEL)
- const result = await host.run(argv, isCold ? Math.max(spec.timeoutMs ?? 0, COLD_TIMEOUT_MS) : spec.timeoutMs ?? 90_000, spec.stdin)
+ const result = spec.write !== undefined
+ ? await writeVia('host-fs', host, { ...spec.write, timeoutMs: spec.timeoutMs ?? 10_000 })
+ : await host.run(argv, isCold ? Math.max(spec.timeoutMs ?? 0, COLD_TIMEOUT_MS) : spec.timeoutMs ?? 90_000, spec.stdin)
// A verdict command's "found something" exit with its JSON answer is an answer (`spec.findings`): the CLI was
// reached, so the launcher is kept, and the run is not a failure. Any other non-zero exit is one.
@@ -166,9 +171,16 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
await deps.freshRead()
- const verified = spec.verifyLocal !== undefined
- ? ok && await spec.verifyLocal(host) ? 'yes' : 'no'
- : spec.verify === undefined || state.snapshot === null ? 'n/a' : spec.verify(state.snapshot) ? 'yes' : 'no'
+ const verifiedOnce = () => (spec.verify === undefined || state.snapshot === null ? 'n/a' : spec.verify(state.snapshot) ? 'yes' : 'no')
+ let verified = spec.verifyLocal !== undefined ? (ok && (await spec.verifyLocal(host)) ? 'yes' : 'no') : verifiedOnce()
+
+ // The CLI can return before its state file lands: when the run succeeded but the file is not there yet, look once more a second later.
+ // `n/a` here means the snapshot had not loaded (null) rather than "no verifier"; retry only when the verifier is defined.
+ if ((verified === 'no' || (verified === 'n/a' && spec.verify !== undefined)) && ok && spec.verifyLocal === undefined) {
+ await new Promise<void>(resolve => void host.after(VERIFY_RETRY_MS, resolve))
+ await deps.freshRead()
+ verified = verifiedOnce()
+ }
state.outcome = {
label: spec.label,
diff --git a/plugins/ruflo-console/hooks/skills-lab.ts b/plugins/ruflo-console/hooks/skills-lab.ts
index 9a11318f8f..45465e3057 100644
--- a/plugins/ruflo-console/hooks/skills-lab.ts
+++ b/plugins/ruflo-console/hooks/skills-lab.ts
@@ -9,6 +9,7 @@
import type { ActionSpec } from './actions'
import { readBounded, textOf, under, type ReaderFs } from './data/files'
import { plain } from './data/parse'
+import { hasParentSegment, isAbsolutePath } from './data/paths'
import { checkLines, checkSkillMd, inferStack, skillRefs } from './data/skill-md'
import { AGENT_TARGETS, agentsOf, findArgv, listRepoArgv, nameInId, newNameOf, parseRepoList, restoreArgv, skillIdOf, skillNameOf, sortedFound, syncArgv, updateAllArgv, useArgv, usePromptOf, type FoundSkill, type InstalledSkill, type Scope } from './data/skills'
import type { Host } from './host'
@@ -129,7 +130,7 @@ export function previewFoundSpec(state: State, host: Host, found: FoundSkill): A
}
/** A path the CLI listed, accepted only when absolute and free of `..` segments. */
-export const isSafeDir = (path: string): boolean => path.startsWith('/') && !path.split('/').includes('..') && !/[\u0000-\u001f]/.test(path)
+export const isSafeDir = (path: string): boolean => isAbsolutePath(path) && !hasParentSegment(path) && !/[\u0000-\u001f]/.test(path)
/** Reads a SKILL.md (bounded), checks it and keeps the result as the preview; never runs it. */
async function previewFile(state: State, fs: ReaderFs, title: string, path: string, folder: string): Promise<void> {
diff --git a/plugins/ruflo-console/hooks/startup-loads.ts b/plugins/ruflo-console/hooks/startup-loads.ts
index 23265891e5..34cc129c28 100644
--- a/plugins/ruflo-console/hooks/startup-loads.ts
+++ b/plugins/ruflo-console/hooks/startup-loads.ts
@@ -5,6 +5,10 @@ import { loadAllowed } from './remember'
import { loadAiPrefs } from './settings'
import type { State } from './state'
import { loadThemes } from './themes'
+import { prefsFromStore, saveToastPrefs, TOASTS_KEY } from './toasts'
+import { runUpdateCheck } from './update-flow'
+import { parseMode, RECHECK_EVERY_MS, UPDATES_KEY } from './updates'
+import { hydrateWhatsNew } from './whatsnew'
export function loadSaved(state: State, host: Host): void {
void loadThemes(state, host)
@@ -12,3 +16,41 @@ export function loadSaved(state: State, host: Host): void {
void loadAllowed(state, host)
void loadLedger(state, host)
}
+
+/**
+ * What a session reads from the plugin's store when it starts, and the one update check that follows (moved out of register.ts, which the
+ * console smoke holds to 500 lines). Never throws and never blocks the console. `built` settles once the build is known.
+ */
+export function loadAtStart(state: State, here: Host, built: Promise<unknown>): void {
+ // The update mode is the person's, kept in the plugin's store; then, once the build is known (a development checkout is never offered
+ // an update) and the screen has settled, one check for a newer published version. It never throws and never blocks the console.
+ const moded = here.storeGet(UPDATES_KEY).then(
+ value => {
+ state.updates = parseMode(value)
+ here.invalidate()
+ },
+ () => undefined,
+ )
+
+ // The Toasts setting is the person's, kept in the plugin's store and mirrored to a file the other plugins read (ADR-477).
+ const toasted = here.storeGet(TOASTS_KEY).then(
+ value => {
+ state.toastPrefs = prefsFromStore(value)
+ if (state.toastPrefs.mode !== 'all' || state.toastPrefs.muted.length > 0) void saveToastPrefs(state, here)
+ },
+ () => undefined,
+ )
+
+ // What's new (ADR-478): the record of what was looked at, read once; the controller's first disk read then takes the baseline.
+ const looked = hydrateWhatsNew(state, here).catch(() => undefined)
+
+ void toasted
+ void looked
+ void Promise.all([built, moded]).then(() => {
+ if (!state.isInteractive) return
+
+ here.after(2_500, () => void runUpdateCheck(state, here))
+ // A session left open for days re-asks too, quietly (no dialog mid-work); the daily gate keeps the network to once a day.
+ state.timers.set('update-recheck', here.every(RECHECK_EVERY_MS, () => void runUpdateCheck(state, here, { quiet: true })))
+ })
+}
diff --git a/plugins/ruflo-console/hooks/state.ts b/plugins/ruflo-console/hooks/state.ts
index cc1996dbb5..c6704055d2 100644
--- a/plugins/ruflo-console/hooks/state.ts
+++ b/plugins/ruflo-console/hooks/state.ts
@@ -1,4 +1,5 @@
import type { PluginOptions, Timer } from 'claude-code'
+import { isWindowsPath, trimTrailing } from './data/paths'
import { guardOptionsOf, type GuardOptions } from './data/wf-alerts'
import { sessionOptionsOf, type SessionOptions } from './data/sessions-options'
import { convoOptionsOf, type ConvoOptions } from './data/wf-targets'
@@ -93,7 +94,16 @@ export const viewOf = (word: string): ViewId | null => {
* `$.store` is the plugin's, not the folder's: the key carries the working directory, so a view chosen in one project
* never follows the person into another (the ruflo-swarm leak).
*/
-export const storeKeyOf = (cwd: string): string => `ruflo-console/ui:${cwd}`
+export const storeKeyOf = (cwd: string): string => `ruflo-console/ui:${workspaceKeyOf(cwd)}`
+
+/**
+ * The working directory as a store-key part. A POSIX folder is the string itself (today's keys, byte for byte). A Windows folder (drive-lettered
+ * or a share) is one folder however it is spelled, so it is folded: lower case, `/` for `\`, no trailing separator (`c:\users\me\` and
+ * `C:\Users\me` share a key).
+ */
+function workspaceKeyOf(cwd: string): string {
+ return isWindowsPath(cwd) ? trimTrailing(cwd).replace(/\\/g, '/').toLowerCase() : cwd
+}
/** How actions reach the ruflo CLI: each a fixed argv prefix. Only `npx` may download. */
export const CLI_PREFIXES = {
@@ -172,7 +182,7 @@ export type TermLine = { kind: 'in' | 'head' | 'out' | 'err' | 'sys' | 'tool' |
/** A conversation kept per project: codex's thread id, claude's session id, so a follow-up resumes it. */
export type TermSessions = { codex?: string; claude?: string }
-export const termStoreKeyOf = (cwd: string): string => `ruflo-console/term:${cwd}`
+export const termStoreKeyOf = (cwd: string): string => `ruflo-console/term:${workspaceKeyOf(cwd)}`
/** What an action did: what ran, how it exited, whether the disk shows the change, and anything it printed to show. */
export type Outcome = { label: string; ok: boolean; verified: 'yes' | 'no' | 'n/a'; detail: string; atMs: number; lines?: string[]; /** A confirm card that nobody answered within PENDING_TTL_MS and was cleared unrun (the Room shows it briefly). */ expired?: boolean }
diff --git a/plugins/ruflo-console/hooks/version.ts b/plugins/ruflo-console/hooks/version.ts
index e6eeca6693..83c2c4d34b 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.45.0'
+export const CONSOLE_VERSION = '0.45.1'
diff --git a/plugins/ruflo-console/hooks/views/ap-panel.ts b/plugins/ruflo-console/hooks/views/ap-panel.ts
index 9454c973a1..587659b2fd 100644
--- a/plugins/ruflo-console/hooks/views/ap-panel.ts
+++ b/plugins/ruflo-console/hooks/views/ap-panel.ts
@@ -8,13 +8,14 @@
import type { RenderElement } from 'claude-code'
import type { ActionSpec } from '../actions'
-import { activeOf, apTick, appendEvents, clearKill, drainNotices, hostOf, pauseNow, refreshAutopilot, resumeNow, setPin, stopNow, storeOf, writeEnvelope } from '../ap-live'
+import { activeOf, apTick, appendEvents, AUTOPILOT_WINDOWS_REFUSAL, clearKill, drainNotices, hostOf, pauseNow, refreshAutopilot, resumeNow, setPin, stopNow, storeOf, writeEnvelope } from '../ap-live'
import { DEFAULTS, tierOf, tunablesFrom, verifyReceipts } from '../data/ap-adapt'
import { AUTOPILOT_DIR, hashOf, HARD_DENIES, MAX_DURATION_MS, MIN_DURATION_MS, seal, TOOL_CLASSES, validateEnvelope, widened, type Envelope, type ToolClass } from '../data/ap-envelope'
import { anatoleFact } from '../data/ap-guard'
import { SPEND_BASIS, spendSource } from '../data/ap-spend'
import { bandText, summarize } from '../data/ap-loop'
import { cleanText } from '../data/wf-clean'
+import { writeFlavorReady } from '../data/write-flavor'
import { readBounded, under } from '../data/files'
import type { NoticeDraft } from '../notices'
import type { State } from '../state'
@@ -233,6 +234,15 @@ export function startSpec(env: SlotEnv): ActionSpec | null {
expect: 'a start line in the autopilot journal, then steps handed to the session',
note: 'After this, steps inside the envelope run WITHOUT asking this console, for days if the session lives, and spend money. Claude Code\'s own permission dialog still applies and is never bypassed: anything it would ask about is parked. Stop, the KILL file or /ruflo autopilot stop halts it within one tick.',
run: async () => {
+ // Windows (host-fs): no atomic append for the journal's duplicate-start guard and no Windows-aware path fence yet. Nothing is written or dispatched (follow-up).
+ if ((await writeFlavorReady()) === 'host-fs') {
+ store.error = AUTOPILOT_WINDOWS_REFUSAL
+ host.toast(AUTOPILOT_WINDOWS_REFUSAL)
+ host.invalidate()
+
+ return
+ }
+
const now = Date.now()
const sealed = seal(next, (store.sealed?.revision ?? 0) + 1, now)
const mode = anatoleFact(state.snapshot?.anatole)
diff --git a/plugins/ruflo-console/hooks/wf-saved-live.ts b/plugins/ruflo-console/hooks/wf-saved-live.ts
index deb578cf90..d0d254e24a 100644
--- a/plugins/ruflo-console/hooks/wf-saved-live.ts
+++ b/plugins/ruflo-console/hooks/wf-saved-live.ts
@@ -10,8 +10,9 @@
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, replaceFileArgv } from './data/wf-file'
+import { checkNoLinks, dirOf, removeFileArgv } from './data/wf-file'
import { writeFlavorReady } from './data/write-flavor'
+import { writeVia } from './data/write-via'
import { readBounded } from './data/files'
import type { Host } from './host'
import type { State } from './state'
@@ -141,7 +142,7 @@ export async function syncSavedViews(state: State, host: SavedHost, nowMs: numbe
}
const hasDir = (await host.fs.stat(dirOf(path)).catch(() => undefined)) !== undefined
- const result = await host.run(replaceFileArgv(path, hasDir, await writeFlavorReady()), 10_000, encodeSaved(own.saved, nowMs))
+ const result = await writeVia(await writeFlavorReady(), host, { kind: 'replace', path, text: encodeSaved(own.saved, nowMs), hasDir })
own.error = result.exitCode === 0 ? null : `the write exited ${result.exitCode}`
if (result.exitCode === 0) own.isDirty = false
diff --git a/plugins/ruflo-console/scripts/smoke.sh b/plugins/ruflo-console/scripts/smoke.sh
index 73ef30ab55..2ac5e36dba 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.45.0"
+step "1. plugin.json declares ruflo-console 0.45.1"
grep -q '"name": "ruflo-console"' "$ROOT/.claude-plugin/plugin.json" \
- && grep -q '"version": "0.45.0"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"
+ && grep -q '"version": "0.45.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" \
diff --git a/plugins/ruflo-console/tests/abs-path.spec.ts b/plugins/ruflo-console/tests/abs-path.spec.ts
deleted file mode 100644
index f31c89513f..0000000000
--- a/plugins/ruflo-console/tests/abs-path.spec.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { isAbsolutePath, rootedPath } from '../hooks/data/abs-path'
-
-// #4175: on Windows the working directory is `C:\dev\app`, so `under(cwd, ...)` returns `C:\dev\app/.claude-flow/...`.
-// The host wrapper used to treat only a leading `/` as absolute and prefixed the cwd a second time.
-describe('absolute paths, POSIX and Windows (#4175)', () => {
- it('knows a rooted path on both families', () => {
- for (const path of ['/home/a/b', 'C:\\dev\\app', 'C:/dev/app', 'c:\\x', 'Z:/', '\\\\server\\share\\x', 'C:\\dev\\app/.claude-flow/console/events.jsonl']) {
- expect(isAbsolutePath(path), path).toBe(true)
- }
- })
-
- it('treats a relative path, a bare drive and a drive-relative path as relative', () => {
- for (const path of ['.claude-flow/config.yaml', 'a/b', '', 'C:', 'C:foo', '..\\x', 'dev/C:/x']) {
- expect(isAbsolutePath(path), path).toBe(false)
- }
- })
-
- it('never prefixes the working directory twice (the doubled path of the issue)', () => {
- const cwd = 'C:\\dev\\app'
- const built = `${cwd}/.claude-flow/console/events.jsonl`
-
- expect(rootedPath(cwd, built)).toBe(built)
- expect(rootedPath(cwd, built)).not.toContain('app\\C:')
- expect(rootedPath('C:/dev/app', 'C:/dev/app/x')).toBe('C:/dev/app/x')
- expect(rootedPath('/home/a', '/home/a/x')).toBe('/home/a/x')
- expect(rootedPath('\\\\srv\\share\\app', '\\\\srv\\share\\app/x')).toBe('\\\\srv\\share\\app/x')
- })
-
- it('still roots a relative path, and trims trailing separators of either kind', () => {
- expect(rootedPath('/home/a/', '.claude-flow/x')).toBe('/home/a/.claude-flow/x')
- expect(rootedPath('C:\\dev\\app\\', '.claude-flow/x')).toBe('C:\\dev\\app/.claude-flow/x')
- expect(rootedPath('C:\\dev\\app', 'a/b')).toBe('C:\\dev\\app/a/b')
- })
-})
-
-describe('the host wrapper uses it (#4175)', () => {
- it('register.ts roots host paths through rootedPath, not an inline leading-slash test', async () => {
- const { readFileSync } = await import('node:fs')
- const source = readFileSync(new URL('../hooks/register.ts', import.meta.url), 'utf8')
-
- expect(source).toContain("import { rootedPath } from './data/abs-path'")
- expect(source).toContain('rootedPath(cwd, path)')
- expect(source).not.toMatch(/path\.startsWith\('\/'\) \? path/)
- })
-})
diff --git a/plugins/ruflo-console/tests/adr-windows-init.spec.ts b/plugins/ruflo-console/tests/adr-windows-init.spec.ts
new file mode 100644
index 0000000000..5fb4e53ef3
--- /dev/null
+++ b/plugins/ruflo-console/tests/adr-windows-init.spec.ts
@@ -0,0 +1,72 @@
+/**
+ * #4433: on Windows "initialise ADRs" failed with `$.process.run(install) failed to start: ENOENT`, because the console wrote files by
+ * running dd / install / sh and none of them is on a Windows PATH. The write goes through the host's file API there (host-fs). This is that
+ * scenario end to end on an in-memory Windows-style project: a host whose `run` throws ENOENT proves nothing is spawned. Run with
+ * npx vitest run plugins/ruflo-console/tests/adr-windows-init.spec.ts
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { adrOf, initSpec, loadAdrs } from '../hooks/adr'
+import { setWriteFlavor } from '../hooks/data/write-flavor'
+import { newState } from '../hooks/state'
+
+/** A project on disk as a Map: files by path, folders implied by the files under them. Windows reads `\` and `/` as the same separator, so keys are kept with `/`. */
+function memoryHost() {
+ const files = new Map<string, string>()
+ const k = (path: string) => path.replace(/\\/g, '/')
+ const isDir = (path: string) => [...files.keys()].some(file => file.startsWith(`${k(path)}/`))
+ const run = vi.fn(async (argv: readonly string[]) => { throw new Error(`ruflo-console: $.process.run(${argv[0]}) failed to start: ENOENT`) })
+ const host = {
+ fs: {
+ read: async (path: string) => (files.has(k(path)) ? (files.get(k(path)) as string) : Promise.reject(new Error('ENOENT'))),
+ stat: async (path: string) => (files.has(k(path)) ? { kind: 'file', size: (files.get(k(path)) as string).length, mtimeMs: 1, isLink: false } : isDir(path) ? { kind: 'dir', size: 0, mtimeMs: 1, isLink: false } : Promise.reject(new Error('ENOENT'))),
+ list: async (path: string) => {
+ const names = new Set<string>()
+
+ const base = k(path)
+
+ for (const file of files.keys()) if (file.startsWith(`${base}/`)) names.add(file.slice(base.length + 1).split('/')[0] as string)
+ if (names.size === 0) throw new Error('ENOENT')
+
+ return [...names].map(name => ({ name, kind: files.has(`${k(path)}/${name}`) ? 'file' : 'dir' }))
+ },
+ write: async (path: string, text: string) => void files.set(k(path), text),
+ exists: async (path: string) => files.has(k(path)) || isDir(path),
+ },
+ run,
+ toast: () => undefined,
+ invalidate: () => undefined,
+ storeGet: async () => undefined,
+ }
+
+ return { host: host as never, files, run }
+}
+
+describe('ADRs: initialise on a Windows project', () => {
+ beforeEach(() => setWriteFlavor('host-fs'))
+ afterEach(() => setWriteFlavor(null))
+
+ for (const cwd of ['C:/Users/me/app', 'C:\\Users\\me\\app']) {
+ it(`creates the folder and the first record through the host's file API, spawning nothing (${cwd})`, async () => {
+ const { host, files, run } = memoryHost()
+ const state = newState({})
+
+ state.cwd = cwd
+ await loadAdrs(state, host)
+ expect(adrOf(state).dir).toBeNull()
+ expect(adrOf(state).why).not.toBe('no project folder is known')
+
+ const spec = initSpec(state, host, '2026-10-23')
+
+ expect(spec).not.toBeNull()
+ await spec!.run!(undefined as never)
+
+ const made = [...files.keys()].filter(path => /0001-record-architecture-decisions\.md$/.test(path))
+
+ expect(made, JSON.stringify([...files.keys()])).toHaveLength(1)
+ expect(files.get(made[0] as string)).toMatch(/Record architecture decisions/i)
+ expect(run).not.toHaveBeenCalled()
+ expect(adrOf(state).dir, `the page finds the folder it just made: ${adrOf(state).why}; files=${JSON.stringify([...files.keys()])}`).not.toBeNull()
+ })
+ }
+})
diff --git a/plugins/ruflo-console/tests/ap-windows-gate.spec.ts b/plugins/ruflo-console/tests/ap-windows-gate.spec.ts
new file mode 100644
index 0000000000..a0aa51e3a9
--- /dev/null
+++ b/plugins/ruflo-console/tests/ap-windows-gate.spec.ts
@@ -0,0 +1,105 @@
+/**
+ * Autopilot on Windows (write flavor host-fs) is not available yet: its journal needs atomic appends (host-fs appends are read-then-write, so two
+ * concurrent `step.started` lines can lose one and a step can be dispatched twice) and its folder fence and envelope-edit deny need Windows-aware
+ * path checks. So every start refuses, writing nothing and dispatching nothing; stop and the kill-flag clear keep working. Elsewhere a start is
+ * unchanged.
+ */
+import { afterEach, describe, expect, it } from 'vitest'
+
+import { setWriteFlavor } from '../hooks/data/write-flavor'
+import { KILL_CLEARED } from '../hooks/data/ap-envelope'
+import { resetSlots, slotsFor } from '../hooks/views/wf-slots'
+import { boardRows, draftOf, editDraft, registerAutopilotSlots, startSpec } from '../hooks/views/ap-panel'
+import { CWD, ctxOf, envOf, flat, journal, KILL, rig, stateWith, T0 } from './fixtures/ap-rig'
+
+const MESSAGE = 'Autopilot is not yet available on Windows: its journal and path fence need atomic appends and Windows-aware path checks (follow-up).'
+
+afterEach(() => setWriteFlavor(null))
+
+async function world(flavor: 'host-fs' | 'gnu') {
+ setWriteFlavor(flavor)
+
+ const live = await import('../hooks/ap-live')
+ const r = rig()
+ const state = stateWith([], 'off')
+ const fs = r.host.fs as unknown as Record<string, unknown>
+
+ fs.write = async (p: string, t: string) => void r.files.set(p, t)
+ fs.exists = async (p: string) => r.files.has(p)
+ live.wireAutopilot(state, r.host)
+ editDraft(draftOf(state), { kind: 'anatole' })
+
+ return { r, state, live }
+}
+
+describe('autopilot start on a host-fs machine', () => {
+ it('the card run refuses with the plain message and writes nothing, runs nothing, dispatches nothing', async () => {
+ const { r, state, live } = await world('host-fs')
+ const before = [...r.files.keys()]
+
+ await startSpec(envOf(state, T0))?.run?.()
+
+ expect(live.storeOf(state).error).toBe(MESSAGE)
+ expect(r.toasts).toContain(MESSAGE)
+ expect([...r.files.keys()]).toEqual(before)
+ expect(r.runs).toEqual([])
+ expect(r.prompts).toEqual([])
+ expect(live.storeOf(state).loop.phase).not.toBe('running')
+ })
+
+ it('every start entry point converges on it: the Workflows action row, the pane button and the confirm they raise', async () => {
+ const { r, state, live } = await world('host-fs')
+ const before = [...r.files.keys()]
+
+ resetSlots()
+ registerAutopilotSlots()
+
+ const slot = slotsFor('action').find(s => s.id === 'ap-start')
+
+ await slot?.spec(envOf(state, T0))?.run?.()
+ expect(live.storeOf(state).error).toBe(MESSAGE)
+
+ live.storeOf(state).error = null
+
+ const asked: unknown[] = []
+ const ctx = { ...ctxOf(state, T0), act: { workflows: { ask: (spec: unknown) => void asked.push(spec) } } as never }
+ const press = flat(boardRows({ ...envOf(state, T0), ctx })).find(el => el.kind === 'Button' && el.props.key === 'ap-start-btn')?.props.onPress as () => void
+
+ press()
+ expect(asked).toHaveLength(1)
+ await (asked[0] as { run: () => Promise<void> }).run()
+ expect(live.storeOf(state).error).toBe(MESSAGE)
+ expect([...r.files.keys()]).toEqual(before)
+ expect(r.runs).toEqual([])
+ expect(r.prompts).toEqual([])
+ })
+
+ it('stop and the kill-flag clear still work: a stopped flag is cleared with the marker, and a stop writes it again', async () => {
+ const { r, state, live } = await world('host-fs')
+ const { killSeen } = await import('../hooks/data/ap-guard')
+
+ await live.stopNow(state, r.host, 'because')
+ expect(await killSeen(r.host.fs, CWD)).toBe(true)
+
+ await startSpec(envOf(state, T0))?.run?.()
+ expect(live.storeOf(state).error).toBe(MESSAGE)
+ expect(await killSeen(r.host.fs, CWD)).toBe(true)
+
+ await live.clearKill(state, r.host)
+ expect(r.files.get(KILL)).toBe(KILL_CLEARED)
+ expect(await killSeen(r.host.fs, CWD)).toBe(false)
+
+ await live.stopNow(state, r.host, 'again')
+ expect(await killSeen(r.host.fs, CWD)).toBe(true)
+ })
+
+ it('gnu: a start is unchanged (the envelope is written and a start line is journaled)', async () => {
+ const { r, state, live } = await world('gnu')
+
+ await startSpec(envOf(state, T0))?.run?.()
+
+ expect(live.storeOf(state).error).toBeFalsy()
+ expect(r.files.has(`${CWD}/.claude-flow/console/autopilot/envelope.json`)).toBe(true)
+ expect(journal(r).some(event => event.t === 'start')).toBe(true)
+ })
+})
diff --git a/plugins/ruflo-console/tests/dispatch-timer.spec.ts b/plugins/ruflo-console/tests/dispatch-timer.spec.ts
new file mode 100644
index 0000000000..533ec9db83
--- /dev/null
+++ b/plugins/ruflo-console/tests/dispatch-timer.spec.ts
@@ -0,0 +1,35 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { settleWithin } from '../hooks/dispatch'
+
+describe('settleWithin', () => {
+ afterEach(() => vi.useRealTimers())
+
+ it('leaves no timer pending after a fast probe', async () => {
+ vi.useFakeTimers()
+ await settleWithin(Promise.resolve('fast'), 8_000)
+
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
+ it('leaves no timer pending after a probe that rejects, and passes the rejection on', async () => {
+ vi.useFakeTimers()
+ await expect(settleWithin(Promise.reject(new Error('x')), 8_000)).rejects.toThrow('x')
+
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
+ it('still gives up on a probe that never settles once the wait is over', async () => {
+ vi.useFakeTimers()
+
+ let isDone = false
+ const waiting = settleWithin(new Promise(() => undefined), 8_000).then(() => { isDone = true })
+
+ await vi.advanceTimersByTimeAsync(7_999)
+ expect(isDone).toBe(false)
+ await vi.advanceTimersByTimeAsync(1)
+ await waiting
+ expect(isDone).toBe(true)
+ expect(vi.getTimerCount()).toBe(0)
+ })
+})
diff --git a/plugins/ruflo-console/tests/fixtures/world.ts b/plugins/ruflo-console/tests/fixtures/world.ts
index 792674c7ea..18ef7f8c0b 100644
--- a/plugins/ruflo-console/tests/fixtures/world.ts
+++ b/plugins/ruflo-console/tests/fixtures/world.ts
@@ -28,6 +28,9 @@ export const BAND: RenderInput<'AbovePrompt'> = {
export const command = (args = '') => ({ command: 'ruflo', args, origin: { kind: 'composer' as const }, presentation: { isFullscreen: true, columns: 180 } })
+/** The host hands hooks native paths (`C:\work\.claude-flow\x` on Windows); the fake file system keys on `/work/...`. */
+export const normalizeFixturePath = (p: string): string => p.replace(/^[A-Za-z]:/, '').replace(/\\/g, '/')
+
export type Answer = { exitCode: number; stdout: string; stderr: string } | { deny: string }
export type World = {
@@ -87,7 +90,7 @@ export function cliAnswer(argv: readonly string[]): Answer {
*/
export function worldOf(on: On, files: Readonly<Record<string, string>>, options: { refuseAll?: boolean; commands?: readonly string[]; home?: Readonly<Record<string, string>>; env?: Readonly<Record<string, string>> } = {}): World {
let tick = 1_000
- const all = new Map<string, string>([...Object.entries(files).map(([path, text]) => [`${CWD}/${path}`, text] as const), ...Object.entries(options.home ?? {}).map(([path, text]) => [`${HOME}/${path}`, text] as const)])
+ const all = new Map<string, string>([...Object.entries(files).map(([path, text]) => [normalizeFixturePath(`${CWD}/${path}`), text] as const), ...Object.entries(options.home ?? {}).map(([path, text]) => [normalizeFixturePath(`${HOME}/${path}`), text] as const)])
const mtimes = new Map<string, number>([...all.keys()].map(path => [path, tick]))
const world: World = {
files: all,
@@ -107,25 +110,34 @@ export function worldOf(on: On, files: Readonly<Record<string, string>>, options
respond: cliAnswer,
put: (path, text) => {
tick += 1_000
- all.set(`${CWD}/${path}`, text)
- mtimes.set(`${CWD}/${path}`, tick)
+ all.set(normalizeFixturePath(`${CWD}/${path}`), text)
+ mtimes.set(normalizeFixturePath(`${CWD}/${path}`), tick)
},
}
const refuse = options.refuseAll === true
on('session.start', ($, e) => ({ cwd: e.cwd }))
- on('fs.read', ($, e) => (world.reads.push(e.path), refuse || !all.has(e.path) ? { deny: `ENOENT: ${e.path}` } : { value: all.get(e.path) as string }))
+ on('fs.read', ($, e) => {
+ const path = normalizeFixturePath(e.path)
+
+ world.reads.push(path)
+
+ return refuse || !all.has(path) ? { deny: `ENOENT: ${path}` } : { value: all.get(path) as string }
+ })
on('fs.stat', ($, e) => {
- world.stats.push(e.path)
- const text = all.get(e.path)
+ const path = normalizeFixturePath(e.path)
+
+ world.stats.push(path)
+
+ const text = all.get(path)
// A folder that holds a file stats as a directory, as a real one does (the ADRs page asks before it lists).
- if (!refuse && text === undefined && [...all.keys()].some(path => path.startsWith(`${e.path}/`))) return { value: { kind: 'dir' as const, size: 0, mtimeMs: 1, isLink: false } }
+ if (!refuse && text === undefined && [...all.keys()].some(key => key.startsWith(`${path}/`))) return { value: { kind: 'dir' as const, size: 0, mtimeMs: 1, isLink: false } }
- return refuse || text === undefined ? { deny: `ENOENT: ${e.path}` } : { value: { kind: 'file' as const, size: text.length, mtimeMs: mtimes.get(e.path) ?? 0, isLink: false } }
+ return refuse || text === undefined ? { deny: `ENOENT: ${path}` } : { value: { kind: 'file' as const, size: text.length, mtimeMs: mtimes.get(path) ?? 0, isLink: false } }
})
on('fs.list', ($, e) => {
- const prefix = `${e.path ?? CWD}/`
+ const prefix = `${normalizeFixturePath(e.path ?? CWD)}/`
const below = [...all.keys()].filter(path => path.startsWith(prefix)).map(path => path.slice(prefix.length))
const files = below.filter(name => !name.includes('/'))
// A folder holding a file shows as a directory entry of its own, as a real listing does.
diff --git a/plugins/ruflo-console/tests/hive-appears.spec.ts b/plugins/ruflo-console/tests/hive-appears.spec.ts
new file mode 100644
index 0000000000..e69fac39bc
--- /dev/null
+++ b/plugins/ruflo-console/tests/hive-appears.spec.ts
@@ -0,0 +1,168 @@
+/**
+ * A hive that exists shows up. The missing-file backoff (MISSING_RECHECK_MS) must not hide a hive.json written after the first read:
+ * the next refresh past the window reads it, and a hive started from the console is read fresh when the CLI returns.
+ * npx vitest run plugins/ruflo-console/tests/hive-appears.spec.ts
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { MISSING_RECHECK_MS, PROJECT, type ReaderFs, type ReadCache } from '../hooks/data/files'
+import { readSnapshot } from '../hooks/data/snapshot'
+import { createController } from '../hooks/controller'
+import type { Host } from '../hooks/host'
+import { newState } from '../hooks/state'
+import { startSpec } from '../hooks/starts'
+import { HIVE_STATE } from './fixtures/hive'
+
+const CWD = 'C:/Users/me/project'
+const HIVE_PATH = `${CWD}/${PROJECT.hive}`
+const TEXT = JSON.stringify(HIVE_STATE)
+
+/** A disk where only the hive file may exist, and from when. */
+function disk(): { fs: ReaderFs; put: () => void } {
+ let exists = false
+
+ return {
+ put: () => void (exists = true),
+ fs: {
+ stat: async path => (path === HIVE_PATH && exists ? { mtimeMs: 1, size: TEXT.length, kind: 'file' } : Promise.reject(new Error('ENOENT'))),
+ read: async path => (path === HIVE_PATH && exists ? TEXT : Promise.reject(new Error('ENOENT'))),
+ list: async () => Promise.reject(new Error('ENOENT')),
+ },
+ }
+}
+
+describe('the hive file first seen missing', () => {
+ beforeEach(() => vi.useFakeTimers({ now: 1_000_000 }))
+ afterEach(() => vi.useRealTimers())
+
+ it('is found by the first refresh after the recheck window, not before', async () => {
+ const { fs, put } = disk()
+ const cache: ReadCache = new Map()
+
+ expect((await readSnapshot(fs, cache, CWD, null, null, Date.now())).hive).toBeNull()
+ vi.advanceTimersByTime(2_000)
+ put()
+ expect((await readSnapshot(fs, cache, CWD, null, null, Date.now())).hive).toBeNull()
+ vi.advanceTimersByTime(MISSING_RECHECK_MS)
+
+ const snapshot = await readSnapshot(fs, cache, CWD, null, null, Date.now())
+
+ expect(snapshot.hive?.queen).toBe(HIVE_STATE.queen.agentId)
+ })
+})
+
+describe('a hive started from the console', () => {
+ it('is verified against a fresh read even when the file was first seen missing seconds ago', async () => {
+ const { fs, put } = disk()
+ const host = new Proxy(
+ {},
+ {
+ get: (_target, key) => {
+ if (key === 'fs') return fs
+ if (key === 'run') return async () => { put(); return { exitCode: 0, stdout: '{"success":true}', stderr: '' } }
+ if (key === 'after' || key === 'every') return () => ({ cancel: () => undefined })
+ if (key === 'settings') return async () => null
+
+ return () => Promise.resolve(undefined)
+ },
+ },
+ ) as unknown as Host
+ const state = newState({})
+
+ state.cwd = CWD
+ state.home = null
+ state.configDir = null
+
+ const control = createController(state, host)
+
+ await control.refresh()
+ expect(state.snapshot?.hive).toBeNull()
+
+ const spec = startSpec('hive', Date.now())
+
+ control.runner.ask({ ...spec!, argv: ['ruflo', 'hive-mind', 'init'] }, 'test')
+ await control.runner.confirm()
+
+ expect(state.outcome?.verified).toBe('yes')
+ expect(state.outcome?.ok).toBe(true)
+ expect(state.snapshot?.hive).not.toBeNull()
+ })
+})
+
+describe('a start whose CLI returns before state.json lands', () => {
+ beforeEach(() => vi.useFakeTimers({ now: 1_000_000 }))
+ afterEach(() => vi.useRealTimers())
+
+ /** `landsAfterMs` null: never. `exitCode` is the CLI's. Counts stats of the hive file. */
+ function setup(landsAfterMs: number | null, exitCode = 0) {
+ const { fs, put } = disk()
+ const seen = { stats: 0 }
+ const counted: ReaderFs = {
+ ...fs,
+ stat: async path => {
+ if (path === HIVE_PATH) seen.stats += 1
+
+ return fs.stat(path)
+ },
+ }
+ const host = new Proxy(
+ {},
+ {
+ get: (_target, key) => {
+ if (key === 'fs') return counted
+ if (key === 'run') return async () => { if (landsAfterMs !== null) setTimeout(put, landsAfterMs); return { exitCode, stdout: exitCode === 0 ? '{"success":true}' : '', stderr: exitCode === 0 ? '' : 'boom' } }
+ if (key === 'after') return (ms: number, fn: () => void) => { const id = setTimeout(fn, ms); return { cancel: () => clearTimeout(id) } }
+ if (key === 'every') return () => ({ cancel: () => undefined })
+ if (key === 'settings') return async () => null
+
+ return () => Promise.resolve(undefined)
+ },
+ },
+ ) as unknown as Host
+ const state = newState({})
+
+ state.cwd = CWD
+ state.home = null
+ state.configDir = null
+
+ return { state, host, seen }
+ }
+
+ async function start(state: ReturnType<typeof newState>, host: Host) {
+ const control = createController(state, host)
+
+ await control.refresh()
+ control.runner.ask({ ...startSpec('hive', Date.now())!, argv: ['ruflo', 'hive-mind', 'init'] }, 'test')
+
+ const done = control.runner.confirm()
+
+ await vi.advanceTimersByTimeAsync(5_000)
+ await done
+ }
+
+ it('reports success when the file lands 500 ms after the run returns', async () => {
+ const { state, host } = setup(500)
+
+ await start(state, host)
+ expect(state.outcome?.verified).toBe('yes')
+ expect(state.outcome?.ok).toBe(true)
+ })
+
+ it('reports the expected text after exactly one retry when it never lands', async () => {
+ const { state, host, seen } = setup(null)
+
+ await start(state, host)
+ expect(state.outcome?.verified).toBe('no')
+ expect(state.outcome?.detail).toMatch(/expected a queen in \.claude-flow\/hive-mind\/state\.json/)
+ // initial refresh + first verify read + one retry read: bounded to one retry.
+ expect(seen.stats).toBe(3)
+ })
+
+ it('does not retry when the run itself failed', async () => {
+ const { state, host, seen } = setup(500, 1)
+
+ await start(state, host)
+ expect(state.outcome?.ok).toBe(false)
+ expect(seen.stats).toBe(2)
+ })
+})
diff --git a/plugins/ruflo-console/tests/home-dir.spec.ts b/plugins/ruflo-console/tests/home-dir.spec.ts
new file mode 100644
index 0000000000..639749ec6f
--- /dev/null
+++ b/plugins/ruflo-console/tests/home-dir.spec.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it } from 'vitest'
+
+import { homeOf } from '../hooks/data/paths'
+
+describe('homeOf', () => {
+ it('returns HOME when set', () => {
+ const get = (k: string): string | undefined => k === 'HOME' ? '/home/user' : undefined
+ expect(homeOf(get)).toBe('/home/user')
+ })
+
+ it('returns USERPROFILE when HOME is empty and USERPROFILE is set', () => {
+ const get = (k: string): string | undefined => k === 'USERPROFILE' ? 'C:\\Users\\mariu' : undefined
+ expect(homeOf(get)).toBe('C:\\Users\\mariu')
+ })
+
+ it('joins HOMEDRIVE and HOMEPATH when neither HOME nor USERPROFILE is set', () => {
+ const get = (k: string): string | undefined => {
+ if (k === 'HOMEDRIVE') return 'C:'
+ if (k === 'HOMEPATH') return '\\Users\\mariu'
+ return undefined
+ }
+ expect(homeOf(get)).toBe('C:\\Users\\mariu')
+ })
+
+ it('returns null when no home environment variables are set', () => {
+ const get = (k: string): string | undefined => undefined
+ expect(homeOf(get)).toBeNull()
+ })
+
+ it('HOME takes precedence over USERPROFILE', () => {
+ const get = (k: string): string | undefined => {
+ if (k === 'HOME') return '/home/user'
+ if (k === 'USERPROFILE') return 'C:\\Users\\mariu'
+ return undefined
+ }
+ expect(homeOf(get)).toBe('/home/user')
+ })
+
+ it('USERPROFILE takes precedence over HOMEDRIVE+HOMEPATH', () => {
+ const get = (k: string): string | undefined => {
+ if (k === 'USERPROFILE') return 'C:\\Users\\mariu'
+ if (k === 'HOMEDRIVE') return 'D:'
+ if (k === 'HOMEPATH') return '\\Users\\other'
+ return undefined
+ }
+ expect(homeOf(get)).toBe('C:\\Users\\mariu')
+ })
+
+ it('ignores empty HOMEDRIVE or HOMEPATH', () => {
+ const get = (k: string): string | undefined => {
+ if (k === 'HOMEDRIVE') return ''
+ if (k === 'HOMEPATH') return '\\Users\\mariu'
+ return undefined
+ }
+ expect(homeOf(get)).toBeNull()
+ })
+
+ it('ignores empty USERPROFILE', () => {
+ const get = (k: string): string | undefined => {
+ if (k === 'USERPROFILE') return ''
+ if (k === 'HOMEDRIVE') return 'C:'
+ if (k === 'HOMEPATH') return '\\Users\\mariu'
+ return undefined
+ }
+ expect(homeOf(get)).toBe('C:\\Users\\mariu')
+ })
+
+ it('ignores empty HOME', () => {
+ const get = (k: string): string | undefined => {
+ if (k === 'HOME') return ''
+ if (k === 'USERPROFILE') return 'C:\\Users\\mariu'
+ return undefined
+ }
+ expect(homeOf(get)).toBe('C:\\Users\\mariu')
+ })
+})
diff --git a/plugins/ruflo-console/tests/paths.spec.ts b/plugins/ruflo-console/tests/paths.spec.ts
new file mode 100644
index 0000000000..3ccc9d0b93
--- /dev/null
+++ b/plugins/ruflo-console/tests/paths.spec.ts
@@ -0,0 +1,81 @@
+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'
+
+describe('paths', () => {
+ it('absolute forms', () => {
+ for (const p of ['/work', 'C:\\Users\\x', 'c:/Users/x', '\\\\srv\\share\\x']) expect(isAbsolutePath(p)).toBe(true)
+ for (const p of ['work', '.\\x', 'C:x', '']) expect(isAbsolutePath(p)).toBe(false)
+ })
+ it('join keeps style', () => {
+ expect(joinPath('C:\\Users\\x', '.claude-flow', 'console')).toBe('C:\\Users\\x\\.claude-flow\\console')
+ expect(joinPath('/work', '.claude-flow')).toBe('/work/.claude-flow')
+ })
+ it('join does not double a trailing separator', () => {
+ expect(joinPath('C:\\Users\\x\\', 'a')).toBe('C:\\Users\\x\\a')
+ expect(joinPath('c:/Users/x/', 'a/b')).toBe('c:/Users/x/a/b')
+ expect(joinPath('/work/', 'a')).toBe('/work/a')
+ })
+ it('same path', () => {
+ expect(samePath('c:\\users\\mariu\\', 'C:\\Users\\mariu')).toBe(true)
+ expect(samePath('C:/Users/mariu', 'c:\\users\\MARIU')).toBe(true)
+ expect(samePath('/a/B', '/a/b')).toBe(false)
+ })
+ it('parent segments, either separator on a Windows path', () => {
+ expect(hasParentSegment('C:\\a\\..\\b')).toBe(true)
+ expect(hasParentSegment('c:/a/../b')).toBe(true)
+ expect(hasParentSegment('C:\\a\\b..c')).toBe(false)
+ expect(hasParentSegment('/a/../b')).toBe(true)
+ expect(hasParentSegment('/a\\..\\b')).toBe(false) // a POSIX name may hold a backslash
+ })
+ it('normalises in the style it was written', () => {
+ expect(normalizePath('/a//./b/')).toBe('/a/b')
+ expect(normalizePath('C:\\a\\.\\b')).toBe('C:\\a\\b')
+ expect(normalizePath('c:/a//b')).toBe('c:/a/b')
+ expect(normalizePath('C:\\x\\proj/out/./f.md')).toBe('C:\\x\\proj/out/f.md')
+ expect(normalizePath('\\\\srv\\share\\a')).toBe('\\\\srv\\share\\a')
+ })
+ it('protected folders are matched ignoring case on a Windows path, exactly on a POSIX one', () => {
+ for (const p of ['C:/proj/.Claude-Flow/Console/x', 'C:/proj/.CLAUDE-FLOW/protector-mod/y', 'c:/proj/.claude-flow/console/x', 'C:/proj/.Claude-Flow']) expect(isProtectedPath(p), p).toBe(true)
+ expect(isProtectedPath('C:/proj/src/x')).toBe(false)
+ // POSIX is case-sensitive and stays so (pinned from base behaviour).
+ expect(isProtectedPath('/proj/.Claude-Flow/Console/x')).toBe(false)
+ expect(isProtectedPath('/proj/.claude-flow/console/x')).toBe(true)
+ })
+ it('an envelope refuses a differently-cased protected drive path and accepts an ordinary one', () => {
+ const base = { name: 'a', toolClasses: ['read'], repos: [], network: [], secretEnv: [], spend: { hourUsd: 1, dayUsd: 1, totalUsd: 1 }, concurrency: 1, maxDurationMs: 3_600_000, verify: [], acceptWithoutAnatole: false }
+ const withPath = (p: string) => validateEnvelope({ ...base, paths: [p] })
+
+ expect(withPath('C:/proj/.Claude-Flow/Console/x').ok).toBe(false)
+ expect(withPath('C:/proj/.CLAUDE-FLOW/protector-mod/y').ok).toBe(false)
+ expect(withPath('C:/proj/src/x').ok).toBe(true)
+ })
+ it('below and trimTrailing', () => {
+ expect(below('/work', '/work/a/b')).toEqual(['a', 'b'])
+ expect(below('/work', '/workshop/a')).toBeNull()
+ expect(below('/work', '/work')).toBeNull()
+ expect(below('C:\\Work\\', 'c:/work/a/b')).toEqual(['a', 'b'])
+ expect(below('C:\\Work', 'D:\\work\\a')).toBeNull()
+ expect(trimTrailing('C:\\a\\\\')).toBe('C:\\a')
+ expect(trimTrailing('/a//')).toBe('/a')
+ })
+ it('Windows containment: a sibling that shares a prefix is not inside, another drive is not inside, either separator and any case is', () => {
+ expect(below('C:\\proj', 'C:\\project\\x')).toBeNull()
+ expect(below('C:\\proj', 'C:\\proj\\x')).toEqual(['x'])
+ expect(below('C:\\proj', 'c:/PROJ/x')).toEqual(['x'])
+ expect(below('C:\\proj', 'D:\\proj\\x')).toBeNull()
+ expect(below('\\\\srv\\share\\a', '\\\\srv\\share\\a\\b')).toEqual(['b'])
+ expect(below('\\\\srv\\share\\a', '\\\\srv\\share\\ab')).toBeNull()
+ })
+ it('Windows parent segments are seen with either separator, in a drive path and in a share path', () => {
+ expect(hasParentSegment('C:/a\\..\\b')).toBe(true)
+ expect(hasParentSegment('\\\\srv\\share\\..\\x')).toBe(true)
+ expect(hasParentSegment('C:\\a\\b..c\\d')).toBe(false)
+ })
+ it('samePath rule: if either side is a Windows path, both compare ignoring case, separator style and trailing separators (a UNC share equals its // form)', () => {
+ expect(samePath('\\\\srv\\share\\x', '//srv/share/x')).toBe(true)
+ expect(samePath('\\\\srv\\share\\x', '\\\\SRV\\share\\x\\')).toBe(true)
+ expect(samePath('\\\\srv\\share\\x', '\\\\srv\\share\\y')).toBe(false)
+ })
+})
diff --git a/plugins/ruflo-console/tests/state-keys.spec.ts b/plugins/ruflo-console/tests/state-keys.spec.ts
new file mode 100644
index 0000000000..edaecb98b7
--- /dev/null
+++ b/plugins/ruflo-console/tests/state-keys.spec.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from 'vitest'
+
+import { storeKeyOf, termStoreKeyOf } from '../hooks/state'
+
+describe('workspace store keys', () => {
+ it('a Windows folder gives one key whatever its drive-letter case, separator style or trailing separator', () => {
+ const spellings = ['c:\\users\\mariu\\', 'C:\\Users\\mariu', 'C:/Users/mariu/', 'c:/USERS/Mariu//']
+
+ for (const key of [storeKeyOf, termStoreKeyOf]) expect(new Set(spellings.map(key)).size, key.name).toBe(1)
+ expect(storeKeyOf('C:\\Users\\mariu')).toBe('ruflo-console/ui:c:/users/mariu')
+ expect(termStoreKeyOf('c:\\users\\mariu\\')).toBe('ruflo-console/term:c:/users/mariu')
+ })
+
+ it('a share path is folded the same way, and two different folders keep two keys', () => {
+ expect(storeKeyOf('\\\\SRV\\Share\\a\\')).toBe(storeKeyOf('\\\\srv\\share\\a'))
+ expect(storeKeyOf('C:\\a')).not.toBe(storeKeyOf('D:\\a'))
+ expect(storeKeyOf('C:\\a')).not.toBe(storeKeyOf('C:\\ab'))
+ })
+
+ it('a POSIX folder keeps today\'s exact key (case and trailing slash are significant there)', () => {
+ expect(storeKeyOf('/work')).toBe('ruflo-console/ui:/work')
+ expect(storeKeyOf('/Work/Proj/')).toBe('ruflo-console/ui:/Work/Proj/')
+ expect(termStoreKeyOf('/work')).toBe('ruflo-console/term:/work')
+ expect(termStoreKeyOf('/Work/Proj/')).toBe('ruflo-console/term:/Work/Proj/')
+ })
+})
diff --git a/plugins/ruflo-console/tests/tui-actions.spec.ts b/plugins/ruflo-console/tests/tui-actions.spec.ts
index 783a38b8be..21da36c273 100644
--- a/plugins/ruflo-console/tests/tui-actions.spec.ts
+++ b/plugins/ruflo-console/tests/tui-actions.spec.ts
@@ -90,7 +90,10 @@ describe('a change asked for by name', () => {
await ask(t, 'swarm-stop')
t.press('y')
- await settle(600)
+ // 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)
const after = ran().slice(before)
diff --git a/plugins/ruflo-console/tests/wf-worktrees-view.spec.ts b/plugins/ruflo-console/tests/wf-worktrees-view.spec.ts
index 96169a5542..3b8fe92e34 100644
--- a/plugins/ruflo-console/tests/wf-worktrees-view.spec.ts
+++ b/plugins/ruflo-console/tests/wf-worktrees-view.spec.ts
@@ -4,7 +4,7 @@
* Pure and fast: a stand-in for git and /proc (tests/fixtures/wf-git.ts), no engine. Run with
* npx vitest run plugins/ruflo-console/tests/wf-worktrees-view.spec.ts --testTimeout=30000
*/
-import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'
import { newWfUi } from '../hooks/data/workflows-nav'
import { AHEAD_ARGV, REMOVE_ARGV, type WtRead } from '../hooks/data/wf-worktrees'
@@ -15,6 +15,12 @@ import { registerSlot, resetSlots, slotsFor, type SlotEnv } from '../hooks/views
import { boardRows, clock, nameOf, ordered, refreshWorktrees, registerWorktreeSlots, removalSpec, resetWorktrees, storeFor, wireWfWorktrees } from '../hooks/views/wf-worktrees'
import { BASE_PROCS, block, flatWords, ioOf, kit, NOW, procLines, ROOT, wt, words, world, type World } from './fixtures/wf-git'
+const realPlatform = Object.getOwnPropertyDescriptor(process, 'platform')
+
+// The /proc check is Linux-only (checkProcs asks the engine's own platform); these tests stand in for a Linux host whatever runs them.
+beforeAll(() => { Object.defineProperty(process, 'platform', { value: 'linux', configurable: true }) })
+afterAll(() => { if (realPlatform !== undefined) Object.defineProperty(process, 'platform', realPlatform) })
+
describe('the board and the confirm-gated removal', () => {
let state: State
let w: World
diff --git a/plugins/ruflo-console/tests/wf-worktrees.spec.ts b/plugins/ruflo-console/tests/wf-worktrees.spec.ts
index 81dc4e2d31..b317ed802e 100644
--- a/plugins/ruflo-console/tests/wf-worktrees.spec.ts
+++ b/plugins/ruflo-console/tests/wf-worktrees.spec.ts
@@ -4,7 +4,7 @@
* Pure and fast: a stand-in for git and /proc (tests/fixtures/wf-git.ts), no engine. Run with
* npx vitest run plugins/ruflo-console/tests/wf-worktrees.spec.ts --testTimeout=30000
*/
-import { describe, expect, it } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
import { AHEAD_ARGV, BATCH, checkProcs, DIRTY_CAP, inUseOf, isRemovableDir, isSafePath, LIST_MAX_BYTES, makerOf, MAX_PROBED, MIN_AGE_MS, MIN_PROCS, parseProcs, parseWorktrees, planRemoval, PROCS_ARGV, PROCS_FRESH_MS, readWorktrees, REMOVE_ARGV, REMOVE_MAX, whyKept, type WtRow } from '../hooks/data/wf-worktrees'
import type { WfAgent, WfRun } from '../hooks/data/workflows'
@@ -48,20 +48,20 @@ describe('the live-process check', () => {
})
it('refuses to answer when it looks blind: fewer than the minimum working directories', async () => {
- const blind = parseProcs(procLines(Array.from({ length: MIN_PROCS - 1 }, (_, i) => [i + 1, 'cwd', '/'] as [number, string, string])), [wt('a')], NOW)
+ const blind = parseProcs(procLines(Array.from({ length: MIN_PROCS - 1 }, (_, i) => [i + 1, 'cwd', '/'] as [number, string, string])), [wt('a')], NOW, 'linux')
expect(blind.ok).toBe(false)
expect(blind.why).toMatch(/may be blind/)
expect(inUseOf(blind, wt('a'))).toBeNull()
- const none = await checkProcs({ run: async () => ({ stdout: '', stderr: '', exitCode: 1 }), stat: async () => undefined }, [wt('a')], NOW)
+ const none = await checkProcs({ run: async () => ({ stdout: '', stderr: '', exitCode: 1 }), stat: async () => undefined }, [wt('a')], NOW, 'linux')
expect(none).toMatchObject({ ok: false, why: 'the process listing did not answer' })
- expect((await checkProcs({ run: async () => Promise.reject(new Error('x')), stat: async () => undefined }, [wt('a')], NOW)).ok).toBe(false)
+ expect((await checkProcs({ run: async () => Promise.reject(new Error('x')), stat: async () => undefined }, [wt('a')], NOW, 'linux')).ok).toBe(false)
})
it('reads a listing that exited non-zero (other users\' processes are unreadable) when it holds what it needs', async () => {
- const check = await checkProcs(ioOf(world()), [wt('busy')], NOW)
+ const check = await checkProcs(ioOf(world()), [wt('busy')], NOW, 'linux')
expect(check.ok).toBe(true)
expect(inUseOf(check, wt('busy'))).toBe(2)
@@ -155,12 +155,32 @@ describe('who made a worktree', () => {
})
})
+describe('the process probe off Linux', () => {
+ const spy = () => { const run = vi.fn(async () => ({ stdout: '', stderr: '', exitCode: 0 })); return { io: { run, stat: async () => undefined }, run } }
+
+ it.each(['win32', 'darwin'])('answers "not available on this system" on %s without spawning', async platform => {
+ const { io, run } = spy()
+ const check = await checkProcs(io, [wt('a')], NOW, platform)
+
+ expect(run).not.toHaveBeenCalled()
+ expect(check).toMatchObject({ ok: false, seen: 0, why: 'the live-process check is not available on this system' })
+ expect(inUseOf(check, wt('a'))).toBeNull()
+ })
+
+ it('still spawns the find on linux', async () => {
+ const { io, run } = spy()
+
+ await checkProcs(io, [wt('a')], NOW, 'linux')
+ expect(run).toHaveBeenCalledWith(PROCS_ARGV, 30_000)
+ })
+})
+
describe('the probes', () => {
it('uses only fixed argv: git -C <dir> ..., one find, never a shell string', async () => {
const w = world()
await readWorktrees(ioOf(w), { cwd: wt('current'), nowMs: NOW, runs: [] })
- await checkProcs(ioOf(w), [wt('old')], NOW)
+ await checkProcs(ioOf(w), [wt('old')], NOW, 'linux')
expect(w.calls.length).toBeGreaterThan(10)
for (const argv of w.calls) {
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 35a7812fa8..8d21493a6a 100644
--- a/plugins/ruflo-console/tests/windows-drive-path-sites.spec.ts
+++ b/plugins/ruflo-console/tests/windows-drive-path-sites.spec.ts
@@ -7,13 +7,23 @@ import type { ReaderFs } from '../hooks/data/files'
// #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
// the project folder" guard, so all three fail closed on Windows regardless of settings —
-// matching the already-fixed #4175 bug in register.ts (see abs-path.spec.ts).
+// matching the already-fixed #4175 bug in register.ts.
+//
+// #4036: PR consolidated path helpers onto `paths.ts`. On a Windows base, `joinPath` now uses
+// the base's own separator (`\\`), so the probe path for `C:\Users\dev\project` + `docs` is
+// `C:\Users\dev\project\docs` rather than the earlier `C:\Users\dev\project/docs`. The
+// semantics are the same on a real Windows filesystem; `fsWithDir` is made separator-agnostic
+// here so the test continues to anchor the behaviour, not the exact string.
const WIN_CWD = 'C:\\Users\\dev\\project'
+const normSeps = (p: string): string => p.replace(/[\\/]+/g, '/')
+
function fsWithDir(dirPath: string): Pick<ReaderFs, 'stat' | 'list' | 'read'> {
+ const target = normSeps(dirPath)
+
return {
- stat: async (path: string) => (path === dirPath ? { kind: 'dir' } : undefined),
+ stat: async (path: string) => (normSeps(path) === target ? { kind: 'dir' } : undefined),
list: async () => [],
read: async () => '',
}
diff --git a/plugins/ruflo-console/tests/write-argv.spec.ts b/plugins/ruflo-console/tests/write-argv.spec.ts
index 91b81878a5..d731cd6cad 100644
--- a/plugins/ruflo-console/tests/write-argv.spec.ts
+++ b/plugins/ruflo-console/tests/write-argv.spec.ts
@@ -55,11 +55,12 @@ describe('which flavor, and when', () => {
expect(asked).toEqual([['uname', '-s']])
})
- it('without an answer, the engine platform decides: darwin and the BSDs posix, everything else gnu', () => {
+ it('without an answer, the engine platform decides: darwin and the BSDs posix, Windows host-fs, everything else gnu', () => {
for (const platform of ['darwin', 'freebsd', 'openbsd', 'netbsd']) expect(flavorOfPlatform(platform), platform).toBe('posix')
- for (const platform of ['linux', 'win32', 'aix', null, 42]) expect(flavorOfPlatform(platform), String(platform)).toBe('gnu')
+ for (const platform of ['linux', 'aix', null, 42]) expect(flavorOfPlatform(platform), String(platform)).toBe('gnu')
+ expect(flavorOfPlatform('win32')).toBe('host-fs')
// In this test process the default reads Node's own process.platform.
- expect(flavorOfPlatform()).toBe(process.platform === 'darwin' || process.platform.endsWith('bsd') ? 'posix' : 'gnu')
+ expect(flavorOfPlatform()).toBe(process.platform === 'win32' ? 'host-fs' : process.platform === 'darwin' || process.platform.endsWith('bsd') ? 'posix' : 'gnu')
})
it.each([
diff --git a/plugins/ruflo-console/tests/write-flavor.spec.ts b/plugins/ruflo-console/tests/write-flavor.spec.ts
new file mode 100644
index 0000000000..0bc6877774
--- /dev/null
+++ b/plugins/ruflo-console/tests/write-flavor.spec.ts
@@ -0,0 +1,340 @@
+/**
+ * The Windows write flavor (A4): Claude Code's process environment on Windows has no uname, dd, sh, install, mkdir or cp, so there every
+ * console disk write goes through the host's own file API (`$.fs.read` / `$.fs.write` / `$.fs.exists`). These tests pin: the flavor choice,
+ * that the Linux GNU and macOS/BSD argv are byte-identical to what shipped before, and what `writeVia` does on a fake host-fs.
+ */
+import { createHash } from 'node:crypto'
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+
+import { BATCH_MAX, flush, pendingOf, queueLine, resetIo } from '../hooks/activity-io'
+import { encodeEvent, EVENTS_FILE } from '../hooks/data/activity-store'
+import { appendArgv } from '../hooks/data/append-argv'
+import { touchArgv } from '../hooks/data/ap-journal'
+import { copyExclusiveArgv, newFileArgv, removeFileArgv, replaceFileArgv } from '../hooks/data/wf-file'
+import { flavorOfKernel, flavorOfPlatform, setWriteFlavor, startWriteFlavor, writeFlavorReady } from '../hooks/data/write-flavor'
+import { KILL_CLEARED } from '../hooks/data/ap-envelope'
+import { HOST_FS_MAX, writeVia, type WriteHost } from '../hooks/data/write-via'
+
+const P = '/work/proj/a b;$(x).jsonl'
+const S = '/work/proj/src.jsonl'
+const digest = (flavor: 'gnu' | 'posix') =>
+ createHash('sha256')
+ .update(JSON.stringify([appendArgv(P, flavor), newFileArgv(P, true, flavor), newFileArgv(P, false, flavor), replaceFileArgv(P, true, flavor), replaceFileArgv(P, false, flavor), copyExclusiveArgv(S, P, flavor), touchArgv(P, flavor), removeFileArgv(P)]))
+ .digest('hex')
+
+afterEach(() => {
+ setWriteFlavor(null)
+ resetIo()
+})
+
+describe('which flavor', () => {
+ it('Windows takes host-fs; Linux gnu; darwin and the BSDs posix', () => {
+ expect(flavorOfPlatform('win32')).toBe('host-fs')
+ expect(flavorOfPlatform('linux')).toBe('gnu')
+ expect(flavorOfPlatform('darwin')).toBe('posix')
+ expect(flavorOfPlatform('freebsd')).toBe('posix')
+ })
+
+ it('the uname answers are unchanged: Linux gnu, every other kernel posix', () => {
+ expect(flavorOfKernel('Linux')).toBe('gnu')
+ expect(flavorOfKernel('Darwin')).toBe('posix')
+ })
+
+ it('a Windows working directory is a Windows engine even where the runtime does not expose its platform', async () => {
+ const asked: (readonly string[])[] = []
+
+ expect(await startWriteFlavor(async argv => (asked.push(argv), { exitCode: 0, stdout: 'Linux\n' }), undefined, 'C:\\Users\\me\\proj')).toBe('host-fs')
+ expect(asked).toEqual([])
+ })
+
+ it('on a Windows engine no uname is run at all', async () => {
+ const asked: (readonly string[])[] = []
+
+ expect(await startWriteFlavor(async argv => (asked.push(argv), { exitCode: 0, stdout: 'Linux\n' }), 'win32')).toBe('host-fs')
+ expect(await writeFlavorReady()).toBe('host-fs')
+ expect(asked).toEqual([])
+ })
+
+ it('elsewhere the detection is the uname one', async () => {
+ expect(await startWriteFlavor(async () => ({ exitCode: 0, stdout: 'Darwin\n' }), 'linux')).toBe('posix')
+ })
+})
+
+describe('the argv that shipped before is unchanged', () => {
+ it('GNU (Linux) literals', () => {
+ expect(appendArgv(P, 'gnu')).toEqual(['dd', `of=${P}`, 'oflag=append', 'conv=notrunc', 'bs=1M', 'iflag=fullblock', 'status=none'])
+ expect(newFileArgv(P, true, 'gnu')).toEqual(['dd', `of=${P}`, 'conv=excl', 'status=none'])
+ expect(newFileArgv(P, false, 'gnu')).toEqual(['install', '-D', '-m', '0644', '/dev/stdin', '--', P])
+ expect(replaceFileArgv(P, true, 'gnu')).toEqual(['dd', `of=${P}`, 'status=none'])
+ expect(copyExclusiveArgv(S, P, 'gnu')).toEqual(['cp', '--no-clobber', '--', S, P])
+ expect(touchArgv(P, 'gnu')).toEqual(['install', '-D', '-m', '600', '/dev/null', P])
+ expect(removeFileArgv(P)).toEqual(['rm', '-f', '--', P])
+ })
+
+ it('whole-set digests of the GNU and the BSD argv (taken before this change)', () => {
+ expect(digest('gnu')).toBe('cfd9124d0ee8208f81f0c8dc87ccdc9505b17d632267f9b8a942a6ae987094ad')
+ expect(digest('posix')).toBe('4c60ee6b0510418188772bc443afc9b8744a46d18e6b07c82837f8960a4e1160')
+ })
+
+ it('writeVia on gnu and posix is the same host.run call as before (argv, timeout, stdin)', async () => {
+ const calls: unknown[][] = []
+ const host: WriteHost = {
+ fs: { read: async () => '', stat: async () => undefined, list: async () => [] },
+ run: async (argv, timeout, stdin) => (calls.push([argv, timeout, stdin]), { exitCode: 0, stdout: '', stderr: '' }),
+ }
+
+ await writeVia('gnu', host, { kind: 'append', path: P, text: 'x\n' })
+ await writeVia('posix', host, { kind: 'create-excl', path: P, text: 'y' })
+ await writeVia('gnu', host, { kind: 'create-dirs', path: P, text: 'z' })
+ await writeVia('posix', host, { kind: 'replace', path: P, text: 'r', hasDir: false })
+ await writeVia('gnu', host, { kind: 'copy-no-clobber', path: P, from: S })
+ await writeVia('posix', host, { kind: 'touch', path: P })
+
+ expect(calls).toEqual([
+ [appendArgv(P, 'gnu'), 10_000, 'x\n'],
+ [newFileArgv(P, true, 'posix'), 10_000, 'y'],
+ [newFileArgv(P, false, 'gnu'), 10_000, 'z'],
+ [replaceFileArgv(P, false, 'posix'), 10_000, 'r'],
+ [copyExclusiveArgv(S, P, 'gnu'), 10_000, undefined],
+ [touchArgv(P, 'posix'), 10_000, undefined],
+ ])
+ })
+})
+
+/** A fake host with a map for a disk and no way to run anything: a run is a test failure. */
+function fsHost(files: Record<string, string> = {}, extra: { dirs?: string[]; links?: string[]; noWrite?: boolean } = {}) {
+ const disk = new Map(Object.entries(files))
+ const writes: [string, string][] = []
+ const dirs = new Set(extra.dirs ?? [])
+ const links = new Set(extra.links ?? [])
+ const host: WriteHost = {
+ fs: {
+ read: async path => {
+ const found = disk.get(path)
+
+ if (found === undefined) throw new Error('missing')
+
+ return found
+ },
+ stat: async path => (links.has(path) ? { kind: 'other', isLink: true } : disk.has(path) ? { kind: 'file', size: disk.get(path)!.length } : dirs.has(path) ? { kind: 'dir' } : undefined),
+ list: async () => [],
+ exists: async path => disk.has(path) || dirs.has(path) || links.has(path),
+ ...(extra.noWrite === true ? {} : { write: async (path: string, text: string) => void (writes.push([path, text]), disk.set(path, text)) }),
+ },
+ run: async argv => {
+ throw new Error(`host.run must not be called on host-fs: ${argv.join(' ')}`)
+ },
+ }
+
+ return { host, disk, writes }
+}
+
+describe('writeVia on host-fs', () => {
+ it('append concatenates onto what is there, and a missing file reads as empty', async () => {
+ const { host, disk } = fsHost({ '/p/a.jsonl': '{"n":1}\n' })
+
+ expect((await writeVia('host-fs', host, { kind: 'append', path: '/p/a.jsonl', text: '{"n":2}\n' })).exitCode).toBe(0)
+ expect(disk.get('/p/a.jsonl')).toBe('{"n":1}\n{"n":2}\n')
+ expect((await writeVia('host-fs', host, { kind: 'append', path: '/p/new.jsonl', text: 'first\n' })).exitCode).toBe(0)
+ expect(disk.get('/p/new.jsonl')).toBe('first\n')
+ })
+
+ it('append past 4 MiB is refused, and nothing is written', async () => {
+ const { host, disk, writes } = fsHost({ '/p/a.jsonl': 'x'.repeat(HOST_FS_MAX - 5) })
+ const result = await writeVia('host-fs', host, { kind: 'append', path: '/p/a.jsonl', text: 'y'.repeat(10) })
+
+ expect(result.exitCode).not.toBe(0)
+ expect(result.stderr).toMatch(/4 MiB/)
+ expect(writes).toEqual([])
+ expect(disk.get('/p/a.jsonl')).toHaveLength(HOST_FS_MAX - 5)
+ })
+
+ it('create-excl refuses an existing file with the "already exists" text, and writes nothing', async () => {
+ const { host, writes } = fsHost({ '/p/a.md': 'mine' })
+ const result = await writeVia('host-fs', host, { kind: 'create-excl', path: '/p/a.md', text: 'new' })
+
+ expect(result.exitCode).not.toBe(0)
+ expect(result.stderr).toContain('already exists: the console does not overwrite a file; pick another name')
+ expect(writes).toEqual([])
+ })
+
+ it('create-excl and create-dirs make a new file (the host write makes the folders)', async () => {
+ const { host, disk } = fsHost()
+
+ expect((await writeVia('host-fs', host, { kind: 'create-excl', path: '/p/a.md', text: 'a' })).exitCode).toBe(0)
+ expect((await writeVia('host-fs', host, { kind: 'create-dirs', path: '/p/deep/er/b.md', text: 'b' })).exitCode).toBe(0)
+ expect([...disk]).toEqual([['/p/a.md', 'a'], ['/p/deep/er/b.md', 'b']])
+ })
+
+ it('refuses a folder or a link as the target, for every kind', async () => {
+ const { host, writes } = fsHost({}, { dirs: ['/p/folder'], links: ['/p/link'] })
+
+ for (const path of ['/p/folder', '/p/link']) {
+ for (const kind of ['append', 'replace', 'touch'] as const) {
+ const result = await writeVia('host-fs', host, { kind, path, text: 'x' })
+
+ expect(result.exitCode, `${kind} ${path}`).not.toBe(0)
+ expect(result.stderr).toMatch(/refused/)
+ }
+ }
+
+ expect(writes).toEqual([])
+ })
+
+ it('replace overwrites; touch keeps an existing file and makes an empty one', async () => {
+ const { host, disk } = fsHost({ '/p/s.json': 'old', '/p/keep': 'content' })
+
+ expect((await writeVia('host-fs', host, { kind: 'replace', path: '/p/s.json', text: 'new', hasDir: true })).exitCode).toBe(0)
+ expect((await writeVia('host-fs', host, { kind: 'touch', path: '/p/keep' })).exitCode).toBe(0)
+ expect((await writeVia('host-fs', host, { kind: 'touch', path: '/p/flag' })).exitCode).toBe(0)
+ expect([...disk]).toEqual([['/p/s.json', 'new'], ['/p/keep', 'content'], ['/p/flag', '']])
+ })
+
+ it('copy-no-clobber copies the source to a new name and refuses an existing target or a missing source', async () => {
+ const { host, disk } = fsHost({ '/p/j.jsonl': 'journal', '/p/taken': 'x' })
+
+ expect((await writeVia('host-fs', host, { kind: 'copy-no-clobber', from: '/p/j.jsonl', path: '/p/j.jsonl.1' })).exitCode).toBe(0)
+ expect(disk.get('/p/j.jsonl.1')).toBe('journal')
+ expect((await writeVia('host-fs', host, { kind: 'copy-no-clobber', from: '/p/j.jsonl', path: '/p/taken' })).exitCode).not.toBe(0)
+ expect(disk.get('/p/taken')).toBe('x')
+ expect((await writeVia('host-fs', host, { kind: 'copy-no-clobber', from: '/p/none', path: '/p/new' })).exitCode).not.toBe(0)
+ expect(disk.has('/p/new')).toBe(false)
+ })
+
+ it('a host without a file write, or a write that rejects, is a refusal with a reason, never a throw', async () => {
+ const none = fsHost({}, { noWrite: true })
+ const refused = await writeVia('host-fs', none.host, { kind: 'replace', path: '/p/a', text: 'x', hasDir: true })
+
+ expect(refused.exitCode).not.toBe(0)
+ expect(refused.stderr).toMatch(/file API/)
+
+ const failing = fsHost()
+
+ failing.host.fs.write = async () => {
+ throw new Error('EACCES: permission denied')
+ }
+ expect((await writeVia('host-fs', failing.host, { kind: 'replace', path: '/p/a', text: 'x', hasDir: true })).stderr).toMatch(/EACCES/)
+ })
+})
+
+describe('the Events store on host-fs', () => {
+ const CWD = 'C:/work/proj'
+ const FILE = `${CWD}/${EVENTS_FILE}`
+ const line = (text: string) => encodeEvent({ kind: 'swarm', text, atMs: 1_800_000_000_000 })
+
+ beforeEach(() => setWriteFlavor('host-fs'))
+
+ it('persists a batch with no process run: the file is created, no mkdir runs, a .gitignore is written once', async () => {
+ const { host, disk } = fsHost({}, { dirs: [CWD] })
+
+ queueLine(FILE, 2 * 1024 * 1024, line('a'))
+ queueLine(FILE, 2 * 1024 * 1024, line('b'))
+ await flush(host as never, CWD, FILE, 1)
+
+ expect(pendingOf(FILE)).toBe(0)
+ expect(disk.get(FILE)?.split('\n').filter(Boolean)).toHaveLength(2)
+ expect(disk.get(`${CWD}/.claude-flow/console/.gitignore`)).toContain('*')
+ })
+
+ it('rotates where the GNU path rotates (past the cap), by a whole rewrite to the newest half', async () => {
+ const cap = 4_000
+ const { host, disk } = fsHost({}, { dirs: [CWD] })
+ const big = line('x'.repeat(400))
+
+ for (let i = 0; i < Math.ceil((cap * 2) / big.length); i++) disk.set(FILE, (disk.get(FILE) ?? '') + big)
+ queueLine(FILE, cap, line('tail'))
+ await flush(host as never, CWD, FILE, 1)
+
+ expect(disk.get(FILE)!.length).toBeLessThan(cap)
+ expect(disk.get(FILE)!.endsWith(line('tail'))).toBe(true)
+ expect(disk.has(`${FILE}.tmp`)).toBe(false)
+ })
+
+ it('a batch is never over the batch cap on host-fs either', () => {
+ expect(BATCH_MAX).toBe(32 * 1024)
+ })
+})
+
+describe('a confirmed write on host-fs is the host write, not an argv', () => {
+ it('the run summary spec carries the write op (and the GNU spec does not)', async () => {
+ const { exportSpec } = await import('../hooks/data/wf-export')
+ const win = exportSpec('C:/p/s.md', '# run', 'r', false, 'host-fs')
+ const linux = exportSpec('/p/s.md', '# run', 'r', true, 'gnu')
+
+ expect(win.write).toEqual({ kind: 'create-dirs', path: 'C:/p/s.md', text: '# run' })
+ expect(linux.write).toBeUndefined()
+ expect(linux.argv).toEqual(['dd', 'of=/p/s.md', 'conv=excl', 'status=none'])
+ })
+})
+
+describe('the autopilot kill flag on a machine with no delete', () => {
+ async function world() {
+ const { CWD, KILL, envOf, rig, stateWith, T0 } = await import('./fixtures/ap-rig')
+ const { killSeen } = await import('../hooks/data/ap-guard')
+ const live = await import('../hooks/ap-live')
+ const panel = await import('../hooks/views/ap-panel')
+ const r = rig()
+ const state = stateWith([], 'off')
+ const fs = r.host.fs as unknown as Record<string, unknown>
+
+ fs.write = async (p: string, t: string) => void r.files.set(p, t)
+ fs.exists = async (p: string) => r.files.has(p)
+ live.wireAutopilot(state, r.host)
+
+ return { r, state, KILL, CWD, killSeen, live, panel, envOf, T0 }
+ }
+
+ it('host-fs: stop -> flag seen -> a start is refused (autopilot is not yet available there) and leaves it -> clearKill writes the marker (not a delete) -> not seen -> stop again -> seen', async () => {
+ setWriteFlavor('host-fs')
+
+ const { r, state, KILL, CWD, killSeen, live, panel, envOf, T0 } = await world()
+
+ await live.stopNow(state, r.host, 'because')
+ expect(r.files.get(KILL)).toBe('')
+ expect(await killSeen(r.host.fs, CWD)).toBe(true)
+
+ panel.editDraft(panel.draftOf(state), { kind: 'anatole' })
+ await panel.startSpec(envOf(state, T0))?.run?.()
+
+ expect(live.storeOf(state).error).toBe('Autopilot is not yet available on Windows: its journal and path fence need atomic appends and Windows-aware path checks (follow-up).')
+ expect(r.files.has(`${CWD}/.claude-flow/console/autopilot/envelope.json`)).toBe(false)
+ expect(await killSeen(r.host.fs, CWD)).toBe(true)
+
+ await live.clearKill(state, r.host)
+ expect(r.files.get(KILL)).toBe(KILL_CLEARED)
+ expect(await killSeen(r.host.fs, CWD)).toBe(false)
+ expect(r.runs.filter(argv => argv[0] === 'rm')).toEqual([])
+
+ await live.stopNow(state, r.host, 'again')
+ expect(r.files.get(KILL)).toBe('')
+ expect(await killSeen(r.host.fs, CWD)).toBe(true)
+ })
+
+ it('only the exact marker clears; a missing file is not a stop; any other content is', async () => {
+ setWriteFlavor('host-fs')
+
+ const { r, KILL, CWD, killSeen } = await world()
+
+ expect(await killSeen(r.host.fs, CWD)).toBe(false)
+ for (const content of ['', 'cleared\n', 'Cleared', 'x']) {
+ r.files.set(KILL, content)
+ expect(await killSeen(r.host.fs, CWD), JSON.stringify(content)).toBe(true)
+ }
+ r.files.set(KILL, KILL_CLEARED)
+ expect(await killSeen(r.host.fs, CWD)).toBe(false)
+ })
+
+ it('gnu: clearKill is still the same rm -f argv, and a present flag is a stop whatever it holds', async () => {
+ setWriteFlavor('gnu')
+
+ const { r, state, KILL, CWD, killSeen, live } = await world()
+
+ r.files.set(KILL, KILL_CLEARED)
+ expect(await killSeen(r.host.fs, CWD)).toBe(true)
+ await live.clearKill(state, r.host)
+ expect(r.runs).toContainEqual(['rm', '-f', '--', KILL])
+ expect(r.files.has(KILL)).toBe(false)
+ expect(await killSeen(r.host.fs, CWD)).toBe(false)
+ })
+})