Documentation
¶
Overview ¶
Package store provides SQLite persistence with atomic state+event appends (§32). Relational state is authoritative; events are appended in the same transaction as the state mutation they describe.
Index ¶
- Constants
- Variables
- func AllowlistKey(fingerprint, path string) string
- func DetectTaskCycle(deps map[string][]string) string
- func IsStorageFailure(err error) bool
- func PushSubscriberName(subscriptionID string) string
- func ValidateMetric(m *domain.OutcomeMetric) error
- type AgentRunStats
- type ArtifactRollup
- type ArtifactView
- type AutomationRun
- type CaptureToken
- type ChangeSetPatchRef
- type ChangeSetRecovery
- type DB
- func (db *DB) AddTaskDependencies(ctx context.Context, initiativeID, taskID string, depTaskIDs []string) error
- func (db *DB) AnswerQuestion(ctx context.Context, questionID, answerDigest, actor string) error
- func (db *DB) AppendAutomationEvent(ctx context.Context, automation, eventType, operation string) error
- func (db *DB) AppendJournal(ctx context.Context, e *domain.ApplyJournalEntry) error
- func (db *DB) AppendRemoteRunProgress(ctx context.Context, runID, fromEventID, lastEventID string, events int, ...) (applied bool, err error)
- func (db *DB) AppendRemoteRunProgressEvents(ctx context.Context, runID, fromEventID, lastEventID string, events int, ...) (applied bool, err error)
- func (db *DB) AppendRunEvents(ctx context.Context, runID string, evs []domain.RunEvent) ([]domain.RunEvent, error)
- func (db *DB) AppendSuggestedAnswers(ctx context.Context, initiativeID string, answers []domain.SuggestedAnswer) error
- func (db *DB) Apply(ctx context.Context, ev Event, fn func(tx *sql.Tx) error) error
- func (db *DB) ApplyNoop(ctx context.Context, ev Event) error
- func (db *DB) ApproveRequirements(ctx context.Context, initiativeID, actor string) error
- func (db *DB) AttachTaskEdges(ctx context.Context, initiativeID string, tasks []domain.Task) error
- func (db *DB) AuditGraphEdges(ctx context.Context, initiativeID string) ([]domain.Finding, error)
- func (db *DB) BurnedPairingCodes(ctx context.Context, since time.Time) (int, time.Time, error)
- func (db *DB) CancelOperationStatus(ctx context.Context, opID string) error
- func (db *DB) ChangeSetWorkspaceTimes(ctx context.Context, initiativeID string) (map[string]time.Time, error)
- func (db *DB) ClaimInitiativeRunning(ctx context.Context, initiativeID string, from ...domain.InitiativeStatus) error
- func (db *DB) ClaimNoOpBackfill(ctx context.Context) (bool, error)
- func (db *DB) ClearStaleItem(ctx context.Context, initiativeID, staleID, actor string) error
- func (db *DB) ClearStaleItemsForInitiative(ctx context.Context, initiativeID, actor string) error
- func (db *DB) ClearVerificationEvidence(ctx context.Context, requirementID, actor string) error
- func (db *DB) Close() error
- func (db *DB) CompleteInitiative(ctx context.Context, initiativeID, actor string) error
- func (db *DB) CountChangeSetsByHumanID(ctx context.Context, humanID string) (int, error)
- func (db *DB) CountTerminalRemoteRuns(ctx context.Context, executor, taskID string) (int, error)
- func (db *DB) CreateArtifact(ctx context.Context, a *domain.Artifact, v *domain.ArtifactVersion) error
- func (db *DB) CreateAssertion(ctx context.Context, a *domain.Assertion) error
- func (db *DB) CreateCaptureToken(ctx context.Context, projectID, tokenHash, label string) (string, error)
- func (db *DB) CreateChangeSet(ctx context.Context, cs *domain.ChangeSet) error
- func (db *DB) CreateContextBundle(ctx context.Context, bundleID, runID, digest string, ...) error
- func (db *DB) CreateContextDoc(ctx context.Context, doc *domain.ContextDoc) error
- func (db *DB) CreateDecision(ctx context.Context, d *domain.Decision) error
- func (db *DB) CreateDecisionDiscussion(ctx context.Context, m *domain.DecisionDiscussion) error
- func (db *DB) CreateDissent(ctx context.Context, d *domain.DecisionDissent) error
- func (db *DB) CreateDocComment(ctx context.Context, c *domain.DocComment) error
- func (db *DB) CreateFinding(ctx context.Context, f *domain.Finding) error
- func (db *DB) CreateInitiative(ctx context.Context, ini *domain.Initiative) error
- func (db *DB) CreateMetric(ctx context.Context, m *domain.OutcomeMetric, actor string) error
- func (db *DB) CreateMetricHypothesis(ctx context.Context, ...) (*domain.Assertion, error)
- func (db *DB) CreateObjective(ctx context.Context, o *domain.Objective, actor string) error
- func (db *DB) CreateOperation(ctx context.Context, projectID, initiativeID, opType string) (string, error)
- func (db *DB) CreatePairingCode(ctx context.Context, codeHash, label string, now, expires time.Time) error
- func (db *DB) CreateQuestion(ctx context.Context, q *domain.Question) error
- func (db *DB) CreateRemoteRun(ctx context.Context, r domain.RemoteRun) (*domain.RemoteRun, bool, error)
- func (db *DB) CreateRequirement(ctx context.Context, r *domain.Requirement) error
- func (db *DB) CreateRun(ctx context.Context, kind domain.RunKind, ...) (string, error)
- func (db *DB) CreateRunManifest(ctx context.Context, m *domain.RunManifest) error
- func (db *DB) CreateTask(ctx context.Context, t *domain.Task, implementsRequirementID string, ...) error
- func (db *DB) CreateTaskMulti(ctx context.Context, t *domain.Task, implementsRequirementIDs []string, ...) error
- func (db *DB) CreateVerificationEvidence(ctx context.Context, e *domain.VerificationEvidence) error
- func (db *DB) CreateVerificationTask(ctx context.Context, t *domain.Task, requirementID string) error
- func (db *DB) DaemonMeta(ctx context.Context, key string) (string, error)
- func (db *DB) DeletePushSubscription(ctx context.Context, subID string) error
- func (db *DB) DeleteTask(ctx context.Context, initiativeID, taskID string) error
- func (db *DB) DeleteTasksForInitiative(ctx context.Context, initiativeID string) error
- func (db *DB) DispositionOpenFindings(ctx context.Context, initiativeID string, disp domain.Disposition, ...) error
- func (db *DB) DispositionUnclaimedFindingsByTarget(ctx context.Context, initiativeID, targetType, targetID string, ...) error
- func (db *DB) DriftingMetrics(ctx context.Context, initiativeID string, now time.Time) ([]domain.OutcomeMetric, error)
- func (db *DB) FailInitiative(ctx context.Context, initiativeID, reason string) error
- func (db *DB) FailInterruptedAutomationRuns(ctx context.Context) error
- func (db *DB) FinishAutomationRun(ctx context.Context, r AutomationRun) error
- func (db *DB) GetArtifactVersion(ctx context.Context, versionID string) (ArtifactView, error)
- func (db *DB) GetChangeSet(ctx context.Context, changeSetID string) (*domain.ChangeSet, error)
- func (db *DB) GetChangeSetByRef(ctx context.Context, ref string) (*domain.ChangeSet, error)
- func (db *DB) GetContextDoc(ctx context.Context, id string) (*domain.ContextDoc, error)
- func (db *DB) GetDecision(ctx context.Context, decisionID string) (*domain.Decision, error)
- func (db *DB) GetDocComment(ctx context.Context, commentID string) (*domain.DocComment, error)
- func (db *DB) GetFinding(ctx context.Context, id string) (*domain.Finding, error)
- func (db *DB) GetInitiative(ctx context.Context, initiativeID string) (domain.Initiative, error)
- func (db *DB) GetInitiativeBudget(ctx context.Context, initiativeID string) (InitiativeBudget, error)
- func (db *DB) GetIntegrationLink(ctx context.Context, integration, kind, localID string) (*IntegrationLink, error)
- func (db *DB) GetIntegrationLinkByRemote(ctx context.Context, integration, kind, remoteID string) (*IntegrationLink, error)
- func (db *DB) GetMetricByRef(ctx context.Context, initiativeID, ref string, now time.Time) (*domain.OutcomeMetric, error)
- func (db *DB) GetMetricRef(ctx context.Context, metricID string) (*MetricRef, error)
- func (db *DB) GetObjectiveByRef(ctx context.Context, initiativeID, ref string) (*domain.Objective, error)
- func (db *DB) GetOperation(ctx context.Context, opID string) (domain.Operation, error)
- func (db *DB) GetProject(ctx context.Context, projectID string) (ProjectRecord, error)
- func (db *DB) GetPushSubscription(ctx context.Context, subID string) (PushSubscription, error)
- func (db *DB) GetQualityResult(ctx context.Context, resultID string) (*domain.QualityResult, error)
- func (db *DB) GetReadCursor(ctx context.Context, scope string) (int64, error)
- func (db *DB) GetRemoteRun(ctx context.Context, runID string) (*domain.RemoteRun, error)
- func (db *DB) GetRemoteRunByAgentRun(ctx context.Context, runID string) (*domain.RemoteRun, error)
- func (db *DB) GetRemoteRunByKey(ctx context.Context, key string) (*domain.RemoteRun, error)
- func (db *DB) GetRequirementByRef(ctx context.Context, initiativeID, ref string) (*domain.Requirement, error)
- func (db *DB) GetRunInfo(ctx context.Context, runID string) (RunInfo, error)
- func (db *DB) GetRunManifest(ctx context.Context, runID string) (domain.RunManifest, error)
- func (db *DB) GetTask(ctx context.Context, taskID string) (*domain.Task, error)
- func (db *DB) GetVerificationEvidenceRef(ctx context.Context, evidenceID string) (*VerificationEvidenceRef, error)
- func (db *DB) GraphEventSeqs(ctx context.Context, initiativeID string) (map[string]int64, error)
- func (db *DB) HasDissent(ctx context.Context, decisionID string) (bool, error)
- func (db *DB) HoldSteeringNote(ctx context.Context, n HeldSteeringNote) error
- func (db *DB) InTx(ctx context.Context, fn func(tx *sql.Tx) error) error
- func (db *DB) IngestOutbox(ctx context.Context, subscriber string, lastSeq int64, rows []OutboxInsert) error
- func (db *DB) IntegrationCursor(ctx context.Context, subscriber string) (int64, bool, error)
- func (db *DB) IntegrationOutboxStats(ctx context.Context, subscriber string) (OutboxStats, error)
- func (db *DB) JournalSnapshotDigest(ctx context.Context, changeSetID string) (string, error)
- func (db *DB) LatestEventRunForInitiative(ctx context.Context, initiativeID string) (string, error)
- func (db *DB) LatestOperationOfType(ctx context.Context, projectID, opType string) (*domain.Operation, error)
- func (db *DB) LatestQualityResults(ctx context.Context, initiativeID string) (map[domain.QualityDimension]domain.QualityResult, error)
- func (db *DB) LinkRequirementObjective(ctx context.Context, initiativeID, requirementID, objectiveID, actor string) error
- func (db *DB) ListAgentRunStats(ctx context.Context, initiativeID string) (AgentRunStats, error)
- func (db *DB) ListAllRunEvents(ctx context.Context, runID string) ([]domain.RunEvent, error)
- func (db *DB) ListAllStaleMarks(ctx context.Context, initiativeID string) ([]domain.StaleItem, error)
- func (db *DB) ListArtifactVersions(ctx context.Context, initiativeID string) ([]domain.ArtifactVersion, error)
- func (db *DB) ListArtifacts(ctx context.Context, initiativeID string) ([]ArtifactView, error)
- func (db *DB) ListAssertions(ctx context.Context, initiativeID string) ([]domain.Assertion, error)
- func (db *DB) ListAutomationRuns(ctx context.Context, automation, target string, limit int) ([]AutomationRun, error)
- func (db *DB) ListCaptureTokens(ctx context.Context, projectID string) ([]CaptureToken, error)
- func (db *DB) ListChangeSetEventsForInitiative(ctx context.Context, initiativeID string) ([]TimelineChangeSetEvent, error)
- func (db *DB) ListChangeSets(ctx context.Context, initiativeID string) ([]domain.ChangeSet, error)
- func (db *DB) ListChangeSetsByTask(ctx context.Context, taskID string) ([]domain.ChangeSet, error)
- func (db *DB) ListChangeSetsForNoOpBackfill(ctx context.Context) ([]ChangeSetPatchRef, error)
- func (db *DB) ListContextDocs(ctx context.Context, initiativeID string) ([]domain.ContextDoc, error)
- func (db *DB) ListDecisionDiscussions(ctx context.Context, decisionID string) ([]domain.DecisionDiscussion, error)
- func (db *DB) ListDecisionEventsForInitiative(ctx context.Context, initiativeID string) ([]TimelineDecisionEvent, error)
- func (db *DB) ListDecisions(ctx context.Context, initiativeID string) ([]domain.Decision, error)
- func (db *DB) ListDissents(ctx context.Context, decisionID string) ([]domain.DecisionDissent, error)
- func (db *DB) ListDocComments(ctx context.Context, artifactVersionID string) ([]domain.DocComment, error)
- func (db *DB) ListEvents(ctx context.Context, sinceSeq int64, limit int) ([]EventRow, error)
- func (db *DB) ListEventsForInitiative(ctx context.Context, initiativeID string, sinceSeq int64, limit int) ([]EventRow, error)
- func (db *DB) ListEvidenceByRequirement(ctx context.Context, requirementID string) ([]domain.VerificationEvidence, error)
- func (db *DB) ListFindings(ctx context.Context, reviewRunID string) ([]domain.Finding, error)
- func (db *DB) ListFindingsByInitiative(ctx context.Context, initiativeID string) ([]domain.Finding, error)
- func (db *DB) ListFindingsByTarget(ctx context.Context, targetType, targetID string) ([]domain.Finding, error)
- func (db *DB) ListGraphEdges(ctx context.Context, initiativeID string) ([]domain.GraphEdge, error)
- func (db *DB) ListGraphEdgesFrom(ctx context.Context, initiativeID, fromType, fromID string) ([]domain.GraphEdge, error)
- func (db *DB) ListGraphEdgesTo(ctx context.Context, initiativeID, toType, toID string) ([]domain.GraphEdge, error)
- func (db *DB) ListInitiativeRemoteRuns(ctx context.Context, initiativeID string) ([]domain.RemoteRun, error)
- func (db *DB) ListInitiativeRollups(ctx context.Context) ([]InitiativeRollup, error)
- func (db *DB) ListInitiativeStatusEvents(ctx context.Context, initiativeID string) ([]TimelineStatusEvent, error)
- func (db *DB) ListInitiatives(ctx context.Context) ([]domain.Initiative, error)
- func (db *DB) ListIntegrationLinks(ctx context.Context, integration, kind string) ([]IntegrationLink, error)
- func (db *DB) ListJournal(ctx context.Context, changeSetID string) ([]domain.ApplyJournalEntry, error)
- func (db *DB) ListMetrics(ctx context.Context, initiativeID string, now time.Time) ([]domain.OutcomeMetric, error)
- func (db *DB) ListModelPhaseCosts(ctx context.Context, initiativeID string) ([]PhaseCostRow, error)
- func (db *DB) ListObjectives(ctx context.Context, initiativeID string) ([]domain.Objective, error)
- func (db *DB) ListObservations(ctx context.Context, metricID string) ([]domain.MetricObservation, error)
- func (db *DB) ListOperationsByInitiative(ctx context.Context, initiativeID string) ([]domain.Operation, error)
- func (db *DB) ListProjectMemory(ctx context.Context, limit int) ([]domain.ProjectMemory, error)
- func (db *DB) ListProjects(ctx context.Context) ([]ProjectRecord, error)
- func (db *DB) ListPushSubscriptions(ctx context.Context) ([]PushSubscription, error)
- func (db *DB) ListQualityResults(ctx context.Context, initiativeID string) ([]domain.QualityResult, error)
- func (db *DB) ListQuestions(ctx context.Context, initiativeID string) ([]domain.Question, error)
- func (db *DB) ListRemoteRuns(ctx context.Context, activeOnly bool, limit int) ([]domain.RemoteRun, error)
- func (db *DB) ListRequirements(ctx context.Context, initiativeID string) ([]domain.Requirement, error)
- func (db *DB) ListReviewTelemetry(ctx context.Context, initiativeID string) ([]domain.ReviewTelemetry, error)
- func (db *DB) ListRunEvents(ctx context.Context, runID string, after int64, limit int) (RunEventPage, error)
- func (db *DB) ListRunEventsAfterID(ctx context.Context, afterID int64, limit int) ([]RunEventRow, error)
- func (db *DB) ListSecretAllowlist(ctx context.Context) ([]domain.SecretAllowlistEntry, error)
- func (db *DB) ListStaleItems(ctx context.Context, initiativeID string) ([]domain.StaleItem, error)
- func (db *DB) ListSuggestedAnswers(ctx context.Context, initiativeID string) ([]domain.SuggestedAnswer, error)
- func (db *DB) ListTasks(ctx context.Context, initiativeID string) ([]domain.Task, error)
- func (db *DB) ListUISessions(ctx context.Context) ([]UISession, error)
- func (db *DB) ListUnfinishedOperations(ctx context.Context) ([]domain.Operation, error)
- func (db *DB) LookupCaptureToken(ctx context.Context, tokenHash string) (string, error)
- func (db *DB) LookupUISession(ctx context.Context, secretHash string, now time.Time) (UISession, bool, error)
- func (db *DB) MarkChangeSetApplied(ctx context.Context, changeSetID, workspaceSnapshotDigest, actor string) error
- func (db *DB) MarkChangeSetReverted(ctx context.Context, changeSetID, actor string) error
- func (db *DB) MarkDocCommentPromoted(ctx context.Context, commentID, questionID string) error
- func (db *DB) MarkOutboxDelivered(ctx context.Context, rowID string) error
- func (db *DB) MarkOutboxFailed(ctx context.Context, rowID, lastError string, nextAttempt time.Time, dead bool) error
- func (db *DB) MarkRequirementFailed(ctx context.Context, requirementID, actor string) error
- func (db *DB) MarkRequirementVerified(ctx context.Context, requirementID, actor string) error
- func (db *DB) MarkRequirementWaived(ctx context.Context, requirementID, actor string) error
- func (db *DB) MaxEventSeq(ctx context.Context) (int64, error)
- func (db *DB) MaxRunEventID(ctx context.Context) (int64, error)
- func (db *DB) MergeTasks(ctx context.Context, initiativeID, keepID, mergeID string) (*domain.Task, error)
- func (db *DB) MetricHypotheses(ctx context.Context, initiativeID, metricID string) ([]domain.Assertion, error)
- func (db *DB) NeedsHumanJudgment(ctx context.Context, initiativeID string, reason domain.JudgmentReason, ...) error
- func (db *DB) NextOutbox(ctx context.Context, subscriber string) (*OutboxRow, error)
- func (db *DB) ObjectivesWithoutMetrics(ctx context.Context, initiativeID string) ([]domain.Objective, error)
- func (db *DB) ObjectivesWithoutRequirements(ctx context.Context, initiativeID string) ([]domain.Objective, error)
- func (db *DB) OutcomeChain(ctx context.Context, initiativeID string, now time.Time) (domain.OutcomeChainGaps, error)
- func (db *DB) ParkForBudget(ctx context.Context, initiativeID, parkedFrom, detail string) error
- func (db *DB) PassedCriterionKeys(ctx context.Context, requirementID string) (map[string]bool, error)
- func (db *DB) PendingSteeringNotes(ctx context.Context, initiativeID string) ([]HeldSteeringNote, error)
- func (db *DB) PreviousInitiativeStatus(ctx context.Context, initiativeID string, beforeSeq int64, skipRunning bool) (string, error)
- func (db *DB) PutIntegrationLink(ctx context.Context, l IntegrationLink) error
- func (db *DB) QualityHistory(ctx context.Context, initiativeID string) ([]domain.QualityResult, error)
- func (db *DB) ReconcileChangeSets(ctx context.Context) ([]ChangeSetRecovery, error)
- func (db *DB) RecordArtifactVersion(ctx context.Context, initiativeID string, kind domain.ArtifactKind, ...) (bool, error)
- func (db *DB) RecordExternalNote(ctx context.Context, initiativeID, actor, note string) error
- func (db *DB) RecordHumanEvidence(ctx context.Context, initiativeID, requirementID string, ...) error
- func (db *DB) RecordObservation(ctx context.Context, o *domain.MetricObservation, actor string, now time.Time) (before, after domain.MetricStatus, err error)
- func (db *DB) RecordPushResult(ctx context.Context, subID, lastErr string) error
- func (db *DB) RecordQualityMeasurement(ctx context.Context, initiativeID string, results []domain.QualityResult, ...) error
- func (db *DB) RedeemPairingCode(ctx context.Context, codeHash string, s UISession, secretHash string, ...) (sess UISession, burned int64, err error)
- func (db *DB) RegisterProject(ctx context.Context, name, rootPath, projectID string) (string, error)
- func (db *DB) RelateAssertions(ctx context.Context, initiativeID, fromID string, edge domain.EdgeType, ...) error
- func (db *DB) ReleaseInitiativeClaim(ctx context.Context, initiativeID string, to domain.InitiativeStatus, ...) error
- func (db *DB) RenewPushSubscription(ctx context.Context, subID, tokenHash string, s PushSubscription, ...) (PushSubscription, error)
- func (db *DB) ReopenDecision(ctx context.Context, decisionID, actor string) error
- func (db *DB) ReorderTasks(ctx context.Context, initiativeID string, orderedIDs []string) error
- func (db *DB) ReplaceRequirementObjectives(ctx context.Context, initiativeID, requirementID string, objectiveIDs []string) error
- func (db *DB) ReplaceSuggestedAnswers(ctx context.Context, initiativeID string, answers []domain.SuggestedAnswer) error
- func (db *DB) ReplaceTaskDependencies(ctx context.Context, initiativeID, taskID string, depTaskIDs []string) error
- func (db *DB) ReplaceTaskRequirements(ctx context.Context, initiativeID, taskID string, requirementIDs []string) error
- func (db *DB) RequirementOutcomeDrift(ctx context.Context, initiativeID string, now time.Time) ([]domain.RequirementOutcomeDrift, error)
- func (db *DB) RequirementsWithoutObjectives(ctx context.Context, initiativeID string) ([]domain.Requirement, error)
- func (db *DB) ResolveDecision(ctx context.Context, decisionID, resolution, actor string) error
- func (db *DB) ResumeFromBudget(ctx context.Context, initiativeID, actor string) (bool, error)
- func (db *DB) RevokeAllUISessions(ctx context.Context, at time.Time) (int64, error)
- func (db *DB) RevokeSecretAllowlist(ctx context.Context, id string) error
- func (db *DB) RevokeUISession(ctx context.Context, id string, at time.Time) (bool, error)
- func (db *DB) RunEventCostTotals(ctx context.Context, runID string) (in, out int64, cost float64, err error)
- func (db *DB) RunEventsChanged() <-chan struct{}
- func (db *DB) RunningOperationID(ctx context.Context, initiativeID string) string
- func (db *DB) SQL() *sql.DB
- func (db *DB) SaveRiskProfile(ctx context.Context, p *domain.RiskProfile) error
- func (db *DB) SecretAllowlistFingerprints(ctx context.Context) (map[string]bool, error)
- func (db *DB) SecretFingerprintKey(ctx context.Context) ([]byte, error)
- func (db *DB) SeedRequirementsFrom(ctx context.Context, destInitiativeID, sourceInitiativeID string) (int, error)
- func (db *DB) SetAssertionBasis(ctx context.Context, initiativeID, fromType, fromID string, ...) error
- func (db *DB) SetAssertionStatus(ctx context.Context, assertionID string, status domain.AssertionStatus, ...) error
- func (db *DB) SetChangeSetCommit(ctx context.Context, changeSetID, sha, actor string) error
- func (db *DB) SetChangeSetGitWarning(ctx context.Context, changeSetID, warning, actor string) error
- func (db *DB) SetChangeSetNoOp(ctx context.Context, changeSetID string, noOp bool) error
- func (db *DB) SetChangeSetReview(ctx context.Context, changeSetID, reviewID, actor string) error
- func (db *DB) SetChangeSetReviewUnavailable(ctx context.Context, changeSetID, reason, actor string) error
- func (db *DB) SetContextDocDescription(ctx context.Context, id, descriptionDigest string) error
- func (db *DB) SetDaemonMeta(ctx context.Context, key, value string) error
- func (db *DB) SetDecisionRecommendation(ctx context.Context, decisionID, rec, convergedBy, actor string) error
- func (db *DB) SetFindingDisposition(ctx context.Context, findingID string, disp domain.Disposition, actor string) error
- func (db *DB) SetFindingNote(ctx context.Context, findingID, note, actor string) error
- func (db *DB) SetInitiativeBudgetCap(ctx context.Context, initiativeID string, capUSD *float64, actor string) error
- func (db *DB) SetInitiativeGitBranch(ctx context.Context, initiativeID, branch, actor string) error
- func (db *DB) SetInitiativePRURL(ctx context.Context, initiativeID, prURL, actor string) error
- func (db *DB) SetInitiativeStatus(ctx context.Context, initiativeID string, status domain.InitiativeStatus, ...) error
- func (db *DB) SetOperationFailed(ctx context.Context, opID string, status domain.OperationStatus, errMsg string) error
- func (db *DB) SetOperationResultRef(ctx context.Context, opID, ref string) error
- func (db *DB) SetOperationStage(ctx context.Context, initiativeID, stage string) error
- func (db *DB) SetOperationStatus(ctx context.Context, opID string, status domain.OperationStatus, ...) error
- func (db *DB) SetPushSubscriptionEvents(ctx context.Context, subID string, events []string) error
- func (db *DB) SetReadCursor(ctx context.Context, scope string, seq int64) error
- func (db *DB) SetRemoteRunAgentRun(ctx context.Context, remoteRunID, agentRunID string) error
- func (db *DB) SetRunManifestReview(ctx context.Context, runID string, t domain.ReviewTelemetry) error
- func (db *DB) SetRunNote(ctx context.Context, runID, note string) error
- func (db *DB) SetRunStatus(ctx context.Context, runID string, status domain.RunStatus, actor string) error
- func (db *DB) SetTaskDependencies(ctx context.Context, initiativeID, taskID string, depTaskIDs []string) error
- func (db *DB) SetTaskStatus(ctx context.Context, taskID string, status domain.TaskStatus) error
- func (db *DB) SplitTask(ctx context.Context, initiativeID, originalID string, specs []SplitTaskSpec, ...) ([]*domain.Task, error)
- func (db *DB) StartAutomationRun(ctx context.Context, automation, target, trigger string, startedAtMS int64) (AutomationRun, error)
- func (db *DB) SumRunUsage(ctx context.Context, initiativeID string) (domain.RunUsage, int, error)
- func (db *DB) SupersedeAssertions(ctx context.Context, initiativeID, supersededBy string) error
- func (db *DB) SupersedeModelObjectivesExcept(ctx context.Context, initiativeID, supersededBy string, keepIDs []string) error
- func (db *DB) SupersedeRequirements(ctx context.Context, initiativeID, supersededBy string) error
- func (db *DB) SupersedeRequirementsExcept(ctx context.Context, initiativeID, supersededBy string, keepIDs []string) error
- func (db *DB) SyncAssertionInvalidations(ctx context.Context, initiativeID string) error
- func (db *DB) TakeSteeringNotes(ctx context.Context, initiativeID, taskID string) ([]HeldSteeringNote, error)
- func (db *DB) TaskEdges(ctx context.Context, initiativeID, taskID string) (requirementIDs, dependsOn []string, err error)
- func (db *DB) TouchUISession(ctx context.Context, id string, at time.Time) error
- func (db *DB) TransitionChangeSet(ctx context.Context, changeSetID string, from, to domain.ChangeSetStatus, ...) error
- func (db *DB) TransitionChangeSetWithNote(ctx context.Context, changeSetID string, from, to domain.ChangeSetStatus, ...) error
- func (db *DB) TransitionInitiative(ctx context.Context, initiativeID string, to domain.InitiativeStatus, ...) error
- func (db *DB) UnlinkRequirementObjective(ctx context.Context, initiativeID, requirementID, objectiveID, actor string) error
- func (db *DB) UnverifyRequirement(ctx context.Context, requirementID, actor string) error
- func (db *DB) UpdateMetric(ctx context.Context, m *domain.OutcomeMetric, actor string) error
- func (db *DB) UpdateObjective(ctx context.Context, o *domain.Objective, actor string) error
- func (db *DB) UpdateRemoteRun(ctx context.Context, runID string, u RemoteRunUpdate) error
- func (db *DB) UpdateRequirement(ctx context.Context, r *domain.Requirement) error
- func (db *DB) UpdateTask(ctx context.Context, initiativeID, taskID, title, statement string, ...) error
- func (db *DB) UpsertPushSubscription(ctx context.Context, s PushSubscription) (PushSubscription, bool, error)
- func (db *DB) WireDecisionDerivedFromQuestion(ctx context.Context, initiativeID, decisionID, questionID string) error
- func (db *DB) WireDocConsumes(ctx context.Context, initiativeID, runID string, docIDs []string) error
- func (db *DB) WireRequirementDerivedFromDecision(ctx context.Context, initiativeID, requirementID, decisionID string) error
- type EdgeToWrite
- type Event
- type EventRow
- type HeldSteeringNote
- type InitiativeBudget
- type InitiativeRollup
- type IntegrationLink
- type MetricRef
- type NotFoundError
- type OutboxInsert
- type OutboxRow
- type OutboxStats
- type PhaseCostRow
- type ProjectRecord
- type PushSubscription
- type QualityLink
- type RemoteRunUpdate
- type RunEventPage
- type RunEventRow
- type RunInfo
- type SplitTaskSpec
- type TimelineChangeSetEvent
- type TimelineDecisionEvent
- type TimelineStatusEvent
- type UISession
- type VerificationEvidenceRef
Constants ¶
const ( AutomationRunning = "running" AutomationSucceeded = "succeeded" AutomationFailed = "failed" AutomationSkipped = "skipped" )
Automation run statuses.
const ( OutboxPending = "pending" OutboxDelivered = "delivered" OutboxDead = "dead" )
Outbox row statuses.
const ( RunEventsPerRunMax = 5000 RunEventsKeepRuns = 50 // RunEventsPageMax bounds one page of ListRunEvents. RunEventsPageMax = 500 )
Run events: the normalized stream of a coding agent's run (domain.RunEvent). Storage is bounded two ways, because a chatty agent on a long task can emit thousands of events and nothing here is meant to be an archive:
- per run, the newest RunEventsPerRunMax events are kept. seq keeps counting, so a client's cursor stays valid; a page reports FirstSeq so a reader can tell that older events were dropped.
- per project, only the RunEventsKeepRuns most recent runs keep any events. The run's change set, findings and manifest are the durable record; the event stream is the live view and the run report.
const ActorOrchestrator = "orchestrator"
ActorOrchestrator is the default event actor for deterministic workflow steps.
const BudgetExceededEvent = "initiative.budget_exceeded"
BudgetExceededEvent is the event type appended when a spending cap stops a run. The integration bus publishes it as initiative.budget_exceeded.
const BurnedCodeRetention = 7 * 24 * time.Hour
BurnedCodeRetention is how long a burned pairing code's row is kept after it burns, so the owner can be told about it (BurnedPairingCodes).
const EvalRegressedEvent = "automation.eval_regressed"
EvalRegressedEvent is the event type appended when a scheduled eval run regresses against its baseline (aggregate: the automation). The integration bus publishes it as eval.regressed.
const HumanActor = "human"
HumanActor is the actor identity for human actions (§11, §15).
const RemoteRunProgressMax = 64 << 10
RemoteRunProgressMax bounds the stored progress log. It is a live view and a post-restart summary, not an archive: the remote server keeps the full event history for as long as it keeps the conversation.
Variables ¶
var ErrCaptureTokenUnknown = errors.New("capture token unknown")
ErrCaptureTokenUnknown is returned for an unknown or wrong capture token — one error, so the unauthenticated capture route says nothing about which tokens exist (the same single-sourcing as push renewal).
var ErrDependsOnCycle = errors.New("that dependency would create a cycle")
ErrDependsOnCycle is returned by SetTaskDependencies when the requested depends_on set would introduce a dependency cycle (review M5). It is checked again INSIDE the write transaction here, not only by the handler's own pre-check (wouldCycle): the daemon's per-initiative lockPlanEdit serializes the common race (two concurrent set-depends_on requests) away, but this is the defense-in-depth layer for any other path that reaches this method without going through that lock.
No "store: " prefix (review LOW #10): the handler surfaces this sentinel's Error() text verbatim to the API caller as a 400 body, and daemon/ errors.go's whole contract is that "the storage layer's own strings" never become the product's error messages -- a literal "store: " leaking through here, for the one sentinel genuinely meant to be read by a person, contradicted it.
var ErrInitiativeNotClaimable = errors.New("store: initiative is not in a claimable state")
ErrInitiativeNotClaimable reports that an initiative could not be claimed: another request holds it, or it is not in a state the operation runs from.
var ErrMergeCycle = errors.New("merging would create a dependency cycle")
ErrMergeCycle is returned by MergeTasks, wrapped with the cycling task's id, when the merge would introduce a dependency cycle (review H4). The handler maps it to 400, the same as the depends-on endpoint's own cycle refusal, and surfaces its Error() text verbatim -- see ErrSelfMerge's comment on why it carries no "store: " prefix (review LOW #10).
var ErrOperationNotLive = errors.New("store: operation is not pending or running")
ErrOperationNotLive reports that a cancel found no pending-or-running row: the operation had already finished, or the id does not exist. Callers report it as "not cancellable" rather than treating it as a write failure.
var ErrPairingCodeBurned = errors.New("this pairing code was cancelled because too many wrong codes were tried at the sign-in page while it was outstanding (someone may be guessing). Run `idea ui pair` on the daemon's machine for a new one")
ErrPairingCodeBurned is returned for a real code that was burned: enough wrong codes were tried while it was outstanding that it can no longer be redeemed. Saying so leaks nothing a guesser can use -- only the holder of the code can see it -- and tells the owner why their code failed.
var ErrPairingCodeInvalid = errors.New("pairing code is invalid, expired or already used")
ErrPairingCodeInvalid is returned when a pairing code is unknown, expired or already used. One error for all three on purpose: telling a guesser which of them it hit is telling it something.
var ErrPushRenewalDenied = errors.New("push subscription renewal refused")
ErrPushRenewalDenied is returned by RenewPushSubscription for an unknown subscription or a wrong renewal token -- one error for both, so the unauthenticated renewal route says nothing about which ids exist.
var ErrRemoteRunNotFound = errors.New("store: remote run not found")
ErrRemoteRunNotFound is returned for an unknown remote run id.
var ErrSelfMerge = errors.New("cannot merge a task with itself")
ErrSelfMerge is returned by MergeTasks when keepID == mergeID (review H4): a self-merge used to pass both existence guards and then delete the survivor, since nothing checked the two ids were distinct.
No "store: " prefix (review LOW #10): unlike most of this package's sentinel errors, the handler surfaces THIS ONE's Error() text verbatim to the API caller as a 400 body -- daemon/errors.go's whole contract is that "the storage layer's own strings" never become the product's error messages, and a literal "store: " leaking through here contradicted it for the one sentinel that is genuinely meant to be read by a person.
Functions ¶
func AllowlistKey ¶ added in v0.6.0
AllowlistKey is the composite key SecretAllowlistFingerprints's set uses, and the key a caller (e.g. workflow.filterAllowlisted) must build to look a match up in it: an allowlist entry (and therefore a sweep denial it can suppress) is scoped to fingerprint AND path together (review H3) -- a value allowlisted in one file must still block in another.
func DetectTaskCycle ¶
DetectTaskCycle returns the id of a task that participates in a dependency cycle, or "" (three-color DFS). It is the single canonical cycle detector, shared by the plan checks and the doctor edge audit.
func IsStorageFailure ¶
IsStorageFailure reports whether err came from the database driver or the filesystem, rather than from a domain rule. Those errors carry schema names, constraint text and absolute state paths, so callers must not show them to a client verbatim.
This is a type check, not a search for substrings: "UNIQUE constraint failed: change_sets.id", "attempt to write a readonly database" and "open /Users/<name>/.local/share/…: permission denied" share no vocabulary, and a list of markers will always be one driver message behind.
func PushSubscriberName ¶ added in v0.7.0
PushSubscriberName is the integration-bus subscriber name of a push subscription: its cursor and outbox rows are keyed by it.
func ValidateMetric ¶ added in v0.7.0
func ValidateMetric(m *domain.OutcomeMetric) error
ValidateMetric reports why m cannot be stored, or nil.
Types ¶
type AgentRunStats ¶ added in v0.6.0
AgentRunStats summarizes an initiative's coding-agent runs (C3, wave 3 contract): how many ran, their total duration, and each run's own output (for ParseAgentCostUSD's best-effort cost parse), oldest first.
type ArtifactRollup ¶
ArtifactRollup is the minimal artifact info phase derivation needs.
type ArtifactView ¶
type ArtifactView struct {
VersionID string `json:"id"`
ArtifactID string `json:"artifact_id"`
InitiativeID string `json:"initiative_id"`
Kind domain.ArtifactKind `json:"kind"`
Version int `json:"version"`
Status string `json:"status"`
BodyDigest string `json:"body_digest"`
ProducedByRun string `json:"produced_by_run"`
CreatedAt time.Time `json:"created_at"`
}
ArtifactView is an artifact version joined with its family kind + initiative.
type AutomationRun ¶ added in v0.7.0
type AutomationRun struct {
ID string `json:"id"`
Automation string `json:"automation"`
Target string `json:"target,omitempty"`
Trigger string `json:"trigger"`
Status string `json:"status"`
StartedAt int64 `json:"started_at_ms"`
FinishedAt int64 `json:"finished_at_ms,omitempty"`
CostUSD *float64 `json:"cost_usd,omitempty"`
Summary string `json:"summary,omitempty"`
Error string `json:"error,omitempty"`
ReportPath string `json:"report_path,omitempty"`
}
AutomationRun is one run of a scheduled background job.
type CaptureToken ¶ added in v0.7.0
CaptureToken is one channel's capability to create draft initiatives in a project (migration 53). Only metadata is ever read back; the token itself is SHA-256-hashed and never listed.
type ChangeSetPatchRef ¶ added in v0.6.0
ChangeSetPatchRef is the minimal projection of a change set needed to recompute its no_op flag from its patch manifest.
type ChangeSetRecovery ¶
type ChangeSetRecovery struct {
ChangeSetID string
InitiativeID string
Status domain.ChangeSetStatus
TaskID string
// LatestJournalState is the most recent apply-journal state, or "" if none.
LatestJournalState domain.ApplyState
// PreImageDigest is the workspace pre-image to restore, scoped to the
// CURRENT (interrupted) apply attempt only -- i.e. a workspace_mutated
// row recorded after the most recent "prepared" row for this change set
// (H3): apply_journal accumulates rows across every apply/revert/
// re-apply of a change set, never cleared, so picking merely the newest
// non-empty digest regardless of which attempt it belonged to let a
// re-apply crashed BEFORE its own mutation was recorded inherit the
// FIRST apply's committed digest instead of correctly reporting "no
// bytes written yet". Empty when no mutation was recorded for this
// attempt.
PreImageDigest string
// FromStatus is the status this change set transitioned FROM when it
// entered `applying`, recovered from the status_changed event (H3): both
// approved->applying (a fresh apply) and reverted->applying (a re-apply)
// are legal, and a crash-recovery that always assumes Approved
// mislabels an in-progress re-apply of an already-reverted change set as
// merely "approved" -- contradicting the reverted->applying edge added
// specifically for this recovery (changeset.go's legalChangeSetTransition)
// and CHANGELOG.md's documented promise that a failed re-apply recovers
// back to `reverted`, not `approved`. Empty (ChangeSetStatus("")) if no
// such event is found, in which case the caller falls back to Approved
// (the only possibility before re-apply existed).
FromStatus domain.ChangeSetStatus
}
ChangeSetRecovery describes a change set stuck in a non-terminal state that startup reconciliation must move to a terminal state (and, for an interrupted apply, restore the workspace).
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB wraps a SQLite connection pool with the schema and event helpers.
func Open ¶
Open opens (or creates) the SQLite database at path, applies migrations, and configures WAL + foreign keys + busy timeout. The daemon is the single writer (§4 D1), so the pool is deliberately small to avoid SQLITE_BUSY.
func OpenGlobal ¶
OpenGlobal opens the global registry database (projects, daemon_meta).
func (*DB) AddTaskDependencies ¶
func (db *DB) AddTaskDependencies(ctx context.Context, initiativeID, taskID string, depTaskIDs []string) error
AddTaskDependencies wires depends_on edges from taskID to each depTaskID in one transaction. Used by the execution-plan two-pass resolution so backward (and normalized) dependency references resolve after all tasks exist.
func (*DB) AnswerQuestion ¶
AnswerQuestion records a human answer (human_approved) and resolves the question.
func (*DB) AppendAutomationEvent ¶ added in v0.7.0
func (db *DB) AppendAutomationEvent(ctx context.Context, automation, eventType, operation string) error
AppendAutomationEvent appends a project-level automation event (e.g. automation.eval_regressed) for the integration bus and the activity feed.
func (*DB) AppendJournal ¶
AppendJournal inserts one apply-journal record (§39).
func (*DB) AppendRemoteRunProgress ¶ added in v0.7.0
func (db *DB) AppendRemoteRunProgress(ctx context.Context, runID, fromEventID, lastEventID string, events int, lines []string) (applied bool, err error)
AppendRemoteRunProgress folds newly ingested events into the run: lines (already redacted by the caller) are appended to the progress log, which is trimmed from the front to RemoteRunProgressMax, and the cursor advances to lastEventID. It is guarded on the cursor the caller read (fromEventID), so two ingesters racing over the same events -- the executor and a reconciler -- cannot both append them: the loser matches nothing and gets applied=false, and re-reads the cursor.
func (*DB) AppendRemoteRunProgressEvents ¶ added in v0.7.0
func (db *DB) AppendRemoteRunProgressEvents(ctx context.Context, runID, fromEventID, lastEventID string, events int, lines []string, evs []domain.RunEvent) (applied bool, err error)
AppendRemoteRunProgressEvents is AppendRemoteRunProgress that also stores the same remote events, normalized (already redacted by the caller), on the agent run this remote run feeds (remote_runs.run_id) -- in the same transaction and under the same cursor guard, so the exactly-once ingestion the progress log has holds for the event stream too. With no run id recorded (a run dispatched before run events existed) the events are dropped and the progress log is still written.
func (*DB) AppendRunEvents ¶ added in v0.7.0
func (db *DB) AppendRunEvents(ctx context.Context, runID string, evs []domain.RunEvent) ([]domain.RunEvent, error)
AppendRunEvents stores events for runID, assigning each the next seq. The caller has already redacted them; they are bounded here. Returns the events as stored. RunID on each event is overwritten with runID.
func (*DB) AppendSuggestedAnswers ¶
func (db *DB) AppendSuggestedAnswers(ctx context.Context, initiativeID string, answers []domain.SuggestedAnswer) error
AppendSuggestedAnswers appends a batch of AI-suggested answers (used for incremental, chunked generation so progress is observable).
func (*DB) Apply ¶
Apply runs fn and appends ev in a single transaction. If fn returns an error, neither the state mutation nor the event is persisted (§32 atomicity).
func (*DB) ApproveRequirements ¶
ApproveRequirements transitions all draft requirements of an initiative to approved (§17). Called when the PRD review passes or a human approves.
func (*DB) AttachTaskEdges ¶ added in v0.6.0
AttachTaskEdges populates RequirementIDs/DependsOn on each of tasks in place, from graph_edges (see TaskEdges). One query per task -- Plan pages list at most a handful of tasks, so this trades a little redundancy for reusing the same per-task helper the single-task handlers use.
func (*DB) AuditGraphEdges ¶
AuditGraphEdges reports traceability gaps for an initiative (§M2 tail): each task missing an `implements` edge, each requirement/assertion/artifact missing a `produced_by` edge, and cyclic task dependencies (DFS cycle check). It is read-only and returns findings rather than persisting them.
func (*DB) BurnedPairingCodes ¶ added in v0.7.0
BurnedPairingCodes reports how many pairing codes burned at or after since, and when the latest did (zero when none did).
func (*DB) CancelOperationStatus ¶
CancelOperationStatus marks an operation cancelled, but only while it is still pending or running.
Separate from SetOperationStatus, and compare-and-swap, because the two writers are not equals. The operation's own goroutine knows what actually happened and must be able to record it unconditionally; a cancel is a request, and a request that arrives after the work finished has to lose.
Both used to be unconditional, so they raced and whichever reached SQLite last won -- an apply that had already committed files and marked the change set applied could be recorded as cancelled, the operation log disagreeing with the disk. Guarding only the cancel side fixes that in both orders: a late cancel is a no-op, and a cancel during a run is overwritten by the goroutine's terminal write when the work turns out to have completed anyway.
Modelled on TransitionChangeSet, the CAS precedent in this package.
func (*DB) ChangeSetWorkspaceTimes ¶ added in v0.7.0
func (db *DB) ChangeSetWorkspaceTimes(ctx context.Context, initiativeID string) (map[string]time.Time, error)
ChangeSetWorkspaceTimes returns, for every change set of the initiative that ever touched the working tree, the last time it did: its most recent committed apply or rolled-back revert in the apply journal. Both count because both change the code a piece of verification evidence was recorded against -- a revert after a pass removes exactly what was verified.
applied_at is NULL on journal rows written before it existed, and is never set on a rolled_back row; created_at is the same instant for both (MarkChangeSetApplied/Reverted write them from one clock read), so it is what is read.
func (*DB) ClaimInitiativeRunning ¶
func (db *DB) ClaimInitiativeRunning(ctx context.Context, initiativeID string, from ...domain.InitiativeStatus) error
ClaimInitiativeRunning marks an initiative running, but only from one of the states given. It reports ErrInitiativeNotClaimable when no row matched.
This is the atomic half of "is it already running?". Seven Runtime entry points asked that question and four of them never set the flag, so two concurrent requests both passed the check -- a double-clicked "Revise plan" let one goroutine delete and recreate the task set while the other wrote dependency edges to task ids that no longer existed, after which every later revise was refused.
A Go-level GetInitiative-then-set cannot fix that: the read and the write are not atomic with each other, which is the same check-then-act the finding is about. SetInitiativeStatus is an unconditional UPDATE and cannot be used for a claim. TransitionChangeSet has been the compare-and-swap precedent in this package all along, and this follows it.
func (*DB) ClaimNoOpBackfill ¶ added in v0.6.0
ClaimNoOpBackfill reports whether THIS call is the one that gets to run the no_op backfill: it inserts the marker row and returns true only when the insert actually happened. Every later caller -- including a concurrent daemon start racing this one, or the next time this project is opened -- finds the row already present and gets false. The marker is never cleared, so the backfill is a true one-time operation per project database, not a per-daemon-lifetime one.
func (*DB) ClearStaleItem ¶ added in v0.6.0
ClearStaleItem explicitly acknowledges one stale item, clearing it (review A4 #5: "explicitly acknowledging the item clears the stale state").
func (*DB) ClearStaleItemsForInitiative ¶ added in v0.6.0
ClearStaleItemsForInitiative clears every active TASK and CHANGE-SET stale mark for an initiative -- never a REQUIREMENT mark (review M5) -- when re-planning regenerates the execution plan (review A4 #5: "re-planning clears the stale state"). Used by RevisePlan and ReopenPhase.
A requirement's staleness is a property of the requirement itself (the decision it was derived from changed), not of the specific plan built for it: regenerating tasks does not re-verify the requirement, so a fresh plan has done nothing to make "this requirement's basis changed" untrue. Before this fix, revise-plan cleared requirement marks too, so a decision reopened mid-initiative could be silently forgotten the moment the plan was regenerated -- with the requirement itself never re-examined against the new answer.
func (*DB) ClearVerificationEvidence ¶
ClearVerificationEvidence deletes every evidence row for a requirement. A new human judgment (pass/fail/waived) supersedes all prior evidence for the requirement's criteria — otherwise a stale pass row would resurrect a requirement that a human has since failed or waived (evidence is otherwise append-only and PassedCriterionKeys counts every pass regardless of newer rows).
func (*DB) CompleteInitiative ¶ added in v0.4.0
CompleteInitiative writes `complete`, but never over a failed initiative.
This is a guard on the write, not an enumeration of the states it accepts. InitiativeStatus has six values, so listing the other five would be the exact complement of the one refusal -- and a seventh status added later would be silently excluded, turning a legitimate completion into a refusal with no test failing. The invariant is "not failed", so that is what the SQL says.
The defect: VerifyInitiative concluded `complete` for an initiative with no requirements at all (the gate loop never runs, so allVerified stays true) and wrote it with SetInitiativeStatus, unconditionally. DX audit 7 reproduced a bare `idea verify` on an initiative that failed at framing with a 401 -- zero requirements, zero tasks, zero change sets -- printing `✓ verified status: complete`, exiting 0, and discarding the failure_reason.
Runtime.RunVerificationGate refuses the request synchronously; this refuses the write, which covers any future caller that does not go through the Runtime and the window where a concurrent FailInitiative lands.
The predicate is failure_reason, not just status, and that is load-bearing. Five entry points -- apply, revert, revise, retry, reopen-phase -- claim `running` FROM `failed` by design, and ClaimInitiativeRunning deliberately leaves failure_reason intact so the release can restore it. During any of them the row is a failed initiative wearing a running status: a status-only guard passes, this write lands, and it clears the reason PERMANENTLY, since the release only writes the status back. A commit review caught it by reproducing exactly that against the real handler. `failed` is a transient display of the status; the recorded reason is the durable fact.
review H7: `status != failed` alone also passes while status == running with an empty failure_reason -- the documented apply-then-verify sequence (`idea apply` does not wait for its operation) runs exactly there, and TestVerifyIsAllowedWhileAnApplyIsInFlight asserts that must keep working, so `running` is deliberately NOT excluded here. What closes the actual hazard (verify's CompleteInitiative racing apply/execute/revert while they are still actively mutating files, not merely while the row still reads `running` after they finished) is VerifyInitiative now taking the same engine mutex Execute/ApplyChangeSet/RevertChangeSet hold for their whole duration (see verify.go) -- verify cannot even reach this write until their real work is over, which is the actual invariant this needs, not a DB-status proxy for it that would also refuse the legitimate case above. The residual sliver -- apply's own release() running a moment after ApplyChangeSet returns (mutex released) but this write lands first -- is closed by making that release a CAS too (ReleaseInitiativeClaim).
func (*DB) CountChangeSetsByHumanID ¶ added in v0.4.0
CountChangeSetsByHumanID reports how many change sets in this project share a human id.
Human ids are assigned per initiative, so CHG-1 exists once per initiative while apply/review/change resolve project-wide. `idea next` printed the human id unconditionally and so prescribed `idea apply CHG-1`, which refuses as ambiguous the moment a project has two initiatives with change sets. Callers use this to print the full id in exactly that case, and the friendly one otherwise.
func (*DB) CountTerminalRemoteRuns ¶ added in v0.7.0
CountTerminalRemoteRuns is how many of a task's remote runs are over (collected, failed or cancelled). The next attempt number is this plus one, which is what makes the idempotency key deterministic: a crash leaves the current attempt non-terminal, so the retry computes the same number.
func (*DB) CreateArtifact ¶
func (db *DB) CreateArtifact(ctx context.Context, a *domain.Artifact, v *domain.ArtifactVersion) error
CreateArtifact inserts an artifact family and its first version.
func (*DB) CreateAssertion ¶
CreateAssertion inserts an assertion and appends its event.
func (*DB) CreateCaptureToken ¶ added in v0.7.0
func (db *DB) CreateCaptureToken(ctx context.Context, projectID, tokenHash, label string) (string, error)
CreateCaptureToken stores a token's hash for a project and returns the row id.
func (*DB) CreateChangeSet ¶
CreateChangeSet inserts a change set, assigning its HumanID "CHG-N" from the per-initiative change_sets counter, and appends its creation event.
func (*DB) CreateContextBundle ¶
func (db *DB) CreateContextBundle(ctx context.Context, bundleID, runID, digest string, entries []domain.ContextEntry) error
CreateContextBundle persists a context bundle and its entries.
func (*DB) CreateContextDoc ¶
CreateContextDoc inserts a context document and appends its creation event.
func (*DB) CreateDecision ¶
CreateDecision inserts a decision with code DEC-xx.
func (*DB) CreateDecisionDiscussion ¶
CreateDecisionDiscussion appends one message to a decision discussion thread.
func (*DB) CreateDissent ¶
CreateDissent preserves a dissenting view (§8).
func (*DB) CreateDocComment ¶
CreateDocComment inserts one human comment anchored to an artifact version.
func (*DB) CreateFinding ¶
CreateFinding inserts a review finding.
func (*DB) CreateInitiative ¶
CreateInitiative inserts an initiative and appends its creation event.
func (*DB) CreateMetric ¶ added in v0.7.0
CreateMetric inserts an outcome metric (MET-n) for an objective and wires metric --measures--> objective.
func (*DB) CreateMetricHypothesis ¶ added in v0.7.0
func (db *DB) CreateMetricHypothesis(ctx context.Context, initiativeID, metricID, statement, source, producedByRun string) (*domain.Assertion, error)
CreateMetricHypothesis records "we believe <statement>" as a hypothesis assertion predicting movement in a metric (assertion --predicts--> metric), in one transaction.
func (*DB) CreateObjective ¶ added in v0.7.0
CreateObjective inserts an objective with an initiative-scoped code (OBJ-n).
func (*DB) CreateOperation ¶
func (db *DB) CreateOperation(ctx context.Context, projectID, initiativeID, opType string) (string, error)
CreateOperation creates a durable operation and returns its id.
func (*DB) CreatePairingCode ¶ added in v0.7.0
func (db *DB) CreatePairingCode(ctx context.Context, codeHash, label string, now, expires time.Time) error
CreatePairingCode stores the hash of a new one-time pairing code.
func (*DB) CreateQuestion ¶
CreateQuestion inserts an open question.
func (*DB) CreateRemoteRun ¶ added in v0.7.0
func (db *DB) CreateRemoteRun(ctx context.Context, r domain.RemoteRun) (*domain.RemoteRun, bool, error)
CreateRemoteRun inserts a run in status dispatching, or -- when a row with the same idempotency key already exists -- returns that row unchanged with created=false. The UNIQUE constraint is the claim, so two concurrent dispatches of the same (task, attempt) cannot both create one.
func (*DB) CreateRequirement ¶
CreateRequirement inserts a requirement with a project-scoped code (REQ-xx).
func (*DB) CreateRun ¶
func (db *DB) CreateRun(ctx context.Context, kind domain.RunKind, stageRunID, actor, initiativeID, stage string) (string, error)
CreateRun creates a run row and returns its id. actor is the producing agent (role name) and is recorded on the run.created event (§14 actor separation). initiativeID and stage attribute the run to an initiative and workflow stage (C3, wave 3 contract), so GET .../costs can group spend/time by phase; both may be empty (e.g. a run with no initiative context).
func (*DB) CreateRunManifest ¶
CreateRunManifest records immutable run provenance (§36).
func (*DB) CreateTask ¶
func (db *DB) CreateTask(ctx context.Context, t *domain.Task, implementsRequirementID string, dependsOn []string) error
CreateTask inserts an execution-plan task and wires a single `implements` (task → requirement) edge plus `depends_on` (task → task) edges in the same transaction. A back-compat wrapper around CreateTaskMulti for the many single-requirement call sites; new production code that may have more than one requirement code should call CreateTaskMulti directly.
func (*DB) CreateTaskMulti ¶ added in v0.6.0
func (db *DB) CreateTaskMulti(ctx context.Context, t *domain.Task, implementsRequirementIDs []string, dependsOn []string) error
CreateTaskMulti inserts an execution-plan task and wires an `implements` edge to each requirement it implements (N:M, review A4 #4: a task-level requirement reference used to be a single free-text field matched against exactly one Requirement.Code; a task may legitimately span several requirements, and the planner should be able to say so). Duplicate or empty ids are dropped rather than rejected -- the caller (runExecutionPlan / the Plan-editing API) is responsible for surfacing an unresolved reference as its own blocking finding before it ever reaches here.
func (*DB) CreateVerificationEvidence ¶
CreateVerificationEvidence inserts one evidence row (§70, review B4/B10).
func (*DB) CreateVerificationTask ¶
func (db *DB) CreateVerificationTask(ctx context.Context, t *domain.Task, requirementID string) error
CreateVerificationTask creates a plan task whose purpose is verifying a requirement, wired with a `verifies` edge (task → requirement).
func (*DB) DaemonMeta ¶ added in v0.7.0
DaemonMeta returns a daemon-wide value ("" when unset).
func (*DB) DeletePushSubscription ¶ added in v0.7.0
DeletePushSubscription removes a subscription together with its bus cursor and outbox rows: a subscriber that no longer exists must not leave pending deliveries nothing will ever drain.
func (*DB) DeleteTask ¶
DeleteTask removes a task and all of its graph edges in one transaction. Callers must first reject deletion when the task has change sets or other tasks depend on it (checked at the handler layer).
func (*DB) DeleteTasksForInitiative ¶
DeleteTasksForInitiative removes every task (and its edges) for an initiative. Used by plan revision, which regenerates the task list fresh. Callers must reject when any task has a change set.
func (*DB) DispositionOpenFindings ¶
func (db *DB) DispositionOpenFindings(ctx context.Context, initiativeID string, disp domain.Disposition, actor string) error
DispositionOpenFindings sets the disposition of every still-open finding for an initiative in one atomic step. Used when a review cycle passes so prior cycles' blocking findings cannot wedge the verify gate (full-platform review).
func (*DB) DispositionUnclaimedFindingsByTarget ¶ added in v0.4.0
func (db *DB) DispositionUnclaimedFindingsByTarget(ctx context.Context, initiativeID, targetType, targetID string, disp domain.Disposition, actor string) error
DispositionUnclaimedFindingsByTarget dispositions the undisposed findings targeting one node that carry NO deny code, in a single event.
Three constraints, each of which a simpler call gets wrong:
- Target-scoped. DispositionOpenFindings is `WHERE initiative_id = ?`, so using it to accept a change set's findings would also sign off every open finding on the initiative -- including the PRD review's.
- `code = ”`. Every producer that raises a system deny stamps a DenyCode: secret_sweep, pii, host_exec, blob_digest_mismatch. Only the adversarial reviewer leaves it empty (review.ParseFindings never sets it). So this cannot sign off a credential detection, whatever the caller intends, and "system deny beats human approve" survives.
- accepted_risk requires a human. SetFindingDisposition enforces that and DispositionOpenFindings does not; a bulk path that skipped it would let an automated actor forge the one disposition the reviewer is forbidden to set.
One event rather than N: a loop of SetFindingDisposition is not atomic, and a partial write here leaves a change set half-accepted.
func (*DB) DriftingMetrics ¶ added in v0.7.0
func (db *DB) DriftingMetrics(ctx context.Context, initiativeID string, now time.Time) ([]domain.OutcomeMetric, error)
DriftingMetrics returns the live metrics whose drift at now is off_track, regressed or stale (MetricDrift.Drifting), each with its Status.
func (*DB) FailInitiative ¶
FailInitiative marks an initiative failed with a reason.
review H7: this is a general-purpose "mark failed" primitive, not only the release half of a live ClaimInitiativeRunning claim -- tests (and, plausibly, a future administrative path) call it directly on an initiative that is not currently `running` and expect it to take effect, so it deliberately stays unconditional here rather than gaining ClaimInitiativeRunning's CAS. The actual hazard this review item is about -- failOperationAfterPanic calling this unconditionally for an operation that never claimed the initiative in the first place (SuggestAnswersInitiative, notably, has no ClaimInitiativeRunning call at all), which could overwrite a DIFFERENT, unrelated live claim with `failed` -- is closed at that call site instead, by skipping this call entirely for operation types known not to claim (operationClaimsInitiative in runtime.go). A blanket CAS here would have been the wrong layer: it cannot distinguish "no claim to release" from "a live claim that happens to belong to someone else", which is exactly the case that matters.
func (*DB) FailInterruptedAutomationRuns ¶ added in v0.7.0
FailInterruptedAutomationRuns marks every run still `running` as failed -- a daemon that stopped mid-run cannot finish it. Called at project open.
func (*DB) FinishAutomationRun ¶ added in v0.7.0
func (db *DB) FinishAutomationRun(ctx context.Context, r AutomationRun) error
FinishAutomationRun records a run's outcome.
func (*DB) GetArtifactVersion ¶
GetArtifactVersion returns one artifact version by its version id.
func (*DB) GetChangeSet ¶
GetChangeSet returns one change set by id, or nil if not found.
func (*DB) GetChangeSetByRef ¶
GetChangeSetByRef resolves a change set by its UUID or its HumanID (CHG-N), so CLI/UI can reference change sets by the human-facing id. HumanID is only unique per-initiative, so a bare CHG-N that matches more than one initiative fails closed with an ambiguity error instead of silently returning an arbitrary (possibly wrong) change set — review: full-platform authorization.
func (*DB) GetContextDoc ¶
GetContextDoc returns a single context document by id.
func (*DB) GetDecision ¶
GetDecision returns a single decision by id.
func (*DB) GetDocComment ¶
GetDocComment returns one comment by id.
func (*DB) GetFinding ¶ added in v0.6.0
GetFinding returns one finding by id (ICP re-run defect #2: used to warn a human dispositioning a finding "rejected" when it carries a system deny code and so will NOT clear the approval bar, per Finding.ResolvesBlocking).
func (*DB) GetInitiative ¶
GetInitiative returns one initiative by id.
func (*DB) GetInitiativeBudget ¶ added in v0.7.0
func (db *DB) GetInitiativeBudget(ctx context.Context, initiativeID string) (InitiativeBudget, error)
GetInitiativeBudget returns the initiative's cap state (zero value when it has never had one).
func (*DB) GetIntegrationLink ¶ added in v0.7.0
func (db *DB) GetIntegrationLink(ctx context.Context, integration, kind, localID string) (*IntegrationLink, error)
GetIntegrationLink returns the link for a local object, or nil when none.
func (*DB) GetIntegrationLinkByRemote ¶ added in v0.7.0
func (db *DB) GetIntegrationLinkByRemote(ctx context.Context, integration, kind, remoteID string) (*IntegrationLink, error)
GetIntegrationLinkByRemote returns the link for a remote object, or nil.
func (*DB) GetMetricByRef ¶ added in v0.7.0
func (db *DB) GetMetricByRef(ctx context.Context, initiativeID, ref string, now time.Time) (*domain.OutcomeMetric, error)
GetMetricByRef resolves a live metric by id or code (MET-n, any case), with its drift status evaluated at now.
func (*DB) GetMetricRef ¶ added in v0.7.0
GetMetricRef resolves an outcome metric to its initiative and codes.
func (*DB) GetObjectiveByRef ¶ added in v0.7.0
func (db *DB) GetObjectiveByRef(ctx context.Context, initiativeID, ref string) (*domain.Objective, error)
GetObjectiveByRef resolves an objective by id or code (OBJ-n, any case) within an initiative.
func (*DB) GetOperation ¶
GetOperation returns an operation.
func (*DB) GetProject ¶
GetProject returns a project by its project_id.
func (*DB) GetPushSubscription ¶ added in v0.7.0
GetPushSubscription returns one subscription.
func (*DB) GetQualityResult ¶ added in v0.7.0
GetQualityResult returns one result by id.
func (*DB) GetReadCursor ¶
GetReadCursor returns the last-seen event seq for a scope (0 if none).
func (*DB) GetRemoteRun ¶ added in v0.7.0
GetRemoteRun returns one run by its local id.
func (*DB) GetRemoteRunByAgentRun ¶ added in v0.7.0
GetRemoteRunByAgentRun returns the newest remote run feeding agent run runID's events, or nil.
func (*DB) GetRemoteRunByKey ¶ added in v0.7.0
GetRemoteRunByKey returns the run with this idempotency key, or nil.
func (*DB) GetRequirementByRef ¶
func (db *DB) GetRequirementByRef(ctx context.Context, initiativeID, ref string) (*domain.Requirement, error)
GetRequirementByRef resolves a requirement by its UUID or its Code (REQ-N) within an initiative.
func (*DB) GetRunInfo ¶ added in v0.7.0
GetRunInfo returns one run, or a *NotFoundError.
func (*DB) GetRunManifest ¶
GetRunManifest returns a manifest by run id.
func (*DB) GetVerificationEvidenceRef ¶ added in v0.7.0
func (db *DB) GetVerificationEvidenceRef(ctx context.Context, evidenceID string) (*VerificationEvidenceRef, error)
GetVerificationEvidenceRef resolves a verification_evidence row to its initiative and requirement code.
func (*DB) GraphEventSeqs ¶ added in v0.7.0
GraphEventSeqs returns the highest event seq per (aggregate id, event type) for the decision and requirement events the gap analysis orders against each other: decision.created, decision.resolved, requirement.created and requirement.revised. Keyed "<aggregate id>|<event type>".
Seq, not created_at: seq is the log's own total order, so two events in the same millisecond still compare correctly, and "revised after it was decided" is never a coin toss.
func (*DB) HasDissent ¶
HasDissent reports whether a decision has any preserved dissent (§8).
func (*DB) HoldSteeringNote ¶ added in v0.7.0
func (db *DB) HoldSteeringNote(ctx context.Context, n HeldSteeringNote) error
HoldSteeringNote stores a note for the initiative's next run. The caller has already redacted it.
func (*DB) IngestOutbox ¶ added in v0.7.0
func (db *DB) IngestOutbox(ctx context.Context, subscriber string, lastSeq int64, rows []OutboxInsert) error
IngestOutbox inserts rows and advances subscriber's cursor to lastSeq in ONE transaction. A row whose idempotency key already exists is ignored, not an error: that is the re-ingest of an event this subscriber already queued (a crash between the insert and the cursor write of a previous attempt can only ever re-offer rows, never lose them, because both commit together).
func (*DB) IntegrationCursor ¶ added in v0.7.0
IntegrationCursor returns subscriber's last ingested event seq, and false when it has none yet (a subscriber seen for the first time).
func (*DB) IntegrationOutboxStats ¶ added in v0.7.0
IntegrationOutboxStats returns counts by status, the newest recorded error (from a pending or dead row), and the newest delivery time.
func (*DB) JournalSnapshotDigest ¶
JournalSnapshotDigest returns the workspace_snapshot_digest of the most recent committed journal entry for a change set (the pre-image to restore on revert).
func (*DB) LatestEventRunForInitiative ¶ added in v0.7.0
LatestEventRunForInitiative returns the run id of the most recent run of the initiative that has events ("" when none): what the run view shows once nothing is running.
func (*DB) LatestOperationOfType ¶ added in v0.5.1
func (db *DB) LatestOperationOfType(ctx context.Context, projectID, opType string) (*domain.Operation, error)
LatestOperationOfType returns the newest operation of opType for a project, or (nil, nil) when there is none. It answers "how did the last smoke test go", which no initiative-scoped listing can: a smoke belongs to no initiative.
func (*DB) LatestQualityResults ¶ added in v0.7.0
func (db *DB) LatestQualityResults(ctx context.Context, initiativeID string) (map[domain.QualityDimension]domain.QualityResult, error)
LatestQualityResults returns the most recent result of each dimension for an initiative, keyed by dimension, with each result's linked requirement codes filled in from its `verifies` edges.
func (*DB) LinkRequirementObjective ¶ added in v0.7.0
func (db *DB) LinkRequirementObjective(ctx context.Context, initiativeID, requirementID, objectiveID, actor string) error
LinkRequirementObjective records that a requirement serves an objective (requirement --serves--> objective). Idempotent: linking twice is one edge.
func (*DB) ListAgentRunStats ¶ added in v0.6.0
ListAgentRunStats returns the count and total duration of an initiative's RunAgent-kind runs (C3, wave 3 contract).
func (*DB) ListAllRunEvents ¶ added in v0.7.0
ListAllRunEvents returns every stored event of a run, oldest first (the run report). Bounded by RunEventsPerRunMax.
func (*DB) ListAllStaleMarks ¶ added in v0.6.0
func (db *DB) ListAllStaleMarks(ctx context.Context, initiativeID string) ([]domain.StaleItem, error)
ListAllStaleMarks returns every stale mark for an initiative -- cleared and active alike -- oldest first, for BuildTimeline (C1, wave 3 contract). ListStaleItems (above) intentionally returns only the active ones, which is right for "what needs acknowledgement now"; the timeline instead needs "what went stale, and when", including a mark since cleared.
func (*DB) ListArtifactVersions ¶
func (db *DB) ListArtifactVersions(ctx context.Context, initiativeID string) ([]domain.ArtifactVersion, error)
ListArtifactVersions returns versions for an initiative's artifacts.
func (*DB) ListArtifacts ¶
ListArtifacts returns artifact versions (with kind) for an initiative.
func (*DB) ListAssertions ¶
ListAssertions returns assertions for an initiative.
func (*DB) ListAutomationRuns ¶ added in v0.7.0
func (db *DB) ListAutomationRuns(ctx context.Context, automation, target string, limit int) ([]AutomationRun, error)
ListAutomationRuns returns an automation's runs, newest first. target "" lists every target.
func (*DB) ListCaptureTokens ¶ added in v0.7.0
ListCaptureTokens returns metadata for a project's tokens, never the hashes.
func (*DB) ListChangeSetEventsForInitiative ¶ added in v0.6.0
func (db *DB) ListChangeSetEventsForInitiative(ctx context.Context, initiativeID string) ([]TimelineChangeSetEvent, error)
ListChangeSetEventsForInitiative returns the change-set lifecycle events (applied/reverted/status_changed) for change sets belonging to initiativeID, oldest first. Scoped by joining events back to change_sets on aggregate_id, not by trusting anything on the event row itself -- events carry no initiative_id.
func (*DB) ListChangeSets ¶
ListChangeSets returns change sets for an initiative, oldest first.
func (*DB) ListChangeSetsByTask ¶
ListChangeSetsByTask returns change sets for a task, oldest first.
func (*DB) ListChangeSetsForNoOpBackfill ¶ added in v0.6.0
func (db *DB) ListChangeSetsForNoOpBackfill(ctx context.Context) ([]ChangeSetPatchRef, error)
ListChangeSetsForNoOpBackfill returns every change set currently recorded as no_op = 0. Before migration 34 introduced the column, EVERY change set defaulted to it (review MEDIUM #1's "0 for every change set created before this migration" default), including ones whose patch manifest, persisted unconditionally since efac66d, actually touched zero files. This package cannot recompute the flag itself -- that requires reading the patch manifest out of the blob store, which store does not import (migrations are plain SQL text; store has no fsdiff/blob dependency) -- so it hands the candidates to a caller that can (workflow.Engine.BackfillNoOpChangeSets).
func (*DB) ListContextDocs ¶
func (db *DB) ListContextDocs(ctx context.Context, initiativeID string) ([]domain.ContextDoc, error)
ListContextDocs returns context documents for an initiative, oldest first.
func (*DB) ListDecisionDiscussions ¶
func (db *DB) ListDecisionDiscussions(ctx context.Context, decisionID string) ([]domain.DecisionDiscussion, error)
ListDecisionDiscussions returns the discussion thread for a decision.
func (*DB) ListDecisionEventsForInitiative ¶ added in v0.6.0
func (db *DB) ListDecisionEventsForInitiative(ctx context.Context, initiativeID string) ([]TimelineDecisionEvent, error)
ListDecisionEventsForInitiative returns decision resolve/reopen events for decisions belonging to initiativeID, oldest first.
func (*DB) ListDecisions ¶
ListDecisions returns decisions for an initiative.
func (*DB) ListDissents ¶
func (db *DB) ListDissents(ctx context.Context, decisionID string) ([]domain.DecisionDissent, error)
ListDissents returns the dissenting views for a decision.
func (*DB) ListDocComments ¶
func (db *DB) ListDocComments(ctx context.Context, artifactVersionID string) ([]domain.DocComment, error)
ListDocComments returns comments for an artifact version, oldest first.
func (*DB) ListEvents ¶
ListEvents returns events with seq >= sinceSeq ordered by seq ascending.
func (*DB) ListEventsForInitiative ¶ added in v0.6.0
func (db *DB) ListEventsForInitiative(ctx context.Context, initiativeID string, sinceSeq int64, limit int) ([]EventRow, error)
ListEventsForInitiative returns events with seq > sinceSeq that belong to initiativeID, ordered by seq ascending (C1/JTBD 6 fix). Events carry no initiative_id of their own, so each aggregate type is joined back to its owning table's initiative_id -- the same scoping BuildTimeline uses for change_set/decision events, extended here to every aggregate BuildChanged narrates. Before this, BuildChanged called ListEvents (the whole project, every initiative) and "what changed" for one initiative could report another's counts entirely.
func (*DB) ListEvidenceByRequirement ¶
func (db *DB) ListEvidenceByRequirement(ctx context.Context, requirementID string) ([]domain.VerificationEvidence, error)
ListEvidenceByRequirement returns evidence for a requirement, oldest first.
func (*DB) ListFindings ¶
ListFindings returns findings for a review run.
func (*DB) ListFindingsByInitiative ¶
func (db *DB) ListFindingsByInitiative(ctx context.Context, initiativeID string) ([]domain.Finding, error)
ListFindingsByInitiative returns all findings for an initiative.
func (*DB) ListFindingsByTarget ¶
func (db *DB) ListFindingsByTarget(ctx context.Context, targetType, targetID string) ([]domain.Finding, error)
ListFindingsByTarget returns all findings targeting a specific node (e.g. a change set), used by the review_open_blocking deny gate at approve time.
func (*DB) ListGraphEdges ¶
ListGraphEdges returns every edge for an initiative, oldest first.
func (*DB) ListGraphEdgesFrom ¶
func (db *DB) ListGraphEdgesFrom(ctx context.Context, initiativeID, fromType, fromID string) ([]domain.GraphEdge, error)
ListGraphEdgesFrom returns outgoing edges from a node.
func (*DB) ListGraphEdgesTo ¶
func (db *DB) ListGraphEdgesTo(ctx context.Context, initiativeID, toType, toID string) ([]domain.GraphEdge, error)
ListGraphEdgesTo returns incoming edges to a node.
func (*DB) ListInitiativeRemoteRuns ¶ added in v0.7.0
func (db *DB) ListInitiativeRemoteRuns(ctx context.Context, initiativeID string) ([]domain.RemoteRun, error)
ListInitiativeRemoteRuns returns one initiative's remote runs, newest first -- every attempt, terminal or not. It is the listing `idea runs remote` and GET …/initiatives/{id}/remote-runs serve; reconciliation keeps using ListRemoteRuns, which spans the project.
func (*DB) ListInitiativeRollups ¶
func (db *DB) ListInitiativeRollups(ctx context.Context) ([]InitiativeRollup, error)
ListInitiativeRollups returns one rollup per initiative in the project DB.
func (*DB) ListInitiativeStatusEvents ¶ added in v0.6.0
func (db *DB) ListInitiativeStatusEvents(ctx context.Context, initiativeID string) ([]TimelineStatusEvent, error)
ListInitiativeStatusEvents returns an initiative's own status_changed events, oldest first (the phase-completed entries of BuildTimeline).
func (*DB) ListInitiatives ¶
ListInitiatives returns all initiatives ordered by creation.
func (*DB) ListIntegrationLinks ¶ added in v0.7.0
func (db *DB) ListIntegrationLinks(ctx context.Context, integration, kind string) ([]IntegrationLink, error)
ListIntegrationLinks returns every link of one integration (and kind, when kind is non-empty), oldest first.
func (*DB) ListJournal ¶
func (db *DB) ListJournal(ctx context.Context, changeSetID string) ([]domain.ApplyJournalEntry, error)
ListJournal returns apply-journal records for a change set, oldest first.
func (*DB) ListMetrics ¶ added in v0.7.0
func (db *DB) ListMetrics(ctx context.Context, initiativeID string, now time.Time) ([]domain.OutcomeMetric, error)
ListMetrics returns an initiative's live metrics (not superseded), each with its drift Status evaluated at now.
func (*DB) ListModelPhaseCosts ¶ added in v0.6.0
ListModelPhaseCosts groups an initiative's RunModel-kind runs by stage, summing cost and duration from their manifests (C3, wave 3 contract). Agent (coding) runs are excluded -- see ListAgentRunStats -- since their cost is not always measurable the same way and they are reported separately.
func (*DB) ListObjectives ¶ added in v0.7.0
ListObjectives returns an initiative's objectives, superseded ones included (callers filter with Objective.Active), with RequirementIDs and MetricIDs attached.
func (*DB) ListObservations ¶ added in v0.7.0
func (db *DB) ListObservations(ctx context.Context, metricID string) ([]domain.MetricObservation, error)
ListObservations returns a metric's observations, oldest first.
func (*DB) ListOperationsByInitiative ¶
func (db *DB) ListOperationsByInitiative(ctx context.Context, initiativeID string) ([]domain.Operation, error)
ListOperationsByInitiative returns an initiative's operations, most recent first, so the UI can find the running one and show elapsed time.
func (*DB) ListProjectMemory ¶ added in v0.7.0
ListProjectMemory returns the most recent project-memory entries, newest first. The per-project DB is the project, so no scope argument is needed.
func (*DB) ListProjects ¶
func (db *DB) ListProjects(ctx context.Context) ([]ProjectRecord, error)
ListProjects returns all registered projects.
func (*DB) ListPushSubscriptions ¶ added in v0.7.0
func (db *DB) ListPushSubscriptions(ctx context.Context) ([]PushSubscription, error)
ListPushSubscriptions returns every subscription, oldest first.
func (*DB) ListQualityResults ¶ added in v0.7.0
func (db *DB) ListQualityResults(ctx context.Context, initiativeID string) ([]domain.QualityResult, error)
ListQualityResults returns every result for an initiative, oldest first (the trace label cache reads it; Requirements is left empty).
func (*DB) ListQuestions ¶
ListQuestions returns questions for an initiative.
func (*DB) ListRemoteRuns ¶ added in v0.7.0
func (db *DB) ListRemoteRuns(ctx context.Context, activeOnly bool, limit int) ([]domain.RemoteRun, error)
ListRemoteRuns returns runs newest first. With activeOnly, only those not yet terminal -- what reconciliation re-attaches to. limit <= 0 means all.
func (*DB) ListRequirements ¶
func (db *DB) ListRequirements(ctx context.Context, initiativeID string) ([]domain.Requirement, error)
ListRequirements returns requirements for an initiative.
func (*DB) ListReviewTelemetry ¶ added in v0.7.0
func (db *DB) ListReviewTelemetry(ctx context.Context, initiativeID string) ([]domain.ReviewTelemetry, error)
ListReviewTelemetry returns every review cycle's convergence record for an initiative, oldest first -- the PRD loop's cycles and the plan review's pass, across every invocation (a human revise starts a new loop at cycle 1, so Cycle alone does not order them; started_at does).
func (*DB) ListRunEvents ¶ added in v0.7.0
func (db *DB) ListRunEvents(ctx context.Context, runID string, after int64, limit int) (RunEventPage, error)
ListRunEvents returns up to limit of runID's events with seq > after, oldest first.
func (*DB) ListRunEventsAfterID ¶ added in v0.7.0
func (db *DB) ListRunEventsAfterID(ctx context.Context, afterID int64, limit int) ([]RunEventRow, error)
ListRunEventsAfterID returns up to limit events of any run with a project-wide id > afterID, oldest first: the project event stream's run events.
func (*DB) ListSecretAllowlist ¶ added in v0.6.0
ListSecretAllowlist returns every "not a secret" entry for this project's state.db, newest first, for the Settings page (review changes #1).
func (*DB) ListStaleItems ¶ added in v0.6.0
ListStaleItems returns the active (uncleared) stale marks for an initiative, oldest first.
func (*DB) ListSuggestedAnswers ¶
func (db *DB) ListSuggestedAnswers(ctx context.Context, initiativeID string) ([]domain.SuggestedAnswer, error)
ListSuggestedAnswers returns the stored AI-suggested answers for an initiative.
func (*DB) ListUISessions ¶ added in v0.7.0
ListUISessions returns every session not yet pruned, newest first.
func (*DB) ListUnfinishedOperations ¶
ListUnfinishedOperations returns operations not in a terminal state (for daemon restart reconciliation, §16).
func (*DB) LookupCaptureToken ¶ added in v0.7.0
LookupCaptureToken returns the project a token authorizes, or ErrCaptureTokenUnknown. It also records the use, best-effort.
func (*DB) LookupUISession ¶ added in v0.7.0
func (db *DB) LookupUISession(ctx context.Context, secretHash string, now time.Time) (UISession, bool, error)
LookupUISession returns the live (unrevoked, unexpired) session whose secret hashes to secretHash, or ok=false.
func (*DB) MarkChangeSetApplied ¶
func (db *DB) MarkChangeSetApplied(ctx context.Context, changeSetID, workspaceSnapshotDigest, actor string) error
MarkChangeSetApplied atomically advances applying→applied and appends the committed journal entry (carrying the pre-image workspace snapshot digest) in one transaction, so the change set status and the apply journal can never diverge (§39).
func (*DB) MarkChangeSetReverted ¶
MarkChangeSetReverted atomically advances applied→reverted and appends a rolled_back journal entry in one transaction, so the change set status and the apply journal can never diverge (§39).
func (*DB) MarkDocCommentPromoted ¶
MarkDocCommentPromoted records the question a comment was promoted into. The update is conditional on the comment being unpromoted, so a concurrent or duplicate promote affects zero rows and fails rather than overwriting the first link (last-writer-wins).
func (*DB) MarkOutboxDelivered ¶ added in v0.7.0
MarkOutboxDelivered records a successful delivery. Conditional on the row still being pending, so a delivered row can never flip back.
func (*DB) MarkOutboxFailed ¶ added in v0.7.0
func (db *DB) MarkOutboxFailed(ctx context.Context, rowID, lastError string, nextAttempt time.Time, dead bool) error
MarkOutboxFailed records a failed attempt: either a retry at nextAttempt or, when dead is true, the end of the line for this row.
func (*DB) MarkRequirementFailed ¶
MarkRequirementFailed transitions a requirement to failed from any approvable state (approved/verified/waived/failed — re-issue is idempotent). A failed requirement stays in the active set and blocks completion until a human re-records a pass.
func (*DB) MarkRequirementVerified ¶
MarkRequirementVerified transitions a requirement approved/failed/waived→verified and stamps verified_at. A human re-pass clears a prior fail or waiver and returns the requirement to the verified set. It fails if the requirement is not in one of those three source states.
func (*DB) MarkRequirementWaived ¶
MarkRequirementWaived transitions a requirement to waived from any approvable state (approved/verified/failed/waived — re-issue is idempotent). A waived requirement is excluded from the completion gate (like removed) but remains visible and recorded as a human judgment, not a deletion.
func (*DB) MaxEventSeq ¶
MaxEventSeq returns the current maximum event sequence (0 if empty).
func (*DB) MaxRunEventID ¶ added in v0.7.0
MaxRunEventID is the newest project-wide run event id (0 when none).
func (*DB) MergeTasks ¶ added in v0.6.0
func (db *DB) MergeTasks(ctx context.Context, initiativeID, keepID, mergeID string) (*domain.Task, error)
MergeTasks merges mergeID into keepID as ONE transaction (review H4). Every step below -- and the cycle check -- runs inside it: the handler used to make six separate Apply calls, so a failure partway (or a concurrent request racing it) could leave a half-merged plan.
It:
- refuses outright when keepID == mergeID (a self-merge used to pass both guards and then delete the survivor);
- unions the requirements ("implements" edges) each task holds onto keepID;
- concatenates their statements;
- unions their outgoing depends_on (each other and self excluded) onto keepID;
- rewires every dependent of mergeID onto keepID, deduplicated -- a task that depended on BOTH merged tasks must not end up with two identical depends_on edges to keepID;
- builds the FINAL task graph (mergeID removed, its incoming edges redirected to keepID) and refuses the whole merge, writing nothing, if that graph has a cycle;
- only then deletes mergeID and its remaining edges.
Returns the updated survivor task.
func (*DB) MetricHypotheses ¶ added in v0.7.0
func (db *DB) MetricHypotheses(ctx context.Context, initiativeID, metricID string) ([]domain.Assertion, error)
MetricHypotheses returns the hypothesis assertions predicting a metric.
func (*DB) NeedsHumanJudgment ¶ added in v0.4.0
func (db *DB) NeedsHumanJudgment(ctx context.Context, initiativeID string, reason domain.JudgmentReason, actor string) error
NeedsHumanJudgment parks an initiative for a human and records why, in one statement. The two must move together: a status without a reason is what left `idea next` guessing from artifact presence, and a reason without the status would be read by nothing.
func (*DB) NextOutbox ¶ added in v0.7.0
NextOutbox returns subscriber's oldest pending row (lowest event seq), or nil when there is none. It does NOT filter on next_attempt_at: the dispatcher delivers in order, so a head row still in backoff must hold back the rows behind it (a Slack thread reply must not land before its root).
func (*DB) ObjectivesWithoutMetrics ¶ added in v0.7.0
func (db *DB) ObjectivesWithoutMetrics(ctx context.Context, initiativeID string) ([]domain.Objective, error)
ObjectivesWithoutMetrics returns the active objectives with no live, measurable metric: promises nobody can check.
func (*DB) ObjectivesWithoutRequirements ¶ added in v0.7.0
func (db *DB) ObjectivesWithoutRequirements(ctx context.Context, initiativeID string) ([]domain.Objective, error)
ObjectivesWithoutRequirements returns the active objectives no active requirement serves: outcomes nothing in the plan is aimed at.
func (*DB) OutcomeChain ¶ added in v0.7.0
func (db *DB) OutcomeChain(ctx context.Context, initiativeID string, now time.Time) (domain.OutcomeChainGaps, error)
OutcomeChain loads the initiative's requirements, objectives and metrics (drift evaluated at now) and returns the outcome chain's gaps.
func (*DB) ParkForBudget ¶ added in v0.7.0
ParkForBudget stops an initiative at its spending cap: needs_human_judgment with reason budget_exceeded, remembering parkedFrom (the status to return to once the cap is raised). Two events are appended in the one transaction: the status change every client already follows, and initiative.budget_exceeded, whose operation carries detail ("$1.2000 of $1.0000"), for the integration bus.
A complete initiative is never parked: nothing is left to spend on, and a completion that landed while the stopped call unwound must stand.
func (*DB) PassedCriterionKeys ¶
func (db *DB) PassedCriterionKeys(ctx context.Context, requirementID string) (map[string]bool, error)
PassedCriterionKeys returns the set of criterion keys that have at least one pass evidence for a requirement.
func (*DB) PendingSteeringNotes ¶ added in v0.7.0
func (db *DB) PendingSteeringNotes(ctx context.Context, initiativeID string) ([]HeldSteeringNote, error)
PendingSteeringNotes lists the initiative's notes no run has taken yet, oldest first.
func (*DB) PreviousInitiativeStatus ¶ added in v0.7.0
func (db *DB) PreviousInitiativeStatus(ctx context.Context, initiativeID string, beforeSeq int64, skipRunning bool) (string, error)
PreviousInitiativeStatus returns the status an initiative held, per the event log, immediately before event seq beforeSeq. With skipRunning, `running` -- a claim, not a milestone -- is skipped. Returns "" when there is none.
The integration bus needs this because a status event is not a status CHANGE: every execute/apply claims plan_approved -> running and releases running -> plan_approved, so a naive "status became plan_approved" rule would announce "plan approved" to Slack after every apply. The previous non-running status is what distinguishes a release from a real transition.
func (*DB) PutIntegrationLink ¶ added in v0.7.0
func (db *DB) PutIntegrationLink(ctx context.Context, l IntegrationLink) error
PutIntegrationLink inserts a link, or updates the remote side of an existing one (same integration/kind/local id).
func (*DB) QualityHistory ¶ added in v0.7.0
func (db *DB) QualityHistory(ctx context.Context, initiativeID string) ([]domain.QualityResult, error)
QualityHistory returns every result for an initiative, oldest first, with each result's linked requirement codes filled in -- the measurement history the web UI's quality page charts (GET .../quality/history). Kept apart from ListQualityResults because the trace label cache calls that on every why/impact and has no use for the per-result edge lookups this does.
func (*DB) ReconcileChangeSets ¶
func (db *DB) ReconcileChangeSets(ctx context.Context) ([]ChangeSetRecovery, error)
ReconcileChangeSets finds change sets stuck in applying/checks_running and marks the non-terminal journal rows of the applying ones recovery_required. It only touches change sets that are themselves non-terminal, so the journal history of already-applied/reverted change sets is left intact.
func (*DB) RecordArtifactVersion ¶ added in v0.7.0
func (db *DB) RecordArtifactVersion(ctx context.Context, initiativeID string, kind domain.ArtifactKind, v *domain.ArtifactVersion, skipIdentical bool) (bool, error)
RecordArtifactVersion records a regenerated body as the next version of the initiative's existing artifact of that kind, creating the family (at v1) only when there is none yet. It returns whether a version was written.
Every regeneration used to go through CreateArtifact, which always starts a new family at v1: a revised plan was a second "execution plan v1", the UI labelled the comparison "Diff v1 → v1", and the diff endpoint then refused it because the two versions belonged to different artifacts. Appending to the family is what makes "v2" mean the second version of the same document.
skipIdentical makes a regeneration whose body is byte-identical to the latest version a no-op (false, nil): a revision that changed nothing must not mint a version that differs from its predecessor only in its number.
func (*DB) RecordExternalNote ¶ added in v0.7.0
RecordExternalNote appends an initiative.external_note event: a non-destructive, human-visible record that something happened to this initiative OUTSIDE the harness (a Linear issue was canceled). It changes no state -- an integration never gets to cancel, delete or transition anything on its own say-so -- and it is an event precisely so it shows up where a human already looks (What Changed, the activity feed).
func (*DB) RecordHumanEvidence ¶ added in v0.6.0
func (db *DB) RecordHumanEvidence(ctx context.Context, initiativeID, requirementID string, acceptanceCriteria int, status domain.VerificationStatus, note, actor string) error
RecordHumanEvidence atomically supersedes a requirement's prior verification evidence with a fresh human judgment across every one of its acceptanceCriteria acceptance criteria, plus the resulting requirement status transition (fail/waived only -- a pass leaves status alone; VerifyInitiative promotes it separately once every criterion is covered), all in ONE transaction (review MEDIUM: RecordHumanEvidence atomicity).
Before this, workflow.Engine.RecordHumanEvidence ran the equivalent sequence -- ClearVerificationEvidence, one CreateVerificationEvidence per criterion, then an optional MarkRequirementFailed/MarkRequirementWaived -- as N+2 separate transactions. A crash (or a Stop) between any two of them destroyed the prior judgment without recording the new one: zero evidence rows left standing under whatever status the requirement had before the call, most visibly `verified` surviving over no evidence at all. One transaction makes the whole judgment atomic: either the old evidence is gone AND the new evidence AND status transition are all in place, or nothing here changed.
Matches the merge/split precedent (store/merge.go, store/split.go) for a compound write: one event for the whole operation, not one per row.
func (*DB) RecordObservation ¶ added in v0.7.0
func (db *DB) RecordObservation(ctx context.Context, o *domain.MetricObservation, actor string, now time.Time) (before, after domain.MetricStatus, err error)
RecordObservation stores one measured value of a metric. In the same transaction it computes the outcome attribution -- the change sets applied (committed in the apply journal, still applied, and not a no-op) after the previous observation and at or before this one; for a metric's first observation, after the metric was defined -- stores it on the observation, and wires metric --attributed_to--> change_set for each.
When the observation moves the metric's drift INTO off_track or regressed from anything else, a `metric.drifted` event (Operation "<from>-><to>") is appended alongside `metric.observed`: that is what the integration bus turns into an outcome.drifted notification. Staleness is a function of the clock, not of a write, so it is never evented -- it is surfaced on read (status, guidance, Health) instead.
now is the evaluation time for the before/after drift comparison.
func (*DB) RecordPushResult ¶ added in v0.7.0
RecordPushResult records the outcome of a delivery attempt (lastErr "" on success), for the Settings list.
func (*DB) RecordQualityMeasurement ¶ added in v0.7.0
func (db *DB) RecordQualityMeasurement(ctx context.Context, initiativeID string, results []domain.QualityResult, links map[domain.QualityDimension][]QualityLink) error
RecordQualityMeasurement writes one measurement -- every measured dimension's result -- and each result's `verifies` edges to the requirements it bears on, in one transaction with one `quality.measured` event on the initiative. Either the whole scorecard lands or none of it does: a half-written measurement would leave the gate reading some dimensions from this run and some from the last.
Results are append-only. The latest per dimension is the scorecard; the one before is the performance baseline.
func (*DB) RedeemPairingCode ¶ added in v0.7.0
func (db *DB) RedeemPairingCode(ctx context.Context, codeHash string, s UISession, secretHash string, now time.Time, failureBudget int) (sess UISession, burned int64, err error)
RedeemPairingCode consumes a pairing code and creates the session it pays for, in one transaction: a code can be spent once, and a crash between "spent" and "session exists" must not leave a used code with nothing to show for it.
A code that matches nothing is a wrong guess at every code outstanding now, so -- in the same transaction, which is what makes the budget exact under concurrent sign-ins -- each of them has failed_attempts raised, and any that reaches failureBudget is burned. burned is how many burned on this call. The error is then ErrPairingCodeInvalid.
func (*DB) RegisterProject ¶
func (db *DB) RegisterProject(ctx context.Context, name, rootPath, projectID string) (string, error)
RegisterProject inserts or updates a project registry entry and returns the project id. The global registry has no event log, so this is a direct upsert.
func (*DB) RelateAssertions ¶ added in v0.7.0
func (db *DB) RelateAssertions(ctx context.Context, initiativeID, fromID string, edge domain.EdgeType, toID string) error
RelateAssertions records that one assertion corroborates (supports) or contradicts another -- a research finding judging a framing assumption. Both must belong to the initiative. supports makes the target one of the source's dependents in gap analysis (it is what the finding props up); contradicts is recorded for `idea why`/`impact` and the reader, and is not itself a gap trigger between two assertions.
func (*DB) ReleaseInitiativeClaim ¶ added in v0.6.0
func (db *DB) ReleaseInitiativeClaim(ctx context.Context, initiativeID string, to domain.InitiativeStatus, actor string) error
ReleaseInitiativeClaim transitions an initiative FROM `running` back to `to` -- the release half of ClaimInitiativeRunning -- but only while it is STILL `running` (review H7). Every apply/execute/revert-style entry point claims running, does its real work, and then hands the initiative back to wherever it found it (or a related status); before this, that handback (runtime.go's `release()` closures) used the unconditional SetInitiativeStatus, so it could run moments after the claiming operation's real work finished (its engine mutex already released) but AFTER some other, legitimate write had already moved the initiative somewhere else -- proven with verify's CompleteInitiative landing in that exact gap and being silently overwritten back to the pre-apply status, discarding a real completion. CAS-ing this on `running` makes the handback a no-op whenever that has happened, instead of a stomp.
func (*DB) RenewPushSubscription ¶ added in v0.7.0
func (db *DB) RenewPushSubscription(ctx context.Context, subID, tokenHash string, s PushSubscription, newTokenHash string) (PushSubscription, error)
RenewPushSubscription re-points subscription subID at a new endpoint and keys -- what a browser's `pushsubscriptionchange` asks for -- provided tokenHash matches its stored renewal token, and rotates that token to newTokenHash. Events and label are kept: renewal is the same browser.
If the new endpoint already has a row of its own (the page re-subscribed before the worker got here), that row survives with the new token and subID is deleted, outbox and cursor included; the survivor is returned either way. The token comparison is on hashes of 256-bit secrets, so a timing difference reveals nothing usable.
func (*DB) ReopenDecision ¶
ReopenDecision returns a decided decision to open and clears its resolution, so the human can choose again. Dissent is preserved (never erased, §8).
Review A4 #5 ("impact is true"): a decided decision is authoritative only while it stays decided. The moment it is reopened, whatever was built on it -- the requirements that cite it, their tasks, and the applied change sets for those tasks -- is marked stale, so `impact decision DEC-n` and `/guidance` can say so instead of "no dependents found". This covers both "reopened" and "re-resolved with a different answer", since the latter is only reachable through this reopen in the current API.
func (*DB) ReorderTasks ¶
ReorderTasks assigns 0..n-1 positions to the given task ids, which must be exactly a permutation of the initiative's current tasks. Idempotent and transactional.
func (*DB) ReplaceRequirementObjectives ¶ added in v0.7.0
func (db *DB) ReplaceRequirementObjectives(ctx context.Context, initiativeID, requirementID string, objectiveIDs []string) error
ReplaceRequirementObjectives sets exactly which objectives a requirement serves. Used by a PRD revision that named the requirement's objectives; an empty list is refused rather than read as "unlink everything", because a revision that simply did not say must not erase a human's links.
func (*DB) ReplaceSuggestedAnswers ¶
func (db *DB) ReplaceSuggestedAnswers(ctx context.Context, initiativeID string, answers []domain.SuggestedAnswer) error
ReplaceSuggestedAnswers replaces the stored AI-suggested answers for an initiative with a fresh set.
func (*DB) ReplaceTaskDependencies ¶ added in v0.6.0
func (db *DB) ReplaceTaskDependencies(ctx context.Context, initiativeID, taskID string, depTaskIDs []string) error
ReplaceTaskDependencies replaces a task's depends_on edges wholesale with one per id in depTaskIDs (review B3: "set a task's depends_on"). An empty depTaskIDs clears every dependency. Cycle validation is the caller's job (it needs the whole initiative's graph, not just this one task's edges).
func (*DB) ReplaceTaskRequirements ¶ added in v0.6.0
func (db *DB) ReplaceTaskRequirements(ctx context.Context, initiativeID, taskID string, requirementIDs []string) error
ReplaceTaskRequirements replaces a task's `implements` edges with one per requirement id given (N:M, review A4 #4). Used by the Plan-editing "add task"/"update task" API so a task's requirement links can be set or changed after creation. Requires at least one id -- callers must enforce "at least one requirement when the plan is approved" before calling this; it does not itself refuse an empty list.
func (*DB) RequirementOutcomeDrift ¶ added in v0.7.0
func (db *DB) RequirementOutcomeDrift(ctx context.Context, initiativeID string, now time.Time) ([]domain.RequirementOutcomeDrift, error)
RequirementOutcomeDrift returns the "works but fails its objective" signals: for every VERIFIED active requirement, each active objective it serves whose live metrics include one that is off_track or regressed. Stale alone does not count -- not knowing is not the same as failing.
func (*DB) RequirementsWithoutObjectives ¶ added in v0.7.0
func (db *DB) RequirementsWithoutObjectives(ctx context.Context, initiativeID string) ([]domain.Requirement, error)
RequirementsWithoutObjectives returns the active requirements that serve no active objective: work with no stated outcome. Empty while the initiative has no active objective at all (OutcomeChainGaps.ObjectivesMissing is that case, reported once).
func (*DB) ResolveDecision ¶
ResolveDecision records a human decision (immutable once resolved).
ICP re-run defect H (third clause): quick rigor can auto-approve a plan (and tasks can execute) while a decision is still open, so "resolving a decision for the first time" is no longer guaranteed to happen before anything was built on it -- unlike the ordinary flow, where a decision is expected to resolve before the plan it feeds even exists. When something already depends on this decision (a live requirement derived from it, that requirement's tasks, their applied change sets), resolving it now is exactly as consequential as ReopenDecision's "changed my mind" case, and must mark the same dependents stale the same way -- otherwise a human's answer given after plan approval (e.g. "keys in an env var") never surfaces as "N items may be invalid" anywhere, and the tasks/change sets built without it are never flagged for a second look.
func (*DB) ResumeFromBudget ¶ added in v0.7.0
ResumeFromBudget returns a budget-stopped initiative to the status it was parked from, and reports whether it did. A no-op (false, nil) unless the initiative is parked on budget_exceeded.
Where it returns to:
- plan_approved, approved, or needs_human_judgment with its old reason: there, exactly, so the step that stopped can simply be run again;
- anything else (a stop mid-PRD from a fresh initiative, or from a retry of a failed one): failed, with a reason naming `idea retry`, which is how a design-phase run is continued.
func (*DB) RevokeAllUISessions ¶ added in v0.7.0
RevokeAllUISessions revokes every live session and returns how many.
func (*DB) RevokeSecretAllowlist ¶ added in v0.6.0
RevokeSecretAllowlist removes one allowlist entry by id, so the sweep starts denying that fingerprint+path again. The delete itself targets the entry's (fingerprint, path) pair rather than its id (review M1): the unique index added alongside this scoping means there is at most one row per pair going forward, but it also cleans up any pre-existing duplicate the dedup-on- migration step might have raced with, or that predates this fix.
func (*DB) RevokeUISession ¶ added in v0.7.0
RevokeUISession revokes one session; ok=false when no live session has id.
func (*DB) RunEventCostTotals ¶ added in v0.7.0
func (db *DB) RunEventCostTotals(ctx context.Context, runID string) (in, out int64, cost float64, err error)
RunEventCostTotals sums a run's stored cost events: what an ingester that turns running totals into deltas has already accounted for (an OpenHands watcher re-attaching after a restart starts from here, not from zero).
func (*DB) RunEventsChanged ¶ added in v0.7.0
func (db *DB) RunEventsChanged() <-chan struct{}
RunEventsChanged returns a channel closed at the next append of any run event. Take it BEFORE reading, then read, then wait on it: an append between the read and the wait still closes the channel taken first.
func (*DB) RunningOperationID ¶ added in v0.7.0
RunningOperationID is the id of the initiative's running operation ("" when none), the same row SetOperationStage writes.
func (*DB) SaveRiskProfile ¶
SaveRiskProfile persists a deterministic risk profile for an initiative. A profile is append-only history: every computed profile is retained.
Currently unused, deliberately. handleRisk called this on a GET, so every read appended a row and an event without bound; nothing ever read them back (risk_profiles has no SELECT anywhere). ComputeRiskProfile is a pure function of the change-set patches, so a profile is recomputable on demand and the history bought nothing. Kept -- with the table -- for whenever a durable profile gains an actual reader, which is the thing to add first.
func (*DB) SecretAllowlistFingerprints ¶ added in v0.6.0
SecretAllowlistFingerprints returns every allowlisted (fingerprint, path) pair as a set keyed by allowlistKey, for the sweep to filter its own matches against -- one query per sweep rather than one per match.
func (*DB) SecretFingerprintKey ¶ added in v0.6.0
SecretFingerprintKey returns this project's per-project HMAC key for secret fingerprints, generating and persisting a random 32-byte key on first use. A fingerprint keyed per-project (rather than a bare sha256 of the value) is not the same, precomputable value across every installation that ever saw the same secret -- it cannot be used to correlate the same credential across unrelated projects or daemons.
func (*DB) SeedRequirementsFrom ¶ added in v0.7.0
func (db *DB) SeedRequirementsFrom(ctx context.Context, destInitiativeID, sourceInitiativeID string) (int, error)
SeedRequirementsFrom copies a source initiative's live requirements into dest, preserving their codes so a subsequent PRD run treats them as continuing (and thus emits added/modified/removed deltas). Removed/superseded requirements are not copied — the delta is what the new initiative changes, not what the source had already dropped. Returns the number of requirements seeded.
func (*DB) SetAssertionBasis ¶ added in v0.7.0
func (db *DB) SetAssertionBasis(ctx context.Context, initiativeID, fromType, fromID string, assertionIDs []string, replace bool) error
SetAssertionBasis records the assertions a requirement or decision rests on (its PRD `based_on`): one fromType --derived_from--> assertion edge per id. derived_from, not a new edge kind: it is the edge a requirement's source assertion already uses, the one `idea why` walks toward the evidence and `idea impact` walks away from it, and the one gap analysis reads both for an assertion's dependents and for a decision's basis_refuted.
replace is for a node the same PRD cycle restates -- a requirement revised in place: its earlier derived_from->assertion edges that ids no longer names are removed first, so the graph says what the requirement rests on now, not the union of every revision. The requirement's own source_assertion_id edge is never removed here; it is a fact about where the row came from, not a claim the model restates each cycle. A decision is never replaced (callers pass false): a re-listed decision merges into the existing row, and an earlier cycle's basis for a choice already made is still its basis.
Ids must belong to the initiative; an unknown one is refused rather than written as a dangling edge.
func (*DB) SetAssertionStatus ¶ added in v0.7.0
func (db *DB) SetAssertionStatus(ctx context.Context, assertionID string, status domain.AssertionStatus, actor string) error
SetAssertionStatus records a human's judgment on an assumption or hypothesis: accepted (validated), disputed (contested, still unvalidated) or retracted (refuted). Retraction also writes an invalidates edge from the assertion to each live requirement or decision resting on it (see syncInvalidatesTx); a later accept or dispute removes them.
It is the only path that moves an assertion out of `candidate`. Framing and research record every assumption as a candidate and nothing ever validated one, so `idea gaps` could report an unvalidated assumption that nothing could close. A superseded assertion is history, not a live claim, and is refused rather than resurrected.
func (*DB) SetChangeSetCommit ¶
SetChangeSetCommit records the git commit SHA for a change set.
func (*DB) SetChangeSetGitWarning ¶ added in v0.6.0
SetChangeSetGitWarning records why an applied change set was not committed even though git_commit is on (review C4, adopted #2): a detached HEAD, a rebase/merge/cherry-pick in progress, or the repository's default branch without git.allow_default_branch.
func (*DB) SetChangeSetNoOp ¶ added in v0.6.0
SetChangeSetNoOp backfills the no_op flag for one change set (review MEDIUM #1), after the caller has determined from the patch manifest that it touched zero files. This is the only writer of no_op other than CreateChangeSet's implicit default.
func (*DB) SetChangeSetReview ¶
SetChangeSetReview records the review id for a change set AND stamps review_completed_at (ICP re-run defect #1). This is the ONLY place a completed adversarial review is ever recorded — called once from Execute after runChangeSetAdversarialReview succeeds, and again from RerunChangeSetReview when a human explicitly retries a review that never completed the first time. If the caller's review attempt itself errors, this must never be called, so the change set correctly keeps ReviewCompletedAt nil (unreviewed).
func (*DB) SetChangeSetReviewUnavailable ¶ added in v0.6.0
func (db *DB) SetChangeSetReviewUnavailable(ctx context.Context, changeSetID, reason, actor string) error
SetChangeSetReviewUnavailable records that the adversarial reviewer was genuinely ATTEMPTED for cs but could not complete -- e.g. every attempt (including runModel's own reduced-ask retry) was cut off at the model's output-token ceiling (model.ErrTruncated) -- as a plain, non-empty reason. It deliberately does NOT set review_completed_at: round-4's guarantee that an unreviewed change set cannot be silently approved must hold exactly as before ReviewCompleted() still reports false. What changes is ReviewNeverCompletedCause, which now names this reason instead of the generic "likely cancelled mid-review", and ReviewUnavailable, which reviewChangeSet's "approved" verdict consults to allow the one new, explicit, recorded escape: --accept-findings on a change set whose review never completed but was genuinely attempted and exhausted.
Called from Execute's own review call and from RerunChangeSetReview, in place of returning the truncation error outright -- that early return is exactly what used to leave the task never marked done and the change set wedged behind a guard with no supported way forward (the defect this closes).
func (*DB) SetContextDocDescription ¶
SetContextDocDescription records the vision-generated description digest for an image doc.
func (*DB) SetDaemonMeta ¶ added in v0.7.0
SetDaemonMeta stores a daemon-wide key/value in global.db; an empty value deletes the key.
func (*DB) SetDecisionRecommendation ¶
func (db *DB) SetDecisionRecommendation(ctx context.Context, decisionID, rec, convergedBy, actor string) error
SetDecisionRecommendation overwrites a decision's recommendation with a synthesized value (the orchestrator convergence, §M2 tail) and appends a decision event recording the synthesis.
func (*DB) SetFindingDisposition ¶
func (db *DB) SetFindingDisposition(ctx context.Context, findingID string, disp domain.Disposition, actor string) error
SetFindingDisposition records a disposition from a distinct actor.
not_a_secret (review changes #1, review H3) is scoped to secret_sweep findings only: every other category refuses it, so the one disposition that also writes a project-scoped allowlist entry cannot be forged onto an unrelated finding. A configured secret value's own finding (secret_overridable = false) refuses it too, unconditionally: that match is a real credential by construction, not a shape that might be a false positive, and no human override makes it eligible. The scoping checks and the allowlist write happen in the same transaction as the disposition update, so a crash between them cannot leave one without the other.
The allowlist entry is scoped to (fingerprint, path) -- not fingerprint alone -- via upsert (ON CONFLICT), so the same value allowlisted in one file (e.g. a test fixture) still blocks in another. Changing a finding's disposition AWAY FROM not_a_secret removes the matching allowlist entry, so an allowlist decision can be reversed by re-dispositioning the finding that created it. No "store: " prefix on any message below (same reasoning as ErrSelfMerge/ ErrMergeCycle/ErrDependsOnCycle and ReorderTasks's two messages -- see merge.go/dependson.go/graph.go): handleFindingDisposition surfaces this function's Error() text verbatim in a 400, and `idea disposition` (internal/cli/tasks.go) is the first CLI-reachable caller of this path.
func (*DB) SetFindingNote ¶
SetFindingNote records (or clears) a human free-text note on a finding. The note is fed back to the model on the next revise so the human can "discuss" a finding rather than only disposition it.
func (*DB) SetInitiativeBudgetCap ¶ added in v0.7.0
func (db *DB) SetInitiativeBudgetCap(ctx context.Context, initiativeID string, capUSD *float64, actor string) error
SetInitiativeBudgetCap sets (or, with nil, clears) an initiative's own cap. It does not unpark a budget-stopped initiative; ResumeFromBudget does, and the caller decides whether the new cap allows it.
func (*DB) SetInitiativeGitBranch ¶ added in v0.6.0
SetInitiativeGitBranch records the dedicated branch git.branch_per_initiative created for this initiative on its first apply (review C4 piece 2), so every later change set commits to the same branch instead of computing (and possibly colliding on) a new name each time.
func (*DB) SetInitiativePRURL ¶ added in v0.6.0
SetInitiativePRURL records the pull request `idea pr` opened for the initiative's dedicated branch (review C4 piece 3).
func (*DB) SetInitiativeStatus ¶
func (*DB) SetOperationFailed ¶ added in v0.5.0
func (db *DB) SetOperationFailed(ctx context.Context, opID string, status domain.OperationStatus, errMsg string) error
SetOperationFailed transitions an operation to a terminal failed or cancelled status and records why (B2).
Separate from SetOperationStatus rather than an added parameter there: every other caller of SetOperationStatus is the success path, which has no error to record, and giving them all a permanent "" argument to thread through would have obscured which of the two paths callers actually meant. errMsg is expected to already be redacted by the caller (the daemon layer, which holds the project's redactor); this only bounds its size.
func (*DB) SetOperationResultRef ¶ added in v0.5.1
SetOperationResultRef records a reference on a finished operation, e.g. what a smoke test tested, which the failure path has no other place for.
func (*DB) SetOperationStage ¶ added in v0.6.0
SetOperationStage records the engine's current step on the initiative's running operation (C3, wave 3 contract). It is a plain, event-free update: the stage is a cosmetic progress hint for the CLI/UI wait loop, not a durable domain fact, and an event per stage change would spam the event log that BuildTimeline reads. A no-op (not an error) when the initiative has no running operation right now -- e.g. a synchronous call outside launchOperation, such as change-set review.
func (*DB) SetOperationStatus ¶
func (db *DB) SetOperationStatus(ctx context.Context, opID string, status domain.OperationStatus, resultRef string) error
SetOperationStatus transitions an operation.
func (*DB) SetPushSubscriptionEvents ¶ added in v0.7.0
SetPushSubscriptionEvents replaces the event kinds a subscription wants.
func (*DB) SetReadCursor ¶
SetReadCursor records the last-seen event seq for a scope.
func (*DB) SetRemoteRunAgentRun ¶ added in v0.7.0
SetRemoteRunAgentRun records which agent run a remote run's events feed. An Execute that re-attaches to a run another Execute (or a previous daemon) dispatched moves it to its own run: that is the run being watched.
func (*DB) SetRunManifestReview ¶ added in v0.7.0
func (db *DB) SetRunManifestReview(ctx context.Context, runID string, t domain.ReviewTelemetry) error
SetRunManifestReview records one review cycle's convergence telemetry on the adversarial reviewer's run manifest (migration 38).
A separate write rather than a field CreateRunManifest fills, because the manifest is written inside runModel the moment the reviewer's response validates -- before the loop has classified a single finding. What the telemetry records (re-raised, demoted, the outcome) only exists after that. A run with no manifest (a failed call) has nothing to attach to; the UPDATE then touches no row, which is reported rather than silently ignored.
func (*DB) SetRunNote ¶ added in v0.6.0
SetRunNote records a human note on a run (D-a, wave 3 contract): the optional note on `POST .../execute`/`POST .../retry`, appended to the implementer's brief and kept here as the run's own record of it. Plain update, no event -- the note is provenance on the run, not itself a fact the event log narrates (the run's own created/status events already are).
func (*DB) SetRunStatus ¶
func (db *DB) SetRunStatus(ctx context.Context, runID string, status domain.RunStatus, actor string) error
SetRunStatus transitions a run's status.
func (*DB) SetTaskDependencies ¶ added in v0.6.0
func (db *DB) SetTaskDependencies(ctx context.Context, initiativeID, taskID string, depTaskIDs []string) error
SetTaskDependencies replaces taskID's depends_on edges wholesale with one per (de-duplicated, non-empty, non-self) id in depTaskIDs, refusing -- writing nothing -- if doing so would introduce a dependency cycle anywhere in the initiative's task graph (review M5). The cycle check and the write share this one transaction.
func (*DB) SetTaskStatus ¶
SetTaskStatus updates a task's status (domain methods only, §13).
func (*DB) SplitTask ¶ added in v0.6.0
func (db *DB) SplitTask(ctx context.Context, initiativeID, originalID string, specs []SplitTaskSpec, originalDeps []string) ([]*domain.Task, error)
SplitTask replaces originalID with the given specs in ONE transaction (review M4): the old handler validated and created each replacement inside the same loop, so an invalid second (or third...) spec returned 400 AFTER the first replacement was already created and the original was not yet deleted -- the exact half-applied-write bug this branch had already fixed for PATCH. Every spec here is validated BEFORE any write, all creations share this one transaction, and the original is deleted last, in the same transaction, only if every earlier step succeeded.
Each new task inherits originalDeps (the original's own outgoing depends_on); every dependent of originalID is rewired to depend on ALL the new tasks (a safe superset -- narrowing it is a follow-up `set depends_on`). Returns the created tasks, in spec order.
func (*DB) StartAutomationRun ¶ added in v0.7.0
func (db *DB) StartAutomationRun(ctx context.Context, automation, target, trigger string, startedAtMS int64) (AutomationRun, error)
StartAutomationRun records a run as running and returns it.
func (*DB) SumRunUsage ¶ added in v0.7.0
SumRunUsage sums the usage of every run manifest attributed to an initiative (runs.initiative_id) and counts them -- the token figures GET .../costs does not report. Summed in Go because usage is stored as JSON.
func (*DB) SupersedeAssertions ¶
SupersedeAssertions marks every active assertion of an initiative as superseded, mirroring SupersedeRequirements, so a full workflow retry does not accumulate duplicate framing/research assumptions.
func (*DB) SupersedeModelObjectivesExcept ¶ added in v0.7.0
func (db *DB) SupersedeModelObjectivesExcept(ctx context.Context, initiativeID, supersededBy string, keepIDs []string) error
SupersedeModelObjectivesExcept marks every live, MODEL-authored objective of an initiative superseded except those in keepIDs, along with their model-authored metrics that have never been observed. Used by a PRD revision that dropped an objective.
A human-added objective (an empty produced_by_run_id) is never superseded by a model revision -- it is the human's to change -- and neither is a metric with observations: its history is evidence, and a revision that stopped mentioning it does not make the measurements untrue.
func (*DB) SupersedeRequirements ¶
SupersedeRequirements marks every active requirement of an initiative as removed and records the superseding run. Used by the revise step (§11).
func (*DB) SupersedeRequirementsExcept ¶ added in v0.6.0
func (db *DB) SupersedeRequirementsExcept(ctx context.Context, initiativeID, supersededBy string, keepIDs []string) error
SupersedeRequirementsExcept marks every active requirement of an initiative as removed EXCEPT those in keepIDs, recording the superseding reason. Used by a PRD revision that updates some requirements in place (UpdateRequirement) rather than recreating them (review ICP re-run #1): only the requirements this cycle's response actually dropped are superseded, so the code and every graph edge of a requirement carried forward stays stable across the revision. An empty keepIDs behaves exactly like SupersedeRequirements -- backward compatible, additive API.
func (*DB) SyncAssertionInvalidations ¶ added in v0.7.0
SyncAssertionInvalidations reconciles the initiative's invalidates edges (see syncInvalidatesTx). SetAssertionStatus and SetAssertionBasis already do this in their own transaction; the PRD stage calls it once more after recording a cycle's basis, because a new requirement whose basis matched an earlier one writes no basis edge of its own and so never passed through SetAssertionBasis.
func (*DB) TakeSteeringNotes ¶ added in v0.7.0
func (db *DB) TakeSteeringNotes(ctx context.Context, initiativeID, taskID string) ([]HeldSteeringNote, error)
TakeSteeringNotes marks every pending note of the initiative consumed by taskID's run and returns them, oldest first. One UPDATE ... RETURNING: the read and the mark are a single statement, so two concurrent takers can never both get the same note.
func (*DB) TaskEdges ¶ added in v0.6.0
func (db *DB) TaskEdges(ctx context.Context, initiativeID, taskID string) (requirementIDs, dependsOn []string, err error)
TaskEdges returns one task's requirement_ids (the requirements it implements, via `task --implements--> requirement` edges) and depends_on (via `task --depends_on--> task` edges), for serializing them onto the Task response (GET .../tasks and the merge/split/depends-on responses).
func (*DB) TouchUISession ¶ added in v0.7.0
TouchUISession records activity on a session.
func (*DB) TransitionChangeSet ¶
func (db *DB) TransitionChangeSet(ctx context.Context, changeSetID string, from, to domain.ChangeSetStatus, actor string) error
TransitionChangeSet advances a change set from status `from` to status `to`, enforcing the legal transition matrix. Both the transition legality and the current-state precondition are checked; an illegal or stale transition fails with a clear error and mutates nothing.
func (*DB) TransitionChangeSetWithNote ¶ added in v0.7.0
func (db *DB) TransitionChangeSetWithNote(ctx context.Context, changeSetID string, from, to domain.ChangeSetStatus, actor, note string) error
TransitionChangeSetWithNote is TransitionChangeSet that also records the human's review note (migration 43) in the same transaction, so a verdict and what it asked for are never stored apart. An empty note leaves any existing review_note untouched.
func (*DB) TransitionInitiative ¶ added in v0.4.0
func (db *DB) TransitionInitiative(ctx context.Context, initiativeID string, to domain.InitiativeStatus, actor string, from ...domain.InitiativeStatus) error
TransitionInitiative is the compare-and-swap for a status change that is not a claim.
SetInitiativeStatus is an unconditional UPDATE, so guarding it with a GetInitiative first is the check-then-act this package already rejected for ClaimInitiativeRunning: the read and the write are not atomic with each other. `Approve` did exactly that -- it had no check at all and simply overwrote the status, releasing a claim a running advance was holding, so two advances ran concurrently on one initiative. A guard that reads first would have narrowed that window without closing it.
func (*DB) UnlinkRequirementObjective ¶ added in v0.7.0
func (db *DB) UnlinkRequirementObjective(ctx context.Context, initiativeID, requirementID, objectiveID, actor string) error
UnlinkRequirementObjective removes a requirement --serves--> objective edge.
func (*DB) UnverifyRequirement ¶
UnverifyRequirement resets a verified requirement back to approved and clears verified_at (e.g. when the change set that verified it is reverted). It also clears the requirement's verification evidence in the SAME transaction (review H1): verification_evidence is append-only and PassedCriterionKeys counts every pass regardless of newer rows, so leaving the pass evidence in place after a revert let a bare, no-op `idea verify` re-mark the requirement verified from evidence that was never re-earned (human pass → verify → revert → verify, with nothing new on disk, re-verified it).
func (*DB) UpdateMetric ¶ added in v0.7.0
UpdateMetric rewrites a metric's definition in place. Moving it to another objective re-points its measures edge. Its observations are untouched: a changed target re-evaluates the same history against the new target.
func (*DB) UpdateObjective ¶ added in v0.7.0
UpdateObjective rewrites an objective's statement, rationale, status and owner in place -- same id, same code, every edge kept. A non-empty ProducedByRun adds a produced_by edge for the revising run, as UpdateRequirement does, so every run that shaped it stays in the graph.
func (*DB) UpdateRemoteRun ¶ added in v0.7.0
UpdateRemoteRun applies u. A run already terminal keeps its status: a late "running" from a slow poller must not resurrect a run the operator cancelled, and a reconciler that lost a race to the executor must not overwrite "collected" with "finished". The guard is inside the statement, so there is no read-then-write window.
func (*DB) UpdateRequirement ¶ added in v0.6.0
UpdateRequirement updates an existing requirement's statement, priority and acceptance criteria in place -- same id, same code -- and records the run that produced the revision. Used when a PRD revision continues a requirement's SUBJECT rather than replacing it (review ICP re-run #1): keeping the same id preserves every graph edge already wired to it (derived_from a decision, implements from a task, produced_by an earlier run) instead of orphaning them the way supersede-and-recreate did on every revise cycle. r.ID must already be set to the existing requirement's id.
When the revision actually changes the statement or acceptance criteria of a requirement that has already left draft (review C5) -- approved, verified, failed or waived -- its status is reset to approved, verified_at is cleared, and every verification_evidence row for it is deleted, all in THIS SAME transaction. Without this, a requirement could report verified, with surviving human evidence, for a statement that no longer exists: the evidence was recorded against the OLD subject, and status/verified_at are otherwise untouched by a code-matched revision even though the thing being verified has changed underneath it. A revision that leaves the statement and acceptance criteria byte-for-byte unchanged (e.g. only priority moved) is not treated as re-opening verification. A still-draft requirement (an in-progress PRD review cycle revising it before it has ever been approved) is left in draft -- resetting it to approved here would let a mid-review revision jump the requirement past the review gate it hasn't passed yet.
func (*DB) UpdateTask ¶
func (db *DB) UpdateTask(ctx context.Context, initiativeID, taskID, title, statement string, priority domain.RequirementPriority, estimate string) error
UpdateTask edits a task's human-editable fields. Guarded at the handler layer (only while the plan is editable and the task is not done/cancelled).
func (*DB) UpsertPushSubscription ¶ added in v0.7.0
func (db *DB) UpsertPushSubscription(ctx context.Context, s PushSubscription) (PushSubscription, bool, error)
UpsertPushSubscription stores a subscription, keyed by endpoint: the same browser subscribing again (a new tab, a re-grant) refreshes its keys and events rather than creating a second row that would notify it twice.
func (*DB) WireDecisionDerivedFromQuestion ¶
func (db *DB) WireDecisionDerivedFromQuestion(ctx context.Context, initiativeID, decisionID, questionID string) error
WireDecisionDerivedFromQuestion links a decision to the open question it resolves (decision derived_from question), so the decision's provenance is traceable through why/impact.
func (*DB) WireDocConsumes ¶
func (db *DB) WireDocConsumes(ctx context.Context, initiativeID, runID string, docIDs []string) error
WireDocConsumes records that a run consumed a set of context documents (run --consumes--> context_doc). This is deterministic provenance: the engine knows exactly which docs it injected into a run's inputs, so no model attribution is required. It wires the edges atomically with a run event.
func (*DB) WireRequirementDerivedFromDecision ¶
func (db *DB) WireRequirementDerivedFromDecision(ctx context.Context, initiativeID, requirementID, decisionID string) error
WireRequirementDerivedFromDecision links a requirement to the decision that shaped it (requirement derived_from decision), so an open decision's impact ("blocks N") is the set of requirements waiting on its resolution.
type EdgeToWrite ¶
type EdgeToWrite struct {
FromType string
FromID string
EdgeType domain.EdgeType
ToType string
ToID string
}
EdgeToWrite describes one Product Graph edge to write within a transaction.
type Event ¶
type Event struct {
ID string
AggregateType string
AggregateID string
Actor string
CorrelationID string
CausationID string
Operation string
EventType string
PayloadDigest string
}
Event is an append-only event record (§32). PayloadDigest references a blob already stored (and redacted) by the caller.
type EventRow ¶
type EventRow struct {
Seq int64 `json:"seq"`
ID string `json:"id"`
AggregateType string `json:"aggregate_type"`
AggregateID string `json:"aggregate_id"`
Actor string `json:"actor"`
CorrelationID string `json:"correlation_id"`
CausationID string `json:"causation_id"`
Operation string `json:"operation"`
EventType string `json:"event_type"`
PayloadDigest string `json:"payload_digest"`
CreatedAtMS int64 `json:"created_at_ms"`
}
EventRow is a materialized event.
type HeldSteeringNote ¶ added in v0.7.0
type HeldSteeringNote struct {
ID int64
InitiativeID string
// TaskID and RunID are the task and run the note was sent to.
TaskID string
RunID string
Note string
}
HeldSteeringNote is one note held for an initiative's next run.
type InitiativeBudget ¶ added in v0.7.0
type InitiativeBudget struct {
// CapUSD is the initiative's own cap; nil inherits the project default.
CapUSD *float64
// ParkedFrom is the status ("plan_approved", "needs_human_judgment:prd_review",
// ...) the initiative held before a budget stop parked it; "" otherwise.
ParkedFrom string
}
InitiativeBudget is one initiative's own spending-cap state.
type InitiativeRollup ¶
type InitiativeRollup struct {
ID string `json:"id"`
Title string `json:"title"`
Status domain.InitiativeStatus `json:"status"`
// JudgmentReason is why the initiative is parked. All four reasons share
// `needs_human_judgment`, so the status alone cannot tell a PRD-review park
// from a plan-stage one -- and ProductHome derives its phase rail from this
// rollup, so without it that page has to guess from artifact presence, which
// is wrong for exactly the plan_dependencies case.
JudgmentReason domain.JudgmentReason `json:"judgment_reason,omitempty"`
Artifacts []ArtifactRollup `json:"artifacts"`
TaskStatuses []string `json:"task_statuses"`
ChangeSetStatuses []string `json:"change_set_statuses"`
OpenDecisions int `json:"open_decisions"`
OpenQuestions int `json:"open_questions"`
OpenFindings int `json:"open_findings"`
VerifiedRequirements int `json:"verified_requirements"`
}
InitiativeRollup is a cross-initiative summary: the phase-derivation inputs (artifacts/tasks/change sets) plus the open-item counts for the attention inbox, gathered with a handful of grouped queries instead of one round trip per initiative per entity (the ProductHome N+1).
type IntegrationLink ¶ added in v0.7.0
type IntegrationLink struct {
Integration string `json:"integration"`
Kind string `json:"kind"`
LocalID string `json:"local_id"`
RemoteID string `json:"remote_id"`
RemoteKey string `json:"remote_key,omitempty"`
RemoteURL string `json:"remote_url,omitempty"`
RemoteState string `json:"remote_state,omitempty"`
Note string `json:"note,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
IntegrationLink maps a local object to a remote one.
type MetricRef ¶ added in v0.7.0
MetricRef is what the integration bus needs to narrate an outcome metric's drift: its initiative, its code and name, and its objective's code.
type NotFoundError ¶
type NotFoundError struct {
Kind string // "change set", "initiative", "requirement", …
Ref string // what the caller asked for
}
NotFoundError is the store's answer for a lookup that matched nothing. It carries the kind and the reference the caller asked for, so every layer above can render "no change set matching \"CHG-99\"" instead of the driver's "sql: no rows in result set", and the daemon can map it to 404.
It unwraps to sql.ErrNoRows so existing errors.Is checks keep working.
func (*NotFoundError) Error ¶
func (e *NotFoundError) Error() string
func (*NotFoundError) Unwrap ¶
func (e *NotFoundError) Unwrap() error
type OutboxInsert ¶ added in v0.7.0
type OutboxInsert struct {
Subscriber string
IdempotencyKey string
EventSeq int64
Kind string
PayloadJSON string
}
OutboxInsert is the ingest-side shape of an outbox row.
type OutboxRow ¶ added in v0.7.0
type OutboxRow struct {
ID string
Subscriber string
IdempotencyKey string
EventSeq int64
Kind string
PayloadJSON string
Status string
Attempts int
NextAttemptAt time.Time
LastError string
CreatedAt time.Time
DeliveredAt *time.Time
}
OutboxRow is one (subscriber, domain event) delivery.
type OutboxStats ¶ added in v0.7.0
type OutboxStats struct {
Pending int `json:"pending"`
Delivered int `json:"delivered"`
Dead int `json:"dead"`
LastError string `json:"last_error,omitempty"`
LastDeliveredAt *time.Time `json:"last_delivered_at,omitempty"`
}
OutboxStats summarizes one subscriber's outbox for health reporting.
type PhaseCostRow ¶ added in v0.6.0
PhaseCostRow is one (stage, run kind) group of an initiative's model-call spend/time (C3, wave 3 contract).
type ProjectRecord ¶
type ProjectRecord struct {
ID string `json:"id"`
Name string `json:"name"`
RootPath string `json:"root_path"`
ProjectID string `json:"project_id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
ProjectRecord is a registered project in global.db.
type PushSubscription ¶ added in v0.7.0
type PushSubscription struct {
ID string
Endpoint string
P256dh string
Auth string
Events []string
Label string
CreatedAt time.Time
UpdatedAt time.Time
LastDeliveredAt *time.Time
LastError string
// RenewalTokenHash is the SHA-256 (hex) of the subscription's renewal
// token (migration 49). Write-only here: Upsert stores it when set, and
// no read returns it.
RenewalTokenHash string
}
PushSubscription is one browser's Web Push subscription for a project (migration 46). Endpoint, P256dh and Auth are what a push service needs to reach that browser; the API never returns them.
type QualityLink ¶ added in v0.7.0
QualityLink is one quality result's `verifies` edge target: a requirement id (and its code, for the result's Requirements list).
type RemoteRunUpdate ¶ added in v0.7.0
type RemoteRunUpdate struct {
ConversationID *string
RemoteDir *string
BaseDigest *string
Status *domain.RemoteRunStatus
RemoteStatus *string
Error *string
}
RemoteRunUpdate is a partial update; nil fields are left alone.
type RunEventPage ¶ added in v0.7.0
type RunEventPage struct {
RunID string `json:"run_id"`
Events []domain.RunEvent `json:"events"`
// FirstSeq is the oldest seq still stored for the run (0 when it has
// none). Greater than 1 means the per-run cap dropped earlier events.
FirstSeq int64 `json:"first_seq"`
// LastSeq is the newest seq stored for the run: the cursor to resume
// from once this page has been read and More is false.
LastSeq int64 `json:"last_seq"`
// More reports that events after this page exist; ask again with
// after = the last event's seq.
More bool `json:"more"`
}
RunEventPage is one page of a run's events, oldest first.
type RunEventRow ¶ added in v0.7.0
RunEventRow is a stored event with its project-wide id, the cursor of the project event stream.
type RunInfo ¶ added in v0.7.0
type RunInfo struct {
ID string
Kind string
Status string
InitiativeID string
Stage string
Note string
StartedAt time.Time
FinishedAt *time.Time
}
RunInfo is the part of a runs row the run view and report need.
type SplitTaskSpec ¶ added in v0.6.0
type SplitTaskSpec struct {
Title string
Statement string
Priority domain.RequirementPriority
RequirementIDs []string
}
SplitTaskSpec is one replacement task for SplitTask (review M4, B3): a title, statement, priority, and the requirement ids it implements. RequirementIDs must be non-empty -- "Added tasks take a requirement" -- the caller (the handler, which alone has access to resolveRequirementRefs) is responsible for resolving referenced codes to ids and defaulting to the original task's own requirements before this is ever called.
type TimelineChangeSetEvent ¶ added in v0.6.0
type TimelineChangeSetEvent struct {
ChangeSetID string
HumanID string
TaskID string
EventType string // "change_set.applied" | "change_set.reverted" | "change_set.status_changed"
Operation string // "from->to" for status_changed
Actor string
At time.Time
}
TimelineChangeSetEvent is one change_set-aggregate event scoped to a change set that belongs to the given initiative (C1, wave 3 contract): the join that makes BuildTimeline correct where the old What Changed projection was not -- it read the whole events table with no initiative filter at all, so one initiative's "changed" leaked another's counts.
type TimelineDecisionEvent ¶ added in v0.6.0
type TimelineDecisionEvent struct {
DecisionID string
Code string
Question string
EventType string // "decision.resolved" | "decision.reopened"
Actor string
At time.Time
}
TimelineDecisionEvent is one decision-aggregate event scoped to a decision that belongs to the given initiative (C1, wave 3 contract).
type TimelineStatusEvent ¶ added in v0.6.0
TimelineStatusEvent is one initiative.status_changed event.
type UISession ¶ added in v0.7.0
type UISession struct {
ID string `json:"id"`
Label string `json:"label,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
RemoteAddr string `json:"remote_addr,omitempty"`
CreatedAt time.Time `json:"created_at"`
LastSeenAt time.Time `json:"last_seen_at"`
ExpiresAt time.Time `json:"expires_at"`
RevokedAt *time.Time `json:"revoked_at,omitempty"`
}
UISession is one browser session of the web UI, signed in remotely with a pairing code (global.db, migration 2). The session secret itself is never stored -- only its hash -- so this record can be listed without care.
Source Files
¶
- artifact.go
- budget.go
- capture.go
- changeset.go
- contextdocs.go
- dependson.go
- doccomment.go
- errors.go
- event.go
- gaps.go
- global.go
- graph.go
- integration.go
- invalidates.go
- merge.go
- migrate.go
- nooop_backfill.go
- outcomes.go
- push.go
- quality.go
- remoterun.go
- repo.go
- risk.go
- rollup.go
- runevent.go
- runrepo.go
- secret_allowlist.go
- split.go
- stale.go
- steering.go
- store.go
- timeline.go
- uisession.go
- verify.go