rootle-stdio 0.12.2

External rootle providers: NDJSON-RPC 2.0 over stdio child processes (the LSP model)
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
//! Wire mapping: each `trait Provider` method as one NDJSON-RPC round
//! trip, with its reply shape. Wire structs live next to the method
//! that reads them — the shapes are the provider-protocol contract
//! (doc/provider-protocol.md), versioned in lockstep.

use super::StdioProvider;
use super::transport::{cancel_notification, de};
use rootle_provider::{
    BlameRange, Capabilities, CodeMatch, CommitDetail, ErrorKind, GitRef, LogEntry, Provider,
    ProviderError, ProviderResult, RefInfo, RepoId, RepoInfo, RepoRefs, SearchCodeResult,
    SearchItem, Sha, TreeNode, TreeResult,
};
use serde_json::json;
use std::io::Write;
use std::sync::atomic::Ordering;

impl Provider for StdioProvider {
    fn name(&self) -> &str {
        &self.name
    }

    fn icon(&self) -> Option<String> {
        self.icon.clone()
    }

    fn capabilities(&self) -> Capabilities {
        self.capabilities
    }

    fn search(&self, query: &str) -> ProviderResult<Vec<SearchItem>> {
        #[derive(serde::Deserialize)]
        struct RepositorySearchReply {
            #[serde(default)]
            items: Vec<Item>,
        }
        #[derive(serde::Deserialize)]
        struct Item {
            full_name: Option<String>,
            org: Option<String>,
        }
        let reply: RepositorySearchReply =
            de(self.request("search/repos", json!({ "query": query }))?)?;
        Ok(reply
            .items
            .into_iter()
            .filter_map(|i| match (i.full_name, i.org) {
                (Some(r), _) => Some(SearchItem::Repo(r)),
                (None, Some(o)) => Some(SearchItem::Org(o)),
                _ => None,
            })
            .collect())
    }

    fn org_repos(&self, org: &str) -> ProviderResult<Vec<RepoInfo>> {
        #[derive(serde::Deserialize)]
        struct OrganizationRepositoriesReply {
            #[serde(default)]
            repos: Vec<RepoEntry>,
        }
        /// v1.4: entries are the bare name or an object riding reader
        /// tolerance — `{name, description?, private?, archived?,
        /// pushed_at?}` (doc/provider-protocol.md).
        #[derive(serde::Deserialize)]
        #[serde(untagged)]
        enum RepoEntry {
            Name(String),
            Meta {
                name: String,
                description: Option<String>,
                #[serde(default)]
                private: bool,
                #[serde(default)]
                archived: bool,
                pushed_at: Option<String>,
            },
        }
        let reply: OrganizationRepositoriesReply =
            de(self.request("org/repos", json!({ "org": org }))?)?;
        Ok(reply
            .repos
            .into_iter()
            .map(|e| match e {
                RepoEntry::Name(name) => RepoInfo::bare(name),
                RepoEntry::Meta {
                    name,
                    description,
                    private,
                    archived,
                    pushed_at,
                } => RepoInfo {
                    name,
                    description,
                    private,
                    archived,
                    pushed_at,
                },
            })
            .collect())
    }

    fn fetch_tree(&self, repo: &RepoId, ref_: Option<&GitRef>) -> ProviderResult<TreeResult> {
        #[derive(serde::Deserialize)]
        struct RepositoryTreeReply {
            #[serde(default)]
            entries: Vec<Entry>,
            #[serde(default)]
            truncated: bool,
            #[serde(default = "main")]
            branch: String,
        }
        #[derive(serde::Deserialize)]
        struct Entry {
            path: String,
            #[serde(rename = "type")]
            kind: String, // "blob" | "tree"
            sha: String,
            size: Option<u64>,
        }
        fn main() -> String {
            "main".into()
        }
        let reply: RepositoryTreeReply =
            de(self.request("repo/tree", json!({ "repo": repo, "ref": ref_ }))?)?;
        Ok(TreeResult {
            entries: reply
                .entries
                .into_iter()
                .map(|e| TreeNode {
                    path: e.path,
                    is_dir: e.kind == "tree",
                    sha: e.sha,
                    size: e.size,
                })
                .collect(),
            truncated: reply.truncated,
            branch: reply.branch,
        })
    }

    fn fetch_blob(&self, repo: &RepoId, sha: &Sha) -> ProviderResult<Vec<u8>> {
        #[derive(serde::Deserialize)]
        struct BlobReply {
            bytes_b64: String,
        }
        let reply: BlobReply = de(self.request("repo/blob", json!({ "repo": repo, "sha": sha }))?)?;
        use base64::Engine;
        base64::engine::general_purpose::STANDARD
            .decode(reply.bytes_b64)
            .map_err(|e| ProviderError::other(format!("provider blob base64: {e}")))
    }

    fn web_url(
        &self,
        repo: &RepoId,
        path: &str,
        branch: Option<&GitRef>,
        line: Option<u32>,
        end: Option<u32>,
        is_file: bool,
    ) -> ProviderResult<String> {
        #[derive(serde::Deserialize)]
        struct RepositoryUrlReply {
            url: String,
        }
        let reply: RepositoryUrlReply = de(self.request(
            "repo/web_url",
            json!({ "repo": repo, "path": path, "branch": branch.map(GitRef::as_str).unwrap_or(""), "line": line, "end_line": end, "is_file": is_file }),
        )?)?;
        Ok(reply.url)
    }

    fn org_url(&self, org: &str) -> ProviderResult<String> {
        #[derive(serde::Deserialize)]
        struct OrganizationUrlReply {
            url: String,
        }
        let reply: OrganizationUrlReply = de(self.request("org/url", json!({ "org": org }))?)?;
        Ok(reply.url)
    }

    fn clone_url(&self, repo: &RepoId) -> ProviderResult<String> {
        #[derive(serde::Deserialize)]
        struct CloneUrlReply {
            clone_url: String,
        }
        let reply: CloneUrlReply = de(self.request("repo/clone_url", json!({ "repo": repo }))?)?;
        Ok(reply.clone_url)
    }

    fn search_code(&self, q: &str) -> ProviderResult<SearchCodeResult> {
        let r: CodeReply = de(self.request(
            "search/code",
            json!({ "q": q, "limit": rootle_provider::RENDER_BUDGET }),
        )?)?;
        Ok(SearchCodeResult {
            hits: code_matches(&r.items),
            truncated: r.truncated,
            index_as_of: r.index.as_of,
        })
    }

    /// v1.3 progressive search (plans/0011): `partial: true` opts into
    /// `$/partial` batches for this request's id; the reply is
    /// metadata-only when the provider streamed (items empty,
    /// `truncated` authoritative).
    fn search_code_progressive(
        &self,
        q: &str,
        on_hits: &(dyn Fn(&[CodeMatch]) + Send + Sync),
    ) -> ProviderResult<SearchCodeResult> {
        let sink = |params: &serde_json::Value| {
            let items: Vec<WireItem> = params
                .get("items")
                .cloned()
                .and_then(|v| serde_json::from_value(v).ok())
                .unwrap_or_default();
            on_hits(&code_matches(&items));
        };
        let reply: CodeReply = de(self.exchange_with_partials(
            "search/code",
            json!({ "q": q, "partial": true, "limit": rootle_provider::RENDER_BUDGET }),
            &sink,
        )?)?;
        Ok(SearchCodeResult {
            hits: Vec::new(),
            truncated: reply.truncated,
            index_as_of: reply.index.as_of,
        })
    }

    /// v1.5 (plans/0016 M1): branches + tags.
    fn refs(&self, repo: &RepoId) -> ProviderResult<RepoRefs> {
        #[derive(serde::Deserialize)]
        struct RepositoryRefsReply {
            #[serde(default)]
            branches: Vec<RefEntry>,
            #[serde(default)]
            tags: Vec<RefEntry>,
        }
        #[derive(serde::Deserialize)]
        struct RefEntry {
            name: String,
            sha: String,
            #[serde(default)]
            default: bool,
        }
        let reply: RepositoryRefsReply = de(self.request("repo/refs", json!({ "repo": repo }))?)?;
        let map = |e: RefEntry| RefInfo {
            name: e.name,
            sha: e.sha,
            is_default: e.default,
        };
        Ok(RepoRefs {
            branches: reply.branches.into_iter().map(map).collect(),
            tags: reply.tags.into_iter().map(map).collect(),
        })
    }

    /// v1.5: commit log, newest first.
    fn log(
        &self,
        repo: &RepoId,
        path: Option<&str>,
        ref_: Option<&GitRef>,
        limit: Option<usize>,
    ) -> ProviderResult<(Vec<LogEntry>, bool)> {
        #[derive(serde::Deserialize)]
        struct CommitLogReply {
            #[serde(default)]
            items: Vec<LogEntry>,
            #[serde(default)]
            truncated: bool,
        }
        let reply: CommitLogReply = de(self.request(
            "repo/log",
            json!({ "repo": repo, "path": path, "ref": ref_, "limit": limit }),
        )?)?;
        Ok((reply.items, reply.truncated))
    }

    /// v1.5: file bytes + content id at path@ref (open-at-commit).
    fn blob_at(
        &self,
        repo: &RepoId,
        path: &str,
        ref_: Option<&GitRef>,
    ) -> ProviderResult<(Vec<u8>, Sha)> {
        #[derive(serde::Deserialize)]
        struct BlobAtRevisionReply {
            bytes_b64: String,
            sha: String,
        }
        let reply: BlobAtRevisionReply = de(self.request(
            "repo/blob_at",
            json!({ "repo": repo, "path": path, "ref": ref_ }),
        )?)?;
        use base64::Engine;
        let bytes = base64::engine::general_purpose::STANDARD
            .decode(reply.bytes_b64)
            .map_err(|e| ProviderError::new(ErrorKind::Provider, format!("bad base64: {e}")))?;
        Ok((bytes, Sha::from(reply.sha)))
    }

    /// v1.5: blame ranges.
    fn blame(
        &self,
        repo: &RepoId,
        path: &str,
        ref_: Option<&GitRef>,
    ) -> ProviderResult<Vec<BlameRange>> {
        #[derive(serde::Deserialize)]
        struct BlameReply {
            #[serde(default)]
            ranges: Vec<BlameRange>,
        }
        let reply: BlameReply = de(self.request(
            "repo/blame",
            json!({ "repo": repo, "path": path, "ref": ref_ }),
        )?)?;
        Ok(reply.ranges)
    }

    /// v1.6 (plans/0028): one commit's detail — the reply
    /// deserializes straight into the seam type (it already carries
    /// the wire defaults).
    fn commit(&self, repo: &RepoId, sha: &Sha) -> ProviderResult<CommitDetail> {
        de(self.request("repo/commit", json!({ "repo": repo, "sha": sha }))?)
    }

    /// v1.1 advisory cancel: name a request currently in flight, if
    /// any. Best-effort — a racing cancel for an id that just
    /// completed is ignored by the provider by contract.
    fn advise_cancel(&self) {
        let id = self.current_id.load(Ordering::Acquire);
        if id == 0 {
            return;
        }
        let line = cancel_notification(id);
        let session = self.shared.routing.lock().session;
        let mut process = self.process.lock();
        let written = writeln!(process.stdin, "{line}")
            .and_then(|()| process.stdin.flush())
            .is_ok();
        crate::trace::tx_cancel(session, id, line.len() as u64 + 1, written);
    }

    /// One-shot restart notice for the status line (plans/0008 §5).
    fn take_notice(&self) -> Option<String> {
        self.notice.lock().take()
    }

    /// Cache usage reported at the initialize handshake, when the
    /// provider participates in the advisory budget (v1.2).
    fn cache_usage(&self) -> Option<u64> {
        *self.cache_used.lock()
    }
}

/// `search/code` reply (items present only when the provider did not
/// stream) — the protocol v1.3 contract.
#[derive(serde::Deserialize)]
struct CodeReply {
    #[serde(default)]
    items: Vec<WireItem>,
    /// v1.2 (plans/0008 §4): provider capped its result set.
    #[serde(default)]
    truncated: bool,
    /// v1.3: index-wide freshness for indexed backends.
    #[serde(default)]
    index: IndexInfo,
}

#[derive(serde::Deserialize, Default)]
struct IndexInfo {
    #[serde(default)]
    as_of: Option<String>,
}

#[derive(serde::Deserialize)]
struct WireItem {
    repo: String,
    path: String,
    #[serde(default)]
    sha: String,
    #[serde(default = "main_branch")]
    branch: String,
    #[serde(default)]
    matches: Vec<String>,
    /// v1.1: absent = located (verified placement).
    #[serde(default = "located")]
    located: bool,
    /// v1.3: provider-known line number; absent = unknown.
    #[serde(default)]
    line: Option<u32>,
}

fn main_branch() -> String {
    "main".into()
}

fn located() -> bool {
    true
}

fn code_matches(items: &[WireItem]) -> Vec<CodeMatch> {
    items
        .iter()
        .map(|i| CodeMatch {
            repo: i.repo.clone(),
            path: i.path.clone(),
            sha: i.sha.clone(),
            branch: i.branch.clone(),
            matches: i.matches.clone(),
            located: i.located,
            line: i.line,
        })
        .collect()
}
#[cfg(test)]
mod tests {
    use rootle_provider::CommitDetail;

    /// The v1.1 `located` default: absent means located (verified
    /// placement); only an explicit false flags a stale hit.
    #[test]
    fn located_defaults_true_and_parses_false() {
        #[derive(serde::Deserialize)]
        struct Item {
            #[serde(default = "located")]
            located: bool,
        }
        fn located() -> bool {
            true
        }
        let absent: Item = serde_json::from_str("{}").unwrap();
        assert!(absent.located);
        let stale: Item = serde_json::from_str(r#"{"located":false}"#).unwrap();
        assert!(!stale.located);
    }

    #[test]
    fn commit_unknown_status_and_missing_counts_remain_honest() {
        let detail: CommitDetail = super::de(serde_json::json!({
            "sha": "id", "author": "author", "date": "2026-09-06", "message": "message",
            "files": [
                {"path": "one", "status": "future-status", "additions": 4294967295u64, "deletions": 0},
                {"path": "two", "status": "added", "additions": 4294967295u64}
            ]
        })).unwrap();
        assert_eq!(
            detail.files[0].status,
            rootle_provider::FileStatus::Modified
        );
        assert_eq!(detail.line_stats().additions, Some(8589934590));
        assert_eq!(detail.line_stats().deletions, None);
    }
}