kernel

package
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const DeadProcessTTL = 60 * time.Second

DeadProcessTTL is how long a Dead process stays in the procTable before removal.

View Source
const DefaultCtxSize = 64

DefaultCtxSize is the default context size (message count) for new contexts.

View Source
const DefaultDeviationThreshold = 3.0

DefaultDeviationThreshold is the default deviation threshold (standard deviation multiplier). When actual value > mean + threshold * stddev, the behavior is considered anomalous. 3.0 corresponds to 99.7% confidence interval of a normal distribution.

View Source
const DefaultMaxSteps = 100

DefaultMaxSteps is the maximum number of reasoning steps before forced completion.

View Source
const DefaultPipeBufferSize = 64 * 1024

DefaultPipeBufferSize is the default capacity for pipe buffers (64KB, matches Linux pipe default).

View Source
const DefaultReinforcementThreshold = 5

DefaultReinforcementThreshold is the minimum cooperation count for a path to be considered reinforced.

View Source
const MinMigrationSimilarity = 0.3

MinMigrationSimilarity is the minimum similarity score required for capability migration.

View Source
const MinSamplesForProfile = 5

MinSamplesForProfile is the minimum number of samples required to build a NormalProfile.

Variables

This section is empty.

Functions

func ReadAllSteps added in v0.7.0

func ReadAllSteps(path string, afterStep int) ([]types.StepRecord, int, error)

ReadAllSteps reads all step records from a steps.jsonl file. If afterStep > 0, only records with Step > afterStep are returned. Returns the matching records and the total count of all records in the file.

func ReadStep added in v0.7.0

func ReadStep(path string, targetStep int) (*types.StepRecord, error)

ReadStep reads a specific step from a steps.jsonl file by sequential scan.

func SaveProcInfo added in v0.7.1

func SaveProcInfo(baseDir string, info vfs.ProcInfo) error

SaveProcInfo writes a ProcInfo snapshot to <baseDir>/data/steps/<uuid>/proc-info.json. Best-effort: returns nil silently if baseDir or UUID is empty.

Types

type ActionType

type ActionType string

ActionType classifies LLM response actions.

const (
	ActionText       ActionType = "text"
	ActionToolCall   ActionType = "tool_call"
	ActionPlan       ActionType = "plan"
	ActionSpawn      ActionType = "spawn"
	ActionComplete   ActionType = "complete"
	ActionReplan     ActionType = "replan"
	ActionSpecialize ActionType = "specialize"
)

type AgentLoaderFunc

type AgentLoaderFunc func(name string) (*agents.AgentInfo, error)

AgentLoaderFunc loads an agent definition by name.

type AgentQuota

type AgentQuota struct {
	PID      types.PID
	Name     string
	Priority Priority
	Quota    int // allocated quota
	Consumed int // tokens consumed so far
}

AgentQuota records a single agent's budget quota and consumption.

type AnomalyAlert

type AnomalyAlert struct {
	PID           types.PID   `json:"pid"`
	AgentTemplate string      `json:"agent_template"`
	Type          AnomalyType `json:"type"`
	Detail        string      `json:"detail"`    // human-readable description
	Deviation     float64     `json:"deviation"` // deviation multiplier (actual / mean)
	Timestamp     time.Time   `json:"timestamp"`
}

AnomalyAlert records a single anomaly detection event.

type AnomalyDetector

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

AnomalyDetector detects behavioral anomalies by comparing runtime metrics against NormalProfiles.

func NewAnomalyDetector

func NewAnomalyDetector(threshold float64) *AnomalyDetector

NewAnomalyDetector creates a new AnomalyDetector with the given threshold.

func (*AnomalyDetector) CheckSyscallAnomaly

func (d *AnomalyDetector) CheckSyscallAnomaly(
	pid types.PID,
	agentTemplate string,
	syscallName string,
	currentCount int,
	profile *NormalProfile,
) *AnomalyAlert

CheckSyscallAnomaly checks whether the current syscall count is anomalous. Returns nil if normal or if profile is nil / has no data for this syscall.

func (*AnomalyDetector) CheckTokenRateAnomaly

func (d *AnomalyDetector) CheckTokenRateAnomaly(
	pid types.PID,
	agentTemplate string,
	currentRate float64,
	profile *NormalProfile,
) *AnomalyAlert

CheckTokenRateAnomaly checks whether the current token rate is anomalous. Returns nil if normal or if profile is nil / has zero mean.

func (*AnomalyDetector) MatchThreat

func (d *AnomalyDetector) MatchThreat(
	agentTemplate string,
	anomalyType AnomalyType,
	metric string,
	threats []ThreatSignature,
) *ThreatSignature

MatchThreat checks if the current behavior matches a known threat signature. Match criteria: same agent_template + same anomaly_type + same metric. Returns the first matching threat, or nil if no match.

type AnomalyType

type AnomalyType string

AnomalyType enumerates the kinds of anomalies the immune system can detect.

const (
	AnomalySyscallFreq  AnomalyType = "syscall_freq"  // syscall invocation frequency anomaly
	AnomalyTokenRate    AnomalyType = "token_rate"    // token consumption rate anomaly
	AnomalyDeviceAccess AnomalyType = "device_access" // unexpected device access anomaly
)

type BehaviorCollector

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

BehaviorCollector monitors a single process and aggregates SyscallEvent data.

func NewBehaviorCollector

func NewBehaviorCollector(pid types.PID, agentTemplate string) *BehaviorCollector

NewBehaviorCollector creates a new BehaviorCollector for the given process.

func (*BehaviorCollector) Finalize

func (c *BehaviorCollector) Finalize(tokensUsed int, exitNormal bool) BehaviorSample

Finalize produces the final BehaviorSample when the process exits.

func (*BehaviorCollector) GetAgentTemplate

func (c *BehaviorCollector) GetAgentTemplate() string

GetAgentTemplate returns the agent template name for this collector.

func (*BehaviorCollector) GetSyscallCount

func (c *BehaviorCollector) GetSyscallCount(syscallName string) int

GetSyscallCount returns the current cumulative count for the given syscall name.

func (*BehaviorCollector) Observe

func (c *BehaviorCollector) Observe(event types.SyscallEvent)

Observe processes a SyscallEvent and updates behavior statistics.

type BehaviorSample

type BehaviorSample struct {
	AgentTemplate string         `json:"agent_template"`
	SyscallCounts map[string]int `json:"syscall_counts"`
	DeviceAccess  []string       `json:"device_access"`
	TokensUsed    int            `json:"tokens_used"`
	TokenRate     float64        `json:"token_rate"`
	DurationMs    int64          `json:"duration_ms"`
	ExitNormal    bool           `json:"exit_normal"`
	Timestamp     time.Time      `json:"timestamp"`
}

BehaviorSample records a single agent execution's behavioral summary.

type Breakpoint

type Breakpoint struct {
	ID        int
	Type      BreakpointType
	Condition BreakpointCondition
	Enabled   bool
	HitCount  int
}

Breakpoint represents a single gdb breakpoint registered on a process.

type BreakpointCondition

type BreakpointCondition interface {
	Match(ctx BreakpointContext) bool
}

BreakpointCondition is the interface for type-specific matching logic.

type BreakpointContext

type BreakpointContext struct {
	BPType      BreakpointType
	SyscallName string
	SyscallArgs map[string]any
	LLMResponse string
	TokensUsed  int
	StepNumber  int
}

BreakpointContext carries the runtime data needed to evaluate breakpoint conditions.

type BreakpointType

type BreakpointType int

BreakpointType enumerates the four kinds of gdb breakpoints.

const (
	BPSyscall   BreakpointType = 1
	BPReasoning BreakpointType = 2
	BPQuality   BreakpointType = 3
	BPBudget    BreakpointType = 4
)

type BudgetCondition

type BudgetCondition struct {
	Threshold int
	// contains filtered or unexported fields
}

BudgetCondition matches when token usage reaches or exceeds Threshold. Tracks whether it has already fired to prevent infinite re-triggering (tokens only increase, so >= would match on every subsequent step).

func (*BudgetCondition) Match

func (c *BudgetCondition) Match(ctx BreakpointContext) bool

type BudgetPool

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

BudgetPool manages a Compose orchestration's total token budget. Thread-safe via sync.RWMutex.

func NewBudgetPool

func NewBudgetPool(totalBudget int) *BudgetPool

NewBudgetPool creates a budget pool with the given total token budget.

func (*BudgetPool) AllocateQuota

func (bp *BudgetPool) AllocateQuota(pid types.PID, name string, priority Priority) int

AllocateQuota registers an agent and recalculates proportional quotas for all registered agents. Returns the quota for this agent.

The quota is calculated as: totalBudget * agentWeight / totalWeight where totalWeight is the sum of all registered agents' priorities. Each call recalculates ALL quotas to maintain proportional fairness.

func (*BudgetPool) GetQuota

func (bp *BudgetPool) GetQuota(pid types.PID) (int, bool)

GetQuota returns the current allocated quota for a specific agent.

func (*BudgetPool) GetStatus

func (bp *BudgetPool) GetStatus() BudgetPoolStatus

GetStatus returns a point-in-time snapshot of the budget pool state.

func (*BudgetPool) IsExhausted

func (bp *BudgetPool) IsExhausted() bool

IsExhausted returns true when total consumption >= total budget. A zero-budget pool is always exhausted. A negative-budget pool is never exhausted.

func (*BudgetPool) RecordUsage

func (bp *BudgetPool) RecordUsage(pid types.PID, tokens int) error

RecordUsage records token consumption for an agent. Returns an error if the PID is not registered.

func (*BudgetPool) Remaining

func (bp *BudgetPool) Remaining() int

Remaining returns the number of unspent tokens in the pool.

type BudgetPoolStatus

type BudgetPoolStatus struct {
	TotalBudget int
	Allocated   int
	Consumed    int
	Remaining   int
	Quotas      []AgentQuota
}

BudgetPoolStatus is a point-in-time snapshot of the pool state.

type CapabilitySimilarity

type CapabilitySimilarity struct {
	AgentA     string  `json:"agent_a"`
	AgentB     string  `json:"agent_b"`
	SkillScore float64 `json:"skill_score"` // Skill overlap 0.0~1.0 (Jaccard coefficient)
	CoopScore  float64 `json:"coop_score"`  // Cooperation history score 0.0~1.0
	Score      float64 `json:"score"`       // Combined = 0.7 * SkillScore + 0.3 * CoopScore
}

CapabilitySimilarity records the similarity between two agents.

type ChildConfig

type ChildConfig struct {
	Name          string `yaml:"name"`
	Intent        string `yaml:"intent"`
	Agent         string `yaml:"agent"`
	Model         string `yaml:"model"`
	Provider      string `yaml:"provider,omitempty"`
	ContextBudget int    `yaml:"context_budget"`
	Restart       string `yaml:"restart"`
}

ChildConfig describes a child process within a SupervisorConfig.

type ChildRestart

type ChildRestart string

ChildRestart defines the restart policy for individual children.

const (
	RestartPermanent ChildRestart = "permanent"
	RestartTransient ChildRestart = "transient"
	RestartTemporary ChildRestart = "temporary"
)

type ChildSpec

type ChildSpec struct {
	Name          string
	Intent        string
	Agent         *agents.AgentInfo
	Model         string
	Provider      string
	ContextBudget int
	Restart       ChildRestart
}

ChildSpec describes a child process to be supervised.

type CollaborationTopology

type CollaborationTopology struct {
	Nodes           []TopologyNode    `json:"nodes"`
	Edges           []CooperationEdge `json:"edges"`
	ReinforcedPaths []CooperationEdge `json:"reinforced_paths"`
}

CollaborationTopology holds the complete collaboration graph.

type ComboSummary

type ComboSummary struct {
	ComboKey         SynergyComboKey `json:"combo_key"`
	Skills           []string        `json:"skills"`
	SuccessRate      float64         `json:"success_rate"`
	AvgTokens        int             `json:"avg_tokens"`
	TotalExecutions  int             `json:"total_executions"`
	AvgSoloRate      float64         `json:"avg_solo_rate"`
	TokenImprovement float64         `json:"token_improvement"`
	Recommended      bool            `json:"recommended"`
}

ComboSummary holds aggregated statistics for a single skill combination.

type ConcurrencyManager

type ConcurrencyManager interface {
	SpawnThread(parentPID types.PID, intent string) (types.TID, error)
	JoinThread(parentPID types.PID, tid types.TID) error
	SpawnCoroutine(parentPID types.PID, fn CoroutineFunc) (types.CoID, error)
	Yield(parentPID types.PID, coID types.CoID, value any) error
	ResumeCoroutine(parentPID types.PID, coID types.CoID) (any, error)
}

ConcurrencyManager manages thread and coroutine concurrency primitives.

type CoopRecord

type CoopRecord struct {
	SpawnCount int
	MsgCount   int
}

CoopRecord stores typed cooperation counts between two agents.

type CooperationEdge

type CooperationEdge struct {
	From       string `json:"from"`
	To         string `json:"to"`
	SpawnCount int    `json:"spawn_count"` // parent spawned child count
	MsgCount   int    `json:"msg_count"`   // IPC message send count
	Total      int    `json:"total"`       // SpawnCount + MsgCount
	Reinforced bool   `json:"reinforced"`  // true if Total >= threshold
}

CooperationEdge represents a directed cooperation relationship between two agents.

type Coroutine

type Coroutine struct {
	CoID      types.CoID
	ParentPID types.PID
	State     coroutineState
	// contains filtered or unexported fields
}

Coroutine represents a cooperatively scheduled execution unit within a process.

type CoroutineFunc

type CoroutineFunc func(yield func(any)) any

CoroutineFunc is the function executed by a coroutine. The yield parameter is used to yield control and pass a value to the caller.

type DetailSnapshot added in v0.7.0

type DetailSnapshot struct {
	PID            types.PID
	UUID           string
	PPID           types.PID
	State          types.ProcessState
	Intent         string
	Provider       string
	Model          string
	CreatedAt      time.Time
	DeadAt         time.Time
	Skills         []string
	AllowedDevices []string
	CtxID          types.CtxID
	TokensUsed     int
	ContextBudget  int
}

GetDetailSnapshot returns a thread-safe snapshot of process fields needed for detail view.

type DiffMemory

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

DiffMemory stores and retrieves differentiation paths keyed by intent signatures.

func NewDiffMemory

func NewDiffMemory(maxSize int) *DiffMemory

NewDiffMemory creates a new DiffMemory with the given maximum entry count.

func (*DiffMemory) Lookup

func (dm *DiffMemory) Lookup(intent string) ([]string, bool)

Lookup retrieves the skill list for a given intent. Returns the skills and true if found, or nil and false if not found. A successful lookup increments the entry's HitCount.

func (*DiffMemory) Record

func (dm *DiffMemory) Record(intent string, skills []string)

Record stores a differentiation path for the given intent. If the entry already exists with the same skills, only Timestamp is updated. If the entry exists with different skills, the skill list is replaced (latest wins). HitCount is only incremented by Lookup (actual reuse), not by Record. When maxSize is exceeded, the entry with the lowest HitCount (and oldest Timestamp as tiebreaker) is evicted.

type DiffMemoryEntry

type DiffMemoryEntry struct {
	Intent    string    `json:"intent"`
	Skills    []string  `json:"skills"`
	Timestamp time.Time `json:"timestamp"`
	HitCount  int       `json:"hit_count"`
}

DiffMemoryEntry records a single differentiation path for later reuse.

type EventWriter added in v0.7.1

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

EventWriter writes SyscallEvent entries as NDJSON to disk.

func NewEventWriter added in v0.7.1

func NewEventWriter(baseDir string, procUUID string) (*EventWriter, error)

NewEventWriter creates an EventWriter that writes to .rnix/data/steps/<uuid>/events.jsonl.

func (*EventWriter) Close added in v0.7.1

func (ew *EventWriter) Close() error

Close flushes and closes the underlying file.

func (*EventWriter) Flush added in v0.7.1

func (ew *EventWriter) Flush() error

Flush flushes the buffered writer to disk.

func (*EventWriter) WriteEvent added in v0.7.1

func (ew *EventWriter) WriteEvent(ev types.SyscallEvent) error

WriteEvent marshals and appends a SyscallEvent as a single NDJSON line.

type ExitStatus

type ExitStatus struct {
	Code   int    // 0 = normal, non-zero = abnormal
	Reason string // human-readable reason
	Err    error  // underlying error, if any
}

ExitStatus records how a process terminated.

type FDSnapshot added in v0.7.0

type FDSnapshot struct {
	FD         types.FD
	DevicePath string
}

FDSnapshot represents a point-in-time copy of a file descriptor entry.

type IPCManager

type IPCManager interface {
	Send(senderPID, targetPID types.PID, data []byte) error
	Recv(pid types.PID) (*Message, error)
	Pipe(writerPID, readerPID types.PID) (writeFD, readFD types.FD, err error)
}

IPCManager defines the kernel's inter-process communication interface.

type ImmuneConfig added in v0.7.0

type ImmuneConfig struct {
	Enabled                bool    `json:"enabled" yaml:"enabled"`
	DeviationThreshold     float64 `json:"deviation_threshold" yaml:"deviation_threshold"`
	MinSamples             int     `json:"min_samples" yaml:"min_samples"`
	ReinforcementThreshold int     `json:"reinforcement_threshold" yaml:"reinforcement_threshold"`
	MinMigrationSimilarity float64 `json:"min_migration_similarity" yaml:"min_migration_similarity"`
}

ImmuneConfig holds configuration for the immune system. Parsed from the "immune" section of .rnix/config.yaml.

func DefaultImmuneConfig added in v0.7.0

func DefaultImmuneConfig() ImmuneConfig

DefaultImmuneConfig returns the default immune configuration (disabled).

func ParseImmuneConfig added in v0.7.0

func ParseImmuneConfig(data map[string]any, base ...ImmuneConfig) (ImmuneConfig, []string)

ParseImmuneConfig parses an ImmuneConfig from a generic map (from YAML). Fields not present in data retain their values from base. Invalid values fall back to the base value and produce warnings.

type ImmuneDaemon

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

ImmuneDaemon is the security monitoring daemon. It passively monitors agent behavior through event-driven hooks (no polling).

func NewImmuneDaemon

func NewImmuneDaemon(store *ImmuneStore, cfg ImmuneConfig) *ImmuneDaemon

NewImmuneDaemon creates a new ImmuneDaemon backed by the given store and config.

func (*ImmuneDaemon) ActivePIDs

func (d *ImmuneDaemon) ActivePIDs() []types.PID

ActivePIDs returns the PIDs of all processes currently being monitored.

func (*ImmuneDaemon) AttemptMigration

func (d *ImmuneDaemon) AttemptMigration(pid types.PID, agentTemplate string, intent string, contextMsgs []string) *MigrationResult

AttemptMigration tries to migrate a failed process to the best alternative agent. Returns nil if d is nil. Returns a MigrationResult with Success=false if no suitable candidate.

func (*ImmuneDaemon) ClearAlert

func (d *ImmuneDaemon) ClearAlert(pid types.PID)

ClearAlert removes the anomaly alert for the given PID. The actual SIGRESUME is sent by the caller (CLI/IPC handler).

func (*ImmuneDaemon) GetAlerts

func (d *ImmuneDaemon) GetAlerts() map[types.PID]*AnomalyAlert

GetAlerts returns a copy of all active anomaly alerts (keyed by PID).

func (*ImmuneDaemon) GetAllProfiles

func (d *ImmuneDaemon) GetAllProfiles() map[string]*NormalProfile

GetAllProfiles returns a copy of all established NormalProfiles.

func (*ImmuneDaemon) GetConfig added in v0.7.0

func (d *ImmuneDaemon) GetConfig() ImmuneConfig

GetConfig returns a copy of the ImmuneConfig used by this daemon.

func (*ImmuneDaemon) GetProfile

func (d *ImmuneDaemon) GetProfile(agentTemplate string) *NormalProfile

GetProfile returns the NormalProfile for the given agent template, or nil if none exists.

func (*ImmuneDaemon) GetReinforcedPaths

func (d *ImmuneDaemon) GetReinforcedPaths() []CooperationEdge

GetReinforcedPaths returns cooperation edges with Total >= DefaultReinforcementThreshold, sorted by Total descending. Returns nil if d is nil.

func (*ImmuneDaemon) GetSimilarAgents

func (d *ImmuneDaemon) GetSimilarAgents(agentName string, minScore float64) []CapabilitySimilarity

GetSimilarAgents returns agents similar to agentName with Score >= minScore.

func (*ImmuneDaemon) GetSimilarity

func (d *ImmuneDaemon) GetSimilarity(agentA, agentB string) *CapabilitySimilarity

GetSimilarity returns the similarity between two agents, or nil if not found.

func (*ImmuneDaemon) GetThreats

func (d *ImmuneDaemon) GetThreats() []ThreatSignature

GetThreats returns a copy of all known threat signatures.

func (*ImmuneDaemon) GetTopology

func (d *ImmuneDaemon) GetTopology() *CollaborationTopology

GetTopology builds and returns the complete collaboration topology. Returns nil if d is nil. Returns an empty topology if no cooperation data exists.

func (*ImmuneDaemon) IsRunning

func (d *ImmuneDaemon) IsRunning() bool

IsRunning reports whether the ImmuneDaemon is currently running.

func (*ImmuneDaemon) OnProcessExit

func (d *ImmuneDaemon) OnProcessExit(pid types.PID, tokensUsed int, exitNormal bool)

OnProcessExit finalizes the behavior sample and updates the NormalProfile.

func (*ImmuneDaemon) OnProcessStart

func (d *ImmuneDaemon) OnProcessStart(pid types.PID, agentTemplate string)

OnProcessStart creates a BehaviorCollector for the new process.

func (*ImmuneDaemon) OnSyscallEvent

func (d *ImmuneDaemon) OnSyscallEvent(pid types.PID, event types.SyscallEvent)

OnSyscallEvent forwards a SyscallEvent to the corresponding BehaviorCollector and performs anomaly detection (Story 22.2).

func (*ImmuneDaemon) RecordCooperation

func (d *ImmuneDaemon) RecordCooperation(agentA, agentB string)

RecordCooperation records a cooperation event between two agents (bidirectional).

func (*ImmuneDaemon) RecordCooperationTyped

func (d *ImmuneDaemon) RecordCooperationTyped(agentA, agentB string, coopType string)

RecordCooperationTyped records a typed cooperation event between two agents. coopType must be "spawn" or "msg". Also calls RecordCooperation for backward compatibility.

func (*ImmuneDaemon) SetDetector

func (d *ImmuneDaemon) SetDetector(detector *AnomalyDetector)

SetDetector sets the anomaly detector engine.

func (*ImmuneDaemon) SetMigrateFunc

func (d *ImmuneDaemon) SetMigrateFunc(fn MigrateFunc)

SetMigrateFunc sets the function used to spawn migration target processes.

func (*ImmuneDaemon) SetReputationStore

func (d *ImmuneDaemon) SetReputationStore(rs *ReputationStore)

SetReputationStore sets the reputation store for migration candidate scoring.

func (*ImmuneDaemon) SetSuspendFunc

func (d *ImmuneDaemon) SetSuspendFunc(fn func(pid types.PID) error)

SetSuspendFunc sets the callback used to suspend (SIGPAUSE) a process. If nil, anomalies are recorded but processes are not suspended.

func (*ImmuneDaemon) Start

func (d *ImmuneDaemon) Start() error

Start initializes the ImmuneDaemon and loads existing NormalProfiles and threat signatures.

func (*ImmuneDaemon) Stop

func (d *ImmuneDaemon) Stop()

Stop shuts down the ImmuneDaemon.

func (*ImmuneDaemon) SuspendedPIDs

func (d *ImmuneDaemon) SuspendedPIDs() []types.PID

SuspendedPIDs returns the PIDs of all processes that have active anomaly alerts. These are the processes that have been suspended due to detected anomalies.

func (*ImmuneDaemon) UpdateSimilarityMatrix

func (d *ImmuneDaemon) UpdateSimilarityMatrix(agents map[string][]string)

UpdateSimilarityMatrix recomputes the similarity matrix with the given agent-skill mapping.

func (*ImmuneDaemon) Uptime

func (d *ImmuneDaemon) Uptime() time.Duration

Uptime returns the duration since the daemon was started. Returns 0 if the daemon is nil or not running.

type ImmuneStore

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

ImmuneStore manages behavior sample persistence and NormalProfile read/write. Data is stored in baseDir (typically $PROJECT/.rnix/immune/).

func NewImmuneStore

func NewImmuneStore(baseDir string) *ImmuneStore

NewImmuneStore creates a new ImmuneStore rooted at baseDir.

func (*ImmuneStore) GetSamples

func (s *ImmuneStore) GetSamples(agentTemplate string) ([]BehaviorSample, error)

GetSamples reads all historical behavior samples for the given agent template. Returns an empty slice if no file exists.

func (*ImmuneStore) LoadAllProfiles

func (s *ImmuneStore) LoadAllProfiles() (map[string]*NormalProfile, error)

LoadAllProfiles loads all saved NormalProfiles from the profiles directory.

func (*ImmuneStore) LoadProfile

func (s *ImmuneStore) LoadProfile(agentTemplate string) (*NormalProfile, error)

LoadProfile loads a NormalProfile from disk. Returns nil, nil if the file does not exist (not an error).

func (*ImmuneStore) LoadThreats

func (s *ImmuneStore) LoadThreats() ([]ThreatSignature, error)

LoadThreats loads all threat signatures from the threat memory file. Returns an empty slice if the file does not exist.

func (*ImmuneStore) RecordSample

func (s *ImmuneStore) RecordSample(sample BehaviorSample) error

RecordSample appends a behavior sample to the agent template's JSONL file.

func (*ImmuneStore) SaveProfile

func (s *ImmuneStore) SaveProfile(profile *NormalProfile) error

SaveProfile saves a NormalProfile to disk as a complete JSON file.

func (*ImmuneStore) SaveThreat

func (s *ImmuneStore) SaveThreat(sig ThreatSignature) error

SaveThreat appends a threat signature to the threat memory (threats.jsonl).

type InitConfig

type InitConfig struct {
	Services    []ServiceConfig    `yaml:"services"`
	Supervisors []SupervisorConfig `yaml:"supervisors"`
}

InitConfig holds the init bootstrap configuration.

func DefaultInitConfig

func DefaultInitConfig() *InitConfig

DefaultInitConfig returns an empty config for when no rnix-init.yaml exists.

func LoadInitConfig

func LoadInitConfig(path string) (*InitConfig, error)

LoadInitConfig reads and parses a rnix-init.yaml file. If the file does not exist, returns DefaultInitConfig().

type InitResult

type InitResult struct {
	Started  []string
	Warnings []string
	Failed   []ServiceError
}

InitResult holds the outcome of a bootstrap sequence.

func Bootstrap

func Bootstrap(k *KernelImpl, cfg *InitConfig, agentLoader AgentLoaderFunc) (*InitResult, error)

Bootstrap executes the init sequence: services first, then supervisors. Returns InitResult on success (may contain warnings for optional failures). Returns error if any required service or supervisor fails.

type KernelCallbacks

type KernelCallbacks interface {
	OnSpawn(pid types.PID, intent, provider, model, uuid string)
	OnStep(pid types.PID, step int, total int)
	OnStepComplete(pid types.PID, step int, action string, summary string, hasError bool, durationMs float64)
	OnComplete(pid types.PID, result string, exit ExitStatus)
	OnError(pid types.PID, err error)
}

KernelCallbacks allows the CLI layer to receive progress notifications from the kernel without introducing a reverse dependency on internal/ui.

type KernelImpl

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

KernelImpl is the core microkernel implementation.

func NewKernel

func NewKernel(v *vfs.VFS, ctxMgr *rnixctx.Manager, cb KernelCallbacks) *KernelImpl

NewKernel creates a new KernelImpl with the given VFS, context manager, and optional callbacks.

func (*KernelImpl) AddProcess

func (k *KernelImpl) AddProcess(p *Process)

AddProcess registers a process in the kernel's process table.

func (*KernelImpl) FindHistoryByPID added in v0.7.1

func (k *KernelImpl) FindHistoryByPID(pid types.PID) *vfs.ProcInfo

FindHistoryByPID returns the most recent history snapshot for a reaped process, or nil.

func (*KernelImpl) FindHistoryByUUID added in v0.7.1

func (k *KernelImpl) FindHistoryByUUID(uuid string) *vfs.ProcInfo

FindHistoryByUUID returns the most recent history snapshot for the given UUID, or nil.

func (*KernelImpl) GetBudgetStatus

func (k *KernelImpl) GetBudgetStatus(groupID types.PGID) (*BudgetPoolStatus, error)

GetBudgetStatus returns a snapshot of the budget pool for the given group.

func (*KernelImpl) GetDebugChan

func (k *KernelImpl) GetDebugChan(pid types.PID) (chan types.SyscallEvent, bool)

GetDebugChan safely retrieves the debug channel for a process under lock.

func (*KernelImpl) GetLineage

func (k *KernelImpl) GetLineage(pid types.PID) ([]LineageEvent, error)

GetLineage returns the lineage events for the given PID.

func (*KernelImpl) GetLogChan

func (k *KernelImpl) GetLogChan(pid types.PID) (chan types.LogEntry, bool)

GetLogChan safely retrieves the log channel for a process under lock.

func (*KernelImpl) GetLogHistory

func (k *KernelImpl) GetLogHistory(pid types.PID) ([]types.LogEntry, bool)

GetLogHistory returns a copy of the log history for a process.

func (*KernelImpl) GetProcGroup

func (k *KernelImpl) GetProcGroup(groupID types.PGID) ([]types.PID, error)

GetProcGroup returns the list of PIDs in a process group.

func (*KernelImpl) GetProcInfo

func (k *KernelImpl) GetProcInfo(pid types.PID) (*vfs.ProcInfo, error)

GetProcInfo returns a snapshot of process information for the given PID.

func (*KernelImpl) GetProcess

func (k *KernelImpl) GetProcess(pid types.PID) (*Process, bool)

GetProcess retrieves a process by PID.

func (*KernelImpl) GetProcessByUUID added in v0.7.0

func (k *KernelImpl) GetProcessByUUID(uuid string) (*Process, bool)

GetProcessByUUID finds a process by UUID in the process table.

func (*KernelImpl) GetRecordManager

func (k *KernelImpl) GetRecordManager() *debug.RecordManager

GetRecordManager returns the record manager.

func (*KernelImpl) GetSLAResults

func (k *KernelImpl) GetSLAResults(groupID types.PGID) ([]*SLAResult, error)

GetSLAResults returns the SLA evaluation results for a compose group (Story 21.2).

func (*KernelImpl) GetSpanID

func (k *KernelImpl) GetSpanID(pid types.PID) (types.SpanID, bool)

GetSpanID returns the SpanID for the given process, if it has one.

func (*KernelImpl) GetStepDataDir added in v0.7.0

func (k *KernelImpl) GetStepDataDir() string

GetStepDataDir returns the base directory for step data output.

func (*KernelImpl) GetTokenHistory

func (k *KernelImpl) GetTokenHistory(pid types.PID) ([]types.TokenSnapshot, error)

GetTokenHistory returns a copy of the token usage history for a process.

func (*KernelImpl) JoinGroup

func (k *KernelImpl) JoinGroup(pid types.PID, groupID types.PGID) error

JoinGroup adds a process to a process group. The group is auto-created if it doesn't exist.

func (*KernelImpl) JoinThread

func (k *KernelImpl) JoinThread(parentPID types.PID, tid types.TID) error

JoinThread waits for the specified thread to complete and cleans up its resources.

func (*KernelImpl) Kill

func (k *KernelImpl) Kill(pid types.PID, signal types.Signal) error

Kill sends a signal to the target process.

func (*KernelImpl) LeaveGroup

func (k *KernelImpl) LeaveGroup(pid types.PID, groupID types.PGID) error

LeaveGroup removes a process from a process group. The group is auto-destroyed if empty.

func (*KernelImpl) ListAllProcs added in v0.7.0

func (k *KernelImpl) ListAllProcs() []vfs.ProcInfo

ListAllProcs returns the union of active processes and historical processes.

func (*KernelImpl) ListProcesses

func (k *KernelImpl) ListProcesses() []*Process

ListProcesses returns all processes currently in the process table.

func (*KernelImpl) ListProcs

func (k *KernelImpl) ListProcs() []vfs.ProcInfo

ListProcs returns snapshots of all processes in the process table.

func (*KernelImpl) LoadHistory added in v0.7.1

func (k *KernelImpl) LoadHistory() error

LoadHistory loads process history from disk into the in-memory ring buffer.

func (*KernelImpl) Mount

func (k *KernelImpl) Mount(path string, config vfs.MCPConfig) error

Mount mounts an MCP server at the given path via the MountManager.

func (*KernelImpl) Pipe

func (k *KernelImpl) Pipe(writerPID, readerPID types.PID) (writeFD, readFD types.FD, err error)

Pipe creates a unidirectional data channel between two processes. The writeFD is registered in the writer's fdTable, and readFD in the reader's.

func (*KernelImpl) Reap

func (k *KernelImpl) Reap(pid types.PID)

Reap triggers cleanup of a zombie process by PID. Safe to call even if the process has already been reaped (idempotent via reapOnce). This is used by the IPC server to reap top-level processes (PPID=0) after spawn streaming completes, since no CLI Wait() call exists in daemon mode.

func (*KernelImpl) RecordSLAResult

func (k *KernelImpl) RecordSLAResult(groupID types.PGID, result *SLAResult)

RecordSLAResult appends an SLA evaluation result for a compose group (Story 21.2).

func (*KernelImpl) Recv

func (k *KernelImpl) Recv(pid types.PID) (*Message, error)

Recv blocks until a message is available for the given process.

func (*KernelImpl) RegisterBudgetPool

func (k *KernelImpl) RegisterBudgetPool(groupID types.PGID, pool *BudgetPool)

RegisterBudgetPool associates a BudgetPool with a process group.

func (*KernelImpl) RemoveProcess

func (k *KernelImpl) RemoveProcess(pid types.PID)

RemoveProcess removes a process from the process table.

func (*KernelImpl) ResumeCoroutine

func (k *KernelImpl) ResumeCoroutine(parentPID types.PID, coID types.CoID) (any, error)

ResumeCoroutine resumes a suspended coroutine and returns the next yielded value or final result.

Protocol:

  • First call after SpawnCoroutine: reads the initial yield value from yieldCh
  • Subsequent calls: sends resume signal first (unblocking the coroutine), then reads next yield/completion
  • When coroutine completes: detects closed yieldCh and returns the final result

func (*KernelImpl) Send

func (k *KernelImpl) Send(senderPID, targetPID types.PID, data []byte) error

Send delivers a message from senderPID to targetPID.

func (*KernelImpl) SetAgentLoader

func (k *KernelImpl) SetAgentLoader(loader func(name string) (*agents.AgentInfo, error))

SetAgentLoader injects the agent loading function for autonomous spawn.

func (*KernelImpl) SetDefaultProvider

func (k *KernelImpl) SetDefaultProvider(name string)

SetDefaultProvider injects the default LLM provider name.

func (*KernelImpl) SetDiffMemory

func (k *KernelImpl) SetDiffMemory(m *DiffMemory)

SetDiffMemory injects the differentiation memory for stem agent path reuse.

func (*KernelImpl) SetImmuneDaemon

func (k *KernelImpl) SetImmuneDaemon(d *ImmuneDaemon)

SetImmuneDaemon injects the immune daemon for behavioral monitoring (Story 22.1).

func (*KernelImpl) SetMountManager

func (k *KernelImpl) SetMountManager(mgr MountManager)

SetMountManager sets the MCP mount manager on the kernel.

func (*KernelImpl) SetProviderResolver

func (k *KernelImpl) SetProviderResolver(names func() []string, has func(name string) bool)

SetProviderResolver injects callbacks for dynamic LLM provider validation.

func (*KernelImpl) SetRecordManager

func (k *KernelImpl) SetRecordManager(mgr *debug.RecordManager)

SetRecordManager sets the execution recording manager on the kernel.

func (*KernelImpl) SetSkillLoader

func (k *KernelImpl) SetSkillLoader(fn func(string) (*skills.SkillInfo, error))

SetSkillLoader injects the skill loading function for stem agent differentiation.

func (*KernelImpl) SetSpanWriter

func (k *KernelImpl) SetSpanWriter(w *debug.SpanWriter)

SetSpanWriter sets the optional SpanWriter for persisting completed spans.

func (*KernelImpl) SetStemMatcher

func (k *KernelImpl) SetStemMatcher(m *StemMatcher)

SetStemMatcher injects the stem agent matcher for auto-differentiation.

func (*KernelImpl) SetStepDataDir added in v0.7.0

func (k *KernelImpl) SetStepDataDir(dir string)

SetStepDataDir overrides the base directory for StepWriter output.

func (*KernelImpl) Shutdown

func (k *KernelImpl) Shutdown()

Shutdown stops the reaper goroutine, unmounts all MCP servers, closes all active recordings, and waits for exit. Safe to call multiple times — only the first call closes stopCh.

func (*KernelImpl) SigBlock

func (k *KernelImpl) SigBlock(pid types.PID, sig types.Signal) error

SigBlock blocks a signal for the target process.

func (*KernelImpl) SigUnblock

func (k *KernelImpl) SigUnblock(pid types.PID, sig types.Signal) error

SigUnblock unblocks a signal for the target process. If there was a pending signal of this type, it is immediately delivered.

func (*KernelImpl) Signal

func (k *KernelImpl) Signal(pid types.PID, sig types.Signal) error

Signal delivers a signal to the target process.

func (*KernelImpl) SignalGroup

func (k *KernelImpl) SignalGroup(groupID types.PGID, signal types.Signal) error

SignalGroup sends a signal to all processes in a group.

func (*KernelImpl) Spawn

func (k *KernelImpl) Spawn(intent string, agent *agents.AgentInfo, opts SpawnOpts) (types.PID, error)

Spawn creates a new agent process that automatically executes the reasonStep loop.

func (*KernelImpl) SpawnCoroutine

func (k *KernelImpl) SpawnCoroutine(parentPID types.PID, fn CoroutineFunc) (types.CoID, error)

SpawnCoroutine creates a new coroutine within the parent process.

func (*KernelImpl) SpawnSupervisor

func (k *KernelImpl) SpawnSupervisor(spec SupervisorSpec) (types.PID, error)

SpawnSupervisor creates a Supervisor process that manages child processes.

func (*KernelImpl) SpawnThread

func (k *KernelImpl) SpawnThread(parentPID types.PID, intent string) (types.TID, error)

SpawnThread creates a new thread within the parent process and launches a goroutine.

func (*KernelImpl) StartRecording

func (k *KernelImpl) StartRecording(pid types.PID) (string, error)

StartRecording starts execution recording for the given PID.

func (*KernelImpl) StopRecording

func (k *KernelImpl) StopRecording(pid types.PID) error

StopRecording stops execution recording for the given PID.

func (*KernelImpl) Unmount

func (k *KernelImpl) Unmount(path string) error

Unmount unmounts the MCP server at the given path.

func (*KernelImpl) UnregisterBudgetPool

func (k *KernelImpl) UnregisterBudgetPool(groupID types.PGID)

UnregisterBudgetPool removes a BudgetPool association.

func (*KernelImpl) Wait

func (k *KernelImpl) Wait(pid types.PID) (ExitStatus, error)

Wait blocks until the target process enters Zombie state, then performs the complete resource release sequence and returns the ExitStatus. Returns *SyscallError with ErrNotFound if the PID does not exist.

func (*KernelImpl) Yield

func (k *KernelImpl) Yield(parentPID types.PID, coID types.CoID, value any) error

Yield is called externally to yield a value from a coroutine. Note: In practice, the coroutine yields via the yield function passed to CoroutineFunc. This method is provided for the ConcurrencyManager interface.

type Lineage

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

Lineage tracks the complete differentiation history for a process.

func NewLineage

func NewLineage() *Lineage

NewLineage creates a new empty Lineage.

func (*Lineage) Events

func (l *Lineage) Events() []LineageEvent

Events returns a copy of all lineage events in order.

func (*Lineage) Record

func (l *Lineage) Record(event LineageEvent)

Record appends a lineage event.

type LineageEvent

type LineageEvent struct {
	Timestamp  time.Time `json:"timestamp"`
	Phase      string    `json:"phase"`       // "initial" | "progressive"
	Skills     []string  `json:"skills"`      // skills loaded in this step
	Trigger    string    `json:"trigger"`     // intent or reason that triggered this differentiation
	FromMemory bool      `json:"from_memory"` // true if reused from DiffMemory
}

LineageEvent records a single differentiation step in a process's lineage.

type Message

type Message struct {
	FromPID   types.PID
	ToPID     types.PID
	Seq       types.MsgSeq
	Data      []byte
	CreatedAt time.Time
	TraceID   types.TraceID
	SpanID    types.SpanID
}

Message is a kernel-internal inter-process message.

type MessageQueue

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

MessageQueue is a per-process receive queue for IPC messages.

type MigrateFunc

type MigrateFunc func(intent string, agentName string, contextMessages []string) (types.PID, error)

MigrateFunc is the function signature for spawning a migration target process.

type MigrationResult

type MigrationResult struct {
	OriginalPID   types.PID `json:"original_pid"`
	OriginalAgent string    `json:"original_agent"`
	TargetAgent   string    `json:"target_agent"`
	NewPID        types.PID `json:"new_pid"`
	Similarity    float64   `json:"similarity"`
	DurationMs    int64     `json:"duration_ms"`
	Success       bool      `json:"success"`
	Reason        string    `json:"reason"` // failure reason (empty on success)
}

MigrationResult records the outcome of a capability migration attempt.

type MountManager

type MountManager interface {
	Mount(path string, config vfs.MCPConfig) error
	Unmount(path string) error
	UnmountAll() error
}

MountManager defines the interface for mounting/unmounting MCP servers.

type NormalProfile

type NormalProfile struct {
	AgentTemplate    string             `json:"agent_template"`
	SampleCount      int                `json:"sample_count"`
	SyscallMean      map[string]float64 `json:"syscall_mean"`
	SyscallStdDev    map[string]float64 `json:"syscall_std_dev"`
	TokenRateMean    float64            `json:"token_rate_mean"`
	TokenRateStdDev  float64            `json:"token_rate_std_dev"`
	DurationMeanMs   float64            `json:"duration_mean_ms"`
	DurationStdDevMs float64            `json:"duration_std_dev_ms"`
	LastUpdated      time.Time          `json:"last_updated"`
}

NormalProfile describes the normal behavior range for an agent template. Computed from historical BehaviorSample data using statistical methods.

func ComputeProfile

func ComputeProfile(agentTemplate string, samples []BehaviorSample, minSamples int) *NormalProfile

ComputeProfile builds a NormalProfile from historical behavior samples. Returns nil if fewer than minSamples samples are provided.

type Priority

type Priority int

Priority defines agent priority for budget allocation. Higher values receive proportionally more quota.

const (
	PriorityLow    Priority = 1
	PriorityNormal Priority = 5
	PriorityHigh   Priority = 10
)

func ParsePriority

func ParsePriority(s string) Priority

ParsePriority converts a priority string to a Priority value. Returns PriorityNormal for empty or unrecognized strings.

type ProcGroup

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

ProcGroup is the internal representation of a process group.

func (*ProcGroup) Add

func (g *ProcGroup) Add(pid types.PID)

func (*ProcGroup) Contains

func (g *ProcGroup) Contains(pid types.PID) bool

func (*ProcGroup) Members

func (g *ProcGroup) Members() []types.PID

func (*ProcGroup) Remove

func (g *ProcGroup) Remove(pid types.PID) bool

func (*ProcGroup) Size

func (g *ProcGroup) Size() int

type ProcGroupManager

type ProcGroupManager interface {
	JoinGroup(pid types.PID, groupID types.PGID) error
	LeaveGroup(pid types.PID, groupID types.PGID) error
	GetProcGroup(groupID types.PGID) ([]types.PID, error)
	SignalGroup(groupID types.PGID, signal types.Signal) error
}

ProcGroupManager manages process groups and batch signaling.

type Process

type Process struct {
	PID            types.PID
	UUID           string // UUID v7 — immutable after creation, globally unique across daemon restarts
	PPID           types.PID
	State          types.ProcessState // guarded by mu
	Intent         string             // immutable after creation
	Skills         []string
	Children       []types.PID
	FDTable        map[types.FD]vfs.VFSFile // per architecture doc; VFS manages actual FD state internally
	DebugChan      chan types.SyscallEvent
	LogChan        chan types.LogEntry
	Done           chan ExitStatus
	CreatedAt      time.Time
	DeadAt         time.Time   // set by reapProcess, used for TTL cleanup
	Exit           *ExitStatus // non-nil in Zombie/Dead
	CtxID          types.CtxID // context allocated by Spawn
	Result         string      // final output from reasoning
	TokensUsed     int         // cumulative token consumption
	ContextBudget  int         // 0 = no limit; >0 = terminate when TokensUsed >= ContextBudget
	MaxSteps       int         // max reasoning steps for this process (from SpawnOpts.MaxTurns or DefaultMaxSteps)
	AllowedDevices []string    // nil/empty = all devices allowed; non-empty = whitelist only
	MCPMounts      []string    // MCP mount paths auto-mounted by Spawn
	TraceID        types.TraceID
	SpanID         types.SpanID
	ParentSpanID   types.SpanID
	HasToolError   bool // true if any tool call failed (mu protected)

	// Fallback configuration (Story 23.5)
	FallbackModel    string // fallback model name
	FallbackProvider string // fallback provider name; "" = same as primary
	FallbackDevice   string // resolved fallback VFS device path; "" = no fallback
	PrimaryDevice    string // primary VFS device path (e.g. "/dev/llm/claude")
	Provider         string // resolved provider name (immutable after spawn)
	Model            string // resolved model name (immutable after spawn)
	PlanningEnabled  bool   // true = inject planProtocol; derived from agent manifest Planning field

	// Observation system (Story 27.1)
	FinalSystemPrompt string // Full system prompt captured on first reasonStep (mu protected)

	// Native tool calling support (immutable after Spawn)
	UseNativeTools bool // true when LLM driver implements ToolCallingDriver

	// Project configuration (Story 25.3) — immutable after spawn, no locking needed
	ProjectConfig *config.ProjectConfig
	// contains filtered or unexported fields
}

Process represents an agent process.

func NewProcess

func NewProcess(ppid types.PID, intent string, skills []string) *Process

NewProcess creates a new process in the Created state with a unique PID.

func (*Process) AddBreakpoint

func (p *Process) AddBreakpoint(bp *Breakpoint) int

AddBreakpoint registers a breakpoint on the process and returns its assigned ID.

func (*Process) AddChild

func (p *Process) AddChild(pid types.PID)

AddChild appends a child PID to the Children slice (thread-safe).

func (*Process) AddCoroutine

func (p *Process) AddCoroutine(c *Coroutine)

AddCoroutine registers a coroutine in the process's coroutine table.

func (*Process) AddGdbSkill

func (p *Process) AddGdbSkill(name string)

AddGdbSkill adds a skill name to the gdb extra skills list. Idempotent. Thread-safe.

func (*Process) AddGroup

func (p *Process) AddGroup(pgid types.PGID)

AddGroup adds a process group ID to the process's group list (idempotent, thread-safe).

func (*Process) AddPending

func (p *Process) AddPending(sig types.Signal)

AddPending adds the signal to the pending set.

func (*Process) AddThread

func (p *Process) AddThread(t *Thread)

AddThread registers a thread in the process's thread table.

func (*Process) AppendLogHistory

func (p *Process) AppendLogHistory(entry types.LogEntry)

AppendLogHistory adds a log entry to the ring buffer. Caller must hold p.mu.

func (*Process) AppendTokenSnapshot

func (p *Process) AppendTokenSnapshot(step, tokens int)

AppendTokenSnapshot records token usage at the current step. Thread-safe.

func (*Process) BlockSignal

func (p *Process) BlockSignal(sig types.Signal)

BlockSignal adds the signal to the blocked set.

func (*Process) Cancel

func (p *Process) Cancel()

Cancel cancels the process context, signaling the reasoning goroutine to stop.

func (*Process) CancelledCh

func (p *Process) CancelledCh() <-chan struct{}

CancelledCh returns a channel that is closed when the process context is cancelled. Returns nil if the process has no context.

func (*Process) CheckBreakpoint

func (p *Process) CheckBreakpoint(ctx BreakpointContext) *Breakpoint

CheckBreakpoint evaluates all enabled breakpoints of the matching type. Returns the first matching breakpoint (with HitCount incremented), or nil.

func (*Process) ClearCoroutines

func (p *Process) ClearCoroutines()

ClearCoroutines cleans up all coroutines by closing their resume channels. Used during process reap.

Coroutine goroutines can be blocked at two points:

  1. co.yieldCh <- value (inside yield closure, waiting for caller to read)
  2. <-co.resumeCh (inside yield closure, waiting for caller to resume)

Closing resumeCh unblocks case 2. For case 1, the goroutine will panic on send to closed channel if we close yieldCh, so we use a drain goroutine to consume from yieldCh, which unblocks the sender, then the coroutine proceeds to <-resumeCh which returns zero value (closed channel).

func (*Process) ClearPending

func (p *Process) ClearPending(sig types.Signal)

ClearPending removes the signal from the pending set.

func (*Process) ClearSignalState

func (p *Process) ClearSignalState()

ClearSignalState cleans up all signal state (handlers, blocked, pending, resume channel). Used during process reap.

func (*Process) ClearStepMode

func (p *Process) ClearStepMode()

ClearStepMode resets the step mode to StepNone. Thread-safe.

func (*Process) ClearThreads

func (p *Process) ClearThreads()

ClearThreads cancels all threads and waits for them to finish. Used during process reap.

func (*Process) Finish added in v0.7.0

func (p *Process) Finish(result string, code int, err error)

Finish is a test convenience that records a result, writes to Done, and transitions to Zombie.

func (*Process) GdbPause

func (p *Process) GdbPause(reason string, hitBP *Breakpoint, extraArgs ...map[string]any)

GdbPause blocks the calling goroutine until GdbResume is called. Sends a GdbPause event to DebugChan before blocking. extraArgs are merged into the event args (e.g., syscall_name, step_number).

func (*Process) GdbPauseCh

func (p *Process) GdbPauseCh() <-chan struct{}

GdbPauseCh returns the gdb pause channel, or nil if not paused.

func (*Process) GdbResume

func (p *Process) GdbResume()

GdbResume unblocks a GdbPause. Idempotent (no-op if not paused).

func (*Process) GetChildren

func (p *Process) GetChildren() []types.PID

GetChildren returns a copy of the Children slice (thread-safe).

func (*Process) GetCoroutine

func (p *Process) GetCoroutine(coID types.CoID) (*Coroutine, bool)

GetCoroutine retrieves a coroutine by CoID from the process's coroutine table.

func (*Process) GetDetailSnapshot added in v0.7.0

func (p *Process) GetDetailSnapshot() DetailSnapshot

GetDetailSnapshot returns a thread-safe copy of process detail fields.

func (*Process) GetFDSnapshot added in v0.7.0

func (p *Process) GetFDSnapshot() []FDSnapshot

GetFDSnapshot returns a thread-safe snapshot of the current FD table. Collects FD-to-file references under lock, then calls Stat() outside the lock to avoid potential deadlock if a VFS driver acquires another lock in Stat().

func (*Process) GetFinalSystemPrompt added in v0.7.0

func (p *Process) GetFinalSystemPrompt() string

GetFinalSystemPrompt returns the captured system prompt (thread-safe).

func (*Process) GetGdbEnvVars

func (p *Process) GetGdbEnvVars() map[string]string

GetGdbEnvVars returns a copy of the gdb environment variables. Thread-safe.

func (*Process) GetGdbExtraSkills

func (p *Process) GetGdbExtraSkills() []string

GetGdbExtraSkills returns a copy of the gdb extra skills list. Thread-safe.

func (*Process) GetGdbModelOverride

func (p *Process) GetGdbModelOverride() string

GetGdbModelOverride returns the current model override. Thread-safe. Returns empty string if no override is set.

func (*Process) GetGroups

func (p *Process) GetGroups() []types.PGID

GetGroups returns a copy of the process's group membership list (thread-safe).

func (*Process) GetHandler

func (p *Process) GetHandler(sig types.Signal) (SignalHandler, bool)

GetHandler returns the custom handler for the given signal, if any.

func (*Process) GetLineage

func (p *Process) GetLineage() *Lineage

GetLineage returns the process lineage, or nil if not a differentiated process.

func (*Process) GetLogHistory

func (p *Process) GetLogHistory() []types.LogEntry

GetLogHistory returns a time-ordered copy of the log history. Caller must hold p.mu.

func (*Process) GetNativeToolDefs added in v0.7.0

func (p *Process) GetNativeToolDefs() []vfs.ToolDef

GetNativeToolDefs returns the native tool definitions (immutable after Spawn).

func (*Process) GetPID

func (p *Process) GetPID() types.PID

GetPID returns the process's own PID. This is the Rnix equivalent of Unix getpid(2). Since PID is immutable after creation, no locking is required.

func (*Process) GetProjectConfig added in v0.7.0

func (p *Process) GetProjectConfig() *config.ProjectConfig

GetProjectConfig returns the project config (immutable after Spawn).

func (*Process) GetState

func (p *Process) GetState() types.ProcessState

GetState returns the current process state in a thread-safe manner.

func (*Process) GetStepMode

func (p *Process) GetStepMode() StepMode

GetStepMode returns the current single-step mode. Thread-safe.

func (*Process) GetThread

func (p *Process) GetThread(tid types.TID) (*Thread, bool)

GetThread retrieves a thread by TID from the process's thread table.

func (*Process) GetTokenHistory

func (p *Process) GetTokenHistory() []types.TokenSnapshot

GetTokenHistory returns a time-ordered copy of the token history. Thread-safe.

func (*Process) HasPending

func (p *Process) HasPending(sig types.Signal) bool

HasPending reports whether the signal is in the pending set.

func (*Process) IsBlocked

func (p *Process) IsBlocked(sig types.Signal) bool

IsBlocked reports whether the signal is in the blocked set.

func (*Process) IsCancelled

func (p *Process) IsCancelled() bool

IsCancelled returns true if the process context has been cancelled.

func (*Process) IsGdbPaused

func (p *Process) IsGdbPaused() bool

IsGdbPaused reports whether the process is currently paused by gdb.

func (*Process) IsPaused

func (p *Process) IsPaused() bool

IsPaused reports whether the process is currently paused.

func (*Process) ListBreakpoints

func (p *Process) ListBreakpoints() []*Breakpoint

ListBreakpoints returns a copy of all registered breakpoints.

func (*Process) Pause

func (p *Process) Pause()

Pause creates a resumeCh channel, putting the process into paused state. Idempotent — if already paused, this is a no-op.

func (*Process) Reap

func (p *Process) Reap() error

Reap transitions the process from Zombie to Dead.

func (*Process) RemoveBreakpoint

func (p *Process) RemoveBreakpoint(id int) bool

RemoveBreakpoint removes the breakpoint with the given ID. Returns true if found.

func (*Process) RemoveChild

func (p *Process) RemoveChild(pid types.PID)

RemoveChild removes a child PID from the Children slice (thread-safe).

func (*Process) RemoveCoroutine

func (p *Process) RemoveCoroutine(coID types.CoID)

RemoveCoroutine removes a coroutine from the process's coroutine table.

func (*Process) RemoveGroup

func (p *Process) RemoveGroup(pgid types.PGID)

RemoveGroup removes a process group ID from the process's group list (thread-safe).

func (*Process) RemoveThread

func (p *Process) RemoveThread(tid types.TID)

RemoveThread removes a thread from the process's thread table.

func (*Process) Resume

func (p *Process) Resume()

Resume closes the resumeCh channel, unblocking any goroutine waiting on WaitIfPaused. Idempotent — if not paused, this is a no-op.

func (*Process) SetFinalSystemPrompt added in v0.7.0

func (p *Process) SetFinalSystemPrompt(s string)

SetFinalSystemPrompt sets the captured system prompt (thread-safe).

func (*Process) SetGdbEnv

func (p *Process) SetGdbEnv(key, value string)

SetGdbEnv sets an environment variable in the gdb env vars map. Thread-safe.

func (*Process) SetGdbModelOverride

func (p *Process) SetGdbModelOverride(model string)

SetGdbModelOverride sets the model override for LLM requests. Thread-safe. An empty string clears the override.

func (*Process) SetHandler

func (p *Process) SetHandler(sig types.Signal, handler SignalHandler)

SetHandler registers a custom signal handler for the given signal.

func (*Process) SetLineage

func (p *Process) SetLineage(l *Lineage)

SetLineage sets the process lineage.

func (*Process) SetNativeToolDefs added in v0.7.0

func (p *Process) SetNativeToolDefs(defs []vfs.ToolDef)

SetNativeToolDefs sets the native tool definitions.

func (*Process) SetStepMode

func (p *Process) SetStepMode(mode StepMode)

SetStepMode sets the single-step execution mode. Thread-safe.

func (*Process) Start

func (p *Process) Start() error

Start transitions the process from Created to Running.

func (*Process) Terminate

func (p *Process) Terminate(exit ExitStatus) error

Terminate transitions the process from Running to Zombie and records the exit status.

func (*Process) Transition

func (p *Process) Transition(target types.ProcessState) error

Transition attempts to move the process to the target state. Returns *SyscallError if the transition is illegal.

func (*Process) UnblockSignal

func (p *Process) UnblockSignal(sig types.Signal) bool

UnblockSignal removes the signal from the blocked set and returns whether there was a pending signal of this type.

func (*Process) WaitIfPaused

func (p *Process) WaitIfPaused() <-chan struct{}

WaitIfPaused returns the resume channel if the process is paused. Returns nil if not paused (caller should skip select).

type ProcessHistory added in v0.7.0

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

ProcessHistory stores snapshots of processes that have been removed from the process table by the reaper. It acts as a bounded FIFO ring buffer protected by a RWMutex so the reaper can write while the Dashboard reads concurrently.

func LoadProcHistory added in v0.7.1

func LoadProcHistory(baseDir string, maxSize int) (*ProcessHistory, error)

LoadProcHistory scans <baseDir>/data/steps/*/proc-info.json and returns a ProcessHistory populated with the most recent maxSize entries (sorted by CreatedAt). Missing or corrupt files are skipped with a warning log.

func NewProcessHistory added in v0.7.0

func NewProcessHistory(maxSize int) *ProcessHistory

NewProcessHistory creates a ProcessHistory with the given capacity.

func (*ProcessHistory) Add added in v0.7.0

func (h *ProcessHistory) Add(info vfs.ProcInfo)

Add appends a process snapshot. If the buffer is full, the oldest entry is evicted (FIFO).

func (*ProcessHistory) FindByPID added in v0.7.1

func (h *ProcessHistory) FindByPID(pid types.PID) *vfs.ProcInfo

FindByPID returns the most recent snapshot for the given PID, or nil if not found.

func (*ProcessHistory) FindByUUID added in v0.7.1

func (h *ProcessHistory) FindByUUID(uuid string) *vfs.ProcInfo

FindByUUID returns the most recent snapshot for the given UUID, or nil if not found.

func (*ProcessHistory) Len added in v0.7.0

func (h *ProcessHistory) Len() int

Len returns the current number of stored entries.

func (*ProcessHistory) List added in v0.7.0

func (h *ProcessHistory) List() []vfs.ProcInfo

List returns a deep copy of all stored snapshots.

type ProcessManager

type ProcessManager interface {
	Spawn(intent string, agent *agents.AgentInfo, opts SpawnOpts) (types.PID, error)
	Kill(pid types.PID, signal types.Signal) error
	Wait(pid types.PID) (ExitStatus, error)
}

ProcessManager defines the kernel's process management interface.

type QualityCondition

type QualityCondition struct {
	Mode     QualityMode
	Pattern  *regexp.Regexp // used when Mode == QualityModePattern
	EvalExpr string         // used when Mode == QualityModeEval
}

QualityCondition matches based on LLM response content.

func (*QualityCondition) Match

func (c *QualityCondition) Match(ctx BreakpointContext) bool

type QualityMode

type QualityMode int

QualityMode distinguishes pattern-match vs eval-based quality breakpoints.

const (
	QualityModePattern QualityMode = 1
	QualityModeEval    QualityMode = 2
)

type ReasonAction

type ReasonAction struct {
	Type     ActionType
	Content  string
	ToolPath string
	ToolData []byte
}

ReasonAction represents a parsed action from an LLM response.

type ReasoningCondition

type ReasoningCondition struct{}

ReasoningCondition always matches (triggers on every reasoning step).

func (*ReasoningCondition) Match

type ReputationRecord

type ReputationRecord struct {
	SLAResult *SLAResult `json:"sla_result"`
	Timestamp time.Time  `json:"timestamp"`
}

ReputationRecord records a single SLA evaluation for persistence.

type ReputationStore

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

ReputationStore manages agent reputation data via JSON Lines files.

func NewReputationStore

func NewReputationStore(baseDir string) *ReputationStore

NewReputationStore creates a new ReputationStore rooted at baseDir.

func (*ReputationStore) GetAllSummaries

func (rs *ReputationStore) GetAllSummaries() ([]ReputationSummary, error)

GetAllSummaries returns reputation summaries for all known agents, sorted by Score descending.

func (*ReputationStore) GetHistory

func (rs *ReputationStore) GetHistory(agentName string) ([]ReputationRecord, error)

GetHistory reads the reputation history for the given agent. Returns an empty (non-nil) slice if no file exists.

func (*ReputationStore) GetSummary

func (rs *ReputationStore) GetSummary(agentName string) (*ReputationSummary, error)

GetSummary computes a reputation summary for the given agent. Returns a default neutral summary (Score=0.5) if no records exist.

func (*ReputationStore) ListAgents

func (rs *ReputationStore) ListAgents() ([]string, error)

ListAgents returns agent names from all .json files in the reputation store directory. Returns an empty slice if the directory does not exist.

func (*ReputationStore) RecordResult

func (rs *ReputationStore) RecordResult(agentName string, result *SLAResult) error

RecordResult appends an SLA evaluation result to the agent's reputation file. The file is created (with parent directories) if it does not exist. Format: JSON Lines (one JSON object per line).

func (*ReputationStore) SelectBest

func (rs *ReputationStore) SelectBest(candidates []string) (string, error)

SelectBest returns the agent name with the highest reputation score from the given candidates. If all candidates have the same default score, the first candidate is returned (deterministic). Returns an error if the candidates list is empty.

type ReputationSummary

type ReputationSummary struct {
	AgentName     string  `json:"agent_name"`
	Score         float64 `json:"score"`           // 综合声誉分 0.0~1.0
	SuccessRate   float64 `json:"success_rate"`    // SLA 通过率
	AvgTokens     int     `json:"avg_tokens"`      // 平均 token 消耗
	AvgDurationMs int64   `json:"avg_duration_ms"` // 平均执行时长
	TotalRecords  int     `json:"total_records"`   // 总评估次数
	RecentTrend   string  `json:"recent_trend"`    // "improving" | "declining" | "stable"
}

ReputationSummary holds a computed reputation summary for an agent.

type RestartStrategy

type RestartStrategy string

RestartStrategy defines how a Supervisor responds to child failures.

const (
	OneForOne  RestartStrategy = "one_for_one"
	OneForAll  RestartStrategy = "one_for_all"
	RestForOne RestartStrategy = "rest_for_one"
)

type SLACheckResult

type SLACheckResult struct {
	Name   string `json:"name"` // check name ("max_tokens", "max_duration_ms", "output_format")
	Passed bool   `json:"passed"`
	Actual string `json:"actual"` // actual value as string
	Limit  string `json:"limit"`  // SLA limit value as string
}

SLACheckResult records the result of a single SLA constraint check.

type SLAResult

type SLAResult struct {
	AgentName   string           `json:"agent_name"`
	Passed      bool             `json:"passed"` // true if all checks passed
	Checks      []SLACheckResult `json:"checks"`
	EvaluatedAt time.Time        `json:"evaluated_at"`
	TokensUsed  int              `json:"tokens_used"`
	DurationMs  int64            `json:"duration_ms"`
}

SLAResult records the complete SLA evaluation result.

type SLASpec

type SLASpec struct {
	MaxTokens     int    `yaml:"max_tokens,omitempty" json:"max_tokens,omitempty"`
	MaxDurationMs int64  `yaml:"max_duration_ms,omitempty" json:"max_duration_ms,omitempty"`
	OutputFormat  string `yaml:"output_format,omitempty" json:"output_format,omitempty"` // "json" | "markdown" | "" (any)
}

SLASpec defines contract SLA constraints for agent execution.

func (*SLASpec) Evaluate

func (s *SLASpec) Evaluate(agentName string, tokensUsed int, durationMs int64, output string) *SLAResult

Evaluate checks the SLA against actual execution metrics. Only non-zero constraints are evaluated. Returns an SLAResult with individual check results and an overall Passed flag.

func (*SLASpec) IsEmpty

func (s *SLASpec) IsEmpty() bool

IsEmpty returns true if no SLA constraints are defined.

type ServiceConfig

type ServiceConfig struct {
	Name     string         `yaml:"name"`
	Type     string         `yaml:"type"`
	Required bool           `yaml:"required"`
	Config   map[string]any `yaml:"config"`
}

ServiceConfig describes a service to initialize during bootstrap.

type ServiceError

type ServiceError struct {
	Service  string
	Err      error
	Recovery string
}

ServiceError records a service initialization failure.

type ServiceInitializer

type ServiceInitializer interface {
	Name() string
	Init(cfg map[string]any) error
}

ServiceInitializer defines the interface for init-time service setup.

type SignalHandler

type SignalHandler func(types.Signal)

SignalHandler is a custom signal handler function.

type SignalManager

type SignalManager interface {
	Signal(pid types.PID, sig types.Signal) error
	SigBlock(pid types.PID, sig types.Signal) error
	SigUnblock(pid types.PID, sig types.Signal) error
}

SignalManager manages signal delivery, blocking, and handling.

type SimilarityMatrix

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

SimilarityMatrix stores pairwise agent similarity scores.

func NewSimilarityMatrix

func NewSimilarityMatrix() *SimilarityMatrix

NewSimilarityMatrix creates a new empty SimilarityMatrix.

func (*SimilarityMatrix) Compute

func (m *SimilarityMatrix) Compute(agents map[string][]string, coopHistory map[string]map[string]int)

Compute calculates the similarity matrix from agent skill mappings and cooperation history. agents maps agentName -> skillNames list. coopHistory maps agentA -> agentB -> cooperation count.

func (*SimilarityMatrix) Get

func (m *SimilarityMatrix) Get(agentA, agentB string) *CapabilitySimilarity

Get returns the similarity between two agents, or nil if not found.

func (*SimilarityMatrix) GetSimilar

func (m *SimilarityMatrix) GetSimilar(agentName string, minScore float64) []CapabilitySimilarity

GetSimilar returns agents similar to agentName with Score >= minScore, sorted by Score descending.

type SpawnOpts

type SpawnOpts struct {
	Model         string
	SystemPrompt  string
	MaxTurns      int
	TimeoutMs     int64
	ParentPID     types.PID     // parent process PID; 0 = top-level/CLI spawn
	ContextBudget int           // 0 = no limit; >0 = terminate when TokensUsed >= ContextBudget
	TraceID       types.TraceID // inherited trace ID; empty = no tracing
	ParentSpanID  types.SpanID  // parent process span ID
	Provider      string        // LLM provider override (from CLI --provider); "" = use agent manifest or default "claude"

	PreallocatedCtxID types.CtxID           // non-zero = skip CtxAlloc, use this pre-setup context
	SkipReasonLoop    bool                  // true = don't open LLM device or start reasonStep goroutine
	ProjectConfig     *config.ProjectConfig // project-level config snapshot; nil = global only
}

SpawnOpts configures optional parameters for Spawn.

type StemMatcher

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

StemMatcher matches intents to skill combinations using keyword analysis.

func NewStemMatcher

func NewStemMatcher(discovery *skills.SkillDiscovery) *StemMatcher

NewStemMatcher creates a StemMatcher using a SkillDiscovery instance.

func NewStemMatcherFromFunc

func NewStemMatcherFromFunc(discoverFn func() ([]skills.SkillInfo, error)) *StemMatcher

NewStemMatcherFromFunc creates a StemMatcher with a custom discovery function (for testing).

func (*StemMatcher) Match

func (m *StemMatcher) Match(intent string) ([]string, error)

Match analyzes the intent and returns skill names ordered by relevance (descending score). Returns an empty list (not an error) if no skills match.

type StepMode

type StepMode int

StepMode controls single-step execution for gdb debugging.

const (
	StepNone      StepMode = 0 // no step mode active (zero value)
	StepSyscall   StepMode = 1 // step to next syscall
	StepReasoning StepMode = 2 // step to next reasoning iteration
)

type StepWriter added in v0.7.0

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

StepWriter writes StepRecord entries as NDJSON to disk. STUB: Created for ATDD red phase — implements structure per AC-2, not yet wired into kernel.

func NewStepWriter added in v0.7.0

func NewStepWriter(baseDir string, procUUID string) (*StepWriter, error)

NewStepWriter creates a StepWriter that writes to .rnix/data/steps/<uuid>/steps.jsonl.

func (*StepWriter) Close added in v0.7.0

func (sw *StepWriter) Close() error

Close flushes and closes the underlying file.

func (*StepWriter) WriteStep added in v0.7.0

func (sw *StepWriter) WriteStep(rec types.StepRecord) error

WriteStep marshals and appends a StepRecord as a single NDJSON line.

type Supervisor

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

Supervisor manages a set of child processes with automatic restart.

type SupervisorConfig

type SupervisorConfig struct {
	Name        string        `yaml:"name"`
	Strategy    string        `yaml:"strategy"`
	MaxRestarts int           `yaml:"max_restarts"`
	MaxWindow   time.Duration `yaml:"max_window"`
	Required    bool          `yaml:"required"`
	Children    []ChildConfig `yaml:"children"`
}

SupervisorConfig describes a Supervisor tree to build during bootstrap.

type SupervisorManager

type SupervisorManager interface {
	SpawnSupervisor(spec SupervisorSpec) (types.PID, error)
}

SupervisorManager defines the interface for spawning Supervisor processes.

type SupervisorSpec

type SupervisorSpec struct {
	Strategy    RestartStrategy
	MaxRestarts int
	MaxWindow   time.Duration
	Children    []ChildSpec
}

SupervisorSpec configures a Supervisor's behavior.

type SynergyComboKey

type SynergyComboKey string

SynergyComboKey represents a deterministic identifier for a set of skills. Skills are sorted alphabetically and joined with commas.

func NewComboKey

func NewComboKey(skills []string) SynergyComboKey

NewComboKey creates a deterministic combo key from a list of skill names. Names are sorted alphabetically and joined with commas, ensuring {A,B} and {B,A} produce the same key.

type SynergyMatrix

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

SynergyMatrix manages skill combination historical performance data. Data is persisted as JSON Lines in $PROJECT/.rnix/reputation/synergy-matrix.json.

func NewSynergyMatrix

func NewSynergyMatrix(reputationDir string) *SynergyMatrix

NewSynergyMatrix creates a new SynergyMatrix using the given reputation directory.

func (*SynergyMatrix) GetAllRecords

func (m *SynergyMatrix) GetAllRecords() ([]SynergyRecord, error)

GetAllRecords reads all historical records from the synergy matrix file. Returns an empty (non-nil) slice if no file exists.

func (*SynergyMatrix) GetComboSummaries

func (m *SynergyMatrix) GetComboSummaries() ([]ComboSummary, error)

GetComboSummaries computes aggregated statistics for all skill combinations. Results are sorted: recommended combos first, then by success rate descending.

func (*SynergyMatrix) RecordCombo

func (m *SynergyMatrix) RecordCombo(record SynergyRecord) error

RecordCombo appends a combo execution record to the synergy matrix file.

type SynergyRecord

type SynergyRecord struct {
	ComboKey   SynergyComboKey `json:"combo_key"`
	Skills     []string        `json:"skills"`
	Passed     bool            `json:"passed"`
	TokensUsed int             `json:"tokens_used"`
	DurationMs int64           `json:"duration_ms"`
	Timestamp  time.Time       `json:"timestamp"`
}

SynergyRecord records a single skill combination execution result.

type SyscallCondition

type SyscallCondition struct {
	Name string
}

SyscallCondition matches when the syscall name equals Name.

func (*SyscallCondition) Match

func (c *SyscallCondition) Match(ctx BreakpointContext) bool

type SyscallError

type SyscallError struct {
	Syscall string
	PID     types.PID
	Device  string
	Err     error
	Code    types.ErrCode
}

SyscallError represents an error that occurred during a syscall.

func NewSyscallError

func NewSyscallError(syscall string, pid types.PID, device string, err error, code types.ErrCode) *SyscallError

NewSyscallError creates a new SyscallError.

func (*SyscallError) Error

func (e *SyscallError) Error() string

Error returns a formatted error string: [Code] PID N Syscall: Device (Err)

func (*SyscallError) Unwrap

func (e *SyscallError) Unwrap() error

Unwrap returns the underlying error for use with errors.Is and errors.As.

type SyscallEventDisk added in v0.7.1

type SyscallEventDisk struct {
	TimestampMs float64        `json:"ts_ms"`
	PID         uint64         `json:"pid"`
	Syscall     string         `json:"syscall"`
	Args        map[string]any `json:"args,omitempty"`
	Result      any            `json:"result,omitempty"`
	Error       string         `json:"error,omitempty"`
	DurationMs  float64        `json:"dur_ms"`
	TraceID     string         `json:"trace_id,omitempty"`
	SpanID      string         `json:"span_id,omitempty"`
}

SyscallEventDisk is the JSON-serializable representation of a SyscallEvent on disk.

func ReadAllEvents added in v0.7.1

func ReadAllEvents(path string) ([]SyscallEventDisk, error)

ReadAllEvents reads all syscall events from an events.jsonl file.

type Thread

type Thread struct {
	TID       types.TID
	ParentPID types.PID
	Intent    string
	State     types.ProcessState // reuses Created/Running/Zombie/Dead
	Done      chan struct{}      // closed when thread finishes
	Result    string
	Err       error
	// contains filtered or unexported fields
}

Thread represents a lightweight execution unit that shares its parent process's context space.

func (*Thread) Finish

func (t *Thread) Finish(result string, err error)

Finish marks the thread as completed with the given result and error.

func (*Thread) Start

func (t *Thread) Start()

Start transitions the thread to Running state.

type ThreatSignature

type ThreatSignature struct {
	ID            string      `json:"id"`
	Type          AnomalyType `json:"type"`
	AgentTemplate string      `json:"agent_template"`
	Metric        string      `json:"metric"`    // specific metric name (e.g., syscall name "Open", or "token_rate")
	Threshold     float64     `json:"threshold"` // deviation multiplier that triggered this signature
	CreatedAt     time.Time   `json:"created_at"`
}

ThreatSignature describes a known anomalous behavior pattern (antibody memory).

type TopologyNode

type TopologyNode struct {
	Agent           string  `json:"agent"`
	ReputationScore float64 `json:"reputation_score"`
	Connections     int     `json:"connections"` // number of edges involving this node
}

TopologyNode represents an agent in the collaboration topology.

Jump to

Keyboard shortcuts

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