refinement

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package refinement defines backend-neutral continual-refinement plans, append-only audit records, and an approval-aware workflow over authoritative resource editors. Task lifecycle and distributed recovery remain host-owned.

Index

Constants

View Source
const (
	DefaultQueryLimit       = 20
	MaxQueryLimit           = 100
	MaxQueryCursorBytes     = 8 << 10
	MaxQueryTextBytes       = 200
	MaxQueryRefinementBytes = 200
)
View Source
const (
	PhaseProposal    Phase = "proposal"
	PhaseDecision    Phase = "decision"
	PhaseApplication Phase = "application"
	PhaseRollback    Phase = "rollback"

	ScopeSession   Scope = "session"
	ScopeWorkspace Scope = "workspace"
	ScopeUser      Scope = "user"
	ScopeTenant    Scope = "tenant"
	ScopeGlobal    Scope = "global"

	OutcomeProposed         Outcome = "proposed"
	OutcomeApproved         Outcome = "approved"
	OutcomeRejected         Outcome = "rejected"
	OutcomeApplied          Outcome = "applied"
	OutcomePartiallyApplied Outcome = "partially_applied"
	OutcomeFailed           Outcome = "failed"
	OutcomeRolledBack       Outcome = "rolled_back"
	OutcomeNoOp             Outcome = "no_op"

	ResourcePromptNote         ResourceKind = "prompt_note"
	ResourceMemory             ResourceKind = "memory"
	ResourceSkill              ResourceKind = "skill"
	ResourceAgentSpecification ResourceKind = "agent_specification"

	ActionCreate  Action = "create"
	ActionReplace Action = "replace"
	ActionDelete  Action = "delete"
	ActionRestore Action = "restore"

	EvidenceMessage          EvidenceKind = "message"
	EvidenceToolResult       EvidenceKind = "tool_result"
	EvidenceResourceRevision EvidenceKind = "resource_revision"
	EvidenceEvaluation       EvidenceKind = "evaluation"
	EvidenceUserInstruction  EvidenceKind = "user_instruction"
	EvidenceOther            EvidenceKind = "other"
)
View Source
const (
	ProposeToolName      = "propose_refinement"
	ApplyToolName        = "apply_refinement"
	PlanRollbackToolName = "plan_refinement_rollback"
	GetRecordToolName    = "get_refinement_record"
	QueryRecordsToolName = "query_refinement_records"
)

Variables

View Source
var (
	ErrInvalid  = errors.New("refinement: invalid record")
	ErrConflict = errors.New("refinement: conflict")
	ErrNotFound = errors.New("refinement: record not found")
)
View Source
var (
	ErrApprovalRequired    = errors.New("refinement: explicit approval required")
	ErrApprovalRejected    = errors.New("refinement: approval rejected")
	ErrUnsupportedResource = errors.New("refinement: unsupported resource authority")
)

Functions

func RegisterTools

func RegisterTools(registry *tools.Registry, service *Service) error

func ValidateQueryCursor

func ValidateQueryCursor(cursor string) error

Types

type Action

type Action string

type AppendRequest

type AppendRequest struct {
	Key string `json:"key"`
	Plan
	Phase              Phase              `json:"phase"`
	Outcome            Outcome            `json:"outcome"`
	ParentRecordID     string             `json:"parent_record_id,omitempty"`
	RollbackOfRecordID string             `json:"rollback_of_record_id,omitempty"`
	TaskRef            *ExternalReference `json:"task_ref,omitempty"`
	ApprovalRef        *ExternalReference `json:"approval_ref,omitempty"`
	SchemaVersion      int                `json:"schema_version,omitempty"`
	Metadata           map[string]any     `json:"metadata,omitempty"`
}

AppendRequest creates one immutable audit record. Later decisions, applications, corrections, and rollbacks are separate linked records.

func (AppendRequest) Validate

func (r AppendRequest) Validate() error

type AppendResult

type AppendResult struct {
	Record   Record
	Replayed bool
}

type ApplyRequest

type ApplyRequest struct {
	OperationID      string
	ProposalRecordID string
	Approval         Approval
}

type ApplyResult

type ApplyResult struct {
	Assessment  Assessment `json:"assessment"`
	Decision    Record     `json:"decision"`
	Application *Record    `json:"application,omitempty"`
}

type Approval

type Approval struct {
	Granted   bool
	Reference *ExternalReference
}

type Assessment

type Assessment struct {
	Risk             RiskLevel `json:"risk"`
	RequiresApproval bool      `json:"requires_approval"`
	Reasons          []string  `json:"reasons"`
}

func Assess

func Assess(plan Plan, policy Policy) Assessment

type AuditAuthorizer

type AuditAuthorizer interface {
	AuthorizeRefinementAudit(context.Context, protocol.MessageAddress, protocol.ChatMessage) error
}

AuditAuthorizer is an optional composition policy before operator-command audit reads. The MemoryLayer authority still enforces its own workspace ACL under the OBO context; this seam covers enterprise command exposure policy.

type Edit

type Edit struct {
	Action       Action       `json:"action"`
	ResourceKind ResourceKind `json:"resource_kind"`
	ResourceKey  string       `json:"resource_key"`
	ResourceID   string       `json:"resource_id,omitempty"`
	ExpectedETag string       `json:"expected_etag,omitempty"`
	BeforeETag   string       `json:"before_etag,omitempty"`
	AfterETag    string       `json:"after_etag,omitempty"`
	Reason       string       `json:"reason"`
	// Content is the desired authority-neutral resource document for create and
	// replace actions. Delete and restore actions leave it empty; restore asks
	// the authority to reactivate the exact tombstoned head.
	Content map[string]any    `json:"content,omitempty"`
	Before  *ResourceSnapshot `json:"before,omitempty"`
	After   *ResourceSnapshot `json:"after,omitempty"`
	Applied *bool             `json:"applied,omitempty"`
	Error   string            `json:"error,omitempty"`
}

type Evidence

type Evidence struct {
	Kind        EvidenceKind `json:"kind"`
	Reference   string       `json:"reference"`
	Description string       `json:"description"`
	ContentHash string       `json:"content_hash,omitempty"`
}

type EvidenceKind

type EvidenceKind string

type ExternalReference

type ExternalReference struct {
	System    string `json:"system"`
	ID        string `json:"id"`
	AttemptID string `json:"attempt_id,omitempty"`
}

ExternalReference correlates an audit record to an execution-plane object such as an Aether task or approval without copying its live state.

type FileStore

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

func NewFileStore

func NewFileStore(stateDir string, now func() time.Time) (*FileStore, error)

func (*FileStore) Append

func (s *FileStore) Append(ctx context.Context, workspaceID, operationID string, request AppendRequest) (AppendResult, error)

func (*FileStore) Get

func (s *FileStore) Get(ctx context.Context, workspaceID, recordID string) (Record, error)

func (*FileStore) Path

func (s *FileStore) Path(workspaceID string) string

func (*FileStore) Query

func (s *FileStore) Query(ctx context.Context, workspaceID string, query Query) (Page, error)

type Mutation

type Mutation struct {
	Before   *ResourceSnapshot `json:"before,omitempty"`
	After    *ResourceSnapshot `json:"after,omitempty"`
	Replayed bool              `json:"replayed,omitempty"`
}

Mutation is the authoritative result of exactly one edit. Editors must make operationID idempotent: replaying it with the same edit returns the same result, while replaying it with different input returns ErrConflict.

type Outcome

type Outcome string

type Page

type Page struct {
	Records       []Record `json:"records"`
	NextPageToken string   `json:"next_page_token,omitempty"`
	ScannedCount  int      `json:"scanned_count"`
	ScanTruncated bool     `json:"scan_truncated,omitempty"`
}

Page is one bounded authority page. ScannedCount can exceed len(Records) when filters are sparse. ScanTruncated means the backend hit its bounded scan ceiling before filling the page; NextPageToken continues from the last record inspected without repeating the scan.

type Phase

type Phase string

type Plan

type Plan struct {
	RefinementID    string     `json:"refinement_id"`
	Trigger         string     `json:"trigger"`
	Scope           Scope      `json:"scope"`
	Summary         string     `json:"summary"`
	Rationale       string     `json:"rationale"`
	ExpectedOutcome string     `json:"expected_outcome"`
	Evidence        []Evidence `json:"evidence"`
	Edits           []Edit     `json:"edits"`
}

Plan is the evidence-backed semantic proposal shared by proposal and outcome records. Before/after ETags live on edits so applications are auditable.

func BuildRollbackPlan

func BuildRollbackPlan(application Record, refinementID string) (Plan, error)

BuildRollbackPlan deterministically reverses the applied subset in reverse order. Its ETag preconditions target the exact revisions created by the application, so later user changes cause a conflict rather than being lost.

type Policy

type Policy struct {
	AllowSessionLowRiskWithoutApproval bool
}

Policy is intentionally conservative by default. Only a session-scoped, low-risk proposal can ever bypass explicit approval, and only when a host opts in.

type ProposalResult

type ProposalResult struct {
	Record     Record     `json:"record"`
	Assessment Assessment `json:"assessment"`
	Replayed   bool       `json:"replayed"`
}

type ProposeRequest

type ProposeRequest struct {
	OperationID        string
	Key                string
	Plan               Plan
	RollbackOfRecordID string
	TaskRef            *ExternalReference
	Metadata           map[string]any
}

type Query

type Query struct {
	Phases        []Phase        `json:"phases,omitempty"`
	Outcomes      []Outcome      `json:"outcomes,omitempty"`
	Scopes        []Scope        `json:"scopes,omitempty"`
	ResourceKinds []ResourceKind `json:"resource_kinds,omitempty"`
	RefinementID  string         `json:"refinement_id,omitempty"`
	Text          string         `json:"text,omitempty"`
	Limit         int            `json:"limit,omitempty"`
	PageToken     string         `json:"page_token,omitempty"`
}

Query selects one newest-first page from the configured refinement audit authority. Values within one filter are ORed; distinct filters are ANDed. PageToken is authority-owned and opaque to callers.

func NormalizeQuery

func NormalizeQuery(query Query) (Query, error)

NormalizeQuery validates and canonicalizes a query before it reaches a backend. Canonical filter ordering makes opaque cursor scopes deterministic.

type Record

type Record struct {
	ID          string `json:"id"`
	WorkspaceID string `json:"workspace_id"`
	AppendRequest
	Revision  int    `json:"revision"`
	ETag      string `json:"etag"`
	CreatedAt string `json:"created_at"`
}

Record is the immutable, authority-neutral audit projection.

type ResourceEditor

type ResourceEditor interface {
	Apply(ctx context.Context, workspaceID, operationID string, edit Edit) (Mutation, error)
}

func BindResourceEditor

func BindResourceEditor(base ResourceEditor, logicalWorkspace, backendWorkspaceID string) ResourceEditor

type ResourceKind

type ResourceKind string

type ResourceSnapshot

type ResourceSnapshot struct {
	ResourceID    string         `json:"resource_id,omitempty"`
	ResourceKey   string         `json:"resource_key"`
	ETag          string         `json:"etag,omitempty"`
	SchemaVersion int            `json:"schema_version,omitempty"`
	Content       map[string]any `json:"content,omitempty"`
	Metadata      map[string]any `json:"metadata,omitempty"`
	Deleted       bool           `json:"deleted,omitempty"`
}

ResourceSnapshot captures the authority response before or after a mutation. Content is the authority-neutral resource document used to plan a safe rollback; secrets and other non-resource execution state must not be placed here.

type RiskLevel

type RiskLevel string
const (
	RiskLow    RiskLevel = "low"
	RiskMedium RiskLevel = "medium"
	RiskHigh   RiskLevel = "high"
)

type Scope

type Scope string

type Service

type Service struct {
	Store           Store
	Editors         map[ResourceKind]ResourceEditor
	Policy          Policy
	AuditAuthority  string
	AuditAuthorizer AuditAuthorizer
}

Service coordinates immutable audit transitions around resource editors. It does not own a distributed task lifecycle: TaskRef and approval references point at Aether (or another execution authority) when one is present.

func (*Service) Apply

func (s *Service) Apply(ctx context.Context, workspaceID string, request ApplyRequest) (ApplyResult, error)

func (*Service) Propose

func (s *Service) Propose(ctx context.Context, workspaceID string, request ProposeRequest) (ProposalResult, error)

func (*Service) RunRefinementAuditCommand

func (s *Service) RunRefinementAuditCommand(
	ctx context.Context,
	addr protocol.MessageAddress,
	user protocol.ChatMessage,
	args string,
) (string, error)

RunRefinementAuditCommand implements turn's optional command provider without coupling the neutral turn package to refinement storage or rendering.

type Store

type Store interface {
	Append(ctx context.Context, workspaceID, operationID string, request AppendRequest) (AppendResult, error)
	Get(ctx context.Context, workspaceID, recordID string) (Record, error)
	// Query returns one bounded newest-first authority page.
	Query(ctx context.Context, workspaceID string, query Query) (Page, error)
}

Store is an append-only, workspace-aware refinement audit. It never applies edits or represents an execution task's live lifecycle.

func BindStore

func BindStore(base Store, logicalWorkspace, backendWorkspaceID string) Store

BindStore maps the process-selected logical workspace to an authority's configured workspace while preserving explicitly addressed other workspaces.

Jump to

Keyboard shortcuts

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