goncho

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: May 22, 2026 License: MIT Imports: 34 Imported by: 0

README

Goncho

High-trust local memory for Go-native AI agent runtimes.

Goncho is the memory kernel for agent hosts that need durable local state, auditability, scoped recall, review warnings, and live-verification discipline without a Python service, Docker sidecar, hosted memory API, vector database wrapper, or giant tool catalog.

It is designed for the Trebuchet local-first agent stack:

  • Gormes — a Go-native AI agent runtime for Linux, Windows, macOS, and Termux on Android. One binary runs providers, tools, skills, sessions, local memory, chat, and gateways with no Python or Docker required.
  • Navivox — an Android app in development that turns a phone into an AI agent server with local memory, chat, and gateways.
  • Goncho — the high-trust memory layer underneath: evidence, claims, scoped temporal beliefs, context packs, review queues, and live verification.

Goncho's rule is simple:

evidence before belief
live verification before action

If memory says a file exists, verify it. If memory says a migration was approved, verify it. If memory says an API path still exists, verify it. Goncho treats memory as orientation until current evidence says it is safe to act.

Use Goncho as an embedded Go module:

go get github.com/TrebuchetDynamics/goncho@latest

From a checkout, verify the reproducible benchmark CLI builds and starts when you need local retrieval reports:

make install-smoke

The root module is a library package, not a root go install target; goncho-bench is the installable command in ./cmd/goncho-bench. Public @latest currently resolves to v0.1.0, published May 20, 2026, so use the checkout-local command until the next v0.1.x tag contains the benchmark CLI.

Go Reference

Package Status

Goncho is pre-1.0, but it has the public release signals needed to evaluate it as an ecosystem component: a tagged v0.1.0 release published May 20, 2026, a valid Go module, pkg.go.dev API docs, public docs, reproducible benchmark commands, deterministic benchmark methodology, and stable-ID backend comparison artifacts. The LOCOMO backend comparison is conversation-scoped so duplicate content in other conversations cannot win by content alone. Benchmark methodology, the external adapter contract, and current agentmemory PR #583 stable-ID status live in Retrieval Benchmarks.

Verify public release metadata, local Go module metadata, package documentation, public docs site build, external importability, and the checkout-local benchmark CLI without editing another project:

make ecosystem-smoke

For the narrower public release metadata proof only, run make public-release-smoke; it checks the documented public @latest version and published date from go list -m -json. For the narrower local go.mod metadata proof only, run make local-module-smoke; it checks the module path and Go version from go list -m -json. For the narrower package documentation proof only, run make package-doc-smoke; it checks that local package docs render through go doc .. For the narrower public docs site proof only, run make docs-site-smoke; it checks the local docs-site build with npm run build. For the narrower external import proof only, run make public-module-smoke. For the CI-safe external backend comparison proof, run make bench-locomo-backends-smoke.

Use go get github.com/TrebuchetDynamics/goncho@latest to depend on the library package. For the command-line benchmark runner, use make install-smoke or go install ./cmd/goncho-bench from this checkout until the next v0.1.x tag includes the CLI.


Why Goncho

Most agent memory systems optimize for breadth: more connectors, more tools, more autonomous behavior. Goncho optimizes for trust: memory correctness, bounded writes, reproducible retrieval, local state, and verification before action.

Goncho exists because Gormes and Navivox need memory that can run anywhere the agent runs: a workstation, small server, Windows laptop, WSL2 shell, macOS terminal, or Android phone through Termux. The memory layer cannot assume Python packaging, Docker, Redis, hosted vector infrastructure, or always-online cloud services.

Goncho is inspired by broad integration systems like agentmemory, but it makes a different product bet:

agentmemory: broad integration layer
Gormes:      Go-native agent runtime
Navivox:     Android agent server
Goncho:      high-trust local memory kernel

The core abstraction is not “top-k chunks in a prompt.” It is:

raw evidence
  -> claims
  -> scoped temporal beliefs
  -> task-specific orientation
  -> agent action
  -> review, verification, revision, or forgetting

Vectors and search are useful. They are not the source of truth. Retrieval can suggest; verification decides.


Where Goncho Fits

Navivox Android app
  -> Gormes Go runtime
    -> Goncho local memory
    -> chat gateways
    -> providers, tools, skills

Gormes owns the agent runtime: provider turns, tools, skills, profiles, sessions, TUI, dashboard, and chat gateways. Goncho owns memory integrity: what was observed, what was concluded, which profile can read it, whether it may be stale, and what must be verified before action.

Navivox brings that stack onto Android. The phone becomes a local agent server: chat interface, gateway hub, and memory-bearing runtime. Goncho's job in that environment is to keep memory useful without requiring a heavyweight server deployment.

The boundary is intentional:

Layer Responsibility
Navivox Android app, mobile UX, phone-hosted agent server, local chat and gateway controls.
Gormes Go-native agent runtime, providers, tools, skills, profiles, sessions, TUI/dashboard, gateways.
Goncho Local memory kernel, scoped recall, evidence capture, review warnings, stale-claim verification, handoffs.

What Goncho Provides

Capability Status
Embedded Go service Implemented
SQLite local storage Implemented
Profile, search, context, chat, conclude APIs Implemented
Honcho-compatible primitives Implemented
MCP-style memory tools Implemented
Public tools: context, search, remember, review, handoff Implemented
Multi-profile memory isolation Implemented
Gormes profile directories Implemented
Prompt-injection quarantine Implemented
Stale code-claim verification Implemented
Negative drift anchors Implemented
Review queues Experimental
Graph/cognitive-map layer Planned
PostgreSQL team adapter Planned

Quick Start

package main

import (
    "context"
    "fmt"

    "github.com/TrebuchetDynamics/goncho"
    "github.com/TrebuchetDynamics/goncho/memory"
)

func main() {
    ctx := context.Background()

    store, err := memory.OpenSqlite("memory.db", 0, nil)
    if err != nil {
        panic(err)
    }
    defer func() { _ = store.Close(ctx) }()

    if err := goncho.RunMigrations(store.DB()); err != nil {
        panic(err)
    }

    svc := goncho.NewService(store.DB(), goncho.Config{
        WorkspaceID:    "my-agent",
        ObserverPeerID: "assistant",
    }, nil)

    _, err = svc.Conclude(ctx, goncho.ConcludeParams{
        ProfileID:  "mineru",
        Peer:       "telegram:12345",
        Conclusion: "User prefers SQLite over hosted vector services.",
    })
    if err != nil {
        panic(err)
    }

    pack, err := svc.Context(ctx, goncho.ContextParams{
        ProfileID: "mineru",
        Peer:      "telegram:12345",
        Query:     "database preferences",
        MaxTokens: 2000,
    })
    if err != nil {
        panic(err)
    }

    fmt.Println(pack.Representation)
}

Core API

Common embedded calls:

svc := goncho.NewService(db, cfg, log)

profile, err := svc.Profile(ctx, "telegram:12345")

err = svc.SetProfile(ctx, "telegram:12345", []string{
    "Prefers concise status reports",
})

results, err := svc.Search(ctx, goncho.SearchParams{
    ProfileID: "mineru",
    Peer:      "telegram:12345",
    Query:     "deployment preferences",
    Limit:     5,
})

pack, err := svc.Context(ctx, goncho.ContextParams{
    ProfileID: "mineru",
    Peer:      "telegram:12345",
    Query:     "what should I know before deploying?",
})

write, err := svc.Conclude(ctx, goncho.ConcludeParams{
    ProfileID:  "mineru",
    Peer:       "telegram:12345",
    Conclusion: "Deploy only after tests and docs build pass.",
})

Full API reference: pkg.go.dev/github.com/TrebuchetDynamics/goncho


Gormes And Navivox Integration

If you are building on Gormes, use Goncho through the Gormes adapter instead of reaching into database internals. The adapter opens profile-local SQLite state, runs migrations, creates the service, and exposes the public memory tools.

mem, err := gormesgoncho.Open(ctx, gormesgoncho.Config{
    ProfilesDirectory: ".gormes/profiles",
    ProfileID:         "mineru",
    WorkspaceID:       "gormes-prod",
    ObserverID:        "gormes",
})

Register these with the Gormes tool registry:

goncho_context
goncho_search
goncho_remember
goncho_review
goncho_handoff

goncho_context has public E2E coverage for generated primer behavior under max_tokens: it preserves the newest in-budget turns and excludes older turns outside the budget while returning a representation for the target peer.

For Navivox, the same boundary applies: the Android app should treat Goncho as the local memory kernel behind the phone-hosted Gormes runtime, not as a separate memory server users must operate.

See: Gormes Agent Integration


Multi-Profile Memory

Gormes can manage multiple profiles in one runtime. Goncho supports that at the contract and API level.

Memory visibility is determined by:

workspace_id + profile_id + scope + peer_id

Default behavior:

  • If profile_id is present and scope is empty, Goncho uses private profile scope.
  • Workspace-shared recall requires explicit scope: "workspace".
  • Profile A cannot read profile B memory by default.

Gormes profile-local state can live under a custom profile root:

.gormes/profiles/<profile_id>/goncho.db
.gormes/profiles/<profile_id>/GONCHO_MEMORY.md

Gormes adapter example:

mem, err := gormesgoncho.Open(ctx, gormesgoncho.Config{
    ProfilesDirectory: ".gormes/profiles",
    ProfileID:         "mineru",
    WorkspaceID:       "gormes-prod",
    ObserverID:        "gormes",
})

See: Gormes Agent Integration


Trust Model

Goncho separates memory into layers:

Layer Meaning
Evidence Raw observations from sessions, tools, files, imports, and user messages.
Claims Interpreted statements derived from evidence.
Beliefs Scoped, time-aware memory eligible for retrieval.
Context packs Compact prompt-ready orientation with warnings.
Review Conflict, stale-memory, quarantine, and verification surfaces.

Design principles:

  • Evidence before belief.
  • Claims, not chunks.
  • Live verification before action.
  • Profile isolation before recall.
  • Bounded, auditable memory writes.
  • Orientation packs, not memory dumps.
  • Negative memory matters.
  • Trust is the moat.

Local Verification

Goncho favors deterministic local tests over benchmark theater.

go test ./...

High-signal checks:

go test ./... -run TestGormesMultiProfileMemoryIsolation
go test ./... -run TestGonchoPublicToolsRestartE2E
go test ./... -run TestGonchoGoalPromptInjectionImportIsQuarantinedE2E
go test ./... -run TestGonchoGoalStaleCodeClaimRequiresLiveVerificationE2E
go test ./... -run TestGonchoGoalNegativeDriftAnchorWarnsBeforeRepeatedFailureE2E

Release, benchmark, and public package smoke checks:

make release-smoke runs release metadata checks, ecosystem smoke, Go tests, vet, race tests, and the docs-site build before local pre-tag decisions.

make release-smoke
make ecosystem-smoke
go test ./cmd/goncho-bench
make bench-longmemeval-s-smoke
make bench-locomo-smoke
make bench-locomo
make bench-locomo-backends-smoke
make bench-locomo-backends
LOCOMO Retrieval Benchmark

Goncho includes a deterministic LOCOMO retrieval harness. This evaluates retrieval only, not answer generation. It uses ID-based scoring with no LLM judge, and answer_hint fields are never indexed or scored.

Pinned full run evidence:

Dataset Questions Memories recall_any@5 recall_any@10 strict_recall@5 strict_recall@10 MRR
LOCOMO full 1,982 5,882 60.14% 67.91% 51.16% 57.67% 46.90%
LOCOMO smoke 8 17 100.00% 100.00% 100.00% 100.00% 85.42%

Candidate-generation milestone: LOCOMO exposed a candidate-generation weakness in Goncho. After widening lexical pre-rank candidates, BM25-win missing_candidate failures dropped from 164 to 2, and Goncho now essentially matches BM25 on full LOCOMO retrieval while preserving LongMemEval-S performance. This was achieved without LLM judgment, answer scoring, benchmark-specific gold-ID hacks, or ranking changes.

The full LOCOMO run compares random, recency, BM25, SQLite FTS5, and Goncho baselines against the pinned official LOCOMO source dataset.

The backend comparison harness uses the same LOCOMO JSONL, same gold IDs, same centralized scoring, same leakage checks, and same failure taxonomy for Goncho, BM25, SQLite FTS5, agentmemory, and mem0. External backends are scored only if they return stable inserted memory_id values. If they cannot preserve IDs, they are marked not comparable instead of being scored by content matching or answer text.

Current external-backend status:

Backend Comparable Reason
Goncho yes Native local adapter with stable IDs.
BM25 yes Local lexical baseline with stable LOCOMO IDs.
SQLite FTS5 yes Local FTS baseline with stable LOCOMO IDs.
agentmemory yes, PR standalone fallback PR #583 commit 9b18a80c9d2839b025279978d3f4b5e1f9bc6e74 preserves stable IDs via external_id/metadata. LOCOMO full scored 0.0000 in standalone InMemoryKV fallback mode; this is not the full running agentmemory server.
mem0 no mem0/mem0ai is not installed in the local benchmark environment; no stable-ID run was produced.

Retrieval benchmark docs: docs-site/src/content/docs/reference/retrieval-benchmarks.md


Documentation

Start here:

Research:

Docs site:

cd docs-site
npm ci
npm run dev

Build:

cd docs-site
npm run build

Repository Map

Path Purpose
service.go Main embedded service API.
types.go Public request/result contracts.
sql.go SQLite-backed profile, conclusion, and session operations.
observations.go Raw evidence capture and audit-backed observations.
goncho_public_tools.go Public agent-facing tool surface.
memory_tools.go Generic MCP-style memory tools.
review.go / review_tool.go Review queue behavior.
code_claim_verification.go Live verification for remembered code/file claims.
drift_anchor.go Negative-memory drift warning logic.
integration/gormes/ Gormes adapter.
http/ Local HTTP adapter and compatibility tests.
docs-site/ Starlight documentation site.
docs/opensource-memory-systems/ Research corpus and reference systems.

Development

git clone https://github.com/TrebuchetDynamics/goncho.git
cd goncho
go test ./...

If tests fail, treat the first compiler or test error as the source of truth. Goncho intentionally favors evidence over optimistic status claims.

License

MIT


Goncho is developed by Trebuchet Dynamics as part of a local-first agent infrastructure ecosystem.

Documentation

Overview

Package goncho provides high-trust local memory for Go-native AI agent runtimes.

Goncho is designed as an embedded memory kernel rather than a hosted memory service. It stores local evidence, derives scoped recall, assembles context, records review signals, and helps callers verify remembered claims before an agent acts on them.

The core operating rule is evidence before belief: memory can orient an agent, but current evidence decides whether an action is safe.

Index

Constants

View Source
const (
	GonchoWriteFlushed     = "goncho_write_flushed"
	GonchoWriteDeferred    = "goncho_write_deferred"
	GonchoWriteQueued      = "goncho_write_queued"
	GonchoWriteFlushFailed = "goncho_write_flush_failed"

	GonchoAsyncEnqueued    = "goncho_async_enqueued"
	GonchoAsyncFlushed     = "goncho_async_flushed"
	GonchoAsyncRetry       = "goncho_async_retry"
	GonchoAsyncFlushFailed = "goncho_async_flush_failed"
	GonchoAsyncShutdown    = "goncho_async_shutdown"
	GonchoAsyncClosed      = "goncho_async_closed"
)
View Source
const (
	CrossChatDecisionAllowed       = "allowed"
	CrossChatDecisionDenied        = "denied"
	CrossChatDecisionDegraded      = "degraded"
	CrossChatFallbackSameChat      = "same-chat"
	SearchLineageStatusUnavailable = "unavailable"
)

Cross-chat recall constants.

View Source
const (
	LineageKindPrimary     = "primary"
	LineageKindCompression = "compression"
	LineageKindFork        = "fork"
	LineageStatusOK        = "ok"
	LineageStatusMissing   = "missing"
	LineageStatusOrphan    = "orphan"
	LineageStatusLoop      = "loop"
	LineageStatusError     = "error"
)

Lineage constants (mirrors internal/session).

View Source
const (
	GonchoMemoryV1ContractVersion = "1"
	GonchoMemoryV1MarkdownFormat  = "1"
	GonchoMemoryV1MCPToolContract = "1"
)

Goncho Memory V1 constants.

View Source
const (
	RecallBenchmarkCorpusVersion = "goncho-recall-benchmark-v1"

	RecallBenchmarkWarningMissingTrace  = "benchmark_missing_trace"
	RecallBenchmarkWarningNoRelevantIDs = "benchmark_no_relevant_ids"
)
View Source
const (
	RecallStageGenerate = "generate"
	RecallStageScore    = "score"
	RecallStageSelect   = "select"
	RecallStageProject  = "project"

	RecallWarningInfo     = "info"
	RecallWarningDegraded = "degraded"
	RecallWarningError    = "error"

	RecallWarningSemanticUnavailable        = "semantic_unavailable"
	RecallWarningGraphDisabled              = "graph_disabled"
	RecallWarningStaleEmbeddingIndex        = "stale_embedding_index"
	RecallWarningFTSUnavailable             = "fts_unavailable"
	RecallWarningScopeExcludedAllCandidates = "scope_excluded_all_candidates"
	RecallWarningTokenBudgetTruncated       = "token_budget_truncated"

	RecallRejectScopeMismatch = "scope_mismatch"
	RecallRejectTokenBudget   = "token_budget"
	RecallRejectNotSelected   = "not_selected"
)
View Source
const (
	RecallReplayStageQuery    = "query"
	RecallReplayStageWarn     = "warn"
	RecallReplayKindQuery     = "recall_query"
	RecallReplayKindCandidate = "candidate_scored"
	RecallReplayKindWarning   = "warning"
	RecallReplayKindSelected  = "selected"
	RecallReplayKindRejected  = "rejected"
	RecallReplayKindProject   = "projection_ready"
)
View Source
const (
	LocalHonchoAPIKeySentinel = "local"

	GonchoConfigBaseURLInvalid = "goncho_config_base_url_invalid"
	GonchoConfigLocalBaseURL   = "goncho_config_local_base_url"
)
View Source
const (
	DefaultWorkspaceID    = "gormes"
	DefaultObserverPeerID = "gormes"
)
View Source
const (
	EvidenceDefaultWorkspace     = "default_workspace:gormes"
	EvidenceHardIsolation        = "workspace:hard_isolation"
	EvidenceCanonicalUserID      = "peer:session_metadata_user_id"
	EvidenceExternalPeerFallback = "peer:source_prefixed_external_fallback"
	EvidenceCrossPeerOptIn       = "observation:cross_peer_opt_in"
)
View Source
const (
	MemoryScopeProfile   = "profile"
	MemoryScopeWorkspace = "workspace"
	MemoryScopeShared    = "shared"
	MemoryScopeSession   = "session"
	MemoryScopeGlobal    = "global"
)
View Source
const (
	DefaultRecentMessages               = 4
	DefaultMaxMessageSize               = 25_000
	DefaultMaxFileSize                  = 5_242_880
	DefaultGetContextMaxTokens          = 100_000
	DefaultDeriverWorkers               = 1
	DefaultRepresentationBatchMaxTokens = 1024
	DefaultDreamMinConclusions          = 50
	DefaultDreamCooldown                = 8 * time.Hour
	DefaultDreamIdleTimeout             = time.Hour
)
View Source
const (
	DefaultWebhookWorkspaceLimit = 10
	MaxWebhookURLLength          = 2048
)
View Source
const (
	// WriteEvidenceComplete signals the originating write succeeded and
	// (if applicable) any pending relation candidates were stored.
	WriteEvidenceComplete = "goncho_write_complete"
	// WriteEvidenceCancelled signals the submission was cancelled before the
	// write started; storage was not mutated.
	WriteEvidenceCancelled = "goncho_write_cancelled"
	// WriteEvidenceRelationFailed signals the originating write succeeded but
	// candidate detection failed; no relations were stored. The write is
	// authoritative and is not rolled back.
	WriteEvidenceRelationFailed = "goncho_relation_detection_failed"
	// WriteEvidenceWriteFailed signals the originating write itself failed;
	// no relations are recorded and the caller must retry or surface the
	// underlying error.
	WriteEvidenceWriteFailed = "goncho_write_failed"
)

Write evidence codes returned by Submit. Keep these in sync with operator docs; they are part of the public contract.

View Source
const GlobalWorkspaceID = "__global__"

Variables

View Source
var (
	ErrKeyAuthDisabled  = errors.New("goncho: key creation is disabled when auth is off")
	ErrKeyAdminRequired = errors.New("goncho: scoped key creation requires admin credentials")
	ErrKeyScopeRequired = errors.New("goncho: at least one of workspace_id, peer_id, or session_id is required")
	ErrKeySecretMissing = errors.New("goncho: jwt secret is required")
	ErrKeyInvalid       = errors.New("goncho: invalid scoped key")
	ErrKeyExpired       = errors.New("goncho: scoped key expired")
)
View Source
var (
	ErrObservationConflict      = errors.New("goncho: observation conflict")
	ErrObservationNotFound      = errors.New("goncho: observation not found")
	ErrObservationSchemaMissing = errors.New("goncho: observation schema missing")
	ErrObservationInvalid       = errors.New("goncho: invalid observation")
)
View Source
var (
	ErrWorkspacePerUser               = errors.New("goncho: workspace-per-user topology is not allowed")
	ErrWorkspaceRequiresHardIsolation = errors.New("goncho: explicit workspace requires hard isolation")
	ErrWorkspaceRequired              = errors.New("goncho: hard-isolation workspace is required")
	ErrPeerIdentityRequired           = errors.New("goncho: peer identity requires user_id or source/chat_id")
	ErrSessionBoundaryRequired        = errors.New("goncho: session boundary is required")
)
View Source
var (
	ErrWebhookWorkspaceRequired = errors.New("goncho: workspace_id is required")
	ErrWebhookInvalidURL        = errors.New("goncho: invalid webhook url")
	ErrWebhookLimitReached      = errors.New("goncho: maximum webhook endpoints reached for workspace")
	ErrWebhookNotFound          = errors.New("goncho: webhook endpoint not found")
	ErrWebhookSecretMissing     = errors.New("goncho: webhook secret is required")
)
View Source
var ErrAgentIDInvalid = errors.New("goncho: dynamic agent name does not normalize to a valid id")

ErrAgentIDInvalid is returned when the normalized AgentID would not match the pattern accepted by config.AgentsCfg (^[a-z][a-z0-9_-]{0,63}$). The caller should report the underlying name back to the operator.

View Source
var ErrAgentIDReserved = errors.New("goncho: dynamic agent id reserved by static config")

ErrAgentIDReserved is returned by Create when the requested name would normalize to an AgentID that is already claimed by the static config (passed via CreateAgentOptions.ReservedIDs). Operator-defined identity in config.toml must not be silently shadowed by a runtime spawn.

View Source
var ErrUserScopeDenied = errors.New("memory: user scope denied")
View Source
var QueueTaskTypes = []string{"representation", "summary", "dream"}

QueueTaskTypes are the only Honcho-style reasoning work units that Goncho reports. Delivery, deletion, and vector reconciliation counters are deliberately excluded because queue status is observability, not sync.

Functions

func AcceptProposal

func AcceptProposal(ctx context.Context, db *sql.DB, proposalID, reviewedBy string, committedMemoryID *string) error

AcceptProposal marks a proposal as accepted and optionally records the committed memory ID. The reviewedBy field identifies the parent agent that approved the proposal.

func AgentCanAccessMemory

func AgentCanAccessMemory(ctx context.Context, db *sql.DB, memoryID, agentID, workspaceID string, readableTiers []MemoryTier) (bool, error)

func CanRecallGonchoMemoryV1

func CanRecallGonchoMemoryV1(ctx context.Context, db *sql.DB) (bool, error)

CanRecallGonchoMemoryV1 checks if the V1 memory tables exist.

func DefaultDecayCurve

func DefaultDecayCurve(createdAt time.Time, now time.Time) float64

func DetectWorkspaceFromPath

func DetectWorkspaceFromPath(start string) (workspaceRoot, marker string)

DetectWorkspaceFromPath finds the workspace root by looking for project markers. Returns the directory containing the marker and the marker filename.

func FormatRecallDiagnosticsReport

func FormatRecallDiagnosticsReport(report RecallDiagnosticsReport) string

func FormatRecallReplay

func FormatRecallReplay(replay RecallReplay) string

func GonchoMemoryV1Checksum

func GonchoMemoryV1Checksum(content string) string

GonchoMemoryV1Checksum returns a SHA-256 hex digest of the content.

func GonchoMemoryV1ContractInfo

func GonchoMemoryV1ContractInfo() map[string]any

GonchoMemoryV1ContractInfo returns the V1 contract metadata.

func GrantReadACL

func GrantReadACL(ctx context.Context, db *sql.DB, memoryID, agentID, grantedBy string) error

func MemoryEntryRelevance

func MemoryEntryRelevance(entry MemoryToolEntry, query string) float64

func RejectProposal

func RejectProposal(ctx context.Context, db *sql.DB, proposalID, reviewedBy string) error

RejectProposal marks a proposal as rejected. The reviewedBy field identifies the parent agent that rejected the proposal.

func ResolvePluginSessionName

func ResolvePluginSessionName(cfg PluginConfig, input SessionNameInput) string

func RevokeACL

func RevokeACL(ctx context.Context, db *sql.DB, memoryID, agentID, permission string) error

func RunMigrations

func RunMigrations(db *sql.DB) error

func SanitizePayloadSummary

func SanitizePayloadSummary(summary map[string]string) map[string]string

func SignWebhookPayload

func SignWebhookPayload(payload, secret string) (string, error)

func ValidDialecticLevel

func ValidDialecticLevel(level string) bool

func ValidProposalKind

func ValidProposalKind(k string) bool

ValidProposalKind returns true if k is a recognized proposal kind.

func ValidTier

func ValidTier(t string) bool

func ValidateGonchoMemoryV1Item

func ValidateGonchoMemoryV1Item(item GonchoMemoryV1Item) error

ValidateGonchoMemoryV1Item checks required fields on a V1 item.

func ValidateTierOrErr

func ValidateTierOrErr(raw string) error

func WorkspaceIDForPath

func WorkspaceIDForPath(path string) string

WorkspaceIDForPath returns a stable workspace ID derived from the project root.

Types

type ACLQuery

type ACLQuery struct {
	AgentID     string
	IsParent    bool
	ReadTiers   []MemoryTier
	WriteTier   MemoryTier
	WorkspaceID string
}

func (ACLQuery) CanRead

func (q ACLQuery) CanRead(tier MemoryTier) bool

func (ACLQuery) CanWrite

func (q ACLQuery) CanWrite(tier MemoryTier) bool

func (ACLQuery) ReadScopeSQL

func (q ACLQuery) ReadScopeSQL() (string, []any)

type AgentRecord

type AgentRecord struct {
	ID        string
	Name      string
	Persona   string
	CreatedAt time.Time
}

AgentRecord describes a runtime-spawned agent persisted in the dynamic registry. Static config.AgentCfg remains the operator-defined surface; AgentRecord is the runtime overlay layered on top of it.

type AuditAction

type AuditAction string
const (
	AuditActionObserve AuditAction = "observe"
)

type AuditEvent

type AuditEvent struct {
	ID          string            `json:"id"`
	Action      AuditAction       `json:"action"`
	TargetType  AuditTargetType   `json:"target_type"`
	TargetID    string            `json:"target_id"`
	WorkspaceID string            `json:"workspace_id"`
	PeerID      string            `json:"peer_id"`
	SessionKey  string            `json:"session_key"`
	Reason      string            `json:"reason"`
	Metadata    map[string]string `json:"metadata,omitempty"`
	CreatedAt   time.Time         `json:"created_at"`
}

type AuditQuery

type AuditQuery struct {
	Action      AuditAction     `json:"action,omitempty"`
	TargetType  AuditTargetType `json:"target_type,omitempty"`
	TargetID    string          `json:"target_id,omitempty"`
	WorkspaceID string          `json:"workspace_id,omitempty"`
	PeerID      string          `json:"peer_id,omitempty"`
	SessionKey  string          `json:"session_key,omitempty"`
	Since       time.Time       `json:"since,omitempty"`
	Until       time.Time       `json:"until,omitempty"`
	Limit       int             `json:"limit,omitempty"`
}

type AuditResult

type AuditResult struct {
	Events []AuditEvent `json:"events"`
	Count  int          `json:"count"`
}

func AuditTrail

func AuditTrail(ctx context.Context, db *sql.DB, q AuditQuery) (AuditResult, error)

type AuditTargetType

type AuditTargetType string
const (
	AuditTargetObservation AuditTargetType = "observation"
)

type BindingMatch

type BindingMatch struct {
	Channel  string
	PeerKind string
	PeerID   string
	ThreadID string
}

BindingMatch describes a (channel, peer) tuple that should resolve to a dynamic AgentID at runtime. ThreadID is optional and stored as an empty string when absent; matches are scoped exactly so the General topic of a Telegram forum and one of its named topics never share a binding row.

type CandidateDetector

type CandidateDetector interface {
	Detect(ctx context.Context, w MemoryWrite, prior []MemoryWrite) ([]RelationCandidate, error)
}

CandidateDetector inspects a write against existing memories and returns pending relation candidates. Returning an error must not cause the originating write to fail; callers record the failure as evidence and proceed.

type ChatCompletionMetadata

type ChatCompletionMetadata struct {
	TokensIn  int `json:"tokens_in,omitempty"`
	TokensOut int `json:"tokens_out,omitempty"`
}

ChatCompletionMetadata carries terminal stream metadata that can be attached after the assistant response is complete.

type ChatParams

type ChatParams struct {
	SessionID      string `json:"session_id,omitempty"`
	Target         string `json:"target,omitempty"`
	Query          string `json:"query"`
	Stream         bool   `json:"stream,omitempty"`
	ReasoningLevel string `json:"reasoning_level,omitempty"`
}

ChatParams mirrors Honcho's DialecticOptions request body for peer.chat(). The peer itself is path/tool context, so it is passed separately to Service.Chat.

type ChatResult

type ChatResult struct {
	Content string `json:"content"`
}

ChatResult is Honcho's non-streaming dialectic response shape.

type ConcludeParams

type ConcludeParams struct {
	ProfileID  string `json:"profile_id,omitempty"`
	Peer       string `json:"peer"`
	Conclusion string `json:"conclusion,omitempty"`
	DeleteID   int64  `json:"delete_id,omitempty"`
	SessionKey string `json:"session_key,omitempty"`
	Scope      string `json:"scope,omitempty"`
}

ConcludeParams controls manual conclusion writes and deletes.

type ConcludeResult

type ConcludeResult struct {
	WorkspaceID string `json:"workspace_id"`
	ProfileID   string `json:"profile_id,omitempty"`
	Peer        string `json:"peer"`
	ID          int64  `json:"id,omitempty"`
	Status      string `json:"status"`
	Deleted     bool   `json:"deleted,omitempty"`
}

ConcludeResult is the stable JSON shape for honcho_conclude. ConcludeResult represents the outcome of a create/delete conclusion operation.

type Config

type Config struct {
	Enabled                      bool
	WorkspaceID                  string
	ObserverPeerID               string
	RecentMessages               int
	MaxMessageSize               int
	MaxFileSize                  int
	GetContextMaxTokens          int
	ReasoningEnabled             bool
	PeerCardEnabled              bool
	SummaryEnabled               bool
	DreamEnabled                 bool
	DreamIdleTimeout             time.Duration
	DeriverWorkers               int
	RepresentationBatchMaxTokens int
	DialecticDefaultLevel        DialecticLevel
	SessionDirectory             SessionDirectory
}

Config controls the minimal Goncho service defaults for a runtime.

func (Config) Effective

func (c Config) Effective() Config

Effective fills the Go-native Goncho defaults used when older callers still construct Config directly instead of going through internal/config.

type ConfigEvidence

type ConfigEvidence struct {
	Code    string `json:"code"`
	Source  string `json:"source,omitempty"`
	Message string `json:"message,omitempty"`
}

type ConflictResolution

type ConflictResolution struct {
	Winner   *MemoryEntry
	Loser    *MemoryEntry
	Reason   string
	Resolved bool
}

func ResolveConflict

func ResolveConflict(existing, incoming *MemoryEntry) ConflictResolution

type ContextParams

type ContextParams struct {
	ProfileID           string   `json:"profile_id,omitempty"`
	Peer                string   `json:"peer"`
	Query               string   `json:"query,omitempty"`
	SearchQuery         string   `json:"search_query,omitempty"`
	MaxTokens           int      `json:"max_tokens,omitempty"`
	Tokens              int      `json:"tokens,omitempty"`
	Summary             *bool    `json:"summary,omitempty"`
	SessionKey          string   `json:"session_key,omitempty"`
	Scope               string   `json:"scope,omitempty"`
	Sources             []string `json:"sources,omitempty"`
	PeerTarget          string   `json:"peer_target,omitempty"`
	PeerPerspective     string   `json:"peer_perspective,omitempty"`
	LimitToSession      *bool    `json:"limit_to_session,omitempty"`
	SearchTopK          *int     `json:"search_top_k,omitempty"`
	SearchMaxDistance   *float64 `json:"search_max_distance,omitempty"`
	IncludeMostFrequent *bool    `json:"include_most_frequent,omitempty"`
	MaxConclusions      *int     `json:"max_conclusions,omitempty"`
	IncludeDreamStatus  *bool    `json:"include_dream_status,omitempty"`
}

ContextParams controls honcho_context reads.

type ContextResult

type ContextResult struct {
	WorkspaceID       string                       `json:"workspace_id"`
	ProfileID         string                       `json:"profile_id,omitempty"`
	Peer              string                       `json:"peer"`
	ObserverPeerID    string                       `json:"observer_peer_id,omitempty"`
	ObservedPeerID    string                       `json:"observed_peer_id,omitempty"`
	SessionKey        string                       `json:"session_key,omitempty"`
	PeerCard          []string                     `json:"peer_card"`
	Representation    string                       `json:"representation"`
	Summary           *SessionSummary              `json:"summary,omitempty"`
	StructuredSummary *StructuredSummary           `json:"structured_summary,omitempty"`
	Conclusions       []string                     `json:"conclusions,omitempty"`
	SearchResults     []SearchHit                  `json:"search_results,omitempty"`
	ScopeEvidence     *CrossChatRecallEvidence     `json:"scope_evidence,omitempty"`
	RecentMessages    []MessageSlice               `json:"recent_messages,omitempty"`
	Unavailable       []ContextUnavailableEvidence `json:"unavailable,omitempty"`
}

ContextResult is the stable JSON shape for honcho_context.

type ContextUnavailableEvidence

type ContextUnavailableEvidence struct {
	Field      string `json:"field"`
	Capability string `json:"capability"`
	Reason     string `json:"reason"`
}

ContextUnavailableEvidence names a requested context capability that Goncho accepted but cannot yet fulfill with the current local storage model.

type CreateAgentOptions

type CreateAgentOptions struct {
	Name        string
	Persona     string
	ReservedIDs map[string]struct{}
}

CreateAgentOptions parameterizes DynamicAgentRegistry.Create. Name is required; the registry normalizes it to an AgentID compatible with config.AgentsCfg. ReservedIDs (typically the set of static AgentCfg.IDs observed at the time of the call) prevents the runtime registry from silently shadowing an operator-defined identity.

type CreateMessage

type CreateMessage struct {
	ProfileID string         `json:"profile_id,omitempty"`
	Peer      string         `json:"peer_id"`
	Role      string         `json:"role,omitempty"`
	Content   string         `json:"content"`
	Metadata  map[string]any `json:"metadata,omitempty"`
	CreatedAt time.Time      `json:"created_at,omitempty"`
}

type CreateMessagesParams

type CreateMessagesParams struct {
	SessionKey string          `json:"session_key"`
	Messages   []CreateMessage `json:"messages"`
}

CreateMessagesParams mirrors Honcho's session message creation contract at the local Goncho service boundary.

type CreateMessagesResult

type CreateMessagesResult struct {
	WorkspaceID string          `json:"workspace_id"`
	SessionKey  string          `json:"session_key"`
	Messages    []MessageRecord `json:"messages"`
}

type CrossChatRecallEvidence

type CrossChatRecallEvidence struct {
	Decision                  string                     `json:"decision"`
	Scope                     string                     `json:"scope"`
	FallbackScope             string                     `json:"fallback_scope,omitempty"`
	Reason                    string                     `json:"reason,omitempty"`
	UserID                    string                     `json:"user_id,omitempty"`
	CurrentSessionID          string                     `json:"current_session_id,omitempty"`
	CurrentChatKey            string                     `json:"current_chat_key,omitempty"`
	CurrentBinding            *CrossChatSessionEvidence  `json:"current_binding,omitempty"`
	SourceAllowlist           []string                   `json:"source_allowlist,omitempty"`
	SessionsConsidered        int                        `json:"sessions_considered"`
	WidenedSessionsConsidered int                        `json:"widened_sessions_considered"`
	Sessions                  []CrossChatSessionEvidence `json:"sessions,omitempty"`
}

CrossChatRecallEvidence explains why a user-scoped recall/search request was allowed, denied, or degraded.

func DegradedCrossChatRecallEvidence

func DegradedCrossChatRecallEvidence(filter SearchFilter, reason string) CrossChatRecallEvidence

DegradedCrossChatRecallEvidence reports that a caller asked for user scope but the diagnostic path could not inspect the session binding dependency.

func ExplainCrossChatRecall

func ExplainCrossChatRecall(metas []SessionMetadata, filter SearchFilter) CrossChatRecallEvidence

ExplainCrossChatRecall returns evidence for a user-scoped widening decision.

type CrossChatSessionEvidence

type CrossChatSessionEvidence struct {
	SessionID string `json:"session_id"`
	Source    string `json:"source,omitempty"`
	ChatID    string `json:"chat_id,omitempty"`
	ChatKey   string `json:"chat_key,omitempty"`
	Current   bool   `json:"current,omitempty"`
}

CrossChatSessionEvidence is the operator-readable identity for one session.

type CrossSessionKnowledge

type CrossSessionKnowledge struct {
	Query    string
	Memories []MemoryToolEntry
	Sessions map[string]int
	Summary  string
}

type CrossSessionMemory

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

func NewCrossSessionMemory

func NewCrossSessionMemory(store MemoryToolStore) *CrossSessionMemory

func (*CrossSessionMemory) DetectContradictions

func (csm *CrossSessionMemory) DetectContradictions(ctx context.Context, newEntry MemoryToolEntry) ([]MemoryToolEntry, error)

func (*CrossSessionMemory) LoadRelevant

func (csm *CrossSessionMemory) LoadRelevant(ctx context.Context, query string, limit int) ([]MemoryToolEntry, error)

func (*CrossSessionMemory) QueryKnowledge

func (csm *CrossSessionMemory) QueryKnowledge(ctx context.Context, query string, limit int) (CrossSessionKnowledge, error)

type DialecticCaller

type DialecticCaller interface {
	Chat(ctx context.Context, peer string, systemPrompt string, query string) (string, error)
}

type DialecticLevel

type DialecticLevel string
const (
	DialecticLevelMinimal DialecticLevel = "minimal"
	DialecticLevelLow     DialecticLevel = "low"
	DialecticLevelMedium  DialecticLevel = "medium"
	DialecticLevelHigh    DialecticLevel = "high"
	DialecticLevelMax     DialecticLevel = "max"
)

type DivergenceClassification

type DivergenceClassification string
const (
	DivergenceLocal         DivergenceClassification = "local"
	DivergenceOwnedExcluded DivergenceClassification = "owned_excluded"
)

type DivergenceEvidence

type DivergenceEvidence struct {
	Classification DivergenceClassification `json:"classification"`
	Rationale      string                   `json:"rationale,omitempty"`
	Replacement    string                   `json:"replacement,omitempty"`
}

type DreamQueueStatus

type DreamQueueStatus struct {
	Status       string                `json:"status"`
	Enabled      bool                  `json:"enabled"`
	TablePresent bool                  `json:"table_present"`
	Evidence     []DreamStatusEvidence `json:"evidence,omitempty"`
}

DreamQueueStatus is embedded in queue/doctor output so operators can see whether dreaming is disabled, unavailable, cooling down, pending, or running.

type DreamScheduleParams

type DreamScheduleParams struct {
	Peer   string
	Now    time.Time
	Manual bool
	Reason string
}

DreamScheduleParams controls a local dream work-intent scheduling attempt. Manual requests bypass threshold/cooldown/idle gates but still dedupe active work and respect disabled/unavailable degraded modes.

type DreamScheduleResult

type DreamScheduleResult struct {
	Action           string              `json:"action"`
	ID               int64               `json:"id,omitempty"`
	Status           string              `json:"status,omitempty"`
	WorkspaceID      string              `json:"workspace_id"`
	ObserverPeerID   string              `json:"observer_peer_id"`
	ObservedPeerID   string              `json:"observed_peer_id"`
	WorkUnitKey      string              `json:"work_unit_key,omitempty"`
	NewConclusions   int                 `json:"new_conclusions"`
	MinConclusions   int                 `json:"min_conclusions"`
	LastConclusionID int64               `json:"last_conclusion_id,omitempty"`
	Evidence         DreamStatusEvidence `json:"evidence"`
}

DreamScheduleResult is auditable scheduler evidence. It never contains LLM output; the first dream slice only records local work intent.

type DreamStatusEvidence

type DreamStatusEvidence struct {
	Code             string `json:"code"`
	Reason           string `json:"reason"`
	DreamID          int64  `json:"dream_id,omitempty"`
	WorkspaceID      string `json:"workspace_id,omitempty"`
	ObserverPeerID   string `json:"observer_peer_id,omitempty"`
	ObservedPeerID   string `json:"observed_peer_id,omitempty"`
	Status           string `json:"status,omitempty"`
	WorkUnitKey      string `json:"work_unit_key,omitempty"`
	NewConclusions   int    `json:"new_conclusions,omitempty"`
	MinConclusions   int    `json:"min_conclusions,omitempty"`
	LastConclusionID int64  `json:"last_conclusion_id,omitempty"`
	LastActivityAt   int64  `json:"last_activity_at,omitempty"`
	IdleUntil        int64  `json:"idle_until,omitempty"`
	CooldownUntil    int64  `json:"cooldown_until,omitempty"`
}

DreamStatusEvidence is the shared doctor/status/context evidence shape for local dream scheduler state.

type DriftAnchorCheckParams

type DriftAnchorCheckParams struct {
	Prompt string `json:"prompt"`
	Limit  int    `json:"limit,omitempty"`
}

type DriftAnchorDetector

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

func NewDriftAnchorDetector

func NewDriftAnchorDetector(store MemoryToolStore) *DriftAnchorDetector

func (*DriftAnchorDetector) Check

type DriftAnchorWarning

type DriftAnchorWarning struct {
	Warn            bool    `json:"warn"`
	Code            string  `json:"code,omitempty"`
	MatchedMemoryID string  `json:"matched_memory_id,omitempty"`
	MatchedContent  string  `json:"matched_content,omitempty"`
	SimilarityScore float64 `json:"similarity_score,omitempty"`
	Recommendation  string  `json:"recommendation,omitempty"`
}

type DynamicAgentRegistry

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

DynamicAgentRegistry persists runtime-spawned agents and their channel bindings in the Goncho SQLite database. The registry knows nothing about the gateway resolver or channel adapters; callers compose it with the existing config.AgentsCfg overlay at the gateway boundary.

func NewDynamicAgentRegistry

func NewDynamicAgentRegistry(db *sql.DB) (*DynamicAgentRegistry, error)

NewDynamicAgentRegistry opens (or migrates) the dynamic agent tables and returns a registry bound to db. The DDL is idempotent — calling the constructor twice on the same database is safe.

func (*DynamicAgentRegistry) Bind

func (r *DynamicAgentRegistry) Bind(ctx context.Context, agentID string, match BindingMatch) error

Bind associates agentID with match. Re-binding the same tuple replaces the previous AgentID — the most recent runtime decision wins.

func (*DynamicAgentRegistry) Create

Create inserts a new dynamic agent. Returns ErrAgentIDReserved if the normalized AgentID is present in opts.ReservedIDs, and ErrAgentIDInvalid if the name does not normalize to a config-compatible AgentID.

func (*DynamicAgentRegistry) Get

Get returns the AgentRecord for id, if any. The second return value is false (no error) when the id is unknown.

func (*DynamicAgentRegistry) List

List returns every dynamic AgentRecord ordered by creation time, oldest first. Empty registries return an empty slice with no error.

func (*DynamicAgentRegistry) Resolve

func (r *DynamicAgentRegistry) Resolve(ctx context.Context, match BindingMatch) (string, bool, error)

Resolve returns the dynamic AgentID bound to match, if any. The second return value is false (no error) when no binding exists; callers should then fall back to static config.AgentBindingCfg at the gateway boundary.

func (*DynamicAgentRegistry) Unbind

func (r *DynamicAgentRegistry) Unbind(ctx context.Context, match BindingMatch) error

Unbind removes the binding for match. Unbinding an unknown tuple is a no-op so callers can call Unbind defensively without checking Resolve first. The associated AgentRecord is preserved — Unbind only releases the (channel, peer, thread) -> agent mapping.

type Event

type Event struct {
	Name             string              `json:"name"`
	UpstreamEvent    string              `json:"upstream_event,omitempty"`
	Source           string              `json:"source,omitempty"`
	Category         string              `json:"category,omitempty"`
	Timestamp        time.Time           `json:"timestamp"`
	SessionID        string              `json:"session_id,omitempty"`
	AgentID          string              `json:"agent_id,omitempty"`
	PeerID           string              `json:"peer_id,omitempty"`
	WorkspaceID      string              `json:"workspace_id,omitempty"`
	RunID            string              `json:"run_id,omitempty"`
	TraceID          string              `json:"trace_id,omitempty"`
	TreeNodeID       string              `json:"tree_node_id,omitempty"`
	ParentID         string              `json:"parent_id,omitempty"`
	Level            int                 `json:"level,omitempty"`
	EventType        string              `json:"event_type,omitempty"`
	Provider         string              `json:"provider,omitempty"`
	Model            string              `json:"model,omitempty"`
	TaskType         string              `json:"task_type,omitempty"`
	ReasoningEffort  string              `json:"reasoning_effort,omitempty"`
	DurationMs       int64               `json:"duration_ms,omitempty"`
	TokensIn         int                 `json:"tokens_in,omitempty"`
	TokensOut        int                 `json:"tokens_out,omitempty"`
	CacheReadTokens  int                 `json:"cache_read_tokens,omitempty"`
	CacheWriteTokens int                 `json:"cache_write_tokens,omitempty"`
	ReasoningTokens  int                 `json:"reasoning_tokens,omitempty"`
	RequestCount     int                 `json:"request_count,omitempty"`
	ToolCalls        int                 `json:"tool_calls,omitempty"`
	ToolErrors       int                 `json:"tool_errors,omitempty"`
	QueueItems       int                 `json:"queue_items,omitempty"`
	PayloadSummary   map[string]string   `json:"payload_summary,omitempty"`
	Divergence       *DivergenceEvidence `json:"divergence,omitempty"`
}

func NewTelemetryEvent

func NewTelemetryEvent(input TelemetryEventInput) Event

func NormalizeEvent

func NormalizeEvent(event Event, now time.Time) Event

type EventMatrixEntry

type EventMatrixEntry struct {
	UpstreamEvent      string             `json:"upstream_event"`
	LocalEvent         string             `json:"local_event"`
	Source             string             `json:"source"`
	Category           string             `json:"category"`
	HostedExporterOnly bool               `json:"hosted_exporter_only,omitempty"`
	Divergence         DivergenceEvidence `json:"divergence"`
}

func LookupTelemetryEvent

func LookupTelemetryEvent(upstream string) (EventMatrixEntry, bool)

type EvidenceItem

type EvidenceItem struct {
	Kind     string            `json:"kind"`
	Source   string            `json:"source,omitempty"`
	ID       string            `json:"id,omitempty"`
	Note     string            `json:"note,omitempty"`
	Score    float64           `json:"score,omitempty"`
	Metadata map[string]string `json:"metadata,omitempty"`
}

type ExternalCompatibility

type ExternalCompatibility struct {
	InternalService   string
	ExternalToolNames []string
}

ExternalCompatibility records the internal/external naming contract.

func HonchoExternalCompatibility

func HonchoExternalCompatibility() ExternalCompatibility

HonchoExternalCompatibility returns the current public Honcho-compatible tool names while keeping the implementation service named Goncho.

type FileImportMetadata

type FileImportMetadata struct {
	FileID              string `json:"file_id"`
	Filename            string `json:"filename"`
	ChunkIndex          int    `json:"chunk_index"`
	TotalChunks         int    `json:"total_chunks"`
	OriginalFileSize    int64  `json:"original_file_size"`
	ContentType         string `json:"content_type"`
	ChunkCharacterRange [2]int `json:"chunk_character_range"`
}

FileImportMetadata mirrors Honcho's file-related internal metadata attached to every message generated from an uploaded document.

type FileImportResult

type FileImportResult struct {
	WorkspaceID string                       `json:"workspace_id"`
	SessionKey  string                       `json:"session_key"`
	PeerID      string                       `json:"peer_id"`
	FileID      string                       `json:"file_id"`
	Messages    []ImportedFileMessage        `json:"messages"`
	Unavailable []ContextUnavailableEvidence `json:"unavailable,omitempty"`
}

FileImportResult describes the ordinary session messages written from an import plus degraded-mode evidence for reasoning work that cannot be queued.

type ForgetMemoryTool

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

func NewForgetMemoryTool

func NewForgetMemoryTool(store MemoryToolStore) *ForgetMemoryTool

func (*ForgetMemoryTool) Description

func (t *ForgetMemoryTool) Description() string

func (*ForgetMemoryTool) Execute

func (t *ForgetMemoryTool) Execute(ctx context.Context, args json.RawMessage) (json.RawMessage, error)

func (*ForgetMemoryTool) Name

func (t *ForgetMemoryTool) Name() string

func (*ForgetMemoryTool) Schema

func (t *ForgetMemoryTool) Schema() json.RawMessage

func (ForgetMemoryTool) Spec

func (t ForgetMemoryTool) Spec() toolmeta.OperationSpec

func (*ForgetMemoryTool) Timeout

func (t *ForgetMemoryTool) Timeout() time.Duration

type GonchoContextTool

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

func NewGonchoContextTool

func NewGonchoContextTool(svc *Service) *GonchoContextTool

func (*GonchoContextTool) Description

func (t *GonchoContextTool) Description() string

func (*GonchoContextTool) Execute

func (*GonchoContextTool) Name

func (t *GonchoContextTool) Name() string

func (*GonchoContextTool) Schema

func (t *GonchoContextTool) Schema() json.RawMessage

func (*GonchoContextTool) Spec

func (*GonchoContextTool) Timeout

func (t *GonchoContextTool) Timeout() time.Duration

type GonchoHandoffTool

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

func NewGonchoHandoffTool

func NewGonchoHandoffTool(store MemoryToolStore) *GonchoHandoffTool

func (*GonchoHandoffTool) Description

func (t *GonchoHandoffTool) Description() string

func (*GonchoHandoffTool) Execute

func (*GonchoHandoffTool) Name

func (t *GonchoHandoffTool) Name() string

func (*GonchoHandoffTool) Schema

func (t *GonchoHandoffTool) Schema() json.RawMessage

func (*GonchoHandoffTool) Spec

func (*GonchoHandoffTool) Timeout

func (t *GonchoHandoffTool) Timeout() time.Duration

type GonchoMarkdownStore

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

GonchoMarkdownStore is the markdown-backed memory store.

func NewGonchoMarkdownStore

func NewGonchoMarkdownStore(db *sql.DB, cfg GonchoMarkdownStoreConfig) (*GonchoMarkdownStore, error)

NewGonchoMarkdownStore creates a new markdown-backed memory store.

type GonchoMarkdownStoreConfig

type GonchoMarkdownStoreConfig struct {
	WorkspaceID string
	ObserverID  string
	FilePath    string
}

GonchoMarkdownStoreConfig controls the markdown-backed memory store.

type GonchoMemoryV1Document

type GonchoMemoryV1Document struct {
	FormatVersion   string               `json:"format_version"`
	ContractVersion string               `json:"contract_version"`
	Items           []GonchoMemoryV1Item `json:"items"`
}

GonchoMemoryV1Item is a single memory entry in the V1 contract.

func ParseGonchoMemoryV1Markdown

func ParseGonchoMemoryV1Markdown(raw string) (GonchoMemoryV1Document, error)

ParseGonchoMemoryV1Markdown parses markdown into V1 documents.

type GonchoMemoryV1Item

type GonchoMemoryV1Item struct {
	MemoryID        string   `json:"memory_id" yaml:"memory_id"`
	Revision        int      `json:"revision" yaml:"revision"`
	AgentID         string   `json:"agent_id" yaml:"agent_id"`
	WorkspaceID     string   `json:"workspace_id" yaml:"workspace_id"`
	PeerID          string   `json:"peer_id" yaml:"peer_id"`
	SessionID       string   `json:"session_id" yaml:"session_id"`
	Scope           string   `json:"scope" yaml:"scope"`
	State           string   `json:"state" yaml:"state"`
	SourceKind      string   `json:"source_kind" yaml:"source_kind"`
	SourceTurnID    string   `json:"source_turn_id,omitempty" yaml:"source_turn_id,omitempty"`
	TombstonedAt    string   `json:"tombstoned_at,omitempty" yaml:"tombstoned_at,omitempty"`
	TombstoneReason string   `json:"tombstone_reason,omitempty" yaml:"tombstone_reason,omitempty"`
	Checksum        string   `json:"checksum" yaml:"checksum"`
	Tags            []string `json:"tags,omitempty" yaml:"tags,omitempty"`
	Importance      float64  `json:"importance" yaml:"importance"`
	CreatedAt       string   `json:"created_at" yaml:"created_at"`
	UpdatedAt       string   `json:"updated_at" yaml:"updated_at"`
	ProvenanceJSON  string   `json:"provenance_json,omitempty" yaml:"provenance_json,omitempty"`
	Content         string   `json:"content" yaml:"-"`
}

type GonchoMemoryV1RecallRequest

type GonchoMemoryV1RecallRequest struct {
	WorkspaceID string
	PeerID      string
	Query       string
	Limit       int
	Scope       string
	Sources     []string
	SessionID   string
}

GonchoMemoryV1RecallRequest controls a V1 recall operation.

type GonchoMetaanalysisCoverageInput

type GonchoMetaanalysisCoverageInput struct {
	SourceDocumentPath       string
	SourceDocumentSHA256     string
	ProofMatrix              gonchoProofMatrixReport
	ReviewLoopVerified       bool
	MemoryToolLoopVerified   bool
	LocalOnlyEvaluator       string
	DocsArchitectureKeywords []string
}

GonchoMetaanalysisCoverageInput binds the local proof evidence back to the architecture requirements documented in METAANALYSIS-MEMORY-SYSTEMS.md.

type GonchoMetaanalysisCoverageReport

type GonchoMetaanalysisCoverageReport struct {
	Service                       string   `json:"service"`
	CoverageVersion               string   `json:"coverage_version"`
	SourceDocumentPath            string   `json:"source_document_path"`
	SourceDocumentSHA256          string   `json:"source_document_sha256"`
	DocsArchitectureKeywords      []string `json:"docs_architecture_keywords"`
	PrinciplesCovered             []string `json:"principles_covered"`
	ContextLayersCovered          []string `json:"context_layers_covered"`
	LifecycleStatesCovered        []string `json:"lifecycle_states_covered"`
	CoreEvaluationsCovered        []string `json:"core_evaluations_covered"`
	PublicToolsVerified           []string `json:"public_tools_verified"`
	LocalFeaturesVerified         []string `json:"local_features_verified"`
	DeferredFeatures              []string `json:"deferred_features"`
	CompletionCondition           string   `json:"completion_condition"`
	AllLocalEvaluatorChecksPassed bool     `json:"all_local_evaluator_checks_passed"`
}

type GonchoPublicToolsRestartE2EConfig

type GonchoPublicToolsRestartE2EConfig struct {
	DBPath       string
	MarkdownPath string
	WorkspaceID  string
	ObserverID   string
	PeerID       string
	SessionKey   string
}

type GonchoPublicToolsRestartE2EReport

type GonchoPublicToolsRestartE2EReport struct {
	ToolNames                         []string `json:"tool_names"`
	SQLiteRestartVerified             bool     `json:"sqlite_restart_verified"`
	NetworkRequired                   bool     `json:"network_required"`
	OllamaRequired                    bool     `json:"ollama_required"`
	SearchCountBeforeRestart          int      `json:"search_count_before_restart"`
	SearchCountAfterRestart           int      `json:"search_count_after_restart"`
	ContextRepresentationAfterRestart string   `json:"context_representation_after_restart"`
	ReviewWarningBeforeResolve        bool     `json:"review_warning_before_resolve"`
	ReviewWarningAfterResolve         bool     `json:"review_warning_after_resolve"`
	HandoffCountAfterRestart          int      `json:"handoff_count_after_restart"`
	CompletionCondition               string   `json:"completion_condition"`
}

type GonchoRememberTool

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

func NewGonchoRememberTool

func NewGonchoRememberTool(svc *Service) *GonchoRememberTool

func (*GonchoRememberTool) Description

func (t *GonchoRememberTool) Description() string

func (*GonchoRememberTool) Execute

func (*GonchoRememberTool) Name

func (t *GonchoRememberTool) Name() string

func (*GonchoRememberTool) Schema

func (t *GonchoRememberTool) Schema() json.RawMessage

func (*GonchoRememberTool) Spec

func (*GonchoRememberTool) Timeout

func (t *GonchoRememberTool) Timeout() time.Duration

type GonchoSearchTool

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

func NewGonchoSearchTool

func NewGonchoSearchTool(svc *Service) *GonchoSearchTool

func (*GonchoSearchTool) Description

func (t *GonchoSearchTool) Description() string

func (*GonchoSearchTool) Execute

func (*GonchoSearchTool) Name

func (t *GonchoSearchTool) Name() string

func (*GonchoSearchTool) Schema

func (t *GonchoSearchTool) Schema() json.RawMessage

func (*GonchoSearchTool) Spec

func (*GonchoSearchTool) Timeout

func (t *GonchoSearchTool) Timeout() time.Duration

type HonchoSDKCompatibilityHarness

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

HonchoSDKCompatibilityHarness is a hermetic adapter for proving Honcho SDK request/response flows against the local Goncho service.

func NewHonchoSDKCompatibilityHarness

func NewHonchoSDKCompatibilityHarness(service *Service) *HonchoSDKCompatibilityHarness

func (*HonchoSDKCompatibilityHarness) ContextPreview

func (*HonchoSDKCompatibilityHarness) Search

func (*HonchoSDKCompatibilityHarness) SeedSession

type HonchoSDKConclusion

type HonchoSDKConclusion struct {
	ID     int64  `json:"id"`
	Status string `json:"status"`
}

type HonchoSDKContextPreview

type HonchoSDKContextPreview struct {
	WorkspaceID    string                     `json:"workspace_id"`
	PeerID         string                     `json:"peer_id"`
	SessionID      string                     `json:"session_id,omitempty"`
	PeerCard       []string                   `json:"peer_card"`
	Representation string                     `json:"representation"`
	Summary        *HonchoSDKContextSummary   `json:"summary,omitempty"`
	SearchResults  []HonchoSDKSearchHit       `json:"search_results,omitempty"`
	RecentMessages []MessageSlice             `json:"recent_messages,omitempty"`
	Unsupported    []HonchoSDKUnsupportedFlow `json:"unsupported,omitempty"`
}

type HonchoSDKContextPreviewRequest

type HonchoSDKContextPreviewRequest struct {
	PeerID    string
	SessionID string
	Query     string
	Tokens    int
}

type HonchoSDKContextSummary

type HonchoSDKContextSummary struct {
	Content    string `json:"content"`
	MessageID  int64  `json:"message_id"`
	Type       string `json:"summary_type"`
	CreatedAt  int64  `json:"created_at"`
	TokenCount int    `json:"token_count"`
}

type HonchoSDKMessage

type HonchoSDKMessage struct {
	ID          int64          `json:"id"`
	WorkspaceID string         `json:"workspace_id"`
	SessionID   string         `json:"session_id"`
	PeerID      string         `json:"peer_id"`
	Role        string         `json:"role"`
	Content     string         `json:"content"`
	Sequence    int            `json:"seq_in_session"`
	CreatedAt   int64          `json:"created_at"`
	Metadata    map[string]any `json:"metadata,omitempty"`
}

type HonchoSDKMessageInput

type HonchoSDKMessageInput struct {
	PeerID    string
	Role      string
	Content   string
	Metadata  map[string]any
	CreatedAt time.Time
}

type HonchoSDKPeer

type HonchoSDKPeer struct {
	ID string `json:"id"`
}

type HonchoSDKSearchHit

type HonchoSDKSearchHit struct {
	ID           int64          `json:"id,omitempty"`
	Source       string         `json:"source"`
	OriginSource string         `json:"origin_source,omitempty"`
	Content      string         `json:"content"`
	SessionID    string         `json:"session_id,omitempty"`
	Lineage      *SearchLineage `json:"lineage,omitempty"`
}

type HonchoSDKSearchRequest

type HonchoSDKSearchRequest struct {
	PeerID    string
	SessionID string
	Query     string
	Limit     int
}

type HonchoSDKSearchResponse

type HonchoSDKSearchResponse struct {
	WorkspaceID string               `json:"workspace_id"`
	PeerID      string               `json:"peer_id"`
	Query       string               `json:"query"`
	Results     []HonchoSDKSearchHit `json:"results"`
}

type HonchoSDKSeedResult

type HonchoSDKSeedResult struct {
	Workspace   HonchoSDKWorkspace    `json:"workspace"`
	Peer        HonchoSDKPeer         `json:"peer"`
	Session     HonchoSDKSession      `json:"session"`
	Messages    []HonchoSDKMessage    `json:"messages"`
	Conclusions []HonchoSDKConclusion `json:"conclusions,omitempty"`
}

type HonchoSDKSession

type HonchoSDKSession struct {
	ID string `json:"id"`
}

type HonchoSDKSessionSeed

type HonchoSDKSessionSeed struct {
	PeerID      string
	SessionID   string
	PeerCard    []string
	Conclusions []string
	Messages    []HonchoSDKMessageInput
}

type HonchoSDKUnsupportedFlow

type HonchoSDKUnsupportedFlow struct {
	Code     string   `json:"code"`
	Method   string   `json:"method"`
	Endpoint string   `json:"endpoint"`
	Fields   []string `json:"fields"`
}

func UnsupportedHonchoSDKFlow

func UnsupportedHonchoSDKFlow(method, endpoint string, fields ...string) HonchoSDKUnsupportedFlow

type HonchoSDKWorkspace

type HonchoSDKWorkspace struct {
	ID string `json:"id"`
}

type HostConfigDocument

type HostConfigDocument struct {
	APIKey    string                       `json:"apiKey,omitempty"`
	BaseURL   string                       `json:"baseUrl,omitempty"`
	PeerName  string                       `json:"peerName,omitempty"`
	Workspace string                       `json:"workspace,omitempty"`
	Hosts     map[string]HostRuntimeConfig `json:"hosts,omitempty"`
}

HostConfigDocument is the shared ~/.honcho/config.json shape needed for host-scoped config isolation fixtures.

func ApplyHostConfigPatch

func ApplyHostConfigPatch(doc HostConfigDocument, host string, patch HostConfigPatch) (HostConfigDocument, error)

ApplyHostConfigPatch applies host-scoped config writes without mutating the input document or sibling host entries.

type HostConfigPatch

type HostConfigPatch struct {
	Workspace       *string
	AIPeer          *string
	PeerName        *string
	RecallMode      *string
	ObservationMode *string
	SessionStrategy *string
}

HostConfigPatch updates only one hosts.<name> block.

type HostIntegrationInput

type HostIntegrationInput struct {
	Host             string
	Workspace        string
	PeerName         string
	AIPeer           string
	SessionStrategy  string
	WorkingDirectory string
	Repository       string
	Branch           string
	HostSessionID    string
	ChatInstanceID   string
	CharacterName    string
	RecallMode       string
}

HostIntegrationInput is the host-facing compatibility fixture input. It models the shared Honcho concepts used by current hosts without importing or running those hosts' plugins.

type HostIntegrationMapping

type HostIntegrationMapping struct {
	Host              string
	WorkspaceID       string
	UserPeerID        string
	AIPeerID          string
	SessionStrategy   string
	SessionKey        string
	RecallMode        string
	InjectContext     bool
	ExposeTools       bool
	InternalService   string
	ExternalToolNames []string
	Unsupported       []UnsupportedHostMapping
}

HostIntegrationMapping is the internal Goncho interpretation of one host configuration.

func MapHostIntegration

func MapHostIntegration(input HostIntegrationInput) HostIntegrationMapping

MapHostIntegration translates host config concepts to the current internal Goncho service contract. Unsupported fields are returned as diagnostics instead of being silently widened or accepted.

type HostRuntimeConfig

type HostRuntimeConfig struct {
	Workspace       string `json:"workspace,omitempty"`
	AIPeer          string `json:"aiPeer,omitempty"`
	PeerName        string `json:"peerName,omitempty"`
	RecallMode      string `json:"recallMode,omitempty"`
	ObservationMode string `json:"observationMode,omitempty"`
	SessionStrategy string `json:"sessionStrategy,omitempty"`
}

HostRuntimeConfig is one hosts.<name> block from the Honcho shared config.

type ImportFileParams

type ImportFileParams struct {
	SessionKey    string         `json:"session_key"`
	PeerID        string         `json:"peer_id"`
	Filename      string         `json:"filename"`
	ContentType   string         `json:"content_type"`
	Content       []byte         `json:"-"`
	Metadata      map[string]any `json:"metadata,omitempty"`
	Configuration map[string]any `json:"configuration,omitempty"`
	CreatedAt     *time.Time     `json:"created_at,omitempty"`
}

ImportFileParams is the local Goncho equivalent of Honcho's multipart file upload request body. Content is consumed in memory and is not persisted as original file bytes.

type ImportanceScorer

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

func NewImportanceScorer

func NewImportanceScorer() *ImportanceScorer

func (*ImportanceScorer) EffectiveImportance

func (s *ImportanceScorer) EffectiveImportance(entry MemoryToolEntry, now time.Time) float64

func (*ImportanceScorer) Rank

func (s *ImportanceScorer) Rank(entries []MemoryToolEntry, relevanceByID map[string]float64, now time.Time) []ScoredMemory

func (*ImportanceScorer) RankByQuery

func (s *ImportanceScorer) RankByQuery(entries []MemoryToolEntry, query string, now time.Time) []ScoredMemory

func (*ImportanceScorer) ReviewRetentionCandidates

func (s *ImportanceScorer) ReviewRetentionCandidates(entries []MemoryToolEntry, policy RetentionPolicy) []RetentionCandidate

func (*ImportanceScorer) Score

func (s *ImportanceScorer) Score(entry MemoryToolEntry, relevanceScore float64, now time.Time) float64

type ImportedFileMessage

type ImportedFileMessage struct {
	ID               int64              `json:"id"`
	SessionKey       string             `json:"session_key"`
	PeerID           string             `json:"peer_id"`
	Role             string             `json:"role"`
	Content          string             `json:"content"`
	CreatedAt        time.Time          `json:"created_at"`
	MemorySyncStatus string             `json:"memory_sync_status"`
	MemorySyncReason string             `json:"memory_sync_reason,omitempty"`
	Metadata         map[string]any     `json:"metadata,omitempty"`
	Configuration    map[string]any     `json:"configuration,omitempty"`
	File             FileImportMetadata `json:"file"`
}

ImportedFileMessage is the stable return shape for each imported chunk.

type LocalMarkdownMemoryConfig

type LocalMarkdownMemoryConfig struct {
	Path           string
	AgentID        string
	WorkspaceID    string
	ObserverPeerID string
	PeerID         string
	SessionID      string
}

LocalMarkdownMemoryConfig wires the local-first Goncho V1 memory tools to a SQLite database and a Markdown export file.

type LocalMarkdownMemoryStatus

type LocalMarkdownMemoryStatus struct {
	Enabled         bool     `json:"enabled"`
	Path            string   `json:"path"`
	LocalFirst      bool     `json:"local_first"`
	SQLiteBacked    bool     `json:"sqlite_backed"`
	MarkdownBacked  bool     `json:"markdown_backed"`
	NetworkRequired bool     `json:"network_required"`
	OllamaRequired  bool     `json:"ollama_required"`
	MCPTools        []string `json:"mcp_tools"`
	Evidence        []string `json:"evidence,omitempty"`
}

LocalMarkdownMemoryStatus is the operator-facing status for the local memory backend used by Memory V1 MCP tools.

type LocalMarkdownMemoryStore

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

LocalMarkdownMemoryStore persists tool memories into the Goncho V1 SQLite table and mirrors the table to a human-editable Markdown file.

func NewLocalMarkdownMemoryStore

func NewLocalMarkdownMemoryStore(db *sql.DB, cfg LocalMarkdownMemoryConfig) *LocalMarkdownMemoryStore

func (*LocalMarkdownMemoryStore) Forget

func (*LocalMarkdownMemoryStore) Retrieve

func (s *LocalMarkdownMemoryStore) Retrieve(ctx context.Context, query string, limit int) ([]MemoryToolEntry, error)

func (*LocalMarkdownMemoryStore) Status

func (*LocalMarkdownMemoryStore) Store

func (*LocalMarkdownMemoryStore) Update

func (s *LocalMarkdownMemoryStore) Update(ctx context.Context, id string, content string) error

func (*LocalMarkdownMemoryStore) UpdateImportance

func (s *LocalMarkdownMemoryStore) UpdateImportance(ctx context.Context, id string, importance float64) error

type MemoryContradiction

type MemoryContradiction struct {
	Existing MemoryToolEntry
	Incoming MemoryToolEntry
	Subject  string
	Relation string
	Reason   string
}

func DetectMemoryContradiction

func DetectMemoryContradiction(existing, incoming MemoryToolEntry) (MemoryContradiction, bool)

type MemoryEntry

type MemoryEntry struct {
	ID         string
	Type       MemoryType
	Content    string
	Confidence float64
	Durability float64
	CreatedAt  time.Time
	UpdatedAt  time.Time
	LastUsedAt time.Time
}

type MemoryImportanceUpdater

type MemoryImportanceUpdater interface {
	UpdateImportance(ctx context.Context, id string, importance float64) error
}

type MemoryNamespace added in v0.1.1

type MemoryNamespace struct {
	WorkspaceID      string `json:"workspace_id"`
	ProfileID        string `json:"profile_id"`
	PeerID           string `json:"peer_id,omitempty"`
	Scope            string `json:"scope,omitempty"`
	ProfileDirectory string `json:"profile_directory,omitempty"`
}

type MemoryProposal

type MemoryProposal struct {
	ID                int64           `json:"id"`
	ProposalID        string          `json:"proposal_id"`
	SubtaskID         string          `json:"subtask_id"`
	ChildAgentID      string          `json:"child_agent_id"`
	ParentAgentID     string          `json:"parent_agent_id"`
	ProposedTier      MemoryTier      `json:"proposed_tier"`
	Kind              ProposalKind    `json:"kind"`
	Content           string          `json:"content"`
	EvidenceJSON      json.RawMessage `json:"evidence_json"`
	Status            ProposalStatus  `json:"status"`
	ReviewedBy        *string         `json:"reviewed_by,omitempty"`
	ReviewedAt        *int64          `json:"reviewed_at,omitempty"`
	CommittedMemoryID *string         `json:"committed_memory_id,omitempty"`
	CreatedAt         int64           `json:"created_at"`
}

MemoryProposal represents a child agent's tentative write to durable memory. Children propose; parents review and commit.

func GetProposal

func GetProposal(ctx context.Context, db *sql.DB, proposalID string) (*MemoryProposal, error)

GetProposal fetches a single proposal by its ID.

func ListPendingProposals

func ListPendingProposals(ctx context.Context, db *sql.DB, parentAgentID string) ([]MemoryProposal, error)

ListPendingProposals returns all pending proposals for a given parent agent, ordered by creation time (newest first).

type MemoryStore

type MemoryStore interface {
	Apply(ctx context.Context, w MemoryWrite) error
	List(ctx context.Context) ([]MemoryWrite, error)
}

MemoryStore is the seam the write queue uses to persist memories. Apply must be safe to call from a single goroutine; the queue serializes calls.

type MemoryTier

type MemoryTier string
const (
	TierGlobal    MemoryTier = "global"
	TierProject   MemoryTier = "project"
	TierTask      MemoryTier = "task"
	TierWorkspace MemoryTier = "workspace"
	TierDecision  MemoryTier = "decision"
)

func DefaultTierForSource

func DefaultTierForSource(sourceKind string) MemoryTier

func NormalizeTier

func NormalizeTier(raw string) MemoryTier

func TierHierarchy

func TierHierarchy() []MemoryTier

func TiersReadableBy

func TiersReadableBy(agentTier MemoryTier) []MemoryTier

func TiersWritableBy

func TiersWritableBy(isParent bool) []MemoryTier

type MemoryToolEntry

type MemoryToolEntry struct {
	ID         string            `json:"id"`
	Content    string            `json:"content"`
	Tags       []string          `json:"tags"`
	Importance float64           `json:"importance"`
	SessionID  string            `json:"session_id,omitempty"`
	CreatedAt  time.Time         `json:"created_at"`
	UpdatedAt  time.Time         `json:"updated_at"`
	Metadata   map[string]string `json:"metadata,omitempty"`
}

MemoryToolEntry is a single unit of agent-managed memory.

func RecentEntries

func RecentEntries(entries []MemoryToolEntry, now time.Time, maxAge time.Duration) []MemoryToolEntry

type MemoryToolStore

type MemoryToolStore interface {
	Store(ctx context.Context, entry MemoryToolEntry) error
	Retrieve(ctx context.Context, query string, limit int) ([]MemoryToolEntry, error)
	Update(ctx context.Context, id string, content string) error
	Forget(ctx context.Context, id string) error
}

MemoryToolStore abstracts the storage backend for agent-controlled memory tool calls.

type MemoryType

type MemoryType string
const (
	MemoryTypeIdentity   MemoryType = "identity"
	MemoryTypePreference MemoryType = "preference"
	MemoryTypeGoal       MemoryType = "goal"
	MemoryTypeHabit      MemoryType = "habit"
	MemoryTypeEpisode    MemoryType = "episode"
	MemoryTypeReflection MemoryType = "reflection"
)

type MemoryV1ToolContractInfo

type MemoryV1ToolContractInfo struct {
	ContractVersion                string                      `json:"contract_version"`
	PrivateAgentMemoryDefault      bool                        `json:"private_agent_memory_default"`
	SelfImprovementPerAgentDefault bool                        `json:"self_improvement_per_agent_default"`
	PurgePolicy                    string                      `json:"purge_policy"`
	Tools                          map[string]MemoryV1ToolSpec `json:"tools"`
}

func MemoryV1ToolContract

func MemoryV1ToolContract() MemoryV1ToolContractInfo

type MemoryV1ToolSpec

type MemoryV1ToolSpec struct {
	Name                  string `json:"name"`
	Mutating              bool   `json:"mutating"`
	Idempotent            bool   `json:"idempotent"`
	RequiresStableID      bool   `json:"requires_stable_id"`
	RequiresProvenance    bool   `json:"requires_provenance"`
	CreatesRevision       bool   `json:"creates_revision"`
	DeleteSemantics       string `json:"delete_semantics,omitempty"`
	ResultContractVersion string `json:"result_contract_version"`
}

type MemoryV1ToolTranscriptEntry

type MemoryV1ToolTranscriptEntry struct {
	Tool      string         `json:"tool"`
	Arguments map[string]any `json:"arguments"`
	Result    map[string]any `json:"result"`
}

func DecodeMemoryV1ToolTranscript

func DecodeMemoryV1ToolTranscript(body []byte) ([]MemoryV1ToolTranscriptEntry, error)

type MemoryWrite

type MemoryWrite struct {
	ID      string
	Content string
	Tags    []string
}

MemoryWrite is the Goncho-native shape submitted to the serialized write queue. It is intentionally narrower than the full Honcho message envelope: the queue only needs a stable ID and the content/tags the detector can inspect to surface relation candidates.

type Message

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

Message is a goncho-owned chat message type used by session summary extraction. It replaces hermes.Message to enable standalone extraction.

type MessageRecord

type MessageRecord struct {
	ID          int64          `json:"id"`
	WorkspaceID string         `json:"workspace_id"`
	SessionKey  string         `json:"session_key"`
	Peer        string         `json:"peer_id"`
	Role        string         `json:"role"`
	Content     string         `json:"content"`
	Sequence    int            `json:"seq_in_session"`
	CreatedAt   int64          `json:"created_at"`
	Metadata    map[string]any `json:"metadata,omitempty"`
}

type MessageSearchHit

type MessageSearchHit struct {
	SessionID string
	ChatID    string
	Source    string
	Role      string
	Content   string
	TSUnix    int64
	Lineage   SearchLineage
}

MessageSearchHit is one turn-level result from the session catalog.

func SearchMessages

func SearchMessages(ctx context.Context, db *sql.DB, metas []SessionMetadata, filter SearchFilter, limit int) ([]MessageSearchHit, error)

SearchMessages returns matching turns across the canonical sessions bound to one user, optionally narrowed to a subset of sources.

type MessageSlice

type MessageSlice struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

MessageSlice is one recent message excerpt included in context responses.

type Observation

type Observation struct {
	ID                  string            `json:"id"`
	Kind                ObservationKind   `json:"kind"`
	WorkspaceID         string            `json:"workspace_id,omitempty"`
	ProfileID           string            `json:"profile_id,omitempty"`
	PeerID              string            `json:"peer_id,omitempty"`
	SessionKey          string            `json:"session_key,omitempty"`
	ContextID           string            `json:"context_id,omitempty"`
	Input               string            `json:"input"`
	Output              string            `json:"output"`
	Success             *bool             `json:"success,omitempty"`
	Metadata            map[string]string `json:"metadata,omitempty"`
	InputTruncated      bool              `json:"input_truncated"`
	OutputTruncated     bool              `json:"output_truncated"`
	InputOriginalBytes  int               `json:"input_original_bytes"`
	OutputOriginalBytes int               `json:"output_original_bytes"`
	Redacted            bool              `json:"redacted"`
	RedactionCount      int               `json:"redaction_count"`
	Checksum            string            `json:"checksum"`
	ObservedAt          time.Time         `json:"observed_at"`
}

type ObservationDecision

type ObservationDecision struct {
	ObserveMe     bool
	ObserveOthers bool
	Evidence      []string
}

func DefaultObservation

func DefaultObservation(req ObservationRequest) ObservationDecision

type ObservationKind

type ObservationKind string
const (
	ObservationKindSessionStart      ObservationKind = "session_start"
	ObservationKindUserPrompt        ObservationKind = "user_prompt"
	ObservationKindToolCall          ObservationKind = "tool_call"
	ObservationKindToolResult        ObservationKind = "tool_result"
	ObservationKindToolError         ObservationKind = "tool_error"
	ObservationKindAssistantResponse ObservationKind = "assistant_response"
	ObservationKindCompact           ObservationKind = "compact"
	ObservationKindSessionEnd        ObservationKind = "session_end"
	ObservationKindCustom            ObservationKind = "custom"
)

type ObservationList

type ObservationList struct {
	Observations []Observation `json:"observations"`
	Count        int           `json:"count"`
}

func ListObservations

func ListObservations(ctx context.Context, db *sql.DB, q ObservationQuery) (ObservationList, error)

type ObservationParams

type ObservationParams struct {
	ID          string            `json:"id,omitempty"`
	Kind        ObservationKind   `json:"kind"`
	WorkspaceID string            `json:"workspace_id,omitempty"`
	ProfileID   string            `json:"profile_id,omitempty"`
	PeerID      string            `json:"peer_id,omitempty"`
	SessionKey  string            `json:"session_key,omitempty"`
	ContextID   string            `json:"context_id,omitempty"`
	Input       string            `json:"input"`
	Output      string            `json:"output"`
	Success     *bool             `json:"success,omitempty"`
	Metadata    map[string]string `json:"metadata,omitempty"`
	ObservedAt  time.Time         `json:"observed_at,omitempty"`
	Reason      string            `json:"reason,omitempty"`
}

type ObservationQuery

type ObservationQuery struct {
	WorkspaceID string            `json:"workspace_id,omitempty"`
	ProfileID   string            `json:"profile_id,omitempty"`
	PeerID      string            `json:"peer_id,omitempty"`
	SessionKey  string            `json:"session_key,omitempty"`
	ContextID   string            `json:"context_id,omitempty"`
	Kinds       []ObservationKind `json:"kinds,omitempty"`
	Success     *bool             `json:"success,omitempty"`
	Since       time.Time         `json:"since,omitempty"`
	Until       time.Time         `json:"until,omitempty"`
	Limit       int               `json:"limit,omitempty"`
}

type ObservationRequest

type ObservationRequest struct {
	Role                 PeerRole
	CrossPeerObservation bool
}

type ObservationResult

type ObservationResult struct {
	Observation Observation `json:"observation"`
	AuditID     string      `json:"audit_id"`
	Replayed    bool        `json:"replayed,omitempty"`
}

type PeerIdentityDecision

type PeerIdentityDecision struct {
	PeerID   string
	Degraded bool
	Evidence []string
}

func ResolvePeerID

func ResolvePeerID(meta SessionMetadata) (PeerIdentityDecision, error)

type PeerRole

type PeerRole string
const (
	PeerRoleHuman                  PeerRole = "human"
	PeerRoleGormesAssistant        PeerRole = "gormes_assistant"
	PeerRoleDeterministicAssistant PeerRole = "deterministic_assistant"
	PeerRoleTransportBot           PeerRole = "transport_bot"
	PeerRoleImportHelper           PeerRole = "import_helper"
	PeerRoleParentAgent            PeerRole = "parent_agent"
)

type PluginAsyncResult

type PluginAsyncResult struct {
	Code     string
	Flushed  int
	Pending  int
	Evidence []string
}

func (PluginAsyncResult) HasEvidence

func (r PluginAsyncResult) HasEvidence(code string) bool

type PluginAsyncWriter

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

func NewPluginAsyncWriter

func NewPluginAsyncWriter(flusher PluginSessionFlusher) *PluginAsyncWriter

func (*PluginAsyncWriter) Cache

func (w *PluginAsyncWriter) Cache(session PluginMemorySession)

func (*PluginAsyncWriter) Enqueue

func (*PluginAsyncWriter) FlushAll

func (w *PluginAsyncWriter) FlushAll() PluginAsyncResult

func (*PluginAsyncWriter) Shutdown

func (w *PluginAsyncWriter) Shutdown() PluginAsyncResult

type PluginConfig

type PluginConfig struct {
	Host              string
	WorkspaceID       string
	APIKey            string
	APIKeySource      string
	Environment       string
	BaseURL           string
	PeerName          string
	AIPeer            string
	PinPeerName       bool
	Enabled           bool
	SaveMessages      bool
	WriteFrequency    PluginWriteFrequency
	SessionStrategy   string
	SessionPeerPrefix bool
	Sessions          map[string]string
	Raw               map[string]any
	Evidence          []ConfigEvidence
}

func ResolvePluginConfig

func ResolvePluginConfig(input PluginConfigInput) PluginConfig

func (PluginConfig) HasEvidence

func (c PluginConfig) HasEvidence(code string) bool

type PluginConfigInput

type PluginConfigInput struct {
	Host string
	Raw  map[string]any
	Env  map[string]string
}

type PluginMemoryMessage

type PluginMemoryMessage struct {
	Role    string
	Content string
	Synced  bool
}

type PluginMemorySession

type PluginMemorySession struct {
	Key             string
	UserPeerID      string
	AssistantPeerID string
	HonchoSessionID string
	Messages        []PluginMemoryMessage
}

type PluginPeerInput

type PluginPeerInput struct {
	Config              PluginConfig
	RuntimeUserPeerName string
	SessionKey          string
}

type PluginPeerResolution

type PluginPeerResolution struct {
	UserPeerID      string
	AssistantPeerID string
}

func ResolvePluginPeerNames

func ResolvePluginPeerNames(input PluginPeerInput) PluginPeerResolution

type PluginSessionFlusher

type PluginSessionFlusher interface {
	FlushPluginSession(PluginMemorySession) error
}

type PluginSessionFlusherFunc

type PluginSessionFlusherFunc func(PluginMemorySession) error

func (PluginSessionFlusherFunc) FlushPluginSession

func (f PluginSessionFlusherFunc) FlushPluginSession(session PluginMemorySession) error

type PluginWriteFrequency

type PluginWriteFrequency struct {
	Mode  WriteFrequencyMode
	Every int
	Raw   string
}

func ParsePluginWriteFrequency

func ParsePluginWriteFrequency(raw any) PluginWriteFrequency

type PluginWriteResult

type PluginWriteResult struct {
	Code     string
	Evidence []string
}

type PluginWriteRouter

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

func NewPluginWriteRouter

func NewPluginWriteRouter(cfg PluginWriteRouterConfig) *PluginWriteRouter

func (*PluginWriteRouter) Save

type PluginWriteRouterConfig

type PluginWriteRouterConfig struct {
	Frequency   PluginWriteFrequency
	Flusher     PluginSessionFlusher
	AsyncWriter *PluginAsyncWriter
}

type ProfileHint

type ProfileHint struct {
	Code         string   `json:"code"`
	Message      string   `json:"message"`
	Alternatives []string `json:"alternatives"`
}

ProfileHint gives honcho_profile callers actionable guidance when an empty peer card is a valid non-error state.

type ProfileResult

type ProfileResult struct {
	WorkspaceID    string       `json:"workspace_id"`
	ProfileID      string       `json:"profile_id,omitempty"`
	Peer           string       `json:"peer"`
	Target         string       `json:"target,omitempty"`
	ObserverPeerID string       `json:"observer_peer_id,omitempty"`
	ObservedPeerID string       `json:"observed_peer_id,omitempty"`
	Card           []string     `json:"card"`
	Result         string       `json:"result,omitempty"`
	Hint           *ProfileHint `json:"hint,omitempty"`
}

ProfileResult is the external shape used by profile reads and updates.

type ProposalKind

type ProposalKind string

ProposalKind enumerates the types of memory a child agent can propose.

const (
	KindFact        ProposalKind = "fact"
	KindPreference  ProposalKind = "preference"
	KindDecision    ProposalKind = "decision"
	KindObservation ProposalKind = "observation"
	KindReport      ProposalKind = "report"
	KindArtifact    ProposalKind = "artifact"
)

type ProposalRef

type ProposalRef struct {
	ProposalID    string         `json:"proposal_id"`
	ChildAgentID  string         `json:"child_agent_id"`
	ParentAgentID string         `json:"parent_agent_id"`
	Status        ProposalStatus `json:"status"`
}

ProposalRef is a lightweight handle returned when submitting a proposal.

func SubmitProposal

func SubmitProposal(ctx context.Context, db *sql.DB, subtaskID, childAgentID, parentAgentID, content string, tier MemoryTier, kind ProposalKind, evidence any) (*ProposalRef, error)

SubmitProposal inserts a child agent's memory proposal into the database. The proposal enters "pending" status awaiting parent review. Returns a ProposalRef for the caller to track the submission.

type ProposalStatus

type ProposalStatus string

ProposalStatus tracks the lifecycle state of a memory proposal.

const (
	StatusPending  ProposalStatus = "pending"
	StatusAccepted ProposalStatus = "accepted"
	StatusRejected ProposalStatus = "rejected"
)

type QueueEmptyWebhookEventParams

type QueueEmptyWebhookEventParams struct {
	WorkspaceID string
	QueueType   string
	SessionID   string
	Observer    string
	Observed    string
}

type QueueStatus

type QueueStatus struct {
	Status            string                         `json:"status"`
	ObservabilityOnly bool                           `json:"observability_only"`
	WorkUnits         map[string]QueueWorkUnitStatus `json:"work_units"`
	Dream             DreamQueueStatus               `json:"dream"`
	Degraded          bool                           `json:"degraded"`
	Message           string                         `json:"message"`
}

QueueStatus is the local Goncho queue status read model. Until a dedicated Goncho task queue exists, it reports deterministic zero-state counts with degraded evidence.

func ReadQueueStatus

func ReadQueueStatus(ctx context.Context, db *sql.DB, cfgs ...QueueStatusConfig) (QueueStatus, error)

ReadQueueStatus returns a deterministic local read model. It never waits for the queue to drain; dream rows are auditable work intent, not worker output.

func ZeroQueueStatus

func ZeroQueueStatus() QueueStatus

ZeroQueueStatus reports that no dedicated Goncho task queue exists yet while preserving Honcho-compatible work-unit fields.

type QueueStatusConfig

type QueueStatusConfig struct {
	DreamEnabled     bool
	WorkspaceID      string
	ObserverPeerID   string
	Now              time.Time
	DreamIdleTimeout time.Duration
}

QueueStatusConfig supplies config-dependent dream status to ReadQueueStatus.

type QueueWorkUnitStatus

type QueueWorkUnitStatus struct {
	CompletedWorkUnits  int                            `json:"completed_work_units"`
	InProgressWorkUnits int                            `json:"in_progress_work_units"`
	PendingWorkUnits    int                            `json:"pending_work_units"`
	TotalWorkUnits      int                            `json:"total_work_units"`
	Sessions            map[string]QueueWorkUnitStatus `json:"sessions,omitempty"`
}

QueueWorkUnitStatus mirrors Honcho's queue status count shape.

type ReasoningTraceInput

type ReasoningTraceInput struct {
	TraceID, TreeNodeID, ParentID, EventType, TaskType, Provider, Model, ReasoningEffort string
	Level, InputTokens, OutputTokens                                                     int
	StartedAt, FinishedAt                                                                time.Time
	ToolCalls                                                                            []string
	Payload                                                                              map[string]any
}

type ReasoningTraceRecord

type ReasoningTraceRecord struct {
	TraceID, TreeNodeID, ParentID, EventType, TaskType, Provider, Model, ReasoningEffort string
	Level                                                                                int
	Timestamp                                                                            time.Time
	DurationMs                                                                           int64
	InputTokens, OutputTokens                                                            int
	ToolCalls                                                                            []string
	PayloadSummary                                                                       map[string]string
	Redactions                                                                           []RedactionEvidence
}

func NewReasoningTraceRecord

func NewReasoningTraceRecord(input ReasoningTraceInput) ReasoningTraceRecord

func (ReasoningTraceRecord) TelemetryEvent

func (r ReasoningTraceRecord) TelemetryEvent() Event

type RecallBenchmarkCase

type RecallBenchmarkCase struct {
	ID              string
	Trace           RecallTrace
	RelevantIDs     []string
	ContextContains []string
	Latency         time.Duration
}

RecallBenchmarkCase is one hermetic retrieval-evaluation case. It consumes an already-produced RecallTrace; it never runs retrieval or opens storage.

type RecallBenchmarkCaseReport

type RecallBenchmarkCaseReport struct {
	ID                   string   `json:"id"`
	TraceID              string   `json:"trace_id"`
	PipelineVersion      string   `json:"pipeline_version"`
	ScoringConfigVersion string   `json:"scoring_config_version"`
	RelevantIDs          []string `json:"relevant_ids"`
	CandidateMemoryIDs   []string `json:"candidate_memory_ids"`
	SelectedMemoryIDs    []string `json:"selected_memory_ids"`
	RecallAt5            float64  `json:"recall_at_5"`
	RecallAt10           float64  `json:"recall_at_10"`
	ContextSatisfied     bool     `json:"context_satisfied"`
	TokenBudget          int      `json:"token_budget"`
	SelectedTokens       int      `json:"selected_tokens"`
	TokenBudgetWithin    bool     `json:"token_budget_within"`
	LatencyMS            int      `json:"latency_ms"`
	WarningCodes         []string `json:"warning_codes"`
}

type RecallBenchmarkLatency

type RecallBenchmarkLatency struct {
	MinMS int `json:"min_ms"`
	P50MS int `json:"p50_ms"`
	P95MS int `json:"p95_ms"`
	MaxMS int `json:"max_ms"`
}

type RecallBenchmarkReport

type RecallBenchmarkReport struct {
	Service             string                      `json:"service"`
	CorpusVersion       string                      `json:"corpus_version"`
	CaseCount           int                         `json:"case_count"`
	RecallAt5           float64                     `json:"recall_at_5"`
	RecallAt10          float64                     `json:"recall_at_10"`
	ContextHitRate      float64                     `json:"context_hit_rate"`
	TokenBudgetPassRate float64                     `json:"token_budget_pass_rate"`
	Latency             RecallBenchmarkLatency      `json:"latency"`
	WarningCount        int                         `json:"warning_count"`
	Warnings            []RecallWarning             `json:"warnings"`
	Cases               []RecallBenchmarkCaseReport `json:"cases"`
}

func EvaluateRecallBenchmark

func EvaluateRecallBenchmark(cases []RecallBenchmarkCase) RecallBenchmarkReport

type RecallCandidate

type RecallCandidate struct {
	MemoryID   string         `json:"memory_id"`
	SourceType string         `json:"source_type"`
	Content    string         `json:"content"`
	SessionID  string         `json:"session_id,omitempty"`
	AgentID    string         `json:"agent_id,omitempty"`
	ScopeID    string         `json:"scope_id,omitempty"`
	CreatedAt  time.Time      `json:"created_at,omitempty"`
	Importance float64        `json:"importance,omitempty"`
	Provenance []EvidenceItem `json:"provenance,omitempty"`
}

type RecallDiagnosticsCandidate

type RecallDiagnosticsCandidate struct {
	MemoryID       string      `json:"memory_id"`
	SourceType     string      `json:"source_type,omitempty"`
	SessionID      string      `json:"session_id,omitempty"`
	AgentID        string      `json:"agent_id,omitempty"`
	ScopeID        string      `json:"scope_id,omitempty"`
	ContentPreview string      `json:"content_preview,omitempty"`
	FinalScore     float64     `json:"final_score"`
	Scores         RecallScore `json:"scores"`
	WhySelected    []string    `json:"why_selected,omitempty"`
}

type RecallDiagnosticsRejection

type RecallDiagnosticsRejection struct {
	MemoryID       string      `json:"memory_id"`
	SourceType     string      `json:"source_type,omitempty"`
	SessionID      string      `json:"session_id,omitempty"`
	AgentID        string      `json:"agent_id,omitempty"`
	ScopeID        string      `json:"scope_id,omitempty"`
	ContentPreview string      `json:"content_preview,omitempty"`
	Reason         string      `json:"reason"`
	FinalScore     float64     `json:"final_score"`
	Scores         RecallScore `json:"scores"`
	WhyRejected    []string    `json:"why_rejected,omitempty"`
}

type RecallDiagnosticsReport

type RecallDiagnosticsReport struct {
	Service              string                       `json:"service"`
	Status               string                       `json:"status"`
	TraceID              string                       `json:"trace_id"`
	PipelineVersion      string                       `json:"pipeline_version"`
	Query                RecallQuery                  `json:"query"`
	ScoringConfig        RecallScoringConfig          `json:"scoring_config"`
	CandidateCount       int                          `json:"candidate_count"`
	SelectedCount        int                          `json:"selected_count"`
	RejectedCount        int                          `json:"rejected_count"`
	WarningCount         int                          `json:"warning_count"`
	Selected             []RecallDiagnosticsCandidate `json:"selected"`
	Rejected             []RecallDiagnosticsRejection `json:"rejected"`
	Warnings             []RecallWarning              `json:"warnings"`
	ProjectionInvariant  string                       `json:"projection_invariant"`
	DegradedPathContract string                       `json:"degraded_path_contract"`
}

func BuildRecallDiagnostics

func BuildRecallDiagnostics(trace RecallTrace) RecallDiagnosticsReport

type RecallEngine

type RecallEngine interface {
	Run(ctx context.Context, q RecallQuery) (RecallTrace, error)
}

type RecallProjector

type RecallProjector struct{}

func (*RecallProjector) ProjectContext

func (p *RecallProjector) ProjectContext(trace RecallTrace) ContextResult

func (*RecallProjector) ProjectSearch

func (p *RecallProjector) ProjectSearch(trace RecallTrace) SearchResultSet

type RecallQuery

type RecallQuery struct {
	WorkspaceID string   `json:"workspace_id"`
	Peer        string   `json:"peer"`
	Query       string   `json:"query"`
	SessionKey  string   `json:"session_key,omitempty"`
	ScopeID     string   `json:"scope_id,omitempty"`
	Sources     []string `json:"sources,omitempty"`
	Limit       int      `json:"limit,omitempty"`
	MaxTokens   int      `json:"max_tokens,omitempty"`
}

type RecallReplay

type RecallReplay struct {
	Service              string              `json:"service"`
	TraceID              string              `json:"trace_id"`
	PipelineVersion      string              `json:"pipeline_version"`
	ScoringConfigVersion string              `json:"scoring_config_version"`
	Query                RecallQuery         `json:"query"`
	EventCount           int                 `json:"event_count"`
	Events               []RecallReplayEvent `json:"events"`
	ProjectionInvariant  string              `json:"projection_invariant"`
	ReplayContract       string              `json:"replay_contract"`
}

func BuildRecallReplay

func BuildRecallReplay(trace RecallTrace) RecallReplay

type RecallReplayEvent

type RecallReplayEvent struct {
	Index       int      `json:"index"`
	Stage       string   `json:"stage"`
	Kind        string   `json:"kind"`
	MemoryID    string   `json:"memory_id,omitempty"`
	SourceType  string   `json:"source_type,omitempty"`
	SessionID   string   `json:"session_id,omitempty"`
	AgentID     string   `json:"agent_id,omitempty"`
	ScopeID     string   `json:"scope_id,omitempty"`
	Reason      string   `json:"reason,omitempty"`
	FinalScore  float64  `json:"final_score,omitempty"`
	WarningCode string   `json:"warning_code,omitempty"`
	Severity    string   `json:"severity,omitempty"`
	Details     []string `json:"details,omitempty"`
}

type RecallScore

type RecallScore struct {
	KeywordScore     float64  `json:"keyword_score"`
	SemanticScore    float64  `json:"semantic_score"`
	GraphScore       float64  `json:"graph_score"`
	RecencyScore     float64  `json:"recency_score"`
	ImportanceScore  float64  `json:"importance_score"`
	ScopeScore       float64  `json:"scope_score"`
	RRFScore         float64  `json:"rrf_score"`
	DiversityPenalty float64  `json:"diversity_penalty"`
	FinalScore       float64  `json:"final_score"`
	WhySelected      []string `json:"why_selected,omitempty"`
}

type RecallScoringConfig

type RecallScoringConfig struct {
	Version       string             `json:"version"`
	Weights       map[string]float64 `json:"weights"`
	RRFK          int                `json:"rrf_k"`
	MMRLambda     float64            `json:"mmr_lambda"`
	DiversityKeys []string           `json:"diversity_keys,omitempty"`
	TokenBudget   int                `json:"token_budget,omitempty"`
}

type RecallTrace

type RecallTrace struct {
	TraceID         string                    `json:"trace_id"`
	PipelineVersion string                    `json:"pipeline_version"`
	CreatedAt       time.Time                 `json:"created_at"`
	Query           RecallQuery               `json:"query"`
	ScoringConfig   RecallScoringConfig       `json:"scoring_config"`
	Candidates      []ScoredRecallCandidate   `json:"candidates"`
	Selected        []ScoredRecallCandidate   `json:"selected"`
	Rejected        []RejectedRecallCandidate `json:"rejected"`
	Warnings        []RecallWarning           `json:"warnings"`
}

func DecodeRecallTraceJSON

func DecodeRecallTraceJSON(r io.Reader) (RecallTrace, error)

func (RecallTrace) StableJSON

func (t RecallTrace) StableJSON() ([]byte, error)

type RecallWarning

type RecallWarning struct {
	Code     string            `json:"code"`
	Stage    string            `json:"stage"`
	Severity string            `json:"severity"`
	Message  string            `json:"message,omitempty"`
	Evidence map[string]string `json:"evidence,omitempty"`
}

type RedactionEvidence

type RedactionEvidence struct {
	Field, Reason string
}

func SummarizePayload

func SummarizePayload(payload map[string]any) (map[string]string, []RedactionEvidence)

type RejectedRecallCandidate

type RejectedRecallCandidate struct {
	Candidate   RecallCandidate `json:"candidate"`
	Score       RecallScore     `json:"score"`
	Reason      string          `json:"reason"`
	WhyRejected []string        `json:"why_rejected,omitempty"`
}

type RelationCandidate

type RelationCandidate struct {
	From string       // memory ID the relation originates from
	To   string       // memory ID the relation targets
	Verb RelationVerb // canonical Goncho relation vocabulary
	Note string       // free-form note for later human/LLM judgment
}

RelationCandidate is one PENDING relation between two memories awaiting later judgment. The detector returns these synchronously after a write completes; storage must not block the originating write.

type RelationStore

type RelationStore interface {
	SavePending(ctx context.Context, candidates []RelationCandidate) error
}

RelationStore persists pending relation candidates. Implementations must treat the candidates as PENDING — no judgment, no LLM, no resolution.

type RelationVerb

type RelationVerb string

RelationVerb names a Goncho-native relation between two memories. The vocabulary is intentionally Honcho-compatible and does not surface Engram-specific identifiers in any public Gormes/Honcho API.

const (
	// RelationRelated is the catch-all "see also" link between two memories.
	RelationRelated RelationVerb = "related"
	// RelationConflicts marks a contradiction that may need human or judge
	// resolution; the original write still succeeds and the candidate is
	// stored as PENDING.
	RelationConflicts RelationVerb = "conflicts_with"
	// RelationSupersedes marks the new memory as replacing an older one.
	RelationSupersedes RelationVerb = "supersedes"
	// RelationCompatible marks two memories as not in conflict and reinforcing.
	RelationCompatible RelationVerb = "compatible"
	// RelationScoped marks a relation that only holds inside a narrower scope
	// (e.g. one session or one peer card slot).
	RelationScoped RelationVerb = "scoped"
	// RelationNotConflict explicitly records that a candidate inspected by the
	// detector was found to be not in conflict, useful for audit trails.
	RelationNotConflict RelationVerb = "not_conflict"
)

Canonical Goncho relation vocabulary. New verbs must be added here so the pending-relation path remains deterministic and reviewable.

type RetentionAction

type RetentionAction string
const (
	RetentionActionSummarize RetentionAction = "summarize"
	RetentionActionForget    RetentionAction = "forget"
)

type RetentionCandidate

type RetentionCandidate struct {
	Entry               MemoryToolEntry
	Age                 time.Duration
	EffectiveImportance float64
	Action              RetentionAction
	Reason              string
}

type RetentionPolicy

type RetentionPolicy struct {
	Now                    time.Time
	MinAge                 time.Duration
	MinEffectiveImportance float64
	Limit                  int
}

type RetrieveMemoryTool

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

func NewRetrieveMemoryTool

func NewRetrieveMemoryTool(store MemoryToolStore) *RetrieveMemoryTool

func (*RetrieveMemoryTool) Description

func (t *RetrieveMemoryTool) Description() string

func (*RetrieveMemoryTool) Execute

func (t *RetrieveMemoryTool) Execute(ctx context.Context, args json.RawMessage) (json.RawMessage, error)

func (*RetrieveMemoryTool) Name

func (t *RetrieveMemoryTool) Name() string

func (*RetrieveMemoryTool) Schema

func (t *RetrieveMemoryTool) Schema() json.RawMessage

func (RetrieveMemoryTool) Spec

func (t RetrieveMemoryTool) Spec() toolmeta.OperationSpec

func (*RetrieveMemoryTool) Timeout

func (t *RetrieveMemoryTool) Timeout() time.Duration

type ReviewItem

type ReviewItem struct {
	ID               string           `json:"id"`
	Kind             ReviewKind       `json:"kind"`
	Status           ReviewStatus     `json:"status"`
	WorkspaceID      string           `json:"workspace_id"`
	PeerID           string           `json:"peer_id,omitempty"`
	SessionKey       string           `json:"session_key,omitempty"`
	SubjectID        string           `json:"subject_id"`
	RelatedID        string           `json:"related_id,omitempty"`
	Reason           string           `json:"reason"`
	EvidenceIDs      []string         `json:"evidence_ids,omitempty"`
	CreatedAt        time.Time        `json:"created_at"`
	Resolution       ReviewResolution `json:"resolution,omitempty"`
	ResolvedBy       string           `json:"resolved_by,omitempty"`
	ResolutionReason string           `json:"resolution_reason,omitempty"`
	ResolvedAt       *time.Time       `json:"resolved_at,omitempty"`
}

func CreateReviewItem

func CreateReviewItem(ctx context.Context, db *sql.DB, p ReviewItemCreateParams) (ReviewItem, error)

func ResolveReviewItem

func ResolveReviewItem(ctx context.Context, db *sql.DB, p ReviewResolutionParams) (ReviewItem, error)

type ReviewItemCreateParams

type ReviewItemCreateParams struct {
	Kind        ReviewKind `json:"kind"`
	WorkspaceID string     `json:"workspace_id,omitempty"`
	PeerID      string     `json:"peer_id,omitempty"`
	SessionKey  string     `json:"session_key,omitempty"`
	SubjectID   string     `json:"subject_id"`
	RelatedID   string     `json:"related_id,omitempty"`
	Reason      string     `json:"reason"`
	EvidenceIDs []string   `json:"evidence_ids,omitempty"`
	CreatedAt   time.Time  `json:"created_at,omitempty"`
}

type ReviewKind

type ReviewKind string
const (
	ReviewKindConflict ReviewKind = "conflict"
	ReviewKindStale    ReviewKind = "stale"
)

type ReviewList

type ReviewList struct {
	Items []ReviewItem `json:"items"`
	Count int          `json:"count"`
}

func ListReviewItems

func ListReviewItems(ctx context.Context, db *sql.DB, q ReviewQuery) (ReviewList, error)

type ReviewQuery

type ReviewQuery struct {
	WorkspaceID string       `json:"workspace_id,omitempty"`
	PeerID      string       `json:"peer_id,omitempty"`
	SessionKey  string       `json:"session_key,omitempty"`
	SubjectID   string       `json:"subject_id,omitempty"`
	RelatedID   string       `json:"related_id,omitempty"`
	Kind        ReviewKind   `json:"kind,omitempty"`
	Status      ReviewStatus `json:"status,omitempty"`
	Limit       int          `json:"limit,omitempty"`
}

type ReviewResolution

type ReviewResolution string
const (
	ReviewResolutionAccepted   ReviewResolution = "accepted"
	ReviewResolutionRejected   ReviewResolution = "rejected"
	ReviewResolutionSuperseded ReviewResolution = "superseded"
	ReviewResolutionVerified   ReviewResolution = "verified"
)

type ReviewResolutionParams

type ReviewResolutionParams struct {
	ID               string           `json:"id"`
	Resolution       ReviewResolution `json:"resolution"`
	ResolvedBy       string           `json:"resolved_by"`
	ResolutionReason string           `json:"resolution_reason"`
	ResolvedAt       time.Time        `json:"resolved_at,omitempty"`
}

type ReviewStatus

type ReviewStatus string
const (
	ReviewStatusOpen     ReviewStatus = "open"
	ReviewStatusResolved ReviewStatus = "resolved"
)

type ReviewTool

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

func NewReviewTool

func NewReviewTool(svc *Service) *ReviewTool

func (*ReviewTool) Description

func (t *ReviewTool) Description() string

func (*ReviewTool) Execute

func (t *ReviewTool) Execute(ctx context.Context, args json.RawMessage) (json.RawMessage, error)

func (*ReviewTool) Name

func (t *ReviewTool) Name() string

func (*ReviewTool) Schema

func (t *ReviewTool) Schema() json.RawMessage

func (*ReviewTool) Spec

func (t *ReviewTool) Spec() toolmeta.OperationSpec

func (*ReviewTool) Timeout

func (t *ReviewTool) Timeout() time.Duration

type ScopedKeyClaims

type ScopedKeyClaims struct {
	Timestamp   string `json:"t,omitempty"`
	ExpiresAt   string `json:"exp,omitempty"`
	Admin       *bool  `json:"ad,omitempty"`
	WorkspaceID string `json:"w,omitempty"`
	PeerID      string `json:"p,omitempty"`
	SessionID   string `json:"s,omitempty"`
}

func VerifyScopedKey

func VerifyScopedKey(token, secret string, now time.Time) (ScopedKeyClaims, error)

type ScopedKeyParams

type ScopedKeyParams struct {
	WorkspaceID string
	PeerID      string
	SessionID   string
	ExpiresAt   time.Time
	AuthEnabled bool
	Admin       bool
	Secret      string
	Now         time.Time
}

type ScopedKeyResult

type ScopedKeyResult struct {
	Key    string          `json:"key"`
	Claims ScopedKeyClaims `json:"claims"`
}

func CreateScopedKey

func CreateScopedKey(params ScopedKeyParams) (ScopedKeyResult, error)

type ScoredMemory

type ScoredMemory struct {
	Entry               MemoryToolEntry
	Relevance           float64
	Recency             float64
	EffectiveImportance float64
	Score               float64
}

type ScoredRecallCandidate

type ScoredRecallCandidate struct {
	Candidate RecallCandidate `json:"candidate"`
	Score     RecallScore     `json:"score"`
}

type SearchFilter

type SearchFilter struct {
	UserID           string
	Sources          []string
	SessionIDs       []string
	Query            string
	Roles            []string
	CurrentSessionID string
	CurrentChatKey   string
}

SearchFilter narrows cross-session search to one canonical user.

type SearchHit

type SearchHit struct {
	ID           int64          `json:"id,omitempty"`
	Source       string         `json:"source"`
	OriginSource string         `json:"origin_source,omitempty"`
	Content      string         `json:"content"`
	SessionKey   string         `json:"session_key,omitempty"`
	Lineage      *SearchLineage `json:"lineage,omitempty"`
}

SearchHit is one result entry returned by search.

type SearchLineage

type SearchLineage struct {
	ParentSessionID string   `json:"parent_session_id,omitempty"`
	LineageKind     string   `json:"lineage_kind,omitempty"`
	ChildSessionIDs []string `json:"child_session_ids,omitempty"`
	Status          string   `json:"status"`
}

SearchLineage is operator evidence for the session lineage attached to a search hit.

type SearchParams

type SearchParams struct {
	ProfileID  string         `json:"profile_id,omitempty"`
	Peer       string         `json:"peer"`
	Query      string         `json:"query"`
	MaxTokens  int            `json:"max_tokens,omitempty"`
	SessionKey string         `json:"session_key,omitempty"`
	Scope      string         `json:"scope,omitempty"`
	Sources    []string       `json:"sources,omitempty"`
	Filters    map[string]any `json:"filters,omitempty"`
	Limit      int            `json:"limit,omitempty"`
}

SearchParams controls retrieval for honcho_search.

type SearchResultSet

type SearchResultSet struct {
	WorkspaceID   string                   `json:"workspace_id"`
	ProfileID     string                   `json:"profile_id,omitempty"`
	Peer          string                   `json:"peer"`
	Query         string                   `json:"query"`
	ScopeEvidence *CrossChatRecallEvidence `json:"scope_evidence,omitempty"`
	Results       []SearchHit              `json:"results"`
}

SearchResultSet is the stable JSON shape for honcho_search.

type Service

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

Service is the first in-binary Goncho domain facade. It sits directly on top of the SQLite store used by Gormes today.

func NewService

func NewService(db *sql.DB, cfg Config, log *slog.Logger) *Service

NewService constructs a Goncho service with conservative defaults.

func (*Service) ApproveSkillLearningProposal added in v0.1.1

func (s *Service) ApproveSkillLearningProposal(ctx context.Context, p SkillLearningProposalReviewParams) (SkillLearningProposal, error)

func (*Service) AuditTrail

func (s *Service) AuditTrail(ctx context.Context, q AuditQuery) (AuditResult, error)

func (*Service) Chat

func (s *Service) Chat(ctx context.Context, peer string, params ChatParams) (ChatResult, error)

func (*Service) Conclude

func (s *Service) Conclude(ctx context.Context, params ConcludeParams) (ConcludeResult, error)

func (*Service) Context

func (s *Service) Context(ctx context.Context, params ContextParams) (ContextResult, error)

func (*Service) CreateMessages

func (s *Service) CreateMessages(ctx context.Context, params CreateMessagesParams) (CreateMessagesResult, error)

func (*Service) CreateReviewItem

func (s *Service) CreateReviewItem(ctx context.Context, p ReviewItemCreateParams) (ReviewItem, error)

func (*Service) DeleteSession

func (s *Service) DeleteSession(ctx context.Context, sessionKey string) (SessionDeletionResult, error)

func (*Service) DeleteWebhookEndpoint

func (s *Service) DeleteWebhookEndpoint(ctx context.Context, workspaceID, endpointID string) error

func (*Service) DeleteWorkspace

func (s *Service) DeleteWorkspace(ctx context.Context) (WorkspaceDeletionResult, error)

func (*Service) DialecticCaller

func (s *Service) DialecticCaller() DialecticCaller

func (*Service) ExecuteDreamCompression

func (s *Service) ExecuteDreamCompression(ctx context.Context) (int, error)

func (*Service) ExecuteDreamFactExtraction

func (s *Service) ExecuteDreamFactExtraction(ctx context.Context, sessionKey string) (int, error)

func (*Service) GetOrCreateWebhookEndpoint

func (s *Service) GetOrCreateWebhookEndpoint(ctx context.Context, params WebhookEndpointCreateParams) (WebhookEndpointCreateResult, error)

func (*Service) GetSkillLearningProposal added in v0.1.1

func (s *Service) GetSkillLearningProposal(ctx context.Context, proposalID string) (SkillLearningProposal, error)

func (*Service) ImportFile

func (s *Service) ImportFile(ctx context.Context, params ImportFileParams) (FileImportResult, error)

ImportFile converts a text-like file into ordinary ready user turns for the requested session. The original uploaded bytes are only used for extraction.

func (*Service) ListObservations

func (s *Service) ListObservations(ctx context.Context, q ObservationQuery) (ObservationList, error)

func (*Service) ListPendingSkillLearningProposals added in v0.1.1

func (s *Service) ListPendingSkillLearningProposals(ctx context.Context, q SkillLearningProposalQuery) (SkillLearningProposalList, error)

func (*Service) ListReviewItems

func (s *Service) ListReviewItems(ctx context.Context, q ReviewQuery) (ReviewList, error)

func (*Service) ListWebhookEndpoints

func (s *Service) ListWebhookEndpoints(ctx context.Context, workspaceID string) ([]WebhookEndpoint, error)

func (*Service) NewStreamingChatPersistence

func (s *Service) NewStreamingChatPersistence(peer string, params ChatParams) (*StreamingChatPersistence, error)

func (*Service) Observe

func (*Service) OnSessionEnd

func (s *Service) OnSessionEnd(ctx context.Context, sessionKey string, messages []Message) error

func (*Service) Profile

func (s *Service) Profile(ctx context.Context, peer string) (ProfileResult, error)

func (*Service) ProfileForTarget

func (s *Service) ProfileForTarget(ctx context.Context, peer, target string) (ProfileResult, error)

func (*Service) ProfileInNamespace added in v0.1.1

func (s *Service) ProfileInNamespace(ctx context.Context, ns MemoryNamespace) (ProfileResult, error)

func (*Service) RecordSkillOutcome

func (s *Service) RecordSkillOutcome(ctx context.Context, outcome SkillOutcome) error

RecordSkillOutcome writes a skill execution result as a Goncho conclusion. The source prefix "skill:<name>" is embedded in the conclusion text for later querying.

func (*Service) RejectSkillLearningProposal added in v0.1.1

func (s *Service) RejectSkillLearningProposal(ctx context.Context, p SkillLearningProposalReviewParams) (SkillLearningProposal, error)

func (*Service) ResolveReviewItem

func (s *Service) ResolveReviewItem(ctx context.Context, p ReviewResolutionParams) (ReviewItem, error)

func (*Service) ScheduleDream

func (s *Service) ScheduleDream(ctx context.Context, params DreamScheduleParams) (DreamScheduleResult, error)

func (*Service) Search

func (s *Service) Search(ctx context.Context, params SearchParams) (SearchResultSet, error)

func (*Service) SearchSkillOutcomes

func (s *Service) SearchSkillOutcomes(ctx context.Context, skillName string, limit int) ([]string, error)

SearchSkillOutcomes returns conclusions from skill executions matching the given skill name.

func (*Service) SetDialecticCaller

func (s *Service) SetDialecticCaller(dc DialecticCaller)

func (*Service) SetProfile

func (s *Service) SetProfile(ctx context.Context, peer string, card []string) error

func (*Service) SetProfileForTarget

func (s *Service) SetProfileForTarget(ctx context.Context, peer, target string, card []string) error

func (*Service) SetProfileInNamespace added in v0.1.1

func (s *Service) SetProfileInNamespace(ctx context.Context, ns MemoryNamespace, card []string) error

func (*Service) SubmitSkillLearningProposal added in v0.1.1

func (s *Service) SubmitSkillLearningProposal(ctx context.Context, p SkillLearningProposalCreateParams) (SkillLearningProposalRef, error)

func (*Service) VerifiedCodeContext

func (s *Service) VerifiedCodeContext(ctx context.Context, params VerifiedCodeContextParams) (VerifiedCodeContextResult, error)

type SessionBoundaryDecision

type SessionBoundaryDecision struct {
	Kind       SessionBoundaryKind
	SessionKey string
	Evidence   []string
}

type SessionBoundaryKind

type SessionBoundaryKind string
const (
	SessionBoundaryThread            SessionBoundaryKind = "thread"
	SessionBoundaryChannel           SessionBoundaryKind = "channel"
	SessionBoundaryRepository        SessionBoundaryKind = "repository"
	SessionBoundaryImportBatch       SessionBoundaryKind = "import_batch"
	SessionBoundaryDelegatedChildRun SessionBoundaryKind = "delegated_child_run"
)

type SessionBoundaryRequest

type SessionBoundaryRequest struct {
	Kind   SessionBoundaryKind
	Key    string
	Source string
}

type SessionDeletionResult

type SessionDeletionResult struct {
	WorkspaceID        string `json:"workspace_id"`
	SessionKey         string `json:"session_key"`
	MessagesDeleted    int64  `json:"messages_deleted"`
	ConclusionsDeleted int64  `json:"conclusions_deleted"`
	SummariesDeleted   int64  `json:"summaries_deleted"`
}

type SessionDirectory

type SessionDirectory interface {
	ListMetadataByUserID(ctx context.Context, userID string) ([]SessionMetadata, error)
}

SessionDirectory exposes the canonical user->session metadata seam needed for user-scoped cross-chat search.

type SessionMemoryDeletionPlan

type SessionMemoryDeletionPlan struct {
	SessionID     string
	Preserve      bool
	Preserved     []MemoryToolEntry
	CascadeForget []MemoryToolEntry
	Unrelated     []MemoryToolEntry
}

func PlanSessionMemoryDeletion

func PlanSessionMemoryDeletion(entries []MemoryToolEntry, sessionID string, cascade bool) SessionMemoryDeletionPlan

type SessionMetadata

type SessionMetadata struct {
	SessionID       string `json:"session_id"`
	Source          string `json:"source,omitempty"`
	ChatID          string `json:"chat_id,omitempty"`
	UserID          string `json:"user_id,omitempty"`
	Title           string `json:"title,omitempty"`
	ParentSessionID string `json:"parent_session_id,omitempty"`
	LineageKind     string `json:"lineage_kind"`
	CreatedAt       int64  `json:"created_at,omitempty"`
	UpdatedAt       int64  `json:"updated_at"`
}

SessionMetadata is the goncho-owned subset of session directory metadata needed for user-scoped cross-chat search. This type exists so goncho can be extracted as a standalone repository without importing internal/session.

type SessionNameInput

type SessionNameInput struct {
	CWD               string
	Title             string
	SessionID         string
	GatewaySessionKey string
}

type SessionSummary

type SessionSummary struct {
	Content     string `json:"content"`
	MessageID   int64  `json:"message_id"`
	SummaryType string `json:"summary_type"`
	CreatedAt   int64  `json:"created_at"`
	TokenCount  int    `json:"token_count"`
}

SessionSummary is the summary component returned by session context when a short or long summary slot fits inside the requested summary budget.

type SillyTavernIntegrationInput

type SillyTavernIntegrationInput struct {
	Workspace                string
	PeerMode                 string
	PeerName                 string
	PersonaName              string
	SessionNaming            string
	ChatInstanceID           string
	CharacterName            string
	CustomSessionName        string
	ExistingSessionKey       string
	ResetActiveSession       bool
	GroupCharacterNames      []string
	ExistingCharacterPeerIDs []string
	MessageCharacterName     string
	EnrichmentMode           string
	UnsupportedPanelKnobs    []string
}

SillyTavernIntegrationInput models the Honcho SillyTavern panel decisions Goncho needs to preserve without importing the browser extension or Node plugin.

type SillyTavernIntegrationMapping

type SillyTavernIntegrationMapping struct {
	WorkspaceID               string
	UserPeerID                string
	SessionKey                string
	OrphanedSessionKey        string
	CharacterPeerIDs          []string
	LazyAddedCharacterPeerIDs []string
	InjectContext             bool
	UseReasoning              bool
	ReasoningToolName         string
	ExposeTools               bool
	ExternalToolNames         []string
	Unsupported               []UnsupportedHostMapping
}

SillyTavernIntegrationMapping is Goncho's fixture-level interpretation of the SillyTavern host contract.

func MapSillyTavernIntegration

func MapSillyTavernIntegration(input SillyTavernIntegrationInput) SillyTavernIntegrationMapping

MapSillyTavernIntegration maps the SillyTavern-specific Honcho integration controls into Goncho's host compatibility fixture surface.

type SkillLearningProposal added in v0.1.1

type SkillLearningProposal struct {
	ID           int64                       `json:"id"`
	ProposalID   string                      `json:"proposal_id"`
	WorkspaceID  string                      `json:"workspace_id"`
	SkillName    string                      `json:"skill_name"`
	SourceTask   string                      `json:"source_task"`
	DraftBody    string                      `json:"draft_body"`
	EvidenceJSON json.RawMessage             `json:"evidence_json"`
	Status       SkillLearningProposalStatus `json:"status"`
	CreatedBy    string                      `json:"created_by"`
	ReviewedBy   string                      `json:"reviewed_by,omitempty"`
	ReviewedAt   *time.Time                  `json:"reviewed_at,omitempty"`
	ReviewReason string                      `json:"review_reason,omitempty"`
	CreatedAt    time.Time                   `json:"created_at"`
}

func GetSkillLearningProposal added in v0.1.1

func GetSkillLearningProposal(ctx context.Context, db *sql.DB, proposalID string) (SkillLearningProposal, error)

type SkillLearningProposalCreateParams added in v0.1.1

type SkillLearningProposalCreateParams struct {
	WorkspaceID string    `json:"workspace_id,omitempty"`
	SkillName   string    `json:"skill_name"`
	SourceTask  string    `json:"source_task"`
	DraftBody   string    `json:"draft_body"`
	CreatedBy   string    `json:"created_by"`
	Evidence    any       `json:"evidence,omitempty"`
	CreatedAt   time.Time `json:"created_at,omitempty"`
}

type SkillLearningProposalList added in v0.1.1

type SkillLearningProposalList struct {
	Items []SkillLearningProposal `json:"items"`
	Count int                     `json:"count"`
}

func ListSkillLearningProposals added in v0.1.1

func ListSkillLearningProposals(ctx context.Context, db *sql.DB, q SkillLearningProposalQuery) (SkillLearningProposalList, error)

type SkillLearningProposalQuery added in v0.1.1

type SkillLearningProposalQuery struct {
	WorkspaceID string                      `json:"workspace_id,omitempty"`
	Status      SkillLearningProposalStatus `json:"status,omitempty"`
	Limit       int                         `json:"limit,omitempty"`
}

type SkillLearningProposalRef added in v0.1.1

type SkillLearningProposalRef struct {
	ProposalID  string                      `json:"proposal_id"`
	WorkspaceID string                      `json:"workspace_id"`
	SkillName   string                      `json:"skill_name"`
	Status      SkillLearningProposalStatus `json:"status"`
}

func SubmitSkillLearningProposal added in v0.1.1

func SubmitSkillLearningProposal(ctx context.Context, db *sql.DB, p SkillLearningProposalCreateParams) (SkillLearningProposalRef, error)

type SkillLearningProposalReviewParams added in v0.1.1

type SkillLearningProposalReviewParams struct {
	ProposalID   string    `json:"proposal_id"`
	ReviewedBy   string    `json:"reviewed_by"`
	ReviewReason string    `json:"review_reason"`
	ReviewedAt   time.Time `json:"reviewed_at,omitempty"`
}

type SkillLearningProposalStatus added in v0.1.1

type SkillLearningProposalStatus string
const (
	SkillLearningProposalPending  SkillLearningProposalStatus = "pending"
	SkillLearningProposalApproved SkillLearningProposalStatus = "approved"
	SkillLearningProposalRejected SkillLearningProposalStatus = "rejected"
)

type SkillOutcome

type SkillOutcome struct {
	SkillName string
	Success   bool
	Lesson    string
}

SkillOutcome records the result of a skill execution.

type StoreMemoryTool

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

func NewStoreMemoryTool

func NewStoreMemoryTool(store MemoryToolStore) *StoreMemoryTool

func (*StoreMemoryTool) Description

func (t *StoreMemoryTool) Description() string

func (*StoreMemoryTool) Execute

func (t *StoreMemoryTool) Execute(ctx context.Context, args json.RawMessage) (json.RawMessage, error)

func (*StoreMemoryTool) Name

func (t *StoreMemoryTool) Name() string

func (*StoreMemoryTool) Schema

func (t *StoreMemoryTool) Schema() json.RawMessage

func (StoreMemoryTool) Spec

func (t StoreMemoryTool) Spec() toolmeta.OperationSpec

func (*StoreMemoryTool) Timeout

func (t *StoreMemoryTool) Timeout() time.Duration

type StreamingChatPersistence

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

StreamingChatPersistence buffers stream chunks until a terminal event decides whether the assistant response is complete enough to become durable memory.

func (*StreamingChatPersistence) AppendChunk

func (p *StreamingChatPersistence) AppendChunk(chunk string)

func (*StreamingChatPersistence) Complete

func (*StreamingChatPersistence) Interrupt

func (p *StreamingChatPersistence) Interrupt(reason string) ChatResult

type StructuredSummary

type StructuredSummary struct {
	FilesModified []string `json:"files_modified,omitempty"`
	DecisionsMade []string `json:"decisions_made,omitempty"`
	OpenQuestions []string `json:"open_questions,omitempty"`
	SkillOutcomes []string `json:"skill_outcomes,omitempty"`
	NextSteps     []string `json:"next_steps,omitempty"`
}

StructuredSummary captures session-end facts for cross-session continuity.

type SummarizeMemoryTool

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

func NewSummarizeMemoryTool

func NewSummarizeMemoryTool(store MemoryToolStore) *SummarizeMemoryTool

func (*SummarizeMemoryTool) Description

func (t *SummarizeMemoryTool) Description() string

func (*SummarizeMemoryTool) Execute

func (t *SummarizeMemoryTool) Execute(ctx context.Context, args json.RawMessage) (json.RawMessage, error)

func (*SummarizeMemoryTool) Name

func (t *SummarizeMemoryTool) Name() string

func (*SummarizeMemoryTool) Schema

func (t *SummarizeMemoryTool) Schema() json.RawMessage

func (SummarizeMemoryTool) Spec

func (t SummarizeMemoryTool) Spec() toolmeta.OperationSpec

func (*SummarizeMemoryTool) Timeout

func (t *SummarizeMemoryTool) Timeout() time.Duration

type TelemetryEventInput

type TelemetryEventInput struct {
	Type       string
	Workspace  string
	SessionKey string
	Peer       string
	RunID      string
	AgentID    string
	ResourceID string
	Iteration  int
	Timestamp  time.Time
	Metrics    TelemetryMetrics
	Payload    map[string]any
}

type TelemetryMetrics

type TelemetryMetrics struct {
	InputTokens         int
	OutputTokens        int
	CacheReadTokens     int
	CacheWriteTokens    int
	ReasoningTokens     int
	QueueItemsProcessed int
	ToolCallsCount      int
	ToolErrors          int
	DurationMs          int64
}

type TypedMemoryStore

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

func NewTypedMemoryStore

func NewTypedMemoryStore() *TypedMemoryStore

func (*TypedMemoryStore) Create

func (s *TypedMemoryStore) Create(entry *MemoryEntry) error

func (*TypedMemoryStore) Delete

func (s *TypedMemoryStore) Delete(id string) bool

func (*TypedMemoryStore) GetAverageConfidence

func (s *TypedMemoryStore) GetAverageConfidence(memType MemoryType) float64

func (*TypedMemoryStore) GetPruningCandidates

func (s *TypedMemoryStore) GetPruningCandidates(now time.Time) []*MemoryEntry

func (*TypedMemoryStore) GetStats

func (s *TypedMemoryStore) GetStats() map[MemoryType]int

func (*TypedMemoryStore) ListAll

func (s *TypedMemoryStore) ListAll() []*MemoryEntry

func (*TypedMemoryStore) ListByType

func (s *TypedMemoryStore) ListByType(memType MemoryType) []*MemoryEntry

func (*TypedMemoryStore) Prune

func (s *TypedMemoryStore) Prune(now time.Time) int

func (*TypedMemoryStore) Read

func (s *TypedMemoryStore) Read(id string) (*MemoryEntry, bool)

func (*TypedMemoryStore) Update

func (s *TypedMemoryStore) Update(id string, updateFn func(*MemoryEntry)) bool

func (*TypedMemoryStore) UpsertWithConflictResolution

func (s *TypedMemoryStore) UpsertWithConflictResolution(entry *MemoryEntry) ConflictResolution

type UnsupportedFilterError

type UnsupportedFilterError struct {
	Code     string `json:"code"`
	Field    string `json:"field,omitempty"`
	Operator string `json:"operator,omitempty"`
	Reason   string `json:"reason"`
}

UnsupportedFilterError is returned before search when a Honcho-shaped filter cannot be enforced by the current Goncho storage model.

func (*UnsupportedFilterError) Error

func (e *UnsupportedFilterError) Error() string

type UnsupportedHostMapping

type UnsupportedHostMapping struct {
	Field  string
	Value  string
	Reason string
}

UnsupportedHostMapping explains a host compatibility input that Goncho cannot safely accept yet.

type UpdateMemoryTool

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

func NewUpdateMemoryTool

func NewUpdateMemoryTool(store MemoryToolStore) *UpdateMemoryTool

func (*UpdateMemoryTool) Description

func (t *UpdateMemoryTool) Description() string

func (*UpdateMemoryTool) Execute

func (t *UpdateMemoryTool) Execute(ctx context.Context, args json.RawMessage) (json.RawMessage, error)

func (*UpdateMemoryTool) Name

func (t *UpdateMemoryTool) Name() string

func (*UpdateMemoryTool) Schema

func (t *UpdateMemoryTool) Schema() json.RawMessage

func (UpdateMemoryTool) Spec

func (t UpdateMemoryTool) Spec() toolmeta.OperationSpec

func (*UpdateMemoryTool) Timeout

func (t *UpdateMemoryTool) Timeout() time.Duration

type VerifiedCodeClaim

type VerifiedCodeClaim struct {
	Path    string `json:"path"`
	Content string `json:"content"`
	Status  string `json:"status"`
}

type VerifiedCodeContextParams

type VerifiedCodeContextParams struct {
	Peer       string `json:"peer"`
	SessionKey string `json:"session_key,omitempty"`
	Query      string `json:"query,omitempty"`
	RepoRoot   string `json:"repo_root"`
	MaxTokens  int    `json:"max_tokens,omitempty"`
}

type VerifiedCodeContextResult

type VerifiedCodeContextResult struct {
	WorkspaceID    string                       `json:"workspace_id"`
	Peer           string                       `json:"peer"`
	SessionKey     string                       `json:"session_key,omitempty"`
	Representation string                       `json:"representation"`
	VerifiedClaims []VerifiedCodeClaim          `json:"verified_claims"`
	StaleClaims    []VerifiedCodeClaim          `json:"stale_claims"`
	Unavailable    []ContextUnavailableEvidence `json:"unavailable,omitempty"`
}

type WebhookClock

type WebhookClock interface {
	Now() time.Time
}

type WebhookDeliveryAttempt

type WebhookDeliveryAttempt struct {
	EndpointID  string
	WorkspaceID string
	EventType   WebhookEventType
	Attempt     int
	Status      WebhookDeliveryStatus
	StatusCode  int
	ErrorClass  WebhookDeliveryErrorClass
	Error       string
	Retry       bool
	NextRetryAt *time.Time
	Evidence    WebhookDeliveryEvidence
	RecordedAt  time.Time
}

type WebhookDeliveryEndpoint

type WebhookDeliveryEndpoint struct {
	ID             string
	WorkspaceID    string
	URL            string
	Disabled       bool
	DisabledReason string
}

type WebhookDeliveryErrorClass

type WebhookDeliveryErrorClass string
const (
	WebhookDeliveryErrorNone       WebhookDeliveryErrorClass = ""
	WebhookDeliveryErrorHTTPStatus WebhookDeliveryErrorClass = "http_status"
	WebhookDeliveryErrorNetwork    WebhookDeliveryErrorClass = "network"
	WebhookDeliveryErrorSigning    WebhookDeliveryErrorClass = "signing"
	WebhookDeliveryErrorStore      WebhookDeliveryErrorClass = "store"
	WebhookDeliveryErrorDisabled   WebhookDeliveryErrorClass = "endpoint_disabled"
)

type WebhookDeliveryEvidence

type WebhookDeliveryEvidence struct {
	EndpointID  string
	EndpointURL string
	WorkspaceID string
	EventType   WebhookEventType
	Status      WebhookDeliveryStatus
	StatusCode  int
	ErrorClass  WebhookDeliveryErrorClass
	Attempt     int
	NextRetryAt *time.Time
}

type WebhookDeliveryRequest

type WebhookDeliveryRequest struct {
	WorkspaceID string
	Event       WebhookEvent
	Attempt     int
}

type WebhookDeliveryResult

type WebhookDeliveryResult struct {
	EndpointID  string
	WorkspaceID string
	EventType   WebhookEventType
	Attempt     int
	Status      WebhookDeliveryStatus
	StatusCode  int
	ErrorClass  WebhookDeliveryErrorClass
	Error       string
	Retry       bool
	NextRetryAt *time.Time
	Evidence    WebhookDeliveryEvidence
}

type WebhookDeliveryStatus

type WebhookDeliveryStatus string
const (
	WebhookDeliveryDelivered        WebhookDeliveryStatus = "delivered"
	WebhookDeliveryRetryable        WebhookDeliveryStatus = "retryable"
	WebhookDeliveryFailed           WebhookDeliveryStatus = "failed"
	WebhookDeliveryEndpointDisabled WebhookDeliveryStatus = "endpoint_disabled"
	WebhookDeliverySkipped          WebhookDeliveryStatus = "skipped"
)

type WebhookDeliveryStore

type WebhookDeliveryStore interface {
	ListWebhookDeliveryEndpoints(ctx context.Context, workspaceID string) ([]WebhookDeliveryEndpoint, error)
	RecordWebhookDelivery(ctx context.Context, attempt WebhookDeliveryAttempt) error
	DisableWebhookDeliveryEndpoint(ctx context.Context, endpoint WebhookDeliveryEndpoint, reason string, now time.Time) error
}

type WebhookDeliveryWorker

type WebhookDeliveryWorker struct {
	Store       WebhookDeliveryStore
	Client      WebhookHTTPClient
	Clock       WebhookClock
	Secret      string
	MaxAttempts int
	Backoff     func(attempt int) time.Duration
}

func (WebhookDeliveryWorker) Deliver

type WebhookEndpoint

type WebhookEndpoint struct {
	ID          string    `json:"id"`
	WorkspaceID string    `json:"workspace_id"`
	URL         string    `json:"url"`
	CreatedAt   time.Time `json:"created_at"`
}

type WebhookEndpointCreateParams

type WebhookEndpointCreateParams struct {
	WorkspaceID string
	URL         string
	Limit       int
	Now         time.Time
}

type WebhookEndpointCreateResult

type WebhookEndpointCreateResult struct {
	Endpoint WebhookEndpoint `json:"endpoint"`
	Created  bool            `json:"created"`
}

type WebhookEvent

type WebhookEvent struct {
	Type        WebhookEventType `json:"type"`
	WorkspaceID string           `json:"workspace_id"`
	Data        map[string]any   `json:"data,omitempty"`
}

func NewQueueEmptyWebhookEvent

func NewQueueEmptyWebhookEvent(params QueueEmptyWebhookEventParams) (WebhookEvent, error)

func NewTestWebhookEvent

func NewTestWebhookEvent(workspaceID string) (WebhookEvent, error)

type WebhookEventType

type WebhookEventType string
const (
	WebhookEventQueueEmpty WebhookEventType = "queue.empty"
	WebhookEventTest       WebhookEventType = "test.event"
)

type WebhookHTTPClient

type WebhookHTTPClient interface {
	PostWebhook(ctx context.Context, req WebhookHTTPRequest) (WebhookHTTPResponse, error)
}

type WebhookHTTPRequest

type WebhookHTTPRequest struct {
	URL     string
	Body    string
	Headers map[string]string
}

type WebhookHTTPResponse

type WebhookHTTPResponse struct {
	StatusCode int
}

type WorkspaceDecision

type WorkspaceDecision struct {
	WorkspaceID   string
	HardIsolation bool
	Evidence      []string
}

func ResolveWorkspace

func ResolveWorkspace(req WorkspaceRequest) (WorkspaceDecision, error)

type WorkspaceDeletionResult

type WorkspaceDeletionResult struct {
	WorkspaceID        string `json:"workspace_id"`
	MessagesDeleted    int64  `json:"messages_deleted"`
	PeerCardsDeleted   int64  `json:"peer_cards_deleted"`
	ConclusionsDeleted int64  `json:"conclusions_deleted"`
	SummariesDeleted   int64  `json:"summaries_deleted"`
	DreamsDeleted      int64  `json:"dreams_deleted"`
}

type WorkspaceRequest

type WorkspaceRequest struct {
	Strategy    WorkspaceStrategy
	WorkspaceID string
	UserID      string
}

type WorkspaceStrategy

type WorkspaceStrategy string
const (
	WorkspaceStrategyDefault       WorkspaceStrategy = "default"
	WorkspaceStrategyHardIsolation WorkspaceStrategy = "hard_isolation"
	WorkspaceStrategyPerUser       WorkspaceStrategy = "per_user"
)

type WriteEvidence

type WriteEvidence struct {
	Code       string
	WriteOK    bool
	Candidates []RelationCandidate
	Err        error
}

WriteEvidence is the Goncho-native operator evidence for one Submit call. It is the only return shape from the queue; callers MUST inspect Code and WriteOK before treating Candidates as authoritative.

type WriteFrequencyMode

type WriteFrequencyMode string
const (
	WriteFrequencyInvalid WriteFrequencyMode = "invalid"
	WriteFrequencyAsync   WriteFrequencyMode = "async"
	WriteFrequencyTurn    WriteFrequencyMode = "turn"
	WriteFrequencySession WriteFrequencyMode = "session"
	WriteFrequencyEvery   WriteFrequencyMode = "every"
)

type WriteQueue

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

WriteQueue serializes memory writes and records pending relation candidates without blocking the originating write. The queue uses a single mutex to guarantee mutex-serialized order; concurrent submitters are safe but the deterministic acceptance test exercises sequential submission so the recorded order is reproducible.

func NewWriteQueue

func NewWriteQueue(store MemoryStore, detector CandidateDetector, relations RelationStore) *WriteQueue

NewWriteQueue constructs a queue from the three required seams. Pass nil for relations if relation candidate storage is intentionally disabled; in that case detected candidates are still attached to the returned evidence for the caller to inspect.

func (*WriteQueue) Cancel

func (q *WriteQueue) Cancel(id string) bool

Cancel marks the given write ID as cancelled. Returns true if the cancellation was registered before the write started, false if the write has already begun, completed, or the ID was already consumed.

func (*WriteQueue) Submit

Submit serializes the write through the queue. The originating memory write is authoritative: relation detection runs after a successful write and its failure is recorded as evidence without rolling the write back.

Directories

Path Synopsis
cmd
goncho-bench command
integration

Jump to

Keyboard shortcuts

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