mant-protocol 0.11.0

Transport-neutral query contracts and projections for ManT
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
//! Stable contracts for bounded queries over a linked set of documents.

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::{
    DocumentAddress, SearchCase, SearchHit, SearchQuery, SearchRender, SearchScope, SearchSyntax,
    default_search_limit,
};

/// Maximum number of initial documents accepted by the native scope contract.
pub const MAX_SCOPE_DOCUMENTS: usize = 16;
/// Default maximum number of link edges followed from an initial document.
pub const DEFAULT_SCOPE_DEPTH: u16 = 8;
/// Hard maximum number of link edges accepted by the native scope contract.
pub const MAX_SCOPE_DEPTH: u16 = 32;
/// Default maximum number of distinct documents in one resolved scope.
pub const DEFAULT_SCOPE_DOCUMENT_LIMIT: u32 = 64;
/// Hard maximum number of distinct documents in one resolved scope.
pub const MAX_SCOPE_DOCUMENT_LIMIT: u32 = 256;
/// Maximum aggregate normalized-document payload retained by one scope.
///
/// Scope resolution keeps each parsed document in memory so later search,
/// explanation, and interactive navigation observe one consistent graph. This
/// independent guard prevents a small number of individually valid documents
/// from creating an unbounded aggregate allocation.
pub const MAX_SCOPE_CONTENT_BYTES: u64 = 64 * 1024 * 1024;
/// Maximum Unicode scalar length of one logical document selector.
pub const MAX_DOCUMENT_SELECTOR_CHARS: usize = 1024;
/// Maximum Unicode scalar length of one semantic-entry selector.
pub const MAX_SEMANTIC_ENTRY_CHARS: usize = 512;
/// Maximum Unicode scalar length of one search pattern.
pub const MAX_SEARCH_PATTERN_CHARS: usize = 4096;
/// Maximum Unicode scalar length of one configured Markdown source selector.
pub const MAX_SOURCE_SELECTOR_CHARS: usize = 128;
/// Maximum Unicode scalar length of one native manual section selector.
pub const MAX_MANUAL_SECTION_CHARS: usize = 32;

/// One violated runtime constraint shared by scope-query request adapters.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScopeTextError {
    /// The value was empty after trimming surrounding whitespace.
    Empty,
    /// The value contained a terminal or structural control character.
    ControlCharacter,
    /// The Unicode scalar length exceeded the declared maximum.
    TooLong {
        /// Inclusive maximum accepted Unicode scalar length.
        maximum: usize,
    },
}

/// Validate one bounded logical selector at the native request boundary.
///
/// JSON Schema advertises the same limits, but native `--request-json` callers
/// do not pass through a schema validator, so the runtime contract must check
/// them independently.
///
/// # Errors
///
/// Returns the precise empty, control-character, or scalar-length violation.
pub fn validate_scope_text(value: &str, maximum: usize) -> Result<(), ScopeTextError> {
    if value.trim().is_empty() {
        return Err(ScopeTextError::Empty);
    }
    if value.chars().any(char::is_control) {
        return Err(ScopeTextError::ControlCharacter);
    }
    if value.chars().count() > maximum {
        return Err(ScopeTextError::TooLong { maximum });
    }
    Ok(())
}

/// One logical document selector before catalog resolution.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DocumentSelector {
    /// Unqualified name or complete catalog path.
    #[schemars(length(min = 1, max = MAX_DOCUMENT_SELECTOR_CHARS))]
    pub selector: String,
    /// Optional configured Markdown source for an unqualified selector.
    #[schemars(length(min = 1, max = MAX_SOURCE_SELECTOR_CHARS))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    /// Optional native manual category for an unqualified selector.
    #[schemars(length(min = 1, max = MAX_MANUAL_SECTION_CHARS))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub manual_section: Option<String>,
}

/// Bounded traversal applied after resolving the initial documents.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DocumentTraversal {
    /// Follow typed links to other registered documents.
    #[serde(default)]
    pub follow_links: bool,
    /// Optional maximum number of link edges from an initial document.
    ///
    /// Omission selects [`DEFAULT_SCOPE_DEPTH`] when [`Self::follow_links`] is
    /// true. The field is invalid when link traversal is disabled.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(range(max = 32))]
    pub max_depth: Option<u16>,
    /// Optional maximum number of distinct documents, including roots.
    ///
    /// Omission selects [`DEFAULT_SCOPE_DOCUMENT_LIMIT`] when
    /// [`Self::follow_links`] is true. The field is invalid when link traversal
    /// is disabled.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(range(min = 1, max = 256))]
    pub max_documents: Option<u32>,
}

impl DocumentTraversal {
    /// Effective edge limit after applying the native default.
    #[must_use]
    pub fn effective_max_depth(self) -> u16 {
        self.max_depth.unwrap_or(DEFAULT_SCOPE_DEPTH)
    }

    /// Effective document budget after applying the native default.
    #[must_use]
    pub fn effective_max_documents(self) -> u32 {
        self.max_documents.unwrap_or(DEFAULT_SCOPE_DOCUMENT_LIMIT)
    }
}

/// Return [`DEFAULT_SCOPE_DEPTH`].
#[must_use]
pub const fn default_scope_depth() -> u16 {
    DEFAULT_SCOPE_DEPTH
}

/// Return [`DEFAULT_SCOPE_DOCUMENT_LIMIT`].
#[must_use]
pub const fn default_scope_document_limit() -> u32 {
    DEFAULT_SCOPE_DOCUMENT_LIMIT
}

/// Initial documents and the link policy used to expand them.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DocumentScope {
    /// Ordered initial documents. The first one is the initial TUI page.
    #[schemars(length(min = 1, max = 16))]
    pub documents: Vec<DocumentSelector>,
    /// Deterministic outbound-link traversal policy.
    #[serde(default)]
    pub traversal: DocumentTraversal,
}

/// Exact schema marker for a scope-query request.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum ScopeRequestSchema {
    /// Version 0.11 of the pre-stable scope-query request.
    #[serde(rename = "mant.scope-request/v0.11")]
    V0Dot11,
}

impl ScopeRequestSchema {
    /// Serialized identifier of the current request contract.
    pub const ID: &'static str = "mant.scope-request/v0.11";
}

/// Query projection supported over a document set.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(
    tag = "kind",
    rename_all = "kebab-case",
    rename_all_fields = "camelCase",
    deny_unknown_fields
)]
pub enum ScopeQueryView {
    /// Collect independent evidence across loaded documents.
    Explain {
        /// Documented name, full form, exact entry ID/path, or bounded literal.
        #[schemars(length(min = 1, max = MAX_SEMANTIC_ENTRY_CHARS))]
        entry: String,
        /// Global result pagination and copied-content budget.
        #[serde(default)]
        options: crate::ExplanationOptions,
    },
    /// Search visible or generated-Markdown text over the complete scope.
    Search {
        /// Literal or regular-expression search pattern.
        #[schemars(length(min = 1, max = MAX_SEARCH_PATTERN_CHARS))]
        pattern: String,
        /// Pattern language.
        #[serde(default)]
        syntax: SearchSyntax,
        /// Case-matching policy.
        #[serde(default)]
        case: SearchCase,
        /// Semantic representation searched.
        #[serde(default)]
        scope: SearchScope,
        /// Require Unicode-aware word boundaries.
        #[serde(default)]
        word: bool,
        /// Neighboring rendered lines included around a match.
        #[serde(default)]
        #[schemars(range(max = 100))]
        context_lines: u16,
        /// Global maximum number of matching line groups returned.
        #[serde(default = "default_search_limit")]
        #[schemars(range(min = 1, max = 10000))]
        limit: u32,
        /// Global number of matching line groups skipped.
        #[serde(default)]
        offset: u32,
    },
}

/// Native request for a bounded multi-document query.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[schemars(extend("$id" = "urn:mant:scope-request:v0.11"))]
pub struct ScopeQueryRequest {
    /// Exact request schema discriminator.
    pub schema: ScopeRequestSchema,
    /// Initial documents and traversal limits.
    pub scope: DocumentScope,
    /// Projection applied independently to resolved documents.
    pub view: ScopeQueryView,
}

/// Exact schema marker for a resolved scope query.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum ScopeQuerySchema {
    /// Version 0.11 of the pre-stable scope-query result.
    #[serde(rename = "mant.scope-query/v0.11")]
    V0Dot11,
}

impl ScopeQuerySchema {
    /// Serialized identifier of the current result contract.
    pub const ID: &'static str = "mant.scope-query/v0.11";
}

/// Typed cross-document edge retained in a resolved scope.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum DocumentEdgeKind {
    /// A relative Markdown link inside one registered namespace.
    Document,
    /// A semantic native-manual reference.
    Manual,
}

/// Traversal bound that excluded an outbound logical link.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum TraversalLimit {
    /// The maximum number of followed link edges was reached.
    MaxDepth,
    /// The maximum number of distinct loaded documents was reached.
    MaxDocuments,
    /// Retaining another normalized document would exceed the aggregate
    /// semantic-content budget.
    MaxContentBytes,
}

/// One typed outbound link excluded by a traversal bound.
///
/// A frontier retains the logical selector rather than requiring a resolved
/// address: resolving a target may itself exceed the requested bound.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct DocumentFrontier {
    /// Address containing the excluded link.
    pub from: DocumentAddress,
    /// Logical target that would be resolved if traversal continued.
    pub target: DocumentSelector,
    /// Semantic link family.
    pub kind: DocumentEdgeKind,
    /// Bound that prevented traversal of this link.
    pub limit: TraversalLimit,
}

/// One resolved edge in source order.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct DocumentEdge {
    /// Address containing the link.
    pub from: DocumentAddress,
    /// Resolved linked address.
    pub to: DocumentAddress,
    /// Semantic link family.
    pub kind: DocumentEdgeKind,
}

/// One distinct document in breadth-first traversal order.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct ScopedDocument {
    /// Stable logical document identity.
    pub address: DocumentAddress,
    /// Minimum outbound-link distance from any initial document.
    pub depth: u16,
    /// Initial document positions that resolve to this address.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub root_indices: Vec<u16>,
    /// Distinct documents whose links reached this address.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reached_from: Vec<DocumentAddress>,
}

/// A seed or typed link that could not be resolved.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct UnresolvedDocument {
    /// Referring document, omitted for an initial selector.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from: Option<DocumentAddress>,
    /// Original logical selector or link target.
    pub selector: DocumentSelector,
    /// Stable, concise resolution diagnostic.
    pub reason: String,
}

/// Logical graph produced before applying a projection.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct ResolvedDocumentScope {
    /// Original normalized scope request.
    pub query: DocumentScope,
    /// Distinct documents in deterministic breadth-first order.
    pub documents: Vec<ScopedDocument>,
    /// Successfully resolved typed edges in source order.
    pub edges: Vec<DocumentEdge>,
    /// Typed outbound links excluded by depth, document, or content limits.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub frontier: Vec<DocumentFrontier>,
    /// Seeds and edges that could not resolve to a readable document.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub unresolved: Vec<UnresolvedDocument>,
    /// Documents whose outbound reference scan was incomplete. Missing edges
    /// are unknown, not proof that these documents have no further links.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reference_limits: Vec<ScopeReferenceLimit>,
}

/// A bounded outbound scan that could not establish the complete edge set.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ScopeReferenceLimit {
    /// Loaded logical source document, never a host filesystem path.
    pub document: DocumentAddress,
    /// Shared traversal accounting and first stop condition.
    pub coverage: crate::ReferenceCoverage,
    /// Distinct reference retention cap, when it caused the stop.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retention_limit: Option<crate::ReferencePageLimit>,
}

/// One document's search hits inside a globally paginated scope result.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct ScopedSearchDocument {
    /// Stable logical document identity.
    pub address: DocumentAddress,
    /// Distance retained from the resolved scope.
    pub depth: u16,
    /// Canonical Markdown coordinate space for this document's hits.
    pub render: SearchRender,
    /// Matching line groups retained from the globally paginated result set.
    /// Their ordinals are global across all documents in the scope.
    pub matches: Vec<SearchHit>,
}

/// Globally paginated search over a resolved document scope.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct ScopeSearch {
    /// Normalized search configuration.
    pub query: SearchQuery,
    /// Matching line groups across all documents before pagination.
    pub total: u32,
    /// Matching line groups present in this response.
    pub returned: u32,
    /// Applied global zero-based offset.
    pub offset: u32,
    /// Whether additional matching line groups remain.
    pub truncated: bool,
    /// Global offset for the next page.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_offset: Option<u32>,
    /// Non-empty document groups in scope order.
    pub documents: Vec<ScopedSearchDocument>,
}

/// One readable document's contribution to the evidence result.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ScopedExplanation {
    /// Declaration context pool for evidence with this document index.
    pub supports: Vec<crate::ExplanationSupport>,
    /// Stable logical document identity.
    pub address: DocumentAddress,
    /// Distance retained from the resolved scope.
    pub depth: u16,
    /// Selected source label, independent of catalog identity.
    pub label: String,
    /// Parser and process provenance when available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub producer: Option<crate::Producer>,
    /// Recoverable producer and shared invariant findings.
    pub diagnostics: Vec<mant_ir::Diagnostic>,
    /// Semantic validation, not evidence recall.
    pub semantics_complete: bool,
    /// Normal local evidence/no-evidence outcome before global pagination.
    pub outcome: crate::ExplanationOutcome,
    /// Local collected owners.
    pub total: u32,
    /// Local owners selected on the one global page.
    pub returned: u32,
    /// Local contributions to each global evidence category.
    pub counts: crate::EvidenceCounts,
    /// Local collection and copy truncation.
    pub truncation: crate::ExplanationTruncation,
}

/// One global evidence record with an explicit source-report reference.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ScopedExplanationEvidence {
    /// Zero-based index into this explanation's documents, not the scope graph.
    pub document_index: usize,
    /// The unique record; bodies are never duplicated in the document reports.
    pub evidence: crate::ExplanationEvidence,
}

/// One per-document projection failure that does not invalidate other results.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct ScopedQueryFailure {
    /// Stable logical document identity.
    pub address: DocumentAddress,
    /// Concise projection diagnostic.
    pub reason: String,
}

/// Projection result carried by a scope-query response.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(
    tag = "kind",
    rename_all = "kebab-case",
    rename_all_fields = "camelCase"
)]
pub enum ScopeQueryResult {
    /// Semantic entries found across the scope.
    Explain {
        /// Globally bounded evidence with coverage separate from the scope graph.
        explanation: ScopeExplanation,
    },
    /// Globally paginated text search.
    Search {
        /// Search result grouped by document.
        search: ScopeSearch,
    },
}

/// Global evidence page over a resolved scope. Source loading failures/frontier
/// remain in `ScopeQueryResponse.scope`, independently of this normal outcome.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ScopeExplanation {
    /// Normative global category/BFS/source ordering.
    pub order: crate::EvidenceOrder,
    /// Global per-class totals and page counts.
    pub counts: crate::EvidenceCounts,
    /// Original global pagination/content request.
    pub query: crate::ExplanationQuery,
    /// Evidence/no-evidence before pagination, never uniqueness or recall proof.
    pub outcome: crate::ExplanationOutcome,
    /// Sum of collected owner counts (a lower bound when collection is truncated).
    pub total: u32,
    /// Owners present on this global page.
    pub returned: u32,
    /// Next global result offset when more collected evidence remains.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_offset: Option<u32>,
    /// Independent bounds, combined across readable sources.
    pub truncation: crate::ExplanationTruncation,
    /// Readable documents, including normal zero-evidence contributions.
    pub documents: Vec<ScopedExplanation>,
    /// The only materialized evidence list, in global classification order.
    pub evidence: Vec<ScopedExplanationEvidence>,
    /// Unexpected unreadable loaded content, never normal multiple/zero hits.
    pub failures: Vec<ScopedQueryFailure>,
}

/// Complete bounded multi-document response.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
#[schemars(extend("$id" = "urn:mant:scope-query:v0.11"))]
pub struct ScopeQueryResponse {
    /// Exact response schema discriminator.
    pub schema: ScopeQuerySchema,
    /// Resolved logical graph, including missing links and truncation.
    pub scope: ResolvedDocumentScope,
    /// Requested projection over that graph.
    pub result: ScopeQueryResult,
}

// Remote derive keeps the public schema closed while validating cross-field
// references after structural decoding, without a JSON intermediate tree.
#[derive(Deserialize)]
#[serde(
    remote = "ScopeExplanation",
    rename_all = "camelCase",
    deny_unknown_fields
)]
struct ScopeExplanationWire {
    pub order: crate::EvidenceOrder,
    pub counts: crate::EvidenceCounts,
    pub query: crate::ExplanationQuery,
    pub outcome: crate::ExplanationOutcome,
    pub total: u32,
    pub returned: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_offset: Option<u32>,
    pub truncation: crate::ExplanationTruncation,
    pub documents: Vec<ScopedExplanation>,
    pub evidence: Vec<ScopedExplanationEvidence>,
    pub failures: Vec<ScopedQueryFailure>,
}
impl<'de> Deserialize<'de> for ScopeExplanation {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = ScopeExplanationWire::deserialize(deserializer)?;
        value
            .validate_references()
            .map_err(serde::de::Error::custom)?;
        Ok(value)
    }
}