@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/tidy.ts CHANGED
@@ -1,38 +1,46 @@
1
1
  import {
2
- agentWork,
2
+ agent,
3
3
  artifact,
4
4
  ask,
5
5
  call,
6
- changeRequest,
7
6
  ChangeRequestResult,
8
7
  defineLoop,
9
8
  evidenceGate,
10
9
  RunFile,
11
10
  rallyStop,
12
11
  settleRound,
12
+ step,
13
13
  syncBase,
14
14
  testsNotRunReasons,
15
- verify
15
+ verify,
16
+ type VerifyResult
16
17
  } from '@kitman-sh/sdk/loop'
17
18
  import * as Effect from 'effect/Effect'
18
19
  import * as Schema from 'effect/Schema'
20
+ import { implementer } from './agents'
19
21
  import { changeRequestBody, unsettledItems } from './change-request-body'
22
+ import { opened } from './opened'
20
23
  import { outOfScopeLines } from './out-of-scope'
21
24
  import plan from './plan'
22
- import review from './review'
25
+ import review, { type ReviewOutput } from './review'
23
26
  import { OneSentence, ShortStatement } from './text-limits'
27
+ import { baseOf, TargetBranchField } from './delivery'
28
+
29
+ const surveyor = agent('surveyor')
24
30
 
25
31
  const Input = Schema.Struct({
26
- /**
27
- * The head of a change to tidy, such as a Build's: Tidy then touches only that change's area and opens at most one
28
- * ChangeRequest, unasked. Left out, Tidy surveys and asks what next.
29
- */
30
- revision: Schema.optional(Schema.String),
31
- /** The branch the ChangeRequest targets; the repository's default branch when left out. */
32
- branch: Schema.optional(Schema.String),
33
- repoBindingId: Schema.optional(Schema.String),
34
- /** Where to look, in a few words. */
35
- words: Schema.optional(Schema.String)
32
+ revision: Schema.optional(Schema.String).annotate({
33
+ description:
34
+ "The head of a change to tidy, such as a Build's: Tidy then touches only that change's area and opens at most one ChangeRequest, unasked. Left out, Tidy surveys and asks what next."
35
+ }),
36
+ branch: Schema.optional(Schema.String).annotate({
37
+ description: "The branch the ChangeRequest targets; the repository's default branch when left out."
38
+ }),
39
+ ...TargetBranchField,
40
+ repoBindingId: Schema.optional(Schema.String).annotate({
41
+ description: "The repository to tidy; the Team's default repository when left out."
42
+ }),
43
+ words: Schema.optional(Schema.String).annotate({ description: 'Where to look, in a few words.' })
36
44
  })
37
45
 
38
46
  const Hint = Schema.Literals(['architecture', 'simplification'])
@@ -46,7 +54,7 @@ const Candidate = Schema.Struct({
46
54
  worth: Schema.String
47
55
  })
48
56
 
49
- const Survey = Schema.Struct({
57
+ const SurveyAnswer = Schema.Struct({
50
58
  /** The report, as Markdown. */
51
59
  report: Schema.String,
52
60
  /** The skill's HTML report, attached to the Run. */
@@ -65,7 +73,7 @@ const Survey = Schema.Struct({
65
73
  ).check(Schema.isMaxLength(3))
66
74
  })
67
75
 
68
- const Tidied = Schema.Struct({
76
+ const TidyAnswer = Schema.Struct({
69
77
  /** Whether it changed anything; false is a good outcome when nothing is worth it. */
70
78
  improved: Schema.Boolean,
71
79
  hint: Schema.optional(Hint),
@@ -75,12 +83,22 @@ const Tidied = Schema.Struct({
75
83
  })
76
84
 
77
85
  const Output = Schema.Struct({
78
- status: Schema.Literals(['nothing_worth_it', 'reported', 'planned', 'opened']),
79
- summary: Schema.String,
80
- reportArtifactId: Schema.optional(Schema.String),
81
- changeRequest: Schema.optional(ChangeRequestResult),
82
- settled: Schema.optional(Schema.Boolean),
83
- unsettled: Schema.optional(Schema.Array(Schema.String))
86
+ status: Schema.Literals(['nothing_worth_it', 'reported', 'planned', 'opened']).annotate({
87
+ description: 'nothing worth it, reported, planned as Tasks, or opened a ChangeRequest.'
88
+ }),
89
+ summary: Schema.String.annotate({ description: 'What Tidy found or did, in a line.' }),
90
+ reportArtifactId: Schema.optional(Schema.String).annotate({
91
+ description: 'The Artifact holding the report, when it wrote one.'
92
+ }),
93
+ changeRequest: Schema.optional(ChangeRequestResult).annotate({
94
+ description: 'The ChangeRequest it opened, when it opened one.'
95
+ }),
96
+ settled: Schema.optional(Schema.Boolean).annotate({
97
+ description: "Whether the ChangeRequest's review rally ended with nothing left standing."
98
+ }),
99
+ unsettled: Schema.optional(Schema.Array(Schema.String)).annotate({
100
+ description: 'What still stands on the ChangeRequest, one line each.'
101
+ })
84
102
  })
85
103
 
86
104
  type Output = typeof Output.Type
@@ -116,8 +134,143 @@ const tidyPrompt = (scope: string, words: string | undefined) =>
116
134
  const areaOf = (revision: string, branch: string | undefined) =>
117
135
  `in the area of the change at ${revision}: only the files that \`git diff $(git merge-base origin/${branch ?? 'HEAD'} ${revision}) ${revision}\` touches, and the files that change with them`
118
136
 
137
+ /** The report, with the improvements worth making, most valuable first; none when nothing is worth it. */
138
+ export class Surveyed extends Schema.TaggedClass<Surveyed>()('Surveyed', {
139
+ report: Schema.String,
140
+ htmlReport: Schema.optional(RunFile),
141
+ candidates: Schema.Array(Candidate)
142
+ }) {}
143
+
144
+ /**
145
+ * Surveys the repository for the improvements worth making, and again with the answers when the code could not tell it
146
+ * something. The Loop that uses it names a `surveyor` agent.
147
+ */
148
+ export const surveyed = step('surveyed', {
149
+ payload: { words: Schema.optional(Schema.String).annotate({ description: 'Where to look, in a few words.' }) },
150
+ success: Surveyed,
151
+ run: ({ words }) =>
152
+ Effect.gen(function* () {
153
+ const survey = yield* surveyor('survey', {
154
+ skill: 'improve-codebase-architecture',
155
+ prompt: surveyPrompt(words, []),
156
+ output: SurveyAnswer
157
+ })
158
+
159
+ if (survey.questions.length === 0)
160
+ return new Surveyed({ report: survey.report, htmlReport: survey.htmlReport, candidates: survey.candidates })
161
+
162
+ const answers = yield* Effect.forEach(survey.questions, (question, index) =>
163
+ Effect.map(
164
+ ask(`question:${index + 1}`, {
165
+ prompt: question.question,
166
+ freeText: true,
167
+ recommended: question.recommended,
168
+ recommendationReason: question.why,
169
+ default: 'No answer; go by the code.',
170
+ timeout: '1 day'
171
+ }),
172
+ answer => `- ${question.question} ${answer}`
173
+ )
174
+ )
175
+
176
+ const { report, htmlReport, candidates } = yield* surveyor('survey:answered', {
177
+ skill: 'improve-codebase-architecture',
178
+ prompt: surveyPrompt(words, answers),
179
+ output: SurveyAnswer
180
+ })
181
+
182
+ return new Surveyed({ report, htmlReport, candidates })
183
+ })
184
+ })
185
+
186
+ export class Tidied extends Schema.TaggedClass<Tidied>()('Tidied', {
187
+ title: Schema.optional(Schema.String),
188
+ summary: Schema.String,
189
+ claims: Schema.Array(Schema.String)
190
+ }) {}
191
+
192
+ /** Nothing was worth changing, as `summary` says why, so it changed nothing. */
193
+ export class NothingWorthIt extends Schema.TaggedClass<NothingWorthIt>()('NothingWorthIt', {
194
+ summary: Schema.String
195
+ }) {}
196
+
197
+ /** Makes the one improvement worth most. The Loop that uses it names an `implementer` agent. */
198
+ export const tidied = step('tidied', {
199
+ payload: {
200
+ revision: Schema.optional(Schema.String).annotate({
201
+ description: 'The head of the change whose area to tidy; the whole repository when left out.'
202
+ }),
203
+ branch: Schema.optional(Schema.String).annotate({
204
+ description: 'The branch that change is against; the default branch when left out.'
205
+ }),
206
+ words: Schema.optional(Schema.String).annotate({ description: 'Where to look, or what to change.' })
207
+ },
208
+ success: Schema.Union([Tidied, NothingWorthIt]),
209
+ run: ({ revision, branch, words }) =>
210
+ Effect.gen(function* () {
211
+ const { improved, title, summary, claims } = yield* implementer('tidy', {
212
+ prompt: tidyPrompt(revision === undefined ? '' : areaOf(revision, branch), words),
213
+ output: TidyAnswer
214
+ })
215
+
216
+ return improved ? new Tidied({ title, summary, claims }) : new NothingWorthIt({ summary })
217
+ })
218
+ })
219
+
119
220
  const next = ['Plan it', 'Tidy the top one now', 'Done'] as const
120
221
 
222
+ const chosen = (survey: Surveyed, top: typeof Candidate.Type) =>
223
+ ask('chosen', {
224
+ prompt: `Tidy found ${survey.candidates.length} worth doing, top: ${top.title}. ${top.worth}\n\nWhat next?`,
225
+ options: [
226
+ { value: 'Plan it', description: 'Plan plans the candidates for you to review, then files them as Tasks.' },
227
+ { value: 'Tidy the top one now', description: 'An agent makes the top one and opens a ChangeRequest.' },
228
+ { value: 'Done', description: 'Keep the report and stop.' }
229
+ ] satisfies { readonly value: (typeof next)[number]; readonly description: string }[],
230
+ recommended: 'Tidy the top one now',
231
+ recommendationReason: `The top one is worth a reviewer's time on its own: ${top.worth}`,
232
+ default: 'Done',
233
+ timeout: '1 day'
234
+ })
235
+
236
+ const planWords = (survey: Surveyed) =>
237
+ [
238
+ 'Plan these code-quality improvements:',
239
+ ...survey.candidates.map(candidate => `- ${candidate.title}: ${candidate.words}`),
240
+ survey.report
241
+ ].join('\n\n')
242
+
243
+ /** What the one Review and the evidence gate leave unsettled, and the ChangeRequest's description saying so. */
244
+ const gated = ({
245
+ improvement,
246
+ base,
247
+ head,
248
+ reviewed
249
+ }: {
250
+ readonly improvement: Tidied
251
+ readonly base: VerifyResult
252
+ readonly head: VerifyResult
253
+ readonly reviewed: typeof ReviewOutput.Type
254
+ }) => {
255
+ const settled = settleRound({ findings: reviewed.findings, rebuttals: [], verdicts: reviewed.verdicts })
256
+ const decision = rallyStop({ round: 1, maxRounds: 1, settled })
257
+ const verdict = evidenceGate({ outcome: 'refactor', base, head })
258
+ const unsettled = [...(verdict.settled ? [] : verdict.reasons), ...unsettledItems(settled)]
259
+
260
+ return {
261
+ unsettled,
262
+ body: changeRequestBody({
263
+ summary: improvement.summary,
264
+ head,
265
+ claims: improvement.claims,
266
+ unsettled,
267
+ outOfScope: outOfScopeLines(reviewed.outOfScopeFindings ?? [], reviewed.scope),
268
+ rounds: 1,
269
+ stopped: decision.stop ? decision.reason : 'round_cap'
270
+ })
271
+ }
272
+ }
273
+
121
274
  /**
122
275
  * Finds the code-quality improvement worth most and makes it reviewable in one sitting, or says nothing is worth it.
123
276
  * Given a change's head, such as from a Build's offer, it tidies that change's area once, verifies base and head,
@@ -126,167 +279,97 @@ const next = ['Plan it', 'Tidy the top one now', 'Done'] as const
126
279
  */
127
280
  export default defineLoop({
128
281
  id: 'tidy',
129
- version: '1.1.0',
282
+ version: '2.1.0',
130
283
  title: 'Tidy',
284
+ description: 'Finds the code-quality improvement worth most and opens it as one reviewable ChangeRequest.',
131
285
  input: Input,
132
286
  output: Output,
133
287
  agents: { implementer: 'implementer', surveyor: 'surveyor' },
134
288
  checkout: 'write',
135
- capabilities: ['agent_work', 'ask', 'verify', 'change_request'],
289
+ capabilities: ['agent_work', 'ask', 'verify', 'change_request', 'write_back'],
136
290
  calls: () => [review, plan],
137
291
  run: input =>
138
292
  Effect.gen(function* () {
139
- const start = input.revision ?? `origin/${input.branch ?? 'HEAD'}`
140
-
141
- /** One improvement, verified on base and head and reviewed once, so the reviewed diff is the one that ships. */
142
- const tidy = (scope: string, words: string | undefined) =>
143
- Effect.gen(function* () {
144
- const improvement = yield* agentWork('tidy', {
145
- agent: 'implementer',
146
- prompt: tidyPrompt(scope, words),
147
- output: Tidied
148
- })
293
+ let words = input.words
294
+ let report: Pick<Output, 'reportArtifactId'> = {}
149
295
 
150
- if (!improvement.improved)
151
- return { status: 'nothing_worth_it', summary: improvement.summary } satisfies Output
296
+ if (input.revision === undefined) {
297
+ const survey = yield* surveyed({ words })
152
298
 
153
- const base = yield* verify('verify:base', { revision: start })
154
- const head = yield* verify('verify', {})
155
- const notRun = testsNotRunReasons(head)
299
+ const stored = yield* artifact('report', {
300
+ kind: 'tidy_report',
301
+ title: 'Tidy report',
302
+ text: survey.report,
303
+ ...(survey.htmlReport === undefined ? undefined : { files: [survey.htmlReport] })
304
+ })
156
305
 
157
- const reviewed = yield* call('review', review, {
158
- base: start,
159
- head: head.revision,
160
- outcome: 'refactor',
161
- ...(notRun.length === 0 ? undefined : { notRun }),
162
- claims: improvement.claims
163
- })
306
+ const [top] = survey.candidates
164
307
 
165
- const settled = settleRound({ findings: reviewed.findings, rebuttals: [], verdicts: reviewed.verdicts })
166
- const decision = rallyStop({ round: 1, maxRounds: 1, settled })
167
- const verdict = evidenceGate({ outcome: 'refactor', base, head })
168
-
169
- const unsettled = [
170
- ...(verdict.settled ? [] : verdict.reasons),
171
- ...(decision.stop ? unsettledItems(settled, decision) : [])
172
- ]
173
-
174
- const opened = yield* changeRequest('change-request', {
175
- title: improvement.title ?? 'Tidy',
176
- body: changeRequestBody({
177
- summary: improvement.summary,
178
- head,
179
- claims: improvement.claims,
180
- unsettled,
181
- outOfScope: outOfScopeLines(reviewed.outOfScopeFindings ?? [], reviewed.scope),
182
- rounds: 1,
183
- stopped: decision.stop ? decision.reason : 'round_cap'
184
- })
185
- })
308
+ report = { reportArtifactId: stored.artifactId }
186
309
 
310
+ if (top === undefined)
187
311
  return {
188
- status: 'opened',
189
- summary: improvement.summary,
190
- changeRequest: opened,
191
- settled: unsettled.length === 0,
192
- unsettled
312
+ ...report,
313
+ status: 'nothing_worth_it',
314
+ summary: 'Nothing here is worth a reviewer’s time.'
193
315
  } satisfies Output
194
- })
195
316
 
196
- if (input.revision !== undefined) return yield* tidy(areaOf(input.revision, input.branch), input.words)
317
+ const choice = yield* chosen(survey, top)
197
318
 
198
- let survey = yield* agentWork('survey', {
199
- agent: 'surveyor',
200
- skill: 'improve-codebase-architecture',
201
- prompt: surveyPrompt(input.words, []),
202
- output: Survey
203
- })
319
+ if (choice === 'Done') return { ...report, status: 'reported', summary: `Top: ${top.title}` } satisfies Output
204
320
 
205
- if (survey.questions.length > 0) {
206
- const answers = yield* Effect.forEach(survey.questions, (question, index) =>
207
- Effect.map(
208
- ask(`question:${index + 1}`, {
209
- prompt: question.question,
210
- freeText: true,
211
- recommended: question.recommended,
212
- recommendationReason: question.why,
213
- default: 'No answer; go by the code.',
214
- timeout: '1 day'
215
- }),
216
- answer => `- ${question.question} ${answer}`
217
- )
218
- )
321
+ if (choice === 'Plan it') {
322
+ yield* call('plan', plan, {
323
+ words: planWords(survey),
324
+ ...(input.repoBindingId === undefined ? undefined : { repoBindingId: input.repoBindingId }),
325
+ ...(input.branch === undefined ? undefined : { branch: input.branch })
326
+ })
219
327
 
220
- survey = yield* agentWork('survey:answered', {
221
- agent: 'surveyor',
222
- skill: 'improve-codebase-architecture',
223
- prompt: surveyPrompt(input.words, answers),
224
- output: Survey
225
- })
226
- }
328
+ return { ...report, status: 'planned', summary: `Top: ${top.title}` } satisfies Output
329
+ }
227
330
 
228
- const stored = yield* artifact('report', {
229
- kind: 'tidy_report',
230
- title: 'Tidy report',
231
- text: survey.report,
232
- ...(survey.htmlReport === undefined ? undefined : { files: [survey.htmlReport] })
233
- })
331
+ // The answer can come a day after the survey: tidy on the base as it is now.
332
+ const synced = yield* syncBase('sync', { agent: 'implementer', ...baseOf(input) })
234
333
 
235
- const [top] = survey.candidates
236
-
237
- if (top === undefined)
238
- return {
239
- status: 'nothing_worth_it',
240
- summary: 'Nothing here is worth a reviewer’s time.',
241
- reportArtifactId: stored.artifactId
242
- } satisfies Output
243
-
244
- const answer = yield* ask('next', {
245
- prompt: `Tidy found ${survey.candidates.length} worth doing, top: ${top.title}. ${top.worth}\n\nWhat next?`,
246
- options: [
247
- { value: 'Plan it', description: 'Plan plans the candidates for you to review, then files them as Tasks.' },
248
- { value: 'Tidy the top one now', description: 'An agent makes the top one and opens a ChangeRequest.' },
249
- { value: 'Done', description: 'Keep the report and stop.' }
250
- ] satisfies { readonly value: (typeof next)[number]; readonly description: string }[],
251
- recommended: 'Tidy the top one now',
252
- recommendationReason: `The top one is worth a reviewer's time on its own: ${top.worth}`,
253
- default: 'Done',
254
- timeout: '1 day'
255
- })
334
+ if (synced.status === 'conflict')
335
+ return {
336
+ ...report,
337
+ status: 'reported',
338
+ summary: `Top: ${top.title}. Bringing the branch up to date conflicts on ${synced.files.join(', ')}`
339
+ } satisfies Output
256
340
 
257
- const reported = { summary: `Top: ${top.title}`, reportArtifactId: stored.artifactId }
341
+ words = `${top.title}: ${top.words}`
342
+ }
258
343
 
259
- if (answer === 'Done') return { status: 'reported', ...reported } satisfies Output
344
+ const improvement = yield* tidied({ revision: input.revision, branch: input.branch, words })
260
345
 
261
- if (answer === 'Plan it') {
262
- yield* call('plan', plan, {
263
- words: [
264
- 'Plan these code-quality improvements:',
265
- ...survey.candidates.map(candidate => `- ${candidate.title}: ${candidate.words}`),
266
- survey.report
267
- ].join('\n\n'),
268
- ...(input.repoBindingId === undefined ? undefined : { repoBindingId: input.repoBindingId }),
269
- ...(input.branch === undefined ? undefined : { branch: input.branch })
270
- })
346
+ if (improvement._tag === 'NothingWorthIt')
347
+ return { ...report, status: 'nothing_worth_it', summary: improvement.summary } satisfies Output
271
348
 
272
- return { status: 'planned', ...reported } satisfies Output
273
- }
349
+ // Verified on base and head and reviewed once, so the reviewed diff is the one that ships.
350
+ const start = input.revision ?? `origin/${input.branch ?? input.targetBranch ?? 'HEAD'}`
351
+ const base = yield* verify('verify:base', { revision: start })
352
+ const head = yield* verify('verify', {})
353
+ const notRun = testsNotRunReasons(head)
274
354
 
275
- // The answer can come a day after the survey: tidy on the base as it is now.
276
- const synced = yield* syncBase('sync', {
277
- agent: 'implementer',
278
- ...(input.branch === undefined ? undefined : { target: input.branch })
355
+ const reviewed = yield* call('review', review, {
356
+ base: start,
357
+ head: head.revision,
358
+ outcome: 'refactor',
359
+ ...(notRun.length === 0 ? undefined : { notRun }),
360
+ claims: improvement.claims
279
361
  })
280
362
 
281
- if (synced.status === 'conflict')
282
- return {
283
- status: 'reported',
284
- ...reported,
285
- summary: `Top: ${top.title}. Bringing the branch up to date conflicts on ${synced.files.join(', ')}`
286
- } satisfies Output
287
-
288
- const tidied = yield* tidy('', `${top.title}: ${top.words}`)
289
-
290
- return { ...tidied, reportArtifactId: stored.artifactId } satisfies Output
363
+ const { unsettled, body } = gated({ improvement, base, head, reviewed })
364
+ const { changeRequest } = yield* opened({ title: improvement.title ?? 'Tidy', body })
365
+
366
+ return {
367
+ ...report,
368
+ status: 'opened',
369
+ summary: improvement.summary,
370
+ changeRequest,
371
+ settled: unsettled.length === 0,
372
+ unsettled
373
+ } satisfies Output
291
374
  })
292
375
  })