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
131 changes: 114 additions & 17 deletions src/skillspector/nodes/analyzers/static_patterns_tool_misuse.py
Original file line number Diff line number Diff line change
Expand Up @@ -5430,36 +5430,88 @@ def _markdown_shell_text(
list_marker = re.compile(r"(?:[-+*]|[0-9]{1,9}[.)])(?=[ \t])")
backtick_runs = re.compile(r"`+")

def mask_inline_delimiters() -> None:
if not complete_context:
runs.clear()
return
def complete_inline_code_pairs(
source: str,
delimiter_runs: list[tuple[int, int]],
) -> list[tuple[tuple[int, int], tuple[int, int]]]:
next_by_length: dict[int, int] = {}
closing: dict[int, int] = {}
for index in range(len(runs) - 1, -1, -1):
for index in range(len(delimiter_runs) - 1, -1, -1):
check_runtime()
start, end = runs[index]
start, end = delimiter_runs[index]
length = end - start
if length in next_by_length:
closing[index] = next_by_length[length]
next_by_length[length] = index

pairs: list[tuple[tuple[int, int], tuple[int, int]]] = []
index = 0
while index < len(runs):
while index < len(delimiter_runs):
check_runtime()
start, end = runs[index]
start, end = delimiter_runs[index]
escape_start = start
while escape_start > 0 and content[escape_start - 1] == "\\":
while escape_start > 0 and source[escape_start - 1] == "\\":
escape_start -= 1
close_index = closing.get(index)
if (start - escape_start) % 2 or close_index is None:
index += 1
continue
close_start, close_end = runs[close_index]
close_start, close_end = delimiter_runs[close_index]
pairs.append(((start, end), (close_start, close_end)))
index = close_index + 1
return pairs

def mask_inline_delimiters() -> None:
if not complete_context:
runs.clear()
return
for (start, end), (close_start, close_end) in complete_inline_code_pairs(content, runs):
output[start:end] = " " * (end - start)
output[close_start:close_end] = " " * (close_end - close_start)
index = close_index + 1
runs.clear()

def prose_without_complete_inline_code(
text: str,
source_start: int,
*,
list_marker_owns_initial_command: bool,
) -> tuple[str, bool]:
"""Blank complete same-line spans and retain their runtime-command guard."""
line_runs = [(match.start(), match.end()) for match in backtick_runs.finditer(text)]
projected = list(text)
protects_runtime_command = False

def starts_additional_clause(source: str) -> bool:
return any(
clause_start > 0 and source[clause_start - 1] in ";|&\n"
for clause_start in _shell_clause_starts(source, check_runtime)
)

for (start, end), (close_start, close_end) in complete_inline_code_pairs(text, line_runs):
body = text[end:close_start]
remainder_start = source_start + start
evidence_end = remainder_start + _ROOT_GLOB_COMMAND_CHARS
list_marker_owns_span_command = (
list_marker_owns_initial_command
and not starts_additional_clause(text[:start])
and not starts_additional_clause(body)
)
if (
# A clipped window cannot prove that operands are absent.
(
evidence_end < len(content)
or _may_have_destructive_outer_operands(content[remainder_start:evidence_end])
)
and (
_MARKDOWN_PROSE_SHELL_SYNTAX_RE.search(body) is not None
or next(_destructive_command_words(body), None) is not None
)
and not list_marker_owns_span_command
):
protects_runtime_command = True
projected[start:close_end] = " " * (close_end - start)
return "".join(projected), protects_runtime_command

# This is a conservative projection, not a general Markdown renderer.
# Container/HTML bodies with uncertain inline ownership remain literal.
fence: tuple[str, int, int, str] | None = None
Expand Down Expand Up @@ -5488,6 +5540,9 @@ def mask_inline_delimiters() -> None:
column = indentation
list_indented = False
has_list_marker = False
# The first marker is the shell word that owns the command position.
# ``*`` is a glob, not an inert word, so it never owns it.
first_marker_is_glob = False
list_markers = 0
if indentation < 4:
while marker := list_marker.match(stripped, prefix):
Expand All @@ -5502,6 +5557,8 @@ def mask_inline_delimiters() -> None:
# Only a list starting at 1 can interrupt a paragraph.
# Other numbers may be literal text within an inline span.
break
if not has_list_marker:
first_marker_is_glob = marker[0][0] == "*"
has_list_marker = True
list_markers += 1
column += marker.end() - prefix
Expand All @@ -5527,6 +5584,14 @@ def mask_inline_delimiters() -> None:
# Single '-' still starts an empty item; '---' remains thematic.
separator = False
html_open = re.match(r"<(?:[A-Za-z][A-Za-z0-9-]*(?=[\s/>]|$)|[!?/])", leading)
nested_fence_opening = (
MARKDOWN_FENCE_OPEN.fullmatch(stripped[prefix:])
if paragraph_in_list
and not has_list_marker
and not list_indented
and 0 <= indentation - paragraph_list_indent <= 3
else None
)
continuing_paragraph = False
if table_columns is not None and (
html_end is not None
Expand Down Expand Up @@ -5634,6 +5699,21 @@ def mask_inline_delimiters() -> None:
else ""
)
html_end = None if terminator and terminator in leading.lower() else terminator
elif nested_fence_opening:
mask_inline_delimiters()
begin, end = nested_fence_opening.span(1)
info = stripped[prefix + end :].strip()
fence = (
nested_fence_opening[1][0],
len(nested_fence_opening[1]),
paragraph_list_indent,
info.split(maxsplit=1)[0].casefold() if info else "",
)
fence_literal_apostrophes.clear()
fence_literal_ownership = True
fence_has_literal_apostrophe = False
fence_has_nonliteral_apostrophe = False
output[offset + prefix + begin : offset + prefix + end] = " " * (end - begin)
elif not leading or indentation >= 4 or list_indented:
mask_inline_delimiters()
else:
Expand Down Expand Up @@ -5704,12 +5784,28 @@ def mask_inline_delimiters() -> None:
if not cells:
table_columns = None
elif not separator and not empty_list_item:
prose_leading = leading
inline_runtime_guard = False
if (
complete_context
and not runs
and not heading
and len(leading) <= 512
and (prose := _MARKDOWN_CONTRACTION_PROSE_RE.fullmatch(leading))
and 0 <= leading.find("`") < leading.find("'")
):
prose_leading, inline_runtime_guard = prose_without_complete_inline_code(
leading,
offset + prefix,
list_marker_owns_initial_command=(
has_list_marker and not first_marker_is_glob
),
)
if (
complete_context
and not runs
and not heading
and not inline_runtime_guard
and len(prose_leading) <= 512
and (prose := _MARKDOWN_CONTRACTION_PROSE_RE.fullmatch(prose_leading))
):
# A whole plain-language sentence, including a parsed
# list-item body, owns its contraction;
Expand All @@ -5723,12 +5819,13 @@ def mask_inline_delimiters() -> None:
and complete_context
and not runs
and not heading
and "'" in leading
and not inline_runtime_guard
and "'" in prose_leading
# Inline-code delimiters are Markdown, not shell
# syntax: judge the line with its line-local pairs
# blanked, exactly as the masking pass will.
and _MARKDOWN_PROSE_SHELL_SYNTAX_RE.search(
_blank_line_local_paired_backticks(leading)
_blank_line_local_paired_backticks(prose_leading)
)
is None
and (
Expand All @@ -5746,10 +5843,10 @@ def mask_inline_delimiters() -> None:
# runtime-selected command can take later text as
# operands through it. The same block exclusions apply.
apostrophes: list[int] = []
for word in _MARKDOWN_WORD_APOSTROPHE_RE.finditer(leading):
for word in _MARKDOWN_WORD_APOSTROPHE_RE.finditer(prose_leading):
check_runtime()
apostrophes.append(offset + prefix + word.start("apostrophe"))
if len(apostrophes) == leading.count("'"):
if len(apostrophes) == prose_leading.count("'"):
prose_apostrophes.update(apostrophes)
for match in backtick_runs.finditer(line):
check_runtime()
Expand Down
51 changes: 51 additions & 0 deletions tests/nodes/analyzers/test_documentation_reconstruction.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,57 @@ def test_list_fence_closes_before_following_inline_documentation(opening: str, i
assert result["inspection_ledger"][0]["outcome"] is LedgerOutcome.COMPLETED


def test_nested_list_fence_uses_container_relative_indentation() -> None:
Comment thread
kshitijrajes marked this conversation as resolved.
Resolved
content = (
"3. Inspect the configuration:\n"
" - Check the active value:\n"
" ```bash\n"
" echo harmless\n"
" rm -rf /\n"
" ```\n"
)

projected = tm_module._markdown_shell_text(content, lambda: None)

assert "```" not in projected
assert "echo harmless" in projected
assert "rm -rf /" in projected


@pytest.mark.parametrize("language", ["tcl", "verilog"])
def test_nested_list_fence_keeps_typed_fence_quote_ownership(language: str) -> None:
# A nested list fence takes the same typed-fence path as a top-level fence:
# a shell quote in it is never owned as a hardware literal.
content = (
"3. Inspect the configuration:\n"
" - Check the active value:\n"
f" ```{language}\n"
" // echo '1'\n"
" sh -c '$CMD -rf /'\n"
" ```\n"
)

result = static_runner.run_static_patterns_with_ledger(
{"components": ["guide.md"], "file_cache": {"guide.md": content}}, [tm_module]
)

assert result["inspection_ledger"][0]["outcome"] is LedgerOutcome.PARTIAL
assert result["inspection_ledger"][0]["reason_code"] is LedgerReason.STATIC_PARSE_LIMIT


@pytest.mark.parametrize(("relative_indent", "opens"), [(3, True), (4, False)])
def test_list_fence_container_relative_indentation_boundary(
relative_indent: int, opens: bool
) -> None:
indent = " " * (2 + relative_indent)
content = f"- Check the active value:\n{indent}```bash\n{indent}echo harmless\n{indent}```\n"

projected = tm_module._markdown_shell_text(content, lambda: None)

assert ("```" not in projected) is opens
assert "echo harmless" in projected


@pytest.mark.parametrize("opening,indent", [(" ```sh", " "), ("- - ```sh", " ")])
def test_deeply_indented_marker_does_not_close_fence(opening: str, indent: str) -> None:
content = opening + "\n" + indent + "```\n" + _LITERAL_BACKTICK_COMMAND + "\n```\n"
Expand Down
Loading
Loading