Skip to main content

lean_ctx_protocol/cloud/
metrics_v2.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Engine metrics v2 (C0 2.0 `schemas/metrics.schema.json`, telemetry SPEC).
4//!
5//! `POST /v1/metrics/hours` [`HoursRequestV2`] → [`HoursAckV2`]: hourly
6//! counters of one engine, split by Cloud vault, signed by the instance key
7//! (Ed25519 over [`ENGINE_METRICS_DOMAIN`] ‖ canonical_json(body with
8//! `key_id`, without `signature`), as `worker_register`). Bucket key (instance
9//! from the bearer token, `hour`, `vault`); a higher `rev` replaces the
10//! hour, a lower or equal one is acked `unchanged`. `GET /v1/metrics/sharing`
11//! and every ack carry the [`SharingStateV2`].
12//!
13//! Aggregates only, enforced by the types: every string on this wire is a
14//! closed-pattern newtype ([`ToolName`], [`RuleId`], [`WireName`],
15//! [`FilterName`], [`DetectorName`], [`UnregulatedName`], [`Fingerprint`],
16//! [`HourStamp`], [`VaultId`], [`EngineVersion`], [`KeyId`],
17//! [`SignatureHex`], [`TimeStamp`]) or a closed enum ([`ReadMode`],
18//! [`EngineOs`], the schema constants). None of them can hold a path, a
19//! command line, a prompt, a secret or other free text: constructing one
20//! from such a value fails (or maps to `other`), and deserialising one
21//! refuses it. Every struct refuses unknown fields.
22
23use std::collections::{BTreeMap, BTreeSet};
24use std::fmt;
25
26use serde::{Deserialize, Deserializer, Serialize, Serializer};
27
28use crate::ValidationError;
29
30pub const ENGINE_METRICS_SCHEMA: &str = "leanctx.cloud.instance-metrics/v2";
31pub const ENGINE_METRICS_ACK_SCHEMA: &str = "leanctx.cloud.instance-metrics-ack/v2";
32/// The policy member that gates engine metrics (`x-merge: false_wins`,
33/// `x-enforcement: server`; absent at every level = the plan default).
34pub const SHARE_ENGINE_METRICS_MEMBER: &str = "sharing.share_instance_metrics";
35/// Domain of the batch signature (instance key).
36pub const ENGINE_METRICS_DOMAIN: &str = "leanctx.cloud.instance-metrics.v2\n";
37/// HKDF info of the per-workspace secret fingerprint key.
38pub const SECRET_FINGERPRINT_INFO: &str = "leanctx.cloud.secret-fingerprint.v1";
39/// `POST /v1/metrics/hours`, relative to the engine API base.
40pub const HOURS_ROUTE: &str = "/metrics/hours";
41/// `GET /v1/metrics/sharing`.
42pub const SHARING_ROUTE: &str = "/metrics/sharing";
43/// `POST /v1/metrics/sharing/confirm`.
44pub const SHARING_CONFIRM_ROUTE: &str = "/metrics/sharing/confirm";
45
46pub const MAX_BUCKETS: usize = 168;
47pub const MAX_SLICES: usize = 33;
48pub const MAX_TOOLS: usize = 48;
49pub const MAX_POLICY_BLOCKS: usize = 32;
50pub const MAX_REFETCH: usize = 32;
51pub const MAX_UNREGULATED: usize = 32;
52pub const MAX_SECRET_HITS: usize = 32;
53pub const MAX_HOSTS: usize = 16;
54pub const MAX_SPEND: usize = 32;
55/// Largest request body Cloud accepts.
56pub const MAX_HOURS_BODY_BYTES: usize = 512 * 1024;
57/// Largest count a JSON number carries exactly (2^53).
58pub const MAX_COUNT: u64 = 1 << 53;
59/// Name of the row that absorbs rows beyond a limit or names outside a rule.
60pub const OTHER: &str = "other";
61
62/// K2 (M1): the LeanCTX tool names the engine may send as `tools[].tool`;
63/// any other name (a proxied or custom MCP tool) is `other`. The engine's
64/// tool registry must be a subset (engine test).
65pub const KNOWN_TOOLS: &[&str] = &[
66    "cli_deps",
67    "cli_diff",
68    "cli_find",
69    "cli_full",
70    "cli_glob",
71    "cli_grep",
72    "cli_ls",
73    "cli_read",
74    "cli_read_dedup",
75    "cli_shell",
76    "cli_signatures",
77    "ctx_agent",
78    "ctx_analyze",
79    "ctx_architecture",
80    "ctx_artifacts",
81    "ctx_benchmark",
82    "ctx_call",
83    "ctx_callgraph",
84    "ctx_checkpoint",
85    "ctx_compose",
86    "ctx_compress",
87    "ctx_compress_memory",
88    "ctx_compute",
89    "ctx_context",
90    "ctx_control",
91    "ctx_cost",
92    "ctx_dedup",
93    "ctx_delta",
94    "ctx_discover",
95    "ctx_discover_tools",
96    "ctx_doc",
97    "ctx_edit",
98    "ctx_execute",
99    "ctx_expand",
100    "ctx_feedback",
101    "ctx_gain",
102    "ctx_git_read",
103    "ctx_glob",
104    "ctx_graph",
105    "ctx_handoff",
106    "ctx_heatmap",
107    "ctx_impact",
108    "ctx_index",
109    "ctx_intent",
110    "ctx_knowledge",
111    "ctx_load_tools",
112    "ctx_memory",
113    "ctx_metrics",
114    "ctx_multi_read",
115    "ctx_multi_repo",
116    "ctx_outline",
117    "ctx_overview",
118    "ctx_pack",
119    "ctx_package",
120    "ctx_patch",
121    "ctx_prefetch",
122    "ctx_preload",
123    "ctx_proof",
124    "ctx_provider",
125    "ctx_radar",
126    "ctx_read",
127    "ctx_review",
128    "ctx_search",
129    "ctx_semantic_search",
130    "ctx_session",
131    "ctx_shape",
132    "ctx_share",
133    "ctx_shell",
134    "ctx_smart_read",
135    "ctx_symbol",
136    "ctx_tasks",
137    "ctx_tools",
138    "ctx_transcript_compact",
139    "ctx_tree",
140    "ctx_url_read",
141    "ctx_verify",
142    "ctx_work_graph",
143    "ctx_wrapped",
144    "ocla_savings",
145    "shell",
146    OTHER,
147];
148
149/// Policy member paths and gateway rule ids (`policy_blocks[].rule`).
150pub const KNOWN_RULES: &[&str] = &[
151    "agents.allowed",
152    "context.allowed_sources",
153    "context.allowed_tools",
154    "context.auto_extraction",
155    "context.denied_tools",
156    "context.extraction_requires_source_anchor",
157    "context.injection_filter",
158    "context.max_context_tokens",
159    "context.max_cost_cents_per_person_per_day",
160    "context.max_cost_cents_per_project_per_month",
161    "context.max_requests_per_minute_per_person",
162    "context.max_source_age_days",
163    "context.max_writes_per_min",
164    "context.ranking_profile",
165    "context.read_mode",
166    "security.allowed_models",
167    "security.allowed_providers",
168    "security.block_secrets",
169    "security.blocked_host_countries",
170    "security.blocked_labels",
171    "security.blocked_model_origins",
172    "security.classification",
173    "security.confidential_out_of_sharing",
174    "security.excluded_paths",
175    "security.external_model_excluded_classes",
176    "security.never_send",
177    "security.pii",
178    "security.readable_roots",
179    "security.vendor_direct_cn",
180    "sharing.allowed_vaults",
181    "sharing.consent_required_for",
182    "sharing.cross_team_sharing",
183    "sharing.personal_workspace",
184    "sharing.share_instance_metrics",
185    "sharing.task_claim_min_role",
186    "gateway.budget_exceeded",
187    "gateway.cross_project",
188    "gateway.path_jail",
189    "gateway.rate_limited",
190    "gateway.security_violation",
191    "gateway.tool_denied",
192    "gateway.destination",
193    "gateway.egress",
194    OTHER,
195];
196
197/// Re-fetch filters: a read mode or an output class (`refetch[].filter`).
198pub const KNOWN_FILTERS: &[&str] = &[
199    "auto",
200    "full",
201    "map",
202    "signatures",
203    "diff",
204    "task",
205    "reference",
206    "aggressive",
207    "entropy",
208    "lines",
209    "shell_output",
210    "search_output",
211    OTHER,
212];
213
214/// Secret detectors (`secret_hits[].detector`).
215pub const KNOWN_DETECTORS: &[&str] = &[
216    "aws_access_key",
217    "aws_secret_key",
218    "gcp_key",
219    "azure_key",
220    "github_token",
221    "gitlab_token",
222    "slack_token",
223    "stripe_key",
224    "openai_key",
225    "anthropic_key",
226    "private_key",
227    "jwt",
228    "password_assignment",
229    "connection_string",
230    "generic_api_key",
231    OTHER,
232];
233
234/// Known programs (`unregulated[]` of kind `program`); never a command line.
235pub const KNOWN_PROGRAMS: &[&str] = &[
236    "git",
237    "cargo",
238    "rustc",
239    "npm",
240    "npx",
241    "pnpm",
242    "yarn",
243    "node",
244    "deno",
245    "bun",
246    "python",
247    "python3",
248    "pip",
249    "uv",
250    "go",
251    "make",
252    "cmake",
253    "docker",
254    "kubectl",
255    "helm",
256    "terraform",
257    "aws",
258    "gcloud",
259    "az",
260    "gh",
261    "curl",
262    "wget",
263    "ssh",
264    "scp",
265    "rsync",
266    "psql",
267    "mysql",
268    "redis-cli",
269    "java",
270    "mvn",
271    "gradle",
272    "dotnet",
273    "ruby",
274    "bundle",
275    "php",
276    "composer",
277    "swift",
278    "xcodebuild",
279    "bash",
280    "sh",
281    "zsh",
282    OTHER,
283];
284
285/// K2 (H2): MCP hosts by their client id; any other `clientInfo.name` is `other`.
286pub const KNOWN_HOSTS: &[&str] = &[
287    "amp",
288    "antigravity",
289    "augment",
290    "chatgpt",
291    "claude-code",
292    "claude-desktop",
293    "cline",
294    "codebuddy",
295    "codewhale",
296    "codex",
297    "continue",
298    "copilot-cli",
299    "crush",
300    "cursor",
301    "emacs",
302    "factory",
303    "gemini-cli",
304    "goose",
305    "jetbrains",
306    "kilo-code",
307    "kiro",
308    "lm-studio",
309    "neovim",
310    "oh-my-pi",
311    "opencode",
312    "pi",
313    "qwen-code",
314    "roo-code",
315    "trae",
316    "visual-studio",
317    "vscode-copilot",
318    "warp",
319    "windsurf",
320    "zed",
321    "unknown",
322    OTHER,
323];
324
325/// K13: agent host families (`unregulated[]` of kind `host`), coarser than
326/// [`KNOWN_HOSTS`]: one family per vendor integration; anything else is `other`.
327pub const HOST_FAMILIES: &[&str] = &[
328    "amp",
329    "claude",
330    "cline",
331    "codex",
332    "continue",
333    "copilot",
334    "cursor",
335    "gemini",
336    "goose",
337    "jetbrains",
338    "kilo",
339    "kiro",
340    "opencode",
341    "pi",
342    "qwen",
343    "roo",
344    "windsurf",
345    "zed",
346    OTHER,
347];
348
349/// The host family of an MCP client id (a [`KNOWN_HOSTS`] entry or what the
350/// client announced); never the announced text itself.
351#[must_use]
352pub fn host_family(client: &str) -> &'static str {
353    let client = client.to_ascii_lowercase();
354    let family = match client.as_str() {
355        "claude" | "claude-code" | "claude-desktop" | "claude-ai" => "claude",
356        "codex" | "codex-cli" | "codex-mcp-client" => "codex",
357        "copilot" | "copilot-cli" | "vscode-copilot" | "vscode" => "copilot",
358        "gemini" | "gemini-cli" => "gemini",
359        "pi" | "oh-my-pi" | "omp" => "pi",
360        "roo" | "roo-code" => "roo",
361        "kilo" | "kilo-code" => "kilo",
362        "qwen" | "qwen-code" => "qwen",
363        other => other,
364    };
365    HOST_FAMILIES
366        .iter()
367        .copied()
368        .find(|f| *f == family)
369        .unwrap_or(OTHER)
370}
371
372/// Providers of `spend[]`.
373pub const KNOWN_PROVIDERS: &[&str] = &[
374    "anthropic",
375    "openai",
376    "google",
377    "microsoft",
378    "deepseek",
379    "meta",
380    "unknown",
381    OTHER,
382];
383
384/// K2 (H3): models of `spend[]`: the engine's embedded price table keys
385/// (and the contract fixture names); any other model id (fine-tunes, local
386/// or org-named models) is `other`. The engine's price table must be a
387/// subset (engine test).
388pub const KNOWN_MODELS: &[&str] = &[
389    "claude-fable-5",
390    "claude-opus-4.5",
391    "claude-sonnet-4.5",
392    "claude-haiku-4.5",
393    "claude-sonnet-4-5",
394    "claude-3.5-sonnet",
395    "claude-3-opus",
396    "claude-3-haiku",
397    "gpt-5",
398    "gpt-5.4",
399    "gpt-5.4-mini",
400    "gpt-5.4-nano",
401    "gemini-2.5-pro",
402    "gemini-2.5-flash",
403    "gemini-2.5-flash-lite",
404    "phi-4",
405    "phi-4-mini",
406    "deepseek-v3.2",
407    "deepseek-v3",
408    "llama-3.3-70b",
409    "llama-4-maverick",
410    "fallback-blended",
411    OTHER,
412];
413
414fn invalid(what: &str) -> ValidationError {
415    ValidationError::new(format!("instance metrics: invalid {what}"))
416}
417
418// ── closed-pattern strings ───────────────────────────────────────────────────
419
420macro_rules! closed_string {
421    ($(#[$doc:meta])* $name:ident, $check:path, $what:literal) => {
422        $(#[$doc])*
423        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
424        pub struct $name(String);
425
426        impl $name {
427            /// `value` when it matches the rule, else `None`.
428            pub fn new(value: &str) -> Option<Self> {
429                $check(value).then(|| Self(value.to_string()))
430            }
431
432            pub fn as_str(&self) -> &str {
433                &self.0
434            }
435        }
436
437        impl fmt::Display for $name {
438            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
439                f.write_str(&self.0)
440            }
441        }
442
443        impl Serialize for $name {
444            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
445                serializer.serialize_str(&self.0)
446            }
447        }
448
449        impl<'de> Deserialize<'de> for $name {
450            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
451                let raw = String::deserialize(deserializer)?;
452                Self::new(&raw).ok_or_else(|| serde::de::Error::custom(concat!("invalid ", $what)))
453            }
454        }
455    };
456}
457pub(crate) use closed_string;
458
459/// K2 H3: a closed table, not a shape. A custom or proxied MCP tool name
460/// that looks like an identifier (`acme_secret_project`) is refused, so the
461/// engine maps it to `other` ([`ToolName::or_other`]) before it is counted.
462fn is_tool(value: &str) -> bool {
463    KNOWN_TOOLS.contains(&value)
464}
465
466fn is_rule(value: &str) -> bool {
467    KNOWN_RULES.contains(&value)
468}
469
470fn is_filter(value: &str) -> bool {
471    KNOWN_FILTERS.contains(&value)
472}
473
474fn is_detector(value: &str) -> bool {
475    KNOWN_DETECTORS.contains(&value)
476}
477
478/// An MCP server name as the contract allows it: `^[a-z0-9][a-z0-9_-]{0,47}$`
479/// and never a run of 24+ letters or digits (token-like).
480pub fn is_mcp_server_name(value: &str) -> bool {
481    let mut bytes = value.bytes();
482    let shape = bytes
483        .next()
484        .is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
485        && value.len() <= 48
486        && bytes.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'-'));
487    let mut run = 0usize;
488    let token_like = value.bytes().any(|b| {
489        run = if b.is_ascii_alphanumeric() {
490            run + 1
491        } else {
492            0
493        };
494        run >= 24
495    });
496    shape && !token_like
497}
498
499/// v1 `name` rule (`[A-Za-z0-9._:/-]{1,64}`, never a path) and, since the
500/// K2 review, a closed table: a known host, provider or model, or `other`.
501/// A relative path, a host name, a fine-tune id or a key never passes.
502fn is_wire_name(value: &str) -> bool {
503    (1..=64).contains(&value.len())
504        && value
505            .bytes()
506            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b':' | b'/' | b'-'))
507        && !value.starts_with('/')
508        && !value.contains("..")
509        && !value.contains("//")
510        && (value == OTHER
511            || KNOWN_HOSTS.contains(&value)
512            || KNOWN_PROVIDERS.contains(&value)
513            || KNOWN_MODELS.contains(&value))
514}
515
516/// A known program, a host family or an MCP server name (the kind decides
517/// which one applies, [`SliceV2::validate`]).
518fn is_unregulated_name(value: &str) -> bool {
519    KNOWN_PROGRAMS.contains(&value) || HOST_FAMILIES.contains(&value) || is_mcp_server_name(value)
520}
521
522fn is_hour(value: &str) -> bool {
523    is_time(value) && value.ends_with(":00:00Z")
524}
525
526/// `YYYY-MM-DDTHH:MM:SSZ`.
527fn is_time(value: &str) -> bool {
528    let b = value.as_bytes();
529    b.len() == 20
530        && b[4] == b'-'
531        && b[7] == b'-'
532        && b[10] == b'T'
533        && b[13] == b':'
534        && b[16] == b':'
535        && b[19] == b'Z'
536        && [0, 1, 2, 3, 5, 6, 8, 9, 11, 12, 14, 15, 17, 18]
537            .iter()
538            .all(|&i| b[i].is_ascii_digit())
539        && lean_ctx_time::OffsetDateTime::parse_from_rfc3339(value).is_ok()
540}
541
542fn is_hex(value: &str, len: usize) -> bool {
543    value.len() == len
544        && value
545            .bytes()
546            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
547}
548
549fn is_hex16(value: &str) -> bool {
550    is_hex(value, 16)
551}
552
553fn is_hex32(value: &str) -> bool {
554    is_hex(value, 32)
555}
556
557fn is_hex128(value: &str) -> bool {
558    is_hex(value, 128)
559}
560
561fn is_engine_version(value: &str) -> bool {
562    (1..=32).contains(&value.len())
563        && value
564            .bytes()
565            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'+' | b'-'))
566}
567
568closed_string!(
569    /// A registered LeanCTX tool name ([`KNOWN_TOOLS`], `other` included).
570    ToolName,
571    is_tool,
572    "tool name"
573);
574closed_string!(
575    /// A policy member path or gateway rule id (`security.excluded_paths`).
576    RuleId,
577    is_rule,
578    "rule id"
579);
580closed_string!(
581    /// A model, provider or host name (v1 `name` rule, never a path).
582    WireName,
583    is_wire_name,
584    "name"
585);
586closed_string!(
587    /// A compression filter: a read mode or a pattern name (tool rule).
588    FilterName,
589    is_filter,
590    "filter name"
591);
592closed_string!(
593    /// A secret detector name (tool rule).
594    DetectorName,
595    is_detector,
596    "detector name"
597);
598closed_string!(
599    /// A known program, host or MCP server name (never a command line).
600    UnregulatedName,
601    is_unregulated_name,
602    "unregulated name"
603);
604closed_string!(
605    /// First 16 hex of HMAC-SHA256(workspace fingerprint key, secret).
606    Fingerprint,
607    is_hex16,
608    "fingerprint"
609);
610closed_string!(
611    /// A UTC hour start, `YYYY-MM-DDTHH:00:00Z`.
612    HourStamp,
613    is_hour,
614    "hour"
615);
616closed_string!(
617    /// A UTC time, second precision.
618    TimeStamp,
619    is_time,
620    "time"
621);
622closed_string!(
623    /// A Cloud vault id (32 lowercase hex characters).
624    VaultId,
625    is_hex32,
626    "vault id"
627);
628closed_string!(
629    /// `CARGO_PKG_VERSION` as the contract allows it.
630    EngineVersion,
631    is_engine_version,
632    "engine version"
633);
634closed_string!(
635    /// `hex(blake3(instance public key))[..16]`.
636    KeyId,
637    is_hex16,
638    "key id"
639);
640closed_string!(
641    /// An Ed25519 signature, lowercase hex.
642    SignatureHex,
643    is_hex128,
644    "signature"
645);
646
647impl ToolName {
648    /// `value` when it is a registered LeanCTX tool ([`KNOWN_TOOLS`]), else
649    /// `other`: a command line, a path, a proxied or custom MCP tool name
650    /// never becomes a tool name.
651    pub fn or_other(value: &str) -> Self {
652        if KNOWN_TOOLS.contains(&value) {
653            Self(value.to_string())
654        } else {
655            Self::other()
656        }
657    }
658
659    pub fn other() -> Self {
660        Self(OTHER.into())
661    }
662}
663
664impl FilterName {
665    pub fn or_other(value: &str) -> Self {
666        Self::new(value).unwrap_or_else(|| Self(OTHER.into()))
667    }
668}
669
670impl UnregulatedName {
671    pub fn other() -> Self {
672        Self(OTHER.into())
673    }
674}
675
676impl WireName {
677    pub fn other() -> Self {
678        Self(OTHER.into())
679    }
680}
681
682impl DetectorName {
683    pub fn or_other(value: &str) -> Self {
684        Self::new(value).unwrap_or_else(|| Self(OTHER.into()))
685    }
686}
687
688impl RuleId {
689    pub fn or_other(value: &str) -> Self {
690        Self::new(value).unwrap_or_else(Self::other)
691    }
692
693    pub fn other() -> Self {
694        Self(OTHER.into())
695    }
696}
697
698impl HourStamp {
699    /// The hour that holds `time` (UTC).
700    pub fn of(time: lean_ctx_time::UtcDateTime) -> Self {
701        Self(time.format("%Y-%m-%dT%H:00:00Z").to_string())
702    }
703
704    pub fn start(&self) -> lean_ctx_time::UtcDateTime {
705        lean_ctx_time::OffsetDateTime::parse_from_rfc3339(&self.0)
706            .map(|t| t.to_utc())
707            .unwrap_or_default()
708    }
709}
710
711impl TimeStamp {
712    pub fn at(&self) -> lean_ctx_time::UtcDateTime {
713        lean_ctx_time::OffsetDateTime::parse_from_rfc3339(&self.0)
714            .map(|t| t.to_utc())
715            .unwrap_or_default()
716    }
717}
718
719/// A schema id that serialises as exactly `ID` and accepts nothing else.
720macro_rules! schema_const {
721    ($name:ident, $id:expr) => {
722        #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
723        pub struct $name;
724
725        impl Serialize for $name {
726            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
727                serializer.serialize_str($id)
728            }
729        }
730
731        impl<'de> Deserialize<'de> for $name {
732            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
733                let raw = String::deserialize(deserializer)?;
734                (raw == $id)
735                    .then_some(Self)
736                    .ok_or_else(|| serde::de::Error::custom("wrong schema"))
737            }
738        }
739    };
740}
741pub(crate) use schema_const;
742
743schema_const!(HoursSchema, ENGINE_METRICS_SCHEMA);
744schema_const!(HoursAckSchema, ENGINE_METRICS_ACK_SCHEMA);
745
746// ── closed enums ─────────────────────────────────────────────────────────────
747
748/// `ctx_read` read modes (closed set; unknown modes count as `other`).
749#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
750#[serde(rename_all = "snake_case")]
751pub enum ReadMode {
752    Auto,
753    Full,
754    Map,
755    Signatures,
756    Diff,
757    Task,
758    Reference,
759    Aggressive,
760    Entropy,
761    Lines,
762    Other,
763}
764
765impl ReadMode {
766    /// The read mode a recorded mode name counts as: `lines:10-20` is
767    /// `lines`, anything outside the set is `other`.
768    pub fn of(mode: &str) -> Self {
769        let head = mode.split(':').next().unwrap_or(mode).trim();
770        match head {
771            "auto" => Self::Auto,
772            "full" => Self::Full,
773            "map" => Self::Map,
774            "signatures" => Self::Signatures,
775            "diff" => Self::Diff,
776            "task" => Self::Task,
777            "reference" => Self::Reference,
778            "aggressive" => Self::Aggressive,
779            "entropy" => Self::Entropy,
780            "lines" => Self::Lines,
781            _ => Self::Other,
782        }
783    }
784}
785
786#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
787#[serde(rename_all = "snake_case")]
788pub enum EngineOs {
789    Macos,
790    Linux,
791    Windows,
792}
793
794/// Policy level that set the rule.
795#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
796#[serde(rename_all = "snake_case")]
797pub enum PolicyLevel {
798    Org,
799    Workspace,
800    Vault,
801    Instance,
802}
803
804impl PolicyLevel {
805    /// How people read the level (Company › Workspace › Vault › Instance).
806    pub fn label(self) -> &'static str {
807        match self {
808            Self::Org => "Company",
809            Self::Workspace => "Workspace",
810            Self::Vault => "Vault",
811            Self::Instance => "Instance",
812        }
813    }
814
815    pub fn from_wire(value: &str) -> Option<Self> {
816        match value {
817            "org" => Some(Self::Org),
818            "workspace" => Some(Self::Workspace),
819            "vault" => Some(Self::Vault),
820            "instance" => Some(Self::Instance),
821            _ => None,
822        }
823    }
824}
825
826#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
827#[serde(rename_all = "snake_case")]
828pub enum RefusalReason {
829    TooOld,
830    Future,
831    BeforeSharing,
832    PolicyDenied,
833    VaultNotAllowed,
834    VaultUnknown,
835    UnattributedNotPersonal,
836}
837
838/// `unregulated[].kind`.
839#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
840#[serde(rename_all = "snake_case")]
841pub enum UnregulatedKind {
842    Program,
843    Host,
844    McpServer,
845}
846
847/// `sharing_state.state`.
848#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
849#[serde(rename_all = "snake_case")]
850pub enum SharingValue {
851    On,
852    Off,
853    NeedsConfirmation,
854}
855
856/// `sharing_state.plan_default`.
857#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
858#[serde(rename_all = "snake_case")]
859pub enum PlanDefault {
860    On,
861    Off,
862}
863
864// ── wire structs ─────────────────────────────────────────────────────────────
865
866/// The batch as signed: `hours_request` without `key_id` and `signature`.
867/// `cloud metrics preview --json` prints this.
868#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
869#[serde(deny_unknown_fields)]
870pub struct HoursBodyV2 {
871    pub schema: HoursSchema,
872    pub instance: EngineV2,
873    pub buckets: Vec<BucketV2>,
874}
875
876/// `POST /v1/metrics/hours` body.
877#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
878#[serde(deny_unknown_fields)]
879pub struct HoursRequestV2 {
880    pub schema: HoursSchema,
881    pub instance: EngineV2,
882    pub buckets: Vec<BucketV2>,
883    pub key_id: KeyId,
884    pub signature: SignatureHex,
885}
886
887#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
888#[serde(deny_unknown_fields)]
889pub struct EngineV2 {
890    pub instance_version: EngineVersion,
891    pub os: EngineOs,
892}
893
894#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
895#[serde(deny_unknown_fields)]
896pub struct BucketV2 {
897    pub hour: HourStamp,
898    pub rev: u32,
899    pub slices: Vec<SliceV2>,
900}
901
902#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
903#[serde(deny_unknown_fields)]
904pub struct SliceV2 {
905    pub vault: Option<VaultId>,
906    pub tokens: TokensV2,
907    pub savings: SavingsV2,
908    pub calls: CallsV2,
909    pub read_modes: BTreeMap<ReadMode, u64>,
910    pub tools: Vec<ToolRowV2>,
911    pub compression: CompressionV2,
912    pub ledger: LedgerV2,
913    pub guards: GuardsV2,
914    pub policy_blocks: Vec<BlockRowV2>,
915    pub refetch: Vec<RefetchRowV2>,
916    pub unregulated: Vec<UnregulatedRowV2>,
917    pub secret_hits: Vec<SecretRowV2>,
918    pub sessions: SessionsV2,
919    pub hosts: Vec<HostRowV2>,
920    pub spend: Vec<SpendRowV2>,
921    #[serde(default, skip_serializing_if = "Option::is_none")]
922    pub cloud: Option<CloudHourV2>,
923    #[serde(default, skip_serializing_if = "Option::is_none")]
924    pub gauges: Option<GaugesV2>,
925}
926
927#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
928#[serde(deny_unknown_fields)]
929pub struct TokensV2 {
930    pub input: u64,
931    pub output: u64,
932    pub saved: u64,
933}
934
935/// Saved tokens by trust label (K7) and LeanCTX's own overhead (K8).
936#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
937#[serde(deny_unknown_fields)]
938pub struct SavingsV2 {
939    pub measured: u64,
940    pub estimated: u64,
941    pub estimated_low: u64,
942    pub estimated_high: u64,
943    pub evidenced: u64,
944    pub overhead: u64,
945}
946
947#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
948#[serde(deny_unknown_fields)]
949pub struct CallsV2 {
950    pub tool_calls: u64,
951    pub cache_reads: u64,
952    pub cache_hits: u64,
953}
954
955#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
956#[serde(deny_unknown_fields)]
957pub struct ToolRowV2 {
958    pub tool: ToolName,
959    pub calls: u64,
960    pub saved: u64,
961}
962
963#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
964#[serde(deny_unknown_fields)]
965pub struct CompressionV2 {
966    pub original: u64,
967    pub compressed: u64,
968}
969
970/// Saved tokens by ledger kind (the ROI view).
971#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
972#[serde(deny_unknown_fields)]
973pub struct LedgerV2 {
974    pub reduction: u64,
975    pub cache_discount: u64,
976    pub correction: u64,
977    pub edit: u64,
978    pub other: u64,
979}
980
981#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
982#[serde(deny_unknown_fields)]
983pub struct GuardsV2 {
984    pub secrets_redacted: u64,
985    pub pii_redacted: u64,
986    pub injection_flags: u64,
987    pub content_withheld: u64,
988    pub paths_blocked: u64,
989    pub shell_blocked: u64,
990    pub partial_inspections: u64,
991}
992
993/// K12: refusals in force and refusals a monitor-mode rule would make.
994#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
995#[serde(deny_unknown_fields)]
996pub struct BlockRowV2 {
997    pub rule: RuleId,
998    pub blocked: u64,
999    pub would_block: u64,
1000}
1001
1002/// K10: outputs truncated and fetched back in full.
1003#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1004#[serde(deny_unknown_fields)]
1005pub struct RefetchRowV2 {
1006    pub filter: FilterName,
1007    pub truncated: u64,
1008    pub refetched: u64,
1009}
1010
1011/// K13: activity no rule covers.
1012#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1013#[serde(deny_unknown_fields)]
1014pub struct UnregulatedRowV2 {
1015    pub kind: UnregulatedKind,
1016    pub name: UnregulatedName,
1017    pub calls: u64,
1018}
1019
1020/// K21: a redacted secret as its workspace fingerprint, never its value.
1021#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1022#[serde(deny_unknown_fields)]
1023pub struct SecretRowV2 {
1024    pub detector: DetectorName,
1025    pub count: u64,
1026}
1027
1028/// X4 Cloud help in one hour.
1029#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1030#[serde(deny_unknown_fields)]
1031pub struct CloudHourV2 {
1032    pub knowledge_hits_referenced: u64,
1033    pub first_context_sessions: u64,
1034    pub first_context_ms_p50: Option<u64>,
1035    pub task_usage: Vec<TaskUsageV2>,
1036}
1037
1038/// Ledger usage while a session held a Cloud task (by number, never a title).
1039#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1040#[serde(deny_unknown_fields)]
1041pub struct TaskUsageV2 {
1042    pub number: u64,
1043    pub input_tokens: u64,
1044    pub output_tokens: u64,
1045    pub list_usd_micros: u64,
1046}
1047
1048pub const MAX_TASK_USAGE: usize = 64;
1049pub const MAX_FIRST_CONTEXT_MS: u64 = 3_600_000;
1050
1051#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1052#[serde(deny_unknown_fields)]
1053pub struct SessionsV2 {
1054    pub started: u64,
1055}
1056
1057#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1058#[serde(deny_unknown_fields)]
1059pub struct HostRowV2 {
1060    pub host: WireName,
1061    pub sessions: u64,
1062    pub tool_calls: u64,
1063}
1064
1065#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1066#[serde(deny_unknown_fields)]
1067pub struct SpendRowV2 {
1068    pub model: WireName,
1069    pub provider: WireName,
1070    pub requests: u64,
1071    pub input_tokens: u64,
1072    pub output_tokens: u64,
1073    pub cached_tokens: u64,
1074    pub usd_micros: u64,
1075}
1076
1077#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1078#[serde(deny_unknown_fields)]
1079pub struct GaugesV2 {
1080    #[serde(default, skip_serializing_if = "Option::is_none")]
1081    pub facts_current: Option<u64>,
1082}
1083
1084#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1085#[serde(deny_unknown_fields)]
1086pub struct HoursAckV2 {
1087    pub schema: HoursAckSchema,
1088    pub accepted: u32,
1089    pub unchanged: u32,
1090    pub refused: Vec<RefusalV2>,
1091    pub sharing: SharingStateV2,
1092}
1093
1094#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1095#[serde(deny_unknown_fields)]
1096pub struct RefusalV2 {
1097    pub hour: HourStamp,
1098    pub vault: Option<VaultId>,
1099    pub reason: RefusalReason,
1100    pub level: Option<PolicyLevel>,
1101}
1102
1103/// The policy part of a sharing state.
1104#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1105#[serde(deny_unknown_fields)]
1106pub struct SharingPolicyValueV2 {
1107    pub value: bool,
1108    pub level: PolicyLevel,
1109}
1110
1111/// `sharing_state`: `GET /v1/metrics/sharing`, the confirm answer, and the
1112/// `sharing` of every ack.
1113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1114#[serde(deny_unknown_fields)]
1115pub struct SharingStateV2 {
1116    pub state: SharingValue,
1117    pub plan_default: PlanDefault,
1118    pub policy: Option<SharingPolicyValueV2>,
1119    pub confirmed_at: Option<TimeStamp>,
1120    pub since: Option<TimeStamp>,
1121}
1122
1123// ── checks ───────────────────────────────────────────────────────────────────
1124
1125fn counts_ok(values: impl IntoIterator<Item = u64>) -> bool {
1126    values.into_iter().all(|n| n <= MAX_COUNT)
1127}
1128
1129fn unique<'a>(names: impl IntoIterator<Item = &'a str>) -> bool {
1130    let mut seen = BTreeSet::new();
1131    names.into_iter().all(|n| seen.insert(n))
1132}
1133
1134impl SliceV2 {
1135    /// Every counter of the slice, for the 2^53 bound and activity checks.
1136    pub fn counters(&self) -> Vec<u64> {
1137        let t = &self.tokens;
1138        let s = &self.savings;
1139        let c = &self.calls;
1140        let l = &self.ledger;
1141        let g = &self.guards;
1142        let mut all = vec![
1143            t.input,
1144            t.output,
1145            t.saved,
1146            s.measured,
1147            s.estimated,
1148            s.estimated_low,
1149            s.estimated_high,
1150            s.evidenced,
1151            s.overhead,
1152            c.tool_calls,
1153            c.cache_reads,
1154            c.cache_hits,
1155            self.compression.original,
1156            self.compression.compressed,
1157            l.reduction,
1158            l.cache_discount,
1159            l.correction,
1160            l.edit,
1161            l.other,
1162            g.secrets_redacted,
1163            g.pii_redacted,
1164            g.injection_flags,
1165            g.content_withheld,
1166            g.paths_blocked,
1167            g.shell_blocked,
1168            g.partial_inspections,
1169            self.sessions.started,
1170        ];
1171        all.extend(self.read_modes.values().copied());
1172        all.extend(self.tools.iter().flat_map(|r| [r.calls, r.saved]));
1173        all.extend(
1174            self.policy_blocks
1175                .iter()
1176                .flat_map(|r| [r.blocked, r.would_block]),
1177        );
1178        all.extend(self.refetch.iter().flat_map(|r| [r.truncated, r.refetched]));
1179        all.extend(self.unregulated.iter().map(|r| r.calls));
1180        if let Some(a) = &self.cloud {
1181            all.extend([a.knowledge_hits_referenced, a.first_context_sessions]);
1182            all.extend(a.first_context_ms_p50);
1183            all.extend(
1184                a.task_usage
1185                    .iter()
1186                    .flat_map(|t| [t.number, t.input_tokens, t.output_tokens, t.list_usd_micros]),
1187            );
1188        }
1189        all.extend(self.secret_hits.iter().map(|r| r.count));
1190        all.extend(self.hosts.iter().flat_map(|r| [r.sessions, r.tool_calls]));
1191        all.extend(self.spend.iter().flat_map(|r| {
1192            [
1193                r.requests,
1194                r.input_tokens,
1195                r.output_tokens,
1196                r.cached_tokens,
1197                r.usd_micros,
1198            ]
1199        }));
1200        all
1201    }
1202
1203    /// Whether anything happened (the gauge is a level, not activity; the
1204    /// overhead alone is not activity either).
1205    pub fn has_activity(&self) -> bool {
1206        let mut counters = self.counters();
1207        counters.remove(8);
1208        counters.into_iter().any(|n| n > 0)
1209    }
1210
1211    pub fn validate(&self) -> Result<(), ValidationError> {
1212        if self.tools.len() > MAX_TOOLS
1213            || self.policy_blocks.len() > MAX_POLICY_BLOCKS
1214            || self.refetch.len() > MAX_REFETCH
1215            || self.unregulated.len() > MAX_UNREGULATED
1216            || self.secret_hits.len() > MAX_SECRET_HITS
1217            || self.hosts.len() > MAX_HOSTS
1218            || self.spend.len() > MAX_SPEND
1219        {
1220            return Err(invalid("slice: too many rows"));
1221        }
1222        if !unique(self.tools.iter().map(|r| r.tool.as_str()))
1223            || !unique(self.policy_blocks.iter().map(|r| r.rule.as_str()))
1224            || !unique(self.refetch.iter().map(|r| r.filter.as_str()))
1225            || !unique(self.hosts.iter().map(|r| r.host.as_str()))
1226        {
1227            return Err(invalid("slice: duplicate row name"));
1228        }
1229        let mut pairs = BTreeSet::new();
1230        if !self
1231            .spend
1232            .iter()
1233            .all(|r| pairs.insert((r.model.as_str(), r.provider.as_str())))
1234        {
1235            return Err(invalid("slice: duplicate spend row"));
1236        }
1237        let mut unregulated = BTreeSet::new();
1238        if !self
1239            .unregulated
1240            .iter()
1241            .all(|r| unregulated.insert((r.kind, r.name.as_str())))
1242        {
1243            return Err(invalid("slice: duplicate unregulated row"));
1244        }
1245        if !unique(self.secret_hits.iter().map(|r| r.detector.as_str())) {
1246            return Err(invalid("slice: duplicate secret row"));
1247        }
1248        for row in &self.unregulated {
1249            let name = row.name.as_str();
1250            let fits = match row.kind {
1251                UnregulatedKind::Program => KNOWN_PROGRAMS.contains(&name),
1252                UnregulatedKind::Host => HOST_FAMILIES.contains(&name),
1253                UnregulatedKind::McpServer => is_mcp_server_name(name),
1254            };
1255            if !fits {
1256                return Err(invalid("slice: unregulated name of another kind"));
1257            }
1258        }
1259        if let Some(a) = &self.cloud {
1260            let sorted = a.task_usage.windows(2).all(|w| w[0].number < w[1].number);
1261            if a.task_usage.len() > MAX_TASK_USAGE
1262                || !sorted
1263                || a.task_usage.iter().any(|t| t.number == 0)
1264                || a.first_context_ms_p50
1265                    .is_some_and(|ms| ms > MAX_FIRST_CONTEXT_MS)
1266            {
1267                return Err(invalid("slice: cloud"));
1268            }
1269        }
1270        let gauge = self.gauges.and_then(|g| g.facts_current).unwrap_or(0);
1271        if !counts_ok(self.counters()) || gauge > MAX_COUNT {
1272            return Err(invalid("slice: count beyond 2^53"));
1273        }
1274        Ok(())
1275    }
1276}
1277
1278impl BucketV2 {
1279    pub fn validate(&self) -> Result<(), ValidationError> {
1280        if self.rev == 0 {
1281            return Err(invalid("bucket rev"));
1282        }
1283        if self.slices.is_empty() || self.slices.len() > MAX_SLICES {
1284            return Err(invalid("bucket: 1-33 slices"));
1285        }
1286        let mut vaults = BTreeSet::new();
1287        for slice in &self.slices {
1288            if !vaults.insert(slice.vault.as_ref().map(VaultId::as_str)) {
1289                return Err(invalid("bucket: duplicate vault"));
1290            }
1291            slice.validate()?;
1292        }
1293        Ok(())
1294    }
1295}
1296
1297impl HoursBodyV2 {
1298    pub fn validate(&self) -> Result<(), ValidationError> {
1299        if self.buckets.is_empty() || self.buckets.len() > MAX_BUCKETS {
1300            return Err(invalid("request: 1-168 buckets"));
1301        }
1302        if !unique(self.buckets.iter().map(|b| b.hour.as_str())) {
1303            return Err(invalid("request: duplicate hour"));
1304        }
1305        self.buckets.iter().try_for_each(BucketV2::validate)
1306    }
1307
1308    /// The bytes the signature covers: the request with `key_id` and
1309    /// without `signature` (the `worker_register` scheme).
1310    pub fn signing_input(&self, key_id: &KeyId) -> Result<Vec<u8>, ValidationError> {
1311        let mut value = serde_json::to_value(self)
1312            .map_err(|e| ValidationError::new(format!("instance metrics: encode: {e}")))?;
1313        value["key_id"] = serde_json::Value::String(key_id.as_str().to_string());
1314        super::signing_input(ENGINE_METRICS_DOMAIN, &value)
1315    }
1316
1317    pub fn signed(self, key_id: KeyId, signature: SignatureHex) -> HoursRequestV2 {
1318        HoursRequestV2 {
1319            schema: self.schema,
1320            instance: self.instance,
1321            buckets: self.buckets,
1322            key_id,
1323            signature,
1324        }
1325    }
1326}
1327
1328impl HoursRequestV2 {
1329    /// The signed part.
1330    pub fn body(&self) -> HoursBodyV2 {
1331        HoursBodyV2 {
1332            schema: self.schema,
1333            instance: self.instance.clone(),
1334            buckets: self.buckets.clone(),
1335        }
1336    }
1337
1338    pub fn validate(&self) -> Result<(), ValidationError> {
1339        self.body().validate()
1340    }
1341}
1342
1343#[cfg(test)]
1344mod tests {
1345    use super::*;
1346
1347    #[test]
1348    fn names_follow_their_closed_rules() {
1349        assert!(ToolName::new("ctx_read").is_some());
1350        for bad in ["rm -rf /", "/etc/passwd", "Ctx_Read", "ctx-read", "", "a b"] {
1351            assert!(ToolName::new(bad).is_none(), "{bad}");
1352            assert_eq!(ToolName::or_other(bad).as_str(), OTHER);
1353        }
1354        for unknown in ["acme_secret_project", "a", "ctx_reader"] {
1355            assert!(ToolName::new(unknown).is_none(), "{unknown}");
1356            assert_eq!(ToolName::or_other(unknown).as_str(), OTHER);
1357        }
1358        assert!(ToolName::new(OTHER).is_some());
1359        assert!(RuleId::new("sharing.share_instance_metrics").is_some());
1360        assert!(RuleId::new("gateway.tool_denied").is_some());
1361        assert!(RuleId::new("gateway.destination").is_some());
1362        assert!(RuleId::new("gateway.egress").is_some());
1363        assert_eq!(host_family("claude-code"), "claude");
1364        assert_eq!(host_family("Cursor"), "cursor");
1365        assert_eq!(host_family("oh-my-pi"), "pi");
1366        assert_eq!(host_family("acme-internal-agent"), OTHER);
1367        assert!(HOST_FAMILIES.iter().all(|f| is_unregulated_name(f)));
1368        for bad in ["blocked because of /x", "a.b.c", "Security.pii", ".x", "x."] {
1369            assert!(RuleId::new(bad).is_none(), "{bad}");
1370        }
1371        assert!(WireName::new("claude-sonnet-4-5").is_some());
1372        assert!(WireName::new("anthropic").is_some());
1373        assert!(WireName::new("claude-code").is_some());
1374        for bad in [
1375            "/Users/me",
1376            "a//b",
1377            "../x",
1378            "with space",
1379            "",
1380            "anthropic/claude",
1381            "ada-macbook.local",
1382        ] {
1383            assert!(WireName::new(bad).is_none(), "{bad}");
1384        }
1385        assert_eq!(ToolName::or_other("ctx_read").as_str(), "ctx_read");
1386        assert_eq!(ToolName::or_other("acme_internal_db").as_str(), OTHER);
1387        assert!(UnregulatedName::new("terraform").is_some());
1388        assert!(
1389            UnregulatedName::new("github").is_some(),
1390            "an MCP server name"
1391        );
1392        assert!(!is_mcp_server_name(&"a".repeat(30)), "token-like");
1393        assert_eq!(RuleId::or_other("custom.rule").as_str(), OTHER);
1394        assert_eq!(FilterName::or_other("cargo_test").as_str(), OTHER);
1395        assert_eq!(DetectorName::or_other("Generic").as_str(), OTHER);
1396        for bad in [
1397            "terraform apply -auto-approve",
1398            "/usr/bin/terraform",
1399            "a..b",
1400            "Git",
1401        ] {
1402            assert!(UnregulatedName::new(bad).is_none(), "{bad}");
1403        }
1404        assert!(Fingerprint::new("9c1e4b7a02d3f658").is_some());
1405        assert!(Fingerprint::new("[REDACTED:AWS key]").is_none());
1406        assert!(HourStamp::new("2026-10-26T17:00:00Z").is_some());
1407        for bad in [
1408            "2026-10-26T17:05:00Z",
1409            "2026-10-26T17:00:00+01:00",
1410            "2026-13-26T17:00:00Z",
1411        ] {
1412            assert!(HourStamp::new(bad).is_none(), "{bad}");
1413        }
1414        assert!(TimeStamp::new("2026-10-26T15:12:40Z").is_some());
1415        assert_eq!(ReadMode::of("lines:10-20"), ReadMode::Lines);
1416        assert_eq!(ReadMode::of("signatures"), ReadMode::Signatures);
1417        assert_eq!(ReadMode::of("something new"), ReadMode::Other);
1418    }
1419
1420    #[test]
1421    fn free_text_cannot_be_deserialised_into_any_field() {
1422        let tool = serde_json::from_str::<ToolRowV2>(
1423            r#"{"tool":"cat ~/.ssh/id_rsa","calls":1,"saved":0}"#,
1424        );
1425        assert!(tool.is_err());
1426        let extra =
1427            serde_json::from_str::<TokensV2>(r#"{"input":1,"output":1,"saved":0,"prompt":"x"}"#);
1428        assert!(extra.is_err());
1429        let schema = serde_json::from_str::<HoursSchema>(r#""leanctx.cloud.instance-metrics/v3""#);
1430        assert!(schema.is_err());
1431    }
1432}