@chernabog/sdk 0.4.0 → 0.7.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.
package/src/prompt.ts CHANGED
@@ -1,50 +1,102 @@
1
1
  // Prompts are agent-neutral Markdown in .chernabog/prompts/, filled in with
2
- // {{name}} placeholders. A list renders as one `- ` line per item.
2
+ // {{name}} placeholders. A list renders as one `- ` line per item. An imported
3
+ // flow's prompts are looked up in layers: the repo's prompts/<name>.md first,
4
+ // then its package's, then the default the SDK carries, if any.
3
5
 
4
- import * as Effect from 'effect/Effect';
5
- import * as FileSystem from 'effect/FileSystem';
6
- import * as Option from 'effect/Option';
7
- import * as Predicate from 'effect/Predicate';
6
+ import * as Effect from "effect/Effect";
7
+ import * as FileSystem from "effect/FileSystem";
8
+ import * as Option from "effect/Option";
9
+ import * as Predicate from "effect/Predicate";
8
10
 
9
- import { StepFailed } from './errors.ts';
10
- import { Repo } from './services.ts';
11
+ import { StepFailed } from "./errors.ts";
12
+ import { FlowPackage, Repo } from "./services.ts";
11
13
 
12
14
  export type PromptValue = string | number | ReadonlyArray<string> | Option.Option<string>;
13
15
 
14
16
  const render = (value: PromptValue): string => {
15
- if (Option.isOption(value)) return Option.getOrElse(value, () => '');
17
+ if (Option.isOption(value)) {
18
+ return Option.getOrElse(value, () => "");
19
+ }
16
20
 
17
- if (Predicate.isString(value) || Predicate.isNumber(value)) return String(value);
21
+ if (Predicate.isString(value) || Predicate.isNumber(value)) {
22
+ return String(value);
23
+ }
18
24
 
19
- if (value.length === 0) return '- none';
25
+ if (value.length === 0) {
26
+ return "- none";
27
+ }
20
28
 
21
- return value.map((item) => `- ${item}`).join('\n');
29
+ return value.map((item) => `- ${item}`).join("\n");
22
30
  };
23
31
 
24
32
  export const fillTemplate = (template: string, values: Readonly<Record<string, PromptValue>>) =>
25
33
  template.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (placeholder, key: string) =>
26
- Option.match(Option.fromUndefinedOr(values[key]), { onNone: () => placeholder, onSome: render }),
34
+ Option.match(Option.fromUndefinedOr(values[key]), {
35
+ onNone: () => placeholder,
36
+ onSome: render,
37
+ }),
27
38
  );
28
39
 
29
- export const renderPrompt = (name: string, values: Readonly<Record<string, PromptValue>>) =>
40
+ // Where a prompt is looked for, in order: the repo, then the package an
41
+ // imported flow comes from.
42
+ const promptPaths = (name: string) =>
30
43
  Effect.gen(function* () {
31
44
  const repo = yield* Repo;
32
- const fs = yield* FileSystem.FileSystem;
33
- const path = `${repo.configDir}/prompts/${name}.md`;
34
- const template = yield* fs.readFileString(path).pipe(Effect.mapError(() => new StepFailed({ step: `prompt ${name}`, message: `no prompt at ${path}` })));
45
+ const flowPackage = yield* Effect.serviceOption(FlowPackage);
35
46
 
36
- return fillTemplate(template, values);
47
+ return [
48
+ `${repo.configDir}/prompts/${name}.md`,
49
+ ...Option.toArray(Option.map(flowPackage, (found) => `${found.dir}/prompts/${name}.md`)),
50
+ ];
37
51
  });
38
52
 
39
- // Like renderPrompt, from the default the SDK carries when the repo has no
40
- // .chernabog/prompts/<name>.md of its own.
41
- export const renderPromptOr = (name: string, fallback: string, values: Readonly<Record<string, PromptValue>>) =>
53
+ // The first of the prompt's layers that has it; none when no layer does.
54
+ const findPrompt = (name: string) =>
42
55
  Effect.gen(function* () {
43
- const repo = yield* Repo;
44
56
  const fs = yield* FileSystem.FileSystem;
45
- const path = `${repo.configDir}/prompts/${name}.md`;
46
57
 
47
- if (!(yield* fs.exists(path).pipe(Effect.orElseSucceed(() => false)))) return fillTemplate(fallback, values);
58
+ for (const path of yield* promptPaths(name)) {
59
+ if (yield* fs.exists(path).pipe(Effect.orElseSucceed(() => false))) {
60
+ return Option.some(path);
61
+ }
62
+ }
63
+
64
+ return Option.none<string>();
65
+ });
66
+
67
+ const readPrompt = (name: string, path: string) =>
68
+ FileSystem.FileSystem.use((fs) => fs.readFileString(path)).pipe(
69
+ Effect.mapError(
70
+ () => new StepFailed({ step: `prompt ${name}`, message: `no prompt at ${path}` }),
71
+ ),
72
+ );
73
+
74
+ export const renderPrompt = (name: string, values: Readonly<Record<string, PromptValue>>) =>
75
+ Effect.gen(function* () {
76
+ const found = yield* findPrompt(name);
77
+
78
+ if (Option.isNone(found)) {
79
+ const looked = (yield* promptPaths(name)).join(" or ");
80
+
81
+ return yield* new StepFailed({ step: `prompt ${name}`, message: `no prompt at ${looked}` });
82
+ }
83
+
84
+ return fillTemplate(yield* readPrompt(name, found.value), values);
85
+ });
86
+
87
+ // Like renderPrompt, from the default the SDK carries when neither the repo
88
+ // nor the flow's package has prompts/<name>.md.
89
+ export const renderPromptOr = (
90
+ name: string,
91
+ fallback: string,
92
+ values: Readonly<Record<string, PromptValue>>,
93
+ ) =>
94
+ Effect.gen(function* () {
95
+ const found = yield* findPrompt(name);
96
+
97
+ if (Option.isNone(found)) {
98
+ return fillTemplate(fallback, values);
99
+ }
48
100
 
49
- return yield* renderPrompt(name, values);
101
+ return fillTemplate(yield* readPrompt(name, found.value), values);
50
102
  });
@@ -1,81 +1,177 @@
1
- // Steps on a pull request that any flow can use, whichever flow opened it. A
2
- // flow that reviews and fixes a pull request itself owns it while it works, so
3
- // the standalone review and fix flows leave it alone.
4
-
5
- import * as Cause from 'effect/Cause';
6
- import * as Effect from 'effect/Effect';
7
- import * as Exit from 'effect/Exit';
8
- import * as Option from 'effect/Option';
9
- import * as Schema from 'effect/Schema';
10
-
11
- import { commentStep } from './comment.ts';
12
- import { NeedsHuman } from './errors.ts';
13
- import { activity } from './flow.ts';
14
- import { latestMarker, type OwnerMarker, ownerMarker, reviewMarker } from './markers.ts';
15
- import { pathsMatching } from './paths.ts';
16
- import { GitHub, type MergeMethod, Repo, Run, Runs } from './services.ts';
17
-
18
- const writeOwner = (name: string, pullRequest: number, released: boolean) =>
1
+ // Steps on a pull request that any flow can use, whichever flow opened it:
2
+ // asking the team's reviewer pool for a review, merging on the automated path,
3
+ // and handing it to a person. A flow that works on a pull request itself can
4
+ // own it while it does, so the standalone flows leave it alone.
5
+
6
+ import * as Cause from "effect/Cause";
7
+ import * as Effect from "effect/Effect";
8
+ import * as Exit from "effect/Exit";
9
+ import * as Option from "effect/Option";
10
+ import * as Random from "effect/Random";
11
+ import * as Schema from "effect/Schema";
12
+
13
+ import * as Claims from "./claims.ts";
14
+ import { commentStep } from "./comment.ts";
15
+ import { MergeRefused, NeedsHuman, PullRequestClosed, Skip } from "./errors.ts";
16
+ import { activity } from "./flow.ts";
17
+ import { latestMarker, type OwnerMarker, ownerMarker, reviewMarker } from "./markers.ts";
18
+ import { pathsMatching } from "./paths.ts";
19
+ import {
20
+ GitHub,
21
+ type Labels,
22
+ type MergeMethod,
23
+ type PullRequest,
24
+ Repo,
25
+ Run,
26
+ Runs,
27
+ } from "./services.ts";
28
+
29
+ // Marks the pull request as this run's: its claim ref, and a comment for people to read.
30
+ export const own = (pullRequest: number) =>
19
31
  activity(
20
- name,
32
+ `own-pr-${pullRequest}`,
21
33
  Effect.gen(function* () {
22
34
  const run = yield* Run;
23
- const marker = ownerMarker.write({ flow: run.flow, runId: run.runId, released });
35
+ const item = Claims.pullRequest(pullRequest);
36
+ const claimed = yield* Claims.acquire(item);
37
+
38
+ if (!claimed.acquired) {
39
+ return yield* new Skip({
40
+ reason: `#${pullRequest} is owned by another run (${Claims.describeHolder(item, claimed.holder)})`,
41
+ });
42
+ }
43
+
44
+ const marker = ownerMarker.write({
45
+ flow: run.flow,
46
+ runId: run.runId,
47
+ released: false,
48
+ ref: true,
49
+ });
24
50
 
25
- if (released) yield* (yield* GitHub).comment(pullRequest, `The \`${run.flow}\` run is done with this pull request. ${marker}`);
26
- else yield* (yield* GitHub).comment(pullRequest, `The \`${run.flow}\` run owns this pull request until it ends. ${marker}`);
51
+ yield* (yield* GitHub).comment(
52
+ pullRequest,
53
+ `The \`${run.flow}\` run owns this pull request until it ends. ${marker}`,
54
+ );
27
55
  }),
28
56
  );
29
57
 
30
58
  // Comments on the pull request, and does nothing else.
31
- export const comment = (pullRequest: number, body: string) => commentStep('pr', pullRequest, body);
32
-
33
- // Marks the pull request as this run's.
34
- export const own = (pullRequest: number) => writeOwner(`own-pr-${pullRequest}`, pullRequest, false);
59
+ export const comment = (pullRequest: number, body: string) => commentStep("pr", pullRequest, body);
35
60
 
36
61
  // Lets the pull request go, so the standalone flows pick it up again.
37
- export const release = (pullRequest: number) => writeOwner(`release-pr-${pullRequest}`, pullRequest, true);
62
+ export const release = (pullRequest: number) =>
63
+ activity(
64
+ `release-pr-${pullRequest}`,
65
+ Effect.gen(function* () {
66
+ const run = yield* Run;
67
+ yield* Claims.release(Claims.pullRequest(pullRequest));
68
+
69
+ const marker = ownerMarker.write({
70
+ flow: run.flow,
71
+ runId: run.runId,
72
+ released: true,
73
+ ref: true,
74
+ });
75
+
76
+ yield* (yield* GitHub).comment(
77
+ pullRequest,
78
+ `The \`${run.flow}\` run is done with this pull request. ${marker}`,
79
+ );
80
+ }),
81
+ );
38
82
 
39
83
  // Owns the pull request for as long as `effect` runs, and releases it however
40
- // that ends. A run waiting on a signal keeps it.
84
+ // that ends. A run waiting on a signal keeps it. A pull request another run
85
+ // owns is skipped.
41
86
  export const owning =
42
87
  (pullRequest: number) =>
43
88
  <A, E, R>(effect: Effect.Effect<A, E, R>) =>
44
89
  own(pullRequest).pipe(
45
- Effect.andThen(effect),
46
- // A wait suspends the run by interrupting it; that is not an ending.
47
- Effect.onExit((exit) => {
48
- if (Exit.isFailure(exit) && Cause.hasInterrupts(exit.cause)) return Effect.void;
90
+ Effect.andThen(
91
+ effect.pipe(
92
+ // A wait suspends the run by interrupting it; that is not an ending.
93
+ Effect.onExit((exit) => {
94
+ if (Exit.isFailure(exit) && Cause.hasInterrupts(exit.cause)) {
95
+ return Effect.void;
96
+ }
49
97
 
50
- return release(pullRequest).pipe(Effect.ignore);
51
- }),
98
+ return release(pullRequest).pipe(Effect.ignore);
99
+ }),
100
+ ),
101
+ ),
52
102
  );
53
103
 
104
+ // Whether this machine knows the run has ended; a run it never had, such as
105
+ // one on another machine, is taken to be going.
106
+ const knownEnded = (runId: string) =>
107
+ Effect.gen(function* () {
108
+ const runs = yield* Effect.serviceOption(Runs);
109
+
110
+ const active = yield* Option.match(runs, {
111
+ onNone: () => Effect.succeedNone,
112
+ onSome: (known) => known.isActive(runId),
113
+ });
114
+
115
+ return Option.contains(active, false);
116
+ });
117
+
54
118
  // The run that owns the pull request, from its comments: none once it let go,
55
119
  // or when this machine knows the run has ended.
56
120
  export const ownerOf = (bodies: ReadonlyArray<string>) =>
57
121
  Effect.gen(function* () {
58
- const latest = Option.filter(latestMarker(ownerMarker.read, bodies), (marker) => !marker.released);
59
-
60
- if (Option.isNone(latest)) return Option.none<OwnerMarker>();
122
+ const latest = Option.filter(
123
+ latestMarker(ownerMarker.read, bodies),
124
+ (marker) => !marker.released,
125
+ );
61
126
 
62
- const runs = yield* Effect.serviceOption(Runs);
63
- const active = yield* Option.match(runs, { onNone: () => Effect.succeedNone, onSome: (known) => known.isActive(latest.value.runId) });
127
+ if (Option.isNone(latest)) {
128
+ return Option.none<OwnerMarker>();
129
+ }
64
130
 
65
- if (Option.contains(active, false)) return Option.none<OwnerMarker>();
131
+ if (yield* knownEnded(latest.value.runId)) {
132
+ return Option.none<OwnerMarker>();
133
+ }
66
134
 
67
135
  return latest;
68
136
  });
69
137
 
138
+ export type Owner = { readonly flow: string; readonly runId: string };
139
+
140
+ // The run that owns the pull request: the holder of its claim ref, none when
141
+ // this machine knows that run has ended. Migration: while runs that owned a
142
+ // pull request by comment alone may be in flight, one with no claim ref falls
143
+ // back to the latest owner marker that names no ref (ownerOf). Drop the
144
+ // fallback a release after owners became claim refs.
145
+ export const owner = (pullRequest: number) =>
146
+ Effect.gen(function* () {
147
+ const held = yield* Claims.holder(Claims.pullRequest(pullRequest));
148
+
149
+ if (Option.isSome(held)) {
150
+ if (yield* knownEnded(held.value.runId)) {
151
+ return Option.none<Owner>();
152
+ }
153
+
154
+ return Option.some<Owner>({ flow: held.value.flow, runId: held.value.runId });
155
+ }
156
+
157
+ const bodies = (yield* (yield* GitHub).comments(pullRequest)).map((found) => found.body);
158
+ const legacy = yield* ownerOf(bodies);
159
+
160
+ return Option.map(
161
+ Option.filter(legacy, (marker) => marker.ref !== true),
162
+ (marker): Owner => ({ flow: marker.flow, runId: marker.runId }),
163
+ );
164
+ });
165
+
70
166
  export type MergeOptions = { readonly method: MergeMethod };
71
167
 
72
- const refuse = (pullRequest: number, reason: string) => new NeedsHuman({ reason: `#${pullRequest} not merged: ${reason}` });
168
+ const refuse = (pullRequest: number, reason: string) => new MergeRefused({ pullRequest, reason });
73
169
 
74
170
  // Merges the pull request, only when that is safe: it is open, its required
75
171
  // checks are green on the current head, the latest review approved that very
76
172
  // head, it touches no humanOnlyPaths, and GitHub's rules for the repo allow it.
77
- // Otherwise it fails with NeedsHuman, saying why. Nothing merges unless a flow
78
- // calls this.
173
+ // Otherwise it fails with MergeRefused, saying why, or PullRequestClosed for
174
+ // one closed without merging. Nothing merges unless a flow calls this.
79
175
  export const merge = (pullRequest: number, options: MergeOptions) =>
80
176
  activity(
81
177
  `merge-pr-${pullRequest}`,
@@ -85,36 +181,139 @@ export const merge = (pullRequest: number, options: MergeOptions) =>
85
181
  const pull = yield* github.pullRequest(pullRequest);
86
182
 
87
183
  // A rerun after a crash finds its own merge done.
88
- if (pull.state === 'merged') return `#${pullRequest} merged`;
184
+ if (pull.state === "merged") {
185
+ return `#${pullRequest} merged`;
186
+ }
89
187
 
90
- if (pull.state !== 'open') return yield* refuse(pullRequest, 'it is closed');
188
+ if (pull.state === "closed") {
189
+ return yield* new PullRequestClosed({ pullRequest, state: "closed" });
190
+ }
91
191
 
92
192
  const ci = yield* github.ciState(pullRequest);
93
193
 
94
- if (ci.state === 'red') return yield* refuse(pullRequest, `checks failed: ${ci.failedChecks.join(', ')}`);
194
+ if (ci.state === "red") {
195
+ return yield* refuse(pullRequest, `checks failed: ${ci.failedChecks.join(", ")}`);
196
+ }
95
197
 
96
- if (ci.state === 'pending') return yield* refuse(pullRequest, 'checks are still pending');
198
+ if (ci.state === "pending") {
199
+ return yield* refuse(pullRequest, "checks are still pending");
200
+ }
97
201
 
98
202
  const reviewed = latestMarker(
99
203
  reviewMarker.read,
100
204
  (yield* github.comments(pullRequest)).map((posted) => posted.body),
101
205
  );
102
206
 
103
- if (Option.isNone(reviewed)) return yield* refuse(pullRequest, 'it has no review');
104
-
105
- if (reviewed.value.sha !== pull.headSha) return yield* refuse(pullRequest, `the head moved to \`${pull.headSha.slice(0, 7)}\` since review ${reviewed.value.round} saw \`${reviewed.value.sha.slice(0, 7)}\``);
207
+ if (Option.isNone(reviewed)) {
208
+ return yield* refuse(pullRequest, "it has no review");
209
+ }
106
210
 
107
- if (reviewed.value.verdict !== 'approve') return yield* refuse(pullRequest, `review ${reviewed.value.round} requested changes`);
211
+ if (reviewed.value.sha !== pull.headSha) {
212
+ return yield* refuse(
213
+ pullRequest,
214
+ `the head moved to \`${pull.headSha.slice(0, 7)}\` since review ${reviewed.value.round} saw \`${reviewed.value.sha.slice(0, 7)}\``,
215
+ );
216
+ }
108
217
 
109
- const touched = pathsMatching(yield* github.pullRequestFiles(pullRequest), repo.humanOnlyPaths);
218
+ if (reviewed.value.verdict !== "approve") {
219
+ return yield* refuse(pullRequest, `review ${reviewed.value.round} requested changes`);
220
+ }
110
221
 
111
- if (touched.length > 0) return yield* refuse(pullRequest, `it touches paths a person must handle: ${touched.map((path) => `\`${path}\``).join(', ')}`);
222
+ const touched = pathsMatching(
223
+ yield* github.pullRequestFiles(pullRequest),
224
+ repo.humanOnlyPaths,
225
+ );
112
226
 
113
- const merged = yield* github.merge(pullRequest, { method: options.method, sha: pull.headSha });
227
+ if (touched.length > 0) {
228
+ return yield* refuse(
229
+ pullRequest,
230
+ `it touches paths a person must handle: ${touched.map((path) => `\`${path}\``).join(", ")}`,
231
+ );
232
+ }
114
233
 
115
- if (merged.status === 'refused') return yield* refuse(pullRequest, merged.reason);
234
+ const merged = yield* github.merge(pullRequest, {
235
+ method: options.method,
236
+ sha: pull.headSha,
237
+ });
116
238
 
117
239
  return `#${pullRequest} merged (${options.method}) as \`${merged.sha.slice(0, 7)}\``;
118
240
  }),
119
241
  Schema.String,
120
242
  );
243
+
244
+ const sameLogin = (left: string, right: string) => left.toLowerCase() === right.toLowerCase();
245
+
246
+ // Asks one reviewer from the team's pool (reviewers: in config) to review the
247
+ // pull request, never its author. The choice is made once, at random, in an
248
+ // activity, so a replay asks the same person. Without a pool, or with no one
249
+ // in it but the author, it labels the pull request needs-review for a person.
250
+ export const requestReview = (pullRequest: number) =>
251
+ activity(
252
+ `request-review-${pullRequest}`,
253
+ Effect.gen(function* () {
254
+ const github = yield* GitHub;
255
+ const repo = yield* Repo;
256
+ const pull = yield* github.pullRequest(pullRequest);
257
+ const pool = (repo.reviewers ?? []).filter((login) => !sameLogin(login, pull.author));
258
+
259
+ if (pool.length === 0) {
260
+ yield* github.addLabel(pullRequest, repo.labels.needsReview);
261
+
262
+ return `#${pullRequest}: no reviewer in the pool but its author; labelled ${repo.labels.needsReview} for a person`;
263
+ }
264
+
265
+ const reviewer = pool[yield* Random.nextIntBetween(0, pool.length, { halfOpen: true })];
266
+ yield* github.requestReviewers(pullRequest, [reviewer]);
267
+
268
+ return `#${pullRequest}: review requested of ${reviewer}`;
269
+ }),
270
+ Schema.String,
271
+ );
272
+
273
+ // Whether chernabog may merge the pull request: only on the automated path,
274
+ // one labelled ship (auto:ship). Anything else, a missing or misspelt label
275
+ // included, is left for a person to merge. The one place that decides it.
276
+ export const ships = (pull: PullRequest, labels: Labels) => pull.labels.includes(labels.ship);
277
+
278
+ // Labels the pull request needs-human and says why; no flow picks it up again
279
+ // until a person removes the label.
280
+ export const handToPerson = (pullRequest: number, reason: string) =>
281
+ activity(
282
+ `needs-human-pr-${pullRequest}`,
283
+ Effect.gen(function* () {
284
+ const github = yield* GitHub;
285
+ const repo = yield* Repo;
286
+ yield* github.addLabel(pullRequest, repo.labels.needsHuman);
287
+ yield* github.comment(pullRequest, `Chernabog stopped and needs a person: ${reason}`);
288
+ }),
289
+ ).pipe(Effect.andThen(Effect.fail(new NeedsHuman({ reason: `#${pullRequest}: ${reason}` }))));
290
+
291
+ // Whether chernabog may merge the pull request, as `ships` decides it,
292
+ // read once in an activity so a replay decides the same.
293
+ export const shipping = (pullRequest: number) =>
294
+ activity(
295
+ `ships-pr-${pullRequest}`,
296
+ Effect.gen(function* () {
297
+ const repo = yield* Repo;
298
+
299
+ return ships(yield* (yield* GitHub).pullRequest(pullRequest), repo.labels);
300
+ }),
301
+ Schema.Boolean,
302
+ );
303
+
304
+ // After an approval: on the automated path, merges the pull request when that
305
+ // is safe, and otherwise hands it to a person; any other pull request is left
306
+ // for a person to merge, and one closed meanwhile is left alone.
307
+ export const mergeOrLeave = (pullRequest: number) =>
308
+ Effect.gen(function* () {
309
+ if (!(yield* shipping(pullRequest))) {
310
+ return `#${pullRequest} approved; a person merges`;
311
+ }
312
+
313
+ return yield* merge(pullRequest, { method: "squash" }).pipe(
314
+ Effect.catchTags({
315
+ MergeRefused: (refused) => handToPerson(pullRequest, refused.message),
316
+ PullRequestClosed: (closed) => Effect.succeed(`${closed.message}; nothing to merge`),
317
+ }),
318
+ );
319
+ });