index-ai 1.0.0

Optional AI-assisted transformation boundary for Index documents.
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
//! Optional AI-assisted transformation boundary.
//!
//! This crate defines provider traits, prompt templates, privacy preparation,
//! and deterministic local fallbacks. It performs no network IO.

use std::fmt::{Display, Formatter};

use index_core::{IndexDocument, IndexNode, Link, Redactor};
use index_extract::{ExtractFormat, extract_document};

/// Version identifier for prompt templates shipped in this crate.
pub const PROMPT_TEMPLATE_VERSION: &str = "index-ai-prompt-v1";

const EXPLAIN_SYSTEM_PROMPT: &str = "Explain the Index document in concise terminal-native terms.";
const SUMMARIZE_SYSTEM_PROMPT: &str =
    "Summarize the Index document without adding unsupported claims.";
const EXTRACT_SYSTEM_PROMPT: &str =
    "Extract structured facts from the Index document as short bullet points.";

/// AI-assisted action requested by a user.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AiAction {
    /// Explain the document.
    Explain,
    /// Summarize the document.
    Summarize,
    /// Extract facts from the document.
    Extract,
}

impl AiAction {
    /// Parses an AI action name.
    #[must_use]
    pub fn parse(input: &str) -> Option<Self> {
        match input.trim().to_ascii_lowercase().as_str() {
            "explain" => Some(Self::Explain),
            "summarize" | "summary" => Some(Self::Summarize),
            "extract" => Some(Self::Extract),
            _ => None,
        }
    }

    /// Returns the canonical action name.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Explain => "explain",
            Self::Summarize => "summarize",
            Self::Extract => "extract",
        }
    }
}

impl Display for AiAction {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Prompt template metadata.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PromptTemplate {
    /// Stable template version.
    pub version: &'static str,
    /// Action this template is for.
    pub action: AiAction,
    /// System instruction text.
    pub system: &'static str,
}

/// Returns the prompt template for an AI action.
#[must_use]
pub const fn prompt_template(action: AiAction) -> PromptTemplate {
    let system = match action {
        AiAction::Explain => EXPLAIN_SYSTEM_PROMPT,
        AiAction::Summarize => SUMMARIZE_SYSTEM_PROMPT,
        AiAction::Extract => EXTRACT_SYSTEM_PROMPT,
    };
    PromptTemplate {
        version: PROMPT_TEMPLATE_VERSION,
        action,
        system,
    }
}

/// Privacy mode for prompt preparation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrivacyMode {
    /// Redact credential-shaped content before a provider sees it.
    Redacted,
    /// Permit page text after the user explicitly invokes an AI action.
    AllowPageContent,
}

/// Prepared prompt sent to an AI provider.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AiPrompt {
    /// Stable prompt template version.
    pub template_version: String,
    /// Requested action.
    pub action: AiAction,
    /// System prompt.
    pub system: String,
    /// User prompt.
    pub user: String,
    /// Privacy mode used while preparing the prompt.
    pub privacy_mode: PrivacyMode,
}

/// AI provider request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AiRequest {
    /// Prepared prompt.
    pub prompt: AiPrompt,
}

/// AI provider response.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AiResponse {
    /// Provider response text.
    pub text: String,
    /// Whether the response came from deterministic local fallback logic.
    pub deterministic_fallback: bool,
}

/// Errors returned by AI providers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AiError {
    /// Provider failed.
    Provider(String),
    /// No mock response was configured.
    MissingMockResponse,
}

impl Display for AiError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Provider(message) => write!(f, "AI provider failed: {message}"),
            Self::MissingMockResponse => f.write_str("AI mock provider has no response"),
        }
    }
}

impl std::error::Error for AiError {}

/// AI provider abstraction.
pub trait AiProvider {
    /// Transforms a prepared prompt into a response.
    fn transform(&self, request: &AiRequest) -> Result<AiResponse, AiError>;
}

/// Deterministic local/offline provider.
#[derive(Debug, Clone, Copy, Default)]
pub struct OfflineProvider;

impl AiProvider for OfflineProvider {
    fn transform(&self, request: &AiRequest) -> Result<AiResponse, AiError> {
        Ok(AiResponse {
            text: deterministic_fallback(&request.prompt),
            deterministic_fallback: true,
        })
    }
}

/// Mock provider for tests and adapter integration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MockProvider {
    response: Option<AiResponse>,
}

impl MockProvider {
    /// Creates a mock provider with a response.
    #[must_use]
    pub fn with_response(text: impl Into<String>) -> Self {
        Self {
            response: Some(AiResponse {
                text: text.into(),
                deterministic_fallback: false,
            }),
        }
    }

    /// Creates a mock provider with no response.
    #[must_use]
    pub const fn empty() -> Self {
        Self { response: None }
    }
}

impl AiProvider for MockProvider {
    fn transform(&self, _request: &AiRequest) -> Result<AiResponse, AiError> {
        self.response.clone().ok_or(AiError::MissingMockResponse)
    }
}

/// Prepares an AI request from a document.
#[must_use]
pub fn prepare_ai_request(
    document: &IndexDocument,
    action: AiAction,
    privacy_mode: PrivacyMode,
    redactor: &Redactor,
) -> AiRequest {
    let template = prompt_template(action);
    let document_text = document_for_prompt(document, action);
    let user = match privacy_mode {
        PrivacyMode::Redacted => redactor.redact(&document_text),
        PrivacyMode::AllowPageContent => document_text,
    };

    AiRequest {
        prompt: AiPrompt {
            template_version: template.version.to_owned(),
            action,
            system: template.system.to_owned(),
            user,
            privacy_mode,
        },
    }
}

/// Runs an action through a provider.
pub fn run_ai_action<P: AiProvider>(
    provider: &P,
    document: &IndexDocument,
    action: AiAction,
    privacy_mode: PrivacyMode,
    redactor: &Redactor,
) -> Result<AiResponse, AiError> {
    let request = prepare_ai_request(document, action, privacy_mode, redactor);
    provider.transform(&request)
}

fn document_for_prompt(document: &IndexDocument, action: AiAction) -> String {
    match action {
        AiAction::Explain | AiAction::Summarize => {
            extract_document(document, ExtractFormat::Markdown)
        }
        AiAction::Extract => extract_document(document, ExtractFormat::Json),
    }
}

fn deterministic_fallback(prompt: &AiPrompt) -> String {
    let title = prompt
        .user
        .lines()
        .find_map(|line| line.strip_prefix("# "))
        .unwrap_or("Untitled document");
    let facts = prompt
        .user
        .lines()
        .filter(|line| !line.trim().is_empty())
        .take(4)
        .collect::<Vec<_>>();

    match prompt.action {
        AiAction::Explain => format!(
            "Offline explain: {title}. This document has {} visible prompt lines.",
            facts.len()
        ),
        AiAction::Summarize => {
            let summary = facts.join(" ");
            format!("Offline summary: {summary}")
        }
        AiAction::Extract => format!(
            "Offline extract:\n- template: {}\n- prompt_lines: {}",
            prompt.template_version,
            facts.len()
        ),
    }
}

/// Collects links from a document for provider-side context.
#[must_use]
pub fn document_links(document: &IndexDocument) -> Vec<&Link> {
    document
        .nodes
        .iter()
        .filter_map(|node| match node {
            IndexNode::Link(link) => Some(link),
            _ => None,
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use index_core::{IndexDocument, IndexNode, Link, Redactor};

    use super::{
        AiAction, AiError, MockProvider, OfflineProvider, PrivacyMode, document_links,
        prepare_ai_request, prompt_template, run_ai_action,
    };

    fn document() -> IndexDocument {
        let mut document = IndexDocument::titled("AI Fixture");
        document.push(IndexNode::Paragraph(
            "Visible body token=secret Authorization: Bearer abc123".to_owned(),
        ));
        document.push(IndexNode::Link(Link::new(
            "Docs",
            "https://example.com/docs",
        )));
        document
    }

    #[test]
    fn prompt_template_snapshot_is_versioned() {
        let template = prompt_template(AiAction::Summarize);
        assert_eq!(template.version, "index-ai-prompt-v1");
        assert_eq!(
            template.system,
            "Summarize the Index document without adding unsupported claims."
        );
    }

    #[test]
    fn action_parser_accepts_supported_actions() {
        assert_eq!(AiAction::parse("explain"), Some(AiAction::Explain));
        assert_eq!(AiAction::parse("summary"), Some(AiAction::Summarize));
        assert_eq!(AiAction::parse("extract"), Some(AiAction::Extract));
        assert_eq!(AiAction::parse("chat"), None);
    }

    #[test]
    fn redacted_prompt_hides_known_credential_fields() {
        let mut redactor = Redactor::new();
        redactor.add_secret("abc123");
        let request = prepare_ai_request(
            &document(),
            AiAction::Summarize,
            PrivacyMode::Redacted,
            &redactor,
        );

        assert!(request.prompt.user.contains("[REDACTED]"));
        assert!(!request.prompt.user.contains("abc123"));
        assert!(!request.prompt.user.contains("token=secret"));
    }

    #[test]
    fn explicit_page_content_mode_preserves_document_text() {
        let redactor = Redactor::new();
        let request = prepare_ai_request(
            &document(),
            AiAction::Summarize,
            PrivacyMode::AllowPageContent,
            &redactor,
        );

        assert!(request.prompt.user.contains("token=secret"));
    }

    #[test]
    fn offline_provider_returns_deterministic_fallback() {
        let redactor = Redactor::new();
        let response = run_ai_action(
            &OfflineProvider,
            &document(),
            AiAction::Explain,
            PrivacyMode::Redacted,
            &redactor,
        );

        assert!(
            matches!(response, Ok(response) if response.deterministic_fallback && response.text.contains("Offline explain"))
        );
    }

    #[test]
    fn mock_provider_returns_configured_response() {
        let provider = MockProvider::with_response("provider text");
        let redactor = Redactor::new();
        let response = run_ai_action(
            &provider,
            &document(),
            AiAction::Extract,
            PrivacyMode::Redacted,
            &redactor,
        );

        assert!(matches!(response, Ok(response) if response.text == "provider text"));
    }

    #[test]
    fn mock_provider_reports_missing_response() {
        let redactor = Redactor::new();
        let response = run_ai_action(
            &MockProvider::empty(),
            &document(),
            AiAction::Extract,
            PrivacyMode::Redacted,
            &redactor,
        );

        assert_eq!(response, Err(AiError::MissingMockResponse));
    }

    #[test]
    fn document_link_context_uses_document_model_links() {
        let document = document();
        let links = document_links(&document);
        assert_eq!(links.len(), 1);
        assert_eq!(links[0].href, "https://example.com/docs");
    }
}