1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//! Errors from loading, resolving, reviewing, indexing, or locking a
//! research-harness-template (rht) corpus.
use mif_problem::{
Applicability, CodeAction, ProblemDetails, ProblemMeta, SuggestedFix, ToProblem,
};
/// Errors from `mif-rh`'s engine core.
///
/// Variants split into two classes: those that produce a
/// [`crate::resolve::MapRecord`] anyway (a finding that classifies as
/// invalid/ambiguous/unresolved is still recorded, per rht's own
/// `resolve-ontology.sh` — see [`crate::resolve::resolve_finding`]) and
/// those below, which mean no record could be produced at all (the file
/// itself is unreadable, the catalog is missing, or an ontology definition
/// is broken). [`crate::review::review`] folds the latter into its
/// reconciliation "gap" count rather than aborting the whole review.
#[derive(Debug, thiserror::Error)]
pub enum MifRhError {
/// Failed to read a finding file.
#[error("failed to read finding {path}: {source}")]
FindingIo {
/// The path that failed to read.
path: String,
/// The underlying I/O error.
#[source]
source: std::io::Error,
},
/// A finding file was not valid JSON.
#[error("finding {path} is not valid JSON: {source}")]
FindingJson {
/// The path that failed to parse.
path: String,
/// The underlying parse error.
#[source]
source: serde_json::Error,
},
/// A generic I/O failure reading a supporting file (ontology directory,
/// map file, `harness.config.json`).
#[error("failed to read {path}: {source}")]
Io {
/// The path that failed to read.
path: String,
/// The underlying I/O error.
#[source]
source: std::io::Error,
},
/// A supporting file was not valid JSON.
#[error("failed to parse {path} as JSON: {source}")]
Json {
/// The path that failed to parse.
path: String,
/// The underlying parse error.
#[source]
source: serde_json::Error,
},
/// A value could not be serialized to JSON for an atomic write. This
/// indicates a bug in the value's `Serialize` implementation (e.g. a
/// non-finite float) rather than anything a caller can fix by changing
/// its input.
#[error("failed to serialize {path} as JSON: {source}")]
JsonSerialize {
/// The path the value was being written to.
path: String,
/// The underlying serialization error.
#[source]
source: serde_json::Error,
},
/// An ontology pack YAML file failed to parse (the direct equivalent of
/// `yq` failing to read an ontology's `extends`/`entity_types`/full
/// YAML — a fail-closed abort, matching rht's own bash exit code 4).
#[error("failed to parse ontology pack {path} as YAML: {source}")]
OntologyPackYaml {
/// The path that failed to parse.
path: String,
/// The underlying parse error.
#[source]
source: serde_norway::Error,
},
/// The catalog file (`.claude/enabled-packs.json`) is missing.
#[error("catalog file {path} does not exist")]
CatalogMissing {
/// The missing catalog path.
path: String,
},
/// The config file (`harness.config.json`) is missing.
#[error("config file {path} does not exist")]
ConfigMissing {
/// The missing config path.
path: String,
},
/// A topic directly binds an ontology id that is not cataloged, or pins
/// a version that does not match the cataloged one.
#[error("topic '{topic}' binds ontology '{id}', which is not cataloged or version-mismatched")]
DirectBindingInvalid {
/// The topic with the invalid binding.
topic: String,
/// The offending ontology id.
id: String,
},
/// Resolving the transitive `extends` ancestry for an allowed ontology
/// failed (an ancestor is missing from the supplied ontology-pack
/// directory, or the `extends` graph is cyclic).
#[error(transparent)]
Ontology(#[from] mif_ontology::OntologyError),
/// Building a dynamic `jsonschema` validator for a resolved entity
/// type's `schema` field failed. Indicates a malformed ontology pack,
/// not a bug in the finding being validated.
#[error("entity type '{entity_type}' has a malformed validation schema: {detail}")]
EntityTypeSchemaInvalid {
/// The offending entity type name.
entity_type: String,
/// The underlying schema compilation error, stringified (the
/// original `jsonschema` error type is not `'static` and cannot be
/// stored here directly).
detail: String,
},
/// A `SQLite` index operation failed.
#[error("sqlite index operation failed: {source}")]
Index {
/// The underlying `SQLite` error.
#[source]
source: rusqlite::Error,
},
/// Failed to open or write the exclusive review lock file.
#[error("failed to acquire the review lock at {path}: {source}")]
LockIo {
/// The lock file path.
path: String,
/// The underlying I/O error.
#[source]
source: std::io::Error,
},
/// Another `review` run already holds the lock.
#[error("another review is already in progress (lock held by pid {holder_pid})")]
LockHeld {
/// The PID recorded in the held lock file.
holder_pid: u32,
},
/// A suggestion queue file on disk belongs to a different topic than
/// the one being upserted — a copied/renamed queue file or a
/// wrong-path caller, which must not silently mix topics' entries.
#[error("suggestion queue at {path} belongs to topic '{found}', not '{expected}'")]
QueueTopicMismatch {
/// The queue file path.
path: String,
/// The topic the caller is upserting.
expected: String,
/// The topic recorded inside the queue file.
found: String,
},
/// Computing an embedding failed.
#[error(transparent)]
Embed(#[from] mif_embed::EmbedError),
}
impl MifRhError {
// One arm per error variant, each a flat struct literal — length is
// inherent to the variant count, not a complexity signal.
#[allow(clippy::too_many_lines)]
const fn meta(&self) -> ProblemMeta {
match self {
Self::FindingIo { .. } => ProblemMeta {
slug: "finding-io",
version: "v1",
title: "Failed to read a finding file",
status: 500,
exit_code: 2,
},
Self::FindingJson { .. } => ProblemMeta {
slug: "finding-invalid-json",
version: "v1",
title: "Finding file is not valid JSON",
status: 400,
exit_code: 2,
},
Self::Io { .. } => ProblemMeta {
slug: "mif-rh-io",
version: "v1",
title: "Failed to read a supporting file",
status: 500,
exit_code: 1,
},
Self::Json { .. } => ProblemMeta {
slug: "mif-rh-invalid-json",
version: "v1",
title: "Supporting file is not valid JSON",
status: 400,
exit_code: 1,
},
Self::JsonSerialize { .. } => ProblemMeta {
slug: "json-serialize-failure",
version: "v1",
title: "A value could not be serialized to JSON",
status: 500,
exit_code: 1,
},
Self::OntologyPackYaml { .. } => ProblemMeta {
slug: "ontology-pack-invalid-yaml",
version: "v1",
title: "Ontology pack YAML failed to parse",
status: 422,
exit_code: 4,
},
Self::CatalogMissing { .. } => ProblemMeta {
slug: "catalog-missing",
version: "v1",
title: "Ontology catalog file does not exist",
status: 404,
exit_code: 3,
},
Self::ConfigMissing { .. } => ProblemMeta {
slug: "config-missing",
version: "v1",
title: "Harness config file does not exist",
status: 404,
exit_code: 2,
},
Self::DirectBindingInvalid { .. } => ProblemMeta {
slug: "direct-binding-invalid",
version: "v1",
title: "Topic binds an uncataloged or version-mismatched ontology",
status: 422,
exit_code: 1,
},
Self::Ontology(_) => ProblemMeta {
slug: "delegated-ontology",
version: "v1",
title: "Delegated ontology error",
status: 500,
exit_code: 4,
},
Self::EntityTypeSchemaInvalid { .. } => ProblemMeta {
slug: "entity-type-schema-invalid",
version: "v1",
title: "Entity type validation schema is malformed",
status: 422,
exit_code: 4,
},
Self::Index { .. } => ProblemMeta {
slug: "index-failure",
version: "v1",
title: "A SQLite index operation failed",
status: 500,
exit_code: 1,
},
Self::LockIo { .. } => ProblemMeta {
slug: "lock-io",
version: "v1",
title: "Failed to acquire the review lock file",
status: 500,
exit_code: 2,
},
Self::LockHeld { .. } => ProblemMeta {
slug: "lock-held",
version: "v1",
title: "Another review is already in progress",
status: 409,
exit_code: 2,
},
Self::QueueTopicMismatch { .. } => ProblemMeta {
slug: "queue-topic-mismatch",
version: "v1",
title: "Suggestion queue belongs to a different topic",
status: 409,
exit_code: 2,
},
Self::Embed(_) => ProblemMeta {
slug: "delegated-embed",
version: "v1",
title: "Delegated embedding error",
status: 500,
exit_code: 1,
},
}
}
}
/// The `(suggested_fix, code_action)` pair for every variant that carries
/// its own static remediation text (everything except the delegated
/// `Ontology`/`Embed` variants and the IO-classified variants, which
/// `to_problem` handles separately).
// One arm per error variant, each a flat struct literal — length is
// inherent to the variant count, not a complexity signal.
#[allow(clippy::too_many_lines)]
fn fix_and_action(error: &MifRhError) -> (SuggestedFix, CodeAction) {
match error {
MifRhError::OntologyPackYaml { .. } => (
SuggestedFix::new(
"Fix the YAML syntax error in the ontology pack, then retry.",
Applicability::MaybeIncorrect,
),
CodeAction::new(
"Fix the malformed ontology pack YAML",
"quickfix",
Applicability::MaybeIncorrect,
),
),
MifRhError::CatalogMissing { .. } => (
SuggestedFix::new(
"Run rht's scripts/sync-packs.sh (or mif-rh-cli's equivalent) to generate the \
catalog, then retry.",
Applicability::MachineApplicable,
),
CodeAction::new(
"Generate the missing catalog",
"quickfix",
Applicability::MachineApplicable,
),
),
MifRhError::ConfigMissing { .. } => (
SuggestedFix::new(
"Supply the correct --config path to harness.config.json, then retry.",
Applicability::MaybeIncorrect,
),
CodeAction::new(
"Correct the --config path",
"quickfix",
Applicability::MaybeIncorrect,
),
),
MifRhError::DirectBindingInvalid { .. } => (
SuggestedFix::new(
"Catalog the missing ontology, correct its pinned version, or remove the \
invalid topic binding, then retry.",
Applicability::MaybeIncorrect,
),
CodeAction::new(
"Fix the topic's ontology binding",
"quickfix",
Applicability::MaybeIncorrect,
),
),
MifRhError::EntityTypeSchemaInvalid { .. } => (
SuggestedFix::new(
"Fix the entity type's schema field in the ontology pack, then retry.",
Applicability::MaybeIncorrect,
),
CodeAction::new(
"Fix the entity type's schema",
"quickfix",
Applicability::MaybeIncorrect,
),
),
MifRhError::Index { .. } => (
SuggestedFix::new(
"This indicates a corrupt or inaccessible index database. Delete it and \
rebuild with `mif-rh-cli review --build-index`, then retry.",
Applicability::Unspecified,
),
CodeAction::new("Rebuild the index", "quickfix", Applicability::Unspecified),
),
MifRhError::LockHeld { .. } => (
SuggestedFix::new(
"Wait for the in-progress review to finish, then retry.",
Applicability::MaybeIncorrect,
),
CodeAction::new("Wait and retry", "quickfix", Applicability::MaybeIncorrect),
),
MifRhError::QueueTopicMismatch { .. } => (
SuggestedFix::new(
"Point the upsert at reports/_meta/suggestions/<topic>.json for the topic \
being reviewed, or remove the stray queue file that was copied or renamed \
across topics.",
Applicability::MaybeIncorrect,
),
CodeAction::new(
"Use the topic's own suggestion queue path",
"quickfix",
Applicability::MaybeIncorrect,
),
),
MifRhError::JsonSerialize { .. } => (
SuggestedFix::new(
"This indicates a bug in mif-rh: a value could not be serialized to JSON. \
Report it upstream with the record that triggered it; no caller-side fix \
exists.",
Applicability::Unspecified,
),
CodeAction::new(
"Report the serialization bug",
"quickfix",
Applicability::Unspecified,
),
),
// FindingJson/Json carry no additional remediation beyond the
// error message itself; the caller (`to_problem`) never invokes
// this helper for the delegated or IO-classified variants.
MifRhError::FindingJson { .. } | MifRhError::Json { .. } => (
SuggestedFix::new(
"Correct the file so it is valid JSON, then retry.",
Applicability::MaybeIncorrect,
),
CodeAction::new(
"Fix the JSON syntax error",
"quickfix",
Applicability::MaybeIncorrect,
),
),
MifRhError::FindingIo { .. }
| MifRhError::Io { .. }
| MifRhError::LockIo { .. }
| MifRhError::Ontology(_)
| MifRhError::Embed(_) => unreachable!(
"to_problem handles the IO-classified and delegated variants before calling \
fix_and_action"
),
}
}
impl ToProblem for MifRhError {
fn to_problem(&self) -> ProblemDetails {
match self {
Self::Ontology(inner) => inner.to_problem(),
Self::Embed(inner) => inner.to_problem(),
Self::FindingIo { source, .. }
| Self::Io { source, .. }
| Self::LockIo { source, .. } => {
let (status, fix, action) = mif_problem::classify_io_error(source);
let mut problem = self
.meta()
.into_details(env!("CARGO_PKG_NAME"), self.to_string());
problem.status = status;
problem.with_suggested_fix(fix).with_code_action(action)
},
_ => {
let (fix, action) = fix_and_action(self);
self.meta()
.into_details(env!("CARGO_PKG_NAME"), self.to_string())
.with_suggested_fix(fix)
.with_code_action(action)
},
}
}
}
impl From<rusqlite::Error> for MifRhError {
fn from(source: rusqlite::Error) -> Self {
Self::Index { source }
}
}
#[cfg(test)]
mod tests {
use super::MifRhError;
fn io_error() -> std::io::Error {
std::io::Error::new(std::io::ErrorKind::NotFound, "not found")
}
fn json_error() -> serde_json::Error {
serde_json::from_str::<serde_json::Value>("not json").unwrap_err()
}
fn yaml_error() -> serde_norway::Error {
serde_norway::from_str::<serde_json::Value>("- a\n bad: [unterminated").unwrap_err()
}
fn every_variant() -> Vec<MifRhError> {
vec![
MifRhError::FindingIo {
path: "f.json".to_string(),
source: io_error(),
},
MifRhError::FindingJson {
path: "f.json".to_string(),
source: json_error(),
},
MifRhError::Io {
path: "x".to_string(),
source: io_error(),
},
MifRhError::Json {
path: "x.json".to_string(),
source: json_error(),
},
MifRhError::JsonSerialize {
path: "x.json".to_string(),
source: json_error(),
},
MifRhError::OntologyPackYaml {
path: "x.yaml".to_string(),
source: yaml_error(),
},
MifRhError::CatalogMissing {
path: "catalog.json".to_string(),
},
MifRhError::ConfigMissing {
path: "config.json".to_string(),
},
MifRhError::DirectBindingInvalid {
topic: "t".to_string(),
id: "o".to_string(),
},
MifRhError::Ontology(mif_ontology::OntologyError::Io {
path: "onto.yaml".to_string(),
source: io_error(),
}),
MifRhError::EntityTypeSchemaInvalid {
entity_type: "widget".to_string(),
detail: "bad schema".to_string(),
},
MifRhError::Index {
source: rusqlite::Error::InvalidParameterName("p".to_string()),
},
MifRhError::LockIo {
path: "lock".to_string(),
source: io_error(),
},
MifRhError::LockHeld { holder_pid: 1234 },
MifRhError::QueueTopicMismatch {
path: "reports/_meta/suggestions/edu.json".to_string(),
expected: "edu".to_string(),
found: "sec".to_string(),
},
MifRhError::Embed(mif_embed::EmbedError::NoCacheDir {
model: "test-model",
}),
]
}
#[test]
fn every_variant_produces_a_distinct_problem_type() {
use mif_problem::ToProblem;
let problem_types: Vec<String> = every_variant()
.iter()
.map(|e| e.to_problem().problem_type)
.collect();
let mut deduped = problem_types.clone();
deduped.sort();
deduped.dedup();
assert_eq!(
problem_types.len(),
deduped.len(),
"expected every variant to produce a distinct problem_type: {problem_types:?}"
);
}
#[test]
fn every_variant_has_a_display_message() {
for error in every_variant() {
assert!(!error.to_string().is_empty());
}
}
#[test]
fn io_classified_variants_delegate_status_to_classify_io_error() {
use mif_problem::ToProblem;
let not_found = MifRhError::Io {
path: "missing".to_string(),
source: io_error(),
};
// classify_io_error maps NotFound to 404, overriding meta()'s generic 500.
assert_eq!(not_found.to_problem().status, 404);
}
#[test]
fn delegated_variants_forward_to_the_inner_error() {
use mif_problem::ToProblem;
let ontology_problem = MifRhError::Ontology(mif_ontology::OntologyError::Io {
path: "onto.yaml".to_string(),
source: io_error(),
})
.to_problem();
let inner_problem = mif_ontology::OntologyError::Io {
path: "onto.yaml".to_string(),
source: io_error(),
}
.to_problem();
assert_eq!(ontology_problem.problem_type, inner_problem.problem_type);
let embed_problem = MifRhError::Embed(mif_embed::EmbedError::NoCacheDir {
model: "test-model",
})
.to_problem();
let inner_embed_problem = mif_embed::EmbedError::NoCacheDir {
model: "test-model",
}
.to_problem();
assert_eq!(embed_problem.problem_type, inner_embed_problem.problem_type);
}
#[test]
fn exit_codes_match_the_documented_scheme() {
use mif_problem::ToProblem;
assert_eq!(
MifRhError::CatalogMissing {
path: "c".to_string()
}
.to_problem()
.exit_code,
Some(3)
);
assert_eq!(
MifRhError::LockHeld { holder_pid: 1 }
.to_problem()
.exit_code,
Some(2)
);
assert_eq!(
MifRhError::DirectBindingInvalid {
topic: "t".to_string(),
id: "o".to_string(),
}
.to_problem()
.exit_code,
Some(1)
);
}
#[test]
fn rusqlite_error_converts_into_the_index_variant() {
let source = rusqlite::Error::InvalidParameterName("p".to_string());
let error: MifRhError = source.into();
assert!(matches!(error, MifRhError::Index { .. }));
}
}