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
- type AgentRunStats
- type ArtifactRollup
- type ArtifactView
- 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) AppendJournal(ctx context.Context, e *domain.ApplyJournalEntry) 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) CancelOperationStatus(ctx context.Context, opID string) 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) 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) 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) CreateOperation(ctx context.Context, projectID, initiativeID, opType string) (string, error)
- func (db *DB) CreateQuestion(ctx context.Context, q *domain.Question) 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) 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) FailInitiative(ctx context.Context, initiativeID, reason string) 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) GetOperation(ctx context.Context, opID string) (domain.Operation, error)
- func (db *DB) GetProject(ctx context.Context, projectID string) (ProjectRecord, error)
- func (db *DB) GetReadCursor(ctx context.Context, scope string) (int64, error)
- func (db *DB) GetRequirementByRef(ctx context.Context, initiativeID, ref string) (*domain.Requirement, 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) HasDissent(ctx context.Context, decisionID string) (bool, error)
- func (db *DB) InTx(ctx context.Context, fn func(tx *sql.Tx) error) error
- func (db *DB) JournalSnapshotDigest(ctx context.Context, changeSetID string) (string, error)
- func (db *DB) LatestOperationOfType(ctx context.Context, projectID, opType string) (*domain.Operation, error)
- func (db *DB) ListAgentRunStats(ctx context.Context, initiativeID string) (AgentRunStats, 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) 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) 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) ListJournal(ctx context.Context, changeSetID string) ([]domain.ApplyJournalEntry, error)
- func (db *DB) ListModelPhaseCosts(ctx context.Context, initiativeID string) ([]PhaseCostRow, error)
- func (db *DB) ListOperationsByInitiative(ctx context.Context, initiativeID string) ([]domain.Operation, error)
- func (db *DB) ListProjects(ctx context.Context) ([]ProjectRecord, error)
- func (db *DB) ListQuestions(ctx context.Context, initiativeID string) ([]domain.Question, error)
- func (db *DB) ListRequirements(ctx context.Context, initiativeID string) ([]domain.Requirement, 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) ListUnfinishedOperations(ctx context.Context) ([]domain.Operation, 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) 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) MergeTasks(ctx context.Context, initiativeID, keepID, mergeID string) (*domain.Task, error)
- func (db *DB) NeedsHumanJudgment(ctx context.Context, initiativeID string, reason domain.JudgmentReason, ...) error
- func (db *DB) PassedCriterionKeys(ctx context.Context, requirementID string) (map[string]bool, error)
- func (db *DB) ReconcileChangeSets(ctx context.Context) ([]ChangeSetRecovery, error)
- func (db *DB) RecordHumanEvidence(ctx context.Context, initiativeID, requirementID string, ...) error
- func (db *DB) RegisterProject(ctx context.Context, name, rootPath, projectID string) (string, error)
- func (db *DB) ReleaseInitiativeClaim(ctx context.Context, initiativeID string, to domain.InitiativeStatus, ...) 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) 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) ResolveDecision(ctx context.Context, decisionID, resolution, actor string) error
- func (db *DB) RevokeSecretAllowlist(ctx context.Context, id string) error
- 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) 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) 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) 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) SetReadCursor(ctx context.Context, scope string, seq int64) 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) SupersedeAssertions(ctx context.Context, initiativeID, supersededBy 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) TaskEdges(ctx context.Context, initiativeID, taskID string) (requirementIDs, dependsOn []string, err error)
- func (db *DB) TransitionChangeSet(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) UnverifyRequirement(ctx context.Context, requirementID, actor string) 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) 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 InitiativeRollup
- type NotFoundError
- type PhaseCostRow
- type ProjectRecord
- type SplitTaskSpec
- type TimelineChangeSetEvent
- type TimelineDecisionEvent
- type TimelineStatusEvent
Constants ¶
const ActorOrchestrator = "orchestrator"
ActorOrchestrator is the default event actor for deterministic workflow steps.
const HumanActor = "human"
HumanActor is the actor identity for human actions (§11, §15).
Variables ¶
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 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.
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 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) AppendJournal ¶
AppendJournal inserts one apply-journal record (§39).
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) 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) 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) 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) 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) 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) CreateQuestion ¶
CreateQuestion inserts an open question.
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) 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) 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) 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) GetOperation ¶
GetOperation returns an operation.
func (*DB) GetProject ¶
GetProject returns a project by its project_id.
func (*DB) GetReadCursor ¶
GetReadCursor returns the last-seen event seq for a scope (0 if none).
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) GetRunManifest ¶
GetRunManifest returns a manifest by run id.
func (*DB) HasDissent ¶
HasDissent reports whether a decision has any preserved dissent (§8).
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) 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) 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) 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) 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) 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) 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) 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) 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) ListProjects ¶
func (db *DB) ListProjects(ctx context.Context) ([]ProjectRecord, error)
ListProjects returns all registered projects.
func (*DB) ListQuestions ¶
ListQuestions returns questions for an initiative.
func (*DB) ListRequirements ¶
func (db *DB) ListRequirements(ctx context.Context, initiativeID string) ([]domain.Requirement, error)
ListRequirements returns requirements for an initiative.
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) ListUnfinishedOperations ¶
ListUnfinishedOperations returns operations not in a terminal state (for daemon restart reconciliation, §16).
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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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.
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) 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) SetReadCursor ¶
SetReadCursor records the last-seen event seq for a scope.
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) 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) 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) 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) 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) 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) 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) 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) 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 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 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 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 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).