delval-gate 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,23 @@
1
+ """delval-gate: Fail-closed delivery-permission ledger & action gate."""
2
+
3
+ from .ledger import (
4
+ ContractRule,
5
+ ContractTamperedError,
6
+ GateDecision,
7
+ Judgment,
8
+ JudgmentLedger,
9
+ JudgmentStatus,
10
+ ReuseContract,
11
+ )
12
+
13
+ __all__ = [
14
+ "ContractRule",
15
+ "ContractTamperedError",
16
+ "GateDecision",
17
+ "Judgment",
18
+ "JudgmentLedger",
19
+ "JudgmentStatus",
20
+ "ReuseContract",
21
+ ]
22
+
23
+ __version__ = "0.1.0"
delval_gate/cli.py ADDED
@@ -0,0 +1,159 @@
1
+ """Command-line interface for delval-gate."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+ import argparse
6
+ import json
7
+ import sys
8
+
9
+ from .ledger import JudgmentLedger, ReuseContract
10
+ from .mcp_server import DelValMCPServer
11
+
12
+
13
+ def build_parser() -> argparse.ArgumentParser:
14
+ ap = argparse.ArgumentParser(prog="delval-gate", description="DelVal fail-closed delivery permission gate")
15
+ ap.add_argument("--ledger", default=".delval.json", help="Path to persistent JSON ledger file")
16
+ sub = ap.add_subparsers(dest="cmd", required=True)
17
+
18
+ p_init = sub.add_parser("init", help="Initialize a new ledger (optionally binding a frozen JSON reuse contract)")
19
+ p_init.add_argument("--contract", help="Path to JSON reuse contract file")
20
+
21
+ p_reg = sub.add_parser("register", help="Register an evidence-bound judgment")
22
+ p_reg.add_argument("--jid", required=True)
23
+ p_reg.add_argument("--evidence", nargs="+", required=True)
24
+ p_reg.add_argument("--deps", nargs="*", default=[])
25
+ p_reg.add_argument("--digest", default="")
26
+ p_reg.add_argument("--passed", action="store_true", default=False)
27
+ p_reg.add_argument("--failed", action="store_true", default=False)
28
+
29
+ p_chg = sub.add_parser("change", help="Notify changed file/object paths (path or path@class)")
30
+ p_chg.add_argument("paths", nargs="+")
31
+
32
+ p_rec = sub.add_parser("recheck", help="Record a trusted verifier recheck outcome")
33
+ p_rec.add_argument("--jid", required=True)
34
+ p_rec.add_argument("--passed", action="store_true", default=False)
35
+ p_rec.add_argument("--failed", action="store_true", default=False)
36
+ p_rec.add_argument("--digest", default="")
37
+ p_rec.add_argument("--detail", default="")
38
+
39
+ p_obj = sub.add_parser("object", help="Raise an open objection against a judgment")
40
+ p_obj.add_argument("--jid", required=True)
41
+ p_obj.add_argument("--note", required=True)
42
+ p_obj.add_argument("--id", dest="objection_id")
43
+
44
+ p_res = sub.add_parser("resolve", help="Resolve an open objection with audit evidence")
45
+ p_res.add_argument("--jid", required=True)
46
+ p_res.add_argument("--id", dest="objection_id", required=True)
47
+ p_res.add_argument("--evidence", required=True)
48
+
49
+ p_wd = sub.add_parser("withdraw", help="Permanently retire a judgment (Withdrawn)")
50
+ p_wd.add_argument("--jid", required=True)
51
+ p_wd.add_argument("--reason", default="")
52
+
53
+ p_sup = sub.add_parser("supersede", help="Permanently supersede old_jid with new_jid")
54
+ p_sup.add_argument("--old", required=True)
55
+ p_sup.add_argument("--new", required=True)
56
+ p_sup.add_argument("--reason", default="")
57
+
58
+ p_gate = sub.add_parser("gate", help="Run fail-closed delivery gate (exit 0 on ALLOW, exit 2 on BLOCK)")
59
+ p_gate.add_argument("cited", nargs="*")
60
+
61
+ p_st = sub.add_parser("status", help="Show ledger status as JSON")
62
+ p_st.add_argument("jids", nargs="*")
63
+
64
+ sub.add_parser("mcp", help="Start zero-dependency JSON-RPC 2.0 MCP stdio server")
65
+ return ap
66
+
67
+
68
+ def main(argv: list[str] | None = None) -> int:
69
+ ap = build_parser()
70
+ args = ap.parse_args(argv)
71
+ ledger_path = Path(args.ledger)
72
+
73
+ if args.cmd == "mcp":
74
+ DelValMCPServer(ledger_path).serve_stdio()
75
+ return 0
76
+
77
+ if args.cmd == "init":
78
+ contract = ReuseContract.from_json_file(Path(args.contract)) if args.contract else None
79
+ ledger = JudgmentLedger(contract=contract)
80
+ ledger.save(ledger_path)
81
+ print(json.dumps({"initialized": str(ledger_path), "contract_id": ledger.contract.contract_id}))
82
+ return 0
83
+
84
+ ledger = JudgmentLedger.load(ledger_path)
85
+
86
+ if args.cmd == "register":
87
+ passed = not args.failed if (args.passed or args.failed) else True
88
+ st = ledger.register(args.jid, args.evidence, passed=passed, digest=args.digest, deps=args.deps)
89
+ ledger.save(ledger_path)
90
+ print(json.dumps({"jid": args.jid, "status": st.value}))
91
+ return 0
92
+
93
+ if args.cmd == "change":
94
+ inv = ledger.notify_change(args.paths)
95
+ ledger.save(ledger_path)
96
+ print(json.dumps({"invalidated": inv}))
97
+ return 0
98
+
99
+ if args.cmd == "recheck":
100
+ if not (args.passed or args.failed):
101
+ ap.error("recheck requires --passed or --failed")
102
+ st = ledger.recheck(args.jid, passed=bool(args.passed and not args.failed), digest=args.digest, detail=args.detail)
103
+ ledger.save(ledger_path)
104
+ print(json.dumps({"jid": args.jid, "status": st.value if st else "unknown"}))
105
+ return 0
106
+
107
+ if args.cmd == "object":
108
+ obj = ledger.raise_objection(args.jid, args.note, objection_id=args.objection_id)
109
+ ledger.save(ledger_path)
110
+ print(json.dumps({"jid": args.jid, "objection_id": obj.objection_id}))
111
+ return 0
112
+
113
+ if args.cmd == "resolve":
114
+ st = ledger.resolve_objection(args.jid, args.objection_id, audit_evidence=args.evidence)
115
+ ledger.save(ledger_path)
116
+ print(json.dumps({"jid": args.jid, "status": st.value}))
117
+ return 0
118
+
119
+ if args.cmd == "withdraw":
120
+ st = ledger.withdraw(args.jid, reason=args.reason)
121
+ ledger.save(ledger_path)
122
+ print(json.dumps({"jid": args.jid, "status": st.value}))
123
+ return 0
124
+
125
+ if args.cmd == "supersede":
126
+ st = ledger.supersede(args.old, args.new, reason=args.reason)
127
+ ledger.save(ledger_path)
128
+ print(json.dumps({"old": args.old, "new": args.new, "status": st.value}))
129
+ return 0
130
+
131
+ if args.cmd == "gate":
132
+ dec = ledger.gate(args.cited)
133
+ ledger.save(ledger_path)
134
+ print(json.dumps(dec.to_dict(), indent=2))
135
+ return 0 if dec.allow else 2
136
+
137
+ if args.cmd == "status":
138
+ jids = args.jids or sorted(ledger.judgments.keys())
139
+ out = {
140
+ "contract_id": ledger.contract.contract_id,
141
+ "judgments": {
142
+ j: {
143
+ "status": ledger.judgments[j].status.value,
144
+ "roots": sorted(ledger.judgments[j].roots),
145
+ "open_objections": [o.objection_id for o in ledger.judgments[j].open_objections()],
146
+ }
147
+ if j in ledger.judgments
148
+ else {"status": "unknown"}
149
+ for j in jids
150
+ },
151
+ }
152
+ print(json.dumps(out, indent=2))
153
+ return 0
154
+
155
+ return 1
156
+
157
+
158
+ if __name__ == "__main__":
159
+ raise SystemExit(main())
delval_gate/ledger.py ADDED
@@ -0,0 +1,515 @@
1
+ """Core DelVal five-state, ten-rule judgment ledger and fail-closed action gate.
2
+
3
+ Zero third-party dependencies (Python 3.10+ stdlib only).
4
+ Implements the formally verified semantics of Isabelle/HOL session RC_DelVal:
5
+ - Five states: valid, stale, blocked, withdrawn, superseded
6
+ - Ten operations: register (echo-immune), notify_change (with frozen reuse
7
+ contract & transitive invalidation), recheck (sole recovery gate + closure
8
+ coherence), raise_objection, resolve_objection, withdraw, supersede, cite,
9
+ gate (fail-closed), and status/audit inspection.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import asdict, dataclass, field
14
+ from enum import Enum
15
+ from pathlib import Path
16
+ from typing import Iterable, Sequence
17
+ import fnmatch
18
+ import hashlib
19
+ import json
20
+
21
+ STRUCTURAL = "structural"
22
+
23
+
24
+ class JudgmentStatus(str, Enum):
25
+ VALID = "valid"
26
+ STALE = "stale"
27
+ BLOCKED = "blocked"
28
+ WITHDRAWN = "withdrawn"
29
+ SUPERSEDED = "superseded"
30
+
31
+
32
+ class ContractTamperedError(RuntimeError):
33
+ """Raised when a frozen reuse contract file is modified after registration."""
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class ContractRule:
38
+ rule_id: str
39
+ change_classes: tuple[str, ...] # e.g. ("docs/*.md@typo", "README.md@comment")
40
+ keeps_valid: tuple[str, ...] # jid globs whose existing validity is preserved
41
+
42
+ def matches_event(self, path: str, annotation: str) -> bool:
43
+ for spec in self.change_classes:
44
+ glob, _, cond = spec.partition("@")
45
+ if fnmatch.fnmatchcase(path, glob) and (cond == "" or cond == annotation):
46
+ return True
47
+ return False
48
+
49
+ def keeps_judgment(self, jid: str) -> bool:
50
+ return any(fnmatch.fnmatchcase(jid, g) for g in self.keeps_valid)
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class ReuseContract:
55
+ contract_id: str
56
+ rules: tuple[ContractRule, ...] = ()
57
+ sha256: str = ""
58
+ source_path: str | None = None
59
+
60
+ @classmethod
61
+ def from_dict(cls, data: dict, *, sha256: str = "", source_path: str | None = None) -> "ReuseContract":
62
+ if not isinstance(data, dict):
63
+ raise ValueError("Reuse contract must be a JSON object")
64
+ cid = data.get("contract_id")
65
+ if not isinstance(cid, str) or not cid:
66
+ raise ValueError("Reuse contract requires non-empty string 'contract_id'")
67
+ raw_rules = data.get("rules", [])
68
+ if not isinstance(raw_rules, list):
69
+ raise ValueError("Reuse contract 'rules' must be a list")
70
+ rules: list[ContractRule] = []
71
+ for r in raw_rules:
72
+ if not isinstance(r, dict):
73
+ raise ValueError(f"Malformed contract rule: {r!r}")
74
+ rid = r.get("rule_id")
75
+ cc = r.get("change_classes", r.get("change_class"))
76
+ if isinstance(cc, str):
77
+ cc_tuple = tuple(p.strip() for p in cc.split("|") if p.strip())
78
+ elif isinstance(cc, list) and all(isinstance(x, str) and x for x in cc):
79
+ cc_tuple = tuple(cc)
80
+ else:
81
+ raise ValueError(f"Rule {rid!r} needs non-empty 'change_classes'")
82
+ kv = r.get("keeps_valid")
83
+ if not isinstance(rid, str) or not rid:
84
+ raise ValueError("Rule requires non-empty string 'rule_id'")
85
+ if not isinstance(kv, list) or not kv or not all(isinstance(k, str) and k for k in kv):
86
+ raise ValueError(f"Rule {rid!r} needs non-empty list 'keeps_valid'")
87
+ rules.append(ContractRule(rule_id=rid, change_classes=cc_tuple, keeps_valid=tuple(kv)))
88
+ return cls(contract_id=cid, rules=tuple(rules), sha256=sha256, source_path=source_path)
89
+
90
+ @classmethod
91
+ def from_json_file(cls, path: Path) -> "ReuseContract":
92
+ p = Path(path)
93
+ raw = p.read_bytes()
94
+ digest = hashlib.sha256(raw).hexdigest()
95
+ data = json.loads(raw.decode("utf-8"))
96
+ return cls.from_dict(data, sha256=digest, source_path=str(p.resolve()))
97
+
98
+ def to_dict(self) -> dict:
99
+ return {
100
+ "contract_id": self.contract_id,
101
+ "sha256": self.sha256,
102
+ "source_path": self.source_path,
103
+ "rules": [
104
+ {
105
+ "rule_id": r.rule_id,
106
+ "change_classes": list(r.change_classes),
107
+ "keeps_valid": list(r.keeps_valid),
108
+ }
109
+ for r in self.rules
110
+ ],
111
+ }
112
+
113
+
114
+ @dataclass
115
+ class Objection:
116
+ objection_id: str
117
+ note: str
118
+ resolved: bool = False
119
+ resolution_evidence: str = ""
120
+
121
+
122
+ @dataclass
123
+ class Judgment:
124
+ jid: str
125
+ status: JudgmentStatus
126
+ evidence: tuple[str, ...]
127
+ deps: tuple[str, ...] = ()
128
+ roots: set[str] = field(default_factory=set)
129
+ superseded_by: str | None = None
130
+ objections: list[Objection] = field(default_factory=list)
131
+ history: list[dict] = field(default_factory=list)
132
+ citations: int = 0
133
+
134
+ def open_objections(self) -> list[Objection]:
135
+ return [o for o in self.objections if not o.resolved]
136
+
137
+
138
+ @dataclass(frozen=True)
139
+ class GateDecision:
140
+ allow: bool
141
+ cited: tuple[str, ...]
142
+ closure: tuple[str, ...]
143
+ blocked_reasons: tuple[str, ...]
144
+
145
+ def to_dict(self) -> dict:
146
+ return asdict(self)
147
+
148
+
149
+ def _split_change_entry(entry: str) -> tuple[str, str]:
150
+ path, sep, ann = str(entry).rpartition("@")
151
+ if not sep or not path:
152
+ return str(entry), STRUCTURAL
153
+ return path, (ann or STRUCTURAL)
154
+
155
+
156
+ class JudgmentLedger:
157
+ """DelVal five-state, ten-rule judgment ledger and fail-closed action gate."""
158
+
159
+ def __init__(self, contract: ReuseContract | None = None) -> None:
160
+ self.contract: ReuseContract = contract or ReuseContract(contract_id="default-strict")
161
+ self.judgments: dict[str, Judgment] = {}
162
+ self.audit_log: list[str] = []
163
+
164
+ # ---- contract integrity (Commitment 2 / I-4) ----------------------------
165
+
166
+ def verify_contract_intact(self) -> None:
167
+ if not self.contract.source_path or not self.contract.sha256:
168
+ return
169
+ p = Path(self.contract.source_path)
170
+ try:
171
+ current = p.read_bytes()
172
+ except OSError as exc:
173
+ raise ContractTamperedError(f"Frozen contract unreadable: {p} ({exc})") from exc
174
+ if hashlib.sha256(current).hexdigest() != self.contract.sha256:
175
+ raise ContractTamperedError(
176
+ f"Frozen contract tampered after registration: {p} "
177
+ f"(expected sha256={self.contract.sha256})"
178
+ )
179
+
180
+ # ---- Rule 1: Aregister (echo-immune; binding is an obligation) ----------
181
+
182
+ def register(
183
+ self,
184
+ jid: str,
185
+ evidence: Sequence[str],
186
+ *,
187
+ passed: bool = True,
188
+ digest: str = "",
189
+ deps: Sequence[str] = (),
190
+ ) -> JudgmentStatus:
191
+ if not isinstance(jid, str) or not jid:
192
+ raise ValueError("jid must be a non-empty string")
193
+ ev_tuple = tuple(str(e) for e in evidence)
194
+ if not ev_tuple or any(not e for e in ev_tuple):
195
+ raise ValueError(f"Judgment {jid!r} must bind at least one non-empty evidence object")
196
+ dep_tuple = tuple(dict.fromkeys(str(d) for d in deps if d and d != jid))
197
+
198
+ if jid in self.judgments:
199
+ # Echo immunity (I-1a / I-3): duplicate ingest never revives, rebinds, or inflates roots.
200
+ j = self.judgments[jid]
201
+ j.history.append({"event": "echo", "passed": bool(passed), "digest": digest})
202
+ self.audit_log.append(f"echo ignored: {jid} (duplicate register cannot alter status)")
203
+ return j.status
204
+
205
+ # Enforce I-1b coherence at registration: cannot register valid if a known dep is non-valid.
206
+ initial_status = JudgmentStatus.VALID if passed else JudgmentStatus.STALE
207
+ if initial_status == JudgmentStatus.VALID:
208
+ bad_deps = [d for d in dep_tuple if d in self.judgments and self.judgments[d].status != JudgmentStatus.VALID]
209
+ if bad_deps:
210
+ initial_status = JudgmentStatus.STALE
211
+ self.audit_log.append(f"register deferred to stale: {jid} (non-valid deps: {', '.join(bad_deps)})")
212
+
213
+ roots = {digest} if digest else set()
214
+ self.judgments[jid] = Judgment(
215
+ jid=jid,
216
+ status=initial_status,
217
+ evidence=ev_tuple,
218
+ deps=dep_tuple,
219
+ roots=roots,
220
+ history=[{"event": "register", "passed": bool(passed), "digest": digest}],
221
+ )
222
+ self.audit_log.append(f"register: {jid} -> {initial_status.value}")
223
+ return initial_status
224
+
225
+ # ---- Dependency closure helpers ----------------------------------------
226
+
227
+ def _binds(self, j: Judgment, path: str) -> bool:
228
+ return any(path.startswith(obj) if obj.endswith("/") else path == obj for obj in j.evidence)
229
+
230
+ def dependency_closure(self, jid: str) -> set[str]:
231
+ seen: set[str] = {jid}
232
+ stack: list[str] = [jid]
233
+ while stack:
234
+ cur = stack.pop()
235
+ j = self.judgments.get(cur)
236
+ if j is None:
237
+ continue
238
+ for d in j.deps:
239
+ if d not in seen:
240
+ seen.add(d)
241
+ stack.append(d)
242
+ seen.discard(jid)
243
+ return seen
244
+
245
+ def _cascade_stale(self) -> None:
246
+ """Fixed-point closure propagation (I-1b): any valid judgment with a non-valid dep becomes stale."""
247
+ while True:
248
+ newly_stale: list[str] = []
249
+ for jid in sorted(self.judgments):
250
+ j = self.judgments[jid]
251
+ if j.status != JudgmentStatus.VALID:
252
+ continue
253
+ if any(
254
+ d not in self.judgments or self.judgments[d].status != JudgmentStatus.VALID
255
+ for d in j.deps
256
+ ):
257
+ newly_stale.append(jid)
258
+ if not newly_stale:
259
+ return
260
+ for jid in newly_stale:
261
+ self.judgments[jid].status = JudgmentStatus.STALE
262
+ self.judgments[jid].history.append({"event": "cascade_stale"})
263
+ self.audit_log.append(f"cascade stale: {jid}")
264
+
265
+ # ---- Rule 2: Achange (contract-aware propagation, I-4) ------------------
266
+
267
+ def notify_change(self, changed_entries: Iterable[str]) -> list[str]:
268
+ self.verify_contract_intact()
269
+ invalidated: list[str] = []
270
+ for entry in changed_entries:
271
+ path, ann = _split_change_entry(entry)
272
+ hit_rules = [r for r in self.contract.rules if r.matches_event(path, ann)]
273
+ for jid in sorted(self.judgments):
274
+ j = self.judgments[jid]
275
+ if j.status != JudgmentStatus.VALID:
276
+ continue # Contract reuse preserves validity only; never revives.
277
+ if not self._binds(j, path):
278
+ continue
279
+ keep = next((r for r in hit_rules if r.keeps_judgment(jid)), None)
280
+ if keep is not None:
281
+ self.audit_log.append(f"contract keep: {keep.rule_id} keeps {jid} ({path}@{ann})")
282
+ else:
283
+ j.status = JudgmentStatus.STALE
284
+ j.history.append({"event": "change_stale", "path": path, "class": ann})
285
+ self.audit_log.append(f"propagate stale: {jid} ({path}@{ann})")
286
+ invalidated.append(jid)
287
+ self._cascade_stale()
288
+ return invalidated
289
+
290
+ # ---- Rule 3: Arecheck (sole recovery gate, I-1a & I-1b) -----------------
291
+
292
+ def recheck(self, jid: str, *, passed: bool, digest: str = "", detail: str = "") -> JudgmentStatus | None:
293
+ j = self.judgments.get(jid)
294
+ if j is None:
295
+ return None
296
+ if j.status in (JudgmentStatus.WITHDRAWN, JudgmentStatus.SUPERSEDED):
297
+ # Retired judgments cannot be revived via recheck (5-state retirement invariant).
298
+ j.history.append({"event": "recheck_ignored_retired", "passed": bool(passed), "digest": digest})
299
+ self.audit_log.append(f"recheck ignored ({j.status.value}): {jid}")
300
+ return j.status
301
+
302
+ if digest:
303
+ j.roots.add(digest)
304
+
305
+ rec: dict = {"event": "recheck", "passed": bool(passed), "digest": digest}
306
+ if detail:
307
+ rec["detail"] = detail
308
+
309
+ if not passed:
310
+ j.status = JudgmentStatus.STALE
311
+ j.history.append(rec)
312
+ self.audit_log.append(f"recheck fail: {jid} -> stale")
313
+ self._cascade_stale()
314
+ return j.status
315
+
316
+ # I-1b closure coherence: cannot become valid while any dependency in closure is non-valid.
317
+ non_valid_deps = sorted(
318
+ d for d in self.dependency_closure(jid)
319
+ if d not in self.judgments or self.judgments[d].status != JudgmentStatus.VALID
320
+ )
321
+ if non_valid_deps:
322
+ j.status = JudgmentStatus.STALE
323
+ rec["deferred_deps"] = non_valid_deps
324
+ j.history.append(rec)
325
+ self.audit_log.append(f"recheck deferred: {jid} (non-valid deps: {', '.join(non_valid_deps)})")
326
+ return j.status
327
+
328
+ # If open objections exist, status stays BLOCKED even on passing recheck (I-2).
329
+ if j.open_objections():
330
+ j.status = JudgmentStatus.BLOCKED
331
+ j.history.append(rec)
332
+ self.audit_log.append(f"recheck pass but blocked by open objection: {jid}")
333
+ return j.status
334
+
335
+ j.status = JudgmentStatus.VALID
336
+ j.history.append(rec)
337
+ self.audit_log.append(f"recheck pass: {jid} -> valid")
338
+ return j.status
339
+
340
+ # ---- Rules 4 & 5: Araise / Aresolve (objections, I-2) -------------------
341
+
342
+ def raise_objection(self, jid: str, note: str, *, objection_id: str | None = None) -> Objection:
343
+ if jid not in self.judgments:
344
+ raise KeyError(f"Unknown judgment: {jid!r}")
345
+ if not note or not note.strip():
346
+ raise ValueError("Objection note must be non-empty")
347
+ j = self.judgments[jid]
348
+ oid = objection_id or f"obj-{len(j.objections) + 1}"
349
+ obj = Objection(objection_id=oid, note=note.strip())
350
+ j.objections.append(obj)
351
+ if j.status == JudgmentStatus.VALID:
352
+ j.status = JudgmentStatus.BLOCKED
353
+ j.history.append({"event": "objection_raised", "objection_id": oid, "note": obj.note})
354
+ self.audit_log.append(f"objection open: {jid} [{oid}]: {obj.note}")
355
+ self._cascade_stale()
356
+ return obj
357
+
358
+ def resolve_objection(self, jid: str, objection_id: str, *, audit_evidence: str) -> JudgmentStatus:
359
+ if jid not in self.judgments:
360
+ raise KeyError(f"Unknown judgment: {jid!r}")
361
+ if not audit_evidence or not audit_evidence.strip():
362
+ raise ValueError("Resolving an objection requires non-empty audit_evidence")
363
+ j = self.judgments[jid]
364
+ target = next((o for o in j.objections if o.objection_id == objection_id), None)
365
+ if target is None:
366
+ raise KeyError(f"Unknown objection {objection_id!r} on {jid!r}")
367
+ target.resolved = True
368
+ target.resolution_evidence = audit_evidence.strip()
369
+ j.history.append({
370
+ "event": "objection_resolved",
371
+ "objection_id": objection_id,
372
+ "evidence": target.resolution_evidence,
373
+ })
374
+ self.audit_log.append(f"objection resolved: {jid} [{objection_id}]")
375
+ # Resolution clears the block into STALE; an explicit passing recheck is required to return to VALID.
376
+ if j.status == JudgmentStatus.BLOCKED and not j.open_objections():
377
+ j.status = JudgmentStatus.STALE
378
+ return j.status
379
+
380
+ # ---- Rules 6 & 7: Awithdraw / Asupersede (5-state retirement) -----------
381
+
382
+ def withdraw(self, jid: str, *, reason: str = "") -> JudgmentStatus:
383
+ if jid not in self.judgments:
384
+ raise KeyError(f"Unknown judgment: {jid!r}")
385
+ j = self.judgments[jid]
386
+ j.status = JudgmentStatus.WITHDRAWN
387
+ j.history.append({"event": "withdraw", "reason": reason})
388
+ self.audit_log.append(f"withdraw: {jid} ({reason})")
389
+ self._cascade_stale()
390
+ return j.status
391
+
392
+ def supersede(self, old_jid: str, new_jid: str, *, reason: str = "") -> JudgmentStatus:
393
+ if old_jid not in self.judgments:
394
+ raise KeyError(f"Unknown judgment: {old_jid!r}")
395
+ if new_jid not in self.judgments:
396
+ raise KeyError(f"Replacement judgment not registered: {new_jid!r}")
397
+ if old_jid == new_jid:
398
+ raise ValueError("A judgment cannot supersede itself")
399
+ old = self.judgments[old_jid]
400
+ old.status = JudgmentStatus.SUPERSEDED
401
+ old.superseded_by = new_jid
402
+ old.history.append({"event": "supersede", "replaced_by": new_jid, "reason": reason})
403
+ self.audit_log.append(f"supersede: {old_jid} -> {new_jid} ({reason})")
404
+ self._cascade_stale()
405
+ return old.status
406
+
407
+ # ---- Rule 8: Acite (pure citation leaves roots & gate invariant, I-3) ---
408
+
409
+ def cite(self, jid: str) -> int:
410
+ if jid not in self.judgments:
411
+ raise KeyError(f"Unknown judgment: {jid!r}")
412
+ j = self.judgments[jid]
413
+ j.citations += 1
414
+ # Strictly does NOT add to j.roots or alter j.status (I-3).
415
+ return j.citations
416
+
417
+ # ---- Rule 9: Adeliver / fail-closed Action Gate (Commitment 4) ----------
418
+
419
+ def gate(self, cited: Sequence[str], *, require_non_empty: bool = True) -> GateDecision:
420
+ self.verify_contract_intact()
421
+ cited_tuple = tuple(dict.fromkeys(str(c) for c in cited))
422
+ reasons: list[str] = []
423
+
424
+ if require_non_empty and not cited_tuple:
425
+ reasons.append("empty-citations")
426
+ return GateDecision(allow=False, cited=(), closure=(), blocked_reasons=tuple(reasons))
427
+
428
+ closure: set[str] = set()
429
+ for jid in cited_tuple:
430
+ closure.add(jid)
431
+ closure |= self.dependency_closure(jid)
432
+
433
+ for jid in sorted(closure):
434
+ j = self.judgments.get(jid)
435
+ if j is None:
436
+ reasons.append(f"unknown-judgment:{jid}")
437
+ continue
438
+ if j.status != JudgmentStatus.VALID:
439
+ extra = f" (superseded_by={j.superseded_by})" if j.superseded_by else ""
440
+ reasons.append(f"claim-not-valid:{jid}:{j.status.value}{extra}")
441
+ if j.open_objections():
442
+ oids = ",".join(o.objection_id for o in j.open_objections())
443
+ reasons.append(f"objection-open:{jid}:{oids}")
444
+
445
+ allow = len(reasons) == 0
446
+ self.audit_log.append(
447
+ f"gate {'ALLOW' if allow else 'BLOCK'}: cited={list(cited_tuple)} reasons={reasons}"
448
+ )
449
+ return GateDecision(
450
+ allow=allow,
451
+ cited=cited_tuple,
452
+ closure=tuple(sorted(closure)),
453
+ blocked_reasons=tuple(reasons),
454
+ )
455
+
456
+ # ---- JSON Persistence ---------------------------------------------------
457
+
458
+ def to_dict(self) -> dict:
459
+ return {
460
+ "schema": "delval-gate-v1",
461
+ "contract": self.contract.to_dict(),
462
+ "judgments": {
463
+ jid: {
464
+ "jid": j.jid,
465
+ "status": j.status.value,
466
+ "evidence": list(j.evidence),
467
+ "deps": list(j.deps),
468
+ "roots": sorted(j.roots),
469
+ "superseded_by": j.superseded_by,
470
+ "objections": [asdict(o) for o in j.objections],
471
+ "history": j.history,
472
+ "citations": j.citations,
473
+ }
474
+ for jid, j in sorted(self.judgments.items())
475
+ },
476
+ "audit_log": list(self.audit_log),
477
+ }
478
+
479
+ @classmethod
480
+ def from_dict(cls, data: dict) -> "JudgmentLedger":
481
+ c_raw = data.get("contract") or {"contract_id": "default-strict", "rules": []}
482
+ contract = ReuseContract.from_dict(
483
+ c_raw,
484
+ sha256=c_raw.get("sha256", ""),
485
+ source_path=c_raw.get("source_path"),
486
+ )
487
+ ledger = cls(contract=contract)
488
+ for jid, jraw in (data.get("judgments") or {}).items():
489
+ ledger.judgments[jid] = Judgment(
490
+ jid=jraw["jid"],
491
+ status=JudgmentStatus(jraw["status"]),
492
+ evidence=tuple(jraw["evidence"]),
493
+ deps=tuple(jraw.get("deps", ())),
494
+ roots=set(jraw.get("roots", ())),
495
+ superseded_by=jraw.get("superseded_by"),
496
+ objections=[Objection(**o) for o in jraw.get("objections", ())],
497
+ history=list(jraw.get("history", ())),
498
+ citations=int(jraw.get("citations", 0)),
499
+ )
500
+ ledger.audit_log = list(data.get("audit_log", ()))
501
+ return ledger
502
+
503
+ def save(self, path: Path) -> None:
504
+ p = Path(path)
505
+ p.parent.mkdir(parents=True, exist_ok=True)
506
+ tmp = p.with_suffix(p.suffix + ".tmp")
507
+ tmp.write_text(json.dumps(self.to_dict(), indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
508
+ tmp.replace(p)
509
+
510
+ @classmethod
511
+ def load(cls, path: Path) -> "JudgmentLedger":
512
+ p = Path(path)
513
+ if not p.exists():
514
+ return cls()
515
+ return cls.from_dict(json.loads(p.read_text(encoding="utf-8")))
@@ -0,0 +1,266 @@
1
+ """Zero-dependency JSON-RPC 2.0 MCP stdio server for delval-gate.
2
+
3
+ Allows Claude Code, Cursor, or any MCP-compatible agent to enforce fail-closed
4
+ DelVal delivery permission directly over stdio.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from pathlib import Path
9
+ from typing import Any
10
+ import json
11
+ import sys
12
+
13
+ from .ledger import JudgmentLedger
14
+
15
+ TOOLS = [
16
+ {
17
+ "name": "delval_register",
18
+ "description": "Register an evidence-bound judgment in the DelVal ledger. Duplicate registrations are logged as echoes and never alter status.",
19
+ "inputSchema": {
20
+ "type": "object",
21
+ "properties": {
22
+ "jid": {"type": "string", "description": "Unique judgment identifier (e.g., build:api-schema)"},
23
+ "evidence": {"type": "array", "items": {"type": "string"}, "minItems": 1, "description": "Bound file paths or object identifiers"},
24
+ "passed": {"type": "boolean", "default": True},
25
+ "digest": {"type": "string", "default": ""},
26
+ "deps": {"type": "array", "items": {"type": "string"}, "default": []},
27
+ },
28
+ "required": ["jid", "evidence"],
29
+ },
30
+ },
31
+ {
32
+ "name": "delval_notify_change",
33
+ "description": "Notify the ledger of changed file/object paths (format: 'path' or 'path@change_class') and propagate staleness along dependency closures.",
34
+ "inputSchema": {
35
+ "type": "object",
36
+ "properties": {
37
+ "changed": {"type": "array", "items": {"type": "string"}, "minItems": 1},
38
+ },
39
+ "required": ["changed"],
40
+ },
41
+ },
42
+ {
43
+ "name": "delval_recheck",
44
+ "description": "Record a trusted verifier recheck result. This is the sole recovery path for stale judgments.",
45
+ "inputSchema": {
46
+ "type": "object",
47
+ "properties": {
48
+ "jid": {"type": "string"},
49
+ "passed": {"type": "boolean"},
50
+ "digest": {"type": "string", "default": ""},
51
+ "detail": {"type": "string", "default": ""},
52
+ },
53
+ "required": ["jid", "passed"],
54
+ },
55
+ },
56
+ {
57
+ "name": "delval_raise_objection",
58
+ "description": "Register an open objection against a judgment, blocking delivery until evidence-backed resolution.",
59
+ "inputSchema": {
60
+ "type": "object",
61
+ "properties": {
62
+ "jid": {"type": "string"},
63
+ "note": {"type": "string"},
64
+ "objection_id": {"type": "string"},
65
+ },
66
+ "required": ["jid", "note"],
67
+ },
68
+ },
69
+ {
70
+ "name": "delval_resolve_objection",
71
+ "description": "Resolve an open objection with audit evidence (transitions blocked -> stale; explicit recheck still required for valid).",
72
+ "inputSchema": {
73
+ "type": "object",
74
+ "properties": {
75
+ "jid": {"type": "string"},
76
+ "objection_id": {"type": "string"},
77
+ "audit_evidence": {"type": "string"},
78
+ },
79
+ "required": ["jid", "objection_id", "audit_evidence"],
80
+ },
81
+ },
82
+ {
83
+ "name": "delval_withdraw",
84
+ "description": "Permanently retire a judgment into Withdrawn status (always blocked by gate).",
85
+ "inputSchema": {
86
+ "type": "object",
87
+ "properties": {
88
+ "jid": {"type": "string"},
89
+ "reason": {"type": "string", "default": ""},
90
+ },
91
+ "required": ["jid"],
92
+ },
93
+ },
94
+ {
95
+ "name": "delval_supersede",
96
+ "description": "Permanently retire old_jid as Superseded by a registered replacement new_jid.",
97
+ "inputSchema": {
98
+ "type": "object",
99
+ "properties": {
100
+ "old_jid": {"type": "string"},
101
+ "new_jid": {"type": "string"},
102
+ "reason": {"type": "string", "default": ""},
103
+ },
104
+ "required": ["old_jid", "new_jid"],
105
+ },
106
+ },
107
+ {
108
+ "name": "delval_gate",
109
+ "description": "Fail-closed delivery permission gate: checks that every cited judgment and its entire transitive dependency closure are valid with zero open objections.",
110
+ "inputSchema": {
111
+ "type": "object",
112
+ "properties": {
113
+ "cited": {"type": "array", "items": {"type": "string"}},
114
+ },
115
+ "required": ["cited"],
116
+ },
117
+ },
118
+ {
119
+ "name": "delval_status",
120
+ "description": "Inspect the current statuses, distinct root counts, open objections, and recent audit trail of the ledger.",
121
+ "inputSchema": {
122
+ "type": "object",
123
+ "properties": {
124
+ "jids": {"type": "array", "items": {"type": "string"}},
125
+ },
126
+ },
127
+ },
128
+ ]
129
+
130
+
131
+ class DelValMCPServer:
132
+ def __init__(self, ledger_path: Path) -> None:
133
+ self.ledger_path = Path(ledger_path)
134
+
135
+ def _call_tool(self, name: str, args: dict[str, Any]) -> dict[str, Any]:
136
+ ledger = JudgmentLedger.load(self.ledger_path)
137
+ if name == "delval_register":
138
+ st = ledger.register(
139
+ args["jid"],
140
+ args["evidence"],
141
+ passed=bool(args.get("passed", True)),
142
+ digest=str(args.get("digest", "")),
143
+ deps=args.get("deps", ()),
144
+ )
145
+ ledger.save(self.ledger_path)
146
+ return {"jid": args["jid"], "status": st.value}
147
+ if name == "delval_notify_change":
148
+ inv = ledger.notify_change(args["changed"])
149
+ ledger.save(self.ledger_path)
150
+ return {"invalidated": inv}
151
+ if name == "delval_recheck":
152
+ st = ledger.recheck(
153
+ args["jid"],
154
+ passed=bool(args["passed"]),
155
+ digest=str(args.get("digest", "")),
156
+ detail=str(args.get("detail", "")),
157
+ )
158
+ ledger.save(self.ledger_path)
159
+ return {"jid": args["jid"], "status": st.value if st else "unknown"}
160
+ if name == "delval_raise_objection":
161
+ obj = ledger.raise_objection(
162
+ args["jid"],
163
+ args["note"],
164
+ objection_id=args.get("objection_id"),
165
+ )
166
+ ledger.save(self.ledger_path)
167
+ return {"jid": args["jid"], "objection_id": obj.objection_id, "status": ledger.judgments[args["jid"]].status.value}
168
+ if name == "delval_resolve_objection":
169
+ st = ledger.resolve_objection(
170
+ args["jid"],
171
+ args["objection_id"],
172
+ audit_evidence=args["audit_evidence"],
173
+ )
174
+ ledger.save(self.ledger_path)
175
+ return {"jid": args["jid"], "status": st.value}
176
+ if name == "delval_withdraw":
177
+ st = ledger.withdraw(args["jid"], reason=str(args.get("reason", "")))
178
+ ledger.save(self.ledger_path)
179
+ return {"jid": args["jid"], "status": st.value}
180
+ if name == "delval_supersede":
181
+ st = ledger.supersede(args["old_jid"], args["new_jid"], reason=str(args.get("reason", "")))
182
+ ledger.save(self.ledger_path)
183
+ return {"old_jid": args["old_jid"], "new_jid": args["new_jid"], "status": st.value}
184
+ if name == "delval_gate":
185
+ dec = ledger.gate(args["cited"])
186
+ ledger.save(self.ledger_path)
187
+ return dec.to_dict()
188
+ if name == "delval_status":
189
+ jids = args.get("jids") or sorted(ledger.judgments.keys())
190
+ return {
191
+ "contract_id": ledger.contract.contract_id,
192
+ "judgments": {
193
+ j: {
194
+ "status": ledger.judgments[j].status.value,
195
+ "roots_count": len(ledger.judgments[j].roots),
196
+ "open_objections": [o.objection_id for o in ledger.judgments[j].open_objections()],
197
+ }
198
+ if j in ledger.judgments
199
+ else {"status": "unknown"}
200
+ for j in jids
201
+ },
202
+ "recent_audit": ledger.audit_log[-10:],
203
+ }
204
+ raise ValueError(f"Unknown tool: {name}")
205
+
206
+ def handle_request(self, req: dict[str, Any]) -> dict[str, Any] | None:
207
+ method = req.get("method")
208
+ req_id = req.get("id")
209
+ params = req.get("params") or {}
210
+
211
+ if method == "notifications/initialized":
212
+ return None
213
+ if method == "initialize":
214
+ return {
215
+ "jsonrpc": "2.0",
216
+ "id": req_id,
217
+ "result": {
218
+ "protocolVersion": "2024-11-05",
219
+ "capabilities": {"tools": {}},
220
+ "serverInfo": {"name": "delval-gate", "version": "0.1.0"},
221
+ },
222
+ }
223
+ if method == "tools/list":
224
+ return {"jsonrpc": "2.0", "id": req_id, "result": {"tools": TOOLS}}
225
+ if method == "tools/call":
226
+ name = params.get("name", "")
227
+ args = params.get("arguments") or {}
228
+ try:
229
+ payload = self._call_tool(name, args)
230
+ return {
231
+ "jsonrpc": "2.0",
232
+ "id": req_id,
233
+ "result": {
234
+ "content": [{"type": "text", "text": json.dumps(payload, ensure_ascii=False)}],
235
+ "isError": False,
236
+ },
237
+ }
238
+ except Exception as exc:
239
+ return {
240
+ "jsonrpc": "2.0",
241
+ "id": req_id,
242
+ "result": {
243
+ "content": [{"type": "text", "text": json.dumps({"error": str(exc)}, ensure_ascii=False)}],
244
+ "isError": True,
245
+ },
246
+ }
247
+ return {
248
+ "jsonrpc": "2.0",
249
+ "id": req_id,
250
+ "error": {"code": -32601, "message": f"Method not found: {method}"},
251
+ }
252
+
253
+ def serve_stdio(self) -> None:
254
+ for line in sys.stdin:
255
+ line = line.strip()
256
+ if not line:
257
+ continue
258
+ try:
259
+ req = json.loads(line)
260
+ except json.JSONDecodeError as exc:
261
+ resp = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": str(exc)}}
262
+ else:
263
+ resp = self.handle_request(req)
264
+ if resp is not None:
265
+ sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
266
+ sys.stdout.flush()
@@ -0,0 +1,173 @@
1
+ Metadata-Version: 2.4
2
+ Name: delval-gate
3
+ Version: 0.1.0
4
+ Summary: Fail-closed Delivery Permission & Judgment Ledger action gate for long-running LLM agents (Python API, CLI, and zero-dependency MCP stdio server).
5
+ Author: Tao Shi (Zhurong)
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/iannil/delval-gate
8
+ Project-URL: Repository, https://github.com/iannil/delval-gate
9
+ Project-URL: Protocol Paper, https://zhurongshuo.com/en/papers/delval-protocol/
10
+ Project-URL: Experiment Paper, https://zhurongshuo.com/en/papers/delval-experiment/
11
+ Project-URL: Zenodo Formal Proofs & Dataset, https://doi.org/10.5281/zenodo.24455837
12
+ Keywords: llm,agents,mcp,verification,judgment-ledger,delivery-gate,delval
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Software Development :: Quality Assurance
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Dynamic: license-file
23
+
24
+ # delval-gate
25
+
26
+ [![CI](https://github.com/iannil/delval-gate/actions/workflows/ci.yml/badge.svg)](https://github.com/iannil/delval-gate/actions/workflows/ci.yml)
27
+ [![PyPI](https://img.shields.io/pypi/v/delval-gate.svg)](https://pypi.org/project/delval-gate/)
28
+ [![DOI](https://img.shields.io/badge/Zenodo%20DOI-10.5281%2Fzenodo.24455837-blue)](https://doi.org/10.5281/zenodo.24455837)
29
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
30
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
31
+ [![Zero Dependencies](https://img.shields.io/badge/dependencies-0%20(stdlib%20only)-brightgreen.svg)](pyproject.toml)
32
+
33
+ **Fail-Closed Delivery Permission & Judgment Ledger for Long-Running AI Agents**
34
+ *(Zero-dependency Python 3 library, CLI, and Model Context Protocol (MCP) stdio server)*
35
+
36
+ When AI coding and ops agents work across sessions—modifying configs, migrating schemas, publishing releases—stale judgments lingering in ordinary text or vector memory silently trigger unsafe deliveries. Even retraction-based memory layers degrade stale records at read time without blocking delivery when an agent cites them anyway.
37
+
38
+ `delval-gate` implements the **DelVal** five-state, ten-rule delivery-permission protocol—machine-checked in **Isabelle/HOL 2026** (session `RC_DelVal`, zero `sorry`) and evaluated across **728 live LLM agent trials** (`0/293` unsafe published deliveries vs. `68/150` in a version-bound retraction control without a delivery gate, McNemar $p = 6.776 \times 10^{-21}$).
39
+
40
+ ---
41
+
42
+ ## Core Guarantees (Formally Verified Invariants)
43
+
44
+ | Invariant | What `delval-gate` Enforces |
45
+ |---|---|
46
+ | **I-1a · Recovery Gate** | Once a judgment turns `stale`, **only** an explicit passing `recheck` restores it to `valid`. Duplicate `register` echoes are logged and ignored—never reviving stale claims. |
47
+ | **I-1b · Closure Coherence** | Object/file changes propagate `stale` along the full transitive dependency closure. A derived judgment cannot return to `valid` while any upstream dependency remains non-valid. |
48
+ | **I-2 · Objection Blocking** | Open objections transition a judgment to `blocked` and fail-close the delivery gate until closed with explicit `audit_evidence` followed by a fresh passing `recheck`. |
49
+ | **I-3 · Pure-Citation Invariance** | Repeated citations of the same evidence root never inflate independent root support (`roots` is a set of distinct non-empty digests) and never flip gate decisions. |
50
+ | **I-4 · Frozen Reuse Contract** | Preregistered harmless-change rules (SHA-256 hashed at initialization) preserve existing validity without false invalidation, and raise `ContractTamperedError` if modified mid-run. |
51
+ | **5-State Retirement Lifecycle** | Full five-state machine (`valid`, `stale`, `blocked`, `withdrawn`, `superseded`). Retired claims (`withdraw` / `supersede`) stay permanently blocked and cannot be revived by `recheck`. |
52
+
53
+ ---
54
+
55
+ ## Installation
56
+
57
+ Zero third-party dependencies (Python 3.10+ stdlib only):
58
+
59
+ ```bash
60
+ pip install delval-gate
61
+ ```
62
+
63
+ Or install from source:
64
+
65
+ ```bash
66
+ git clone https://github.com/iannil/delval-gate.git
67
+ cd delval-gate
68
+ pip install -e .
69
+ ```
70
+
71
+ Or run directly from source without installing:
72
+ ```bash
73
+ PYTHONPATH=src python3 -m delval_gate.cli --help
74
+ ```
75
+
76
+ ---
77
+
78
+ ## Quickstart (CLI & CI Gate)
79
+
80
+ ```bash
81
+ # 1. Initialize a ledger with a frozen JSON reuse contract
82
+ delval-gate --ledger .delval.json init --contract examples/reuse-contract.json
83
+
84
+ # 2. Register an upstream evidence-bound judgment
85
+ delval-gate --ledger .delval.json register \
86
+ --jid "build:api-schema" \
87
+ --evidence "src/schema.py" "pyproject.toml" \
88
+ --digest "sha256:abc123" --passed
89
+
90
+ # 3. Register a downstream derived judgment depending on build:api-schema
91
+ delval-gate --ledger .delval.json register \
92
+ --jid "release:v2-ready" \
93
+ --evidence "docs/api.md" \
94
+ --deps "build:api-schema" \
95
+ --digest "sha256:def456" --passed
96
+
97
+ # 4. Structural change -> automatic transitive invalidation
98
+ delval-gate --ledger .delval.json change "src/schema.py"
99
+
100
+ # 5. Delivery gate FAILS CLOSED (exit code 2 + exact blocking reasons)
101
+ delval-gate --ledger .delval.json gate "release:v2-ready"
102
+
103
+ # 6. Trusted recheck in dependency order -> gate ALLOWS (exit code 0)
104
+ delval-gate --ledger .delval.json recheck --jid "build:api-schema" --passed --digest "sha256:new1"
105
+ delval-gate --ledger .delval.json recheck --jid "release:v2-ready" --passed --digest "sha256:new2"
106
+ delval-gate --ledger .delval.json gate "release:v2-ready"
107
+ ```
108
+
109
+ Run the full interactive demo script:
110
+ ```bash
111
+ bash examples/demo.sh
112
+ ```
113
+
114
+ ---
115
+
116
+ ## MCP Server Mode (Claude Code / Cursor / Any MCP Agent)
117
+
118
+ `delval-gate` includes a zero-dependency JSON-RPC 2.0 **Model Context Protocol (MCP)** stdio server (`delval-gate --ledger .delval.json mcp`). Add it to your agent's MCP configuration:
119
+
120
+ ```json
121
+ {
122
+ "mcpServers": {
123
+ "delval-gate": {
124
+ "command": "delval-gate",
125
+ "args": ["--ledger", ".delval.json", "mcp"]
126
+ }
127
+ }
128
+ }
129
+ ```
130
+
131
+ ### Exposed MCP Tools
132
+ - `delval_register` — register an evidence-bound judgment (echo-immune)
133
+ - `delval_notify_change` — notify changed paths (`path` or `path@change_class`) and propagate staleness
134
+ - `delval_recheck` — record a trusted verifier recheck outcome (sole recovery gate)
135
+ - `delval_raise_objection` / `delval_resolve_objection` — open or evidence-backed close an objection
136
+ - `delval_withdraw` / `delval_supersede` — permanently retire or replace a judgment
137
+ - `delval_gate` — fail-closed delivery-permission check over cited judgments and their transitive closure
138
+ - `delval_status` — inspect statuses, distinct root counts, open objections, and audit trail
139
+
140
+ ---
141
+
142
+ ## Python API
143
+
144
+ ```python
145
+ from delval_gate import JudgmentLedger
146
+
147
+ ledger = JudgmentLedger()
148
+ ledger.register("build:api", ["src/api.py"], passed=True, digest="sha256:111")
149
+ ledger.register("release:v1", ["docs/api.md"], deps=["build:api"], passed=True, digest="sha256:222")
150
+
151
+ ledger.notify_change(["src/api.py"])
152
+ decision = ledger.gate(["release:v1"])
153
+ assert not decision.allow
154
+ print(decision.blocked_reasons)
155
+ # ('claim-not-valid:build:api:stale', 'claim-not-valid:release:v1:stale')
156
+ ```
157
+
158
+ ---
159
+
160
+ ## Running Tests
161
+
162
+ ```bash
163
+ python3 -m unittest discover -s tests -v
164
+ ```
165
+
166
+ ---
167
+
168
+ ## Academic Papers & Formal Verification Archive
169
+
170
+ - **Protocol Semantics & Isabelle/HOL–Alloy Formalization:** Tao Shi (Zhurong), *Delivery Permission: Protocol Semantics for Judgment Ledger, Action Gate, and Bounded Separation*, https://zhurongshuo.com/en/papers/delval-protocol/
171
+ - **Preregistered 150-Pair & 728-Trial Empirical Evaluation:** Tao Shi (Zhurong), *Does an Action Gate Reduce Unsafe Delivery? A 150-Pair Preregistered Experiment*, https://zhurongshuo.com/en/papers/delval-experiment/
172
+ - **Isabelle/HOL 2026 Proofs, Alloy Models & 728-Trial Dataset (Zenodo DOI):** [10.5281/zenodo.24455837](https://doi.org/10.5281/zenodo.24455837)
173
+ - **Author ORCID:** [0009-0002-6890-085X](https://orcid.org/0009-0002-6890-085X)
@@ -0,0 +1,10 @@
1
+ delval_gate/__init__.py,sha256=nHghCqfMkku7PhQB7m__c7tkCyiNjGGj-t7EL0NjaRs,422
2
+ delval_gate/cli.py,sha256=x7vw1-bgadaCaICbinKBxRUcSs2DjcML7YTHWbVHAME,6344
3
+ delval_gate/ledger.py,sha256=MD8sHq9MDR-mCZFjBBNf2xP3o-6CApjqSwZ6uDlTWXM,21216
4
+ delval_gate/mcp_server.py,sha256=kGTe-D0KMKdigBdDyzPVqVA_42cu6mFtJfm2mFyoNeU,10542
5
+ delval_gate-0.1.0.dist-info/licenses/LICENSE,sha256=VtHQKVDzhdYWMCQw6Ry-ka0Fx39vGuIHDQmUmVJpOLQ,1074
6
+ delval_gate-0.1.0.dist-info/METADATA,sha256=W0--WeBp9EoYk0BYYIfS3Q4Qd4Fb9PqlAWE8-1QwK1M,8108
7
+ delval_gate-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ delval_gate-0.1.0.dist-info/entry_points.txt,sha256=qIeiv0tM2RymaWVpgzLsQpNvTausHYvfVz6fXgnR9kE,53
9
+ delval_gate-0.1.0.dist-info/top_level.txt,sha256=dmXOD_wfyQGqEyFooELPv00Yi-7T0ElWgF8te-TLDOg,12
10
+ delval_gate-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ delval-gate = delval_gate.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tao Shi (Zhurong)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ delval_gate