🌊 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
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(console): disk writes work on macOS/BSD (append, exclusive create, create-with-folders, copy)
Dragan Spiridonovf59889088843
diff --git a/plugins/ruflo-console/hooks/activity-io.ts b/plugins/ruflo-console/hooks/activity-io.tsindex 70e42d2ad2..a62782f35d 100644--- a/plugins/ruflo-console/hooks/activity-io.ts+++ b/plugins/ruflo-console/hooks/activity-io.ts@@ -2,12 +2,14 @@* The one write path for the Events and Timeline files (ADR-474), with the host's `fs` and `run` passed in so a test supplies its own.* Lines are queued in memory and written in batches (never one write per event): at most one write per file is in flight, each batch* is at most BATCH_MAX bytes, and a failure is remembered and retried later, never thrown. A write appends through the journal's fixed- * argv (GNU `dd oflag=append`, no shell: the path is one element, and an O_APPEND write keeps a batch whole when two consoles share the file). A file past its cap is cut to its newest half through a temporary file and a rename.+ * argv (data/append-argv.ts: GNU `dd oflag=append` with no shell on Linux, a constant `sh -c` script with the path as `$1` on macOS/BSD; the+ * path is one element either way, and one dd block per batch into an O_APPEND file keeps two consoles' batches apart unless a write is split). A file past its cap is cut to its newest half through a temporary file and a rename.* The folder is created once, and nothing is written through a link.*/import { checkNoLinks } from './data/wf-file'import { appendArgv } from './data/append-argv'import { dirOf, newFileArgv, replaceFileArgv } from './data/wf-file'+import { writeFlavorReady } from './data/write-flavor'import { keepNewestHalf, READ_MAX } from './data/activity-store'import type { Host } from './host'@@ -61,12 +63,12 @@ export const forgetChannel = (path: string): void => void channels.delete(path)const tmpOf = (path: string): string => `${path}.tmp`-/** Writes `<dir>/.gitignore` once per folder if there is none (`conv=excl` fails, harmlessly, where one exists). Never throws. */+/** Writes `<dir>/.gitignore` once per folder if there is none (the exclusive create fails, harmlessly, where one exists). Never throws. */async function ensureIgnored(host: IoHost, dir: string): Promise<void> {if (ignored.has(dir)) returnignored.add(dir)- await host.run(['dd', `of=${dir}/.gitignore`, 'conv=excl', 'status=none'], WRITE_TIMEOUT_MS, IGNORE_BODY).catch(() => undefined)+ await host.run(newFileArgv(`${dir}/.gitignore`, true, await writeFlavorReady()), WRITE_TIMEOUT_MS, IGNORE_BODY).catch(() => undefined)}async function rotate(host: IoHost, channel: Channel): Promise<void> {@@ -78,7 +80,8 @@ async function rotate(host: IoHost, channel: Channel): Promise<void> {const kept = size > READ_MAX ? '' : keepNewestHalf(await host.fs.read(channel.path).catch(() => ''), channel.cap)await host.run(['rm', '-f', '--', tmpOf(channel.path)], WRITE_TIMEOUT_MS)- const written = await host.run(newFileArgv(tmpOf(channel.path), true), WRITE_TIMEOUT_MS, kept)+ // 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)if (written.exitCode !== 0) return@@ -126,7 +129,7 @@ export async function flush(host: IoHost, cwd: string, path: string, nowMs: numbif (channel.size === null) channel.size = (await host.fs.stat(path).catch(() => undefined))?.size ?? 0- const result = await host.run(appendArgv(path), WRITE_TIMEOUT_MS, batch.join(''))+ const result = await host.run(appendArgv(path, await writeFlavorReady()), WRITE_TIMEOUT_MS, batch.join(''))if (result.exitCode !== 0) throw new Error(`the write exited ${result.exitCode}`)@@ -152,7 +155,7 @@ export async function replaceFile(host: IoHost, cwd: string, path: string, conteif (!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), WRITE_TIMEOUT_MS, content)+ const result = await host.run(replaceFileArgv(path, hasDir, await writeFlavorReady()), WRITE_TIMEOUT_MS, content)if (result.exitCode === 0) await ensureIgnored(host, dirOf(path))diff --git a/plugins/ruflo-console/hooks/adr.ts b/plugins/ruflo-console/hooks/adr.tsindex e0ac007ed5..e35fd7711f 100644--- a/plugins/ruflo-console/hooks/adr.ts+++ b/plugins/ruflo-console/hooks/adr.ts@@ -14,6 +14,7 @@ import { record as recordEvents } from './data/events'import { readBounded, type ReadCache } from './data/files'import { plain } from './data/parse'import { checkNoLinks, dirOf, newFileArgv, replaceFileArgv } from './data/wf-file'+import { writeFlavorReady } from './data/write-flavor'import type { Host } from './host'import { activeMission, mcOf, record, saveLedger } from './mission-control'import type { MissionRecord } from './mission-types'@@ -190,15 +191,25 @@ async function writeNew(state: State, host: Pick<Host, 'fs' | 'run'>, dir: strinif (!safe.ok) return safe.whyconst hasDir = (await host.fs.stat(dirOf(path)).catch(() => undefined)) !== undefined- const result = await host.run(newFileArgv(path, hasDir), 10_000, text).catch(() => null)+ 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' }))- if (result === null || result.exitCode !== 0) return 'the file could not be created (it may have appeared meanwhile: nothing was overwritten)'+ if (result.exitCode !== 0) return writeFailure(result.exitCode, result.stderr)const back = await host.fs.read(path).catch(() => null)return back === text ? null : 'the file was written but reads back differently'}+/**+ * Why a create failed, in the person's words: the write's own reason (its first stderr line, plain and capped) and that nothing was+ * replaced. It does not guess at a race: a file that appeared meanwhile says so in that reason ("cannot overwrite existing file", "File exists").+ */+export function writeFailure(exitCode: number | null, stderr: string | undefined): string {+ const reason = plain((stderr ?? '').split('\n').map(line => line.trim()).find(line => line !== '') ?? '', 160)++ return `the write failed (${exitCode === null ? 'it could not run' : `exit ${exitCode}`}${reason === '' ? '' : `: ${reason}`}); no file was replaced`+}+/** The new file as the confirm shows it: every line, up to 40, each marked +. */const preview = (text: string): string => `${text.split('\n').slice(0, 40).map(line => `+${line}`).join('\n')}${text.split('\n').length > 40 ? '\n+… (the rest of the file is the same template)' : ''}`@@ -339,7 +350,7 @@ export async function statusSpec(state: State, host: Pick<Host, 'fs' | 'run' | 'if (now !== change.before) return say(state, host, `change ADR ${doc.number ?? doc.file}`, false, [...done, `${change.file} changed since the diff was shown: nothing was written to it. Ask again.`])- const result = await host.run(replaceFileArgv(path, true), 10_000, change.after).catch(() => null)+ const result = await host.run(replaceFileArgv(path, true, await writeFlavorReady()), 10_000, change.after).catch(() => null)const back = await host.fs.read(path).catch(() => null)if (result === null || result.exitCode !== 0 || back !== change.after) return say(state, host, `change ADR ${doc.number ?? doc.file}`, false, [...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.tsindex 34367ba446..bd478d9c8a 100644--- a/plugins/ruflo-console/hooks/ap-live.ts+++ b/plugins/ruflo-console/hooks/ap-live.ts@@ -14,6 +14,7 @@ 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 { writeFlavorReady } from './data/write-flavor'import { cleanText } from './data/wf-clean'import { tierOf, tunablesFrom } from './data/ap-adapt'import { adaptPass, rotate } from './ap-maint'@@ -166,9 +167,9 @@ export function appendEvents(state: State, host: Host, events: readonly JournalEreturn false}- if ((await host.fs.stat(path).catch(() => undefined)) === undefined) await host.run(touchArgv(path), 10_000)+ if ((await host.fs.stat(path).catch(() => undefined)) === undefined) await host.run(touchArgv(path, await writeFlavorReady()), 10_000)- const result = await host.run(appendArgv(path), 10_000, events.map(encodeLine).join(''))+ const result = await host.run(appendArgv(path, await writeFlavorReady()), 10_000, events.map(encodeLine).join(''))if (result.exitCode !== 0) {store.error = `the journal write exited ${result.exitCode}`@@ -222,7 +223,7 @@ export async function stopNow(state: State, host: Host, reason = 'stopped by youhost.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), 10_000).then(result => result.exitCode === 0, () => false) : false+ const flagged = clear.ok ? await host.run(touchArgv(flag, await writeFlavorReady()), 10_000).then(result => result.exitCode === 0, () => false) : falseconst 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.@@ -262,7 +263,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), 10_000, `${JSON.stringify(sealed, null, 2)}\n`)+ const result = await host.run(replaceFileArgv(path, hasDir, await writeFlavorReady()), 10_000, `${JSON.stringify(sealed, null, 2)}\n`)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.tsindex ee9e4b9147..fd32408d8f 100644--- a/plugins/ruflo-console/hooks/ap-maint.ts+++ b/plugins/ruflo-console/hooks/ap-maint.ts@@ -4,7 +4,8 @@*/import type { Host } from './host'import type { Store } from './ap-live'-import { checkNoLinks, replaceFileArgv } from './data/wf-file'+import { checkNoLinks, copyExclusiveArgv, replaceFileArgv } from './data/wf-file'+import { writeFlavorReady } from './data/write-flavor'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'@@ -40,9 +41,9 @@ export async function rotate(store: Store, host: Host, cwd: string, nowMs: numbeif (lines === '') return- // The archive must be a new name with no link on the way: a pre-made link there would make `cp --no-clobber` skip and the old journal be lost.+ // 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(['cp', '--no-clobber', '--', path, archive], 30_000).catch(() => ({ exitCode: 1 })) : { exitCode: 1 }+ const copied = clear.ok ? await host.run(copyExclusiveArgv(path, archive, await writeFlavorReady()), 30_000).catch(() => ({ exitCode: 1 })) : { exitCode: 1 }const saved = (await host.fs.stat(archive).catch(() => undefined)) !== undefinedif (copied.exitCode !== 0 || !saved) return@@ -54,7 +55,7 @@ export async function rotate(store: Store, host: Host, cwd: string, nowMs: numbetry {if (pin !== null) await setPin(store, host, cwd, { ...pin, starts: 1 })- const wrote = await host.run(replaceFileArgv(path, true), 10_000, lines).catch(() => ({ exitCode: 1 }))+ const wrote = await host.run(replaceFileArgv(path, true, await writeFlavorReady()), 10_000, lines).catch(() => ({ exitCode: 1 }))if (wrote.exitCode !== 0 && pin !== null) await setPin(store, host, cwd, pin)} finally {diff --git a/plugins/ruflo-console/hooks/data/ap-journal.ts b/plugins/ruflo-console/hooks/data/ap-journal.tsindex b0849685dc..6442168fba 100644--- a/plugins/ruflo-console/hooks/data/ap-journal.ts+++ b/plugins/ruflo-console/hooks/data/ap-journal.ts@@ -9,6 +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'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`). */@@ -172,11 +173,15 @@ export function parseJournal(text: string | null): ParsedJournal {return { events, bad: lines.length - events.length, isCapped: false }}-/** Fixed argv that appends stdin to the journal: the shared GNU dd append (data/append-argv.ts), one O_APPEND block per batch. */+/** Fixed argv that appends stdin to the journal: the shared append (data/append-argv.ts), one dd block per batch on GNU and BSD alike. */export { appendArgv }-/** Fixed argv that creates a flag file (the kill switch) and its folder: GNU install -D from an empty stdin. */-export const touchArgv = (path: string): readonly string[] => ['install', '-D', '-m', '600', '/dev/null', path]+/**+ * Fixed argv that creates an empty file (the kill switch flag, a new journal) and its folder, mode 0600. GNU: `install -D` from /dev/null,+ * 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))/** 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).lengthdiff --git a/plugins/ruflo-console/hooks/data/append-argv.ts b/plugins/ruflo-console/hooks/data/append-argv.tsindex c99b855f0a..a0b0218572 100644--- a/plugins/ruflo-console/hooks/data/append-argv.ts+++ b/plugins/ruflo-console/hooks/data/append-argv.ts@@ -1,8 +1,19 @@/**- * The one argv that appends stdin to a log: GNU `dd` with O_APPEND, no shell, the path one element. Shared by the Events store- * (activity-io.ts) and the autopilot journal (ap-journal.ts), so both keep a batch whole when two consoles write one file.- * `bs=1M iflag=fullblock` matters: dd's default 512-byte blocks write a batch from a pipe in many short `write` calls, so two- * writers' batches interleave in the middle of a line (measured: 1094 of 4800 lines torn with two writers). One block is one- * O_APPEND write, which the kernel keeps whole. A leaf: no imports.+ * The one argv that appends stdin to a log. Shared by the Events store (activity-io.ts) and the autopilot journal (ap-journal.ts), so both+ * keep a batch in one piece when two consoles write one file.+ *+ * GNU (Linux): `dd` with O_APPEND, no shell, the path one element. `bs=1M iflag=fullblock` matters: dd's default 512-byte blocks write a+ * batch from a pipe in many short `write` calls, so two writers' batches interleave in the middle of a line (measured: 1094 of 4800 lines+ * torn with two writers). With one block per batch, dd issues one write(2) per batch to an O_APPEND file.+ *+ * POSIX (macOS, BSD): BSD `dd` has no `oflag=append`, so the shell opens the file for append (`>>` is O_APPEND) and the same `dd bs=1M+ * iflag=fullblock` writes the batch to it (BSD dd has `iflag=fullblock` and `status=none`; verified on macOS 26). See write-flavor.ts.+ *+ * What holds on both: one dd block per batch of at most 1 MiB. Appends from two consoles can interleave only if a write is split: a batch+ * 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.*/-export const appendArgv = (path: string): readonly string[] => ['dd', `of=${path}`, 'oflag=append', 'conv=notrunc', 'bs=1M', 'iflag=fullblock', 'status=none']+import { 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)diff --git a/plugins/ruflo-console/hooks/data/event-export.ts b/plugins/ruflo-console/hooks/data/event-export.tsindex 48924b88f2..4f82f892eb 100644--- a/plugins/ruflo-console/hooks/data/event-export.ts+++ b/plugins/ruflo-console/hooks/data/event-export.ts@@ -11,6 +11,7 @@ import type { ConsoleEvent } from './events'import { refOf } from './events'import { EXPORT_DIR } from './activity-store'import { checkNoLinks, dirOf, newFileArgv, type PathCheck } from './wf-file'+import { writeFlavorReady } from './write-flavor'import { clockOf, type Concurrency, type LaneView } from './timeline-model'import type { ReaderFs } from './files'@@ -136,12 +137,12 @@ export async function exportSpecFor(fs: Pick<ReaderFs, 'stat'>, cwd: string, tarspec: {label: `write ${label}`,args: [],- argv: newFileArgv(placed.path, hasDir),+ argv: newFileArgv(placed.path, hasDir, await writeFlavorReady()),stdin: content,expect: `a new file at ${placed.path}`,declared: 'write',shows: `write ${placed.path} (${bytes(content)} bytes; never overwrites)`,- note: 'writes one new file inside the project; a file that already exists makes it fail instead of replacing it (a missing folder is made with GNU install, which macOS lacks)',+ note: 'writes one new file inside the project; a file that already exists makes it fail instead of replacing it; a missing folder is made first',timeoutMs: 10_000,verifyLocal: async host => (await host.fs.stat(placed.path).catch(() => undefined)) !== undefined,},diff --git a/plugins/ruflo-console/hooks/data/wf-export.ts b/plugins/ruflo-console/hooks/data/wf-export.tsindex 778dba6b08..74fa6e8f9a 100644--- a/plugins/ruflo-console/hooks/data/wf-export.ts+++ b/plugins/ruflo-console/hooks/data/wf-export.ts@@ -7,6 +7,7 @@import { isoOf } from './safe'import type { ActionSpec } from '../actions'import { newFileArgv } from './wf-file'+import type { WriteFlavor } from './write-flavor'import { cleanText } from './wf-clean'import { fmtElapsed, fmtTokens, modelName, type WfAgent, type WfRun } from './workflows'@@ -81,16 +82,16 @@ function capped(text: string): string {}/** The confirm-gated write of a summary: the card shows the path and size, the argv is fixed and the text goes in on stdin. */-export function exportSpec(path: string, markdown: string, label: string, hasDir: boolean): ActionSpec {+export function exportSpec(path: string, markdown: string, label: string, hasDir: boolean, flavor: WriteFlavor): ActionSpec {return {label: `write run summary: ${label}`,args: [],- argv: newFileArgv(path, hasDir),+ argv: newFileArgv(path, hasDir, flavor),stdin: markdown,expect: `a new file at ${path}`,declared: 'write',shows: `write ${path} (${BYTES(markdown)} bytes; never overwrites)`,- note: 'writes one new markdown file inside the project or the scratchpad; a file that already exists makes it fail instead of replacing it (a missing folder is made with GNU install, which macOS lacks)',+ note: 'writes one new markdown file inside the project or the scratchpad; a file that already exists makes it fail instead of replacing it; a missing folder is made first',timeoutMs: 10_000,verifyLocal: async host => (await host.fs.stat(path).catch(() => undefined)) !== undefined,}diff --git a/plugins/ruflo-console/hooks/data/wf-file.ts b/plugins/ruflo-console/hooks/data/wf-file.tsindex c5dcfc5512..2241f42aaf 100644--- a/plugins/ruflo-console/hooks/data/wf-file.ts+++ b/plugins/ruflo-console/hooks/data/wf-file.ts@@ -1,13 +1,16 @@/*** The two files the Workflows page may write (ADR-461): a run summary the person asks for (markdown), and the page's own- * saved views. The host's `fs` is read-only, so a write is a fixed-argv command with the content on stdin and no shell: `dd- * of=<path>` where the folder exists (`conv=excl` makes it fail rather than replace a file), else GNU `install -D`, which makes the- * folders first. The path is one argv element, never part of a script.+ * saved views. The host's `fs` is read-only, so a write is a fixed command with the content on stdin. On GNU (Linux) it has no shell:+ * `dd of=<path>` where the folder exists (`conv=excl` makes it fail rather than replace a file), else `install -D`, which makes the+ * folders first. BSD `dd` and `install` (macOS) have neither `conv=excl` nor `-D`, so there one of the constant `sh -c` scripts in write-flavor.ts does+ * the same: `set -C` (noclobber, an O_EXCL open) for a new file and `mkdir -p` of the parent where the folder is missing, after refusing a+ * link or a non-regular target. Either way the path is one argv element, never part of a script.** 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 type { ReaderFs } from './files'+import { 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 }@@ -73,11 +76,32 @@ export async function checkNoLinks(fs: Pick<ReaderFs, 'stat'>, path: string, rooreturn { ok: true, path }}-/** A new file, content on stdin: `dd` with `conv=excl` where the folder is there (it fails if the file appeared meanwhile), `install -D` (GNU: makes the folders; not on macOS) where it is not. */-export const newFileArgv = (path: string, hasDir: boolean): readonly string[] => (hasDir ? ['dd', `of=${path}`, 'conv=excl', 'status=none'] : INSTALL(path))+/**+ * A new file, content on stdin. GNU: `dd conv=excl` where the folder is there (O_EXCL: it fails if anything appeared after the check),+ * `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).+ *+ * 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)++/**+ * 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+ * torn write is a corrupt file, which the reader tolerates. GNU: `dd of=<path>` or `install -D`, unchanged. POSIX: the guarded scripts in+ * 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)-/** 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 torn write is a corrupt file, which the reader tolerates. */-export const replaceFileArgv = (path: string, hasDir: boolean): readonly string[] => (hasDir ? ['dd', `of=${path}`, 'status=none'] : INSTALL(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)const INSTALL = (path: string): readonly string[] => ['install', '-D', '-m', '0644', '/dev/stdin', '--', path]diff --git a/plugins/ruflo-console/hooks/data/write-flavor.ts b/plugins/ruflo-console/hooks/data/write-flavor.tsnew file mode 100644index 0000000000..1cb76a91a8--- /dev/null+++ b/plugins/ruflo-console/hooks/data/write-flavor.ts@@ -0,0 +1,105 @@+/**+ * Which file-writing argv the host's tools take, and the POSIX forms of those writes. The host's `fs` is read-only, so the console writes+ * through fixed argv with the content on stdin. The GNU forms (`dd oflag=append`, `dd conv=excl`, `install -D`) are what Linux has always+ * run; BSD `dd` and `install` (macOS) refuse every one of them ("dd: unknown open flag append", "dd: unknown conversion excl", `install`+ * usage, exit 64), so there the same writes go through `sh -c` with one of the constant scripts below and the path as `$1`.+ *+ * There is no generic shell builder: only the enumerated operations are exported, each with its own constant script, and the path is+ * only ever expanded quoted ("$1"), so no character in it is interpreted. Every script first refuses a target that is a link or is not a+ * regular file (a FIFO, a device, a folder): exit 73 with the reason on stderr. That check and the open are two steps, so a link raced in+ * between them is followed; this is the same check-then-write window as `checkNoLinks`, which every caller runs first.+ *+ * Ordering: the flavor is detected once per process from `uname -s` (`startWriteFlavorDetection`, called at session start before the+ * 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.+ */+export type WriteFlavor = 'gnu' | 'posix'++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. */+export function flavorOfPlatform(platform: unknown = (globalThis as { process?: { platform?: unknown } }).process?.platform): WriteFlavor {+ return typeof platform === 'string' && (platform === 'darwin' || platform.endsWith('bsd')) ? 'posix' : 'gnu'+}++type Run = (argv: readonly string[], timeoutMs: number) => Promise<{ exitCode: number | null; stdout: string }>++/**+ * Starts the one detection of this process (later calls return the same promise). `run` is the host's command runner. Never rejects, and+ * settles within `deadlineMs` whatever the runner does.+ */+export function startWriteFlavorDetection(run: Run, deadlineMs: number = DETECT_DEADLINE_MS, fallback: () => WriteFlavor = flavorOfPlatform): Promise<WriteFlavor> {+ if (detection !== null) return detection++ const asked = Promise.resolve()+ .then(() => run(['uname', '-s'], deadlineMs))+ .then(+ result => (result.exitCode === 0 && result.stdout.trim() !== '' ? flavorOfKernel(result.stdout) : fallback()),+ () => fallback(),+ )+ let timer: ReturnType<typeof setTimeout> | undefined+ const deadline = new Promise<WriteFlavor>(resolve => {+ timer = setTimeout(() => resolve(fallback()), deadlineMs)+ })++ detection = Promise.race([asked, deadline]).finally(() => clearTimeout(timer))++ return detection+}++/** 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')++/** Tests: a known flavor (or, with null, back to "never detected"). */+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. */+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. */+const GUARD = 'if [ -L "$1" ] || { [ -e "$1" ] && [ ! -f "$1" ]; }; then echo "refused: the target is a link or not a regular file" >&2; exit 73; fi;'+/** Makes the folder the file sits in (`install -D` did this on GNU). */+const MKDIR = 'mkdir -p -- "$(dirname -- "$1")" || exit 1;'++/**+ * The whole set of POSIX write scripts. umask 022 makes a created file 0644 (as `install -m 0644`); the touch uses 077 and chmod 600.+ * `set -C` (noclobber) makes the shell open with O_CREAT|O_EXCL, so an exclusive create fails on a file that is already there.+ */+export const POSIX_SCRIPTS = Object.freeze({+ append: `umask 022; ${GUARD} exec dd bs=1M iflag=fullblock status=none >> "$1"`,+ createExclusive: `umask 022; ${GUARD} set -C; exec cat > "$1"`,+ createExclusiveWithDirs: `umask 022; ${MKDIR} ${GUARD} set -C; exec cat > "$1"`,+ replace: `umask 022; ${GUARD} exec cat > "$1"`,+ replaceWithDirs: `umask 022; ${MKDIR} ${GUARD} exec cat > "$1"`,+ touch: `umask 077; ${MKDIR} ${GUARD} if [ ! -f "$1" ]; then set -C; : > "$1" || exit 1; fi; exec chmod 600 "$1"`,+ /** "$1" the new file, "$2" the regular file it copies (refused if a link or not regular); umask 077: the copy is 0600, like the journal. */+ copyExclusive: `umask 077; ${GUARD} if [ -L "$2" ] || [ ! -f "$2" ]; then echo "refused: the source is a link or not a regular file" >&2; exit 73; fi; set -C; exec cat < "$2" > "$1"`,+} as const)++type PosixOp = keyof typeof POSIX_SCRIPTS++/** The only sh argv: a script from the set above by key, then the target as "$1" (and, for a copy, its source as "$2"). */+const posix = (op: PosixOp, path: string, source?: string): readonly string[] => ['sh', '-c', POSIX_SCRIPTS[op], 'sh', path, ...(source === undefined ? [] : [source])]++/** Appends stdin; one `dd` block of up to 1 MiB per batch through an O_APPEND open (`>>`). */+export const posixAppend = (path: string): readonly string[] => posix('append', path)+/** Creates a new file from stdin; fails if anything is at the path. */+export const posixCreateExclusive = (path: string): readonly string[] => posix('createExclusive', path)+/** Makes the folders, then creates a new file from stdin; fails if anything is at the path. */+export const posixCreateExclusiveWithDirs = (path: string): readonly string[] => posix('createExclusiveWithDirs', path)+/** Replaces a regular file (or creates it) from stdin. */+export const posixReplace = (path: string): readonly string[] => posix('replace', path)+/** Makes the folders, then replaces (or creates) a regular file from stdin. */+export const posixReplaceWithDirs = (path: string): readonly string[] => posix('replaceWithDirs', path)+/** Makes the folders and an empty 0600 file where none is (an existing regular file keeps its content and is set to 0600). */+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)diff --git a/plugins/ruflo-console/hooks/register.ts b/plugins/ruflo-console/hooks/register.tsindex bd5d902163..2cb4ca4311 100644--- a/plugins/ruflo-console/hooks/register.ts+++ b/plugins/ruflo-console/hooks/register.ts@@ -13,6 +13,7 @@ import { newState, PANE_ID, restore, restoreSessions, storeKeyOf, termStoreKeyOfimport { BAR_KEY, barView } from './views/bar'import { addNotice, dismissNotices } from './notices'import { setBootChecks } from './boot-checks'+import { startWriteFlavorDetection } from './data/write-flavor'import { buildOf, isOurCheckout, setBuild } from './build'import { runUpdateCheck } from './update-flow'import { announceModelTools, parseControlEnv, serveModelTools } from './model-tools'@@ -165,6 +166,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.+ const detecting = host+ void startWriteFlavorDetection((argv, timeoutMs) => detecting.run(argv, timeoutMs))state.cwd = e.cwdstate.nostrKeyVerifiedAtMs = nullstate.isInteractive = e.isInteractive !== falsediff --git a/plugins/ruflo-console/hooks/views/wf-export.ts b/plugins/ruflo-console/hooks/views/wf-export.tsindex 631c88b24a..99e5f245a9 100644--- a/plugins/ruflo-console/hooks/views/wf-export.ts+++ b/plugins/ruflo-console/hooks/views/wf-export.ts@@ -8,6 +8,7 @@ import type { RenderElement } from 'claude-code'import { exportName, exportSpec, runMarkdown, type ExportCost } from '../data/wf-export'import { checkNoLinks, dirOf, EXPORT_DIR, resolveExportPath, type Roots } from '../data/wf-file'+import { writeFlavorReady } from '../data/write-flavor'import { button, clip, row, text, THEME } from './common'import { fold, redraw } from './wf-fold'import { registerSlot, type SlotEnv } from './wf-slots'@@ -57,7 +58,7 @@ export async function requestExport(env: Pick<SlotEnv, 'ctx' | 'nowMs'>, run: Wfconst hasDir = (await fs.stat(dirOf(clear.path)).catch(() => undefined)) !== undefined- env.ctx.act.workflows.ask(exportSpec(clear.path, markdown, clip(run.name, 40), hasDir), 'that summary cannot be written')+ env.ctx.act.workflows.ask(exportSpec(clear.path, markdown, clip(run.name, 40), hasDir, await writeFlavorReady()), 'that summary cannot be written')return { ok: true, text: `asked: confirm below to write ${clear.path}` }}diff --git a/plugins/ruflo-console/hooks/wf-convo-live.ts b/plugins/ruflo-console/hooks/wf-convo-live.tsindex 9c5e54da31..9e48d04521 100644--- a/plugins/ruflo-console/hooks/wf-convo-live.ts+++ b/plugins/ruflo-console/hooks/wf-convo-live.ts@@ -8,6 +8,7 @@ import type { ActionSpec } from './actions'import { cleanText } from './data/wf-clean'import { addMessage, applyFetch, FETCH_MAX, fromBbs, fromChannel, newConvo, pollParams, POLL_MAX, POLL_MS, recordSend, relayBody, lastAnswer, threadOf, transcriptMarkdown, transcriptName, type Convo } from './data/wf-convo'import { checkNoLinks, EXPORT_DIR, resolveExportPath } from './data/wf-file'+import { writeFlavorReady } from './data/write-flavor'import { exportSpec } from './data/wf-export'import { payloadOf, sendTo, type SendDeps, tidy } from './data/wf-send'import { parseConfig, peersOf, targetsOf, type Config, type PeerRef, type Target } from './data/wf-targets'@@ -261,7 +262,7 @@ export async function saveTranscript(state: State, target: Target, ask: (spec: Aconst made = transcriptMarkdown(thread, target, Date.now())const hasDir = (await host.fs.stat(clear.path.slice(0, Math.max(1, clear.path.lastIndexOf('/')))).catch(() => undefined)) !== undefined- ask({ ...exportSpec(clear.path, made.text, cleanText(target.id), hasDir), label: `save the ${target.id} conversation${made.isCut ? ' (cut at the cap)' : ''}` }, 'that transcript cannot be written')+ ask({ ...exportSpec(clear.path, made.text, cleanText(target.id), hasDir, await writeFlavorReady()), label: `save the ${target.id} conversation${made.isCut ? ' (cut at the cap)' : ''}` }, 'that transcript cannot be written')}/** For tests: drops the held conversation and host of a state, and stops its timers. */diff --git a/plugins/ruflo-console/hooks/wf-saved-live.ts b/plugins/ruflo-console/hooks/wf-saved-live.tsindex ad9f96f8e9..deb578cf90 100644--- a/plugins/ruflo-console/hooks/wf-saved-live.ts+++ b/plugins/ruflo-console/hooks/wf-saved-live.ts@@ -11,6 +11,7 @@ import type { ActionSpec } from './actions'import { decodeSaved, emptySaved, encodeSaved, captureDrill, restoreDrill, sameDrill, SAVED_FILE, SAVED_MAX_BYTES, type Saved } from './data/wf-saved'import { cleanText } from './data/wf-clean'import { checkNoLinks, dirOf, removeFileArgv, replaceFileArgv } from './data/wf-file'+import { writeFlavorReady } from './data/write-flavor'import { readBounded } from './data/files'import type { Host } from './host'import type { State } from './state'@@ -140,7 +141,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), 10_000, encodeSaved(own.saved, nowMs))+ const result = await host.run(replaceFileArgv(path, hasDir, await writeFlavorReady()), 10_000, encodeSaved(own.saved, nowMs))own.error = result.exitCode === 0 ? null : `the write exited ${result.exitCode}`if (result.exitCode === 0) own.isDirty = falsediff --git a/plugins/ruflo-console/scripts/smoke.sh b/plugins/ruflo-console/scripts/smoke.shindex d4da04c507..5978df2f18 100755--- a/plugins/ruflo-console/scripts/smoke.sh+++ b/plugins/ruflo-console/scripts/smoke.sh@@ -51,7 +51,14 @@ grep -q "fs.stat(under(home, NOSTR_KEY))" "$HOOKS/data/files.ts" && [[ -z "$keysstep "8. mutations only through fixed argv (claims_* via JSON.stringify), behind a confirm"grep -q "JSON.stringify(params)" "$HOOKS/actions.ts" \&& [[ "$(grep -ohE "exec\('claims_[a-z-]+'" "$HOOKS/actions.ts" "$HOOKS/ops.ts" | sort -u | tr '\n' ' ')" == "exec('claims_claim' exec('claims_handoff' exec('claims_release' exec('claims_status' exec('claims_steal' " ]] \- && grep -q "state.pending = " "$HOOKS/runner.ts" && ! grep -qE "'(sh|bash)', '-c'" -r "$HOOKS" && ok || bad "action surface changed"+ && grep -q "state.pending = " "$HOOKS/runner.ts" && ! grep -qE "'(sh|bash)', '-c'" -r --exclude=write-flavor.ts "$HOOKS" \+ && [[ "$(grep -cE "'(sh|bash)', '-c'" "$HOOKS/data/write-flavor.ts")" == 1 ]] \+ && grep -qF "['sh', '-c', POSIX_SCRIPTS[op], 'sh', path, ...(source === undefined ? [] : [source])]" "$HOOKS/data/write-flavor.ts" \+ && [[ "$(awk '/POSIX_SCRIPTS = Object.freeze\(\{/{on=1;next} on&&/^\}/{on=0} on' "$HOOKS/data/write-flavor.ts" | sed -nE 's/^ ([A-Za-z]+): .*/\1/p' | sort | tr '\n' ' ')" == "append copyExclusive createExclusive createExclusiveWithDirs replace replaceWithDirs touch " ]] \+ && ok || bad "action surface changed"+# The one shell: data/write-flavor.ts, the macOS/BSD file writes (BSD dd/install lack oflag=append, conv=excl, -D). It runs only a script+# from the frozen POSIX_SCRIPTS set (exactly these seven), by key, with the path as "$1" (a copy's source as "$2"); no exported builder takes a script.+# tests/write-argv.spec.ts checks each script: the link/non-regular guard first, "$1" always quoted, no other parameter.step "9. plugin.register and tool.call are observed, never answered (but the console's own tools, ADR-444)"reg=$(awk '/on\(.plugin.register./,/^ }\)/' "$HOOKS/register.ts" | grep -cE "refuse:|deny:")diff --git a/plugins/ruflo-console/tests/adr-integration.spec.ts b/plugins/ruflo-console/tests/adr-integration.spec.tsindex 3cddc5a41b..697d1560cb 100644--- a/plugins/ruflo-console/tests/adr-integration.spec.ts+++ b/plugins/ruflo-console/tests/adr-integration.spec.ts@@ -21,9 +21,12 @@ import { newState } from '../hooks/state'import { setLook } from '../hooks/views/common'import { readAdrDigest } from '../../ruflo-swarm/hooks/adr-digest'import { cleanAfter } from './adr-helpers'+import { useNativeWriteFlavor } from './fixtures/write-flavor'import { missionOf, TASK, world } from './adr-world'cleanAfter()+// The digest file and the drafted ADR are written to a real disk: the argv this machine's tools take (GNU on Linux, sh on macOS).+useNativeWriteFlavor()afterAll(() => setLook('plain'))describe('attach, suggest and detach on a mission', () => {diff --git a/plugins/ruflo-console/tests/adr-write.spec.ts b/plugins/ruflo-console/tests/adr-write.spec.tsindex d2fa318a3e..7c6ec7bb5c 100644--- a/plugins/ruflo-console/tests/adr-write.spec.ts+++ b/plugins/ruflo-console/tests/adr-write.spec.ts@@ -11,9 +11,12 @@ import { describe, expect, it } from 'vitest'import { lint, parseAdr, type AdrDoc } from '../hooks/data/adr'import { fsOfRoot, hostOfRoot, cleanAfter, keep, loaded, project, stateAt, TODAY } from './adr-helpers'+import { useNativeWriteFlavor } from './fixtures/write-flavor'import { adrOf, discover, initSpec, loadAdrs, planStatus, proposeSpec, statusSpec } from '../hooks/adr'cleanAfter()+// These write to a real disk through the console's own argv: the one this machine's dd/install take (GNU on Linux, sh on macOS).+useNativeWriteFlavor()describe('finding the ADR folder of the project the console runs in', () => {it.each([@@ -113,6 +116,28 @@ describe('writing, in a copy of each project', () => {expect(world.log.toasts).toEqual([])})+ it('a file that appears between the check and the write is refused by the write itself, and the person is told the write failed and why', async () => {+ const { root, state, world } = await loaded('empty')+ const spec = initSpec(state, world.host as never, today)+ const target = join(root, 'docs/adr/0001-record-architecture-decisions.md')+ const run = world.host.run++ // The folder is there (so the create is the exclusive one on both flavors: dd conv=excl, or sh noclobber); the link-and-exists check+ // passes, and the file lands just before the create runs (another console, an editor).+ mkdirSync(join(root, 'docs/adr'), { recursive: true })+ world.host.run = async (argv, ms, stdin) => {+ if (argv.some(arg => arg.includes('0001-record-architecture-decisions.md')) && !existsSync(target)) writeFileSync(target, 'MINE')++ return run(argv, ms, stdin)+ }+ await spec?.run?.()+ expect(readFileSync(target, 'utf8')).toBe('MINE')+ expect(adrOf(state).last?.ok).toBe(false)+ // The tool's own reason is shown (BSD sh: "cannot overwrite existing file"; GNU dd: "File exists"), not a guess that it "may have appeared".+ expect(adrOf(state).last?.lines.join('\n')).toMatch(/the write failed \(exit [1-9]\d*: \S[^)]*\); no file was replaced/)+ expect(adrOf(state).last?.lines.join('\n')).not.toMatch(/may have appeared/)+ })+it.each([['madr', 'docs/decisions', '0004-cache-reads.md', 'status: proposed'],['nygard', 'doc/adr', '0004-cache-reads.md', '## Status\n\nProposed'],diff --git a/plugins/ruflo-console/tests/ap-core.spec.ts b/plugins/ruflo-console/tests/ap-core.spec.tsindex 6ff3ccf7f8..6bbe2fe3e4 100644--- a/plugins/ruflo-console/tests/ap-core.spec.ts+++ b/plugins/ruflo-console/tests/ap-core.spec.ts@@ -123,7 +123,7 @@ describe('journal', () => {})it('appends with a fixed argv, the path as one element', () => {- expect(appendArgv('/p/j; rm -rf /.jsonl')).toEqual(['dd', 'of=/p/j; rm -rf /.jsonl', 'oflag=append', 'conv=notrunc', 'bs=1M', 'iflag=fullblock', 'status=none'])+ expect(appendArgv('/p/j; rm -rf /.jsonl', 'gnu')).toEqual(['dd', 'of=/p/j; rm -rf /.jsonl', 'oflag=append', 'conv=notrunc', 'bs=1M', 'iflag=fullblock', 'status=none'])})it.skipIf(process.platform !== 'linux')('with the real GNU dd, eight writers of whole journal batches never tear a line (ADR-466)', () => {@@ -132,7 +132,7 @@ describe('journal', () => {try {const batch = (c: string): string => Array.from({ length: 60 }, (_, i) => `{"w":"${c}","n":${i},"pad":"${c.repeat(900)}"}\n`).join('')const file = join(dir, 'journal.jsonl')- const argv = (appendArgv(file) as string[]).map(arg => `'${arg}'`).join(' ')+ const argv = (appendArgv(file, 'gnu') as string[]).map(arg => `'${arg}'`).join(' ')const script = Array.from({ length: 8 }, (_, w) => {const src = join(dir, `b${w}.txt`)diff --git a/plugins/ruflo-console/tests/events-review.spec.ts b/plugins/ruflo-console/tests/events-review.spec.tsindex f4e107ec31..abda4d58e1 100644--- a/plugins/ruflo-console/tests/events-review.spec.ts+++ b/plugins/ruflo-console/tests/events-review.spec.ts@@ -261,7 +261,7 @@ describe('the append path', () => {await flush(hostOn(disk), odd, `${odd}f.jsonl`, T)expect(disk.runs.every(argv => !['sh', 'bash', 'zsh'].includes(argv[0] as string) && !argv.includes('-c'))).toBe(true)- expect(appendArgv('/p/a b')).toEqual(['dd', 'of=/p/a b', 'oflag=append', 'conv=notrunc', 'bs=1M', 'iflag=fullblock', 'status=none'])+ expect(appendArgv('/p/a b', 'gnu')).toEqual(['dd', 'of=/p/a b', 'oflag=append', 'conv=notrunc', 'bs=1M', 'iflag=fullblock', 'status=none'])expect(BATCH_MAX + 2000).toBeLessThan(1024 * 1024)})@@ -271,7 +271,7 @@ describe('the append path', () => {try {const batch = (c: string): string => Array.from({ length: 60 }, (_, i) => `{"w":"${c}","n":${i},"pad":"${c.repeat(900)}"}\n`).join('')const file = join(dir, 'out.jsonl')- const [cmd, ...rest] = appendArgv(file) as string[]+ const [cmd, ...rest] = appendArgv(file, 'gnu') as string[]const script = Array.from({ length: 8 }, (_, w) => {const src = join(dir, `b${w}.txt`)diff --git a/plugins/ruflo-console/tests/fixtures/write-flavor.ts b/plugins/ruflo-console/tests/fixtures/write-flavor.tsnew file mode 100644index 0000000000..94c7521383--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/write-flavor.ts@@ -0,0 +1,38 @@+/**+ * For specs that write to a real disk through the console's own code: the write argv must be the one this machine's tools take (GNU on+ * Linux, the sh scripts on macOS/BSD), found the way the console finds it at session start (`uname -s` through+ * `startWriteFlavorDetection`). The detection is module state, so it is cleared after the block: specs on a fake disk keep seeing the GNU+ * argv they parse.+ */+import { spawnSync } from 'node:child_process'++import { afterAll, beforeAll } from 'vitest'++import { setWriteFlavor, startWriteFlavorDetection, type WriteFlavor } from '../../hooks/data/write-flavor'++/** The host's run, for `uname -s` only. */+export const realRun = async (argv: readonly string[]): Promise<{ exitCode: number | null; stdout: string }> => {+ const result = spawnSync(argv[0] as string, argv.slice(1), { encoding: 'utf8' })++ return { exitCode: result.status, stdout: result.stdout ?? '' }+}++/** The flavor this machine needs, as the console would detect it; the module state is left cleared. */+export async function nativeWriteFlavor(): Promise<WriteFlavor> {+ setWriteFlavor(null)++ const flavor = await startWriteFlavorDetection(realRun)++ setWriteFlavor(null)++ return flavor+}++/** Detects the machine's flavor before the enclosing block (or file) and clears it after. */+export function useNativeWriteFlavor(): void {+ beforeAll(async () => {+ setWriteFlavor(null)+ await startWriteFlavorDetection(realRun)+ })+ afterAll(() => setWriteFlavor(null))+}diff --git a/plugins/ruflo-console/tests/wf-export.spec.ts b/plugins/ruflo-console/tests/wf-export.spec.tsindex 4880f6d368..5291948718 100644--- a/plugins/ruflo-console/tests/wf-export.spec.ts+++ b/plugins/ruflo-console/tests/wf-export.spec.ts@@ -7,6 +7,7 @@ import { describe, expect, it } from 'vitest'import { exportName, exportSpec, MAX_EXPORT_BYTES, runMarkdown } from '../hooks/data/wf-export'import { checkNoLinks, newFileArgv, removeFileArgv, replaceFileArgv, resolveExportPath } from '../hooks/data/wf-file'import { BASE, runOf } from './fixtures/wf-runs'+import { nativeWriteFlavor } from './fixtures/write-flavor'const KEY = 'sk-abcdefghijklmnopqrstuvwx'const ROOTS = { cwd: '/work/proj', scratch: '/home/u/.cache/claude-code/tmp/s1' }@@ -92,40 +93,64 @@ describe('the write', () => {it('is a command with no shell: the path is one element, whatever it says', () => {const evil = '/work/proj/a b;$(rm -rf ~)`x`.md'- expect(newFileArgv(evil, true)).toEqual(['dd', `of=${evil}`, 'conv=excl', 'status=none'])- expect(newFileArgv(evil, false)).toEqual(['install', '-D', '-m', '0644', '/dev/stdin', '--', evil])- expect(replaceFileArgv(evil, true)).toEqual(['dd', `of=${evil}`, 'status=none'])- expect(replaceFileArgv(evil, false)).toEqual(newFileArgv(evil, false))+ expect(newFileArgv(evil, true, 'gnu')).toEqual(['dd', `of=${evil}`, 'conv=excl', 'status=none'])+ expect(newFileArgv(evil, false, 'gnu')).toEqual(['install', '-D', '-m', '0644', '/dev/stdin', '--', evil])+ expect(replaceFileArgv(evil, true, 'gnu')).toEqual(['dd', `of=${evil}`, 'status=none'])+ expect(replaceFileArgv(evil, false, 'gnu')).toEqual(newFileArgv(evil, false, 'gnu'))expect(removeFileArgv(evil)).toEqual(['rm', '-f', '--', evil])- for (const argv of [newFileArgv(evil, true), newFileArgv(evil, false), replaceFileArgv(evil, true), removeFileArgv(evil)]) expect(argv.some(part => part === 'sh' || part === 'bash' || part === '-c')).toBe(false)+ for (const argv of [newFileArgv(evil, true, 'gnu'), newFileArgv(evil, false, 'gnu'), replaceFileArgv(evil, true, 'gnu'), removeFileArgv(evil)]) expect(argv.some(part => part === 'sh' || part === 'bash' || part === '-c')).toBe(false)})- it('a new file never replaces one: dd refuses an existing file (conv=excl) on a real disk', async () => {- const { mkdtempSync, readFileSync, rmSync } = await import('node:fs')+ it('a new file never replaces one: the exclusive create refuses an existing file on a real disk, with this machine\'s tools', async () => {+ const { closeSync, mkdtempSync, openSync, readFileSync, rmSync, writeFileSync } = await import('node:fs')const { spawnSync } = await import('node:child_process')const { tmpdir } = await import('node:os')+ const flavor = await nativeWriteFlavor()const dir = mkdtempSync(`${tmpdir()}/wf-export-`)const file = `${dir}/a b;$(x).md`+ // stdin from a file descriptor, not Node's socket pair: GNU `install -D /dev/stdin` reopens stdin and refuses a socket.+ const write = (input: string, path = file, hasDir = true) => {+ writeFileSync(`${dir}.in`, input)++ const fd = openSync(`${dir}.in`, 'r')++ try {+ const [cmd, ...args] = newFileArgv(path, hasDir, flavor) as string[]++ return spawnSync(cmd as string, args, { stdio: [fd, 'pipe', 'pipe'] })+ } finally {+ closeSync(fd)+ }+ }try {- const first = spawnSync(...(args => [args[0] as string, args.slice(1) as string[], { input: 'one\n' }] as const)(newFileArgv(file, true)))+ const first = write('one\n')expect(first.status).toBe(0)expect(readFileSync(file, 'utf8')).toBe('one\n')- const second = spawnSync(...(args => [args[0] as string, args.slice(1) as string[], { input: 'two\n' }] as const)(newFileArgv(file, true)))+ const second = write('two\n')expect(second.status).not.toBe(0)expect(readFileSync(file, 'utf8')).toBe('one\n')++ // No folder yet: it is made, then the file (GNU install -D, or mkdir -p and the exclusive create).+ const deep = `${dir}/new dir/$(y)/b.md`++ expect(write('deep\n', deep, false).status).toBe(0)+ expect(readFileSync(deep, 'utf8')).toBe('deep\n')+ expect(spawnSync('test', ['-e', `${dir}/x`]).status).not.toBe(0)+ expect(spawnSync('test', ['-e', `${dir}/y`]).status).not.toBe(0)} finally {rmSync(dir, { recursive: true, force: true })+ rmSync(`${dir}.in`, { force: true })}})it('is a confirm-gated spec: argv, text on stdin, declared write, verified on disk', async () => {- const spec = exportSpec('/work/proj/o.md', '# hi\n', 'demo', true)+ const spec = exportSpec('/work/proj/o.md', '# hi\n', 'demo', true, 'gnu')- expect(spec).toMatchObject({ argv: newFileArgv('/work/proj/o.md', true), stdin: '# hi\n', declared: 'write', args: [] })+ expect(spec).toMatchObject({ argv: newFileArgv('/work/proj/o.md', true, 'gnu'), stdin: '# hi\n', declared: 'write', args: [] })expect(spec.shows).toMatch(/never overwrites/)expect(await spec.verifyLocal?.({ fs: { stat: async () => ({ size: 1 }) } } as never)).toBe(true)expect(await spec.verifyLocal?.({ fs: { stat: async () => Promise.reject(new Error('x')) } } as never)).toBe(false)diff --git a/plugins/ruflo-console/tests/wf-security-worktrees.spec.ts b/plugins/ruflo-console/tests/wf-security-worktrees.spec.tsindex 548d6f189e..550dda1b43 100644--- a/plugins/ruflo-console/tests/wf-security-worktrees.spec.ts+++ b/plugins/ruflo-console/tests/wf-security-worktrees.spec.ts@@ -106,8 +106,12 @@ afterAll(async () => {const rowOf = (name: string): WtRow => storeFor(state).read?.rows.find(entry => entry.path === wtPath(name)) as WtRow+// The first three are Linux only: the in-use probe reads /proc with GNU find -printf (data/wf-worktrees.ts PROCS_ARGV), which macOS has+// neither of, so on another kernel they measure the test machine, not the guard. CI runs them on Linux.+const onLinux = process.platform === 'linux'+describe('the removal guard against a real repository', () => {- it('offers exactly the merged, clean, idle, old, not-current worktrees, and keeps everything else with the right reason', async () => {+ it.skipIf(!onLinux)('offers exactly the merged, clean, idle, old, not-current worktrees, and keeps everything else with the right reason', async () => {await refreshWorktrees(state, host, true)const { read, check } = storeFor(state)@@ -133,7 +137,7 @@ describe('the removal guard against a real repository', () => {expect(rowOf('old').createdMs).toBeLessThan(Date.now() - MIN_AGE_MS)})- it('removes only those, one at a time, never a branch, and a path that reads like a command line is one argv element', async () => {+ it.skipIf(!onLinux)('removes only those, one at a time, never a branch, and a path that reads like a command line is one argv element', async () => {const spec = removalSpec(envOf())expect(spec?.declared).toBe('delete')@@ -152,7 +156,7 @@ describe('the removal guard against a real repository', () => {expect(state.outcome?.verified).toBe('yes')})- it('re-checks each worktree at the moment of removal: one made dirty, in use or unmerged after the confirm is kept', async () => {+ it.skipIf(!onLinux)('re-checks each worktree at the moment of removal: one made dirty, in use or unmerged after the confirm is kept', async () => {for (const name of ['race-dirty', 'race-busy', 'race-ahead', 'race-ok']) {await git(main, 'worktree', 'add', '-b', `b-${name}`, wtPath(name))await utimes(join(wtPath(name), '.git'), new Date(Date.now() - 5 * 86_400_000), new Date(Date.now() - 5 * 86_400_000))diff --git a/plugins/ruflo-console/tests/wf-security.spec.ts b/plugins/ruflo-console/tests/wf-security.spec.tsindex 991d31cdff..69ad1b913d 100644--- a/plugins/ruflo-console/tests/wf-security.spec.ts+++ b/plugins/ruflo-console/tests/wf-security.spec.ts@@ -15,6 +15,8 @@ import { decodeSaved, encodeSaved, emptySaved, setFilter } from '../hooks/data/wimport { cleanBlock, cleanPath } from '../hooks/data/wf-activity'import { cleanText } from '../hooks/data/wf-clean'import { checkNoLinks, newFileArgv, resolveExportPath } from '../hooks/data/wf-file'+import { posixCreateExclusive, writeFlavorReady } from '../hooks/data/write-flavor'+import { useNativeWriteFlavor } from './fixtures/write-flavor'import { exportName, exportSpec, runMarkdown } from '../hooks/data/wf-export'import { maskSecrets, parseAgentMeta, parseJournal } from '../hooks/data/workflows'import { guardText } from '../hooks/data/wf-guide'@@ -113,6 +115,9 @@ describe('terminal injection', () => {})describe('export and saved-view paths', () => {+ // Real files and the real dd/sh: the argv this machine's tools take (GNU on Linux, the sh scripts on macOS/BSD).+ useNativeWriteFlavor()+let dir: stringlet outside: string@@ -186,11 +191,11 @@ describe('export and saved-view paths', () => {expect((await checkNoLinks(fsOf, (wanted as { path: string }).path, roots)).ok, rel).toBe(false)}- // The disk half holds even if the check were skipped: conv=excl refuses an existing file and a dangling link.+ // The disk half holds even if the check were skipped: conv=excl (GNU) or noclobber's O_EXCL (sh) refuses an existing file and a dangling link.await symlink(join(outside, 'not-yet.md'), join(dir, 'dangling.md'))for (const rel of ['exists.md', 'dangling.md']) {- const result = await run(newFileArgv(join(dir, rel), true), 5000, 'PWNED')+ const result = await run(newFileArgv(join(dir, rel), true, await writeFlavorReady()), 5000, 'PWNED')expect(result.exitCode, rel).not.toBe(0)}@@ -202,17 +207,18 @@ describe('export and saved-view paths', () => {it('writes a summary whose name has spaces and a leading dash-free base as one argv element, content on stdin', async () => {const path = `${dir}/odd name; $(touch pwned) \`id\`.md`- const result = await run(newFileArgv(path, true), 5000, '# hi\n')+ const result = await run(newFileArgv(path, true, await writeFlavorReady()), 5000, '# hi\n')expect(result.exitCode).toBe(0)expect(await readFile(path, 'utf8')).toBe('# hi\n')expect(await statOf(join(dir, 'pwned')).catch(() => null)).toBeNull()})- it('the export spec carries a fixed argv with no shell and the text only on stdin', () => {- const spec = exportSpec(`${dir}/a.md`, '# x', 'run', true)+ it('the export spec carries a fixed argv (no shell on GNU, one constant script with the path as $1 on BSD) and the text only on stdin', async () => {+ const flavor = await writeFlavorReady()+ const spec = exportSpec(`${dir}/a.md`, '# x', 'run', true, flavor)- expect(spec.argv?.[0]).toBe('dd')+ expect(spec.argv).toEqual(flavor === 'gnu' ? ['dd', `of=${dir}/a.md`, 'conv=excl', 'status=none'] : posixCreateExclusive(`${dir}/a.md`))expect(spec.stdin).toBe('# x')expect(spec.declared).toBe('write')expect(exportName(runOf('wf_x', BASE, {}, '../../etc/passwd; rm -rf /'))).toMatch(/^[A-Za-z0-9][A-Za-z0-9._-]*\.md$/)diff --git a/plugins/ruflo-console/tests/write-argv.spec.ts b/plugins/ruflo-console/tests/write-argv.spec.tsnew file mode 100644index 0000000000..2841588c8c--- /dev/null+++ b/plugins/ruflo-console/tests/write-argv.spec.ts@@ -0,0 +1,403 @@+/**+ * The console's file-writing argv on both kinds of host: GNU (Linux: dd oflag=append / conv=excl, install -D, no shell) and POSIX (macOS+ * and the BSDs, whose dd and install refuse those flags: one constant `sh -c` script per enumerated operation, the path as $1). The+ * builders are pure and take the flavor, so both branches are checked here on any machine; the POSIX scripts also run for real (sh and dd+ * exist on Linux and macOS alike), so their guarantees are measured, not assumed. Also: no write is built before the flavor is known.+ * Run with+ * npx vitest run plugins/ruflo-console/tests/write-argv.spec.ts --testTimeout=30000+ */+import { spawnSync } from 'node:child_process'+import { closeSync, existsSync, lstatSync, mkdtempSync, openSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { afterEach, describe, expect, it } from 'vitest'++import { flush, queueLine, resetIo } from '../hooks/activity-io'+import { refreshAutopilot, storeOf, wireAutopilot } from '../hooks/ap-live'+import { rotate } from '../hooks/ap-maint'+import { hostOfRoot } from './adr-helpers'+import { J, rig, started, stateWith, T0 } from './fixtures/ap-rig'+import { realRun } from './fixtures/write-flavor'+import { appendArgv } from '../hooks/data/append-argv'+import { encodeLine, JOURNAL_FILE, touchArgv } from '../hooks/data/ap-journal'+import { snapshotEvents } from '../hooks/data/ap-loop'+import { copyExclusiveArgv, newFileArgv, replaceFileArgv } from '../hooks/data/wf-file'+import * as writeFlavor from '../hooks/data/write-flavor'+import { DETECT_DEADLINE_MS, flavorOfKernel, flavorOfPlatform, POSIX_SCRIPTS, setWriteFlavor, startWriteFlavorDetection, writeFlavorReady } from '../hooks/data/write-flavor'++const EVIL = "/work/proj/a b;$(touch pwned) `id` 'q' \"d\"\n-rf.md"+const sh = (op: keyof typeof POSIX_SCRIPTS, path: string, source?: string) => ['sh', '-c', POSIX_SCRIPTS[op], 'sh', path, ...(source === undefined ? [] : [source])]++afterEach(() => {+ setWriteFlavor(null)+ resetIo()+})++describe('which flavor, and when', () => {+ it('Linux keeps the GNU argv; Darwin and the BSDs take the sh scripts', () => {+ expect(flavorOfKernel('Linux\n')).toBe('gnu')+ expect(flavorOfKernel('Darwin\n')).toBe('posix')+ expect(flavorOfKernel('FreeBSD')).toBe('posix')+ })++ it('is GNU where no detection was started, so a host that never asks behaves exactly as before', async () => {+ expect(await writeFlavorReady()).toBe('gnu')+ })++ it('is detected once per process from uname -s: a second start reuses the first answer', async () => {+ const asked: (readonly string[])[] = []+ const run = async (argv: readonly string[]) => (asked.push(argv), { exitCode: 0, stdout: 'Darwin\n' })++ expect(await startWriteFlavorDetection(run)).toBe('posix')+ expect(await startWriteFlavorDetection(async () => ({ exitCode: 0, stdout: 'Linux\n' }))).toBe('posix')+ expect(await writeFlavorReady()).toBe('posix')+ expect(asked).toEqual([['uname', '-s']])+ })++ it('without an answer, the engine platform decides: darwin and the BSDs posix, 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')+ // In this test process the default reads Node's own process.platform.+ expect(flavorOfPlatform()).toBe(process.platform === 'darwin' || process.platform.endsWith('bsd') ? 'posix' : 'gnu')+ })++ it.each([+ ['a non-zero exit', async () => ({ exitCode: 1, stdout: 'Linux\n' })],+ ['an empty answer', async () => ({ exitCode: 0, stdout: '' })],+ ['a refused command', async () => Promise.reject(new Error('refused'))],+ ['a runner that throws', () => {+ throw new Error('no runner')+ }],+ ])('after %s, a darwin engine takes posix (and a linux one gnu)', async (_name, run) => {+ expect(await startWriteFlavorDetection(run as never, DETECT_DEADLINE_MS, () => flavorOfPlatform('darwin'))).toBe('posix')+ expect(await writeFlavorReady()).toBe('posix')+ setWriteFlavor(null)+ expect(await startWriteFlavorDetection(run as never, DETECT_DEADLINE_MS, () => flavorOfPlatform('linux'))).toBe('gnu')+ })++ it('a failing detector on this machine falls back to its own platform (posix on macOS)', async () => {+ expect(await startWriteFlavorDetection(async () => ({ exitCode: 127, stdout: '' }))).toBe(flavorOfPlatform(process.platform))+ })++ it('a runner that never settles cannot hold the writes: the deadline answers with the platform fallback', async () => {+ const started = Date.now()++ expect(await startWriteFlavorDetection(() => new Promise(() => undefined), 50, () => flavorOfPlatform('darwin'))).toBe('posix')+ expect(Date.now() - started).toBeLessThan(1_000)+ expect(await writeFlavorReady()).toBe('posix')+ expect(DETECT_DEADLINE_MS).toBe(3_000)+ })++ it('a write that starts while detection is still running waits for it, and is built with the detected flavor', async () => {+ let answer: (value: { exitCode: number; stdout: string }) => void = () => undefined+ const runs: (readonly string[])[] = []+ let detectedAt = -1++ void startWriteFlavorDetection(() => new Promise(resolve => (answer = resolve)))++ const host = {+ fs: { read: async () => '', stat: async () => undefined, list: async () => [] },+ run: async (argv: readonly string[]) => (runs.push(argv), { exitCode: 0, stdout: '', stderr: '' }),+ }++ // The Events store's first flush starts before uname answers (as a timer during controller construction can).+ queueLine('/work/proj/.claude-flow/console/events.jsonl', 1_000_000, '{"v":1}\n')++ const flushing = flush(host as never, '/work/proj', '/work/proj/.claude-flow/console/events.jsonl', 0)++ await new Promise(resolve => setTimeout(resolve, 20))+ // Nothing that depends on the flavor has been built yet: at most the flavor-free mkdir has run.+ expect(runs.every(argv => argv[0] === 'mkdir')).toBe(true)+ detectedAt = runs.length+ answer({ exitCode: 0, stdout: 'Darwin\n' })+ await flushing++ const writes = runs.slice(detectedAt)++ expect(writes).toContainEqual(sh('createExclusive', '/work/proj/.claude-flow/console/.gitignore'))+ expect(writes).toContainEqual(sh('append', '/work/proj/.claude-flow/console/events.jsonl'))+ expect(runs.some(argv => argv[0] === 'dd' || argv[0] === 'install')).toBe(false)+ })+})++describe('the GNU argv (Linux): unchanged, no shell, the path one element', () => {+ it('appends, creates, replaces and touches with the argv Linux has always run', () => {+ expect(appendArgv(EVIL, 'gnu')).toEqual(['dd', `of=${EVIL}`, 'oflag=append', 'conv=notrunc', 'bs=1M', 'iflag=fullblock', 'status=none'])+ expect(newFileArgv(EVIL, true, 'gnu')).toEqual(['dd', `of=${EVIL}`, 'conv=excl', 'status=none'])+ expect(newFileArgv(EVIL, false, 'gnu')).toEqual(['install', '-D', '-m', '0644', '/dev/stdin', '--', EVIL])+ expect(replaceFileArgv(EVIL, true, 'gnu')).toEqual(['dd', `of=${EVIL}`, 'status=none'])+ expect(replaceFileArgv(EVIL, false, 'gnu')).toEqual(['install', '-D', '-m', '0644', '/dev/stdin', '--', EVIL])+ expect(touchArgv(EVIL, 'gnu')).toEqual(['install', '-D', '-m', '600', '/dev/null', EVIL])+ expect(copyExclusiveArgv(`${EVIL}.src`, EVIL, 'gnu')).toEqual(['cp', '--no-clobber', '--', `${EVIL}.src`, EVIL])++ const all = [appendArgv(EVIL, 'gnu'), newFileArgv(EVIL, true, 'gnu'), newFileArgv(EVIL, false, 'gnu'), replaceFileArgv(EVIL, true, 'gnu'), replaceFileArgv(EVIL, false, 'gnu'), touchArgv(EVIL, 'gnu'), copyExclusiveArgv(EVIL, EVIL, 'gnu')]++ for (const argv of all) expect(argv.some(part => ['sh', 'bash', '-c'].includes(part))).toBe(false)+ })+})++describe('the POSIX argv (macOS, BSD): a fixed set of constant scripts, the path only ever as "$1"', () => {+ it('maps every write to its enumerated script, the path its own argument after $0', () => {+ expect(appendArgv(EVIL, 'posix')).toEqual(sh('append', EVIL))+ expect(newFileArgv(EVIL, true, 'posix')).toEqual(sh('createExclusive', EVIL))+ expect(newFileArgv(EVIL, false, 'posix')).toEqual(sh('createExclusiveWithDirs', EVIL))+ expect(replaceFileArgv(EVIL, true, 'posix')).toEqual(sh('replace', EVIL))+ expect(replaceFileArgv(EVIL, false, 'posix')).toEqual(sh('replaceWithDirs', EVIL))+ expect(touchArgv(EVIL, 'posix')).toEqual(sh('touch', EVIL))+ expect(copyExclusiveArgv('/src/j.jsonl', EVIL, 'posix')).toEqual(sh('copyExclusive', EVIL, '/src/j.jsonl'))+ })++ it('the set is closed: seven frozen scripts, and no exported builder takes a script', () => {+ expect(Object.isFrozen(POSIX_SCRIPTS)).toBe(true)+ expect(Object.keys(POSIX_SCRIPTS).sort()).toEqual(['append', 'copyExclusive', 'createExclusive', 'createExclusiveWithDirs', 'replace', 'replaceWithDirs', 'touch'])++ const builders = Object.entries(writeFlavor).filter(([name, value]) => typeof value === 'function' && name.startsWith('posix'))++ expect(builders.map(([name]) => name).sort()).toEqual(['posixAppend', 'posixCopyExclusive', 'posixCreateExclusive', 'posixCreateExclusiveWithDirs', 'posixReplace', 'posixReplaceWithDirs', 'posixTouch'])+ for (const [name, build] of builders) expect((build as (...args: unknown[]) => unknown).length, name).toBe(name === 'posixCopyExclusive' ? 2 : 1)+ // Every argument is a path that lands after the script, never in it.+ for (const [name, build] of builders) for (const argv of [(build as (a: string, b: string) => readonly string[])('X$(id)', 'Y`id`')]) expect(argv[2]?.includes('$(id)') || argv[2]?.includes('`id`'), name).toBe(false)+ expect(Object.keys(writeFlavor)).not.toContain('shArgv')+ })++ it('every script refuses a link or a non-regular target before it opens anything, quotes $1 at each use and names no other parameter', () => {+ for (const [op, script] of Object.entries(POSIX_SCRIPTS)) {+ const params = op === 'copyExclusive' ? ['$1', '$2'] : ['$1']++ for (const param of ['$1', '$2']) expect(script.replaceAll(`"${param}"`, '').includes(param), `${op} ${param}`).toBe(false)+ expect(script.replace(/\$\(dirname -- "\$1"\)/g, '').match(/\$[^12]/), op).toBeNull()+ if (!params.includes('$2')) expect(script.includes('$2'), op).toBe(false)++ const guard = script.indexOf('if [ -L "$1" ] || { [ -e "$1" ] && [ ! -f "$1" ]; }; then')+ const open = Math.min(...['>', ':'].map(c => script.indexOf(` ${c} "$1"`)).filter(i => i >= 0), script.indexOf('>>'))++ expect(guard, op).toBeGreaterThanOrEqual(0)+ expect(guard < open || open < 0, op).toBe(true)+ }++ expect(POSIX_SCRIPTS.createExclusive).toMatch(/set -C; exec cat > "\$1"$/)+ expect(POSIX_SCRIPTS.createExclusiveWithDirs).toMatch(/set -C; exec cat > "\$1"$/)+ expect(POSIX_SCRIPTS.touch).toMatch(/umask 077;.*set -C; : > "\$1"/)+ for (const op of ['append', 'createExclusive', 'createExclusiveWithDirs', 'replace', 'replaceWithDirs'] as const) expect(POSIX_SCRIPTS[op]).toMatch(/^umask 022;/)+ for (const op of ['touch', 'copyExclusive'] as const) expect(POSIX_SCRIPTS[op]).toMatch(/^umask 077;/)+ expect(POSIX_SCRIPTS.copyExclusive).toMatch(/set -C; exec cat < "\$2" > "\$1"$/)+ })+})++describe('the POSIX scripts on a real disk (sh and dd as this machine has them)', () => {+ let dir = ''++ afterEach(() => {+ if (dir !== '') rmSync(dir, { recursive: true, force: true })+ dir = ''+ })++ /** Runs argv under umask 000 (so a mode is the script's own, not the test's), stdin from a file (never Node's socket pair). */+ const run = (argv: readonly string[], input = '') => {+ const holder = `${dir}.in`++ writeFileSync(holder, input)++ const fd = openSync(holder, 'r')++ try {+ const result = spawnSync('sh', ['-c', 'umask 000; exec "$@"', 'wrap', ...argv], { stdio: [fd, 'pipe', 'pipe'], cwd: dir, encoding: 'utf8' })++ return { status: result.status, stderr: result.stderr }+ } finally {+ closeSync(fd)+ rmSync(holder, { force: true })+ }+ }+ const fresh = () => (dir = mkdtempSync(join(tmpdir(), 'write-argv-')))+ const fifo = (path: string) => expect(spawnSync('mkfifo', [path]).status).toBe(0)++ it('an exclusive create writes once, then refuses the file, a dangling link and a link to a file, replacing nothing', () => {+ fresh()++ const file = join(dir, "odd $(touch pwned) `touch pwned2` 'n'.md")++ expect(run(newFileArgv(file, true, 'posix'), 'one\n').status).toBe(0)+ expect(readFileSync(file, 'utf8')).toBe('one\n')+ expect(statSync(file).mode & 0o777).toBe(0o644)+ expect(run(newFileArgv(file, true, 'posix'), 'two\n').status).not.toBe(0)+ expect(readFileSync(file, 'utf8')).toBe('one\n')++ const victim = join(dir, 'victim')++ writeFileSync(victim, 'keep')+ symlinkSync(victim, join(dir, 'to-file.md'))+ symlinkSync(join(dir, 'not-yet'), join(dir, 'dangling.md'))++ for (const name of ['to-file.md', 'dangling.md']) {+ const refused = run(newFileArgv(join(dir, name), true, 'posix'), 'PWNED')++ expect(refused.status, name).toBe(73)+ expect(refused.stderr, name).toMatch(/link or not a regular file/)+ }++ expect(readFileSync(victim, 'utf8')).toBe('keep')+ expect(existsSync(join(dir, 'not-yet'))).toBe(false)+ expect(existsSync(join(dir, 'pwned')) || existsSync(join(dir, 'pwned2'))).toBe(false)+ })++ it('every script refuses a FIFO, a link to a device and a dangling link, and never blocks on the FIFO', () => {+ fresh()++ const pipe = join(dir, 'pipe')++ fifo(pipe)+ symlinkSync('/dev/null', join(dir, 'to-null'))+ symlinkSync(join(dir, 'gone'), join(dir, 'dangling'))++ const source = join(dir, 'source.jsonl')++ writeFileSync(source, 'x\n')++ const argvs = (path: string) => [appendArgv(path, 'posix'), newFileArgv(path, true, 'posix'), newFileArgv(path, false, 'posix'), replaceFileArgv(path, true, 'posix'), replaceFileArgv(path, false, 'posix'), touchArgv(path, 'posix'), copyExclusiveArgv(source, path, 'posix')]++ for (const name of ['pipe', 'to-null', 'dangling']) {+ for (const argv of argvs(join(dir, name))) {+ const result = run(argv, 'PWNED')++ expect(result.status, `${name}: ${argv[2]}`).toBe(73)+ }+ }++ expect(lstatSync(pipe).isFIFO()).toBe(true)+ expect(existsSync(join(dir, 'gone'))).toBe(false)+ })++ it('an exclusive copy (the journal archive) copies a regular file to a new 0600 file, and refuses an existing target or a source that is a link or a FIFO', () => {+ fresh()++ const journal = join(dir, "journal $(touch pwned).jsonl")+ const archive = `${journal}.20261009`++ writeFileSync(journal, '{"t":"start"}\n{"t":"stop"}\n', { mode: 0o600 })+ expect(run(copyExclusiveArgv(journal, archive, 'posix')).status).toBe(0)+ expect(readFileSync(archive, 'utf8')).toBe('{"t":"start"}\n{"t":"stop"}\n')+ expect(statSync(archive).mode & 0o777).toBe(0o600)++ writeFileSync(journal, 'changed\n')+ expect(run(copyExclusiveArgv(journal, archive, 'posix')).status).not.toBe(0)+ expect(readFileSync(archive, 'utf8')).toBe('{"t":"start"}\n{"t":"stop"}\n')++ symlinkSync(journal, join(dir, 'link-src'))+ fifo(join(dir, 'fifo-src'))+ for (const name of ['link-src', 'fifo-src']) expect(run(copyExclusiveArgv(join(dir, name), join(dir, `${name}.copy`), 'posix')).status, name).toBe(73)+ expect(existsSync(join(dir, 'pwned'))).toBe(false)+ })++ it('a create where the folder is missing makes the folders, writes mode 0644, and still never replaces', () => {+ fresh()++ const file = join(dir, 'a/b c/$(touch pwned)/new.md')++ expect(run(newFileArgv(file, false, 'posix'), '# hi\n').status).toBe(0)+ expect(readFileSync(file, 'utf8')).toBe('# hi\n')+ expect(statSync(file).mode & 0o777).toBe(0o644)+ expect(run(newFileArgv(file, false, 'posix'), 'again\n').status).not.toBe(0)+ expect(readFileSync(file, 'utf8')).toBe('# hi\n')+ expect(existsSync(join(dir, 'pwned'))).toBe(false)+ })++ it('a replace makes a missing folder, writes 0644, and replaces the content on the next run', () => {+ fresh()++ const file = join(dir, 'state/views.json')++ expect(run(replaceFileArgv(file, false, 'posix'), '{"a":1}\n').status).toBe(0)+ expect(statSync(file).mode & 0o777).toBe(0o644)+ expect(run(replaceFileArgv(file, false, 'posix'), '{"a":2}\n').status).toBe(0)+ expect(readFileSync(file, 'utf8')).toBe('{"a":2}\n')+ expect(run(replaceFileArgv(file, true, 'posix'), '{"a":3}\n').status).toBe(0)+ expect(readFileSync(file, 'utf8')).toBe('{"a":3}\n')+ })++ it('a touch makes the folders and an empty 0600 file, keeps an existing one, and refuses a link without following it', () => {+ fresh()++ const flag = join(dir, '.claude-flow/console/autopilot/KILL')++ expect(run(touchArgv(flag, 'posix')).status).toBe(0)+ expect(lstatSync(flag).isFile()).toBe(true)+ expect(statSync(flag).size).toBe(0)+ expect(statSync(flag).mode & 0o777).toBe(0o600)+ expect(run(touchArgv(flag, 'posix')).status).toBe(0)++ const victim = join(dir, 'victim')++ writeFileSync(victim, 'precious', { mode: 0o644 })+ symlinkSync(victim, join(dir, 'link-flag'))+ expect(run(touchArgv(join(dir, 'link-flag'), 'posix')).status).toBe(73)+ expect(readFileSync(victim, 'utf8')).toBe('precious')+ expect(statSync(victim).mode & 0o777).toBe(0o644)+ })++ it('an append creates the file 0644, then adds to it, and keeps every byte of a hostile path as one name', () => {+ fresh()++ const file = join(dir, "j; echo x > pwned2 $(touch pwned) `id`.jsonl")++ expect(run(appendArgv(file, 'posix'), '{"n":1}\n').status).toBe(0)+ expect(statSync(file).mode & 0o777).toBe(0o644)+ expect(run(appendArgv(file, 'posix'), '{"n":2}\n').status).toBe(0)+ expect(readFileSync(file, 'utf8')).toBe('{"n":1}\n{"n":2}\n')+ expect(existsSync(join(dir, 'pwned')) || existsSync(join(dir, 'pwned2'))).toBe(false)+ })++ it('eight writers of 55 kB batches through the POSIX append tear no line here (one dd block per batch)', () => {+ fresh()++ const batch = (c: string): string => Array.from({ length: 60 }, (_, i) => `{"w":"${c}","n":${i},"pad":"${c.repeat(900)}"}\n`).join('')+ const file = join(dir, 'out.jsonl')+ const argv = (appendArgv(file, 'posix') as string[]).map(arg => `'${arg.replaceAll("'", `'\\''`)}'`).join(' ')+ const script = Array.from({ length: 8 }, (_, w) => {+ const src = join(dir, `b${w}.txt`)++ writeFileSync(src, batch(w % 2 === 0 ? 'A' : 'B'))++ return `( for k in 1 2 3 4 5; do cat '${src}' | ${argv}; done ) &`+ }).join('\n')++ expect(spawnSync('bash', ['-c', `${script}\nwait`]).status).toBe(0)++ const lines = readFileSync(file, 'utf8').split('\n').filter(Boolean)++ expect(lines).toHaveLength(8 * 5 * 60)+ expect(lines.filter(line => !/^\{"w":"(A+|B+)","n":\d+,"pad":"(A+|B+)"\}$/.test(line) || line.length < 900)).toHaveLength(0)+ })++ it('the autopilot journal rotation archives and compacts on this machine, with the flavor the console detects', async () => {+ fresh()++ // The loop's state comes from the in-memory rig; the journal it rotates is a real file under a real project folder.+ const r = rig()+ const state = stateWith([])++ started(r, [])+ wireAutopilot(state, r.host)+ await refreshAutopilot(state, r.host, T0 + 1000)++ const journal = join(dir, JOURNAL_FILE)+ const before = r.files.get(J) as string++ expect(spawnSync('mkdir', ['-p', join(journal, '..')]).status).toBe(0)+ writeFileSync(journal, before)+ await startWriteFlavorDetection(realRun)+ await rotate(storeOf(state), hostOfRoot(dir).host as never, dir, T0 + 5000)++ const archive = `${journal}.${new Date(T0 + 5000).toISOString().replace(/[^0-9]/g, '').slice(0, 14)}`++ // The archive is the old journal byte for byte (on macOS `cp --no-clobber` exits 64 and rotation stopped here); the journal is the snapshot.+ expect(readFileSync(archive, 'utf8')).toBe(before)+ expect(readFileSync(journal, 'utf8')).toBe(snapshotEvents(storeOf(state).loop).map(encodeLine).join(''))+ // Run again at the same instant: the archive name is taken, so the copy refuses and nothing is replaced.+ writeFileSync(journal, 'newer\n')+ await rotate(storeOf(state), hostOfRoot(dir).host as never, dir, T0 + 5000)+ expect(readFileSync(archive, 'utf8')).toBe(before)+ expect(readFileSync(journal, 'utf8')).toBe('newer\n')+ })+})