Skip to content

Post commit hook impl#36

Merged
davidabram merged 11 commits into
mainfrom
post-commit-hook-impl
May 5, 2026
Merged

Post commit hook impl#36
davidabram merged 11 commits into
mainfrom
post-commit-hook-impl

Conversation

@davidabram
Copy link
Copy Markdown
Member

@davidabram davidabram commented May 4, 2026

Summary by CodeRabbit

  • New Features

    • Post-commit hook now computes and stores patch intersections between the current commit and recent trace data, reporting loaded/skipped counts and number of intersecting files.
  • Performance

    • Added a database index and query improvements to speed recent patch lookups.
  • Reliability

    • Query now returns parsed patches while isolating and counting invalid/skipped entries instead of failing the whole operation.

Adds a new post_commit_patch_intersections table and insert
capability to the agent trace Turso database. The table stores
commit-level patch intersection results including the commit ID,
timing window metrics, trace counts, and the intersection patch payload.

This enables capturing the diff-trace intersection results
that occur after each commit for later analysis of agent
behavior around commit boundaries.

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

coderabbitai Bot commented May 4, 2026

Warning

Rate limit exceeded

@davidabram has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 36 minutes and 22 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: c32799ab-1fa5-40d2-8dcd-8acb792e2244

📥 Commits

Reviewing files that changed from the base of the PR and between 34ce2ac and d5cc7d6.

⛔ Files ignored due to path filters (10)
  • context/architecture.md is excluded by !context/**/*.md
  • context/cli/patch-service.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/patterns.md is excluded by !context/**/*.md
  • context/plans/one_off_agent_trace_db_migration_fix.md is excluded by !context/**/*.md
  • context/plans/post_commit_intersection_regression_and_context_drift.md is excluded by !context/**/*.md
  • context/sce/agent-trace-db.md is excluded by !context/**/*.md
  • context/sce/shared-turso-db.md is excluded by !context/**/*.md
📒 Files selected for processing (4)
  • cli/migrations/agent-trace/003_add_diff_traces_time_ms_id_index.sql
  • cli/src/services/agent_trace_db/mod.rs
  • cli/src/services/db/mod.rs
  • cli/src/services/hooks/mod.rs
📝 Walkthrough

Walkthrough

Adds DB persistence and query support for post-commit patch intersections, a new DB table and index, helpers to map query rows, new agent-trace APIs to select recent diff-trace patches and insert intersection results, and a post-commit hook flow that captures git HEAD, combines/intersects recent patches, and persists the intersection.

Changes

Post-Commit Patch Intersection Persistence

Layer / File(s) Summary
Database Schema
cli/migrations/agent-trace/002_create_post_commit_patch_intersections.sql, cli/migrations/agent-trace/003_add_diff_traces_time_ms_id_index.sql
Adds post_commit_patch_intersections table (id, commit/timing metadata, non-negative loaded/skipped counts, intersection payload, created_at) and composite index idx_diff_traces_time_ms_id on diff_traces(time_ms, id).
Database Layer Generic Helper
cli/src/services/db/mod.rs
Adds TursoDb<M>::query_map to run a query, iterate rows, map each turso::Row via a closure, collect results, and wrap errors with context.
Data Model & SQL Constants
cli/src/services/agent_trace_db/mod.rs
Introduces DiffTracePatchRow, ParsedDiffTracePatch, SkippedDiffTracePatch, RecentDiffTracePatches (+counts accessors), PostCommitPatchIntersectionInsert and SQL constants SELECT_RECENT_DIFF_TRACE_PATCHES_SQL and INSERT_POST_COMMIT_PATCH_INTERSECTION_SQL.
Query & Insert Implementation
cli/src/services/agent_trace_db/mod.rs
Adds recent_diff_trace_patches (maps DB rows, parses patch payloads, separates valid vs skipped parse results) and insert_post_commit_patch_intersection helpers; routes insert_diff_trace via common helper; updates migration list.
Post-Commit Hook Intersection Flow
cli/src/services/hooks/mod.rs
Replaces no-op post-commit behavior with run_post_commit_intersection_flow: computes a 7-day window, captures HEAD commit OID/time/patch, queries recent diff traces, combines recent parsed patches, intersects with current commit patch, serializes intersection JSON, and inserts a post_commit_patch_intersections row; returns summary including counts and intersection file count.
Git Patch Capture API
cli/src/services/hooks/mod.rs
Adds PostCommitPatchData and capture_post_commit_patch_from_git that read HEAD OID, commit timestamp (ms), and patch text from git and parse into ParsedPatch.
Minor Documentation / Imports
cli/src/services/hooks/command.rs, cli/src/services/hooks/mod.rs, cli/src/services/agent_trace_db/mod.rs
Replaced #[allow(dead_code)] with doc comment; added time and patch-related imports; removed obsolete no-op helper.
Tests / Validation
cli/src/services/agent_trace_db/mod.rs (tests)
Tests/refactors updated to reflect helper functions and new recent-patch parsing/skipping behavior and cutoff/order semantics.

Sequence Diagram

sequenceDiagram
    participant Hook as Post-Commit Hook
    participant Git as Git Repository
    participant DB as AgentTraceDb
    participant Patch as Patch Ops

    Hook->>Git: read HEAD OID, commit time, patch text
    Git-->>Hook: commit metadata + patch
    Hook->>Patch: parse current patch
    Patch-->>Hook: ParsedPatch (current)

    Hook->>DB: query recent diff traces (time_ms window)
    DB-->>Hook: RecentDiffTracePatches (loaded + skipped)

    Hook->>Patch: combine loaded recent patches
    Patch-->>Hook: CombinedParsedPatch

    Hook->>Patch: intersect CombinedParsedPatch ∩ CurrentParsedPatch
    Patch-->>Hook: IntersectionParsedPatch

    Hook->>Patch: serialize intersection to JSON
    Patch-->>Hook: intersection_payload

    Hook->>DB: insert post_commit_patch_intersection(row)
    DB-->>Hook: stored
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 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 60.00% 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 'Post commit hook impl' directly refers to the main change in the changeset, which implements post-commit hook functionality across multiple files including the hooks/mod.rs implementation.
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 unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch post-commit-hook-impl

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.

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: 4

🤖 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 155-157: The recent_diff_trace_patches API currently only filters
rows with time_ms >= cutoff_time_ms and thus includes any future-dated rows;
update the function signature (recent_diff_trace_patches and the helper
recent_diff_trace_patches_with) to accept an additional end_time_ms
(recent_window_end_ms) and change the DB query to enforce both bounds time_ms >=
cutoff_time_ms AND time_ms <= end_time_ms; also propagate the new end_time_ms
parameter from the caller (post-commit flow that records recent_window_end_ms)
so the query correctly restricts the "recent" window on both ends.
- Around line 319-362: The test
recent_diff_trace_patches_filters_by_cutoff_and_orders_chronologically currently
uses distinct time_ms values; add a same-timestamp ordering case by inserting
two DiffTraceInsert rows with identical time_ms (e.g., 1000) but different
session_id values and relying on insert_diff_trace_with to create distinct ids,
then call recent_diff_trace_patches_with(db, 1000) and assert the returned
result.patches order is deterministic (matches the id tie-breaker ordering used
by the query, e.g., session_ids in ascending id order); place the new assertions
alongside the existing ones in that test so equal-timestamp ordering is
validated.

In `@cli/src/services/db/mod.rs`:
- Around line 250-255: The row-mapper errors currently lose the SQL/DB context;
change the call in the loop so failures from map_row preserve context by using
anyhow::Context (e.g., call map_row(&row).with_context(...) and include
M::db_name() and the sql string in the message) before the ? so any mapping
error is annotated with "row mapping failed" plus the SQL and DB name; locate
this around the rows.next() loop where results.push(map_row(&row)?) is invoked
and update that expression to add the context.

In `@cli/src/services/hooks/mod.rs`:
- Around line 810-823: The function capture_head_timestamp_from_git currently
reads the git author timestamp (%at) in seconds and returns it directly; change
it to use the committer timestamp specifier "%ct", parse the seconds, convert to
milliseconds using a checked multiplication (e.g.,
seconds.checked_mul(1000).ok_or_else(...) ) to prevent overflow, and return that
i64 milliseconds value; keep the same error path using post_commit_patch_error
for parse/overflow errors so callers expecting commit_time_ms receive a
correctly scaled millisecond timestamp.
🪄 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: bc353e02-27ef-416e-943c-b24e0dfd65fc

📥 Commits

Reviewing files that changed from the base of the PR and between 8a4484a and 649ef0f.

⛔ Files ignored due to path filters (11)
  • context/architecture.md is excluded by !context/**/*.md
  • context/cli/patch-service.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/patterns.md is excluded by !context/**/*.md
  • context/plans/post_commit_patch_intersection_db.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
  • context/sce/agent-trace-post-commit-dual-write.md is excluded by !context/**/*.md
  • context/sce/shared-turso-db.md is excluded by !context/**/*.md
📒 Files selected for processing (6)
  • cli/migrations/agent-trace/002_create_post_commit_patch_intersections.sql
  • cli/migrations/agent-trace/003_add_diff_traces_time_ms_id_index.sql
  • cli/src/services/agent_trace_db/mod.rs
  • cli/src/services/db/mod.rs
  • cli/src/services/hooks/command.rs
  • cli/src/services/hooks/mod.rs
💤 Files with no reviewable changes (1)
  • cli/src/services/hooks/command.rs

Comment thread cli/src/services/agent_trace_db/mod.rs Outdated
Comment thread cli/src/services/agent_trace_db/mod.rs
Comment thread cli/src/services/db/mod.rs Outdated
Comment thread cli/src/services/hooks/mod.rs
davidabram and others added 5 commits May 5, 2026 00:12
Adds TursoDb::query_map for row-mapping queries, and
AgentTraceDb::recent_diff_trace_patches(cutoff_time_ms) for chronological
diff_traces reads with patch parsing and malformed-row skip accounting.

Co-authored-by: SCE <sce@crocoder.dev>
…nd intersect

Replace the no-op post-commit entrypoint with an active intersection flow
that captures the current commit patch via git, queries recent diff_traces
from the past 7 days, combines valid patches, intersects the combined result
with the post-commit patch, and persists the serialized intersection to the
post_commit_patch_intersections table. Empty recent patch sets produce a
deterministic empty intersection instead of crashing.

Co-authored-by: SCE <sce@crocoder.dev>
…nctions

Co-authored-by: SCE <sce@crocoder.dev>
The post-commit intersection query filters by time_ms and sorts by
(time_ms, id). Without this composite index, SQLite performs a full
table scan and an extra sort pass. The new index covers both the range
filter and the sort order in a single pass.

Co-authored-by: SCE <sce@crocoder.dev>
@davidabram davidabram force-pushed the post-commit-hook-impl branch from 649ef0f to 811bc9a Compare May 4, 2026 22:12
davidabram and others added 4 commits May 5, 2026 13:26
Convert Git commit timestamps from seconds to milliseconds and bound recent diff trace queries to the hook execution time so post-commit intersection uses the intended inclusive window.

Also improves DB row-mapping error context and simplifies nearby hook comments.

Co-authored-by: SCE <sce@crocoder.dev>
Add DB-backed regression coverage for inclusive recent diff-trace query bounds,
deterministic time/id ordering, raw patch parsing, and malformed-row skip
accounting.

Co-authored-by: SCE <sce@crocoder.dev>
Add a focused injectable seam around the post-commit intersection
flow so the query window, persisted window metadata, skipped/loaded
counts, and intersection output can be asserted deterministically.

Co-authored-by: SCE <sce@crocoder.dev>
Align Agent Trace DB and patch-service docs with the inclusive
recent diff-trace query window and raw patch parsing behavior.

Update the migration query comment to show the upper time
bound used by the runtime.

Co-authored-by: SCE <sce@crocoder.dev>
@davidabram davidabram force-pushed the post-commit-hook-impl branch from ae13f29 to 65d1aa8 Compare May 5, 2026 20:21
Record applied Turso migration IDs per database so setup can skip completed migrations while bringing metadata-less databases forward with the current idempotent migration set.

Plan: one_off_agent_trace_db_migration_fix

Task: one-off approved task (no T0X task ID)

Co-authored-by: SCE <sce@crocoder.dev>
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.

1 participant