fauxnix-cli 1.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,8 +15,12 @@ back output that looks like GNU/Linux: `ls -l` columns, bash-style error message
15
15
  codes, UTF-8/GBK handled automatically.
16
16
 
17
17
  One-command install for **Claude Code · Codex · OpenCode · Kimi Code · Qwen Code**, plus any MCP
18
- client. **109 translated commands · 400+ automated tests · 253-case differential corpus verified
19
- against real GNU coreutils · zero LLM calls at runtime.**
18
+ client. **109 translated commands · 1,044 automated tests · 270-case Git Bash differential
19
+ corpus plus 41 supplementary checks · zero LLM calls at runtime.**
20
+
21
+ This checkout prepares **v2.0.0**. See [migration and release notes](docs/releases/v2.0.0.md)
22
+ for the Node.js requirement, changed file-operation contracts and verification limits.
23
+ The npm badge and `@latest` examples show the published version until publication completes.
20
24
 
21
25
  ## Try it now — no install
22
26
 
@@ -49,7 +53,9 @@ config files yourself.
49
53
 
50
54
  > npm package name is `fauxnix-cli` (the `fauxnix` name on npm belongs to an unrelated 2015
51
55
  > websocket library); the installed command is `fauxnix`. Requires Windows with PowerShell 5.1+
52
- > (built-in) and Node.js ≥ 18.
56
+ > (built-in) and Node.js ≥ 22.20.0.
57
+ > Node 18/20 are unsupported in v2. Current Node 22/24 LTS patches are tested.
58
+ > Published v1.0.0 retains its original metadata.
53
59
 
54
60
  <details>
55
61
  <summary><b>Manual config per harness</b></summary>
@@ -123,6 +129,26 @@ structured result per step in a single MCP round trip (stops on first nonzero ex
123
129
  See [compiled MCP batch plans](docs/rfc-mcp-batch-plans.md) for timeout, budget, cancellation,
124
130
  and preflight semantics.
125
131
 
132
+ ### Experimental: native shell facade
133
+
134
+ Point Claude Code's **built-in Bash tool** at fauxnix — no MCP sidecar, zero protocol round
135
+ trips per command:
136
+
137
+ ```bash
138
+ fauxnix install --claude-shell # builds a fauxnix-backed bash.exe (~85 MB) and sets
139
+ # CLAUDE_CODE_GIT_BASH_PATH; restart Claude Code after
140
+ fauxnix doctor # reports the launcher status
141
+ fauxnix install --claude-shell-off # restores the previous setting
142
+ ```
143
+
144
+ The launcher is a copy of your own node.exe with the facade bundle injected via Node SEA
145
+ (experimental trade-off; the GA plan is a small prebuilt stub). It implements the bash argv
146
+ contract (`bash -c`/`-lc`, `$0`/`$1` from trailing operands), adapts the harness's private
147
+ command scaffolding (captured from a live session — payload execution, cwd markers, snapshot
148
+ stubs), and always identifies itself via `--version`. The harness's own Bash approval flow
149
+ governs runs. `fauxnix facade` also runs standalone. Details, security rules, and the protocol
150
+ findings: [RFC — native shell facade](docs/rfc-bash-facade.md).
151
+
126
152
  ## Measured: your model is probably worse at PowerShell than you think
127
153
 
128
154
  Same model (DeepSeek-V4-Pro), same 5 tasks, three execution modes on one Windows machine —
@@ -150,7 +176,7 @@ isn't curl, mojibake from codepage mismatches, inscrutable `CategoryInfo` error
150
176
  | agent writes plain bash | ✓ | ✓ | ✓ | ✗ |
151
177
  | only needs Node (no bash toolchain / VM) | ✓ | ✗ | ✗ (VM, GBs) | ✓ |
152
178
  | native Windows filesystem & environment | ✓ | mostly | ✗ (9P bridge) | ✓ |
153
- | GNU-exact output, verified | ✓ 253-case differential | ✓ (is GNU) | ✓ | ✗ |
179
+ | differential compatibility | 269/270 cases identical; limits below | GNU reference | GNU tools | different contracts |
154
180
  | CRLF / UTF-8 / GBK traps handled | ✓ | locale-dependent | ✓ | ✗ |
155
181
 
156
182
  **If Git Bash already works for you, keep it** — we literally use it as our differential-testing
@@ -250,10 +276,33 @@ fauxnix optimizes for the commands agents actually run. Documented deviations:
250
276
  (as in Git Bash).
251
277
  - `ps aux` columns are approximations (no per-process CPU% accounting, USER shows `?`).
252
278
  - `gzip -c`/pipeline stdin is text-faithful, not byte-faithful; file-mode `gzip f` is byte-exact.
279
+ - Gzip decompression and `gzip -t` use Node's strict streaming decoder, including
280
+ every concatenated member. Incomplete streams and checksum errors fail without
281
+ committing a destination or deleting the archive. Trailing non-gzip garbage is
282
+ an error rather than GNU's warning. Text stdout is validated before emission and
283
+ needs temporary disk space proportional to decoded size; `-t` discards output.
284
+ Standalone translated scripts require supported `node.exe` on PATH. See the
285
+ [strict gzip contract](docs/rfc-strict-gzip.md) for cancellation and spool limits.
286
+ - `mv` replaces regular files only within one volume, without predeleting the
287
+ destination. Cross-volume replacement, leaf reparse-point replacement, and
288
+ replacing an existing empty directory fail explicitly with originals retained;
289
+ `-f` does not bypass these limits. Existing-target `-n` still skips. Ordinary
290
+ absent-target moves retain PowerShell behavior and are not transactional across
291
+ volumes. Identity checks and rename are separate operations, not a race-proof
292
+ transaction. See the [move contract](docs/rfc-safe-file-move.md).
293
+ - `stat --printf` omits the implicit newline and interprets text escapes, including ASCII
294
+ octal/hex escapes. Numeric escapes producing bytes `0x80`–`0xFF` are rejected before output;
295
+ use literal Unicode text instead. NUL is preserved in direct output, text pipelines, and
296
+ redirected files; command substitution retains fauxnix's existing text behavior rather
297
+ than Bash's NUL-removal behavior.
253
298
  - A pipeline producing exactly one line, piped into `wc -l`, counts that line (bash would count 0
254
299
  if the producer omitted the trailing newline). `printf 'x' | md5sum` stays byte-exact.
255
300
  - `sed`/`awk` support the common subset; hold-space, labels, arrays, loops throw named
256
301
  "not supported" errors at translate time.
302
+ For `awk` programs using `printf`, terminal and file-redirect output streams per formatted
303
+ fragment. Pipeline and command-substitution output is coalesced into one text value to
304
+ preserve adjacent fragments without adding separators. That intermediate value requires
305
+ memory proportional to output size and is not capped by the caller's capture budget.
257
306
  - `curl`/`wget` refuse loopback/private/reserved addresses (localhost, 127.x, ::1, 10.x,
258
307
  172.16–31.x, 192.168.x, 169.254.x) as a safety default for agent-driven HTTP.
259
308
  - **Native-tool pipelines vs encoding**: PS 5.1 has a single console-encoding knob, so piping
@@ -272,10 +321,14 @@ npm run build
272
321
  npx tsx scratch/run.mjs "any bash command" # quick live check
273
322
  ```
274
323
 
275
- Differential vs Git Bash is opt-in (`FAUXNIX_DIFF_ORACLE=1`; skips if unset or `bash.exe` is
276
- missing — Git Bash is not required). See [`test/differential/README.md`](test/differential/README.md).
277
- The 253-case corpus enforces the RFC C-7 minimum of 200 cases and a 95% identity gate; the weekly
278
- oracle runs from `.github/workflows/differential.yml`.
324
+ Differential vs Git Bash is locally opt-in (`FAUXNIX_DIFF_ORACLE=1`). The minimum-runtime
325
+ Windows x64 / PowerShell 5.1 CI lane requires Git Bash and runs the 270-case primary corpus
326
+ plus a separate 41-case supplementary corpus. Other lanes may skip these checks.
327
+ The primary corpus currently matches 269/270 cases (99.6%); the remaining observed mismatch
328
+ is the documented Git Bash empty-regex-alternative behavior. The historical 253-case result
329
+ is not a same-corpus comparison. See [`test/differential/README.md`](test/differential/README.md).
330
+ The primary gate remains at least 200 cases and 95% identity; the weekly oracle also runs
331
+ from `.github/workflows/differential.yml`.
279
332
 
280
333
  Architecture map: `src/parser.ts` (bash subset → AST) · `src/translator.ts` (AST → PowerShell +
281
334
  executor wrapper) · `src/executor.ts` (spawn, redirects, session persistence) ·
package/dist/cli.js CHANGED
@@ -6,6 +6,8 @@ import { listCommandsJson, registeredNames, specsMarkdown } from './registry.js'
6
6
  import { encodeCommand } from './encoding.js';
7
7
  import { startMcpServer } from './mcp.js';
8
8
  import { collectDoctorReport } from './doctor.js';
9
+ import { runFacade } from './facade.js';
10
+ import { installClaudeShell, uninstallClaudeShell } from './facade-launch.js';
9
11
  import { runInstall } from './install.js';
10
12
  import { packageVersion } from './version.js';
11
13
  import { POWERSHELL_ARGS, powerShellDisplay, powerShellMissingMessage, resolvePowerShell, } from './powershell.js';
@@ -63,6 +65,17 @@ export async function runCli(argv) {
63
65
  return;
64
66
  }
65
67
  if (verb === 'install') {
68
+ if (rest.includes('--claude-shell')) {
69
+ // Experimental: bash.exe facade launcher (RFC: docs/rfc-bash-facade.md)
70
+ for (const line of await installClaudeShell())
71
+ console.log(line);
72
+ return;
73
+ }
74
+ if (rest.includes('--claude-shell-off')) {
75
+ for (const line of await uninstallClaudeShell())
76
+ console.log(line);
77
+ return;
78
+ }
66
79
  const result = runInstall(rest);
67
80
  for (const line of result.lines)
68
81
  console.log(line);
@@ -74,6 +87,12 @@ export async function runCli(argv) {
74
87
  await startMcpServer();
75
88
  return;
76
89
  }
90
+ if (verb === 'facade') {
91
+ // Experimental bash.exe-compatible entry (RFC: docs/rfc-bash-facade.md).
92
+ // Let pending stdout/stderr writes drain before the process exits.
93
+ process.exitCode = await runFacade(rest);
94
+ return;
95
+ }
77
96
  if (verb === 'translate') {
78
97
  const cmd = rest.join(' ');
79
98
  const list = parseCommand(cmd);
@@ -89,13 +108,17 @@ export async function runCli(argv) {
89
108
  const list = parseCommand(cmd);
90
109
  const plans = translateCommandList(list, EXECUTE_TRANSLATION);
91
110
  const session = new FauxnixSession();
92
- const result = await session.run(plans);
93
- if (result.stdout)
94
- process.stdout.write(result.stdout);
95
- if (result.stderr)
96
- process.stderr.write(result.stderr);
97
- await session.dispose();
98
- process.exit(result.exitCode);
111
+ try {
112
+ const result = await session.run(plans);
113
+ if (result.stdout)
114
+ process.stdout.write(result.stdout);
115
+ if (result.stderr)
116
+ process.stderr.write(result.stderr);
117
+ process.exitCode = result.exitCode;
118
+ }
119
+ finally {
120
+ await session.dispose();
121
+ }
99
122
  }
100
123
  async function runDoctor() {
101
124
  const checkOk = await runCheck();
@@ -1,8 +1,9 @@
1
1
  import { wordToString } from '../ast.js';
2
- import { psStr } from '../registry.js';
2
+ import { parseWords } from '../registry.js';
3
3
  import { argListExpr, exprOfWord, operandExpr } from '../translator.js';
4
+ import { gzipNodeFunctions } from './gzip-node.js';
4
5
  /* ------------------------------------------------------------------ */
5
- /* gzip family — .NET GZipStream helpers */
6
+ /* gzip family — .NET compression and strict Node decoding */
6
7
  /* ------------------------------------------------------------------ */
7
8
  const PS_GZ_FNS = [
8
9
  'Add-Type -AssemblyName System.IO.Compression',
@@ -28,88 +29,102 @@ const PS_GZ_FNS = [
28
29
  ' $fx_gz.Close()',
29
30
  ' return ,$fx_ms.ToArray()',
30
31
  '}',
31
- 'function fx-gz-open($src, $isBytes) {',
32
- ' if ($isBytes) { $fx_raw = New-Object System.IO.MemoryStream(,$src) }',
33
- ' else { $fx_raw = [IO.File]::OpenRead($src) }',
32
+ 'function fx-gz-output-exists($dst) {',
33
+ " [Console]::Error.WriteLine('gzip: ' + $dst + ' already exists; not overwritten')",
34
+ ' if ($script:fx_exit -ne 1) { $script:fx_exit = 2 }',
35
+ '}',
36
+ // File compression is no-clobber by default. Ownership begins only after
37
+ // CreateNew succeeds, so a failed open never removes somebody else's file.
38
+ 'function fx-gz-write-new($b, $dst) {',
39
+ ' $fx_os = $null',
40
+ ' $fx_owned = $false',
34
41
  ' try {',
35
- ' return (New-Object System.IO.Compression.GZipStream($fx_raw, [System.IO.Compression.CompressionMode]::Decompress))',
36
- ' } catch {',
37
- ' $fx_raw.Dispose()',
38
- ' throw',
42
+ ' try {',
43
+ ' $fx_os = [IO.File]::Open($dst, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None)',
44
+ ' $fx_owned = $true',
45
+ ' } catch {',
46
+ // This post-failure check selects a diagnostic; CreateNew enforces the
47
+ // no-overwrite contract even if a destination appears during the operation.
48
+ ' if (Test-Path -LiteralPath $dst) { fx-gz-output-exists $dst; return $false }',
49
+ ' throw',
50
+ ' }',
51
+ ' $fx_os.Write($b, 0, $b.Length)',
52
+ ' $fx_os.Dispose(); $fx_os = $null',
53
+ ' $fx_owned = $false',
54
+ ' return $true',
55
+ ' } finally {',
56
+ ' try { if ($null -ne $fx_os) { $fx_os.Dispose() } }',
57
+ ' finally { if ($fx_owned -and [IO.File]::Exists($dst)) { [IO.File]::Delete($dst) } }',
39
58
  ' }',
40
59
  '}',
41
- // Drain the complete stream before producing stdout. Besides keeping -t
42
- // bounded, this preserves the old all-or-nothing behavior for malformed
43
- // inputs while remembering which text decoder the second pass should use.
44
60
  'function fx-gz-validate($src, $isBytes) {',
61
+ ' fx-gz-decode $src $isBytes ([IO.Stream]::Null) $true',
62
+ ' return $true',
63
+ '}',
64
+ 'function fx-gz-stream-text($src, $isBytes) {',
45
65
  ' $fx_gz = fx-gz-open $src $isBytes',
46
- ' $fx_buf = New-Object byte[] 65536',
47
- ' $fx_dec = (New-Object System.Text.UTF8Encoding($false, $true)).GetDecoder()',
48
- ' $fx_utf8 = $true',
66
+ ' $fx_sr = $null',
49
67
  ' try {',
68
+ ' $fx_buf = New-Object byte[] 65536',
69
+ ' $fx_dec = (New-Object System.Text.UTF8Encoding($false, $true)).GetDecoder()',
70
+ ' $fx_utf8 = $true',
50
71
  ' while ($true) {',
51
72
  ' $fx_n = $fx_gz.Read($fx_buf, 0, $fx_buf.Length)',
52
73
  ' if ($fx_n -le 0) { break }',
53
- ' if ($fx_utf8) {',
54
- ' try { [void]$fx_dec.GetCharCount($fx_buf, 0, $fx_n, $false) }',
55
- ' catch [System.Text.DecoderFallbackException] { $fx_utf8 = $false }',
56
- ' }',
74
+ ' try { [void]$fx_dec.GetCharCount($fx_buf, 0, $fx_n, $false) }',
75
+ ' catch [System.Text.DecoderFallbackException] { $fx_utf8 = $false; break }',
57
76
  ' }',
58
77
  ' if ($fx_utf8) {',
59
78
  ' try { [void]$fx_dec.GetCharCount($fx_buf, 0, 0, $true) }',
60
79
  ' catch [System.Text.DecoderFallbackException] { $fx_utf8 = $false }',
61
80
  ' }',
62
- ' return $fx_utf8',
63
- ' } finally {',
64
- ' $fx_gz.Dispose()',
65
- ' }',
66
- '}',
67
- 'function fx-gz-stream-text($src, $isBytes) {',
68
- ' $fx_utf8 = fx-gz-validate $src $isBytes',
69
- ' if ($fx_utf8) { $fx_enc = New-Object System.Text.UTF8Encoding($false, $true) }',
70
- ' else { try { $fx_enc = [System.Text.Encoding]::GetEncoding(936) } catch { $fx_enc = [System.Text.Encoding]::ASCII } }',
71
- ' $fx_gz = fx-gz-open $src $isBytes',
72
- ' $fx_sr = New-Object System.IO.StreamReader($fx_gz, $fx_enc, $false, 65536)',
73
- ' try {',
81
+ ' $fx_gz.Position = 0',
82
+ ' if ($fx_utf8) { $fx_enc = New-Object System.Text.UTF8Encoding($false, $true) }',
83
+ ' else { try { $fx_enc = [System.Text.Encoding]::GetEncoding(936) } catch { $fx_enc = [System.Text.Encoding]::ASCII } }',
84
+ ' $fx_sr = New-Object System.IO.StreamReader($fx_gz, $fx_enc, $false, 65536)',
74
85
  ' while ($true) {',
75
86
  ' $fx_line = $fx_sr.ReadLine()',
76
87
  ' if ($null -eq $fx_line) { break }',
77
88
  ' Write-Output -NoEnumerate $fx_line',
78
89
  ' }',
79
90
  ' } finally {',
80
- ' $fx_sr.Dispose()',
91
+ ' if ($null -ne $fx_sr) { $fx_sr.Dispose() } else { $fx_gz.Dispose() }',
81
92
  ' }',
82
93
  '}',
83
94
  // File output is streamed into a sibling temporary file. The destination
84
- // changes only after a complete decompression, and the temporary is removed
85
- // on every failed path.
95
+ // is created only after the stream has been drained. File.Move never
96
+ // overwrites an existing destination, including one that appeared late.
86
97
  'function fx-gz-stream-file($src, $dst) {',
87
98
  ' $fx_full = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($dst)',
88
99
  ' $fx_parent = [IO.Path]::GetDirectoryName($fx_full)',
89
100
  " $fx_tmp = [IO.Path]::Combine($fx_parent, '.fauxnix-gzip-' + [Guid]::NewGuid().ToString('N') + '.tmp')",
90
- ' $fx_gz = $null',
91
101
  ' $fx_os = $null',
102
+ ' $fx_tmpOwned = $false',
103
+ ' $fx_outputPhase = $false',
92
104
  ' try {',
93
- ' $fx_gz = fx-gz-open $src $false',
94
- " $fx_os = New-Object System.IO.FileStream($fx_tmp, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None)",
95
- ' $fx_buf = New-Object byte[] 65536',
96
- ' while ($true) {',
97
- ' $fx_n = $fx_gz.Read($fx_buf, 0, $fx_buf.Length)',
98
- ' if ($fx_n -le 0) { break }',
99
- ' $fx_os.Write($fx_buf, 0, $fx_n)',
100
- ' }',
105
+ ' $fx_outputPhase = $true',
106
+ ' $fx_os = [IO.File]::Open($fx_tmp, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None)',
107
+ ' $fx_tmpOwned = $true',
108
+ ' $fx_outputPhase = $false',
109
+ ' fx-gz-decode $src $false $fx_os $false',
110
+ ' $fx_outputPhase = $true',
101
111
  ' $fx_os.Dispose(); $fx_os = $null',
102
- ' $fx_gz.Dispose(); $fx_gz = $null',
103
- ' if ([IO.File]::Exists($fx_full)) {',
104
- ' $fx_null = [System.Management.Automation.Language.NullString]::Value',
105
- ' [IO.File]::Replace($fx_tmp, $fx_full, $fx_null)',
112
+ ' try { [IO.File]::Move($fx_tmp, $fx_full); $fx_tmpOwned = $false }',
113
+ ' catch {',
114
+ ' if (Test-Path -LiteralPath $dst) { fx-gz-output-exists $dst; return $false }',
115
+ ' throw',
106
116
  ' }',
107
- ' else { [IO.File]::Move($fx_tmp, $fx_full) }',
117
+ ' return $true',
108
118
  ' } catch {',
109
- ' if ($null -ne $fx_os) { $fx_os.Dispose() }',
110
- ' if ($null -ne $fx_gz) { $fx_gz.Dispose() }',
111
- ' if ([IO.File]::Exists($fx_tmp)) { [IO.File]::Delete($fx_tmp) }',
119
+ ' if ($fx_outputPhase) {',
120
+ " [Console]::Error.WriteLine('gzip: ' + $dst + ': ' + $_.Exception.Message)",
121
+ ' $script:fx_exit = 1',
122
+ ' return $false',
123
+ ' }',
112
124
  ' throw',
125
+ ' } finally {',
126
+ ' try { if ($null -ne $fx_os) { $fx_os.Dispose() } }',
127
+ ' finally { if ($fx_tmpOwned -and [IO.File]::Exists($fx_tmp)) { [IO.File]::Delete($fx_tmp) } }',
113
128
  ' }',
114
129
  '}',
115
130
  ].join('\n');
@@ -153,11 +168,7 @@ function parseGzipArgs(args) {
153
168
  // other long options (force/quiet/verbose/no-name/recursive...) ignored
154
169
  continue;
155
170
  }
156
- if (/^-[1-9]$/.test(t)) {
157
- p.level = parseInt(t.slice(1), 10);
158
- continue;
159
- }
160
- if (t.startsWith('-') && t.length > 1 && !/^-\d/.test(t)) {
171
+ if (t.startsWith('-') && t.length > 1 && (!/^-\d/.test(t) || /^-[1-9]/.test(t))) {
161
172
  for (const c of t.slice(1)) {
162
173
  if (c === 'd')
163
174
  p.decompress = true;
@@ -167,6 +178,8 @@ function parseGzipArgs(args) {
167
178
  p.stdout = true;
168
179
  else if (c === 't')
169
180
  p.test = true;
181
+ else if (/^[1-9]$/.test(c))
182
+ p.level = Number(c);
170
183
  // f/q/v/n/r accepted as no-ops
171
184
  }
172
185
  continue;
@@ -202,7 +215,7 @@ function gzBlock(args, ctx, forced) {
202
215
  ' try {',
203
216
  p.test ? ' [void](fx-gz-validate $fx_in $true)' : ' fx-gz-stream-text $fx_in $true',
204
217
  ' } catch {',
205
- " [Console]::Error.WriteLine('gzip: stdin: not in gzip format')",
218
+ " [Console]::Error.WriteLine('gzip: stdin: ' + $_.Exception.Message)",
206
219
  ' $script:fx_exit = 1',
207
220
  ' }',
208
221
  ].join('\n')
@@ -227,29 +240,38 @@ function gzBlock(args, ctx, forced) {
227
240
  ' }',
228
241
  ];
229
242
  if (p.test) {
230
- fileLoop.push(' try { [void](fx-gz-validate $fx_f $false) }', " catch { [Console]::Error.WriteLine('gzip: ' + $fx_f + ': not in gzip format'); $script:fx_exit = 1 }", ' continue');
243
+ fileLoop.push(' try { [void](fx-gz-validate $fx_f $false) }', " catch { [Console]::Error.WriteLine('gzip: ' + $fx_f + ': ' + $_.Exception.Message); $script:fx_exit = 1 }", ' continue');
231
244
  }
232
245
  else if (p.decompress) {
233
- fileLoop.push(' $fx_low = $fx_f.ToLower()', " if (-not ($fx_low.EndsWith('.gz') -or $fx_low.EndsWith('.tgz'))) {", " [Console]::Error.WriteLine('gzip: ' + $fx_f + ': unknown suffix -- ignored')", ' $script:fx_exit = 2', ' continue', ' }', ' $fx_out = $fx_f.Substring(0, $fx_f.Length - 3)', " if ($fx_low.EndsWith('.tgz')) { $fx_out = $fx_f.Substring(0, $fx_f.Length - 4) + '.tar' }", ' try {', p.stdout
246
+ // Suffixes determine a destination filename only. gunzip -c and zcat
247
+ // validate the stream itself and accept any source filename.
248
+ if (!p.stdout) {
249
+ fileLoop.push(' $fx_low = $fx_f.ToLower()', " if (-not ($fx_low.EndsWith('.gz') -or $fx_low.EndsWith('.tgz'))) {", " [Console]::Error.WriteLine('gzip: ' + $fx_f + ': unknown suffix -- ignored')", ' if ($script:fx_exit -ne 1) { $script:fx_exit = 2 }', ' continue', ' }', ' $fx_out = $fx_f.Substring(0, $fx_f.Length - 3)', " if ($fx_low.EndsWith('.tgz')) { $fx_out = $fx_f.Substring(0, $fx_f.Length - 4) + '.tar' }");
250
+ }
251
+ fileLoop.push(' try {', p.stdout
234
252
  ? ' fx-gz-stream-text $fx_f $false'
235
253
  : [
236
- ' fx-gz-stream-file $fx_f $fx_out',
254
+ ' if (-not (fx-gz-stream-file $fx_f $fx_out)) { continue }',
237
255
  ' try { (Get-Item -LiteralPath $fx_out).LastWriteTime = (Get-Item -LiteralPath $fx_f).LastWriteTime } catch {}',
238
- ' if (-not ' + b(p.keep) + ') { Remove-Item -LiteralPath $fx_f -Force }',
239
- ].join('\n'), " } catch { [Console]::Error.WriteLine('gzip: ' + $fx_f + ': not in gzip format'); $script:fx_exit = 1 }");
256
+ ' if (-not ' + b(p.keep) + ') { Remove-Item -LiteralPath $fx_f -Force -ErrorAction Stop }',
257
+ ].join('\n'), " } catch { [Console]::Error.WriteLine('gzip: ' + $fx_f + ': ' + $_.Exception.Message); $script:fx_exit = 1 }");
240
258
  }
241
259
  else {
242
- fileLoop.push(' $fx_low = $fx_f.ToLower()', " if ($fx_low.EndsWith('.gz') -or $fx_low.EndsWith('.tgz')) {", " [Console]::Error.WriteLine('gzip: ' + $fx_f + ': already has .gz suffix -- unchanged')", ' continue', ' }', ' try {', p.stdout
260
+ if (!p.stdout) {
261
+ fileLoop.push(' $fx_low = $fx_f.ToLower()', " if ($fx_low.EndsWith('.gz') -or $fx_low.EndsWith('.tgz')) {", " [Console]::Error.WriteLine('gzip: ' + $fx_f + ': already has .gz suffix -- unchanged')", ' continue', ' }');
262
+ }
263
+ fileLoop.push(' try {', p.stdout
243
264
  ? ' ' + emitBin('(fx-gz-cbytes ([IO.File]::ReadAllBytes($fx_f)) ' + p.level + ')')
244
265
  : [
245
266
  ' $fx_o = fx-gz-cbytes ([IO.File]::ReadAllBytes($fx_f)) ' + p.level,
246
- " [IO.File]::WriteAllBytes($fx_f + '.gz', $fx_o)",
267
+ " if (-not (fx-gz-write-new $fx_o ($fx_f + '.gz'))) { continue }",
247
268
  " try { (Get-Item -LiteralPath ($fx_f + '.gz')).LastWriteTime = (Get-Item -LiteralPath $fx_f).LastWriteTime } catch {}",
248
- ' if (-not ' + b(p.keep) + ') { Remove-Item -LiteralPath $fx_f -Force }',
269
+ ' if (-not ' + b(p.keep) + ') { Remove-Item -LiteralPath $fx_f -Force -ErrorAction Stop }',
249
270
  ].join('\n'), " } catch { [Console]::Error.WriteLine('gzip: ' + $fx_f + ': ' + $_.Exception.Message); $script:fx_exit = 1 }");
250
271
  }
251
272
  fileLoop.push(' }');
252
273
  return [
274
+ gzipNodeFunctions(ctx.translationMode === 'pure'),
253
275
  PS_GZ_FNS,
254
276
  '$fx_files = ' + (p.files.length ? argListExpr(p.files, operandExpr) : '@()'),
255
277
  'if ($fx_files.Count -eq 0) {',
@@ -292,38 +314,16 @@ const tar = (args) => {
292
314
  /* zip / unzip */
293
315
  /* ------------------------------------------------------------------ */
294
316
  const zip = (args) => {
295
- const raw = args.map(wordToString);
296
- let excludeNote = false;
297
- const rest = [];
298
- for (let i = 0; i < raw.length; i++) {
299
- const t = raw[i];
300
- if (t === '-x' || t === '--exclude') {
301
- excludeNote = true;
302
- if (i + 1 < args.length)
303
- i++;
304
- continue;
305
- }
306
- if (t.startsWith('--exclude=')) {
307
- excludeNote = true;
308
- continue;
309
- }
310
- if (t.startsWith('-') && t.length > 1 && !/^-\d/.test(t))
311
- continue; // -r -q ... implicit
312
- rest.push(args[i]);
313
- }
314
- const note = excludeNote
315
- ? '[Console]::Error.WriteLine(' +
316
- psStr('zip: fauxnix: -x/--exclude patterns are not supported, ignoring') +
317
- ')\n'
318
- : '';
317
+ // CommandSpec has already rejected unsupported options. Keep the same
318
+ // operand boundary as that validation, especially filenames after `--`.
319
+ const { operandWords: rest } = parseWords(args);
319
320
  if (rest.length < 2) {
320
- return (note +
321
- "[Console]::Error.WriteLine('zip error: Nothing to do! (fauxnix: usage: zip [-r] ARCHIVE FILES...)'); $script:fx_exit = 12");
321
+ return "[Console]::Error.WriteLine('zip error: Nothing to do! (fauxnix: usage: zip [-r] ARCHIVE FILES...)'); $script:fx_exit = 12";
322
322
  }
323
323
  const arc = operandExpr(rest[0]);
324
324
  const inputs = argListExpr(rest.slice(1), operandExpr);
325
325
  return [
326
- note + '$fx_arc = ' + arc,
326
+ '$fx_arc = ' + arc,
327
327
  '$fx_inputs = ' + inputs,
328
328
  '$fx_valid = @()',
329
329
  'foreach ($fx_p in $fx_inputs) {',
@@ -359,11 +359,36 @@ const zip = (args) => {
359
359
  ' }',
360
360
  ' }',
361
361
  ' } finally { $fx_z.Dispose() }',
362
- ' if ($fx_rename) { Move-Item -LiteralPath $fx_dst -Destination $fx_arc -Force }',
362
+ ' if ($fx_rename) { Move-Item -LiteralPath $fx_dst -Destination $fx_arc -Force -ErrorAction Stop }',
363
363
  " } catch { [Console]::Error.WriteLine('zip: fauxnix: ' + $_.Exception.Message); $script:fx_exit = 1 }",
364
364
  '}',
365
365
  ].join('\n');
366
366
  };
367
+ /** Remove a literal option prefix without flattening quoted/dynamic values. */
368
+ function afterOptionPrefix(word, length) {
369
+ let remaining = length;
370
+ const strip = (parts) => {
371
+ const result = [];
372
+ for (const part of parts) {
373
+ if (remaining === 0) {
374
+ result.push(part);
375
+ }
376
+ else if (part.kind === 'Text' || part.kind === 'SingleQuoted') {
377
+ const taken = Math.min(remaining, part.text.length);
378
+ remaining -= taken;
379
+ if (taken < part.text.length)
380
+ result.push({ ...part, text: part.text.slice(taken) });
381
+ }
382
+ else if (part.kind === 'DoubleQuoted') {
383
+ const tail = strip(part.parts);
384
+ if (tail.length > 0)
385
+ result.push({ ...part, parts: tail });
386
+ }
387
+ }
388
+ return result;
389
+ };
390
+ return strip(word);
391
+ }
367
392
  const unzip = (args) => {
368
393
  const raw = args.map(wordToString);
369
394
  let list = false;
@@ -372,14 +397,12 @@ const unzip = (args) => {
372
397
  const rest = [];
373
398
  for (let i = 0; i < raw.length; i++) {
374
399
  const t = raw[i];
375
- if (t === '-d' && i + 1 < args.length) {
376
- dir = args[i + 1];
377
- i++;
378
- continue;
400
+ if (t === '--') {
401
+ rest.push(...args.slice(i + 1));
402
+ break;
379
403
  }
380
404
  if (t.startsWith('--directory=')) {
381
- const dv = [{ kind: 'Text', text: t.slice('--directory='.length) }];
382
- dir = dv;
405
+ dir = afterOptionPrefix(args[i], '--directory='.length);
383
406
  continue;
384
407
  }
385
408
  if (t === '--directory' && i + 1 < args.length) {
@@ -388,10 +411,19 @@ const unzip = (args) => {
388
411
  continue;
389
412
  }
390
413
  if (t.startsWith('-') && t.length > 1 && !/^-\d/.test(t)) {
391
- if (t.includes('l'))
392
- list = true;
393
- if (t.includes('o'))
394
- over = true;
414
+ for (let c = 1; c < t.length; c++) {
415
+ if (t[c] === 'l')
416
+ list = true;
417
+ else if (t[c] === 'o')
418
+ over = true;
419
+ else if (t[c] === 'd') {
420
+ if (c + 1 < t.length)
421
+ dir = afterOptionPrefix(args[i], c + 1);
422
+ else if (i + 1 < args.length)
423
+ dir = args[++i];
424
+ break;
425
+ }
426
+ }
395
427
  continue;
396
428
  }
397
429
  rest.push(args[i]);
@@ -1,5 +1,6 @@
1
1
  import { CommandSpec, Handler } from '../registry.js';
2
2
  /** Destructive file commands migrated first (#130). Unspec'd handlers stay unchecked.
3
- * cp/mv `-f`/`--force` is always-on overwrite (Copy-Item/Move-Item -Force); listed so `cp -rf` stays valid. */
3
+ * cp `-f` is always-on overwrite. mv `-f` retains safe same-volume regular-file
4
+ * replacement and never overrides preservation limits or permissions. */
4
5
  export declare const specs: CommandSpec[];
5
6
  export declare const handlers: Record<string, Handler>;