@ai-devkit/agent-manager 0.24.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,307 @@
1
+ /**
2
+ * Tests for GrokCliAdapter
3
+ *
4
+ * The adapter resolves a live process to its cwd via ~/.grok/active_sessions.json
5
+ * and reads session details from chat_history.jsonl (not summary.json/updates.jsonl).
6
+ */
7
+
8
+ import type { MockedFunction } from 'vitest';
9
+ import * as fs from 'fs';
10
+ import * as os from 'os';
11
+ import * as path from 'path';
12
+
13
+ import { GrokCliAdapter } from '../../adapters/GrokCliAdapter.js';
14
+ import type { ProcessInfo } from '../../adapters/AgentAdapter.js';
15
+ import { AgentStatus } from '../../adapters/AgentAdapter.js';
16
+ import { listAgentProcesses, enrichProcesses } from '../../utils/process.js';
17
+ import { generateAgentName } from '../../utils/matching.js';
18
+
19
+ vi.mock('../../utils/process.js', async (importOriginal) => {
20
+ const actual = (await importOriginal()) as typeof import('../../utils/process.js');
21
+ return {
22
+ ...actual,
23
+ listAgentProcesses: vi.fn(),
24
+ enrichProcesses: vi.fn(),
25
+ };
26
+ });
27
+
28
+ vi.mock('../../utils/matching.js', async (importOriginal) => {
29
+ const actual = (await importOriginal()) as typeof import('../../utils/matching.js');
30
+ return {
31
+ ...actual,
32
+ generateAgentName: vi.fn(),
33
+ };
34
+ });
35
+
36
+ const mockedListAgentProcesses = listAgentProcesses as MockedFunction<typeof listAgentProcesses>;
37
+ const mockedEnrichProcesses = enrichProcesses as MockedFunction<typeof enrichProcesses>;
38
+ const mockedGenerateAgentName = generateAgentName as MockedFunction<typeof generateAgentName>;
39
+
40
+ const SESSION_ID = '019f16c3-5d5d-7dc3-85d1-bc629416ca2d';
41
+
42
+ /** A user transcript record: the real prompt wrapped in <user_query> like Grok writes it. */
43
+ const userRecord = (text: string) => ({
44
+ type: 'user',
45
+ content: [{ type: 'text', text: `<user_query>\n${text}\n</user_query>` }],
46
+ });
47
+ /** A user context-injection record (no <user_query>) — should be ignored as a prompt. */
48
+ const contextRecord = (text: string) => ({ type: 'user', content: [{ type: 'text', text }] });
49
+ const assistantRecord = (text: string) => ({ type: 'assistant', content: [{ type: 'text', text }] });
50
+ const systemRecord = (text: string) => ({ type: 'system', content: text });
51
+
52
+ describe('GrokCliAdapter', () => {
53
+ let adapter: GrokCliAdapter;
54
+ let tmpHome: string;
55
+ let cwd: string;
56
+
57
+ beforeEach(() => {
58
+ tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'grok-adapter-test-'));
59
+ process.env.HOME = tmpHome;
60
+ delete process.env.GROK_HOME;
61
+ cwd = '/Users/dev/my-project';
62
+
63
+ adapter = new GrokCliAdapter();
64
+
65
+ mockedListAgentProcesses.mockReset();
66
+ mockedEnrichProcesses.mockReset();
67
+ mockedGenerateAgentName.mockReset();
68
+
69
+ mockedEnrichProcesses.mockImplementation((procs) => procs);
70
+ mockedGenerateAgentName.mockImplementation((c: string, pid: number) => `${path.basename(c) || 'unknown'}-${pid}`);
71
+ });
72
+
73
+ afterEach(() => {
74
+ fs.rmSync(tmpHome, { recursive: true, force: true });
75
+ });
76
+
77
+ /** Write a session dir under ~/.grok/sessions/<enc(cwd)>/<id>/chat_history.jsonl. */
78
+ function writeSession(opts: {
79
+ sessionCwd?: string;
80
+ id?: string;
81
+ records?: object[];
82
+ chat?: boolean;
83
+ mtime?: Date;
84
+ }): string {
85
+ const sessionCwd = opts.sessionCwd ?? cwd;
86
+ const id = opts.id ?? SESSION_ID;
87
+ const sessionDir = path.join(tmpHome, '.grok', 'sessions', encodeURIComponent(sessionCwd), id);
88
+ fs.mkdirSync(sessionDir, { recursive: true });
89
+
90
+ if (opts.chat !== false) {
91
+ const records = opts.records ?? [userRecord('fix the bug')];
92
+ const chatPath = path.join(sessionDir, 'chat_history.jsonl');
93
+ fs.writeFileSync(chatPath, records.map((r) => JSON.stringify(r)).join('\n'));
94
+ if (opts.mtime) fs.utimesSync(chatPath, opts.mtime, opts.mtime);
95
+ }
96
+
97
+ return sessionDir;
98
+ }
99
+
100
+ /** Write ~/.grok/active_sessions.json (the live pid -> cwd registry). */
101
+ function writeActiveSessions(entries: Array<{ pid: number; cwd: string; opened_at?: number }>): void {
102
+ fs.mkdirSync(path.join(tmpHome, '.grok'), { recursive: true });
103
+ fs.writeFileSync(path.join(tmpHome, '.grok', 'active_sessions.json'), JSON.stringify(entries));
104
+ }
105
+
106
+ function proc(overrides: Partial<ProcessInfo> = {}): ProcessInfo {
107
+ return { pid: 4242, ppid: 1, command: 'grok', cwd, tty: 'ttys010', startTime: new Date(), ...overrides };
108
+ }
109
+
110
+ describe('initialization', () => {
111
+ it('exposes the grok_cli type', () => {
112
+ expect(adapter.type).toBe('grok_cli');
113
+ });
114
+ });
115
+
116
+ describe('canHandle', () => {
117
+ it('returns true for a plain grok command', () => {
118
+ expect(adapter.canHandle(proc({ command: 'grok' }))).toBe(true);
119
+ });
120
+
121
+ it('returns true for grok with a full path and args', () => {
122
+ expect(adapter.canHandle(proc({ command: '/Users/dev/.grok/bin/grok --always-approve' }))).toBe(true);
123
+ });
124
+
125
+ it('returns false for non-grok processes', () => {
126
+ expect(adapter.canHandle(proc({ command: 'node app.js' }))).toBe(false);
127
+ });
128
+
129
+ it('returns false when "grok" appears only in an argument path', () => {
130
+ expect(adapter.canHandle(proc({ command: 'node /path/to/grok-thing.js' }))).toBe(false);
131
+ });
132
+ });
133
+
134
+ describe('detectAgents', () => {
135
+ it('returns [] when there are no grok processes', async () => {
136
+ mockedListAgentProcesses.mockReturnValue([]);
137
+ expect(await adapter.detectAgents()).toEqual([]);
138
+ });
139
+
140
+ it('resolves the cwd via active_sessions.json (authoritative over the process cwd)', async () => {
141
+ const realCwd = '/Users/dev/real-project';
142
+ writeSession({ sessionCwd: realCwd });
143
+ // The process cwd is stale/wrong; active_sessions.json has the truth.
144
+ writeActiveSessions([{ pid: 4242, cwd: realCwd, opened_at: 1 }]);
145
+ mockedListAgentProcesses.mockReturnValue([proc({ cwd: '/wrong/path' })]);
146
+
147
+ const agents = await adapter.detectAgents();
148
+
149
+ expect(agents).toHaveLength(1);
150
+ expect(agents[0]).toMatchObject({
151
+ type: 'grok_cli',
152
+ pid: 4242,
153
+ projectPath: realCwd,
154
+ sessionId: SESSION_ID,
155
+ summary: 'fix the bug',
156
+ });
157
+ expect(agents[0].sessionFilePath).toBe(
158
+ path.join(tmpHome, '.grok', 'sessions', encodeURIComponent(realCwd), SESSION_ID, 'chat_history.jsonl'),
159
+ );
160
+ });
161
+
162
+ it('falls back to the process cwd when the pid is not in active_sessions.json', async () => {
163
+ writeSession({});
164
+ writeActiveSessions([{ pid: 9999, cwd: '/somewhere/else' }]);
165
+ mockedListAgentProcesses.mockReturnValue([proc()]);
166
+
167
+ const agents = await adapter.detectAgents();
168
+
169
+ expect(agents[0]).toMatchObject({ projectPath: cwd, sessionId: SESSION_ID });
170
+ });
171
+
172
+ it('picks the most recently active session dir when a cwd has several', async () => {
173
+ const older = new Date(Date.now() - 60 * 60 * 1000);
174
+ writeSession({ id: '019f0000-0000-7000-8000-00000000000a', records: [userRecord('old one')], mtime: older });
175
+ writeSession({ id: '019f0000-0000-7000-8000-00000000000b', records: [userRecord('newest one')] });
176
+ mockedListAgentProcesses.mockReturnValue([proc()]);
177
+
178
+ const agents = await adapter.detectAgents();
179
+
180
+ expect(agents[0].sessionId).toBe('019f0000-0000-7000-8000-00000000000b');
181
+ expect(agents[0].summary).toBe('newest one');
182
+ });
183
+
184
+ it('falls back to a process-only RUNNING agent when no session matches', async () => {
185
+ mockedListAgentProcesses.mockReturnValue([proc()]);
186
+
187
+ const agents = await adapter.detectAgents();
188
+
189
+ expect(agents).toHaveLength(1);
190
+ expect(agents[0].status).toBe(AgentStatus.RUNNING);
191
+ expect(agents[0].sessionId).toBe('pid-4242');
192
+ expect(agents[0].sessionFilePath).toBeUndefined();
193
+ });
194
+
195
+ it('treats a session dir without chat_history.jsonl as no match (process-only)', async () => {
196
+ writeSession({ chat: false });
197
+ mockedListAgentProcesses.mockReturnValue([proc()]);
198
+
199
+ const agents = await adapter.detectAgents();
200
+
201
+ expect(agents).toHaveLength(1);
202
+ expect(agents[0].sessionId).toBe('pid-4242');
203
+ });
204
+ });
205
+
206
+ describe('getConversation', () => {
207
+ it('maps user (<user_query>) and assistant records to roles', () => {
208
+ const dir = writeSession({ records: [userRecord('hi'), assistantRecord('hello')] });
209
+ expect(adapter.getConversation(path.join(dir, 'chat_history.jsonl'))).toEqual([
210
+ { role: 'user', content: 'hi' },
211
+ { role: 'assistant', content: 'hello' },
212
+ ]);
213
+ });
214
+
215
+ it('accepts a session dir path and skips context-injection user records', () => {
216
+ const dir = writeSession({
217
+ records: [contextRecord('<user_info>OS: macos</user_info>'), userRecord('do the thing')],
218
+ });
219
+ expect(adapter.getConversation(dir)).toEqual([{ role: 'user', content: 'do the thing' }]);
220
+ });
221
+
222
+ it('skips malformed lines', () => {
223
+ const dir = writeSession({ records: [userRecord('hi')] });
224
+ fs.appendFileSync(path.join(dir, 'chat_history.jsonl'), '\n{bad json');
225
+ expect(adapter.getConversation(dir)).toEqual([{ role: 'user', content: 'hi' }]);
226
+ });
227
+
228
+ it('excludes system records unless verbose', () => {
229
+ const dir = writeSession({ records: [systemRecord('You are Grok'), userRecord('go')] });
230
+ expect(adapter.getConversation(dir)).toEqual([{ role: 'user', content: 'go' }]);
231
+ expect(adapter.getConversation(dir, { verbose: true }).map((m) => m.role)).toEqual(['system', 'user']);
232
+ });
233
+ });
234
+
235
+ describe('detectAgents status + summary mapping', () => {
236
+ const detectFirst = async () => (await adapter.detectAgents())[0];
237
+
238
+ it('marks WAITING when the last transcript turn is an assistant message', async () => {
239
+ writeSession({ records: [userRecord('go'), assistantRecord('done')] });
240
+ mockedListAgentProcesses.mockReturnValue([proc()]);
241
+ expect((await detectFirst()).status).toBe(AgentStatus.WAITING);
242
+ });
243
+
244
+ it('marks RUNNING when the last transcript turn is a user message', async () => {
245
+ writeSession({ records: [userRecord('still there?')] });
246
+ mockedListAgentProcesses.mockReturnValue([proc()]);
247
+ expect((await detectFirst()).status).toBe(AgentStatus.RUNNING);
248
+ });
249
+
250
+ it('marks IDLE when chat_history.jsonl is older than the threshold', async () => {
251
+ const old = new Date(Date.now() - 10 * 60 * 1000);
252
+ writeSession({ records: [userRecord('go')], mtime: old });
253
+ mockedListAgentProcesses.mockReturnValue([proc()]);
254
+ expect((await detectFirst()).status).toBe(AgentStatus.IDLE);
255
+ });
256
+
257
+ it('uses the last user prompt as the agent summary', async () => {
258
+ writeSession({ records: [userRecord('refactor the parser'), assistantRecord('on it')] });
259
+ mockedListAgentProcesses.mockReturnValue([proc()]);
260
+ expect((await detectFirst()).summary).toBe('refactor the parser');
261
+ });
262
+ });
263
+
264
+ describe('listSessions', () => {
265
+ it('returns [] when the sessions dir does not exist', async () => {
266
+ expect(await adapter.listSessions()).toEqual([]);
267
+ });
268
+
269
+ it('lists historical sessions with cwd decoded from the group dir', async () => {
270
+ writeSession({});
271
+ const summaries = await adapter.listSessions();
272
+ expect(summaries).toHaveLength(1);
273
+ expect(summaries[0]).toMatchObject({
274
+ type: 'grok_cli',
275
+ sessionId: SESSION_ID,
276
+ cwd,
277
+ firstUserMessage: 'fix the bug',
278
+ });
279
+ expect(summaries[0].sessionFilePath).toBe(
280
+ path.join(tmpHome, '.grok', 'sessions', encodeURIComponent(cwd), SESSION_ID, 'chat_history.jsonl'),
281
+ );
282
+ });
283
+
284
+ it('applies the cwd filter against the decoded cwd', async () => {
285
+ writeSession({ sessionCwd: '/Users/dev/project-a', id: '019f0000-0000-7000-8000-00000000000a' });
286
+ writeSession({ sessionCwd: '/Users/dev/project-b', id: '019f0000-0000-7000-8000-00000000000b' });
287
+
288
+ const all = await adapter.listSessions();
289
+ expect(all).toHaveLength(2);
290
+
291
+ const filtered = await adapter.listSessions({ cwd: '/Users/dev/project-a' });
292
+ expect(filtered).toHaveLength(1);
293
+ expect(filtered[0].cwd).toBe('/Users/dev/project-a');
294
+ });
295
+
296
+ it('skips non-session entries (e.g. prompt_history.jsonl) in a group dir', async () => {
297
+ writeSession({});
298
+ // Grok writes a group-level prompt_history.jsonl alongside session dirs.
299
+ fs.writeFileSync(
300
+ path.join(tmpHome, '.grok', 'sessions', encodeURIComponent(cwd), 'prompt_history.jsonl'),
301
+ '{"text":"noise"}',
302
+ );
303
+ const summaries = await adapter.listSessions();
304
+ expect(summaries).toHaveLength(1);
305
+ });
306
+ });
307
+ });
@@ -14,4 +14,11 @@ describe('AGENTS', () => {
14
14
  expect(AGENTS.pi.matches('/usr/local/bin/pi --model x')).toBe(true);
15
15
  expect(AGENTS.pi.matches('node /repo/feature-pi-adapter/script.js')).toBe(false);
16
16
  });
17
+
18
+ it('includes Grok as a startable agent', () => {
19
+ expect(AGENTS.grok_cli.command).toBe('grok');
20
+ expect(AGENTS.grok_cli.matches('grok')).toBe(true);
21
+ expect(AGENTS.grok_cli.matches('/Users/dev/.grok/bin/grok --always-approve')).toBe(true);
22
+ expect(AGENTS.grok_cli.matches('node /repo/feature-grok-cli/script.js')).toBe(false);
23
+ });
17
24
  });
@@ -8,7 +8,7 @@
8
8
  /**
9
9
  * Type of AI agent
10
10
  */
11
- export type AgentType = 'claude' | 'gemini_cli' | 'codex' | 'opencode' | 'copilot' | 'pi' | 'other';
11
+ export type AgentType = 'claude' | 'gemini_cli' | 'grok_cli' | 'codex' | 'opencode' | 'copilot' | 'pi' | 'other';
12
12
 
13
13
  /**
14
14
  * Current status of an agent