Documentation
¶
Overview ¶
Package store is kōjō's persistence: the job queue, sessions and their checkpoints, the audit log, day-2 config revisions, skill drafts, team memory, eval results and the proposals kōjō makes for its own skills. Postgres is the only production implementation (internal/store/postgres); internal/store/memory backs unit tests. Both pass internal/store/storetest.
Index ¶
- Constants
- Variables
- func CampaignOpen(status string) bool
- func MatchAction(filter, action string) bool
- func MatchSource(filter, source string) bool
- func NewID(prefix string) string
- func ParseReviewSource(source string) (number int, reviewer string, ok bool)
- func PersonKey(namespace, id string) string
- func ProposalOpen(status string) bool
- func RepoScope(repo string) string
- func ReviewSource(number int, reviewer string) string
- func SessionTitle(req Request) string
- type Actor
- type AlertRef
- type Approval
- type AuditEntry
- type AuditFilter
- type Campaign
- type CampaignEstimate
- type CampaignFilter
- type CampaignItem
- type CampaignRow
- type CampaignSelector
- type CampaignSkip
- type CampaignTotals
- type CampaignView
- type CapHold
- type Caps
- type CheckRef
- type ConfigChange
- type EvalCase
- type EvalRun
- type Evidence
- type FileProvenance
- type FollowUp
- type HistoryCase
- type HistoryCheck
- type HistoryEstimate
- type HistoryOutcome
- type HistoryRequest
- type HistoryRun
- type HistorySkip
- type IDLocks
- type LineBlock
- type Memory
- type MemoryFilter
- type MemoryQuery
- type Plan
- type PlanEstimate
- type Proposal
- type ProposalChange
- type ProposalFilter
- type Provenance
- type ProvenanceStep
- type PullRequest
- type PullRequestFilter
- type PullRequestLink
- type RepoProvenance
- type Request
- type ReviewContext
- type Revision
- type Risk
- type Running
- type RunningCount
- type ScheduleState
- type Session
- type SessionFilter
- type SessionMessage
- type SessionResult
- type SessionStatus
- type SkillDraft
- type SkillIndexEntry
- type Step
- type StepKind
- type Store
- type TestRun
- type ThreadRef
- type TicketRef
- type User
Constants ¶
const ( // CampaignPending waits for a person to confirm the cost bound. CampaignPending = "pending" // CampaignRunning starts sessions, a few at a time. CampaignRunning = "running" // CampaignPaused starts nothing until someone continues it: after its // pilot, when it spent what was confirmed, or when its sessions' cost // is no longer bounded (Campaign.Paused). CampaignPaused = "paused" CampaignDone = "done" CampaignCancelled = "cancelled" )
Campaign statuses.
const ( PausedPilot = "pilot" PausedCost = "cost" // PausedBound: settings/models no longer bounds what a session costs // (Campaign.Problem says why). PausedBound = "bound" )
Why a campaign is paused.
const ( // ItemPending has no session yet. ItemPending = "pending" // ItemStarted has a session that is not over; its own status is read // from the session. ItemStarted = "started" // ItemDone has a session that is over, whatever its outcome. ItemDone = "done" // ItemFailed could not be submitted (Error says why). ItemFailed = "failed" ItemCancelled = "cancelled" )
Campaign item states.
const ( // EvalValidating: mining merged pull requests and checking each case // in a sandbox. No model is called. EvalValidating = "validating" // EvalValidated: the cases are checked and the cost bound is known; // the run waits for someone to confirm it. EvalValidated = "validated" EvalRunning = "running" EvalDone = "done" EvalFailed = "failed" )
History eval run states, in EvalRun.Status.
const ( // CasePending is a mined case not checked yet. CasePending = "pending" // CaseValid: the fix's tests fail without the fix and pass with it. CaseValid = "valid" // CaseInvalid: the check did not hold; Reason says why. An invalid case // costs no model call. CaseInvalid = "invalid" // CasePass and CaseFail: the skill ran and the fix's tests passed, or // did not, on its result. CasePass = "pass" CaseFail = "fail" // CaseError: the case could not be measured (the session or a check // failed for a reason of its own). CaseError = "error" // CaseSkipped: the case did not run (the daily budget was spent). CaseSkipped = "skipped" )
History case states, in HistoryCase.State.
const ( KindMention = "mention" KindIssueOpened = "issue_opened" KindPROpened = "pr_opened" KindPRUpdated = "pr_updated" KindCheckFailed = "check_failed" KindSchedule = "schedule" KindManual = "manual" KindChat = "chat" // KindTicket is a ticket of an issue tracker assigned to kōjō, labelled // for it, or a comment on one that mentions it (Request.Ticket). KindTicket = "ticket" KindSkillTest = "skill_test" KindEval = "eval" // KindFeedback is a maintainer's review or comment on a pull request // kōjō opened. Its session runs no skill: it distils lessons from the // comment and saves them as team memory. KindFeedback = "feedback" // KindImprove asks kōjō to propose a change to one of its own skills // from the evidence it has gathered. Its session runs no skill: it // writes a proposal (ProposalID), has it measured by evals, and leaves // it for a person to approve. KindImprove = "improve" // KindAlert is a production alert (Sentry) for an error of a // repository's application (Request.Alert). KindAlert = "alert" // KindCampaign is one repository's session of a campaign: the same // task run across many repositories (Request.Campaign). KindCampaign = "campaign" )
Request kinds.
const ( FollowUpMention = "mention" FollowUpCheckFailed = "check_failed" )
Follow-up triggers.
const ( PlanPending = "pending" PlanRevising = "revising" PlanApproved = "approved" PlanDeclined = "declined" PlanExpired = "expired" )
Statuses of a Plan.
const ( // ProposalProposing: queued, or the model is writing it. ProposalProposing = "proposing" // ProposalEvaluating: the draft exists and its evals are running. ProposalEvaluating = "evaluating" // ProposalReady: it held up; a person approves or rejects it. ProposalReady = "ready" // ProposalApproved: a person activated it. ProposalApproved = "approved" // ProposalRejected: a person turned it down (Reason says why). ProposalRejected = "rejected" // ProposalDidNotHoldUp: its eval pass rate was lower than the version // in use, or below the activation policy's minimum. ProposalDidNotHoldUp = "did_not_hold_up" // ProposalRefused: it tried to change something a proposal may not // change (Refused lists what), or did not validate. ProposalRefused = "refused" // ProposalNothing: there was nothing to propose. ProposalNothing = "nothing_to_propose" // ProposalFailed: its session failed before a result. ProposalFailed = "failed" )
Proposal statuses. A proposal is open while it is being written, measured, or waiting for a person; every other status is final.
const ( EvidenceCritic = "critic" // the goal critic rejected a result EvidenceLesson = "lesson" // a lesson learned from a review EvidencePullRequest = "pull_request" // closed unmerged, or edited by a person )
Evidence kinds.
const ( PROpen = "open" PRMerged = "merged" PRClosed = "closed" // closed without merging )
Pull request states.
const ( // MessagePending: stored, and no model of the session has read it yet. MessagePending = "pending" // MessageDelivered: a model call of the session read it. MessageDelivered = "delivered" // MessageUnread: the session's work ended before any model read it. MessageUnread = "unread" )
Statuses of a SessionMessage.
const ProposalAuthor = "kojo"
ProposalAuthor is the author of a draft kōjō proposed. No person and no API token has this name: a token's actor is "token:<name>" and a person's is an email address.
const ScopeOrg = "org"
ScopeOrg is the scope of org-wide configuration. A repository's scope is "repo:" + its ID.
const SourceReview = "review:"
SourceReview prefixes the source of a lesson learned from a review.
Variables ¶
var ( ErrNotFound = errors.New("store: not found") // ErrDuplicate is returned by Enqueue for a request whose DedupeKey was // already enqueued (a webhook delivered twice). ErrDuplicate = errors.New("store: duplicate request") // ErrConflict is returned when a write lost a race (a job claimed by // another worker, a draft edited from a stale version). ErrConflict = errors.New("store: conflict") // ErrLimit is returned by AddSessionMessage for a session that already // holds as many messages as it may. ErrLimit = errors.New("store: limit reached") // ErrLocked is returned by TryUpdateCampaign when another update holds // the campaign. ErrLocked = errors.New("store: locked by another update") )
Errors every implementation returns for the same cases.
Functions ¶
func CampaignOpen ¶ added in v0.4.0
CampaignOpen reports whether a campaign may still start sessions.
func MatchAction ¶
MatchAction reports whether an audit action matches a filter: an empty filter matches all, one ending in "." is a prefix, anything else is exact.
func MatchSource ¶
MatchSource reports whether a memory's source matches a filter: an empty filter matches all, one ending in ":" is a prefix, anything else is exact.
func NewID ¶
NewID returns a unique ID with a prefix: ses_01j.... IDs made by one process sort in the order they were made, which listings page on.
func ParseReviewSource ¶
ParseReviewSource reads a ReviewSource back. ok is false for any other source.
func PersonKey ¶
PersonKey is the key personal memories are stored under: "email:" and the address for someone kōjō knows by email, "<namespace>:<id>" (a forge login, a chat user ID, an API token's name) for anyone else. Keys are lower case, so alice@Example.com and Alice@example.com are one person.
func ProposalOpen ¶
ProposalOpen reports whether a proposal status is not final.
func ReviewSource ¶
ReviewSource is the source of a lesson learned from reviewer's feedback on pull request number: review:12:alice. The repository is the memory's own Repo.
func SessionTitle ¶
SessionTitle is the one-line title a session is listed under.
Types ¶
type Actor ¶
type Actor struct {
// ID is the login on the surface the request came from (a forge login,
// a Slack user ID, an OIDC subject).
ID string `json:"id"`
Name string `json:"name,omitempty"`
Email string `json:"email,omitempty"`
// Trusted is true when the actor may trigger write actions: a
// maintainer of the repository, or a kōjō operator. Requests from
// anyone else are handled read-only (issue and PR text is data).
Trusted bool `json:"trusted"`
}
Actor is who asked for something.
type AlertRef ¶ added in v0.4.0
type AlertRef struct {
// Source is sentry.
Source string `json:"source"`
// IssueID is the source's ID of the issue.
IssueID string `json:"issue_id,omitempty"`
// ShortID is the issue's short name, such as FRONT-END-1F, when the
// source could be read.
ShortID string `json:"short_id,omitempty"`
URL string `json:"url,omitempty"`
Project string `json:"project,omitempty"`
Environment string `json:"environment,omitempty"`
// Title, Count and FirstSeen are the issue's when the alert came: what
// the pull request says of it.
Title string `json:"title,omitempty"`
Count int `json:"count,omitempty"`
FirstSeen time.Time `json:"first_seen,omitzero"`
// Delivery is the webhook delivery that started the session: the same
// delivery again starts nothing.
Delivery string `json:"delivery,omitempty"`
// Entry is the repos entry that took the alert: its project and
// environment, lowercased, as project/environment (project/ for an
// entry that names none). Its day is counted by it, whatever the case
// the events wrote.
Entry string `json:"entry,omitempty"`
}
AlertRef is the production alert a request came from (Sentry): the source's issue, which repeated alerts of one error share. Nothing is posted back to it.
type Approval ¶
type Approval struct {
ID string `json:"id"`
SessionID string `json:"session_id"`
// Kind is open_pr, merge, push, schedule or plan.
Kind string `json:"kind"`
Title string `json:"title"`
Text string `json:"text,omitempty"`
// Status is pending, approved, denied, or expired: nobody decided
// before the deadline. A plan's approval can also end in revise: a
// person asked for a revised plan instead.
Status string `json:"status"`
// DecidedBy is who clicked, or kojo for an approval that expired.
DecidedBy string `json:"decided_by,omitempty"`
Thread *ThreadRef `json:"thread,omitempty"`
MessageID string `json:"message_id,omitempty"`
CreatedAt time.Time `json:"created_at"`
DecidedAt time.Time `json:"decided_at,omitempty"`
// Deadline is when the approval expires without a decision. Zero
// means it waits until someone decides.
Deadline time.Time `json:"deadline,omitempty"`
}
Approval is a question waiting for a human: "Open PR?", "Merge?".
type AuditEntry ¶
type AuditEntry struct {
ID string `json:"id"`
At time.Time `json:"at"`
Actor string `json:"actor"`
SessionID string `json:"session_id,omitempty"`
// Action is a dotted verb: session.start, pr.open, config.activate,
// skill.draft.update, sandbox.exec, proxy.deny.
Action string `json:"action"`
Target string `json:"target,omitempty"`
Detail json.RawMessage `json:"detail,omitempty"`
}
AuditEntry is one line of the append-only audit log.
type AuditFilter ¶
type AuditFilter struct {
Actor string
SessionID string
// Action matches exactly, or as a prefix when it ends with ".".
Action string
Since time.Time
Until time.Time
Before string // entry ID, for paging
Limit int // default 100
}
AuditFilter narrows ListAudit.
type Campaign ¶ added in v0.4.0
type Campaign struct {
ID string `json:"id"`
Title string `json:"title"`
// Task is the request's text each session gets.
Task string `json:"task"`
// Skill runs one skill directly; empty lets the orchestrator choose.
Skill string `json:"skill,omitempty"`
// Inputs are handed to each session as POST /sessions inputs are.
Inputs map[string]string `json:"inputs,omitempty"`
// Selector is what the person asked for; Repos is what it resolved to
// when the campaign was created, sorted.
Selector CampaignSelector `json:"selector"`
Repos []string `json:"repos"`
// Skipped are the repositories the selector matched that cannot run
// the campaign, with the reason.
Skipped []CampaignSkip `json:"skipped,omitempty"`
// MaxParallel bounds the campaign's open sessions.
MaxParallel int `json:"max_parallel"`
// Pilot is how many repositories run first; the campaign then pauses
// for a person to look at their pull requests. 0 means no pilot.
Pilot int `json:"pilot"`
// PilotPassed is set when someone continued the campaign after its
// pilot.
PilotPassed bool `json:"pilot_passed,omitempty"`
// Status is pending, running, paused, done or cancelled; Paused says
// why a paused campaign is paused (pilot, cost or bound), and Problem
// what keeps the per-session budget from bounding a session (bound).
Status string `json:"status"`
Paused string `json:"paused,omitempty"`
Problem string `json:"problem,omitempty"`
// Estimate is the most the campaign can cost; MaxCostUSD is the bound
// the person confirmed (raised when continued after a cost pause).
Estimate CampaignEstimate `json:"estimate"`
MaxCostUSD float64 `json:"max_cost_usd,omitempty"`
// Items are the repositories' progress, in the order of Repos.
Items []CampaignItem `json:"items"`
// Author is who created the campaign (the actor ID their sessions
// carry), AuthorEmail their email when known.
Author string `json:"author"`
AuthorEmail string `json:"author_email,omitempty"`
ConfirmedBy string `json:"confirmed_by,omitempty"`
CreatedAt time.Time `json:"created_at"`
ConfirmedAt time.Time `json:"confirmed_at,omitzero"`
UpdatedAt time.Time `json:"updated_at"`
EndedAt time.Time `json:"ended_at,omitzero"`
}
Campaign is one task run as one session per repository: the same change across many repositories, at a bounded pace, after a person confirmed what it can cost.
type CampaignEstimate ¶ added in v0.4.0
type CampaignEstimate struct {
PerSessionUSD float64 `json:"per_session_usd"`
MaxCostUSD float64 `json:"max_cost_usd"`
// Problem says why the cost cannot be bounded (no per-session budget, a
// tier without a price). The campaign cannot be confirmed while it is
// set.
Problem string `json:"problem,omitempty"`
}
CampaignEstimate bounds what a campaign costs: each session stops at the per-session budget, so the repositories times that budget.
type CampaignFilter ¶ added in v0.4.0
type CampaignFilter struct {
Status string
// Before lists campaigns whose ID sorts before it, for paging.
Before string
Limit int // default 50
}
CampaignFilter narrows ListCampaigns.
type CampaignItem ¶ added in v0.4.0
type CampaignItem struct {
Repo string `json:"repo"`
// Sessions are the item's attempts, oldest first.
Sessions []string `json:"sessions,omitempty"`
State string `json:"state"`
Error string `json:"error,omitempty"`
// CostUSD is what the item's sessions that are over cost, added up
// as each ends: with the open sessions' cost, what the campaign spent.
CostUSD float64 `json:"cost_usd,omitempty"`
}
CampaignItem is one repository of a campaign.
func (*CampaignItem) Session ¶ added in v0.4.0
func (it *CampaignItem) Session() string
Session is the item's newest session, or "".
type CampaignRow ¶ added in v0.4.0
type CampaignRow struct {
Repo string `json:"repo"`
// Status is the newest session's status (queued, running, waiting,
// succeeded, failed, cancelled), or the item's state when that has no
// session (pending, failed, cancelled).
Status string `json:"status"`
SessionID string `json:"session_id,omitempty"`
CostUSD float64 `json:"cost_usd"`
// Outcome is the newest session's outcome (draft_pr_opened,
// no_change, ...).
Outcome string `json:"outcome,omitempty"`
PR *PullRequestLink `json:"pull_request,omitempty"`
// PRState is open, merged or closed, as the forge's events last said.
PRState string `json:"pr_state,omitempty"`
Attempts int `json:"attempts"`
Error string `json:"error,omitempty"`
}
CampaignRow is one repository of a campaign.
type CampaignSelector ¶ added in v0.4.0
type CampaignSelector struct {
Repos []string `json:"repos,omitempty"`
Team string `json:"team,omitempty"`
// Match is a path.Match pattern over repository IDs, such as
// github/acme/svc-*.
Match string `json:"match,omitempty"`
}
CampaignSelector chooses repositories: a list, a team's repositories and the enabled repositories matching a pattern, together.
type CampaignSkip ¶ added in v0.4.0
CampaignSkip is a repository the selector matched that the campaign leaves out.
type CampaignTotals ¶ added in v0.4.0
type CampaignTotals struct {
Repos int `json:"repos"`
// ByStatus counts the rows by Status (in a listing, the items by
// state).
ByStatus map[string]int `json:"by_status"`
// Over is how many repositories are done, failed or cancelled.
Over int `json:"over"`
SpentUSD float64 `json:"spent_usd"`
// Merged and Open count the campaign's pull requests by state.
Merged int `json:"merged"`
Open int `json:"open"`
}
CampaignTotals add up a campaign's repositories.
type CampaignView ¶ added in v0.4.0
type CampaignView struct {
Campaign
Rows []CampaignRow `json:"rows,omitempty"`
Totals CampaignTotals `json:"totals"`
}
CampaignView is a campaign with where each of its repositories stands, read from its sessions and pull requests when asked for, not stored twice (core.Engine.CampaignView).
type CapHold ¶ added in v0.3.0
type CapHold struct {
// Scope is repo, team or trigger; Name is the repository, the team or
// the trigger.
Scope string `json:"scope"`
Name string `json:"name"`
Running int `json:"running"`
Max int `json:"max_running"`
}
CapHold says which cap holds a session back.
type Caps ¶ added in v0.3.0
type Caps struct {
// Repos caps each repository, by forge/owner/name.
Repos map[string]int `json:"repos,omitempty"`
// Teams caps each team, by name; TeamOf names the team of each
// repository that belongs to one.
Teams map[string]int `json:"teams,omitempty"`
TeamOf map[string]string `json:"team_of,omitempty"`
// Triggers caps each trigger: the kind of request that started the
// session (eval, schedule, ...).
Triggers map[string]int `json:"triggers,omitempty"`
}
Caps bound how many sessions run at once (settings/limits). A queued or waiting session is not claimed while its repository, its repository's team or its trigger already has as many running sessions as its cap allows; it keeps its place in the queue. A missing entry, or a cap of 0, means no cap.
func (Caps) Blocked ¶ added in v0.3.0
func (c Caps) Blocked(counts []RunningCount) (repos, triggers []string)
Blocked returns the repositories and the triggers whose queued and waiting sessions may not start now: a store's claim skips them. It says the same as Hold, in a form a query can use. Neither slice is nil.
func (Caps) Hold ¶ added in v0.3.0
Hold returns the cap that keeps a session of this repository and trigger from starting now, or nil. The repository's cap is looked at first, then its team's, then the trigger's.
func (Caps) Tally ¶ added in v0.3.0
func (c Caps) Tally(counts []RunningCount) Running
Tally totals running counts with the caps' teams.
type CheckRef ¶
type CheckRef struct {
Name string `json:"name,omitempty"`
SHA string `json:"sha,omitempty"`
URL string `json:"url,omitempty"`
}
CheckRef names a failed check: its name, the commit it ran on and where the forge shows it. Its output is in the request's text.
type ConfigChange ¶
type ConfigChange struct {
Scope string `json:"scope"`
Object string `json:"object"`
RevisionID string `json:"revision_id"`
}
ConfigChange is sent to watchers when an object's active revision moves.
type EvalCase ¶
type EvalCase struct {
Name string `json:"name"`
Passed bool `json:"passed"`
Attempts int `json:"attempts"`
CostUSD float64 `json:"cost_usd"`
SessionID string `json:"session_id,omitempty"`
// Similarity is the diff similarity to the human fix, 0 to 1. Negative
// when the fixture has no reference fix.
Similarity float64 `json:"similarity"`
Detail string `json:"detail,omitempty"`
// History is set on a case of an eval from a repository's history.
History *HistoryCase `json:"history,omitempty"`
}
EvalCase is the result of one eval fixture.
type EvalRun ¶
type EvalRun struct {
ID string `json:"id"`
Skill string `json:"skill"`
// Revision, SHA or DraftID is the skill version evaluated.
Revision string `json:"revision,omitempty"`
SHA string `json:"sha,omitempty"`
DraftID string `json:"draft_id,omitempty"`
Models string `json:"models,omitempty"`
Cases []EvalCase `json:"cases"`
PassRate float64 `json:"pass_rate"`
CostUSD float64 `json:"cost_usd"`
// Status is running, done or failed; a history run is validating, then
// validated until someone confirms it, then running.
Status string `json:"status"`
Author string `json:"author,omitempty"`
Started time.Time `json:"started_at"`
Ended time.Time `json:"ended_at,omitempty"`
// History is set on an eval from a repository's own history instead of
// fixtures (history.go).
History *HistoryRun `json:"history,omitempty"`
}
EvalRun is one `kojo eval` of a skill.
type Evidence ¶
type Evidence struct {
// Ref is the short name the proposal's rationale cites: E1, E2, ...
Ref string `json:"ref"`
Kind string `json:"kind"`
// SessionID is the session whose result the critic rejected, or the one
// that opened the pull request.
SessionID string `json:"session_id,omitempty"`
// MemoryID is the lesson.
MemoryID string `json:"memory_id,omitempty"`
Repo string `json:"repo,omitempty"`
// Number is the pull request.
Number int `json:"number,omitempty"`
URL string `json:"url,omitempty"`
// Text is a short description of the item. It came from outside (a
// reviewer's words, a check's name): it is data.
Text string `json:"text,omitempty"`
At time.Time `json:"at,omitempty"`
}
Evidence is one thing a proposal is based on, with where to look it up.
type FileProvenance ¶
type FileProvenance struct {
// Path is relative to its repository.
Path string `json:"path"`
// Status is A (added), M (modified) or D (deleted).
Status string `json:"status"`
// Added are blocks of lines of the new version, by line number in it.
Added []LineBlock `json:"added,omitempty"`
// Removed are blocks of lines of the old version that were removed, by
// line number in the old version.
Removed []LineBlock `json:"removed,omitempty"`
// Last is the step whose snapshot last changed the file. It is what a
// file without line blocks (binary, or a mode change) is attributed to.
Last string `json:"last,omitempty"`
}
FileProvenance is the provenance of one changed file.
type FollowUp ¶
type FollowUp struct {
// Session is the session that opened the pull request.
Session string `json:"session"`
// Branch is the pull request's kojo/* branch, where the follow-up
// commits.
Branch string `json:"branch"`
// Trigger is mention or check_failed.
Trigger string `json:"trigger"`
// Check is the failed check a check_failed follow-up is about.
Check *CheckRef `json:"check,omitempty"`
// Thread is the chat thread of the session that opened the pull
// request: where the merge policy asks again when it asks.
Thread *ThreadRef `json:"thread,omitempty"`
}
FollowUp is what intake knew about a pull request kōjō opened when it queued a follow-up on it. The store's record of the pull request is how it was recognised, never the branch name alone.
type HistoryCase ¶
type HistoryCase struct {
State string `json:"state"`
Reason string `json:"reason,omitempty"`
// Issue is the issue the fix closed; PR is the fix.
Issue int `json:"issue"`
IssueTitle string `json:"issue_title,omitempty"`
IssueURL string `json:"issue_url,omitempty"`
PR int `json:"pr"`
PRTitle string `json:"pr_title,omitempty"`
PRURL string `json:"pr_url,omitempty"`
MergedAt time.Time `json:"merged_at,omitzero"`
// Cutoff: the forge tools of the case's session see nothing created at
// or after it (when the fix was opened).
Cutoff time.Time `json:"cutoff,omitzero"`
// FixSHA is the commit the fix was merged as, BaseSHA the commit before
// it the case runs at (found by the validation check), PRBaseSHA the
// pull request's base as the forge reported it.
FixSHA string `json:"fix_sha,omitempty"`
BaseSHA string `json:"base_sha,omitempty"`
PRBaseSHA string `json:"pr_base_sha,omitempty"`
// Tests and Code are the files the fix changed: the hidden tests and the
// rest.
Tests []string `json:"tests,omitempty"`
Code []string `json:"code,omitempty"`
// CheckSessionID is the session that validated the case; ScoreSessionID
// the one that ran the fix's tests on the result.
CheckSessionID string `json:"check_session_id,omitempty"`
ScoreSessionID string `json:"score_session_id,omitempty"`
// CriticPassed is the goal critic's verdict on the skill's result.
CriticPassed *bool `json:"critic_passed,omitempty"`
// Seconds is how long the skill's session took.
Seconds float64 `json:"seconds,omitempty"`
// Tests is the last run of the test command: on the result for a case
// that ran, else the run that made the case invalid.
TestRun *TestRun `json:"test_run,omitempty"`
}
HistoryCase is one issue of a history eval and what became of it.
type HistoryCheck ¶
type HistoryCheck struct {
// TestCmd is the operator's test command. It runs in the sandbox only.
TestCmd string `json:"test_cmd"`
// Tests and Code are the files the fix changed.
Tests []string `json:"tests"`
Code []string `json:"code"`
// ResultOf is the session whose change is scored.
ResultOf string `json:"result_of,omitempty"`
}
HistoryCheck is a check session of a history eval: it runs the operator's test command against the fix (validation, ResultOf empty) or against another session's change (scoring).
type HistoryEstimate ¶
type HistoryEstimate struct {
// Cases is how many cases would run: the valid ones.
Cases int `json:"cases"`
// PerSessionUSD is the per-session budget each case's session stops
// at; MaxCostUSD is Cases times it.
PerSessionUSD float64 `json:"per_session_usd"`
MaxCostUSD float64 `json:"max_cost_usd"`
// DailyCapUSD and SpentTodayUSD are the daily budget and what the
// install spent in the last 24 hours, when there is a daily budget.
DailyCapUSD float64 `json:"daily_cap_usd,omitempty"`
SpentTodayUSD float64 `json:"spent_today_usd,omitempty"`
// Problem says why the cost cannot be bounded (no per-session budget, a
// tier without a price). The run cannot be confirmed while it is set.
Problem string `json:"problem,omitempty"`
}
HistoryEstimate bounds what running the valid cases costs.
type HistoryOutcome ¶
type HistoryOutcome struct {
// BaseSHA is the commit before the fix the check settled on.
BaseSHA string `json:"base_sha,omitempty"`
// Runs are the runs of the test command, in order.
Runs []TestRun `json:"runs,omitempty"`
}
HistoryOutcome is what a history check found.
type HistoryRequest ¶
type HistoryRequest struct {
// FixPR is the pull request that fixed the issue (the request's
// Number) and FixSHA the commit it was merged as.
FixPR int `json:"fix_pr"`
FixSHA string `json:"fix_sha"`
// BaseSHA is the commit before the fix. The check that validates a case
// leaves it empty and works it out; PRBaseSHA, the pull request's base,
// is its fallback.
BaseSHA string `json:"base_sha,omitempty"`
PRBaseSHA string `json:"pr_base_sha,omitempty"`
// Cutoff: the forge tools show nothing created at or after it.
Cutoff time.Time `json:"cutoff"`
// Check, when set, makes the session a check that calls no model.
Check *HistoryCheck `json:"check,omitempty"`
}
HistoryRequest is what a session of a history eval needs. The workspace is cloned at BaseSHA with nothing after it, the forge leaves the sandbox's egress once the clone is done, and the forge tools see the repository as it was at Cutoff, without the fix's pull request.
type HistoryRun ¶
type HistoryRun struct {
// Repo is forge/owner/name.
Repo string `json:"repo"`
// TestCmd is the operator's test command: trusted input, run only in
// sandboxes, with the fix's test files in KOJO_HIDDEN_TESTS.
TestCmd string `json:"test_cmd"`
// Limit is the most cases the run takes.
Limit int `json:"limit"`
// Since: only pull requests merged at or after it are mined.
Since time.Time `json:"since"`
// Scanned counts the merged pull requests mining looked at; Skipped
// lists those it left out, with the reason.
Scanned int `json:"scanned"`
Skipped []HistorySkip `json:"skipped,omitempty"`
// Estimate is the cost bound reported once the cases are validated.
Estimate *HistoryEstimate `json:"estimate,omitempty"`
// ConfirmedBy and ConfirmedAt record who started the model runs.
ConfirmedBy string `json:"confirmed_by,omitempty"`
ConfirmedAt time.Time `json:"confirmed_at,omitzero"`
// Error is why the run stopped before its cases ran.
Error string `json:"error,omitempty"`
}
HistoryRun is what an eval from a repository's history was asked for and what it found before any model ran.
type HistorySkip ¶
type HistorySkip struct {
PR int `json:"pr"`
Title string `json:"title,omitempty"`
URL string `json:"url,omitempty"`
Reason string `json:"reason"`
}
HistorySkip is a merged pull request mining left out.
type IDLocks ¶ added in v0.4.0
type IDLocks struct {
// contains filtered or unexported fields
}
IDLocks holds one lock per ID, so a store can run the updates of one record one at a time while updates of other records go on. A lock that nobody holds or waits for is forgotten. The zero value is ready to use.
type LineBlock ¶
type LineBlock struct {
Start int `json:"start"`
// End is the last line of the block, inclusive.
End int `json:"end"`
// Step is the step's ID; empty when no recorded tool call wrote the
// lines (a kit's setup, a check of the goal critic).
Step string `json:"step,omitempty"`
}
LineBlock is a run of consecutive lines one step wrote, or removed.
type Memory ¶
type Memory struct {
ID string `json:"id"`
// Repo scopes the memory. Empty means org-wide for a team memory, and
// "wherever the person asks" for a personal one.
Repo string `json:"repo,omitempty"`
// Person is the key of the person the memory belongs to (PersonKey).
// Empty means it is the team's. A personal memory is only ever read in
// that person's own sessions and by that person.
Person string `json:"person,omitempty"`
Topic string `json:"topic,omitempty"`
// Skill is the skill the memory is about, when it is about one: the
// skill a learned lesson concerns.
Skill string `json:"skill,omitempty"`
// Source says where the memory came from: seed, session:<id>,
// user:<email>, or review:<pr number>:<reviewer> for a lesson learned
// from a review (ReviewSource).
Source string `json:"source,omitempty"`
// URL links to what the memory was learned from (the review comment).
URL string `json:"url,omitempty"`
Content string `json:"content"`
Embedding []float32 `json:"-"`
CreatedAt time.Time `json:"created_at"`
// Score is set by SearchMemory: higher is closer.
Score float64 `json:"score,omitempty"`
}
Memory is one thing kōjō remembers. It belongs to the team (a repository or the whole org), or to one person when Person is set.
type MemoryFilter ¶
type MemoryFilter struct {
// Repo lists the memories of one repository. Empty means every
// repository and the org-wide ones.
Repo string
// Person and PersonOnly work as in MemoryQuery.
Person string
PersonOnly bool
// Skill lists the memories about one skill.
Skill string
// Source matches exactly, or as a prefix when it ends with ":":
// "review:" lists every lesson learned from a review.
Source string
Limit int // default 100
}
MemoryFilter narrows ListMemory. The zero filter lists team memory.
func Lessons ¶
func Lessons(repo, skill string) MemoryFilter
Lessons is the filter for the lessons learned from reviews for one skill in one repository. An empty skill lists the repository's lessons for every skill.
type MemoryQuery ¶
type MemoryQuery struct {
// Repo limits the search to a repository's memories plus org-wide ones.
Repo string
// Person adds one person's memories to the team's. Nobody else's
// personal memories are ever returned, and with an empty Person none
// are.
Person string
// PersonOnly leaves the team's memories out. It needs Person.
PersonOnly bool
Text string
Embedding []float32
K int // default 5
}
MemoryQuery searches memory. With an Embedding the search is by cosine similarity; otherwise by full-text match on Text.
type Plan ¶ added in v0.3.0
type Plan struct {
// Skill is the skill the work was about to run, and Task what it was
// asked to do.
Skill string `json:"skill"`
Task string `json:"task,omitempty"`
// Why says what asked for a plan: the request, the label on the issue
// or pull request, or settings/plan.
Why string `json:"why"`
// Approach is how the work will go; Files the files likely to change;
// Risks what could go wrong; Tests the tests it will add or run;
// NotDoing what it will leave alone.
Approach string `json:"approach"`
Files []string `json:"files,omitempty"`
Risks []string `json:"risks,omitempty"`
Tests []string `json:"tests,omitempty"`
NotDoing []string `json:"not_doing,omitempty"`
// Estimate is a rough cost of the work, when one could be had.
Estimate *PlanEstimate `json:"estimate,omitempty"`
// Revision counts the revised plans: 0 for the first one.
Revision int `json:"revision"`
MaxRevisions int `json:"max_revisions"`
// CostUSD is what writing the plans cost, revisions included. It is
// part of the session's cost.
CostUSD float64 `json:"cost_usd"`
// Status is pending, revising, approved, declined or expired.
Status string `json:"status"`
// ApprovalID is the approval the plan waits on; Deadline when it closes
// without an answer; URL the comment or thread it was posted to.
ApprovalID string `json:"approval_id,omitempty"`
Deadline time.Time `json:"deadline,omitempty"`
URL string `json:"url,omitempty"`
// DecidedBy is who approved or declined it, kojo when it expired or
// ran out of revisions; Reason says why it ended without approval.
DecidedBy string `json:"decided_by,omitempty"`
DecidedAt time.Time `json:"decided_at,omitempty"`
Reason string `json:"reason,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
Plan is what a session means to do before it changes code: written by one model call that read the repository, posted where the request came from, and approved by a person before any skill that changes the workspace runs. Its text was written by a model from data that came from outside: it is shown as data, never followed as instructions.
type PlanEstimate ¶ added in v0.3.0
type PlanEstimate struct {
// TypicalUSD is the median cost of Samples recent sessions that ran
// the skill; zero when there were none.
TypicalUSD float64 `json:"typical_usd,omitempty"`
Samples int `json:"samples,omitempty"`
// CapUSD is the per-session budget: the session stops there.
CapUSD float64 `json:"cap_usd,omitempty"`
}
PlanEstimate is a rough cost of a plan's work: what recent sessions of the same skill cost, and the session's budget.
type Proposal ¶
type Proposal struct {
ID string `json:"id"`
// Scope is org or repo:<forge/owner/name>; Skill is the skill's name.
Scope string `json:"scope"`
Skill string `json:"skill"`
Status string `json:"status"`
// Trigger is schedule (the periodic check) or manual; RequestedBy is
// who started a manual one.
Trigger string `json:"trigger,omitempty"`
RequestedBy string `json:"requested_by,omitempty"`
// SessionID is the session that writes and measures the proposal.
SessionID string `json:"session_id,omitempty"`
// DraftID is the proposal's draft, while it has one: from the moment
// it is written until it is approved, rejected or closed.
DraftID string `json:"draft_id,omitempty"`
// BaseRevision or BaseSHA is the version in use the proposal was
// written against; BaseFiles are that version's files and Files the
// proposed ones, kept so a closed proposal can still be read.
BaseRevision string `json:"base_revision,omitempty"`
BaseSHA string `json:"base_sha,omitempty"`
BaseFiles map[string]string `json:"base_files,omitempty"`
Files map[string]string `json:"files,omitempty"`
// Summary says in a sentence or two what the proposal changes.
Summary string `json:"summary,omitempty"`
Rationale []ProposalChange `json:"rationale,omitempty"`
Evidence []Evidence `json:"evidence,omitempty"`
// Loosens lists every way the proposed goals are easier to meet than
// the ones in use, found by comparing the two. The approver sees it
// next to the diff.
Loosens []string `json:"loosens,omitempty"`
// Refused lists why the proposal was refused: what it tried to widen,
// or how it failed validation.
Refused []string `json:"refused,omitempty"`
// Measured is false when the skill has no eval fixtures: there was
// nothing to measure the proposal against.
Measured bool `json:"measured"`
// EvalRunID is the eval of the proposal and BaselineRunID the eval of
// the version in use it is compared with.
EvalRunID string `json:"eval_run_id,omitempty"`
BaselineRunID string `json:"baseline_run_id,omitempty"`
PassRate float64 `json:"pass_rate"`
BaselinePassRate float64 `json:"baseline_pass_rate"`
// Note says how the proposal ended, or what a person should know
// before deciding.
Note string `json:"note,omitempty"`
// EditedBy is the last person who changed the proposal's draft.
EditedBy string `json:"edited_by,omitempty"`
// Editors are everyone who changed the proposal's draft, in the order
// they first did. With require_second_reviewer none of them may
// approve it.
Editors []string `json:"editors,omitempty"`
// DecidedBy approved or rejected it; Reason is why it was rejected.
DecidedBy string `json:"decided_by,omitempty"`
Reason string `json:"reason,omitempty"`
// Version increases with every write; an update must name the version
// it read.
Version int `json:"version"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ClosedAt time.Time `json:"closed_at,omitempty"`
}
Proposal is a change to a skill that kōjō proposed from evidence. It is the record of the whole attempt: it exists from the moment the work is queued and stays after the draft is gone, so a rejected change is remembered. Only a person makes a proposal the skill in use.
type ProposalChange ¶
type ProposalChange struct {
Change string `json:"change"`
// Evidence are the Refs of the items the change answers. Empty means
// the proposal gave no known item for it.
Evidence []string `json:"evidence,omitempty"`
}
ProposalChange is one change a proposal makes and the evidence it cites.
type ProposalFilter ¶
type ProposalFilter struct {
Scope string
Skill string
// Open lists only the proposals that are not final.
Open bool
Limit int // default 100
}
ProposalFilter narrows ListProposals.
type Provenance ¶
type Provenance struct {
// Missing says why provenance could not be computed. The session's
// change is published either way.
Missing string `json:"missing,omitempty"`
// Repos has one entry per repository that changed: the session's own
// first, then its linked repositories.
Repos []RepoProvenance `json:"repos,omitempty"`
// Steps describes the steps the blocks name, by step ID.
Steps map[string]ProvenanceStep `json:"steps,omitempty"`
// Truncated is set when there were more blocks than are kept; the
// files past the limit have no blocks.
Truncated bool `json:"truncated,omitempty"`
}
Provenance links each block of a session's changed lines to the step of the session that wrote it. It is computed in the sandbox from snapshots the core records after each tool call that can change the workspace, and is an aid for review: it says which step last wrote a line, as the session's own sandbox reported it.
type ProvenanceStep ¶
type ProvenanceStep struct {
// Seq is the step's number in the session's replay.
Seq int `json:"seq"`
// Tool is the tool call: write_file, edit_file or exec.
Tool string `json:"tool"`
// Skill is the skill whose subagent made the call.
Skill string `json:"skill,omitempty"`
// Intent is a short line on why: the purpose the call gave, the
// model's own text with the call, or what the call did. Plain text,
// bounded.
Intent string `json:"intent,omitempty"`
}
ProvenanceStep is what a provenance block says about its step.
type PullRequest ¶
type PullRequest struct {
Repo string `json:"repo"`
Number int `json:"number"`
SessionID string `json:"session_id,omitempty"`
// Skill is the skill whose change the pull request carries: the last
// skill of the session that changed files. Skills lists all of them.
Skill string `json:"skill,omitempty"`
Skills []string `json:"skills,omitempty"`
Branch string `json:"branch,omitempty"`
URL string `json:"url,omitempty"`
// State is open, merged or closed.
State string `json:"state"`
// HumanEdited is true once someone other than kōjō pushed commits to
// the pull request's branch.
HumanEdited bool `json:"human_edited"`
OpenedAt time.Time `json:"opened_at"`
ClosedAt time.Time `json:"closed_at,omitempty"`
UpdatedAt time.Time `json:"updated_at"`
}
PullRequest is a pull request a session opened, and what became of it after the session ended.
type PullRequestFilter ¶
type PullRequestFilter struct {
Repo string
// Since lists pull requests opened at or after it.
Since time.Time
Limit int // default 500
}
PullRequestFilter narrows ListPullRequests.
type PullRequestLink ¶
type PullRequestLink struct {
// Repo is forge/owner/name.
Repo string `json:"repo"`
Number int `json:"number"`
URL string `json:"url,omitempty"`
Branch string `json:"branch,omitempty"`
Draft bool `json:"draft,omitempty"`
}
PullRequestLink is one pull request a session opened.
type RepoProvenance ¶
type RepoProvenance struct {
// Repo is forge/owner/name; empty for a session without a forge.
Repo string `json:"repo,omitempty"`
// Dir is where the repository is in the workspace: empty for the
// session's own, .kojo/linked/<name> for a linked one. The session's
// diff names a linked repository's files with this prefix.
Dir string `json:"dir,omitempty"`
// Missing says why this repository has no provenance.
Missing string `json:"missing,omitempty"`
Files []FileProvenance `json:"files,omitempty"`
}
RepoProvenance is the provenance of one repository's change.
type Request ¶
type Request struct {
ID string `json:"id"`
// Surface is github, gitlab, forgejo, slack, cli, mcp, dashboard or
// schedule.
Surface string `json:"surface"`
Kind string `json:"kind"`
Actor Actor `json:"actor"`
// Repo is forge/owner/name. Empty for a chat request that names none.
Repo string `json:"repo,omitempty"`
// Number is the issue or pull request the request is about.
Number int `json:"number,omitempty"`
IsPR bool `json:"is_pr,omitempty"`
Title string `json:"title,omitempty"`
// Text is what was asked, verbatim. It is data, never instructions with
// more authority than its Actor has.
Text string `json:"text"`
// Skill asks for one skill directly (schedules, `kojo run --skill`).
Skill string `json:"skill,omitempty"`
// Thread is the chat thread, when the request came from chat.
Thread *ThreadRef `json:"thread,omitempty"`
// Ticket is the issue tracker's ticket, when the request came from
// one (Linear, Jira, Asana).
Ticket *TicketRef `json:"ticket,omitempty"`
CommentID string `json:"comment_id,omitempty"`
Ref string `json:"ref,omitempty"`
SHA string `json:"sha,omitempty"`
// Alert is the production alert, when the request came from one
// (Sentry).
Alert *AlertRef `json:"alert,omitempty"`
// DryRun runs the session without pushing or commenting anywhere
// (skill tests from the dashboard, evals).
DryRun bool `json:"dry_run,omitempty"`
// DraftID runs a skill draft instead of the active revision. Only
// DryRun requests may carry one: drafts never run in real sessions.
DraftID string `json:"draft_id,omitempty"`
// Inputs are named values handed to the skill (eval fixtures).
Inputs map[string]string `json:"inputs,omitempty"`
// Review says what a feedback request's text was written on.
Review *ReviewContext `json:"review,omitempty"`
// ProposalID is the proposal an improve request works on.
ProposalID string `json:"proposal_id,omitempty"`
// History marks a session of an eval from a repository's own history
// (kojo eval --history). Such a request is always a dry run.
History *HistoryRequest `json:"history,omitempty"`
// FollowUp marks a request that continues one of kōjō's own pull
// requests (Number, IsPR): its session works on the pull request's
// branch and adds commits to it instead of opening another pull
// request.
FollowUp *FollowUp `json:"follow_up,omitempty"`
// Confidential marks a request whose text the surface keeps from
// people outside the project (a GitLab confidential issue or internal
// note). Its session never gets a shareable report.
Confidential bool `json:"confidential,omitempty"`
// Plan asks the session to write a plan and wait for a person's
// go-ahead before a skill that changes code runs (kojo run --plan).
Plan bool `json:"plan,omitempty"`
// Campaign is the campaign whose session this is, for one of its
// repositories.
Campaign string `json:"campaign,omitempty"`
// DedupeKey makes Enqueue idempotent (the forge's delivery ID).
DedupeKey string `json:"dedupe_key,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
Request is the one shape every surface normalizes into: who, where, what, and the thread to answer in.
type ReviewContext ¶
type ReviewContext struct {
// Kind is pr_comment, pr_review or pr_review_comment.
Kind string `json:"kind"`
// State is the verdict of a review: approved, changes_requested or
// commented.
State string `json:"state,omitempty"`
Path string `json:"path,omitempty"`
Line int `json:"line,omitempty"`
DiffHunk string `json:"diff_hunk,omitempty"`
URL string `json:"url,omitempty"`
}
ReviewContext is where a piece of review feedback was written: which kind of comment it is and, for a comment on a line, the file and the diff around it. All of it came from the forge and is data.
type Revision ¶
type Revision struct {
ID string `json:"id"`
// Scope is org or repo:<forge/owner/name>.
Scope string `json:"scope"`
// Object is what the revision configures: settings/models, schedules,
// rbac, skill/fix-bug.
Object string `json:"object"`
Content json.RawMessage `json:"content"`
Author string `json:"author"`
// ParentID is the revision that was active when this one was written.
ParentID string `json:"parent_id,omitempty"`
Message string `json:"message,omitempty"`
CreatedAt time.Time `json:"created_at"`
Active bool `json:"active"`
}
Revision is one version of one day-2 config object. Revisions are never changed or deleted; activating one moves the object's active pointer.
type Risk ¶
type Risk struct {
Score float64 `json:"score"` // 0 (safe) to 1 (risky)
Level string `json:"level"` // low, medium, high
Reasons []string `json:"reasons,omitempty"`
}
Risk is the merge policy's assessment of a change.
type Running ¶ added in v0.3.0
Running is the running sessions, totalled per repository, team and trigger.
type RunningCount ¶ added in v0.3.0
type RunningCount struct {
Repo string `json:"repo"`
Trigger string `json:"trigger"`
N int `json:"n"`
}
RunningCount is how many sessions of one repository and one trigger are running.
func CountRunning ¶ added in v0.3.0
func CountRunning(sessions []Session) []RunningCount
CountRunning counts running sessions by repository and trigger.
type ScheduleState ¶
type ScheduleState struct {
// Key is scope + "/" + schedule name.
Key string `json:"key"`
LastRun time.Time `json:"last_run,omitempty"`
LastSession string `json:"last_session,omitempty"`
}
ScheduleState is when a schedule last ran. The schedule's definition is a config object; only its run state lives here.
type Session ¶
type Session struct {
ID string `json:"id"`
RequestID string `json:"request_id"`
Request Request `json:"request"`
Status SessionStatus `json:"status"`
// Repo, Surface and Trigger are copied from the request for listing.
Repo string `json:"repo,omitempty"`
Surface string `json:"surface"`
Trigger string `json:"trigger"`
Title string `json:"title,omitempty"`
Actor string `json:"actor,omitempty"`
CostUSD float64 `json:"cost_usd"`
TokensIn int64 `json:"tokens_in"`
TokensOut int64 `json:"tokens_out"`
// Revisions are the config revision IDs in effect when the session
// started, by "scope/object". In-flight sessions keep them.
Revisions map[string]string `json:"revisions,omitempty"`
// SkillSHAs are the git commits of git-backed skills the session used.
SkillSHAs map[string]string `json:"skill_shas,omitempty"`
// Sandboxes are the sandbox IDs the session owns.
Sandboxes []string `json:"sandboxes,omitempty"`
Result *SessionResult `json:"result,omitempty"`
Error string `json:"error,omitempty"`
// Checkpoint is the orchestrator's state after its last completed step.
Checkpoint json.RawMessage `json:"checkpoint,omitempty"`
// Queue fields.
Attempts int `json:"attempts"`
RunAfter time.Time `json:"run_after"`
LockedBy string `json:"locked_by,omitempty"`
LockedUntil time.Time `json:"locked_until,omitempty"`
// CancelRequested asks the worker running the session to stop.
CancelRequested bool `json:"cancel_requested,omitempty"`
CreatedAt time.Time `json:"created_at"`
StartedAt time.Time `json:"started_at,omitempty"`
EndedAt time.Time `json:"ended_at,omitempty"`
UpdatedAt time.Time `json:"updated_at"`
}
Session is one unit of work: a request being handled by the orchestrator. It is also the queue entry workers claim.
func (*Session) TakesMessages ¶
TakesMessages reports whether a session in this state may be given a message: queued or running, and not asked to stop.
type SessionFilter ¶
type SessionFilter struct {
Status SessionStatus
Repo string
Surface string
Since time.Time
// Before is a session ID: list sessions older than it (paging).
Before string
Limit int // default 50
// ExcludeTriggers leaves out the sessions started by these triggers
// (request kinds), such as "eval": the dashboard's session list hides
// the many sessions an eval run starts unless asked for them.
ExcludeTriggers []string
// Open lists only sessions that are not over: queued, running or
// waiting.
Open bool
// Number lists the sessions about one issue (IsPR false) or pull
// request (IsPR true) of Repo.
Number int
IsPR bool
// Thread lists the sessions whose request came from one chat thread.
Thread *ThreadRef
// Ticket lists the sessions whose request came from one ticket of an
// issue tracker (its Tracker and ID).
Ticket *TicketRef
// Alert lists the sessions whose request came from a production alert
// of Alert.Source: of one issue, project or environment when Alert
// names it.
Alert *AlertRef
// Campaign lists the sessions of one campaign.
Campaign string
// DedupeKey lists the session whose request has this dedupe key
// (unique, so at most one).
DedupeKey string
// WithoutDiff leaves each result's Diff and Provenance out, the
// large part of a session, for listings that do not show them:
// Postgres does not send them.
WithoutDiff bool
}
SessionFilter narrows ListSessions.
func (SessionFilter) Match ¶
func (f SessionFilter) Match(s *Session) bool
Match reports whether a session passes the filter's Open, Number, Thread, Ticket, Alert, Campaign and DedupeKey conditions: the part of the filter both stores read from the request.
type SessionMessage ¶
type SessionMessage struct {
ID string `json:"id"`
SessionID string `json:"session_id"`
// Seq orders a session's messages, from 1.
Seq int `json:"seq"`
// Surface is where it was written: github, gitlab, forgejo, slack,
// mattermost, discord, teams, linear, jira, asana, dashboard, cli or
// mcp.
Surface string `json:"surface"`
Author Actor `json:"author"`
Text string `json:"text"`
// Number and IsPR are the issue or pull request a forge comment was
// written on, CommentID and URL the comment itself; Thread is the chat
// thread a chat message was written in; Ticket is the tracker's ticket
// a comment was written on.
Number int `json:"number,omitempty"`
IsPR bool `json:"is_pr,omitempty"`
CommentID string `json:"comment_id,omitempty"`
URL string `json:"url,omitempty"`
Thread *ThreadRef `json:"thread,omitempty"`
Ticket *TicketRef `json:"ticket,omitempty"`
// Status is pending, delivered or unread.
Status string `json:"status"`
// DeliveredTo is the model call that read it first: orchestrator, or
// subagent:<skill>.
DeliveredTo string `json:"delivered_to,omitempty"`
// DedupeKey makes AddSessionMessage idempotent (a webhook or chat event
// delivered twice). It is written once and not read back.
DedupeKey string `json:"-"`
CreatedAt time.Time `json:"created_at"`
DeliveredAt time.Time `json:"delivered_at,omitempty"`
}
SessionMessage is something a person told a session while it worked: a mention on its issue or pull request, a message in its chat thread, or a message sent from the dashboard, the API, MCP or the CLI. Its text came from outside: it is data, and reaches a model only inside the untrusted fence, as guidance that cannot change the skill's goals or limits.
type SessionResult ¶
type SessionResult struct {
// Outcome is pr_opened, draft_pr_opened, commented, merged, no_change,
// or failed_with_report.
Outcome string `json:"outcome"`
Summary string `json:"summary,omitempty"`
// Report is the critic's report, in Markdown.
Report string `json:"report,omitempty"`
// Branch, PRNumber and PRURL are the session's primary pull request:
// the one on its own repository, or, when only linked repositories
// changed, the first of theirs.
Branch string `json:"branch,omitempty"`
PRNumber int `json:"pr_number,omitempty"`
PRURL string `json:"pr_url,omitempty"`
// PullRequests are all the pull requests the session opened, one per
// repository that changed, the primary one first.
PullRequests []PullRequestLink `json:"pull_requests,omitempty"`
URL string `json:"url,omitempty"` // comment or thread
// Diff is the unified diff the session produced, published or not: a
// dry run keeps it here instead of pushing it.
Diff string `json:"diff,omitempty"`
// Risk is the merge policy's score and the rules that fired.
Risk *Risk `json:"risk,omitempty"`
// Approval is how the question the merge policy asked in chat ended:
// approved, denied, or expired when nobody answered before its
// deadline.
Approval string `json:"approval,omitempty"`
// Outputs are the values subagents declared (REPRO_TEST, ...).
Outputs map[string]string `json:"outputs,omitempty"`
// Passed is the goal critic's final verdict over every delegated skill.
Passed bool `json:"passed"`
// Provenance says which step of the session wrote each block of changed
// lines (provenance.go).
Provenance *Provenance `json:"provenance,omitempty"`
// History is what a check of a history eval found.
History *HistoryOutcome `json:"history,omitempty"`
// Round is the number of a follow-up session among the follow-ups of
// its pull request, from 1, and Commit the commit it added to the pull
// request's branch.
Round int `json:"round,omitempty"`
Commit string `json:"commit,omitempty"`
// Plan is the plan the session wrote before it changed code, and what
// became of it. It is set while the session waits for the go-ahead.
Plan *Plan `json:"plan,omitempty"`
}
SessionResult is what a session produced.
type SessionStatus ¶
type SessionStatus string
SessionStatus is where a session is in its life.
const ( SessionQueued SessionStatus = "queued" SessionRunning SessionStatus = "running" SessionWaiting SessionStatus = "waiting" // on a human approval SessionSucceeded SessionStatus = "succeeded" SessionFailed SessionStatus = "failed" SessionCancelled SessionStatus = "cancelled" )
Session statuses.
func (SessionStatus) Terminal ¶
func (s SessionStatus) Terminal() bool
Terminal reports whether the session is over.
type SkillDraft ¶
type SkillDraft struct {
ID string `json:"id"`
Scope string `json:"scope"`
Name string `json:"name"`
// BaseRevision or BaseSHA is what the draft was started from.
BaseRevision string `json:"base_revision,omitempty"`
BaseSHA string `json:"base_sha,omitempty"`
// Files are the skill's files by name: SKILL.md, goals.yaml, kit.yaml.
Files map[string]string `json:"files"`
Author string `json:"author"`
// Editors are everyone who wrote the draft's content: its author, then
// each person who saved its files, in the order they first did. With
// require_second_reviewer none of them may activate it. A draft saved
// before editors were kept has only Author to go by.
Editors []string `json:"editors,omitempty"`
// Version increases with every save; an update must name the version
// it edited.
Version int `json:"version"`
// Tests are the IDs of dry-run sessions run against the draft.
Tests []string `json:"tests,omitempty"`
// EvalRunID is the latest eval run of the draft.
EvalRunID string `json:"eval_run_id,omitempty"`
// ProposalID is set on a draft kōjō wrote itself (Author is
// ProposalAuthor): the proposal that holds its rationale, its evidence
// and what it loosens. It is set when the draft is created and never
// changes.
ProposalID string `json:"proposal_id,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
SkillDraft is an unpublished edit of a skill. Drafts never run in real sessions.
type SkillIndexEntry ¶
type SkillIndexEntry struct {
Repo string `json:"repo"`
Name string `json:"name"`
// Layer is repo, org or builtin.
Layer string `json:"layer"`
// Revision (dashboard-backed) or SHA (git-backed) identifies the
// version.
Revision string `json:"revision,omitempty"`
SHA string `json:"sha,omitempty"`
Description string `json:"description,omitempty"`
// Overrides lists the layers this entry shadows.
Overrides []string `json:"overrides,omitempty"`
UpdatedAt time.Time `json:"updated_at"`
}
SkillIndexEntry records which skill a repository resolves a name to.
type Step ¶
type Step struct {
ID string `json:"id"`
SessionID string `json:"session_id"`
Seq int `json:"seq"`
ParentID string `json:"parent_id,omitempty"`
Kind StepKind `json:"kind"`
Name string `json:"name"`
Status string `json:"status"` // running, ok, failed
Input json.RawMessage `json:"input,omitempty"`
Output json.RawMessage `json:"output,omitempty"`
Error string `json:"error,omitempty"`
Model string `json:"model,omitempty"`
TokensIn int64 `json:"tokens_in,omitempty"`
TokensOut int64 `json:"tokens_out,omitempty"`
CostUSD float64 `json:"cost_usd,omitempty"`
StartedAt time.Time `json:"started_at"`
EndedAt time.Time `json:"ended_at,omitempty"`
}
Step is one recorded action of a session. Steps are append-only and form a tree through ParentID.
type StepKind ¶
type StepKind string
StepKind is the kind of a recorded step.
const ( StepOrchestrator StepKind = "orchestrator" // a model turn of the orchestrator StepSubagent StepKind = "subagent" // one delegated skill run StepModel StepKind = "model" // a model turn of a subagent StepTool StepKind = "tool" // a tool call StepExec StepKind = "exec" // a sandbox command StepCritic StepKind = "critic" // a goal critic verdict StepMerge StepKind = "merge" // the merge policy decision StepSurface StepKind = "surface" // a comment, message or PR StepSandbox StepKind = "sandbox" // sandbox created or destroyed StepMessage StepKind = "message" // a person's message read by a model of the session StepPlan StepKind = "plan" // the plan written before code changes )
Step kinds, the vocabulary of session replay.
type Store ¶
type Store interface {
// Enqueue stores a request and a queued session for it. It returns
// ErrDuplicate when the request's DedupeKey was seen before.
Enqueue(ctx context.Context, req Request) (*Session, error)
// Claim hands one runnable session to a worker and locks it for lease:
// a queued session whose RunAfter has passed, a waiting one whose
// RunAfter (the deadline of what it waits for) has passed, or a running
// one whose lock expired (its worker died). It returns nil when there is
// none.
Claim(ctx context.Context, worker string, lease time.Duration) (*Session, error)
// ClaimWithin is Claim with caps on running sessions: it skips a queued
// or waiting session whose repository, team or trigger is at its cap,
// which keeps its place in the queue. A running session whose lock
// expired is taken back whatever the caps say: it already counts as
// running. Claims by any number of workers and replicas at once never
// start more sessions than a cap allows.
ClaimWithin(ctx context.Context, worker string, lease time.Duration, caps Caps) (*Session, error)
// Heartbeat extends a worker's lock. It returns ErrConflict when the
// worker no longer holds it.
Heartbeat(ctx context.Context, sessionID, worker string, lease time.Duration) error
// Release ends a worker's hold: the session moves to status. A queued
// session is claimable again at runAfter; a waiting one at runAfter, or
// as soon as its approval is decided. A zero runAfter means now.
Release(ctx context.Context, sessionID, worker string, status SessionStatus, runAfter time.Time) error
GetSession(ctx context.Context, id string) (*Session, error)
ListSessions(ctx context.Context, f SessionFilter) ([]Session, error)
// UpdateSession writes the mutable fields of a session: status, result,
// error, checkpoint, costs, revisions, sandboxes, timestamps.
UpdateSession(ctx context.Context, s *Session) error
// RequestCancel flags a session for cancellation. A queued or waiting
// session is cancelled at once.
RequestCancel(ctx context.Context, id string) error
// SpendSince sums the model cost of every step started since t.
SpendSince(ctx context.Context, t time.Time) (float64, error)
// SpendByRepo sums the model cost of the steps started in [from, to) by
// the repository of their session, "" for sessions without one. A zero
// to means up to now.
SpendByRepo(ctx context.Context, from, to time.Time) (map[string]float64, error)
// AppendStep stores a step and assigns its Seq.
AppendStep(ctx context.Context, st *Step) error
// UpdateStep writes a step's status, output, error, usage and end time.
UpdateStep(ctx context.Context, st *Step) error
ListSteps(ctx context.Context, sessionID string) ([]Step, error)
AppendAudit(ctx context.Context, e AuditEntry) error
ListAudit(ctx context.Context, f AuditFilter) ([]AuditEntry, error)
// PutRevision stores a new revision of (Scope, Object) and, when
// activate is set, makes it the active one.
PutRevision(ctx context.Context, r Revision, activate bool) (*Revision, error)
// ActivateRevision moves an object's active pointer to an existing
// revision: that is a rollback.
ActivateRevision(ctx context.Context, id string) (*Revision, error)
GetRevision(ctx context.Context, id string) (*Revision, error)
// ActiveRevision returns the active revision of an object, or
// ErrNotFound.
ActiveRevision(ctx context.Context, scope, object string) (*Revision, error)
// ActiveRevisions returns every active revision of a scope. An empty
// scope means every scope.
ActiveRevisions(ctx context.Context, scope string) ([]Revision, error)
// ListRevisions returns an object's history, newest first. An empty
// object lists the whole scope.
ListRevisions(ctx context.Context, scope, object string, limit int) ([]Revision, error)
// WatchConfig delivers a ConfigChange for every activation, from any
// replica, until ctx ends.
WatchConfig(ctx context.Context) (<-chan ConfigChange, error)
// PutDraft creates a draft (empty ID) or updates one. An update whose
// Version is not the stored one returns ErrConflict.
PutDraft(ctx context.Context, d *SkillDraft) error
GetDraft(ctx context.Context, id string) (*SkillDraft, error)
ListDrafts(ctx context.Context, scope string) ([]SkillDraft, error)
DeleteDraft(ctx context.Context, id string) error
// PutProposal creates a proposal (empty ID) or updates one. Creating
// one while the same skill of the same scope has an open proposal
// returns ErrConflict: there is one at a time. An update whose Version
// is not the stored one returns ErrConflict too.
PutProposal(ctx context.Context, p *Proposal) error
GetProposal(ctx context.Context, id string) (*Proposal, error)
// ListProposals lists proposals newest first.
ListProposals(ctx context.Context, f ProposalFilter) ([]Proposal, error)
// ReplaceSkillIndex replaces the resolved skills of one repository.
ReplaceSkillIndex(ctx context.Context, repo string, entries []SkillIndexEntry) error
ListSkillIndex(ctx context.Context, repo string) ([]SkillIndexEntry, error)
AddMemory(ctx context.Context, m *Memory) error
GetMemory(ctx context.Context, id string) (*Memory, error)
// SearchMemory returns team memories and, when the query names a
// person, that person's own. It never returns another person's.
SearchMemory(ctx context.Context, q MemoryQuery) ([]Memory, error)
// ListMemory lists memories newest first, under the same rule.
ListMemory(ctx context.Context, f MemoryFilter) ([]Memory, error)
DeleteMemory(ctx context.Context, id string) error
// RecordPullRequest stores a pull request a session opened. Recording
// one that is already there changes nothing.
RecordPullRequest(ctx context.Context, pr PullRequest) error
// GetPullRequest returns a recorded pull request, or ErrNotFound: it is
// how kōjō tells its own pull requests from everyone else's.
GetPullRequest(ctx context.Context, repo string, number int) (*PullRequest, error)
// UpdatePullRequest writes a recorded pull request's state, human-edit
// flag and closing time.
UpdatePullRequest(ctx context.Context, pr *PullRequest) error
// ListPullRequests lists recorded pull requests, newest first.
ListPullRequests(ctx context.Context, f PullRequestFilter) ([]PullRequest, error)
PutEvalRun(ctx context.Context, r *EvalRun) error
GetEvalRun(ctx context.Context, id string) (*EvalRun, error)
// ListEvalRuns lists runs newest first. An empty skill lists them all.
ListEvalRuns(ctx context.Context, skill string, limit int) ([]EvalRun, error)
// CreateCampaign stores a new campaign, setting its ID and times when
// unset.
CreateCampaign(ctx context.Context, c *Campaign) error
GetCampaign(ctx context.Context, id string) (*Campaign, error)
// ListCampaigns lists campaigns newest first (by ID).
ListCampaigns(ctx context.Context, f CampaignFilter) ([]Campaign, error)
// UpdateCampaign runs fn on the stored campaign while holding its row
// lock and saves what fn left, so two replicas never interleave
// changes to one campaign. It waits for an update that holds the lock.
// An error from fn changes nothing and is returned. fn may call the
// store, but must not update a campaign, this one or another: this
// one's update would wait for itself, and on Postgres another's takes
// a second campaign slot, which with a pool of 2 waits until ctx ends.
UpdateCampaign(ctx context.Context, id string, fn func(*Campaign) error) (*Campaign, error)
// TryUpdateCampaign is UpdateCampaign without the wait: when another
// update, of this process or another, holds the campaign it returns
// ErrLocked and runs nothing.
TryUpdateCampaign(ctx context.Context, id string, fn func(*Campaign) error) (*Campaign, error)
UpsertUser(ctx context.Context, u User) error
ListUsers(ctx context.Context) ([]User, error)
PutApproval(ctx context.Context, a *Approval) error
GetApproval(ctx context.Context, id string) (*Approval, error)
// DecideApproval records the first decision and returns the approval.
// A second decision returns ErrConflict.
DecideApproval(ctx context.Context, id, status, by string) (*Approval, error)
// AddSessionMessage stores a message for its session and assigns its
// ID, Seq, Status (pending) and CreatedAt. The session must take
// messages (Session.TakesMessages), checked in the same transaction
// that writes the message, so a session that just ended never gets
// one: ErrConflict otherwise, ErrNotFound for an unknown session,
// ErrLimit when the session already has max messages, and ErrDuplicate
// for a DedupeKey stored before.
AddSessionMessage(ctx context.Context, m *SessionMessage, max int) error
// ListSessionMessages returns all of a session's messages, oldest
// first.
ListSessionMessages(ctx context.Context, sessionID string) ([]SessionMessage, error)
// UndeliveredMessages returns a session's pending messages, oldest
// first: the ones no model of the session has read yet.
UndeliveredMessages(ctx context.Context, sessionID string) ([]SessionMessage, error)
// MarkSessionMessages moves the named messages of a session that are
// still pending to status (delivered or unread); a delivered one also
// records to (DeliveredTo) and the time. It returns the messages it
// changed: a message another call already moved is left as it is and
// not returned, so whoever gets it back acts on it once.
MarkSessionMessages(ctx context.Context, sessionID string, ids []string, status, to string) ([]SessionMessage, error)
GetScheduleState(ctx context.Context, key string) (*ScheduleState, error)
PutScheduleState(ctx context.Context, s ScheduleState) error
// TryLead tries to become the leader for name (the scheduler). The
// returned release function gives leadership up; ok is false when
// another replica leads.
TryLead(ctx context.Context, name string) (release func(), ok bool, err error)
// Ping checks the database is reachable.
Ping(ctx context.Context) error
Close()
}
Store is everything kōjō persists.
type TestRun ¶
type TestRun struct {
// What says what the workspace held.
What string `json:"what"`
ExitCode int `json:"exit_code"`
TimedOut bool `json:"timed_out,omitempty"`
Seconds float64 `json:"seconds"`
// Output is the end of what the command printed.
Output string `json:"output,omitempty"`
}
TestRun is one run of a history eval's test command.
type ThreadRef ¶
type ThreadRef struct {
Surface string `json:"surface"`
Channel string `json:"channel"`
ThreadID string `json:"thread_id,omitempty"`
}
ThreadRef is the chat thread a request came from and replies go to.
type TicketRef ¶ added in v0.3.0
type TicketRef struct {
// Tracker is linear, jira or asana.
Tracker string `json:"tracker"`
// ID is the tracker's own ID of the ticket.
ID string `json:"id"`
// Key is the ticket's key, such as ENG-123 or PAY-7. Asana tasks have
// none.
Key string `json:"key,omitempty"`
URL string `json:"url,omitempty"`
}
TicketRef is the ticket of an issue tracker (Linear, Jira, Asana) a request came from: where its result is posted and where people talk to its session.
type User ¶
type User struct {
Subject string `json:"subject"`
Email string `json:"email"`
Name string `json:"name,omitempty"`
LastSeen time.Time `json:"last_seen"`
CreatedAt time.Time `json:"created_at"`
}
User is someone who signed in to the dashboard. Roles live in the rbac config object, so they are versioned like every other day-2 change.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package memory is an in-process store.Store for unit tests and for `kojo eval --local`.
|
Package memory is an in-process store.Store for unit tests and for `kojo eval --local`. |
|
Package postgres is kōjō's production store: one Postgres database holds the queue (FOR UPDATE SKIP LOCKED), sessions and checkpoints (JSONB), team memory (pgvector, with a full-text fallback), the append-only audit log, config revisions (hot reload through LISTEN/NOTIFY) and everything else.
|
Package postgres is kōjō's production store: one Postgres database holds the queue (FOR UPDATE SKIP LOCKED), sessions and checkpoints (JSONB), team memory (pgvector, with a full-text fallback), the append-only audit log, config revisions (hot reload through LISTEN/NOTIFY) and everything else. |
|
Package storetest is the behaviour every store.Store must have.
|
Package storetest is the behaviour every store.Store must have. |