Skip to content

Commit e0c985c

Browse files
committed
fix(mp3): preserve explicit state adoption findings
Signed-off-by: Christopher Kevin <[email protected]>
1 parent 36d9ac4 commit e0c985c

4 files changed

Lines changed: 401 additions & 3 deletions

File tree

‎src/skillspector/nodes/analyzers/prohibition_context.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,21 @@
4141
r"instead|for|to|in|on|during|after|before)\b",
4242
re.IGNORECASE,
4343
)
44+
# A comma or colon can introduce a defensive instruction, but also a condition or scope.
45+
# Callers opting into that boundary must still reject the latter. Prepositions
46+
# inside an earlier independent action ("Use X for rendering:") are not scopes
47+
# on the prohibition; a leading "For rendering:" is.
48+
_CLAUSE_PREFIX_QUALIFIER = re.compile(
49+
r"\b(?:unless|except|until|if|when|whenever|while|only|otherwise|else|but|however|"
50+
r"instead)\b|\A[ \t]*(?:for|to|in|on|during|after|before)\b",
51+
re.IGNORECASE,
52+
)
53+
_CLAUSE_MARKDOWN_PREFIX = re.compile(
54+
r"\A[ \t]*(?:>[ \t]*)*"
55+
r"(?:(?:[-+]|\d{1,9}[.)])[ \t]+)?(?:#{1,6}[ \t]+)?"
56+
)
57+
# Brackets and punctuation inside reference paths cannot discard a leading scope.
58+
_CLAUSE_PREFIX_BREAK = re.compile(rf"[{LINE_BREAK_CHARS}]|[.!?;](?=\s|\Z)")
4459

4560
# Reversal wording is matched by stem so that every inflection ("negation",
4661
# "inverts", "opposites", "contrarily", ...) retains detection.
@@ -106,6 +121,7 @@ def is_directly_prohibited(
106121
*,
107122
allowed_tail: re.Pattern[str] | None = None,
108123
allow_yara_continuation: bool = False,
124+
allow_clause_prefix: bool = False,
109125
) -> bool:
110126
"""Whether a bounded, unambiguous prohibition governs this exact action.
111127
@@ -116,6 +132,9 @@ def is_directly_prohibited(
116132
fully match the caller's allowed_tail grammar after formatting is stripped.
117133
Callers may allow YARA-only continuations only when content is raw source,
118134
because YARA does not scan normalized or reconstructed security views.
135+
A caller may opt into comma/colon prefixes only after its own matcher establishes
136+
action ownership; leading conditions, scopes, quotes and reversals still
137+
retain detection.
119138
Work per match is constant-bounded; unknown or incomplete context retains
120139
detection.
121140
"""
@@ -124,6 +143,21 @@ def is_directly_prohibited(
124143
left = max(0, start - _CONTEXT_CHARS)
125144
prefix = content[left:start].translate(_MARKDOWN)
126145
prohibited = _DIRECT_PREFIX.search(prefix)
146+
if allow_clause_prefix:
147+
prefix_boundary = max(prefix.rfind(":"), prefix.rfind(","))
148+
if prefix_boundary >= 0 and _DIRECT_PREFIX.fullmatch(prefix[prefix_boundary + 1 :]):
149+
preceding_clause = _CLAUSE_PREFIX_BREAK.split(prefix[:prefix_boundary])[-1]
150+
scope_view = _CLAUSE_MARKDOWN_PREFIX.sub("", preceding_clause, count=1)
151+
if (
152+
not scope_view
153+
or not scope_view[0].isalpha()
154+
or _CLAUSE_PREFIX_QUALIFIER.search(scope_view)
155+
):
156+
return False
157+
# This is a bounded boolean view; source offsets and findings stay
158+
# unchanged. Retain all leading text for quote/reversal checks.
159+
prefix = prefix[:prefix_boundary] + ";" + prefix[prefix_boundary + 1 :]
160+
prohibited = _DIRECT_PREFIX.search(prefix)
127161
if prohibited is None or (left and prohibited.start() == 0):
128162
return False
129163
leading = prefix[: prohibited.start()]

‎src/skillspector/nodes/analyzers/static_patterns_memory_poisoning.py‎

Lines changed: 56 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626

2727
import re
2828
import sys
29+
from collections.abc import Iterator
2930

3031
from skillspector.logging_config import get_logger
3132
from skillspector.models import AnalyzerFinding, Location, Severity
@@ -34,6 +35,7 @@
3435
from . import static_runner
3536
from .common import LOGICAL_LINE_BREAK, get_context, get_line_number
3637
from .pattern_defaults import PatternCategory
38+
from .prohibition_context import is_directly_prohibited
3739

3840
logger = get_logger(__name__)
3941

@@ -111,8 +113,40 @@
111113
]
112114
MP2_PATTERNS = MP2_CONTENT_PATTERNS + MP2_PROSE_PATTERNS
113115

116+
# Report explicit state adoption at the instruction, even when its source
117+
# is a separate linked document with an otherwise benign hardware state.
118+
# The bounded gap accepts a wrapped reference and dots inside link paths,
119+
# but cannot borrow the target from a later sentence or paragraph. Bounded
120+
# inline decorators keep the original source span and cannot hide an action.
121+
_ADOPTION_MARKUP = r"[*_`]{0,3}"
122+
_ADOPTION_DIALOGUE = (
123+
rf"(?:conversation|chat|dialogue){_ADOPTION_MARKUP}"
124+
rf"(?:\s+{_ADOPTION_MARKUP}(?:state|history|context|transcript))?"
125+
)
126+
_ADOPTION_ACTION_SOURCE = (
127+
rf"(?<!\w){_ADOPTION_MARKUP}(?:treat|consider|regard|use|adopt){_ADOPTION_MARKUP}\s+"
128+
rf"(?:(?:the|this|that){_ADOPTION_MARKUP}\s+)?"
129+
rf"(?:\[\s*)?{_ADOPTION_MARKUP}(?:reset\s+)?state{_ADOPTION_MARKUP}(?!\w)"
130+
)
131+
_MP3_STATE_ADOPTION_PATTERN = (
132+
_ADOPTION_ACTION_SOURCE
133+
# A later adoption action owns its own target and prohibition context.
134+
+ rf"(?:(?!{_ADOPTION_ACTION_SOURCE})(?:[^.!?]|\.(?=\S))){{0,512}}?\bas\s+"
135+
rf"{_ADOPTION_MARKUP}(?:your{_ADOPTION_MARKUP}\s+{_ADOPTION_MARKUP}"
136+
rf"(?:{_ADOPTION_DIALOGUE}|memory)"
137+
rf"|(?:the{_ADOPTION_MARKUP}\s+)?{_ADOPTION_MARKUP}"
138+
rf"(?:agent|assistant|llm|(?:ai|language)\s+model)(?:'s|’s){_ADOPTION_MARKUP}\s+"
139+
rf"{_ADOPTION_MARKUP}(?:{_ADOPTION_DIALOGUE}|memory|context|state|history|transcript))"
140+
rf"{_ADOPTION_MARKUP}(?!\w)(?:[.!?][*_`]{{1,3}})?"
141+
)
142+
_ADOPTION_PARAGRAPH_BOUNDARY = re.compile(
143+
rf"(?>{LOGICAL_LINE_BREAK.pattern})[ \t]*(?:>[ \t]*)*"
144+
rf"(?>{LOGICAL_LINE_BREAK.pattern})"
145+
)
146+
114147
# MP3: Memory Manipulation — direct modification of agent memory/state
115148
MP3_PATTERNS = [
149+
(_MP3_STATE_ADOPTION_PATTERN, 0.85),
116150
(
117151
r"(?:clear|reset|wipe|erase|delete|purge)\s+(?:your\s+)?(?:memory|context|state|history|conversation)",
118152
0.8,
@@ -295,6 +329,16 @@
295329
_MAX_LAYOUT_ONLY_SPAN = 256
296330

297331

332+
def _iter_state_adoption_matches(content: str) -> Iterator[re.Match[str]]:
333+
"""Keep adoption and its target in one paragraph, including blockquote blanks."""
334+
pattern = re.compile(_MP3_STATE_ADOPTION_PATTERN, re.IGNORECASE | re.MULTILINE)
335+
start = 0
336+
for boundary in _ADOPTION_PARAGRAPH_BOUNDARY.finditer(content):
337+
yield from pattern.finditer(content, start, boundary.start())
338+
start = boundary.end()
339+
yield from pattern.finditer(content, start)
340+
341+
298342
def _is_layout_only_span(span: str, max_cosmetic_span: int = _MAX_LAYOUT_ONLY_SPAN) -> bool:
299343
"""Return True when a captured MP2 span is only layout glyphs and whitespace."""
300344
if len(span) > max_cosmetic_span:
@@ -622,9 +666,18 @@ def ctx(start: int) -> str:
622666
)
623667
)
624668
for pattern, confidence in MP3_PATTERNS:
625-
for match in static_runner.iter_paragraph_matches(
626-
pattern, content, re.IGNORECASE | re.MULTILINE
627-
):
669+
mp3_matches = (
670+
_iter_state_adoption_matches(content)
671+
if pattern == _MP3_STATE_ADOPTION_PATTERN
672+
else static_runner.iter_paragraph_matches(
673+
pattern, content, re.IGNORECASE | re.MULTILINE
674+
)
675+
)
676+
for match in mp3_matches:
677+
if pattern == _MP3_STATE_ADOPTION_PATTERN and is_directly_prohibited(
678+
content, match.start(), match.end(), allow_clause_prefix=True
679+
):
680+
continue
628681
if (
629682
_is_benign_reset_state_coverage(content, match)
630683
or _is_benign_hardware_reset_state(content, match)

0 commit comments

Comments
 (0)