deusproof 0.2.0__tar.gz → 0.4.0__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.
@@ -1,12 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: deusproof
3
- Version: 0.2.0
3
+ Version: 0.4.0
4
4
  Summary: Prove your AI agent's work existed at a given moment — one call, self-signed, timestamped and Bitcoin-anchored on a public append-only register. Free.
5
5
  Author: DEUSPROOF
6
6
  License: MIT
7
7
  Project-URL: Homepage, https://deusproof.com
8
8
  Project-URL: Pantheon, https://deusproof.com/pantheon
9
- Keywords: ai-agents,provenance,notary,did,bitcoin,c2pa,langchain
9
+ Keywords: ai-agents,provenance,audit-log,tamper-evident,did,bitcoin,rfc3161,langchain,langgraph,claude-code,cli
10
10
  Requires-Python: >=3.9
11
11
  Description-Content-Type: text/markdown
12
12
  Requires-Dist: httpx>=0.24
@@ -66,6 +66,79 @@ print(proof.badge_markdown) # paste into your README
66
66
 
67
67
  MIT · free public beta · [deusproof.com](https://deusproof.com)
68
68
 
69
+ ## A log your agent can edit is not evidence
70
+
71
+ `deusproof.audit` keeps a **tamper-evident audit log**: every record carries the hash of the one
72
+ before it, so an edited, deleted or reordered line breaks the chain. `seal()` timestamps the
73
+ current head with an RFC 3161 token and a Bitcoin anchor. Only that 64-character digest leaves
74
+ your machine; the log never does.
75
+
76
+ ```python
77
+ from deusproof import Notary
78
+ from deusproof.audit import AuditLog
79
+
80
+ log = AuditLog("agent-audit.jsonl", notary=Notary(handle="my-agent"))
81
+ log.append("tool_call", {"tool": "search", "input": "..."})
82
+ proof = log.seal() # one call, digest only
83
+ print(proof.verify_url)
84
+ ```
85
+
86
+ Check a log anywhere, offline:
87
+
88
+ ```bash
89
+ python -m deusproof.audit verify agent-audit.jsonl
90
+ ```
91
+
92
+ ### LangChain and LangGraph: one line
93
+
94
+ ```bash
95
+ pip install 'deusproof[langchain]'
96
+ ```
97
+
98
+ ```python
99
+ from deusproof.langchain_audit import audit_callback
100
+
101
+ cb = audit_callback(handle="my-agent", path="agent-audit.jsonl")
102
+ graph.invoke(inputs, config={"callbacks": [cb]}) # works for any Runnable
103
+ ```
104
+
105
+ It records runs, tool calls and model outputs (hashed; add `keep_payload=True` to keep the text in
106
+ the local file), and seals the head once when each top-level run ends. A failed seal never breaks
107
+ your agent's run. Guide: https://deusproof.com/guides/tamper-evident-agent-logs
108
+
109
+ ## Seal any log you already have: no code changes
110
+
111
+ Your tool already writes a log (an agent runtime, an audit trail, a JSONL of tool calls)? Seal it
112
+ from the command line. Only its SHA-256 leaves your machine.
113
+
114
+ ```bash
115
+ deusproof seal runtime.jsonl --handle my-endpoint # e.g. once a day from cron
116
+ deusproof verify runtime.jsonl # anyone, any time, offline
117
+ ```
118
+
119
+ Logs grow, so each receipt records how many bytes it covered and `verify` re-hashes exactly that
120
+ part: lines appended later still pass; anything changed or cut inside a sealed part fails. Receipts
121
+ are kept beside the file in `runtime.jsonl.deusproof.jsonl` (no content, just digest, size, time
122
+ and the link to check the timestamp and the Bitcoin anchor).
123
+
124
+ ### Claude Code: every session sealed
125
+
126
+ Add a `SessionEnd` hook to `.claude/settings.json` (or `~/.claude/settings.json` for all projects):
127
+
128
+ ```json
129
+ {
130
+ "hooks": {
131
+ "SessionEnd": [
132
+ { "hooks": [ { "type": "command",
133
+ "command": "deusproof seal --hook --handle my-dev-agent --platform claude-code" } ] }
134
+ ]
135
+ }
136
+ }
137
+ ```
138
+
139
+ When a session ends, its transcript is fingerprinted and sealed. The transcript never leaves your
140
+ machine. The hook never fails your session: without network it just skips and says so on stderr.
141
+
69
142
  ## Use it from LangChain
70
143
 
71
144
  ```bash
@@ -48,6 +48,79 @@ print(proof.badge_markdown) # paste into your README
48
48
 
49
49
  MIT · free public beta · [deusproof.com](https://deusproof.com)
50
50
 
51
+ ## A log your agent can edit is not evidence
52
+
53
+ `deusproof.audit` keeps a **tamper-evident audit log**: every record carries the hash of the one
54
+ before it, so an edited, deleted or reordered line breaks the chain. `seal()` timestamps the
55
+ current head with an RFC 3161 token and a Bitcoin anchor. Only that 64-character digest leaves
56
+ your machine; the log never does.
57
+
58
+ ```python
59
+ from deusproof import Notary
60
+ from deusproof.audit import AuditLog
61
+
62
+ log = AuditLog("agent-audit.jsonl", notary=Notary(handle="my-agent"))
63
+ log.append("tool_call", {"tool": "search", "input": "..."})
64
+ proof = log.seal() # one call, digest only
65
+ print(proof.verify_url)
66
+ ```
67
+
68
+ Check a log anywhere, offline:
69
+
70
+ ```bash
71
+ python -m deusproof.audit verify agent-audit.jsonl
72
+ ```
73
+
74
+ ### LangChain and LangGraph: one line
75
+
76
+ ```bash
77
+ pip install 'deusproof[langchain]'
78
+ ```
79
+
80
+ ```python
81
+ from deusproof.langchain_audit import audit_callback
82
+
83
+ cb = audit_callback(handle="my-agent", path="agent-audit.jsonl")
84
+ graph.invoke(inputs, config={"callbacks": [cb]}) # works for any Runnable
85
+ ```
86
+
87
+ It records runs, tool calls and model outputs (hashed; add `keep_payload=True` to keep the text in
88
+ the local file), and seals the head once when each top-level run ends. A failed seal never breaks
89
+ your agent's run. Guide: https://deusproof.com/guides/tamper-evident-agent-logs
90
+
91
+ ## Seal any log you already have: no code changes
92
+
93
+ Your tool already writes a log (an agent runtime, an audit trail, a JSONL of tool calls)? Seal it
94
+ from the command line. Only its SHA-256 leaves your machine.
95
+
96
+ ```bash
97
+ deusproof seal runtime.jsonl --handle my-endpoint # e.g. once a day from cron
98
+ deusproof verify runtime.jsonl # anyone, any time, offline
99
+ ```
100
+
101
+ Logs grow, so each receipt records how many bytes it covered and `verify` re-hashes exactly that
102
+ part: lines appended later still pass; anything changed or cut inside a sealed part fails. Receipts
103
+ are kept beside the file in `runtime.jsonl.deusproof.jsonl` (no content, just digest, size, time
104
+ and the link to check the timestamp and the Bitcoin anchor).
105
+
106
+ ### Claude Code: every session sealed
107
+
108
+ Add a `SessionEnd` hook to `.claude/settings.json` (or `~/.claude/settings.json` for all projects):
109
+
110
+ ```json
111
+ {
112
+ "hooks": {
113
+ "SessionEnd": [
114
+ { "hooks": [ { "type": "command",
115
+ "command": "deusproof seal --hook --handle my-dev-agent --platform claude-code" } ] }
116
+ ]
117
+ }
118
+ }
119
+ ```
120
+
121
+ When a session ends, its transcript is fingerprinted and sealed. The transcript never leaves your
122
+ machine. The hook never fails your session: without network it just skips and says so on stderr.
123
+
51
124
  ## Use it from LangChain
52
125
 
53
126
  ```bash
@@ -15,4 +15,4 @@
15
15
  from .notary import Notary, Proof
16
16
 
17
17
  __all__ = ["Notary", "Proof"]
18
- __version__ = "0.1.0"
18
+ __version__ = "0.4.0"
@@ -0,0 +1,185 @@
1
+ """A tamper-evident audit log for an AI agent, sealed by an outside witness.
2
+
3
+ from deusproof import Notary
4
+ from deusproof.audit import AuditLog
5
+
6
+ log = AuditLog("agent-audit.jsonl", notary=Notary(handle="my-agent"))
7
+ log.append("tool_call", {"tool": "search", "input": "..."})
8
+ log.append("tool_result", {"tool": "search", "output": "..."})
9
+ proof = log.seal() # ONE network call: only the head's SHA-256 leaves
10
+ print(proof.verify_url)
11
+
12
+ # later, anyone with the file:
13
+ report = AuditLog.verify("agent-audit.jsonl")
14
+ print(report.ok, report.records, report.seals)
15
+
16
+ WHY (13-nov-2026). An agent can edit its own log, so a plain log is not
17
+ evidence. Here every record carries the hash of the one before it: deleting or
18
+ changing a line breaks the chain from that point on. And `seal()` sends the
19
+ current head's fingerprint to DEUSPROOF, where it gets an RFC 3161 timestamp
20
+ and a Bitcoin anchor. From then on, nothing the head covers can be rewritten
21
+ without it showing, not even by whoever holds the file.
22
+
23
+ WHAT IT KEEPS AND WHAT IT SENDS. Records hold the SHA-256 of each payload; the
24
+ payload itself is stored only if `keep_payload=True`, and only in the local
25
+ file. The network sees one 64-char digest per seal, never the log. That is also
26
+ why this does not certify every output (the line the council drew on 22-jul):
27
+ the agent logs locally as much as it likes and seals a head now and then.
28
+
29
+ No dependency beyond the SDK's own. Python's standard library does the hashing.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import argparse
35
+ import hashlib
36
+ import json
37
+ import sys
38
+ import threading
39
+ import time
40
+ from dataclasses import dataclass, field
41
+ from datetime import datetime, timezone
42
+ from pathlib import Path
43
+ from typing import Any, Optional
44
+
45
+ GENESIS = "0" * 64
46
+
47
+ __all__ = ["AuditLog", "VerifyReport", "GENESIS"]
48
+
49
+
50
+ def _canonical(obj: Any) -> bytes:
51
+ return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str).encode("utf-8")
52
+
53
+
54
+ def _sha256(data: bytes) -> str:
55
+ return hashlib.sha256(data).hexdigest()
56
+
57
+
58
+ def _record_hash(record: dict) -> str:
59
+ return _sha256(_canonical({k: v for k, v in record.items() if k != "hash"}))
60
+
61
+
62
+ @dataclass
63
+ class VerifyReport:
64
+ ok: bool
65
+ records: int = 0
66
+ head: str = GENESIS
67
+ seals: list = field(default_factory=list)
68
+ error: str = ""
69
+ error_line: int = 0
70
+
71
+ def __str__(self) -> str:
72
+ if self.ok:
73
+ return f"OK · {self.records} records · head {self.head} · {len(self.seals)} seal(s)"
74
+ return f"BROKEN at line {self.error_line}: {self.error}"
75
+
76
+
77
+ class AuditLog:
78
+ """Append-only, hash-chained JSONL log with optional outside sealing."""
79
+
80
+ def __init__(self, path: str | Path, *, notary: Any = None, keep_payload: bool = False):
81
+ self.path = Path(path)
82
+ self.notary = notary
83
+ self.keep_payload = keep_payload
84
+ self._lock = threading.Lock()
85
+ self._seq = 0
86
+ self._head = GENESIS
87
+ if self.path.exists():
88
+ report = self.verify(self.path)
89
+ if not report.ok:
90
+ raise ValueError(f"refusing to append to a broken log: {report}")
91
+ self._seq, self._head = report.records, report.head
92
+
93
+ # ------------------------------------------------------------------ write
94
+ @property
95
+ def head(self) -> str:
96
+ return self._head
97
+
98
+ def append(self, kind: str, payload: Any = None, *, keep: Optional[bool] = None) -> dict:
99
+ """Add one record. `keep` overrides `keep_payload` for this record."""
100
+ keep = self.keep_payload if keep is None else keep
101
+ with self._lock:
102
+ record = {
103
+ "seq": self._seq + 1,
104
+ "ts": datetime.now(timezone.utc).isoformat(timespec="milliseconds"),
105
+ "kind": str(kind),
106
+ "payload_sha256": _sha256(_canonical(payload)),
107
+ "prev": self._head,
108
+ }
109
+ if keep and payload is not None:
110
+ record["payload"] = payload
111
+ record["hash"] = _record_hash(record)
112
+ self.path.parent.mkdir(parents=True, exist_ok=True)
113
+ with self.path.open("a", encoding="utf-8") as fh:
114
+ fh.write(json.dumps(record, ensure_ascii=False, default=str) + "\n")
115
+ self._seq, self._head = record["seq"], record["hash"]
116
+ return record
117
+
118
+ def seal(self, notary: Any = None):
119
+ """Timestamp the current head with DEUSPROOF (RFC 3161 + Bitcoin anchor).
120
+
121
+ Sends only the head's SHA-256. Appends a `seal` record with the receipt,
122
+ so the file itself says which head was sealed and where to check it."""
123
+ n = notary or self.notary
124
+ if n is None:
125
+ raise ValueError("seal() needs a Notary: AuditLog(path, notary=Notary(handle=...))")
126
+ sealed_head = self._head
127
+ proof = n.notarize_hash(output_hash=sealed_head)
128
+ # The receipt is always kept in the file: it holds no content, and without
129
+ # it nobody reading the log later would know where to check the seal.
130
+ self.append("seal", {"sealed_head": sealed_head, "certificate_id": proof.id,
131
+ "verify_url": proof.verify_url}, keep=True)
132
+ return proof
133
+
134
+ # ------------------------------------------------------------------ check
135
+ @staticmethod
136
+ def verify(path: str | Path) -> VerifyReport:
137
+ """Recompute the chain. Any edited, reordered or deleted line breaks it.
138
+
139
+ Does not call the network: to check a seal, fetch its receipts
140
+ (/api/anchors/{seed,tsr,ots}/<certificate_id>) and verify them with
141
+ `openssl ts -verify` and `ots verify`."""
142
+ p = Path(path)
143
+ head, seq, seals = GENESIS, 0, []
144
+ if not p.exists():
145
+ return VerifyReport(ok=True)
146
+ with p.open(encoding="utf-8") as fh:
147
+ for n, line in enumerate(fh, start=1):
148
+ if not line.strip():
149
+ continue
150
+ try:
151
+ rec = json.loads(line)
152
+ except ValueError:
153
+ return VerifyReport(ok=False, records=seq, head=head, seals=seals, error="not JSON", error_line=n)
154
+ if rec.get("seq") != seq + 1:
155
+ return VerifyReport(ok=False, records=seq, head=head, seals=seals, error="sequence gap", error_line=n)
156
+ if rec.get("prev") != head:
157
+ return VerifyReport(ok=False, records=seq, head=head, seals=seals, error="prev does not match the previous hash", error_line=n)
158
+ if "payload" in rec and _sha256(_canonical(rec["payload"])) != rec.get("payload_sha256"):
159
+ return VerifyReport(ok=False, records=seq, head=head, seals=seals, error="payload does not match its hash", error_line=n)
160
+ if _record_hash(rec) != rec.get("hash"):
161
+ return VerifyReport(ok=False, records=seq, head=head, seals=seals, error="record hash mismatch", error_line=n)
162
+ if rec.get("kind") == "seal" and isinstance(rec.get("payload"), dict):
163
+ seals.append(rec["payload"])
164
+ elif rec.get("kind") == "seal":
165
+ seals.append({"seq": rec["seq"]})
166
+ head, seq = rec["hash"], rec["seq"]
167
+ return VerifyReport(ok=True, records=seq, head=head, seals=seals)
168
+
169
+
170
+ def _main(argv: Optional[list] = None) -> int:
171
+ ap = argparse.ArgumentParser(prog="python -m deusproof.audit", description="Check a DEUSPROOF audit log.")
172
+ sub = ap.add_subparsers(dest="cmd", required=True)
173
+ v = sub.add_parser("verify", help="recompute the hash chain of a log file")
174
+ v.add_argument("path")
175
+ args = ap.parse_args(argv)
176
+ report = AuditLog.verify(args.path)
177
+ print(report)
178
+ for s in report.seals:
179
+ if "certificate_id" in s:
180
+ print(f" sealed {s.get('sealed_head', '')[:16]}… → {s.get('verify_url', '')}")
181
+ return 0 if report.ok else 1
182
+
183
+
184
+ if __name__ == "__main__": # pragma: no cover
185
+ sys.exit(_main())
@@ -0,0 +1,205 @@
1
+ """`deusproof` — seal any file or log from the command line, with no code changes.
2
+
3
+ deusproof seal runtime.jsonl --handle my-endpoint # once a day, from cron
4
+ deusproof verify runtime.jsonl # anyone, any time later
5
+ deusproof audit verify agent-audit.jsonl # the hash-chained log of deusproof.audit
6
+
7
+ WHY (16-nov-2026). Asking every tool to integrate a witness means waiting for
8
+ every maintainer. A command means any USER of any tool that already writes a
9
+ log (an agent runtime, a coding assistant, an audit trail) can get an outside
10
+ timestamp today, by themselves. Only the SHA-256 leaves the machine.
11
+
12
+ APPEND-ONLY LOGS. Logs grow. A seal records the byte length it covered, and
13
+ `verify` re-hashes exactly that prefix: "the first N bytes are as they were
14
+ when sealed; M bytes were added afterwards" is a pass, because appending is
15
+ what a log does. Changing or deleting anything inside the sealed prefix is a
16
+ fail. So the same receipt keeps meaning something while the log keeps growing.
17
+
18
+ RECEIPTS. Each seal appends one JSON line to `<file>.deusproof.jsonl` beside the
19
+ file (or `--receipts PATH`). It holds no content: digest, byte length, time,
20
+ certificate id and the URL where anyone can check the timestamp and the Bitcoin
21
+ anchor. Keep it with the file.
22
+
23
+ HOOK MODE. `deusproof seal --hook` reads a hook event as JSON on stdin and seals
24
+ its `transcript_path`. That makes it a one-line SessionEnd hook for Claude Code
25
+ (and any tool that passes a transcript path the same way). In hook mode it
26
+ never fails the caller: errors go to stderr and the exit code is 0.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import argparse
32
+ import hashlib
33
+ import json
34
+ import os
35
+ import sys
36
+ from datetime import datetime, timezone
37
+ from pathlib import Path
38
+ from typing import Any, Optional
39
+
40
+ __all__ = ["seal_file", "verify_file", "main"]
41
+
42
+ _CHUNK = 1 << 20
43
+
44
+
45
+ def _sha256_prefix(path: Path, length: Optional[int] = None) -> tuple[str, int]:
46
+ """SHA-256 of the first `length` bytes (the whole file if None). Returns (hex, bytes hashed)."""
47
+ h = hashlib.sha256()
48
+ done = 0
49
+ with path.open("rb") as fh:
50
+ while length is None or done < length:
51
+ want = _CHUNK if length is None else min(_CHUNK, length - done)
52
+ block = fh.read(want)
53
+ if not block:
54
+ break
55
+ h.update(block)
56
+ done += len(block)
57
+ return h.hexdigest(), done
58
+
59
+
60
+ def _receipts_path(path: Path, receipts: Optional[str]) -> Path:
61
+ return Path(receipts) if receipts else path.with_name(path.name + ".deusproof.jsonl")
62
+
63
+
64
+ def _read_receipts(rp: Path) -> list[dict]:
65
+ if not rp.exists():
66
+ return []
67
+ out = []
68
+ for line in rp.read_text(encoding="utf-8").splitlines():
69
+ line = line.strip()
70
+ if line:
71
+ try:
72
+ out.append(json.loads(line))
73
+ except ValueError:
74
+ continue
75
+ return out
76
+
77
+
78
+ def seal_file(path: str | Path, *, notary: Any, receipts: Optional[str] = None) -> dict:
79
+ """Hash `path` locally, timestamp the digest with `notary`, append a receipt. Returns the receipt."""
80
+ p = Path(path)
81
+ if not p.is_file():
82
+ raise FileNotFoundError(f"not a file: {p}")
83
+ digest, size = _sha256_prefix(p)
84
+ proof = notary.notarize_hash(output_hash=digest)
85
+ receipt = {
86
+ "file": p.name,
87
+ "sha256": digest,
88
+ "bytes": size,
89
+ "sealed_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
90
+ "certificate_id": proof.id,
91
+ "verify_url": proof.verify_url,
92
+ }
93
+ rp = _receipts_path(p, receipts)
94
+ rp.parent.mkdir(parents=True, exist_ok=True)
95
+ with rp.open("a", encoding="utf-8") as fh:
96
+ fh.write(json.dumps(receipt, ensure_ascii=False) + "\n")
97
+ return receipt
98
+
99
+
100
+ def verify_file(path: str | Path, *, receipts: Optional[str] = None) -> list[dict]:
101
+ """Check `path` against every receipt. Offline: re-hashes the sealed prefix of each.
102
+
103
+ Each result: the receipt plus `ok` (sealed bytes unchanged) and `added` (bytes
104
+ appended since). The timestamp itself is checked at `verify_url`, or offline
105
+ from the receipts at /api/anchors/{seed,tsr,ots}/<certificate_id>."""
106
+ p = Path(path)
107
+ rp = _receipts_path(p, receipts)
108
+ rows = _read_receipts(rp)
109
+ if not rows:
110
+ raise FileNotFoundError(f"no receipts at {rp}")
111
+ size_now = p.stat().st_size if p.is_file() else -1
112
+ results = []
113
+ for r in rows:
114
+ want = int(r.get("bytes", -1))
115
+ if size_now < 0 or want < 0 or size_now < want:
116
+ results.append({**r, "ok": False, "added": 0, "why": "file is shorter than what was sealed"})
117
+ continue
118
+ got, _ = _sha256_prefix(p, want)
119
+ ok = got == r.get("sha256")
120
+ results.append({**r, "ok": ok, "added": size_now - want if ok else 0,
121
+ "why": "" if ok else "the sealed bytes were changed"})
122
+ return results
123
+
124
+
125
+ # ---------------------------------------------------------------------- CLI
126
+ def _notary(args: argparse.Namespace):
127
+ from .notary import Notary # imported here so `verify` works without network deps configured
128
+
129
+ handle = args.handle or os.environ.get("DEUSPROOF_HANDLE", "")
130
+ if not handle:
131
+ raise SystemExit("seal needs a public name: --handle NAME or DEUSPROOF_HANDLE=NAME")
132
+ kw = {"handle": handle, "platform": args.platform}
133
+ if args.base_url:
134
+ kw["base_url"] = args.base_url
135
+ return Notary(**kw)
136
+
137
+
138
+ def _cmd_seal(args: argparse.Namespace) -> int:
139
+ target = args.path
140
+ if args.hook:
141
+ try:
142
+ event = json.loads(sys.stdin.read() or "{}")
143
+ target = event.get("transcript_path") or target
144
+ if not target:
145
+ print("deusproof: hook event has no transcript_path; nothing sealed", file=sys.stderr)
146
+ return 0
147
+ r = seal_file(os.path.expanduser(target), notary=_notary(args), receipts=args.receipts)
148
+ print(f"deusproof: sealed {r['bytes']} bytes | {r['verify_url']}", file=sys.stderr)
149
+ except BaseException as e: # a witness must never break the session it witnesses
150
+ print(f"deusproof: not sealed ({e})", file=sys.stderr)
151
+ return 0
152
+ if not target:
153
+ raise SystemExit("seal needs a file path (or --hook)")
154
+ r = seal_file(target, notary=_notary(args), receipts=args.receipts)
155
+ print(f"sealed {r['file']} | {r['bytes']} bytes | sha256 {r['sha256']}")
156
+ print(f" {r['verify_url']}")
157
+ print(f" receipt kept in {_receipts_path(Path(target), args.receipts)}")
158
+ return 0
159
+
160
+
161
+ def _cmd_verify(args: argparse.Namespace) -> int:
162
+ try:
163
+ results = verify_file(args.path, receipts=args.receipts)
164
+ except FileNotFoundError as e:
165
+ print(f"BROKEN: {e}")
166
+ return 1
167
+ bad = 0
168
+ for r in results:
169
+ if r["ok"]:
170
+ extra = f" · {r['added']} bytes added since" if r["added"] else ""
171
+ print(f"OK {r['sealed_at']} | first {r['bytes']} bytes unchanged{extra} | {r['verify_url']}")
172
+ else:
173
+ bad += 1
174
+ print(f"BROKEN {r['sealed_at']} | {r['why']} | sealed sha256 {r['sha256']}")
175
+ return 1 if bad else 0
176
+
177
+
178
+ def main(argv: Optional[list] = None) -> int:
179
+ ap = argparse.ArgumentParser(prog="deusproof", description="Timestamp files and logs with an outside witness. Only a SHA-256 leaves your machine.")
180
+ sub = ap.add_subparsers(dest="cmd", required=True)
181
+
182
+ s = sub.add_parser("seal", help="timestamp a file or log (only its SHA-256 is sent)")
183
+ s.add_argument("path", nargs="?", help="file to seal")
184
+ s.add_argument("--handle", help="public name for the seal (or DEUSPROOF_HANDLE)")
185
+ s.add_argument("--platform", default="cli", help="label for where the seal comes from (default: cli)")
186
+ s.add_argument("--receipts", help="where to keep receipts (default: <file>.deusproof.jsonl)")
187
+ s.add_argument("--base-url", help=argparse.SUPPRESS)
188
+ s.add_argument("--hook", action="store_true", help="read a hook event (JSON on stdin) and seal its transcript_path; never fails")
189
+ s.set_defaults(func=_cmd_seal)
190
+
191
+ v = sub.add_parser("verify", help="check a file against its receipts (offline)")
192
+ v.add_argument("path")
193
+ v.add_argument("--receipts")
194
+ v.set_defaults(func=_cmd_verify)
195
+
196
+ a = sub.add_parser("audit", help="hash-chained audit logs (deusproof.audit)")
197
+ a.add_argument("rest", nargs=argparse.REMAINDER)
198
+ a.set_defaults(func=lambda ns: __import__("deusproof.audit", fromlist=["_main"])._main(ns.rest))
199
+
200
+ args = ap.parse_args(argv)
201
+ return args.func(args)
202
+
203
+
204
+ if __name__ == "__main__": # pragma: no cover
205
+ sys.exit(main())
@@ -0,0 +1,146 @@
1
+ """Tamper-evident audit log for LangChain and LangGraph agents (13-nov-2026).
2
+
3
+ from deusproof.langchain_audit import audit_callback
4
+ cb = audit_callback(handle="my-agent", path="agent-audit.jsonl")
5
+ graph.invoke(inputs, config={"callbacks": [cb]})
6
+
7
+ POR QUÉ ES UN MÓDULO APARTE. `deusproof.langchain` es LA SONDA del 16-sep: una
8
+ herramienta que el modelo decide llamar sobre su entregable final, y su prueba
9
+ prohíbe cualquier enganche automático, porque la regla del consejo es «nunca
10
+ auto-certificar cada salida». Esto NO certifica cada salida: anota en LOCAL,
11
+ encadenado por hashes, y sella solo la huella de la cabeza al terminar cada
12
+ ejecución de nivel superior (como mucho una vez cada `min_seal_interval`
13
+ segundos). Es otro producto —el registro a prueba de cambios, problema 5 del
14
+ pilar— y vive aparte para que la sonda siga midiendo lo que medía.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import time
20
+ from typing import Any
21
+
22
+ from .langchain import DEUSPROOF_PLATFORM, _sin_langchain
23
+ from .notary import Notary
24
+
25
+ __all__ = ["audit_callback"]
26
+
27
+
28
+ # ---------------------------------------------------------------------------
29
+ # EL REGISTRO A PRUEBA DE CAMBIOS (13-nov-2026, punto G del plan de expansión).
30
+ #
31
+ # La sonda de arriba (una herramienta para sellar el entregable final) llevaba
32
+ # dos meses en cero: nadie la conocía y pedía al modelo que se acordara de
33
+ # usarla. Esto es distinto y no la contradice: NO certifica cada salida. Anota
34
+ # en LOCAL, encadenado por hashes, lo que hace el agente (herramientas, modelo,
35
+ # inicio y fin de cada ejecución) y al terminar una ejecución sella SOLO la
36
+ # huella de la cabeza: una llamada por ejecución, con un mínimo de segundos
37
+ # entre sellos. El problema que resuelve es el 5 del pilar: «un registro que el
38
+ # agente puede editar no es prueba».
39
+ #
40
+ # from deusproof.langchain_audit import audit_callback
41
+ # cb = audit_callback(handle="my-agent", path="agent-audit.jsonl")
42
+ # graph.invoke(inputs, config={"callbacks": [cb]}) # LangGraph o LangChain
43
+ # print(cb.last_proof.verify_url if cb.last_proof else "no seal yet")
44
+ # ---------------------------------------------------------------------------
45
+
46
+
47
+ def audit_callback(
48
+ handle: str,
49
+ path: str = "deusproof-audit.jsonl",
50
+ model: str = "",
51
+ *,
52
+ seal: str = "run",
53
+ keep_payload: bool = False,
54
+ min_seal_interval: float = 60.0,
55
+ notary: Any = None,
56
+ base_url: str | None = None,
57
+ api_key: str | None = None,
58
+ key_path: str | None = None,
59
+ ):
60
+ """A LangChain/LangGraph callback that keeps a tamper-evident log of the agent.
61
+
62
+ `seal="run"` timestamps the log's head when each top-level run ends (at most
63
+ once every `min_seal_interval` seconds); `seal="manual"` never seals on its
64
+ own, call `handler.seal()` when you want. Only the head's SHA-256 is sent.
65
+ Payloads (tool inputs and outputs, model text) are hashed; they are written
66
+ to the local file only with `keep_payload=True`.
67
+ """
68
+ try:
69
+ from langchain_core.callbacks import BaseCallbackHandler
70
+ except Exception as exc: # pragma: no cover - depende del entorno del dev
71
+ raise _sin_langchain(exc) from exc
72
+
73
+ from .audit import AuditLog
74
+
75
+ if seal not in ("run", "manual"):
76
+ raise ValueError('seal must be "run" or "manual"')
77
+ if notary is None:
78
+ notary = Notary(
79
+ handle=handle,
80
+ model=model,
81
+ platform=DEUSPROOF_PLATFORM,
82
+ **{k: v for k, v in (
83
+ ("base_url", base_url), ("api_key", api_key), ("key_path", key_path),
84
+ ) if v is not None},
85
+ )
86
+ log = AuditLog(path, notary=notary, keep_payload=keep_payload)
87
+
88
+ class DeusproofAuditHandler(BaseCallbackHandler):
89
+ raise_error = False # a failed seal must never break the agent's run
90
+
91
+ def __init__(self) -> None:
92
+ super().__init__()
93
+ self.log = log
94
+ self.last_proof = None
95
+ self.last_error = ""
96
+ self._last_seal = 0.0
97
+
98
+ # -- runs --------------------------------------------------------
99
+ def on_chain_start(self, serialized, inputs, *, run_id, parent_run_id=None, **kw):
100
+ if parent_run_id is None:
101
+ self.log.append("run_start", {"run_id": str(run_id), "name": (serialized or {}).get("name", "")})
102
+
103
+ def on_chain_end(self, outputs, *, run_id, parent_run_id=None, **kw):
104
+ if parent_run_id is None:
105
+ self.log.append("run_end", {"run_id": str(run_id), "outputs": outputs})
106
+ self._maybe_seal()
107
+
108
+ def on_chain_error(self, error, *, run_id, parent_run_id=None, **kw):
109
+ if parent_run_id is None:
110
+ self.log.append("run_error", {"run_id": str(run_id), "error": repr(error)})
111
+ self._maybe_seal()
112
+
113
+ # -- tools -------------------------------------------------------
114
+ def on_tool_start(self, serialized, input_str, *, run_id, **kw):
115
+ self.log.append("tool_start", {"run_id": str(run_id), "tool": (serialized or {}).get("name", ""), "input": input_str})
116
+
117
+ def on_tool_end(self, output, *, run_id, **kw):
118
+ self.log.append("tool_end", {"run_id": str(run_id), "output": str(output)})
119
+
120
+ def on_tool_error(self, error, *, run_id, **kw):
121
+ self.log.append("tool_error", {"run_id": str(run_id), "error": repr(error)})
122
+
123
+ # -- model -------------------------------------------------------
124
+ def on_llm_end(self, response, *, run_id, **kw):
125
+ try:
126
+ text = [[g.text for g in gens] for gens in response.generations]
127
+ except Exception:
128
+ text = str(response)
129
+ self.log.append("llm_end", {"run_id": str(run_id), "text": text})
130
+
131
+ # -- sealing -----------------------------------------------------
132
+ def _maybe_seal(self) -> None:
133
+ if seal != "run" or time.monotonic() - self._last_seal < min_seal_interval:
134
+ return
135
+ self.seal()
136
+
137
+ def seal(self):
138
+ try:
139
+ self.last_proof = self.log.seal()
140
+ self._last_seal = time.monotonic()
141
+ self.last_error = ""
142
+ except Exception as exc: # network down, quota… the log stays intact
143
+ self.last_error = repr(exc)
144
+ return self.last_proof
145
+
146
+ return DeusproofAuditHandler()
@@ -1,12 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: deusproof
3
- Version: 0.2.0
3
+ Version: 0.4.0
4
4
  Summary: Prove your AI agent's work existed at a given moment — one call, self-signed, timestamped and Bitcoin-anchored on a public append-only register. Free.
5
5
  Author: DEUSPROOF
6
6
  License: MIT
7
7
  Project-URL: Homepage, https://deusproof.com
8
8
  Project-URL: Pantheon, https://deusproof.com/pantheon
9
- Keywords: ai-agents,provenance,notary,did,bitcoin,c2pa,langchain
9
+ Keywords: ai-agents,provenance,audit-log,tamper-evident,did,bitcoin,rfc3161,langchain,langgraph,claude-code,cli
10
10
  Requires-Python: >=3.9
11
11
  Description-Content-Type: text/markdown
12
12
  Requires-Dist: httpx>=0.24
@@ -66,6 +66,79 @@ print(proof.badge_markdown) # paste into your README
66
66
 
67
67
  MIT · free public beta · [deusproof.com](https://deusproof.com)
68
68
 
69
+ ## A log your agent can edit is not evidence
70
+
71
+ `deusproof.audit` keeps a **tamper-evident audit log**: every record carries the hash of the one
72
+ before it, so an edited, deleted or reordered line breaks the chain. `seal()` timestamps the
73
+ current head with an RFC 3161 token and a Bitcoin anchor. Only that 64-character digest leaves
74
+ your machine; the log never does.
75
+
76
+ ```python
77
+ from deusproof import Notary
78
+ from deusproof.audit import AuditLog
79
+
80
+ log = AuditLog("agent-audit.jsonl", notary=Notary(handle="my-agent"))
81
+ log.append("tool_call", {"tool": "search", "input": "..."})
82
+ proof = log.seal() # one call, digest only
83
+ print(proof.verify_url)
84
+ ```
85
+
86
+ Check a log anywhere, offline:
87
+
88
+ ```bash
89
+ python -m deusproof.audit verify agent-audit.jsonl
90
+ ```
91
+
92
+ ### LangChain and LangGraph: one line
93
+
94
+ ```bash
95
+ pip install 'deusproof[langchain]'
96
+ ```
97
+
98
+ ```python
99
+ from deusproof.langchain_audit import audit_callback
100
+
101
+ cb = audit_callback(handle="my-agent", path="agent-audit.jsonl")
102
+ graph.invoke(inputs, config={"callbacks": [cb]}) # works for any Runnable
103
+ ```
104
+
105
+ It records runs, tool calls and model outputs (hashed; add `keep_payload=True` to keep the text in
106
+ the local file), and seals the head once when each top-level run ends. A failed seal never breaks
107
+ your agent's run. Guide: https://deusproof.com/guides/tamper-evident-agent-logs
108
+
109
+ ## Seal any log you already have: no code changes
110
+
111
+ Your tool already writes a log (an agent runtime, an audit trail, a JSONL of tool calls)? Seal it
112
+ from the command line. Only its SHA-256 leaves your machine.
113
+
114
+ ```bash
115
+ deusproof seal runtime.jsonl --handle my-endpoint # e.g. once a day from cron
116
+ deusproof verify runtime.jsonl # anyone, any time, offline
117
+ ```
118
+
119
+ Logs grow, so each receipt records how many bytes it covered and `verify` re-hashes exactly that
120
+ part: lines appended later still pass; anything changed or cut inside a sealed part fails. Receipts
121
+ are kept beside the file in `runtime.jsonl.deusproof.jsonl` (no content, just digest, size, time
122
+ and the link to check the timestamp and the Bitcoin anchor).
123
+
124
+ ### Claude Code: every session sealed
125
+
126
+ Add a `SessionEnd` hook to `.claude/settings.json` (or `~/.claude/settings.json` for all projects):
127
+
128
+ ```json
129
+ {
130
+ "hooks": {
131
+ "SessionEnd": [
132
+ { "hooks": [ { "type": "command",
133
+ "command": "deusproof seal --hook --handle my-dev-agent --platform claude-code" } ] }
134
+ ]
135
+ }
136
+ }
137
+ ```
138
+
139
+ When a session ends, its transcript is fingerprinted and sealed. The transcript never leaves your
140
+ machine. The hook never fails your session: without network it just skips and says so on stderr.
141
+
69
142
  ## Use it from LangChain
70
143
 
71
144
  ```bash
@@ -1,10 +1,14 @@
1
1
  README.md
2
2
  pyproject.toml
3
3
  deusproof/__init__.py
4
+ deusproof/audit.py
5
+ deusproof/cli.py
4
6
  deusproof/langchain.py
7
+ deusproof/langchain_audit.py
5
8
  deusproof/notary.py
6
9
  deusproof.egg-info/PKG-INFO
7
10
  deusproof.egg-info/SOURCES.txt
8
11
  deusproof.egg-info/dependency_links.txt
12
+ deusproof.egg-info/entry_points.txt
9
13
  deusproof.egg-info/requires.txt
10
14
  deusproof.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ deusproof = deusproof.cli:main
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "deusproof"
7
- version = "0.2.0"
7
+ version = "0.4.0"
8
8
  description = "Prove your AI agent's work existed at a given moment — one call, self-signed, timestamped and Bitcoin-anchored on a public append-only register. Free."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -15,7 +15,7 @@ dependencies = [
15
15
  "cryptography>=41",
16
16
  "base58>=2.1",
17
17
  ]
18
- keywords = ["ai-agents", "provenance", "notary", "did", "bitcoin", "c2pa", "langchain"]
18
+ keywords = ["ai-agents", "provenance", "audit-log", "tamper-evident", "did", "bitcoin", "rfc3161", "langchain", "langgraph", "claude-code", "cli"]
19
19
 
20
20
  # LA SONDA, COMO EXTRA OPCIONAL (16-sep-2026). Quien instale `deusproof` a secas
21
21
  # no se descarga el arbol de LangChain; solo lo pide quien lo va a usar.
@@ -23,6 +23,11 @@ keywords = ["ai-agents", "provenance", "notary", "did", "bitcoin", "c2pa", "lang
23
23
  [project.optional-dependencies]
24
24
  langchain = ["langchain-core>=0.3", "pydantic>=2"]
25
25
 
26
+ # EL COMANDO (16-nov-2026): `deusproof seal <fichero>` sella cualquier registro sin tocar
27
+ # el codigo de la herramienta que lo escribe; `--hook` lo convierte en gancho de Claude Code.
28
+ [project.scripts]
29
+ deusproof = "deusproof.cli:main"
30
+
26
31
  [project.urls]
27
32
  Homepage = "https://deusproof.com"
28
33
  Pantheon = "https://deusproof.com/pantheon"
File without changes
File without changes