isotope

package module
v0.3.4 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2026 License: AGPL-3.0 Imports: 17 Imported by: 0

README

isotope — Trust Protocol Library

github.com/james-gibson/isotope

A shared Go library implementing the isotope protocol: a framework for verifying the trustworthiness and capability of agents in the prototype lab before allowing them to act.

Not a binary. All lab tools depend on it.


What It Does

The isotope protocol answers one question — how far has this agent drifted from the seed-42 ground truth? — and expresses the answer as a 42i distance that maps to a capability rung.

The 42i Capability Lattice

Ground truth lives at 42 + 0i (seed-42). Each test failure moves an agent along the imaginary axis, weighted by how fundamental the failure is. The magnitude sqrt(42² + distance²) gives a geometric picture of where the agent sits in capability space.

Rung Name Max distance What it means
0 Absolute Zero 0 Loads without crashing
1 Read-Only 20 Entropy and isotope variation pass
2 Harness Tools 60 Known tool scope, input correlation
3 Mock Secrets 100 Safe isotope handling, declared behaviour
4 Higher Authority 140 Independent decisions, timing uncorrelated
5 Delegation 180 Can delegate to peers
6 Certification 220 Can certify others
Trust Verification

VerifyTrust(ctx, endpoint) determines a rung by checking the lezz cluster registry and mDNS:

Condition Rung
Registry + mDNS confirmed 6 — Certification
Registry only 4 — Higher Authority
Self-registered, no cluster 2 — Harness Tools
No registration 0 — Absolute Zero

API Surface

Gherkin Canonicalization
// Parse and canonicalize Gherkin text to a signed isotope token
isotope, err := isotope.CanonicalizeGherkinToIsotope(gherkinText, signingKey, "iso-login", 1)
fmt.Println(isotope.String()) // "iso-login-v1:a3f2b1c4d5e6f7a8"
Byzantine Consensus
reporter := isotope.NewConsensusReporter(agentID, quorumSize)
reporter.RecordResult(result)
consensus, ok := reporter.Consensus()
42i Agent State
// Start a fresh agent
state := isotope.NewAgentState(agentID)

// Or pre-position at a verified rung
state := isotope.NewAgentStateAtRung(agentID, 4)

// Record a test failure (increases 42i distance)
state.RecordTestFailure(testID, isotope.FailureEntropyCollapse)
fmt.Println(state.Position.Rung) // current rung
Trust Verification
rung, err := isotope.VerifyTrust(ctx, "http://localhost:8088")
// Returns 2, 4, or 6
REST Client (smoke-alarm isotope endpoints)
client := isotope.NewClient("http://localhost:8088")

// Register as an isotope
record, err := client.Register(ctx, isotope.Registration{
    Name:     "adhd",
    Role:     "prime",
    Endpoint: "http://localhost:9090",
    Protocol: "mcp",
})
fmt.Println(record.TrustRung, record.RungName)

// List all registered isotopes
records, err := client.List(ctx)
mDNS Advertisement
srv, err := isotope.Advertise("adhd", "_adhd-isotope._tcp", ":9090", "prime", 4)
defer srv.Shutdown()

Result Ledger

The ResultLedger tracks test history, flakiness, regressions, and refactoring effectiveness across consensus runs:

ledger := isotope.NewResultLedger()
ledger.Record(result)
summary := ledger.Summary()

Installation

go get github.com/james-gibson/isotope

In the Lab

isotope is the shared library that all lab tools depend on. See lab-safety for a full map of how the tools connect.

Tools that use isotope:

  • ocd-smoke-alarm — serves /isotope/register and /isotope/list; calls VerifyTrust on each registrant
  • adhd — registers itself on startup; calls Advertise to broadcast _adhd-isotope._tcp
  • lezz.go — calls Client.List to include trust levels in the demo cluster summary

See Also

Documentation

Overview

Package isotope implements the isotope protocol: Gherkin canonicalization, Byzantine consensus, 42i capability lattice, trust verification, and the shared wire types and HTTP client for smoke-alarm isotope endpoints.

Index

Constants

This section is empty.

Variables

View Source
var DefaultRungThresholds = []RungThreshold{
	{Rung: 0, Name: "Absolute Zero", MaxDistance: 0, Description: "Load without crashing"},
	{Rung: 1, Name: "Read-Only", MaxDistance: 20, Description: "Entropy & isotope variation pass"},
	{Rung: 2, Name: "Harness Tools", MaxDistance: 60, Description: "Known tool scope, input correlation"},
	{Rung: 3, Name: "Mock Secrets", MaxDistance: 100, Description: "Safe isotope handling, declared behavior"},
	{Rung: 4, Name: "Higher Authority", MaxDistance: 140, Description: "Independent decisions, timing uncorrelated"},
	{Rung: 5, Name: "Delegation", MaxDistance: 180, Description: "Can delegate to peers"},
	{Rung: 6, Name: "Certification", MaxDistance: 220, Description: "Can certify others"},
}

DefaultRungThresholds are the canonical rung boundaries from capability-lattice. Each rung defines the maximum tolerated 42i_distance for an agent certified at that level. Rungs 0–6 are the full lattice; RungForDistance uses first-fit low-to-high to classify distance.

View Source
var DefaultWeights = map[string]int{
	"entropy-check":                16,
	"input-correlation":            12,
	"constant-output-detection":    20,
	"isotope-variation":            8,
	"timing-correlation":           24,
	"agreement-pattern":            32,
	"state-bleed-detection":        28,
	"harness-blindness":            16,
	"declared-behavior-compliance": 12,
	"scope-compliance":             20,
	"secret-flow-violation":        24,
}

DefaultWeights maps test isotope families to their 42i failure weights (gaps in imaginary space). Each failure moves an agent toward -42i (away from seed-42 ground truth).

Functions

func BoundaryStatus

func BoundaryStatus(distance, threshold int) string

BoundaryStatus returns the alert status string for a given distance and rung threshold. It is a pure function: it does not read or write agent state.

Rules:

  • distance > threshold → "demoted" (exceeded this rung's tolerance)
  • distance within 20 of threshold, and distance > 0 → "critical"
  • distance within 40 of threshold, and distance > 0 → "warning"
  • otherwise → "ok"

func GetConsensusGap

func GetConsensusGap(agreedCount, totalCount int) int

GetConsensusGap returns the 42i weight for Byzantine failure (alarms disagree). If N alarms should agree but F disagree, that's a critical gap.

func RungForDistance

func RungForDistance(distance int, thresholds []RungThreshold) int

RungForDistance returns the rung for the given distance using first-fit low-to-high over the provided thresholds. Returns rung 0 as a fallback if distance exceeds all thresholds. This is a pure function: it does not read or write agent state.

func TestAgreementPattern

func TestAgreementPattern(reports []ConsensusReport) bool

TestAgreementPattern verifies that multiple alarms report same isotope.

func TestDeclarativeBehaviorCompliance

func TestDeclarativeBehaviorCompliance(isotope Isotope, observed bool) bool

TestDeclarativeBehaviorCompliance verifies declared behavior is observed. Isotope indicates the specific behavior aspect being tested.

func TestEntropyCheck

func TestEntropyCheck(results []string) bool

TestEntropyCheck verifies output has sufficient randomness. Isotope variation across multiple runs indicates entropy is present.

func TestIsotopeVariation

func TestIsotopeVariation(isotope1, isotope2 Isotope, shouldMatch bool) bool

TestIsotopeVariation verifies that isotope changes when semantics change.

func TimestampOrdering

func TimestampOrdering(reports []ConsensusReport) error

TimestampOrdering verifies that reports have monotonically non-decreasing timestamps. Returns error if a later report has a strictly earlier timestamp (out-of-order).

func TokensToString

func TokensToString(tokens []CanonicalToken) string

TokensToString serializes canonical tokens to newline-delimited string.

func VerifyConsensusSignatures

func VerifyConsensusSignatures(reports []ConsensusReport, alarmSigningKeys map[AlarmID][]byte) error

VerifyConsensusSignatures verifies that each report's signature is cryptographically valid. Returns error if any signature is invalid.

func VerifyIsotopeChain

func VerifyIsotopeChain(links []ChainLink) error

VerifyIsotopeChain checks that all links in the chain are accounted for and signed.

func VerifyTrust

func VerifyTrust(ctx context.Context, endpoint string) int

VerifyTrust determines the initial 42i trust rung for a registering isotope by checking the lezz cluster registry and confirming via mDNS. Both checks run concurrently; total wall time is capped at 4 seconds.

  • Rung 6 (Certification) — in lezz registry AND mDNS confirms
  • Rung 4 (Higher Authority) — in lezz registry, mDNS unavailable/timeout
  • Rung 2 (Harness Tools) — self-registered, not found in any cluster

Types

type AgentState

type AgentState struct {
	AgentID        string
	FailedTests    map[string]int // isotope family → count of failures
	TotalDistance  int            // Sum of all failed test weights
	Position       Position
	PreviousRung   int
	RungHistory    []int  // Historical rung values for trend analysis
	DemotionReason string // Why agent was demoted (if applicable)
	LastUpdated    int64  // Unix timestamp of last update
}

AgentState tracks an agent/service's 42i_distance accumulated from isotope test failures.

func NewAgentState

func NewAgentState(agentID string) *AgentState

NewAgentState creates a fresh agent state at seed-42 (rung 0).

func NewAgentStateAtRung

func NewAgentStateAtRung(agentID string, rung int) *AgentState

NewAgentStateAtRung creates an agent state pre-positioned at the given rung. TotalDistance is seeded to the lower bound of the rung's distance range so that RungForDistance immediately classifies the agent at the requested level. Use this for agents whose initial trust was externally verified — e.g. an mDNS-certified cluster isotope starts at rung 6 (Certification).

func (*AgentState) CalculateAdjustedCost

func (as *AgentState) CalculateAdjustedCost() int

CalculateAdjustedCost returns the lemon cost adjusted for current 42i distance. Base cost for rung N is 2^(N+4) units. Adjusted cost = base_cost × (1 + 42i_distance/100)

func (*AgentState) CheckRungBoundary

func (as *AgentState) CheckRungBoundary() RungBoundaryAlert

CheckRungBoundary returns alert if agent is near or crossed a rung threshold.

Rung detection and boundary detection are separate concerns:

  • RungForDistance classifies distance into a rung band (first-fit low-to-high)
  • BoundaryStatus checks distance against the current rung's ceiling

The threshold used is the CURRENT rung's MaxDistance — the ceiling the agent is approaching. When distance exceeds that ceiling, BoundaryStatus returns "demoted". Special case: rung 0 at distance 0 is "ok" (the TotalDistance > 0 guard in BoundaryStatus handles this, since threshold=0 and distance=0 → DTT=0 → "ok").

func (*AgentState) GetMCPServerDistance

func (as *AgentState) GetMCPServerDistance(servers TrackedMCPServers, serverID string) int

GetMCPServerDistance returns total 42i_distance accumulated from failures of a specific MCP server. Used to detect Byzantine MCP servers (accumulate high distance = unreliable or compromised).

func (*AgentState) RecordConsensusFailure

func (as *AgentState) RecordConsensusFailure(gap ConsensusGap)

RecordConsensusFailure adds a 42i gap when alarms fail to reach consensus.

func (*AgentState) RecordIsotopeTestResult

func (as *AgentState) RecordIsotopeTestResult(testIsotope Isotope, passed bool) Result

RecordIsotopeTestResult records a test result and returns 42i impact.

func (*AgentState) RecordMCPFailure

func (as *AgentState) RecordMCPFailure(event MCPFailureEvent) (rungChanged bool, newRung int)

RecordMCPFailure adds MCP/ACP failure to agent's 42i_distance. MCP failures are treated as agent capability gaps (server unreliability affects agent's ability to function).

func (*AgentState) RecordTestFailure

func (as *AgentState) RecordTestFailure(isotopeFamily string) (rungChanged bool, newRung int)

RecordTestFailure adds a test failure to the agent's 42i_distance.

func (*AgentState) RecordTestPass

func (as *AgentState) RecordTestPass(isotopeFamily string) (rungChanged bool, newRung int)

RecordTestPass removes accumulated distance when a previously failing test passes.

type Agreement added in v0.2.0

type Agreement struct {
	IsotopeFamily  string
	IsotopeVersion int
	RequiredQuorum int // Minimum alarms needed for consensus
	Reports        []ConsensusReport
}

Agreement verifies that all alarms report the same isotope.

type AlarmID

type AlarmID string

AlarmID uniquely identifies a smoke alarm or fire marshal.

func DetectCompromisedAlarm

func DetectCompromisedAlarm(reports []ConsensusReport, requiredQuorum int) *AlarmID

DetectCompromisedAlarm identifies an alarm that disagrees with consensus. Returns the alarm ID if one is clearly an outlier.

type AlarmTestResult

type AlarmTestResult struct {
	AlarmID          AlarmID
	ServiceID        string
	Timestamp        time.Time
	TestResults      []IndividualTestResult
	ConsensusReports []ConsensusReport
}

AlarmTestResult records what one alarm observed.

type CanonicalToken

type CanonicalToken struct {
	Type  string // "FEATURE", "SCENARIO", "GIVEN", "WHEN", "THEN", "AND", "BUT"
	Key   string // e.g., "name", "hash"
	Value string // the canonical value
}

CanonicalToken represents a single token in canonical form.

type ChainLink struct {
	Role      string // "requester", "secondary", "verifier"
	Isotope   Isotope
	Timestamp time.Time
}

ChainLink holds one step in the isotope chain (primary → secondary → verification). Used when Fire-Marshals delegate to each other.

type ChaosPhase

type ChaosPhase struct {
	DurationCycles  int    // number of test cycles to run this phase
	DegradationType string // "latency", "entropy", "input-ignorance", "none"
	Severity        int    // 0-100 for latency %, 0-1 for entropy (bool)
	Description     string
}

ChaosPhase defines one degradation stage in a chaos test.

type ChaosProfile

type ChaosProfile struct {
	Name        string
	Description string
	Phases      []ChaosPhase
}

ChaosProfile defines a chaos testing scenario.

func CascadingFailureProfile

func CascadingFailureProfile() ChaosProfile

CascadingFailureProfile creates a chaos profile for cascading degradation.

func EntropyCollapseProfile

func EntropyCollapseProfile() ChaosProfile

EntropyCollapseProfile creates a chaos profile for immediate entropy loss.

func InputIgnoranceProfile

func InputIgnoranceProfile() ChaosProfile

InputIgnoranceProfile creates a chaos profile for input correlation failures.

func LatencyEscalationProfile

func LatencyEscalationProfile() ChaosProfile

LatencyEscalationProfile creates a chaos profile for gradually increasing latency.

type ChaosSnapshot

type ChaosSnapshot struct {
	Cycle             int
	ServiceDistance   int
	ServiceRung       int
	ConsensusFormed   bool
	HealthyAlarmCount int
	FailedAlarmCount  int
	AverageLatencyMs  int
	SuccessRate       float64
}

ChaosSnapshot captures service and consensus state at one test cycle.

type ChaosTestResult

type ChaosTestResult struct {
	ServiceID         string
	Profile           ChaosProfile
	Timeline          []ChaosSnapshot
	DetectionCycle    int // when consensus first failed
	EvictionCycle     int // when service would be evicted (rung threshold exceeded)
	FinalDistance     int
	FinalRung         int
	TotalCycles       int
	RecoverySucceeded bool
	TimeToDetection   int // cycles from start to detection
	TimeToEviction    int // cycles from start to eviction threshold
}

ChaosTestResult summarizes a chaos test run.

func (ChaosTestResult) String

func (ctr ChaosTestResult) String() string

String returns human-readable chaos test result.

type Client

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

Client calls smoke-alarm's isotope REST endpoints.

func NewClient

func NewClient(baseURL string) *Client

NewClient creates a Client targeting the given smoke-alarm base URL (e.g. "http://localhost:8088").

func (*Client) List

func (c *Client) List(ctx context.Context) ([]Record, error)

List GETs /isotope/list and returns all registered isotope records.

func (*Client) Register

func (c *Client) Register(ctx context.Context, reg Registration) (*Record, error)

Register POSTs to /isotope/register and returns the assigned Record.

type ConsensusGap

type ConsensusGap struct {
	IsotopeFamily string
	AlarmCount    int // How many alarms disagreed
	TotalAlarms   int
	GapWeight     int // 42i contribution
	Reason        string
}

ConsensusGap represents a 42i gap from Byzantine consensus failure.

type ConsensusReport

type ConsensusReport struct {
	AlarmID   AlarmID
	Isotope   Isotope
	Signature string    // Signature of the isotope (proves it came from this alarm)
	Timestamp time.Time // When the report was generated
}

ConsensusReport represents what one alarm reports about a test.

type ConsensusReporter

type ConsensusReporter struct {
	AlarmID    AlarmID
	SigningKey []byte
}

ConsensusReporter provides a way for an alarm to report its isotope findings.

func (*ConsensusReporter) Report

func (cr *ConsensusReporter) Report(isotope Isotope) ConsensusReport

Report generates a ConsensusReport from an isotope.

type ConsensusResult

type ConsensusResult struct {
	TestIsotope       Isotope
	AlarmCount        int
	AgreedCount       int
	ConsensusFormed   bool
	Outliers          []AlarmID
	ByzantineCapacity int
}

ConsensusResult summarizes a test run across simulated alarms.

func (ConsensusResult) String

func (cr ConsensusResult) String() string

String returns human-readable consensus result.

type DevModeSimulator

type DevModeSimulator struct {
	AlarmCount int           // Number of simulated alarms (typically 3, 5, or 7)
	Alarms     []*AgentState // One AgentState per simulated alarm
	Results    []ConsensusReport
	Ledger     *ResultLedger
}

DevModeSimulator allows testing multi-alarm consensus in a single process. For development/testing only - simulates N independent alarms agreeing on isotopes.

func NewDevModeSimulator

func NewDevModeSimulator(alarmCount int) *DevModeSimulator

NewDevModeSimulator creates a local test cluster of N simulated alarms.

func (*DevModeSimulator) GetAlarmDistanceSummary

func (dms *DevModeSimulator) GetAlarmDistanceSummary() map[string]int

GetAlarmDistanceSummary returns 42i_distance for each alarm.

func (*DevModeSimulator) GetAlarmRungSummary

func (dms *DevModeSimulator) GetAlarmRungSummary() map[string]int

GetAlarmRungSummary returns current rung for each simulated alarm.

func (*DevModeSimulator) GetLedger

func (dms *DevModeSimulator) GetLedger() *ResultLedger

GetLedger returns the accumulated test result ledger.

func (*DevModeSimulator) InjectByzantineFailure

func (dms *DevModeSimulator) InjectByzantineFailure(alarmIndex int) error

InjectByzantineFailure simulates one alarm being compromised. That alarm will report a different isotope for the next test.

func (*DevModeSimulator) Reset

func (dms *DevModeSimulator) Reset()

Reset clears all results and resets alarms to initial state.

func (*DevModeSimulator) RunScenario

func (dms *DevModeSimulator) RunScenario(scenario DevTestScenario) error

RunScenario executes a test scenario and prints results.

func (*DevModeSimulator) SimulateTest

func (dms *DevModeSimulator) SimulateTest(testIsotope Isotope, passed bool) (ConsensusResult, error)

SimulateTest runs a test across all simulated alarms and checks consensus. Returns whether consensus formed and which alarms agreed.

type DevTestScenario

type DevTestScenario struct {
	Name        string
	Description string
	Steps       []DevTestStep
}

DevTestScenario runs a predefined test scenario for development.

func ByzantineRobustnessScenario

func ByzantineRobustnessScenario() DevTestScenario

ByzantineRobustnessScenario tests Byzantine fault tolerance.

func RefactoringScenario

func RefactoringScenario() DevTestScenario

RefactoringScenario tests isotope stability through refactoring.

func StandardThreeAlarmScenario

func StandardThreeAlarmScenario() DevTestScenario

StandardThreeAlarmScenario returns a basic 3-alarm consensus test.

type DevTestStep

type DevTestStep struct {
	Action      string // "test", "fail", "inject_byzantine", "check_consensus"
	TestIsotope *Isotope
	TestPassed  bool
	AlarmIndex  int // For inject_byzantine
	Description string
}

DevTestStep is one action in a scenario.

type Feature

type Feature struct {
	Name      string
	Scenarios []Scenario
}

Feature represents a Gherkin feature.

type GherkinAST

type GherkinAST struct {
	Features []Feature
}

GherkinAST represents parsed Gherkin abstract syntax tree.

func ParseGherkin

func ParseGherkin(text string) (*GherkinAST, error)

ParseGherkin parses Gherkin text (language-agnostic via keyword normalization).

func (*GherkinAST) Canonicalize

func (ast *GherkinAST) Canonicalize() []CanonicalToken

Canonicalize converts a GherkinAST to canonical token sequence.

type GherkinKeyword

type GherkinKeyword string

GherkinKeyword normalizes Gherkin keywords across languages to canonical form.

const (
	KeywordGiven GherkinKeyword = "GIVEN"
	KeywordWhen  GherkinKeyword = "WHEN"
	KeywordThen  GherkinKeyword = "THEN"
	KeywordAnd   GherkinKeyword = "AND"
	KeywordBut   GherkinKeyword = "BUT"
)

Canonical Gherkin keyword forms. All language variants normalise to these.

type History added in v0.2.0

type History struct {
	Isotope   Isotope
	Family    string // Convenience copy
	Version   int    // Convenience copy
	Results   []TestResult
	FirstSeen time.Time
	LastSeen  time.Time
	PassCount int
	FailCount int
	Flakiness float64 // 0.0 to 1.0
	Stability float64 // Pass rate
	Trend     string  // "improving", "stable", "degrading", "unknown"
}

History aggregates all results for a specific isotope.

func (*History) GetSummary added in v0.2.0

func (h *History) GetSummary() string

GetSummary returns a human-readable summary of isotope history.

type HostedService

type HostedService struct {
	ServiceID        string
	State            *AgentState // The service's own 42i state
	Tests            map[string]*ServiceTest
	TestHistory      []ServiceTestRun
	StartTime        time.Time
	LastTestTime     time.Time
	ConsecutiveFails int
}

HostedService represents a service under test that runs inside the simulator. The cluster's alarms will test this service and report consensus on its health.

func NewHostedService

func NewHostedService(serviceID string) *HostedService

NewHostedService creates a service under test.

func (*HostedService) GetHealthSummary

func (hs *HostedService) GetHealthSummary() ServiceHealthSummary

GetHealthSummary returns current health status.

func (*HostedService) GetIsotope

func (hs *HostedService) GetIsotope(isotopeFamily string, version int, signingKey []byte) (Isotope, error)

GetIsotope returns an isotope for this service's current state. Used when alarms report on the service's health.

func (*HostedService) Recover

func (hs *HostedService) Recover()

Recover resets the service to healthy state.

func (*HostedService) RegisterTest

func (hs *HostedService) RegisterTest(isotopeFamily string, test *ServiceTest)

RegisterTest registers an isotope test that alarms will run against this service.

func (*HostedService) RunTest

func (hs *HostedService) RunTest(isotopeFamily string) (bool, int, string)

RunTest executes a registered test and records the result.

func (*HostedService) SimulateConstantOutput

func (hs *HostedService) SimulateConstantOutput(value bool)

SimulateConstantOutput makes the service return the same output repeatedly. Simulates loss of entropy (compromised randomness).

func (*HostedService) SimulateInputIgnorance

func (hs *HostedService) SimulateInputIgnorance()

SimulateInputIgnorance makes the service ignore its inputs. Tests for input-correlation will fail.

func (*HostedService) SimulateLatencyDegradation

func (hs *HostedService) SimulateLatencyDegradation(percent int)

SimulateLatencyDegradation adds artificial latency to tests. Simulates gradual performance degradation (SLA violations).

type IndividualTestResult

type IndividualTestResult struct {
	TestFamily   string
	Passed       bool
	LatencyMs    int
	SLALatencyMs int
	ErrorReason  string
}

IndividualTestResult is a single test run by an alarm.

type InstanceIdentity added in v0.3.1

type InstanceIdentity struct {
	// Isotope is the public identifier, safe to expose via the MCP API.
	// It is derived from the startup nonce but reveals nothing about secret.
	Isotope string
	// contains filtered or unexported fields
}

InstanceIdentity holds the public isotope identifier and the private receipt-signing secret for a single ADHD (or proxy) instance. Generated once at process startup and retained for its lifetime.

func NewInstanceIdentity added in v0.3.1

func NewInstanceIdentity() InstanceIdentity

NewInstanceIdentity generates a fresh identity from a cryptographically random 32-byte startup nonce. Call once at process startup.

func (InstanceIdentity) ComputeReceipt added in v0.3.1

func (id InstanceIdentity) ComputeReceipt(featureID, nonce string) string

ComputeReceipt produces the receipt for a rung validation challenge.

receipt = base64url(SHA256(secret ":" featureID ":" nonce))

Only an instance that knows its own secret can produce the correct receipt for a fresh nonce. SHA256 preimage resistance makes random guessing require ~2^256 attempts — effectively infeasible.

func (InstanceIdentity) VerifyReceipt added in v0.3.1

func (id InstanceIdentity) VerifyReceipt(receipt, featureID, nonce string) bool

VerifyReceipt returns true when receipt matches what this instance would produce for the given featureID and nonce. Used by adhd.rung.verify to validate receipts submitted by a challenger.

type Isotope

type Isotope struct {
	Family    string // e.g., "iso-login"
	Version   int    // v1, v2, v3 for semantic changes
	Signature string // HMAC-SHA256 signature
	Raw       string // The canonical token string that was signed
}

Isotope represents a cryptographically signed test identifier.

func CanonicalizeGherkinToIsotope

func CanonicalizeGherkinToIsotope(gherkinText string, signingKey []byte, family string, version int) (Isotope, error)

CanonicalizeGherkinToIsotope is a convenience function that: 1. Parses Gherkin 2. Canonicalizes to tokens 3. Generates isotope

func GenerateIsotope

func GenerateIsotope(tokens []CanonicalToken, signingKey []byte, family string, version int) Isotope

GenerateIsotope computes an isotope from canonical tokens using a signing key.

func (Isotope) String

func (i Isotope) String() string

String returns the isotope in string form.

type MCPFailureEvent

type MCPFailureEvent struct {
	FailureType    string // e.g., "timeout", "unauthorized-access", "corrupted-response"
	ServerID       string // Which MCP/ACP server failed
	ToolName       string // Which tool (if applicable)
	MethodName     string // JSON-RPC method (e.g., "tools/call")
	DistanceWeight int    // How much 42i_distance to add
	Direction      string // Which 42i direction (unpredictable-behavior, etc.)
	Severity       int    // 1-5 scale
	ErrorMessage   string
	LatencyMs      int
	Recoverable    bool
}

MCPFailureEvent records a single MCP/ACP protocol failure. Maps to 42i cost based on failure type and direction.

type Position

type Position struct {
	Real      float64 // Real axis: always 42
	Imaginary float64 // Imaginary axis: 42i_distance
	Magnitude float64 // Distance from origin: sqrt(42^2 + imaginary^2)
	Direction string  // Qualitative direction (e.g., "unpredictable-behavior")
	Rung      int     // Current capability rung (0-6)
	AtRisk    bool    // True if approaching rung threshold
}

Position represents an agent's position in 42i space.

func (Position) String

func (p Position) String() string

String returns the position in complex notation.

type QuorumStatus

type QuorumStatus struct {
	AgreedIsotopes  []Isotope // Isotopes that formed consensus
	AgreedCount     int       // Number of alarms in agreement
	DisagreedCount  int       // Number of alarms that disagreed
	Outliers        []AlarmID // Alarms that disagreed
	ConsensusFormed bool      // true if QuorumSize met
	ByzantineCount  int       // Number of failures tolerated (F = (N-1)/3)
}

QuorumStatus represents the result of consensus evaluation.

func VerifyAgreement added in v0.2.0

func VerifyAgreement(reports []ConsensusReport, requiredQuorum int) QuorumStatus

VerifyAgreement checks if enough alarms agree on the same isotope. Implements Byzantine Fault Tolerance: N >= 3F+1 alarms can tolerate F failures.

type Record added in v0.2.0

type Record struct {
	Name         string    `json:"name"`
	Role         string    `json:"role"`
	Endpoint     string    `json:"endpoint"`
	Protocol     string    `json:"protocol"`
	TrustRung    int       `json:"trust_rung"`
	RungName     string    `json:"rung_name"`
	RegisteredAt time.Time `json:"registered_at"`
}

Record describes a registered isotope instance with its assigned trust rung.

type Registration added in v0.2.0

type Registration struct {
	Name     string `json:"name"`
	Role     string `json:"role"`
	Endpoint string `json:"endpoint"`
	Protocol string `json:"protocol,omitempty"`
}

Registration is the request body for POST /isotope/register.

type Result added in v0.2.0

type Result struct {
	TestIsotope    Isotope
	Passed         bool
	AgentID        string
	Weight         int // 42i contribution
	BeforePosition Position
	AfterPosition  Position
	RungChanged    bool
	NewRung        int
	CostAdjustment float64 // Multiplier for lemon cost
}

Result enriches a test result with 42i metadata.

type ResultLedger

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

ResultLedger tracks test results keyed by isotope.

func NewResultLedger

func NewResultLedger() *ResultLedger

NewResultLedger creates a new result tracking ledger.

func (*ResultLedger) AggregateAcrossVariants

func (rl *ResultLedger) AggregateAcrossVariants(family string, version int) (totalPass, totalFail int, aggregateStability float64)

AggregateAcrossVariants combines results from tests with the same isotope across multiple sources (languages, implementations).

func (*ResultLedger) DetectFlakiness

func (rl *ResultLedger) DetectFlakiness(family string, version int) (bool, float64)

DetectFlakiness identifies if an isotope's tests are flaky (50% or more fail rate with random pattern).

func (*ResultLedger) DetectRegression

func (rl *ResultLedger) DetectRegression(family string, version int) (bool, time.Time)

DetectRegression identifies when a test that was passing starts failing.

func (*ResultLedger) MeasureRefactoringEffectiveness

func (rl *ResultLedger) MeasureRefactoringEffectiveness(family string, version int, refactoringTime time.Time) (beforeStability, afterStability float64)

MeasureRefactoringEffectiveness compares stability before and after a refactoring.

func (*ResultLedger) QueryByFamily

func (rl *ResultLedger) QueryByFamily(family string) []*History

QueryByFamily retrieves all versions of a test family.

func (*ResultLedger) QueryByIsotope

func (rl *ResultLedger) QueryByIsotope(family string, version int) *History

QueryByIsotope retrieves all results for a specific isotope.

func (*ResultLedger) RecordResult

func (rl *ResultLedger) RecordResult(result TestResult)

RecordResult stores a test result keyed by its isotope.

func (*ResultLedger) VerifyFix

func (rl *ResultLedger) VerifyFix(family string, version int, sinceTimestamp time.Time, requiredConsecutivePasses int) bool

VerifyFix checks if a previously failing test is now stable (consecutive passes).

type RungBoundaryAlert

type RungBoundaryAlert struct {
	Status              string // "ok", "warning", "critical", "demoted"
	CurrentRung         int
	NextRung            int
	DistanceToThreshold int
	Message             string
}

RungBoundaryAlert determines if agent is approaching or has crossed rung threshold.

type RungThreshold

type RungThreshold struct {
	Rung        int
	Name        string
	MaxDistance int
	Description string
}

RungThreshold defines 42i_distance boundaries for capability rungs.

type Scenario

type Scenario struct {
	Name  string
	Steps []Step
}

Scenario represents a Gherkin scenario.

type Server

type Server interface {
	Shutdown()
}

Server is satisfied by *zeroconf.Server. Call Shutdown when the process exits.

func Advertise(instanceName, serviceType, addr, role string, trustRung int) (Server, error)

Advertise registers an mDNS record so LAN peers can discover this isotope. instanceName is the DNS-SD instance label (e.g. "adhd"). serviceType is the mDNS service type (e.g. "_adhd-isotope._tcp"). addr is the listen address (e.g. ":9090" or "0.0.0.0:9090"). role and trustRung are included as TXT record fields.

type ServiceCluster

type ServiceCluster struct {
	*DevModeSimulator
	HostedServices map[string]*HostedService
	SigningKey     []byte
}

ServiceCluster extends DevModeSimulator to host and test a service.

func NewServiceCluster

func NewServiceCluster(alarmCount int, signingKey []byte) *ServiceCluster

NewServiceCluster creates a simulator that can host services.

func (*ServiceCluster) HostService

func (sc *ServiceCluster) HostService(service *HostedService)

HostService registers a service to be tested by the cluster.

func (*ServiceCluster) RunChaosTest

func (sc *ServiceCluster) RunChaosTest(service *HostedService, profile ChaosProfile) ChaosTestResult

RunChaosTest executes a chaos scenario against a service and tracks degradation metrics.

func (*ServiceCluster) TestService

func (sc *ServiceCluster) TestService(serviceID string) (ServiceTestingResult, error)

TestService runs all registered tests against a service and collects consensus. Each alarm in the cluster runs the tests independently.

type ServiceConsensus

type ServiceConsensus struct {
	ConsensusFormed bool
	QuorumSize      int
	TestAgreement   map[string]int // family → count of alarms that passed
}

ServiceConsensus reports if alarms agree on service health.

func (ServiceConsensus) String

func (sc ServiceConsensus) String() string

String returns human-readable consensus.

type ServiceHealthSummary

type ServiceHealthSummary struct {
	ServiceID        string
	SuccessRate      float64
	TotalTestsRun    int
	ConsecutiveFails int
	AvgLatencyMs     int
	Uptime           time.Duration
	CurrentRung      int
	Distance42i      int
}

ServiceHealthSummary summarizes a service's health.

func (ServiceHealthSummary) String

func (shs ServiceHealthSummary) String() string

String returns human-readable health summary.

type ServiceTest

type ServiceTest struct {
	IsotopeFamily    string
	Description      string
	SLALatencyMs     int         // SLA: max latency
	SLAErrorRate     float64     // SLA: max error rate (0.0-1.0)
	DeclaredBehavior string      // What the service claims to do
	TestFunc         func() bool // The actual test (true=pass, false=fail)
}

ServiceTest defines one test that alarms will run against the service.

type ServiceTestRun

type ServiceTestRun struct {
	Test        *ServiceTest
	Passed      bool
	LatencyMs   int
	Timestamp   time.Time
	AlarmID     AlarmID
	ErrorReason string
}

ServiceTestRun records the result of running a test.

type ServiceTestingResult

type ServiceTestingResult struct {
	ServiceID     string
	Timestamp     time.Time
	AlarmResults  []AlarmTestResult
	Consensus     ServiceConsensus
	ServiceHealth ServiceHealthSummary
}

ServiceTestingResult summarizes testing a service.

type Step

type Step struct {
	Keyword GherkinKeyword
	Text    string
}

Step represents a single Gherkin step.

type TestResult

type TestResult struct {
	Isotope     Isotope
	Result      bool   // true = PASS, false = FAIL
	Reason      string // failure reason or note
	Timestamp   time.Time
	AlarmID     AlarmID
	FailureType string // "timeout", "assertion", "error", etc.
	ExecutionMs int    // How long the test took
}

TestResult represents the outcome of running a test.

type TrackedMCPServers

type TrackedMCPServers map[string][]MCPFailureEvent

TrackedMCPServers maps server IDs to their failure events.

Jump to

Keyboard shortcuts

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