Skip to main content

Crate sokf_core

Crate sokf_core 

Source
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 host module answers the engine’s questions about the repository.
compare
The compare module 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 fix module 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 graph module represents the knowledge as a graph of nodes and edges, which it builds once from the model (CLI-7). build builds the graph, start resolves the start of a command (a key, an id, or a path) to a node, traverse walks the graph from the start nodes to a bounded depth, json writes the graph as JSON, and locate turns ids into paths (CLI-8).
harness
The harness module integrates sokf with agent harnesses (CLI-3) through agent-harness-adapter. It holds sokf’s integration, sokf as a adapter Tool, and the hook. The adapter holds the harnesses, the part kinds, the states, the record, and install and status.
include
The include module 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 index module 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 its sokf: 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 that sokf new creates a document from.
yaml
YAML 1.2 core-schema parsing as TL_13 and TL_14 read it.

Structs§

AddedExclude
An AddedExclude is one glob that a file of /.sokf/excludes.d/ lists, with the file.
BlockGuide
BlockGuide holds the guidance of one block.
Body
A parsed body.
Cache
Cache holds the store and the state of this run’s sync.
Config
Config is the resolved configuration, with every root checked.
ConfigText
ConfigText is the configuration as written, for init and the harness commands: the roots as listed, whether or not each one is a directory, and the file’s text.
DocumentGuide
DocumentGuide holds 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). Each text holds the words of the guidance line that the scaffold of the schema writes before the same part at the same states, and each example the text that the scaffold writes for the part, with the document’s own frontmatter values.
Expr
Expr is a compiled JMESPath expression, kept with the source text it was compiled from.
FileKey
FileKey identifies a file’s content for the cache (CACHE-1_AC-1, CACHE-1_AC-2).
Finding
One line of the report.
FormatEntry
One line format of the registry: its keys as a formats file writes them, which the grammar format of sokf info grammar defines, such as template, example, and variants, and its source.
FormatRegistry
A named set of formats, each with its source, and the hole types the layers declared.
FormatType
One placeholder type of the registry.
FormatsJson
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.
GraphOptions
GraphOptions holds the options of sokf graph.
GuideLimit
GuideLimit is 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.
GuideOptions
GuideOptions holds the options of sokf guide.
GuideReport
GuideReport is the report of sokf guide --json: the guide of each document that an argument names, in the order of the arguments (CLI-17_AC-17).
HarnessDirs
The directories that install and status work in.
HarnessOptions
The options of install.
HarnessReport
The report of sokf harness install --json and sokf 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).
HarnessResult
The parts of one harness.
IdTemplate
An id template a new document can be filled with.
InitOptions
InitOptions holds the options of sokf init.
InitResult
InitResult is the report of sokf 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
KeyGuide holds the guidance of one frontmatter key.
LabelGuide
LabelGuide holds one attribution label of the schema.
LinkGuide
LinkGuide holds the guidance of one links rule.
Loaded
Loaded holds 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 id of the schema, and the rule’s rule-id, else its section and block position. A finding that a schema rule raises ends with it.
NewOptions
NewOptions holds the options of sokf new.
NewResult
NewResult is the report of sokf 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 at path (CLI-6_AC-72).
PartResult
One part of a harness.
PathArg
PathArg is a path argument, written either as a spec path or as a filesystem path (CLI-1_AC-7, CLI-1_AC-8).
PreambleGuide
PreambleGuide holds the guidance of the preamble.
RepoFormats
RepoFormats holds the formats layers that the repository supplies: the repository layer and the layer formats.d.
RepoPath
A path relative to the repository root, which starts with / and uses forward slashes. The path / is the root itself.
RepoRoot
The repository root on disk.
Report
Report holds the errors, the warnings, and the fixes of a run.
RuleLabel
RuleLabel says whether the units of a block, or the units of one of its unit rules, carry a label.
RuleLimit
RuleLimit is one limit of a block: its own, or one of a unit rule’s or a line rule’s.
Scope
Scope holds the files and directories that the PATHS arguments of validate point to (CLI-4_AC-2). When PATHS is empty, the scope is the whole repository.
SectionGuide
SectionGuide holds the guidance of one section.
Segments
The markers of one body.
Source
Source is one loaded file, with its text normalised to LF.
Spanned
A value with the line it starts on.
Stat
Stat holds the metadata that the walk reads without opening the file (CACHE-1_AC-1).
StoreView
StoreView is 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.
SyncStats
SyncStats holds 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
Texts holds sokf’s texts, keyed by language, as a tag in lower case, and by entry, such as limit.hard or units.item.
Tree
A Tree is the walked repository.
ValidateOptions
The options of sokf validate.
ValidateReport
ValidateReport is the report that sokf validate --json prints. It holds every error, every warning, and each repair by --fix (CLI-4_AC-12).
WalkedDir
A WalkedDir is one directory that the walk visits under a knowledge root. Each such directory must have an index (SOKF_FORMAT_96).
WalkedFile
A WalkedFile is one file that the walk found.

Enums§

CacheMode
CacheMode sets whether a run reads and writes the cache.
Error
Error holds the errors of this crate. Every variant renders a message that the CLI prints unchanged after error: .
FileKind
A FileKind is the kind of a walked file, as the store structure of sokf-format-spec defines it.
FileState
FileState says what the sync found a file to be.
FixOp
FixOp is one operation that validate --fix performed (CLI-4_AC-26).
FormatSource
Where a registry entry comes from.
GuideCounts
GuideCounts is what the limit of a unit rule or a line rule counts.
GuideLabel
GuideLabel says whether a unit carries a label.
GuideLimitKind
GuideLimitKind is the kind of a limit.
HarnessScope
Where a harness integration is installed.
InfoLayer
InfoLayer lists the values of the --layer option of sokf info formats (CLI-5).
LineEnding
LineEnding is the line ending of a file’s first line.
MarkerCheck
MarkerCheck selects 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
Output names each JSON output that the tool prints or writes.
Severity
How a finding is reported.
TypeMatch
What a placeholder type matches.
Yaml
A YAML 1.2 core-schema value.
YamlError
A construct the YAML dialect refuses (TL_14), or a syntax error, with its line.

Constants§

ALL_HARNESSES
ALL_HARNESSES is the harness name that stands for every harness that sokf supports.
CACHE_DIR
CACHE_DIR is the cache directory, relative to the repository root.
STORE_FILE
STORE_FILE is the name of the store file inside the cache directory.
STORE_FORMAT
STORE_FORMAT is 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_repository loads 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
collect walks 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_root returns the repository root. When the caller passes given, the root is that directory’s canonical path, and the directory must exist. Otherwise the root is the nearest ancestor of cwd that holds a .git directory 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-root reaches the directory through a symbolic link, as the temporary directory of macOS does.
graph
graph builds the graph and runs the query on it. With the cache on, it first checks the documents that changed since the last check, as validate does, so that the store is current before graph reads its edges and keys. The graph has a node for each document in the repository, and graph reads from the store only the edges near each START. graph reads a document’s fields from its file only when the query first visits the document’s node. With --no-cache, graph reads every document and every edge. The cache is the only file that graph writes.
guide
guide returns the guide of each document that opts.documents names, 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 a type or without a schema that passes the grammar, and a --state that the document’s lifecycle doesn’t declare, before it returns anything. guide writes only the cache.
harness_diff
diff returns a patch for each file of each part in the state edited of each harness named, from the text that install would write to the text on disk, with the paths a/<path> and b/<path> from the root of scope, in the order of status. A file part gives each file whole; a region part gives the block between its markers, and a merge part 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_ids returns the harnesses that names names, in the order given, with all in place of every harness that sokf supports, each once.
harness_install
install makes 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
status returns the state of every part of each harness named, and writes nothing.
info_formats
info_formats returns a format registry as YAML, from registry.
info_formats_json
info_formats_json returns the format registry that info_formats prints as YAML, as the object of --json.
info_grammar
info_grammar returns the schema language verbatim: the tramlines core grammar, then the tramlines-md grammar, and then the schema extension of SOKF.
init
init creates a knowledge store and registers it as a root in knowledge.roots. It checks for every reason to refuse before it writes anything.
load
load reads a file under root as 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_config reads /.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 than exclude, or that lists such a glob (CONF-3_AC-10, CONF-3_AC-11).
load_for_lookup
load_for_lookup returns the model that a lookup reads. With the cache on, this is the model of the check that load_checked ran: it holds the changed documents, and the store’s rows stand in for the others. With --no-cache, load_for_lookup reads every document.
load_keys_for
load_keys_for returns the model that a lookup reads, with the keys that a command resolves. With the cache on, the model is the one that load_checked checked, and the keys are the store’s keys for slugs. Those keys are current, because load_checked commits its check before it returns. With --no-cache, load_keys_for captures every key.
load_model
load_model walks 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_formats reads the repository’s formats layers: the files of /.sokf/formats.d/, as the layer formats.d, which is built on the embedded formats, and /.sokf/formats.yaml, as the repository layer, which is built on the layer formats.d. It parses each file of formats.d on the embedded formats, and merges the files with tramlines’ with_packs, so that no file takes precedence over another, and lays /.sokf/formats.yaml on 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_repository loads 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_texts reads sokf’s texts: its English, then each file *.yaml at 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.yaml doesn’t give.
load_with_keys
load_with_keys returns the model with every key captured, for a lookup under --no-cache. Such a lookup runs no check.
load_working
load_working walks 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_working reads every document.
locate
locate finds the file of each id in ids. 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. When asset is true and an id doesn’t identify a sidecar, locate returns an error. locate writes no file except the cache.
new
new builds a document of a type from the skeleton of the type’s schema, with the document’s guide, and writes it when write is set. When it refuses, it has written nothing.
output_schemas
output_schemas returns the schema of each output, paired with the name of its file in /knowledge/json/.
report_fixable_line
fixable_line returns the line that follows the line of counts in a run without --fix: the number of the findings that the report lists and that --fix repairs, followed by potentially fixable with and the command, or None where it lists none (CLI-4_AC-30). A file whose schema breaks the grammar holds none, because --fix leaves it unchanged (CLI-4_AC-106).
report_message
message returns the message of f followed by the key of the criterion that f breaks, in parentheses, such as (SOKF_FORMAT_53).
report_text
text renders the text report: the fixes, then the findings, then the counts line.
resolve_paths
resolve_paths turns the PATHS arguments into a scope. It refuses a path that doesn’t exist or that lies outside the root.
validate
validate runs sokf validate and returns the report, and the report’s projection when opts.query is given.

Type Aliases§

Result
Result is the result type of this crate, with Error as its error.