Documentation
¶
Overview ¶
Package workflow implements the deterministic M1 stage graph and the orchestrator that drives it (§6, §11). The orchestrator is constrained by workflow policy: it runs stages in order and may only rank/explain next moves within that policy.
Index ¶
- Constants
- Variables
- func ImplementerModelSpec(cfg config.HarnessConfig, registry *model.Registry) string
- func ImplementerProvider(cfg config.HarnessConfig, registry *model.Registry) (executor.AgentProvider, error)
- func NormalizeRequirementRef(raw string) string
- func PlanNotReadyForExecution(ini domain.Initiative) string
- func ValidNodeType(typ string) bool
- type Coverage
- type DiffDecision
- type DiffRequirement
- type Engine
- func (e *Engine) Advance(ctx context.Context, initiativeID string) (domain.InitiativeStatus, error)
- func (e *Engine) AgentOutput(ctx context.Context, initiativeID string) (state string, output string)
- func (e *Engine) ApplyChangeSet(ctx context.Context, initiativeID, changeSetID string) error
- func (e *Engine) Approve(ctx context.Context, initiativeID string) error
- func (e *Engine) ApprovePlan(ctx context.Context, initiativeID string) (domain.InitiativeStatus, error)
- func (e *Engine) BackfillNoOpChangeSets(ctx context.Context) (int, error)
- func (e *Engine) ConvergeDecisions(ctx context.Context, initiativeID string) error
- func (e *Engine) Coverage(ctx context.Context, initiativeID string) ([]Coverage, error)
- func (e *Engine) CreatePR(ctx context.Context, initiativeID string) (string, error)
- func (e *Engine) DescribeImages(ctx context.Context, initiativeID string) error
- func (e *Engine) DiscardPartial(initiativeID string) error
- func (e *Engine) DiscussDecision(ctx context.Context, decisionID, message string) (string, error)
- func (e *Engine) Execute(ctx context.Context, initiativeID string) (domain.ChangeSet, error)
- func (e *Engine) ExecutePrecondition(ctx context.Context, initiativeID string) error
- func (e *Engine) Impact(ctx context.Context, initiativeID, nodeType, nodeID string) ([]ImpactItem, error)
- func (e *Engine) ImpactCounts(ctx context.Context, initiativeID string, nodes []NodeRef) (map[string]int, error)
- func (e *Engine) NextAction(ctx context.Context, initiativeID string) (string, error)
- func (e *Engine) NextReadyTask(ctx context.Context, initiativeID string) (*NextTask, error)
- func (e *Engine) PRChecks(ctx context.Context, changeSetID string) (git.PRChecksResult, error)
- func (e *Engine) PartialWork(initiativeID string) *PartialWorkInfo
- func (e *Engine) PromoteDocComment(ctx context.Context, commentID string) (*domain.Question, error)
- func (e *Engine) RecordHumanEvidence(ctx context.Context, initiativeID, requirementRef string, ...) error
- func (e *Engine) RecordHumanPass(ctx context.Context, initiativeID, requirementRef, note, actor string) error
- func (e *Engine) RejectConflicted(ctx context.Context, initiativeID, changeSetID string) error
- func (e *Engine) Reload(cfg config.HarnessConfig, registry *model.Registry, ...)
- func (e *Engine) RenderPatch(cs *domain.ChangeSet) string
- func (e *Engine) RenderPatchPage(cs *domain.ChangeSet) (rendered string, total int)
- func (e *Engine) ReopenPhase(ctx context.Context, initiativeID, phase string) (domain.InitiativeStatus, error)
- func (e *Engine) RerunChangeSetReview(ctx context.Context, initiativeID, changeSetID string) error
- func (e *Engine) ResetConflictedForRetry(ctx context.Context, initiativeID, changeSetID string) error
- func (e *Engine) RestoreWorkspace(ctx context.Context, changeSetID, manifestDigest string) error
- func (e *Engine) Resume(ctx context.Context, initiativeID string) (status domain.InitiativeStatus, err error)
- func (e *Engine) Retry(ctx context.Context, initiativeID string) (domain.InitiativeStatus, error)
- func (e *Engine) RevertBlockedReason(ctx context.Context, initiativeID, changeSetID string) (string, error)
- func (e *Engine) RevertChangeSet(ctx context.Context, initiativeID, changeSetID string) error
- func (e *Engine) ReviewChangeSet(ctx context.Context, initiativeID, changeSetID, verdict string) error
- func (e *Engine) ReviewChangeSetAccepting(ctx context.Context, initiativeID, changeSetID, verdict string) error
- func (e *Engine) Revise(ctx context.Context, initiativeID string) (domain.InitiativeStatus, error)
- func (e *Engine) RevisePlan(ctx context.Context, initiativeID string) (domain.InitiativeStatus, error)
- func (e *Engine) Run(ctx context.Context, initiativeID, idea string) (domain.InitiativeStatus, error)
- func (e *Engine) RunBlockedReason(ctx context.Context, initiativeID string) (string, error)
- func (e *Engine) SemanticDiff(ctx context.Context, initiativeID string) (*SemanticDiff, error)
- func (e *Engine) SetDotEnv(dotEnv map[string]string)
- func (e *Engine) SetModelOverride(initiativeID, spec string)
- func (e *Engine) SetNoteOverride(initiativeID, note string)
- func (e *Engine) SetRawBlobs(b *blob.Store)
- func (e *Engine) SetRedactor(r *security.Redactor)
- func (e *Engine) SetWorkRoot(dir string)
- func (e *Engine) SetWorkspaceRoot(dir string)
- func (e *Engine) StructuredDiff(cs *domain.ChangeSet) []StructuredFile
- func (e *Engine) StructuredDiffPage(cs *domain.ChangeSet) (files []StructuredFile, total int)
- func (e *Engine) SuggestAnswers(ctx context.Context, initiativeID string, emit func([]domain.SuggestedAnswer)) error
- func (e *Engine) VerifyInitiative(ctx context.Context, initiativeID string) error
- func (e *Engine) Why(ctx context.Context, initiativeID, nodeType, nodeID string) ([]TraceItem, error)
- type ErrReviewUnavailable
- type ImpactItem
- type NextTask
- type NodeRef
- type PartialWorkInfo
- type RigorLevel
- type SemanticDiff
- type StructuredFile
- type TraceItem
Constants ¶
const ( StageFraming = "framing" StageResearch = "research" StageProductDefinition = "product_definition" StageReview = "review" )
Stage keys for the M1 graph.
const ( StageArchitecture = "architecture" StageProductDesign = "product_design" StageVerificationDesign = "verification_design" StageConvergence = "convergence" StageExecutionPlan = "execution_plan" StageExecutionPlanReview = "execution_plan_review" StageImplementationBrief = "implementation_brief" )
Stage keys for the M2 graph (§12).
const ( RoleOrchestrator = "product_orchestrator" RoleResearchAnalyst = "research_analyst" RoleProductManager = "product_manager" RoleAdversarialReviewer = "adversarial_reviewer" RoleArchitect = "architect" RoleProductDesigner = "product_designer" RoleVerificationEngineer = "verification_engineer" RoleEngineeringLead = "engineering_lead" )
Role names (must match contracts/*.yaml).
const ( LiveIdle = "idle" // no run in progress LiveStarting = "starting" // a run is preparing: planning, copying the workspace LiveRunning = "running" // the agent is running LiveFinished = "finished" // the agent is done; the run is in its checks )
Live output states, as reported to clients.
const ChangeSetReviewSchemaName = "change_set_review"
ChangeSetReviewSchemaName is the fake provider's queue key for the change-set adversarial review. Exported so demoProvider can prime it and tests can steer it; it never reaches a real provider.
const DeterministicPlanCheckRun = "deterministic-plan-check"
DeterministicPlanCheckRun is the ReviewRunID stamped on every finding deterministicPlanChecks produced, distinguishing them from the adversarial reviewer's, whose run id runModel supplies. The daemon reads it to refuse `approve-plan` over a structural defect a human cannot meaningfully accept. The PRD loop's equivalent literal is "deterministic-check", deliberately different, so the two sets cannot be confused.
const PlanFindingTarget = "execution_plan"
PlanFindingTarget is the target type of every finding raised against the execution plan. The UI shows these on the Plan page, where approval happens.
const RigorCapCategory = "review_rigor"
RigorCapNote is the category stamped on the synthetic observation finding capFindings adds when it drops findings, so the UI and tests can find it without string-matching the whole findings list.
Variables ¶
var ErrNoInitiativeBranch = errors.New("workflow: this initiative has no dedicated branch yet; " +
"enable git.branch_per_initiative and apply a change set first")
ErrNoInitiativeBranch is returned by CreatePR when the initiative has no dedicated branch yet AND git.branch_per_initiative is off -- the message names the actual fix in that case: turn the setting on, then apply a change set. It must not be returned verbatim when the setting is already on (see noInitiativeBranchError): a real founder-journey run hit `idea pr` with git.branch_per_initiative already enabled and no change set applied yet, and got told to "enable git.branch_per_initiative" -- advice for a state the initiative was not in.
var ErrNoPR = errors.New("workflow: this initiative has no pull request yet; run `idea pr` first")
ErrNoPR is returned by PRChecks when the initiative has no pull request yet.
var ErrNoReadyTask = errors.New("workflow: no ready tasks")
ErrNoReadyTask is what nextReadyTask returns when the initiative has nothing runnable. A sentinel rather than a bare error so callers can tell it from the storage failures the same function can return -- NextAction has to make exactly that distinction.
var GraphNodeTypes = []string{
"task", "requirement", "decision", "question", "artifact", "context_doc", "run",
}
GraphNodeTypes is the closed set of node types the product graph addresses. Exported so the daemon can reject an unknown one at the edge rather than answering an empty traversal.
Functions ¶
func ImplementerModelSpec ¶ added in v0.5.0
func ImplementerModelSpec(cfg config.HarnessConfig, registry *model.Registry) string
ImplementerModelSpec is the model the coding agent runs: models.implementer, then executor.model, then the implementer role's usual resolution. Exported so the daemon's "can a run start" check resolves exactly what Execute will; it checked executor.model alone and so blocked runs Execute would accept, and passed ones it would refuse.
func ImplementerProvider ¶ added in v0.5.0
func ImplementerProvider(cfg config.HarnessConfig, registry *model.Registry) (executor.AgentProvider, error)
ImplementerProvider resolves the provider the coding agent will use, as Execute does.
func NormalizeRequirementRef ¶ added in v0.6.0
NormalizeRequirementRef normalizes a model- or human-supplied requirement reference for tolerant matching against a Requirement.Code (review A4 #4): trimmed, upper-cased, and a "REQ-3: title" form reduced to the code prefix before the colon. Exported so the daemon's task-editing handlers (`add task` / `update task`) apply the identical tolerance.
func PlanNotReadyForExecution ¶ added in v0.5.0
func PlanNotReadyForExecution(ini domain.Initiative) string
PlanNotReadyForExecution returns why an initiative waiting on a human cannot have its tasks run yet, or "".
needs_human_judgment covers parks before the plan is approved (the PRD or the plan under review) as well as after (verification). Execution was allowed from all of them, so from a plan-review park it ran tasks from an unapproved plan -- and left the initiative where approve-plan and revise-plan were both refused. The Build page then offered that one click away.
func ValidNodeType ¶ added in v0.4.0
ValidNodeType reports whether typ names a node the graph can hold.
Nothing validated it, so `idea why requirements REQ-1` -- a plural typo -- answered "No provenance edges found." and exited 0. A bad *id* was caught and a bad *type* was not, which turns a provenance question into a confident false negative on the product's headline claim.
Types ¶
type Coverage ¶
type Coverage struct {
Code string `json:"code"`
Pass int `json:"pass"`
Total int `json:"total"`
NeedsManual int `json:"needs_manual"`
Status string `json:"status"`
}
Coverage is a per-requirement verification-coverage summary (§70).
type DiffDecision ¶
type DiffDecision struct {
Code string `json:"code"`
Question string `json:"question"`
Resolution string `json:"resolution,omitempty"`
}
DiffDecision is one decision in the semantic diff.
type DiffRequirement ¶
type DiffRequirement struct {
Code string `json:"code"`
Statement string `json:"statement"`
Priority string `json:"priority"`
}
DiffRequirement is one requirement in the semantic diff.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine drives the M1 workflow.
func New ¶
func New(db *store.DB, blobs *blob.Store, registry *model.Registry, cfg config.HarnessConfig, log *slog.Logger) *Engine
New builds an engine.
func (*Engine) AgentOutput ¶ added in v0.5.1
func (e *Engine) AgentOutput(ctx context.Context, initiativeID string) (state string, output string)
AgentOutput returns the end of a running agent's output for an initiative, redacted and sanitized, and whether the agent is still running. It never takes e.mu.
func (*Engine) ApplyChangeSet ¶
ApplyChangeSet applies an approved change set: approved→applying→applied. It writes the orchestrator-computed diff into the canonical workspace via atomic per-file temp+rename, capturing the pre-image into the journal so revert can restore it byte-for-byte (§39, review B1).
func (*Engine) Approve ¶
Approve records explicit human approval of the initiative (§11): the reviewed PRD is accepted as it stands, findings and all, and the initiative moves on to design.
Compare-and-swap, not a read-then-write. This was an unconditional SetInitiativeStatus with no check whatsoever, so it overwrote whatever the initiative was doing -- including releasing the claim a running `advance` was holding, after which a second advance was accepted and two ran concurrently on one initiative. Reading the status first would have narrowed that window without closing it, which is the same check-then-act ClaimInitiativeRunning exists to avoid.
`approved` is a legal source so a repeated approve is a no-op rather than an error. Every other status is refused: `running` because work is in flight, `plan_approved` and `complete` because approving there walks the state machine backwards, and `failed` because the recovery for that is `idea retry`.
func (*Engine) ApprovePlan ¶
func (e *Engine) ApprovePlan(ctx context.Context, initiativeID string) (domain.InitiativeStatus, error)
ApprovePlan accepts a plan whose review raised findings: it records the human's acceptance of them and moves the initiative to plan_approved. It does not regenerate tasks, and it is terminal -- there is no re-evaluation and no path back to needs_human_judgment, which is what makes it an accept rather than a retry.
Gated on the reason, exactly as Approve is, and for the same defect. All four JudgmentReasons share one status, so a status-only gate let this accept a plan parked on `plan_dependencies` -- where the undisposed `plan_dependency` finding IS the guard that keeps a dependency graph known to be incomplete out of `complete`, something advance.go relies on in three places and the CHANGELOG states outright. Approving there shipped the incomplete graph.
The change-set guard matches RevisePlan and ReopenPhase. Without it, an initiative already building could have its change set's findings swept by a plan-level command -- and a blocking change-set finding is the one this repository repeatedly calls unclearable by any CLI command.
The disposition lives here and not in runExecutionPlanReview, which Advance, RevisePlan and ReopenPhase also call: on those paths the plan was regenerated and nobody accepted anything, so attributing an acceptance to a human would be a lie. accepted_risk by HumanActor, the same pair Approve records, because that is what happened -- nothing was fixed.
func (*Engine) BackfillNoOpChangeSets ¶ added in v0.6.0
BackfillNoOpChangeSets recomputes no_op for every change set migration 34 left at its conservative default of false (review MEDIUM #1). The migration's comment argued file counts "aren't recomputable" -- they are: the patch manifest was persisted unconditionally before no_op existed, so len(loadPatch(cs).Files) == 0 is one blob read per row. The recompute doesn't happen IN the migration because a migration is plain SQL text (store.migrations) with no access to the blob store; this runs once, at daemon start, after both the DB and the raw blob store exist (see runtime.go's EnsureProject), gated by store.ClaimNoOpBackfill's persisted marker so it costs one query per project on every later start rather than a full table scan.
A change set whose patch can no longer be read (a blob evicted or corrupted independently of this fix) is left at no_op=false -- exactly migration 34's own fallback for a row it cannot recompute -- rather than failing the whole backfill.
func (*Engine) ConvergeDecisions ¶
ConvergeDecisions runs the orchestrator synthesis across every open decision that has preserved dissents (§M2 tail). For each such decision the product orchestrator reconciles the dissenting positions into a single synthesized recommendation, which is stored back on the decision (and surfaced as its synthesis in the projection). Dissents themselves are never erased (§8).
func (*Engine) Coverage ¶
Coverage computes the verification coverage for each requirement of an initiative (pass criteria / total criteria, plus how many still need a human). The requirement's status is surfaced so consumers can distinguish waived and failed (neither of which is "needs manual sign-off") from genuinely pending.
func (*Engine) CreatePR ¶ added in v0.6.0
CreatePR pushes an initiative's dedicated branch and opens a pull request via `gh pr create` (review C4 piece 3), with a body built from the initiative's title, description, change sets and verification progress. Idempotent: a repeat call returns the already-recorded PR URL rather than opening a second PR for the same branch.
func (*Engine) DescribeImages ¶
DescribeImages describes every image context doc that lacks a description, using a vision-capable model. Each description is stored (redacted) and its digest recorded so contextDocs can inject it. Failures are logged per-doc and do not block the remaining docs.
func (*Engine) DiscardPartial ¶ added in v0.5.1
DiscardPartial throws the initiative's kept partial away. It is called by "Start over", and by reopening a phase or revising the plan, which can change the task it belongs to.
func (*Engine) DiscussDecision ¶
DiscussDecision runs one human→AI discussion turn on a decision (§8): the human asks for elaboration or proposes an alternative, and the product manager replies. Both messages are persisted to the decision's thread.
func (*Engine) Execute ¶
Execute runs the multi-role pipeline for the next ready task — planner (engineering_lead brief) → implementer (executor writes files) → deterministic checks → review_required/rejected. The adversarial reviewer runs at review time (§50).
func (*Engine) ExecutePrecondition ¶ added in v0.6.0
ExecutePrecondition runs Execute's own fast, read-only guards -- task selection, another open change set, executor resolution, the trust-tier gate, and a prior change set of the SAME task left mid-review or as an unresolved no-op -- without doing any of Execute's actual work. It exists so Runtime.ExecuteInitiativeFreshWithNote can call it SYNCHRONOUSLY, before ever creating an operation (ICP re-run D5).
Execute is asynchronous: before this existed, every one of these guards ran only inside the launchOperation goroutine, strictly after the daemon had already answered 202 and the CLI had already printed "✓ execute started". A guard that refuses in under a millisecond, at zero model cost -- the ordinary case, since none of them call a model -- then landed a moment later as an operation failure: a success line immediately followed by a failure, for a run that in fact never started at all.
This mirrors, but does not replace, the identical checks inlined in Execute below: they remain the backstop for the genuine race window between this call returning and the task actually being claimed, the same reasoning ExecuteInitiativeFreshWithNote's own NextReadyTask precheck already documents. Deliberately excluded: the changes_requested -> superseded transition Execute performs over the same prior-change-set loop is a WRITE, not a read -- calling it here too would supersede a change set during the precondition check and then find it no longer changes_requested when Execute runs for real a moment later.
No engine mutex: like the exported NextReadyTask, every read here is a plain table scan with no dependency on state e.mu protects, so it is safe to call from outside Execute's own locked section.
func (*Engine) Impact ¶
func (e *Engine) Impact(ctx context.Context, initiativeID, nodeType, nodeID string) ([]ImpactItem, error)
Impact returns the dependents of a node: it follows incoming edges (from nodes that point to this node) with a staleness classification.
A task's change sets are not wired as graph edges (review A4 #4: a change set is linked to its task via ChangeSet.TaskID, not an edge), so when the frontier reaches a task node, its change sets are pulled in by query and added as synthetic dependents -- otherwise `impact requirement REQ-n` (or `impact decision DEC-n`) could reach the task and stop there, never reaching the CHG built from it (review A4 #4/#5: "impact is true").
func (*Engine) ImpactCounts ¶
func (e *Engine) ImpactCounts(ctx context.Context, initiativeID string, nodes []NodeRef) (map[string]int, error)
ImpactCounts returns, for each node, the number of unique transitive dependents (nodes that directly or indirectly depend on it). Used to render "blocks N" without an Impact call per node.
Unlike Impact — which returns one item per edge and can repeat a node that is reachable via multiple paths — these counts are DEDUPED by node, so a count is the number of distinct blocked nodes, not the number of edges. In a cycle the queried node itself may appear among its dependents (mirroring Impact's frontier semantics).
func (*Engine) NextAction ¶
NextAction returns the deterministic next step for an initiative (§52, Track C). It stops at human judgment points (review / apply / resolve / done) and otherwise names the next automatable step (advance / execute / verify). `failed` and `wait` are terminal-for-now answers rather than steps: the first is an error the caller must surface, the second means an operation is in flight.
func (*Engine) NextReadyTask ¶ added in v0.5.0
NextReadyTask reports the task Execute would run next for initiativeID, or nil when there is none.
Deliberately lock-free, unlike Execute itself: a poll-driven UI (the Build page) calling this on every refresh must not block for the whole duration of an in-flight Execute, which holds e.mu for as long as the agent container runs. A slightly stale answer is an acceptable cost for a read-only hint; Execute's own claim is still what actually enforces correctness when the button is clicked.
func (*Engine) PRChecks ¶ added in v0.6.0
PRChecks reports the latest CI status of changeSetID's initiative's pull request via `gh pr checks` (review C4 piece 3). Every change set of an initiative shares the same PR, so this is the same result whichever of the initiative's change sets it is asked through.
func (*Engine) PartialWork ¶ added in v0.5.1
func (e *Engine) PartialWork(initiativeID string) *PartialWorkInfo
PartialWork describes the initiative's kept partial, or nil.
func (*Engine) PromoteDocComment ¶
PromoteDocComment turns a document comment into an open Question for the initiative's judgment flow, and links the comment to the new question (so it is not promotable twice). The section, when present, is prefixed to the question so the question names where in the document it came from.
func (*Engine) RecordHumanEvidence ¶
func (e *Engine) RecordHumanEvidence(ctx context.Context, initiativeID, requirementRef string, status domain.VerificationStatus, note, actor string) error
RecordHumanEvidence records a human judgment (pass/fail/waived) for every acceptance criterion of a requirement (§70, review B10), then applies the requirement-level disposition: pass leaves the status for VerifyInitiative to mark verified; fail marks it failed; waived marks it waived. This is the human sign-off path — UX/security criteria that the deterministic verifier marks needs_manual are cleared here by a human actor, never by a model.
func (*Engine) RecordHumanPass ¶
func (e *Engine) RecordHumanPass(ctx context.Context, initiativeID, requirementRef, note, actor string) error
RecordHumanPass records a human "pass" evidence for every acceptance criterion of a requirement (§70, review B10).
func (*Engine) RejectConflicted ¶
RejectConflicted resolves a conflicted change set by rejecting it and re-opening its task (mirrors the existing rejected recovery path).
func (*Engine) Reload ¶
func (e *Engine) Reload(cfg config.HarnessConfig, registry *model.Registry, redactor *security.Redactor, blobs *blob.Store, dotEnv map[string]string)
Reload swaps the config-derived components in place on the SAME engine, so the engine's mutex continues to serialize execute/apply/revert across a reload. e.mu excludes Execute/ApplyChangeSet/RevertChangeSet, which hold it for their whole duration; cfgMu (review H4) is what actually guards the field writes below against every OTHER entry point (Run, Advance, Retry, RevisePlan, Resume, Revise, ReopenPhase, ...), none of which hold e.mu -- the doc comment this replaces claimed "ALL entry points now hold [e.mu]", which was false, and go test -race proved it.
func (*Engine) RenderPatch ¶
RenderPatch renders a change set's patch as a readable diff (path + content per file) for the adversarial reviewer and the diff endpoint. RenderPatch renders a change set's patch as a readable diff (path + content per file) for the adversarial reviewer and the diff endpoint. It is REDACTED at this display surface so raw file content never reaches a network-egress model (review SRE regression); the raw store stays redaction-free for byte-for-byte apply/revert.
func (*Engine) RenderPatchPage ¶ added in v0.6.0
RenderPatchPage is RenderPatch bounded to at most maxDiffEndpointFiles files (the diff endpoint's variant; see maxDiffEndpointFiles). total is the change set's true file count, so a truncated response can say so.
func (*Engine) ReopenPhase ¶
func (e *Engine) ReopenPhase(ctx context.Context, initiativeID, phase string) (domain.InitiativeStatus, error)
ReopenPhase re-runs the design pipeline from the given design stage through plan review (downstream cascade), regenerating artifacts as new versions and the plan from scratch. It is a pre-execution action: once any change set exists the reopen is refused, since re-planning would orphan applied work. phase must be one of architecture, product_design, verification_design.
func (*Engine) RerunChangeSetReview ¶ added in v0.6.0
RerunChangeSetReview runs the adversarial reviewer for a change set whose review never completed (ICP re-run defect #1): Execute's own call to it errored -- most often the operation was cancelled mid-review -- after the change set had already left checks_running for review_required, so it sits there carrying only mechanical-check observations, with the task never marked done and `idea execute` free to re-pick it and duplicate the work.
This is an explicit, paid, user-initiated action (a real model call), never triggered implicitly by approve: the round-3 fix that made a plain approve free of model calls is unconditional, and this is the one, named escape hatch for the one case that needs a review to actually happen. It refuses outright once a review has already completed for this change set -- nothing to rerun, and rerunning would reintroduce exactly the "a rejected finding comes back reworded" non-convergence problem that fix removed.
func (*Engine) ResetConflictedForRetry ¶
func (e *Engine) ResetConflictedForRetry(ctx context.Context, initiativeID, changeSetID string) error
ResetConflictedForRetry resets a conflicted change set back to approved so the existing apply path can be re-run unchanged (approved→applying→applied).
func (*Engine) RestoreWorkspace ¶
RestoreWorkspace restores the canonical workspace from a persisted pre-image manifest digest, for a change set stuck mid-apply. Used by startup reconciliation to unwind an interrupted apply.
H3: RevertChangeSet refuses to restore a pre-image over an edit made to the workspace AFTER the mutation it is unwinding (fsdiff.StalePost) -- without the same guard here, a crash-recovery restore could silently overwrite whatever the user (or a later, successful operation) wrote to one of these same paths between the crash and the next daemon startup. changeSetID identifies the change set whose patch describes exactly the paths (and post-image digests) this restore would otherwise blindly overwrite.
func (*Engine) Resume ¶
func (e *Engine) Resume(ctx context.Context, initiativeID string) (status domain.InitiativeStatus, err error)
Resume re-runs the review loop after a human has resolved decisions/findings in needs_human_judgment (§11).
The claim is what makes that comment true. Resume took no claim and checked no status, so it re-ran the review loop from any state and wrote the result over it: called on a `plan_approved` initiative it discarded the approved plan and left `approved`, silently undoing M2. Claiming from needs_human_judgment is both the guard and the exclusion -- runReviewLoop's terminal transition releases it.
func (*Engine) Retry ¶
Retry resumes a failed initiative's vertical slice after the last phase that actually completed, under the currently-set per-initiative model override (retry-with-a-different-model). Prior requirements and assertions are superseded immediately before product definition re-runs, so that re-run does not duplicate them; artifacts are immutable-versioned and decisions/questions are de-duplicated. The override is cleared when the run finishes.
It used to re-run framing→research→PRD unconditionally, "from scratch", every time (ICP walkthrough finding: a 503 mid-PRD-authoring, followed by `idea retry`, re-asked framing's clarifying questions and re-ran research that had already succeeded). Framing does not consult existing decisions/questions at all, so redoing it after the human had already answered some of them looked, from the outside, like their answers were discarded -- even though the rows survive (SupersedeRequirements/ SupersedeAssertions never touch decisions or questions, and runProductDefinition always feeds current decisions/questions back to the model). The real defect was doing the redundant work and re-asking at all. Resuming after the last completed phase, keyed off artifacts (a durable domain fact -- see the operation `stage` column's own doc comment for why that is NOT used here: it is a cosmetic progress hint, cleared on terminal status) fixes both: no wasted cost, and no re-asked framing questions.
func (*Engine) RevertBlockedReason ¶ added in v0.6.0
func (e *Engine) RevertBlockedReason(ctx context.Context, initiativeID, changeSetID string) (string, error)
RevertBlockedReason reports why RevertChangeSet would refuse to revert changeSetID right now, or "" when it would not. It mirrors RevertChangeSet's own stale-workspace guard read-only and lock-free (see RunBlockedReason), so Runtime can answer a synchronous 409 instead of starting an operation that can only fail in the background, and so a client can grey out "Revert" and say why before the click.
A race between this read and RevertChangeSet's own authoritative recheck (taken under the engine lock, immediately before any byte is restored) is still safe: a file edited in that narrow window is caught there instead, and nothing is written either way.
func (*Engine) RevertChangeSet ¶
RevertChangeSet rolls back an applied change set: it restores the pre-image snapshot recorded at apply time (byte-for-byte), then advances applied→reverted plus a rolled_back journal entry atomically (§39, review B1).
func (*Engine) ReviewChangeSet ¶
func (e *Engine) ReviewChangeSet(ctx context.Context, initiativeID, changeSetID, verdict string) error
ReviewChangeSet with acceptFindings=true is the human accept: it signs off the reviewer's open findings on this change set and approves, without running a fresh review.
That last clause is the whole point, and it is the third time this project has needed it. `idea approve` had to stop re-running the PRD review; `idea approve-plan` had to stop re-running the plan review; and this had to stop re-running the change-set review. A model reviewer is not a fixed point, so "disposition, then review again" is a retry, not an accept -- and here it was worse than a coin flip: the first attempt persists its findings, and every later attempt fails denyReviewOpenBlocking on them before the review even runs. The keyed magic path hit this every run and had no way out.
func (*Engine) ReviewChangeSetAccepting ¶ added in v0.4.0
func (e *Engine) ReviewChangeSetAccepting(ctx context.Context, initiativeID, changeSetID, verdict string) error
ReviewChangeSetAccepting is ReviewChangeSet with the human accept.
func (*Engine) Revise ¶
Revise applies the human's decisions/answers by re-running product definition (with the resolved decisions + answered questions in context), then re-runs review. This is the "apply my judgment → updated PRD" loop (§8, §11).
func (*Engine) RevisePlan ¶
func (e *Engine) RevisePlan(ctx context.Context, initiativeID string) (domain.InitiativeStatus, error)
RevisePlan regenerates the execution plan (and its review) in place after the human edited or rejected the prior plan. It deletes the prior tasks and their edges and disposes prior plan-review findings first, so no duplicate tasks or stale blocking findings survive the regeneration (full-platform review: plan revision must not leave orphans or wedge the verify gate).
func (*Engine) Run ¶
func (e *Engine) Run(ctx context.Context, initiativeID, idea string) (domain.InitiativeStatus, error)
Run executes the full vertical slice for an initiative and returns the final initiative status.
func (*Engine) RunBlockedReason ¶ added in v0.5.0
RunBlockedReason reports why Execute would refuse to run right now for initiativeID, or "" when it would not (the Build contract's `run_blocked_reason`).
It mirrors Execute's own guards read-only and lock-free (see NextReadyTask) so the Build page can grey out "Run next task" and say why, instead of letting the click land on a 409/400 it has to parse. It does NOT check executor readiness (image/key) -- that lives in the daemon package, which alone knows about Docker and the project's .env; the caller composes both.
func (*Engine) SemanticDiff ¶
SemanticDiff computes the structured diff for an initiative.
func (*Engine) SetDotEnv ¶ added in v0.5.0
SetDotEnv supplies the project's .env, which the daemon's model registry already falls back to for provider keys. The coding agent reads its key the same way; with only the process environment it launched keyless for anyone whose key lived in .env.
func (*Engine) SetModelOverride ¶
SetModelOverride forces every role to the given "provider/model" spec for the given initiative's next workflow run (retry-with-a-different-model). The engine clears it once that run finishes.
func (*Engine) SetNoteOverride ¶ added in v0.6.0
SetNoteOverride records a human note to steer the given initiative's next Execute or Retry (D-a, wave 3 contract). Cleared once that run finishes.
func (*Engine) SetRawBlobs ¶
SetRawBlobs sets the redaction-free content store used by the diff/apply/revert path (review C1/C2). File content must round-trip byte-for-byte, so it is never redacted; the redacted `blobs` store is reserved for model artifacts.
func (*Engine) SetRedactor ¶
SetRedactor sets the redactor applied at the DISPLAY/model surface (the adversarial review context and the diff endpoint), so raw file content never reaches a network-egress model unredacted (review SRE regression).
func (*Engine) SetWorkRoot ¶
SetWorkRoot sets the directory that Execute derives per-initiative isolated work roots from. The daemon points this at its per-project state directory so the executor's WorkRoot mirrors "<state-root>/work/<initiative>".
func (*Engine) SetWorkspaceRoot ¶
SetWorkspaceRoot sets the canonical workspace that ApplyChangeSet writes into and RevertChangeSet restores. The daemon points this at the project root.
func (*Engine) StructuredDiff ¶
func (e *Engine) StructuredDiff(cs *domain.ChangeSet) []StructuredFile
StructuredDiff renders a change set as a per-file list (path + kind + redacted content). Deleted files carry no content. A change set rejected by the secret sweep never had its raw bytes persisted (persistDiff is skipped), but carries a MASKED version instead (RedactedDigest, persistRedactedDiff) -- that is served here with Redacted=true rather than leaving Content empty, so the human can see what was blocked. Content is genuinely absent (Size 0, Redacted false) only when neither the raw nor the masked bytes could be found -- e.g. a patch persisted before this fix, or a masking failure. A patch-manifest read/decode failure yields an empty (non-nil) list so the `files` wire field is always a JSON array; the read error is surfaced via RenderPatch's "(patch unreadable: …)" in the sibling `patch` field.
func (*Engine) StructuredDiffPage ¶ added in v0.6.0
func (e *Engine) StructuredDiffPage(cs *domain.ChangeSet) (files []StructuredFile, total int)
StructuredDiffPage is StructuredDiff bounded to at most maxDiffEndpointFiles files, returning the change set's true total file count alongside the (possibly truncated) list so a caller can report "showing 500 of 14300".
func (*Engine) SuggestAnswers ¶
func (e *Engine) SuggestAnswers(ctx context.Context, initiativeID string, emit func([]domain.SuggestedAnswer)) error
SuggestAnswers asks the product manager to propose a concise answer for every open question, grounded in the project's intent and purpose. Questions are answered in bounded chunks, and each chunk's answers are emitted via `emit` as they complete (so callers can persist progress incrementally).
func (*Engine) VerifyInitiative ¶
VerifyInitiative computes coverage across all approved requirements, marks a requirement verified when every mandatory criterion has a pass evidence, and completes the initiative when every requirement is verified and there are no open blocking findings (§70, review B4). It is idempotent and deterministic.
review H7: takes mu, the same mutex Execute/ApplyChangeSet/RevertChangeSet hold for their whole duration, so this cannot run concurrently with any of them actually mutating files or the task/change-set graph. Before this, verify ran with no synchronization of its own; store.CompleteInitiative's CAS only excludes `failed`, not `running` (deliberately -- the documented apply-then-verify sequence verifies while the row still reads `running` after apply's own operation goroutine has not yet released its claim, and that must keep working), so nothing stopped this from reaching CompleteInitiative WHILE one of those three was still actively writing. Proven: an apply mid-file-write let a concurrent verify complete the initiative, after which a third request (revise) claimed `running` FROM the `complete` verify had just manufactured and started superseding requirements while apply's files were still landing -- two pipelines on one initiative. Taking mu here makes verify wait for the real work to finish (mu already excludes the other three from each other and from itself); it does not need to wait for `running` to clear back to a resting status, which is a separate, much narrower race ReleaseInitiativeClaim's own CAS closes.
type ErrReviewUnavailable ¶ added in v0.6.0
type ErrReviewUnavailable struct {
// attributable for `idea logs` / cost accounting even though it never
// produced findings.
RunID string
Cause error
}
ErrReviewUnavailable is returned by runChangeSetAdversarialReview when the adversarial reviewer was genuinely ATTEMPTED for a change set but could not complete: every attempt (including runModel's own reduced-ask retry on model.ErrTruncated) was cut off at the model's output-token ceiling.
This is the "no wedge" half of the change-set review truncation defect. An ordinary error here used to propagate straight out of Execute/ RerunChangeSetReview: the change set was left in review_required with ReviewCompletedAt nil and no record of WHY, indistinguishable from a cancelled operation, and the task was never marked done -- so `idea execute` kept re-offering it, hit the same "never finished its adversarial review" guard every time, and the ONLY documented escape, --accept-findings, refused too (it requires ReviewCompleted()). A caller that receives this instead calls store.SetChangeSetReviewUnavailable, which records the cause explicitly (never silently) and lets that one, narrowly-scoped escape apply -- see domain.ChangeSet.ReviewUnavailable.
func (*ErrReviewUnavailable) Error ¶ added in v0.6.0
func (e *ErrReviewUnavailable) Error() string
func (*ErrReviewUnavailable) Unwrap ¶ added in v0.6.0
func (e *ErrReviewUnavailable) Unwrap() error
type ImpactItem ¶
ImpactItem is a TraceItem with a staleness classification.
type NextTask ¶ added in v0.5.0
type NextTask struct {
ID string `json:"id"`
HumanID string `json:"human_id"`
Title string `json:"title"`
}
NextTask is the task Execute would run next, projected for an API response without exposing the full domain.Task shape (the Build contract's `next_task`).
type PartialWorkInfo ¶ added in v0.5.1
type PartialWorkInfo struct {
TaskID string `json:"task_id"`
Files int `json:"files"`
// Note is set when the stopped run's files were not kept, and why.
Note string `json:"note,omitempty"`
}
PartialWorkInfo describes a kept partial for clients.
type RigorLevel ¶ added in v0.6.0
type RigorLevel string
RigorLevel is review.rigor's calibrated value once "auto" is resolved (review B1). Only critical/high findings ever block approval (§11, Severity.Blocking); rigor governs how MUCH review a change gets, not whether a system-deny check (secret sweep, host exec, blob digest mismatch) can be skipped -- those are absolute and never rigor-gated.
const ( RigorAuto RigorLevel = "auto" RigorQuick RigorLevel = "quick" RigorStandard RigorLevel = "standard" RigorThorough RigorLevel = "thorough" )
func (RigorLevel) Valid ¶ added in v0.6.0
func (r RigorLevel) Valid() bool
Valid reports whether r is one of the four configured values (§B1). Auto is a valid CONFIGURED value (it is what calibrateRigor resolves away), but is never itself an "effective" level a reviewer runs at.
type SemanticDiff ¶
type SemanticDiff struct {
Requirements struct {
Added []DiffRequirement `json:"added"`
Removed []DiffRequirement `json:"removed"`
} `json:"requirements"`
Decisions struct {
Open []DiffDecision `json:"open"`
Decided []DiffDecision `json:"decided"`
Superseded []DiffDecision `json:"superseded"`
} `json:"decisions"`
}
SemanticDiff reports structured requirement/decision changes (added vs removed; open vs decided vs superseded) rather than raw markdown (§25).
type StructuredFile ¶
type StructuredFile struct {
Path string `json:"path"`
ChangeType string `json:"change_type"`
Size int `json:"size"`
Content string `json:"content"`
// Patch is a unified diff of the file against its base (B6): an added file
// is all '+', a deleted file is all '-', a modified file is base vs new.
// Omitted when there is nothing to diff (both sides empty). This is what
// lets the diff view render a change instead of a full-file dump for a
// whole-file rewrite of an existing file.
Patch string `json:"patch,omitempty"`
// PatchNote says why Patch is empty when there was a change to show: the
// file is binary, too large to diff, its content was never kept, or its
// base can no longer be recovered. The UI shows it and falls back to
// Content.
PatchNote string `json:"patch_note,omitempty"`
// Redacted is true when Content holds MASKED content instead of the file's
// real post-image bytes, because the secret sweep denied this change set
// and the raw bytes were never persisted -- only their masked form was.
// The UI shows a distinct, honest note instead of treating this like an
// ordinary (or missing) diff. Review: secret-sweep diff visibility.
Redacted bool `json:"redacted,omitempty"`
// contains filtered or unexported fields
}
StructuredFile is one file of a change set for per-file display: its path, add/modify/delete kind, byte size, and REDACTED content. Content is redacted at this display surface exactly like RenderPatch, so raw bytes never reach a network-egress model (review SRE regression); the raw store stays redaction-free for byte-for-byte apply/revert. The post-image digest is deliberately NOT exposed here — a digest is not needed for display and would be pure hash-confirmation surface.
type TraceItem ¶
type TraceItem struct {
EdgeType string `json:"edge_type"`
FromType string `json:"from_type"`
FromID string `json:"from_id"`
FromLabel string `json:"from_label,omitempty"`
ToType string `json:"to_type"`
ToID string `json:"to_id"`
ToLabel string `json:"to_label,omitempty"`
}
TraceItem is one graph edge with resolved endpoint labels.