-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathdsl_to_contract.py
More file actions
2202 lines (1966 loc) · 75.4 KB
/
Copy pathdsl_to_contract.py
File metadata and controls
2202 lines (1966 loc) · 75.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Sponsio contract DSL → :class:`DetFormula` over the pattern library.
This module owns the **text DSL** layer: a bounded set of English-shaped
phrasings (e.g. ``tool `check_policy` must precede `issue_refund```) that
compile, via regex/keyword matching, into calls on
:mod:`sponsio.patterns.library` and validated :class:`DetFormula`
objects. The DSL is intentionally small. it is not a free-form NL
parser.
Layer diagram::
free-form NL ──(optional LLM extractor)──▶ text DSL ──▶ patterns ──▶ DetFormula
(this file) (library.py)
Entry points (cheapest first):
* :func:`parse_dsl`. strict rule-based DSL parser. Pure Python, no LLM.
* :func:`parse_contract` (aliased as ``parse_nl_unified``). tries
``parse_dsl``, then ``classify_sto``, then optionally an
``llm_extractor`` for free-form NL → DSL translation. Raises
:class:`ContractSyntaxError` if nothing matches.
* :func:`nl_to_contracts` / :func:`build_contracts`. batch helpers
used by older callers.
If a contract string looks like English but is **not** in the DSL, the
right fix is almost never "add another regex rule". it's to translate
it into the DSL up front, or pass ``llm_extractor=`` to
:func:`parse_contract`. Loosening the rule cascade tends to create
spurious matches on plain English ("delivered before christmas"). The
DSL is a feature, not a fallback.
Supported phrasing shapes (non-exhaustive. see ``_KEYWORD_RULES`` for
the full table)::
`A` must precede `B` → must_precede
`A` always followed by `B` → always_followed_by
never call `A` and `B` together → mutual_exclusion
`A` at most N times → rate_limit / bounded_retry
cooldown of N steps between `A`s → cooldown
`A` requires permission `P` → requires_permission
`tool` args must not contain "X" → arg_blacklist
response under N words / no PII → max_length / no_pii / no_keywords
called `A` → trigger atom (for ``.assume()``)
:class:`OpenAIBackend` provides the ``nl_to_contracts(llm_backend=…)``
path, which is a thinner per-line translator distinct from the
unified-pipeline LLM extractor (see :mod:`sponsio.generation.llm_extraction`).
"""
from __future__ import annotations
import re
from dataclasses import dataclass, field
from typing import Any, Callable, Protocol, runtime_checkable
from sponsio.formulas.evaluator import evaluate
from sponsio.models.agent import Agent
from sponsio.models.contract import Contract
from sponsio.patterns.library import (
DetFormula,
always_followed_by,
approval_freshness,
arg_allowlist,
arg_blacklist,
arg_length_limit,
bounded_retry,
arg_value_range,
audit_after,
backup_before_destructive,
confirm_after_source,
cooldown,
ctx_matches_required,
ctx_required,
dangerous_bash_commands,
dangerous_sql_verbs,
delegation_depth_limit,
data_intact,
deadline,
destructive_action_gate,
dry_run_before_commit,
duplicate_call_limit,
idempotent,
irreversible_once,
loop_detection,
must_confirm,
must_precede,
workflow_step,
mutual_exclusion,
never_together,
no_data_leak,
no_reversal,
rate_limit,
redirect_to_safe,
required_steps_completion,
requires_permission,
sanitized_before_sink,
scope_limit,
segregation_of_duty,
token_budget,
tool_allowlist,
untrusted_source_gate,
)
# ---------------------------------------------------------------------------
# Data structures
# ---------------------------------------------------------------------------
@dataclass
class ParsedConstraint:
"""A single constraint parsed from natural language.
Attributes:
original_nl: The original natural language text.
pattern_name: Name of the matched pattern function.
args: Positional arguments for the pattern function.
kwargs: Keyword arguments for the pattern function.
formula: The compiled DetFormula (None if parsing failed).
error: Error message if parsing or validation failed.
"""
original_nl: str
pattern_name: str = ""
args: tuple = ()
kwargs: dict = field(default_factory=dict)
formula: DetFormula | None = None
error: str = ""
@property
def ok(self) -> bool:
return self.formula is not None and not self.error
@dataclass
class NLParseResult:
"""Result of parsing one or more NL constraint descriptions.
Attributes:
constraints: List of parsed constraints (one per NL line).
formulas: Successfully compiled ``DetFormula`` objects
(not ``Contract``s. wrap them yourself if needed).
errors: Lines that failed to parse.
"""
constraints: list[ParsedConstraint] = field(default_factory=list)
@property
def formulas(self) -> list[DetFormula]:
return [c.formula for c in self.constraints if c.ok]
# Backward-compatible alias: previous code called ``.contracts`` but
# the returned items are formulas, not ``Contract`` objects. Kept to
# avoid churn; prefer ``.formulas``.
contracts = formulas
@property
def errors(self) -> list[ParsedConstraint]:
return [c for c in self.constraints if not c.ok]
@property
def ok(self) -> bool:
return len(self.errors) == 0 and len(self.constraints) > 0
# ---------------------------------------------------------------------------
# Pattern registry
# ---------------------------------------------------------------------------
_PATTERN_REGISTRY: dict[str, Callable[..., DetFormula]] = {
"must_precede": must_precede,
"always_followed_by": always_followed_by,
"never_together": never_together,
"requires_permission": requires_permission,
"no_data_leak": no_data_leak,
"mutual_exclusion": mutual_exclusion,
"rate_limit": rate_limit,
"no_reversal": no_reversal,
"idempotent": idempotent,
"deadline": deadline,
"must_confirm": must_confirm,
"cooldown": cooldown,
"segregation_of_duty": segregation_of_duty,
"bounded_retry": bounded_retry,
"arg_allowlist": arg_allowlist,
"arg_blacklist": arg_blacklist,
"arg_length_limit": arg_length_limit,
"scope_limit": scope_limit,
"data_intact": data_intact,
# Layer 1: OWASP Agentic Top 10
"destructive_action_gate": destructive_action_gate,
"untrusted_source_gate": untrusted_source_gate,
"required_steps_completion": required_steps_completion,
"loop_detection": loop_detection,
"tool_allowlist": tool_allowlist,
"redirect_to_safe": redirect_to_safe,
"dangerous_bash_commands": dangerous_bash_commands,
"dangerous_sql_verbs": dangerous_sql_verbs,
"irreversible_once": irreversible_once,
"confirm_after_source": confirm_after_source,
# Layer 2: Atom extensions
"token_budget": token_budget,
"delegation_depth_limit": delegation_depth_limit,
"arg_value_range": arg_value_range,
# External-context gating (caller identity, content source, signed
# message metadata, …). pairs with ``observe_context()``
# / hook ``context`` field.
"ctx_required": ctx_required,
"ctx_matches_required": ctx_matches_required,
# Workflow hygiene
"dry_run_before_commit": dry_run_before_commit,
"backup_before_destructive": backup_before_destructive,
"audit_after": audit_after,
"approval_freshness": approval_freshness,
"sanitized_before_sink": sanitized_before_sink,
"duplicate_call_limit": duplicate_call_limit,
# X-style prescriptive next-step obligation: G(trigger -> X(next_action)).
# Dual-message symmetry counterpart of always_followed_by (F-style):
# workflow_step is bounded (decided at the very next event), F is
# unbounded (decided at trace end).
"workflow_step": workflow_step,
}
def get_available_patterns() -> dict[str, Callable[..., DetFormula]]:
"""Returns the registry of available pattern functions."""
return dict(_PATTERN_REGISTRY)
# ---------------------------------------------------------------------------
# LLM backend protocol
# ---------------------------------------------------------------------------
@runtime_checkable
class LLMBackend(Protocol):
"""Protocol for LLM backends used in NL → contract translation."""
def translate(
self, nl_text: str, available_patterns: list[str]
) -> list[dict[str, Any]]:
"""Translates NL text to pattern function calls.
Args:
nl_text: Natural language constraint description.
available_patterns: List of available pattern function names.
Returns:
List of dicts with keys: "pattern", "args", "kwargs".
Example: [{"pattern": "must_precede", "args": ["A", "B"], "kwargs": {}}]
"""
...
# ---------------------------------------------------------------------------
# Concrete LLM backend: OpenAI
# ---------------------------------------------------------------------------
class OpenAIBackend:
"""Concrete LLM backend using OpenAI API for NL -> contract translation."""
def __init__(self, model: str = "gpt-4o-mini", api_key: str | None = None):
try:
import openai
except ImportError:
raise ImportError("Install openai: pip install 'sponsio[llm]'")
self._client = openai.OpenAI(api_key=api_key)
self._model = model
def translate(
self, nl_description: str, available_patterns: list[str]
) -> list[dict]:
"""Translate NL constraints to pattern function calls via OpenAI.
Returns:
List of dicts with keys: "pattern", "args", "kwargs".
"""
import json as _json
system_prompt = self._build_system_prompt(available_patterns)
response = self._client.chat.completions.create(
model=self._model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": nl_description},
],
response_format={"type": "json_object"},
temperature=0.0,
)
result = _json.loads(response.choices[0].message.content)
return result.get("contracts", [])
def _build_system_prompt(self, available_patterns: list[str]) -> str:
"""Build system prompt listing available patterns and expected output format."""
pattern_list = "\n".join(f" - {p}" for p in available_patterns)
return (
"You are a constraint translator. Given natural language constraint descriptions, "
"translate each one into a pattern function call.\n\n"
f"Available patterns:\n{pattern_list}\n\n"
"Each pattern takes positional string arguments (action/tool names) and an optional "
"'desc' keyword argument. rate_limit takes (action: str, count: int).\n\n"
"Return a JSON object with a 'contracts' array. Each element should have:\n"
' - "pattern": one of the available pattern names\n'
' - "args": list of positional arguments\n'
' - "kwargs": dict of keyword arguments (at minimum {"desc": "<original NL>"})\n\n'
"Example output:\n"
'{"contracts": [{"pattern": "must_precede", "args": ["A", "B"], '
'"kwargs": {"desc": "A before B"}}]}'
)
# ---------------------------------------------------------------------------
# NLContractGenerator. convenience wrapper with optional LLM fallback
# ---------------------------------------------------------------------------
class NLContractGenerator:
"""High-level NL -> contract generator with optional LLM backend.
When ``backend`` is provided and rule-based parsing fails for a line,
the LLM backend is used as a fallback. When ``backend`` is None,
only rule-based parsing is used (current default behavior).
"""
def __init__(self, registry: dict | None = None, backend: LLMBackend | None = None):
self._backend = backend # None = rule-based only
self._registry = registry or dict(_PATTERN_REGISTRY)
def generate(self, nl_text: str, agent: Any | None = None) -> Any:
"""Parse NL text, falling back to LLM backend if rule-based fails."""
return nl_to_contracts(nl_text, agent=agent, llm_backend=self._backend)
# ---------------------------------------------------------------------------
# Rule-based keyword matcher (fallback when no LLM is available)
# ---------------------------------------------------------------------------
# Input length caps. bound the worst case of any downstream regex on
# user-provided NL. Real contract descriptions are 1-2 sentences;
# these limits are generous (~100 KB total / 10 KB per line) but cut
# off pathological inputs that could trigger polynomial backtracking
# in patterns like ``\s+(.+)`` or ``(\d+)\s*\w+``.
_MAX_NL_INPUT_LEN = 100_000
_MAX_NL_LINE_LEN = 10_000
# Regex patterns for extracting action names from NL text
_QUOTED_RE = re.compile(r'["\']([^"\']+)["\']')
_BACKTICK_RE = re.compile(r"`([^`]+)`")
# Bare snake_case identifiers (at least one underscore to avoid matching
# common English words). Must be preceded by a word boundary and not be a
# known stop word.
_BARE_SNAKE_RE = re.compile(r"\b([a-z][a-z0-9]*(?:_[a-z0-9]+)+)\b")
# Known "not tool names". common English phrases that happen to look
# snake_case-ish when squished.
_BARE_STOP = frozenset(
{
"at_most",
"at_least",
"no_more",
"per_session",
"per_call",
"must_not",
"should_not",
"same_session",
"each_other",
}
)
# Positional patterns: extract the word right after these cue phrases.
# e.g. "tool deploy" → "deploy", "call delete" → "delete"
_CUE_PHRASE_RE = re.compile(
r"(?:^|\s)(?:tool|tools|action|actions|call(?:ing)?|run(?:ning)?|"
r"execute|invoke|use|using)\s+"
r"([a-zA-Z][a-zA-Z0-9_]*)",
re.IGNORECASE,
)
# Extended cue: "call X and Y", "tools X and Y", etc.
_CUE_AND_RE = re.compile(
r"(?:^|\s)(?:tool|tools|call(?:ing)?|run(?:ning)?|execute|invoke)\s+"
r"([a-zA-Z][a-zA-Z0-9_]*)\s+and\s+([a-zA-Z][a-zA-Z0-9_]*)",
re.IGNORECASE,
)
# Word before "command"/"args"/"argument". likely a tool name
# e.g. "bash command" → "bash"
_TOOL_BEFORE_FIELD_RE = re.compile(
r"([a-zA-Z][a-zA-Z0-9_]*)\s+(?:command|args?|arguments?|input|params?)",
re.IGNORECASE,
)
# Common English words that should NOT be extracted as tool names
_STOP_WORDS = frozenset(
{
"a",
"an",
"the",
"is",
"are",
"was",
"were",
"be",
"been",
"being",
"it",
"its",
"this",
"that",
"these",
"those",
"my",
"your",
"our",
"to",
"of",
"in",
"on",
"at",
"by",
"for",
"with",
"from",
"as",
"and",
"or",
"but",
"not",
"no",
"nor",
"so",
"if",
"then",
"than",
"both",
"each",
"every",
"all",
"any",
"few",
"more",
"most",
"some",
"only",
"once",
"just",
"also",
"very",
"too",
"can",
"may",
"must",
"will",
"shall",
"should",
"would",
"could",
"do",
"does",
"did",
"have",
"has",
"had",
"get",
"got",
"make",
"made",
"let",
"set",
"same",
"different",
"other",
"new",
"old",
"first",
"last",
"before",
"after",
"between",
"within",
"always",
"never",
"them",
"they",
"he",
"she",
"we",
"you",
"me",
"him",
"her",
"us",
"confirmed",
"called",
"required",
"allowed",
"restricted",
"file",
"data",
"permission",
"admin",
"user",
"agent",
}
)
def _extract_actions(text: str) -> list[str]:
"""Extracts tool/action names from text.
Priority order:
1. Backtick-delimited: ``tool `name` ``
2. Quoted: ``"name"`` or ``'name'``
3. Bare snake_case identifiers (e.g. ``check_policy``, ``issue_refund``)
4. Positional cue phrases: word after "tool"/"call"/"run"/"execute"
Only one extraction method is used. whichever yields results first.
"""
actions = _BACKTICK_RE.findall(text) or _QUOTED_RE.findall(text)
if actions:
return actions
# Fallback 1: bare snake_case identifiers (high confidence)
bare = [m for m in _BARE_SNAKE_RE.findall(text) if m not in _BARE_STOP]
if bare:
return bare
# Fallback 2: "call X and Y" / "tools X and Y" pattern
and_match = _CUE_AND_RE.search(text)
if and_match:
a, b = and_match.group(1), and_match.group(2)
result = [w for w in [a, b] if w.lower() not in _STOP_WORDS]
if len(result) >= 2:
return result
# Fallback 3: positional extraction after cue phrases
cue_matches = _CUE_PHRASE_RE.findall(text)
cue_actions = [w for w in cue_matches if w.lower() not in _STOP_WORDS]
if cue_actions:
return cue_actions
# Fallback 4: word before "command"/"args" (for arg_blacklist context)
field_match = _TOOL_BEFORE_FIELD_RE.search(text)
if field_match:
word = field_match.group(1)
if word.lower() not in _STOP_WORDS:
return [word]
return []
# Keyword rules: (keywords_to_match, pattern_name, min_args)
# Order matters. first match wins. More specific patterns first.
_KEYWORD_RULES: list[tuple[list[str], str, int]] = [
# --- arg_allowlist (must come before arg_blacklist for "must be one of"
# phrases that could otherwise trip the "must not contain" rule) ---
(
[
r"arg(?:ument)?s?\s+(?:must\s+be|must\s+match)\s+(?:one\s+of|in)",
r"(?:command|input|param|recipient|to|host|domain|url)\s+must\s+be\s+(?:one\s+of|in)",
r"allowlist",
r"whitelist",
r"only\s+(?:allow|permit)\s+(?:the\s+)?(?:value|values|recipient|recipients|host|hosts|domain|domains)",
r"restrict\s+(?:.*\s+)?(?:to|in)\s+(?:the\s+)?(?:allowed|allow-listed|whitelisted)\s+(?:value|values|set|list)",
],
"arg_allowlist",
2,
),
# --- arg_blacklist (must come before general "must not contain") ---
(
[
r"arg(?:ument)?s?\s+(?:must\s+)?not\s+contain",
r"(?:command|input|param)\s+must\s+not\s+contain",
r"blacklist",
r"must\s+not\s+contain\s+(?:.*(?:rm\s*-rf|sudo|DROP|eval))",
r"forbid.*(?:in\s+(?:arguments?|params?|input))",
r"ban\s+(?:patterns?|commands?)\s+in",
],
"arg_blacklist",
2,
),
# --- scope_limit ---
(
[
r"restrict\s+(?:file\s+)?(?:access|operations?)\s+to\s+(?:`|/)",
r"scope\s*limit",
r"only\s+(?:access|read|write|operate)\s+(?:files?\s+)?(?:in|within|under)\s+(?:`|/)",
r"file\s+(?:operations?\s+)?restricted\s+to\s+(?:`|/)",
r"(?:paths?|files?|directories?)\s+(?:must\s+be\s+)?(?:within|under)\s+(?:`|/)",
r"confine.*to\s+(?:/|`)",
r"restricted\s+to\s+(?:`?/)",
],
"scope_limit",
2,
),
# --- data_intact ---
(
[
r"data\s+(?:must\s+)?remain\s+(?:un(?:modified|changed|altered)|intact)",
r"(?:must\s+)?(?:only|exclusively)\s+(?:read|operate\s+on)\s+(?:from\s+)?(?:original|unmodified)",
r"data\s*intact",
r"read[- ]?only\s+(?:from|on)\b",
],
"data_intact",
2,
),
# --- Workflow hygiene: dry-run / backup / audit / fresh approval ---
(
[
r"dry[- ]?run.*before",
r"plan.*before.*(?:apply|commit|deploy|execute)",
r"(?:apply|commit|deploy|execute).*requires?.*dry[- ]?run",
],
"dry_run_before_commit",
2,
),
(
[
r"backup.*before",
r"snapshot.*before",
r"(?:delete|drop|destroy|destructive).*requires?.*(?:backup|snapshot)",
],
"backup_before_destructive",
2,
),
(
[
r"audit.*after",
r"log.*after",
r"(?:must|should).*be\s+(?:audited|logged)",
r"(?:audit|log)\s+(?:required|needed)",
],
"audit_after",
2,
),
(
[
r"fresh\s+approval",
r"approval.*(?:within|expires?|expire)",
r"(?:approval|authorization).*fresh",
r"(?:approve|approval).*(?:\d+)\s+steps?",
],
"approval_freshness",
3,
),
(
[
r"sanitize.*before",
r"saniti[sz]ed.*before",
r"(?:untrusted|external|web|email).*sanitize.*(?:before|then)",
r"(?:source|input).*sanitizer.*sink",
],
"sanitized_before_sink",
3,
),
(
[
r"duplicate\s+call",
r"same.*request.*at most",
r"same\s+(?:tool|api|request|args?).*at most",
r"repeat(?:ed)?\s+(?:same\s+)?(?:call|request)",
r"no duplicate",
r"never repeat",
],
"duplicate_call_limit",
3,
),
# --- Bounded retry (must come before rate_limit. "at most N retries") ---
(
[
r"at most.*retr",
r"retry.*at most",
r"bounded retry",
r"max.*retries",
r"maximum.*retries",
r"no more than.*retr",
r"limit.*retries?\s+to\b",
],
"bounded_retry",
2,
),
# --- Rate limit ---
(
[
r"rate\s*limit",
r"at most.*times",
r"maximum.*invocations",
r"limit.*(?:calls|invocations|uses)\b",
r"must not be called more than",
r"(?:at most|no more than|up to|maximum|max)\s+(\d+)\s+(?:per|times|calls)",
r"limit.*to\s+(\d+)\s+(?:per|times|calls)",
],
"rate_limit",
2,
),
# --- Idempotent ---
(
[
r"idempotent",
r"at most once",
r"only (?:once|run once|call(?:ed)? once)",
r"called? once\b",
r"should only (?:run|be called|execute) once",
r"single invocation",
r"no repeated calls?\b",
],
"idempotent",
1,
),
# --- Mutual exclusion ---
(
[
r"mutually exclusive",
r"exactly one of",
r"either.*or.*not both",
r"cannot (?:both|call both)",
r"only one of",
r"at most one of",
],
"mutual_exclusion",
2,
),
# --- Never together → routes to mutual_exclusion ---
(
[
r"never together",
r"never both",
r"not at the same time",
r"never co-occur",
r"must never.*called together",
r"never be called together",
r"not.*(?:in|within|during)\s+(?:the\s+)?same\s+session",
r"do not call.*(?:and|,).*(?:in|within|during)\s+(?:the\s+)?same",
],
"mutual_exclusion",
2,
),
# --- Cooldown ---
(
[
r"cooldown",
r"cool\s*down\s+(?:of|between|period\s+of)\s+\d+",
r"minimum\s+\d+\s+steps?\s+between",
r"at least\s+\d+\s+steps?\s+between",
r"wait\s+\d+\s+steps?\s+between",
r"gap of\s+\d+\s+steps?",
r"interval\s+(?:of\s+)?\d+\s+steps?",
],
"cooldown",
2,
),
# --- Segregation of duty ---
(
[
r"segregation of dut",
r"separation of dut",
r"same agent.*cannot.*both",
r"different agent",
r"cannot do both",
r"must be (?:done|performed) by different",
r"two[- ]person\s+rule",
r"dual\s+control",
],
"segregation_of_duty",
2,
),
# --- Deadline ---
(
[
r"within\s+\d+\s+steps?\s+(?:of|after)",
r"deadline\s+(?:of\s+)?\d+\s+steps?",
r"must.*within\s+\d+\s+steps?",
r"at most\s+\d+\s+steps?\s+after",
],
"deadline",
3,
),
# --- Must confirm ---
(
[
r"must be confirmed",
r"confirm(?:ation)?\s+(?:before|required|needed)",
r"requires?\s+confirmation",
r"must confirm before",
r"(?:needs?|requires?)\s+(?:user\s+)?(?:approval|consent)\s+before",
r"without\s+confirmation",
r"never\s+call.*without\s+confirm",
],
"must_confirm",
1,
),
# --- No reversal ---
(
[
r"cannot.*after\s+approv",
r"no reversal",
r"never\s+reverse",
r"cannot\s+deny\s+after",
r"cannot\s+reject\s+after",
r"cannot\s+contradict",
r"cannot\s+be\s+reversed",
r"(?:never|cannot|must\s+not)\s+(?:call\s+)?.*after\s+(?:calling\s+)?",
r"forbidden\s+after",
r"prohibited\s+after",
r"must\s+not\s+follow",
r"must\s+not.*after",
r"should\s+not\s+follow",
r"not\s+allowed\s+after",
r"once.*(?:cannot|must\s+not|never)",
r"irreversible",
],
"no_reversal",
2,
),
# --- Requires permission ---
(
[
r"requires?\s+(?:\w+\s+)?permission",
r"needs?\s+permission",
r"must\s+have\s+permission",
r"(?:requires?|needs?)\s+(?:\w+\s+)?(?:authorization|auth)\b",
r"requires?\s+admin\b",
r"(?:only\s+)?(?:authorized|permitted)\s+(?:users?|agents?|roles?)\s+(?:can|may)",
r"require\s+\w+\s+(?:permission|role|access)\s+to\b",
],
"requires_permission",
2,
),
# --- No data leak ---
(
[
r"no data leak",
r"data must not (?:flow|leak|be\s+sent)",
r"no leak",
r"(?:must\s+)?not\s+(?:send|transmit|expose|share).*(?:to\s+external|outside)",
r"protect.*from\s+(?:leaking|exposure)",
],
"no_data_leak",
2,
),
# --- Always followed by ---
(
[
r"(?:must\s+be\s+|always\s+)?followed\s+by",
r"must eventually follow",
r"eventually.*after",
r"after\s+(?:calling\s+)?.*(?:always|must)\s+(?:call\s+|run\s+)?",
r"(?:always|must)\s+(?:call|run|execute)\s+.*after",
r"whenever.*(?:is\s+)?called.*(?:must|should|always)",
r"(?:should|must)\s+(?:always\s+)?come\s+after",
],
"always_followed_by",
2,
),
# --- Must precede (LAST. most general) ---
# Requires tool-like context to avoid matching plain English "before".
(
[
r"precede",
r"prior to\s+`",
r"`[^`]+`\s+(?:must\s+)?(?:be\s+)?(?:called\s+|run\s+|executed\s+)?before\s+`",
r"before\s+(?:calling\s+)?`",
r"required\s+before\s+`",
r"is\s+(?:a\s+)?prerequisite\s+for\b",
r"(?:always|must)\s+run\s+`[^`]+`\s+first",
r"is\s+required\s+before",
r"needs?\s+to\s+(?:be\s+)?(?:called|run)\s+before",
r"must\s+(?:be\s+)?(?:called|run|executed)\s+first",
],
"must_precede",
2,
),
]
def _match_keyword_rule(text: str) -> tuple[str, int] | None:
"""Matches text against keyword rules, returns (pattern_name, min_args) or None."""
lower = text.lower()
for keywords, pattern_name, min_args in _KEYWORD_RULES:
for kw in keywords:
if re.search(kw, lower):
return pattern_name, min_args
return None
# Word → number mapping for small numbers
_WORD_NUMBERS: dict[str, int] = {
"one": 1,
"once": 1,
"two": 2,
"twice": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
"ten": 10,
}
def _parse_number(text: str) -> int | None:
"""Parse a digit or word number (e.g. '3', 'three', 'once')."""
m = re.search(r"(\d+)", text)
if m:
return int(m.group(1))
lower = text.lower()
for word, num in _WORD_NUMBERS.items():
if word in lower:
return num
return None
def _parse_rate_limit_count(text: str) -> int | None:
"""Extracts a numeric count from rate limit NL text."""
lower = text.lower()
m = re.search(r"at most (\d+)", lower)
if m:
return int(m.group(1))
m = re.search(r"(\d+)\s*(?:times|invocations|calls|per)", lower)
if m:
return int(m.group(1))
m = re.search(r"limit.*?(\d+)", lower)
if m:
return int(m.group(1))
m = re.search(r"(?:no more than|up to|maximum|max|more than)\s+(\d+)", lower)
if m:
return int(m.group(1))
# Word numbers after "more than" / "at most" / "no more than": e.g.
# "must not be called more than once" → 1
word_pattern = "|".join(re.escape(w) for w in _WORD_NUMBERS.keys())
m = re.search(
rf"(?:more than|at most|no more than|up to)\s+({word_pattern})\b",
lower,
)
if m:
return _WORD_NUMBERS[m.group(1)]
# Word numbers followed by "times/calls/per": e.g. "at most three times"
for word, num in _WORD_NUMBERS.items():
if word in lower and re.search(rf"{word}\s+(?:times|calls|per)", lower):
return num
return None
def _parse_retry_count(text: str) -> int | None:
"""Extracts a retry count from NL text."""
m = re.search(r"at most (\d+)\s*retr", text.lower())
if m:
return int(m.group(1))
m = re.search(r"(\d+)\s*retr", text.lower())
if m:
return int(m.group(1))
m = re.search(r"max(?:imum)?\s*(\d+)", text.lower())
if m:
return int(m.group(1))
return None
def _parse_step_count(text: str) -> int | None:
"""Extracts a step count from NL text."""
m = re.search(r"(\d+)\s*steps?", text.lower())
if m:
return int(m.group(1))
m = re.search(r"cooldown\s+(?:of\s+)?(\d+)", text.lower())
if m:
return int(m.group(1))
return None
def _extract_blacklist_patterns(text: str) -> list[str]:
"""Extracts forbidden string patterns from NL text.
Looks for quoted or backtick-delimited strings after 'contain',
'include', or specific known dangerous commands.
"""
# First try: extract from the part after "contain" / "include"
m = re.search(
r"(?:contain|include|allow|permit)\s+(.+)",
text,
re.IGNORECASE,
)
if m:
tail = m.group(1)
# Extract quoted/backtick items from the tail
items = _BACKTICK_RE.findall(tail) or _QUOTED_RE.findall(tail)
if items:
return items
# Split on "or" / "," / "and"
parts = re.split(r"\s+or\s+|\s*,\s*|\s+and\s+", tail)
return [p.strip().rstrip(".") for p in parts if p.strip()]
return []
def _extract_allowlist_patterns(text: str) -> list[str]:
"""Extracts allowed-value patterns from NL text.
Looks for quoted or backtick-delimited strings after 'one of' / 'in'
/ 'allow' / 'permit' / 'whitelist' / 'allowlist'. Falls back to
splitting the tail on 'or' / ',' / 'and'.
"""
m = re.search(
r"(?:one\s+of|in|allow(?:list)?|whitelist|permit)\s+(.+)",