npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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/sdk 1.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 as 4 errors, 1 warning;
  • formatJson: a ledger-findings/v1 report with ok, summary and every finding, with null for unknown values (findingsReport returns 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's reduce. 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. compareEvents is the order.
  • Projection. projectLog(kind, folded, { numbering }) builds the kind's views and lists subjects that are unreadable (a newer envelope or schema) or unfoldable. kindFindings maps a kind's findings onto files.
  • Numbering. numberLog(git, { kind, layout, mainRef }) gives display numbers in the order the numbering.on event files first landed on first-parent main. Numbers are computed from file names only, never stored, and never change; a --no-ff merge numbers its acceptances at the merge commit. resolveMainRef prefers origin/HEAD, then origin/main, origin/master, local main and master. A repository without a main branch reports numbers as unavailable (NO_NUMBERING with a reason). In a shallow clone the history is incomplete, so numberLog uses the numbers its fallback returns, 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 holding tree (building on history and merging merging, such as MERGE_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 of history's own first-parent commits after it, then, as one last group, the numbering.on event files in tree that 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's numberLog equals the branch's projection. On main's first-parent line, and without a main ref, the history part is history's first-parent additions. In a shallow clone the history comes from recorded, and the pending subjects are numbered after its highest number. compareNumberingKeys is 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. writeNewFile creates a new file (a body, a template), never overwriting one (FileExistsError). replaceFile(git, path, content, { expected }) replaces an existing file only if it still holds expected, through a temporary file renamed over it, and otherwise throws FileChangedError (code file-changed) and touches nothing. nextEventIdentity picks an at and ULID that sort after a subject's existing events, even with a clock that goes backwards.
  • Git.identity() reads the configured author identity and Git.committerIdentity() the committer, and neither guesses one. Git.commit({ message, trailers, mergeTrailers, only }) commits only the given paths (Git.commitMessage gives the exact message it writes; with mergeTrailers, the trailers join the message's last paragraph when the installed git reads trailers in it, such as Co-authored-by: or Refs: lines, which ledger asks git with one git interpret-trailers --parse call that honours the user's trailer.* config), and stagedPaths, unstagedPaths and untrackedPaths tell a tool what a commit would take.
  • Behaviour change: Git.commit now writes trailers itself, as a literal final paragraph of the message, instead of passing them to git commit --trailer. Repeated keys and their order survive any trailer.* git config. Don't put a trailer block of your own in message unless you pass mergeTrailers, 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 over MAX_TEXT_BYTES (64 KiB) with a UsageError, and checkReason(reason) trims a --reason, refuses an empty one and gives null without one. subjectView(projection, id, { missing, unreadable }) gives a folded subject's view, else a UsageError with unreadable(id) for a subject in a newer format (when given) or missing(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 and o.after; eventFiles(layout, events) serializes events to their paths, and eventPairs(events, keys) gives one trailer pair per event (repeats kept, unlike eventTrailers). precheck(read, files, replace, refold) folds the overlay with the tool's refold and returns it with the findings the write adds (compared by findingKey); 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 follows staged (StagedRenames) in each view's globs, skips unchanged ones, reports blocked(view, leaving)'s note for a view whose state forbids a new scope, refuses more than 200 globs, notes skipped and gained files, and collects change(view, globs) until one returns { stop }.
  • Apply step. applyPlan(log, plan, o) applies a tool's WritePlan (the subject, files, replace, events, stage, commitScope, eventDirs, trailers, findings and notes a tool's plan extends). With o.commit it first takes the commit scope (o.scope(plan), default the plan's commitScope and eventDirs) 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, runs o.afterStage(scope) (the editor step, which can replace the findings or turn the commit off), and commits plan.stage plus the scope's staged files with --only and eventTrailers with o.trailerKeys (the plan's own trailers only for a plan without events). The message is o.message (with mergeTrailers) or what o.compose({ plan, extra, tree }) (ComposeInput) renders; giving both, or neither when committing, is an InvalidArgumentError. After the editor step the index is rendered again with o.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 sets compose's tree), and refreshed from the work tree after the commit. A failed commit throws CommitFailedError with WRITE_RERUN and the notes so far; the index hints use indexBeforeHint/indexAfterHint with o.tool and o.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 returns AppliedPlan: written (replaced, then new files, then the index), commit, findings, notes and rendered.
  • Write driver. runWrite(o) is the loop around a tool's plan and apply, inside withGitOperation. checkWorkTree(log) refuses a log opened at a ref or with another tree reader (InvalidArgumentError); with a commit (o.commit, default o.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 with planContext(log, root, builtins, deps) (PlanContext: the clock and randomness of deps, the built-in templates, and templates read from the work tree, else from the history templateHistoryRef gives). A refused plan (PlanRefusal) becomes o.refused(r, notes) with the log's and the caller's notes, then o.refusalNotes(r). A plan with nothing to write, and every plan with o.dryRun, becomes o.done(outcome) without touching the repository. With o.requireCommitParts, committing a plan whose commit is null is an InvalidArgumentError. Otherwise o.apply(plan, read, commit) writes it; the outcome (WriteOutcome) has the views from viewsAfter(sha, views, reread) (the plan's own o.views(plan) without a commit, else those of o.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. An EventExistsError plans and applies once more; a CommitFailedError gets the log's, the caller's and the plan's notes first. The plan is a DriverPlan: a WritePlan with commit parts and a draft (DraftFile). editorStep({ git, edit, onNote, editorNotes, finding }) gives the afterStage of new: 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 by finding). editorNotes also passes the failed editor's own note to onNote. readIfPresent(path) and sameBytes(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. parseGlob and globMatcher match 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 over MAX_GLOB_LENGTH (500) characters are refused with a GlobProblem and 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 whose data.set is the complete set; the latest applied one wins (latestSet). applySetOp(current, { set | add | remove }, { what, validate, maxItems, names }) applies a --set/--add/--remove style change and returns the new set sorted and deduplicated, with what was added, removed, already present or absent; names sets the flag names its UsageError messages use. adr's scoped and issues' assigned/labeled use it.
  • Anchors. scanAnchors(git, { keyword, tree, paths, excludeDirs, exclude }) finds <keyword>:<id> and <keyword>:<source>:<id> tokens with one git grep in the work tree, the index or a commit; anchorsInLine applies 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, the excludeDirs and files matching an exclude glob aren't found, and a comment leader inside a string literal counts like a real one.
  • Renames. stagedRenames(git) reads the renames staged against HEAD (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 behind adr for and issues for: it takes 1 to 100 paths relative to cwd, refuses paths outside the repository, paths over 4096 characters and directories (found with lstat in the work tree, by listing the index for a path missing from it, or by listing the ref's tree) with a UsageError naming tool, drops duplicates, and returns per path whether it is tracked (in the index, or in the ref's tree), the matches of scopeLookup over globSubjects and the anchors read from the work tree or the commit, and the unresolved anchors by line: other-log for a qualified one, not-found for a local one whose id known rejects. globSubjects are only the subjects whose globs apply, while known covers every subject, so an anchor to an inactive subject still matches and each tool filters matches itself.
  • Checks. Verify checks for kinds with scope, which need CheckContext.repo. scopeGlobCheck() reports scope/glob-invalid for a stored glob that doesn't parse and scope/glob-unmatched for a glob that matches no tracked file, for statuses in scope.requireMatchIn (default activeIn), so a kind's planned states can name code that doesn't exist yet; defineKind refuses a requireMatchIn state outside activeIn. anchorCheck({ keyword, exclude }) reports scope/anchor-missing for a local anchor whose id isn't in the log; qualified anchors aren't checked, and paths matching an exclude glob 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 of statuses governs, and narrowedScopes(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 an IndexSpec (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. escapeMarkdown escapes table cells.
  • parseIndexNumbers(text) reads the numbers line back (null for 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 as numberLog's fallback and projectNumbering's recorded in shallow clones. indexNumbering(byId) turns that map into the Numbering a tree read without history, such as a cached source's, gets from its committed index (reason index), or NO_INDEX_NUMBERING for null.
  • indexCheck({ path, expected, fix }) is the verify check that the file is what the tool renders for the head: index/missing, index/stale, or the index/unchecked warning when the bytes can't be computed (a shallow clone without a recorded index). In scope changed it runs only when the log has changes.
  • writeIndexFile(git, path, text) writes the file atomically and returns false, touching nothing, when it already holds text.
  • renderLogIndex(git, { kind, layout, mainRef, tree, history, views, spec }) is a tool's whole render: it numbers tree's subjects with projectNumbering as they will be once the commit holding tree (which builds on history) is on main, merging MERGE_HEAD while a merge is in progress and falling back to the numbers history's index.md recorded in a shallow clone, then renders spec(root, views) of the tool's views(tree, numbering). It returns null when 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 as docs/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] root in <repo>/<tool>.toml, else the kind's defaultRoot, with <root>/<tool>.toml as the alternative config file. It reads config and log from the same tree (the --ref tree, 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>.toml with errors (ConfigError) that name file, else config.file, else <tool>.toml: table(name) ({} when missing, refusing anything but a table), bool(t, section, key, fallback) and oneOf(t, section, key, values, fallback), plus its fail, where and config. parseSharedKeys(reader, { defaults, indexValues }) validates the keys every tool config has, [log] default_template, main_branch and index, [policy] auto_commit, [verify] fail_on, [scope] anchor_keyword and anchor_exclude (at most 100 globs), [hooks] scope_follow_renames and index, and [commit] subject (through readCommitTemplate with defaults.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_branch and index, for a tool that reads another tool's numbering. indexValues is the order the log.index message lists "committed" and "none" in.
  • resolveAttribution(git, { env, agent }) returns the actor a write is recorded as, with notes for the user. Without ARK_AGENT (or agent) it is the human from the git identity. With it, it is an agent acting on behalf of ARK_ON_BEHALF_OF, or, when that isn't set, of the git identity's email, with the note on_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. An ARK_ON_BEHALF_OF that isn't an email address (parseOnBehalfOf) is a ConfigError (exit 2 in the CLI). ARK_ON_BEHALF_OF without ARK_AGENT is ignored, with a note. resolveActor returns just the actor.
  • The git identity is git's author identity (git var GIT_AUTHOR_IDENT with user.useConfigOnly): GIT_AUTHOR_NAME and GIT_AUTHOR_EMAIL when set, else user.name and user.email; it is never guessed. Setting GIT_AUTHOR_* also changes the author of --commit commits, which is why agents should use ARK_ON_BEHALF_OF instead.
  • Commit messages. readCommitTemplate(config, { file, vars, defaultSubject, names }) reads [commit] subject from <tool>.toml, a one-line template such as docs(adr): {action} {title} with {title} (the title with an ordinary capitalized first word lowercased, acronyms, identifiers and mixed-case names such as CLI, ARK_AGENT or GraphQL kept), {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; parseCommitTemplate checks it, including that each of names (a name the title placeholder can hold instead of a title, such as ADR-0001 with ADR-0002) fits uncut. renderCommitMessage(template, { title, vars, body, slot }) keeps the Conventional Commits description within MAX_DESCRIPTION (72) characters by shortening the title with …, at a word boundary when one is near the limit, and putting Full title: <title> in the body, and wraps body paragraphs at 72 (wrapParagraph). With slot: { before, after, quote } the title placeholder holds before, the title (in double quotes with quote) and after; only the title is shortened. RenderedCommit.note is the note to report when it was shortened, naming the 72-character limit of the description after the Conventional prefix. joinActions joins a batch's verbs (link, scope and comment on), and eventTrailers(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 among paths, sorted by path and deduplicated, for those trailers. checkCommitMessage checks a --message given 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 like Git.commit; when git commit fails (a hook, signing) and HEAD didn't move, it saves the full message, trailers included, to <git dir>/ark/COMMIT_MSG (saveCommitRecovery) and throws CommitFailedError (code commit-failed, exit 2). Its message lists the staged paths and the trailers, gives the exact git -C <top> commit --cleanup=whitespace -F <file> --only -- <paths> command, and includes the caller's rerun sentence on why running the tool again won't help. withNotes(notes) attaches the notes the write would have reported, which runCli prints as warnings before the error and puts in the ark-error/v1 document's notes.
  • Index merge driver. <tool> index --merge is git's merge driver for a log's committed index.md (runLogIndexMerge(log, { tool, noun, render, index }, args, { env, cwd })): identifyMerge finds 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 %Y labels, which exist from git 2.44), mergeLog merges the log's other files three-way in memory (overlayTree, MemoryTree), and the tool's render renders them with HEAD as history (and merging for 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, uninstallMergeDriver and mergeDriverState set and read merge.<tool>-index.{name,driver,recursive} in the clone's local config; installToolHooks and doctor --fix-clone call them for a log with [log] index = "committed" (commitsIndex), and gitattributesLines(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: with check it reports logIndexCheck'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 (default autoCommit) it commits HEAD's render of <root>/index.md alone 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 be committed, [policy] auto_commit, [commit] subject), its commit title and action, its JSON format (LogIndexJson<F>, such as adr-index/v1) and render(git, { tree, history }), its renderLogIndex call 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 to git add. The recovery hints of failed index commits are indexRerunHint(tool), indexBeforeHint(tool, plural, root) and indexAfterHint(tool, plural, root). ToolWriteOptions holds 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-sources and list --since ORIG_HEAD, with --root <root> first only when neither <repo>/<tool>.toml nor the kind's default root finds the log. installToolHooks(log, { tool, format }) registers them in ledger's shims and throws HookConflictError after writing the rest when core.hooksPath is set or a foreign hook is in the way, uninstallToolHooks removes the tool from every shim, and printToolHooks(log, spec, manager) gives the hook manager snippet instead. Each returns the <tool> hooks … --json document (ToolHooksJson<F>, such as adr-hooks/v1): the shims written and unchanged, repo-relative in hook order, the registrations, the snippet and the trailers; toolHooksResult builds it for a tool's own actions. The commit-msg step starts with readCommitMessage(git, messageFile, { event }), which resolves the message file against the work tree (UsageError when it's missing) and returns it with its git interpret-trailers --parse text, or null when 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 among paths sorted, deduplicated by subject and type) and their eventTrailers. runPreCommitHook({ tool, worktree, index, env, config, followRenames, renderIndex, verify, dropWorktreeNotes }) is the pre-commit step: rename following on the work-tree log by [hooks] scope_follow_renames (followRenames in its dry-run or index: "skip" mode), then with [hooks] index = "stage" the index render staged as index.md, then verify, 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. dropWorktreeNotes leaves 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>.toml for the kind's default root, else a repo-level <tool>.toml naming 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.md unless 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). With skill: { dir, version } it writes <dir>/SKILL.md and appends the pointer line to AGENTS.md unless a line already names the skill's path (namesSkill(text, skill)), refusing an AGENTS.md with 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, through commitWithRecovery with the spec's rerun and indexAfter(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) and defaultWhenEmpty, templateChoices for the unknown-template error, skillText, agentsPointer(skill), indexStep ("before-skill" counts index.md among the log files, "after-skill" doesn't), renderIndex, shallowNote(at), action, commitTitle({ logFiles, written, removed, skill }), and removePlaceholder, which removes an empty <root>/.gitkeep once init writes a log file and commits its deletion. It returns ToolInitResult: root, config, written, kept, removed, skill, commit and notes.
  • renderStateHeader(header) prints a subject's state line and warning, for example ADR-0001 (a7c2m9xd) · superseded and 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 throws UsageError for an empty query, one over 200 characters or with a control character, or more than 10 terms. countOccurrences(hay, needle) counts non-overlapping hits, and searchExcerpt(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, then loadFindings, transitions, invariantsCheck(checkOptions) and relateCheck(checkOptions) over one CheckContext with no diff, each finding stamped with the kind's name and sorted, and projectLog numbered with numbering; projectOptions reaches the kind's project only when given. It returns the snapshot, folded, projection and findings (KindLogRead<K>) with the kind's types, and compiles each kind once. numberToolLog(git, { kind, layout, mainRef, index, ref }) is numberLog plus, with index: "committed", the shallow-clone fallback to <root>/index.md in 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 the ref tree (else HEAD's) that rev's tree lacks, in log order (ChangedSince, the since key of list --since); it throws RefNotFoundError when either revision doesn't resolve. unavailableReason(numbering, source) says why numbers are unavailable (shallow clone, <source> has no committed index.md, with the log for no source, or no main branch). numberingJson(read) is the numbering key of the read documents (NumberingJson: available, reason, ref), and eventsInFoldOrder(events) gives a subject's valid loaded events in fold order for show --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 committed index.md (indexNumbering), its commit and no notes; an uncached one gives an empty MemoryTree, the layout at config.root (else the kind's defaultRoot), NO_NUMBERING, a null commit and the note notFetched. readSourceSubjects(fetched, kind, toForeign) folds a cached source with kind, numbers it from its committed index and maps each view to a ForeignSubject (status, display, title and effective: the decision in force or the canonical issue); empty and root let 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 an isError result with the ark-error/v1 document, code usage, listing up to five problems and the tool's inputHint.
  • Results. A tool returns { document, headers, text }. The document, the tool's CLI --json document, is sent unchanged as structuredContent; the first text block is the state headers (renderStateHeader), a blank line, then the text; the second is the document as JSON. A LedgerError becomes an isError result with ark-error/v1 and the error's code (a failed commit's notes included), anything else code internal, 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 null is MCP's resource-not-found (−32002), a UsageError is −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 to MAX_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 to MAX_GLOB_LENGTH characters) and SOURCE (SOURCE_NAME, anchored). object(properties, required) makes a tool's input schema with no other properties allowed; READ and WRITE are the annotations of a read and a write tool. The argument readers str, strings and sectionsOf return 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's document. checkResourceId(id, noun) is a resource template's guard: an {id} longer than MAX_ID throws UsageError (−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 (mcpAgentName makes the name safe for the agent rule, with a note when it changed; ARK_AGENT, then mcp-client, when nothing is left), acting for ARK_ON_BEHALF_OF or, with the note, the git identity. Stdio clients pass only a few environment variables to the server, so ARK_ON_BEHALF_OF belongs in the client's server config.

Other layers

  • Git. Git.open runs 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, and appendTrailers(file, trailers, { ifExists }) adds trailers to a commit message file (for commit-msg), with ifExists: "add" keeping repeats such as one ADR: trailer per event. refReader, indexReader, worktreeReader and MemoryTree read a tree from a ref, the index, the work tree or memory through one TreeReader interface. firstParentHistory and parseTrailerBlock read commits and trailers. withGitOperation(fn) runs fn as one git operation: every Git on 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, or invalidateGitOperation() is called, which drops them all; nothing is shared once fn settles. A withGitOperation inside 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>.yaml and bodies <bodies>/<subject>-<slug>.md, under a configurable LogLayout. bodySha256 hashes a body with CRLF normalized to LF.
  • Envelope. The ledger/v1 event envelope with its JSON Schema (envelopeSchema), YAML parsing and serialization (parseEventYaml, serializeEvent), and compileKind, which validates a kind's data schemas with ajv in strict mode.
  • Log. loadLog turns a tree into a LogSnapshot of subjects, events and bodies, reporting unreadable files as findings. writeEvent validates an event and writes its file, never overwriting one (EventExistsError).
  • Mechanical verify. verifyLog runs in staged, range or full mode: envelope and data schemas, 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. verifySnapshots runs the same checks on two snapshots, for example from MemoryTrees.
  • Sources. readToolConfig reads <tool>.toml and its [[sources]]; a source's name follows SOURCE_NAME ([a-z][a-z0-9-]{0,31}, unanchored, so a tool can anchor it or build it into a larger pattern), which isSourceName(s) checks; a ref is a branch, a tag or a full commit, and refs starting with - or +, or holding :, globs or revision suffixes, are refused. fetchSource keeps each source in a bare cache repo under <git common dir>/ark/sources, pinned to its ref. 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 plain verify) never touches the network, and a source that isn't cached reads as null; "network" (verify --fetch-sources) fetches each first and throws SourceFetchError (exit 2) when one fails, even with an older pin cached. Each status records the resolved commit and whether it was fetched, which verify --json reports in sources. sourceFindings gives one sources/not-fetched warning per referenced source that isn't cached, and sourcesOfKinds picks 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, and extractSections, 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 (findings render/unknown-section, render/section-missing, render/heading-in-content). emptyOptional: "drop" leaves an optional section without content out of a render, and lets replaceSections remove such a section with empty text and insert an absent one in template order; extractSections lists a dropped section in missing, so the round trip is exact under the default "keep". lintDocument checks a document against its template, loadTemplates reads a template directory, and findTemplateVersion finds 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>/templates that parse and pass lintTemplate with requireSections, and the builtins (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, as templates/ sits below kind/.
  • 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. installHooks never overwrites a foreign hook or writes when core.hooksPath is set; it reports both as conflicts. hookSnippet prints 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). Without commands, installHooks registers the two defaults (DEFAULT_HOOK_COMMANDS): pre-commit: verify --staged and pre-push: verify --base @{upstream} --ref HEAD --fetch-sources, which falls back as resolveVerifyBase says on a branch without an upstream. assertNoHookConflicts(result, { tool }) turns the conflicts into a HookConflictError (exit 2) that names each one and what to do, so every tool's hooks install reports them the same way.

Testing (@nikovirtala/ledger/testing)

  • createTempRepo creates hermetic temp repos (no global or system config, no outer repo); TempRepo.env is that environment, for spawning a tool on the repo. forkAndMerge builds two branch histories and merges or rebases them.
  • exampleKind is a small KindSchema for tests, and exampleMachineKind a kind with a state machine (draft, published, retired), freezing and numbering.
  • arbLegalHistory(kind, { data, body }) generates legal histories of any kind, including same-at events whose file order differs from fold order; DataArbs supplies each event type's data from the history so far. arbSemanticTamper and applySemanticTamper add 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 under src/ and its text) whose anchor names an id outside taken, 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.