@adhdev/mesh-shared 1.0.82-rc.46 → 1.0.82-rc.47

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,455 @@
1
+ /**
2
+ * task-stages — vocabulary, shapes and validators for "review in task".
3
+ *
4
+ * A medium/difficult `code_change` can be enqueued as ONE stage task: the daemon runs
5
+ * implement → self-check → independent review → (bounded) revise inside the task and the
6
+ * coordinator is woken once, by the parent's terminal. Design:
7
+ * docs/design/2026-11-01-review-in-task.md (§3 model, §5 data contract).
8
+ *
9
+ * Dependency-free leaf: every cap and enum the daemon validator, the MCP schemas and the
10
+ * dashboard chips read lives here once.
11
+ */
12
+
13
+ import type { LightTestRun } from './light-task'
14
+
15
+ // ─── Vocabulary ─────────────────────────────────────────────────────────
16
+
17
+ export const REVIEW_VERDICTS = ['approve', 'approve_with_nits', 'changes_requested', 'reject_approach'] as const
18
+ export type MeshReviewVerdict = typeof REVIEW_VERDICTS[number]
19
+
20
+ export const FINDING_SEVERITIES = ['blocking', 'major', 'minor', 'nit'] as const
21
+ export type MeshFindingSeverity = typeof FINDING_SEVERITIES[number]
22
+
23
+ export const FINDING_CATEGORIES = ['correctness', 'regression', 'test_gap', 'scope', 'security', 'performance', 'maintainability'] as const
24
+ export type MeshFindingCategory = typeof FINDING_CATEGORIES[number]
25
+
26
+ export const PRIOR_FINDING_STATUSES = ['resolved', 'unresolved', 'dispute_accepted', 'dispute_rejected'] as const
27
+ export type MeshPriorFindingStatus = typeof PRIOR_FINDING_STATUSES[number]
28
+
29
+ export const FINDING_RESPONSE_KINDS = ['fixed', 'disputed'] as const
30
+ export type MeshFindingResponseKind = typeof FINDING_RESPONSE_KINDS[number]
31
+
32
+ export const STAGE_PHASES = ['implementing', 'self_checking', 'awaiting_review', 'reviewing', 'revising', 'done'] as const
33
+ export type MeshStagePhase = typeof STAGE_PHASES[number]
34
+
35
+ /** Phases in which the parent row holds NO open attempt but is waiting on the daemon (watchdogs must skip it). */
36
+ export const STAGE_PARKED_PHASES: readonly MeshStagePhase[] = ['self_checking', 'awaiting_review', 'reviewing']
37
+
38
+ export const STAGE_INDEPENDENCE_MODES = ['different_provider', 'fresh_session_ok'] as const
39
+ export type MeshStageIndependenceMode = typeof STAGE_INDEPENDENCE_MODES[number]
40
+
41
+ /** What actually reviewed (recorded on the verdict and in the final report). */
42
+ export type MeshStageIndependenceUsed = 'different_provider' | 'fresh_session_fallback'
43
+
44
+ export const STAGE_ROLES = ['implement', 'revise', 'review'] as const
45
+ export type MeshStageRole = typeof STAGE_ROLES[number]
46
+
47
+ /** Why a stage parent ended `blocked` (R4/R12, doc §3.2). */
48
+ export const STAGE_BLOCKED_REASONS = [
49
+ 'review_unresolved',
50
+ 'review_rejected_approach',
51
+ 'review_unavailable',
52
+ 'self_check_failed',
53
+ 'stage_pipeline_ceiling',
54
+ 'reviewer_mutated_source',
55
+ // The read-lease checkout could not be fingerprinted (start or end): the review's integrity cannot be verified.
56
+ 'reviewer_integrity_unverifiable',
57
+ ] as const
58
+ export type MeshStageBlockedReason = typeof STAGE_BLOCKED_REASONS[number]
59
+
60
+ export const STAGE_DECIDE_ACTIONS = ['accept', 'revise_once', 'rereview', 'abandon'] as const
61
+ export type MeshStageDecideAction = typeof STAGE_DECIDE_ACTIONS[number]
62
+
63
+ // ─── Limits ─────────────────────────────────────────────────────────────
64
+
65
+ export const STAGE_MAX_REVISIONS_LIMIT = 3
66
+ export const STAGE_DEFAULT_MAX_REVISIONS = 2
67
+ export const STAGE_SELF_CHECK_MAX_BOUNCES = 2
68
+ /** Minutes a review child may be refused only for `review_independence_required` before fresh_session fallback (R2). */
69
+ export const STAGE_INDEPENDENCE_FALLBACK_MS = 10 * 60 * 1000
70
+ /** Parent pipeline ceiling from first dispatch (R12). */
71
+ export const STAGE_PIPELINE_CEILING_DEFAULT_MS = 4 * 60 * 60 * 1000
72
+
73
+ export const REVIEW_FINDINGS_MAX = 30
74
+ export const REVIEW_CLAIM_MAX_CHARS = 500
75
+ export const REVIEW_EVIDENCE_MAX_CHARS = 1_000
76
+ export const REVIEW_FIX_MAX_CHARS = 500
77
+ export const REVIEW_FINDING_ID_MAX_CHARS = 40
78
+ export const REVIEW_CHECKED_MAX = 20
79
+ export const REVIEW_NOTE_MAX_CHARS = 500
80
+ export const REVIEW_TESTS_RUN_MAX = 20
81
+ export const FINDING_RESPONSES_MAX = 30
82
+
83
+ // ─── Shapes ─────────────────────────────────────────────────────────────
84
+
85
+ export interface MeshTaskStagePlan {
86
+ review: true
87
+ maxRevisions: 0 | 1 | 2 | 3
88
+ independence: MeshStageIndependenceMode
89
+ }
90
+
91
+ export interface MeshStageHead {
92
+ round: number
93
+ rootSha: string
94
+ submodules?: Record<string, string>
95
+ }
96
+
97
+ export interface MeshTaskStageState {
98
+ phase: MeshStagePhase
99
+ /** Review round in progress (0 before the first review child exists). */
100
+ round: number
101
+ selfCheckBounces: number
102
+ startedAt: string
103
+ phaseSince: string
104
+ baseSha: string
105
+ stageHeads: MeshStageHead[]
106
+ reviewTaskIds: string[]
107
+ lastVerdict?: MeshReviewVerdict
108
+ openFindingIds: string[]
109
+ artifacts: { diff: string[]; selfCheck: string[]; verdict: string[] }
110
+ reviewerSessionId?: string
111
+ independenceUsed?: MeshStageIndependenceUsed
112
+ /** Attempts the reducer already consumed (idempotency against the two terminal paths). */
113
+ handledAttemptIds?: string[]
114
+ /** Consecutive reviewer-unavailable outcomes (2 → review_unavailable). */
115
+ reviewerFailures?: number
116
+ /** Coordinator-granted extra revision rounds (`mesh_task_stage_decide revise_once`). */
117
+ extraRevisions?: number
118
+ /** Why the parent is blocked, once it is. */
119
+ blockedReason?: MeshStageBlockedReason
120
+ /** Unresolved findings snapshot kept for the final report (id + severity + claim). */
121
+ openFindings?: Array<{ id: string; severity: MeshFindingSeverity; claim: string }>
122
+ /** Nits/minors from the approving verdict, delivered in the final report. */
123
+ openNits?: Array<{ id: string; severity: MeshFindingSeverity; claim: string }>
124
+ /** Self-check outcome summary for the final report. */
125
+ selfCheck?: 'passed' | 'skipped_not_configured' | 'skipped_infra_error' | 'unavailable' | 'failed'
126
+ /** Resolved/disputed counters for the verdict line. */
127
+ findingsFixed?: number
128
+ /** The original coordinator message, preserved while revise memos replace `message`. */
129
+ originalMessage?: string
130
+ /** Artifact ids the implementer cited in its own report (feed the next stage's input, top 4). */
131
+ workerArtifactIds?: string[]
132
+ /** Read-lease reviews only: HEAD + working-tree fingerprint of the parent checkout taken when the review child was created (§11). */
133
+ reviewFingerprint?: string
134
+ /** Read-lease review whose baseline fingerprint could not be taken (after one retry): the verdict is never accepted. */
135
+ reviewFingerprintUnavailable?: boolean
136
+ /** True once the parent was released to a terminal by the pipeline (hold lifted). */
137
+ released?: boolean
138
+ }
139
+
140
+ export interface MeshReviewFinding {
141
+ id: string
142
+ severity: MeshFindingSeverity
143
+ category: MeshFindingCategory
144
+ file?: string
145
+ line?: number
146
+ claim: string
147
+ evidence: string
148
+ suggestedFix?: string
149
+ }
150
+
151
+ export interface MeshPriorFindingStatusEntry { id: string; status: MeshPriorFindingStatus; note?: string }
152
+
153
+ /** One definition: the light-task `LightTestRun` (same {command, exit, passed?, failed?, note?} shape). */
154
+ export type MeshTestRun = LightTestRun
155
+
156
+ export interface MeshReviewReport {
157
+ verdict: MeshReviewVerdict
158
+ findings: MeshReviewFinding[]
159
+ priorFindings?: MeshPriorFindingStatusEntry[]
160
+ checked: string[]
161
+ notChecked: string[]
162
+ testsRun?: MeshTestRun[]
163
+ }
164
+
165
+ export interface MeshFindingResponse { id: string; response: MeshFindingResponseKind; note: string }
166
+
167
+ export interface StageValidationError { field: string; message: string }
168
+
169
+ // ─── Guards ─────────────────────────────────────────────────────────────
170
+
171
+ function makeGuard<T extends readonly string[]>(values: T): (value: unknown) => value is T[number] {
172
+ const set: ReadonlySet<string> = new Set(values)
173
+ return (value: unknown): value is T[number] => typeof value === 'string' && set.has(value)
174
+ }
175
+
176
+ export const isReviewVerdict = makeGuard(REVIEW_VERDICTS)
177
+ export const isFindingSeverity = makeGuard(FINDING_SEVERITIES)
178
+ export const isFindingCategory = makeGuard(FINDING_CATEGORIES)
179
+ export const isPriorFindingStatus = makeGuard(PRIOR_FINDING_STATUSES)
180
+ export const isFindingResponseKind = makeGuard(FINDING_RESPONSE_KINDS)
181
+ export const isStageBlockedReason = makeGuard(STAGE_BLOCKED_REASONS)
182
+
183
+ const isRecord = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)
184
+
185
+ /** Blocking/major findings keep a review from passing. */
186
+ export function isBlockingSeverity(severity: MeshFindingSeverity): boolean {
187
+ return severity === 'blocking' || severity === 'major'
188
+ }
189
+
190
+ // ─── Plan normalization (enqueue `review` option, R5) ───────────────────
191
+
192
+ export interface StagePlanDefaultsInput {
193
+ taskMode?: string
194
+ difficulty?: string
195
+ readonly?: boolean
196
+ }
197
+
198
+ /**
199
+ * Resolve the enqueue-time `review` option into a stage plan, or null when review is off.
200
+ * `review` undefined → R5 default (applied by the MCP layer; the daemon's enqueueTask passes `defaultOn: false` so internal and legacy callers never get a pipeline they did not ask for) (medium/difficult non-readonly `code_change` → on; easy/freeform/readonly → off).
201
+ * Throws `invalid_review_option: …` on malformed input (rejected, never coerced).
202
+ */
203
+ export function resolveStagePlan(raw: unknown, task: StagePlanDefaultsInput, opts: { defaultOn?: boolean } = {}): MeshTaskStagePlan | null {
204
+ const eligible = isStageEligibleTask(task)
205
+ if (raw === undefined || raw === null) return (opts.defaultOn ?? true) && defaultsOnFor(task) ? defaultStagePlan() : null
206
+ if (raw === false) return null
207
+ if (raw === true) {
208
+ if (!eligible) throw new Error(`invalid_review_option: review requires a non-readonly code_change task (got taskMode=${task.taskMode ?? 'unset'}${task.readonly ? ', readonly' : ''})`)
209
+ return defaultStagePlan()
210
+ }
211
+ if (!isRecord(raw)) throw new Error('invalid_review_option: review must be true, false or {max_revisions?, independence?}')
212
+ const allowed = new Set(['max_revisions', 'maxRevisions', 'independence'])
213
+ for (const key of Object.keys(raw)) {
214
+ if (!allowed.has(key)) throw new Error(`invalid_review_option: unknown review key '${key}' (expected max_revisions, independence)`)
215
+ }
216
+ if (!eligible) throw new Error(`invalid_review_option: review requires a non-readonly code_change task (got taskMode=${task.taskMode ?? 'unset'}${task.readonly ? ', readonly' : ''})`)
217
+ const rawMax = raw.max_revisions ?? raw.maxRevisions
218
+ let maxRevisions = STAGE_DEFAULT_MAX_REVISIONS as MeshTaskStagePlan['maxRevisions']
219
+ if (rawMax !== undefined) {
220
+ if (typeof rawMax !== 'number' || !Number.isInteger(rawMax) || rawMax < 0 || rawMax > STAGE_MAX_REVISIONS_LIMIT) {
221
+ throw new Error(`invalid_review_option: max_revisions must be an integer 0..${STAGE_MAX_REVISIONS_LIMIT}`)
222
+ }
223
+ maxRevisions = rawMax as MeshTaskStagePlan['maxRevisions']
224
+ }
225
+ let independence: MeshStageIndependenceMode = 'fresh_session_ok'
226
+ if (raw.independence !== undefined) {
227
+ if (!(STAGE_INDEPENDENCE_MODES as readonly string[]).includes(raw.independence as string)) {
228
+ throw new Error(`invalid_review_option: independence must be one of ${STAGE_INDEPENDENCE_MODES.join(' | ')}`)
229
+ }
230
+ independence = raw.independence as MeshStageIndependenceMode
231
+ }
232
+ return { review: true, maxRevisions, independence }
233
+ }
234
+
235
+ export function defaultStagePlan(): MeshTaskStagePlan {
236
+ return { review: true, maxRevisions: STAGE_DEFAULT_MAX_REVISIONS as MeshTaskStagePlan['maxRevisions'], independence: 'fresh_session_ok' }
237
+ }
238
+
239
+ /** R5: only non-readonly code_change tasks run the pipeline by default (medium/difficult). */
240
+ export function isStageEligibleTask(task: StagePlanDefaultsInput): boolean {
241
+ if (task.readonly) return false
242
+ return (task.taskMode ?? 'code_change') === 'code_change'
243
+ }
244
+
245
+ function defaultsOnFor(task: StagePlanDefaultsInput): boolean {
246
+ return isStageEligibleTask(task) && (task.difficulty === 'medium' || task.difficulty === 'difficult')
247
+ }
248
+
249
+ // ─── Review report validation (§5.2) ────────────────────────────────────
250
+
251
+ function str(value: unknown): string { return typeof value === 'string' ? value.trim() : '' }
252
+
253
+ function validateStringList(value: unknown, field: string, max: number, maxChars: number, errors: StageValidationError[], minItems = 0): string[] {
254
+ if (!Array.isArray(value)) {
255
+ errors.push({ field, message: `${field} must be an array of strings` })
256
+ return []
257
+ }
258
+ if (value.length > max) errors.push({ field, message: `${field} has ${value.length} entries, over the ${max} limit` })
259
+ const out: string[] = []
260
+ for (const item of value) {
261
+ const text = str(item)
262
+ if (!text) continue
263
+ if (text.length > maxChars) { errors.push({ field, message: `${field} contains an entry over ${maxChars} chars` }); continue }
264
+ out.push(text)
265
+ }
266
+ if (out.length < minItems) errors.push({ field, message: `${field} needs at least ${minItems} entry — an empty ${field} list is a review with no recorded scope` })
267
+ return out
268
+ }
269
+
270
+ export interface ReviewValidationContext {
271
+ /** 1-based review round of the child this report is for. */
272
+ round: number
273
+ /** Blocking/major finding ids still open from the previous round (round ≥ 2 must answer each). */
274
+ priorOpenBlockingIds?: readonly string[]
275
+ }
276
+
277
+ /**
278
+ * Validate the `review` field of a reviewer's `report_completion`. Rejects, never coerces;
279
+ * unknown keys are rejected (a misspelled `notChecked` must not silently vanish).
280
+ */
281
+ export function validateReviewReport(raw: unknown, ctx: ReviewValidationContext): { report?: MeshReviewReport; errors: StageValidationError[] } {
282
+ const errors: StageValidationError[] = []
283
+ if (!isRecord(raw)) return { errors: [{ field: 'review', message: 'review must be an object {verdict, findings, checked, notChecked, ...}' }] }
284
+ const KNOWN = new Set(['verdict', 'findings', 'priorFindings', 'checked', 'notChecked', 'testsRun'])
285
+ for (const key of Object.keys(raw)) if (!KNOWN.has(key)) errors.push({ field: `review.${key}`, message: `unknown field '${key}' (expected one of: ${[...KNOWN].join(', ')})` })
286
+
287
+ const verdict = raw.verdict
288
+ if (!isReviewVerdict(verdict)) errors.push({ field: 'review.verdict', message: `verdict must be one of ${REVIEW_VERDICTS.join(' | ')}` })
289
+
290
+ const findings: MeshReviewFinding[] = []
291
+ if (!Array.isArray(raw.findings)) errors.push({ field: 'review.findings', message: 'findings must be an array (use [] when there are none)' })
292
+ else {
293
+ if (raw.findings.length > REVIEW_FINDINGS_MAX) errors.push({ field: 'review.findings', message: `findings has ${raw.findings.length} entries, over the ${REVIEW_FINDINGS_MAX} limit — keep the most important` })
294
+ const seen = new Set<string>()
295
+ raw.findings.forEach((f, i) => {
296
+ const at = `review.findings[${i}]`
297
+ if (!isRecord(f)) { errors.push({ field: at, message: 'each finding must be an object' }); return }
298
+ const FK = new Set(['id', 'severity', 'category', 'file', 'line', 'claim', 'evidence', 'suggestedFix'])
299
+ for (const key of Object.keys(f)) if (!FK.has(key)) errors.push({ field: `${at}.${key}`, message: `unknown field '${key}'` })
300
+ const id = str(f.id)
301
+ if (!id || id.length > REVIEW_FINDING_ID_MAX_CHARS) errors.push({ field: `${at}.id`, message: `id is required (≤ ${REVIEW_FINDING_ID_MAX_CHARS} chars)` })
302
+ else if (seen.has(id)) errors.push({ field: `${at}.id`, message: `duplicate finding id '${id}'` })
303
+ else seen.add(id)
304
+ if (!isFindingSeverity(f.severity)) errors.push({ field: `${at}.severity`, message: `severity must be one of ${FINDING_SEVERITIES.join(' | ')}` })
305
+ if (!isFindingCategory(f.category)) errors.push({ field: `${at}.category`, message: `category must be one of ${FINDING_CATEGORIES.join(' | ')}` })
306
+ const claim = str(f.claim)
307
+ if (!claim) errors.push({ field: `${at}.claim`, message: 'claim is required' })
308
+ else if (claim.length > REVIEW_CLAIM_MAX_CHARS) errors.push({ field: `${at}.claim`, message: `claim is over ${REVIEW_CLAIM_MAX_CHARS} chars` })
309
+ const evidence = str(f.evidence)
310
+ if (!evidence) errors.push({ field: `${at}.evidence`, message: 'evidence is required — what did you read or run to know this' })
311
+ else if (evidence.length > REVIEW_EVIDENCE_MAX_CHARS) errors.push({ field: `${at}.evidence`, message: `evidence is over ${REVIEW_EVIDENCE_MAX_CHARS} chars` })
312
+ const fix = f.suggestedFix === undefined ? undefined : str(f.suggestedFix)
313
+ if (fix !== undefined && fix.length > REVIEW_FIX_MAX_CHARS) errors.push({ field: `${at}.suggestedFix`, message: `suggestedFix is over ${REVIEW_FIX_MAX_CHARS} chars` })
314
+ if (f.file !== undefined && typeof f.file !== 'string') errors.push({ field: `${at}.file`, message: 'file must be a string' })
315
+ if (f.line !== undefined && (typeof f.line !== 'number' || !Number.isInteger(f.line) || f.line < 1)) errors.push({ field: `${at}.line`, message: 'line must be a positive integer' })
316
+ if (id && isFindingSeverity(f.severity) && isFindingCategory(f.category) && claim && evidence) {
317
+ findings.push({
318
+ id, severity: f.severity, category: f.category,
319
+ ...(typeof f.file === 'string' && f.file.trim() ? { file: f.file.trim() } : {}),
320
+ ...(typeof f.line === 'number' ? { line: f.line } : {}),
321
+ claim, evidence, ...(fix ? { suggestedFix: fix } : {}),
322
+ })
323
+ }
324
+ })
325
+ }
326
+
327
+ const checked = validateStringList(raw.checked, 'review.checked', REVIEW_CHECKED_MAX, REVIEW_CLAIM_MAX_CHARS, errors, 1)
328
+ const notChecked = validateStringList(raw.notChecked, 'review.notChecked', REVIEW_CHECKED_MAX, REVIEW_CLAIM_MAX_CHARS, errors, 1)
329
+
330
+ let priorFindings: MeshPriorFindingStatusEntry[] | undefined
331
+ if (raw.priorFindings !== undefined) {
332
+ if (!Array.isArray(raw.priorFindings)) errors.push({ field: 'review.priorFindings', message: 'priorFindings must be an array' })
333
+ else {
334
+ priorFindings = []
335
+ raw.priorFindings.forEach((p, i) => {
336
+ const at = `review.priorFindings[${i}]`
337
+ if (!isRecord(p)) { errors.push({ field: at, message: 'each entry must be an object {id, status, note?}' }); return }
338
+ for (const key of Object.keys(p)) if (!['id', 'status', 'note'].includes(key)) errors.push({ field: `${at}.${key}`, message: `unknown field '${key}'` })
339
+ const id = str(p.id)
340
+ if (!id) errors.push({ field: `${at}.id`, message: 'id is required' })
341
+ if (!isPriorFindingStatus(p.status)) errors.push({ field: `${at}.status`, message: `status must be one of ${PRIOR_FINDING_STATUSES.join(' | ')}` })
342
+ const note = p.note === undefined ? undefined : str(p.note)
343
+ if (note !== undefined && note.length > REVIEW_NOTE_MAX_CHARS) errors.push({ field: `${at}.note`, message: `note is over ${REVIEW_NOTE_MAX_CHARS} chars` })
344
+ if (id && isPriorFindingStatus(p.status)) priorFindings!.push({ id, status: p.status, ...(note ? { note } : {}) })
345
+ })
346
+ }
347
+ }
348
+
349
+ const testsRun = raw.testsRun === undefined ? undefined : validateTestsRun(raw.testsRun, 'review.testsRun', errors)
350
+
351
+ // Cross-field rules.
352
+ if (isReviewVerdict(verdict)) {
353
+ const blocking = findings.filter(f => isBlockingSeverity(f.severity))
354
+ if (verdict === 'changes_requested' && blocking.length === 0 && Array.isArray(raw.findings) && errors.length === 0) {
355
+ errors.push({ field: 'review.verdict', message: 'changes_requested needs at least one blocking or major finding — nits alone are approve_with_nits' })
356
+ }
357
+ if ((verdict === 'approve') && blocking.length > 0) {
358
+ errors.push({ field: 'review.verdict', message: 'approve cannot carry blocking or major findings' })
359
+ }
360
+ if (verdict === 'approve_with_nits' && blocking.length > 0) {
361
+ errors.push({ field: 'review.verdict', message: 'approve_with_nits cannot carry blocking or major findings — use changes_requested' })
362
+ }
363
+ }
364
+ if (ctx.round >= 2 && ctx.priorOpenBlockingIds?.length) {
365
+ const answered = new Set((priorFindings ?? []).map(p => p.id))
366
+ const missing = ctx.priorOpenBlockingIds.filter(id => !answered.has(id))
367
+ if (missing.length) errors.push({ field: 'review.priorFindings', message: `round ${ctx.round} must give a status for every prior blocking/major finding; missing: ${missing.join(', ')}` })
368
+ }
369
+
370
+ if (errors.length) return { errors }
371
+ return {
372
+ report: {
373
+ verdict: verdict as MeshReviewVerdict,
374
+ findings,
375
+ ...(priorFindings?.length ? { priorFindings } : {}),
376
+ checked,
377
+ notChecked,
378
+ ...(testsRun?.length ? { testsRun } : {}),
379
+ },
380
+ errors: [],
381
+ }
382
+ }
383
+
384
+ /** Shared by the reviewer's `review.testsRun` and the top-level `testsRun` of any report. */
385
+ export function validateTestsRun(raw: unknown, field: string, errors: StageValidationError[]): MeshTestRun[] {
386
+ if (!Array.isArray(raw)) { errors.push({ field, message: `${field} must be an array of {command, exit, passed?, failed?, note?}` }); return [] }
387
+ if (raw.length > REVIEW_TESTS_RUN_MAX) errors.push({ field, message: `${field} has ${raw.length} entries, over the ${REVIEW_TESTS_RUN_MAX} limit` })
388
+ const out: MeshTestRun[] = []
389
+ raw.forEach((t, i) => {
390
+ const at = `${field}[${i}]`
391
+ if (!isRecord(t)) { errors.push({ field: at, message: 'each entry must be an object' }); return }
392
+ for (const key of Object.keys(t)) if (!['command', 'exit', 'passed', 'failed', 'note'].includes(key)) errors.push({ field: `${at}.${key}`, message: `unknown field '${key}'` })
393
+ const command = str(t.command)
394
+ if (!command || command.length > REVIEW_CLAIM_MAX_CHARS) errors.push({ field: `${at}.command`, message: `command is required (≤ ${REVIEW_CLAIM_MAX_CHARS} chars)` })
395
+ if (typeof t.exit !== 'number' || !Number.isInteger(t.exit)) errors.push({ field: `${at}.exit`, message: 'exit must be an integer' })
396
+ for (const k of ['passed', 'failed'] as const) {
397
+ if (t[k] !== undefined && (typeof t[k] !== 'number' || !Number.isInteger(t[k] as number) || (t[k] as number) < 0)) errors.push({ field: `${at}.${k}`, message: `${k} must be a non-negative integer` })
398
+ }
399
+ const note = t.note === undefined ? undefined : str(t.note)
400
+ if (note !== undefined && note.length > REVIEW_NOTE_MAX_CHARS) errors.push({ field: `${at}.note`, message: `note is over ${REVIEW_NOTE_MAX_CHARS} chars` })
401
+ if (command && typeof t.exit === 'number') {
402
+ out.push({
403
+ command, exit: t.exit,
404
+ ...(typeof t.passed === 'number' ? { passed: t.passed } : {}),
405
+ ...(typeof t.failed === 'number' ? { failed: t.failed } : {}),
406
+ ...(note ? { note } : {}),
407
+ })
408
+ }
409
+ })
410
+ return out
411
+ }
412
+
413
+ /** Validate an implementer's `findingResponses` (§5.3). */
414
+ export function validateFindingResponses(raw: unknown, field = 'findingResponses'): { responses?: MeshFindingResponse[]; errors: StageValidationError[] } {
415
+ const errors: StageValidationError[] = []
416
+ if (!Array.isArray(raw)) return { errors: [{ field, message: `${field} must be an array of {id, response, note}` }] }
417
+ if (raw.length > FINDING_RESPONSES_MAX) errors.push({ field, message: `${field} has ${raw.length} entries, over the ${FINDING_RESPONSES_MAX} limit` })
418
+ const out: MeshFindingResponse[] = []
419
+ raw.forEach((r, i) => {
420
+ const at = `${field}[${i}]`
421
+ if (!isRecord(r)) { errors.push({ field: at, message: 'each entry must be an object {id, response, note}' }); return }
422
+ for (const key of Object.keys(r)) if (!['id', 'response', 'note'].includes(key)) errors.push({ field: `${at}.${key}`, message: `unknown field '${key}'` })
423
+ const id = str(r.id)
424
+ if (!id) errors.push({ field: `${at}.id`, message: 'id is required' })
425
+ if (!isFindingResponseKind(r.response)) errors.push({ field: `${at}.response`, message: `response must be one of ${FINDING_RESPONSE_KINDS.join(' | ')}` })
426
+ const note = str(r.note)
427
+ if (!note) errors.push({ field: `${at}.note`, message: 'note is required — say what changed, or why you dispute it' })
428
+ else if (note.length > REVIEW_NOTE_MAX_CHARS) errors.push({ field: `${at}.note`, message: `note is over ${REVIEW_NOTE_MAX_CHARS} chars` })
429
+ if (id && isFindingResponseKind(r.response) && note && note.length <= REVIEW_NOTE_MAX_CHARS) out.push({ id, response: r.response, note })
430
+ })
431
+ return errors.length ? { errors } : { responses: out, errors: [] }
432
+ }
433
+
434
+ // ─── Verdict line (§5.4) ────────────────────────────────────────────────
435
+
436
+ export interface StageVerdictLineInput {
437
+ verdict: MeshReviewVerdict | 'skipped_no_diff'
438
+ rounds: number
439
+ reviewerProvider?: string
440
+ independenceUsed?: MeshStageIndependenceUsed
441
+ fixed?: number
442
+ openNits?: number
443
+ }
444
+
445
+ /** One human-readable line: `review: approve_with_nits · 2 rounds · reviewer codex-cli (different_provider) · 3 findings fixed, 1 nit open`. */
446
+ export function formatStageVerdictLine(input: StageVerdictLineInput): string {
447
+ const parts: string[] = [`review: ${input.verdict}`]
448
+ if (input.verdict === 'skipped_no_diff') return parts[0]
449
+ parts.push(`${input.rounds} round${input.rounds === 1 ? '' : 's'}`)
450
+ if (input.reviewerProvider) parts.push(`reviewer ${input.reviewerProvider} (${input.independenceUsed ?? 'different_provider'})`)
451
+ const tail: string[] = []
452
+ if (input.fixed) tail.push(`${input.fixed} finding${input.fixed === 1 ? '' : 's'} fixed`)
453
+ if (input.openNits) tail.push(`${input.openNits} nit${input.openNits === 1 ? '' : 's'} open`)
454
+ return tail.length ? `${parts.join(' · ')} · ${tail.join(', ')}` : parts.join(' · ')
455
+ }
@@ -79,6 +79,33 @@ export function sanitizeRefusalCode(value: unknown): string | undefined {
79
79
  return normalized.slice(0, 64)
80
80
  }
81
81
 
82
+ /** Longest refusal message kept on a failed dispatch (see {@link sanitizeDispatchRefusalDetail}). */
83
+ export const DISPATCH_REFUSAL_DETAIL_MAX = 200
84
+
85
+ /**
86
+ * Bounded, sanitized "why was this dispatch refused" detail for triage:
87
+ * `{code, message}` with the code in the refusal-code identifier shape and the
88
+ * message a single printable line of at most {@link DISPATCH_REFUSAL_DETAIL_MAX}
89
+ * chars (home-directory prefixes collapsed to `~`). Refusal texts are generated
90
+ * by the daemon / transport, never by a user or an agent. LOCAL records only:
91
+ * it is deliberately NOT part of the replicated turn evidence (content-free).
92
+ */
93
+ export function sanitizeDispatchRefusalDetail(code: unknown, message: unknown): { code?: string; message?: string } | undefined {
94
+ const cleanCode = sanitizeRefusalCode(code)
95
+ let cleanMessage: string | undefined
96
+ if (typeof message === 'string') {
97
+ const line = message
98
+ .replace(/(?:[A-Za-z]:)?[\\/](?:Users|home)[\\/][^\s\\/]+/g, '~')
99
+ // eslint-disable-next-line no-control-regex
100
+ .replace(/[\u0000-\u001f\u007f]+/g, ' ')
101
+ .replace(/\s+/g, ' ')
102
+ .trim()
103
+ if (line) cleanMessage = line.length > DISPATCH_REFUSAL_DETAIL_MAX ? `${line.slice(0, DISPATCH_REFUSAL_DETAIL_MAX - 1)}…` : line
104
+ }
105
+ if (!cleanCode && !cleanMessage) return undefined
106
+ return { ...(cleanCode ? { code: cleanCode } : {}), ...(cleanMessage ? { message: cleanMessage } : {}) }
107
+ }
108
+
82
109
  export const CONSUME_PROFILES = ['default', 'native_source'] as const
83
110
  export type ConsumeProfile = typeof CONSUME_PROFILES[number]
84
111
 
@@ -172,6 +199,8 @@ export const TURN_REASONS = [
172
199
  'operator_cancel', 'intentional_cleanup', 'task_removed', 'mission_abandoned', 'superseded',
173
200
  'operator_update', 'refine_terminal', 'validation_terminal',
174
201
  'hard_ceiling', 'reclaim_budget_exhausted', 'hollow_max_retries', 'migration_orphan',
202
+ // a stopping attempt whose writer node stayed unreachable (or was removed) past the bound
203
+ 'writer_unreachable',
175
204
  // reclaims (generation + 1)
176
205
  'dispatch_refused_session_exited', 'dispatch_refused_no_target', 'dispatch_refused_unsupported_input', 'dispatch_failed',
177
206
  'session_exit', 'session_exit_before_turn', 'session_dead', 'hollow_completion',
@@ -689,6 +689,8 @@ export interface LedgerQueryEntryWire {
689
689
  export interface LedgerQuerySummaryWire {
690
690
  /** Absent on older peers; never folded into failed by the decoder. */
691
691
  taskBlocked?: number
692
+ /** Failed Refinery jobs (not tasks). Absent on older peers. */
693
+ refineFailed?: number
692
694
  meshId: string
693
695
  totalEntries: number
694
696
  taskDispatched: number
@@ -734,13 +736,14 @@ function isLedgerQueryEntryWire(value: unknown): value is LedgerQueryEntryWire {
734
736
  }
735
737
 
736
738
  function isLedgerQuerySummaryWire(value: unknown): value is LedgerQuerySummaryWire {
737
- const keys = ['meshId', 'totalEntries', 'taskDispatched', 'taskCompleted', 'taskFailed', 'taskBlocked', 'taskStalled', 'sessionLaunched', 'checkpointCreated', 'lastActivityAt', 'recentFailures'] as const
739
+ const keys = ['meshId', 'totalEntries', 'taskDispatched', 'taskCompleted', 'taskFailed', 'taskBlocked', 'taskStalled', 'sessionLaunched', 'checkpointCreated', 'lastActivityAt', 'recentFailures', 'taskBlocked', 'refineFailed'] as const
738
740
  if (!isRecord(value) || !hasOnlyKeys(value, keys)) return false
739
741
  if (!isEvidenceIdentifier(value.meshId)) return false
740
742
  for (const k of ['totalEntries', 'taskDispatched', 'taskCompleted', 'taskFailed', 'taskStalled', 'sessionLaunched', 'checkpointCreated', 'recentFailures'] as const) {
741
743
  if (!isNonNegativeInt(value[k])) return false
742
744
  }
743
745
  if (value.taskBlocked !== undefined && !isNonNegativeInt(value.taskBlocked)) return false
746
+ if (value.refineFailed !== undefined && !isNonNegativeInt(value.refineFailed)) return false
744
747
  if (value.lastActivityAt !== null && typeof value.lastActivityAt !== 'string') return false
745
748
  return true
746
749
  }
@@ -86,6 +86,33 @@ export interface WorkerProtocolFooterInput {
86
86
  * which is what every worker launched with the default gate receives.
87
87
  */
88
88
  workerMcp?: boolean
89
+ /**
90
+ * Same-machine light task: the worker runs in a temporary light workspace.
91
+ * Renders the light-workspace rules (stay inside, commit there, no installs).
92
+ */
93
+ light?: { workspace: string; baseSha: string; ossBaseSha?: string; ownedPaths: string[] }
94
+ /**
95
+ * Review-in-task (docs/design/2026-11-01-review-in-task.md §9.3): present when this
96
+ * dispatch is one stage of a stage pipeline. `workspace` is the reviewer's pinned
97
+ * workspace path when the daemon prepared one.
98
+ */
99
+ stage?: { role: 'implement' | 'revise' | 'review'; round: number; maxRevisions: number; workspace?: string }
100
+ }
101
+
102
+ /** Light-workspace worker rules (design §9). */
103
+ export function renderLightWorkspaceRules(light: NonNullable<WorkerProtocolFooterInput['light']>): string[] {
104
+ const base = light.ossBaseSha ? `${light.baseSha} (oss ${light.ossBaseSha})` : light.baseSha
105
+ return [
106
+ `You are working in a temporary light workspace at \`${light.workspace}\` based on \`${base}\`. `
107
+ + 'Work only inside it. Commit your change there (the branch is already set up); do not push.',
108
+ 'Do not run `npm install`/`npm ci`/`npm rebuild`/`node-gyp`, do not change package.json or lockfiles — '
109
+ + 'if the fix needs a dependency change, stop and report `blocked`.',
110
+ 'Do not start long-running servers on fixed ports. Run the narrowest tests that cover your change and '
111
+ + 'list them in `report_completion.testsRun`.',
112
+ light.ownedPaths.length
113
+ ? `Stay inside \`owned_paths\` (${light.ownedPaths.join(', ')}); if you must touch more, say why in the summary.`
114
+ : 'Stay inside the paths the task names; if you must touch more, say why in the summary.',
115
+ ]
89
116
  }
90
117
 
91
118
  export function hasWorkerProtocolFooter(body: string): boolean {
@@ -123,6 +150,7 @@ export function renderWorkerProtocolFooter(input: WorkerProtocolFooterInput = {}
123
150
  if (input.readonly) scope.push('read-only')
124
151
  if (scope.length) lines.push(`You are a delegated worker (${scope.join(', ')}).`)
125
152
  else lines.push('You are a delegated worker.')
153
+ if (input.light) lines.push(...renderLightWorkspaceRules(input.light))
126
154
  if (input.workerMcp === false) {
127
155
  lines.push(
128
156
  'This session has NO adhdev worker tools (`report_completion`, `progress_update`, `peer_context_pull`, '
@@ -169,9 +197,29 @@ export function renderWorkerProtocolFooter(input: WorkerProtocolFooterInput = {}
169
197
  + 'honour their conflict guidance and add your own in `handoff_notes` when you report.',
170
198
  )
171
199
  }
200
+ if (input.stage) lines.push(...renderStageProtocolLines(input.stage))
172
201
  return lines.join('\n')
173
202
  }
174
203
 
204
+ /** The stage-pipeline paragraph of the worker footer (implement / revise / review). */
205
+ export function renderStageProtocolLines(stage: NonNullable<WorkerProtocolFooterInput['stage']>): string[] {
206
+ if (stage.role === 'review') {
207
+ return [
208
+ `STAGE: you are the independent reviewer (round ${stage.round} of at most ${stage.maxRevisions + 1}). Read the input artifacts first (diff, self-check log, previous verdict).`
209
+ + (stage.workspace ? ` Your workspace ${stage.workspace} is pinned to the round head — you may run tests, but nothing you change lands; do not fix, record findings instead.` : ' Do not modify the workspace: read it, and record findings instead of fixing.'),
210
+ 'Your `report_completion` MUST carry `review`: {verdict: approve | approve_with_nits | changes_requested | reject_approach, findings[{id, severity, category, claim, evidence, suggested_fix?}], checked[], not_checked[], tests_run?[]}. '
211
+ + '`changes_requested` needs at least one blocking/major finding; `approve` allows none. From round 2 also give `prior_findings[{id, status}]` for every earlier blocking/major finding. '
212
+ + '`reject_approach` is only for a wrong approach, not for fixable defects.',
213
+ ]
214
+ }
215
+ return [
216
+ `STAGE: your \`report_completion\` is a stage report (${stage.role}, round ${stage.round}). An independent reviewer reads your diff next, so commit your work and leave the workspace clean before you report. You may receive review findings as a follow-up memo in this same session.`,
217
+ ...(stage.role === 'revise'
218
+ ? ['For every open blocking/major finding in the memo, fill `finding_responses[{id, response: fixed | disputed, note}]` — `disputed` needs your reasoning; the reviewer judges it next round.']
219
+ : []),
220
+ ]
221
+ }
222
+
175
223
  /**
176
224
  * The authored text of a dispatched body: everything before the footer marker.
177
225
  * Ledger descriptors, replay fixtures and tests compare authored text, never