Skip to content
Open
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
84 changes: 64 additions & 20 deletions scripts/utils/strat_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,18 @@
_COLOR_SECTION_HEADING_RE = re.compile(r"^\{color:[^}]+\}.+\{color\}\s*$", re.IGNORECASE)


def extract_jira_section(content: str, heading_prefix: str) -> str | None:
def _trim_section(lines: list[str], keep_indent: bool) -> str:
"""Join section lines; `keep_indent` drops only surrounding blank lines so the first line keeps its indent."""
body = "\n".join(lines)
return body.strip("\r\n").rstrip() if keep_indent else body.strip()


def extract_jira_section(content: str, heading_prefix: str, *, keep_indent: bool = False) -> str | None:
"""Extract text after a Jira heading up to its next section boundary.

Jira h2./h3. headings end every section. Inline bold labels also stop at the next bold,
color-marked, panel, or h2./h3. section boundary.
color-marked, panel, or h2./h3. section boundary. The result is `.strip()`ed unless `keep_indent`
is set, in which case only blank lines around the section are removed so list indentation survives.
"""
lines = content.splitlines()
start = None
Expand All @@ -38,29 +45,68 @@ def extract_jira_section(content: str, heading_prefix: str) -> str | None:
or stripped == "{panel}"
)
):
return "\n".join(lines[start:i]).strip()
return "\n".join(lines[start:]).strip() if start is not None else None
return _trim_section(lines[start:i], keep_indent)
return _trim_section(lines[start:], keep_indent) if start is not None else None


_MARKDOWN_MARKER_RES = {
"numbered": re.compile(r"^(\s*)\d+\.\s+(.*)$"),
"dash": re.compile(r"^(\s*)-\s+(.*)$"),
}


def _split_markdown_list(section: str) -> list[str] | None:
"""Split a section that opens with a markdown `1.` / `-` list into one string per top-level item.

Returns None unless the first non-blank line is a list marker, so paragraphs that merely contain
example sub-bullets stay in paragraph mode. Items start at a marker of the same kind and indent as
the first one; deeper nested bullets and continuation lines fold into the current item.
"""
lines = [line.expandtabs(4) for line in section.splitlines()]
first = next((line for line in lines if line.strip()), None)
if first is None:
return None
for pattern in _MARKDOWN_MARKER_RES.values():
if match := pattern.match(first):
marker, top_indent = pattern, len(match.group(1))
break
else:
return None

items: list[list[str]] = []
for line in lines:
match = marker.match(line)
if match and len(match.group(1)) == top_indent:
Comment thread
fullsend-ai-coder[bot] marked this conversation as resolved.
Resolved

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[low] logic-error

_split_markdown_list only treats a marker as a sibling when its indent equals the first item's indent exactly; a list of '1. First', ' 2. Second', '3. Third' yields two ACs with Second folded into First, so AC counts and citation numbering can be wrong. Edge case, unchanged since the prior review.

Suggested fix: Decide nesting from the parent item's content indent rather than exact marker indent, and add a regression test for slightly indented siblings.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Resolved by the review agent: this is an older copy of a finding that a newer review thread also carries: #111 (comment)

The finding is still open. Follow up in the newer thread.

Resolving this duplicate. Unresolve it if you disagree.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[low] logic-error

_split_markdown_list starts a new item only when a marker's indent exactly equals the first marker's indent. Any other indentation is folded into the previous item, so - First\n - Second\n- Third yields 2 criteria instead of 3 and later AC citation numbers shift. This is a narrow edge case (inconsistently indented sibling markers); the author has chosen not to tolerate mixed sibling indent in this PR, so it is advisory.

Suggested fix: Treat a marker as nested only when its indent is at least the current item's content column; otherwise start a new top-level item, and add a regression test next to the nested-list test.

items.append([match.group(2)])
elif items:
items[-1].append(line)
Comment on lines +77 to +82

@fege fege Dec 4, 2026 •

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.

Last one I think @Benkapner. Thanks

This folds a paragraph after a blank line into the last item, merging criteria main keeps separate:

- Exports must preserve row order.

Imports must reject malformed files.

main → 2 ACs; here → 1, so (AC: #2) becomes out_of_range (scripts/validate.py:205). With 2+ bullets ac_count stays the same and #2 silently means something else instead.

Fix: after a blank line, a non-marker line indented <= top_indent ends the list; the rest falls through to the paragraph split at line 110. Leave the Jira path at 103–105 alone. Add a list → blank line → paragraph test; the fixtures at strategy_constants.py:58 only cover the reverse order.

return [" ".join(" ".join(parts).split()) for parts in items if "".join(parts).strip()]


def _extract_bulleted_texts(section: str) -> list[str]:
"""Split a Jira wiki section body into merged, whitespace-normalized bullet-item strings.

Handles both `#` (numbered) and `*` (plain) bullet markers, and falls back to blank-line
paragraph splitting when no bullet marker is present.
Prefers Jira markers (`#` numbered, then `*` plain) so existing STRAT fixtures stay unchanged.
Overflow markdown attachments keep `1.` / `-` after heading normalization; those are recognized
only when the section body starts with the list (see `_split_markdown_list`). Falls back to
blank-line paragraph splitting otherwise. Pass the section with its indentation intact
(`extract_jira_section(..., keep_indent=True)`) so indented markdown lists split correctly.
"""
stripped = section.strip()

bullet_marker = None
if re.search(r"(?m)^#\s+", stripped):
bullet_marker = r"(?m)^#\s+"
elif re.search(r"(?m)^\*\s+", stripped):
bullet_marker = r"(?m)^\*\s+"
else:
bullet_marker = None

if bullet_marker:
# Split on the bullet marker directly so entries survive with no blank line between them.
return [" ".join(item.split()) for item in re.split(bullet_marker, stripped)[1:] if item.strip()]

if (markdown_items := _split_markdown_list(section)) is not None:
return markdown_items

merged = []
for para in re.split(r"\n\n+", stripped):
if text := " ".join(para.split()):
Expand All @@ -80,14 +126,14 @@ def parse_acceptance_criteria(content: str) -> dict:
whose sentence exactly duplicates (case/whitespace-insensitive) one already present are
skipped; semantic near-duplicates are not detected.
"""
section = extract_jira_section(content, "h3. Acceptance Criteria")
section = extract_jira_section(content, "h3. Acceptance Criteria", keep_indent=True)
if section is None:
heading = next((line for line in content.splitlines() if _STRATEGY_AC_HEADING_RE.match(line)), None)
if heading is None:
heading = next((line for line in content.splitlines() if _ADDITIONAL_AC_HEADING_RE.match(line)), None)
section = extract_jira_section(content, heading) if heading is not None else None
section = extract_jira_section(content, heading, keep_indent=True) if heading is not None else None
if section is None:
section = extract_jira_section(content, "*Acceptance Criteria*")
section = extract_jira_section(content, "*Acceptance Criteria*", keep_indent=True)
if section is None:
return {"found": False, "count": 0, "acceptance_criteria": []}

Expand All @@ -100,7 +146,9 @@ def parse_acceptance_criteria(content: str) -> dict:
break

testability_section = (
extract_jira_section(content, testability_heading) if testability_heading is not None else None
extract_jira_section(content, testability_heading, keep_indent=True)
if testability_heading is not None
else None
)
if testability_section:
seen = {" ".join(_parse_bullet_item(text)["text"].split()).casefold() for text in texts}
Expand All @@ -123,20 +171,16 @@ def parse_nfr(content: str) -> dict:
if section is None:
return {"found": False, "requirements": []}

nfr_re = re.compile(r"^\*\s+\*([^*]+)\*:\s*(.+)")
nfr_re = re.compile(r"^\*\s+\*(?:([^*]+):\*|([^*]+)\*:)\s*(.+)")
Comment thread
fullsend-ai-coder[bot] marked this conversation as resolved.
Resolved
requirements = []
for raw_line in section.splitlines():
line = raw_line.strip()
if not line:
continue
match = nfr_re.match(line)
if match:
requirements.append(
{
"category": match.group(1).strip(),
"text": match.group(2).strip(),
}
)
category = (match.group(1) or match.group(2)).strip() if match else ""
if category:
requirements.append({"category": category, "text": match.group(3).strip()})
elif requirements and not line.startswith("*"):
# Merge wrapped continuation text, but not a new "*" bullet that failed nfr_re.
requirements[-1]["text"] = f"{requirements[-1]['text']} {line}"
Expand Down
83 changes: 82 additions & 1 deletion tests/consts/strategy_constants.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Formatted strategy Markdown fixtures for the overflow-marker fetch-failure gate."""
"""Strategy fixtures for overflow-marker fetch failures and STRAT section parsing."""

from scripts.strategy_source import OVERFLOW_MARKER

Expand Down Expand Up @@ -28,3 +28,84 @@

The strategy has no acceptance criteria section.
"""

# Heading-normalized overflow attachments keep markdown list markers (`1.` / `-`).
# Parser input looks like this after `_normalize_strategy_headings` rewrites `###` → `h3.`.
STRAT_AC_MARKDOWN_NUMBERED = (
"h3. Acceptance Criteria\n\n"
"1. *Attachment wins*: Given overflow When fetched Then the newest attachment is parsed\n"
"2. *Inline description*: Given a short strategy When fetched Then the body is parsed\n"
"3. *Fallback snapshot*: Given no live issue When a snapshot exists Then it is parsed\n"
"\nh3. Effort Estimate\n"
)

STRAT_AC_MARKDOWN_DASH = (
"h3. Acceptance Criteria\n\n"
"- Given a user opens a session, when the page loads, then a tile is visible.\n"
"- Given a user clicks the tile, when the dialog opens, then samples are shown.\n"
"- Given the dialog is open, when the user selects a filter, then results update.\n"
"\nh3. Effort Estimate\n"
)

STRAT_AC_JIRA_HASH_WITH_MARKDOWN_NUMBERS = (
"h3. Acceptance Criteria\n\n"
"# Given a user opens a session, when the page loads, then a tile is visible.\n"
"1. This markdown item must not split the Jira numbered list.\n"
"# Given a user clicks the tile, when the dialog opens, then samples are shown.\n"
"\nh3. Effort Estimate\n"
)

STRAT_AC_PARAGRAPH_WITH_DASH_EXAMPLES = """h3. Acceptance Criteria

The export must support:
- CSV
- JSON

The import must reject malformed files."""

STRAT_AC_INDENTED_NUMBERED = """h3. Acceptance Criteria

1. Given A when B then C
2. Given D when E then F
3. Given G when H then I"""

STRAT_AC_INDENTED_DASH = """h3. Acceptance Criteria

- Given A when B then C
- Given D when E then F
- Given G when H then I"""

STRAT_AC_INDENTED_DASH_WITH_NESTED = """h3. Acceptance Criteria

- Given A when B then C
- nested detail for A
- Given D when E then F"""

STRAT_AC_JIRA_HASH_WRAPPED_PARAGRAPHS = """h3. Acceptance Criteria

# Given A when B then C
- wrapped detail for the first item

second paragraph of the first item
# Given D when E then F"""

STRAT_NFR_COLON_INSIDE_BOLD = (
"h3. Non-Functional Requirements\n\n"
"* *Performance:* The strategy fetch completes within the request timeout\n"
"* *Security*: Auth required\n"
"\nh3. Out-of-Scope\n"
)

STRAT_NFR_BOLD_WITHOUT_COLON = (
"h3. Non-Functional Requirements\n\n"
"* *Performance*: Responses stay under two seconds\n"
"* *Note* For discussion only\n"
"\nh3. Out-of-Scope\n"
)

STRAT_NFR_EMPTY_CATEGORY_TEXT = (
"h3. Non-Functional Requirements\n\n"
"* *Performance*: Responses stay under two seconds\n"
"* *Security*:\n"
"\nh3. Out-of-Scope\n"
)
123 changes: 122 additions & 1 deletion tests/unit/test_parse_strat.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,21 @@
parse_out_of_scope,
workflow_inputs,
)
from tests.consts.strategy_constants import STRATEGY_WITH_UNFETCHED_ATTACHMENT, STRATEGY_WITHOUT_AC
from tests.consts.strategy_constants import (
STRATEGY_WITHOUT_AC,
STRATEGY_WITH_UNFETCHED_ATTACHMENT,
STRAT_AC_INDENTED_DASH,
STRAT_AC_INDENTED_DASH_WITH_NESTED,
STRAT_AC_INDENTED_NUMBERED,
STRAT_AC_JIRA_HASH_WITH_MARKDOWN_NUMBERS,
STRAT_AC_JIRA_HASH_WRAPPED_PARAGRAPHS,
STRAT_AC_MARKDOWN_DASH,
STRAT_AC_MARKDOWN_NUMBERED,
STRAT_AC_PARAGRAPH_WITH_DASH_EXAMPLES,
STRAT_NFR_BOLD_WITHOUT_COLON,
STRAT_NFR_COLON_INSIDE_BOLD,
STRAT_NFR_EMPTY_CATEGORY_TEXT,
)
from tests.helpers import strat_with_testability_heading
from tests.constants import (
STRAT_AC_H2_PREFIX_COLLISION,
Expand Down Expand Up @@ -212,6 +226,85 @@ def test_star_bulleted_acs_no_blank_lines_between_entries(self):
assert "Given a user submits invalid input" in result["acceptance_criteria"][1]["text"]
assert "Given a duplicate name is submitted" in result["acceptance_criteria"][2]["text"]

def test_markdown_numbered_acs_are_split(self):
result = parse_acceptance_criteria(STRAT_AC_MARKDOWN_NUMBERED)

assert result["found"] is True
assert result["count"] == 3
assert [ac["num"] for ac in result["acceptance_criteria"]] == [1, 2, 3]
texts = [ac["text"] for ac in result["acceptance_criteria"]]
assert "Attachment wins" in texts[0]
assert "Inline description" in texts[1]
assert "Fallback snapshot" in texts[2]
assert texts[0] != texts[1]
assert "Inline description" not in texts[0]
assert gate_inputs(STRAT_AC_MARKDOWN_NUMBERED)["ac_count"] == 3

def test_markdown_dash_acs_are_split(self):
result = parse_acceptance_criteria(STRAT_AC_MARKDOWN_DASH)

assert result["found"] is True
assert result["count"] == 3
assert "opens a session" in result["acceptance_criteria"][0]["text"]
assert "clicks the tile" in result["acceptance_criteria"][1]["text"]
assert "dialog is open" in result["acceptance_criteria"][2]["text"]

def test_jira_hash_still_wins_over_markdown_numbers(self):
result = parse_acceptance_criteria(STRAT_AC_JIRA_HASH_WITH_MARKDOWN_NUMBERS)

assert result["found"] is True
assert result["count"] == 2
assert "opens a session" in result["acceptance_criteria"][0]["text"]
assert "markdown item must not split" in result["acceptance_criteria"][0]["text"]
assert "clicks the tile" in result["acceptance_criteria"][1]["text"]

def test_dash_examples_inside_paragraph_keep_paragraph_mode(self):
result = parse_acceptance_criteria(STRAT_AC_PARAGRAPH_WITH_DASH_EXAMPLES)

assert result["count"] == 2
assert [ac["text"] for ac in result["acceptance_criteria"]] == [
"The export must support: - CSV - JSON",
"The import must reject malformed files.",
]

def test_indented_numbered_list_splits_every_item(self):
result = parse_acceptance_criteria(STRAT_AC_INDENTED_NUMBERED)

assert result["count"] == 3
assert [ac["text"] for ac in result["acceptance_criteria"]] == [
"Given A when B then C",
"Given D when E then F",
"Given G when H then I",
]
assert gate_inputs(STRAT_AC_INDENTED_NUMBERED)["ac_count"] == 3
assert workflow_inputs(STRAT_AC_INDENTED_NUMBERED)["ac_count"] == 3

def test_indented_dash_list_splits_every_item(self):
result = parse_acceptance_criteria(STRAT_AC_INDENTED_DASH)

assert result["count"] == 3
assert [ac["text"] for ac in result["acceptance_criteria"]] == [
"Given A when B then C",
"Given D when E then F",
"Given G when H then I",
]

def test_nested_markdown_bullets_are_not_promoted_to_acs(self):
result = parse_acceptance_criteria(STRAT_AC_INDENTED_DASH_WITH_NESTED)

assert [ac["text"] for ac in result["acceptance_criteria"]] == [
"Given A when B then C - nested detail for A",
"Given D when E then F",
]

def test_jira_hash_wrapped_paragraphs_stay_one_ac(self):
result = parse_acceptance_criteria(STRAT_AC_JIRA_HASH_WRAPPED_PARAGRAPHS)

assert [ac["text"] for ac in result["acceptance_criteria"]] == [
"Given A when B then C - wrapped detail for the first item second paragraph of the first item",
"Given D when E then F",
]

def test_testability_edge_cases_folded_in_with_continued_numbering(self):
result = parse_acceptance_criteria(STRAT_TESTABILITY_FOLDED_INTO_AC)

Expand Down Expand Up @@ -272,6 +365,34 @@ def test_wrapped_bullet_not_truncated(self):
# A stray "*" bullet that is not a "* *Cat*: text" NFR must not be merged into Security.
assert "stray bullet" not in security["text"]

def test_colon_inside_bold_category_is_kept(self):
result = parse_nfr(STRAT_NFR_COLON_INSIDE_BOLD)

assert result["found"] is True
categories = [nfr["category"] for nfr in result["requirements"]]
assert categories == ["Performance", "Security"]
performance = result["requirements"][0]
assert performance["text"] == "The strategy fetch completes within the request timeout"

def test_bold_category_without_colon_is_not_an_nfr(self):
result = parse_nfr(STRAT_NFR_BOLD_WITHOUT_COLON)

assert [nfr["category"] for nfr in result["requirements"]] == ["Performance"]
assert "Note" not in gate_inputs(STRAT_NFR_BOLD_WITHOUT_COLON)["nfr_categories"]

def test_empty_category_bullet_is_not_a_requirement(self):
result = parse_nfr(STRAT_NFR_EMPTY_CATEGORY_TEXT)

assert [nfr["category"] for nfr in result["requirements"]] == ["Performance"]
assert all(nfr["text"] != ":" for nfr in result["requirements"])
assert "Security" not in gate_inputs(STRAT_NFR_EMPTY_CATEGORY_TEXT)["nfr_categories"]

def test_whitespace_only_category_is_not_a_requirement(self):
content = "h3. Non-Functional Requirements\n\n* * :* Response must complete within two seconds"

assert parse_nfr(content)["requirements"] == []
assert gate_inputs(content)["nfr_categories"] == [] # main ignored this malformed bullet


class TestGateInputs:
"""Tests for gate_inputs — the citation gate's deterministic ac_count + nfr_categories.
Expand Down
Loading