@chernabog/sdk 0.6.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,5 +1,7 @@
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
6
  import * as Effect from "effect/Effect";
5
7
  import * as FileSystem from "effect/FileSystem";
@@ -7,7 +9,7 @@ import * as Option from "effect/Option";
7
9
  import * as Predicate from "effect/Predicate";
8
10
 
9
11
  import { StepFailed } from "./errors.ts";
10
- import { Repo } from "./services.ts";
12
+ import { FlowPackage, Repo } from "./services.ts";
11
13
 
12
14
  export type PromptValue = string | number | ReadonlyArray<string> | Option.Option<string>;
13
15
 
@@ -35,38 +37,66 @@ export const fillTemplate = (template: string, values: Readonly<Record<string, P
35
37
  }),
36
38
  );
37
39
 
38
- 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) =>
39
43
  Effect.gen(function* () {
40
44
  const repo = yield* Repo;
45
+ const flowPackage = yield* Effect.serviceOption(FlowPackage);
46
+
47
+ return [
48
+ `${repo.configDir}/prompts/${name}.md`,
49
+ ...Option.toArray(Option.map(flowPackage, (found) => `${found.dir}/prompts/${name}.md`)),
50
+ ];
51
+ });
52
+
53
+ // The first of the prompt's layers that has it; none when no layer does.
54
+ const findPrompt = (name: string) =>
55
+ Effect.gen(function* () {
41
56
  const fs = yield* FileSystem.FileSystem;
42
- const path = `${repo.configDir}/prompts/${name}.md`;
43
57
 
44
- const template = yield* fs
45
- .readFileString(path)
46
- .pipe(
47
- Effect.mapError(
48
- () => new StepFailed({ step: `prompt ${name}`, message: `no prompt at ${path}` }),
49
- ),
50
- );
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 ");
51
80
 
52
- return fillTemplate(template, values);
81
+ return yield* new StepFailed({ step: `prompt ${name}`, message: `no prompt at ${looked}` });
82
+ }
83
+
84
+ return fillTemplate(yield* readPrompt(name, found.value), values);
53
85
  });
54
86
 
55
- // Like renderPrompt, from the default the SDK carries when the repo has no
56
- // .chernabog/prompts/<name>.md of its own.
87
+ // Like renderPrompt, from the default the SDK carries when neither the repo
88
+ // nor the flow's package has prompts/<name>.md.
57
89
  export const renderPromptOr = (
58
90
  name: string,
59
91
  fallback: string,
60
92
  values: Readonly<Record<string, PromptValue>>,
61
93
  ) =>
62
94
  Effect.gen(function* () {
63
- const repo = yield* Repo;
64
- const fs = yield* FileSystem.FileSystem;
65
- const path = `${repo.configDir}/prompts/${name}.md`;
95
+ const found = yield* findPrompt(name);
66
96
 
67
- if (!(yield* fs.exists(path).pipe(Effect.orElseSucceed(() => false)))) {
97
+ if (Option.isNone(found)) {
68
98
  return fillTemplate(fallback, values);
69
99
  }
70
100
 
71
- return yield* renderPrompt(name, values);
101
+ return fillTemplate(yield* readPrompt(name, found.value), values);
72
102
  });
@@ -10,8 +10,9 @@ import * as Option from "effect/Option";
10
10
  import * as Random from "effect/Random";
11
11
  import * as Schema from "effect/Schema";
12
12
 
13
+ import * as Claims from "./claims.ts";
13
14
  import { commentStep } from "./comment.ts";
14
- import { MergeRefused, NeedsHuman, PullRequestClosed } from "./errors.ts";
15
+ import { MergeRefused, NeedsHuman, PullRequestClosed, Skip } from "./errors.ts";
15
16
  import { activity } from "./flow.ts";
16
17
  import { latestMarker, type OwnerMarker, ownerMarker, reviewMarker } from "./markers.ts";
17
18
  import { pathsMatching } from "./paths.ts";
@@ -25,54 +26,95 @@ import {
25
26
  Runs,
26
27
  } from "./services.ts";
27
28
 
28
- const writeOwner = (name: string, pullRequest: number, released: boolean) =>
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) =>
29
31
  activity(
30
- name,
32
+ `own-pr-${pullRequest}`,
31
33
  Effect.gen(function* () {
32
34
  const run = yield* Run;
33
- const marker = ownerMarker.write({ flow: run.flow, runId: run.runId, released });
35
+ const item = Claims.pullRequest(pullRequest);
36
+ const claimed = yield* Claims.acquire(item);
34
37
 
35
- if (released) {
36
- yield* (yield* GitHub).comment(
37
- pullRequest,
38
- `The \`${run.flow}\` run is done with this pull request. ${marker}`,
39
- );
40
- } else {
41
- yield* (yield* GitHub).comment(
42
- pullRequest,
43
- `The \`${run.flow}\` run owns this pull request until it ends. ${marker}`,
44
- );
38
+ if (!claimed.acquired) {
39
+ return yield* new Skip({
40
+ reason: `#${pullRequest} is owned by another run (${Claims.describeHolder(item, claimed.holder)})`,
41
+ });
45
42
  }
43
+
44
+ const marker = ownerMarker.write({
45
+ flow: run.flow,
46
+ runId: run.runId,
47
+ released: false,
48
+ ref: true,
49
+ });
50
+
51
+ yield* (yield* GitHub).comment(
52
+ pullRequest,
53
+ `The \`${run.flow}\` run owns this pull request until it ends. ${marker}`,
54
+ );
46
55
  }),
47
56
  );
48
57
 
49
58
  // Comments on the pull request, and does nothing else.
50
59
  export const comment = (pullRequest: number, body: string) => commentStep("pr", pullRequest, body);
51
60
 
52
- // Marks the pull request as this run's.
53
- export const own = (pullRequest: number) => writeOwner(`own-pr-${pullRequest}`, pullRequest, false);
54
-
55
61
  // Lets the pull request go, so the standalone flows pick it up again.
56
62
  export const release = (pullRequest: number) =>
57
- writeOwner(`release-pr-${pullRequest}`, pullRequest, true);
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
+ );
58
82
 
59
83
  // Owns the pull request for as long as `effect` runs, and releases it however
60
- // 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.
61
86
  export const owning =
62
87
  (pullRequest: number) =>
63
88
  <A, E, R>(effect: Effect.Effect<A, E, R>) =>
64
89
  own(pullRequest).pipe(
65
- Effect.andThen(effect),
66
- // A wait suspends the run by interrupting it; that is not an ending.
67
- Effect.onExit((exit) => {
68
- if (Exit.isFailure(exit) && Cause.hasInterrupts(exit.cause)) {
69
- return Effect.void;
70
- }
71
-
72
- return release(pullRequest).pipe(Effect.ignore);
73
- }),
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
+ }
97
+
98
+ return release(pullRequest).pipe(Effect.ignore);
99
+ }),
100
+ ),
101
+ ),
74
102
  );
75
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
+
76
118
  // The run that owns the pull request, from its comments: none once it let go,
77
119
  // or when this machine knows the run has ended.
78
120
  export const ownerOf = (bodies: ReadonlyArray<string>) =>
@@ -86,20 +128,41 @@ export const ownerOf = (bodies: ReadonlyArray<string>) =>
86
128
  return Option.none<OwnerMarker>();
87
129
  }
88
130
 
89
- const runs = yield* Effect.serviceOption(Runs);
90
-
91
- const active = yield* Option.match(runs, {
92
- onNone: () => Effect.succeedNone,
93
- onSome: (known) => known.isActive(latest.value.runId),
94
- });
95
-
96
- if (Option.contains(active, false)) {
131
+ if (yield* knownEnded(latest.value.runId)) {
97
132
  return Option.none<OwnerMarker>();
98
133
  }
99
134
 
100
135
  return latest;
101
136
  });
102
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
+
103
166
  export type MergeOptions = { readonly method: MergeMethod };
104
167
 
105
168
  const refuse = (pullRequest: number, reason: string) => new MergeRefused({ pullRequest, reason });
package/src/review.ts CHANGED
@@ -79,17 +79,9 @@ export const reviewItem = (pull: PullRequest, key: string): WorkItem => ({
79
79
  reviewers: pull.requestedReviewers,
80
80
  });
81
81
 
82
- const commentBodies = (pull: PullRequest) =>
83
- GitHub.use((github) => github.comments(pull.number)).pipe(
84
- Effect.map((comments) => comments.map((comment) => comment.body)),
85
- );
86
-
87
- // Whether a run of another flow owns the pull request; the standalone flows leave it alone.
88
- const ownedByARunOf = (bodies: ReadonlyArray<string>) =>
89
- PullRequestSteps.ownerOf(bodies).pipe(Effect.map(Option.isSome));
90
-
82
+ // Whether a run of another flow owns the pull request, by its claim ref; the standalone flows leave it alone.
91
83
  export const ownedByARun = (pull: PullRequest) =>
92
- commentBodies(pull).pipe(Effect.flatMap(ownedByARunOf));
84
+ PullRequestSteps.owner(pull.number).pipe(Effect.map(Option.isSome));
93
85
 
94
86
  const sameLogin = (left: string, right: string) => left.toLowerCase() === right.toLowerCase();
95
87
 
package/src/services.ts CHANGED
@@ -85,6 +85,10 @@ export const Limits = Schema.Struct({
85
85
  staleAfter: Schema.Duration,
86
86
  // How long CI may stay pending before a person looks.
87
87
  ciTimeout: Schema.Duration,
88
+ // The most tasks one plan may hold, its verify node aside.
89
+ planNodes: Schema.Finite,
90
+ // Times the agent is asked to fix a plan that fails its checks before a person takes over.
91
+ planRounds: Schema.Finite,
88
92
  });
89
93
 
90
94
  export type Limits = typeof Limits.Type;
@@ -194,6 +198,21 @@ export type RunInfo = typeof RunInfo.Type;
194
198
 
195
199
  export class Run extends Context.Service<Run, RunInfo>()("@chernabog/sdk/Run") {}
196
200
 
201
+ // The recipe package a run's flow is imported from (config.yaml's
202
+ // flows.<name>.from): its name, version, and the directory it's installed in.
203
+ // Its prompts and steps are looked up there after the repo's own, so a repo can
204
+ // override one of them without copying the flow. A flow copied into the repo,
205
+ // or written there, has none.
206
+ export type FlowPackageInfo = {
207
+ readonly name: string;
208
+ readonly version: string;
209
+ readonly dir: string;
210
+ };
211
+
212
+ export class FlowPackage extends Context.Service<FlowPackage, FlowPackageInfo>()(
213
+ "@chernabog/sdk/FlowPackage",
214
+ ) {}
215
+
197
216
  export type Issue = {
198
217
  readonly number: number;
199
218
  readonly title: string;
@@ -204,6 +223,15 @@ export type Issue = {
204
223
  readonly assignees: ReadonlyArray<string>;
205
224
  };
206
225
 
226
+ // An issue as GitHub lists it under another: a sub-issue, or a blocker.
227
+ export type LinkedIssue = Issue & { readonly state: "open" | "closed" };
228
+
229
+ export type NewIssue = {
230
+ readonly title: string;
231
+ readonly body: string;
232
+ readonly labels: ReadonlyArray<string>;
233
+ };
234
+
207
235
  export type Comment = {
208
236
  readonly id: number;
209
237
  readonly author: string;
@@ -260,6 +288,14 @@ export type SubmittedReview = {
260
288
  readonly commitSha: string;
261
289
  };
262
290
 
291
+ export type NewCommit = {
292
+ readonly message: string;
293
+ readonly tree: string;
294
+ readonly parents: ReadonlyArray<string>;
295
+ };
296
+
297
+ export type RefCommit = { readonly sha: string; readonly message: string };
298
+
263
299
  export type MergeMethod = "merge" | "squash" | "rebase";
264
300
 
265
301
  // The merge of exactly `sha`: GitHub refuses one whose head has moved since.
@@ -281,7 +317,20 @@ export class GitHub extends Context.Service<
281
317
  // Open issues with this label (and ready on the board, when the repo has one), oldest first.
282
318
  queuedIssuesLabelled(label: string): Effect.Effect<ReadonlyArray<Issue>, GitHubError>;
283
319
  readonly oldestQueued: Effect.Effect<Option.Option<number>, GitHubError>;
320
+ // Open issues with this label, whatever their status on the board, oldest first.
321
+ issuesLabelled(label: string): Effect.Effect<ReadonlyArray<Issue>, GitHubError>;
284
322
  issue(number: number): Effect.Effect<Issue, NotFound | GitHubError>;
323
+ createIssue(issue: NewIssue): Effect.Effect<Issue, GitHubError>;
324
+ // An epic's tasks, open and closed, in GitHub's order.
325
+ subIssues(parent: number): Effect.Effect<ReadonlyArray<LinkedIssue>, GitHubError>;
326
+ // Makes `child` a sub-issue of `parent`; one already there stays.
327
+ addSubIssue(parent: number, child: number): Effect.Effect<void, GitHubError>;
328
+ // The issues that must close before this one can start, open and closed.
329
+ blockedBy(issue: number): Effect.Effect<ReadonlyArray<LinkedIssue>, GitHubError>;
330
+ // Records that `blocker` blocks `issue`; a link already there stays.
331
+ addBlockedBy(issue: number, blocker: number): Effect.Effect<void, GitHubError>;
332
+ // Removing a link that isn't there is not an error.
333
+ removeBlockedBy(issue: number, blocker: number): Effect.Effect<void, GitHubError>;
285
334
  // Comments by the repo's owners, members and collaborators only; anyone can comment on a public repo.
286
335
  trustedComments(number: number): Effect.Effect<ReadonlyArray<Comment>, GitHubError>;
287
336
  comments(number: number): Effect.Effect<ReadonlyArray<Comment>, GitHubError>;
@@ -299,6 +348,14 @@ export class GitHub extends Context.Service<
299
348
  sha: string,
300
349
  ): Effect.Effect<"created" | "already-exists", GitHubError>;
301
350
  deleteBranch(branch: string): Effect.Effect<void, GitHubError>;
351
+ // A commit made through the API, with no worktree: its sha.
352
+ createCommit(commit: NewCommit): Effect.Effect<string, GitHubError>;
353
+ // Any ref, named in full (`refs/chernabog/claims/issue-12`). Whoever creates one first holds it.
354
+ createRef(ref: string, sha: string): Effect.Effect<"created" | "already-exists", GitHubError>;
355
+ // The commit a ref points at, with its message; none for a ref GitHub doesn't have.
356
+ ref(ref: string): Effect.Effect<Option.Option<RefCommit>, GitHubError>;
357
+ // Deleting a ref GitHub doesn't have is not an error.
358
+ deleteRef(ref: string): Effect.Effect<void, GitHubError>;
302
359
  pullRequest(number: number): Effect.Effect<PullRequest, NotFound | GitHubError>;
303
360
  pullRequestForBranch(branch: string): Effect.Effect<Option.Option<PullRequest>, GitHubError>;
304
361
  pullRequestsLabelled(label: string): Effect.Effect<ReadonlyArray<PullRequest>, GitHubError>;
@@ -400,6 +457,9 @@ export type AgentRequest = {
400
457
  // to answer, and it is done once its answer is written. Only Claude under
401
458
  // a launcher can.
402
459
  readonly withPerson?: boolean;
460
+ // The step that asks, such as `implement` or `fix-ci-2`. The Agent service
461
+ // fills it in from the activity it runs in, when the caller leaves it out.
462
+ readonly step?: string;
403
463
  };
404
464
 
405
465
  export class Agent extends Context.Service<