-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathadapter.test.ts
More file actions
1586 lines (1362 loc) · 59.7 KB
/
Copy pathadapter.test.ts
File metadata and controls
1586 lines (1362 loc) · 59.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
/**
* Unit tests for GitHub adapter
*
* Note: Database modules are mocked to prevent self-filtering tests from
* writing phantom records (e.g., testuser/testrepo) to the real SQLite DB.
*/
import { describe, test, expect, mock, beforeEach, afterEach } from 'bun:test';
// Mock logger to suppress noisy output during tests
const mockLogger = {
fatal: mock(() => undefined),
error: mock(() => undefined),
warn: mock(() => undefined),
info: mock(() => undefined),
debug: mock(() => undefined),
trace: mock(() => undefined),
child: mock(function (this: unknown) {
return this;
}),
bindings: mock(() => ({ module: 'test' })),
isLevelEnabled: mock(() => true),
level: 'info',
};
mock.module('@archon/paths', () => ({
createLogger: mock(() => mockLogger),
getCommandFolderSearchPaths: mock(() => ['.archon/commands', '.claude/commands']),
getProjectSourcePath: mock(
(owner: string, repo: string) => `/tmp/test-workspaces/${owner}/${repo}/source`
),
ensureProjectStructure: mock(async () => undefined),
}));
// Only mock what's needed for the adapter's direct functionality
const mockExecFile = mock(
(
_cmd: string,
_args: string[],
_opts: unknown,
callback: (err: Error | null, result: { stdout: string; stderr: string }) => void
) => {
callback(null, { stdout: '', stderr: '' });
}
);
mock.module('child_process', () => ({
execFile: mockExecFile,
}));
// Mock database modules to prevent self-filtering tests from writing
// phantom records (testuser/testrepo) to the real SQLite database.
// handleWebhook() calls getOrCreateConversation + getOrCreateCodebaseForRepo
// before hitting unmocked Octokit calls - those DB writes persisted silently.
const mockGetOrCreateConversation = mock(async () => ({
id: 'conv-test',
codebase_id: null,
cwd: null,
isolation_env_id: null,
}));
const mockUpdateConversation = mock(async () => {});
mock.module('@archon/core/db/conversations', () => ({
getOrCreateConversation: mockGetOrCreateConversation,
updateConversation: mockUpdateConversation,
}));
const mockFindCodebaseByRepoUrl = mock(async () => null);
const mockCreateCodebase = mock(async () => ({
id: 'codebase-test',
name: 'testuser/testrepo',
default_cwd: '/tmp/test',
}));
mock.module('@archon/core/db/codebases', () => ({
findCodebaseByRepoUrl: mockFindCodebaseByRepoUrl,
createCodebase: mockCreateCodebase,
updateCodebase: mock(async () => {}),
getCodebaseCommands: mock(async () => ({})),
updateCodebaseCommands: mock(async () => {}),
}));
// Mock the users module so adapter.handleWebhook's user-id resolution can be
// inspected without hitting the real DB. Captures the (platform, login) args
// so the comment.user.login ?? sender.login fallback can be asserted.
const mockFindOrCreateUserByPlatformIdentity = mock(
async (_platform: string, _platformUserId: string, _displayName?: string) => ({
id: 'user-test-uuid',
display_name: 'Test',
email: null,
created_at: new Date(),
updated_at: new Date(),
})
);
mock.module('@archon/core/db/users', () => ({
findOrCreateUserByPlatformIdentity: mockFindOrCreateUserByPlatformIdentity,
}));
// Mock @archon/git for ensureRepoReady integration tests
const mockCloneRepository = mock(async () => ({ ok: true, value: undefined }));
const mockSyncRepository = mock(async () => ({ ok: true, value: undefined }));
const mockAddSafeDirectory = mock(async () => undefined);
const mockIsWorktreePath = mock(async () => false);
// execFileAsync is used by installCredentialHelper (which runs after a
// successful App-mode clone). We don't need to assert against it here; it
// just has to be a no-op rather than `undefined` (which would TypeError).
const mockExecFileAsync = mock(async () => ({ stdout: '', stderr: '' }));
mock.module('@archon/git', () => ({
cloneRepository: mockCloneRepository,
syncRepository: mockSyncRepository,
addSafeDirectory: mockAddSafeDirectory,
isWorktreePath: mockIsWorktreePath,
toRepoPath: (p: string) => p,
toBranchName: (n: string) => n,
toWorktreePath: (p: string) => p,
execFileAsync: mockExecFileAsync,
mkdirAsync: mock(async () => undefined),
}));
import { GitHubAdapter } from './adapter';
import { ConversationLockManager } from '@archon/core';
// Create a mock lock manager that immediately executes handlers
const mockLockManager = {
acquireLock: mock(async (_id: string, handler: () => Promise<void>) => {
await handler();
}),
getStats: () => ({
active: 0,
queuedTotal: 0,
queuedByConversation: [],
maxConcurrent: 10,
activeConversationIds: [],
}),
} as unknown as ConversationLockManager;
/**
* Helper to create a test adapter with mocked Octokit createComment method.
* Reduces duplication across tests that need to verify comment posting behavior.
*/
async function createTestAdapterWithMockedOctokit(
mockCreateComment: ReturnType<typeof mock>,
options?: { retryDelayMs?: (attempt: number) => number }
): Promise<GitHubAdapter> {
const testAdapter = new GitHubAdapter(
{ kind: 'pat', token: 'fake-token-for-testing' },
'fake-webhook-secret',
mockLockManager,
undefined,
options
);
await testAdapter.start();
// @ts-expect-error - accessing private property for testing
testAdapter.octokit = {
rest: {
issues: {
createComment: mockCreateComment,
},
},
};
return testAdapter;
}
describe('GitHubAdapter', () => {
let adapter: GitHubAdapter;
beforeEach(() => {
mockExecFile.mockClear();
adapter = new GitHubAdapter(
{ kind: 'pat', token: 'fake-token-for-testing' },
'fake-webhook-secret',
mockLockManager
);
});
describe('streaming mode', () => {
test('should always return batch mode', () => {
expect(adapter.getStreamingMode()).toBe('batch');
});
});
describe('platform type', () => {
test('should return github', () => {
expect(adapter.getPlatformType()).toBe('github');
});
});
describe('lifecycle methods', () => {
test('should start without errors', async () => {
await expect(adapter.start()).resolves.toBeUndefined();
});
test('should stop without errors', () => {
expect(() => adapter.stop()).not.toThrow();
});
});
describe('bot mention detection', () => {
test('should detect mention case-insensitively', () => {
const adapterWithMention = new GitHubAdapter(
{ kind: 'pat', token: 'token' },
'secret',
mockLockManager,
'Dylan'
);
const hasMention = (
adapterWithMention as unknown as { hasMention: (text: string) => boolean }
).hasMention;
expect(hasMention.call(adapterWithMention, '@Dylan please help')).toBe(true);
expect(hasMention.call(adapterWithMention, '@dylan please help')).toBe(true);
expect(hasMention.call(adapterWithMention, '@DYLAN please help')).toBe(true);
expect(hasMention.call(adapterWithMention, '@DyLaN please help')).toBe(true);
expect(hasMention.call(adapterWithMention, '@other-bot please help')).toBe(false);
expect(hasMention.call(adapterWithMention, 'no mention here')).toBe(false);
});
test('should detect mention when it is the entire message', () => {
const adapterWithMention = new GitHubAdapter(
{ kind: 'pat', token: 'token' },
'secret',
mockLockManager,
'Archon'
);
const hasMention = (
adapterWithMention as unknown as { hasMention: (text: string) => boolean }
).hasMention;
expect(hasMention.call(adapterWithMention, '@Archon')).toBe(true);
expect(hasMention.call(adapterWithMention, '@ARCHON')).toBe(true);
expect(hasMention.call(adapterWithMention, '@archon')).toBe(true);
});
test('should strip mention case-insensitively', () => {
const adapterWithMention = new GitHubAdapter(
{ kind: 'pat', token: 'token' },
'secret',
mockLockManager,
'Dylan'
);
const stripMention = (
adapterWithMention as unknown as { stripMention: (text: string) => string }
).stripMention;
expect(stripMention.call(adapterWithMention, '@Dylan please help')).toBe('please help');
expect(stripMention.call(adapterWithMention, '@dylan please help')).toBe('please help');
expect(stripMention.call(adapterWithMention, '@DYLAN please help')).toBe('please help');
});
});
describe('self-filtering', () => {
// Test context for self-filtering tests
let originalAllowedUsers: string | undefined;
/**
* Creates an adapter with mocked signature verification for self-filtering tests.
*/
function createSelfFilterAdapter(botMention = 'archon'): GitHubAdapter {
const adapter = new GitHubAdapter(
{ kind: 'pat', token: 'fake-token-for-testing' },
'fake-webhook-secret',
mockLockManager,
botMention
);
// @ts-expect-error - accessing private method for testing
adapter.verifySignature = mock(() => true);
return adapter;
}
/**
* Creates a webhook payload for issue comment events.
*/
function createCommentPayload(commentBody: string, commentAuthor: string | undefined): string {
const comment: { body: string; user?: { login: string } } = { body: commentBody };
if (commentAuthor !== undefined) {
comment.user = { login: commentAuthor };
}
return JSON.stringify({
action: 'created',
issue: {
number: 42,
title: 'Test Issue',
body: 'Description',
user: { login: 'user123' },
labels: [],
state: 'open',
},
comment,
repository: {
owner: { login: 'testuser' },
name: 'testrepo',
full_name: 'testuser/testrepo',
html_url: 'https://github.com/testuser/testrepo',
default_branch: 'main',
},
sender: { login: commentAuthor ?? 'user123' },
});
}
beforeEach(() => {
originalAllowedUsers = process.env.GITHUB_ALLOWED_USERS;
delete process.env.GITHUB_ALLOWED_USERS;
mockLockManager.acquireLock.mockClear();
mockGetOrCreateConversation.mockClear();
mockFindCodebaseByRepoUrl.mockClear();
mockCreateCodebase.mockClear();
mockFindOrCreateUserByPlatformIdentity.mockClear();
});
afterEach(() => {
if (originalAllowedUsers !== undefined) {
process.env.GITHUB_ALLOWED_USERS = originalAllowedUsers;
}
});
test('attribution falls back to sender.login when comment.user is absent', async () => {
const adapter = createSelfFilterAdapter();
const payload = createCommentPayload('@archon help', undefined); // no comment.user
// sender.login defaults to 'user123' in createCommentPayload when commentAuthor is undefined.
try {
await adapter.handleWebhook(payload, 'mock-signature');
} catch {
// Expected — Octokit not mocked for the message path.
}
// Identity resolution must run, and must have used sender.login.
const calls = mockFindOrCreateUserByPlatformIdentity.mock.calls;
expect(calls.length).toBeGreaterThan(0);
expect(calls[0]).toEqual(['github', 'user123', 'user123']);
});
test('attribution prefers comment.user.login over sender.login when both present', async () => {
const adapter = createSelfFilterAdapter();
// Simulate a PR-review-comment shape: sender (e.g. PR author who triggered the
// event flow) differs from the comment author (the reviewer).
const payload = JSON.stringify({
action: 'created',
issue: {
number: 42,
title: 'Test Issue',
body: 'x',
user: { login: 'pr-author' },
labels: [],
state: 'open',
},
comment: { body: '@archon look at this', user: { login: 'reviewer-alice' } },
repository: {
owner: { login: 'testuser' },
name: 'testrepo',
full_name: 'testuser/testrepo',
html_url: 'https://github.com/testuser/testrepo',
default_branch: 'main',
},
sender: { login: 'pr-author' },
});
try {
await adapter.handleWebhook(payload, 'mock-signature');
} catch {
// Expected — Octokit not mocked.
}
const calls = mockFindOrCreateUserByPlatformIdentity.mock.calls;
expect(calls.length).toBeGreaterThan(0);
// Reviewer (comment author) gets the row, not the PR author (sender).
expect(calls[0]).toEqual(['github', 'reviewer-alice', 'reviewer-alice']);
});
test('handleWebhook never throws when identity resolution fails', async () => {
const adapter = createSelfFilterAdapter();
mockFindOrCreateUserByPlatformIdentity.mockRejectedValueOnce(new Error('db down'));
const payload = createCommentPayload('@archon help', 'user123');
try {
await adapter.handleWebhook(payload, 'mock-signature');
} catch {
// Octokit not mocked downstream — that's fine.
}
// The user-resolution failure was caught and warn-logged; the webhook
// handler proceeded past it (DB write for the conversation still happened).
expect(mockGetOrCreateConversation).toHaveBeenCalled();
});
test('should ignore comments from the bot itself', async () => {
const adapter = createSelfFilterAdapter();
const payload = createCommentPayload('@archon fix this', 'archon');
await adapter.handleWebhook(payload, 'mock-signature');
// Bot's own comments should be silently dropped - no lock acquired, no processing
expect(mockLockManager.acquireLock).not.toHaveBeenCalled();
});
test('should handle case-insensitive username matching', async () => {
const adapter = createSelfFilterAdapter('Archon'); // Mixed case config
const payload = createCommentPayload('@archon test', 'archon'); // Lowercase author
await adapter.handleWebhook(payload, 'mock-signature');
// Bot's own comments should be silently dropped regardless of case
expect(mockLockManager.acquireLock).not.toHaveBeenCalled();
});
test('should NOT filter comments from real users', async () => {
const adapter = createSelfFilterAdapter();
const payload = createCommentPayload('@archon please help', 'user123');
// handleWebhook progresses past self-filtering into DB/Octokit operations
try {
await adapter.handleWebhook(payload, 'mock-signature');
} catch {
// Expected - Octokit API not mocked for this test
}
// Real user comments proceed to conversation creation (not self-filtered)
expect(mockGetOrCreateConversation).toHaveBeenCalled();
});
test('should ignore comments containing bot marker (works with user PAT)', async () => {
const adapter = createSelfFilterAdapter();
// Comment has the marker but author is a real user (using PAT)
const payload = createCommentPayload(
'@archon fix this\n\n<!-- archon-bot-response -->',
'Wirasm'
);
await adapter.handleWebhook(payload, 'mock-signature');
// Marked comments should be silently dropped
expect(mockLockManager.acquireLock).not.toHaveBeenCalled();
});
test('should process comments without bot marker from same user', async () => {
const adapter = createSelfFilterAdapter();
// Comment from same user but WITHOUT marker - should be processed
const payload = createCommentPayload('@archon fix this', 'Wirasm');
// handleWebhook progresses past self-filtering into DB/Octokit operations
try {
await adapter.handleWebhook(payload, 'mock-signature');
} catch {
// Expected - Octokit API not mocked for this test
}
// Comment without marker proceeds to conversation creation (not self-filtered)
expect(mockGetOrCreateConversation).toHaveBeenCalled();
});
test('should handle missing comment.user gracefully', async () => {
const adapter = createSelfFilterAdapter();
const payload = createCommentPayload('@archon help', undefined); // No user field
// Should not crash on undefined user
try {
await adapter.handleWebhook(payload, 'mock-signature');
} catch {
// Expected - Octokit API not mocked for this test
}
// Missing user should not trigger self-filtering (proceeds to conversation creation)
expect(mockGetOrCreateConversation).toHaveBeenCalled();
});
});
describe('webhook delivery dedup', () => {
let originalAllowedUsers: string | undefined;
function createDedupAdapter(): GitHubAdapter {
const adapter = new GitHubAdapter(
{ kind: 'pat', token: 'fake-token-for-testing' },
'fake-webhook-secret',
mockLockManager,
'archon'
);
// @ts-expect-error - accessing private method for testing
adapter.verifySignature = mock(() => true);
return adapter;
}
/**
* Comment payload carrying GitHub's comment identity (id + updated_at),
* as real issue_comment deliveries do.
*/
function createIdentifiedCommentPayload(
commentBody: string,
commentId: number | undefined,
updatedAt: string | undefined
): string {
const comment: {
id?: number;
body: string;
user: { login: string };
updated_at?: string;
} = { body: commentBody, user: { login: 'user123' } };
if (commentId !== undefined) comment.id = commentId;
if (updatedAt !== undefined) comment.updated_at = updatedAt;
return JSON.stringify({
action: 'created',
issue: {
number: 42,
title: 'Test Issue',
body: 'Description',
user: { login: 'user123' },
labels: [],
state: 'open',
},
comment,
repository: {
owner: { login: 'testuser' },
name: 'testrepo',
full_name: 'testuser/testrepo',
html_url: 'https://github.com/testuser/testrepo',
default_branch: 'main',
},
sender: { login: 'user123' },
});
}
async function deliver(adapter: GitHubAdapter, payload: string, deliveryId?: string) {
try {
await adapter.handleWebhook(payload, 'mock-signature', deliveryId);
} catch {
// Expected - Octokit API not mocked for the downstream message path.
}
}
beforeEach(() => {
originalAllowedUsers = process.env.GITHUB_ALLOWED_USERS;
delete process.env.GITHUB_ALLOWED_USERS;
mockLockManager.acquireLock.mockClear();
mockGetOrCreateConversation.mockClear();
});
afterEach(() => {
if (originalAllowedUsers !== undefined) {
process.env.GITHUB_ALLOWED_USERS = originalAllowedUsers;
}
});
test('drops a repeat delivery of the same comment (same GUID)', async () => {
const adapter = createDedupAdapter();
const payload = createIdentifiedCommentPayload('@archon help', 1001, '2026-06-12T21:00:00Z');
await deliver(adapter, payload, 'guid-1');
await deliver(adapter, payload, 'guid-1');
expect(mockGetOrCreateConversation).toHaveBeenCalledTimes(1);
});
test('drops a dual-subscription duplicate (same comment, different GUIDs)', async () => {
const adapter = createDedupAdapter();
const payload = createIdentifiedCommentPayload('@archon help', 1001, '2026-06-12T21:00:00Z');
// Repo webhook and App webhook deliver the same comment under different
// delivery GUIDs — the #1951 incident shape.
await deliver(adapter, payload, 'guid-repo-hook');
await deliver(adapter, payload, 'guid-app-hook');
expect(mockGetOrCreateConversation).toHaveBeenCalledTimes(1);
});
test('processes an edited comment again (new updated_at)', async () => {
const adapter = createDedupAdapter();
const original = createIdentifiedCommentPayload('@archon help', 1001, '2026-06-12T21:00:00Z');
const edited = createIdentifiedCommentPayload(
'@archon help please',
1001,
'2026-06-12T21:05:00Z'
);
await deliver(adapter, original, 'guid-1');
await deliver(adapter, edited, 'guid-2');
expect(mockGetOrCreateConversation).toHaveBeenCalledTimes(2);
});
test('processes distinct comments independently', async () => {
const adapter = createDedupAdapter();
const first = createIdentifiedCommentPayload('@archon help', 1001, '2026-06-12T21:00:00Z');
const second = createIdentifiedCommentPayload('@archon also', 1002, '2026-06-12T21:00:30Z');
await deliver(adapter, first, 'guid-1');
await deliver(adapter, second, 'guid-2');
expect(mockGetOrCreateConversation).toHaveBeenCalledTimes(2);
});
test('requires both id and updated_at for the comment key (id alone uses GUID fallback)', async () => {
const adapter = createDedupAdapter();
// id present but updated_at missing — keying on id alone would dedup a
// later edit against the original, so this must use the GUID fallback.
const payload = createIdentifiedCommentPayload('@archon help', 1001, undefined);
await deliver(adapter, payload, 'guid-1');
await deliver(adapter, payload, 'guid-1');
await deliver(adapter, payload, 'guid-2');
// Same GUID deduped, different GUID processed (no comment-identity key).
expect(mockGetOrCreateConversation).toHaveBeenCalledTimes(2);
});
test('falls back to delivery GUID when payload lacks comment id', async () => {
const adapter = createDedupAdapter();
const payload = createIdentifiedCommentPayload('@archon help', undefined, undefined);
await deliver(adapter, payload, 'guid-1');
await deliver(adapter, payload, 'guid-1');
expect(mockGetOrCreateConversation).toHaveBeenCalledTimes(1);
});
test('fails open when neither comment id nor delivery GUID is available', async () => {
const adapter = createDedupAdapter();
const payload = createIdentifiedCommentPayload('@archon help', undefined, undefined);
await deliver(adapter, payload, undefined);
await deliver(adapter, payload, undefined);
// No key to dedup on — both deliveries process rather than risk drops.
expect(mockGetOrCreateConversation).toHaveBeenCalledTimes(2);
});
});
describe('conversationId format', () => {
test('should parse valid owner/repo#number format', async () => {
const mockCreateComment = mock(() => Promise.resolve({ data: {} }));
const testAdapter = await createTestAdapterWithMockedOctokit(mockCreateComment);
await testAdapter.sendMessage('owner/repo#123', 'test');
expect(mockCreateComment).toHaveBeenCalledWith({
owner: 'owner',
repo: 'repo',
issue_number: 123,
body: 'test\n\n<!-- archon-bot-response -->',
});
});
test('postComment appends bot marker to outgoing comments', async () => {
const mockCreateComment = mock(() => Promise.resolve({ data: {} }));
const testAdapter = await createTestAdapterWithMockedOctokit(mockCreateComment);
await testAdapter.sendMessage('owner/repo#123', 'Hello world');
const body = mockCreateComment.mock.calls[0][0].body as string;
expect(body).toContain('Hello world');
expect(body).toContain('<!-- archon-bot-response -->');
expect(body).toBe('Hello world\n\n<!-- archon-bot-response -->');
});
test('should reject invalid conversationId format', async () => {
const mockCreateComment = mock(() => Promise.resolve({ data: {} }));
const testAdapter = await createTestAdapterWithMockedOctokit(mockCreateComment);
// Invalid format (pr-42 is not a number) should return early without calling API
await testAdapter.sendMessage('owner/repo#pr-42', 'test');
expect(mockCreateComment).not.toHaveBeenCalled();
});
});
describe('PR detection helpers', () => {
test('should detect PR from issue.pull_request property', () => {
const issueWithPR = {
number: 42,
title: 'Test PR',
body: 'Test body',
user: { login: 'testuser' },
labels: [],
state: 'open',
pull_request: { url: 'https://api.github.com/repos/owner/repo/pulls/42' },
};
const issueWithoutPR = {
number: 42,
title: 'Test Issue',
body: 'Test body',
user: { login: 'testuser' },
labels: [],
state: 'open',
};
expect(!!issueWithPR.pull_request).toBe(true);
expect(!!(issueWithoutPR as typeof issueWithPR).pull_request).toBe(false);
});
});
describe('worktree path detection helpers', () => {
test('paths containing /worktrees/ should be detected', () => {
const worktreePath = '/workspace/worktrees/issue-42/repo';
const normalPath = '/workspace/repo';
expect(worktreePath.includes('/worktrees/')).toBe(true);
expect(normalPath.includes('/worktrees/')).toBe(false);
});
});
describe('worktree creation feedback messages', () => {
test('issue worktree message format', () => {
// Verify the message format for issue worktrees
const number = 42;
const branchName = `issue-${String(number)}`;
const message = `Working in isolated branch \`${branchName}\``;
expect(message).toBe('Working in isolated branch `issue-42`');
expect(message).toContain('isolated branch');
expect(message).toContain('issue-42');
});
test('PR worktree message format with SHA', () => {
// Verify the message format for PR worktrees with SHA
const prHeadSha = 'abc123def456789';
const prHeadBranch = 'feature/awesome-feature';
const shortSha = prHeadSha.substring(0, 7);
const message = `Reviewing PR at commit \`${shortSha}\` (branch: \`${prHeadBranch}\`)`;
expect(message).toBe('Reviewing PR at commit `abc123d` (branch: `feature/awesome-feature`)');
expect(message).toContain('Reviewing PR');
expect(message).toContain('abc123d');
expect(message).toContain('feature/awesome-feature');
});
test('PR worktree message format without SHA (fallback)', () => {
// Verify the fallback message format for PRs without head SHA
const number = 42;
const isPR = true;
const branchName = isPR ? `pr-${String(number)}` : `issue-${String(number)}`;
const message = `Working in isolated branch \`${branchName}\``;
expect(message).toBe('Working in isolated branch `pr-42`');
expect(message).toContain('isolated branch');
expect(message).toContain('pr-42');
});
test('shared worktree message format (PR linked to issue)', () => {
// Verify the message format when PR shares worktree with linked issue
const issueNum = 42;
const message = `Reusing worktree from issue #${String(issueNum)}`;
expect(message).toBe('Reusing worktree from issue #42');
expect(message).toContain('Reusing');
expect(message).toContain('#42');
});
test('existing worktree reuse message format', () => {
// Verify the message format when conversation already has a worktree
const number = 42;
const isPR = false;
const branchName = isPR ? `pr-${String(number)}` : `issue-${String(number)}`;
const message = `Reusing worktree \`${branchName}\``;
expect(message).toBe('Reusing worktree `issue-42`');
expect(message).toContain('Reusing');
expect(message).toContain('issue-42');
});
test('messages use backticks for branch names', () => {
// Verify messages use GitHub markdown backticks for branch names
const issueMessage = 'Working in isolated branch `issue-42`';
const prMessage = 'Reviewing PR at commit `abc1234` (branch: `feature-x`)';
// Count backticks (should be pairs for formatting)
const issueBackticks = (issueMessage.match(/`/g) ?? []).length;
const prBackticks = (prMessage.match(/`/g) ?? []).length;
expect(issueBackticks).toBe(2); // One pair for branch name
expect(prBackticks).toBe(4); // Two pairs (SHA + branch)
});
});
describe('multi-repo path isolation', () => {
test('should use owner/repo path structure for codebases', () => {
// Test that path construction includes owner
const workspacePath = '/workspace';
const owner1 = 'alice';
const owner2 = 'bob';
const repo = 'utils';
// Simulate the path construction logic
const path1 = `${workspacePath}/${owner1}/${repo}`;
const path2 = `${workspacePath}/${owner2}/${repo}`;
// Paths should be different even with same repo name
expect(path1).not.toBe(path2);
expect(path1).toBe('/workspace/alice/utils');
expect(path2).toBe('/workspace/bob/utils');
});
test('worktrees should be isolated by owner', () => {
// Worktrees are relative to repo path, so they auto-isolate
const aliceRepoPath = '/workspace/alice/utils';
const bobRepoPath = '/workspace/bob/utils';
const issueNumber = 33;
// Simulate worktree path construction
const aliceWorktree = `${aliceRepoPath}/../worktrees/issue-${issueNumber}`;
const bobWorktree = `${bobRepoPath}/../worktrees/issue-${issueNumber}`;
// Note: These resolve to different paths
// /workspace/alice/worktrees/issue-33 vs /workspace/bob/worktrees/issue-33
expect(aliceWorktree).not.toBe(bobWorktree);
});
});
describe('message splitting', () => {
test('should split long messages into multiple chunks', async () => {
const mockCreateComment = mock(() => Promise.resolve({ data: {} }));
const testAdapter = await createTestAdapterWithMockedOctokit(mockCreateComment);
// Create message exceeding MAX_LENGTH (65000)
const paragraph1 = 'a'.repeat(40000);
const paragraph2 = 'b'.repeat(30000);
const message = `${paragraph1}\n\n${paragraph2}`;
await testAdapter.sendMessage('owner/repo#123', message);
// Should have sent 2 separate comments
expect(mockCreateComment).toHaveBeenCalledTimes(2);
// First chunk should contain paragraph1
expect(mockCreateComment).toHaveBeenNthCalledWith(1, {
owner: 'owner',
repo: 'repo',
issue_number: 123,
body: expect.stringContaining('aaa'),
});
// Second chunk should contain paragraph2
expect(mockCreateComment).toHaveBeenNthCalledWith(2, {
owner: 'owner',
repo: 'repo',
issue_number: 123,
body: expect.stringContaining('bbb'),
});
// Verify chunk sizes are within limits
const firstChunkBody = mockCreateComment.mock.calls[0][0].body as string;
const secondChunkBody = mockCreateComment.mock.calls[1][0].body as string;
expect(firstChunkBody.length).toBeLessThanOrEqual(65000);
expect(secondChunkBody.length).toBeLessThanOrEqual(65000);
});
test('should not split message at exactly MAX_LENGTH', async () => {
const mockCreateComment = mock(() => Promise.resolve({ data: {} }));
const testAdapter = await createTestAdapterWithMockedOctokit(mockCreateComment);
// Message exactly at MAX_LENGTH (65000) should not be split
const message = 'a'.repeat(65000);
await testAdapter.sendMessage('owner/repo#123', message);
expect(mockCreateComment).toHaveBeenCalledTimes(1);
});
test('should handle message without paragraph breaks', async () => {
const mockCreateComment = mock(() => Promise.resolve({ data: {} }));
const testAdapter = await createTestAdapterWithMockedOctokit(mockCreateComment);
// Message under MAX_LENGTH with no paragraph breaks
const message = 'a'.repeat(50000);
await testAdapter.sendMessage('owner/repo#123', message);
expect(mockCreateComment).toHaveBeenCalledTimes(1);
});
test('should throw error when chunk posting fails', async () => {
const mockCreateComment = mock()
.mockResolvedValueOnce({ data: {} }) // First chunk succeeds
.mockRejectedValueOnce(new Error('API rate limit exceeded')); // Second chunk fails
const testAdapter = await createTestAdapterWithMockedOctokit(mockCreateComment);
// Create message that will be split into 2 chunks
const paragraph1 = 'a'.repeat(40000);
const paragraph2 = 'b'.repeat(30000);
const message = `${paragraph1}\n\n${paragraph2}`;
// Should throw with context about partial delivery
await expect(testAdapter.sendMessage('owner/repo#123', message)).rejects.toThrow(
/Failed to post comment chunk 2\/2/
);
// First chunk should have been posted
expect(mockCreateComment).toHaveBeenCalledTimes(2);
});
});
describe('retry logic', () => {
test('should retry on transient network errors', async () => {
const mockCreateComment = mock()
.mockRejectedValueOnce(new Error('fetch failed')) // First attempt fails
.mockResolvedValueOnce({ data: {} }); // Second attempt succeeds
const testAdapter = await createTestAdapterWithMockedOctokit(mockCreateComment, {
retryDelayMs: () => 1,
});
await testAdapter.sendMessage('owner/repo#123', 'test message');
// Should have retried once
expect(mockCreateComment).toHaveBeenCalledTimes(2);
});
test('should retry on transient status errors', async () => {
const transientError = Object.assign(new Error('Gateway failure'), { status: 502 });
const mockCreateComment = mock()
.mockRejectedValueOnce(transientError) // First attempt fails
.mockResolvedValueOnce({ data: {} }); // Second attempt succeeds
const testAdapter = await createTestAdapterWithMockedOctokit(mockCreateComment, {
retryDelayMs: () => 1,
});
await testAdapter.sendMessage('owner/repo#123', 'test message');
// Should have retried once for structured 502 status
expect(mockCreateComment).toHaveBeenCalledTimes(2);
});
test('should not retry on non-retryable errors', async () => {
const mockCreateComment = mock().mockRejectedValue(new Error('Bad credentials'));
const testAdapter = await createTestAdapterWithMockedOctokit(mockCreateComment);
// Should throw immediately without retry
await expect(testAdapter.sendMessage('owner/repo#123', 'test message')).rejects.toThrow(
'Bad credentials'
);
// Should only have tried once (no retry for auth errors)
expect(mockCreateComment).toHaveBeenCalledTimes(1);
});
test('should not retry on auth status errors', async () => {
const authError = Object.assign(new Error('Unauthorized'), { status: 401 });
const mockCreateComment = mock().mockRejectedValue(authError);
const testAdapter = await createTestAdapterWithMockedOctokit(mockCreateComment);
// Should throw immediately without retry
await expect(testAdapter.sendMessage('owner/repo#123', 'test message')).rejects.toThrow(
'Unauthorized'
);
// Should only have tried once (no retry for auth errors)
expect(mockCreateComment).toHaveBeenCalledTimes(1);
});
test('should throw after exhausting retries', async () => {
const mockCreateComment = mock().mockRejectedValue(new Error('fetch failed'));
const testAdapter = await createTestAdapterWithMockedOctokit(mockCreateComment, {
retryDelayMs: () => 1,
});
// Should throw after 3 attempts
await expect(testAdapter.sendMessage('owner/repo#123', 'test message')).rejects.toThrow(
'fetch failed'
);
// Should have tried 3 times (max retries)
expect(mockCreateComment).toHaveBeenCalledTimes(3);
});
});
describe('fork detection logic', () => {
/**
* Tests for the fork detection comparison logic used in handleWebhook.
* The actual logic: isForkPR = headRepoFullName !== baseRepoFullName
* This logic determines whether a PR uses the actual branch (same-repo)
* or a synthetic pr-N-review branch (fork).
*/
test('should detect same-repo PR when head and base repos match', () => {
// Simulates same-repo PR where contributor has push access
const headRepoFullName = 'owner/repo';
const baseRepoFullName = 'owner/repo';
const isForkPR = headRepoFullName !== baseRepoFullName;
expect(isForkPR).toBe(false);
});
test('should detect fork PR when head and base repos differ', () => {
// Simulates fork PR where head is from a different repo
const headRepoFullName = 'contributor/repo';
const baseRepoFullName = 'owner/repo';
const isForkPR = headRepoFullName !== baseRepoFullName;
expect(isForkPR).toBe(true);
});
test('should detect fork PR when head.repo is null (deleted fork)', () => {
// When a fork is deleted after a PR was opened, head.repo becomes null
// The optional chaining (?.) returns undefined, and undefined !== 'owner/repo' is true
const headRepoFullName: string | undefined = undefined; // Simulates prData.head.repo?.full_name
const baseRepoFullName = 'owner/repo';
const isForkPR = headRepoFullName !== baseRepoFullName;
// Correctly treated as fork - can't push to deleted repo anyway
expect(isForkPR).toBe(true);
});
test('should handle case sensitivity correctly', () => {
// GitHub full_names are case-sensitive in the API response
const headRepoFullName = 'Owner/Repo';
const baseRepoFullName = 'owner/repo';