Repository navigation
Expand file tree
/
Copy pathsmoke.mjs
More file actions
3545 lines (3348 loc) · 225 KB
/
Copy pathsmoke.mjs
File metadata and controls
3545 lines (3348 loc) · 225 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import test from 'node:test'
import assert from 'node:assert/strict'
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { tmpdir } from 'node:os'
import { join, resolve as resolvePath, sep } from 'node:path'
import { fileURLToPath } from 'node:url'
import { _internal } from '../src/index.js'
import {
TOOLCHAIN, WINGET_SOURCE, classifyToolState, classifyWingetResult, installArgv,
isActionable, isNoMatchExit, parseExportJson, scanCommands, toolById, upgradeArgv,
} from '../src/toolchain.js'
import { fenceToolRequest, runToolJob } from '../src/tool-runner.js'
/**
* Reduce one src module to an evaluable body for the `new Function` harnesses
* below: imports/exports go, and so does the module's SINGLE top-level await —
* a `new Function` body cannot contain one. v0.31.1 made shell.js and
* src/index.js resolve their schemastery copy asynchronously (issue #12, see
* src/schemastery.js), so the harness supplies that resolution result directly;
* the resolution itself is covered by the schemastery tests further down.
*/
function stripModule(source) {
return source
.replace(/^import .*$/gm, '')
.replace(/^export default /gm, '')
.replace(/^export /gm, '')
.replace(/^.*await loadSchemastery\([^\n]*\).*$/m, (line) => (
line.includes('const schema =') ? 'const schema = { z: z }' : 'Schema = z'))
}
/* Bindings for the shell.js eval harnesses below: those strip every `import`
line, so the shared bash resolver arrives as explicit stubs. The stub keeps
the real contract that matters to the executor — a CONFIGURED path resolves
to itself (never to some other shell), an empty one does not resolve. */
const resolveBashStub = ({ configured }) => configured === ''
? { ok: false, path: '', root: '', gitExe: '', source: '', tried: [], rejected: [], configured: '' }
: { ok: true, path: configured, root: configured.replace(/\/bin\/bash\.exe$/, ''), gitExe: '', source: 'configured', tried: [], rejected: [], configured }
const effectiveBashStub = (own, settings) => (typeof own === 'string' && own.trim() !== '' ? own.trim() : (typeof settings === 'string' ? settings.trim() : ''))
const settingsBashStub = () => ''
const bashReportStub = (resolution) => (resolution.ok ? 'resolved: ' + resolution.path : 'unresolved (stub)')
test('hashTree/classify roundtrip with marker', () => {
const dir = mkdtempSync(join(tmpdir(), 'gitbash-shell-'))
try {
mkdirSync(join(dir, 'skills'))
writeFileSync(join(dir, 'agent.cordis.yml'), 'a')
writeFileSync(join(dir, 'skills', 'SKILL.md'), 's')
const files = _internal.hashTree(dir)
assert.ok(files['agent.cordis.yml'] !== undefined)
assert.ok(files['skills/SKILL.md'] !== undefined)
assert.equal(_internal.classify(dir), 'foreign')
writeFileSync(join(dir, '.plugin-managed.json'), JSON.stringify({ managedBy: 'dsh-gitbash-shell', version: '0.1.0', files }))
assert.equal(_internal.classify(dir), 'unmodified')
writeFileSync(join(dir, 'agent.cordis.yml'), 'user edit')
assert.equal(_internal.classify(dir), 'user-modified')
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
test('inspect registry shim tolerates duplicate registrations', () => {
const providers = new Map()
const reg = {
providers,
register(registration) {
if (this.providers.has(registration.manifest.id)) throw new Error('Host Cordis inspect provider "' + registration.manifest.id + '" is already registered')
this.providers.set(registration.manifest.id, registration)
return () => { this.providers.delete(registration.manifest.id) }
},
}
const first = _internal.installRegisterShim(reg)
assert.equal(first.installed, true)
const dup = reg.register({ manifest: { id: 'Service' } })
reg.register({ manifest: { id: 'Service' } })
assert.equal(providers.size, 1)
assert.equal(typeof dup, 'function')
})
// ── built-in era split (dsh 0.1.2 renamed `code` → `ptc`, no alias) ────────
test('msys path translation helpers', async () => {
const { _internal } = await import('../src/index.js')
const { translateMsysPath, translatePathArguments } = _internal
assert.equal(translateMsysPath('/c/Users/kanna'), 'C:/Users/kanna')
assert.equal(translateMsysPath('/e/project/x'), 'E:/project/x')
assert.equal(translateMsysPath('/c/'), 'C:/')
// non-MSYS shapes pass through unchanged
assert.equal(translateMsysPath('C:/Users'), 'C:/Users')
assert.equal(translateMsysPath('C:\\Users'), 'C:\\Users')
assert.equal(translateMsysPath('AGENTS.md'), 'AGENTS.md')
assert.equal(translateMsysPath('/home/u'), '/home/u')
// argument rewriting: PURE — a NEW object when any path field changes,
// the ORIGINAL reference otherwise; the frozen input is never touched
// (0.10.2: the registry deep-freezes exec.arguments, the wrapper replaces
// the exec.arguments property instead)
const args = { file_path: '/c/a/b.txt', command: 'ls /c/a', workdir: '/e/p', pattern: '*.ts' }
const out = translatePathArguments(args)
assert.notEqual(out, args, 'a changed result must be a new object')
assert.equal(out.file_path, 'C:/a/b.txt')
assert.equal(out.workdir, 'E:/p')
assert.equal(out.command, 'ls /c/a', 'bash command stays MSYS-native')
assert.equal(out.pattern, '*.ts')
assert.equal(args.file_path, '/c/a/b.txt', 'the original (frozen) input is untouched')
assert.deepEqual(translatePathArguments(args), out, 'deterministic translation (value equality; fresh reference each call)')
const none = { command: 'pwd' }
assert.equal(translatePathArguments(none), none, 'unchanged input returns the same reference')
assert.equal(translatePathArguments(null), null)
const empty = {}
assert.equal(translatePathArguments(empty), empty, 'empty object returns the same reference')
const frozen = Object.freeze({ file_path: '/c/x/y.txt' })
const thawed = translatePathArguments(frozen)
assert.equal(thawed.file_path, 'C:/x/y.txt', 'a deep-frozen input still translates into the new object')
})
test('msys virtual mounts, glob split, present nesting, temp echo (v0.17.0)', async () => {
const { _internal } = await import('../src/index.js')
const { translateMsysPath, translatePathArguments, translateGlobArguments, rewriteResultPaths } = _internal
const BS = String.fromCharCode(92)
const NUL = BS + BS + '.' + BS + 'NUL'
const env = { tmpDir: 'C:/Users/u/AppData/Local/Temp', home: 'C:/Users/u', gitRoot: 'C:/Program Files/Git' }
// ~ expands to home exactly like bash ($HOME), ~user stays untouched
assert.equal(translateMsysPath('~', env), 'C:/Users/u')
assert.equal(translateMsysPath('~/.gitconfig', env), 'C:/Users/u/.gitconfig')
assert.equal(translateMsysPath('~other/x', env), '~other/x')
// /tmp is the user TEMP dir (usertemp mount), segment-bounded
assert.equal(translateMsysPath('/tmp', env), env.tmpDir)
assert.equal(translateMsysPath('/tmp/a b.txt', env), env.tmpDir + '/a b.txt')
assert.equal(translateMsysPath('/tmpfoo', env), '/tmpfoo')
assert.equal(translateMsysPath('/tmpx/y', env), '/tmpx/y')
assert.equal(translateMsysPath('/Tmp/x', env), '/Tmp/x', 'mount names are case-sensitive like the msys table')
// /dev/null is the Windows NUL device — never a bare 'NUL' string (which
// libuv would create as a REAL FILE in cwd) and never a recycle bin
assert.equal(translateMsysPath('/dev/null', env), NUL)
// /usr & friends live under the Git root; /bin maps to usr/bin (mount table)
assert.equal(translateMsysPath('/usr', env), 'C:/Program Files/Git/usr')
assert.equal(translateMsysPath('/usr/bin/bash.exe', env), 'C:/Program Files/Git/usr/bin/bash.exe')
assert.equal(translateMsysPath('/bin/sh', env), 'C:/Program Files/Git/usr/bin/sh')
assert.equal(translateMsysPath('/etc/profile', env), 'C:/Program Files/Git/etc/profile')
assert.equal(translateMsysPath('/home/u', env), 'C:/Program Files/Git/home/u', '/home is the GIT mount, matching bash — the shorthand ~ is the user home')
// bare drive roots
assert.equal(translateMsysPath('/c', env), 'C:/')
assert.equal(translateMsysPath('/E', env), 'E:/')
// without an env only drive roots translate (backwards compatibility)
assert.equal(translateMsysPath('/tmp/x'), '/tmp/x')
assert.equal(translateMsysPath('/usr/bin'), '/usr/bin')
assert.equal(translateMsysPath('~/.gitconfig'), '~/.gitconfig')
// a missing gitRoot fact leaves /usr untranslated (defensive no-op)
const noGit = { tmpDir: env.tmpDir, home: env.home }
assert.equal(translateMsysPath('/usr/bin/rg', noGit), '/usr/bin/rg')
// present's nested files[].path rides along, frozen input safe
const pa = translatePathArguments({ files: [{ path: '/c/a/b.txt', description: 'd' }, { path: 'plain.md' }] }, env)
assert.equal(pa.files[0].path, 'C:/a/b.txt')
assert.equal(pa.files[1].path, 'plain.md')
const frozenFiles = Object.freeze({ files: Object.freeze([{ path: '/tmp/t.png' }]) })
assert.equal(translatePathArguments(frozenFiles, env).files[0].path, env.tmpDir + '/t.png')
const plain = translatePathArguments({ command: 'ls /c/a' }, env)
assert.equal(plain.command, 'ls /c/a', 'bash command stays MSYS-native')
// glob: an absolute pattern splits into { path, pattern }; relative stays
const tg = translateGlobArguments
assert.deepEqual(tg({ pattern: '/c/Users/x/*.md' }, env), { pattern: '*.md', path: 'C:/Users/x' })
assert.deepEqual(tg({ pattern: '/c/a/*/b/*.md' }, env), { pattern: '*/b/*.md', path: 'C:/a' })
assert.deepEqual(tg({ pattern: '/tmp/t/*.log' }, env), { pattern: '*.log', path: env.tmpDir + '/t' })
assert.deepEqual(tg({ pattern: '/c/Users/x/readme.md' }, env), { pattern: 'readme.md', path: 'C:/Users/x' }, 'no wildcard: dir + basename')
assert.deepEqual(tg({ pattern: 'C:/Users/x/*.md' }, env), { pattern: '*.md', path: 'C:/Users/x' }, 'Windows-form patterns split too')
assert.deepEqual(tg({ pattern: 'C:' + BS + 'Users' + BS + 'x' + BS + '*.md' }, env), { pattern: '*.md', path: 'C:/Users/x' })
assert.deepEqual(tg({ pattern: '/c/a/*.md', path: '/e/p' }, env), { pattern: '*.md', path: 'C:/a' }, 'an absolute pattern supersedes an existing path')
const rel = { pattern: '*.ts' }
assert.equal(tg(rel, env), rel, 'relative patterns return the same reference')
const bare = { pattern: '/c' }
assert.equal(tg(bare, env), bare, 'a bare drive root is not a pattern split')
// result echo: TEMP paths come back as /tmp (that IS what /tmp means)
const rr = rewriteResultPaths
assert.equal(rr('read', { path: 'C:/Users/u/AppData/Local/Temp/x.txt' }, env).path, '/tmp/x.txt')
assert.equal(rr('read', { path: 'c:/users/u/appdata/local/temp/x' }, env).path, '/tmp/x', 'case-insensitive prefix')
assert.equal(rr('read', { path: 'C:' + BS + 'Users' + BS + 'u' + BS + 'AppData' + BS + 'Local' + BS + 'Temp' + BS + 'y.png' }, env).path, '/tmp/y.png')
assert.equal(rr('read', { path: 'C:/Users/u/x/f.txt' }, env).path, '/c/Users/u/x/f.txt', 'non-TEMP paths keep the drive-root dialect')
const pv = rr('present', { turn: 1, files: [{ path: 'C:/Users/u/AppData/Local/Temp/o.png', description: 'd' }] }, env)
assert.equal(pv.files[0].path, '/tmp/o.png')
assert.equal(rr('present', { turn: 1, files: [{ path: 'C:/x/o.png' }] }).files[0].path, '/c/x/o.png', 'present echoes MSYS without an env too')
assert.equal(rr('read', { path: 'C:/Users/u/AppData/Local/Temp/x.txt' }).path, '/c/Users/u/AppData/Local/Temp/x.txt', 'no env: no temp substitution (backwards compatible)')
})
test('error-content dialect: path diagnostics translated, data never (v0.17.1)', async () => {
const { _internal } = await import('../src/index.js')
const { rewriteErrorContent, rewriteResultPaths, ERROR_CONTENT_TOOLS } = _internal
const BS = String.fromCharCode(92)
// a harness path diagnostic comes back in the MSYS dialect
const ec = rewriteErrorContent([{ type: 'text', text: 'Error: cannot read ' + String.fromCharCode(34) + 'C:' + BS + 'Users' + BS + 'x' + BS + 'f.txt' + String.fromCharCode(34) + ': not found' }])
assert.equal(ec[0].text, 'Error: cannot read ' + String.fromCharCode(34) + '/c/Users/x/f.txt' + String.fromCharCode(34) + ': not found')
// non-drive-letter diagnostics stay verbatim; a NUL-device EINVAL gains
// the v0.18.0 guidance block APPENDED (original text untouched)
const keep = [{ type: 'text', text: 'EINVAL: invalid argument, realpath ' + BS + BS + '.' + BS + 'NUL' }]
const guidedOld = rewriteErrorContent(keep)
assert.equal(guidedOld[0].text, keep[0].text, 'device-path diagnostic text stays verbatim')
assert.equal(guidedOld.length, 2, 'plus the appended NUL guidance block (v0.18.0)')
const urlKeep = [{ type: 'text', text: 'see https://x.dev/a and file://C:/y stay' }]
assert.equal(rewriteErrorContent(urlKeep), urlKeep, 'URLs never match and keep the exact reference')
// bash is NOT on the error-translation list: failed command output is data
assert.equal(ERROR_CONTENT_TOOLS.has('bash'), false)
assert.equal(ERROR_CONTENT_TOOLS.has('read'), true)
// the red line: file CONTENT in successful results is never rewritten
const rd = rewriteResultPaths('read', { path: 'C:' + BS + 'x' + BS + 'f.txt', lines: [{ n: 1, text: 'content mentions C:' + BS + 'Users' + BS + 'kanna inside' }] })
assert.equal(rd.lines[0].text, 'content mentions C:' + BS + 'Users' + BS + 'kanna inside')
})
test('leading variable shorthands + NUL guidance (v0.18.0)', async () => {
const { _internal } = await import('../src/index.js')
const { translateMsysPath, rewriteErrorContent } = _internal
const D = String.fromCharCode(36)
const env = { tmpDir: 'C:/Users/u/AppData/Local/Temp', home: 'C:/Users/u', gitRoot: 'C:/Program Files/Git' }
assert.equal(translateMsysPath(D + 'HOME/.gitconfig', env), 'C:/Users/u/.gitconfig')
assert.equal(translateMsysPath(D + '{TMPDIR}/x', env), env.tmpDir + '/x')
assert.equal(translateMsysPath(D + 'TMP', env), env.tmpDir)
assert.equal(translateMsysPath(D + 'OTHER/x', env), D + 'OTHER/x', 'unknown variables stay verbatim')
assert.equal(translateMsysPath(D + 'HOMEX', env), D + 'HOMEX', 'NAMEX false positives stay verbatim')
assert.equal(translateMsysPath(D + 'HOMEfoo/x', env), D + 'HOMEfoo/x')
assert.equal(translateMsysPath(D + 'HOME/x', undefined), D + 'HOME/x', 'no env: no expansion (backwards compatible)')
const BS = String.fromCharCode(92)
const guided = rewriteErrorContent([{ type: 'text', text: 'EINVAL: invalid argument, realpath ' + BS + BS + '.' + BS + BS + 'NUL' }])
assert.equal(guided.length, 2, 'a NUL-device error gains one guidance block')
assert.match(guided[1].text, /^hint: \/dev\/null is the NUL device/)
assert.equal(guided[0].text.includes('EINVAL'), true, 'the original diagnostic stays verbatim')
const plain = rewriteErrorContent([{ type: 'text', text: 'Error: cannot read X: not found' }])
assert.equal(plain.length, 1, 'ordinary errors gain no guidance')
})
test('glob patterns may open with a variable shorthand (v0.18.1)', async () => {
const { _internal } = await import('../src/index.js')
const D = String.fromCharCode(36)
const env = { tmpDir: 'C:/Users/u/AppData/Local/Temp', home: 'C:/Users/u', gitRoot: 'C:/Program Files/Git' }
const tg = _internal.translateGlobArguments
assert.deepEqual(tg({ pattern: D + 'HOME/sandbox/*.md' }, env), { pattern: '*.md', path: 'C:/Users/u/sandbox' })
assert.deepEqual(tg({ pattern: D + '{TMPDIR}/t/*.log' }, env), { pattern: '*.log', path: env.tmpDir + '/t' })
const rel = { pattern: '*.ts' }
assert.equal(tg(rel, env), rel, 'relative patterns still return the same reference')
})
test('client half is a ModuleLoader bundle with baseline requires only', () => {
const text = readFileSync(new URL('../src/client.js', import.meta.url), 'utf8')
assert.match(text, /window\.__ModuleLoader__\.load\(/)
assert.match(text, /return module\.exports/, 'factory must return its exports (0.10.1 guard: without it the module materializes undefined and the loader rejects the plugin)')
assert.match(text, /slots\.inject\("plugins\.bundle\.config", function \(\) \{[\s\S]*return slots\.register\(/, 'two-stage slot registration: slots.inject(hole, cb) whose body calls slots.register — direct options/component args never register (0.10.3 lesson)')
assert.match(text, /id: "dsh-gitbash-shell"/)
const requires = [...text.matchAll(/require\("([^"]+)"\)/g)].map((m) => m[1])
const baseline = new Set(['react', '@deepseek-ai/dsh-client-ui-primitives'])
for (const specifier of requires) {
assert.ok(baseline.has(specifier), 'non-baseline require: ' + specifier)
}
assert.ok(requires.length > 0)
assert.doesNotMatch(text, /(^|\n)\s*import\s/)
assert.doesNotMatch(text, /(^|\n)\s*export\s/)
assert.doesNotMatch(text, /=> </, 'JSX arrow syntax is forbidden')
new Function(text)
})
test('every shipped dictionary carries the same key set as zh', () => {
// A locale block is preceded by a /* locale: <tag> */ marker, so the blocks
// can be sliced without parsing the file. Equality matters because a key
// missing from a third language falls back to English at lookup time — a
// silent half-translated card, which is exactly what this catches.
const text = readFileSync(new URL('../src/client.js', import.meta.url), 'utf8')
const keysOf = (segment) => [...segment.matchAll(/^\s*"([^"]+)":\s*"/gm)].map((match) => match[1]).sort()
const zhKeys = keysOf(text.slice(text.indexOf('var zh = {'), text.indexOf('var en = {')))
assert.ok(zhKeys.length >= 9, 'the zh dictionary looks truncated: ' + zhKeys.length)
assert.deepEqual(
keysOf(text.slice(text.indexOf('var en = {'), text.indexOf('var LOCALES = {'))),
zhKeys,
'en must stay key-aligned with zh',
)
const table = text.slice(text.indexOf('var LOCALES = {'), text.indexOf('// ── locale resolution'))
const parts = table.split('/* locale: ')
assert.ok(parts.length - 1 >= 19, 'expected at least nineteen third-language dictionaries, saw ' + (parts.length - 1))
const shipped = new Set()
for (let index = 1; index < parts.length; index += 1) {
const tag = parts[index].slice(0, parts[index].indexOf(' */'))
shipped.add(tag)
assert.deepEqual(keysOf(parts[index]), zhKeys, 'dictionary ' + tag + ' does not match the zh key set')
}
for (const tag of ['ar', 'de', 'fr', 'hi', 'id', 'it', 'ja', 'ko', 'nl', 'pl', 'pt', 'ru', 'sv', 'th', 'tr', 'vi', 'zh-hk', 'zh-mo', 'zh-tw']) {
assert.ok(shipped.has(tag), 'missing shipped locale: ' + tag)
}
})
test('client dictionaries resolve live, never from a captured table', () => {
const text = readFileSync(new URL('../src/client.js', import.meta.url), 'utf8')
assert.match(text, /function dictionaryFor\(active\)/, 'locale tags must resolve through dictionaryFor')
assert.match(text, /function translatorOf\(ctx\)/, 'the live lookup must exist')
assert.match(text, /var t = translatorOf\(ctx\)/, 'the card copy must come from the live lookup')
assert.match(text, /locale\.subscribe\(/, 'the card must repaint on a live language switch')
assert.match(text, /ctx\.locale\.register\(NS, Object\.assign\(\{ zh: zh, en: en \}, LOCALES\)\)/, 'every shipped dictionary must ride ctx.locale.register')
assert.doesNotMatch(text, /var \w+ = dictionaryFor\(/, 'the dictionary must not be captured once at activation')
// Drive the real bundle: apply() against a fake cordis ctx, then render the
// registered card once per active locale. A switch must change the strings on
// the SAME registration (no re-apply), which is what "live" means here.
const react = {
createElement: (type, props, ...children) => ({
type,
props: props === null || props === undefined ? {} : props,
children: children.filter((child) => child !== null && child !== undefined && child !== false),
}),
useState: (initial) => [typeof initial === 'function' ? initial() : initial, () => {}],
useEffect: (effect) => effect(),
Component: class Component { constructor(props) { this.props = props; this.state = {} } },
}
let bundle = null
const navigatorStub = { language: 'en-US' }
new Function('window', 'navigator', text)({ __ModuleLoader__: { load: (value) => { bundle = value } } }, navigatorStub)
assert.equal(bundle.id, 'dsh-gitbash-shell')
const dictionaries = new Map()
const subscribers = []
const locale = {
register: (ns, dicts) => { dictionaries.set(ns, dicts); return () => {} },
getSnapshot: () => ({ active: activeLocale }),
subscribe: (fn) => { subscribers.push(fn); return () => {} },
}
let activeLocale = 'en'
let registration = null
const scope = { getSnapshot: () => ({ status: 'ready', value: { posixPaths: true } }), set: async () => {} }
const ctx = {
get: (name) => (name === 'locale' ? locale : undefined),
// the settings face: a ConfigForm per live profile entry (the only era now)
inject: (names, cb) => { if (names.includes('configForms')) cb({ configForms: { get: () => scope } }) },
slots: {
inject: (hole, callback) => { callback() },
register: (options, component) => { registration = { options, component }; return () => {} },
},
locale,
effect: (body) => body(),
}
bundle.factory((specifier) => (specifier === 'react' ? react : {})).apply(ctx)
const shipped = dictionaries.get('gitbashShell')
assert.equal(Object.keys(shipped).length, 21, 'zh + en + 19 third languages must ride the registry')
assert.equal(shipped.ja['title'], 'Git Bash パス方言')
const render = () => {
const props = Object.assign({}, registration.options.inject())
const wrapper = registration.component(props) // CardWithLocale -> LocaleLive element
const live = wrapper.type(wrapper.props) // LocaleLive render (subscribes on mount)
const card = live.children[0]
const strings = []
const walk = (node) => {
if (typeof node === 'string') { strings.push(node); return }
if (node === null || typeof node !== 'object') return
for (const child of node.children || []) walk(child)
}
walk(card.type(card.props))
return strings
}
activeLocale = 'ja'
assert.ok(render().includes('Git Bash パス方言'), 'ja must answer from its own dictionary')
activeLocale = 'de'
assert.ok(render().includes('Git-Bash-Pfaddialekt'), 'a switch must repaint without re-applying the plugin')
activeLocale = 'zh-Hant-TW'
assert.ok(render().includes('Git Bash 路徑方言'), 'a bare zh-Hant-* tag falls back to the HK copy')
activeLocale = 'pt-BR'
assert.ok(render().includes('Dialeto de caminhos do Git Bash'), 'a regional tag resolves through its primary subtag')
activeLocale = ''
navigatorStub.language = 'fr'
assert.ok(render().includes('Dialecte de chemins Git Bash'), 'an empty preference falls back to the browser language')
activeLocale = ''
navigatorStub.language = 'xx-YY'
assert.ok(render().includes('Git Bash path dialect'), 'an unsupported language shows English, never a raw key')
assert.ok(subscribers.length >= 1 && subscribers.every((fn) => typeof fn === 'function'), 'the card subscribes to the locale service for the repaint')
})
test('client settings seat: the live configForms seat only — the legacy seat is gone', () => {
const text = readFileSync(new URL('../src/client.js', import.meta.url), 'utf8')
// v0.32.1: the dsh <= 0.1.6-alpha.1 "Settings → Plugins" seat is deleted —
// no supported host dispatches it any more (the namespace registration that
// paired with it is gone from the host half too).
assert.doesNotMatch(text, /settings\.plugin\.item/, 'the legacy seat must stay deleted')
assert.doesNotMatch(text, /settingsScope/, 'the removed settingsScope service must not be injected')
assert.match(text, /slots\.inject\("plugins\.bundle\.config"/)
assert.match(text, /key: "dsh-gitbash-shell"/, 'the Plugins-page seat is keyed by the PACKAGE name')
assert.match(text, /props\.view === "page"/, 'the page view drops the collapsible shell')
})
test('sidebar adoption is switchable, default on, and never clobbers manual picks', async () => {
const text = readFileSync(new URL('../src/index.js', import.meta.url), 'utf8')
assert.match(text, /adoptSidebar: Schema\.boolean\(\)\.default\(true\)\.volatile\(\)/)
assert.match(text, /adoptSidebar: \(\) => dialect\(\)\.adoptSidebar !== false/, 'host reads the switch through the live Config reader')
// OFF enters the owned restore path; that path writes ONLY while the
// current value is still ours. A startup same-value is not our takeover.
const start = text.indexOf('function adoptSidebarShell(')
const body = text.slice(start, text.indexOf('\n// ── plugin', start))
assert.match(body, /if \(!desired\) \{ await restore\(\); return true \}/)
assert.match(body, /const restore = async \(\) => \{\s*if \(!adopted\) return[\s\S]*const now = readShell\(\)[\s\S]*if \(now === bashPath\) \{\s*await ctx\.get\('settings'\)\.update\(SIDEBAR_NS, \{ terminalShell: previous \}\)/)
assert.match(body, /if \(adopted \|\| current === bashPath\) return true\s*previous = current[\s\S]*await ctx\.get\('settings'\)\.update\(SIDEBAR_NS, \{ terminalShell: bashPath \}\)\s*adopted = true/)
})
test('host gates the path dialect behind the posixPaths setting', async () => {
const text = readFileSync(new URL('../src/index.js', import.meta.url), 'utf8')
assert.match(text, /posixPaths: Schema\.boolean\(\)\.default\(true\)\.volatile\(\)/)
// The wrapper and the directive closure read the live Config refs,
// re-reading them per dispatch/assembly.
assert.match(text, /const dialect = liveSettings\.dialect\(\)/, 'wrapper must read the gate per dispatch')
assert.match(text, /liveSettings\.dialect\(\)/, 'directive closure must read the live dialect')
// v0.27.0: the same live dialect object also carries the delegated-agent gate
assert.match(text, /dialect\.posixPaths && dialectApplies\(dialect, exec && exec\.agent\)/,
'the dispatch face asks the per-agent gate with THIS execution\'s agent')
})
test('shellEnv fact DSH_PATH_DIALECT rides the official registry, gated live', () => {
const text = readFileSync(new URL('../src/index.js', import.meta.url), 'utf8')
const pathText = readFileSync(new URL('../src/path-dialect.js', import.meta.url), 'utf8')
// registered through the official dsh-shell-env registry at service-ready
// timing — never by mutating the process environment
assert.match(text, /ctx\.inject\(\['shellEnv'\], \(envCtx\) => \{/)
assert.match(text, /shellEnv\.register\(\{/)
assert.match(text, /DSH_PATH_DIALECT/)
// The resolver reads the live switch per execution: flipping the setting
// empties the variable with no re-registration.
assert.match(text, /resolve\(execution\) \{/, 'the resolver receives the execution')
assert.match(text, /dialectApplies\(dialect, execution && execution\.agent\)/,
'the DSH_PATH_DIALECT fact is withheld from a delegated agent the user excluded')
// REGRESSION GUARD (v0.21.0 → v0.21.1): the registry accepts DSH_* facts
// ONLY. A contributor declaring any other key throws, and the whole
// contribution — DSH_PATH_DIALECT included — is lost. Non-DSH parity facts
// belong to the executor's env layer (src/shell.js).
const declared = /variables: \{([^}]*)\}/.exec(text)
assert.ok(declared !== null, 'the contributor must declare its variables')
// Literal keys must be DSH_*; computed keys are allowed only for constants
// whose own literal value is asserted to start with DSH_.
for (const key of declared[1].matchAll(/'([A-Za-z0-9_]+)':/g)) {
assert.match(key[1], /^DSH_/, 'a non-DSH key in the shell-env registry kills the contribution: ' + key[1])
}
for (const key of declared[1].matchAll(/\[([A-Za-z0-9_]+)\]/g)) {
assert.equal(key[1], 'PATH_DIALECT_KEY', 'unexpected computed key in the shell-env declaration: ' + key[1])
}
assert.match(pathText, /export const PATH_DIALECT_KEY = 'DSH_/, 'the computed key must itself be a DSH_* fact')
assert.doesNotMatch(declared[1], /GIT_CONFIG/, 'git config belongs to the executor, not to the DSH_* registry')
assert.match(text, /envCtx\.effect\(\(\) => unregister/)
})
test('windowsToMsys rewrites Windows absolute paths to MSYS roots', async () => {
const { _internal } = await import('../src/index.js')
const w = _internal.windowsToMsys
const BS = String.fromCharCode(92) // backslash, assembled to survive any transport layer
const q = (s) => String.fromCharCode(34) + s + String.fromCharCode(34)
assert.equal(w('C:' + BS + 'Users' + BS + 'kanna' + BS + 'sandbox'), '/c/Users/kanna/sandbox')
assert.equal(w('C:/Users/kanna'), '/c/Users/kanna')
assert.equal(w('E:' + BS + 'project' + BS + 'deepseek-harness'), '/e/project/deepseek-harness')
assert.equal(w('see C:' + BS + 'Users' + BS + 'kanna, then stop'), 'see /c/Users/kanna, then stop')
assert.equal(w('root (C:' + BS + 'Users' + BS + 'kanna) done'), 'root (/c/Users/kanna) done')
assert.equal(w(q('C:' + BS + 'Program Files' + BS + 'Git')), q('/c/Program Files/Git'))
assert.equal(w('https://x.dev/a and file://C:/x stay'), 'https://x.dev/a and file://C:/x stay')
assert.equal(w('/c/already/posix stays'), '/c/already/posix stays')
assert.equal(w('no paths here'), 'no paths here')
})
test('windowsToMsys keeps JSON-escaped Windows paths canonical (v0.26.0, issue #10)', async () => {
const { _internal } = await import('../src/index.js')
const w = _internal.windowsToMsys
const BS = String.fromCharCode(92)
const q = (s) => String.fromCharCode(34) + s + String.fromCharCode(34)
// The host renders its sandbox:policy context line as
// `JSON.stringify(policy.workspaceRoot)`, so the prompt carries DOUBLED
// backslashes. A single-separator atom at the drive colon left the second
// one in `rest` and the separator normalization promoted it to a leading
// slash: "/d//dsh/工作".
const escaped = 'D:' + BS + BS + 'dsh' + BS + BS + '工作'
assert.equal(w(escaped), '/d/dsh/工作', 'the bare branch costs no extra slash')
assert.equal(w(q(escaped)), q('/d/dsh/工作'), 'the quoted branch agrees')
assert.equal(w(JSON.stringify('D:' + BS + 'dsh' + BS + '工作')), q('/d/dsh/工作'), 'exactly what JSON.stringify emits')
assert.equal(w('D://dsh//工作'), '/d/dsh/工作', 'doubled forward slashes collapse the same way')
assert.equal(w('C:' + BS + BS + 'Program Files' + BS + BS + 'Git'), '/c/Program Files/Git', 'spaced directories keep working')
// Negative faces: single separators (the pre-existing behavior) stay
// byte-for-byte, and non-drive forms are never touched.
assert.equal(w('C:' + BS + 'Users' + BS + 'kanna'), '/c/Users/kanna')
assert.equal(w(q('C:' + BS + 'Program Files' + BS + 'Git')), q('/c/Program Files/Git'))
assert.equal(w('https://x.dev/a and file://C:/x stay'), 'https://x.dev/a and file://C:/x stay')
assert.equal(w(BS + BS + 'server' + BS + 'share stays'), BS + BS + 'server' + BS + 'share stays', 'a UNC path has no drive colon')
assert.equal(w('/d/dsh/工作 stays'), '/d/dsh/工作 stays')
})
test('rewriteResultPaths rewrites result metadata, never content', async () => {
const { _internal } = await import('../src/index.js')
const rr = _internal.rewriteResultPaths
const BS = String.fromCharCode(92)
const rd = rr('read', { path: 'C:' + BS + 'Users' + BS + 'x' + BS + 'f.txt', lines: [{ n: 1, text: 'see C:' + BS + 'Users in content' }] })
assert.equal(rd.path, '/c/Users/x/f.txt')
assert.equal(rd.lines[0].text, 'see C:' + BS + 'Users in content', 'file content is never rewritten')
const gl = rr('glob', { paths: ['a' + BS + 'b' + BS + 'c.txt'] })
assert.equal(gl.paths[0], 'a/b/c.txt')
const gp = rr('grep', { matches: [{ path: 'd' + BS + 's' + BS + 'i.js', line: 'C:' + BS + 'x stays' }] })
assert.equal(gp.matches[0].path, 'd/s/i.js')
assert.equal(gp.matches[0].line, 'C:' + BS + 'x stays', 'match text is never rewritten')
const bash = { stdout: 'x' }
assert.equal(rr('bash', bash), bash, 'non-path tools pass through untouched')
const already = { path: '/c/already.txt' }
assert.equal(rr('read', already), already, 'an unchanged value returns the same reference')
// v0.23.0 (issue #3): a whole-value field goes through pathEcho, so the
// prose rewriter can no longer leave a spaced directory half-translated
const spaced = rr('read', { path: 'C:' + BS + 'Users' + BS + 'u' + BS + 'my dir' + BS + 'f.txt' })
assert.equal(spaced.path, '/c/Users/u/my dir/f.txt')
assert.equal(rr('grep', { matches: [{ path: 'my dir' + BS + 's.js', line: 'x' }] }).matches[0].path, 'my dir/s.js')
})
test('manifest and package versions stay in sync', () => {
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
const manifest = JSON.parse(readFileSync(new URL('../dsh.plugin.json', import.meta.url), 'utf8'))
assert.equal(pkg.version, manifest.version, 'dsh.plugin.json must track package.json (npm version script)')
assert.equal(manifest.id, 'dsh-external/dsh-gitbash-shell')
assert.equal(pkg.scripts.version !== undefined, true, 'the version script must exist so bumps stay in sync')
})
test('executor: Config fields ride schemastery volatile (dsh >=0.2.2-rc.1)', () => {
// The base class declares its six inherited limits with .volatile() and
// reads every one through .get(); our Config must match that contract or the
// first shell call throws `config.timeoutMs.get is not a function` (#6).
const baseLiveFields = ['cwd', 'timeoutMs', 'maxTimeoutMs', 'maxOutputBytes', 'maxSpillBytes', 'graceMs']
const src = readFileSync('src/shell.js', 'utf8')
const stripped = stripModule(src)
const scope = new Function('DEFAULT_GIT_BASH', 'SandboxBashExecutor', 'z', 'process',
stripped + '\nreturn { gitBashShellConfig, Config, GitBashSandboxExecutor }')
class FakeBase {}
/** A recording schemastery stand-in: volatile() is always available. */
const recorder = () => {
const nodes = []
const node = () => {
const n = { marked: 0 }
n.default = () => n
n.volatile = () => { n.marked += 1; return n }
nodes.push(n)
return n
}
const z = { string: node, number: node, array: node, object: (fields) => fields }
return { z, nodes }
}
const rec = recorder()
const liveFields = scope('C:/Program Files/Git/bin/bash.exe', FakeBase, rec.z, process).gitBashShellConfig(rec.z)
assert.deepEqual(Object.keys(liveFields).sort(), [...baseLiveFields, 'bashPath'].sort(),
'the executor Config must declare exactly the inherited fields plus bashPath')
for (const key of baseLiveFields) {
assert.equal(liveFields[key].marked, 1, key + ' must be marked volatile exactly once (issue #6)')
}
assert.equal(liveFields.bashPath.marked, 0, 'bashPath is our own knob and must stay a plain value')
// The shipping Config comes from the host-aware resolver.
assert.match(src, /await loadSchemastery\(\)/)
assert.match(src, /export const Config = schema\.z \? gitBashShellConfig\(schema\.z\) : undefined/)
assert.doesNotMatch(src, /^import .*'@deepseek-ai\/schemastery'/m, 'no static peer import may kill the whole row')
})
test('executor: Windows restricted and unresolved policies fail before any argv route', async () => {
const src = readFileSync('src/shell.js', 'utf8')
const stripped = stripModule(src)
const scope = new Function('DEFAULT_GIT_BASH', 'resolveGitBashCached', 'effectiveConfiguredBashPath', 'settingsBashPath', 'bashResolutionReport', 'SandboxBashExecutor', 'z', 'process', stripped + '\nreturn { GitBashSandboxExecutor }')
const EMPTY = { exitCode: 0, signal: null, stdout: {}, stderr: {} }
class FakeBase {
async execute(spec) { this.calls.push(['super.execute', spec]); return { via: 'super.execute', result: async () => EMPTY } }
async executeArgv(spec, argv) { this.calls.push(['executeArgv', argv, spec]); return { started: true, result: async () => EMPTY } }
}
const chain = new Proxy(function () {}, { get: () => chain, apply: () => chain })
const make = (platform) => {
const mod = scope('C:/Program Files/Git/bin/bash.exe', resolveBashStub, effectiveBashStub, settingsBashStub, bashReportStub, FakeBase, chain, { platform })
const ex = Object.create(mod.GitBashSandboxExecutor.prototype)
ex.config = { bashPath: 'X:/git/bin/bash.exe' }
ex.calls = []
return ex
}
const refusal = error => error.code === 'SANDBOX_UNAVAILABLE' && /not started/.test(error.message)
for (const mode of ['read-only', 'workspace-write', undefined, 'invalid-mode']) {
const spec = { command: 'echo hi', ...(mode === undefined ? {} : { sandboxPolicy: { mode } }) }
const ex = make('win32')
ex.requireBashPath = () => { throw new Error('refused calls must not even resolve argv') }
await assert.rejects(() => ex.execute(spec), refusal)
assert.throws(() => ex.gitBashRoute(spec), refusal)
assert.deepEqual(ex.calls, [], 'no inherited, fallback or explicit argv execution')
}
const exFull = make('win32')
const full = { command: 'echo hi', sandboxPolicy: { mode: 'danger-full-access' } }
const handle = await exFull.execute(full)
assert.deepEqual(exFull.calls[0][1], ['X:/git/bin/bash.exe', '-c', 'echo hi'])
assert.deepEqual((await handle.result()).sandbox, { mode: 'danger-full-access', denied: false })
const legacy = make('win32')
legacy.experimentalEnabled = () => false
for (const mode of ['read-only', 'workspace-write']) {
const spec = { command: 'echo hi', sandboxPolicy: { mode } }
const facts = { mode, denied: false, enforcement: 'unconfined' }
const unconfined = await legacy.execute(spec)
assert.deepEqual((await unconfined.result()).sandbox, facts)
assert.equal(legacy.calls.at(-1)[0], 'executeArgv', 'the opt-out uses the explicit Git Bash argv')
}
await legacy.execute({ command: 'echo hi' })
assert.equal(legacy.calls.at(-1)[0], 'super.execute', 'unresolved opt-out keeps host delegation')
legacy.experimentalEnabled = () => true
await assert.rejects(() => legacy.execute({ command: 'echo hi', sandboxPolicy: { mode: 'read-only' } }), refusal)
const linux = make('linux')
await linux.execute({ command: 'echo hi', sandboxPolicy: { mode: 'read-only' } })
const linuxUnresolved = make('linux')
await linuxUnresolved.execute({ command: 'echo hi' })
assert.deepEqual(linux.calls.map(call => call[0]), ['super.execute'])
assert.deepEqual(linuxUnresolved.calls.map(call => call[0]), ['super.execute'])
})
test('executor: dsh >=0.2.2-rc.1 execute() keeps both Git Bash substitutions', async () => {
// dsh >=0.2.2-rc.1 has no `run`/`start`: the runtime
// calls `execute(spec): Promise<ShellExecution>` and background work is an
// `onExpiry: 'none'` execution. Without an `execute` override the shipped
// full-access branch spawns the bare `bash` name and a Windows confined call
// goes back through the restricted-token runner MSYS2 cannot start under
// (issue #1) — i.e. the plugin's whole reason to exist would be inert even
// after the Config fix.
const src = readFileSync('src/shell.js', 'utf8')
const stripped = stripModule(src)
const scope = new Function('DEFAULT_GIT_BASH', 'resolveGitBashCached', 'effectiveConfiguredBashPath', 'settingsBashPath', 'bashResolutionReport', 'SandboxBashExecutor', 'z', 'process', stripped + '\nreturn { GitBashSandboxExecutor }')
const RESULT = { exitCode: 0, signal: null, timedOut: false, aborted: false, timeoutMs: 1000, stdout: { text: 'hi', truncated: false }, stderr: { text: '', truncated: false } }
const chain = new Proxy(function () {}, { get: () => chain, apply: () => chain })
/** The dsh >=0.2.2-rc.1 executor surface: execute/executeArgv, no run/start. */
class NewBase {
async execute(spec) { this.calls.push(['super.execute', spec]); return { via: 'super.execute', result: async () => RESULT } }
async executeArgv(spec, argv, onStarted) {
this.calls.push(['executeArgv', argv, spec])
const ex = { status: 'running', result: async () => RESULT }
if (onStarted !== undefined) onStarted(ex)
return ex
}
}
const build = (Base, platform) => {
const mod = scope('C:/Program Files/Git/bin/bash.exe', resolveBashStub, effectiveBashStub, settingsBashStub, bashReportStub, Base, chain, { platform })
const ex = Object.create(mod.GitBashSandboxExecutor.prototype)
ex.config = { bashPath: 'X:/git/bin/bash.exe' }
ex.calls = []
return ex
}
const GIT_BASH_ARGV = ['X:/git/bin/bash.exe', '-c', 'echo hi']
const full = { command: 'echo hi', sandboxPolicy: { mode: 'danger-full-access' } }
const confined = { command: 'echo hi', sandboxPolicy: { mode: 'workspace-write' } }
const kindOf = (ex, kind) => ex.calls.filter((c) => c[0] === kind)
const logs = []
const origLog = console.log
console.log = (...a) => logs.push(a.join(' '))
try {
// Full access on Windows: our argv, labelled like the parent's branch.
const fullEx = build(NewBase, 'win32')
const fullHandle = await fullEx.execute(full)
assert.equal(kindOf(fullEx, 'super.execute').length, 0, 'full access must not reach the bare-bash branch')
const fullArgs = kindOf(fullEx, 'executeArgv')
assert.equal(fullArgs.length, 1)
assert.deepEqual(fullArgs[0][1], GIT_BASH_ARGV, 'the Git Bash argv replaces the shipped bare `bash`')
assert.deepEqual((await fullHandle.result()).sandbox, { mode: 'danger-full-access', denied: false })
// Windows restricted and missing policies are unavailable, not a licence
// to route through the unconfined helper or another interpreter.
for (const mode of ['read-only', 'workspace-write', undefined]) {
const refused = build(NewBase, 'win32')
refused.ctx = { sandbox: { confine: () => { throw new Error('unexpected confine') } } }
await assert.rejects(() => refused.execute({ ...confined, sandboxPolicy: mode === undefined ? undefined : { mode } }),
error => error.code === 'SANDBOX_UNAVAILABLE' && /not started/.test(error.message))
assert.deepEqual(refused.calls, [], 'no base execute, argv helper or sandbox launch')
}
assert.equal(logs.length, 0, 'no announcement of a route that was not allowed to run')
// Non-Windows confined: inherit the parent unchanged (its confine path
// already runs Git Bash through the subclass override).
const linuxEx = build(NewBase, 'linux')
const linuxHandle = await linuxEx.execute(confined)
assert.equal(kindOf(linuxEx, 'executeArgv').length, 0, 'the confined Linux path stays with the parent')
assert.equal(kindOf(linuxEx, 'super.execute').length, 1)
assert.equal(linuxHandle.via, 'super.execute')
// The parity env is still merged into the spec the spawn sees.
const parityEx = build(NewBase, 'win32')
parityEx.ctx = { get: () => ({ describe: () => [{ ns: 'gitbash-shell', value: { posixPaths: true } }] }) }
await parityEx.execute(full)
assert.equal(kindOf(parityEx, 'executeArgv')[0][2].dshEnv.GIT_CONFIG_VALUE_0, 'input')
// The result projection is memoized in place, like the parent's.
const memoEx = build(NewBase, 'win32')
const memoHandle = await memoEx.execute(full)
assert.equal(memoHandle.result(), memoHandle.result(), 'one decorated promise per handle')
} finally {
console.log = origLog
}
})
test('live settings readers use describe()/update() only (issue #6 follow-up)', async () => {
// The settings service exposes describe()/update() and NO get(ns)
// (packages/settings/settings/src/index.ts). A reader that still called
// get(ns) silently degraded — the executor's Linux-parity env
// (GIT_CONFIG_* autocrlf=input) and the better-sidebar terminal adoption
// both stopped happening with no error.
const src = readFileSync('src/shell.js', 'utf8')
const stripped = stripModule(src)
const scope = new Function('DEFAULT_GIT_BASH', 'resolveGitBashCached', 'effectiveConfiguredBashPath', 'settingsBashPath', 'bashResolutionReport', 'SandboxBashExecutor', 'z', 'process', stripped + '\nreturn { GitBashSandboxExecutor }')
const chain = new Proxy(function () {}, { get: () => chain, apply: () => chain })
const build = (settings) => {
const ex = Object.create(scope('C:/Program Files/Git/bin/bash.exe', resolveBashStub, effectiveBashStub, settingsBashStub, bashReportStub, chain, chain, { platform: 'win32' }).GitBashSandboxExecutor.prototype)
ex.config = { bashPath: 'X:/git/bin/bash.exe' }
ex.ctx = settings === undefined ? {} : { get: (name) => (name === 'settings' ? settings : undefined) }
return ex
}
const spec = () => ({ command: 'echo hi' })
const gitConfig = (result) => result.dshEnv === undefined ? undefined : result.dshEnv.GIT_CONFIG_VALUE_0
// The values live in the row Config's projected form.
const rowSettings = build({ describe: () => [{ ns: 'locale', value: {} }, { ns: 'gitbash-shell', value: { posixPaths: true, gitAutocrlf: true } }], update: async () => {} })
assert.equal(gitConfig(rowSettings.withParityEnv(spec())), 'input', 'the describe() read must find the row form')
// Switch off, namespace missing, service missing: the spec is returned as-is.
const off = build({ describe: () => [{ ns: 'gitbash-shell', value: { posixPaths: true, gitAutocrlf: false } }] })
assert.equal(off.withParityEnv(spec()).dshEnv, undefined, 'gitAutocrlf:false disables the parity env')
assert.equal(build({ describe: () => [] }).withParityEnv(spec()).dshEnv, undefined)
assert.equal(build(undefined).withParityEnv(spec()).dshEnv, undefined)
// A describe() that throws must degrade, not break the spawn.
assert.equal(build({ describe: () => { throw new Error('boom') } }).withParityEnv(spec()).dshEnv, undefined)
// The better-sidebar adoption read goes through describe() as well.
const { _internal } = await import('../src/index.js')
const adopt = async (settings) => {
const updates = []
const ctx = {
get: (name) => (name === 'settings' ? { ...settings, update: async (ns, patch) => { updates.push([ns, patch]) } } : undefined),
effect: (fn) => { fn(); return () => {} },
}
_internal.adoptSidebarShell(ctx, 'X:/git/bin/bash.exe', () => true)
await new Promise((resolve) => setTimeout(resolve, 0))
return updates
}
const adopted = await adopt({ describe: () => [{ ns: 'better-sidebar', value: { terminalShell: '' } }] })
assert.deepEqual(adopted, [['better-sidebar', { terminalShell: 'X:/git/bin/bash.exe' }]],
'the adoption must still find the sidebar row through describe()')
// Already adopted: nothing to write.
const settled = await adopt({ describe: () => [{ ns: 'better-sidebar', value: { terminalShell: 'X:/git/bin/bash.exe' } }] })
assert.deepEqual(settled, [], 'an already-adopted sidebar is left alone')
// better-sidebar 0.32 removed terminalShell from the row schema (issue #47).
// The host must probe the schema and stop, not write into a field the loader
// will reject on every boot.
const retired = await adopt({ describe: () => [{ ns: 'better-sidebar', schema: { dict: {} }, value: { terminalShell: '' } }] })
assert.deepEqual(retired, [], 'a row without the terminalShell schema field is not written')
})
test('the bash init script rides BASH_ENV (issue #37, v0.45.0)', () => {
const host = readFileSync(new URL('../src/index.js', import.meta.url), 'utf8')
const shell = readFileSync(new URL('../src/shell.js', import.meta.url), 'utf8')
const client = readFileSync(new URL('../src/client.js', import.meta.url), 'utf8')
// The row Config exposes the setting: live, default '' = never set.
assert.match(host, /initScript: Schema\.string\(\)\.default\(''\)\.volatile\(\)/)
// The hook is bash's own BASH_ENV, never a login shell: `-l` would cd $HOME,
// reorder PATH and mix profile output into stdout (the issue #37 answer).
assert.match(shell, /BASH_ENV: configured/)
assert.doesNotMatch(shell, /'(?:-l|-lc|--login)'/, 'no login-shell argv anywhere')
// The single execution entry point merges it.
assert.equal((shell.match(/withInitScript\(this\.withParityEnv\(spec\)\)/g) || []).length, 1,
'execute must merge the init script')
const stripped = stripModule(shell)
const scope = new Function('DEFAULT_GIT_BASH', 'resolveGitBashCached', 'effectiveConfiguredBashPath', 'settingsBashPath', 'bashResolutionReport', 'SandboxBashExecutor', 'z', 'process', 'homedir', 'join',
stripped + '\nreturn { GitBashSandboxExecutor, expandHomePath }')
const chain = new Proxy(function () {}, { get: () => chain, apply: () => chain })
const mod = scope('C:/Program Files/Git/bin/bash.exe', resolveBashStub, effectiveBashStub, settingsBashStub, bashReportStub, chain, chain, { platform: 'win32' }, () => '/home/kanna', (...parts) => parts.join('/'))
const build = (settings) => {
const ex = Object.create(mod.GitBashSandboxExecutor.prototype)
ex.config = { bashPath: 'X:/git/bin/bash.exe' }
ex.ctx = settings === undefined ? {} : { get: (name) => (name === 'settings' ? settings : undefined) }
return ex
}
const row = (value) => ({ describe: () => [{ ns: 'gitbash-shell', value }] })
const spec = () => ({ command: 'echo hi' })
// Unset = byte-identical spec: this setting cannot change existing behavior.
assert.equal(build(row({})).withInitScript(spec()).dshEnv, undefined)
assert.equal(build(row({ initScript: '' })).withInitScript(spec()).dshEnv, undefined)
assert.equal(build(undefined).withInitScript(spec()).dshEnv, undefined)
// Set: exported as BASH_ENV on the trusted env layer.
assert.equal(build(row({ initScript: 'C:/Users/kanna/.dsh/bash-env.sh' })).withInitScript(spec()).dshEnv.BASH_ENV,
'C:/Users/kanna/.dsh/bash-env.sh')
// ~ expands against the home directory; pasted quotes are trimmed.
assert.equal(mod.expandHomePath('~/.dsh/bash-env.sh'), '/home/kanna/.dsh/bash-env.sh')
assert.equal(mod.expandHomePath('"C:/Users/kanna/env.sh"'), 'C:/Users/kanna/env.sh')
assert.equal(build(row({ initScript: '~/env.sh' })).withInitScript(spec()).dshEnv.BASH_ENV, '/home/kanna/env.sh')
// It composes with the Linux-parity env instead of replacing it.
const both = build(row({ posixPaths: true, gitAutocrlf: true, initScript: 'C:/env.sh' }))
const merged = both.withInitScript(both.withParityEnv(spec())).dshEnv
assert.equal(merged.BASH_ENV, 'C:/env.sh')
assert.equal(merged.GIT_CONFIG_VALUE_0, 'input')
// A describe() that throws degrades to "unset" — the command still runs.
assert.equal(build({ describe: () => { throw new Error('boom') } }).withInitScript(spec()).dshEnv, undefined)
// The settings card renders the field and writes the row key.
assert.match(client, /t\("init\.label"\)/)
assert.match(client, /writeField\("initScript", initDraft\.trim\(\)\)/)
})
test('run_code program literals ride the same MSYS mount table (v0.20.0)', async () => {
const { _internal } = await import('../src/index.js')
const { rewriteCodePaths, scanCodeLiterals } = _internal
const env = { tmpDir: 'C:/Temp', home: 'C:/Users/kanna', gitRoot: 'C:/Program Files/Git' }
// What the model writes stays what it means: the literal becomes the path a
// native Node process can actually open.
assert.equal(rewriteCodePaths("fs.readFileSync('/c/Users/kanna/x.txt')", env), "fs.readFileSync('C:/Users/kanna/x.txt')")
assert.equal(rewriteCodePaths('const p = "/tmp/a.txt"', env), 'const p = "C:/Temp/a.txt"')
assert.equal(rewriteCodePaths('x = `/c/Users/a/b`', env), 'x = `C:/Users/a/b`')
assert.equal(rewriteCodePaths("const u = '/usr/bin/env'", env), "const u = 'C:/Program Files/Git/usr/bin/env'")
assert.equal(rewriteCodePaths("const h = '~/notes.md'", env), "const h = 'C:/Users/kanna/notes.md'")
// The NUL device lands as SOURCE text: it must cook back to the device path.
const devSource = rewriteCodePaths("const dev = '/dev/null'", env)
const devLiteral = devSource.slice(devSource.indexOf("'"), devSource.lastIndexOf("'") + 1)
assert.equal(eval(devLiteral), '\\\\' + '.' + '\\' + 'NUL', 'escaped for the literal it is written into')
// Anything that is not a path literal is left exactly as written.
const untouched = [
"// comment '/c/Users/meh'",
"/* block '/c/Users/meh' */",
"const url = 'http://x/c/y'",
"const dollar = '$HOME/c/x'",
"const win = 'C:/Users/kanna/ok'",
"const rel = 'src/foo/bar'",
'const tpl = `/c/${name}/x`',
"const esc = '/c/Users/a\\\\nb'",
"const quoted = \"see '/c/Users/kanna/inside'\"",
]
for (const code of untouched) assert.equal(rewriteCodePaths(code, env), code, 'must stay verbatim: ' + code)
// A program the scanner cannot walk is left WHOLE: never half-rewritten.
const broken = "const a = '/c/Users/kanna/ok'\nconst b = '/c/Users/unterminated"
assert.equal(scanCodeLiterals(broken), null)
assert.equal(rewriteCodePaths(broken, env), broken)
// Quotes inside a regex literal, and a division, must not desync the scan.
assert.equal(rewriteCodePaths("const re = /['\"]/ ; const s = '/c/Users/kanna/y'", env), "const re = /['\"]/ ; const s = 'C:/Users/kanna/y'")
assert.equal(rewriteCodePaths('const d = a / b; const s = "/c/Users/kanna/w"', env), 'const d = a / b; const s = "C:/Users/kanna/w"')
// Drive roots are the base layer (no env needed); mounts need real facts and
// are never invented.
assert.equal(rewriteCodePaths("x = '/e/project/x'", null), "x = 'E:/project/x'")
assert.equal(rewriteCodePaths("x = '/tmp/x'", null), "x = '/tmp/x'")
})
test('the run_code literal rewrite has its own switch (codePaths)', async () => {
const text = readFileSync(new URL('../src/index.js', import.meta.url), 'utf8')
const pathText = readFileSync(new URL('../src/path-dialect.js', import.meta.url), 'utf8')
assert.match(text, /codePaths: Schema\.boolean\(\)\.default\(true\)\.volatile\(\)/)
assert.match(pathText, /exec\.name === 'run_code' && dialect\.codePaths/)
assert.match(pathText, /rewriteCodePaths\(translated\.code, env\)/)
// v0.20.1: the run_code sentence is NOT in the base directive — it rides the
// same context entry only for assemblies whose tool list carries run_code, so
// every other mode (standard/cordis sessions, run_code disabled) stays quiet.
const base = /const POSIX_DIRECTIVE_TEXT = '([^']*)'/.exec(pathText)
assert.ok(base !== null, 'directive text is gone')
assert.doesNotMatch(base[1], /run_code/, 'the base directive must not talk about run_code')
const strict = /const POSIX_DIRECTIVE_TEXT_STRICT = '([^']*)'/.exec(pathText)
assert.ok(strict !== null, 'strict directive text is gone')
assert.doesNotMatch(strict[1], /run_code/, 'the strict directive must not talk about run_code either')
assert.match(pathText, /const RUN_CODE_DIRECTIVE_TEXT = '/, 'the conditional run_code sentence is gone')
assert.match(text, /runCodeHintFor\(offeredTools, dialect\.codePaths === true, programLanguageFor/, 'the assembly hook must gate on the tool list and live codePaths state')
// The event does not carry tools — read the step's admitted toolSet back
// from the tools service, so conditional tools are judged exactly as
// execution judges them.
assert.match(text, /registry\.definitions\(scope, assembleContext\?\.toolSet\)/, 'the offered tools must come from the step-admitted set')
})
test('the run_code sentence is injected only where the tool exists (v0.20.1)', async () => {
const { runCodeHintFor } = await import('../src/index.js')
assert.equal(runCodeHintFor(undefined), '', 'no tool list → nothing to say')
assert.equal(runCodeHintFor([]), '')
assert.equal(runCodeHintFor([{ name: 'bash' }, { name: 'read' }, { name: 'present' }]), '', 'a mode without run_code stays quiet')
const hint = runCodeHintFor([{ name: 'bash' }, { name: 'run_code' }], true, 'typescript')
assert.match(hint, /run_code program/, 'a mode WITH run_code gets the sentence')
assert.match(hint, /translated/, 'and it says what the layer does')
assert.equal(runCodeHintFor([{ name: 'run_code' }, { name: 'run_code' }], true, 'typescript'), hint, 'idempotent, one sentence')
})
test('run_code gets TEMP/TMP only — never a fake HOME or PATH (v0.21.0)', async () => {
const { programPrelude } = await import('../src/index.js')
assert.equal(programPrelude(null), '', 'no temp fact → no prelude at all')
assert.equal(programPrelude({}), '')
const prelude = programPrelude({ tmpDir: 'C:/Users/kanna/AppData/Local/Temp' })
assert.match(prelude, /e\.TEMP="C:\/Users\/kanna\/AppData\/Local\/Temp"/, 'TEMP is seeded with the real temp dir')
assert.match(prelude, /e\.TMP=e\.TEMP/)
assert.doesNotMatch(prelude, /HOME|PATH|USERPROFILE/, 'HOME/PATH stay untouched: seeding them would diverge from macOS')
assert.ok(prelude.endsWith('\n'), 'the prelude is exactly one line')
assert.equal(prelude.split('\n').length, 2, 'one line plus the terminator')
})
test('the model git gets Linux line endings from the executor (v0.21.1)', () => {
const host = readFileSync(new URL('../src/index.js', import.meta.url), 'utf8')
const shell = readFileSync(new URL('../src/shell.js', import.meta.url), 'utf8')
assert.match(host, /gitAutocrlf: Schema\.boolean\(\)\.default\(true\)\.volatile\(\)/)
// the injection lives where the child env is actually built
assert.match(shell, /withParityEnv\(spec\)/)
assert.match(shell, /GIT_CONFIG_COUNT: '2'/)
assert.match(shell, /GIT_CONFIG_KEY_0: 'core\.autocrlf'/)
assert.match(shell, /GIT_CONFIG_VALUE_0: 'input'/, 'input (not false): a CRLF worktree must read as CLEAN, not as whole-file churn')
assert.match(shell, /GIT_CONFIG_KEY_1: 'core\.eol'/)
assert.match(shell, /GIT_CONFIG_VALUE_1: 'lf'/)
assert.match(shell, /value\.gitAutocrlf === false/, 'the switch must be able to turn it off')
assert.match(shell, /dshEnv/, 'the facts ride the trusted dshEnv layer')
// and nothing anywhere writes the user's global git config
assert.doesNotMatch(shell, /GIT_CONFIG_VALUE_0: 'false'/, 'false showed every line of a CRLF worktree as modified (v0.22.0 evidence)')
assert.doesNotMatch(host, /'--global'/)
assert.doesNotMatch(shell, /'--global'/)
})
test('a failing run_code program reports paths in the MSYS dialect (v0.21.0)', async () => {
const text = readFileSync(new URL('../src/index.js', import.meta.url), 'utf8')
assert.match(text, /if \(exec\.name === 'run_code'\) \{/, 'run_code must ride the error-dialect branch')
assert.match(text, /rewriteErrorContent\(result\.content, \{ nulHint: false, env \}\)/, 'paths only — the /dev/null hint is for file tools')
const { rewriteErrorContent } = await import('../src/index.js')
const err = rewriteErrorContent([{ type: 'text', text: "ENOENT: no such file or directory, open 'C:\\Users\\kanna\\x.txt'" }], { nulHint: false })
assert.match(err[0].text, /\/c\/Users\/kanna\/x\.txt/, 'the Windows path comes back as an MSYS path')
assert.match(err[0].text, /ENOENT: no such file or directory/, 'the diagnostic itself stays verbatim')
assert.equal(err.length, 1, 'no guidance block is appended for a program error')
})
test('a failure speaks one dialect on BOTH faces (v0.22.0)', async () => {
const { _internal } = await import('../src/index.js')
const { rewriteErrorMessage, rewriteFailureMessage, rewriteErrorContent, msysEcho } = _internal
const BS = String.fromCharCode(92)
const Q = String.fromCharCode(34)
const env = { tmpDir: 'C:/Users/u/AppData/Local/Temp', home: 'C:/Users/u', gitRoot: 'C:/Program Files/Git' }
const raw = 'cannot read ' + Q + 'C:' + BS + 'Users' + BS + 'u' + BS + 'x.txt' + Q + ': not found'
const posix = 'cannot read ' + Q + '/c/Users/u/x.txt' + Q + ': not found'
// the message face: drive paths become MSYS, every diagnostic byte stays
assert.equal(rewriteErrorMessage(raw), posix)
assert.equal(rewriteErrorMessage(raw, { env }), posix)
// and the /tmp mount echoes exactly like a successful result does
const tmpMsg = 'ENOENT: no such file or directory, open ' + Q + env.tmpDir + '/x.txt' + Q
assert.equal(rewriteErrorMessage(tmpMsg, { env }), 'ENOENT: no such file or directory, open ' + Q + '/tmp/x.txt' + Q)
assert.equal(rewriteErrorMessage(tmpMsg), 'ENOENT: no such file or directory, open ' + Q + '/c/Users/u/AppData/Local/Temp/x.txt' + Q, 'no mount facts: the drive root still translates, the mount does not')
assert.equal(rewriteErrorMessage('boom: no such file'), 'boom: no such file', 'nothing to translate → the same value')
assert.equal(rewriteErrorMessage(''), '')
assert.equal(rewriteErrorMessage(undefined), undefined)
assert.equal(msysEcho(null), null, 'non-strings pass straight through')
// the result owns the message: patched in place, identity preserved
const result = { isError: true, error: { message: raw, info: { name: 'FsError', code: 'FS_NOT_FOUND' } } }
assert.equal(rewriteFailureMessage(result, env), true)
assert.equal(result.error.message, posix)
assert.equal(result.error.info.code, 'FS_NOT_FOUND', 'the structured identity survives — this is why it is not a block decision')
assert.equal(rewriteFailureMessage(result, env), false, 'idempotent: nothing left to rewrite')
// someone else frozen result must not throw
const frozen = Object.freeze({ isError: true, error: Object.freeze({ message: raw }) })
assert.equal(rewriteFailureMessage(frozen, env), false)
assert.equal(frozen.error.message, raw, 'a frozen error keeps the host form; the content face still carries the dialect')
assert.equal(rewriteFailureMessage(undefined, env), false)
assert.equal(rewriteFailureMessage({ isError: true }, env), false)
// both faces come out of ONE helper, so they cannot disagree
const blocks = rewriteErrorContent([{ type: 'text', text: raw }], { env })
assert.equal(blocks[0].text, posix)
})
test('the post-execute branch patches both faces, and never forges a block (v0.22.0)', () => {
const text = readFileSync(new URL('../src/index.js', import.meta.url), 'utf8')
assert.match(text, /rewriteFailureMessage\(result, env\)/, 'the message face rides the same branch as the content face')
assert.equal((text.match(/\n\s+rewriteFailureMessage\(result, env\)/g) ?? []).length, 2, 'run_code AND the file tools')
assert.match(text, /rewriteErrorContent\(result\.content, \{ nulHint: false, env \}\)/, 'run_code still gets paths only')
assert.doesNotMatch(text, /kind: 'block'/, 'a block decision rebuilds the error as a bare message and drops its identity')
})
test('glob patterns may open with a tilde (v0.22.0)', async () => {
const { _internal } = await import('../src/index.js')
const env = { tmpDir: 'C:/Users/u/AppData/Local/Temp', home: 'C:/Users/u', gitRoot: 'C:/Program Files/Git' }
const tg = _internal.translateGlobArguments
assert.deepEqual(tg({ pattern: '~/sandbox/*.md' }, env), { pattern: '*.md', path: 'C:/Users/u/sandbox' })
assert.deepEqual(tg({ pattern: '~' }, env), { pattern: 'u', path: 'C:/Users' }, 'bare ~ is the home directory itself')
const named = { pattern: '~other/x/*.md' }
assert.equal(tg(named, env), named, '~user has no fact behind it → untouched, same reference')
const noEnv = { pattern: '~/x/*.md' }
assert.equal(tg(noEnv, undefined), noEnv, 'no mount facts → no expansion')
const rel = { pattern: 'sub/*.md' }
assert.equal(tg(rel, env), rel, 'relative patterns still return the same reference')
})
test('a whole-value path never goes through the prose rewriter (v0.23.0, issue #3)', async () => {
const { _internal } = await import('../src/index.js')
const BS = String.fromCharCode(92)
const SL = String.fromCharCode(47)
const d = _internal.driveToMsys
const p = _internal.pathEcho
assert.equal(d('C:' + BS + 'my dir' + BS + 'f.txt'), SL + 'c/my dir/f.txt', 'a spaced directory no longer leaks a backslash')
assert.equal(d('C:/my dir/f.txt'), SL + 'c/my dir/f.txt')
assert.equal(d('my dir' + BS + 'f.txt'), 'my dir/f.txt', 'relative values only normalize')
assert.equal(d(SL + 'c/already/posix'), SL + 'c/already/posix', 'an MSYS path passes through')
assert.equal(d('C:relative'), 'C:relative', 'a drive-relative path is not a root')
assert.equal(d(''), '')
assert.equal(d(undefined), undefined)
assert.equal(p('C:' + BS + 'Users' + BS + 'u' + BS + 'Temp dir' + BS + 'x', { tmpDir: 'C:/Users/u/Temp dir' }), SL + 'tmp/x', 'the /tmp mount survives a spaced TEMP root')
const rr = _internal.rewriteResultPaths
assert.equal(rr('read', { path: 'C:' + BS + 'Users' + BS + 'u' + BS + 'my dir' + BS + 'f.txt' }).path, SL + 'c/Users/u/my dir/f.txt')
assert.equal(rr('glob', { paths: ['C:' + BS + 'a b' + BS + 'c.txt'] }).paths[0], SL + 'c/a b/c.txt')
})
test('prose rewriting crosses a space only into a path token (v0.23.0)', async () => {
const { _internal } = await import('../src/index.js')
const BS = String.fromCharCode(92)
const w = _internal.windowsToMsys
assert.equal(w('C:' + BS + 'Program Files' + BS + 'Git' + BS + 'bin' + BS + 'bash.exe'), '/c/Program Files/Git/bin/bash.exe', 'a spaced program-files path comes back whole')
assert.equal(w('see C:' + BS + 'Users' + BS + 'kanna for details'), 'see /c/Users/kanna for details', 'prose after a path is not swallowed')
assert.equal(w('https://x.dev/a and file://C:/x stay'), 'https://x.dev/a and file://C:/x stay')
assert.equal(w('no paths here'), 'no paths here')
})