linesmith-plugin 0.1.3

Internal rhai plugin host for linesmith. No SemVer guarantee for direct dependents — depend on the `linesmith` binary or accept breakage between minor versions.
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
//! Parses the optional `@data_deps = [...]` declaration from the first
//! contiguous block of `//` line comments at the top of a plugin
//! script. See `docs/specs/plugin-api.md` §@data_deps header syntax for
//! the full contract.
//!
//! Resolved dep list is always a superset of `["status"]` — every
//! plugin implicitly has access to the stdin payload — even if the
//! author lists other deps explicitly or declares no header at all.
//!
//! Names are returned as raw lowercase tokens (`Vec<String>`); the
//! consumer maps them to its own dep enum at registration time. Names
//! reserved from plugins per spec (`credentials`, `jsonl`) and any
//! token outside the plugin-accessible set surface as
//! [`HeaderError::UnknownDep`] so the consumer doesn't have to repeat
//! the validation.

/// Plugin-accessible dep names per `docs/specs/plugin-api.md`. The
/// header validator rejects any token outside this list; the
/// consumer maps these strings back to its own enum at registration
/// time. Exposed `pub` so consumer-side drift-detection tests can
/// iterate the same catalog rather than hard-coding a parallel list
/// (a third copy that could itself fall out of sync).
pub const KNOWN_DEPS: &[&str] = &[
    "status",
    "settings",
    "claude_json",
    "usage",
    "sessions",
    "git",
];

/// Error surface for header parsing. The registry layer wraps these
/// into [`PluginError`](super::error::PluginError) variants with
/// the plugin id attached.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HeaderError {
    /// The `@data_deps = ...` RHS didn't parse as a JSON-style array
    /// of bare-string dep names.
    Malformed(String),
    /// A listed dep name is not in the plugin-accessible set
    /// defined by [`KNOWN_DEPS`]. `credentials` and `jsonl` are
    /// reserved per spec and surface here alongside truly unknown
    /// names.
    UnknownDep(String),
}

/// Parse a plugin script's `@data_deps` header. Returns the resolved
/// dep list as raw lowercase token strings (always including
/// `"status"`), or [`HeaderError`] on malformed syntax / unknown /
/// reserved dep name.
///
/// Accepts:
/// - No header at all (defaults to `["status"]`)
/// - Empty array (`@data_deps = []`) — same as no header
/// - Single-line (`@data_deps = ["status", "usage"]`)
/// - Multi-line across multiple `//` comment lines
/// - Trailing commas
/// - Single or double quotes around each name
pub fn parse_data_deps_header(src: &str) -> Result<Vec<String>, HeaderError> {
    let header_block = collect_header_block(src);
    let Some(rhs) = find_data_deps_rhs(&header_block)? else {
        return Ok(vec!["status".to_string()]);
    };
    let tokens = split_array_body(rhs)?;
    let mut deps = vec!["status".to_string()];
    for token in tokens {
        if !KNOWN_DEPS.contains(&token.as_str()) {
            return Err(HeaderError::UnknownDep(token));
        }
        if !deps.iter().any(|d| d == &token) {
            deps.push(token);
        }
    }
    Ok(deps)
}

/// Concatenate the first contiguous block of `//` comment lines,
/// stripping the `//` prefix and optional single following space from
/// each. A blank line or any non-`//` line ends the block (per spec).
fn collect_header_block(src: &str) -> String {
    let mut buf = String::new();
    for line in src.lines() {
        let trimmed = line.trim_start();
        if trimmed.is_empty() {
            break;
        }
        let Some(rest) = trimmed.strip_prefix("//") else {
            break;
        };
        // Drop a single leading space after `//` for ergonomic
        // multi-line indentation; anything else is kept verbatim.
        let rest = rest.strip_prefix(' ').unwrap_or(rest);
        buf.push_str(rest);
        buf.push('\n');
    }
    buf
}

/// Locate `@data_deps = [ ... ]` in the header block and return the
/// text starting right after the opening `[`. `Ok(None)` when no
/// `@data_deps` declaration exists at all (a valid "no header" state
/// resolved to the default `["status"]` by the caller). If the key is
/// present but the `= [` shape is missing (e.g. `@data_deps ["x"]`
/// or `@data_deps = "x"`), returns [`HeaderError::Malformed`] rather
/// than silently degrading to the default — writing `@data_deps`
/// signals intent, so a malformed RHS should surface as an error.
/// Missing closing `]` is detected downstream by [`split_array_body`].
fn find_data_deps_rhs(header: &str) -> Result<Option<&str>, HeaderError> {
    let Some(start) = header.find("@data_deps") else {
        return Ok(None);
    };
    let after_key = &header[start + "@data_deps".len()..];
    let Some(eq_pos) = after_key.find('=') else {
        return Err(HeaderError::Malformed(
            "@data_deps declaration missing `=`".to_string(),
        ));
    };
    let after_eq = after_key[eq_pos + 1..].trim_start();
    let Some(open) = after_eq.strip_prefix('[') else {
        return Err(HeaderError::Malformed(
            "@data_deps RHS must be an array literal starting with `[`".to_string(),
        ));
    };
    Ok(Some(open))
}

/// Split the body between `[` and `]` into trimmed, unquoted tokens.
/// Whitespace, newlines, trailing commas, and inline `//` comments
/// (per spec §@data_deps header syntax "comments inside the array")
/// are tolerated. Missing closing `]` or unbalanced quoting surfaces
/// as [`HeaderError::Malformed`].
fn split_array_body(body: &str) -> Result<Vec<String>, HeaderError> {
    let Some(end) = body.find(']') else {
        return Err(HeaderError::Malformed(
            "missing closing `]` in @data_deps array".to_string(),
        ));
    };
    let inside = &body[..end];
    // Strip `//` inline comments line-by-line before comma-splitting.
    // `//` extends to end-of-line, not end-of-fragment; a fragment
    // can span multiple lines (a dep on one line, a justification
    // comment on the next), so we can't just find the first `//`.
    let stripped: String = inside
        .lines()
        .map(|line| match line.find("//") {
            Some(i) => &line[..i],
            None => line,
        })
        .collect::<Vec<_>>()
        .join(" ");
    let mut tokens = Vec::new();
    for raw in stripped.split(',') {
        let s = raw.trim();
        if s.is_empty() {
            continue;
        }
        let unquoted = unquote(s)?;
        tokens.push(unquoted);
    }
    Ok(tokens)
}

fn unquote(s: &str) -> Result<String, HeaderError> {
    let bytes = s.as_bytes();
    if bytes.len() >= 2
        && ((bytes[0] == b'"' && bytes[bytes.len() - 1] == b'"')
            || (bytes[0] == b'\'' && bytes[bytes.len() - 1] == b'\''))
    {
        Ok(s[1..s.len() - 1].to_string())
    } else {
        Err(HeaderError::Malformed(format!(
            "expected quoted string, got `{s}`"
        )))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn deps(names: &[&str]) -> Vec<String> {
        names.iter().map(|s| (*s).to_string()).collect()
    }

    #[test]
    fn no_header_defaults_to_status_only() {
        let src = "fn render(ctx) { () }";
        assert_eq!(parse_data_deps_header(src), Ok(deps(&["status"])));
    }

    #[test]
    fn empty_array_defaults_to_status_only() {
        let src = "// @data_deps = []\nfn render(ctx) {}";
        assert_eq!(parse_data_deps_header(src), Ok(deps(&["status"])));
    }

    #[test]
    fn single_line_single_entry_unions_with_status() {
        let src = r#"// @data_deps = ["usage"]
fn render(ctx) {}"#;
        assert_eq!(parse_data_deps_header(src), Ok(deps(&["status", "usage"])));
    }

    #[test]
    fn single_line_multi_entry() {
        let src = r#"// @data_deps = ["settings", "usage", "git"]
fn render(ctx) {}"#;
        assert_eq!(
            parse_data_deps_header(src),
            Ok(deps(&["status", "settings", "usage", "git"]))
        );
    }

    #[test]
    fn explicit_status_is_accepted_without_duplication() {
        let src = r#"// @data_deps = ["status", "usage"]
fn render(ctx) {}"#;
        let resolved = parse_data_deps_header(src).unwrap();
        assert_eq!(resolved, deps(&["status", "usage"]));
        assert_eq!(
            resolved.iter().filter(|d| *d == "status").count(),
            1,
            "status must not be duplicated when listed explicitly"
        );
    }

    #[test]
    fn multi_line_array_accepted() {
        let src = r#"// @data_deps = [
//   "settings",
//   "usage",
//   "git",
// ]
fn render(ctx) {}"#;
        assert_eq!(
            parse_data_deps_header(src),
            Ok(deps(&["status", "settings", "usage", "git"]))
        );
    }

    #[test]
    fn trailing_comma_in_single_line_ok() {
        let src = r#"// @data_deps = ["usage",]
fn render(ctx) {}"#;
        assert_eq!(parse_data_deps_header(src), Ok(deps(&["status", "usage"])));
    }

    #[test]
    fn single_quotes_accepted() {
        let src = "// @data_deps = ['usage']\nfn render(ctx) {}";
        assert_eq!(parse_data_deps_header(src), Ok(deps(&["status", "usage"])));
    }

    #[test]
    fn unknown_dep_name_rejected() {
        let src = r#"// @data_deps = ["usage", "mystery"]
fn render(ctx) {}"#;
        assert_eq!(
            parse_data_deps_header(src),
            Err(HeaderError::UnknownDep("mystery".to_string()))
        );
    }

    #[test]
    fn reserved_credentials_dep_rejected_as_unknown() {
        // `credentials` is plugin-reserved per spec §@data_deps
        // header syntax. Header parser must reject it with UnknownDep,
        // matching the error surface for truly unknown names.
        let src = r#"// @data_deps = ["credentials"]
fn render(ctx) {}"#;
        assert_eq!(
            parse_data_deps_header(src),
            Err(HeaderError::UnknownDep("credentials".to_string()))
        );
    }

    #[test]
    fn reserved_jsonl_dep_rejected_as_unknown() {
        let src = r#"// @data_deps = ["jsonl"]
fn render(ctx) {}"#;
        assert_eq!(
            parse_data_deps_header(src),
            Err(HeaderError::UnknownDep("jsonl".to_string()))
        );
    }

    #[test]
    fn blank_line_ends_header_block() {
        // The header is the first block of `//` lines. A blank line
        // after it means `@data_deps` below is in a different block
        // and must not be parsed.
        let src = r#"// top comment

// @data_deps = ["usage"]
fn render(ctx) {}"#;
        // The `@data_deps` line is in a second block, so the first
        // block's resolution defaults to [status] only.
        assert_eq!(parse_data_deps_header(src), Ok(deps(&["status"])));
    }

    #[test]
    fn non_comment_line_ends_header_block() {
        // Anything that doesn't start with `//` (after trimming
        // whitespace) ends the block — including rhai statements.
        let src = r#"// top comment
fn render(ctx) {}
// @data_deps = ["usage"]"#;
        assert_eq!(parse_data_deps_header(src), Ok(deps(&["status"])));
    }

    #[test]
    fn header_appearing_after_other_comments_still_parses() {
        // Multi-line `//` comments before `@data_deps` are part of
        // the same header block; the parser finds the declaration
        // regardless of its position within the block.
        let src = r#"// Some plugin description
// Authored by me
// @data_deps = ["usage"]
fn render(ctx) {}"#;
        assert_eq!(parse_data_deps_header(src), Ok(deps(&["status", "usage"])));
    }

    #[test]
    fn malformed_missing_equals_rejected() {
        // Spec intent: writing `@data_deps` declares a header, so
        // malformed RHS must surface as an error — not silently
        // downgrade to the default `[status]`.
        let src = r#"// @data_deps ["usage"]
fn render(ctx) {}"#;
        assert!(matches!(
            parse_data_deps_header(src),
            Err(HeaderError::Malformed(_))
        ));
    }

    #[test]
    fn malformed_scalar_rhs_rejected() {
        let src = r#"// @data_deps = "usage"
fn render(ctx) {}"#;
        assert!(matches!(
            parse_data_deps_header(src),
            Err(HeaderError::Malformed(_))
        ));
    }

    #[test]
    fn malformed_missing_closing_bracket() {
        let src = r#"// @data_deps = ["usage"
fn render(ctx) {}"#;
        assert!(matches!(
            parse_data_deps_header(src),
            Err(HeaderError::Malformed(_))
        ));
    }

    #[test]
    fn malformed_unquoted_token() {
        let src = r#"// @data_deps = [usage]
fn render(ctx) {}"#;
        assert!(matches!(
            parse_data_deps_header(src),
            Err(HeaderError::Malformed(_))
        ));
    }

    #[test]
    fn block_comment_syntax_is_not_scanned() {
        // Per spec: `/* @data_deps = [...] */` is NOT parsed.
        let src = r#"/* @data_deps = ["usage"] */
fn render(ctx) {}"#;
        assert_eq!(parse_data_deps_header(src), Ok(deps(&["status"])));
    }

    #[test]
    fn inline_comment_on_array_line_accepted() {
        // Spec §@data_deps header syntax: "Trailing commas, comments
        // inside the array, and multi-line forms are all accepted."
        let src = r#"// @data_deps = [
//   "usage",       // why we need it
//   "git",         // trailing comment too
// ]
fn render(ctx) {}"#;
        assert_eq!(
            parse_data_deps_header(src),
            Ok(deps(&["status", "usage", "git"]))
        );
    }

    #[test]
    fn inline_comment_after_last_entry_accepted() {
        // Spec only requires line-comment support inside the array;
        // block comments are not scanned. Exercise the single-line
        // `//` case after a quoted entry.
        let src = r#"// @data_deps = [
//   "usage", // ok
//   "git"
// ]
fn render(ctx) {}"#;
        assert_eq!(
            parse_data_deps_header(src),
            Ok(deps(&["status", "usage", "git"]))
        );
    }

    #[test]
    fn whitespace_before_double_slash_is_tolerated() {
        let src = r#"    // @data_deps = ["usage"]
fn render(ctx) {}"#;
        assert_eq!(parse_data_deps_header(src), Ok(deps(&["status", "usage"])));
    }
}