@nikovirtala/ledger
v0.19.0
Published
Shared core for ark's git-backed, event-sourced records. Internal: the API is unstable until 1.0.
Readme
@nikovirtala/ledger
The shared core of ark's ledger-based tools (adr, issues): git-backed, event-sourced records. It is internal to ark, released at 0.x, and its API is unstable until 1.0. See the design doc.
Requirements: Node 24 or newer (engines: >=24; older Node prints npm's EBADENGINE warning and isn't supported) and git 2.32 or newer.
Step 2 shipped the mechanical core: everything that can be specified without knowing what an event means. Step 3 adds the domain-free half of a kind: defineKind with the state machine as data, the fold engine, numbering, fold-aware verify checks, atomic log writes, surfaces and CLI scaffolding. adr's phase 2b adds the Index layer (a generated, committed index with its freshness check and the shallow-clone number fallback), checks over code (scope globs and anchors), a pre-push hook default and a recovery hint for a failed commit. Phase 3 adds the mcp entry, MCP server scaffolding for agents. A plain KindSchema (a name, versioned per-type data JSON Schemas and a body policy) still works everywhere it did, with step 2's checks.
Entries
@nikovirtala/ledger: every public function, class and type, from the layers below.@nikovirtala/ledger/cli: CLI scaffolding for tools built on ledger (runCli,processIO,verifyCommand). Importing a kind never loads it, because the root entry doesn't import it.@nikovirtala/ledger/mcp: MCP server scaffolding (serveMcp,mcpAttribution, the input schemas and argument readers,checkResourceId). It is built on@modelcontextprotocol/sdk1.32.2, a dependency of ledger that only this entry loads.@nikovirtala/ledger/testing: the test harness. It needs fast-check ^4, an optional peer dependency that the root entry never loads.
The cli and mcp entries re-export LedgerError and UsageError, and the testing entry LedgerError and InvalidArgumentError. They are the same classes as the root entry's, so instanceof works across entries.
Errors and findings
Wrong data in a repository becomes a Finding: { severity, rule, message, file, line, subject, kind }, where rule is a stable <area>/<name> id such as append-only/modified. Caller misuse, invalid config and environment failures throw a LedgerError subclass with a fixed code (for example InvalidArgumentError, UsageError, ConfigError, GitError, RefNotFoundError, FileExistsError, FileChangedError). ledger's root entry never writes to stdout or stderr; only the cli entry does.
Findings have three output formats:
formatText: one<file>[:<line>]: <severity>: <message> [<rule>] (<subject>)line per finding, then a summary such as4 errors, 1 warning;formatJson: aledger-findings/v1report withok,summaryand every finding, withnullfor unknown values (findingsReportreturns the same report as an object, for embedding);formatGithub: GitHub Actions workflow-command annotations.
exitCode(findings) returns 1 when there is an error, and with { failOn: "warning" } also when there is a warning; otherwise 0.
Kinds
defineKind declares a kind with its state machine as data:
import { defineKind, eventType } from "@nikovirtala/ledger";
export const widgetKind = defineKind({
name: "widget",
schema: "widget/v1",
states: ["draft", "published", "retired"],
events: {
created: eventType<{ title: string }>()({
data: { type: "object", required: ["title"], properties: { title: { type: "string" } } },
allowedIn: [],
to: "draft",
}),
published: eventType<{ body_sha256: string }>()({
data: { type: "object", required: ["body_sha256"], properties: { body_sha256: { type: "string" } } },
allowedIn: ["draft"],
to: "published",
}),
retired: eventType()({ data: { type: "object" }, allowedIn: ["published"], to: "retired", reason: "required" }),
},
initial: "created",
reduce: (state, e) => (e.type === "created" ? { title: e.data.title } : state ?? { title: "" }),
project: (subject, ctx) => ({ id: subject.id, display: ctx.display(subject.id), status: subject.status }),
body: { freezeOn: "published" },
layout: { bodies: "items", events: "events" },
defaultRoot: "docs/widgets",
numbering: { on: "published", format: (n) => `W-${n}`, parse: (s) => Number.parseInt(s.replace(/^w-/i, ""), 10) || null },
options: undefined,
});Each event type says in which states it is allowed (allowedIn, or "any") and which state it leads to (to, or null for events that don't change the state, such as notes). An event type can require a reason (event/reason-required). body.freezeOn names the event that freezes the body and records its hash. Optional parts: invariants(subject, options) for per-subject rules, relate(log, options) for rules across subjects, templates (lintIn, lintOn, requireSections) for template lint in verify, numbering, and scope (event, the set event that holds a subject's globs; activeIn; keyword, the comment-anchor keyword, default the tool's source name; kind.anchorKeyword is the resolved value). defineKind checks the definition and throws KindDefinitionError, for example for an event type that names an unknown state, a scope.event without a data.set array, an invalid scope.keyword, an event type other than the initial one with allowedIn: [], a freeze event that leaves the state unchanged, or a schema name not of the form <name>/v<n>. The result is frozen and passes compileKind. kind.machine (terminal, allowed, next) exposes the state machine as data, so tools can inspect it.
Fold, projection and numbering
- Fold.
foldLog(kind, snapshot)replays each subject's valid events in(at, id)order, independent of file names and file order, through the state machine and the kind'sreduce. An event the machine doesn't allow is skipped and the state is unchanged; a subject whose first event isn't the initial one, or a body without events, can't be folded.compareEventsis the order. - Projection.
projectLog(kind, folded, { numbering })builds the kind's views and lists subjects that areunreadable(a newer envelope or schema) orunfoldable.kindFindingsmaps a kind's findings onto files. - Numbering.
numberLog(git, { kind, layout, mainRef })gives display numbers in the order thenumbering.onevent files first landed on first-parent main. Numbers are computed from file names only, never stored, and never change; a--no-ffmerge numbers its acceptances at the merge commit.resolveMainRefprefersorigin/HEAD, thenorigin/main,origin/master, localmainandmaster. A repository without a main branch reports numbers as unavailable (NO_NUMBERINGwith areason). In a shallow clone the history is incomplete, sonumberLoguses the numbers itsfallbackreturns, such as the ones a committed index records (reason: "index"), and reports them unavailable without one (reason: "shallow").NO_INDEX_NUMBERING(reason: "no-index") is for a tree read without history, such as a cached source's log, that has no usable committed index. - Projected numbers.
projectNumbering(git, { kind, layout, history, tree, recorded, mainRef, merging })gives the numbers a log's subjects will have once the commit holdingtree(building onhistoryand mergingmerging, such asMERGE_HEAD) is on main: main's first-parent additions up to the newest commit on its first-parent line that the commit contains, then those ofhistory's own first-parent commits after it, then, as one last group, thenumbering.onevent files intreethat neither numbers yet. After a fast-forward, rebase or merge-commit merge of an up-to-date branch, whether it was updated by rebasing or by merging main, main'snumberLogequals the branch's projection. On main's first-parent line, and without a main ref, the history part ishistory's first-parent additions. In a shallow clone the history comes fromrecorded, and the pending subjects are numbered after its highest number.compareNumberingKeysis the order within a commit (stamp, then rand, then subject), shared by both.
Verify
For a kind made with defineKind, verifyLog folds the head and base logs and runs foldChecks(kind): step 2's mechanical checks, plus transitions (transition/illegal, transition/not-initial, transition/no-events), invariantsCheck, relateCheck and templateCheck. Freezing is fold-aware: only an applied freeze event freezes the body, and in a kind with bodies every subject with applied events needs one (body/missing). templateCheck lints bodies against the template version they were written with, found in the tree or in git history (treeTemplates, historyTemplates, gitTemplates, templateHistoryRef). In staged scope a cross-subject finding is kept when any subject it names is touched. A plain KindSchema gets exactly step 2's checks.
verifyLog({ widenOn }) takes the repository paths every check reads that live outside the log (a tool's config files and templates; a trailing / covers a directory): when the staged changes touch one of them (touchedInputs), staged mode checks every subject and the whole tree for anchors, because a policy or template change can break subjects no staged file touches. verifyCommand prints a note saying so.
verifyLog also gives checks a CheckContext.repo (RepoContext: the Git, the mode, the head as "worktree", "index" or { commit }, and the base commit), so checks can read code outside the log; verifySnapshots callers that pass none get checks that report nothing. The scope checks below use it.
Writes
writeEvents(git, layout, events, { kind })validates a batch, refuses an event over 1 MiB, creates each file exclusively, removes the batch again if any write fails, and stages it only after every write succeeded.writeNewFilecreates a new file (a body, a template), never overwriting one (FileExistsError).replaceFile(git, path, content, { expected })replaces an existing file only if it still holdsexpected, through a temporary file renamed over it, and otherwise throwsFileChangedError(codefile-changed) and touches nothing.nextEventIdentitypicks anatand ULID that sort after a subject's existing events, even with a clock that goes backwards.Git.identity()reads the configured author identity andGit.committerIdentity()the committer, and neither guesses one.Git.commit({ message, trailers, mergeTrailers, only })commits only the given paths (Git.commitMessagegives the exact message it writes; withmergeTrailers, the trailers join the message's last paragraph when the installed git reads trailers in it, such asCo-authored-by:orRefs:lines, which ledger asks git with onegit interpret-trailers --parsecall that honours the user'strailer.*config), andstagedPaths,unstagedPathsanduntrackedPathstell a tool what a commit would take.- Behaviour change:
Git.commitnow writestrailersitself, as a literal final paragraph of the message, instead of passing them togit commit --trailer. Repeated keys and their order survive anytrailer.*git config. Don't put a trailer block of your own inmessageunless you passmergeTrailers, or git reads only the last block. overlayTree(base, files)reads a tree with some files added or replaced, so a tool can fold the log as it would be after a write before writing anything.- Plan helpers. A tool's write plans share these, with the tool's kind, messages and read passed in.
checkText(what, text)refuses NUL characters and text overMAX_TEXT_BYTES(64 KiB) with aUsageError, andcheckReason(reason)trims a--reason, refuses an empty one and givesnullwithout one.subjectView(projection, id, { missing, unreadable })gives a folded subject's view, else aUsageErrorwithunreadable(id)for a subject in a newer format (when given) ormissing(id).refusal(read, kind, rule, message, subject)is an error finding on the subject's body, else its events directory.newEvent(read, { now, random }, { name, schema }, o)builds an event that sorts after the subject's events ando.after;eventFiles(layout, events)serializes events to their paths, andeventPairs(events, keys)gives one trailer pair per event (repeats kept, unlikeeventTrailers).precheck(read, files, replace, refold)folds the overlay with the tool'srefoldand returns it with the findings the write adds (compared byfindingKey); the tool decides which of them refuse the write.chooseTemplate(tree, root, name, builtins, requireSections)reads<root>/templates/<name>.md, else picks the built-in to materialize, refusing an invalid or unknown name, and gives the parse or lint findings of a bad template.unmatchedGlobs(globs, files)lists globs no file matches.followRenamesChanges(views, staged, { named, blocked, change })is the loop of--follow-renames: in id order, it followsstaged(StagedRenames) in each view's globs, skips unchanged ones, reportsblocked(view, leaving)'s note for a view whose state forbids a new scope, refuses more than 200 globs, notes skipped and gained files, and collectschange(view, globs)until one returns{ stop }. - Apply step.
applyPlan(log, plan, o)applies a tool'sWritePlan(the subject,files,replace,events,stage,commitScope,eventDirs,trailers,findingsandnotesa tool's plan extends). Witho.commitit first takes the commit scope (o.scope(plan), default the plan'scommitScopeandeventDirs) and refuses an unstaged or untracked path in it (UsageError). It renders the index (o.index(tree, history), given only with[log] index = "committed") before anything is written, writes the replacements, new files and events (removing them and restoring the index if a write fails), stages them, runso.afterStage(scope)(the editor step, which can replace the findings or turn the commit off), and commitsplan.stageplus the scope's staged files with--onlyandeventTrailerswitho.trailerKeys(the plan's owntrailersonly for a plan without events). The message iso.message(withmergeTrailers) or whato.compose({ plan, extra, tree })(ComposeInput) renders; giving both, or neither when committing, is anInvalidArgumentError. After the editor step the index is rendered again witho.rerenderAfterEdit"always"or"when-events-change"(only when the staged event files changed), from the plan's bytes or the work tree's (o.afterEditBytes"plan"or"worktree", which also setscompose's tree), and refreshed from the work tree after the commit. A failed commit throwsCommitFailedErrorwithWRITE_RERUNand the notes so far; the index hints useindexBeforeHint/indexAfterHintwitho.toolando.plural.unstagedIndexNote(log, at, staged, history, render, { tool, noun })is the note for a staged index that only the work tree's render matches. It returnsAppliedPlan:written(replaced, then new files, then the index),commit,findings,notesandrendered. - Write driver.
runWrite(o)is the loop around a tool's plan and apply, insidewithGitOperation.checkWorkTree(log)refuses a log opened at a ref or with another tree reader (InvalidArgumentError); with a commit (o.commit, defaulto.autoCommit)checkCommitIdentity(git)refuses a missing author or committer identity (ConfigError), before anything is written. Each attempt reads the log again (o.read()) and plans withplanContext(log, root, builtins, deps)(PlanContext: the clock and randomness ofdeps, the built-in templates, and templates read from the work tree, else from the historytemplateHistoryRefgives). A refused plan (PlanRefusal) becomeso.refused(r, notes)with the log's and the caller's notes, theno.refusalNotes(r). A plan with nothing to write, and every plan witho.dryRun, becomeso.done(outcome)without touching the repository. Witho.requireCommitParts, committing a plan whosecommitisnullis anInvalidArgumentError. Otherwiseo.apply(plan, read, commit)writes it; the outcome (WriteOutcome) has the views fromviewsAfter(sha, views, reread)(the plan's owno.views(plan)without a commit, else those ofo.reread(sha)), and the notes in order: the log's, the caller's, the plan's,applyPlan's, then the shortened-subject note of a commit. AnEventExistsErrorplans and applies once more; aCommitFailedErrorgets the log's, the caller's and the plan's notes first. The plan is aDriverPlan: aWritePlanwithcommitparts and adraft(DraftFile).editorStep({ git, edit, onNote, editorNotes, finding })gives theafterStageofnew: it runs the editor on the staged draft, re-stages the body when the editor exited 0, and turns the commit off with a note when the body was removed, changed while the editor failed, another path in the commit scope changed meanwhile, or required sections are still unfilled; its findings are the draft's lint (each mapped byfinding).editorNotesalso passes the failed editor's own note toonNote.readIfPresent(path)andsameBytes(a, b)are the file helpers it uses.
Scope
Which code a subject governs: glob sets recorded in whole-set events, and comment anchors in the code.
- Globs.
parseGlobandglobMatchermatch repo-relative POSIX paths with one fixed dialect that doesn't depend on the Node version:*and?(never across/),**as a whole segment, classes[a-z],[!a]and[^a], brace alternatives{a,b}(no/,**or nesting inside, at most 64 alternatives after expansion), and\escapes.*and**match dot-files. Absolute globs,.and..segments, empty segments, a trailing/, negation (!x) and globs overMAX_GLOB_LENGTH(500) characters are refused with aGlobProblemand a message. Matching uses no regular expressions built from input.escapeGlob(path)writes a path as a literal glob. - Set events.
setEventType({ item, maxItems, allowedIn })declares an event whosedata.setis the complete set; the latest applied one wins (latestSet).applySetOp(current, { set | add | remove }, { what, validate, maxItems, names })applies a--set/--add/--removestyle change and returns the new set sorted and deduplicated, with what was added, removed, already present or absent;namessets the flag names itsUsageErrormessages use. adr'sscopedand issues'assigned/labeleduse it. - Anchors.
scanAnchors(git, { keyword, tree, paths, excludeDirs, exclude })finds<keyword>:<id>and<keyword>:<source>:<id>tokens with onegit grepin the work tree, the index or a commit;anchorsInLineapplies the rule to one line. A token counts only when a comment leader (//,/*,#,--,;,%,<!--,(*) comes earlier on its line. That rule is a heuristic: anchors in binary files, submodules, theexcludeDirsand files matching anexcludeglob aren't found, and a comment leader inside a string literal counts like a real one. - Renames.
stagedRenames(git)reads the renames staged againstHEAD(git's similarity detection; copies are ignored).followRenames({ globs, renames, before, after })rewrites a glob set so every file it covered is still covered under its new path, and lists the files it newly covers (gained) and the renames it can't write as a glob (skipped). - Lookup.
scopedSubjects(log)lists every folded subject with its status and latest globs;scopeLookup({ subjects, anchors })returns, for a path, each subject that governs it with every glob and anchor line that matched.lookupPaths(git, { tool, tree, ref, commit, cwd, paths, keyword, exclude, excludeDirs, globSubjects, known })does the path handling behindadr forandissues for: it takes 1 to 100 paths relative tocwd, refuses paths outside the repository, paths over 4096 characters and directories (found withlstatin the work tree, by listing the index for a path missing from it, or by listing the ref's tree) with aUsageErrornamingtool, drops duplicates, and returns per path whether it is tracked (in the index, or in the ref's tree), thematchesofscopeLookupoverglobSubjectsand the anchors read from the work tree or the commit, and theunresolvedanchors by line:other-logfor a qualified one,not-foundfor a local one whose idknownrejects.globSubjectsare only the subjects whose globs apply, whileknowncovers every subject, so an anchor to an inactive subject still matches and each tool filtersmatchesitself. - Checks. Verify checks for kinds with
scope, which needCheckContext.repo.scopeGlobCheck()reportsscope/glob-invalidfor a stored glob that doesn't parse andscope/glob-unmatchedfor a glob that matches no tracked file, for statuses inscope.requireMatchIn(defaultactiveIn), so a kind's planned states can name code that doesn't exist yet;defineKindrefuses arequireMatchInstate outsideactiveIn.anchorCheck({ keyword, exclude })reportsscope/anchor-missingfor a local anchor whose id isn't in the log; qualified anchors aren't checked, and paths matching anexcludeglob are skipped. In staged mode both look only at touched subjects and changed files. Two helpers let a kind build its own governance checks:governedChanges(ctx, { keyword, exclude, statuses })lists the changed code paths that a subject in one ofstatusesgoverns, andnarrowedScopes(ctx, { statuses })lists subjects whose new set stops covering files that still exist (a moved or deleted file isn't narrowing).
Index
A generated, committed Markdown index of a log, for people browsing on a forge; tools read only its numbers line.
renderIndex(spec, views, numbering)renders it from anIndexSpec(the tool, the title, groups, columns and row order): a header naming the tool (not its version, so upgrades don't make every index stale), one table per non-empty group, and a last line<!-- ledger-index/v1 numbers: <id>=<n> … -->recording the numbers.escapeMarkdownescapes table cells.parseIndexNumbers(text)reads the numbers line back (nullfor a missing or malformed line, a duplicate id or number);readIndexNumbers(tree, path)reads it from a tree, ignoring files over 4 MiB. A tool passes it asnumberLog'sfallbackandprojectNumbering'srecordedin shallow clones.indexNumbering(byId)turns that map into theNumberinga tree read without history, such as a cached source's, gets from its committed index (reasonindex), orNO_INDEX_NUMBERINGfornull.indexCheck({ path, expected, fix })is the verify check that the file is what the tool renders for the head:index/missing,index/stale, or theindex/uncheckedwarning when the bytes can't be computed (a shallow clone without a recorded index). In scopechangedit runs only when the log has changes.writeIndexFile(git, path, text)writes the file atomically and returnsfalse, touching nothing, when it already holdstext.renderLogIndex(git, { kind, layout, mainRef, tree, history, views, spec })is a tool's whole render: it numberstree's subjects withprojectNumberingas they will be once the commit holdingtree(which builds onhistory) is on main, mergingMERGE_HEADwhile a merge is in progress and falling back to the numbershistory'sindex.mdrecorded in a shallow clone, then rendersspec(root, views)of the tool'sviews(tree, numbering). It returnsnullwhen the numbers can't be projected.indexPath(layout)is the file,<root>/index.md.unstagedLogFiles(git, layout)lists the log's event and body files whose work-tree content isn't staged, sorted: the cause of a staged index that only the work tree's render matches.unstagedIndexText(path, files, noun)is the start of the finding and the write note that name them, such asdocs/adr/index.md lists decision files that aren't staged (…), naming at most five.
Surfaces
openToolLog({ cwd, tool, kind, root, ref })locates a tool's log and config:--root, else[log] rootin<repo>/<tool>.toml, else the kind'sdefaultRoot, with<root>/<tool>.tomlas the alternative config file. It reads config and log from the same tree (the--reftree, the index or the work tree) and returns notes such as "ignoring adr.toml (its root is docs/adr; --root is fixtures/adr)".- Config keys.
toolConfigReader(config, file, tool)reads a parsed<tool>.tomlwith errors (ConfigError) that namefile, elseconfig.file, else<tool>.toml:table(name)({}when missing, refusing anything but a table),bool(t, section, key, fallback)andoneOf(t, section, key, values, fallback), plus itsfail,whereandconfig.parseSharedKeys(reader, { defaults, indexValues })validates the keys every tool config has,[log] default_template,main_branchandindex,[policy] auto_commit,[verify] fail_on,[scope] anchor_keywordandanchor_exclude(at most 100 globs),[hooks] scope_follow_renamesandindex, and[commit] subject(throughreadCommitTemplatewithdefaults.commit), and gives the defaults for missing keys; a tool reads its own keys with the same reader.parseNumberingKeys(log, fail, { indexValues })validates only[log] main_branchandindex, for a tool that reads another tool's numbering.indexValuesis the order thelog.indexmessage lists"committed"and"none"in. resolveAttribution(git, { env, agent })returns the actor a write is recorded as, with notes for the user. WithoutARK_AGENT(oragent) it is the human from the git identity. With it, it is an agent acting on behalf ofARK_ON_BEHALF_OF, or, when that isn't set, of the git identity's email, with the noteon_behalf_of taken from the git identity <email>; set ARK_ON_BEHALF_OF to name who you act for. With both set, no git identity is read. AnARK_ON_BEHALF_OFthat isn't an email address (parseOnBehalfOf) is aConfigError(exit 2 in the CLI).ARK_ON_BEHALF_OFwithoutARK_AGENTis ignored, with a note.resolveActorreturns just the actor.- The git identity is git's author identity (
git var GIT_AUTHOR_IDENTwithuser.useConfigOnly):GIT_AUTHOR_NAMEandGIT_AUTHOR_EMAILwhen set, elseuser.nameanduser.email; it is never guessed. SettingGIT_AUTHOR_*also changes the author of--commitcommits, which is why agents should useARK_ON_BEHALF_OFinstead. - Commit messages.
readCommitTemplate(config, { file, vars, defaultSubject, names })reads[commit] subjectfrom<tool>.toml, a one-line template such asdocs(adr): {action} {title}with{title}(the title with an ordinary capitalized first word lowercased, acronyms, identifiers and mixed-case names such asCLI,ARK_AGENTorGraphQLkept),{raw_title}(the title as recorded) and the tool's placeholders; the description's first letter is always lowercased and the rest keeps its natural casing;parseCommitTemplatechecks it, including that each ofnames(a name the title placeholder can hold instead of a title, such asADR-0001 with ADR-0002) fits uncut.renderCommitMessage(template, { title, vars, body, slot })keeps the Conventional Commits description withinMAX_DESCRIPTION(72) characters by shortening the title with…, at a word boundary when one is near the limit, and puttingFull title: <title>in the body, and wraps body paragraphs at 72 (wrapParagraph). Withslot: { before, after, quote }the title placeholder holdsbefore, the title (in double quotes withquote) andafter; only the title is shortened.RenderedCommit.noteis the note to report when it was shortened, naming the 72-character limit of the description after the Conventional prefix.joinActionsjoins a batch's verbs (link, scope and comment on), andeventTrailers(events, keys)gives one subject/event trailer pair per distinct subject and type, so a commit never has two identical pairs.stagedEventRefs(layout, paths)gives the (subject, type) refs of the event files amongpaths, sorted by path and deduplicated, for those trailers.checkCommitMessagechecks a--messagegiven as is. resolveSubjectInput(input, { subjects, kind, numbering })resolves an id or a number in any form the kind parses, and says why when it can't (malformed, qualified, unknown, numbers unavailable).- Failed commits.
commitWithRecovery(git, { message, trailers, only, rerun, after })commits likeGit.commit; whengit commitfails (a hook, signing) andHEADdidn't move, it saves the full message, trailers included, to<git dir>/ark/COMMIT_MSG(saveCommitRecovery) and throwsCommitFailedError(codecommit-failed, exit 2). Its message lists the staged paths and the trailers, gives the exactgit -C <top> commit --cleanup=whitespace -F <file> --only -- <paths>command, and includes the caller'srerunsentence on why running the tool again won't help.withNotes(notes)attaches the notes the write would have reported, whichrunCliprints as warnings before the error and puts in theark-error/v1document'snotes. - Index merge driver.
<tool> index --mergeis git's merge driver for a log's committedindex.md(runLogIndexMerge(log, { tool, noun, render, index }, args, { env, cwd })):identifyMergefinds ours (HEAD), theirs and the base from git's own state (rebase-merge/done,sequencer/todo,GITHEAD_<oid>, and for a lone cherry-pick git's%S %X %Ylabels, which exist from git 2.44),mergeLogmerges the log's other files three-way in memory (overlayTree,MemoryTree), and the tool'srenderrenders them with HEAD ashistory(andmergingfor a merge). It compares the three files git passed with those commits'index.md, and when anything is uncertain leaves git's text merge (git merge-file) in%A, so git stops as it does without the driver.installMergeDriver,uninstallMergeDriverandmergeDriverStateset and readmerge.<tool>-index.{name,driver,recursive}in the clone's local config;installToolHooksanddoctor --fix-clonecall them for a log with[log] index = "committed"(commitsIndex), andgitattributesLines(logs, tool, { indexCommitted })names it in.gitattributes(mergeDriverAttributeLine). - Index command.
runLogIndex(log, { tool, noun, plural, format, index, autoCommit, commitSubject, title, action, render }, { check, commit, message, notes })is<tool> index: withcheckit reportslogIndexCheck's findings and writes nothing; without a commit it writes and stages the work tree's render where the work tree or the index differ; with one (defaultautoCommit) it commits HEAD's render of<root>/index.mdalone when HEAD's copy differs, then refreshes the work tree's copy, which may include other subjects' uncommitted entries (IndexRun.refreshed). The tool passes its config ([log] index, which must becommitted,[policy] auto_commit,[commit] subject), its commit title and action, its JSONformat(LogIndexJson<F>, such asadr-index/v1) andrender(git, { tree, history }), itsrenderLogIndexcall with its spec bound.logIndexCheck(log, { tool, noun, render })is the verify check:indexCheck, and in staged mode, when the stale staged copy is the work tree's render, a finding that names the unstaged files togit add. The recovery hints of failed index commits areindexRerunHint(tool),indexBeforeHint(tool, plural, root)andindexAfterHint(tool, plural, root).ToolWriteOptionsholds the options a tool's writes share with it (commit,message,notes,index: "refresh" | "skip"). - Git hooks.
toolHookCommands(log, tool)is a tool's command per hook, after<tool>:hooks run pre-commit,hooks trailers {args},verify --base @{upstream} --ref HEAD --fetch-sourcesandlist --since ORIG_HEAD, with--root <root>first only when neither<repo>/<tool>.tomlnor the kind's default root finds the log.installToolHooks(log, { tool, format })registers them in ledger's shims and throwsHookConflictErrorafter writing the rest whencore.hooksPathis set or a foreign hook is in the way,uninstallToolHooksremoves the tool from every shim, andprintToolHooks(log, spec, manager)gives the hook manager snippet instead. Each returns the<tool> hooks … --jsondocument (ToolHooksJson<F>, such asadr-hooks/v1): the shims written and unchanged, repo-relative in hook order, the registrations, the snippet and the trailers;toolHooksResultbuilds it for a tool's own actions. Thecommit-msgstep starts withreadCommitMessage(git, messageFile, { event }), which resolves the message file against the work tree (UsageErrorwhen it's missing) and returns it with itsgit interpret-trailers --parsetext, ornullwhen the message already has a<event>:trailer (any case) or a merge is in progress.stagedEventTrailers(git, layout, { subject, event })then gives the staged added event files' refs (stagedEventRefs(layout, paths): the event files amongpathssorted, deduplicated by subject and type) and theireventTrailers.runPreCommitHook({ tool, worktree, index, env, config, followRenames, renderIndex, verify, dropWorktreeNotes })is thepre-commitstep: rename following on the work-tree log by[hooks] scope_follow_renames(followRenamesin its dry-run orindex: "skip"mode), then with[hooks] index = "stage"the index render staged asindex.md, thenverify, exiting by[verify] fail_on. Neither step stages into a temporary index (git commit <paths>); renames that change a scope then fail the hook with a note.dropWorktreeNotesleaves the work-tree log's own notes out of the rename following's. - Init.
initToolLog(log, spec, { templates, commit, message, skill })is<tool> init, writing no events and never overwriting a file. It writes the starter config unless the log has one: in<root>/<tool>.tomlfor the kind's default root, else a repo-level<tool>.tomlnaming the root, or, when that file names another log, in the root with the note<tool>.toml names <other>; pass --root <root> to use this log. It writes each chosen built-in template to<root>/templates/<name>.md. With[log] index = "committed"it writes<root>/index.mdunless one exists, rendered from the tree the commit (or the work tree) will hold, and refreshes it after the commit (a failed refresh is the note<at> may be stale: …; run <tool> index). Withskill: { dir, version }it writes<dir>/SKILL.mdand appends the pointer line toAGENTS.mdunless a line already names the skill's path (namesSkill(text, skill)), refusing anAGENTS.mdwith unstaged changes or not tracked when committing and leaving it unstaged otherwise. A failed write removes what it wrote. The commit (default[policy] auto_commit) holds only what init wrote and removed, throughcommitWithRecoverywith the spec'srerunandindexAfter(root)hint. The spec (ToolInitSpec) holds the tool's domain and the differences between tools:tool,config([log] index,[policy] auto_commit,[commit] subject),starterConfig({ root, template }),builtins,defaultTemplates(the config names the first when no template is chosen) anddefaultWhenEmpty,templateChoicesfor the unknown-template error,skillText,agentsPointer(skill),indexStep("before-skill"countsindex.mdamong the log files,"after-skill"doesn't),renderIndex,shallowNote(at),action,commitTitle({ logFiles, written, removed, skill }), andremovePlaceholder, which removes an empty<root>/.gitkeeponce init writes a log file and commits its deletion. It returnsToolInitResult:root,config,written,kept,removed,skill,commitandnotes. renderStateHeader(header)prints a subject's state line and warning, for exampleADR-0001 (a7c2m9xd) · supersededand what to read instead.- Text search.
foldText(s)is the case- and accent-insensitive form a tool's search compares (per code point NFKD, combining marks dropped, lower-cased:Café→cafe,fi→fi,ßunchanged), with a map back to the original offsets.searchTerms(query)gives a query's folded, deduplicated terms, and throwsUsageErrorfor an empty query, one over 200 characters or with a control character, or more than 10 terms.countOccurrences(hay, needle)counts non-overlapping hits, andsearchExcerpt(lines, terms)picks the first line with the most terms, cut to about 160 characters around the first hit. Ranking stays with each tool. - Log reads.
readKindLog(kind, tree, { layout, numbering, checkOptions, projectOptions })is a tool's read of its log:loadLog,foldLog, thenloadFindings,transitions,invariantsCheck(checkOptions)andrelateCheck(checkOptions)over oneCheckContextwith no diff, each finding stamped with the kind's name and sorted, andprojectLognumbered withnumbering;projectOptionsreaches the kind'sprojectonly when given. It returns thesnapshot,folded,projectionandfindings(KindLogRead<K>) with the kind's types, and compiles each kind once.numberToolLog(git, { kind, layout, mainRef, index, ref })isnumberLogplus, withindex: "committed", the shallow-clone fallback to<root>/index.mdin the commit read (ref, else HEAD; no numbers when it doesn't resolve), never the work tree's copy.changedSince(log, rev)lists the event files in thereftree (else HEAD's) thatrev's tree lacks, in log order (ChangedSince, thesincekey oflist --since); it throwsRefNotFoundErrorwhen either revision doesn't resolve.unavailableReason(numbering, source)says why numbers are unavailable (shallow clone,<source> has no committed index.md, withthe logfor no source, orno main branch).numberingJson(read)is thenumberingkey of the read documents (NumberingJson:available,reason,ref), andeventsInFoldOrder(events)gives a subject's valid loaded events in fold order forshow --history. - Source reads.
readSourceLog(git, config, { kind, notFetched })reads a[[sources]]entry's log from the cache, once the tool has found and checked the entry: a cached source gives its pinned tree, its layout and the numbers of its committedindex.md(indexNumbering), its commit and no notes; an uncached one gives an emptyMemoryTree, the layout atconfig.root(else the kind'sdefaultRoot),NO_NUMBERING, anullcommit and the notenotFetched.readSourceSubjects(fetched, kind, toForeign)folds a cached source withkind, numbers it from its committed index and maps each view to aForeignSubject(status,display,titleandeffective: the decision in force or the canonical issue);emptyandrootlet the tool say when the source has no log at its root.
CLI (@nikovirtala/ledger/cli)
runCli(tool, processIO()) runs one invocation of a tool defined as commands (CommandSpec: name, options for node:util parseArgs, positionals, and whether it reads --ref or refuses it). Each option (CommandOption) can carry the help line, the value placeholder (default <value>) and, for a boolean, the negatedHelp line of a --no-<name> row that <tool> <command> --help prints. Every tool gets the same globals and exit codes: --json prints exactly one JSON document on stdout, --root <dir> and --ref <ref> choose the log and the tree, -h/--help and -V/--version work everywhere, and the exit code is 0 (success), 1 (failing findings, or a write the log forbids) or 2 (usage, config and environment errors, with an ark-error/v1 document on stdout under --json). Notes go to stderr. runCli never throws. verifyCommand({ open }) is the shared verify [--staged | --base <ref>] [--fetch-sources] [--format text|json|github] command; sourcesCommand({ format, tool, open }) is the shared sources fetch [<name>]. hooksCommand({ tool, possessive, manager, open, install, uninstall, print, preCommit, trailers }) is the shared hooks install | uninstall | print --manager … | run pre-commit | trailers <message-file>, with the tool's steps as callbacks and manager the --manager option's placeholder and help line, if any. editorFromEnv(env, { stdoutIsTTY, failureSuffix }) is the user's editor (VISUAL, else EDITOR, run by sh -c with the path as $1) as an Edit callback, or null when neither is set; without a TTY the editor's stdout goes to stderr, and a failure becomes the note the editor exited with status <n> followed by failureSuffix. indexCommand({ tool, noun, checkHelp, open }) is the shared index [--check] [--commit | --no-commit] [-m <message>]: open returns the tool's [policy] auto_commit and fail_on and its runLogIndex call, and checkHelp is --check's help line, if any. When --base is an upstream spec (@{upstream}, @{u}) and the branch has none, resolveVerifyBase verifies against origin/HEAD's target, origin/main or origin/master instead, with the note no upstream for this branch; verifying against origin/main, and with no remote (or no default branch fetched) it verifies the whole log; any other unresolvable base still exits 2. COMMIT_OPTIONS adds --commit/--no-commit and -m/--message to a command, and commitChoice(values, { autoCommit }) decides whether to commit and checks the message (--message without a commit is a usage error). confirm(io, question, { json }) asks a yes/no question on stderr and returns true only for y or yes; it never asks under --json or without a terminal on stdin and stdout (scripts, CI, hooks), and then returns false.
MCP (@nikovirtala/ledger/mcp)
serveMcp(spec, { env, stderr, transport }) serves a tool's library functions as an MCP server over stdio (the default transport) until stdin ends or the client closes, so <tool> mcp exits 0. A spec names the tool (the prefix of every tool and prompt, <tool>_<verb>, checked at startup), its tools, the tools it knows but doesn't list (unavailable, each with the reason a call gets as JSON-RPC error −32602), resources, resource templates (whole-segment variables such as adr://decision/{id}) and prompts.
- Tools (
McpTool) declare a JSON Schema for their input. ledger compiles it with ajv in strict mode at startup and checks every call against it; invalid input is anisErrorresult with theark-error/v1document, codeusage, listing up to five problems and the tool'sinputHint. - Results. A tool returns
{ document, headers, text }. The document, the tool's CLI--jsondocument, is sent unchanged asstructuredContent; the first text block is the state headers (renderStateHeader), a blank line, then the text; the second is the document as JSON. ALedgerErrorbecomes anisErrorresult withark-error/v1and the error's code (a failed commit's notes included), anything else codeinternal, with the stack on stderr. A refusal is a normal result. - Resources and prompts. A resource read returns the header, a blank line and the text; a template read that returns
nullis MCP's resource-not-found (−32002), aUsageErroris −32602. Prompt arguments are checked (declared names only, required ones present, at most 1,000 characters, no NUL). - Inputs. The input schemas adr and issues share (
McpSchema):ID(1 toMAX_ID, 64, characters),TEXT(1 to 65,536),SECTIONS(up to 50 section ids,^[a-z][a-z0-9-]*$and at most 64 characters, to markdown of at most 65,536),GLOBS(up to 200 globs of 1 toMAX_GLOB_LENGTHcharacters) andSOURCE(SOURCE_NAME, anchored).object(properties, required)makes a tool's input schema with no other properties allowed;READandWRITEare the annotations of a read and a write tool. The argument readersstr,stringsandsectionsOfreturn a string input, an array input's strings and a sections input's string entries, ignoring values of other types;doc(d)passes a library document as a result'sdocument.checkResourceId(id, noun)is a resource template's guard: an{id}longer thanMAX_IDthrowsUsageError(−32602)invalid <noun> "<first 64 characters>…": an id or number is at most 64 characters. - Calls, reads and prompt gets run one at a time, in arrival order.
- Attribution.
mcpAttribution(git, ctx)records an MCP write as an agent named by the MCP client (mcpAgentNamemakes the name safe for the agent rule, with a note when it changed;ARK_AGENT, thenmcp-client, when nothing is left), acting forARK_ON_BEHALF_OFor, with the note, the git identity. Stdio clients pass only a few environment variables to the server, soARK_ON_BEHALF_OFbelongs in the client's server config.
Other layers
- Git.
Git.openruns the system git (2.32.0 or newer) with fixed output settings. It keeps the caller's environment, so inside a hook it reads the commit's index (GIT_INDEX_FILE); temporary repositories and source fetches drop the hook-exported variables (GIT_ENV_ISOLATION).trackedPaths(head)lists the tracked paths of the index, the work tree or a commit,changedPaths(base, head)the paths that differ, andappendTrailers(file, trailers, { ifExists })adds trailers to a commit message file (forcommit-msg), withifExists: "add"keeping repeats such as oneADR:trailer per event.refReader,indexReader,worktreeReaderandMemoryTreeread a tree from a ref, the index, the work tree or memory through oneTreeReaderinterface.firstParentHistoryandparseTrailerBlockread commits and trailers.withGitOperation(fn)runsfnas one git operation: everyGiton the same repository and environment called from it shares answers that depend only on refs and objects (isShallow,symbolicRef,firstParentAdditions,refReader(…).list), until a git command that can change HEAD, a ref or the index runs through any of them, orinvalidateGitOperation()is called, which drops them all; nothing is shared oncefnsettles. AwithGitOperationinside another joins it. A git operation is unrelated to a subject's scope (applies_to). - Identity. Subject ids are 8 lowercase Crockford base32 characters; event ids are ULIDs (in-house, monotonic). Event files are
events/<subject>/<stamp>-<rand>-<type>.yamland bodies<bodies>/<subject>-<slug>.md, under a configurableLogLayout.bodySha256hashes a body with CRLF normalized to LF. - Envelope. The
ledger/v1event envelope with its JSON Schema (envelopeSchema), YAML parsing and serialization (parseEventYaml,serializeEvent), andcompileKind, which validates a kind'sdataschemas with ajv in strict mode. - Log.
loadLogturns a tree into aLogSnapshotof subjects, events and bodies, reporting unreadable files as findings.writeEventvalidates an event and writes its file, never overwriting one (EventExistsError). - Mechanical verify.
verifyLogruns instaged,rangeorfullmode: envelope anddataschemas, identity and file names, duplicate ids, append-only event files, and the body policy (a frozen body can't change, and every freeze event's hash must match it). In staged mode only touched subjects and changed paths are checked.verifySnapshotsruns the same checks on two snapshots, for example fromMemoryTrees. - Sources.
readToolConfigreads<tool>.tomland its[[sources]]; a source'snamefollowsSOURCE_NAME([a-z][a-z0-9-]{0,31}, unanchored, so a tool can anchor it or build it into a larger pattern), whichisSourceName(s)checks; arefis a branch, a tag or a full commit, and refs starting with-or+, or holding:, globs or revision suffixes, are refused.fetchSourcekeeps each source in a bare cache repo under<git common dir>/ark/sources, pinned to itsref. A source repository may use SHA-1 or SHA-256; each cache takes its source's object format and is recreated if the source's format changes.readSources(git, sources, { fetch })reads them:"cache"(the default for every read, write and plainverify) never touches the network, and a source that isn't cached reads asnull;"network"(verify --fetch-sources) fetches each first and throwsSourceFetchError(exit 2) when one fails, even with an older pin cached. Each status records the resolvedcommitand whether it wasfetched, whichverify --jsonreports insources.sourceFindingsgives onesources/not-fetchedwarning per referenced source that isn't cached, andsourcesOfKindspicks the entries of the kinds a tool reads. Qualified ids (<source>:<subject>) are parsed, formatted and resolved against the local log and the sources. - Templates. Section-schema Markdown templates:
parseTemplate,lintTemplate,renderTemplate, andextractSections, which reads a rendered document back into its sections (rendering and extracting round-trip).replaceSections(template, doc, sections)replaces the given sections of a document in place and keeps every other line (findingsrender/unknown-section,render/section-missing,render/heading-in-content).emptyOptional: "drop"leaves an optional section without content out of a render, and letsreplaceSectionsremove such a section with empty text and insert an absent one in template order;extractSectionslists a dropped section inmissing, so the round trip is exact under the default"keep".lintDocumentchecks a document against its template,loadTemplatesreads a template directory, andfindTemplateVersionfinds an older template version in git history, for documents written against it.listKindTemplates(tree, root, { requireSections, builtins })lists the templates a new document can use: those of<root>/templatesthat parse and passlintTemplatewithrequireSections, and thebuiltins(name to template text) that no repo template or file of the same name shadows, sorted by name, with the findings of the templates left out. It takes the section ids rather than a kind, astemplates/sits belowkind/. - Hooks. One generated sh shim per git hook, shared by every ark tool. The registry of tools and their commands is embedded in the shim, and the shim runs every registered tool even after one fails.
installHooksnever overwrites a foreign hook or writes whencore.hooksPathis set; it reports both as conflicts.hookSnippetprints the equivalent config for lefthook, husky or the pre-commit framework.hookRegistrations(commands)lists a tool's command map as registrations in hook order (pre-commit, commit-msg, pre-push, post-merge). Withoutcommands,installHooksregisters the two defaults (DEFAULT_HOOK_COMMANDS):pre-commit: verify --stagedandpre-push: verify --base @{upstream} --ref HEAD --fetch-sources, which falls back asresolveVerifyBasesays on a branch without an upstream.assertNoHookConflicts(result, { tool })turns the conflicts into aHookConflictError(exit 2) that names each one and what to do, so every tool'shooks installreports them the same way.
Testing (@nikovirtala/ledger/testing)
createTempRepocreates hermetic temp repos (no global or system config, no outer repo);TempRepo.envis that environment, for spawning a tool on the repo.forkAndMergebuilds two branch histories and merges or rebases them.exampleKindis a smallKindSchemafor tests, andexampleMachineKinda kind with a state machine (draft, published, retired), freezing and numbering.arbLegalHistory(kind, { data, body })generates legal histories of any kind, including same-atevents whose file order differs from fold order;DataArbssupplies each event type's data from the history so far.arbSemanticTamperandapplySemanticTamperadd one semantic mutation (illegal transition, non-initial first event, missing reason, body without events) with the rules verify must report (semanticExpectedRules).- fast-check arbitraries cover ids, envelopes, event sequences, valid log fixtures (
arbLogFixture), appends that keep a log valid (arbAppend) and mechanical tamper mutations with the rules they must trigger (arbTamper,applyTamper,expectedRules). danglingAnchor({ keyword, taken, seed })gives verifier-mutation tests a code file (a path undersrc/and its text) whose anchor names an id outsidetaken, the same for the same seed.
Not yet included
- Later: qualified-reference checks (step 5; the supersession chain and the issue graph stay in the tools), the GitHub Action that merges findings across tools (step 6), source cache garbage collection, and
template migrate. Event-id uniqueness is checked per log, not across logs.
