@chernabog/sdk 0.7.0 → 0.8.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/src/review.ts CHANGED
@@ -7,41 +7,51 @@
7
7
  // `address-review` is the author's side: it answers a review that asks for
8
8
  // changes in the session that wrote the code, and asks the reviewer again.
9
9
 
10
- import * as Effect from "effect/Effect";
11
- import * as Option from "effect/Option";
12
- import * as Schema from "effect/Schema";
13
-
14
- import { RECHECK } from "./default-prompts.ts";
15
- import { NeedsHuman, StepFailed } from "./errors.ts";
16
- import { activity } from "./flow.ts";
17
- import { sessionIdFor } from "./implement.ts";
18
- import type { Json } from "./json.ts";
19
- import {
20
- latestMarker,
21
- type ReviewMarker,
22
- reviewMarker,
23
- SessionMarker,
24
- sessionMarker,
25
- } from "./markers.ts";
26
- import { renderPrompt, renderPromptOr } from "./prompt.ts";
27
- import * as PullRequestSteps from "./pull-request.ts";
28
- import { adapterFor, type RoleOptions } from "./roles.ts";
29
10
  import {
11
+ activity,
12
+ adapterFor,
30
13
  Agent,
14
+ type DoctorCheck,
31
15
  Git,
32
16
  GitHub,
17
+ type Json,
18
+ latestMarker,
19
+ Machine,
20
+ NeedsHuman,
33
21
  type PullRequest,
34
22
  Repo,
35
23
  ReviewerSeat,
36
24
  type ReviewEvent,
25
+ type ReviewMarker,
26
+ reviewMarker,
37
27
  type ReviewNote,
28
+ type RoleOptions,
38
29
  Run,
30
+ SessionMarker,
31
+ sessionMarker,
32
+ StepFailed,
39
33
  type SubmittedReview,
40
34
  type WorkItem,
41
35
  Worktree,
42
- } from "./services.ts";
36
+ } from "@chernabog/core";
37
+ import * as Effect from "effect/Effect";
38
+ import * as Option from "effect/Option";
39
+ import * as Schema from "effect/Schema";
43
40
 
44
- export { type ReviewMarker, reviewMarker, type SessionMarker, sessionMarker } from "./markers.ts";
41
+ import { RECHECK } from "./default-prompts.ts";
42
+ import { ADOPTED_LABEL, sessionIdFor } from "./implement.ts";
43
+ import { renderPrompt, renderPromptOr } from "./prompt.ts";
44
+ import * as PullRequestSteps from "./pull-request.ts";
45
+ import * as Routing from "./routing.ts";
46
+ import * as Settings from "./settings.ts";
47
+ import { pullRequestValidity } from "./still-valid.ts";
48
+
49
+ export {
50
+ type ReviewMarker,
51
+ reviewMarker,
52
+ type SessionMarker,
53
+ sessionMarker,
54
+ } from "@chernabog/core";
45
55
 
46
56
  // Agent-written pull requests come from claim branches.
47
57
  export const isAgentBranch = (branch: string) => branch.startsWith("auto/");
@@ -65,6 +75,18 @@ const itemData =
65
75
 
66
76
  export const pullRequestOf = itemData(ReviewItem);
67
77
 
78
+ // Any work item on a pull request: review's, re-review's, address-review's,
79
+ // resolve-conflicts'.
80
+ const OnPullRequest = Schema.Struct({ pullRequest: Schema.Finite });
81
+
82
+ // Whether the pull request is still there to work on, for a flow's
83
+ // stillValid: it is open, and no other run holds its claim. A run whose pull
84
+ // request was closed or merged ends as superseded.
85
+ export const stillValid = (item: WorkItem) =>
86
+ itemData(OnPullRequest)(item).pipe(
87
+ Effect.flatMap(({ pullRequest }) => pullRequestValidity(pullRequest)),
88
+ );
89
+
68
90
  // A pull request as a work item, keyed by `key`, for a trigger to report.
69
91
  export const reviewItem = (pull: PullRequest, key: string): WorkItem => ({
70
92
  key,
@@ -75,10 +97,14 @@ export const reviewItem = (pull: PullRequest, key: string): WorkItem => ({
75
97
  headRef: pull.headRef,
76
98
  agentWritten: isAgentBranch(pull.headRef),
77
99
  },
78
- assignees: pull.assignees,
79
- reviewers: pull.requestedReviewers,
80
100
  });
81
101
 
102
+ // A work item of the pull request, left for others when the flow's routing
103
+ // (Routing's settings) says it isn't this persona's, by the pull request's
104
+ // assignees and requested reviewers.
105
+ export const routed = (pull: PullRequest, item: WorkItem) =>
106
+ Routing.route(item, { assignees: pull.assignees, reviewers: pull.requestedReviewers });
107
+
82
108
  // Whether a run of another flow owns the pull request, by its claim ref; the standalone flows leave it alone.
83
109
  export const ownedByARun = (pull: PullRequest) =>
84
110
  PullRequestSteps.owner(pull.number).pipe(Effect.map(Option.isSome));
@@ -117,6 +143,128 @@ export const reviewRequests = Effect.gen(function* () {
117
143
  return found;
118
144
  });
119
145
 
146
+ // Whether this machine acts as the login, among the logins it acts as.
147
+ const actsAs = (here: ReadonlyArray<string>, login: string) =>
148
+ here.some((own) => sameLogin(own, login));
149
+
150
+ // Open pull requests that wait on a review from a login no persona on this
151
+ // machine acts as, as work items that wait on those logins, for `chernabog
152
+ // status` to list: this persona's trigger never finds them, and another
153
+ // person's machine may serve them. One that asks this persona too is the
154
+ // trigger's own work. None from a binary that doesn't say which logins it
155
+ // acts as. It requires the persona's seat in the reviewer pool.
156
+ export const waitingElsewhere = Effect.gen(function* () {
157
+ const machine = yield* Effect.serviceOption(Machine);
158
+
159
+ if (Option.isNone(machine)) {
160
+ return [];
161
+ }
162
+
163
+ const me = yield* reviewerLogin;
164
+ const pulls = yield* (yield* GitHub).openPullRequests;
165
+
166
+ return pulls.flatMap((pull): ReadonlyArray<WorkItem> => {
167
+ if (pull.requestedReviewers.some((login) => sameLogin(login, me))) {
168
+ return [];
169
+ }
170
+
171
+ const others = pull.requestedReviewers.filter(
172
+ (login) => !actsAs(machine.value.personas, login),
173
+ );
174
+
175
+ if (others.length === 0) {
176
+ return [];
177
+ }
178
+
179
+ return [
180
+ {
181
+ ...reviewItem(pull, `pr-${pull.number}`),
182
+ waitsOn: { who: others.join(", "), why: "not on this machine" },
183
+ },
184
+ ];
185
+ });
186
+ });
187
+
188
+ // Doctor's check for a flow that reviews the pull requests asked of its
189
+ // persona, such as review: a persona that runs it holds a seat in the
190
+ // reviewer pool, since no pull request asks one that doesn't. Its presence
191
+ // also marks the flow as one that reviews, for the pool check of the flows
192
+ // that ask for reviews.
193
+ export const reviewerCheck: DoctorCheck = (context) =>
194
+ Effect.gen(function* () {
195
+ const { pool } = yield* Settings.reviewers;
196
+
197
+ const unseated = Option.filter(
198
+ context.login,
199
+ (login) => context.runs && pool.length > 0 && !actsAs(pool, login),
200
+ );
201
+
202
+ return Option.match(unseated, {
203
+ onNone: () => [],
204
+ onSome: (login) => [
205
+ {
206
+ warning: `${login} runs ${context.flow}, but the reviewer pool (${pool.join(", ")}) doesn't list it, so no pull request asks it to review`,
207
+ fix: `add ${login} to reviewers: in .chernabog/config.yaml, or turn ${context.flow} off for ${login}`,
208
+ },
209
+ ],
210
+ });
211
+ });
212
+
213
+ // Doctor's check for a flow that asks the reviewer pool to review its pull
214
+ // requests, such as implement: some reviewer the persona's pull requests may
215
+ // ask (the pool, less the persona) is a persona on this machine, and runs a
216
+ // flow that reviews here, one with reviewerCheck. A warning, since another
217
+ // person's machine may serve that login.
218
+ export const poolCheck: DoctorCheck = (context) =>
219
+ Effect.gen(function* () {
220
+ if (!context.runs) {
221
+ return [];
222
+ }
223
+
224
+ const { pool } = yield* Settings.reviewers;
225
+
226
+ const asked = pool.filter(
227
+ (login) => !Option.exists(context.login, (own) => sameLogin(own, login)),
228
+ );
229
+
230
+ if (asked.length === 0) {
231
+ return [];
232
+ }
233
+
234
+ const author = Option.getOrElse(context.login, () => "the implicit account");
235
+ const reviewers = asked.join(", ");
236
+
237
+ if (!asked.some((login) => actsAs(context.personas, login))) {
238
+ return [
239
+ {
240
+ warning: `pull requests authored as ${author} go to ${reviewers}, which this machine doesn't act as; they wait until another machine reviews them`,
241
+ fix: `run a flow that reviews, such as review, as one of ${reviewers} on this machine (chernabog setup, then chernabog enroll), or make sure another machine does`,
242
+ },
243
+ ];
244
+ }
245
+
246
+ const reviewing = context.flows.filter((flow) => flow.doctor.includes(reviewerCheck));
247
+
248
+ if (asked.some((login) => reviewing.some((flow) => actsAs(flow.runners, login)))) {
249
+ return [];
250
+ }
251
+
252
+ const flows = Option.getOrElse(
253
+ Option.liftPredicate(
254
+ reviewing.map((flow) => flow.name).join(", "),
255
+ (names) => names.length > 0,
256
+ ),
257
+ () => "such as review",
258
+ );
259
+
260
+ return [
261
+ {
262
+ warning: `pull requests authored as ${author} go to ${reviewers}, which no persona here reviews as: none of them runs a flow that reviews (${flows}) here`,
263
+ fix: `turn a flow that reviews on for one of ${reviewers} (chernabog enroll --persona <login> --flows ...), or make sure another machine reviews as them`,
264
+ },
265
+ ];
266
+ });
267
+
120
268
  export const Verdict = Schema.Struct({
121
269
  verdict: Schema.Literals(["approve", "request-changes"]),
122
270
  summary: Schema.String,
@@ -268,6 +416,7 @@ const reviewAndPost = (pullRequest: number, round: number, role: Option.Option<s
268
416
  Effect.gen(function* () {
269
417
  const github = yield* GitHub;
270
418
  const repo = yield* Repo;
419
+ const rules = yield* Settings.rules;
271
420
  const run = yield* Run;
272
421
  const pull = yield* github.pullRequest(pullRequest);
273
422
 
@@ -286,8 +435,8 @@ const reviewAndPost = (pullRequest: number, round: number, role: Option.Option<s
286
435
  base: pull.baseRef,
287
436
  round,
288
437
  earlier: earlier.map(describeNote),
289
- humanOnly: repo.humanOnly,
290
- notes: repo.notes,
438
+ humanOnly: rules.humanOnly,
439
+ notes: rules.notes,
291
440
  });
292
441
 
293
442
  const adapter = yield* adapterFor(role);
@@ -482,12 +631,17 @@ export const latestOwnReview = (pullRequest: number) =>
482
631
  Schema.Option(ReviewResult),
483
632
  );
484
633
 
485
- // Open pull requests this persona wrote.
634
+ // Open pull requests this persona wrote, and those it adopted for an issue
635
+ // they close (Implement.ADOPTED_LABEL, with the persona assigned).
486
636
  export const authoredByMe = Effect.gen(function* () {
487
637
  const github = yield* GitHub;
488
638
  const me = yield* github.login;
489
639
 
490
- return (yield* github.openPullRequests).filter((pull) => sameLogin(pull.author, me));
640
+ return (yield* github.openPullRequests).filter(
641
+ (pull) =>
642
+ sameLogin(pull.author, me) ||
643
+ (pull.labels.includes(ADOPTED_LABEL) && pull.assignees.some((login) => sameLogin(login, me))),
644
+ );
491
645
  });
492
646
 
493
647
  // The pull request's approvals and requests for changes, oldest first; comments don't count.
@@ -513,15 +667,19 @@ export const addressItem = (
513
667
  data: {
514
668
  pullRequest: pull.number,
515
669
  headRef: pull.headRef,
670
+ baseRef: pull.baseRef,
516
671
  agentWritten: isAgentBranch(pull.headRef),
517
672
  reviewer: review.author,
518
673
  reviewedSha: review.commitSha,
519
674
  },
520
- assignees: pull.assignees,
521
675
  });
522
676
 
677
+ // baseRef: the pull request's base, which a layer of a stack has as the
678
+ // layer below's branch. An item saved without it pushes against the repo's
679
+ // base branch.
523
680
  export const AddressItem = Schema.Struct({
524
681
  ...ReviewItem.fields,
682
+ baseRef: Schema.optionalKey(Schema.String),
525
683
  reviewer: Schema.String,
526
684
  reviewedSha: Schema.String,
527
685
  });
@@ -530,29 +688,31 @@ export type AddressItem = typeof AddressItem.Type;
530
688
 
531
689
  export const addressItemOf = itemData(AddressItem);
532
690
 
533
- // The author's session, from the marker the implement run left; a fresh one if there is none.
534
- export const authorSession = (pullRequest: number) =>
535
- activity(
536
- "find-author",
537
- Effect.gen(function* () {
538
- const github = yield* GitHub;
539
- const run = yield* Run;
540
- const repo = yield* Repo;
691
+ // The author's session, from the marker the implement run left; a fresh one
692
+ // for `purpose` if there is none. Outside an activity, for a block that reads
693
+ // it under a name of its own.
694
+ export const findAuthorSession = (pullRequest: number, purpose: string) =>
695
+ Effect.gen(function* () {
696
+ const github = yield* GitHub;
697
+ const run = yield* Run;
698
+ const repo = yield* Repo;
541
699
 
542
- const found = latestMarker(
543
- sessionMarker.read,
544
- (yield* github.comments(pullRequest)).map((comment) => comment.body),
545
- );
700
+ const found = latestMarker(
701
+ sessionMarker.read,
702
+ (yield* github.comments(pullRequest)).map((comment) => comment.body),
703
+ );
546
704
 
547
- return Option.getOrElse(found, () => ({
548
- adapter: repo.agent,
549
- sessionId: sessionIdFor(run.runId, "address-review"),
550
- issue: 0,
551
- branch: "",
552
- }));
553
- }),
554
- SessionMarker,
555
- );
705
+ return Option.getOrElse(found, (): SessionMarker => ({
706
+ adapter: repo.agent,
707
+ sessionId: sessionIdFor(run.runId, purpose),
708
+ issue: 0,
709
+ branch: "",
710
+ }));
711
+ });
712
+
713
+ // The author's session, from the marker the implement run left; a fresh one if there is none.
714
+ export const authorSession = (pullRequest: number) =>
715
+ activity("find-author", findAuthorSession(pullRequest, "address-review"), SessionMarker);
556
716
 
557
717
  // The author's worktree on the pull request's branch, brought up to date.
558
718
  export const prepareAuthorWorktree = (headRef: string) =>
@@ -607,7 +767,9 @@ export const changesAsked = (address: AddressItem) =>
607
767
  ReviewResult,
608
768
  );
609
769
 
610
- // Fails with NeedsHuman when the author committed nothing since the review.
770
+ // Fails with NeedsHuman when the author committed nothing since the review,
771
+ // or left edits it didn't commit, which the push would leave behind. Ignored
772
+ // files don't count, as `git status --porcelain` doesn't list them.
611
773
  export const checkChanged = (
612
774
  pullRequest: number,
613
775
  round: number,
@@ -617,22 +779,40 @@ export const checkChanged = (
617
779
  activity(
618
780
  `check-changed-${round}`,
619
781
  Effect.gen(function* () {
620
- if ((yield* (yield* Git).headSha(worktree)) === reviewedSha) {
782
+ const git = yield* Git;
783
+
784
+ if ((yield* git.headSha(worktree)) === reviewedSha) {
621
785
  return yield* new NeedsHuman({
622
786
  reason: `#${pullRequest}: the author agent committed nothing in answer to review ${round}`,
623
787
  });
624
788
  }
789
+
790
+ const uncommitted = (yield* git.run(["status", "--porcelain"], worktree))
791
+ .split("\n")
792
+ .filter((line) => line.trim().length > 0)
793
+ .map((line) => `\`${line.slice(3)}\``);
794
+
795
+ if (uncommitted.length > 0) {
796
+ return yield* new NeedsHuman({
797
+ reason: `#${pullRequest}: the author agent left changes it didn't commit in answer to review ${round}: ${uncommitted.join(", ")}`,
798
+ });
799
+ }
625
800
  }),
626
801
  );
627
802
 
803
+ // Says why on the pull request, and asks the reviewer to review again,
804
+ // outside an activity, for a block that asks under a name of its own.
805
+ export const requestAgain = (pullRequest: number, reviewer: string, said: string) =>
806
+ Effect.gen(function* () {
807
+ const github = yield* GitHub;
808
+ yield* github.comment(pullRequest, said);
809
+ yield* github.requestReviewers(pullRequest, [reviewer]);
810
+ });
811
+
628
812
  // Asks the reviewer who requested the changes to review again, which starts
629
813
  // their re-review.
630
814
  export const askAgain = (pullRequest: number, round: number, reviewer: string, summary: string) =>
631
815
  activity(
632
816
  `ask-again-${round}`,
633
- Effect.gen(function* () {
634
- const github = yield* GitHub;
635
- yield* github.comment(pullRequest, `Addressed review ${round}: ${summary}`);
636
- yield* github.requestReviewers(pullRequest, [reviewer]);
637
- }),
817
+ requestAgain(pullRequest, reviewer, `Addressed review ${round}: ${summary}`),
638
818
  );
package/src/routing.ts ADDED
@@ -0,0 +1,113 @@
1
+ // Whose work a persona's flow starts: a trigger routes each item it reports
2
+ // by the people on it, as GitHub's assignee: and review-requested: qualifiers
3
+ // do, and leaves the others for another persona or machine, saying why. The
4
+ // engine starts nothing it leaves, and `chernabog status` lists it with the
5
+ // reason. A flow can route by anything else, a label or a path, by setting
6
+ // the item's `elsewhere` itself.
7
+ //
8
+ // A repo sets the filters in .chernabog/config.yaml under
9
+ // `flows.<name>.settings`, and a person per persona in machine config:
10
+ // `assignee: ["@me", none]`, `reviewRequested: "@me"`. Until core's next major
11
+ // (ADR 0005), the binary also gives a flow the old `flows.<name>.assignee`
12
+ // and `reviewRequested` keys as these settings.
13
+
14
+ import { GitHub, type GitHubError, Settings as CoreSettings, type WorkItem } from "@chernabog/core";
15
+ import * as Effect from "effect/Effect";
16
+ import * as Option from "effect/Option";
17
+ import * as Schema from "effect/Schema";
18
+
19
+ // Who an item must be for: @me (the persona's GitHub login), a login, or none for nobody.
20
+ const Who = Schema.Union([Schema.String, Schema.Array(Schema.String)]);
21
+
22
+ const whoFor = (qualifier: string) =>
23
+ Schema.optionalKey(
24
+ Schema.OptionFromNullOr(Who).annotate({
25
+ description: `Start only work items whose ${qualifier} include one of these: @me for the persona's GitHub login, a login, or none for nobody. null clears the team's.`,
26
+ }),
27
+ );
28
+
29
+ export const Settings = Schema.Struct({
30
+ assignee: whoFor("assignees"),
31
+ reviewRequested: whoFor("requested reviewers"),
32
+ });
33
+
34
+ // The people on an item, as routing reads them: its assignees, and who is asked to review it.
35
+ export type People = {
36
+ readonly assignees?: ReadonlyArray<string>;
37
+ readonly reviewers?: ReadonlyArray<string>;
38
+ };
39
+
40
+ // A filter the flow's settings set; none when they leave it out, or clear it with null.
41
+ const listOf = (who: (typeof Settings.Type)["assignee"]) =>
42
+ Option.map(Option.flatten(Option.fromUndefinedOr(who)), (found): ReadonlyArray<string> =>
43
+ [found].flat(),
44
+ );
45
+
46
+ const lower = (login: string) => login.toLowerCase();
47
+
48
+ // Whether people match a filter: none for nobody, @me for the persona, or a
49
+ // login. Case-insensitive, as on GitHub.
50
+ const matches = (filter: ReadonlyArray<string>, people: ReadonlyArray<string>, me: string) =>
51
+ filter.some((who) => {
52
+ const wanted = lower(who);
53
+
54
+ if (wanted === "none") {
55
+ return people.length === 0;
56
+ }
57
+
58
+ if (wanted === "@me") {
59
+ return people.some((person) => lower(person) === lower(me));
60
+ }
61
+
62
+ return people.some((person) => lower(person) === wanted);
63
+ });
64
+
65
+ const named = (people: ReadonlyArray<string>) =>
66
+ Option.getOrElse(
67
+ Option.liftPredicate(people.join(", "), (text) => text.length > 0),
68
+ () => "none",
69
+ );
70
+
71
+ // Why the flow's routing leaves an item with these people for others, such as
72
+ // "assignee: alice"; none when it's this persona's. The persona's login is
73
+ // asked of GitHub only when a filter names @me.
74
+ export const leftFor = (
75
+ people: People,
76
+ ): Effect.Effect<Option.Option<string>, GitHubError, GitHub> =>
77
+ Effect.gen(function* () {
78
+ const own = yield* CoreSettings.read(Settings);
79
+
80
+ const filters = [
81
+ { label: "assignee", filter: listOf(own.assignee), people: people.assignees ?? [] },
82
+ {
83
+ label: "review requested",
84
+ filter: listOf(own.reviewRequested),
85
+ people: people.reviewers ?? [],
86
+ },
87
+ ].flatMap((one) => Option.toArray(Option.map(one.filter, (filter) => ({ ...one, filter }))));
88
+
89
+ if (filters.length === 0) {
90
+ return Option.none();
91
+ }
92
+
93
+ let me = "";
94
+
95
+ if (filters.some((one) => one.filter.some((who) => lower(who) === "@me"))) {
96
+ me = yield* GitHub.use((github) => github.login);
97
+ }
98
+
99
+ if (filters.every((one) => matches(one.filter, one.people, me))) {
100
+ return Option.none();
101
+ }
102
+
103
+ return Option.some(filters.map((one) => `${one.label}: ${named(one.people)}`).join("; "));
104
+ });
105
+
106
+ // The item, left for others when the flow's routing says it isn't this persona's.
107
+ export const route = (item: WorkItem, people: People) =>
108
+ Effect.map(leftFor(people), (why) =>
109
+ Option.match(why, {
110
+ onNone: () => item,
111
+ onSome: (elsewhere): WorkItem => ({ ...item, elsewhere }),
112
+ }),
113
+ );