context

package
v0.0.0-...-3024e77 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package context implements the Context Engine — approved context management, context views, FTS-backed search, and delivery (L0-L4). It enforces v4 Principle 6: "El contexto siempre se deriva de entidades aprobadas."

Main types: AuthorityService, Builder, DeliveryEngine, Registry. Main entry: AuthorityService.Add for deduplicated approved context insertion.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsApproved

func IsApproved(item ApprovedItem) bool

Types

type ApprovedConstraint

type ApprovedConstraint = ApprovedItem

type ApprovedDecision

type ApprovedDecision = ApprovedItem

type ApprovedGoal

type ApprovedGoal = ApprovedItem

type ApprovedItem

type ApprovedItem struct {
	ID        string
	ProjectID string
	Type      ApprovedType
	SourceID  string
	Content   string
	State     State
	CreatedAt time.Time
	UpdatedAt time.Time
}

type ApprovedPreference

type ApprovedPreference = ApprovedItem

type ApprovedReference

type ApprovedReference = ApprovedItem

type ApprovedRequirement

type ApprovedRequirement = ApprovedItem

type ApprovedType

type ApprovedType string
const (
	TypeRequirement ApprovedType = "requirement"
	TypeConstraint  ApprovedType = "constraint"
	TypeDecision    ApprovedType = "decision"
	TypePreference  ApprovedType = "preference"
	TypeGoal        ApprovedType = "goal"
	TypeReference   ApprovedType = "reference"
)

type AuthorityService

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

AuthorityService makes approved context the authority for what Plan-AI already knows. It provides:

  • deduplicated storage (same content → same ID, no doubles)
  • cross-type FTS search via approved_context_fts
  • supersession (mark a fact as obsolete and link to its replacement)
  • hooks for memory records and continuous planning events

This implements Phase 6 (Approved Context Authority).

func NewAuthorityService

func NewAuthorityService(repo Repository, db *sql.DB) *AuthorityService

NewAuthorityService creates an authority service backed by the given repo and database. The db is used for FTS queries and migrations.

func (*AuthorityService) Add

func (s *AuthorityService) Add(item ApprovedItem) (approved ApprovedItem, existed bool, err error)

Add stores an approved item. If a matching item already exists (same project, same content, same type), it returns the existing one without creating a duplicate.

The returned bool is true if the item already existed.

func (*AuthorityService) EnsureFTS

func (s *AuthorityService) EnsureFTS() error

EnsureFTS creates the FTS5 virtual table and triggers over all approved_* tables. Idempotent — safe to call multiple times.

func (*AuthorityService) FindAll

func (s *AuthorityService) FindAll(projectID string, query string) ([]ApprovedItem, error)

FindAll searches approved items of all types for matching content. Uses SQL LIKE by default; FTS is preferred when the approved_context_fts virtual table has been created (see EnsureFTS).

func (*AuthorityService) IsKnown

func (s *AuthorityService) IsKnown(projectID string, content string) bool

IsKnown checks if the exact content has already been approved for this project. Case-insensitive match.

func (*AuthorityService) SetHook

func (s *AuthorityService) SetHook(fn func(item ApprovedItem))

SetHook attaches a callback fired when an item is added or superseded.

func (*AuthorityService) Supersede

func (s *AuthorityService) Supersede(projectID string, oldContent string, newItem ApprovedItem) (ApprovedItem, error)

Supersede marks an existing approved item (matching content) as "superseded" and creates a new item with the replacement content. Returns the new item.

type BudgetStrategy

type BudgetStrategy string

BudgetStrategy defines how context budgets are managed.

const (
	BudgetFixed      BudgetStrategy = "fixed"
	BudgetDynamic    BudgetStrategy = "dynamic"
	BudgetPercentage BudgetStrategy = "percentage"
)

type Builder

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

func NewBuilder

func NewBuilder(repo Repository, domainQ ProjectQuerier, visionQ VisionQuerier, planningQ PlanningQuerier) *Builder

NewBuilder creates a context builder.

func (*Builder) BuildExecutiveContext

func (b *Builder) BuildExecutiveContext(projectID string) (ExecutiveContext, error)

BuildExecutiveContext builds an executive overview of project status.

func (*Builder) BuildImplementationContext

func (b *Builder) BuildImplementationContext(projectID, taskID string) (ImplementationContext, error)

BuildImplementationContext assembles context for a specific task implementation.

func (*Builder) BuildPlanningContext

func (b *Builder) BuildPlanningContext(projectID string) (PlanningContext, error)

BuildPlanningContext assembles a planning context from vision, requirements, etc.

func (*Builder) BuildResearchContext

func (b *Builder) BuildResearchContext(projectID, topic string) (ResearchContext, error)

BuildResearchContext assembles research context for a topic.

func (*Builder) PersistContextView

func (b *Builder) PersistContextView(name, viewType, projectID, content string) (ContextView, error)

PersistContextView saves a context view to the store.

type ContextChunk

type ContextChunk struct {
	ID            string `json:"id"`
	ContextViewID string `json:"context_view_id"`
	ChunkIndex    int    `json:"chunk_index"`
	Content       string `json:"content"`
	CreatedAt     string `json:"created_at"`
}

type ContextView

type ContextView struct {
	ID        string    `json:"id"`
	ProjectID string    `json:"project_id"`
	Name      string    `json:"name"`
	ViewType  string    `json:"view_type"`
	Content   string    `json:"content"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

type DecisionBrief

type DecisionBrief struct {
	ID     string
	Title  string
	Status string
}

DecisionBrief is a lightweight decision representation.

type DeliveryBudget

type DeliveryBudget struct {
	ID           string         `json:"id"`
	ProjectID    string         `json:"project_id"`
	Level        DeliveryLevel  `json:"level"`
	MaxTokens    int            `json:"max_tokens"`
	CurrentUsage int            `json:"current_usage"`
	Strategy     BudgetStrategy `json:"strategy"`
	CreatedAt    time.Time      `json:"created_at"`
	UpdatedAt    time.Time      `json:"updated_at"`
}

DeliveryBudget represents token budget configuration for a level.

type DeliveryEngine

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

DeliveryEngine delivers context at the right granularity with budget awareness.

func NewDeliveryEngine

func NewDeliveryEngine(
	repo DeliveryRepository,
	execData ExecutiveData,
	planData PlanningData,
	implData ImplementationData,
	researchData ResearchData,
) *DeliveryEngine

NewDeliveryEngine creates a new ContextDeliveryEngine.

func (*DeliveryEngine) DeliverContext

func (e *DeliveryEngine) DeliverContext(projectID string, level DeliveryLevel, params map[string]string) (*DeliverySession, error)

DeliverContext builds and delivers context at the requested level.

func (*DeliveryEngine) GetUsageSummary

func (e *DeliveryEngine) GetUsageSummary(projectID string) (map[string]int, error)

GetUsageSummary returns token usage summary for a project.

func (*DeliveryEngine) SetBudget

func (e *DeliveryEngine) SetBudget(projectID string, level DeliveryLevel, maxTokens int, strategy BudgetStrategy) (DeliveryBudget, error)

SetBudget sets or updates a budget for a level.

type DeliveryLevel

type DeliveryLevel string

DeliveryLevel defines the granularity level of context delivery.

const (
	LevelExecutive      DeliveryLevel = "L0_executive"
	LevelPlanning       DeliveryLevel = "L1_planning"
	LevelImplementation DeliveryLevel = "L2_implementation"
	LevelResearch       DeliveryLevel = "L3_research"
	LevelApproval       DeliveryLevel = "L4_approval"
)

type DeliveryRepository

type DeliveryRepository interface {
	CreateSession(session DeliverySession) (DeliverySession, error)
	ListSessions(projectID string, level string, limit int) ([]DeliverySession, error)

	CreateUsage(usage DeliveryUsage) (DeliveryUsage, error)
	GetTotalUsage(projectID string) (int, error)

	CreateOrUpdateBudget(budget DeliveryBudget) (DeliveryBudget, error)
	GetBudget(projectID string, level DeliveryLevel) (DeliveryBudget, error)
}

DeliveryRepository provides persistence for context delivery entities.

type DeliverySession

type DeliverySession struct {
	ID           string                 `json:"id"`
	ProjectID    string                 `json:"project_id"`
	Level        DeliveryLevel          `json:"level"`
	BudgetTokens int                    `json:"budget_tokens"`
	TokensUsed   int                    `json:"tokens_used"`
	Content      string                 `json:"content"`
	Metadata     map[string]interface{} `json:"metadata"`
	Status       DeliveryStatus         `json:"status"`
	CreatedAt    time.Time              `json:"created_at"`
}

DeliverySession represents a context delivery session.

type DeliveryStatus

type DeliveryStatus string

DeliveryStatus defines the status of a delivery session.

const (
	DeliveryPending    DeliveryStatus = "pending"
	DeliveryInProgress DeliveryStatus = "in_progress"
	DeliveryDelivered  DeliveryStatus = "delivered"
	DeliveryFailed     DeliveryStatus = "failed"
)

type DeliveryUsage

type DeliveryUsage struct {
	ID        string    `json:"id"`
	ProjectID string    `json:"project_id"`
	SessionID string    `json:"session_id"`
	Level     string    `json:"level"`
	Tokens    int       `json:"tokens"`
	Source    string    `json:"source"`
	CreatedAt time.Time `json:"created_at"`
}

DeliveryUsage represents a token usage record.

type ExecutiveContext

type ExecutiveContext struct {
	ProjectID   string         `json:"project_id"`
	Status      string         `json:"status"`
	WhatMissing []string       `json:"what_missing"`
	WhatNext    []string       `json:"what_next"`
	Risks       []string       `json:"risks"`
	Progress    map[string]int `json:"progress"` // phase -> completed tasks
	UpdatedAt   time.Time      `json:"updated_at"`
}

type ExecutiveData

type ExecutiveData interface {
	GetProjectBrief(projectID string) (domain.Project, error)
	ListPlanBriefs(projectID string) ([]domain.MasterPlan, error)
	ListDecisionBriefs(projectID string) ([]domain.Decision, error)
}

ExecutiveData provides data for L0 executive context.

type ImplementationContext

type ImplementationContext struct {
	ProjectID         string    `json:"project_id"`
	Task              string    `json:"task"`
	SpecificPlan      string    `json:"specific_plan"`
	ImplementationDoc string    `json:"implementation_doc"`
	Decisions         []string  `json:"decisions"`
	Constraints       []string  `json:"constraints"`
	Validations       []string  `json:"validations"`
	KnownRisks        []string  `json:"known_risks"`
	ExpectedFiles     []string  `json:"expected_files"`
	UpdatedAt         time.Time `json:"updated_at"`
}

type ImplementationData

type ImplementationData interface {
	ListApproved(projectID string, itemType ApprovedType) ([]ApprovedItem, error)
	GetSpecificPlan(planID string) (domain.SpecificPlan, error)
	ListTasks(phaseID string) ([]domain.Task, error)
}

ImplementationData provides data for L2 implementation context.

type ImplementationPackage

type ImplementationPackage struct {
	ID              string
	ProjectID       string
	PlanID          string
	ModelTarget     string
	WhatToDo        string
	HowToDoIt       string
	FilesToTouch    []string
	FilesNotToTouch []string
	Examples        []string
	Commands        []string
	Validations     []string
	RollbackNotes   []string
	Status          string
	CreatedAt       time.Time
	UpdatedAt       time.Time
}

func BuildImplementationPackage

func BuildImplementationPackage(projectID, planID, modelTarget, objective string) ImplementationPackage

type ImplementationPackageRepository

type ImplementationPackageRepository interface {
	SaveImplementationPackage(ImplementationPackage) (ImplementationPackage, error)
	ListImplementationPackages(projectID string) ([]ImplementationPackage, error)
}

type ImplementationPackageService

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

func (ImplementationPackageService) Create

func (s ImplementationPackageService) Create(projectID, planID, modelTarget, objective string) (ImplementationPackage, error)

func (ImplementationPackageService) List

type KnowledgeBrief

type KnowledgeBrief struct {
	ID      string
	Topic   string
	Summary string
}

KnowledgeBrief is a lightweight knowledge object representation.

type PackageType

type PackageType string
const (
	PackageVision         PackageType = "vision"
	PackageResearch       PackageType = "research"
	PackagePlanning       PackageType = "planning"
	PackageImplementation PackageType = "implementation"
	PackageChange         PackageType = "change"
)

type PhaseBrief

type PhaseBrief struct {
	ID     string
	Title  string
	Status string
}

PhaseBrief is a lightweight phase representation.

type PlanBrief

type PlanBrief struct {
	ID     string
	Title  string
	Status string
}

PlanBrief is a lightweight plan representation.

type PlanningContext

type PlanningContext struct {
	ProjectID    string    `json:"project_id"`
	Vision       string    `json:"vision"`
	Requirements []string  `json:"requirements"`
	Constraints  []string  `json:"constraints"`
	Research     []string  `json:"research"`
	Knowledge    []string  `json:"knowledge"`
	Decisions    []string  `json:"decisions"`
	UpdatedAt    time.Time `json:"updated_at"`
}

type PlanningData

type PlanningData interface {
	ListApproved(projectID string, itemType ApprovedType) ([]ApprovedItem, error)
	ListKnowledgeBriefs(projectID string) ([]KnowledgeBrief, error)
	ListResearchBriefs(projectID string) ([]ResearchBrief, error)
	ListVisions(projectID string) ([]domain.Vision, error)
}

PlanningData provides data for L1 planning context.

type PlanningQuerier

type PlanningQuerier interface {
	ListMasterPlans(projectID string) ([]domain.MasterPlan, error)
	ListSpecificPlans(masterPlanID string) ([]domain.SpecificPlan, error)
	ListPhases(planID string) ([]domain.Phase, error)
	ListTasks(phaseID string) ([]domain.Task, error)
}

PlanningQuerier provides access to planning data.

type ProjectBrief

type ProjectBrief struct {
	ID     string
	Name   string
	Status string
}

ProjectBrief is a lightweight project representation used by context builders.

type ProjectQuerier

type ProjectQuerier interface {
	GetProjectBrief(id string) (ProjectBrief, error)
	ListPlanBriefs(projectID string) ([]PlanBrief, error)
	ListPhaseBriefs(planID string) ([]PhaseBrief, error)
	ListTaskBriefs(phaseID string) ([]TaskBrief, error)
	ListDecisionBriefs(projectID string) ([]DecisionBrief, error)
	ListResearchBriefs(projectID string) ([]ResearchBrief, error)
	ListKnowledgeBriefs(projectID string) ([]KnowledgeBrief, error)
}

ProjectQuerier provides read-only access to project data for context building. This interface lives in the context package to avoid import cycles with store.

type Query

type Query struct {
	ProjectID string
	Type      ApprovedType
	Text      string
}

type Registry

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

func NewRegistry

func NewRegistry(repo Repository) Registry

func (Registry) FindApproved

func (r Registry) FindApproved(projectID string, itemType ApprovedType, query string) ([]ApprovedItem, error)

func (Registry) GetApproved

func (r Registry) GetApproved(itemType ApprovedType, id string) (ApprovedItem, error)

func (Registry) ListApproved

func (r Registry) ListApproved(projectID string, itemType ApprovedType) ([]ApprovedItem, error)

func (Registry) StoreApproved

func (r Registry) StoreApproved(item ApprovedItem) (ApprovedItem, error)

type Repository

type Repository interface {
	StoreApproved(ApprovedItem) (ApprovedItem, error)
	GetApproved(ApprovedType, string) (ApprovedItem, error)
	ListApproved(projectID string, itemType ApprovedType) ([]ApprovedItem, error)
	FindApproved(projectID string, itemType ApprovedType, query string) ([]ApprovedItem, error)
}

type ResearchBrief

type ResearchBrief struct {
	ID      string
	Topic   string
	Summary string
}

ResearchBrief is a lightweight research entry representation.

type ResearchContext

type ResearchContext struct {
	ProjectID        string    `json:"project_id"`
	Topic            string    `json:"topic"`
	PreviousFindings []string  `json:"previous_findings"`
	RelatedKnowledge []string  `json:"related_knowledge"`
	RelatedDecisions []string  `json:"related_decisions"`
	UpdatedAt        time.Time `json:"updated_at"`
}

type ResearchData

type ResearchData interface {
	ListResearchBriefs(projectID string) ([]ResearchBrief, error)
	ListKnowledgeBriefs(projectID string) ([]KnowledgeBrief, error)
	ListDecisionBriefs(projectID string) ([]domain.Decision, error)
}

ResearchData provides data for L3 research context.

type Service

type Service struct{ Registry }

func NewService

func NewService(repo Repository) Service

type SmartPackage

type SmartPackage struct {
	ID          string
	ProjectID   string
	Type        PackageType
	ModelTarget string
	Summary     string
	Content     string
	Priority    int
	TokenBudget int
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

func BuildSmartPackage

func BuildSmartPackage(projectID string, typ PackageType, model, content string, budget int) SmartPackage

type SmartPackageRepository

type SmartPackageRepository interface {
	SavePackage(SmartPackage) (SmartPackage, error)
	ListPackages(projectID string) ([]SmartPackage, error)
	GetPackage(id string) (SmartPackage, error)
}

type SmartPackageService

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

func NewSmartPackageService

func NewSmartPackageService(repo SmartPackageRepository) SmartPackageService

func (SmartPackageService) Create

func (s SmartPackageService) Create(projectID string, typ PackageType, model, content string, budget int) (SmartPackage, error)

func (SmartPackageService) Get

func (SmartPackageService) List

func (s SmartPackageService) List(projectID string) ([]SmartPackage, error)

type State

type State string
const StateApproved State = "approved"

type TaskBrief

type TaskBrief struct {
	ID     string
	Title  string
	Status string
}

TaskBrief is a lightweight task representation.

type VisionQuerier

type VisionQuerier interface {
	ListVisions(projectID string) ([]domain.Vision, error)
}

VisionQuerier provides access to vision data.

Jump to

Keyboard shortcuts

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