executor

package
v0.0.0-...-e1638d3 Latest Latest
Warning

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

Go to latest
Published: May 13, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package executor provides EvidencePack production. Per Section 6 - EvidencePack Normative Contract

Package executor provides Visual Evidence Verification. Inspired by Kimi K2.5's visual debugging and reasoning verification.

Package executor provides Merkle tree construction for EvidencePack. Per HELM Normative Addendum v1.5 Section C - EvidencePack Merkle Construction.

Index

Constants

View Source
const MerkleProfileID = "merkle-v1"

MerkleProfileID is the profile identifier for Merkle-v1.

Variables

View Source
var LeafDomainSeparator = []byte{0x00}

LeafDomainSeparator is the prefix for leaf hashes. Per Section C.2: leaf_hash = sha256(0x00 || leaf_canonical_bytes)

View Source
var NodeDomainSeparator = []byte{0x01}

NodeDomainSeparator is the prefix for internal node hashes. Per Section C.3: node_hash = sha256(0x01 || left_hash || right_hash)

Functions

func DecodeScreenshot

func DecodeScreenshot(encoded string) ([]byte, error)

DecodeScreenshot decodes base64 screenshot data.

func EncodeScreenshot

func EncodeScreenshot(data []byte) string

EncodeScreenshot encodes binary data as base64 for snapshot storage.

func ValidateEvidencePack

func ValidateEvidencePack(pack *contracts.EvidencePack) []string

ValidateEvidencePack validates an EvidencePack for completeness.

func VerifyProof

func VerifyProof(proof *MerkleProof) (bool, error)

VerifyProof verifies a Merkle inclusion proof. Per Section C.6: Proof verification algorithm.

func VerifyView

func VerifyView(view *EvidenceView) (bool, error)

VerifyView verifies an EvidenceView.

Types

type Annotation

type Annotation struct {
	AnnotationID string `json:"annotation_id"`
	Type         string `json:"type"` // "highlight", "arrow", "bbox", "text"
	Target       string `json:"target"`
	Description  string `json:"description"`
	Severity     string `json:"severity,omitempty"` // "info", "warning", "error"
}

Annotation marks a region or value in a snapshot.

type CompilerPolicy

type CompilerPolicy interface {
	GetProhibitedTools() []string
}

Match interfaces for compiler output

type EvidencePackInput

type EvidencePackInput struct {
	// Actor information
	ActorID         string
	ActorType       string
	SessionID       string
	DelegationChain []string

	// Policy decision
	DecisionID          string
	PolicyVersion       string
	RulesFired          []string
	EvaluationGraphHash string

	// Effect details
	EffectID          string
	EffectType        string
	EffectPayloadHash string
	IdempotencyKey    string
	Classification    string

	// Context
	ModeID             string
	LoopID             string
	Jurisdiction       string
	PhenotypeHash      string
	OrchestrationRunID string
	PhaseID            string
	CheckpointRef      string
	CritiqueRef        string
	HeuristicTraceID   string

	// Execution
	ResultHash    string
	Status        string
	RetryCount    int
	StartedAt     time.Time
	CompletedAt   time.Time
	FailureReason string

	// Receipts
	PALReceipts      []contracts.PALReceiptRef
	ExternalReceipts []contracts.ExternalReceiptRef

	// New Receipt Fields support in Input
	ReplayScript     *contracts.ReplayScriptRef
	Provenance       *contracts.ReceiptProvenance
	BundledArtifacts []contracts.ParsedArtifact

	// Reconciliation
	OutboxID       string
	DeniedAttempts []contracts.DeniedAttemptRecord
	FailedAttempts []contracts.FailedAttemptRecord
}

EvidencePackInput contains all inputs needed to produce an EvidencePack.

type EvidencePackProducer

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

EvidencePackProducer creates EvidencePacks for effect executions.

func NewEvidencePackProducer

func NewEvidencePackProducer(kernelVersion string) *EvidencePackProducer

NewEvidencePackProducer creates a new evidence pack producer.

func (*EvidencePackProducer) Produce

Produce creates an EvidencePack from the input.

type EvidenceView

type EvidenceView struct {
	// ViewID uniquely identifies this view.
	ViewID string `json:"view_id"`

	// PackID references the source EvidencePack.
	PackID string `json:"pack_id"`

	// RootHash is the Merkle root of the full pack.
	RootHash string `json:"root_hash"`

	// IncludedPaths lists the paths included in this view.
	IncludedPaths []string `json:"included_paths"`

	// Proofs contains inclusion proofs for included leaves.
	Proofs []MerkleProof `json:"proofs"`

	// Data contains the actual data for included paths.
	Data map[string]any `json:"data"`
}

EvidenceView represents a derived view of an EvidencePack. Per Section C.9: EvidenceView derivation.

type Executor

type Executor interface {
	Execute(ctx context.Context, effect *contracts.Effect, decision *contracts.DecisionRecord, intent *contracts.AuthorizedExecutionIntent) (*contracts.Receipt, *interfaces.Artifact, error)
}

Executor runs an effect if and only if it has a valid, notarized decision AND an execution intent.

type MCPClient

type MCPClient interface {
	Call(tool string, params map[string]any) (any, error)
}

MCPClient defines the interface for interacting with the Managed Capability Platform. Kept for backward compatibility if needed, but ToolDriver is preferred.

type MCPDriver

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

MCPDriver executes tools via the Model Context Protocol.

func NewMCPDriver

func NewMCPDriver(client interface {
	Call(tool string, params map[string]any) (any, error)
}) *MCPDriver

func (*MCPDriver) Execute

func (m *MCPDriver) Execute(ctx context.Context, toolName string, params map[string]any) (any, error)

type MerkleBuilder

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

MerkleBuilder builds a Merkle tree from evidence components.

func NewMerkleBuilder

func NewMerkleBuilder() *MerkleBuilder

NewMerkleBuilder creates a new Merkle builder.

func (*MerkleBuilder) AddLeaf

func (b *MerkleBuilder) AddLeaf(path string, value any, sealed bool) error

AddLeaf adds a leaf to the tree. Per Section C.2: Leaf derivation from canonical JSON.

func (*MerkleBuilder) AddLeafBytes

func (b *MerkleBuilder) AddLeafBytes(path string, data []byte, sealed bool)

AddLeafBytes adds a leaf from raw bytes.

func (*MerkleBuilder) Build

func (b *MerkleBuilder) Build() (*MerkleTree, error)

Build constructs the Merkle tree and returns the root. Per Section C.4: Tree construction algorithm.

type MerkleLeaf

type MerkleLeaf struct {
	Index    int    `json:"index"`
	Path     string `json:"path"` // JSON pointer path
	Hash     []byte `json:"hash"`
	Sealed   bool   `json:"sealed"` // Per Section C.8: Sealed leaves
	SealedAt int64  `json:"sealed_at,omitempty"`
}

MerkleLeaf represents a leaf in the Merkle tree.

type MerkleProof

type MerkleProof struct {
	LeafIndex int             `json:"leaf_index"`
	LeafPath  string          `json:"leaf_path"`
	LeafHash  string          `json:"leaf_hash"`
	Siblings  []MerkleSibling `json:"siblings"`
	Root      string          `json:"root"`
}

MerkleProof represents an inclusion proof. Per Section C.5: Inclusion proof structure.

type MerkleSibling

type MerkleSibling struct {
	Hash     string `json:"hash"`
	Position string `json:"position"` // "left" or "right"
}

MerkleSibling represents a sibling in the proof path.

type MerkleTree

type MerkleTree struct {
	// Root is the root hash of the tree.
	Root []byte `json:"root"`

	// Leaves contains the original data and their hashes.
	Leaves []MerkleLeaf `json:"leaves"`

	// Levels contains all tree levels for proof generation.
	// Level 0 is leaves, last level is root.
	Levels [][][]byte `json:"-"`
}

MerkleTree represents a complete Merkle tree.

func (*MerkleTree) DeriveView

func (t *MerkleTree) DeriveView(viewID, packID string, paths []string, getData func(path string) (any, error)) (*EvidenceView, error)

DeriveView creates an EvidenceView with only specified paths. Per Section C.9: View derivation for minimal disclosure.

func (*MerkleTree) GenerateProof

func (t *MerkleTree) GenerateProof(leafIndex int) (*MerkleProof, error)

GenerateProof generates an inclusion proof for a leaf. Per Section C.5: Proof generation algorithm.

func (*MerkleTree) RootHex

func (t *MerkleTree) RootHex() string

RootHex returns the root hash as a hex string.

type OutboxRecord

type OutboxRecord struct {
	ID        string                               `json:"id"`
	Effect    *contracts.Effect                    `json:"effect"`
	Intent    *contracts.AuthorizedExecutionIntent `json:"intent"`
	Scheduled time.Time                            `json:"scheduled"`
	Status    string                               `json:"status"` // PENDING, DONE, FAILED
}

OutboxRecord represents an intent to execute an effect.

type OutboxStore

type OutboxStore interface {
	// Schedule persists the intent to execute.
	Schedule(ctx context.Context, effect *contracts.Effect, intent *contracts.AuthorizedExecutionIntent) error
	// GetPending returns all scheduled but not yet executed records.
	GetPending(ctx context.Context) ([]*OutboxRecord, error)
	// MarkDone marks a record as executed (idempotency key).
	MarkDone(ctx context.Context, id string) error
}

OutboxStore defines the transactional persistence layer for effects.

type OutputSchemaRegistry

type OutputSchemaRegistry interface {
	LookupOutput(toolName string) *manifest.ToolOutputSchema
}

OutputSchemaRegistry provides tool output schemas for drift detection.

type PackExporter

type PackExporter interface {
	ExportChangePack(ctx context.Context, input *contracts.ChangePack) (*contracts.ChangePack, error)
	ExportIncidentPack(ctx context.Context, input *contracts.IncidentPack) (*contracts.IncidentPack, error)
	ExportAccessReviewPack(ctx context.Context, input *contracts.AccessReviewPack) (*contracts.AccessReviewPack, error)
	ExportVendorDueDiligencePack(ctx context.Context, input *contracts.VendorDueDiligencePack) (*contracts.VendorDueDiligencePack, error)
}

PackExporter defines the interface for generating and signing proof packs.

func NewPackExporter

func NewPackExporter(signerID string, signer crypto.Signer) PackExporter

NewPackExporter creates a new PackExporter with a real cryptographic signer. The signer MUST implement crypto.Signer (e.g. Ed25519Signer).

type ReasoningChain

type ReasoningChain struct {
	ChainID      string          `json:"chain_id"`
	PackID       string          `json:"pack_id"`
	Steps        []ReasoningStep `json:"steps"`
	FinalOutcome string          `json:"final_outcome"`
	ChainHash    string          `json:"chain_hash"`
	Verified     bool            `json:"verified"`
	VerifiedAt   time.Time       `json:"verified_at,omitempty"`
}

ReasoningChain represents the causal reasoning for a decision.

type ReasoningStep

type ReasoningStep struct {
	StepID         string    `json:"step_id"`
	SequenceNum    int       `json:"sequence_num"`
	Action         string    `json:"action"`
	Rationale      string    `json:"rationale"`
	InputRefs      []string  `json:"input_refs,omitempty"`  // References to evidence
	OutputRefs     []string  `json:"output_refs,omitempty"` // References to outputs
	SnapshotBefore string    `json:"snapshot_before,omitempty"`
	SnapshotAfter  string    `json:"snapshot_after,omitempty"`
	Confidence     float64   `json:"confidence,omitempty"` // 0.0-1.0
	Timestamp      time.Time `json:"timestamp"`
	DurationMs     int64     `json:"duration_ms,omitempty"`
}

ReasoningStep represents a step in the causal chain.

type ReceiptStore

type ReceiptStore interface {
	Get(ctx context.Context, decisionID string) (*contracts.Receipt, error)
	Store(ctx context.Context, receipt *contracts.Receipt) error
	// GetLastForSession returns the most recent receipt for a given session (for causal DAG chaining).
	GetLastForSession(ctx context.Context, sessionID string) (*contracts.Receipt, error)
}

ReceiptStore defines the interface for persisting execution receipts.

type SafeExecutor

type SafeExecutor struct {
	AuditLog crypto.AuditLog
	// contains filtered or unexported fields
}

SafeExecutor enforces strict gating and authorized execution. Per Section 1.4: Receipt policy enforcement is fail-closed. Per KERNEL_TCB §3: uses injected authority clock, never wall-clock time.Now().

func NewSafeExecutor

func NewSafeExecutor(verifier crypto.Verifier, signer crypto.Signer, driver ToolDriver, store ReceiptStore, artStore artifacts.Store, outbox OutboxStore, phenotypeHash string, auditLog crypto.AuditLog, meter UsageMeter, outputRegistry OutputSchemaRegistry, clock func() time.Time) *SafeExecutor

NewSafeExecutor creates a new SafeExecutor. Uses an injected authority clock (KERNEL_TCB §3).

func (*SafeExecutor) ApplyCompilerPolicy

func (e *SafeExecutor) ApplyCompilerPolicy(policy CompilerPolicy)

ApplyCompilerPolicy updates the internal policy enforcer with constraints mainly from the Compiler. This allows dynamic regulation to be injected into the SafeExecutor.

func (*SafeExecutor) Execute

Execute returns the Receipt (proof) and the Tool Result (Artifact), or error.

func (*SafeExecutor) WithClock

func (e *SafeExecutor) WithClock(clock func() time.Time) *SafeExecutor

WithClock overrides the clock for deterministic testing and production authority clock injection. Per KERNEL_TCB §3: the kernel MUST NOT use wall-clock time.Now().

type SnapshotDiff

type SnapshotDiff struct {
	PreviousSnapshotID string   `json:"previous_snapshot_id"`
	AddedPaths         []string `json:"added_paths,omitempty"`
	RemovedPaths       []string `json:"removed_paths,omitempty"`
	ModifiedPaths      []string `json:"modified_paths,omitempty"`
	DiffHash           string   `json:"diff_hash"`
}

SnapshotDiff captures changes between snapshots.

type ToolDriver

type ToolDriver interface {
	// Execute performs the capability action with the given payload.
	Execute(ctx context.Context, toolName string, params map[string]any) (any, error)
}

ToolDriver abstracts the actual execution of an effect. This allows the Executor to support both Native (Go code) and MCP (Remote) tools.

type UsageEvent

type UsageEvent struct {
	TenantID  string         `json:"tenant_id"`
	EventType string         `json:"event_type"`
	Quantity  int64          `json:"quantity"`
	Timestamp time.Time      `json:"timestamp"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

UsageEvent represents an execution usage event for optional metering.

type UsageMeter

type UsageMeter interface {
	Record(ctx context.Context, event UsageEvent) error
}

UsageMeter is an optional interface for recording execution usage events. Implementations may be injected for commercial metering; the canonical standard operates correctly with a nil meter.

type VerificationError

type VerificationError struct {
	CheckID     string `json:"check_id"`
	Type        string `json:"type"` // "missing_snapshot", "broken_chain", "hash_mismatch"
	Description string `json:"description"`
	Severity    string `json:"severity"` // "error", "warning"
}

VerificationError describes a failed verification check.

type VerificationResult

type VerificationResult struct {
	Verified        bool                `json:"verified"`
	VerificationID  string              `json:"verification_id"`
	ChecksPassed    []string            `json:"checks_passed"`
	ChecksFailed    []VerificationError `json:"checks_failed,omitempty"`
	CausalIntegrity bool                `json:"causal_integrity"`
	Timestamp       time.Time           `json:"timestamp"`
}

VerificationResult contains the outcome of visual verification.

type VisualEvidence

type VisualEvidence struct {
	Pack           *contracts.EvidencePack `json:"pack"`
	Snapshots      []VisualSnapshot        `json:"snapshots"`
	ReasoningChain *ReasoningChain         `json:"reasoning_chain,omitempty"`
	VisualHash     string                  `json:"visual_hash"`
	CreatedAt      time.Time               `json:"created_at"`
}

VisualEvidence extends EvidencePack with visual verification.

type VisualEvidenceConfig

type VisualEvidenceConfig struct {
	// MaxSnapshotsPerPack limits snapshots per evidence pack
	MaxSnapshotsPerPack int `json:"max_snapshots_per_pack"`

	// EnableDiffTracking tracks differences between snapshots
	EnableDiffTracking bool `json:"enable_diff_tracking"`

	// VerifyReasoningChain validates causal reasoning
	VerifyReasoningChain bool `json:"verify_reasoning_chain"`

	// MaxReasoningSteps limits reasoning chain depth
	MaxReasoningSteps int `json:"max_reasoning_steps"`
}

VisualEvidenceConfig configures the visual evidence verifier.

func DefaultVisualEvidenceConfig

func DefaultVisualEvidenceConfig() *VisualEvidenceConfig

DefaultVisualEvidenceConfig returns production defaults.

type VisualEvidenceVerifier

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

VisualEvidenceVerifier provides K2.5-style visual evidence verification.

func NewVisualEvidenceVerifier

func NewVisualEvidenceVerifier(config *VisualEvidenceConfig) *VisualEvidenceVerifier

NewVisualEvidenceVerifier creates a new visual verifier.

func (*VisualEvidenceVerifier) AttachReasoningChain

func (v *VisualEvidenceVerifier) AttachReasoningChain(evidence *VisualEvidence, steps []ReasoningStep) (*ReasoningChain, error)

AttachReasoningChain adds a reasoning chain to visual evidence.

func (*VisualEvidenceVerifier) CreateVisualEvidence

func (v *VisualEvidenceVerifier) CreateVisualEvidence(pack *contracts.EvidencePack, snapshots []VisualSnapshot) (*VisualEvidence, error)

CreateVisualEvidence wraps an EvidencePack with visual evidence.

func (*VisualEvidenceVerifier) GetMetrics

GetMetrics returns verification statistics.

func (*VisualEvidenceVerifier) Verify

Verify performs comprehensive visual verification.

type VisualSnapshot

type VisualSnapshot struct {
	SnapshotID   string                 `json:"snapshot_id"`
	Timestamp    time.Time              `json:"timestamp"`
	SequenceNum  int                    `json:"sequence_num"`
	ContentType  string                 `json:"content_type"` // e.g., "state", "ui", "log"
	ContentHash  string                 `json:"content_hash"`
	Content      map[string]interface{} `json:"content,omitempty"`
	Screenshot   string                 `json:"screenshot,omitempty"` // Base64 encoded
	Annotations  []Annotation           `json:"annotations,omitempty"`
	DiffFromPrev *SnapshotDiff          `json:"diff_from_prev,omitempty"`
}

VisualSnapshot represents a point-in-time visual state.

type VisualVerifierMetric

type VisualVerifierMetric struct {
	TotalVerifications      int     `json:"total_verifications"`
	SuccessfulVerifications int     `json:"successful_verifications"`
	FailedVerifications     int     `json:"failed_verifications"`
	AvgSnapshotsPerPack     float64 `json:"avg_snapshots_per_pack"`
	AvgReasoningSteps       float64 `json:"avg_reasoning_steps"`
	TotalSnapshotsProcessed int     `json:"total_snapshots_processed"`
	// contains filtered or unexported fields
}

VisualVerifierMetric tracks verification statistics.

Jump to

Keyboard shortcuts

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