Skip to content

feat(review): add optional behavior and impact analysis - #1937

Merged
lizhengfeng101 merged 27 commits into
mainfrom
feat/review-analysis
Nov 21, 2026
Merged

lizhengfeng101 merged 27 commits into
mainfrom
feat/review-analysis

Conversation

@lizhengfeng101

@lizhengfeng101 lizhengfeng101 commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

ocr review --analysis runs a read-only Behavior/Impact investigation in parallel with the existing code review. Review still selects its own files, uses its usual concurrency and budgets, and determines the exit status. A failed or skipped Analysis is reported separately.

How Analysis works

  • For commit and range reviews, Analysis uses the base and head SHAs resolved by Review. In workspace mode, the new side is the live working tree, not a commit snapshot. Analysis builds its own change inventory and respects file exclusions. If it cannot reproduce the active Git view, it skips the investigation rather than changing Review's inputs.
  • Analysis has its own session and can make at most one additional concurrent model request. It defaults to 300 investigation rounds, independent of Review's --max-tools. If the round or token budget is exhausted, at most one additional round is available for submit_analysis only; it cannot read or search for more evidence.
  • --analysis-max-tokens-budget sets a soft token limit for Analysis only. The default is 0 (unlimited). The Review summary reports Review usage; analysis_meta.usage reports Analysis usage.
  • Text output appends the report. JSON output uses ocr.review-with-analysis/v2 and records execution status separately from the model's assessment of completeness. --analysis is not supported with --preview, --resume, or SARIF output.

Validation

At 5fac2817, make check and the race-enabled make test passed (28 packages). make coverage reported 91.5% against a 90% minimum. The pre-commit ocr review reported 20 findings across 28 selected files; this count is not a claim that all findings are confirmed or resolved.

AI/LLM disclosure

Implementation and PR preparation used OpenAI Codex with gpt-6-astra. Automated pre-commit reviews used OpenCodeReview (ocr) with gpt-6-astra and, for 5fac2817, gpt-6.2-astra.

@github-actions

github-actions Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

🔍 OpenCodeReview found 8 issue(s) in this PR.

  • ✅ Successfully posted inline: 8 comment(s)

Comment thread cmd/opencodereview/output.go Outdated
Comment on lines +444 to +445
payload.Status = combined.status()
payload.Message = fmt.Sprintf("Review: %s. Analysis execution: %s. Model-declared completeness: %s (not a quality guarantee).", combined.ReviewStatus, combined.Report.Status, combined.Report.DeclaredCompletion)

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.

maintainability · medium
When analysis is enabled, payload.Status is overwritten with the combined status from combined.status(), which returns "partial" when either the review or analysis didn't complete successfully. This means a fully successful review paired with a failed analysis will report status: "partial" at the top level, potentially misleading downstream consumers that parse only the status field to determine review success.

Consider keeping the review's own status in the top-level status field and using a separate field (e.g., analysis_status) for the combined or analysis-specific status. Alternatively, document this semantic change clearly in the schema version bump (ocr.review-with-analysis/v2).

Comment on lines +229 to +232
match := numberedLine.FindStringSubmatch(line)
if match == nil || !code.allowed[side][filePath] {
continue
}

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.

bug · low
Inconsistent authorization check: this uses code.allowed[side][filePath] (raw map lookup) instead of code.fileAllowed(side, filePath). In workspace mode, fileAllowed additionally verifies the file still exists on disk as a regular non-symlink file via regularWorkspaceFile. While the actual content access is properly gated elsewhere, location metadata could reference files that have been deleted or replaced with symlinks since the allowed map was populated, producing stale/incorrect location entries in observations.

Suggestion:

Suggested change
match := numberedLine.FindStringSubmatch(line)
if match == nil || !code.allowed[side][filePath] {
continue
}
match := numberedLine.FindStringSubmatch(line)
if match == nil || !code.fileAllowed(side, filePath) {
continue
}

Comment on lines +28 to +35
for _, captured := range runner.contexts {
if captured.Kind == kind && captured.ID == id {
content = captured.Content
captured.Content = ""
observation.Context = &captured
break
}
}

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.

bug · high
Bug: captured is a value copy from ranging over runner.contexts (a []Context slice). Setting captured.Content = "" only clears the copy, not the original element in runner.contexts. This means the "consume once" semantics are broken — repeated calls to readContext with the same kind/id will always return the full content.

To fix, iterate by index so you can modify the original slice element:

Suggestion:

Suggested change
for _, captured := range runner.contexts {
if captured.Kind == kind && captured.ID == id {
content = captured.Content
captured.Content = ""
observation.Context = &captured
break
}
}
for i := range runner.contexts {
if runner.contexts[i].Kind == kind && runner.contexts[i].ID == id {
content = runner.contexts[i].Content
runner.contexts[i].Content = ""
copy := runner.contexts[i]
observation.Context = &copy
break
}
}

Comment on lines +23 to +26
data, err := templateFS.ReadFile("behavior_template.json")
if err != nil {
return nil, err
}

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.

maintainability · medium
Unlike LoadDefault() in the same package, LoadBehaviorDefault returns raw errors without contextual wrapping. When loading fails (e.g., a missing prompt file or malformed JSON), the caller gets no indication of which step failed. Consider wrapping each error with context, consistent with the existing pattern:

return nil, fmt.Errorf("read embedded behavior_template.json: %w", err)
// ...
return nil, fmt.Errorf("unmarshal behavior_template manifest: %w", err)
// ...
return nil, fmt.Errorf("MAIN_TASK: %w", err)

This is especially important because resolveConversation already wraps prompt-file errors, but the unmarshal and ReadFile errors here are bare.

Comment on lines +60 to +62
if !slices.Equal(actual, expected) || !slices.Equal(tpl.FinalRound.Tools, []string{"submit_analysis"}) || len(tpl.MemoryCompressionTask.Tools) != 0 {
return fmt.Errorf("behavior template has invalid tool bindings")
}

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.

maintainability · low
This single error message covers three distinct validation failures (MainTask tool set mismatch, FinalRound tool set mismatch, or MemoryCompressionTask having tools). When validation fails, the caller has no way to determine which check failed. Consider returning specific error messages for each condition, similar to how Template.Validate() and ScanTemplate.Validate() return targeted errors for each field.

Comment thread internal/llmloop/loop.go
Comment on lines +357 to +359
if errors.Is(err, llm.ErrTokenBudget) {
return false, StopTokenBudget, nil
}

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.

bug · high
When the LLM client returns ErrTokenBudget (e.g., from the shared budgetClient wrapper), this early return skips the grace round entirely. However, when the local pre-request check (tokenBudgetExceeded()) detects budget exhaustion, the loop breaks and the grace round is attempted (lines 459-464). Both paths represent the same condition — budget exhausted — but produce different behavior.

To be consistent, this should break out of the loop (like the local check does) so the grace round can still run:

Suggestion:

Suggested change
if errors.Is(err, llm.ErrTokenBudget) {
return false, StopTokenBudget, nil
}
if errors.Is(err, llm.ErrTokenBudget) {
stop = StopTokenBudget
break
}

Comment on lines +57 to +63
budget.mu.Lock()
if budget.maximum > 0 && budget.usage.InputTokens+budget.usage.OutputTokens >= budget.maximum {
budget.exhausted = true
budget.mu.Unlock()
return nil, llm.ErrTokenBudget
}
budget.mu.Unlock()

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.

bug · medium
Budget over-admission due to check-then-act race. The budget check (lines 57-63) releases the lock before making the LLM call (line 64), and only updates usage after the response returns (lines 88-93). With concurrency slots (default 8), up to concurrency requests can simultaneously pass the budget check before any of them record their token usage. This means actual spend can exceed maximum by up to (concurrency - 1) full LLM calls' worth of tokens.

Consider holding the lock across both the check and a reservation/commit step, or using an atomic counter to reserve estimated tokens before the call and reconcile afterward. A simpler alternative is to re-check the budget after updating usage and set exhausted eagerly so subsequent admissions fail faster.

Comment thread internal/workflow/report.go Outdated
Comment on lines +40 to +42
Errors: append([]string{}, result.Errors...), Warnings: result.Warnings, ToolFailures: result.ToolFailures, Usage: result.Usage, Model: result.Model,
TemplateVersion: result.TemplateVersion, ToolsVersion: result.ToolsVersion, SessionID: result.SessionID, ArtifactDir: directory, ObservationIDs: result.ObservationIDs,
CitedObservationIDs: append([]string{}, result.CitedObservationIDs...), ContextIndex: result.ContextIndex}

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.

maintainability · medium
Inconsistent defensive copying: Errors and CitedObservationIDs are defensively copied via append([]string{}, ...), but Warnings, ToolFailures, Scope, ObservationIDs, and ContextIndex share backing arrays with the original result slices. Since result is passed by value, these slice headers point to the same underlying arrays. If the caller retains and later mutates the original Result, or if the Report fields are mutated downstream, they can silently corrupt each other.

Recommendation: Either copy all slice fields consistently, or document that the Report intentionally shares ownership of these slices with the source Result.

@MuoDoo MuoDoo left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM

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