service

package
v0.5.4 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2026 License: MIT Imports: 49 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",
	"cursor":      ".cursor/hooks.json",
	"gemini":      ".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, with an optional idle linger between them. Markers that fail to run or delete are skipped for the rest of the invocation and retried by a later one.

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 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.

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 AnalysisOutcome added in v0.5.4

type AnalysisOutcome string

AnalysisOutcome reports whether local analysis completed or errored.

const (
	AnalysisAnalyzed AnalysisOutcome = "analyzed"
	AnalysisErrored  AnalysisOutcome = "errored"
)

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"`
	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
	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
}

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 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 for the given backfill. It opens the DB, loads backfill state, iterates candidates, and updates cursor/failure state as it goes. Safe to call from connect or worker.

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 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
	AfterTs  int64 // lower bound of delta window (exclusive)
	UpToTs   int64 // upper bound of delta window (inclusive, checkpoint created_at)
}

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

	// 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 is the hook-provider registry used by Enable.
	// Production callers must pass providers.NewHookRegistry()
	// (the enable cobra command does so). A nil Registry collapses
	// the production provider set to empty: validateProviderNames
	// rejects every name as unknown, and installProviderHooks
	// installs nothing, so `semantica enable` would succeed but
	// silently capture nothing. This is the explicit-registry
	// architecture's main footgun; documented as test-only so a
	// future direct caller treats it as a programming error rather
	// than a valid production path.
	Registry *hooks.Registry
}

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
	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 IntentGapUploadDeps added in v0.5.4

type IntentGapUploadDeps struct {
	HTTPClient *http.Client
	// BaseRef overrides automatic base-branch detection for manual analysis.
	BaseRef string
	// Endpoint defaults to auth.EffectiveEndpoint.
	Endpoint string
	// Token defaults to the current CLI access token.
	Token string
	// Now defaults to time.Now.
	Now func() time.Time
	// LLMRegistry defaults to the configured local AI fallback chain.
	LLMRegistry *llm.WriterRegistry
	// DeviceID defaults to the persisted installation identifier.
	DeviceID string
	// BundleAssembler defaults to the Git and lineage-backed assembler.
	BundleAssembler intentgap.BundleAssembler
	// Analyzer defaults to the local LLM analyzer.
	Analyzer intentgap.IntentGapAnalyzer
}

IntentGapUploadDeps provides optional collaborators for the upload service.

type IntentGapUploadResult added in v0.5.4

type IntentGapUploadResult struct {
	Status     IntentGapUploadStatus
	Reason     string
	PRNumber   int32
	HeadSHA    string
	UploadID   string
	ReceivedAt string
	Provider   string
	Model      string
	// Analysis is empty when execution stops before analysis.
	Analysis AnalysisOutcome
	// AnalysisReason contains a sanitized code for errored analysis.
	AnalysisReason string
}

IntentGapUploadResult records transport and analysis outcomes separately.

type IntentGapUploadService added in v0.5.4

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

IntentGapUploadService analyzes the current pull request and records the result.

func NewIntentGapUploadService added in v0.5.4

func NewIntentGapUploadService(deps IntentGapUploadDeps) *IntentGapUploadService

func (*IntentGapUploadService) Run added in v0.5.4

Run analyzes the current PR and records the result. Expected skip outcomes are returned in Status; infrastructure failures are returned as errors.

type IntentGapUploadStatus added in v0.5.4

type IntentGapUploadStatus string

IntentGapUploadStatus is the high-level outcome of an upload attempt.

const (
	UploadStatusUploaded  IntentGapUploadStatus = "uploaded"
	UploadStatusDuplicate IntentGapUploadStatus = "duplicate"
	UploadStatusSkipped   IntentGapUploadStatus = "skipped"
	UploadStatusError     IntentGapUploadStatus = "error"
)

type LastCheckpointInfo

type LastCheckpointInfo struct {
	ID        string `json:"id"`
	CreatedAt int64  `json:"created_at"`
	Kind      string `json:"kind"`
	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 PrePushResult added in v0.5.4

type PrePushResult struct {
	RepoRoot      string
	CurrentBranch string
	// Triggered is true when the current branch appeared in the pushed
	// refs AND the intent-gap setting was on. False covers every
	// no-op reason (Semantica disabled, intent-gap disabled, branch
	// not pushed, etc.).
	Triggered bool
	// Reason gives a one-line human-readable explanation, mirrored into
	// the activity log so `semantica doctor` can surface the last
	// trigger decision without re-running the hook.
	Reason string
}

PrePushResult records what the hook decided for tests and doctor output.

type PrePushService added in v0.5.4

type PrePushService struct{}

PrePushService handles git's pre-push hook.

git invokes pre-push with the remote name + URL as argv and one "<local-ref> <local-sha> <remote-ref> <remote-sha>" line per pushed ref on stdin. The hook is non-blocking: settings reads, file I/O, and command spawn errors are logged and do not fail the push.

func NewPrePushService added in v0.5.4

func NewPrePushService() *PrePushService

func (*PrePushService) HandlePrePush added in v0.5.4

func (s *PrePushService) HandlePrePush(ctx context.Context, repoPath string, stdin io.Reader) (*PrePushResult, error)

HandlePrePush is the hook entry point.

Contract:

  • Always returns nil so Semantica does not block the push.
  • Decisions land in PrePushResult and the activity log.
  • When triggered, follow-up analysis runs outside the blocking hook path.

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 PushedRef added in v0.5.4

type PushedRef struct {
	LocalRef  string
	LocalSHA  string
	RemoteRef string
	RemoteSHA string
}

PushedRef is one parsed line of pre-push stdin.

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 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"`
	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"`
	AutoImplSummary    bool                   `json:"auto_implementation_summary"`
	GitTrailers        bool                   `json:"git_trailers"`
	LastCheckpoint     *LastCheckpointInfo    `json:"last_checkpoint,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"`
	ImplStale            int          `json:"implementations_stale,omitempty"`
	ImplConflicts        int          `json:"implementations_conflicts,omitempty"`
	ImplFailedObs        int          `json:"implementations_failed_observations,omitempty"`
	ImplObsPruned        int          `json:"implementations_observations_pruned,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) Run

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

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