zcode-agent 0.0.0-stage → 1.0.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,530 @@
1
+ 'use strict';
2
+ // The task contract (handoff) and the handback.
3
+ //
4
+ // Handoff: an orchestrator describes the work as a small JSON object (or a
5
+ // markdown brief, or just flags). Only `objective` is required; everything
6
+ // else scales with the task. zcode renders it into the executor protocol
7
+ // prompt below.
8
+ //
9
+ // Handback: the model ends its final message with a fenced `zcode-handback`
10
+ // JSON block. That block is a CLAIM. The status zcode reports is derived
11
+ // from evidence zcode gathered itself (its own check runs, the workspace
12
+ // diff, the ownership scope) and only falls back on the claim for what
13
+ // cannot be checked mechanically — and says so in `notVerified`.
14
+
15
+ class ContractError extends Error {}
16
+
17
+ const CONTRACT_KEYS = [
18
+ 'objective',
19
+ 'scope',
20
+ 'constraints',
21
+ 'design',
22
+ 'decisions',
23
+ 'units',
24
+ 'visual',
25
+ 'viewports',
26
+ 'serve',
27
+ 'acceptance',
28
+ 'checks',
29
+ 'files',
30
+ 'references',
31
+ 'context',
32
+ 'owns',
33
+ 'touch',
34
+ 'limits',
35
+ 'model',
36
+ 'effort',
37
+ ];
38
+ const LIMIT_KEYS = ['timeoutMs', 'maxRepairs', 'checkTimeoutMs'];
39
+
40
+ const asList = (v) =>
41
+ v === undefined || v === null
42
+ ? []
43
+ : (Array.isArray(v) ? v : [v]).map((x) => String(x).trim()).filter(Boolean);
44
+
45
+ const uniq = (items) => [...new Set(items)];
46
+ const VIEWPORT_RE = /^\d{2,5}x\d{2,5}$/;
47
+ const DEFAULT_VIEWPORTS = ['390x844', '1440x900'];
48
+ const UNIT_KEYS = ['name', 'objective', 'owns'];
49
+
50
+ // "name: objective [owns a,b]" -> {name, objective, owns?}
51
+ function parseUnit(spec) {
52
+ const m = /^\s*([^:]+?)\s*:\s*([\s\S]*?)\s*(?:\[owns\s+([^\]]*)\])?\s*$/.exec(String(spec));
53
+ if (!m || !m[1].trim() || !m[2].trim()) {
54
+ throw new ContractError(`unit "${String(spec).slice(0, 60)}" must look like "name: objective" (optionally "[owns a,b]")`);
55
+ }
56
+ const owns = (m[3] || '').split(',').map((x) => x.trim()).filter(Boolean);
57
+ return { name: m[1].trim(), objective: m[2].trim(), ...(owns.length ? { owns } : {}) };
58
+ }
59
+
60
+ function normalizeUnits(items) {
61
+ const units = items.map((raw) => {
62
+ if (typeof raw === 'string') return parseUnit(raw);
63
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
64
+ throw new ContractError('contract "units" entries must be {name, objective, owns?} objects or "name: objective" strings');
65
+ }
66
+ const bad = Object.keys(raw).filter((k) => !UNIT_KEYS.includes(k));
67
+ if (bad.length) throw new ContractError(`unknown unit key(s): ${bad.join(', ')}. Accepted: ${UNIT_KEYS.join(', ')}`);
68
+ const name = String(raw.name ?? '').trim();
69
+ const objective = String(raw.objective ?? '').trim();
70
+ if (!name || !objective) throw new ContractError('every unit needs a name and an objective');
71
+ const owns = asList(raw.owns);
72
+ return { name, objective, ...(owns.length ? { owns } : {}) };
73
+ });
74
+ const seen = new Set();
75
+ for (const u of units) {
76
+ if (seen.has(u.name)) throw new ContractError(`duplicate unit name "${u.name}"`);
77
+ seen.add(u.name);
78
+ }
79
+ return units;
80
+ }
81
+
82
+ // Builds a contract from an optional base object (JSON file / markdown
83
+ // brief) plus CLI additions. Throws ContractError on unknown keys or a
84
+ // missing objective — before any engine spawn.
85
+ function normalizeContract(base = {}, additions = {}) {
86
+ if (!base || typeof base !== 'object' || Array.isArray(base)) {
87
+ throw new ContractError('task contract must be a JSON object');
88
+ }
89
+ const unknown = Object.keys(base).filter((k) => !CONTRACT_KEYS.includes(k));
90
+ if (unknown.length) {
91
+ throw new ContractError(
92
+ `unknown task contract key(s): ${unknown.join(', ')}. Accepted: ${CONTRACT_KEYS.join(', ')}`
93
+ );
94
+ }
95
+ const limits = base.limits || {};
96
+ if (typeof limits !== 'object' || Array.isArray(limits)) {
97
+ throw new ContractError('contract "limits" must be an object');
98
+ }
99
+ const badLimit = Object.keys(limits).filter((k) => !LIMIT_KEYS.includes(k));
100
+ if (badLimit.length) {
101
+ throw new ContractError(`unknown limits key(s): ${badLimit.join(', ')}. Accepted: ${LIMIT_KEYS.join(', ')}`);
102
+ }
103
+ for (const k of LIMIT_KEYS) {
104
+ if (limits[k] !== undefined && !(Number.isFinite(limits[k]) && limits[k] >= 0)) {
105
+ throw new ContractError(`contract limits.${k} must be a non-negative number`);
106
+ }
107
+ }
108
+ const viewports = uniq([...asList(base.viewports), ...asList(additions.viewports)]);
109
+ for (const v of viewports) {
110
+ if (!VIEWPORT_RE.test(v)) throw new ContractError(`viewport "${v}" must look like 390x844`);
111
+ }
112
+ const serve = String(additions.serve ?? base.serve ?? '').trim();
113
+ const objective = [String(base.objective ?? '').trim(), String(additions.objective ?? '').trim()]
114
+ .filter(Boolean)
115
+ .join('\n\n');
116
+ if (!objective) {
117
+ throw new ContractError('the task needs an objective (positional text, --task file, or "objective" in JSON)');
118
+ }
119
+ return {
120
+ objective,
121
+ scope: asList(base.scope),
122
+ constraints: asList(base.constraints),
123
+ design: asList(base.design),
124
+ decisions: uniq([...asList(base.decisions), ...asList(additions.decisions)]),
125
+ units: normalizeUnits([
126
+ ...(Array.isArray(base.units) ? base.units : base.units === undefined ? [] : [base.units]),
127
+ ...(additions.units || []),
128
+ ]),
129
+ visual: uniq([...asList(base.visual), ...asList(additions.visual)]),
130
+ viewports,
131
+ serve,
132
+ acceptance: uniq([...asList(base.acceptance), ...asList(additions.acceptance)]),
133
+ checks: [...asList(base.checks), ...asList(additions.checks)],
134
+ files: uniq([...asList(base.files), ...asList(additions.files)]),
135
+ references: asList(base.references),
136
+ context: uniq([...asList(base.context), ...asList(additions.context)]),
137
+ owns: [...asList(base.owns), ...asList(additions.owns)],
138
+ touch: [...asList(base.touch), ...asList(additions.touch)],
139
+ limits: { ...limits },
140
+ model: base.model ?? null,
141
+ effort: base.effort ?? null,
142
+ };
143
+ }
144
+
145
+ // --- prompts ------------------------------------------------------------------
146
+
147
+ const bullets = (items) => items.map((i) => `- ${i}`).join('\n');
148
+
149
+ function section(title, items) {
150
+ return items.length ? `## ${title}\n${bullets(items)}\n` : '';
151
+ }
152
+
153
+ const HANDBACK_SPEC = [
154
+ 'End your final message with exactly one fenced block in this form (valid JSON):',
155
+ '```zcode-handback',
156
+ '{"status": "done | partial | blocked",',
157
+ ' "summary": "one or two sentences: what you delivered",',
158
+ ' "changes": [{"path": "relative/path", "what": "short description"}],',
159
+ ' "checks": [{"what": "command or inspection you ran", "result": "pass | fail | not-run", "evidence": "short"}],',
160
+ ' "criteria": [{"criterion": "acceptance criterion", "met": true, "evidence": "short"}],',
161
+ ' "unresolved": ["problems inside your scope that remain unfixed"],',
162
+ ' "questions": ["what you need from the orchestrator (only when blocked)"],',
163
+ ' "decisions": [{"what": "choice you made in scope", "why": "short"}],',
164
+ ' "notes": "risks or follow-ups the orchestrator should know"}',
165
+ '```',
166
+ '"done" means every acceptance criterion is met and verified; "partial" means some work remains; "blocked" means you cannot proceed without the orchestrator.',
167
+ 'A question may be {"q": "...", "options": ["A ...", "B ..."], "recommend": "A"}.',
168
+ ].join('\n');
169
+
170
+ // Rendered on every task prompt, so it stays tiny (<= 400 bytes with
171
+ // realistic paths; scripts/measure.js budgets for it). `session` is
172
+ // {id, port, out, tmp}: the environment zcode gives the executor and the
173
+ // checks so parallel sessions cannot collide.
174
+ function sessionSection(session) {
175
+ if (!session) return '';
176
+ return [
177
+ '## Session environment',
178
+ 'Parallel sessions share this machine. Use these, never fixed values:',
179
+ `- ZCODE_PORT=${session.port}: the only port to bind (dev/preview servers)`,
180
+ `- ZCODE_OUT=${session.out}: build output dirs (e.g. --outDir) and test artifacts`,
181
+ `- ZCODE_TMP=${session.tmp}: scratch files`,
182
+ '',
183
+ ].join('\n');
184
+ }
185
+
186
+ function unitsSection(units) {
187
+ if (!units || !units.length) return '';
188
+ const lines = units.map((u) => `${u.name}: ${u.objective}${u.owns && u.owns.length ? ` (owns: ${u.owns.join(', ')})` : ''}`);
189
+ return `## Units\nDispatch each unit below to its own subagent (Agent tool) with that unit's objective, the binding decisions above and its owns. Run independent units in parallel, then integrate and verify the whole. Report each in handback \`units\`: [{"name", "status", "note"}].\n${bullets(lines)}\n`;
190
+ }
191
+
192
+ // Only rendered when the contract declares visual criteria. zcode itself
193
+ // decides `visual`: an independent image-capable verifier judges the result
194
+ // from its own screenshots after the work (lib/verify.js).
195
+ function visualSection(contract, { canSee = true } = {}) {
196
+ if (!contract.visual || !contract.visual.length) return '';
197
+ const viewports = contract.viewports && contract.viewports.length ? contract.viewports : DEFAULT_VIEWPORTS;
198
+ const serve = contract.serve
199
+ ? `- Make sure the app serves with \`${contract.serve}\` on $ZCODE_PORT (it must honour that port).`
200
+ : '- Make sure the app serves on $ZCODE_PORT (pick the dev/preview command from package.json; no other port).';
201
+ if (!canSee) {
202
+ return [
203
+ '## Visual verification',
204
+ 'You cannot see images. Do not judge screenshots or report `visual`; an independent vision verifier will.',
205
+ serve,
206
+ '- Self-check visibility in the DOM: key text must have a non-zero box inside the viewport, not clipped by an overflow ancestor, computed opacity > 0, visibility visible, after animations finish.',
207
+ `Viewports: ${viewports.join(', ')}. Criteria the verifier will judge:`,
208
+ bullets(contract.visual),
209
+ '',
210
+ ].join('\n');
211
+ }
212
+ return [
213
+ '## Visual verification',
214
+ 'An independent vision verifier judges these criteria from its own screenshots after you finish, and sends back anything unmet. Do not run your own screenshot rounds; one quick sanity pass is enough:',
215
+ serve,
216
+ `- Once the work is done, capture in ONE Playwright run-code call (browser_run_code_unsafe), not step by step: at each viewport (${viewports.join(', ')}) wait for fonts and animations, then save a viewport screenshot per window height (scrolling) and every key state a criterion names into $ZCODE_OUT/shots.`,
217
+ '- Read those PNGs in one parallel batch and fix what is clearly wrong. Stop the server when done.',
218
+ 'Criteria:',
219
+ bullets(contract.visual),
220
+ 'You may report handback `visual`: [{"criterion", "viewport", "met", "note", "shot"}]; it is not required.',
221
+ '',
222
+ ].join('\n');
223
+ }
224
+
225
+ const PREFLIGHT_SECTION = [
226
+ '## Preflight (read-only)',
227
+ 'This turn is a preflight, not the task. Make NO edits: do not create, modify or delete files, and run nothing with side effects. Read what you need, then list every open question you would otherwise have to guess (user-visible or behavioural choices the binding decisions and context do not settle) in handback `questions`, each as {"q": "...", "options": ["A ...", "B ..."], "recommend": "A"}. Report status "blocked" with those questions, or "done" with summary "no open questions" if there are none. The orchestrator will answer, then continue this session.',
228
+ '',
229
+ ].join('\n');
230
+
231
+ // `ownsDisplay` are the patterns as the caller wrote them (relative to cwd).
232
+ function buildTaskPrompt(contract, { ownsDisplay = contract.owns, session = null, preflight = false, canSeeImages = true } = {}) {
233
+ const parts = [
234
+ 'You are Zcode, an execution engine invoked by an orchestrator agent. The orchestrator owns product decisions, design direction, planning and task boundaries. You own implementation and verification inside the scope of this task. Work autonomously: there is no human watching and nobody reviews your intermediate steps.',
235
+ '',
236
+ `## Objective\n${contract.objective}\n`,
237
+ section('Scope', contract.scope),
238
+ section('Constraints', contract.constraints),
239
+ section('Binding decisions (made by the orchestrator: implement exactly)', [...(contract.decisions || []), ...contract.design]),
240
+ section('Relevant files (read these first)', contract.files),
241
+ section('References', contract.references),
242
+ section('Context', contract.context),
243
+ section('Acceptance criteria', contract.acceptance),
244
+ unitsSection(contract.units),
245
+ ownsDisplay.length
246
+ ? `## Workspace ownership\nYou may create, modify or delete ONLY these paths (relative to the working directory):\n${bullets(ownsDisplay)}\nOther sessions may be working in this workspace at the same time: do not touch anything else, and do not run formatters or code generators over the whole repository.\n`
247
+ : '',
248
+ contract.touch && contract.touch.length
249
+ ? `## Also allowed\nYou may also make minimal edits to:\n${bullets(contract.touch)}\nReport each such edit in your handback \`changes\`. Do not use this to widen the task.\n`
250
+ : '',
251
+ sessionSection(session),
252
+ visualSection(contract, { canSee: canSeeImages }),
253
+ preflight ? PREFLIGHT_SECTION : '',
254
+ contract.checks.length && !preflight
255
+ ? `## Acceptance checks\nAfter you finish, Zcode will run these commands in the working directory and treat any non-zero exit as a failure. Run them yourself before you finish:\n${bullets(contract.checks.map((c) => `\`${c}\``))}\n`
256
+ : '',
257
+ [
258
+ '## How to work',
259
+ '- Make routine implementation decisions yourself. Do not stop to ask for approval of intermediate steps.',
260
+ '- Decisions are made: don\'t re-weigh them or draft files in your reasoning. List short todos, then write files, batching tool calls.',
261
+ '- Where the binding decisions and context leave something user-visible or behavioural open, do not guess: if it blocks the work, report "blocked" with a structured question; otherwise take the most conservative choice and list it in handback `decisions`.',
262
+ '- Do not make product or design decisions the orchestrator has not made.',
263
+ '- You may use the Agent tool for independent units of work. Give each subagent a bounded objective and an explicit list of files it may change; never let two subagents change the same file. A subagent reporting success is a claim: inspect its changes and verify the integrated result yourself.',
264
+ '- Verify every acceptance criterion against the actual result. When something fails, diagnose and fix it, then verify again.',
265
+ '- Do not commit, push, publish, deploy, or cause other external side effects unless this task explicitly asks for it.',
266
+ '- Report "blocked" only when you lack information or authority that this task does not provide (for example a missing credential, a required change outside your ownership, or a consequential ambiguity).',
267
+ '',
268
+ ].join('\n'),
269
+ `## Handback\n${HANDBACK_SPEC}`,
270
+ ];
271
+ return parts.filter(Boolean).join('\n');
272
+ }
273
+
274
+ // `visual`: the verifier's unmet entries {criterion, viewport, seen, note, shot}.
275
+ function buildRepairPrompt(failures, { attempt, maxRepairs, visual = [] }) {
276
+ const blocks = failures.map((f) => {
277
+ const why = f.timedOut ? 'timed out' : `exit ${f.exitCode}`;
278
+ return `### \`${f.command}\` (${why})\n\`\`\`\n${f.output.trim().slice(-3000) || '(no output)'}\n\`\`\``;
279
+ });
280
+ const head = failures.length
281
+ ? `Zcode ran the acceptance checks and ${failures.length === 1 ? 'one failed' : `${failures.length} failed`} (repair attempt ${attempt} of ${maxRepairs}):`
282
+ : `An independent visual verifier, looking at screenshots of the running app, found criteria unmet (repair attempt ${attempt} of ${maxRepairs}).`;
283
+ const lines = [head, '', ...blocks];
284
+ if (visual.length) {
285
+ lines.push(
286
+ failures.length ? '' : null,
287
+ 'Visual criteria the verifier found unmet:',
288
+ ...visual.map((v) => {
289
+ const text = [
290
+ v.seen ? `saw: ${JSON.stringify(String(v.seen).slice(0, 300))}` : null,
291
+ v.note ? String(v.note).slice(0, 300) : null,
292
+ v.shot ? `shot: ${v.shot}` : null,
293
+ ].filter(Boolean).join(' | ');
294
+ return `- ${v.criterion || '(unnamed)'}${v.viewport ? ` @${v.viewport}` : ''}${text ? ` - ${text}` : ''}`;
295
+ }),
296
+ 'Fix the cause. Zcode will re-run the checks and the verifier will look again; its screenshots are the evidence, not DOM presence.'
297
+ );
298
+ }
299
+ lines.push(
300
+ '',
301
+ failures.length
302
+ ? 'Diagnose the root cause and fix it within your ownership, run the checks again yourself, then finish with a fresh zcode-handback block. If the failure is outside your scope or cannot be fixed, report status "partial" or "blocked" and explain why.'
303
+ : 'Finish with a fresh zcode-handback block. If a criterion cannot be met within your scope, report status "partial" or "blocked" and explain why.'
304
+ );
305
+ return lines.filter((l) => l !== null).join('\n');
306
+ }
307
+
308
+ const HANDBACK_REQUEST =
309
+ 'Your previous message did not end with a valid zcode-handback block. Do not redo any work. Reply with only the handback block describing the current state.\n\n' +
310
+ HANDBACK_SPEC;
311
+
312
+ function buildResumePrompt(message, { kind, portChange = null }) {
313
+ const note =
314
+ 'Work from earlier in this session is already applied to the workspace. Inspect the current state before repeating any step, and do not repeat external side effects.';
315
+ if (kind !== 'task') return message;
316
+ const body = message && message.trim()
317
+ ? `Message from the orchestrator:\n\n${message.trim()}`
318
+ : 'Continue the task from where you stopped.';
319
+ const env = portChange ? `\n\nZCODE_PORT is now ${portChange} (the previous port was taken); bind that one.` : '';
320
+ return `${body}\n\n${note}${env}\n\n${HANDBACK_SPEC}`;
321
+ }
322
+
323
+ // --- handback -------------------------------------------------------------------
324
+
325
+ const HANDBACK_RE = /```zcode-handback[^\n]*\n([\s\S]*?)```/g;
326
+ const STATUS_ALIASES = new Map([
327
+ ['done', 'done'],
328
+ ['complete', 'done'],
329
+ ['completed', 'done'],
330
+ ['success', 'done'],
331
+ ['partial', 'partial'],
332
+ ['incomplete', 'partial'],
333
+ ['failed', 'partial'],
334
+ ['blocked', 'blocked'],
335
+ ]);
336
+
337
+ const isObject = (v) => v && typeof v === 'object' && !Array.isArray(v);
338
+
339
+ // Plain-string questions stay strings; structured ones are {q, options?, recommend?}.
340
+ function question(q) {
341
+ if (!isObject(q) || typeof q.q !== 'string') return isObject(q) ? JSON.stringify(q) : String(q);
342
+ const options = Array.isArray(q.options) ? q.options.map(String) : [];
343
+ return {
344
+ q: q.q,
345
+ ...(options.length ? { options } : {}),
346
+ ...(q.recommend !== undefined && q.recommend !== null && q.recommend !== '' ? { recommend: String(q.recommend) } : {}),
347
+ };
348
+ }
349
+
350
+ const questionText = (q) => (typeof q === 'string' ? q : [q.q, ...(q.options || []).map((o) => ` - ${o}`), q.recommend ? ` recommend: ${q.recommend}` : null].filter(Boolean).join('\n'));
351
+
352
+ function decision(d) {
353
+ return isObject(d) ? { what: String(d.what ?? '').trim(), why: String(d.why ?? '').trim() } : { what: String(d ?? '').trim(), why: '' };
354
+ }
355
+
356
+ // Visual verdicts (zcode's verifier entries) against the declared criteria.
357
+ // `failed`: entries judged unmet (met:false); `unverified`: entries the
358
+ // verifier could not judge (met:null); `missing`: declared criteria no entry
359
+ // covers. Entries not met:true include the built-in readability criterion.
360
+ function visualGaps(entries, declared) {
361
+ const list = Array.isArray(entries) ? entries : [];
362
+ const norm = (x) => String(x || '').trim().toLowerCase();
363
+ const covered = (c) => list.some((v) => {
364
+ const a = norm(v.criterion);
365
+ return a && (a === norm(c) || a.includes(norm(c)) || norm(c).includes(a));
366
+ });
367
+ const label = (v) => `${v.criterion || '(unnamed)'}${v.viewport ? ` @${v.viewport}` : ''}`;
368
+ return {
369
+ missing: (declared || []).filter((c) => !covered(c)),
370
+ failed: list.filter((v) => v.met === false),
371
+ unverified: list.filter((v) => v.met === null).map(label),
372
+ };
373
+ }
374
+
375
+ // Strings for what is unmet: failed entries and declared criteria nobody judged.
376
+ function unmetVisual(entries, declared) {
377
+ const { missing, failed } = visualGaps(entries, declared);
378
+ return [...failed.map((v) => `${v.criterion || '(unnamed)'}${v.viewport ? ` @${v.viewport}` : ''}`), ...missing.map((c) => `${c} (not reported)`)];
379
+ }
380
+
381
+ // Returns {handback, report, error}: the LAST block wins; `report` is the
382
+ // response text with the block removed.
383
+ function parseHandback(text) {
384
+ const source = String(text || '');
385
+ const matches = [...source.matchAll(HANDBACK_RE)];
386
+ if (matches.length === 0) return { handback: null, report: source.trim(), error: 'missing' };
387
+ const last = matches[matches.length - 1];
388
+ const report = (source.slice(0, last.index) + source.slice(last.index + last[0].length)).trim();
389
+ let raw;
390
+ try {
391
+ raw = JSON.parse(last[1]);
392
+ } catch (err) {
393
+ return { handback: null, report, error: `invalid JSON: ${err.message}` };
394
+ }
395
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
396
+ return { handback: null, report, error: 'not a JSON object' };
397
+ }
398
+ const status = STATUS_ALIASES.get(String(raw.status || '').toLowerCase()) || null;
399
+ const arr = (v) => (Array.isArray(v) ? v : v ? [v] : []);
400
+ return {
401
+ handback: {
402
+ status,
403
+ summary: typeof raw.summary === 'string' ? raw.summary : '',
404
+ changes: arr(raw.changes),
405
+ checks: arr(raw.checks),
406
+ criteria: arr(raw.criteria),
407
+ unresolved: arr(raw.unresolved).map(String),
408
+ questions: arr(raw.questions).map(question),
409
+ decisions: arr(raw.decisions).map(decision).filter((d) => d.what),
410
+ units: arr(raw.units).filter(isObject),
411
+ visual: arr(raw.visual).filter(isObject),
412
+ notes: typeof raw.notes === 'string' ? raw.notes : '',
413
+ },
414
+ report,
415
+ error: status ? null : 'missing or unknown status',
416
+ };
417
+ }
418
+
419
+ // --- status ---------------------------------------------------------------------
420
+
421
+ // The single place the final status is decided.
422
+ // completed — zcode's own checks ran and all passed, the model reports
423
+ // done, no unmet criteria, nothing changed outside ownership
424
+ // unverified — the model reports done but zcode had no checks to run
425
+ // (or no usable handback): completion is self-reported
426
+ // partial — work remains: model says partial / criteria unmet /
427
+ // files changed outside ownership
428
+ // blocked — needs the orchestrator (questions in the result)
429
+ // failed — engine/turn error, timeout, or checks still failing after
430
+ // the repair budget
431
+ // cancelled — stopped by zcode cancel / a signal
432
+ function deriveStatus({
433
+ kind,
434
+ error = null,
435
+ cancelled = false,
436
+ userInput = null,
437
+ handback = null,
438
+ handbackError = null,
439
+ checks = [],
440
+ scopeViolations = [],
441
+ preflight = false,
442
+ preflightWrote = [],
443
+ visualDeclared = [],
444
+ visual = [],
445
+ }) {
446
+ const issues = [];
447
+ if (cancelled) return { status: 'cancelled', issues: ['cancelled before completion'] };
448
+ if (userInput) {
449
+ return { status: 'blocked', issues: [`the engine requested interactive input: ${userInput}`] };
450
+ }
451
+ if (error) return { status: 'failed', issues: [error.message || String(error)] };
452
+ if (kind !== 'task') return { status: 'completed', issues };
453
+
454
+ if (preflight) {
455
+ if (preflightWrote.length) {
456
+ return { status: 'failed', issues: [`preflight must be read-only but changed: ${preflightWrote.join(', ')}`] };
457
+ }
458
+ if (!handback) return { status: 'unverified', issues: [`no usable handback from the executor (${handbackError || 'missing'})`] };
459
+ if (handback.status === 'blocked' || handback.questions.length) {
460
+ return { status: 'blocked', issues: ['preflight found open questions (see questions)'] };
461
+ }
462
+ return { status: 'completed', issues };
463
+ }
464
+ if (handback && handback.status === 'blocked') {
465
+ return { status: 'blocked', issues: ['the executor reported it is blocked (see questions)'] };
466
+ }
467
+ const failedChecks = checks.filter((c) => !c.ok);
468
+ if (failedChecks.length) {
469
+ return {
470
+ status: 'failed',
471
+ issues: [`${failedChecks.length} of ${checks.length} acceptance check(s) failing: ${failedChecks.map((c) => c.command).join('; ')}`],
472
+ };
473
+ }
474
+ let partial = false;
475
+ if (handback && handback.status === 'partial') {
476
+ partial = true;
477
+ issues.push('the executor reported partial completion');
478
+ }
479
+ const unmet = handback ? handback.criteria.filter((c) => c && c.met === false) : [];
480
+ if (unmet.length) {
481
+ partial = true;
482
+ issues.push(`unmet acceptance criteria: ${unmet.map((c) => c.criterion).join('; ')}`);
483
+ }
484
+ if (handback && visualDeclared.length) {
485
+ const gaps = visualGaps(visual, visualDeclared);
486
+ const unmet = unmetVisual(visual, visualDeclared);
487
+ if (unmet.length) {
488
+ partial = true;
489
+ issues.push(`visual criteria unmet: ${unmet.join('; ')}`);
490
+ }
491
+ if (gaps.unverified.length) {
492
+ partial = true;
493
+ issues.push(`visual not verified: ${gaps.unverified.join('; ')}`);
494
+ }
495
+ }
496
+ if (scopeViolations.length) {
497
+ partial = true;
498
+ issues.push(`changed files outside the owned scope: ${scopeViolations.join(', ')}`);
499
+ }
500
+ if (partial) return { status: 'partial', issues };
501
+ if (!handback || handback.status !== 'done') {
502
+ issues.push(`no usable handback from the executor (${handbackError || 'missing'})`);
503
+ // Passing checks prove only the mechanical criteria; without a "done"
504
+ // report nobody has confirmed the rest.
505
+ return { status: 'unverified', issues };
506
+ }
507
+ if (!checks.length) {
508
+ issues.push('no acceptance checks were declared, so completion is self-reported by the executor');
509
+ return { status: 'unverified', issues };
510
+ }
511
+ return { status: 'completed', issues };
512
+ }
513
+
514
+ module.exports = {
515
+ ContractError,
516
+ sessionSection,
517
+ CONTRACT_KEYS,
518
+ DEFAULT_VIEWPORTS,
519
+ parseUnit,
520
+ questionText,
521
+ unmetVisual,
522
+ visualGaps,
523
+ normalizeContract,
524
+ buildTaskPrompt,
525
+ buildRepairPrompt,
526
+ buildResumePrompt,
527
+ HANDBACK_REQUEST,
528
+ parseHandback,
529
+ deriveStatus,
530
+ };