Architecture¶
Feature contexts group command-specific behavior across domain, application,
infrastructure, and presentation layers. Shared types and services live in
core/kernel, core/protocol, core/workspace, core/text, and core/store.
Contexts¶
| Context | Layers present | Responsibility |
|---|---|---|
| core/kernel | domain | Shared value types: path, selector, guard, duration, size, digests and the content hash, token estimate, unified diff generation, parsing, and application. |
| core/protocol | domain, application, infrastructure | Envelopes, the error catalog, secret masking, the schema model, the command registry, unknown-name repairs, the streaming JSON writer. |
| core/workspace | domain, application, infrastructure | Root resolution, the write boundary, native .gitignore evaluation, the parallel ordered scan. |
| core/text | domain, application, infrastructure | Byte decoding, line index, binary sniffing, line endings and BOM, charsets and encoding guesses, MIME, the language table, and byte-format codecs (DEFLATE and gzip via cl-deflate-kit, ZIP, and TAR). |
| core/store | domain, application, infrastructure | State directory, locks, the write protocol and recovery, the journal, blobs, the tx overlay. |
| feature/search | domain, application, infrastructure, presentation, composition | search, find, code outline, code defs, code refs, overview |
| feature/inspect | domain, application, infrastructure, presentation, composition | read, info, check, diff, doc get/select/diff, table read/agg, archive list/read, snapshot create/diff |
| feature/edit | domain, application, infrastructure, presentation, composition | The edit context's write commands, from edit through archive create in the command index |
| feature/journal | domain, application, infrastructure, presentation, composition | history, undo, the tx group |
| feature/process | domain, application, infrastructure, presentation, composition | run, wait, signal, the bg group |
| feature/org | domain, application, infrastructure, presentation, composition | Org outline, query, export, agenda and clock reports; TODO, property, planning, clock, and table updates |
| feature/env | domain, application, infrastructure, presentation, composition | The sys and time groups |
| feature/md | domain, application, infrastructure, presentation, composition | md headings, md read, md replace |
| feature/util | domain, application, infrastructure, presentation, composition | The util group |
| feature/net | domain, application, infrastructure, presentation, composition | net get, net head, net resolve |
schema and batch read or run commands of every context, so they belong to
no context; they live in the composition root, src/schema.lisp and
src/batch.lisp.
CLI groups organize user-facing commands and can span contexts: doc get is
in inspect, while doc set is in edit. Contexts organize implementation
ownership and dependency boundaries.
Placement decisions¶
A cl-boundary-kit boundary context groups effect capabilities under names.
Application flows retrieve a capability with boundary-context-require.
Composition assembles the context, and infrastructure supplies production
adapters.
- Byte codecs in core/text.
archive listandarchive read(inspect) andarchive extractandarchive create(edit) all need deflate, gzip, zip, and tar.cl-deflate-kitsupplies DEFLATE and gzip; core/text keeps the ZIP and TAR codecs. A feature domain may not depend on another feature context, so the adapters and archive codecs live inpackages/core/text/src/domain/codec-*.lisp, where both can reach them. - Command registry in core/protocol. A presentation layer may reference
protocol but not the composition root, and presentation modules load
before
aitools/cli. Somake-command-registryandregister-commandlive inpackages/core/protocol/src/application/command-registry.lisp. The registry treats cl-cli command values as opaque; onlyfinalize-app-commands(src/registry.lisp) interprets them, which keeps theaitoolssystem free of cl-cli. - core/text has an application layer.
call-with-sniffed-octets/kandcall-with-text-file/k(packages/core/text/src/application/source.lisp) give every context one way to read a file's bytes through the text boundary context, deciding text or binary from the first bytes over a single open. - The streaming JSON writer in protocol infrastructure calls json-kit.
json-kit is otherwise a domain-layer kit, but writing an envelope directly
to the output stream, rather than building the whole document as a string
first, requires calling
json-kit:write-jsonwhere the stream is (packages/core/protocol/src/infrastructure/json-writer.lisp). - Org parsing and export live in feature/org. The infrastructure adapter
calls
cl-org-kitandcl-date-kit; application flows reach these APIs through boundary contexts. The structure test allows only the adapter's used kit symbols for this context. File reads go through text and workspace boundary contexts. Export supports HTTP, HTTPS, and mailto links; it rejects other link types.
Layers and dependency direction¶
| Layer | Holds | May reference |
|---|---|---|
| domain | Values, rules, pure functions; no I/O | Its own domain, every core context's domain, and pure APIs from kits (deterministic functions without I/O), including cl-regex-kit, json-kit, cl-codec-kit, cl-crypto-kit, cl-date-kit, and cl-deflate-kit |
| application | Use cases and continuation-based flow | Its own domain and application, core domains and applications, and (feature contexts only) other feature contexts' applications; cl-boundary-kit boundary objects and fakes; in Store, the pure resilience-kit:make-retry-policy constructor |
| infrastructure | Production adapters and host effects | Its own domain and application, host-kit, process-kit, cl-concurrent-kit, cl-boundary-kit, sb-posix, and json-kit; in Store, resilience-kit:call-with-retry and resilience-kit:retry-exhausted |
| presentation | cl-cli command definitions, argument conversion | Its own application, aitools.protocol.domain, aitools.protocol.application, cl-cli |
| composition | Context registration and dependency construction | That context's presentation and infrastructure, aitools/cli |
The define-flow, flow-call, and flow-continue macros live in
aitools.kernel.domain. Both domain and application packages can use this
dependency-free DSL without reversing the dependency direction.
The kernel domain keeps sha256-hex and content-hash; sha256-hex delegates
to crypto-kit:digest-hex from cl-crypto-kit. The inspect domain exposes
info-digest-hex for the algorithms used by info --digest. It calls
crypto-kit:digest-hex for MD5 and SHA-1 and uses the kernel's SHA-256 helper
for SHA-256. These pure computations map octet vectors to lowercase
hexadecimal digests. The kernel domain has no application dependencies, so
domain and application flows can share the DSL without reversing the dependency
direction.
Store application uses resilience-kit:make-retry-policy only to describe
lock retry behavior. The POSIX Store boundary context supplies the clock and
sleeper; its infrastructure adapter implements call-with-retry through
resilience-kit:call-with-retry and maps
resilience-kit:retry-exhausted to NIL. Store application then calls its
timeout continuation when no lock was acquired. In other words, NIL means
that lock acquisition timed out.
Each context/layer pair is one package, aitools.<context>.<layer>
(aitools.search.domain). Table data lives in the shared aitools.data
package, filled by data/<layer>/<context>/*-data.lisp files that each
export their own symbols.
Secret format prefixes and assignment key names live in
data/domain/protocol/redaction-patterns-data.lisp. The protocol matcher
derives its first-character dispatch table from those values for each masking
scan. Add a pattern there, rebuild aitools, and cover its masking behavior
in the protocol tests. The scanner needs no branch change.
The structure test¶
t/integration/structure-test.lisp enforces the table. For every
packages/<core|feature>/<context>/src/<layer>/*.lisp file, it strips
comments, strings, and character literals and looks for package-qualified
references (name: or name::) to any package it knows. It also checks package
designators in DEFPACKAGE clauses such as :USE, :IMPORT-FROM,
:SHADOWING-IMPORT-FROM, and :LOCAL-NICKNAMES. A dependency that the file's
layer may not make is a violation.
The structure test also supports context-specific symbol allowances, each
with a reason. The Org adapter may reference only the kit symbols it uses.
Protocol infrastructure may use JSON-KIT for the streaming JSON writer.
Neither allowance adds a kit to a global package list.
The test also runs against fixtures under t/integration/fixtures/: three
violating trees (a domain file referencing an effectful kit, a core file
referencing a feature context, an application file referencing another
context's domain) must fail, and a clean tree must pass.
The scan covers packages/ only; the composition root in src/ may
reference every layer.
Context dependencies and registration¶
Feature dependency constructors provide cl-boundary-kit boundary contexts.
They either assemble capabilities in composition or use production adapters
from infrastructure. Application flows retrieve capabilities with
boundary-context-require; tests provide fakes through the same contexts.
The structure test permits make-boundary-context and
boundary-context-with in composition, application, and infrastructure, and
rejects them in domain. See steps 3 and 4 of
Adding a command for the
registration flow.
Context-owned feature registration modules live under
packages/feature/<ctx>/src/composition/context-registration.lisp.
Each declares its registrar and dependency constructor with
aitools/cli::define-context-command-registration. The macro stores the
constructor without inspecting it or its return value. The CLI composition
root in src/context-registration.lisp invokes each constructor with shared
runtime dependencies and passes the result unchanged to the registrar. The
order follows aitools/cli's feature presentation dependencies, which an
integration test checks.
Store's filesystem boundary context includes operations that the general
cl-boundary-kit filesystem boundary does not provide: exclusive creation
with fsync, separately synced append, lstat without following symlinks,
chmod, symlink creation, and flock. Infrastructure builds the production
context, and tests provide fakes through boundary contexts.
Command handler contract¶
A presentation handler converts parsed options into a flow call wrapped in
call-with-command-result/k
(packages/core/protocol/src/application/command-result.lisp). The flow
receives three continuations and calls exactly one: on-ok or on-partial
with an alist of output fields in envelope order, or on-error with
(code message &key candidates diagnostics conflicts repairs). A flow never
writes to a stream and never chooses an exit code. src/dispatch.lisp turns
the result into an envelope and an exit code, and adds recovered.
See CPS audit for the flow and continuation conventions, and
the success envelope for field order and
the error envelope for error fields.
dispatch calls cl-cli's parse-argv directly instead of run-app,
because run-app prints usage errors and help as plain text. Every exit
from dispatch, including an uncaught condition, writes one JSON envelope.
State directory¶
The store keeps all state outside the working tree, under
$XDG_STATE_HOME/aitools/ (or ~/.local/state/aitools/), one directory
per workspace:
<state>/<workspace-id>/
lock workspace lock (flock)
commit/ intent records of in-flight writes
journal/ops.jsonl one line per committed operation
blobs/ contents named by content hash, shared by journal and tx
tx/<tx-id>/ open transactions
snapshots/ bg/ tmp/ snapshot records, bg logs, mktemp area
The workspace id is the root directory's name followed by the first 16 hex
digits of the SHA-256 of the root's real path (workspace-id in
packages/core/store/src/domain/layout.lisp). The write protocol creates
temporary files in the working tree named .aitools-<op_id>-<n>.tmp; every
scan excludes them.
The store creates its state files with mode 0600 and its directories with
mode 0700, opening files O_CREAT|O_EXCL|O_NOFOLLOW, so the state is
private to the owner and a pre-planted symlink cannot redirect a create.
The bg records store a redacted copy of the launched argv. bg status displays
that value and does not rerun it, so the displayed command line contains no raw
secrets.
The journal keeps the newest 20 operations per path
(+retained-generations+ in packages/core/store/src/domain/journal.lisp).
The workspace and per-transaction locks use exclusive flock(2) on lock files.
Store application supplies a retry policy with delays that grow from 5 ms to
100 ms, bounded by --lock-timeout, which defaults to 10s (see
global options and
packages/core/store/src/application/lock.lisp).
The OS releases a lock when its process exits.
CPS audit¶
aitools uses continuation-passing style at control boundaries and plain
return values for computations with one outcome. Control boundaries are
traversals (an emit continuation per element), operations with several
outcomes (a name/k function with one continuation per exit), the command
boundary (ok, partial, and error continuations), and resources that must be
released on every exit (a call-with-X function, with a with-X macro as
sugar). The tables list the applied sites per context, found with:
rg -n -U -uuu \
'^\s*\(def(un|macro)\s+([a-z0-9%-]*/k|call-with-[a-z0-9-]*|with-[a-z0-9-]*)\b|define-flow\s+\(\s*[a-z0-9%-]*/k\b' \
packages src
Names starting with % are internal helpers of the listed functions and are
omitted.
Multiple exits (name/k) and resources (call-with-X)¶
| Context | /k functions (multiple exits) |
call-with-X resources |
|---|---|---|
| kernel | apply-hunks/k, json-model-resolve/k |
none |
| protocol | none | call-with-command-result/k (ok, partial, error; returns the command result) |
| workspace | call-with-resolved-root/k, call-with-workspace-boundary/k (inside, outside), call-with-scan-options/k, resolve-user-path/k (inside, outside) |
call-with-workspace-scan/k (emit per entry), call-with-ordered-mapper (worker pool) |
| text | decode-utf8-strict/k, decode-octets/k, encode-string/k |
call-with-sniffed-octets/k (text, binary, missing, unreadable, too large), call-with-text-file/k |
| store | plan-changes/k, commit-changes/k, recover/k (rolled forward, discarded, none, busy), undo-op/k, tx-begin/k, tx-status/k, tx-stage/k, tx-record-read/k, tx-drop/k, tx-rebase/k, tx-diff/k, tx-commit/k, tx-abort/k |
call-with-workspace-lock/k and with-workspace-lock, call-with-tx-lock/k and with-tx-lock (acquired, timeout), call-with-tx-view/k, call-with-prepared-intent/k and with-prepared-intent (intent record and write temp files), call-with-temp-file and with-temp-file, call-with-temp-dir and with-temp-dir |
| search | build-matcher/k, search/k, find/k, code-outline/k, code-defs/k, code-refs/k, overview/k, scan-options/k |
call-with-session/k, call-with-regex-budget/k |
| inspect | parse-selector-options/k, resolve-selector/k, resolve-line-selector/k, text-view/k, record-read/k, compile-pattern/k, resolve-json-pointer/k, make-comparison/k, parse-json-document/k, parse-yaml-write-document/k, parse-toml-write-document/k, decode-charset-lines/k, parse-table/k, table-comparison/k, open-archive/k, archive-item-content/k, decode-snapshot/k, call-with-regex-limit/k (result, step limit) |
call-with-readable-file/k, call-with-inspect-file/k, call-with-target-text/k, call-with-archive/k |
| edit | run-write-command/k, check-expect-count/k, require-expect-hash/k, resolve-extra-path/k, read-stdin/k, read-stdin-text/k, read-stdin-json/k, read-input-file/k, read-content/k, read-content-text/k, read-file-octets/k, read-document/k, parse-selector/k, resolve-lines/k, scan-files/k, compile-pattern/k, decode-text-document/k, parse-json-text/k, find-old/k, compile-search-pattern/k |
call-with-regex-refusals |
| journal | none of its own; its flows call the store's /k functions |
none |
| process | run-command/k, wait-until/k, wait-command/k, bg-start/k, bg-logs/k, bg-status/k, bg-stop/k, signal-command/k |
call-with-bg-log and with-bg-log |
| org | org-read-document/k, org-outline/k, org-query/k, org-export/k, org-agenda/k, org-clock-report/k, org-todo-set/k, org-property-set/k, org-property-delete/k, org-planning-set/k, org-planning-delete/k, org-clock-in/k, org-clock-out/k, org-table-align/k, org-table-sort/k, org-table-recalculate/k |
none |
| env | resolve-zone/k, time-now/k, time-convert/k, time-diff/k, sys-info/k, sys-env/k, sys-tools/k, sys-procs/k, sys-metrics/k, sys-snapshot/k, sys-network/k, sys-disk/k, sys-ports/k |
none |
| md | md-headings/k, md-read/k, md-replace/k |
none |
| util | none | none |
| net | get/k, head/k, resolve/k |
none |
| composition root | call-with-invocation-workspace/k (ready, busy, invalid timeout) |
none |
The util flows resolve-input, evaluate-expression, and decode-text use
continuations without the /k suffix.
Resources¶
| Resource | Form | Used by |
|---|---|---|
| Intent record and the write protocol's temporary files | call-with-prepared-intent/k, with-prepared-intent (packages/core/store/src/application/write-preparation.lisp) |
commit-changes/k (write-protocol.lisp) |
| A temporary file renamed into place | call-with-temp-file, with-temp-file (packages/core/store/src/application/files.lisp) |
blob writes (blobs.lisp) and whole-file replacement of store files (files.lisp) |
| A temporary directory filled, then renamed into place | call-with-temp-dir, with-temp-dir (files.lisp) |
tx-begin/k, which builds the tx directory under a staging name (tx.lisp) |
| The bg log | call-with-bg-log, with-bg-log (packages/feature/process/src/infrastructure/host.lisp) |
bg start (bg-launcher.lisp) |
call-with-prepared-intent/k distinguishes three exits. An error before
the commit point removes the temporary files and, best effort, the
incomplete intent record, then lets the error propagate; the workspace was
never touched. A non-error unwind (the test fault injector's :throw mode)
skips the error-only cleanup and leaves the prepared state for recovery,
matching the store data left by a dead process. The unwind still releases the
flock; actual process death lets the operating system release it. A normal
return is the commit, so a complete intent record survives for recovery to
roll forward. call-with-temp-file and
call-with-temp-dir remove the temporary path after their function returns
or unwinds; after a successful rename there is nothing left to remove. The
bg log is reopened with O_APPEND|O_NOFOLLOW at mode 0600 and closed on
any exit.
The paths mktemp creates are not resources: they are the command's result
and outlive the call by design. mktemp removes entries of its area older
than 7 days when it runs
(packages/feature/edit/src/application/mktemp.lisp).
Traversals with emit continuations¶
Each function invokes a callback for every element. A callback's :stop
return ends only the traversals marked yes.
| Function | Elements | Stops on :stop |
File |
|---|---|---|---|
call-with-workspace-scan/k |
Directory entries, in path order | yes | packages/core/workspace/src/application/scan.lisp |
map-lines |
Lines of a byte buffer | yes | packages/core/text/src/domain/line-index.lisp |
map-matches, map-selected-lines |
Regex matches and selected lines | no | packages/feature/search/src/domain/matcher-scan.lisp |
map-word-occurrences |
Identifier occurrences for code refs |
no | packages/feature/search/src/domain/code.lisp |
map-journal-entries |
Journal entries | yes | packages/core/store/src/application/journal.lisp |
scan-lisp-delimiters |
Delimiters for check --format lisp |
yes | packages/feature/inspect/src/domain/lisp-scan.lisp |
The search hot path marks its per-line callbacks dynamic-extent in
packages/feature/search/src/domain/results.lisp,
packages/feature/search/src/domain/matcher-scan.lisp, and
packages/feature/search/src/domain/code.lisp. The declaration limits their
lifetime to the call. t/perf/search-allocation-test.lisp checks that
allocation does not grow with the number of non-matching lines. See
Benchmarks.
Deliberately value-returning¶
| Computation | Function | File |
|---|---|---|
| Content hash and SHA-256 digest | content-hash, sha256-hex |
packages/core/kernel/src/domain/digest-kit.lisp |
| Inspection digests | info-digest-hex |
packages/feature/inspect/src/domain/file-facts.lisp |
| Token estimate | approx-token-count |
packages/core/kernel/src/domain/token-estimate.lisp |
| Masking one string | redact-secrets |
packages/core/protocol/src/domain/redaction.lisp |
| Diff generation (LCS) | generate-diff-hunks, generate-unified-diff |
packages/core/kernel/src/domain/unified-diff.lisp |
| Diff parsing | parse-unified-diff |
packages/core/kernel/src/domain/unified-diff-patch.lisp |
transform operations |
transform-lines |
packages/feature/edit/src/domain/transform.lisp |
| Compression adapters | inflate, deflate |
packages/core/text/src/domain/codec-deflate.lisp (cl-deflate-kit) |
| Envelope construction | make-ok-envelope, make-error-envelope |
packages/core/protocol/src/domain/envelope.lisp |
Each has a single outcome (or signals a condition that its caller's /k
function converts), so a continuation would add a call without adding a
branch.
ASDF systems¶
aitools.asd defines the standard three systems:
aitools:data/and every context's domain, application, and infrastructure layers. It does not depend on cl-cli.aitools/cli: every presentation layer and the composition root insrc/;program-opbuilds theaitoolsexecutable.aitools/test: the cl-weave suites undert/.
The delivered binary is built in two SBCL processes (overrideOutputs in
flake.nix). The first compiles every fasl of the aitools/cli closure and
never dumps an image. The second runs program-op through cl-nix-forge's
mkExecutable over that precompiled tree, so the dumping process loads the
fasls without compiling and the dumped core never shares a heap with the
compiler. See Development.
aitools.asd loads each context's ASD in order: core kernel, protocol,
workspace, text, store, then feature search, inspect, journal, edit, process,
org, env, md, util, net. See
Development.