@kitman-sh/software-engineering 0.10.91 → 0.10.92

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/dist/bundle.js CHANGED
@@ -20448,7 +20448,8 @@ var scriptedHost = (script, engine, agentLaunches, childLaunches, waits, verifyL
20448
20448
  event: launch.event,
20449
20449
  ...launch.filter === undefined ? undefined : { filter: launch.filter },
20450
20450
  ...launch.since === undefined ? undefined : { since: launch.since },
20451
- ...launch.or === undefined ? undefined : { or: launch.or }
20451
+ ...launch.or === undefined ? undefined : { or: launch.or },
20452
+ timeoutMillis: launch.timeoutMillis
20452
20453
  });
20453
20454
  return resolve(eventDeferred(launch.step), launch.token, event === undefined ? fail5(new WaitTimedOut({ step: launch.step, event: launch.event })) : succeed4(event));
20454
20455
  },
@@ -21519,6 +21520,8 @@ var ShepherdOutput = Struct({
21519
21520
  // src/shepherd.ts
21520
21521
  var reviewLoop = () => ({ id: "review", input: Input, output: Output });
21521
21522
  var stepBudget = "45 minutes";
21523
+ var pipelineRun = "10 minutes";
21524
+ var targetLooks = 6;
21522
21525
  var roundLimits = { "ci-fix": 1, "head-fix": 2 };
21523
21526
  var handBackAnswer = "Hand back to Build";
21524
21527
  var Input3 = Struct({
@@ -21602,7 +21605,7 @@ var repliesPrompt = (threads) => [
21602
21605
  var threadKey = (thread) => `${thread.id}:${thread.comments.length}`;
21603
21606
  var shepherd_default = defineLoop({
21604
21607
  id: "shepherd",
21605
- version: "1.5.0",
21608
+ version: "1.6.0",
21606
21609
  title: "Shepherd",
21607
21610
  input: Input3,
21608
21611
  output: Output3,
@@ -21637,6 +21640,9 @@ var shepherd_default = defineLoop({
21637
21640
  let stalledAt;
21638
21641
  let stalls = 0;
21639
21642
  let unreviewed;
21643
+ let reviewOnceShown;
21644
+ let pipelineFirst;
21645
+ const reviewedHeads = new Set;
21640
21646
  let notCarried;
21641
21647
  let behind = false;
21642
21648
  let pushed;
@@ -21759,7 +21765,8 @@ ${open}`,
21759
21765
  yield* note(`target-red:${cycle}`, {
21760
21766
  text: `Shepherd is waiting for ${target} to change instead of fixing ${pipeline.head}: ${why}`
21761
21767
  }).pipe(catchTag2("StepFailed", () => void_3));
21762
- const woke = yield* waitFor(`target-moved:${cycle}`, {
21768
+ const targetHead = pipeline.target?.head;
21769
+ const mergedInto = {
21763
21770
  event: "change_request.closed",
21764
21771
  filter: {
21765
21772
  merged: true,
@@ -21767,12 +21774,19 @@ ${open}`,
21767
21774
  ...repository === undefined ? undefined : { repository }
21768
21775
  },
21769
21776
  or: [{ event: "change_request.closed", filter: { changeRequestId } }],
21770
- timeout: "1 hour",
21777
+ timeout: targetHead === undefined ? "1 hour" : pipelineRun,
21771
21778
  ...pipeline.readAt === undefined ? undefined : { since: pipeline.readAt }
21772
- }).pipe(catchTag2("WaitTimedOut", () => undefined_2));
21779
+ };
21780
+ let woke = yield* waitFor(`target-moved:${cycle}`, mergedInto).pipe(catchTag2("WaitTimedOut", () => undefined_2));
21781
+ for (let look = 2;woke === undefined && targetHead !== undefined && look <= targetLooks; look++) {
21782
+ const again = yield* pipelineStatus(`target-read:${cycle}:${look}`, { changeRequestId });
21783
+ if (again.head !== pipeline.head || again.target?.head !== targetHead)
21784
+ break;
21785
+ woke = yield* waitFor(`target-moved:${cycle}:${look}`, mergedInto).pipe(catchTag2("WaitTimedOut", () => undefined_2));
21786
+ }
21773
21787
  if (woke?.payload.changeRequestId === changeRequestId)
21774
21788
  return woke.payload.merged === true ? done("merged", "Someone else merged the ChangeRequest") : done("needs_you", "The ChangeRequest was closed");
21775
- redTarget = { head: pipeline.head, targetHead: pipeline.target?.head, moved: woke !== undefined };
21789
+ redTarget = { head: pipeline.head, targetHead, moved: woke !== undefined };
21776
21790
  return;
21777
21791
  });
21778
21792
  const catchUp = (cycle, targetHead, forBlocker = false) => gen2(function* () {
@@ -21809,6 +21823,8 @@ ${open}`,
21809
21823
  }
21810
21824
  if (caught !== undefined) {
21811
21825
  pushed = { head: caught.head, stale: 0, by: "the catch-up" };
21826
+ reviewOnceShown = caught.head;
21827
+ pipelineFirst = caught.head;
21812
21828
  if (targetHead !== undefined)
21813
21829
  syncedFor.add(syncedKey(caught.head, targetHead));
21814
21830
  if (forBlocker)
@@ -21821,6 +21837,120 @@ ${open}`,
21821
21837
  }
21822
21838
  return;
21823
21839
  });
21840
+ const stop = (output) => ({ kind: "stop", output });
21841
+ const reviewMergedFiles = (cycle, head, files) => gen2(function* () {
21842
+ yield* passTurn();
21843
+ const reviewed = yield* call(`review:${cycle}`, reviewLoop(), {
21844
+ base: `origin/${target}`,
21845
+ head,
21846
+ files: files.files,
21847
+ ...head === files.synced ? undefined : { since: files.synced },
21848
+ ...files.earlier.length === 0 ? undefined : { earlier: files.earlier }
21849
+ });
21850
+ if (reviewed.blocking) {
21851
+ const blocking = reviewed.findings.filter(isBlocking);
21852
+ if (!(yield* mayFix("head-fix", cycle, blocking.map((finding) => finding.id).join(", "))))
21853
+ return stop(handBack(`The review of the catch-up merge's files still finds ${blocking.map((finding) => finding.id).join(", ")} after ${rounds["head-fix"]} head-fix rounds`, findingLines2(blocking)));
21854
+ rounds["head-fix"]++;
21855
+ const fix = yield* agentWork(`review-fix:${cycle}`, {
21856
+ agent: "implementer",
21857
+ prompt: reviewFixPrompt("the files the catch-up merge changed", blocking),
21858
+ output: ReviewFix,
21859
+ timeout: stepBudget
21860
+ });
21861
+ unreviewed = { ...files, earlier: reviewed.findings };
21862
+ fixedFrom = { head, changed: fix.changed, looks: 0 };
21863
+ return { kind: "fixing" };
21864
+ }
21865
+ const approval = yield* approveChangeRequest(`approve:${cycle}`, {
21866
+ changeRequestId,
21867
+ head,
21868
+ summary: `A review of the files merging ${target} in changed (${files.files.join(", ")}) passed with nothing blocking.`,
21869
+ review: `review:${cycle}`,
21870
+ carries: files.sync
21871
+ }).pipe(catchTag2("StepFailed", (error) => succeed7({ approved: false, reason: error.reason })));
21872
+ unreviewed = undefined;
21873
+ if (!approval.approved) {
21874
+ notCarried = `merging ${target} in, whose files' review passed but did not approve it: ${approval.reason}`;
21875
+ return { kind: "unapproved" };
21876
+ }
21877
+ reviewedHeads.add(head);
21878
+ return { kind: "approved" };
21879
+ });
21880
+ const reviewHead = (cycle, pipeline, which) => gen2(function* () {
21881
+ const head = pipeline.head;
21882
+ const since = pipeline.approved === undefined || pipeline.approved === head ? undefined : pipeline.approved;
21883
+ const reviewIt = leftToPerson.has(head) ? "Wait" : yield* ask(`unapproved:${cycle}`, {
21884
+ prompt: `Nobody has approved ${head}, ${which}. Have Kitman review it?`,
21885
+ options: [
21886
+ {
21887
+ value: "Review",
21888
+ description: since === undefined ? "Kitman's Review reads the whole change at this head and approves it if nothing blocks." : `Kitman's Review reads what changed since ${since}, the last approved head, and approves it if nothing there blocks.`
21889
+ },
21890
+ { value: "Wait", description: "Waits for a person to approve this head." }
21891
+ ],
21892
+ recommended: "Review",
21893
+ recommendationReason: "A passing Review of the change is what approved the head Build shipped.",
21894
+ default: "Wait",
21895
+ auto: "Review",
21896
+ timeout: "1 hour"
21897
+ });
21898
+ yield* passTurn();
21899
+ if (reviewIt === "Wait") {
21900
+ leftToPerson.add(head);
21901
+ return { kind: "left" };
21902
+ }
21903
+ const { notRun: headNotRun } = yield* verifyHead(`head-verify:${cycle}`, head);
21904
+ const notRun = [...new Set([...input.notRun ?? [], ...headNotRun])];
21905
+ const reviewed = yield* call(`head-review:${cycle}`, reviewLoop(), {
21906
+ base: `origin/${target}`,
21907
+ head,
21908
+ ...notRun.length === 0 ? undefined : { notRun },
21909
+ ...since === undefined ? undefined : { approved: since },
21910
+ ...headFindings.length === 0 ? undefined : { earlier: headFindings }
21911
+ });
21912
+ if (reviewed.blocking) {
21913
+ const blocking = reviewed.findings.filter(isBlocking);
21914
+ if (!(yield* mayFix("head-fix", cycle, blocking.map((finding) => finding.id).join(", "))))
21915
+ return stop(handBack(`The review of ${head} still finds ${blocking.map((finding) => finding.id).join(", ")} after ${rounds["head-fix"]} head-fix rounds`, findingLines2(blocking)));
21916
+ rounds["head-fix"]++;
21917
+ const fix = yield* agentWork(`head-fix:${cycle}`, {
21918
+ agent: "implementer",
21919
+ prompt: reviewFixPrompt(since === undefined ? `the change at ${head}` : `what changed between ${since} and ${head}`, blocking),
21920
+ output: ReviewFix,
21921
+ timeout: stepBudget
21922
+ });
21923
+ headFindings = reviewed.findings;
21924
+ fixedFrom = { head, changed: fix.changed, looks: 0 };
21925
+ return { kind: "fixing" };
21926
+ }
21927
+ headFindings = [];
21928
+ if (notRun.length > 0)
21929
+ unranAt.set(head, { notRun, review: `head-review:${cycle}` });
21930
+ else {
21931
+ const recorded = yield* approveChangeRequest(`head-approve:${cycle}`, {
21932
+ changeRequestId,
21933
+ head,
21934
+ summary: since === undefined ? `A review of the whole change at ${head} passed with nothing blocking.` : `A review of what changed between ${since}, the last approved head, and ${head} passed with nothing blocking.`,
21935
+ review: `head-review:${cycle}`
21936
+ }).pipe(catchTag2("StepFailed", (error) => succeed7({ approved: false, reason: error.reason })));
21937
+ if (!recorded.approved)
21938
+ return stop(done("needs_you", `The review of ${head} passed, but did not approve it: ${recorded.reason}`));
21939
+ }
21940
+ reviewedHeads.add(head);
21941
+ return { kind: "reviewed" };
21942
+ });
21943
+ const reviewCaughtUp = (cycle, pipeline) => gen2(function* () {
21944
+ const head = reviewOnceShown;
21945
+ reviewOnceShown = undefined;
21946
+ if (head !== pipeline.head)
21947
+ return;
21948
+ if (unreviewed !== undefined)
21949
+ return yield* reviewMergedFiles(cycle, head, unreviewed);
21950
+ if (notCarried !== undefined && pipeline.approved !== head)
21951
+ return yield* reviewHead(cycle, pipeline, "the head its catch-up merge pushed");
21952
+ return;
21953
+ });
21824
21954
  return gen2(function* () {
21825
21955
  for (let cycle = 1;; cycle++) {
21826
21956
  if (cycle > (input.maxCycles ?? 20)) {
@@ -21865,7 +21995,25 @@ ${open}`,
21865
21995
  else
21866
21996
  return found;
21867
21997
  }
21868
- if (pipeline.conflicts === true || pipeline.needsRebase === true) {
21998
+ const blocked = pipeline.conflicts === true || pipeline.needsRebase === true;
21999
+ const caughtUpHead = pipeline.head === pipelineFirst;
22000
+ const onRunnerDue = pipeline.status === "none" && pipeline.runnerChecks !== undefined;
22001
+ if (onRunnerDue && (!blocked || caughtUpHead)) {
22002
+ if (ranOnRunner.has(pipeline.head))
22003
+ return done("needs_you", `The pipeline ran on the Runner at ${pipeline.head}, but no result was recorded`);
22004
+ ranOnRunner.add(pipeline.head);
22005
+ const ran = yield* runOnRunner("run", cycle, pipeline.head, pipeline.runnerChecks ?? []);
22006
+ if ("failed" in ran)
22007
+ return done("needs_you", `The pipeline could not run on the Runner: ${ran.failed}`);
22008
+ continue;
22009
+ }
22010
+ const reviewing = yield* reviewCaughtUp(cycle, pipeline);
22011
+ if (reviewing?.kind === "stop")
22012
+ return reviewing.output;
22013
+ const approvedHere = reviewing?.kind === "approved" || reviewing?.kind === "reviewed";
22014
+ if (reviewing?.kind === "fixing" || approvedHere && !blocked && pipeline.status === "success")
22015
+ continue;
22016
+ if (blocked && !(pipeline.status === "running" && caughtUpHead)) {
21869
22017
  const blocker = pipeline.conflicts === true ? `conflicts with ${target}` : `needs ${target} merged in`;
21870
22018
  const targetHead = pipeline.target?.head;
21871
22019
  const syncedAlready = targetHead === undefined ? blockerSynced.has(pipeline.head) : syncedFor.has(syncedKey(pipeline.head, targetHead));
@@ -21892,15 +22040,6 @@ ${open}`,
21892
22040
  return stopped;
21893
22041
  continue;
21894
22042
  }
21895
- if (pipeline.status === "none" && pipeline.runnerChecks !== undefined) {
21896
- if (ranOnRunner.has(pipeline.head))
21897
- return done("needs_you", `The pipeline ran on the Runner at ${pipeline.head}, but no result was recorded`);
21898
- ranOnRunner.add(pipeline.head);
21899
- const ran = yield* runOnRunner("run", cycle, pipeline.head, pipeline.runnerChecks);
21900
- if ("failed" in ran)
21901
- return done("needs_you", `The pipeline could not run on the Runner: ${ran.failed}`);
21902
- continue;
21903
- }
21904
22043
  if (pipeline.status === "none" || pipeline.status === "running") {
21905
22044
  yield* pipelineMoved(`wait:${cycle}`, changeRequestId, pipeline);
21906
22045
  continue;
@@ -22026,45 +22165,15 @@ ${open}`,
22026
22165
  return stopped;
22027
22166
  continue;
22028
22167
  }
22029
- let reviewedHere = false;
22168
+ let reviewedHere = reviewedHeads.has(pipeline.head) && (pipeline.approved === pipeline.head || unranAt.has(pipeline.head));
22030
22169
  if (unreviewed !== undefined) {
22031
- const files = unreviewed;
22032
- const head = pipeline.head;
22033
- yield* passTurn();
22034
- const reviewed = yield* call(`review:${cycle}`, reviewLoop(), {
22035
- base: `origin/${target}`,
22036
- head,
22037
- files: files.files,
22038
- ...head === files.synced ? undefined : { since: files.synced },
22039
- ...files.earlier.length === 0 ? undefined : { earlier: files.earlier }
22040
- });
22041
- if (reviewed.blocking) {
22042
- const blocking = reviewed.findings.filter(isBlocking);
22043
- if (!(yield* mayFix("head-fix", cycle, blocking.map((finding) => finding.id).join(", "))))
22044
- return handBack(`The review of the catch-up merge's files still finds ${blocking.map((finding) => finding.id).join(", ")} after ${rounds["head-fix"]} head-fix rounds`, findingLines2(blocking));
22045
- rounds["head-fix"]++;
22046
- const fix = yield* agentWork(`review-fix:${cycle}`, {
22047
- agent: "implementer",
22048
- prompt: reviewFixPrompt("the files the catch-up merge changed", blocking),
22049
- output: ReviewFix,
22050
- timeout: stepBudget
22051
- });
22052
- unreviewed = { ...files, earlier: reviewed.findings };
22053
- fixedFrom = { head, changed: fix.changed, looks: 0 };
22170
+ const reviewing = yield* reviewMergedFiles(cycle, pipeline.head, unreviewed);
22171
+ if (reviewing.kind === "stop")
22172
+ return reviewing.output;
22173
+ if (reviewing.kind === "fixing")
22054
22174
  continue;
22055
- }
22056
- const approval = yield* approveChangeRequest(`approve:${cycle}`, {
22057
- changeRequestId,
22058
- head,
22059
- summary: `A review of the files merging ${target} in changed (${files.files.join(", ")}) passed with nothing blocking.`,
22060
- review: `review:${cycle}`,
22061
- carries: files.sync
22062
- }).pipe(catchTag2("StepFailed", (error) => succeed7({ approved: false, reason: error.reason })));
22063
- unreviewed = undefined;
22064
- if (approval.approved)
22175
+ if (reviewing.kind === "approved")
22065
22176
  reviewedHere = true;
22066
- else
22067
- notCarried = `merging ${target} in, whose files' review passed but did not approve it: ${approval.reason}`;
22068
22177
  }
22069
22178
  const moved = pipeline.readAt === undefined ? [] : [
22070
22179
  { event: "change_request.pipeline", filter: { changeRequestId }, since: pipeline.readAt },
@@ -22088,66 +22197,13 @@ ${open}`,
22088
22197
  timeout: "1 minute"
22089
22198
  }).pipe(map8((woke) => woke.type === "change_request.approval" && woke.payload.source !== "kitman" ? undefined : woke), catchTag2("WaitTimedOut", () => undefined_2));
22090
22199
  if (!reviewedHere && approved === undefined) {
22091
- const head = pipeline.head;
22092
- const since = pipeline.approved === undefined || pipeline.approved === head ? undefined : pipeline.approved;
22093
- const reviewIt = leftToPerson.has(head) ? "Wait" : yield* ask(`unapproved:${cycle}`, {
22094
- prompt: `Nobody has approved ${head}, the head whose pipeline passed. Have Kitman review it?`,
22095
- options: [
22096
- {
22097
- value: "Review",
22098
- description: since === undefined ? "Kitman's Review reads the whole change at this head and approves it if nothing blocks." : `Kitman's Review reads what changed since ${since}, the last approved head, and approves it if nothing there blocks.`
22099
- },
22100
- { value: "Wait", description: "Waits for a person to approve this head." }
22101
- ],
22102
- recommended: "Review",
22103
- recommendationReason: "A passing Review of the change is what approved the head Build shipped.",
22104
- default: "Wait",
22105
- auto: "Review",
22106
- timeout: "1 hour"
22107
- });
22108
- yield* passTurn();
22109
- if (reviewIt === "Wait") {
22110
- leftToPerson.add(head);
22200
+ const reviewing = yield* reviewHead(cycle, pipeline, "the head whose pipeline passed");
22201
+ if (reviewing.kind === "stop")
22202
+ return reviewing.output;
22203
+ if (reviewing.kind === "fixing")
22204
+ continue;
22205
+ if (reviewing.kind === "left")
22111
22206
  approved = yield* waitFor(`approval:${cycle}`, { ...approval, timeout: "7 days" });
22112
- } else {
22113
- const { notRun: headNotRun } = yield* verifyHead(`head-verify:${cycle}`, head);
22114
- const notRun = [...new Set([...input.notRun ?? [], ...headNotRun])];
22115
- const reviewed = yield* call(`head-review:${cycle}`, reviewLoop(), {
22116
- base: `origin/${target}`,
22117
- head,
22118
- ...notRun.length === 0 ? undefined : { notRun },
22119
- ...since === undefined ? undefined : { approved: since },
22120
- ...headFindings.length === 0 ? undefined : { earlier: headFindings }
22121
- });
22122
- if (reviewed.blocking) {
22123
- const blocking = reviewed.findings.filter(isBlocking);
22124
- if (!(yield* mayFix("head-fix", cycle, blocking.map((finding) => finding.id).join(", "))))
22125
- return handBack(`The review of ${head} still finds ${blocking.map((finding) => finding.id).join(", ")} after ${rounds["head-fix"]} head-fix rounds`, findingLines2(blocking));
22126
- rounds["head-fix"]++;
22127
- const fix = yield* agentWork(`head-fix:${cycle}`, {
22128
- agent: "implementer",
22129
- prompt: reviewFixPrompt(since === undefined ? `the change at ${head}` : `what changed between ${since} and ${head}`, blocking),
22130
- output: ReviewFix,
22131
- timeout: stepBudget
22132
- });
22133
- headFindings = reviewed.findings;
22134
- fixedFrom = { head, changed: fix.changed, looks: 0 };
22135
- continue;
22136
- }
22137
- headFindings = [];
22138
- if (notRun.length > 0)
22139
- unranAt.set(head, { notRun, review: `head-review:${cycle}` });
22140
- else {
22141
- const recorded = yield* approveChangeRequest(`head-approve:${cycle}`, {
22142
- changeRequestId,
22143
- head,
22144
- summary: since === undefined ? `A review of the whole change at ${head} passed with nothing blocking.` : `A review of what changed between ${since}, the last approved head, and ${head} passed with nothing blocking.`,
22145
- review: `head-review:${cycle}`
22146
- }).pipe(catchTag2("StepFailed", (error) => succeed7({ approved: false, reason: error.reason })));
22147
- if (!recorded.approved)
22148
- return done("needs_you", `The review of ${head} passed, but did not approve it: ${recorded.reason}`);
22149
- }
22150
- }
22151
22207
  }
22152
22208
  if (approved !== undefined && approved.type !== "change_request.approval")
22153
22209
  continue;
@@ -30337,4 +30393,4 @@ var runKit = (config, identity, packages) => {
30337
30393
  runMain2(program.pipe(flatMap3((code) => sync2(() => process.exit(code)))));
30338
30394
  };
30339
30395
  // .kitman-build-entry.ts
30340
- runKit(kitman_config_default, { name: "@kitman-sh/software-engineering", version: "0.10.91" }, []);
30396
+ runKit(kitman_config_default, { name: "@kitman-sh/software-engineering", version: "0.10.92" }, []);
@@ -2705,7 +2705,7 @@
2705
2705
  {
2706
2706
  "id": "shepherd",
2707
2707
  "title": "Shepherd",
2708
- "version": "1.5.0",
2708
+ "version": "1.6.0",
2709
2709
  "input": {
2710
2710
  "type": "object",
2711
2711
  "properties": {
@@ -3528,7 +3528,7 @@
3528
3528
  "carried": [
3529
3529
  {
3530
3530
  "name": "@kitman-sh/software-engineering",
3531
- "version": "0.10.91",
3531
+ "version": "0.10.92",
3532
3532
  "setup": "2a237548a69b0cd53ec3be7f687cfa8c2128335b3a655d34e185f2abce6a3c37",
3533
3533
  "loops": [
3534
3534
  "build",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kitman-sh/software-engineering",
3
- "version": "0.10.91",
3
+ "version": "0.10.92",
4
4
  "description": "Everything for building software: Loops, their Agents, the skills they use and the Ponytail plugin.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
@@ -17,12 +17,12 @@
17
17
  "tsconfig.json"
18
18
  ],
19
19
  "dependencies": {
20
- "@kitman-sh/sdk": "0.10.91",
20
+ "@kitman-sh/sdk": "0.10.92",
21
21
  "effect": "^4.1.2"
22
22
  },
23
23
  "kitman": {
24
24
  "bundle": "dist/bundle.js",
25
- "digest": "59d1513c526ad394e8733d33c5b2e2137e5eb33ad65c020ffe5f23692697254c",
25
+ "digest": "4a0190c4cef68fdd251124779e541a4a9717be82e6f7e596a23dd5b1007901c8",
26
26
  "protocolVersion": 5,
27
27
  "declarations": "dist/declarations.json",
28
28
  "setup": {
package/src/shepherd.ts CHANGED
@@ -42,6 +42,12 @@ const reviewLoop = () => ({ id: 'review', input: ReviewInput, output: ReviewOutp
42
42
  /** The model time one fix or round of replies may take before a person looks. */
43
43
  const stepBudget = '45 minutes'
44
44
 
45
+ /** About one pipeline run: the longest it waits on a red target before it reads it again, for a push no Event announces. */
46
+ const pipelineRun = '10 minutes' as const
47
+
48
+ /** The reads of a red target one look takes, about an hour of them. */
49
+ const targetLooks = 6
50
+
45
51
  /** Rounds of each kind a Run takes before it asks whether to hand the ChangeRequest back to Build. */
46
52
  const roundLimits = { 'ci-fix': 1, 'head-fix': 2 } as const
47
53
 
@@ -196,13 +202,14 @@ const threadKey = (thread: ReviewThreads['threads'][number]) => `${thread.id}:${
196
202
  * and mergeable when told to or when a person says so. A branch the forge says conflicts or is behind merges its target
197
203
  * in before any pipeline is run or fixed, and one whose merge Shepherd cannot settle goes back to Build. It merges the
198
204
  * target in and merges only while it holds the target's turn, so ChangeRequests for one target land one at a time, in
199
- * order. A head nobody approved gets a review of what changed since the last approved head. It runs one ci-fix and two
205
+ * order. A head nobody approved gets a review of what changed since the last approved head, and the head a catch-up
206
+ * pushed gets its pipeline started and its review as soon as the forge shows it, not once its pipeline passes. It runs one ci-fix and two
200
207
  * head-fix rounds, each judged by the pipeline at the head the last fix pushed, then hands the ChangeRequest back to
201
208
  * Build, and stops as needs you, with why, instead of spinning.
202
209
  */
203
210
  export default defineLoop({
204
211
  id: 'shepherd',
205
- version: '1.5.0',
212
+ version: '1.6.0',
206
213
  title: 'Shepherd',
207
214
  input: Input,
208
215
  output: Output,
@@ -253,6 +260,13 @@ export default defineLoop({
253
260
  }
254
261
  | undefined
255
262
 
263
+ /** The head the last catch-up pushed, to review as soon as the forge shows it rather than once its pipeline passes. */
264
+ let reviewOnceShown: string | undefined
265
+ /** The head the last catch-up pushed, whose pipeline runs before Shepherd catches up again. */
266
+ let pipelineFirst: string | undefined
267
+ /** Heads Shepherd's own review passed, approved or left to a person for tests verify never ran. */
268
+ const reviewedHeads = new Set<string>()
269
+
256
270
  /** Why an approval of the head is still needed after a catch-up merge, for a person who is left to give it. */
257
271
  let notCarried: string | undefined
258
272
  // The last merge did not go in as the ChangeRequest is: its target moved on, or it conflicts.
@@ -463,7 +477,10 @@ export default defineLoop({
463
477
  text: `Shepherd is waiting for ${target} to change instead of fixing ${pipeline.head}: ${why}`
464
478
  }).pipe(Effect.catchTag('StepFailed', () => Effect.void))
465
479
 
466
- const woke = yield* waitFor(`target-moved:${cycle}`, {
480
+ // Only a read that names the target's head can tell a push straight to it, which makes no Event.
481
+ const targetHead = pipeline.target?.head
482
+
483
+ const mergedInto = {
467
484
  event: 'change_request.closed',
468
485
  filter: {
469
486
  merged: true,
@@ -471,16 +488,31 @@ export default defineLoop({
471
488
  ...(repository === undefined ? undefined : { repository })
472
489
  },
473
490
  or: [{ event: 'change_request.closed', filter: { changeRequestId } }],
474
- timeout: '1 hour',
491
+ timeout: targetHead === undefined ? ('1 hour' as const) : pipelineRun,
475
492
  ...(pipeline.readAt === undefined ? undefined : { since: pipeline.readAt })
476
- }).pipe(Effect.catchTag('WaitTimedOut', () => Effect.undefined))
493
+ }
494
+
495
+ let woke = yield* waitFor(`target-moved:${cycle}`, mergedInto).pipe(
496
+ Effect.catchTag('WaitTimedOut', () => Effect.undefined)
497
+ )
498
+
499
+ // Reading again each pipeline run is part of this one look, so it costs no look of its own.
500
+ for (let look = 2; woke === undefined && targetHead !== undefined && look <= targetLooks; look++) {
501
+ const again = yield* pipelineStatus(`target-read:${cycle}:${look}`, { changeRequestId })
502
+
503
+ if (again.head !== pipeline.head || again.target?.head !== targetHead) break
504
+
505
+ woke = yield* waitFor(`target-moved:${cycle}:${look}`, mergedInto).pipe(
506
+ Effect.catchTag('WaitTimedOut', () => Effect.undefined)
507
+ )
508
+ }
477
509
 
478
510
  if (woke?.payload.changeRequestId === changeRequestId)
479
511
  return woke.payload.merged === true
480
512
  ? done('merged', 'Someone else merged the ChangeRequest')
481
513
  : done('needs_you', 'The ChangeRequest was closed')
482
514
 
483
- redTarget = { head: pipeline.head, targetHead: pipeline.target?.head, moved: woke !== undefined }
515
+ redTarget = { head: pipeline.head, targetHead, moved: woke !== undefined }
484
516
 
485
517
  return undefined
486
518
  })
@@ -542,6 +574,8 @@ export default defineLoop({
542
574
  // The forge can show the old head for a moment after the push; the next look reads it once it shows this one.
543
575
  if (caught !== undefined) {
544
576
  pushed = { head: caught.head, stale: 0, by: 'the catch-up' }
577
+ reviewOnceShown = caught.head
578
+ pipelineFirst = caught.head
545
579
 
546
580
  if (targetHead !== undefined) syncedFor.add(syncedKey(caught.head, targetHead))
547
581
 
@@ -557,6 +591,194 @@ export default defineLoop({
557
591
  return undefined
558
592
  })
559
593
 
594
+ const stop = (output: Output) => ({ kind: 'stop', output }) as const
595
+
596
+ /**
597
+ * Reviews the files a catch-up merge settled, at `head`, and approves it on a pass: `fixing` when a fix round ran for
598
+ * its findings, `approved` or `unapproved` once the review passed, or `stop` with the Output.
599
+ */
600
+ const reviewMergedFiles = (cycle: number, head: string, files: NonNullable<typeof unreviewed>) =>
601
+ Effect.gen(function* () {
602
+ yield* passTurn()
603
+
604
+ const reviewed = yield* call(`review:${cycle}`, reviewLoop(), {
605
+ base: `origin/${target}`,
606
+ head,
607
+ files: files.files,
608
+ ...(head === files.synced ? undefined : { since: files.synced }),
609
+ ...(files.earlier.length === 0 ? undefined : { earlier: files.earlier })
610
+ })
611
+
612
+ if (reviewed.blocking) {
613
+ const blocking = reviewed.findings.filter(isBlocking)
614
+
615
+ if (!(yield* mayFix('head-fix', cycle, blocking.map(finding => finding.id).join(', '))))
616
+ return stop(
617
+ handBack(
618
+ `The review of the catch-up merge's files still finds ${blocking.map(finding => finding.id).join(', ')} after ${rounds['head-fix']} head-fix rounds`,
619
+ findingLines(blocking)
620
+ )
621
+ )
622
+ rounds['head-fix']++
623
+
624
+ const fix = yield* agentWork(`review-fix:${cycle}`, {
625
+ agent: 'implementer',
626
+ prompt: reviewFixPrompt('the files the catch-up merge changed', blocking),
627
+ output: ReviewFix,
628
+ timeout: stepBudget
629
+ })
630
+
631
+ unreviewed = { ...files, earlier: reviewed.findings }
632
+ fixedFrom = { head, changed: fix.changed, looks: 0 }
633
+
634
+ return { kind: 'fixing' } as const
635
+ }
636
+
637
+ const approval = yield* approveChangeRequest(`approve:${cycle}`, {
638
+ changeRequestId,
639
+ head,
640
+ summary: `A review of the files merging ${target} in changed (${files.files.join(', ')}) passed with nothing blocking.`,
641
+ review: `review:${cycle}`,
642
+ carries: files.sync
643
+ }).pipe(
644
+ Effect.catchTag('StepFailed', error => Effect.succeed({ approved: false as const, reason: error.reason }))
645
+ )
646
+
647
+ unreviewed = undefined
648
+
649
+ if (!approval.approved) {
650
+ notCarried = `merging ${target} in, whose files' review passed but did not approve it: ${approval.reason}`
651
+
652
+ return { kind: 'unapproved' } as const
653
+ }
654
+
655
+ reviewedHeads.add(head)
656
+
657
+ return { kind: 'approved' } as const
658
+ })
659
+
660
+ /**
661
+ * Has Kitman review the head of `pipeline`, which nobody approved, when a person or full auto says so, and approves
662
+ * it on a pass: `fixing` when a fix round ran for its findings, `left` when its approval is left to a person,
663
+ * `reviewed` once the review passed, or `stop` with the Output.
664
+ */
665
+ const reviewHead = (cycle: number, pipeline: PipelineStatus, which: string) =>
666
+ Effect.gen(function* () {
667
+ const head = pipeline.head
668
+ // Only what changed since the last approved head is unreviewed; the rest was approved as it stands.
669
+ const since = pipeline.approved === undefined || pipeline.approved === head ? undefined : pipeline.approved
670
+
671
+ const reviewIt = leftToPerson.has(head)
672
+ ? 'Wait'
673
+ : yield* ask(`unapproved:${cycle}`, {
674
+ prompt: `Nobody has approved ${head}, ${which}. Have Kitman review it?`,
675
+ options: [
676
+ {
677
+ value: 'Review',
678
+ description:
679
+ since === undefined
680
+ ? "Kitman's Review reads the whole change at this head and approves it if nothing blocks."
681
+ : `Kitman's Review reads what changed since ${since}, the last approved head, and approves it if nothing there blocks.`
682
+ },
683
+ { value: 'Wait', description: 'Waits for a person to approve this head.' }
684
+ ],
685
+ recommended: 'Review',
686
+ recommendationReason: 'A passing Review of the change is what approved the head Build shipped.',
687
+ default: 'Wait',
688
+ // A full-auto Team merges what its Review approved, including heads Shepherd pushed itself.
689
+ auto: 'Review',
690
+ timeout: '1 hour'
691
+ })
692
+
693
+ yield* passTurn()
694
+
695
+ if (reviewIt === 'Wait') {
696
+ leftToPerson.add(head)
697
+
698
+ return { kind: 'left' } as const
699
+ }
700
+
701
+ const { notRun: headNotRun } = yield* verifyHead(`head-verify:${cycle}`, head)
702
+ const notRun = [...new Set([...(input.notRun ?? []), ...headNotRun])]
703
+
704
+ const reviewed = yield* call(`head-review:${cycle}`, reviewLoop(), {
705
+ base: `origin/${target}`,
706
+ head,
707
+ ...(notRun.length === 0 ? undefined : { notRun }),
708
+ ...(since === undefined ? undefined : { approved: since }),
709
+ ...(headFindings.length === 0 ? undefined : { earlier: headFindings })
710
+ })
711
+
712
+ if (reviewed.blocking) {
713
+ const blocking = reviewed.findings.filter(isBlocking)
714
+
715
+ if (!(yield* mayFix('head-fix', cycle, blocking.map(finding => finding.id).join(', '))))
716
+ return stop(
717
+ handBack(
718
+ `The review of ${head} still finds ${blocking.map(finding => finding.id).join(', ')} after ${rounds['head-fix']} head-fix rounds`,
719
+ findingLines(blocking)
720
+ )
721
+ )
722
+ rounds['head-fix']++
723
+
724
+ const fix = yield* agentWork(`head-fix:${cycle}`, {
725
+ agent: 'implementer',
726
+ prompt: reviewFixPrompt(
727
+ since === undefined ? `the change at ${head}` : `what changed between ${since} and ${head}`,
728
+ blocking
729
+ ),
730
+ output: ReviewFix,
731
+ timeout: stepBudget
732
+ })
733
+
734
+ headFindings = reviewed.findings
735
+ fixedFrom = { head, changed: fix.changed, looks: 0 }
736
+
737
+ return { kind: 'fixing' } as const
738
+ }
739
+
740
+ headFindings = []
741
+
742
+ if (notRun.length > 0) unranAt.set(head, { notRun, review: `head-review:${cycle}` })
743
+ else {
744
+ const recorded = yield* approveChangeRequest(`head-approve:${cycle}`, {
745
+ changeRequestId,
746
+ head,
747
+ summary:
748
+ since === undefined
749
+ ? `A review of the whole change at ${head} passed with nothing blocking.`
750
+ : `A review of what changed between ${since}, the last approved head, and ${head} passed with nothing blocking.`,
751
+ review: `head-review:${cycle}`
752
+ }).pipe(
753
+ Effect.catchTag('StepFailed', error => Effect.succeed({ approved: false as const, reason: error.reason }))
754
+ )
755
+
756
+ if (!recorded.approved)
757
+ return stop(done('needs_you', `The review of ${head} passed, but did not approve it: ${recorded.reason}`))
758
+ }
759
+
760
+ reviewedHeads.add(head)
761
+
762
+ return { kind: 'reviewed' } as const
763
+ })
764
+
765
+ /** Reviews the head the last catch-up pushed, if `pipeline` shows it and it still needs a review. */
766
+ const reviewCaughtUp = (cycle: number, pipeline: PipelineStatus) =>
767
+ Effect.gen(function* () {
768
+ const head = reviewOnceShown
769
+
770
+ reviewOnceShown = undefined
771
+
772
+ if (head !== pipeline.head) return undefined
773
+
774
+ if (unreviewed !== undefined) return yield* reviewMergedFiles(cycle, head, unreviewed)
775
+
776
+ if (notCarried !== undefined && pipeline.approved !== head)
777
+ return yield* reviewHead(cycle, pipeline, 'the head its catch-up merge pushed')
778
+
779
+ return undefined
780
+ })
781
+
560
782
  return Effect.gen(function* () {
561
783
  for (let cycle = 1; ; cycle++) {
562
784
  if (cycle > (input.maxCycles ?? 20)) {
@@ -618,7 +840,37 @@ export default defineLoop({
618
840
  else return found
619
841
  }
620
842
 
621
- if (pipeline.conflicts === true || pipeline.needsRebase === true) {
843
+ const blocked = pipeline.conflicts === true || pipeline.needsRebase === true
844
+ const caughtUpHead = pipeline.head === pipelineFirst
845
+ // The forge runs no pipeline for this repository: its pipeline runs on a Runner and is reported to Kitman.
846
+ const onRunnerDue = pipeline.status === 'none' && pipeline.runnerChecks !== undefined
847
+
848
+ // Run this head's pipeline before reviewing it or catching up again.
849
+ if (onRunnerDue && (!blocked || caughtUpHead)) {
850
+ if (ranOnRunner.has(pipeline.head))
851
+ return done('needs_you', `The pipeline ran on the Runner at ${pipeline.head}, but no result was recorded`)
852
+ ranOnRunner.add(pipeline.head)
853
+
854
+ const ran = yield* runOnRunner('run', cycle, pipeline.head, pipeline.runnerChecks ?? [])
855
+
856
+ if ('failed' in ran) return done('needs_you', `The pipeline could not run on the Runner: ${ran.failed}`)
857
+
858
+ continue
859
+ }
860
+
861
+ // A catch-up's head is reviewed once the forge shows it, not once the target stops moving, so the next clean
862
+ // catch-up carries its approval. A head that may merge on this read is read again after its approval, which the
863
+ // merge gates would otherwise not see.
864
+ const reviewing = yield* reviewCaughtUp(cycle, pipeline)
865
+
866
+ if (reviewing?.kind === 'stop') return reviewing.output
867
+
868
+ const approvedHere = reviewing?.kind === 'approved' || reviewing?.kind === 'reviewed'
869
+
870
+ if (reviewing?.kind === 'fixing' || (approvedHere && !blocked && pipeline.status === 'success')) continue
871
+
872
+ // Wait for this head's running pipeline before catching up again.
873
+ if (blocked && !(pipeline.status === 'running' && caughtUpHead)) {
622
874
  const blocker = pipeline.conflicts === true ? `conflicts with ${target}` : `needs ${target} merged in`
623
875
  const targetHead = pipeline.target?.head
624
876
 
@@ -662,19 +914,6 @@ export default defineLoop({
662
914
  continue
663
915
  }
664
916
 
665
- // The forge runs no pipeline for this repository: its pipeline runs on a Runner and is reported to Kitman.
666
- if (pipeline.status === 'none' && pipeline.runnerChecks !== undefined) {
667
- if (ranOnRunner.has(pipeline.head))
668
- return done('needs_you', `The pipeline ran on the Runner at ${pipeline.head}, but no result was recorded`)
669
- ranOnRunner.add(pipeline.head)
670
-
671
- const ran = yield* runOnRunner('run', cycle, pipeline.head, pipeline.runnerChecks)
672
-
673
- if ('failed' in ran) return done('needs_you', `The pipeline could not run on the Runner: ${ran.failed}`)
674
-
675
- continue
676
- }
677
-
678
917
  if (pipeline.status === 'none' || pipeline.status === 'running') {
679
918
  yield* pipelineMoved(`wait:${cycle}`, changeRequestId, pipeline)
680
919
 
@@ -860,60 +1099,18 @@ export default defineLoop({
860
1099
  continue
861
1100
  }
862
1101
 
863
- let reviewedHere = false
1102
+ // Its own review approved a head only while this read still shows the approval: a request for changes takes it back.
1103
+ let reviewedHere =
1104
+ reviewedHeads.has(pipeline.head) && (pipeline.approved === pipeline.head || unranAt.has(pipeline.head))
864
1105
 
865
1106
  if (unreviewed !== undefined) {
866
- const files = unreviewed
867
- const head = pipeline.head
868
-
869
- yield* passTurn()
1107
+ const reviewing = yield* reviewMergedFiles(cycle, pipeline.head, unreviewed)
870
1108
 
871
- const reviewed = yield* call(`review:${cycle}`, reviewLoop(), {
872
- base: `origin/${target}`,
873
- head,
874
- files: files.files,
875
- ...(head === files.synced ? undefined : { since: files.synced }),
876
- ...(files.earlier.length === 0 ? undefined : { earlier: files.earlier })
877
- })
878
-
879
- if (reviewed.blocking) {
880
- const blocking = reviewed.findings.filter(isBlocking)
1109
+ if (reviewing.kind === 'stop') return reviewing.output
881
1110
 
882
- if (!(yield* mayFix('head-fix', cycle, blocking.map(finding => finding.id).join(', '))))
883
- return handBack(
884
- `The review of the catch-up merge's files still finds ${blocking.map(finding => finding.id).join(', ')} after ${rounds['head-fix']} head-fix rounds`,
885
- findingLines(blocking)
886
- )
887
- rounds['head-fix']++
1111
+ if (reviewing.kind === 'fixing') continue
888
1112
 
889
- const fix = yield* agentWork(`review-fix:${cycle}`, {
890
- agent: 'implementer',
891
- prompt: reviewFixPrompt('the files the catch-up merge changed', blocking),
892
- output: ReviewFix,
893
- timeout: stepBudget
894
- })
895
-
896
- unreviewed = { ...files, earlier: reviewed.findings }
897
- fixedFrom = { head, changed: fix.changed, looks: 0 }
898
-
899
- continue
900
- }
901
-
902
- const approval = yield* approveChangeRequest(`approve:${cycle}`, {
903
- changeRequestId,
904
- head,
905
- summary: `A review of the files merging ${target} in changed (${files.files.join(', ')}) passed with nothing blocking.`,
906
- review: `review:${cycle}`,
907
- carries: files.sync
908
- }).pipe(
909
- Effect.catchTag('StepFailed', error => Effect.succeed({ approved: false as const, reason: error.reason }))
910
- )
911
-
912
- unreviewed = undefined
913
-
914
- if (approval.approved) reviewedHere = true
915
- else
916
- notCarried = `merging ${target} in, whose files' review passed but did not approve it: ${approval.reason}`
1113
+ if (reviewing.kind === 'approved') reviewedHere = true
917
1114
  }
918
1115
 
919
1116
  // A newer head's finished pipeline goes round again, to gate that head and wait for its own approval. A
@@ -961,97 +1158,14 @@ export default defineLoop({
961
1158
  )
962
1159
 
963
1160
  if (!reviewedHere && approved === undefined) {
964
- const head = pipeline.head
965
- // Only what changed since the last approved head is unreviewed; the rest was approved as it stands.
966
- const since = pipeline.approved === undefined || pipeline.approved === head ? undefined : pipeline.approved
967
-
968
- const reviewIt = leftToPerson.has(head)
969
- ? 'Wait'
970
- : yield* ask(`unapproved:${cycle}`, {
971
- prompt: `Nobody has approved ${head}, the head whose pipeline passed. Have Kitman review it?`,
972
- options: [
973
- {
974
- value: 'Review',
975
- description:
976
- since === undefined
977
- ? "Kitman's Review reads the whole change at this head and approves it if nothing blocks."
978
- : `Kitman's Review reads what changed since ${since}, the last approved head, and approves it if nothing there blocks.`
979
- },
980
- { value: 'Wait', description: 'Waits for a person to approve this head.' }
981
- ],
982
- recommended: 'Review',
983
- recommendationReason: 'A passing Review of the change is what approved the head Build shipped.',
984
- default: 'Wait',
985
- // A full-auto Team merges what its Review approved, including heads Shepherd pushed itself.
986
- auto: 'Review',
987
- timeout: '1 hour'
988
- })
989
-
990
- yield* passTurn()
991
-
992
- if (reviewIt === 'Wait') {
993
- leftToPerson.add(head)
994
- approved = yield* waitFor(`approval:${cycle}`, { ...approval, timeout: '7 days' })
995
- } else {
996
- const { notRun: headNotRun } = yield* verifyHead(`head-verify:${cycle}`, head)
997
- const notRun = [...new Set([...(input.notRun ?? []), ...headNotRun])]
998
-
999
- const reviewed = yield* call(`head-review:${cycle}`, reviewLoop(), {
1000
- base: `origin/${target}`,
1001
- head,
1002
- ...(notRun.length === 0 ? undefined : { notRun }),
1003
- ...(since === undefined ? undefined : { approved: since }),
1004
- ...(headFindings.length === 0 ? undefined : { earlier: headFindings })
1005
- })
1006
-
1007
- if (reviewed.blocking) {
1008
- const blocking = reviewed.findings.filter(isBlocking)
1009
-
1010
- if (!(yield* mayFix('head-fix', cycle, blocking.map(finding => finding.id).join(', '))))
1011
- return handBack(
1012
- `The review of ${head} still finds ${blocking.map(finding => finding.id).join(', ')} after ${rounds['head-fix']} head-fix rounds`,
1013
- findingLines(blocking)
1014
- )
1015
- rounds['head-fix']++
1016
-
1017
- const fix = yield* agentWork(`head-fix:${cycle}`, {
1018
- agent: 'implementer',
1019
- prompt: reviewFixPrompt(
1020
- since === undefined ? `the change at ${head}` : `what changed between ${since} and ${head}`,
1021
- blocking
1022
- ),
1023
- output: ReviewFix,
1024
- timeout: stepBudget
1025
- })
1026
-
1027
- headFindings = reviewed.findings
1028
- fixedFrom = { head, changed: fix.changed, looks: 0 }
1161
+ const reviewing = yield* reviewHead(cycle, pipeline, 'the head whose pipeline passed')
1029
1162
 
1030
- continue
1031
- }
1163
+ if (reviewing.kind === 'stop') return reviewing.output
1032
1164
 
1033
- headFindings = []
1034
-
1035
- if (notRun.length > 0) unranAt.set(head, { notRun, review: `head-review:${cycle}` })
1036
- else {
1037
- const recorded = yield* approveChangeRequest(`head-approve:${cycle}`, {
1038
- changeRequestId,
1039
- head,
1040
- summary:
1041
- since === undefined
1042
- ? `A review of the whole change at ${head} passed with nothing blocking.`
1043
- : `A review of what changed between ${since}, the last approved head, and ${head} passed with nothing blocking.`,
1044
- review: `head-review:${cycle}`
1045
- }).pipe(
1046
- Effect.catchTag('StepFailed', error =>
1047
- Effect.succeed({ approved: false as const, reason: error.reason })
1048
- )
1049
- )
1165
+ if (reviewing.kind === 'fixing') continue
1050
1166
 
1051
- if (!recorded.approved)
1052
- return done('needs_you', `The review of ${head} passed, but did not approve it: ${recorded.reason}`)
1053
- }
1054
- }
1167
+ if (reviewing.kind === 'left')
1168
+ approved = yield* waitFor(`approval:${cycle}`, { ...approval, timeout: '7 days' })
1055
1169
  }
1056
1170
 
1057
1171
  if (approved !== undefined && approved.type !== 'change_request.approval') continue