Skip to content
Merged
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
102 changes: 102 additions & 0 deletions docs/ai/design/feature-codex-adapter-agent-manager-package.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
---
phase: design
title: "Codex Adapter in @ai-devkit/agent-manager - Design"
feature: codex-adapter-agent-manager-package
description: Architecture and implementation design for introducing Codex adapter support in the shared agent manager package
---

# Design: Codex Adapter for @ai-devkit/agent-manager

## Architecture Overview

```mermaid
graph TD
User[User runs ai-devkit agent list/open] --> Cmd[packages/cli/src/commands/agent.ts]
Cmd --> Manager[AgentManager]

subgraph Pkg[@ai-devkit/agent-manager]
Manager --> Claude[ClaudeCodeAdapter]
Manager --> Codex[CodexAdapter]
Codex --> Proc[process utils]
Codex --> File[file utils]
Codex --> Types[AgentAdapter/AgentInfo/AgentStatus]
Focus[TerminalFocusManager]
end

Cmd --> Focus
Cmd --> Output[CLI table/json rendering]
```

Responsibilities:
- `CodexAdapter`: discover and map running Codex sessions to `AgentInfo`
- `AgentManager`: aggregate Codex + existing adapter results
- CLI command: register adapters, display results, and invoke open/focus behavior

## Data Models

- Reuse existing `AgentAdapter`, `AgentInfo`, `AgentStatus`, and `AgentType` models
- `AgentType` already supports `codex`; adapter emits `type: 'codex'`
- Codex raw metadata (internal to adapter) is normalized into:
- `id`: deterministic session/process identifier
- `name`: user-facing label derived from `cwd`; fallback to `codex-<session-id-prefix>` when `cwd` is missing
- `cwd`: workspace path (if available)
- `sessionStart`: parsed from `session_meta.timestamp` for process/session time matching
- `status`: computed from recency/activity metadata using the same threshold values already used by existing adapters
- `pid`: matched running Codex process id used by terminal focus flow

## API Design

### Package Exports
- Add `CodexAdapter` to:
- `packages/agent-manager/src/adapters/index.ts`
- `packages/agent-manager/src/index.ts`

### CLI Integration
- Update `packages/cli/src/commands/agent.ts` to register `CodexAdapter` alongside `ClaudeCodeAdapter`
- Keep display mapping logic in CLI; do not move presentation concerns into package

## Component Breakdown

1. `packages/agent-manager/src/adapters/CodexAdapter.ts`
- Implement adapter contract methods/properties
- Discover Codex sessions from `~/.codex/sessions/YYYY/MM/DD/*.jsonl`
- Map session data to standardized `AgentInfo`

2. `packages/agent-manager/src/__tests__/adapters/CodexAdapter.test.ts`
- Unit tests for detection/parsing/status mapping/error handling

3. `packages/agent-manager/src/adapters/index.ts` and `src/index.ts`
- Export adapter class

4. `packages/cli/src/commands/agent.ts`
- Register Codex adapter in manager setup path(s)

## Design Decisions

- Decision: Implement Codex detection in package, not CLI.
- Rationale: preserves package as the single source of truth for agent discovery.
- Decision: Reuse existing adapter contract and manager aggregation flow.
- Rationale: minimizes surface area and regression risk.
- Decision: Keep CLI output semantics unchanged.
- Rationale: this feature adds detection capability, not UX changes.
- Decision: Parse the first JSON line (`type=session_meta`) as the authoritative session identity/cwd/timestamp source.
- Rationale: sampled session files consistently include this shape, and it avoids scanning full transcript payloads.
- Decision: Treat running `codex` processes as source-of-truth for list membership.
- Rationale: session tail events can represent turn completion while process remains active.
- Decision: Match `pid -> session` by closest process start time (`now - etime`) to `session_meta.timestamp` with tolerance.
- Rationale: improves accuracy when multiple Codex processes share the same project `cwd`.
- Decision: Bound session scanning for performance while including process-start day windows.
- Rationale: keeps list latency low and still supports long-lived process/session mappings.
- Decision: Keep status-threshold values consistent across adapters.
- Rationale: preserves cross-agent behavior consistency and avoids adapter-specific drift.
- Decision: Use `codex-<session-id-prefix>` fallback naming when `cwd` is unavailable.
- Rationale: keeps identifiers deterministic and short while remaining user-readable.
- Decision: Keep matching orchestration in explicit phases (`cwd`, `missing-cwd`, `any`) with extracted helper methods and PID/session tracking sets.
- Rationale: preserves behavior while reducing branching complexity and repeated scans in `detectAgents`.

## Non-Functional Requirements

- Performance: `agent list` should remain bounded by existing adapter aggregation patterns.
- Reliability: Codex adapter failures must be isolated (no full-command failure when one adapter errors).
- Maintainability: follow Claude adapter structure to keep adapter implementations consistent.
- Security: only read local metadata/process info already permitted by existing CLI behavior.
139 changes: 139 additions & 0 deletions docs/ai/implementation/feature-codex-adapter-agent-manager-package.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
---
phase: implementation
title: "Codex Adapter in @ai-devkit/agent-manager - Implementation"
feature: codex-adapter-agent-manager-package
description: Implementation notes for Codex adapter support in package agent manager and CLI integration
---

# Implementation Guide: Codex Adapter in @ai-devkit/agent-manager

## Development Setup

- Use branch/worktree: `feature-codex-adapter-agent-manager-package`
- Install dependencies with `npm ci`
- Validate docs and feature scope with:
- `npx ai-devkit@latest lint`
- `npx ai-devkit@latest lint --feature codex-adapter-agent-manager-package`

## Code Structure

- Package adapter implementation:
- `packages/agent-manager/src/adapters/CodexAdapter.ts`
- Package exports:
- `packages/agent-manager/src/adapters/index.ts`
- `packages/agent-manager/src/index.ts`
- CLI wiring:
- `packages/cli/src/commands/agent.ts`
- Tests:
- `packages/agent-manager/src/__tests__/adapters/CodexAdapter.test.ts`
- CLI tests touching adapter registration/open flow

## Implementation Notes

### Core Features
- Implement Codex adapter contract (`type`, `canHandle`, `detectAgents`) using existing utilities where possible.
- Normalize Codex metadata into stable `AgentInfo` output.
- Register Codex adapter in command paths that instantiate `AgentManager`.
- Match process/session pairs by `cwd` plus process-start-time proximity (`etime` vs `session_meta.timestamp`) using configurable tolerance.

### Patterns & Best Practices
- Follow `ClaudeCodeAdapter` structure for consistency.
- Keep adapter-specific parsing in adapter module; keep formatting in CLI.
- Fail soft on malformed/partial entries; avoid throwing across adapter boundary.
- Keep `detectAgents` orchestration readable via small private helpers for each matching stage.

## Integration Points

- `AgentManager` parallel aggregation behavior
- `TerminalFocusManager` open/focus flow compatibility for Codex command metadata
- CLI list/json output mapping

## Error Handling

- Handle missing/unreadable Codex source data by returning empty results.
- Catch parsing errors per-entry and continue processing valid entries.
- Let manager collect adapter errors without crashing full command.

## Performance Considerations

- Avoid full session-history scans per run; use bounded recent-file selection.
- Include process-start day windows to preserve long-lived session mapping without scanning all days.
- Keep parsing linear to selected entries only.
- Reuse existing async aggregation model.

## Security Notes

- Read only local metadata/process information necessary for agent detection.
- Do not execute arbitrary commands during detection.

## Implementation Status

- Completed:
- Added `packages/agent-manager/src/adapters/CodexAdapter.ts`
- Added package exports in `packages/agent-manager/src/adapters/index.ts` and `packages/agent-manager/src/index.ts`
- Updated `packages/cli/src/commands/agent.ts` to register `CodexAdapter` for `list` and `open`
- Added adapter unit tests and CLI command test mock update for Codex export
- Notes:
- 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.
- Matching/performance constants are defined in `CodexAdapter`:
- `PROCESS_SESSION_TIME_TOLERANCE_MS`
- `PROCESS_START_DAY_WINDOW_DAYS`
- session-scan bound constants (`MIN/MAX/SCAN_MULTIPLIER`)
- Simplification refactor (no behavior change):
- extracted orchestration helpers:
- `listCodexProcesses`
- `calculateSessionScanLimit`
- `assignSessionsForMode`
- `addMappedSessionAgent`
- `addProcessOnlyAgent`
- `filterCandidateSessions`
- `rankCandidatesByStartTime`
- replaced repeated `agents.some(...)` PID checks with `assignedPids` set tracking

## Phase 6 Check Implementation (February 26, 2026)

### Alignment Summary

- Overall status: aligned with requirements and design.
- Codex adapter implementation remains package-owned and exported through public entry points.
- CLI registration for `list` and `open` includes `CodexAdapter` and preserves existing command UX boundaries.

### File-by-File Comparison

- `packages/agent-manager/src/adapters/CodexAdapter.ts`
- Implements required adapter contract and process-first list membership.
- Uses configured time-based matching (`etime` start time vs `session_meta.timestamp`) with tolerance and day-window file inclusion.
- Includes simplification refactor helpers and set-based PID/session assignment tracking with no behavior drift.
- `packages/agent-manager/src/adapters/index.ts`
- Exports `CodexAdapter` as designed.
- `packages/agent-manager/src/index.ts`
- Re-exports `CodexAdapter` from package root as designed.
- `packages/cli/src/commands/agent.ts`
- Registers `CodexAdapter` for both list and open manager paths; no CLI presentation logic moved into package.
- `packages/agent-manager/src/__tests__/adapters/CodexAdapter.test.ts`
- Covers core mapping/status behavior plus simplified matching-phase behavior (`cwd`, `missing-cwd`, `any`) and no-session-reuse expectations.

### Deviations / Concerns

- No requirement/design deviations found.
- Residual validation note: full `cli:test` still has known unrelated pre-existing failures outside this feature scope; focused Codex adapter tests pass.

## Phase 8 Code Review (February 26, 2026)

### Findings

1. No blocking correctness, security, or design-alignment issues found in the Codex adapter implementation or CLI integration paths.
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.
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.

### Final Checklist

- Design/requirements match: ✅
- Logic gaps on changed paths: ✅ none identified
- Security concerns introduced: ✅ none identified
- Tests for changed behavior: ✅ focused adapter + CLI command suites pass
- Docs updated across lifecycle phases: ✅

### Review Verdict

- Ready for push/PR from a Phase 8 review perspective.
77 changes: 77 additions & 0 deletions docs/ai/planning/feature-codex-adapter-agent-manager-package.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
---
phase: planning
title: "Codex Adapter in @ai-devkit/agent-manager - Planning"
feature: codex-adapter-agent-manager-package
description: Task plan for adding Codex adapter support and integrating it into CLI agent commands
---

# Planning: Codex Adapter in @ai-devkit/agent-manager

## Milestones

- [x] Milestone 1: Codex adapter design finalized and scaffolding created
- [x] Milestone 2: Codex adapter implementation and package exports complete
- [x] Milestone 3: CLI integration, tests, and verification complete

## Task Breakdown

### Phase 1: Foundation
- [x] Task 1.1: Confirm Codex discovery inputs and mapping contract
- Use `~/.codex/sessions/YYYY/MM/DD/*.jsonl` as the primary source
- Parse line 1 `session_meta` for `id`, `cwd`, `timestamp`
- Parse the last line for terminal event markers (`task_complete`, `turn_aborted`)
- Define normalization rules for `id`, `name`, `cwd`, and `status`
- [x] Task 1.2: Scaffold package adapter files
- Add `CodexAdapter.ts` and test file skeleton
- Update adapter/index exports

### Phase 2: Core Features
- [x] Task 2.1: Implement Codex discovery and mapping logic
- Parse metadata with robust validation/fallback behavior
- Compute status using existing status model
- [x] Task 2.2: Register Codex adapter in CLI command flow
- Update all manager registration paths in `commands/agent.ts`
- Preserve output structure and errors

### Phase 3: Integration & Polish
- [x] Task 3.1: Add/extend tests
- Unit tests for Codex adapter branches and failure handling
- CLI command tests for registration/path coverage
- [x] Task 3.2: Validate and document
- Run lint/build/tests for affected projects
- Record implementation + testing outcomes in docs/ai
- [x] Task 3.3: Simplify implementation structure without behavior changes
- Extract matching orchestration and ranking helpers for readability
- Replace repeated PID lookup scans with set-based tracking

## Dependencies

- Existing `@ai-devkit/agent-manager` adapter contract and utilities
- Existing CLI agent command integration points
- Availability of Codex metadata sources in local runtime

## Timeline & Estimates

- Task 1.1-1.2: 0.5 day
- Task 2.1-2.2: 1.0 day
- Task 3.1-3.2: 0.5 day
- Total estimate: 2.0 days

## Risks & Mitigation

- Risk: Codex metadata format may vary across versions.
- Mitigation: defensive parsing + tests with partial/malformed fixtures.
- Risk: `agent open` behavior for Codex may need command-specific nuances.
- Mitigation: validate open flow with representative commands and add focused tests.
- Risk: Adding adapter increases list latency.
- Mitigation: keep async aggregation pattern and short-circuit invalid entries.

## Resources Needed

- Existing adapter examples (`ClaudeCodeAdapter`) as implementation template
- Maintainer validation for Codex session/source assumptions
- CI runtime for lint/build/test verification

## Progress Summary

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.
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
---
phase: requirements
title: "Codex Adapter in @ai-devkit/agent-manager - Requirements"
feature: codex-adapter-agent-manager-package
description: Add a Codex adapter to the shared agent-manager package and wire CLI consumption through package exports
---

# Requirements: Add Codex Adapter to @ai-devkit/agent-manager

## Problem Statement

`@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.

Who is affected:
- Users running Codex alongside other supported agents who expect `ai-devkit agent list/open` to include Codex
- CLI maintainers who want adapter support centralized in `@ai-devkit/agent-manager`
- Contributors who need a reference implementation for adding new adapters

## Goals & Objectives

### Primary Goals
- Implement a package-level `CodexAdapter` under `packages/agent-manager`
- Export `CodexAdapter` from package public entry points
- Update CLI agent command wiring to register `CodexAdapter` through package imports
- Preserve existing behavior for Claude and existing output/error contracts

### Secondary Goals
- Reuse shared process/file utilities and adapter contract patterns
- Add tests for Codex adapter discovery, status mapping, and command metadata
- Establish a clean extension path for future adapters (Gemini/others)
- Keep Codex adapter internals maintainable via small helper functions without changing runtime behavior

### Non-Goals
- Reworking overall `ai-devkit agent` UX
- Refactoring unrelated CLI command modules
- Introducing a new plugin system for adapters in this phase

## User Stories & Use Cases

1. As a Codex user, I want running Codex sessions to appear in `ai-devkit agent list` so I can inspect active work quickly.
2. As a CLI user, I want `ai-devkit agent open <id>` to support Codex agents with the same behavior guarantees as existing agents.
3. As a maintainer, I want Codex detection logic in `@ai-devkit/agent-manager` so package/CLI behavior does not drift.
4. As an adapter author, I want Codex adapter tests to act as a template for future adapter implementations.

## Success Criteria

- `packages/agent-manager/src/adapters/CodexAdapter.ts` exists and implements `AgentAdapter`
- `@ai-devkit/agent-manager` public exports include `CodexAdapter`
- `packages/cli/src/commands/agent.ts` registers `CodexAdapter` from package exports
- Unit tests cover Codex adapter happy path, empty/no-session path, and invalid data handling
- Existing agent command tests continue to pass without regressions
- Implementation remains readable enough for future adapter extension work (clear matching phases/helpers)

## Constraints & Assumptions

### Technical Constraints
- Must follow existing Nx TypeScript project structure and test setup
- Must keep adapter contract compatibility (`AgentAdapter`, `AgentInfo`, `AgentStatus`)
- Must not break JSON/table output schema consumed by users

### Assumptions
- Codex session metadata is available in `~/.codex/sessions/YYYY/MM/DD/*.jsonl` with a stable first-line `session_meta` payload
- `TerminalFocusManager` can open Codex sessions using command metadata supplied by adapter or existing CLI flow
- Codex naming and workspace path conventions are stable enough for first-pass implementation

## Questions & Open Items

- 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`.
- Resolved (2026-02-26): Running `codex` process list is the source of truth for whether an agent is listed.
- Session tail events such as `task_complete` and `turn_aborted` do not hide an agent when the process is still running.
- Resolved (2026-02-26): Session matching uses process start time (`now - etime`) against `session_meta.timestamp` with a configurable tolerance window constant.
- Resolved (2026-02-26): For long-lived processes, session scan includes process-start day window in addition to bounded recent-file scanning.
- Resolved (2026-02-26): Use the same status threshold values across all adapters (Codex uses existing shared/Claude-equivalent thresholds).
- Resolved (2026-02-26): If `cwd` is missing, fallback display identifier is `codex-<session-id-prefix>`.
Loading