zcode-agent 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,383 @@
1
+ 'use strict';
2
+ // Workspace boundaries for concurrent sessions:
3
+ // - ownership: `--owns` patterns (paths or globs, relative to --cwd) name
4
+ // what a session may modify; none = the whole workspace.
5
+ // - leases: a live session registers its ownership under
6
+ // <root>/leases/<workspace>/; a new session whose ownership overlaps a
7
+ // live one is refused (exit 7) unless --allow-overlap.
8
+ // - change tracking: a snapshot before and after the work yields the files
9
+ // the session changed (git status + content hashes in a git repo, a
10
+ // bounded mtime walk otherwise) and the ones outside its ownership.
11
+ const fs = require('node:fs');
12
+ const path = require('node:path');
13
+ const crypto = require('node:crypto');
14
+ const { execFileSync } = require('node:child_process');
15
+ const { rootDir } = require('./isolation.js');
16
+ const { pidAlive } = require('./store.js');
17
+
18
+ class OwnershipError extends Error {}
19
+
20
+ const toPosix = (p) => p.split(path.sep).join('/');
21
+
22
+ function gitToplevel(cwd) {
23
+ try {
24
+ return execFileSync('git', ['-C', cwd, 'rev-parse', '--show-toplevel'], {
25
+ encoding: 'utf8',
26
+ stdio: ['ignore', 'pipe', 'ignore'],
27
+ timeout: 5000,
28
+ }).trim();
29
+ } catch {
30
+ return null;
31
+ }
32
+ }
33
+
34
+ // The lease/change-tracking root: the git toplevel when --cwd is inside a
35
+ // repo (so sessions in sibling subdirectories still see each other), else
36
+ // the real --cwd.
37
+ function workspaceRoot(cwd) {
38
+ const real = fs.realpathSync(cwd);
39
+ const top = gitToplevel(real);
40
+ return top ? fs.realpathSync(top) : real;
41
+ }
42
+
43
+ // Ownership patterns arrive relative to --cwd; store them relative to the
44
+ // workspace root, posix-style, so every session compares like with like.
45
+ function normalizeOwns(patterns, cwd, root, flag = '--owns') {
46
+ const realCwd = fs.realpathSync(cwd);
47
+ return patterns.map((raw) => {
48
+ const pattern = String(raw).trim();
49
+ if (!pattern) throw new OwnershipError(`${flag} pattern must not be empty`);
50
+ const abs = path.isAbsolute(pattern) ? pattern : path.join(realCwd, pattern);
51
+ const rel = toPosix(path.relative(root, abs));
52
+ if (rel === '' || rel === '.') return '**';
53
+ if (rel.startsWith('../') || rel === '..' || path.isAbsolute(rel)) {
54
+ throw new OwnershipError(`${flag} "${pattern}" is outside the workspace ${root}`);
55
+ }
56
+ return /[/\\]$/.test(pattern) && !hasWildcard(rel) ? `${rel}/**` : rel;
57
+ });
58
+ }
59
+
60
+ function globToRegExp(glob) {
61
+ let re = '';
62
+ for (let i = 0; i < glob.length; i++) {
63
+ const c = glob[i];
64
+ if (c === '*') {
65
+ if (glob[i + 1] === '*') {
66
+ i++;
67
+ if (glob[i + 1] === '/') {
68
+ i++;
69
+ re += '(?:.*/)?';
70
+ } else {
71
+ re += '.*';
72
+ }
73
+ } else {
74
+ re += '[^/]*';
75
+ }
76
+ } else if (c === '?') {
77
+ re += '[^/]';
78
+ } else {
79
+ re += c.replace(/[.+^${}()|[\]\\]/g, '\\$&');
80
+ }
81
+ }
82
+ return new RegExp(`^${re}$`);
83
+ }
84
+
85
+ const hasWildcard = (p) => /[*?]/.test(p);
86
+
87
+ // A plain path owns itself and everything beneath it; a glob owns its
88
+ // matches. Empty ownership = the whole workspace.
89
+ function isOwned(relPath, owns) {
90
+ if (!owns || owns.length === 0) return true;
91
+ return owns.some((pattern) => {
92
+ if (!hasWildcard(pattern)) return relPath === pattern || relPath.startsWith(`${pattern}/`);
93
+ return globToRegExp(pattern).test(relPath);
94
+ });
95
+ }
96
+
97
+ // The literal directory part of a pattern (segments before the first
98
+ // wildcard). Overlap is decided conservatively on these prefixes: two
99
+ // patterns overlap when one prefix contains the other.
100
+ function staticSegments(pattern) {
101
+ const out = [];
102
+ for (const seg of pattern.split('/')) {
103
+ if (hasWildcard(seg)) break;
104
+ out.push(seg);
105
+ }
106
+ return out;
107
+ }
108
+
109
+ function patternsOverlap(a, b) {
110
+ const sa = staticSegments(a);
111
+ const sb = staticSegments(b);
112
+ const n = Math.min(sa.length, sb.length);
113
+ for (let i = 0; i < n; i++) if (sa[i] !== sb[i]) return false;
114
+ // Same literal prefix. Two fully literal, distinct paths of equal depth
115
+ // were already ruled out above; anything else may share files.
116
+ return true;
117
+ }
118
+
119
+ function ownsOverlap(a, b) {
120
+ if (!a || !b || a.length === 0 || b.length === 0) return true;
121
+ return a.some((pa) => b.some((pb) => patternsOverlap(pa, pb)));
122
+ }
123
+
124
+ // --- leases -------------------------------------------------------------------
125
+
126
+ function leaseDir(root, env = process.env) {
127
+ const key = crypto.createHash('sha256').update(root).digest('hex').slice(0, 16);
128
+ return path.join(rootDir(env), 'leases', key);
129
+ }
130
+
131
+ function readLeases(dir) {
132
+ let names = [];
133
+ try {
134
+ names = fs.readdirSync(dir).filter((n) => n.endsWith('.json'));
135
+ } catch {
136
+ return [];
137
+ }
138
+ const out = [];
139
+ for (const name of names) {
140
+ try {
141
+ out.push(JSON.parse(fs.readFileSync(path.join(dir, name), 'utf8')));
142
+ } catch {
143
+ /* half-written or removed concurrently */
144
+ }
145
+ }
146
+ return out;
147
+ }
148
+
149
+ // Registers this session's lease, then compares against every other live
150
+ // lease. Writing first and reading second means two sessions starting at
151
+ // the same instant both see each other; the later (startedAt, id) backs
152
+ // off, so exactly one proceeds.
153
+ function acquireLease({ id, root, owns, touch = [], allowOverlap = false, env = process.env }) {
154
+ const dir = leaseDir(root, env);
155
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
156
+ const mine = { id, pid: process.pid, root, owns, touch, startedAt: Date.now() };
157
+ const file = path.join(dir, `${id}.json`);
158
+ fs.writeFileSync(file, JSON.stringify(mine) + '\n', { mode: 0o600 });
159
+
160
+ const others = [];
161
+ for (const lease of readLeases(dir)) {
162
+ if (!lease || lease.id === id) continue;
163
+ if (!pidAlive(lease.pid)) {
164
+ fs.rmSync(path.join(dir, `${lease.id}.json`), { force: true });
165
+ continue;
166
+ }
167
+ others.push(lease);
168
+ }
169
+ // --touch never reserves anything, but it may not edit what a live
170
+ // session owns (an empty ownership is the whole workspace). Not ordered by
171
+ // start time: the toucher is the one that has to step aside.
172
+ const touchConflicts = touch.length && !allowOverlap ? others.filter((o) => ownsOverlap(touch, o.owns)) : [];
173
+ if (touchConflicts.length) {
174
+ fs.rmSync(file, { force: true });
175
+ return { ok: false, conflicts: touchConflicts, others, touch: true };
176
+ }
177
+ const conflicts = others.filter((o) => ownsOverlap(owns, o.owns));
178
+ const blocking = conflicts.filter(
179
+ (o) => o.startedAt < mine.startedAt || (o.startedAt === mine.startedAt && o.id < id)
180
+ );
181
+ if (blocking.length > 0 && !allowOverlap) {
182
+ fs.rmSync(file, { force: true });
183
+ return { ok: false, conflicts: blocking, others };
184
+ }
185
+ return { ok: true, conflicts, others, release: () => fs.rmSync(file, { force: true }) };
186
+ }
187
+
188
+ function liveLeases(root, env = process.env) {
189
+ return readLeases(leaseDir(root, env)).filter((l) => l && pidAlive(l.pid));
190
+ }
191
+
192
+ // --- change tracking ----------------------------------------------------------
193
+
194
+ // zcode's own per-session directories (<cwd>/.zcode/out/<id>, project skills)
195
+ // are never changes of the task, at any depth. The Playwright MCP's scratch
196
+ // dir (.playwright-mcp: console logs, page snapshots) written by --visual
197
+ // verification is tooling output, not task output.
198
+ const TOOL_DIRS = new Set(['.zcode', '.playwright-mcp']);
199
+ const isZcodePath = (rel) => rel.split('/').some((seg) => TOOL_DIRS.has(seg));
200
+
201
+ const WALK_SKIP = new Set(['.git', 'node_modules', '.zcode', '.playwright-mcp', '.DS_Store']);
202
+ const WALK_LIMIT = 20000;
203
+ const HASH_LIMIT = 8 * 1024 * 1024;
204
+
205
+ function fileSignature(abs) {
206
+ try {
207
+ const st = fs.statSync(abs);
208
+ if (!st.isFile()) return `other:${st.mtimeMs}`;
209
+ if (st.size > HASH_LIMIT) return `big:${st.size}:${st.mtimeMs}`;
210
+ return crypto.createHash('sha1').update(fs.readFileSync(abs)).digest('hex');
211
+ } catch {
212
+ return 'missing';
213
+ }
214
+ }
215
+
216
+ // Parses `git status --porcelain=v1 -z`; rename/copy entries carry the
217
+ // source path as an extra NUL field.
218
+ function gitStatus(root) {
219
+ const raw = execFileSync(
220
+ 'git',
221
+ ['-C', root, 'status', '--porcelain=v1', '-z', '--untracked-files=all'],
222
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 15000, maxBuffer: 64 * 1024 * 1024 }
223
+ );
224
+ const fields = raw.split('\0');
225
+ const out = new Map();
226
+ for (let i = 0; i < fields.length; i++) {
227
+ const f = fields[i];
228
+ if (f.length < 4) continue;
229
+ const code = f.slice(0, 2);
230
+ out.set(f.slice(3), code);
231
+ if (code[0] === 'R' || code[0] === 'C') i++;
232
+ }
233
+ return out;
234
+ }
235
+
236
+ function gitHead(root) {
237
+ try {
238
+ return execFileSync('git', ['-C', root, 'rev-parse', '--verify', '-q', 'HEAD'], {
239
+ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000,
240
+ }).trim() || null;
241
+ } catch {
242
+ return null;
243
+ }
244
+ }
245
+
246
+ // Files changed between two commits (the executor committed, stashed or
247
+ // checked out): without this, committed work would vanish from the diff.
248
+ function committedChanges(root, from, to) {
249
+ try {
250
+ const raw = execFileSync('git', ['-C', root, 'diff', '--name-status', '-z', '--no-renames', from, to], {
251
+ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 15000, maxBuffer: 64 * 1024 * 1024,
252
+ });
253
+ const f = raw.split('\0');
254
+ const out = [];
255
+ for (let i = 0; i + 1 < f.length; i += 2) {
256
+ if (!f[i]) break;
257
+ const change = f[i][0] === 'A' ? 'added' : f[i][0] === 'D' ? 'deleted' : 'modified';
258
+ out.push({ path: f[i + 1], change });
259
+ }
260
+ return out;
261
+ } catch {
262
+ return [];
263
+ }
264
+ }
265
+
266
+ function snapshot(root) {
267
+ if (gitToplevel(root)) {
268
+ try {
269
+ const entries = new Map();
270
+ for (const [rel, code] of gitStatus(root)) {
271
+ if (isZcodePath(rel)) continue;
272
+ entries.set(rel, { code, sig: fileSignature(path.join(root, rel)) });
273
+ }
274
+ return { kind: 'git', root, head: gitHead(root), entries };
275
+ } catch {
276
+ /* fall back to the walk */
277
+ }
278
+ }
279
+ const entries = new Map();
280
+ const stack = [''];
281
+ while (stack.length) {
282
+ const rel = stack.pop();
283
+ let dirents;
284
+ try {
285
+ dirents = fs.readdirSync(path.join(root, rel), { withFileTypes: true });
286
+ } catch {
287
+ continue;
288
+ }
289
+ for (const d of dirents) {
290
+ if (WALK_SKIP.has(d.name)) continue;
291
+ const childRel = rel ? `${rel}/${d.name}` : d.name;
292
+ if (d.isDirectory()) stack.push(childRel);
293
+ else if (d.isFile()) {
294
+ if (entries.size >= WALK_LIMIT) return { kind: 'unavailable', entries: null };
295
+ try {
296
+ const st = fs.statSync(path.join(root, childRel));
297
+ entries.set(childRel, { code: 'fs', sig: `${st.size}:${st.mtimeMs}` });
298
+ } catch {
299
+ /* vanished mid-walk */
300
+ }
301
+ }
302
+ }
303
+ }
304
+ return { kind: 'fs', entries };
305
+ }
306
+
307
+ // Files whose state differs between two snapshots. In git mode a path
308
+ // absent from `after` but present in `before` went back to clean — it was
309
+ // still changed by someone.
310
+ function diffSnapshots(before, after) {
311
+ if (!before || !after || !before.entries || !after.entries || before.kind !== after.kind) {
312
+ return null;
313
+ }
314
+ const out = [];
315
+ const paths = new Set([...before.entries.keys(), ...after.entries.keys()]);
316
+ for (const rel of [...paths].sort()) {
317
+ const b = before.entries.get(rel);
318
+ const a = after.entries.get(rel);
319
+ if (b && a && b.sig === a.sig && b.code === a.code) continue;
320
+ let change = 'modified';
321
+ if (after.kind === 'fs') {
322
+ if (!b) change = 'added';
323
+ else if (!a) change = 'deleted';
324
+ } else if (a) {
325
+ if (a.code.includes('D') || a.sig === 'missing') change = 'deleted';
326
+ else if (!b && (a.code === '??' || a.code[0] === 'A')) change = 'added';
327
+ }
328
+ out.push({ path: rel, change });
329
+ }
330
+ if (after.kind === 'git' && before.head && after.head && before.head !== after.head) {
331
+ const seen = new Set(out.map((f) => f.path));
332
+ for (const f of committedChanges(after.root, before.head, after.head)) {
333
+ if (!seen.has(f.path) && !isZcodePath(f.path)) out.push({ ...f, committed: true });
334
+ }
335
+ out.sort((a, b) => a.path.localeCompare(b.path));
336
+ }
337
+ return out;
338
+ }
339
+
340
+ // Keeps zcode's own scratch dirs out of the target repo's `git status`:
341
+ // appends missing entries to the repo-local exclude file (never .gitignore;
342
+ // `--git-path info/exclude` also resolves for worktrees). Idempotent,
343
+ // append-only, silent: every error is ignored.
344
+ const LOCAL_EXCLUDES = ['.zcode/', '.playwright-mcp/'];
345
+ function ensureLocalExclude(cwd) {
346
+ try {
347
+ const rel = execFileSync('git', ['-C', cwd, 'rev-parse', '--git-path', 'info/exclude'], {
348
+ encoding: 'utf8',
349
+ stdio: ['ignore', 'pipe', 'ignore'],
350
+ }).trim();
351
+ if (!rel) return;
352
+ const file = path.resolve(cwd, rel);
353
+ let text = '';
354
+ try {
355
+ text = fs.readFileSync(file, 'utf8');
356
+ } catch {
357
+ /* no exclude file yet */
358
+ }
359
+ const have = new Set(text.split(/\r?\n/).map((l) => l.trim().replace(/^\//, '').replace(/\/$/, '')));
360
+ const missing = LOCAL_EXCLUDES.filter((e) => !have.has(e.replace(/\/$/, '')));
361
+ if (!missing.length) return;
362
+ fs.mkdirSync(path.dirname(file), { recursive: true });
363
+ fs.appendFileSync(file, `${text && !text.endsWith('\n') ? '\n' : ''}${missing.join('\n')}\n`);
364
+ } catch {
365
+ /* hygiene is best-effort */
366
+ }
367
+ }
368
+
369
+ module.exports = {
370
+ ensureLocalExclude,
371
+ OwnershipError,
372
+ workspaceRoot,
373
+ normalizeOwns,
374
+ globToRegExp,
375
+ isOwned,
376
+ isZcodePath,
377
+ ownsOverlap,
378
+ acquireLease,
379
+ liveLeases,
380
+ leaseDir,
381
+ snapshot,
382
+ diffSnapshots,
383
+ };
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "zcode-agent",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "Cheap, verified execution for Claude Code and Codex: your orchestrator decides, GLM-5.3-Flash builds, tests and visually verifies in headless ZCode sessions (parallel sessions, subagents, dependency plans) and hands back a compact result. Also an ACP agent for T3 Code, Zed and any Agent Client Protocol client. Uses your ZCode app's key, MCP servers and skills, or runs standalone.",
5
+ "license": "MIT",
6
+ "bin": {
7
+ "zcode-agent": "bin/zcode-agent.js",
8
+ "zcode-agent-acp": "bin/zcode-agent-acp.js"
9
+ },
10
+ "engines": {
11
+ "node": ">=22.13"
12
+ },
13
+ "files": [
14
+ "bin",
15
+ "lib",
16
+ "assets",
17
+ "skills",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "dependencies": {
22
+ "@zcode-agent/engine": "0.16.9"
23
+ },
24
+ "scripts": {
25
+ "test": "node --test --test-concurrency=1 \"test/unit/*.test.js\"",
26
+ "test:live": "node --test --test-concurrency=1 \"test/live/*.test.js\"",
27
+ "prepack": "node ../../scripts/sync-package-docs.mjs",
28
+ "accept:flash": "node scripts/accept.js flash",
29
+ "accept:subagent": "node scripts/accept.js subagent",
30
+ "accept:53": "node scripts/accept.js glm53"
31
+ },
32
+ "keywords": [
33
+ "glm",
34
+ "glm-5.3",
35
+ "zai",
36
+ "zcode",
37
+ "claude-code",
38
+ "codex",
39
+ "orchestrator",
40
+ "executor",
41
+ "coding-agent",
42
+ "subagent",
43
+ "headless",
44
+ "mcp",
45
+ "acp",
46
+ "agent-client-protocol",
47
+ "t3code",
48
+ "zed"
49
+ ],
50
+ "repository": {
51
+ "type": "git",
52
+ "url": "git+https://github.com/0xgeorgemathew/zcode-agent.git",
53
+ "directory": "packages/cli"
54
+ },
55
+ "homepage": "https://github.com/0xgeorgemathew/zcode-agent#readme",
56
+ "bugs": {
57
+ "url": "https://github.com/0xgeorgemathew/zcode-agent/issues"
58
+ }
59
+ }
@@ -0,0 +1,40 @@
1
+ # Orchestrator skills
2
+
3
+ These skills teach an orchestrating agent to make the design and logic decisions once, delegate the implementation to zcode-agent (one session with units, parallel sessions, or a plan), and read the compact handbacks, spending its own tokens only on decisions and exceptions. Both describe the same CLI; they differ only in runtime notes (tool timeouts for Claude Code, sandbox and network escalation for Codex).
4
+
5
+ | platform | skill in this repo | format |
6
+ |---|---|---|
7
+ | Claude Code | `skills/claude-code/zcode-agent/SKILL.md` | `SKILL.md` with `name` + `description` frontmatter |
8
+ | Codex | `skills/codex/zcode-agent/SKILL.md` + `agents/openai.yaml` | `SKILL.md` with `name` + `description` frontmatter; optional UI metadata in `agents/openai.yaml` |
9
+
10
+ ## Install
11
+
12
+ After `npm install -g zcode-agent`, install both skills with:
13
+
14
+ ```sh
15
+ zcode-agent skills install # or: zcode-agent skills install claude | codex
16
+ ```
17
+
18
+ This copies the Claude Code skill to `~/.claude/skills/zcode-agent` and the Codex skill to `${CODEX_HOME:-~/.codex}/skills/zcode-agent`, replacing only an earlier copy of the skill (and removing the pre-1.0 `zcode` skill if it is there). Run it again after upgrading zcode-agent to refresh them. `zcode-agent skills` shows what is installed, and `zcode-agent skills uninstall` removes them. The package runs no install scripts, so npm never asks to allow one.
19
+
20
+ To copy them by hand instead, run these from a checkout of this repo, or from the installed package (`$(npm root -g)/zcode-agent`), which ships `skills/`.
21
+
22
+ **Claude Code.** Personal skills, available in every project:
23
+
24
+ ```sh
25
+ mkdir -p ~/.claude/skills
26
+ cp -R skills/claude-code/zcode-agent ~/.claude/skills/zcode-agent
27
+ ```
28
+
29
+ For a single project, copy it to `<project>/.claude/skills/zcode-agent` instead and commit it so the whole team gets it. Claude Code discovers the skill from its description. You can also invoke it directly with `/zcode-agent`.
30
+
31
+ **Codex.** User skills live in `$CODEX_HOME/skills`, which defaults to `~/.codex/skills`:
32
+
33
+ ```sh
34
+ mkdir -p "${CODEX_HOME:-$HOME/.codex}/skills"
35
+ cp -R skills/codex/zcode-agent "${CODEX_HOME:-$HOME/.codex}/skills/zcode-agent"
36
+ ```
37
+
38
+ Skills are discovered when a session starts, so open a new Codex session if `$zcode-agent` doesn't appear. The skill is selected automatically from its description, or explicitly with `$zcode-agent`.
39
+
40
+ Both skills assume `zcode-agent` is on `PATH` (`npm install -g zcode-agent`) and that `zcode-agent doctor` passes.
@@ -0,0 +1,169 @@
1
+ ---
2
+ name: zcode-agent
3
+ description: Delegate scoped implementation work to the zcode-agent CLI (cheap GLM-5.3-Flash executor: sees images, has Playwright; an independent vision verifier judges UI) and consume its compact verified handback. Use when you are orchestrating: you make the product, design and logic decisions once, then zcode-agent implements, tests, visually verifies and repairs — in one session with subagent units, several parallel sessions, or a dependency plan — while you spend tokens only on decisions and exceptions.
4
+ ---
5
+
6
+ # Operating zcode-agent as an executor
7
+
8
+ zcode-agent is a CLI execution engine. You decide; it builds. It implements a scoped task in its own session, runs your checks itself, has a fresh, independent vision verifier screenshot and judge UI when you ask, repairs failures within a budget, and returns a small structured handback.
9
+
10
+ **The point is cost.** Your tokens are the expensive ones; GLM-5.3-Flash's are cheap. Your tokens go to decisions and exceptions. Everything mechanical — writing code, running builds and tests, reading diffs, looking at screenshots, fixing small failures — is zcode-agent's. If you are doing any of that after dispatch, you are paying twice.
11
+
12
+ Check readiness once per machine: `zcode-agent doctor` (exit 3 → no key: the user runs `zcode-agent login` or sets `ZAI_API_KEY`; with the ZCode app installed its key, MCP servers and skills are used automatically). Don't run `--help` or a bare `zcode-agent status`: everything you need is here.
13
+
14
+ ## The workflow
15
+
16
+ 1. **Read** the codebase as much as you need to plan. This is the one phase where reading files is expected.
17
+ 2. **Decide** everything a user could see or a system depends on (checklists below). Write the decisions down once, as decisions — a file such as `docs/decisions.md` that sessions receive with `--decisions @file`.
18
+ 3. **Shape** the work: one session, one session with units, parallel sessions, or a plan (see Parallelizing).
19
+ 4. **Preflight** (optional): `--preflight` makes zcode-agent list every question it would otherwise guess; answer them all in one edit to the decisions file. It costs you a round trip, so use it only when your decisions have known gaps or the work is large and novel; skip it when the checklists below are fully covered.
20
+ 5. **Dispatch and wait** with `--detach` + `zcode-agent wait`, or `zcode-agent plan run` + `zcode-agent plan wait`.
21
+ 6. **Handle exceptions only.** `completed` → move on. Anything else → read only what the brief shows, answer or adjust in one line with `zcode-agent resume`.
22
+
23
+ ## Deciding: leave nothing open-ended
24
+
25
+ The executor implements binding decisions exactly and is told not to invent anything user-visible or behavioural. Gaps either block it (a round trip for you) or get the most conservative default. Close them up front.
26
+
27
+ **Front end:** palette (exact values), type families and scale, spacing scale, radii, iconography/illustration style; every section's layout and hierarchy at each breakpoint you care about; exact copy; component states (hover, focus, active, disabled, loading, empty, error); motion (what moves, property, distance, duration, easing, stagger, trigger, reduced-motion behaviour); accessibility (focus order, traps, labels, contrast floor); stack and libraries; performance budget.
28
+
29
+ **Back end / logic:** data shapes and storage keys; API routes, payloads, status codes and errors; validation rules (exact regexes, ranges); state machines (steps, transitions, what persists, what resets); auth and permissions; idempotency and retries; what is mocked vs real; side effects that are forbidden.
30
+
31
+ **Boundaries:** what the executor may choose freely (internal names, file structure, helpers) and what it must ask about.
32
+
33
+ Keep the decisions file dense: tables and one-line statements, no prose, no rationale the executor doesn't need (aim for a few thousand tokens for a one-page site). Write decisions as statements, not wishes: "Reveal: opacity 0→1 and translateY 16px→0, 400 ms, cubic-bezier(.2,.7,.2,1), 60 ms stagger, at 20% visibility; reduced motion: opacity only."
34
+
35
+ ## Parallelizing
36
+
37
+ Parallel work can cut wall time a lot, but it is optional: one well-specified session is always correct. Split only when the work really splits, and never at the cost of a session finishing without you. Two levels, cheapest first:
38
+
39
+ 1. **Units inside one session** (`--unit "name: objective [owns a,b]"`). The executor runs one subagent per unit and integrates the result. One engine, one verifier pass, shared context, no extra briefs for you to read. Use it when the pieces share decisions and context but write separate files: one page's sections, one module's functions, a component set.
40
+ 2. **Several sessions** (`--detach` each, then one `wait` on all ids), or a **plan** when there are dependencies. Each session is a separate executor with its own context, port, verifier and brief. Use it when the pieces are independent deliverables.
41
+
42
+ | the work | shape |
43
+ |---|---|
44
+ | one deliverable, small or tightly coupled | one session, no units |
45
+ | one deliverable with 3–6 separable parts that share decisions | one session + units |
46
+ | 2+ independent deliverables that own disjoint paths | parallel sessions |
47
+ | a shared base first (scaffold, schema, design tokens), then parallel features | a plan with `after` |
48
+
49
+ **Split only when all of these hold:**
50
+ - Every concurrent session (and every unit) owns disjoint paths. Overlap is refused (exit 7; `plan check` catches it).
51
+ - Shared files have one owner: `package.json`, lockfiles, router, app shell, global styles, config. Give them to a scaffold session that runs first and mounts a stub for every feature, so feature sessions need no wiring. A later session may `--touch` a shared file only for a tiny edit no running session owns.
52
+ - Dependencies are decided and installed up front, by one session. Parallel sessions must not add packages: concurrent installs race on the lockfile.
53
+ - No piece needs a decision another piece will make. Put every shared decision in the decisions file all sessions receive.
54
+ - Each piece is big enough to pay for itself: a session costs startup plus its own verifier round (minutes) on the critical path. A 5-minute fix is one session.
55
+
56
+ **Keep it bounded.** 2–4 concurrent sessions is the useful range; past that they contend for the GLM rate limit and the machine (each runs its own engine, MCP servers, builds and browser), and sessions beyond `ZAI_CODE_MAX_ACTIVE` (8) queue. Units: 2–6 per session.
57
+
58
+ **Keep the critical path short.** Each `after` stage waits for a whole session (tens of minutes). Prefer one wide stage over a chain. Integration, if you need one at all, is a small pass (cross-feature checks, fix only what breaks between features), not a rebuild.
59
+
60
+ Visual criteria cost a verifier round (minutes of Flash time on the critical path), so put them where finished UI is built. A scaffold of stubs gets checks only; an integration session gets only cross-cutting criteria (the whole page in order, anchors, the dialog opening from every button), not a re-check of what the feature sessions' verifiers already passed.
61
+
62
+ Parallel safety is automatic: each session gets `ZCODE_PORT`, `ZCODE_OUT`, `ZCODE_TMP` and `ZCODE_SESSION_ID`. Tell the first (scaffold) session to make dev-server ports, build output dirs and test artifacts honour them. zcode-agent keeps `.zcode/` and `.playwright-mcp/` out of git via the repo's local `.git/info/exclude`; you don't need to touch `.gitignore` for them.
63
+
64
+ Parallel sessions cost you nothing extra while they run: one background `wait` on all of them (or `plan wait`) is a single call, and you read one brief per session at the end.
65
+
66
+ ## The handoff
67
+
68
+ | field | flag | give it when |
69
+ |---|---|---|
70
+ | objective | positional text | always: the outcome, not the steps |
71
+ | decisions | `--decision "…"`, `--decisions @file` | always for anything user-visible or behavioural |
72
+ | checks | `--check "cmd"` | always: build, typecheck, tests, lint, greps — zcode-agent runs them itself |
73
+ | visual | `--visual "criterion"`, `--viewport WxH`, `--serve "cmd"` | any UI work: after the build, a fresh vision verifier serves on $ZCODE_PORT, waits for animations to finish, screenshots each viewport, quotes the text it can actually see, judges each criterion (plus "all intended text is readable"), and unmet ones go back to the implementer for repair. Phrase criteria as what must be visible: "hero headline 'Your money, simplified' is fully readable at 390 and 1440" |
74
+ | units | `--unit "name: objective [owns a,b]"` | one session should fan out to subagents (see Parallelizing) |
75
+ | owns | `--owns path/glob` | always when other sessions may run in the same repo; must be disjoint from every concurrent session |
76
+ | touch | `--touch path` | a small edit to a shared file no running session owns |
77
+ | files | `--file path` | files to read first (don't also pass them as `--context @`) |
78
+ | context | `--context "…"` / `--context @file` | background that isn't a decision |
79
+ | acceptance | `--accept "…"` | criteria beyond checks and visuals |
80
+ | everything | `--task contract.json` | keys: objective, scope, constraints, decisions, design, acceptance, checks, visual, viewports, units, files, references, context, owns, touch, limits, model, effort |
81
+
82
+ Environment: by default the executor gets the ZCode app's MCP servers and user skills (OAuth-only remote servers excluded) plus zcode-agent's own executor instructions; `--hermetic` gives it only your `--mcp` servers and `--skills`. Leave the default unless a run needs to be reproducible on another machine.
83
+
84
+ Model and effort: don't pass `--model`. Everything runs on GLM-5.3-Flash by default (it sees images): sessions, units, plans, the verifier. Use `--model glm-5.3` only when the user asks for it; it can't see images. `--effort low|high|max` (default `max`). Other values are refused before anything starts.
85
+
86
+ ## Running
87
+
88
+ ```sh
89
+ zcode-agent task --detach --id <id> --cwd <repo> [flags] "<objective>" # prints the id, returns at once
90
+ zcode-agent wait <id…> --timeout-ms 7000000 --json --quiet # in the background; 124 = still running: wait again
91
+ zcode-agent wait <id…> --any --timeout-ms 7000000 --json --quiet # return on the first that finishes
92
+ zcode-agent resume <id> "<answer or follow-up>" --detach # same session, context intact
93
+ zcode-agent result <id> [--full] # brief again, or the full record
94
+ zcode-agent cancel <id>
95
+ ```
96
+
97
+ Plans:
98
+
99
+ ```sh
100
+ zcode-agent plan check plan.json
101
+ zcode-agent plan run plan.json --detach [--preflight]
102
+ zcode-agent plan wait <name> --timeout-ms 7000000 --json # in the background; one line per session, details only for non-completed
103
+ zcode-agent plan resume <name> ["<message>"] # resume failed/partial, relaunch skipped
104
+ zcode-agent plan resume <name> --session <id> "<answer>" # answer one blocked session
105
+ ```
106
+
107
+ `plan.json`: `{"cwd"?, "decisions"?, "context"?, "files"?, "model"?, "effort"?, "limits"?, "sessions": [{"id", "after"?: [ids], "label"?, ...contract keys}]}`. Top-level decisions/context/files/limits go to every session; `@` entries resolve against the plan file's directory, then the plan's cwd. Don't also list the decisions file under `files`: it is already inlined. The plan name is the file basename (or `--id`). Sessions that can run at the same time must own disjoint paths; `plan check` enforces it. When an upstream session ends non-completed, its dependants are `skipped` until you `plan resume`.
108
+
109
+ Session ids are global and permanent: give every new run a fresh prefix (`wc3-scaffold`, …) so `plan check` passes first time. A task session may run 2 h by default; a big session (a whole page, a whole flow) can set `"limits": {"timeoutMs": 10800000}`. If one still times out, `zcode-agent plan resume <name> "continue"` picks up from the files it already wrote.
110
+
111
+ While sessions run, the user can watch them with `zcode-agent watch` (live phase, last tool, model requests, GLM cost so far, `STALLED?` after 8 idle minutes) and total a directory with `zcode-agent cost`; you never run either. `wait` timeout lines carry `idleMs`/`stalled`: a stalled session is the one case to `cancel` + `resume` early.
112
+
113
+ Wait once, in the background: run `zcode-agent plan wait <name> --timeout-ms 7000000 --json` (or `zcode-agent wait <id…> --timeout-ms 7000000 --json --quiet`) with Bash `run_in_background: true` and `timeout: 7200000`. You are re-invoked when it exits; do not poll in 9-minute foreground slices (each slice is a full-context Opus call). On exit 124, start one more background wait.
114
+
115
+ ## Reading the brief
116
+
117
+ `--json` prints one compact line: `status`, `summary`, `files`, failing `checks` with tails (`checksPassed` counts the rest), `questions`, `issues`, `unresolved`, `scopeViolations`, `touched`, the first `decisions` (`decisionsMore` counts the rest), unmet `visual` with what the verifier actually `seen` (`visualMet` is "met/total"), `units`, and `result` (path to the full record). Read it straight from the command output; don't pipe it through jq, python or tail.
118
+
119
+ | status | exit | do |
120
+ |---|---|---|
121
+ | `completed` | 0 | nothing. Skim `decisions` (the executor's own in-scope choices); veto with `resume` only if one is wrong |
122
+ | `blocked` | 10 | answer `questions` (they come with options and a recommendation) via `zcode-agent resume <id> "<answer>"`, and add the answer to your decisions file |
123
+ | `partial` | 8 | read `issues` / `unresolved` / unmet `visual` / `scopeViolations`; resume with one-line guidance or re-scope |
124
+ | `failed` | 8/5/124 | read the failing check `tail` or `error`; resume with guidance |
125
+ | `unverified` | 9 | you forgot checks: resume with a check added |
126
+ | `cancelled` | 130 | resume if wanted |
127
+
128
+ ## Hard rules after dispatch
129
+
130
+ - Don't open files a `completed` session changed. Don't re-run checks it ran. Don't look at its screenshots.
131
+ - Don't poll `status`; use `wait` (or `plan wait`) once, in the background if you like, and act on its exit.
132
+ - Don't fix code yourself; `resume` the session with one line.
133
+ - Need to know something about the result? `zcode-agent result <id> --full` first; read code only as a last resort.
134
+ - Don't ask zcode-agent to commit, push, publish or deploy unless the user asked; when they did, make it its own final session gated on everything else being `completed`.
135
+
136
+ ## Example: a marketing one-pager with an application form
137
+
138
+ You read the empty repo, decide the design system, copy, motion, form logic and demo constraints, and write `docs/decisions.md`. Then `plan.json`:
139
+
140
+ ```json
141
+ {
142
+ "decisions": ["@docs/decisions.md"],
143
+ "effort": "high",
144
+ "sessions": [
145
+ {"id": "scaffold", "owns": ["package.json", "package-lock.json", "index.html", "*.config.*", "tsconfig*.json", "src/app/**", "src/styles/**", "src/components/**", "e2e/smoke.spec.ts", ".gitignore"],
146
+ "objective": "Vite + React + TS scaffold, tokens, shared shell, stubs for src/landing and src/apply; dev/preview/e2e honour ZCODE_PORT and ZCODE_OUT",
147
+ "checks": ["npm run build", "npm test", "npm run e2e"]},
148
+ {"id": "landing", "after": ["scaffold"], "owns": ["src/landing/**", "e2e/landing.spec.ts"],
149
+ "objective": "All landing sections per the decisions",
150
+ "units": ["hero: …", "highlights: …", "products: …", "how: …", "charges: …", "faqs: …", "about-cta: …"],
151
+ "checks": ["npm run build", "npx playwright test e2e/landing.spec.ts"],
152
+ "visual": ["hero headline fits on two lines at 390px", "product cards align on one row at 1440px", "no text overlaps any circle motif"]},
153
+ {"id": "apply", "after": ["scaffold"], "owns": ["src/apply/**", "e2e/apply.spec.ts"],
154
+ "objective": "Application dialog: demo OTP, four steps, local draft, thank-you",
155
+ "checks": ["npm run build", "npm test -- apply", "npx playwright test e2e/apply.spec.ts"],
156
+ "visual": ["OTP code is visible on screen after entering a number", "step indicator shows the current step at 390px"]},
157
+ {"id": "integration", "after": ["landing", "apply"], "owns": ["src/App.tsx", "e2e/**"],
158
+ "objective": "Full-page pass across landing and apply: fix only what breaks between them",
159
+ "checks": ["npm run build", "npm test", "npm run e2e"],
160
+ "visual": ["every section heading is readable in page order at 390 and 1440", "the apply dialog opens readable from the hero and closing buttons"]}
161
+ ]
162
+ }
163
+ ```
164
+
165
+ `zcode-agent plan check plan.json` → `zcode-agent plan run plan.json --preflight` (read-only `<id>.pre` sessions, all at once; downstream sessions are told their upstream hasn't run yet; prints only the questions) → answer them once in the decisions file → `zcode-agent plan run plan.json --detach` → `zcode-agent plan wait plan --timeout-ms 7000000 --json` in the background. Your total involvement: the decisions, one answer pass, one summary.
166
+
167
+ ## Exit codes
168
+
169
+ 0 completed · 2 usage (bad flag, contract, plan, effort, or duplicate id) · 3 no key · 4 no engine · 5 failed · 6 `agent` had no subagent · 7 workspace conflict / session busy · 8 partial or checks failing · 9 unverified · 10 blocked · 124 timeout (for `wait`: still running) · 130 cancelled.