@adhdev/mesh-shared 1.0.82-rc.12 → 1.0.82-rc.120

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.
Files changed (60) hide show
  1. package/dist/assistant-protocol.d.ts +158 -6
  2. package/dist/decision-push-relay.d.ts +20 -0
  3. package/dist/index.d.ts +10 -0
  4. package/dist/index.js +1534 -112
  5. package/dist/index.js.map +1 -1
  6. package/dist/index.mjs +1400 -112
  7. package/dist/index.mjs.map +1 -1
  8. package/dist/launch-defaults.d.ts +196 -0
  9. package/dist/light-task.d.ts +96 -0
  10. package/dist/mesh-tool-names.d.ts +2 -2
  11. package/dist/mesh-vocabulary.d.ts +13 -4
  12. package/dist/mission-git-state.d.ts +83 -0
  13. package/dist/mission-items.d.ts +202 -0
  14. package/dist/node-facts.d.ts +54 -1
  15. package/dist/outbound-message.d.ts +9 -2
  16. package/dist/protocol/daemon-server.d.ts +42 -2
  17. package/dist/protocol/dashboard-daemon-p2p.d.ts +1 -1
  18. package/dist/protocol/dashboard-server.d.ts +20 -2
  19. package/dist/quota-freshness.d.ts +4 -4
  20. package/dist/relay-reprobe.d.ts +52 -0
  21. package/dist/release.d.ts +90 -0
  22. package/dist/role-launch.d.ts +11 -0
  23. package/dist/session-launch.d.ts +10 -22
  24. package/dist/slot-proposal.d.ts +14 -0
  25. package/dist/task-source-phase.d.ts +83 -0
  26. package/dist/task-stages.d.ts +210 -0
  27. package/dist/turn-evidence.d.ts +31 -9
  28. package/dist/turn-ipc-mission.d.ts +72 -1
  29. package/dist/turn-ipc-queue.d.ts +30 -0
  30. package/dist/turn-ipc.d.ts +2 -2
  31. package/dist/worker-protocol.d.ts +41 -1
  32. package/package.json +1 -1
  33. package/src/assistant-protocol.ts +294 -6
  34. package/src/daemon-normalize.ts +7 -5
  35. package/src/decision-push-relay.ts +23 -0
  36. package/src/index.ts +11 -0
  37. package/src/launch-defaults.ts +170 -0
  38. package/src/light-task.ts +116 -0
  39. package/src/mesh-tool-names.ts +22 -0
  40. package/src/mesh-vocabulary.ts +12 -2
  41. package/src/mission-git-state.ts +112 -0
  42. package/src/mission-items.ts +421 -0
  43. package/src/node-facts.ts +54 -1
  44. package/src/outbound-message.ts +19 -0
  45. package/src/protocol/daemon-server.ts +37 -2
  46. package/src/protocol/dashboard-server.ts +13 -2
  47. package/src/quota-freshness.ts +29 -13
  48. package/src/relay-reprobe.ts +117 -0
  49. package/src/release.ts +121 -0
  50. package/src/role-launch.ts +51 -0
  51. package/src/session-launch.ts +17 -1
  52. package/src/slot-proposal.ts +61 -2
  53. package/src/task-source-phase.ts +70 -0
  54. package/src/task-stages.ts +459 -0
  55. package/src/turn-evidence.ts +47 -7
  56. package/src/turn-ipc-mission.ts +127 -11
  57. package/src/turn-ipc-queue.ts +45 -2
  58. package/src/turn-ipc-turn.ts +1 -1
  59. package/src/turn-ipc.ts +1 -0
  60. package/src/worker-protocol.ts +94 -0
@@ -0,0 +1,459 @@
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
+ /** The underlying error text when the reason alone does not say it (e.g. why no reviewer could be created). */
121
+ blockedDetail?: string
122
+ /** Unresolved findings snapshot kept for the final report (id + severity + claim). */
123
+ openFindings?: Array<{ id: string; severity: MeshFindingSeverity; claim: string }>
124
+ /** Nits/minors from the approving verdict, delivered in the final report. */
125
+ openNits?: Array<{ id: string; severity: MeshFindingSeverity; claim: string }>
126
+ /** Self-check outcome summary for the final report. */
127
+ selfCheck?: 'passed' | 'skipped_not_configured' | 'skipped_infra_error' | 'unavailable' | 'failed'
128
+ /** Resolved/disputed counters for the verdict line. */
129
+ findingsFixed?: number
130
+ /** The original coordinator message, preserved while revise memos replace `message`. */
131
+ originalMessage?: string
132
+ /** Artifact ids the implementer cited in its own report (feed the next stage's input, top 4). */
133
+ workerArtifactIds?: string[]
134
+ /** Read-lease reviews only: HEAD + working-tree fingerprint of the parent checkout taken when the review child was created (§11). */
135
+ reviewFingerprint?: string
136
+ /** Read-lease review whose baseline fingerprint could not be taken (after one retry): the verdict is never accepted. */
137
+ reviewFingerprintUnavailable?: boolean
138
+ /** True once the parent was released to a terminal by the pipeline (hold lifted). */
139
+ released?: boolean
140
+ }
141
+
142
+ export interface MeshReviewFinding {
143
+ id: string
144
+ severity: MeshFindingSeverity
145
+ category: MeshFindingCategory
146
+ file?: string
147
+ line?: number
148
+ claim: string
149
+ evidence: string
150
+ suggestedFix?: string
151
+ }
152
+
153
+ export interface MeshPriorFindingStatusEntry { id: string; status: MeshPriorFindingStatus; note?: string }
154
+
155
+ /** One definition: the light-task `LightTestRun` (same {command, exit, passed?, failed?, note?} shape). */
156
+ export type MeshTestRun = LightTestRun
157
+
158
+ export interface MeshReviewReport {
159
+ verdict: MeshReviewVerdict
160
+ findings: MeshReviewFinding[]
161
+ priorFindings?: MeshPriorFindingStatusEntry[]
162
+ checked: string[]
163
+ notChecked: string[]
164
+ testsRun?: MeshTestRun[]
165
+ }
166
+
167
+ export interface MeshFindingResponse { id: string; response: MeshFindingResponseKind; note: string }
168
+
169
+ export interface StageValidationError { field: string; message: string }
170
+
171
+ // ─── Guards ─────────────────────────────────────────────────────────────
172
+
173
+ function makeGuard<T extends readonly string[]>(values: T): (value: unknown) => value is T[number] {
174
+ const set: ReadonlySet<string> = new Set(values)
175
+ return (value: unknown): value is T[number] => typeof value === 'string' && set.has(value)
176
+ }
177
+
178
+ export const isReviewVerdict = makeGuard(REVIEW_VERDICTS)
179
+ export const isFindingSeverity = makeGuard(FINDING_SEVERITIES)
180
+ export const isFindingCategory = makeGuard(FINDING_CATEGORIES)
181
+ export const isPriorFindingStatus = makeGuard(PRIOR_FINDING_STATUSES)
182
+ export const isFindingResponseKind = makeGuard(FINDING_RESPONSE_KINDS)
183
+ export const isStageBlockedReason = makeGuard(STAGE_BLOCKED_REASONS)
184
+
185
+ const isRecord = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)
186
+
187
+ /** Blocking/major findings keep a review from passing. */
188
+ export function isBlockingSeverity(severity: MeshFindingSeverity): boolean {
189
+ return severity === 'blocking' || severity === 'major'
190
+ }
191
+
192
+ // ─── Plan normalization (enqueue `review` option, R5) ───────────────────
193
+
194
+ export interface StagePlanDefaultsInput {
195
+ taskMode?: string
196
+ difficulty?: string
197
+ readonly?: boolean
198
+ }
199
+
200
+ /**
201
+ * Resolve the enqueue-time `review` option into a stage plan, or null when review is off.
202
+ * `review` undefined → OFF (owner decision 2026-11-08: in-task review is opt-in; the default cost speed and parallelism
203
+ * without catching the live bugs). Pass `review: true` (or an options object) for a change that genuinely needs one.
204
+ * `defaultOn: true` restores the old R5 default (medium/difficult non-readonly `code_change` → on) for a caller that asks for it.
205
+ * Throws `invalid_review_option: …` on malformed input (rejected, never coerced).
206
+ */
207
+ export function resolveStagePlan(raw: unknown, task: StagePlanDefaultsInput, opts: { defaultOn?: boolean } = {}): MeshTaskStagePlan | null {
208
+ const eligible = isStageEligibleTask(task)
209
+ if (raw === undefined || raw === null) return (opts.defaultOn ?? false) && defaultsOnFor(task) ? defaultStagePlan() : null
210
+ if (raw === false) return null
211
+ if (raw === true) {
212
+ if (!eligible) throw new Error(`invalid_review_option: review requires a non-readonly code_change task (got taskMode=${task.taskMode ?? 'unset'}${task.readonly ? ', readonly' : ''})`)
213
+ return defaultStagePlan()
214
+ }
215
+ if (!isRecord(raw)) throw new Error('invalid_review_option: review must be true, false or {max_revisions?, independence?}')
216
+ const allowed = new Set(['max_revisions', 'maxRevisions', 'independence'])
217
+ for (const key of Object.keys(raw)) {
218
+ if (!allowed.has(key)) throw new Error(`invalid_review_option: unknown review key '${key}' (expected max_revisions, independence)`)
219
+ }
220
+ if (!eligible) throw new Error(`invalid_review_option: review requires a non-readonly code_change task (got taskMode=${task.taskMode ?? 'unset'}${task.readonly ? ', readonly' : ''})`)
221
+ const rawMax = raw.max_revisions ?? raw.maxRevisions
222
+ let maxRevisions = STAGE_DEFAULT_MAX_REVISIONS as MeshTaskStagePlan['maxRevisions']
223
+ if (rawMax !== undefined) {
224
+ if (typeof rawMax !== 'number' || !Number.isInteger(rawMax) || rawMax < 0 || rawMax > STAGE_MAX_REVISIONS_LIMIT) {
225
+ throw new Error(`invalid_review_option: max_revisions must be an integer 0..${STAGE_MAX_REVISIONS_LIMIT}`)
226
+ }
227
+ maxRevisions = rawMax as MeshTaskStagePlan['maxRevisions']
228
+ }
229
+ let independence: MeshStageIndependenceMode = 'fresh_session_ok'
230
+ if (raw.independence !== undefined) {
231
+ if (!(STAGE_INDEPENDENCE_MODES as readonly string[]).includes(raw.independence as string)) {
232
+ throw new Error(`invalid_review_option: independence must be one of ${STAGE_INDEPENDENCE_MODES.join(' | ')}`)
233
+ }
234
+ independence = raw.independence as MeshStageIndependenceMode
235
+ }
236
+ return { review: true, maxRevisions, independence }
237
+ }
238
+
239
+ export function defaultStagePlan(): MeshTaskStagePlan {
240
+ return { review: true, maxRevisions: STAGE_DEFAULT_MAX_REVISIONS as MeshTaskStagePlan['maxRevisions'], independence: 'fresh_session_ok' }
241
+ }
242
+
243
+ /** R5: only non-readonly code_change tasks run the pipeline by default (medium/difficult). */
244
+ export function isStageEligibleTask(task: StagePlanDefaultsInput): boolean {
245
+ if (task.readonly) return false
246
+ return (task.taskMode ?? 'code_change') === 'code_change'
247
+ }
248
+
249
+ function defaultsOnFor(task: StagePlanDefaultsInput): boolean {
250
+ return isStageEligibleTask(task) && (task.difficulty === 'medium' || task.difficulty === 'difficult')
251
+ }
252
+
253
+ // ─── Review report validation (§5.2) ────────────────────────────────────
254
+
255
+ function str(value: unknown): string { return typeof value === 'string' ? value.trim() : '' }
256
+
257
+ function validateStringList(value: unknown, field: string, max: number, maxChars: number, errors: StageValidationError[], minItems = 0): string[] {
258
+ if (!Array.isArray(value)) {
259
+ errors.push({ field, message: `${field} must be an array of strings` })
260
+ return []
261
+ }
262
+ if (value.length > max) errors.push({ field, message: `${field} has ${value.length} entries, over the ${max} limit` })
263
+ const out: string[] = []
264
+ for (const item of value) {
265
+ const text = str(item)
266
+ if (!text) continue
267
+ if (text.length > maxChars) { errors.push({ field, message: `${field} contains an entry over ${maxChars} chars` }); continue }
268
+ out.push(text)
269
+ }
270
+ 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` })
271
+ return out
272
+ }
273
+
274
+ export interface ReviewValidationContext {
275
+ /** 1-based review round of the child this report is for. */
276
+ round: number
277
+ /** Blocking/major finding ids still open from the previous round (round ≥ 2 must answer each). */
278
+ priorOpenBlockingIds?: readonly string[]
279
+ }
280
+
281
+ /**
282
+ * Validate the `review` field of a reviewer's `report_completion`. Rejects, never coerces;
283
+ * unknown keys are rejected (a misspelled `notChecked` must not silently vanish).
284
+ */
285
+ export function validateReviewReport(raw: unknown, ctx: ReviewValidationContext): { report?: MeshReviewReport; errors: StageValidationError[] } {
286
+ const errors: StageValidationError[] = []
287
+ if (!isRecord(raw)) return { errors: [{ field: 'review', message: 'review must be an object {verdict, findings, checked, notChecked, ...}' }] }
288
+ const KNOWN = new Set(['verdict', 'findings', 'priorFindings', 'checked', 'notChecked', 'testsRun'])
289
+ 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(', ')})` })
290
+
291
+ const verdict = raw.verdict
292
+ if (!isReviewVerdict(verdict)) errors.push({ field: 'review.verdict', message: `verdict must be one of ${REVIEW_VERDICTS.join(' | ')}` })
293
+
294
+ const findings: MeshReviewFinding[] = []
295
+ if (!Array.isArray(raw.findings)) errors.push({ field: 'review.findings', message: 'findings must be an array (use [] when there are none)' })
296
+ else {
297
+ 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` })
298
+ const seen = new Set<string>()
299
+ raw.findings.forEach((f, i) => {
300
+ const at = `review.findings[${i}]`
301
+ if (!isRecord(f)) { errors.push({ field: at, message: 'each finding must be an object' }); return }
302
+ const FK = new Set(['id', 'severity', 'category', 'file', 'line', 'claim', 'evidence', 'suggestedFix'])
303
+ for (const key of Object.keys(f)) if (!FK.has(key)) errors.push({ field: `${at}.${key}`, message: `unknown field '${key}'` })
304
+ const id = str(f.id)
305
+ if (!id || id.length > REVIEW_FINDING_ID_MAX_CHARS) errors.push({ field: `${at}.id`, message: `id is required (≤ ${REVIEW_FINDING_ID_MAX_CHARS} chars)` })
306
+ else if (seen.has(id)) errors.push({ field: `${at}.id`, message: `duplicate finding id '${id}'` })
307
+ else seen.add(id)
308
+ if (!isFindingSeverity(f.severity)) errors.push({ field: `${at}.severity`, message: `severity must be one of ${FINDING_SEVERITIES.join(' | ')}` })
309
+ if (!isFindingCategory(f.category)) errors.push({ field: `${at}.category`, message: `category must be one of ${FINDING_CATEGORIES.join(' | ')}` })
310
+ const claim = str(f.claim)
311
+ if (!claim) errors.push({ field: `${at}.claim`, message: 'claim is required' })
312
+ else if (claim.length > REVIEW_CLAIM_MAX_CHARS) errors.push({ field: `${at}.claim`, message: `claim is over ${REVIEW_CLAIM_MAX_CHARS} chars` })
313
+ const evidence = str(f.evidence)
314
+ if (!evidence) errors.push({ field: `${at}.evidence`, message: 'evidence is required — what did you read or run to know this' })
315
+ else if (evidence.length > REVIEW_EVIDENCE_MAX_CHARS) errors.push({ field: `${at}.evidence`, message: `evidence is over ${REVIEW_EVIDENCE_MAX_CHARS} chars` })
316
+ const fix = f.suggestedFix === undefined ? undefined : str(f.suggestedFix)
317
+ if (fix !== undefined && fix.length > REVIEW_FIX_MAX_CHARS) errors.push({ field: `${at}.suggestedFix`, message: `suggestedFix is over ${REVIEW_FIX_MAX_CHARS} chars` })
318
+ if (f.file !== undefined && typeof f.file !== 'string') errors.push({ field: `${at}.file`, message: 'file must be a string' })
319
+ 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' })
320
+ if (id && isFindingSeverity(f.severity) && isFindingCategory(f.category) && claim && evidence) {
321
+ findings.push({
322
+ id, severity: f.severity, category: f.category,
323
+ ...(typeof f.file === 'string' && f.file.trim() ? { file: f.file.trim() } : {}),
324
+ ...(typeof f.line === 'number' ? { line: f.line } : {}),
325
+ claim, evidence, ...(fix ? { suggestedFix: fix } : {}),
326
+ })
327
+ }
328
+ })
329
+ }
330
+
331
+ const checked = validateStringList(raw.checked, 'review.checked', REVIEW_CHECKED_MAX, REVIEW_CLAIM_MAX_CHARS, errors, 1)
332
+ const notChecked = validateStringList(raw.notChecked, 'review.notChecked', REVIEW_CHECKED_MAX, REVIEW_CLAIM_MAX_CHARS, errors, 1)
333
+
334
+ let priorFindings: MeshPriorFindingStatusEntry[] | undefined
335
+ if (raw.priorFindings !== undefined) {
336
+ if (!Array.isArray(raw.priorFindings)) errors.push({ field: 'review.priorFindings', message: 'priorFindings must be an array' })
337
+ else {
338
+ priorFindings = []
339
+ raw.priorFindings.forEach((p, i) => {
340
+ const at = `review.priorFindings[${i}]`
341
+ if (!isRecord(p)) { errors.push({ field: at, message: 'each entry must be an object {id, status, note?}' }); return }
342
+ for (const key of Object.keys(p)) if (!['id', 'status', 'note'].includes(key)) errors.push({ field: `${at}.${key}`, message: `unknown field '${key}'` })
343
+ const id = str(p.id)
344
+ if (!id) errors.push({ field: `${at}.id`, message: 'id is required' })
345
+ if (!isPriorFindingStatus(p.status)) errors.push({ field: `${at}.status`, message: `status must be one of ${PRIOR_FINDING_STATUSES.join(' | ')}` })
346
+ const note = p.note === undefined ? undefined : str(p.note)
347
+ if (note !== undefined && note.length > REVIEW_NOTE_MAX_CHARS) errors.push({ field: `${at}.note`, message: `note is over ${REVIEW_NOTE_MAX_CHARS} chars` })
348
+ if (id && isPriorFindingStatus(p.status)) priorFindings!.push({ id, status: p.status, ...(note ? { note } : {}) })
349
+ })
350
+ }
351
+ }
352
+
353
+ const testsRun = raw.testsRun === undefined ? undefined : validateTestsRun(raw.testsRun, 'review.testsRun', errors)
354
+
355
+ // Cross-field rules.
356
+ if (isReviewVerdict(verdict)) {
357
+ const blocking = findings.filter(f => isBlockingSeverity(f.severity))
358
+ if (verdict === 'changes_requested' && blocking.length === 0 && Array.isArray(raw.findings) && errors.length === 0) {
359
+ errors.push({ field: 'review.verdict', message: 'changes_requested needs at least one blocking or major finding — nits alone are approve_with_nits' })
360
+ }
361
+ if ((verdict === 'approve') && blocking.length > 0) {
362
+ errors.push({ field: 'review.verdict', message: 'approve cannot carry blocking or major findings' })
363
+ }
364
+ if (verdict === 'approve_with_nits' && blocking.length > 0) {
365
+ errors.push({ field: 'review.verdict', message: 'approve_with_nits cannot carry blocking or major findings — use changes_requested' })
366
+ }
367
+ }
368
+ if (ctx.round >= 2 && ctx.priorOpenBlockingIds?.length) {
369
+ const answered = new Set((priorFindings ?? []).map(p => p.id))
370
+ const missing = ctx.priorOpenBlockingIds.filter(id => !answered.has(id))
371
+ 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(', ')}` })
372
+ }
373
+
374
+ if (errors.length) return { errors }
375
+ return {
376
+ report: {
377
+ verdict: verdict as MeshReviewVerdict,
378
+ findings,
379
+ ...(priorFindings?.length ? { priorFindings } : {}),
380
+ checked,
381
+ notChecked,
382
+ ...(testsRun?.length ? { testsRun } : {}),
383
+ },
384
+ errors: [],
385
+ }
386
+ }
387
+
388
+ /** Shared by the reviewer's `review.testsRun` and the top-level `testsRun` of any report. */
389
+ export function validateTestsRun(raw: unknown, field: string, errors: StageValidationError[]): MeshTestRun[] {
390
+ if (!Array.isArray(raw)) { errors.push({ field, message: `${field} must be an array of {command, exit, passed?, failed?, note?}` }); return [] }
391
+ if (raw.length > REVIEW_TESTS_RUN_MAX) errors.push({ field, message: `${field} has ${raw.length} entries, over the ${REVIEW_TESTS_RUN_MAX} limit` })
392
+ const out: MeshTestRun[] = []
393
+ raw.forEach((t, i) => {
394
+ const at = `${field}[${i}]`
395
+ if (!isRecord(t)) { errors.push({ field: at, message: 'each entry must be an object' }); return }
396
+ for (const key of Object.keys(t)) if (!['command', 'exit', 'passed', 'failed', 'note'].includes(key)) errors.push({ field: `${at}.${key}`, message: `unknown field '${key}'` })
397
+ const command = str(t.command)
398
+ if (!command || command.length > REVIEW_CLAIM_MAX_CHARS) errors.push({ field: `${at}.command`, message: `command is required (≤ ${REVIEW_CLAIM_MAX_CHARS} chars)` })
399
+ if (typeof t.exit !== 'number' || !Number.isInteger(t.exit)) errors.push({ field: `${at}.exit`, message: 'exit must be an integer' })
400
+ for (const k of ['passed', 'failed'] as const) {
401
+ 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` })
402
+ }
403
+ const note = t.note === undefined ? undefined : str(t.note)
404
+ if (note !== undefined && note.length > REVIEW_NOTE_MAX_CHARS) errors.push({ field: `${at}.note`, message: `note is over ${REVIEW_NOTE_MAX_CHARS} chars` })
405
+ if (command && typeof t.exit === 'number') {
406
+ out.push({
407
+ command, exit: t.exit,
408
+ ...(typeof t.passed === 'number' ? { passed: t.passed } : {}),
409
+ ...(typeof t.failed === 'number' ? { failed: t.failed } : {}),
410
+ ...(note ? { note } : {}),
411
+ })
412
+ }
413
+ })
414
+ return out
415
+ }
416
+
417
+ /** Validate an implementer's `findingResponses` (§5.3). */
418
+ export function validateFindingResponses(raw: unknown, field = 'findingResponses'): { responses?: MeshFindingResponse[]; errors: StageValidationError[] } {
419
+ const errors: StageValidationError[] = []
420
+ if (!Array.isArray(raw)) return { errors: [{ field, message: `${field} must be an array of {id, response, note}` }] }
421
+ if (raw.length > FINDING_RESPONSES_MAX) errors.push({ field, message: `${field} has ${raw.length} entries, over the ${FINDING_RESPONSES_MAX} limit` })
422
+ const out: MeshFindingResponse[] = []
423
+ raw.forEach((r, i) => {
424
+ const at = `${field}[${i}]`
425
+ if (!isRecord(r)) { errors.push({ field: at, message: 'each entry must be an object {id, response, note}' }); return }
426
+ for (const key of Object.keys(r)) if (!['id', 'response', 'note'].includes(key)) errors.push({ field: `${at}.${key}`, message: `unknown field '${key}'` })
427
+ const id = str(r.id)
428
+ if (!id) errors.push({ field: `${at}.id`, message: 'id is required' })
429
+ if (!isFindingResponseKind(r.response)) errors.push({ field: `${at}.response`, message: `response must be one of ${FINDING_RESPONSE_KINDS.join(' | ')}` })
430
+ const note = str(r.note)
431
+ if (!note) errors.push({ field: `${at}.note`, message: 'note is required — say what changed, or why you dispute it' })
432
+ else if (note.length > REVIEW_NOTE_MAX_CHARS) errors.push({ field: `${at}.note`, message: `note is over ${REVIEW_NOTE_MAX_CHARS} chars` })
433
+ if (id && isFindingResponseKind(r.response) && note && note.length <= REVIEW_NOTE_MAX_CHARS) out.push({ id, response: r.response, note })
434
+ })
435
+ return errors.length ? { errors } : { responses: out, errors: [] }
436
+ }
437
+
438
+ // ─── Verdict line (§5.4) ────────────────────────────────────────────────
439
+
440
+ export interface StageVerdictLineInput {
441
+ verdict: MeshReviewVerdict | 'skipped_no_diff'
442
+ rounds: number
443
+ reviewerProvider?: string
444
+ independenceUsed?: MeshStageIndependenceUsed
445
+ fixed?: number
446
+ openNits?: number
447
+ }
448
+
449
+ /** One human-readable line: `review: approve_with_nits · 2 rounds · reviewer codex-cli (different_provider) · 3 findings fixed, 1 nit open`. */
450
+ export function formatStageVerdictLine(input: StageVerdictLineInput): string {
451
+ const parts: string[] = [`review: ${input.verdict}`]
452
+ if (input.verdict === 'skipped_no_diff') return parts[0]
453
+ parts.push(`${input.rounds} round${input.rounds === 1 ? '' : 's'}`)
454
+ if (input.reviewerProvider) parts.push(`reviewer ${input.reviewerProvider} (${input.independenceUsed ?? 'different_provider'})`)
455
+ const tail: string[] = []
456
+ if (input.fixed) tail.push(`${input.fixed} finding${input.fixed === 1 ? '' : 's'} fixed`)
457
+ if (input.openNits) tail.push(`${input.openNits} nit${input.openNits === 1 ? '' : 's'} open`)
458
+ return tail.length ? `${parts.join(' · ')} · ${tail.join(', ')}` : parts.join(' · ')
459
+ }
@@ -56,7 +56,11 @@ export type DeliveryOutcome = typeof DELIVERY_OUTCOMES[number]
56
56
  export const DELIVERY_VIAS = ['local', 'p2p'] as const
57
57
  export type DeliveryVia = typeof DELIVERY_VIAS[number]
58
58
 
59
- export const DISPATCH_FAILURE_REASONS = ['worker_absent', 'transport_error', 'spawn_failed', 'rejected_by_worker', 'timeout'] as const
59
+ /** `submit_unconfirmed` (SUBMIT-UNCONFIRMED-RECLAIM): the worker's CLI never
60
+ * took the written prompt — the submit budget and one re-paste were spent at
61
+ * an idle composer. An owner daemon older than this value drops the evidence
62
+ * as invalid and falls back to its consume/turn holds (the pre-fix path). */
63
+ export const DISPATCH_FAILURE_REASONS = ['worker_absent', 'transport_error', 'spawn_failed', 'rejected_by_worker', 'timeout', 'submit_unconfirmed'] as const
60
64
  export type DispatchFailureReason = typeof DISPATCH_FAILURE_REASONS[number]
61
65
 
62
66
  /**
@@ -75,6 +79,33 @@ export function sanitizeRefusalCode(value: unknown): string | undefined {
75
79
  return normalized.slice(0, 64)
76
80
  }
77
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
+
78
109
  export const CONSUME_PROFILES = ['default', 'native_source'] as const
79
110
  export type ConsumeProfile = typeof CONSUME_PROFILES[number]
80
111
 
@@ -150,11 +181,14 @@ export const HOLD_REASONS = [
150
181
  // — a turn_end commits the report (R9t), expiry commits it anyway (R13t) so
151
182
  // a session whose FSM never shows the idle edge again does not wait for
152
183
  // liveness / hard_ceiling.
153
- 'await_end',
184
+ 'await_end', 'report_correction',
185
+ // A generating mesh attempt with no output/activity for `stallReclaimMs`: expiry reclaims it
186
+ // (`stalled_no_output`) instead of waiting for the hard ceiling. Re-armed by every output.
187
+ 'stall_ceiling',
154
188
  ] as const
155
189
  export type HoldReason = typeof HOLD_REASONS[number]
156
190
 
157
- export const TURN_OUTCOMES = ['completed', 'failed', 'cancelled'] as const
191
+ export const TURN_OUTCOMES = ['completed', 'blocked', 'failed', 'cancelled'] as const
158
192
  export type TurnOutcome = typeof TURN_OUTCOMES[number]
159
193
 
160
194
  export const COMMIT_STRENGTHS = ['genuine', 'weak', 'tool_report', 'operator'] as const
@@ -164,14 +198,18 @@ export type CommitStrength = typeof COMMIT_STRENGTHS[number]
164
198
  export const TURN_REASONS = [
165
199
  // commits
166
200
  'turn_end', 'weak_end_confirmed', 'transcript_final', 'worker_reported',
167
- 'finalization_timeout_no_response', 'session_error', 'provider_auth_failed', 'provider_billing_failed', 'provider_usage_limit_exceeded', 'provider_server_overloaded', 'provider_error',
201
+ 'finalization_timeout_no_response', 'weak_end_liveness_unconfirmed', 'weak_end_probe_unobserved', 'report_correction_expired', 'report_missing_timeout', 'session_error', 'provider_auth_failed', 'provider_billing_failed', 'provider_usage_limit_exceeded', 'provider_server_overloaded', 'provider_error',
168
202
  'operator_cancel', 'intentional_cleanup', 'task_removed', 'mission_abandoned', 'superseded',
169
203
  'operator_update', 'refine_terminal', 'validation_terminal',
170
204
  'hard_ceiling', 'reclaim_budget_exhausted', 'hollow_max_retries', 'migration_orphan',
205
+ // a stopping attempt whose writer node stayed unreachable (or was removed) past the bound
206
+ 'writer_unreachable',
171
207
  // reclaims (generation + 1)
172
208
  'dispatch_refused_session_exited', 'dispatch_refused_no_target', 'dispatch_refused_unsupported_input', 'dispatch_failed',
173
209
  'session_exit', 'session_exit_before_turn', 'session_dead', 'hollow_completion',
174
210
  'assigned_stranded_dispatch_unconfirmed', 'delivered_not_consumed_redrive', 'delivered_no_turn_deadline',
211
+ // a generating worker produced no output/activity for the stall reclaim bound
212
+ 'stalled_no_output',
175
213
  ] as const
176
214
  export type TurnReason = typeof TURN_REASONS[number]
177
215
 
@@ -186,7 +224,7 @@ export type TurnReason = typeof TURN_REASONS[number]
186
224
  * owner's local `turn_events.payload_json` and is rendered at deliver time.
187
225
  */
188
226
  export const NOTIFY_KINDS = [
189
- 'completed', 'failed', 'cancelled', 'stopped', 'approval', 'choice', 'approval_resolved',
227
+ 'completed', 'blocked', 'failed', 'cancelled', 'stopped', 'approval', 'choice', 'approval_resolved',
190
228
  'candidate', 'no_progress', 'progress', 'late_completion', 'mesh_event',
191
229
  ] as const
192
230
  export type NotifyKind = typeof NOTIFY_KINDS[number]
@@ -273,7 +311,7 @@ export type TurnEvidenceBody =
273
311
  live: LiveTurnPending; summary?: SummaryRef; messageAt?: number }
274
312
  | { kind: 'transcript_activity'; newestActivityAt: number }
275
313
  | { kind: 'no_progress'; stalledMs: number; observedStatus: NoProgressObservedStatus; finalAssistantPresent: boolean }
276
- | { kind: 'liveness'; result: LivenessResult }
314
+ | { kind: 'liveness'; result: LivenessResult; probeStartedAtMs?: number }
277
315
  | { kind: 'process_exit'; exitCode: number | null; providerFailure?: ProviderFailure }
278
316
  | { kind: 'session_error'; reason: SessionErrorReason }
279
317
  // ── worker MCP (F2) ──
@@ -284,6 +322,7 @@ export type TurnEvidenceBody =
284
322
  */
285
323
  | { kind: 'worker_report'; outcome: WorkerReportOutcome; summary?: SummaryRef; hasHandoffNotes: boolean
286
324
  branchState?: WorkerBranchState; touchedFileCount?: number }
325
+ | { kind: 'worker_report_correction_requested'; deliveryId?: string }
287
326
  | { kind: 'worker_progress'; note?: SummaryRef }
288
327
  // ── coordinator / operator ──
289
328
  | { kind: 'git_side_effect'; dirty: boolean; commitsSinceDispatch: number; attributable: boolean }
@@ -366,13 +405,14 @@ export const TURN_EVIDENCE_FIELD_SPECS: TurnEvidenceFieldSpecs = {
366
405
  },
367
406
  transcript_activity: { newestActivityAt: ms },
368
407
  no_progress: { stalledMs: ms, observedStatus: en(NO_PROGRESS_OBSERVED_STATUSES), finalAssistantPresent: bool },
369
- liveness: { result: en(LIVENESS_RESULTS) },
408
+ liveness: { result: en(LIVENESS_RESULTS), probeStartedAtMs: msOpt },
370
409
  process_exit: { exitCode: { t: 'int', nullable: true }, providerFailure: enOpt(PROVIDER_FAILURES) },
371
410
  session_error: { reason: en(SESSION_ERROR_REASONS) },
372
411
  worker_report: {
373
412
  outcome: en(WORKER_REPORT_OUTCOMES), summary: { t: 'summary_ref', optional: true }, hasHandoffNotes: bool,
374
413
  branchState: enOpt(WORKER_BRANCH_STATES), touchedFileCount: intOpt,
375
414
  },
415
+ worker_report_correction_requested: { deliveryId: { t: 'id', optional: true } },
376
416
  worker_progress: { note: { t: 'summary_ref', optional: true } },
377
417
  git_side_effect: { dirty: bool, commitsSinceDispatch: { t: 'int' }, attributable: bool },
378
418
  cancel: { reason: en(CANCEL_REASONS) },