zebra 0.0.1-preview.1
Zebra: an incremental build orchestrator for Zena and standalone workspaces
zebra#
An incremental script and service runner for Zena (zena-package.json), standalone Zebra (zebra.json), and Wireit (package.json) workspaces, built on zena-lang:workflow.
Zebra runs a dependency graph of scripts and long-running services with declared inputs, outputs, and dependencies, rerunning only what changed. For each script, Zebra content-hashes the declared inputs and asks the workflow engine what to do: nothing (when the previous run recorded the same fingerprints and declared outputs are intact), restore from the local content-addressed cache, or execute the command (sh -c in the package directory with node_modules/.bin on PATH).
Installation#
zebra is built into the zena CLI (zena build <target>). To use it as a library or standalone runner:
zena pkg add zena-lang:zebra
CLI Usage#
zena build [-j <jobs>] [-w|--watch] [-f|--force] [--no-cache] [-v|--verbose] [<target>] [-- <args>...]
zena run [-j <jobs>] [-w|--watch] [-f|--force] [--no-cache] [-v|--verbose] <target> [-- <args>...]
zena test [-j <jobs>] [-w|--watch] [--force] [--no-cache] [-v|--verbose] [-- <args>...]
zena build --migrate [--dry-run] [-f|--force] [<package-dir>...]
<target>can be a script name in the current package (zena build test,zena run check), a package directory (zena build ./packages/app, which runsbuild), or<package-dir>:<script>(zena build ./packages/app:test). With no<target>,zena buildruns the current package'sbuildscript andzena testruns itstestscript.-- <args>...appends shell-quoted arguments to the entry target's command only, running that entry step uncached without overwriting its saved freshness record.-j/--jobs <n>bounds parallel command execution (defaulting toZEBRA_PARALLEL,WIREIT_PARALLEL, orZENA_AVAILABLE_PARALLELISM).-w/--watchwatches input globs, lockfiles, and package manifests for changes, re-running affected steps incrementally while keeping unchanged services alive in aServicePoolacross rebuilds.-f/--forcebypasses freshness and cached outputs to rerun scripts unconditionally.--no-cachedisables restoring outputs from.zebra/blobs/when a step is not fresh.-v/--verboseprints every step (includingfreshandskipped) and any captured stdout/stderr on the rail.--migrateconverts Wireit blocks inpackage.jsonintozena-package.json(when present) orzebra.json.
Programmatic Usage#
import { buildTarget, reportBuild } from 'zena-lang:zebra/runner';
import { ScriptRef } from 'zena-lang:zebra/wireit-config';
let outcome = await buildTarget('.', new ScriptRef('packages/app', 'build'), {
parallelism: 4,
});
let exitCode = reportBuild(outcome);
Configuration (zena-package.json and zebra.json)#
Zena packages configure scripts and filesets directly in zena-package.json. Non-Zena projects can use a standalone zebra.json (with an optional "workspace": {"packages": [...]} at the workspace root). Both support // and /* ... */ comments:
{
"name": "app",
"dependencies": {
"lib": {"path": "../lib"},
},
"filesets": {
"assets": ["assets/**"],
},
"scripts": {
"build": {
"command": "zena build src/main.zena -o out/app.wasm",
"output": ["out/app.wasm"],
"dependencies": ["source", "assets"],
},
"test": {
"type": "zena:test",
"tests": "test/*_test.zena",
},
"fmt": "zena fmt --check .",
},
}
- Declarative
zena:teststeps and defaulttesttarget: Scripts inzena-package.jsonandzebra.jsoncan set"type": "zena:test"(with optional"tests": true,"tests": "test/*_test.zena", or"tests": ["test/*_test.zena", ...]— defaulting to["test/**/*_test.zena", "tests/**/*_test.zena"]when omitted — and optional"debug": truefor-g) to run Zena tests in-process throughTestStepRunner. Test pattern globs merge intofiles, andzena-package.json"zena:test"steps automatically depend onsource. When azena-package.jsonomits atestscript (and no fallbackpackage.jsondefinestest), Zebra synthesizes a"type": "zena:test"target overtest/**/*_test.zenaandtests/**/*_test.zena. - Automatic
sourcefileset: Every package withzena-package.jsonexposes an automaticsourcefileset covering its library.zenafiles (from"source", defaulting to"src"and excluding*_test.zena,test/**, andtests/**),zena-package.json, any"wit"dependencies, and thesourcefilesets of all"path"dependencies. Scripts opt into it via"dependencies": ["source"](or"../pkg:source"). - Named
filesets: Entries accept either a glob array shorthand ("wit": ["wit/**/*.wit"]) or{"files": [...], "dependencies": [...]}and compose transitively without spawning commands. - Caching and tracking: Task scripts cache automatically whenever
files,output, or a fileset dependency is declared, defaultingoutputto[]when omitted. Setting"cache": falseopts a step out of freshness and caching while keeping itsfilesglobs active in--watchmode. Omittingfiles,output, and fileset dependencies on a command step leaves it untracked so it runs every time. String entries ("fmt": "zena fmt --check .") are shorthands for always-run commands. - Locks:
locksdefaults to["zena-lock.json"]and may be set at the package root or overridden per script ("locks": []disables lockfile hashing). - Services: Scripts with
"service": trueor"service": {"readyWhen": {"lineMatches": "..."}}start on demand when a dependent executes, wait for readiness when configured, are shared across dependents, and are stopped as a Unix process group (SIGTERMthenSIGKILL) when dependents finish. Invoking a service directly as the top-level target runs its dependencies and streams the service in the foreground. - Wireit fallback: When a package directory has no
zebra.jsonand no"scripts"block inzena-package.json, Zebra falls back topackage.jsonWireit scripts while still serving filesets fromzena-package.json. Dependencies can cross freely betweenzena-package.json,zebra.json, andpackage.jsonpackages.
Cache Layout (.zebra/)#
Each package's <pkg>/.zebra/ directory stores:
state.json— freshness records for that package's scripts (the last cache key and output manifest).cache/<key>.json— cache key to output manifest.blobs/— content-addressed output bytes (sha256).
The workspace root's .zebra/ directory stores:
hashes.json— the(mtime, size)tosha256file hash memo shared across packages (with a 20ms racy-timestamp guard).plans/<hash>.plan—stat-verified cachedScriptConfigclosures keyed by target entry.
A dependency contributes the digest of its outputs to dependents' cache keys rather than its input fingerprint, giving early cutoff when a dependency reruns and produces identical outputs.
GitHub Actions Remote Cache#
Setting ZEBRA_CACHE=github layers GitHubActionsCache behind the local .zebra/ DiskCache (TieredCache). On a local cache miss, Zebra queries the GitHub Actions v2 CacheService Twirp JSON API, verifies downloaded blob sha256 digests, populates <pkg>/.zebra/, and materializes outputs into the workspace. On a build step execution, Zebra writes <pkg>/.zebra/ first and uploads the step's entry to GitHub Actions Cache (ZEBRA_CACHE_READ_ONLY=1 disables uploads; ZEBRA_CACHE=none disables both local and remote caching).
In GitHub Actions workflows, run .github/actions/setup-zebra-cache before build steps so ACTIONS_RESULTS_URL and ACTIONS_RUNTIME_TOKEN are served to run: steps over a 127.0.0.1 token custodian (ZEBRA_GITHUB_CUSTODIAN_URL).
Libraries#
zebra(zebra/main) — CLI entry point (main).zebra/runner—buildTarget,watchTarget,BuildOptions,WatchOptions,reportBuild,reportMigration,formatBuildReport, andBuildOutcome.zebra/zebra-config—zena-package.jsonandzebra.jsonparsing (ZebraWorkspace), synthesizedsourcefilesets, and Wireit migration (migrateWorkspaceToZebra,convertPackageJsonToZebraJson,mergeWireitIntoZenaPackageJson).zebra/wireit-config—package.jsonWireit parsing (WireitWorkspace) and shared script configuration types (ScriptConfig,ScriptRef,DependencySpec,ServiceConfig,EnvBinding,ConfigError,refKey,resolveDependency).zebra/plan-cache—.zebra/plans/snapshot serialization andstat-verified warm plan loading (loadOrCollectConfigs,PlanLoadStats,ConfigProbe).zebra/builder— TranslatesScriptConfigclosures intoworkflowsteps and execution callbacks (planScripts,StepExecution,lockfileCandidates).zebra/disk-cache,zebra/github-cache, andzebra/state-json—.zebra/blob/manifest storage (DiskCache,TieredCache,stateDirOf), GitHub Actions remote caching (GitHubActionsCache,GitHubCacheConfig,CacheMode,resolveCacheMode,resolveGitHubCacheConfig), and JSON serialization for state, manifests, and hash memos.zebra/fs-walkandzebra/fs-util— Input glob discovery (FileHasher,expandGlobs,hashFile,validateGlobs,splitBase) and workspace path utilities.zebra/shell— POSIX shell argument quoting (shellQuote,appendShellArgs). Zebra's terminal output useszena-lang:terminal(packages/terminal): colors, the Clack-style rail layout and the spinner.
License#
MIT
import {Future} from 'zena:async';
import {getArguments} from 'zena:cli';
import {checkSignal} from 'zena:process';
import {joinWorkspace} from './fs-util.zena';
import {
BuildOutcome,
buildTarget,
reportBuild,
reportMigration,
watchTarget,
} from './runner.zena';
import {ScriptRef} from './wireit-config.zena';
import {migrateWorkspaceToZebra} from './zebra-config.zena';
/**
* zebra: an incremental build runner for Zena (`zena-package.json`),
* standalone Zebra (`zebra.json`), and Wireit (`package.json`) workspaces.
*
* zebra [-C <workspace-root>] [-j <jobs>] [-w|--watch] [-f|--force] [--no-cache] [-v|--verbose] [<package-dir>] [<script>] [-- <args>...]
* zebra [-C <workspace-root>] --migrate [--dry-run] [-f|--force] [<package-dir>...]
*
* The workspace root defaults to the current directory (`-C` points at a
* nested workspace), and `<script>` defaults to `build`.
*/
let usage =
'usage: zebra [-C <workspace-root>] [-j <jobs>] [-w|--watch] [-f|--force] [--no-cache] [-v|--verbose] [--migrate [--dry-run]] [<package-dir>] [<script>] [-- <args>...]';
function parseCliEntry(args: Array<String>, next: i32) {
let rest = args.length - next;
if (rest == 0) {
return new ScriptRef('', 'build');
}
if (rest == 1) {
let arg = args[next];
if (arg.startsWith('.')) {
var colon = -1;
for (var i = 0; i < arg.length; i += 1) {
if (arg.getByteAt(i) == 58) {
colon = i;
break;
}
}
if (colon < 0) {
return new ScriptRef(joinWorkspace('', arg), 'build');
}
let pkg = joinWorkspace('', arg.sliceBytes(0, colon));
let script = arg.sliceBytes(colon + 1, arg.length);
return new ScriptRef(pkg, script);
}
return new ScriptRef('', arg);
}
return new ScriptRef(joinWorkspace('', args[next]), args[next + 1]);
}
export async function main(): Future<i32> {
let args = getArguments();
var root = '';
var jobs = 0;
var watch = false;
var force = false;
var useCache = true;
var verbose = false;
var migrate = false;
var dryRun = false;
var next = 1;
while (next < args.length && args[next].startsWith('-')) {
let flag = args[next];
if (flag == '-C') {
if (next + 1 >= args.length) {
console.log(usage);
return 2;
}
root = args[next + 1];
next += 2;
} else if (flag == '-j' || flag == '--jobs') {
if (next + 1 >= args.length) {
console.log(usage);
return 2;
}
if (let (true, n) = parseI32(args[next + 1])) {
if (n >= 1) {
jobs = n;
next += 2;
continue;
}
}
console.log(`zebra: invalid job count "${args[next + 1]}"`);
return 2;
} else if (flag == '-w' || flag == '--watch') {
watch = true;
next += 1;
} else if (flag == '-f' || flag == '--force') {
force = true;
next += 1;
} else if (flag == '--no-cache') {
useCache = false;
next += 1;
} else if (flag == '-v' || flag == '--verbose') {
verbose = true;
next += 1;
} else if (flag == '--migrate') {
migrate = true;
next += 1;
} else if (flag == '--dry-run') {
dryRun = true;
next += 1;
} else if (flag == '--') {
break;
} else {
console.log(usage);
return 2;
}
}
let targetArgs = new GrowableArray<String>();
let extraArgs = new GrowableArray<String>();
var afterDashDash = false;
while (next < args.length) {
let arg = args[next];
if (!afterDashDash && arg == '--') {
afterDashDash = true;
} else if (afterDashDash) {
extraArgs.push(arg);
} else {
targetArgs.push(arg);
}
next += 1;
}
if (migrate) {
if (extraArgs.length > 0) {
console.log(usage);
return 2;
}
try {
let result = await migrateWorkspaceToZebra(root, targetArgs, force, dryRun);
return reportMigration(result, dryRun);
} catch (e) {
console.log('zebra: ' + e.message);
return 1;
}
}
if (dryRun) {
console.log(usage);
return 2;
}
if (targetArgs.length > 2) {
console.log(usage);
return 2;
}
let entry = parseCliEntry(targetArgs, 0);
var outcome: BuildOutcome | null = null;
try {
outcome = if (watch)
await watchTarget(root, entry, {
parallelism: jobs,
force,
useCache,
verbose,
extraArgs,
})
else
await buildTarget(root, entry, {
parallelism: jobs,
force,
useCache,
extraArgs,
});
} catch (e) {
let sig = checkSignal();
if (sig != 0) {
return 128 + sig;
}
console.log('zebra: ' + e.message);
return 1;
}
if (outcome == null) {
return 1;
}
return reportBuild(outcome, verbose);
}
| Version | Published | Dependencies | Approved by |
|---|---|---|---|
| 0.0.1-preview.1 | 2026-11-19 |
|