worker

package
v0.25.2 Latest Latest
Warning

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

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

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

Documentation

Overview

Package worker provides background goroutine workers for the second-brain service. Workers are long-running and must be started via [Run] with a context that controls their lifetime.

Index

Constants

This section is empty.

Variables

View Source
var ErrRefetchNotSupported = errors.New("refetch not supported for this source")

ErrRefetchNotSupported is returned by a Refetcher when it cannot handle the given failure record. The worker treats this as a permanent skip (same behaviour as the pre-Refetcher debug-log skip) so that sources without a re-fetch capability do not regress.

Functions

func ExtractEntities

func ExtractEntities(ctx context.Context, client llm.Completer, doc *model.Document) ([]model.Entity, error)

ExtractEntities calls the LLM to extract named entities from doc and returns a slice of model.Entity values (Name + Type populated; ID and CreatedAt are zero-values — they are assigned by the store on upsert).

The call is BEST-EFFORT: when the LLM is disabled, the response cannot be parsed, or any other error occurs, an empty slice and a non-nil error are returned. Callers MUST treat this as a warning and proceed without entities.

Types

type ActionWriter added in v0.23.0

type ActionWriter interface {
	UpsertAction(ctx context.Context, a model.Action) error
	EnsureOpenStatus(ctx context.Context, identityKey string) error
}

ActionWriter persists extracted actions and their default open status. Declared here (Task 11) per the plan's dependency direction; reused unchanged by StructuralSignalWorker (Task 12, structural_signals.go) — both workers write the same actions table through the identical two methods.

type ClassificationDocumentStore added in v0.23.0

type ClassificationDocumentStore interface {
	// ListUnclassified returns up to limit active documents (sms/gmail/call)
	// that have never been tagged with retention.
	ListUnclassified(ctx context.Context, limit int, backfillDays int) ([]*model.Document, error)
	// ListLegacyForRecheck returns up to limit already retention-tagged
	// documents (any classifier value except "user") that have not yet been
	// gate-audited (classifier_gate_checked_at unset).
	ListLegacyForRecheck(ctx context.Context, limit int) ([]*model.Document, error)
	// MergeClassificationMetadata merges updates into a document's
	// metadata, refusing to touch classifier="user" documents.
	MergeClassificationMetadata(ctx context.Context, documentID uuid.UUID, updates map[string]any) error
	// IncrementClassificationAttempts records a failed classification
	// attempt, eventually excluding the document from future listings.
	IncrementClassificationAttempts(ctx context.Context, documentID uuid.UUID, attempts int) error
}

ClassificationDocumentStore is the document-store dependency of ClassificationWorker. *store.DocumentStore satisfies it.

type ClassificationGateEvaluator added in v0.23.0

type ClassificationGateEvaluator interface {
	Evaluate(ctx context.Context, doc *model.Document) (classify.Gate, error)
}

ClassificationGateEvaluator is the gate-evaluation dependency of ClassificationWorker, narrowed to an interface so tests can substitute a fixed-response fake instead of a real *classify.Evaluator (which needs a SenderLookup). A fresh instance MUST be constructed per tick — see classify.NewEvaluator's doc comment on its per-tick cache.

type ClassificationGateEvaluatorFactory added in v0.23.0

type ClassificationGateEvaluatorFactory func() ClassificationGateEvaluator

ClassificationGateEvaluatorFactory constructs a ClassificationGateEvaluator for a single tick. Defaults to classify.NewEvaluator wrapping the configured SenderLookup.

type ClassificationJevClassifier added in v0.23.0

type ClassificationJevClassifier interface {
	JevEnabled() bool
	ClassifyDeterministic(gate classify.Gate) *classify.Result
	ClassifyWithJev(ctx context.Context, doc *model.Document, gate classify.Gate) (*classify.Result, int, error)
}

ClassificationJevClassifier is the classify.Classifier dependency of ClassificationWorker, narrowed to an interface for testability.

type ClassificationWorker added in v0.23.0

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

ClassificationWorker is a background worker that tags SMS/Gmail/call documents with a segment/retention classification (rule-based where possible, Jev-based otherwise), and separately re-audits legacy (pre-worker) tags against the deterministic Gate.

See internal/classify's package doc for the Gate's asymmetric design and internal/jev for the TypeSafe Jev client this worker calls through Classifier.

func NewClassificationWorker added in v0.23.0

func NewClassificationWorker(cfg ClassificationWorkerConfig) *ClassificationWorker

NewClassificationWorker constructs a ClassificationWorker from cfg. Panics when required fields are nil (programming error).

func (*ClassificationWorker) Run added in v0.23.0

func (w *ClassificationWorker) Run(ctx context.Context)

Run starts the classification loop. It blocks until ctx is cancelled. When Jev is not configured, tagging still proceeds for documents the deterministic Gate fully decides (auth/ad/short-call rules) — only the Jev-requiring documents are skipped, one diagnostic log per tick via tick's own logging, not a permanent idle like EntityWorker/SummarizerWorker (whose entire pipeline is LLM-only).

type ClassificationWorkerConfig added in v0.23.0

type ClassificationWorkerConfig struct {
	// Store provides document listing and metadata write-back.
	Store ClassificationDocumentStore
	// Classifier performs the deterministic/Jev classification decision.
	Classifier ClassificationJevClassifier
	// NewEvaluator constructs a fresh gate evaluator for each tick. Required.
	NewEvaluator ClassificationGateEvaluatorFactory
	// Interval controls how often the worker polls. Defaults to 10 minutes.
	Interval time.Duration
	// BatchSize is the number of documents processed per tick (across both
	// the unclassified and legacy-recheck queues combined). Defaults to 50.
	BatchSize int
	// BackfillDays restricts ListUnclassified to documents collected within
	// the last N days. 0 (default) means no limit — the entire history is
	// eligible.
	BackfillDays int
	// RecheckLegacy enables the legacy-recheck queue. Defaults to true.
	RecheckLegacy bool
	// MaxCallsPerTick caps the number of Jev API calls made in a single
	// tick, shared across both queues. Defaults to 200.
	MaxCallsPerTick int
}

ClassificationWorkerConfig holds configuration for ClassificationWorker.

type Config

type Config struct {
	// FailureStore is required: the persistence layer for extraction failures.
	FailureStore FailureStore
	// DocStore is required: used to persist successfully re-extracted content.
	DocStore DocStore
	// Extractor is required: performs the actual text extraction from a file path.
	Extractor Extractor
	// Refetcher is optional: when non-nil it is used to re-download remote
	// binaries (e.g. Discord/Slack attachments) before extraction.
	// When nil (or when the Refetcher returns ErrRefetchNotSupported), remote
	// paths are skipped with a debug log — identical to the pre-Refetcher
	// behaviour.
	Refetcher Refetcher
	// Interval controls how often the worker polls for due failures.
	// Defaults to 1 minute when zero or negative.
	Interval time.Duration
	// BatchSize limits the number of failures processed per tick.
	// Defaults to 20 when zero or negative.
	BatchSize int
}

Config holds all configuration for ExtractionRetryWorker. Zero values for Interval and BatchSize are replaced with safe defaults.

type DocStore

type DocStore interface {
	Upsert(ctx context.Context, doc *model.Document) error
}

DocStore persists documents produced by successful re-extractions.

type Embedder

type Embedder interface {
	Enabled() bool
	Embed(ctx context.Context, text string) ([]float32, error)
}

Embedder generates embedding vectors for text. It is satisfied by *search.EmbedClient.

type EntityDocumentLister

type EntityDocumentLister interface {
	// ListWithoutEntities returns up to limit active documents whose
	// entities_processed_at column is NULL. Documents are ordered by
	// collected_at ASC so backfill progresses forward in time.
	ListWithoutEntities(ctx context.Context, limit int) ([]*model.Document, error)

	// MarkEntitiesProcessed sets entities_processed_at to now() for the
	// given document so it is not re-queued by ListWithoutEntities on the
	// next tick (issue #86).
	MarkEntitiesProcessed(ctx context.Context, documentID uuid.UUID) error
}

EntityDocumentLister is the read/write side of the document store required by EntityWorker.

type EntityLinker

type EntityLinker interface {
	// UpsertAndLinkEntities persists entities and links them to the document.
	UpsertAndLinkEntities(ctx context.Context, documentID uuid.UUID, entities []model.Entity) error
}

EntityLinker is the write side of the entity store required by EntityWorker.

type EntityWorker

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

EntityWorker is a background worker that extracts named entities from documents that have not yet been processed and persists them via EntityStore.

Extraction is BEST-EFFORT: LLM failures are logged as warnings and the document is left eligible for retry on the next tick. For documents where extraction succeeds (even with zero entities) or where entity linking fails, MarkEntitiesProcessed is called so the document is not re-queued indefinitely (issue #86).

func NewEntityWorker

func NewEntityWorker(cfg EntityWorkerConfig) *EntityWorker

NewEntityWorker constructs an EntityWorker from cfg. Panics when required fields are nil (programming error).

func (*EntityWorker) Run

func (w *EntityWorker) Run(ctx context.Context)

Run starts the entity extraction loop. It blocks until ctx is cancelled. When the LLM is not configured a single diagnostic log is emitted and the loop idles without processing any documents.

type EntityWorkerConfig

type EntityWorkerConfig struct {
	// Store provides both document listing and marking-processed.
	// Typically *store.DocumentStore satisfies this interface.
	Store EntityDocumentLister
	// Entities is the entity store (write side).
	Entities EntityLinker
	// LLM is the completion client used for extraction.
	LLM llm.Completer
	// Interval controls how often the worker polls. Defaults to 10 minutes.
	Interval time.Duration
	// BatchSize is the number of documents processed per tick. Defaults to 5.
	BatchSize int
}

EntityWorkerConfig holds configuration for EntityWorker.

type ExtractionLister added in v0.23.0

type ExtractionLister interface {
	ListPendingForExtraction(ctx context.Context, limit int) ([]*model.Document, error)
	MarkRelationsExtracted(ctx context.Context, documentID uuid.UUID) error
	MarkExtractionAttemptFailed(ctx context.Context, documentID uuid.UUID, attempts int, reason string, nextRetryAt time.Time) error
	MarkExtractionTerminal(ctx context.Context, documentID uuid.UUID, reason string) error
}

ExtractionLister is the read/write side of the document store required by ExtractionWorker. *store.DocumentStore satisfies this interface.

type ExtractionResult added in v0.23.0

type ExtractionResult struct {
	Entities  []model.Entity
	Relations []rawRelation
	Actions   []rawAction
}

ExtractionResult is the parsed output of one ExtractRelationsAndActions call.

func ExtractRelationsAndActions added in v0.23.0

func ExtractRelationsAndActions(ctx context.Context, client llm.Completer, doc *model.Document, userAddresses []string) (*ExtractionResult, error)

ExtractRelationsAndActions calls the LLM exactly once (spec §5.2). Configured account addresses are identity anchors, separate from untrusted document evidence. No graph edge is inferred from an action's counterpart.

type ExtractionRetryWorker

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

ExtractionRetryWorker periodically reads due failures from the extraction_failures table and re-runs extraction for each entry.

On success the failure record is deleted (via FailureStore.Resolve) and the extracted content is upserted into the document store.

On failure the failure record's attempt counter is incremented (via FailureStore.Record), backing off exponentially until the row is dead-lettered at 10 attempts.

Remote-source files (Slack attachments, Discord attachments, etc.) are handled as follows:

  • When Config.Refetcher is nil or returns ErrRefetchNotSupported, the record is skipped with a debug log (same as pre-Refetcher behaviour).
  • When Config.Refetcher successfully downloads the binary, extraction runs on the temp file; success resolves the record, failure increments attempts.

func New

func New(cfg Config) *ExtractionRetryWorker

New returns a configured ExtractionRetryWorker. It panics if any required dependency (FailureStore, DocStore, Extractor) is nil.

func (*ExtractionRetryWorker) Run

Run blocks until ctx is cancelled, processing retry batches at each tick. An initial batch is processed immediately on entry so that short-lived test contexts see at least one attempt.

type ExtractionWorker added in v0.23.0

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

ExtractionWorker runs a single structured LLM call per pending document to produce entity relations and candidate actions (spec §5.2). Deadline model (work/persist/bookkeeping budgets, detached writes) mirrors NoteEnrichmentWorker's — see that file's top-of-file comment for the production incident this shape exists to prevent; this worker adopts the same shape from day one.

func NewExtractionWorker added in v0.23.0

func NewExtractionWorker(cfg ExtractionWorkerConfig) *ExtractionWorker

NewExtractionWorker constructs an ExtractionWorker from cfg. Panics when required fields are nil (programming error) — mirrors NewNoteEnrichmentWorker.

func (*ExtractionWorker) Run added in v0.23.0

func (w *ExtractionWorker) Run(ctx context.Context)

Run blocks until ctx is cancelled (mirrors EntityWorker.Run / NoteEnrichmentWorker.Run).

type ExtractionWorkerConfig added in v0.23.0

type ExtractionWorkerConfig struct {
	Store         ExtractionLister
	Entities      RelationEntityResolver
	Relations     RelationWriter
	Actions       ActionWriter
	LLM           llm.Completer
	UserAddresses []string // config.UserEmailAddresses
	Interval      time.Duration
	BatchSize     int
	MaxAttempts   int
	RetryBackoff  []time.Duration
	LLMTimeout    time.Duration
}

ExtractionWorkerConfig holds configuration for ExtractionWorker.

type Extractor

type Extractor interface {
	ExtractFromPath(ctx context.Context, path string) (string, error)
}

Extractor re-extracts plain text from a file at the given absolute path. Implementations must not panic and must respect context cancellation.

The concrete adapter ([registryExtractor]) bridges this interface to the extractor.Registry type in internal/collector/extractor.

func NewRegistryExtractor

func NewRegistryExtractor(reg *extractor.Registry, timeout time.Duration) Extractor

NewRegistryExtractor returns an Extractor backed by the given extractor.Registry. Each extraction call is bounded by timeout; when timeout is zero, extractor.ExtractTimeout seconds are used.

type FailureStore

type FailureStore interface {
	DueForRetry(ctx context.Context, limit int) ([]store.ExtractionFailure, error)
	Record(ctx context.Context, f store.ExtractionFailure) error
	Resolve(ctx context.Context, sourceType, sourceID string) error
}

FailureStore manages extraction_failures rows.

type GraphProjectionSource added in v0.23.0

type GraphProjectionSource interface {
	ListRelationsAfter(ctx context.Context, afterID int64, limit int) ([]model.ProjectionRelation, error)
	ListMentionsAfter(ctx context.Context, afterDocumentID string, afterEntityID int64, limit int) ([]model.ProjectionMention, error)
}

GraphProjectionSource is the PostgreSQL read side. *store.GraphSource satisfies it.

type GraphProjectionWorker added in v0.23.0

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

GraphProjectionWorker mirrors ExtractionWorker's shape — a ticker driving serial batches, where an individual failure logs and returns instead of killing the worker.

The one invariant worth stating out loud: the watermark only advances after the corresponding batch has been written successfully. Advancing past a failed batch would lose those relations permanently, since nothing ever revisits ids below the watermark (outside the overlap window).

func NewGraphProjectionWorker added in v0.23.0

func NewGraphProjectionWorker(cfg GraphProjectionWorkerConfig) *GraphProjectionWorker

NewGraphProjectionWorker constructs a worker from cfg. Panics when required fields are nil (programming error) — mirrors NewExtractionWorker.

func (*GraphProjectionWorker) Run added in v0.23.0

Run blocks until ctx is cancelled (mirrors ExtractionWorker.Run).

type GraphProjectionWorkerConfig added in v0.23.0

type GraphProjectionWorkerConfig struct {
	Source    GraphProjectionSource
	Projector GraphProjector
	Interval  time.Duration
	BatchSize int
	Overlap   int64
	// ResetToken is compared against the token stored in the graph. Changing
	// it is the rebuild switch: the next tick wipes the graph and reprojects
	// from scratch. Empty on both sides (the default) means "never rebuild".
	ResetToken string
}

GraphProjectionWorkerConfig holds configuration for GraphProjectionWorker.

type GraphProjector added in v0.23.0

type GraphProjector interface {
	EnsureSchema(ctx context.Context) error
	State(ctx context.Context) (model.GraphProjectionState, error)
	UpsertRelations(ctx context.Context, rows []model.ProjectionRelation) error
	UpsertMentions(ctx context.Context, rows []model.ProjectionMention) error
	SetLastRelationID(ctx context.Context, id int64) error
	SetResetToken(ctx context.Context, token string) error
	Wipe(ctx context.Context) error
}

GraphProjector is the Neo4j write side. *graph.Projector satisfies it; the interface is declared here so tests can substitute a fake without a live database.

type InsightWriter added in v0.23.0

type InsightWriter interface {
	// SaveInsight persists an insight document with the given content,
	// deterministic sourceID and metadata. Returning a non-nil error means
	// the insight was NOT durably stored; the caller treats that as a failed
	// enrichment attempt so the note is retried.
	SaveInsight(ctx context.Context, content, sourceID string, metadata map[string]any) error
}

InsightWriter persists one derived insight document.

It is deliberately NOT a bare document upsert: an insight that exists as a row but has no chunks and no embedding vector is invisible to the /ask vector lane, i.e. an inference the system drew and can never surface again (spec §6.5). Implementations must persist the document AND its chunks AND request embeddings. insightSaver below is the production implementation; it delegates to note.Save, the same upsert+chunk+embed path used by POST /api/v1/notes.

func NewInsightSaver added in v0.23.0

func NewInsightSaver(docs note.DocumentUpserter, chunks note.ChunkWriter, embed note.Embedder) InsightWriter

NewInsightSaver returns the production InsightWriter, backed by note.Save. docs and chunks are required; embed may be nil, in which case the insight is stored and chunked but not embedded.

type NoteEnrichmentLister added in v0.23.0

type NoteEnrichmentLister interface {
	ListPendingNotes(ctx context.Context, limit int) ([]*model.Document, error)
	MarkNoteEnriched(ctx context.Context, documentID uuid.UUID, title string, metadata map[string]any) error
	MarkNoteEnrichmentAttemptFailed(ctx context.Context, documentID uuid.UUID, attempts int, reason string, nextRetryAt time.Time) error
	MarkNoteEnrichmentTerminal(ctx context.Context, documentID uuid.UUID, reason string) error
}

NoteEnrichmentLister is the read/write side of the document store required by NoteEnrichmentWorker. *store.DocumentStore satisfies this interface (Task 5).

ListPendingNotes is hard-scoped to source_type='note' in SQL. That filter — not anything in this file — is what makes insight-of-insight structurally impossible: a derived insight document can never be listed for enrichment, so an inference can never become the evidence for another inference (spec §3.2). Do not add an alternative intake path here.

type NoteEnrichmentResult added in v0.23.0

type NoteEnrichmentResult struct {
	Title    string
	Summary  string
	Tags     []string
	Entities []model.Entity
	Insights []NoteInsightCandidate
}

NoteEnrichmentResult is the parsed output of a single EnrichNote call.

func EnrichNote added in v0.23.0

func EnrichNote(ctx context.Context, client llm.Completer, doc *model.Document) (*NoteEnrichmentResult, error)

EnrichNote calls the LLM exactly once to produce the Organized layer and insight candidates for doc (spec §6.3 single-call requirement). Mirrors the shape of ExtractEntities (internal/worker/entity_extractor.go) — BEST-EFFORT: any error means the caller must treat this note as failed for this attempt and apply the retry policy (handleFailure).

doc is read-only here: only Title and Content are marshalled into the request, and nothing is written back to it (spec §3.1).

type NoteEnrichmentWorker added in v0.23.0

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

NoteEnrichmentWorker is a background worker that runs a single structured LLM call per pending note to generate the Organized layer (title/summary/ tags/entities) plus up to maxInsightsPerNote Inferred insight documents (spec §6.3).

Two invariants are load-bearing and must survive future edits:

  • The note's Content is never written. Only Title and Metadata are updated, via MarkNoteEnriched — whose signature has no content parameter (spec §3.1). The user's own words stay verbatim and remain distinguishable from anything a model produced about them.
  • Inferences are persisted as separate model.SourceInsight documents with provenance back to the note, never merged into the note itself (spec §3.2). Merged inferences would later be cited as if they were the user's own observations.

func NewNoteEnrichmentWorker added in v0.23.0

func NewNoteEnrichmentWorker(cfg NoteEnrichmentWorkerConfig) *NoteEnrichmentWorker

NewNoteEnrichmentWorker constructs a NoteEnrichmentWorker from cfg. Panics when required fields are nil (programming error).

func (*NoteEnrichmentWorker) MaxDetachedWriteDuration added in v0.23.0

func (w *NoteEnrichmentWorker) MaxDetachedWriteDuration() time.Duration

MaxDetachedWriteDuration is the longest a single note can keep running AFTER its caller's context has been cancelled. Only the persist and bookkeeping phases are detached (the LLM call is cancelled by the caller), so the bound is: one persist budget, plus the commit write, plus the failure write that a failed commit triggers.

cmd/collector/main.go derives its SIGTERM drain window from this value. If the drain were shorter, the process would exit while a detached status write was still in flight — which is precisely the write whose loss re-opens the unbounded-retry hole this worker's deadline model exists to close.

func (*NoteEnrichmentWorker) Run added in v0.23.0

func (w *NoteEnrichmentWorker) Run(ctx context.Context)

Run starts the note enrichment loop. It blocks until ctx is cancelled. When the LLM is not configured a single diagnostic log is emitted and the loop idles without processing any notes (mirrors EntityWorker.Run).

type NoteEnrichmentWorkerConfig added in v0.23.0

type NoteEnrichmentWorkerConfig struct {
	Store NoteEnrichmentLister
	// Insights persists derived insight documents with chunks + embeddings.
	// Production wiring: NewInsightSaver(documentStore, chunkStore, embedClient).
	Insights     InsightWriter
	Entities     EntityLinker // reused from entity_worker.go, same package
	LLM          llm.Completer
	Interval     time.Duration
	BatchSize    int
	MaxAttempts  int             // defaults to 3
	RetryBackoff []time.Duration // defaults to {1m, 5m, 30m}; see spec §13.2 — placeholder values, not final

	// LLMTimeout is the LLM client's OWN per-request HTTP timeout
	// (config.LLMTimeoutSeconds). Pass the same value used to build the
	// llm.Completer; the worker derives its work deadline from it
	// (LLMTimeout + noteEnrichmentWorkMargin) so the two can never drift into
	// the inverted relationship described above. Defaults to
	// defaultNoteEnrichmentLLMTimeout (120 s) when zero.
	LLMTimeout time.Duration

	// WorkTimeout optionally raises the per-note LLM work deadline. It is
	// clamped UP to LLMTimeout + noteEnrichmentWorkMargin — a caller cannot
	// configure a work budget tighter than the LLM client's own timeout.
	WorkTimeout time.Duration

	// PersistTimeout bounds the insight/entity writes for one note.
	// Defaults to defaultNoteEnrichmentPersistTimeout (30 s) when zero.
	PersistTimeout time.Duration

	// BookkeepingTimeout bounds a single enrichment-status write.
	// Defaults to defaultNoteEnrichmentBookkeepingTimeout (10 s) when zero.
	BookkeepingTimeout time.Duration
}

NoteEnrichmentWorkerConfig holds configuration for NoteEnrichmentWorker.

type NoteInsightCandidate added in v0.23.0

type NoteInsightCandidate struct {
	Content    string
	Confidence float64
	SourceSpan string
}

NoteInsightCandidate is one candidate inference returned by EnrichNote, not yet persisted as an insight document.

type PgStructuralSignalLister added in v0.23.0

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

PgStructuralSignalLister is the pgx-backed implementation of StructuralSignalLister. The SQL lives entirely in this file (rather than internal/store) per this task's scope: it talks to the documents table directly via a *pgxpool.Pool.

func NewPgStructuralSignalLister added in v0.23.0

func NewPgStructuralSignalLister(pool *pgxpool.Pool) *PgStructuralSignalLister

NewPgStructuralSignalLister returns a PgStructuralSignalLister backed by pool (typically (*store.Postgres).Pool()).

func (*PgStructuralSignalLister) ListLatestPerThread added in v0.23.0

func (l *PgStructuralSignalLister) ListLatestPerThread(ctx context.Context, limit int) ([]ThreadLatestMessage, error)

ListLatestPerThread implements StructuralSignalLister.

type RefetchResult

type RefetchResult struct {
	// LocalPath is the absolute path to the downloaded temp file.
	LocalPath string
	// Cleanup removes the temp file. It is always non-nil. Callers must call
	// Cleanup exactly once (typically via defer) after extraction.
	Cleanup func()
}

RefetchResult is returned by a successful Refetcher.Refetch call. The caller is responsible for invoking Cleanup after the temp file is no longer needed.

type Refetcher

type Refetcher interface {
	Refetch(ctx context.Context, f store.ExtractionFailure) (*RefetchResult, error)
}

Refetcher can re-download a remote binary given an ExtractionFailure record and return a temporary local file path for the extractor to process.

Implementations must:

  • Return ErrRefetchNotSupported when they cannot handle the given record.
  • Return a non-nil RefetchResult.Cleanup function on success.
  • Respect ctx cancellation.
  • Not panic.

type RelationEntityResolver added in v0.23.0

type RelationEntityResolver interface {
	EntityLinker
	UpsertEntity(ctx context.Context, name string, entityType model.EntityType) (int64, error)
}

RelationEntityResolver combines EntityLinker (reused from entity_worker.go, same package) with the single-entity resolve method the extraction worker also needs to turn an LLM-named relation/action counterpart into an entities.id before writing entity_relations/actions. *store.EntityStore already implements both methods.

type RelationWriter added in v0.23.0

type RelationWriter interface {
	UpsertEntityRelations(ctx context.Context, relations []model.EntityRelation) error
}

RelationWriter persists extracted entity relations.

type StructuralSignalLister added in v0.23.0

type StructuralSignalLister interface {
	ListLatestPerThread(ctx context.Context, limit int) ([]ThreadLatestMessage, error)
}

StructuralSignalLister provides the thread-grouped SQL query PgStructuralSignalLister implements. StructuralSignalWorker no longer calls it (see the worker's doc comment) — the interface remains so PgStructuralSignalLister keeps a typed contract and cmd/collector/main.go's wiring keeps compiling unchanged.

type StructuralSignalWorker added in v0.23.0

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

StructuralSignalWorker used to compute the "awaiting my reply" candidate action (spec §7.1) — the only structural signal this plan implemented.

2026-09-21 결정: 메일·SMS에 "답장하지 않았다"로 자동 생성되는 awaiting_my_reply 항목은 할일이 아니라 잡음이라고 판단해 더 이상 만들지 않기로 했다(migrations/038 이 기존에 열려 있던 행도 무시 처리한다). 이 워커가 만들던 신호는 그것 하나뿐이었 으므로, 생성 경로(스레드 조회 → 상대방/스레드 식별 → identity_key 계산 → UpsertAction/EnsureOpenStatus 호출)를 통째로 들어냈다 — Tick은 이제 아무 SQL도 실행하지 않고 아무 액션도 쓰지 않는다.

타입·생성자·Run 시그니처는 cmd/collector/main.go의 배선을 건드리지 않기 위해 그대로 남겨 두었다. 배선 자체(고루틴 기동 여부)를 정리하는 것은 이번 변경의 범위가 아니다.

func NewStructuralSignalWorker added in v0.23.0

func NewStructuralSignalWorker(cfg StructuralSignalWorkerConfig) *StructuralSignalWorker

NewStructuralSignalWorker constructs a StructuralSignalWorker from cfg. Panics when required fields are nil.

func (*StructuralSignalWorker) Run added in v0.23.0

Run blocks until ctx is cancelled. Tick is now a no-op (see the type's doc comment), so this loop no longer does any work — it is kept only so cmd/collector/main.go's existing goroutine wiring stays valid.

func (*StructuralSignalWorker) Tick added in v0.23.0

func (w *StructuralSignalWorker) Tick(_ context.Context) tickStats

Tick is exported (unlike ExtractionWorker's unexported tick) so tests can drive one pass deterministically without a ticker.

It performs no read and no write: the only signal this worker ever produced was awaiting_my_reply, and that generation path — thread listing, counterpart/thread-key resolution, identity_key construction, and the UpsertAction/EnsureOpenStatus calls — has been removed entirely (see the type's doc comment). Calling w.store.ListLatestPerThread here would only spend a database round trip on behalf of a candidate this worker will never write, so it is skipped rather than kept as dead instrumentation.

type StructuralSignalWorkerConfig added in v0.23.0

type StructuralSignalWorkerConfig struct {
	// Store lists the latest document per active thread. Typically
	// *PgStructuralSignalLister. Kept for wiring compatibility — Tick no
	// longer calls it (see StructuralSignalWorker's doc comment) — and is
	// still validated non-nil so a caller does not silently depend on a
	// zero-value StructuralSignalLister that would panic differently later.
	Store StructuralSignalLister
	// Actions is the write side of the actions table (reused from Task 11).
	Actions ActionWriter
	// UserAddresses is config.UserEmailAddresses. Unused now that Tick no
	// longer infers gmail direction, but kept so cmd/collector/main.go's
	// existing wiring does not need to change.
	UserAddresses []string
	// Interval controls how often the worker polls. Defaults to 10 minutes.
	Interval time.Duration
	// BatchSize is the number of threads inspected per tick. Defaults to 500.
	BatchSize int
	// Now supplies the current instant. Unused now that Tick writes nothing,
	// kept for wiring compatibility.
	Now func() time.Time
}

StructuralSignalWorkerConfig holds configuration for StructuralSignalWorker.

type SummarizerConfig

type SummarizerConfig struct {
	// Store is required: provides document read/write access.
	Store SummaryStore
	// LLM is required: the chat completion client.
	LLM llm.Completer
	// Embedder is optional: when non-nil and Enabled, summary embeddings are generated.
	Embedder Embedder
	// Interval controls how often the worker polls for unsummarized documents.
	// Defaults to 5 minutes when zero or negative.
	Interval time.Duration
	// BatchSize is the number of documents processed per tick.
	// Defaults to 10 when zero or negative.
	BatchSize int
	// DocTimeout bounds a single document's summarization work (LLM call +
	// optional embed + UpdateSummary write). Documents are independently
	// idempotent (UpdateSummary's WHERE title_summary IS NULL guard), so a
	// timed-out document simply stays unsummarized and is re-queued by
	// ListUnsummarized on a later tick.
	// Defaults to defaultDocTimeout (30 s) when zero or negative.
	DocTimeout time.Duration
	// Concurrency is the number of documents processed in parallel within a
	// single tick via a bounded worker pool. A failure or timeout on one
	// document never aborts the others.
	// Defaults to defaultConcurrency (5) when zero or negative.
	Concurrency int
	// BackfillEnabled controls whether the worker scans for pre-existing
	// unsummarized documents (WHERE title_summary IS NULL).
	// When false, ListUnsummarized is not called and only documents summarized
	// via an explicit call path are processed (future use).
	// Defaults to true when not set, preserving existing behaviour.
	// Set to false to skip the pre-existing backlog entirely
	// (SUMMARIZER_BACKFILL_ENABLED=false).
	BackfillEnabled *bool
}

SummarizerConfig holds configuration for SummarizerWorker.

type SummarizerWorker

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

SummarizerWorker periodically fetches documents without LLM summaries, generates title_summary and bullet_summary via an LLM, optionally embeds the summary text, and persists the result via UpdateSummary.

The worker respects the context lifetime: cancel the context to stop it. Per-tick scheduling (deciding whether to start a NEW document) is governed by the caller-supplied context. Documents already in flight run to completion (or their own docTimeout deadline) on a context detached from parent cancellation, so an in-progress UpdateSummary write is never truncated mid-write — see tick() for the detail. This keeps cmd/collector/main.go's shutdown drain window bounded by docTimeout regardless of BatchSize or Concurrency (#65, #170).

Concurrent instance safety relies on two mechanisms:

  1. UpdateSummary's idempotency guard (WHERE title_summary IS NULL) prevents two instances from overwriting the same summary (#64).
  2. SUMMARIZER_ENABLED=false allows operators to run a single dedicated summariser pod so that concurrent writes do not occur in the first place.

func NewSummarizerWorker

func NewSummarizerWorker(cfg SummarizerConfig) *SummarizerWorker

NewSummarizerWorker constructs a SummarizerWorker from cfg. Panics when cfg.Store or cfg.LLM is nil (programming error).

func (*SummarizerWorker) Run

func (w *SummarizerWorker) Run(ctx context.Context)

Run starts the summarizer loop. It blocks until ctx is cancelled. An initial tick runs immediately on entry so that pending documents are processed without waiting a full interval on first start.

When the LLM is not configured, a single startup log is emitted and the loop runs without processing any documents (#67).

type SummaryStore

type SummaryStore interface {
	// ListUnsummarized returns up to limit unsummarized active documents.
	// No transaction or row locks are acquired; callers must tolerate racing
	// concurrent instances. Duplicate work is prevented by UpdateSummary's
	// idempotency guard.
	ListUnsummarized(ctx context.Context, limit int) ([]*model.Document, error)

	// UpdateSummary persists the LLM summary for a single document.
	// Idempotent: a no-op when title_summary is already set. Must be safe to
	// call concurrently for different document IDs — SummarizerWorker calls
	// it from a bounded worker pool (#170).
	UpdateSummary(ctx context.Context, id uuid.UUID, titleSummary, bulletSummary string, summaryEmbedding []float32) error
}

SummaryStore is the persistence interface required by SummarizerWorker.

ListUnsummarized returns up to limit active documents whose title_summary is NULL (plain SELECT, no row locks). Concurrent instances may read the same row, but UpdateSummary's idempotency guard (WHERE title_summary IS NULL) ensures only the first writer persists a summary (#64).

type ThreadLatestMessage added in v0.23.0

type ThreadLatestMessage struct {
	DocumentID uuid.UUID
	SourceType string
	Metadata   map[string]any
	Title      string
	// EventAt is COALESCE(occurred_at, collected_at) — occurred_at is
	// nullable, and ingest order is a serviceable stand-in for event time
	// when the collector could not determine one.
	EventAt time.Time
}

ThreadLatestMessage is one row of StructuralSignalLister.ListLatestPerThread's result: the most recent document in a conversation thread. It used to also carry what StructuralSignalWorker needed to decide whether the thread was an "awaiting my reply" candidate (spec §7.1) and to describe it on an action card; that consumer is gone (see StructuralSignalWorker's doc comment), but the struct and the query below are read-only and still correct, so they are kept as-is rather than deleted along with their only caller.

type URLRefetcher

type URLRefetcher struct {
	// SlackBotToken is the Slack OAuth token used to authenticate file
	// downloads. Optional: when empty, Slack records are skipped.
	SlackBotToken string
	// contains filtered or unexported fields
}

URLRefetcher re-downloads remote attachments whose FilePath is an HTTP(S) URL. It handles two source types:

  • "discord": Discord CDN URLs (no authentication required; URLs are pre-signed and time-limited by Discord). On expiry the download will return an HTTP error and the worker will increment the attempt counter.

  • "slack": Slack file URLs that require a Bearer token. Provide the token via SlackBotToken; when empty, Slack records fall back to ErrRefetchNotSupported (no regression).

Any failure record whose FilePath does not start with "http://" or "https://" returns ErrRefetchNotSupported (preserving the existing skip behaviour for non-URL paths).

func NewURLRefetcher

func NewURLRefetcher(slackBotToken string) *URLRefetcher

NewURLRefetcher returns a URLRefetcher. slackBotToken may be empty — Slack records will return ErrRefetchNotSupported when it is.

func (*URLRefetcher) Refetch

Refetch downloads the file at f.FilePath (which must be an HTTP/HTTPS URL) to a temporary local file and returns the path + a cleanup func.

Returns ErrRefetchNotSupported when:

  • f.FilePath is not an HTTP/HTTPS URL
  • f.SourceType is "slack" and SlackBotToken is empty
  • f.FilePath hostname is not in the allowlist for f.SourceType (SSRF guard)

Jump to

Keyboard shortcuts

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