@adhdev/mesh-shared 1.0.82-rc.8 → 1.0.82-rc.81

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 (69) hide show
  1. package/dist/assistant-protocol.d.ts +163 -6
  2. package/dist/decision-push-relay.d.ts +20 -0
  3. package/dist/index.d.ts +12 -0
  4. package/dist/index.js +1637 -124
  5. package/dist/index.js.map +1 -1
  6. package/dist/index.mjs +1499 -124
  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 +61 -1
  15. package/dist/outbound-message.d.ts +9 -2
  16. package/dist/path-ownership.d.ts +1 -1
  17. package/dist/protocol/daemon-server.d.ts +42 -2
  18. package/dist/protocol/dashboard-daemon-p2p.d.ts +1 -1
  19. package/dist/protocol/dashboard-server.d.ts +20 -2
  20. package/dist/provider-approval.d.ts +36 -0
  21. package/dist/provider-question.d.ts +19 -0
  22. package/dist/quota-freshness.d.ts +4 -4
  23. package/dist/relay-reprobe.d.ts +52 -0
  24. package/dist/release.d.ts +90 -0
  25. package/dist/role-launch.d.ts +11 -0
  26. package/dist/session-launch.d.ts +10 -22
  27. package/dist/slot-proposal.d.ts +14 -0
  28. package/dist/task-source-phase.d.ts +83 -0
  29. package/dist/task-stages.d.ts +208 -0
  30. package/dist/turn-evidence.d.ts +43 -13
  31. package/dist/turn-ipc-mission.d.ts +72 -1
  32. package/dist/turn-ipc-queue.d.ts +30 -0
  33. package/dist/turn-ipc.d.ts +2 -2
  34. package/dist/types.d.ts +1 -0
  35. package/dist/worker-protocol.d.ts +33 -1
  36. package/package.json +1 -1
  37. package/src/assistant-protocol.ts +306 -6
  38. package/src/daemon-normalize.ts +7 -5
  39. package/src/decision-push-relay.ts +23 -0
  40. package/src/index.ts +13 -0
  41. package/src/keyed-doc-delta.ts +9 -1
  42. package/src/launch-defaults.ts +170 -0
  43. package/src/light-task.ts +116 -0
  44. package/src/mesh-tool-names.ts +22 -0
  45. package/src/mesh-vocabulary.ts +12 -2
  46. package/src/mission-git-state.ts +112 -0
  47. package/src/mission-items.ts +421 -0
  48. package/src/node-facts.ts +56 -1
  49. package/src/outbound-message.ts +19 -0
  50. package/src/path-ownership.ts +4 -6
  51. package/src/protocol/daemon-server.ts +37 -2
  52. package/src/protocol/dashboard-server.ts +13 -2
  53. package/src/provider-approval.ts +59 -0
  54. package/src/provider-question.ts +31 -0
  55. package/src/quota-freshness.ts +29 -13
  56. package/src/relay-reprobe.ts +117 -0
  57. package/src/release.ts +121 -0
  58. package/src/role-launch.ts +51 -0
  59. package/src/session-launch.ts +17 -1
  60. package/src/slot-proposal.ts +61 -2
  61. package/src/task-source-phase.ts +70 -0
  62. package/src/task-stages.ts +457 -0
  63. package/src/turn-evidence.ts +56 -20
  64. package/src/turn-ipc-mission.ts +127 -11
  65. package/src/turn-ipc-queue.ts +43 -2
  66. package/src/turn-ipc-turn.ts +1 -1
  67. package/src/turn-ipc.ts +1 -0
  68. package/src/types.ts +1 -0
  69. package/src/worker-protocol.ts +79 -0
@@ -0,0 +1,70 @@
1
+ import type { OwnedPathEntry } from './path-ownership'
2
+
3
+ export type MeshTaskPhase = 'source' | 'integration'
4
+
5
+ /** Host-produced evidence. Never accepted from MCP/peer-supplied paths or branch labels. */
6
+ export interface PhysicalOwnershipScope {
7
+ version: 1
8
+ repoIdentity: string
9
+ machineId: string
10
+ nodeId: string
11
+ worktree: string
12
+ worktreeIdentity: string
13
+ gitDir: string
14
+ commonGitDir: string
15
+ phase: MeshTaskPhase
16
+ gitResources: { index: string; refs: string; hooks: string; config: string }
17
+ resources: Array<{ path: string; identity?: string; subtree: boolean }>
18
+ declaration: readonly OwnedPathEntry[]
19
+ }
20
+
21
+ /** A source packet is an input to integration, never release/feature acceptance. */
22
+ export interface MeshSourceCandidate {
23
+ version: 1
24
+ readiness: 'uncommitted' | 'verified_source_candidate'
25
+ taskId: string
26
+ missionId: string
27
+ revision: number
28
+ repoIdentity: string
29
+ machineId: string
30
+ canonicalWorktree: string
31
+ rootBaseSha: string
32
+ ossBaseSha: string
33
+ rootCandidateSha?: string
34
+ ossCandidateSha?: string
35
+ patchSha256: string
36
+ manifestSha256: string
37
+ touchedPaths: string[]
38
+ tests: Array<{ command: string; exit: number; logSha256: string }>
39
+ settledCommands: boolean
40
+ integrationTaskId: string
41
+ logicalOverlapTaskIds: string[]
42
+ }
43
+
44
+ /** Product B consumes one frozen batch; normal hooks/parity/gates remain required. */
45
+ export interface MeshIntegrationBatchContract {
46
+ version: 1
47
+ batchId: string
48
+ candidates: MeshSourceCandidate[]
49
+ integrationOrder: string[]
50
+ approvedRootSha: string
51
+ approvedOssSha: string
52
+ bundleInvocationCount: 1
53
+ requiredGates: string[]
54
+ normalHooksRequired: true
55
+ independentReviewRequired: true
56
+ ownerLandingApprovalRequired: true
57
+ }
58
+
59
+ /** These only rank legal targets; targetNodeId/SessionId and requiredTags remain hard. */
60
+ export interface MeshRoutingPreferences { nodeIds?: string[]; providers?: string[] }
61
+ export type MeshReviewIndependence = 'different_provider' | 'fresh_session'
62
+ /**
63
+ * Review row constraint. `differentProvider: true` is the legacy spelling of
64
+ * `independence: 'different_provider'`; `independence: 'fresh_session'` is the stage pipeline's
65
+ * fallback (same provider allowed, but never the implementer's session).
66
+ */
67
+ export interface MeshReviewConstraint { sourceTaskId: string; differentProvider?: true; independence?: MeshReviewIndependence }
68
+ export function reviewIndependenceOf(review: Pick<MeshReviewConstraint, 'differentProvider' | 'independence'>): MeshReviewIndependence {
69
+ return review.independence ?? 'different_provider'
70
+ }
@@ -0,0 +1,457 @@
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 → 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).
203
+ * Throws `invalid_review_option: …` on malformed input (rejected, never coerced).
204
+ */
205
+ export function resolveStagePlan(raw: unknown, task: StagePlanDefaultsInput, opts: { defaultOn?: boolean } = {}): MeshTaskStagePlan | null {
206
+ const eligible = isStageEligibleTask(task)
207
+ if (raw === undefined || raw === null) return (opts.defaultOn ?? true) && defaultsOnFor(task) ? defaultStagePlan() : null
208
+ if (raw === false) return null
209
+ if (raw === true) {
210
+ if (!eligible) throw new Error(`invalid_review_option: review requires a non-readonly code_change task (got taskMode=${task.taskMode ?? 'unset'}${task.readonly ? ', readonly' : ''})`)
211
+ return defaultStagePlan()
212
+ }
213
+ if (!isRecord(raw)) throw new Error('invalid_review_option: review must be true, false or {max_revisions?, independence?}')
214
+ const allowed = new Set(['max_revisions', 'maxRevisions', 'independence'])
215
+ for (const key of Object.keys(raw)) {
216
+ if (!allowed.has(key)) throw new Error(`invalid_review_option: unknown review key '${key}' (expected max_revisions, independence)`)
217
+ }
218
+ if (!eligible) throw new Error(`invalid_review_option: review requires a non-readonly code_change task (got taskMode=${task.taskMode ?? 'unset'}${task.readonly ? ', readonly' : ''})`)
219
+ const rawMax = raw.max_revisions ?? raw.maxRevisions
220
+ let maxRevisions = STAGE_DEFAULT_MAX_REVISIONS as MeshTaskStagePlan['maxRevisions']
221
+ if (rawMax !== undefined) {
222
+ if (typeof rawMax !== 'number' || !Number.isInteger(rawMax) || rawMax < 0 || rawMax > STAGE_MAX_REVISIONS_LIMIT) {
223
+ throw new Error(`invalid_review_option: max_revisions must be an integer 0..${STAGE_MAX_REVISIONS_LIMIT}`)
224
+ }
225
+ maxRevisions = rawMax as MeshTaskStagePlan['maxRevisions']
226
+ }
227
+ let independence: MeshStageIndependenceMode = 'fresh_session_ok'
228
+ if (raw.independence !== undefined) {
229
+ if (!(STAGE_INDEPENDENCE_MODES as readonly string[]).includes(raw.independence as string)) {
230
+ throw new Error(`invalid_review_option: independence must be one of ${STAGE_INDEPENDENCE_MODES.join(' | ')}`)
231
+ }
232
+ independence = raw.independence as MeshStageIndependenceMode
233
+ }
234
+ return { review: true, maxRevisions, independence }
235
+ }
236
+
237
+ export function defaultStagePlan(): MeshTaskStagePlan {
238
+ return { review: true, maxRevisions: STAGE_DEFAULT_MAX_REVISIONS as MeshTaskStagePlan['maxRevisions'], independence: 'fresh_session_ok' }
239
+ }
240
+
241
+ /** R5: only non-readonly code_change tasks run the pipeline by default (medium/difficult). */
242
+ export function isStageEligibleTask(task: StagePlanDefaultsInput): boolean {
243
+ if (task.readonly) return false
244
+ return (task.taskMode ?? 'code_change') === 'code_change'
245
+ }
246
+
247
+ function defaultsOnFor(task: StagePlanDefaultsInput): boolean {
248
+ return isStageEligibleTask(task) && (task.difficulty === 'medium' || task.difficulty === 'difficult')
249
+ }
250
+
251
+ // ─── Review report validation (§5.2) ────────────────────────────────────
252
+
253
+ function str(value: unknown): string { return typeof value === 'string' ? value.trim() : '' }
254
+
255
+ function validateStringList(value: unknown, field: string, max: number, maxChars: number, errors: StageValidationError[], minItems = 0): string[] {
256
+ if (!Array.isArray(value)) {
257
+ errors.push({ field, message: `${field} must be an array of strings` })
258
+ return []
259
+ }
260
+ if (value.length > max) errors.push({ field, message: `${field} has ${value.length} entries, over the ${max} limit` })
261
+ const out: string[] = []
262
+ for (const item of value) {
263
+ const text = str(item)
264
+ if (!text) continue
265
+ if (text.length > maxChars) { errors.push({ field, message: `${field} contains an entry over ${maxChars} chars` }); continue }
266
+ out.push(text)
267
+ }
268
+ 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` })
269
+ return out
270
+ }
271
+
272
+ export interface ReviewValidationContext {
273
+ /** 1-based review round of the child this report is for. */
274
+ round: number
275
+ /** Blocking/major finding ids still open from the previous round (round ≥ 2 must answer each). */
276
+ priorOpenBlockingIds?: readonly string[]
277
+ }
278
+
279
+ /**
280
+ * Validate the `review` field of a reviewer's `report_completion`. Rejects, never coerces;
281
+ * unknown keys are rejected (a misspelled `notChecked` must not silently vanish).
282
+ */
283
+ export function validateReviewReport(raw: unknown, ctx: ReviewValidationContext): { report?: MeshReviewReport; errors: StageValidationError[] } {
284
+ const errors: StageValidationError[] = []
285
+ if (!isRecord(raw)) return { errors: [{ field: 'review', message: 'review must be an object {verdict, findings, checked, notChecked, ...}' }] }
286
+ const KNOWN = new Set(['verdict', 'findings', 'priorFindings', 'checked', 'notChecked', 'testsRun'])
287
+ 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(', ')})` })
288
+
289
+ const verdict = raw.verdict
290
+ if (!isReviewVerdict(verdict)) errors.push({ field: 'review.verdict', message: `verdict must be one of ${REVIEW_VERDICTS.join(' | ')}` })
291
+
292
+ const findings: MeshReviewFinding[] = []
293
+ if (!Array.isArray(raw.findings)) errors.push({ field: 'review.findings', message: 'findings must be an array (use [] when there are none)' })
294
+ else {
295
+ 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` })
296
+ const seen = new Set<string>()
297
+ raw.findings.forEach((f, i) => {
298
+ const at = `review.findings[${i}]`
299
+ if (!isRecord(f)) { errors.push({ field: at, message: 'each finding must be an object' }); return }
300
+ const FK = new Set(['id', 'severity', 'category', 'file', 'line', 'claim', 'evidence', 'suggestedFix'])
301
+ for (const key of Object.keys(f)) if (!FK.has(key)) errors.push({ field: `${at}.${key}`, message: `unknown field '${key}'` })
302
+ const id = str(f.id)
303
+ if (!id || id.length > REVIEW_FINDING_ID_MAX_CHARS) errors.push({ field: `${at}.id`, message: `id is required (≤ ${REVIEW_FINDING_ID_MAX_CHARS} chars)` })
304
+ else if (seen.has(id)) errors.push({ field: `${at}.id`, message: `duplicate finding id '${id}'` })
305
+ else seen.add(id)
306
+ if (!isFindingSeverity(f.severity)) errors.push({ field: `${at}.severity`, message: `severity must be one of ${FINDING_SEVERITIES.join(' | ')}` })
307
+ if (!isFindingCategory(f.category)) errors.push({ field: `${at}.category`, message: `category must be one of ${FINDING_CATEGORIES.join(' | ')}` })
308
+ const claim = str(f.claim)
309
+ if (!claim) errors.push({ field: `${at}.claim`, message: 'claim is required' })
310
+ else if (claim.length > REVIEW_CLAIM_MAX_CHARS) errors.push({ field: `${at}.claim`, message: `claim is over ${REVIEW_CLAIM_MAX_CHARS} chars` })
311
+ const evidence = str(f.evidence)
312
+ if (!evidence) errors.push({ field: `${at}.evidence`, message: 'evidence is required — what did you read or run to know this' })
313
+ else if (evidence.length > REVIEW_EVIDENCE_MAX_CHARS) errors.push({ field: `${at}.evidence`, message: `evidence is over ${REVIEW_EVIDENCE_MAX_CHARS} chars` })
314
+ const fix = f.suggestedFix === undefined ? undefined : str(f.suggestedFix)
315
+ if (fix !== undefined && fix.length > REVIEW_FIX_MAX_CHARS) errors.push({ field: `${at}.suggestedFix`, message: `suggestedFix is over ${REVIEW_FIX_MAX_CHARS} chars` })
316
+ if (f.file !== undefined && typeof f.file !== 'string') errors.push({ field: `${at}.file`, message: 'file must be a string' })
317
+ 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' })
318
+ if (id && isFindingSeverity(f.severity) && isFindingCategory(f.category) && claim && evidence) {
319
+ findings.push({
320
+ id, severity: f.severity, category: f.category,
321
+ ...(typeof f.file === 'string' && f.file.trim() ? { file: f.file.trim() } : {}),
322
+ ...(typeof f.line === 'number' ? { line: f.line } : {}),
323
+ claim, evidence, ...(fix ? { suggestedFix: fix } : {}),
324
+ })
325
+ }
326
+ })
327
+ }
328
+
329
+ const checked = validateStringList(raw.checked, 'review.checked', REVIEW_CHECKED_MAX, REVIEW_CLAIM_MAX_CHARS, errors, 1)
330
+ const notChecked = validateStringList(raw.notChecked, 'review.notChecked', REVIEW_CHECKED_MAX, REVIEW_CLAIM_MAX_CHARS, errors, 1)
331
+
332
+ let priorFindings: MeshPriorFindingStatusEntry[] | undefined
333
+ if (raw.priorFindings !== undefined) {
334
+ if (!Array.isArray(raw.priorFindings)) errors.push({ field: 'review.priorFindings', message: 'priorFindings must be an array' })
335
+ else {
336
+ priorFindings = []
337
+ raw.priorFindings.forEach((p, i) => {
338
+ const at = `review.priorFindings[${i}]`
339
+ if (!isRecord(p)) { errors.push({ field: at, message: 'each entry must be an object {id, status, note?}' }); return }
340
+ for (const key of Object.keys(p)) if (!['id', 'status', 'note'].includes(key)) errors.push({ field: `${at}.${key}`, message: `unknown field '${key}'` })
341
+ const id = str(p.id)
342
+ if (!id) errors.push({ field: `${at}.id`, message: 'id is required' })
343
+ if (!isPriorFindingStatus(p.status)) errors.push({ field: `${at}.status`, message: `status must be one of ${PRIOR_FINDING_STATUSES.join(' | ')}` })
344
+ const note = p.note === undefined ? undefined : str(p.note)
345
+ if (note !== undefined && note.length > REVIEW_NOTE_MAX_CHARS) errors.push({ field: `${at}.note`, message: `note is over ${REVIEW_NOTE_MAX_CHARS} chars` })
346
+ if (id && isPriorFindingStatus(p.status)) priorFindings!.push({ id, status: p.status, ...(note ? { note } : {}) })
347
+ })
348
+ }
349
+ }
350
+
351
+ const testsRun = raw.testsRun === undefined ? undefined : validateTestsRun(raw.testsRun, 'review.testsRun', errors)
352
+
353
+ // Cross-field rules.
354
+ if (isReviewVerdict(verdict)) {
355
+ const blocking = findings.filter(f => isBlockingSeverity(f.severity))
356
+ if (verdict === 'changes_requested' && blocking.length === 0 && Array.isArray(raw.findings) && errors.length === 0) {
357
+ errors.push({ field: 'review.verdict', message: 'changes_requested needs at least one blocking or major finding — nits alone are approve_with_nits' })
358
+ }
359
+ if ((verdict === 'approve') && blocking.length > 0) {
360
+ errors.push({ field: 'review.verdict', message: 'approve cannot carry blocking or major findings' })
361
+ }
362
+ if (verdict === 'approve_with_nits' && blocking.length > 0) {
363
+ errors.push({ field: 'review.verdict', message: 'approve_with_nits cannot carry blocking or major findings — use changes_requested' })
364
+ }
365
+ }
366
+ if (ctx.round >= 2 && ctx.priorOpenBlockingIds?.length) {
367
+ const answered = new Set((priorFindings ?? []).map(p => p.id))
368
+ const missing = ctx.priorOpenBlockingIds.filter(id => !answered.has(id))
369
+ 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(', ')}` })
370
+ }
371
+
372
+ if (errors.length) return { errors }
373
+ return {
374
+ report: {
375
+ verdict: verdict as MeshReviewVerdict,
376
+ findings,
377
+ ...(priorFindings?.length ? { priorFindings } : {}),
378
+ checked,
379
+ notChecked,
380
+ ...(testsRun?.length ? { testsRun } : {}),
381
+ },
382
+ errors: [],
383
+ }
384
+ }
385
+
386
+ /** Shared by the reviewer's `review.testsRun` and the top-level `testsRun` of any report. */
387
+ export function validateTestsRun(raw: unknown, field: string, errors: StageValidationError[]): MeshTestRun[] {
388
+ if (!Array.isArray(raw)) { errors.push({ field, message: `${field} must be an array of {command, exit, passed?, failed?, note?}` }); return [] }
389
+ if (raw.length > REVIEW_TESTS_RUN_MAX) errors.push({ field, message: `${field} has ${raw.length} entries, over the ${REVIEW_TESTS_RUN_MAX} limit` })
390
+ const out: MeshTestRun[] = []
391
+ raw.forEach((t, i) => {
392
+ const at = `${field}[${i}]`
393
+ if (!isRecord(t)) { errors.push({ field: at, message: 'each entry must be an object' }); return }
394
+ for (const key of Object.keys(t)) if (!['command', 'exit', 'passed', 'failed', 'note'].includes(key)) errors.push({ field: `${at}.${key}`, message: `unknown field '${key}'` })
395
+ const command = str(t.command)
396
+ if (!command || command.length > REVIEW_CLAIM_MAX_CHARS) errors.push({ field: `${at}.command`, message: `command is required (≤ ${REVIEW_CLAIM_MAX_CHARS} chars)` })
397
+ if (typeof t.exit !== 'number' || !Number.isInteger(t.exit)) errors.push({ field: `${at}.exit`, message: 'exit must be an integer' })
398
+ for (const k of ['passed', 'failed'] as const) {
399
+ 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` })
400
+ }
401
+ const note = t.note === undefined ? undefined : str(t.note)
402
+ if (note !== undefined && note.length > REVIEW_NOTE_MAX_CHARS) errors.push({ field: `${at}.note`, message: `note is over ${REVIEW_NOTE_MAX_CHARS} chars` })
403
+ if (command && typeof t.exit === 'number') {
404
+ out.push({
405
+ command, exit: t.exit,
406
+ ...(typeof t.passed === 'number' ? { passed: t.passed } : {}),
407
+ ...(typeof t.failed === 'number' ? { failed: t.failed } : {}),
408
+ ...(note ? { note } : {}),
409
+ })
410
+ }
411
+ })
412
+ return out
413
+ }
414
+
415
+ /** Validate an implementer's `findingResponses` (§5.3). */
416
+ export function validateFindingResponses(raw: unknown, field = 'findingResponses'): { responses?: MeshFindingResponse[]; errors: StageValidationError[] } {
417
+ const errors: StageValidationError[] = []
418
+ if (!Array.isArray(raw)) return { errors: [{ field, message: `${field} must be an array of {id, response, note}` }] }
419
+ if (raw.length > FINDING_RESPONSES_MAX) errors.push({ field, message: `${field} has ${raw.length} entries, over the ${FINDING_RESPONSES_MAX} limit` })
420
+ const out: MeshFindingResponse[] = []
421
+ raw.forEach((r, i) => {
422
+ const at = `${field}[${i}]`
423
+ if (!isRecord(r)) { errors.push({ field: at, message: 'each entry must be an object {id, response, note}' }); return }
424
+ for (const key of Object.keys(r)) if (!['id', 'response', 'note'].includes(key)) errors.push({ field: `${at}.${key}`, message: `unknown field '${key}'` })
425
+ const id = str(r.id)
426
+ if (!id) errors.push({ field: `${at}.id`, message: 'id is required' })
427
+ if (!isFindingResponseKind(r.response)) errors.push({ field: `${at}.response`, message: `response must be one of ${FINDING_RESPONSE_KINDS.join(' | ')}` })
428
+ const note = str(r.note)
429
+ if (!note) errors.push({ field: `${at}.note`, message: 'note is required — say what changed, or why you dispute it' })
430
+ else if (note.length > REVIEW_NOTE_MAX_CHARS) errors.push({ field: `${at}.note`, message: `note is over ${REVIEW_NOTE_MAX_CHARS} chars` })
431
+ if (id && isFindingResponseKind(r.response) && note && note.length <= REVIEW_NOTE_MAX_CHARS) out.push({ id, response: r.response, note })
432
+ })
433
+ return errors.length ? { errors } : { responses: out, errors: [] }
434
+ }
435
+
436
+ // ─── Verdict line (§5.4) ────────────────────────────────────────────────
437
+
438
+ export interface StageVerdictLineInput {
439
+ verdict: MeshReviewVerdict | 'skipped_no_diff'
440
+ rounds: number
441
+ reviewerProvider?: string
442
+ independenceUsed?: MeshStageIndependenceUsed
443
+ fixed?: number
444
+ openNits?: number
445
+ }
446
+
447
+ /** One human-readable line: `review: approve_with_nits · 2 rounds · reviewer codex-cli (different_provider) · 3 findings fixed, 1 nit open`. */
448
+ export function formatStageVerdictLine(input: StageVerdictLineInput): string {
449
+ const parts: string[] = [`review: ${input.verdict}`]
450
+ if (input.verdict === 'skipped_no_diff') return parts[0]
451
+ parts.push(`${input.rounds} round${input.rounds === 1 ? '' : 's'}`)
452
+ if (input.reviewerProvider) parts.push(`reviewer ${input.reviewerProvider} (${input.independenceUsed ?? 'different_provider'})`)
453
+ const tail: string[] = []
454
+ if (input.fixed) tail.push(`${input.fixed} finding${input.fixed === 1 ? '' : 's'} fixed`)
455
+ if (input.openNits) tail.push(`${input.openNits} nit${input.openNits === 1 ? '' : 's'} open`)
456
+ return tail.length ? `${parts.join(' · ')} · ${tail.join(', ')}` : parts.join(' · ')
457
+ }