@chernabog/sdk 0.10.0 → 0.11.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/block.ts ADDED
@@ -0,0 +1,466 @@
1
+ // What a block is, and the values blocks pass each other, each typed by what it
2
+ // means. See blocks.ts for the blocks.
3
+
4
+ import {
5
+ activity,
6
+ describeError,
7
+ type DoctorCheck,
8
+ type FlowError,
9
+ type FlowLabel,
10
+ type Json,
11
+ NeedsHuman,
12
+ NothingCommitted,
13
+ type Repo,
14
+ Skip,
15
+ StepFailed,
16
+ StepRunner,
17
+ type TriggeredFlow,
18
+ } from "@chernabog/core";
19
+ import * as Brand from "effect/Brand";
20
+ import * as Effect from "effect/Effect";
21
+ import * as Option from "effect/Option";
22
+ import * as Record from "effect/Record";
23
+ import * as Schema from "effect/Schema";
24
+
25
+ import * as Implement from "./implement.ts";
26
+ import type { FlowSettings } from "./settings.ts";
27
+
28
+ // What a scope's failures can tell a person beyond why: what the run got to.
29
+ export type FailureContext = { pr: Option.Option<PullRequestNumber> };
30
+
31
+ export type IssueNumber = number & Brand.Brand<"IssueNumber">;
32
+
33
+ export const IssueNumber = Brand.nominal<IssueNumber>();
34
+
35
+ export type PullRequestNumber = number & Brand.Brand<"PullRequestNumber">;
36
+
37
+ export const PullRequestNumber = Brand.nominal<PullRequestNumber>();
38
+
39
+ export type BranchName = string & Brand.Brand<"BranchName">;
40
+
41
+ export const BranchName = Brand.nominal<BranchName>();
42
+
43
+ export type BaseBranch = string & Brand.Brand<"BaseBranch">;
44
+
45
+ export const BaseBranch = Brand.nominal<BaseBranch>();
46
+
47
+ export type WorktreePath = string & Brand.Brand<"WorktreePath">;
48
+
49
+ export const WorktreePath = Brand.nominal<WorktreePath>();
50
+
51
+ // That the agent committed its work, that a branch was pushed, and that a
52
+ // review approved.
53
+ export class Committed extends Schema.TaggedClass<Committed, { readonly brand: "Committed" }>()(
54
+ "Committed",
55
+ {},
56
+ ) {}
57
+
58
+ export class Pushed extends Schema.TaggedClass<Pushed, { readonly brand: "Pushed" }>()(
59
+ "Pushed",
60
+ {},
61
+ ) {}
62
+
63
+ export class Approved extends Schema.TaggedClass<Approved, { readonly brand: "Approved" }>()(
64
+ "Approved",
65
+ {},
66
+ ) {}
67
+
68
+ // A pull request a step can name, by the number it can only be.
69
+ export const pullRequestRef = <A extends Implement.PullRequestRef>(ref: A) => ({
70
+ ...ref,
71
+ number: PullRequestNumber(ref.number),
72
+ });
73
+
74
+ // Claim always settles a base; only a run claimed before bases resumes with none.
75
+ export const onBase = (base: Option.Option<BaseBranch>) =>
76
+ Option.match(base, { onNone: () => ({}), onSome: (branch) => ({ base: branch }) });
77
+
78
+ // The line of work a step runs on beside others, which its step names carry:
79
+ // `implement#task-12`.
80
+ export type LaneId = string & Brand.Brand<"LaneId">;
81
+
82
+ export const LaneId = Brand.nominal<LaneId>();
83
+
84
+ export const inLane = (lane?: LaneId) =>
85
+ Option.match(Option.fromUndefinedOr(lane), { onNone: () => ({}), onSome: (id) => ({ id }) });
86
+
87
+ // The agent session a lane's fixes resume, or this run's.
88
+ export const laneSession = (lane?: LaneId) =>
89
+ Option.match(Option.fromUndefinedOr(lane), {
90
+ onNone: () => Effect.succeed(Implement.thisRunsSession),
91
+ onSome: (id) => Implement.sessionFor({ id }),
92
+ });
93
+
94
+ // Any number of days, as a block's wait is written.
95
+ export type Days = `${number} days`;
96
+
97
+ // What a block's failure comes to:
98
+ // - person: a person is told why, and the enclosing scope ends needing them;
99
+ // - told: a person already knows, and the enclosing scope ends needing them;
100
+ // - skip: nothing is left to do, and the enclosing scope ends skipped;
101
+ // - fail: the enclosing scope ends failed.
102
+ export type Disposition = "person" | "told" | "skip" | "fail";
103
+
104
+ type Tagged = { readonly _tag: string };
105
+
106
+ type Tags<E> = E extends Tagged ? E["_tag"] : never;
107
+
108
+ export type Failures<E> = { readonly [Tag in Tags<E>]: Disposition };
109
+
110
+ // A block's failure on its way to a person. The scope around the blocks tells
111
+ // them, since what it can tell them depends on what the run got to.
112
+ export class ToPerson extends Schema.TaggedError<ToPerson, { readonly brand: "ToPerson" }>()(
113
+ "ToPerson",
114
+ { reason: Schema.String },
115
+ ) {}
116
+
117
+ const reasonOf = (error: Tagged) => {
118
+ // Each says why in its reason; its message, as an Error's, is empty.
119
+ if (error instanceof NeedsHuman || error instanceof Skip) {
120
+ return error.reason;
121
+ }
122
+
123
+ if (error instanceof NothingCommitted) {
124
+ return `the agent finished without committing anything on ${error.branch}`;
125
+ }
126
+
127
+ return describeError(error);
128
+ };
129
+
130
+ const told = (error: Tagged) => {
131
+ if (error instanceof NeedsHuman) {
132
+ return error;
133
+ }
134
+
135
+ return new NeedsHuman({ reason: reasonOf(error) });
136
+ };
137
+
138
+ const skipped = (error: Tagged) => {
139
+ if (error instanceof Skip) {
140
+ return error;
141
+ }
142
+
143
+ return new Skip({ reason: reasonOf(error) });
144
+ };
145
+
146
+ const failed = (block: string, error: Tagged) => {
147
+ if (error instanceof StepFailed) {
148
+ return error;
149
+ }
150
+
151
+ return new StepFailed({ step: block, message: reasonOf(error) });
152
+ };
153
+
154
+ const settled = (block: string, error: Tagged, disposition: Disposition): FlowError | ToPerson => {
155
+ switch (disposition) {
156
+ case "person":
157
+ return new ToPerson({ reason: reasonOf(error) });
158
+ case "told":
159
+ return told(error);
160
+ case "skip":
161
+ return skipped(error);
162
+ case "fail":
163
+ return failed(block, error);
164
+ }
165
+ };
166
+
167
+ // The fields of a flow's settings a block reads, none of which needs a service.
168
+ export type SettingsFields = {
169
+ readonly [key: string]: Schema.Top & {
170
+ readonly DecodingServices: never;
171
+ readonly EncodingServices: never;
172
+ };
173
+ };
174
+
175
+ // What using a block adds to its flow, unasked.
176
+ export type Contribution = {
177
+ readonly settings?: SettingsFields;
178
+ readonly labels?: ReadonlyArray<FlowLabel>;
179
+ // Labels named by the flow's settings, as a repo may rename them.
180
+ readonly namedLabels?: ReadonlyArray<Effect.Effect<FlowLabel, never, FlowSettings | Repo>>;
181
+ readonly doctor?: ReadonlyArray<DoctorCheck>;
182
+ // Finds runs of this flow parked in the block, to wake them.
183
+ readonly wakes?: TriggeredFlow["trigger"];
184
+ readonly ownWork?: boolean;
185
+ };
186
+
187
+ const DispositionTable = Schema.Record(
188
+ Schema.String,
189
+ Schema.Literals(["person", "told", "skip", "fail"]),
190
+ );
191
+
192
+ const InputNeeds = Schema.Record(Schema.String, Schema.Literals(["required", "optional"]));
193
+
194
+ const dispositionsOf = Schema.decodeUnknownSync(DispositionTable);
195
+
196
+ const inputNeedsOf = Schema.decodeUnknownSync(InputNeeds);
197
+
198
+ const Kinds = Schema.Record(Schema.String, Schema.String);
199
+
200
+ const kindsOf = Schema.decodeUnknownSync(Kinds);
201
+
202
+ const outputKindsOf = Schema.decodeUnknownSync(Schema.Union([Schema.String, Kinds]));
203
+
204
+ const opensOf = Schema.decodeUnknownSync(Schema.Record(Schema.String, Schema.Array(Schema.String)));
205
+
206
+ // What a block gives, as a listing says it: a word for a value, or a word for
207
+ // each field. It must name every field the block's output has, and no others.
208
+ type OutputKinds<Output> = [Output] extends [string | number | boolean | void]
209
+ ? string
210
+ : { readonly [Field in keyof Output]-?: string };
211
+
212
+ type BlockSpec<Input, Output, E, R, Outcomes> = {
213
+ readonly name: string;
214
+ // What it does, for someone choosing blocks.
215
+ readonly about: string;
216
+ // What each input takes, each output gives and each outcome binds, for the
217
+ // same. The compiler makes these name exactly what the block has.
218
+ readonly inputKinds: { readonly [Name in keyof Input]-?: string };
219
+ readonly outputKinds: OutputKinds<NoInfer<Output>>;
220
+ readonly outcomeKinds: { readonly [Name in keyof NoInfer<Outcomes>]: string };
221
+ // The inputs a document gives as a fixed value, under `with`, rather than
222
+ // wiring them to an earlier step's output, under `in`.
223
+ readonly fixed?: ReadonlyArray<keyof Input & string>;
224
+ // The inputs a document may give either way: a fixed value under `with`, or
225
+ // an earlier step's output under `in`.
226
+ readonly either?: ReadonlyArray<keyof Input & string>;
227
+ // The blocks that, on a path with both, must run after this one.
228
+ readonly before?: ReadonlyArray<string>;
229
+ // The blocks that must already have run on any path to this one.
230
+ readonly needs?: ReadonlyArray<string>;
231
+ // What this leaves to be done on any path that goes on to finish well, and
232
+ // what it does of that. A path that ends with a person is excused.
233
+ readonly opens?: ReadonlyArray<string>;
234
+ readonly closes?: ReadonlyArray<string>;
235
+ // What taking an outcome leaves to be done, the same way.
236
+ readonly opensOn?: { readonly [Name in keyof NoInfer<Outcomes>]?: ReadonlyArray<string> };
237
+ // Each input and whether a document must wire it. An input it needn't wire
238
+ // has a default.
239
+ readonly inputs: { readonly [Name in keyof Input]-?: "required" | "optional" };
240
+ readonly run: (input: Input) => Effect.Effect<Output, E, R>;
241
+ readonly failures: Failures<NoInfer<E>>;
242
+ // The branches a document can take on the block's output, each the value it
243
+ // binds there, or none when the output didn't take it.
244
+ readonly outcomes: Outcomes;
245
+ // The outcomes a document must say what to do about.
246
+ readonly mustRoute: ReadonlyArray<keyof Outcomes & string>;
247
+ // Whether the block waits, so a loop through it doesn't spin.
248
+ readonly waits?: boolean;
249
+ // Whether it runs only on a run's way out: in a repeat, no way past it goes
250
+ // on to another round, which a document is checked for, so it runs once and
251
+ // its steps needn't carry the round.
252
+ readonly last?: boolean;
253
+ // The outcomes that changed something, so a loop taking one doesn't spin.
254
+ readonly progressOn?: ReadonlyArray<keyof Outcomes & string>;
255
+ // The outcome it comes to when it changed nothing: any other way past it,
256
+ // a loop doesn't spin.
257
+ readonly progressUnless?: keyof Outcomes & string;
258
+ // Whether every run comes to one of the outcomes, so a document whose
259
+ // branches all end has nothing after the block.
260
+ readonly exhaustive?: boolean;
261
+ // The groups of step names its run uses that another block's also does, or
262
+ // its own name when none are shared, and none for a block that runs no step.
263
+ // A second use of a step name replays the first's result instead of doing
264
+ // the work, so no path takes a group twice, and a block that runs steps in a
265
+ // loop's rounds or beside others must carry the round or the lane in them.
266
+ readonly stepNames?: ReadonlyArray<string>;
267
+ // The subjects it suits, for a block whose inputs can't show them: one that
268
+ // reads its run's work item itself, or leans on what only a subject's scope
269
+ // does, such as letting its claim go. It suits none of the others, even
270
+ // where what it takes could be wired; see suits.ts.
271
+ readonly suits?: ReadonlyArray<string>;
272
+ readonly contributes: Contribution;
273
+ };
274
+
275
+ // Where a flow's work comes from.
276
+ export type Source = {
277
+ readonly trigger: TriggeredFlow["trigger"];
278
+ readonly contributes: Contribution;
279
+ };
280
+
281
+ // A source, by the name a document uses it by, and the subject of the work
282
+ // items it finds.
283
+ export const defineSource = <Subject extends string, Input extends ReadonlyArray<unknown>>(
284
+ name: string,
285
+ subject: Subject,
286
+ find: (...input: Input) => Source,
287
+ ) => ({ name, subject, find });
288
+
289
+ type Named = { readonly [key: string]: { readonly name: string } };
290
+
291
+ // What a document can use by name, gathered from the files that define it, a
292
+ // file at a time. Spreading the files together would let a later file's entry
293
+ // quietly replace an earlier one's, so a document compiled against a block its
294
+ // author didn't mean; a name defined twice, or kept under a key other than its
295
+ // own, is refused instead, when the module loads.
296
+ export type Gathered<Entries> = {
297
+ readonly entries: Entries;
298
+ readonly and: <More extends Named>(file: string, more: More) => Gathered<Entries & More>;
299
+ };
300
+
301
+ // What a catalogue gets wrong, refused the way a block's tables are: by
302
+ // decoding, when the module loads.
303
+ const refuseMistakes = Schema.decodeUnknownSync(
304
+ Schema.Array(Schema.String).pipe(
305
+ Schema.check(
306
+ Schema.makeFilter(
307
+ (mistakes: ReadonlyArray<string>) => mistakes.length === 0 || mistakes.join("; "),
308
+ ),
309
+ ),
310
+ ),
311
+ );
312
+
313
+ const gatherOnto = <Before extends Named, Entries extends Named>(
314
+ kind: string,
315
+ where: ReadonlyMap<string, string>,
316
+ before: Before,
317
+ file: string,
318
+ entries: Entries,
319
+ ): Gathered<Before & Entries> => {
320
+ const found = new Map(where);
321
+ const mistakes: Array<string> = [];
322
+
323
+ for (const [key, entry] of Object.entries(entries)) {
324
+ if (entry.name !== key) {
325
+ mistakes.push(
326
+ `${kind} "${key}" in ${file} is named "${entry.name}"; its key must be its name`,
327
+ );
328
+ }
329
+
330
+ const earlier = Option.fromUndefinedOr(found.get(key));
331
+
332
+ if (Option.isSome(earlier)) {
333
+ mistakes.push(`${kind} "${key}" is defined twice: in ${earlier.value} and in ${file}`);
334
+ }
335
+
336
+ found.set(key, file);
337
+ }
338
+
339
+ refuseMistakes(mistakes);
340
+
341
+ const all = { ...before, ...entries };
342
+
343
+ return {
344
+ entries: all,
345
+ and: (next, more) => gatherOnto(kind, found, all, next, more),
346
+ };
347
+ };
348
+
349
+ export const gather = <Entries extends Named>(kind: string, file: string, entries: Entries) =>
350
+ gatherOnto(kind, new Map(), {}, file, entries);
351
+
352
+ export const defineBlock = <
353
+ Input,
354
+ Output,
355
+ E extends Tagged,
356
+ R,
357
+ const Outcomes extends {
358
+ readonly [Name in string]: (output: Output) => Option.Option<unknown>;
359
+ },
360
+ >(
361
+ spec: BlockSpec<Input, Output, E, R, Outcomes>,
362
+ ) => {
363
+ const table = dispositionsOf(spec.failures);
364
+
365
+ return {
366
+ name: spec.name,
367
+ failures: table,
368
+ about: spec.about,
369
+ inputKinds: kindsOf(spec.inputKinds),
370
+ outputKinds: outputKindsOf(spec.outputKinds),
371
+ outcomeKinds: kindsOf(spec.outcomeKinds),
372
+ fixed: (spec.fixed ?? []).map(String),
373
+ either: (spec.either ?? []).map(String),
374
+ before: spec.before ?? [],
375
+ needs: spec.needs ?? [],
376
+ opens: spec.opens ?? [],
377
+ closes: spec.closes ?? [],
378
+ opensOn: opensOf(spec.opensOn ?? {}),
379
+ inputs: inputNeedsOf(spec.inputs),
380
+ outcomes: spec.outcomes,
381
+ mustRoute: spec.mustRoute,
382
+ exhaustive: spec.exhaustive === true,
383
+ waits: spec.waits === true,
384
+ last: spec.last === true,
385
+ progressOn: spec.progressOn ?? [],
386
+ progressUnless: Option.fromUndefinedOr(spec.progressUnless),
387
+ stepNames: spec.stepNames ?? [spec.name],
388
+ suits: Option.fromUndefinedOr(spec.suits),
389
+ contributes: spec.contributes,
390
+ run: (input: Input, overrides: Partial<Failures<NoInfer<E>>> = {}) => {
391
+ const own = dispositionsOf(overrides);
392
+
393
+ return spec.run(input).pipe(
394
+ Effect.mapError((error) =>
395
+ settled(
396
+ spec.name,
397
+ error,
398
+ Option.getOrElse(
399
+ Option.orElse(Record.get(own, error._tag), () => Record.get(table, error._tag)),
400
+ (): Disposition => "fail",
401
+ ),
402
+ ),
403
+ ),
404
+ );
405
+ },
406
+ };
407
+ };
408
+
409
+ // What a document says each failure of a stage means: a stage has no table of
410
+ // its own. Exit 78 is Skip; any other failure is StepFailed.
411
+ export type StageFailures = { readonly Skip: Disposition; readonly StepFailed: Disposition };
412
+
413
+ // What names a stage's step beside its name: the round of a loop it runs in,
414
+ // `find-work-2`, or the lane, `find-work#task-12`.
415
+ export type StageKey = { readonly round?: number; readonly lane?: LaneId };
416
+
417
+ const stageStep = (name: string, key: StageKey) =>
418
+ [
419
+ name,
420
+ ...Option.toArray(Option.fromUndefinedOr(key.round)).map((round) => `-${round}`),
421
+ ...Option.toArray(Option.fromUndefinedOr(key.lane)).map((lane) => `#${lane}`),
422
+ ].join("");
423
+
424
+ const stageDisposition = (failures: StageFailures, error: FlowError): Disposition => {
425
+ if (error instanceof Skip) {
426
+ return failures.Skip;
427
+ }
428
+
429
+ if (error instanceof StepFailed) {
430
+ return failures.StepFailed;
431
+ }
432
+
433
+ // A stage's process can't ask for a person; an activity's own can.
434
+ return "told";
435
+ };
436
+
437
+ // Runs a step of the repo's own from .chernabog/stages/, as a document does:
438
+ // its input, typed by the stage's schema, crosses to its process as JSON, and
439
+ // what it prints comes back checked against its output schema. Each failure
440
+ // comes to what the document says.
441
+ export const runStage = <I, O>(
442
+ name: string,
443
+ stage: { readonly input: Schema.Codec<I, Json>; readonly output: Schema.Codec<O, Json> },
444
+ input: NoInfer<I>,
445
+ failures: StageFailures,
446
+ key: StageKey,
447
+ ) =>
448
+ activity(
449
+ stageStep(name, key),
450
+ Effect.gen(function* () {
451
+ const encoded = yield* Schema.encodeEffect(stage.input)(input).pipe(
452
+ Effect.mapError(
453
+ (issue) => new StepFailed({ step: name, message: `input: ${issue.message}` }),
454
+ ),
455
+ );
456
+
457
+ const raw = yield* StepRunner.use((runner) => runner.run(name, encoded));
458
+
459
+ return yield* Schema.decodeEffect(stage.output)(raw).pipe(
460
+ Effect.mapError(
461
+ (issue) => new StepFailed({ step: name, message: `output: ${issue.message}` }),
462
+ ),
463
+ );
464
+ }),
465
+ stage.output,
466
+ ).pipe(Effect.mapError((error) => settled(name, error, stageDisposition(failures, error))));