fauxnix-cli 2.1.1 → 2.2.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.
@@ -4,7 +4,7 @@ import path from 'node:path';
4
4
  import { FauxnixParseError, wordToString } from '../ast.js';
5
5
  import { parseWords, psStr } from '../registry.js';
6
6
  import { PS_WRITE_FN, fxTermLine } from './text-output.js';
7
- import { argListExpr, exprOfWord, literalOfWord, operandExpr, PURE_SED_FILE_MESSAGE, } from '../translator.js';
7
+ import { argListExpr, exprOfWord, globOperandExpr, literalOfWord, operandExpr, PURE_SED_FILE_MESSAGE, } from '../translator.js';
8
8
  /* ------------------------------------------------------------------ */
9
9
  /* Shared PS snippets (same shape as files.ts) */
10
10
  /* ------------------------------------------------------------------ */
@@ -12,9 +12,12 @@ const PS_GLOB_FN = [
12
12
  'function fx-glob($p) {',
13
13
  " if ($p -notlike '*[*?]*') { return @($p) }",
14
14
  ' $m = @(Get-Item -Path $p -ErrorAction SilentlyContinue)',
15
- ' if ($m.Count -eq 0) { return @($p) }',
15
+ ' if ($m.Count -eq 0) { return @(fx-wclit $p) }',
16
16
  ' return @($m | ForEach-Object { $_.FullName })',
17
17
  '}',
18
+ // Unescape wildcard-escaped literals (#255): quoted glob characters that
19
+ // matched nothing keep their shell spelling as the literal operand.
20
+ "function fx-wclit($p) { return ($p -replace '`(?=[*?[])', '') }",
18
21
  ].join('\n');
19
22
  const PS_READTEXT_FN = [
20
23
  'function fx-read($p) {',
@@ -415,7 +418,7 @@ const grep = (args) => {
415
418
  lines.push(' }');
416
419
  lines.push('}');
417
420
  }
418
- lines.push('foreach ($fx_o in ' + psArray(fileWords) + ') {');
421
+ lines.push('foreach ($fx_o in ' + psArray(fileWords, globOperandExpr) + ') {');
419
422
  lines.push(' foreach ($fx_g in (fx-glob $fx_o)) {');
420
423
  lines.push(" if (-not (Test-Path -LiteralPath $fx_g)) { [Console]::Error.WriteLine('grep: ' + $fx_g + ': No such file or directory'); $fx_err = $true; continue }");
421
424
  lines.push(' if (Test-Path -LiteralPath $fx_g -PathType Container) {');
@@ -605,8 +608,16 @@ function sedReplToNet(repl, delim) {
605
608
  out += '\t';
606
609
  else if (n === '&')
607
610
  out += '&';
608
- else if (/[1-9]/.test(n))
609
- out += '$' + n;
611
+ else if (n === '0')
612
+ out += '$&';
613
+ else if (/[1-9]/.test(n)) {
614
+ // \10 is group 1 and a literal 0. $10 would be group 10.
615
+ const next = repl[i + 2];
616
+ if (next !== undefined && /[0-9]/.test(next))
617
+ out += '${' + n + '}';
618
+ else
619
+ out += '$' + n;
620
+ }
610
621
  else
611
622
  out += '\\' + n;
612
623
  i += 2;
@@ -1145,7 +1156,7 @@ const sed = (args, ctx) => {
1145
1156
  lines.push(...hoisted);
1146
1157
  lines.push('$fx_qn = 0');
1147
1158
  if (operandWords.length > 0) {
1148
- lines.push(...psCollectSources(psArray(operandWords), (v) => "[Console]::Error.WriteLine('sed: can''t read ' + " + v + " + ': No such file or directory')", true));
1159
+ lines.push(...psCollectSources(psArray(operandWords, globOperandExpr), (v) => "[Console]::Error.WriteLine('sed: can''t read ' + " + v + " + ': No such file or directory')", true));
1149
1160
  lines.push('foreach ($fx_f in $fx_srcs) {');
1150
1161
  for (const l of scanFile)
1151
1162
  lines.push(' ' + l);
@@ -1615,6 +1626,47 @@ class AwkParser {
1615
1626
  throw new FauxnixParseError("fauxnix: awk unexpected character '" + c + "' in expression");
1616
1627
  }
1617
1628
  }
1629
+ /** d/i/o/x/X. Width counts the sign, so %05d of -42 is -0042, not .NET D5's -00042. */
1630
+ const PS_AWK_IFMT_FN = [
1631
+ 'function fx-awk-ifmt($v, $conv, $flags, $width, $prec) {',
1632
+ ' $n = [long][math]::Truncate((fx-num $v))',
1633
+ " $prefix = ''",
1634
+ " $digits = ''",
1635
+ " if ($conv -ceq 'd') {",
1636
+ ' if ($n -lt 0) {',
1637
+ " $prefix = '-'",
1638
+ " if ($n -eq [long]::MinValue) { $digits = '9223372036854775808' }",
1639
+ ' else { $digits = [string]([math]::Abs([long]$n)) }',
1640
+ ' } else {',
1641
+ " if ($flags.Contains('+')) { $prefix = '+' }",
1642
+ " elseif ($flags.Contains(' ')) { $prefix = ' ' }",
1643
+ ' $digits = [string]$n',
1644
+ ' }',
1645
+ " } elseif ($conv -ceq 'o') {",
1646
+ ' $digits = [Convert]::ToString([long]$n, 8)',
1647
+ " } elseif ($conv -ceq 'X') {",
1648
+ ' $digits = [Convert]::ToString([long]$n, 16).ToUpperInvariant()',
1649
+ ' } else {',
1650
+ ' $digits = [Convert]::ToString([long]$n, 16)',
1651
+ ' }',
1652
+ ' if ($null -ne $prec) {',
1653
+ ' $p = [int]$prec',
1654
+ " if ($p -eq 0 -and $digits -eq '0') { $digits = '' }",
1655
+ ' elseif ($digits.Length -lt $p) { $digits = $digits.PadLeft($p, [char]48) }',
1656
+ ' }',
1657
+ ' $body = $prefix + $digits',
1658
+ ' if ($null -eq $width) { return $body }',
1659
+ ' $w = [int]$width',
1660
+ ' if ($body.Length -ge $w) { return $body }',
1661
+ " if ($flags.Contains('-')) { return $body.PadRight($w) }",
1662
+ " if ($flags.Contains('0') -and $null -eq $prec) {",
1663
+ ' $digits = $digits.PadLeft($w - $prefix.Length, [char]48)',
1664
+ ' return $prefix + $digits',
1665
+ ' }',
1666
+ ' return $body.PadLeft($w)',
1667
+ '}',
1668
+ ].join('\n');
1669
+ const AWK_INT_CONVS = new Set(['d', 'o', 'x', 'X']);
1618
1670
  function awkFmtToPs(fmt) {
1619
1671
  const chunks = [];
1620
1672
  const kinds = [];
@@ -1630,25 +1682,28 @@ function awkFmtToPs(fmt) {
1630
1682
  while (i < fmt.length) {
1631
1683
  const c = fmt[i];
1632
1684
  if (c === '%') {
1633
- // %[-][width][.prec]conv — conv in s c d f
1634
- const m = fmt.slice(i).match(/^%([-+0 ]*)(\d+)?(?:\.(\d+))?([sdfc])/);
1685
+ // %[-+0 ][width][.prec]conv — s/c/f stay on -f; d/i/o/x/X go through fx-awk-ifmt
1686
+ const m = fmt.slice(i).match(/^%([-+0 ]*)(\d+)?(?:\.(\d+))?([sdfcioxX])/);
1635
1687
  if (m) {
1636
1688
  const flags = m[1];
1637
1689
  const width = m[2];
1638
1690
  const prec = m[3];
1639
- const conv = m[4];
1691
+ let conv = m[4];
1692
+ if (conv === 'i')
1693
+ conv = 'd';
1640
1694
  flushLit();
1641
1695
  const idx = kinds.length;
1642
1696
  let spec = '';
1697
+ let align = '';
1698
+ // Integer conversions are fully formatted by fx-awk-ifmt, then spliced in.
1643
1699
  if (conv === 'f') {
1644
1700
  spec = 'F' + (prec === undefined ? '6' : prec);
1645
1701
  }
1646
- else if (conv === 'd' && prec !== undefined) {
1647
- spec = 'D' + prec; // zero-pad, close to awk %.Nd
1702
+ if (!AWK_INT_CONVS.has(conv) && width !== undefined) {
1703
+ align = ',' + (flags.includes('-') ? '-' : '') + width;
1648
1704
  }
1649
- const align = width === undefined ? '' : ',' + (flags.includes('-') ? '-' : '') + width;
1650
1705
  chunks.push("'{" + idx + align + (spec === '' ? '' : ':' + spec) + "}'");
1651
- kinds.push({ conv, align, spec });
1706
+ kinds.push({ conv, align, spec, flags, width, prec });
1652
1707
  i += m[0].length;
1653
1708
  continue;
1654
1709
  }
@@ -1688,6 +1743,19 @@ function awkFmtToPs(fmt) {
1688
1743
  const ps = chunks.length === 0 ? "''" : '(' + chunks.join(' + ') + ')';
1689
1744
  return { ps, kinds };
1690
1745
  }
1746
+ function awkUsesIntPrintf(prog) {
1747
+ const stmts = [
1748
+ ...prog.begin,
1749
+ ...prog.items.flatMap((item) => item.act ?? []),
1750
+ ...prog.end,
1751
+ ];
1752
+ for (const st of stmts) {
1753
+ if (st.k === 'printf' && awkFmtToPs(st.fmt).kinds.some((k) => AWK_INT_CONVS.has(k.conv))) {
1754
+ return true;
1755
+ }
1756
+ }
1757
+ return false;
1758
+ }
1691
1759
  const awk = (args, ctx) => {
1692
1760
  const { values, operandWords } = parseWords(args, ['F', 'v']);
1693
1761
  // -v may repeat; collect all of them
@@ -1882,8 +1950,21 @@ const awk = (args, ctx) => {
1882
1950
  const argExprs = f.kinds.map((kind, idx) => {
1883
1951
  const arg = st.args[idx];
1884
1952
  const raw = gen(arg ?? { k: 'num', v: 0 }).ps;
1885
- if (kind.conv === 'd')
1886
- return '([string][math]::Truncate((fx-num ' + raw + ')))';
1953
+ if (AWK_INT_CONVS.has(kind.conv)) {
1954
+ const w = kind.width === undefined ? '$null' : kind.width;
1955
+ const p = kind.prec === undefined ? '$null' : kind.prec;
1956
+ return ('(fx-awk-ifmt ' +
1957
+ raw +
1958
+ ' ' +
1959
+ psStr(kind.conv) +
1960
+ ' ' +
1961
+ psStr(kind.flags) +
1962
+ ' ' +
1963
+ w +
1964
+ ' ' +
1965
+ p +
1966
+ ')');
1967
+ }
1887
1968
  if (kind.conv === 'f')
1888
1969
  return '(fx-num ' + raw + ')';
1889
1970
  if (kind.conv === 'c') {
@@ -1935,6 +2016,8 @@ const awk = (args, ctx) => {
1935
2016
  if (fileWords.length > 0)
1936
2017
  lines.push(PS_GLOB_FN);
1937
2018
  lines.push('function fx-num($v) {', ' if ($v -is [double]) { return $v }', ' if ($v -is [int] -or $v -is [long]) { return [double]$v }', ' if ($null -eq $v) { return [double]0 }', ' $s = [string]$v', " if ($s -match '^[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$') { return [double]$s }", ' return [double]0', '}', 'function fx-fnum($v) {', ' if ($v -eq [math]::Floor($v) -and [math]::Abs($v) -lt 1e15) { return ([string][long]$v) }', " return ('{0:G6}' -f $v)", '}', 'function fx-str($v) {', ' if ($v -is [double]) { return (fx-fnum $v) }', " if ($null -eq $v) { return '' }", ' return [string]$v', '}', 'function fx-true($v) {', ' if ($v -is [double] -or $v -is [int]) { return ($v -ne 0) }', ' if ($null -eq $v) { return $false }', ' $s = [string]$v', " if ($s -eq '' -or $s -eq '0') { return $false }", ' return $true', '}', 'function fx-cmp($a, $b, $op) {', ' $ad = $null', ' $bd = $null', ' if ($a -is [double] -or $a -is [int]) { $ad = [double]$a }', " elseif ($a -match '^[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$') { $ad = [double]$a }", ' if ($b -is [double] -or $b -is [int]) { $bd = [double]$b }', " elseif ($b -match '^[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$') { $bd = [double]$b }", ' $r = 0', ' if ($null -ne $ad -and $null -ne $bd) {', ' if ($ad -lt $bd) { $r = -1 } elseif ($ad -gt $bd) { $r = 1 }', ' } else {', ' $r = [string]::CompareOrdinal((fx-str $a), (fx-str $b))', ' }', " if ($op -eq 'lt') { return ($r -lt 0) }", " if ($op -eq 'le') { return ($r -le 0) }", " if ($op -eq 'gt') { return ($r -gt 0) }", " if ($op -eq 'ge') { return ($r -ge 0) }", " if ($op -eq 'eq') { return ($r -eq 0) }", ' return ($r -ne 0)', '}', 'function fx-fld($n) {', ' if ($n -ge 1 -and $n -le $fx_flds.Count) { return [string]$fx_flds[$n - 1] }', " return ''", '}', 'function fx-substr($s, $a, $b) {', ' $t = [string]$s', ' $st = [int]$a - 1', ' if ($st -lt 0) { $b = $b + $st; $st = 0 }', " if ($b -lt 1 -or $st -ge $t.Length) { return '' }", ' $len = [math]::Min([int]$b, $t.Length - $st)', ' return $t.Substring($st, $len)', '}', 'function fx-firstchar($v) {', ' $t = [string]$v', ' if ($t.Length -ge 1) { return ([string]$t[0]) }', " return ''", '}');
2019
+ if (awkUsesIntPrintf(prog))
2020
+ lines.push(PS_AWK_IFMT_FN);
1938
2021
  lines.push(...hoistedRegex);
1939
2022
  for (const v of prog.vars)
1940
2023
  lines.push('$fxv_' + v + ' = $null');
@@ -1947,7 +2030,7 @@ const awk = (args, ctx) => {
1947
2030
  lines.push(...genStmts(prog.begin, false));
1948
2031
  lines.push('$fx_nr = 0');
1949
2032
  if (fileWords.length > 0) {
1950
- lines.push(...psCollectSources(psArray(fileWords), (v) => "[Console]::Error.WriteLine('awk: fatal: cannot open file ' + [string][char]96 + " +
2033
+ lines.push(...psCollectSources(psArray(fileWords, globOperandExpr), (v) => "[Console]::Error.WriteLine('awk: fatal: cannot open file ' + [string][char]96 + " +
1951
2034
  v +
1952
2035
  " + [string][char]39 + ' for reading (No such file or directory)')", true));
1953
2036
  lines.push('$fx_lines = @()');
@@ -2055,7 +2138,7 @@ const sort = (args) => {
2055
2138
  }
2056
2139
  }
2057
2140
  const lines = [PS_READTEXT_FN, PS_SPLITLINES_FN, PS_GLOB_FN];
2058
- lines.push(...psCollectSources(psArray(operandWords), (v) => "[Console]::Error.WriteLine('sort: cannot read: ' + " + v + " + ': No such file or directory')", false));
2141
+ lines.push(...psCollectSources(psArray(operandWords, globOperandExpr), (v) => "[Console]::Error.WriteLine('sort: cannot read: ' + " + v + " + ': No such file or directory')", false));
2059
2142
  if (operandWords.length > 0) {
2060
2143
  lines.push('$fx_lines = @()');
2061
2144
  lines.push('foreach ($fx_f in $fx_srcs) { $fx_lines += fx-splitlines (fx-read $fx_f) }');
@@ -2188,7 +2271,7 @@ const uniq = (args) => {
2188
2271
  const lines = [PS_READTEXT_FN, PS_SPLITLINES_FN];
2189
2272
  if (inFile !== null) {
2190
2273
  lines.push(PS_GLOB_FN);
2191
- lines.push(...psCollectSources('@(' + operandExpr(inFile) + ')', (v) => "[Console]::Error.WriteLine('uniq: ' + " + v + " + ': No such file or directory')", false));
2274
+ lines.push(...psCollectSources('@(' + globOperandExpr(inFile) + ')', (v) => "[Console]::Error.WriteLine('uniq: ' + " + v + " + ': No such file or directory')", false));
2192
2275
  lines.push('if ($fx_srcs.Count -gt 0) { $fx_lines = @(fx-splitlines (fx-read $fx_srcs[0])) }');
2193
2276
  lines.push('else { $fx_lines = @() }');
2194
2277
  }
@@ -2299,7 +2382,7 @@ const cut = (args) => {
2299
2382
  .join(' -or ');
2300
2383
  const testExpr = complement ? '(-not (' + inTest + '))' : '(' + inTest + ')';
2301
2384
  const lines = [PS_READTEXT_FN, PS_SPLITLINES_FN, PS_GLOB_FN];
2302
- lines.push(...psCollectSources(psArray(operandWords), (v) => "[Console]::Error.WriteLine('cut: ' + " + v + " + ': No such file or directory')", false));
2385
+ lines.push(...psCollectSources(psArray(operandWords, globOperandExpr), (v) => "[Console]::Error.WriteLine('cut: ' + " + v + " + ': No such file or directory')", false));
2303
2386
  if (operandWords.length > 0) {
2304
2387
  lines.push('$fx_lines = @()');
2305
2388
  lines.push('foreach ($fx_f in $fx_srcs) { $fx_lines += fx-splitlines (fx-read $fx_f) }');
@@ -1,6 +1,6 @@
1
1
  import { wordToString } from '../ast.js';
2
2
  import { lookup, parseWords, psStr } from '../registry.js';
3
- import { argListExpr, exprOfWord, operandExpr } from '../translator.js';
3
+ import { argListExpr, exprOfWord, globOperandExpr, operandExpr } from '../translator.js';
4
4
  import { PS_WRITE_FN, fxTermLine } from './text-output.js';
5
5
  /* ------------------------------------------------------------------ */
6
6
  /* Shared PS snippets (same shape as files.ts / text-filters.ts) */
@@ -9,9 +9,12 @@ const PS_GLOB_FN = [
9
9
  'function fx-glob($p) {',
10
10
  " if ($p -notlike '*[*?]*') { return @($p) }",
11
11
  ' $m = @(Get-Item -Path $p -ErrorAction SilentlyContinue)',
12
- ' if ($m.Count -eq 0) { return @($p) }',
12
+ ' if ($m.Count -eq 0) { return @(fx-wclit $p) }',
13
13
  ' return @($m | ForEach-Object { $_.FullName })',
14
14
  '}',
15
+ // Unescape wildcard-escaped literals (#255): quoted glob characters that
16
+ // matched nothing keep their shell spelling as the literal operand.
17
+ "function fx-wclit($p) { return ($p -replace '`(?=[*?[])', '') }",
15
18
  ].join('\n');
16
19
  const PS_READTEXT_FN = [
17
20
  'function fx-read($p) {',
@@ -109,7 +112,9 @@ function psCollectFiles(operandWords, missErr, dirErr, stdinDefault = true) {
109
112
  const lit = w.every((p) => p.kind === 'Text' || p.kind === 'SingleQuoted')
110
113
  ? w.map((p) => p.text).join('')
111
114
  : null;
112
- out.push('foreach ($fx_d in ' + argListExpr([w], lit !== null ? operandExpr : exprOfWord) + ') {');
115
+ // glob-aware operand expression (#255): quoted metas stay literal through
116
+ // fx-glob; unmatched literals keep their shell spelling via fx-wclit.
117
+ out.push('foreach ($fx_d in ' + argListExpr([w], globOperandExpr) + ') {');
113
118
  out.push('foreach ($fx_g in (fx-glob $fx_d)) {');
114
119
  if (dirErr) {
115
120
  const dis = lit !== null && /[*?]/.test(lit) ? '$fx_g' : '$fx_d';
@@ -118,7 +123,9 @@ function psCollectFiles(operandWords, missErr, dirErr, stdinDefault = true) {
118
123
  '; continue }');
119
124
  }
120
125
  out.push(' if (-not (Test-Path -LiteralPath $fx_g -PathType Leaf)) { ' +
121
- psErrExpr(missErr('$fx_d')) +
126
+ // $fx_g: unmatched literals come back unescaped by fx-wclit, keeping
127
+ // the shell spelling in the message (matched globs resolve anyway).
128
+ psErrExpr(missErr('$fx_g')) +
122
129
  '; continue }');
123
130
  out.push(' $fx_srcs += $fx_g');
124
131
  // glob operands display their expansion; plain operands the text as typed
package/dist/doctor.js CHANGED
@@ -2,7 +2,9 @@ import { existsSync, readFileSync } from 'node:fs';
2
2
  import { nodeEngineRange, supportsNode } from './runtime-support.js';
3
3
  import { homedir } from 'node:os';
4
4
  import { join } from 'node:path';
5
+ import { resolveMcpLaunchTuple, sameMcpLaunchTuple } from './mcp-launch.js';
5
6
  import { resolveQwenLaunchTuple, sameQwenLaunchTuple } from './qwen-launch.js';
7
+ import { kimiConfigPath } from './install.js';
6
8
  import { launcherStatus } from './facade-launch.js';
7
9
  const VALUE_INDENT = ' ';
8
10
  export async function collectDoctorReport(opts = {}) {
@@ -17,6 +19,7 @@ export async function collectDoctorReport(opts = {}) {
17
19
  lines.push(field('codex', detectCodex(home, env)));
18
20
  lines.push(field('opencode', detectOpenCode(home, env)));
19
21
  lines.push(field('qwen', detectQwen(home)));
22
+ lines.push(field('kimi', detectKimi(home, env)));
20
23
  lines.push(field('facade', detectFacade(env)));
21
24
  lines.push('');
22
25
  const mcp = await mcpLines(nodeVersion, opts.loadMcp);
@@ -172,6 +175,38 @@ function detectOpenCode(home, env) {
172
175
  return `fauxnix MCP configured (${path})`;
173
176
  return `found ${path}, fauxnix MCP not listed — add mcp.fauxnix (see README)`;
174
177
  }
178
+ /** Kimi Code (`install --kimi`) — mcp.json under KIMI_CODE_HOME or ~/.kimi-code (#259). */
179
+ function detectKimi(home, env) {
180
+ const path = kimiConfigPath(home, env);
181
+ if (!existsSync(path))
182
+ return 'not detected — see README';
183
+ const text = readText(path);
184
+ if (text === undefined)
185
+ return `found ${path} (unreadable) — see README`;
186
+ let data;
187
+ try {
188
+ data = JSON.parse(stripBom(text));
189
+ }
190
+ catch {
191
+ return `found ${path} (unreadable JSON) — see README`;
192
+ }
193
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
194
+ return `found ${path} (not a JSON object) — see README`;
195
+ }
196
+ const servers = data.mcpServers;
197
+ if (!isServerMap(servers)) {
198
+ return `found ${path}, fauxnix MCP not listed — run: fauxnix install --kimi`;
199
+ }
200
+ const config = servers.fauxnix;
201
+ const expected = resolveMcpLaunchTuple();
202
+ if (expected.ok && sameMcpLaunchTuple(config, expected.value)) {
203
+ return `fauxnix MCP configured with an absolute launcher (${path})`;
204
+ }
205
+ if (config != null || serverMapHasFauxnix(servers)) {
206
+ return `found ${path}, fauxnix MCP launcher does not match this installation — run: fauxnix install --kimi`;
207
+ }
208
+ return `found ${path}, fauxnix MCP not listed — run: fauxnix install --kimi`;
209
+ }
175
210
  function detectQwen(home) {
176
211
  const path = join(home, '.qwen', 'settings.json');
177
212
  if (!existsSync(path))
@@ -29,16 +29,37 @@ export interface BatchExecResult {
29
29
  results: ExecResult[];
30
30
  stopReason: BatchStopReason;
31
31
  }
32
- /** Session persists cwd and env across segments, like a real shell. */
32
+ /**
33
+ * Remove state directories left behind by fauxnix processes that died without
34
+ * cleaning up (SIGKILL, TerminateProcess, power loss). Only directories whose
35
+ * name matches the exact pattern, whose owner PID is gone, and which are older
36
+ * than a minute are touched; symlinks are never followed. Best effort, once
37
+ * per process.
38
+ */
39
+ export declare function sweepStaleStateDirs(root?: string, now?: number): string[];
40
+ /**
41
+ * Synchronously terminate every live session's host and remove its state
42
+ * directory. For process-exit paths, where async dispose cannot run.
43
+ */
44
+ export declare function cleanupSessionStateSync(): void;
45
+ /**
46
+ * For short-lived entrypoints (CLI, bash facade): remove session state on
47
+ * normal exit and on SIGINT/SIGTERM/SIGHUP. After cleaning up, the process
48
+ * exits with the conventional 128+signal status unless some other listener
49
+ * is also registered for that signal (then that listener decides). Idempotent.
50
+ */
51
+ export declare function installSessionExitCleanup(): void;
33
52
  export declare class FauxnixSession {
34
53
  id: string;
35
54
  cwd: string | null;
36
55
  env: Record<string, string>;
37
56
  /** Exit code of the previous segment — powers bash's `$?`. */
38
57
  prevExit: number | null;
58
+ /** Per-session private directory holding every state/spool file (#256). */
59
+ private stateDir;
60
+ private stateDirCreated;
39
61
  private cwdFile;
40
62
  private envFile;
41
- private scriptFile;
42
63
  private hostFile;
43
64
  private host;
44
65
  private lifecycleLock;
@@ -47,6 +68,22 @@ export declare class FauxnixSession {
47
68
  private readonly powerShell;
48
69
  constructor();
49
70
  private bindFiles;
71
+ /** Paths of this session's private state (diagnostics and tests). */
72
+ get statePaths(): {
73
+ dir: string;
74
+ cwd: string;
75
+ env: string;
76
+ host: string;
77
+ };
78
+ /** Lazily create the private state directory (owner-only where POSIX modes apply). */
79
+ private ensureStateDir;
80
+ /**
81
+ * Synchronous, best-effort release for process-exit paths: terminate the
82
+ * host first (on Windows its open spool/checkpoint handles would make the
83
+ * delete fail), then remove the directory with retries. The session stays
84
+ * usable: the next run recreates a directory and a host.
85
+ */
86
+ releaseStateSync(): void;
50
87
  private withLock;
51
88
  private syncFromDisk;
52
89
  private ensureHost;
package/dist/executor.js CHANGED
@@ -1,5 +1,5 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { promises as fs, readFileSync, existsSync, openSync, closeSync, readSync, rmSync, writeSync, } from 'node:fs';
1
+ import { randomBytes, randomUUID } from 'node:crypto';
2
+ import { promises as fs, readFileSync, existsSync, lstatSync, mkdirSync, readdirSync, openSync, closeSync, readSync, rmSync, writeSync, } from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { normalizeLiteralPath, wrapScript } from './translator.js';
@@ -211,15 +211,107 @@ function planRedirects(redirects) {
211
211
  return r;
212
212
  }
213
213
  /** Session persists cwd and env across segments, like a real shell. */
214
+ /** `fauxnix-<owner pid>-<24 hex>`: the per-session private state directory. */
215
+ const STATE_DIR_RE = /^fauxnix-(\d+)-[0-9a-f]{24}$/;
216
+ const STALE_MIN_AGE_MS = 60_000;
217
+ /**
218
+ * Sessions whose private state directory currently exists. That directory
219
+ * holds the cwd and the full environment snapshot (often API tokens), so it
220
+ * is removed on dispose and, best effort, when the process exits (#256).
221
+ */
222
+ const liveSessions = new Set();
223
+ function isProcessAlive(pid) {
224
+ try {
225
+ process.kill(pid, 0);
226
+ return true;
227
+ }
228
+ catch (error) {
229
+ // EPERM: exists but belongs to someone else — treat as alive.
230
+ return error.code !== 'ESRCH';
231
+ }
232
+ }
233
+ let staleSweepDone = false;
234
+ /**
235
+ * Remove state directories left behind by fauxnix processes that died without
236
+ * cleaning up (SIGKILL, TerminateProcess, power loss). Only directories whose
237
+ * name matches the exact pattern, whose owner PID is gone, and which are older
238
+ * than a minute are touched; symlinks are never followed. Best effort, once
239
+ * per process.
240
+ */
241
+ export function sweepStaleStateDirs(root = os.tmpdir(), now = Date.now()) {
242
+ const removed = [];
243
+ let names;
244
+ try {
245
+ names = readdirSync(root);
246
+ }
247
+ catch {
248
+ return removed;
249
+ }
250
+ for (const name of names) {
251
+ const m = STATE_DIR_RE.exec(name);
252
+ if (!m)
253
+ continue;
254
+ const pid = Number(m[1]);
255
+ if (pid === process.pid || isProcessAlive(pid))
256
+ continue;
257
+ const dir = path.join(root, name);
258
+ try {
259
+ const st = lstatSync(dir);
260
+ if (!st.isDirectory() || now - st.mtimeMs < STALE_MIN_AGE_MS)
261
+ continue;
262
+ rmSync(dir, { recursive: true, force: true });
263
+ removed.push(dir);
264
+ }
265
+ catch {
266
+ // not ours, already gone, or still locked: leave it
267
+ }
268
+ }
269
+ return removed;
270
+ }
271
+ /**
272
+ * Synchronously terminate every live session's host and remove its state
273
+ * directory. For process-exit paths, where async dispose cannot run.
274
+ */
275
+ export function cleanupSessionStateSync() {
276
+ for (const session of [...liveSessions])
277
+ session.releaseStateSync();
278
+ }
279
+ let exitCleanupInstalled = false;
280
+ /**
281
+ * For short-lived entrypoints (CLI, bash facade): remove session state on
282
+ * normal exit and on SIGINT/SIGTERM/SIGHUP. After cleaning up, the process
283
+ * exits with the conventional 128+signal status unless some other listener
284
+ * is also registered for that signal (then that listener decides). Idempotent.
285
+ */
286
+ export function installSessionExitCleanup() {
287
+ if (exitCleanupInstalled)
288
+ return;
289
+ exitCleanupInstalled = true;
290
+ process.once('exit', cleanupSessionStateSync);
291
+ const signals = [
292
+ ['SIGINT', 130],
293
+ ['SIGTERM', 143],
294
+ ['SIGHUP', 129],
295
+ ];
296
+ for (const [signal, code] of signals) {
297
+ process.once(signal, () => {
298
+ cleanupSessionStateSync();
299
+ if (process.listenerCount(signal) === 0)
300
+ process.exit(code);
301
+ });
302
+ }
303
+ }
214
304
  export class FauxnixSession {
215
305
  id;
216
306
  cwd = null;
217
307
  env = {};
218
308
  /** Exit code of the previous segment — powers bash's `$?`. */
219
309
  prevExit = null;
310
+ /** Per-session private directory holding every state/spool file (#256). */
311
+ stateDir;
312
+ stateDirCreated = false;
220
313
  cwdFile;
221
314
  envFile;
222
- scriptFile;
223
315
  hostFile;
224
316
  host = null;
225
317
  lifecycleLock = Promise.resolve();
@@ -233,10 +325,53 @@ export class FauxnixSession {
233
325
  }
234
326
  bindFiles(id) {
235
327
  this.id = id;
236
- this.cwdFile = path.join(os.tmpdir(), 'fauxnix-' + id + '-cwd.txt');
237
- this.envFile = path.join(os.tmpdir(), 'fauxnix-' + id + '-env.json');
238
- this.scriptFile = path.join(os.tmpdir(), 'fauxnix-' + id + '-script.ps1');
239
- this.hostFile = path.join(os.tmpdir(), 'fauxnix-' + id + '-host.ps1');
328
+ // `id` is a short display handle; the directory name carries 96 bits of
329
+ // CSPRNG randomness and is created exclusively (mkdir fails if it exists).
330
+ // The owner PID lets a later process sweep directories orphaned by a crash.
331
+ this.stateDir = path.join(os.tmpdir(), 'fauxnix-' + process.pid + '-' + randomBytes(12).toString('hex'));
332
+ this.stateDirCreated = false;
333
+ this.cwdFile = path.join(this.stateDir, 'cwd.txt');
334
+ this.envFile = path.join(this.stateDir, 'env.json');
335
+ this.hostFile = path.join(this.stateDir, 'host.ps1');
336
+ }
337
+ /** Paths of this session's private state (diagnostics and tests). */
338
+ get statePaths() {
339
+ return { dir: this.stateDir, cwd: this.cwdFile, env: this.envFile, host: this.hostFile };
340
+ }
341
+ /** Lazily create the private state directory (owner-only where POSIX modes apply). */
342
+ ensureStateDir() {
343
+ if (this.stateDirCreated)
344
+ return;
345
+ if (!staleSweepDone) {
346
+ staleSweepDone = true;
347
+ sweepStaleStateDirs();
348
+ }
349
+ mkdirSync(this.stateDir, { mode: 0o700 });
350
+ this.stateDirCreated = true;
351
+ liveSessions.add(this);
352
+ }
353
+ /**
354
+ * Synchronous, best-effort release for process-exit paths: terminate the
355
+ * host first (on Windows its open spool/checkpoint handles would make the
356
+ * delete fail), then remove the directory with retries. The session stays
357
+ * usable: the next run recreates a directory and a host.
358
+ */
359
+ releaseStateSync() {
360
+ if (this.host) {
361
+ this.host.killSync();
362
+ this.host = null;
363
+ }
364
+ if (this.stateDirCreated) {
365
+ try {
366
+ rmSync(this.stateDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
367
+ }
368
+ catch {
369
+ // still locked (e.g. by an orphaned native grandchild); the host's own
370
+ // EOF cleanup or the next process's stale sweep will retry
371
+ }
372
+ this.stateDirCreated = false;
373
+ }
374
+ liveSessions.delete(this);
240
375
  }
241
376
  withLock(fn) {
242
377
  const done = this.lifecycleLock.then(fn, fn);
@@ -269,6 +404,7 @@ export class FauxnixSession {
269
404
  }
270
405
  ensureHost() {
271
406
  if (!this.host) {
407
+ this.ensureStateDir();
272
408
  this.host = new PowerShellHost(this.hostFile, () => this.childEnv(), this.powerShell);
273
409
  }
274
410
  return this.host;
@@ -298,12 +434,13 @@ export class FauxnixSession {
298
434
  this.env = {};
299
435
  this.hasEnvSnapshot = false;
300
436
  this.prevExit = null;
301
- await Promise.allSettled([
302
- fs.rm(this.cwdFile, { force: true }),
303
- fs.rm(this.envFile, { force: true }),
304
- fs.rm(this.scriptFile, { force: true }),
305
- fs.rm(this.hostFile, { force: true }),
306
- ]);
437
+ if (this.stateDirCreated) {
438
+ await fs
439
+ .rm(this.stateDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 })
440
+ .catch(() => undefined);
441
+ this.stateDirCreated = false;
442
+ }
443
+ liveSessions.delete(this);
307
444
  this.bindFiles(randomUUID().slice(0, 8));
308
445
  }
309
446
  /** env for the child powershell process. */