openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

feat(approval): persist post-execution audit row alongside approval (#2135)

Open CodeGhost21 opened this issue 6 months ago • 1 comments

Summary

  • Add executed_at, execution_outcome, and execution_error columns to pending_approvals so every approved tool call carries both a before-row (approval decision) and an after-row (terminal execution status).
  • New ApprovalGate::intercept_audited returns the persisted request_id so the four agent paths that gate external-effect tools can stamp the terminal status when the tool finishes.
  • New store::record_execution enforces monotonic audit (decided_at IS NOT NULL guard) and caps error strings at 512 chars to keep upstream crash dumps out of the audit log.

Problem

pending_approvals rows transition from (no decided_at) → (decided_at, decision) and stop there. There is no terminal entry recording whether the approved tool actually ran, what it returned, or whether it failed. A compliance reviewer can see approved but not executed — they have to cross-reference the agent transcript, which is the wrong place for an audit trail. Issue #2135 calls this gap out explicitly under "Tests cover audit write before AND after an action".

Solution

Approval domain

  • New ExecutionOutcome enum (Success / Failure / Aborted).
  • pending_approvals table gets three new columns. Idempotent PRAGMA table_info migration upgrades v1 DBs in place — pre-#2135 rows back-fill as NULL so older audit history stays readable.
  • store::record_execution(request_id, outcome, error) gated by decided_at IS NOT NULL so the audit trail stays monotonic (no executed before approved rows possible). Error strings capped at 512 chars + ellipsis.
  • ApprovalGate::intercept_audited(...) returns (GateOutcome, Option<String>). Legacy intercept(...) is a thin wrapper that drops the id so call sites that don't care about after-execution audit (CLI, tests) keep their current shape.
  • ApprovalGate::record_execution(...) wraps the store call with best-effort logging — audit-write failure is logged but never bubbles back to the agent (the tool already ran).

Wiring (4 call sites)

  • agent/harness/tool_loop.rs — capture request_id from the gate, stamp Success/Failure with the truncated tool result text after the tool finishes.
  • agent/harness/subagent_runner/ops.rs — same shape for sub-agent-dispatched tool calls.
  • channels/proactive.rs — stamp Success on ch.send Ok, Failure with the error message on Err.
  • agent/triage/escalation.rs — stamp Success/Failure on the triage-dispatched sub-agent outcome.

Submission Checklist

If a section does not apply to this change, mark the item as N/A with a one-line reason.

  • [x] Tests added or updated (happy path + at least one failure / edge case) — 8 new tests; cargo test --lib approval → 71 passed, 0 failed.
  • [x] Diff coverage ≥ 80% — every changed line in store.rs / gate.rs is exercised by a new or updated test. Four call-site changes are 5–10 lines each, all on hot paths already covered by existing harness tests.
  • [x] Coverage matrix updated — N/A: behaviour-only change to existing approval surface; no new feature row added/removed/renamed.
  • [x] All affected feature IDs from the matrix are listed in ## Related — N/A: no matrix row touched.
  • [x] No new external network dependencies introduced — pure SQLite + in-process gate code.
  • [x] Manual smoke checklist updated if this touches release-cut surfaces — N/A: audit-trail addition only; no user-visible UI flow changes when approvals work normally.
  • [x] Linked issue closed via Closes #NNN in the ## Related section — see below.

Impact

  • Runtime/platform: desktop core + Tauri shell. Approval domain is in-process.
  • User-visible: none under happy-path operation. The audit trail in ~/.openhuman/approval/approval.db now carries executed_at + execution_outcome + execution_error per approved row; UI surfaces that consume these rows will see the new fields.
  • Performance / security: one extra SQLite UPDATE per gated tool call (best-effort, async-aware tracing on failure). Error strings are capped at 512 chars so a crash dump can't fill the audit DB.
  • Migration / compatibility: schema migration is idempotent and happens on every with_connection call. v1 DBs (older builds) get the new columns added in place, with existing rows back-filled as NULL.

Tests

cargo test --lib approval → 71 passed, 0 failed (8 new, 63 pre-existing).

New test Covers
record_execution_writes_terminal_audit_row_after_decide before-decide attempts must be a no-op; after decide they patch the row
record_execution_persists_outcome_and_redacted_error Failure with error text round-trips through SQLite
record_execution_caps_long_error_messages 2 000-char input is capped to ~512 chars + ellipsis
record_execution_unknown_id_is_safe_noop stray record_execution for an id that was never persisted reports false without writing
migrate_columns_is_idempotent_on_v1_databases synthesise a pre-#2135 schema, prove the migration adds the new columns without losing existing rows AND that a second open is a no-op
execution_outcome_round_trips / _serializes_as_snake_case on-wire shape for the new enum
intercept_audited_returns_request_id_only_when_allowed_and_persisted Allow path returns the id so callers can record_execution
intercept_audited_returns_none_id_for_denied_and_allowlisted Deny path and session-allowlist shortcut both return None (nothing to record afterward)

Related

  • Closes #2135
  • Companion: #2335 (audit history read path — surfaces the data this PR now also writes)
  • Companion: #2357 (lazy expiry of stale pending approvals after restart)
  • Follow-up PR(s)/TODOs: policy-callback hook for unattended channel/webhook denial (managed-runtime use case in the issue) — separate slice.

AI Authored PR Metadata (required for Codex/Linear PRs)

Linear Issue

  • Key: N/A
  • URL: N/A (GitHub-only issue #2135)

Commit & Branch

  • Branch: fix/2135-audit-action-execution (branched from origin/main after fresh fetch)
  • Commit SHA: see PR head

Validation Run

  • [x] pnpm --filter openhuman-app format:check — N/A: no frontend changes.
  • [x] pnpm typecheck — N/A: no TypeScript changes.
  • [x] Focused tests: cargo test --lib approval → 71 passed, 0 failed.
  • [x] Rust fmt/check (if changed): cargo fmt --manifest-path Cargo.toml applied; cargo check clean.
  • [x] Tauri fmt/check (if changed): N/A: no Tauri shell changes.

Validation Blocked

  • command: N/A
  • error: N/A
  • impact: N/A

Behavior Changes

  • Intended behavior change: every gated tool call now leaves both a before-row (approval decision) and an after-row (terminal status) on the same pending_approvals row.
  • User-visible effect: audit-history surfaces will show executed_at + outcome per approved row; agent / UI under normal operation are unchanged.

Parity Contract

  • Legacy behavior preserved: intercept(...) keeps its existing GateOutcome shape (it now wraps intercept_audited and drops the id). CLI and existing tests don't need changes.
  • Guard/fallback/dispatch parity checks: record_execution is gated by decided_at IS NOT NULL so the audit trail stays monotonic; idempotent column migration is tested against a synthetic v1 schema.

Duplicate / Superseded PR Handling

  • Duplicate PR(s): none for this slice. #2335 (audit history read) and #2357 (expiry) cover orthogonal acceptance criteria of the same issue.
  • Canonical PR: this PR for the before+after audit slice.
  • Resolution: N/A.

Summary by CodeRabbit

  • New Features

    • Approval flow now captures audited request IDs and records terminal execution outcomes (success/failure/aborted) for approved external actions
    • Audit trail extended to tool calls, escalations, and proactive external sends
  • Chores

    • Database migration adds execution/audit columns and live-upgrade support to persist terminal outcomes and preserve immutability
  • Tests

    • Added tests for audited approvals, execution recording, truncation/redaction, and migration behavior

Review Change Stack

CodeGhost21 avatar May 20 '26 19:05 CodeGhost21

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▶️ Resume reviews
  • [ ] 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds audited approval intercepts that return request IDs, DB migration and columns for execution audit, an ExecutionOutcome enum, and wiring to record terminal success/failure across tool harness, escalation, and proactive external-channel sends.

Changes

Approval audit recording

Layer / File(s) Summary
ExecutionOutcome type and audited gate APIs
src/openhuman/approval/types.rs, src/openhuman/approval/gate.rs, src/openhuman/approval/mod.rs
ExecutionOutcome (Success/Failure/Aborted) is added. ApprovalGate::intercept_audited() returns (GateOutcome, Option<request_id>) and record_execution() writes terminal outcome; gate tests verify request-id threading and allowlist shortcut behavior.
Approval store schema migration and persistence
src/openhuman/approval/store.rs
pending_approvals gains executed_at, execution_outcome, execution_error. migrate_columns() idempotently upgrades older DBs on open. New record_execution() persists outcome/error only after decided_at and when not already stamped; error text is sanitized and capped/truncated. Tests cover migration, truncation, idempotency, unknown-id safety, and redaction.
Tool harness & escalation integration
src/openhuman/agent/harness/tool_loop.rs, src/openhuman/agent/harness/subagent_runner/ops.rs, src/openhuman/agent/triage/escalation.rs
Tool-loop, subagent runner, and escalation use intercept_audited, retain optional approval_request_id and gate handle, then call record_execution after execution to stamp Success/Failure (exec success is derived from structured result, not text prefixes). Existing allow/deny flows remain.
Proactive message channel audited integration
src/openhuman/channels/proactive.rs
External-channel proactive sends call intercept_audited and record Success/Failure back to the approval audit row after send completes; web-channel delivery is unchanged.
i18n minor update
app/src/lib/i18n/chunks/de-5.ts
Trailing mascot translation entries adjusted.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • tinyhumansai/openhuman#2149: Prior changes to external-effect ApprovalGate flow; this PR extends that flow with audited intercepts and execution recording.
  • tinyhumansai/openhuman#2335: Adds related approval-audit history read APIs over decided audit rows that this change stamps.
  • tinyhumansai/openhuman#2357: Changes pending_approvals lifecycle and interacts with the same row-state transitions updated here.

Suggested reviewers

  • senamakel

Poem

🐰 I found a tiny request id in my hat,
The gate gave a nod and then that was that.
I ran the tool, then penned the tale:
success or fail — stamped without fail.
Hopping home, I left a tidy audit trail.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately reflects the main change: adding post-execution audit row persistence alongside approval decisions, as evidenced by all core files modifying approval storage and audit recording.
Linked Issues check ✅ Passed The PR successfully implements all coding requirements from #2135: durable storage of approval decisions/audit entries, audited tool execution paths across four call sites (tool_loop, subagent_runner, escalation, proactive channels), ExecutionOutcome enum for terminal status tracking, and error redaction with truncation.
Out of Scope Changes check ✅ Passed The PR includes one minor out-of-scope change: a German i18n file (de-5.ts) was modified to fix duplicate keys unrelated to approval auditing, though this appears to be a merge conflict resolution.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 20 '26 19:05 coderabbitai[bot]