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