Python API Reference¶
The okf_schema.api module provides a clean, typed Python interface for all okf-schema operations.
Schema-declared file links¶
File-link semantics belong to the base API, not to either opinionated layer.
Use validate_bundle(..., check_links=True) to check a generic OKF, OKFKB, or
OKFREQ bundle against its own annotated schemas. Checking is disabled by default
and never rewrites documents or installs annotations into existing schemas.
from okf_schema.api import validate_bundle
report = validate_bundle("knowledge", check_links=True, project_root=".")
for finding in report.errors + report.warnings:
print(finding.code, finding.path, finding.message)
A parser that already has frontmatter and a schema can call the same checker
directly. Annotate a scalar for one link or string items for a list of links:
from pathlib import Path
from okf_schema.api import check_file_links
schema = {
"properties": {
"evidence": {
"type": "array",
"items": {
"type": "string",
"x-okf-link": {
"resolution": "bundle-relative-stem",
"syntax": "plain",
},
},
}
}
}
diagnostics = check_file_links(
{"evidence": ["observations/cache-run"]},
schema,
Path("bundle/concepts/cache.md"),
bundle_root=Path("bundle"),
)
This checks bundle/observations/cache-run.md. Missing targets produce E10;
an unavailable bundle root produces W15 rather than silently approving the
link. The return values are FileLinkDiagnostic objects with severity,
code, message, and field_path (for example, evidence[0]).
See Write a custom schema for all resolution
modes and plain/wikilink syntax, KB setup for
Finding evidence, and requirement frontmatter for
implementation and test evidence.
Use inspect_file_links when a consumer needs successful resolutions as well as
diagnostics. It returns one FileLinkResult per applicable annotated value,
including the resolved path, parsed query/fragment/label, and valid, invalid,
or unavailable status:
from okf_schema.api import inspect_file_links
results = inspect_file_links(
{"evidence": ["observations/cache-run"]},
schema,
Path("bundle/concepts/cache.md"),
bundle_root=Path("bundle"),
)
for result in results:
print(result.field_path, result.status, result.resolved_path)
check_file_links is the compatibility-oriented projection that returns only
the E10 and W15 diagnostics. Neither function scans headings, marker lines,
or test results; navigation metadata remains advisory for downstream consumers.
- okf_schema.api.inspect_file_links(frontmatter, schema, document_path, *, bundle_root=None, project_root=None, _context=None)¶
Inspect every
x-okf-linkvalue, including successful values.Added in version 0.13.0.
- Parameters:
frontmatter (
dict[str,Any]) – Parsed document frontmatter to inspect.schema (
dict[str,Any]) – JSON Schema containing optionalx-okf-linkannotations.document_path (
Path) – Markdown document whose frontmatter is being checked.bundle_root (
Path|None) – Bundle root for bundle-relative and filename-stem references.project_root (
Path|None) – Explicit project root for project-relative references. When it is unavailable, the containing Git root of document_path is used._context (_FileLinkContext | None)
- Return type:
list[FileLinkResult]- Returns:
One structured result for each applicable annotated value. Successful results include their resolved path and parsed suffix components.
- class okf_schema.api.FileLinkResult(value, value_identity, field_path, array_index, syntax, resolution, target, normalized_target, resolved_path, query, fragment, label, status, code, severity, message)¶
A structured result for one annotated frontmatter value.
Added in version 0.13.0.
Changed in version 0.13.0:
value_identityis an escaped JSON Pointer, distinct from the human-readablefield_path. Stem indexes are scoped to one inspection.statusis"valid"for a resolved target,"invalid"for anE10result, and"unavailable"for a skippedW15check.value_identityis the stable JSON Pointer identity used by consumers;array_indexis populated separately for an annotated array item.- Parameters:
value (Any)
value_identity (str)
field_path (str)
array_index (int | None)
syntax (str | None)
resolution (str | None)
target (str | None)
normalized_target (str | None)
resolved_path (Path | None)
query (str | None)
fragment (str | None)
label (str | None)
status (Literal['valid', 'invalid', 'unavailable'])
code (Literal['E10', 'W15'] | None)
severity (Literal['error', 'warning'] | None)
message (str)
- class okf_schema.api.FileLinkDiagnostic(severity, code, message, field_path)¶
A result from opt-in file-link checking.
severityis"error"for a resolvable invalid target or malformed annotation and"warning"for a check that was deliberately skipped.- Parameters:
severity (Literal['error', 'warning'])
code (Literal['E10', 'W15'])
message (str)
field_path (str)
Bundle operations¶
- okf_schema.api.validate_bundle(bundle_path, schema_db=None, *, check_links=False, project_root=None)¶
Validate an OKF bundle.
- Parameters:
bundle_path (
str|Path) – Path to the OKF bundle directory.schema_db (
str|Path|None) – Optional directory containing JSON or YAML schema files. If not provided, the_schemasubdirectory inside the bundle is used automatically when it exists.check_links (
bool) – Enable opt-inx-okf-linktarget checking.project_root (
str|Path|None) – Explicit project root for project-relative links. If unavailable, the containing Git root of each document is used.
- Return type:
- Returns:
A
Reportwith all errors and warnings.- Raises:
FileNotFoundError – When bundle_path does not exist.
NotADirectoryError – When bundle_path is not a directory.
- okf_schema.api.format_bundle(bundle_path, check=False, diff=False)¶
Format frontmatter in all concept files of an OKF bundle.
- Parameters:
bundle_path (
str|Path) – Path to the OKF bundle directory.check (
bool) – IfTrue, do not modify files; only report changes needed.diff (
bool) – IfTrue, include unified diffs in results without modifying files.
- Return type:
list[FormattedResult]- Returns:
List of
FormattedResult, one per markdown file.- Raises:
FileNotFoundError – When bundle_path does not exist.
NotADirectoryError – When bundle_path is not a directory.
Examples
>>> from tempfile import TemporaryDirectory >>> from okf_schema.api import format_bundle >>> with TemporaryDirectory() as directory: ... results = format_bundle(directory, check=True)
- okf_schema.api.lint_bundle(bundle_path, check=False, diff=False, links=False)¶
Lint frontmatter in all concept files of an OKF bundle.
Converts block-style (multi-line) lists to inline notation so that frontmatter stays compact. This is important for coding agents that load only the first n lines of a file.
- Parameters:
bundle_path (
str|Path) – Path to the OKF bundle directory.check (
bool) – IfTrue, do not modify files; only report changes needed.diff (
bool) – IfTrue, include unified diffs in results without modifying files.links (
bool) – IfTrue, also updatelinksandbacklinksfrontmatter fields based on markdown body content.
- Return type:
list[FormattedResult]- Returns:
List of
FormattedResult, one per markdown file.- Raises:
FileNotFoundError – When bundle_path does not exist.
NotADirectoryError – When bundle_path is not a directory.
Examples
>>> from tempfile import TemporaryDirectory >>> from okf_schema.api import lint_bundle >>> with TemporaryDirectory() as directory: ... results = lint_bundle(directory, check=True, links=True)
- okf_schema.api.list_bundle(bundle_path)¶
List all concepts in an OKF bundle.
- Parameters:
bundle_path (
str|Path) – Path to the OKF bundle directory.- Return type:
list[ConceptSummary]- Returns:
Sorted list of
ConceptSummaryobjects.- Raises:
FileNotFoundError – When bundle_path does not exist.
NotADirectoryError – When bundle_path is not a directory.
- okf_schema.api.show_bundle(bundle_path, concept_path)¶
Show a single concept’s frontmatter and body.
- Parameters:
bundle_path (
str|Path) – Path to the OKF bundle directory.concept_path (
str) – Relative path to the concept markdown file.
- Return type:
- Returns:
A
ConceptDetailwith frontmatter dict and body text.- Raises:
FileNotFoundError – When the concept file does not exist.
- okf_schema.api.index_bundle(bundle_path)¶
Regenerate all
index.mdfiles in an OKF bundle.For each directory containing markdown files, generates or updates an
index.mdlisting child concepts and subdirectories. Preserves bundle-root frontmatter if present.- Parameters:
bundle_path (
str|Path) – Path to the OKF bundle directory.- Return type:
list[IndexUpdate]- Returns:
List of
IndexUpdaterecords describing what changed.- Raises:
FileNotFoundError – When bundle_path does not exist.
NotADirectoryError – When bundle_path is not a directory.
- okf_schema.api.search_bundle(bundle_path, query)¶
Search concepts in an OKF bundle.
Performs a case-insensitive substring search across
title,description,type, andtagsfrontmatter fields.- Parameters:
bundle_path (
str|Path) – Path to the OKF bundle directory.query (
str) – Search string.
- Return type:
list[SearchResult]- Returns:
Sorted list of matching
SearchResultobjects.- Raises:
FileNotFoundError – When bundle_path does not exist.
NotADirectoryError – When bundle_path is not a directory.
- okf_schema.api.stats_bundle(bundle_path)¶
Compute statistics for an OKF bundle.
- Parameters:
bundle_path (
str|Path) – Path to the OKF bundle directory.- Return type:
- Returns:
A
BundleStatsobject with file counts, link counts, type/tag distributions, and directory counts.- Raises:
FileNotFoundError – When bundle_path does not exist.
NotADirectoryError – When bundle_path is not a directory.
- okf_schema.api.graph_bundle(bundle_path)¶
Build a concept link graph for an OKF bundle.
Parses all internal markdown links in concept bodies and returns an adjacency dictionary mapping each concept’s relative path to the list of concept paths it links to.
- Parameters:
bundle_path (
str|Path) – Path to the OKF bundle directory.- Returns:
{concept_path: [linked_path, ...]}.- Return type:
dict[str,list[str]]- Raises:
FileNotFoundError – When bundle_path does not exist.
NotADirectoryError – When bundle_path is not a directory.
- okf_schema.api.backlinks_bundle(bundle_path, targets)¶
Find all concepts that link to any of the given target concepts.
For each target path, scans every concept in the bundle and returns a backlink record for each concept that contains an internal markdown link pointing to that target. Reserved files (
index.md,log.md) are excluded as sources. Self-links are ignored.Targets may be given with or without the
.mdextension.- Parameters:
bundle_path (
str|Path) – Path to the OKF bundle directory.targets (
list[str]) – List of relative concept paths to find backlinks for.
- Return type:
list[BacklinkResult]- Returns:
Sorted list of
BacklinkResultrecords, one per backlink. Results are ordered by(target, source).- Raises:
FileNotFoundError – When bundle_path does not exist.
NotADirectoryError – When bundle_path is not a directory.
- okf_schema.api.validate_markdown_files(input_patterns, schemas_dir=None, *, check_links=False, bundle_root=None, project_root=None)¶
Validate standalone markdown files against JSON schemas.
This is useful for validating markdown files with frontmatter that are not part of a full OKF bundle. Each pattern is resolved using pathlib’s glob syntax (supports
**for recursive matching).- Parameters:
input_patterns (
list[str] |str) – One or more glob patterns (for example,"docs/**/*.md"). Can be a single string or a list of strings. Patterns are resolved relative to the current working directory. Absolute paths are also supported.schemas_dir (
str|Path|None) – Optional directory containing JSON or YAML schema files. If not provided, schema validation is skipped. Because no schema database was requested, missing-schema (W6) warnings are not emitted. Schema files should be named<type>.schema.{json|json5|yaml|yml}.check_links (
bool) – Enable opt-inx-okf-linktarget checking.bundle_root (
str|Path|None) – Optional bundle root for bundle-relative and filename-stem links.project_root (
str|Path|None) – Explicit project root for project-relative links. If unavailable, the containing Git root of each document is used.
- Return type:
- Returns:
A
Reportwith all errors and warnings.- Raises:
FileNotFoundError – When schemas_dir does not exist (if provided).
NotADirectoryError – When schemas_dir is not a directory (if provided).
- okf_schema.api.rewrite_superseded_links(bundle_path, check=False)¶
Rewrite markdown body links pointing to superseded documents.
Scans all documents for
status: supersededwith asuperseded_byfield. For each such document, every other document whose markdown body links to it has that link rewritten to the firstsuperseded_bypath.The
links/backlinksfrontmatter fields are not updated here; they are refreshed by the subsequentlint_bundle()call thatupdate_bundle()performs automatically.- Parameters:
bundle_path (
str|Path) – Path to the OKF bundle directory.check (
bool) – IfTrue, report rewrites without modifying files.
- Return type:
tuple[list[SupersededRewrite],list[DeferredRewrite]]- Returns:
A tuple
(rewrites, deferred)where rewrites lists performed replacements and deferred lists superseded docs whose links could not be automatically updated (missing or non-existentsuperseded_by).- Raises:
FileNotFoundError – When bundle_path does not exist.
NotADirectoryError – When bundle_path is not a directory.
Examples
>>> from pathlib import Path >>> from tempfile import TemporaryDirectory >>> from okf_schema.api import rewrite_superseded_links >>> with TemporaryDirectory() as directory: ... bundle = Path(directory) ... old = "---\nstatus: superseded\nsuperseded_by: [new.md]\n---\n" ... source = "---\ntype: concept\n---\nSee [old](old.md).\n" ... _ = (bundle / "old.md").write_text(old) ... _ = (bundle / "new.md").write_text("---\ntype: concept\n---\n") ... _ = (bundle / "source.md").write_text(source) ... rewrites, deferred = rewrite_superseded_links(bundle, check=True) ... (len(rewrites), len(deferred)) (1, 0)
- okf_schema.api.update_bundle(bundle_path, check=False, diff=False, links=True)¶
Regenerate indexes and lint frontmatter in an OKF bundle.
Combines
rewrite_superseded_links(),index_bundle(), andlint_bundle()into a single operation. This is the recommended command for keeping a knowledge base up to date after edits.The superseded-link rewriting pass runs first so that the subsequent lint pass can update the
links/backlinksfrontmatter to reflect the rewritten targets.- Parameters:
bundle_path (
str|Path) – Path to the OKF bundle directory.check (
bool) – IfTrue, do not modify files; only report changes needed.diff (
bool) – IfTrue, include unified diffs in results without modifying files.links (
bool) – IfTrue, also updatelinksandbacklinksfrontmatter fields based on markdown body content.
- Return type:
- Returns:
An
UpdateResultwith index, lint, and rewrite results.- Raises:
FileNotFoundError – When bundle_path does not exist.
NotADirectoryError – When bundle_path is not a directory.
Examples
>>> from tempfile import TemporaryDirectory >>> from okf_schema.api import update_bundle >>> with TemporaryDirectory() as directory: ... result = update_bundle(directory, check=True, links=True)
Result types¶
- class okf_schema.api.UpdateResult(index_updates, lint_results, superseded_rewrites=<factory>, deferred_rewrites=<factory>)¶
Result of updating an OKF bundle (index + lint).
- Parameters:
index_updates (list[IndexUpdate])
lint_results (list[FormattedResult])
superseded_rewrites (list[SupersededRewrite])
deferred_rewrites (list[DeferredRewrite])
- class okf_schema.api.SupersededRewrite(source, old_target, new_target)¶
A link in a document rewritten from a superseded target to its replacement.
- Parameters:
source (str)
old_target (str)
new_target (str)
- class okf_schema.api.DeferredRewrite(superseded_doc, reason)¶
A superseded document whose backlinks could not be automatically rewritten.
- Parameters:
superseded_doc (str)
reason (str)
Result identities and inspection lifetime¶
value_identity is an escaped JSON Pointer: /a.b identifies a literal dotted
key, /a/b identifies a nested key, and /attachments/0 identifies an array
item. ~ and / in keys escape as ~0 and ~1; the document root is the empty
string. Use this identity for editor state and matching results; field_path
remains a human-readable label such as attachments[0] and is not a unique key.
A local $ref and its siblings both constrain union applicability. Only the
selected then or else branch contributes conditional annotations. A literal
null character in a target produces E10 rather than interrupting inspection.
Filename-stem resolution indexes Markdown candidates once per bundle in an inspection or validation campaign. The index is discarded after the call, so a later call observes added files and newly ambiguous names. There is no global cache and callers do not need to invalidate editor state.