Skip to content

Rules

agent_gate.rules

Layer 1: deterministic rules.

These checks are lookups and pattern matches. No wording of a command can talk them out of a verdict, which is why they run first and why the model gate may only make their verdicts stricter.

The shell checks are heuristics, not a shell parser. They catch the common shapes of network access, outward actions, identity changes and writes outside the mandate. A command they cannot read is sent to a person.

ask(law, reason)

An ask from the rules layer.

Source code in src/agent_gate/rules.py
184
185
186
def ask(law: int, reason: str) -> Verdict:
    """An ask from the rules layer."""
    return Verdict("ask", law, reason, "rules")

check(action, mandate)

Layer 1: judge one action against the mandate.

Parameters:

Name Type Description Default
action Action

the action.

required
mandate Mandate

the governing mandate.

required
Source code in src/agent_gate/rules.py
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
def check(action: Action, mandate: Mandate) -> Verdict:
    """Layer 1: judge one action against the mandate.

    :param action: the action.
    :param mandate: the governing mandate.
    """
    if not action.consequential:
        return PASS
    verdicts: list[Verdict] = [PASS]
    if not mandate.found:
        verdicts.append(
            ask(
                2,
                "No mandate is set for this project, so a person must confirm each action. Write .agent_gate/mandate.toml.",
            )
        )
    if action.tool in WRITE_TOOLS:
        raw = str(action.params.get(WRITE_TOOLS[action.tool], ""))
        verdicts.append(_check_write_path(_resolve(raw, action.cwd), mandate))
    elif action.tool == "Bash":
        verdicts.append(check_bash(action, mandate))
    elif action.tool in DELEGATION_TOOLS:
        verdicts.append(check_delegation(action, mandate))
    elif action.tool == "WebFetch":
        host = urlsplit(str(action.params.get("url", ""))).hostname or ""
        if mandate.found and not mandate.allows_host(host):
            verdicts.append(ask(2, f"{host or 'This URL'} is not a host in the mandate."))
    elif action.tool == "Artifact" and action.params.get("action", "publish") in {
        "publish",
        "delete",
    }:
        verdicts.append(
            ask(2, "Publishing or deleting an artifact is an outward action a person must confirm.")
        )
    elif action.is_mcp and action.tool not in mandate.mcp_tools:
        verdicts.append(ask(2, f"{action.tool} is not an MCP tool the mandate allows."))
    return strictest(*verdicts)

check_bash(action, mandate)

Judge a Bash command.

Parameters:

Name Type Description Default
action Action

a Bash action.

required
mandate Mandate

the governing mandate.

required
Source code in src/agent_gate/rules.py
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
def check_bash(action: Action, mandate: Mandate) -> Verdict:
    """Judge a Bash command.

    :param action: a Bash action.
    :param mandate: the governing mandate.
    """
    command = action.command
    verdicts: list[Verdict] = [PASS]
    marks = [str(gate_home()), ".agent_gate", ".claude/settings"]
    if mandate.source is not None:
        marks.append(str(mandate.source))
    if _touches_gate(command, marks):
        verdicts.append(
            deny(
                2,
                "This command touches the gate, the mandate or the hook settings; an agent may not change its own mandate or gate.",
            )
        )
    for pattern, what in IDENTITY:
        if pattern.search(command):
            verdicts.append(
                deny(4, f"This command {what}; an agent may not create or change an identity.")
            )
    for pattern, what in OBFUSCATED:
        if pattern.search(command):
            verdicts.append(
                ask(2, f"This command {what}, so the gate cannot tell what it touches.")
            )
    if mandate.outward != "pass":
        for pattern, what in OUTWARD:
            if pattern.search(command):
                reason = f"This is {what}, an outward action a person must confirm."
                verdicts.append(deny(2, reason) if mandate.outward == "deny" else ask(2, reason))
    verdicts.extend(_check_commands(command, action, mandate))
    return strictest(*verdicts)

check_delegation(action, mandate)

Judge the prompt of a subagent call (Agent, or Task in older Claude Code).

A subagent's own tool calls reach the gate too, but its prompt is where an agent hands off what it may not do itself. The prompt is prose, so what it names outside the mandate goes to a person; it is not denied.

Parameters:

Name Type Description Default
action Action

an Agent or Task action.

required
mandate Mandate

the governing mandate.

required
Source code in src/agent_gate/rules.py
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
def check_delegation(action: Action, mandate: Mandate) -> Verdict:
    """Judge the prompt of a subagent call (``Agent``, or ``Task`` in older Claude Code).

    A subagent's own tool calls reach the gate too, but its prompt is where
    an agent hands off what it may not do itself. The prompt is prose, so
    what it names outside the mandate goes to a person; it is not denied.

    :param action: an ``Agent`` or ``Task`` action.
    :param mandate: the governing mandate.
    """
    prompt = str(action.params.get("prompt", ""))
    found: list[str] = []
    for url in URL_RE.findall(prompt):
        url = url.rstrip(".,;:)")
        remote = normalize_remote(url)
        if remote and mandate.allows_remote(remote):
            continue
        host = urlsplit(url).hostname or ""
        if host and not mandate.allows_host(host):
            found.append(f"the host {host}")
    recipients = []
    if MAIL_INTENT.search(prompt):
        recipients = [a for a in EMAIL_RE.findall(prompt) if not mandate.allows_recipient(a)]
    found += [f"the address {a}" for a in recipients]
    for pattern, what in IDENTITY:
        if pattern.search(prompt):
            found.append(f"a step that {what}")
    if mandate.outward != "pass":
        for pattern, what in OUTWARD:
            if pattern.search(prompt):
                found.append(what)
    if not found:
        return PASS
    return ask(
        1 if recipients else 2,
        "This subagent prompt names " + ", ".join(found) + ", outside the mandate; "
        "a person must confirm the hand-off.",
    )

check_history(action, mandate, entries, digest)

Layer 1, history: actions that resemble blocked ones, and repeated denials.

A close resemblance to a denied action asks a person rather than denying: the rules still deny a true repeat on their own, and a rewording that slips past them goes to a person. Repeated denials count only within the last :data:DENIAL_WINDOW consequential actions, so a burst of blocked attempts stops the agent but a long session recovers once the agent works inside the mandate again. Only denials made under the current mandate count, so a person also clears them by changing the mandate.

Parameters:

Name Type Description Default
action Action

the action.

required
mandate Mandate

the governing mandate.

required
entries list[dict[str, Any]]

the session's ledger entries.

required
digest str

the current mandate's digest.

required
Source code in src/agent_gate/rules.py
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
def check_history(
    action: Action, mandate: Mandate, entries: list[dict[str, Any]], digest: str
) -> Verdict:
    """Layer 1, history: actions that resemble blocked ones, and repeated denials.

    A close resemblance to a denied action asks a person rather than
    denying: the rules still deny a true repeat on their own, and a
    rewording that slips past them goes to a person. Repeated denials count
    only within the last :data:`DENIAL_WINDOW` consequential actions, so a burst of
    blocked attempts stops the agent but a long session recovers once the
    agent works inside the mandate again. Only denials made under the
    current mandate count, so a person also clears them by changing the
    mandate.

    :param action: the action.
    :param mandate: the governing mandate.
    :param entries: the session's ledger entries.
    :param digest: the current mandate's digest.
    """
    if not action.consequential:
        return PASS
    denied = [e for e in entries if e.get("decision") == "deny" and e.get("mandate") == digest]
    params = redact(action.params_text(limit=None))[:ACTION_CHARS]
    for entry in denied[-50:]:
        if entry.get("tool") != action.tool:
            continue
        ratio = SequenceMatcher(None, params, entry.get("action", "")).ratio()
        if ratio >= mandate.retry_similarity:
            return Verdict(
                "ask",
                3,
                f"This resembles an action blocked earlier in this session "
                f"({entry.get('reason', '')}). A person should confirm it is not a retry.",
                "history",
            )
    consequential = [e for e in entries if e.get("consequential", True)]
    recent = [
        e
        for e in consequential[-DENIAL_WINDOW:]
        if e.get("decision") == "deny" and e.get("mandate") == digest
    ]
    if len(recent) >= mandate.max_denials:
        return Verdict(
            "ask",
            3,
            f"The gate has blocked {len(recent)} of the last {DENIAL_WINDOW} consequential actions; a person should review before the agent continues.",
            "history",
        )
    return PASS

deny(law, reason)

A deny from the rules layer.

Source code in src/agent_gate/rules.py
179
180
181
def deny(law: int, reason: str) -> Verdict:
    """A deny from the rules layer."""
    return Verdict("deny", law, reason, "rules")

drop_heredoc_text(command)

Remove the bodies of heredocs that feed a program other than a shell.

A heredoc fed to cat or python is text, not commands; reading its lines as commands gives false alarms. A heredoc fed to a shell keeps its body, since those lines are commands.

Parameters:

Name Type Description Default
command str

the command line.

required
Source code in src/agent_gate/rules.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
def drop_heredoc_text(command: str) -> str:
    """Remove the bodies of heredocs that feed a program other than a shell.

    A heredoc fed to ``cat`` or ``python`` is text, not commands; reading its
    lines as commands gives false alarms. A heredoc fed to a shell keeps its
    body, since those lines are commands.

    :param command: the command line.
    """

    def body(match: re.Match) -> str:
        line_start = command.rfind("\n", 0, match.start()) + 1
        if SHELL_FEED.search(command[line_start : match.start()]):
            return match.group(0)
        return match.group(0)[: match.start(4) - match.start()] + match.group(2)

    return HEREDOC_RE.sub(body, command)

normalize_remote(url)

Reduce a git URL to host/owner/repo, lowercased.

Parameters:

Name Type Description Default
url str

an https, ssh, git or scp-style (user@host:owner/repo) URL.

required

Returns:

Type Description
str | None

the normalized remote, or None if it is not a URL.

Source code in src/agent_gate/rules.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
def normalize_remote(url: str) -> str | None:
    """Reduce a git URL to ``host/owner/repo``, lowercased.

    :param url: an https, ssh, git or scp-style (``user@host:owner/repo``) URL.
    :return: the normalized remote, or ``None`` if it is not a URL.
    """
    url = url.strip().strip("'\"")
    scp = re.fullmatch(r"[\w.-]+@([A-Za-z0-9.-]+):(.+)", url)
    if scp:
        host, path = scp.group(1), scp.group(2)
    elif "://" in url:
        parts = urlsplit(url)
        host, path = parts.hostname or "", parts.path
    else:
        return None
    path = path.strip("/").removesuffix(".git")
    owner_repo = "/".join(path.split("/")[:2])
    return f"{host.lower()}/{owner_repo.lower()}" if host and owner_repo else None

split_commands(command)

Split a shell command at ;, |, &&, || and newlines outside quotes.

Parameters:

Name Type Description Default
command str

the command line.

required

Returns:

Type Description
list[str]

the stripped, non-empty pieces.

Source code in src/agent_gate/rules.py
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
def split_commands(command: str) -> list[str]:
    """Split a shell command at ``;``, ``|``, ``&&``, ``||`` and newlines outside quotes.

    :param command: the command line.
    :return: the stripped, non-empty pieces.
    """
    pieces, current, quote, i = [], [], "", 0
    while i < len(command):
        char = command[i]
        if quote:
            current.append(char)
            if char == "\\" and quote == '"' and i + 1 < len(command):
                current.append(command[i + 1])
                i += 1
            elif char == quote:
                quote = ""
        elif char == "\\" and i + 1 < len(command):
            current.append(command[i : i + 2])
            i += 1
        elif char in "'\"":
            quote = char
            current.append(char)
        elif char in ";|\n" or (char == "&" and command[i : i + 2] == "&&"):
            pieces.append("".join(current))
            current = []
            if command[i : i + 2] in {"&&", "||"}:
                i += 1
        else:
            current.append(char)
        i += 1
    pieces.append("".join(current))
    return [p.strip() for p in pieces if p.strip()]