Skip to content

API Reference parrot.knowledge.contracts.library

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

parrot.knowledge.contracts.library

View source

Staged contract ingestion and canonical source identity (FEAT-539 M4).

:class:ContractLibrary is the ingestion entry point: it validates a source, resolves its identity (URI first, then content hash), builds the PageIndex tree in a staging root, cards it under the bounded 1 + N budget, archives the derived evidence immutably and persists the card, obligations, version and publication work in one catalog transaction. The staged tree is promoted only after that transaction commits, so a failure anywhere in between leaves the previously published card/evidence pair usable.

Verification and refresh (TASK-3035) and judged relations (TASK-3040) extend this same class.

Class ContractLibrary

Ingest, card and publish contracts for one tenant.

Parameter Type Default Description
catalog ContractCatalogStore The tenant-bound authoritative catalog.
storage_root str | Path Root of the tenant's PageIndex storage (published and staging trees live underneath it).
evidence_root str | Path Root of the immutable evidence archive.
adapter Any None A PageIndexLLMAdapter-shaped object, or None for deterministic no-LLM ingestion.
indexer_factory Optional[Callable[[Path, Any], TreeIndexer]] None (storage_dir, adapter) -> TreeIndexer. Defaults to a real :class:PageIndexToolkit.
content_store_factory Optional[Callable[[Path], Any]] None storage_dir -> NodeContentStore.
owner_rules Sequence[OwnerRule] () Folder-path ownership rules.
max_obligation_sections int DEFAULT_MAX_OBLIGATION_SECTIONS The N of the 1 + N carding budget.
max_candidates int 8 Bound on relation candidates per source contract.
relation_stage Any None Pre-built ContractRelationStage (optional).
relate_on_ingest bool False Judge relations after each successful ingestion.
now Callable[[], datetime] _utcnow Clock for recorded timestamps.
today Callable[[], date] _today Clock for contractual derivations.

Method ContractLibrary.add_contract

Ingest one document, returning a card or an explicit reason.

add_contract(source: str | Path, *, source_uri: Optional[str] = None, force: bool = False) -> IngestResult

Parameter Type Default Description
source str | Path Path to the document on disk.
source_uri Optional[str] None Canonical location; defaults to the local path.
force bool False Re-card even when the content hash is unchanged.

Returns: IngestResult — class:IngestResult — added/updated with a card, or skipped/error with a reason. Never raises for expected outcomes (unsupported format, unreadable file, scanned PDF).

Method ContractLibrary.add_folder

Ingest every supported document in a folder, deterministically.

add_folder(folder: str | Path, *, recursive: bool = False, force: bool = False) -> IngestReport

Parameter Type Default Description
folder str | Path Folder to walk.
recursive bool False Walk sub-folders too.
force bool False Re-card unchanged content.

Returns: IngestReport — class:IngestReport with one row per document.

Method ContractLibrary.verify_card

Confirm or correct card fields on behalf of an authenticated human.

fields=None verifies the whole current card and refuses while required evidence gaps, unresolved low-confidence fields or stale fields remain. A mapping verifies only the paths it names: a value equal to the current one (or None) is a confirmation — the origin is untouched — while a different value is a correction, which additionally moves the origin to manual.

verify_card(contract_id: str, fields: Optional[Mapping[str, Any]] = None, *, user: str, expected_revision: Optional[int] = None) -> VerificationResult

Parameter Type Default Description
contract_id str The card to verify.
fields Optional[Mapping[str, Any]] None path -> value to confirm/correct, or None.
user str Authenticated actor stamped on every touched field.
expected_revision Optional[int] None Revision the caller read; a concurrent write raises :class:CatalogConflictError.

Returns: VerificationResult — class:VerificationResult.

Raises:

  • UnknownContractError — When the contract does not exist.
  • KeyError — When a requested path is not correctable.
  • CatalogConflictError — On a stale expected_revision.

Method ContractLibrary.refresh_card

Re-card a contract while preserving every human decision.

Verified values survive: unchanged nonempty evidence is rebound to its new node, and changed or missing evidence keeps the prior value, records the new one as a candidate and marks the field stale.

refresh_card(contract_id: str, *, source: Optional[str | Path] = None) -> IngestResult

Parameter Type Default Description
contract_id str The contract to refresh.
source Optional[str | Path] None Path to the new bytes; defaults to the recorded source_path and then the canonical source_uri.

Returns: IngestResult — class:IngestResult (skipped when nothing changed).

Raises:

  • UnknownContractError — When the contract does not exist.

Method ContractLibrary.apply_amendment_history

Record a verified amendment on its base contract's history.

Only a verified effective date and a resolved parent may create a new contractual interval: an unknown effective date stays unresolved instead of becoming today.

apply_amendment_history(amendment_id: str, *, user: str) -> Optional[ContractVersion]

Parameter Type Default Description
amendment_id str The amendment's contract id.
user str Authenticated actor recorded on the base card's write.

Returns: Optional[ContractVersion] — The version appended to the base contract, or None when the preconditions are not met.

Method ContractLibrary.relate_contracts

Judge contract relations explicitly (never during retrieval).

relate_contracts(contract_ids: Optional[Sequence[str]] = None, *, force: bool = False) -> 'RelationStageReport'

Parameter Type Default Description
contract_ids Optional[Sequence[str]] None Source contracts to judge; None means the whole active catalog.
force bool False Re-judge pairs that already carry an active judgement, appending a new record and replacing the active result.

Returns: 'RelationStageReport' — The relation stage's report.

Method ContractLibrary.load_section

Read current source evidence, including trees published before hash markers.

The immutable archive also stays available if tree promotion failed. Its catalog reference binds the body to the requested source version.

load_section(contract_id: str, node_id: str, *, source_sha256: str) -> Optional[str]

Parameter Type Default Description
contract_id str
node_id str
source_sha256 str

Returns: Optional[str]

Method ContractLibrary.published_loader

Return a node-body loader over the published tree.

published_loader(contract_id: str, *, source_sha256: Optional[str] = None) -> Callable[[str], Optional[str]]

Parameter Type Default Description
contract_id str
source_sha256 Optional[str] None

Returns: Callable[[str], Optional[str]]

Method ContractLibrary.evidence_reference

Build a tenant-bound evidence reference for this library.

evidence_reference(contract_id: str, *, version_n: int, revision: int, source_sha256: str) -> EvidenceRef

Parameter Type Default Description
contract_id str
version_n int
revision int
source_sha256 str

Returns: EvidenceRef

Class OwnerRule

A folder-path rule assigning ownership at ingest time.

The most specific (longest) matching prefix wins; when nothing matches the card is left unassigned rather than guessed.

Fields:

Field Type Default Description
path_prefix str
owner_employee_id Optional[str] None
department Optional[str] None

Attribute SUPPORTED_FORMATS

Type: dict[str, SourceFormat]

Class TreeIndexer

The PageIndex surface the library depends on.

Satisfied by :class:~parrot.knowledge.pageindex.toolkit.PageIndexToolkit and by test doubles.

Method TreeIndexer.create_tree

create_tree(tree_name: str, doc_name: Optional[str] = None) -> dict[str, Any]

Parameter Type Default Description
tree_name str
doc_name Optional[str] None

Returns: dict[str, Any]

Method TreeIndexer.insert_markdown

insert_markdown(tree_name: str, markdown: str, parent_node_id: Optional[str] = None, doc_name: Optional[str] = None) -> dict[str, Any]

Parameter Type Default Description
tree_name str
markdown str
parent_node_id Optional[str] None
doc_name Optional[str] None

Returns: dict[str, Any]

Method TreeIndexer.get_tree

get_tree(tree_name: str) -> dict[str, Any]

Parameter Type Default Description
tree_name str

Returns: dict[str, Any]

Method TreeIndexer.delete_tree

delete_tree(tree_name: str) -> dict[str, Any]

Parameter Type Default Description
tree_name str

Returns: dict[str, Any]

Attribute VERIFIABLE_PATHS

Type: tuple[str, ...]

Class VerificationResult

What one verify_card call confirmed, corrected or blocked.

Fields:

Field Type Default Description
card ContractCard
verified list[str]
corrected list[str]
blockers list[str]

Attributes:

Attribute Type Description
card_verified bool Whether the whole card is now verified.

Function deterministic_sections

Section heading-less text deterministically.

Splits on blank lines and packs paragraphs into stable, numbered sections so a TXT (or heading-less markdown) document still produces a navigable tree without a model.

deterministic_sections(text: str, *, chunk_chars: int = _DEFAULT_SECTION_CHARS, title_prefix: str = 'Section') -> str

Parameter Type Default Description
text str The raw document text.
chunk_chars int _DEFAULT_SECTION_CHARS Target characters per section.
title_prefix str 'Section' Heading prefix for generated sections.

Returns: str — Markdown with ## <title_prefix> N headings.

Function get_card_field

Read one card field by its provenance path.

get_card_field(card: ContractCard, path: str) -> Any

Parameter Type Default Description
card ContractCard The card to read.
path str A dotted path such as "term.notice_days" or "parties.<party_id>.name".

Returns: Any — The current value.

Raises:

  • KeyError — When the path does not address a known field.

Function merge_verified_fields

Carry human decisions across a refresh.

For every field a human verified on previous:

  • a nonempty quote found verbatim in the refreshed bodies proves the evidence is unchanged — the verified value and its verification are preserved and the evidence is rebound to the node that now holds it;
  • changed or missing evidence (and an empty quote, which never proves anything) keeps the previous value, records the incoming value as a separate candidate and marks the field stale for review.

merge_verified_fields(previous: ContractCard, incoming: ContractCard, bodies: Mapping[str, str]) -> ContractCard

Parameter Type Default Description
previous ContractCard The currently published card.
incoming ContractCard The freshly carded card.
bodies Mapping[str, str] node_id -> markdown of the refreshed tree.

Returns: ContractCard — The merged card.

Function pdf_markdown

Render extracted PDF page text as page-anchored markdown.

Each page becomes a ## Page N section so evidence keeps a physical page anchor even when model-dependent indexing is unavailable.

pdf_markdown(pages: Sequence[str]) -> str

Parameter Type Default Description
pages Sequence[str] Text of each page, in order.

Returns: str — Page-anchored markdown (empty when no page carried text).

Function set_card_field

Return a copy of card with one field corrected.

set_card_field(card: ContractCard, path: str, value: Any) -> ContractCard

Parameter Type Default Description
card ContractCard The card to correct.
path str A verifiable provenance path.
value Any The corrected value.

Returns: ContractCard — The updated card.

Raises:

  • KeyError — When the path is not correctable.

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