Skip to content

Add unified-session BM25 audit search with automatic evidence grouping - #70998

Merged
pelikhan merged 3 commits into
mainfrom
pelikhan-urban-adventure
Oct 22, 2026
Merged

pelikhan merged 3 commits into
mainfrom
pelikhan-urban-adventure

Conversation

@pelikhan

Copy link
Copy Markdown
Collaborator

Summary

Audits expose deterministic findings and metrics, but locating the relevant event inside a large session still requires scanning logs. This adds optional local evidence retrieval over the actual redacted unified session, without changing audit completeness, findings, severity, or confidence.

  • Add single-run gh aw audit RUN_ID --search "query" --search-limit 5 with JSON and console output. Read usage/aw_session.jsonl or root aw_session.jsonl; never substitute native engine logs or synthesized run summaries.
  • Rank decoded event fields and event types with in-memory BM25. Preserve paths, domains, tool names, error codes, source references, and neighboring chronology. Exact repeats share ranking statistics.
  • Enable Drain3 automatically only when repetitive top matches crowd the requested slots and grouping saves excerpt text. Templates and anomaly scores never influence BM25 ranking. Structured outcomes partition groups so successful and failed events cannot share occurrence counts. No additional configuration is required.
  • Bound input, result count, excerpts, and total returned text. Missing, invalid, unsupported, oversized, or symlinked session inputs produce explicit errors. Keep query-specific results out of shared audit caches.
  • Update audit reference documentation and agent instructions to distinguish retrieved evidence groups from fleet failure clusters and audit --group finding codes.

Validation

  • Build and formatting completed; change-scoped standard and custom Go lint passed.
  • Audit compatibility regressions and race-enabled search tests passed, including automatic activation, rank invariance, outcome partitions, provenance, output bounds, and cache isolation.
  • All 24 guidance contract tests passed.
  • Compiled 346 workflows successfully with no lock-file drift. Existing workflow warnings remain unchanged.

Live evaluation

Collected unified sessions from 1,000 completed runs across 231 workflows. Of these, 999 were searchable; one correctly failed the existing record-size limit. Replayed six fixed queries per searchable session: 5,994 query evaluations over 399,905 events. No workflows were dispatched.

Across 1,879 query/session cases with structured relevant evidence:

Measure BM25 Automatic grouping
Relevant first result 1,664 1,664
Relevant result in top five 1,780 1,782
Average returned text 4.00 KB 4.08 KB

Grouping appeared in 13.9% of queries. The replay verified unchanged first-result identities and scores, outcome-safe group counts, source references, and output bounds.

These are structured-field relevance proxies, not human-rated diagnostic outcomes or fleet-health claims. The sample selects available artifacts: 587 additional inspected runs lacked usage artifacts. Raw transcripts and local evaluation artifacts are not included in this PR.

pelikhan and others added 2 commits October 21, 2026 16:48
Keep BM25 ranking independent of Drain3, mine only crowded results, and retain template groups only when they save excerpt text. Preserve structured outcomes and use compact exact-duplicate counts without mining. Update audit guidance and regression coverage.

Co-authored-by: Copilot App <[email protected]>
@pelikhan
pelikhan marked this pull request as ready for review October 22, 2026 02:16
Copilot AI max review requested due to automatic review settings October 22, 2026 02:16
@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

✅ Design Decision Gate 🏗️ completed the design decision gate check. See the comment below for the result and any generated ADR draft.

🏗️ ADR gate enforced by Design Decision Gate 🏗️

@github-actions

Copy link
Copy Markdown
Contributor

🔬 Test Quality Sentinel is analyzing test quality on this pull request...

@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

🧠 Matt Pocock Skills Reviewer has completed the skills-based review. ✅

🧠 Reviewed using Matt Pocock's skills by Matt Pocock Skills Reviewer

@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

✅ PR Code Quality Reviewer completed the code quality review.

🔎 Code quality review by PR Code Quality Reviewer

@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

✅ Ponytail Reviewer completed successfully!

Ponytail Reviewer

Outcome: reported_no_action

The agent completed and reported no action. A no-op output alone does not verify that all required work was completed or that publication was possible.

Agent messages are omitted from this comment. The category uses structured run status, not interpretation of agent prose.

Generated from Ponytail Reviewer · gpt56 · 21.1 AIC · ⌖ 5.48 AIC · ⊞ 14.8K · ◷

Generated by Ponytail Reviewer for #70998

Regenerate audit and logs-jsonl schemas for the evidence_search field added by the audit evidence retrieval changes.

Co-authored-by: Copilot App <[email protected]>
@github-actions

Copy link
Copy Markdown
Contributor

🏗️ Design Decision Gate — ADR Required

This PR has more than 100 new lines in core business logic (1,388 additions in pkg/), but it does not link an Architecture Decision Record (ADR).

📄 Draft ADR committed: docs/adr/70998-unified-session-bm25-audit-search-with-automatic-drain3-grouping.md. Review and complete it before merging.

The draft records this decision: add gh aw audit --search, which uses in-memory BM25 to search the unified session only (aw_session.jsonl) and never falls back to native logs. Drain3 grouping turns on automatically, never changes ranking, and keeps successful and failed outcomes in separate groups. Results stay out of the shared audit cache. The draft compares this with three alternatives: falling back to native logs, a persistent or semantic index, and grouping that is always on or controlled by a flag.

🔒 This PR cannot merge until an ADR is linked in the PR body.

📋 What to do next
  1. Review the draft ADR on your branch. It was generated from the PR diff and description.
  2. Complete or correct the sections: confirm who made the decision, refine the reasoning, and replace any alternatives you did not actually consider.
  3. Commit the finalized ADR to docs/adr/ on your branch.
  4. Reference the ADR in this PR body with a line such as:

    ADR: ADR-70998: Unified-Session BM25 Audit Search with Automatic Drain3 Evidence Grouping

After the PR body links an ADR, this gate runs again and checks that the implementation matches the decision.

❓ Why ADRs Matter

ADRs create a searchable, permanent record of why the codebase looks the way it does. Future contributors, including your future self, will benefit from it.

📋 Michael Nygard ADR Format Reference

A complete ADR has these four sections:

  • Context: What is the problem, and what constraints apply?
  • Decision: What was decided, and why?
  • Alternatives Considered: What other options were there?
  • Consequences: What are the positive and negative trade-offs?

ADRs are stored in docs/adr/ as Markdown files numbered by PR number.

🏗️ ADR gate enforced by Design Decision Gate 🏗️ · pi · opus55 · 29.3 AIC · ⌖ 40.6 AIC · ⊞ 1.9K · ◷
Comment /review to run again

@github-actions

Copy link
Copy Markdown
Contributor

Comment Memory

Peek at saved memory (pr-code-quality-reviewer)
reviewed_at: 2026-10-22T02:25:00Z
review_event: REQUEST_CHANGES
top_themes: exact duplicate evidence with different structured outcomes is merged into one ungrouped occurrence count
files_reviewed: pkg/cli/audit_search.go, pkg/cli/audit_search_grouping.go, pkg/cli/audit_search_session.go, pkg/cli/audit_run_pipeline.go, pkg/cli/audit_render_output.go
comment_count: 1

Note

This comment is managed by comment memory.

Expand the saved memory block to view or edit the persistent context for this thread.
Edit only the text inside the backtick fences; workflow metadata and the footer are regenerated automatically.

Learn more about comment memory

🔎 Code quality review by PR Code Quality Reviewer · copilot · gpt50 · 2.98 AIC · ⌖ 0.685 AIC · ⊞ 1.6K · ◷
Comment /review to run again

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict

Request changes: exact duplicate evidence with different structured outcomes is currently merged into one ungrouped result, which misreports success/failure occurrence counts.

Details
  • pkg/cli/audit_search.go: the zero-cluster key is based only on stage and text, while BM25 deduplication intentionally ignores outcome. This needs a separate outcome partition before counts are emitted.
  • No tests were run; this was a static review of the pre-fetched diff.

🔎 Code quality review by PR Code Quality Reviewer · copilot · gpt50 · 2.98 AIC · ⌖ 0.685 AIC · ⊞ 1.6K
Comment /review to run again

Comment thread pkg/cli/audit_search.go
}

func auditEvidenceClusterKey(doc auditSearchDocument) string {
if doc.clusterID == 0 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Exact duplicate events with different structured outcomes are collapsed into the same ungrouped key here, so successes and failures can be reported as one occurrences/matching_occurrences total even though outcome partitioning is required.

💡 Keep outcome partitions for exact duplicates

rankAuditEvidence deduplicates by stage + text, and when Drain3 is not enabled clusterID remains zero, making auditEvidenceClusterKey identical for every outcome variant. selectAuditEvidence then counts all of them together. For a retry stream containing identical success and failure payload text, this produces a misleading combined count and loses the outcome distinction. Include the outcome in the unmined grouping key (while retaining outcome-independent BM25 deduplication), or partition exact-duplicate representatives before counting.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Skills-Based Review 🧠

Applied /tdd and /codebase-design (via pr-triage: new_feature). Thorough, well-tested feature addition; only a minor maintainability nit flagged inline.

📋 Key Themes & Highlights

Review scope

Reviewed pkg/cli/audit_search.go, audit_search_grouping.go, audit_search_session.go, audit_command.go, and audit_run_pipeline.go (the pr-triage high-impact set), plus the full new test suites (audit_search_test.go, audit_search_grouping_test.go) and doc updates. Verified go build ./... succeeds and go test ./pkg/cli/... -run TestAuditSearch passes (all test functions/subtests green), along with the new test_guidance.py contract test.

Positive highlights (/tdd)

  • ✅ Excellent test coverage: BM25 scoring math is asserted against a closed-form expected value (TestAuditSearchBM25), not just snapshot comparisons.
  • ✅ Dedicated invariance tests prove Drain3 grouping never perturbs BM25 ranking ("Drain3 must never change BM25 scores or ranks") — a strong regression guard for the PR's core safety claim.
  • ✅ Boundary/cancellation tests cover all declared limits (64 MiB, 20k events, 256 stages, 64-level nesting, context cancellation) with explicit error-string assertions.
  • ✅ Cache-isolation test (TestAuditSearchReportDoesNotChangeFindingsOrCache) confirms --search never mutates deterministic cached audit data on disk — directly verifies a key safety property called out in the PR description.
  • ✅ UTF-8 offset-mapping edge cases (case-folding expanding byte length) are specifically tested in TestAuditSearchOutputBoundsAndExcerpt.

Minor finding (/codebase-design)

  • The 256-stage limit check is duplicated between clusterAuditEvidence (audit_search.go) and validateAuditSearchStages (audit_search_grouping.go). Both are exercised by tests and correct today, but a shared constant/helper would prevent future drift — see inline comment.

Documentation (/grill-with-docs)

  • New vocabulary ("evidence group", "BM25 relevance", run-local Drain3 cluster IDs) is consistently distinguished from existing fleet failure_clusters and audit --group finding codes across analyzing-runs.md, cli-commands.md, debug-agentic-workflow.md, instructions.md, and the debugging-workflows skill — reinforced by a new guidance contract test. No ambiguity introduced into the existing audit vocabulary.

@copilot please address the review comments above.

🧠 Reviewed using Matt Pocock's skills by Matt Pocock Skills Reviewer · copilot · sonnet50 · 128.2 AIC · ⌖ 15.1 AIC · ⊞ 10.2K
Comment /matt to run again

for _, doc := range docs {
stages[doc.stage] = struct{}{}
if len(stages) > 256 {
return errors.New("unified session exceeds the 256-stage search input limit")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[/codebase-design] The 256-stage limit check is duplicated verbatim in clusterAuditEvidence (audit_search.go:213) and validateAuditSearchStages here. Low risk today, but if the bound ever changes one call site will silently drift from the other.

💡 Suggested consolidation

Extract a shared helper, e.g.:

const maxAuditSearchStages = 256

func countAuditSearchStages(docs []auditSearchDocument) (map[string]struct{}, error) {
    stages := make(map[string]struct{})
    for _, doc := range docs {
        stages[doc.stage] = struct{}{}
        if len(stages) > maxAuditSearchStages {
            return nil, fmt.Errorf("unified session exceeds the %d-stage search input limit", maxAuditSearchStages)
        }
    }
    return stages, nil
}

and have both call sites use it. This is a minor maintainability nit, not a correctness bug — the current duplicated checks are both exercised and passing in audit_search_grouping_test.go/audit_search_test.go.

@copilot please address this.

@github-actions

Copy link
Copy Markdown
Contributor

🧪 Test Quality Sentinel Report

✅ Test Quality Score: 89/100 — Excellent

Analyzed 20 test(s): 8 design, 12 implementation, 0 violation(s).

📊 Metrics (20 tests)
Metric Value
Analyzed 20 (Go: 20, JS: 0)
✅ Design 8 (40%)
⚠️ Implementation 12 (60%)
Edge/error coverage 13 (65%)
Duplicate clusters 0
Inflation ✅ No (1.58:1 ratio)
🚨 Violations 0
Category Count Examples
Behavioral contracts 8 BM25 ranking, session parsing, automatic grouping, provenance
Error handling 13 Invalid sessions, size limits, cancellation, Unicode edge cases
Table-driven tests 30+ Field partitioning (14 variants), scenario-driven
Build tags ✅ All have (go/redacted):build !integration —
Mock libraries 0 (none used) Uses testify/assert, testify/require only

Test Quality Highlights

Excellent design coverage:

  • TestAuditSearchBM25: Verifies ranking algorithm with deterministic precision (delta: 0.000001)
  • TestAuditSearchUnifiedSession: Validates session structure, JSON unmarshaling, and output constraints
  • TestAuditSearchDrainGrouping: Confirms automatic Drain3 clustering behavior
  • TestAuditSearchOutcomePartitions: Parametric test covering 14 distinct outcome field types

Strong edge-case protection:

  • Input limits: 20,000-event cap, 64 MiB session size, oversized-line detection
  • Output bounds: 10 MiB text budget with excerpt truncation; Unicode validity verification
  • 256-stage Drain3 clustering limit enforced
  • Cancellation context propagation (context.Canceled)

Data integrity invariants:

  • BM25 scores and ranks must never change after clustering (assert.Equal(t, raw, after, "...must never change..."))
  • Outcome counts preserved across partitioning
  • Cache stability under search operations
  • Provenance tracking (native paths, agent IDs, indices)

Scoring Breakdown

score = ((design_tests / total_new_tests) * 40) +
        ((tests_with_edge_cases / total_new_tests) * 30) +
        (20 - min(duplicate_clusters * 5, 20)) +
        (0 if inflation_ratio > 2:1 else 10)

score = ((8 / 20) * 40) +
        ((13 / 20) * 30) +
        (20 - 0) +
        10

score = 16 + 19.5 + 20 + 10 = 89/100 ✅

Verdict

✅ passed. 60% implementation tests (threshold: 30%). All hard violations are absent: no forbidden mocks, build tags present, test inflation within bounds, and comprehensive behavioral coverage.

🧪 Test quality analysis by Test Quality Sentinel · copilot · haiku45 · 86 AIC · ⌖ 10.1 AIC · ⊞ 9.2K · ◷
Comment /review to run again

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ Test Quality Sentinel: 89/100 — Excellent. 60% implementation tests (threshold: 30%). All hard violations absent: no forbidden mocks, build tags present, inflation within bounds (1.58:1), and comprehensive behavioral coverage across 20 tests with 13+ edge cases and 8 design contracts.

🧪 Test quality analysis by Test Quality Sentinel · copilot · haiku45 · 86 AIC · ⌖ 10.1 AIC · ⊞ 9.2K
Comment /review to run again

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Warning

Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.

Copilot review overview

4 open issues
What changed in this PR

Adds optional, query-specific evidence retrieval to gh aw audit by locally searching the redacted unified session with BM25 and (when beneficial) automatic Drain3 grouping, while ensuring deterministic audit findings/caches remain unchanged.

Changes:

  • Introduces --search / --search-limit flags and plumbs results into audit rendering without persisting query output to shared caches.
  • Implements unified-session parsing, BM25 ranking, bounded excerpts/context, and automatic repetition grouping with outcome-safe partitions.
  • Updates JSON schemas and documentation/guidance to describe the new evidence_search output and its guarantees/limitations.
File Description
schemas/​logs-jsonl.schema.json Adds evidence_search shape to logs JSONL schema for emitted search results.
schemas/​audit.schema.json Adds evidence_search to audit JSON schema for stable JSON output validation.
pkg/​cli/​audit_search_test.go Adds comprehensive unit tests for tokenization, BM25, session provenance, bounds, output truncation, and CLI option interactions.
pkg/​cli/​audit_search_session.go Implements unified-session discovery, bounded parsing, and field flattening into searchable documents.
pkg/​cli/​audit_search_grouping_test.go Tests automatic Drain3 activation criteria, rank invariance, and outcome partitioning.
pkg/​cli/​audit_search_grouping.go Implements outcome detection, stage limits, and “useful grouping” selection logic.
pkg/​cli/​audit_search.go Implements BM25 ranking, optional grouping, excerpting, and console rendering of evidence search results.
pkg/​cli/​audit_run_pipeline.go Threads Search/SearchLimit through run config and ensures cache bypass/marker invalidation when session is missing.
pkg/​cli/​audit_report_render.go Renders evidence_search in console output.
pkg/​cli/​audit_report.go Extends AuditData with EvidenceSearch field for JSON/console reports.
pkg/​cli/​audit_render_output.go Ensures evidence search is computed at render time and not written into deterministic caches.
pkg/​cli/​audit_command.go Adds CLI flags, validation, and compatibility constraints for single-run --search.
pkg/​cli/​audit_cache.go Ensures EvidenceSearch is never persisted in the cached audit file.
pkg/​cli/​audit.go Extends AuditOptions and run config with search fields.
docs/​src/​content/​docs/​reference/​audit.md Documents --search behavior, bounds, grouping semantics, and interpretation guidance.
.github/​skills/​debugging-workflows/​SKILL.md Adds guidance on using evidence_search vs other clustering/grouping concepts.
.github/​skills/​agentic-workflows/​tests/​test_guidance.py Adds contract test to ensure guidance text includes required --search caveats and distinctions.
.github/​aw/​instructions.md Updates agent instructions to incorporate audit --search usage and interpretation constraints.
.github/​aw/​debug-agentic-workflow.md Adds debugging workflow guidance for using evidence_search responsibly.
.github/​aw/​cli-commands.md Adds CLI examples and guardrails around --search.
.github/​aw/​analyzing-runs.md Adds a dedicated section explaining session evidence retrieval and clustering distinctions.

Review effort: Lite

Comment thread pkg/cli/audit_search.go
// Preserve exact identifiers as well as their components, without stemming paths or error codes.
func auditSearchTokens(text string) []string {
var tokens []string
for word := range strings.FieldsFuncSeq(strings.ToLower(text), func(r rune) bool {
Comment thread schemas/audit.schema.json
Comment on lines 5565 to 5575
if len(bytes.TrimSpace(line)) > 0 {
var event auditSearchSessionEvent
if err := json.Unmarshal(line, &event); err != nil {
return nil, fmt.Errorf("invalid unified session search record on line %d", lineNumber)
Comment thread pkg/cli/audit_search.go
Comment on lines +247 to +250
matching := make(map[string]int)
for _, hit := range ranked {
doc := docs[hit.index] //nolint:uncheckedsliceindex // ranked indexes come from ranging over this document slice
matching[doc.stage+"\n"+doc.text] = hit.index
@pelikhan
pelikhan merged commit f504dc0 into main Oct 22, 2026
37 checks passed
@pelikhan
pelikhan deleted the pelikhan-urban-adventure branch October 22, 2026 02:49
@github-actions

Copy link
Copy Markdown
Contributor

🎉 This pull request is included in a new release.

Release: v0.93.1

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