iterate-plugin 2.11.0 → 2.12.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.
@@ -0,0 +1,334 @@
1
+ /**
2
+ * src/tools/transcript.ts — `iterate_transcript` tool.
3
+ *
4
+ * Exposes the runtime-observatory manifest to the model (and, via its persisted
5
+ * on-disk copy, to the client observatory panel). Purely local, deterministic,
6
+ * and safe:
7
+ *
8
+ * - `read` — return the persisted transcript manifest (or a structured
9
+ * "not found" empty view). Used each round by the workflow to
10
+ * pick up steering nudges, and polled by tool-reading agents.
11
+ * - `capture` — build a fresh transcript from the review `rounds` + `report`
12
+ * and persist it. Called by the canonical scripts after the
13
+ * final aggregate so the client always sees the latest run.
14
+ * - `nudge` — set (`text`) or clear (`text: null`) steering text persisted
15
+ * for the next round's reviewers to read.
16
+ *
17
+ * All writes are persisted to `.iterate/transcript.json` via an atomic
18
+ * tmp+rename so a crashed writer never leaves a corrupt manifest.
19
+ */
20
+
21
+ import { defineTool } from '@deepseek-ai/dsh-tools'
22
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
23
+ import { existsSync } from 'node:fs'
24
+ import { dirname } from 'node:path'
25
+ import type { JsonValue } from '@deepseek-ai/dsh-session'
26
+ import {
27
+ loadEffectiveConfig,
28
+ resolveProjectRootForExec,
29
+ } from '../config-loader.ts'
30
+ import { transcriptPath } from '../paths.ts'
31
+ import { ReviewTranscriptBuilder } from '../transcript.ts'
32
+ import { readLive } from '../live.ts'
33
+ import type {
34
+ TranscriptManifest,
35
+ TranscriptFix,
36
+ } from '../types.ts'
37
+
38
+ /** Build per-dimension threads for one round from its (dimension-tagged) findings. */
39
+ function captureRound(builder: ReviewTranscriptBuilder, round: unknown): void {
40
+ if (!round || typeof round !== 'object') return
41
+ const r = round as {
42
+ round?: unknown
43
+ findings?: unknown
44
+ readFiles?: unknown
45
+ }
46
+ const roundNo = typeof r.round === 'number' ? Math.floor(r.round) : 0
47
+ if (roundNo <= 0) return
48
+ builder.roundStart(roundNo)
49
+ const findings = Array.isArray(r.findings) ? r.findings : []
50
+ const readFiles = Array.isArray(r.readFiles) ? r.readFiles : []
51
+ // Group the round's findings by dimension → one reviewer thread each.
52
+ const byDim = new Map<string, unknown[]>()
53
+ for (const f of findings) {
54
+ if (!f || typeof f !== 'object') continue
55
+ const rec = f as Record<string, unknown>
56
+ const dim = typeof rec.dimension === 'string' && rec.dimension ? rec.dimension : 'review'
57
+ const list = byDim.get(dim) ?? []
58
+ list.push(f)
59
+ byDim.set(dim, list)
60
+ }
61
+ if (byDim.size === 0) {
62
+ builder.reviewerSnapshot('review', [], readFiles)
63
+ } else {
64
+ for (const [dim, list] of byDim) builder.reviewerSnapshot(dim, list, readFiles)
65
+ }
66
+ }
67
+
68
+ /** Normalize the checkpoint shape if present. */
69
+ function normalizeCheckpoint(input: unknown): TranscriptManifest['checkpoint'] {
70
+ if (!input || typeof input !== 'object') return null
71
+ const c = input as Record<string, unknown>
72
+ const round = typeof c.round === 'number' ? c.round : 0
73
+ if (round <= 0) return null
74
+ return {
75
+ mode: c.mode === 'dry-run' || c.mode === 'normal' ? c.mode : 'normal',
76
+ round,
77
+ maxRounds: typeof c.maxRounds === 'number' ? c.maxRounds : 0,
78
+ fixedCount: typeof c.fixedCount === 'number' ? c.fixedCount : 0,
79
+ resumeCount: typeof c.resumeCount === 'number' ? c.resumeCount : 0,
80
+ updatedAt: typeof c.updatedAt === 'string' ? c.updatedAt : new Date().toISOString(),
81
+ }
82
+ }
83
+
84
+ /** Normalize a fix record. */
85
+ function normalizeFix(input: unknown): TranscriptFix | null {
86
+ if (!input || typeof input !== 'object') return null
87
+ const f = input as Record<string, unknown>
88
+ const id = typeof f.id === 'string' ? f.id : ''
89
+ const file = typeof f.file === 'string' ? f.file : ''
90
+ if (!id || !file) return null
91
+ return {
92
+ id,
93
+ timestamp: typeof f.timestamp === 'string' ? f.timestamp : new Date().toISOString(),
94
+ round: typeof f.round === 'number' ? f.round : 0,
95
+ file,
96
+ summary: typeof f.summary === 'string' ? f.summary : '',
97
+ linesAdded: typeof f.linesAdded === 'number' ? f.linesAdded : 0,
98
+ linesRemoved: typeof f.linesRemoved === 'number' ? f.linesRemoved : 0,
99
+ success: f.success !== false,
100
+ }
101
+ }
102
+
103
+ /** Register the `iterate_transcript` tool. */
104
+ export function registerTranscriptTool(ctx: {
105
+ tools: { register: (def: ReturnType<typeof defineTool>) => void }
106
+ }): void {
107
+ ctx.tools.register(
108
+ defineTool({
109
+ name: 'iterate_transcript',
110
+ description:
111
+ 'Runtime-observatory transcript for the iterate workflow. ' +
112
+ '`read` returns the current persisted transcript manifest (per-reviewer threads, ' +
113
+ 'convergence series, findings, fixes, checkpoint, timeline, and any steering nudge ' +
114
+ 'written for the next round). ' +
115
+ '`capture` builds a fresh transcript from the review `rounds` + `report` and persists it ' +
116
+ '(call once after the final aggregate so the UI reflects the run). ' +
117
+ '`nudge` sets (text) or clears (text:null) steering text the next round\'s reviewers read. ' +
118
+ 'Purely local and deterministic — never touches source files.',
119
+ parameters: {
120
+ operation: {
121
+ type: 'string',
122
+ required: true,
123
+ description: '"read" to fetch the manifest, "capture" to persist one, "nudge" to set steering text.',
124
+ enum: ['read', 'capture', 'nudge'],
125
+ },
126
+ rounds: {
127
+ type: 'json',
128
+ description: 'For `capture`: per-round findings, each [{round, findings:[{dimension,file,line?,severity,summary,…}], readFiles:[…]}].',
129
+ },
130
+ report: {
131
+ type: 'json',
132
+ description: 'For `capture`: the ReviewReport (convergence.findingsByRound used for the trend).',
133
+ },
134
+ mode: {
135
+ type: 'string',
136
+ description: 'For `capture`: run mode ("dry-run" | "normal"). Default dry-run.',
137
+ enum: ['dry-run', 'normal'],
138
+ },
139
+ goal: { type: 'string', description: 'For `capture`: run goal.' },
140
+ maxRounds: { type: 'integer', description: 'For `capture`: round cap.' },
141
+ roundsExecuted: { type: 'integer', description: 'For `capture`: number of rounds actually executed.' },
142
+ findingsByRound: { type: 'json', description: 'For `capture`: the per-round new-findings count series (report.convergence.findingsByRound). Preferred over passing the whole report.' },
143
+ checkpoint: { type: 'json', description: 'For `capture`: checkpoint summary (optional).' },
144
+ fixes: {
145
+ type: 'json',
146
+ description: 'For `capture`: array of applied fixes [{id, file, round, summary, linesAdded, linesRemoved, success}].',
147
+ },
148
+ refReadFiles: { type: 'json', description: 'For `capture`: flat array of all read files across rounds (optional).' },
149
+ text: { type: 'string', description: 'For `nudge`: steering text to set (or null to clear).' },
150
+ path: { type: 'string', description: 'Project root directory (default: current working directory).' },
151
+ },
152
+
153
+ output: {
154
+ schema: {
155
+ type: 'object',
156
+ additionalProperties: false,
157
+ properties: {
158
+ operation: { type: 'string', required: true },
159
+ found: { type: 'boolean' },
160
+ transcript: { type: 'json' },
161
+ live: { type: 'json', description: 'Recent live reviewer-activity entries (newest first).' },
162
+ updated: { type: 'boolean' },
163
+ error: { type: 'string' },
164
+ },
165
+ },
166
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
167
+ },
168
+
169
+ async execute(args, exec) {
170
+ const resolved = resolveProjectRootForExec(exec, args.path)
171
+ if (!resolved.ok) return { operation: args.operation, error: resolved.reason }
172
+ const projectRoot = resolved.root
173
+ const file = transcriptPath(projectRoot)
174
+ const { config } = loadEffectiveConfig(projectRoot)
175
+ const approval = config.observatory?.approval ?? 'ask'
176
+
177
+ if (args.operation === 'read') {
178
+ const live = await readLive(projectRoot)
179
+ if (!existsSync(file)) {
180
+ return {
181
+ operation: 'read',
182
+ found: false,
183
+ live: live as unknown as JsonValue,
184
+ transcript: new ReviewTranscriptBuilder({
185
+ project: projectRoot,
186
+ approval,
187
+ }).serialize() as unknown as JsonValue,
188
+ }
189
+ }
190
+ try {
191
+ const raw = await readFile(file, 'utf-8')
192
+ const parsed = JSON.parse(raw) as unknown as TranscriptManifest
193
+ return {
194
+ operation: 'read',
195
+ found: true,
196
+ live: live as unknown as JsonValue,
197
+ transcript: parsed as unknown as JsonValue,
198
+ }
199
+ } catch (err) {
200
+ return {
201
+ operation: 'read',
202
+ found: false,
203
+ error: `Failed to read transcript: ${err instanceof Error ? err.message : String(err)}`,
204
+ }
205
+ }
206
+ }
207
+
208
+ if (args.operation === 'nudge') {
209
+ let manifest: TranscriptManifest | null = null
210
+ if (existsSync(file)) {
211
+ try {
212
+ const parsed = JSON.parse(await readFile(file, 'utf-8')) as unknown as TranscriptManifest
213
+ manifest = parsed
214
+ } catch {
215
+ manifest = null
216
+ }
217
+ }
218
+ const builder = manifest
219
+ ? rehydrateBuilder(manifest, approval)
220
+ : new ReviewTranscriptBuilder({ project: projectRoot, mode: 'normal', approval })
221
+ builder.setNudge(typeof args.text === 'string' && args.text.trim() ? args.text : null)
222
+ await persist(file, builder.serialize())
223
+ return {
224
+ operation: 'nudge',
225
+ updated: true,
226
+ transcript: builder.serialize() as unknown as JsonValue,
227
+ }
228
+ }
229
+
230
+ // capture
231
+ const mode = args.mode === 'normal' ? 'normal' : 'dry-run'
232
+ const goal = typeof args.goal === 'string' ? args.goal : ''
233
+ const maxRounds =
234
+ typeof args.maxRounds === 'number' ? Math.floor(args.maxRounds) : 0
235
+ const builder = new ReviewTranscriptBuilder({ project: projectRoot, mode, approval, goal, maxRounds })
236
+ const report = args.report as Record<string, unknown> | null | undefined
237
+ const reportFindings: unknown =
238
+ report && typeof report === 'object' && Array.isArray(report.findings)
239
+ ? report.findings
240
+ : []
241
+ const convergence =
242
+ Array.isArray(args.findingsByRound) ? (args.findingsByRound as number[])
243
+ : report && typeof report === 'object' && report.convergence
244
+ ? ((report.convergence as Record<string, unknown>).findingsByRound as number[] | undefined) ?? []
245
+ : []
246
+
247
+ const rounds = Array.isArray(args.rounds) ? (args.rounds as unknown[]) : []
248
+ for (const r of rounds) captureRound(builder, r)
249
+ if (rounds.length === 0) {
250
+ // No pre-grouped rounds: fall back to the report's flattened findings.
251
+ const readFiles = Array.isArray(args.refReadFiles) ? args.refReadFiles : []
252
+ const byDim = new Map<string, unknown[]>()
253
+ for (const f of reportFindings as unknown[]) {
254
+ if (!f || typeof f !== 'object') continue
255
+ const rec = f as Record<string, unknown>
256
+ const dim = typeof rec.dimension === 'string' && rec.dimension ? rec.dimension : 'review'
257
+ const list = byDim.get(dim) ?? []
258
+ list.push(f)
259
+ byDim.set(dim, list)
260
+ }
261
+ for (const [dim, list] of byDim) builder.reviewerSnapshot(dim, list, readFiles)
262
+ }
263
+
264
+ // Convergence series from the report (position per round).
265
+ for (let i = 0; i < convergence.length; i += 1) {
266
+ const n = convergence[i]
267
+ if (typeof n === 'number') builder.snapshotConvergence(i + 1, n)
268
+ }
269
+ const roundsExecuted =
270
+ typeof args.roundsExecuted === 'number' ? Math.floor(args.roundsExecuted) : rounds.length
271
+ if (roundsExecuted > 0) builder.roundStart(roundsExecuted, maxRounds)
272
+
273
+ builder.recordCheckpoint(normalizeCheckpoint(args.checkpoint))
274
+ if (Array.isArray(args.fixes)) {
275
+ for (const fx of args.fixes) {
276
+ const record = normalizeFix(fx)
277
+ if (record) builder.fix(record)
278
+ }
279
+ }
280
+ // Convergence "found nothing → settled" marker when the trend ends on 0.
281
+ const last = convergence[convergence.length - 1]
282
+ if (convergence.length > 0 && last === 0) builder.finish()
283
+
284
+ await persist(file, builder.serialize())
285
+ const live = await readLive(projectRoot)
286
+ return {
287
+ operation: 'capture',
288
+ found: true,
289
+ updated: true,
290
+ live: live as unknown as JsonValue,
291
+ transcript: builder.serialize() as unknown as JsonValue,
292
+ }
293
+ },
294
+ }),
295
+ )
296
+ }
297
+
298
+ /** Rebuild a builder from a persisted manifest so nudge edits preserve history. */
299
+ function rehydrateBuilder(manifest: TranscriptManifest, approval: 'ask' | 'deny' | 'allow'): ReviewTranscriptBuilder {
300
+ const builder = new ReviewTranscriptBuilder({
301
+ project: manifest.project,
302
+ mode: manifest.mode ?? null,
303
+ approval,
304
+ goal: manifest.goal,
305
+ maxRounds: manifest.maxRounds,
306
+ })
307
+ for (const r of Array.isArray(manifest.rounds) ? manifest.rounds : []) {
308
+ builder.roundStart(r.round, manifest.maxRounds)
309
+ for (const t of Array.isArray(r.threads) ? r.threads : []) {
310
+ builder.reviewerStart(t.dimension || 'review', t.attempt || 1)
311
+ builder.reviewerMessage((t.messages ?? []).join('\n'))
312
+ builder.reviewerRead(t.readFiles ?? [])
313
+ for (const f of t.findings ?? []) builder.reviewerFindings([f])
314
+ }
315
+ }
316
+ for (let idx = 0; idx < (manifest.convergence ?? []).length; idx += 1) {
317
+ const n = manifest.convergence[idx]
318
+ if (typeof n === 'number' && n >= 0) builder.snapshotConvergence(idx + 1, n)
319
+ }
320
+ if (manifest.checkpoint) builder.recordCheckpoint(manifest.checkpoint)
321
+ if (Array.isArray(manifest.fixes)) for (const fx of manifest.fixes) builder.fix(fx as TranscriptFix)
322
+ if (Array.isArray(manifest.timeline)) for (const e of manifest.timeline) builder.decision(e)
323
+ builder.setNudge(manifest.nudge?.text ?? null)
324
+ if (!manifest.active) builder.finish()
325
+ return builder
326
+ }
327
+
328
+ /** Atomically persist a manifest (tmp + rename) under `.iterate/`. */
329
+ async function persist(file: string, manifest: TranscriptManifest): Promise<void> {
330
+ await mkdir(dirname(file), { recursive: true })
331
+ const tmp = `${file}.tmp`
332
+ await writeFile(tmp, JSON.stringify(manifest, null, 2), 'utf-8')
333
+ await rename(tmp, file)
334
+ }