provenance

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package provenance implements session provenance tracking including checkpoints, session trees, and attribution for the Lango P2P layer.

Index

Constants

View Source
const AlgorithmSecp256k1Keccak256 = security.AlgorithmSecp256k1Keccak256

AlgorithmSecp256k1Keccak256 re-exports the canonical algorithm constant for backward compatibility.

Variables

View Source
var (
	ErrCheckpointNotFound = errors.New("checkpoint not found")
	ErrSessionNotFound    = errors.New("session node not found")
	ErrMaxCheckpoints     = errors.New("maximum checkpoints per session reached")
	ErrInvalidLabel       = errors.New("checkpoint label is required")
	ErrInvalidRunID       = errors.New("run ID is required")
	ErrInvalidSessionKey  = errors.New("session key is required")
	ErrInvalidRedaction   = errors.New("invalid redaction level")
)

Sentinel errors for the provenance package.

Functions

This section is empty.

Types

type Attribution

type Attribution struct {
	ID           string            `json:"id"`
	SessionKey   string            `json:"session_key"`
	RunID        string            `json:"run_id,omitempty"`
	WorkspaceID  string            `json:"workspace_id,omitempty"`
	AuthorType   AuthorType        `json:"author_type"`
	AuthorID     string            `json:"author_id"`
	FilePath     string            `json:"file_path,omitempty"`
	CommitHash   string            `json:"commit_hash,omitempty"`
	StepID       string            `json:"step_id,omitempty"`
	Source       AttributionSource `json:"source,omitempty"`
	LinesAdded   int               `json:"lines_added"`
	LinesRemoved int               `json:"lines_removed"`
	TokensUsed   TokenSummary      `json:"tokens_used"`
	CreatedAt    time.Time         `json:"created_at"`
}

Attribution records a coarse contribution by an author within a session.

func SortedAttributions

func SortedAttributions(items []Attribution) []Attribution

SortedAttributions returns a copy ordered by created_at ascending for canonical bundles.

type AttributionReport

type AttributionReport struct {
	SessionKey  string                 `json:"session_key"`
	ByAuthor    map[string]AuthorStats `json:"by_author"`
	ByFile      map[string]FileStats   `json:"by_file"`
	TotalTokens TokenSummary           `json:"total_tokens"`
	Checkpoints int                    `json:"checkpoints"`
	GeneratedAt time.Time              `json:"generated_at"`
}

AttributionReport aggregates attribution data for a session.

type AttributionService

type AttributionService struct {
	// contains filtered or unexported fields
}

AttributionService builds provenance views and reports.

func NewAttributionService

func NewAttributionService(store AttributionStore, checkpoints CheckpointStore, tokenUsage TokenUsageReader) *AttributionService

NewAttributionService creates a new attribution service.

func (*AttributionService) RecordWorkspaceOperation

func (s *AttributionService) RecordWorkspaceOperation(
	ctx context.Context,
	sessionKey, runID, workspaceID string,
	authorType AuthorType,
	authorID, commitHash, stepID string,
	source AttributionSource,
	stats []GitFileStat,
) error

RecordWorkspaceOperation persists git-aware attribution evidence.

func (*AttributionService) Report

func (s *AttributionService) Report(ctx context.Context, sessionKey string) (*AttributionReport, error)

Report builds an aggregated attribution report for a session.

func (*AttributionService) Save

func (s *AttributionService) Save(ctx context.Context, attr Attribution) error

Save records a single attribution row.

func (*AttributionService) View

func (s *AttributionService) View(ctx context.Context, sessionKey string, limit int) (*AttributionView, error)

View returns the raw attribution rows plus token/checkpoint rollups.

type AttributionSource

type AttributionSource string

AttributionSource identifies how an attribution record was captured.

const (
	AttributionSourceWorkspaceMerge       AttributionSource = "workspace_merge"
	AttributionSourceWorkspaceBundlePush  AttributionSource = "workspace_bundle_push"
	AttributionSourceWorkspaceBundleApply AttributionSource = "workspace_bundle_apply"
	AttributionSourceSessionFork          AttributionSource = "session_fork"
	AttributionSourceSessionMerge         AttributionSource = "session_merge"
	AttributionSourceSessionDiscard       AttributionSource = "session_discard"
	AttributionSourceBundleImport         AttributionSource = "bundle_import"
)

type AttributionStore

type AttributionStore interface {
	SaveAttribution(ctx context.Context, attr Attribution) error
	ListBySession(ctx context.Context, sessionKey string, limit int) ([]Attribution, error)
}

AttributionStore persists attribution records.

type AttributionView

type AttributionView struct {
	Attributions   []Attribution           `json:"attributions"`
	ByAuthorTokens map[string]TokenSummary `json:"by_author_tokens,omitempty"`
	TotalTokens    TokenSummary            `json:"total_tokens"`
	Checkpoints    int                     `json:"checkpoints"`
}

AttributionView is the raw attribution view returned by CLI show/export logic.

type AuthorStats

type AuthorStats struct {
	AuthorType   AuthorType   `json:"author_type"`
	LinesAdded   int          `json:"lines_added"`
	LinesRemoved int          `json:"lines_removed"`
	TokensUsed   TokenSummary `json:"tokens_used"`
	FileCount    int          `json:"file_count"`
}

AuthorStats summarizes an author's contributions.

type AuthorType

type AuthorType string

AuthorType identifies the kind of contributor.

const (
	AuthorHuman      AuthorType = "human"
	AuthorAgent      AuthorType = "agent"
	AuthorRemotePeer AuthorType = "remote_peer"
)

type BundleService

type BundleService struct {
	// contains filtered or unexported fields
}

BundleService exports, verifies, and imports provenance bundles.

func NewBundleService

func NewBundleService(
	checkpoints CheckpointStore,
	treeStore SessionTreeStore,
	attributions AttributionStore,
	attrService *AttributionService,
	verifiers map[string]SignatureVerifyFunc,
) *BundleService

NewBundleService creates a new provenance bundle service. verifiers maps algorithm names to verification functions; the provenance package does not contain any built-in verifier implementation.

func (*BundleService) Export

func (s *BundleService) Export(
	ctx context.Context,
	sessionKey string,
	level RedactionLevel,
	signerDID string,
	signer BundleSigner,
) (*ProvenanceBundle, []byte, error)

Export builds a provenance bundle, applies redaction, and signs it.

func (*BundleService) Import

func (s *BundleService) Import(ctx context.Context, data []byte) (*ProvenanceBundle, error)

Import verifies a bundle and stores only provenance-owned records.

func (*BundleService) Verify

func (s *BundleService) Verify(bundle *ProvenanceBundle) error

Verify validates the signer DID and signature of a bundle. The verifier is looked up from the map injected at construction time.

type BundleSigner

type BundleSigner interface {
	Sign(ctx context.Context, payload []byte) ([]byte, error)
	Algorithm() string
}

BundleSigner signs a canonical provenance payload and declares its algorithm.

type Checkpoint

type Checkpoint struct {
	ID         string            `json:"id"`
	SessionKey string            `json:"session_key"`
	RunID      string            `json:"run_id,omitempty"`
	Label      string            `json:"label"`
	Trigger    CheckpointTrigger `json:"trigger"`
	JournalSeq int64             `json:"journal_seq"`
	GitRef     string            `json:"git_ref,omitempty"`
	TokensUsed *TokenSummary     `json:"tokens_used,omitempty"`
	Metadata   map[string]string `json:"metadata,omitempty"`
	CreatedAt  time.Time         `json:"created_at"`
}

Checkpoint is a thin metadata record marking a point in a RunLedger journal. It does NOT contain snapshot data — restoration replays the journal up to JournalSeq.

func SortedCheckpoints

func SortedCheckpoints(items []Checkpoint) []Checkpoint

SortedCheckpoints returns a copy ordered by created_at ascending for canonical bundles.

type CheckpointService

type CheckpointService struct {
	// contains filtered or unexported fields
}

CheckpointService manages checkpoint creation and lifecycle.

func NewCheckpointService

func NewCheckpointService(store CheckpointStore, ledger runledger.RunLedgerStore, cfg config.CheckpointConfig) *CheckpointService

NewCheckpointService creates a new checkpoint service.

func (*CheckpointService) CreateManual

func (s *CheckpointService) CreateManual(ctx context.Context, sessionKey, runID, label string) (*Checkpoint, error)

CreateManual creates a manually-triggered checkpoint.

func (*CheckpointService) CreateManualWithMetadata

func (s *CheckpointService) CreateManualWithMetadata(
	ctx context.Context, sessionKey, runID, label string,
	metadata map[string]string,
) (*Checkpoint, error)

CreateManualWithMetadata creates a manually-triggered checkpoint with metadata. Unlike CreateManual, runID is optional — session-init checkpoints may not have a run.

func (*CheckpointService) OnJournalEvent

func (s *CheckpointService) OnJournalEvent(event runledger.JournalEvent)

OnJournalEvent is the append hook callback for automatic checkpoint creation. It checks whether the event type warrants a checkpoint based on config.

type CheckpointStore

type CheckpointStore interface {
	// SaveCheckpoint persists a new checkpoint.
	SaveCheckpoint(ctx context.Context, cp Checkpoint) error

	// GetCheckpoint returns a checkpoint by ID.
	GetCheckpoint(ctx context.Context, id string) (*Checkpoint, error)

	// ListByRun returns checkpoints for a run, ordered by journal_seq asc.
	ListByRun(ctx context.Context, runID string) ([]Checkpoint, error)

	// ListBySession returns checkpoints for a session, ordered by created_at desc.
	ListBySession(ctx context.Context, sessionKey string, limit int) ([]Checkpoint, error)

	// CountBySession returns the number of checkpoints for a session.
	CountBySession(ctx context.Context, sessionKey string) (int, error)

	// DeleteCheckpoint removes a checkpoint by ID.
	DeleteCheckpoint(ctx context.Context, id string) error
}

CheckpointStore is the persistence interface for provenance checkpoints.

type CheckpointTrigger

type CheckpointTrigger string

CheckpointTrigger identifies what caused a checkpoint to be created.

const (
	TriggerManual       CheckpointTrigger = "manual"
	TriggerStepComplete CheckpointTrigger = "step_complete"
	TriggerPolicy       CheckpointTrigger = "policy_applied"
)

type EntAttributionStore

type EntAttributionStore struct {
	// contains filtered or unexported fields
}

EntAttributionStore persists attribution rows in Ent.

func NewEntAttributionStore

func NewEntAttributionStore(client *ent.Client) *EntAttributionStore

NewEntAttributionStore creates a new Ent-backed attribution store.

func (*EntAttributionStore) ListBySession

func (s *EntAttributionStore) ListBySession(ctx context.Context, sessionKey string, limit int) ([]Attribution, error)

func (*EntAttributionStore) SaveAttribution

func (s *EntAttributionStore) SaveAttribution(ctx context.Context, attr Attribution) error

type EntCheckpointStore

type EntCheckpointStore struct {
	// contains filtered or unexported fields
}

EntCheckpointStore is an Ent-backed CheckpointStore for persistent checkpoints.

func NewEntCheckpointStore

func NewEntCheckpointStore(client *ent.Client) *EntCheckpointStore

NewEntCheckpointStore creates a new Ent-backed CheckpointStore.

func (*EntCheckpointStore) CountBySession

func (s *EntCheckpointStore) CountBySession(ctx context.Context, sessionKey string) (int, error)

func (*EntCheckpointStore) DeleteCheckpoint

func (s *EntCheckpointStore) DeleteCheckpoint(ctx context.Context, id string) error

func (*EntCheckpointStore) GetCheckpoint

func (s *EntCheckpointStore) GetCheckpoint(ctx context.Context, id string) (*Checkpoint, error)

func (*EntCheckpointStore) ListByRun

func (s *EntCheckpointStore) ListByRun(ctx context.Context, runID string) ([]Checkpoint, error)

func (*EntCheckpointStore) ListBySession

func (s *EntCheckpointStore) ListBySession(ctx context.Context, sessionKey string, limit int) ([]Checkpoint, error)

func (*EntCheckpointStore) SaveCheckpoint

func (s *EntCheckpointStore) SaveCheckpoint(ctx context.Context, cp Checkpoint) error

type EntSessionTreeStore

type EntSessionTreeStore struct {
	// contains filtered or unexported fields
}

EntSessionTreeStore persists session provenance nodes in Ent.

func NewEntSessionTreeStore

func NewEntSessionTreeStore(client *ent.Client) *EntSessionTreeStore

NewEntSessionTreeStore creates a new Ent-backed session tree store.

func (*EntSessionTreeStore) GetChildren

func (s *EntSessionTreeStore) GetChildren(ctx context.Context, parentKey string) ([]SessionNode, error)

func (*EntSessionTreeStore) GetNode

func (s *EntSessionTreeStore) GetNode(ctx context.Context, sessionKey string) (*SessionNode, error)

func (*EntSessionTreeStore) ListAll

func (s *EntSessionTreeStore) ListAll(ctx context.Context, limit int) ([]SessionNode, error)

func (*EntSessionTreeStore) SaveNode

func (s *EntSessionTreeStore) SaveNode(ctx context.Context, node SessionNode) error

func (*EntSessionTreeStore) UpdateStatus

func (s *EntSessionTreeStore) UpdateStatus(ctx context.Context, sessionKey string, status SessionStatus, closedAt *time.Time) error

type FileStats

type FileStats struct {
	LinesAdded   int `json:"lines_added"`
	LinesRemoved int `json:"lines_removed"`
	AuthorCount  int `json:"author_count"`
}

FileStats summarizes contributions to a file.

type GitFileStat

type GitFileStat struct {
	FilePath     string
	LinesAdded   int
	LinesRemoved int
}

GitFileStat describes a per-file git delta used for attribution capture.

type MemoryAttributionStore

type MemoryAttributionStore struct {
	// contains filtered or unexported fields
}

MemoryAttributionStore is an in-memory AttributionStore for tests.

func NewMemoryAttributionStore

func NewMemoryAttributionStore() *MemoryAttributionStore

NewMemoryAttributionStore creates a new in-memory attribution store.

func (*MemoryAttributionStore) ListBySession

func (s *MemoryAttributionStore) ListBySession(_ context.Context, sessionKey string, limit int) ([]Attribution, error)

func (*MemoryAttributionStore) SaveAttribution

func (s *MemoryAttributionStore) SaveAttribution(_ context.Context, attr Attribution) error

type MemoryStore

type MemoryStore struct {
	// contains filtered or unexported fields
}

MemoryStore is an in-memory CheckpointStore for testing.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore creates a new in-memory CheckpointStore.

func (*MemoryStore) CountBySession

func (s *MemoryStore) CountBySession(_ context.Context, sessionKey string) (int, error)

func (*MemoryStore) DeleteCheckpoint

func (s *MemoryStore) DeleteCheckpoint(_ context.Context, id string) error

func (*MemoryStore) GetCheckpoint

func (s *MemoryStore) GetCheckpoint(_ context.Context, id string) (*Checkpoint, error)

func (*MemoryStore) ListByRun

func (s *MemoryStore) ListByRun(_ context.Context, runID string) ([]Checkpoint, error)

func (*MemoryStore) ListBySession

func (s *MemoryStore) ListBySession(_ context.Context, sessionKey string, limit int) ([]Checkpoint, error)

func (*MemoryStore) SaveCheckpoint

func (s *MemoryStore) SaveCheckpoint(_ context.Context, cp Checkpoint) error

type MemoryTreeStore

type MemoryTreeStore struct {
	// contains filtered or unexported fields
}

MemoryTreeStore is an in-memory SessionTreeStore for testing.

func NewMemoryTreeStore

func NewMemoryTreeStore() *MemoryTreeStore

NewMemoryTreeStore creates a new in-memory session tree store.

func (*MemoryTreeStore) GetChildren

func (s *MemoryTreeStore) GetChildren(_ context.Context, parentKey string) ([]SessionNode, error)

func (*MemoryTreeStore) GetNode

func (s *MemoryTreeStore) GetNode(_ context.Context, sessionKey string) (*SessionNode, error)

func (*MemoryTreeStore) ListAll

func (s *MemoryTreeStore) ListAll(_ context.Context, limit int) ([]SessionNode, error)

func (*MemoryTreeStore) SaveNode

func (s *MemoryTreeStore) SaveNode(_ context.Context, node SessionNode) error

func (*MemoryTreeStore) UpdateStatus

func (s *MemoryTreeStore) UpdateStatus(_ context.Context, sessionKey string, status SessionStatus, closedAt *time.Time) error

type PQBundleSigner

type PQBundleSigner interface {
	SignPQ(ctx context.Context, payload []byte) ([]byte, error)
	PQAlgorithm() string
	PQPublicKey() []byte
}

PQBundleSigner is an optional interface that BundleSigners can implement to provide ML-DSA-65 post-quantum dual signatures.

type ProvenanceBundle

type ProvenanceBundle struct {
	Version              string             `json:"version"`
	Checkpoints          []Checkpoint       `json:"checkpoints"`
	SessionTree          []SessionNode      `json:"session_tree,omitempty"`
	Attributions         []Attribution      `json:"attributions,omitempty"`
	Report               *AttributionReport `json:"report,omitempty"`
	SignerDID            string             `json:"signer_did,omitempty"`
	SignatureAlgorithm   string             `json:"signature_algorithm,omitempty"`
	Signature            []byte             `json:"signature,omitempty"`
	PQSignerPublicKey    []byte             `json:"pq_signer_public_key,omitempty"` // embedded ML-DSA-65 pubkey for rotation-safe verification
	PQSignatureAlgorithm string             `json:"pq_signature_algorithm,omitempty"`
	PQSignature          []byte             `json:"pq_signature,omitempty"`
	RedactionLevel       RedactionLevel     `json:"redaction_level"`
}

ProvenanceBundle is the portable container for provenance data.

type RedactionLevel

type RedactionLevel string

RedactionLevel controls how much detail is exposed in provenance bundles.

const (
	RedactionNone    RedactionLevel = "none"
	RedactionContent RedactionLevel = "content"
	RedactionFull    RedactionLevel = "full"
)

func (RedactionLevel) Valid

func (r RedactionLevel) Valid() bool

Valid reports whether r is a recognised redaction level.

type SessionNode

type SessionNode struct {
	SessionKey  string        `json:"session_key"`
	ParentKey   string        `json:"parent_key,omitempty"`
	AgentName   string        `json:"agent_name"`
	Goal        string        `json:"goal,omitempty"`
	RunID       string        `json:"run_id,omitempty"`
	WorkspaceID string        `json:"workspace_id,omitempty"`
	Depth       int           `json:"depth"`
	Status      SessionStatus `json:"status"`
	CreatedAt   time.Time     `json:"created_at"`
	ClosedAt    *time.Time    `json:"closed_at,omitempty"`
}

SessionNode represents a node in the session tree hierarchy.

func SortedSessionNodes

func SortedSessionNodes(items []SessionNode) []SessionNode

SortedSessionNodes returns a copy ordered by depth, then created_at, then session key.

type SessionStatus

type SessionStatus string

SessionStatus is the lifecycle status of a session node in the session tree.

const (
	SessionStatusActive    SessionStatus = "active"
	SessionStatusMerged    SessionStatus = "merged"
	SessionStatusDiscarded SessionStatus = "discarded"
	SessionStatusCompleted SessionStatus = "completed"
)

type SessionTree

type SessionTree struct {
	// contains filtered or unexported fields
}

SessionTree manages session hierarchy registration and queries.

func NewSessionTree

func NewSessionTree(store SessionTreeStore) *SessionTree

NewSessionTree creates a new session tree manager.

func (*SessionTree) CloseSession

func (t *SessionTree) CloseSession(ctx context.Context, sessionKey string, status SessionStatus) error

CloseSession marks a session as completed, merged, or discarded.

func (*SessionTree) GetNode

func (t *SessionTree) GetNode(ctx context.Context, sessionKey string) (*SessionNode, error)

GetNode retrieves a session node by key.

func (*SessionTree) GetTree

func (t *SessionTree) GetTree(ctx context.Context, rootKey string, maxDepth int) ([]SessionNode, error)

GetTree returns the subtree rooted at the given session, up to maxDepth levels.

func (*SessionTree) RegisterSession

func (t *SessionTree) RegisterSession(ctx context.Context, sessionKey, parentKey, agentName, goal string) (*SessionNode, error)

RegisterSession creates a new node in the session tree.

type SessionTreeStore

type SessionTreeStore interface {
	// SaveNode persists a session node.
	SaveNode(ctx context.Context, node SessionNode) error

	// GetNode returns a node by session key.
	GetNode(ctx context.Context, sessionKey string) (*SessionNode, error)

	// GetChildren returns direct children of a session.
	GetChildren(ctx context.Context, parentKey string) ([]SessionNode, error)

	// ListAll returns all session nodes, ordered by created_at desc.
	ListAll(ctx context.Context, limit int) ([]SessionNode, error)

	// UpdateStatus updates the status and optional closed_at of a node.
	UpdateStatus(ctx context.Context, sessionKey string, status SessionStatus, closedAt *time.Time) error
}

SessionTreeStore is the persistence interface for session tree nodes.

type SignatureVerifyFunc

type SignatureVerifyFunc func(signerDID string, payload, signature []byte) error

SignatureVerifyFunc verifies a signature against a signer DID. Implementations are injected at the app/cli wiring layer.

type TokenSummary

type TokenSummary struct {
	InputTokens  int64 `json:"input_tokens"`
	OutputTokens int64 `json:"output_tokens"`
	TotalTokens  int64 `json:"total_tokens"`
}

TokenSummary aggregates token usage across a session or checkpoint.

type TokenUsageReader

type TokenUsageReader interface {
	QueryBySession(ctx context.Context, sessionKey string) ([]observability.TokenUsage, error)
}

TokenUsageReader reads persisted token usage records.

Jump to

Keyboard shortcuts

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