@chernabog/recipes 0.3.0 → 0.4.1

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.
package/flows/epic.ts CHANGED
@@ -16,6 +16,8 @@
16
16
  //
17
17
  // Each block is a durable activity from @chernabog/sdk, and a task's carry
18
18
  // its number (`implement#task-12`), so tasks in one run never share a step.
19
+ // Each task's id is its lane on the run's page, and the run declares the
20
+ // lanes each waited on (Lanes.declare), which the page draws as arrows.
19
21
  // Side effects belong inside activities or steps, never in the workflow body,
20
22
  // which runs again whenever the run resumes.
21
23
  //
@@ -33,6 +35,7 @@ import {
33
35
  Git,
34
36
  GitHub,
35
37
  Implement,
38
+ Lanes,
36
39
  Plan,
37
40
  PullRequest,
38
41
  Repo,
@@ -118,12 +121,13 @@ const releaseTask = (issue: number, id: string) =>
118
121
  // (Stack.updateFromBase): a squash or rebase of the layer below is recorded as
119
122
  // already here, so its review shows only the task's change, and its edits of
120
123
  // lines that layer added are no conflict. A merge that conflicts is undone and
121
- // left to resolve-conflicts, as any conflict with its base is.
124
+ // left to resolve-conflicts, as any conflict with its base is. `step` is
125
+ // `task-base#<id>`, or `task-base-2#<id>` when GitHub refused that base.
122
126
  const TaskBase = Schema.Struct({ base: Schema.String });
123
127
 
124
- const settleBase = (id: string, claimed: Option.Option<string>, worktree: string) =>
128
+ const settleBase = (step: string, claimed: Option.Option<string>, worktree: string) =>
125
129
  activity(
126
- `task-base#${id}`,
130
+ step,
127
131
  Effect.gen(function* () {
128
132
  const github = yield* GitHub;
129
133
  const integration = yield* Settings.base;
@@ -162,6 +166,20 @@ const settleBase = (id: string, claimed: Option.Option<string>, worktree: string
162
166
  TaskBase,
163
167
  );
164
168
 
169
+ // Whether the branch a task's pull request was refused on is gone, as the
170
+ // step `task-base-gone#<id>`: the layer below merged, and GitHub deleted its
171
+ // branch, between settleBase and the pull request (#320).
172
+ const baseGone = (id: string, base: string) =>
173
+ activity(
174
+ `task-base-gone#${id}`,
175
+ Effect.gen(function* () {
176
+ const github = yield* GitHub;
177
+
178
+ return Option.isNone(yield* github.branchSha(base));
179
+ }),
180
+ Schema.Boolean,
181
+ );
182
+
165
183
  // Implements one ready task as implement does, on its base, with its own
166
184
  // steps and session. A task that needs a person is handed to one, and lets
167
185
  // its claim go; the run carries on with the rest either way.
@@ -198,22 +216,65 @@ const implementTask = (
198
216
 
199
217
  return yield* Effect.gen(function* () {
200
218
  yield* Implement.localGate(worktree, { id, session });
201
- const settled = yield* settleBase(id, Option.fromUndefinedOr(base), worktree);
202
- yield* Implement.push(`push#${id}`, worktree, branch, { base: settled.base });
203
-
204
- const opened = yield* Implement.openPullRequest(issue, outcome, {
205
- base: settled.base,
206
- id,
207
- partOf: epic,
208
- ...(yield* queuedAs(ships)),
209
- });
219
+ const queued = yield* queuedAs(ships);
220
+
221
+ const pushAndOpen = (step: string, onBase: string, openId: string) =>
222
+ Effect.gen(function* () {
223
+ yield* Implement.push(`${step}#${id}`, worktree, branch, { base: onBase });
224
+
225
+ const opened = yield* Implement.openPullRequest(issue, outcome, {
226
+ base: onBase,
227
+ id: openId,
228
+ partOf: epic,
229
+ ...queued,
230
+ });
231
+
232
+ return { opened, base: onBase };
233
+ });
234
+
235
+ const settled = yield* settleBase(
236
+ `task-base#${id}`,
237
+ Option.fromUndefinedOr(base),
238
+ worktree,
239
+ );
240
+
241
+ // The layer below can merge, and its branch go, after its base is
242
+ // settled and before the pull request opens: GitHub then refuses the
243
+ // base. The base is settled again, on what that layer merged into,
244
+ // and the pull request opened there, once (#320).
245
+ const { base: openedOn, opened } = yield* pushAndOpen("push", settled.base, id).pipe(
246
+ Effect.catchTag("StepFailed", (refused) =>
247
+ Effect.gen(function* () {
248
+ if (
249
+ refused.step !== `open-pull-request#${id}` ||
250
+ !(yield* baseGone(id, settled.base))
251
+ ) {
252
+ return yield* refused;
253
+ }
254
+
255
+ const again = yield* settleBase(
256
+ `task-base-2#${id}`,
257
+ Option.some(settled.base),
258
+ worktree,
259
+ );
260
+
261
+ if (again.base === settled.base) {
262
+ return yield* refused;
263
+ }
264
+
265
+ // openPullRequest names its step `open-pull-request#<id>`
266
+ // alone, so the retry's id carries the round.
267
+ return yield* pushAndOpen("push-2", again.base, `${id}-base-2`);
268
+ }),
269
+ ),
270
+ );
210
271
 
211
272
  pullRequest = Option.some(opened.number);
212
273
 
213
274
  yield* Implement.waitForCi(
214
275
  opened.number,
215
276
  worktree,
216
- { ...session, branch, base: settled.base },
277
+ { ...session, branch, base: openedOn },
217
278
  { id },
218
279
  );
219
280
 
@@ -695,6 +756,45 @@ const land = (round: number, progress: Epic.Progress, upkeep: Upkeep) =>
695
756
  return moved;
696
757
  });
697
758
 
759
+ // Adds to `waitedOn` what each layer waits on as `progress` reads it: the
760
+ // sub-issues a held one waits on, and the one a stacked one is stacked on.
761
+ const noteWaits = (progress: Epic.Progress, waitedOn: Map<number, Set<number>>) => {
762
+ for (const layer of progress.layers) {
763
+ const on = [
764
+ ...(layer.waitsOn ?? []),
765
+ ...Option.toArray(Option.fromUndefinedOr(layer.stackedOn)),
766
+ ];
767
+
768
+ if (on.length > 0) {
769
+ waitedOn.set(layer.number, new Set([...(waitedOn.get(layer.number) ?? []), ...on]));
770
+ }
771
+ }
772
+ };
773
+
774
+ // The lanes of a task's attempts in this run so far, by the ids its steps
775
+ // carry (`task-12`, `task-12-2`): none for one it never started, as a person's.
776
+ const lanesOf = (task: number, attempts: ReadonlyMap<number, number>) =>
777
+ Array.from({ length: attempts.get(task) ?? 0 }, (_, index) => attemptId(task, index + 1));
778
+
779
+ // Declares the lane of a task's attempt for the run's page (Lanes.declare): it
780
+ // waited on the lanes of the tasks it waited on, and a later attempt on the
781
+ // one before it. Declaring it again, as a resumed run does, changes nothing.
782
+ const declareLane = (
783
+ task: number,
784
+ attempt: number,
785
+ waitedOn: ReadonlyMap<number, ReadonlySet<number>>,
786
+ attempts: ReadonlyMap<number, number>,
787
+ ) =>
788
+ Lanes.declare(attemptId(task, attempt), [
789
+ ...[...(waitedOn.get(task) ?? [])].flatMap((below) => lanesOf(below, attempts)),
790
+ ...Option.toArray(
791
+ Option.map(
792
+ Option.filter(Option.some(attempt), (count) => count > 1),
793
+ (count) => attemptId(task, count - 1),
794
+ ),
795
+ ),
796
+ ]);
797
+
698
798
  // Round after round: read where the epic stands, write its status comment,
699
799
  // carry each moved layer's change up its stack, land the layers that ship
700
800
  // and may, start every ready task, and
@@ -712,6 +812,8 @@ const workThrough = (epic: number, ships: boolean, concurrency: number) =>
712
812
  const handedBack = new Set<number>();
713
813
  // Tasks whose attempt ended with a person.
714
814
  const withPerson = new Set<number>();
815
+ // The sub-issues each task waited on, as the rounds read them.
816
+ const waitedOn = new Map<number, Set<number>>();
715
817
 
716
818
  const upkeep: Upkeep = {
717
819
  attempts: new Map(),
@@ -724,6 +826,7 @@ const workThrough = (epic: number, ships: boolean, concurrency: number) =>
724
826
  for (let round = 1; ; round++) {
725
827
  const progress = yield* Epic.progress(epic, round);
726
828
  yield* Epic.postStatus(epic, round, progress);
829
+ noteWaits(progress, waitedOn);
727
830
 
728
831
  if (Epic.finished(progress)) {
729
832
  return `#${epic}: every task is closed`;
@@ -762,6 +865,10 @@ const workThrough = (epic: number, ships: boolean, concurrency: number) =>
762
865
  return { task, attempt };
763
866
  });
764
867
 
868
+ for (const start of starts) {
869
+ yield* declareLane(start.task.number, start.attempt, waitedOn, attempts);
870
+ }
871
+
765
872
  yield* Effect.forEach(
766
873
  starts,
767
874
  (start) => implementTask(epic, start.task, start.attempt, ships, withPerson),
@@ -7,6 +7,13 @@
7
7
  // another flow waiting on the pull request's CI, such as implement's, carries
8
8
  // on from there.
9
9
  //
10
+ // A pull request whose layer below squash- or rebase-merged into its base,
11
+ // as one GitHub moved onto the base when the branch below it was deleted,
12
+ // would bring back with a plain merge what the base has since moved or
13
+ // deleted of that layer (#311). The flow records that layer's commits as
14
+ // already here first (Stack.mergedBelow and Stack.syncBase), and the agent
15
+ // resolves only what conflicts after that.
16
+ //
10
17
  // A pull request that was already approved goes back to its reviewer, whose
11
18
  // re-review merges it if it's on the automated path: review and re-review
12
19
  // leave an approved pull request that can't merge for a conflict to this flow
@@ -38,6 +45,7 @@ import {
38
45
  Run,
39
46
  Settings,
40
47
  Skip,
48
+ Stack,
41
49
  StepFailed,
42
50
  type WorkItem,
43
51
  } from "@chernabog/sdk";
@@ -122,10 +130,32 @@ const resolutionJsonSchema = {
122
130
  additionalProperties: false,
123
131
  } satisfies Json;
124
132
 
125
- // The agent merges the base into the branch and commits the merge, in its own session.
126
- const resolve = (conflict: ConflictItem, worktree: string, sessionId: string) =>
133
+ // What the agent is told of the merge: to make it, or that the flow left one
134
+ // in progress, with these conflicts, after recording the layer below.
135
+ type Merge = Option.Option<{ readonly lower: number; readonly conflicts: ReadonlyArray<string> }>;
136
+
137
+ const describeMerge = (base: string, merge: Merge) =>
138
+ Option.match(merge, {
139
+ onNone: () => `1. \`git fetch origin ${base}\`, then \`git merge --no-ff origin/${base}\`.`,
140
+ onSome: ({ conflicts, lower }) =>
141
+ [
142
+ `1. The merge is already started, and left in progress for you. #${lower}, the layer below this pull request, was squash- or rebase-merged into \`${base}\`, and Chernabog recorded its commits as already here, so a merge doesn't bring back what \`${base}\` has since moved or deleted of that layer. Resolve and commit the merge in progress; don't abort it, start another, or merge \`${base}\` yourself, which would undo that. Chernabog merges whatever of \`${base}\` is left. These files are in conflict:`,
143
+ "",
144
+ ...conflicts.map((path) => ` - ${path}`),
145
+ ].join("\n"),
146
+ });
147
+
148
+ // The agent merges the base into the branch and commits the merge, in its own
149
+ // session: `step` is "resolve", or "resolve-2" for a second merge the flow left it.
150
+ const resolve = (
151
+ conflict: ConflictItem,
152
+ worktree: string,
153
+ sessionId: string,
154
+ merge: Merge = Option.none(),
155
+ step = "resolve",
156
+ ) =>
127
157
  activity(
128
- "resolve",
158
+ step,
129
159
  Effect.gen(function* () {
130
160
  const repo = yield* Repo;
131
161
  const rules = yield* Settings.rules;
@@ -136,6 +166,7 @@ const resolve = (conflict: ConflictItem, worktree: string, sessionId: string) =>
136
166
  pullRequest: conflict.pullRequest,
137
167
  branch: conflict.headRef,
138
168
  base: conflict.baseRef,
169
+ merge: describeMerge(conflict.baseRef, merge),
139
170
  humanOnly: rules.humanOnly,
140
171
  notes: rules.notes,
141
172
  localGate: localGate.commands,
@@ -152,7 +183,7 @@ const resolve = (conflict: ConflictItem, worktree: string, sessionId: string) =>
152
183
 
153
184
  return yield* Schema.decodeUnknownEffect(Resolution)(result.output).pipe(
154
185
  Effect.mapError(
155
- (issue) => new StepFailed({ step: "resolve", message: `agent answer: ${issue.message}` }),
186
+ (issue) => new StepFailed({ step, message: `agent answer: ${issue.message}` }),
156
187
  ),
157
188
  );
158
189
  }),
@@ -181,6 +212,77 @@ const askApproverAgain = (pullRequest: number) =>
181
212
  Schema.Option(Schema.String),
182
213
  );
183
214
 
215
+ // Resolves the conflict, after recording a squash- or rebase-merged layer
216
+ // below as already here when there is one. That record is a merge the flow
217
+ // makes (Stack.syncBase), and the agent resolves what it leaves in progress.
218
+ // A conflict in the base before the layer below's commits stops it short:
219
+ // once the agent commits that, the flow merges again to finish, and the agent
220
+ // resolves what that leaves. With nothing left in conflict, no agent runs.
221
+ const resolveWithBelow = (conflict: ConflictItem, worktree: string, sessionId: string) =>
222
+ Effect.gen(function* () {
223
+ const below = yield* activity(
224
+ "merged-below",
225
+ Stack.mergedBelow(worktree, conflict.baseRef),
226
+ Schema.Option(Schema.Finite),
227
+ );
228
+
229
+ if (Option.isNone(below)) {
230
+ return yield* resolve(conflict, worktree, sessionId);
231
+ }
232
+
233
+ const lower = below.value;
234
+ const recorded = `Recorded #${lower}, the layer below as \`${conflict.baseRef}\` merged it, as already here.`;
235
+ const summaries: Array<string> = [recorded];
236
+
237
+ const round = (id: string, step: string) =>
238
+ Effect.gen(function* () {
239
+ const synced = yield* Stack.syncBase(worktree, { base: conflict.baseRef, lower, id }).pipe(
240
+ Effect.catchTag("NotFound", (gone) =>
241
+ Effect.fail(new StepFailed({ step: "update-from-base", message: gone.message })),
242
+ ),
243
+ );
244
+
245
+ if (synced.clean) {
246
+ return { synced, resolution: Option.none<typeof Resolution.Type>() };
247
+ }
248
+
249
+ const resolution = yield* resolve(
250
+ conflict,
251
+ worktree,
252
+ sessionId,
253
+ Option.some({ lower, conflicts: synced.conflicts }),
254
+ step,
255
+ );
256
+
257
+ return { synced, resolution: Option.some(resolution) };
258
+ });
259
+
260
+ const rounds = [yield* round("resolve", "resolve")];
261
+
262
+ if (
263
+ !rounds[0].synced.reconciled &&
264
+ Option.exists(rounds[0].resolution, (said) => said.status === "resolved")
265
+ ) {
266
+ rounds.push(yield* round("resolve-2", "resolve-2"));
267
+ }
268
+
269
+ for (const done of rounds) {
270
+ if (Option.isSome(done.resolution)) {
271
+ if (done.resolution.value.status === "needs-human") {
272
+ return done.resolution.value;
273
+ }
274
+
275
+ summaries.push(done.resolution.value.summary);
276
+ }
277
+ }
278
+
279
+ if (summaries.length === 1) {
280
+ summaries.push("Nothing else conflicted.");
281
+ }
282
+
283
+ return { status: "resolved", summary: summaries.join("\n\n") } satisfies typeof Resolution.Type;
284
+ });
285
+
184
286
  const unstick = (conflict: ConflictItem) =>
185
287
  Effect.gen(function* () {
186
288
  const run = yield* Run;
@@ -189,7 +291,7 @@ const unstick = (conflict: ConflictItem) =>
189
291
  const session = { sessionId: Option.some(sessionId), adapter: Option.none<string>() };
190
292
 
191
293
  const worktree = yield* Review.prepareAuthorWorktree(conflict.headRef);
192
- const resolution = yield* resolve(conflict, worktree, sessionId);
294
+ const resolution = yield* resolveWithBelow(conflict, worktree, sessionId);
193
295
 
194
296
  if (resolution.status === "needs-human") {
195
297
  return yield* new NeedsHuman({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chernabog/recipes",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "license": "MIT",
5
5
  "description": "Chernabog's recipes: complete flows a repo copies in, or imports, written from @chernabog/sdk",
6
6
  "repository": {
@@ -15,7 +15,8 @@
15
15
  "README.md"
16
16
  ],
17
17
  "peerDependencies": {
18
- "@chernabog/sdk": "^0.9.0"
18
+ "@chernabog/core": "^1.1.0",
19
+ "@chernabog/sdk": ">=0.10.0 <0.12.0"
19
20
  },
20
21
  "chernabog": {
21
22
  "recipes": {
@@ -4,7 +4,8 @@ You are running **unattended** in the worktree of branch `{{branch}}`, the head
4
4
 
5
5
  ## Steps
6
6
 
7
- 1. `git fetch origin {{base}}`, then `git merge --no-ff origin/{{base}}`.
7
+ {{merge}}
8
+
8
9
  2. Resolve each conflicted file so it keeps **both** sides' intent: the pull request's change, applied on top of what `{{base}}` now has. Read the pull request's own commits (`git log origin/{{base}}..HEAD`) and what changed on `{{base}}` since the branch was cut (`git log HEAD..origin/{{base}}`) to understand each side before choosing.
9
10
  3. Generated files are regenerated, never hand-merged. For a lockfile (`pnpm-lock.yaml`, `package-lock.json`, `bun.lock`, `yarn.lock`), take `{{base}}`'s version (`git checkout --theirs <lockfile>`), then rerun the pull request's dependency change on top of it with the package manager, for example the same `pnpm update …` or `pnpm add …` its commits describe. Then check the install is reproducible (`pnpm install --frozen-lockfile`, or the equivalent).
10
11
  4. Make sure nothing is left: no conflict markers (`git diff --check`, and `grep -rn '^<<<<<<< \|^>>>>>>> '` over the files that conflicted), and `git status` shows no unmerged paths.