Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
schema: spec-driven
created: 2026-10-26
skip_specs: true
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Design

## Context

See `proposal.md` for problem motivation and background.
`src/devops_cli/review/analysis.py` defines two model-driven review jobs:
- `_execute_single_group_job`: validates group replies through `_judge_group_reply`, enforces `max_retries=0`, and catches `ReplyRejectedError` (#1013).
- `run_review_plan_job`: calls `llm_client.chat(...)` without a validator, allowing unverified or invalid plans to enter the response cache.

## Goals / Non-Goals

**Goals:**
- Validate review plan replies before the response cache stores them.
- Send review plan chat requests with `max_retries=0`.
- Catch `ReplyRejectedError` to inspect the rejected reply and record rejection reasons.
- Share the chat-and-judge workflow between `_execute_single_group_job` and `run_review_plan_job`.
- Add test coverage driving `run_review_plan_job` through a real `LLMClient` with mock transport and isolated disk cache.

**Non-Goals:**
- Modify G10 plan validation rules in `verify_review_plan`.
- Modify pipeline orchestrator stages or stage flag defaults.

## Decisions

### 1. Extract shared `_chat_and_judge` execution helper

Both jobs follow the same workflow:
1. Define a `judge` function returning `(parsed_output, rejection_reasons)`.
2. Wrap `judge` in an `accept` closure that caches verdicts by reply text.
3. Call `llm_client.chat(..., max_retries=0, validator=accept)`.
4. Catch `ReplyRejectedError` and extract `rejected.reply`.
5. Check if `finish_reason == CONST_FINISH_REASON_LENGTH` to set `reply-truncated`.
6. Return `(verified_output, reasons, is_cached)`.

Extracting `_chat_and_judge` avoids duplication across the two jobs.

*Alternative considered:* Copy the chat, validator, and exception handling directly into `run_review_plan_job`.
*Evidence rejecting alternative:* Copying duplicates 30 lines of error-handling and cache-checking logic. Issue #1810 explicitly directs sharing the step.

### 2. Parse and verify review plan output inside `_judge_plan_reply`

`_judge_plan_reply` performs candidate extraction, Pydantic schema validation (`ReviewPlanOutput`), and G10 checks (`verify_review_plan`).
If any step fails, it returns `None` and the rejection reason list.

*Alternative considered:* Only validate schema in the validator and run `verify_review_plan` after `chat` returns.
*Evidence rejecting alternative:* A model reply that passes schema checks but violates G10 plan rules would be accepted by the validator and saved in the cache.

## Risks / Trade-offs

- [Model network or runtime errors] → `run_review_plan_job` catches runtime exceptions (`RuntimeError`, `ValueError`, `OSError`, `TimeoutError`, etc.) and records `model-call-error`.
- [Empty response content] → `LLMClient` raises `AIClientError` when response content and thinking are empty. Handled as `model-call-error` after one call without retries.
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Proposal

## Why

Issue #1810: `run_review_plan_job` in `src/devops_cli/review/analysis.py` sends a review plan prompt with `llm_client.chat(...)` without a validator, without `max_retries=0`, and without handling `ReplyRejectedError`.
The response cache would store a model reply that does not parse or that fails `verify_review_plan` checks, and the client could resend an unusable reply up to four more times.
Pull request #1812 resolved this defect for group analysis jobs (#1013), but left `run_review_plan_job` unvalidated.

## What Changes

- Give `run_review_plan_job` the same shape as `_execute_single_group_job`: a judge function that parses the output and runs `verify_review_plan` once, passes `max_retries=0` and a validator to `chat`, and handles `ReplyRejectedError`.
- Share the chat-and-judge execution step between `_execute_single_group_job` and `run_review_plan_job` through a helper function in `src/devops_cli/review/analysis.py`.
- Add test coverage driving `run_review_plan_job` through a real `LLMClient` with a mock transport and test cache directory, verifying that unparseable replies and check failures are rejected after one dispatch and never cached.
- The change sets `skip_specs: true` in `.openspec.yaml` because this change fixes an internal review pipeline job and alters no user-facing CLI command or schema.
- This change fits in one pull request.

## Capabilities

### New Capabilities

None.

### Modified Capabilities

None.

## Impact

- Code: `src/devops_cli/review/analysis.py`.
- Tests: `tests/test_review_group_analysis.py`.

## Feasibility

- Premise confirmed against `src/devops_cli/review/analysis.py`: lines 1354-1360 call `llm_client.chat(...)` with only `temperature`, `top_p`, and `seed`, running verification only after the cache stores the reply.
- Premise confirmed against `src/devops_cli/ai/client/unified.py`: `chat(...)` supports `validator` and `max_retries=0`, discards unvalidated replies from the cache, and raises `ReplyRejectedError` carrying the raw `LLMResponse`.

## Existing Tool Considered

`LLMClient.chat` already provides response validation and cache rejection via `validator` and `max_retries=0`.
`verify_review_plan` already implements all review plan G10 rules.
Sharing the chat-and-judge logic between jobs uses existing internal components and deletes duplicate response checking code.
No external tool or library is required.
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Tasks

## 1. Failing test

- [x] 1.1 Add failing tests in `tests/test_review_group_analysis.py` proving that `run_review_plan_job` rejects unparseable and invalid replies without caching, and does not retry empty replies: `uv run devops ci test tests/test_review_group_analysis.py -k "plan_reply"`

## 2. Implementation

- [x] 2.1 Implement `_judge_plan_reply` and shared `_chat_and_judge` in `src/devops_cli/review/analysis.py`: `uv run devops ci test tests/test_review_group_analysis.py`
- [x] 2.2 Update `_execute_single_group_job` and `run_review_plan_job` to execute through `_chat_and_judge`: `uv run devops ci test tests/test_review_group_analysis.py`

## 3. Verification and static checks

- [x] 3.1 Verify fail-to-pass check run passes against base: `uv run devops ci fail-to-pass --base origin/main`
- [x] 3.2 Verify full static checks pass: `uv run devops ci`

## Workflow follow-up

- Pending a person: review the diff in tuicr (`tuicr -r origin/main..HEAD`).
160 changes: 90 additions & 70 deletions src/devops_cli/review/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -1051,26 +1051,16 @@ def _judge_group_reply(
)


def _execute_single_group_job(
job_input: AnalysisJobInput,
def _chat_and_judge[T](
*,
llm_client: Any,
system_prompt: str,
user_prompt: str,
sampling: SamplingRecord,
admitted_ids: set[str],
file_contents: Mapping[str, str],
python_block_checker: Callable[[str, str], list[str]] | None,
correlation_table: Sequence[CorrelationEntry] | None = None,
) -> tuple[GroupAnalysisRecord, list[str], bool]:
judge = functools.partial(
_judge_group_reply,
job_input=job_input,
admitted_ids=admitted_ids,
file_contents=file_contents,
python_block_checker=python_block_checker,
correlation_table=correlation_table,
)
judged: dict[str, _GroupVerdict] = {}
judge: Callable[[str], tuple[T | None, list[str]]],
) -> tuple[T | None, list[str], bool]:
"""Execute one model chat turn under a validator judge, max_retries=0, and ReplyRejectedError handling (#1013, #1810)."""
judged: dict[str, tuple[T | None, list[str]]] = {}

def accept(text: str) -> bool:
judged[text] = judge(text)
Expand All @@ -1081,7 +1071,7 @@ def accept(text: str) -> bool:
try:
raw = llm_client.chat(
system_prompt,
job_input.model_dump_json(indent=2),
user_prompt,
temperature=sampling.temperature,
top_p=sampling.top_p,
seed=sampling.seed,
Expand All @@ -1093,9 +1083,38 @@ def accept(text: str) -> bool:
is_cached = bool(getattr(raw, "cached", False))
if getattr(raw, "finish_reason", None) == CONST_FINISH_REASON_LENGTH:
reason = CONST_ANALYSIS_REJECTION_REPLY_TRUNCATED
return (_rejected_group_record(job_input, sampling, reason), [reason], is_cached)
return None, [reason], is_cached
text = str(raw).strip()
verified, reasons = judged[text] if text in judged else judge(text)
return verified, reasons, is_cached


def _execute_single_group_job(
job_input: AnalysisJobInput,
*,
llm_client: Any,
system_prompt: str,
sampling: SamplingRecord,
admitted_ids: set[str],
file_contents: Mapping[str, str],
python_block_checker: Callable[[str, str], list[str]] | None,
correlation_table: Sequence[CorrelationEntry] | None = None,
) -> tuple[GroupAnalysisRecord, list[str], bool]:
judge = functools.partial(
_judge_group_reply,
job_input=job_input,
admitted_ids=admitted_ids,
file_contents=file_contents,
python_block_checker=python_block_checker,
correlation_table=correlation_table,
)
verified, reasons, is_cached = _chat_and_judge(
llm_client=llm_client,
system_prompt=system_prompt,
user_prompt=job_input.model_dump_json(indent=2),
sampling=sampling,
judge=judge,
)
return _group_record(job_input, sampling, verified, reasons), reasons, is_cached


Expand Down Expand Up @@ -1298,6 +1317,44 @@ def verify_review_plan(
return (None if reasons else plan), reasons


_PlanVerdict = tuple[ReviewPlanOutput | None, list[str]]


def _judge_plan_reply(
text: str,
*,
admitted: Sequence[Finding],
correlation_table: Sequence[CorrelationEntry],
environment: EnvironmentFacts | None,
python_block_checker: Callable[[str, str], list[str]] | None,
) -> _PlanVerdict:
"""Parse a review plan reply and run the G10 checks on it (#1148, #1810)."""
extracted = extract_json_block(text, default=None)
candidate = extracted if isinstance(extracted, dict) else None
if candidate is None:
try:
parsed = json.loads(text)
candidate = parsed if isinstance(parsed, dict) else None
except ValueError:
pass

if candidate is None or "steps" not in candidate:
return None, [CONST_ANALYSIS_REJECTION_SCHEMA_VALIDATION_FAILED]

try:
parsed_plan = ReviewPlanOutput.model_validate(candidate)
except PydanticValidationError:
return None, [CONST_ANALYSIS_REJECTION_SCHEMA_VALIDATION_FAILED]

return verify_review_plan(
parsed_plan,
admitted,
correlation_table,
environment=environment,
python_block_checker=python_block_checker,
)


def run_review_plan_job(
findings: Sequence[Finding],
correlation_table: Sequence[CorrelationEntry],
Expand All @@ -1308,7 +1365,7 @@ def run_review_plan_job(
environment: EnvironmentFacts,
python_block_checker: Callable[[str, str], list[str]] | None = None,
) -> tuple[ReviewPlanRecord, list[str], bool]:
"""Execute one model review plan job across admitted findings under G10 checks (#1148)."""
"""Execute one model review plan job across admitted findings under G10 checks (#1148, #1810)."""
admitted = [f for f in findings if f.state != FindingState.SUPPRESSED]
if not admitted or llm_client is None:
plan = build_deterministic_review_plan(findings, correlation_table, group_records)
Expand Down Expand Up @@ -1349,14 +1406,22 @@ def run_review_plan_job(
],
}

judge = functools.partial(
_judge_plan_reply,
admitted=admitted,
correlation_table=correlation_table,
environment=environment,
python_block_checker=python_block_checker,
)

try:
system_prompt = load_task_prompt(CONST_ANALYSIS_PLAN_PROMPT_FILENAME)
raw = llm_client.chat(
system_prompt,
json.dumps(plan_input, indent=2),
temperature=sampling.temperature,
top_p=sampling.top_p,
seed=sampling.seed,
verified_plan, reasons, is_cached = _chat_and_judge(
llm_client=llm_client,
system_prompt=system_prompt,
user_prompt=json.dumps(plan_input, indent=2),
sampling=sampling,
judge=judge,
)
except RuntimeError, ValueError, OSError, TimeoutError, TypeError, KeyError:
reason = CONST_ANALYSIS_REJECTION_MODEL_CALL_ERROR
Expand All @@ -1366,51 +1431,6 @@ def run_review_plan_job(
False,
)

is_cached = bool(getattr(raw, "cached", False))

if getattr(raw, "finish_reason", None) == CONST_FINISH_REASON_LENGTH:
reason = CONST_ANALYSIS_REJECTION_REPLY_TRUNCATED
return (
ReviewPlanRecord(status="rejected", output=None, rejected_reasons=[reason]),
[reason],
is_cached,
)

text = raw if isinstance(raw, str) else str(getattr(raw, "content", raw))
extracted = extract_json_block(text, default=None)
candidate = extracted if isinstance(extracted, dict) else None
if candidate is None:
try:
parsed = json.loads(text)
candidate = parsed if isinstance(parsed, dict) else None
except ValueError:
pass

if candidate is None or "steps" not in candidate:
reason = CONST_ANALYSIS_REJECTION_SCHEMA_VALIDATION_FAILED
return (
ReviewPlanRecord(status="rejected", output=None, rejected_reasons=[reason]),
[reason],
is_cached,
)

try:
parsed_plan = ReviewPlanOutput.model_validate(candidate)
except PydanticValidationError:
reason = CONST_ANALYSIS_REJECTION_SCHEMA_VALIDATION_FAILED
return (
ReviewPlanRecord(status="rejected", output=None, rejected_reasons=[reason]),
[reason],
is_cached,
)

verified_plan, reasons = verify_review_plan(
parsed_plan,
admitted,
correlation_table,
environment=environment,
python_block_checker=python_block_checker,
)
return (
ReviewPlanRecord(
status="verified" if verified_plan is not None else "rejected",
Expand Down
Loading
Loading