-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Expand file tree
/
Copy pathapi.workflows.test.ts
More file actions
685 lines (593 loc) · 27.1 KB
/
api.workflows.test.ts
File metadata and controls
685 lines (593 loc) · 27.1 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
import { describe, test, expect, mock } from 'bun:test';
import { OpenAPIHono } from '@hono/zod-openapi';
import type { ConversationLockManager } from '@archon/core';
import type { WebAdapter } from '../adapters/web';
import { mkdir, rm, writeFile } from 'fs/promises';
import { join } from 'path';
import { tmpdir } from 'os';
import { validationErrorHook } from './openapi-defaults';
import { makeTestWorkflow, makeTestWorkflowWithSource } from '@archon/workflows/test-utils';
/** Test app factory: includes defaultHook to format validation errors as { error: string }. */
function createTestApp(): OpenAPIHono {
return new OpenAPIHono({ defaultHook: validationErrorHook });
}
const mockDiscoverWorkflows = mock(async (_cwd: string) => ({
workflows: [makeTestWorkflowWithSource({ name: 'deploy', description: 'Deploy app' }, 'bundled')],
errors: [
{ filename: '/tmp/.archon/workflows/bad.md', error: 'invalid', errorType: 'parse_error' },
],
}));
// Default: returns a valid workflow. Use mockReturnValueOnce in tests that need a parse failure.
const mockParseWorkflow = mock((_content: string, _filename: string) => ({
workflow: makeTestWorkflow({ name: 'test', description: 'Test workflow' }),
error: null,
}));
mock.module('@archon/core', () => ({
handleMessage: mock(async () => {}),
getDatabaseType: () => 'sqlite',
loadConfig: mock(async () => ({})),
getWorkflowFolderSearchPaths: mock(() => ['.archon/workflows']),
getCommandFolderSearchPaths: mock(() => ['.archon/commands', '.archon/commands/defaults']),
getDefaultCommandsPath: mock(() => '/tmp/.archon-test-nonexistent/commands/defaults'),
getDefaultWorkflowsPath: mock(() => '/tmp/.archon-test-nonexistent/workflows/defaults'),
cloneRepository: mock(async () => {}),
registerRepository: mock(async () => ({ success: true })),
removeWorktree: mock(async () => ({ success: true })),
ConversationNotFoundError: class extends Error {},
getArchonWorkspacesPath: () => '/tmp/.archon/workspaces',
createLogger: () => ({
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/workflows/workflow-discovery', () => ({
discoverWorkflowsWithConfig: mockDiscoverWorkflows,
}));
mock.module('@archon/workflows/loader', () => ({
parseWorkflow: mockParseWorkflow,
}));
mock.module('@archon/workflows/command-validation', () => ({
isValidCommandName: mock(
(name: string) =>
!name.includes('/') &&
!name.includes('\\') &&
!name.includes('..') &&
!!name &&
!name.startsWith('.')
),
}));
mock.module('@archon/workflows/defaults', () => ({
BUNDLED_WORKFLOWS: {
'archon-assist': 'name: archon-assist\ndescription: Archon Assist\nnodes: []',
},
BUNDLED_COMMANDS: {
'archon-assist': '# archon-assist command',
},
isBinaryBuild: mock(() => false),
}));
// Note: @archon/core/defaults/bundled-defaults and @archon/core/utils/commands are NOT mocked.
// The real implementations are used. isBinaryBuild() returns false in Bun test environment, and
// the filesystem paths used by the routes point to non-existent directories, so access/readFile/unlink
// calls naturally fail with ENOENT without needing to mock fs/promises (which would leak globally).
mock.module('@archon/core/db/conversations', () => ({}));
mock.module('@archon/core/db/isolation-environments', () => ({}));
mock.module('@archon/core/db/workflows', () => ({}));
mock.module('@archon/core/db/workflow-events', () => ({}));
mock.module('@archon/core/db/messages', () => ({}));
const mockListCodebases = mock(async () => [{ default_cwd: '/tmp/project' }]);
mock.module('@archon/core/db/codebases', () => ({
listCodebases: mockListCodebases,
}));
import { registerApiRoutes } from './api';
describe('GET /api/workflows', () => {
test('returns a flat workflows array from discoverWorkflows result', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
const response = await app.request('/api/workflows');
expect(response.status).toBe(200);
const body = (await response.json()) as {
workflows: Array<{ workflow: { name: string }; source: string }> & { workflows?: unknown };
errors: unknown[];
};
expect(Array.isArray(body.workflows)).toBe(true);
expect(body.workflows[0]?.workflow.name).toBe('deploy');
expect(body.workflows[0]?.source).toBe('bundled');
expect(body.workflows.workflows).toBeUndefined();
expect(mockDiscoverWorkflows).toHaveBeenCalledWith('/tmp/project', expect.any(Function));
expect(body.errors).toBeDefined();
expect(Array.isArray(body.errors)).toBe(true);
});
});
describe('POST /api/workflows/validate', () => {
test('returns valid:true for valid definition', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
const response = await app.request('/api/workflows/validate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ definition: { name: 'my-workflow', description: 'test', nodes: [] } }),
});
expect(response.status).toBe(200);
const body = (await response.json()) as { valid: boolean };
expect(body.valid).toBe(true);
});
test('returns valid:false with errors for invalid definition', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
mockParseWorkflow.mockReturnValueOnce({
workflow: null,
error: { filename: 'test.yaml', error: 'parse error', errorType: 'validation_error' },
});
const response = await app.request('/api/workflows/validate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ definition: { name: 'my-workflow', description: 'bad' } }),
});
expect(response.status).toBe(200);
const body = (await response.json()) as { valid: boolean; errors: string[] };
expect(body.valid).toBe(false);
expect(Array.isArray(body.errors)).toBe(true);
expect(body.errors.length).toBeGreaterThan(0);
});
test('returns 400 for missing definition', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
const response = await app.request('/api/workflows/validate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ other: 'data' }),
});
expect(response.status).toBe(400);
const body = (await response.json()) as { error: string };
expect(body.error).toContain('definition');
});
test('returns 400 for malformed JSON body', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
const response = await app.request('/api/workflows/validate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: 'not json at all {{{',
});
expect(response.status).toBe(400);
});
});
describe('GET /api/workflows/:name', () => {
test('returns 400 for invalid name (path traversal)', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
const response = await app.request('/api/workflows/..secret');
expect(response.status).toBe(400);
const body = (await response.json()) as { error: string };
expect(body.error).toContain('Invalid workflow name');
});
test('returns 404 when workflow not found', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
// No cwd → no readFile attempt → checks BUNDLED_WORKFLOWS → not there → 404
mockListCodebases.mockImplementationOnce(async () => []);
const response = await app.request('/api/workflows/nonexistent-workflow');
expect(response.status).toBe(404);
const body = (await response.json()) as { error: string };
expect(body.error).toContain('nonexistent-workflow');
});
test('returns bundled workflow with source:bundled', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
// No cwd → no readFile attempt → checks BUNDLED_WORKFLOWS → archon-assist found
mockListCodebases.mockImplementationOnce(async () => []);
const response = await app.request('/api/workflows/archon-assist');
expect(response.status).toBe(200);
const body = (await response.json()) as { source: string; filename: string; workflow: unknown };
expect(body.source).toBe('bundled');
expect(body.filename).toBe('archon-assist.yaml');
expect(body.workflow).toBeDefined();
});
test('returns project workflow with source:project when file exists on disk', async () => {
const testDir = join(tmpdir(), `wf-get-test-${Date.now()}`);
const workflowDir = join(testDir, '.archon', 'workflows');
await mkdir(workflowDir, { recursive: true });
await writeFile(
join(workflowDir, 'custom.yaml'),
'name: custom\ndescription: My custom\nnodes:\n - id: plan\n command: plan\n'
);
try {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
mockListCodebases.mockImplementationOnce(async () => [{ default_cwd: testDir }]);
const response = await app.request(`/api/workflows/custom?cwd=${testDir}`);
expect(response.status).toBe(200);
const body = (await response.json()) as {
source: string;
filename: string;
workflow: { name: string };
};
expect(body.source).toBe('project');
expect(body.filename).toBe('custom.yaml');
expect(body.workflow).toBeDefined();
} finally {
await rm(testDir, { recursive: true, force: true });
}
});
test('returns home-scoped workflow with source:global when only ~/.archon/workflows/ has it', async () => {
// Regression for #1524: home-scoped workflows are listed by the
// dashboard but were unfetchable via GET, breaking the run detail page.
const testArchonHome = join(tmpdir(), `archon-home-get-${Date.now()}`);
const homeWorkflowDir = join(testArchonHome, 'workflows');
await mkdir(homeWorkflowDir, { recursive: true });
await writeFile(
join(homeWorkflowDir, 'team-shared.yaml'),
'name: team-shared\ndescription: shared\nnodes:\n - id: n\n command: c\n'
);
process.env.ARCHON_HOME = testArchonHome;
try {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
// No project-scoped match; falls through to home-scoped.
mockListCodebases.mockImplementationOnce(async () => []);
mockParseWorkflow.mockReturnValueOnce({
workflow: makeTestWorkflow({ name: 'team-shared', description: 'shared' }),
error: null,
});
const response = await app.request('/api/workflows/team-shared');
expect(response.status).toBe(200);
const body = (await response.json()) as {
source: string;
filename: string;
workflow: { name: string };
};
expect(body.source).toBe('global');
expect(body.filename).toBe('team-shared.yaml');
expect(body.workflow.name).toBe('team-shared');
} finally {
delete process.env.ARCHON_HOME;
await rm(testArchonHome, { recursive: true, force: true });
}
});
test('project-scoped workflow shadows a same-named home-scoped one (priority: project > global > bundled)', async () => {
const testArchonHome = join(tmpdir(), `archon-home-shadow-${Date.now()}`);
const homeWorkflowDir = join(testArchonHome, 'workflows');
await mkdir(homeWorkflowDir, { recursive: true });
await writeFile(
join(homeWorkflowDir, 'shared.yaml'),
'name: shared\ndescription: home version\nnodes: []\n'
);
const projectDir = join(tmpdir(), `archon-proj-shadow-${Date.now()}`);
const projectWorkflowDir = join(projectDir, '.archon', 'workflows');
await mkdir(projectWorkflowDir, { recursive: true });
await writeFile(
join(projectWorkflowDir, 'shared.yaml'),
'name: shared\ndescription: project version\nnodes: []\n'
);
process.env.ARCHON_HOME = testArchonHome;
try {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
mockListCodebases.mockImplementationOnce(async () => [{ default_cwd: projectDir }]);
mockParseWorkflow.mockReturnValueOnce({
workflow: makeTestWorkflow({ name: 'shared', description: 'project version' }),
error: null,
});
const response = await app.request(`/api/workflows/shared?cwd=${projectDir}`);
expect(response.status).toBe(200);
const body = (await response.json()) as { source: string; workflow: { description: string } };
expect(body.source).toBe('project');
expect(body.workflow.description).toBe('project version');
} finally {
delete process.env.ARCHON_HOME;
await rm(testArchonHome, { recursive: true, force: true });
await rm(projectDir, { recursive: true, force: true });
}
});
test('returns WorkflowDefinition shape with expected top-level fields', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
mockListCodebases.mockImplementationOnce(async () => []);
const response = await app.request('/api/workflows/archon-assist');
expect(response.status).toBe(200);
const body = (await response.json()) as {
workflow: Record<string, unknown>;
};
const wf = body.workflow;
// Guard against silent spec drift if engine's workflowBaseSchema drops or renames fields
expect(typeof wf['name']).toBe('string');
expect(typeof wf['description']).toBe('string');
expect(Array.isArray(wf['nodes'])).toBe(true);
});
});
describe('GET /api/workflows/:name - cwd validation', () => {
test('returns 400 when cwd is not a registered codebase path', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
// default mock returns /tmp/project; /etc/secrets is not registered
const response = await app.request('/api/workflows/archon-assist?cwd=/etc/secrets');
expect(response.status).toBe(400);
const body = (await response.json()) as { error: string };
expect(body.error).toContain('Invalid cwd');
});
});
describe('PUT /api/workflows/:name', () => {
test('returns 400 for invalid name', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
const response = await app.request('/api/workflows/..secret', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ definition: { name: 'test' } }),
});
expect(response.status).toBe(400);
const body = (await response.json()) as { error: string };
expect(body.error).toContain('Invalid workflow name');
});
test('returns 400 for missing definition', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
const response = await app.request('/api/workflows/my-workflow', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ other: 'data' }),
});
expect(response.status).toBe(400);
const body = (await response.json()) as { error: string };
expect(body.error).toContain('definition');
});
test('falls back to home-scoped (~/.archon/workflows/) when no cwd and no codebases registered', async () => {
// Regression: previously this fell through to
// <archonHome>/.archon/workflows/, which is the legacy pre-0.x path the
// migration warning explicitly tells users to abandon. Closes #1524.
const testArchonHome = join(tmpdir(), `archon-home-test-${Date.now()}`);
process.env.ARCHON_HOME = testArchonHome;
try {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
mockListCodebases.mockImplementationOnce(async () => []);
mockParseWorkflow.mockReturnValueOnce({
workflow: makeTestWorkflow({ name: 'my-workflow', description: 'test' }),
error: null,
});
const response = await app.request('/api/workflows/my-workflow', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
definition: {
name: 'my-workflow',
description: 'test',
nodes: [{ id: 'n1', command: 'assist' }],
},
}),
});
expect(response.status).toBe(200);
const body = (await response.json()) as { workflow: object; source: string };
// The save must land in ~/.archon/workflows/ (source 'global'), NOT
// ~/.archon/.archon/workflows/ (source 'project' on a legacy path).
expect(body.source).toBe('global');
const savedPath = join(testArchonHome, 'workflows', 'my-workflow.yaml');
const stat = await import('fs/promises').then(m => m.stat(savedPath));
expect(stat.isFile()).toBe(true);
} finally {
delete process.env.ARCHON_HOME;
await rm(testArchonHome, { recursive: true, force: true });
}
});
test('returns 400 when definition fails validation', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
mockParseWorkflow.mockReturnValueOnce({
workflow: null,
error: {
filename: 'test.yaml',
error: 'missing required fields',
errorType: 'validation_error',
},
});
const response = await app.request('/api/workflows/my-workflow', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ definition: { name: 'my-workflow', description: 'bad' } }),
});
expect(response.status).toBe(400);
const body = (await response.json()) as { error: string; detail: string };
expect(body.error).toContain('invalid');
expect(body.detail).toBeDefined();
});
test('saves valid workflow and returns parsed workflow with source:project', async () => {
const testDir = join(tmpdir(), `wf-put-test-${Date.now()}`);
try {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
mockListCodebases.mockImplementationOnce(async () => [{ default_cwd: testDir }]);
const response = await app.request(`/api/workflows/my-workflow?cwd=${testDir}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
definition: {
name: 'my-workflow',
description: 'Test',
nodes: [{ id: 'plan', command: 'plan' }],
},
}),
});
expect(response.status).toBe(200);
const body = (await response.json()) as {
workflow: { name: string };
filename: string;
source: string;
};
expect(body.workflow).toBeDefined();
expect(body.filename).toBe('my-workflow.yaml');
expect(body.source).toBe('project');
} finally {
await rm(testDir, { recursive: true, force: true });
}
});
});
describe('DELETE /api/workflows/:name', () => {
test('returns 400 for bundled default name', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
// archon-assist is in the real BUNDLED_WORKFLOWS
const response = await app.request('/api/workflows/archon-assist', { method: 'DELETE' });
expect(response.status).toBe(400);
const body = (await response.json()) as { error: string };
expect(body.error).toContain('archon-assist');
});
test('returns 404 when workflow file not found', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
// Uses real unlink on a path that definitely does not exist → natural ENOENT → 404
const response = await app.request('/api/workflows/test-nonexistent-workflow-xyz', {
method: 'DELETE',
});
expect(response.status).toBe(404);
const body = (await response.json()) as { error: string };
expect(body.error).toContain('test-nonexistent-workflow-xyz');
});
test('falls back to getArchonHome() when no cwd and no codebases, returns 404 for missing file', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
mockListCodebases.mockImplementationOnce(async () => []);
const response = await app.request('/api/workflows/nonexistent-no-cwd-test', {
method: 'DELETE',
});
expect(response.status).toBe(404);
const body = (await response.json()) as { error: string };
expect(body.error).toContain('nonexistent-no-cwd-test');
});
test('removes home-scoped workflow when no cwd / no codebases registered', async () => {
// Regression for #1524: DELETE used to fall through to
// <archonHome>/.archon/workflows/, the legacy path, leaving real
// home-scoped files untouched. Now it deletes from ~/.archon/workflows/.
const testArchonHome = join(tmpdir(), `archon-home-del-${Date.now()}`);
const homeWorkflowDir = join(testArchonHome, 'workflows');
await mkdir(homeWorkflowDir, { recursive: true });
await writeFile(
join(homeWorkflowDir, 'home-only.yaml'),
'name: home-only\ndescription: x\nnodes: []\n'
);
process.env.ARCHON_HOME = testArchonHome;
try {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
mockListCodebases.mockImplementationOnce(async () => []);
const response = await app.request('/api/workflows/home-only', { method: 'DELETE' });
expect(response.status).toBe(200);
const body = (await response.json()) as { deleted: boolean; name: string };
expect(body.deleted).toBe(true);
expect(body.name).toBe('home-only');
// Verify the file is actually gone from the home-scoped location.
const fs = await import('fs/promises');
await expect(fs.stat(join(homeWorkflowDir, 'home-only.yaml'))).rejects.toThrow();
} finally {
delete process.env.ARCHON_HOME;
await rm(testArchonHome, { recursive: true, force: true });
}
});
test('removes existing workflow file and returns deleted:true', async () => {
const testDir = join(tmpdir(), `wf-del-test-${Date.now()}`);
const workflowDir = join(testDir, '.archon', 'workflows');
await mkdir(workflowDir, { recursive: true });
await writeFile(
join(workflowDir, 'to-delete.yaml'),
'name: x\ndescription: y\nnodes:\n - id: z\n command: z\n'
);
try {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
mockListCodebases.mockImplementationOnce(async () => [{ default_cwd: testDir }]);
const response = await app.request(`/api/workflows/to-delete?cwd=${testDir}`, {
method: 'DELETE',
});
expect(response.status).toBe(200);
const body = (await response.json()) as { deleted: boolean; name: string };
expect(body.deleted).toBe(true);
expect(body.name).toBe('to-delete');
} finally {
await rm(testDir, { recursive: true, force: true });
}
});
});
describe('GET /api/workflows - cwd validation', () => {
test('returns 400 when cwd is not a registered codebase path', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
// default mock returns /tmp/project; /etc is not registered
const response = await app.request('/api/workflows?cwd=/etc');
expect(response.status).toBe(400);
const body = (await response.json()) as { error: string };
expect(body.error).toContain('Invalid cwd');
});
test('accepts cwd matching a registered codebase path', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
// default mock returns /tmp/project
const response = await app.request('/api/workflows?cwd=/tmp/project');
expect(response.status).toBe(200);
});
});
describe('PUT /api/workflows/:name - cwd validation', () => {
test('returns 400 when cwd is not a registered codebase path', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
const response = await app.request('/api/workflows/my-workflow?cwd=/etc/secrets', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ definition: { name: 'my-workflow', description: 'test', nodes: [] } }),
});
expect(response.status).toBe(400);
const body = (await response.json()) as { error: string };
expect(body.error).toContain('Invalid cwd');
});
});
describe('DELETE /api/workflows/:name - cwd validation', () => {
test('returns 400 when cwd is not a registered codebase path', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
const response = await app.request('/api/workflows/some-workflow?cwd=/etc/secrets', {
method: 'DELETE',
});
expect(response.status).toBe(400);
const body = (await response.json()) as { error: string };
expect(body.error).toContain('Invalid cwd');
});
});
describe('GET /api/commands - cwd validation', () => {
test('returns 400 when cwd is not a registered codebase path', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
const response = await app.request('/api/commands?cwd=/etc/secrets');
expect(response.status).toBe(400);
const body = (await response.json()) as { error: string };
expect(body.error).toContain('Invalid cwd');
});
});
describe('GET /api/commands', () => {
test('returns commands array', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
const response = await app.request('/api/commands');
expect(response.status).toBe(200);
const body = (await response.json()) as { commands: Array<{ name: string; source: string }> };
expect(Array.isArray(body.commands)).toBe(true);
});
test('includes bundled commands with source:bundled', async () => {
const app = createTestApp();
registerApiRoutes(app, {} as WebAdapter, {} as ConversationLockManager);
const response = await app.request('/api/commands');
expect(response.status).toBe(200);
const body = (await response.json()) as { commands: Array<{ name: string; source: string }> };
// archon-assist is in the real BUNDLED_COMMANDS
const archonAssist = body.commands.find(c => c.name === 'archon-assist');
expect(archonAssist).toBeDefined();
expect(archonAssist?.source).toBe('bundled');
});
});