service

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2026 License: MIT Imports: 46 Imported by: 0

Documentation

Overview

Package service implements the core business logic for the semantica CLI.

Index

Constants

View Source
const DefaultDrainLinger = 2 * time.Second

DefaultDrainLinger is the idle wait before the drain loop exits.

Variables

View Source
var ErrLauncherNotEnabled = errors.New("launcher not enabled")

ErrLauncherNotEnabled reports that launcher dispatch is disabled.

View Source
var ErrNoEventsInWindow = fmt.Errorf("no agent events in delta window")

ErrNoEventsInWindow is returned by ComputeAIPercentFromDiff when no agent events exist in the delta window. The caller can use this to decide whether to attempt an inline ingest before retrying.

View Source
var ProviderGitignorePaths = map[string]string{
	"claude-code": ".claude/settings.local.json",
	"codex":       ".codex/hooks.json",
	"cursor":      ".cursor/hooks.json",
	"gemini-cli":  ".gemini/settings.json",
	"copilot":     ".github/hooks/semantica.json",
	"kiro-ide":    ".kiro/hooks/",
	"kiro-cli":    ".kiro/agents/semantica.json",
}

ProviderGitignorePaths maps hook provider names to repo-local config files that should be gitignored when created by Semantica.

Functions

func CompactTokens

func CompactTokens(n int64) string

CompactTokens formats a token count as a compact string like "1.5k", "12k", "4.4M".

func DrainUntilStable added in v0.3.6

func DrainUntilStable(ctx context.Context, linger time.Duration, run MarkerRunner) error

DrainUntilStable keeps draining until two passes in a row remove no markers. It waits for retries due within maxRetryDrainWait; other failed markers remain queued for a later invocation.

func EnsureProviderGitignore added in v0.3.3

func EnsureProviderGitignore(repoRoot string, installedProviders []string, preExisting map[string]bool) error

EnsureProviderGitignore adds gitignore entries for provider config files that were created by Semantica (not pre-existing).

func ExtendBackfillCutoff

func ExtendBackfillCutoff(ctx context.Context, h *sqlstore.Handle, connectedRepoID, repositoryID, commitHash string, linkedAt int64) error

ExtendBackfillCutoff extends the backfill cutoff to include a commit that failed during live push. Re-opens completed backfills if needed.

func FormatDuration

func FormatDuration(startMs, endMs int64) string

FormatDuration formats a duration in milliseconds between two timestamps as a compact human-readable string.

func InitBackfillState

func InitBackfillState(ctx context.Context, h *sqlstore.Handle, connectedRepoID, repositoryID string) (bool, error)

InitBackfillState snapshots the latest commit link as the replay cutoff and upserts the backfill row. If no commit links exist, returns false.

func LoadDeltaCandidates added in v0.6.0

LoadDeltaCandidates returns verified tool-delta evidence and diagnostics for an attribution window.

func RePushAttribution

func RePushAttribution(ctx context.Context, repoRoot, commitHash, checkpointID string)

RePushAttribution re-sends attribution after summary generation.

func RedirectWorkerLog added in v0.3.7

func RedirectWorkerLog(path string) (cleanup func() error, err error)

RedirectWorkerLog opens path in append mode and routes worker logs there. Linux and Windows launchers use it; macOS launchd already redirects output at the OS level.

The redirect updates wlogWriter, os.Stdout, os.Stderr, and the default slog logger so plain writes and structured logs land in the same file. It does not retarget loggers that captured os.Stderr at package init in other code, and it does not affect runtime panic output.

Call this before per-job redirects in `worker drain`. The returned cleanup restores the previous logging state and closes the file. It is safe to call cleanup multiple times.

func RelativeTime

func RelativeTime(ms int64) string

RelativeTime formats a unix-milli timestamp as a human-friendly relative duration like "2m", "1h", "3d".

func SnapshotProviderConfigs added in v0.3.3

func SnapshotProviderConfigs(repoRoot string) map[string]bool

SnapshotProviderConfigs returns provider config files that already exist.

func SweepToolWindows added in v0.6.0

func SweepToolWindows(ctx context.Context)

SweepToolWindows recovers tool-window evidence for active repositories. Repository failures are logged without stopping the remaining sweep.

func WorkerLockPath added in v0.6.0

func WorkerLockPath(semDir string) string

WorkerLockPath returns the repository worker lock location.

Types

type AIPercentResult

type AIPercentResult struct {
	Percent           float64
	TotalLines        int
	AILines           int
	ExactLines        int // tier 1: exact trimmed match
	ModifiedLines     int // tier 0 with hunk overlap
	FormattedLines    int // tier 2: whitespace-normalized match
	ProviderOnlyLines int // provider-touch only, excluded from headline
	FilesTouched      int // unique files in the diff
	Providers         []ProviderAttribution
}

AIPercentResult contains the full attribution breakdown returned by ComputeAIPercentFromDiff. The Percent field is the headline number; the remaining fields support richer commit trailers and diagnostics.

type AITrendPoint

type AITrendPoint struct {
	CommitHash   string  `json:"commit_hash"`
	AIPercentage float64 `json:"ai_percentage"`
	CreatedAt    int64   `json:"created_at"`
}

type AttributionDiagnostics

type AttributionDiagnostics struct {
	EventsConsidered  int `json:"events_considered"`
	EventsAssistant   int `json:"events_assistant"`
	PayloadsLoaded    int `json:"payloads_loaded"`
	AIToolEvents      int `json:"ai_tool_events"`
	ExactMatches      int `json:"exact_matches"`
	NormalizedMatches int `json:"normalized_matches"`
	ModifiedMatches   int `json:"modified_matches"`
	// Tool-delta counters are set only by v2 scoring.
	DeltaExactMatches      int      `json:"delta_exact_matches,omitempty"`
	DeltaNormalizedMatches int      `json:"delta_normalized_matches,omitempty"`
	DeltaAlignmentsRefused int      `json:"delta_alignments_refused,omitempty"`
	DeltaGroupsEligible    int      `json:"delta_groups_eligible,omitempty"`
	DeltaGroupsRejected    int      `json:"delta_groups_rejected,omitempty"`
	Notes                  []string `json:"notes,omitempty"`
}

AttributionDiagnostics provides transparency into why a particular AI percentage was computed. Useful when AI% is 0 and the user wants to understand which stage of the pipeline had no data.

Notes carries both the pipeline-state message (first entry, when non-empty) and the factual notes produced by the attribution pipeline (fallback signals, carry-forward, deletion inference). The API normalizes any singular "note" field from older CLI versions into this same slice at ingest time.

type AttributionInput

type AttributionInput struct {
	RepoPath   string // path to the git repository (defaults to ".")
	CommitHash string // full or abbreviated commit SHA
}

AttributionInput holds the parameters for an attribution request.

type AttributionResult

type AttributionResult struct {
	CommitHash          string `json:"commit_hash"`
	CheckpointID        string `json:"checkpoint_id"`
	AIExactLines        int    `json:"ai_exact_lines"`
	AIFormattedLines    int    `json:"ai_formatted_lines"`
	AIModifiedLines     int    `json:"ai_modified_lines"`
	AIProviderOnlyLines int    `json:"ai_provider_only_lines,omitempty"` // provider-touch only; excluded from AILines/AIPercentage
	// Tool-delta subsets of the exact and formatted totals.
	AIDeltaExactLines     int                    `json:"ai_delta_exact_lines,omitempty"`
	AIDeltaFormattedLines int                    `json:"ai_delta_formatted_lines,omitempty"`
	AILines               int                    `json:"ai_lines"` // exact + formatted + modified (headline number)
	HumanLines            int                    `json:"human_lines"`
	TotalLines            int                    `json:"total_lines"`
	AIPercentage          float64                `json:"ai_percentage"` // (exact + formatted + modified) / total * 100
	FilesAITouched        int                    `json:"files_ai_touched"`
	FilesTotal            int                    `json:"files_total"`
	FilesCreated          []FileChange           `json:"files_created,omitempty"`
	FilesEdited           []FileChange           `json:"files_edited,omitempty"`
	FilesDeleted          []FileChange           `json:"files_deleted,omitempty"`
	Files                 []FileAttribution      `json:"files,omitempty"`
	ProviderDetails       []ProviderAttribution  `json:"provider_details,omitempty"`
	Diagnostics           AttributionDiagnostics `json:"diagnostics"`
	Evidence              string                 `json:"evidence,omitempty"`       // "High", "Medium", "Low"
	FallbackCount         int                    `json:"fallback_count,omitempty"` // AI-attributed files with provider-touch or weaker evidence
	// AttrVersion identifies the scoring algorithm that produced the result.
	AttrVersion string `json:"attribution_version,omitempty"`
}

AttributionResult is the full attribution breakdown for a single commit.

type AttributionService

type AttributionService struct {
	// contains filtered or unexported fields
}

AttributionService computes per-commit AI vs human attribution. openOpts lets worker callers fail fast while user-facing commands can wait out short-lived SQLite writer locks.

func NewAttributionService

func NewAttributionService() *AttributionService

NewAttributionService returns a fail-fast service for worker paths.

func NewAttributionServiceWithOpenOptions added in v0.5.2

func NewAttributionServiceWithOpenOptions(opts sqlstore.OpenOptions) *AttributionService

NewAttributionServiceWithOpenOptions returns a service with custom SQLite open options.

func (*AttributionService) AttributeCommit

AttributeCommit computes the AI attribution breakdown for a single commit.

func (*AttributionService) Blame

Blame resolves a generic ref (commit hash or checkpoint ID/prefix) and computes AI attribution. For commits, it produces full line-level attribution against the commit diff. For checkpoints without a commit, it reports AI activity (events and files touched) in the checkpoint's delta window.

func (*AttributionService) ComputeAIPercentFromDiff

func (s *AttributionService) ComputeAIPercentFromDiff(
	ctx context.Context,
	h *sqlstore.Handle,
	bs *blobs.Store,
	diffBytes []byte,
	in ComputeAIPercentInput,
) (AIPercentResult, error)

ComputeAIPercentFromDiff computes attribution from a git diff against agent events in a time window. Returns a rich AIPercentResult with per-provider breakdown and tier diagnostics for commit trailers.

Returns ErrNoEventsInWindow when no events exist, allowing the caller to attempt ingestion and retry.

type AuditReadiness added in v0.6.0

type AuditReadiness struct {
	Policy      string             `json:"policy"`
	Manifest    ReadinessComponent `json:"manifest"`
	Attribution ReadinessComponent `json:"attribution"`
	Provenance  ReadinessComponent `json:"provenance"`
	Sync        ReadinessComponent `json:"sync"`
	AuditReady  bool               `json:"audit_ready"`
}

AuditReadiness is the audit-readiness verdict for one checkpoint. Checkpoint completion means the immutable core snapshot exists; audit readiness means the required derived evidence is available.

func EvaluateAuditReadiness added in v0.6.0

func EvaluateAuditReadiness(ctx context.Context, h *sqlstore.Handle, semDir string, cp sqldb.Checkpoint, policy ReadinessPolicy) AuditReadiness

EvaluateAuditReadiness derives a checkpoint verdict from stored evidence.

type BackfillResult

type BackfillResult struct {
	Uploaded int
	Skipped  int
	Failed   bool   // true if the batch stopped on a retryable error
	Reason   string // human-readable reason for failure
	Done     bool   // true if backfill is now complete
}

BackfillResult summarizes one run of the attribution backfill loop.

func DrainBackfillBatch

func DrainBackfillBatch(ctx context.Context, repoRoot, connectedRepoID string, limit int) BackfillResult

DrainBackfillBatch runs up to limit replay pushes and updates backfill state.

type BlameInput

type BlameInput struct {
	RepoPath string // path to the git repository (defaults to ".")
	Ref      string // commit hash or checkpoint ID/prefix
}

BlameInput holds the parameters for a blame request.

type BlockedCheckpointInfo added in v0.6.0

type BlockedCheckpointInfo struct {
	CheckpointID string `json:"checkpoint_id"`
	Status       string `json:"status"`
	LastError    string `json:"last_error,omitempty"`
}

BlockedCheckpointInfo identifies the terminally failed checkpoint gating the repository's commit-linked queue.

type BrokerStatusInfo

type BrokerStatusInfo struct {
	ActiveRepos   int               `json:"active_repos"`
	InactiveRepos int               `json:"inactive_repos"`
	Repos         []broker.RepoInfo `json:"repos"`
}

type CheckpointKind

type CheckpointKind string
const (
	CheckpointManual   CheckpointKind = "manual"
	CheckpointAuto     CheckpointKind = "auto"
	CheckpointBaseline CheckpointKind = "baseline"
)

type CheckpointService

type CheckpointService struct{}

func NewCheckpointService

func NewCheckpointService() *CheckpointService

func (*CheckpointService) Create

type CommitMsgHookService

type CommitMsgHookService struct {
	RepoPath string
	// Registry is the hook-provider registry used by the
	// flushActiveSessions sweep that runs before commit-msg
	// attribution. Production callers must pass
	// providers.NewHookRegistry(); the commit-msg cobra command
	// does so. A nil Registry makes flushActiveSessions a no-op
	// (every per-session lookup returns nil and is skipped),
	// which is useful only for tests that intentionally exercise
	// the non-flush paths.
	Registry *hooks.Registry
}

func NewCommitMsgHookService

func NewCommitMsgHookService(repoPath string, registry *hooks.Registry) *CommitMsgHookService

func (*CommitMsgHookService) Run

func (s *CommitMsgHookService) Run(ctx context.Context, msgFile string) error

type ComputeAIPercentInput

type ComputeAIPercentInput struct {
	RepoRoot string
	RepoID   string
	Window   eventWindow // delta window (previous checkpoint, this checkpoint]
}

ComputeAIPercentInput holds parameters for the lightweight AI% computation.

type CreateCheckpointInput

type CreateCheckpointInput struct {
	RepoPath string
	Kind     CheckpointKind
	Trigger  string
	Message  string
}

type CreateCheckpointResult

type CreateCheckpointResult struct {
	CheckpointID string `json:"checkpoint_id"`
	RepositoryID string `json:"repository_id"`
	ManifestHash string `json:"manifest_hash"`
	FileCount    int    `json:"file_count"`
	TotalBytes   int64  `json:"total_bytes"`
	CreatedAt    int64  `json:"created_at"`
}

type DisableResult

type DisableResult struct {
	RepoRoot     string `json:"repo_root"`
	SemanticaDir string `json:"semantica_dir"`
}

type DisableService

type DisableService struct {
	// contains filtered or unexported fields
}

func NewDisableService

func NewDisableService(registry *hooks.Registry) *DisableService

NewDisableService constructs the disable-service with the given hook registry. The registry drives which providers get their repo-local hooks uninstalled during teardown. Production callers must pass providers.NewHookRegistry() (the disable cobra command does so); a nil registry causes the uninstall loop to be a no-op, leaving repo-local hook files in place. Treat nil as test-only.

func (*DisableService) Disable

func (s *DisableService) Disable(ctx context.Context, repoPath string) (*DisableResult, error)

type DrainStats added in v0.3.6

type DrainStats struct {
	// Processed counts markers that ran and were deleted.
	Processed int

	// Rejected counts markers dropped as unreadable or invalid.
	Rejected int

	// RunErrors counts markers left on disk after runner failure.
	RunErrors int

	// EarliestRetry is the soonest scheduled-retry time reported by a
	// runner, zero when none was reported.
	EarliestRetry time.Time

	// DeleteErrors counts markers whose work ran but could not be
	// removed.
	DeleteErrors int
}

DrainStats counts outcomes from one drain pass.

func DrainOnce added in v0.3.6

func DrainOnce(ctx context.Context, run MarkerRunner) (DrainStats, error)

DrainOnce processes the current marker set once. Broker-level failures stop the pass; per-marker failures are logged and kept in the returned stats.

func (DrainStats) Progress added in v0.3.6

func (s DrainStats) Progress() int

Progress returns the number of markers removed from the queue.

type EnableOptions

type EnableOptions struct {
	Force     bool
	Providers []string // selected provider names; nil = install all registered
}

type EnableResult

type EnableResult struct {
	RepoRoot           string   `json:"repo_root"`
	SemanticaDir       string   `json:"semantica_dir"`
	DBPath             string   `json:"db_path"`
	RepositoryID       string   `json:"repository_id,omitempty"`
	CheckpointID       string   `json:"checkpoint_id,omitempty"`
	WorkspaceTierTitle string   `json:"workspace_tier_title,omitempty"`
	UpdateAvailable    bool     `json:"update_available,omitempty"`
	LatestVersion      string   `json:"latest_version,omitempty"`
	UpdateDownloadURL  string   `json:"update_download_url,omitempty"`
	HooksInstalled     bool     `json:"hooks_installed"`
	Providers          []string `json:"providers,omitempty"`
}

type EnableService

type EnableService struct {
	// contains filtered or unexported fields
}

func NewEnableService

func NewEnableService(opts EnableServiceOptions) (*EnableService, error)

func (*EnableService) Enable

func (s *EnableService) Enable(ctx context.Context, opts EnableOptions) (*EnableResult, error)

type EnableServiceOptions

type EnableServiceOptions struct {
	RepoPath string
	// Registry contains the providers available for hook installation.
	Registry *hooks.Registry
}

type ErrLeaseHeld added in v0.6.0

type ErrLeaseHeld struct {
	CheckpointID string
	Until        time.Time
}

ErrLeaseHeld stops the queue until its head checkpoint's lease expires.

func (*ErrLeaseHeld) Error added in v0.6.0

func (e *ErrLeaseHeld) Error() string

type ErrRetryScheduled added in v0.6.0

type ErrRetryScheduled struct {
	CheckpointID string
	At           time.Time
	Cause        error // the transient failure, when one just occurred
}

ErrRetryScheduled stops the queue until a checkpoint is due. Cause is set when the retry follows a fresh transient failure.

func (*ErrRetryScheduled) Error added in v0.6.0

func (e *ErrRetryScheduled) Error() string

func (*ErrRetryScheduled) Unwrap added in v0.6.0

func (e *ErrRetryScheduled) Unwrap() error

type ExplainInput

type ExplainInput struct {
	RepoPath string
	Ref      string // commit hash or prefix
}

type ExplainResult

type ExplainResult struct {
	CommitHash    string `json:"commit_hash"`
	CheckpointID  string `json:"checkpoint_id"`
	CommitSubject string `json:"commit_subject"`
	// Git facts
	FilesChanged int         `json:"files_changed"`
	LinesAdded   int         `json:"lines_added"`
	LinesDeleted int         `json:"lines_deleted"`
	TopFiles     []FileDelta `json:"top_files"`
	// Attribution facts
	AIPercentage   float64 `json:"ai_percentage"`
	AILines        int     `json:"ai_lines"`
	HumanLines     int     `json:"human_lines"`
	FilesWithAI    int     `json:"files_with_ai"`
	FilesHumanOnly int     `json:"files_human_only"`
	// Session facts
	SessionCount int              `json:"session_count"`
	RootSessions int              `json:"root_sessions"`
	Subagents    int              `json:"subagents"`
	Sessions     []SessionSummary `json:"sessions,omitempty"`
	// Transcript (for --generate)
	Transcript []TranscriptEventSummary `json:"transcript,omitempty"`
	// Persisted summary (from --generate)
	Summary *NarrativeResultJSON `json:"summary,omitempty"`
}

type ExplainService

type ExplainService struct{}

func NewExplainService

func NewExplainService() *ExplainService

func (*ExplainService) Explain

func (*ExplainService) SaveSummary

func (s *ExplainService) SaveSummary(ctx context.Context, in SaveSummaryInput) error

SaveSummary persists a generated summary to the database.

type FileAttribution

type FileAttribution struct {
	Path                string `json:"path"`
	Operation           string `json:"operation,omitempty"`      // created, edited, deleted
	Classification      string `json:"classification,omitempty"` // ai, human (coarse pipeline flag)
	AIExactLines        int    `json:"ai_exact_lines"`
	AIFormattedLines    int    `json:"ai_formatted_lines"`
	AIModifiedLines     int    `json:"ai_modified_lines"`
	AIProviderOnlyLines int    `json:"ai_provider_only_lines,omitempty"` // provider-touch only; excluded from AILines/AIPercent
	// Tool-delta subsets of the exact and formatted counts.
	AIDeltaExactLines     int      `json:"ai_delta_exact_lines,omitempty"`
	AIDeltaFormattedLines int      `json:"ai_delta_formatted_lines,omitempty"`
	AILines               int      `json:"ai_lines,omitempty"` // exact + formatted + modified
	HumanLines            int      `json:"human_lines"`
	TotalLines            int      `json:"total_lines"`
	DeletedNonBlank       int      `json:"deleted_non_blank"`          // deleted non-blank lines (not attributed, display only)
	AIPercent             float64  `json:"ai_percentage"`              // (exact + formatted + modified) / total * 100
	EvidenceClass         string   `json:"evidence_class,omitempty"`   // primary (strongest) evidence class for this file
	EvidenceClasses       []string `json:"evidence_classes,omitempty"` // every contributing evidence class, strongest first
	Providers             []string `json:"providers,omitempty"`        // providers involved in this file; mirrors FileChange.Providers
}

FileAttribution holds per-file line attribution counts using four deterministic categories:

  • AI-Exact: line matches AI tool output (trimmed)
  • AI-Formatted: matches after whitespace normalization (formatter/linter)
  • AI-Modified: in a contiguous group overlapping AI output, but changed
  • Human: no overlap with any AI output

Operation and Classification mirror what the commit's FilesCreated/ FilesEdited/FilesDeleted arrays already carry, surfaced on each file so callers do not need to cross-reference the three arrays. Classification is the coarse AI-touched flag from the attribution pipeline, not a majority-authorship verdict.

type FileChange

type FileChange struct {
	Path string `json:"path"`
	AI   bool   `json:"ai"`
	// Providers lists the providers involved in this file. Ordering is by
	// matched line count when available, then provider-touch evidence or fallback.
	Providers []string `json:"providers,omitempty"`
}

FileChange records a file that was created, edited, or deleted in a commit, along with whether the change was performed by an AI agent.

type FileDelta

type FileDelta struct {
	Path       string  `json:"path"`
	Added      int     `json:"added"`       // added non-blank lines (same basis as attribution)
	Deleted    int     `json:"deleted"`     // deleted non-blank lines
	TotalLines int     `json:"total_lines"` // equals Added (added non-blank lines)
	AILines    int     `json:"ai_lines"`
	HumanLines int     `json:"human_lines"`
	AIPercent  float64 `json:"ai_percentage"`
}

type LastCheckpointInfo

type LastCheckpointInfo struct {
	ID        string `json:"id"`
	CreatedAt int64  `json:"created_at"`
	Kind      string `json:"kind"`
	Status    string `json:"status"`
	Message   string `json:"message,omitempty"`
	Commit    string `json:"commit,omitempty"`
}

type ListCheckpointsInput

type ListCheckpointsInput struct {
	RepoPath string
	Limit    int64
}

type ListCheckpointsResult

type ListCheckpointsResult struct {
	RepoRoot string
	Items    []ListedCheckpoint
}

type ListService

type ListService struct{}

func NewListService

func NewListService() *ListService

func (*ListService) ListCheckpoints

type ListedCheckpoint

type ListedCheckpoint struct {
	ID           string
	CreatedAt    int64
	Kind         string
	Trigger      string
	Message      string
	ManifestHash string
	SizeBytes    *int64

	CommitHash    string
	CommitSubject string
}

type MarkerRunner added in v0.3.6

type MarkerRunner func(ctx context.Context, in WorkerInput) error

MarkerRunner executes one marker.

func DefaultMarkerRunner added in v0.3.6

func DefaultMarkerRunner(registry *hooks.Registry) MarkerRunner

DefaultMarkerRunner returns the production marker runner backed by the given hook registry. Production callers must pass providers.NewHookRegistry() (the worker cobra command does so). A nil registry produces a runner that skips reconciliation silently. This is useful only for tests that exercise the drain loop without provider wiring.

type NarrativeResultJSON

type NarrativeResultJSON struct {
	Title     string   `json:"title"`
	Intent    string   `json:"intent"`
	Outcome   string   `json:"outcome"`
	Learnings []string `json:"learnings"`
	Friction  []string `json:"friction"`
	OpenItems []string `json:"open_items"`
	Keywords  []string `json:"keywords"`
}

NarrativeResultJSON is the persisted form of an LLM-generated playbook.

type PendingProvenanceInfo added in v0.5.2

type PendingProvenanceInfo struct {
	Count                int64 `json:"count"`
	SinceLastCommitCount int64 `json:"since_last_commit_count,omitempty"`
	HasLastCommit        bool  `json:"has_last_commit"`
	LastCommitAt         int64 `json:"last_commit_at,omitempty"`
}

PendingProvenanceInfo summarizes local turn provenance waiting to upload.

func PendingProvenance added in v0.5.2

func PendingProvenance(ctx context.Context, repoRoot string) (*PendingProvenanceInfo, error)

PendingProvenance counts local provenance manifests that are ready or queued for upload. Count covers all pending local manifests; when a commit-linked checkpoint exists, SinceLastCommitCount covers manifests created after the most recent such checkpoint.

type PostCommitResult

type PostCommitResult struct {
	RepoRoot     string
	CommitHash   string
	CheckpointID string
	Linked       bool // false means "nothing to link" or already linked
}

type PostCommitService

type PostCommitService struct{}

func NewPostCommitService

func NewPostCommitService() *PostCommitService

func (*PostCommitService) HandlePostCommit

func (s *PostCommitService) HandlePostCommit(ctx context.Context, repoPath string) (*PostCommitResult, error)

type PreCommitService

type PreCommitService struct{}

func NewPreCommitService

func NewPreCommitService() *PreCommitService

func (*PreCommitService) HandlePreCommit

func (s *PreCommitService) HandlePreCommit(ctx context.Context, repoPath string) error

type ProviderAttribution

type ProviderAttribution struct {
	Provider          string
	Model             string // empty if unknown
	AILines           int    // line-level evidence
	ProviderOnlyLines int    // provider-touch only, excluded from headline
}

ProviderAttribution is the per-provider counterpart to the headline counts. AILines is line-level evidence only (exact, formatted, modified). ProviderOnlyLines is the provider-touch sidecar and is excluded from the headline AILines / Percent.

type PushAction

type PushAction string

PushAction classifies the outcome of a push attempt.

const (
	PushUploaded PushAction = "uploaded" // remote upsert succeeded
	PushRetry    PushAction = "retry"    // transient remote/auth failure
	PushSkip     PushAction = "skip"     // local failure or permanently non-retryable
)

type PushResult

type PushResult struct {
	CommitHash   string
	CheckpointID string
	Action       PushAction
	AIPercentage float64
	Err          error
}

PushResult is the structured outcome of tryPushAttribution.

type ReadinessComponent added in v0.6.0

type ReadinessComponent struct {
	State  ReadinessState `json:"state"`
	Reason string         `json:"reason,omitempty"`
}

ReadinessComponent is one evidence component's state with an optional human-readable reason.

type ReadinessPolicy added in v0.6.0

type ReadinessPolicy string

ReadinessPolicy identifies the evidence requirements used for a verdict.

const (
	// PolicyLocal evaluates local evidence only; sync is never
	// required.
	PolicyLocal ReadinessPolicy = "local"

	// PolicyHosted additionally requires hosted sync evidence.
	PolicyHosted ReadinessPolicy = "hosted"
)

type ReadinessState added in v0.6.0

type ReadinessState string

ReadinessState describes the availability of one evidence component.

const (
	ReadinessNotRequired ReadinessState = "not_required"
	ReadinessPending     ReadinessState = "pending"
	ReadinessReady       ReadinessState = "ready"
	ReadinessFailed      ReadinessState = "failed"
	ReadinessUnknown     ReadinessState = "unknown"
)

type RecentSessionInfo

type RecentSessionInfo struct {
	SessionID    string `json:"session_id"`
	Provider     string `json:"provider"`
	StartedAt    int64  `json:"started_at"`
	LastEventAt  int64  `json:"last_event_at"`
	StepCount    int64  `json:"step_count"`
	TokensIn     int64  `json:"tokens_in"`
	TokensOut    int64  `json:"tokens_out"`
	TokensCached int64  `json:"tokens_cached,omitempty"`
}

type RepoLockInfo added in v0.6.0

type RepoLockInfo struct {
	PID          int    `json:"pid"`
	AcquiredAt   int64  `json:"acquired_at"` // unix ms
	CheckpointID string `json:"checkpoint_id,omitempty"`
}

RepoLockInfo is diagnostic metadata; the file lock is authoritative.

func ReadRepoLockInfo added in v0.6.0

func ReadRepoLockInfo(path string) (RepoLockInfo, error)

ReadRepoLockInfo parses holder metadata, best-effort.

type RewindInput

type RewindInput struct {
	RepoPath      string
	CheckpointID  string
	NoSafety      bool
	Exact         bool // delete files not present in checkpoint set
	SafetyMessage string
}

type RewindResult

type RewindResult struct {
	RepoRoot           string `json:"repo_root"`
	CheckpointID       string `json:"checkpoint_id"`
	SafetyCheckpointID string `json:"safety_checkpoint_id,omitempty"`
	FilesRestored      int    `json:"files_restored"`
	FilesDeleted       int    `json:"files_deleted"`
}

type RewindService

type RewindService struct{}

func NewRewindService

func NewRewindService() *RewindService

func (*RewindService) Rewind

func (s *RewindService) Rewind(ctx context.Context, in RewindInput) (*RewindResult, error)

type SaveSummaryInput

type SaveSummaryInput struct {
	RepoPath     string
	CheckpointID string
	Summary      *NarrativeResultJSON
	Model        string
}

SaveSummaryInput contains the data needed to persist a generated summary.

type SessionDetailInput

type SessionDetailInput struct {
	RepoPath  string
	SessionID string // full UUID or prefix
}

SessionDetailInput holds parameters for a single-session lookup.

type SessionInfo

type SessionInfo struct {
	SessionID         string         `json:"session_id"`
	ProviderSessionID string         `json:"provider_session_id"`
	Provider          string         `json:"provider"`
	ParentSessionID   string         `json:"parent_session_id,omitempty"`
	StartedAt         string         `json:"started_at"`
	LastEventAt       string         `json:"last_event_at"`
	LastEventAtMs     int64          `json:"-"` // unix millis, for relative time formatting
	StepCount         int64          `json:"step_count"`
	ToolCallCount     int64          `json:"tool_call_count"`
	TokensIn          int64          `json:"tokens_in"`
	TokensOut         int64          `json:"tokens_out"`
	TokensCached      int64          `json:"tokens_cached,omitempty"`
	Children          []*SessionInfo `json:"children,omitempty"`
}

type SessionListInput

type SessionListInput struct {
	RepoPath string
	Limit    int64
	All      bool // include sessions with 0 events
}

type SessionService

type SessionService struct{}

func NewSessionService

func NewSessionService() *SessionService

func (*SessionService) GetSession

GetSession resolves a session ID (prefix or full) and returns its stats.

func (*SessionService) ListSessions

type SessionSummary

type SessionSummary struct {
	SessionID     string `json:"session_id"`
	Provider      string `json:"provider"`
	IsSubagent    bool   `json:"is_subagent,omitempty"`
	StepCount     int64  `json:"step_count"`
	ToolCallCount int64  `json:"tool_call_count"`
	TokensIn      int64  `json:"tokens_in"`
	TokensOut     int64  `json:"tokens_out"`
	TokensCached  int64  `json:"tokens_cached,omitempty"`
}

type SessionTranscript

type SessionTranscript struct {
	SessionID         string            `json:"session_id"`
	ProviderSessionID string            `json:"provider_session_id"`
	Provider          string            `json:"provider"`
	Events            []TranscriptEvent `json:"events"`
}

type SessionTreeResult

type SessionTreeResult struct {
	Roots []*SessionInfo `json:"sessions"`
	Total int            `json:"total"`
}

SessionTreeResult holds the tree-structured session list.

type ShowCheckpointFile

type ShowCheckpointFile struct {
	Path string `json:"path"`
	Blob string `json:"blob"`
	Size int64  `json:"size"`
}

type ShowCheckpointInput

type ShowCheckpointInput struct {
	RepoPath     string
	CheckpointID string
}

type ShowCheckpointResult

type ShowCheckpointResult struct {
	RepoRoot      string               `json:"repo_root"`
	CheckpointID  string               `json:"checkpoint_id"`
	CommitHash    string               `json:"commit_hash,omitempty"`
	CreatedAtUnix int64                `json:"created_at_unix"`
	CreatedAt     string               `json:"created_at"` // RFC3339
	Kind          string               `json:"kind"`
	Trigger       string               `json:"trigger,omitempty"`
	Message       string               `json:"message,omitempty"`
	ManifestHash  string               `json:"manifest_hash"`
	Bytes         *int64               `json:"bytes,omitempty"`
	FileCount     int                  `json:"file_count"`
	Files         []ShowCheckpointFile `json:"files"`
}

type ShowService

type ShowService struct{}

func NewShowService

func NewShowService() *ShowService

func (*ShowService) ShowCheckpoint

type StatusInput

type StatusInput struct {
	RepoPath string
}

type StatusResult

type StatusResult struct {
	Enabled bool `json:"enabled"`
	// StaleReason is set when local state exists but cannot receive
	// broker-routed events.
	StaleReason        string                 `json:"stale_reason,omitempty"`
	RepoRoot           string                 `json:"repo_root"`
	Connected          bool                   `json:"connected"`
	HasRemote          bool                   `json:"has_remote"`
	Endpoint           string                 `json:"endpoint"`
	RepoProvider       string                 `json:"repo_provider"`
	WorkspaceTierTitle string                 `json:"workspace_tier_title,omitempty"`
	UpdateAvailable    bool                   `json:"update_available,omitempty"`
	LatestVersion      string                 `json:"latest_version,omitempty"`
	UpdateDownloadURL  string                 `json:"update_download_url,omitempty"`
	AutoPlaybook       bool                   `json:"auto_playbook"`
	GitTrailers        bool                   `json:"git_trailers"`
	LastCheckpoint     *LastCheckpointInfo    `json:"last_checkpoint,omitempty"`
	BlockedBy          *BlockedCheckpointInfo `json:"blocked_by,omitempty"`
	AuditReadiness     *AuditReadiness        `json:"audit_readiness,omitempty"`
	RecentSessions     []RecentSessionInfo    `json:"recent_sessions,omitempty"`
	AITrend            []AITrendPoint         `json:"ai_trend,omitempty"`
	PlaybookCount      int64                  `json:"playbook_count"`
	Providers          []string               `json:"providers"`
	PendingProvenance  *PendingProvenanceInfo `json:"pending_provenance,omitempty"`
	Broker             *BrokerStatusInfo      `json:"broker,omitempty"`
}

type StatusService

type StatusService struct{}

func NewStatusService

func NewStatusService() *StatusService

func (*StatusService) Status

func (s *StatusService) Status(ctx context.Context, in StatusInput) (*StatusResult, error)

type SuggestInput

type SuggestInput struct {
	RepoPath string
}

type SuggestPRInput

type SuggestPRInput struct {
	RepoPath string
	Base     string // base branch; empty means auto-detect
}

type SuggestPRResult

type SuggestPRResult struct {
	Title    string `json:"title"`
	Body     string `json:"body"`
	Provider string `json:"provider,omitempty"`
	Model    string `json:"model,omitempty"`
	Dirty    bool   `json:"dirty,omitempty"` // true if working tree had uncommitted changes
}

type SuggestPRService

type SuggestPRService struct {
	// contains filtered or unexported fields
}

func NewSuggestPRService

func NewSuggestPRService(writers *llm.WriterRegistry) *SuggestPRService

NewSuggestPRService constructs the PR-suggestion service. The writer registry is a required dependency.

func (*SuggestPRService) SuggestPR

type SuggestResult

type SuggestResult struct {
	Message  string `json:"message"`
	Provider string `json:"provider,omitempty"`
	Model    string `json:"model,omitempty"`
}

type SuggestService

type SuggestService struct {
	// contains filtered or unexported fields
}

func NewSuggestService

func NewSuggestService(writers *llm.WriterRegistry) *SuggestService

NewSuggestService constructs the commit-message suggestion service. The writer registry is a required dependency; production callers pass providers.NewWriterRegistry().

func (*SuggestService) Suggest

type TidyAction

type TidyAction struct {
	Category string `json:"category"`
	ID       string `json:"id"`
	Detail   string `json:"detail"`
}

TidyAction describes one reported cleanup item.

type TidyInput

type TidyInput struct {
	RepoPath string
	Apply    bool
}

type TidyResult

type TidyResult struct {
	DryRun               bool         `json:"dry_run"`
	BrokerEntriesPruned  int          `json:"broker_entries_pruned"`
	CaptureStatesRemoved int          `json:"capture_states_removed"`
	CheckpointsMarked    int          `json:"checkpoints_marked_failed"`
	ToolWindowsRecovered int          `json:"tool_windows_recovered,omitempty"`
	ToolWindowsRemoved   int          `json:"tool_windows_removed,omitempty"`
	TombstonesRemoved    int          `json:"tombstones_removed,omitempty"`
	Errors               int          `json:"errors,omitempty"`
	Actions              []TidyAction `json:"actions,omitempty"`
}

type TidyService

type TidyService struct{}

func NewTidyService

func NewTidyService() *TidyService

func (*TidyService) Tidy

func (s *TidyService) Tidy(ctx context.Context, in TidyInput) (*TidyResult, error)

type TranscriptEvent

type TranscriptEvent struct {
	EventID           string `json:"event_id"`
	SessionID         string `json:"session_id"`
	Provider          string `json:"provider,omitempty"`
	Ts                int64  `json:"ts"`
	TsISO             string `json:"ts_iso"`
	Kind              string `json:"kind"`
	Role              string `json:"role,omitempty"`
	RoleUpper         string `json:"role_upper,omitempty"`
	ToolName          string `json:"tool_name,omitempty"`
	FilePath          string `json:"file_path,omitempty"`
	FileOp            string `json:"file_op,omitempty"`
	HasThinking       bool   `json:"has_thinking,omitempty"`
	ToolUsesJSON      string `json:"tool_uses,omitempty"`
	TokensIn          int64  `json:"tokens_in,omitempty"`
	TokensOut         int64  `json:"tokens_out,omitempty"`
	TokensCacheRead   int64  `json:"tokens_cache_read,omitempty"`
	TokensCacheCreate int64  `json:"tokens_cache_create,omitempty"`
	Summary           string `json:"summary,omitempty"`
	ProviderEventID   string `json:"provider_event_id,omitempty"`
	PayloadHash       string `json:"payload_hash,omitempty"`
	Payload           string `json:"payload,omitempty"` // only when Raw=true
}

type TranscriptEventSummary

type TranscriptEventSummary struct {
	Role     string `json:"role"`
	Summary  string `json:"summary,omitempty"`
	ToolName string `json:"tool_name,omitempty"`
	FilePath string `json:"file_path,omitempty"`
}

TranscriptEventSummary is a lightweight event for the condensed transcript.

type TranscriptMeta

type TranscriptMeta struct {
	CheckpointID string `json:"checkpoint_id"`
	CommitHash   string `json:"commit_hash,omitempty"`
	SessionCount int64  `json:"session_count"`
}

type TranscriptService

type TranscriptService struct{}

func NewTranscriptService

func NewTranscriptService() *TranscriptService

func (*TranscriptService) Transcripts

Transcripts is the polymorphic entry point: resolves Ref as either a checkpoint or session ID, then delegates to the appropriate method.

func (*TranscriptService) TranscriptsForCheckpoint

func (*TranscriptService) TranscriptsForSession

TranscriptsForSession loads the transcript for a specific session by ID.

type TranscriptsForCheckpointInput

type TranscriptsForCheckpointInput struct {
	RepoPath     string
	CheckpointID string
	Raw          bool   // if true, load payload JSON from blob store
	Verbose      bool   // reserved for CLI formatting; included for symmetry
	Cumulative   bool   // if true, show all events up to checkpoint; default is delta (since previous checkpoint)
	BySession    bool   // if true, group events by session
	SessionID    string // if set, filter to a specific session
	Commit       bool   // if true, filter to sessions that touched files in the commit diff
}

type TranscriptsForCheckpointResult

type TranscriptsForCheckpointResult struct {
	Meta     TranscriptMeta      `json:"meta"`
	Events   []TranscriptEvent   `json:"events"`
	Sessions []SessionTranscript `json:"sessions,omitempty"`
}

type TranscriptsForSessionInput

type TranscriptsForSessionInput struct {
	RepoPath  string
	SessionID string
	Raw       bool
}

TranscriptsForSessionInput holds parameters for session-first transcript access.

type TranscriptsInput

type TranscriptsInput struct {
	RepoPath        string
	Ref             string
	ForceCheckpoint bool
	ForceSession    bool
	// Checkpoint-mode flags (ignored/invalid in session mode).
	Raw             bool
	Verbose         bool
	Cumulative      bool
	BySession       bool
	FilterSessionID string
	Commit          bool
}

TranscriptsInput is the polymorphic entry point. Ref is resolved as a checkpoint or session ID (prefix matching). ForceCheckpoint / ForceSession bypass auto-resolution.

type TranscriptsResult

type TranscriptsResult struct {
	ResolvedAs string                          `json:"resolved_as"` // "checkpoint" or "session"
	Checkpoint *TranscriptsForCheckpointResult `json:"checkpoint,omitempty"`
	Session    *SessionTranscript              `json:"session,omitempty"`
}

TranscriptsResult wraps the output from either resolution path.

type WorkerInput

type WorkerInput struct {
	CheckpointID string
	CommitHash   string // optional, for logging
	RepoRoot     string
}

type WorkerService

type WorkerService struct {
	// contains filtered or unexported fields
}

func NewWorkerService

func NewWorkerService(registry *hooks.Registry) *WorkerService

NewWorkerService constructs the worker with the given hook registry. The registry drives reconciliation of active capture sessions; production callers must pass providers.NewHookRegistry() (the worker cobra command does so). A nil registry makes reconciliation a no-op: every per-session provider lookup returns nil and is skipped. This is useful only for tests that intentionally exercise the non-reconcile paths.

func (*WorkerService) ResolveAndRetryCheckpoint added in v0.6.0

func (s *WorkerService) ResolveAndRetryCheckpoint(ctx context.Context, repoRoot, idOrPrefix string) (string, error)

ResolveAndRetryCheckpoint resolves a checkpoint ID prefix within the repository and retries it via RetryCheckpoint.

func (*WorkerService) RetryCheckpoint added in v0.6.0

func (s *WorkerService) RetryCheckpoint(ctx context.Context, repoRoot, checkpointID string) error

RetryCheckpoint resets a terminally failed checkpoint and drains its repository. The wake-up marker is written before the database reset so a pending checkpoint is never left without a future drain.

func (*WorkerService) Run

func (s *WorkerService) Run(ctx context.Context, in WorkerInput) error

Run serializes and drains commit-linked work for one repository. The requested checkpoint is a wake-up signal, not a direct claim.

Directories

Path Synopsis
Package handoff assembles a redacted, provenance-rich markdown bundle from an active Semantica capture session so a fresh agent session can pick up where the previous one left off without re-reading the original transcript.
Package handoff assembles a redacted, provenance-rich markdown bundle from an active Semantica capture session so a fresh agent session can pick up where the previous one left off without re-reading the original transcript.

Jump to

Keyboard shortcuts

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