group

package
v0.3.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 18, 2026 License: MPL-2.0 Imports: 16 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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.

View Source
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

View Source
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.

View Source
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 CASPath

func CASPath(id [32]byte) string

CASPath is the well-known HTTP path served on an a2cs stream.

func CASURL

func CASURL(holder a2al.Address, id [32]byte) string

CASURL is the shareable download locator. It never embeds a filesystem path.

func DMGroupID

func DMGroupID(a, b a2al.Address) [32]byte

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

func DecodeMemberBody(body []byte) (a2al.Address, bool)

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

func EncodeBudgetBody(target a2al.Address, amount int64, modelTag string) []byte

EncodeBudgetBody returns the CBOR body for a budget entry.

func EncodeMemberBody

func EncodeMemberBody(aid a2al.Address) []byte

EncodeMemberBody returns CBOR body bytes for a membership entry targeting aid.

func EncodeSpendBody

func EncodeSpendBody(amount int64, modelTag string) []byte

EncodeSpendBody returns the CBOR body for a spend entry.

func GroupURL

func GroupURL(creatorAID a2al.Address, groupID [32]byte) string

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

func MigrateFromLegacy(dst *Store, srcDir string) (int, error)

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

func ParseCASPath(p string) (id [32]byte, ok bool)

ParseCASPath extracts an object id from "/cas/{64hex}" (query string ignored).

func ParseGroupURL

func ParseGroupURL(link string) (creatorAID a2al.Address, groupID [32]byte, err error)

ParseGroupURL parses a canonical a2al:// Group link produced by GroupURL. Returns creatorAID and groupID on success. Format: a2al://{creatorAID}/groups/{groupID_hex}

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

func TopoSort(entries []Entry) []Entry

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

func Unmarshal(data []byte) (Entry, error)

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) Marshal

func (e Entry) Marshal() ([]byte, error)

Marshal encodes e to CBOR for storage or transport.

func (Entry) Verify

func (e Entry) Verify(pub ed25519.PublicKey) error

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.

func (Entry) VerifyID

func (e Entry) VerifyID() error

VerifyID checks that e.ID equals SHA256 of the canonical core fields. This is a purely local, key-free integrity check: it detects corruption or crafted entries whose claimed ID does not match their content. Call Verify to additionally validate the Ed25519 signature.

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

type EntryRead struct {
	Entry
	Seq uint64
}

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

func (ms *MemberSet) Apply(e Entry, creatorAID a2al.Address)

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

func (ms MemberSet) CanGrantAdmin(aid a2al.Address) bool

CanGrantAdmin reports whether aid may promote members to admin.

func (MemberSet) CanInvite

func (ms MemberSet) CanInvite(aid a2al.Address) bool

CanInvite reports whether aid may directly invite new members (without approval).

func (MemberSet) CanSync

func (ms MemberSet) CanSync(aid a2al.Address) bool

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.

func (MemberSet) CanWrite

func (ms MemberSet) CanWrite(aid a2al.Address) bool

CanWrite reports whether aid may append entries to the group.

func (MemberSet) Role

func (ms MemberSet) Role(aid a2al.Address) MemberRole

Role returns the current role of aid. Returns RoleNone for unknown AIDs.

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.

func ReadMeta

func ReadMeta(dir string) (Meta, error)

ReadMeta reads only the metadata from a group store directory without loading the entry index. Use for lightweight enumeration.

func (Meta) ID

func (m Meta) ID() [32]byte

ID returns the Group's persistent identifier.

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

func Join(dir string, groupID [32]byte, creatorAID a2al.Address, title string) (*Store, error)

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 Open

func Open(dir string) (*Store, error)

Open loads an existing Group store from dir.

func (*Store) AdvanceCursor

func (s *Store) AdvanceCursor(seq uint64) (advanced bool, err error)

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

func (s *Store) Append(e Entry, pub ed25519.PublicKey) error

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

func (s *Store) Balance(aid a2al.Address) (int64, error)

Balance returns the cost balance (total budgeted minus total spent) for aid.

func (*Store) Close

func (s *Store) Close() error

Close releases the log file handle. The Store must not be used after Close.

func (*Store) Closure

func (s *Store) Closure(fromIDs, peerKnownHeads [][32]byte) ([]Entry, error)

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

func (s *Store) Entries(ids [][32]byte) ([]Entry, error)

Entries retrieves multiple entries by ID. IDs not locally known are skipped.

func (*Store) EntryCount

func (s *Store) EntryCount() int

EntryCount returns the total number of locally-stored entries.

func (*Store) Get

func (s *Store) Get(id [32]byte) (Entry, bool)

Get retrieves an entry by ID. Returns (Entry{}, false) if not locally present.

func (*Store) Heads

func (s *Store) Heads() [][32]byte

Heads returns the current DAG leaf entry IDs.

func (*Store) ID

func (s *Store) ID() [32]byte

ID returns the group's persistent identifier.

func (*Store) LastEntryTS

func (s *Store) LastEntryTS() int64

LastEntryTS returns the TS of the most recently stored entry, or 0 if empty.

func (*Store) MaxSeq

func (s *Store) MaxSeq() uint64

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

func (s *Store) MaxSeqLocked() uint64

MaxSeqLocked returns MaxSeq without acquiring the read lock. Must be called while already holding s.mu (read or write).

func (*Store) Members

func (s *Store) Members() (MemberSet, error)

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) Meta

func (s *Store) Meta() Meta

Meta returns a copy of the group's metadata.

func (*Store) Missing

func (s *Store) Missing(peerHeads [][32]byte) [][32]byte

Missing returns the IDs from peerHeads that are not locally known.

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

func (s *Store) ReadCursor() uint64

ReadCursor returns the current read-cursor value (0 = nothing read).

func (*Store) RebuildDerived

func (s *Store) RebuildDerived() error

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

func (s *Store) UnreadCount(self a2al.Address) uint64

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

func (s *Store) UnreadCountUpTo(self a2al.Address, upToSeq uint64) uint64

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

func (s *Store) WantedParents() [][32]byte

WantedParents returns parent IDs referenced by local entries but not yet stored locally. These should be included in the next Want request.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL