@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/hillclimb.ts CHANGED
@@ -1,43 +1,51 @@
1
1
  import {
2
- agentWork,
3
- agentWorkOnce,
4
2
  artifact,
5
3
  ask,
6
- call,
7
- changeRequest,
8
4
  ChangeRequestResult,
9
5
  createTasks,
10
6
  defineLoop,
11
7
  isBlocking,
12
8
  measure,
9
+ Measurement,
13
10
  MeasurePlan,
11
+ step,
14
12
  syncBase,
15
13
  testsNotRunReasons,
16
14
  verify,
17
- writeBack,
18
- type Measurement,
19
- type VerifyResult
15
+ VerifyResult
20
16
  } from '@kitman-sh/sdk/loop'
21
17
  import * as Effect from 'effect/Effect'
22
18
  import * as Schema from 'effect/Schema'
23
- import { notVerifiedSection, scopeFindings } from './change-request-body'
19
+ import { implementer, investigator } from './agents'
20
+ import { notVerifiedSection, scopeFindings, withoutOutput } from './change-request-body'
21
+ import { baseOf, TargetBranchField } from './delivery'
22
+ import { opened } from './opened'
23
+ import { Halted, rallied, type Settled } from './rallied'
24
24
  import { outOfScopeLines, outOfScopeSection } from './out-of-scope'
25
25
  import review from './review'
26
26
  import { FindingDetail, OneSentence } from './text-limits'
27
27
 
28
28
  const Input = Schema.Struct({
29
- /** What to make faster, in words; the journeys that matter most when left out. */
30
- focus: Schema.optional(Schema.String),
31
- taskId: Schema.optional(Schema.String),
32
- repoBindingId: Schema.optional(Schema.String),
33
- /** The base branch; the repository's default branch when left out. */
34
- branch: Schema.optional(Schema.String),
35
- /** Changes tried at most; 5 when left out. */
36
- cycles: Schema.optional(Schema.Int),
37
- /** The smallest gain that counts, as a fraction of the base; 0.05 when left out. */
38
- threshold: Schema.optional(Schema.Finite),
39
- /** How much worse a guardrail may get, as a fraction of the base; 0.02 when left out. */
40
- tolerance: Schema.optional(Schema.Finite)
29
+ focus: Schema.optional(Schema.String).annotate({
30
+ description: 'What to make faster, in words; the journeys that matter most when left out.'
31
+ }),
32
+ taskId: Schema.optional(Schema.String).annotate({
33
+ description: 'The Task the Run works for; its words say what to make faster.'
34
+ }),
35
+ repoBindingId: Schema.optional(Schema.String).annotate({
36
+ description: "The repository to measure and change; the Task's, else the Team's default, when left out."
37
+ }),
38
+ branch: Schema.optional(Schema.String).annotate({
39
+ description: "The base branch; the repository's default branch when left out."
40
+ }),
41
+ ...TargetBranchField,
42
+ cycles: Schema.optional(Schema.Int).annotate({ description: 'Changes tried at most; 5 when left out.' }),
43
+ threshold: Schema.optional(Schema.Finite).annotate({
44
+ description: 'The smallest gain that counts, as a fraction of the base; 0.05 when left out.'
45
+ }),
46
+ tolerance: Schema.optional(Schema.Finite).annotate({
47
+ description: 'How much worse a guardrail may get, as a fraction of the base; 0.02 when left out.'
48
+ })
41
49
  })
42
50
 
43
51
  const Opportunity = Schema.Struct({
@@ -49,6 +57,8 @@ const Opportunity = Schema.Struct({
49
57
  external: Schema.optional(Schema.Boolean)
50
58
  })
51
59
 
60
+ type Opportunity = typeof Opportunity.Type
61
+
52
62
  const Discovery = Schema.Struct({
53
63
  stack: Schema.String,
54
64
  journeys: Schema.Array(Schema.Struct({ name: Schema.String, objective: Schema.String })),
@@ -59,6 +69,8 @@ const Discovery = Schema.Struct({
59
69
  opportunities: Schema.Array(Opportunity)
60
70
  })
61
71
 
72
+ type Discovery = typeof Discovery.Type
73
+
62
74
  const Harness = Schema.Struct({
63
75
  /** What the benchmark exercises and why it stands for the journeys. */
64
76
  summary: OneSentence,
@@ -71,20 +83,41 @@ const Change = Schema.Struct({
71
83
  summary: OneSentence
72
84
  })
73
85
 
74
- const Kept = Schema.Struct({ summary: Schema.String, verdict: Schema.String, reason: Schema.String })
86
+ const KeptChange = Schema.Struct({ summary: Schema.String, verdict: Schema.String, reason: Schema.String })
87
+
88
+ type KeptChange = typeof KeptChange.Type
89
+
90
+ const Limits = { threshold: Schema.optional(Schema.Finite), tolerance: Schema.optional(Schema.Finite) }
91
+
92
+ const limitsOf = ({
93
+ threshold,
94
+ tolerance
95
+ }: {
96
+ readonly threshold?: number | undefined
97
+ readonly tolerance?: number | undefined
98
+ }) => ({
99
+ ...(threshold === undefined ? undefined : { threshold }),
100
+ ...(tolerance === undefined ? undefined : { tolerance })
101
+ })
75
102
 
76
103
  const Output = Schema.Struct({
77
- /** improved: a ChangeRequest holds a gain the final measurement proved; otherwise a findings report only. */
78
- status: Schema.Literals(['improved', 'no_gain', 'gain_gone', 'checks_failed', 'too_noisy']),
79
- reason: Schema.String,
80
- kept: Schema.Array(Kept),
81
- cycles: Schema.Int,
82
- reportArtifactId: Schema.String,
83
- changeRequest: Schema.optional(ChangeRequestResult),
84
- /** Improvements only another repository can make. */
85
- external: Schema.Array(Schema.String),
86
- /** What the ChangeRequest leaves open. */
87
- unsettled: Schema.optional(Schema.Array(Schema.String))
104
+ status: Schema.Literals(['improved', 'no_gain', 'gain_gone', 'checks_failed', 'too_noisy']).annotate({
105
+ description:
106
+ 'improved: a ChangeRequest holds a gain the final measurement proved; otherwise a findings report only.'
107
+ }),
108
+ reason: Schema.String.annotate({ description: 'Why it ended as it did, in a line.' }),
109
+ kept: Schema.Array(KeptChange).annotate({
110
+ description: "Each change tried, with the measurement's verdict and why it was kept or dropped."
111
+ }),
112
+ cycles: Schema.Int.annotate({ description: 'Changes it tried.' }),
113
+ reportArtifactId: Schema.String.annotate({ description: 'The Artifact holding the findings report.' }),
114
+ changeRequest: Schema.optional(ChangeRequestResult).annotate({
115
+ description: 'The ChangeRequest holding the gain, when it improved.'
116
+ }),
117
+ external: Schema.Array(Schema.String).annotate({ description: 'Improvements only another repository can make.' }),
118
+ unsettled: Schema.optional(Schema.Array(Schema.String)).annotate({
119
+ description: 'What the ChangeRequest leaves open.'
120
+ })
88
121
  })
89
122
 
90
123
  const discoverPrompt = (focus: string | undefined) =>
@@ -94,19 +127,24 @@ const discoverPrompt = (focus: string | undefined) =>
94
127
  'Rank the opportunities, most promising first, each marked measured, telemetry or hypothesis. Mark one that only another repository can make as external.'
95
128
  ].join('\n\n')
96
129
 
97
- const harnessPrompt = (discovery: typeof Discovery.Type) =>
130
+ const harnessPrompt = (journeys: Discovery['journeys']) =>
98
131
  [
99
132
  'Commit a local benchmark for these journeys, and change no product code:',
100
- ...discovery.journeys.map(journey => `- ${journey.name}: ${journey.objective}`),
133
+ ...journeys.map(journey => `- ${journey.name}: ${journey.objective}`),
101
134
  'It runs on this Runner alone: never call a service, database or URL outside it. Each run prints one JSON line of numbers by metric name as its last line; wall time is measured for you as wall_ms. Keep it under a minute a run.',
102
135
  'Give the measurement plan: the command, any prepare command, and the metrics with one primary and the rest guardrails. Add a low-variance counter (instructions, allocations, queries) where you can, marked lowVariance.'
103
136
  ].join('\n\n')
104
137
 
105
- const changePrompt = (discovery: typeof Discovery.Type, plan: MeasurePlan, tried: readonly string[], cycle: number) =>
138
+ const changePrompt = (
139
+ opportunities: readonly Opportunity[],
140
+ plan: MeasurePlan,
141
+ tried: readonly string[],
142
+ cycle: number
143
+ ) =>
106
144
  [
107
145
  `Cycle ${cycle}: make one bounded change that should improve ${plan.metrics.find(metric => metric.role === 'primary')?.name ?? 'the primary metric'} without making a guardrail worse, and commit it. Kitman measures it; do not report numbers of your own.`,
108
146
  'Opportunities, most promising first:',
109
- ...discovery.opportunities.flatMap(entry =>
147
+ ...opportunities.flatMap(entry =>
110
148
  entry.external === true ? [] : [`- ${entry.title} (${entry.evidence}): ${entry.detail}`]
111
149
  ),
112
150
  ...(tried.length === 0 ? [] : ['Already tried:', ...tried.map(entry => `- ${entry}`)]),
@@ -116,11 +154,8 @@ const changePrompt = (discovery: typeof Discovery.Type, plan: MeasurePlan, tried
116
154
  const revertPrompt = (start: string, cycle: number) =>
117
155
  `Cycle ${cycle}'s change did not prove faster. Revert its commits, and only those: run \`git revert --no-edit ${start}..HEAD\`. Touch no commit at or before ${start}, never reset or force-push, and change nothing else.`
118
156
 
119
- const fixPrompt = (findings: readonly { readonly id: string; readonly detail: string }[]) =>
120
- [
121
- 'The review of the climb found these. Fix each, keep behaviour exactly as it is and keep the gain, and commit. Kitman verifies and measures again; a fix that costs the gain ends the climb.',
122
- ...findings.map(finding => `- ${finding.id}: ${finding.detail}`)
123
- ].join('\n\n')
157
+ const fixGuidance =
158
+ 'The review of the climb found these. Fix each, keep behaviour exactly as it is and keep the gain, and commit. Kitman verifies and measures again; a fix that costs the gain ends the climb.'
124
159
 
125
160
  const percent = (fraction: number) => `${(fraction * 100).toFixed(1)}%`
126
161
 
@@ -134,33 +169,97 @@ const numbers = (measured: Measurement) =>
134
169
  )
135
170
  ].join('\n')
136
171
 
137
- const report = (input: {
138
- readonly discovery: typeof Discovery.Type
139
- readonly harness: typeof Harness.Type
140
- readonly reason: string
141
- readonly kept: readonly (typeof Kept.Type)[]
172
+ type Climb = {
173
+ /** The head of the last kept cycle, the baseline before one, which the next cycle starts from. */
174
+ readonly start: string
175
+ readonly kept: readonly KeptChange[]
142
176
  readonly tried: readonly string[]
143
- readonly final: Measurement | undefined
144
- }) =>
177
+ readonly cycles: number
178
+ readonly unkeptInARow: number
179
+ readonly stopped: boolean
180
+ }
181
+
182
+ const atBaseline = (baseline: string): Climb => ({
183
+ start: baseline,
184
+ kept: [],
185
+ tried: [],
186
+ cycles: 0,
187
+ unkeptInARow: 0,
188
+ stopped: false
189
+ })
190
+
191
+ const climbing = (climb: Climb, cycles: number) => !climb.stopped && climb.cycles < cycles && climb.unkeptInARow < 2
192
+
193
+ const afterCycle = (climb: Climb, ended: Kept | Reverted | RevertUnconfirmed | Exhausted | Unsafe): Climb => {
194
+ const cycle = climb.cycles + 1
195
+
196
+ switch (ended._tag) {
197
+ case 'Kept':
198
+ return {
199
+ ...climb,
200
+ start: ended.head,
201
+ kept: [...climb.kept, { summary: ended.summary, verdict: 'gain', reason: ended.reason }],
202
+ tried: [...climb.tried, `Cycle ${cycle}, kept: ${ended.summary} (${ended.reason})`],
203
+ cycles: cycle,
204
+ unkeptInARow: 0
205
+ }
206
+ case 'Reverted':
207
+ case 'RevertUnconfirmed':
208
+ return {
209
+ ...climb,
210
+ tried: [...climb.tried, `Cycle ${cycle}, reverted: ${ended.summary} (${ended.reason})`],
211
+ cycles: cycle,
212
+ unkeptInARow: climb.unkeptInARow + 1
213
+ }
214
+ case 'Exhausted':
215
+ case 'Unsafe':
216
+ return {
217
+ ...climb,
218
+ tried: [...climb.tried, `Cycle ${cycle}: ${ended._tag.toLowerCase()}, ${ended.summary}`],
219
+ stopped: true
220
+ }
221
+ }
222
+ }
223
+
224
+ type Findings = { readonly discovery: Discovery; readonly benchmark: string; readonly climb: Climb }
225
+
226
+ const report = (
227
+ { discovery, benchmark, climb: { kept, tried } }: Findings,
228
+ reason: string,
229
+ final: Measurement | undefined
230
+ ) =>
145
231
  [
146
- `# Hillclimb findings\n\n${input.reason}`,
147
- `## Stack\n\n${input.discovery.stack}`,
148
- `## Telemetry\n\n${input.discovery.telemetry.map(entry => `- ${entry.source}: ${entry.status}, ${entry.why}`).join('\n') || '- None reached'}`,
149
- `## Benchmark\n\n${input.harness.summary}`,
150
- `## Tried\n\n${input.tried.map(entry => `- ${entry}`).join('\n') || '- Nothing'}`,
151
- ...(input.kept.length === 0
152
- ? []
153
- : [`## Kept\n\n${input.kept.map(entry => `- ${entry.summary}: ${entry.reason}`).join('\n')}`]),
154
- ...(input.final === undefined ? [] : [`## Final measurement\n\n${input.final.reason}\n\n${numbers(input.final)}`]),
155
- `## Opportunities\n\n${input.discovery.opportunities.map(entry => `- ${entry.title} (${entry.evidence}${entry.external === true ? ', external' : ''}): ${entry.detail}`).join('\n')}`
232
+ `# Hillclimb findings\n\n${reason}`,
233
+ `## Stack\n\n${discovery.stack}`,
234
+ `## Telemetry\n\n${discovery.telemetry.map(entry => `- ${entry.source}: ${entry.status}, ${entry.why}`).join('\n') || '- None reached'}`,
235
+ `## Benchmark\n\n${benchmark}`,
236
+ `## Tried\n\n${tried.map(entry => `- ${entry}`).join('\n') || '- Nothing'}`,
237
+ ...(kept.length === 0 ? [] : [`## Kept\n\n${kept.map(entry => `- ${entry.summary}: ${entry.reason}`).join('\n')}`]),
238
+ ...(final === undefined ? [] : [`## Final measurement\n\n${final.reason}\n\n${numbers(final)}`]),
239
+ `## Opportunities\n\n${discovery.opportunities.map(entry => `- ${entry.title} (${entry.evidence}${entry.external === true ? ', external' : ''}): ${entry.detail}`).join('\n')}`
156
240
  ].join('\n\n')
157
241
 
158
- /** Review's `notRun` for a head, left out when verify ran every test. */
159
- const notRunOf = (head: VerifyResult) => {
160
- const notRun = testsNotRunReasons(head)
242
+ const externalTitles = (opportunities: readonly Opportunity[]) =>
243
+ opportunities.flatMap(entry => (entry.external === true ? [entry.title] : []))
161
244
 
162
- return notRun.length === 0 ? undefined : { notRun }
163
- }
245
+ /** Stores the findings report, and gives the Output every end of the climb shares. */
246
+ const ending = (status: typeof Output.Type.status, reason: string, found: Findings, final?: Measurement) =>
247
+ Effect.gen(function* () {
248
+ const stored = yield* artifact('report', {
249
+ kind: 'hillclimb-report',
250
+ title: 'Hillclimb findings',
251
+ text: report(found, reason, final)
252
+ })
253
+
254
+ return {
255
+ status,
256
+ reason,
257
+ kept: found.climb.kept,
258
+ cycles: found.climb.cycles,
259
+ reportArtifactId: stored.artifactId,
260
+ external: externalTitles(found.discovery.opportunities)
261
+ }
262
+ })
164
263
 
165
264
  /** Makes the plan's low-variance counter its primary metric, the old primary a guardrail. */
166
265
  const steadier = (plan: MeasurePlan): MeasurePlan | undefined => {
@@ -177,264 +276,455 @@ const steadier = (plan: MeasurePlan): MeasurePlan | undefined => {
177
276
  }
178
277
  }
179
278
 
180
- /**
181
- * Climbs one measured step at a time and keeps only the steps Kitman's own measurement proves uphill. It reads the
182
- * repository and what telemetry it can reach, commits a benchmark, measures the noise floor, then tries one change a
183
- * cycle: kept on a gain with no guardrail worse, else reverted to the cycle's start. Two unkept cycles in a row end
184
- * the climb. A ChangeRequest opens only when the final tree still proves the gain over the harness on the base; with
185
- * no gain the Run ends with a findings report.
186
- */
187
- export default defineLoop({
188
- id: 'hillclimb',
189
- version: '1.6.0',
190
- title: 'Hillclimb',
191
- outcome: 'performance',
192
- input: Input,
193
- output: Output,
194
- agents: { investigator: 'climber', implementer: 'implementer' },
195
- checkout: 'write',
196
- capabilities: ['agent_work', 'verify', 'measure', 'change_request', 'write_back', 'ask', 'create_tasks'],
197
- calls: () => [review],
198
- offers: [{ id: 'retry', title: 'Climb again', loop: 'hillclimb' }],
199
- run: input =>
200
- Effect.gen(function* () {
201
- const limits = {
202
- ...(input.threshold === undefined ? undefined : { threshold: input.threshold }),
203
- ...(input.tolerance === undefined ? undefined : { tolerance: input.tolerance })
204
- }
205
-
206
- const discovery = yield* agentWork('discover', {
207
- agent: 'investigator',
208
- prompt: discoverPrompt(input.focus),
209
- output: Discovery
210
- })
279
+ export class Discovered extends Schema.TaggedClass<Discovered>()('Discovered', Discovery.fields) {}
211
280
 
212
- const external = discovery.opportunities.flatMap(entry => (entry.external === true ? [entry.title] : []))
281
+ /** Finds where the repository is slow, changing nothing. */
282
+ export const discovered = step('discovered', {
283
+ payload: {
284
+ focus: Schema.optional(Schema.String).annotate({
285
+ description: 'What to make faster; the journeys that matter most when left out.'
286
+ })
287
+ },
288
+ success: Discovered,
289
+ run: ({ focus }) =>
290
+ Effect.map(
291
+ investigator('discover', { prompt: discoverPrompt(focus), output: Discovery }),
292
+ found => new Discovered(found)
293
+ )
294
+ })
213
295
 
296
+ /** The benchmark is steady enough to judge a change by. */
297
+ export class Calibrated extends Schema.TaggedClass<Calibrated>()('Calibrated', {
298
+ summary: Schema.String,
299
+ /** Its primary metric is the low-variance counter when the one asked for is too noisy. */
300
+ plan: MeasurePlan,
301
+ /** The base with the benchmark on it, which every gain is measured over. */
302
+ baseline: Schema.String
303
+ }) {}
304
+
305
+ /** The primary metric is too noisy to judge a change by, and no counter is steadier. */
306
+ export class TooNoisy extends Schema.TaggedClass<TooNoisy>()('TooNoisy', {
307
+ summary: Schema.String,
308
+ baseline: Schema.String,
309
+ reason: Schema.String
310
+ }) {}
311
+
312
+ /** Commits a benchmark on the base as the climb found it, and measures the base against itself. */
313
+ export const harnessed = step('harnessed', {
314
+ payload: {
315
+ journeys: Discovery.fields.journeys,
316
+ target: Schema.optional(Schema.String).annotate({
317
+ description: 'The branch to merge in first; the default branch when left out.'
318
+ }),
319
+ ...Limits
320
+ },
321
+ success: Schema.Union([Calibrated, TooNoisy]),
322
+ run: ({ journeys, target, ...limits }) =>
323
+ Effect.gen(function* () {
214
324
  // The harness sits on the base as the climb found it, so every baseline holds the benchmark.
215
- yield* syncBase('sync:start', {
216
- agent: 'implementer',
217
- ...(input.branch === undefined ? undefined : { target: input.branch })
218
- })
325
+ yield* syncBase('sync', { agent: 'implementer', ...baseOf({ branch: target }) })
326
+
327
+ const { summary, plan } = yield* implementer('harness', { prompt: harnessPrompt(journeys), output: Harness })
328
+ const baseline = (yield* verify('verify', {})).revision
219
329
 
220
- const harness = yield* agentWorkOnce('harness', {
221
- agent: 'implementer',
222
- prompt: harnessPrompt(discovery),
223
- output: Harness
330
+ const calibrated = yield* measure('calibrate', {
331
+ plan,
332
+ base: baseline,
333
+ head: baseline,
334
+ ...limitsOf(limits)
224
335
  })
225
336
 
226
- const baseline = (yield* verify('verify:harness', {})).revision
227
- let plan = harness.plan
228
- const calibrated = yield* measure('calibrate', { plan, base: baseline, head: baseline, ...limits })
229
- const kept: (typeof Kept.Type)[] = []
230
- const tried: string[] = []
231
- let cycles = 0
232
-
233
- const ending = (status: typeof Output.Type.status, reason: string, final?: Measurement) =>
234
- Effect.gen(function* () {
235
- const stored = yield* artifact('report', {
236
- kind: 'hillclimb-report',
237
- title: 'Hillclimb findings',
238
- text: report({ discovery, harness, reason, kept, tried, final })
337
+ if (calibrated.verdict !== 'too_noisy') return new Calibrated({ summary, plan, baseline })
338
+ const switched = steadier(plan)
339
+
340
+ return switched === undefined
341
+ ? new TooNoisy({
342
+ summary,
343
+ baseline,
344
+ reason: `${calibrated.reason}. ${calibrated.suggestion ?? ''}`.trim()
239
345
  })
346
+ : new Calibrated({ summary, plan: switched, baseline })
347
+ })
348
+ })
240
349
 
241
- return { status, reason, kept, cycles, reportArtifactId: stored.artifactId, external }
242
- })
350
+ /** The change proved a gain with no guardrail worse; `head` holds it. */
351
+ export class Kept extends Schema.TaggedClass<Kept>()('Kept', {
352
+ summary: Schema.String,
353
+ reason: Schema.String,
354
+ head: Schema.String
355
+ }) {}
356
+
357
+ /** The change failed its checks or did not prove a gain, and its commits were reverted. */
358
+ export class Reverted extends Schema.TaggedClass<Reverted>()('Reverted', {
359
+ summary: Schema.String,
360
+ reason: Schema.String
361
+ }) {}
362
+
363
+ /** As `Reverted`, but the agent did not confirm the revert, so the branch may still hold the change. */
364
+ export class RevertUnconfirmed extends Schema.TaggedClass<RevertUnconfirmed>()('RevertUnconfirmed', {
365
+ summary: Schema.String,
366
+ reason: Schema.String
367
+ }) {}
368
+
369
+ export class Exhausted extends Schema.TaggedClass<Exhausted>()('Exhausted', { summary: Schema.String }) {}
370
+
371
+ export class Unsafe extends Schema.TaggedClass<Unsafe>()('Unsafe', { summary: Schema.String }) {}
372
+
373
+ /** One cycle: makes one change, checks and measures it, and reverts it to `start` unless it proves a gain. */
374
+ export const climbed = step('climbed', {
375
+ payload: {
376
+ cycle: Schema.Int,
377
+ start: Schema.String.annotate({ description: 'The head the cycle starts from, which the gain is measured over.' }),
378
+ opportunities: Discovery.fields.opportunities,
379
+ tried: Schema.Array(Schema.String).annotate({ description: 'What earlier cycles tried, a line each.' }),
380
+ plan: MeasurePlan,
381
+ ...Limits
382
+ },
383
+ success: Schema.Union([Kept, Reverted, RevertUnconfirmed, Exhausted, Unsafe]),
384
+ run: ({ cycle, start, opportunities, tried, plan, ...limits }) =>
385
+ Effect.gen(function* () {
386
+ const { status, summary } = yield* implementer('change', {
387
+ prompt: changePrompt(opportunities, plan, tried, cycle),
388
+ output: Change
389
+ })
243
390
 
244
- if (calibrated.verdict === 'too_noisy') {
245
- const switched = steadier(plan)
391
+ if (status === 'exhausted') return new Exhausted({ summary })
246
392
 
247
- if (switched === undefined)
248
- return yield* ending('too_noisy', `${calibrated.reason}. ${calibrated.suggestion ?? ''}`.trim())
393
+ if (status === 'unsafe') return new Unsafe({ summary })
394
+ const head = yield* verify('verify', {})
249
395
 
250
- plan = switched
251
- }
396
+ const measurement = head.passed
397
+ ? yield* measure('measure', { plan, base: start, head: head.revision, ...limitsOf(limits) })
398
+ : undefined
252
399
 
253
- let start = baseline
254
- let unkept = 0
400
+ if (measurement?.verdict === 'gain') return new Kept({ summary, reason: measurement.reason, head: head.revision })
255
401
 
256
- for (let cycle = 1; cycle <= (input.cycles ?? 5) && unkept < 2; cycle++) {
257
- const change = yield* agentWorkOnce(`change:${cycle}`, {
258
- agent: 'implementer',
259
- prompt: changePrompt(discovery, plan, tried, cycle),
260
- output: Change
261
- })
402
+ const reason = measurement?.reason ?? 'its checks failed'
262
403
 
263
- if (change.status !== 'changed') {
264
- tried.push(`Cycle ${cycle}: ${change.status}, ${change.summary}`)
265
- break
266
- }
404
+ const { reverted } = yield* implementer('revert', {
405
+ prompt: revertPrompt(start, cycle),
406
+ output: Schema.Struct({ reverted: Schema.Boolean })
407
+ })
267
408
 
268
- cycles = cycle
409
+ return reverted ? new Reverted({ summary, reason }) : new RevertUnconfirmed({ summary, reason })
410
+ })
411
+ })
269
412
 
270
- const head = yield* verify(`verify:${cycle}`, {})
413
+ export class Filed extends Schema.TaggedClass<Filed>()('Filed', {}) {}
271
414
 
272
- const measured = head.passed
273
- ? yield* measure(`measure:${cycle}`, { plan, base: start, head: head.revision, ...limits })
274
- : undefined
415
+ export class Unfiled extends Schema.TaggedClass<Unfiled>()('Unfiled', {}) {}
275
416
 
276
- if (measured?.verdict === 'gain') {
277
- kept.push({ summary: change.summary, verdict: measured.verdict, reason: measured.reason })
278
- tried.push(`Cycle ${cycle}, kept: ${change.summary} (${measured.reason})`)
279
- start = head.revision
280
- unkept = 0
281
- continue
282
- }
417
+ /** Asks whether to file the improvements only another repository can make as Tasks. */
418
+ export const external = step('external', {
419
+ payload: { opportunities: Discovery.fields.opportunities },
420
+ success: Schema.Union([Filed, Unfiled]),
421
+ run: ({ opportunities }) =>
422
+ Effect.gen(function* () {
423
+ const file = yield* ask('file', {
424
+ prompt: `Only other repositories can make these improvements: ${externalTitles(opportunities).join('; ')}. File them as Tasks?`,
425
+ options: ['File as Tasks', 'Leave them'],
426
+ recommended: 'File as Tasks',
427
+ recommendationReason:
428
+ 'Filed as Tasks, the improvements wait in the repositories that can make them instead of being lost.',
429
+ default: 'Leave them',
430
+ timeout: '1 hour'
431
+ })
283
432
 
284
- tried.push(
285
- `Cycle ${cycle}, reverted: ${change.summary} (${measured === undefined ? 'its checks failed' : measured.reason})`
433
+ if (file !== 'File as Tasks') return new Unfiled()
434
+
435
+ yield* createTasks('tasks', {
436
+ tickets: opportunities.flatMap((entry, index) =>
437
+ entry.external === true
438
+ ? [
439
+ {
440
+ key: `external-${index + 1}`,
441
+ title: entry.title,
442
+ body: entry.detail,
443
+ acceptanceCriteria: [],
444
+ blockedBy: [],
445
+ outcome: 'performance' as const
446
+ }
447
+ ]
448
+ : []
286
449
  )
287
- yield* agentWork(`revert:${cycle}`, {
288
- agent: 'implementer',
289
- prompt: revertPrompt(start, cycle),
290
- output: Schema.Struct({ reverted: Schema.Boolean })
291
- })
292
- unkept++
293
- }
450
+ })
294
451
 
295
- if (external.length > 0) {
296
- const file = yield* ask('external', {
297
- prompt: `Only other repositories can make these improvements: ${external.join('; ')}. File them as Tasks?`,
298
- options: ['File as Tasks', 'Leave them'],
299
- recommended: 'File as Tasks',
300
- recommendationReason:
301
- 'Filed as Tasks, the improvements wait in the repositories that can make them instead of being lost.',
302
- default: 'Leave them',
303
- timeout: '1 hour'
452
+ return new Filed()
453
+ })
454
+ })
455
+
456
+ export class Improved extends Schema.TaggedClass<Improved>()('Improved', {
457
+ /** Less what its checks printed, which its verify Step's entry holds. */
458
+ head: VerifyResult,
459
+ measurement: Measurement,
460
+ /** Whether the target was merged in before it was measured. */
461
+ merged: Schema.Boolean,
462
+ conflicts: Schema.Array(Schema.String)
463
+ }) {}
464
+
465
+ /** No change was kept, so nothing was measured. */
466
+ export class NoGain extends Schema.TaggedClass<NoGain>()('NoGain', {}) {}
467
+
468
+ /** The head no longer proves the gain. */
469
+ export class GainGone extends Schema.TaggedClass<GainGone>()('GainGone', { measurement: Measurement }) {}
470
+
471
+ /** The head fails its checks, so nothing was measured. */
472
+ export class ChecksFailed extends Schema.TaggedClass<ChecksFailed>()('ChecksFailed', {
473
+ failing: Schema.Array(Schema.String)
474
+ }) {}
475
+
476
+ /** Checks the head and measures the whole gain over the baseline. */
477
+ export const measured = step('measured', {
478
+ payload: {
479
+ kept: Schema.Int.annotate({ description: 'Changes the climb kept; with none, nothing is measured.' }),
480
+ plan: MeasurePlan,
481
+ baseline: Schema.String,
482
+ sync: Schema.optional(Schema.Struct({ target: Schema.optional(Schema.String) })).annotate({
483
+ description: 'Merges the target in first; the default branch when it names none.'
484
+ }),
485
+ revision: Schema.optional(Schema.String).annotate({
486
+ description: "What to check and measure; the branch's head when left out."
487
+ }),
488
+ ...Limits
489
+ },
490
+ success: Schema.Union([Improved, NoGain, GainGone, ChecksFailed]),
491
+ run: ({ kept, plan, baseline, sync, revision, ...limits }) =>
492
+ Effect.gen(function* () {
493
+ if (kept === 0) return new NoGain()
494
+
495
+ const synced =
496
+ sync === undefined
497
+ ? undefined
498
+ : yield* syncBase('sync', { agent: 'implementer', ...baseOf({ branch: sync.target }) })
499
+
500
+ const head = yield* verify('verify', revision === undefined ? {} : { revision })
501
+
502
+ if (!head.passed)
503
+ return new ChecksFailed({
504
+ failing: head.checks.filter(check => check.status === 'failed').map(check => check.name)
304
505
  })
305
506
 
306
- if (file === 'File as Tasks')
307
- yield* createTasks('external-tasks', {
308
- tickets: discovery.opportunities.flatMap((entry, index) =>
309
- entry.external === true
310
- ? [
311
- {
312
- key: `external-${index + 1}`,
313
- title: entry.title,
314
- body: entry.detail,
315
- acceptanceCriteria: [],
316
- blockedBy: [],
317
- outcome: 'performance' as const
318
- }
319
- ]
320
- : []
321
- )
507
+ const measurement = yield* measure('measure', {
508
+ plan,
509
+ base: baseline,
510
+ head: head.revision,
511
+ ...limitsOf(limits)
512
+ })
513
+
514
+ return measurement.verdict === 'gain'
515
+ ? new Improved({
516
+ head: withoutOutput(head),
517
+ measurement,
518
+ merged: synced?.status === 'merged',
519
+ conflicts:
520
+ synced?.status === 'conflict' ? [`Merging the base in conflicts on ${synced.files.join(', ')}`] : []
322
521
  })
323
- }
522
+ : new GainGone({ measurement })
523
+ })
524
+ })
324
525
 
325
- if (kept.length === 0) return yield* ending('no_gain', 'No change proved faster than the noise allows')
526
+ const changeRequestOf = (made: {
527
+ readonly kept: readonly KeptChange[]
528
+ readonly harness: Calibrated
529
+ readonly head: VerifyResult
530
+ readonly measurement: Measurement
531
+ readonly unsettled: readonly string[]
532
+ /** Whether the base moved during the climb. */
533
+ readonly merged: boolean
534
+ readonly rally: Pick<Settled, 'outOfScope' | 'scope'>
535
+ }) => {
536
+ const notVerified = notVerifiedSection(made.head)
537
+
538
+ const caveats = made.merged
539
+ ? ['The base moved during the climb; the final measurement includes its changes too.']
540
+ : []
541
+
542
+ return {
543
+ title: `Faster: ${made.kept.map(entry => entry.summary).join('; ')}`.slice(0, 240),
544
+ body: [
545
+ `${made.measurement.reason}, measured by Kitman against the benchmark on the base.`,
546
+ numbers(made.measurement),
547
+ `## Kept\n\n${made.kept.map(entry => `- ${entry.summary}: ${entry.reason}`).join('\n')}`,
548
+ `## Benchmark\n\n${made.harness.summary}\n\n\`${made.harness.plan.command}\``,
549
+ ...(notVerified === undefined ? [] : [notVerified]),
550
+ ...(made.unsettled.length + caveats.length === 0
551
+ ? []
552
+ : [`## Unsettled\n\n${[...made.unsettled, ...caveats].map(entry => `- ${entry}`).join('\n')}`]),
553
+ ...outOfScopeSection(outOfScopeLines(made.rally.outOfScope, made.rally.scope))
554
+ ].join('\n\n')
555
+ }
556
+ }
326
557
 
327
- const synced = yield* syncBase('sync:final', {
328
- agent: 'implementer',
329
- ...(input.branch === undefined ? undefined : { target: input.branch })
330
- })
558
+ const claimsOf = (harness: Calibrated, kept: readonly KeptChange[]) => [
559
+ 'Behaviour is preserved: every kept change leaves what the code does exactly as it was.',
560
+ `The measurement is valid: ${harness.summary}`,
561
+ ...kept.map(entry => entry.summary)
562
+ ]
563
+
564
+ type Measured = typeof measured.successSchema.Type
565
+
566
+ /** Ends the rally when its fix fails the checks or costs the gain. */
567
+ const haltUnlessImproved = (ended: Measured) => {
568
+ switch (ended._tag) {
569
+ case 'Improved':
570
+ return Effect.succeed(ended)
571
+ case 'ChecksFailed':
572
+ return Effect.fail(
573
+ new Halted({
574
+ reason: 'checks_failed',
575
+ message: `The review's fixes fail ${ended.failing.join(', ') || 'the checks'}`
576
+ })
577
+ )
578
+ case 'GainGone':
579
+ return Effect.fail(
580
+ new Halted({
581
+ reason: 'gain_gone',
582
+ message: `The review's fixes cost the gain: ${ended.measurement.reason}`,
583
+ measurement: ended.measurement
584
+ })
585
+ )
586
+ case 'NoGain':
587
+ return Effect.fail(new Halted({ reason: 'gain_gone', message: "The review's fixes cost the gain" }))
588
+ }
589
+ }
331
590
 
332
- const checked = yield* verify('verify:final', {})
591
+ const unproven = (ended: Exclude<Measured, Improved>, found: Findings) => {
592
+ switch (ended._tag) {
593
+ case 'NoGain':
594
+ return ending('no_gain', 'No change proved faster than the noise allows', found)
595
+ case 'ChecksFailed':
596
+ return ending('checks_failed', `The final tree fails ${ended.failing.join(', ') || 'its checks'}`, found)
597
+ case 'GainGone':
598
+ return ending(
599
+ 'gain_gone',
600
+ `The final tree no longer proves the gain: ${ended.measurement.reason}`,
601
+ found,
602
+ ended.measurement
603
+ )
604
+ }
605
+ }
333
606
 
334
- if (!checked.passed) {
335
- const failing = checked.checks.filter(check => check.status === 'failed').map(check => check.name)
607
+ const halted = (halt: Halted, found: Findings) => {
608
+ switch (halt.reason) {
609
+ case 'checks_failed':
610
+ return ending('checks_failed', halt.message, found)
611
+ case 'gain_gone':
612
+ return ending('gain_gone', halt.message, found, halt.measurement)
613
+ default:
614
+ return Effect.fail(halt)
615
+ }
616
+ }
336
617
 
337
- return yield* ending('checks_failed', `The final tree fails ${failing.join(', ') || 'its checks'}`)
338
- }
618
+ /** The reviewed head with the measurement of its tree, when it passes its checks and one was made. */
619
+ const provenAt = (head: VerifyResult, improvements: readonly Improved[]) => {
620
+ const proven = head.passed ? improvements.findLast(improved => improved.head.tree === head.tree) : undefined
339
621
 
340
- let final = yield* measure('measure:final', { plan, base: baseline, head: checked.revision, ...limits })
622
+ return proven === undefined
623
+ ? undefined
624
+ : new Improved({ head, measurement: proven.measurement, merged: proven.merged, conflicts: proven.conflicts })
625
+ }
341
626
 
342
- if (final.verdict !== 'gain')
343
- return yield* ending('gain_gone', `The final tree no longer proves the gain: ${final.reason}`, final)
627
+ /** What the review left blocking and what it found not done, and the base when it could not be merged in. */
628
+ const unsettledOf = ({ settled, scope }: Pick<Settled, 'settled' | 'scope'>, conflicts: readonly string[]) => [
629
+ ...[...settled.open, ...settled.standing.map(entry => entry.finding), ...scopeFindings(scope)].flatMap(finding =>
630
+ isBlocking(finding) ? [`${finding.id}: ${finding.detail}`] : []
631
+ ),
632
+ ...conflicts
633
+ ]
344
634
 
345
- const claims = [
346
- 'Behaviour is preserved: every kept change leaves what the code does exactly as it was.',
347
- `The measurement is valid: ${harness.summary}`,
348
- ...kept.map(entry => entry.summary)
349
- ]
635
+ const fixRounds = 2
350
636
 
351
- let head = checked
637
+ /**
638
+ * Climbs one measured step at a time and keeps only the steps Kitman's own measurement proves uphill. It reads the
639
+ * repository and what telemetry it can reach, commits a benchmark, measures the noise floor, then tries one change a
640
+ * cycle: kept on a gain with no guardrail worse, else reverted to the cycle's start. Two unkept cycles in a row end
641
+ * the climb. A ChangeRequest opens only when the final tree still proves the gain over the harness on the base; with
642
+ * no gain the Run ends with a findings report.
643
+ */
644
+ export default defineLoop({
645
+ id: 'hillclimb',
646
+ version: '2.0.0',
647
+ title: 'Hillclimb',
648
+ description: 'Improves a measured number one verified step at a time, keeping only the steps that prove a gain.',
649
+ outcome: 'performance',
650
+ input: Input,
651
+ output: Output,
652
+ agents: { investigator: 'climber', implementer: 'implementer' },
653
+ checkout: 'write',
654
+ capabilities: ['agent_work', 'verify', 'measure', 'change_request', 'write_back', 'ask', 'create_tasks'],
655
+ calls: () => [review],
656
+ offers: [{ id: 'retry', title: 'Climb again', loop: 'hillclimb' }],
657
+ run: input =>
658
+ Effect.gen(function* () {
659
+ const limits = limitsOf(input)
660
+ const target = input.branch ?? input.targetBranch
661
+ const discovery = yield* discovered({ focus: input.focus })
662
+ const { opportunities } = discovery
663
+ const harness = yield* harnessed({ journeys: discovery.journeys, target, ...limits })
664
+ let climb = atBaseline(harness.baseline)
352
665
 
353
- let reviewed = yield* call('review', review, {
354
- base: baseline,
355
- head: checked.revision,
356
- outcome: 'performance',
357
- ...notRunOf(checked),
358
- claims
359
- })
666
+ if (harness._tag === 'TooNoisy')
667
+ return yield* ending('too_noisy', harness.reason, { discovery, benchmark: harness.summary, climb })
360
668
 
361
- for (let round = 1; round <= 2 && reviewed.findings.some(isBlocking); round++) {
362
- const blocking = reviewed.findings.filter(isBlocking)
669
+ const { plan, baseline } = harness
363
670
 
364
- yield* agentWork(`fix:${round}`, {
365
- agent: 'implementer',
366
- prompt: fixPrompt(blocking),
367
- output: Schema.Struct({ summary: OneSentence })
368
- })
671
+ while (climbing(climb, input.cycles ?? 5)) {
672
+ const { start, tried } = climb
369
673
 
370
- const fixed = yield* verify(`verify:fix:${round}`, {})
674
+ climb = afterCycle(
675
+ climb,
676
+ yield* climbed({ cycle: climb.cycles + 1, start, opportunities, tried, plan, ...limits })
677
+ )
678
+ }
371
679
 
372
- if (!fixed.passed) {
373
- const failing = fixed.checks.filter(check => check.status === 'failed').map(check => check.name)
680
+ if (externalTitles(opportunities).length > 0) yield* external({ opportunities })
374
681
 
375
- return yield* ending('checks_failed', `The review's fixes fail ${failing.join(', ') || 'the checks'}`)
376
- }
682
+ const { kept } = climb
683
+ const findings = { discovery, benchmark: harness.summary, climb }
684
+ const gain = { kept: kept.length, plan, baseline, ...limits }
685
+ const first = yield* measured({ ...gain, sync: { target } })
377
686
 
378
- final = yield* measure(`measure:fix:${round}`, { plan, base: baseline, head: fixed.revision, ...limits })
687
+ if (first._tag !== 'Improved') return yield* unproven(first, findings)
688
+ const improvements = [first]
379
689
 
380
- if (final.verdict !== 'gain')
381
- return yield* ending('gain_gone', `The review's fixes cost the gain: ${final.reason}`, final)
690
+ const rally = yield* rallied({
691
+ base: baseline,
692
+ verified: first.head,
693
+ outcome: 'performance',
694
+ claims: claimsOf(harness, kept),
695
+ suggested: [],
696
+ maxRounds: fixRounds + 1,
697
+ fixes: 'blocking',
698
+ fixer: 'implementer',
699
+ guidance: fixGuidance,
700
+ afterFix: measured(gain).pipe(
701
+ Effect.flatMap(haltUnlessImproved),
702
+ Effect.map(improved => {
703
+ improvements.push(improved)
704
+
705
+ return improved.head
706
+ })
707
+ )
708
+ }).pipe(Effect.catchTag('Halted', halt => Effect.succeed(halt)))
382
709
 
383
- const fixedFrom = head.revision
710
+ if (rally._tag === 'Halted') return yield* halted(rally, findings)
384
711
 
385
- head = fixed
712
+ const shipped =
713
+ provenAt(rally.head, improvements) ?? (yield* measured({ ...gain, revision: rally.head.revision }))
386
714
 
387
- reviewed = yield* call(`review:${round + 1}`, review, {
388
- base: baseline,
389
- head: fixed.revision,
390
- outcome: 'performance',
391
- ...notRunOf(fixed),
392
- claims,
393
- earlier: reviewed.findings,
394
- reviewed: fixedFrom,
395
- ...(reviewed.outOfScopeFindings === undefined
396
- ? undefined
397
- : { outOfScopeFindings: reviewed.outOfScopeFindings }),
398
- ...(reviewed.scope === undefined ? undefined : { scope: reviewed.scope })
399
- })
400
- }
715
+ if (shipped._tag !== 'Improved') return yield* unproven(shipped, findings)
401
716
 
402
- const notRun = testsNotRunReasons(head)
403
- const notVerified = notVerifiedSection(head)
404
-
405
- const unsettled = [
406
- ...[...reviewed.findings, ...scopeFindings(reviewed.scope)].flatMap(finding =>
407
- isBlocking(finding) ? [`${finding.id}: ${finding.detail}`] : []
408
- ),
409
- ...(synced.status === 'conflict' ? [`Merging the base in conflicts on ${synced.files.join(', ')}`] : [])
410
- ]
411
-
412
- const caveats =
413
- synced.status === 'merged'
414
- ? ['The base moved during the climb; the final measurement includes its changes too.']
415
- : []
416
-
417
- const opened = yield* changeRequest('change-request', {
418
- title: `Faster: ${kept.map(entry => entry.summary).join('; ')}`.slice(0, 240),
419
- body: [
420
- `${final.reason}, measured by Kitman against the benchmark on the base.`,
421
- numbers(final),
422
- `## Kept\n\n${kept.map(entry => `- ${entry.summary}: ${entry.reason}`).join('\n')}`,
423
- `## Benchmark\n\n${harness.summary}\n\n\`${plan.command}\``,
424
- ...(notVerified === undefined ? [] : [notVerified]),
425
- ...(unsettled.length + caveats.length === 0
426
- ? []
427
- : [`## Unsettled\n\n${[...unsettled, ...caveats].map(entry => `- ${entry}`).join('\n')}`]),
428
- ...outOfScopeSection(outOfScopeLines(reviewed.outOfScopeFindings ?? [], reviewed.scope))
429
- ].join('\n\n')
430
- })
717
+ const { head, measurement } = shipped
718
+ const unsettled = unsettledOf(rally, first.conflicts)
431
719
 
432
- yield* writeBack('write-back', { milestone: 'change_request_opened', changeRequestUrl: opened.url })
720
+ const { changeRequest } = yield* opened(
721
+ changeRequestOf({ kept, harness, head, measurement, unsettled, merged: first.merged, rally })
722
+ )
433
723
 
434
724
  return {
435
- ...(yield* ending('improved', final.reason, final)),
436
- changeRequest: opened,
437
- unsettled: [...unsettled, ...notRun]
725
+ ...(yield* ending('improved', measurement.reason, findings, measurement)),
726
+ changeRequest,
727
+ unsettled: [...unsettled, ...testsNotRunReasons(head)]
438
728
  }
439
729
  })
440
730
  })