agent-orchestrator icon indicating copy to clipboard operation
agent-orchestrator copied to clipboard

feat(agent-codex): use Codex hooks for activity detection

Open harshitsinghbhandari opened this issue 6 months ago • 7 comments

Summary

This PR pivots Codex hook work away from raw hook telemetry and into AO activity observations:

  • installs a project-local Codex hook activity updater (.codex/ao-codex-activity-updater.cjs)
  • enables Codex hooks on launch/resume with --enable hooks
  • pre-trusts only AO's updater hook commands and marks the project trusted so Codex loads project-local hooks
  • maps hook payloads directly into normal .ao/activity.jsonl entries with source: "hook", trigger, and sessionId
  • removes .ao/codex-hooks.jsonl as both an output and an input; raw hook payloads are not persisted

Activity-state impact from hook entries

  • active: hook updater writes active for SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, SubagentStart, PreCompact, and PostCompact. These decay through the existing AO activity fallback (active → ready → idle).
  • ready: hook updater writes ready for Stop; it decays to idle through the existing AO activity fallback.
  • waiting_input: hook updater writes waiting_input for PermissionRequest, scoped by AO_SESSION_ID.
  • blocked: not affected by hooks. Codex hook payloads currently do not provide a clear blocked/error event, so blocked still comes from native Codex JSONL (error / stream_error) and terminal-derived AO safety-net activity.
  • idle: not written by hooks. Idle is produced only by existing age decay.
  • exited: not affected by hooks. Process exit detection still short-circuits before file reads.

Precedence and scoping

  • Native Codex JSONL actionable states (waiting_input, blocked) still win.
  • Terminal-derived AO actionable activity remains a safety net.
  • Hook actionable activity is ignored when it is older than newer native non-actionable Codex JSONL evidence.
  • Hook activity entries are ignored when they belong to a different AO session or predate the current session.
  • Malformed/partial .ao/activity.jsonl lines are skipped.

Tests

  • pnpm --filter @aoagents/ao-core build
  • pnpm --filter @aoagents/ao-plugin-agent-codex build
  • pnpm --filter @aoagents/ao-plugin-agent-codex test
  • pnpm --filter @aoagents/ao-plugin-agent-codex typecheck
  • pnpm build
  • pnpm typecheck
  • pnpm lint (passes with existing warnings)
  • pnpm test (fails in existing @aoagents/ao-plugin-tracker-linear tests because @composio/core is not installed; Codex tests pass)

harshitsinghbhandari avatar May 20 '26 13:05 harshitsinghbhandari

Greptile Summary

This PR pivots Codex activity detection from raw hook telemetry (.ao/codex-hooks.jsonl) to writing hook payloads directly into the standard AO activity log (.ao/activity.jsonl) with a source: "hook" field and sessionId scoping. It also extracts the bulk of index.ts activity-detection logic into a dedicated activity-detection.ts module.

  • New hook updater script (ao-codex-activity-updater.cjs) maps Codex hook events (SessionStart, PermissionRequest, Stop, etc.) to AO activity states and appends them to .ao/activity.jsonl; the file is installed to .codex/ on workspace setup and pre-trusted in ~/.codex/config.toml.
  • Activity-state cascade now reads a 64 KB tail of .ao/activity.jsonl, filters hook entries by AO_SESSION_ID and session creation time to prevent cross-session bleed, and respects a strict precedence order: native Codex JSONL actionable states win → activity-log actionable states → age-decayed fallback → session file mtime.

Confidence Score: 5/5

Safe to merge. The hook activity cascade is well-guarded: opt-in via AO_CODEX_HOOK_ACTIVITY, session-scoped to AO_SESSION_ID, and hook entries can never mask native waiting_input/blocked signals from the Codex JSONL. The tail-based file read (64 KB cap) resolves the previously flagged unbounded read concern.

The activity-state cascade logic is correct — tested across all precedence scenarios (native wins over hook, hook wins over stale terminal, cross-session entries are filtered). The opt-in guard isHookActivityEnabled() is consistently applied to getLaunchCommand, getRestoreCommand, and setupWorkspaceHooks. No data-loss, security, or correctness issues were found in the changed paths.

No files require special attention.

Important Files Changed

Filename Overview
packages/plugins/agent-codex/src/activity-detection.ts New 1011-line module extracting all activity detection, session scanning, hook trust setup, and TOML config management; logic is well-structured and session-scoped, with tail-based file reading (64 KB cap) fixing the prior full-file-read concern.
packages/plugins/agent-codex/src/ao-codex-activity-updater.cjs New 73-line CJS hook script that maps Codex hook event names to AO activity states and appends session-scoped entries to .ao/activity.jsonl; correctly exits early when AO_CODEX_HOOK_ACTIVITY=0 or AO_SESSION_ID is unset.
packages/plugins/agent-codex/src/index.ts Refactored to delegate getActivityState, isProcessRunning, and setupWorkspaceHooks to the new activity-detection.ts module; adds --enable hooks CLI flag and AO_WORKSPACE_PATH env var to launch/resume commands when hook activity is enabled.
packages/plugins/agent-codex/src/index.test.ts Adds ~300 lines of new tests covering hook activity states, session scoping, precedence rules, decay, malformed-line resilience, and the no-op default when hook activity is disabled; updates mock infrastructure to support positional file reads.
packages/core/src/types.ts Adds optional sessionId?: string to ActivityLogEntry to support hook-derived session scoping.
packages/core/src/activity-log.ts Propagates sessionId field through readLastActivityEntry using the same conditional-spread pattern as existing trigger.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[getActivityState called] --> B{runtimeHandle present?}
    B -- No --> C[return exited]
    B -- Yes --> D{Process alive?}
    D -- No --> C
    D -- Indeterminate --> E[return null]
    D -- Yes --> F[findCodexSessionFileCached]

    F --> G{Native JSONL found?}
    G -- Yes --> H[readLastJsonlEntry]
    H --> I{Actionable?}
    I -- Yes --> J[return native state]
    I -- No --> K[save nativeDetection]
    G -- No --> K

    K --> L[readCodexActivityResults 64KB tail]
    L --> M{latest or latestHook actionable?}
    M -- terminal/native source --> N[return immediately]
    M -- hook source ts >= nativeTime --> O[return hook state]
    M -- hook source ts < nativeTime --> P[skip stale hook]
    M -- not actionable --> P

    P --> Q[getActivityFallbackState age-decay]
    Q --> R[pickNewest native vs fallback]
    R --> T[return active/ready/idle]
Prompt To Fix All With AI
Fix the following 1 code review issue. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 1
packages/plugins/agent-codex/src/index.ts:192-195
`getSessionMetadataString` is now defined in both `activity-detection.ts` (line ~721) and retained verbatim in `index.ts`. Since `index.ts` already imports from `./activity-detection.js`, the copy here can be removed and the import reused, keeping the two files in sync if the function ever needs to change.

```suggestion
// getSessionMetadataString is exported from ./activity-detection.js — import it there instead of duplicating.
```


Reviews (11): Last reviewed commit: "feat(agent-codex): use Codex hooks for a..." | Re-trigger Greptile

greptile-apps avatar May 20 '26 13:05 greptile-apps

PR Review — feat(agent-codex): derive activity from Codex hook logs

Scope Check ✅ Clean

3 files changed — changeset, source, and tests for @aoagents/ao-plugin-agent-codex. No submodules, no stray files, no config drift.


Findings

# Severity Category Finding
1 Medium Perf/Correctness readLastCodexHookActivity reads entire codex-hooks.jsonl into memory via readFile + split. Should use streaming reverse-tail (like readLastJsonlEntry in ao-core) or add a line limit. O(n) growth per getActivityState() call.
2 Low Style setupWorkspaceHooks reformat is cosmetic-only — should be split out or reverted to keep the diff surgical.
3 Low Style PR body has bare #1947 instead of linkified [#1947](https://github.com/ComposioHQ/agent-orchestrator/pull/1947).
4 Info Style CODEX_HOOK_ACTIVE_EVENTS is a subset of CODEX_KNOWN_HOOK_EVENTS — a comment noting the relationship would help future maintainers.

What's Done Well ✅

  • Precedence model is sound — exited → native JSONL actionable → AO hook actionable → merged fallback → session mtime. Clean layering.
  • Session scoping correct — filters pre-session records and cross-session entries properly
  • Security clean — no user-controlled path components, no eval, JSON parsing guarded with try/catch + type narrowing
  • isWindows() used correctly — no raw process.platform checks
  • Test coverage thorough — 9+ new cases covering hook events, age decay, precedence, cross-session filtering, malformed JSON, and exited override
  • Pure refactor of mapCodexJsonlEntryToActivity — verified identical to removed inline switch. No behavioral change to existing paths.

One item worth addressing before merge: finding #1 (full-file read). For a long-running workspace, that jsonl grows unbounded and every polling cycle slurps the whole thing. The fix is straightforward — either reuse readLastJsonlEntry from core or cap lines with a SESSION_MATCH_SCAN_LINE_LIMIT-style constant.

OrcInc avatar May 20 '26 15:05 OrcInc

Addressed the new review comments in 5960f068:

  • Avoid repeated hook-log ENOENT I/O for non-opt-in users by only reading .ao/codex-hooks.jsonl when AO_CODEX_HOOK_LOGGING=1.
  • Replaced full-file readFile + split with a bounded reverse-tail read (64 KiB) so polling does not scale with total hook log size.
  • Left setupWorkspaceHooks untouched after removing the #1947 harness; the PR only consumes existing hook logs now.
  • Added a comment explaining known-but-unmapped hook events as boundaries.

Validation rerun:

  • pnpm --filter @aoagents/ao-plugin-agent-codex test ✅
  • pnpm --filter @aoagents/ao-plugin-agent-codex typecheck ✅
  • pnpm build ✅
  • pnpm typecheck ✅
  • pnpm lint ✅ existing warnings only

harshitsinghbhandari avatar May 20 '26 15:05 harshitsinghbhandari

Pivoted this PR to Codex hook activity observations only. It no longer writes or reads .ao/codex-hooks.jsonl and does not persist raw hook payloads. Hooks now append normal .ao/activity.jsonl entries with source=hook/sessionId, and getActivityState compares those against native JSONL + terminal AO activity with the documented precedence. Also force-pushed a single clean commit from upstream/main and resolved the stale hook trust review thread.

harshitsinghbhandari avatar May 20 '26 16:05 harshitsinghbhandari

Addressed ao-162 P1: the hook updater now exits without writing unless AO_SESSION_ID is a non-empty string, and the Codex activity reader now ignores all hook entries unless sessionId exactly matches the AO session id. Added regressions for missing-session hook entries and for the updater script's early guard. Also applied the optional hardening: setup removes stale AO updater hooks from existing groups and appends one canonical unfiltered AO updater group per event. Re-ran Codex build/typecheck/test and lint.

harshitsinghbhandari avatar May 20 '26 16:05 harshitsinghbhandari

From the NotesBot call on 2026-05-20, this existing pr appears to be relevant. Match confidence: 0.73 (fuzzy).

Relevant discussion excerpts:

  • 🧠 Agent Sessions: Instrumentation, Hooks, and Status Schema - prateek: Root cause example—Yoel + NixOS: Codex process name differs; regex matcher in is_process_alive fails → liveness detection breaks. - prateek: Leverage hooks from session activity detection work: “Hooks… make things super deterministic.”
    • prateek: Root cause example—Yoel + NixOS: Codex process name differs; regex matcher in is_process_alive fails → liveness detection breaks. - prateek: Leverage hooks from session activity detection work: “Hooks… make things super deterministic.”
    • prateek: Root cause example—Yoel + NixOS: Codex process name differs; regex matcher in is_process_alive fails → liveness detection breaks. - prateek: Leverage hooks from session activity detection work: “Hooks… make things super deterministic.” 📋 Notes from the Call

Source thread: https://discord.com/channels/1476302178913357958/1506709026531053768/1506709026531053768

Generated by AO Bot based on the transcript from NotesBot.

OrcInc avatar May 20 '26 19:05 OrcInc

@greptile review.

harshitsinghbhandari avatar May 21 '26 19:05 harshitsinghbhandari