@cat-factory/executor-harness 1.108.0 → 1.110.2

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,379 @@
1
+ import { mkdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { makeDirClaimer } from './checkout-dir.js';
4
+ import { branchAheadOfBase, branchHasCommitsSince, cloneExistingBranch, cloneRepo, commitTrackedEdits, createBranch, excludeFromGit, fetchReferenceBranches, headCommit, listUntrackedFiles, pushBranch, refreshFromBaseIfClean, remoteBranchExists, } from './git.js';
5
+ import { openPullRequest } from './vcs-api.js';
6
+ import { applyPrDescription, PR_DESCRIPTION_FILE, readPrDescription } from './pr-description.js';
7
+ import { runAgentInWorkspace, withWorkspace } from './pi-workspace.js';
8
+ import { log } from './logger.js';
9
+ import { prepopulateDependencies, withDependencyNote } from './dependency-install.js';
10
+ import { resolvePrTemplateNote, withPrTemplateNote, } from './pr-template.js';
11
+ import { noChangesReason } from './coding-agent.js';
12
+ /**
13
+ * Multi-repo coding (service-connections phase 3): clone the primary repo AND every connected
14
+ * peer repo as SIBLING checkouts under one workspace root, run the agent ONCE with its cwd at
15
+ * that root (so it makes the cross-service change coherently across all of them), then commit +
16
+ * push each repo that actually changed and open one PR per dirty repo. The task's own-service PR
17
+ * is reported as `prUrl`/`branch`; the peer PRs as `peerPullRequests`.
18
+ *
19
+ * Deliberately simpler than the single-repo {@link runCodingAgent} for the first cut: NO mid-run
20
+ * checkpoint pushes (an evicted multi-repo run re-clones on retry — the deterministic work branch
21
+ * still lets it resume any commits it managed to push at the end), NO warm-pool persistent
22
+ * checkout (always ephemeral), and NO follow-up sentinel streaming. It reuses the SAME dir-scoped
23
+ * git helpers, so the per-repo clone/commit/push/PR mechanics match the single-repo path exactly.
24
+ */
25
+ export async function runMultiRepoCoding(job, opts = {}) {
26
+ const logger = (opts.log ?? log).child({ kind: 'multi-repo', jobId: job.jobId });
27
+ const peers = job.peerRepos ?? [];
28
+ const references = job.referenceRepos ?? [];
29
+ const primaryWorkBranch = job.pushBranch ?? job.newBranch ?? job.branch;
30
+ // Assign the sibling directory per repo via the shared deterministic allocator
31
+ // (`owner__name__digest`, matching the backend prompt's `siblingCheckoutDir`), shared with the
32
+ // read-only explore fan-out.
33
+ const claimDir = makeDirClaimer();
34
+ const legs = [
35
+ {
36
+ repo: job.repo,
37
+ dirName: claimDir(job.repo),
38
+ dir: '',
39
+ cloneBranch: job.branch,
40
+ workBranch: primaryWorkBranch,
41
+ ghToken: job.ghToken,
42
+ ...(job.pr ? { pr: job.pr } : {}),
43
+ primary: true,
44
+ baseSha: '',
45
+ resumed: false,
46
+ },
47
+ ...peers.map((peer) => ({
48
+ repo: peer.repo,
49
+ dirName: claimDir(peer.repo),
50
+ dir: '',
51
+ cloneBranch: peer.repo.baseBranch,
52
+ // Coding peers always carry `newBranch` (the backend sets the shared work branch);
53
+ // fall back to the primary's for the type (read-only peers never reach this path).
54
+ workBranch: peer.newBranch ?? primaryWorkBranch,
55
+ ghToken: peer.ghToken ?? job.ghToken,
56
+ ...(peer.pr ? { pr: peer.pr } : {}),
57
+ ...(peer.frameIds?.length ? { frameIds: peer.frameIds } : {}),
58
+ primary: false,
59
+ baseSha: '',
60
+ resumed: false,
61
+ })),
62
+ // Read-only reference repos (doc-writer): cloned as siblings the agent reads but never writes.
63
+ // `workBranch` is set to the base only to satisfy the type — a read-only leg never branches or
64
+ // pushes (guarded by `readOnly` in both the clone and push phases below).
65
+ ...references.map((reference) => ({
66
+ repo: reference.repo,
67
+ dirName: claimDir(reference.repo),
68
+ dir: '',
69
+ cloneBranch: reference.repo.baseBranch,
70
+ workBranch: reference.repo.baseBranch,
71
+ ghToken: reference.ghToken ?? job.ghToken,
72
+ primary: false,
73
+ readOnly: true,
74
+ baseSha: '',
75
+ resumed: false,
76
+ })),
77
+ ];
78
+ return withWorkspace('multi', async (root) => {
79
+ // Clone (or resume) every sibling checkout under the workspace root and fetch the primary's
80
+ // reference branches. Mutates each leg's `dir`/`resumed`/`baseSha` in place.
81
+ await prepareMultiRepoCheckouts(root, legs, job, logger, opts);
82
+ // DEPENDENCY PREPOPULATION for the PRIMARY leg, exactly as the read-only multi-repo fan-out
83
+ // does it. The install is declared on ONE service frame (the primary repo's), so it runs in
84
+ // that leg's checkout and is never fanned out across peers, whose own frames declare configs
85
+ // this dispatch never resolved — running a `pnpm install` inside a Go checkout is not a
86
+ // degraded outcome, it is a wrong one. A cross-repo implementer needs its dependencies for
87
+ // the same reason a cross-repo investigator does; the note names the sibling directory
88
+ // because the agent itself stands at the workspace root.
89
+ //
90
+ // At the leg's checkout ROOT, not a `serviceDirectory` subtree: this layout applies no
91
+ // service-directory scoping anywhere (the agent runs at the root and the prompt explains the
92
+ // sibling checkouts), and a root install is the one that resolves a monorepo workspace whole.
93
+ const primaryLeg = legs.find((leg) => leg.primary);
94
+ const dependencyNote = primaryLeg
95
+ ? await prepopulateDependencies({
96
+ spec: job.dependencyInstall,
97
+ installDir: primaryLeg.dir,
98
+ repoDir: primaryLeg.dir,
99
+ agentDir: root,
100
+ logger,
101
+ opts,
102
+ })
103
+ : undefined;
104
+ // THE REPOS' OWN PR TEMPLATES: one per leg that will actually open a pull request, each named
105
+ // by its sibling directory so the agent knows which checkout's briefing takes which shape —
106
+ // the repos in a workspace need not share a template, or ship one at all. A read-only
107
+ // reference leg is excluded by construction: it carries no `pr`, so nothing publishes for it.
108
+ const prTemplate = await resolvePrTemplateNote({
109
+ targets: legs
110
+ .filter((leg) => leg.pr)
111
+ .map((leg) => ({
112
+ repoDir: leg.dir,
113
+ repoLabel: leg.dirName,
114
+ ...(leg.repo.provider ? { provider: leg.repo.provider } : {}),
115
+ })),
116
+ logger,
117
+ });
118
+ // Run the agent ONCE with its cwd at the workspace root, so it sees every sibling checkout
119
+ // and can change them coherently. No monorepo/service-directory scoping — the multi-repo
120
+ // note + the backend system-prompt section explain the layout.
121
+ opts.onPhase?.('agent');
122
+ logger.info('multi-repo: running agent', { repos: legs.map((l) => l.dirName) });
123
+ const { summary, stats, stderrTail, usage, callMetrics, effortReport } = await runAgentInWorkspace({
124
+ dir: root,
125
+ systemPrompt: job.systemPrompt,
126
+ userPrompt: withDependencyNote(withPrTemplateNote(job.userPrompt, prTemplate.note), dependencyNote),
127
+ model: job.model,
128
+ harness: job.harness,
129
+ subscriptionToken: job.subscriptionToken,
130
+ subscriptionBaseUrl: job.subscriptionBaseUrl,
131
+ ambientAuth: job.ambientAuth,
132
+ proxyBaseUrl: job.proxyBaseUrl,
133
+ proxyPhasePath: job.proxyPhasePath,
134
+ sessionToken: job.sessionToken,
135
+ webToolsGuidance: job.webToolsGuidance,
136
+ webSearchProxy: job.webSearch,
137
+ guardLimits: job.guardLimits,
138
+ ...(job.contextFiles ? { contextFiles: job.contextFiles } : {}),
139
+ // Skills + tool servers apply to a multi-repo run exactly as to a single-repo one: they
140
+ // are properties of the AGENT KIND, not of the checkout layout.
141
+ ...(job.skills?.length ? { skills: job.skills } : {}),
142
+ ...(job.mcpServers?.length ? { mcpServers: job.mcpServers } : {}),
143
+ ...(job.referenceScreenshots ? { referenceScreenshots: job.referenceScreenshots } : {}),
144
+ ...(job.designImages ? { designImages: job.designImages } : {}),
145
+ multiRepo: true,
146
+ }, opts);
147
+ // Commit forgotten tracked edits, then push + open a PR for each repo the run actually changed.
148
+ const { primaryPushed, primaryPrUrl, peerPullRequests } = await pushMultiRepoLegs(legs, job, logger, opts, root, prTemplate);
149
+ const anyWork = primaryPushed || peerPullRequests.length > 0;
150
+ if (!anyWork) {
151
+ // Nothing changed in ANY repo. For the implementer this is a failure (as in the
152
+ // single-repo path); a caller that tolerates a no-op (never the implementer today)
153
+ // gets a clean non-event.
154
+ if (job.noChangesIsError === false) {
155
+ return {
156
+ pushed: false,
157
+ branch: primaryWorkBranch,
158
+ summary,
159
+ stats,
160
+ ...(usage ? { usage } : {}),
161
+ ...(callMetrics ? { callMetrics } : {}),
162
+ ...(effortReport ? { effortReport } : {}),
163
+ };
164
+ }
165
+ return {
166
+ pushed: false,
167
+ branch: primaryWorkBranch,
168
+ summary,
169
+ stats,
170
+ error: noChangesReason('the agent produced no file changes in any repository', stats, stderrTail),
171
+ failureCause: 'no-changes',
172
+ ...(usage ? { usage } : {}),
173
+ ...(callMetrics ? { callMetrics } : {}),
174
+ ...(effortReport ? { effortReport } : {}),
175
+ };
176
+ }
177
+ logger.info('multi-repo: complete', {
178
+ primaryPushed,
179
+ primaryPrUrl: primaryPrUrl ?? null,
180
+ peers: peerPullRequests.length,
181
+ });
182
+ return {
183
+ pushed: primaryPushed,
184
+ ...(primaryPrUrl ? { prUrl: primaryPrUrl } : {}),
185
+ branch: primaryWorkBranch,
186
+ ...(peerPullRequests.length ? { peerPullRequests } : {}),
187
+ summary,
188
+ stats,
189
+ ...(usage ? { usage } : {}),
190
+ ...(callMetrics ? { callMetrics } : {}),
191
+ ...(effortReport ? { effortReport } : {}),
192
+ };
193
+ });
194
+ }
195
+ /**
196
+ * Clone phase for {@link runMultiRepoCoding}: every repo into its sibling dir under the workspace
197
+ * root. Resume an existing remote work branch (an evicted retry) rather than branching off base
198
+ * again, then fetch the primary repo's reference branches. Mutates each leg's `dir`/`resumed`/
199
+ * `baseSha` in place. Extracted so the multi-repo body stays small.
200
+ */
201
+ async function prepareMultiRepoCheckouts(root, legs, job, logger, opts) {
202
+ const { signal } = opts;
203
+ opts.onPhase?.('clone');
204
+ for (const leg of legs) {
205
+ const dir = join(root, leg.dirName);
206
+ await mkdir(dir, { recursive: true });
207
+ // A read-only reference leg: clone its base branch for the agent to read, and stop there —
208
+ // no work branch, no resume, no base-refresh. It is skipped in the push phase, so it can
209
+ // never be written to. (Kept in the loop so it lands in the same workspace root as siblings.)
210
+ if (leg.readOnly) {
211
+ logger.info('multi-repo: cloning read-only reference', {
212
+ repo: leg.dirName,
213
+ cloneBranch: leg.cloneBranch,
214
+ });
215
+ await cloneRepo({
216
+ repo: { ...leg.repo, baseBranch: leg.cloneBranch },
217
+ ghToken: leg.ghToken,
218
+ dir,
219
+ signal,
220
+ });
221
+ leg.dir = dir;
222
+ continue;
223
+ }
224
+ leg.resumed = await remoteBranchExists(leg.repo.cloneUrl, leg.workBranch, leg.ghToken, signal);
225
+ if (leg.resumed) {
226
+ logger.info('multi-repo: resuming existing branch', {
227
+ repo: leg.dirName,
228
+ branch: leg.workBranch,
229
+ });
230
+ await cloneExistingBranch({
231
+ cloneUrl: leg.repo.cloneUrl,
232
+ branch: leg.workBranch,
233
+ ghToken: leg.ghToken,
234
+ dir,
235
+ signal,
236
+ });
237
+ }
238
+ else {
239
+ logger.info('multi-repo: cloning', { repo: leg.dirName, cloneBranch: leg.cloneBranch });
240
+ await cloneRepo({
241
+ repo: { ...leg.repo, baseBranch: leg.cloneBranch },
242
+ ghToken: leg.ghToken,
243
+ dir,
244
+ signal,
245
+ });
246
+ await createBranch(dir, leg.workBranch, signal);
247
+ }
248
+ leg.dir = dir;
249
+ // Exclude the agent-authored PR-description sentinel locally (as the single-repo path does)
250
+ // so the agent's own `git add` can never stage the briefing into the PR it describes.
251
+ await excludeFromGit(dir, PR_DESCRIPTION_FILE, signal);
252
+ // The branch tip before the agent runs. Captured BEFORE the resume base refresh below so
253
+ // that refresh's merge commit counts as advancement and is pushed (as in the single-repo
254
+ // path). A fresh leg produced work iff its branch advances past this; a resumed leg already
255
+ // carries prior work.
256
+ leg.baseSha = await headCommit(dir, signal);
257
+ // A resumed branch was cut from an OLDER base; merge the latest base in when the two merge
258
+ // cleanly so the agent works against current base and the peer/own PRs stay current. On a
259
+ // conflict this is a best-effort no-op (the merge gate handles a conflicting PR downstream),
260
+ // mirroring the single-repo {@link runCodingAgent} resume refresh.
261
+ if (leg.resumed) {
262
+ const refreshed = await refreshFromBaseIfClean(dir, leg.cloneBranch, leg.ghToken, signal).catch(() => false);
263
+ if (!refreshed) {
264
+ logger.info('multi-repo: resume base refresh skipped (conflict or error)', {
265
+ repo: leg.dirName,
266
+ base: leg.cloneBranch,
267
+ });
268
+ }
269
+ }
270
+ }
271
+ // Reference branches attach to the PRIMARY repo, so fetch them into the primary sibling
272
+ // checkout's `origin/<b>` refs (best-effort per branch). The backend's reference-branches
273
+ // prompt section names the primary repo's directory to run the read commands in.
274
+ if (job.referenceBranches?.length) {
275
+ const primaryLeg = legs.find((l) => l.primary);
276
+ if (primaryLeg?.dir) {
277
+ const fetched = await fetchReferenceBranches({
278
+ dir: primaryLeg.dir,
279
+ branches: job.referenceBranches,
280
+ ghToken: primaryLeg.ghToken,
281
+ signal,
282
+ onSkip: (branch, reason) => logger.warn('multi-repo: reference branch fetch skipped', { branch, reason }),
283
+ });
284
+ logger.info('multi-repo: fetched reference branches', {
285
+ requested: job.referenceBranches.length,
286
+ fetched: fetched.length,
287
+ });
288
+ }
289
+ }
290
+ }
291
+ /**
292
+ * Push phase for {@link runMultiRepoCoding}: commit forgotten tracked edits, then push + open a PR
293
+ * for each repo the run actually changed (a repo the agent left untouched is skipped — no branch,
294
+ * no PR; a read-only reference leg is never committed or pushed). Extracted so the multi-repo body
295
+ * stays small; returns the primary's push/PR state plus the peer PRs.
296
+ */
297
+ async function pushMultiRepoLegs(legs, job, logger, opts,
298
+ /** The workspace root the agent ran in — the fallback probe for the primary's briefing. */
299
+ root,
300
+ /** Which legs' briefings are filled templates — see the `titleFromHeading` read below. */
301
+ prTemplate) {
302
+ const { signal } = opts;
303
+ opts.onPhase?.('push');
304
+ let primaryPushed = false;
305
+ let primaryPrUrl;
306
+ const peerPullRequests = [];
307
+ for (const leg of legs) {
308
+ // A read-only reference leg is never committed or pushed — the third layer of the read-only
309
+ // guarantee (the spec carries no branch/PR, and the clone phase gave it no work branch).
310
+ if (leg.readOnly)
311
+ continue;
312
+ // Lift (and remove) the agent-authored PR description for THIS repo's PR before anything
313
+ // else touches the checkout — each sibling checkout carries its own briefing for its own PR.
314
+ // The agent's cwd here is the WORKSPACE ROOT rather than any one checkout, so an agent that
315
+ // read the prompt loosely may well have written a single briefing there instead. Fall back
316
+ // to it for the PRIMARY leg only: at the root there is nothing to say which repo it
317
+ // describes, and the primary is the one the run is actually about.
318
+ //
319
+ // Per-leg `titleFromHeading`: only a leg whose OWN repo ships a template has repo-authored
320
+ // headings in its sentinel, and the legs of a workspace need not agree about that — so this
321
+ // is keyed on the leg, never on whether the run found any template at all.
322
+ const readOptions = { titleFromHeading: !prTemplate.templated.has(leg.dir) };
323
+ const agentPrDescription = (await readPrDescription(leg.dir, readOptions)) ??
324
+ (leg.primary ? await readPrDescription(root, readOptions) : undefined);
325
+ await commitTrackedEdits(leg.dir, job.commitMessage ?? leg.pr?.title ?? 'Agent changes', signal);
326
+ const advanced = await branchHasCommitsSince(leg.dir, leg.baseSha, signal);
327
+ let hasWork = advanced || leg.resumed;
328
+ if (leg.resumed && !advanced) {
329
+ const ahead = await branchAheadOfBase(leg.dir, leg.repo.baseBranch, leg.ghToken, signal);
330
+ if (ahead === false)
331
+ hasWork = false;
332
+ }
333
+ const leftover = await listUntrackedFiles(leg.dir, signal);
334
+ if (leftover.length > 0) {
335
+ logger.warn('multi-repo: uncommitted new files left behind (not pushed)', {
336
+ repo: leg.dirName,
337
+ count: leftover.length,
338
+ files: leftover.slice(0, 20),
339
+ });
340
+ }
341
+ if (!hasWork) {
342
+ logger.info('multi-repo: no changes for repo', { repo: leg.dirName });
343
+ continue;
344
+ }
345
+ await pushBranch(leg.dir, leg.workBranch, leg.ghToken, signal);
346
+ let prUrl = null;
347
+ if (leg.pr) {
348
+ prUrl = await openPullRequest({
349
+ owner: leg.repo.owner,
350
+ name: leg.repo.name,
351
+ ghToken: leg.ghToken,
352
+ head: leg.workBranch,
353
+ base: leg.repo.baseBranch,
354
+ pr: applyPrDescription(leg.pr, agentPrDescription),
355
+ // See the single-repo call site: refresh a resumed leg's already-open PR, but only
356
+ // when the text is the agent's own briefing rather than the dispatch-time fallback.
357
+ ...(agentPrDescription ? { refreshExisting: true } : {}),
358
+ apiBase: job.githubApiBase,
359
+ cloneUrl: leg.repo.cloneUrl,
360
+ ...(leg.repo.provider ? { provider: leg.repo.provider } : {}),
361
+ signal,
362
+ });
363
+ }
364
+ if (leg.primary) {
365
+ primaryPushed = true;
366
+ if (prUrl)
367
+ primaryPrUrl = prUrl;
368
+ }
369
+ else if (prUrl) {
370
+ peerPullRequests.push({
371
+ repo: `${leg.repo.owner}/${leg.repo.name}`,
372
+ ...(leg.frameIds?.length ? { frameIds: leg.frameIds } : {}),
373
+ prUrl,
374
+ branch: leg.workBranch,
375
+ });
376
+ }
377
+ }
378
+ return { primaryPushed, primaryPrUrl, peerPullRequests };
379
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cat-factory/executor-harness",
3
- "version": "1.108.0",
3
+ "version": "1.110.2",
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.284.0",
34
- "@cat-factory/server": "0.267.0",
35
- "@cat-factory/spend": "0.15.63"
33
+ "@cat-factory/kernel": "0.292.1",
34
+ "@cat-factory/server": "0.278.1",
35
+ "@cat-factory/spend": "0.15.80"
36
36
  },
37
37
  "scripts": {
38
38
  "build": "tsc -p tsconfig.json",
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'
@@ -49,6 +50,7 @@ import {
49
50
  diagnosticsSuffix,
50
51
  resolveStructuredOutput,
51
52
  } from './structured-output.js'
53
+ import { extractJsonObject } from './json-reply.js'
52
54
  import type { RunOptions } from './runner.js'
53
55
  import { log, type Logger } from './logger.js'
54
56
 
@@ -262,23 +264,6 @@ async function resolveReplyCustom(
262
264
  return { value: resolved.value, diagnostics: resolved.diagnostics }
263
265
  }
264
266
 
265
- /** Extract the first JSON object from an agent's final message (tolerating fences/prose). */
266
- function extractJsonObject(text: string): unknown {
267
- const trimmed = text.trim()
268
- const fenced = /^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(trimmed)
269
- const body = fenced ? (fenced[1] ?? '') : trimmed
270
- try {
271
- return JSON.parse(body)
272
- } catch {
273
- const start = body.indexOf('{')
274
- const end = body.lastIndexOf('}')
275
- if (start === -1 || end === -1 || end <= start) {
276
- throw new Error('agent did not return a JSON object')
277
- }
278
- return JSON.parse(body.slice(start, end + 1))
279
- }
280
- }
281
-
282
267
  /**
283
268
  * The service work directory for a checkout at `dir`: the monorepo service subtree
284
269
  * (`repo.serviceDirectory`, created if missing) when the job is service-scoped, else the clone