Skip to content

API Reference parrot.knowledge.wiki.store

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

parrot.knowledge.wiki.store

View source

WikiStore — single-file SQLite retrieval plane for the LLM Wiki.

Machine-first knowledge storage (follow-up to FEAT-260): every wiki query is answered from indexed SQL — no YAML/markdown parsing, no tree walks, and no dual-toolkit fan-out at retrieval time.

Design (mirrors graphindex/persist_sqlite.py patterns):

  • One wiki.db per wiki (WAL journal mode, aiosqlite).
  • pages — page bodies live IN the database, keyed by stable concept_id (volatile PageIndex node_id kept as a secondary column). category and edge rel are open strings — no enum ceremony in the machine plane.
  • edges — typed relations (summarizes, references, …).
  • sources — absorbs the former .manifest.json manifest (SHA-1 + mtime staleness detection).
  • pages_fts — FTS5/BM25 lexical index over title/summary/body (external-content, mirrors pages by rowid, trigger-maintained).
  • embeddings — optional per-page vectors for cosine re-ranking.
  • meta — schema version + wiki name.

The store is a derived retrieval plane: PageIndex remains the authoring/structuring engine, and the database can always be rebuilt from a PageIndex tree via :meth:WikiStore.rebuild_from_tree.

Class AttrsUnsupportedError

Raised when a backend or plane cannot persist page attributes.

Class BaseWikiStore

Contract for wiki retrieval-plane backends.

Every consumer (wiki/search.py, wiki/ingest.py, wiki/toolkit.py, wiki/export.py) talks only to this surface, so backends are interchangeable via :func:create_wiki_store:

  • :class:SQLiteWikiStore — single-file wiki.db (FTS5/BM25).
  • :class:InMemoryWikiStore — RAM indexes persisted as an OKF markdown bundle directory (wiki/file_store.py).

search_fts is the lexical-search entry point on all backends (the name predates the second backend; semantics are backend-defined lexical ranking, not necessarily SQLite FTS).

Attributes:

Attribute Type Description
supports_attrs bool

Method BaseWikiStore.get_attrs

Return persisted attrs, or an empty mapping when unsupported.

get_attrs(concept_id: str) -> dict[str, str]

Parameter Type Default Description
concept_id str

Returns: dict[str, str]

Method BaseWikiStore.list_by_attrs

Return matching page stubs without bodies; unsupported stores return none.

list_by_attrs(filters: Mapping[str, str | Sequence[str]], *, date_key: str | None = None, since: str | None = None, until: str | None = None, limit: int = 200) -> list[dict[str, Any]]

Parameter Type Default Description
filters Mapping[str, str | Sequence[str]]
date_key str | None None
since str | None None
until str | None None
limit int 200

Returns: list[dict[str, Any]]

Method BaseWikiStore.upsert_attrs

Persist attrs only on supported writable stores.

upsert_attrs(concept_id: str, attrs: Mapping[str, str], *, replace: bool = True) -> int

Parameter Type Default Description
concept_id str
attrs Mapping[str, str]
replace bool True

Returns: int

Raises:

  • AttrsUnsupportedError — Always, on backends without attrs support.

Method BaseWikiStore.upsert_pages

upsert_pages(pages: list[WikiPageRecord]) -> int

Parameter Type Default Description
pages list[WikiPageRecord]

Returns: int

Method BaseWikiStore.add_edges

add_edges(edges: list[tuple]) -> int

Parameter Type Default Description
edges list[tuple]

Returns: int

Method BaseWikiStore.replace_source_slice

replace_source_slice(source_id: str, pages: list[WikiPageRecord], edges: Optional[list[tuple[str, str, str]]] = None) -> dict[str, Any]

Parameter Type Default Description
source_id str
pages list[WikiPageRecord]
edges Optional[list[tuple[str, str, str]]] None

Returns: dict[str, Any]

Method BaseWikiStore.delete_page

delete_page(concept_id: str) -> bool

Parameter Type Default Description
concept_id str

Returns: bool

Method BaseWikiStore.upsert_embedding

upsert_embedding(concept_id: str, vector: list[float], model: str = '') -> None

Parameter Type Default Description
concept_id str
vector list[float]
model str ''

Method BaseWikiStore.get_page

get_page(concept_id: str, include_body: bool = True) -> Optional[dict[str, Any]]

Parameter Type Default Description
concept_id str
include_body bool True

Returns: Optional[dict[str, Any]]

Method BaseWikiStore.list_pages

list_pages(category: Optional[str] = None, limit: int = 100, origin: Optional[list[str]] = None) -> list[dict[str, Any]]

Parameter Type Default Description
category Optional[str] None
limit int 100
origin Optional[list[str]] None

Returns: list[dict[str, Any]]

Method BaseWikiStore.search_fts

search_fts(query: str, category: Optional[str] = None, limit: int = 10) -> list[dict[str, Any]]

Parameter Type Default Description
query str
category Optional[str] None
limit int 10

Returns: list[dict[str, Any]]

Method BaseWikiStore.search_vector

search_vector(embedding: list[float], limit: int = 10) -> list[dict[str, Any]]

Parameter Type Default Description
embedding list[float]
limit int 10

Returns: list[dict[str, Any]]

Method BaseWikiStore.neighbors

neighbors(concept_id: str, rel: Optional[str] = None, direction: str = 'both') -> list[dict[str, Any]]

Parameter Type Default Description
concept_id str
rel Optional[str] None
direction str 'both'

Returns: list[dict[str, Any]]

Method BaseWikiStore.dump_pages

dump_pages() -> list[dict[str, Any]]

Returns: list[dict[str, Any]]

Method BaseWikiStore.dump_edges

dump_edges() -> list[dict[str, Any]]

Returns: list[dict[str, Any]]

Method BaseWikiStore.stats

stats() -> dict[str, Any]

Returns: dict[str, Any]

Method BaseWikiStore.orphan_sources

orphan_sources() -> list[str]

Returns: list[str]

Method BaseWikiStore.broken_edges

broken_edges() -> list[dict[str, Any]]

Returns: list[dict[str, Any]]

Method BaseWikiStore.rebuild_index

Rebuild derived search indexes and repair meta.

Default is a no-op for backends without derived indexes.

rebuild_index() -> dict[str, Any]

Returns: dict[str, Any] — {"rebuilt": [<index names>]}.

Method BaseWikiStore.index_drift

Return {index_name: row_count_delta} for drifted indexes; {} when clean.

index_drift() -> dict[str, int]

Returns: dict[str, int]

Method BaseWikiStore.missing_bodies

missing_bodies() -> list[str]

Returns: list[str]

Method BaseWikiStore.compare_and_swap_page

Insert only if absent, or atomically replace an exact hash.

The one write primitive with a revision precondition (FEAT-578 Module 2). Every managed adr mutation goes through it, so a concurrent reviewer can never silently overwrite another's audit history.

compare_and_swap_page(page: WikiPageRecord, expected_content_hash: Optional[str]) -> bool

Parameter Type Default Description
page WikiPageRecord The full replacement record. Its content_hash is the new stored hash.
expected_content_hash Optional[str] The hash the caller last read. None means insert-only — succeed if the row is absent, fail if any row already exists (it does NOT match a NULL hash).

Returns: bool — True when the write landed; False when the precondition did not hold (row present for an insert, or a differing stored hash). A False return is a lost race, not an error.

Raises:

  • NotImplementedError — On backends that do not support a conditional write. Concrete by design rather than abstract, so out-of-tree BaseWikiStore subclasses stay instantiable; callers surface this as ADR_WRITE_UNSUPPORTED.
  • PermissionError — When the store was opened read-only.

Method BaseWikiStore.get_meta

Read one plane-level metadata value (FEAT-609 Q2).

get_meta(key: str) -> Optional[str]

Parameter Type Default Description
key str Metadata key (e.g. "extractor_fingerprint").

Returns: Optional[str] — The stored string, or None when the key is absent.

Raises:

  • NotImplementedError — When the backend has no meta support.

Method BaseWikiStore.set_meta

Write one plane-level metadata value (FEAT-609 Q2).

set_meta(key: str, value: str) -> None

Parameter Type Default Description
key str
value str

Raises:

  • NotImplementedError — When the backend has no meta support.
  • PermissionError — When the store was opened read-only.

Method BaseWikiStore.rebuild_from_tree

Rebuild page rows from a PageIndex tree (derived-plane refresh).

Backend-agnostic: walks every node once and calls :meth:upsert_pages. Page identity prefers concept_id (assigned by splice_subtree) and falls back to node_id. Bodies are loaded through content_loader (typically NodeContentStore.loader_for(tree_name)).

rebuild_from_tree(tree: dict[str, Any], content_loader: Optional[Callable[[str], Optional[str]]] = None, source_id: Optional[str] = None) -> dict[str, Any]

Parameter Type Default Description
tree dict[str, Any] PageIndex tree dict ({"structure": [...]}).
content_loader Optional[Callable[[str], Optional[str]]] None node_id -> markdown callable, or None to store summary-only rows.
source_id Optional[str] None Optional source id stamped on every rebuilt page.

Returns: dict[str, Any] — {"pages_written": N}

Raises:

  • PermissionError — When the store is read-only.

Method BaseWikiStore.upsert_symbols

Persist symbol rows in a native symbol store (default: no-op).

Backends without a native symbols table already persist symbols as sym: pages via :meth:upsert_pages / :meth:replace_source_slice — this default simply does nothing.

upsert_symbols(symbols: list[SymbolRecord], source_id: Optional[str] = None) -> int

Parameter Type Default Description
symbols list[SymbolRecord] Symbol records to persist.
source_id Optional[str] None Originating source id.

Returns: int — 0 — no rows written by the default implementation.

Method BaseWikiStore.symbols_for

List every symbol extracted from one file.

Default: filters :meth:list_pages (category="symbol") by the page's node_id (== rel_path for a sym: page).

symbols_for(rel_path: str) -> list[SymbolRecord]

Parameter Type Default Description
rel_path str POSIX path relative to the repository root.

Returns: list[SymbolRecord] — class:~parrot.knowledge.wiki.symbols.SymbolRecord list (best-effort — see func:~parrot.knowledge.wiki.symbols.symbol_from_page).

Method BaseWikiStore.find_symbols

Find symbols by name/qualname/kind/language/path filters.

Default: linear scan over :meth:list_pages (category="symbol") — adequate at wiki scale for backends without a native index.

find_symbols(name: Optional[str] = None, qualname_prefix: Optional[str] = None, kind: Optional[str] = None, language: Optional[str] = None, path_prefix: Optional[str] = None, limit: int = 50) -> list[SymbolRecord]

Parameter Type Default Description
name Optional[str] None Exact local-name filter.
qualname_prefix Optional[str] None Qualname must start with this prefix.
kind Optional[str] None Exact :class:SymbolKind value filter.
language Optional[str] None Exact scanner-name filter.
path_prefix Optional[str] None rel_path must start with this prefix.
limit int 50 Maximum results.

Returns: list[SymbolRecord] — Matching, decoded symbol records (name matches ranked first).

Method BaseWikiStore.search_symbols_fts

Lexical search over symbols (default: :meth:search_fts).

search_symbols_fts(query: str, limit: int = 20) -> list[SymbolRecord]

Parameter Type Default Description
query str Free-form query text.
limit int 20 Maximum results.

Returns: list[SymbolRecord] — Decoded symbol records ranked by the backend's lexical score.

Method BaseWikiStore.page_hashes

Look up content_hash for a batch of page ids.

Default: one :meth:get_page call per id.

page_hashes(concept_ids: list[str]) -> dict[str, Optional[str]]

Parameter Type Default Description
concept_ids list[str] Page ids to look up (file: or sym:).

Returns: dict[str, Optional[str]] — {concept_id: content_hash_or_None} for every requested id.

Attribute MIGRATION_BACKUP_KEEP

Type: int

Attribute MIN_RUNTIME_KEY

Attribute SCHEMA_VERSION

Class SQLitePragmaPolicy

Validated SQLite connection policy for one wiki plane.

Fields:

Field Type Default Description
busy_timeout_s float 15.0 Seconds a connection waits for the writer lock before SQLite gives up. Installed both as the connect-time timeout= (which registers the busy handler) and as PRAGMA busy_timeout (which makes the setting readable back for diagnostics).
performance_pragmas bool False Opt-in memory-oriented tuning (mmap, cache, temp-store). Off by default so that N concurrent agents do not each map excessive memory.
journal_size_limit int 67108864 Bytes of WAL retained after a successful checkpoint. Defaults to 64 MiB.

Class SQLiteWikiStore

Async single-file SQLite retrieval plane for one wiki.

Example::

store = WikiStore(storage_dir / "wiki.db", wiki_name="my-wiki")
await store.upsert_pages([WikiPageRecord(concept_id="intro", ...)])
hits = await store.search_fts("neural networks", limit=5)
Parameter Type Default Description
db_path str | Path Path of the wiki.db file. Parent directories are created automatically (except in read-only mode).
wiki_name str '' Optional wiki name recorded in the meta table.
read_only bool False Open the plane strictly for reading (FEAT-450). No parent mkdir, no schema replay, no column migration and no sidecar creation — every connection goes straight to :meth:_connect_readonly, and every write method raises :class:PermissionError. Used for foreign namespaces, whose planes belong to another project and must never be mutated by a read here.
sqlite_policy SQLitePragmaPolicy | None None
persistent_writer bool False

Attributes:

Attribute Type Description
supports_attrs bool
db_path Path Path of the underlying SQLite file.
read_only bool Whether this store was opened strictly for reading.

Method SQLiteWikiStore.upsert_pages

Insert or update wiki pages (and their FTS index rows).

upsert_pages(pages: list[WikiPageRecord]) -> int

Parameter Type Default Description
pages list[WikiPageRecord] Page records to write.

Returns: int — Number of pages written.

Raises:

  • PermissionError — When the store is read-only.

Method SQLiteWikiStore.compare_and_swap_page

Conditionally write one page inside a single immediate transaction.

See :meth:BaseWikiStore.compare_and_swap_page for the contract.

compare_and_swap_page(page: WikiPageRecord, expected_content_hash: Optional[str]) -> bool

Parameter Type Default Description
page WikiPageRecord
expected_content_hash Optional[str]

Returns: bool

Method SQLiteWikiStore.add_edges

Insert typed edges.

add_edges(edges: list[tuple]) -> int

Parameter Type Default Description
edges list[tuple] (src, dst, rel) or (src, dst, rel, provenance) tuples; rel is an open string. A missing provenance defaults to 'extracted'.

Returns: int — Number of edges written.

Raises:

  • PermissionError — When the store is read-only.

Method SQLiteWikiStore.replace_source_slice

Atomically replace all pages/edges derived from one source.

Deletes existing pages whose source_id matches (plus their FTS rows, embeddings, and any edges touching them), then inserts the replacements — so re-ingest never accumulates duplicates.

Incoming edges from OTHER sources (e.g. a directory contains edge, or a references edge from an importing file) are preserved when the replacement re-inserts the same stable concept_id — the slice owns its outgoing edges, but links pointing INTO it stay valid across a re-ingest.

replace_source_slice(source_id: str, pages: list[WikiPageRecord], edges: Optional[list[tuple[str, str, str]]] = None) -> dict[str, Any]

Parameter Type Default Description
source_id str Source whose derived pages are being replaced.
pages list[WikiPageRecord] Replacement page records.
edges Optional[list[tuple[str, str, str]]] None Optional replacement (src, dst, rel) edges.

Returns: dict[str, Any] — {"pages_deleted": N, "pages_written": M, "edges_written": K}

Raises:

  • PermissionError — When the store is read-only.

Method SQLiteWikiStore.delete_page

Delete a page and its FTS row, embeddings, and edges.

delete_page(concept_id: str) -> bool

Parameter Type Default Description
concept_id str Page identity to delete.

Returns: bool — True when a page row was actually deleted.

Raises:

  • PermissionError — When the store is read-only.

Method SQLiteWikiStore.upsert_attrs

Write attrs for an EXISTING page in one immediate transaction.

upsert_attrs(concept_id: str, attrs: Mapping[str, str], *, replace: bool = True) -> int

Parameter Type Default Description
concept_id str Page to annotate; unknown pages are not created.
attrs Mapping[str, str] Attribute mapping (values are stored as text).
replace bool True True replaces the page's whole attr set (an empty mapping clears it); False merges, overwriting only the given keys.

Returns: int — Number of attr rows written; 0 when the page is missing.

Raises:

  • PermissionError — When the store is read-only.

Method SQLiteWikiStore.get_attrs

Return the persisted attrs of one page (empty when none/unsupported).

get_attrs(concept_id: str) -> dict[str, str]

Parameter Type Default Description
concept_id str

Returns: dict[str, str]

Method SQLiteWikiStore.list_by_attrs

List page stubs (no bodies) whose attrs match every filter.

Filters are ANDed across keys; a non-string sequence value means IN. since/until are inclusive ISO-date bounds applied to the attr named date_key. With no filters and no date bounds, every page that has at least one attr is returned. Keys and values are always bound parameters.

list_by_attrs(filters: Mapping[str, str | Sequence[str]], *, date_key: str | None = None, since: str | None = None, until: str | None = None, limit: int = 200) -> list[dict[str, Any]]

Parameter Type Default Description
filters Mapping[str, str | Sequence[str]] {key: value | [values]}.
date_key str | None None Attr key the date bounds apply to.
since str | None None Inclusive lower ISO-date bound.
until str | None None Inclusive upper ISO-date bound.
limit int 200 Maximum rows (newest updated_at first).

Returns: list[dict[str, Any]] — Stub dicts including an attrs mapping; [] on a plane without page_attrs.

Raises:

  • ValueError — A date bound was given without date_key.

Method SQLiteWikiStore.upsert_embedding

Store (or replace) the embedding vector for a page.

upsert_embedding(concept_id: str, vector: list[float], model: str = '') -> None

Parameter Type Default Description
concept_id str Page the vector belongs to.
vector list[float] Embedding as a list of floats (stored as float32).
model str '' Identifier of the embedding model used.

Raises:

  • PermissionError — When the store is read-only.

Method SQLiteWikiStore.upsert_symbols

Insert or update rows in the native symbols table.

The symbols_ai/symbols_au triggers mirror every row into symbols_fts — this must never touch the FTS table itself.

upsert_symbols(symbols: list[SymbolRecord], source_id: Optional[str] = None) -> int

Parameter Type Default Description
symbols list[SymbolRecord] Symbol records to persist.
source_id Optional[str] None Originating source id, stamped on every row.

Returns: int — Number of symbols written.

Raises:

  • PermissionError — When the store is read-only.

Method SQLiteWikiStore.symbols_for

List every symbol row extracted from one file.

symbols_for(rel_path: str) -> list[SymbolRecord]

Parameter Type Default Description
rel_path str POSIX path relative to the repository root.

Returns: list[SymbolRecord] — Symbol records for rel_path, ordered by start_line.

Method SQLiteWikiStore.find_symbols

Find symbols in the native symbols table by filter.

find_symbols(name: Optional[str] = None, qualname_prefix: Optional[str] = None, kind: Optional[str] = None, language: Optional[str] = None, path_prefix: Optional[str] = None, limit: int = 50) -> list[SymbolRecord]

Parameter Type Default Description
name Optional[str] None Exact local-name filter.
qualname_prefix Optional[str] None Qualname must start with this prefix.
kind Optional[str] None Exact :class:SymbolKind value filter.
language Optional[str] None Exact scanner-name filter.
path_prefix Optional[str] None rel_path must start with this prefix.
limit int 50 Maximum results.

Returns: list[SymbolRecord] — Matching symbol records — exact name matches first (when name is not itself a filter), then by rel_path, qualname.

Method SQLiteWikiStore.search_symbols_fts

BM25 lexical search over symbols_fts (name/qualname/doc/signature).

search_symbols_fts(query: str, limit: int = 20) -> list[SymbolRecord]

Parameter Type Default Description
query str Free-form query text.
limit int 20 Maximum results.

Returns: list[SymbolRecord] — Symbol records ranked by BM25 score (best match first).

Method SQLiteWikiStore.get_meta

Read key from the meta table (works on read-only planes).

get_meta(key: str) -> Optional[str]

Parameter Type Default Description
key str

Returns: Optional[str]

Method SQLiteWikiStore.set_meta

Upsert key into the meta table.

set_meta(key: str, value: str) -> None

Parameter Type Default Description
key str
value str

Method SQLiteWikiStore.page_hashes

Batch look-up of pages.content_hash for the given ids.

page_hashes(concept_ids: list[str]) -> dict[str, Optional[str]]

Parameter Type Default Description
concept_ids list[str] Page ids to look up (file: or sym:).

Returns: dict[str, Optional[str]] — {concept_id: content_hash_or_None} for every requested id (None both when the row is absent and when its hash is unset).

Method SQLiteWikiStore.get_page

Fetch a single page by concept_id (falls back to node_id).

get_page(concept_id: str, include_body: bool = True) -> Optional[dict[str, Any]]

Parameter Type Default Description
concept_id str Stable page identity — for convenience a volatile PageIndex node_id is also accepted.
include_body bool True When False the body column is omitted (cheaper for stub-only reads).

Returns: Optional[dict[str, Any]] — Page row as a dict, or None when not found.

Method SQLiteWikiStore.list_pages

List page stubs (no bodies), optionally filtered.

list_pages(category: Optional[str] = None, limit: int = 100, origin: Optional[list[str]] = None) -> list[dict[str, Any]]

Parameter Type Default Description
category Optional[str] None Exact category pre-filter (open string).
limit int 100 Maximum rows returned.
origin Optional[list[str]] None Optional origin filter, e.g. ["memory", "authored"] to list only agent-saved knowledge.

Returns: list[dict[str, Any]] — List of stub dicts ordered by updated_at (newest first).

Method SQLiteWikiStore.search_fts

BM25 lexical search over title/summary/body.

search_fts(query: str, category: Optional[str] = None, limit: int = 10) -> list[dict[str, Any]]

Parameter Type Default Description
query str Free-form natural-language query (sanitised before reaching FTS5 — no operator injection).
category Optional[str] None Optional exact category pre-filter (deterministic gate applied before ranking). When None (the default), "archive"-category pages are excluded from the results (FEAT-402 — supervised-ingestion archive pages are opt-in only, retrievable via category="archive").
limit int 10 Maximum results.

Returns: list[dict[str, Any]] — Stub dicts with a score key (higher is better; scores are -bm25 and NOT normalised — callers normalise).

Method SQLiteWikiStore.search_vector

Cosine-similarity search over stored page embeddings.

Brute-force in-process scan — appropriate at wiki scale (10³–10⁴ pages) and keeps the store dependency-free.

search_vector(embedding: list[float], limit: int = 10) -> list[dict[str, Any]]

Parameter Type Default Description
embedding list[float] Query vector.
limit int 10 Maximum results.

Returns: list[dict[str, Any]] — Stub dicts with a score key in [-1, 1] (cosine).

Method SQLiteWikiStore.neighbors

Return edge-adjacent pages/targets of a concept.

neighbors(concept_id: str, rel: Optional[str] = None, direction: str = 'both') -> list[dict[str, Any]]

Parameter Type Default Description
concept_id str Seed page identity.
rel Optional[str] None Optional exact relation filter (open string).
direction str 'both' "out", "in", or "both".

Returns: list[dict[str, Any]] — Dicts with concept_id, rel, direction and — when the target is a known page — its title/summary stub.

Method SQLiteWikiStore.dump_pages

Return every page row WITH bodies (bulk export path).

dump_pages() -> list[dict[str, Any]]

Returns: list[dict[str, Any]] — Full page dicts ordered by concept_id.

Method SQLiteWikiStore.dump_edges

Return every edge row (bulk export path).

dump_edges() -> list[dict[str, Any]]

Returns: list[dict[str, Any]]

Method SQLiteWikiStore.stats

Aggregate counters for the wiki (single fast query set).

stats() -> dict[str, Any]

Returns: dict[str, Any] — {"pages": N, "edges": M, "sources": S, "embeddings": E, "attrs_pages": A, "total_tokens": T, "categories": {...}}

Method SQLiteWikiStore.checkpoint

Fold the WAL back into the database; never raise for live readers.

A single live reader can block TRUNCATE indefinitely. That is normal, observable maintenance — not an error — so this method falls back to PASSIVE, logs the outcome, and reports it. It must never turn an otherwise successful build or ingest into a failure (AC-7).

checkpoint(truncate: bool = True) -> dict[str, int | bool]

Parameter Type Default Description
truncate bool True Attempt TRUNCATE first. When False, only PASSIVE is run.

Returns: dict[str, int | bool] — A report with keys ok (the checkpoint ran at all), mode (the mode that actually took effect), busy (truncation was blocked by a reader), log (pages left in the WAL) and checkpointed (pages moved).

Method SQLiteWikiStore.sqlite_settings

Report the SQLite settings a live connection actually has.

Read back from the connection rather than echoed from the policy, so what the operator sees is what SQLite is really doing (AC-5).

sqlite_settings() -> dict[str, Any]

Returns: dict[str, Any] — journal_mode, busy_timeout_ms, synchronous, journal_size_limit and performance_pragmas.

Method SQLiteWikiStore.orphan_sources

Sources that produced no pages (zero rows in pages).

orphan_sources() -> list[str]

Returns: list[str]

Method SQLiteWikiStore.broken_edges

Edges whose destination is neither a page nor a source.

broken_edges() -> list[dict[str, Any]]

Returns: list[dict[str, Any]]

Method SQLiteWikiStore.missing_bodies

Pages with an empty body (stub rows without content).

missing_bodies() -> list[str]

Returns: list[str]

Method SQLiteWikiStore.rebuild_index

Run FTS5 'rebuild' on pages_fts and symbols_fts and re-stamp schema_version.

rebuild_index() -> dict[str, Any]

Returns: dict[str, Any] — {"rebuilt": ["pages_fts", "symbols_fts"]}.

Method SQLiteWikiStore.index_drift

Compare content-table rows with indexed FTS documents.

The FTS tables are external-content, so COUNT(*) on them reads the content table and can never drift; the <fts>_docsize shadow table holds one row per actually-indexed document and is what is compared.

index_drift() -> dict[str, int]

Returns: dict[str, int] — {fts_table: content_count - indexed_count} for non-zero deltas only.

Attribute STALE_MIGRATION_LOCK_S

Type: float

Alias SymbolRecord

Re-exported from parrot.knowledge.wiki.symbols.SymbolRecord.

Attribute WIKI_FTS_SQL

Attribute WIKI_SCHEMA_SQL

Attribute WIKI_TABLES_SQL

Class WikiBackendSpec

One wiki backend entry of the registry (FEAT-540 M7).

Fields:

Field Type Default Description
name str Backend name (WikiNamespaceConfig.backend / create_wiki_store(backend=...)).
kind Literal['local', 'server'] "local" (on-disk plane under a storage dir) or "server" (server-hosted plane — no local directory).
factory Any Store factory, or a lazy "module:attr" path to it.
resolve_options Any None Optional callable (or lazy "module:attr" path) (cfg) -> dict turning a WikiNamespaceConfig into factory keyword options. None keeps the legacy ArangoDB-params behaviour (only ever used by satellites registered with the two-argument form).
is_built str | None None Optional lazy path of the "is this plane built" probe.
extra str | None None Optional install extra that provides the backend.

Class WikiPageRecord

A single wiki page row in the retrieval plane.

Fields:

Field Type Default Description
concept_id str Stable page identity (primary key, link target).
node_id Optional[str] None Volatile PageIndex node id (secondary lookup only).
title str '' Page title.
category str 'concept' Open-string category (e.g. "summary", "entity").
summary str '' Short summary used for stubs and FTS.
body str '' Full markdown body (lives in the DB — no sidecar reads).
source_id Optional[str] None Originating source id (sources.source_id).
token_count int 0 Estimated token cost of the body.
origin str 'ingest' How the page came to exist — "ingest" (derived from a source), "authored" (written by an agent tool), or "memory" (saved via the remember authoring surface).
asserted_by Optional[str] None Identity of the writer for authored/memory pages, e.g. "agent:<id>" or "human:<user>".
updated_at Optional[str] None ISO-8601 UTC last-modified stamp (FEAT-461). On write, None means "stamp now" — both backends already persist this column and fill it in unconditionally when the caller does not supply one. On read, it is always populated from the DB. A caller-supplied value is preserved verbatim on upsert (never overwritten with "now"), which is what lets sync (TASK-2466) replicate a record without making it look newer than its source. Legacy/defensive None sorts oldest in any last-write-wins comparison.
content_hash Optional[str] None SHA-1 hex digest of the page's source content (FEAT-498) — same digest family as SourceCollectionManager._compute_hash for file: pages, and :func:parrot.knowledge.wiki.symbols.sha1_of_text of the node text for sym: pages. None for pages that predate the freshness plane or are not backed by scanned source (e.g. dir: pages).
attrs dict[str, str] Entity attributes persisted to page_attrs in the same transaction as the page (FEAT-627). On upsert the page's previous attrs are replaced; an empty mapping clears them.

Attribute WikiStore

Class WikiStoreBusy

Writer lock was not acquired within the configured busy timeout.

Subclasses :class:sqlite3.OperationalError so existing handlers keep working; raised ONLY at the BEGIN IMMEDIATE boundary, never for an arbitrary later statement error.

Parameter Type Default Description
db_path Path
operation str
waited_seconds float

Attributes:

Attribute Type Description
db_path Plane whose writer lock was contended.
operation Logical write operation that was waiting.
waited_seconds Configured busy timeout that was exhausted.

Class WikiStoreMigrationError

A stale plane cannot be migrated safely: the migration lock or the pre-migration backup could not be created (spec rev 0.5 C24; PR #1746 review). Never a sqlite3.OperationalError — _read must not degrade it into a read-only open.

Parameter Type Default Description
directory Path
step str
cause BaseException

Class WikiStoreVersionError

The plane's schema_version is newer than the running SCHEMA_VERSION (FEAT-633).

Decided by schema number only. store_minimum (the plane's min_runtime_version stamp) is quoted in the message, never compared. Deliberately NOT a :class:sqlite3.OperationalError: the read ladder in :meth:SQLiteWikiStore._read degrades on OperationalError, and this must never degrade — an older runtime has to fail fast rather than open a newer plane.

Parameter Type Default Description
db_path Path
store_schema str
store_minimum Optional[str]
running str

Method WikiStoreVersionError.newer_schema

The plane's schema_version is newer than SCHEMA_VERSION (the only refusal).

newer_schema(db_path: Path, stored: str, store_minimum: Optional[str], running: str) -> 'WikiStoreVersionError'

Parameter Type Default Description
db_path Path
stored str
store_minimum Optional[str]
running str

Returns: 'WikiStoreVersionError'

Function create_wiki_store

Instantiate the configured wiki retrieval-plane backend.

Selection is explicit (WikiConfig.storage_backend) — there is no silent fallback: a broken/unavailable backend is a hard error.

create_wiki_store(storage_dir: str | Path, wiki_name: str = '', backend: str = 'sqlite', **kwargs: Any) -> BaseWikiStore

Parameter Type Default Description
storage_dir str | Path Wiki storage root. sqlite uses {storage_dir}/wiki.db; memory uses the OKF bundle directory {storage_dir}/pages/. Unused by arangodb and postgres (server-hosted — no local directory).
wiki_name str '' Wiki name recorded by the backend.
backend str 'sqlite' "sqlite" (single-file SQLite plane), "memory" (in-memory indexes + OKF markdown directory), "arangodb" (server-hosted, shared retrieval plane), or "postgres" (server-hosted, shared graphindex.* schema — FEAT-520).
**kwargs Any {} Backend-specific extras. For "arangodb": arango_params (connection params dict for AsyncDB("arangodb", ...) — see :func:parrot.knowledge.wiki.project.resolve_arango_params), database (target database name, defaults to wiki_{wiki_name}), and text_analyzer (ArangoSearch text analyzer, defaults to "text_en"). For "postgres": dsn (defaults to pg_schema.GRAPHINDEX_PG_DSN) and schema (defaults to "graphindex").

Returns: BaseWikiStore — class:BaseWikiStore implementation.

Raises:

  • ValueError — For an unknown backend value.

Function estimate_tokens

Cheap deterministic token estimate for budget accounting.

Uses tiktoken (cl100k_base) when available, falling back to the len(text) // 4 heuristic. The result is stored per page so context packing can budget without re-tokenising at query time.

estimate_tokens(text: str) -> int

Parameter Type Default Description
text str Text to measure.

Returns: int — Estimated token count (>= 0).

Function is_server_backend

Whether name is a server-hosted backend (no local storage dir).

is_server_backend(name: str) -> bool

Parameter Type Default Description
name str

Returns: bool

Attribute logger

Function rank_by_cosine

Rank candidate stubs by cosine similarity to a query vector.

Shared by every backend — brute-force in-process scan, appropriate at wiki scale (10³–10⁴ pages). Candidates whose vector dimension does not match the query are skipped.

rank_by_cosine(embedding: list[float], candidates: list[tuple[dict[str, Any], list[float]]], limit: int = 10) -> list[dict[str, Any]]

Parameter Type Default Description
embedding list[float] Query vector.
candidates list[tuple[dict[str, Any], list[float]]] (stub_dict, vector) pairs.
limit int 10 Maximum results.

Returns: list[dict[str, Any]] — Stub dicts with a score key in [-1, 1], best first.

Function register_wiki_backend

Register a satellite-provided wiki backend (FEAT-449 M7, FEAT-540 M7).

register_wiki_backend(name: str, factory: Callable[..., BaseWikiStore], *, kind: Literal['local', 'server'] = 'server', resolve_options: Callable[[Any], dict[str, Any]] | None = None) -> None

Parameter Type Default Description
name str Backend name (matches WikiNamespaceConfig.backend / create_wiki_store(backend=...)). Must not collide with a built-in name ("sqlite", "memory", "arangodb", "postgres").
factory Callable[..., BaseWikiStore] Callable constructing the store, factory(*, storage_dir=None, wiki_name="", **kwargs) -> BaseWikiStore.
kind Literal['local', 'server'] 'server' "server" (default) or "local".
resolve_options Callable[[Any], dict[str, Any]] | None None (WikiNamespaceConfig) -> dict of factory options used when opening a federated namespace. None keeps the legacy behaviour of passing ArangoDB params (backward compatibility for the two-argument form).

Function resolve_wiki_backend

Return the store factory registered for name.

resolve_wiki_backend(name: str) -> Callable[..., BaseWikiStore]

Parameter Type Default Description
name str

Returns: Callable[..., BaseWikiStore]

Raises:

  • ValueError — For an unknown backend.

Function wiki_backend_names

Return every known backend name (built-ins first, then satellites).

wiki_backend_names() -> list[str]

Returns: list[str]

Function wiki_backend_spec

Return the :class:WikiBackendSpec for name.

wiki_backend_spec(name: str) -> WikiBackendSpec

Parameter Type Default Description
name str

Returns: WikiBackendSpec

Raises:

  • ValueError — For an unknown backend, listing the known ones.

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