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,2 @@
schema: spec-driven
created: 2026-11-15
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Design

## Decisions
- Read the code-scanning alert with one GET request when an item names an alert number in title or body.
- Extract the alert number using regular expression matching `code-scanning/(?:alerts/)?(\d+)` or `alert\s+#?(\d+)`.
- Store `rule_description` on `CodeScanningAlert` mapped from `rule.description`.
- Add the alert URL to `allowed_urls` so validation preserves the alert as a verified source for key question answers.
- Inject the alert rule description into `VerificationInput.body` so the judge model evaluates the proposal against the rule text.

## Rejected alternatives
- Only supply the rule identifier: rejected because the model hallucinates requirements for unfamiliar rule identifiers.
- Query Trivy database directly: rejected because the code-scanning API already supplies the exact rule description reported during CI.
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Proposal: #5258

## Why
When an issue names a code-scanning alert, refine previously read only the rule identifier from the issue body. The scanner rule description was not retrieved. Without the rule description, refine generated proposals that addressed the wrong scanner rule, and the judge approved them. Closes #5258.

## What Changes
- Add `rule_description` to `CodeScanningAlert` in `src/devops_cli/security/alert_filer.py`.
- Add `read_alert(session, repo, number)` to retrieve alert metadata with one GET request.
- Add `alert_number_of(text)` to extract code-scanning alert numbers from text.
- Update `refine_one_item` in `src/devops_cli/roadmap/refine/refine.py` to retrieve named alerts, add alert details to request context and allowed URLs, and include rule requirements in key questions.
- Update `judge` in `src/devops_cli/roadmap/refine/refine_judge.py` to compare proposals against alert rule descriptions and refuse mismatched proposals.

## Capabilities
- Refine includes scanner rule descriptions in design evidence and verification input when items cite code-scanning alerts.
- Refine judge refuses proposals that contradict alert rule requirements.

## Impact
- Items for code-scanning alerts generate designs that match the reported scanner rule.
- Scanner alerts are not closed with incorrect fixes.

## Feasibility
- Verified with code-scanning alert 213 in repository `dan-petty/devops-cli`.
- GitHub REST API endpoint `/repos/{repo}/code-scanning/alerts/{number}` provides `rule.description`.

## Existing Tool Considered
- The GitHub REST API code-scanning endpoint is used directly through `GitHubSession`. No new external dependency is needed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
## ADDED Requirements

### Requirement: Refine includes code-scanning alert details in proposal context and evidence
When an item names a code-scanning alert, refine SHALL read the alert metadata with one GET request, include the alert rule description in the proposal prompt context, allow the alert URL as a verified source, and record the rule requirement in the key questions design evidence.

#### Scenario: Item names a code-scanning alert
- **WHEN** Refine processes an item that names a code-scanning alert
- **THEN** The request context contains the alert rule description and the refined section holds the alert rule description under key questions
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
## ADDED Requirements

### Requirement: The refine review verifies against the code-scanning alert rule description
When an item names a code-scanning alert, the refine review SHALL supply the rule description of the alert in the verification input body, and the review SHALL refuse a proposal that contradicts the alert rule description.

#### Scenario: An item naming an alert has the alert rule description in the review input
- **WHEN** An item names a code-scanning alert number
- **THEN** The verification input body holds the alert rule description

#### Scenario: Proposal contradicts the alert rule
- **WHEN** An item names a code-scanning alert and the proposal addresses a different scanner rule
- **THEN** The review refuses the proposal with a false premise defect and keeps the item in status New
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Tasks

## 1. Behavior

- [x] 1.1 Write tests for alert reading and refine judge validation
- Verification: `$ uv run devops ci test tests/roadmap/refine/test_roadmap_refine_alert.py`
- [x] 1.2 Implement `rule_description` and `read_alert` in `alert_filer.py`
- Verification: `$ uv run devops ci test tests/roadmap/refine/test_roadmap_refine_alert.py`
- [x] 1.3 Implement `alert_number_of` and alert context injection in `refine.py`
- Verification: `$ uv run devops ci test tests/roadmap/refine/test_roadmap_refine_alert.py`
- [x] 1.4 Implement alert comparison in `refine_judge.py`
- Verification: `$ uv run devops ci test tests/roadmap/refine/test_roadmap_refine_alert.py`

## 2. Documents

- [x] 2.1 Update OpenSpec change artifacts
- Verification: `$ uv run devops openspec validate 5258-refine-designs-against-alert-without-rule-text`
7 changes: 7 additions & 0 deletions openspec/specs/roadmap-refine/proposal/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,3 +169,10 @@ When the count of tries reaches `CONST_ROADMAP_REFINE_MAX_TRIES`, refine SHALL r
#### Scenario: A body edit
- **WHEN** a person edits the body of an item whose next step is `failed`
- **THEN** the next round selects the item, and its count of tries starts at 1

### Requirement: Refine includes code-scanning alert details in proposal context and evidence
When an item names a code-scanning alert, refine SHALL read the alert metadata with one GET request, include the alert rule description in the proposal prompt context, allow the alert URL as a verified source, and record the rule requirement in the key questions design evidence.

#### Scenario: Item names a code-scanning alert
- **WHEN** Refine processes an item that names a code-scanning alert
- **THEN** The request context contains the alert rule description and the refined section holds the alert rule description under key questions
11 changes: 11 additions & 0 deletions openspec/specs/roadmap-refine/review/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,14 @@ Refine SHALL make no review call for an item that holds `refine.judge` `approved
#### Scenario: A body edit after a refusal
- **WHEN** a person edits the body after a refusal, and the review finds no open defect
- **THEN** the next round makes one review call and sets the item Ready

### Requirement: The refine review verifies against the code-scanning alert rule description
When an item names a code-scanning alert, the refine review SHALL supply the rule description of the alert in the verification input body, and the review SHALL refuse a proposal that contradicts the alert rule description.

#### Scenario: An item naming an alert has the alert rule description in the review input
- **WHEN** An item names a code-scanning alert number
- **THEN** The verification input body holds the alert rule description

#### Scenario: Proposal contradicts the alert rule
- **WHEN** An item names a code-scanning alert and the proposal addresses a different scanner rule
- **THEN** The review refuses the proposal with a false premise defect and keeps the item in status New
164 changes: 139 additions & 25 deletions src/devops_cli/roadmap/refine/refine.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,7 @@

if TYPE_CHECKING:
from devops_cli.roadmap.stage.stage import StageClient
from devops_cli.security.alert_filer import CodeScanningAlert

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -2133,6 +2134,22 @@ def _text_issues(text: str, own: int) -> list[int]:
return numbers[:CONST_ROADMAP_REFINE_MAX_WAIT_CHECKS]


# A code scanning alert reference in text: code-scanning/(alerts/)?123 or alert 123.
_CODE_SCANNING_ALERT_RE: Final[re.Pattern[str]] = re.compile(
r"code-scanning/(?:alerts/)?(\d+)|(?:\balert\s+#?(\d+)\b)",
re.IGNORECASE,
)


def alert_number_of(text: str) -> int | None:
"""The number of the first code scanning alert that `text` names, or None."""
match = _CODE_SCANNING_ALERT_RE.search(text)
if match is None:
return None
num_str = match.group(1) or match.group(2)
return int(num_str) if num_str else None


def _closed_since(store: RoadmapStore, number: int, since: datetime) -> bool:
"""Whether issue `number` closed at or after `since`. The timeline is read only for an issue
that is closed and changed since then."""
Expand Down Expand Up @@ -2831,6 +2848,110 @@ def _failed_round(
)


def _item_alert(item: Item, body: str, repo: str) -> CodeScanningAlert | None:
"""The code scanning alert that `item` names in its title or body, or None."""
alert_num = alert_number_of(f"{item.title}\n{body}")
if alert_num is None:
return None
from devops_cli.github.session import get_github_session
from devops_cli.security.alert_filer import read_alert

return read_alert(get_github_session(), repo, alert_num)


def _alert_urls(alert: CodeScanningAlert | None, repo: str) -> set[str]:
"""The URLs of `alert` that the proposal may cite, or an empty set."""
if alert is None:
return set()
return {f"https://github.com/{repo}/security/code-scanning/{alert.number}"}


def _proposal_context(ctx: str, alert: CodeScanningAlert | None) -> str:
"""`ctx` with the code scanning alert summary prepended when `alert` is given."""
if alert is None:
return ctx
alert_block = (
f"### Code-scanning alert {alert.number}\n\n"
f"- Rule: {alert.rule_id}\n"
f"- Description: {alert.rule_description}\n"
f"- Severity: {alert.severity}\n"
f"- Path: {alert.path}\n"
)
return f"{alert_block}\n{ctx}".strip()


def _proposal_request(
item: Item,
current_body: str,
comments: Sequence[Any],
returned: Any,
check: Any,
covers: Any,
answer: Any,
store: RoadmapStore,
ctx: str,
alert: CodeScanningAlert | None,
repo: str,
) -> dict[str, Any]:
"""The JSON document that the proposal model receives."""
request: dict[str, Any] = {
"number": item.number,
"title": item.title,
"body": current_body,
"replies": _replies_for_model(comments),
"stage_return": _stage_evidence(returned),
"alternatives": _alternatives_request(check, comments, covers),
"context": _proposal_context(ctx, alert),
"body_questions": [
{"number": number, "question": asked}
for number, asked in enumerate(_asked_questions(current_body, covers), start=1)
],
"deferred_issues": [
{"number": number, "title": title} for number, title in _recorded_deferrals(store, item)
],
"judge_findings": _judge_findings(item),
"owner_answer": _owner_answer_request(item, answer),
}
if alert is not None:
request["alert"] = {
"number": alert.number,
"rule_id": alert.rule_id,
"rule_description": alert.rule_description,
"severity": alert.severity,
"path": alert.path,
"url": f"https://github.com/{repo}/security/code-scanning/{alert.number}",
}
return request


def _ensure_alert_key_question(
proposal: RefinementProposal,
alert: CodeScanningAlert | None,
repo: str,
) -> RefinementProposal:
"""Add a key question covering the alert rule if not already present."""
if alert is None or not alert.rule_description:
return proposal
url = f"https://github.com/{repo}/security/code-scanning/{alert.number}"
has_qa = any(
str(alert.number) in qa.question
or (alert.rule_description and alert.rule_description in qa.answer)
for qa in proposal.key_questions
)
if has_qa:
return proposal
alert_qa = QuestionAnswer(
question=f"Which rule does alert {alert.number} report, and what does it require?",
answer=(
f"Alert {alert.number} reports {alert.rule_id} at {alert.severity} "
f"severity on `{alert.path}`. The rule requires {alert.rule_description}."
),
kind="decision",
sources=[url],
)
return proposal.model_copy(update={"key_questions": [*proposal.key_questions, alert_qa]})


def refine_one_item(
store: RoadmapStore,
item: Item,
Expand Down Expand Up @@ -2878,6 +2999,7 @@ def refine_one_item(

# Step 1: Context minimization
ctx = collect_context(source, sha, current_body, max_tokens=max_context_tokens)
alert = _item_alert(item, current_body, repo)

# Step 2: Proposal generation. Only the comments of trusted authors reach the model (#3502).
comments = trusted_replies(store.comments_on(item.number))
Expand All @@ -2891,33 +3013,23 @@ def refine_one_item(
actor=actor,
comments_on=partial(_frame_comments, store, item.number, comments),
)
request: dict[str, Any] = {
"number": item.number,
"title": item.title,
"body": current_body,
"replies": _replies_for_model(comments),
"stage_return": _stage_evidence(returned),
"alternatives": _alternatives_request(check, comments, covers),
"context": ctx,
"body_questions": [
{"number": number, "question": asked}
for number, asked in enumerate(_asked_questions(current_body, covers), start=1)
],
"deferred_issues": [
{"number": number, "title": title} for number, title in _recorded_deferrals(store, item)
],
"judge_findings": _judge_findings(item),
"owner_answer": _owner_answer_request(item, answer),
}
raw_proposal: RefinementProposal = client.chat_structured(
_prompt("roadmap_refine_proposal.md"),
json.dumps(request, ensure_ascii=False, indent=1),
RefinementProposal,
max_retries=_REPLY_RETURNS,
request = _proposal_request(
item, current_body, comments, returned, check, covers, answer, store, ctx, alert, repo
)
raw_proposal = _ensure_alert_key_question(
client.chat_structured(
_prompt("roadmap_refine_proposal.md"),
json.dumps(request, ensure_ascii=False, indent=1),
RefinementProposal,
max_retries=_REPLY_RETURNS,
),
alert,
repo,
)

# Step 3: Validation, and the investigation of what stays open (#2398)
allowed_urls: set[str] = set()
alert_urls = _alert_urls(alert, repo)
allowed_urls: set[str] = set(alert_urls)
proposal, open_questions = validate_proposal(
raw_proposal, current_body, allowed_urls, source, sha, store, covers
)
Expand All @@ -2933,7 +3045,7 @@ def refine_one_item(
if isinstance(revised, InvestigationStopped):
stopped = revised
else:
allowed_urls = tools.allowed_urls
allowed_urls = tools.allowed_urls | alert_urls
proposal, open_questions = validate_proposal(
revised, current_body, allowed_urls, source, sha, store, covers
)
Expand Down Expand Up @@ -2961,6 +3073,7 @@ def refine_one_item(
source,
unchanged=is_unchanged(item, current_body),
repo=repo,
alert=alert,
)
is_ready = judge is JudgeVerdict.APPROVED
needs_split = not proposal.fits_one_pr
Expand Down Expand Up @@ -3907,6 +4020,7 @@ def render_refine_plan(plan: RefinePlan) -> str:
"TitleDependencies",
"WaitingItem",
"WebSearch",
"alert_number_of",
"apply_refine",
"body_dependencies",
"body_questions",
Expand Down
18 changes: 17 additions & 1 deletion src/devops_cli/roadmap/refine/refine_judge.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
if TYPE_CHECKING:
from devops_cli.roadmap.refine.refine import RefinementProposal
from devops_cli.roadmap.stage.stage import StageClient
from devops_cli.security.alert_filer import CodeScanningAlert

# The open types of this review (#3039). A proposal of refine holds no task group and no verify
# command, so a `task_order`, a `verify_form` or a `criterion_dropped` finding on it is advice and
Expand All @@ -58,21 +59,36 @@ def judge(
*,
unchanged: bool,
repo: str,
alert: CodeScanningAlert | None = None,
) -> tuple[JudgeVerdict, tuple[str, ...]]:
"""The verdict on `proposal` for `item`, and the lines of the open findings that refuse it.

`body` is the body that refine read. An item that the review approved before, and whose body is
`unchanged` since, keeps its approval with no model call: the review looks again only after the
body changes. `client_of` makes the client of the verification task, only when a call is made.
`alert` is the code scanning alert that `item` names, when it names one (#5258).
Each review that calls the model logs one result line for `repo` with its verdict and the count
of its open findings (#4845).
"""
if unchanged and item.job_record.get(RefineRecordKey.JUDGE) == JudgeVerdict.APPROVED.value:
return JudgeVerdict.APPROVED, ()
outside_body = extract_section_and_outside(body)[0]
if alert is not None and alert.rule_description and alert.rule_description not in outside_body:
alert_summary = (
f"\n\n### Code-scanning alert {alert.number}\n\n"
f"- Rule: {alert.rule_id}\n"
f"- Description: {alert.rule_description}\n"
f"- Severity: {alert.severity}\n"
f"- Path: {alert.path}\n"
)
judge_body = f"{outside_body}{alert_summary}"
else:
judge_body = outside_body

given = VerificationInput.of(
number=item.number,
title=item.title,
body=extract_section_and_outside(body)[0],
body=judge_body,
plan=proposal.model_dump(mode="json"),
source=source,
)
Expand Down
Loading