Expand description
sokf core: the library half of the sokf command-line interface (CLI).
The binary (crates/app/sokf) parses the arguments and renders the output.
The logic that the binary drives lives here, so that tests can run that
logic without starting a process.
The core loads and validates SOKF knowledge stores, their documents, and
the assets those documents describe, as the core specifications in
sokf-spec/ define them. It also runs the sokf command that
knowledge/contracts/ specifies. Its entry points are init,
harness_install, harness_status, harness_diff, validate, info_formats,
info_grammar, new, graph, guide, and locate. The harness
hook is harness::hook.
SOKF uses the schema language of the tramlines-md engine. This crate
re-exports the engine’s modules under their old sokf-core paths. SOKF
adds its own schema extension, dialect, and model.
This crate is unstable. It is at a 0.x version, and its interface can change in any release.
§Example
use sokf_core::{RepoPath, markdown};
let body = "# Title\n\nA paragraph.\n";
let segments = markdown::segments(body, 1);
let parsed = markdown::parse(body, 1, &segments);
assert_eq!(parsed.headings[0].slug, "title");
assert_eq!(RepoPath::parse("/knowledge/a.md").unwrap().relative(), "knowledge/a.md");Re-exports§
pub use grammar::Compiled;pub use grammar::compile_all;pub use grammar::formats_text;pub use grammar::grammar_text;pub use grammar::load_grammar;pub use graph::Edge;pub use graph::EdgeKind;pub use graph::Entry;pub use graph::Graph;pub use graph::GraphJson;pub use graph::GraphQuery;pub use graph::GraphResult;pub use graph::LocateReport;pub use graph::Location;pub use graph::Node;pub use graph::NodeKey;pub use graph::NodeKind;pub use graph::Row;pub use graph::Start;pub use include::Expected;pub use include::expected;pub use index::IndexEntry;pub use index::Indexes;pub use model::Document;pub use model::FsLoader;pub use model::Knowledge;pub use model::Loader;pub use model::Located;pub use model::Model;pub use model::build;
Modules§
- check
- This module checks documents against the validation specification, with
one submodule for each group of criteria. The check engine checks the
grammar’s rules, and the
hostmodule answers the engine’s questions about the repository. - compare
- The
comparemodule asks the library same-same whether a generated block that differs from its expected text byte for byte means the same as it (design-loading, “Comparing by meaning”). same-same compares the formats that it knows by their meaning, and any other format through the project’s formatter, or else by the bytes. The module builds the two sides of each pair, reads each answer as current or stale, and words the warning of a formatter that failed (CLI-4_AC-49). It passes same-same no type of sokf. - fix
- The
fixmodule repairs files as the validation specification defines: it plans which files to rewrite and move, and then applies those changes on disk. - grammar
- This module holds the grammar: the core grammar of the engine with SOKF’s extension, SOKF’s formats and reference types, and the compilation of every schema in the model.
- graph
- The
graphmodule represents the knowledge as a graph of nodes and edges, which it builds once from the model (CLI-7).buildbuilds the graph,startresolves the start of a command (a key, an id, or a path) to a node,traversewalks the graph from the start nodes to a bounded depth,jsonwrites the graph as JSON, andlocateturns ids into paths (CLI-8). - harness
- The
harnessmodule integrates sokf with agent harnesses (CLI-3) through agent-harness-adapter. It holds sokf’s integration, sokf as a adapterTool, and the hook. The adapter holds the harnesses, the part kinds, the states, the record, andinstallandstatus. - include
- The
includemodule handles generated content (format specification §9). It finds the regions of a file, chooses the length and language tag of the code fence around each file-form include, builds the include graph, and works out the expected content of every generated block. - index
- The
indexmodule builds the generated index of each directory of a knowledge (format specification §9.4). It computes the expected text of each index from the model and the moves that a fix plans, and renders that text. - markdown
- This module reads Markdown in SOKF’s dialect. It runs the parser of the
Markdown engine,
tramlines_md, with SOKF’s markers and itssokf:reference syntax, as sokf-format-spec defines them. - markers
- Markers (sokf-format-spec §9.5). A marker is a comment line in a repository file outside every knowledge store. It cites a key or a document. This module scans a file for markers and resolves what each marker cites.
- model
- This module holds the model of the knowledge in memory: the manifests, schemas, documents, indexes, and additional files of each store. It keys them by id, path, and type.
- scaffold
- This module writes the files of a new store for
sokf init, and edits the config to register a root. It also derives the skeleton thatsokf newcreates a document from. - yaml
- YAML 1.2 core-schema parsing as
TL_13andTL_14read it.
Structs§
- Added
Exclude - An
AddedExcludeis one glob that a file of/.sokf/excludes.d/lists, with the file. - Block
Guide BlockGuideholds the guidance of one block.- Body
- A parsed body.
- Cache
Cacheholds the store and the state of this run’s sync.- Config
Configis the resolved configuration, with every root checked.- Config
Text ConfigTextis the configuration as written, forinitand the harness commands: the roots as listed, whether or not each one is a directory, and the file’s text.- Document
Guide DocumentGuideholds the guidance that a document’s schema gives for the parts that the document’s lifecycle states admit, in the schema’s order (CLI-17_AC-6), with each part’s example (CLI-17_AC-38). Eachtextholds the words of the guidance line that the scaffold of the schema writes before the same part at the same states, and eachexamplethe text that the scaffold writes for the part, with the document’s own frontmatter values.- Expr
Expris a compiled JMESPath expression, kept with the source text it was compiled from.- FileKey
FileKeyidentifies a file’s content for the cache (CACHE-1_AC-1, CACHE-1_AC-2).- Finding
- One line of the report.
- Format
Entry - One line format of the registry: its keys as a formats file writes
them, which the grammar
formatofsokf info grammardefines, such astemplate,example, andvariants, and its source. - Format
Registry - A named set of formats, each with its source, and the hole types the layers declared.
- Format
Type - One placeholder type of the registry.
- Formats
Json - The registry of
sokf info formats --json: the types and the formats of the registry that the command prints as YAML, in the shape of a formats file, each entry with its source (CLI-5_AC-38). - Grammar
- The parsed grammar file.
- Graph
Options GraphOptionsholds the options ofsokf graph.- Guide
Limit GuideLimitis a limit on a part: its kind, the number of units, lines, or elements that it states, and what the writer does at the limit.- Guide
Options GuideOptionsholds the options ofsokf guide.- Guide
Report GuideReportis the report ofsokf guide --json: the guide of each document that an argument names, in the order of the arguments (CLI-17_AC-17).- Harness
Dirs - The directories that
installandstatuswork in. - Harness
Options - The options of
install. - Harness
Report - The report of
sokf harness install --jsonandsokf harness status --json: one entry for each harness named, in sokf’s order of the harnesses, with one entry for each part (CLI-3_AC-20). - Harness
Result - The parts of one harness.
- IdTemplate
- An id template a new document can be filled with.
- Init
Options InitOptionsholds the options ofsokf init.- Init
Result InitResultis the report ofsokf init --json: it holds the directory of the store that the command created. It also holds the files that the command wrote (CLI-2_AC-12).- KeyGuide
KeyGuideholds the guidance of one frontmatter key.- Label
Guide LabelGuideholds one attribution label of the schema.- Link
Guide LinkGuideholds the guidance of onelinksrule.- Loaded
Loadedholds everything that a run derives from the tree before the run checks any document, and records what the run checks.- Locator
- Where in a schema the rule that failed sits: the
idof the schema, and the rule’srule-id, else its section and block position. A finding that a schema rule raises ends with it. - NewOptions
NewOptionsholds the options ofsokf new.- NewResult
NewResultis the report ofsokf new --json: it holds the document that the command builds. Without--write, the command prints the document but does not write it (CLI-6_AC-12). With--write, it also writes the document atpath(CLI-6_AC-72).- Part
Result - One part of a harness.
- PathArg
PathArgis a path argument, written either as a spec path or as a filesystem path (CLI-1_AC-7, CLI-1_AC-8).- Preamble
Guide PreambleGuideholds the guidance of the preamble.- Repo
Formats RepoFormatsholds the formats layers that the repository supplies: the repository layer and the layerformats.d.- Repo
Path - A path relative to the repository root, which starts with
/and uses forward slashes. The path/is the root itself. - Repo
Root - The repository root on disk.
- Report
Reportholds the errors, the warnings, and the fixes of a run.- Rule
Label RuleLabelsays whether the units of a block, or the units of one of its unit rules, carry a label.- Rule
Limit RuleLimitis one limit of a block: its own, or one of a unit rule’s or a line rule’s.- Scope
Scopeholds the files and directories that thePATHSarguments ofvalidatepoint to (CLI-4_AC-2). WhenPATHSis empty, the scope is the whole repository.- Section
Guide SectionGuideholds the guidance of one section.- Segments
- The markers of one body.
- Source
Sourceis one loaded file, with its text normalised to LF.- Spanned
- A value with the line it starts on.
- Stat
Statholds the metadata that the walk reads without opening the file (CACHE-1_AC-1).- Store
View StoreViewis a read-only view of the store file, for the documents that the run reads only from the store. Its queries add to the cache’s query counter.- Sync
Stats SyncStatsholds the counts of a run, for tests and diagnostics: what the sync found, and the work that the run did against the store (contract-cache CACHE-3_AC-4).- Texts
Textsholds sokf’s texts, keyed by language, as a tag in lower case, and by entry, such aslimit.hardorunits.item.- Tree
- A
Treeis the walked repository. - Validate
Options - The options of
sokf validate. - Validate
Report ValidateReportis the report thatsokf validate --jsonprints. It holds every error, every warning, and each repair by--fix(CLI-4_AC-12).- Walked
Dir - A
WalkedDiris one directory that the walk visits under a knowledge root. Each such directory must have an index (SOKF_FORMAT_96). - Walked
File - A
WalkedFileis one file that the walk found.
Enums§
- Cache
Mode CacheModesets whether a run reads and writes the cache.- Error
Errorholds the errors of this crate. Every variant renders a message that the CLI prints unchanged aftererror:.- File
Kind - A
FileKindis the kind of a walked file, as the store structure of sokf-format-spec defines it. - File
State FileStatesays what the sync found a file to be.- FixOp
FixOpis one operation thatvalidate --fixperformed (CLI-4_AC-26).- Format
Source - Where a registry entry comes from.
- Guide
Counts GuideCountsis what the limit of a unit rule or a line rule counts.- Guide
Label GuideLabelsays whether a unit carries a label.- Guide
Limit Kind GuideLimitKindis the kind of a limit.- Harness
Scope - Where a harness integration is installed.
- Info
Layer InfoLayerlists the values of the--layeroption ofsokf info formats(CLI-5).- Line
Ending LineEndingis the line ending of a file’s first line.- Marker
Check MarkerCheckselects what a run does with markers: the run reports a broken marker as an error or as a warning, or it does not check markers at all.- Output
Outputnames each JSON output that the tool prints or writes.- Severity
- How a finding is reported.
- Type
Match - What a placeholder type matches.
- Yaml
- A YAML 1.2 core-schema value.
- Yaml
Error - A construct the YAML dialect refuses (
TL_14), or a syntax error, with its line.
Constants§
- ALL_
HARNESSES ALL_HARNESSESis the harness name that stands for every harness that sokf supports.- CACHE_
DIR CACHE_DIRis the cache directory, relative to the repository root.- STORE_
FILE STORE_FILEis the name of the store file inside the cache directory.- STORE_
FORMAT STORE_FORMATis the version of the store’s tables. Raise it whenever a table changes. A change to what a check finds needs no raise, because the fingerprint of the build in the version changes with the code (CACHE-1_AC-7).
Functions§
- check_
repository check_repositoryloads the knowledge for a check and checks it. It checks the documents of the dirty set, then the readers of each citation that changed. It also runs the checks that run every time, whatever documents are dirty. It stores what the run derived in the cache, and returns every finding: those of the documents it checked, and the cache’s stored findings for the documents it didn’t check.- collect
collectwalks the repository and returns its tree: every file and directory under each knowledge root, then every other file that no exclude and no gitignore rule matches.- discover_
root discover_rootreturns the repository root. When the caller passesgiven, the root is that directory’s canonical path, and the directory must exist. Otherwise the root is the nearest ancestor ofcwdthat holds a.gitdirectory or file. The root is canonical so that a path resolved from the current directory, which the operating system reports in canonical form, lies under it even when--repo-rootreaches the directory through a symbolic link, as the temporary directory of macOS does.- graph
graphbuilds the graph and runs the query on it. With the cache on, it first checks the documents that changed since the last check, asvalidatedoes, so that the store is current beforegraphreads its edges and keys. The graph has a node for each document in the repository, andgraphreads from the store only the edges near eachSTART.graphreads a document’s fields from its file only when the query first visits the document’s node. With--no-cache,graphreads every document and every edge. The cache is the only file thatgraphwrites.- guide
guidereturns the guide of each document thatopts.documentsnames, in the order of the arguments. It reads the tree as a lookup does, reads each document from its file, and compiles the schemas of their types. It refuses an argument that names no document of a store, a document without atypeor without a schema that passes the grammar, and a--statethat the document’s lifecycle doesn’t declare, before it returns anything.guidewrites only the cache.- harness_
diff diffreturns a patch for each file of each part in the stateeditedof each harness named, from the text thatinstallwould write to the text on disk, with the pathsa/<path>andb/<path>from the root ofscope, in the order ofstatus. Afilepart gives each file whole; aregionpart gives the block between its markers, and amergepart its entries as JSON, so their line numbers count from the block or the entries. It returns an empty text when no part is edited, and writes nothing.- harness_
ids harness_idsreturns the harnesses thatnamesnames, in the order given, withallin place of every harness that sokf supports, each once.- harness_
install installmakes the tree match sokf’s integration for each harness named, as CLI-3 describes. The adapter writes nothing until every check has passed, writes the parts, then the record, and never the configuration. The adapter carries out the part kinds, the states, the hashes, the shared locations, and the record, so this call implements their criteria.- harness_
status statusreturns the state of every part of each harness named, and writes nothing.- info_
formats info_formatsreturns a format registry as YAML, fromregistry.- info_
formats_ json info_formats_jsonreturns the format registry thatinfo_formatsprints as YAML, as the object of--json.- info_
grammar info_grammarreturns the schema language verbatim: the tramlines core grammar, then the tramlines-md grammar, and then the schema extension of SOKF.- init
initcreates a knowledge store and registers it as a root inknowledge.roots. It checks for every reason to refuse before it writes anything.- load
loadreads a file underrootas UTF-8 and returns it as a source, with its modification time in the key. It returns an I/O error when the file isn’t valid UTF-8.- load_
config load_configreads/.sokf/config.toml, or returns the defaults when the file is absent. It refuses a file that does not parse, that holds a[[pack]]entry (CONF-1_AC-6), or that has an unknown key, a glob that is not/-rooted or does not parse, or a root that is not a directory. It also refuses a file of/.sokf/excludes.d/that does not parse, that has a key other thanexclude, or that lists such a glob (CONF-3_AC-10, CONF-3_AC-11).- load_
for_ lookup load_for_lookupreturns the model that a lookup reads. With the cache on, this is the model of the check thatload_checkedran: it holds the changed documents, and the store’s rows stand in for the others. With--no-cache,load_for_lookupreads every document.- load_
keys_ for load_keys_forreturns the model that a lookup reads, with the keys that a command resolves. With the cache on, the model is the one thatload_checkedchecked, and the keys are the store’s keys forslugs. Those keys are current, becauseload_checkedcommits its check before it returns. With--no-cache,load_keys_forcaptures every key.- load_
model load_modelwalks the repository, syncs the cache, and builds the model through the cache, reading and parsing every document. The caller records the results that it derives from the model, then commits the cache.- load_
repo_ formats load_repo_formatsreads the repository’s formats layers: the files of/.sokf/formats.d/, as the layerformats.d, which is built on the embedded formats, and/.sokf/formats.yaml, as the repository layer, which is built on the layerformats.d. It parses each file offormats.don the embedded formats, and merges the files with tramlines’with_packs, so that no file takes precedence over another, and lays/.sokf/formats.yamlon them with tramlines’with_host. It reads only the files of the working tree, so a check reports the same findings for the same tree. It returns an error when:- load_
repository load_repositoryloads everything that a full run needs: it walks the repository, loads every document, builds the model, compiles the schemas, captures the keys, and expands the generated content.- load_
texts load_textsreads sokf’s texts: its English, then each file*.yamlat any depth below/.sokf/texts.d/, then/.sokf/texts.yaml. An entry of a later layer replaces the same entry of an earlier one. It refuses a file that doesn’t parse as a file of texts, and an entry that two files of the folder give different texts and/.sokf/texts.yamldoesn’t give.- load_
with_ keys load_with_keysreturns the model with every key captured, for a lookup under--no-cache. Such a lookup runs no check.- load_
working load_workingwalks the repository, syncs the cache, and builds the model from only the changed documents, with the store’s rows standing in for the others. When the store has no rows to stand in for them,load_workingreads every document.- locate
locatefinds the file of each id inids. Before it looks up the ids, it brings the cache up to date with the files that changed. It finds an id among the store’s ids and a key among the store’s keys, and it finds an asset by the sidecar that pairs with it. Whenassetis true and an id doesn’t identify a sidecar,locatereturns an error.locatewrites no file except the cache.- new
newbuilds a document of a type from the skeleton of the type’s schema, with the document’s guide, and writes it whenwriteis set. When it refuses, it has written nothing.- output_
schemas output_schemasreturns the schema of each output, paired with the name of its file in/knowledge/json/.- report_
fixable_ line fixable_linereturns the line that follows the line of counts in a run without--fix: the number of the findings that the report lists and that--fixrepairs, followed bypotentially fixable withand the command, orNonewhere it lists none (CLI-4_AC-30). A file whose schema breaks the grammar holds none, because--fixleaves it unchanged (CLI-4_AC-106).- report_
message messagereturns the message offfollowed by the key of the criterion thatfbreaks, in parentheses, such as(SOKF_FORMAT_53).- report_
text textrenders the text report: the fixes, then the findings, then the counts line.- resolve_
paths resolve_pathsturns thePATHSarguments into a scope. It refuses a path that doesn’t exist or that lies outside the root.- validate
validaterunssokf validateand returns the report, and the report’s projection whenopts.queryis given.
Type Aliases§
- Result
Resultis the result type of this crate, withErroras its error.