Skip to content

Commit 88fb786

Browse files
Add codex adapter (#28)
* docs(ai): add codex adapter agent-manager lifecycle docs * feat(agent-manager): improve codex process-session matching * refactor(agent-manager): simplify codex matching flow * test(agent-manager): extend codex adapter matching coverage * docs(ai): finalize phase 7 and 8 for codex adapter feature
1 parent 425f317 commit 88fb786

File tree

11 files changed

+1413
-1
lines changed

11 files changed

+1413
-1
lines changed
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
---
2+
phase: design
3+
title: "Codex Adapter in @ai-devkit/agent-manager - Design"
4+
feature: codex-adapter-agent-manager-package
5+
description: Architecture and implementation design for introducing Codex adapter support in the shared agent manager package
6+
---
7+
8+
# Design: Codex Adapter for @ai-devkit/agent-manager
9+
10+
## Architecture Overview
11+
12+
```mermaid
13+
graph TD
14+
User[User runs ai-devkit agent list/open] --> Cmd[packages/cli/src/commands/agent.ts]
15+
Cmd --> Manager[AgentManager]
16+
17+
subgraph Pkg[@ai-devkit/agent-manager]
18+
Manager --> Claude[ClaudeCodeAdapter]
19+
Manager --> Codex[CodexAdapter]
20+
Codex --> Proc[process utils]
21+
Codex --> File[file utils]
22+
Codex --> Types[AgentAdapter/AgentInfo/AgentStatus]
23+
Focus[TerminalFocusManager]
24+
end
25+
26+
Cmd --> Focus
27+
Cmd --> Output[CLI table/json rendering]
28+
```
29+
30+
Responsibilities:
31+
- `CodexAdapter`: discover and map running Codex sessions to `AgentInfo`
32+
- `AgentManager`: aggregate Codex + existing adapter results
33+
- CLI command: register adapters, display results, and invoke open/focus behavior
34+
35+
## Data Models
36+
37+
- Reuse existing `AgentAdapter`, `AgentInfo`, `AgentStatus`, and `AgentType` models
38+
- `AgentType` already supports `codex`; adapter emits `type: 'codex'`
39+
- Codex raw metadata (internal to adapter) is normalized into:
40+
- `id`: deterministic session/process identifier
41+
- `name`: user-facing label derived from `cwd`; fallback to `codex-<session-id-prefix>` when `cwd` is missing
42+
- `cwd`: workspace path (if available)
43+
- `sessionStart`: parsed from `session_meta.timestamp` for process/session time matching
44+
- `status`: computed from recency/activity metadata using the same threshold values already used by existing adapters
45+
- `pid`: matched running Codex process id used by terminal focus flow
46+
47+
## API Design
48+
49+
### Package Exports
50+
- Add `CodexAdapter` to:
51+
- `packages/agent-manager/src/adapters/index.ts`
52+
- `packages/agent-manager/src/index.ts`
53+
54+
### CLI Integration
55+
- Update `packages/cli/src/commands/agent.ts` to register `CodexAdapter` alongside `ClaudeCodeAdapter`
56+
- Keep display mapping logic in CLI; do not move presentation concerns into package
57+
58+
## Component Breakdown
59+
60+
1. `packages/agent-manager/src/adapters/CodexAdapter.ts`
61+
- Implement adapter contract methods/properties
62+
- Discover Codex sessions from `~/.codex/sessions/YYYY/MM/DD/*.jsonl`
63+
- Map session data to standardized `AgentInfo`
64+
65+
2. `packages/agent-manager/src/__tests__/adapters/CodexAdapter.test.ts`
66+
- Unit tests for detection/parsing/status mapping/error handling
67+
68+
3. `packages/agent-manager/src/adapters/index.ts` and `src/index.ts`
69+
- Export adapter class
70+
71+
4. `packages/cli/src/commands/agent.ts`
72+
- Register Codex adapter in manager setup path(s)
73+
74+
## Design Decisions
75+
76+
- Decision: Implement Codex detection in package, not CLI.
77+
- Rationale: preserves package as the single source of truth for agent discovery.
78+
- Decision: Reuse existing adapter contract and manager aggregation flow.
79+
- Rationale: minimizes surface area and regression risk.
80+
- Decision: Keep CLI output semantics unchanged.
81+
- Rationale: this feature adds detection capability, not UX changes.
82+
- Decision: Parse the first JSON line (`type=session_meta`) as the authoritative session identity/cwd/timestamp source.
83+
- Rationale: sampled session files consistently include this shape, and it avoids scanning full transcript payloads.
84+
- Decision: Treat running `codex` processes as source-of-truth for list membership.
85+
- Rationale: session tail events can represent turn completion while process remains active.
86+
- Decision: Match `pid -> session` by closest process start time (`now - etime`) to `session_meta.timestamp` with tolerance.
87+
- Rationale: improves accuracy when multiple Codex processes share the same project `cwd`.
88+
- Decision: Bound session scanning for performance while including process-start day windows.
89+
- Rationale: keeps list latency low and still supports long-lived process/session mappings.
90+
- Decision: Keep status-threshold values consistent across adapters.
91+
- Rationale: preserves cross-agent behavior consistency and avoids adapter-specific drift.
92+
- Decision: Use `codex-<session-id-prefix>` fallback naming when `cwd` is unavailable.
93+
- Rationale: keeps identifiers deterministic and short while remaining user-readable.
94+
- Decision: Keep matching orchestration in explicit phases (`cwd`, `missing-cwd`, `any`) with extracted helper methods and PID/session tracking sets.
95+
- Rationale: preserves behavior while reducing branching complexity and repeated scans in `detectAgents`.
96+
97+
## Non-Functional Requirements
98+
99+
- Performance: `agent list` should remain bounded by existing adapter aggregation patterns.
100+
- Reliability: Codex adapter failures must be isolated (no full-command failure when one adapter errors).
101+
- Maintainability: follow Claude adapter structure to keep adapter implementations consistent.
102+
- Security: only read local metadata/process info already permitted by existing CLI behavior.
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
---
2+
phase: implementation
3+
title: "Codex Adapter in @ai-devkit/agent-manager - Implementation"
4+
feature: codex-adapter-agent-manager-package
5+
description: Implementation notes for Codex adapter support in package agent manager and CLI integration
6+
---
7+
8+
# Implementation Guide: Codex Adapter in @ai-devkit/agent-manager
9+
10+
## Development Setup
11+
12+
- Use branch/worktree: `feature-codex-adapter-agent-manager-package`
13+
- Install dependencies with `npm ci`
14+
- Validate docs and feature scope with:
15+
- `npx ai-devkit@latest lint`
16+
- `npx ai-devkit@latest lint --feature codex-adapter-agent-manager-package`
17+
18+
## Code Structure
19+
20+
- Package adapter implementation:
21+
- `packages/agent-manager/src/adapters/CodexAdapter.ts`
22+
- Package exports:
23+
- `packages/agent-manager/src/adapters/index.ts`
24+
- `packages/agent-manager/src/index.ts`
25+
- CLI wiring:
26+
- `packages/cli/src/commands/agent.ts`
27+
- Tests:
28+
- `packages/agent-manager/src/__tests__/adapters/CodexAdapter.test.ts`
29+
- CLI tests touching adapter registration/open flow
30+
31+
## Implementation Notes
32+
33+
### Core Features
34+
- Implement Codex adapter contract (`type`, `canHandle`, `detectAgents`) using existing utilities where possible.
35+
- Normalize Codex metadata into stable `AgentInfo` output.
36+
- Register Codex adapter in command paths that instantiate `AgentManager`.
37+
- Match process/session pairs by `cwd` plus process-start-time proximity (`etime` vs `session_meta.timestamp`) using configurable tolerance.
38+
39+
### Patterns & Best Practices
40+
- Follow `ClaudeCodeAdapter` structure for consistency.
41+
- Keep adapter-specific parsing in adapter module; keep formatting in CLI.
42+
- Fail soft on malformed/partial entries; avoid throwing across adapter boundary.
43+
- Keep `detectAgents` orchestration readable via small private helpers for each matching stage.
44+
45+
## Integration Points
46+
47+
- `AgentManager` parallel aggregation behavior
48+
- `TerminalFocusManager` open/focus flow compatibility for Codex command metadata
49+
- CLI list/json output mapping
50+
51+
## Error Handling
52+
53+
- Handle missing/unreadable Codex source data by returning empty results.
54+
- Catch parsing errors per-entry and continue processing valid entries.
55+
- Let manager collect adapter errors without crashing full command.
56+
57+
## Performance Considerations
58+
59+
- Avoid full session-history scans per run; use bounded recent-file selection.
60+
- Include process-start day windows to preserve long-lived session mapping without scanning all days.
61+
- Keep parsing linear to selected entries only.
62+
- Reuse existing async aggregation model.
63+
64+
## Security Notes
65+
66+
- Read only local metadata/process information necessary for agent detection.
67+
- Do not execute arbitrary commands during detection.
68+
69+
## Implementation Status
70+
71+
- Completed:
72+
- Added `packages/agent-manager/src/adapters/CodexAdapter.ts`
73+
- Added package exports in `packages/agent-manager/src/adapters/index.ts` and `packages/agent-manager/src/index.ts`
74+
- Updated `packages/cli/src/commands/agent.ts` to register `CodexAdapter` for `list` and `open`
75+
- Added adapter unit tests and CLI command test mock update for Codex export
76+
- Notes:
77+
- CLI TypeScript tests resolve workspace package exports from built artifacts; run `npx nx run agent-manager:build` before focused CLI agent-command tests when export surface changes.
78+
- Matching/performance constants are defined in `CodexAdapter`:
79+
- `PROCESS_SESSION_TIME_TOLERANCE_MS`
80+
- `PROCESS_START_DAY_WINDOW_DAYS`
81+
- session-scan bound constants (`MIN/MAX/SCAN_MULTIPLIER`)
82+
- Simplification refactor (no behavior change):
83+
- extracted orchestration helpers:
84+
- `listCodexProcesses`
85+
- `calculateSessionScanLimit`
86+
- `assignSessionsForMode`
87+
- `addMappedSessionAgent`
88+
- `addProcessOnlyAgent`
89+
- `filterCandidateSessions`
90+
- `rankCandidatesByStartTime`
91+
- replaced repeated `agents.some(...)` PID checks with `assignedPids` set tracking
92+
93+
## Phase 6 Check Implementation (February 26, 2026)
94+
95+
### Alignment Summary
96+
97+
- Overall status: aligned with requirements and design.
98+
- Codex adapter implementation remains package-owned and exported through public entry points.
99+
- CLI registration for `list` and `open` includes `CodexAdapter` and preserves existing command UX boundaries.
100+
101+
### File-by-File Comparison
102+
103+
- `packages/agent-manager/src/adapters/CodexAdapter.ts`
104+
- Implements required adapter contract and process-first list membership.
105+
- Uses configured time-based matching (`etime` start time vs `session_meta.timestamp`) with tolerance and day-window file inclusion.
106+
- Includes simplification refactor helpers and set-based PID/session assignment tracking with no behavior drift.
107+
- `packages/agent-manager/src/adapters/index.ts`
108+
- Exports `CodexAdapter` as designed.
109+
- `packages/agent-manager/src/index.ts`
110+
- Re-exports `CodexAdapter` from package root as designed.
111+
- `packages/cli/src/commands/agent.ts`
112+
- Registers `CodexAdapter` for both list and open manager paths; no CLI presentation logic moved into package.
113+
- `packages/agent-manager/src/__tests__/adapters/CodexAdapter.test.ts`
114+
- Covers core mapping/status behavior plus simplified matching-phase behavior (`cwd`, `missing-cwd`, `any`) and no-session-reuse expectations.
115+
116+
### Deviations / Concerns
117+
118+
- No requirement/design deviations found.
119+
- Residual validation note: full `cli:test` still has known unrelated pre-existing failures outside this feature scope; focused Codex adapter tests pass.
120+
121+
## Phase 8 Code Review (February 26, 2026)
122+
123+
### Findings
124+
125+
1. No blocking correctness, security, or design-alignment issues found in the Codex adapter implementation or CLI integration paths.
126+
2. Non-blocking performance follow-up: `readFirstLine` currently reads full file content (`fs.readFileSync`) before splitting first line in `CodexAdapter`; this is acceptable for current bounded scan but can be optimized later for very large transcripts.
127+
3. Test-phase risk remains low for changed paths (focused suites pass), with residual global coverage/flaky-suite signals tracked as pre-existing workspace-level issues.
128+
129+
### Final Checklist
130+
131+
- Design/requirements match: ✅
132+
- Logic gaps on changed paths: ✅ none identified
133+
- Security concerns introduced: ✅ none identified
134+
- Tests for changed behavior: ✅ focused adapter + CLI command suites pass
135+
- Docs updated across lifecycle phases: ✅
136+
137+
### Review Verdict
138+
139+
- Ready for push/PR from a Phase 8 review perspective.
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
---
2+
phase: planning
3+
title: "Codex Adapter in @ai-devkit/agent-manager - Planning"
4+
feature: codex-adapter-agent-manager-package
5+
description: Task plan for adding Codex adapter support and integrating it into CLI agent commands
6+
---
7+
8+
# Planning: Codex Adapter in @ai-devkit/agent-manager
9+
10+
## Milestones
11+
12+
- [x] Milestone 1: Codex adapter design finalized and scaffolding created
13+
- [x] Milestone 2: Codex adapter implementation and package exports complete
14+
- [x] Milestone 3: CLI integration, tests, and verification complete
15+
16+
## Task Breakdown
17+
18+
### Phase 1: Foundation
19+
- [x] Task 1.1: Confirm Codex discovery inputs and mapping contract
20+
- Use `~/.codex/sessions/YYYY/MM/DD/*.jsonl` as the primary source
21+
- Parse line 1 `session_meta` for `id`, `cwd`, `timestamp`
22+
- Parse the last line for terminal event markers (`task_complete`, `turn_aborted`)
23+
- Define normalization rules for `id`, `name`, `cwd`, and `status`
24+
- [x] Task 1.2: Scaffold package adapter files
25+
- Add `CodexAdapter.ts` and test file skeleton
26+
- Update adapter/index exports
27+
28+
### Phase 2: Core Features
29+
- [x] Task 2.1: Implement Codex discovery and mapping logic
30+
- Parse metadata with robust validation/fallback behavior
31+
- Compute status using existing status model
32+
- [x] Task 2.2: Register Codex adapter in CLI command flow
33+
- Update all manager registration paths in `commands/agent.ts`
34+
- Preserve output structure and errors
35+
36+
### Phase 3: Integration & Polish
37+
- [x] Task 3.1: Add/extend tests
38+
- Unit tests for Codex adapter branches and failure handling
39+
- CLI command tests for registration/path coverage
40+
- [x] Task 3.2: Validate and document
41+
- Run lint/build/tests for affected projects
42+
- Record implementation + testing outcomes in docs/ai
43+
- [x] Task 3.3: Simplify implementation structure without behavior changes
44+
- Extract matching orchestration and ranking helpers for readability
45+
- Replace repeated PID lookup scans with set-based tracking
46+
47+
## Dependencies
48+
49+
- Existing `@ai-devkit/agent-manager` adapter contract and utilities
50+
- Existing CLI agent command integration points
51+
- Availability of Codex metadata sources in local runtime
52+
53+
## Timeline & Estimates
54+
55+
- Task 1.1-1.2: 0.5 day
56+
- Task 2.1-2.2: 1.0 day
57+
- Task 3.1-3.2: 0.5 day
58+
- Total estimate: 2.0 days
59+
60+
## Risks & Mitigation
61+
62+
- Risk: Codex metadata format may vary across versions.
63+
- Mitigation: defensive parsing + tests with partial/malformed fixtures.
64+
- Risk: `agent open` behavior for Codex may need command-specific nuances.
65+
- Mitigation: validate open flow with representative commands and add focused tests.
66+
- Risk: Adding adapter increases list latency.
67+
- Mitigation: keep async aggregation pattern and short-circuit invalid entries.
68+
69+
## Resources Needed
70+
71+
- Existing adapter examples (`ClaudeCodeAdapter`) as implementation template
72+
- Maintainer validation for Codex session/source assumptions
73+
- CI runtime for lint/build/test verification
74+
75+
## Progress Summary
76+
77+
Implementation scope is complete. `CodexAdapter` was added to `@ai-devkit/agent-manager`, exported through package entry points, and registered in CLI agent command flows. Follow-up fixes addressed false-positive process matching, missing long-lived session links, and list latency from broad session scans. Matching now uses `etime`-based process start time with configurable tolerance and process-start day-window session inclusion, while keeping a bounded recent-file scan for performance. A final simplification pass extracted helper methods for match phases/ranking and introduced set-based PID assignment tracking; behavior is unchanged with focused tests still passing.
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
---
2+
phase: requirements
3+
title: "Codex Adapter in @ai-devkit/agent-manager - Requirements"
4+
feature: codex-adapter-agent-manager-package
5+
description: Add a Codex adapter to the shared agent-manager package and wire CLI consumption through package exports
6+
---
7+
8+
# Requirements: Add Codex Adapter to @ai-devkit/agent-manager
9+
10+
## Problem Statement
11+
12+
`@ai-devkit/agent-manager` currently ships `ClaudeCodeAdapter` as the only concrete adapter, while `AgentType` already includes `codex`. As a result, Codex sessions are not detected/listed/opened through the shared package flow used by CLI agent commands.
13+
14+
Who is affected:
15+
- Users running Codex alongside other supported agents who expect `ai-devkit agent list/open` to include Codex
16+
- CLI maintainers who want adapter support centralized in `@ai-devkit/agent-manager`
17+
- Contributors who need a reference implementation for adding new adapters
18+
19+
## Goals & Objectives
20+
21+
### Primary Goals
22+
- Implement a package-level `CodexAdapter` under `packages/agent-manager`
23+
- Export `CodexAdapter` from package public entry points
24+
- Update CLI agent command wiring to register `CodexAdapter` through package imports
25+
- Preserve existing behavior for Claude and existing output/error contracts
26+
27+
### Secondary Goals
28+
- Reuse shared process/file utilities and adapter contract patterns
29+
- Add tests for Codex adapter discovery, status mapping, and command metadata
30+
- Establish a clean extension path for future adapters (Gemini/others)
31+
- Keep Codex adapter internals maintainable via small helper functions without changing runtime behavior
32+
33+
### Non-Goals
34+
- Reworking overall `ai-devkit agent` UX
35+
- Refactoring unrelated CLI command modules
36+
- Introducing a new plugin system for adapters in this phase
37+
38+
## User Stories & Use Cases
39+
40+
1. As a Codex user, I want running Codex sessions to appear in `ai-devkit agent list` so I can inspect active work quickly.
41+
2. As a CLI user, I want `ai-devkit agent open <id>` to support Codex agents with the same behavior guarantees as existing agents.
42+
3. As a maintainer, I want Codex detection logic in `@ai-devkit/agent-manager` so package/CLI behavior does not drift.
43+
4. As an adapter author, I want Codex adapter tests to act as a template for future adapter implementations.
44+
45+
## Success Criteria
46+
47+
- `packages/agent-manager/src/adapters/CodexAdapter.ts` exists and implements `AgentAdapter`
48+
- `@ai-devkit/agent-manager` public exports include `CodexAdapter`
49+
- `packages/cli/src/commands/agent.ts` registers `CodexAdapter` from package exports
50+
- Unit tests cover Codex adapter happy path, empty/no-session path, and invalid data handling
51+
- Existing agent command tests continue to pass without regressions
52+
- Implementation remains readable enough for future adapter extension work (clear matching phases/helpers)
53+
54+
## Constraints & Assumptions
55+
56+
### Technical Constraints
57+
- Must follow existing Nx TypeScript project structure and test setup
58+
- Must keep adapter contract compatibility (`AgentAdapter`, `AgentInfo`, `AgentStatus`)
59+
- Must not break JSON/table output schema consumed by users
60+
61+
### Assumptions
62+
- Codex session metadata is available in `~/.codex/sessions/YYYY/MM/DD/*.jsonl` with a stable first-line `session_meta` payload
63+
- `TerminalFocusManager` can open Codex sessions using command metadata supplied by adapter or existing CLI flow
64+
- Codex naming and workspace path conventions are stable enough for first-pass implementation
65+
66+
## Questions & Open Items
67+
68+
- Resolved (2026-02-26): Canonical discovery source is `~/.codex/sessions` JSONL files. In 88/88 sampled files, line 1 is `type=session_meta` with `payload.id`, `payload.cwd`, and `payload.timestamp`.
69+
- Resolved (2026-02-26): Running `codex` process list is the source of truth for whether an agent is listed.
70+
- Session tail events such as `task_complete` and `turn_aborted` do not hide an agent when the process is still running.
71+
- Resolved (2026-02-26): Session matching uses process start time (`now - etime`) against `session_meta.timestamp` with a configurable tolerance window constant.
72+
- Resolved (2026-02-26): For long-lived processes, session scan includes process-start day window in addition to bounded recent-file scanning.
73+
- Resolved (2026-02-26): Use the same status threshold values across all adapters (Codex uses existing shared/Claude-equivalent thresholds).
74+
- Resolved (2026-02-26): If `cwd` is missing, fallback display identifier is `codex-<session-id-prefix>`.

0 commit comments

Comments
 (0)