iterate-plugin 3.8.0 → 3.9.1

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,355 @@
1
+ /**
2
+ * src/session-record.ts — dsh session-linked run records (dsh ≥ 0.2.1-rc.1).
3
+ *
4
+ * Upstream capability (dsh `0.2.1-rc.1`, released 2026-10-17): the *Session
5
+ * state-record API*. An experimental plugin may append its own record onto a
6
+ * session's append-only log with `appendPluginRecord(session, type, data)` and
7
+ * read it back with `pluginRecordOf(event)` (`@deepseek-ai/dsh-session`). The
8
+ * record is marked `ignorable`, never enters the model-visible surface, and is
9
+ * carried along by fork / resume / format migration.
10
+ *
11
+ * Why the plugin adopts it:
12
+ * The iterate run state has, until now, lived ONLY under `<projectRoot>/.iterate/`.
13
+ * That is correct for normal operation but has two blind spots the session
14
+ * log closes:
15
+ * 1. **Loss recovery** — if `.iterate/` is deleted, moved, or the working
16
+ * directory changes, the observatory goes blank even though the session
17
+ * that produced the run is still open. A compact run record on the
18
+ * session log lets `iterate_transcript read` rehydrate the run summary
19
+ * instead of returning an empty view.
20
+ * 2. **Session anchoring** — run provenance is tied to the *session* that
21
+ * produced it, not only to whatever directory the process happens to be
22
+ * in when someone looks afterwards.
23
+ *
24
+ * Design (fail-safe, never a hard dependency):
25
+ * - The API is loaded lazily via a dynamic `import()` and used structurally
26
+ * (no compile-time coupling to `PluginRecordMap`), so a host whose copy of
27
+ * `@deepseek-ai/dsh-session` predates the API simply reports
28
+ * `supported: false` instead of failing to load the plugin.
29
+ * - Every entry point returns a structured result; nothing throws. Writing a
30
+ * record is best-effort — a run must never fail because the session log
31
+ * could not accept a bookkeeping record.
32
+ * - `normalizeRunRecord` re-validates a restored payload, because a record
33
+ * read from a resumed session carries whatever JSON an earlier build wrote.
34
+ */
35
+
36
+ /** The `plugin:` record type this plugin owns (grammar-checked by dsh). */
37
+ export const ITERATE_RUN_RECORD_TYPE = 'plugin:iterate/run'
38
+ /** Bump when the record payload shape changes incompatibly. */
39
+ export const ITERATE_RUN_RECORD_VERSION = 1
40
+
41
+ /** Compact, lossless-JSON summary of one iterate run at a point in time. */
42
+ export interface IterateRunRecord {
43
+ version: number
44
+ /** Project root the run belongs to (absolute at write time). */
45
+ project: string
46
+ goal: string
47
+ mode: 'dry-run' | 'normal' | null
48
+ taskMode: 'code' | 'iterate' | null
49
+ /** Highest round reached. */
50
+ round: number
51
+ maxRounds: number
52
+ /** False once the run recorded a terminal `stoppedReason`. */
53
+ active: boolean
54
+ stoppedReason: string | null
55
+ /** Per-round NEW-finding counts, newest last (drives the F2 trend on recovery). */
56
+ convergence: number[]
57
+ findings: {
58
+ total: number
59
+ critical: number
60
+ high: number
61
+ medium: number
62
+ low: number
63
+ }
64
+ /** Applied (successful) fixes recorded so far. */
65
+ fixedCount: number
66
+ /** Quality-gate verdict snapshotted at write time (`pending` when undecided). */
67
+ qualityStatus: 'pass' | 'fail' | 'pending' | null
68
+ /** ISO timestamp the record was written. */
69
+ updatedAt: string
70
+ }
71
+
72
+ /** A run record read back from a session log, with its log position. */
73
+ export interface StoredRunRecord extends IterateRunRecord {
74
+ /** Session-log sequence number the record occupies. */
75
+ seq: number
76
+ /** Unix epoch milliseconds at append (from the host). */
77
+ time: number
78
+ }
79
+
80
+ /** Minimal structural view of the session-log API we consume. */
81
+ export interface SessionRecordApi {
82
+ appendPluginRecord(session: unknown, type: string, data: unknown): number
83
+ pluginRecordOf(event: unknown): { type: string; seq: number; time: number; data: unknown } | undefined
84
+ }
85
+
86
+ /** Minimal structural view of a dsh Session (only what this module reads). */
87
+ export interface SessionLike {
88
+ ownEvents?(): readonly unknown[]
89
+ snapshotEvents?(): readonly unknown[]
90
+ }
91
+
92
+ /** Result of a best-effort record append. */
93
+ export type AppendRecordResult =
94
+ | { ok: true; supported: true; seq: number }
95
+ | { ok: false; supported: boolean; error: string }
96
+
97
+ /** Result of reading the session's iterate run records. */
98
+ export interface ReadRecordsResult {
99
+ supported: boolean
100
+ /** Oldest → newest. */
101
+ records: StoredRunRecord[]
102
+ /** Present only when the read itself failed unexpectedly. */
103
+ error?: string
104
+ }
105
+
106
+ // ─── Pure payload construction / validation ─────────────────────────────────
107
+
108
+ /** Coerce an unknown to a finite non-negative integer, else `fallback`. */
109
+ function nonNegInt(value: unknown, fallback = 0): number {
110
+ if (typeof value !== 'number' || !Number.isFinite(value)) return fallback
111
+ const n = Math.floor(value)
112
+ return n >= 0 ? n : fallback
113
+ }
114
+
115
+ /** Extract a string, else `''`. */
116
+ function str(value: unknown): string {
117
+ return typeof value === 'string' ? value : ''
118
+ }
119
+
120
+ /** Extract one of the allowed literal values, else `null`. */
121
+ function oneOf<T extends string>(value: unknown, allowed: readonly T[]): T | null {
122
+ return typeof value === 'string' && (allowed as readonly string[]).includes(value) ? (value as T) : null
123
+ }
124
+
125
+ /** Severity counts recovered from an on-disk manifest summary. */
126
+ export interface RunRecordCounts {
127
+ total: number
128
+ critical: number
129
+ high: number
130
+ medium: number
131
+ low: number
132
+ }
133
+
134
+ /**
135
+ * Build a run record from the fields a persisted transcript manifest exposes.
136
+ * Pure: the caller passes already-normalized values, so this is unit-testable
137
+ * without touching disk or a session.
138
+ */
139
+ export function buildRunRecord(input: {
140
+ project?: unknown
141
+ goal?: unknown
142
+ mode?: unknown
143
+ taskMode?: unknown
144
+ round?: unknown
145
+ maxRounds?: unknown
146
+ active?: unknown
147
+ stoppedReason?: unknown
148
+ convergence?: unknown
149
+ counts?: Partial<RunRecordCounts>
150
+ fixedCount?: unknown
151
+ qualityStatus?: unknown
152
+ now?: string
153
+ }): IterateRunRecord {
154
+ const convergence = Array.isArray(input.convergence)
155
+ ? input.convergence
156
+ .filter((n): n is number => typeof n === 'number' && Number.isFinite(n) && n >= 0)
157
+ .slice(-1000)
158
+ : []
159
+ const c = input.counts ?? {}
160
+ const stopped = str(input.stoppedReason)
161
+ return {
162
+ version: ITERATE_RUN_RECORD_VERSION,
163
+ project: str(input.project),
164
+ goal: str(input.goal),
165
+ mode: oneOf(input.mode, ['dry-run', 'normal'] as const),
166
+ taskMode: oneOf(input.taskMode, ['code', 'iterate'] as const),
167
+ round: nonNegInt(input.round),
168
+ maxRounds: nonNegInt(input.maxRounds),
169
+ active: input.active !== false,
170
+ stoppedReason: stopped ? stopped : null,
171
+ convergence,
172
+ findings: {
173
+ total: nonNegInt(c.total),
174
+ critical: nonNegInt(c.critical),
175
+ high: nonNegInt(c.high),
176
+ medium: nonNegInt(c.medium),
177
+ low: nonNegInt(c.low),
178
+ },
179
+ fixedCount: nonNegInt(input.fixedCount),
180
+ qualityStatus: oneOf(input.qualityStatus, ['pass', 'fail', 'pending'] as const),
181
+ updatedAt: str(input.now) || new Date().toISOString(),
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Owner-side validation of a payload read back from a session log.
187
+ * A restored record carries whatever JSON an earlier build of this plugin
188
+ * wrote, so every field is re-checked; anything unrecognizable returns `null`
189
+ * (the caller skips it) rather than surfacing junk to a renderer.
190
+ */
191
+ export function normalizeRunRecord(data: unknown): IterateRunRecord | null {
192
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return null
193
+ const d = data as Record<string, unknown>
194
+ // A record written by a future/incompatible build is skipped rather than
195
+ // coerced: the version gate is the contract that lets the payload evolve.
196
+ // The check is exact (an integer compare, not a floor) so a payload stamped
197
+ // `1.9` by a future build is rejected instead of rounded down to `1`.
198
+ if (!Number.isInteger(d.version) || d.version !== ITERATE_RUN_RECORD_VERSION) return null
199
+ const findings = (d.findings && typeof d.findings === 'object' && !Array.isArray(d.findings)
200
+ ? (d.findings as Record<string, unknown>)
201
+ : {}) as Record<string, unknown>
202
+ return buildRunRecord({
203
+ project: d.project,
204
+ goal: d.goal,
205
+ mode: d.mode,
206
+ taskMode: d.taskMode,
207
+ round: d.round,
208
+ maxRounds: d.maxRounds,
209
+ active: d.active,
210
+ stoppedReason: d.stoppedReason,
211
+ convergence: d.convergence,
212
+ counts: {
213
+ total: findings.total as number,
214
+ critical: findings.critical as number,
215
+ high: findings.high as number,
216
+ medium: findings.medium as number,
217
+ low: findings.low as number,
218
+ },
219
+ fixedCount: d.fixedCount,
220
+ qualityStatus: d.qualityStatus,
221
+ now: typeof d.updatedAt === 'string' ? d.updatedAt : undefined,
222
+ })
223
+ }
224
+
225
+ // ─── Session access (lazy, fail-safe) ────────────────────────────────────────
226
+
227
+ /** Lazily-resolved production API; `undefined` = not yet attempted. */
228
+ let cachedApi: Promise<SessionRecordApi | null> | undefined
229
+ /** Test override; when set (including `null`) the dynamic import is bypassed. */
230
+ let testApiOverride: SessionRecordApi | null | undefined
231
+ /** Module loader; replaceable for tests to exercise import failure/late availability. */
232
+ let moduleImporter: () => Promise<unknown> = () => import('@deepseek-ai/dsh-session')
233
+
234
+ /** Resolve the `@deepseek-ai/dsh-session` record API, or `null` when absent. */
235
+ export function loadSessionRecordApi(): Promise<SessionRecordApi | null> {
236
+ if (testApiOverride !== undefined) return Promise.resolve(testApiOverride)
237
+ if (cachedApi === undefined) {
238
+ // `Promise.resolve().then(...)` (not a bare call) so a loader that throws
239
+ // SYNCHRONOUSLY still lands in the `.catch` instead of escaping.
240
+ cachedApi = Promise.resolve()
241
+ .then(() => moduleImporter())
242
+ .then((mod) => {
243
+ const m = mod as unknown as Partial<SessionRecordApi>
244
+ if (typeof m.appendPluginRecord !== 'function' || typeof m.pluginRecordOf !== 'function') {
245
+ return null
246
+ }
247
+ return {
248
+ appendPluginRecord: m.appendPluginRecord.bind(mod),
249
+ pluginRecordOf: m.pluginRecordOf.bind(mod),
250
+ }
251
+ })
252
+ .catch(() => null)
253
+ // A `null` resolution (module/API absent, or a transient import failure) is
254
+ // NOT memoized: it is cleared so the next call retries. Otherwise one
255
+ // unlucky first import would disable session linking for the whole process.
256
+ void cachedApi.then((api) => {
257
+ if (!api) cachedApi = undefined
258
+ })
259
+ }
260
+ return cachedApi
261
+ }
262
+
263
+ /**
264
+ * Replace the module loader for tests (to exercise the import-failure and
265
+ * late-availability paths). Pass `undefined` to restore the real dynamic import.
266
+ */
267
+ export function setSessionRecordImporterForTests(loader: (() => Promise<unknown>) | undefined): void {
268
+ moduleImporter = loader ?? (() => import('@deepseek-ai/dsh-session'))
269
+ cachedApi = undefined
270
+ }
271
+
272
+ /**
273
+ * Override the session-record API for tests. Pass `undefined` to restore the
274
+ * real dynamic import, or an object / `null` to force a deterministic result.
275
+ */
276
+ export function setSessionRecordApiForTests(api: SessionRecordApi | null | undefined): void {
277
+ testApiOverride = api
278
+ }
279
+
280
+ /** Extract the session from a tool execution (`exec.agent.session`), defensively. */
281
+ export function sessionOf(exec: unknown): SessionLike | undefined {
282
+ try {
283
+ const agent = (exec as { agent?: { session?: unknown } } | null | undefined)?.agent
284
+ const session = agent?.session
285
+ if (!session || typeof session !== 'object') return undefined
286
+ const s = session as SessionLike
287
+ if (typeof s.ownEvents === 'function' || typeof s.snapshotEvents === 'function') return s
288
+ return undefined
289
+ } catch {
290
+ return undefined
291
+ }
292
+ }
293
+
294
+ /** Read every event a session exposes (own events preferred, snapshot fallback). */
295
+ function eventsOf(session: SessionLike): readonly unknown[] {
296
+ try {
297
+ if (typeof session.ownEvents === 'function') return session.ownEvents() ?? []
298
+ } catch {
299
+ // fall through to snapshot
300
+ }
301
+ try {
302
+ if (typeof session.snapshotEvents === 'function') return session.snapshotEvents() ?? []
303
+ } catch {
304
+ // no readable log
305
+ }
306
+ return []
307
+ }
308
+
309
+ /**
310
+ * Best-effort append of one run record to the session log.
311
+ * Never throws: an absent API, a degraded session, or a rejected payload all
312
+ * surface as `{ ok: false }` so the surrounding tool call can continue.
313
+ */
314
+ export async function appendRunRecord(
315
+ session: SessionLike | undefined,
316
+ record: IterateRunRecord,
317
+ ): Promise<AppendRecordResult> {
318
+ const api = await loadSessionRecordApi()
319
+ if (!api) return { ok: false, supported: false, error: 'session record API unavailable' }
320
+ if (!session) return { ok: false, supported: true, error: 'no session in scope' }
321
+ try {
322
+ const seq = api.appendPluginRecord(session, ITERATE_RUN_RECORD_TYPE, record)
323
+ return { ok: true, supported: true, seq }
324
+ } catch (err) {
325
+ return {
326
+ ok: false,
327
+ supported: true,
328
+ error: `session rejected the run record: ${err instanceof Error ? err.message : String(err)}`,
329
+ }
330
+ }
331
+ }
332
+
333
+ /** Read every iterate run record from the session log (oldest → newest). */
334
+ export async function readRunRecords(session: SessionLike | undefined): Promise<ReadRecordsResult> {
335
+ const api = await loadSessionRecordApi()
336
+ if (!api) return { supported: false, records: [] }
337
+ if (!session) return { supported: true, records: [] }
338
+ try {
339
+ const records: StoredRunRecord[] = []
340
+ for (const event of eventsOf(session)) {
341
+ const rec = api.pluginRecordOf(event)
342
+ if (!rec || rec.type !== ITERATE_RUN_RECORD_TYPE) continue
343
+ const normalized = normalizeRunRecord(rec.data)
344
+ if (!normalized) continue
345
+ records.push({ ...normalized, seq: nonNegInt(rec.seq), time: nonNegInt(rec.time) })
346
+ }
347
+ return { supported: true, records }
348
+ } catch (err) {
349
+ return {
350
+ supported: true,
351
+ records: [],
352
+ error: `failed to read session records: ${err instanceof Error ? err.message : String(err)}`,
353
+ }
354
+ }
355
+ }
@@ -23,7 +23,8 @@ You have the iterate plugin installed, which registers these tools:
23
23
  - \`iterate_status\` — summarize the current run: mode, round, fixes applied, architectural remaining, decision-log size, checkpoint presence, and whether the run was interrupted (a checkpoint on disk with no newer decision-log activity means the previous run was interrupted and can be resumed)
24
24
  - \`iterate_history\` — inspect the runtime state in detail: decision-log entries and applied fixes (optionally scoped to a round or a fixed file)
25
25
  - \`iterate_prune\` — remove stale runtime artifacts (\`.iterate/\` entries). Defaults to a read-only dry-run that reports what WOULD be removed; pass \`dryRun:false\` to actually prune.
26
- - \`iterate_transcript\` — runtime observatory file (\`.iterate/transcript.json\`). \`read\` fetches the persisted manifest including any steering \`nudge\` for this run's reviewers; \`capture\` (call once after the final report) persists the per-reviewer threads, convergence trend, findings, fixes, checkpoint, per-round validation results (\`validations\`: command + exitCode + allowed + rejectReason), and timeline so the client observatory panel reflects the run; \`nudge\` sets/clears steering text the next round's reviewers read. Purely local, never touches source files.
26
+ - \`iterate_transcript\` — runtime observatory file (\`.iterate/transcript.json\`). \`read\` fetches the persisted manifest including any steering \`nudge\` for this run's reviewers — and, when the file is missing or malformed, recovers a summary manifest from the session log's run record (returns \`recovered:true\`); \`capture\` (call once after the final report) persists the per-reviewer threads, convergence trend, findings, fixes, checkpoint, per-round validation results (\`validations\`: command + exitCode + allowed + rejectReason), and timeline so the client observatory panel reflects the run, and links the run to the dsh session (\`sessionRecord\`); \`recall\` lists the run records linked to this session (newest first) so a run stays traceable after \`.iterate/\` is wiped; \`nudge\` sets/clears steering text the next round's reviewers read. Purely local, never touches source files.
27
+ - \`iterate_report\` — export the current run as a portable report. \`format:"markdown"\` (default) renders a PR-pasteable report (run header, quality gate, findings, fixes, validations, defense events, experience bank); \`format:"sarif"\` renders a SARIF 2.1.0 log for CI / GitHub Code Scanning (one rule per review dimension, severity → error/warning/note, file+line locations, suggested fix attached). Set \`write:true\` to persist it under \`.iterate/report.md\` / \`.iterate/report.sarif\`; \`lang\` (zh | en) selects the report language. Read-only apart from the optional report file.
27
28
  - \`iterate_experience\` — experience bank (\`.iterate/experience.json\`): \`list\`/\`search\`/\`get\` recall verified fixes and patterns from past sessions (read the bank before fixing so proven fixes are applied first); \`add\` records a new verified fix — re-adding the same pattern+dimension bumps its hit count instead of duplicating it; \`remove\` deletes a stale or incorrect entry by \`id\` so bad experiences never resurface.
28
29
  - \`iterate_quality_gate\` — quality certificate: \`read\` loads the persisted dimension convergence rates / verification pass rate / PASS-FAIL status; \`compute\` recomputes a fresh snapshot from this round's findings + validation results (supply \`findingsByRound\` for real convergence) and persists it to \`.iterate/quality-gate.json\`; \`clear\` removes the persisted certificate to reset a stale gate before a fresh iteration.
29
30
  - \`iterate_defense_events\` — defense event stream (\`.iterate/defense-events.json\`): \`list\`/\`counts\` review precondition failures, rollbacks, invariant violations, and falsified assumptions; \`record\` logs a new event when a defense fires. Human-readable labels follow the project \`language\` (en/zh).
@@ -0,0 +1,244 @@
1
+ /**
2
+ * src/tools/report.ts — `iterate_report` tool.
3
+ *
4
+ * iterate_report — render the current iterate run into a portable report.
5
+ *
6
+ * Two formats, one normalized data model (shared with the client export
7
+ * buttons via `src/report-render.ts`, so the on-screen export and this tool
8
+ * can never drift):
9
+ *
10
+ * - `markdown` — a PR-pasteable run report: header (mode/round/status), the
11
+ * quality-gate table, the findings table, the fixes table,
12
+ * validations, defense events, and the experience bank.
13
+ * - `sarif` — a SARIF 2.1.0 log so CI / GitHub Code Scanning can consume
14
+ * iterate findings as code-scanning results (ruleId =
15
+ * dimension, severity → error/warning/note, file+line
16
+ * locations, suggested fix attached).
17
+ *
18
+ * Reads only local state (`.iterate/transcript.json` + the quality / experience
19
+ * / defense stores) and writes only `.iterate/report.<ext>` when `write:true`.
20
+ * Malformed or missing state is rendered as-is (empty tables) — an export must
21
+ * never fail because a run was partial.
22
+ */
23
+
24
+ import { existsSync, readFileSync } from 'node:fs'
25
+ import { mkdirSync, writeFileSync } from 'node:fs'
26
+ import { defineTool } from '@deepseek-ai/dsh-tools'
27
+ import type { JsonValue } from '@deepseek-ai/dsh-util-values'
28
+ import { resolveProjectRootForExec } from '../config-loader.ts'
29
+ import { iterateDir, transcriptPath } from '../paths.ts'
30
+ import { readQualityGate } from './quality-store.ts'
31
+ import { readExperienceBank } from './experience-store.ts'
32
+ import { readDefenseEvents } from './defense-store.ts'
33
+ import { resultHeadline } from './present.ts'
34
+ import { renderRunReportMarkdown, renderRunReportSarif, REPORT_FORMATS } from '../report-render.ts'
35
+
36
+ /** Formats accepted by the tool (kept in sync with the shared renderer). */
37
+ const FORMATS: ReadonlySet<string> = new Set(REPORT_FORMATS)
38
+
39
+ /** Read the persisted transcript manifest, tolerating a missing/garbled file. */
40
+ function readManifest(projectRoot: string): { manifest: unknown; source: 'disk' | 'empty' } {
41
+ const file = transcriptPath(projectRoot)
42
+ if (!existsSync(file)) return { manifest: {}, source: 'empty' }
43
+ try {
44
+ const parsed = JSON.parse(readFileSync(file, 'utf-8')) as unknown
45
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
46
+ return { manifest: parsed, source: 'disk' }
47
+ }
48
+ return { manifest: {}, source: 'empty' }
49
+ } catch {
50
+ return { manifest: {}, source: 'empty' }
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Register the `iterate_report` tool.
56
+ * Renders the current run into a Markdown or SARIF report.
57
+ */
58
+ export function registerReportTool(ctx: { tools: { register: (def: ReturnType<typeof defineTool>) => void } }): void {
59
+ ctx.tools.register(
60
+ defineTool({
61
+ name: 'iterate_report',
62
+ // Result card: surface the report headline ("report: markdown · N findings")
63
+ // as the card title. Pure: reads only the rendered result (replay-safe).
64
+ presentResult: (_args, result) => {
65
+ const title = resultHeadline(result)
66
+ return title ? { card: 'generic', title } : undefined
67
+ },
68
+ // `write:true` persists a file; a pure render joins a parallel group.
69
+ isConcurrencySafe: (args) => (args as { write?: unknown }).write !== true,
70
+ description:
71
+ 'Export the current iterate run as a portable report. ' +
72
+ '`format:"markdown"` (default) renders a PR-pasteable report: run header (mode / round / status), ' +
73
+ 'quality-gate table, findings table, fixes table, per-round validations, defense events, and the ' +
74
+ 'experience bank. `format:"sarif"` renders a SARIF 2.1.0 log for CI / GitHub Code Scanning ' +
75
+ '(one rule per review dimension; finding severity maps to error/warning/note; findings carry ' +
76
+ 'file + line locations and the suggested fix). ' +
77
+ 'Set `write:true` to also persist the report under `.iterate/report.md` / `.iterate/report.sarif` ' +
78
+ 'and get the path back. `lang` selects the report language (zh | en). ' +
79
+ 'Read-only apart from the optional report file; never touches source files.',
80
+ parameters: {
81
+ format: {
82
+ type: 'string',
83
+ description: 'Report format: "markdown" (default) or "sarif".',
84
+ enum: ['markdown', 'sarif'],
85
+ },
86
+ write: {
87
+ type: 'boolean',
88
+ description: 'When true, persist the report to `.iterate/report.md` / `.iterate/report.sarif` and return its path. Default: false.',
89
+ },
90
+ lang: {
91
+ type: 'string',
92
+ description: 'Report language: "zh" (default) or "en". Affects labels/headings only.',
93
+ enum: ['zh', 'en'],
94
+ },
95
+ path: {
96
+ type: 'string',
97
+ description: 'Project root directory (default: current working directory).',
98
+ },
99
+ },
100
+
101
+ output: {
102
+ schema: {
103
+ type: 'object',
104
+ additionalProperties: false,
105
+ properties: {
106
+ ok: { type: 'boolean', required: true },
107
+ kind: { type: 'string' },
108
+ format: { type: 'string' },
109
+ /** The rendered report text (Markdown, or pretty-printed SARIF JSON). */
110
+ content: { type: 'string' },
111
+ /** The SARIF log object, when format is "sarif". */
112
+ sarif: { type: 'json' },
113
+ /** Whether a source transcript manifest was found on disk. */
114
+ source: { type: 'string' },
115
+ written: { type: 'boolean' },
116
+ reportPath: { type: 'string' },
117
+ findings: { type: 'number' },
118
+ error: { type: 'string' },
119
+ },
120
+ },
121
+ render: (_args, value) => {
122
+ if (!value.ok) return [{ type: 'text', text: `report export failed: ${value.error}` }]
123
+ const content = typeof value.content === 'string' ? value.content : ''
124
+ const header = [
125
+ `report: ${String(value.format ?? 'markdown')} · ${String(value.findings ?? 0)} findings · source=${String(value.source ?? 'empty')}`,
126
+ value.written ? `written to ${String(value.reportPath ?? '')}` : '',
127
+ ].filter(Boolean).join(' · ')
128
+ return [{ type: 'text', text: `${header}\n\n${content}` }]
129
+ },
130
+ },
131
+
132
+ async execute(args, exec) {
133
+ const resolved = resolveProjectRootForExec(exec, args.path)
134
+ if (!resolved.ok) return { ok: false, kind: 'report', error: resolved.reason }
135
+ const projectRoot = resolved.root
136
+
137
+ const rawFormat = typeof args.format === 'string' ? args.format : 'markdown'
138
+ const format = FORMATS.has(rawFormat) ? rawFormat : 'markdown'
139
+ const lang = args.lang === 'en' ? 'en' : 'zh'
140
+
141
+ const { manifest, source } = readManifest(projectRoot)
142
+ let qualityGate: unknown = null
143
+ let experienceBank: unknown = null
144
+ let defenseEvents: unknown = null
145
+ try {
146
+ qualityGate = readQualityGate(projectRoot)
147
+ } catch {
148
+ qualityGate = null
149
+ }
150
+ try {
151
+ experienceBank = readExperienceBank(projectRoot)
152
+ } catch {
153
+ experienceBank = null
154
+ }
155
+ try {
156
+ defenseEvents = readDefenseEvents(projectRoot)
157
+ } catch {
158
+ defenseEvents = null
159
+ }
160
+
161
+ const extra = { qualityGate, experienceBank, defenseEvents }
162
+ let content: string
163
+ let sarif: JsonValue | undefined
164
+ let findings = 0
165
+ try {
166
+ if (format === 'sarif') {
167
+ const doc = renderRunReportSarif(manifest, extra, {
168
+ toolVersion: pluginVersion(),
169
+ }) as unknown as { runs?: Array<{ results?: unknown[] }> }
170
+ sarif = doc as unknown as JsonValue
171
+ content = JSON.stringify(doc, null, 2)
172
+ findings = Array.isArray(doc?.runs?.[0]?.results) ? (doc.runs[0].results as unknown[]).length : 0
173
+ } else {
174
+ content = renderRunReportMarkdown(manifest, extra, { lang }) as unknown as string
175
+ findings = countMarkdownFindings(content)
176
+ }
177
+ } catch (err) {
178
+ return {
179
+ ok: false,
180
+ kind: 'report',
181
+ format,
182
+ error: `failed to render report: ${err instanceof Error ? err.message : String(err)}`,
183
+ }
184
+ }
185
+
186
+ let written = false
187
+ let reportPath: string | undefined
188
+ if (args.write === true) {
189
+ try {
190
+ const dir = iterateDir(projectRoot)
191
+ mkdirSync(dir, { recursive: true })
192
+ reportPath = `${dir}/report.${format === 'sarif' ? 'sarif' : 'md'}`
193
+ writeFileSync(reportPath, content, 'utf-8')
194
+ written = true
195
+ } catch (err) {
196
+ return {
197
+ ok: false,
198
+ kind: 'report',
199
+ format,
200
+ error: `failed to write report: ${err instanceof Error ? err.message : String(err)}`,
201
+ }
202
+ }
203
+ }
204
+
205
+ return {
206
+ ok: true,
207
+ kind: 'report',
208
+ format,
209
+ content,
210
+ ...(sarif !== undefined ? { sarif } : {}),
211
+ source,
212
+ written,
213
+ ...(reportPath ? { reportPath } : {}),
214
+ findings,
215
+ }
216
+ },
217
+ }),
218
+ )
219
+ }
220
+
221
+ /**
222
+ * Best-effort plugin version for the SARIF driver. Resolved from the package
223
+ * manifest next to this module (`src/tools` and `dist/tools` are both two
224
+ * levels below the root); an unreadable/unparsable manifest yields ''.
225
+ */
226
+ function pluginVersion(): string {
227
+ try {
228
+ const raw = readFileSync(new URL('../../package.json', import.meta.url), 'utf-8')
229
+ const pkg = JSON.parse(raw) as { version?: unknown }
230
+ return typeof pkg.version === 'string' ? pkg.version : ''
231
+ } catch {
232
+ return ''
233
+ }
234
+ }
235
+
236
+ /** Count the findings table rows in a rendered Markdown report (for the card). */
237
+ function countMarkdownFindings(markdown: string): number {
238
+ const m = /##\s+.*?\((\d+)\)/.exec(markdown)
239
+ if (m && m[1]) {
240
+ const n = Number(m[1])
241
+ if (Number.isFinite(n)) return n
242
+ }
243
+ return 0
244
+ }