collector

package
v0.19.5 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2026 License: MIT Imports: 42 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 collector defines the Collector interface and common types used by all source-specific collectors.

Package collector provides source-specific document collectors. discord.go implements the Discord collector using the discordgo library.

Security note: DM and GroupDM channels are NEVER collected. Only the following channel types are allowed (positive-list approach):

  • GuildText (ChannelTypeGuildText)
  • GuildPublicThread (ChannelTypeGuildPublicThread)
  • GuildPrivateThread (ChannelTypeGuildPrivateThread)

This file covers:

  1. Periodic REST-based collection (full backfill on first run, incremental after)
  2. Mention-response via WebSocket gateway (always-on, separate from cron)
  3. Attachment download + extraction pipeline per message

Package collector — metrics.go tracks Discord bot response latency and result-quality signals in a lightweight in-memory store.

All operations are safe for concurrent use. No external dependencies: only stdlib sync/atomic, sync, and sort are used.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExtractFileID

func ExtractFileID(stubContent []byte) string

ExtractFileID parses a Google Workspace stub file's URL and returns the embedded Drive file ID. Returns "" when the URL cannot be parsed.

Types

type AttachmentDocumentStore

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

AttachmentDocumentStore is the document persistence interface used by DiscordCollector for attachment documents. It is a subset of store.DocumentStore.

type CalendarCollector

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

CalendarCollector collects events from Google Calendar via the Calendar REST API. It is disabled when credentials or token are not configured.

func NewCalendarCollector

func NewCalendarCollector(cfg *config.Config) *CalendarCollector

NewCalendarCollector returns a CalendarCollector configured from cfg. When CalendarCredentialsJSON or CalendarTokenJSON is empty, Enabled() returns false and the scheduler will not call Collect.

func (*CalendarCollector) Collect

func (c *CalendarCollector) Collect(ctx context.Context, since time.Time) ([]model.Document, error)

Collect fetches Google Calendar events in the window [now - LookbehindDays, now + LookaheadDays] that were updated after since.

func (*CalendarCollector) Enabled

func (c *CalendarCollector) Enabled() bool

func (*CalendarCollector) Name

func (c *CalendarCollector) Name() string

func (*CalendarCollector) Source

func (c *CalendarCollector) Source() model.SourceType

type Collector

type Collector interface {
	// Name returns a human-readable identifier (e.g. "slack", "github").
	Name() string

	// Source returns the SourceType that this collector produces.
	Source() model.SourceType

	// Enabled reports whether this collector is configured and should run.
	Enabled() bool

	// Collect fetches documents created or updated since the given time.
	Collect(ctx context.Context, since time.Time) ([]model.Document, error)
}

Collector collects documents from an external source.

type CutoverAwareCollector added in v0.16.4

type CutoverAwareCollector interface {
	Collector
	// WithCutover sets the cutover floor time. Zero = disabled.
	WithCutover(t time.Time)
}

CutoverAwareCollector is an optional interface implemented by IndexAware collectors that support a cutover floor time. When a non-zero cutover is set, the collector will not emit any record whose event time (OccurredAt for SMS/call-log, mtime for Whisper) is before the cutover — even if the record was never indexed.

This prevents re-collecting pre-cutover history that is already covered by the legacy secretary source while still allowing post-cutover late-arrival recovery via the IndexAware path.

Zero cutover (time.Time{}) disables the floor (no behaviour change).

type DeletionDetector

type DeletionDetector interface {
	// ListActiveSourceIDs returns all source IDs that currently exist in the
	// source. The scheduler uses this to detect files removed since last run.
	ListActiveSourceIDs(ctx context.Context) ([]string, error)
}

DeletionDetector is an optional interface that collectors may implement to support soft-delete detection. Collectors that can enumerate all currently existing source IDs (regardless of modification time) should implement this.

type DiscordCollector

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

DiscordCollector collects messages from Discord guild channels using the discordgo library. It respects discordgo's built-in rate-limit handler.

func NewDiscordCollector

func NewDiscordCollector(
	botToken string,
	applicationID string,
	guildIDs []string,
	mentionResponseEnabled bool,
) *DiscordCollector

NewDiscordCollector returns a DiscordCollector configured from the given parameters. When botToken or guildIDs is empty the collector is disabled and Collect will not be called by the scheduler.

func NewDiscordCollectorWithAttachments

func NewDiscordCollectorWithAttachments(
	botToken string,
	applicationID string,
	guildIDs []string,
	mentionResponseEnabled bool,
	docStore AttachmentDocumentStore,
	extractionFailures *store.ExtractionFailureStore,
) *DiscordCollector

NewDiscordCollectorWithAttachments returns a DiscordCollector with full attachment processing support. docStore and extractionFailures may be nil (attachments are then skipped or failures only logged respectively).

func (*DiscordCollector) Collect

func (c *DiscordCollector) Collect(ctx context.Context, since time.Time) ([]model.Document, error)

Collect fetches messages from all allowed text channels in the configured guilds that were created or updated since the given time. On the first run (since.IsZero()) it performs a full backfill. Thread messages (public + archived public threads) are also collected.

func (*DiscordCollector) Enabled

func (c *DiscordCollector) Enabled() bool

Enabled reports whether the collector has the minimum required configuration.

func (*DiscordCollector) Name

func (c *DiscordCollector) Name() string

func (*DiscordCollector) Source

func (c *DiscordCollector) Source() model.SourceType

type DiscordGateway

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

DiscordGateway holds the WebSocket session used for real-time mention responses and real-time message collection. It is decoupled from the REST-based DiscordCollector to keep concerns separate.

When both searcher and llmClient are non-nil, it performs full RAG:

mention → search top-K docs → LLM chat completion → Discord reply

When either dependency is nil it falls back to the legacy static message.

When docStore is non-nil (injected via SetDocStore), every incoming guild message is upserted immediately — reducing collection latency from 5 minutes to near-zero. The 5-minute cron collector continues to run as a backfill for messages missed during gateway downtime; duplicate source_ids are de-duplicated by the UNIQUE constraint on documents.source_id.

func NewDiscordGateway

func NewDiscordGateway(
	botToken string,
	mentionResponseEnabled bool,
	searcher Searcher,
	llmClient llm.Completer,
) *DiscordGateway

NewDiscordGateway creates a gateway that connects to the Discord WebSocket and responds to bot mentions when enabled.

searcher and llmClient may be nil — in that case the gateway uses the legacy static response. Inject both to enable the RAG flow.

func (*DiscordGateway) Enabled

func (g *DiscordGateway) Enabled() bool

Enabled reports whether the gateway has the minimum required configuration.

func (*DiscordGateway) Run

func (g *DiscordGateway) Run(ctx context.Context)

Run opens the Discord WebSocket gateway and blocks until ctx is cancelled. On cancellation it performs a graceful close.

func (*DiscordGateway) SetDocStore

func (g *DiscordGateway) SetDocStore(s AttachmentDocumentStore)

SetDocStore injects a document store for real-time message persistence. It must be called before Run. It is safe to call even after construction so existing callers of NewDiscordGateway do not need to change their call sites.

func (*DiscordGateway) SetFeedbackStore

func (g *DiscordGateway) SetFeedbackStore(r FeedbackRecorder)

SetFeedbackStore injects a feedback recorder so that 👍/👎 reactions on bot replies are persisted. It must be called before Run. When nil (the default), reaction feedback is silently ignored — backward-compatible with callers that do not need feedback collection.

func (*DiscordGateway) SetMetrics

func (g *DiscordGateway) SetMetrics(m *DiscordMetrics)

SetMetrics injects a DiscordMetrics instance for response-latency tracking. It must be called before Run. When nil (the default), metrics recording is skipped — backward-compatible with callers that do not need metrics.

type DiscordMetrics

type DiscordMetrics struct {
	// TotalResponses is the number of buildReply completions (success or error).
	TotalResponses atomic.Int64

	// ZeroResultCount is the number of completions where the search returned
	// no results (an important quality signal).
	ZeroResultCount atomic.Int64
	// contains filtered or unexported fields
}

DiscordMetrics accumulates Discord bot response metrics in memory. It maintains a rolling window of the last 100 total-latency samples and atomic counters for total responses and zero-search-result events.

Zero value is usable — all fields are initialised lazily or default to zero.

func (*DiscordMetrics) Record

func (m *DiscordMetrics) Record(total time.Duration, zeroResults bool)

Record adds a single observation to the metrics store. total is the end-to-end latency of the buildReply call. zeroResults should be true when the knowledge-base search returned no hits.

func (*DiscordMetrics) Snapshot

func (m *DiscordMetrics) Snapshot() DiscordMetricsSnapshot

Snapshot returns a consistent point-in-time view of the current metrics. The latency percentiles are computed from the rolling window.

type DiscordMetricsSnapshot

type DiscordMetricsSnapshot struct {
	TotalResponses  int64              `json:"total_responses"`
	ZeroResultCount int64              `json:"zero_result_count"`
	LatencyMS       latencyPercentiles `json:"latency_ms"`
}

DiscordMetricsSnapshot is a point-in-time read of DiscordMetrics. It is safe to serialise to JSON directly.

type DriveExporter

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

DriveExporter exports text content from Google Workspace stub files via the Drive API using Application Default Credentials (ADC). When ADC is not available, Enabled() returns false and all export calls are no-ops.

func NewDriveExporter

func NewDriveExporter(ctx context.Context) (*DriveExporter, error)

NewDriveExporter creates a DriveExporter backed by ADC. It returns nil (not an error) when credentials are unavailable so callers can treat it as optional.

func (*DriveExporter) Enabled

func (e *DriveExporter) Enabled() bool

Enabled reports whether the exporter has valid credentials.

func (*DriveExporter) Export

func (e *DriveExporter) Export(ctx context.Context, fileID, ext string) (string, error)

Export fetches the text content of the Google Workspace file identified by fileID. The MIME type used for export is chosen based on ext:

  • .gdoc, .gscript, .gform → text/plain
  • .gsheet → text/csv
  • .gslides → text/plain (falls back to raw export on error)

type FeedbackEntry

type FeedbackEntry struct {
	Source    string
	SessionID *string        // message ID used as session key
	UserID    *string        // opaque Discord user ID
	Thumbs    int16          // +1 (👍) or -1 (👎)
	Comment   *string        // bot answer used as context hint
	Metadata  map[string]any // guild_id, channel_id, message_id, emoji
}

FeedbackEntry is the domain type the Discord gateway uses to record reaction feedback. It mirrors store.Feedback but avoids a direct store import so the collector package stays decoupled from persistence details.

type FeedbackRecorder

type FeedbackRecorder interface {
	Record(ctx context.Context, entry FeedbackEntry) (int64, error)
}

FeedbackRecorder is the minimal interface the gateway requires to persist reaction feedback. store.FeedbackStore satisfies this interface via feedbackStoreAdapter (see feedback_adapter.go) when the Feedback type signatures differ.

func NewFeedbackStoreAdapter

func NewFeedbackStoreAdapter(s *store.FeedbackStore) FeedbackRecorder

NewFeedbackStoreAdapter wraps the given store.FeedbackStore as a FeedbackRecorder. Pass the result to DiscordGateway.SetFeedbackStore.

type FilesystemCollector

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

FilesystemCollector walks a local directory tree and indexes files. It is strictly read-only; it never acquires file locks.

func NewFilesystemCollector

func NewFilesystemCollector(rootPath string) *FilesystemCollector

NewFilesystemCollector returns a FilesystemCollector rooted at rootPath.

func NewFilesystemCollectorWithDriveExport

func NewFilesystemCollectorWithDriveExport(rootPath string, exporter *DriveExporter) *FilesystemCollector

NewFilesystemCollectorWithDriveExport returns a FilesystemCollector that uses the provided DriveExporter to export Google Workspace file content. When exporter is nil (ADC not configured), the collector falls back to URL-only metadata for workspace stub files.

func (*FilesystemCollector) Collect

func (c *FilesystemCollector) Collect(ctx context.Context, since time.Time) ([]model.Document, error)

Collect walks the root directory and returns documents for files modified after since. Individual file errors are logged and skipped.

Collect is retained for backward compatibility and is implemented as a thin accumulator around CollectStream. Callers expecting to process very large result sets should use CollectStream directly to avoid memory blow-up.

func (*FilesystemCollector) CollectStream

func (c *FilesystemCollector) CollectStream(ctx context.Context, since time.Time, onBatch func([]model.Document) error) error

CollectStream walks the root directory and emits documents in batches via onBatch. Memory usage stays bounded at roughly batchSize documents regardless of total file count. The context is checked between batches so that SIGTERM during a long scan exits promptly.

func (*FilesystemCollector) Enabled

func (c *FilesystemCollector) Enabled() bool

func (*FilesystemCollector) ListActiveSourceIDs

func (c *FilesystemCollector) ListActiveSourceIDs(_ context.Context) ([]string, error)

ListActiveSourceIDs walks the entire root directory and returns the relative path of every indexable file, regardless of modification time. This allows the scheduler to detect files that were removed since the last collection run.

If the root directory does not exist or cannot be accessed (e.g. the volume is unmounted), an error is returned immediately. This distinguishes a broken root from a legitimately empty source directory, preventing the scheduler from misinterpreting the error as "all files deleted" and bulk-deleting active documents in the database.

func (*FilesystemCollector) Name

func (c *FilesystemCollector) Name() string

func (*FilesystemCollector) Source

func (c *FilesystemCollector) Source() model.SourceType

func (*FilesystemCollector) WithBatchSize

func (c *FilesystemCollector) WithBatchSize(n int) *FilesystemCollector

WithBatchSize overrides the streaming batch size used by CollectStream. Values <= 0 are ignored and the default (defaultFilesystemBatchSize) is used.

func (*FilesystemCollector) WithExcludes

func (c *FilesystemCollector) WithExcludes(dirs, exts []string) *FilesystemCollector

WithExcludes registers additional directory names and file extensions to skip, on top of the built-in skipDirs/skipExts defaults. Both lists are merged (union), not replaced, so security-critical defaults (.git, etc.) cannot be silently disabled by configuration. Extensions must be lowercase and include the leading dot (e.g. ".pem"); callers are expected to normalize beforehand (see config.normalizeExts).

func (*FilesystemCollector) WithIndexedIDs

func (c *FilesystemCollector) WithIndexedIDs(ids map[string]struct{})

WithIndexedIDs provides the collector with a pre-loaded set of source_ids that are already active in the store. When set, CollectStream treats any file whose relative path is NOT in this set as "new" and collects it unconditionally, regardless of whether its mtime predates the cursor. Files that ARE in the set are still skipped by the normal mtime guard so that already-indexed, unchanged files are not re-processed on every run.

The scheduler calls this at the start of each filesystem collection cycle (after loading the set from store.ActiveSourceIDSet) to fix the bug where files copied with a preserved old mtime are silently skipped on their first encounter. Passing nil disables the store-aware new-file detection and restores the previous mtime-only behaviour (used in tests that do not need a store).

type GDriveCollector

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

GDriveCollector collects documents from Google Drive using a service account.

It uses the Drive REST API v3 with a service-account access token obtained via golang.org/x/oauth2/google. Two credential paths are supported:

  • GDRIVE_CREDENTIALS_JSON: service account JSON inline (takes priority).
  • ADC (GOOGLE_APPLICATION_CREDENTIALS or GCP metadata): Application Default Credentials.

func NewGDriveCollector

func NewGDriveCollector(credentialsJSON string) *GDriveCollector

NewGDriveCollector returns a GDriveCollector. When credentialsJSON is empty the collector is disabled.

func (*GDriveCollector) Collect

func (c *GDriveCollector) Collect(ctx context.Context, since time.Time) ([]model.Document, error)

Collect lists Google Docs modified after since and exports their text content.

func (*GDriveCollector) Enabled

func (c *GDriveCollector) Enabled() bool

func (*GDriveCollector) Name

func (c *GDriveCollector) Name() string

func (*GDriveCollector) Source

func (c *GDriveCollector) Source() model.SourceType

type GitHubCollector

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

GitHubCollector collects issues, PRs, and READMEs from an organisation's repositories using the GitHub REST API.

func NewGitHubCollector

func NewGitHubCollector(token, org string) *GitHubCollector

NewGitHubCollector returns a GitHubCollector. When token is empty the collector is disabled.

func (*GitHubCollector) Collect

func (c *GitHubCollector) Collect(ctx context.Context, since time.Time) ([]model.Document, error)

Collect fetches issues and pull requests updated after since.

func (*GitHubCollector) Enabled

func (c *GitHubCollector) Enabled() bool

func (*GitHubCollector) Name

func (c *GitHubCollector) Name() string

func (*GitHubCollector) Source

func (c *GitHubCollector) Source() model.SourceType

type GmailCollector

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

GmailCollector collects emails from a Gmail account via the Gmail REST API. It is disabled when credentials or token are not configured.

func NewGmailCollector

func NewGmailCollector(cfg *config.Config) *GmailCollector

NewGmailCollector returns a GmailCollector configured from cfg. When GmailCredentialsJSON or GmailTokenJSON is empty, Enabled() returns false and the scheduler will not call Collect.

func (*GmailCollector) Collect

func (c *GmailCollector) Collect(ctx context.Context, since time.Time) ([]model.Document, error)

Collect fetches Gmail messages matching cfg.GmailQuery that were received after since. It returns one Document per message (thread-level dedup is left to the store's Upsert logic via SourceID).

func (*GmailCollector) Enabled

func (c *GmailCollector) Enabled() bool

func (*GmailCollector) Name

func (c *GmailCollector) Name() string

func (*GmailCollector) Source

func (c *GmailCollector) Source() model.SourceType

type IndexAwareCollector

type IndexAwareCollector interface {
	Collector
	// WithIndexedIDs supplies the collector with the set of source_ids currently
	// active in the store. When set, the collector emits a record when EITHER
	// its event time is after since OR its source_id is absent from the set.
	// Passing nil disables store-aware detection (fallback to event-time only).
	WithIndexedIDs(ids map[string]struct{})
}

IndexAwareCollector is an optional interface implemented by collectors that can use the set of already-indexed source IDs to detect records that have never been collected, even when their event time (OccurredAt or mtime) predates the scheduler watermark.

This fixes two classes of data-loss bugs:

  1. Late-arriving records (HIGH#1): SMS/call events or audio files that arrive on the device after a collection run completed have an event time before the watermark. A pure event-time filter drops them forever.
  2. Post-truncation records (HIGH#2): After an XML parse error, records after the truncation point were never indexed. The SourceID mechanism guarantees they are eventually collected on the next successful run.

The scheduler calls WithIndexedIDs once per run (before Collect). Passing nil disables the mechanism and restores mtime/event-time-only filtering.

type LLMMemoryCollector

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

LLMMemoryCollector reads records from an llm-memory SQLite database and produces model.Document values for indexing. It uses a watermark-based incremental strategy keyed on the records.updated_at column.

Table schema expected in the llm-memory database:

records(
  id TEXT PK, source TEXT, kind TEXT, device_id TEXT,
  project TEXT NULLABLE, agent TEXT NULLABLE, path TEXT,
  title TEXT, summary TEXT NULLABLE, content TEXT NULLABLE,
  tags TEXT, sensitivity TEXT, updated_at TEXT
)

The kind value (e.g. "session", "note", "fact") is preserved verbatim as metadata["kind"]. source_type is always "llm-memory".

func NewLLMMemoryCollector

func NewLLMMemoryCollector(dbPath string) *LLMMemoryCollector

NewLLMMemoryCollector returns an LLMMemoryCollector. When dbPath is empty the collector is disabled and Collect is never called by the scheduler.

func (*LLMMemoryCollector) Collect

func (c *LLMMemoryCollector) Collect(ctx context.Context, since time.Time) ([]model.Document, error)

Collect fetches all llm-memory records whose updated_at is after since. Records with empty content (after joining summary + content) are silently skipped.

The watermark (since) is passed in by the scheduler via the collector_state table. On the first run since is the zero time, causing a full collection.

func (*LLMMemoryCollector) Enabled

func (c *LLMMemoryCollector) Enabled() bool

func (*LLMMemoryCollector) Name

func (c *LLMMemoryCollector) Name() string

func (*LLMMemoryCollector) Source

func (c *LLMMemoryCollector) Source() model.SourceType

type NotionCollector

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

NotionCollector collects pages from a Notion workspace.

func NewNotionCollector

func NewNotionCollector(token string) *NotionCollector

NewNotionCollector returns a NotionCollector. When token is empty the collector is disabled.

func (*NotionCollector) Collect

func (c *NotionCollector) Collect(ctx context.Context, since time.Time) ([]model.Document, error)

Collect searches all pages edited after since and fetches their block content.

func (*NotionCollector) Enabled

func (c *NotionCollector) Enabled() bool

func (*NotionCollector) Name

func (c *NotionCollector) Name() string

func (*NotionCollector) Source

func (c *NotionCollector) Source() model.SourceType

type SMSCollector

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

SMSCollector reads SMS messages and call logs from SMS Backup & Restore XML exports. Each prefix (sms-*.xml, calls-*.xml) uses the single file with the lexicographically-greatest filename (date-stamped sms-YYYYMMDD.xml) in cfg.SMSSourceDir, enabling additive backups where the app writes a new file per export without overwriting the previous one.

Incremental strategy (primary): the full XML is parsed on every run (XML streams cannot be seeked), but only records whose OccurredAt > since are emitted. This is correct because each export is cumulative.

IndexAware strategy (defence-in-depth): when WithIndexedIDs is called with a non-nil set, records are ALSO emitted when their SourceID is absent from the indexed set regardless of OccurredAt. This rescues late-arriving records (OneDrive sync lag) and records after an XML truncation point.

func NewSMSCollector

func NewSMSCollector(sourceDir string, maxFileBytes int64) *SMSCollector

NewSMSCollector returns an SMSCollector that reads XML exports from sourceDir. maxFileBytes is the per-file OOM guard (from cfg.SMSMaxFileBytes): files exceeding this size are skipped with a slog.Warn. Pass 0 to disable the cap. When sourceDir is empty, Enabled() returns false and the scheduler will not call Collect.

func (*SMSCollector) Collect

func (c *SMSCollector) Collect(ctx context.Context, since time.Time) ([]model.Document, error)

Collect parses the latest sms-*.xml and calls-*.xml files in sourceDir and returns documents for all records that satisfy the emission criteria. Both files are optional: if one is missing it is silently skipped.

Partial-result contract: if the SMS file parse fails, already-parsed call-log docs (and vice-versa) are still returned. Per-file failures are logged as slog.Warn. This matches the gmail/calendar/whisper partial-result pattern.

func (*SMSCollector) CollectStream added in v0.16.5

func (c *SMSCollector) CollectStream(ctx context.Context, since time.Time, onBatch func([]model.Document) error) error

CollectStream implements StreamingCollector. It streams the same sms-*.xml and calls-*.xml files as Collect but emits documents in bounded batches of smsStreamBatchSize instead of accumulating the entire result set in memory.

Memory strategy: the raw XML bytes are still read into a []byte buffer via readFileWithRetry (required for FUSE-safe retry semantics). The OOM concern on large exports (~300 MB XML / ~1M records) is NOT the raw bytes but the unbounded []model.Document slice that Collect builds. CollectStream caps that at smsStreamBatchSize documents at a time, so peak live Document memory is bounded regardless of file size.

Partial-result contract is preserved: if one file's stream fails, the other file's already-emitted batches are kept; a slog.Warn is issued. onBatch errors abort the stream immediately and are propagated.

func (*SMSCollector) Enabled

func (c *SMSCollector) Enabled() bool

func (*SMSCollector) Name

func (c *SMSCollector) Name() string

func (*SMSCollector) Source

func (c *SMSCollector) Source() model.SourceType

func (*SMSCollector) WithCutover added in v0.16.4

func (c *SMSCollector) WithCutover(t time.Time)

WithCutover implements CutoverAwareCollector. When t is non-zero, records whose OccurredAt is before t are suppressed even if they were never indexed. Zero t disables the floor (no behaviour change).

func (*SMSCollector) WithIndexedIDs

func (c *SMSCollector) WithIndexedIDs(ids map[string]struct{})

WithIndexedIDs implements IndexAwareCollector. Supplying a non-nil set enables store-aware new-record detection: records whose SourceID is absent from the set are emitted unconditionally (i.e. even when OccurredAt <= since). Passing nil restores event-time-only filtering.

type Searcher

type Searcher interface {
	Search(ctx context.Context, q model.SearchQuery) ([]*model.SearchResult, error)
}

Searcher is the interface the gateway uses to query the knowledge base. It is satisfied by *search.Service, but expressed here as an interface to keep the collector package free of a direct search import.

type SecretaryCollector

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

SecretaryCollector reads documents from a secretary.db SQLite database and produces model.Document values for indexing. It uses a watermark-based incremental strategy: only rows whose timestamp is after the watermark are returned on subsequent runs.

Table schema expected in secretary.db:

documents(
  id TEXT PK, source TEXT, source_path TEXT,
  external_id TEXT, timestamp TEXT, sender TEXT, recipient TEXT,
  subject TEXT, title TEXT, body TEXT, metadata_json TEXT,
  indexed_at TEXT NOT NULL  -- secretary's ingest timestamp; used as incremental cursor (WHERE indexed_at > ?)
)

source values map to kind: "gmail" → "gmail", "sms" → "sms", "call-log" → "call-log", "call-transcript" → "call-transcript", "calendar" → "calendar".

func NewSecretaryCollector

func NewSecretaryCollector(dbPath string) *SecretaryCollector

NewSecretaryCollector returns a SecretaryCollector. When dbPath is empty the collector is disabled and Collect is never called by the scheduler.

func (*SecretaryCollector) Collect

func (c *SecretaryCollector) Collect(ctx context.Context, since time.Time) ([]model.Document, error)

Collect fetches all secretary documents whose indexed_at is after since. Rows with an empty or whitespace-only content are silently skipped.

The watermark (since) is passed in by the scheduler via the collector_state table. On the first run since is the zero time, causing a full collection.

Incremental strategy: filter by indexed_at (secretary's ingest timestamp), NOT by document timestamp. The document timestamp represents when the original event occurred (e.g. an email from 2022), which can be far in the past even for records freshly indexed by secretary. Using timestamp > since caused permanent missed records: after the initial full collection, the watermark advances to the current wall-clock time, so any newly-indexed document whose original event timestamp predates that watermark is silently skipped on every subsequent run. indexed_at is set by secretary at ingest time and increases monotonically, making it the correct cursor for incremental collection.

func (*SecretaryCollector) Enabled

func (c *SecretaryCollector) Enabled() bool

func (*SecretaryCollector) Name

func (c *SecretaryCollector) Name() string

func (*SecretaryCollector) Source

func (c *SecretaryCollector) Source() model.SourceType

type SlackChannelWatcher

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

SlackChannelWatcher periodically polls the list of channels the bot belongs to and triggers an immediate first-collection for any newly discovered channel, rather than waiting for the next cron cycle.

func NewSlackChannelWatcher

func NewSlackChannelWatcher(
	col *SlackCollector,
	store watcherStore,
	embed search.EmbeddingEngine,
	interval time.Duration,
) *SlackChannelWatcher

NewSlackChannelWatcher creates a watcher that polls on the given interval.

func (*SlackChannelWatcher) Run

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

Run starts the polling loop and blocks until ctx is cancelled. On the first tick, all current channels are registered in the seen set without triggering collection (the cron scheduler handles the initial run). On subsequent ticks, any channel not yet in the seen set is collected immediately from the beginning of history (since=zero time).

type SlackCollector

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

SlackCollector collects messages from Slack channels using the Web API.

func NewSlackCollector

func NewSlackCollector(botToken, teamID string) *SlackCollector

NewSlackCollector returns a SlackCollector. When botToken is empty the collector is disabled and Collect will not be called.

func (*SlackCollector) Collect

func (c *SlackCollector) Collect(ctx context.Context, since time.Time) ([]model.Document, error)

Collect fetches messages from all channels the bot is a member of, updated since the given time. For each top-level message that has thread replies, it additionally fetches all replies via conversations.replies and merges them as independent Documents. Known limitation: if a parent message predates `since` but received new replies after `since`, those replies will not be collected in incremental runs.

func (*SlackCollector) CollectChannel

func (c *SlackCollector) CollectChannel(ctx context.Context, channelID, channelName string, since time.Time) ([]model.Document, error)

CollectChannel fetches messages from a single channel by ID and name. since=time.Time{} fetches the full history. This method is intended for the SlackChannelWatcher to trigger an immediate first-collection for newly joined channels.

func (*SlackCollector) Enabled

func (c *SlackCollector) Enabled() bool

func (*SlackCollector) FindMemberChannelByName

func (c *SlackCollector) FindMemberChannelByName(ctx context.Context, name string) (string, string, bool, error)

FindMemberChannelByName looks up a channel the bot belongs to by name. Matching is case-insensitive and ignores a leading "#". Returns (id, name, true, nil) on match, ("", "", false, nil) when not found, and ("", "", false, err) on API failure.

func (*SlackCollector) ListMemberChannels

func (c *SlackCollector) ListMemberChannels(ctx context.Context) ([]slackChannel, error)

ListMemberChannels calls users.conversations to enumerate every channel the bot belongs to. It handles cursor-based pagination automatically.

func (*SlackCollector) Name

func (c *SlackCollector) Name() string

func (*SlackCollector) Source

func (c *SlackCollector) Source() model.SourceType

type StreamingCollector

type StreamingCollector interface {
	Collector
	// CollectStream walks the source since the given time and invokes onBatch
	// for every accumulated batch of documents. If onBatch returns an error the
	// stream terminates and the error is propagated. Implementations MUST flush
	// the final partial batch before returning a nil error.
	CollectStream(ctx context.Context, since time.Time, onBatch func([]model.Document) error) error
}

StreamingCollector is implemented by collectors that can emit documents in batches rather than accumulating the entire result set in memory. The scheduler prefers this when available (type assertion).

type TelegramCollector

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

TelegramCollector collects messages from configured Telegram chats via the Bot API. It tracks the highest seen update_id so each call to Collect only fetches new updates since the previous invocation.

func NewTelegramCollector

func NewTelegramCollector(token string, chatIDs []int64) *TelegramCollector

NewTelegramCollector returns a TelegramCollector. When token is empty or chatIDs is empty the collector is disabled.

func (*TelegramCollector) Collect

func (c *TelegramCollector) Collect(ctx context.Context, since time.Time) ([]model.Document, error)

Collect fetches new updates from the Telegram Bot API, filters them to the configured chat IDs and messages sent after since, and returns them as Documents.

func (*TelegramCollector) Enabled

func (c *TelegramCollector) Enabled() bool

func (*TelegramCollector) Name

func (c *TelegramCollector) Name() string

func (*TelegramCollector) Source

func (c *TelegramCollector) Source() model.SourceType

type WhisperCollector

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

WhisperCollector transcribes audio files via an OpenAI-compatible Whisper endpoint and produces call-transcript documents.

The collector scans cfg.WhisperAudioDir recursively, submitting only files whose modification time is after the scheduler watermark (since). This prevents re-transcription of already-processed files, which is important because transcription API calls are expensive.

The implementation targets the /v1/audio/transcriptions endpoint using multipart/form-data (OpenAI API contract). Setting cfg.WhisperAPIURL to a local whisper.cpp server URL routes all requests through that server instead of the public OpenAI API — the protocol is identical.

Enabled() returns true only when both WhisperAudioDir and WhisperAPIURL are set. WhisperAPIKey is optional: local whisper.cpp servers do not require authentication, so the Authorization header is omitted when the key is empty.

func NewWhisperCollector

func NewWhisperCollector(cfg *config.Config) *WhisperCollector

NewWhisperCollector returns a WhisperCollector configured from cfg. When WhisperAudioDir or WhisperAPIURL is empty, Enabled() returns false and the scheduler will not call Collect.

The HTTP client timeout is sourced from cfg.WhisperHTTPTimeout (set via WHISPER_HTTP_TIMEOUT env var; default 2h). If cfg.WhisperHTTPTimeout is zero (e.g. a zero-value Config in tests), whisperDefaultHTTPTimeout (2h) is used as a defence-in-depth fallback so a zero config value never yields an infinite (zero-timeout) HTTP client.

func (*WhisperCollector) Collect

func (c *WhisperCollector) Collect(ctx context.Context, since time.Time) ([]model.Document, error)

Collect walks WhisperAudioDir recursively, transcribes audio files modified after since, and returns a Document per successful transcription.

Incremental strategy (primary): only files with mtime > since are submitted. The scheduler watermark ensures that on subsequent runs only new or changed audio files are processed. The first run (since == zero) processes all files.

IndexAware strategy (defence-in-depth): when WithIndexedIDs is called with a non-nil set, files whose SourceID is absent from the set are also transcribed regardless of mtime (fixes late-arriving files on OneDrive FUSE mounts).

Cloud-endpoint guard: if the configured Whisper endpoint resolves to a non-local host, a prominent warning is logged on every collect call. Issue #100 mandates call transcription stays LOCAL.

Partial success: individual transcription failures are logged as warnings and the walk continues. The final error is nil as long as the directory walk itself succeeds.

func (*WhisperCollector) Enabled

func (c *WhisperCollector) Enabled() bool

Enabled reports whether the collector is configured. WhisperAPIKey is intentionally NOT required: local whisper.cpp servers do not enforce authentication. The Authorization header is added only when the key is non-empty (see transcribeFile).

func (*WhisperCollector) Name

func (c *WhisperCollector) Name() string

func (*WhisperCollector) Source

func (c *WhisperCollector) Source() model.SourceType

func (*WhisperCollector) WithCutover added in v0.16.4

func (c *WhisperCollector) WithCutover(t time.Time)

WithCutover implements CutoverAwareCollector. When t is non-zero, files whose recording timestamp (parsed from the filename; falls back to mtime) is before t are suppressed even if they were never indexed. Zero t disables the floor (no behaviour change).

func (*WhisperCollector) WithIndexedIDs

func (c *WhisperCollector) WithIndexedIDs(ids map[string]struct{})

WithIndexedIDs implements IndexAwareCollector. Supplying a non-nil set enables store-aware new-file detection: audio files whose SourceID is absent from the set are transcribed unconditionally (even when mtime <= since). Passing nil restores mtime-only filtering.

Directories

Path Synopsis
Package extractor provides content extraction for binary and structured file formats (HTML, PDF, Office, etc.) that cannot be read as plain text.
Package extractor provides content extraction for binary and structured file formats (HTML, PDF, Office, etc.) that cannot be read as plain text.
Package smsmap provides pure functions that map raw SMS and call-log fields to model.Document.
Package smsmap provides pure functions that map raw SMS and call-log fields to model.Document.

Jump to

Keyboard shortcuts

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