Skip to content

Expand local agent usage coverage - #43

Merged
MapleEve merged 4 commits into
mainfrom
maple/all-agent-full-data-support
Jul 3, 2026
Merged

MapleEve merged 4 commits into
mainfrom
maple/all-agent-full-data-support

Conversation

@MapleEve

@MapleEve MapleEve commented Jul 3, 2026

Copy link
Copy Markdown
Owner

Summary

  • expand local agent usage collection across the registered agent matrix
  • add bounded scan ordering, delta/cache safeguards, edit retention, and rollup support
  • strengthen architecture, source-matrix, server, and coverage gates
  • refresh public documentation for the expanded local collection surface

Validation

  • python3 -B scripts/architecture_gate.py
  • python3 -B e2e/local_usage_matrix.py --self-check
  • cargo fmt --manifest-path client/Cargo.toml -- --check
  • cargo test --manifest-path client/Cargo.toml --lib agent::tests -- --nocapture
  • cargo test --manifest-path client/Cargo.toml --lib usage::tests -- --nocapture
  • cargo clippy --manifest-path client/Cargo.toml -- -D warnings
  • cd server-go && go vet ./...
  • cd server-go && go test -p 1 ./...
  • cd server-java && mvn verify -q
  • AITRACK_E2E_SERVER_URL=http://localhost:18080 bash e2e/run-client-e2e.sh external

Copilot AI review requested due to automatic review settings July 3, 2026 05:25
@claude

claude Bot commented Jul 3, 2026 •

Copy link
Copy Markdown

Claude finished @MapleEve's task in 3m 13s —— View job


Code Review Complete

Reviewed PR #43: Expand local agent usage coverage

Summary

This PR adds the usage_basis dimension to usage rollups, implements edit record retention/truncation, and expands the default agent scanning matrix. I've identified 7 actionable issues across contract compliance, concurrency safety, and data handling, plus validated the existing copilot findings.


Critical Issues

1. Java: Race condition in duplicate detection ⚠️

File: server-java/src/main/java/com/aitrack/server/application/IngestService.java:94

The existsByRecordSig() pre-check (line 94) is not atomic with the subsequent save(). Under concurrent uploads with the same record_sig, both requests can pass the check and the second will fail with a unique constraint violation, rolling back the entire transaction batch.

Impact: Legitimate duplicate submissions are rejected instead of being silently ignored.

Fix: Catch DataIntegrityViolationException on save and treat it as a benign duplicate (return false). The Go server already handles this correctly via ON CONFLICT DO NOTHING.

Fix this →


2. Java: Missing record_sig unique constraint in migration ⚠️

File: server-java/src/main/java/com/aitrack/server/infrastructure/config/EditRecordSchemaMigrator.java:33-34

The migrator only adds prompt_summary but does not create the uk_edit_records_record_sig unique index. While the entity annotation declares @UniqueConstraint, Hibernate's ddl-auto=update does not reliably add unique constraints to existing tables. Databases that existed before this PR may lack the constraint, rendering the existsByRecordSig check ineffective.

Impact: Without the DB-level constraint, duplicate record_sig values can be inserted, breaking deduplication guarantees.

Fix: Add the unique index creation to postgresMigrationSql() and the @PostConstruct migration:

"CREATE UNIQUE INDEX IF NOT EXISTS uk_edit_records_record_sig ON edit_records(record_sig)"

Fix this →


3. Go: Migration only handles empty string, not NULL ⚠️

File: server-go/internal/infrastructure/db/db.go:163

Line 163 normalizes usage_basis = '' to 'native', but does not handle NULL. If an existing database has NULL values (e.g., column added manually without a default, or from a prior incomplete migration), those rows will remain NULL and violate NOT NULL assumptions elsewhere.

Impact: Breaks rollup grouping and summary queries when NULL rows exist.

Fix: Change line 163 to:

UPDATE usage_daily_rollups SET usage_basis = 'native' WHERE usage_basis IS NULL OR usage_basis = ''

Fix this →


High Priority Issues

4. Client: Empty string → pruning marker conversion 🔶

Files:

  • client/src/adapter/sqlite/queries.rs:124-135 (mark_synced)
  • client/src/adapter/sqlite/queries.rs:329-358 (strip_retry_exhausted_pending_original_text)

Both functions use WHEN field IS NULL THEN NULL ELSE marker logic, which replaces both NULL and empty strings with pruning markers. This changes the semantics: an intentionally empty diff_hunk="" becomes "[aitrack-pruned:diff_hunk]", misrepresenting the record.

Impact: Empty strings are incorrectly flagged as "pruned by retention policy" instead of "originally empty."

Fix: Preserve empty strings:

WHEN diff_hunk IS NULL OR diff_hunk = '' THEN diff_hunk
ELSE ?marker

Fix mark_synced →

Fix strip_retry_exhausted →


5. Client: O(n²) cloning in batch splitter 🔶

File: client/src/uploader.rs:116-118

The split_upload_batches function clones the entire current Vec on every iteration to test the size limit. For a batch approaching the limit, this is O(n²) clone operations on potentially large strings (diff_hunk, metadata).

Impact: Performance degradation and memory churn on large uploads.

Fix: Push first, measure, then pop if exceeded:

current.push(row.clone());
if HttpUploader::payload_size_bytes(&current, device_id)? > max_body_bytes {
    current.pop();
    batches.push(std::mem::take(&mut current));
    current.push(row.clone());
}

Fix this →


Medium Priority Issues

6. Rust: Non-test expect() in production paths

File: client/src/lib.rs:116, 191, 617

Three production code paths use .expect("cannot find home directory"):

  • Line 116: handle_init
  • Line 191: handle_remove
  • Line 617: handle_capture

Impact: Panics instead of returning a proper error when HOME is unset or inaccessible.

Recommendation: Use dirs::home_dir().ok_or_else(|| anyhow!("HOME directory not found"))? for graceful error propagation.

Fix this →


7. CONTRACT.md: usage_basis field not documented

File: CONTRACT.md

The POST /api/v1/ai-track/usage/rollup section (lines 269-292) does not mention usage_basis, even though the PR adds it to the server schema and API response. The example at line 274-287 should include it.

Impact: Contract drift. Integrators won't know the field exists or how to use it.

Fix: Add usage_basis to the rollup item schema and update the example to show "usage_basis": "native".

Fix this →


Three-Way Sync Validation ✅

usage_basis field consistency:

  • ✅ Java: UsageDailyRollupEntity.java adds field + unique constraint includes it
  • ✅ Go: db.go adds field + unique constraint includes it
  • ✅ Client: N/A (client doesn't use rollups internally)
  • ⚠️ CONTRACT.md: Missing from /usage/rollup documentation (see issue revert: remove unauthorized ParadeDB CI/docs; fix Go version #7)
  • ✅ API.md: Documented at lines 557, 577, 636, 641

Security Review ✅

  • ✅ No signing keys or secrets in code
  • ✅ No internal identifiers exposed
  • ✅ HMAC logic unchanged
  • ✅ New usage_basis field is benign (no injection surface)
  • ✅ Truncation limits properly enforced (Java: 8192/4096/4096, Go: mirrors via retention)

Copilot Findings Validated

The copilot-pull-request-reviewer identified 6 findings. I've confirmed and expanded on them:

  1. ✅ EditRecordSchemaMigrator missing unique constraint → My issue chore(deps): bump github.com/jackc/pgx/v5 from 5.7.2 to 5.9.2 in /server-go #2 (critical)
  2. ✅ IngestService race condition → My issue Bump github.com/go-chi/chi/v5 from 5.1.0 to 5.2.2 in /server-go #1 (critical)
  3. ✅ mark_synced empty string handling → My issue chore(deps): bump github.com/jackc/pgx/v5 from 5.7.2 to 5.9.2 in /e2e #4 (high)
  4. ✅ strip_retry_exhausted empty string handling → My issue chore(deps): bump github.com/jackc/pgx/v5 from 5.7.2 to 5.9.2 in /e2e #4 (high)
  5. ✅ split_upload_batches O(n²) cloning → My issue docs: add CHANGELOG entry for fossa + stale workflows #5 (high)
  6. ✅ Go migration NULL handling → My issue chore(deps): bump golang.org/x/crypto from 0.31.0 to 0.45.0 in /server-go #3 (critical)

All copilot findings are accurate and actionable.


Verdict

Changes Requested — The PR adds valuable functionality but has 3 critical data-integrity issues that must be fixed before merge:

  1. Java duplicate handling race condition
  2. Java missing unique constraint migration
  3. Go NULL handling in usage_basis migration

The other 4 issues are recommended fixes that improve correctness and performance but are not blockers.


@codecov

codecov Bot commented Jul 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.56374% with 105 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.80%. Comparing base (b226783) to head (e5bdacf).

Files with missing lines Patch % Lines
client/src/lib.rs 88.78% 36 Missing ⚠️
client/src/adapter/sqlite/queries.rs 90.62% 21 Missing ⚠️
client/src/main.rs 0.00% 8 Missing ⚠️
...rver-go/internal/adapter/db/edit_record_adapter.go 85.96% 4 Missing and 4 partials ⚠️
server-go/internal/application/ingest_usecase.go 70.83% 5 Missing and 2 partials ⚠️
...a/com/aitrack/server/application/UsageService.java 90.90% 3 Missing and 4 partials ⚠️
...ructure/config/UsageDailyRollupSchemaMigrator.java 90.90% 3 Missing and 4 partials ⚠️
client/src/cli.rs 91.30% 2 Missing ⚠️
server-go/internal/domain/model/dto.go 84.61% 1 Missing and 1 partial ⚠️
...itrack/server/adapter/db/EditRecordRepository.java 66.66% 0 Missing and 2 partials ⚠️
... and 3 more
Additional details and impacted files
@@             Coverage Diff              @@
##               main      #43      +/-   ##
============================================
- Coverage     92.60%   90.80%   -1.81%     
- Complexity      245      301      +56     
============================================
  Files            85       89       +4     
  Lines         13958    41013   +27055     
  Branches        152      175      +23     
============================================
+ Hits          12926    37241   +24315     
- Misses          872     3593    +2721     
- Partials        160      179      +19     
Flag Coverage Δ
go 90.36% <86.06%> (+0.30%) ⬆️
java 85.57% <90.47%> (+0.24%) ⬆️
rust 90.96% <93.70%> (-2.62%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR expands “local agent usage” collection and reporting across the tool matrix by introducing a usage_basis dimension (native vs locally-derived), strengthening ingestion safeguards (bounded request decoding, dedup/idempotency, retention), and refreshing the E2E gates + documentation to match the expanded coverage surface.

Changes:

  • Add usage_basis to usage rollup ingestion + summary grouping, including schema migrations and new Java/Go tests.
  • Add edit-record retention + stored-text truncation + record signature idempotency safeguards across server + client.
  • Strengthen E2E matrix gating and update docs/readmes to reflect the expanded default tool set and the new API surface.

Reviewed changes

Copilot reviewed 64 out of 69 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
server-java/src/test/java/com/aitrack/server/infrastructure/config/UsageDailyRollupSchemaMigratorTest.java Tests usage rollup schema migration behavior for new 7-column uniqueness (usage_basis).
server-java/src/test/java/com/aitrack/server/infrastructure/config/EditRecordSchemaMigratorTest.java Tests edit_records migration adds prompt_summary.
server-java/src/test/java/com/aitrack/server/domain/model/EditRecordViewTest.java Tests prompt_summary flows into the API view model.
server-java/src/test/java/com/aitrack/server/application/UsageServiceSummaryTest.java Validates summary totals paging and rollup upsert idempotency with usage_basis.
server-java/src/test/java/com/aitrack/server/application/RepositoryIngestServiceTest.java Exercises retention stripping + truncation + duplicate idempotency paths for edit ingestion.
server-java/src/test/java/com/aitrack/server/application/IngestServiceTest.java Adds unit tests for retention invocation, dedup behavior, and truncation.
server-java/src/test/java/com/aitrack/server/adapter/handler/UsageControllerTest.java Adds controller-level tests for usage_basis behavior and gzip decoded-body size enforcement.
server-java/src/main/java/com/aitrack/server/infrastructure/config/UsageDailyRollupSchemaMigrator.java Adds runtime schema migrator to add usage_basis, drop legacy uniques, and create new unique index.
server-java/src/main/java/com/aitrack/server/infrastructure/config/EditRecordSchemaMigrator.java Adds runtime schema migrator to add prompt_summary to edit_records.
server-java/src/main/java/com/aitrack/server/domain/port/EditRecordPort.java Extends port with existsByRecordSig and raw-retention hook.
server-java/src/main/java/com/aitrack/server/domain/model/UsageSummaryItem.java Adds usage_basis field to summary response items.
server-java/src/main/java/com/aitrack/server/domain/model/UsageRollupItem.java Adds usage_basis field to rollup ingest items.
server-java/src/main/java/com/aitrack/server/domain/model/UsageDailyRollupEntity.java Extends uniqueness + entity schema to include usage_basis.
server-java/src/main/java/com/aitrack/server/domain/model/EditRecordView.java Adds prompt_summary to the API view.
server-java/src/main/java/com/aitrack/server/domain/model/EditRecordEntity.java Adds unique constraint on record_sig.
server-java/src/main/java/com/aitrack/server/application/UsageService.java Switches rollup ingestion to SQL batch upsert and summary to projection-based aggregation, adding usage_basis normalization.
server-java/src/main/java/com/aitrack/server/application/IngestService.java Adds stored-text truncation, idempotent dedup check, and raw retention invocation after saves.
server-java/src/main/java/com/aitrack/server/adapter/handler/UsageController.java Enforces decoded gzip body limit using bounded read.
server-java/src/main/java/com/aitrack/server/adapter/db/UsageDailyRollupRepository.java Adds summary totals/items projections + includes usage_basis in grouping.
server-java/src/main/java/com/aitrack/server/adapter/db/EditRecordRepository.java Adds raw-retention implementation + record_sig existence query and dedup support.
server-java/README.md Documents usage summary endpoint and usage_basis.
server-go/README.md Documents usage summary endpoint and usage_basis.
server-go/internal/infrastructure/db/db.go Adds DB DDL/migrations for edit record unique sig and rollup usage_basis.
server-go/internal/infrastructure/db/db_internal_test.go Validates DDL contains usage_basis and legacy constraint drops.
server-go/internal/domain/port/edit_record_port.go Adds retention port contract.
server-go/internal/domain/model/usage.go Adds UsageBasis in rollups and summary items.
server-go/internal/domain/model/usage_test.go Tests defaulting + validation behavior for usage_basis.
server-go/internal/domain/model/dto.go Adds custom JSON unmarshal to normalize/validate usage_basis.
server-go/internal/CLAUDE.md Documentation tweak for internal package conventions.
server-go/internal/application/ingest_usecase.go Adds truncation and retention application after successful save.
server-go/internal/application/ingest_usecase_test.go Tests truncation, idempotency, and retention behavior.
server-go/internal/adapter/handler/usage.go Adds bounded gzip read limit check.
server-go/internal/adapter/handler/usage_test.go Adds tests for usage_basis grouping/defaulting and gzip decoded-size rejection.
server-go/internal/adapter/db/usage_adapter.go Updates rollup upsert + summary grouping to include usage_basis.
server-go/internal/adapter/db/edit_record_retention_test.go Adds adapter-level retention tests (skipping when DB unavailable).
server-go/internal/adapter/db/edit_record_adapter.go Adds ON CONFLICT(record_sig) DO NOTHING and retention stripping implementation.
README.zh-CN.md Updates public docs for expanded default matrix and behavior guarantees.
README.md Updates public docs for expanded default matrix and behavior guarantees.
e2e/run-client-e2e.sh Expands matrix, strengthens expected-source validation, adds bounded outbox and post-sync assertions, improves docker build diagnostics.
docs/TESTING.md Minor test name correction.
docs/SECURITY_MODEL.md Updates docs around default scan key count and minor wording.
docs/ROADMAP.md Updates roadmap text to reflect expanded default matrix and revised phrasing.
docs/RELEASE_NOTES_v1.7.0.md Updates release notes to reflect expanded matrix and new assertions.
docs/PRIVACY.md Updates privacy wording and default scan key count.
docs/DEVELOPMENT.md Updates developer docs for expanded default matrix and alias normalization.
docs/DEPLOYMENT.md Updates deployment docs paths and default scan key count.
docs/ARCHITECTURE.md Updates architecture docs for expanded default scan key count.
docs/API.md Updates API docs for usage_basis rollup keying and response shape, plus repo_url examples.
docs/AGENT_SUPPORT.md Major update describing source-tiering and expanded default scan list.
docker/Dockerfile.server-java Improves Maven build caching and retry settings; updates Dockerfile syntax directive.
client/src/uploader.rs Adds upload body-size bounded batching + tests and ensures synced records are pruned.
client/src/main.rs Skips banner for usage probe to keep probe output clean.
client/src/lib.rs Adds usage probe, journals hook events for known agents, prunes local storage, and truncates prompt capture consistently.
client/src/init.rs Updates tests around canonical tool key handling (alias removal from expected list).
client/src/domain/model.rs Centralizes truncation limits and sanitization helpers.
client/src/cli.rs Adds usage probe command + argument parsing tests.
client/src/adapter/sqlite/schema.rs Adds SQLite pragmas + new indexes for size/queue maintenance.
client/src/adapter/sqlite/queries.rs Adds pruning/retention logic for local storage and prompt context and changes mark_synced behavior.
client/src/adapter/sqlite/mod.rs Exposes new prune helpers and updates test factory record_sig uniqueness.
client/src/adapter/http/upload.rs Exposes payload builder/size helpers for batching.
client/README.md Updates client README to match expanded default matrix and sourcing semantics.
CHANGELOG.md Updates changelog for expanded default matrix and updated test counts.
.gitignore Adds common coverage artifacts and python cache ignores; keeps .env.example.
.github/ISSUE_TEMPLATE/feature_request.yml Tightens privacy language to “private links/sensitive paths/logs”.
.github/ISSUE_TEMPLATE/bug_report.yml Tightens privacy language to “private links/sensitive paths/logs”.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +33 to +34
executeRequired(connection, addPromptSummarySql());
}
Comment on lines 117 to +121
entity.setStatus(status);
entity.setFlags(flags.isEmpty() ? null : String.join(",", flags));
entity.setReceivedAt(Instant.now());
editRecordPort.save(entity);
return true;
Comment on lines +124 to +128
diff_hunk = CASE
WHEN diff_hunk IS NULL THEN NULL
ELSE ?{diff_marker}
END,
metadata = CASE
Comment on lines +332 to +336
SET diff_hunk = CASE
WHEN diff_hunk IS NULL THEN NULL
ELSE ?1
END,
metadata = CASE
Comment thread client/src/uploader.rs
Comment on lines +111 to +125
for row in rows {
let count_full = current.len() >= max_count;
let byte_full = if current.is_empty() {
false
} else {
let mut candidate = current.clone();
candidate.push(row.clone());
HttpUploader::payload_size_bytes(&candidate, device_id)? > max_body_bytes
};

if count_full || byte_full {
batches.push(std::mem::take(&mut current));
}
current.push(row.clone());
}
Comment on lines +162 to +164
`ALTER TABLE usage_daily_rollups ADD COLUMN IF NOT EXISTS usage_basis TEXT NOT NULL DEFAULT 'native'`,
`UPDATE usage_daily_rollups SET usage_basis = 'native' WHERE usage_basis = ''`,
`ALTER TABLE usage_daily_rollups DROP CONSTRAINT IF EXISTS usage_daily_rollups_token_key_device_id_day_agent_model_account_key`,
@MapleEve
MapleEve merged commit b396b5f into main Jul 3, 2026
18 checks passed
@MapleEve
MapleEve deleted the maple/all-agent-full-data-support branch July 3, 2026 08:02
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