From 78f096f69e815ed81e5b566a6e2df0474fa01f03 Mon Sep 17 00:00:00 2001 From: MugunthPerumal Date: Fri, 4 Dec 2026 09:18:46 +0530 Subject: [PATCH] fix(agent-manager): treat ephemeral session markers as authoritative --- .../src/harnesses/codex/CodexAdapter.ts | 9 +- .../harnesses/codex/CodexSessionMapping.ts | 12 ++- .../src/harnesses/pi/PiAdapter.ts | 9 +- .../src/harnesses/pi/PiSessionTracker.ts | 12 ++- .../harnesses/codex/CodexAdapter.test.ts | 49 ++++++++++ .../codex/CodexSessionMapping.test.ts | 14 +++ .../tests/harnesses/pi/PiAdapter.test.ts | 46 +++++++++ .../harnesses/pi/PiSessionTracker.test.ts | 14 +++ rust/crates/devkit-harness/src/codex/mod.rs | 96 +++++++++++++++++-- rust/crates/devkit-harness/src/pi/mod.rs | 85 +++++++++++++++- 10 files changed, 321 insertions(+), 25 deletions(-) diff --git a/packages/agent-manager/src/harnesses/codex/CodexAdapter.ts b/packages/agent-manager/src/harnesses/codex/CodexAdapter.ts index fe27a2543..9e65c0879 100644 --- a/packages/agent-manager/src/harnesses/codex/CodexAdapter.ts +++ b/packages/agent-manager/src/harnesses/codex/CodexAdapter.ts @@ -202,6 +202,7 @@ export class CodexAdapter implements AgentAdapter { ...cacheResult.agents, ...directResult.agents, ...legacyResult.agents, + ...mappingResult.ephemeral.map((processInfo) => this.mapper.mapProcessOnlyAgent(processInfo)), ...directResult.fallback.map((processInfo) => this.mapper.mapProcessOnlyAgent(processInfo)), ...unmatchedProcesses.map((processInfo) => this.mapper.mapProcessOnlyAgent(processInfo)), ]; @@ -249,8 +250,10 @@ export class CodexAdapter implements AgentAdapter { }); } - private mapSessionMappingMatches(processes: ProcessInfo[]): MappedAgentResult { - const { matches, fallback } = this.createSessionMapping().match(processes); + private mapSessionMappingMatches( + processes: ProcessInfo[], + ): MappedAgentResult & { ephemeral: ProcessInfo[] } { + const { matches, fallback, ephemeral } = this.createSessionMapping().match(processes); const agents: AgentInfo[] = []; for (const match of matches) { @@ -262,7 +265,7 @@ export class CodexAdapter implements AgentAdapter { } } - return { agents, fallback }; + return { agents, fallback, ephemeral }; } private mapRegistryCache(processes: ProcessInfo[]): MappedAgentResult { diff --git a/packages/agent-manager/src/harnesses/codex/CodexSessionMapping.ts b/packages/agent-manager/src/harnesses/codex/CodexSessionMapping.ts index c14278b12..b19450616 100644 --- a/packages/agent-manager/src/harnesses/codex/CodexSessionMapping.ts +++ b/packages/agent-manager/src/harnesses/codex/CodexSessionMapping.ts @@ -9,6 +9,8 @@ export interface CodexSessionMappingOptions { sessionsDir?: string; } +export const EPHEMERAL_SESSION_MARKER = "ephemeral"; + export interface CodexSessionMappingMatch { process: ProcessInfo; filePath: string; @@ -17,6 +19,7 @@ export interface CodexSessionMappingMatch { export interface CodexSessionMappingResult { matches: CodexSessionMappingMatch[]; fallback: ProcessInfo[]; + ephemeral: ProcessInfo[]; } export class CodexSessionMapping { @@ -31,13 +34,18 @@ export class CodexSessionMapping { match(processes: ProcessInfo[]): CodexSessionMappingResult { const mapping = this.read(); - if (mapping.size === 0) return { matches: [], fallback: processes }; + if (mapping.size === 0) return { matches: [], fallback: processes, ephemeral: [] }; const matches: CodexSessionMappingMatch[] = []; const fallback: ProcessInfo[] = []; + const ephemeral: ProcessInfo[] = []; for (const processInfo of processes) { const filePath = mapping.get(processInfo.pid); + if (filePath === EPHEMERAL_SESSION_MARKER) { + ephemeral.push(processInfo); + continue; + } if (!filePath || !this.isTrustedSessionPath(filePath) || !fs.existsSync(filePath)) { fallback.push(processInfo); continue; @@ -46,7 +54,7 @@ export class CodexSessionMapping { matches.push({ process: processInfo, filePath }); } - return { matches, fallback }; + return { matches, fallback, ephemeral }; } private read(): Map { diff --git a/packages/agent-manager/src/harnesses/pi/PiAdapter.ts b/packages/agent-manager/src/harnesses/pi/PiAdapter.ts index b53a99acc..7760b14a9 100644 --- a/packages/agent-manager/src/harnesses/pi/PiAdapter.ts +++ b/packages/agent-manager/src/harnesses/pi/PiAdapter.ts @@ -85,6 +85,7 @@ export class PiAdapter implements AgentAdapter { ...trackerResult.agents, ...cacheResult.agents, ...legacyResult.agents, + ...trackerResult.ephemeral.map((processInfo) => this.mapper.mapProcessOnlyAgent(processInfo)), ...unmatchedProcesses.map((processInfo) => this.mapper.mapProcessOnlyAgent(processInfo)), ]; } @@ -157,10 +158,12 @@ export class PiAdapter implements AgentAdapter { return { agents: mapped.agents, fallback: [...fallback, ...mapped.fallback] }; } - private mapTrackerMatches(processes: ProcessInfo[]): MappedAgentResult { - const { matches, fallback } = this.createTracker().match(processes); + private mapTrackerMatches( + processes: ProcessInfo[], + ): MappedAgentResult & { ephemeral: ProcessInfo[] } { + const { matches, fallback, ephemeral } = this.createTracker().match(processes); const mapped = this.mapSessionFileMatches(matches); - return { agents: mapped.agents, fallback: [...fallback, ...mapped.fallback] }; + return { agents: mapped.agents, fallback: [...fallback, ...mapped.fallback], ephemeral }; } private mapLegacyMatches( diff --git a/packages/agent-manager/src/harnesses/pi/PiSessionTracker.ts b/packages/agent-manager/src/harnesses/pi/PiSessionTracker.ts index 291d1cc94..602c35045 100644 --- a/packages/agent-manager/src/harnesses/pi/PiSessionTracker.ts +++ b/packages/agent-manager/src/harnesses/pi/PiSessionTracker.ts @@ -4,6 +4,8 @@ import type { ProcessInfo } from "../../adapters/AgentAdapter.js"; import { safeReadFile } from "../../utils/session.js"; import { homeDir } from "../shared.js"; +export const EPHEMERAL_SESSION_MARKER = "ephemeral"; + export interface PiTrackerMatch { process: ProcessInfo; filePath: string; @@ -12,6 +14,7 @@ export interface PiTrackerMatch { export interface PiTrackerMatchResult { matches: PiTrackerMatch[]; fallback: ProcessInfo[]; + ephemeral: ProcessInfo[]; } export interface PiSessionTrackerOptions { @@ -31,13 +34,18 @@ export class PiSessionTracker { match(processes: ProcessInfo[]): PiTrackerMatchResult { const tracker = this.readTracker(); - if (tracker.size === 0) return { matches: [], fallback: processes }; + if (tracker.size === 0) return { matches: [], fallback: processes, ephemeral: [] }; const matches: PiTrackerMatch[] = []; const fallback: ProcessInfo[] = []; + const ephemeral: ProcessInfo[] = []; for (const processInfo of processes) { const filePath = tracker.get(processInfo.pid); + if (filePath === EPHEMERAL_SESSION_MARKER) { + ephemeral.push(processInfo); + continue; + } if (!filePath || !this.isTrustedSessionPath(filePath) || !fs.existsSync(filePath)) { fallback.push(processInfo); continue; @@ -46,7 +54,7 @@ export class PiSessionTracker { matches.push({ process: processInfo, filePath }); } - return { matches, fallback }; + return { matches, fallback, ephemeral }; } private readTracker(): Map { diff --git a/packages/agent-manager/tests/harnesses/codex/CodexAdapter.test.ts b/packages/agent-manager/tests/harnesses/codex/CodexAdapter.test.ts index 4d1664af4..abac422be 100644 --- a/packages/agent-manager/tests/harnesses/codex/CodexAdapter.test.ts +++ b/packages/agent-manager/tests/harnesses/codex/CodexAdapter.test.ts @@ -542,6 +542,55 @@ describe("CodexAdapter", () => { expect(mockedMatchProcessesToSessions).not.toHaveBeenCalled(); }); + it("treats an ephemeral hook mapping entry as authoritative and skips stale registry and fallback", async () => { + const registry = new AgentRegistry(path.join(tmpHome, "agents.json")); + const staleSession = path.join(tmpHome, "stale-ephemeral.jsonl"); + fs.writeFileSync( + staleSession, + [ + JSON.stringify({ + type: "session_meta", + payload: { id: "stale", timestamp: new Date().toISOString(), cwd: "/repo-stale" }, + }), + JSON.stringify({ + type: "event", + timestamp: new Date().toISOString(), + payload: { type: "agent_message", message: "stale" }, + }), + ].join("\n"), + ); + registry.register(registryEntry({ sessionFilePath: staleSession })); + + const mappedAdapter = new CodexAdapter(registry); + fs.mkdirSync(path.join(tmpHome, ".codex", "ai-devkit"), { recursive: true }); + fs.writeFileSync( + path.join(tmpHome, ".codex", "ai-devkit", "sessions.json"), + JSON.stringify({ 100: "ephemeral" }), + ); + + mockedListAgentProcesses.mockReturnValue([ + { + pid: 100, + command: "codex --ephemeral", + cwd: "/repo-current", + tty: "ttys001", + startTime: new Date(), + }, + ]); + + const agents = await mappedAdapter.detectAgents(); + + expect(agents).toHaveLength(1); + expect(agents[0]).toMatchObject({ + type: "codex", + pid: 100, + }); + expect(agents[0]?.sessionFilePath).toBeUndefined(); + expect(agents[0]?.sessionId).toBe("pid-100"); + expect(mockedBatchGetSessionFileBirthtimes).not.toHaveBeenCalled(); + expect(mockedMatchProcessesToSessions).not.toHaveBeenCalled(); + }); + it("uses a valid registry cache entry before scanning sessions", async () => { const registry = new AgentRegistry(path.join(tmpHome, "agents.json")); const { sessionFile } = writeSession("cached", "/repo-a", [ diff --git a/packages/agent-manager/tests/harnesses/codex/CodexSessionMapping.test.ts b/packages/agent-manager/tests/harnesses/codex/CodexSessionMapping.test.ts index 076570092..8cd362d4c 100644 --- a/packages/agent-manager/tests/harnesses/codex/CodexSessionMapping.test.ts +++ b/packages/agent-manager/tests/harnesses/codex/CodexSessionMapping.test.ts @@ -31,6 +31,7 @@ describe("CodexSessionMapping", () => { expect(createMapping().match([processInfo])).toEqual({ matches: [{ process: processInfo, filePath: sessionFile }], fallback: [], + ephemeral: [], }); }); @@ -48,12 +49,25 @@ describe("CodexSessionMapping", () => { expect(createMapping().match([processInfo])).toEqual({ matches: [], fallback: [processInfo], + ephemeral: [], }); fs.writeFileSync(mappingPath, "{not-json"); expect(createMapping().match([processInfo])).toEqual({ matches: [], fallback: [processInfo], + ephemeral: [], + }); + }); + + it("treats ephemeral mapping entries as authoritative and excludes them from fallback", () => { + fs.mkdirSync(path.dirname(mappingPath), { recursive: true }); + fs.writeFileSync(mappingPath, JSON.stringify({ 5151: "ephemeral" })); + + expect(createMapping().match([processInfo])).toEqual({ + matches: [], + fallback: [], + ephemeral: [processInfo], }); }); diff --git a/packages/agent-manager/tests/harnesses/pi/PiAdapter.test.ts b/packages/agent-manager/tests/harnesses/pi/PiAdapter.test.ts index 76d183489..d9e1cf2b0 100644 --- a/packages/agent-manager/tests/harnesses/pi/PiAdapter.test.ts +++ b/packages/agent-manager/tests/harnesses/pi/PiAdapter.test.ts @@ -386,6 +386,52 @@ describe("PiAdapter", () => { ); return filePath; } + + it("treats an ephemeral tracker entry as authoritative and skips stale registry and fallback", async () => { + const staleRegistry = new AgentRegistry(path.join(tmpHome, "agents.json")); + const staleFile = writePiSessionWithFileName("/repo-a", "stale.jsonl", [ + { + type: "session", + id: "stale-sess", + timestamp: "2026-11-12T09:00:00.000Z", + cwd: "/repo-a", + }, + { + type: "message", + timestamp: "2026-11-12T09:00:01.000Z", + message: { role: "user", content: "stale prompt" }, + }, + ]); + staleRegistry.register({ + name: "pi-100", + type: "pi", + pid: 100, + runtime: "tmux", + runtimeRef: null, + cwd: "/repo-a", + startedAt: "2026-05-30T00:00:00.000Z", + sessionId: "stale-sess", + sessionFilePath: staleFile, + pinned: false, + }); + + const ephemeralAdapter = new PiAdapter(staleRegistry); + writeTracker({ 100: "ephemeral" }); + + const proc = makeProcess({ pid: 100, command: "pi --no-session", cwd: "/repo-a" }); + mockedCaptureProcessSnapshot.mockResolvedValue([proc]); + + const agents = await ephemeralAdapter.detectAgents(); + + expect(agents).toHaveLength(1); + expect(agents[0]).toMatchObject({ + type: "pi", + pid: 100, + }); + expect(agents[0]?.sessionFilePath).toBeUndefined(); + expect(agents[0]?.sessionId).toBe("pid-100"); + expect(mockedMatchProcessesToSessions).not.toHaveBeenCalled(); + }); }); function encodeProjectDir(cwd: string): string { diff --git a/packages/agent-manager/tests/harnesses/pi/PiSessionTracker.test.ts b/packages/agent-manager/tests/harnesses/pi/PiSessionTracker.test.ts index b699a8b3c..e02f96b6d 100644 --- a/packages/agent-manager/tests/harnesses/pi/PiSessionTracker.test.ts +++ b/packages/agent-manager/tests/harnesses/pi/PiSessionTracker.test.ts @@ -31,6 +31,7 @@ describe("PiSessionTracker", () => { expect(tracker.match([proc])).toEqual({ matches: [{ process: proc, filePath: sessionFile }], fallback: [], + ephemeral: [], }); }); @@ -41,6 +42,7 @@ describe("PiSessionTracker", () => { expect(tracker.match([proc])).toEqual({ matches: [], fallback: [proc], + ephemeral: [], }); }); @@ -53,6 +55,18 @@ describe("PiSessionTracker", () => { expect(tracker.match([proc])).toEqual({ matches: [], fallback: [proc], + ephemeral: [], + }); + }); + + it("treats ephemeral tracker entries as authoritative and excludes them from fallback", () => { + const proc = makeProcess({ pid: 505 }); + writeTracker({ 505: "ephemeral" }); + + expect(tracker.match([proc])).toEqual({ + matches: [], + fallback: [], + ephemeral: [proc], }); }); diff --git a/rust/crates/devkit-harness/src/codex/mod.rs b/rust/crates/devkit-harness/src/codex/mod.rs index 4d38e282c..c6eb73ef8 100644 --- a/rust/crates/devkit-harness/src/codex/mod.rs +++ b/rust/crates/devkit-harness/src/codex/mod.rs @@ -161,6 +161,8 @@ fn is_variadic_flag_value(arg: &str) -> bool { !arg.starts_with('-') && !CODEX_SUBCOMMANDS.contains(&arg) } +const EPHEMERAL_SESSION_MARKER: &str = "ephemeral"; + /// `~/.codex/ai-devkit/sessions.json` — pid→session filePath written by the /// CLI when it launches managed codex sessions. struct SessionMapping { @@ -169,22 +171,30 @@ struct SessionMapping { } impl SessionMapping { - fn match_processes<'a>(&self, processes: &[&'a AgentProc]) -> Vec<(&'a AgentProc, String)> { + fn match_processes<'a>( + &self, + processes: &[&'a AgentProc], + ) -> (Vec<(&'a AgentProc, String)>, Vec<&'a AgentProc>) { let mapping = self.read(); if mapping.is_empty() { - return Vec::new(); + return (Vec::new(), Vec::new()); } let mut out = Vec::new(); + let mut ephemeral = Vec::new(); for &proc in processes { let Some(file_path) = mapping.get(&proc.pid) else { continue; }; + if file_path == EPHEMERAL_SESSION_MARKER { + ephemeral.push(proc); + continue; + } if !self.is_trusted(file_path) || !Path::new(file_path).exists() { continue; } out.push((proc, file_path.clone())); } - out + (out, ephemeral) } fn read(&self) -> HashMap { @@ -317,13 +327,15 @@ impl HarnessAdapter for CodexAdapter { .join("sessions.json"), sessions_dir: self.sessions_dir.clone(), }; - let mapped: HashMap = mapping - .match_processes(&procs) - .into_iter() - .map(|(p, f)| (p.pid, f)) - .collect(); + let (mapped_pairs, ephemeral_procs) = mapping.match_processes(&procs); + let mapped: HashMap = + mapped_pairs.into_iter().map(|(p, f)| (p.pid, f)).collect(); + let ephemeral_pids: HashSet = ephemeral_procs.iter().map(|p| p.pid).collect(); let mut fallback: Vec<&AgentProc> = Vec::new(); for &proc in &procs { + if ephemeral_pids.contains(&proc.pid) { + continue; + } match mapped.get(&proc.pid) { Some(file_path) => match parser::read_session(file_path) { Some(session) => { @@ -380,9 +392,13 @@ impl HarnessAdapter for CodexAdapter { } } - // 4. process-only: direct parse failures, then locator survivors. + // 4. process-only: ephemeral mapping entries, direct parse failures, then locator survivors. // `matches.fallback` excludes every proc that produced a direct match. - for &proc in direct_fallback.iter().chain(matches.fallback.iter()) { + for &proc in ephemeral_procs + .iter() + .chain(direct_fallback.iter()) + .chain(matches.fallback.iter()) + { if done_pids.contains(&proc.pid) { continue; } @@ -442,6 +458,66 @@ mod tests { assert!(!is_helper_command("codex --image a.png b.png foo")); } + #[test] + fn ephemeral_mapping_entry_skips_stale_registry_and_session_scan() { + let home = + std::env::temp_dir().join(format!("aidk-codex-ephemeral-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&home); + let stale = home.join(".codex/sessions/2026/03/18/stale.jsonl"); + std::fs::create_dir_all(stale.parent().unwrap()).unwrap(); + std::fs::write( + &stale, + format!( + "{}\n{}\n", + serde_json::json!({"type":"session_meta","payload":{"id":"sess-old","timestamp":"2026-03-18T15:00:00Z","cwd":"/repo"}}), + serde_json::json!({"type":"event","timestamp":"2026-03-18T15:00:01Z","payload":{"type":"agent_message","message":"old session"}}), + ), + ) + .unwrap(); + let mapping = home.join(".codex/ai-devkit/sessions.json"); + std::fs::create_dir_all(mapping.parent().unwrap()).unwrap(); + std::fs::write( + &mapping, + serde_json::json!({"4242": EPHEMERAL_SESSION_MARKER}).to_string(), + ) + .unwrap(); + let db = home.join(".ai-devkit/agents.db"); + std::fs::create_dir_all(db.parent().unwrap()).unwrap(); + let conn = rusqlite::Connection::open(&db).unwrap(); + conn.execute_batch( + "CREATE TABLE agents (type TEXT NOT NULL, pid INTEGER NOT NULL, name TEXT NOT NULL, + session_file_path TEXT NOT NULL DEFAULT '', started_at TEXT NOT NULL DEFAULT '');", + ) + .unwrap(); + conn.execute( + "INSERT INTO agents (type,pid,name,session_file_path) VALUES ('codex',4242,'codex-a',?1)", + [stale.to_string_lossy()], + ) + .unwrap(); + drop(conn); + + let procs = vec![AgentProc { + pid: 4242, + ppid: Some(1), + tty: None, + command: Some("codex --ephemeral".into()), + cwd: Some("/repo".into()), + session_file: None, + start_time_ms: None, + }]; + let adapter = CodexAdapter::new(&home); + let out = adapter.detect(&SweepContext { + processes: &procs, + now: 0, + home: &home, + }); + assert_eq!(out.len(), 1); + assert_eq!(out[0].pid, 4242); + assert_eq!(out[0].session_id, "pid-4242"); + assert_eq!(out[0].session_file_path, None); + let _ = std::fs::remove_dir_all(&home); + } + #[test] fn pid_parsing() { assert_eq!(to_pid_json("123"), Some(123)); diff --git a/rust/crates/devkit-harness/src/pi/mod.rs b/rust/crates/devkit-harness/src/pi/mod.rs index 4fb09381e..f5d5b990f 100644 --- a/rust/crates/devkit-harness/src/pi/mod.rs +++ b/rust/crates/devkit-harness/src/pi/mod.rs @@ -22,6 +22,8 @@ fn is_pi_executable(command: &str) -> bool { }) } +const EPHEMERAL_SESSION_MARKER: &str = "ephemeral"; + /// `~/.pi/agent/sessions.json` — pid→session filePath written when the CLI /// launches managed pi sessions. struct SessionTracker { @@ -33,22 +35,30 @@ impl SessionTracker { fn match_processes<'a>( &self, processes: &[&'a AgentProc], - ) -> (Vec<(&'a AgentProc, String)>, Vec<&'a AgentProc>) { + ) -> ( + Vec<(&'a AgentProc, String)>, + Vec<&'a AgentProc>, + Vec<&'a AgentProc>, + ) { let tracker = self.read(); let mut matches = Vec::new(); + let mut ephemeral = Vec::new(); let mut fallback = Vec::new(); if tracker.is_empty() { - return (matches, processes.to_vec()); + return (matches, ephemeral, processes.to_vec()); } for &proc in processes { match tracker.get(&proc.pid) { + Some(file_path) if file_path == EPHEMERAL_SESSION_MARKER => { + ephemeral.push(proc); + } Some(file_path) if self.is_trusted(file_path) && Path::new(file_path).exists() => { matches.push((proc, file_path.clone())); } _ => fallback.push(proc), } } - (matches, fallback) + (matches, ephemeral, fallback) } fn read(&self) -> HashMap { @@ -202,7 +212,8 @@ impl HarnessAdapter for PiAdapter { tracker_path: self.home.join(".pi").join("agent").join("sessions.json"), sessions_dir: self.sessions_dir.clone(), }; - let (tracker_matches, tracker_fallback) = tracker.match_processes(&procs); + let (tracker_matches, tracker_ephemeral, tracker_fallback) = + tracker.match_processes(&procs); let (tracker_agents, tracker_parse_fail, _) = self.map_file_matches(&tracker_matches, ctx.now); agents.extend(tracker_agents); @@ -235,7 +246,16 @@ impl HarnessAdapter for PiAdapter { let (legacy_agents, _, legacy_matched) = self.map_file_matches(&legacy_pairs, ctx.now); agents.extend(legacy_agents); - // 4. process-only for locator survivors not legacy-matched + // 4. process-only for ephemeral tracker matches and locator survivors not legacy-matched + for &proc in &tracker_ephemeral { + agents.push(shared::process_only_agent( + "pi", + proc, + "Pi process running", + None, + ctx.now, + )); + } for &proc in &locator_fallback { if legacy_matched.contains(&proc.pid) { continue; @@ -330,6 +350,61 @@ mod tests { let _ = std::fs::remove_dir_all(&home); } + #[test] + fn ephemeral_tracker_entry_skips_stale_registry_and_session_scan() { + let home = std::env::temp_dir().join(format!("aidk-pi-ephemeral-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&home); + let dir = home.join(".pi/agent/sessions/--repo--"); + let stale = dir.join("stale.jsonl"); + write( + &stale, + &format!( + "{}\n{}\n", + serde_json::json!({"type":"session","id":"sess-old","timestamp":"2026-11-12T09:00:00.000Z","cwd":"/repo"}), + serde_json::json!({"type":"message","timestamp":"2026-11-12T09:00:01.000Z","message":{"role":"user","content":"old session"}}), + ), + ); + write( + &home.join(".pi/agent/sessions.json"), + &serde_json::json!({"4242": EPHEMERAL_SESSION_MARKER}).to_string(), + ); + let db = home.join(".ai-devkit/agents.db"); + std::fs::create_dir_all(db.parent().unwrap()).unwrap(); + let conn = rusqlite::Connection::open(&db).unwrap(); + conn.execute_batch( + "CREATE TABLE agents (type TEXT NOT NULL, pid INTEGER NOT NULL, name TEXT NOT NULL, + session_file_path TEXT NOT NULL DEFAULT '', started_at TEXT NOT NULL DEFAULT '');", + ) + .unwrap(); + conn.execute( + "INSERT INTO agents (type,pid,name,session_file_path) VALUES ('pi',4242,'pi-a',?1)", + [stale.to_string_lossy()], + ) + .unwrap(); + drop(conn); + + let procs = vec![AgentProc { + pid: 4242, + ppid: Some(1), + tty: None, + command: Some("pi --no-session".into()), + cwd: Some("/repo".into()), + session_file: None, + start_time_ms: None, + }]; + let adapter = PiAdapter::new(&home); + let out = adapter.detect(&SweepContext { + processes: &procs, + now: 0, + home: &home, + }); + assert_eq!(out.len(), 1); + assert_eq!(out[0].pid, 4242); + assert_eq!(out[0].session_id, "pid-4242"); + assert_eq!(out[0].session_file_path, None); + let _ = std::fs::remove_dir_all(&home); + } + #[test] fn pid_parsing() { assert_eq!(to_pid("42"), Some(42));