sm-feed 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.
sm_feed/__init__.py ADDED
@@ -0,0 +1,71 @@
1
+ """sm-feed — the Verifiable Agent Feed.
2
+
3
+ A signed, hash-chained, cursor-based append-only feed primitive for the internet
4
+ of agents. It gives a subscriber what RSS/Atom/ActivityPub cannot: proof it
5
+ received the *complete, untampered* sequence of entries, not just "some recent
6
+ items". The payload is opaque (any JSON object with a ``type``), so one wire
7
+ format carries published claims, binding-lifecycle events, or community deltas.
8
+
9
+ Pull (`GET /feed?since=<cursor>`) and push (`POST` a page to a callback) deliver
10
+ the same signed :func:`FeedLog.page`; :func:`verify_page` checks either.
11
+
12
+ Crypto is reused from sm-arp (Ed25519, JCS, did:key); sm-feed adds only the feed
13
+ shape and its verification.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from sm_arp import Identity
19
+
20
+ from .checkpoint import (
21
+ CHECKPOINT_TYPE,
22
+ CheckpointAnchor,
23
+ adopt_checkpoint,
24
+ emit_checkpoint,
25
+ is_checkpoint,
26
+ )
27
+ from .entry import (
28
+ ENTRY_VERSION,
29
+ build_entry,
30
+ compute_entry_hash,
31
+ verify_entry,
32
+ )
33
+ from .equivocation import (
34
+ EQUIVOCATION_VERSION,
35
+ detect_equivocation,
36
+ verify_equivocation_proof,
37
+ )
38
+ from .feed import (
39
+ HEAD_VERSION,
40
+ PAGE_VERSION,
41
+ FeedLog,
42
+ build_signed_head,
43
+ verify_page,
44
+ verify_signed_head,
45
+ )
46
+
47
+ __version__ = "0.1.0"
48
+
49
+ __all__ = [
50
+ "Identity",
51
+ "ENTRY_VERSION",
52
+ "HEAD_VERSION",
53
+ "PAGE_VERSION",
54
+ "FeedLog",
55
+ "build_entry",
56
+ "compute_entry_hash",
57
+ "verify_entry",
58
+ "build_signed_head",
59
+ "verify_signed_head",
60
+ "verify_page",
61
+ # compaction — state checkpoints
62
+ "CHECKPOINT_TYPE",
63
+ "CheckpointAnchor",
64
+ "emit_checkpoint",
65
+ "adopt_checkpoint",
66
+ "is_checkpoint",
67
+ # fork detection — equivocation via gossip
68
+ "EQUIVOCATION_VERSION",
69
+ "detect_equivocation",
70
+ "verify_equivocation_proof",
71
+ ]
sm_feed/checkpoint.py ADDED
@@ -0,0 +1,115 @@
1
+ """State checkpoints (compaction) for the Verifiable Agent Feed.
2
+
3
+ A checkpoint is an ordinary feed entry — signed and hash-chained exactly like any
4
+ other entry; it introduces no Merkle tree or parallel structure, so the chain
5
+ stays strictly linear — whose *payload* commits to the feed's aggregated state up
6
+ to that point. It lets a LATE-JOINING subscriber start from a signed anchor
7
+ instead of replaying the whole chain from genesis, and lets a publisher prune
8
+ history a new subscriber no longer needs to fetch.
9
+
10
+ CRYPTOGRAPHIC ASSUMPTIONS — read before trusting a checkpoint:
11
+
12
+ * Authenticity is ONLY the issuer's Ed25519 signature over the entry (via
13
+ ``build_entry``). Adopting a checkpoint as genesis therefore *trusts the
14
+ issuer* for all history at or before it: the joiner cannot itself prove
15
+ completeness of anything before the checkpoint (SPEC §5 — completeness is
16
+ relative to the anchor you hold; THREATMODEL — "mid-stream completeness").
17
+ Catching an issuer that hands *different* checkpoints to different joiners is
18
+ the job of gossip / equivocation (``equivocation.py``), not this file.
19
+
20
+ * ``chain_tip`` is the ``entry_hash`` of the checkpoint's immediate predecessor.
21
+ In a LINEAR hash chain that single value is already a cryptographic commitment
22
+ to the entire prior history — every ``entry_hash`` folds in its ``prev_hash``
23
+ by induction — so no Merkle root is needed to commit "everything so far".
24
+
25
+ * ``state_digest`` is an OPAQUE, consumer-computed hash of the *materialized*
26
+ aggregate state (whatever the payloads fold into — a merged view, a balance, a
27
+ set). sm-feed neither computes nor interprets it; it only carries and signs it.
28
+ Whether a full replay reproduces that digest is the consuming profile's check,
29
+ not sm-feed's.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ from typing import Any, NamedTuple
35
+
36
+ from .entry import verify_entry
37
+ from .feed import FeedLog
38
+
39
+ # Payload discriminator. A checkpoint is a normal entry whose payload.type is this.
40
+ CHECKPOINT_TYPE = "feed/state-checkpoint"
41
+
42
+
43
+ def emit_checkpoint(log: FeedLog, *, state_digest: str, issued_at: str) -> dict[str, Any]:
44
+ """Publisher: append a checkpoint entry summarizing the feed state so far.
45
+
46
+ The checkpoint is appended at the next ``seq`` like any entry; its ``prev_hash``
47
+ is the current head's ``entry_hash`` (so the chain stays unbroken and strictly
48
+ linear). Its payload records ``chain_tip`` (that same head hash — the linear
49
+ commitment to history ``0..covers_through_seq``) and the caller's opaque
50
+ ``state_digest``. Raises on an empty feed: there is nothing to summarize.
51
+ """
52
+ head = log.head_ref()
53
+ if head is None:
54
+ raise ValueError("cannot checkpoint an empty feed")
55
+ payload = {
56
+ "type": CHECKPOINT_TYPE,
57
+ # last seq included in what this checkpoint commits to (the predecessor):
58
+ "covers_through_seq": head["seq"],
59
+ # linear commitment to history 0..covers_through_seq (== this entry's prev_hash):
60
+ "chain_tip": head["entry_hash"],
61
+ # opaque, consumer-computed hash of the materialized aggregate state:
62
+ "state_digest": state_digest,
63
+ }
64
+ return log.append(payload, issued_at=issued_at)
65
+
66
+
67
+ def is_checkpoint(entry: dict[str, Any]) -> bool:
68
+ """True if ``entry`` is a well-typed checkpoint entry (by payload.type only)."""
69
+ payload = entry.get("payload") or {}
70
+ return isinstance(payload, dict) and payload.get("type") == CHECKPOINT_TYPE
71
+
72
+
73
+ class CheckpointAnchor(NamedTuple):
74
+ """What a late joiner adopts from a checkpoint: the cursor/anchor to walk the
75
+ chain forward from, plus the inherited state to seed the materialized view."""
76
+
77
+ seq: int # the checkpoint entry's own seq — the joiner's new cursor
78
+ entry_hash: str # the checkpoint entry's hash — the next ``expected_prev_hash``
79
+ covers_through_seq: int # history the state_digest already accounts for
80
+ state_digest: str # opaque inherited aggregate state
81
+
82
+
83
+ def adopt_checkpoint(entry: dict[str, Any]) -> tuple[bool, str, CheckpointAnchor | None]:
84
+ """Subscriber (late join): validate a signed checkpoint entry and, if good,
85
+ return the anchor to continue the chain from. ``(ok, reason, anchor)``.
86
+
87
+ Verifies the entry's own signature + content hash (``verify_entry``), that it is
88
+ a well-formed checkpoint, and — critically — that its ``prev_hash`` equals the
89
+ ``chain_tip`` it claims to commit to (otherwise the signed commitment and the
90
+ actual chain position disagree, and the checkpoint is rejected). The returned
91
+ ``anchor.entry_hash`` becomes the ``expected_prev_hash`` for the very next
92
+ ``verify_page`` call, so the joiner continues the SAME linear chain from
93
+ ``seq + 1`` — it simply declines to replay everything before the (trusted)
94
+ checkpoint. No completeness claim is made for pre-checkpoint history.
95
+ """
96
+ ok, reason = verify_entry(entry)
97
+ if not ok:
98
+ return False, reason, None
99
+ if not is_checkpoint(entry):
100
+ return False, "not_a_checkpoint", None
101
+ payload = entry["payload"]
102
+ for f in ("covers_through_seq", "chain_tip", "state_digest"):
103
+ if f not in payload:
104
+ return False, f"checkpoint missing {f!r}", None
105
+ # The payload's commitment MUST match the actual chain link, or the issuer
106
+ # signed a checkpoint whose stated history doesn't match where it sits.
107
+ if entry.get("prev_hash") != payload["chain_tip"]:
108
+ return False, "chain_tip_mismatch", None
109
+ anchor = CheckpointAnchor(
110
+ seq=entry["seq"],
111
+ entry_hash=entry["entry_hash"],
112
+ covers_through_seq=payload["covers_through_seq"],
113
+ state_digest=payload["state_digest"],
114
+ )
115
+ return True, "ok", anchor
sm_feed/entry.py ADDED
@@ -0,0 +1,114 @@
1
+ """A verifiable agent-feed entry — one signed, hash-chained, content-addressed
2
+ record a feed publishes.
3
+
4
+ An entry commits to its predecessor (``prev_hash``) and to its own content
5
+ (``entry_hash``), and is Ed25519-signed by the feed's issuer key. A subscriber
6
+ that walks a contiguous run of entries verifies three things at once: each entry
7
+ is authentic (signature), unaltered (hash), and that none were silently dropped
8
+ between two it holds — the chain links and the sequence numbers are contiguous.
9
+ That last property, completeness, is what a plain RSS/Atom/ActivityPub feed
10
+ cannot give.
11
+
12
+ The payload is opaque: the feed carries any JSON object with a ``type``, so the
13
+ same primitive serves published claims, binding-lifecycle events, or community
14
+ intelligence deltas without the feed knowing what they mean.
15
+
16
+ Crypto (Ed25519, JCS canonicalisation, did:key) is reused from sm-arp; this
17
+ module adds only the entry shape and its hash / sign / verify.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import base64
23
+ import hashlib
24
+ from typing import Any
25
+
26
+ from sm_arp import Identity, canonical_bytes, pubkey_from_did
27
+
28
+ ENTRY_VERSION = "feed-entry/0.1"
29
+
30
+ # The content-addressed core: everything the entry_hash commits to (all fields
31
+ # except entry_hash and signature, which are derived from it).
32
+ _CORE_FIELDS = ("version", "feed_id", "seq", "issued_at", "payload", "prev_hash")
33
+
34
+ # Closed field set: a valid entry has EXACTLY these keys. Enforced on verify so
35
+ # an extra field — which the signature would cover but entry_hash would not — can
36
+ # never create a shape two implementations disagree on. This is the sm-* family's
37
+ # exact-match convention (frozenset(doc) != _FIELDS ⇒ reject).
38
+ _ALLOWED_ENTRY_FIELDS = frozenset({*_CORE_FIELDS, "entry_hash", "signature"})
39
+
40
+
41
+ def _core(entry: dict[str, Any]) -> dict[str, Any]:
42
+ return {k: entry[k] for k in _CORE_FIELDS}
43
+
44
+
45
+ def compute_entry_hash(entry: dict[str, Any]) -> str:
46
+ '''"sha256:<hex>" over the JCS-canonical core (excludes entry_hash + signature).'''
47
+ digest = hashlib.sha256(canonical_bytes(_core(entry), include_signature=False)).hexdigest()
48
+ return f"sha256:{digest}"
49
+
50
+
51
+ def build_entry(
52
+ identity: Identity,
53
+ *,
54
+ seq: int,
55
+ payload: dict[str, Any],
56
+ prev_hash: str | None,
57
+ issued_at: str,
58
+ ) -> dict[str, Any]:
59
+ """Build a signed feed entry.
60
+
61
+ ``feed_id`` is the issuer's DID (the feed's identity); ``prev_hash`` is the
62
+ previous entry's ``entry_hash`` (``None`` for the genesis entry). ``issued_at``
63
+ is caller-supplied RFC 3339 — this module takes no wall-clock, matching the
64
+ rest of the sm-* cores.
65
+ """
66
+ if not (isinstance(payload, dict) and isinstance(payload.get("type"), str) and payload["type"]):
67
+ raise ValueError("payload must be a JSON object with a non-empty string 'type'")
68
+ if not isinstance(seq, int) or isinstance(seq, bool) or seq < 0:
69
+ raise ValueError("seq must be an int >= 0")
70
+ core = {
71
+ "version": ENTRY_VERSION,
72
+ "feed_id": identity.did,
73
+ "seq": seq,
74
+ "issued_at": issued_at,
75
+ "payload": payload,
76
+ "prev_hash": prev_hash,
77
+ }
78
+ signed: dict[str, Any] = {**core, "entry_hash": compute_entry_hash(core)}
79
+ sig = identity.sign(canonical_bytes(signed, include_signature=False))
80
+ signed["signature"] = base64.b64encode(sig).decode("ascii")
81
+ return signed
82
+
83
+
84
+ def verify_entry(entry: dict[str, Any]) -> tuple[bool, str]:
85
+ """Verify an entry's content hash and issuer signature. Returns ``(ok, reason)``.
86
+
87
+ This checks the entry in isolation; chain linkage across entries is
88
+ :func:`sm_feed.feed.verify_page`'s job.
89
+ """
90
+ # Hostile input must never raise — a non-object is simply invalid.
91
+ if not isinstance(entry, dict):
92
+ return False, "not_an_object"
93
+ # Exactly the known fields — no missing, no extra (see _ALLOWED_ENTRY_FIELDS).
94
+ if frozenset(entry) != _ALLOWED_ENTRY_FIELDS:
95
+ return False, "field_set_mismatch"
96
+ if entry["version"] != ENTRY_VERSION:
97
+ return False, f"version must be {ENTRY_VERSION!r}"
98
+ # A verified entry a consumer dispatches on MUST carry a typed payload.
99
+ payload = entry["payload"]
100
+ if not (isinstance(payload, dict) and isinstance(payload.get("type"), str) and payload["type"]):
101
+ return False, "payload_not_typed_object"
102
+ if not isinstance(entry["seq"], int) or isinstance(entry["seq"], bool) or entry["seq"] < 0:
103
+ return False, "seq_not_non_negative_int"
104
+ if compute_entry_hash(entry) != entry["entry_hash"]:
105
+ return False, "entry_hash_mismatch"
106
+ body = {k: v for k, v in entry.items() if k != "signature"}
107
+ try:
108
+ pubkey_from_did(entry["feed_id"]).verify(
109
+ base64.b64decode(entry["signature"]),
110
+ canonical_bytes(body, include_signature=False),
111
+ )
112
+ except Exception: # noqa: BLE001 — any failure is a failed verification
113
+ return False, "bad_signature"
114
+ return True, "ok"
@@ -0,0 +1,106 @@
1
+ """Fork (equivocation) detection via subscriber gossip.
2
+
3
+ Two subscribers exchange the latest SIGNED HEAD each has seen for a feed. If an
4
+ issuer ever signed two *different* heads at the SAME ``seq``, it forked its
5
+ history — presented incompatible views to different subscribers. This module is
6
+ the pure EVALUATION a subscriber runs on a gossiped head; the gossip transport
7
+ itself (who to ask, how often) is the consumer's (SPEC §6).
8
+
9
+ Strict linearity (no Merkle): a single linear chain has exactly one entry at each
10
+ ``seq``, and ``(seq, entry_hash)`` fully locates a position in it.
11
+ So a conflict is detectable by direct comparison of two signed heads — no Merkle
12
+ consistency proof, no ``O(log n)`` structure.
13
+
14
+ CRYPTOGRAPHIC ASSUMPTIONS — this is where the non-repudiation lives:
15
+
16
+ * An ``EquivocationProof`` is non-repudiable ONLY because BOTH heads carry a
17
+ valid Ed25519 signature by the SAME ``feed_id``. ``detect_equivocation``
18
+ therefore verifies both signatures BEFORE emitting a proof — otherwise a
19
+ malicious peer could fabricate a fake head and frame an honest issuer. A
20
+ "proof" built from an unverified head is worthless; never construct one.
21
+
22
+ * (feed_id equal) ∧ (seq equal) ∧ (entry_hash differ), both validly signed, is
23
+ conclusive: the two heads are the issuer's OWN contradictory statements about
24
+ the tip at one position. No third party could have produced them.
25
+
26
+ * The proof proves the ISSUER equivocated — nothing about which branch is
27
+ "correct" (both are the issuer's signed statements). What to do about it (drop
28
+ the feed, publish the proof, slash a bond) is policy, not this function.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ from typing import Any
34
+
35
+ from .feed import verify_signed_head
36
+
37
+ EQUIVOCATION_VERSION = "feed-equivocation/0.1"
38
+
39
+
40
+ def detect_equivocation(
41
+ local_head: dict[str, Any], peer_head: dict[str, Any]
42
+ ) -> dict[str, Any] | None:
43
+ """Return a signed ``EquivocationProof`` iff the two heads prove the issuer
44
+ forked its feed; otherwise ``None``.
45
+
46
+ A proof is emitted only when BOTH heads verify under the SAME ``feed_id`` at
47
+ the SAME ``seq`` with CONFLICTING ``entry_hash``. Consistent heads (equal
48
+ tips), heads from different feeds, heads at different positions, or any head
49
+ whose signature does not verify all yield ``None`` — a conflict that cannot be
50
+ cryptographically attributed to the issuer is not a proof.
51
+ """
52
+ # 1. Authenticity gate. An unsigned or forged head can NEVER ground a proof;
53
+ # verify both before comparing anything, so a peer cannot frame the issuer.
54
+ ok_local, _ = verify_signed_head(local_head)
55
+ ok_peer, _ = verify_signed_head(peer_head)
56
+ if not (ok_local and ok_peer):
57
+ return None
58
+
59
+ # 2. Same issuer, same position — else these are simply two different feeds, or
60
+ # two honest points on one history, not a contradiction.
61
+ if local_head.get("feed_id") != peer_head.get("feed_id"):
62
+ return None
63
+ if local_head.get("seq") != peer_head.get("seq"):
64
+ return None
65
+
66
+ # 3. Conflicting tips at that position = a fork. Equal tips = consistent.
67
+ if local_head.get("entry_hash") == peer_head.get("entry_hash"):
68
+ return None
69
+
70
+ # The two conflicting signed heads ARE the proof — each is self-contained and
71
+ # independently re-verifiable via verify_equivocation_proof below.
72
+ return {
73
+ "version": EQUIVOCATION_VERSION,
74
+ "feed_id": local_head["feed_id"],
75
+ "seq": local_head["seq"],
76
+ "head_a": local_head,
77
+ "head_b": peer_head,
78
+ }
79
+
80
+
81
+ def verify_equivocation_proof(proof: dict[str, Any]) -> tuple[bool, str]:
82
+ """Independently re-check a proof without trusting whoever reported it:
83
+ ``(ok, reason)``.
84
+
85
+ Re-verifies both heads' signatures and that they share ``feed_id`` and ``seq``
86
+ but differ in ``entry_hash``. Because the evidence is the issuer's own two
87
+ signatures, anyone can run this on a gossiped proof and reach the same verdict.
88
+ """
89
+ if proof.get("version") != EQUIVOCATION_VERSION:
90
+ return False, f"version must be {EQUIVOCATION_VERSION!r}"
91
+ a, b = proof.get("head_a"), proof.get("head_b")
92
+ if not isinstance(a, dict) or not isinstance(b, dict):
93
+ return False, "proof missing head_a/head_b"
94
+ ok_a, ra = verify_signed_head(a)
95
+ if not ok_a:
96
+ return False, f"head_a: {ra}"
97
+ ok_b, rb = verify_signed_head(b)
98
+ if not ok_b:
99
+ return False, f"head_b: {rb}"
100
+ if not (a["feed_id"] == b["feed_id"] == proof.get("feed_id")):
101
+ return False, "feed_id mismatch"
102
+ if not (a["seq"] == b["seq"] == proof.get("seq")):
103
+ return False, "seq mismatch"
104
+ if a["entry_hash"] == b["entry_hash"]:
105
+ return False, "no_conflict" # heads agree — not equivocation
106
+ return True, "ok"
sm_feed/feed.py ADDED
@@ -0,0 +1,191 @@
1
+ """The feed itself: an append-only log, the page a subscriber pulls (or is
2
+ pushed), and the signed head that anchors "the feed as of here".
3
+
4
+ :func:`verify_page` is the point of the whole primitive. It checks that a
5
+ returned run of entries is authentic, unaltered, **contiguous from the cursor
6
+ the subscriber already holds**, and ends at a signed head — so the subscriber
7
+ can prove it received the *complete* sequence, not just "some recent items".
8
+ Completeness is relative to the anchor you hold: sync from genesis
9
+ (``expected_prev_hash=None``) for end-to-end completeness, or from a trusted
10
+ signed head to start mid-stream.
11
+
12
+ Pull and push deliver the same object — a :func:`FeedLog.page`. A pull is a
13
+ ``GET /feed?since=<cursor>`` returning it; a push is a ``POST`` of it to a
14
+ subscriber's callback. The wire format and the verification are identical.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import base64
20
+ from typing import Any
21
+
22
+ from sm_arp import Identity, canonical_bytes, pubkey_from_did
23
+
24
+ from .entry import build_entry, verify_entry
25
+
26
+ HEAD_VERSION = "feed-head/0.1"
27
+ PAGE_VERSION = "feed-page/0.1"
28
+
29
+ # Closed field sets (the sm-* family's exact-match discipline): a valid head/page
30
+ # has EXACTLY these keys. Enforced on verify so no extra field slips past.
31
+ _ALLOWED_HEAD_FIELDS = frozenset(
32
+ {"version", "feed_id", "seq", "entry_hash", "generated_at", "signature"}
33
+ )
34
+ _ALLOWED_PAGE_FIELDS = frozenset({"version", "feed_id", "since", "entries", "head"})
35
+
36
+
37
+ def build_signed_head(
38
+ identity: Identity, *, seq: int, entry_hash: str, generated_at: str
39
+ ) -> dict[str, Any]:
40
+ """A signed statement of the feed's current head — ``{seq, entry_hash}`` bound
41
+ to the issuer's key and a timestamp. A subscriber pins this to detect a server
42
+ that later tries to rewind or fork the feed."""
43
+ core = {
44
+ "version": HEAD_VERSION,
45
+ "feed_id": identity.did,
46
+ "seq": seq,
47
+ "entry_hash": entry_hash,
48
+ "generated_at": generated_at,
49
+ }
50
+ sig = identity.sign(canonical_bytes(core, include_signature=False))
51
+ return {**core, "signature": base64.b64encode(sig).decode("ascii")}
52
+
53
+
54
+ def verify_signed_head(head: dict[str, Any]) -> tuple[bool, str]:
55
+ """Verify a signed head's issuer signature. Returns ``(ok, reason)``. Never
56
+ raises on hostile input — a non-object or wrong-shaped head is just invalid."""
57
+ if not isinstance(head, dict):
58
+ return False, "not_an_object"
59
+ if frozenset(head) != _ALLOWED_HEAD_FIELDS:
60
+ return False, "field_set_mismatch"
61
+ if head["version"] != HEAD_VERSION:
62
+ return False, f"version must be {HEAD_VERSION!r}"
63
+ body = {k: v for k, v in head.items() if k != "signature"}
64
+ try:
65
+ pubkey_from_did(head["feed_id"]).verify(
66
+ base64.b64decode(head["signature"]),
67
+ canonical_bytes(body, include_signature=False),
68
+ )
69
+ except Exception: # noqa: BLE001 — any failure is a failed verification
70
+ return False, "bad_signature"
71
+ return True, "ok"
72
+
73
+
74
+ class FeedLog:
75
+ """In-memory reference feed. ``append`` signs and chains a new entry;
76
+ ``since`` / ``head_ref`` / ``page`` read.
77
+
78
+ Persistence is a consumer concern, deliberately not baked in: back the entry
79
+ list with your own store (a table keyed by ``seq``) and reuse the same
80
+ ``page`` / :func:`verify_page` on either side — exactly how sm-arp's ReceiptLog
81
+ grows a SQLite and a Postgres backend over one receipt shape.
82
+ """
83
+
84
+ def __init__(self, identity: Identity, entries: list[dict[str, Any]] | None = None) -> None:
85
+ self._identity = identity
86
+ self._entries: list[dict[str, Any]] = list(entries or [])
87
+
88
+ @property
89
+ def feed_id(self) -> str:
90
+ return str(self._identity.did)
91
+
92
+ def append(self, payload: dict[str, Any], *, issued_at: str) -> dict[str, Any]:
93
+ """Sign and append one entry, chained to the current head."""
94
+ seq = self._entries[-1]["seq"] + 1 if self._entries else 0
95
+ prev_hash = self._entries[-1]["entry_hash"] if self._entries else None
96
+ entry = build_entry(
97
+ self._identity, seq=seq, payload=payload, prev_hash=prev_hash, issued_at=issued_at
98
+ )
99
+ self._entries.append(entry)
100
+ return entry
101
+
102
+ def since(self, cursor: int | None) -> list[dict[str, Any]]:
103
+ """Entries with ``seq`` strictly greater than ``cursor`` (all, if ``None``)."""
104
+ floor = -1 if cursor is None else int(cursor)
105
+ return [e for e in self._entries if e["seq"] > floor]
106
+
107
+ def head_ref(self) -> dict[str, Any] | None:
108
+ """The unsigned ``{seq, entry_hash}`` of the last entry, or ``None`` if empty."""
109
+ if not self._entries:
110
+ return None
111
+ last = self._entries[-1]
112
+ return {"seq": last["seq"], "entry_hash": last["entry_hash"]}
113
+
114
+ def page(self, cursor: int | None, *, generated_at: str) -> dict[str, Any]:
115
+ """A ``feed-page/0.1`` for a subscriber whose cursor is ``cursor``: the
116
+ entries after it plus a signed head. Serve on pull, or POST on push."""
117
+ ref = self.head_ref()
118
+ head = (
119
+ build_signed_head(
120
+ self._identity,
121
+ seq=ref["seq"],
122
+ entry_hash=ref["entry_hash"],
123
+ generated_at=generated_at,
124
+ )
125
+ if ref is not None
126
+ else None
127
+ )
128
+ return {
129
+ "version": PAGE_VERSION,
130
+ "feed_id": self.feed_id,
131
+ "since": cursor,
132
+ "entries": self.since(cursor),
133
+ "head": head,
134
+ }
135
+
136
+
137
+ def verify_page(
138
+ page: dict[str, Any], *, expected_prev_hash: str | None = None
139
+ ) -> tuple[bool, str, dict[str, Any] | None]:
140
+ """Verify a pulled or pushed page and return ``(ok, reason, new_head_ref)``.
141
+
142
+ ``expected_prev_hash`` is the ``entry_hash`` of the last entry the subscriber
143
+ already holds (``None`` on a first, from-genesis sync). Verifies: page shape,
144
+ every entry (signature + hash), an unbroken chain from ``expected_prev_hash``,
145
+ contiguous sequence numbers (no silent gaps), and a signed head that matches
146
+ the last entry. ``new_head_ref`` is the ``{seq, entry_hash}`` to persist as the
147
+ next cursor anchor.
148
+ """
149
+ # Never raise on hostile input — a non-object or wrong-shaped page is invalid.
150
+ if not isinstance(page, dict):
151
+ return False, "not_an_object", None
152
+ if frozenset(page) != _ALLOWED_PAGE_FIELDS:
153
+ return False, "field_set_mismatch", None
154
+ if page["version"] != PAGE_VERSION:
155
+ return False, f"version must be {PAGE_VERSION!r}", None
156
+ feed_id = page["feed_id"]
157
+ entries = page["entries"]
158
+ if not isinstance(entries, list):
159
+ return False, "entries must be a list", None
160
+
161
+ prev_hash = expected_prev_hash
162
+ prev_seq: int | None = None
163
+ for e in entries:
164
+ if not isinstance(e, dict):
165
+ return False, "entry_not_an_object", None
166
+ if e.get("feed_id") != feed_id:
167
+ return False, f"feed_id mismatch at seq {e.get('seq')}", None
168
+ ok, reason = verify_entry(e)
169
+ if not ok:
170
+ return False, f"entry {e.get('seq')}: {reason}", None
171
+ if e.get("prev_hash") != prev_hash:
172
+ return False, f"chain_break at seq {e.get('seq')}", None
173
+ if prev_seq is not None and e.get("seq") != prev_seq + 1:
174
+ return False, f"non_contiguous_seq at {e.get('seq')}", None
175
+ prev_hash = e["entry_hash"]
176
+ prev_seq = e["seq"]
177
+
178
+ head = page.get("head")
179
+ if head is None:
180
+ if entries:
181
+ return False, "entries present but no signed head", None
182
+ return True, "ok", None
183
+
184
+ ok, reason = verify_signed_head(head)
185
+ if not ok:
186
+ return False, f"head: {reason}", None
187
+ if head.get("feed_id") != feed_id:
188
+ return False, "head feed_id mismatch", None
189
+ if entries and (head.get("entry_hash") != prev_hash or head.get("seq") != prev_seq):
190
+ return False, "head does not match last entry", None
191
+ return True, "ok", {"seq": head["seq"], "entry_hash": head["entry_hash"]}
sm_feed/py.typed ADDED
File without changes
@@ -0,0 +1,132 @@
1
+ Metadata-Version: 2.4
2
+ Name: sm-feed
3
+ Version: 0.1.0
4
+ Summary: The Verifiable Agent Feed — a signed, hash-chained, cursor-based append-only feed a subscriber can prove is complete and untampered.
5
+ Project-URL: Homepage, https://github.com/Sharathvc23/sm-feed
6
+ Project-URL: Spec, https://github.com/Sharathvc23/sm-feed/blob/main/SPEC.md
7
+ Author-email: StellarMinds <hello@stellarminds.ai>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: ai-agents,did,federation,feed,nanda,transparency-log,verifiable
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.11
16
+ Requires-Dist: sm-arp>=0.3.0
17
+ Provides-Extra: dev
18
+ Requires-Dist: coverage>=7.0; extra == 'dev'
19
+ Requires-Dist: mypy>=1.0; extra == 'dev'
20
+ Requires-Dist: pytest>=7.0; extra == 'dev'
21
+ Requires-Dist: ruff>=0.4; extra == 'dev'
22
+ Description-Content-Type: text/markdown
23
+
24
+ # sm-feed
25
+
26
+ **The Verifiable Agent Feed — a signed, hash-chained, cursor-based append-only feed a subscriber can prove is complete and untampered.**
27
+
28
+ An agent that publishes an ongoing stream — claims, lifecycle events, aggregate
29
+ signals — is served today by an RSS feed or a bespoke webhook. Both ask the
30
+ subscriber to *trust the server* for completeness: a feed can silently drop or
31
+ reorder an item and no one can tell. `sm-feed` closes that gap. Every entry is
32
+ Ed25519-signed and hash-chained, so a subscriber that walks a contiguous run
33
+ verifies authenticity, integrity, **and completeness** in one pass. It owns the
34
+ *feed* — the wire shape and its verification — and nothing else: the transport,
35
+ the storage, and the meaning of the payload are the consumer's. The payload is
36
+ opaque (any JSON object with a `type`), so one format carries any agent's stream.
37
+
38
+ ## What this package secures (v0.1)
39
+
40
+ - **Authenticity** — each entry is Ed25519-signed by the feed's issuer DID.
41
+ - **Tamper-evidence** — `entry_hash` content-addresses the entry; any edit to any
42
+ field breaks it and verification returns falsy (never raises on hostile input).
43
+ - **Completeness** — entries are hash-chained (`prev_hash`) with contiguous `seq`;
44
+ a dropped or reordered entry breaks the chain from the subscriber's anchor.
45
+ - **Head attestation** — a signed head (`{seq, entry_hash}`) lets a subscriber pin
46
+ "the feed as of here" and detect a later rewind.
47
+ - **Adversarially tested.** The conformance corpus includes a hostile vector per
48
+ failure path: dropped entry, tampered payload, wrong anchor, forged head.
49
+
50
+ ## What this package does NOT (yet) do
51
+
52
+ - **Fork detection across subscribers** — a signed head proves "the issuer said
53
+ this is head", not that every subscriber saw the same history. Witness
54
+ co-signing / gossip (à la Certificate Transparency) is a later property; see
55
+ [`SPEC.md`](./SPEC.md) §6.
56
+ - **Merkle inclusion proofs** — completeness is by walking the chain; an
57
+ `O(log n)` proof for a single old entry is future work.
58
+ - **Push delivery, retry, and subscription registration** — the consumer's
59
+ responsibility; this primitive fixes only the payload and its verification.
60
+ - **A trusted clock or key custody** — `issued_at` is caller-asserted; key
61
+ generation/rotation/revocation is out of scope.
62
+
63
+ ## Features
64
+
65
+ - One dependency (`sm-arp`, for the shared Ed25519 / JCS / did:key crypto).
66
+ - Pure, wall-clock-free core: the caller supplies timestamps.
67
+ - Pull (`GET …/feed?since=<cursor>`) and push (`POST` a page) deliver the same
68
+ object; `verify_page` checks both.
69
+ - Opaque typed payload — the same wire format serves claims, events, or deltas.
70
+
71
+ ## Installation
72
+
73
+ Not yet published to PyPI — install directly from the repository:
74
+
75
+ ```bash
76
+ pip install git+https://github.com/Sharathvc23/sm-feed.git
77
+ ```
78
+
79
+ ## Quick start
80
+
81
+ ```python
82
+ from sm_arp import Identity
83
+ from sm_feed import FeedLog, verify_page
84
+
85
+ issuer = Identity.generate()
86
+ log = FeedLog(issuer)
87
+ log.append({"type": "example/claim", "title": "First"}, issued_at="2026-01-01T00:00:00+00:00")
88
+ log.append({"type": "example/claim", "title": "Second"}, issued_at="2026-01-01T01:00:00+00:00")
89
+
90
+ # Serve on pull (GET /feed?since=<cursor>) or POST on push — same object.
91
+ page = log.page(cursor=None, generated_at="2026-01-01T02:00:00+00:00")
92
+
93
+ # Subscriber: verify authenticity + completeness, keep the new cursor anchor.
94
+ ok, reason, head = verify_page(page, expected_prev_hash=None)
95
+ assert ok, reason
96
+ # persist head["entry_hash"] as expected_prev_hash for the next pull
97
+ ```
98
+
99
+ A runnable end-to-end example (publish → verify → detect a dropped entry) is in
100
+ [`examples/quick_start.py`](./examples/quick_start.py).
101
+
102
+ ## Reference fixtures
103
+
104
+ The golden vectors under [`conformance/vectors/`](./conformance/vectors/) are
105
+ regenerated by `conformance/_vector_gen.py` from a fixed, non-secret fixture seed
106
+ (`"11"×32` — regenerable, never a real key) and replayed by
107
+ `tests/test_conformance_vectors.py`. They are the language-agnostic corpus a
108
+ second implementation replays to prove interoperability.
109
+
110
+ ## Specification
111
+
112
+ - [`SPEC.md`](./SPEC.md) — normative wire shape and verification, working draft.
113
+ - [`WHITEPAPER.md`](./WHITEPAPER.md) — design rationale and axioms.
114
+ - [`THREATMODEL.md`](./THREATMODEL.md) — what it defends, and what it doesn't.
115
+
116
+ ## Related packages
117
+
118
+ | Package | Role |
119
+ | --- | --- |
120
+ | [`sm-arp`](https://github.com/Sharathvc23/sm-arp) | Agency Receipt Protocol — the signed, hash-chained record primitive sm-feed reuses for crypto |
121
+ | [`sm-authority`](https://github.com/Sharathvc23/sm-authority) | Common Authority Evidence — establishes who controls a subject |
122
+ | [`sm-bridge`](https://github.com/Sharathvc23/sm-bridge) | AgentFacts / registry endpoints — a natural feed publisher and consumer |
123
+
124
+ ## License
125
+
126
+ [MIT](./LICENSE)
127
+
128
+ ---
129
+
130
+ *First published: 2026-07-30 | Last modified: 2026-07-30*
131
+
132
+ *Personal research contributions aligned with [Project NANDA](https://projectnanda.org) standards. [Stellarminds.ai](https://stellarminds.ai)*
@@ -0,0 +1,10 @@
1
+ sm_feed/__init__.py,sha256=rMjOZdi-xPj3UUZdhy2OSwppsjRahpzZy50asw4_Rbw,1808
2
+ sm_feed/checkpoint.py,sha256=3wxbgCOt-GpVaQWUEVf0OCFY_BKXgmWCV7P0FugkXpM,5762
3
+ sm_feed/entry.py,sha256=ppb2qJ1bKDuf3DHZ9UgmGeF5S4TvRMaO2bvV2uVWmRI,4938
4
+ sm_feed/equivocation.py,sha256=NjlKzauizS3SSGYBDY3XbuI8vwlkD4afzZ3NpdtZ_qk,4806
5
+ sm_feed/feed.py,sha256=4zH7PLZwMKzjfZP-HIHKMIefiwN0zChsiHGOiYKwA04,8038
6
+ sm_feed/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ sm_feed-0.1.0.dist-info/METADATA,sha256=t3hag-mzoa39zxacw1rfWQrZ_I1pCQKkNqFSXBz8_UM,6007
8
+ sm_feed-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
9
+ sm_feed-0.1.0.dist-info/licenses/LICENSE,sha256=1GxUXVSqnKiacfzoeho3QqL8bklwbXfzVtWKRefzc24,1087
10
+ sm_feed-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 StellarMinds (stellarminds.ai)
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.