Skip to content

API Reference parrot.knowledge.wiki.sources

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.knowledge.wiki.sources

View source

Source collection manager for the LLM Wiki feature (FEAT-260).

Implements the "Raw Sources" layer of Karpathy's 3-layer architecture. Tracks ingested source documents in one of two backends, matching the wiki's storage_backend:

  • "sqlite" (default) — the sources table of the wiki's single-file SQLite retrieval plane (wiki.db — see :mod:parrot.knowledge.wiki.store). A legacy .manifest.json found on first open is migrated into the database automatically and renamed to .manifest.json.bak.
  • "json" — a plain .manifest.json file in sources_dir (atomic tmp-file writes), used with the SQLite-free InMemoryWikiStore backend.

Staleness detection reuses the same mtime + SHA-1 pattern as SQLitePersistence.is_stale() in graphindex/persist_sqlite.py.

The public API is synchronous (callers off-load to a thread pool via asyncio.to_thread); the sqlite mode uses short-lived per-call sqlite3 connections — WAL mode makes this safe alongside the async :class:~parrot.knowledge.wiki.store.WikiStore connections on the same file.

Class SourceCollectionManager

Manages the raw-source collection for a single wiki instance.

External identity convention (FEAT-472): a source may optionally carry an external_id — an immutable identity in "<source>:<id>" form (e.g. "fireflies:abc123" for a Fireflies transcript id), distinct from source_id/source_uri which are derived from the file's path and change if the file is renamed or moved. Any future external source integration (Jira, audio notes, etc.) that needs identity-not-path dedup should adopt the same "<source>:<id>" convention rather than inventing a parallel registry. See :meth:find_by_external_id, :meth:find_entries_by_external_ids, :meth:list_by_external_prefix, and :meth:set_external_id.

Example::

mgr = SourceCollectionManager(Path("/wiki/sources"))
entry = mgr.add_source(Path("/docs/article.md"))
print(entry.source_id, entry.file_hash)

if mgr.is_stale(entry.source_id):
    mgr.reingest(...)
Parameter Type Default Description
sources_dir Path Root directory for raw source documents. Created automatically if it does not exist.
db_path Path | None None Optional explicit path of the wiki database (sqlite mode only). When omitted, defaults to <sources_dir>/../wiki.db — the same file used by :class:SQLiteWikiStore.
backend str 'sqlite' "sqlite" (default), "json", or "arangodb".
arango_db Any | None None Already-connected asyncdb ArangoDB driver instance (the same connection used by ArangoDBWikiStore — see its _db attribute after initialize()). One of arango_db/arango_store is required when backend="arangodb".
arango_store Any | None None An ArangoDBWikiStore instance to lazily initialize() (idempotent) and read ._db from at first use, instead of requiring an already-connected driver at construction time. Lets callers that cannot await here (e.g. LLMWikiToolkit.__init__, which is synchronous) still wire the arangodb backend correctly. Takes precedence over arango_db when both are given.
busy_timeout float 15.0

Attributes:

Attribute Type Description
sources_dir Path Directory where raw source files live.
backend str "sqlite" (sources table in wiki.db), "json" (.manifest.json in sources_dir), or "arangodb" (wiki_sources collection in a shared ArangoDB database).
db_path Path Path of the shared wiki.db file (sqlite mode).
manifest_path Path .manifest.json location (json-mode storage; sqlite-mode legacy migration source).
logger logging.Logger Standard Python logger.
busy_timeout float

Method SourceCollectionManager.add_source

Register a new source file in the sources table.

Computes the SHA-1 hash and mtime of the file at registration time. If the source is already tracked (by URI), the existing entry is refreshed with the current hash and mtime.

add_source(path: Path, *, external_id: str | None = None) -> SourceManifestEntry

Parameter Type Default Description
path Path Absolute or relative path to the source file.
external_id str | None None FEAT-472 immutable external identity in "<source>:<id>" form (e.g. "fireflies:abc123"). None (default) leaves the source without one.

Returns: SourceManifestEntry — The created or updated :class:SourceManifestEntry.

Raises:

  • FileNotFoundError — If path does not exist.

Method SourceCollectionManager.find_entries_by_uris

Look up many sources by URI in as few statements as possible.

find_entries_by_uris(uris: list[str]) -> dict[str, SourceManifestEntry]

Parameter Type Default Description
uris list[str] Absolute source URIs (str(path.resolve())).

Returns: dict[str, SourceManifestEntry] — Mapping of source_uri -> entry, containing only the URIs that are actually tracked.

Method SourceCollectionManager.find_entries_by_ids

Fetch many sources by id in as few statements as possible.

find_entries_by_ids(source_ids: list[str]) -> dict[str, SourceManifestEntry]

Parameter Type Default Description
source_ids list[str] Stable source identifiers.

Returns: dict[str, SourceManifestEntry] — Mapping of source_id -> entry, for the ids that exist.

Method SourceCollectionManager.add_sources

Register (or refresh) many source files in one write.

The batch equivalent of :meth:add_source: hashes and stats every file locally, resolves existing ids with a single lookup, then writes every row in one statement.

One deliberate difference from :meth:add_source: an already-tracked source keeps its original ingested_at and pages_generated instead of having them reset. The build pipeline registers changed files through here (the single-source path only ever saw brand-new ones), and resetting those fields would both re-date every re-ingested file and drop its page list if the run failed before mark_ingested_many.

add_sources(paths: list[Path], known: dict[str, SourceManifestEntry] | None = None) -> list[SourceManifestEntry]

Parameter Type Default Description
paths list[Path] Source file paths; each is resolved before use.
known dict[str, SourceManifestEntry] | None None Entries already read for these URIs (see :meth:find_entries_by_uris). Pass it when the caller has just read them to skip this method's own id-resolution read — one fewer round trip on a server-hosted manifest.

Returns: list[SourceManifestEntry] — The created/updated entries, in the order given.

Raises:

  • FileNotFoundError — If any path does not exist — same contract as :meth:add_source, reported for the whole batch.

Method SourceCollectionManager.mark_ingested_many

Record ingest results for many sources in one write.

The batch equivalent of :meth:mark_ingested, including its re-hash of each file (a file rewritten during the ingest run must not be left looking fresh). Untracked ids are skipped with a warning, exactly as the single-source version does.

mark_ingested_many(pages_by_source: dict[str, list[str]], status: str = 'ingested') -> None

Parameter Type Default Description
pages_by_source dict[str, list[str]] source_id -> page ids produced for it.
status str 'ingested' New lifecycle status for every source in the batch.

Method SourceCollectionManager.list_sources

Return all tracked sources.

list_sources() -> list[SourceManifestEntry]

Returns: list[SourceManifestEntry] — A list of :class:SourceManifestEntry objects, one per registered source, in insertion order.

Method SourceCollectionManager.get_source

Retrieve a single source entry by its ID.

get_source(source_id: str) -> SourceManifestEntry | None

Parameter Type Default Description
source_id str The stable source identifier assigned at registration time.

Returns: SourceManifestEntry | None — class:SourceManifestEntry, or None if not found.

Method SourceCollectionManager.is_stale

Determine whether a tracked source has changed since last ingest.

Replicates the SQLitePersistence.is_stale() logic: a source is stale when its current SHA-1 hash or mtime differs from the values recorded at ingest time.

is_stale(source_id: str) -> bool

Parameter Type Default Description
source_id str The stable source identifier to check.

Returns: bool — True when the source is missing from the table, the underlying file no longer exists, or the file content / mtime has changed. False otherwise.

Method SourceCollectionManager.entry_is_stale

Staleness of an ALREADY-FETCHED manifest entry — no DB read.

The comparison half of :meth:is_stale, split out so a caller that has just read a batch of entries (see :meth:find_entries_by_uris) can classify them without one round trip per file. :meth:is_stale is this plus the read, so the rule lives in exactly one place.

entry_is_stale(entry: SourceManifestEntry) -> bool

Parameter Type Default Description
entry SourceManifestEntry The manifest entry to compare against its file.

Returns: bool — True when the underlying file is gone or its content / mtime has changed since the entry was recorded.

Method SourceCollectionManager.mark_ingested

Update the sources table after a successful ingest run.

mark_ingested(source_id: str, pages_generated: list[str], status: str = 'ingested') -> SourceManifestEntry | None

Parameter Type Default Description
source_id str The source to update.
pages_generated list[str] List of wiki page IDs produced by the ingest.
status str 'ingested' New lifecycle status (defaults to "ingested").

Returns: SourceManifestEntry | None — The updated :class:SourceManifestEntry, or None if source_id is not tracked.

Method SourceCollectionManager.record_decision

Register or update a source with its supervised-ingestion decision.

Sibling to :meth:mark_ingested (FEAT-402, TASK-2073): handles ALL three triage destinations, including "discard" — a rejected document may never have been registered via :meth:add_source at all (the triage router evaluates raw scanned files, not already-tracked sources), so this method creates a new entry when the URI isn't tracked yet rather than requiring one to already exist. Per spec §2: rejected docs are recorded with status="rejected" and are never ingested (no pages).

record_decision(path: Path, *, destination: str, decision_source: str | None = None, charter_version: str | None = None, composite_score: float | None = None, pages_generated: list[str] | None = None, status: str | None = None, external_id: str | None = None) -> SourceManifestEntry

Parameter Type Default Description
path Path Path to the source document.
destination str Triage destination — "wiki", "archive", or "discard".
decision_source str | None None Who/what made the decision — "heuristic", "model", "human", or "auto".
charter_version str | None None Editorial charter version the decision was made against (audit/reproducibility).
composite_score float | None None The weighted composite triage score.
pages_generated list[str] | None None Wiki page IDs produced, if any. Left as the existing value (or empty) when not given — rejected / archived-without-pages documents pass None or [].
status str | None None Lifecycle status override. Defaults to "rejected" when destination == "discard", else "ingested".
external_id str | None None FEAT-472 immutable external identity in "<source>:<id>" form. None (default) leaves any existing value on the row unchanged when the source is already tracked, or leaves it unset for a new source.

Returns: SourceManifestEntry — The created or updated :class:SourceManifestEntry.

Method SourceCollectionManager.record_document_metadata

Persist FEAT-451 extracted document metadata for a tracked source.

Sibling to :meth:mark_ingested/:meth:record_decision: updates the descriptive document-metadata columns on an already-tracked source. Unlike :meth:record_decision, this method never creates a new entry — document metadata is only meaningful once the source itself is tracked (e.g. via :meth:add_source or :meth:record_decision).

record_document_metadata(source_id: str, *, doc_metadata: dict[str, Any] | None, content_type: str | None, loader: str | None) -> None

Parameter Type Default Description
source_id str The tracked source to update.
doc_metadata dict[str, Any] | None Extracted DocumentMetadata as a dict, or None.
content_type str | None MIME type of the source document, or None.
loader str | None Name of the loader used to extract the document, or None.

Method SourceCollectionManager.remove_source

Remove a source from the sources table.

remove_source(source_id: str) -> bool

Parameter Type Default Description
source_id str The stable source identifier to remove.

Returns: bool — True if the entry existed and was removed; False if source_id was not present.

Method SourceCollectionManager.find_by_uri

Look up an existing source ID by URI (public API).

find_by_uri(source_uri: str) -> str | None

Parameter Type Default Description
source_uri str The URI to search for.

Returns: str | None — The matching source_id, or None if not tracked.

Method SourceCollectionManager.find_by_external_id

Look up a source by its immutable external identity.

find_by_external_id(external_id: str) -> SourceManifestEntry | None

Parameter Type Default Description
external_id str "<source>:<id>" value to search for (e.g. "fireflies:abc123").

Returns: SourceManifestEntry | None — The matching :class:SourceManifestEntry, or None if no row carries that external_id.

Method SourceCollectionManager.find_entries_by_external_ids

Look up many sources by external id in as few statements as possible.

find_entries_by_external_ids(external_ids: list[str]) -> dict[str, SourceManifestEntry]

Parameter Type Default Description
external_ids list[str] "<source>:<id>" values to search for.

Returns: dict[str, SourceManifestEntry] — Mapping of external_id -> entry, containing only the ids that are actually tracked.

Method SourceCollectionManager.list_by_external_prefix

List every source whose external_id starts with prefix.

list_by_external_prefix(prefix: str) -> list[SourceManifestEntry]

Parameter Type Default Description
prefix str External-id prefix to match, e.g. "fireflies:".

Returns: list[SourceManifestEntry] — Matching entries; rows with a None external_id or a different prefix are excluded.

Method SourceCollectionManager.set_external_id

Set (or clear) the external identity of an already-tracked source.

set_external_id(source_id: str, external_id: str | None) -> SourceManifestEntry | None

Parameter Type Default Description
source_id str The tracked source to update.
external_id str | None New "<source>:<id>" value, or None to clear it.

Returns: SourceManifestEntry | None — The updated :class:SourceManifestEntry, or None if source_id is not tracked.

Method SourceCollectionManager.update_source_uri

Repoint a tracked source at a new path, keeping its source_id.

Used by repair flows that move/rename the underlying file: the row's identity (source_id, and any external_id) survives the move; only source_uri/file_hash/mtime change.

update_source_uri(source_id: str, new_uri: Path | str) -> SourceManifestEntry | None

Parameter Type Default Description
source_id str The tracked source to update.
new_uri Path | str The file's new location. Must exist.

Returns: SourceManifestEntry | None — The updated :class:SourceManifestEntry, or None if source_id is not tracked.

Raises:

  • FileNotFoundError — If new_uri does not exist.
  • ValueError — If new_uri is already tracked under a different source_id (would otherwise surface as a sqlite3.IntegrityError on the source_uri UNIQUE constraint).

Alias SourceManifestEntry

Re-exported from parrot.knowledge.wiki.models.SourceManifestEntry.

Alias create_source_backend

Re-exported from parrot.knowledge.wiki.sources_backend.create_source_backend.

Function format_decision_log_details

Format a WikiBookkeeper log line for a supervised-ingestion decision.

FEAT-402 (TASK-2073): pairs with :meth:SourceCollectionManager. record_decision. Callers pass the formatted string as the details argument to WikiBookkeeper.log_operation(wiki_dir, operation, details), choosing operation from "TRIAGE"/"ADMIT"/"ARCHIVE"/"DISCARD" — free-string tags, no enum (see bookkeeper.py module docstring). This helper only formats the details line; it does not call log_operation itself, since the caller (TASK-2074's orchestrator wiring) owns the wiki_dir and WikiBookkeeper instance.

format_decision_log_details(entry: SourceManifestEntry) -> str

Parameter Type Default Description
entry SourceManifestEntry The source manifest entry with the recorded decision (typically the return value of record_decision).

Returns: str — A single-line, human-readable details string: source URI, composite score, decision source, and charter version.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally