@kitman-sh/software-engineering 0.18.0 → 0.19.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kitman-sh/software-engineering",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
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": "SEE LICENSE IN LICENSE.md",
@@ -19,12 +19,12 @@
19
19
  "LICENSE.md"
20
20
  ],
21
21
  "dependencies": {
22
- "@kitman-sh/sdk": "0.18.0",
22
+ "@kitman-sh/sdk": "0.19.0",
23
23
  "effect": "^4.1.2"
24
24
  },
25
25
  "kitman": {
26
26
  "bundle": "dist/bundle.js",
27
- "digest": "32734b822de538ce7230a3ffee78f6d576f232962e01fcd683fcce59f5d9d116",
27
+ "digest": "db8059f5e1104c2b8d38527a488aee1c77f0450c8713b95a0f985f7c4af6b834",
28
28
  "protocolVersion": 5,
29
29
  "declarations": "dist/declarations.json",
30
30
  "setup": {
package/src/shepherd.ts CHANGED
@@ -85,6 +85,12 @@ const pipelineRun = '10 minutes' as const
85
85
  /** The reads of a red target one look takes, about an hour of them. */
86
86
  const targetLooks = 6
87
87
 
88
+ /** The reads of a red target before which its failing checks run there again: about 10, 20 and 40 minutes in. */
89
+ const targetRechecks: readonly number[] = [2, 3, 5]
90
+
91
+ /** A steer queued for the Run's next agent Step, which wakes a wait on the target. */
92
+ const steered = { event: 'run.steered' } as const
93
+
88
94
  /** How long one look waits, left for a person to merge, for the target to move before it reads the ChangeRequest again. */
89
95
  const watchLook = '6 hours' as const
90
96
 
@@ -185,11 +191,94 @@ const failedJobs = (pipeline: PipelineStatus) =>
185
191
  const failingJobs = (pipeline: PipelineStatus) =>
186
192
  pipeline.jobs.flatMap(job => (job.status === 'failed' ? [job.name] : []))
187
193
 
188
- /** The failing checks the head of the target branch fails too, and those it passes; any other is not known. */
189
- const OnTarget = Schema.Struct({ failed: Schema.Array(Schema.String), passed: Schema.Array(Schema.String) })
194
+ /**
195
+ * The failing checks the head of the target branch fails too, and those it passes; any other is not known. `timedOut`
196
+ * failed there only by timing out, which is not a failure the target is known to share.
197
+ */
198
+ const OnTarget = Schema.Struct({
199
+ failed: Schema.Array(Schema.String),
200
+ passed: Schema.Array(Schema.String),
201
+ timedOut: Schema.optional(Schema.Array(Schema.String))
202
+ })
190
203
 
191
204
  type OnTarget = typeof OnTarget.Type
192
205
 
206
+ const timedOutLine = /\b(?:Test|Hook) timed out in \d+ ?ms\b/u
207
+
208
+ /** A test runner's line naming a failed test or suite, as Vitest prints it before the error. */
209
+ const failLine = /^\s*FAIL\s+(.+?)\s*$/u
210
+
211
+ /** `bun run --parallel`'s prefix on each line a command printed. */
212
+ const parallelPrefix = /^\S(?:(?! +\| ).)* +\| ?/u
213
+
214
+ const parallelHeader = /^Failed in parallel: (.*)$/u
215
+
216
+ /** The tests each failure block of a tail names, and whether the block's error is a timeout. */
217
+ const failureBlocks = (lines: readonly string[]) => {
218
+ const blocks: { names: string[]; timedOut: boolean | undefined }[] = []
219
+ let current: { names: string[]; timedOut: boolean | undefined } | undefined
220
+
221
+ for (const line of lines) {
222
+ const failed = failLine.exec(line)
223
+
224
+ if (failed !== null) {
225
+ if (current === undefined || current.timedOut !== undefined) {
226
+ current = { names: [], timedOut: undefined }
227
+ blocks.push(current)
228
+ }
229
+
230
+ current.names.push(failed[1] ?? '')
231
+ } else if (current !== undefined && current.timedOut === undefined && line.trim() !== '')
232
+ current.timedOut = timedOutLine.test(line)
233
+ }
234
+
235
+ return blocks
236
+ }
237
+
238
+ const namedBy = (test: string, name: string) =>
239
+ test === name || test.startsWith(`${name} > `) || name.endsWith(` > ${test}`)
240
+
241
+ /**
242
+ * Whether a failed check failed only by timing out, as a test or hook on a loaded Runner: one command failed, and its
243
+ * tail shows each failed test it names under a failure whose error is a timeout, and no other failure.
244
+ */
245
+ const onlyTimedOut = (check: {
246
+ readonly outputTail?: string | undefined
247
+ readonly failedTests?: readonly string[]
248
+ }) => {
249
+ const failedTests = check.failedTests ?? []
250
+ const lines = (check.outputTail ?? '').split('\n')
251
+ const header = parallelHeader.exec(lines[0] ?? '')
252
+
253
+ if (failedTests.length === 0 || (header !== null && header[1]?.includes('; ') === true)) return false
254
+
255
+ const blocks = failureBlocks(header === null ? lines : lines.map(line => line.replace(parallelPrefix, '')))
256
+ const timedOut = blocks.filter(block => block.timedOut === true).flatMap(block => block.names)
257
+
258
+ return (
259
+ blocks.every(block => block.timedOut === true) &&
260
+ failedTests.every(test => timedOut.some(name => namedBy(test, name)))
261
+ )
262
+ }
263
+
264
+ const listed = (names: readonly string[]) => names.join(', ')
265
+
266
+ /** Why a target that fails or times out on every failing check is waited out rather than fixed. */
267
+ const redTargetWhy = (target: string, head: string, failing: readonly string[], onTarget: OnTarget) => {
268
+ const failed = failing.filter(name => onTarget.failed.includes(name))
269
+ const timedOut = failing.filter(name => (onTarget.timedOut ?? []).includes(name))
270
+ const rerun = `Shepherd runs ${listed(timedOut)} there again after a wait rather than fixing ${head}`
271
+
272
+ if (failed.length === 0)
273
+ return `${target} only timed out on ${listed(timedOut)} at its own head, which reads as a loaded Runner rather than a failure it shares: ${rerun}`
274
+
275
+ const shared = `${target} fails ${listed(failed)} at its own head too, so no fix here can mend it`
276
+
277
+ return timedOut.length === 0
278
+ ? shared
279
+ : `${shared}; ${listed(timedOut)} only timed out there, which is not a failure it is known to share: ${rerun}`
280
+ }
281
+
193
282
  const ciFixPrompt = (pipeline: PipelineStatus, target: string, onTarget: OnTarget) => {
194
283
  const unknown = failingJobs(pipeline).filter(
195
284
  name => !onTarget.failed.includes(name) && !onTarget.passed.includes(name)
@@ -209,6 +298,11 @@ const ciFixPrompt = (pipeline: PipelineStatus, target: string, onTarget: OnTarge
209
298
  : [
210
299
  `${onTarget.failed.join(', ')} fail at the head of \`origin/${target}\` too: they are the target's to fix, so leave them as they are.`
211
300
  ]),
301
+ ...(onTarget.timedOut === undefined || onTarget.timedOut.length === 0
302
+ ? []
303
+ : [
304
+ `${onTarget.timedOut.join(', ')} only timed out at the head of \`origin/${target}\`, so whether they fail there is not known.`
305
+ ]),
212
306
  ...(unknown.length === 0
213
307
  ? []
214
308
  : [
@@ -490,10 +584,10 @@ export class TargetPassed extends Schema.TaggedClass<TargetPassed>()('TargetPass
490
584
  export class TargetMoved extends Schema.TaggedClass<TargetMoved>()('TargetMoved', {}) {}
491
585
 
492
586
  /** A wait for the target to move, and the Event that ended it, when one did. */
493
- export class Waited extends Schema.TaggedClass<Waited>()('Waited', {
494
- woke: Schema.optional(LoopEvent),
495
- read: Schema.optional(PipelineStatus)
496
- }) {}
587
+ export class Waited extends Schema.TaggedClass<Waited>()('Waited', { woke: Schema.optional(LoopEvent) }) {}
588
+
589
+ /** The failing checks run again at a red target that never moved, and those of them that passed there. */
590
+ export class Rechecked extends Schema.TaggedClass<Rechecked>()('Rechecked', { passing: Schema.Array(Schema.String) }) {}
497
591
 
498
592
  const withAdded = (list: readonly string[], item: string) => (list.includes(item) ? list : [...list, item])
499
593
 
@@ -618,6 +712,16 @@ const mergedInto = (charge: Charge, repository: string | undefined, since: strin
618
712
  ...(since === undefined ? undefined : { since })
619
713
  })
620
714
 
715
+ /**
716
+ * A wait on a red target: a merge into it, this ChangeRequest closing, or a steer sent since `since` that nobody else
717
+ * would read.
718
+ */
719
+ const redTargetWait = (charge: Charge, repository: string | undefined, since: string | undefined) => {
720
+ const merged = mergedInto(charge, repository, since)
721
+
722
+ return { ...merged, or: [...merged.or, { ...steered, ...(since === undefined ? undefined : { since }) }] }
723
+ }
724
+
621
725
  /** How a wait for the target ended this ChangeRequest, when the Event that woke it closed this one. */
622
726
  const closedBy = (charge: Charge, at: Shepherding, woke: LoopEvent | undefined, mergedBy: string) =>
623
727
  woke?.payload.changeRequestId !== charge.changeRequestId
@@ -962,31 +1066,58 @@ export const targetChecked = step('targetChecked', {
962
1066
 
963
1067
  if (onRunner.length === 0) return { failed, passed }
964
1068
 
965
- const atTarget = yield* verify('target-check', { revision: `origin/${charge.target}`, checks: onRunner }).pipe(
966
- Effect.catchTag('StepFailed', () => Effect.undefined)
967
- )
1069
+ // A failure at the target's tree is run again, not reused: a red target holds the Run until it passes.
1070
+ const atTarget = yield* verify('target-check', {
1071
+ revision: `origin/${charge.target}`,
1072
+ checks: onRunner,
1073
+ rerunFailed: true
1074
+ }).pipe(Effect.catchTag('StepFailed', () => Effect.undefined))
968
1075
 
969
1076
  const ran = atTarget?.checks.filter(check => onRunner.includes(check.name)) ?? []
1077
+ const timedOut = ran.flatMap(check => (check.status === 'failed' && onlyTimedOut(check) ? [check.name] : []))
970
1078
 
971
1079
  return {
972
- failed: [...failed, ...ran.flatMap(check => (check.status === 'failed' ? [check.name] : []))],
973
- passed: [...passed, ...ran.flatMap(check => (check.status === 'passed' ? [check.name] : []))]
1080
+ failed: [
1081
+ ...failed,
1082
+ ...ran.flatMap(check => (check.status === 'failed' && !timedOut.includes(check.name) ? [check.name] : []))
1083
+ ],
1084
+ passed: [...passed, ...ran.flatMap(check => (check.status === 'passed' ? [check.name] : []))],
1085
+ ...(timedOut.length === 0 ? undefined : { timedOut })
974
1086
  }
975
1087
  })
976
1088
  })
977
1089
 
978
- /** Reads a red target again, a pipeline run after the last wait, and waits once more while nothing moved. */
1090
+ /**
1091
+ * Reads a red target again, a pipeline run after the last wait. While nothing moved it runs the failing checks there
1092
+ * again when `recheck` asks, and waits once more unless one passed.
1093
+ */
979
1094
  export const targetReread = step('targetReread', {
980
- payload: { charge: Charge, repository: Schema.optional(Schema.String), pipeline: PipelineStatus },
981
- success: Schema.Union([TargetMoved, Waited]),
982
- run: ({ charge, repository, pipeline }) =>
1095
+ payload: {
1096
+ charge: Charge,
1097
+ repository: Schema.optional(Schema.String),
1098
+ pipeline: PipelineStatus,
1099
+ recheck: Schema.optional(Schema.Boolean)
1100
+ },
1101
+ success: Schema.Union([TargetMoved, Rechecked, Waited]),
1102
+ run: ({ charge, repository, pipeline, recheck }) =>
983
1103
  Effect.gen(function* () {
984
1104
  const again = yield* pipelineStatus('target-read', { changeRequestId: charge.changeRequestId })
985
1105
 
986
1106
  if (again.head !== pipeline.head || again.target?.head !== pipeline.target?.head) return new TargetMoved()
987
1107
 
1108
+ if (recheck === true) {
1109
+ const onTarget = yield* targetChecked({
1110
+ charge,
1111
+ pipeline: again.target === undefined ? pipeline : { ...pipeline, target: again.target }
1112
+ })
1113
+
1114
+ const passing = failingJobs(pipeline).filter(name => onTarget.passed.includes(name))
1115
+
1116
+ if (passing.length > 0) return new Rechecked({ passing })
1117
+ }
1118
+
988
1119
  const woke = yield* waitFor('target-moved', {
989
- ...mergedInto(charge, repository, pipeline.readAt),
1120
+ ...redTargetWait(charge, repository, pipeline.readAt),
990
1121
  timeout: pipelineRun
991
1122
  }).pipe(Effect.catchTag('WaitTimedOut', () => Effect.undefined))
992
1123
 
@@ -1010,23 +1141,50 @@ export const waitedOut = step('waitedOut', {
1010
1141
  const targetHead = pipeline.target?.head
1011
1142
 
1012
1143
  const first = yield* waitFor('target-moved', {
1013
- ...mergedInto(charge, at.repository, pipeline.readAt),
1014
- timeout: targetHead === undefined ? '1 hour' : pipelineRun
1144
+ ...redTargetWait(charge, at.repository, pipeline.readAt),
1145
+ timeout: pipelineRun
1015
1146
  }).pipe(Effect.catchTag('WaitTimedOut', () => Effect.undefined))
1016
1147
 
1148
+ const failing = failingJobs(pipeline)
1149
+
1017
1150
  const wokeBy = (woke: LoopEvent | undefined) =>
1018
1151
  closedBy(charge, at, woke, 'Someone else') ??
1019
1152
  new Again({ at: { ...at, redTarget: { head: pipeline.head, targetHead, moved: woke !== undefined } } })
1020
1153
 
1021
- if (first !== undefined || targetHead === undefined) return wokeBy(first)
1154
+ // Going round with `redTarget` as it stands merges in a target that moved, else checks it there again.
1155
+ const steerRead = Effect.as(
1156
+ note('steer-read', {
1157
+ text: `Shepherd read a steer while it waited for ${charge.target}: it weighs the failure at ${pipeline.head} again now, merging in ${charge.target} if it moved, else running ${listed(failing)} there once more. An agent Step reads the steer's words when one runs; while ${charge.target} still fails as ${pipeline.head} does, none does.`
1158
+ }).pipe(Effect.catchTag('StepFailed', () => Effect.void)),
1159
+ wokeBy(undefined)
1160
+ )
1161
+
1162
+ const ended = (woke: LoopEvent | undefined) =>
1163
+ woke?.type === steered.event ? steerRead : Effect.succeed(wokeBy(woke))
1164
+
1165
+ if (first !== undefined) return yield* ended(first)
1022
1166
 
1023
1167
  // Reading again each pipeline run is part of this one look, so it costs no look of its own.
1024
1168
  for (let look = 2; look <= targetLooks; look++) {
1025
- const again = yield* targetReread({ charge, repository: at.repository, pipeline })
1169
+ const again = yield* targetReread({
1170
+ charge,
1171
+ repository: at.repository,
1172
+ pipeline,
1173
+ recheck: targetRechecks.includes(look)
1174
+ })
1026
1175
 
1027
1176
  if (again._tag === 'TargetMoved') return wokeBy(undefined)
1028
1177
 
1029
- if (again.woke !== undefined) return wokeBy(again.woke)
1178
+ if (again._tag === 'Rechecked') {
1179
+ yield* note('target-rechecked', {
1180
+ text: `${charge.target} passes ${listed(again.passing)} now, run again at the same head: Shepherd stops waiting and weighs the failure at ${pipeline.head} again`
1181
+ }).pipe(Effect.catchTag('StepFailed', () => Effect.void))
1182
+
1183
+ // Going round without `redTarget` weighs the failure afresh, as this branch's own: a ci-fix.
1184
+ return new Again({ at: { ...at, redTarget: undefined } })
1185
+ }
1186
+
1187
+ if (again.woke !== undefined) return yield* ended(again.woke)
1030
1188
  }
1031
1189
 
1032
1190
  return wokeBy(undefined)
@@ -1771,13 +1929,10 @@ const failureWeighed = (charge: Charge, at: Shepherding, pipeline: PipelineStatu
1771
1929
  const onTarget = yield* targetChecked({ charge, pipeline })
1772
1930
  const failing = failingJobs(pipeline)
1773
1931
 
1774
- if (failing.length > 0 && failing.every(name => onTarget.failed.includes(name)))
1775
- return yield* waitedOut({
1776
- charge,
1777
- at,
1778
- pipeline,
1779
- why: `${target} fails ${failing.join(', ')} at its own head too, so no fix here can mend it`
1780
- })
1932
+ const redAtTarget = [...onTarget.failed, ...(onTarget.timedOut ?? [])]
1933
+
1934
+ if (failing.length > 0 && failing.every(name => redAtTarget.includes(name)))
1935
+ return yield* waitedOut({ charge, at, pipeline, why: redTargetWhy(target, head, failing, onTarget) })
1781
1936
 
1782
1937
  // The target passes now what it failed, with nothing merged that this read shows: merge it in.
1783
1938
  if (onTarget.passed.length > 0 && redTarget?.head === head)