@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/hindsight.ts CHANGED
@@ -1,30 +1,37 @@
1
1
  import {
2
- agentWork,
3
2
  call,
4
3
  defineLoop,
5
4
  propose,
5
+ ProposeRequest,
6
+ ProposeResult,
7
+ step,
6
8
  TranscriptPoint,
7
9
  transcripts,
8
- type ProposeRequest,
9
- type TranscriptsResult
10
+ TranscriptsResult
10
11
  } from '@kitman-sh/sdk/loop'
11
12
  import * as Effect from 'effect/Effect'
12
13
  import * as Schema from 'effect/Schema'
14
+ import { investigator } from './agents'
13
15
  import build from './build'
14
16
  import errand from './errand'
15
17
  import { FindingDetail, OneSentence, Reason } from './text-limits'
16
18
 
17
19
  const Input = Schema.Struct({
18
- /** How many days back to read; a week when left out. */
19
- days: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(31))),
20
- /** Reads one Team's Runs; every Team's the Run may read when left out. */
21
- teamId: Schema.optional(Schema.String),
22
- /** Reads only the Runs of one Project's Tasks; every Project's when left out. */
23
- projectId: Schema.optional(Schema.String),
24
- /** The Project its Tasks are filed into once accepted; the Project read, else none, when left out. */
25
- fileIntoProjectId: Schema.optional(Schema.String),
26
- /** How many findings to start fixing as Errands or Builds; none when left out. */
27
- improvements: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(5)))
20
+ days: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(31))).annotate({
21
+ description: 'How many days back to read; a week when left out.'
22
+ }),
23
+ teamId: Schema.optional(Schema.String).annotate({
24
+ description: "Reads one Team's Runs; every Team's the Run may read when left out."
25
+ }),
26
+ projectId: Schema.optional(Schema.String).annotate({
27
+ description: "Reads only the Runs of one Project's Tasks; every Project's when left out."
28
+ }),
29
+ fileIntoProjectId: Schema.optional(Schema.String).annotate({
30
+ description: 'The Project its Tasks are filed into once accepted; the Project read, else none, when left out.'
31
+ }),
32
+ improvements: Schema.optional(
33
+ Schema.Int.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(5))
34
+ ).annotate({ description: 'How many findings to start fixing as Errands or Builds; none when left out.' })
28
35
  })
29
36
 
30
37
  const categories = [
@@ -72,16 +79,17 @@ const Proposal = Schema.Struct({
72
79
  })
73
80
 
74
81
  const Output = Schema.Struct({
75
- /** One line on what the Run found. */
76
- summary: OneSentence,
77
- proposals: Schema.Array(Proposal),
78
- /** Findings left out, and why. */
79
- leftOut: Schema.Array(Schema.Struct({ key: Schema.String, reason: Reason })),
82
+ summary: OneSentence.annotate({ description: 'One line on what the Run found.' }),
83
+ proposals: Schema.Array(Proposal).annotate({ description: 'The Memory and Task proposals filed from the findings.' }),
84
+ leftOut: Schema.Array(Schema.Struct({ key: Schema.String, reason: Reason })).annotate({
85
+ description: 'Findings left out, and why.'
86
+ }),
80
87
  improvements: Schema.Array(
81
88
  Schema.Struct({ key: Schema.String, loop: Schema.Literals(['errand', 'build']), outcome: Schema.String })
82
- ),
83
- /** Findings with a fix that no Run started on, and why. */
84
- notStarted: Schema.Array(Schema.Struct({ key: Schema.String, reason: Reason }))
89
+ ).annotate({ description: 'The findings it started fixing, each with the Loop and Run that took it.' }),
90
+ notStarted: Schema.Array(Schema.Struct({ key: Schema.String, reason: Reason })).annotate({
91
+ description: 'Findings with a fix that no Run started on, and why.'
92
+ })
85
93
  })
86
94
 
87
95
  type Read = TranscriptsResult
@@ -230,6 +238,121 @@ const notStartedReason = (
230
238
  ? 'A Run is already working on its Task'
231
239
  : `Only ${wanted} ${wanted === 1 ? 'improvement was' : 'improvements were'} asked for, and findings that recurred in more top-level Runs went first`
232
240
 
241
+ type Kept = { readonly finding: Finding; readonly request: ProposeRequest; readonly recurrence: number }
242
+
243
+ /** The findings to propose, and those left out with why. */
244
+ const sorted = (
245
+ findings: readonly Finding[],
246
+ runs: readonly ReadRun[],
247
+ teamId: string | undefined,
248
+ projectId: string | undefined
249
+ ) => {
250
+ const judged = findings.map(finding => ({ finding, judged: proposal(finding, runs, teamId, projectId) }))
251
+
252
+ return {
253
+ leftOut: judged.flatMap(({ finding, judged }) =>
254
+ judged.request === undefined ? [{ key: finding.key, reason: judged.reason }] : []
255
+ ),
256
+ kept: judged.flatMap(({ finding, judged }): Kept[] =>
257
+ judged.request === undefined ? [] : [{ finding, request: judged.request, recurrence: judged.recurrence }]
258
+ )
259
+ }
260
+ }
261
+
262
+ type Made = Kept & { readonly made: typeof ProposeResult.Type }
263
+
264
+ const proposalOf = ({ finding, request, recurrence, made }: Made) => ({
265
+ key: finding.key,
266
+ category: finding.category,
267
+ kind: made.kind,
268
+ id: made.id,
269
+ matched: made.matched === true,
270
+ runIds: [...new Set(request.citations.map(cited => cited.runId))],
271
+ recurrence
272
+ })
273
+
274
+ /** The findings to start fixing, those that recurred in the most top-level Runs first, and why each other was not. */
275
+ const toStart = (made: readonly Made[], wanted: number) => {
276
+ const fixable = made.flatMap(({ finding, recurrence, made }) =>
277
+ finding.fix === undefined
278
+ ? []
279
+ : [{ key: finding.key, kind: made.kind, fix: finding.fix, recurrence, task: made.task }]
280
+ )
281
+
282
+ const startable = fixable
283
+ .flatMap(finding =>
284
+ finding.task === undefined || finding.task.active ? [] : [{ ...finding, taskId: finding.task.id }]
285
+ )
286
+ .toSorted((a, b) => b.recurrence - a.recurrence)
287
+
288
+ const chosen = startable.slice(0, wanted)
289
+ const chosenKeys = new Set(chosen.map(finding => finding.key))
290
+
291
+ const notStarted =
292
+ wanted === 0
293
+ ? []
294
+ : fixable.flatMap(finding =>
295
+ chosenKeys.has(finding.key) ? [] : [{ key: finding.key, reason: notStartedReason(finding, wanted) }]
296
+ )
297
+
298
+ return { chosen, notStarted }
299
+ }
300
+
301
+ const summaryOf = (proposals: readonly { readonly matched: boolean }[], runs: number) => {
302
+ const fresh = proposals.filter(made => !made.matched).length
303
+
304
+ return proposals.length === 0
305
+ ? `Nothing recurred with evidence in ${runs} Runs.`
306
+ : `${proposals.length} recurring ${proposals.length === 1 ? 'problem' : 'problems'}: ${fresh} proposed, ${proposals.length - fresh} added to earlier work.`
307
+ }
308
+
309
+ /** What keeps going wrong across the Runs read. The Loop that uses it names an `investigator` agent. */
310
+ export const found = step('found', {
311
+ payload: { read: TranscriptsResult, days: Schema.Int },
312
+ success: Findings,
313
+ run: ({ read, days }) => investigator('find', { prompt: prompt(read, days), output: Findings })
314
+ })
315
+
316
+ /** A Memory or a Task for one finding, or the earlier proposal or open Task it adds to. */
317
+ export const proposed = step('proposed', {
318
+ payload: { key: Schema.String, request: ProposeRequest },
319
+ success: ProposeResult,
320
+ key: ({ key }) => key,
321
+ run: ({ request }) => propose('propose', request)
322
+ })
323
+
324
+ const Improvement = Schema.Struct({
325
+ key: Schema.String,
326
+ loop: Schema.Literals(['errand', 'build']),
327
+ /** How the Run it started ended. */
328
+ outcome: Schema.String
329
+ })
330
+
331
+ /** Starts fixing one finding on its Task: an Errand for a small change, a Build for a feature. */
332
+ export const improved = step('improved', {
333
+ payload: {
334
+ key: Schema.String,
335
+ size: Schema.Literals(['errand', 'build']),
336
+ words: Schema.String,
337
+ taskId: Schema.String
338
+ },
339
+ success: Improvement,
340
+ key: ({ key }) => key,
341
+ run: ({ key, size, words, taskId }) => {
342
+ const on = { words, taskId }
343
+
344
+ const started =
345
+ size === 'errand'
346
+ ? Effect.map(call('improve', errand, on), done => done.status)
347
+ : Effect.map(call('improve', build, on), built => built.stopped)
348
+
349
+ return started.pipe(
350
+ Effect.catchTag('ChildFailed', failed => Effect.succeed(`failed: ${failed.reason}`)),
351
+ Effect.map(outcome => ({ key, loop: size, outcome }))
352
+ )
353
+ }
354
+ })
355
+
233
356
  /**
234
357
  * Reads every Run that settled in the last week (or `days`), of one Team or every Team the person it acts for may
235
358
  * read, and of one Project's Tasks when given, completed ones too, as a bounded digest, and proposes Memory and
@@ -242,8 +365,9 @@ const notStartedReason = (
242
365
  */
243
366
  export default defineLoop({
244
367
  id: 'hindsight',
245
- version: '1.2.0',
368
+ version: '2.0.0',
246
369
  title: 'Hindsight',
370
+ description: "Reads the last week's settled Runs and proposes Memory and Tasks for what kept going wrong.",
247
371
  input: Input,
248
372
  output: Output,
249
373
  outcome: 'investigation',
@@ -275,90 +399,20 @@ export default defineLoop({
275
399
  notStarted: []
276
400
  }
277
401
 
278
- const { findings } = yield* agentWork('find', {
279
- agent: 'investigator',
280
- prompt: prompt(read, days),
281
- output: Findings
282
- })
283
-
284
- const fileInto = input.fileIntoProjectId ?? input.projectId
285
-
286
- const judged = findings.map(finding => ({
287
- finding,
288
- judged: proposal(finding, runs, input.teamId, fileInto)
289
- }))
290
-
291
- const leftOut = judged.flatMap(({ finding, judged }) =>
292
- judged.request === undefined ? [{ key: finding.key, reason: judged.reason }] : []
293
- )
294
-
295
- const kept = judged.flatMap(({ finding, judged }) =>
296
- judged.request === undefined ? [] : [{ finding, request: judged.request, recurrence: judged.recurrence }]
297
- )
402
+ const { findings } = yield* found({ read, days })
403
+ const { leftOut, kept } = sorted(findings, runs, input.teamId, input.fileIntoProjectId ?? input.projectId)
298
404
 
299
405
  const made = yield* Effect.forEach(kept, kept =>
300
- Effect.map(propose(`propose:${kept.finding.key}`, kept.request), made => ({ ...kept, made }))
406
+ Effect.map(proposed({ key: kept.finding.key, request: kept.request }), made => ({ ...kept, made }))
301
407
  )
302
408
 
303
- const proposals = made.map(({ finding, request, recurrence, made }) => ({
304
- key: finding.key,
305
- category: finding.category,
306
- kind: made.kind,
307
- id: made.id,
308
- matched: made.matched === true,
309
- runIds: [...new Set(request.citations.map(cited => cited.runId))],
310
- recurrence
311
- }))
312
-
313
- const wanted = input.improvements ?? 0
409
+ const proposals = made.map(proposalOf)
410
+ const { chosen, notStarted } = toStart(made, input.improvements ?? 0)
314
411
 
315
- const fixable = made.flatMap(({ finding, recurrence, made }) =>
316
- finding.fix === undefined
317
- ? []
318
- : [{ key: finding.key, kind: made.kind, fix: finding.fix, recurrence, task: made.task }]
412
+ const improvements = yield* Effect.forEach(chosen, finding =>
413
+ improved({ key: finding.key, size: finding.fix.size, words: finding.fix.words, taskId: finding.taskId })
319
414
  )
320
415
 
321
- const startable = fixable
322
- .flatMap(finding =>
323
- finding.task === undefined || finding.task.active ? [] : [{ ...finding, taskId: finding.task.id }]
324
- )
325
- .toSorted((a, b) => b.recurrence - a.recurrence)
326
-
327
- const chosen = startable.slice(0, wanted)
328
- const chosenKeys = new Set(chosen.map(finding => finding.key))
329
-
330
- const notStarted =
331
- wanted === 0
332
- ? []
333
- : fixable.flatMap(finding =>
334
- chosenKeys.has(finding.key) ? [] : [{ key: finding.key, reason: notStartedReason(finding, wanted) }]
335
- )
336
-
337
- const improvements = yield* Effect.forEach(chosen, finding => {
338
- const on = { words: finding.fix.words, taskId: finding.taskId }
339
-
340
- const started =
341
- finding.fix.size === 'errand'
342
- ? Effect.map(call(`improve:${finding.key}`, errand, on), done => done.status)
343
- : Effect.map(call(`improve:${finding.key}`, build, on), built => built.stopped)
344
-
345
- return started.pipe(
346
- Effect.catchTag('ChildFailed', failed => Effect.succeed(`failed: ${failed.reason}`)),
347
- Effect.map(outcome => ({ key: finding.key, loop: finding.fix.size, outcome }))
348
- )
349
- })
350
-
351
- const fresh = proposals.filter(made => !made.matched).length
352
-
353
- return {
354
- summary:
355
- proposals.length === 0
356
- ? `Nothing recurred with evidence in ${runs.length} Runs.`
357
- : `${proposals.length} recurring ${proposals.length === 1 ? 'problem' : 'problems'}: ${fresh} proposed, ${proposals.length - fresh} added to earlier work.`,
358
- proposals,
359
- leftOut,
360
- improvements,
361
- notStarted
362
- }
416
+ return { summary: summaryOf(proposals, runs.length), proposals, leftOut, improvements, notStarted }
363
417
  })
364
418
  })
@@ -0,0 +1,143 @@
1
+ import { Continuing, continuingBrief, LoopOutcome, step } from '@kitman-sh/sdk/loop'
2
+ import * as Effect from 'effect/Effect'
3
+ import * as Schema from 'effect/Schema'
4
+ import { implementer, plannedImplementer } from './agents'
5
+ import { CriterionAnswer, taskOf } from './build-schemas'
6
+ import { caseOf, numberedCases } from './out-of-scope'
7
+ import { SuggestedCheck } from './suggested-check'
8
+ import { ChangeRequestSummary, ShortStatement } from './text-limits'
9
+
10
+ const Change = Schema.Struct({
11
+ /** The ChangeRequest's title. */
12
+ title: Schema.String,
13
+ summary: ChangeRequestSummary,
14
+ claims: Schema.Array(ShortStatement),
15
+ /** The approved checks that run the documented commands, for a docs Outcome. */
16
+ documented: Schema.optional(Schema.Array(Schema.String)),
17
+ /** The approved check that rolls a migration back. */
18
+ rollback: Schema.optional(Schema.String),
19
+ /** Each acceptance criterion of the Task, answered; empty when it has none, left out when building from words. */
20
+ criteria: Schema.optional(Schema.Array(CriterionAnswer)),
21
+ /** Checks to run when the repository has none approved, from its package scripts or CI config. */
22
+ checks: Schema.optional(Schema.Array(SuggestedCheck))
23
+ })
24
+
25
+ const Criteria = Schema.Struct({ criteria: Schema.Array(CriterionAnswer) })
26
+
27
+ const outcomeGuidance = {
28
+ feature: 'Deliver the whole scope; review checks it was met.',
29
+ bug: 'Your failing test is already in place: make it pass.',
30
+ refactor: 'Keep behaviour exactly as it is; the approved verifications must pass before and after.',
31
+ investigation: 'Investigate and report what you found, with its sources.',
32
+ docs: 'Name, in `documented`, the approved checks that run the commands you documented.',
33
+ migration: 'Name, in `rollback`, the approved check that rolls the migration back.',
34
+ performance: 'Make it faster without changing behaviour.'
35
+ } as const satisfies { readonly [outcome in LoopOutcome]: string }
36
+
37
+ const criteriaGuidance =
38
+ '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.'
39
+
40
+ const outOfScopeGuidance = (cases: readonly string[]) =>
41
+ cases.length === 0
42
+ ? []
43
+ : [
44
+ [
45
+ "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.",
46
+ ...numberedCases(cases),
47
+ "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."
48
+ ].join('\n')
49
+ ]
50
+
51
+ const checksGuidance =
52
+ '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.'
53
+
54
+ /** How Build and Errand adapt the implement skill to a Step. */
55
+ export const implementAdaptation =
56
+ '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.'
57
+
58
+ const implementPrompt = (
59
+ task: string,
60
+ outcome: LoopOutcome | undefined,
61
+ continuing: Continuing | undefined,
62
+ cases: readonly string[]
63
+ ) =>
64
+ [
65
+ ...(continuing === undefined ? [] : [continuingBrief(continuing), 'Fix forward from there.']),
66
+ `Build ${task}`,
67
+ implementAdaptation,
68
+ ...(outcome === undefined ? [] : [outcomeGuidance[outcome]]),
69
+ '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".',
70
+ ...outOfScopeGuidance(cases),
71
+ criteriaGuidance,
72
+ checksGuidance
73
+ ].join('\n\n')
74
+
75
+ const criteriaPrompt = (unanswered: boolean, unmet: readonly CriterionAnswer[], cases: readonly string[]) =>
76
+ [
77
+ unanswered
78
+ ? "You did not answer the Task's acceptance criteria. Answer each one before anyone reviews the change."
79
+ : '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:',
80
+ ...unmet.map(answer => `- ${answer.criterion}: ${answer.detail}`),
81
+ ...outOfScopeGuidance(cases),
82
+ criteriaGuidance
83
+ ].join('\n\n')
84
+
85
+ /** The change is in the workspace, with the Task's acceptance criteria answered; none when it has none. */
86
+ export class Implemented extends Schema.TaggedClass<Implemented>()('Implemented', {
87
+ ...Change.fields,
88
+ criteria: Schema.Array(CriterionAnswer)
89
+ }) {}
90
+
91
+ /**
92
+ * Has the Loop's `implementer`, or its `planned-implementer` for a plan-reviewed Task's first implementation, implement the Task or words and answer the Task's acceptance criteria, sending what is
93
+ * missing or unmet back once.
94
+ */
95
+ export const implemented = step('implemented', {
96
+ payload: {
97
+ words: Schema.optional(Schema.String).annotate({ description: 'What to build; the Task when left out.' }),
98
+ taskId: Schema.optional(Schema.String).annotate({
99
+ description: 'The Task whose acceptance criteria the change answers.'
100
+ }),
101
+ outcome: Schema.optional(LoopOutcome).annotate({ description: 'The Outcome the change must prove.' }),
102
+ continuing: Schema.optional(Continuing).annotate({
103
+ description: 'The earlier Run whose branch this one continues.'
104
+ }),
105
+ cases: Schema.optional(Schema.Array(Schema.String)).annotate({
106
+ description: "The Task's Out of scope list, which the implementer does not build."
107
+ }),
108
+ planReviewed: Schema.optional(Schema.Boolean).annotate({
109
+ description:
110
+ 'Plan review passed the Task and this is its first implementation: the `planned-implementer` makes it.'
111
+ })
112
+ },
113
+ success: Implemented,
114
+ run: ({ words, taskId, outcome, continuing, cases = [], planReviewed }) =>
115
+ Effect.gen(function* () {
116
+ const work = {
117
+ skill: 'implement',
118
+ prompt: implementPrompt(taskOf(words), outcome, continuing, cases),
119
+ output: Change
120
+ }
121
+
122
+ const change = yield* planReviewed === true
123
+ ? plannedImplementer('implement', work)
124
+ : implementer('implement', work)
125
+
126
+ // An empty list says the Task has none; only a missing one goes back.
127
+ const unanswered = taskId !== undefined && change.criteria === undefined
128
+
129
+ // A criterion the implementer puts in an Out of scope case is Review's to judge, not sent back.
130
+ const unmet = (change.criteria ?? []).filter(
131
+ answer => answer.status === 'not_met' && caseOf(cases, answer) === undefined
132
+ )
133
+
134
+ if (!unanswered && unmet.length === 0) return new Implemented({ ...change, criteria: change.criteria ?? [] })
135
+
136
+ const { criteria } = yield* implementer('criteria', {
137
+ prompt: criteriaPrompt(unanswered, unmet, cases),
138
+ output: Criteria
139
+ })
140
+
141
+ return new Implemented({ ...change, criteria })
142
+ })
143
+ })