awgov 0.1.8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
awgov-0.1.8/PKG-INFO ADDED
@@ -0,0 +1,116 @@
1
+ Metadata-Version: 2.4
2
+ Name: awgov
3
+ Version: 0.1.8
4
+ Summary: The platform's Policy Decision Point for agent tool calls -- allow, deny plus the lane to use instead, or needs-owner.
5
+ License: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/Aitherium/awgov
7
+ Project-URL: Documentation, https://github.com/Aitherium/awgov#readme
8
+ Project-URL: Repository, https://github.com/Aitherium/awgov.git
9
+ Project-URL: Issues, https://github.com/Aitherium/awgov/issues
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ Requires-Dist: awbac
13
+ Requires-Dist: PyYAML>=6
14
+ Provides-Extra: dev
15
+ Requires-Dist: pytest>=7.0; extra == "dev"
16
+ Requires-Dist: awdecide; extra == "dev"
17
+
18
+ # awgov
19
+
20
+ The platform's Policy Decision Point for tool calls. One YAML sanction file
21
+ (`agent_policy.yaml`, the sanction file in the platform's config) decides; the answer is one of:
22
+
23
+ - **allow** — a grant covers every descriptor the call resolves to;
24
+ - **deny** — a destructive floor fired (G1..G16) or no grant covers a descriptor;
25
+ the verdict carries the **lane** that should have been used instead;
26
+ - **needs_owner** — a B2/B3 call; a decision card is raised, never a raw prompt.
27
+ The card SHOWS the whole call in its facts (the command, or every input field
28
+ but the agent's own description and timeout) and carries `call sha256:<digest>`
29
+ of it (principal, session, tool, input, cwd). When the owner approves it **with
30
+ a signed answer** (a passkey/TOTP sign-in, verified by
31
+ `awstorage.attest.verify_receipt`), the agent's re-run of that same call is
32
+ admitted **once** (`verdict.rule_id == "owner-approved"`). Refused: an unsigned
33
+ answer, a different call, a second run, a call with two steps of the kind or
34
+ carrying a secret-looking value (the card says approving runs nothing), and any
35
+ step the call's grants do not cover. A deny cools the call and its family down
36
+ for `AWGOV_ASK_TTL_S` (900 s); a session holds at most three open asks.
37
+ `AWGOV_ADMIT=0` turns admission off. The card names the session whose call it is,
38
+ so the owner's answer is written into that session's steering mailbox: the agent
39
+ that has to re-run the call hears the answer without polling the card.
40
+ - **a standing permit** lifts G12 (spend) without a card per call. The owner signs
41
+ one permit card (`awgov permit request`) whose facts ARE the grant: one op on one
42
+ loopback/fleet host, a per-call `max_price_per_hour` ceiling, a number of uses and
43
+ an expiry of at most 24 h. A spend call it covers is allowed as
44
+ `rule_id == "owner-permit"`, and each use is counted. The call must be one literal
45
+ POST to `http://<host>/api/op/<op>`, with nothing that can reroute it, and a JSON
46
+ body inside the ceiling. Anything else still asks per call. A permit never lifts a
47
+ send, a secret write or a publish.
48
+
49
+ Claude Code reaches it through a `PreToolUse` hook. P1 is **shadow**: awgov
50
+ computes and audits every call and never blocks (`hook_response` returns `{}`).
51
+ Enforce is a mode switch on the hook, not a code change.
52
+
53
+ ## API
54
+
55
+ ```python
56
+ from awgov import evaluate, hook_response, load_policy
57
+ from awgov.audit import record
58
+
59
+ verdict = evaluate(payload, principal="agent:atlas") # "owner-tty" by default
60
+ verdict.decision # "allow" | "deny" | "needs_owner"
61
+ verdict.rule_id # "G1" | "grant" | "default" | "error"
62
+ verdict.lane # the platform lane to use instead, or ""
63
+ verdict.b_code # "" | "B2" | "B3"
64
+ verdict.descriptors # ("fleet:read:podman.logs", ...)
65
+
66
+ hook_response(verdict, "shadow") # {} -- no decision
67
+ hook_response(verdict, "enforce") # {"hookSpecificOutput": {...}}
68
+ record(verdict, payload, principal, "shadow") # append-only, never raises
69
+ ```
70
+
71
+ `load_policy(path=None)` reads `AWGOV_POLICY`, else the repo's
72
+ the sanction file `agent_policy.yaml`, else a built-in **deny floor** (reads only),
73
+ and caches by mtime.
74
+
75
+ ## Parsing, not pattern matching
76
+
77
+ A command is split into steps on unquoted separators, `$(...)` substitutions are
78
+ parsed as their own commands, and every step is resolved through `env`, `sudo`,
79
+ `wsl -d X -u root --`, `nsenter`, `bash -c`, `pwsh -Command` and `cmd /c` before
80
+ it is classified on the resolved argv. `rg -n "rm -rf .git" .claude/hooks` is a
81
+ read; the text it searches for is data, never a verb.
82
+
83
+ ## CLI
84
+
85
+ ```bash
86
+ awgov check --tool Bash --command "git status"
87
+ awgov check --tool Edit --path C:/x/y.py --principal agent:lyra
88
+ echo '<PreToolUse json>' | awgov hook # AWGOV_MODE=shadow|enforce
89
+ awgov replay --days 5 # read-only audit of transcripts
90
+ awgov permit request --op burst_up --host 127.0.0.1:8200 --max-price 1.6 --uses 3 \
91
+ --session <session id> # the session the signed answer reaches
92
+ awgov permit status # permits, their terms and uses
93
+ awgov --self-test # incident + sanctioned fixture
94
+ ```
95
+
96
+ `replay` exits 1 if any READ-class command was denied (the false positive the
97
+ parser exists to prevent) and 2 if it could not read the transcripts.
98
+
99
+ ## Wiring into hookd
100
+
101
+ The durable host service (`awdk/adk/harnesses/hookd.py`) gets a `POST /pdp` route
102
+ that forwards the PreToolUse body here, sets `AITHER_PDP_PRINCIPAL` from the
103
+ daemon's session record (`owner-tty` for the owner, `agent:<name>` or
104
+ `tainted:<name>` for workers) and returns the `hook_response` JSON verbatim. The
105
+ hook must be HTTP and must never exit non-zero in shadow.
106
+
107
+ ## Tests
108
+
109
+ ```bash
110
+ python -m pytest tests -q # from this package's directory
111
+ python -m pytest ../../dev/tests/test_awgov_policy.py -q --noconftest
112
+ ```
113
+
114
+ Every incident command must deny for `owner-tty`; every sanctioned ops command
115
+ must allow for both `owner-tty` and `agent:atlas`. Tests point `AWGOV_HOME` at a
116
+ temp dir — nothing under `~/.aither` is written by a test run.
awgov-0.1.8/README.md ADDED
@@ -0,0 +1,99 @@
1
+ # awgov
2
+
3
+ The platform's Policy Decision Point for tool calls. One YAML sanction file
4
+ (`agent_policy.yaml`, the sanction file in the platform's config) decides; the answer is one of:
5
+
6
+ - **allow** — a grant covers every descriptor the call resolves to;
7
+ - **deny** — a destructive floor fired (G1..G16) or no grant covers a descriptor;
8
+ the verdict carries the **lane** that should have been used instead;
9
+ - **needs_owner** — a B2/B3 call; a decision card is raised, never a raw prompt.
10
+ The card SHOWS the whole call in its facts (the command, or every input field
11
+ but the agent's own description and timeout) and carries `call sha256:<digest>`
12
+ of it (principal, session, tool, input, cwd). When the owner approves it **with
13
+ a signed answer** (a passkey/TOTP sign-in, verified by
14
+ `awstorage.attest.verify_receipt`), the agent's re-run of that same call is
15
+ admitted **once** (`verdict.rule_id == "owner-approved"`). Refused: an unsigned
16
+ answer, a different call, a second run, a call with two steps of the kind or
17
+ carrying a secret-looking value (the card says approving runs nothing), and any
18
+ step the call's grants do not cover. A deny cools the call and its family down
19
+ for `AWGOV_ASK_TTL_S` (900 s); a session holds at most three open asks.
20
+ `AWGOV_ADMIT=0` turns admission off. The card names the session whose call it is,
21
+ so the owner's answer is written into that session's steering mailbox: the agent
22
+ that has to re-run the call hears the answer without polling the card.
23
+ - **a standing permit** lifts G12 (spend) without a card per call. The owner signs
24
+ one permit card (`awgov permit request`) whose facts ARE the grant: one op on one
25
+ loopback/fleet host, a per-call `max_price_per_hour` ceiling, a number of uses and
26
+ an expiry of at most 24 h. A spend call it covers is allowed as
27
+ `rule_id == "owner-permit"`, and each use is counted. The call must be one literal
28
+ POST to `http://<host>/api/op/<op>`, with nothing that can reroute it, and a JSON
29
+ body inside the ceiling. Anything else still asks per call. A permit never lifts a
30
+ send, a secret write or a publish.
31
+
32
+ Claude Code reaches it through a `PreToolUse` hook. P1 is **shadow**: awgov
33
+ computes and audits every call and never blocks (`hook_response` returns `{}`).
34
+ Enforce is a mode switch on the hook, not a code change.
35
+
36
+ ## API
37
+
38
+ ```python
39
+ from awgov import evaluate, hook_response, load_policy
40
+ from awgov.audit import record
41
+
42
+ verdict = evaluate(payload, principal="agent:atlas") # "owner-tty" by default
43
+ verdict.decision # "allow" | "deny" | "needs_owner"
44
+ verdict.rule_id # "G1" | "grant" | "default" | "error"
45
+ verdict.lane # the platform lane to use instead, or ""
46
+ verdict.b_code # "" | "B2" | "B3"
47
+ verdict.descriptors # ("fleet:read:podman.logs", ...)
48
+
49
+ hook_response(verdict, "shadow") # {} -- no decision
50
+ hook_response(verdict, "enforce") # {"hookSpecificOutput": {...}}
51
+ record(verdict, payload, principal, "shadow") # append-only, never raises
52
+ ```
53
+
54
+ `load_policy(path=None)` reads `AWGOV_POLICY`, else the repo's
55
+ the sanction file `agent_policy.yaml`, else a built-in **deny floor** (reads only),
56
+ and caches by mtime.
57
+
58
+ ## Parsing, not pattern matching
59
+
60
+ A command is split into steps on unquoted separators, `$(...)` substitutions are
61
+ parsed as their own commands, and every step is resolved through `env`, `sudo`,
62
+ `wsl -d X -u root --`, `nsenter`, `bash -c`, `pwsh -Command` and `cmd /c` before
63
+ it is classified on the resolved argv. `rg -n "rm -rf .git" .claude/hooks` is a
64
+ read; the text it searches for is data, never a verb.
65
+
66
+ ## CLI
67
+
68
+ ```bash
69
+ awgov check --tool Bash --command "git status"
70
+ awgov check --tool Edit --path C:/x/y.py --principal agent:lyra
71
+ echo '<PreToolUse json>' | awgov hook # AWGOV_MODE=shadow|enforce
72
+ awgov replay --days 5 # read-only audit of transcripts
73
+ awgov permit request --op burst_up --host 127.0.0.1:8200 --max-price 1.6 --uses 3 \
74
+ --session <session id> # the session the signed answer reaches
75
+ awgov permit status # permits, their terms and uses
76
+ awgov --self-test # incident + sanctioned fixture
77
+ ```
78
+
79
+ `replay` exits 1 if any READ-class command was denied (the false positive the
80
+ parser exists to prevent) and 2 if it could not read the transcripts.
81
+
82
+ ## Wiring into hookd
83
+
84
+ The durable host service (`awdk/adk/harnesses/hookd.py`) gets a `POST /pdp` route
85
+ that forwards the PreToolUse body here, sets `AITHER_PDP_PRINCIPAL` from the
86
+ daemon's session record (`owner-tty` for the owner, `agent:<name>` or
87
+ `tainted:<name>` for workers) and returns the `hook_response` JSON verbatim. The
88
+ hook must be HTTP and must never exit non-zero in shadow.
89
+
90
+ ## Tests
91
+
92
+ ```bash
93
+ python -m pytest tests -q # from this package's directory
94
+ python -m pytest ../../dev/tests/test_awgov_policy.py -q --noconftest
95
+ ```
96
+
97
+ Every incident command must deny for `owner-tty`; every sanctioned ops command
98
+ must allow for both `owner-tty` and `agent:atlas`. Tests point `AWGOV_HOME` at a
99
+ temp dir — nothing under `~/.aither` is written by a test run.
@@ -0,0 +1,25 @@
1
+ """awgov — the platform's Policy Decision Point for every tool call.
2
+
3
+ from awgov import evaluate, hook_response
4
+
5
+ verdict = evaluate(payload, principal="agent:atlas")
6
+ print(verdict.decision, verdict.rule_id, verdict.lane)
7
+ print(hook_response(verdict, "shadow")) # {} — P1 never blocks
8
+
9
+ One YAML sanction file decides; awbac's segment-aware matcher answers the grant
10
+ question; a deny can always name the lane that should have been used instead.
11
+ """
12
+
13
+ from .engine import Verdict, evaluate, principal_kind
14
+ from .hook import hook_response
15
+ from .policy import Policy, load_policy
16
+
17
+ __version__ = "0.1.8"
18
+ __all__ = [
19
+ "Verdict",
20
+ "Policy",
21
+ "evaluate",
22
+ "hook_response",
23
+ "load_policy",
24
+ "principal_kind",
25
+ ]
@@ -0,0 +1,6 @@
1
+ """``python -m awgov`` — the same CLI as the console script."""
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())
@@ -0,0 +1,374 @@
1
+ """A needs-owner call the owner APPROVED with a signed answer runs once.
2
+
3
+ The card awgov raises for a B2 verdict promises "Approve = this exact call runs
4
+ once for this session; the agent re-runs it". Until 0.1.3 nothing kept that
5
+ promise. ``evaluate()`` never read the card store, so the re-run met the same
6
+ needs-owner verdict, the answered card was no longer open, and a NEW card was
7
+ raised. Measured 2026-11-24 on a capped cloud render: approving it would have
8
+ admitted nothing, and the owner would have been asked again.
9
+
10
+ Admission is bound four ways, and every check fails closed:
11
+
12
+ * the card SHOWS the call. Its facts carry the whole command, or the whole tool
13
+ input, unclipped and unmasked. A call that carries a secret-looking value is
14
+ shown masked and can never be admitted;
15
+ * the card's facts carry ``call sha256:<digest>`` of (principal, session, tool,
16
+ everything in the input but the agent's own description and timeout, cwd). The
17
+ owner's receipt signs the facts, so an approval never admits a different call;
18
+ * the answer is ``approve`` with a receipt ``awstorage.attest.verify_receipt``
19
+ accepts: the platform's Ed25519 key, a fresh passkey/TOTP owner sign-in, this
20
+ card, this choice, these facts. A surface LABEL is never proof
21
+ (``answered_via`` is whatever the answering client wrote);
22
+ * one admission per card, recorded in awgov's own ledger before the call runs.
23
+
24
+ Every ledger read waits at most ``BUSY_S``. The PEP is an HTTP hook with a short
25
+ timeout, and a slow decision is no decision at all.
26
+
27
+ Threat model: the one awstorage.attest documents. This is a governance gate with
28
+ an audit trail for agents that use the tools, not a boundary against a hostile
29
+ local agent, which could edit the ledger under its home directory. The signed
30
+ digest is what stops one approval from admitting another call.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import hashlib
36
+ import json
37
+ import os
38
+ import sqlite3
39
+ import time
40
+ from dataclasses import dataclass
41
+ from pathlib import Path
42
+ from typing import Any, Callable, Iterable, Optional
43
+
44
+ #: The fact that binds a card to one call. The receipt signs the card's facts.
45
+ CALL_FACT_PREFIX = "call sha256:"
46
+ #: Said on every card, because an unsigned answer is recorded and admits nothing.
47
+ PASSKEY_FACT = ("Approve with your passkey (awdesk or app.aitherium.com/decide); "
48
+ "an unsigned answer runs nothing.")
49
+ #: ``AWGOV_ADMIT=0`` turns admission off (every needs-owner call stays denied).
50
+ ADMIT_ENV = "AWGOV_ADMIT"
51
+ #: The owner principals a signed answer must name (same list the platform's
52
+ #: other signed-card consumers read).
53
+ OWNERS_ENV = "AWSTORAGE_MANAGE_OWNERS"
54
+ #: Tools whose call IS their command text.
55
+ SHELL_TOOLS = ("Bash", "PowerShell")
56
+ #: Input fields that never change what runs: the agent's own label and its timeout.
57
+ _UNBOUND_FIELDS = ("description", "timeout")
58
+ #: The longest any ledger read or write may wait on a lock, in seconds.
59
+ BUSY_S = 0.3
60
+
61
+ _DDL = """
62
+ CREATE TABLE IF NOT EXISTS cards_v2 (
63
+ card_id TEXT PRIMARY KEY,
64
+ digest TEXT NOT NULL,
65
+ family TEXT NOT NULL DEFAULT '',
66
+ session TEXT NOT NULL DEFAULT '',
67
+ admissible INTEGER NOT NULL DEFAULT 1,
68
+ raised_at REAL NOT NULL
69
+ );
70
+ CREATE INDEX IF NOT EXISTS cards_v2_digest ON cards_v2(digest, raised_at);
71
+ CREATE INDEX IF NOT EXISTS cards_v2_family ON cards_v2(family, raised_at);
72
+ CREATE INDEX IF NOT EXISTS cards_v2_session ON cards_v2(session, raised_at);
73
+ CREATE TABLE IF NOT EXISTS admissions_v2 (
74
+ card_id TEXT PRIMARY KEY,
75
+ digest TEXT NOT NULL,
76
+ admitted_at REAL NOT NULL
77
+ );
78
+ """
79
+
80
+
81
+ class LedgerError(RuntimeError):
82
+ """The ledger exists but could not be read or written in time."""
83
+
84
+
85
+ #: What a card may show the owner: printable ASCII plus newline and tab. A carriage
86
+ #: return can overwrite a line in a terminal, a bidi control reorders it, and a
87
+ #: look-alike letter hides another host (second review, 2026-11-24).
88
+ def showable(text: str) -> bool:
89
+ return all(ch in "\n\t" or 32 <= ord(ch) < 127 for ch in str(text or ""))
90
+
91
+
92
+ @dataclass(frozen=True)
93
+ class Admission:
94
+ """The outcome of one admission attempt. ``why`` is always set."""
95
+
96
+ admitted: bool
97
+ card_id: str = ""
98
+ why: str = ""
99
+
100
+
101
+ def enabled(environ: Optional[dict] = None) -> bool:
102
+ env = os.environ if environ is None else environ
103
+ return str(env.get(ADMIT_ENV, "")).strip().lower() not in ("0", "false", "no", "off")
104
+
105
+
106
+ def wanted(payload: Any) -> bool:
107
+ """Only a real PreToolUse from a session is admitted.
108
+
109
+ An ``awgov check`` preview or a test payload carries no hook event, and it
110
+ must never spend the one admission an approval buys.
111
+ """
112
+ return (isinstance(payload, dict)
113
+ and str(payload.get("hook_event_name") or "") == "PreToolUse"
114
+ and bool(str(payload.get("session_id") or "").strip()))
115
+
116
+
117
+ def _canonical(obj: Any) -> str:
118
+ return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False,
119
+ default=str)
120
+
121
+
122
+ def bound_input(payload: dict) -> dict:
123
+ """The part of the tool input that decides what runs."""
124
+ tool_input = payload.get("tool_input") or {}
125
+ if not isinstance(tool_input, dict):
126
+ return {"value": tool_input}
127
+ return {k: v for k, v in tool_input.items() if k not in _UNBOUND_FIELDS}
128
+
129
+
130
+ def call_digest(payload: dict, principal: str) -> str:
131
+ """sha256 of exactly what would run: who, which session, which tool, the input
132
+ it runs with and the directory it runs in."""
133
+ body = {"v": 2, "principal": str(principal or ""),
134
+ "session": str(payload.get("session_id") or ""),
135
+ "tool": str(payload.get("tool_name") or ""), "input": bound_input(payload),
136
+ "cwd": os.path.normcase(str(payload.get("cwd") or ""))}
137
+ return hashlib.sha256(_canonical(body).encode("utf-8")).hexdigest()
138
+
139
+
140
+ def call_fact(digest: str) -> str:
141
+ return CALL_FACT_PREFIX + digest
142
+
143
+
144
+ def shown_call(payload: dict) -> str:
145
+ """The fact that shows the owner the whole call: the command of a shell tool,
146
+ otherwise every bound input field. Unclipped and unmasked by construction."""
147
+ tool = str(payload.get("tool_name") or "")
148
+ if tool in SHELL_TOOLS:
149
+ return "command: %s" % str((payload.get("tool_input") or {}).get("command") or "")
150
+ return "input: %s %s" % (tool, _canonical(bound_input(payload)))
151
+
152
+
153
+ def _home() -> Path:
154
+ home = os.environ.get("AWGOV_HOME", "").strip()
155
+ return Path(home) if home else Path.home() / ".aither" / "awgov"
156
+
157
+
158
+ def ledger_path(path: str = "") -> Path:
159
+ return Path(path) if path else _home() / "admit.sqlite"
160
+
161
+
162
+ def _connect(path: Path) -> sqlite3.Connection:
163
+ path.parent.mkdir(parents=True, exist_ok=True)
164
+ db = sqlite3.connect(str(path), timeout=BUSY_S, isolation_level=None)
165
+ db.executescript(_DDL)
166
+ return db
167
+
168
+
169
+ def ledger_ok(path: str = "") -> bool:
170
+ """True when the ledger can be opened and written within ``BUSY_S``."""
171
+ try:
172
+ db = _connect(ledger_path(path))
173
+ db.close()
174
+ return True
175
+ except (OSError, sqlite3.Error):
176
+ return False
177
+
178
+
179
+ def remember_card(digest: str, card_id: str, path: str = "", *, family: str = "",
180
+ session: str = "", admissible: bool = True) -> bool:
181
+ """Index the card raised for this exact call. Best effort: False on failure,
182
+ which only means the call cannot be admitted later (fail closed)."""
183
+ if not digest or not card_id:
184
+ return False
185
+ try:
186
+ db = _connect(ledger_path(path))
187
+ try:
188
+ db.execute("INSERT OR IGNORE INTO cards_v2(card_id, digest, family, session,"
189
+ " admissible, raised_at) VALUES (?,?,?,?,?,?)",
190
+ (card_id, digest, family, session, int(bool(admissible)),
191
+ time.time()))
192
+ finally:
193
+ db.close()
194
+ return True
195
+ except (OSError, sqlite3.Error):
196
+ return False
197
+
198
+
199
+ def recent_cards(path: str = "", *, digest: str = "", family: str = "",
200
+ session: str = "", limit: int = 1, admissible_only: bool = False) -> list:
201
+ """Card ids raised for this call, family or session, newest first. [] when nothing
202
+ was ever raised (the ledger is never created just to look); raises LedgerError
203
+ when the ledger exists and cannot answer, so a caller never mistakes a lock for
204
+ "no card yet" and raises another."""
205
+ column, value = (("digest", digest) if digest else ("family", family) if family
206
+ else ("session", session))
207
+ target = ledger_path(path)
208
+ if not value or not target.is_file():
209
+ return []
210
+ where = "%s = ?%s" % (column, " AND admissible = 1" if admissible_only else "")
211
+ try:
212
+ db = _connect(target)
213
+ try:
214
+ rows = db.execute("SELECT card_id FROM cards_v2 WHERE %s ORDER BY raised_at"
215
+ " DESC LIMIT ?" % where, (value, int(limit))).fetchall()
216
+ finally:
217
+ db.close()
218
+ except (OSError, sqlite3.Error) as exc:
219
+ raise LedgerError(str(exc)) from exc
220
+ return [str(r[0]) for r in rows]
221
+
222
+
223
+ def previous_card(digest: str, path: str = "") -> str:
224
+ """The card last raised for this exact call, or "" (also when the ledger cannot
225
+ answer: admission then refuses, which is the closed side)."""
226
+ try:
227
+ found = recent_cards(path, digest=digest)
228
+ except LedgerError:
229
+ return ""
230
+ return found[0] if found else ""
231
+
232
+
233
+ def spent(card_id: str, path: str = "") -> bool:
234
+ """True when this card already admitted its call (or the ledger cannot say)."""
235
+ target = ledger_path(path)
236
+ if not target.is_file():
237
+ return False
238
+ try:
239
+ db = _connect(target)
240
+ try:
241
+ return db.execute("SELECT 1 FROM admissions_v2 WHERE card_id = ?",
242
+ (card_id,)).fetchone() is not None
243
+ finally:
244
+ db.close()
245
+ except (OSError, sqlite3.Error):
246
+ return True
247
+
248
+
249
+ def _consume(card_id: str, digest: str, path: Path) -> bool:
250
+ """Record the one admission. False when it is already spent or cannot be written."""
251
+ try:
252
+ db = _connect(path)
253
+ try:
254
+ db.execute("INSERT INTO admissions_v2(card_id, digest, admitted_at)"
255
+ " VALUES (?,?,?)", (card_id, digest, time.time()))
256
+ return True
257
+ finally:
258
+ db.close()
259
+ except sqlite3.IntegrityError:
260
+ return False
261
+ except (OSError, sqlite3.Error):
262
+ return False
263
+
264
+
265
+ def _owners() -> list:
266
+ raw = os.environ.get(OWNERS_ENV, "")
267
+ return [o.strip() for o in raw.split(",") if o.strip()]
268
+
269
+
270
+ def _norm(fact: Any) -> str:
271
+ return " ".join(str(fact).split())
272
+
273
+
274
+ def _facts(card: Any) -> set:
275
+ raw = card.get("facts") if isinstance(card, dict) else getattr(card, "facts", None)
276
+ return {_norm(f) for f in (raw or [])}
277
+
278
+
279
+ def _field(card: Any, name: str) -> Any:
280
+ return card.get(name) if isinstance(card, dict) else getattr(card, name, None)
281
+
282
+
283
+ def _default_store():
284
+ from .ask_lane import _store # late: awask is optional
285
+ return _store()
286
+
287
+
288
+ def _default_verify() -> Callable[..., Any]:
289
+ from awstorage.attest import verify_receipt # late: the signed-answer verifier
290
+
291
+ def verify(card: Any, owners: Iterable[str]) -> Any:
292
+ # No nonce store: the receipt is bound to this card and these facts, and
293
+ # the one admission it buys is this module's own primary key.
294
+ return verify_receipt(card, owners=owners, record=False)
295
+
296
+ return verify
297
+
298
+
299
+ def admit(verdict: Any, payload: dict, principal: str, *, store: Any = None,
300
+ verify: Optional[Callable[..., Any]] = None, owners: Optional[list] = None,
301
+ ledger: str = "", consume: bool = True) -> Admission:
302
+ """Admit this needs-owner call once if the owner approved it with a signed
303
+ answer on the card that showed it. Never raises; every failure is a refusal.
304
+
305
+ ``consume=False`` answers "would it be admitted?" without spending the one
306
+ admission; the caller checks the call's other grants first, then consumes.
307
+ """
308
+ try:
309
+ if getattr(verdict, "decision", "") != "needs_owner":
310
+ return Admission(False, "", "not a needs-owner verdict")
311
+ if not enabled():
312
+ return Admission(False, "", "admission is off (%s=0)" % ADMIT_ENV)
313
+ digest = call_digest(payload, principal)
314
+ card_id = previous_card(digest, ledger)
315
+ if not card_id:
316
+ return Admission(False, "", "no card was raised for this exact call")
317
+ st = store if store is not None else _default_store()
318
+ card = st.get(card_id)
319
+ if card is None:
320
+ return Admission(False, card_id, "card %s is gone" % card_id)
321
+ status = str(_field(card, "status") or "")
322
+ if status != "answered":
323
+ return Admission(False, card_id, "card %s is %s" % (card_id, status or "unknown"))
324
+ if str(_field(card, "answer") or "") != "approve":
325
+ return Admission(False, card_id, "card %s was answered %r"
326
+ % (card_id, _field(card, "answer")))
327
+ facts = _facts(card)
328
+ if _norm(call_fact(digest)) not in facts:
329
+ return Admission(False, card_id, "card %s does not name this call" % card_id)
330
+ shown = shown_call(payload)
331
+ if not showable(shown) or _norm(shown) not in facts:
332
+ return Admission(False, card_id, "card %s did not show this call in full"
333
+ % card_id)
334
+ if _norm("rule %s" % getattr(verdict, "rule_id", "")) not in facts:
335
+ return Admission(False, card_id, "card %s was raised for another rule" % card_id)
336
+ who = owners if owners is not None else _owners()
337
+ if not who:
338
+ return Admission(False, card_id, "%s is empty: no owner to verify against"
339
+ % OWNERS_ENV)
340
+ check = verify if verify is not None else _default_verify()
341
+ try:
342
+ check(card, owners=who)
343
+ except Exception as exc: # noqa: BLE001 -- any verifier failure is a refusal
344
+ return Admission(False, card_id, "card %s: the answer is not signed by the "
345
+ "owner (%s)" % (card_id, exc))
346
+ path = ledger_path(ledger)
347
+ if spent(card_id, ledger) or (consume and not _consume(card_id, digest, path)):
348
+ return Admission(False, card_id, "card %s already admitted its call once"
349
+ % card_id)
350
+ return Admission(True, card_id, "approved once by the owner on card %s "
351
+ "(signed answer)" % card_id)
352
+ except Exception as exc: # noqa: BLE001 -- admission must never crash the PDP
353
+ return Admission(False, "", "admission failed: %s: %s" % (type(exc).__name__, exc))
354
+
355
+
356
+ __all__ = [
357
+ "ADMIT_ENV",
358
+ "Admission",
359
+ "BUSY_S",
360
+ "CALL_FACT_PREFIX",
361
+ "PASSKEY_FACT",
362
+ "admit",
363
+ "bound_input",
364
+ "call_digest",
365
+ "call_fact",
366
+ "enabled",
367
+ "ledger_path",
368
+ "previous_card",
369
+ "recent_cards",
370
+ "remember_card",
371
+ "shown_call",
372
+ "spent",
373
+ "wanted",
374
+ ]