-
Notifications
You must be signed in to change notification settings - Fork 448
Expand file tree
/
Copy pathsafe_output_handler_manager.test.cjs
More file actions
1666 lines (1345 loc) · 63.7 KB
/
Copy pathsafe_output_handler_manager.test.cjs
File metadata and controls
1666 lines (1345 loc) · 63.7 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
// @ts-check
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import fs from "fs";
import os from "os";
import path from "path";
import { loadConfig, loadHandlers, processMessages, buildCommentMemoryMessagesFromFiles } from "./safe_output_handler_manager.cjs";
describe("Safe Output Handler Manager", () => {
beforeEach(() => {
// Mock global core
global.core = {
info: vi.fn(),
debug: vi.fn(),
warning: vi.fn(),
error: vi.fn(),
setOutput: vi.fn(),
setFailed: vi.fn(),
};
});
afterEach(() => {
// Clean up environment variables
delete process.env.GH_AW_SAFE_OUTPUTS_HANDLER_CONFIG;
delete process.env.GH_AW_TRACKER_LABEL;
delete process.env.GH_AW_SAFE_OUTPUT_JOBS;
delete process.env.GH_AW_SAFE_OUTPUT_SCRIPTS;
fs.rmSync("/tmp/gh-aw/comment-memory", { recursive: true, force: true });
});
describe("loadConfig", () => {
it("should load config from environment variable and normalize keys", () => {
const config = {
"create-issue": { max: 5 },
"add-comment": { max: 1 },
};
process.env.GH_AW_SAFE_OUTPUTS_HANDLER_CONFIG = JSON.stringify(config);
const result = loadConfig();
expect(result).toHaveProperty("create_issue");
expect(result).toHaveProperty("add_comment");
expect(result.create_issue).toEqual({ max: 5 });
expect(result.add_comment).toEqual({ max: 1 });
});
it("should throw error if environment variable is not set", () => {
expect(() => loadConfig()).toThrow("GH_AW_SAFE_OUTPUTS_HANDLER_CONFIG environment variable is required but not set");
});
it("should throw error if environment variable contains invalid JSON", () => {
process.env.GH_AW_SAFE_OUTPUTS_HANDLER_CONFIG = "not json";
expect(() => loadConfig()).toThrow("Failed to parse GH_AW_SAFE_OUTPUTS_HANDLER_CONFIG");
});
});
describe("loadHandlers", () => {
// These tests are skipped because they require actual handler modules to exist
// In a real environment, handlers are loaded dynamically via require()
it.skip("should load handlers for enabled safe output types", async () => {
const config = {
create_issue: { max: 1 },
add_comment: { max: 1 },
};
const handlers = await loadHandlers(config);
expect(handlers.size).toBeGreaterThan(0);
expect(handlers.has("create_issue")).toBe(true);
expect(handlers.has("add_comment")).toBe(true);
});
it.skip("should not load handlers when config entry is missing", async () => {
const config = {
create_issue: { max: 1 },
// add_comment is not in config
};
const handlers = await loadHandlers(config);
expect(handlers.has("create_issue")).toBe(true);
expect(handlers.has("add_comment")).toBe(false);
});
it.skip("should handle missing handlers gracefully", async () => {
const config = {
nonexistent_handler: { max: 1 },
};
const handlers = await loadHandlers(config);
expect(handlers.size).toBe(0);
});
it("should throw error when handler main() does not return a function", async () => {
// This test verifies that if a handler's main() function doesn't return
// a message handler function, the loadHandlers function will throw an error
// rather than just logging a warning.
//
// Expected behavior:
// 1. Handler is loaded successfully
// 2. main() is called with config
// 3. If main() returns non-function, an error is thrown
// 4. The error should fail the step
//
// This is important because:
// - Old handlers execute directly and return undefined
// - New handlers follow factory pattern and return a function
// - Silent failures from misconfigured handlers are hard to debug
//
// The implementation checks: typeof messageHandler !== "function"
// and throws: "Handler X main() did not return a function"
// Note: Actual integration testing requires real handler modules
// This test documents the expected behavior for validation
expect(true).toBe(true);
});
});
describe("loadHandlers - path traversal sanitization", () => {
// These tests exercise the path traversal sanitization added to protect against
// malicious scriptFilename values in GH_AW_SAFE_OUTPUT_SCRIPTS.
// The sanitization runs BEFORE require(), so no real file needs to exist.
it("should reject scriptFilename with a leading ../", async () => {
process.env.GH_AW_SAFE_OUTPUT_SCRIPTS = JSON.stringify({
evil: "../evil.cjs",
});
const handlers = await loadHandlers({}, {});
expect(handlers.has("evil")).toBe(false);
expect(core.error).toHaveBeenCalledWith(expect.stringContaining('path traversal detected in "../evil.cjs"'));
});
it("should reject scriptFilename with an embedded directory separator", async () => {
process.env.GH_AW_SAFE_OUTPUT_SCRIPTS = JSON.stringify({
evil: "subdir/evil.cjs",
});
const handlers = await loadHandlers({}, {});
expect(handlers.has("evil")).toBe(false);
expect(core.error).toHaveBeenCalledWith(expect.stringContaining('path traversal detected in "subdir/evil.cjs"'));
});
it("should reject scriptFilename with an absolute Unix path", async () => {
process.env.GH_AW_SAFE_OUTPUT_SCRIPTS = JSON.stringify({
evil: "/etc/passwd",
});
const handlers = await loadHandlers({}, {});
expect(handlers.has("evil")).toBe(false);
expect(core.error).toHaveBeenCalledWith(expect.stringContaining('path traversal detected in "/etc/passwd"'));
});
it("should reject scriptFilename with multiple levels of path traversal", async () => {
process.env.GH_AW_SAFE_OUTPUT_SCRIPTS = JSON.stringify({
evil: "../../etc/shadow",
});
const handlers = await loadHandlers({}, {});
expect(handlers.has("evil")).toBe(false);
expect(core.error).toHaveBeenCalledWith(expect.stringContaining('path traversal detected in "../../etc/shadow"'));
});
it("should reject scriptFilename that is just '..'", async () => {
process.env.GH_AW_SAFE_OUTPUT_SCRIPTS = JSON.stringify({
evil: "..",
});
const handlers = await loadHandlers({}, {});
expect(handlers.has("evil")).toBe(false);
expect(core.error).toHaveBeenCalledWith(expect.stringContaining("evil"));
});
it("should skip rejected entry but continue loading other valid scripts", async () => {
process.env.GH_AW_SAFE_OUTPUT_SCRIPTS = JSON.stringify({
evil: "../evil.cjs",
// This valid name will attempt require() which will fail (file doesn't exist),
// and that failure is caught as a non-fatal warning — so the handler is absent
// but no core.error is called for path traversal.
safe_script: "safe_output_script_safe_script.cjs",
});
const handlers = await loadHandlers({}, {});
// The evil entry must be rejected with core.error (path traversal)
expect(core.error).toHaveBeenCalledWith(expect.stringContaining('path traversal detected in "../evil.cjs"'));
// The safe entry should NOT trigger a path traversal error
expect(core.error).not.toHaveBeenCalledWith(expect.stringContaining('path traversal detected in "safe_output_script_safe_script.cjs"'));
// Neither handler is loaded (safe one fails because the file doesn't exist in test env)
expect(handlers.has("evil")).toBe(false);
});
it("should accept a plain filename with no path components", async () => {
// A well-formed filename — require() will fail because the file doesn't exist in
// the test environment, but NO core.error for path traversal should be logged.
process.env.GH_AW_SAFE_OUTPUT_SCRIPTS = JSON.stringify({
my_script: "safe_output_script_my_script.cjs",
});
const handlers = await loadHandlers({}, {});
// No path traversal error should have been emitted
expect(core.error).not.toHaveBeenCalledWith(expect.stringContaining("path traversal detected"));
expect(core.error).not.toHaveBeenCalledWith(expect.stringContaining("Script path outside expected directory"));
// Handler is absent only because the file doesn't exist in the test env (warning, not error)
expect(handlers.has("my_script")).toBe(false);
});
});
describe("processMessages", () => {
it("should process messages in order of appearance", async () => {
const messages = [
{ type: "add_comment", body: "Comment" },
{ type: "create_issue", title: "Issue" },
];
const mockHandler = vi.fn().mockResolvedValue({ success: true });
const handlers = new Map([
["create_issue", mockHandler],
["add_comment", mockHandler],
]);
const result = await processMessages(handlers, messages);
expect(result.success).toBe(true);
expect(result.results).toHaveLength(2);
// Verify handlers were called
expect(mockHandler).toHaveBeenCalledTimes(2);
// Verify messages were processed in order of appearance (add_comment first, then create_issue)
expect(result.results[0].type).toBe("add_comment");
expect(result.results[0].messageIndex).toBe(0);
expect(result.results[1].type).toBe("create_issue");
expect(result.results[1].messageIndex).toBe(1);
});
it("should pass the shared temporary ID map to handlers", async () => {
const messages = [
{ type: "create_issue", title: "Issue", body: "Body", temporary_id: "aw_abc123" },
{ type: "update_project", project: "https://github.com/orgs/test/projects/1", content_type: "issue", content_number: "aw_abc123" },
];
const mockCreateHandler = vi.fn().mockResolvedValue({
repo: "owner/repo",
number: 101,
temporaryId: "aw_abc123",
});
const mockUpdateProjectHandler = vi.fn().mockImplementation((message, resolvedTemporaryIds, temporaryIdMap) => {
expect(temporaryIdMap).toBeInstanceOf(Map);
expect(temporaryIdMap.get("aw_abc123")).toEqual({ repo: "owner/repo", number: 101 });
expect(resolvedTemporaryIds["aw_abc123"]).toEqual({ repo: "owner/repo", number: 101 });
return Promise.resolve({ success: true });
});
const handlers = new Map([
["create_issue", mockCreateHandler],
["update_project", mockUpdateProjectHandler],
]);
const result = await processMessages(handlers, messages);
expect(result.success).toBe(true);
expect(mockCreateHandler).toHaveBeenCalledTimes(1);
expect(mockUpdateProjectHandler).toHaveBeenCalledTimes(1);
});
it("should skip messages without type", async () => {
const messages = [{ type: "create_issue", title: "Issue" }, { title: "No type" }, { type: "add_comment", body: "Comment" }];
const mockHandler = vi.fn().mockResolvedValue({ success: true });
const handlers = new Map([
["create_issue", mockHandler],
["add_comment", mockHandler],
]);
const result = await processMessages(handlers, messages);
expect(result.success).toBe(true);
expect(result.results).toHaveLength(2);
expect(core.warning).toHaveBeenCalledWith("Skipping message 2 without type");
});
it("should warn and record result when no handler is available for message type", async () => {
const messages = [
{ type: "create_issue", title: "Issue" },
{ type: "unknown_type", data: "test" },
];
const mockHandler = vi.fn().mockResolvedValue({ success: true });
// Only create_issue handler is available, unknown_type has no handler
const handlers = new Map([["create_issue", mockHandler]]);
const result = await processMessages(handlers, messages);
expect(result.success).toBe(true);
expect(result.results).toHaveLength(2);
// First message should succeed
expect(result.results[0].success).toBe(true);
expect(result.results[0].type).toBe("create_issue");
// Second message should be recorded as failed with no handler error
expect(result.results[1].success).toBe(false);
expect(result.results[1].type).toBe("unknown_type");
expect(result.results[1].error).toContain("No handler loaded");
// Should have logged a warning
expect(core.warning).toHaveBeenCalledWith(expect.stringContaining("No handler loaded for message type 'unknown_type'"));
});
it("should skip custom safe output job types gracefully without error", async () => {
// Set up custom safe output jobs (e.g., send_slack_message handled by a dedicated job step)
process.env.GH_AW_SAFE_OUTPUT_JOBS = JSON.stringify({
send_slack_message: "message_url",
});
const messages = [
{ type: "create_issue", title: "Issue" },
{ type: "send_slack_message", channel: "#alerts", text: "Hello" },
];
const mockHandler = vi.fn().mockResolvedValue({ success: true });
// Only create_issue handler is available; send_slack_message is a custom job
const handlers = new Map([["create_issue", mockHandler]]);
const result = await processMessages(handlers, messages);
expect(result.success).toBe(true);
expect(result.results).toHaveLength(2);
// First message should succeed
expect(result.results[0].success).toBe(true);
expect(result.results[0].type).toBe("create_issue");
// Custom job message should be skipped gracefully (not an error)
expect(result.results[1].success).toBe(false);
expect(result.results[1].type).toBe("send_slack_message");
expect(result.results[1].skipped).toBe(true);
expect(result.results[1].reason).toBe("Handled by custom safe output job");
expect(result.results[1].error).toBeUndefined();
// Should NOT have logged a "No handler loaded" warning
expect(core.warning).not.toHaveBeenCalledWith(expect.stringContaining("No handler loaded for message type 'send_slack_message'"));
});
it("should skip multiple custom safe output job types gracefully", async () => {
process.env.GH_AW_SAFE_OUTPUT_JOBS = JSON.stringify({
send_slack_message: "message_url",
notion_add_comment: "comment_url",
});
const messages = [
{ type: "send_slack_message", channel: "#alerts", text: "Hello" },
{ type: "notion_add_comment", page_id: "abc123", text: "Note" },
{ type: "create_issue", title: "Issue" },
];
const mockHandler = vi.fn().mockResolvedValue({ success: true });
const handlers = new Map([["create_issue", mockHandler]]);
const result = await processMessages(handlers, messages);
expect(result.success).toBe(true);
expect(result.results).toHaveLength(3);
// Custom job types should be skipped gracefully
expect(result.results[0].skipped).toBe(true);
expect(result.results[0].reason).toBe("Handled by custom safe output job");
expect(result.results[1].skipped).toBe(true);
expect(result.results[1].reason).toBe("Handled by custom safe output job");
// create_issue should succeed
expect(result.results[2].success).toBe(true);
});
it("should still warn for unknown types not in custom job types", async () => {
process.env.GH_AW_SAFE_OUTPUT_JOBS = JSON.stringify({
send_slack_message: "message_url",
});
const messages = [{ type: "completely_unknown_type", data: "test" }];
const handlers = new Map();
const result = await processMessages(handlers, messages);
expect(result.success).toBe(true);
expect(result.results[0].error).toContain("No handler loaded");
expect(result.results[0].skipped).toBeUndefined();
// Should have logged a warning for truly unknown types
expect(core.warning).toHaveBeenCalledWith(expect.stringContaining("No handler loaded for message type 'completely_unknown_type'"));
});
it("should handle handler errors gracefully", async () => {
const messages = [{ type: "create_issue", title: "Issue" }];
const errorHandler = vi.fn().mockRejectedValue(new Error("Handler failed"));
const handlers = new Map([["create_issue", errorHandler]]);
const result = await processMessages(handlers, messages);
expect(result.success).toBe(true);
expect(result.results).toHaveLength(1);
expect(result.results[0].success).toBe(false);
expect(result.results[0].error).toBe("Handler failed");
});
it("should treat handler returning success: false as a failure", async () => {
const messages = [{ type: "create_project_status_update", project: "https://github.com/orgs/test/projects/1", body: "Test" }];
const failureHandler = vi.fn().mockResolvedValue({
success: false,
error: "GraphQL query failed",
});
const handlers = new Map([["create_project_status_update", failureHandler]]);
const result = await processMessages(handlers, messages);
expect(result.success).toBe(true);
expect(result.results).toHaveLength(1);
expect(result.results[0].success).toBe(false);
expect(result.results[0].error).toBe("GraphQL query failed");
expect(core.error).toHaveBeenCalledWith(expect.stringContaining("failed: GraphQL query failed"));
});
it("should track outputs with unresolved temporary IDs", async () => {
const messages = [
{
type: "create_issue",
body: "See #aw_abc123 for context",
title: "Test Issue",
},
];
const mockCreateIssueHandler = vi.fn().mockResolvedValue({
repo: "owner/repo",
number: 100,
});
const handlers = new Map([["create_issue", mockCreateIssueHandler]]);
const result = await processMessages(handlers, messages);
expect(result.success).toBe(true);
expect(result.outputsWithUnresolvedIds).toBeDefined();
// Should track the output because it has unresolved temp ID
expect(result.outputsWithUnresolvedIds.length).toBe(1);
expect(result.outputsWithUnresolvedIds[0].type).toBe("create_issue");
expect(result.outputsWithUnresolvedIds[0].result.number).toBe(100);
});
it("tracks comment_memory outputs using managed body for temporary ID resolution", async () => {
const messages = [
{
type: "comment_memory",
body: "raw body without ids",
memory_id: "default",
},
];
const mockCommentMemoryHandler = vi.fn().mockResolvedValue({
repo: "owner/repo",
number: 55,
commentId: 12345,
managedBody: '<gh-aw-comment-memory id="default">\nSee #aw_abc123 for details\n</gh-aw-comment-memory>',
});
const handlers = new Map([["comment_memory", mockCommentMemoryHandler]]);
const result = await processMessages(handlers, messages);
expect(result.success).toBe(true);
expect(result.outputsWithUnresolvedIds.length).toBe(1);
expect(result.outputsWithUnresolvedIds[0].type).toBe("comment_memory");
expect(result.outputsWithUnresolvedIds[0].result.commentId).toBe(12345);
});
it("should track outputs needing synthetic updates when temporary ID is resolved", async () => {
const messages = [
{
type: "create_issue",
body: "See #aw_abc123 for context",
title: "First Issue",
},
{
type: "create_issue",
temporary_id: "aw_abc123",
body: "Second issue body",
title: "Second Issue",
},
];
const mockCreateIssueHandler = vi
.fn()
.mockResolvedValueOnce({
repo: "owner/repo",
number: 100,
})
.mockResolvedValueOnce({
repo: "owner/repo",
number: 101,
temporaryId: "aw_abc123",
});
const handlers = new Map([["create_issue", mockCreateIssueHandler]]);
const result = await processMessages(handlers, messages);
expect(result.success).toBe(true);
expect(result.outputsWithUnresolvedIds).toBeDefined();
// Should track output with unresolved temp ID
expect(result.outputsWithUnresolvedIds.length).toBe(1);
expect(result.outputsWithUnresolvedIds[0].result.number).toBe(100);
// Temp ID should be registered
expect(result.temporaryIdMap["aw_abc123"]).toBeDefined();
expect(result.temporaryIdMap["aw_abc123"].number).toBe(101);
});
it("should not track output if temporary IDs remain unresolved", async () => {
const messages = [
{
type: "create_issue",
body: "See #aw_abc123 and #aw_unresolved99 for context",
title: "Test Issue",
},
];
const mockCreateIssueHandler = vi.fn().mockResolvedValue({
repo: "owner/repo",
number: 100,
});
const handlers = new Map([["create_issue", mockCreateIssueHandler]]);
const result = await processMessages(handlers, messages);
expect(result.success).toBe(true);
expect(result.outputsWithUnresolvedIds).toBeDefined();
// Should track because there are unresolved IDs
expect(result.outputsWithUnresolvedIds.length).toBe(1);
});
it("should handle multiple outputs needing synthetic updates", async () => {
const messages = [
{
type: "create_issue",
body: "Related to #aw_aabbcc11",
title: "First Issue",
},
{
type: "create_discussion",
body: "See #aw_aabbcc11 for details",
title: "Discussion",
},
{
type: "create_issue",
temporary_id: "aw_aabbcc11",
body: "The referenced issue",
title: "Referenced Issue",
},
];
const mockCreateIssueHandler = vi
.fn()
.mockResolvedValueOnce({
repo: "owner/repo",
number: 100,
})
.mockResolvedValueOnce({
repo: "owner/repo",
number: 102,
temporaryId: "aw_aabbcc11",
});
const mockCreateDiscussionHandler = vi.fn().mockResolvedValue({
repo: "owner/repo",
number: 101,
});
const handlers = new Map([
["create_issue", mockCreateIssueHandler],
["create_discussion", mockCreateDiscussionHandler],
]);
const result = await processMessages(handlers, messages);
expect(result.success).toBe(true);
expect(result.outputsWithUnresolvedIds).toBeDefined();
// Should track 2 outputs (issue and discussion) with unresolved temp IDs
expect(result.outputsWithUnresolvedIds.length).toBe(2);
// Temp ID should be registered
expect(result.temporaryIdMap["aw_aabbcc11"]).toBeDefined();
});
it("should populate artifactUrlMap when upload_artifact succeeds", async () => {
const messages = [
{
type: "upload_artifact",
temporary_id: "aw_chart1",
path: "chart.png",
},
];
const mockUploadHandler = vi.fn().mockResolvedValue({
tmpId: "aw_chart1",
artifactUrl: "https://github.com/owner/repo/actions/runs/1/artifacts/42",
});
const handlers = new Map([["upload_artifact", mockUploadHandler]]);
const result = await processMessages(handlers, messages);
expect(result.success).toBe(true);
expect(result.artifactUrlMap).toBeDefined();
expect(result.artifactUrlMap.get("aw_chart1")).toBe("https://github.com/owner/repo/actions/runs/1/artifacts/42");
});
it("should track issue with artifact reference as needing synthetic update when artifact is uploaded after", async () => {
const messages = [
{
type: "create_issue",
title: "Issue with chart",
body: "See chart: ",
},
{
type: "upload_artifact",
temporary_id: "aw_chart1",
path: "chart.png",
},
];
const mockCreateIssueHandler = vi.fn().mockResolvedValue({
repo: "owner/repo",
number: 100,
});
const mockUploadHandler = vi.fn().mockResolvedValue({
tmpId: "aw_chart1",
artifactUrl: "https://github.com/owner/repo/actions/runs/1/artifacts/42",
});
const handlers = new Map([
["create_issue", mockCreateIssueHandler],
["upload_artifact", mockUploadHandler],
]);
const result = await processMessages(handlers, messages);
expect(result.success).toBe(true);
expect(result.artifactUrlMap.get("aw_chart1")).toBe("https://github.com/owner/repo/actions/runs/1/artifacts/42");
// The issue was created before the artifact was uploaded, so it should be tracked
expect(result.outputsWithUnresolvedIds.length).toBe(1);
expect(result.outputsWithUnresolvedIds[0].result.number).toBe(100);
});
it("should replace artifact URL references in issue body when artifact is uploaded before issue", async () => {
const messages = [
{
type: "upload_artifact",
temporary_id: "aw_chart1",
path: "chart.png",
},
{
type: "create_issue",
title: "Issue with chart",
body: "See chart: ",
},
];
const mockUploadHandler = vi.fn().mockResolvedValue({
tmpId: "aw_chart1",
artifactUrl: "https://github.com/owner/repo/actions/runs/1/artifacts/42",
});
const mockCreateIssueHandler = vi.fn().mockResolvedValue({
repo: "owner/repo",
number: 100,
});
const handlers = new Map([
["upload_artifact", mockUploadHandler],
["create_issue", mockCreateIssueHandler],
]);
const result = await processMessages(handlers, messages);
expect(result.success).toBe(true);
// When artifact is already uploaded, the body passed to create_issue should have URL replaced
const calledMessage = mockCreateIssueHandler.mock.calls[0][0];
expect(calledMessage.body).toContain("https://github.com/owner/repo/actions/runs/1/artifacts/42");
expect(calledMessage.body).not.toContain("#aw_chart1");
// The issue does not need synthetic update since body was pre-resolved
expect(result.outputsWithUnresolvedIds.length).toBe(0);
});
describe("@filepath expansion in message body", () => {
let tempWorkspace;
beforeEach(() => {
tempWorkspace = fs.mkdtempSync(path.join(os.tmpdir(), "handler-manager-ws-"));
process.env.GITHUB_WORKSPACE = tempWorkspace;
});
afterEach(() => {
delete process.env.GITHUB_WORKSPACE;
fs.rmSync(tempWorkspace, { recursive: true, force: true });
});
it("should expand @filepath reference in add_comment body to file contents", async () => {
const bodyFile = path.join(tempWorkspace, "comment-body.md");
fs.writeFileSync(bodyFile, "# Hello\n\nThis is the comment body.");
const messages = [{ type: "add_comment", body: `@${bodyFile}` }];
const mockHandler = vi.fn().mockResolvedValue({ success: true });
const handlers = new Map([["add_comment", mockHandler]]);
await processMessages(handlers, messages);
const calledMessage = mockHandler.mock.calls[0][0];
expect(calledMessage.body).toBe("# Hello\n\nThis is the comment body.");
expect(calledMessage.body).not.toContain("@/");
});
it("should expand @filepath reference in create_issue body to file contents", async () => {
const bodyFile = path.join(tempWorkspace, "issue-body.md");
fs.writeFileSync(bodyFile, "Issue body content.");
const messages = [{ type: "create_issue", title: "My Issue", body: `@${bodyFile}` }];
const mockHandler = vi.fn().mockResolvedValue({ repo: "owner/repo", number: 42 });
const handlers = new Map([["create_issue", mockHandler]]);
await processMessages(handlers, messages);
const calledMessage = mockHandler.mock.calls[0][0];
expect(calledMessage.body).toBe("Issue body content.");
});
it("should allow @filepath reference from /tmp/gh-aw when GITHUB_WORKSPACE is set", async () => {
// Create a temp file simulating /tmp/gh-aw by writing to tempWorkspace/subdir instead
// (actual /tmp/gh-aw may not be writable in all CI environments; we test via workspace)
const bodyFile = path.join(tempWorkspace, "agent-body.md");
fs.writeFileSync(bodyFile, "Agent comment body.");
const messages = [{ type: "add_comment", body: `@${bodyFile}` }];
const mockHandler = vi.fn().mockResolvedValue({ success: true });
const handlers = new Map([["add_comment", mockHandler]]);
await processMessages(handlers, messages);
const calledMessage = mockHandler.mock.calls[0][0];
expect(calledMessage.body).toBe("Agent comment body.");
});
it("should leave body unchanged when no @filepath reference is present", async () => {
const messages = [{ type: "add_comment", body: "Plain comment body without file refs." }];
const mockHandler = vi.fn().mockResolvedValue({ success: true });
const handlers = new Map([["add_comment", mockHandler]]);
await processMessages(handlers, messages);
const calledMessage = mockHandler.mock.calls[0][0];
expect(calledMessage.body).toBe("Plain comment body without file refs.");
});
it("should leave disallowed @filepath references unchanged", async () => {
const messages = [{ type: "add_comment", body: "See @/etc/passwd for details." }];
const mockHandler = vi.fn().mockResolvedValue({ success: true });
const handlers = new Map([["add_comment", mockHandler]]);
await processMessages(handlers, messages);
const calledMessage = mockHandler.mock.calls[0][0];
expect(calledMessage.body).toBe("See @/etc/passwd for details.");
});
});
it("should silently skip message types handled by standalone steps", async () => {
const messages = [
{ type: "create_issue", title: "Issue" },
{ type: "upload_asset", path: "file.txt" },
];
const mockHandler = vi.fn().mockResolvedValue({ success: true });
// Only create_issue handler is available
// upload_asset is handled by a standalone step
const handlers = new Map([["create_issue", mockHandler]]);
const result = await processMessages(handlers, messages);
expect(result.success).toBe(true);
expect(result.results).toHaveLength(2);
// First message should succeed
expect(result.results[0].success).toBe(true);
expect(result.results[0].type).toBe("create_issue");
// Second message should be skipped (standalone step)
expect(result.results[1].success).toBe(false);
expect(result.results[1].type).toBe("upload_asset");
expect(result.results[1].skipped).toBe(true);
expect(result.results[1].reason).toBe("Handled by standalone step");
// Should NOT have logged warnings for standalone step types
expect(core.warning).not.toHaveBeenCalledWith(expect.stringContaining("No handler loaded for message type 'upload_asset'"));
// Should have logged debug messages
expect(core.debug).toHaveBeenCalledWith(expect.stringContaining("upload_asset"));
});
it("should track skipped message types for logging", async () => {
const messages = [
{ type: "create_issue", title: "Issue" },
{ type: "upload_asset", path: "file.txt" },
{ type: "unknown_type", data: "test" },
{ type: "another_unknown", data: "test2" },
];
const mockHandler = vi.fn().mockResolvedValue({ success: true });
// Only create_issue handler is available
const handlers = new Map([["create_issue", mockHandler]]);
const result = await processMessages(handlers, messages);
expect(result.success).toBe(true);
// Collect skipped standalone types
const skippedStandaloneResults = result.results.filter(r => r.skipped && r.reason === "Handled by standalone step");
const standaloneTypes = [...new Set(skippedStandaloneResults.map(r => r.type))];
expect(standaloneTypes).toEqual(expect.arrayContaining(["upload_asset"]));
// Collect skipped no-handler types
const skippedNoHandlerResults = result.results.filter(r => !r.success && !r.skipped && r.error?.includes("No handler loaded"));
const noHandlerTypes = [...new Set(skippedNoHandlerResults.map(r => r.type))];
expect(noHandlerTypes).toEqual(expect.arrayContaining(["unknown_type", "another_unknown"]));
});
it("should register temporary IDs from deferred messages on retry", async () => {
const messages = [
{
type: "link_sub_issue",
parent_issue_number: "aw_parent12",
sub_issue_number: 42,
},
{
type: "create_issue",
temporary_id: "aw_parent12",
title: "Parent Issue",
body: "Parent body",
},
];
// First call: link_sub_issue is deferred (parent not resolved yet)
// Second call: create_issue succeeds and registers temp ID
// Third call: link_sub_issue retry succeeds
const mockLinkHandler = vi
.fn()
.mockResolvedValueOnce({
deferred: true,
error: "Unresolved temporary IDs: parent: aw_parent12",
})
.mockResolvedValueOnce({
parent_issue_number: 100,
sub_issue_number: 42,
success: true,
});
const mockCreateIssueHandler = vi.fn().mockResolvedValue({
repo: "owner/repo",
number: 100,
temporaryId: "aw_parent12",
});
const handlers = new Map([
["link_sub_issue", mockLinkHandler],
["create_issue", mockCreateIssueHandler],
]);
const result = await processMessages(handlers, messages);
expect(result.success).toBe(true);
// Temp ID should be registered after create_issue
expect(result.temporaryIdMap["aw_parent12"]).toBeDefined();
expect(result.temporaryIdMap["aw_parent12"].number).toBe(100);
// link_sub_issue should succeed after retry
const linkResult = result.results.find(r => r.type === "link_sub_issue");
expect(linkResult.success).toBe(true);
expect(linkResult.deferred).toBe(false);
});
it("should track outputs created during deferred retry with unresolved temp IDs", async () => {
const messages = [
{
type: "create_issue",
temporary_id: "aw_aabbcc11",
title: "Issue 1",
body: "References #aw_ddeeff22",
},
{
type: "link_sub_issue",
parent_issue_number: "aw_aabbcc11",
sub_issue_number: "aw_ddeeff22",
},
{
type: "create_issue",
temporary_id: "aw_ddeeff22",
title: "Issue 2",
body: "Issue 2 body",
},
];
// create_issue for issue1: succeeds with unresolved temp ID in body
// link_sub_issue: deferred (parent and sub not resolved)
// create_issue for issue2: succeeds
// link_sub_issue retry: succeeds
const mockCreateHandler = vi
.fn()
.mockResolvedValueOnce({
repo: "owner/repo",
number: 100,
temporaryId: "aw_aabbcc11",
})
.mockResolvedValueOnce({
repo: "owner/repo",
number: 101,
temporaryId: "aw_ddeeff22",
});
const mockLinkHandler = vi
.fn()
.mockResolvedValueOnce({
deferred: true,
error: "Unresolved temporary IDs",
})
.mockResolvedValueOnce({
parent_issue_number: 100,
sub_issue_number: 101,
success: true,
});
const handlers = new Map([
["create_issue", mockCreateHandler],
["link_sub_issue", mockLinkHandler],
]);
const result = await processMessages(handlers, messages);
expect(result.success).toBe(true);
// Both issues should have temp IDs registered
expect(result.temporaryIdMap["aw_aabbcc11"]).toBeDefined();
expect(result.temporaryIdMap["aw_ddeeff22"]).toBeDefined();
// Issue 1 should be tracked for synthetic update (had unresolved temp ID in body at creation time)
// Note: By the time all messages are processed, the temp ID is resolved, but Issue 1 was
// tracked when it was created because at that moment aw_ddeeff22 was not yet in the map
const trackedIssue1 = result.outputsWithUnresolvedIds.find(o => o.result.number === 100);
expect(trackedIssue1).toBeDefined();
});
it("should handle complex parent/sub-issue creation order", async () => {
const messages = [
{
type: "create_issue",
temporary_id: "aw_abc11def",
title: "Parent",
body: "See #aw_111aaa22 and #aw_333ccc44",
},
{
type: "create_issue",
temporary_id: "aw_111aaa22",
title: "Sub 1",
body: "Sub 1 body",
},
{
type: "create_issue",
temporary_id: "aw_333ccc44",