Documentation
¶
Overview ¶
Package knowledge provides a knowledge capture toolkit for the MCP data platform.
Index ¶
- Constants
- Variables
- func AgeDays(t, now time.Time) int
- func InstructionsTargetURN(section string) string
- func NormalizeConfidence(c string) string
- func NormalizeSource(s string) string
- func PageTargetURN(slug string) string
- func RollbackReviewNote(changesetID string) string
- func ValidateAction(action string) error
- func ValidateApplyChanges(changes []ApplyChange) error
- func ValidateCategory(c string) error
- func ValidateConfidence(c string) error
- func ValidateEntityURNs(urns []string) error
- func ValidateInsightText(text string) error
- func ValidateRelatedColumns(cols []RelatedColumn) error
- func ValidateSource(s string) error
- func ValidateStatusTransition(from, to string) error
- func ValidateSuggestedActions(actions []SuggestedAction) error
- type ApplyChange
- type ApplyConfig
- type BackfillStats
- type CatalogQueryWriter
- type CatalogReach
- type Changeset
- type ChangesetFilter
- type ChangesetStore
- type EntityInsightSummary
- type EntityMetadata
- type Insight
- type InsightFilter
- type InsightSearchQuery
- type InsightSearcher
- type InsightStats
- type InsightStore
- type InsightUpdate
- type InstructionsEditedError
- type InstructionsStore
- type PageEditedError
- type PageReverter
- type PendingReview
- type PromptCreator
- type ProposedChange
- type RelatedColumn
- type RequiredFieldError
- type RollbackConflictError
- type RollbackDeps
- type RollbackResult
- type ScoredInsight
- type SearchableInsightStore
- type SuggestedAction
- type ToolInventory
- type Toolkit
- func (t *Toolkit) BackfillPageRefs(ctx context.Context, pages knowledgepage.Store) (BackfillStats, error)
- func (*Toolkit) Close() error
- func (*Toolkit) Connection() string
- func (*Toolkit) Kind() string
- func (t *Toolkit) Name() string
- func (*Toolkit) PromptInfos() []registry.PromptInfo
- func (t *Toolkit) RegisterTools(s *mcp.Server)
- func (t *Toolkit) RunGuardedBackfill(ctx context.Context, db *sql.DB, pages knowledgepage.Store)
- func (t *Toolkit) SetApplyConfig(cfg ApplyConfig, csStore ChangesetStore, store catalog.Store)
- func (t *Toolkit) SetCatalogReach(reach CatalogReach)
- func (t *Toolkit) SetInstructionsSink(store InstructionsStore, tools ToolInventory)
- func (t *Toolkit) SetPageGuards(guards knowledgepage.PageGuards, emb embedding.Provider)
- func (t *Toolkit) SetPageWriter(pw pageWriter)
- func (t *Toolkit) SetPortalBaseURL(base string)
- func (t *Toolkit) SetPromptCreator(pc PromptCreator)
- func (t *Toolkit) SetQueryProvider(provider query.Provider)
- func (t *Toolkit) SetSemanticProvider(provider semantic.Provider)
- func (t *Toolkit) Tools() []string
- type UnrevertibleError
Constants ¶
const ( MinInsightTextLen = 10 MaxInsightTextLen = 4000 MaxEntityURNs = 10 MaxRelatedColumns = 20 MaxSuggestedActions = 5 MaxApplyChanges = 20 MaxInsightIDs = 50 )
Insight validation constraints.
const ( StatusPending = "pending" StatusApproved = "approved" StatusRejected = "rejected" StatusApplied = "applied" StatusSuperseded = "superseded" )
Insight status constants.
const DefaultLimit = 20
DefaultLimit is the default page size for list queries.
const MaxLimit = 100
MaxLimit is the maximum page size for list queries.
const PendingStalenessThresholdDays = 30
PendingStalenessThresholdDays is the age, in days, at or past which a pending insight is counted as stale review debt (reported as pending_over_30d). An unreviewed queue erodes the knowledge flywheel, so this threshold makes the aging visible to reviewers and to agents nudging them (#764). "At or past" (age >= threshold) matches the portal's age badge, which flags a row stale at the same 30-day mark, so the count and the badge never disagree.
Variables ¶
var ErrChangesetAlreadyRolledBack = errors.New("changeset already rolled back")
ErrChangesetAlreadyRolledBack is returned when a rollback targets a changeset that has already been rolled back.
var ErrDataHubChangeset = errors.New("this changeset was applied to DataHub before the platform catalog replaced it, " +
"so it has no catalog history to roll back; restore the desired state with a new apply")
ErrDataHubChangeset refuses the rollback of a changeset written to DataHub before the platform catalog replaced it: its writes are not in the catalog's history.
var ErrNoQueryTarget = errors.New("the platform catalog holds none of the datasets the statement reads")
ErrNoQueryTarget refuses a promoted query none of whose datasets the catalog holds: there is no dataset to keep it on.
var ErrTargetNotCataloged = errors.New("the platform catalog holds no entity with this reference")
ErrTargetNotCataloged is returned for an apply target the platform catalog does not hold.
Functions ¶
func AgeDays ¶ added in v1.100.0
AgeDays returns the whole-day age of t relative to now, floored at 0 so a clock skew that puts t slightly in the future never reports negative. It is the single definition of whole-day insight age shared by bulk_review and platform_info so the two never drift (#764); the portal mirrors it in TS.
func InstructionsTargetURN ¶ added in v1.130.0
InstructionsTargetURN is the changeset target_urn for a promoted instruction section. Exported so a caller listing a target's changesets names the same form the sink wrote rather than duplicating the prefix.
func NormalizeConfidence ¶
NormalizeConfidence returns the confidence value, defaulting to "medium" if empty.
func NormalizeSource ¶ added in v0.21.1
NormalizeSource returns the source value, defaulting to "user" if empty.
func PageTargetURN ¶ added in v1.89.0
Page changeset markers. The changeset target_urn is free-form text (migration 000008), so a page promotion records "kp:<slug>" and shares the same changeset store / list / rollback surface as catalog changesets. PageTargetURN is the changeset target_urn for a knowledge page, keyed by slug. Exported so other packages (the portal lineage endpoint) reference the same format instead of duplicating the "kp:" prefix.
func RollbackReviewNote ¶ added in v1.121.0
RollbackReviewNote is the review note left on an insight a rollback returned to the queue (#1257). It names the changeset whose revert sent it back, so the reviewer reading the queue entry knows why an insight carrying applied_by and applied_at is pending again.
func ValidateAction ¶
ValidateAction checks whether an action value is valid.
func ValidateApplyChanges ¶
func ValidateApplyChanges(changes []ApplyChange) error
ValidateApplyChanges validates the changes slice for the apply action.
func ValidateCategory ¶
ValidateCategory checks whether a category value is valid.
func ValidateConfidence ¶
ValidateConfidence checks whether a confidence value is valid. An empty string is valid and defaults to "medium".
func ValidateEntityURNs ¶
ValidateEntityURNs validates the entity URN slice.
func ValidateInsightText ¶
ValidateInsightText checks whether the insight text meets length requirements.
func ValidateRelatedColumns ¶
func ValidateRelatedColumns(cols []RelatedColumn) error
ValidateRelatedColumns validates the related columns slice.
func ValidateSource ¶ added in v0.21.1
ValidateSource checks whether a source value is valid. An empty string is valid and defaults to "user".
func ValidateStatusTransition ¶
ValidateStatusTransition checks whether a status transition is allowed.
func ValidateSuggestedActions ¶
func ValidateSuggestedActions(actions []SuggestedAction) error
ValidateSuggestedActions validates a slice of suggested actions.
Types ¶
type ApplyChange ¶
type ApplyChange struct {
ChangeType string `json:"change_type"`
Target string `json:"target"`
Detail string `json:"detail"`
QuerySQL string `json:"query_sql,omitempty"`
QueryDescription string `json:"query_description,omitempty"`
}
ApplyChange is a single change an apply writes to the catalog.
type ApplyConfig ¶
type ApplyConfig struct {
Enabled bool `yaml:"enabled"`
RequireConfirmation bool `yaml:"require_confirmation"`
}
ApplyConfig configures the apply_knowledge tool.
type BackfillStats ¶ added in v1.88.0
type BackfillStats struct {
PagesScanned int `json:"pages_scanned"`
InlineRefs int `json:"inline_refs"`
PromotedRefs int `json:"promoted_refs"`
}
BackfillStats reports what a reference backfill touched.
type CatalogQueryWriter ¶ added in v1.146.0
type CatalogQueryWriter struct {
// contains filtered or unexported fields
}
CatalogQueryWriter keeps a promoted statement as a curated query on every dataset it reads (#1321, #1920).
func NewCatalogQueryWriter ¶ added in v1.146.0
func NewCatalogQueryWriter(store catalog.Store) *CatalogQueryWriter
NewCatalogQueryWriter returns the curated-query writer over store, or nil when there is no catalog to write to.
func (*CatalogQueryWriter) CreateCuratedQuery ¶ added in v1.146.0
func (w *CatalogQueryWriter) CreateCuratedQuery(ctx context.Context, targets []string, name, sql, description string) (string, error)
CreateCuratedQuery adds the query to each dataset the targets name, in one transaction, and returns the reference of the first. A target the catalog does not hold is left out; none held is ErrNoQueryTarget.
type CatalogReach ¶ added in v1.146.0
CatalogReach reports whether the caller of ctx may curate the entity a catalog reference names: a reference naming a connection when the caller's persona reaches it, and one naming none always. The portal's catalog routes ask the same of their caller.
type Changeset ¶
type Changeset struct {
ID string `json:"id" example:"cs_x1y2z3a4b5c6d7e8"`
CreatedAt time.Time `json:"created_at" example:"2026-01-15T16:00:00Z"`
TargetURN string `json:"target_urn" example:"mcp:dataset:(trino,warehouse,hive.sales.orders)"`
ChangeType string `json:"change_type" example:"update_description"`
PreviousValue map[string]any `json:"previous_value"`
NewValue map[string]any `json:"new_value"`
SourceInsightIDs []string `json:"source_insight_ids"`
ApprovedBy string `json:"approved_by" example:"admin@example.com"`
AppliedBy string `json:"applied_by" example:"admin@example.com"`
RolledBack bool `json:"rolled_back" example:"false"`
RolledBackBy string `json:"rolled_back_by,omitempty"`
RolledBackAt *time.Time `json:"rolled_back_at,omitempty"`
}
Changeset records one apply: its changes, the catalog changes it wrote, and the insights it promoted.
type ChangesetFilter ¶
type ChangesetFilter struct {
EntityURN string
AppliedBy string
// SourceInsightID filters to changesets whose source_insight_ids array
// contains this insight id (the thread -> insight -> changeset bridge).
SourceInsightID string
Since *time.Time
Until *time.Time
RolledBack *bool
Limit int
Offset int
}
ChangesetFilter defines filtering criteria for listing changesets.
func (*ChangesetFilter) EffectiveLimit ¶
func (f *ChangesetFilter) EffectiveLimit() int
EffectiveLimit returns the limit to use, applying defaults and caps.
type ChangesetStore ¶
type ChangesetStore interface {
InsertChangeset(ctx context.Context, cs Changeset) error
GetChangeset(ctx context.Context, id string) (*Changeset, error)
ListChangesets(ctx context.Context, filter ChangesetFilter) ([]Changeset, int, error)
RollbackChangeset(ctx context.Context, id, rolledBackBy string) error
}
ChangesetStore persists and queries knowledge changesets.
func NewNoopChangesetStore ¶
func NewNoopChangesetStore() ChangesetStore
NewNoopChangesetStore creates a no-op ChangesetStore.
func NewPostgresChangesetStore ¶
func NewPostgresChangesetStore(db *sql.DB) ChangesetStore
NewPostgresChangesetStore creates a new PostgreSQL changeset store.
type EntityInsightSummary ¶
type EntityInsightSummary struct {
EntityURN string `json:"entity_urn"`
Count int `json:"count"`
Categories []string `json:"categories"`
LatestAt string `json:"latest_at"`
}
EntityInsightSummary summarizes insights for a single entity.
type EntityMetadata ¶
type EntityMetadata struct {
Description string `json:"description"`
Tags []string `json:"tags"`
GlossaryTerms []string `json:"glossary_terms"`
Owners []string `json:"owners"`
}
EntityMetadata is the summary of an entity's curation that review, synthesize and a changeset's before-image carry.
type Insight ¶
type Insight struct {
ID string `json:"id" example:"a1b2c3d4e5f67890a1b2c3d4e5f67890"`
CreatedAt time.Time `json:"created_at" example:"2026-01-15T14:30:00Z"`
SessionID string `json:"session_id" example:"sess_abc123"`
CapturedBy string `json:"captured_by" example:"analyst@example.com"`
Persona string `json:"persona" example:"analyst"`
Source string `json:"source" example:"user"`
Category string `json:"category" example:"correction"`
InsightText string `json:"insight_text" example:"The amount column represents gross margin before returns, not revenue."`
Confidence string `json:"confidence" example:"high"`
EntityURNs []string `json:"entity_urns"`
RelatedColumns []RelatedColumn `json:"related_columns"`
SuggestedActions []SuggestedAction `json:"suggested_actions"`
Status string `json:"status" example:"pending"`
// SinkClass is the #633 organizing axis carried onto the backing memory
// record so the unified write path and apply_knowledge sink router can
// route by it. Empty for insights captured before #633.
SinkClass string `json:"sink_class,omitempty" example:"schema_entity"`
// Lifecycle fields (populated by migrations 000007 and 000008)
ReviewedBy string `json:"reviewed_by,omitempty" example:"admin@example.com"`
ReviewedAt *time.Time `json:"reviewed_at,omitempty"`
ReviewNotes string `json:"review_notes,omitempty" example:"Verified with data engineering team"`
// AppliedBy, AppliedAt and ChangesetRef record the last application. They are
// retained when a rollback returns the insight to the review queue (#1257), so
// the next reviewer sees the destination and changeset that were already tried
// rather than deciding blind; a pending insight carrying them is one whose
// application was reverted.
AppliedBy string `json:"applied_by,omitempty"`
AppliedAt *time.Time `json:"applied_at,omitempty"`
ChangesetRef string `json:"changeset_ref,omitempty"`
}
Insight represents a captured domain knowledge insight.
type InsightFilter ¶
type InsightFilter struct {
Status string
Category string
EntityURN string
CapturedBy string
Confidence string
Source string
Since *time.Time
Until *time.Time
Limit int
Offset int
// OrderCreatedAsc lists insights oldest-first (created_at ASC) instead of the
// default newest-first (created_at DESC). The review queue uses it to work the
// oldest, stalest review debt first (#764).
OrderCreatedAsc bool
// owner's. Like InsightSearchQuery.Shared it overrides CapturedBy and Status
// together, so listing across owners cannot be reached without pinning the
// applied status (#980 B2).
Shared bool
}
InsightFilter defines filtering criteria for listing insights.
func (*InsightFilter) EffectiveLimit ¶
func (f *InsightFilter) EffectiveLimit() int
EffectiveLimit returns the limit to use, applying defaults and caps.
type InsightSearchQuery ¶ added in v1.80.0
type InsightSearchQuery struct {
QueryText string
Embedding []float32
CapturedBy string
Status string
Limit int
// applied insights of every capturer, not the caller's own. It is a single
// flag rather than "leave CapturedBy empty" so that reaching across owners
// is impossible without also pinning the status — the adapter overrides
// both CapturedBy and Status together (see sharedInsightScope), so a caller
// that forgets to set an owner gets applied insights, never everyone's
// private pending captures (#980 B2).
Shared bool
}
InsightSearchQuery parameterizes a relevance-ranked insight search. It is owner-scoped (CapturedBy) and, like List, restricted to the knowledge dimension by the adapter. Embedding drives semantic (hybrid) ranking when non-empty; a nil/empty Embedding selects the lexical-only path used when no embedding provider is configured. The caller (the portal search handler) owns the embedder and precomputes Embedding so the adapter does not depend on an embedding provider.
type InsightSearcher ¶ added in v1.81.0
type InsightSearcher interface {
Search(ctx context.Context, q InsightSearchQuery) ([]ScoredInsight, error)
}
InsightSearcher is the optional relevance-search capability of an InsightStore. Only the memory-backed adapter implements it; the legacy SQL store and the noop store do not. Both the recall_insight tool and the portal insight-search route type-assert the wired store against this to gate registration, so the capability is declared once here next to the query and result types it uses.
type InsightStats ¶
type InsightStats struct {
TotalPending int `json:"total_pending"`
ByEntity []EntityInsightSummary `json:"by_entity"`
ByCategory map[string]int `json:"by_category"`
ByConfidence map[string]int `json:"by_confidence"`
ByStatus map[string]int `json:"by_status"`
// OldestPendingAt is the created_at of the oldest pending insight, or nil
// when the pending queue is empty. It surfaces review-queue staleness so
// pending insights do not silently age (#764).
OldestPendingAt *time.Time `json:"oldest_pending_at,omitempty"`
// PendingOver30d counts pending insights older than
// PendingStalenessThresholdDays, the accumulating review debt (#764).
PendingOver30d int `json:"pending_over_30d"`
}
InsightStats holds aggregated insight statistics.
type InsightStore ¶
type InsightStore interface {
Insert(ctx context.Context, insight Insight) error
Get(ctx context.Context, id string) (*Insight, error)
List(ctx context.Context, filter InsightFilter) ([]Insight, int, error)
UpdateStatus(ctx context.Context, id, status, reviewedBy, reviewNotes string) error
Update(ctx context.Context, id string, updates InsightUpdate) error
Stats(ctx context.Context, filter InsightFilter) (*InsightStats, error)
MarkApplied(ctx context.Context, id, appliedBy, changesetRef string) error
// ReturnToReview sends an applied insight back to pending after its changeset
// was rolled back (#1257), so the review queue surfaces it for a decision
// again. The prior application is retained (applied_by, applied_at,
// changeset_ref) and the rollback is recorded in the review fields, so the
// next reviewer sees what was already tried. It returns whether the insight
// was in the applied state and was transitioned: an insight in any other
// state is left alone (returned == false, no error), so re-running a rollback
// neither errors nor resurrects an insight somebody has since decided.
ReturnToReview(ctx context.Context, id, rolledBackBy, changesetID string) (returned bool, err error)
Supersede(ctx context.Context, entityURN string, excludeID string) (int, error)
}
InsightStore persists and queries captured insights.
func NewMemoryInsightAdapter ¶ added in v1.52.0
func NewMemoryInsightAdapter(store memory.Store) InsightStore
NewMemoryInsightAdapter creates an InsightStore backed by a memory.Store.
func NewNoopStore ¶
func NewNoopStore() InsightStore
NewNoopStore creates a no-op InsightStore for use when no database is available.
func ParseConfig ¶
func ParseConfig(cfg map[string]any) InsightStore
ParseConfig extracts an InsightStore from a configuration map. The store must be provided programmatically (not from YAML).
type InsightUpdate ¶
type InsightUpdate struct {
InsightText string `json:"insight_text,omitempty"`
Category string `json:"category,omitempty"`
Confidence string `json:"confidence,omitempty"`
}
InsightUpdate holds fields that can be edited on a non-applied insight.
type InstructionsEditedError ¶ added in v1.130.0
type InstructionsEditedError struct {
Section string
}
InstructionsEditedError is returned when an agent-instructions promotion cannot be rolled back because the layer was written again after the promotion, so reverting would clobber the later edit. The instructions sink's counterpart of PageEditedError.
func (*InstructionsEditedError) Error ¶ added in v1.130.0
func (e *InstructionsEditedError) Error() string
Error implements the error interface.
type InstructionsStore ¶ added in v1.130.0
type InstructionsStore interface {
// AgentInstructions returns the deployment's customized instruction text, or
// "" when the deployment has never set one (which the sink writes into: a
// first promotion creates the value, the way a first page promotion creates
// the page).
AgentInstructions(ctx context.Context) (string, error)
// SetAgentInstructions replaces the customized instruction text, recording
// author as the writer.
SetAgentInstructions(ctx context.Context, value, author string) error
}
InstructionsStore is the deployment's customized agent-instruction layer as the sink and its rollback need it: read the current text, write a new one.
It is the capability rather than the config store, so this toolkit carries neither the config-store types nor the config key: the platform owns ConfigKeyServerAgentInstructions and adapts its store onto this interface. A deployment with no database-backed config store wires nothing, and the sink then refuses rather than silently writing to a store that cannot hold the value.
type PageEditedError ¶ added in v1.88.0
PageEditedError is returned when a knowledge-page promotion cannot be rolled back because the page was edited after the promotion (its current version advanced past the version the changeset produced), so reverting would clobber the later edit. The page sink's counterpart of RollbackConflictError.
func (*PageEditedError) Error ¶ added in v1.88.0
func (e *PageEditedError) Error() string
Error implements the error interface.
type PageReverter ¶ added in v1.88.0
type PageReverter interface {
GetBySlug(ctx context.Context, slug string) (*knowledgepage.Page, error)
Update(ctx context.Context, id string, updates knowledgepage.Update) error
SoftDelete(ctx context.Context, id string) error
// Entity references (#664): restore the page's promoted references on rollback,
// scoped to source=promoted so manual and inline references are not clobbered.
ReplaceEntityRefsBySource(ctx context.Context, pageID, source string, refs []knowledgepage.EntityRef) error
}
PageReverter is the slice of the knowledge-page store a rollback needs: look up by slug, restore a prior version, or soft-delete a newly created page. It is the read-and-revert subset of pageWriter, satisfied by portal/knowledgepage. Store, and is exported so the admin REST rollback (pkg/admin) can supply it via RollbackDeps.Pages.
type PendingReview ¶ added in v1.100.0
type PendingReview struct {
TotalPending int `json:"total_pending"`
OldestPendingAt *time.Time `json:"oldest_pending_at,omitempty"`
PendingOver30d int `json:"pending_over_30d"`
}
PendingReview is the lightweight review-queue summary: the pending count and its staleness rollup, without the by-category/by-confidence group-bys that the full InsightStats carries. It lets platform_info surface the review-debt nudge per session without the heavier Stats fan-out (#764).
func PendingReviewOf ¶ added in v1.100.0
func PendingReviewOf(ctx context.Context, store InsightStore) (*PendingReview, error)
PendingReviewOf returns the review-queue summary platform_info shows as the review-debt nudge (#764): the pending count, the oldest pending capture and how many have waited over thirty days.
It reads them off the store's Stats, which the memory-backed adapter answers in one pass over the active records rather than the group-by fan-out the dropped Postgres store issued.
type PromptCreator ¶ added in v1.51.0
type PromptCreator interface {
Create(ctx context.Context, p *prompt.Prompt) error
RegisterRuntimePrompt(p *prompt.Prompt)
}
PromptCreator creates and registers prompts at runtime.
type ProposedChange ¶
type ProposedChange struct {
ChangeType string `json:"change_type"`
Target string `json:"target"`
CurrentValue string `json:"current_value"`
SuggestedValue string `json:"suggested_value"`
SourceInsightIDs []string `json:"source_insight_ids"`
}
ProposedChange represents a deterministic change proposal from synthesis.
type RelatedColumn ¶
type RelatedColumn struct {
URN string `json:"urn" example:"mcp:dataset:(trino,warehouse,hive.sales.orders)"`
Column string `json:"column" example:"amount"`
Relevance string `json:"relevance" example:"direct"`
}
RelatedColumn represents a column related to an insight.
type RequiredFieldError ¶ added in v1.51.0
type RequiredFieldError string
RequiredFieldError is a sentinel-like error for missing required fields.
func (RequiredFieldError) Error ¶ added in v1.51.0
func (e RequiredFieldError) Error() string
Error implements the error interface.
type RollbackConflictError ¶ added in v1.70.0
type RollbackConflictError struct {
Conflict *catalog.ConflictError
}
RollbackConflictError is returned when an aspect the changeset wrote has been written again since. Reverting would silently discard that newer write, so the rollback is refused and nothing is reverted.
func (*RollbackConflictError) Error ¶ added in v1.70.0
func (e *RollbackConflictError) Error() string
Error implements the error interface.
func (*RollbackConflictError) Unwrap ¶ added in v1.146.0
func (e *RollbackConflictError) Unwrap() error
Unwrap exposes the catalog's conflict.
type RollbackDeps ¶ added in v1.70.0
type RollbackDeps struct {
// Catalog is the platform catalog a catalog changeset is rolled back in.
Catalog catalog.Store
Changesets ChangesetStore
Insights InsightStore
// Pages reverts knowledge-page promotions (target "kp:<slug>"). Optional; a
// nil Pages makes a page-changeset rollback return a clear "not configured"
// error rather than mis-routing through the catalog path.
// PageReverter and PageEditedError live in page_sink.go with the rest of the
// page-sink machinery.
Pages PageReverter
// Instructions reverts promotions into the deployment's customized agent
// instructions (target "ai:<section>"). Optional; a nil Instructions makes an
// instructions-changeset rollback return a clear "not configured" error rather
// than mis-routing through the catalog path. InstructionsStore and
// InstructionsEditedError live in instructions_sink.go with the rest of that
// sink's machinery.
Instructions InstructionsStore
}
RollbackDeps bundles the stores a rollback operates on. It is the shared dependency set for both the apply_knowledge MCP tool and the admin REST endpoint.
type RollbackResult ¶ added in v1.70.0
type RollbackResult struct {
ChangesetID string `json:"changeset_id"`
TargetURN string `json:"target_urn"`
RevertedChanges []string `json:"reverted_changes"`
SkippedChanges []string `json:"skipped_changes,omitempty"`
// InsightsReturnedToReview lists the source insights the rollback sent back to
// the review queue as pending (#1257). Only insights that actually moved are
// listed: one already returned by an earlier rollback, or since decided some
// other way, is left as it is.
InsightsReturnedToReview []string `json:"insights_returned_to_review"`
RolledBackBy string `json:"rolled_back_by,omitempty"`
}
RollbackResult summarizes the outcome of a successful changeset rollback.
func RevertChangeset ¶ added in v1.70.0
func RevertChangeset(ctx context.Context, deps RollbackDeps, cs *Changeset, rolledBackBy string) (*RollbackResult, error)
RevertChangeset rolls back a changeset, returns its source insights to the review queue, and marks it rolled back. It is the single rollback implementation shared by the apply_knowledge MCP tool and the admin REST endpoint.
A catalog changeset is undone through the catalog's own history, every aspect it wrote restored in one transaction. It refuses (rather than silently no-ops) when the changeset is already rolled back, when it created a prompt, or when an aspect it wrote has been written again since.
type ScoredInsight ¶ added in v1.80.0
ScoredInsight pairs an insight with its search relevance score.
type SearchableInsightStore ¶ added in v1.88.0
type SearchableInsightStore interface {
InsightStore
InsightSearcher
}
SearchableInsightStore is an InsightStore that also supports relevance search. Only the memory-backed adapter satisfies it; the legacy SQL store and the noop store implement InsightStore but not InsightSearcher. The unified search wiring asserts the wired store against this so the insights search provider gets both the entity-keyed lookup (List, filtered by EntityURN) and the relevance search (Search) from one value.
type SuggestedAction ¶
type SuggestedAction struct {
ActionType string `json:"action_type" example:"update_description"`
Target string `json:"target" example:"amount"`
Detail string `json:"detail" example:"Gross margin before returns"`
QuerySQL string `json:"query_sql,omitempty"`
QueryDescription string `json:"query_description,omitempty"`
}
SuggestedAction represents a proposed catalog change.
type ToolInventory ¶ added in v1.130.0
type ToolInventory func() []string
ToolInventory reports every tool name this deployment registers. It is a function rather than a slice because the sink is wired before the last toolkit registers, so the inventory is read at promotion time.
type Toolkit ¶
type Toolkit struct {
// contains filtered or unexported fields
}
Toolkit implements the knowledge capture toolkit.
func New ¶
func New(name string, store InsightStore) (*Toolkit, error)
New creates a new knowledge toolkit. If store is nil, a no-op store is used.
func (*Toolkit) BackfillPageRefs ¶ added in v1.88.0
func (t *Toolkit) BackfillPageRefs(ctx context.Context, pages knowledgepage.Store) (BackfillStats, error)
BackfillPageRefs re-derives entity references for existing knowledge pages, so pages that predate the reference feature get their references without a manual re-save (#664 Phase 5). For each live page it:
- re-scans the body for inline references and reconciles them as source=inline (the same reconcile a page save performs); and
- re-derives the references the page's source insights carried, via the page's changesets, and adds them as source=promoted.
It is idempotent (the inline reconcile is a source-scoped replace, the promoted add unions) and best-effort per page: a page whose reference cannot be written (for example an inline mention of a since-deleted entity, the same case the live save path swallows) is logged and skipped, so one bad page never aborts the pass. Only a failure to list pages is returned. Pages are processed in batches because the store caps a single list at backfillPageBatch.
func (*Toolkit) Connection ¶
Connection returns the connection name for audit logging.
func (*Toolkit) PromptInfos ¶ added in v1.38.0
func (*Toolkit) PromptInfos() []registry.PromptInfo
PromptInfos returns metadata for prompts registered by the knowledge toolkit.
func (*Toolkit) RegisterTools ¶
RegisterTools registers the knowledge toolkit's tools. Capture moved to the memory toolkit's memory_capture verb (#633) and reading is search; this toolkit owns admin promotion (apply_knowledge) and the capture-guidance prompts.
func (*Toolkit) RunGuardedBackfill ¶ added in v1.88.0
RunGuardedBackfill runs BackfillPageRefs once, guarded by the platform_backfills sentinel: if the sentinel is absent it runs the backfill and records it. It is idempotent and leaves the sentinel unset on failure so it retries on the next start. Failures are logged, never fatal. Intended to be called in a goroutine at startup.
func (*Toolkit) SetApplyConfig ¶
func (t *Toolkit) SetApplyConfig(cfg ApplyConfig, csStore ChangesetStore, store catalog.Store)
SetApplyConfig enables the apply_knowledge tool with its dependencies. A nil store leaves catalog changes refused; the other sinks still apply.
func (*Toolkit) SetCatalogReach ¶ added in v1.146.0
func (t *Toolkit) SetCatalogReach(reach CatalogReach)
SetCatalogReach installs the connection boundary curation writes respect.
func (*Toolkit) SetInstructionsSink ¶ added in v1.130.0
func (t *Toolkit) SetInstructionsSink(store InstructionsStore, tools ToolInventory)
SetInstructionsSink wires the customized agent-instruction layer and the deployment's tool inventory, enabling sink=agent_instructions. A nil store leaves the sink unavailable (apply with sink=agent_instructions then refuses rather than reporting a success nothing recorded); a nil inventory leaves the stale-tool-name guard inactive, since there is nothing to measure a reference against.
func (*Toolkit) SetPageGuards ¶ added in v1.94.0
func (t *Toolkit) SetPageGuards(guards knowledgepage.PageGuards, emb embedding.Provider)
SetPageGuards wires the resolved knowledge-page write-guard thresholds and the embedding provider used by the create-time duplicate gate (#705). A nil provider (or the noop placeholder) leaves the gate inactive: without a real embedding the cosine similarity is not defined, so the create proceeds unguarded.
func (*Toolkit) SetPageWriter ¶ added in v1.88.0
func (t *Toolkit) SetPageWriter(pw pageWriter)
SetPageWriter wires the knowledge-page store so apply can promote captures to canonical pages (the destination is the sink chosen at apply, not the capture-time class). A nil store leaves the page sink unavailable (apply with sink=knowledge_page then errors rather than silently no-oping).
func (*Toolkit) SetPortalBaseURL ¶ added in v1.131.2
SetPortalBaseURL wires the deployment's public portal address, so a promotion can hand back where the page it wrote is read (#1696). An empty value leaves the address off the response rather than reporting a relative path no one can open: a deployment that has not declared its public address cannot know it.
func (*Toolkit) SetPromptCreator ¶ added in v1.51.0
func (t *Toolkit) SetPromptCreator(pc PromptCreator)
SetPromptCreator sets the prompt creator for add_prompt change type support.
func (*Toolkit) SetQueryProvider ¶
SetQueryProvider sets the query execution provider.
func (*Toolkit) SetSemanticProvider ¶
SetSemanticProvider sets the semantic metadata provider.
type UnrevertibleError ¶ added in v1.70.0
type UnrevertibleError struct {
ChangeTypes []string
}
UnrevertibleError is returned when a changeset contains change types whose pre-change state is not captured in the changeset's before-image, so they cannot be reverted automatically. The recovery path for these is a manual re-apply of the desired state.
func (*UnrevertibleError) Error ¶ added in v1.70.0
func (e *UnrevertibleError) Error() string
Error implements the error interface.