Skip to content

Ledger

agent_gate.ledger

The gate's append-only ledger, one JSON Lines file per session.

The ledger is the gate's own record of every action it judged. It gives the model gate the recent trajectory and lets the history rules spot a retry of a blocked action. Claude Code's transcript is not used: it is written asynchronously and can lag the call being judged.

The ledger keeps the first 2,000 characters of each call's input with secrets redacted (:func:redact), and a session's file is deleted :data:KEEP_DAYS days after its last entry.

Ledger(session_id, root=None)

The ledger for one session.

Parameters:

Name Type Description Default
session_id str

the Claude Code session id.

required
root Path | None

the state directory; defaults to :func:gate_home.

None
Source code in src/agent_gate/ledger.py
90
91
92
def __init__(self, session_id: str, root: Path | None = None) -> None:
    safe = re.sub(r"[^A-Za-z0-9_.-]", "_", session_id) or "unknown"
    self.path = (root or gate_home()) / "sessions" / f"{safe}.jsonl"

append(action, verdict, digest)

Record one judged action.

Parameters:

Name Type Description Default
action Action

the action.

required
verdict Verdict

the gate's verdict on it.

required
digest str

the digest of the mandate it was judged under.

required
Source code in src/agent_gate/ledger.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
def append(self, action: Action, verdict: Verdict, digest: str) -> None:
    """Record one judged action.

    :param action: the action.
    :param verdict: the gate's verdict on it.
    :param digest: the digest of the mandate it was judged under.
    """
    self.path.parent.mkdir(parents=True, exist_ok=True)
    if not self.path.exists():
        self.prune()
    entry = {
        "ts": datetime.now(UTC).isoformat(timespec="seconds"),
        "tool_use_id": action.tool_use_id,
        "tool": action.tool,
        "action": redact(action.params_text(limit=None))[:ACTION_CHARS],
        "consequential": action.consequential,
        "decision": verdict.decision,
        "law": verdict.law,
        "layer": verdict.layer,
        "reason": verdict.reason,
        "mandate": digest,
    }
    with self.path.open("a", encoding="utf-8") as handle:
        handle.write(json.dumps(entry) + "\n")

entries()

Every entry so far, oldest first.

Source code in src/agent_gate/ledger.py
101
102
103
104
105
106
def entries(self) -> list[dict[str, Any]]:
    """Every entry so far, oldest first."""
    if not self.path.exists():
        return []
    with self.path.open(encoding="utf-8") as handle:
        return [json.loads(line) for line in handle if line.strip()]

prune()

Delete session ledgers whose last entry is older than :data:KEEP_DAYS.

Source code in src/agent_gate/ledger.py
94
95
96
97
98
99
def prune(self) -> None:
    """Delete session ledgers whose last entry is older than :data:`KEEP_DAYS`."""
    cutoff = time.time() - KEEP_DAYS * 86400
    for old in self.path.parent.glob("*.jsonl"):
        if old.stat().st_mtime < cutoff:
            old.unlink(missing_ok=True)

gate_home()

The gate's state directory: $AGENT_GATE_HOME or ~/.agent_gate.

Source code in src/agent_gate/ledger.py
78
79
80
def gate_home() -> Path:
    """The gate's state directory: ``$AGENT_GATE_HOME`` or ``~/.agent_gate``."""
    return Path(os.environ.get("AGENT_GATE_HOME", "~/.agent_gate")).expanduser().resolve()

redact(text)

Replace the secrets the gate can recognize in text with [redacted].

Recognized: private key blocks, tokens with a known prefix (Anthropic, OpenAI, GitHub, Slack, AWS), Authorization headers, bearer tokens, and values given to fields or flags named like a key, token, secret or password. A secret of no recognizable shape is not found.

Parameters:

Name Type Description Default
text str

the text to clean.

required

Returns:

Type Description
str

the text with each recognized secret replaced.

Source code in src/agent_gate/ledger.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def redact(text: str) -> str:
    """Replace the secrets the gate can recognize in ``text`` with ``[redacted]``.

    Recognized: private key blocks, tokens with a known prefix (Anthropic,
    OpenAI, GitHub, Slack, AWS), ``Authorization`` headers, bearer tokens,
    and values given to fields or flags named like a key, token, secret or
    password. A secret of no recognizable shape is not found.

    :param text: the text to clean.
    :return: the text with each recognized secret replaced.
    """
    for pattern, keep in _SECRETS:
        text = pattern.sub(lambda m, keep=keep: m.expand(keep) + "[redacted]", text)
    return text