projection

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2026 License: Apache-2.0 Imports: 14 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 projection computes the user-facing projections — Current Understanding (§5), Recommended Next Move (§6), and What Changed (§7) — deterministically from relational state. They are projections, not a source of truth, and every statement retains provenance.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AgentCostFromRuns added in v0.6.0

func AgentCostFromRuns(ctx context.Context, db *store.DB, initiativeID string, stats store.AgentRunStats) domain.AgentCost

AgentCostFromRuns fills in the agent cost's USD/note from the initiative's change sets' AgentOutput, given the run count/duration already computed. Exported for tests that want to exercise the parsing rule directly.

func AllTestsPassed added in v0.6.0

func AllTestsPassed(ev []domain.EvidenceTest) bool

AllTestsPassed reports whether ev is non-empty and every entry passed -- the rule both GET .../requirements' display and confirm_passing_tests use (C2, wire contract).

func BuildCosts added in v0.6.0

func BuildCosts(ctx context.Context, db *store.DB, initiativeID string) (domain.InitiativeCosts, error)

BuildCosts builds an initiative's spend/time summary (C3, wave 3 contract) from the run records that already exist: model-call cost/duration (per phase, from run_manifests via runs.stage) and agent (coding) run count/ duration, with agent spend parsed best-effort from each change set's own AgentOutput -- Hermes's own token/cost line, when it printed one -- or reported as not measured.

func BuildQueue added in v0.6.0

func BuildQueue(ctx context.Context, db *store.DB, blobs, rawBlobs *blob.Store) ([]domain.QueueItem, error)

BuildQueue builds the "needs you" queue across every initiative in the project (D-b, wave 3 contract): open blocking decisions, change sets awaiting review, conflicts, denials, stale items, and verifications ready to confirm -- ranked blocking first, then by age.

The returned Rank is a small 1..N ordinal (H6, review fix), not the internal tier*age sort key used to order them: that key is tier*2^59+milliseconds, well past JavaScript's safe-integer range, so the UI rendered it as a garbled, meaningless number ("#1729384046714066200") and had nothing it could compare across items anyway. 1 is always the most urgent item; the ordinal is documented in docs/openapi.yaml.

func BuildTimeline added in v0.6.0

func BuildTimeline(ctx context.Context, db *store.DB, initiativeID string, since int64, limit int) ([]domain.TimelineEntry, error)

BuildTimeline builds an initiative's "what changed" timeline (C1, wave 3 contract) from the event log and the change-set, decision and stale-mark tables, scoped to initiativeID throughout by joining back to those tables' own initiative_id -- never by reading the events table unscoped, which is what let the old What Changed projection leak another initiative's counts (JTBD 6). Entries are newest first; since, if non-zero, excludes anything at or before it. limit<=0 uses defaultTimelineLimit.

func ComputeEvidenceTests added in v0.6.0

func ComputeEvidenceTests(ctx context.Context, db *store.DB, blobs, rawBlobs *blob.Store, initiativeID string) (map[string][]domain.EvidenceTest, error)

ComputeEvidenceTests maps each of an initiative's requirements to the test-run evidence that covers it (C2, wave 3 contract), tried in order until one produces names:

  1. Tests named for its code in the verification plan's hooks (mappedTestsByRequirement, resolved against the redacted `blobs` store that holds model artifacts).
  2. Any parsed test whose name contains the requirement's code on a word boundary.
  3. Test functions found in test/spec files touched by the change set implementing a task that `implements` this requirement (taskDerivedTests, ICP re-run defect #3 bullet (b)) -- because a real test's name almost never contains the requirement's code ("TestRateLimiterAllowsWithinBudget" for a per-key-rate-limiting requirement has no "REQ-5" in it anywhere), so (2) alone left every requirement unmapped on a real run despite tests passing. Only counted when that change set is applied and its OWN check passed. Resolved against `rawBlobs`, the redaction-free store: a change set's patch manifest and file content are written there (see workflow.Engine.contentBlobs), never in the redacted `blobs` store, so passing the wrong store here silently produced zero task-derived evidence on every real run (evidence_tests null on every requirement despite tests passing) -- decodePatch's Get against the wrong store failed not-found every time. `blobs` and `rawBlobs` may be the same value only in tests that don't need to distinguish them.

Every tier is resolved against the most recent parsed result for that test name among the initiative's ELIGIBLE change sets (eligibleChangeSets) -- never a rejected, reverted, or task-superseded attempt, and never a check that did not itself exit 0 (Disposition == DispositionRejected covers a non-zero exit, a timeout, and a sandbox that could not launch; only those three write a "tests" finding without an observation-level pass, so this predicate is exact, not heuristic). A test named by tier (1) or (3) that is missing from that finding's parsed output counts as failed, never as silently absent (C1 fix: a plan naming [TestA, TestB] where only TestA's line survived must not read as "both passed") -- tier (2) can never produce a "missing" name by construction (it only ever matches a name already known to have run).

func DedupDecisions added in v0.5.0

func DedupDecisions(decs []domain.Decision) []domain.Decision

DedupDecisions is dedupDecisionsForDisplay for callers outside the package: the decisions endpoint the UI reads applies it too, so the page and the guidance agree on how many decisions there are.

func LatestChangeSetsPerActiveTask added in v0.6.0

func LatestChangeSetsPerActiveTask(changeSets []domain.ChangeSet, tasks []domain.Task) []domain.ChangeSet

LatestChangeSetsPerActiveTask reduces changeSets to at most one entry per task -- that task's own most recently created (by CreatedAt) change set -- keeping only tasks whose CURRENT status is not cancelled (review M7).

ICP re-run defect G: this used to also exclude `done` tasks, on the assumption that a done task has nothing left to report. But Execute marks a task done as soon as its change set passes checks -- BEFORE that change set has been reviewed, approved, or applied (execute.go: "Mark done so a repeated Execute does not re-pick the same task") -- so a task sitting on a change set awaiting human review/apply is `done` the whole time it is waiting. Excluding it here hid exactly the change set BuildGuidance most needs to report, and once every task reached `done` this way the reduction emptied out entirely, so guidance kept saying "run the next task" forever with nothing left to run instead of ever pointing at Verify. A cancelled (or deleted) task's change set is still excluded: there is nothing left to resolve on work that no longer exists as active.

func ParseAgentCostUSD added in v0.6.0

func ParseAgentCostUSD(output string) (usd float64, ok bool)

ParseAgentCostUSD extracts a dollar cost from a coding agent's own console output, best-effort (C3, wave 3 contract). A line explicitly labelled "total cost" wins outright; otherwise the LAST plain "cost: $x" match wins (M6, review fix: taking the first match anywhere picked up a per-step cost printed before the run's own final total). ok is false when no recognizable cost line is present at all.

func ParseAgentTokenUsage added in v0.6.0

func ParseAgentTokenUsage(output string) (inputTokens, outputTokens int64, ok bool)

ParseAgentTokenUsage extracts input/output token counts from a coding agent's own console output, best-effort (review defect #5). ok is true only when BOTH counts are present: a bare total_tokens with no split cannot be priced against a catalog with separate input/output rates without guessing the split, and a guess that happened to look precise would be worse than admitting the cost is not measured.

func SameQuestion added in v0.5.0

func SameQuestion(a, b string) bool

SameQuestion reports whether two decision questions are the same question for display: equal after normalizeDecisionQuestion.

Types

type ChangeGroup

type ChangeGroup struct {
	Category string   `json:"category"`
	Items    []string `json:"items"`
}

ChangeGroup is one grouped category of changes.

type Changed

type Changed struct {
	Groups  []ChangeGroup `json:"groups"`
	Through int64         `json:"through"`
}

Changed is the grouped What Changed projection. Through is the highest event sequence actually consumed by this projection (or the caller's cursor when no events matched) — the client echoes it back to the read-cursor write so that exactly what was shown is marked seen, never events that arrived mid-read.

func BuildChanged

func BuildChanged(ctx context.Context, db *store.DB, initiativeID string, sinceSeq int64, limit int) (Changed, error)

BuildChanged summarizes an initiative's events since sinceSeq into grouped, narrated items (§7), scoped to initiativeID throughout (C1/JTBD 6: this used to read the whole project's events with no initiative filter at all, so one initiative's What Changed could report another's counts). The raw event timeline is served separately via /activity.

type DecisionView

type DecisionView struct {
	ID             string                `json:"id"`
	Code           string                `json:"code"`
	Question       string                `json:"question"`
	Recommendation string                `json:"recommendation"`
	Options        []string              `json:"options"`
	Resolution     string                `json:"resolution,omitempty"`
	Status         domain.DecisionStatus `json:"status"`
	HasDissent     bool                  `json:"has_dissent"`
	Dissents       []DissentView         `json:"dissents"`
	Synthesis      string                `json:"synthesis,omitempty"`
}

DecisionView is a decision in the projection (with dissent presence).

type DissentView

type DissentView struct {
	ProponentRole string `json:"proponent_role"`
	Position      string `json:"position"`
}

DissentView is one dissenting position on a decision (§8).

type Guidance

type Guidance struct {
	Action   string   `json:"action"`
	Why      string   `json:"why"`
	Affected []string `json:"affected"`
	// NextTask is the task Execute would run next, omitted when there is none
	// (the Build contract's `next_task`, reusing workflow's nextReadyTask).
	// Omitted rather than null: every other daemon endpoint's contract is
	// "never emit a null field" (TestNoEndpointEmitsANullArray), and this is
	// the same rule applied to a single optional object instead of a slice.
	// BuildGuidance leaves this nil: it stays a pure function of Understanding
	// with no engine/task-store access, so the daemon handler populates it
	// after calling BuildGuidance (via Engine.NextReadyTask).
	NextTask *NextTaskRef `json:"next_task,omitempty"`
	// RunBlockedReason is empty (and so omitted) when Execute could start
	// right now for this initiative, otherwise a user-facing sentence naming
	// the fix (the Build contract's `run_blocked_reason`): another change set
	// still open, an operation already running, the plan not approved yet, or
	// -- composed in by the daemon handler, not here -- the executor not
	// being ready. Same population note as NextTask.
	RunBlockedReason string `json:"run_blocked_reason,omitempty"`
	// PartialWork is what a stopped run left for the next run of its task
	// to continue from, omitted when nothing was kept. Same population note
	// as NextTask.
	PartialWork *PartialWorkRef `json:"partial_work,omitempty"`
	// StaleItems lists the requirements, tasks and change sets marked stale by
	// a decision that was reopened or re-resolved after they were built
	// (review A4 #5: "impact is true"), omitted when nothing is stale. Same
	// population note as NextTask: the daemon handler appends both this field
	// and a sentence onto Why, since BuildGuidance has no store access.
	StaleItems []StaleItemRef `json:"stale_items,omitempty"`
}

Guidance is the Recommended Next Move projection.

func BuildGuidance

func BuildGuidance(ini domain.Initiative, understanding Understanding, recentChangeSets []domain.ChangeSet, allTasksDone bool) Guidance

BuildGuidance computes the Recommended Next Move with deterministic precedence: judgment items outrank stage advancement (§6, §9).

recentChangeSets should be LatestChangeSetsPerActiveTask's result, not the initiative's raw change-set list (review C6, M7; C6 was the original signature change from the earlier BuildGuidance(ini, understanding)): guidance must not say "ready to build" over a change set that was just denied, rejected, or failed -- it says what happened and the next step instead, and it must not miss one just because a DIFFERENT task's change set was created more recently, or keep reporting one whose task was since cancelled or deleted (review M7). Callers with no change sets to report (a fresh initiative, or one with none yet) pass nil, which behaves exactly as before.

allTasksDone (ICP re-run defect G) is true when every one of the initiative's non-cancelled tasks is done -- the caller's job, since BuildGuidance stays a pure function with no task-store access of its own (same reason NextTask/RunBlockedReason are composed by the daemon handler instead of computed here). Guidance used to have no way to tell "nothing left to build" from "nothing built yet": once every task reached done with its change set applied, this fell through to the same "run the next task" message a fresh plan gets, and status stayed plan_approved forever with no pointer to `idea verify` at all.

type NextTaskRef added in v0.5.0

type NextTaskRef struct {
	ID      string `json:"id"`
	HumanID string `json:"human_id"`
	Title   string `json:"title"`
}

NextTaskRef is the Build contract's `next_task` shape: enough to name and link the task without exposing the full domain.Task.

type PartialWorkRef added in v0.5.1

type PartialWorkRef struct {
	TaskID      string `json:"task_id"`
	TaskHumanID string `json:"task_human_id,omitempty"`
	Files       int    `json:"files"`
	// Note says why nothing was kept, when the stopped run's files looked
	// like they contained a secret.
	Note string `json:"note,omitempty"`
}

PartialWorkRef names a stopped run's kept files for the Build page.

type QuestionView

type QuestionView struct {
	ID       string                `json:"id"`
	Question string                `json:"question"`
	Status   domain.QuestionStatus `json:"status"`
}

QuestionView is an open question in the projection.

type RequirementView

type RequirementView struct {
	ID                 string                       `json:"id"`
	Code               string                       `json:"code"`
	Statement          string                       `json:"statement"`
	Priority           domain.RequirementPriority   `json:"priority"`
	Status             domain.RequirementStatus     `json:"status"`
	AcceptanceCriteria []domain.AcceptanceCriterion `json:"acceptance_criteria"`
}

RequirementView is a requirement in the projection.

type StaleItemRef added in v0.6.0

type StaleItemRef struct {
	StaleID string `json:"stale_id"`
	Type    string `json:"type"`
	ID      string `json:"id"`
	Label   string `json:"label,omitempty"`
	Reason  string `json:"reason"`
}

StaleItemRef names one stale item on the Recommended Next Move projection. StaleID is the stale-mark's own id -- what POST …/stale/{staleId}/ack takes -- distinct from ID, the graph node (requirement/task/change_set) it marks.

type TestResult added in v0.6.0

type TestResult struct {
	Package string
	Name    string
	Status  string // "passed" | "failed"
}

TestResult is one parsed test outcome (C2, wave 3 contract). Package is a best-effort grouping key (a Go import path, from `go test -json`'s own Package field or a `-v` output's trailing "ok/FAIL <pkg>" summary line) -- "" when the format carries no such notion (TAP, pytest, jest). It disambiguates two same-named tests in different packages; the exposed evidence (domain.EvidenceTest) never carries it, only Name.

func ParseTestOutput added in v0.6.0

func ParseTestOutput(output string) []TestResult

ParseTestOutput parses a test check's raw console output into per-test results, best-effort (C2, wave 3 contract). Two shapes are understood:

  • `go test -json`'s newline-delimited JSON event stream (detected when the first non-blank line looks like a JSON object) -- preferred whenever the check command can produce it (see execute.go's checkCommand), because it carries an exact Package/Test identity instead of one scraped from text.
  • Free text: node --test's TAP output, `go test -v`, `pytest -v`, and jest-style ✓/✗ lines. Unrecognized lines are ignored.

A test name that appears more than once (a genuine rerun, a name reused across packages, or an agent's own test printing a line that mimics the format) keeps its most severe outcome: any "failed" observation for a key is sticky and can never be overwritten back to "passed" by a later line, in either format (C2: "an agent-printed fake --- PASS cannot flip a real FAIL").

type TriageItem added in v0.6.0

type TriageItem struct {
	Type       string          `json:"type"` // "decision" | "question" | "finding"
	ID         string          `json:"id"`
	Label      string          `json:"label"`
	Blocking   bool            `json:"blocking"`
	Severity   domain.Severity `json:"severity,omitempty"`
	Dependents int             `json:"dependents"`
	// Rank is "priority" for the top 3 by impact, "optional" for the rest --
	// the ICP round's own words for what six audits could not get past: "53
	// things need your judgment", none of them ranked.
	Rank string `json:"rank"`
}

TriageItem is one open judgment item ranked for the triage view (review B4, adopted #8's guidance/decisions triage): "the top 3 open items by impact (blocking > high severity > dependents count). The rest are labelled optional."

func BuildTriage added in v0.6.0

func BuildTriage(decisions []domain.Decision, questions []domain.Question, findings []domain.Finding, dependents map[string]int) []TriageItem

BuildTriage ranks open decisions, open questions, and open blocking findings into a single priority order and labels the top 3 "priority", the rest "optional" (review B4, adopted #8). dependents maps a decision or question's id to how many other objects (requirements, tasks, change sets) cite it -- the caller supplies it since counting edges needs store access this package's other Build* functions do not have either.

Ranking key, highest first: blocking, then severity (findings only -- decisions/questions have none and rank below any finding of the same blocking-ness), then dependents count. Ties preserve input order (each slice's own, decisions/questions/findings concatenated in that order) for a deterministic, boring sort.

type Understanding

type Understanding struct {
	Title         string                  `json:"title"`
	Description   string                  `json:"description"`
	Status        domain.InitiativeStatus `json:"status"`
	FailureReason string                  `json:"failure_reason,omitempty"`
	Summary       string                  `json:"summary"`
	NeedsJudgment []string                `json:"needs_judgment"`
	Assertions    []UnderstandingItem     `json:"assertions"`
	Requirements  []RequirementView       `json:"requirements"`
	Decisions     []DecisionView          `json:"decisions"`
	Questions     []QuestionView          `json:"questions"`
}

Understanding is the Current Understanding projection.

func BuildUnderstanding

func BuildUnderstanding(ctx context.Context, db *store.DB, ini domain.Initiative) (Understanding, error)

BuildUnderstanding assembles the Current Understanding projection.

type UnderstandingItem

type UnderstandingItem struct {
	ID            string                 `json:"id"`
	Type          domain.AssertionType   `json:"type"`
	Status        domain.AssertionStatus `json:"status"`
	Statement     string                 `json:"statement"`
	Confidence    domain.Confidence      `json:"confidence"`
	Source        string                 `json:"source"`
	Provenance    []domain.ProvenanceRef `json:"provenance"`
	ProducedByRun string                 `json:"produced_by_run"`
}

UnderstandingItem is one provenance-backed statement.

Jump to

Keyboard shortcuts

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