Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions packages/agent-manager/src/harnesses/codex/CodexAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
];
Expand Down Expand Up @@ -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) {
Expand All @@ -262,7 +265,7 @@ export class CodexAdapter implements AgentAdapter {
}
}

return { agents, fallback };
return { agents, fallback, ephemeral };
}

private mapRegistryCache(processes: ProcessInfo[]): MappedAgentResult {
Expand Down
12 changes: 10 additions & 2 deletions packages/agent-manager/src/harnesses/codex/CodexSessionMapping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export interface CodexSessionMappingOptions {
sessionsDir?: string;
}

export const EPHEMERAL_SESSION_MARKER = "ephemeral";

export interface CodexSessionMappingMatch {
process: ProcessInfo;
filePath: string;
Expand All @@ -17,6 +19,7 @@ export interface CodexSessionMappingMatch {
export interface CodexSessionMappingResult {
matches: CodexSessionMappingMatch[];
fallback: ProcessInfo[];
ephemeral: ProcessInfo[];
}

export class CodexSessionMapping {
Expand All @@ -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;
Expand All @@ -46,7 +54,7 @@ export class CodexSessionMapping {
matches.push({ process: processInfo, filePath });
}

return { matches, fallback };
return { matches, fallback, ephemeral };
}

private read(): Map<number, string> {
Expand Down
9 changes: 6 additions & 3 deletions packages/agent-manager/src/harnesses/pi/PiAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
];
}
Expand Down Expand Up @@ -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(
Expand Down
12 changes: 10 additions & 2 deletions packages/agent-manager/src/harnesses/pi/PiSessionTracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -12,6 +14,7 @@ export interface PiTrackerMatch {
export interface PiTrackerMatchResult {
matches: PiTrackerMatch[];
fallback: ProcessInfo[];
ephemeral: ProcessInfo[];
}

export interface PiSessionTrackerOptions {
Expand All @@ -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;
Expand All @@ -46,7 +54,7 @@ export class PiSessionTracker {
matches.push({ process: processInfo, filePath });
}

return { matches, fallback };
return { matches, fallback, ephemeral };
}

private readTracker(): Map<number, string> {
Expand Down
49 changes: 49 additions & 0 deletions packages/agent-manager/tests/harnesses/codex/CodexAdapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ describe("CodexSessionMapping", () => {
expect(createMapping().match([processInfo])).toEqual({
matches: [{ process: processInfo, filePath: sessionFile }],
fallback: [],
ephemeral: [],
});
});

Expand All @@ -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],
});
});

Expand Down
46 changes: 46 additions & 0 deletions packages/agent-manager/tests/harnesses/pi/PiAdapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
14 changes: 14 additions & 0 deletions packages/agent-manager/tests/harnesses/pi/PiSessionTracker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ describe("PiSessionTracker", () => {
expect(tracker.match([proc])).toEqual({
matches: [{ process: proc, filePath: sessionFile }],
fallback: [],
ephemeral: [],
});
});

Expand All @@ -41,6 +42,7 @@ describe("PiSessionTracker", () => {
expect(tracker.match([proc])).toEqual({
matches: [],
fallback: [proc],
ephemeral: [],
});
});

Expand All @@ -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],
});
});

Expand Down
Loading