Search by

sugarcraft / candy-kv

detain

Personal key/value store — a native PHP project inspired by charmbracelet/skate (Go), with multi-database support, binary-safe values, and glob/list filtering.

dev-master 2026-11-19 11:34 UTC

This package is auto-updated.

Last update: 2026-11-20 01:03:59 UTC


README

candy-kv

CI codecov Packagist Version License PHP

candy-kv

candy-kv is a personal key/value store for PHP 8.3+: multi-database support, binary-safe values, glob filtering, TTL expiry, JSON/YAML import/export, and a small strict CLI. Values land in plain SQLite files you own.

Formerly published as sugarcraft/sugar-skate (renamed 2026-10). Namespace changed: SugarCraft\Skate\ → SugarCraft\Kv\.

Scope note: upstream skate also ships an interactive full-screen browser. candy-kv does not — it is the storage library plus a scriptable command front end. Terminal UIs that want a browse pane build one on top of Store::list().

Features

  • Multi-database — separate stores with the key@dbname suffix; the SQLite file for a name is created the first time something is written to it (reads of a missing database come back empty)

  • Binary-safe — values containing NUL bytes or invalid UTF-8 are stored base64-encoded with the binary flag (auto-detected; --binary/--text override); binary entries export as base64 envelopes and reimport byte-exact

  • Glob patterns — list and delete accept * and ?; \*/\? spell literals

    • Matching is case-sensitive and character-wise: the pattern compiles to SQLite LIKE over the stored text, so ? spans one character, not one byte. For a case-insensitive sweep list twice (User-* and user-*) — or use */? wildcards in place of the differing letters
    • get takes an exact key only — raw unescaped */? in a get argument stay the pattern refusal
    • An exact key that contains the characters may be spelled with the same escapes: get 'ra\*wt' reads the key ra*wt
  • Ordered, filterable listing — forward or reverse, keys only, values only, or full entries

  • SQLite-backed — one file per database under $XDG_CONFIG_HOME/skate/ (or ~/.config/skate/; see Data directory)

  • Iterable streams — list() yields results without loading everything into memory

  • TTL / expiry — integer epoch seconds, so an entry means the same instant on every machine and timezone; prune removes expired residue

  • Levenshtein suggestions — a key miss prints the closest live key (within half the query's codepoint count, floored at one edit so short queries still get a hint) to stderr

  • Import/Export — JSON and YAML (yml accepted), fail-fast: a bad document or an unround-trippable value refuses before writing anything

  • Atomic transactions — transaction() wraps a callback in BEGIN IMMEDIATE/COMMIT/ROLLBACK

  • Pinned connection pragmas — WAL with a 62.5 MiB page-cache cap and a 5-second busy timeout on every connection (Database.php); synchronous deliberately stays at FULL and foreign_keys is omitted outright — the economics of both choices are argued at the pragmas in src/Database.php

  • Plain text output — the CLI emits no color and no escapes of its own; get echoes the stored bytes untouched. --sanitize collapses a value to one line, stripping every control a terminal would execute (the C0 controls — ESC is one of them — plus DEL and the UTF-8-encoded C1 pair) — script-friendly by contract

Install

composer require sugarcraft/candy-kv

Sibling sugarcraft/sugar-core and sugarcraft/sugar-fuzzy requirements track dev-master, so the plain command above only resolves when dev stability is allowed. Pin the package with composer require sugarcraft/candy-kv:@dev, or set minimum-stability to dev with prefer-stable set to true in your consuming manifest. The pin covers the whole sibling closure, so allowing dev for candy-kv alone is not enough.

candy-kv needs PHP 8.3+ and the SQLite3 extension (ext-sqlite3, declared in composer.json): the store is a plain SQLite file and there is no fallback engine. The CLI lands at vendor/bin/candy-kv; add vendor/bin to your $PATH, or invoke the full path. A rolling latest-channel phar (self-contained, stamped dev-<sha>) is also published:

wget https://github.com/detain/sugarcraft/releases/download/candy-kv/latest/candy-kv.phar -O candy-kv
chmod +x candy-kv

YAML import/export works out of the box with candy-kv's own flat YAML dialect. Installing symfony/yaml (composer require symfony/yaml) upgrades the YAML route to the full component — same data contract, sturdier quoting.

Quick Start

This runs against the real store, so sandbox it first the way the CLI section shows: XDG_CONFIG_HOME=$(mktemp -d) php test.php.

<?php

require __DIR__ . '/vendor/autoload.php';

use SugarCraft\Kv\Store;

$store = new Store();

// Set and get
$store->set('greeting', 'Hello, World!');
echo $store->get('greeting'); // Hello, World!

// With a database — target it with the `key@db` suffix.
// (`set()`'s 3rd parameter is `bool $binary`; `get()`'s 2nd is a fallback
// string. A db name NEVER goes in either — the `@` suffix is the routing.)
// Values are stored UNENCRYPTED (see Privacy & file modes below).
$store->set('token@passwords', 'ghp_xxxx');
echo $store->get('token@passwords');

// List all entries (lazy generator of Entry objects)
foreach ($store->list() as $entry) {
    echo "{$entry->key} => {$entry->rawValue()}\n";
}

// Glob patterns (list/delete only — get is exact-key)
foreach ($store->list(pattern: 'user-*') as $entry) {
    echo "{$entry->key}\n";
}

// Delete (returns the number of entries removed; patterns too)
$removed = $store->delete('greeting');

CLI

To try the CLI without touching your real store, sandbox it first: export XDG_CONFIG_HOME=$(mktemp -d).

candy-kv set <key> [value] [--ttl SECONDS] [--binary|--text]   # no value reads STDIN — silently, no prompt (see STDIN)
candy-kv get <key> [--sanitize]                               # exact stored bytes by default
candy-kv list [-k|-v] [-r] [-d DELIM] [@db] [pattern]         # one row per entry; @db scopes the listing
candy-kv delete <key> [--dry-run]                             # exact key or glob pattern
candy-kv list-dbs                                             # databases present in the dir
candy-kv delete-db <name>                                     # remove one database file (and its sidecars)
candy-kv prune [--db NAME|--all]                              # remove expired residue (default db, unless routed)
candy-kv import <json|yaml|yml> <path> [--no-atomic] [--if-exists=MODE] [--max-bytes=N]  # path=- reads STDIN
candy-kv export <json|yaml|yml> [db] [pattern]
candy-kv --help    # or: -h, help
candy-kv --version
  • --ttl accepts both attached and space forms and must be a positive whole number of seconds (1..999999999). --ttl 0 is a usage error, not "expire immediately" and not "forever" — omit --ttl for a forever entry.
  • set auto-detects binary: a value containing a NUL byte or invalid UTF-8 is stored base64-encoded with the binary flag. --binary forces that, --text forbids it — and a --text-forced value that actually contains a NUL byte is refused (usage error, exit 2), because every reader would truncate it at the first NUL; such payloads belong in --binary.
  • get prints the exact stored bytes (no added newline, no scrubbing) so round-trips and $(candy-kv get k) stay honest. --sanitize collapses the value to one line with the C0 controls (ESC included) and DEL stripped, plus the UTF-8-encoded C1 pair, for terminal printing.
  • --dry-run reports how many entries delete would touch and writes nothing.
  • --binary and --text are mutually exclusive: passing both refuses as a usage error (exit 2) instead of letting flag order decide.
  • prune sweeps the default database; --db NAME routes the sweep, key@db positional is the same routing in suffix spelling, and --all walks every listed database, printing the per-database counts.
  • delete-db <name> removes one database (plus its sidecars). A typo'd name is reported with did you mean hints over the databases that exist.
  • import --if-exists chooses the clobber policy for keys already stored: replace (default), skip (keep the live row), or fail (refuse, naming the key). An overwriting import always says how much it replaced.
  • import --max-bytes N raises the per-document size ceiling above the 268435456-byte (256 MiB) default; 0 removes it. Oversized documents are refused before their bytes are read.
  • -- ends option processing: set backup -- --ttl=60 stores the literal value --ttl=60. Only the first -- ends option processing — a second one is ordinary positional data, so set k -- -- stores the value --. Unknown options and surplus positionals are refused (exit 2) rather than silently ignored — a typo'd --ttl300 never becomes a forever secret.
  • -d accepts the delimiter attached (-d,) or spaced (-d ,); the printed delimiter is the raw bytes you asked for. A bare trailing -d (list -d) is not an error — it keeps the tab default, unlike the value-hungry flags, which refuse a missing or flag-like next token loudly (exit 2).
  • --version reports the phar build's stamped version when the archive carries one; source-tree and checkout builds honestly report dev-master rather than inventing a semver for unreleased code.

Exit codes

Situation Code
success 0
key/pattern found nothing (get miss, delete miss, delete-db/prune --db on an absent database) 1
a runtime error (unreadable store, failed write, oversized document) 1
usage error: unknown command, unknown option, bad/missing arguments, --ttl 0, contradictory --binary --text, pattern passed to get 2

Nothing is written on exit 2 paths. The "pattern passed to get" refusal fires on unescaped glob bytes only — a \*/\? spelling is not a pattern but the grammar's literal escape, and get 'ra\*wt' fetches the key ra*wt; the same bytes unescaped stay the pattern refusal (see Glob patterns above).

Two edge cases complete the table. A bare candy-kv (no arguments at all) prints the help and exits 0 — asking for guidance is not a usage error; exit 2 starts where a command was named but its arguments are wrong or missing. And prune with nothing expired is a success (No expired entries to remove., stdout, exit 0) while a delete that matches nothing exits 1: the asymmetry is deliberate — a failed lookup is an error, an empty sweep is nothing to fail on.

Output format

Real transcript (sandboxed $XDG_CONFIG_HOME; # annotations are not part of the output):

$ candy-kv set greeting 'Hello, World!'        # silent on success
$ candy-kv set color blue
$ candy-kv set note@notes 'buy milk'           # the @ suffix routes to the notes database
$ candy-kv get greeting
Hello, World!                                  # exact bytes, no trailing newline
$ candy-kv list
color	blue                                   # key, TAB, value; rows newline-terminated
greeting	Hello, World!
$ candy-kv get colar
Key not found; did you mean 'color'?            # stderr; exit 1
$ candy-kv delete 'user-*' --dry-run
Nothing deleted: no entries match "user-*".    # stderr; exit 1 (no user-* keys exist)
$ candy-kv list -v
blue
Hello, World!
$ candy-kv list-dbs
default
notes

Newline discipline: get never adds a newline (piped set stores STDIN byte-verbatim, so echo token | candy-kv set k stores the trailing newline too — use printf %s or pass the value as an argument for exact bytes); list, delete, prune, and import success lines are newline-terminated one-shots. list scrubs control bytes from stored keys/values for the terminal (a multi-line value prints as one collapsed line); the -d delimiter itself prints raw. Binary entries print as <binary N bytes> in list — their decoded bytes come from get (exact) or saveTo(). Upstream skate's list -b (raw bytes inline) has no equivalent: the collapsed marker is deliberate, so a dump of binary values can never scribble on your terminal; reach for get per key where a ported script asked for -b.

TTL (Time-To-Live)

candy-kv set session:abc123 '{"user":"bob"}' --ttl=3600  # expires in one hour

Expiry is stored as an integer epoch second, so a database written in one timezone reads with the same true instants everywhere. Pre-2026-10 databases stored offset-bearing ISO strings — candy-kv migrates those rows once, on open, preserving each row's exact instant; a cell that no longer parses at all is quarantined as expired — loudly, naming the key — rather than letting it block the whole store from opening.

Liveness has a one-second boundary worth stating precisely. A row is live when expires_at >= now, an integer-second comparison every SQL read makes. Entry::isExpired() checks the same instant at sub-second precision. During the final second the two can disagree; when they do, SQL reads keep the row — the boundary resolves in the user's favour.

Expired entries are invisible to every reader (get, list, delete, count) but still occupy disk until you candy-kv prune, which removes exactly the expired rows every reader hides (--db NAME routes the sweep, --all walks every database).

Zero and absent TTLs mean different things on different surfaces — the table is the whole map:

Door Given Result
CLI --ttl 0 (or negative) zero usage error, exit 2, nothing stored — omit --ttl for forever
Store::set(..., ttlSeconds: 0) or negative ≤ 0 a forever entry — expiry arms only above zero
Store::setWithTtl(..., ttlSeconds: 0) or negative ≤ 0 documented NO-OP — nothing is stored at all

STDIN

When no value is given as an argument, set reads from STDIN. For import, use - or /dev/stdin as the path:

printf %s my-secret-token | candy-kv set api-token
candy-kv import json - < backup.json

Note: piped values are stored verbatim — STDIN is read with no trimming, byte-for-byte, under the same 256 MiB default size ceiling as import documents (SizeCap; the import door raises it per call with --max-bytes, the set door uses the default).

The - STDIN sentinel is meaningful only as import's path argument. Option parsing exempts a bare - from the dash prefix for every subcommand (ArgParser::isOptionLike()), so elsewhere it is literal data, never a STDIN switch and never an error: set k - stores a one-character dash value, get - looks up a key literally named -, and list - is a pattern matching the single character -.

There is no prompt and no tty check behind the STDIN fallback (SizeCap::readStream(STDIN, ...) in bin/candy-kv): running candy-kv set k with nothing piped waits silently for the value, which looks like a hang at a keyboard until EOF arrives (Ctrl-D). Pipe the value or pass it as the second argument; printf %s my-secret-token | candy-kv set api-token never pauses.

Key naming, @, and escapes

The rightmost unescaped @ routes the key: cache@notes stores entry cache in database notes. A literal @ inside an entry key is spelled \@, so support\@acme is one key regardless of other @ signs. A key with no separator stays in the default database, and a leading @ (@x) is a literal key, never a database suffix. A further unescaped @ left in the entry part after routing (a@b@c — the rightmost one routes, which strands a@b with another) is refused rather than guessed. The same law is public in the library: Store::splitKey('a\@b@db', 'default') returns ['db', 'a@b']. Export writes a stored key's literal @ back in that escaped spelling (the @database suffix stays raw), so a dump reimports into the same key and database it came from. The grammar has no escape for the backslash itself, so key spellings whose decoded form ends in a backslash or carries a doubled-backslash @ (bs\, a\\@b) are refused loudly at every door — set, get, delete, import, and qualified export — instead of being silently rewritten and re-routed; keep such bytes out of keys (store them base64 or in the value). Names are case-sensitive at every level: unlike upstream skate, which lowercases keys and database names on input, candy-kv stores what you type — Foo and foo are two keys, and k@Notes and k@notes are two databases.

Glob characters */? in a key name are reachable by get through the pattern engine's own escape: get 'ra\*wt' fetches the literal key ra*wt (the backslash-unescaped form is tried first, then the raw argument, so keys written before this rule keep answering). A get argument carrying an unescaped */? is still refused as a pattern — wildcards are for list/delete, never a fetch.

Import/Export

Import and export support JSON and YAML (yml alias). Import runs inside an atomic transaction by default; pass --no-atomic for multi-database or non-atomic imports:

candy-kv import json backup.json
candy-kv import yaml -              # read from STDIN
candy-kv export json > dump.json
candy-kv export yaml mydb 'user-*'  # export filtered keys from one database

The shape contract is strict in both directions. A top-level JSON list or YAML sequence is refused ("got a list/sequence") instead of importing indices as keys; values that cannot round-trip as stored text (nulls, booleans, arrays, objects) refuse the whole import before anything is written — no silent drops, no partial loads. That guarantee is about the data rows; the envelope metadata is best-effort — a "_ttl" or binary member naming a key the document does not otherwise carry is simply ignored, not an error. "_ttl" entries must be whole seconds; a zero/negative TTL on an entry refuses that import too (a forever entry omits the TTL instead). An atomic import that would write to more than one database refuses unless --no-atomic (library: atomic: false) is given, so the BEGIN/COMMIT guard cannot be bypassed by value shapes. A re-import of a dump whose keys are already stored replaces them by default — and the success line says how many entries it overwrote; --if-exists=skip keeps live rows and --if-exists=fail refuses the import naming the key.

Exporting with an explicit [db] argument qualifies every key to key@dbname so the dump reimports into the same databases; a pattern or default-database export prints bare keys. An empty database exports as an empty JSON object ({}), not a list.

Both formats are value-preserving: backslashes, newlines, colons, empty strings and control bytes round-trip, and binary entries come back as binary — through JSON and both YAML engines. Remaining TTLs are exported for live entries only (expired rows are invisible to the reader the export walks). Size is bounded, not buffered: an import document may not exceed the 256 MiB default ceiling — a file is refused on its stat before its bytes are read, and a stream (STDIN included) is stopped within one chunk of the cap — --max-bytes N raises the ceiling, 0 removes it. Export streams row-by-row: peak memory stays flat whether the database holds three thousand rows or thirty thousand (a binary value still costs ~1.33× as base64 text in the document itself).

JSON envelope. Plain "key": "value" pairs. Binary entries ride base64; their keys are listed in a reserved "_binary" array. Remaining TTLs (whole seconds) collect into a reserved "_ttl" object:

{
  "session:abc123": "{\"user\":\"bob\"}",
  "icon": "iVBORw0KGgo=",
  "_binary": ["icon"],
  "_ttl": { "session:abc123": 3540 }
}

YAML envelope. A flat key: value dialect — one pair per line, keys quoted when needed, values quoted/escaped as required. Binary entries ride the same base64; TTLs become skate_ttl_<key> integer lines and binary flags skate_binary_<key> lines. For compatibility the YAML route also reads the legacy nested _ttl: / _binary: envelope (the JSON reserved shape pasted into YAML) and honors it like the flat lines (src/Import/YamlImporter.php); the skate_… lines above are the only shape YAML export ever writes. When symfony/yaml is installed it renders and parses the identical flat shape (plus !!binary tags for stray control bytes, which the fallback parser also reads). One engine serves a process, and the two agree on that data contract; they differ only on the edge shapes below. Colon keys: the fallback refuses an unquoted colon-containing key that symfony accepts — e:f: hey becomes the key e:f under symfony and a refusal under the fallback. Bool tokens: the fallback keeps true-style tokens as literal text where symfony decodes them to a bool; the importer refuses bools, so a document carrying true imports on one engine and is refused on the other (a decoded int is stringified on import and lands identically either way). Long scalars: for very long plain scalars the fallback refuses constructs symfony would fold or wrap — and, unlike symfony, it names the line that failed. Export refuses keys that would collide with the reserved shapes of the format being written — _ttl / _binary for JSON, skate_ttl_… / skate_binary_… for YAML — instead of emitting unreadable files.

CLI surface vs library surface

The CLI covers set, get, list, delete, list-dbs, delete-db, prune, import and export — list-dbs is a thin loop over Store::listDatabases(), delete-db calls Store::deleteDatabase(), and prune sweeps Store::pruneExpired() by default with --db NAME / --all routing the same law per database (Store::pruneDatabase()), so those library twins do have CLI verbs. Everything else is library-only, by design: Store::entry(), suggestionFor(), setWithTtl(), fuzzyFilter(), setFile(), saveTo(), transaction(), and the rest of the single-file surface (Database::count(), raw(), allKeys(), close()) have no CLI verbs — the binary stays a thin front end for the everyday loop.

Import and export keep that shape programmatically, not just as CLI verbs: SugarCraft\Kv\Import\JsonImporter and SugarCraft\Kv\Import\YamlImporter are public API — constructed with a Store (plus options such as ttl), each exposes importFromFile(string $path, bool $atomic = true, string $ifExists = 'replace', int $maxBytes = SizeCap::DEFAULT_MAX_BYTES) and the same-shaped importFromString(string $text, ...) — both answer an ImportReport (imported / overwritten / skipped counts), where $atomic = false is the --no-atomic skip-the-wrapping-transaction path, $ifExists carries the clobber policy and $maxBytes the size ceiling. On the other side, SugarCraft\Kv\Cli\ExportCommand exposes run(...): int (writes to stdout, returns the exit code) and exportToString(string $format, ?string $dbName = null, ?string $pattern = null): string for callers that want the document as a value. Key-bearing commands route to a named database through the key@dbname suffix; the CLI list scans the default database unless its first positional is a lone @db token, which scopes the listing to that database (list @notes 'user-*'), while export <format> [db] takes an explicit database name.

Public API

Store

Method Purpose
__construct(?string $dataDir = null, string $defaultDb = 'default') Optional data dir (else resolveDataDir()); touches nothing on disk — databases open on first use
resolveDataDir(): string (static) XDG_CONFIG_HOME/skate → $HOME/.config/skate → passwd home; refuses relative env values; throws when no home exists
const DEFAULT_SUBDIR .config/skate — the directory segment under the home (historical name, see Data directory)
set(string $key, string $value, bool $binary = false, ?int $ttlSeconds = null): Entry Store a value; $binary base64-wraps it; TTL in whole seconds (the CLI auto-detects what this parameter forces). A ttlSeconds <= 0 stores a forever entry — expiry arms only above zero — the deliberate opposite of setWithTtl below, where the same bound stores nothing
setWithTtl(string $key, mixed $value, int $ttlSeconds): void Convenience setter — stringable values (scalars plus __toString objects); arrays, resources and non-stringable objects throw; ttlSeconds <= 0 is a documented NO-OP (stores nothing)
get(string $key, string $fallback = ''): string Exact-key read; pure — no terminal writes, expired or missing keys return the fallback
entry(string $key): ?Entry Full entry (metadata included, live rows only)
suggestionFor(string $key): ?string Closest live key within half the query's codepoint count, floored at one edit (what the CLI prints on a miss); null when nothing is near
suggestDatabase(string $name): ?string Same distance law over the listed database names — the delete-db/prune --db typo hint
list(?string $pattern = null, ?string $dbName = null, bool $reverse = false, string $mode = 'all', string $delimiter = "\t") Lazy generator — Entry objects, or plain string keys/values with $mode 'keys'/'values'. The $delimiter parameter is accepted for signature compatibility but no path applies it any longer (the CLI prints the raw delimiter; kept because removing it breaks the public API — slated for a v2 removal)
delete(string $key): int Exact key or glob; returns live entries removed
pruneExpired(): int Permanently delete expired rows from the default database (readers never see them; this reclaims the disk)
pruneDatabase(string $dbName): int The same sweep aimed at one named database (--db/--all routing); a missing database answers 0 without creating it
isReservedDatabase(string $name): bool The settings reservation door, public so the CLI answers reserved names before typo-suggesting
setFile(string $key, string $filePath): Entry Store file contents as a binary entry
saveTo(string $key, string $filePath): bool Write an entry to disk, created/tightened 0600 before any byte lands
fuzzyFilter(string $query, ?string $dbName = null): array Live Smith-Waterman scored key search (sugar-fuzzy), best match first
listDatabases(): array Database names in the data dir (settings is reserved — see Database::listDatabases())
deleteDatabase(string $dbName): bool Closes the handle, unlinks <db>.db + WAL/SHM sidecars; false if any file survives
transaction(string $dbName, callable $fn): mixed BEGIN IMMEDIATE/COMMIT/ROLLBACK around a callback (no nesting)
sanitizeForTty(string $text): string (static) Control-char scrub used for terminal printing (the CLI's lossy list preview; exact bytes always come from get/rawValue())
splitKey(string $key, string $defaultDb): array{0:string,1:string} (static) The escape-aware @ routing law, public
dataDir(): string / defaultDatabase(): string Accessors

Entry / Database

Entry carries key, value (the stored form — base64 text for binary entries), binary, createdAt/modifiedAt (DateTimeImmutable, display timestamps only), expiresAt (?DateTimeImmutable), isExpired(), and rawValue() which base64-decodes when binary is set (a binary row holding corrupt base64 raises rather than printing its own encoding as content). A row whose stored date cell no longer parses raises the same keyed way — Entry '<key>' does not hold a valid <field> date — at construction, the one point every accessor meets the database. Entry::binary($key, $bytes) is the factory for the binary form. Database is the single-file layer behind a store name: get/raw/set/delete/deleteMany/list/allKeys/count/pruneExpired/transaction/ close — count(?pattern) counts live entries, raw() skips the expiry filter (the documented bypass: a live-only read never shows residue, raw and pruneExpired are how you see and clear it), and pattern operations share the case-sensitive, character-wise semantics of exact ones.

Privacy & file modes

  • Values are stored unencrypted — SQLite is a container, not a vault. The token example above is readable with sqlite3 or any text editor.
  • A fresh database file is born under the process umask — SQLite offers no creation mode — and only schema pages are written at that mode before the file is tightened. On open, the file and its *-wal / *-shm sidecars are tightened to 0600 (owner-only); pre-existing looser files are tightened too, so no user-value byte ever lands on a looser file. A chmod that cannot be applied fails the open loudly. The data directory is created 0700 and its mode is re-asserted on every open. saveTo() likewise writes through a private temporary file into a 0600 target.
  • get on a typo prints the closest key to stderr. On shared machines, remember key names can themselves be sensitive — stderr is still a log. Suggestions fire only within half the query's codepoint count (floored at one edit); a far-from-anything miss says just Key not found: <the sanitized query> (shipped string Key not found: {key}, cli.key_not_found in lang/en.php).
  • Command lines are not secret storage. Anything passed as an argument (candy-kv set token "$SECRET") is visible to ps, shell history, and any process accounting. Piping the value via STDIN keeps it out of argv — that is the high-value-entry path. --binary has no bearing on exposure: it only forces the base64 storage form (see Binary-safe above), it does not hide, encrypt, or redact anything, and the value still round-trips through get.
  • Backups: copy the .db together with its -wal sidecar (or checkpoint first). Copying only *.db under WAL can lose the most recent writes. deleteDatabase() reports failure (returns false) when a sidecar could not be removed — a surviving -wal can still hold recoverable rows.

Data directory

Default: ~/.config/skate/ (respects $XDG_CONFIG_HOME). Each database is its own SQLite file: <dir>/<dbname>.db (default.db for unsuffixed keys). Neither the directory nor any database file is created until the first write. XDG_CONFIG_HOME and HOME, when set, must be absolute paths — a relative home would silently move the store with the working directory, so candy-kv refuses it. Database names are [A-Za-z0-9_-]+. The name settings is reserved: listDatabases() never shows it and every write aimed at it (set, delete, deleteDatabase, imports) is refused, so a listing-driven backup can never miss a half-written values database; reading a planted key@settings still works.

The directory keeps the pre-rename skate name on disk so existing candy-kv (née sugar-skate) installs keep working; new code can point $XDG_CONFIG_HOME anywhere. Upstream Go skate keeps its own data elsewhere, in a BadgerDB layout this store cannot read — moving data from skate means exporting it there and candy-kv importing it here (JSON/YAML is the only bridge), never a shared directory. If neither XDG_CONFIG_HOME nor $HOME is set, candy-kv falls back to the passwd home and throws loudly when even that is unavailable — it never writes into the install tree.

Language

CLI diagnostics and success lines are localized: the binary selects a locale from LC_ALL → LC_MESSAGES → LANG at start-up (16 shipped locales, see lang/). The missing-argument usage line is part of that translated surface — usage() emits Lang::t('cli.usage_*') before exit 2, so LANG=fr candy-kv get answers Usage : candy-kv get <clé> [--sanitize] — provided no higher-precedence LC_ALL/LC_MESSAGES is set in your environment, since that is exactly the chain just named. The translated set is the CLI's own answers: usage lines, the key/database miss diagnostics and their suggestions, and the success counts (Deleted …, Imported … Overwrote …, pruned …, Deleted database …). Four surfaces stay English by design:

  1. candy-kv --help — a fixed heredoc whose every documented flag is pinned by CliContractTest;
  2. src/Cli/ArgParser.php's own parse errors (unknown option, surplus positional, malformed values) — the one surface quoted verbatim by the test suite;
  3. the import/export failure diagnostics — refusal wrappers such as File not found: <path> and the importers' RuntimeException texts, a design the src/Cli/ImportCommand.php docblock states outright;
  4. the library's own validation throws (Store key routing, Database writes, expiry laws).

Only (2) through (4) can surface as exceptions; the help heredoc is not one. Exactly two library exceptions are catalog-keyed, so they follow the active locale: store.cannot_read and database.entry_unreadable. Everything else English above is English on purpose, not drift.

Demos

VHS tapes under .vhs/, re-rendered by CI — five GIFs. glob.gif is recorded from live ./bin/candy-kv calls; the other four drive the library surface through php examples/*.php. For a text walkthrough of the CLI itself, see the Output format transcript above.

Glob pattern matching

glob

Basic store/set/get

basic

Binary-safe values

binary

Multiple databases (key@dbname)

multidb

Reverse-ordered listing

reverse-order

Shared foundations

candy-kv uses sugar-fuzzy for Smith-Waterman scored matching: Store::fuzzyFilter() is a live API that ranks keys against a free-text query. Glob-to-SQLite LIKE pattern filtering remains the active filter path for list/delete.

Accessor removal (2026-11-16)

The house naming rule is bare accessors, with no get prefix. Two public forwarders that broke it were removed on 2026-11-16, ahead of their scheduled v2.0.0 removal, because nothing in the monorepo called them. Use the canonical methods instead:

Class Removed Use instead
Database getRaw() raw() (returns the entry, bypassing the expiry filter)
Store getFile() saveTo() (writes the entry bytes to a file, returns a bool)

saveTo() is named for the direction of the write: store data goes out to disk. The store-side mutator setFile() keeps its name as the file form of set(). The CLI get command is unrelated to the accessor rule and stays. tests/AccessorDeprecationTest.php pins the removal, the canonical behaviour, and the src/ census that keeps any public get*() accessor out. The history is in CHANGELOG.md.

Contributing & extending

Public classes are final by design — compose them rather than inherit. The familiar loop is: store verbs in Store, single-file mechanics in Database, argument discipline in src/Cli/ArgParser.php (every flag gets answered or refused — never silently ignored), and copy in lang/*.php (tests/LocaleParityTest.php requires every locale to carry every key and placeholder). Repo-wide conventions live in the monorepo root AGENTS.md; lib-local gotchas accumulate in CALIBER_LEARNINGS.md.

License

MIT

Credits & inspiration

Originally inspired by the Go Charm ecosystem (and the skate key/value tool that grew out of it); candy-kv is a native PHP project, not a line-by-line port.