Documentation
¶
Overview ¶
Package specgen turns a product idea into a complete, validated version 2 specification package.
It is the `afspec` skill rebuilt as a program. The skill is ~750 lines of markdown describing a seven-step workflow across fifteen CLI subcommands, with a refinement loop that stops to ask a person questions. This package keeps the two things that genuinely need a model — write the PRD, and generate the three artifacts — and turns everything else into a mechanism:
- The workflow is the pipeline, not a numbered list the model may skip.
- The refinement loop is gone. Nobody is waiting to answer questions, so the PRD phase resolves every open question itself, records each in a `## Design Decisions` section, and reports the ones it is least sure of as `open_questions` in the result. A caller that wants a human in the loop reads that array; a caller that does not gets a finished spec.
- Each artifact is submitted through a tool whose schema is the format's own JSON Schema, and whose handler runs every cross-file rule decidable at that point. A violation is a tool error the loop hands back, so the repair loop IS the loop — there is no second conversation assembled by hand, and the system prompt and tool schemas stay byte-identical across the attempt and its correction so the provider's cache prefix survives.
- The "post-generation language audit" the skill asks a human to perform is a check: the project's real test runner and linter are detected in Go, and a tasks artifact that names another ecosystem's runner is refused with the detected commands in the message.
- The spec is validated, and activated only if it validates. The traceability matrix in the result is derived, never stored.
- An input that is more than one spec's worth of work is written as every spec it divides into, not the first one plus a recommendation. The split is decided once, recorded in the spec root while unfinished, and followed to the last package — by this run, or by the next run on the same input if this one stops early.
The three generation phases are separate agents rather than one conversation, because sharing a transcript would carry the requirements phase's reasoning into the tests that are supposed to check the requirements.
Index ¶
- Constants
- func ArtifactSchema(step afspec.GenerationStep) (*schema.Schema, error)
- func ArtifactToolName(step afspec.GenerationStep) string
- func HasIntent(body string) bool
- func PatchToolName(step afspec.GenerationStep) string
- func Preflight(ctx context.Context, o Options) (*Result, *Failure)
- func ToolSchema(raw []byte) (*schema.Schema, []string, error)
- func ValidSpecName(s string) bool
- type Disposition
- type Failure
- type Finding
- type OpenQuestion
- type Options
- type PRD
- type Package
- type PlanInput
- type PlanScope
- type RelevantFile
- type Result
- type Review
- type ReviewRound
- type ScopeReport
- type SplitPlan
- type SplitScope
- type TraceReport
- type ValidationItem
- type ValidationReport
Constants ¶
const ( // ScopeDone means the package exists and validates. ScopeDone = envelope.ScopeDone // ScopeInvalid means the package exists and does not validate. It is // not written again; the errors name the rules to fix by hand. ScopeInvalid = envelope.ScopeInvalid // ScopeFailed means this run stopped on this scope. The plan is kept, // and running spec on the same input again resumes here. ScopeFailed = envelope.ScopeFailed // ScopePending means the scope was not reached. ScopePending = envelope.ScopePending )
Scope states, as reported in Result.Split.
const ( // CategoryInvalid means the package was generated and does not satisfy // the format's rules, its own or those across specs. The files are on // disk and the errors name the rules, because a spec you can read and fix // is worth more than no spec at all. CategoryInvalid = envelope.CategoryInvalidSpec // CategoryDisk is a filesystem failure. CategoryDisk = envelope.CategoryDisk )
Categories this package adds to the shared vocabulary.
const DefaultMaxParallel = 3
DefaultMaxParallel is how many packages of a split the command generates at once when --max-parallel is not given.
const DefaultSpecDirName = ".specs"
DefaultSpecDirName is where spec packages live under the repository root.
const SpecDirEnv = "AF_SPEC_DIR"
SpecDirEnv overrides the spec root. The --specs-dir flag wins over it.
const SplitPlanSuffix = ".split.json"
SplitPlanSuffix is the file name suffix of an unfinished split's plan, which lives in the spec root beside the packages it describes.
The plan is the one piece of state the tool keeps between runs, and it is kept only while the work it describes is unfinished. A run that was cut short after writing two of four packages leaves the plan behind; the next run with the same input finds it and continues with the third scope, and the run that writes the last package removes it. Its presence therefore means exactly one thing — `spec` stopped before it was done — which is why it is a visible file rather than something hidden in a package.
const ToolSubmitArchitecture = "submit_architecture"
ToolSubmitArchitecture is the terminating tool of the optional architecture phase.
const ToolSubmitPRD = "submit_prd"
ToolSubmitPRD is the terminating tool of the PRD phase.
const ToolSubmitPRDReview = "submit_prd_review"
ToolSubmitPRDReview is the terminating tool of the review phase.
const ToolSubmitPRDRevision = "submit_prd_revision"
ToolSubmitPRDRevision is the terminating tool of the revision phase.
Variables ¶
This section is empty.
Functions ¶
func ArtifactSchema ¶
func ArtifactSchema(step afspec.GenerationStep) (*schema.Schema, error)
ArtifactSchema returns the tool schema for one generation step, converted from the JSON Schema afspec embeds.
The schema is not re-authored here. afspec/schemas/*.json is the format's definition and the same bytes validate the artifact after generation; a second, hand-written copy for the tool declaration would be a copy that can disagree with the thing it is supposed to describe.
func ArtifactToolName ¶
func ArtifactToolName(step afspec.GenerationStep) string
ArtifactToolName is the tool that submits one generation step's artifact.
func HasIntent ¶
HasIntent reports whether a PRD body carries the section afspec hashes, by afspec's own rule and on the body as it will be written: a looser check would pass a PRD whose activation then fails (#223).
func PatchToolName ¶
func PatchToolName(step afspec.GenerationStep) string
PatchToolName is the tool that corrects one generation step's last rejected submission in place.
func ToolSchema ¶
ToolSchema converts an afspec JSON Schema document into the structured schema value a tool declares (core.Tool.InputSchema).
It replaces the map[string]any pipeline of InlineRefs + CleanSchema, and the difference is not cosmetic. That pipeline walked every map in the document and deleted keys by name at every depth, which is correct for a schema object and wrong for a `properties` map, whose keys are property NAMES. The v2 test object has properties called `title` and `then`; both were deleted from the tool schema while `required` still listed them and additionalProperties stayed false, so the schema handed to the model for submit_test_spec could not be satisfied by any argument object. This walk knows which position it is in and only drops a keyword where a keyword is what it is reading.
Decoding goes through decodeOrdered rather than encoding/json because Go marshals map keys in sorted order unconditionally, and property order is model-visible: it is the order the model is shown the fields and, through the request body, part of the provider's cache prefix. schema.Schema carries PropertyOrder for exactly this reason, and a map cannot carry it.
func ValidSpecName ¶
ValidSpecName reports whether s is a usable spec name. It is exported so a command can refuse a bad --name before anything is fetched.
Types ¶
type Disposition ¶
type Disposition struct {
ID string `json:"id"`
// Disposition is accepted or rejected.
Disposition string `json:"disposition"`
// Reason says why a rejected finding does not hold; empty when accepted.
Reason string `json:"reason"`
}
Disposition is the reviser's answer to one finding.
type Failure ¶
type Failure struct {
Stage string
Category string
Err error
// TotalBudget is the --total-budget ceiling a budget stop was checked
// against, so the envelope's fix_hint can name it. Zero otherwise.
TotalBudget float64
}
Failure carries the stage and category of a failed run.
func (*Failure) CategoryName ¶
func (*Failure) TotalBudgetUSD ¶
TotalBudgetUSD is the run-level ceiling behind a stage "budget" failure.
type Finding ¶
type Finding = envelope.ReviewFinding
Finding is one flaw a reviewer reported and what became of it.
type OpenQuestion ¶
type OpenQuestion = envelope.OpenQuestion
OpenQuestion is one decision made under uncertainty. It is defined in package envelope, because the result reports it.
type Options ¶
type Options struct {
// Input is the classified argument: a product idea, a PRD file, or a
// forge issue thread. Required.
Input cli.Input
// Workspace roots the read-only source access. Required.
Workspace *workspace.Workspace
// SpecsDir is where NN_name directories live. Empty means
// <workspace>/.specs, or $AF_SPEC_DIR when that is set.
SpecsDir string
// Name overrides the spec name the model chooses. It must match
// [a-z][a-z0-9]*(_[a-z0-9]+)*.
Name string
// Architecture runs the optional fifth phase and writes architecture.md.
Architecture bool
// Activate transitions a valid spec from draft to active, computing its
// intent hash. A spec that does not validate is never activated.
Activate bool
// Comment posts the finished PRD back to the issue the input came from.
Comment bool
// DryRun writes nothing to disk and nothing to the forge. The generated
// artifacts are still produced and reported.
DryRun bool
// TotalBudgetUSD caps the spend of the whole run. It is checked before
// each scope's PRD phase after the first; an input that does not split has no interior boundary and is
// bound by the one phase's ceiling alone. Zero means no cap beyond the
// per-phase bound.
TotalBudgetUSD float64
// Adversarial reviews every PRD the run writes before its package is
// generated: a fresh agent looks for its flaws and another revises it to
// answer them, for up to AdversarialRounds rounds.
Adversarial bool
// AdversarialRounds is the round limit, 1 to 5. The command passes 1
// when --adversarial is given without --adversarial-rounds.
AdversarialRounds int
// MaxParallel is how many packages of a split are generated at once. The
// PRD phases still run one after another, each seeing the PRDs before it;
// a scope's package is generated as soon as its PRD exists, beside the
// next scope's PRD phase. One or less writes the scopes strictly one after
// another, each scope's PRD waiting for the package before it.
MaxParallel int
// RepoMapTokens is the token budget of the repository map in every
// phase's user prompt. Zero, the zero value, disables it.
RepoMapTokens int
// Index is the code-search index for this run. Nil means no indexed search.
Index tools.Index
// builder returned. RunPreflight reports it. Empty when the
// index was built or the reason is not known.
IndexUnavailable string
// Runner drives the model phases. Required unless author is injected.
Runner *agentrun.Runner
// Forge is the forge client, GitHub or GitLab, used only by Comment.
Forge issuex.Client
// Run records warnings and per-phase cost.
Run *cli.Run
// Progress reports steps to stderr.
Progress *cli.Progress
// contains filtered or unexported fields
}
Options configure one spec generation run.
type PRD ¶
type PRD struct {
// SpecName is the snake_case half of the directory name.
SpecName string `json:"spec_name"`
// Title is the human-readable name, which becomes the PRD frontmatter's
// title. The schema requires it to be non-empty, and a spec whose title
// is blank fails validation — which is why it is asked for here rather
// than derived from the directory name.
Title string `json:"title"`
// Body is the finished PRD in Markdown, without frontmatter.
Body string `json:"body"`
// OpenQuestions are the decisions the model would most like checked.
OpenQuestions []OpenQuestion `json:"open_questions,omitempty"`
// RecommendedSplit is set when the input describes more than one spec's
// worth of work. The PRD then covers the first scope only.
RecommendedSplit []SplitScope `json:"recommended_split,omitempty"`
// RelevantFiles lists the files the PRD phase found important for later
// generation phases.
RelevantFiles []RelevantFile `json:"relevant_files,omitempty"`
// CodebaseNotes is what the phase learned reading the code, for the
// phases after it. It is bounded by maxCodebaseNotes.
CodebaseNotes string `json:"codebase_notes,omitempty"`
}
PRD is the first phase's result.
type PlanInput ¶
type PlanInput struct {
Kind string `json:"kind"`
Origin string `json:"origin"`
SHA256 string `json:"sha256"`
}
PlanInput is the identity of the input a plan belongs to.
type PlanScope ¶
type PlanScope struct {
Name string `json:"name"`
Scope string `json:"scope"`
// SpecID and Dir are set once the package exists. Dir is the package's
// directory name under the spec root.
SpecID string `json:"spec_id,omitempty"`
Dir string `json:"dir,omitempty"`
// Invalid records a package that was written and does not validate. It
// is on disk and is not written again; a person fixes it.
Invalid bool `json:"invalid,omitempty"`
}
PlanScope is one spec of the split.
type RelevantFile ¶
type RelevantFile = envelope.RelevantFile
RelevantFile is one file the PRD phase identified as important for later generation phases. It is defined in package envelope, because the result reports it.
type Result ¶
type Result struct {
envelope.SpecResult
// contains filtered or unexported fields
}
Result is what the tool reports as JSON: the envelope package's SpecResult, which a program reading the output decodes into, and the one thing the pipeline keeps beside it.
The fields of the first package this run wrote sit at the top level, so a run on an input that is one spec's worth of work reports exactly what it always did. An input that was more than that adds the further packages in FollowOnSpecs and the whole plan, scope by scope, in Split.
func Run ¶
Run produces every specification package the input calls for.
An input that is one spec's worth of work is one PRD phase and one package. An input the PRD phase reports as more than that is written as a split: the first package from the PRD just written, then one PRD phase and one package per remaining scope, each seeing the packages before it. The split is planned once, recorded in the spec root, and followed until every scope has a package — by this run, or by the next run on the same input if this one stops early.
Within a package the order is the format's, not a preference: requirements, then tests, then tasks, each phase seeing the complete artifacts before it. A generator that cannot see a test id cannot own it, which is how the previous format produced specs whose edge-case and property tests belonged to no task.
func RunPreflight ¶
RunPreflight is spec --preflight: every check Run performs before its first model call, reported and then stopped at. It calls the one Preflight function Run calls, and the one findSplitPlan Run calls, never a copy of either, so a run that would refuse refuses here with the identical stage, category and message. A refusal returns no result: a partial checklist of what passed before it would be a second answer to "would this run start".
Nothing is written: no package, no split plan, no comment, and no phase is run. What the package would be called is the model's to choose, so nothing about it is checked here.
func (*Result) Artifacts ¶
Artifacts implements cli.ArtifactsProvider. One spec_package entry per package this run wrote — the first (embedded as Result.Package) plus every entry of FollowOnSpecs — each with valid read off that package's own Validation.Valid, and a comment entry when its CommentURL is set. Nothing here is read from a field that is the model's account of its own work; SpecDir, Validation and CommentURL are all facts this package established itself, from the format's own validator and from the forge's response to AddComment.
It lives in this file, not artifacts.go, because that file already defines the unrelated "artifact" the generation phases submit — one step of a spec package (requirements.json, tests_spec.json, ...) — and the two concepts share a name by coincidence, not by relation.
func (*Result) Next ¶
Next implements cli.NextProvider. It suggests impl on every written package that validates, in split order, and spec again on the same input when the split is unfinished. Every value is a fact the pipeline established — SpecDir, Validation.Valid, SplitPlan and the input's own origin — never anything a model wrote.
func (Result) Resumable ¶
Resumable implements cli.Resumabler. For specgen, this is true whenever SplitPlan is non-empty.
func (Result) Summary ¶
Summary returns one sentence describing the outcome in spec's vocabulary, or none when the run produced no package to describe: the envelope then says what failed instead.
func (*Result) SummaryView ¶
SummaryView implements cli.Summarizable. It is defined on Result (rather than on the embedded Package) because Split lives on Result alone.
type ReviewRound ¶
type ReviewRound = envelope.ReviewRound
ReviewRound is one review and the revision that answered it.
type ScopeReport ¶
type ScopeReport = envelope.ScopeReport
ScopeReport is one scope of a split and where it stands.
type SplitPlan ¶
type SplitPlan struct {
// Input identifies what the split was planned for, so a run with a
// different input does not resume someone else's work.
Input PlanInput `json:"input"`
// CreatedAt is when the split was planned; UpdatedAt when a scope was
// last written.
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
// Scopes are the specs, first one first.
Scopes []PlanScope `json:"scopes"`
}
SplitPlan is the record of an input that was more than one spec's worth of work: every scope the PRD phase carved it into, in the order they are written, and which of them exist.
type SplitScope ¶
SplitScope is one spec's worth of the work, when the input held several.
type TraceReport ¶
type TraceReport = envelope.TraceReport
TraceReport is the derived coverage summary.
type ValidationItem ¶
type ValidationItem = envelope.ValidationItem
ValidationItem is one finding, carrying the rule that produced it.
type ValidationReport ¶
type ValidationReport = envelope.ValidationReport
ValidationReport is afspec's verdict, flattened for JSON.