core

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2026 License: Apache-2.0 Imports: 40 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package core is the factory itself: the orchestrator that delegates to skill subagents, the goal critic that checks their work, the merge policy that decides what happens to a change, and the scheduler.

The core holds every credential and never runs a repository command: all untrusted code runs in a sandbox, reached only through a sandbox.Driver. Pushes, pull requests and comments are made by the core through the forge's API.

Index

Constants

View Source
const (
	DefaultCampaignPilot       = 3
	DefaultCampaignMaxParallel = 5
	MaxCampaignParallel        = 50
	MaxCampaignRepos           = 500
	// MaxCampaignTitle is in characters. The title is in every pull
	// request's description, in the part that is never cut.
	MaxCampaignTitle = 200
)

Bounds of a campaign.

View Source
const (
	TriggerSchedule = "schedule"
	TriggerManual   = "manual"
)

Triggers of a proposal.

View Source
const BaselineAuthor = store.ProposalAuthor + ":baseline"

BaselineAuthor is the author of the copy of the version in use that a proposal is measured against. Such a draft exists only while its eval runs; it is not a proposal and nobody edits or activates it.

View Source
const KindPRMerged = "pr_merged"

KindPRMerged is the kind of a request a merged pull request started in another repository (on_merge).

Variables

View Source
var ErrRejected = errors.New("request rejected")

ErrRejected is returned by the intake functions for a request kōjō will not act on: a repository that is not enabled, an actor without the permission to trigger work.

Functions

func AssessRisk

func AssessRisk(p config.MergePolicy, d *diffInfo, criticPassed bool) *store.Risk

AssessRisk scores a change with deterministic rules: the paths it touches, its size, whether tests moved with the code, and whether the goal critic accepted it. The score is the highest rule that fired, not a sum, so one serious signal is not diluted by harmless ones.

func Decide

func Decide(p config.MergePolicy, risk *store.Risk, criticPassed, hasChat bool, prot *forge.Protection) decision

Decide applies the merge policy. Draft pull requests are the default, and what every mode falls back to: a result the critic rejected, a missing human gate, or an unprotected branch can only make the outcome more conservative.

func IsGo added in v0.3.0

func IsGo(text string) bool

IsGo reports whether a message is the command that approves a plan: the word go, alone besides mentions, in any case, with an optional ! or full stop.

func MessagesClosed

func MessagesClosed(s *store.Session) string

MessagesClosed says why a session takes no more messages, or "" when it takes them. A session takes messages while it is queued or running with model steps still ahead of it, was asked for by someone trusted, and is a real session that runs skills.

func PersonKey

func PersonKey(ms config.MemorySettings, surface string, a store.Actor) string

PersonKey resolves who an actor is, for per-person memory: the key their personal memories are stored under, on whatever surface they ask from.

An email is the person: chat surfaces and the dashboard supply one they verified themselves, and it is already what roles are granted to. A forge login or a chat user without an email is a person of its own ("github:alice") unless an admin linked the account to an email in the memory settings, in which case it is that person. kōjō never guesses that two accounts are one human: a wrong guess would hand one person's memory to another.

func PublicSession added in v0.3.0

func PublicSession(ses *store.Session) bool

PublicSession reports, from a stored session's checkpoint, whether everything it read came from repositories anyone could read when it ran. A session without a checkpoint, or that never read its repository, is not known to be public.

Types

type BudgetHold added in v0.3.0

type BudgetHold struct {
	// Scope is install, team or repo; Name is the team or the repository.
	Scope string `json:"scope"`
	Name  string `json:"name,omitempty"`
	// Window is day (the last 24 hours) or month (the calendar month, UTC).
	Window   string  `json:"window"`
	SpentUSD float64 `json:"spent_usd"`
	LimitUSD float64 `json:"limit_usd"`
}

BudgetHold is a budget that is spent.

func (BudgetHold) String added in v0.3.0

func (b BudgetHold) String() string

type CampaignSpec added in v0.4.0

type CampaignSpec struct {
	Title  string            `json:"title"`
	Task   string            `json:"task"`
	Skill  string            `json:"skill,omitempty"`
	Inputs map[string]string `json:"inputs,omitempty"`
	Repos  []string          `json:"repos,omitempty"`
	Team   string            `json:"team,omitempty"`
	Match  string            `json:"match,omitempty"`
	// MaxParallel and Pilot are DefaultCampaignMaxParallel and
	// DefaultCampaignPilot when nil.
	MaxParallel *int `json:"max_parallel,omitempty"`
	Pilot       *int `json:"pilot,omitempty"`
}

CampaignSpec is what a person asks a campaign to do: a task, and the repositories to do it in, chosen by list, team or pattern.

type CheckResult

type CheckResult struct {
	Name     string `json:"name"`
	Passed   bool   `json:"passed"`
	Skipped  bool   `json:"skipped,omitempty"`
	ExitCode int    `json:"exit_code"`
	// Output is the end of the command's output.
	Output  string  `json:"output,omitempty"`
	Seconds float64 `json:"seconds,omitempty"`
}

CheckResult is the outcome of one deterministic check.

type Engine

type Engine struct {
	Store  store.Store
	Config *config.Manager
	Skills *skills.Resolver
	Models models.Gateway
	Driver sandbox.Driver
	// Forges and Chats are the configured surfaces, by name.
	Forges map[string]forge.Forge
	Chats  map[string]chat.Adapter
	// Trackers are the configured issue trackers, by name (tickets.go).
	Trackers map[string]tracker.Tracker
	// Fixtures opens an eval fixture's repository by name. Nil outside evals.
	Fixtures func(name string) (fs.FS, error)
	// FixtureForge opens the forge an eval fixture seeds with issues, pull
	// requests and comments, by fixture name, and the repository on it they
	// belong to. The forge tools of an eval session read it. Nil outside
	// evals; forge.ErrNotFound for a fixture that seeds none.
	FixtureForge func(name string) (forge.Forge, forge.Repo, error)
	// Evals measures the proposals kōjō makes for its own skills. Without
	// one a proposal is left for review unmeasured.
	Evals Evaluator
	// Reports makes links to shareable session reports for pull request
	// descriptions. Without it they link the dashboard only.
	Reports ReportLinks

	// DefaultImage is the sandbox image of kits that name none.
	DefaultImage string
	// SandboxTTL bounds a sandbox's life.
	SandboxTTL time.Duration
	// PublicURL is the dashboard's address, for links in comments.
	PublicURL string
	// Workers is how many sessions run at once.
	Workers int
	// KeepSandboxes leaves sandboxes running after a session, for debugging.
	KeepSandboxes bool
	// Reap removes sandboxes whose TTL has passed, when the driver can.
	Reap func(ctx context.Context) error

	Log     *slog.Logger
	Metrics *Metrics
	// contains filtered or unexported fields
}

Engine runs sessions.

func (*Engine) CampaignView added in v0.4.0

func (e *Engine) CampaignView(ctx context.Context, id string) (*store.CampaignView, error)

CampaignView reads a campaign and where each of its repositories stands.

func (*Engine) Campaigns added in v0.4.0

func (e *Engine) Campaigns(ctx context.Context, f store.CampaignFilter) ([]store.CampaignView, error)

Campaigns lists campaigns with their totals but no rows: how many of their repositories are over, and what they spent.

func (*Engine) CancelCampaign added in v0.4.0

func (e *Engine) CancelCampaign(ctx context.Context, id string, by store.Actor) (*store.Campaign, error)

CancelCampaign stops a campaign: nothing more starts, the repositories not started are cancelled, and every open session of the campaign is asked to stop. A session that could not be asked does not stop the others: the errors are returned together, and cancelling the cancelled campaign again asks its open sessions once more.

func (*Engine) CancelledNow

func (e *Engine) CancelledNow(ctx context.Context, id string)

CancelledNow closes the messages of a session a cancel request ended at once (one that was queued or waiting): no worker will. A session still running is left to its worker.

func (*Engine) CompareWithInUse

func (e *Engine) CompareWithInUse(ctx context.Context, scope, name string, files map[string]string) (SkillChange, error)

CompareWithInUse compares skill files with the version of the skill a scope uses now. The dashboard calls it for a proposal's draft, so what the approver is told a proposal loosens, and the refusal of one that widens the skill, are about the draft as it is and the skill as it is.

func (*Engine) ConfirmCampaign added in v0.4.0

func (e *Engine) ConfirmCampaign(ctx context.Context, id string, maxCostUSD float64, by store.Actor) (*store.Campaign, error)

ConfirmCampaign starts a pending campaign. maxCostUSD is the bound the person confirming saw: it must cover the estimate as it is now, which is worked out again (the budget may have changed since).

func (*Engine) ContinueCampaign added in v0.4.0

func (e *Engine) ContinueCampaign(ctx context.Context, id string, maxCostUSD float64, by store.Actor) (*store.Campaign, error)

ContinueCampaign starts a paused campaign again. After its pilot that marks the pilot passed. After it spent what was confirmed, maxCostUSD must raise the bound by enough for one more session; it may raise the bound after a pilot too. 0 keeps the bound. While settings/models does not bound what a session costs, no campaign continues.

func (*Engine) CreateCampaign added in v0.4.0

func (e *Engine) CreateCampaign(ctx context.Context, spec CampaignSpec, author store.Actor) (*store.Campaign, error)

CreateCampaign resolves a campaign's repositories, bounds what it can cost, and stores it pending: nothing runs until a person confirms the bound (ConfirmCampaign). Errors that wrap ErrRejected are the caller's.

func (*Engine) Credentials

func (e *Engine) Credentials() sandbox.CredentialSource

Credentials returns the engine as the sandbox drivers' credential source. A credential named after a forge resolves to clone credentials for the session's own repository, or for one of its reference or linked repositories while the core clones that one (credentialRepo). The proxy only sets them on requests that cannot write (HostCredential.ReadOnly). On GitHub they are also short-lived and scoped to that repository; on GitLab and Forgejo they are the configured token. Nothing else resolves, so a kit cannot name its way to another secret.

func (*Engine) DecidePlan added in v0.3.0

func (e *Engine) DecidePlan(ctx context.Context, sessionID string, approve bool, who, surface string) error

DecidePlan approves or declines the plan a session waits on, for an operator of the dashboard, the API, MCP or the CLI. It returns ErrRejected (wrapped) when the session waits on no plan or the plan was decided or closed already, and store.ErrNotFound for an unknown session.

func (*Engine) HandleAlert added in v0.4.0

func (e *Engine) HandleAlert(ctx context.Context, src alerts.Source, a alerts.Alert, deliveryID string) error

HandleAlert turns a verified alert into work. It returns ErrRejected (wrapped) for an alert kōjō does not act on; that is not a failure of the delivery. Nothing is answered to the source: there is nowhere to.

func (*Engine) HandleForgeEvent

func (e *Engine) HandleForgeEvent(ctx context.Context, f forge.Forge, ev *forge.Event) error

HandleForgeEvent turns a verified webhook event into work. It returns ErrRejected (wrapped) for events kōjō ignores; that is not a failure of the delivery.

Who may trigger what is decided here, before anything is queued: a mention only starts work when its author has the repository's trigger permission, and events nobody asked for (a new issue, a new pull request) only run the skill an operator configured for them, without write access. A failed check on one of kōjō's own pull requests is the exception the repository opts into: it continues that pull request with the trust of whoever asked for it, if they still have it (followup.go).

func (*Engine) HandleTicketEvent added in v0.3.0

func (e *Engine) HandleTicketEvent(ctx context.Context, t tracker.Tracker, ev tracker.Event) error

HandleTicketEvent turns a verified tracker event into work. It returns ErrRejected (wrapped) for events kōjō does not act on; that is not a failure of the delivery.

func (*Engine) Holds added in v0.3.0

func (e *Engine) Holds(ctx context.Context, list []store.Session) (map[string]*Hold, error)

Holds says, for each session of list that is held back now, why: by session ID. Sessions that are not held are left out.

func (*Engine) ImproveTick

func (e *Engine) ImproveTick(ctx context.Context, now time.Time) (int, error)

ImproveTick is the periodic check: for every scope where self-improvement is on and every skill it covers, it queues a proposal when the skill has no open one, its cooldown has passed, and enough evidence has gathered since the last proposal. It returns how many it queued. It does nothing when another replica leads.

func (*Engine) LimitsReport added in v0.3.0

func (e *Engine) LimitsReport(ctx context.Context) (*LimitsReport, error)

LimitsReport reads every limit and what counts against it. It lists the teams that own repositories or have limits, and the repositories that are enabled, belong to a team, have limits, or spent or ran something.

func (*Engine) OnAction

func (e *Engine) OnAction(ctx context.Context, a chat.Action) error

OnAction implements chat.Handler: a click on an approval button.

func (*Engine) OnMessage

func (e *Engine) OnMessage(ctx context.Context, m chat.Incoming) error

OnMessage implements chat.Handler: a DM or a mention becomes a request.

The sender's role in kōjō decides what the request may do: operators and admins may trigger write actions, everyone else gets read-only answers.

func (*Engine) ProposalApproved

func (e *Engine) ProposalApproved(ctx context.Context, id, by string, detail map[string]any) (*store.Proposal, error)

ProposalApproved records that a person made a proposal's draft the skill in use. The dashboard calls it after the activation went through; nothing in the core does.

func (*Engine) ProposalEdited

func (e *Engine) ProposalEdited(ctx context.Context, id, by string, files map[string]string, change SkillChange) (*store.Proposal, error)

ProposalEdited records that a person changed a proposal's draft: who, the files as they are now and what they loosen. What was measured was the earlier content, so the proposal's eval no longer stands: the comparison keeps the version in use's run, and the draft's next eval is the one shown against it.

func (*Engine) RejectProposal

func (e *Engine) RejectProposal(ctx context.Context, id, by, reason string) (*store.Proposal, error)

RejectProposal closes a proposal a person turned down and deletes its draft. The reason is kept on the proposal: the next proposal for the skill is shown it, and the same files are not proposed again.

func (*Engine) RetryCampaign added in v0.4.0

func (e *Engine) RetryCampaign(ctx context.Context, id string, by store.Actor) (*store.Campaign, error)

RetryCampaign runs again the repositories whose item failed and those whose newest session failed, each as its next attempt. The sessions that ended since the last pass are noted first, as a pass would. A campaign that was done runs again, as does one paused after its pilot (so a failed pilot is tried again before the rest); one paused at its cost bound stays paused until it is continued.

func (*Engine) Rounds

func (e *Engine) Rounds(ctx context.Context, ses *store.Session) ([]PullRequestRounds, error)

Rounds returns the follow-ups of the pull requests a session is part of: for a follow-up session, the pull request it continued; for any other, each pull request it opened that had a follow-up.

func (*Engine) Run

func (e *Engine) Run(ctx context.Context) error

Run claims and runs sessions until ctx ends, then waits for the sessions in flight to checkpoint.

func (*Engine) RunCampaigns added in v0.4.0

func (e *Engine) RunCampaigns(ctx context.Context) error

RunCampaigns moves campaigns on until ctx ends: every open campaign at start and at each tick, and a campaign one of whose sessions ended as soon as the worker that ran it says so (campaignSessionEnded). Every replica runs this loop; the campaign's row lock and each start's dedupe key make that safe.

func (*Engine) RunOne

func (e *Engine) RunOne(ctx context.Context) (bool, error)

RunOne claims one session, if there is one, and runs it to its next stop: done, failed, or waiting for a human. It reports whether it ran one.

func (*Engine) RunReaper

func (e *Engine) RunReaper(ctx context.Context) error

RunReaper removes expired sandboxes every few minutes: the safety net for sandboxes whose session died without cleaning up. It does nothing when the driver has no reaper (Engine.Reap is nil).

func (*Engine) RunScheduler

func (e *Engine) RunScheduler(ctx context.Context) error

RunScheduler fires schedules until ctx ends. Every replica runs this loop; only the one holding the leader lock fires, so a schedule fires once.

func (*Engine) SendMessage

func (e *Engine) SendMessage(ctx context.Context, sessionID string, m store.SessionMessage) (*store.SessionMessage, error)

SendMessage gives a session a message from the dashboard, the API, MCP or the CLI. Only operators reach it, so the author is trusted. It returns ErrRejected (wrapped) when the session takes no messages or the message is out of bounds, and store.ErrNotFound for an unknown session.

func (*Engine) StartImprovement

func (e *Engine) StartImprovement(ctx context.Context, scope, skill, surface string, by store.Actor) (*store.Proposal, *store.Session, error)

StartImprovement queues the work of proposing a change to one skill of one scope, on behalf of someone who asked for it. It refuses when self-improvement is not turned on for the skill, when the evidence is below the threshold, and when the skill already has an open proposal.

func (*Engine) Submit

func (e *Engine) Submit(ctx context.Context, req store.Request) (*store.Session, error)

Submit enqueues a request and wakes a worker. Every surface ends here.

func (*Engine) Tick

func (e *Engine) Tick(ctx context.Context, now time.Time) (int, error)

Tick fires every schedule that is due at now and returns how many sessions it enqueued. It does nothing when another replica leads.

func (*Engine) Wake

func (e *Engine) Wake()

Wake makes an idle worker look at the queue now instead of at its next poll. Surfaces call it after enqueueing.

type Evaluator

type Evaluator interface {
	// Start begins an eval of a draft of a skill and returns the run's ID
	// at once; the run continues in the background.
	Start(ctx context.Context, skill, draftID, author string) (string, error)
	// HasFixtures reports whether the skill has eval fixtures at all.
	HasFixtures(skill string) bool
}

Evaluator runs skill evals. internal/eval implements it.

type FollowUpRound

type FollowUpRound struct {
	Round     int                 `json:"round"`
	SessionID string              `json:"session_id"`
	Trigger   string              `json:"trigger"`
	Check     string              `json:"check,omitempty"`
	Actor     string              `json:"actor,omitempty"`
	Status    store.SessionStatus `json:"status"`
	Outcome   string              `json:"outcome,omitempty"`
	Commit    string              `json:"commit,omitempty"`
	CreatedAt time.Time           `json:"created_at"`
}

FollowUpRound is one follow-up session of one of kōjō's pull requests.

type Hold added in v0.3.0

type Hold struct {
	Reason string         `json:"reason"`
	Cap    *store.CapHold `json:"cap,omitempty"`
	Budget *BudgetHold    `json:"budget,omitempty"`
}

Hold says why a session does not start: a cap on running sessions (Cap), or a spent budget (Budget). Reason says it in words.

type InstallUsage added in v0.3.0

type InstallUsage struct {
	PerSessionUSD float64 `json:"per_session_usd,omitempty"`
	PerDayUSD     float64 `json:"per_day_usd,omitempty"`
	SpentDayUSD   float64 `json:"spent_day_usd"`
	SpentMonthUSD float64 `json:"spent_month_usd"`
	Running       int     `json:"running"`
	Queued        int     `json:"queued"`
	Held          int     `json:"held"`
}

InstallUsage is the whole install against the budgets of settings/models.

type LimitUsage added in v0.3.0

type LimitUsage struct {
	Name string `json:"name"`
	// Team is a repository's team; Repos are a team's repositories.
	Team          string   `json:"team,omitempty"`
	Repos         []string `json:"repos,omitempty"`
	PerDayUSD     float64  `json:"per_day_usd,omitempty"`
	PerMonthUSD   float64  `json:"per_month_usd,omitempty"`
	MaxRunning    int      `json:"max_running,omitempty"`
	SpentDayUSD   float64  `json:"spent_day_usd"`
	SpentMonthUSD float64  `json:"spent_month_usd"`
	Running       int      `json:"running"`
	Queued        int      `json:"queued"`
	// Held is how many queued sessions this limit holds back now.
	Held int `json:"held"`
}

LimitUsage is one team or repository against its limits. A limit of 0 is no limit.

type LimitsReport added in v0.3.0

type LimitsReport struct {
	At time.Time `json:"at"`
	// Workers is how many sessions this replica runs at once. Every replica
	// has its own workers.
	Workers  int            `json:"workers"`
	Install  InstallUsage   `json:"install"`
	Teams    []LimitUsage   `json:"teams"`
	Repos    []LimitUsage   `json:"repos"`
	Triggers []TriggerUsage `json:"triggers"`
}

LimitsReport is every limit with what counts against it now: spend over the last 24 hours and this calendar month, running sessions, and the queued sessions it holds back.

type Metrics

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

Metrics are the factory's Prometheus metrics (design §9): sessions by status, critic pass rate and attempts per skill, tokens and cost, sandbox start-up time, pull requests opened and merged, what became of each pull request (the merge rate and the human-edit rate), and lessons learned.

func NewMetrics

func NewMetrics(reg prometheus.Registerer) *Metrics

NewMetrics registers the metrics on reg. A nil reg keeps them unregistered (tests).

type PullRequestRounds

type PullRequestRounds struct {
	Repo   string `json:"repo"`
	Number int    `json:"number"`
	URL    string `json:"url,omitempty"`
	Branch string `json:"branch,omitempty"`
	// OpenedBy is the session that opened the pull request.
	OpenedBy  string          `json:"opened_by"`
	MaxRounds int             `json:"max_rounds"`
	Rounds    []FollowUpRound `json:"rounds"`
}

PullRequestRounds are the follow-ups of one of kōjō's pull requests.

type ReportLinks interface {
	// For returns the address of a new link to the session's report, or
	// "" when settings/reports or the session do not allow one. public and
	// confidential are what the session knows of itself.
	For(ctx context.Context, ses *store.Session, public, confidential bool) (string, error)
}

ReportLinks makes links to shareable session reports (internal/report): a read-only, redacted page of a session that anyone with the link can open without a dashboard account. A pull request's description links the report instead of the dashboard's replay when settings/reports allows.

type SkillChange

type SkillChange struct {
	// Widens lists every way the proposed version can do more than the one
	// in use: a new tool, another kit, a higher model tier. A proposal with
	// any of these is refused.
	Widens []string `json:"widens"`
	// Loosens lists every way the proposed goals are easier to meet. These
	// are allowed, and shown to the approver next to the diff.
	Loosens []string `json:"loosens"`
}

SkillChange is what a proposed version of a skill changes, as far as the limits on a proposal go. It is found by comparing the two parsed skills, never by asking the model that wrote the proposal.

func CompareSkills

func CompareSkills(cur, next *skills.Skill) SkillChange

CompareSkills reports what next widens and loosens against cur, the version in use.

A proposal may rewrite the instructions, the description, the outputs and the goals. Everything that decides what the skill can reach or spend is fixed: its tools (it may drop some), its kit (image, resources, egress, credentials, Docker, setup commands), its model tier (it may go down), whether it may change the workspace and whether its report is confidential. Files other than SKILL.md and goals.yaml, the kit file among them, may not change at all.

type SkillResult

type SkillResult struct {
	Skill string `json:"skill"`
	Task  string `json:"task,omitempty"`
	// Passed is the goal critic's final verdict.
	Passed   bool `json:"passed"`
	Attempts int  `json:"attempts"`
	// Summary is the subagent's own final report.
	Summary string `json:"summary"`
	// Failures are the acceptance criteria still unmet after the last
	// attempt.
	Failures []string      `json:"failures,omitempty"`
	Checks   []CheckResult `json:"checks,omitempty"`
	// Outputs are the values the subagent recorded with set_output.
	Outputs map[string]string `json:"outputs,omitempty"`
	// ChangedFiles are the files this run changed.
	ChangedFiles []string `json:"changed_files,omitempty"`
	Added        int      `json:"added,omitempty"`
	Removed      int      `json:"removed,omitempty"`
}

SkillResult is the outcome of one delegated skill run, after the goal critic's last verdict.

type TriggerUsage added in v0.3.0

type TriggerUsage struct {
	Name       string `json:"name"`
	MaxRunning int    `json:"max_running"`
	Running    int    `json:"running"`
	Queued     int    `json:"queued"`
	Held       int    `json:"held"`
}

TriggerUsage is one trigger against its cap.

Jump to

Keyboard shortcuts

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