Skip to content

feat: Complete post-commit agent trace pipeline#37

Merged
stefanskoricdev merged 8 commits into
mainfrom
feat/persist-agent-trace
May 14, 2026
Merged

feat: Complete post-commit agent trace pipeline#37
stefanskoricdev merged 8 commits into
mainfrom
feat/persist-agent-trace

Conversation

@stefanskoricdev
Copy link
Copy Markdown
Contributor

@stefanskoricdev stefanskoricdev commented May 13, 2026

Summary

Build the full post-commit agent trace pipeline across six scoped changes:

Changes

  1. agent_traces table migration — Added 004_create_agent_traces.sql migration.
  2. Builder wiring + file artifact — Wired PostCommitIntersectionFlowResult into build_agent_trace() via a dedicated run_post_commit_agent_trace_flow helper.
  3. Agent Trace DB write — Extended the post-commit flow to also insert into agent_traces (DB).
  4. Schema validation gate — Injected validate_agent_trace_value into the post-commit flow as a callable argument, invoked after build_agent_trace() and before DB persistence, reusing the same failure-path as insert errors (cli/src/services/hooks/mod.rs).

Summary by CodeRabbit

  • New Features

    • Agent traces are now generated during post-commit processing and automatically persisted for auditing and analysis.
  • Database

    • Added a migration that creates a new agent_traces table to store trace payloads and metadata.
  • Tests

    • Updated tests to cover the new migration and persisted trace behavior.
  • Chores

    • Packaged crate now includes migration files; development toolchain updated to include the rust-src component.

Review Change Stack

…sult

Move post-commit intersection orchestration to return typed data (PostCommitIntersectionFlowResult) instead of formatted text, and shift command-surface message rendering to run_post_commit_subcommand.

This keeps persistence/intersection behavior unchanged while making the flow easier to test and compose through explicit typed outputs.

Co-authored-by: SCE <sce@crocoder.dev>
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 13, 2026

📝 Walkthrough

Walkthrough

This PR adds persistent storage of agent traces captured during post-commit hooks: a new SQL migration creates the agent_traces table, the agent-trace DB adapter can insert trace payloads, the post-commit hook is refactored to produce a structured result and persist built agent-trace JSON, and the crate packages migration assets.

Changes

Agent Trace Persistence in Post-Commit Hook

Layer / File(s) Summary
Database Migration and Packaging
cli/Cargo.toml, cli/migrations/agent-trace/004_create_agent_traces.sql, cli/src/services/agent_trace_db/mod.rs
"migrations/**" added to include; new migration 004_create_agent_traces.sql creates agent_traces table; migration constant/registration added.
Agent Trace Insert Adapter
cli/src/services/agent_trace_db/mod.rs
Adds INSERT_AGENT_TRACE_SQL, AgentTraceInsert<'a> struct, AgentTraceDb::insert_agent_trace implementation, and updates tests to expect the new table and migration ID.
Post-Commit Hook Integration with Trace Persistence
cli/src/services/hooks/mod.rs
Post-commit flow refactored to return PostCommitIntersectionFlowResult; imports agent-trace builder/validator; builds/validates AgentTrace payload and persists via AgentTraceDb; tests updated to assert structured result fields.
Toolchain extension
flake.nix
Adds rust-src to rustToolchain.extensions.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • ivke995
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 53.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: Complete post-commit agent trace pipeline' accurately describes the main objective of the PR: implementing a complete pipeline for persisting agent traces in post-commit hooks.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/persist-agent-trace

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

stefanskoricdev and others added 5 commits May 13, 2026 15:22
Route post-commit execution through a dedicated agent-trace flow that consumes the typed intersection result, builds Agent Trace metadata from commit-time context, and persists a pretty JSON payload under context/tmp with collision-safe semantics. This keeps the post-commit success contract stable while adding explicit error propagation and test coverage for timestamp validation, persistence failures, and flow wiring behavior.

Co-authored-by: SCE <sce@crocoder.dev>
Add an agent_traces migration and typed insert path so built post-commit Agent Trace payloads are stored in the Agent Trace database alongside filesystem artifacts.

Update post-commit hook flow orchestration and tests to require successful dual persistence (artifact + DB row), and sync SCE context docs to the new runtime behavior.

Co-authored-by: SCE <sce@crocoder.dev>
Keep post-commit Agent Trace persistence DB-only by removing context/tmp artifact writes from the post-commit flow while preserving agent_traces inserts and commit metadata mapping.

Update related tests and context contracts to reflect the active runtime behavior (post-commit DB-only, diff-trace still dual-persisted).

Co-authored-by: SCE <sce@crocoder.dev>
Co-authored-by: SCE <sce@crocoder.dev>
@stefanskoricdev stefanskoricdev marked this pull request as ready for review May 13, 2026 16:38
@stefanskoricdev stefanskoricdev requested review from davidabram and ivke995 and removed request for davidabram May 13, 2026 16:38
@stefanskoricdev stefanskoricdev changed the title hooks: Refactor post-commit intersection flow to return structured result feat: Complete post-commit agent trace pipeline May 13, 2026
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cli/src/services/agent_trace_db/mod.rs`:
- Around line 170-176: Add a focused unit test next to insert_agent_trace that
opens the same test database used by other tests, calls insert_agent_trace with
a single AgentTraceInsert (set commit_id, commit_time_ms, and trace_json), then
query agent_traces to fetch that row and assert the stored commit_id,
commit_time_ms, and trace_json match the input; use the insert_agent_trace
method name and the agent_traces table in the test, ensure cleanup or
transaction rollback per existing test patterns, and keep the test deterministic
and minimal to catch SQL binding regressions for INSERT_AGENT_TRACE_SQL.

In `@cli/src/services/hooks/mod.rs`:
- Around line 455-457: The current orchestration calls
run_intersection_flow(...) and then run_agent_trace_flow(...), which can leave
persisted intersection rows if the second call fails; make these two post-commit
writes atomic by performing both writes inside a single transaction (or by
adding a compensating rollback on failure). Concretely, modify
run_intersection_flow and run_agent_trace_flow (or add a new wrapper like
run_intersection_and_agent_trace_transactional) to accept a shared DB
transaction/context, execute the intersection write and the agent-trace write
within that transaction, and only commit after both succeed (or if your DB layer
cannot do that, delete/undo the intersection rows when run_agent_trace_flow
returns an error). Ensure references to run_intersection_flow,
run_agent_trace_flow, result and the final commit/rollback are updated
accordingly.
- Around line 459-462: The log message reports "intersection_files" but uses
result.combined_recent_patch.files.len(); change it to report the real
intersection count (e.g., use the actual intersection collection's length such
as result.post_commit_data.intersection_files.len() or
result.intersection_files.len. wherever the intersection vector/collection is
stored) or else rename the message key to "combined_files" to match
combined_recent_patch.files.len(); update the call that builds the log
(referencing result.post_commit_data.commit_oid and
result.combined_recent_patch.files.len()) so the metric name matches the value
returned.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: a0054fbf-0bb1-49aa-b65a-98dd3055a49b

📥 Commits

Reviewing files that changed from the base of the PR and between d7883d4 and a7127e5.

⛔ Files ignored due to path filters (7)
  • context/architecture.md is excluded by !context/**/*.md
  • context/cli/cli-command-surface.md is excluded by !context/**/*.md
  • context/context-map.md is excluded by !context/**/*.md
  • context/glossary.md is excluded by !context/**/*.md
  • context/overview.md is excluded by !context/**/*.md
  • context/sce/agent-trace-db.md is excluded by !context/**/*.md
  • context/sce/agent-trace-hooks-command-routing.md is excluded by !context/**/*.md
📒 Files selected for processing (4)
  • cli/Cargo.toml
  • cli/migrations/agent-trace/004_create_agent_traces.sql
  • cli/src/services/agent_trace_db/mod.rs
  • cli/src/services/hooks/mod.rs

Comment on lines +170 to +176
/// Insert a built agent trace payload into the `agent_traces` table.
pub fn insert_agent_trace(&self, input: AgentTraceInsert<'_>) -> Result<u64> {
self.execute(
INSERT_AGENT_TRACE_SQL,
(input.commit_id, input.commit_time_ms, input.trace_json),
)
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Add a focused unit test for insert_agent_trace.

Please add a test that inserts one AgentTraceInsert row and asserts stored commit_id, commit_time_ms, and trace_json in agent_traces. The current migration-only assertions won’t catch insert SQL binding regressions.

As per coding guidelines, "Add unit tests close to the code they exercise."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cli/src/services/agent_trace_db/mod.rs` around lines 170 - 176, Add a focused
unit test next to insert_agent_trace that opens the same test database used by
other tests, calls insert_agent_trace with a single AgentTraceInsert (set
commit_id, commit_time_ms, and trace_json), then query agent_traces to fetch
that row and assert the stored commit_id, commit_time_ms, and trace_json match
the input; use the insert_agent_trace method name and the agent_traces table in
the test, ensure cleanup or transaction rollback per existing test patterns, and
keep the test deterministic and minimal to catch SQL binding regressions for
INSERT_AGENT_TRACE_SQL.

Comment on lines +455 to +457
let result = run_intersection_flow(repository_root)?;
let _agent_trace = run_agent_trace_flow(repository_root, &result)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Prevent partial persistence across the two post-commit write stages.

This orchestration can leave persisted intersection rows without corresponding agent traces when stage 2 fails. Please make the two writes atomic (single transaction or explicit compensating strategy) to avoid inconsistent trace state.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cli/src/services/hooks/mod.rs` around lines 455 - 457, The current
orchestration calls run_intersection_flow(...) and then
run_agent_trace_flow(...), which can leave persisted intersection rows if the
second call fails; make these two post-commit writes atomic by performing both
writes inside a single transaction (or by adding a compensating rollback on
failure). Concretely, modify run_intersection_flow and run_agent_trace_flow (or
add a new wrapper like run_intersection_and_agent_trace_transactional) to accept
a shared DB transaction/context, execute the intersection write and the
agent-trace write within that transaction, and only commit after both succeed
(or if your DB layer cannot do that, delete/undo the intersection rows when
run_agent_trace_flow returns an error). Ensure references to
run_intersection_flow, run_agent_trace_flow, result and the final
commit/rollback are updated accordingly.

Comment on lines +459 to +462
"post-commit hook processed intersection: commit={}, intersection_files={}",
result.post_commit_data.commit_oid,
result.combined_recent_patch.files.len()
))
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix the reported intersection_files count.

intersection_files currently uses combined_recent_patch.files.len(), which is not the intersection file count. Either compute/report the actual intersection count or rename the field text to match the metric.

Proposed minimal wording fix
- "post-commit hook processed intersection: commit={}, intersection_files={}",
+ "post-commit hook processed intersection: commit={}, combined_recent_files={}",
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cli/src/services/hooks/mod.rs` around lines 459 - 462, The log message
reports "intersection_files" but uses result.combined_recent_patch.files.len();
change it to report the real intersection count (e.g., use the actual
intersection collection's length such as
result.post_commit_data.intersection_files.len() or
result.intersection_files.len. wherever the intersection vector/collection is
stored) or else rename the message key to "combined_files" to match
combined_recent_patch.files.len(); update the call that builds the log
(referencing result.post_commit_data.commit_oid and
result.combined_recent_patch.files.len()) so the metric name matches the value
returned.

Co-authored-by: SCE <sce@crocoder.dev>
Comment thread cli/src/services/hooks/mod.rs
Co-authored-by: SCE <sce@crocoder.dev>
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cli/src/services/hooks/mod.rs`:
- Around line 465-486: The post-commit flow in run_post_commit_agent_trace_flow
currently only validates and inserts into AgentTraceDb via
run_post_commit_agent_trace_flow_with and never writes the serialized trace to
disk; update run_post_commit_agent_trace_flow to call
persist_serialized_trace_payload(repository_root, &serialized_payload,
&trace_meta) after successful validation/insert (use the same serialized payload
produced in the closure passed to run_post_commit_agent_trace_flow_with),
ensuring you pass repository_root so the artifact is written; mirror the same
change for the other occurrence noted (lines ~522-533) so both post-commit paths
persist the agent-trace file artifact.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: ecde60a9-f7fc-40f3-ae7f-0c5ec549ef68

📥 Commits

Reviewing files that changed from the base of the PR and between f03b74c and 21d57fe.

📒 Files selected for processing (1)
  • cli/src/services/hooks/mod.rs

Comment on lines +465 to +486
fn run_post_commit_agent_trace_flow(
_repository_root: &Path,
flow_result: &PostCommitIntersectionFlowResult,
) -> Result<AgentTrace> {
let db = AgentTraceDb::new().context("Failed to open Agent Trace DB for post-commit trace.")?;

run_post_commit_agent_trace_flow_with(
flow_result,
|trace_value| {
validate_agent_trace_value(trace_value)
.map_err(|error| anyhow!(error.to_string()))
.context("Failed to verify built post-commit Agent Trace payload.")?;

Ok(())
},
|insert_input| {
db.insert_agent_trace(insert_input)
.context("Failed to persist built post-commit Agent Trace payload.")?;

Ok(())
},
)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Persist the built post-commit agent trace as a file artifact.

This helper takes repository_root, but the new flow only validates the trace and inserts it into AgentTraceDb. There is no call to persist_serialized_trace_payload(...), so the post-commit path never emits the agent-trace artifact on disk even though this is the integration point for that stage of the pipeline.

Also applies to: 522-533

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cli/src/services/hooks/mod.rs` around lines 465 - 486, The post-commit flow
in run_post_commit_agent_trace_flow currently only validates and inserts into
AgentTraceDb via run_post_commit_agent_trace_flow_with and never writes the
serialized trace to disk; update run_post_commit_agent_trace_flow to call
persist_serialized_trace_payload(repository_root, &serialized_payload,
&trace_meta) after successful validation/insert (use the same serialized payload
produced in the closure passed to run_post_commit_agent_trace_flow_with),
ensuring you pass repository_root so the artifact is written; mirror the same
change for the other occurrence noted (lines ~522-533) so both post-commit paths
persist the agent-trace file artifact.

@stefanskoricdev stefanskoricdev merged commit f571391 into main May 14, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants