Documentation
¶
Overview ¶
package group implements the A2AL Group protocol: a signed, append-only DAG replicated across a closed set of AIDs. It is the coordination plane for agent collaboration and has no dependency on the network layer.
Index ¶
- Constants
- Variables
- func CASPath(id [32]byte) string
- func CASURL(holder a2al.Address, id [32]byte) string
- func DMGroupID(a, b a2al.Address) [32]byte
- func DecodeMemberBody(body []byte) (a2al.Address, bool)
- func EncodeBudgetBody(target a2al.Address, amount int64, modelTag string) []byte
- func EncodeMemberBody(aid a2al.Address) []byte
- func EncodeSpendBody(amount int64, modelTag string) []byte
- func GroupURL(creatorAID a2al.Address, groupID [32]byte) string
- func MigrateFromLegacy(dst *Store, srcDir string) (int, error)
- func ParseCASPath(p string) (id [32]byte, ok bool)
- func ParseGroupURL(link string) (creatorAID a2al.Address, groupID [32]byte, err error)
- type Entry
- type EntryOption
- type EntryRead
- type MemberRole
- type MemberSet
- func (ms MemberSet) All() map[a2al.Address]MemberRole
- func (ms *MemberSet) Apply(e Entry, creatorAID a2al.Address)
- func (ms MemberSet) CanGrantAdmin(aid a2al.Address) bool
- func (ms MemberSet) CanInvite(aid a2al.Address) bool
- func (ms MemberSet) CanSync(aid a2al.Address) bool
- func (ms MemberSet) CanWrite(aid a2al.Address) bool
- func (ms MemberSet) Role(aid a2al.Address) MemberRole
- type Meta
- type ReadFilter
- type Store
- func (s *Store) AdvanceCursor(seq uint64) (advanced bool, err error)
- func (s *Store) Append(e Entry, pub ed25519.PublicKey) error
- func (s *Store) Balance(aid a2al.Address) (int64, error)
- func (s *Store) Close() error
- func (s *Store) Closure(fromIDs, peerKnownHeads [][32]byte) ([]Entry, error)
- func (s *Store) Entries(ids [][32]byte) ([]Entry, error)
- func (s *Store) EntryCount() int
- func (s *Store) Get(id [32]byte) (Entry, bool)
- func (s *Store) Heads() [][32]byte
- func (s *Store) ID() [32]byte
- func (s *Store) LastEntryTS() int64
- func (s *Store) MaxSeq() uint64
- func (s *Store) MaxSeqLocked() uint64
- func (s *Store) Members() (MemberSet, error)
- func (s *Store) Meta() Meta
- func (s *Store) Missing(peerHeads [][32]byte) [][32]byte
- func (s *Store) Read(afterSeq uint64, limit int, filter ReadFilter) ([]EntryRead, uint64, bool, error)
- func (s *Store) ReadCursor() uint64
- func (s *Store) RebuildDerived() error
- func (s *Store) UnreadCount(self a2al.Address) uint64
- func (s *Store) UnreadCountUpTo(self a2al.Address, upToSeq uint64) uint64
- func (s *Store) WantedParents() [][32]byte
Constants ¶
const ( KindMeta = "meta" KindInvite = "invite" KindRevoke = "revoke" KindGrantAdmin = "grant_admin" KindRevokeAdmin = "revoke_admin" KindProposeInvite = "propose_invite" KindRetract = "retract" KindBudget = "budget" KindSpend = "spend" KindSnapshot = "snapshot" )
Protocol-level entry kinds. Application layers may define additional kinds freely.
const MaxEntryBodySize = 2048
MaxEntryBodySize mirrors protocol.MaxEntryBodySize and is the maximum allowed byte length of an inline entry body. Defined here to avoid importing the protocol package from the core group library. The value MUST match protocol.MaxEntryBodySize; a test in group_sync enforces this.
Variables ¶
var ( ErrBadSignature = errors.New("group: invalid entry signature") ErrIDMismatch = errors.New("group: entry ID does not match content hash") ErrMalformed = errors.New("group: malformed entry") )
Entry errors.
var ErrNoStore = errors.New("group: no local replica")
ErrNoStore is returned when Open is called on a path that holds no group store. Callers that know the AID and group id should translate it into an actionable message naming what to call next, rather than surfacing it raw.
Functions ¶
func DMGroupID ¶
DMGroupID returns the deterministic Group ID for a one-to-one direct message between two AIDs. Both parties can independently compute the same ID without any prior communication.
func DecodeMemberBody ¶
DecodeMemberBody decodes a membership entry body and returns the target AID. Returns false if the body is not a valid membership body or the AID length is wrong.
func EncodeBudgetBody ¶
EncodeBudgetBody returns the CBOR body for a budget entry.
func EncodeMemberBody ¶
EncodeMemberBody returns CBOR body bytes for a membership entry targeting aid.
func EncodeSpendBody ¶
EncodeSpendBody returns the CBOR body for a spend entry.
func GroupURL ¶
GroupURL returns the canonical a2al:// link for a Group. The link embeds the creator AID to provide a routing hint for new members.
func MigrateFromLegacy ¶
MigrateFromLegacy reads all entries from the old per-file format in dir and appends them (in causal order) to dst. dst must be a freshly created Store. Returns the number of entries migrated.
func ParseCASPath ¶
ParseCASPath extracts an object id from "/cas/{64hex}" (query string ignored).
Types ¶
type Entry ¶
type Entry struct {
// ID is SHA256 of the canonical CBOR encoding of the signed core fields.
ID [32]byte
// Author is the AID that signed this entry.
Author a2al.Address
// Sig is the Ed25519 signature over the canonical CBOR of the core fields.
Sig [64]byte
// Parents lists the DAG leaf IDs known to the author at write time.
// Empty for the first entry in a group (genesis).
Parents [][32]byte
// TS is the author's local Unix milliseconds.
// Used only for display ordering of concurrent entries; not a causal clock.
TS int64
// Kind is an open-ended type tag. The protocol defines well-known kinds
// (see Kind* constants); application layers may extend freely.
Kind string
// ReplyTo is a semantic reply reference to another entry's ID.
// Zero value means no reply reference.
ReplyTo [32]byte
// To lists AIDs explicitly mentioned for notification.
// Empty means no specific recipients.
To []a2al.Address
// Body holds inline content, or an object descriptor (name/size/mime)
// when Ref is also set.
Body []byte
// Ref is a content-addressed object reference (SHA256 of object bytes).
// Zero value means no object. May be set together with Body (descriptor).
Ref [32]byte
}
Entry is the coordination plane's minimal immutable unit. All fields are set at creation time and never modified.
func NewEntry ¶
func NewEntry(priv ed25519.PrivateKey, author a2al.Address, parents [][32]byte, kind string, opts ...EntryOption) (Entry, error)
NewEntry constructs, signs, and returns a new Entry. parents should be the current DAG heads of the local replica at write time.
func TopoSort ¶
TopoSort returns entries sorted in causal (topological) order: every entry appears after all its locally-known parents. Concurrent entries (no causal relationship) are ordered by (TS asc, ID lex asc) as a deterministic tiebreaker.
Parents absent from the input slice are treated as already satisfied.
func Unmarshal ¶
Unmarshal decodes a CBOR-encoded entry. The signature and ID are NOT verified; call e.Verify() separately. Unknown fields are silently ignored for forward compatibility.
func (Entry) Verify ¶
Verify checks that e.ID matches SHA256 of the core fields, and that e.Sig is a valid Ed25519 signature over those same bytes. pub must be the Ed25519 public key that corresponds to e.Author.
type EntryOption ¶
type EntryOption func(*Entry)
EntryOption is a functional option for NewEntry.
func WithBody ¶
func WithBody(body []byte) EntryOption
WithBody sets inline body content (text, or object descriptor when used with WithRef).
func WithRef ¶
func WithRef(ref [32]byte) EntryOption
WithRef sets a content-addressed object reference. May be combined with WithBody.
func WithReplyTo ¶
func WithReplyTo(id [32]byte) EntryOption
WithReplyTo sets the semantic reply-to entry ID.
func WithTS ¶
func WithTS(ts int64) EntryOption
WithTS overrides the timestamp. Intended for testing only.
func WithTo ¶
func WithTo(aids ...a2al.Address) EntryOption
WithTo appends explicitly mentioned AIDs.
type EntryRead ¶
EntryRead pairs an Entry with its local arrival sequence number.
Seq is 1-based, monotonically increasing, and stable: it reflects the order entries were stored locally and never changes once assigned, even when late-arriving entries are inserted before earlier ones in causal order. Clients use Seq as a stable row identifier and as a start point to read from; to page forward they use the scannedTo returned by Read, which also accounts for entries the filter skipped. This mirrors the Kafka "offset" convention for append-only logs.
type MemberRole ¶
type MemberRole uint8
MemberRole represents the permission level of an AID within a Group. Values form a partial order: higher means more authority.
const ( RoleNone MemberRole = 0 // not a member; no record in the log RoleRevoked MemberRole = 1 // was a member; access explicitly revoked — distinct from never-joined RolePending MemberRole = 2 // proposed via propose_invite; awaiting admin approval RoleMember MemberRole = 3 // active member; may write entries and propose invites RoleAdmin MemberRole = 4 // may directly invite new members and revoke members RoleCreator MemberRole = 5 // initial authority; cannot be revoked )
type MemberSet ¶
type MemberSet struct {
// contains filtered or unexported fields
}
MemberSet is the membership state computed by replaying the entry log.
func (MemberSet) All ¶
func (ms MemberSet) All() map[a2al.Address]MemberRole
All returns a copy of the full member map.
func (*MemberSet) Apply ¶
Apply updates ms in-place to reflect the membership effect of a single entry. creatorAID is required to protect the creator from revocation and to seed the initial state when ms is empty. Entry kinds that do not affect membership are silently ignored.
func (MemberSet) CanGrantAdmin ¶
CanGrantAdmin reports whether aid may promote members to admin.
func (MemberSet) CanInvite ¶
CanInvite reports whether aid may directly invite new members (without approval).
func (MemberSet) CanSync ¶
CanSync reports whether aid may open a sync connection to read the entry log. Active and pending members may sync; strangers and revoked members may not.
type Meta ¶
type Meta struct {
SchemaVersion uint8 `cbor:"1,keyasint"`
GroupID [32]byte `cbor:"2,keyasint"`
CreatorAID a2al.Address `cbor:"3,keyasint"`
Title string `cbor:"4,keyasint,omitempty"`
CreatedAt int64 `cbor:"5,keyasint"` // Unix seconds
}
Meta holds the Group's identity and creation parameters. Persisted as meta.cbor in the store root directory.
type ReadFilter ¶
type ReadFilter struct {
Kind string // match exact kind string
Author a2al.Address // match exact author AID (zero = any)
SinceTS int64 // TS >= SinceTS (0 = no lower bound)
UntilTS int64 // TS <= UntilTS (0 = no upper bound)
To a2al.Address // entry must mention this AID in its To list (zero = any)
ReplyTo [32]byte // match exact ReplyTo entry ID (zero = any)
}
ReadFilter provides optional filtering criteria for Read. Zero value means "no constraint on this field".
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store manages the local replica of a single Group.
Storage layout (under dir):
meta.cbor – Group identity and creation parameters (written once) entries.log – Append-only entry log; each record is [4B len][4B CRC32][CBOR]
Objects are not stored here; a2ald maps hash→path in cas-map.json.
In-memory state is rebuilt from entries.log on Open. Crash safety is achieved by a length-prefix + CRC32 per record: incomplete tail records are detected and truncated on next Open.
All exported methods are safe for concurrent use.
func Create ¶
func Create(dir string, priv ed25519.PrivateKey, creator a2al.Address, title string) (*Store, error)
Create initialises a new Group store in dir and returns the opened Store.
func Join ¶
Join initialises a local Group store for a Group we are joining as a new member. Unlike Create, no genesis entry is written — the entry log will be populated by a subsequent sync with an existing member.
groupID, creatorAID and title must come from a trusted source such as a verified GroupInviteBody. dir must not already contain a Group store.
func (*Store) AdvanceCursor ¶
AdvanceCursor sets the read cursor to seq if seq > current cursor. It is a no-op when seq ≤ current cursor. Persists immediately. Returns true when the cursor actually advanced.
func (*Store) Append ¶
Append validates and persists a signed entry.
If pub is non-nil, the entry's signature and ID are verified against it. Pass nil only for entries created locally (already verified by the caller).
If the entry ID is already known, Append is idempotent (returns nil). Parents do not need to be locally present; out-of-order sync is supported.
func (*Store) Balance ¶
Balance returns the cost balance (total budgeted minus total spent) for aid.
func (*Store) Closure ¶
Closure computes the Give payload for a sync session.
Returns all locally-stored entries reachable from fromIDs but not from peerKnownHeads, capped at 200 entries per call.
func (*Store) Entries ¶
Entries retrieves multiple entries by ID. IDs not locally known are skipped.
func (*Store) EntryCount ¶
EntryCount returns the total number of locally-stored entries.
func (*Store) LastEntryTS ¶
LastEntryTS returns the TS of the most recently stored entry, or 0 if empty.
func (*Store) MaxSeq ¶
MaxSeq returns the local arrival sequence number of the most recently stored entry. Seq is 1-based; 0 means the store is empty. Used by the unread-count calculation: unread = MaxSeq − readCursor.
func (*Store) MaxSeqLocked ¶
MaxSeqLocked returns MaxSeq without acquiring the read lock. Must be called while already holding s.mu (read or write).
func (*Store) Members ¶
Members returns the current membership state by replaying the entry log. The result is cached and invalidated whenever Append writes a new entry.
func (*Store) Read ¶
func (s *Store) Read(afterSeq uint64, limit int, filter ReadFilter) ([]EntryRead, uint64, bool, error)
Read returns entries in causal display order, starting after afterSeq.
- afterSeq=0 means "from the beginning".
- Only entries satisfying filter are returned (all fields zero = no filter).
- At most limit entries are returned (default 50 if limit ≤ 0).
- scannedTo is how far this call examined: the seq of the last returned entry when the page hit the limit, otherwise the end of the log (the scan proved nothing further matches). Callers page forward by passing it as afterSeq. It is deliberately not derivable from the returned entries — a filtered read examines far past its last match, and a caller that instead resumes from that match re-walks the unmatched tail on every call.
- hasMore is true only when the page was truncated by limit. A filtered read that scanned to the end reports false even if later entries exist, because none of them match.
Each returned EntryRead carries its Seq so callers can correlate display rows with positions without counting. Within each page entries are sorted in causal (topological) order; Seq values reflect arrival order and may therefore not be monotone within the page when concurrent writes occur.
func (*Store) ReadCursor ¶
ReadCursor returns the current read-cursor value (0 = nothing read).
func (*Store) RebuildDerived ¶
RebuildDerived re-scans entries.log and rebuilds the in-memory index. Use after manual file manipulation or to recover from an inconsistency.
func (*Store) UnreadCount ¶
UnreadCount returns how many entries past the read cursor were written by someone other than self.
An AID's own entries are never unread to itself. Counting them would force the cursor to be advanced on every self-write just to keep the count honest, and that advance would silently swallow entries other members wrote in the meantime — the author would stop being notified about everyone else.
func (*Store) UnreadCountUpTo ¶
UnreadCountUpTo is UnreadCount restricted to entries with seq ≤ upToSeq. Callers use it to reconstruct the unread count as of an earlier moment, which is what makes the group.unread edge (0 → >0) computable.
func (*Store) WantedParents ¶
WantedParents returns parent IDs referenced by local entries but not yet stored locally. These should be included in the next Want request.