draft

package
v0.25.2 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 25 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package draft holds the review draft: findings, human decisions, send-back notes and replies.

Index

Constants

View Source
const (
	DispositionAccepted  = "accepted"
	DispositionExcluded  = "excluded"
	DispositionWithdrawn = "withdrawn"
	DispositionPending   = "pending"
)
View Source
const (
	SideRight = "RIGHT"
	SideLeft  = "LEFT"
)
View Source
const (
	DecisionAccepted = "accepted"
	DecisionExcluded = "excluded"
)
View Source
const (
	NoteOpen      = "open"
	NoteResolved  = "resolved"
	NoteDismissed = "dismissed"
)
View Source
const (
	ByAgent = "agent"
	ByHuman = "human"
)
View Source
const (
	StatusOpen      = "open"
	StatusAddressed = "addressed"
)
View Source
const HandBackSchema = 1

Bump on any field change, so an older loupe refuses the file instead of dropping fields (docs/versioning.md).

View Source
const LabelPattern = `^[\p{L}\p{N}][\p{L}\p{N}_.-]*$`

LabelPattern keeps labels free of Markdown punctuation, because an inline comment's summary line is a Markdown paragraph. The renderer escapes the label there too, so this is a second line of defense, not the only one.

View Source
const MaxReturnNoteRunes = 4096

MaxReturnNoteRunes caps the closing note.

View Source
const ReturnFile = "return.json"

ReturnFile seals a local run once the human returns its decisions to the agent. After it exists, Mutate refuses every change, and loupe review and loupe handoff refuse the run.

View Source
const ReturnSchema = 1

ReturnSchema versions return.json (docs/versioning.md).

View Source
const SchemaVersion = 7

Bump on any field change, so an older loupe refuses the file instead of dropping fields (docs/versioning.md).

Variables

View Source
var ErrNoChange = errors.New("draft unchanged")

ErrNoChange is returned by a mutation fn that left the draft as it was, so Mutate writes nothing and keeps the version; a bumped version would refuse the next decision made against the unchanged draft as stale.

Functions

func Accept

func Accept(d *Draft, findingID, choice string, now time.Time) ([]string, error)

Accept records the decision at the finding's current rev, so any later edit puts the finding back to pending. It resolves the finding's open notes, since accepting is the human's answer to them, and returns their ids.

func AcceptWithNote

func AcceptWithNote(d *Draft, findingID, choice, note string, now time.Time) ([]string, error)

AcceptWithNote accepts the finding with the human's note on how to apply it. A blank note is a plain accept.

func AgentChangedHumanText

func AgentChangedHumanText(f Finding) bool

AgentChangedHumanText reports whether the agent made the latest change to the finding's title or body after a human had changed that same field, so the review interface can say why the human's words are gone.

func Assess

func Assess(d *Draft, against AssessedAgainst, earlier []EarlierFinding, inputs []AssessInput) (dropped int, err error)

Assess records every entry or none, so a refused batch leaves no partial assessment behind. Assessments read against a different previous round name refs of another list, so Assess drops them before recording.

func AssessmentCounts

func AssessmentCounts(d *Draft, earlier []EarlierFinding) (open, addressed, unassessed int)

AssessmentCounts counts against earlier only, so an assessment of a ref the list no longer holds counts for nothing.

func Awaiting

func Awaiting(d *Draft, h *HandBack) []string

Awaiting is the handed-back notes the agent still has to answer: in the set, open and without a reply.

func CheckBatch

func CheckBatch(inputs []FindingInput, failed []EntryFailure, dif *diff.Diff, rules Rules) error

CheckBatch validates every input not already in failed and refuses once, naming every invalid entry, so a caller can fix the whole batch in one retry. The top level is the first invalid entry's own refusal.

func Digest

func Digest(d *Draft) string

Digest is hex SHA-256 over compact JSON of the summary and the publishable set sorted by id, with every key present and no HTML escaping. Accept decisions leave it unchanged, so it can be computed before and after the human decides.

func DismissNote

func DismissNote(d *Draft, noteID string, now time.Time) error

func Dispositions

func Dispositions(d *Draft) map[string]string

func EarlierRef

func EarlierRef(i int) string

EarlierRef names the i-th finding of show --previous's earlier list. The list is rebuilt from the same stored round on every read, so the name is stable for the run.

func Exclude

func Exclude(d *Draft, findingID string, now time.Time) ([]string, error)

Exclude dismisses the finding's open notes and returns their ids.

func ExcludeWithReason

func ExcludeWithReason(d *Draft, findingID, reason string, now time.Time) ([]string, error)

ExcludeWithReason excludes the finding with the human's reason. An empty reason is a plain exclude.

func FindingState

func FindingState(d *Draft, findingID string) ([]byte, error)

FindingState is everything a human's decision on the finding rests on: the finding, its decision, its notes and their replies. It is JSON so a draft Mutate returned compares equal to the same draft loaded, whose times carry no monotonic reading.

func IncludedCount

func IncludedCount(d *Draft) int

func NextFindingID

func NextFindingID(d *Draft) string

func NextNoteID

func NextNoteID(d *Draft) string

func NextReplyID

func NextReplyID(d *Draft) string

func ReadinessRefusal

func ReadinessRefusal(d *Draft) error

ReadinessRefusal refuses a draft with a pending finding or an open note, which neither publish nor return takes.

func Recalibratable

func Recalibratable(f Finding) error

Recalibratable refuses what Recalibrate would, so the review interface can refuse before asking for the new values.

func RecordHandBack

func RecordHandBack(dir string, getenv func(string) string) (added int, err error)

RecordHandBack adds every open, unanswered note to the set under the run lock and returns how many were new. The file is written only when something was added, so a review session that handed nothing back leaves no trace.

func Reinstate

func Reinstate(d *Draft, findingID, choice string, rules Rules, now time.Time) ([]string, error)

Reinstate is the human's override of an agent withdrawal, from the review interface: it puts the finding back in the review and accepts it in one move, since the human decided while looking at it. The command line MUST NOT reach it: --by is self-reported there, so an agent could undo its own withdrawal unseen. Like Accept it resolves the finding's open notes and returns their ids, since overriding the withdrawal is the human's answer to them.

func ResolveNote

func ResolveNote(d *Draft, noteID string, now time.Time) error

func Restore

func Restore(d *Draft, findingID string) error

func Rewritable

func Rewritable(f Finding) error

Rewritable refuses what Rewrite would for the finding's state, so the review interface can refuse before opening the editor.

func Seal

func Seal(dir string, expectVersion int, note string, getenv func(string) string, now time.Time) error

Seal returns a local run's decisions with the human's closing note, which may be empty. It checks the note first, so a refused note writes nothing, then under the draft lock refuses a draft that moved past expectVersion, is not ready, or holds no finding, and otherwise writes return.json.

func SetSummary

func SetSummary(d *Draft, summary string, expectFindings *int, by string) error

SetSummary compares expectFindings with the included count so an agent cannot summarize a set of findings that did not all land.

func ValidateExcludeReason

func ValidateExcludeReason(reason string) error

ValidateExcludeReason holds an exclude reason to the limits of a withdrawal reason: one line of at most 200 characters. The human types it in review, so the refusal speaks to review, not to a command's flags.

func ValidateLabel

func ValidateLabel(label string) error

ValidateLabel accepts the empty label, which means no label.

func ValidateReason

func ValidateReason(r Reason) error

ValidateReason holds a reason to one line a list row can show: a code alone is refused, since the human reads the text and a code tells them nothing.

func ValidateReferences

func ValidateReferences(refs []string, fix string) error

ValidateReferences accepts an empty list. A reference is rendered as a Markdown link to <url>, so whitespace, control characters, angle brackets and backticks are refused: any of them would end or break the destination. fix names the command that repairs the finding, which differs between add and a recheck at publish.

func ValidateReturnNote

func ValidateReturnNote(note string) error

ValidateReturnNote refuses a closing note over MaxReturnNoteRunes, outside the Markdown allowlist, or citing a finding id. An empty note passes.

Types

type AssessInput

type AssessInput struct {
	Ref    string `json:"ref"`
	Status string `json:"status"`
}

type AssessedAgainst

type AssessedAgainst struct {
	From      string `json:"from"`
	Round     int    `json:"round"`
	ReviewURL string `json:"reviewUrl"`
	// PublicationID tells a sticky review's rounds apart, since they share one URL. Empty when the run's previous
	// round was captured before loupe recorded publication ids.
	PublicationID string `json:"publicationId,omitempty"`
}

AssessedAgainst names a previous round as show --previous does.

type Assessment

type Assessment struct {
	// Ref is the name show --previous gave the finding in this round, e-1 onward. A later round names it afresh.
	Ref string `json:"ref"`
	// Status is StatusOpen or StatusAddressed.
	Status  string         `json:"status"`
	Finding EarlierFinding `json:"finding"`
}

Assessment is this round's status for a finding an earlier round published and no round since marked addressed. It copies the finding, so publishing it needs no second read of the previous round.

type Decision

type Decision struct {
	FindingID string `json:"findingId"`
	// Decision is DecisionAccepted or DecisionExcluded.
	Decision string `json:"decision"`
	// FindingRev is the finding's rev when decided; the decision is current only while they are equal.
	FindingRev int       `json:"findingRev"`
	At         time.Time `json:"at"`
	// Note holds the human's accept note or exclude reason. It clears with the decision.
	Note string `json:"note,omitempty"`
	// Choice is the key of the picked option on a finding with options. It clears with the decision.
	Choice string `json:"choice,omitempty"`
}

type Draft

type Draft struct {
	// Schema is SchemaVersion.
	Schema int `json:"schema"`
	// Version starts at 0 on capture; every mutation increments by one.
	Version int    `json:"version"`
	Summary string `json:"summary"`
	// Findings is append-only so ids are never reused.
	Findings []Finding `json:"findings"`
	// Decisions is keyed by finding id, at most one per finding.
	Decisions map[string]Decision `json:"decisions"`
	Notes     []Note              `json:"notes"`
	Replies   []Reply             `json:"replies"`
	// Assessments is sorted by ref and omitted when empty, so a draft that assessed nothing reads as it always has.
	Assessments []Assessment `json:"assessments,omitempty"`
	// AssessedAgainst is the previous round the assessments were read from. Their refs name only that round's earlier
	// list, so publish refuses once a lower round publishes and becomes the previous one.
	AssessedAgainst *AssessedAgainst `json:"assessedAgainst,omitempty"`
	// ChangedIn maps each finding id to the draft version of the last mutation that changed the finding, its
	// decision, its notes or the human's replies to them, so loupe edit --expect-version refuses only when the edited
	// finding moved. Mutate keeps it.
	ChangedIn map[string]int `json:"changedIn,omitempty"`
}

func Load

func Load(dir string) (*Draft, error)

func Mutate

func Mutate(dir, command string, expectVersion *int, getenv func(string) string, fn func(*Draft) error) (*Draft, error)

Mutate is the only way a draft changes: read, check the expected version and apply fn all under the run lock, so concurrent writers serialize and a failed fn leaves the file untouched.

func MutateFinding

func MutateFinding(dir, command, findingID string, expectVersion *int, getenv func(string) string, fn func(*Draft) error) (*Draft, error)

MutateFinding is Mutate for a change to one finding: expectVersion is the draft version the caller read the finding at, and it refuses only when that finding or its decision changed since. A change to another finding passes, so an agent editing one finding does not race the human deciding the rest. A finding that does not exist passes the check, so fn reports it.

func NewEmpty

func NewEmpty() *Draft

type EarlierFinding

type EarlierFinding struct {
	ID       string    `json:"id"`
	Title    string    `json:"title"`
	Body     string    `json:"body"`
	Location *Location `json:"location"`
	Label    string    `json:"label"`
	Blocking bool      `json:"blocking"`
	FiledIn  FiledIn   `json:"filedIn"`
}

EarlierFinding is a published finding as the envelope holds it, plus the round that first filed it.

type EditInput

type EditInput struct {
	Title        json.RawMessage `json:"title"`
	Body         json.RawMessage `json:"body"`
	Location     json.RawMessage `json:"location"`
	General      json.RawMessage `json:"general"`
	Label        json.RawMessage `json:"label"`
	Blocking     json.RawMessage `json:"blocking"`
	Confidence   json.RawMessage `json:"confidence"`
	Severity     json.RawMessage `json:"severity"`
	Verified     json.RawMessage `json:"verified"`
	Impact       json.RawMessage `json:"impact"`
	References   json.RawMessage `json:"references"`
	SuggestedFix json.RawMessage `json:"suggestedFix"`
	Proposal     json.RawMessage `json:"proposal"`
	Options      json.RawMessage `json:"options"`
	// WithdrawReason is not a finding field: it goes on the history entry, and only with --exclude.
	WithdrawReason json.RawMessage `json:"withdrawReason"`
}

EditInput holds each field as raw JSON so an absent key (nil), a null and a value stay distinguishable.

type EntryFailure

type EntryFailure struct {
	Entry int
	Err   error
	// Decoding marks a failure to read the entry as a finding at all, which the message names as an input entry.
	Decoding bool
}

EntryFailure is one batch entry that was refused before or during validation.

type FiledIn

type FiledIn struct {
	Round     int    `json:"round"`
	ReviewURL string `json:"reviewUrl"`
	Commit    string `json:"commit,omitempty"`
}

FiledIn names a round as show --previous names it. Commit is empty when it could not be read back.

type Finding

type Finding struct {
	// ID is f-001, sequential within the run, never reused.
	ID string `json:"id"`
	// Rev starts at 1; increments on any change to a publishable field or to Included.
	Rev   int    `json:"rev"`
	Title string `json:"title"`
	Body  string `json:"body"`
	// Exactly one of Location or General is set.
	Location *FindingLocation `json:"location,omitempty"`
	General  bool             `json:"general"`
	// Proposal is the code change the agent suggests, Markdown, at most 64 KiB. Local runs only.
	Proposal string `json:"proposal,omitempty"`
	// Options are the 2 or 3 alternatives the human picks from, in place of a Proposal. Local runs only.
	Options []Option `json:"options,omitempty"`
	// Label is issue, suggestion, question or any other word kept verbatim; empty means none.
	Label    string `json:"label,omitempty"`
	Blocking bool   `json:"blocking"`
	// Confidence is high, medium or low when present.
	Confidence string `json:"confidence,omitempty"`
	// Severity is critical, major, minor or trivial when set through add or edit. A run captured before that rule may
	// hold free text, which still renders and is refused only once an edit changes it.
	Severity string `json:"severity,omitempty"`
	// Verified is reproduced or plausible when present.
	Verified     string   `json:"verified,omitempty"`
	Impact       string   `json:"impact,omitempty"`
	References   []string `json:"references,omitempty"`
	SuggestedFix string   `json:"suggestedFix,omitempty"`
	// By is ByAgent or ByHuman; audit only, it does not affect readiness.
	By string `json:"by"`
	// Included is never settable from JSON input; only edit --exclude and --include change it.
	Included  bool           `json:"included"`
	CreatedAt time.Time      `json:"createdAt"`
	UpdatedAt time.Time      `json:"updatedAt"`
	History   []HistoryEntry `json:"history"`
}

func Add

func Add(d *Draft, inputs []FindingInput, dif *diff.Diff, rules Rules, by string, now time.Time) ([]Finding, error)

Add validates every entry before appending any, so a batch is stored entirely or not at all.

func Edit

func Edit(d *Draft, findingID string, in EditInput, included *bool, dif *diff.Diff, by string, rules Rules, now time.Time) (f Finding, cleared bool, err error)

Edit applies in and, when included is not nil, sets Included. A change to a publishable field or to Included bumps rev, deletes the decision and appends one history entry; cleared reports whether a decision was deleted. dif is needed only when in changes a publishable field. A withdrawal reason goes on that entry. A new reason for a finding already not included, with nothing else changed, appends an entry of its own and keeps rev and the decision, so a human's exclusion stands. An edit that changes nothing returns the finding with ErrNoChange.

func Ordered

func Ordered(d *Draft) []Finding

Ordered is the findings in the published review's order, which every human-facing surface shares. Severity alone would disagree with the review, which places a blocking finding above every nonblocking one whatever its severity. It never reorders the stored slice, which keeps arrival order and is what the digest is built from.

func PublishableSet

func PublishableSet(d *Draft) []Finding

PublishableSet is what the human could still publish: included findings that are not excluded.

func Recalibrate

func Recalibrate(d *Draft, findingID, label string, blocking bool, dif *diff.Diff, rules Rules, now time.Time) (Finding, error)

Recalibrate is the human's label and blocking edit from the review interface. Unlike Edit it keeps a current decision, since the human made the change while looking at the finding. The command line MUST NOT reach it: --by is self-reported there, so an agent could change an accepted finding unseen. It closes no note, so a label change never answers a note the human has not read.

func Rewrite

func Rewrite(d *Draft, findingID, title, body string, rules Rules, dif *diff.Diff, now time.Time) (Finding, error)

Rewrite is the human's title and body edit from the review interface. It keeps a current decision and closes no note, as Recalibrate does, and for the same reason: the human typed the text while looking at the finding. The command line MUST NOT reach it.

type FindingGate

type FindingGate struct {
	Disposition string
	Reinstated  bool
	Regraded    bool
}

FindingGate is one finding's part in GateCounts. Disposition is the finding's disposition, except that a finding a human withdrew is excluded rather than withdrawn.

func GateOf

func GateOf(d *Draft, f Finding) FindingGate

type FindingInput

type FindingInput struct {
	Title        string         `json:"title"`
	Body         string         `json:"body"`
	Location     *LocationInput `json:"location,omitempty"`
	General      bool           `json:"general,omitempty"`
	Label        string         `json:"label,omitempty"`
	Blocking     bool           `json:"blocking,omitempty"`
	Confidence   string         `json:"confidence,omitempty"`
	Severity     string         `json:"severity,omitempty"`
	Verified     string         `json:"verified,omitempty"`
	Impact       string         `json:"impact,omitempty"`
	References   []string       `json:"references,omitempty"`
	SuggestedFix string         `json:"suggestedFix,omitempty"`
	Proposal     string         `json:"proposal,omitempty"`
	Options      []OptionInput  `json:"options,omitempty"`
}

FindingInput is the add input in contracts/cli.md. It has no included field because only the human changes that.

type FindingLocation

type FindingLocation struct {
	Path      string `json:"path"`
	Side      string `json:"side"`
	Line      int    `json:"line"`
	StartLine int    `json:"startLine,omitempty"`
	// Heading is the section's heading as the file writes it, set when add or edit resolved a heading anchor.
	Heading string `json:"heading,omitempty"`
}

FindingLocation is a finding's location in the draft: the range it publishes on, and the heading it was anchored to. The heading stays in the draft and the review interface; everything published reads Published.

func (FindingLocation) Published

func (l FindingLocation) Published() Location

type GateCounts

type GateCounts struct {
	Excluded   int
	Withdrawn  int
	Reinstated int
	Regraded   int
}

GateCounts is what the human gate did to the round's findings. Excluded and Withdrawn split the findings that do not publish, so published + Excluded + Withdrawn is every finding filed. Reinstated and Regraded are flags that can overlap either and can count published findings.

func GateCountsOf

func GateCountsOf(d *Draft) GateCounts

type HandBack

type HandBack struct {
	Schema int `json:"schema"`
	// Notes is append-only; a note stays listed after it is answered or closed and Awaiting filters it out.
	Notes []string `json:"notes"`
}

HandBack is the set of notes handed to the agent: each note as it is written, and any still open and unanswered when a review session quits. It lives beside the draft rather than in it so recording one never bumps the draft version.

func LoadHandBack

func LoadHandBack(dir string) (*HandBack, error)

LoadHandBack reads the set; a run that never recorded one is empty.

type HistoryEntry

type HistoryEntry struct {
	At time.Time `json:"at"`
	By string    `json:"by"`
	// Changed maps each changed field to its previous value. It is empty on an entry that only amends a reason.
	Changed map[string]any `json:"changed"`
	// Reason is why the finding was withdrawn, on the entry that withdrew it or on a later one that amends it.
	Reason *Reason `json:"reason,omitempty"`
}

type Location

type Location struct {
	Path string `json:"path"`
	// Side is SideRight (the new file, and the default) or SideLeft (the old file).
	Side      string `json:"side"`
	Line      int    `json:"line"`
	StartLine int    `json:"startLine,omitempty"`
}

type LocationInput

type LocationInput struct {
	Path      string `json:"path"`
	Side      string `json:"side"`
	Line      int    `json:"line"`
	StartLine int    `json:"startLine,omitempty"`
	// Heading is a pointer so an empty heading is refused rather than read as a line form with no line.
	Heading *string `json:"heading,omitempty"`
}

LocationInput is a location as add and edit read it: a line form, or a heading anchor that resolves to one.

type Note

type Note struct {
	// ID is n-001, sequential.
	ID        string    `json:"id"`
	FindingID string    `json:"findingId"`
	Body      string    `json:"body"`
	At        time.Time `json:"at"`
	// Status is NoteOpen, NoteResolved or NoteDismissed.
	Status   string     `json:"status"`
	ClosedAt *time.Time `json:"closedAt,omitempty"`
}

func SendBack

func SendBack(d *Draft, findingID, body string, now time.Time) (Note, error)

SendBack deletes the finding's decision so it stays pending until the human decides it again.

type Option

type Option struct {
	Key         string `json:"key"`
	Label       string `json:"label"`
	Proposal    string `json:"proposal"`
	Recommended bool   `json:"recommended,omitempty"`
}

Option is one alternative of a choice finding. Key is "1", "2" or "3", assigned by loupe in input order.

type OptionInput

type OptionInput struct {
	Label       string `json:"label"`
	Proposal    string `json:"proposal"`
	Recommended bool   `json:"recommended,omitempty"`
}

OptionInput is one option as add and edit read it. Loupe assigns the key.

type Readiness

type Readiness struct {
	Ready     bool     `json:"ready"`
	Accepted  []string `json:"accepted"`
	Pending   []string `json:"pending"`
	Excluded  []string `json:"excluded"`
	Withdrawn []string `json:"withdrawn"`
	OpenNotes []string `json:"openNotes"`
}

Readiness holds id lists; counts are their lengths.

func ReadinessOf

func ReadinessOf(d *Draft) Readiness

type Reason

type Reason struct {
	Text string `json:"text"`
	Code string `json:"code,omitempty"`
}

Reason is a withdrawal's reason: one Markdown line the human reads, and an optional word a skill picks to group by.

func CurrentReason

func CurrentReason(f Finding) *Reason

CurrentReason is the reason every surface shows: the newest one since the latest withdrawal, while the finding is still not included. When it is not included, its newest inclusion change is that withdrawal, so the walk stops there.

type Reply

type Reply struct {
	// ID is r-001, sequential.
	ID     string `json:"id"`
	NoteID string `json:"noteId"`
	Body   string `json:"body"`
	// By is ByAgent or ByHuman.
	By string    `json:"by"`
	At time.Time `json:"at"`
}

func AddReply

func AddReply(d *Draft, noteID, body, by string, now time.Time) (Reply, error)

AddReply answers a note. It never changes the note's status or any decision; only the human closes notes.

type Return

type Return struct {
	Schema       int       `json:"schema"`
	ReturnedAt   time.Time `json:"returnedAt"`
	DraftVersion int       `json:"draftVersion"`
	// Note is the human's closing note on the work as a whole, absent when they wrote none.
	Note string `json:"note,omitempty"`
}

Return is the record Seal writes.

func LoadReturn

func LoadReturn(dir string) (r Return, ok bool, err error)

LoadReturn reads return.json; ok is false while the run has not been returned.

type Rules

type Rules struct {
	// AllowProposal accepts a proposal on a finding. Local runs set this; PR runs do not.
	AllowProposal bool
	// GeneralOnly refuses any finding with a location. Local runs captured with --no-files set this.
	GeneralOnly bool
}

Rules configures which fields and input forms a mutator accepts. The zero value is today's PR behavior.

Jump to

Keyboard shortcuts

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