CandyCodetime
Privacy-first coding-time tracker
candy-codetime is a privacy-first coding-time tracker. It records only the heartbeats you give it, one activity sample per call, such as I was working on this file, in this language, for this many seconds. It stores them locally as one append-only JSONL file per day, or in an optional embedded SQLite database, and it draws a seven-day dashboard with SugarCharts. Nothing watches the editor, nothing leaves the machine, and there is no daemon and no database server. The design antecedent is TakaTime, a Go tool whose always-on daemon was replaced here by an explicit push.
Install
composer global require sugarcraft/candy-codetime
# the global bin dir varies by composer version and platform; ask composer:
BIN="$(composer global config bin-dir --absolute)"
export PATH="$BIN:$PATH" # keep this line in your shell profile
Requires PHP 8.3 or newer. The SQLite backend and the milestone command also need the sqlite3 extension, and the dashboard needs a terminal. A project-local install works the same way through vendor/bin/candy-codetime.
Every candy-codetime/v* release also ships a single-file build, candy-codetime.phar, with a .sha256 digest and minisig sidecars. Verify the digest, then run php candy-codetime.phar on stock PHP. The app never rewrites its own archive and has no self-update channel, so an upgrade is a new download. Inside an archive, --version prints the release build stamp.
sha256sum -c candy-codetime.phar.sha256 # integrity before first run
php candy-codetime.phar --version
Quickstart
Record two beats, check for untracked time, and read the digest. The first line is a real run against an empty data directory. The date in the summary is the day you run it.
candy-codetime push sugarcraft php src/App.php 60 # one heartbeat: project, language, file, seconds
candy-codetime push myproj php src/Main.php 120
candy-codetime gaps # untracked stretches of 5 minutes or more
candy-codetime summary # per-project and per-language digest, last 7 days
recorded 60s of sugarcraft (php)
recorded 120s of myproj (php)
No gaps found.
summary: 2026-11-13 – 2026-11-19
total: 0h 03m
by project:
myproj 0h 02m
sugarcraft 0h 01m
by language:
php 0h 03m
Three replies are worth knowing. gaps: no tracked data for that period means no tracked data matches that period and any --project or --tag filter, either because nothing is recorded there yet or because a filter excludes all of it. No gaps found. means the window is covered. Running candy-codetime dashboard < /dev/null prints the dashboard needs an interactive terminal and exits 1, with the headless commands named as the alternative, so a script cannot hang on a missing terminal.
Open the dashboard in a real terminal with candy-codetime, or candy-codetime dashboard 30 for a 30-day window. Use export csv 30 for a plain-text dump of the same data.
Concepts
A heartbeat is one activity sample with six fields: time, project, language, file, duration in seconds and tags. The CLI never sets tags itself. A heartbeat becomes a beat once it is stored, and the two words are used interchangeably below.
Storage is local and plain. The file backend writes one YYYY-MM-DD.jsonl per day inside the data directory, and the file is append-only, so an editor hook can add a line without coordinating with the dashboard. The SQLite backend stores the same heartbeats in candy-codetime.db, indexed on time, for range queries. Milestones exist only in SQLite. The CLI reads whichever backend you select, and it can auto-select SQLite when the database holds records and the JSONL store does not.
Recording is explicit
candy-codetime does not watch files, windows or keystrokes. It records what it is told, by a hand-typed push, a save hook, a cron entry or an editor binding that calls the CLI. No editor plugins ship. The binding is one command line, and the worked example in examples/plugin-heartbeat.example.sh is the recommended starting point.
Reading is pure
Stats::compute() folds a list of beats over a date window into totals per project and per language, plus one bucket per day. It takes no I/O and uses no clock, so the same beats always give the same answer. The dashboard, the exporters and the gaps report all read through the same HeartbeatReader contract.
Tasks
Wire a save hook
# vim: one heartbeat per save, using the worked example script
autocmd BufWritePost * silent! !sh /path/to/examples/plugin-heartbeat.example.sh "$EXPANDEF"
# or feed a batch of JSON lines through the stdin door, which applies ignore rules, clamps and the lock
printf '%s\n' '{"time": 1795100000, "project": "myproj", "language": "php", "file": "src/Main.php", "duration": 300, "tags": []}' | candy-codetime push --
The script prefers push --, so the ignore door, the duration clamps and the advisory lock all apply. It falls back to a raw append under flock whenever push -- exits nonzero, which includes a binary missing from PATH and a refusal such as an oversized ignore file. The raw append skips the ignore door, the duration clamps and the lock, so a file the ignore rules would skip is recorded by the fallback. Set CODETIME_HOOK_DURATION to change the seconds credited per save, which defaults to 60.
Backfill a past beat
candy-codetime push --time=1795000000 myproj php src/Main.php 900 # one beat at a past instant
candy-codetime push --time=1795000000 myproj php src/Main.php 900 review,work # with tags
--time takes a Unix timestamp and files a single beat at that instant. A malformed value is refused rather than coerced. A raw JSON line written by hand has no default time, so a line without time is a corrupt record and is dropped on read. Use push -- or --time to backfill, because both stamp the real instant.
Skip files with an ignore file
printf '%s\n' 'secret.log' 'vendor/*' > .sugartrackignore
candy-codetime push src/Main.php 120 # tracked
candy-codetime push vendor/lib/a.php 60 # skipped: reported, never stored
The .sugartrackignore file in the current directory, or else in the tracked file's own directory, holds one glob per line. A bare pattern matches a file name at any depth, a full path matches exactly, and a path pattern matches below any matching directory. The sibling .sugartrackallow file re-enables a path that an ignore file would skip. Both files are capped at 1 MiB. Ignore files often live inside a checked-out repository, so a bare * pattern, which would silently zero a project, is reported on stderr with the file's path.
Find untracked time
candy-codetime gaps 14 # untracked stretches of 300 seconds or more, last 14 days
candy-codetime gaps --min=1800 2026-11-01 2026-11-19 # only gaps of 30 minutes or more, in a dated window
Report\GapsReport reads the sorted beats and reports each stretch between them that is at least the threshold. The default threshold is 300 seconds. It is a question of whether your tracking is honest, not a judgement about the work.
Export for a spreadsheet, a JSON pipeline or a calendar
candy-codetime export csv 30 --project=myproj > week.csv
candy-codetime export json 2026-10 2026-10 > october.json
candy-codetime export ics 7 --tag=review > review.ics
Output goes to stdout, so redirect it to save it. --project and --tag filter the rows on either backend. The ics format writes one VEVENT per heartbeat, with UTC stamps whose difference is the beat's duration. Every exported path is verbatim, so do not send an export somewhere shared without thinking about what the file paths reveal.
Move to SQLite and keep milestones
candy-codetime --backend=sqlite push myproj php src/Main.php 120
candy-codetime milestone add "v1.0 shipped" "first stable tag"
candy-codetime milestone list
CANDY_CODETIME_BACKEND=sqlite candy-codetime dashboard 30
The SQLite backend tunes the database on open with WAL journaling, and a five-second busy timeout. Once WAL is confirmed, it also sets synchronous=NORMAL; on a filesystem that refuses WAL, synchronous stays at the FULL default. A milestone always writes to SQLite, even when --backend is not given, and the SQLite dashboard marks milestone days with * under the weekday row. The file backend never shows milestones.
Remove a project, safely
candy-codetime backup # archive day files older than 30 days first
candy-codetime forget --project=old-experiment # dry run: counts matches, changes nothing
candy-codetime forget --project=old-experiment --apply # removes them from both stores
forget is a dry run unless --apply is given. Lines that fail to parse are never removed. Run backup first, because the archive is the undo path, and plain backup does not copy a live SQLite database. Use backup --sqlite for that, which writes a consistent snapshot with VACUUM INTO.
Set a daily goal
CANDY_CODETIME_GOAL=6h candy-codetime dashboard
The goal shows as today 2h01 / 1h00 in the header, and every day that reaches it is drawn as a shaded block in the activity band. It is presentation only, so it records nothing and gates nothing.
API reference
The public classes live in SugarCraft\CodeTime\, with the storage, export, report, backup, ignore and support classes in sub-namespaces that follow the same names. The table gives the members a host program is most likely to call. The file layout is in the Architecture section below.
Recording and reading
| Class | Method | Description |
|---|---|---|
Heartbeat | __construct(int $time, string $project, string $language, string $file, int $duration = 60, array $tags = []) | One activity sample. Throws InvalidArgumentException on a negative time or duration. |
Heartbeat | fromArray(array $row), toArray(), withTags(array $tags) | Build from or convert to a JSONL row. withTags() returns a new instance. |
Store | __construct(string $dir, int $rangeBeatBudget) | The JSONL store over one data directory. It implements HeartbeatReader. |
Store | append(Heartbeat $hb, ?CancellationToken $token = null) | Record one heartbeat under an advisory lock. The directory and file modes are private. |
Store | loadRange(DateTimeImmutable $from, DateTimeImmutable $to), loadDay(DateTimeImmutable $day) | Read the beats in a window, or on one day. Corrupt lines are dropped and counted, never invented into beats. |
Store | clampRangeDays(int $days), MAX_RANGE_DAYS | Clamp a requested window to 1 through 3660 days. |
SqliteBackend | __construct(string $dbPath), insert(Heartbeat $hb) | The optional indexed backend. It implements HeartbeatReader and owns the milestones. |
SqliteBackend | insertMilestone(), milestones(), forget(), countMatched() | Milestone markers and the parameterized delete behind forget --apply. |
Milestone | value object | A named marker on one day, carried to the view. Only a SQLite reader fills it. |
Folding, rendering and the dashboard
| Class | Method | Description |
|---|---|---|
Stats | compute(array $beats, DateTimeImmutable $from, DateTimeImmutable $to, array $milestones = []) | A pure fold into day buckets, with totals per project and per language. |
Stats | perProject(), perLanguage(), perTag(), timeline(), totalSeconds(), formatHours(int $seconds) | The folded views. perProject() and perLanguage() sort by time, largest first. |
Dashboard | start(HeartbeatReader $source, ?DateTimeImmutable $endDay = null, int $days = 7, ...) | The SugarCraft Model for the TUI. It is a window over any reader, and it reloads with r. |
Renderer | render(Dashboard $d) | Draws the header, the two ranking panes and the Sparkline timeline. It honours the detected colour profile. |
Theme | default(), named(string $name), NAMES | The six shipped palettes. named() returns null for an unknown name. |
Support\Detect | language(string $file), project(string $file, string|false|null $cwd) | The extension map and the project-name rule behind push without explicit slots. |
Exporters, reports, backup and ignore rules
| Class | Method | Description |
|---|---|---|
Export\CsvExporter, Export\JsonExporter | Tabular exporters behind TabularExporterInterface | The csv and json formats. Free-text cells pass the formula-injection guard in CSV. |
Export\IcalExporter | exporter behind ExporterInterface | The ics format, one VEVENT per heartbeat. |
Report\GapsReport | __construct(array $heartbeats, int $minGapSeconds = 300), gaps(), totalUntrackedSeconds() | Pure gap detection over sorted beats. |
Backup\AutoBackup | rotate(int $keepDays = 30), archiveSqliteDatabase(string $dbPath), listBackups() | Copy-only archiver. It never deletes, and it throws loudly on any failure. |
Ignore\SugarTrackIgnore | load(string $path), isIgnored(string $path), isAllowed(string $path) | The .sugartrackignore matcher used by push. |
Ignore\IgnoreFileTooLargeException | exception | Thrown for an ignore or allow file over 1 MiB. |
Support\Version | CURRENT | The single-source version constant, 0.1.0. |
Lang | t($key, $params) | The i18n facade over the 16 locale catalogs in lang/. |
Only methods declared in candy-codetime/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.
SugarCraft\CodeTime
Dashboard final class
Read-only dashboard Model. Loads the last $days days of heartbeats once, computes Stats, and renders. r reloads from disk, ←/→ shifts the window by one day, q/Esc quits.
| Method | Summary |
|---|---|
__construct(public readonly HeartbeatReader $source, public readonly \DateTimeImmutable $endDay, int $days = 7, public readonly Stats $stats = new Stats([], []), public readonly ?int $width = null, public readonly ?ColorProfile $colorProfile = null, public readonly ?int $height = null, public readonly ?string $backendLabel = null, public readonly int $droppedLines = 0, public readonly int $unreadableFiles = 0, public readonly ?string $loadError = null, public readonly bool $byTags = false, public readonly ?int $goalSeconds = null, ?Theme $theme = null, public readonly bool $storeEmpty = false) | |
static start(HeartbeatReader $source, ?\DateTimeImmutable $endDay = null, int $days = 7, ?string $backendLabel = null, ?int $goalSeconds = null, ?Theme $theme = null): self | |
init(): ?\Closure | |
update(Msg $msg): array | |
view(): string | |
reload(): self | |
static nextWindow(int $current, int $direction): int | The ladder neighbour of an arbitrary width in one direction; the width itself when it is already the end rung. |
subscriptions(): ?\SugarCraft\Core\Subscriptions |
Heartbeat final class
One activity sample. Editor plug-ins record these by shelling out to the local candy-codetime push command — they're the natural unit of storage in the JSONL activity log.
| Method | Summary |
|---|---|
__construct(int $time, string $project, string $language, string $file, int $duration = 60, array $tags = []) | |
static fromArray(array $row): self | Hydrate one stored row (JSONL line or sqlite record). |
toArray(): array | |
withTags(array $tags): self |
Lang final class
Per-library translation facade for candy-codetime.
Milestone final readonly class
A named time-point in the activity timeline — e.g. "shipped v1.0 here".
| Method | Summary |
|---|---|
__construct(public string $name, public int $time, public string $description = '') | |
static fromArray(array $row): self | |
toArray(): array |
Renderer final class
Pure view function. Three sections stacked vertically: header, project + language ranking side-by-side, and the daily-activity sparkline timeline. Under the width derived from PANE_TEXT/FRAME_CHROME the two ranking panes stack vertically instead of side-by-side.
| Method | Summary |
|---|---|
static render(Dashboard $d): string |
Stats final class
Pure-state aggregator — folds a list of heartbeats into the dashboard's projection: totals per project, totals per language, and a per-day timeline (seconds / day) for the active range.
| Method | Summary |
|---|---|
__construct(public readonly array $beats, public readonly array $days, public readonly array $milestones = []) | |
static compute(array $beats, \DateTimeImmutable $from, \DateTimeImmutable $to, array $milestones = []): self | |
perProject(): array | |
perLanguage(): array | |
perTag(): array | |
timeline(): array | |
totalSeconds(): int | |
static formatHours(int $seconds): string |
Store final class
JSONL-backed heartbeat store. One file per day under the data dir — $XDG_DATA_HOME/candy-codetime/YYYY-MM-DD.jsonl (fallback ~/.local/share/candy-codetime/, resolved by self::defaultDir()) — the path stays appendable, every editor plugin just >> echoes a JSON line; whatever loose modes such a line is minted with are swept back to owner-private by self::enforcePrivateModes() on the next CLI launch.
| Method | Summary |
|---|---|
__construct(public readonly string $dir, public readonly int $rangeBeatBudget = self::MAX_RANGE_BEATS) | |
static clampRangeDays(int $days): int | Clamp a requested day count to [1, MAX_RANGE_DAYS] so an out-of-range value from the CLI cannot drive loadRange() into an unbounded walk. |
static defaultDir(): string | Default per-user directory (XDG / fallback to ~). |
static ensurePrivateDir(string $dir, string $label = 'data directory'): void | Create (or tighten) the data directory to owner-private 0700. |
static ensurePrivateFile(string $path, string $label = 'data file'): void | Tighten an existing file to owner-private 0600, throwing when the chmod fails. Public because AutoBackup must apply the same law to the copies it writes: a byte-for-byte clone of a private day file, left at the umask default, leaks the same paths (as supplied) one directory over. |
enforcePrivateModes(): void | Re-establish the whole privacy contract, not just the paths this process writes. A plugin that direct-appends with >> runs no candy-codetime code at all, and a pre-rename migration merely moves the tree — files minted that way can sit at the shell's umask, world- readable absolute paths and project maps. The sweep tightens the data directory (0700), every day file and archived day file (0600), and the SQLite database with its -wal/-shm sidecars (0600). It runs on every CLI launch — reads included — so any exposure lasts at most until the tool is run next, and it throws on an unfixable mode exactly like the write paths do. |
countMatched(callable $drops): int | Count beats the forget door would remove (CT-S42). Lines that do not parse are never counted: a beat whose identity cannot be proven is a beat that survives. Reading populates the day cache, so callers that stop at the count must invalidate() before reading again (the CLI forget arm does). |
forget(callable $drops): int | Rewrite every day file excluding the beats the door matches (CT-S42). |
silenceDiagnostics(): void | Stop the store writing to stderr; counting continues (CT-S19). The dashboard launcher calls this the moment the alt screen takes over, so mid-session reloads can never spray raw bytes into a sync frame. |
drainDiagnostics(): array | Take the data-loss counters since the last drain (CT-S19). Resetting here is what makes a footer count describe the load it accompanies instead of the whole process lifetime. |
loadDay(\DateTimeImmutable $day): array | |
loadRange(\DateTimeImmutable $from, \DateTimeImmutable $to): array | Load every heartbeat in [$from, $to] — date range inclusive. |
invalidate(): void | Invalidate the day cache (forces reload on next loadDay). |
append(Heartbeat $hb, ?CancellationToken $token = null, int $lockTimeoutMs = self::APPEND_LOCK_TIMEOUT_MS): void | Append a heartbeat to today's JSONL file. |
hasAnyHeartbeat(): bool | CT-S46: any non-empty day file answers yes without parsing contents. |
Theme final class
The dashboard palette — every colour the Renderer paints.
| Method | Summary |
|---|---|
static default(): self | The shipped palette: the only one that predates theme selection. |
static named(string $name): ?self | The named palettes: default keeps every documented byte, light answers the pastel-on-white complaint (the shipped candy tones wash out on a white terminal), and the rest ride the well-known scheme families. Unknown names answer null — the CLI refuses them, never guesses. |
SugarCraft\CodeTime\Backup
AutoBackup final class
Rotating backup manager for JSONL data files. Archives (copies) files whose mtime has aged past the keepDays threshold. Scope of the copy-only rotate() is the per-day *.jsonl files; a byte copy of a live SQLite database would be a torn snapshot at best, so the database gets its own door instead: archiveSqliteDatabase() runs VACUUM INTO, which snapshots consistently from a live connection (the CLI's plain backup still refuses to copy the .db and says why).
| Method | Summary |
|---|---|
__construct(private readonly string $backupDir, private readonly array $dirs = []) | |
rotate(int $keepDays = 30): int | Archive day files older than keepDays (copy-only — nothing is ever deleted from the data directory; the "rotating" in the class name is an archive cadence, not a retention sweeper). |
archiveSqliteDatabase(string $dbPath): string | Crash-safe archive /** Crash-safe archive of the SQLite database via VACUUM INTO. |
listBackups(): array |
SugarCraft\CodeTime\Export
CsvExporter final class
Exports heartbeats as CSV with comma-separated values.
| Method | Summary |
|---|---|
headers(): array | |
rows(array $heartbeats): array | |
encode(array $heartbeats): string | Encode heartbeats as a proper RFC-4180 CSV string. |
export(string $name, array $heartbeats): string | |
format(): string | |
contentType(): string |
ExporterInterface interface
Base contract for heartbeat string exporters.
| Method | Summary |
|---|---|
export(string $name, array $heartbeats): string | Export heartbeats as a formatted string. |
format(): string | |
contentType(): string |
IcalExporter final readonly class
Exports heartbeats as iCalendar (RFC 5545) format. Each heartbeat becomes a VEVENT with the file path as the summary.
| Method | Summary |
|---|---|
__construct(private string $prodId = '-//SugarCraft//candy-codetime//EN') | |
export(string $name, array $heartbeats): string | Export heartbeats as iCal format. Each heartbeat becomes a VEVENT with the file path as the summary. |
format(): string | |
contentType(): string |
JsonExporter final class
Exports heartbeats as a JSON array of objects.
| Method | Summary |
|---|---|
headers(): array | |
rows(array $heartbeats): array | |
encode(array $heartbeats): string | Encode heartbeats as a JSON array of objects keyed by headers(). |
export(string $name, array $heartbeats): string | |
format(): string | |
contentType(): string |
TabularExporterInterface interface
Contract for tabular heartbeat exporters (CSV, JSON). Extends ExporterInterface with rows/headers for tabular output.
| Method | Summary |
|---|---|
headers(): array | |
rows(array $heartbeats): array | |
encode(array $heartbeats): string | Encode heartbeats as a formatted string. |
export(string $name, array $heartbeats): string | Export heartbeats as a formatted string. |
format(): string | |
contentType(): string |
SugarCraft\CodeTime\Ignore
IgnoreFileTooLargeException final class
A rule file (.sugartrackignore / .sugartrackallow) larger than the declared byte ceiling. A dedicated type (CT-S39, finding 059) so the CLI reports it as the opt-out misconfiguration it is — never wrapped in the storage-error envelope, which would tell the user their disk failed when their config file was refused on size.
| Method | Summary |
|---|---|
__construct(public readonly string $rulePath, public readonly int $size, public readonly int $limit, string $label = 'ignore file') |
SugarTrackIgnore final class
Loads .sugartrackignore glob patterns and matches file paths.
| Method | Summary |
|---|---|
__construct(private readonly array $patterns = []) | |
static load(string $path, string $label = 'ignore file'): self | Load patterns from an ignore file. |
patternCount(): int | Number of active patterns (comments and blank lines excluded). |
hasWholesalePattern(): bool | True when some pattern is wildcard-only — it ignores EVERY path the matcher is ever consulted about. |
isIgnored(string $path): bool | Returns true if the file path should be ignored. |
isAllowed(string $path): bool | The sibling control of isIgnored, for ".sugartrackallow" files: the same three-leg match, read as a rescue instead of a rejection. The CLI consults an allow-list FIRST — a path matched here is tracked without the deny file ever being consulted — so the two files together give first-match precedence to the allow side (upstream .takatrack parity, finding 045). |
SugarCraft\CodeTime\Report
GapsReport final class
Detects untracked time gaps between heartbeats.
| Method | Summary |
|---|---|
__construct(private readonly array $heartbeats, private readonly int $minGapSeconds = 300) | |
gaps(): array | |
totalUntrackedSeconds(): int |
SugarCraft\CodeTime\Storage
HeartbeatReader interface
The read contract the dashboard and the export/gaps report paths need.
| Method | Summary |
|---|---|
loadRange(\DateTimeImmutable $from, \DateTimeImmutable $to): array | Load every heartbeat in [$from, $to] — date range inclusive. |
invalidate(): void | Drop any cached reads so the next load sees what is on disk now. |
hasAnyHeartbeat(): bool | Does this store hold ANY heartbeat at all, anywhere (CT-S46)? The dashboard swaps its panes for a getting-started block exactly when the answer is no — a first-run user must see the next action, not three politely empty frames. Distinct from an empty WINDOW: old records elsewhere keep the normal panes. |
SqliteBackend final class
SQLite-backed heartbeat + milestone store. Provides an alternative to the JSONL store with query capabilities, and satisfies the same HeartbeatReader contract, so dashboard can read it exactly like push/export/gaps already do.
| Method | Summary |
|---|---|
__construct(string $dbPath) | |
insert(Heartbeat $hb): void | |
query(int $fromTime, int $toTime): array | |
loadRange(\DateTimeImmutable $from, \DateTimeImmutable $to): array | Day-range read shaped for the shared HeartbeatReader contract, so the dashboard and any range consumer can take either storage unchanged. The bounds are whole days: from-day 00:00 through to-day 23:59:59. |
invalidate(): void | No cached reads exist over the live database, so there is nothing to drop — the honest no-op the HeartbeatReader contract expects (same method Store uses to re-read its day files after r). |
insertMilestone(string $name, int $time, string $description = ''): void | |
countMatched(?string $project, ?string $filePrefix): int | Count stored beats the forget door would remove (CT-S42). |
forget(?string $project, ?string $filePrefix): int | Delete the matching beats (CT-S42). Parameterized all the way — the filter values arrive as bound text, never interpolated. |
milestones(): array | |
hasAnyHeartbeat(): bool | CT-S46: one indexed existence probe, never a row walk. |
SugarCraft\CodeTime\Support
Detect final class
CT-S32: the auto-detect lane for push <file> [duration] [tags].
| Method | Summary |
|---|---|
static language(string $file): string | The language an extension names; 'unknown' when the map is silent. |
static project(string $file, string|false|null $cwd): string | The repository the file belongs to: the nearest ancestor carrying a .git (directory or file — worktrees use the file form), else the first segment of the path relative to the working directory (the directory itself when the file sits in it), else 'unknown'. An unrelated absolute path's first segment is filesystem geography, not a project name, so it never becomes a label. |
Version final class
Single source of truth for the printed version.
| Method | Summary |
|---|---|
static resolve(string $archive, string $fallback = self::CURRENT): string | Resolve the version for the current run. |
static fromPharMetadata(string $archivePath): ?string | Read and normalize the version stamp inside an archive, or null when the path is empty, is not a file, is not a readable phar, or its stamp does not parse as a comparable release. Every failure mode falls back to null rather than throwing — a corrupt archive must not crash --version. |
Configuration
Options are accepted before or after the command. Environment variables are read on every invocation, and an explicit flag always outranks the environment.
Options
| Option | Effect |
|---|---|
--backend=file|sqlite | Storage for push, export, gaps, summary and dashboard. Both --backend=sqlite and --backend sqlite work. Without the flag, the CLI auto-selects SQLite when the database holds records and the JSONL store does not. The choice is made per invocation and never saved. |
--theme=<name> | Dashboard palette: default, light, dracula, solarized, gruvbox or high-contrast. A junk name is refused with the list of choices. |
--project=<name>, --tag=<label> | For export and gaps, keep only the rows that match. |
--min=<secs> | For gaps, the minimum untracked stretch to report. The default is 300 seconds. |
--format=text|md | For summary. md prints Markdown for a README or a badge. |
--time=<unix> | For push, files one beat at a past or future instant. |
--sqlite | For backup, archives the SQLite database with VACUUM INTO. |
--apply | For forget, turns the dry run into a real removal. |
Environment
| Variable | Effect |
|---|---|
CANDY_CODETIME_DIR | The data directory. The default is $XDG_DATA_HOME/candy-codetime, falling back to ~/.local/share/candy-codetime. If it is unset and XDG_DATA_HOME and HOME are both unset too, the CLI refuses rather than writing next to the working directory. |
CANDY_CODETIME_BACKEND | The default backend, file or sqlite. An explicit --backend outranks it, and a junk value is refused. |
CANDY_CODETIME_GOAL | The daily goal, as whole seconds or whole hours such as 6h. It is presentation only. |
CANDY_CODETIME_THEME | The palette name, the same as --theme. The flag outranks it. |
CODETIME_HOOK_DURATION, CODETIME_HOOK_BIN | Read by the worked hook script only, for the seconds per save and the binary path. |
SUGARTICK_* | Legacy names from the tool's earlier life. Each one is imported under its CANDY_CODETIME_* name on every launch, with a deprecation notice on stderr. The new name wins. |
Storage details
Each day file line is one JSON object with the keys time, project, language, file, duration and tags. Readers ignore unknown keys. The SQLite schema is versioned with user_version set to 1, and a file stamped with a version this build does not know is refused on open. Nothing is pruned automatically: neither the live database nor the archives are trimmed.
Day files are keyed by the calendar date in PHP's effective timezone. Since PHP 8.3 the TZ variable no longer sets that zone, so set date.timezone in php.ini to choose it.
Keys and keybindings
The dashboard reacts to these keys. Keys cannot be rebound. Letter commands answer unmodified keys only, so Ctrl+q does not quit and Ctrl+r does not reload.
| Key | Action |
|---|---|
| ← / h | Move the window back one day |
| → / l | Move the window forward one day |
| g | Jump the window end back to today |
| + / - | Widen or narrow the window through 7, 14, 30 and 90 days |
| t | Toggle the lower pane between languages and tags |
| r | Reload from disk |
| q, Esc, Ctrl+C | Quit |
The dashboard subscribes to no timers and does not animate. It redraws only when a key changes the view, and it does not refresh by itself while it is open.
Theme and colour
The --theme flag and CANDY_CODETIME_THEME pick one of six palettes. default is the shipped palette. light is for a white terminal, where the pastel tones of the default wash out. The palettes apply only where the terminal answers with 256-colour or TrueColor support. The frames are identical everywhere else.
candy-codetime --theme=light dashboard
CANDY_CODETIME_THEME=gruvbox candy-codetime
Colour is decorative only. Bars are drawn by height, every coloured value carries a text label, and the milestone mark is the text *. NO_COLOR=1, CLICOLOR=0 and TERM=dumb all turn the tints off. A light or high-contrast choice never removes a label.
Examples
The examples/ directory holds two PHP programs and one shell script. The PHP programs load the Composer autoloader, so run them from a checkout after composer install.
examples/dashboard.phpseeds a demo data directory at a fixed path under the system temp directory, which other local users can also reach, with a pretend week of beats and opens the dashboard. It refuses with exit 1 unless both stdin and stdout are terminals. This is the program behind the demo GIF below.examples/headless-report.phpseeds two days of beats into a temporary directory, reads them back withStore::loadRange(), folds them withStats::compute()and prints the totals. It needs no terminal and is the library version ofsummary.examples/plugin-heartbeat.example.shis a POSIX shell hook of about 35 lines. It sends one heartbeat per save throughpush --, falling back to a locked append. It is a worked example, not a shipped plugin.
php examples/headless-report.php < /dev/null
php examples/dashboard.php < /dev/null # exits 1: stdin is not a terminal
Testing
The suite runs under PHPUnit 10. Run it once from the package root, with stdin redirected:
cd candy-codetime && composer install && vendor/bin/phpunit < /dev/null
The tests cover the CLI, the dashboard, the renderer, the store and its privacy modes, the SQLite backend under tests/Storage/, the exporters under tests/Export/, the gaps report, the ignore rules, the backup archiver and the locale parity check in LangParityTest. PharBuildScriptTest covers the phar build. The fold in Stats is pure, so most dashboard tests run against fixed beats.
Troubleshooting
The dashboard prints an error and exits 1
Stdin or stdout is not a terminal. This is expected in a cron job, a pipe or a CI log. Use the headless commands instead: export csv, export json, summary or gaps, which write plain lines to stdout.
A beat I pushed by hand does not appear
There are three usual causes. A raw line written with >> and no time key is a corrupt record, and it is dropped on read and counted in the day-file warning. A --backend=sqlite dashboard never reads a raw JSONL line, because raw lines land in the file backend only. And a .sugartrackignore match skips the push, which is reported on stdout. Run the push through candy-codetime push to see which case applies.
The sqlite backend is used but my records are in the file store
Auto-selection looks at what each store holds. When the database has records and the JSONL store does not, the CLI picks SQLite. Set --backend=file or CANDY_CODETIME_BACKEND=file to pin the choice. When both stores hold records, the CLI prints a one-line pointer on stderr naming the other store.
A push is refused, or an ignore file is refused
A duration that is negative or not a whole number is refused with exit 1. A duration above one year is clamped rather than refused. An ignore or allow file over 1 MiB, or one that exists but cannot be read, makes push exit 1, because tracking with an unknown opt-out is the failure the file exists to prevent. Shrink the file, or fix its permissions.
A file mode warning, or the run aborts
A directory or file left world-readable is tightened on the next CLI run, whatever the command. If the tightening fails, the run aborts instead of printing over data that is still exposed. Write plugin and cron output under umask 077 so the files are private from the start.
The CLI refuses to start a write
With CANDY_CODETIME_DIR unset and neither XDG_DATA_HOME nor HOME set, the CLI has no safe place to write and refuses. Set CANDY_CODETIME_DIR to an absolute path for that run.
Architecture
The CLI lives in bin/candy-codetime. It parses the global flags, then dispatches each command to the library. The library splits along the data flow: the storage layer reads and writes beats, the fold and the report layers turn beats into numbers, and the view layer draws them. Each layer depends only on the one before it.
| File | Role |
|---|---|
src/Heartbeat.php | The value object for one activity sample. |
src/Store.php | The JSONL store. It implements HeartbeatReader, takes the advisory lock and enforces the private modes. |
src/Storage/SqliteBackend.php, src/Storage/HeartbeatReader.php | The indexed SQLite backend, and the read contract that both backends satisfy. |
src/Stats.php | The pure fold into totals and day buckets. |
src/Report/GapsReport.php | Gap detection over sorted beats. |
src/Dashboard.php, src/Renderer.php, src/Theme.php | The SugarCraft Model, its view and the palettes. |
src/Export/* | The csv, json and ics exporters. |
src/Backup/AutoBackup.php | The copy-only archiver for day files and the database. |
src/Ignore/SugarTrackIgnore.php, src/Support/Detect.php | The ignore matcher, and the project and language detection used by push. |
Writes are append-only, and reads degrade loudly
The file store is append-only at the file level, so a hook can append with >>. Raw appends skip the advisory lock and the privacy checks, which is why plugins should call push. A day file that exists but cannot be opened is named in a stderr warning and counted as an empty day. It is never skipped in silence.
Privacy is a launch invariant
Directories are 0700, and day files, the database and its sidecars are 0600. Stored names are swept of escape sequences and control characters before they are drawn, so a doctored file cannot inject a sequence into the dashboard. Shared foundations: the cooperative cancellation token from sugar-async is checked before each write.
Upstream mapping
| Upstream | Where it shows up here |
|---|---|
| Rtarun3606k/TakaTime (Go) | The design antecedent. The heartbeat model, the project, language and file tracking, the dashboard and the ignore file are ported. The always-on daemon became an explicit push, and MongoDB became JSONL day files plus an optional SQLite backend. |
TakaTime's taka-report binary | Not ported. The summary command folds the same data in the CLI, and it has no GitHub Action. |
TakaTime's .takatrack allowlist | Not ported. The .sugartrackallow file plays that role. |
TakaTime's editor field | Not carried. Upstream heartbeats carry it, and this schema omits it, so a plugin-written value survives the round trip but nothing reads it. |
SugarCraft is a native PHP project. This app is not a line-for-line port, and the rename from sugar-tick is covered in the Changelog section.
Changelog and versioning
The version is Support\Version::CURRENT, 0.1.0, and the release tags use the candy-codetime/v prefix. Inside a phar, --version prints the build stamp instead, and SOURCE_DATE_EPOCH keeps rebuilds of a tag byte-stable. The package was published as sugarcraft/sugar-tick until the 2026-10 rename. The namespace moved from SugarCraft\Tick\ to SugarCraft\CodeTime\. The old SUGARTICK_* environment names and the old data directory still work through one-time compatibility paths.
Related
- sugar-charts: the
Sparklinethat draws the daily timeline. - sugar-async: the cancellation token that
Store::append()checks before it writes. - sugar-core: the
ModelandProgramruntime the dashboard runs on.
Demos.
VHS-recorded GIFs of the shipped demos. Regenerated automatically on every push that touches the source.