1use super::{SemanticIntentCandidate, SemanticObservation, target_fingerprint_digest};
8use serde::{Deserialize, Serialize};
9use serde_json::{Value, json};
10use sha2::{Digest, Sha256};
11use std::collections::BTreeSet;
12use std::fmt;
13use url::Url;
14
15pub const KNOWLEDGE_SCHEMA_VERSION: u32 = 1;
16pub const MAX_KNOWLEDGE_RECORDS: usize = 256;
17const MAX_RECORD_ID_BYTES: usize = 128;
18const MAX_SCOPE_VALUE_BYTES: usize = 256;
19const MAX_ROLE_BYTES: usize = 64;
20const MAX_TIMESTAMP_BYTES: usize = 64;
21const MAX_LANDMARKS: usize = 32;
22const MAX_HISTORY: usize = 32;
23const MAX_RETRIEVAL_SIGNALS: usize = 16;
24const MAX_BACKEND_CAPABILITIES: usize = 32;
25const MAX_DATA_BYTES: usize = 16 * 1024;
26const MAX_RECORD_BYTES: usize = 64 * 1024;
27const MAX_EXTENSION_ID_BYTES: usize = 128;
28const MAX_JSON_DEPTH: usize = 8;
29const MAX_JSON_OBJECT_ENTRIES: usize = 64;
30const MAX_JSON_ARRAY_ENTRIES: usize = 64;
31const MAX_JSON_STRING_BYTES: usize = 4096;
32const MAX_RETRIEVAL_QUERY_VALUES: usize = 32;
33const MAX_RETRIEVAL_QUERY_VALUE_BYTES: usize = 256;
34const MAX_WORKSPACE_ID_BYTES: usize = 128;
35#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct KnowledgeLookupContext {
38 pub origin: String,
39 pub path: String,
40 pub profile_scope: KnowledgeProfileScope,
41 pub profile_key: Option<String>,
42 pub locale: Option<String>,
43 pub tenant_key: Option<String>,
44 pub browser_family: String,
45 pub browser_version: Option<String>,
46 pub glass_schema_version: u32,
47 pub policy_preset: String,
48 pub landmarks: Vec<String>,
49 pub now_epoch_seconds: i64,
50 pub current_revision: u64,
51 pub surface_kind: Option<KnowledgeSurfaceKind>,
52 pub backend_kind: Option<KnowledgeBackendKind>,
53 pub backend_capabilities: Vec<KnowledgeBackendCapability>,
55 pub current_extension_id: Option<String>,
56 pub workspace_id: Option<String>,
59 pub workspace_generation: Option<u64>,
60}
61
62#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct KnowledgeLookupOptions {
66 pub profile_scope: KnowledgeProfileScope,
67 pub profile_key: Option<String>,
68 pub locale: Option<String>,
69 pub tenant_key: Option<String>,
70 pub browser_family: String,
71 pub browser_version: Option<String>,
72 pub glass_schema_version: u32,
73 pub policy_preset: String,
74 pub now_epoch_seconds: i64,
75 pub current_revision: Option<u64>,
76 pub current_extension_id: Option<String>,
77 pub surface_kind: Option<KnowledgeSurfaceKind>,
78 pub backend_kind: Option<KnowledgeBackendKind>,
79 pub backend_capabilities: Vec<KnowledgeBackendCapability>,
80 pub workspace_id: Option<String>,
81 pub workspace_generation: Option<u64>,
82}
83
84#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct KnowledgeRecordBuildOptions {
87 pub record_id: String,
88 pub scope: KnowledgeScope,
89 pub glass_version: String,
90 pub observed_at: String,
91 pub surface: KnowledgeSurfaceProvenance,
92 pub backend: KnowledgeBackendProvenance,
93 pub portability: KnowledgePortability,
94 pub current_validation: KnowledgeCurrentValidation,
95}
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub struct KnowledgeLearningPolicy {
100 pub required_verified_uses: u32,
102}
103
104impl Default for KnowledgeLearningPolicy {
105 fn default() -> Self {
106 Self {
107 required_verified_uses: 2,
108 }
109 }
110}
111
112impl KnowledgeLearningPolicy {
113 pub fn validate(self) -> Result<(), KnowledgeValidationError> {
114 if self.required_verified_uses == 0 || self.required_verified_uses > 32 {
115 return Err(KnowledgeValidationError::new(
116 "requiredVerifiedUses",
117 "must be between 1 and 32",
118 ));
119 }
120 Ok(())
121 }
122}
123
124#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct KnowledgeVerifiedWorkflowEvidence {
129 pub guarded_revision: u64,
130 pub successful: bool,
131 pub postcondition_verified: bool,
132 pub evidence_quality: KnowledgeEvidenceQuality,
133 pub observed_at: String,
134 pub compatibility_key: String,
136 pub private_context: bool,
138 pub incognito: bool,
139}
140
141impl KnowledgeVerifiedWorkflowEvidence {
142 pub fn validate_against(
143 &self,
144 observation: &SemanticObservation,
145 ) -> Result<(), KnowledgeValidationError> {
146 if self.private_context || self.incognito {
147 return Err(KnowledgeValidationError::new(
148 "privacy",
149 "private or incognito contexts cannot create persistent knowledge",
150 ));
151 }
152 if !self.successful || !self.postcondition_verified {
153 return Err(KnowledgeValidationError::new(
154 "workflow",
155 "learning requires a successful workflow and verified postcondition",
156 ));
157 }
158 if self.guarded_revision == 0 || self.guarded_revision != observation.revision {
159 return Err(KnowledgeValidationError::new(
160 "guardedRevision",
161 "workflow witness must guard the fresh observation revision",
162 ));
163 }
164 if self.evidence_quality == KnowledgeEvidenceQuality::None {
165 return Err(KnowledgeValidationError::new(
166 "evidenceQuality",
167 "workflow witness requires non-empty evidence quality",
168 ));
169 }
170 validate_timestamp("observedAt", &self.observed_at)?;
171 validate_text(
172 "compatibilityKey",
173 &self.compatibility_key,
174 MAX_SCOPE_VALUE_BYTES,
175 false,
176 )?;
177 validate_public_text("compatibilityKey", &self.compatibility_key)?;
178 Ok(())
179 }
180}
181
182#[derive(Debug, Clone)]
184pub struct KnowledgeLearningRequest<'a> {
185 pub observation: &'a SemanticObservation,
186 pub build: KnowledgeRecordBuildOptions,
187 pub evidence: KnowledgeVerifiedWorkflowEvidence,
188 pub policy: KnowledgeLearningPolicy,
189}
190
191#[derive(Debug, Clone, PartialEq, Eq)]
193pub struct KnowledgeLearningResult {
194 pub record_id: String,
195 pub confidence: KnowledgeConfidence,
196 pub verification_count: u32,
197 pub promoted: bool,
198 pub created: bool,
199}
200
201impl KnowledgeLookupContext {
202 pub fn from_observation(
205 observation: &SemanticObservation,
206 options: KnowledgeLookupOptions,
207 ) -> Result<Self, KnowledgeValidationError> {
208 let url = Url::parse(&observation.route.url).map_err(|error| {
209 KnowledgeValidationError::new("observation.route.url", format!("invalid URL: {error}"))
210 })?;
211 let origin = url.origin().ascii_serialization();
212 let path = if url.path().is_empty() {
213 "/".to_string()
214 } else {
215 url.path().to_string()
216 };
217 let mut landmarks = BTreeSet::new();
218 landmarks.insert(
219 serde_json::to_string(&observation.page.kind).map_err(|error| {
220 KnowledgeValidationError::new("observation.page.kind", error.to_string())
221 })?,
222 );
223 for region in &observation.regions {
224 landmarks.insert(serde_json::to_string(®ion.kind).map_err(|error| {
225 KnowledgeValidationError::new("observation.regions.kind", error.to_string())
226 })?);
227 }
228 if observation.revision == 0 {
229 return Err(KnowledgeValidationError::new(
230 "observation.revision",
231 "must be positive",
232 ));
233 }
234 if options
235 .current_revision
236 .is_some_and(|revision| revision != observation.revision)
237 {
238 return Err(KnowledgeValidationError::new(
239 "currentRevision",
240 "must match the fresh observation revision",
241 ));
242 }
243 let current_revision = observation.revision;
244 let current_extension_id = options.current_extension_id.clone();
245 if options.surface_kind == Some(KnowledgeSurfaceKind::ExtensionDefined)
246 && current_extension_id.is_none()
247 {
248 return Err(KnowledgeValidationError::new(
249 "currentExtensionId",
250 "extension-defined contexts require an extension identifier",
251 ));
252 }
253 validate_workspace_scope(
254 "workspaceId",
255 options.workspace_id.as_deref(),
256 options.workspace_generation,
257 )?;
258 if options.surface_kind != Some(KnowledgeSurfaceKind::ExtensionDefined)
259 && current_extension_id.is_some()
260 {
261 return Err(KnowledgeValidationError::new(
262 "currentExtensionId",
263 "extension identifiers are only valid for extension-defined contexts",
264 ));
265 }
266 let workspace_id = options.workspace_id.clone();
267 let workspace_generation = options.workspace_generation;
268 if let Some(extension_id) = ¤t_extension_id {
269 validate_text(
270 "currentExtensionId",
271 extension_id,
272 MAX_EXTENSION_ID_BYTES,
273 false,
274 )?;
275 validate_public_text("currentExtensionId", extension_id)?;
276 }
277 validate_backend_capabilities("backendCapabilities", &options.backend_capabilities)?;
278 Ok(Self {
279 origin,
280 path,
281 profile_scope: options.profile_scope,
282 profile_key: options.profile_key,
283 locale: options.locale,
284 tenant_key: options.tenant_key,
285 browser_family: options.browser_family,
286 browser_version: options.browser_version,
287 glass_schema_version: options.glass_schema_version,
288 policy_preset: options.policy_preset,
289 landmarks: landmarks
290 .into_iter()
291 .map(|landmark| landmark.trim_matches('"').to_string())
292 .collect(),
293 now_epoch_seconds: options.now_epoch_seconds,
294 surface_kind: options.surface_kind,
295 backend_kind: options.backend_kind,
296 backend_capabilities: options.backend_capabilities,
297 current_extension_id,
298 current_revision,
299 workspace_id,
300 workspace_generation,
301 })
302 }
303 pub fn from_observation_with_portability(
306 observation: &SemanticObservation,
307 options: KnowledgeLookupOptions,
308 surface_kind: KnowledgeSurfaceKind,
309 backend_kind: KnowledgeBackendKind,
310 backend_capabilities: Vec<KnowledgeBackendCapability>,
311 current_extension_id: Option<String>,
312 ) -> Result<Self, KnowledgeValidationError> {
313 validate_backend_capabilities("backendCapabilities", &backend_capabilities)?;
314 let mut context = Self::from_observation(observation, options)?;
315 context.surface_kind = Some(surface_kind);
316 context.backend_kind = Some(backend_kind);
317 context.backend_capabilities = backend_capabilities;
318 context.current_extension_id = current_extension_id;
319 if context.surface_kind == Some(KnowledgeSurfaceKind::ExtensionDefined)
320 && context.current_extension_id.is_none()
321 {
322 return Err(KnowledgeValidationError::new(
323 "currentExtensionId",
324 "extension-defined contexts require an extension identifier",
325 ));
326 }
327 if context.surface_kind != Some(KnowledgeSurfaceKind::ExtensionDefined)
328 && context.current_extension_id.is_some()
329 {
330 return Err(KnowledgeValidationError::new(
331 "currentExtensionId",
332 "extension identifiers are only valid for extension-defined contexts",
333 ));
334 }
335 if let Some(extension_id) = &context.current_extension_id {
336 validate_text(
337 "currentExtensionId",
338 extension_id,
339 MAX_EXTENSION_ID_BYTES,
340 false,
341 )?;
342 validate_public_text("currentExtensionId", extension_id)?;
343 }
344 Ok(context)
345 }
346}
347
348#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
350#[serde(rename_all = "camelCase")]
351pub enum KnowledgeSignalKind {
352 OriginMatch,
353 PathMatch,
354 ProfileScopeMatch,
355 WorkspaceMatch,
356 LocaleMatch,
357 TenantMatch,
358 BrowserMatch,
359 SchemaMatch,
360 PolicyMatch,
361 LandmarkMatch,
362 FreshnessMatch,
363}
364
365#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
367#[serde(rename_all = "camelCase")]
368pub struct KnowledgeAssessmentSignal {
369 pub kind: KnowledgeSignalKind,
370 pub detail: String,
371}
372
373#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
375#[serde(rename_all = "camelCase")]
376pub enum KnowledgeAssessmentStatus {
377 Eligible,
378 OutOfScope,
379 Stale,
380 Contradicted,
381 Quarantined,
382}
383
384#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
387#[serde(rename_all = "camelCase")]
388pub struct KnowledgeAssessment {
389 pub record_id: String,
390 pub status: KnowledgeAssessmentStatus,
391 #[serde(default, skip_serializing_if = "Vec::is_empty")]
392 pub signals: Vec<KnowledgeAssessmentSignal>,
393 #[serde(default, skip_serializing_if = "Vec::is_empty")]
394 pub conflicts: Vec<String>,
395 #[serde(default, skip_serializing_if = "Vec::is_empty")]
396 pub missing_landmarks: Vec<String>,
397 #[serde(default, skip_serializing_if = "Option::is_none")]
398 pub age_seconds: Option<i64>,
399}
400
401#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
403#[serde(rename_all = "camelCase")]
404pub enum KnowledgeObservationMode {
405 FreshOnly,
406 Assessed,
407}
408
409#[derive(Debug, Clone, Serialize, Deserialize)]
412#[serde(rename_all = "camelCase")]
413pub struct KnowledgeObservationReport {
414 pub observation: SemanticObservation,
415 pub mode: KnowledgeObservationMode,
416 #[serde(default, skip_serializing_if = "Vec::is_empty")]
417 pub assessments: Vec<KnowledgeAssessment>,
418 #[serde(default, skip_serializing_if = "Vec::is_empty")]
419 pub eligible_record_ids: Vec<String>,
420 #[serde(default, skip_serializing_if = "Vec::is_empty")]
421 pub stale_record_ids: Vec<String>,
422 #[serde(default, skip_serializing_if = "Vec::is_empty")]
423 pub out_of_scope_record_ids: Vec<String>,
424}
425
426#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
428#[serde(rename_all = "camelCase")]
429pub enum KnowledgeRecordKind {
430 PageFamily,
431 RegionModel,
432 TargetFingerprint,
433 RouteTransition,
434 WorkflowEntryPoint,
435 VerifiedPostcondition,
436 ExtractionShape,
437 InvalidationRule,
438}
439
440#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
442#[serde(rename_all = "lowercase")]
443pub enum KnowledgeConfidence {
444 Candidate,
445 Observed,
446 Verified,
447 Stale,
448 Contradicted,
449 Quarantined,
450}
451
452#[derive(Debug, Clone, PartialEq, Eq)]
455pub struct KnowledgeScopeSelector {
456 pub origin: String,
457 pub profile_scope: KnowledgeProfileScope,
458 pub profile_key: Option<String>,
459 pub workspace_id: Option<String>,
460 pub workspace_generation: Option<u64>,
461}
462
463impl KnowledgeScopeSelector {
464 pub fn new(
465 origin: String,
466 profile_scope: KnowledgeProfileScope,
467 profile_key: Option<String>,
468 workspace_id: Option<String>,
469 workspace_generation: Option<u64>,
470 ) -> Result<Self, KnowledgeValidationError> {
471 let selector = Self {
472 origin,
473 profile_scope,
474 profile_key,
475 workspace_id,
476 workspace_generation,
477 };
478 selector.validate()?;
479 Ok(selector)
480 }
481
482 pub fn validate(&self) -> Result<(), KnowledgeValidationError> {
484 validate_text("selector.origin", &self.origin, 2048, false)?;
485 validate_public_text("selector.origin", &self.origin)?;
486 let url = Url::parse(&self.origin).map_err(|error| {
487 KnowledgeValidationError::new("selector.origin", format!("invalid origin: {error}"))
488 })?;
489 if url.origin().ascii_serialization() != self.origin {
490 return Err(KnowledgeValidationError::new(
491 "selector.origin",
492 "must be an exact serialized URL origin",
493 ));
494 }
495 if let Some(profile_key) = self.profile_key.as_deref() {
496 validate_text(
497 "selector.profileKey",
498 profile_key,
499 MAX_SCOPE_VALUE_BYTES,
500 false,
501 )?;
502 validate_public_text("selector.profileKey", profile_key)?;
503 }
504 match self.profile_scope {
505 KnowledgeProfileScope::ProfileBound if self.profile_key.is_none() => {
506 return Err(KnowledgeValidationError::new(
507 "selector.profileKey",
508 "is required for profileBound access",
509 ));
510 }
511 KnowledgeProfileScope::Anonymous if self.profile_key.is_some() => {
512 return Err(KnowledgeValidationError::new(
513 "selector.profileKey",
514 "must be absent for anonymous access",
515 ));
516 }
517 _ => {}
518 }
519 validate_workspace_scope(
520 "selector.workspaceId",
521 self.workspace_id.as_deref(),
522 self.workspace_generation,
523 )?;
524 if let Some(workspace_id) = self.workspace_id.as_deref() {
525 validate_public_text("selector.workspaceId", workspace_id)?;
526 }
527 Ok(())
528 }
529
530 pub(crate) fn matches(&self, scope: &KnowledgeScope) -> bool {
531 self.origin == scope.origin
532 && self.profile_scope == scope.profile_scope
533 && self.profile_key == scope.profile_key
534 && self.workspace_id == scope.workspace_id
535 && self.workspace_generation == scope.workspace_generation
536 }
537}
538
539#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
541#[serde(rename_all = "camelCase")]
542pub struct KnowledgeScope {
543 pub origin: String,
544 pub path_pattern: String,
545 pub profile_scope: KnowledgeProfileScope,
546 #[serde(default, skip_serializing_if = "Option::is_none")]
547 pub profile_key: Option<String>,
548 #[serde(default, skip_serializing_if = "Option::is_none")]
549 pub locale: Option<String>,
550 #[serde(default, skip_serializing_if = "Option::is_none")]
551 pub tenant_key: Option<String>,
552 pub browser_family: String,
553 #[serde(default, skip_serializing_if = "Option::is_none")]
554 pub browser_version_range: Option<String>,
555 pub glass_schema_version: u32,
556 pub policy_preset: String,
557 #[serde(default, skip_serializing_if = "Option::is_none")]
560 pub workspace_id: Option<String>,
561 #[serde(default, skip_serializing_if = "Option::is_none")]
562 pub workspace_generation: Option<u64>,
563}
564
565#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
568#[serde(rename_all = "camelCase")]
569pub enum KnowledgeProfileScope {
570 Anonymous,
571 Authenticated,
572 ProfileBound,
573}
574#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
575#[serde(rename_all = "camelCase", deny_unknown_fields)]
576pub struct KnowledgeSurfaceProvenance {
577 pub kind: KnowledgeSurfaceKind,
578 pub understanding: KnowledgeUnderstandingLevel,
579 pub coverage: KnowledgeSurfaceCoverage,
580 #[serde(default, skip_serializing_if = "Option::is_none")]
581 pub extension_id: Option<String>,
582}
583
584#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
587#[serde(rename_all = "camelCase")]
588pub enum KnowledgeSurfaceKind {
589 Document,
590 Accessibility,
591 ShadowDocument,
592 FrameDocument,
593 Svg,
594 Canvas2d,
595 Webgl,
596 Webgpu,
597 EmbeddedDocument,
598 Pdf,
599 EmbeddedPdf,
600 Media,
601 Terminal,
602 RemoteApplication,
603 BrowserNative,
604 ExtensionDefined,
605 Unknown,
606 #[default]
607 Opaque,
608}
609
610#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
612#[serde(rename_all = "camelCase")]
613pub enum KnowledgeUnderstandingLevel {
614 Opaque,
615 Inferred,
616 Partial,
617 Strong,
618 TaskCompilable,
619}
620
621#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
623#[serde(rename_all = "camelCase")]
624pub enum KnowledgeSurfaceCoverage {
625 None,
626 Structural,
627 Semantic,
628 Interaction,
629 Complete,
630}
631
632impl Default for KnowledgeSurfaceProvenance {
633 fn default() -> Self {
634 Self {
635 kind: KnowledgeSurfaceKind::Opaque,
636 understanding: KnowledgeUnderstandingLevel::Opaque,
637 coverage: KnowledgeSurfaceCoverage::None,
638 extension_id: None,
639 }
640 }
641}
642
643#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
645#[serde(rename_all = "camelCase", deny_unknown_fields)]
646pub struct KnowledgeBackendProvenance {
647 pub backend: KnowledgeBackendKind,
648 pub profile: String,
649 #[serde(default, skip_serializing_if = "Vec::is_empty")]
650 pub capabilities: Vec<KnowledgeBackendCapability>,
651}
652
653#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
654#[serde(rename_all = "camelCase")]
655pub enum KnowledgeBackendKind {
656 Cdp,
657 WebdriverBidi,
658 BrowserExtension,
659 Visual,
660 Terminal,
661 #[default]
662 Unknown,
663}
664
665#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
667#[serde(rename_all = "camelCase")]
668pub enum KnowledgeBackendCapability {
669 Navigation,
670 SemanticExtraction,
671 CoordinateInput,
672 Script,
673 Capture,
674 Verification,
675 Storage,
676 Prompt,
677}
678
679impl Default for KnowledgeBackendProvenance {
680 fn default() -> Self {
681 Self {
682 backend: KnowledgeBackendKind::Unknown,
683 profile: "legacy".into(),
684 capabilities: Vec::new(),
685 }
686 }
687}
688
689#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
691#[serde(rename_all = "camelCase")]
692pub enum KnowledgePortability {
693 SemanticPortable,
694 SurfacePortable,
695 BackendCapabilityDependent,
696 BackendSpecific,
697 BrowserSpecific,
698 #[default]
699 NonPortable,
700}
701
702#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
704#[serde(rename_all = "camelCase")]
705pub enum KnowledgeMemoryInfluence {
706 #[default]
707 None,
708 RankingOnly,
709 TemplateSuggested,
710 VerificationSuggested,
711 RecoverySuggested,
712 IdentityContinuitySuggested,
713}
714
715#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
717#[serde(rename_all = "camelCase")]
718pub enum KnowledgeRetrievalSignalKind {
719 ExactPageFamilyMatch,
720 ExactFingerprintMatch,
721 OriginMatch,
722 SurfaceMatch,
723 BackendMatch,
724 GraphDistance,
725 SemanticSimilarity,
726 Freshness,
727}
728
729#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
730#[serde(rename_all = "camelCase", deny_unknown_fields)]
731pub struct KnowledgeRetrievalSignal {
732 pub kind: KnowledgeRetrievalSignalKind,
733 pub detail: String,
734 #[serde(default, skip_serializing_if = "Option::is_none")]
735 pub score_millis: Option<u16>,
736}
737
738#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
740#[serde(rename_all = "camelCase")]
741pub enum KnowledgeCurrentValidationStatus {
742 NotValidated,
743 Validated,
744 Rejected,
745 Stale,
746 Contradicted,
747}
748
749#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
750#[serde(rename_all = "camelCase")]
751pub enum KnowledgeEvidenceQuality {
752 None,
753 Weak,
754 Partial,
755 Strong,
756}
757
758#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
759#[serde(rename_all = "camelCase", deny_unknown_fields)]
760pub struct KnowledgeCurrentValidation {
761 pub status: KnowledgeCurrentValidationStatus,
762 pub evidence_quality: KnowledgeEvidenceQuality,
763 #[serde(default, skip_serializing_if = "Option::is_none")]
764 pub current_revision: Option<u64>,
765 #[serde(default, skip_serializing_if = "Option::is_none")]
766 pub validated_at: Option<String>,
767}
768
769impl Default for KnowledgeCurrentValidation {
770 fn default() -> Self {
771 Self {
772 status: KnowledgeCurrentValidationStatus::NotValidated,
773 evidence_quality: KnowledgeEvidenceQuality::None,
774 current_revision: None,
775 validated_at: None,
776 }
777 }
778}
779
780#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
781#[serde(rename_all = "camelCase", deny_unknown_fields)]
782pub struct KnowledgeRetrievalExplanation {
783 #[serde(default, skip_serializing_if = "Vec::is_empty")]
784 pub signals: Vec<KnowledgeRetrievalSignal>,
785 #[serde(default)]
786 pub current_validation: KnowledgeCurrentValidation,
787}
788
789#[derive(Debug, Clone, Default, PartialEq, Eq)]
792pub struct KnowledgeRetrievalQuery {
793 pub page_kind: Option<String>,
794 pub task_kind: Option<String>,
795 pub entity_roles: Vec<String>,
796 pub landmarks: Vec<String>,
797 pub max_results: usize,
798}
799
800impl KnowledgeRetrievalQuery {
801 pub fn is_bounded(&self) -> bool {
802 self.max_results <= 16
803 && self
804 .page_kind
805 .as_deref()
806 .is_none_or(|value| value.len() <= MAX_RETRIEVAL_QUERY_VALUE_BYTES)
807 && self
808 .task_kind
809 .as_deref()
810 .is_none_or(|value| value.len() <= MAX_RETRIEVAL_QUERY_VALUE_BYTES)
811 && self.entity_roles.len() <= MAX_RETRIEVAL_QUERY_VALUES
812 && self.landmarks.len() <= MAX_RETRIEVAL_QUERY_VALUES
813 && self
814 .entity_roles
815 .iter()
816 .chain(self.landmarks.iter())
817 .all(|value| value.len() <= MAX_RETRIEVAL_QUERY_VALUE_BYTES)
818 }
819}
820
821#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
823#[serde(rename_all = "camelCase")]
824pub enum KnowledgeRejectionReason {
825 OutOfScope,
826 WorkspaceMismatch,
827 WorkspaceGenerationMismatch,
828 LegacyWorkspaceUnbound,
829 StaleLifecycle,
830 ContradictedLifecycle,
831 Quarantined,
832 Stale,
833 BackendIncompatible,
834 SurfaceIncompatible,
835 ExtensionMismatch,
836 OpaqueProvenance,
837 Contradicted,
838 CurrentValidationMissing,
839 NoExactOrGraphMatch,
840}
841
842#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
846#[serde(rename_all = "camelCase", deny_unknown_fields)]
847pub struct KnowledgeRetrievalCandidate {
848 pub record_id: String,
849 pub selected: bool,
850 #[serde(default, skip_serializing_if = "Vec::is_empty")]
851 pub signals: Vec<KnowledgeRetrievalSignal>,
852 #[serde(default, skip_serializing_if = "Option::is_none")]
853 pub rejection: Option<KnowledgeRejectionReason>,
854 #[serde(default, skip_serializing_if = "Option::is_none")]
855 pub explanation: Option<String>,
856 #[serde(default)]
859 pub current_validation: KnowledgeCurrentValidation,
860 #[serde(default)]
862 pub portability: KnowledgePortability,
863 #[serde(default)]
864 pub surface_kind: KnowledgeSurfaceKind,
865 #[serde(default)]
866 pub backend_kind: KnowledgeBackendKind,
867}
868
869#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
872#[serde(rename_all = "camelCase", deny_unknown_fields)]
873pub struct KnowledgeRetrievalReport {
874 #[serde(default, skip_serializing_if = "Vec::is_empty")]
875 pub candidates: Vec<KnowledgeRetrievalCandidate>,
876 #[serde(default, skip_serializing_if = "Vec::is_empty")]
877 pub selected_record_ids: Vec<String>,
878 #[serde(default, skip_serializing_if = "Vec::is_empty")]
881 pub rejected_record_ids: Vec<String>,
882 pub embeddings_used: bool,
883}
884
885#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
887#[serde(rename_all = "camelCase")]
888pub enum KnowledgeGraphNodeKind {
889 Record,
890 PageKind,
891 Landmark,
892 Workflow,
893}
894
895#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
896#[serde(rename_all = "camelCase", deny_unknown_fields)]
897pub struct KnowledgeGraphNode {
898 pub id: String,
899 pub kind: KnowledgeGraphNodeKind,
900}
901
902#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
903#[serde(rename_all = "camelCase", deny_unknown_fields)]
904pub struct KnowledgeGraphEdge {
905 pub from: String,
906 pub to: String,
907 pub relation: String,
908}
909
910#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
911#[serde(rename_all = "camelCase", deny_unknown_fields)]
912pub struct KnowledgeGraph {
913 pub nodes: Vec<KnowledgeGraphNode>,
914 pub edges: Vec<KnowledgeGraphEdge>,
915}
916
917#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
918#[serde(rename_all = "camelCase", deny_unknown_fields)]
919pub struct KnowledgeGraphTraversal {
920 pub start: String,
921 pub max_depth: usize,
922 pub node_ids: Vec<String>,
923 pub edges: Vec<KnowledgeGraphEdge>,
924 pub truncated: bool,
925}
926
927pub trait KnowledgeEmbeddingProvider {
929 fn similarity_millis(
930 &self,
931 query: &KnowledgeRetrievalQuery,
932 record: &KnowledgeRecord,
933 ) -> Option<u16>;
934}
935impl KnowledgeRetrievalReport {
936 pub fn selected(&self) -> impl Iterator<Item = &KnowledgeRetrievalCandidate> {
937 self.candidates
938 .iter()
939 .filter(|candidate| candidate.selected)
940 }
941 pub fn rejected(&self) -> impl Iterator<Item = &KnowledgeRetrievalCandidate> {
942 self.candidates
943 .iter()
944 .filter(|candidate| candidate.rejection.is_some())
945 }
946}
947
948#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
950#[serde(rename_all = "camelCase", deny_unknown_fields)]
951pub struct KnowledgeSource {
952 pub first_seen_at: String,
953 pub last_verified_at: String,
954 pub glass_version: String,
955 pub verification_count: u32,
956 #[serde(default, skip_serializing_if = "is_legacy_surface")]
957 pub surface: KnowledgeSurfaceProvenance,
958 #[serde(default, skip_serializing_if = "is_legacy_backend")]
959 pub backend: KnowledgeBackendProvenance,
960}
961
962fn is_legacy_surface(value: &KnowledgeSurfaceProvenance) -> bool {
963 *value == KnowledgeSurfaceProvenance::default()
964}
965
966fn is_legacy_backend(value: &KnowledgeBackendProvenance) -> bool {
967 *value == KnowledgeBackendProvenance::default()
968}
969
970fn is_nonportable(value: &KnowledgePortability) -> bool {
971 *value == KnowledgePortability::NonPortable
972}
973
974fn is_no_memory_influence(value: &KnowledgeMemoryInfluence) -> bool {
975 *value == KnowledgeMemoryInfluence::None
976}
977
978fn is_empty_retrieval(value: &KnowledgeRetrievalExplanation) -> bool {
979 value.signals.is_empty() && value.current_validation == KnowledgeCurrentValidation::default()
980}
981
982#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
984#[serde(rename_all = "camelCase")]
985pub struct KnowledgeInvalidation {
986 #[serde(default, skip_serializing_if = "Option::is_none")]
987 pub max_age_seconds: Option<u64>,
988 #[serde(default, skip_serializing_if = "Vec::is_empty")]
989 pub required_landmarks: Vec<String>,
990}
991
992#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
994#[serde(rename_all = "camelCase")]
995pub struct KnowledgeLifecycleEvent {
996 pub from: KnowledgeConfidence,
997 pub to: KnowledgeConfidence,
998 pub reason: String,
999 pub observed_at: String,
1000}
1001
1002#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1005#[serde(rename_all = "camelCase", deny_unknown_fields)]
1006pub struct KnowledgeRecord {
1007 pub schema_version: u32,
1008 pub record_id: String,
1009 pub kind: KnowledgeRecordKind,
1010 pub scope: KnowledgeScope,
1011 pub source: KnowledgeSource,
1012 pub confidence: KnowledgeConfidence,
1013 pub invalidation: KnowledgeInvalidation,
1014 pub data: Value,
1015 #[serde(default, skip_serializing_if = "is_nonportable")]
1016 pub portability: KnowledgePortability,
1017 #[serde(default, skip_serializing_if = "is_no_memory_influence")]
1018 pub memory_influence: KnowledgeMemoryInfluence,
1019 #[serde(default, skip_serializing_if = "is_empty_retrieval")]
1020 pub retrieval: KnowledgeRetrievalExplanation,
1021 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1022 pub history: Vec<KnowledgeLifecycleEvent>,
1023}
1024
1025impl KnowledgeRecord {
1026 pub fn from_page_observation(
1032 observation: &SemanticObservation,
1033 options: KnowledgeRecordBuildOptions,
1034 ) -> Result<Self, KnowledgeValidationError> {
1035 observation.validate().map_err(|error| {
1036 KnowledgeValidationError::new("observation", format!("invalid observation: {error}"))
1037 })?;
1038 validate_text("recordId", &options.record_id, MAX_RECORD_ID_BYTES, false)?;
1039 validate_text(
1040 "source.glassVersion",
1041 &options.glass_version,
1042 MAX_SCOPE_VALUE_BYTES,
1043 false,
1044 )?;
1045 validate_timestamp("source.observedAt", &options.observed_at)?;
1046 validate_scope(&options.scope)?;
1047 let page_kind = serde_json::to_value(observation.page.kind)
1048 .map_err(|error| KnowledgeValidationError::new("data.pageKind", error.to_string()))?;
1049 let region_kinds = observation
1050 .regions
1051 .iter()
1052 .map(|region| serde_json::to_value(region.kind))
1053 .collect::<Result<Vec<_>, _>>()
1054 .map_err(|error| {
1055 KnowledgeValidationError::new("data.regionKinds", error.to_string())
1056 })?;
1057 let mut required_landmarks = BTreeSet::new();
1058 required_landmarks.insert(page_kind.as_str().unwrap_or_default().to_owned());
1059 for kind in ®ion_kinds {
1060 if let Some(kind) = kind.as_str() {
1061 required_landmarks.insert(kind.to_owned());
1062 }
1063 }
1064 let record = Self {
1065 schema_version: KNOWLEDGE_SCHEMA_VERSION,
1066 record_id: options.record_id,
1067 kind: KnowledgeRecordKind::PageFamily,
1068 scope: options.scope,
1069 source: KnowledgeSource {
1070 first_seen_at: options.observed_at.clone(),
1071 last_verified_at: options.observed_at,
1072 glass_version: options.glass_version,
1073 verification_count: 0,
1074 surface: options.surface,
1075 backend: options.backend,
1076 },
1077 confidence: KnowledgeConfidence::Observed,
1078 invalidation: KnowledgeInvalidation {
1079 max_age_seconds: Some(604_800),
1080 required_landmarks: required_landmarks.into_iter().collect(),
1081 },
1082 data: json!({
1083 "pageKind": page_kind,
1084 "regionKinds": region_kinds,
1085 }),
1086 portability: options.portability,
1087 memory_influence: KnowledgeMemoryInfluence::default(),
1088 retrieval: KnowledgeRetrievalExplanation {
1089 current_validation: options.current_validation,
1090 ..KnowledgeRetrievalExplanation::default()
1091 },
1092 history: Vec::new(),
1093 };
1094 record.validate()?;
1095 Ok(record)
1096 }
1097
1098 pub fn from_verified_observation(
1102 observation: &SemanticObservation,
1103 mut options: KnowledgeRecordBuildOptions,
1104 evidence: &KnowledgeVerifiedWorkflowEvidence,
1105 ) -> Result<Self, KnowledgeValidationError> {
1106 observation.validate().map_err(|error| {
1107 KnowledgeValidationError::new("observation", format!("invalid observation: {error}"))
1108 })?;
1109 evidence.validate_against(observation)?;
1110 if observation.limits.truncated {
1111 return Err(KnowledgeValidationError::new(
1112 "observation.limits",
1113 "verified learning requires complete observation evidence",
1114 ));
1115 }
1116 if observation_contains_sensitive_data(observation)? {
1117 return Err(KnowledgeValidationError::new(
1118 "observation",
1119 "sensitive fields are not eligible for persistent knowledge",
1120 ));
1121 }
1122 options.current_validation = KnowledgeCurrentValidation {
1123 status: KnowledgeCurrentValidationStatus::Validated,
1124 evidence_quality: evidence.evidence_quality,
1125 current_revision: Some(evidence.guarded_revision),
1126 validated_at: Some(evidence.observed_at.clone()),
1127 };
1128 let mut record = Self::from_page_observation(observation, options)?;
1129 record.confidence = KnowledgeConfidence::Candidate;
1130 record.source.verification_count = 1;
1131 record.data["verifiedUseKey"] = Value::String(evidence.compatibility_key.clone());
1132 record.validate()?;
1133 Ok(record)
1134 }
1135
1136 pub fn deterministic_page_family_id(
1138 observation: &SemanticObservation,
1139 scope: &KnowledgeScope,
1140 ) -> Result<String, KnowledgeValidationError> {
1141 let page_kind = serde_json::to_string(&observation.page.kind).map_err(|error| {
1142 KnowledgeValidationError::new("observation.page.kind", error.to_string())
1143 })?;
1144 let digest = hash_knowledge_identity(&[
1145 &scope.origin,
1146 &scope.path_pattern,
1147 &scope.browser_family,
1148 &scope.policy_preset,
1149 &page_kind,
1150 ]);
1151 Ok(format!("page-family-{digest}"))
1152 }
1153
1154 pub fn from_intent_candidate(
1159 candidate: &SemanticIntentCandidate,
1160 options: KnowledgeRecordBuildOptions,
1161 ) -> Result<Self, KnowledgeValidationError> {
1162 let fingerprint = candidate.fingerprint.as_ref().ok_or_else(|| {
1163 KnowledgeValidationError::new(
1164 "candidate.fingerprint",
1165 "fresh intent candidates require a target fingerprint",
1166 )
1167 })?;
1168 validate_text("recordId", &options.record_id, MAX_RECORD_ID_BYTES, false)?;
1169 validate_text(
1170 "source.glassVersion",
1171 &options.glass_version,
1172 MAX_SCOPE_VALUE_BYTES,
1173 false,
1174 )?;
1175 validate_timestamp("source.observedAt", &options.observed_at)?;
1176 validate_scope(&options.scope)?;
1177 validate_text("candidate.role", &candidate.role, MAX_ROLE_BYTES, false)?;
1178 let digest = target_fingerprint_digest(
1179 &candidate.role,
1180 &candidate.name,
1181 candidate.input_type.as_deref(),
1182 candidate.region_kind,
1183 fingerprint.purpose,
1184 );
1185 let required_landmarks = candidate
1186 .region_kind
1187 .map(|kind| serde_json::to_string(&kind).unwrap_or_default())
1188 .into_iter()
1189 .map(|landmark| landmark.trim_matches('"').to_string())
1190 .collect();
1191 let record = Self {
1192 schema_version: KNOWLEDGE_SCHEMA_VERSION,
1193 record_id: options.record_id,
1194 kind: KnowledgeRecordKind::TargetFingerprint,
1195 scope: options.scope,
1196 source: KnowledgeSource {
1197 first_seen_at: options.observed_at.clone(),
1198 last_verified_at: options.observed_at,
1199 glass_version: options.glass_version,
1200 verification_count: 0,
1201 surface: options.surface,
1202 backend: options.backend,
1203 },
1204 confidence: KnowledgeConfidence::Observed,
1205 invalidation: KnowledgeInvalidation {
1206 max_age_seconds: Some(604_800),
1207 required_landmarks,
1208 },
1209 data: json!({
1210 "fingerprint": digest,
1211 "role": candidate.role,
1212 "regionKind": candidate.region_kind,
1213 "purpose": fingerprint.purpose,
1214 }),
1215 portability: options.portability,
1216 memory_influence: KnowledgeMemoryInfluence::default(),
1217 retrieval: KnowledgeRetrievalExplanation {
1218 current_validation: options.current_validation,
1219 ..KnowledgeRetrievalExplanation::default()
1220 },
1221 history: Vec::new(),
1222 };
1223 record.validate()?;
1224 Ok(record)
1225 }
1226
1227 pub fn from_workflow_definition(
1232 workflow: &super::WorkflowDefinition,
1233 options: KnowledgeRecordBuildOptions,
1234 ) -> Result<Self, KnowledgeValidationError> {
1235 workflow.validate().map_err(|error| {
1236 KnowledgeValidationError::new("workflow", format!("invalid workflow: {error}"))
1237 })?;
1238 validate_text("recordId", &options.record_id, MAX_RECORD_ID_BYTES, false)?;
1239 validate_text(
1240 "source.glassVersion",
1241 &options.glass_version,
1242 MAX_SCOPE_VALUE_BYTES,
1243 false,
1244 )?;
1245 validate_timestamp("source.observedAt", &options.observed_at)?;
1246 validate_scope(&options.scope)?;
1247 let workflow_hash = hash_knowledge_identity(&[&workflow.name, &workflow.workflow_version]);
1248 let step_hashes: Vec<String> = workflow
1249 .steps
1250 .iter()
1251 .map(|step| hash_knowledge_identity(&[&step.id]))
1252 .collect();
1253 let output_hashes: Vec<String> = workflow
1254 .outputs
1255 .keys()
1256 .map(|key| hash_knowledge_identity(&[key]))
1257 .collect();
1258 let record = Self {
1259 schema_version: KNOWLEDGE_SCHEMA_VERSION,
1260 record_id: options.record_id,
1261 kind: KnowledgeRecordKind::WorkflowEntryPoint,
1262 scope: options.scope,
1263 source: KnowledgeSource {
1264 first_seen_at: options.observed_at.clone(),
1265 last_verified_at: options.observed_at,
1266 glass_version: options.glass_version,
1267 verification_count: 0,
1268 surface: options.surface,
1269 backend: options.backend,
1270 },
1271 confidence: KnowledgeConfidence::Candidate,
1272 invalidation: KnowledgeInvalidation {
1273 max_age_seconds: Some(604_800),
1274 required_landmarks: Vec::new(),
1275 },
1276 data: json!({
1277 "workflowHash": workflow_hash,
1278 "stepHashes": step_hashes,
1279 "outputHashes": output_hashes,
1280 "stepCount": workflow.steps.len(),
1281 "intentStepCount": workflow.steps.iter().filter(|step| step.intent.is_some()).count(),
1282 "postconditionCount": workflow.steps.iter().filter(|step| step.expect.is_some()).count() + 1,
1283 }),
1284 portability: options.portability,
1285 memory_influence: KnowledgeMemoryInfluence::default(),
1286 retrieval: KnowledgeRetrievalExplanation {
1287 current_validation: options.current_validation,
1288 ..KnowledgeRetrievalExplanation::default()
1289 },
1290 history: Vec::new(),
1291 };
1292 record.validate()?;
1293 Ok(record)
1294 }
1295 pub fn with_provenance(
1298 mut self,
1299 surface: KnowledgeSurfaceProvenance,
1300 backend: KnowledgeBackendProvenance,
1301 portability: KnowledgePortability,
1302 ) -> Result<Self, KnowledgeValidationError> {
1303 self.source.surface = surface;
1304 self.source.backend = backend;
1305 self.portability = portability;
1306 self.validate()?;
1307 Ok(self)
1308 }
1309
1310 pub fn with_current_validation(
1313 mut self,
1314 current_revision: u64,
1315 evidence_quality: KnowledgeEvidenceQuality,
1316 validated_at: String,
1317 ) -> Result<Self, KnowledgeValidationError> {
1318 if current_revision == 0 {
1319 return Err(KnowledgeValidationError::new(
1320 "currentRevision",
1321 "must be positive",
1322 ));
1323 }
1324 if evidence_quality == KnowledgeEvidenceQuality::None {
1325 return Err(KnowledgeValidationError::new(
1326 "evidenceQuality",
1327 "must identify a current evidence quality",
1328 ));
1329 }
1330 validate_timestamp("validatedAt", &validated_at)?;
1331 self.retrieval.current_validation = KnowledgeCurrentValidation {
1332 status: KnowledgeCurrentValidationStatus::Validated,
1333 evidence_quality,
1334 current_revision: Some(current_revision),
1335 validated_at: Some(validated_at),
1336 };
1337 self.validate()?;
1338 Ok(self)
1339 }
1340
1341 pub fn validate(&self) -> Result<(), KnowledgeValidationError> {
1343 if self.schema_version != KNOWLEDGE_SCHEMA_VERSION {
1344 return Err(KnowledgeValidationError::new(
1345 "schemaVersion",
1346 format!(
1347 "unsupported schema version {}; expected {}",
1348 self.schema_version, KNOWLEDGE_SCHEMA_VERSION
1349 ),
1350 ));
1351 }
1352 validate_text("recordId", &self.record_id, MAX_RECORD_ID_BYTES, false)?;
1353 validate_scope(&self.scope)?;
1354 validate_source(&self.source)?;
1355 validate_retrieval(&self.retrieval)?;
1356 if self.memory_influence != KnowledgeMemoryInfluence::None {
1357 if self.retrieval.signals.is_empty() {
1358 return Err(KnowledgeValidationError::new(
1359 "memoryInfluence",
1360 "memory influence requires retrieval signals",
1361 ));
1362 }
1363 if self.retrieval.current_validation.status
1364 != KnowledgeCurrentValidationStatus::Validated
1365 {
1366 return Err(KnowledgeValidationError::new(
1367 "memoryInfluence",
1368 "memory influence requires current validation",
1369 ));
1370 }
1371 }
1372 if (matches!(
1373 self.source.surface.kind,
1374 KnowledgeSurfaceKind::Opaque | KnowledgeSurfaceKind::Unknown
1375 ) || self.source.backend.backend == KnowledgeBackendKind::Unknown)
1376 && self.portability != KnowledgePortability::NonPortable
1377 {
1378 return Err(KnowledgeValidationError::new(
1379 "portability",
1380 "opaque or unknown provenance is nonPortable",
1381 ));
1382 }
1383 validate_invalidation(&self.invalidation)?;
1384 if self.history.len() > MAX_HISTORY {
1385 return Err(KnowledgeValidationError::new(
1386 "history",
1387 format!("contains more than {MAX_HISTORY} events"),
1388 ));
1389 }
1390 for (index, event) in self.history.iter().enumerate() {
1391 validate_text(
1392 &format!("history[{index}].reason"),
1393 &event.reason,
1394 MAX_SCOPE_VALUE_BYTES,
1395 false,
1396 )?;
1397 validate_timestamp(&format!("history[{index}].observedAt"), &event.observed_at)?;
1398 }
1399 if !matches!(self.data, Value::Object(_) | Value::Array(_)) {
1400 return Err(KnowledgeValidationError::new(
1401 "data",
1402 "must be a JSON object or array",
1403 ));
1404 }
1405 validate_json_value("data", &self.data, 0)?;
1406 let data_bytes = serde_json::to_vec(&self.data).map_err(|error| {
1407 KnowledgeValidationError::new("data", format!("cannot serialize data: {error}"))
1408 })?;
1409 if data_bytes.len() > MAX_DATA_BYTES {
1410 return Err(KnowledgeValidationError::new(
1411 "data",
1412 format!("exceeds the {MAX_DATA_BYTES}-byte limit"),
1413 ));
1414 }
1415 let record_bytes = serde_json::to_vec(self).map_err(|error| {
1416 KnowledgeValidationError::new("$", format!("cannot serialize record: {error}"))
1417 })?;
1418 if record_bytes.len() > MAX_RECORD_BYTES {
1419 return Err(KnowledgeValidationError::new(
1420 "$",
1421 format!("record exceeds the {MAX_RECORD_BYTES}-byte limit"),
1422 ));
1423 }
1424 Ok(())
1425 }
1426
1427 pub fn to_canonical_json(&self) -> Result<String, KnowledgeValidationError> {
1429 self.validate()?;
1430 serde_json::to_string(self)
1431 .map_err(|error| KnowledgeValidationError::new("$", error.to_string()))
1432 }
1433
1434 pub fn content_hash(&self) -> Result<String, KnowledgeValidationError> {
1436 let canonical = self.to_canonical_json()?;
1437 let digest = Sha256::digest(canonical.as_bytes());
1438 Ok(format!("sha256:{digest:x}"))
1439 }
1440
1441 pub fn assess(&self, context: &KnowledgeLookupContext) -> KnowledgeAssessment {
1444 let mut signals = Vec::new();
1445 let mut conflicts = Vec::new();
1446 let mut missing_landmarks = Vec::new();
1447
1448 if self.scope.origin == context.origin {
1449 signals.push(signal(KnowledgeSignalKind::OriginMatch, "origin matches"));
1450 } else {
1451 conflicts.push("origin does not match".into());
1452 }
1453 if path_matches(&self.scope.path_pattern, &context.path) {
1454 signals.push(signal(
1455 KnowledgeSignalKind::PathMatch,
1456 "path pattern matches",
1457 ));
1458 } else {
1459 conflicts.push("path is outside the record pattern".into());
1460 }
1461 if self.scope.profile_scope == context.profile_scope
1462 && self.scope.profile_key == context.profile_key
1463 {
1464 signals.push(signal(
1465 KnowledgeSignalKind::ProfileScopeMatch,
1466 "profile scope matches",
1467 ));
1468 } else {
1469 conflicts.push("profile scope does not match".into());
1470 }
1471 if context.workspace_id.is_none() {
1472 if self.scope.workspace_id.is_none() {
1473 signals.push(signal(
1474 KnowledgeSignalKind::WorkspaceMatch,
1475 "legacy workspace-unbound scope is allowed without live workspace binding",
1476 ));
1477 } else {
1478 conflicts.push("record is workspace-bound but context is not".into());
1479 }
1480 } else if self.scope.workspace_id == context.workspace_id
1481 && self.scope.workspace_generation == context.workspace_generation
1482 {
1483 signals.push(signal(
1484 KnowledgeSignalKind::WorkspaceMatch,
1485 "workspace identity and generation match",
1486 ));
1487 } else if self.scope.workspace_id.is_none() {
1488 conflicts.push("record has no workspace identity for the live context".into());
1489 } else if self.scope.workspace_id != context.workspace_id {
1490 conflicts.push("workspace identity does not match".into());
1491 } else {
1492 conflicts.push("workspace generation does not match".into());
1493 }
1494 compare_optional_scope(
1495 &mut signals,
1496 &mut conflicts,
1497 KnowledgeSignalKind::LocaleMatch,
1498 "locale",
1499 &self.scope.locale,
1500 &context.locale,
1501 );
1502 compare_optional_scope(
1503 &mut signals,
1504 &mut conflicts,
1505 KnowledgeSignalKind::TenantMatch,
1506 "tenant",
1507 &self.scope.tenant_key,
1508 &context.tenant_key,
1509 );
1510 if self.scope.browser_family == context.browser_family
1511 && browser_version_matches(
1512 self.scope.browser_version_range.as_deref(),
1513 context.browser_version.as_deref(),
1514 )
1515 {
1516 signals.push(signal(
1517 KnowledgeSignalKind::BrowserMatch,
1518 "browser scope matches",
1519 ));
1520 } else {
1521 conflicts.push("browser family or version does not match".into());
1522 }
1523 if self.scope.glass_schema_version == context.glass_schema_version {
1524 signals.push(signal(
1525 KnowledgeSignalKind::SchemaMatch,
1526 "schema scope matches",
1527 ));
1528 } else {
1529 conflicts.push("Glass schema scope does not match".into());
1530 }
1531 if self.scope.policy_preset == context.policy_preset {
1532 signals.push(signal(
1533 KnowledgeSignalKind::PolicyMatch,
1534 "policy scope matches",
1535 ));
1536 } else {
1537 conflicts.push("policy scope does not match".into());
1538 }
1539 for required in &self.invalidation.required_landmarks {
1540 if context.landmarks.iter().any(|current| current == required) {
1541 signals.push(signal(
1542 KnowledgeSignalKind::LandmarkMatch,
1543 format!("landmark {required} is present"),
1544 ));
1545 } else {
1546 missing_landmarks.push(required.clone());
1547 }
1548 }
1549
1550 let age_seconds =
1551 parse_age_seconds(&self.source.last_verified_at, context.now_epoch_seconds);
1552 if let Some(age) = age_seconds {
1553 if self
1554 .invalidation
1555 .max_age_seconds
1556 .is_none_or(|maximum| age <= maximum as i64)
1557 {
1558 signals.push(signal(
1559 KnowledgeSignalKind::FreshnessMatch,
1560 format!("record age is {age} seconds"),
1561 ));
1562 } else {
1563 conflicts.push("record exceeded its maximum age".into());
1564 }
1565 } else {
1566 conflicts.push("lastVerifiedAt is not a valid RFC3339 timestamp".into());
1567 }
1568
1569 let current_contradiction = self.retrieval.current_validation.status
1570 == KnowledgeCurrentValidationStatus::Contradicted;
1571 let current_validation_conflict =
1572 self.retrieval.current_validation.status != KnowledgeCurrentValidationStatus::Validated;
1573 let current_revision_conflict =
1574 self.retrieval.current_validation.current_revision != Some(context.current_revision);
1575 if current_contradiction {
1576 conflicts.push("current validation contradicts live Web IR".into());
1577 } else if current_validation_conflict {
1578 conflicts.push("record lacks current Web IR validation".into());
1579 } else if current_revision_conflict {
1580 conflicts.push("current Web IR revision does not match".into());
1581 }
1582 if self.confidence == KnowledgeConfidence::Stale {
1583 conflicts.push("record lifecycle is stale".into());
1584 } else if self.confidence == KnowledgeConfidence::Contradicted {
1585 conflicts.push("record lifecycle is contradicted".into());
1586 }
1587 let record_extension = self.source.surface.kind == KnowledgeSurfaceKind::ExtensionDefined;
1588 let context_extension =
1589 context.surface_kind == Some(KnowledgeSurfaceKind::ExtensionDefined);
1590 let extension_conflict = record_extension != context_extension
1591 || (record_extension
1592 && self.source.surface.extension_id.as_ref()
1593 != context.current_extension_id.as_ref());
1594 if extension_conflict {
1595 conflicts.push("extension provenance does not match".into());
1596 }
1597 let provenance_conflict = matches!(
1598 self.source.surface.kind,
1599 KnowledgeSurfaceKind::Opaque | KnowledgeSurfaceKind::Unknown
1600 ) || self.source.surface.understanding
1601 == KnowledgeUnderstandingLevel::Opaque
1602 || self.source.surface.coverage == KnowledgeSurfaceCoverage::None
1603 || self.source.backend.backend == KnowledgeBackendKind::Unknown;
1604 if provenance_conflict {
1605 conflicts.push("surface or backend provenance is unknown".into());
1606 }
1607 let surface_conflict = self.portability == KnowledgePortability::SurfacePortable
1608 && context.surface_kind != Some(self.source.surface.kind);
1609 let backend_conflict = match self.portability {
1610 KnowledgePortability::BackendCapabilityDependent => {
1611 context.backend_kind != Some(self.source.backend.backend)
1612 || self
1613 .source
1614 .backend
1615 .capabilities
1616 .iter()
1617 .any(|capability| !context.backend_capabilities.contains(capability))
1618 }
1619 KnowledgePortability::BackendSpecific | KnowledgePortability::BrowserSpecific => {
1620 context.backend_kind != Some(self.source.backend.backend)
1621 }
1622 _ => false,
1623 };
1624 let portability_conflict = self.portability == KnowledgePortability::NonPortable
1625 || surface_conflict
1626 || backend_conflict;
1627 if portability_conflict {
1628 conflicts.push(
1629 if surface_conflict {
1630 "record surface provenance is incompatible with this context"
1631 } else if backend_conflict {
1632 "record backend provenance is incompatible with this context"
1633 } else {
1634 "record portability is incompatible with this context"
1635 }
1636 .into(),
1637 );
1638 }
1639 let scope_conflict = conflicts.iter().any(|conflict| {
1640 matches!(
1641 conflict.as_str(),
1642 "origin does not match"
1643 | "path is outside the record pattern"
1644 | "profile scope does not match"
1645 | "workspace identity does not match"
1646 | "workspace generation does not match"
1647 | "record has no workspace identity for the live context"
1648 | "record is workspace-bound but context is not"
1649 | "locale does not match"
1650 | "tenant does not match"
1651 | "browser family or version does not match"
1652 | "Glass schema scope does not match"
1653 | "policy scope does not match"
1654 )
1655 });
1656 let status =
1657 if current_contradiction || self.confidence == KnowledgeConfidence::Contradicted {
1658 KnowledgeAssessmentStatus::Contradicted
1659 } else if self.confidence == KnowledgeConfidence::Quarantined {
1660 KnowledgeAssessmentStatus::Quarantined
1661 } else if scope_conflict {
1662 KnowledgeAssessmentStatus::OutOfScope
1663 } else if current_validation_conflict
1664 || current_revision_conflict
1665 || extension_conflict
1666 || provenance_conflict
1667 || portability_conflict
1668 || !missing_landmarks.is_empty()
1669 || age_seconds.is_none()
1670 || self.confidence == KnowledgeConfidence::Stale
1671 || self
1672 .invalidation
1673 .max_age_seconds
1674 .is_some_and(|maximum| age_seconds.is_some_and(|age| age > maximum as i64))
1675 {
1676 KnowledgeAssessmentStatus::Stale
1677 } else {
1678 KnowledgeAssessmentStatus::Eligible
1679 };
1680 KnowledgeAssessment {
1681 record_id: self.record_id.clone(),
1682 status,
1683 signals,
1684 conflicts,
1685 missing_landmarks,
1686 age_seconds,
1687 }
1688 }
1689
1690 pub fn retrieve_candidate(
1693 &self,
1694 context: &KnowledgeLookupContext,
1695 query: &KnowledgeRetrievalQuery,
1696 ) -> KnowledgeRetrievalCandidate {
1697 let assessment = self.assess(context);
1698 if assessment.status != KnowledgeAssessmentStatus::Eligible {
1699 return KnowledgeRetrievalCandidate {
1700 record_id: self.record_id.clone(),
1701 selected: false,
1702 signals: Vec::new(),
1703 rejection: Some(rejection_reason(&assessment)),
1704 explanation: Some(assessment.conflicts.join("; ")),
1705 current_validation: self.retrieval.current_validation.clone(),
1706 portability: self.portability,
1707 surface_kind: self.source.surface.kind,
1708 backend_kind: self.source.backend.backend,
1709 };
1710 }
1711
1712 let mut provenance = vec![
1713 KnowledgeRetrievalSignal {
1714 kind: KnowledgeRetrievalSignalKind::OriginMatch,
1715 detail: "current origin matches".into(),
1716 score_millis: Some(300),
1717 },
1718 KnowledgeRetrievalSignal {
1719 kind: KnowledgeRetrievalSignalKind::Freshness,
1720 detail: "record passed current freshness validation".into(),
1721 score_millis: Some(200),
1722 },
1723 ];
1724 if context.surface_kind == Some(self.source.surface.kind) {
1725 provenance.push(KnowledgeRetrievalSignal {
1726 kind: KnowledgeRetrievalSignalKind::SurfaceMatch,
1727 detail: "surface provenance matches".into(),
1728 score_millis: Some(350),
1729 });
1730 }
1731 if context.backend_kind == Some(self.source.backend.backend) {
1732 provenance.push(KnowledgeRetrievalSignal {
1733 kind: KnowledgeRetrievalSignalKind::BackendMatch,
1734 detail: "backend provenance matches".into(),
1735 score_millis: Some(350),
1736 });
1737 }
1738 let mut signals = Vec::new();
1739 let page_kind = self.data.get("pageKind").and_then(Value::as_str);
1740 let page_kind_mismatch = self.kind == KnowledgeRecordKind::PageFamily
1741 && query.page_kind.as_deref().is_some_and(|expected| {
1742 page_kind.is_some_and(|actual| {
1743 normalized_knowledge_value(actual) != normalized_knowledge_value(expected)
1744 })
1745 });
1746 if page_kind_mismatch {
1747 return KnowledgeRetrievalCandidate {
1748 record_id: self.record_id.clone(),
1749 selected: false,
1750 signals: Vec::new(),
1751 rejection: Some(KnowledgeRejectionReason::Contradicted),
1752 explanation: Some("current page family contradicts live Web IR".into()),
1753 current_validation: self.retrieval.current_validation.clone(),
1754 portability: self.portability,
1755 surface_kind: self.source.surface.kind,
1756 backend_kind: self.source.backend.backend,
1757 };
1758 }
1759 if query.page_kind.as_deref().is_some_and(|expected| {
1760 page_kind.is_some_and(|actual| {
1761 normalized_knowledge_value(actual) == normalized_knowledge_value(expected)
1762 })
1763 }) {
1764 signals.push(KnowledgeRetrievalSignal {
1765 kind: KnowledgeRetrievalSignalKind::ExactPageFamilyMatch,
1766 detail: "current page family matches".into(),
1767 score_millis: Some(1_000),
1768 });
1769 }
1770
1771 if query.landmarks.iter().any(|landmark| {
1772 self.invalidation.required_landmarks.iter().any(|required| {
1773 normalized_knowledge_value(required) == normalized_knowledge_value(landmark)
1774 })
1775 }) {
1776 signals.push(KnowledgeRetrievalSignal {
1777 kind: KnowledgeRetrievalSignalKind::GraphDistance,
1778 detail: "current landmark is connected to the record".into(),
1779 score_millis: Some(600),
1780 });
1781 }
1782 if let Some(role) = self.data.get("role").and_then(Value::as_str)
1783 && query.entity_roles.iter().any(|expected| {
1784 normalized_knowledge_value(role) == normalized_knowledge_value(expected)
1785 })
1786 {
1787 signals.push(KnowledgeRetrievalSignal {
1788 kind: KnowledgeRetrievalSignalKind::ExactFingerprintMatch,
1789 detail: "current entity role matches remembered fingerprint".into(),
1790 score_millis: Some(900),
1791 });
1792 }
1793 if self.kind == KnowledgeRecordKind::WorkflowEntryPoint
1794 && query.task_kind.is_some()
1795 && !signals.is_empty()
1796 {
1797 signals.push(KnowledgeRetrievalSignal {
1798 kind: KnowledgeRetrievalSignalKind::GraphDistance,
1799 detail: "workflow entry is graph-compatible with the task".into(),
1800 score_millis: Some(450),
1801 });
1802 }
1803 if signals.is_empty() {
1804 return KnowledgeRetrievalCandidate {
1805 record_id: self.record_id.clone(),
1806 selected: false,
1807 signals: provenance,
1808 rejection: Some(KnowledgeRejectionReason::NoExactOrGraphMatch),
1809 explanation: Some("no exact or graph-compatible semantic match".into()),
1810 current_validation: self.retrieval.current_validation.clone(),
1811 portability: self.portability,
1812 surface_kind: self.source.surface.kind,
1813 backend_kind: self.source.backend.backend,
1814 };
1815 }
1816 signals.extend(provenance);
1817 KnowledgeRetrievalCandidate {
1818 record_id: self.record_id.clone(),
1819 selected: false,
1820 signals,
1821 rejection: None,
1822 explanation: None,
1823 current_validation: self.retrieval.current_validation.clone(),
1824 portability: self.portability,
1825 surface_kind: self.source.surface.kind,
1826 backend_kind: self.source.backend.backend,
1827 }
1828 }
1829
1830 pub fn transition_with_validation(
1833 &mut self,
1834 next: KnowledgeConfidence,
1835 reason: String,
1836 observed_at: String,
1837 current_revision: u64,
1838 evidence_quality: KnowledgeEvidenceQuality,
1839 ) -> Result<(), KnowledgeValidationError> {
1840 if current_revision == 0 {
1841 return Err(KnowledgeValidationError::new(
1842 "currentRevision",
1843 "must be positive",
1844 ));
1845 }
1846 if evidence_quality == KnowledgeEvidenceQuality::None {
1847 return Err(KnowledgeValidationError::new(
1848 "evidenceQuality",
1849 "must identify a current evidence quality",
1850 ));
1851 }
1852 let previous = self.retrieval.current_validation.clone();
1853 self.retrieval.current_validation = KnowledgeCurrentValidation {
1854 status: KnowledgeCurrentValidationStatus::Validated,
1855 evidence_quality,
1856 current_revision: Some(current_revision),
1857 validated_at: Some(observed_at.clone()),
1858 };
1859 let result = self.transition(next, reason, observed_at, true);
1860 if result.is_err() {
1861 self.retrieval.current_validation = previous;
1862 }
1863 result
1864 }
1865
1866 pub fn transition(
1870 &mut self,
1871 next: KnowledgeConfidence,
1872 reason: String,
1873 observed_at: String,
1874 fresh_verification: bool,
1875 ) -> Result<(), KnowledgeValidationError> {
1876 let mut candidate = self.clone();
1877 candidate.transition_in_place(next, reason, observed_at, fresh_verification)?;
1878 *self = candidate;
1879 Ok(())
1880 }
1881
1882 fn transition_in_place(
1883 &mut self,
1884 next: KnowledgeConfidence,
1885 reason: String,
1886 observed_at: String,
1887 fresh_verification: bool,
1888 ) -> Result<(), KnowledgeValidationError> {
1889 validate_text("reason", &reason, MAX_SCOPE_VALUE_BYTES, false)?;
1890 validate_text("observedAt", &observed_at, MAX_TIMESTAMP_BYTES, false)?;
1891 validate_timestamp("observedAt", &observed_at)?;
1892 if self.confidence == next {
1893 if fresh_verification {
1894 self.source.last_verified_at = observed_at.clone();
1895 self.source.verification_count = self.source.verification_count.saturating_add(1);
1896 self.validate()?;
1897 }
1898 return Ok(());
1899 }
1900 let requires_fresh = matches!(
1901 next,
1902 KnowledgeConfidence::Verified | KnowledgeConfidence::Observed
1903 ) || matches!(
1904 self.confidence,
1905 KnowledgeConfidence::Contradicted | KnowledgeConfidence::Quarantined
1906 );
1907 if requires_fresh && !fresh_verification {
1908 return Err(KnowledgeValidationError::new(
1909 "freshVerification",
1910 "this lifecycle transition requires fresh browser verification",
1911 ));
1912 }
1913 if next == KnowledgeConfidence::Verified
1914 && self.retrieval.current_validation.status
1915 != KnowledgeCurrentValidationStatus::Validated
1916 {
1917 return Err(KnowledgeValidationError::new(
1918 "currentValidation",
1919 "verified promotion requires a current Web IR witness",
1920 ));
1921 }
1922 if self.history.len() >= MAX_HISTORY {
1923 return Err(KnowledgeValidationError::new(
1924 "history",
1925 format!("cannot append beyond {MAX_HISTORY} events"),
1926 ));
1927 }
1928 let event = KnowledgeLifecycleEvent {
1929 from: self.confidence,
1930 to: next,
1931 reason,
1932 observed_at: observed_at.clone(),
1933 };
1934 self.confidence = next;
1935 if fresh_verification {
1936 self.source.last_verified_at = observed_at.clone();
1937 self.source.verification_count = self.source.verification_count.saturating_add(1);
1938 }
1939 if next == KnowledgeConfidence::Stale {
1940 self.invalidate_current_validation(KnowledgeCurrentValidationStatus::Stale);
1941 } else if matches!(
1942 next,
1943 KnowledgeConfidence::Contradicted | KnowledgeConfidence::Quarantined
1944 ) {
1945 self.invalidate_current_validation(KnowledgeCurrentValidationStatus::Contradicted);
1946 }
1947 self.history.push(event);
1948 self.validate()
1949 }
1950
1951 fn invalidate_current_validation(&mut self, status: KnowledgeCurrentValidationStatus) {
1952 self.retrieval.current_validation = KnowledgeCurrentValidation {
1953 status,
1954 evidence_quality: KnowledgeEvidenceQuality::None,
1955 current_revision: None,
1956 validated_at: None,
1957 };
1958 }
1959}
1960fn observation_contains_sensitive_data(
1961 observation: &SemanticObservation,
1962) -> Result<bool, KnowledgeValidationError> {
1963 let value = serde_json::to_value(observation).map_err(|error| {
1964 KnowledgeValidationError::new(
1965 "observation",
1966 format!("cannot inspect observation: {error}"),
1967 )
1968 })?;
1969 fn walk(value: &Value) -> bool {
1970 match value {
1971 Value::String(text) => {
1972 let normalized = text
1973 .chars()
1974 .filter(char::is_ascii_alphanumeric)
1975 .collect::<String>()
1976 .to_ascii_lowercase();
1977 [
1978 "authorization",
1979 "cookie",
1980 "credential",
1981 "password",
1982 "secret",
1983 "token",
1984 ]
1985 .iter()
1986 .any(|word| normalized.contains(word))
1987 }
1988 Value::Array(values) => values.iter().any(walk),
1989 Value::Object(values) => values.iter().any(|(key, value)| {
1990 let normalized = key
1991 .chars()
1992 .filter(char::is_ascii_alphanumeric)
1993 .collect::<String>()
1994 .to_ascii_lowercase();
1995 [
1996 "authorization",
1997 "cookie",
1998 "credential",
1999 "password",
2000 "secret",
2001 "token",
2002 ]
2003 .iter()
2004 .any(|word| normalized.contains(word))
2005 || walk(value)
2006 }),
2007 Value::Null | Value::Bool(_) | Value::Number(_) => false,
2008 }
2009 }
2010 Ok(walk(&value))
2011}
2012
2013fn normalized_knowledge_value(value: &str) -> String {
2014 value
2015 .chars()
2016 .filter(|character| character.is_ascii_alphanumeric())
2017 .flat_map(char::to_lowercase)
2018 .collect()
2019}
2020
2021fn rejection_reason(assessment: &KnowledgeAssessment) -> KnowledgeRejectionReason {
2022 match assessment.status {
2023 KnowledgeAssessmentStatus::Contradicted => {
2024 let joined = assessment.conflicts.join(" ").to_ascii_lowercase();
2025 if joined.contains("current validation") {
2026 KnowledgeRejectionReason::Contradicted
2027 } else {
2028 KnowledgeRejectionReason::ContradictedLifecycle
2029 }
2030 }
2031 KnowledgeAssessmentStatus::Quarantined => KnowledgeRejectionReason::Quarantined,
2032 KnowledgeAssessmentStatus::OutOfScope => {
2033 let joined = assessment.conflicts.join(" ").to_ascii_lowercase();
2034 if joined.contains("workspace generation") {
2035 KnowledgeRejectionReason::WorkspaceGenerationMismatch
2036 } else if joined.contains("workspace") {
2037 if joined.contains("no workspace identity") {
2038 KnowledgeRejectionReason::LegacyWorkspaceUnbound
2039 } else {
2040 KnowledgeRejectionReason::WorkspaceMismatch
2041 }
2042 } else {
2043 KnowledgeRejectionReason::OutOfScope
2044 }
2045 }
2046 KnowledgeAssessmentStatus::Stale => {
2047 let joined = assessment.conflicts.join(" ").to_ascii_lowercase();
2048 if joined.contains("record lifecycle is stale") {
2049 KnowledgeRejectionReason::StaleLifecycle
2050 } else if joined.contains("unknown") || joined.contains("opaque") {
2051 KnowledgeRejectionReason::OpaqueProvenance
2052 } else if joined.contains("extension") {
2053 KnowledgeRejectionReason::ExtensionMismatch
2054 } else if joined.contains("backend") {
2055 KnowledgeRejectionReason::BackendIncompatible
2056 } else if joined.contains("surface provenance") || joined.contains("portability") {
2057 KnowledgeRejectionReason::SurfaceIncompatible
2058 } else if joined.contains("current web ir") {
2059 KnowledgeRejectionReason::CurrentValidationMissing
2060 } else {
2061 KnowledgeRejectionReason::Stale
2062 }
2063 }
2064 KnowledgeAssessmentStatus::Eligible => KnowledgeRejectionReason::NoExactOrGraphMatch,
2065 }
2066}
2067
2068fn signal(kind: KnowledgeSignalKind, detail: impl Into<String>) -> KnowledgeAssessmentSignal {
2069 KnowledgeAssessmentSignal {
2070 kind,
2071 detail: detail.into(),
2072 }
2073}
2074
2075fn hash_knowledge_identity(parts: &[&str]) -> String {
2076 let canonical = serde_json::to_vec(parts).expect("JSON string arrays are serializable");
2077 let digest = Sha256::digest(canonical);
2078 format!("sha256:{digest:x}")
2079}
2080
2081fn compare_optional_scope(
2082 signals: &mut Vec<KnowledgeAssessmentSignal>,
2083 conflicts: &mut Vec<String>,
2084 kind: KnowledgeSignalKind,
2085 label: &str,
2086 expected: &Option<String>,
2087 actual: &Option<String>,
2088) {
2089 if expected
2090 .as_ref()
2091 .is_none_or(|expected| Some(expected) == actual.as_ref())
2092 {
2093 signals.push(signal(kind, format!("{label} scope matches")));
2094 } else {
2095 conflicts.push(format!("{label} does not match"));
2096 }
2097}
2098
2099fn browser_version_matches(expected_range: Option<&str>, actual: Option<&str>) -> bool {
2100 match (expected_range, actual) {
2101 (None, _) => true,
2102 (Some(expected), Some(actual)) => {
2103 if expected == actual || expected == ">=current" {
2104 return true;
2105 }
2106 let (operator, expected_version) = [">=", "<=", ">", "<", "="]
2107 .iter()
2108 .find_map(|operator| {
2109 expected
2110 .strip_prefix(operator)
2111 .map(|version| (*operator, version))
2112 })
2113 .unwrap_or(("=", expected));
2114 let Some(expected_major) = version_major(expected_version) else {
2115 return false;
2116 };
2117 let Some(actual_major) = version_major(actual) else {
2118 return false;
2119 };
2120 match operator {
2121 ">=" => actual_major >= expected_major,
2122 "<=" => actual_major <= expected_major,
2123 ">" => actual_major > expected_major,
2124 "<" => actual_major < expected_major,
2125 "=" => actual_major == expected_major,
2126 _ => false,
2127 }
2128 }
2129 (Some(_), None) => false,
2130 }
2131}
2132
2133fn version_major(value: &str) -> Option<u64> {
2134 value
2135 .trim()
2136 .split_once('.')
2137 .map_or(value.trim(), |(major, _)| major)
2138 .parse()
2139 .ok()
2140}
2141
2142fn parse_age_seconds(last_verified_at: &str, now_epoch_seconds: i64) -> Option<i64> {
2143 let timestamp = chrono::DateTime::parse_from_rfc3339(last_verified_at).ok()?;
2144 Some(
2145 now_epoch_seconds
2146 .saturating_sub(timestamp.timestamp())
2147 .max(0),
2148 )
2149}
2150
2151fn path_matches(pattern: &str, path: &str) -> bool {
2152 if pattern == path {
2153 return true;
2154 }
2155 let Some(prefix) = pattern.strip_suffix('*') else {
2156 return false;
2157 };
2158 path.starts_with(prefix)
2159}
2160
2161#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2163#[serde(rename_all = "camelCase")]
2164pub struct KnowledgeStoreSnapshot {
2165 pub schema_version: u32,
2166 pub records: Vec<KnowledgeRecord>,
2167}
2168
2169impl KnowledgeStoreSnapshot {
2170 pub fn validate(&self) -> Result<(), KnowledgeValidationError> {
2171 if self.schema_version != KNOWLEDGE_SCHEMA_VERSION {
2172 return Err(KnowledgeValidationError::new(
2173 "schemaVersion",
2174 format!(
2175 "unsupported schema version {}; expected {}",
2176 self.schema_version, KNOWLEDGE_SCHEMA_VERSION
2177 ),
2178 ));
2179 }
2180 if self.records.len() > MAX_KNOWLEDGE_RECORDS {
2181 return Err(KnowledgeValidationError::new(
2182 "records",
2183 format!("contains more than {MAX_KNOWLEDGE_RECORDS} records"),
2184 ));
2185 }
2186 let mut record_ids = BTreeSet::new();
2187 for (index, record) in self.records.iter().enumerate() {
2188 record.validate().map_err(|error| error.at(index))?;
2189 if !record_ids.insert(record.record_id.as_str()) {
2190 return Err(KnowledgeValidationError::new(
2191 format!("records[{index}].recordId"),
2192 "record ID is duplicated",
2193 ));
2194 }
2195 }
2196 Ok(())
2197 }
2198
2199 pub fn to_canonical_json(&self) -> Result<String, KnowledgeValidationError> {
2200 self.validate()?;
2201 serde_json::to_string(self)
2202 .map_err(|error| KnowledgeValidationError::new("$", error.to_string()))
2203 }
2204}
2205
2206fn validate_source(source: &KnowledgeSource) -> Result<(), KnowledgeValidationError> {
2207 validate_timestamp("source.firstSeenAt", &source.first_seen_at)?;
2208 validate_timestamp("source.lastVerifiedAt", &source.last_verified_at)?;
2209 validate_text(
2210 "source.glassVersion",
2211 &source.glass_version,
2212 MAX_SCOPE_VALUE_BYTES,
2213 false,
2214 )?;
2215 validate_surface_provenance(&source.surface)?;
2216 validate_backend_provenance(&source.backend)
2217}
2218
2219fn validate_scope(scope: &KnowledgeScope) -> Result<(), KnowledgeValidationError> {
2220 validate_text("scope.origin", &scope.origin, 2048, false)?;
2221 validate_text("scope.pathPattern", &scope.path_pattern, 512, false)?;
2222 validate_text(
2223 "scope.browserFamily",
2224 &scope.browser_family,
2225 MAX_SCOPE_VALUE_BYTES,
2226 false,
2227 )?;
2228 validate_text(
2229 "scope.policyPreset",
2230 &scope.policy_preset,
2231 MAX_SCOPE_VALUE_BYTES,
2232 false,
2233 )?;
2234 if scope.glass_schema_version == 0 {
2235 return Err(KnowledgeValidationError::new(
2236 "scope.glassSchemaVersion",
2237 "must be positive",
2238 ));
2239 }
2240 validate_workspace_scope(
2241 "scope.workspaceId",
2242 scope.workspace_id.as_deref(),
2243 scope.workspace_generation,
2244 )?;
2245 for (path, value) in [
2246 ("scope.profileKey", scope.profile_key.as_deref()),
2247 ("scope.locale", scope.locale.as_deref()),
2248 ("scope.tenantKey", scope.tenant_key.as_deref()),
2249 (
2250 "scope.browserVersionRange",
2251 scope.browser_version_range.as_deref(),
2252 ),
2253 ] {
2254 if let Some(value) = value {
2255 validate_text(path, value, MAX_SCOPE_VALUE_BYTES, false)?;
2256 }
2257 }
2258 match scope.profile_scope {
2259 KnowledgeProfileScope::ProfileBound if scope.profile_key.is_none() => {
2260 Err(KnowledgeValidationError::new(
2261 "scope.profileKey",
2262 "is required for profileBound knowledge",
2263 ))
2264 }
2265 KnowledgeProfileScope::Anonymous if scope.profile_key.is_some() => {
2266 Err(KnowledgeValidationError::new(
2267 "scope.profileKey",
2268 "must be absent for anonymous knowledge",
2269 ))
2270 }
2271 _ => Ok(()),
2272 }
2273}
2274
2275fn validate_workspace_scope(
2276 path: &str,
2277 workspace_id: Option<&str>,
2278 workspace_generation: Option<u64>,
2279) -> Result<(), KnowledgeValidationError> {
2280 if let Some(workspace_id) = workspace_id {
2281 validate_text(path, workspace_id, MAX_WORKSPACE_ID_BYTES, false)?;
2282 validate_public_text(path, workspace_id)?;
2283 } else if workspace_generation.is_some() {
2284 return Err(KnowledgeValidationError::new(
2285 "workspaceGeneration",
2286 "requires a workspace identity",
2287 ));
2288 }
2289 if workspace_generation == Some(0) {
2290 return Err(KnowledgeValidationError::new(
2291 "workspaceGeneration",
2292 "must be positive",
2293 ));
2294 }
2295 Ok(())
2296}
2297
2298fn validate_surface_provenance(
2299 surface: &KnowledgeSurfaceProvenance,
2300) -> Result<(), KnowledgeValidationError> {
2301 if surface.kind == KnowledgeSurfaceKind::ExtensionDefined && surface.extension_id.is_none() {
2302 return Err(KnowledgeValidationError::new(
2303 "source.surface.extensionId",
2304 "extension-defined surfaces require a bounded extension identifier",
2305 ));
2306 }
2307 if surface.kind != KnowledgeSurfaceKind::ExtensionDefined && surface.extension_id.is_some() {
2308 return Err(KnowledgeValidationError::new(
2309 "source.surface.extensionId",
2310 "extension identifiers are only valid for extension-defined surfaces",
2311 ));
2312 }
2313 if let Some(extension_id) = &surface.extension_id {
2314 validate_text(
2315 "source.surface.extensionId",
2316 extension_id,
2317 MAX_EXTENSION_ID_BYTES,
2318 false,
2319 )?;
2320 validate_public_text("source.surface.extensionId", extension_id)?;
2321 }
2322 if surface.coverage == KnowledgeSurfaceCoverage::None
2323 && surface.understanding != KnowledgeUnderstandingLevel::Opaque
2324 {
2325 return Err(KnowledgeValidationError::new(
2326 "source.surface.coverage",
2327 "none coverage requires opaque understanding",
2328 ));
2329 }
2330 if matches!(
2331 surface.kind,
2332 KnowledgeSurfaceKind::Opaque | KnowledgeSurfaceKind::Unknown
2333 ) && surface.understanding != KnowledgeUnderstandingLevel::Opaque
2334 {
2335 return Err(KnowledgeValidationError::new(
2336 "source.surface.understanding",
2337 "opaque or unknown surfaces cannot claim understanding",
2338 ));
2339 }
2340 if surface.understanding == KnowledgeUnderstandingLevel::TaskCompilable
2341 && surface.coverage != KnowledgeSurfaceCoverage::Complete
2342 {
2343 return Err(KnowledgeValidationError::new(
2344 "source.surface.coverage",
2345 "task-compilable understanding requires complete coverage",
2346 ));
2347 }
2348 Ok(())
2349}
2350
2351fn validate_backend_provenance(
2352 backend: &KnowledgeBackendProvenance,
2353) -> Result<(), KnowledgeValidationError> {
2354 validate_text(
2355 "source.backend.profile",
2356 &backend.profile,
2357 MAX_SCOPE_VALUE_BYTES,
2358 false,
2359 )?;
2360 validate_public_text("source.backend.profile", &backend.profile)?;
2361 validate_backend_capabilities("source.backend.capabilities", &backend.capabilities)
2362}
2363
2364fn validate_backend_capabilities(
2365 path: &str,
2366 capabilities: &[KnowledgeBackendCapability],
2367) -> Result<(), KnowledgeValidationError> {
2368 if capabilities.len() > MAX_BACKEND_CAPABILITIES {
2369 return Err(KnowledgeValidationError::new(
2370 path,
2371 format!("contains more than {MAX_BACKEND_CAPABILITIES} capabilities"),
2372 ));
2373 }
2374 let mut unique = BTreeSet::new();
2375 for (index, capability) in capabilities.iter().enumerate() {
2376 if !unique.insert(*capability) {
2377 return Err(KnowledgeValidationError::new(
2378 format!("{path}[{index}]"),
2379 "capability is duplicated",
2380 ));
2381 }
2382 }
2383 Ok(())
2384}
2385
2386fn validate_retrieval(
2387 retrieval: &KnowledgeRetrievalExplanation,
2388) -> Result<(), KnowledgeValidationError> {
2389 if retrieval.signals.len() > MAX_RETRIEVAL_SIGNALS {
2390 return Err(KnowledgeValidationError::new(
2391 "retrieval.signals",
2392 format!("contains more than {MAX_RETRIEVAL_SIGNALS} signals"),
2393 ));
2394 }
2395 for (index, signal) in retrieval.signals.iter().enumerate() {
2396 validate_text(
2397 &format!("retrieval.signals[{index}].detail"),
2398 &signal.detail,
2399 MAX_SCOPE_VALUE_BYTES,
2400 false,
2401 )?;
2402 validate_public_text(
2403 &format!("retrieval.signals[{index}].detail"),
2404 &signal.detail,
2405 )?;
2406 if signal.score_millis.is_some_and(|score| score > 1_000) {
2407 return Err(KnowledgeValidationError::new(
2408 format!("retrieval.signals[{index}].scoreMillis"),
2409 "must be between 0 and 1000",
2410 ));
2411 }
2412 }
2413 let current = &retrieval.current_validation;
2414 match current.status {
2415 KnowledgeCurrentValidationStatus::Validated => {
2416 if current.evidence_quality == KnowledgeEvidenceQuality::None {
2417 return Err(KnowledgeValidationError::new(
2418 "retrieval.currentValidation.evidenceQuality",
2419 "validated evidence requires a quality",
2420 ));
2421 }
2422 if current
2423 .current_revision
2424 .is_none_or(|revision| revision == 0)
2425 {
2426 return Err(KnowledgeValidationError::new(
2427 "retrieval.currentValidation.currentRevision",
2428 "validated evidence requires a positive current revision witness",
2429 ));
2430 }
2431 let timestamp = current.validated_at.as_deref().ok_or_else(|| {
2432 KnowledgeValidationError::new(
2433 "retrieval.currentValidation.validatedAt",
2434 "is required for validated evidence",
2435 )
2436 })?;
2437 validate_timestamp("retrieval.currentValidation.validatedAt", timestamp)?;
2438 }
2439 KnowledgeCurrentValidationStatus::NotValidated => {
2440 if current.current_revision.is_some() || current.validated_at.is_some() {
2441 return Err(KnowledgeValidationError::new(
2442 "retrieval.currentValidation",
2443 "notValidated evidence cannot include revision or timestamp",
2444 ));
2445 }
2446 if current.evidence_quality != KnowledgeEvidenceQuality::None {
2447 return Err(KnowledgeValidationError::new(
2448 "retrieval.currentValidation.evidenceQuality",
2449 "notValidated evidence must have none quality",
2450 ));
2451 }
2452 }
2453 _ => {
2454 if current.current_revision.is_some() || current.validated_at.is_some() {
2455 return Err(KnowledgeValidationError::new(
2456 "retrieval.currentValidation",
2457 "invalidated evidence cannot retain a revision or timestamp",
2458 ));
2459 }
2460 if current.evidence_quality != KnowledgeEvidenceQuality::None {
2461 return Err(KnowledgeValidationError::new(
2462 "retrieval.currentValidation.evidenceQuality",
2463 "invalidated evidence must have none quality",
2464 ));
2465 }
2466 }
2467 }
2468 Ok(())
2469}
2470
2471fn validate_public_text(path: &str, value: &str) -> Result<(), KnowledgeValidationError> {
2472 let normalized = value
2473 .chars()
2474 .filter(char::is_ascii_alphanumeric)
2475 .collect::<String>()
2476 .to_ascii_lowercase();
2477 const FORBIDDEN: &[&str] = &[
2478 "authorization",
2479 "cookie",
2480 "credential",
2481 "password",
2482 "secret",
2483 "session",
2484 "token",
2485 ];
2486 if FORBIDDEN.iter().any(|word| normalized.contains(word)) {
2487 return Err(KnowledgeValidationError::new(
2488 path,
2489 "sensitive value is not permitted in provenance",
2490 ));
2491 }
2492 Ok(())
2493}
2494fn validate_timestamp(path: &str, value: &str) -> Result<(), KnowledgeValidationError> {
2495 validate_text(path, value, MAX_TIMESTAMP_BYTES, false)?;
2496 chrono::DateTime::parse_from_rfc3339(value).map_err(|error| {
2497 KnowledgeValidationError::new(path, format!("must be RFC3339: {error}"))
2498 })?;
2499 Ok(())
2500}
2501
2502fn validate_invalidation(
2503 invalidation: &KnowledgeInvalidation,
2504) -> Result<(), KnowledgeValidationError> {
2505 if invalidation.required_landmarks.len() > MAX_LANDMARKS {
2506 return Err(KnowledgeValidationError::new(
2507 "invalidation.requiredLandmarks",
2508 format!("contains more than {MAX_LANDMARKS} landmarks"),
2509 ));
2510 }
2511 let mut landmarks = BTreeSet::new();
2512 for (index, landmark) in invalidation.required_landmarks.iter().enumerate() {
2513 validate_text(
2514 &format!("invalidation.requiredLandmarks[{index}]"),
2515 landmark,
2516 MAX_SCOPE_VALUE_BYTES,
2517 false,
2518 )?;
2519 if !landmarks.insert(landmark) {
2520 return Err(KnowledgeValidationError::new(
2521 format!("invalidation.requiredLandmarks[{index}]"),
2522 "landmark is duplicated",
2523 ));
2524 }
2525 }
2526 Ok(())
2527}
2528
2529fn validate_json_value(
2530 path: &str,
2531 value: &Value,
2532 depth: usize,
2533) -> Result<(), KnowledgeValidationError> {
2534 if depth > MAX_JSON_DEPTH {
2535 return Err(KnowledgeValidationError::new(
2536 path,
2537 format!("exceeds the {MAX_JSON_DEPTH}-level nesting limit"),
2538 ));
2539 }
2540 match value {
2541 Value::Null | Value::Bool(_) | Value::Number(_) => Ok(()),
2542 Value::String(value) => validate_text(path, value, MAX_JSON_STRING_BYTES, true),
2543 Value::Array(values) => {
2544 if values.len() > MAX_JSON_ARRAY_ENTRIES {
2545 return Err(KnowledgeValidationError::new(
2546 path,
2547 format!("contains more than {MAX_JSON_ARRAY_ENTRIES} values"),
2548 ));
2549 }
2550 for (index, value) in values.iter().enumerate() {
2551 validate_json_value(&format!("{path}[{index}]"), value, depth + 1)?;
2552 }
2553 Ok(())
2554 }
2555 Value::Object(values) => {
2556 if values.len() > MAX_JSON_OBJECT_ENTRIES {
2557 return Err(KnowledgeValidationError::new(
2558 path,
2559 format!("contains more than {MAX_JSON_OBJECT_ENTRIES} fields"),
2560 ));
2561 }
2562 for (key, value) in values {
2563 validate_key(&format!("{path}.{key}"), key)?;
2564 validate_json_value(&format!("{path}.{key}"), value, depth + 1)?;
2565 }
2566 Ok(())
2567 }
2568 }
2569}
2570
2571fn validate_key(path: &str, key: &str) -> Result<(), KnowledgeValidationError> {
2572 validate_text(path, key, MAX_SCOPE_VALUE_BYTES, false)?;
2573 let normalized = key
2574 .chars()
2575 .filter(char::is_ascii_alphanumeric)
2576 .collect::<String>()
2577 .to_ascii_lowercase();
2578 const FORBIDDEN: &[&str] = &[
2579 "authorization",
2580 "cookie",
2581 "credential",
2582 "formvalue",
2583 "password",
2584 "rawaccessibility",
2585 "rawcdp",
2586 "rawdom",
2587 "secret",
2588 "screenshot",
2589 "token",
2590 ];
2591 if FORBIDDEN.iter().any(|word| normalized.contains(word)) {
2592 return Err(KnowledgeValidationError::new(
2593 path,
2594 "field name is not permitted in persistent knowledge",
2595 ));
2596 }
2597 Ok(())
2598}
2599
2600fn validate_text(
2601 path: &str,
2602 value: &str,
2603 maximum: usize,
2604 allow_empty: bool,
2605) -> Result<(), KnowledgeValidationError> {
2606 if (!allow_empty && value.is_empty()) || value.len() > maximum {
2607 let requirement = if allow_empty {
2608 format!("at most {maximum} bytes")
2609 } else {
2610 format!("non-empty and at most {maximum} bytes")
2611 };
2612 return Err(KnowledgeValidationError::new(
2613 path,
2614 format!("must be {requirement}"),
2615 ));
2616 }
2617 Ok(())
2618}
2619
2620#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2622pub struct KnowledgeValidationError {
2623 pub path: String,
2624 pub reason: String,
2625}
2626
2627impl KnowledgeValidationError {
2628 pub(crate) fn new(path: impl Into<String>, reason: impl Into<String>) -> Self {
2629 Self {
2630 path: path.into(),
2631 reason: reason.into(),
2632 }
2633 }
2634
2635 fn at(self, index: usize) -> Self {
2636 Self::new(format!("records[{index}].{}", self.path), self.reason)
2637 }
2638}
2639
2640impl fmt::Display for KnowledgeValidationError {
2641 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2642 write!(formatter, "{}: {}", self.path, self.reason)
2643 }
2644}
2645
2646impl std::error::Error for KnowledgeValidationError {}
2647
2648#[cfg(test)]
2649mod tests {
2650 #[test]
2651 fn lookup_options_propagate_live_portability_without_defaults() {
2652 let corpus: Value = serde_json::from_str(include_str!(
2653 "../../../benchmarks/scenarios/semantic-observation-v1.json"
2654 ))
2655 .unwrap();
2656 let observation =
2657 SemanticObservation::from_json(&corpus["fixtures"][1]["observation"].to_string())
2658 .unwrap();
2659 let options = KnowledgeLookupOptions {
2660 profile_scope: KnowledgeProfileScope::Anonymous,
2661 profile_key: None,
2662 locale: None,
2663 tenant_key: None,
2664 browser_family: "chromium".into(),
2665 browser_version: Some("120.0".into()),
2666 glass_schema_version: 1,
2667 policy_preset: "balanced".into(),
2668 now_epoch_seconds: 0,
2669 current_revision: None,
2670 current_extension_id: None,
2671 surface_kind: Some(KnowledgeSurfaceKind::Svg),
2672 backend_kind: Some(KnowledgeBackendKind::Visual),
2673 backend_capabilities: vec![KnowledgeBackendCapability::Capture],
2674 workspace_id: None,
2675 workspace_generation: None,
2676 };
2677 let mut mismatch = options.clone();
2678 mismatch.current_revision = Some(observation.revision.saturating_sub(1));
2679 let error = KnowledgeLookupContext::from_observation(&observation, mismatch).unwrap_err();
2680 assert_eq!(error.path, "currentRevision");
2681 let context = KnowledgeLookupContext::from_observation(&observation, options).unwrap();
2682 assert_eq!(context.surface_kind, Some(KnowledgeSurfaceKind::Svg));
2683 assert_eq!(context.backend_kind, Some(KnowledgeBackendKind::Visual));
2684 assert_eq!(
2685 context.backend_capabilities,
2686 vec![KnowledgeBackendCapability::Capture]
2687 );
2688 let mut absent = context;
2689 absent.surface_kind = None;
2690 absent.backend_kind = None;
2691 absent.backend_capabilities.clear();
2692 assert!(absent.surface_kind.is_none());
2693 assert!(absent.backend_kind.is_none());
2694 }
2695 use super::*;
2696 use crate::browser::session::{
2697 FingerprintInvalidation, IntentConfidence, SemanticIntentPurpose, SemanticRegionKind,
2698 SemanticRouteIdentity, SemanticTargetFingerprint, WorkflowDefinition,
2699 };
2700 use serde_json::json;
2701
2702 fn record() -> KnowledgeRecord {
2703 KnowledgeRecord {
2704 schema_version: KNOWLEDGE_SCHEMA_VERSION,
2705 record_id: "knowledge_docs_1".into(),
2706 kind: KnowledgeRecordKind::PageFamily,
2707 scope: KnowledgeScope {
2708 origin: "https://example.test".into(),
2709 path_pattern: "/docs/*".into(),
2710 profile_scope: KnowledgeProfileScope::Anonymous,
2711 profile_key: None,
2712 locale: Some("en-US".into()),
2713 tenant_key: None,
2714 browser_family: "chromium".into(),
2715 browser_version_range: Some(">=120".into()),
2716 glass_schema_version: 1,
2717 policy_preset: "balanced".into(),
2718 workspace_id: None,
2719 workspace_generation: None,
2720 },
2721 source: KnowledgeSource {
2722 first_seen_at: "2026-07-27T00:00:00Z".into(),
2723 last_verified_at: "2026-07-27T00:00:00Z".into(),
2724 glass_version: "0.2.0".into(),
2725 verification_count: 1,
2726 surface: KnowledgeSurfaceProvenance {
2727 kind: KnowledgeSurfaceKind::Document,
2728 understanding: KnowledgeUnderstandingLevel::Strong,
2729 coverage: KnowledgeSurfaceCoverage::Semantic,
2730 extension_id: None,
2731 },
2732 backend: KnowledgeBackendProvenance {
2733 backend: KnowledgeBackendKind::Cdp,
2734 profile: "production".into(),
2735 capabilities: vec![
2736 KnowledgeBackendCapability::SemanticExtraction,
2737 KnowledgeBackendCapability::Verification,
2738 ],
2739 },
2740 },
2741 confidence: KnowledgeConfidence::Observed,
2742 invalidation: KnowledgeInvalidation {
2743 max_age_seconds: Some(604_800),
2744 required_landmarks: vec!["main".into(), "search".into()],
2745 },
2746 data: json!({"pageKind": "documentation", "regions": ["main", "search"]}),
2747 portability: KnowledgePortability::SurfacePortable,
2748 memory_influence: KnowledgeMemoryInfluence::None,
2749 retrieval: KnowledgeRetrievalExplanation {
2750 signals: Vec::new(),
2751 current_validation: KnowledgeCurrentValidation {
2752 status: KnowledgeCurrentValidationStatus::Validated,
2753 evidence_quality: KnowledgeEvidenceQuality::Strong,
2754 current_revision: Some(42),
2755 validated_at: Some("2026-07-27T00:00:00Z".into()),
2756 },
2757 },
2758 history: Vec::new(),
2759 }
2760 }
2761
2762 fn retrieval_context() -> KnowledgeLookupContext {
2763 KnowledgeLookupContext {
2764 origin: "https://example.test".into(),
2765 path: "/docs/intro".into(),
2766 profile_scope: KnowledgeProfileScope::Anonymous,
2767 profile_key: None,
2768 locale: Some("en-US".into()),
2769 tenant_key: None,
2770 browser_family: "chromium".into(),
2771 browser_version: Some("120.0".into()),
2772 glass_schema_version: 1,
2773 policy_preset: "balanced".into(),
2774 landmarks: vec!["main".into(), "search".into()],
2775 now_epoch_seconds: 1_785_542_400,
2776 current_revision: 42,
2777 surface_kind: Some(KnowledgeSurfaceKind::Document),
2778 backend_kind: Some(KnowledgeBackendKind::Cdp),
2779 backend_capabilities: vec![
2780 KnowledgeBackendCapability::SemanticExtraction,
2781 KnowledgeBackendCapability::Verification,
2782 ],
2783 current_extension_id: None,
2784 workspace_id: None,
2785 workspace_generation: None,
2786 }
2787 }
2788
2789 #[test]
2790 fn exact_retrieval_is_bounded_and_explains_no_embedding_use() {
2791 let record = record();
2792 let candidate = record.retrieve_candidate(
2793 &retrieval_context(),
2794 &KnowledgeRetrievalQuery {
2795 page_kind: Some("documentation".into()),
2796 landmarks: vec!["main".into()],
2797 max_results: 1,
2798 ..KnowledgeRetrievalQuery::default()
2799 },
2800 );
2801 assert!(candidate.rejection.is_none());
2802 assert_eq!(
2803 candidate.current_validation.status,
2804 KnowledgeCurrentValidationStatus::Validated
2805 );
2806 assert_eq!(candidate.portability, KnowledgePortability::SurfacePortable);
2807 assert_eq!(candidate.surface_kind, KnowledgeSurfaceKind::Document);
2808 assert_eq!(candidate.backend_kind, KnowledgeBackendKind::Cdp);
2809 assert!(
2810 candidate.signals.iter().any(|signal| {
2811 signal.kind == KnowledgeRetrievalSignalKind::ExactPageFamilyMatch
2812 })
2813 );
2814 assert!(
2815 candidate
2816 .signals
2817 .iter()
2818 .any(|signal| { signal.kind == KnowledgeRetrievalSignalKind::BackendMatch })
2819 );
2820 }
2821
2822 #[test]
2823 fn contradictory_current_page_family_wins_over_historical_match() {
2824 let candidate = record().retrieve_candidate(
2825 &retrieval_context(),
2826 &KnowledgeRetrievalQuery {
2827 page_kind: Some("checkout".into()),
2828 ..KnowledgeRetrievalQuery::default()
2829 },
2830 );
2831 assert_eq!(
2832 candidate.rejection,
2833 Some(KnowledgeRejectionReason::Contradicted)
2834 );
2835 }
2836
2837 #[test]
2838 fn incompatible_backend_is_rejected_with_typed_provenance() {
2839 let mut historical = record();
2840 historical.portability = KnowledgePortability::BackendSpecific;
2841 let mut context = retrieval_context();
2842 context.backend_kind = Some(KnowledgeBackendKind::WebdriverBidi);
2843 let candidate = historical.retrieve_candidate(
2844 &context,
2845 &KnowledgeRetrievalQuery {
2846 page_kind: Some("documentation".into()),
2847 ..KnowledgeRetrievalQuery::default()
2848 },
2849 );
2850 assert_eq!(
2851 candidate.rejection,
2852 Some(KnowledgeRejectionReason::BackendIncompatible)
2853 );
2854 assert!(candidate.explanation.is_some());
2855 }
2856
2857 #[test]
2858 fn record_round_trip_and_hash_are_deterministic() {
2859 let record = record();
2860 let canonical = record.to_canonical_json().unwrap();
2861 let parsed: KnowledgeRecord = serde_json::from_str(&canonical).unwrap();
2862 assert_eq!(parsed, record);
2863 assert_eq!(
2864 record.content_hash().unwrap(),
2865 parsed.content_hash().unwrap()
2866 );
2867 }
2868
2869 #[test]
2870 fn workspace_identity_and_generation_isolation_is_fail_closed() {
2871 let mut context = retrieval_context();
2872 context.workspace_id = Some("workspace-alpha".into());
2873 context.workspace_generation = Some(7);
2874 let legacy = record().retrieve_candidate(
2875 &context,
2876 &KnowledgeRetrievalQuery {
2877 page_kind: Some("documentation".into()),
2878 ..KnowledgeRetrievalQuery::default()
2879 },
2880 );
2881 assert_eq!(
2882 legacy.rejection,
2883 Some(KnowledgeRejectionReason::LegacyWorkspaceUnbound)
2884 );
2885
2886 let mut bound = record();
2887 bound.scope.workspace_id = Some("workspace-alpha".into());
2888 bound.scope.workspace_generation = Some(7);
2889 bound.validate().unwrap();
2890 let wire = bound.to_canonical_json().unwrap();
2891 assert!(wire.contains("\"workspaceId\":\"workspace-alpha\""));
2892 assert!(wire.contains("\"workspaceGeneration\":7"));
2893 assert_eq!(
2894 bound
2895 .retrieve_candidate(
2896 &context,
2897 &KnowledgeRetrievalQuery {
2898 page_kind: Some("documentation".into()),
2899 ..KnowledgeRetrievalQuery::default()
2900 },
2901 )
2902 .rejection,
2903 None
2904 );
2905 context.workspace_generation = Some(8);
2906 let stale = bound.retrieve_candidate(
2907 &context,
2908 &KnowledgeRetrievalQuery {
2909 page_kind: Some("documentation".into()),
2910 ..KnowledgeRetrievalQuery::default()
2911 },
2912 );
2913 assert_eq!(
2914 stale.rejection,
2915 Some(KnowledgeRejectionReason::WorkspaceGenerationMismatch)
2916 );
2917 }
2918
2919 #[test]
2920 fn lifecycle_opaque_and_extension_records_fail_closed() {
2921 let query = KnowledgeRetrievalQuery {
2922 page_kind: Some("documentation".into()),
2923 ..KnowledgeRetrievalQuery::default()
2924 };
2925 for (confidence, expected) in [
2926 (
2927 KnowledgeConfidence::Stale,
2928 KnowledgeRejectionReason::StaleLifecycle,
2929 ),
2930 (
2931 KnowledgeConfidence::Contradicted,
2932 KnowledgeRejectionReason::ContradictedLifecycle,
2933 ),
2934 (
2935 KnowledgeConfidence::Quarantined,
2936 KnowledgeRejectionReason::Quarantined,
2937 ),
2938 ] {
2939 let mut historical = record();
2940 historical.confidence = confidence;
2941 assert_eq!(
2942 historical
2943 .retrieve_candidate(&retrieval_context(), &query)
2944 .rejection,
2945 Some(expected)
2946 );
2947 }
2948 let mut opaque = record();
2949 opaque.source.surface.understanding = KnowledgeUnderstandingLevel::Opaque;
2950 assert_eq!(
2951 opaque
2952 .retrieve_candidate(&retrieval_context(), &query)
2953 .rejection,
2954 Some(KnowledgeRejectionReason::OpaqueProvenance)
2955 );
2956 let mut extension = record();
2957 extension.source.surface.kind = KnowledgeSurfaceKind::ExtensionDefined;
2958 extension.source.surface.extension_id = Some("com.example.alpha".into());
2959 let mut extension_context = retrieval_context();
2960 extension_context.current_extension_id = Some("com.example.alpha".into());
2961 assert_eq!(
2962 extension
2963 .retrieve_candidate(&extension_context, &query)
2964 .rejection,
2965 Some(KnowledgeRejectionReason::ExtensionMismatch)
2966 );
2967 }
2968
2969 #[test]
2970 fn stale_lifecycle_confidence_is_not_assessed_as_eligible() {
2971 let mut historical = record();
2972 historical.confidence = KnowledgeConfidence::Stale;
2973 assert_eq!(
2974 historical.assess(&retrieval_context()).status,
2975 KnowledgeAssessmentStatus::Stale
2976 );
2977 }
2978
2979 #[test]
2980 fn sensitive_data_keys_are_rejected() {
2981 let mut record = record();
2982 record.data = json!({"requiredLandmarks": ["main"], "password": "never"});
2983 let error = record.validate().unwrap_err();
2984 assert_eq!(error.path, "data.password");
2985 }
2986
2987 #[test]
2988 fn scalar_record_data_is_rejected_by_the_contract() {
2989 let mut record = record();
2990 record.data = json!("not-a-knowledge-object");
2991 let error = record.validate().unwrap_err();
2992 assert_eq!(error.path, "data");
2993 }
2994
2995 #[test]
2996 fn profile_bound_scope_requires_a_profile_key() {
2997 let mut record = record();
2998 record.scope.profile_scope = KnowledgeProfileScope::ProfileBound;
2999 let error = record.validate().unwrap_err();
3000 assert_eq!(error.path, "scope.profileKey");
3001 }
3002
3003 #[test]
3004 fn verified_promotion_requires_fresh_evidence() {
3005 let mut record = record();
3006 let error = record
3007 .transition(
3008 KnowledgeConfidence::Verified,
3009 "imported record".into(),
3010 "2026-07-27T00:00:01Z".into(),
3011 false,
3012 )
3013 .unwrap_err();
3014 assert_eq!(error.path, "freshVerification");
3015 record
3016 .transition(
3017 KnowledgeConfidence::Verified,
3018 "fresh landmark match".into(),
3019 "2026-07-27T00:00:01Z".into(),
3020 true,
3021 )
3022 .unwrap();
3023 assert_eq!(record.confidence, KnowledgeConfidence::Verified);
3024 assert_eq!(record.source.last_verified_at, "2026-07-27T00:00:01Z");
3025 assert_eq!(record.source.verification_count, 2);
3026 assert_eq!(record.history.len(), 1);
3027 }
3028
3029 #[test]
3030 fn fresh_verification_refreshes_an_unchanged_state() {
3031 let mut record = record();
3032 record
3033 .transition(
3034 KnowledgeConfidence::Observed,
3035 "fresh observation repeated".into(),
3036 "2026-07-27T00:00:02Z".into(),
3037 true,
3038 )
3039 .unwrap();
3040 assert_eq!(record.source.last_verified_at, "2026-07-27T00:00:02Z");
3041 assert_eq!(record.source.verification_count, 2);
3042 assert!(record.history.is_empty());
3043 }
3044
3045 #[test]
3046 fn snapshot_rejects_duplicate_record_ids() {
3047 let record = record();
3048 let snapshot = KnowledgeStoreSnapshot {
3049 schema_version: KNOWLEDGE_SCHEMA_VERSION,
3050 records: vec![record.clone(), record],
3051 };
3052 let error = snapshot.validate().unwrap_err();
3053 assert_eq!(error.path, "records[1].recordId");
3054 }
3055
3056 fn lookup_context() -> KnowledgeLookupContext {
3057 KnowledgeLookupContext {
3058 origin: "https://example.test".into(),
3059 path: "/docs/getting-started".into(),
3060 profile_scope: KnowledgeProfileScope::Anonymous,
3061 profile_key: None,
3062 locale: Some("en-US".into()),
3063 tenant_key: None,
3064 browser_family: "chromium".into(),
3065 browser_version: Some(">=120".into()),
3066 surface_kind: Some(KnowledgeSurfaceKind::Document),
3067 backend_kind: Some(KnowledgeBackendKind::Cdp),
3068 backend_capabilities: vec![
3069 KnowledgeBackendCapability::SemanticExtraction,
3070 KnowledgeBackendCapability::Verification,
3071 ],
3072 glass_schema_version: 1,
3073 policy_preset: "balanced".into(),
3074 current_revision: 42,
3075 current_extension_id: None,
3076 workspace_id: None,
3077 workspace_generation: None,
3078 landmarks: vec!["documentation".into(), "main".into(), "search".into()],
3079 now_epoch_seconds: chrono::DateTime::parse_from_rfc3339("2026-07-27T00:00:00Z")
3080 .unwrap()
3081 .timestamp(),
3082 }
3083 }
3084
3085 #[test]
3086 fn assessment_accepts_fresh_matching_scope_and_landmarks() {
3087 let assessment = record().assess(&lookup_context());
3088 assert_eq!(assessment.status, KnowledgeAssessmentStatus::Eligible);
3089 assert_eq!(assessment.missing_landmarks, Vec::<String>::new());
3090 assert!(assessment.conflicts.is_empty());
3091 }
3092 #[test]
3093 fn assessment_rejects_current_revision_mismatch() {
3094 let mut context = lookup_context();
3095 context.current_revision = 43;
3096 let assessment = record().assess(&context);
3097 assert_eq!(assessment.status, KnowledgeAssessmentStatus::Stale);
3098 assert!(
3099 assessment
3100 .conflicts
3101 .contains(&"current Web IR revision does not match".to_string())
3102 );
3103 }
3104 #[test]
3105 fn extension_identity_must_match_live_surface() {
3106 let mut extension = record();
3107 extension.source.surface.kind = KnowledgeSurfaceKind::ExtensionDefined;
3108 extension.source.surface.extension_id = Some("com.example.alpha".into());
3109 let mut context = lookup_context();
3110 context.surface_kind = Some(KnowledgeSurfaceKind::ExtensionDefined);
3111 context.current_extension_id = Some("com.example.alpha".into());
3112 assert_eq!(
3113 extension.assess(&context).status,
3114 KnowledgeAssessmentStatus::Eligible
3115 );
3116 context.current_extension_id = Some("com.example.beta".into());
3117 let mismatch = extension.assess(&context);
3118 assert_eq!(mismatch.status, KnowledgeAssessmentStatus::Stale);
3119 assert!(
3120 mismatch
3121 .conflicts
3122 .contains(&"extension provenance does not match".to_string())
3123 );
3124 context.current_extension_id = None;
3125 assert_eq!(
3126 extension.assess(&context).status,
3127 KnowledgeAssessmentStatus::Stale
3128 );
3129 }
3130 #[test]
3131 fn lookup_capabilities_are_bounded_and_unique() {
3132 let oversized = vec![KnowledgeBackendCapability::Navigation; MAX_BACKEND_CAPABILITIES + 1];
3133 let error = validate_backend_capabilities("backendCapabilities", &oversized).unwrap_err();
3134 assert_eq!(error.path, "backendCapabilities");
3135 let duplicate = vec![
3136 KnowledgeBackendCapability::Navigation,
3137 KnowledgeBackendCapability::Navigation,
3138 ];
3139 let error = validate_backend_capabilities("backendCapabilities", &duplicate).unwrap_err();
3140 assert_eq!(error.path, "backendCapabilities[1]");
3141 }
3142 #[test]
3143 fn assessment_fails_closed_without_current_validation() {
3144 let mut legacy = record();
3145 legacy.retrieval.current_validation = KnowledgeCurrentValidation::default();
3146 let assessment = legacy.assess(&lookup_context());
3147 assert_eq!(assessment.status, KnowledgeAssessmentStatus::Stale);
3148 assert!(
3149 assessment
3150 .conflicts
3151 .contains(&"record lacks current Web IR validation".to_string())
3152 );
3153 }
3154
3155 #[test]
3156 fn assessment_fails_closed_for_opaque_backend_and_nonportable_memory() {
3157 let mut legacy = record();
3158 legacy.source.surface = KnowledgeSurfaceProvenance::default();
3159 legacy.source.backend = KnowledgeBackendProvenance::default();
3160 legacy.portability = KnowledgePortability::NonPortable;
3161 let assessment = legacy.assess(&lookup_context());
3162 assert_eq!(assessment.status, KnowledgeAssessmentStatus::Stale);
3163 assert!(
3164 assessment
3165 .conflicts
3166 .contains(&"surface or backend provenance is unknown".to_string())
3167 );
3168 }
3169 #[test]
3170 fn surface_portability_requires_current_surface_witness() {
3171 let mut context = lookup_context();
3172 context.surface_kind = Some(KnowledgeSurfaceKind::Svg);
3173 let assessment = record().assess(&context);
3174 assert_eq!(assessment.status, KnowledgeAssessmentStatus::Stale);
3175 assert!(
3176 assessment
3177 .conflicts
3178 .contains(&"record surface provenance is incompatible with this context".into())
3179 );
3180 }
3181
3182 #[test]
3183 fn lifecycle_invalidation_clears_current_validation() {
3184 let mut value = record();
3185 value
3186 .transition(
3187 KnowledgeConfidence::Stale,
3188 "drift detected".into(),
3189 "2026-07-27T00:00:01Z".into(),
3190 false,
3191 )
3192 .unwrap();
3193 assert_eq!(
3194 value.retrieval.current_validation.status,
3195 KnowledgeCurrentValidationStatus::Stale
3196 );
3197 assert_eq!(
3198 value.assess(&lookup_context()).status,
3199 KnowledgeAssessmentStatus::Stale
3200 );
3201 }
3202
3203 #[test]
3204 fn validation_requires_revision_witness_and_retrieval_is_redacted() {
3205 let mut value = record();
3206 value.retrieval.current_validation.current_revision = None;
3207 let error = value.validate().unwrap_err();
3208 assert_eq!(error.path, "retrieval.currentValidation.currentRevision");
3209
3210 let mut signal_value = record();
3211 signal_value
3212 .retrieval
3213 .signals
3214 .push(KnowledgeRetrievalSignal {
3215 kind: KnowledgeRetrievalSignalKind::SemanticSimilarity,
3216 detail: "token from page".into(),
3217 score_millis: None,
3218 });
3219 let error = signal_value.validate().unwrap_err();
3220 assert_eq!(error.path, "retrieval.signals[0].detail");
3221 assert!(
3222 serde_json::from_value::<KnowledgeRetrievalSignal>(
3223 json!({"kind":"freshness","detail":"ok","extra":"reject"})
3224 )
3225 .is_err()
3226 );
3227 }
3228
3229 #[test]
3230 fn assessment_matches_browser_version_ranges() {
3231 assert!(browser_version_matches(Some(">=120"), Some("120.0")));
3232 assert!(browser_version_matches(Some("<121"), Some("120.0.1")));
3233 assert!(!browser_version_matches(Some(">=121"), Some("120.0")));
3234 assert!(!browser_version_matches(Some("120"), None));
3235 }
3236
3237 #[test]
3238 fn assessment_marks_missing_landmarks_stale() {
3239 let mut context = lookup_context();
3240 context.landmarks.retain(|landmark| landmark != "search");
3241 let assessment = record().assess(&context);
3242 assert_eq!(assessment.status, KnowledgeAssessmentStatus::Stale);
3243 assert_eq!(assessment.missing_landmarks, vec!["search"]);
3244 }
3245
3246 #[test]
3247 fn assessment_rejects_cross_origin_scope() {
3248 let mut context = lookup_context();
3249 context.origin = "https://other.test".into();
3250 let assessment = record().assess(&context);
3251 assert_eq!(assessment.status, KnowledgeAssessmentStatus::OutOfScope);
3252 assert!(
3253 assessment
3254 .conflicts
3255 .contains(&"origin does not match".to_string())
3256 );
3257 }
3258
3259 #[test]
3260 fn page_record_keeps_shape_but_not_current_targets() {
3261 let corpus: Value = serde_json::from_str(include_str!(
3262 "../../../benchmarks/scenarios/semantic-observation-v1.json"
3263 ))
3264 .unwrap();
3265 let observation =
3266 SemanticObservation::from_json(&corpus["fixtures"][1]["observation"].to_string())
3267 .unwrap();
3268 let record = KnowledgeRecord::from_page_observation(
3269 &observation,
3270 KnowledgeRecordBuildOptions {
3271 record_id: "knowledge_search".into(),
3272 scope: record().scope,
3273 glass_version: "0.2.0".into(),
3274 observed_at: "2026-07-27T00:00:00Z".into(),
3275 surface: KnowledgeSurfaceProvenance {
3276 kind: KnowledgeSurfaceKind::Document,
3277 understanding: KnowledgeUnderstandingLevel::Strong,
3278 coverage: KnowledgeSurfaceCoverage::Semantic,
3279 extension_id: None,
3280 },
3281 backend: KnowledgeBackendProvenance {
3282 backend: KnowledgeBackendKind::Cdp,
3283 profile: "test".into(),
3284 capabilities: vec![KnowledgeBackendCapability::SemanticExtraction],
3285 },
3286 portability: KnowledgePortability::SemanticPortable,
3287 current_validation: KnowledgeCurrentValidation::default(),
3288 },
3289 )
3290 .unwrap();
3291 let data = serde_json::to_string(&record.data).unwrap();
3292 assert!(data.contains("searchResults"));
3293 assert!(!data.contains("axr-8-9"));
3294 assert_eq!(record.confidence, KnowledgeConfidence::Observed);
3295 }
3296
3297 #[test]
3298 fn target_record_keeps_digest_but_not_current_handles_or_names() {
3299 let candidate = SemanticIntentCandidate {
3300 id: "candidate_1".into(),
3301 reference: "axr-42-1".into(),
3302 role: "button".into(),
3303 name: "Private Settings Label".into(),
3304 input_type: None,
3305 region_id: Some("region_navigation".into()),
3306 region_kind: Some(SemanticRegionKind::Navigation),
3307 confidence: IntentConfidence::Exact,
3308 evidence: Vec::new(),
3309 fingerprint: Some(SemanticTargetFingerprint {
3310 revision: 42,
3311 route: SemanticRouteIdentity {
3312 target_id: "target-1".into(),
3313 frame_id: "frame-1".into(),
3314 url: "https://example.test/settings".into(),
3315 },
3316 role: "button".into(),
3317 name: "Private Settings Label".into(),
3318 input_type: None,
3319 region_id: Some("region_navigation".into()),
3320 region_kind: Some(SemanticRegionKind::Navigation),
3321 purpose: SemanticIntentPurpose::Open,
3322 invalidated_by: vec![FingerprintInvalidation::Revision],
3323 }),
3324 };
3325 let record = KnowledgeRecord::from_intent_candidate(
3326 &candidate,
3327 KnowledgeRecordBuildOptions {
3328 record_id: "knowledge-settings-target".into(),
3329 scope: record().scope,
3330 glass_version: "0.2.0".into(),
3331 observed_at: "2026-07-27T00:00:00Z".into(),
3332 surface: KnowledgeSurfaceProvenance {
3333 kind: KnowledgeSurfaceKind::Document,
3334 understanding: KnowledgeUnderstandingLevel::Strong,
3335 coverage: KnowledgeSurfaceCoverage::Semantic,
3336 extension_id: None,
3337 },
3338 backend: KnowledgeBackendProvenance {
3339 backend: KnowledgeBackendKind::Cdp,
3340 profile: "test".into(),
3341 capabilities: vec![KnowledgeBackendCapability::SemanticExtraction],
3342 },
3343 portability: KnowledgePortability::SemanticPortable,
3344 current_validation: KnowledgeCurrentValidation::default(),
3345 },
3346 )
3347 .unwrap();
3348 let data = serde_json::to_string(&record.data).unwrap();
3349 assert!(data.contains("sha256:"));
3350 assert!(!data.contains("axr-42-1"));
3351 assert!(!data.contains("Private Settings Label"));
3352 assert!(!data.contains("target-1"));
3353 assert!(!data.contains("frame-1"));
3354 }
3355
3356 #[test]
3357 fn workflow_record_keeps_shape_without_definition_details() {
3358 let corpus: Value = serde_json::from_str(include_str!(
3359 "../../../benchmarks/scenarios/workflow-v1.json"
3360 ))
3361 .unwrap();
3362 let workflow =
3363 WorkflowDefinition::from_value(corpus["scenarios"][0]["workflow"].clone()).unwrap();
3364 let record = KnowledgeRecord::from_workflow_definition(
3365 &workflow,
3366 KnowledgeRecordBuildOptions {
3367 record_id: "knowledge-workflow-entry".into(),
3368 scope: record().scope,
3369 glass_version: "0.2.0".into(),
3370 observed_at: "2026-07-27T00:00:00Z".into(),
3371 surface: KnowledgeSurfaceProvenance {
3372 kind: KnowledgeSurfaceKind::Document,
3373 understanding: KnowledgeUnderstandingLevel::Strong,
3374 coverage: KnowledgeSurfaceCoverage::Semantic,
3375 extension_id: None,
3376 },
3377 backend: KnowledgeBackendProvenance {
3378 backend: KnowledgeBackendKind::Cdp,
3379 profile: "test".into(),
3380 capabilities: vec![KnowledgeBackendCapability::SemanticExtraction],
3381 },
3382 portability: KnowledgePortability::SemanticPortable,
3383 current_validation: KnowledgeCurrentValidation::default(),
3384 },
3385 )
3386 .unwrap();
3387 assert_eq!(record.kind, KnowledgeRecordKind::WorkflowEntryPoint);
3388 assert_eq!(record.confidence, KnowledgeConfidence::Candidate);
3389 let data = serde_json::to_string(&record.data).unwrap();
3390 assert!(data.contains("workflowHash"));
3391 assert!(!data.contains("linear-typed-output"));
3392 assert!(!data.contains("Glass Scorecard"));
3393 assert!(!data.contains("target"));
3394 }
3395 #[test]
3396 fn metadata_round_trip_is_serde_stable_and_bounded() {
3397 let mut record = record();
3398 record.source.surface = KnowledgeSurfaceProvenance {
3399 kind: KnowledgeSurfaceKind::Document,
3400 understanding: KnowledgeUnderstandingLevel::Strong,
3401 coverage: KnowledgeSurfaceCoverage::Semantic,
3402 extension_id: None,
3403 };
3404 record.source.backend = KnowledgeBackendProvenance {
3405 backend: KnowledgeBackendKind::Cdp,
3406 profile: "production".into(),
3407 capabilities: vec![
3408 KnowledgeBackendCapability::SemanticExtraction,
3409 KnowledgeBackendCapability::Verification,
3410 ],
3411 };
3412 record.portability = KnowledgePortability::SurfacePortable;
3413 record.retrieval.signals = vec![KnowledgeRetrievalSignal {
3414 kind: KnowledgeRetrievalSignalKind::ExactPageFamilyMatch,
3415 detail: "same page family".into(),
3416 score_millis: Some(1_000),
3417 }];
3418 record.validate().unwrap();
3419 let json = record.to_canonical_json().unwrap();
3420 let parsed: KnowledgeRecord = serde_json::from_str(&json).unwrap();
3421 assert_eq!(parsed, record);
3422 assert!(json.contains("\"surface\""));
3423 assert!(json.contains("\"backend\""));
3424 assert!(json.contains("\"surfacePortable\""));
3425 assert!(json.contains("\"exactPageFamilyMatch\""));
3426 }
3427
3428 #[test]
3429 fn legacy_snapshot_uses_fail_closed_additive_defaults() {
3430 let legacy = r#"{
3431 "schemaVersion":1,
3432 "records":[{
3433 "schemaVersion":1,
3434 "recordId":"legacy",
3435 "kind":"pageFamily",
3436 "scope":{
3437 "origin":"https://example.test",
3438 "pathPattern":"/docs/*",
3439 "profileScope":"anonymous",
3440 "browserFamily":"chromium",
3441 "glassSchemaVersion":1,
3442 "policyPreset":"balanced"
3443 },
3444 "source":{
3445 "firstSeenAt":"2026-07-27T00:00:00Z",
3446 "lastVerifiedAt":"2026-07-27T00:00:00Z",
3447 "glassVersion":"0.2.0",
3448 "verificationCount":1
3449 },
3450 "confidence":"observed",
3451 "invalidation":{},
3452 "data":{"pageKind":"documentation"}
3453 }]
3454 }"#;
3455 let snapshot: KnowledgeStoreSnapshot = serde_json::from_str(legacy).unwrap();
3456 snapshot.validate().unwrap();
3457 let migrated = &snapshot.records[0];
3458 assert_eq!(migrated.source.surface.kind, KnowledgeSurfaceKind::Opaque);
3459 assert_eq!(
3460 migrated.source.backend.backend,
3461 KnowledgeBackendKind::Unknown
3462 );
3463 assert_eq!(migrated.portability, KnowledgePortability::NonPortable);
3464 assert_eq!(migrated.memory_influence, KnowledgeMemoryInfluence::None);
3465 assert_eq!(
3466 migrated.retrieval.current_validation.status,
3467 KnowledgeCurrentValidationStatus::NotValidated
3468 );
3469 let expected: Value = serde_json::from_str(legacy).unwrap();
3470 assert_eq!(serde_json::to_value(&snapshot).unwrap(), expected);
3471 }
3472
3473 #[test]
3474 fn invalid_metadata_fails_closed_and_sensitive_profile_is_rejected() {
3475 let unknown = serde_json::from_str::<KnowledgeSurfaceKind>(r#""futureSurface""#);
3476 assert!(unknown.is_err());
3477 let mut base = record();
3478 base.source.backend.profile = "session-token-profile".into();
3479 let error = base.validate().unwrap_err();
3480 assert_eq!(error.path, "source.backend.profile");
3481 base.source.surface.kind = KnowledgeSurfaceKind::ExtensionDefined;
3482 let error = base.validate().unwrap_err();
3483 assert_eq!(error.path, "source.surface.extensionId");
3484 base.source.surface.extension_id = Some("x".repeat(MAX_EXTENSION_ID_BYTES + 1));
3485 let error = base.validate().unwrap_err();
3486 assert_eq!(error.path, "source.surface.extensionId");
3487
3488 let mut influenced = record();
3489 influenced.source.backend.profile = "production".into();
3490 influenced.memory_influence = KnowledgeMemoryInfluence::RankingOnly;
3491 influenced.retrieval.current_validation = KnowledgeCurrentValidation::default();
3492 let error = influenced.validate().unwrap_err();
3493 assert_eq!(error.path, "memoryInfluence");
3494 }
3495 #[test]
3496 fn boolean_freshness_cannot_promote_without_witness() {
3497 let mut value = record();
3498 value.retrieval.current_validation = KnowledgeCurrentValidation::default();
3499 let before = value.clone();
3500 let error = value
3501 .transition(
3502 KnowledgeConfidence::Verified,
3503 "boolean is insufficient".into(),
3504 "2026-07-27T00:00:01Z".into(),
3505 true,
3506 )
3507 .unwrap_err();
3508 assert_eq!(error.path, "currentValidation");
3509 assert_eq!(value, before);
3510 value
3511 .transition_with_validation(
3512 KnowledgeConfidence::Verified,
3513 "revision witness".into(),
3514 "2026-07-27T00:00:01Z".into(),
3515 43,
3516 KnowledgeEvidenceQuality::Strong,
3517 )
3518 .unwrap();
3519 assert_eq!(value.confidence, KnowledgeConfidence::Verified);
3520 }
3521
3522 #[test]
3523 fn fresh_transition_validates_memory_but_never_authorizes_mutation() {
3524 let mut record = record();
3525 assert_eq!(
3526 record.retrieval.current_validation.status,
3527 KnowledgeCurrentValidationStatus::Validated
3528 );
3529 record
3530 .transition(
3531 KnowledgeConfidence::Verified,
3532 "historical-only".into(),
3533 "2026-07-27T00:00:01Z".into(),
3534 false,
3535 )
3536 .unwrap_err();
3537 record
3538 .transition(
3539 KnowledgeConfidence::Verified,
3540 "fresh browser evidence".into(),
3541 "2026-07-27T00:00:01Z".into(),
3542 true,
3543 )
3544 .unwrap();
3545 assert_eq!(
3546 record.retrieval.current_validation.status,
3547 KnowledgeCurrentValidationStatus::Validated
3548 );
3549 assert!(record.data.get("reference").is_none());
3550 assert!(record.data.get("target").is_none());
3551 }
3552}