@ai-devkit/agent-manager 0.25.0 → 0.26.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.
Files changed (59) hide show
  1. package/README.md +14 -0
  2. package/dist/__tests__/print/ClaudeCliProbe.test.js +53 -0
  3. package/dist/__tests__/print/ClaudeCliProbe.test.js.map +1 -0
  4. package/dist/__tests__/print/ClaudePrintAgent.integration.test.js +69 -0
  5. package/dist/__tests__/print/ClaudePrintAgent.integration.test.js.map +1 -0
  6. package/dist/__tests__/print/ClaudePrintAgentService.test.js +108 -0
  7. package/dist/__tests__/print/ClaudePrintAgentService.test.js.map +1 -0
  8. package/dist/__tests__/print/ClaudePrintRunner.test.js +187 -0
  9. package/dist/__tests__/print/ClaudePrintRunner.test.js.map +1 -0
  10. package/dist/__tests__/print/PrintAgent.test.js +17 -0
  11. package/dist/__tests__/print/PrintAgent.test.js.map +1 -0
  12. package/dist/__tests__/print/PrintAgentStore.test.js +307 -0
  13. package/dist/__tests__/print/PrintAgentStore.test.js.map +1 -0
  14. package/dist/__tests__/terminal/TmuxManager.test.js +9 -0
  15. package/dist/__tests__/terminal/TmuxManager.test.js.map +1 -1
  16. package/dist/index.d.ts +11 -0
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +6 -0
  19. package/dist/index.js.map +1 -1
  20. package/dist/print/ClaudeCliProbe.d.ts +20 -0
  21. package/dist/print/ClaudeCliProbe.d.ts.map +1 -0
  22. package/dist/print/ClaudeCliProbe.js +57 -0
  23. package/dist/print/ClaudeCliProbe.js.map +1 -0
  24. package/dist/print/ClaudePrintAgentService.d.ts +44 -0
  25. package/dist/print/ClaudePrintAgentService.d.ts.map +1 -0
  26. package/dist/print/ClaudePrintAgentService.js +66 -0
  27. package/dist/print/ClaudePrintAgentService.js.map +1 -0
  28. package/dist/print/ClaudePrintRunner.d.ts +32 -0
  29. package/dist/print/ClaudePrintRunner.d.ts.map +1 -0
  30. package/dist/print/ClaudePrintRunner.js +128 -0
  31. package/dist/print/ClaudePrintRunner.js.map +1 -0
  32. package/dist/print/PrintAgent.d.ts +57 -0
  33. package/dist/print/PrintAgent.d.ts.map +1 -0
  34. package/dist/print/PrintAgent.js +42 -0
  35. package/dist/print/PrintAgent.js.map +1 -0
  36. package/dist/print/PrintAgentStore.d.ts +69 -0
  37. package/dist/print/PrintAgentStore.d.ts.map +1 -0
  38. package/dist/print/PrintAgentStore.js +484 -0
  39. package/dist/print/PrintAgentStore.js.map +1 -0
  40. package/dist/terminal/TmuxManager.d.ts +2 -2
  41. package/dist/terminal/TmuxManager.d.ts.map +1 -1
  42. package/dist/terminal/TmuxManager.js +5 -7
  43. package/dist/terminal/TmuxManager.js.map +1 -1
  44. package/package.json +1 -1
  45. package/src/__tests__/fixtures/fake-claude.cjs +24 -0
  46. package/src/__tests__/print/ClaudeCliProbe.test.ts +32 -0
  47. package/src/__tests__/print/ClaudePrintAgent.integration.test.ts +56 -0
  48. package/src/__tests__/print/ClaudePrintAgentService.test.ts +46 -0
  49. package/src/__tests__/print/ClaudePrintRunner.test.ts +105 -0
  50. package/src/__tests__/print/PrintAgent.test.ts +21 -0
  51. package/src/__tests__/print/PrintAgentStore.test.ts +192 -0
  52. package/src/__tests__/terminal/TmuxManager.test.ts +10 -0
  53. package/src/index.ts +39 -0
  54. package/src/print/ClaudeCliProbe.ts +58 -0
  55. package/src/print/ClaudePrintAgentService.ts +94 -0
  56. package/src/print/ClaudePrintRunner.ts +139 -0
  57. package/src/print/PrintAgent.ts +86 -0
  58. package/src/print/PrintAgentStore.ts +503 -0
  59. package/src/terminal/TmuxManager.ts +5 -7
@@ -0,0 +1,503 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import { randomUUID } from 'crypto';
5
+ import { execFileSync } from 'child_process';
6
+ import type { PrintAgent, ProcessIdentity, PrintRunStatus, PrintSessionHealth } from './PrintAgent.js';
7
+ import {
8
+ PrintAgentBusyError,
9
+ PrintAgentNameConflictError,
10
+ PrintAgentNotFoundError,
11
+ PrintAgentStoreError,
12
+ } from './PrintAgent.js';
13
+
14
+ interface PrintAgentStoreFile {
15
+ version: 1;
16
+ agents: PrintAgent[];
17
+ }
18
+
19
+ export interface CreatePrintAgentInput {
20
+ name: string;
21
+ cwd: string;
22
+ }
23
+
24
+ export interface PrintAgentStoreOptions {
25
+ filePath?: string;
26
+ lockTimeoutMs?: number;
27
+ now?: () => Date;
28
+ processInspector?: ProcessInspector;
29
+ incompleteLockGraceMs?: number;
30
+ mutationLockStaleMs?: number;
31
+ }
32
+
33
+ export interface ProcessInspector {
34
+ getIdentity(pid: number): ProcessIdentity | null;
35
+ }
36
+
37
+ export interface PrintRunCompletion {
38
+ status: PrintRunStatus;
39
+ exitCode: number | null;
40
+ summary: string;
41
+ sessionHealth: PrintSessionHealth;
42
+ }
43
+
44
+ const DEFAULT_FILE = path.join(os.homedir(), '.ai-devkit', 'print-agents.json');
45
+
46
+ export class PrintAgentStore {
47
+ readonly filePath: string;
48
+ private readonly lockPath: string;
49
+ private readonly lockTimeoutMs: number;
50
+ private readonly now: () => Date;
51
+ private readonly processInspector: ProcessInspector;
52
+ private readonly runLocksRoot: string;
53
+ private readonly incompleteLockGraceMs: number;
54
+ private readonly mutationLockStaleMs: number;
55
+
56
+ constructor(options: PrintAgentStoreOptions = {}) {
57
+ this.filePath = options.filePath ?? DEFAULT_FILE;
58
+ this.lockPath = `${this.filePath}.lock`;
59
+ this.lockTimeoutMs = options.lockTimeoutMs ?? 2000;
60
+ this.now = options.now ?? (() => new Date());
61
+ this.processInspector = options.processInspector ?? new LocalProcessInspector();
62
+ this.runLocksRoot = path.join(path.dirname(this.filePath), 'print-agent-locks');
63
+ this.incompleteLockGraceMs = options.incompleteLockGraceMs ?? 30_000;
64
+ this.mutationLockStaleMs = options.mutationLockStaleMs ?? 30_000;
65
+ }
66
+
67
+ async create(input: CreatePrintAgentInput): Promise<PrintAgent> {
68
+ const cwd = this.canonicalDirectory(input.cwd);
69
+ return this.withMutationLock(async () => {
70
+ const data = this.readFile();
71
+ if (data.agents.some((agent) => agent.name.toLowerCase() === input.name.toLowerCase())) {
72
+ throw new PrintAgentNameConflictError(input.name);
73
+ }
74
+ const timestamp = this.now().toISOString();
75
+ let id = randomUUID();
76
+ let providerSessionId = randomUUID();
77
+ while (providerSessionId === id) providerSessionId = randomUUID();
78
+ while (data.agents.some((agent) => agent.id === id)) id = randomUUID();
79
+ const agent: PrintAgent = {
80
+ id,
81
+ name: input.name,
82
+ provider: 'claude',
83
+ mode: 'print',
84
+ cwd,
85
+ providerSessionId,
86
+ state: 'ready',
87
+ sessionHealth: 'uninitialized',
88
+ createdAt: timestamp,
89
+ updatedAt: timestamp,
90
+ lastActiveAt: null,
91
+ lastResult: null,
92
+ activeRun: null,
93
+ };
94
+ data.agents.push(agent);
95
+ this.writeFile(data);
96
+ return structuredClone(agent);
97
+ });
98
+ }
99
+
100
+ async list(): Promise<PrintAgent[]> {
101
+ await this.reconcile();
102
+ return this.listRaw();
103
+ }
104
+
105
+ async getById(id: string): Promise<PrintAgent | null> {
106
+ return (await this.list()).find((agent) => agent.id === id) ?? null;
107
+ }
108
+
109
+ async reconcile(): Promise<void> {
110
+ const running = this.listRaw().filter((agent) => agent.state === 'running' && agent.activeRun);
111
+ for (const snapshot of running) {
112
+ const lockPath = this.runLockPath(snapshot.id);
113
+ const metadata = this.readRunLock(snapshot.id);
114
+ if (metadata && this.isActive(metadata)) continue;
115
+ if (!metadata && this.isYoungLock(lockPath)) continue;
116
+
117
+ if (fs.existsSync(lockPath)) {
118
+ const quarantine = `${lockPath}.stale-${randomUUID()}`;
119
+ try {
120
+ fs.renameSync(lockPath, quarantine);
121
+ this.removeLockDirectory(quarantine);
122
+ } catch {
123
+ continue;
124
+ }
125
+ }
126
+ const completedAt = this.now().toISOString();
127
+ await this.updateAgent(snapshot.id, (current) => {
128
+ if (current.state !== 'running' || current.activeRun?.token !== snapshot.activeRun?.token) return current;
129
+ return {
130
+ ...current,
131
+ state: 'degraded',
132
+ sessionHealth: 'unknown',
133
+ activeRun: null,
134
+ updatedAt: completedAt,
135
+ lastActiveAt: completedAt,
136
+ lastResult: {
137
+ status: 'interrupted',
138
+ completedAt,
139
+ exitCode: null,
140
+ summary: 'Previous print run was interrupted.',
141
+ },
142
+ };
143
+ });
144
+ }
145
+ }
146
+
147
+ async resolve(reference: string): Promise<PrintAgent | PrintAgent[] | null> {
148
+ const agents = await this.list();
149
+ const byId = agents.find((agent) => agent.id === reference);
150
+ if (byId) return byId;
151
+ const matches = agents.filter((agent) => agent.name.toLowerCase() === reference.toLowerCase());
152
+ if (matches.length === 0) return null;
153
+ return matches.length === 1 ? matches[0]! : matches;
154
+ }
155
+
156
+ async acquireRun(id: string): Promise<{ agent: PrintAgent; token: string }> {
157
+ const existing = await this.getById(id);
158
+ if (!existing) throw new PrintAgentNotFoundError(id);
159
+ this.validateBoundCwd(existing.cwd);
160
+ const runLock = this.runLockPath(id);
161
+ let recoveredStale = false;
162
+
163
+ for (;;) {
164
+ this.ensureRunLocksRoot();
165
+ this.assertNotSymlink(runLock);
166
+ try {
167
+ fs.mkdirSync(runLock, { mode: 0o700 });
168
+ break;
169
+ } catch (error) {
170
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {
171
+ throw new PrintAgentStoreError(`Cannot acquire print-agent run lock: ${(error as Error).message}`);
172
+ }
173
+ const metadata = this.readRunLock(id);
174
+ if (!metadata || this.isActive(metadata)) {
175
+ throw new PrintAgentBusyError(id, existing.name);
176
+ }
177
+ const quarantine = `${runLock}.stale-${randomUUID()}`;
178
+ try {
179
+ fs.renameSync(runLock, quarantine);
180
+ this.removeLockDirectory(quarantine);
181
+ recoveredStale = true;
182
+ } catch {
183
+ // Another contender changed the lock. Retry and inspect the winner.
184
+ }
185
+ }
186
+ }
187
+
188
+ const owner = this.processInspector.getIdentity(process.pid);
189
+ if (!owner) {
190
+ this.removeLockDirectory(runLock);
191
+ throw new PrintAgentStoreError('Cannot determine the current process identity.');
192
+ }
193
+ const token = randomUUID();
194
+ const startedAt = this.now().toISOString();
195
+ const activeRun = { token, owner, provider: null, startedAt };
196
+ this.writeRunLock(id, activeRun);
197
+
198
+ try {
199
+ const agent = await this.updateAgent(id, (current) => ({
200
+ ...current,
201
+ state: 'running',
202
+ activeRun,
203
+ updatedAt: startedAt,
204
+ ...(recoveredStale ? {
205
+ sessionHealth: 'unknown' as const,
206
+ lastResult: {
207
+ status: 'interrupted' as const,
208
+ completedAt: startedAt,
209
+ exitCode: null,
210
+ summary: 'Previous print run was interrupted.',
211
+ },
212
+ } : {}),
213
+ }));
214
+ return { agent, token };
215
+ } catch (error) {
216
+ this.removeOwnedRunLock(id, token);
217
+ throw error;
218
+ }
219
+ }
220
+
221
+ async recordProviderProcess(id: string, token: string, identity: ProcessIdentity): Promise<void> {
222
+ const metadata = this.requireOwnedRun(id, token);
223
+ const next = { ...metadata, provider: identity };
224
+ this.writeRunLock(id, next);
225
+ await this.updateAgent(id, (agent) => {
226
+ if (agent.activeRun?.token !== token) throw new PrintAgentStoreError('Print run ownership changed.');
227
+ return { ...agent, activeRun: next, updatedAt: this.now().toISOString() };
228
+ });
229
+ }
230
+
231
+ async completeRun(id: string, token: string, result: PrintRunCompletion): Promise<PrintAgent> {
232
+ this.requireOwnedRun(id, token);
233
+ const completedAt = this.now().toISOString();
234
+ const agent = await this.updateAgent(id, (current) => {
235
+ if (current.activeRun?.token !== token) throw new PrintAgentStoreError('Print run ownership changed.');
236
+ return {
237
+ ...current,
238
+ state: result.status === 'succeeded' ? 'ready' : 'degraded',
239
+ sessionHealth: result.sessionHealth,
240
+ activeRun: null,
241
+ lastActiveAt: completedAt,
242
+ updatedAt: completedAt,
243
+ lastResult: {
244
+ status: result.status,
245
+ completedAt,
246
+ exitCode: result.exitCode,
247
+ summary: result.summary.slice(0, 4096),
248
+ },
249
+ };
250
+ });
251
+ this.removeOwnedRunLock(id, token);
252
+ return agent;
253
+ }
254
+
255
+ private canonicalDirectory(input: string): string {
256
+ try {
257
+ const resolved = fs.realpathSync(input);
258
+ if (!fs.statSync(resolved).isDirectory()) throw new Error('not a directory');
259
+ return resolved;
260
+ } catch {
261
+ throw new PrintAgentStoreError(`Print agent cwd is not an existing directory: ${input}`);
262
+ }
263
+ }
264
+
265
+ private validateBoundCwd(bound: string): void {
266
+ try {
267
+ const stat = fs.lstatSync(bound);
268
+ if (!stat.isDirectory() || stat.isSymbolicLink() || fs.realpathSync(bound) !== bound) {
269
+ throw new Error('binding changed');
270
+ }
271
+ } catch {
272
+ throw new PrintAgentStoreError(`Print agent cwd binding is no longer safe: ${bound}`);
273
+ }
274
+ }
275
+
276
+ private ensureSafeParent(): string {
277
+ const parent = path.dirname(this.filePath);
278
+ fs.mkdirSync(parent, { recursive: true, mode: 0o700 });
279
+ const stat = fs.lstatSync(parent);
280
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
281
+ throw new PrintAgentStoreError(`Unsafe print-agent store directory: ${parent}`);
282
+ }
283
+ return parent;
284
+ }
285
+
286
+ private ensureRunLocksRoot(): void {
287
+ this.ensureSafeParent();
288
+ fs.mkdirSync(this.runLocksRoot, { recursive: true, mode: 0o700 });
289
+ const stat = fs.lstatSync(this.runLocksRoot);
290
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
291
+ throw new PrintAgentStoreError(`Unsafe print-agent lock directory: ${this.runLocksRoot}`);
292
+ }
293
+ }
294
+
295
+ private assertNotSymlink(target: string): void {
296
+ try {
297
+ if (fs.lstatSync(target).isSymbolicLink()) {
298
+ throw new PrintAgentStoreError(`Unsafe symbolic link in print-agent storage: ${target}`);
299
+ }
300
+ } catch (error) {
301
+ if (error instanceof PrintAgentStoreError) throw error;
302
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
303
+ throw new PrintAgentStoreError(`Cannot inspect print-agent storage: ${target}`);
304
+ }
305
+ }
306
+ }
307
+
308
+ private readFile(): PrintAgentStoreFile {
309
+ this.ensureSafeParent();
310
+ this.assertNotSymlink(this.filePath);
311
+ if (!fs.existsSync(this.filePath)) return { version: 1, agents: [] };
312
+ try {
313
+ const parsed = JSON.parse(fs.readFileSync(this.filePath, 'utf8')) as unknown;
314
+ if (!this.isStoreFile(parsed)) throw new Error('invalid schema');
315
+ return parsed;
316
+ } catch {
317
+ throw new PrintAgentStoreError(`Invalid print-agent store: ${this.filePath}`);
318
+ }
319
+ }
320
+
321
+ private listRaw(): PrintAgent[] {
322
+ return this.readFile().agents.map((agent) => structuredClone(agent));
323
+ }
324
+
325
+ private isStoreFile(value: unknown): value is PrintAgentStoreFile {
326
+ if (!value || typeof value !== 'object') return false;
327
+ const record = value as Record<string, unknown>;
328
+ return record.version === 1 && Array.isArray(record.agents);
329
+ }
330
+
331
+ private writeFile(data: PrintAgentStoreFile): void {
332
+ const parent = this.ensureSafeParent();
333
+ this.assertNotSymlink(this.filePath);
334
+ const temp = path.join(parent, `.print-agents-${process.pid}-${randomUUID()}.tmp`);
335
+ this.assertNotSymlink(temp);
336
+ let fd: number | undefined;
337
+ try {
338
+ fd = fs.openSync(temp, 'wx', 0o600);
339
+ fs.writeFileSync(fd, JSON.stringify(data, null, 2), 'utf8');
340
+ fs.fsyncSync(fd);
341
+ fs.closeSync(fd);
342
+ fd = undefined;
343
+ fs.renameSync(temp, this.filePath);
344
+ fs.chmodSync(this.filePath, 0o600);
345
+ } catch (error) {
346
+ if (fd !== undefined) fs.closeSync(fd);
347
+ try { fs.unlinkSync(temp); } catch { /* best effort */ }
348
+ if (error instanceof PrintAgentStoreError) throw error;
349
+ throw new PrintAgentStoreError(`Failed to update print-agent store: ${(error as Error).message}`);
350
+ }
351
+ }
352
+
353
+ private async withMutationLock<T>(operation: () => Promise<T>): Promise<T> {
354
+ this.ensureSafeParent();
355
+ const started = Date.now();
356
+ for (;;) {
357
+ this.assertNotSymlink(this.lockPath);
358
+ try {
359
+ fs.mkdirSync(this.lockPath, { mode: 0o700 });
360
+ break;
361
+ } catch (error) {
362
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {
363
+ throw new PrintAgentStoreError(`Cannot acquire print-agent store lock: ${(error as Error).message}`);
364
+ }
365
+ if (!this.isYoungMutationLock()) {
366
+ const quarantine = `${this.lockPath}.stale-${randomUUID()}`;
367
+ try {
368
+ fs.renameSync(this.lockPath, quarantine);
369
+ fs.rmdirSync(quarantine);
370
+ continue;
371
+ } catch {
372
+ // Another contender changed the lock. Retry until the bounded timeout.
373
+ }
374
+ }
375
+ if (Date.now() - started >= this.lockTimeoutMs) {
376
+ throw new PrintAgentStoreError('Timed out acquiring print-agent store lock.');
377
+ }
378
+ await new Promise((resolve) => setTimeout(resolve, 10));
379
+ }
380
+ }
381
+ try {
382
+ return await operation();
383
+ } finally {
384
+ try { fs.rmdirSync(this.lockPath); } catch { /* surfaced by later contention */ }
385
+ }
386
+ }
387
+
388
+ private isYoungMutationLock(): boolean {
389
+ try {
390
+ this.assertNotSymlink(this.lockPath);
391
+ const stat = fs.statSync(this.lockPath);
392
+ return stat.isDirectory() && Date.now() - stat.mtimeMs < this.mutationLockStaleMs;
393
+ } catch {
394
+ return false;
395
+ }
396
+ }
397
+
398
+ private async updateAgent(id: string, update: (agent: PrintAgent) => PrintAgent): Promise<PrintAgent> {
399
+ return this.withMutationLock(async () => {
400
+ const data = this.readFile();
401
+ const index = data.agents.findIndex((agent) => agent.id === id);
402
+ if (index < 0) throw new PrintAgentNotFoundError(id);
403
+ const next = update(data.agents[index]!);
404
+ data.agents[index] = next;
405
+ this.writeFile(data);
406
+ return structuredClone(next);
407
+ });
408
+ }
409
+
410
+ private runLockPath(id: string): string {
411
+ if (!/^[0-9a-f-]{36}$/i.test(id)) throw new PrintAgentStoreError('Invalid print-agent id.');
412
+ return path.join(this.runLocksRoot, `${id}.lock`);
413
+ }
414
+
415
+ private readRunLock(id: string): import('./PrintAgent.js').PrintActiveRun | null {
416
+ const ownerPath = path.join(this.runLockPath(id), 'owner.json');
417
+ try {
418
+ this.assertNotSymlink(ownerPath);
419
+ const value = JSON.parse(fs.readFileSync(ownerPath, 'utf8')) as import('./PrintAgent.js').PrintActiveRun;
420
+ if (!value || typeof value.token !== 'string' || !value.owner || typeof value.owner.pid !== 'number') return null;
421
+ return value;
422
+ } catch {
423
+ return null;
424
+ }
425
+ }
426
+
427
+ private writeRunLock(id: string, metadata: import('./PrintAgent.js').PrintActiveRun): void {
428
+ const lockPath = this.runLockPath(id);
429
+ const ownerPath = path.join(lockPath, 'owner.json');
430
+ const tempPath = path.join(lockPath, `.owner-${randomUUID()}.tmp`);
431
+ this.assertNotSymlink(lockPath);
432
+ this.assertNotSymlink(ownerPath);
433
+ fs.writeFileSync(tempPath, JSON.stringify(metadata), { encoding: 'utf8', mode: 0o600, flag: 'wx' });
434
+ fs.renameSync(tempPath, ownerPath);
435
+ }
436
+
437
+ private requireOwnedRun(id: string, token: string): import('./PrintAgent.js').PrintActiveRun {
438
+ const metadata = this.readRunLock(id);
439
+ if (!metadata || metadata.token !== token) throw new PrintAgentStoreError('Print run ownership changed.');
440
+ return metadata;
441
+ }
442
+
443
+ private isActive(metadata: import('./PrintAgent.js').PrintActiveRun): boolean {
444
+ return this.sameProcess(metadata.owner) || (metadata.provider !== null && this.sameProcess(metadata.provider));
445
+ }
446
+
447
+ private sameProcess(expected: ProcessIdentity): boolean {
448
+ const actual = this.processInspector.getIdentity(expected.pid);
449
+ return actual !== null && actual.startedAt === expected.startedAt;
450
+ }
451
+
452
+ private isYoungLock(lockPath: string): boolean {
453
+ try {
454
+ this.assertNotSymlink(lockPath);
455
+ return Date.now() - fs.statSync(lockPath).mtimeMs < this.incompleteLockGraceMs;
456
+ } catch {
457
+ return false;
458
+ }
459
+ }
460
+
461
+ private removeOwnedRunLock(id: string, token: string): void {
462
+ const metadata = this.readRunLock(id);
463
+ if (!metadata || metadata.token !== token) return;
464
+ this.removeLockDirectory(this.runLockPath(id));
465
+ }
466
+
467
+ private removeLockDirectory(lockPath: string): void {
468
+ this.assertNotSymlink(lockPath);
469
+ try {
470
+ for (const name of fs.readdirSync(lockPath)) {
471
+ const entry = path.join(lockPath, name);
472
+ this.assertNotSymlink(entry);
473
+ if (!fs.lstatSync(entry).isFile()) throw new PrintAgentStoreError(`Unsafe entry in print-agent lock: ${entry}`);
474
+ fs.unlinkSync(entry);
475
+ }
476
+ fs.rmdirSync(lockPath);
477
+ } catch (error) {
478
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
479
+ }
480
+ }
481
+ }
482
+
483
+ export class LocalProcessInspector implements ProcessInspector {
484
+ getIdentity(pid: number): ProcessIdentity | null {
485
+ if (!Number.isInteger(pid) || pid <= 0) return null;
486
+ try {
487
+ if (process.platform === 'linux') {
488
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
489
+ const close = stat.lastIndexOf(')');
490
+ const fields = stat.slice(close + 2).split(' ');
491
+ const startTicks = fields[19];
492
+ if (!startTicks) return null;
493
+ return { pid, startedAt: `linux:${startTicks}` };
494
+ }
495
+ const startedAt = execFileSync('ps', ['-o', 'lstart=', '-p', String(pid)], {
496
+ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'],
497
+ }).trim();
498
+ return startedAt ? { pid, startedAt } : null;
499
+ } catch {
500
+ return null;
501
+ }
502
+ }
503
+ }
@@ -41,7 +41,7 @@ export class TmuxManager {
41
41
  /**
42
42
  * Find the actual agent process PID inside a tmux pane.
43
43
  *
44
- * Strategy: BFS the process tree, return the deepest descendant whose
44
+ * Strategy: BFS the process tree, return the deepest process whose
45
45
  * `ps` command line is accepted by `matches`. The caller supplies the
46
46
  * matcher so this method has no agent-type knowledge.
47
47
  *
@@ -51,7 +51,7 @@ export class TmuxManager {
51
51
  * - Subprocess case: shell → claude (matches) → MCP server child (doesn't match)
52
52
  * → returns claude, not the subprocess
53
53
  *
54
- * Returns null when no descendant matches yet (agent still starting); the
54
+ * Returns null when no process matches yet (agent still starting); the
55
55
  * caller's poll loop retries.
56
56
  */
57
57
  async findAgentPid(session: string, matches: (psCommand: string) => boolean): Promise<number | null> {
@@ -67,11 +67,9 @@ export class TmuxManager {
67
67
  if (visited.has(pid)) continue;
68
68
  visited.add(pid);
69
69
 
70
- if (pid !== panePid) {
71
- const command = await this.getProcessCommand(pid);
72
- if (command && matches(command)) {
73
- deepestMatch = pid;
74
- }
70
+ const command = await this.getProcessCommand(pid);
71
+ if (command && matches(command)) {
72
+ deepestMatch = pid;
75
73
  }
76
74
 
77
75
  const children = await this.pgrepChildren(pid);