cxpak 0.10.0

Spends CPU cycles so you don't spend tokens. The LLM gets a briefing packet instead of a flashlight in a dark room.
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
use crate::parser::language::{
    Export, Import, LanguageSupport, ParseResult, Symbol, SymbolKind, Visibility,
};
use tree_sitter::Language as TsLanguage;

pub struct DockerfileLanguage;

impl DockerfileLanguage {
    fn node_text<'a>(node: &tree_sitter::Node, source: &'a [u8]) -> &'a str {
        node.utf8_text(source).unwrap_or("")
    }

    fn first_line(node: &tree_sitter::Node, source: &[u8]) -> String {
        let text = Self::node_text(node, source);
        text.lines().next().unwrap_or("").trim().to_string()
    }

    fn full_text(node: &tree_sitter::Node, source: &[u8]) -> String {
        Self::node_text(node, source).to_string()
    }

    /// Extract the image name from a FROM instruction.
    fn extract_from_image(node: &tree_sitter::Node, source: &[u8]) -> String {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            let kind = child.kind();
            if kind == "image_spec" {
                // image_spec may contain image_name, image_tag, image_digest
                let mut spec_cursor = child.walk();
                for spec_child in child.children(&mut spec_cursor) {
                    if spec_child.kind() == "image_name" {
                        return Self::node_text(&spec_child, source).trim().to_string();
                    }
                }
                // Fallback: use the full image_spec text
                return Self::node_text(&child, source).trim().to_string();
            }
            // Some grammars directly put the image name
            if kind == "image_name" {
                return Self::node_text(&child, source).trim().to_string();
            }
        }
        // Fallback: parse from text
        let text = Self::node_text(node, source);
        let after_from = text.split_whitespace().nth(1).unwrap_or("").to_string();
        // Strip the alias (AS name)
        after_from
            .split_whitespace()
            .next()
            .unwrap_or(&after_from)
            .to_string()
    }

    /// Extract the alias from a FROM instruction (e.g., `FROM node:18 AS builder` -> `builder`).
    fn extract_from_alias(node: &tree_sitter::Node, source: &[u8]) -> Option<String> {
        let mut cursor = node.walk();
        let mut found_as = false;
        for child in node.children(&mut cursor) {
            let kind = child.kind();
            if kind == "as_instruction" || kind == "image_alias" {
                return Some(Self::node_text(&child, source).trim().to_string());
            }
            let text = Self::node_text(&child, source);
            if text.eq_ignore_ascii_case("as") {
                found_as = true;
                continue;
            }
            if found_as {
                return Some(text.trim().to_string());
            }
        }
        None
    }

    /// Extract a descriptive name for an instruction (e.g., the command or key).
    fn extract_instruction_summary(node: &tree_sitter::Node, source: &[u8]) -> String {
        Self::first_line(node, source)
    }
}

impl LanguageSupport for DockerfileLanguage {
    fn ts_language(&self) -> TsLanguage {
        tree_sitter_dockerfile_updated::language()
    }

    fn name(&self) -> &str {
        "dockerfile"
    }

    fn extract(&self, source: &str, tree: &tree_sitter::Tree) -> ParseResult {
        let source_bytes = source.as_bytes();
        let root = tree.root_node();

        let mut symbols: Vec<Symbol> = Vec::new();
        let imports: Vec<Import> = Vec::new();
        let exports: Vec<Export> = Vec::new();

        let mut cursor = root.walk();

        for node in root.children(&mut cursor) {
            match node.kind() {
                "from_instruction" => {
                    let image = Self::extract_from_image(&node, source_bytes);
                    let alias = Self::extract_from_alias(&node, source_bytes);
                    let name = if let Some(ref a) = alias {
                        format!("{} (as {})", image, a)
                    } else {
                        image
                    };
                    let start_line = node.start_position().row + 1;
                    let end_line = node.end_position().row + 1;

                    symbols.push(Symbol {
                        name,
                        kind: SymbolKind::Section,
                        visibility: Visibility::Public,
                        signature: Self::first_line(&node, source_bytes),
                        body: Self::full_text(&node, source_bytes),
                        start_line,
                        end_line,
                    });
                }

                "run_instruction"
                | "copy_instruction"
                | "env_instruction"
                | "expose_instruction"
                | "cmd_instruction"
                | "entrypoint_instruction"
                | "workdir_instruction"
                | "arg_instruction"
                | "label_instruction"
                | "add_instruction"
                | "volume_instruction"
                | "user_instruction"
                | "healthcheck_instruction"
                | "shell_instruction"
                | "stopsignal_instruction"
                | "onbuild_instruction"
                | "maintainer_instruction" => {
                    let summary = Self::extract_instruction_summary(&node, source_bytes);
                    let start_line = node.start_position().row + 1;
                    let end_line = node.end_position().row + 1;

                    symbols.push(Symbol {
                        name: summary.clone(),
                        kind: SymbolKind::Instruction,
                        visibility: Visibility::Public,
                        signature: summary,
                        body: Self::full_text(&node, source_bytes),
                        start_line,
                        end_line,
                    });
                }

                _ => {}
            }
        }

        ParseResult {
            symbols,
            imports,
            exports,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::language::{SymbolKind, Visibility};

    fn make_parser() -> tree_sitter::Parser {
        let mut parser = tree_sitter::Parser::new();
        parser
            .set_language(&tree_sitter_dockerfile_updated::language())
            .expect("failed to set language");
        parser
    }

    #[test]
    fn test_extract_from_instruction() {
        let source = r#"FROM node:18-alpine
RUN npm install
"#;
        let mut parser = make_parser();
        let tree = parser.parse(source, None).expect("parse failed");
        let lang = DockerfileLanguage;
        let result = lang.extract(source, &tree);

        let sections: Vec<_> = result
            .symbols
            .iter()
            .filter(|s| s.kind == SymbolKind::Section)
            .collect();
        assert!(
            !sections.is_empty(),
            "expected FROM as Section, got: {:?}",
            result
                .symbols
                .iter()
                .map(|s| (&s.name, &s.kind))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_extract_instructions() {
        let source = r#"FROM ubuntu:22.04
RUN apt-get update
COPY . /app
WORKDIR /app
ENV NODE_ENV=production
EXPOSE 8080
CMD ["node", "server.js"]
"#;
        let mut parser = make_parser();
        let tree = parser.parse(source, None).expect("parse failed");
        let lang = DockerfileLanguage;
        let result = lang.extract(source, &tree);

        let instructions: Vec<_> = result
            .symbols
            .iter()
            .filter(|s| s.kind == SymbolKind::Instruction)
            .collect();
        assert!(
            instructions.len() >= 5,
            "expected at least 5 instructions, got: {:?}",
            instructions.iter().map(|i| &i.name).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_empty_source() {
        let source = "";
        let mut parser = make_parser();
        let tree = parser.parse(source, None).unwrap();
        let lang = DockerfileLanguage;
        let result = lang.extract(source, &tree);
        assert!(result.symbols.is_empty());
        assert!(result.imports.is_empty());
        assert!(result.exports.is_empty());
    }

    #[test]
    fn test_complex_dockerfile() {
        let source = r#"FROM node:18 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:18-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
EXPOSE 3000
ENV NODE_ENV=production
CMD ["node", "dist/server.js"]
"#;
        let mut parser = make_parser();
        let tree = parser.parse(source, None).expect("parse failed");
        let lang = DockerfileLanguage;
        let result = lang.extract(source, &tree);

        let sections: Vec<_> = result
            .symbols
            .iter()
            .filter(|s| s.kind == SymbolKind::Section)
            .collect();
        assert!(
            sections.len() >= 2,
            "expected at least 2 FROM sections, got: {:?}",
            sections.iter().map(|s| &s.name).collect::<Vec<_>>()
        );

        let instructions: Vec<_> = result
            .symbols
            .iter()
            .filter(|s| s.kind == SymbolKind::Instruction)
            .collect();
        assert!(
            instructions.len() >= 8,
            "expected at least 8 instructions, got: {:?}",
            instructions.iter().map(|i| &i.name).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_symbol_kinds() {
        let source = "FROM alpine:latest\nRUN echo hello\n";
        let mut parser = make_parser();
        let tree = parser.parse(source, None).expect("parse failed");
        let lang = DockerfileLanguage;
        let result = lang.extract(source, &tree);

        let has_section = result.symbols.iter().any(|s| s.kind == SymbolKind::Section);
        let has_instruction = result
            .symbols
            .iter()
            .any(|s| s.kind == SymbolKind::Instruction);
        assert!(has_section, "expected Section symbol kind for FROM");
        assert!(has_instruction, "expected Instruction symbol kind");

        assert!(
            result
                .symbols
                .iter()
                .all(|s| s.visibility == Visibility::Public),
            "all Dockerfile symbols should be public"
        );
    }

    #[test]
    fn test_no_imports_exports() {
        let source = "FROM alpine\nRUN echo test\n";
        let mut parser = make_parser();
        let tree = parser.parse(source, None).expect("parse failed");
        let lang = DockerfileLanguage;
        let result = lang.extract(source, &tree);
        assert!(
            result.imports.is_empty(),
            "dockerfile should have no imports"
        );
        assert!(
            result.exports.is_empty(),
            "dockerfile should have no exports"
        );
    }

    #[test]
    fn test_from_without_alias() {
        // FROM without AS exercises the `None` path of extract_from_alias,
        // which is the `else` branch in the name construction.
        let source = "FROM scratch\n";
        let mut parser = make_parser();
        let tree = parser.parse(source, None).expect("parse failed");
        let lang = DockerfileLanguage;
        let result = lang.extract(source, &tree);

        let sections: Vec<_> = result
            .symbols
            .iter()
            .filter(|s| s.kind == SymbolKind::Section)
            .collect();
        assert!(!sections.is_empty(), "expected FROM section");
        // Name should be just the image, no "(as ...)" suffix
        assert!(
            !sections[0].name.contains("(as"),
            "expected no alias, got: {}",
            sections[0].name
        );
    }

    #[test]
    fn test_all_instruction_types() {
        // Exercise instruction kinds not hit by other tests: ADD, VOLUME, USER,
        // HEALTHCHECK, SHELL, STOPSIGNAL, ONBUILD, MAINTAINER.
        let source = r#"FROM alpine
ADD . /app
VOLUME /data
USER nobody
HEALTHCHECK CMD curl -f http://localhost/ || exit 1
SHELL ["/bin/bash", "-c"]
STOPSIGNAL SIGTERM
ONBUILD RUN echo "building"
MAINTAINER test@example.com
"#;
        let mut parser = make_parser();
        let tree = parser.parse(source, None).expect("parse failed");
        let lang = DockerfileLanguage;
        let result = lang.extract(source, &tree);

        let instructions: Vec<_> = result
            .symbols
            .iter()
            .filter(|s| s.kind == SymbolKind::Instruction)
            .collect();
        assert!(
            instructions.len() >= 6,
            "expected many instruction types, got: {:?}",
            instructions.iter().map(|i| &i.name).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_arg_instruction() {
        let source = r#"ARG BASE_IMAGE=node:18
FROM ${BASE_IMAGE}
ARG APP_VERSION=1.0
LABEL version=${APP_VERSION}
"#;
        let mut parser = make_parser();
        let tree = parser.parse(source, None).expect("parse failed");
        let lang = DockerfileLanguage;
        let result = lang.extract(source, &tree);

        assert!(
            !result.symbols.is_empty(),
            "expected symbols from ARG Dockerfile"
        );
    }
}