-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathworkflow.test.ts
More file actions
2617 lines (2249 loc) · 99.8 KB
/
Copy pathworkflow.test.ts
File metadata and controls
2617 lines (2249 loc) · 99.8 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
/**
* Tests for workflow commands
*/
import { describe, it, expect, beforeEach, afterEach, spyOn, mock } from 'bun:test';
import type { WorkflowEmitterEvent } from '@archon/workflows/event-emitter';
import { makeTestWorkflowWithSource } from '@archon/workflows/test-utils';
import {
workflowListCommand,
workflowRunCommand,
workflowStatusCommand,
workflowResumeCommand,
workflowAbandonCommand,
workflowApproveCommand,
workflowRejectCommand,
workflowCleanupCommand,
} from './workflow';
const mockLogger = {
fatal: mock(() => undefined),
error: mock(() => undefined),
warn: mock(() => undefined),
info: mock(() => undefined),
debug: mock(() => undefined),
trace: mock(() => undefined),
child: mock(() => mockLogger),
};
// Mock @archon/paths (createLogger moved here from @archon/core)
mock.module('@archon/paths', () => ({
createLogger: mock(() => mockLogger),
getArchonHome: mock(() => '/home/test/.archon'),
}));
// Mock @archon/isolation (getIsolationProvider moved here from @archon/core)
mock.module('@archon/isolation', () => ({
configureIsolation: mock(() => undefined),
getIsolationProvider: mock(() => ({
create: mock(() =>
Promise.resolve({
provider: 'worktree',
id: '/test/path',
workingPath: '/test/path',
branchName: 'test-branch',
status: 'active',
createdAt: new Date(),
metadata: { adopted: false },
})
),
healthCheck: mock(() => Promise.resolve(true)),
})),
}));
// Mock the @archon/core modules
mock.module('@archon/core', () => ({
registerRepository: mock(() =>
Promise.resolve({
codebaseId: 'cb-auto',
name: 'test/repo',
repositoryUrl: null,
defaultCwd: '/test/path',
commandCount: 0,
alreadyExisted: false,
})
),
loadConfig: mock(() => Promise.resolve({ defaults: {} })),
generateAndSetTitle: mock(() => Promise.resolve()),
loadRepoConfig: mock(() => Promise.resolve(null)),
createWorkflowStore: mock(() => ({
createWorkflowEvent: mock(() => Promise.resolve()),
})),
}));
mock.module('@archon/workflows/workflow-discovery', () => ({
discoverWorkflowsWithConfig: mock(() => Promise.resolve({ workflows: [], errors: [] })),
}));
mock.module('@archon/workflows/executor', () => ({
executeWorkflow: mock(() => Promise.resolve({ success: true, workflowRunId: 'test-run-id' })),
hydrateResumableRun: mock(() => Promise.resolve(null)),
}));
// Capture the subscription handler so tests can trigger events
let capturedSubscribeHandler: ((event: WorkflowEmitterEvent) => void) | null = null;
const mockUnsubscribe = mock(() => undefined);
mock.module('@archon/workflows/event-emitter', () => ({
getWorkflowEventEmitter: mock(() => ({
subscribeForConversation: mock(
(_convId: string, handler: (event: WorkflowEmitterEvent) => void) => {
capturedSubscribeHandler = handler;
return mockUnsubscribe;
}
),
})),
}));
mock.module('@archon/git', () => ({
findRepoRoot: mock(() => Promise.resolve(null)),
getRemoteUrl: mock(() => Promise.resolve(null)),
checkout: mock(() => Promise.resolve()),
toRepoPath: mock((path: string) => path),
toWorktreePath: mock((path: string) => path),
toBranchName: mock((branch: string) => branch),
getDefaultBranch: mock(() => Promise.resolve('dev')),
isAncestorOf: mock(() => Promise.resolve(true)),
}));
mock.module('@archon/core/db/conversations', () => ({
getOrCreateConversation: mock(() =>
Promise.resolve({ id: 'conv-123', platform_type: 'cli', platform_conversation_id: 'cli-123' })
),
getConversationById: mock(() => Promise.resolve(null)),
updateConversation: mock(() => Promise.resolve()),
}));
mock.module('@archon/core/db/codebases', () => ({
findCodebaseByDefaultCwd: mock(() => Promise.resolve(null)),
getCodebase: mock(() => Promise.resolve(null)),
}));
mock.module('@archon/core/db/isolation-environments', () => ({
findActiveByWorkflow: mock(() => Promise.resolve(null)),
create: mock(() => Promise.resolve({ id: 'iso-123' })),
}));
mock.module('@archon/core/db/messages', () => ({
addMessage: mock(() => Promise.resolve()),
}));
mock.module('@archon/core/db/workflows', () => ({
getActiveWorkflowRun: mock(() => Promise.resolve(null)),
failWorkflowRun: mock(() => Promise.resolve()),
cancelWorkflowRun: mock(() => Promise.resolve()),
findResumableRun: mock(() => Promise.resolve(null)),
resumeWorkflowRun: mock(() => Promise.resolve(null)),
getWorkflowRun: mock(() => Promise.resolve(null)),
getWorkflowRunStatus: mock(() => Promise.resolve('completed')),
updateWorkflowRun: mock(() => Promise.resolve()),
listWorkflowRuns: mock(() => Promise.resolve([])),
deleteOldWorkflowRuns: mock(() => Promise.resolve({ count: 0 })),
}));
mock.module('@archon/core/db/workflow-events', () => ({
listWorkflowEvents: mock(() => Promise.resolve([])),
createWorkflowEvent: mock(() => Promise.resolve()),
}));
describe('workflowListCommand', () => {
let consoleSpy: ReturnType<typeof spyOn>;
beforeEach(() => {
consoleSpy = spyOn(console, 'log').mockImplementation(() => {});
});
afterEach(() => {
consoleSpy.mockRestore();
});
it('should display message when no workflows found', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [],
errors: [],
});
await workflowListCommand('/test/path');
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Discovering workflows'));
expect(consoleSpy).toHaveBeenCalledWith('\nNo workflows found.');
});
it('should list workflows with names and descriptions', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [
makeTestWorkflowWithSource({ name: 'assist', description: 'General assistance workflow' }),
makeTestWorkflowWithSource({
name: 'plan',
description: 'Create implementation plan',
provider: 'claude',
}),
],
errors: [],
});
await workflowListCommand('/test/path');
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Found 2 workflow(s)'));
expect(consoleSpy).toHaveBeenCalledWith(' assist');
expect(consoleSpy).toHaveBeenCalledWith(' General assistance workflow');
expect(consoleSpy).toHaveBeenCalledWith(' plan');
expect(consoleSpy).toHaveBeenCalledWith(' Create implementation plan');
expect(consoleSpy).toHaveBeenCalledWith(' Provider: claude');
});
it('should output JSON when json flag is true', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [
makeTestWorkflowWithSource({ name: 'assist', description: 'General assistance workflow' }),
makeTestWorkflowWithSource({
name: 'plan',
description: 'Create implementation plan',
provider: 'claude',
}),
],
errors: [],
});
await workflowListCommand('/test/path', true);
expect(consoleSpy).toHaveBeenCalledTimes(1);
const output = consoleSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output) as { workflows: unknown[]; errors: unknown[] };
expect(parsed.workflows).toHaveLength(2);
expect(parsed.errors).toHaveLength(0);
expect(parsed.workflows[0]).toEqual({
name: 'assist',
description: 'General assistance workflow',
});
expect(parsed.workflows[1]).toEqual({
name: 'plan',
description: 'Create implementation plan',
provider: 'claude',
});
});
it('should include errors in JSON output', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [],
errors: [{ filename: 'bad.yaml', error: 'Invalid YAML', errorType: 'parse_error' }],
});
await workflowListCommand('/test/path', true);
const output = consoleSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output) as {
workflows: unknown[];
errors: Array<{ filename: string; error: string; errorType: string }>;
};
expect(parsed.workflows).toHaveLength(0);
expect(parsed.errors).toHaveLength(1);
expect(parsed.errors[0]).toEqual({
filename: 'bad.yaml',
error: 'Invalid YAML',
errorType: 'parse_error',
});
});
it('should not print header text in JSON mode', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [],
errors: [],
});
await workflowListCommand('/test/path', true);
// Only one console.log call (the JSON), no "Discovering workflows" text
expect(consoleSpy).toHaveBeenCalledTimes(1);
const output = consoleSpy.mock.calls[0][0] as string;
expect(output).not.toContain('Discovering workflows');
// Output must be valid JSON
expect(() => JSON.parse(output)).not.toThrow();
});
it('should include modelReasoningEffort and webSearchMode in JSON output when present', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [
makeTestWorkflowWithSource({
name: 'plan',
description: 'Planning workflow',
provider: 'codex',
model: 'gpt-5.3-codex',
modelReasoningEffort: 'high',
webSearchMode: 'live',
}),
],
errors: [],
});
await workflowListCommand('/test/path', true);
const output = consoleSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output) as {
workflows: Array<Record<string, string>>;
errors: unknown[];
};
expect(parsed.workflows[0]).toEqual({
name: 'plan',
description: 'Planning workflow',
provider: 'codex',
model: 'gpt-5.3-codex',
modelReasoningEffort: 'high',
webSearchMode: 'live',
});
});
it('should produce text output when json flag is false', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [
makeTestWorkflowWithSource({ name: 'assist', description: 'General assistance' }),
],
errors: [],
});
await workflowListCommand('/test/path', false);
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Discovering workflows'));
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Found 1 workflow(s)'));
});
it('calls discoverWorkflowsWithConfig with (cwd, loadConfig) — home scope is internal', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [],
errors: [],
});
await workflowListCommand('/test/path');
// After the globalSearchPath refactor, discovery reads ~/.archon/workflows/
// on every call with no option — every caller inherits home-scope for free.
expect(discoverWorkflowsWithConfig).toHaveBeenCalledWith('/test/path', expect.any(Function));
});
it('should throw error when discoverWorkflows fails', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockRejectedValueOnce(
new Error('Permission denied')
);
await expect(workflowListCommand('/test/path')).rejects.toThrow(
'Error loading workflows: Permission denied'
);
});
});
describe('workflowRunCommand', () => {
let consoleSpy: ReturnType<typeof spyOn>;
beforeEach(() => {
consoleSpy = spyOn(console, 'log').mockImplementation(() => {});
mockLogger.warn.mockClear();
mockLogger.info.mockClear();
});
afterEach(() => {
consoleSpy.mockRestore();
});
it('should throw error when no workflows found', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [],
errors: [],
});
await expect(workflowRunCommand('/test/path', 'assist', 'hello')).rejects.toThrow(
'No workflows found in .archon/workflows/'
);
});
it('should throw error when workflow not found', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [
makeTestWorkflowWithSource({ name: 'assist', description: 'Help' }),
makeTestWorkflowWithSource({ name: 'plan', description: 'Plan' }),
],
errors: [],
});
await expect(workflowRunCommand('/test/path', 'nonexistent', 'hello')).rejects.toThrow(
"Workflow 'nonexistent' not found"
);
});
it('should include available workflows in error when workflow not found', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [
makeTestWorkflowWithSource({ name: 'assist', description: 'Help' }),
makeTestWorkflowWithSource({ name: 'plan', description: 'Plan' }),
],
errors: [],
});
try {
await workflowRunCommand('/test/path', 'nonexistent', 'hello');
} catch (error) {
const err = error as Error;
expect(err.message).toContain('Available workflows:');
expect(err.message).toContain('- assist');
expect(err.message).toContain('- plan');
}
});
it('should resolve workflow by suffix match', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
const conversationDb = await import('@archon/core/db/conversations');
const codebaseDb = await import('@archon/core/db/codebases');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [
makeTestWorkflowWithSource({ name: 'archon-assist', description: 'Help' }),
makeTestWorkflowWithSource({ name: 'archon-plan', description: 'Plan' }),
],
errors: [],
});
(conversationDb.getOrCreateConversation as ReturnType<typeof mock>).mockResolvedValueOnce({
id: 'conv-1',
platform: 'cli',
platform_conversation_id: 'cli-123',
title: null,
is_active: true,
codebase_id: null,
});
(codebaseDb.findCodebaseByDefaultCwd as ReturnType<typeof mock>).mockResolvedValueOnce({
id: 'cb-1',
name: 'test-repo',
default_cwd: '/test/path',
});
// Should resolve successfully — "assist" suffix-matches "archon-assist"
await workflowRunCommand('/test/path', 'assist', 'hello');
// Verify suffix matching tier was used
expect(mockLogger.info).toHaveBeenCalledWith(
expect.objectContaining({ requested: 'assist', matched: 'archon-assist' }),
'workflow.resolve_suffix_match'
);
});
it('should resolve workflow by substring match', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [
makeTestWorkflowWithSource({ name: 'archon-smart-pr-review', description: 'Smart review' }),
makeTestWorkflowWithSource({ name: 'archon-assist', description: 'Help' }),
],
errors: [],
});
// "smart" substring-matches only "archon-smart-pr-review"
// Will fail downstream at executeWorkflow mock, but must NOT throw "not found"
const error = await workflowRunCommand('/test/path', 'smart', 'hello').catch(
(e: unknown) => e as Error
);
expect(error).toBeInstanceOf(Error);
expect((error as Error).message).not.toContain('not found');
expect((error as Error).message).not.toContain('Did you mean');
});
it('should prefer case-insensitive exact match over suffix match', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
const conversationDb = await import('@archon/core/db/conversations');
const codebaseDb = await import('@archon/core/db/codebases');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [
makeTestWorkflowWithSource({ name: 'assist', description: 'Help' }),
makeTestWorkflowWithSource({ name: 'archon-assist', description: 'Long' }),
],
errors: [],
});
(conversationDb.getOrCreateConversation as ReturnType<typeof mock>).mockResolvedValueOnce({
id: 'conv-1',
platform: 'cli',
platform_conversation_id: 'cli-123',
title: null,
is_active: true,
codebase_id: null,
});
(codebaseDb.findCodebaseByDefaultCwd as ReturnType<typeof mock>).mockResolvedValueOnce({
id: 'cb-1',
name: 'test-repo',
default_cwd: '/test/path',
});
// "ASSIST" case-insensitive matches "assist" at tier 2, should not reach suffix tier
await workflowRunCommand('/test/path', 'ASSIST', 'hello');
// Verify case-insensitive match was used, not suffix match
expect(mockLogger.info).toHaveBeenCalledWith(
expect.objectContaining({ requested: 'ASSIST', matched: 'assist' }),
'workflow.resolve_case_insensitive_match'
);
expect(mockLogger.info).not.toHaveBeenCalledWith(
expect.anything(),
'workflow.resolve_suffix_match'
);
});
it('should throw ambiguous error for multiple suffix matches', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [
makeTestWorkflowWithSource({ name: 'archon-review', description: 'Review' }),
makeTestWorkflowWithSource({ name: 'custom-review', description: 'Custom review' }),
],
errors: [],
});
await expect(workflowRunCommand('/test/path', 'review', 'hello')).rejects.toThrow(
"Ambiguous workflow 'review'. Did you mean:"
);
});
it('should throw ambiguous error for multiple substring matches', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [
makeTestWorkflowWithSource({
name: 'archon-comprehensive-pr-review',
description: 'Full review',
}),
makeTestWorkflowWithSource({ name: 'archon-smart-pr-review', description: 'Smart review' }),
],
errors: [],
});
await expect(workflowRunCommand('/test/path', 'pr-review', 'hello')).rejects.toThrow(
"Ambiguous workflow 'pr-review'. Did you mean:"
);
});
it('should prefer exact match over suffix match', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
const conversationDb = await import('@archon/core/db/conversations');
const codebaseDb = await import('@archon/core/db/codebases');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [
makeTestWorkflowWithSource({ name: 'assist', description: 'Short name' }),
makeTestWorkflowWithSource({ name: 'archon-assist', description: 'Long name' }),
],
errors: [],
});
(conversationDb.getOrCreateConversation as ReturnType<typeof mock>).mockResolvedValueOnce({
id: 'conv-1',
platform: 'cli',
platform_conversation_id: 'cli-123',
title: null,
is_active: true,
codebase_id: null,
});
(codebaseDb.findCodebaseByDefaultCwd as ReturnType<typeof mock>).mockResolvedValueOnce({
id: 'cb-1',
name: 'test-repo',
default_cwd: '/test/path',
});
// "assist" exact-matches "assist", should NOT go to suffix matching
await workflowRunCommand('/test/path', 'assist', 'hello');
// Should not have logged suffix/substring match — exact match takes priority
expect(mockLogger.info).not.toHaveBeenCalledWith(
expect.objectContaining({ requested: 'assist' }),
'workflow_run_suffix_match'
);
});
it('should throw error when database access fails', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
const conversationDb = await import('@archon/core/db/conversations');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [makeTestWorkflowWithSource({ name: 'assist', description: 'Help' })],
errors: [],
});
(conversationDb.getOrCreateConversation as ReturnType<typeof mock>).mockRejectedValueOnce(
new Error('Connection refused')
);
await expect(workflowRunCommand('/test/path', 'assist', 'hello')).rejects.toThrow(
'Failed to access database: Connection refused'
);
});
it('should throw when codebase lookup fails (isolation is default)', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
const conversationDb = await import('@archon/core/db/conversations');
const codebaseDb = await import('@archon/core/db/codebases');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [makeTestWorkflowWithSource({ name: 'assist', description: 'Help' })],
errors: [],
});
(conversationDb.getOrCreateConversation as ReturnType<typeof mock>).mockResolvedValueOnce({
id: 'conv-123',
});
(codebaseDb.findCodebaseByDefaultCwd as ReturnType<typeof mock>).mockRejectedValueOnce(
new Error('ECONNREFUSED')
);
await expect(workflowRunCommand('/test/path', 'assist', 'hello')).rejects.toThrow(
'Cannot create worktree: database lookup failed'
);
});
it('should continue when codebase lookup fails with --no-worktree', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
const { executeWorkflow } = await import('@archon/workflows/executor');
const conversationDb = await import('@archon/core/db/conversations');
const codebaseDb = await import('@archon/core/db/codebases');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [makeTestWorkflowWithSource({ name: 'assist', description: 'Help' })],
errors: [],
});
(conversationDb.getOrCreateConversation as ReturnType<typeof mock>).mockResolvedValueOnce({
id: 'conv-123',
});
(codebaseDb.findCodebaseByDefaultCwd as ReturnType<typeof mock>).mockRejectedValueOnce(
new Error('ECONNREFUSED')
);
(conversationDb.updateConversation as ReturnType<typeof mock>).mockResolvedValueOnce(undefined);
(executeWorkflow as ReturnType<typeof mock>).mockResolvedValueOnce({
success: true,
workflowRunId: 'run-123',
});
// With --no-worktree, DB failure is non-fatal — user explicitly opted out of isolation
await workflowRunCommand('/test/path', 'assist', 'hello', { noWorktree: true });
expect(mockLogger.warn).toHaveBeenCalledWith(
expect.objectContaining({ cwd: '/test/path' }),
'cli.codebase_lookup_failed'
);
});
it('should throw error when workflow execution fails', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
const { executeWorkflow } = await import('@archon/workflows/executor');
const conversationDb = await import('@archon/core/db/conversations');
const codebaseDb = await import('@archon/core/db/codebases');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [makeTestWorkflowWithSource({ name: 'assist', description: 'Help' })],
errors: [],
});
(conversationDb.getOrCreateConversation as ReturnType<typeof mock>).mockResolvedValueOnce({
id: 'conv-123',
});
(codebaseDb.findCodebaseByDefaultCwd as ReturnType<typeof mock>).mockResolvedValueOnce(null);
(conversationDb.updateConversation as ReturnType<typeof mock>).mockResolvedValueOnce(undefined);
(executeWorkflow as ReturnType<typeof mock>).mockResolvedValueOnce({
success: false,
error: 'Step failed: assist',
});
// Use --no-worktree since no codebase is available (isolation would error)
await expect(
workflowRunCommand('/test/path', 'assist', 'hello', { noWorktree: true })
).rejects.toThrow('Workflow failed: Step failed: assist');
});
it('should call generateAndSetTitle with workflow name and user message', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
const { executeWorkflow } = await import('@archon/workflows/executor');
const conversationDb = await import('@archon/core/db/conversations');
const codebaseDb = await import('@archon/core/db/codebases');
const core = await import('@archon/core');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [makeTestWorkflowWithSource({ name: 'assist', description: 'Help' })],
errors: [],
});
(conversationDb.getOrCreateConversation as ReturnType<typeof mock>).mockResolvedValueOnce({
id: 'conv-123',
ai_assistant_type: 'claude',
});
// Return a codebase so isolation can proceed (default behavior requires isolation)
(codebaseDb.findCodebaseByDefaultCwd as ReturnType<typeof mock>).mockResolvedValueOnce({
id: 'cb-123',
default_cwd: '/test/path',
});
(conversationDb.updateConversation as ReturnType<typeof mock>).mockResolvedValueOnce(undefined);
(executeWorkflow as ReturnType<typeof mock>).mockResolvedValueOnce({
success: true,
workflowRunId: 'run-123',
});
(core.generateAndSetTitle as ReturnType<typeof mock>).mockClear();
await workflowRunCommand('/test/path', 'assist', 'hello world');
expect(core.generateAndSetTitle).toHaveBeenCalledWith(
'conv-123',
'hello world',
'claude',
'/test/path',
'assist',
{}
);
});
it('uses the workflow provider for title generation', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
const { executeWorkflow } = await import('@archon/workflows/executor');
const conversationDb = await import('@archon/core/db/conversations');
const codebaseDb = await import('@archon/core/db/codebases');
const core = await import('@archon/core');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [
makeTestWorkflowWithSource({
name: 'figma-mcp-smoke',
description: 'Smoke test Figma MCP',
provider: 'codex',
}),
],
errors: [],
});
(conversationDb.getOrCreateConversation as ReturnType<typeof mock>).mockResolvedValueOnce({
id: 'conv-123',
ai_assistant_type: 'claude',
});
(core.loadConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
assistant: 'claude',
assistants: { codex: { model: 'gpt-5.4' } },
defaults: {},
});
(codebaseDb.findCodebaseByDefaultCwd as ReturnType<typeof mock>).mockResolvedValueOnce(null);
(conversationDb.updateConversation as ReturnType<typeof mock>).mockResolvedValueOnce(undefined);
(executeWorkflow as ReturnType<typeof mock>).mockResolvedValueOnce({
success: true,
workflowRunId: 'run-123',
});
(core.generateAndSetTitle as ReturnType<typeof mock>).mockClear();
await workflowRunCommand('/test/path', 'figma-mcp-smoke', 'check figma', { noWorktree: true });
expect(core.generateAndSetTitle).toHaveBeenCalledWith(
'conv-123',
'check figma',
'codex',
'/test/path',
'figma-mcp-smoke',
{ model: 'gpt-5.4' }
);
});
it('passes fromBranch into isolation task request', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
const { executeWorkflow } = await import('@archon/workflows/executor');
const conversationDb = await import('@archon/core/db/conversations');
const codebaseDb = await import('@archon/core/db/codebases');
const isolation = await import('@archon/isolation');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [makeTestWorkflowWithSource({ name: 'assist', description: 'Help' })],
errors: [],
});
(conversationDb.getOrCreateConversation as ReturnType<typeof mock>).mockResolvedValueOnce({
id: 'conv-123',
});
(codebaseDb.findCodebaseByDefaultCwd as ReturnType<typeof mock>).mockResolvedValueOnce({
id: 'cb-123',
default_cwd: '/test/path',
});
(conversationDb.updateConversation as ReturnType<typeof mock>).mockResolvedValueOnce(undefined);
(executeWorkflow as ReturnType<typeof mock>).mockResolvedValueOnce({
success: true,
workflowRunId: 'run-123',
});
await workflowRunCommand('/test/path', 'assist', 'hello', {
branchName: 'test-adapters',
fromBranch: 'feature/extract-adapters',
});
const getIsolationProviderMock = isolation.getIsolationProvider as ReturnType<typeof mock>;
const provider = getIsolationProviderMock.mock.results.at(-1)?.value as
| { create: ReturnType<typeof mock> }
| undefined;
expect(provider?.create).toHaveBeenCalledWith(
expect.objectContaining({
workflowType: 'task',
identifier: 'test-adapters',
fromBranch: 'feature/extract-adapters',
})
);
});
it('throws when --branch is used with --no-worktree', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [makeTestWorkflowWithSource({ name: 'assist', description: 'Help' })],
errors: [],
});
// Validation throws before codebase lookup — no need to mock findCodebaseByDefaultCwd
await expect(
workflowRunCommand('/test/path', 'assist', 'hello', {
branchName: 'test-branch',
noWorktree: true,
})
).rejects.toThrow('--branch and --no-worktree are mutually exclusive');
});
it('throws when --from is used with --no-worktree', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [makeTestWorkflowWithSource({ name: 'assist', description: 'Help' })],
errors: [],
});
// Validation throws before codebase lookup — no need to mock findCodebaseByDefaultCwd
await expect(
workflowRunCommand('/test/path', 'assist', 'hello', {
fromBranch: 'dev',
noWorktree: true,
})
).rejects.toThrow('--from/--from-branch has no effect with --no-worktree');
});
it('creates worktree with auto-generated branch when no --branch given', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
const { executeWorkflow } = await import('@archon/workflows/executor');
const conversationDb = await import('@archon/core/db/conversations');
const codebaseDb = await import('@archon/core/db/codebases');
const isolation = await import('@archon/isolation');
const isolationDb = await import('@archon/core/db/isolation-environments');
// Snapshot call counts before this test (process-global mocks)
const findActiveCallsBefore = (isolationDb.findActiveByWorkflow as ReturnType<typeof mock>).mock
.calls.length;
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [makeTestWorkflowWithSource({ name: 'assist', description: 'Help' })],
errors: [],
});
(conversationDb.getOrCreateConversation as ReturnType<typeof mock>).mockResolvedValueOnce({
id: 'conv-123',
});
(codebaseDb.findCodebaseByDefaultCwd as ReturnType<typeof mock>).mockResolvedValueOnce({
id: 'cb-123',
default_cwd: '/test/path',
});
(conversationDb.updateConversation as ReturnType<typeof mock>).mockResolvedValueOnce(undefined);
(executeWorkflow as ReturnType<typeof mock>).mockResolvedValueOnce({
success: true,
workflowRunId: 'run-123',
});
// No branchName, no noWorktree — should auto-isolate
await workflowRunCommand('/test/path', 'assist', 'hello', {});
const getIsolationProviderMock = isolation.getIsolationProvider as ReturnType<typeof mock>;
const provider = getIsolationProviderMock.mock.results.at(-1)?.value as
| { create: ReturnType<typeof mock> }
| undefined;
// provider.create should have been called with an auto-generated identifier
expect(provider?.create).toHaveBeenCalled();
const lastCreateCall = provider?.create.mock.calls.at(-1)?.[0] as {
identifier: string;
workflowType: string;
};
expect(lastCreateCall.workflowType).toBe('task');
expect(lastCreateCall.identifier).toMatch(/^assist-\d+$/);
// findActiveByWorkflow should NOT have been called during this test (no explicit --branch)
const findActiveCallsAfter = (isolationDb.findActiveByWorkflow as ReturnType<typeof mock>).mock
.calls.length;
expect(findActiveCallsAfter).toBe(findActiveCallsBefore);
});
it('skips isolation when --no-worktree flag is set', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
const { executeWorkflow } = await import('@archon/workflows/executor');
const conversationDb = await import('@archon/core/db/conversations');
const codebaseDb = await import('@archon/core/db/codebases');
const isolation = await import('@archon/isolation');
// Snapshot provider.create call count before this test
const getIsolationProviderMock = isolation.getIsolationProvider as ReturnType<typeof mock>;
const providerBefore = getIsolationProviderMock.mock.results.at(-1)?.value as
| { create: ReturnType<typeof mock> }
| undefined;
const createCallsBefore = providerBefore?.create.mock.calls.length ?? 0;
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [makeTestWorkflowWithSource({ name: 'assist', description: 'Help' })],
errors: [],
});
(conversationDb.getOrCreateConversation as ReturnType<typeof mock>).mockResolvedValueOnce({
id: 'conv-123',
});
(codebaseDb.findCodebaseByDefaultCwd as ReturnType<typeof mock>).mockResolvedValueOnce({
id: 'cb-123',
default_cwd: '/test/path',
});
(conversationDb.updateConversation as ReturnType<typeof mock>).mockResolvedValueOnce(undefined);
(executeWorkflow as ReturnType<typeof mock>).mockResolvedValueOnce({
success: true,
workflowRunId: 'run-123',
});
await workflowRunCommand('/test/path', 'assist', 'hello', { noWorktree: true });
// provider.create should NOT have been called during this test
const providerAfter = getIsolationProviderMock.mock.results.at(-1)?.value as
| { create: ReturnType<typeof mock> }
| undefined;
const createCallsAfter = providerAfter?.create.mock.calls.length ?? 0;
expect(createCallsAfter).toBe(createCallsBefore);
});
// -------------------------------------------------------------------------
// Stale workspace source-symlink → truthful CLI error
// -------------------------------------------------------------------------
it('surfaces auto-registration failures instead of claiming the repo is invalid', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
const { registerRepository } = await import('@archon/core');
const conversationDb = await import('@archon/core/db/conversations');
const codebaseDb = await import('@archon/core/db/codebases');
const gitModule = await import('@archon/git');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [makeTestWorkflowWithSource({ name: 'assist', description: 'Help' })],
errors: [],
});
(conversationDb.getOrCreateConversation as ReturnType<typeof mock>).mockResolvedValueOnce({
id: 'conv-123',
});
(codebaseDb.findCodebaseByDefaultCwd as ReturnType<typeof mock>).mockResolvedValueOnce(null);
(gitModule.findRepoRoot as ReturnType<typeof mock>).mockResolvedValueOnce('/test/path');
(registerRepository as ReturnType<typeof mock>).mockRejectedValueOnce(
new Error(
'Source symlink at /home/test/.archon/workspaces/acme/widget/source already points to ' +
'/home/test/.archon/workspaces/widget, expected /test/path'
)
);
const error = await workflowRunCommand('/test/path', 'assist', 'hello', {}).catch(
err => err as Error
);
expect(error).toBeInstanceOf(Error);
expect(error.message).toContain('Cannot create worktree: repository registration failed.');
expect(error.message).toContain(
'Remove the stale workspace entry at /home/test/.archon/workspaces/acme/widget and retry'
);
expect(error.message).not.toContain('not in a git repository');
});
it('surfaces auto-registration failures on --resume instead of claiming the repo is invalid', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
const { registerRepository } = await import('@archon/core');
const conversationDb = await import('@archon/core/db/conversations');
const codebaseDb = await import('@archon/core/db/codebases');
const gitModule = await import('@archon/git');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [makeTestWorkflowWithSource({ name: 'assist', description: 'Help' })],
errors: [],
});
(conversationDb.getOrCreateConversation as ReturnType<typeof mock>).mockResolvedValueOnce({
id: 'conv-123',
});
(codebaseDb.findCodebaseByDefaultCwd as ReturnType<typeof mock>).mockResolvedValueOnce(null);
(gitModule.findRepoRoot as ReturnType<typeof mock>).mockResolvedValueOnce('/test/path');
(registerRepository as ReturnType<typeof mock>).mockRejectedValueOnce(
new Error(
'Source symlink at /home/test/.archon/workspaces/acme/widget/source already points to ' +
'/home/test/.archon/workspaces/widget, expected /test/path'
)
);
const error = await workflowRunCommand('/test/path', 'assist', 'hello', {
resume: true,
}).catch(err => err as Error);
expect(error).toBeInstanceOf(Error);
expect(error.message).toContain('Cannot resume: repository registration failed.');
expect(error.message).toContain(
'Remove the stale workspace entry at /home/test/.archon/workspaces/acme/widget and retry'
);
expect(error.message).not.toContain('Not in a git repository');
});
it('falls back to generic workspace hint when registration error has an unrecognized shape', async () => {
const { discoverWorkflowsWithConfig } = await import('@archon/workflows/workflow-discovery');
const { registerRepository } = await import('@archon/core');
const conversationDb = await import('@archon/core/db/conversations');
const codebaseDb = await import('@archon/core/db/codebases');
const gitModule = await import('@archon/git');
(discoverWorkflowsWithConfig as ReturnType<typeof mock>).mockResolvedValueOnce({
workflows: [makeTestWorkflowWithSource({ name: 'assist', description: 'Help' })],
errors: [],