Repository navigation
Expand file tree
/
Copy pathtool_filters_containers.test.ts
More file actions
919 lines (829 loc) · 44.2 KB
/
Copy pathtool_filters_containers.test.ts
File metadata and controls
919 lines (829 loc) · 44.2 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
// Tests for the container / kubernetes filter family (Batch F): DockerFilter, DockerComposeFilter, KubectlFilter, KubectlLogsFilter, HelmFilter.
//
// Golden tests ported from the Python TestDockerFilter / TestKubectlFilter test classes, plus additional coverage for DockerComposeFilter, KubectlLogsFilter, and HelmFilter and a dispatch ordering smoke test.
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import {
DockerFilter,
DockerComposeFilter,
KubectlFilter,
KubectlLogsFilter,
HelmFilter,
CONTAINER_FILTERS,
} from '../src/tool_filters/containers.js'
import { selectFilter } from '../src/tool_filters/dispatch.js'
import type { ToolFilter } from '../src/tool_filters/base.js'
// --------------------------------------------------------------------------- Helpers ---------------------------------------------------------------------------
function apply(
filter: ToolFilter,
stdout: string,
stderr: string,
exitCode: number,
argv: string[],
): string {
return filter.apply(stdout, stderr, exitCode, argv).text
}
// --------------------------------------------------------------------------- Dispatch ordering — KubectlLogsFilter must precede KubectlFilter; DockerComposeFilter must precede DockerFilter. ---------------------------------------------------------------------------
describe('CONTAINER_FILTERS dispatch ordering', () => {
it('KubectlLogsFilter wins for kubectl logs', () => {
const f = selectFilter(['kubectl', 'logs', 'my-pod'])
expect(f?.name).toBe('kubectl-logs')
})
it('KubectlFilter wins for kubectl get (not logs)', () => {
const f = selectFilter(['kubectl', 'get', 'pods'])
expect(f?.name).toBe('kubectl')
})
it('KubectlFilter wins for kubectl describe', () => {
const f = selectFilter(['kubectl', 'describe', 'pod', 'my-pod'])
expect(f?.name).toBe('kubectl')
})
it('DockerComposeFilter wins for docker compose up', () => {
const f = selectFilter(['docker', 'compose', 'up'])
expect(f?.name).toBe('docker-compose')
})
it('DockerFilter wins for docker build', () => {
const f = selectFilter(['docker', 'build', '.'])
expect(f?.name).toBe('docker')
})
it('DockerFilter wins for docker push', () => {
const f = selectFilter(['docker', 'push', 'myimage:latest'])
expect(f?.name).toBe('docker')
})
it('HelmFilter wins for helm install', () => {
const f = selectFilter(['helm', 'install', 'my-release', './chart'])
expect(f?.name).toBe('helm')
})
it('CONTAINER_FILTERS array has correct ordering (kubectl-logs before kubectl)', () => {
const names = CONTAINER_FILTERS.map((f) => f.name)
expect(names.indexOf('kubectl-logs')).toBeLessThan(names.indexOf('kubectl'))
})
it('CONTAINER_FILTERS array has correct ordering (docker-compose before docker)', () => {
const names = CONTAINER_FILTERS.map((f) => f.name)
expect(names.indexOf('docker-compose')).toBeLessThan(names.indexOf('docker'))
})
})
// --------------------------------------------------------------------------- DockerFilter — ported from Python TestDockerFilter ---------------------------------------------------------------------------
describe('DockerFilter', () => {
const f = new DockerFilter()
it('matches docker', () => expect(f.matches(['docker', 'build', '.'])).toBe(true))
it('matches buildah', () => expect(f.matches(['buildah', 'bud', '.'])).toBe(true))
it('matches podman', () => expect(f.matches(['podman', 'build', '.'])).toBe(true))
it('does not match kubectl', () => expect(f.matches(['kubectl', 'get', 'pods'])).toBe(false))
// HAND-DERIVED: the split is read off this filter's own drop rules, every one of which targets image transfer or build noise, and checked against the subcommands `docker --help` lists. Claiming the rest was not harmless: dispatch stops at the first match, so a filter with no rule for the output still consumed the command and handed back the input minus one blank line, in place of the generic compressor that folds repeated lines.
it.each([['images'], ['ps'], ['logs'], ['inspect'], ['exec'], ['stats'], ['version']])(
'releases `docker %s`, whose output it has no rule for, to the generic path',
(sub) => expect(f.matches(['docker', sub])).toBe(false),
)
it.each([['build'], ['buildx'], ['pull'], ['push'], ['run'], ['load'], ['create']])(
'still claims `docker %s`, which emits the transfer and build noise it drops',
(sub) => expect(f.matches(['docker', sub])).toBe(true),
)
// FORMAT-DERIVED from `docker --help`: every one of these pulls an image or a plugin, so each emits the `<12-hex>: Pull complete` / `Download complete` lines the filter drops at _DOCKER_PULL_LAYER_RE. The layer IDs are all distinct, so the generic compressor folds none of them -- releasing these would hand the noise straight through.
it.each([
[['docker', 'container', 'create', 'nginx']],
[['docker', 'image', 'pull', 'nginx']],
[['docker', 'plugin', 'install', 'vieux/sshfs']],
[['docker', 'plugin', 'upgrade', 'vieux/sshfs']],
])('claims the management-command spelling %j', (argv) => expect(f.matches(argv)).toBe(true))
it('drops digest and progress lines, keeps step header', () => {
// Ported from Python test_drops_digest_and_progress
const text = [
'#1 [internal] load build context',
'#2 sha256:abc123def456789',
'#3 12.3MB / 50.0MB 0.5s',
'#4 [1/3] FROM alpine',
].join('\n')
const result = apply(f, text, '', 0, ['docker', 'build'])
expect(result).not.toContain('sha256:')
expect(result).not.toContain('12.3MB / 50.0MB')
expect(result).toContain('[1/3] FROM alpine')
})
it('drops BuildKit CACHED lines and emits a count', () => {
// Ported from Python test_drops_buildkit_cached_lines
const text = [
'#1 [internal] load build context',
'#2 CACHED',
'#3 CACHED',
'#4 CACHED',
'#5 [1/2] RUN apt-get install -y curl',
'#6 DONE 2.1s',
].join('\n')
const result = apply(f, text, '', 0, ['docker', 'build'])
const contentLines = result.split('\n').filter((ln) => !ln.startsWith('[token-goat:'))
expect(contentLines.every((ln) => !ln.includes('CACHED'))).toBe(true)
expect(result).toContain('3 CACHED')
})
it('drops push layer noise lines, keeps digest summary', () => {
// Ported from Python test_drops_push_layer_noise
const stderr = [
'The push refers to repository [docker.io/myimage]',
'abc123: Layer already exists',
'def456: Layer already exists',
'ghi789: Mounted from library/ubuntu',
'latest: digest: sha256:abc123 size: 1234',
].join('\n')
const result = apply(f, '', stderr, 0, ['docker', 'push'])
expect(result).not.toContain('Layer already exists')
expect(result).not.toContain('Mounted from')
expect(result).toContain('digest')
})
it('drops docker pull per-layer status lines, keeps Status line', () => {
// Ported from Python test_drops_pull_layer_status_lines
const stderr = [
'latest: Pulling from library/ubuntu',
'a1b2c3d4e5f6: Pull complete',
'b2c3d4e5f6a1: Verifying Checksum',
'c3d4e5f6a1b2: Download complete',
'd4e5f6a1b2c3: Already exists',
'Status: Downloaded newer image for ubuntu:latest',
].join('\n')
const result = apply(f, '', stderr, 0, ['docker', 'pull'])
expect(result).not.toContain('Pull complete')
expect(result).not.toContain('Verifying Checksum')
expect(result).not.toContain('Already exists')
expect(result).toContain('Downloaded newer image')
})
it('keeps ERROR lines in step body', () => {
const text = [
'#5 [2/3] RUN npm install',
'#5 0.342 npm ERR! ERROR something went wrong',
'#5 DONE 1.2s',
].join('\n')
const result = apply(f, text, '', 1, ['docker', 'build'])
expect(result).toContain('ERROR something went wrong')
})
it('emits a note marker when lines are dropped', () => {
const text = [
'#1 sha256:abc123def456789',
'#2 12.3MB / 50.0MB 0.5s',
'#3 CACHED',
].join('\n')
const result = apply(f, text, '', 0, ['docker', 'build'])
expect(result).toContain('[token-goat: dropped')
})
it('collapses legacy (non-BuildKit) "---> <hex>" intermediate-layer lines', () => {
// Classic `DOCKER_BUILDKIT=0 docker build` output prints a bare 12-char-hex intermediate layer hash per step (` ---> a1b2c3d4e5f6`), with no `sha256:` label -- that labeled form is specific to the *different*, already-handled BuildKit `#N ... sha256:...` lines covered by the tests above.
const text = [
'Step 1/4 : FROM node:18',
' ---> aaaaaaaaaaaa',
'Step 2/4 : RUN npm install',
' ---> Using cache',
' ---> bbbbbbbbbbbb',
'Step 3/4 : COPY . .',
' ---> cccccccccccc',
'Step 4/4 : CMD ["node", "index.js"]',
'Removing intermediate container dddddddddddd',
' ---> eeeeeeeeeeee',
'Successfully built ffffffffffff',
].join('\n')
const result = apply(f, text, '', 0, ['docker', 'build'])
expect(result).not.toContain('aaaaaaaaaaaa')
expect(result).not.toContain('bbbbbbbbbbbb')
expect(result).not.toContain('cccccccccccc')
expect(result).not.toContain('eeeeeeeeeeee')
expect(result).toContain('building 4 layers, 1 cached')
expect(result).toContain('Successfully built ffffffffffff')
})
it('keeps the failing step header for a legacy (non-BuildKit) RUN failure whose error text never spells out "error"', () => {
// npm's real-world failure marker is "npm ERR!", not the literal substring "error" -- and the docker-emitted failure line ("returned a non-zero code") doesn't say "error" either. A failing RUN step must still keep its "Step N/M :" header so the agent knows *which* command failed, not just see an orphaned npm ERR! line with no context.
const text = [
'Step 1/4 : FROM node:18',
' ---> aaaaaaaaaaaa',
'Step 2/4 : RUN npm install',
' ---> Running in bbbbbbbbbbbb',
'npm ERR! code E404',
'npm ERR! 404 Not Found - GET https://registry.npmjs.org/nonexistent-package',
"The command '/bin/sh -c npm install' returned a non-zero code: 1",
].join('\n')
const result = apply(f, text, '', 1, ['docker', 'build'])
expect(result).toContain('Step 2/4 : RUN npm install')
expect(result).toContain('npm ERR! code E404')
})
})
// --------------------------------------------------------------------------- DockerComposeFilter ---------------------------------------------------------------------------
describe('DockerComposeFilter', () => {
const f = new DockerComposeFilter()
it('matches docker-compose binary', () =>
expect(f.matches(['docker-compose', 'up'])).toBe(true))
it('matches docker compose subcommand', () =>
expect(f.matches(['docker', 'compose', 'up', '-d'])).toBe(true))
it('does not match plain docker build', () =>
expect(f.matches(['docker', 'build', '.'])).toBe(false))
it('collapses repeated Pulling lines, keeps first', () => {
const text = [
'Pulling db (postgres:15)...',
'Pulling web (nginx:latest)...',
'Pulling cache (redis:7)...',
].join('\n')
const result = apply(f, text, '', 0, ['docker', 'compose', 'up'])
// First Pulling line kept; rest elided
expect(result).toContain('Pulling db')
expect(result).toContain('2 more Pulling lines elided')
expect(result).not.toContain('Pulling web')
expect(result).not.toContain('Pulling cache')
})
it('collapses streaming service logs when >50 lines per service', () => {
const lines: string[] = []
for (let i = 0; i < 60; i++) lines.push(`web | log line ${i}`)
const result = apply(f, lines.join('\n'), '', 0, ['docker', 'compose', 'up'])
expect(result).toContain('lines from web elided')
expect(result).toContain('log line 59')
})
it('passes through short service logs unchanged', () => {
const lines: string[] = []
for (let i = 0; i < 10; i++) lines.push(`web | log line ${i}`)
const result = apply(f, lines.join('\n'), '', 0, ['docker', 'compose', 'up'])
expect(result).not.toContain('elided')
expect(result).toContain('log line 9')
})
it('collapses health-check retries per container', () => {
const lines = [
'Container myapp-db-1 Waiting',
'Container myapp-db-1 Waiting',
'Container myapp-db-1 health: starting',
'Container myapp-db-1 Waiting',
]
const result = apply(f, lines.join('\n'), '', 0, ['docker', 'compose', 'up'])
// First occurrence kept; rest elided with a count
expect(result).toContain('health-check wait lines for myapp-db-1')
})
it('passes through error output when exit code is non-zero', () => {
const stderr = 'Error: Cannot connect to the Docker daemon'
const result = apply(f, '', stderr, 1, ['docker', 'compose', 'up'])
expect(result).toContain('Cannot connect to the Docker daemon')
})
})
// --------------------------------------------------------------------------- KubectlFilter — ported from Python TestKubectlFilter ---------------------------------------------------------------------------
describe('KubectlFilter', () => {
const f = new KubectlFilter()
it('matches kubectl', () => expect(f.matches(['kubectl', 'get', 'pods'])).toBe(true))
it('matches k alias', () => expect(f.matches(['k', 'get', 'pods'])).toBe(true))
it('matches k9s alias', () => expect(f.matches(['k9s', 'get', 'pods'])).toBe(true))
it('matches oc alias', () => expect(f.matches(['oc', 'get', 'pods'])).toBe(true))
it('does not match helm', () => expect(f.matches(['helm', 'list'])).toBe(false))
it('get truncates long table to header + 10 rows', () => {
// Ported from Python test_get_truncates_long_table
const rows = ['NAME READY STATUS RESTARTS AGE']
for (let i = 0; i < 50; i++) rows.push(`pod-${i} 1/1 Running 0 5m`)
const text = rows.join('\n')
const result = apply(f, text, '', 0, ['kubectl', 'get', 'pods'])
expect(result).toContain('NAME READY STATUS')
expect(result).toContain('more rows')
expect(result).toContain('pod-0')
expect(result).toContain('pod-9')
})
// CAPTURE: run against the shipped 2.9.27 binary on 2026-09-23 with a stubbed `kubectl` emitting a real 40-pod list, `kubectl get pods -o json` returned 1445 lines and came back as ten, cut in the middle of an object, under `[token-goat: 1435 more rows; use --selector or -l to narrow]` -- a remedy that does not make JSON parseable. `-o yaml` returned 121 lines and came back as thirteen, cut mid-document. The table branch was being applied to a document because nothing looked at the requested output format.
it('releases a structured -o document whole, in every spelling of the flag, because truncating one leaves nothing the caller can parse', () => {
const doc = ['{', ' "kind": "List",', ' "items": ['].concat(
Array.from({ length: 40 }, (_, i) => ` { "name": "web-${i}", "restartCount": ${i} },`),
[' ]', '}'],
)
const text = doc.join('\n')
for (const argv of [
['kubectl', 'get', 'pods', '-o', 'json'],
['kubectl', 'get', 'pods', '-o', 'yaml'],
['kubectl', 'get', 'pods', '-ojson'], // glued to the short flag
['kubectl', 'get', 'pods', '-o=json'],
['kubectl', 'get', 'pods', '--output=json'],
['kubectl', 'get', 'pods', '-o', "jsonpath={.items[*].metadata.name}"],
['kubectl', 'get', 'pods', '-o', 'go-template={{.items}}'],
]) {
const result = apply(f, text, '', 0, argv)
expect(result, argv.join(' ')).toBe(text)
expect(result, argv.join(' ')).not.toContain('more rows')
// The distinguishing detail: the closing structure survives, so the document is still parseable.
expect(result, argv.join(' ')).toContain('"name": "web-39"')
}
})
// A guard on the fix above rather than on the bug. These three stay line-oriented, so a truncated one is still valid and the marker still discloses the loss -- they are the default table's case, not the document one, and releasing them whole would drop real compression.
it('still truncates the line-oriented output formats', () => {
const rows = ['NAME READY STATUS RESTARTS AGE']
for (let i = 0; i < 50; i++) rows.push(`pod-${i} 1/1 Running 0 5m`)
const text = rows.join('\n')
for (const argv of [
['kubectl', 'get', 'pods', '-o', 'wide'],
['kubectl', 'get', 'pods', '-o', 'name'],
['kubectl', 'get', 'pods', '-o', 'custom-columns=NAME:.metadata.name'],
]) {
expect(apply(f, text, '', 0, argv), argv.join(' ')).toContain('more rows')
}
})
it('get keeps short table unchanged', () => {
// Ported from Python test_get_keeps_short_table
const rows = ['NAME READY STATUS RESTARTS AGE']
for (let i = 0; i < 5; i++) rows.push(`pod-${i} 1/1 Running 0 5m`)
const text = rows.join('\n')
const result = apply(f, text, '', 0, ['kubectl', 'get', 'pods'])
expect(result).not.toContain('more rows')
expect(result).toBe(text)
})
it('get truncates long table when -n namespace precedes the subcommand', () => {
// Global `-n <namespace>` before the subcommand is valid kubectl syntax (`kubectl -n myns get pods`) and must not shift positional routing.
const rows = ['NAME READY STATUS RESTARTS AGE']
for (let i = 0; i < 50; i++) rows.push(`pod-${i} 1/1 Running 0 5m`)
const text = rows.join('\n')
const result = apply(f, text, '', 0, ['kubectl', '-n', 'myns', 'get', 'pods'])
expect(result).toContain('more rows')
expect(result).toContain('pod-0')
expect(result).toContain('pod-9')
})
it('top truncates long table', () => {
// Ported from Python test_top_truncates_long_table
const rows = ['NAME CPU(cores) MEMORY(bytes)']
for (let i = 0; i < 30; i++) rows.push(`pod-${i} 100m 256Mi`)
const result = apply(f, rows.join('\n'), '', 0, ['kubectl', 'top', 'pods'])
expect(result).toContain('more rows')
expect(result).toContain('NAME CPU')
})
it('describe extracts key fields (Name, Namespace, Status)', () => {
// Ported from Python test_describe_extracts_key_fields
const text = [
'Name: my-pod',
'Namespace: default',
'Status: Running',
'State: Running',
'Some other field: value',
'Another field: data',
].join('\n')
const result = apply(f, text, '', 0, ['kubectl', 'describe', 'pod', 'my-pod'])
expect(result).toContain('Name: my-pod')
expect(result).toContain('Namespace: default')
expect(result).toContain('Status: Running')
expect(result).not.toContain('Some other field')
})
// FORMAT-DERIVED: the `State:`/`Last State:`/`Container ID:` labels come from kubectl's own describe printer, `kubernetes/kubectl` `pkg/describe/describe.go` (https://github.com/kubernetes/kubectl/blob/master/pkg/describe/describe.go) -- `describeContainerBasicInfo` writes `Container ID:`/`Image ID:`, and the container-state helper (`describeStatus`, called once for the current state and once more for `LastTerminationState` with the label "Last State") writes `State:` and `Last State:` respectively. No live cluster is available on this machine, so this cannot be a CAPTURE.
it('describe keeps Last State separate from State so a past crash is not reattributed to the current one', () => {
const text = [
'Name: mypod',
'Status: Running',
' Image: nginx:1.21',
' Container ID: docker://abc123',
' State: Running',
' Started: Mon, 01 Jan 2024 00:00:00 +0000',
' Last State: Terminated',
' Reason: Error',
' Exit Code: 1',
' Started: Sun, 31 Dec 2023 23:00:00 +0000',
' Finished: Sun, 31 Dec 2023 23:05:00 +0000',
' Ready: True',
' Restart Count: 7',
].join('\n')
const result = apply(f, text, '', 0, ['kubectl', 'describe', 'pod', 'mypod'])
// must-not-drop: the Last State header itself, so Reason/Exit Code/the second Started/Finished read as history, not current state
expect(result).toContain('Last State: Terminated')
expect(result).toContain('Container ID: docker://abc123')
expect(result).toContain('State: Running')
expect(result).toContain('Reason: Error')
expect(result).toContain('Exit Code: 1')
expect(result).toContain('Finished: Sun, 31 Dec 2023 23:05:00 +0000')
expect(result).toContain('Restart Count: 7')
// the crash record must appear after its own header, not directly under the still-kept `State:` line
const lastStateIdx = result.indexOf('Last State:')
const reasonIdx = result.indexOf('Reason: Error')
expect(lastStateIdx).toBeGreaterThan(-1)
expect(reasonIdx).toBeGreaterThan(lastStateIdx)
})
it('describe preserves Events section, elides older events', () => {
// Ported from Python test_describe_preserves_events
let text = [
'Name: my-pod',
'Namespace: default',
'Events:',
' Type Reason Age From Message',
' ---- ------ --- ---- -------',
].join('\n')
const eventLines = Array.from({ length: 15 }, (_, i) => ` Normal Created ${i}s ... Event ${i}`)
text += '\n' + eventLines.join('\n') + '\n'
const result = apply(f, text, '', 0, ['kubectl', 'describe', 'pod', 'my-pod'])
expect(result).toContain('Events:')
expect(result).toContain('earlier events elided')
// Last 10 events should be present; Event 14 or Event 13 is among them
expect(result).toMatch(/Event 1[34]/)
})
// Regression: `kubectl describe svc` without a name emits one document per resource. The Events section used to swallow every remaining line in the output and then stop, so only the first resource survived, the second resource's body was reprinted as the first one's events, and the elision count counted non-event lines.
it('describe keeps every resource in a multi-document listing', () => {
const svc = (name: string, ip: string, events: string[]): string =>
[
`Name: ${name}`,
'Namespace: prod',
`Labels: app=${name}`,
'Annotations: <none>',
`Selector: app=${name}`,
'Type: ClusterIP',
`IP: ${ip}`,
`IPs: ${ip}`,
'Port: http 80/TCP',
'TargetPort: 8080/TCP',
'Session Affinity: None',
'Internal Traffic Policy: Cluster',
...(events.length > 0 ? ['Events:', ...events] : ['Events: <none>']),
].join('\n')
const text = [
svc('api-gateway', '10.96.0.10', []),
svc('payments', '10.96.0.11', [
' Type Reason Age From Message',
' ---- ------ ---- ---- -------',
' Warning FailedToUpdateEndpoint 4m endpoint-controller no ready backends',
]),
svc('redis-cache', '10.96.0.12', []),
].join('\n\n\n') + '\n'
const result = apply(f, text, '', 0, ['kubectl', 'describe', 'svc', '-n', 'prod'])
// Exact ordered survivor list: all three resources, each with its own Events section, and no bogus elision marker.
expect(result.split('\n')).toEqual([
'Name: api-gateway',
'Namespace: prod',
'Labels: app=api-gateway',
'Annotations: <none>',
'Selector: app=api-gateway',
'Type: ClusterIP',
'IP: 10.96.0.10',
'',
'Events: <none>',
'Name: payments',
'Namespace: prod',
'Labels: app=payments',
'Annotations: <none>',
'Selector: app=payments',
'Type: ClusterIP',
'IP: 10.96.0.11',
'',
'Events:',
' Type Reason Age From Message',
' ---- ------ ---- ---- -------',
' Warning FailedToUpdateEndpoint 4m endpoint-controller no ready backends',
'Name: redis-cache',
'Namespace: prod',
'Labels: app=redis-cache',
'Annotations: <none>',
'Selector: app=redis-cache',
'Type: ClusterIP',
'IP: 10.96.0.12',
'',
'Events: <none>',
])
// Control: the filter still drops the fields it is meant to drop, so this is not a pass-through.
expect(result).not.toContain('TargetPort:')
expect(result).not.toContain('Internal Traffic Policy:')
expect(result.length).toBeLessThan(text.length)
})
// Regression: an events section that ends at a less-indented line must still elide, and its count must cover only that resource's event rows.
it('describe elision count covers only the current resource events', () => {
const events = Array.from({ length: 14 }, (_, i) => ` Normal Pulled ${i}m kubelet Pulled image ${i}`)
const text = [
'Name: pod-a',
'Namespace: default',
'Events:',
...events,
'',
'Name: pod-b',
'Namespace: default',
'Status: Running',
'Events: <none>',
'',
].join('\n')
const result = apply(f, text, '', 0, ['kubectl', 'describe', 'pods'])
expect(result.split('\n')).toEqual([
'Name: pod-a',
'Namespace: default',
'',
'Events:',
' [token-goat: 4 earlier events elided]',
...events.slice(-10),
'Name: pod-b',
'Namespace: default',
'Status: Running',
'',
'Events: <none>',
])
})
it('logs uses head+tail compression for >50 lines', () => {
// Ported from Python test_logs_compresses_large_output
const lines = Array.from({ length: 100 }, (_, i) => `Line ${i}: log message`)
const text = lines.join('\n')
const result = apply(f, text, '', 0, ['kubectl', 'logs', 'my-pod'])
expect(result).toContain('log lines')
expect(result).toContain('Line 0')
expect(result).toContain('Line 99')
})
it('logs keeps short output unchanged', () => {
// Ported from Python test_logs_keeps_short_output
const lines = Array.from({ length: 10 }, (_, i) => `Line ${i}: log message`)
const text = lines.join('\n')
const result = apply(f, text, '', 0, ['kubectl', 'logs', 'my-pod'])
expect(result).not.toContain('elided')
expect(result).toBe(text)
})
it('apply passes through short output', () => {
// Ported from Python test_apply_passes_through
const text = 'pod/my-pod created'
const result = apply(f, text, '', 0, ['kubectl', 'apply', '-f', 'manifest.yaml'])
expect(result).toBe(text)
})
it('delete passes through short output', () => {
// Ported from Python test_delete_passes_through
const text = 'pod/my-pod deleted'
const result = apply(f, text, '', 0, ['kubectl', 'delete', 'pod', 'my-pod'])
expect(result).toBe(text)
})
it('diff truncates large diffs to first 50 lines', () => {
// Ported from Python test_diff_truncates_large_diff
const lines = Array.from({ length: 100 }, (_, i) => `diff line ${i}`)
const result = apply(f, lines.join('\n'), '', 0, ['kubectl', 'diff', '-f', 'manifest.yaml'])
expect(result).toContain('diff lines')
expect(result).toContain('diff line 0')
})
it('error exit preserves stderr combined with stdout', () => {
// Ported from Python test_error_preserves_stderr
const result = apply(f, 'Some output', 'Error: something failed', 1, ['kubectl', 'get', 'pods'])
expect(result).toContain('Error: something failed')
expect(result).toContain('---')
})
})
// --------------------------------------------------------------------------- KubectlLogsFilter ---------------------------------------------------------------------------
describe('KubectlLogsFilter', () => {
const f = new KubectlLogsFilter()
it('matches kubectl logs', () => expect(f.matches(['kubectl', 'logs', 'my-pod'])).toBe(true))
it('matches k alias with logs', () => expect(f.matches(['k', 'logs', 'my-pod'])).toBe(true))
it('does not match kubectl get', () => expect(f.matches(['kubectl', 'get', 'pods'])).toBe(false))
it('does not match kubectl with no subcommand', () => expect(f.matches(['kubectl'])).toBe(false))
it('matches kubectl logs when -n namespace precedes the subcommand', () =>
expect(f.matches(['kubectl', '-n', 'myns', 'logs', 'my-pod'])).toBe(true))
it('passes through short log output unchanged', () => {
const lines = Array.from({ length: 20 }, (_, i) => `2024-01-01T00:00:${String(i).padStart(2,'0')}Z INFO message ${i}`)
const result = apply(f, lines.join('\n'), '', 0, ['kubectl', 'logs', 'my-pod'])
expect(result).not.toContain('elided')
})
it('collapses HTTP access logs when >20 lines (with >50 total to pass the early-exit)', () => {
// KubectlLogsFilter only fires when nonEmpty.length > 50 (faithful to Python). Use 60 access-log lines to exercise _collapseAccessLogs.
const accessLine = (i: number) =>
`10.0.0.1 - - [01/Jan/2024:00:00:${String(i % 60).toString().padStart(2,'0')} +0000] "GET /health HTTP/1.1" 200 5 req=${i}`
const lines = Array.from({ length: 60 }, (_, i) => accessLine(i))
const result = apply(f, lines.join('\n'), '', 0, ['kubectl', 'logs', 'my-pod'])
expect(result).toContain('HTTP access log lines collapsed')
expect(result).toContain('2xx')
})
it('collapses stack trace frames beyond 5 (with >50 total to pass the early-exit)', () => {
// KubectlLogsFilter only fires when nonEmpty.length > 50 (faithful to Python). Pad with unique log lines before the stack trace to exceed the threshold.
const preamble = Array.from({ length: 50 }, (_, i) => `2024-01-01T00:00:00Z INFO log msg ${i}`)
const traceLines = [
'Error: something went wrong',
' at com.example.Foo.bar(Foo.java:42)',
' at com.example.Baz.qux(Baz.java:17)',
' at com.example.Main.run(Main.java:100)',
' at com.example.App.start(App.java:55)',
' at com.example.Server.handle(Server.java:88)',
' at com.example.Router.dispatch(Router.java:33)',
' at com.example.Handler.call(Handler.java:10)',
'Next exception here',
]
const lines = [...preamble, ...traceLines]
// 7 frame lines → keep 5, show "... 2 more frames"
const result = apply(f, lines.join('\n'), '', 0, ['kubectl', 'logs', 'my-pod'])
expect(result).toContain('more frames')
expect(result).toContain('2 more frames')
// First 5 frames kept
expect(result).toContain('Foo.bar')
expect(result).toContain('Server.handle')
// 6th and 7th frames collapsed
expect(result).not.toContain('Router.dispatch')
expect(result).not.toContain('Handler.call')
})
it('collapses Python-style 2-line traceback frames beyond 5, keeping each File line paired with its source line', () => {
// KubectlLogsFilter only fires when nonEmpty.length > 50 (faithful to Python). Pad with unique log lines before the traceback to exceed the threshold.
const preamble = Array.from({ length: 50 }, (_, i) => `2024-01-01T00:00:00Z INFO log msg ${i}`)
const traceLines = [
'Traceback (most recent call last):',
' File "app.py", line 1, in foo1',
' bar()',
' File "app.py", line 2, in foo2',
' bar()',
' File "app.py", line 3, in foo3',
' bar()',
' File "app.py", line 4, in foo4',
' bar()',
' File "app.py", line 5, in foo5',
' bar()',
' File "app.py", line 6, in foo6',
' bar()',
' File "app.py", line 7, in foo7',
' bar()',
'ValueError: boom',
]
const lines = [...preamble, ...traceLines]
// 7 logical frames (2 physical lines each) → keep 5 frames, collapse 2.
const result = apply(f, lines.join('\n'), '', 0, ['kubectl', 'logs', 'my-pod'])
expect(result).toContain('more frames')
expect(result).toContain('2 more frames')
// First 5 frames kept, each File line paired with its own source line.
expect(result).toContain('foo1')
expect(result).toContain('foo5')
// 6th and 7th frames collapsed entirely (both File line and its source line).
expect(result).not.toContain('foo6')
expect(result).not.toContain('foo7')
// The final exception summary line must never be swallowed as a "source line".
expect(result).toContain('ValueError: boom')
})
it('deduplicates repetitive log lines, keeps first 3 (with >50 total to pass the early-exit)', () => {
// KubectlLogsFilter only fires when nonEmpty.length > 50 (faithful to Python). 45 unique lines + 10 repetitions = 55 lines total.
const unique = Array.from({ length: 45 }, (_, i) => `2024-01-01T00:00:00Z INFO unique event ${i}`)
const repeated = Array.from({ length: 10 }, (_, i) =>
`2024-01-01T00:00:${String(i).padStart(2,'0')}Z INFO health check ok`)
const lines = [...unique, ...repeated]
const result = apply(f, lines.join('\n'), '', 0, ['kubectl', 'logs', 'my-pod'])
const keptHealthLines = result.split('\n').filter((l) => l.includes('health check ok'))
expect(keptHealthLines.length).toBe(3)
expect(result).toContain('more similar lines omitted')
})
it('applies head+tail cap when output exceeds 200 lines after all steps', () => {
// Create 250 distinct lines (to avoid dedup collapsing them)
const lines = Array.from({ length: 250 }, (_, i) => `2024-01-01T00:00:00Z INFO unique event ${i}`)
const result = apply(f, lines.join('\n'), '', 0, ['kubectl', 'logs', 'my-pod'])
expect(result).toContain('log lines')
expect(result).toContain('unique event 0')
expect(result).toContain('unique event 249')
})
it('collapses multi-line JSON blobs >5 lines', () => {
const blob = [
'{',
' "message": "request started",',
' "level": "info",',
' "service": "api",',
' "trace": "abc123",',
' "extra": "data"',
'}',
]
const lines = Array.from({ length: 60 }, (_, i) => `2024-01-01T00:00:00Z INFO msg ${i}`)
// Insert a JSON blob
lines.splice(30, 0, ...blob)
const result = apply(f, lines.join('\n'), '', 0, ['kubectl', 'logs', 'my-pod'])
expect(result).toContain('JSON blob')
expect(result).toContain('lines collapsed')
})
})
// --------------------------------------------------------------------------- HelmFilter ---------------------------------------------------------------------------
describe('HelmFilter', () => {
const f = new HelmFilter()
it('matches helm', () => expect(f.matches(['helm', 'install', 'my-release', './chart'])).toBe(true))
it('does not match kubectl', () => expect(f.matches(['kubectl', 'get', 'pods'])).toBe(false))
it('install collapses boilerplate and keeps STATUS line', () => {
const text = [
'NAME: my-release',
'LAST DEPLOYED: Mon Jan 1 00:00:00 2024',
'NAMESPACE: default',
'STATUS: deployed',
'REVISION: 1',
'NOTES:',
'Thank you for installing the chart.',
'To get started, run:',
].join('\n')
const result = apply(f, text, '', 0, ['helm', 'install', 'my-release', './chart'])
expect(result).toContain('STATUS: deployed')
expect(result).toContain('helm release description lines elided')
expect(result).not.toContain('LAST DEPLOYED')
expect(result).not.toContain('Thank you for installing')
})
it('install preserves error signal lines', () => {
const text = [
'NAME: my-release',
'STATUS: failed',
'Error: INSTALLATION FAILED: unable to build kubernetes objects',
].join('\n')
const result = apply(f, text, '', 1, ['helm', 'install', 'my-release', './chart'])
expect(result).toContain('Error: INSTALLATION FAILED')
})
it('list caps at 10 data rows with a count', () => {
const rows = ['NAME\tNAMESPACE\tREVISION\tSTATUS\tCHART']
for (let i = 0; i < 25; i++) rows.push(`release-${i}\tdefault\t1\tdeployed\tmy-chart-1.0.0`)
const result = apply(f, rows.join('\n'), '', 0, ['helm', 'list'])
expect(result).toContain('15 more rows')
expect(result).toContain('use --filter or --namespace to narrow')
expect(result).toContain('release-0')
expect(result).toContain('release-9')
expect(result).not.toContain('release-10')
})
// HAND-DERIVED status values, from helm 3's release.Status constants, which helm list prints verbatim in its STATUS column: deployed, failed, superseded, uninstalling, uninstalled, unknown, pending-install, pending-upgrade, pending-rollback. CAPTURE was impossible: helm is not installed here and this loop may not install it. All lowercase, which is why the shared TABLE_ROW_ANOMALY_RE, whose kubectl and CloudFormation entries are capitalised, saw nothing wrong with any of them.
it('list keeps a failed release that sorts past the row cap', () => {
const rows = ['NAME\tNAMESPACE\tREVISION\tSTATUS\tCHART']
for (let i = 0; i < 25; i++) {
const status = i === 22 ? 'failed' : i === 23 ? 'pending-upgrade' : 'deployed'
rows.push(`release-${i}\tdefault\t1\t${status}\tmy-chart-1.0.0`)
}
const result = apply(f, rows.join('\n'), '', 0, ['helm', 'list'])
// Must-not-drop: the two releases that are not healthy, and the header that names the columns.
expect(result).toContain('release-22\tdefault\t1\tfailed')
expect(result).toContain('release-23\tdefault\t1\tpending-upgrade')
expect(result).toContain('NAME\tNAMESPACE\tREVISION\tSTATUS\tCHART')
expect(result).toContain('2 rows kept for a not-ready status')
})
// The two bare words in the shared anomaly pattern had no boundaries on them, so they matched inside any longer word: a chart or release name merely CONTAINING "failed" or "unknown" pinned a perfectly healthy row, spending the row budget on rows nothing is wrong with and pushing out the ones that are. HAND-DERIVED: the status values are helm 3's own release.Status constants, and the chart names below are ordinary naming, not shapes read off the matcher.
it('list does not treat a healthy row as an anomaly because a name contains the word failed or unknown', () => {
const rows = ['NAME\tNAMESPACE\tREVISION\tSTATUS\tCHART']
for (let i = 0; i < 25; i++) {
const chart = i === 20 ? 'failed-login-handler-1.0.0' : i === 21 ? 'unknown-device-api-2.1.0' : 'my-chart-1.0.0'
const status = i === 22 ? 'failed' : 'deployed'
rows.push(`release-${i}\tdefault\t1\t${status}\t${chart}`)
}
const result = apply(f, rows.join('\n'), '', 0, ['helm', 'list'])
// Survival anchor: the genuinely failed release is still kept, so this cannot pass by the anomaly rule having stopped firing altogether.
expect(result).toContain('release-22\tdefault\t1\tfailed')
expect(result).toContain('1 row kept for a not-ready status')
// Both healthy rows sort past the cap and must not be rescued by their chart names.
expect(result).not.toContain('failed-login-handler')
expect(result).not.toContain('unknown-device-api')
})
it('list keeps short output unchanged', () => {
const rows = ['NAME\tNAMESPACE\tREVISION\tSTATUS\tCHART']
for (let i = 0; i < 5; i++) rows.push(`release-${i}\tdefault\t1\tdeployed\tmy-chart-1.0.0`)
const text = rows.join('\n')
const result = apply(f, text, '', 0, ['helm', 'list'])
expect(result).not.toContain('elided')
})
it('template emits only document separators when >200 lines', () => {
const lines: string[] = []
lines.push('---')
lines.push('# Source: my-chart/templates/deployment.yaml')
for (let i = 0; i < 50; i++) lines.push(` field${i}: value`)
lines.push('---')
lines.push('# Source: my-chart/templates/service.yaml')
for (let i = 0; i < 160; i++) lines.push(` port${i}: 80`)
const result = apply(f, lines.join('\n'), '', 0, ['helm', 'template', './chart'])
expect(result).toContain('document headers only')
expect(result).toContain('---')
})
it('template passes through short output unchanged', () => {
const lines: string[] = []
lines.push('---')
lines.push('# Source: my-chart/templates/deployment.yaml')
for (let i = 0; i < 10; i++) lines.push(` field${i}: value`)
const text = lines.join('\n')
const result = apply(f, text, '', 0, ['helm', 'template', './chart'])
expect(result).not.toContain('document headers only')
})
it('other subcommands pass through', () => {
const text = 'Release "my-release" has been rolled back.'
const result = apply(f, text, '', 0, ['helm', 'rollback', 'my-release'])
expect(result).toBe(text)
})
it('error exit passes stderr through', () => {
const stderr = 'Error: release: not found'
const result = apply(f, '', stderr, 1, ['helm', 'status', 'my-release'])
expect(result).toContain('release: not found')
})
})
// --------------------------------------------------------------------------- Regression: KubectlLogsFilter dedup flush order Verified fail-pre (without the prevKey flush guard) / pass-post. ---------------------------------------------------------------------------
describe('KubectlLogsFilter dedup flush regression', () => {
it('flushes omit marker when switching to a different message mid-stream (>50 lines)', () => {
// Without the prevKey guard, the omit marker for the first message would appear at the END of output rather than after the last repeated line. This regression test proves it appears in the right position (before the next distinct message). Pad to >50 lines so the filter actually engages (faithful to Python).
const filler = Array.from({ length: 44 }, (_, i) => `2024-01-01T00:00:00Z INFO filler ${i}`)
const repeated = Array.from({ length: 5 }, () => '2024-01-01T00:00:00Z INFO repeated message')
const different = ['2024-01-01T00:00:01Z INFO different message']
const lines = [...filler, ...repeated, ...different] // 50 total
// Add one more to exceed 50
lines.push('2024-01-01T00:00:02Z INFO extra line')
const result = apply(new KubectlLogsFilter(), lines.join('\n'), '', 0, ['kubectl', 'logs', 'p'])
const outputLines = result.split('\n').filter(Boolean)
const omitIdx = outputLines.findIndex((l) => l.includes('more similar lines omitted'))
const diffIdx = outputLines.findIndex((l) => l.includes('different message'))
// The omit marker must appear BEFORE the different message
expect(omitIdx).toBeGreaterThanOrEqual(0)
expect(diffIdx).toBeGreaterThanOrEqual(0)
expect(omitIdx).toBeLessThan(diffIdx)
})
})
describe('DockerFilter keeps the failing RUN step diagnostics of a real BuildKit build', () => {
// CAPTURE: docker 29.7.2 (Docker Desktop, BuildKit) `docker build --no-cache --progress=plain` 2>&1 over throwaway Dockerfiles, 2026-10-03; rows in tests/fixtures/PROVENANCE.tsv. Real tools spell the failure 'Error:', 'npm error' and 'error:', never the uppercase 'ERROR' the step-body rule matched on.
const capture = (name: string): string => readFileSync(join(__dirname, 'fixtures/tool_output', name), 'utf8')
const f = new DockerFilter()
const build = ['docker', 'build', '--progress=plain', '.']
it('keeps the node module-not-found line and its require stack', () => {
const text = capture('docker-29.7.2-build-plain-failing-node-module.txt')
const out = apply(f, text, '', 1, build)
for (const line of ["#6 0.206 Error: Cannot find module './server-config.js'", '#6 0.206 Require stack:', '#6 0.206 - /app/[eval]']) {
expect(out).toContain(line)
}
expect(out).toContain('#6 ERROR: process')
})
it('keeps the npm 404 lines of a failing npm install', () => {
const text = capture('docker-29.7.2-build-plain-failing-npm-404.txt')
const out = apply(f, text, '', 1, build)
expect(out).toContain('#6 0.733 npm error code E404')
expect(out).toContain('#6 0.733 npm error 404 Not Found - GET https://registry.npmjs.org/tg-nonexistent-pkg-zzq-98765 - Not found')
})
it('keeps the compiler diagnostic of a failing step and still drops the earlier successful step body', () => {
const text = capture('docker-29.7.2-build-plain-failing-gcc.txt')
const out = apply(f, text, '', 2, build)
expect(out).toContain("#7 0.235 src/main.c:42:7: error: expected ';' before 'return'")
expect(out).toContain('#7 0.235 compiling src/main.c')
expect(out).not.toContain('progress line 30')
expect(out.length).toBeLessThan(text.length)
})
it('still compresses a successful build and drops every step body line', () => {
const text = capture('docker-29.7.2-build-plain-success.txt')
const out = apply(f, text, '', 0, build)
expect(out).not.toContain('progress line 30')
expect(out).not.toContain('#7 0.199 done')
expect(out.length).toBeLessThan(text.length * 0.7)
expect(out).toContain('#7 [4/4] RUN echo done')
})
})