review

package
v1.3.2 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const MaxAttachmentBytes = 5 << 20

Variables

This section is empty.

Functions

func Dir

func Dir(dataRoot, key string) string

Dir returns the review folder for a session key.

func EncodeCommentsJSON

func EncodeCommentsJSON(entries []ListedComment) ([]byte, error)

EncodeCommentsJSON marshals a listing, normalizing nil to [].

func FormatCommentsText

func FormatCommentsText(entries []ListedComment, unresolvedOnly bool) string

FormatCommentsText renders the human-readable `comments` listing.

func IsAbsoluteOrTraversal

func IsAbsoluteOrTraversal(p string) bool

IsAbsoluteOrTraversal rejects absolute paths and paths escaping the working tree. The check runs on the raw input before Clean, following crit, so Windows-style prefixes cannot slip through.

func JSONPath

func JSONPath(dir string) string

JSONPath returns the review.json path inside a review folder.

func NormalizePath

func NormalizePath(p string) string

NormalizePath cleans a user-supplied file path into the forward-slash form used both in session-key derivation and as Files map keys. Paths under the current working directory normalize to the same relative form whether given as absolute or relative, so all commands agree on keys.

func Now

func Now() string

Now returns the current UTC time in the RFC 3339 format used throughout review.json.

func ParseDocumentForm

func ParseDocumentForm(d AttachedDocument) ([]form.Item, error)

func ParseLineSpec

func ParseLineSpec(spec string) (start, end int, err error)

ParseLineSpec parses "42" or "45-47" into a start/end line pair.

func PlanCurrentPath

func PlanCurrentPath(slug string) string

PlanCurrentPath returns the path of the plan's latest content.

func PlanSessionKey

func PlanSessionKey(cwd, slug string) string

PlanSessionKey computes the session key for a plan review, matching crit's cwd + "__plan:"+slug derivation (the marker hashes in the branch position).

func PlanStorageDir

func PlanStorageDir(slug string) string

PlanStorageDir returns the storage directory for a plan slug.

func PlansDir

func PlansDir() string

PlansDir returns the root of plan storage.

func RandomCommentID

func RandomCommentID() string

RandomCommentID returns a random line/file comment ID (e.g. "c_a3f8b2").

func RandomReplyID

func RandomReplyID() string

RandomReplyID returns a random reply ID (e.g. "rp_d7e2a0").

func RandomReviewCommentID

func RandomReviewCommentID() string

RandomReviewCommentID returns a random review-level comment ID (e.g. "r_b4c9e1").

func RemoveSessionEntry

func RemoveSessionEntry(key string) error

RemoveSessionEntry deletes the registry entry for a key, ignoring missing files.

func ResolveSlug

func ResolveSlug(content []byte) string

ResolveSlug derives a plan slug from its content: the first markdown heading plus today's date, or a timestamp fallback.

func ReviewsRoot

func ReviewsRoot(dataRoot string) string

ReviewsRoot returns the directory that holds all review folders, honoring an explicit data root (--output / config) when non-empty.

func SavePlanVersionAt

func SavePlanVersionAt(dir string, content []byte) (int, error)

SavePlanVersionAt saves content in a plan's storage directory as the next numbered version and updates current.md, returning the 1-based version.

func SessionKey

func SessionKey(cwd, branch string, args []string) string

SessionKey derives the stable 12-hex-char review session key, matching crit's algorithm: sha256 over the working directory plus either the file arguments (files mode; branch-independent) or the branch (git mode).

func SessionsDir

func SessionsDir() string

SessionsDir returns the directory holding session registry entries.

func Slugify

func Slugify(s string) string

Slugify converts a string to a URL-safe slug.

func SocketPathFor

func SocketPathFor(key string) string

SocketPathFor returns the Unix socket path for a session key.

func ValidSessionKey

func ValidSessionKey(s string) bool

ValidSessionKey reports whether s looks like a session key.

func WriteJSON

func WriteJSON(path string, value any) error

WriteJSON replaces a result only after its complete contents are written.

Types

type AttachedDocument

type AttachedDocument struct {
	ID       string `json:"id"`
	Source   string `json:"source"`
	Name     string `json:"name"`
	Content  string `json:"content"`
	Revision string `json:"revision"`
	Removed  bool   `json:"removed,omitempty"`
}

AttachedDocument keeps the source identity separate from its comment path.

func ReadAttachedDocuments

func ReadAttachedDocuments(paths []string) ([]AttachedDocument, error)

ReadAttachedDocuments validates all inputs before changing session state.

func (AttachedDocument) Path

func (d AttachedDocument) Path() string

type BulkCommentEntry

type BulkCommentEntry struct {
	File     string `json:"file,omitempty"`
	Path     string `json:"path,omitempty"`     // alias for File
	Line     int    `json:"-"`                  // parsed from "line" when int
	LineSpec string `json:"-"`                  // parsed from "line" when string ("45-47")
	EndLine  int    `json:"end_line,omitempty"` // defaults to Line
	Body     string `json:"body"`
	Author   string `json:"author,omitempty"` // per-entry override; falls back to global
	Scope    string `json:"scope,omitempty"`  // "review", "file", or "" (inferred)
	ReplyTo  string `json:"reply_to,omitempty"`
	Resolve  bool   `json:"resolve,omitempty"`
}

BulkCommentEntry is one element of the `comment --json` input array.

func (*BulkCommentEntry) UnmarshalJSON

func (e *BulkCommentEntry) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts the "line" field as either an int (42) or a string line spec ("45-47").

type BulkStats

type BulkStats struct {
	Comments int
	Replies  int
}

BulkStats summarizes what a bulk apply added.

type CodeFileStatus

type CodeFileStatus struct {
	File     string    `json:"file"`
	Comments []Comment `json:"comments"`
}

CodeFileStatus represents a single file's review status in aggregate output.

type CodeReviewStatus

type CodeReviewStatus struct {
	Files         []CodeFileStatus `json:"files"`
	TotalComments int              `json:"total_comments"`
}

CodeReviewStatus is the aggregate status for all files in a code review.

func AggregateStatus

func AggregateStatus(dataRoot string) (*CodeReviewStatus, error)

AggregateStatus summarizes the current code review session.

type Comment

type Comment struct {
	ID          string `json:"id"`
	StartLine   int    `json:"start_line"`
	EndLine     int    `json:"end_line"`
	Side        string `json:"side,omitempty"`
	Body        string `json:"body"`
	Quote       string `json:"quote,omitempty"`
	QuoteOffset *int   `json:"quote_offset,omitempty"`
	// Anchor is the full text of lines StartLine..EndLine at authoring time,
	// used to re-locate the comment when line numbers drift across rounds.
	Anchor  string `json:"anchor,omitempty"`
	Drifted bool   `json:"drifted,omitempty"`
	// DriftedOnRound is the round that newly classified this comment as
	// drifted; preserved for crit compatibility.
	DriftedOnRound int    `json:"drifted_on_round,omitempty"`
	Author         string `json:"author,omitempty"`
	UserID         string `json:"user_id,omitempty"`
	// Scope is "line", "file", or "review".  Empty means "line".
	Scope     string `json:"scope,omitempty"`
	CreatedAt string `json:"created_at"`
	UpdatedAt string `json:"updated_at"`
	Resolved  bool   `json:"resolved,omitempty"`
	// ResolvedRound is the review round during which Resolved transitioned
	// false -> true; cleared to 0 when it transitions back.
	ResolvedRound  int     `json:"resolved_round,omitempty"`
	CarriedForward bool    `json:"carried_forward,omitempty"`
	ReviewRound    int     `json:"review_round,omitempty"`
	Replies        []Reply `json:"replies,omitempty"`

	// Forge-sync fields written by crit; Critty preserves but never sets them.
	GitHubID           int64  `json:"github_id,omitempty"`
	GitLabNoteID       int64  `json:"gitlab_note_id,omitempty"`
	GitLabDiscussionID string `json:"gitlab_discussion_id,omitempty"`
	GitLabResolved     *bool  `json:"gitlab_resolved,omitempty"`
	LastPushedBodyHash string `json:"last_pushed_body_hash,omitempty"`

	HeadSHA string `json:"head_sha,omitempty"`
	// DiffScope is "layer" or "full_stack" for Crit range-focus comments.
	// Working-tree filters such as staged and unstaged intentionally leave it empty.
	DiffScope string `json:"diff_scope,omitempty"`
	FocusKey  string `json:"focus_key,omitempty"`
}

Comment represents a single review comment: line-level, file-level, or review-level depending on Scope.

func CarryForwardFile

func CarryForwardFile(comments []Comment, prevContent, newContent, now string) []Comment

CarryForwardFile maps a file's comments onto the file's new content. prevContent is the content the comments were authored against; now stamps UpdatedAt on the carried comments.

func CarryForwardPartial

func CarryForwardPartial(comments []Comment, changed bool, now string) []Comment

CarryForwardPartial preserves coordinates when missing context prevents a reliable line mapping. Changed snapshots flag line anchors for inspection.

func (*Comment) EndAt

func (c *Comment) EndAt() int

EndAt returns the effective last line of the comment's range.

type CommentNotFoundError

type CommentNotFoundError struct{ ID string }

CommentNotFoundError reports a reply target missing from a review file.

func (*CommentNotFoundError) Error

func (e *CommentNotFoundError) Error() string

type CritJSON

type CritJSON struct {
	RoundState     RoundState              `json:"critty_state,omitempty"`
	Branch         string                  `json:"branch"`
	BaseRef        string                  `json:"base_ref"`
	UpdatedAt      string                  `json:"updated_at"`
	ReviewRound    int                     `json:"review_round"`
	ReviewComments []Comment               `json:"review_comments,omitempty"`
	CliArgs        []string                `json:"cli_args,omitempty"`
	Files          map[string]CritJSONFile `json:"files"`

	// Sharing fields written by crit; preserved but unused by Critty.
	ShareURL        string `json:"share_url,omitempty"`
	DeleteToken     string `json:"delete_token,omitempty"`
	ShareScope      string `json:"share_scope,omitempty"`
	ShareOrg        string `json:"share_org,omitempty"`
	ShareOrgName    string `json:"share_org_name,omitempty"`
	ShareVisibility string `json:"share_visibility,omitempty"`
	LastShareHash   string `json:"last_share_hash,omitempty"`
	// ActiveDiffScope mirrors Crit's current range focus ("layer" or
	// "full_stack").  It is empty for working-tree reviews, including staged.
	ActiveDiffScope string `json:"active_diff_scope,omitempty"`
}

CritJSON is the top-level review.json document.

func NewCritJSON

func NewCritJSON() CritJSON

NewCritJSON returns an empty review document at round 1.

func (*CritJSON) ContainsCommentID

func (cj *CritJSON) ContainsCommentID(id string) bool

ContainsCommentID reports whether the review holds a comment with this ID.

func (*CritJSON) ListComments

func (cj *CritJSON) ListComments(unresolvedOnly bool) []ListedComment

ListComments flattens a review into display order: review-level comments first, then files sorted by path, file-level before line-level, line-level sorted by start line.

func (*CritJSON) TotalComments

func (cj *CritJSON) TotalComments() int

TotalComments counts review-level and per-file comments.

func (*CritJSON) Touch

func (cj *CritJSON) Touch()

Touch stamps UpdatedAt with the current UTC time.

type CritJSONFile

type CritJSONFile struct {
	Status   string    `json:"status"`
	FileHash string    `json:"file_hash,omitempty"`
	Comments []Comment `json:"comments"`
}

CritJSONFile is the per-file section in review files.

type DocumentAttachments

type DocumentAttachments struct {
	Version   int                `json:"version"`
	Documents []AttachedDocument `json:"documents"`
}

type FormDocument

type FormDocument struct {
	AttachedDocument
	Items   []form.Item            `json:"definitions"`
	Answers map[string]form.Answer `json:"answers"`
}

type FormResult

type FormResult struct {
	FormState
	Session       string                     `json:"session,omitempty"`
	Approved      bool                       `json:"approved"`
	Verdict       Verdict                    `json:"verdict,omitempty"`
	ReviewComment *Comment                   `json:"review_comment,omitempty"`
	Round         int                        `json:"round"`
	Consents      map[string]map[string]bool `json:"consents,omitempty"`
}

FormResult is self-contained, including the exact inputs to each consent.

type FormState

type FormState struct {
	Version   int            `json:"version"`
	Revision  string         `json:"review_revision"`
	Input     ReviewInput    `json:"reviewed_target"`
	Documents []FormDocument `json:"attachments"`
}

func (*FormState) Document

func (state *FormState) Document(path string) *FormDocument

func (FormState) HasForms

func (state FormState) HasForms() bool

func (FormState) Missing

func (state FormState) Missing() []string

func (FormState) Result

func (state FormState) Result(approved bool, round int) FormResult

type ListedComment

type ListedComment struct {
	Scope string  `json:"scope"`
	Path  *string `json:"path,omitempty"`
	Comment
}

ListedComment is a comment flattened for CLI output, matching crit's `comments` format. It embeds Comment so new review.json fields flow through automatically; Scope and Path are the only additions.

type Reply

type Reply struct {
	ID        string `json:"id"`
	Body      string `json:"body"`
	Author    string `json:"author,omitempty"`
	UserID    string `json:"user_id,omitempty"`
	CreatedAt string `json:"created_at"`
	// ReviewRound is the review round during which this reply was authored.
	ReviewRound int `json:"review_round,omitempty"`
	// ResolvedRound mirrors Comment.ResolvedRound for per-reply resolution.
	ResolvedRound int `json:"resolved_round,omitempty"`
}

Reply represents a single reply in a comment thread.

type ReviewInput

type ReviewInput struct {
	Scope  string                  `json:"scope"`
	Source *git.ReviewSource       `json:"source,omitempty"`
	Files  map[string]ReviewedFile `json:"files"`
	Diff   string                  `json:"diff,omitempty"`
}

type ReviewedFile

type ReviewedFile struct {
	SnapshotFile
	Status string        `json:"status,omitempty"`
	Binary bool          `json:"binary,omitempty"`
	Digest string        `json:"digest,omitempty"`
	Diff   *git.DiffInfo `json:"diff,omitempty"`
}

type RoundState

type RoundState struct {
	Files              map[string]SnapshotFile    `json:"files,omitempty"`
	Diff               string                     `json:"diff,omitempty"`
	Finished           bool                       `json:"finished,omitempty"`
	NewFeedback        bool                       `json:"new_feedback,omitempty"`
	Verdict            Verdict                    `json:"verdict,omitempty"`
	ReviewCommentID    string                     `json:"review_comment_id,omitempty"`
	FeedbackComments   map[string]map[string]bool `json:"feedback_comments,omitempty"`
	ReviewCommentDraft string                     `json:"review_comment_draft,omitempty"`
	// Nil means no baseline was recorded; an empty array means no replies
	// existed at submission.  Preserve that distinction in saved sessions.
	SubmittedReplies []string `json:"submitted_replies"`
}

RoundState is Critty's saved runtime context, separate from CritJSON comments.

type Session

type Session struct {
	Key  string
	Dir  string
	CJ   CritJSON
	Meta SessionEntry
	// contains filtered or unexported fields
}

Session binds a review folder on disk to its loaded CritJSON document.

func FindSavedSession

func FindSavedSession(matches func(SessionEntry) bool) (*Session, error)

FindSavedSession selects an unambiguous saved review in the current directory.

func FindSessionsByCommentID

func FindSessionsByCommentID(id, excludeKey string) ([]*Session, error)

FindSessionsByCommentID scans every registered session for a comment ID, skipping the session with excludeKey. Used to redirect replies whose target lives in another review file.

func NewSession

func NewSession(dataRoot string, meta SessionEntry) (*Session, error)

NewSession allocates independent storage even for identical review arguments.

func OpenCodeSession

func OpenCodeSession(dataRoot string) (*Session, error)

OpenCodeSession opens the git-mode review session for the current working directory and branch.

func OpenCodeSessionWithArgs

func OpenCodeSessionWithArgs(dataRoot string, args []string) (*Session, error)

OpenCodeSessionWithArgs isolates comments by the selected review source.

func OpenDocSession

func OpenDocSession(dataRoot, docPath string) (*Session, error)

OpenDocSession opens the files-mode review session for a single document.

func OpenPlanSession

func OpenPlanSession(slug string) (*Session, error)

OpenPlanSession opens the review session stored inside a plan directory.

func OpenSession

func OpenSession(dataRoot, key string) (*Session, error)

OpenSession loads the review folder for key, creating an empty round-1 document when none exists yet.

func OpenSessionAt

func OpenSessionAt(key, dir string) (*Session, error)

OpenSessionAt loads a review folder at an explicit directory.

func OpenSessionFromEntry

func OpenSessionFromEntry(e SessionEntry) (*Session, error)

OpenSessionFromEntry opens the review folder a registry entry points at.

func ResolveCode

func ResolveCode(dataRoot string) (*Session, error)

func ResolveDocument

func ResolveDocument(dataRoot, path string) (*Session, error)

func ResolvePlan

func ResolvePlan(slug string) (*Session, error)

func ResolveTarget

func ResolveTarget(dataRoot, sessionID string) (*Session, error)

ResolveTarget finds the review session a comment command should operate on: an explicit --session key, the single session registered for the current directory, or (when none is registered) the git-mode session for the current branch.

func (*Session) AppendFileComment

func (s *Session) AppendFileComment(path, body, author, userID string)

AppendFileComment adds a file-level comment (no line reference).

func (*Session) AppendLineComment

func (s *Session) AppendLineComment(path string, startLine, endLine int, body, author, userID string)

AppendLineComment adds a line-level comment, stamping the drift-correction anchor from the file's current content on disk when readable.

func (*Session) AppendReply

func (s *Session) AppendReply(commentID, body, author, userID string, resolve bool, filterPath string) error

AppendReply adds a reply to the comment with the given ID, searching review-level comments first and then file comments. filterPath, when non-empty, restricts the file search to one path (for duplicated IDs).

Following crit: a resolving reply stamps Resolved/ResolvedRound; a non-resolving reply *un*resolves a previously-resolved comment so the new reply is not hidden by the resolution filter.

func (*Session) AppendReviewComment

func (s *Session) AppendReviewComment(body, author, userID string)

AppendReviewComment adds a review-level comment.

func (*Session) ApplyBulk

func (s *Session) ApplyBulk(entries []BulkCommentEntry, globalAuthor, userID string) (BulkStats, error)

ApplyBulk validates and applies all entries to this session in one atomic write. Any entry error aborts the batch before anything is saved.

func (*Session) ApplyBulkEntry

func (s *Session) ApplyBulkEntry(i int, e BulkCommentEntry, globalAuthor, userID string) error

ApplyBulkEntry routes one bulk entry to the matching authoring helper. globalAuthor fills entries without their own author; userID always comes from local config, never the payload (a payload user_id would be a spoof vector).

func (*Session) BeginForms

func (s *Session) BeginForms(input ReviewInput, docs []AttachedDocument) (FormState, error)

func (*Session) BeginRound

func (s *Session) BeginRound(files map[string]SnapshotFile, rawDiff string) error

BeginRound restores the persisted round and remaps anchors onto fresh content. A stopped, unfinished round keeps its number and feedback state.

func (*Session) Clear

func (s *Session) Clear() error

Clear removes the whole review folder and its registry entry. Missing folders are not an error.

func (*Session) DiffPath

func (s *Session) DiffPath() string

func (*Session) FileComments

func (s *Session) FileComments(path string) []Comment

FileComments returns the comments recorded for a (normalized) file path.

func (*Session) HasAttachments

func (s *Session) HasAttachments() bool

HasAttachments errs on the side of retaining images when the directory cannot be read. Approval cleanup must not remove an unread attachment.

func (*Session) LoadDocuments

func (s *Session) LoadDocuments() (DocumentAttachments, error)

func (*Session) LoadForms

func (s *Session) LoadForms() (FormState, error)

func (*Session) Path

func (s *Session) Path() string

Path returns the session's review.json path.

func (*Session) ReplaceDocuments

func (s *Session) ReplaceDocuments(docs []AttachedDocument) error

ReplaceDocuments retains removed snapshots so their comments remain readable. Callers hold the session run lock while replacing review inputs.

func (*Session) Save

func (s *Session) Save() error

Save merges local edits with updates since the last load or save, then writes the result atomically under an advisory file lock.

func (*Session) SaveAttachment

func (s *Session) SaveAttachment(data []byte) (string, error)

SaveAttachment stores an image beside review.json and returns its Markdown path.

func (*Session) SaveDiff

func (s *Session) SaveDiff(p *git.Patch) error

SaveDiff atomically replaces the snapshot consumed at the next round.

func (*Session) SaveFormResult

func (s *Session) SaveFormResult(result FormResult) error

func (*Session) SaveForms

func (s *Session) SaveForms(state FormState) error

func (*Session) SetFileComments

func (s *Session) SetFileComments(path, status string, comments []Comment)

SetFileComments replaces the comments for a file, creating its entry when missing. An empty status leaves the recorded status untouched.

func (*Session) SetSubmission

func (s *Session) SetSubmission(verdict Verdict, body, author string)

SetSubmission records a round's decision and its optional review-level comment. Reusing the comment ID makes failed saves safe to retry.

func (*Session) SortedFiles

func (s *Session) SortedFiles() []string

SortedFiles returns the session's file paths in stable sorted order.

func (*Session) SubmissionComment

func (s *Session) SubmissionComment() *Comment

func (*Session) Update

func (s *Session) Update(fn func(*Session) error) error

Update reloads the latest review state and applies fn while holding the advisory lock, then saves the result. Keeping the full read-modify-write cycle under one lock prevents concurrent CLI commands from losing updates.

type SessionEntry

type SessionEntry struct {
	Project    *string  `json:"project,omitempty"`
	Topic      *string  `json:"topic,omitempty"`
	Mode       string   `json:"mode,omitempty"`
	PlanSlug   string   `json:"plan_slug,omitempty"`
	Key        string   `json:"key"`
	CWD        string   `json:"cwd"`
	Args       []string `json:"args,omitempty"`
	Branch     string   `json:"branch,omitempty"`
	ReviewPath string   `json:"review_path"`
	StartedAt  string   `json:"started_at"`
	PID        int      `json:"pid,omitempty"`
	SocketPath string   `json:"socket_path,omitempty"`
}

SessionEntry records where a review session's data lives, so commands run later (status, clear, comment) can find review folders belonging to a working directory without re-deriving every possible key.

func ListSessionEntries

func ListSessionEntries() ([]SessionEntry, error)

ListSessionEntries returns all registered session entries.

func ReadSessionEntry

func ReadSessionEntry(key string) (*SessionEntry, error)

ReadSessionEntry loads one registry entry.

type SnapshotFile

type SnapshotFile struct {
	Content string `json:"content"`
	Partial bool   `json:"partial,omitempty"`
}

SnapshotFile preserves the text used to anchor comments across TUI restarts.

type Verdict

type Verdict string
const (
	VerdictApprove Verdict = "approve"
	VerdictReject  Verdict = "reject"
	VerdictComment Verdict = "comment"
)

func (Verdict) Valid

func (v Verdict) Valid() bool

Jump to

Keyboard shortcuts

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