@cat-factory/executor-harness 1.106.0 → 1.110.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.
@@ -1,130 +1,22 @@
1
- import { mkdir, stat, writeFile } from 'node:fs/promises';
2
- import { join } from 'node:path';
3
- import { CONTEXT_DIR, excludeContextDir } from './pi.js';
1
+ import { CONTEXT_DIR } from './pi.js';
2
+ import { materializeContextImages } from './context-images.js';
4
3
  // ---------------------------------------------------------------------------
5
- // REFERENCE DESIGNS on disk: download the images the backend resolved for this task into
6
- // `.cat-context/reference-screenshots/`, the directory the UI-tester prompt has always named and
7
- // nothing wrote.
4
+ // REFERENCE DESIGNS on disk for a CAPTURING kind: the images a UI tester compares its own
5
+ // screenshots against, in `.cat-context/reference-screenshots/` the directory the UI-tester
6
+ // prompt has always named and nothing wrote.
8
7
  //
9
- // The harness MATERIALISES and never decides: which artifact is the reference for which view, and
10
- // what each file is called, are backend answers that ride the job body. What lives here is the
11
- // transfer and its failure reporting: a reference the container could not fetch is NAMED to the
12
- // agent rather than silently missing, because an absent file and a design that has no such screen
13
- // look identical on disk.
8
+ // The transfer itself lives in `context-images.ts`, shared with the design-picture delivery. What
9
+ // stays here is what makes this manifest a CAPTURE instruction: the directory, and the prompt block
10
+ // telling the tester to name each screenshot after the view it was handed, including the views it
11
+ // was handed no image for.
14
12
  // ---------------------------------------------------------------------------
15
13
  /** Subdirectory of {@link CONTEXT_DIR} the reference designs are written to. */
16
14
  export const REFERENCE_SCREENSHOT_SUBDIR = 'reference-screenshots';
17
- /** Per-image ceiling, matching the platform's own upload ceiling (16 MiB). */
18
- const MAX_REFERENCE_BYTES = 16 * 1024 * 1024;
19
- /** Per-image request timeout. */
20
- const REQUEST_TIMEOUT_MS = 20_000;
21
- /**
22
- * Wall-clock ceiling on the WHOLE pass.
23
- *
24
- * Downloading is activity-silent from the watchdog's point of view (no agent stream, no output),
25
- * and `JOB_INACTIVITY_MS` (10 min) is what kills a job that stops producing. Rather than heartbeat
26
- * a transfer that should take seconds, the pass is bounded far below that: a slow or wedged blob
27
- * backend costs the run its references (stated to the agent) instead of costing it the run.
28
- */
29
- const TOTAL_BUDGET_MS = 90_000;
30
- /** How many images are fetched at once. Small on purpose: this is a shared blob backend. */
31
- const CONCURRENCY = 4;
32
- /** The cause reported for a view the backend resolved but never sent this job a file for. */
33
- const OMITTED_REASON = 'not sent to this container (reference limit)';
34
15
  /** The relative directory the references are written to (what the prompt points the agent at). */
35
16
  export const REFERENCE_SCREENSHOT_DIR = `${CONTEXT_DIR}/${REFERENCE_SCREENSHOT_SUBDIR}`;
36
- /**
37
- * Download the manifest's images into the checkout and report what landed.
38
- *
39
- * IDEMPOTENT, and that is load-bearing rather than an optimisation: an agent flow re-enters its
40
- * workspace once per repair round, so this pass runs several times over one checkout. A file
41
- * already on disk is counted and never re-fetched, which keeps a later round from spending the
42
- * budget again AND from reporting a view as absent that pass 1 successfully delivered. A view that
43
- * MISSED is retried, since the next round is a fresh chance at whatever was transiently down.
44
- *
45
- * Never throws: references are an aid to a comparison, not a precondition for running, so a
46
- * backend outage degrades a UI run to "name your own views" (the documented fallback) rather than
47
- * failing it. Every miss is carried out on {@link ReferenceScreenshotOutcome.missing} so the caller
48
- * can say so in the prompt, which is the difference between a design the platform failed to hand
49
- * over and one that has no such screen.
50
- */
51
- export async function materializeReferenceScreenshots(cwd, spec, options = {}) {
52
- const dir = join(cwd, CONTEXT_DIR, REFERENCE_SCREENSHOT_SUBDIR);
53
- const outcome = {
54
- written: [],
55
- // The backend's own dropped views are missing before a single byte is fetched, and for a cause
56
- // no transfer could have changed.
57
- missing: spec.omitted.map((view) => ({ view, reason: OMITTED_REASON })),
58
- dir: REFERENCE_SCREENSHOT_DIR,
59
- };
60
- try {
61
- await mkdir(dir, { recursive: true });
62
- }
63
- catch (error) {
64
- // Nowhere to write: report every reference as missed rather than half of them, since none of
65
- // them can land and the cause is the same for all.
66
- for (const file of spec.files)
67
- outcome.missing.push({ view: file.view, reason: describe(error) });
68
- return sortByManifest(outcome, spec);
69
- }
70
- const deadline = Date.now() + TOTAL_BUDGET_MS;
71
- const queue = [...spec.files];
72
- const workers = Array.from({ length: Math.min(CONCURRENCY, queue.length) }, async () => {
73
- for (;;) {
74
- const file = queue.shift();
75
- if (!file)
76
- return;
77
- // An earlier pass over this same checkout already delivered it. Checked before the budget so
78
- // a fully-delivered set costs one stat per file and no network at all, however long an
79
- // earlier round took.
80
- if (await alreadyOnDisk(dir, file.fileName)) {
81
- outcome.written.push({ fileName: file.fileName, view: file.view });
82
- continue;
83
- }
84
- if (Date.now() >= deadline) {
85
- outcome.missing.push({ view: file.view, reason: 'reference download budget exhausted' });
86
- continue;
87
- }
88
- const failure = await downloadOne(dir, spec, file, options);
89
- if (failure)
90
- outcome.missing.push({ view: file.view, reason: failure });
91
- else
92
- outcome.written.push({ fileName: file.fileName, view: file.view });
93
- }
94
- });
95
- await Promise.all(workers);
96
- // Even a partial set must not reach the agent's PR (same rule as every other context file).
97
- await excludeContextDir(cwd);
98
- return sortByManifest(outcome, spec);
99
- }
100
- /**
101
- * Order both lists the way the BACKEND composed the set (its own gallery order) rather than the
102
- * order the transfers happened to finish in, so the list the agent reads is stable across rounds.
103
- * The dropped views trail the sent ones, having no position in the manifest to sort by.
104
- */
105
- function sortByManifest(outcome, spec) {
106
- const rank = new Map(spec.files.map((file, index) => [file.view, index]));
107
- const at = (view) => rank.get(view) ?? Number.MAX_SAFE_INTEGER;
108
- outcome.written.sort((a, b) => at(a.view) - at(b.view));
109
- outcome.missing.sort((a, b) => at(a.view) - at(b.view));
110
- return outcome;
111
- }
112
- /**
113
- * Whether a previous pass over this checkout already wrote this reference.
114
- *
115
- * Non-empty is the test, not mere existence: a zero-length file is what a half-written transfer
116
- * leaves behind, and treating it as delivered would hand the agent a blank image it reads as a
117
- * design with nothing on the screen (the same case {@link downloadOne} refuses to write).
118
- */
119
- async function alreadyOnDisk(dir, fileName) {
120
- try {
121
- return (await stat(join(dir, fileName))).size > 0;
122
- }
123
- catch {
124
- // silent-catch-ok: absence is the ordinary answer here (first pass over the checkout), and any
125
- // other stat failure is answered the same way — by attempting the download.
126
- return false;
127
- }
17
+ /** Download this job's capture references. See {@link materializeContextImages}. */
18
+ export function materializeReferenceScreenshots(cwd, spec, options = {}) {
19
+ return materializeContextImages(cwd, REFERENCE_SCREENSHOT_SUBDIR, spec, options);
128
20
  }
129
21
  /**
130
22
  * The whole delivery in one call: download the manifest (when there is one) and answer the prompt
@@ -148,84 +40,6 @@ export async function deliverReferenceScreenshots(cwd, spec, options) {
148
40
  }
149
41
  return referenceScreenshotGuidance(outcome);
150
42
  }
151
- /** Fetch and write one reference, answering a failure reason or undefined on success. */
152
- async function downloadOne(dir, spec, file, options) {
153
- const fetchImpl = options.fetchImpl ?? fetch;
154
- const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
155
- const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
156
- try {
157
- const response = await fetchImpl(`${spec.url}/${encodeURIComponent(file.artifactId)}`, {
158
- headers: { authorization: `Bearer ${spec.token}` },
159
- signal,
160
- });
161
- if (!response.ok)
162
- return `HTTP ${response.status}`;
163
- const bytes = await readBounded(response, MAX_REFERENCE_BYTES);
164
- if (bytes === 'too-large')
165
- return 'reference exceeds size limit';
166
- // A zero-length body is a miss, not a file: written out it would be an image the agent opens,
167
- // finds empty, and reads as a design with nothing on the screen.
168
- if (!bytes.byteLength)
169
- return 'empty response';
170
- await writeFile(join(dir, file.fileName), bytes);
171
- return undefined;
172
- }
173
- catch (error) {
174
- return describe(error);
175
- }
176
- }
177
- /**
178
- * Read a response body, refusing one that goes past `limit` WITHOUT buffering all of it first.
179
- *
180
- * The ceiling has to bound the transfer and not just the write. Buffering the whole body and then
181
- * measuring it means an oversized (or endless) response is already resident, times the pass's
182
- * concurrency, by the time it is rejected — which is the container's memory, in a run whose whole
183
- * point is that it has not started working yet. So the declared length is refused up front where
184
- * it is honest, and the stream is counted as it arrives and cancelled the moment it crosses the
185
- * line, which is what makes a chunked or lying body cost no more than a truthful one.
186
- */
187
- async function readBounded(response, limit) {
188
- const declared = Number(response.headers.get('content-length'));
189
- if (Number.isFinite(declared) && declared > limit)
190
- return 'too-large';
191
- const body = response.body;
192
- if (!body) {
193
- // No stream to count (a mocked or already-buffered response): fall back to measuring after the
194
- // fact, which is sound because there is nothing left to stop arriving.
195
- const bytes = new Uint8Array(await response.arrayBuffer());
196
- return bytes.byteLength > limit ? 'too-large' : bytes;
197
- }
198
- const reader = body.getReader();
199
- const chunks = [];
200
- let total = 0;
201
- try {
202
- for (;;) {
203
- const { done, value } = await reader.read();
204
- if (done)
205
- break;
206
- total += value.byteLength;
207
- if (total > limit) {
208
- await reader.cancel();
209
- return 'too-large';
210
- }
211
- chunks.push(value);
212
- }
213
- }
214
- finally {
215
- reader.releaseLock();
216
- }
217
- const bytes = new Uint8Array(total);
218
- let offset = 0;
219
- for (const chunk of chunks) {
220
- bytes.set(chunk, offset);
221
- offset += chunk.byteLength;
222
- }
223
- return bytes;
224
- }
225
- /** A one-line cause for a failed transfer (never the token, which only rides a header). */
226
- function describe(error) {
227
- return error instanceof Error ? error.message : String(error);
228
- }
229
43
  /**
230
44
  * The prompt block naming what the agent was handed, or '' when the pass produced nothing at all.
231
45
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cat-factory/executor-harness",
3
- "version": "1.106.0",
3
+ "version": "1.110.0",
4
4
  "description": "Container payload: a thin TypeScript wrapper that runs the Pi coding agent against a cloned repo and opens a PR. Runs in the Cloudflare Container (and, in local native mode, as a host process); carries no secrets.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -30,9 +30,9 @@
30
30
  "hono": "^4.13.1",
31
31
  "typescript": "7.0.2",
32
32
  "vitest": "^4.1.10",
33
- "@cat-factory/kernel": "0.279.2",
34
- "@cat-factory/server": "0.260.2",
35
- "@cat-factory/spend": "0.15.53"
33
+ "@cat-factory/kernel": "0.285.0",
34
+ "@cat-factory/server": "0.268.0",
35
+ "@cat-factory/spend": "0.15.64"
36
36
  },
37
37
  "scripts": {
38
38
  "build": "tsc -p tsconfig.json",
@@ -343,7 +343,7 @@ export function parseSkillSpecs(value: unknown): SkillSpec[] | undefined {
343
343
  * A member is added here in the SAME change that teaches the parser the field, never ahead of it:
344
344
  * the whole value of the list is that it is the image's own honest answer.
345
345
  */
346
- export const HARNESS_BODY_CAPABILITIES: readonly string[] = ['mcpServers', 'skills']
346
+ export const HARNESS_BODY_CAPABILITIES: readonly string[] = ['mcpServers', 'skills', 'designImages']
347
347
 
348
348
  /**
349
349
  * A safe MCP server id: it becomes a tool-name fragment AND a TOML table key.
@@ -1,10 +1,4 @@
1
- import type {
2
- AgentJob,
3
- AgentResult,
4
- McpServerSpec,
5
- ReferenceScreenshotsSpec,
6
- SkillSpec,
7
- } from './job.js'
1
+ import type { AgentJob, AgentResult, McpServerSpec, ImageManifestSpec, SkillSpec } from './job.js'
8
2
  import type { EffortReport } from './effort.js'
9
3
 
10
4
  // Small helpers shared by every agent MODE (explore / coding / bootstrap / preview). They live
@@ -33,11 +27,13 @@ export function mergeEffort(
33
27
  export function agentCapabilities(job: AgentJob): {
34
28
  skills?: SkillSpec[]
35
29
  mcpServers?: McpServerSpec[]
36
- referenceScreenshots?: ReferenceScreenshotsSpec
30
+ referenceScreenshots?: ImageManifestSpec
31
+ designImages?: ImageManifestSpec
37
32
  } {
38
33
  return {
39
34
  ...(job.skills?.length ? { skills: job.skills } : {}),
40
35
  ...(job.mcpServers?.length ? { mcpServers: job.mcpServers } : {}),
41
36
  ...(job.referenceScreenshots ? { referenceScreenshots: job.referenceScreenshots } : {}),
37
+ ...(job.designImages ? { designImages: job.designImages } : {}),
42
38
  }
43
39
  }
package/src/agent.ts CHANGED
@@ -30,7 +30,8 @@ import { inferVcsProvider, openPullRequest } from './vcs-api.js'
30
30
  import type { PiRunStats, RunDiagnostics } from './pi-reduction.js'
31
31
  import { applyPrDescription } from './pr-description.js'
32
32
  import { makeDirClaimer } from './checkout-dir.js'
33
- import { noChangesReason, runCodingAgent, runMultiRepoCoding } from './coding-agent.js'
33
+ import { noChangesReason, runCodingAgent } from './coding-agent.js'
34
+ import { runMultiRepoCoding } from './multi-repo-coding.js'
34
35
  import { validationFailureMessage } from './validation-checks.js'
35
36
  import { prepopulateDependencies, withDependencyNote } from './dependency-install.js'
36
37
  import { agentCapabilities, mergeEffort } from './agent-shared.js'