tools

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 31, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Overview

Package tools — Apathy Detection and Apoptosis Recovery (DIP H1.4).

This file implements:

  1. ApathyDetector — analyzes text signals for infrastructure apathy patterns (blocked responses, 403 errors, semantic filters, forced resets)
  2. ApoptosisRecovery — on critical entropy, saves genome hash to protected sector for cross-session recovery

Package tools provides application-level tool services that bridge domain logic with MCP tool handlers.

Package tools provides application-level tool services. This file adds the Intent Distiller MCP tool integration (DIP H0.2).

Index

Constants

This section is empty.

Variables

View Source
var (
	Version   = "2.0.0-dev"
	GitCommit = "unknown"
	BuildDate = "unknown"
)

Version info set at build time via ldflags.

Functions

func ToJSON

func ToJSON(v interface{}) string

ToJSON marshals any value to indented JSON string.

Types

type AddEdgeParams

type AddEdgeParams struct {
	FromID   string `json:"from_id"`
	ToID     string `json:"to_id"`
	EdgeType string `json:"edge_type"` // justifies, causes, constrains
}

AddEdgeParams holds parameters for the add_causal_edge tool.

type AddFactParams

type AddFactParams struct {
	Content string `json:"content"`
	Level   int    `json:"level"`
	Domain  string `json:"domain,omitempty"`
	Module  string `json:"module,omitempty"`
	CodeRef string `json:"code_ref,omitempty"`
}

AddFactParams holds parameters for the add_fact tool.

type AddGeneParams

type AddGeneParams struct {
	Content string `json:"content"`
	Domain  string `json:"domain,omitempty"`
}

AddGeneParams holds parameters for the add_gene tool.

type AddNodeParams

type AddNodeParams struct {
	NodeType string `json:"node_type"` // decision, reason, consequence, constraint, alternative, assumption
	Content  string `json:"content"`
}

AddNodeParams holds parameters for the add_causal_node tool.

type ApathyResult

type ApathyResult struct {
	IsApathetic    bool           `json:"is_apathetic"`   // Apathy detected
	Signals        []ApathySignal `json:"signals"`        // Detected signals
	TotalScore     float64        `json:"total_score"`    // Aggregate apathy score
	Recommendation string         `json:"recommendation"` // Suggested action
	Entropy        float64        `json:"entropy"`        // Text entropy
	Timestamp      time.Time      `json:"timestamp"`
}

ApathyResult holds the result of apathy analysis.

func DetectApathy

func DetectApathy(text string) *ApathyResult

DetectApathy analyzes text for infrastructure apathy signals.

type ApathySignal

type ApathySignal struct {
	Pattern    string  `json:"pattern"`    // Matched pattern name
	Confidence float64 `json:"confidence"` // Detection confidence 0.0-1.0
	Evidence   string  `json:"evidence"`   // Fragment that triggered detection
	Severity   string  `json:"severity"`   // "low", "medium", "high", "critical"
}

ApathySignal represents a detected infrastructure apathy pattern.

type ApoptosisRecoveryResult

type ApoptosisRecoveryResult struct {
	GenomeHash     string    `json:"genome_hash"`      // Preserved Merkle hash
	GeneCount      int       `json:"gene_count"`       // Number of genes preserved
	SessionSaved   bool      `json:"session_saved"`    // Session state saved
	EntropyAtDeath float64   `json:"entropy_at_death"` // Entropy level that triggered apoptosis
	RecoveryKey    string    `json:"recovery_key"`     // Key for cross-session recovery
	Timestamp      time.Time `json:"timestamp"`
}

ApoptosisRecoveryResult holds the result of apoptosis recovery.

func TriggerApoptosisRecovery

func TriggerApoptosisRecovery(ctx context.Context, store memory.FactStore, currentEntropy float64) (*ApoptosisRecoveryResult, error)

TriggerApoptosisRecovery performs graceful session death with genome preservation. On critical entropy, it:

  1. Computes and stores the genome Merkle hash
  2. Saves current session state as a recovery snapshot
  3. Returns a recovery key for the next session to pick up

type CausalService

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

CausalService implements MCP tool logic for causal reasoning chains.

func NewCausalService

func NewCausalService(store causal.CausalStore) *CausalService

NewCausalService creates a new CausalService.

func (*CausalService) AddEdge

func (s *CausalService) AddEdge(ctx context.Context, params AddEdgeParams) (*causal.Edge, error)

AddEdge creates a new causal edge.

func (*CausalService) AddNode

func (s *CausalService) AddNode(ctx context.Context, params AddNodeParams) (*causal.Node, error)

AddNode creates a new causal node.

func (*CausalService) GetChain

func (s *CausalService) GetChain(ctx context.Context, query string, maxDepth int) (*causal.Chain, error)

GetChain retrieves a causal chain for a decision matching the query.

func (*CausalService) GetStats

func (s *CausalService) GetStats(ctx context.Context) (*causal.CausalStats, error)

GetStats returns causal store statistics.

type CompressFactsParams

type CompressFactsParams struct {
	IDs     []string `json:"fact_ids"`
	Summary string   `json:"summary"`
}

CompressFactsParams holds parameters for the compress_facts tool.

type CrystalService

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

CrystalService implements MCP tool logic for code crystal operations.

func NewCrystalService

func NewCrystalService(store crystal.CrystalStore) *CrystalService

NewCrystalService creates a new CrystalService.

func (*CrystalService) GetCrystal

func (s *CrystalService) GetCrystal(ctx context.Context, path string) (*crystal.Crystal, error)

GetCrystal retrieves a crystal by path.

func (*CrystalService) GetCrystalStats

func (s *CrystalService) GetCrystalStats(ctx context.Context) (*crystal.CrystalStats, error)

GetCrystalStats returns crystal store statistics.

func (*CrystalService) ListCrystals

func (s *CrystalService) ListCrystals(ctx context.Context, pattern string, limit int) ([]*crystal.Crystal, error)

ListCrystals lists crystals matching a path pattern.

func (*CrystalService) SearchCrystals

func (s *CrystalService) SearchCrystals(ctx context.Context, query string, limit int) ([]*crystal.Crystal, error)

SearchCrystals searches crystals by content/primitives.

func (*CrystalService) Store

func (s *CrystalService) Store() crystal.CrystalStore

Store returns the underlying CrystalStore for direct access.

type DashboardData

type DashboardData struct {
	Health    *HealthStatus          `json:"health"`
	FactStats *memory.FactStoreStats `json:"fact_stats,omitempty"`
}

DashboardData holds summary data for the system dashboard.

type DecisionRecorder

type DecisionRecorder interface {
	RecordDecision(module, decision, reason string)
}

DecisionRecorder is the interface for recording tamper-evident decisions (v3.7). Implemented by audit.DecisionLogger. Optional — nil-safe callers should check.

type DistillIntentParams

type DistillIntentParams struct {
	Text string `json:"text"`
}

DistillIntentParams holds parameters for the distill_intent tool.

type DoctorCheck

type DoctorCheck struct {
	Name    string `json:"name"`
	Status  string `json:"status"` // "OK", "WARN", "FAIL"
	Details string `json:"details,omitempty"`
	Elapsed string `json:"elapsed"`
}

DoctorCheck represents a single diagnostic check result.

type DoctorReport

type DoctorReport struct {
	Timestamp time.Time     `json:"timestamp"`
	Checks    []DoctorCheck `json:"checks"`
	Summary   string        `json:"summary"` // "HEALTHY", "DEGRADED", "CRITICAL"
}

DoctorReport is the full self-diagnostic report (v3.7).

func (DoctorReport) JSON

func (r DoctorReport) JSON() string

ToJSON is already in the package. Alias for DoctorReport.

type DoctorService

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

DoctorService provides self-diagnostic capabilities (v3.7 Cerebro).

func NewDoctorService

func NewDoctorService(db *sql.DB, rlmDir string, facts *FactService) *DoctorService

NewDoctorService creates the doctor diagnostic service.

func (*DoctorService) RunDiagnostics

func (d *DoctorService) RunDiagnostics(ctx context.Context) DoctorReport

RunDiagnostics performs all self-diagnostic checks.

func (*DoctorService) SetEmbedderName

func (d *DoctorService) SetEmbedderName(name string)

SetEmbedderName sets the Oracle model name for diagnostics.

func (*DoctorService) SetSOCChecker

func (d *DoctorService) SetSOCChecker(c SOCHealthChecker)

SetSOCChecker sets the SOC health checker for diagnostics (v3.9).

type FactService

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

FactService implements MCP tool logic for hierarchical fact operations.

func NewFactService

func NewFactService(store memory.FactStore, cache memory.HotCache) *FactService

NewFactService creates a new FactService.

func (*FactService) AddFact

func (s *FactService) AddFact(ctx context.Context, params AddFactParams) (*memory.Fact, error)

AddFact creates a new hierarchical fact.

func (*FactService) AddGene

func (s *FactService) AddGene(ctx context.Context, params AddGeneParams) (*memory.Fact, error)

AddGene creates an immutable genome fact (L0 only). Once created, a gene cannot be updated, deleted, or marked stale. Genes represent survival invariants — the DNA of the system.

func (*FactService) CompressFacts

func (s *FactService) CompressFacts(ctx context.Context, params CompressFactsParams) (string, error)

CompressFacts archives the given facts and creates a summary fact. Genes are silently skipped (invariant protection).

func (*FactService) DeleteFact

func (s *FactService) DeleteFact(ctx context.Context, id string) error

DeleteFact deletes a fact by ID.

func (*FactService) GetColdFacts

func (s *FactService) GetColdFacts(ctx context.Context, limit int) ([]*memory.Fact, error)

GetColdFacts returns facts with hit_count=0, created >30 days ago. Genes are excluded. Use for memory hygiene review.

func (*FactService) GetFact

func (s *FactService) GetFact(ctx context.Context, id string) (*memory.Fact, error)

GetFact retrieves a fact by ID.

func (*FactService) GetL0Facts

func (s *FactService) GetL0Facts(ctx context.Context) ([]*memory.Fact, error)

GetL0Facts returns L0 facts from cache (fast path) or store.

func (*FactService) GetStale

func (s *FactService) GetStale(ctx context.Context, includeArchived bool) ([]*memory.Fact, error)

GetStale returns stale facts.

func (*FactService) GetStats

func (s *FactService) GetStats(ctx context.Context) (*memory.FactStoreStats, error)

GetStats returns fact store statistics.

func (*FactService) ListDomains

func (s *FactService) ListDomains(ctx context.Context) ([]string, error)

ListDomains returns all unique domains.

func (*FactService) ListFacts

func (s *FactService) ListFacts(ctx context.Context, params ListFactsParams) ([]*memory.Fact, error)

ListFacts lists facts by domain or level.

func (*FactService) ListGenes

func (s *FactService) ListGenes(ctx context.Context) ([]*memory.Fact, error)

ListGenes returns all genome facts (immutable survival invariants).

func (*FactService) ProcessExpired

func (s *FactService) ProcessExpired(ctx context.Context) (int, error)

ProcessExpired handles expired TTL facts.

func (*FactService) SearchFacts

func (s *FactService) SearchFacts(ctx context.Context, query string, limit int) ([]*memory.Fact, error)

SearchFacts searches facts by content.

func (*FactService) SetDecisionRecorder

func (s *FactService) SetDecisionRecorder(r DecisionRecorder)

SetDecisionRecorder injects the decision recorder.

func (*FactService) Store

func (s *FactService) Store() memory.FactStore

Store returns the underlying FactStore for direct access by subsystems (e.g., apoptosis recovery that needs raw store operations).

func (*FactService) UpdateFact

func (s *FactService) UpdateFact(ctx context.Context, params UpdateFactParams) (*memory.Fact, error)

UpdateFact updates a fact.

func (*FactService) VerifyGenome

func (s *FactService) VerifyGenome(ctx context.Context) (string, int, error)

VerifyGenome computes the Merkle hash of all genes and returns integrity status.

type HealthStatus

type HealthStatus struct {
	Status    string `json:"status"`
	Version   string `json:"version"`
	GoVersion string `json:"go_version"`
	Uptime    string `json:"uptime"`
	OS        string `json:"os"`
	Arch      string `json:"arch"`
}

HealthStatus holds the health check result.

type IntentService

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

IntentService provides MCP tool logic for intent distillation.

func NewIntentService

func NewIntentService(embedder vectorstore.Embedder) *IntentService

NewIntentService creates a new IntentService. If embedder is nil, the service will be unavailable.

func (*IntentService) DistillIntent

func (s *IntentService) DistillIntent(ctx context.Context, params DistillIntentParams) (*intent.DistillResult, error)

DistillIntent performs recursive intent distillation on user text.

func (*IntentService) IsAvailable

func (s *IntentService) IsAvailable() bool

IsAvailable returns true if the intent distiller is ready.

type ListFactsParams

type ListFactsParams struct {
	Domain       string `json:"domain,omitempty"`
	Level        *int   `json:"level,omitempty"`
	IncludeStale bool   `json:"include_stale,omitempty"`
}

ListFactsParams holds parameters for the list_facts tool.

type ProjectPulse

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

ProjectPulse generates auto-documentation from L0/L1 facts (v3.7 Cerebro). Extracts facts from memory, groups by domain, and produces a structured markdown report reflecting the current state of the project.

func NewProjectPulse

func NewProjectPulse(facts *FactService) *ProjectPulse

NewProjectPulse creates an auto-documentation generator.

func (*ProjectPulse) Generate

func (p *ProjectPulse) Generate(ctx context.Context) (*PulseReport, error)

Generate produces a documentation report from L0 (project) and L1 (domain) facts.

type PulseReport

type PulseReport struct {
	GeneratedAt time.Time      `json:"generated_at"`
	ProjectName string         `json:"project_name"`
	Sections    []PulseSection `json:"sections"`
	TotalFacts  int            `json:"total_facts"`
	Markdown    string         `json:"markdown"`
}

PulseReport is the full auto-generated documentation.

type PulseSection

type PulseSection struct {
	Domain string   `json:"domain"`
	Facts  []string `json:"facts"`
	Count  int      `json:"count"`
}

PulseSection is a domain section of the auto-generated documentation.

type SOCDashboardData

type SOCDashboardData struct {
	TotalEvents      int  `json:"total_events"`
	CorrelationRules int  `json:"correlation_rules"`
	Playbooks        int  `json:"playbooks"`
	ChainValid       bool `json:"chain_valid"`
	SensorsOnline    int  `json:"sensors_online"`
	SensorsTotal     int  `json:"sensors_total"`
}

SOCDashboardData mirrors the dashboard KPIs needed for doctor checks.

type SOCHealthChecker

type SOCHealthChecker interface {
	Dashboard() (SOCDashboardData, error)
}

SOCHealthChecker is an interface for SOC health diagnostics. Implemented by application/soc.Service to avoid circular imports.

type SaveStateParams

type SaveStateParams struct {
	SessionID string  `json:"session_id"`
	GoalDesc  string  `json:"goal_description,omitempty"`
	Progress  float64 `json:"progress,omitempty"`
}

SaveStateParams holds parameters for the save_state tool.

type SessionService

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

SessionService implements MCP tool logic for cognitive state operations.

func NewSessionService

func NewSessionService(store session.StateStore) *SessionService

NewSessionService creates a new SessionService.

func (*SessionService) DeleteSession

func (s *SessionService) DeleteSession(ctx context.Context, sessionID string) (int, error)

DeleteSession removes all versions of a session.

func (*SessionService) GetAuditLog

func (s *SessionService) GetAuditLog(ctx context.Context, sessionID string, limit int) ([]session.AuditEntry, error)

GetAuditLog returns the audit log for a session.

func (*SessionService) GetCompactState

func (s *SessionService) GetCompactState(ctx context.Context, sessionID string, maxTokens int) (string, error)

GetCompactState returns a compact text representation of the current state.

func (*SessionService) ListSessions

func (s *SessionService) ListSessions(ctx context.Context) ([]session.SessionInfo, error)

ListSessions returns all persisted sessions.

func (*SessionService) LoadState

func (s *SessionService) LoadState(ctx context.Context, sessionID string, version *int) (*session.CognitiveStateVector, string, error)

LoadState loads the latest (or specific version) of a session state.

func (*SessionService) RestoreOrCreate

func (s *SessionService) RestoreOrCreate(ctx context.Context, sessionID string) (*session.CognitiveStateVector, bool, error)

RestoreOrCreate loads an existing session or creates a new one.

func (*SessionService) SaveState

func (s *SessionService) SaveState(ctx context.Context, state *session.CognitiveStateVector) error

SaveState saves a cognitive state vector.

type SuggestSynapsesResult

type SuggestSynapsesResult struct {
	ID         int64   `json:"id"`
	FactIDA    string  `json:"fact_id_a"`
	FactIDB    string  `json:"fact_id_b"`
	Confidence float64 `json:"confidence"`
}

SuggestSynapsesResult contains a pending synapse for architect review.

type SynapseService

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

SynapseService implements MCP tool logic for synapse operations.

func NewSynapseService

func NewSynapseService(store synapse.SynapseStore) *SynapseService

NewSynapseService creates a new SynapseService.

func (*SynapseService) AcceptSynapse

func (s *SynapseService) AcceptSynapse(ctx context.Context, id int64) error

AcceptSynapse transitions a synapse from PENDING to VERIFIED. Only VERIFIED synapses influence context ranking.

func (*SynapseService) GetStats

func (s *SynapseService) GetStats(ctx context.Context) (*SynapseStats, error)

GetStats returns synapse counts.

func (*SynapseService) RejectSynapse

func (s *SynapseService) RejectSynapse(ctx context.Context, id int64) error

RejectSynapse transitions a synapse from PENDING to REJECTED.

func (*SynapseService) SetDecisionRecorder

func (s *SynapseService) SetDecisionRecorder(r DecisionRecorder)

SetDecisionRecorder injects the decision recorder into SynapseService.

func (*SynapseService) SuggestSynapses

func (s *SynapseService) SuggestSynapses(ctx context.Context, limit int) ([]SuggestSynapsesResult, error)

SuggestSynapses returns pending synapses for architect approval.

type SynapseStats

type SynapseStats struct {
	Pending  int `json:"pending"`
	Verified int `json:"verified"`
	Rejected int `json:"rejected"`
}

SynapseStats returns counts by status.

type SystemService

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

SystemService implements MCP tool logic for system operations.

func NewSystemService

func NewSystemService(factStore memory.FactStore) *SystemService

NewSystemService creates a new SystemService.

func (*SystemService) Dashboard

func (s *SystemService) Dashboard(ctx context.Context) (*DashboardData, error)

Dashboard returns a summary of all system metrics.

func (*SystemService) GetVersion

func (s *SystemService) GetVersion() *VersionInfo

GetVersion returns version information.

func (*SystemService) Health

func (s *SystemService) Health(_ context.Context) *HealthStatus

Health returns server health status.

type UpdateFactParams

type UpdateFactParams struct {
	ID      string  `json:"id"`
	Content *string `json:"content,omitempty"`
	IsStale *bool   `json:"is_stale,omitempty"`
}

UpdateFactParams holds parameters for the update_fact tool.

type VersionInfo

type VersionInfo struct {
	Version   string `json:"version"`
	GitCommit string `json:"git_commit"`
	BuildDate string `json:"build_date"`
	GoVersion string `json:"go_version"`
}

VersionInfo holds version information.

Jump to

Keyboard shortcuts

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