Repository navigation
okf-parser 0.48.0
okf-parser 0.48.0
Bundle.sql(), okf-parser sql and the MCP sql tool
Phase 4b of RFC 0024. A bundle now
answers SQL, run by the binary over the tables okf-parser duckdb exports:
concepts, links, reserved and diagnostics and, with a spec template,
one typed table per declared type, all on the search path.
Bundle.sql(query, spec_template=None, limit=None)returns aSqlResult
(columnswith their DuckDB types,rows,truncated,to_dicts()),
computed from the snapshot theBundleholds. Values come back as Python
values by column type:Decimal,date,datetime(UTC-aware for
TIMESTAMP WITH TIME ZONE),bytes, parsedJSON, and nested lists,
structs and maps.okf-parser sql PATH "QUERY"prints the same answer as JSON, and the
read-only MCPsqltool answers it with at most 1000 rows. Graph questions
become queries:WITH RECURSIVEoverlinksanswers reachability.- The query cannot read files, reach the network, load extensions or change
settings, and is exactly one query; anything else raisesSqlError(a
ValueError) and is a command or tool error, reported against the query's
own text.
Bundle.compile_types() and TypedRelations are removed with their ibis
tables: query the typed tables through Bundle.sql(..., spec_template=...).
The GraphQL adapter reads declared values that way too.
apply commits and new documents are written by the native binary
Phase 3c of RFC 0024. Every apply
path computes its diff through DuckDB, the --type/--field/--from/--to
sugar included, so the DuckDB planning stays in Python until phase 4 and
everything after it moves to the binary:
__apply-snapshotgives the planner the concepts and a digest of the
bundle it read;__apply-commitsnapshots again and refuses with
the bundle changed while apply was planning itif anything the plan
depended on changed. Concepts are compared by content, so a document
edited and reverted in between does not count.- Frontmatter is edited losslessly with
yaml-edit: comments, quoting and
layout outside the touched keys are kept. Documents the old ruamel-based
check refused as not round-tripping (flow mappings, anchors, tags) are now
edited instead of skipped. Every edit is parsed back and must equal the
intended mapping, or the document is reported inskipped_paths. - The candidate is fingerprinted, staged, validated and committed on the
native write engine, the same oneedituses. Preview tokens are now
okf-apply-preview-v2-sha256:; a v1 token no longer matches. dumpsandimportrender new documents natively (serde_yaml_ng,
through a batched__render):type,titleanddescriptionfirst,
every other key sorted, and the output parsed back before it is used.
importtherefore orders a row's fields canonically rather than by
column order, and multi-line values use block scalars.
okf_parser.write_support and the ruamel.yaml dependency are gone.
apply runs in the binary, and its contract is simpler
Phase 4c of RFC 0024. okf-parser apply, the MCP apply_preview/apply_write tools and apply_bundle() are
planned and committed by the binary in one request; the Python side is a
pydantic wrapper.
The planner used to accept a narrow grammar (leading ALTER TABLEs and one
UPDATE, on one type) and reconstruct intent from it. Now the final state is
the truth:
- Each concept type is a table. The script is any sequence of statements,
run whole in a sandboxed in-memory DuckDB: no files, network, extensions or
setting changes. Several types can change in one script. - A changed value sets the field, as text.
NULLwhere a value existed, or a
dropped or renamed column, removes the field.SET x = NULLon an explicit
x: nullkeeps it. - Rows, the
__okf_*columns, declared fields (with--spec-template) and
structured (list or mapping) fields are not writable; a script that touches
them is refused with the reason and nothing is written.
Breaking. A retyped column (ALTER COLUMN ... TYPE INTEGER) is no longer
refused: its values are written as text. Declared fields are read-only under
--spec-template; run apply without the template to edit them as text.
apply_preview is now annotated read-only and idempotent. The hidden
__apply-snapshot/__apply-commit commands are replaced by __apply.
import reads its source through the binary too (__read-source), every
value as DuckDB's own VARCHAR cast of it: booleans import as true/false
rather than Python's True/False, and lists as DuckDB spells them.
ibis, pyarrow, pandas and numpy are no longer dependencies.
check, inventory, graph and init run in the native binary
Phase 3b of RFC 0024.
The binary now answers check, inventory, graph and init itself, as
CLI commands and as MCP tools, without starting Python. Their JSON output and
exit status are unchanged. That covers check --classify, --require-spec
and --normative-spec: the OKF010 and OKF011 type-specification rules
and the specification scaffold of init are now in
okf-engine/src/specs.rs, pinned against the Python slug by the shared
conformance/type-spec-slugs.json. Two variants still need DuckDB and are
passed to Python until phase 4: check --relational-schema and
init --infer-schema.
The Python paths these replace are gone: okf_parser.classification, the
type-specification checks in okf_parser.type_specs, the specification
scaffold in okf_parser.spec_scaffold, and the inventory/graph handlers
in the service, CLI and MCP bridge. validate_path and check_bundle now
ask the binary (__check) and add only the DuckDB relational diagnostics.
Behavior changes:
ConceptRecord.frontmatter_jsonfromload_bundleis now the binary's
spelling, the same one TypeScript and the DuckDB extension already
received: compact JSON with keys in UTF-16 order, as the parsed digest is
computed. It was re-serialized in Python withjson.dumps(sort_keys=True)
(spaced, code-point order), so Python alone disagreed with the other
surfaces. The parsed value is unchanged.check --classifyno longer lists Markdown undernode_modules/as
ignored: like.git, it is never a candidate.- A specification template without
{slug}is refused even for a bundle
with no typed concepts, instead of only once a type needed it. - A bundle root that does not exist reports
bundle root is not a directory: <path> (<reason>). initcreates each specification stub exclusively (staged, then
hard-linked into place): a document another writer created after the plan
is left untouched instead of being overwritten.ParsedDocument.frontmatter_jsonuses the same compact, UTF-16-ordered
spelling, so every Python record agrees with the binary.okf-parser --helplists every public command. The binary declares the
whole command line and passes the Python-backed commands' arguments,
--helpincluded, through unparsed.check --relational-schemavalidates relations against the same bundle
snapshot the rest of the report describes.
ingestion discovers files the way a load does
ingest_documents() asked a Python walker which Markdown files a bundle
has, while every command asked the engine. The two disagreed on one thing:
the Python walker descended into node_modules, so ingestion could yield
documents a bundle load never reads. Discovery is now the engine's alone,
over a __discover request, and okf_parser.ingestion.discover() exposes
it.
.okfignore semantics are unchanged; conformance/exclusion.json is now
pinned by a Rust test against the engine's matcher, where the nearest rule
decides and !vendor/knowledge re-includes below an excluded vendor.
A corrupt .okfignore is a ValueError naming the file. Removed Python
internals: okf_parser.discovery and okf_parser.exclusion.
The release workflow's conformance job no longer names the deleted Python
corpus tests (it would have failed at the next tag); it runs the engine's
corpus tests instead, and a test now checks that every test file a
workflow names exists.
duckdb, relational checks and starter schemas run in the binary
Phase 4a of RFC 0024. The binary now
carries DuckDB itself, through the duckdb crate in a new okf-db crate, and
answers these without Python:
okf-parser duckdband the MCPduckdb_exporttool.--helpnow
documents the command. The export runs in one transaction: a refused
export, a typed-table collision included, leaves nothing behind.check --relational-schemaand the MCPchecktool with
relational_schema.OKF020-OKF022are native diagnostic codes.init --infer-schemaand the MCPinit_*tools withinfer_schema,
from the same read of the bundle as the specification scaffold.
okf-parser duckdb now writes knowledge.duckdb by default, not
okf.duckdb. DuckDB names a database after its file, so in okf.duckdb a
query for okf.concepts was ambiguous between the database okf and the
schema okf and failed. Pass the database name to keep the old file.
Messages are clearer. Relational diagnostics name the type, the key and
its value (`Book` isbn = "1" is already used by a.md (constraint `Book_isbn_pkey`)) instead of Python tuple reprs, and a refused export
says to pass --overwrite or choose another --schema.
In the Python API, okf_parser.duckdb.attach_okf is removed: exporting
into a caller's own connection has no counterpart in the binary. Use
okf_parser.service.export_duckdb(path, database), which raises
okf_parser.service.BundleExportError on a collision. validate_relations
and okf_parser.spec_scaffold are removed too: validate_path(..., relational_schema=...) and init_bundle(..., infer_schema=True) answer
from the binary. parse_declared_schema and parse_relational_schema keep
their signatures and run their SQL in the binary.
Starter schemas no longer type a field BOOLEAN because its values are
1/0 or t/f, which DuckDB also casts to booleans: only true and
false, in any case, make a boolean, so a 1/0 field is BIGINT.
Wheels ship DuckDB's own prebuilt library (with its JSON, Parquet and ICU
extensions) next to the okf-parser executable, pinned by SHA-256 and
checked on every platform before upload; the npm native package carries it
too. Building from source compiles DuckDB in instead. Typed-table timestamps
are still cast in UTC, so a TIMESTAMPTZ without an offset means the same
instant in every session.
format runs in the binary and rewrites syntax only
Phase 5 of RFC 0024. okf-parser format, the MCP format_check/format_write tools and format_path() run
okf_engine::format, a surgical formatter over pulldown-cmark: it rewrites only
the tokens that spell a document's structure, at their source offsets, and
keeps every other byte.
The canonical form:
-bullets (*for a list right after another bullet list, so the two stay
distinct), consecutive ordered numbering from the list's start, never
zero-padded, one space after each marker;*and**emphasis, ATX headings, compact tables (| a | b |,
| --- | :-: |), backslash hard breaks;- single blank lines between blocks, no trailing whitespace, one final newline;
- a blank line after frontmatter, and simple frontmatter keys ordered
type,
title,description, then by name, as before.
Text, code, HTML, links and escapes are never touched: the rendering
formatters considered (comrak, dprint) escaped x86_64 and #25 or dedented
fenced code. A rewrite must parse to the same document as the original, or the
file is skipped.
Breaking. The report replaces skipped_paths with skipped, a list of
{path, reason} (FormatReport.skipped_paths remains as a property in
Python). --write now replaces every changed file or, on a write error, none.
Documents formatted by mdformat mostly stay as they are; tables with padded
columns and _emphasis_ change once. mdformat, mdformat-gfm and
mdformat-frontmatter are no longer dependencies; okf_parser.markdown_style
and okf_parser.frontmatter_order are removed.
Native import preserves structured source values
The Rust-native importer no longer flattens DuckDB LIST and STRUCT values
to strings before rendering frontmatter. Collection shape is preserved
recursively, while number and boolean leaves keep the parser's existing OKF
scalar contract by using their textual spelling.
Writes remain UTF-8/LF through the native staged byte writer.
import runs in the binary
Phase 6a of RFC 0024. okf-parser import, the MCP import_preview/import_write tools and import_bundle()
run okf_db::import: the source is read by DuckDB, each row is rendered as
<type slug>/<id slug>.md by the engine's canonical renderer, and
verify-identical compares parsed digests. Writes are still staged and
renamed one document at a time.
The preview_token is now bound to DuckDB's text of every value, so a token
printed by 0.47 or earlier does not validate a 0.48 write: preview again.
--expected-preview-token is available on the command line too.
the parser and commit messages run in the binary; Pydantic is the only dependency
Phase 6d of RFC 0024, the last one.
parse_document(), parse_document_text() and ingest_documents() parse
with the engine's strict parse_text over a batched __parse request:
every YAML scalar keeps its authored spelling as a string, and a tag JSON
cannot carry (!!binary, !!set) is still an error. Ingestion reads files
as before and parses 256 documents per native call.
Commit messages are parsed, validated and formatted by
okf_engine::git_commit; the Python API is unchanged and the shared
vectors pass in both. The hook is now okf-parser commit-msg PATH [--require-envelope], replacing python -m okf_parser.git_commit_cli.
markdown-it-py and PyYAML leave the runtime dependencies, so a plain
install is okf-parser and Pydantic. Link destinations from
markdown_facts() keep their authored spelling (path with spaces.md)
instead of markdown-it's percent-encoding, as the bundle loader already
did. Removed Python internals: iter_markdown_links, iter_headings,
has_markdown_suffix, looks_like_frontmatter_link, split_link_target
and split_optional_frontmatter from okf_parser.parser, and
source_digest, parsed_digest and normalize_newlines from
okf_parser.digests.
schema runs in the binary
Phase 6b of RFC 0024. okf-parser schema and the MCP schema tool run okf_db::schema: observed frontmatter,
--infer-types and --cast, declared .schema.sql types, relational
references (--relational-schema, --refs key|embed) and type: Projection
documents compile to one contract set, which the binary renders as JSON
Schema, Zod or GraphQL SDL. Output is byte-for-byte what 0.47 printed; the
shared conformance/schema-output.json and schema-inference.json corpora
pin it.
Pydantic stays in Python, where its naming rules live: --format pydantic
pipes the contracts to python -m okf_parser.pydantic_source (OKF_PYTHON
picks the interpreter), and build_pydantic_models(),
export_pydantic_source() and GraphQLReadAdapter decode the same contracts
from the binary. The MCP server no longer delegates any tool, so
okf_parser.mcp_bridge is gone.
Removed Python internals: okf_parser.projections,
okf_parser.projection_export, okf_parser.schema_references,
okf_parser.schema_lexemes, and the compiler and renderers in
okf_parser.schema_contract (compile_contracts, contract_json_schema,
node_json_schema, node_zod, render_zod, parse_casts,
unique_model_names) and okf_parser.graphql_adapter.render_graphql_sdl.
The export_*, build_* and schema_bundle() entry points keep their
signatures; SchemaReferenceError and ProjectionError now live in
okf_parser.schema_contract.
search runs in the binary, as a command, an MCP tool and Bundle.search()
Phase 4d of RFC 0024. RFC 0016 search
moves to okf_engine::search and gets a surface:
okf-parser search PATH QUERYanswerslocation<TAB>snippetrows, with
--mode literal,--limit,--context,--type,--path,--detail score|fulland--exclude.- The read-only MCP
searchtool, in the default profile, answers compact rows
as text andfullresults as structured content. Bundle.search()is the method form ofsearch_bundle(), which now runs on
the binary over the snapshot theBundleholds.
The built-in BM25 scorer and its results are unchanged; the shared conformance
cases pass as before.
Removed. The optional DuckDB FTS path: fts is not linked into DuckDB's
release builds and loading it needs INSTALL, which search must never run, so
it only answered where the extension had been installed by hand, with scores
that differed from every other machine. okf_parser.materialization
(materialize_sqlite_hot, open_sqlite_memory_copy) and
okf_parser.body_lines are removed too.
The duckdb Python package is no longer a dependency: nothing in the package
imports it. Read an exported .duckdb file with any DuckDB client.
type packs are data, and the Python CLI is gone
Phase 6c of RFC 0024. A type pack is
now a directory with a pack.json manifest and the ordinary OKF files it
lists. okf-parser packs and add-pack run in the binary
(okf_engine::packs): the shipped journalism pack is embedded, and
add-pack ./my-pack installs any local pack directory. Output is unchanged,
a collision still writes nothing and now exits 1 from the binary, and a
path or symbolic link that would leave the destination is refused.
Breaking: the okf_parser.packs entry-point group and
okf_parser.type_packs are gone; publish a pack as a directory instead.
With the last delegated command native, python -m okf_parser.cli and the
cyclopts dependency (with rich, rich-rst and docstring-parser) leave.
The write engine and body edits run in the native binary
Phase 3a of RFC 0024. The conflict-safe
write protocol shared by every writer (snapshot, stage and validate a
candidate bundle, recheck freshness, replace files atomically) now lives in
okf-engine/src/write.rs. preview_concept_edit and write_concept_edit run
entirely in the binary through a new __edit protocol command, with the same
arguments and result shape as before. okf_parser.edit is now a thin shell.
The native commit is also stricter than the Python one it replaces. Each write
stages into its own uniquely named sibling file. A multi-file commit rolls back
the files it already replaced if a later rename fails. The freshness recheck
and the commit run under an exclusive lock on .okf-write.lock at the bundle
root, so two concurrent writers can no longer both pass the recheck and
silently overwrite each other; the second reports a conflict. The lock file is
never treated as part of the bundle.
RFC 0024 also records two decisions: import, init --infer-schema and SQL
apply move with DuckDB (phase 4), and YAML writing will use maintained
libraries (yaml-edit for lossless edits, a serializer for new documents)
rather than hand-written emitters.
The Rust code as a whole now models its domain in types rather than strings,
with every public JSON, MCP and DuckDB shape unchanged:
- Engine, YAML, write and MCP failures are error enums (
LoadError,
FrontmatterError,WriteError, the MCP bridge errors) that keep their
causes; they become text only in the protocol, CLI and MCP adapters.
Diagnostic messages keep their exact wording. - Diagnostic
codeandseverity, reservedfilenameand linkoriginare
enums that serialize to the same strings as before. - Bundle paths are converted to text in one place (
BundlePath), which
refuses a path with no UTF-8 spelling instead of silently replacing bytes
with U+FFFD, since that could give two files the same concept id. On Unix,
a backslash in a file name is now kept as written, matching the Python
engine'sas_posix(). - The canonical JSON behind
parsed_digestandfrontmatter_jsonis written
from borrowed values, with no mapping clones and no per-comparison UTF-16
buffers; a test pins it byte for byte against the previous writer.
load_bundle, check_report and validate_path accept text paths
load_bundle, check_report and validate_path take str | os.PathLike[str]
and normalise with Path(...).resolve(). A str path used to fail with
AttributeError: 'str' object has no attribute 'resolve'.