-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathlibrary.py
More file actions
2218 lines (1795 loc) · 76.7 KB
/
Copy pathlibrary.py
File metadata and controls
2218 lines (1795 loc) · 76.7 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
"""Pattern library — the constraint primitive layer.
Patterns are the building blocks the rest of Sponsio compiles to: each
function takes plain string args and returns a ``DetFormula`` (an LTL
AST plus the original description + pattern name, for diagnostics).
Users never need to write raw LTL.
The pattern library is *not* itself the contract DSL. the DSL is the
text layer above it (``generation/dsl_to_contract.py``), which parses
phrasings like ``tool `check_policy` must precede `issue_refund``` into
the corresponding pattern call. Patterns can also be invoked directly
from Python or produced by the LLM extractor; the DSL is just one of
several front-ends.
Available patterns (35 det + 1 deprecated):
Core temporal (14):
must_precede(A, B) -- A must happen before B
always_followed_by(A, B) -- whenever A, eventually B
never_together(A, B) -- [DEPRECATED → mutual_exclusion]
no_reversal(A, B) -- B forbidden after A commits
requires_permission(tool, perm) -- tool needs permission
no_data_leak(src, ext) -- no flow from src to ext
mutual_exclusion(A, B) -- at most one ever called
rate_limit(action, N) -- action called at most N times
idempotent(action) -- action may occur at most once
deadline(trigger, action, N) -- action within N steps of trigger
must_confirm(action) -- confirmation before action
cooldown(action, N) -- min N steps between calls
segregation_of_duty(A, B) -- same agent can't do both
bounded_retry(action, N) -- at most N retries
loop_detection(action, N) -- max N consecutive calls
Argument / path (5):
arg_blacklist(tool, param, patterns) -- forbid patterns in tool args
arg_allowlist(tool, param, patterns) -- arg must match one of the allowed patterns
scope_limit(tool, allowed) -- restrict tool to allowed paths
arg_length_limit(tool, param, N)-- max N chars in argument field
data_intact(tool, paths) -- tool must use original data
OWASP agentic security (8):
destructive_action_gate(tool, role) -- human approval + role
untrusted_source_gate(sources, sinks) -- re-confirm after untrusted input
required_steps_completion(trigger, steps) -- all steps must follow trigger
tool_allowlist(tools) -- only listed tools allowed
dangerous_bash_commands(forbidden) -- preset: ban shell commands
dangerous_sql_verbs(tool, forbidden) -- preset: ban SQL verbs
irreversible_once(action) -- at most once per session
confirm_after_source(source, action) -- confirm after untrusted source
Resource / delegation (3):
token_budget(max_tokens, scope) -- limit token consumption
arg_value_range(tool, field, min, max) -- constrain numeric args
delegation_depth_limit(max_depth) -- limit delegation chain
Workflow hygiene (6):
dry_run_before_commit(dry_run, commit) -- dry-run before commit
backup_before_destructive(backup, action) -- backup before destructive action
audit_after(action, audit) -- audit/log must follow action
approval_freshness(approval, action, N) -- approval expires after N steps
sanitized_before_sink(source, sanitizer, sink) -- sanitizer after source before sink
duplicate_call_limit(tool, pattern, N) -- cap repeated matching calls
"""
from __future__ import annotations
import re as _re
from dataclasses import dataclass
from typing import Any
from sponsio.formulas.formula import (
Atom,
Not,
And,
Or,
Implies,
G,
F,
X,
U,
Formula,
Var,
Const,
Le,
Ge,
)
_NAMESPACED_TOOL_RE = _re.compile(r"^[A-Za-z_][\w-]*:[A-Za-z_][\w-]*$")
def _is_namespaced_tool_name(tool: str) -> bool:
"""Decide whether ``foo:bar`` is a literal namespaced tool name
(Claude Code plugin skill / MCP server convention) rather than the
``tool:argpattern`` shortcut used by ``bans`` / ``called_with``.
Heuristic: both sides of ``:`` must be bare identifiers. no
whitespace, no regex metacharacters, no shell-like punctuation.
This lets us recognise ``acme:fetch_data`` / ``my-plugin:hello`` /
``mcp__server:tool`` as literal tool names while preserving the
existing pattern usages (``bash:rm -rf``, ``bash:sed -i``,
``bash:python -c``) which all contain whitespace.
The corner case ``bash:rm`` (a hypothetical bare-identifier
argpattern) tips toward "literal tool name". no shipped pack
uses that form, so the change is safe.
"""
return bool(_NAMESPACED_TOOL_RE.match(str(tool)))
def _physical_tool(tool: str) -> str:
"""Return the tool name to ground against.
Strips the ``:argpattern`` suffix when the form is a true
pattern-shortcut; passes namespaced literal names through.
"""
if ":" in tool and not _is_namespaced_tool_name(tool):
return tool.split(":", 1)[0]
return tool
def _called(tool: str) -> Atom:
"""Create a ``called`` / ``called_with`` atom for ``tool``.
``tool:argpattern`` -> ``called_with(physical, argpattern)``.
Bare ``tool`` or namespaced-literal ``plugin:skill`` ->
``called(tool)``.
"""
tool = str(tool)
if ":" in tool and not _is_namespaced_tool_name(tool):
physical, pattern = tool.split(":", 1)
return Atom("called_with", physical, pattern)
return Atom("called", tool)
def _count_var(tool: str) -> Var:
"""Create a ``count`` / ``count_with`` Var for ``tool``.
Same disambiguation as :func:`_called`.
"""
tool = str(tool)
if ":" in tool and not _is_namespaced_tool_name(tool):
physical, pattern = tool.split(":", 1)
return Var("count_with", physical, pattern)
return Var("count", tool)
@dataclass(frozen=True)
class DetFormula:
"""Wraps an LTL formula with a human-readable description.
Delegates operator overloading (``>>``, ``&``, ``|``, ``~``) to the
inner formula so det formulas compose transparently.
Attributes:
formula: The underlying LTL formula.
desc: Human-readable description of the property.
pattern_name: Name of the pattern function that created this.
liveness: True for liveness patterns (``F``, ``always_followed_by``,
``required_steps_completion``, …). used by the runtime to
suppress spurious mid-trace violations.
args: Original arguments the factory was invoked with. Needed for
lossless discovery-store round-trip: ``_extract_args_from_formula``
used to walk the formula tree and only recovered ``called()``
tool names, silently dropping numeric thresholds (``rate_limit``
N, ``deadline`` steps, ``bounded_retry`` max, …). When a stored
pattern was re-materialized, those numeric args collapsed to
nothing and the rule degraded (#13). Patterns now record their
args directly, so store serialization is exact.
"""
formula: Formula
desc: str
pattern_name: str
liveness: bool = False
args: tuple = ()
enforcement_strategy: Any = None
"""Optional per-pattern strategy override. When set, the monitor
routes a violation of this formula to ``enforcement_strategy``
instead of the default ``DetBlock``. Used by patterns whose
intent is something other than "block on violation". currently
``redirect_to_safe`` (which attaches a ``RedirectToSafe`` so a
violation surfaces as a substitute tool call). The user's
explicit ``policy={...}`` mapping still wins over this when both
are set, since the user has the final say on enforcement choice.
"""
# Delegate all formula operations to the inner formula
def __rshift__(self, other):
return self.formula >> other
def __and__(self, other):
return self.formula & other
def __or__(self, other):
return self.formula | other
def __invert__(self):
return ~self.formula
# Backward-compatible alias
AnnotatedFormula = DetFormula
def _ensure_non_empty(value: str, *, pattern: str, arg: str) -> str:
"""Reject ``""``, ``None``, or whitespace-only tool names at factory time.
Why this exists
---------------
``_called("")`` produces the atom ``called()`` which the grounding layer
never emits, so the formula is vacuously satisfied *and* vacuously
unreachable. Silent vacuity is the exact failure mode we're hardening
against here. the operator thinks they added a guard; the runtime sees
nothing.
"""
if not isinstance(value, str) or not value.strip():
raise ValueError(
f"{pattern}: argument {arg!r} must be a non-empty string "
f"(got {value!r}). An empty tool name silently disables the "
"contract. this is almost never what you want."
)
return value
def _ensure_distinct(a: str, b: str, *, pattern: str, arg_a: str, arg_b: str) -> None:
"""Reject degenerate ``f(x, x)`` pattern calls.
Why this exists
---------------
Most two-arg patterns (``must_precede``, ``always_followed_by``,
``mutual_exclusion``, ``no_reversal``, ``deadline``, …) become trivially
satisfied or trivially violated when the two tool names collide:
* ``must_precede("A", "A")`` compiles to ``!called(A) U called(A)``.
every call to ``A`` satisfies the Until at the same step, so the
constraint is *always* True. Operators typing the same tool twice by
mistake get a silent no-op.
* ``mutual_exclusion("A", "A")`` is ``G(called(A) → G(!called(A)))``,
which forbids any second call to ``A`` (silently turning into a weak
``idempotent`` with a misleading pattern name).
* ``deadline("A", "A", n)`` is satisfied at the trigger step itself
and is therefore a no-op.
All of these are almost certainly user errors; surface them at
construction time with a clear message instead of letting the trace
evaluator quietly pass.
"""
_ensure_non_empty(a, pattern=pattern, arg=arg_a)
_ensure_non_empty(b, pattern=pattern, arg=arg_b)
if a == b:
raise ValueError(
f"{pattern}: {arg_a!r} and {arg_b!r} must refer to different "
f"tools (got {a!r} for both). A same-tool pattern is either "
"vacuously satisfied or silently degenerates into a different "
"contract. use ``idempotent`` / ``rate_limit`` if you meant "
"'at most once' / 'at most N times'."
)
def workflow_step(
trigger: Atom,
next_action: Atom,
desc: str = "",
) -> DetFormula:
"""Prescriptive next-step obligation: ``G(trigger -> X(next_action))``.
Reads as "whenever ``trigger`` holds at the current event, the agent
must satisfy ``next_action`` at the very next event". This is the
*prescriptive* counterpart of the existing block-style patterns
(``never_together``, ``arg_blacklist``, ...): instead of saying
"you must not do X", a workflow_step says "you must do X next".
Both ``trigger`` and ``next_action`` may be ANY atomic predicate
(``called(...)``, ``ctx(k, v)``, ``arg_field_has(...)``, ...) — the
runtime extracts them via the same valuation machinery that powers
block contracts, so the symmetry is genuine.
Use case: workflow contracts where ``policy.md`` says "if you
observe X, the next step is Y" — the contract author maps the
diagnostic outcome (pushed into ``ctx`` by an integration hook or
pulled from a tool result) to the prescribed remediation tool.
Example::
workflow_step(
Atom("ctx", "roaming_status", "disabled"),
Atom("called", "toggle_roaming"),
desc="after detecting roaming disabled, the next action must be toggle_roaming",
)
Args:
trigger: Atomic predicate; when this is True at an event, the
obligation is incurred.
next_action: Atomic predicate; must hold at the very next event.
desc: Optional human-readable description (default auto-built
from the two atoms).
Returns:
A ``DetFormula`` (NOT marked liveness — X is one-step bounded
and the runtime can decide it after a single event, unlike F).
Caveat (end-of-trace): under weak finite-trace semantics ``X`` is
vacuously true at the last position, so a ``trigger`` that fires on
the *final* event of a batch-verified trace incurs no violation
(there is no "next" event to inspect). In incremental enforce mode
this self-corrects — when the next event arrives, a non-matching
next action is blocked and rolled back, effectively forcing
``next_action`` — but a whole-trace ``verify`` / replay will
silently pass a trailing trigger. Mirrors the ``rotate_session``
liveness caveat; relevant only to post-hoc batch checks, not live
guarding.
"""
if not isinstance(trigger, Atom) or not isinstance(next_action, Atom):
raise TypeError(
f"workflow_step requires Atom arguments; got "
f"trigger={type(trigger).__name__}, next_action={type(next_action).__name__}"
)
formula = G(Implies(trigger, X(next_action)))
return DetFormula(
formula=formula,
desc=desc
or (
f"after {trigger.predicate}({', '.join(trigger.args)}) "
f"the next event must satisfy "
f"{next_action.predicate}({', '.join(next_action.args)})"
),
pattern_name="workflow_step",
liveness=False,
args=(trigger, next_action),
)
def must_precede(before: str, after: str, desc: str = "") -> DetFormula:
"""Enforces that one action must happen before another.
Compiles to: ``!called(after) U called(before)``. the ``after`` action
is forbidden until ``before`` has occurred at least once.
Args:
before: Tool or action that must occur first.
after: Tool or action that must occur second.
desc: Optional human-readable description.
Returns:
A ``DetFormula`` encoding the ordering constraint.
"""
_ensure_distinct(
before, after, pattern="must_precede", arg_a="before", arg_b="after"
)
# after is forbidden until before appears, OR after is never called
formula = Or(
U(Not(_called(after)), _called(before)),
G(Not(_called(after))),
)
return DetFormula(
formula=formula,
desc=desc or f"{before} must precede {after}",
pattern_name="must_precede",
args=(before, after),
)
def always_followed_by(trigger: str, response: str, desc: str = "") -> DetFormula:
"""Enforces that a trigger is always eventually followed by a response.
Compiles to: ``G(called(trigger) -> F(called(response)))``.
Args:
trigger: Tool or action that triggers the obligation.
response: Tool or action that must eventually follow.
desc: Optional human-readable description.
Returns:
A ``DetFormula`` encoding the liveness constraint.
"""
_ensure_distinct(
trigger,
response,
pattern="always_followed_by",
arg_a="trigger",
arg_b="response",
)
formula = G(Implies(_called(trigger), F(_called(response))))
return DetFormula(
formula=formula,
desc=desc or f"{trigger} must always be followed by {response}",
pattern_name="always_followed_by",
liveness=True,
args=(trigger, response),
)
def never_together(a: str, b: str, desc: str = "") -> DetFormula:
"""Deprecated: use ``mutual_exclusion`` instead.
In sequential traces, two tool calls are always at different timesteps,
so this pattern's formula ``G(!(called(A) & called(B)))`` is trivially
satisfied and can never detect violations.
This function now delegates to ``mutual_exclusion`` for correct behavior.
Args:
a: First action.
b: Second action.
desc: Optional human-readable description.
Returns:
A ``DetFormula`` from ``mutual_exclusion``.
"""
import warnings
warnings.warn(
"never_together is deprecated. use mutual_exclusion instead. "
"In sequential traces, never_together can never trigger.",
DeprecationWarning,
stacklevel=2,
)
return mutual_exclusion(a, b, desc=desc or f"{a} and {b} must never occur together")
def no_reversal(commitment: str, contradiction: str, desc: str = "") -> DetFormula:
"""Enforces that a contradicting action never occurs after a commitment.
Once the commitment action fires, the contradiction must never happen.
This catches cross-turn contradictions at the tool-call level.
Example: ``no_reversal("approve_refund", "deny_refund")`` means once a
refund is approved, it can never be denied in the same session.
Compiles to: ``G(called(commitment) -> G(!called(contradiction)))``.
Args:
commitment: The action that establishes a commitment.
contradiction: The action that would contradict the commitment.
desc: Optional human-readable description.
Returns:
A ``DetFormula`` encoding the no-reversal constraint.
"""
_ensure_distinct(
commitment,
contradiction,
pattern="no_reversal",
arg_a="commitment",
arg_b="contradiction",
)
formula = G(Implies(_called(commitment), G(Not(_called(contradiction)))))
return DetFormula(
formula=formula,
desc=desc or f"{contradiction} must never occur after {commitment}",
pattern_name="no_reversal",
args=(commitment, contradiction),
)
def requires_permission(tool: str, permission: str, desc: str = "") -> DetFormula:
"""Enforces that a tool call requires a specific permission.
Compiles to: ``G(called(tool) -> perm(P))``.
Args:
tool: Tool name that requires authorization.
permission: Permission label that must be held.
desc: Optional human-readable description.
Returns:
A ``DetFormula`` encoding the permission guard.
"""
formula = G(Implies(_called(tool), Atom("perm", permission)))
return DetFormula(
formula=formula,
desc=desc or f"{tool} requires permission {permission}",
pattern_name="requires_permission",
args=(tool, permission),
)
def no_data_leak(source: str, external: str, desc: str = "") -> DetFormula:
"""Enforces that data never flows from a source to an external sink.
Compiles to: ``G(contains(source) -> !flow(source, external))``.
Args:
source: Data field or agent that must be protected.
external: External agent or sink that must not receive the data.
desc: Optional human-readable description.
Returns:
A ``DetFormula`` encoding the data-leak prohibition.
"""
_ensure_distinct(
source, external, pattern="no_data_leak", arg_a="source", arg_b="external"
)
formula = G(Implies(Atom("contains", source), Not(Atom("flow", source, external))))
return DetFormula(
formula=formula,
desc=desc or f"no data leak from {source} to {external}",
pattern_name="no_data_leak",
args=(source, external),
)
def mutual_exclusion(a: str, b: str, desc: str = "") -> DetFormula:
"""Enforces that exactly one of two actions may occur across the trace.
If ``a`` happens, ``b`` must never happen (at any point), and vice versa.
Compiles to: ``G(called(a) -> G(!called(b))) & G(called(b) -> G(!called(a)))``.
This is stronger than ``never_together`` which only prevents co-occurrence
at the *same* timestep. ``mutual_exclusion`` prevents both from ever
appearing in the same trace.
Args:
a: First mutually exclusive action.
b: Second mutually exclusive action.
desc: Optional human-readable description.
Returns:
A ``DetFormula`` encoding the mutual-exclusion constraint.
"""
_ensure_distinct(a, b, pattern="mutual_exclusion", arg_a="a", arg_b="b")
formula = And(
G(Implies(_called(a), G(Not(_called(b))))),
G(Implies(_called(b), G(Not(_called(a))))),
)
return DetFormula(
formula=formula,
desc=desc or f"{a} and {b} are mutually exclusive",
pattern_name="mutual_exclusion",
args=(a, b),
)
def rate_limit(action: str, max_count: int, desc: str = "") -> DetFormula:
"""Enforces a maximum invocation count for an action.
Compiles to an arithmetic constraint:
``G(count(action) <= max_count)``.
The ``count(action)`` variable must be maintained by the grounding
layer or a custom ``DetEvaluator``.
Args:
action: The action to rate-limit.
max_count: Maximum number of allowed invocations.
desc: Optional human-readable description.
Returns:
A ``DetFormula`` encoding the rate-limit constraint.
"""
formula = G(Le(_count_var(action), Const(max_count)))
return DetFormula(
formula=formula,
desc=desc or f"{action} limited to {max_count} invocations",
pattern_name="rate_limit",
args=(action, max_count),
)
# ---------------------------------------------------------------------------
# Helper: bounded temporal operators
# ---------------------------------------------------------------------------
def _bounded_eventually(phi: Formula, n: int) -> Formula:
"""Build F_bounded(phi, n) = phi | X(phi | X(phi | ...)) for n steps."""
result = phi
for _ in range(n - 1):
result = Or(phi, X(result))
return result
def _bounded_never(phi: Formula, n: int) -> Formula:
"""Build !phi & X(!phi & X(!phi & ...)) for n steps."""
result = Not(phi)
for _ in range(n - 1):
result = And(Not(phi), X(result))
return result
def _next_n(phi: Formula, n: int) -> Formula:
"""Shift ``phi`` forward by ``n`` weak-next steps."""
result = phi
for _ in range(n):
result = X(result)
return result
def _forbidden_until(until: Formula, forbidden: Formula) -> Formula:
"""``forbidden`` may not occur until ``until`` occurs, or never occurs."""
return Or(U(Not(forbidden), until), G(Not(forbidden)))
# ---------------------------------------------------------------------------
# New patterns
# ---------------------------------------------------------------------------
def idempotent(action: str, desc: str = "") -> DetFormula:
"""Enforces that an action may occur at most once in the entire session.
Compiles to: ``G(count(action) <= 1)``.
Args:
action: The action that must be idempotent.
desc: Optional human-readable description.
Returns:
A ``DetFormula`` encoding the idempotency constraint.
"""
formula = G(Le(_count_var(action), Const(1)))
return DetFormula(
formula=formula,
desc=desc or f"{action} must be idempotent (at most once)",
pattern_name="idempotent",
args=(action,),
)
def deadline(trigger: str, action: str, steps: int, desc: str = "") -> DetFormula:
"""Enforces that an action must occur within N steps after a trigger.
Compiles to: ``G(called(trigger) -> X(F_bounded(called(action), N)))``.
Args:
trigger: The event that starts the deadline.
action: The action that must happen within the deadline.
steps: Maximum number of steps allowed after the trigger.
desc: Optional human-readable description.
Returns:
A ``DetFormula`` encoding the deadline constraint.
"""
_ensure_distinct(
trigger, action, pattern="deadline", arg_a="trigger", arg_b="action"
)
if not isinstance(steps, int) or steps < 1:
raise ValueError(
f"deadline: 'steps' must be a positive integer (got {steps!r}). "
"A non-positive deadline is unsatisfiable."
)
formula = G(
Implies(
_called(trigger),
X(_bounded_eventually(_called(action), steps)),
)
)
return DetFormula(
formula=formula,
desc=desc or f"{action} must occur within {steps} steps of {trigger}",
pattern_name="deadline",
args=(trigger, action, steps),
)
def must_confirm(action: str, desc: str = "") -> DetFormula:
"""Enforces that an action requires explicit confirmation before execution.
Uses a naming convention: ``confirm_{action}`` must precede ``action``.
The confirmation tool must exist in the agent's tool set.
Compiles to: ``!called(action) U called(confirm_action)``. the action
is forbidden until the confirmation tool has been called.
Args:
action: The action that requires confirmation.
desc: Optional human-readable description.
Returns:
A ``DetFormula`` encoding the confirmation requirement.
"""
confirm_action = f"confirm_{action}"
# action is forbidden until confirm appears, OR action is never called
formula = Or(
U(Not(_called(action)), _called(confirm_action)),
G(Not(_called(action))),
)
return DetFormula(
formula=formula,
desc=desc or f"{action} requires confirmation (confirm_{action})",
pattern_name="must_confirm",
args=(action,),
)
def cooldown(action: str, steps: int, desc: str = "") -> DetFormula:
"""Enforces a minimum interval between consecutive calls to the same action.
After calling the action, it cannot be called again for N steps.
Compiles to: ``G(called(action) -> X(!called(action) & X(!called(action) & ...)))``
for N steps.
Args:
action: The action to apply cooldown to.
steps: Minimum number of steps between consecutive calls.
desc: Optional human-readable description.
Returns:
A ``DetFormula`` encoding the cooldown constraint.
"""
formula = G(
Implies(
_called(action),
X(_bounded_never(_called(action), steps)),
)
)
return DetFormula(
formula=formula,
desc=desc or f"{action} has a cooldown of {steps} steps",
pattern_name="cooldown",
args=(action, steps),
)
def segregation_of_duty(a: str, b: str, desc: str = "") -> DetFormula:
"""Enforces that the same agent cannot perform both actions in a session.
Semantically identical to ``mutual_exclusion`` but named for compliance
contexts (e.g., the same agent cannot both review and approve).
Compiles to: ``G(called(a) -> G(!called(b))) & G(called(b) -> G(!called(a)))``.
Args:
a: First action.
b: Second action.
desc: Optional human-readable description.
Returns:
A ``DetFormula`` encoding the segregation-of-duty constraint.
"""
_ensure_distinct(a, b, pattern="segregation_of_duty", arg_a="a", arg_b="b")
formula = And(
G(Implies(_called(a), G(Not(_called(b))))),
G(Implies(_called(b), G(Not(_called(a))))),
)
return DetFormula(
formula=formula,
desc=desc or f"{a} and {b} must be performed by different agents",
pattern_name="segregation_of_duty",
args=(a, b),
)
def bounded_retry(action: str, max_retries: int, desc: str = "") -> DetFormula:
"""Enforces a maximum number of retry attempts for an action.
Prevents agents from entering infinite retry loops.
Compiles to: ``G(count(action) <= max_retries)``.
Args:
action: The action to limit retries for.
max_retries: Maximum allowed invocations.
desc: Optional human-readable description.
Returns:
A ``DetFormula`` encoding the bounded-retry constraint.
"""
formula = G(Le(_count_var(action), Const(max_retries)))
return DetFormula(
formula=formula,
desc=desc or f"{action} limited to {max_retries} retries",
pattern_name="bounded_retry",
args=(action, max_retries),
)
# ---------------------------------------------------------------------------
# Argument / path / length constraints
# ---------------------------------------------------------------------------
def arg_blacklist(
tool: str, param: str, patterns: list[str], desc: str = ""
) -> DetFormula:
"""Forbids specific content in a tool call's arguments.
Compiles to LTL::
G(called(tool) → ¬arg_field_has(tool, param, p1) ∧ ¬arg_field_has(tool, param, p2) ∧ ...)
Uses ``arg_field_has`` for field-specific matching: only the value
of ``args[param]`` is checked, not the entire serialized args dict.
Args:
tool: Tool name to monitor.
param: Argument key whose value to inspect (e.g. ``"command"``).
patterns: List of regex patterns. Any match -> violation.
desc: Optional human-readable description.
Returns:
A ``DetFormula`` encoding the constraint.
"""
physical_tool = _physical_tool(tool)
body: Formula = Not(Atom("arg_field_has", physical_tool, param, patterns[0]))
for pattern in patterns[1:]:
body = And(body, Not(Atom("arg_field_has", physical_tool, param, pattern)))
formula = G(Implies(_called(tool), body))
return DetFormula(
formula=formula,
desc=desc or f"{tool}.{param} must not match forbidden patterns",
pattern_name="arg_blacklist",
args=(tool, param, tuple(patterns)),
)
def arg_allowlist(
tool: str, param: str, patterns: list[str], desc: str = ""
) -> DetFormula:
"""Restricts a tool argument's value to a whitelist of regex patterns.
The dual of :func:`arg_blacklist`: instead of banning a list of
forbidden patterns, every call must satisfy at least one of the
allowed patterns. Use this when the safe set is small and the
threat surface is "anything else" (e.g. recipient must be one of
a known set of internal IBANs, URL must point at one of an
approved set of internal hosts).
Compiles to LTL::
G(called(tool) → arg_field_has(tool, param, p1) ∨ arg_field_has(tool, param, p2) ∨ ...)
Uses ``arg_field_has`` for field-specific matching: only the value
of ``args[param]`` is checked, not the entire serialized args dict.
Args:
tool: Tool name to monitor.
param: Argument key whose value to inspect (e.g. ``"recipient"``).
patterns: List of regex patterns. The arg value must match at
least one. Empty list raises ``ValueError``.
desc: Optional human-readable description.
Returns:
A ``DetFormula`` encoding the constraint.
Raises:
ValueError: If ``patterns`` is empty (an empty allowlist would
block every call, which is almost always a config bug;
use ``tool_allowlist`` to ban a tool entirely instead).
"""
if not patterns:
raise ValueError(
"arg_allowlist: 'patterns' must be non-empty. An empty "
"allowlist would block every call to the tool. Use "
"tool_allowlist to ban the tool itself, or arg_blacklist "
"if you want to forbid specific patterns."
)
physical_tool = _physical_tool(tool)
body: Formula = Atom("arg_field_has", physical_tool, param, patterns[0])
for pattern in patterns[1:]:
body = Or(body, Atom("arg_field_has", physical_tool, param, pattern))
formula = G(Implies(_called(tool), body))
return DetFormula(
formula=formula,
desc=desc or f"{tool}.{param} must match one of the allowed patterns",
pattern_name="arg_allowlist",
args=(tool, param, tuple(patterns)),
)
def scope_limit(tool: str, allowed_paths: list[str], desc: str = "") -> DetFormula:
"""Restricts a tool's file operations to a whitelist of path prefixes.
Compiles to LTL::
G(called(tool) → arg_paths_within(tool, *allowed_paths))
Args:
tool: Tool name to restrict.
allowed_paths: List of allowed path prefixes.
desc: Optional human-readable description.
Returns:
A ``DetFormula`` encoding the constraint.
"""
# For tool:pattern format, use the physical tool name for arg_paths_within
physical_tool = _physical_tool(tool)
formula = G(
Implies(
_called(tool),
Atom("arg_paths_within", physical_tool, *allowed_paths),
)
)
return DetFormula(
formula=formula,
desc=desc or f"{tool} restricted to paths: {', '.join(allowed_paths)}",
pattern_name="scope_limit",
args=(tool, tuple(allowed_paths)),
)
def arg_length_limit(
tool: str, param: str, max_chars: int, desc: str = ""
) -> DetFormula:
"""Blocks tool calls where an argument field exceeds a length limit.
Detects code injection attacks where an agent inlines an entire
script into a command argument instead of calling the intended tool.
Compiles to LTL::
G(called(tool) → ¬arg_length_exceeds(tool, param, max_chars))
Args:
tool: Tool name to monitor (supports ``tool:pattern`` format).
param: Argument field to check length of (e.g. ``"command"``).
max_chars: Maximum allowed length in characters.
desc: Optional human-readable description.
Returns:
A ``DetFormula`` encoding the length constraint.
"""
physical_tool = _physical_tool(tool)
formula = G(
Implies(
_called(tool),
Not(Atom("arg_length_exceeds", physical_tool, param, str(max_chars))),
)
)
return DetFormula(
formula=formula,
desc=desc or f"{tool}.{param} must not exceed {max_chars} characters",
pattern_name="arg_length_limit",
args=(tool, param, max_chars),
)
def data_intact(
bound_tool: str,
original_paths: list[str],
desc: str = "",
) -> DetFormula:
"""Assumption: a tool must only operate on original, unmodified data.
Compiles to LTL::
G(arg_has(bash, bound_tool) → arg_paths_within(bash, *original_paths))
Uses ``bash`` as the default tool since ``data_intact`` was designed
for shell command checking. The ``bound_tool`` regex matches against
the args to detect the specific command (e.g. ``"grep"``).
Args:
bound_tool: Regex pattern matching the command name.
original_paths: Allowed input file path prefixes.
desc: Optional human-readable description.
Returns:
A ``DetFormula`` encoding the assumption.
"""
formula = G(
Implies(
Atom("arg_has", "bash", bound_tool),
Atom("arg_paths_within", "bash", *original_paths),
)
)
return DetFormula(
formula=formula,
desc=desc or f"{bound_tool} must use only original data from {original_paths}",
pattern_name="data_intact",
args=(bound_tool, tuple(original_paths)),
)
# ---------------------------------------------------------------------------
# Layer 1. OWASP Agentic Top 10 patterns (pure LTL over existing atoms)
# ---------------------------------------------------------------------------
def destructive_action_gate(
tool: str, approver_role: str = "approver", desc: str = ""
) -> DetFormula:
"""Gate a destructive tool behind human confirmation + role permission.
Stronger than ``must_confirm``. forces a human (or a different agent
with the approver permission) into the loop before the destructive
action can proceed.
Covers: **ASI02** (tool misuse), **ASI05** (code execution),
**ASI09** (human-agent trust).
Compiles to::
G(¬called(tool)) ∨ (¬called(tool) U (called(confirm_<tool>) ∧ perm(approver_role)))
Args:
tool: The destructive tool name.
approver_role: Permission label the confirmer must hold.
desc: Optional human-readable description.
Returns: