@kitman-sh/software-engineering 0.14.8 → 0.15.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/build.ts CHANGED
@@ -1,269 +1,46 @@
1
1
  import {
2
- agentWork,
3
- ask,
4
- agentWorkOnce,
5
- approveChangeRequest,
6
- ApproveChangeRequestResult,
7
- call,
8
- CheckName,
9
- Continuing,
10
- continuingBrief,
11
- deliveryBase,
12
- ResolvedDeliveryTarget,
13
- syncBase,
14
- changeRequest,
15
- ChangeRequestResult,
16
- comment,
17
- defineLoop,
18
2
  type CalledLoop,
3
+ defineLoop,
4
+ deliveryBase,
19
5
  evidenceGate,
20
6
  failsOn,
21
7
  isBlocking,
22
- LoopOutcome,
23
- note,
24
- rallyStop,
25
- Rebuttal,
26
- settleRound,
8
+ type LoopOutcome,
9
+ runContext,
27
10
  testsNotRunReasons,
28
- verify,
29
- writeBack,
30
- type Disputed,
31
- MergedFinding,
32
- type RallyDecision,
33
- type SettledRound,
34
- type VerifyResult
11
+ writeBack
35
12
  } from '@kitman-sh/sdk/loop'
36
13
  import * as Effect from 'effect/Effect'
37
14
  import * as Schema from 'effect/Schema'
38
- import {
39
- brokenChecks,
40
- changeRequestBody,
41
- checkFindings,
42
- isCheckFinding,
43
- scopeFindings,
44
- unsettledItems
45
- } from './change-request-body'
46
- import { blockingCount, rebuildRefusal } from './convergence'
47
- import {
48
- caseOf,
49
- inCase,
50
- listedCases,
51
- numberedCases,
52
- OutOfScopeFinding,
53
- outOfScopeCase,
54
- outOfScopeLines
55
- } from './out-of-scope'
15
+ import { BuildInput, BuildOutput, type Built, type CriterionAnswer } from './build-schemas'
16
+ import { brokenChecks, changeRequestBody, codeFindings, unsettledItems } from './change-request-body'
17
+ import { epicOf, ownDeliveryTarget } from './delivery'
18
+ import { implemented, type Implemented } from './implemented'
19
+ import { landed } from './landed'
20
+ import { opened } from './opened'
21
+ import { caseOf, inCase, listedCases, outOfScopeLines } from './out-of-scope'
22
+ import { rallied } from './rallied'
23
+ import { reproduced } from './reproduced'
56
24
  import review from './review'
57
- import { ReviewedScope } from './reviewed-scope'
25
+ import type { ReviewedScope } from './reviewed-scope'
58
26
  import shepherd from './shepherd'
59
- import { ShepherdOutput } from './shepherd-output'
60
- import { DeliveryFields, epicOf, ownDeliveryTarget } from './delivery'
61
- import { ChangeRequestSummary, Reason, ShortStatement } from './text-limits'
62
-
63
- export const BuildInput = Schema.Struct({
64
- /** What to build, when no Task says it. */
65
- words: Schema.optional(Schema.String),
66
- taskId: Schema.optional(Schema.String),
67
- repoBindingId: Schema.optional(Schema.String),
68
- /**
69
- * The base branch; the repository's default branch when left out. Kitman reads an earlier Run's branch as where the
70
- * Build starts and puts the branch it merges into here instead.
71
- */
72
- branch: Schema.optional(Schema.String),
73
- /** Where to start; the head of `branch` when left out. */
74
- revision: Schema.optional(Schema.String),
75
- outcome: Schema.optional(LoopOutcome),
76
- /** Review rounds before the rally stops; 3 when left out. */
77
- maxRounds: Schema.optional(Schema.Int),
78
- /** The Task's open ChangeRequest an earlier Run left, which this Build fixes forward instead of rebuilding. */
79
- continuing: Schema.optional(Continuing),
80
- /** Sees the ChangeRequest through to merge with Shepherd once it opens; false leaves it open for a person. */
81
- land: Schema.optional(Schema.Boolean),
82
- /**
83
- * An open ChangeRequest to fix forward on: the Run works its branch, never force-pushing, and reports in one comment
84
- * on it, leaving the ChangeRequest's title and description to its author.
85
- */
86
- changeRequestId: Schema.optional(Schema.String),
87
- /**
88
- * How many more Builds an unattended full-auto Run starts on its ChangeRequest while review findings still stand,
89
- * before it fails with them; 1 when left out. None starts after Review rounds that were not converging.
90
- */
91
- maxRebuilds: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
92
- /** The head an earlier review read, whose `earlier` findings this Build fixes: its first review reviews the fix. */
93
- reviewed: Schema.optional(Schema.String),
94
- earlier: Schema.optional(Schema.Array(MergedFinding)),
95
- outOfScopeFindings: Schema.optional(Schema.Array(OutOfScopeFinding)),
96
- taskOutOfScope: Schema.optional(Schema.Array(Schema.String)),
97
- /** That review's scope judgement, whose unmet items this Build's first review judges again. */
98
- scope: Schema.optional(ReviewedScope),
99
- /**
100
- * Plan review passed the Task, and this is its first implementation, which the `planned-implementer` makes; Kitman
101
- * sets it when the Run starts.
102
- */
103
- planReviewed: Schema.optional(Schema.Boolean),
104
- ...DeliveryFields
105
- })
106
-
107
- /** The implementer's answer to one acceptance criterion of the Task. */
108
- const CriterionAnswer = Schema.Struct({
109
- criterion: Schema.String,
110
- status: Schema.Literals(['met', 'after_merge', 'not_met']),
111
- /** The test or file that shows it met, or why it is after merge or not met. */
112
- detail: ShortStatement,
113
- ...outOfScopeCase
114
- })
115
-
116
- type CriterionAnswer = typeof CriterionAnswer.Type
117
-
118
- const Criteria = Schema.Struct({ criteria: Schema.Array(CriterionAnswer) })
119
-
120
- export const SuggestedCheck = Schema.Struct({
121
- name: CheckName,
122
- command: Schema.String,
123
- workingDirectory: Schema.optionalKey(Schema.String)
124
- })
125
-
126
- const Implemented = Schema.Struct({
127
- /** The ChangeRequest's title. */
128
- title: Schema.String,
129
- summary: ChangeRequestSummary,
130
- claims: Schema.Array(ShortStatement),
131
- /** The approved checks that run the documented commands, for a docs Outcome. */
132
- documented: Schema.optional(Schema.Array(Schema.String)),
133
- /** The approved check that rolls a migration back. */
134
- rollback: Schema.optional(Schema.String),
135
- /** Each acceptance criterion of the Task, answered; empty when it has none, left out when building from words. */
136
- criteria: Schema.optional(Schema.Array(CriterionAnswer)),
137
- /** Checks to run when the repository has none approved, from its package scripts or CI config. */
138
- checks: Schema.optional(Schema.Array(SuggestedCheck))
139
- })
140
-
141
- const Reproduced = Schema.Struct({
142
- /** The check that runs only the test reproducing the bug; verify runs it on the base and on each head. */
143
- check: SuggestedCheck,
144
- summary: ChangeRequestSummary
145
- })
146
-
147
- /** A bug's proof; a continued Build recovers it from the branch an earlier Run left. */
148
- const ReproducedOnBranch = Schema.Struct({
149
- ...Reproduced.fields,
150
- /** The branch's commit where the reproducing test is in place and the fix is not yet; the head when none is. */
151
- revision: Schema.optional(Schema.String)
152
- })
153
-
154
- const FixRebuttal = Schema.Struct({ ...Rebuttal.fields, reason: Reason })
27
+ import { BuildBlocked, standing } from './standing'
28
+ import { SuggestedCheck } from './suggested-check'
155
29
 
156
- const Fixed = Schema.Struct({
157
- summary: ChangeRequestSummary,
158
- claims: Schema.Array(ShortStatement),
159
- rebuttals: Schema.Array(FixRebuttal)
160
- })
161
-
162
- export const BuildOutput = Schema.Struct({
163
- changeRequest: ChangeRequestResult,
164
- revision: Schema.String,
165
- tree: Schema.String,
166
- settled: Schema.Boolean,
167
- unsettled: Schema.Array(Schema.String),
168
- rounds: Schema.Int,
169
- stopped: Schema.Literals(['settled', 'dispute_stands', 'findings_returned', 'round_cap']),
170
- criteria: Schema.Array(CriterionAnswer),
171
- /** Why each head test verify never ran is unverified; absent when it ran them all. */
172
- notRun: Schema.optional(Schema.Array(Schema.String)),
173
- /** The last review's code findings still open or disputed, which a Build fixing them takes as `earlier`. */
174
- findings: Schema.optional(Schema.Array(MergedFinding)),
175
- /** The reviews' findings kept apart as out of scope, which a Build fixing what it left takes as its own. */
176
- outOfScopeFindings: Schema.optional(Schema.Array(OutOfScopeFinding)),
177
- /** The last review's scope judgement, which a Build fixing what it left takes as `scope`. */
178
- scope: Schema.optional(ReviewedScope),
179
- /** Each Review round's blocking count, first to last, which decides whether a Rebuild may follow. */
180
- blockingCounts: Schema.optional(Schema.Array(Schema.Int)),
181
- /** Whether the last Review's approval was recorded, or why not, when nothing was left unsettled. */
182
- approval: Schema.optional(ApproveChangeRequestResult),
183
- /** What Shepherd did with the ChangeRequest, when the Build was told to land it. */
184
- landed: Schema.optional(ShepherdOutput),
185
- /** The input its Shepherd and Review offers start from. */
186
- next: Schema.Struct({ changeRequestId: Schema.String }),
187
- /** Where the Run's delivery landed and the layer it came from. */
188
- deliversTo: Schema.optional(ResolvedDeliveryTarget)
189
- })
190
-
191
- /** Build was marked blocked on findings that still stand, so the Task waits on its owner. */
192
- export class BuildBlocked extends Schema.TaggedError<BuildBlocked>()('BuildBlocked', {
193
- message: Schema.String
194
- }) {}
195
-
196
- /** The base sync did not say which target commit it merged, so a review would have no fixed base to diff against. */
197
- export class BuildBaseUnpinned extends Schema.TaggedError<BuildBaseUnpinned>()('BuildBaseUnpinned', {
198
- message: Schema.String
199
- }) {}
30
+ export { BuildInput, BuildOutput, SuggestedCheck }
200
31
 
201
32
  export class BuildTargetMissing extends Schema.TaggedError<BuildTargetMissing>()('BuildTargetMissing', {
202
33
  message: Schema.String
203
34
  }) {}
204
35
 
205
- const outcomeGuidance = {
206
- feature: 'Deliver the whole scope; review checks it was met.',
207
- bug: 'Your failing test is already in place: make it pass.',
208
- refactor: 'Keep behaviour exactly as it is; the approved verifications must pass before and after.',
209
- investigation: 'Investigate and report what you found, with its sources.',
210
- docs: 'Name, in `documented`, the approved checks that run the commands you documented.',
211
- migration: 'Name, in `rollback`, the approved check that rolls the migration back.',
212
- performance: 'Make it faster without changing behaviour.'
213
- } as const satisfies { readonly [outcome in LoopOutcome]: string }
214
-
215
36
  /** Build cannot prove a gain: Hillclimb commits a benchmark first and measures each change against it. */
216
37
  export class BuildOutcomeRefused extends Schema.TaggedError<BuildOutcomeRefused>()('BuildOutcomeRefused', {
217
38
  message: Schema.String
218
39
  }) {}
219
40
 
220
- const criteriaGuidance =
221
- 'If your brief has a Task, answer each of its acceptance criteria in `criteria`: met, with the test or file that shows it; after_merge, with why it can only be seen once merged; or not_met, with why. Give an empty `criteria` when the Task has none.'
222
-
223
- const outOfScopeGuidance = (cases: readonly string[]) =>
224
- cases.length === 0
225
- ? []
226
- : [
227
- [
228
- "The Task's Out of scope list is these numbered cases. Do not build them: Review reports a problem in one without holding the change for it, unless it is a blocker, such as a security hole or lost data.",
229
- ...numberedCases(cases),
230
- "A criterion that is not met only because it falls in one of these is not_met, with `outOfScope` set to the case's number; Review says whether it agrees."
231
- ].join('\n')
232
- ]
233
-
234
- const checksGuidance =
235
- 'If your brief lists no approved verifications for this repository, name in `checks` the commands from its package scripts or CI config that test, lint and typecheck it, each with a `name` of letters, digits, `.`, `_`, `:` and `-` only, such as `unit-tests`; Kitman runs them and labels them as suggested by you.'
236
-
237
- /** How Build and Errand adapt the implement skill to a Step. */
238
- export const implementAdaptation =
239
- 'You run the implement skill as a Kitman Step. The work is in this prompt and your brief, so fetch no ticket. Leave your changes uncommitted: the Run owns the branch. Skip its final code-review: a Review run or a person reviews the change.'
240
-
241
- const implementPrompt = (
242
- task: string,
243
- outcome: LoopOutcome | undefined,
244
- continuing: Continuing | undefined,
245
- cases: readonly string[]
246
- ) =>
247
- [
248
- ...(continuing === undefined ? [] : [continuingBrief(continuing), 'Fix forward from there.']),
249
- `Build ${task}`,
250
- implementAdaptation,
251
- ...(outcome === undefined ? [] : [outcomeGuidance[outcome]]),
252
- 'Commit nothing yourself: Kitman pushes what you leave in the workspace. Give the ChangeRequest a title and a summary, and list as claims what you believe but Kitman has not checked, such as "the tests pass".',
253
- ...outOfScopeGuidance(cases),
254
- criteriaGuidance,
255
- checksGuidance
256
- ].join('\n\n')
257
-
258
- const criteriaPrompt = (unanswered: boolean, unmet: readonly CriterionAnswer[], cases: readonly string[]) =>
259
- [
260
- unanswered
261
- ? "You did not answer the Task's acceptance criteria. Answer each one before anyone reviews the change."
262
- : 'These acceptance criteria are not met yet. Meet them, or say why they cannot be met here, such as an answer under Answers so far that put them out of scope; do not ask that Question again:',
263
- ...unmet.map(answer => `- ${answer.criterion}: ${answer.detail}`),
264
- ...outOfScopeGuidance(cases),
265
- criteriaGuidance
266
- ].join('\n\n')
41
+ type Input = typeof BuildInput.Type
42
+
43
+ type Built = typeof Built.Type
267
44
 
268
45
  const answerLine = (answer: CriterionAnswer, cases: readonly string[]) => {
269
46
  const line = `${answer.criterion}: ${answer.status.replaceAll('_', ' ')}, ${answer.detail}`
@@ -309,263 +86,144 @@ const criterionLine = (answer: CriterionAnswer, cases: readonly string[], scope:
309
86
  : inCase(`${answer.criterion}: not done, as Review judged it (${answered})`, final.item)
310
87
  }
311
88
 
312
- const reproducingCheckGuidance =
313
- 'Give in `check` the command that runs only that test, with a `name` of letters, digits, `.`, `_`, `:` and `-` that no approved verification of the repository has, unless it is exactly that approved check. Kitman runs it before the fix, where it must fail, and on every head after, where it must pass.'
314
-
315
- const reproducePrompt = (task: string) =>
316
- [
317
- `Reproduce the bug in ${task} before anyone fixes it.`,
318
- 'Add a test that fails because of the bug, and change nothing else.',
319
- reproducingCheckGuidance
320
- ].join('\n\n')
321
-
322
- const reproducedOnBranchPrompt = (task: string) =>
323
- [
324
- `An earlier Run already worked on fixing the bug in ${task}, on this branch.`,
325
- 'Find the commit on this branch where the test reproducing the bug was in place and the fix was not yet, and give it as `revision`. Change nothing.',
326
- 'If no commit on the branch has the reproducing test without the fix, add a test that fails on the branch head now, change nothing else, and give no `revision`.',
327
- reproducingCheckGuidance
328
- ].join('\n\n')
329
-
330
- const findingLine = (finding: MergedFinding) => `- **${finding.severity}** \`${finding.id}\` ${finding.detail}`
331
-
332
- const disputeLine = ({ finding, rebuttal }: Disputed) => `${findingLine(finding)}\n You rebutted: ${rebuttal.reason}`
333
-
334
- const fixPrompt = (settled: SettledRound) => {
335
- const checks = settled.open.filter(finding => isCheckFinding(finding.id))
336
-
337
- const findings = settled.open.filter(finding => !isCheckFinding(finding.id))
338
-
339
- return [
340
- ...(checks.length === 0
341
- ? []
342
- : [
343
- 'These checks fail on your head and pass on the base. Only the check passing closes one. If you are sure the change did not cause it, such as a flaky test, rebut it with your reason: the ChangeRequest reports that as your claim and the check stays open. A check does not run again on an unchanged tree, so if you change nothing and only these are open, the rally ends.',
344
- ...checks.map(findingLine),
345
- 'Read the full output of a failed check with the Kitman tool check_output, by its name.'
346
- ]),
347
- ...(findings.length === 0
348
- ? []
349
- : [
350
- 'The review found these. Fix each, or rebut it with your reason if it is wrong; reviewers judge the rebuttals next round.',
351
- ...findings.map(findingLine)
352
- ]),
353
- ...(settled.standing.length === 0
354
- ? []
355
- : [
356
- 'The reviewers rejected your rebuttal of these. Fix each, or rebut it again with a better reason; one you leave stays a dispute for a person to settle.',
357
- ...settled.standing.map(disputeLine)
358
- ])
359
- ].join('\n')
360
- }
361
-
362
- const takenOverAnswer = 'Taken over'
363
-
364
- const buildAgainAnswer = 'Build again'
365
-
366
- const blockedAnswer = 'Mark blocked'
367
-
368
- const standingConstraint = (item: string) => `Settle what an earlier Build left standing: ${item}`
369
-
370
- const blockingIds = (settled: SettledRound) => settled.open.filter(isBlocking).map(finding => finding.id)
371
-
372
- const onlyChecksBlock = (settled: SettledRound) =>
373
- blockingIds(settled).every(isCheckFinding) && !settled.standing.some(entry => isBlocking(entry.finding))
374
-
375
- type Round = {
376
- readonly round: number
377
- readonly head: VerifyResult
378
- readonly settled: SettledRound
379
- readonly decision: RallyDecision & { readonly stop: true }
380
- readonly claims: readonly string[]
381
- readonly scope: ReviewedScope | undefined
382
- readonly outOfScope: readonly OutOfScopeFinding[]
383
- readonly conflicts: readonly string[]
384
- readonly earlier: readonly MergedFinding[]
385
- readonly blockingCounts: readonly number[]
386
- }
387
-
388
- /**
389
- * Verifies the head and has it reviewed, then has the implementer fix or rebut the findings, until the rally stops.
390
- * The last Step that changes code comes before the last review, so the reviewed revision is the one that ships.
391
- */
392
- const rally = (input: {
393
- readonly maxRounds: number
394
- readonly target: string | undefined
395
- readonly outcome: LoopOutcome | undefined
396
- readonly claims: readonly string[]
397
- readonly suggested: readonly (typeof SuggestedCheck.Type)[]
398
- /** The bug's reproducing check, run on every head besides the approved ones. */
399
- readonly reproducing: typeof SuggestedCheck.Type | undefined
400
- readonly reviewed: string | undefined
401
- readonly deliveredBy: string | undefined
402
- readonly earlier: readonly MergedFinding[]
403
- readonly outOfScope: readonly OutOfScopeFinding[]
404
- readonly unmetCriteria: readonly string[]
405
- readonly metCriteria: readonly string[]
406
- readonly afterMergeCriteria: readonly string[]
407
- readonly scope: ReviewedScope | undefined
408
- }) =>
89
+ /** The criteria the implementer answered with `status`, which Review judges only for a Task with an Out of scope list. */
90
+ const answeredAs = (
91
+ criteria: readonly CriterionAnswer[],
92
+ cases: readonly string[],
93
+ status: CriterionAnswer['status']
94
+ ) => (cases.length === 0 ? [] : criteria.flatMap(answer => (answer.status === status ? [answer.criterion] : [])))
95
+
96
+ const stoppedAs = {
97
+ Settled: 'settled',
98
+ DisputeStands: 'dispute_stands',
99
+ FindingsReturned: 'findings_returned',
100
+ RoundCap: 'round_cap'
101
+ } as const
102
+
103
+ const startingFrom = (input: Input) =>
409
104
  Effect.gen(function* () {
410
- const claims = [...input.claims]
411
- const conflicts: string[] = []
412
- const blockingCounts: number[] = []
413
- let rebuttals: readonly Rebuttal[] = []
414
- let earlier = input.earlier
415
- let outOfScope = input.outOfScope
416
- let previous: readonly string[] | undefined
417
- let last: Pick<Round, 'head' | 'settled' | 'scope'> | undefined
418
- const shown = new Set<string>()
419
-
420
- for (let round = 1; ; round++) {
421
- // Reviewers see what will merge; a conflict the implementer cannot settle is left unsettled, not hidden.
422
- const synced = yield* syncBase(`sync:${round}`, {
423
- agent: 'implementer',
424
- ...(input.target === undefined ? undefined : { target: input.target })
425
- })
426
-
427
- // A round that merges or finds the branch up to date settles every round before it that could not merge.
428
- if (synced.status === 'conflict')
429
- conflicts.push(
430
- `Could not merge the target branch in round ${round}: ${synced.files.join(', ')} (${synced.reason})`
431
- )
432
- else conflicts.length = 0
105
+ const epic = epicOf(input)
106
+ // The Task's open ChangeRequest an earlier Run left, which this Build fixes forward instead of rebuilding.
107
+ const { continuing } = yield* runContext
433
108
 
434
- // Pinned, so a target that moves during the round does not move what is reviewed.
435
- const base = synced.base
109
+ // Under epic delivery a sub-task branches from its epic's branch, which the first sub-task's Build makes.
110
+ if (epic !== undefined && continuing === undefined && input.branch === undefined) yield* deliveryBase('epic-branch')
436
111
 
437
- if (base === undefined)
438
- return yield* new BuildBaseUnpinned({
439
- message: `The Runner did not report which commit of ${input.target ?? 'the default branch'} it merged in round ${round}, so there is no base to review against; update the Runner`
440
- })
441
-
442
- const head = yield* verify(`verify:${round}`, {
443
- suggested: input.suggested,
444
- ...(input.reproducing === undefined ? undefined : { extra: [input.reproducing] })
445
- })
446
-
447
- // Evidence is held per tree, so the same checks would fail again and a review would judge the same change.
448
- if (last !== undefined && last.head.tree === head.tree && rebuttals.length === 0 && onlyChecksBlock(last.settled))
449
- return {
450
- ...last,
451
- round: round - 1,
452
- head,
453
- decision: { stop: true, reason: 'findings_returned', unsettled: blockingIds(last.settled) },
454
- claims,
455
- outOfScope,
456
- conflicts,
457
- earlier,
458
- blockingCounts
459
- } satisfies Round
460
-
461
- const failing = brokenChecks(head).map(check => check.name)
462
- const notRun = testsNotRunReasons(head)
463
-
464
- const scope = last === undefined ? input.scope : last.scope
465
-
466
- const reviewed = yield* call(`review:${round}`, review, {
467
- base,
468
- head: head.revision,
469
- ...(input.deliveredBy === undefined ? undefined : { deliveredBy: input.deliveredBy }),
470
- ...(rebuttals.length === 0 ? undefined : { rebuttals }),
471
- ...(earlier.length === 0 ? undefined : { earlier }),
472
- ...(last === undefined
473
- ? input.reviewed === undefined
474
- ? undefined
475
- : { reviewed: input.reviewed }
476
- : { reviewed: last.head.revision }),
477
- ...(outOfScope.length === 0 ? undefined : { outOfScopeFindings: outOfScope }),
478
- ...(input.unmetCriteria.length === 0 ? undefined : { unmetCriteria: input.unmetCriteria }),
479
- ...(input.metCriteria.length === 0 ? undefined : { metCriteria: input.metCriteria }),
480
- ...(input.afterMergeCriteria.length === 0 ? undefined : { afterMergeCriteria: input.afterMergeCriteria }),
481
- ...(scope === undefined ? undefined : { scope }),
482
- ...(input.outcome === undefined ? undefined : { outcome: input.outcome }),
483
- ...(failing.length === 0 ? undefined : { failing }),
484
- ...(notRun.length === 0 ? undefined : { notRun }),
485
- claims: [...claims]
112
+ if (input.changeRequestId !== undefined && continuing?.changeRequestId !== input.changeRequestId)
113
+ return yield* new BuildTargetMissing({
114
+ message: `Kitman did not put this Run on ChangeRequest ${input.changeRequestId}'s branch`
486
115
  })
487
116
 
488
- outOfScope = reviewed.outOfScopeFindings ?? []
489
- const checks = checkFindings(head)
490
-
491
- const settled = settleRound({
492
- findings: [...reviewed.findings, ...scopeFindings(reviewed.scope), ...checks],
493
- rebuttals,
494
- verdicts: reviewed.verdicts
495
- })
117
+ // A retry given an earlier Run's branch starts there; Kitman leaves `branch` as what it merges into.
118
+ return { continuing, target: continuing?.targetBranch ?? input.branch ?? epic?.branch ?? input.targetBranch }
119
+ })
496
120
 
497
- blockingCounts.push(blockingCount(settled))
121
+ /** What the head proves and what still stands, as the ChangeRequest says it and the Build's Output reports it. */
122
+ const gated = ({
123
+ outcome,
124
+ before,
125
+ change,
126
+ last,
127
+ cases
128
+ }: {
129
+ readonly cases: readonly string[]
130
+ readonly outcome: LoopOutcome | undefined
131
+ readonly before: Effect.Success<ReturnType<typeof reproduced>>
132
+ readonly change: Implemented
133
+ readonly last: Effect.Success<ReturnType<typeof rallied>>
134
+ }) => {
135
+ const verdict = evidenceGate({
136
+ ...(outcome === undefined ? undefined : { outcome }),
137
+ head: last.head,
138
+ ...(before._tag === 'NotNeeded' ? undefined : { base: before.base }),
139
+ ...(last.scope === undefined ? undefined : { review: last.scope }),
140
+ ...(before._tag === 'Reproduced' ? { reproducing: before.check.name } : undefined),
141
+ ...(change.documented === undefined ? undefined : { documented: change.documented }),
142
+ ...(change.rollback === undefined ? undefined : { rollback: change.rollback })
143
+ })
498
144
 
499
- // A dispute that stands stays in front of the reviewers when a broken check carries the rally on past it.
500
- earlier = [...settled.open, ...settled.standing.map(entry => entry.finding)].filter(
501
- finding => !finding.id.startsWith('scope: ') && !isCheckFinding(finding.id)
145
+ const stopped = stoppedAs[last._tag]
146
+ const findings = codeFindings(last.settled)
147
+ const notRun = testsNotRunReasons(last.head)
148
+
149
+ // An Outcome's gate may not read every check, so a failing one is reported here too, once.
150
+ const unsettled = [
151
+ ...new Set([
152
+ ...(verdict.settled ? [] : verdict.reasons),
153
+ ...brokenChecks(last.head).map(check => failsOn('head', check, last.head.tree)),
154
+ ...unsettledItems(last.settled),
155
+ ...last.conflicts,
156
+ ...change.criteria.flatMap(answer =>
157
+ answer.status === 'not_met' && (reviewedAs(answer.criterion, cases, last.scope)?.status ?? 'open') === 'open'
158
+ ? [`Criterion not met: ${answer.criterion} (${answer.detail})`]
159
+ : []
502
160
  )
161
+ ])
162
+ ]
163
+
164
+ const body = changeRequestBody({
165
+ summary: change.summary,
166
+ head: last.head,
167
+ claims: last.claims,
168
+ unsettled,
169
+ criteria: change.criteria.map(answer => criterionLine(answer, cases, last.scope)),
170
+ later: last.settled.open.filter(finding => !isBlocking(finding)).map(finding => `${finding.id}: ${finding.detail}`),
171
+ outOfScope: outOfScopeLines(last.outOfScope, last.scope),
172
+ rounds: last.round,
173
+ stopped
174
+ })
503
175
 
504
- // A failure the implementer has not been shown has not returned, and a dispute does not keep it from them.
505
- const unseen = checks.some(finding => !shown.has(finding.detail))
506
-
507
- const decision = rallyStop({
508
- round,
509
- maxRounds: input.maxRounds,
510
- settled,
511
- ...(previous === undefined || unseen ? undefined : { previous })
512
- })
513
-
514
- if (decision.stop && (!unseen || round >= input.maxRounds))
515
- return {
516
- round,
517
- head,
518
- settled,
519
- decision,
520
- claims,
521
- scope: reviewed.scope,
522
- outOfScope,
523
- conflicts,
524
- earlier,
525
- blockingCounts
526
- } satisfies Round
527
-
528
- for (const finding of checks) shown.add(finding.detail)
529
-
530
- const fixed = yield* agentWork(`fix:${round}`, {
531
- agent: 'implementer',
532
- prompt: fixPrompt(settled),
533
- output: Fixed
534
- })
535
-
536
- claims.push(
537
- ...fixed.claims,
538
- ...fixed.rebuttals.flatMap(rebuttal =>
539
- isCheckFinding(rebuttal.findingId) ? [`Rebutted ${rebuttal.findingId}: ${rebuttal.reason}`] : []
540
- )
541
- )
542
- // Evidence is not the reviewers' to withdraw.
543
- const rebutted = fixed.rebuttals.filter(rebuttal => !isCheckFinding(rebuttal.findingId))
544
-
545
- // A blocking dispute the implementer does not repeat is still one, unless the fix ends the finding.
546
- rebuttals = [
547
- ...rebutted,
548
- ...settled.standing
549
- .filter(entry => isBlocking(entry.finding))
550
- .map(entry => entry.rebuttal)
551
- .filter(rebuttal => !rebutted.some(entry => entry.findingId === rebuttal.findingId))
552
- ]
553
- previous = blockingIds(settled)
554
- last = { head, settled, scope: reviewed.scope }
176
+ return {
177
+ body,
178
+ // The last round's Review passed on the head that ships, so it is the independent approval Shepherd waits for.
179
+ // Without one, Shepherd waits for a person's.
180
+ approves:
181
+ unsettled.length === 0
182
+ ? {
183
+ head: last.head.revision,
184
+ summary: `Review round ${last.round} passed with nothing blocking.`,
185
+ review: last.review
186
+ }
187
+ : undefined,
188
+ found: {
189
+ revision: last.head.revision,
190
+ tree: last.head.tree,
191
+ settled: unsettled.length === 0,
192
+ unsettled,
193
+ rounds: last.round,
194
+ stopped,
195
+ criteria: change.criteria,
196
+ ...(notRun.length === 0 ? undefined : { notRun }),
197
+ ...(findings.length === 0 ? undefined : { findings }),
198
+ ...(last.outOfScope.length === 0 ? undefined : { outOfScopeFindings: last.outOfScope }),
199
+ ...(last.scope === undefined ? undefined : { scope: last.scope }),
200
+ blockingCounts: last.blockingCounts
555
201
  }
556
- })
202
+ }
203
+ }
204
+
205
+ const outputOf = (
206
+ input: Input,
207
+ changeRequest: (typeof BuildOutput.Type)['changeRequest'],
208
+ built: Built
209
+ ): typeof BuildOutput.Type => ({
210
+ changeRequest,
211
+ ...built,
212
+ next: { changeRequestId: changeRequest.id },
213
+ ...(input.deliversTo === undefined ? undefined : { deliversTo: input.deliversTo })
214
+ })
557
215
 
558
216
  /**
559
- * Implements a Task or words, reviews and fixes until the rally stops, gates on the evidence for the head, and opens
560
- * the Run's ChangeRequest with the evidence, the claims and whatever it could not settle (ADR-0051). It writes the
561
- * Run's milestones to its Task: started, ChangeRequest opened, and failed, or blocked instead of failed when findings
562
- * still stand once full auto's rebuilds run out or its Review rounds are not converging; those findings go on the Task as a blocker
563
- * before the Run fails.
217
+ * Implements a Task or words, reviews and fixes until the rally stops, gates on the evidence for the head, and opens the
218
+ * Run's ChangeRequest with the evidence, the claims and whatever it could not settle (ADR-0051). Nothing unsettled
219
+ * reaches Shepherd. It writes the Run's milestones to its Task: started, ChangeRequest opened, and failed, or blocked
220
+ * instead of failed when it ends as `BuildBlocked`.
564
221
  */
565
222
  const build = defineLoop({
566
223
  id: 'build',
567
- version: '2.13.0',
224
+ version: '3.1.0',
568
225
  title: 'Build',
226
+ description: 'Implements a Task or words, reviews and fixes the change, and opens a ChangeRequest with its evidence.',
569
227
  input: BuildInput,
570
228
  output: BuildOutput,
571
229
  agents: { implementer: 'implementer', 'planned-implementer': 'planned-implementer' },
@@ -591,280 +249,85 @@ const build = defineLoop({
591
249
 
592
250
  yield* writeBack('write-back:started', { milestone: 'started' })
593
251
 
594
- const task = input.words === undefined ? 'the Task your brief describes.' : `this: ${input.words}`
595
- const outcome = input.outcome
252
+ const { words, taskId, outcome } = input
253
+ const { continuing, target } = yield* startingFrom(input)
596
254
  const cases = listedCases(input.taskOutOfScope)
597
- // A retry given an earlier Run's branch starts there; Kitman leaves `branch` as what it merges into.
598
- const epic = epicOf(input)
599
- const target = input.continuing?.targetBranch ?? input.branch ?? epic?.branch
255
+ const before = yield* reproduced({ words, outcome, continuing })
600
256
 
601
- // Under epic delivery a sub-task branches from its epic's branch, which the first sub-task's Build makes.
602
- if (epic !== undefined && input.continuing === undefined && input.branch === undefined)
603
- yield* deliveryBase('epic-branch')
604
-
605
- if (input.changeRequestId !== undefined && input.continuing?.changeRequestId !== input.changeRequestId)
606
- return yield* new BuildTargetMissing({
607
- message: `Kitman did not put this Run on ChangeRequest ${input.changeRequestId}'s branch`
608
- })
609
-
610
- // A continued bug recovers its proof from the branch: the commit where the test failed before the fix.
611
- const reproduced =
612
- outcome === 'bug'
613
- ? yield* agentWork('reproduce', {
614
- agent: 'implementer',
615
- prompt: input.continuing === undefined ? reproducePrompt(task) : reproducedOnBranchPrompt(task),
616
- output: ReproducedOnBranch
617
- })
618
- : undefined
619
-
620
- const base =
621
- reproduced !== undefined
622
- ? yield* verify('verify:reproduction', {
623
- ...(reproduced.revision === undefined ? undefined : { revision: reproduced.revision }),
624
- extra: [reproduced.check]
625
- })
626
- : outcome === 'refactor'
627
- ? yield* verify('verify:base', {})
628
- : undefined
629
-
630
- const implemented = yield* agentWorkOnce('implement', {
631
- agent: input.planReviewed === true ? 'planned-implementer' : 'implementer',
632
- skill: 'implement',
633
- prompt: implementPrompt(task, outcome, input.continuing, cases),
634
- output: Implemented
257
+ const change = yield* implemented({
258
+ words,
259
+ taskId,
260
+ outcome,
261
+ continuing,
262
+ ...(cases.length === 0 ? undefined : { cases }),
263
+ ...(input.planReviewed === true ? { planReviewed: true } : undefined)
635
264
  })
636
265
 
637
- // Every criterion is answered before a reviewer reads the change; what is missing or unmet goes back once.
638
- // An empty list says the Task has none; only a missing one goes back.
639
- const unanswered = input.taskId !== undefined && implemented.criteria === undefined
640
-
641
- const unmet = (implemented.criteria ?? []).filter(
642
- answer => answer.status === 'not_met' && caseOf(cases, answer) === undefined
643
- )
644
-
645
- const criteria =
646
- unanswered || unmet.length > 0
647
- ? (yield* agentWorkOnce('criteria', {
648
- agent: 'implementer',
649
- prompt: criteriaPrompt(unanswered, unmet, cases),
650
- output: Criteria
651
- })).criteria
652
- : (implemented.criteria ?? [])
653
-
654
- const last = yield* rally({
266
+ const last = yield* rallied({
267
+ fixer: 'implementer',
655
268
  maxRounds: input.maxRounds ?? 3,
656
269
  target,
657
270
  outcome,
658
- claims: [...implemented.claims, ...criteria.map(answer => `Criterion ${answerLine(answer, cases)}`)],
659
- suggested: implemented.checks ?? [],
660
- reproducing: reproduced?.check,
271
+ claims: [...change.claims, ...change.criteria.map(answer => `Criterion ${answerLine(answer, cases)}`)],
272
+ suggested: change.checks ?? [],
273
+ extra: before._tag === 'Reproduced' ? [before.check] : undefined,
661
274
  reviewed: input.reviewed,
275
+ earlier: input.earlier,
662
276
  deliveredBy: input.changeRequestId,
663
- earlier: input.earlier ?? [],
664
- outOfScope: input.outOfScopeFindings ?? [],
665
- unmetCriteria:
666
- cases.length === 0 ? [] : criteria.flatMap(answer => (answer.status === 'not_met' ? [answer.criterion] : [])),
667
- metCriteria:
668
- cases.length === 0 ? [] : criteria.flatMap(answer => (answer.status === 'met' ? [answer.criterion] : [])),
669
- afterMergeCriteria:
670
- cases.length === 0
671
- ? []
672
- : criteria.flatMap(answer => (answer.status === 'after_merge' ? [answer.criterion] : [])),
277
+ outOfScopeFindings: input.outOfScopeFindings,
278
+ unmetCriteria: answeredAs(change.criteria, cases, 'not_met'),
279
+ metCriteria: answeredAs(change.criteria, cases, 'met'),
280
+ afterMergeCriteria: answeredAs(change.criteria, cases, 'after_merge'),
673
281
  scope: input.scope
674
282
  })
675
283
 
676
- const verdict = evidenceGate({
677
- ...(outcome === undefined ? undefined : { outcome }),
678
- head: last.head,
679
- ...(base === undefined ? undefined : { base }),
680
- ...(last.scope === undefined ? undefined : { review: last.scope }),
681
- ...(reproduced === undefined ? undefined : { reproducing: reproduced.check.name }),
682
- ...(implemented.documented === undefined ? undefined : { documented: implemented.documented }),
683
- ...(implemented.rollback === undefined ? undefined : { rollback: implemented.rollback })
684
- })
284
+ const gate = gated({ outcome, before, change, last, cases })
685
285
 
686
- const lastNotRun = testsNotRunReasons(last.head)
687
-
688
- // An Outcome's gate may not read every check, so a failing one is reported here too, once.
689
- const unsettled = [
690
- ...new Set([
691
- ...(verdict.settled ? [] : verdict.reasons),
692
- ...brokenChecks(last.head).map(check => failsOn('head', check, last.head.tree)),
693
- ...unsettledItems(last.settled, last.decision),
694
- ...last.conflicts,
695
- ...criteria.flatMap(answer =>
696
- answer.status === 'not_met' &&
697
- (reviewedAs(answer.criterion, cases, last.scope)?.status ?? 'open') === 'open'
698
- ? [`Criterion not met: ${answer.criterion} (${answer.detail})`]
699
- : []
700
- )
701
- ])
702
- ]
703
-
704
- const body = changeRequestBody({
705
- summary: implemented.summary,
706
- head: last.head,
707
- claims: last.claims,
708
- unsettled,
709
- criteria: criteria.map(answer => criterionLine(answer, cases, last.scope)),
710
- later: last.settled.open
711
- .filter(finding => !isBlocking(finding))
712
- .map(finding => `${finding.id}: ${finding.detail}`),
713
- outOfScope: outOfScopeLines(last.outOfScope, last.scope),
714
- rounds: last.round,
715
- stopped: last.decision.reason
286
+ const { changeRequest, approval } = yield* opened({
287
+ title: change.title,
288
+ body: gate.body,
289
+ continues: input.changeRequestId === undefined ? undefined : continuing,
290
+ report: 'kitman-build',
291
+ settled: gate.approves
716
292
  })
717
293
 
718
- const named = input.changeRequestId === undefined ? undefined : input.continuing
719
-
720
- const opened =
721
- named === undefined
722
- ? yield* changeRequest('change-request', { title: implemented.title, body })
723
- : yield* comment('report', { changeRequestId: named.changeRequestId, body, summary: 'kitman-build' }).pipe(
724
- Effect.as({ id: named.changeRequestId, number: named.number, url: named.url })
725
- )
726
-
727
- if (named === undefined)
728
- yield* writeBack('write-back', { milestone: 'change_request_opened', changeRequestUrl: opened.url })
729
-
730
- // The last round's Review passed on the head that ships, so it is the independent approval Shepherd waits for.
731
- // Without one, Shepherd waits for a person's.
732
- const approval =
733
- unsettled.length === 0
734
- ? yield* approveChangeRequest('approve', {
735
- changeRequestId: opened.id,
736
- head: last.head.revision,
737
- summary: `Review round ${last.round} passed with nothing blocking.`,
738
- review: `review:${last.round}`
739
- }).pipe(
740
- Effect.catchTag('StepFailed', error => Effect.succeed({ approved: false as const, reason: error.reason }))
741
- )
742
- : undefined
743
-
744
- let settledAs: Omit<typeof BuildOutput.Type, 'changeRequest' | 'landed' | 'next'> = {
745
- revision: last.head.revision,
746
- tree: last.head.tree,
747
- settled: unsettled.length === 0,
748
- unsettled,
749
- rounds: last.round,
750
- stopped: last.decision.reason,
751
- criteria,
752
- ...(lastNotRun.length === 0 ? undefined : { notRun: lastNotRun }),
753
- ...(last.earlier.length === 0 ? undefined : { findings: last.earlier }),
754
- ...(last.outOfScope.length === 0 ? undefined : { outOfScopeFindings: last.outOfScope }),
755
- ...(last.scope === undefined ? undefined : { scope: last.scope }),
756
- blockingCounts: last.blockingCounts,
757
- ...(approval === undefined ? undefined : { approval })
758
- }
759
-
760
- const maxRebuilds = input.maxRebuilds ?? 1
761
-
762
- // Anything left unsettled stops here with the findings for a person, not in Shepherd. Full auto builds again on
763
- // the same branch up to the cap while its Review rounds converge, then fails with them rather than wait on a
764
- // Question nobody answers.
765
- for (let rebuilds = 0; input.land !== false && settledAs.unsettled.length > 0;) {
766
- const standing = settledAs.unsettled
767
- const refusal = rebuildRefusal(settledAs.blockingCounts ?? [])
768
- const again = rebuilds < maxRebuilds && refusal === undefined
769
- const refused = refusal === undefined ? [] : [`Another Build is not offered: ${refusal}.`]
770
-
771
- const answer = yield* ask(rebuilds === 0 ? 'unsettled' : `unsettled:${rebuilds + 1}`, {
772
- prompt: [
773
- `The ChangeRequest ${opened.url} is open, but these still stand: ${standing.join('; ')}. Build will not land it.`,
774
- ...refused
775
- ].join(' '),
776
- options: [
777
- { value: takenOverAnswer, description: 'A person fixes, rebuts or steers it from here.' },
778
- again
779
- ? {
780
- value: buildAgainAnswer,
781
- description: 'Starts one more Build on this branch, with each of these as a constraint.'
782
- }
783
- : {
784
- value: blockedAnswer,
785
- description: 'Fails this Build, recording these as a blocker on its Task, and tells its owner.'
786
- }
787
- ],
788
- recommended: takenOverAnswer,
789
- recommendationReason: 'Build stopped with these unsettled, so the next step is a person’s.',
790
- // No default: an unattended Run would take it at once even in a gated Team, and finish as partial.
791
- default: null,
792
- unattendedAuto: again ? buildAgainAnswer : blockedAnswer
294
+ let built: Built = { ...gate.found, ...(approval === undefined ? undefined : { approval }) }
295
+
296
+ // Each end's `status` names it in the outline; the Output has none.
297
+ if (input.land === false) return { status: 'left_open', output: outputOf(input, changeRequest, built) }
298
+
299
+ for (let rebuilds = 0; built.unsettled.length > 0; rebuilds++) {
300
+ const decided = yield* standing({
301
+ changeRequest,
302
+ unsettled: built.unsettled,
303
+ revision: built.revision,
304
+ findings: built.findings,
305
+ outOfScopeFindings: built.outOfScopeFindings,
306
+ scope: built.scope,
307
+ blockingCounts: built.blockingCounts,
308
+ again: rebuilds < (input.maxRebuilds ?? 1),
309
+ build: input
793
310
  })
794
311
 
795
- if (answer === takenOverAnswer) break
796
-
797
- if (answer === blockedAnswer) {
798
- if (input.taskId !== undefined)
799
- yield* note('blocked', {
800
- kind: 'blocker',
801
- text: [
802
- `Build stopped without landing ${opened.url}, marked blocked on what still stands:`,
803
- '',
804
- ...standing.map(item => `- ${item}`),
805
- ...(refused.length === 0 ? [] : ['', ...refused])
806
- ].join('\n')
807
- })
808
-
809
- yield* Effect.ignore(writeBack('write-back:blocked', { milestone: 'blocked' }))
810
-
811
- return yield* new BuildBlocked({
812
- message: `The ChangeRequest ${opened.url} is open, and Build was marked blocked on what still stands: ${standing.join('; ')}`
813
- })
814
- }
815
-
816
- rebuilds++
817
-
818
- const {
819
- changeRequest: _,
820
- landed: __,
821
- next: ___,
822
- ...rebuilt
823
- } = yield* call(
824
- `rebuild:${rebuilds}`,
825
- { id: 'build', input: BuildInput, output: BuildOutput },
826
- {
827
- ...(input.words === undefined ? undefined : { words: input.words }),
828
- ...(input.taskId === undefined ? undefined : { taskId: input.taskId }),
829
- ...(input.repoBindingId === undefined ? undefined : { repoBindingId: input.repoBindingId }),
830
- ...(input.outcome === undefined ? undefined : { outcome: input.outcome }),
831
- ...(input.maxRounds === undefined ? undefined : { maxRounds: input.maxRounds }),
832
- changeRequestId: opened.id,
833
- land: false,
834
- // Its first review reviews the fix of what the last review read.
835
- reviewed: settledAs.revision,
836
- ...(settledAs.findings === undefined ? undefined : { earlier: settledAs.findings }),
837
- ...(settledAs.outOfScopeFindings === undefined
838
- ? undefined
839
- : { outOfScopeFindings: settledAs.outOfScopeFindings }),
840
- ...(settledAs.scope === undefined ? undefined : { scope: settledAs.scope }),
841
- ...ownDeliveryTarget(input)
842
- },
843
- { constraints: standing.map(standingConstraint) }
844
- )
845
-
846
- settledAs = rebuilt
847
- }
312
+ if (decided._tag === 'TakenOver') return { status: 'taken_over', output: outputOf(input, changeRequest, built) }
848
313
 
849
- const landed =
850
- input.land !== false && settledAs.unsettled.length === 0
851
- ? yield* call('land', shepherd, {
852
- changeRequestId: opened.id,
853
- ...(settledAs.notRun === undefined ? undefined : { notRun: settledAs.notRun }),
854
- ...(input.taskId === undefined ? undefined : { taskId: input.taskId }),
855
- ...(input.branch === undefined ? undefined : { branch: input.branch }),
856
- ...ownDeliveryTarget(input)
857
- })
858
- : undefined
859
-
860
- return {
861
- changeRequest: opened,
862
- ...settledAs,
863
- ...(landed === undefined ? undefined : { landed }),
864
- next: { changeRequestId: opened.id },
865
- ...(input.deliversTo === undefined ? undefined : { deliversTo: input.deliversTo })
314
+ built = decided.built
866
315
  }
316
+
317
+ const shepherded = yield* landed({
318
+ changeRequestId: changeRequest.id,
319
+ notRun: built.notRun,
320
+ taskId,
321
+ branch: input.branch,
322
+ ...ownDeliveryTarget(input)
323
+ })
324
+
325
+ return { status: 'landed', output: { ...outputOf(input, changeRequest, built), landed: shepherded } }
867
326
  }).pipe(
327
+ Effect.map(end => end.output),
328
+ Effect.tapErrorTag('BuildBlocked', () =>
329
+ Effect.ignore(writeBack('write-back:blocked', { milestone: 'blocked' }))
330
+ ),
868
331
  Effect.tapError(error =>
869
332
  error instanceof BuildBlocked
870
333
  ? Effect.void