firstpass_core/features.rs
1//! The request feature vector (SPEC §9.2) — deterministic, versioned, privacy-preserving.
2//!
3//! Features are the input to routing policy. They are extracted deterministically from a
4//! request so that the same request always produces the same vector (a precondition for a
5//! re-derivable audit trail), and they are **privacy-preserving by construction**: no raw
6//! prompt text, only coarse buckets and salted hashes. The vector is versioned
7//! ([`FEATURE_VERSION`]); a change to how any feature is computed bumps the version so old
8//! traces remain interpretable.
9
10use serde::{Deserialize, Serialize};
11
12/// Version of the feature-extraction contract. Bump on any change to how a feature is
13/// computed. Recorded per trace as `features@vN`.
14/// Feature-extraction contract version.
15///
16/// **v3** changed how `difficulty_hint` is COMPUTED: the `deep` threshold moved from
17/// `assistant_turns >= 8` to `>= 5`, because 8 was unreachable in every workload measured (MBPP
18/// capped observed depth at 2; agentic SWE-bench at 7 against an 8-turn cap), leaving
19/// `DifficultyHint::High` as dead code. Same field, same range, different meaning — a v2 hint of
20/// `Medium` and a v3 hint of `Medium` are not the same measurement, so replaying a v3-fitted policy
21/// against v2 traces would silently compare incomparable numbers. That is precisely what this
22/// constant exists to prevent, and the rule applies to a threshold change exactly as it applies to a
23/// new field. Flagged in review after I changed the semantics and left the version alone.
24///
25/// **v2** added [`Features::difficulty_hint`] (trajectory signals read from the agent's own
26/// conversation). The bump is required even though the field is `#[serde(default)]` and old traces
27/// still deserialize: the version says *how a vector was computed*, and a v1 trace genuinely had no
28/// hint available. Leaving it at 1 would let a policy fitted on v2 traffic be replayed against v1
29/// traces as though the missing hints were real zeroes — silently mixing "no signal" with "not
30/// measured", which is the class of error the version field exists to prevent.
31pub const FEATURE_VERSION: u32 = 3;
32
33/// Coarse task classification. `Other` is the safe default when classification is uncertain.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum TaskKind {
37 /// Editing or writing code (the primary M0/M1 target).
38 CodeEdit,
39 /// Generating or repairing tests.
40 TestGen,
41 /// Read-only investigation / search / navigation.
42 Explore,
43 /// Reviewing or critiquing existing work.
44 Review,
45 /// Structured extraction / classification.
46 Extract,
47 /// Free-form conversation.
48 Chat,
49 /// Anything not confidently classified (the safe default).
50 #[default]
51 Other,
52}
53
54/// Raw counts read off an agent conversation, before they are collapsed into a
55/// [`DifficultyHint`].
56///
57/// Deliberately counts, not content: how many tool results failed, not what they said. A router
58/// needs to know a session is going badly; it does not need the stack trace, and [`Features`] is
59/// not a place raw prompt text may ever land.
60///
61/// Extraction lives in the proxy (it parses HTTP bodies, which is I/O-shaped); the *scoring* lives
62/// here so it stays deterministic, versioned, and testable without a server.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
64pub struct TrajectorySignals {
65 /// Tool results in the recent window that reported an error.
66 pub tool_errors: u32,
67 /// Tool results in the recent window, total. Zero means "no tool activity to judge".
68 pub tool_results: u32,
69 /// Assistant turns in the conversation — a proxy for how long this has been going on.
70 pub assistant_turns: u32,
71 /// Repeated identical tool invocations: the agent trying the same thing again.
72 pub repeated_tool_calls: u32,
73}
74
75/// How hard an agent's own conversation looks. Ordinal, four levels, deliberately coarse.
76///
77/// Four levels rather than a continuous score, because this feeds
78/// `ContextBucket` and every extra distinction multiplies the bandit's state space — the arms then
79/// share less traffic and learn slower. A signal too fine to learn from is worse than a coarse one:
80/// it looks more informative and performs worse.
81#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
82#[repr(u8)]
83pub enum DifficultyHint {
84 /// No usable signal: a single-shot request, a non-agent client, or an unparseable body.
85 #[default]
86 None = 0,
87 /// Some tool activity, nothing going wrong.
88 Low = 1,
89 /// Errors or repetition appearing.
90 Medium = 2,
91 /// Sustained failure: the agent is stuck.
92 High = 3,
93}
94
95impl DifficultyHint {
96 /// Score signals into a hint.
97 ///
98 /// The thresholds below are a **prior, not a finding**. They are a reasonable starting shape,
99 /// and the bandit is what actually learns whether a given bucket deserves a higher start rung —
100 /// so the job here is to separate genuinely different situations into different buckets, not to
101 /// be right about which is harder. Getting the cut points slightly wrong costs a little
102 /// learning rate; collapsing distinct situations into one bucket costs the signal entirely.
103 ///
104 /// No tool activity yields [`DifficultyHint::None`] rather than [`DifficultyHint::Low`]: a
105 /// request with no tools has told us nothing, and "nothing" must not be confused with "fine".
106 #[must_use]
107 pub fn score(s: TrajectorySignals) -> Self {
108 if s.tool_results == 0 && s.repeated_tool_calls == 0 {
109 return Self::None;
110 }
111 // Integer-ratio comparisons rather than float division: this feeds a hash bucket and a
112 // versioned audit field, so it must be bit-identical everywhere, and `a/b > 0.5` is not
113 // something to trust across platforms when `a*2 > b` says it exactly.
114 let e = s.tool_errors;
115 let n = s.tool_results;
116 // `e > n / 2`, not `e * 2 > n`: the multiplication overflows for `e > u32::MAX/2`, which
117 // panics in debug builds. Unreachable through the proxy (its window caps the counts), but
118 // this is public API in an I/O-free crate — anyone may call it with any values, and
119 // "unreachable through the one caller I was thinking about" is not a bound.
120 //
121 // Integer division truncates, so `e > n/2` is very slightly stricter than a true majority
122 // at odd `n` (n=5 needs e>2, i.e. 3 of 5 — which IS the majority). Same semantics, no
123 // overflow. Flagged in review.
124 let half_failing = n > 0 && e > n / 2;
125 let any_failing = e > 0;
126 let stuck = s.repeated_tool_calls >= 2;
127 // `>= 5`, not `>= 8`. The original threshold was unreachable in every workload actually
128 // measured: MBPP capped observed depth at 2 (its retry loop ends when the cheap rung
129 // passes), and agentic SWE-bench at 7 against an 8-turn cap — an off-by-one that made
130 // `High` dead code in both. A level that never fires is worse than no level: it looks like
131 // coverage while contributing nothing, and the bandit can never learn an arm it is never
132 // given.
133 //
134 // Five turns is where a repair session is meaningfully long rather than merely underway,
135 // and it is reachable under both caps. Verified through the real extractors, not by
136 // constructing the struct directly — the mistake that hid this in the first place.
137 let deep = s.assistant_turns >= 5;
138
139 match (half_failing || stuck, any_failing, deep) {
140 // Most calls failing, or the same call retried repeatedly. Being deep on top of that is
141 // the clearest "stuck" signature there is.
142 (true, _, true) => Self::High,
143 (true, _, false) => Self::Medium,
144 // Some errors, and the conversation has been running a while.
145 (false, true, true) => Self::Medium,
146 (false, true, false) => Self::Low,
147 // Tools in use, nothing failing.
148 (false, false, _) => Self::Low,
149 }
150 }
151
152 /// The wire value stored in [`Features::difficulty_hint`].
153 #[must_use]
154 pub const fn as_u8(self) -> u8 {
155 self as u8
156 }
157}
158
159/// Whether a difficulty hint carries no signal, and so should be omitted from the wire form.
160///
161/// Used by [`Features::difficulty_hint`]'s `skip_serializing_if` to keep v1 traces byte-identical
162/// under re-serialization — see that field's note on the hash chain.
163#[expect(
164 clippy::trivially_copy_pass_by_ref,
165 reason = "serde's skip_serializing_if requires a &T predicate"
166)]
167fn is_no_signal(hint: &u8) -> bool {
168 *hint == DifficultyHint::None as u8
169}
170
171/// The per-request feature vector (§9.2).
172///
173/// Rolling per-bucket statistics (e.g. `prior_rung_clearance`) are intentionally **not**
174/// here — they live in the trace store, not the deterministic per-request contract.
175#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
176pub struct Features {
177 /// Feature-extraction contract version (`features@vN`).
178 pub version: u32,
179 /// Coarse task classification.
180 pub task_kind: TaskKind,
181 /// Programming language, when known (lowercased identifier, e.g. `"rust"`).
182 #[serde(default, skip_serializing_if = "Option::is_none")]
183 pub language: Option<String>,
184 /// Calling agent identity, when known (e.g. `"compass"`).
185 #[serde(default, skip_serializing_if = "Option::is_none")]
186 pub agent: Option<String>,
187 /// Calling subagent identity, when known (e.g. `"test-runner"`).
188 #[serde(default, skip_serializing_if = "Option::is_none")]
189 pub subagent: Option<String>,
190 /// Coarse bucket of the prompt's token count (see [`token_bucket`]) — never the raw count.
191 pub prompt_token_bucket: u32,
192 /// Number of tools/functions offered in the request.
193 pub tool_count: u32,
194 /// Whether the request carried image content.
195 pub has_images: bool,
196 /// Salted, truncated hash of the repository identity (see [`repo_fingerprint`]) — never a path.
197 #[serde(default, skip_serializing_if = "Option::is_none")]
198 pub repo_fingerprint: Option<String>,
199 /// How many attempts have already failed in this session (drives session promotion, §8.4).
200 pub session_failure_count: u32,
201 /// How hard the *agent's own conversation* looks, `0..=3` — see [`DifficultyHint`].
202 ///
203 /// Distinct from [`Features::session_failure_count`], and the distinction is the whole point.
204 /// That field counts **our gate's** failures: endogenous evidence, available only after we have
205 /// already paid for a failed attempt. This one reads **the agent's** failures out of the
206 /// transcript it sent us — failing tool calls, repeated identical actions, a long unproductive
207 /// exchange — which is evidence we get *before* spending anything, and which is present on turns
208 /// where our own gate would have passed.
209 ///
210 /// `0` means "no signal", which is what a single-shot request, a non-agent client, and an
211 /// unparseable body all produce. It is a routing *hint* and never a serving decision: it may
212 /// choose which rung to start on, never what is fit to serve. Only a gate decides that.
213 ///
214 /// **`skip_serializing_if` is load-bearing for the hash chain, not a size optimisation.** A v1
215 /// trace's JSON has no such field; serde defaults it to `0` on read, and if re-serialization
216 /// emitted `"difficulty_hint":0` the canonical JSON would differ from the bytes that were
217 /// originally hashed. Every historical receipt would then re-derive to a different hash and
218 /// `firstpass verify` would report `TAMPERED` across the whole store — breaking invariant #1
219 /// ("the hash chain is re-derivable") on upgrade, with no tampering having occurred.
220 ///
221 /// Omitting the default is exactly right rather than merely convenient: a v1 trace *had* no
222 /// hint, and a receipt should say what was measured, not what a later version would have
223 /// defaulted to. A v2 request carrying a real hint serialises it normally.
224 #[serde(default, skip_serializing_if = "is_no_signal")]
225 pub difficulty_hint: u8,
226 /// Hour-of-day bucket in UTC, `0..=23` (see [`hour_bucket`]).
227 pub hour_bucket: u8,
228}
229
230impl Features {
231 /// A minimal vector stamped with the current [`FEATURE_VERSION`] and the given task kind.
232 #[must_use]
233 pub fn new(task_kind: TaskKind) -> Self {
234 Self {
235 version: FEATURE_VERSION,
236 task_kind,
237 language: None,
238 agent: None,
239 subagent: None,
240 prompt_token_bucket: 0,
241 tool_count: 0,
242 has_images: false,
243 repo_fingerprint: None,
244 session_failure_count: 0,
245 difficulty_hint: DifficultyHint::None as u8,
246 hour_bucket: 0,
247 }
248 }
249}
250
251/// Bucket a token count into a coarse, privacy-preserving band: `floor(log2(n))`, with
252/// `0` and `1` both mapping to bucket `0`.
253///
254/// Monotonic non-decreasing in `n`, so ordering is preserved while the exact count is not
255/// recoverable. Deterministic — the same `n` always yields the same bucket.
256#[must_use]
257pub fn token_bucket(n: u64) -> u32 {
258 if n < 2 {
259 0
260 } else {
261 // 63 - leading_zeros == floor(log2(n)) for n >= 1.
262 63 - n.leading_zeros()
263 }
264}
265
266/// Salted, truncated fingerprint of a repository identity: the first 16 hex chars of
267/// `SHA-256(salt || 0x00 || repo)`.
268///
269/// The salt is a per-deployment secret; without it the fingerprint is not reversible to the
270/// repo identity, and cross-deployment correlation is prevented. Deterministic for a fixed salt.
271#[must_use]
272pub fn repo_fingerprint(salt: &str, repo: &str) -> String {
273 use sha2::{Digest, Sha256};
274 let mut h = Sha256::new();
275 h.update(salt.as_bytes());
276 h.update([0u8]); // domain separator so salt||repo can't collide with a different split
277 h.update(repo.as_bytes());
278 let digest = h.finalize();
279 hex::encode(&digest[..8]) // 8 bytes -> 16 hex chars
280}
281
282/// Hour-of-day bucket in UTC (`0..=23`) for a timestamp — a routing feature (traffic varies
283/// by hour) that leaks nothing finer than the hour.
284#[must_use]
285pub fn hour_bucket(ts: jiff::Timestamp) -> u8 {
286 // Convert to a UTC civil time; hour is 0..=23.
287 ts.to_zoned(jiff::tz::TimeZone::UTC).hour() as u8
288}
289
290#[cfg(test)]
291mod tests {
292 use super::*;
293
294 /// A request with no tool activity must score `None`, not `Low`.
295 ///
296 /// "I have no evidence" and "I have evidence that things are fine" are different states, and
297 /// conflating them would make every single-shot request look like a healthy agent session —
298 /// polluting the bandit's healthiest bucket with traffic that carries no trajectory signal
299 /// whatsoever.
300 #[test]
301 fn absent_tool_activity_is_no_signal_not_a_good_signal() {
302 assert_eq!(
303 DifficultyHint::score(TrajectorySignals::default()),
304 DifficultyHint::None
305 );
306 // Turn depth alone is not evidence of difficulty: a long, smooth conversation is still
307 // smooth, and charging it a higher start rung would be a pure cost regression.
308 assert_eq!(
309 DifficultyHint::score(TrajectorySignals {
310 assistant_turns: 50,
311 ..Default::default()
312 }),
313 DifficultyHint::None
314 );
315 }
316
317 /// Clean tool use scores `Low`; a majority-failing window scores higher. This is the ordering
318 /// the whole feature rests on — if these two land in the same bucket, there is no signal.
319 #[test]
320 fn a_failing_window_outranks_a_clean_one() {
321 let clean = DifficultyHint::score(TrajectorySignals {
322 tool_results: 6,
323 tool_errors: 0,
324 assistant_turns: 4,
325 repeated_tool_calls: 0,
326 });
327 let failing = DifficultyHint::score(TrajectorySignals {
328 tool_results: 6,
329 tool_errors: 5,
330 assistant_turns: 4,
331 repeated_tool_calls: 0,
332 });
333 assert_eq!(clean, DifficultyHint::Low);
334 assert!(
335 failing > clean,
336 "5-of-6 failing must outrank 0-of-6: {failing:?} vs {clean:?}"
337 );
338 }
339
340 /// Repetition alone is a stuck signal, even with no reported errors.
341 ///
342 /// This is the case an error-count-only heuristic misses entirely: an agent re-running the same
343 /// command that "succeeds" each time while making no progress reports zero errors and is
344 /// obviously stuck. Switchyard's stage router reads exactly this, and it is why the feature
345 /// counts repeats separately rather than folding them into an error rate.
346 #[test]
347 fn repetition_is_a_stuck_signal_without_any_errors() {
348 let hint = DifficultyHint::score(TrajectorySignals {
349 tool_results: 4,
350 tool_errors: 0,
351 assistant_turns: 5,
352 repeated_tool_calls: 3,
353 });
354 assert!(
355 hint >= DifficultyHint::Medium,
356 "3 repeated calls with no errors must still read as difficulty, got {hint:?}"
357 );
358 }
359
360 /// Sustained failure deep into a conversation is the top bucket, and the depth matters: the
361 /// same failure rate early is recoverable, late it is a pattern.
362 #[test]
363 fn sustained_failure_deep_in_a_session_is_the_top_bucket() {
364 let deep = DifficultyHint::score(TrajectorySignals {
365 tool_results: 10,
366 tool_errors: 8,
367 assistant_turns: 12,
368 repeated_tool_calls: 2,
369 });
370 let shallow = DifficultyHint::score(TrajectorySignals {
371 tool_results: 10,
372 tool_errors: 8,
373 assistant_turns: 2,
374 repeated_tool_calls: 0,
375 });
376 assert_eq!(deep, DifficultyHint::High);
377 assert!(
378 shallow < deep,
379 "the same failure rate early must not score as high as late: {shallow:?} vs {deep:?}"
380 );
381 }
382
383 /// Extreme counts must not panic. `score` is public API in an I/O-free crate, so it is callable
384 /// with any values — the proxy's window is one caller's bound, not the function's. `e * 2`
385 /// overflowed for `e > u32::MAX/2` and panicked in debug. Flagged in review.
386 #[test]
387 fn extreme_counts_do_not_overflow() {
388 let h = DifficultyHint::score(TrajectorySignals {
389 tool_errors: u32::MAX,
390 tool_results: u32::MAX,
391 assistant_turns: u32::MAX,
392 repeated_tool_calls: u32::MAX,
393 });
394 assert_eq!(h, DifficultyHint::High, "all-failing at any scale is High");
395
396 // And the majority semantics are unchanged at ordinary sizes: 3-of-5 is a majority, 2-of-5
397 // is not. Integer division must not have shifted the cut point.
398 assert!(
399 DifficultyHint::score(TrajectorySignals {
400 tool_errors: 3,
401 tool_results: 5,
402 ..Default::default()
403 }) >= DifficultyHint::Medium
404 );
405 assert_eq!(
406 DifficultyHint::score(TrajectorySignals {
407 tool_errors: 2,
408 tool_results: 5,
409 ..Default::default()
410 }),
411 DifficultyHint::Low,
412 "2 of 5 is not a majority and must stay Low"
413 );
414 }
415
416 /// The hint is bounded. It indexes a bandit bucket, so an unbounded value would silently
417 /// fragment the state space; and it is a versioned audit field, where an out-of-range value is
418 /// a contract violation rather than a curiosity.
419 #[test]
420 fn the_hint_is_always_within_its_declared_range() {
421 for tool_results in 0..12u32 {
422 for tool_errors in 0..=tool_results {
423 for assistant_turns in [0u32, 1, 7, 8, 40] {
424 for repeated_tool_calls in 0..4u32 {
425 let h = DifficultyHint::score(TrajectorySignals {
426 tool_errors,
427 tool_results,
428 assistant_turns,
429 repeated_tool_calls,
430 });
431 assert!(h.as_u8() <= DifficultyHint::High.as_u8());
432 }
433 }
434 }
435 }
436 }
437
438 /// A v1 trace, written before this field existed, must still deserialize — and must land on
439 /// `None` rather than any other level. Old receipts stay readable; that is a hard requirement
440 /// of a tamper-evident log, since an auditor cannot re-derive what will not parse.
441 #[test]
442 fn a_v1_trace_without_the_hint_still_deserializes() {
443 let v1 = r#"{"version":1,"task_kind":"other","prompt_token_bucket":3,
444 "tool_count":0,"has_images":false,"session_failure_count":0,"hour_bucket":9}"#;
445 let f: Features = serde_json::from_str(v1).expect("a v1 trace must still parse");
446 assert_eq!(
447 f.version, 1,
448 "the stored version must be preserved, not rewritten"
449 );
450 assert_eq!(
451 f.difficulty_hint,
452 DifficultyHint::None as u8,
453 "a missing hint must read as no-signal"
454 );
455 }
456
457 #[test]
458 fn token_bucket_is_monotonic_and_coarse() {
459 assert_eq!(token_bucket(0), 0);
460 assert_eq!(token_bucket(1), 0);
461 assert_eq!(token_bucket(2), 1);
462 assert_eq!(token_bucket(3), 1);
463 assert_eq!(token_bucket(4), 2);
464 assert_eq!(token_bucket(1024), 10);
465 // monotonic non-decreasing
466 let mut last = 0;
467 for n in 0..5000u64 {
468 let b = token_bucket(n);
469 assert!(b >= last);
470 last = b;
471 }
472 }
473
474 #[test]
475 fn repo_fingerprint_is_deterministic_salted_and_truncated() {
476 let a = repo_fingerprint("salt1", "github.com/acme/api");
477 assert_eq!(a, repo_fingerprint("salt1", "github.com/acme/api")); // deterministic
478 assert_ne!(a, repo_fingerprint("salt2", "github.com/acme/api")); // salt-sensitive
479 assert_ne!(a, repo_fingerprint("salt1", "github.com/acme/web")); // repo-sensitive
480 assert_eq!(a.len(), 16);
481 assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
482 // domain separator: "a"+"bc" must not collide with "ab"+"c"
483 assert_ne!(repo_fingerprint("a", "bc"), repo_fingerprint("ab", "c"));
484 }
485
486 #[test]
487 fn hour_bucket_in_range() {
488 // 2026-07-08T15:04:05Z -> hour 15 UTC
489 let ts: jiff::Timestamp = "2026-07-08T15:04:05Z".parse().unwrap();
490 assert_eq!(hour_bucket(ts), 15);
491 let midnight: jiff::Timestamp = "2026-01-01T00:00:00Z".parse().unwrap();
492 assert_eq!(hour_bucket(midnight), 0);
493 }
494
495 #[test]
496 fn features_default_version_stamped() {
497 let f = Features::new(TaskKind::CodeEdit);
498 assert_eq!(f.version, FEATURE_VERSION);
499 assert_eq!(f.task_kind, TaskKind::CodeEdit);
500 }
501}
502
503#[cfg(test)]
504mod v1_chain_regression {
505 use super::*;
506
507 /// A v1 trace's hash must be re-derivable after v2 adds a field.
508 ///
509 /// Reviewer flagged this as a blocking regression, and the mechanism is exactly right in shape:
510 /// v1 JSON has no `difficulty_hint`, serde defaults it to 0 on read, and if re-serialization
511 /// emits `"difficulty_hint":0` the canonical JSON differs from what was hashed — every historical
512 /// receipt reads as TAMPERED. That is invariant #1 in CLAUDE.md ("the hash chain is
513 /// re-derivable"), so it gets a test rather than an argument.
514 #[test]
515 fn a_v1_feature_vector_round_trips_to_its_original_canonical_json() {
516 let v1 = r#"{"version":1,"task_kind":"other","prompt_token_bucket":3,"tool_count":0,"has_images":false,"session_failure_count":0,"hour_bucket":9}"#;
517 let f: Features = serde_json::from_str(v1).expect("v1 must parse");
518 let reserialized = serde_json::to_string(&f).expect("must serialize");
519 assert!(
520 !reserialized.contains("difficulty_hint"),
521 "re-serializing a v1 vector must NOT emit the v2 field, or every historical receipt \
522 re-derives to a different hash and reads as TAMPERED: {reserialized}"
523 );
524 }
525
526 /// **The chain-level proof**, not just the serde-level one.
527 ///
528 /// The serde test above catches the field appearing; this catches what that would COST. A v1
529 /// receipt's hash was computed over v1 canonical JSON. If today's binary re-derives a different
530 /// hash from the same stored record, `firstpass verify` reports TAMPERED across the entire
531 /// history — the auditor sees fraud where there was only an upgrade, which is the single worst
532 /// failure this system can have.
533 #[test]
534 fn a_v1_receipt_hash_is_still_re_derivable_by_todays_binary() {
535 let v1 = r#"{"version":1,"task_kind":"other","prompt_token_bucket":3,"tool_count":0,"has_images":false,"session_failure_count":0,"hour_bucket":9}"#;
536 // What the v1 binary would have hashed: the canonical form of the v1 document itself.
537 let original: serde_json::Value = serde_json::from_str(v1).expect("v1 must parse");
538 let hash_then = crate::hashchain::record_hash(&original).expect("must hash");
539
540 // What today's binary derives after a round trip through the v2 struct.
541 let f: Features = serde_json::from_str(v1).expect("v1 must parse into v2 struct");
542 let hash_now = crate::hashchain::record_hash(&f).expect("must hash");
543
544 assert_eq!(
545 hash_then, hash_now,
546 "a v1 record must re-derive to its original hash; a mismatch is reported to the \
547 operator as TAMPERED, with no tampering having occurred"
548 );
549 }
550
551 /// ...and a v2 vector that actually carries a hint must still emit it, or the field is
552 /// unauditable — present in routing, absent from the receipt that is supposed to explain it.
553 #[test]
554 fn a_v2_vector_with_a_real_hint_still_serializes_it() {
555 let mut f = Features::new(TaskKind::CodeEdit);
556 f.difficulty_hint = DifficultyHint::High.as_u8();
557 let s = serde_json::to_string(&f).expect("must serialize");
558 assert!(
559 s.contains("\"difficulty_hint\":3"),
560 "a non-default hint must appear in the receipt: {s}"
561 );
562 }
563}