agentis-ctx 0.3.0

Fast CLI tool that generates AI-ready context from your codebase, with built-in code intelligence
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! Harness packaging for `ctx harness` (Claude Code integration).
//!
//! This module scaffolds hook scripts, settings, skills, and plugin
//! manifests from templates embedded in the binary ([`templates`]), stamps
//! every generated file with a version header and checksum ([`checksum`]),
//! guards generated hooks against version skew ([`compat`]), and diagnoses
//! the whole integration ([`doctor`]).
//!
//! # Ownership model
//!
//! `init` records a checksum for every file it writes -- in the file itself
//! (comment header) where the format allows comments, and always in the
//! `.ctx/harness.lock` manifest. On re-run, each planned file is classified:
//!
//! - **Missing**: written.
//! - **Owned, unmodified** (checksum matches): regenerated in place.
//! - **Owned, modified** (checksum mismatch): warned about and skipped;
//!   `--force` overwrites.
//! - **Foreign** (exists but no ctx checksum anywhere): warned about and
//!   skipped; `--force` overwrites.
//!
//! Exception: `.ctx/rules.toml` encodes *user* policy and is never
//! overwritten once it exists, not even with `--force`.

pub mod checksum;
pub mod compat;
pub mod doctor;
pub mod templates;

use std::collections::BTreeMap;
use std::fs;
use std::path::Path;

use serde::{Deserialize, Serialize};

use crate::error::{CtxError, Result};
use checksum::{content_checksum, finalize, recorded_checksum, style_for_path};

/// Relative path of the harness manifest.
pub const LOCK_PATH: &str = ".ctx/harness.lock";

/// Relative path of the starter rules file.
pub const RULES_PATH: &str = ".ctx/rules.toml";

/// Directory holding the local-mode hook scripts.
pub const LOCAL_HOOKS_DIR: &str = ".claude/hooks/ctx";

/// The three hook script basenames (shared by local and plugin modes).
pub const HOOK_NAMES: [&str; 3] = ["session-start", "post-tool-use", "stop"];

/// Harness targets (mirrors the CLI enum; only Claude Code for now).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Target {
    Claude,
}

/// Scaffolding mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    Local,
    Plugin,
}

/// One file `init` plans to write: final content (header + checksum already
/// applied) plus write metadata.
#[derive(Debug, Clone)]
pub struct GeneratedFile {
    /// Path relative to the project root, `/`-separated.
    pub rel_path: String,
    /// Final on-disk content.
    pub content: String,
    /// chmod 0o755 on unix.
    pub executable: bool,
    /// Never overwrite once the file exists (user policy files).
    pub never_overwrite: bool,
}

/// What `write_plan` did with one planned file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileAction {
    /// File did not exist and was written.
    Created,
    /// File was owned by ctx and unmodified; regenerated in place.
    Regenerated,
    /// File was modified or foreign, but `--force` overwrote it.
    Overwritten,
    /// File carried a ctx checksum that no longer matches (user-modified);
    /// skipped.
    SkippedModified,
    /// File exists but was not generated by ctx; skipped.
    SkippedForeign,
    /// File is never overwritten by policy (`.ctx/rules.toml`); skipped.
    SkippedPolicy,
}

impl FileAction {
    /// Stable identifier used in JSON output.
    pub fn as_str(self) -> &'static str {
        match self {
            FileAction::Created => "created",
            FileAction::Regenerated => "regenerated",
            FileAction::Overwritten => "overwritten",
            FileAction::SkippedModified => "skipped_modified",
            FileAction::SkippedForeign => "skipped_foreign",
            FileAction::SkippedPolicy => "skipped_policy",
        }
    }

    /// True when the file was written to disk.
    pub fn wrote(self) -> bool {
        matches!(
            self,
            FileAction::Created | FileAction::Regenerated | FileAction::Overwritten
        )
    }
}

// ============================================================================
// Manifest (.ctx/harness.lock)
// ============================================================================

/// One manifest entry: the checksum and generator version of a file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LockEntry {
    /// `sha256:<hex>` over the file content minus its `ctx:checksum` lines.
    pub checksum: String,
    /// ctx version that generated the file.
    pub ctx_version: String,
}

/// The `.ctx/harness.lock` manifest: rel_path -> entry.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct LockFile {
    #[serde(default = "default_lock_version")]
    pub version: u32,
    #[serde(default)]
    pub files: BTreeMap<String, LockEntry>,
}

fn default_lock_version() -> u32 {
    1
}

/// Read and parse the manifest; `None` when missing or unparseable
/// (a broken manifest falls back to in-file checksum verification).
pub fn read_lock(root: &Path) -> Option<LockFile> {
    let content = fs::read_to_string(root.join(LOCK_PATH)).ok()?;
    toml::from_str(&content).ok()
}

fn write_lock(root: &Path, lock: &LockFile) -> Result<()> {
    let body = toml::to_string_pretty(lock)
        .map_err(|e| CtxError::Other(format!("failed to serialize {LOCK_PATH}: {e}")))?;
    let content = finalize(&body, checksum::HeaderStyle::Toml, templates::CTX_VERSION);
    let path = root.join(LOCK_PATH);
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(path, content)?;
    Ok(())
}

// ============================================================================
// Planning
// ============================================================================

fn generated(rel_path: &str, template: &str, vars: &[(&str, &str)]) -> GeneratedFile {
    let rendered = templates::render(template, vars);
    let content = finalize(&rendered, style_for_path(rel_path), templates::CTX_VERSION);
    GeneratedFile {
        rel_path: rel_path.to_string(),
        content,
        executable: rel_path.ends_with(".sh"),
        never_overwrite: rel_path == RULES_PATH,
    }
}

fn hook_files(dir: &str, vars: &[(&str, &str)]) -> Vec<GeneratedFile> {
    vec![
        generated(
            &format!("{dir}/session-start.sh"),
            templates::SESSION_START_SH,
            vars,
        ),
        generated(
            &format!("{dir}/post-tool-use.sh"),
            templates::POST_TOOL_USE_SH,
            vars,
        ),
        generated(&format!("{dir}/stop.sh"), templates::STOP_SH, vars),
    ]
}

/// Plan the files for `--mode local`: hook scripts under
/// `.claude/hooks/ctx/` plus a starter `.ctx/rules.toml`.
///
/// The settings snippet and CLAUDE.md block are *printed*, not written; see
/// [`render_settings_snippet`] and [`render_claude_md_block`].
pub fn plan_local(root: &Path) -> Vec<GeneratedFile> {
    let branch = templates::default_branch(root);
    let author = templates::author_name();
    let vars = templates::standard_vars(&branch, &author);

    let mut plan = hook_files(LOCAL_HOOKS_DIR, &vars);
    plan.push(generated(RULES_PATH, templates::RULES_TOML, &vars));
    plan
}

/// Plan the files for `--mode plugin`: a full Claude Code plugin scaffold.
///
/// `.mcp.json` is included only when this binary was compiled with the
/// `mcp` feature (release binaries are not); callers should explain how to
/// enable it otherwise.
pub fn plan_plugin(root: &Path) -> Vec<GeneratedFile> {
    let branch = templates::default_branch(root);
    let author = templates::author_name();
    let vars = templates::standard_vars(&branch, &author);

    let mut plan = vec![
        generated(".claude-plugin/plugin.json", templates::PLUGIN_JSON, &vars),
        generated(
            ".claude-plugin/marketplace.json",
            templates::MARKETPLACE_JSON,
            &vars,
        ),
        generated("hooks/hooks.json", templates::HOOKS_JSON, &vars),
    ];
    plan.extend(hook_files("hooks", &vars));
    plan.push(generated(
        "settings.json",
        templates::PLUGIN_SETTINGS_JSON,
        &vars,
    ));
    plan.push(generated("skills/ctx/SKILL.md", templates::SKILL_MD, &vars));
    plan.push(generated("README.md", templates::PLUGIN_README_MD, &vars));
    if cfg!(feature = "mcp") {
        plan.push(generated(".mcp.json", templates::MCP_JSON, &vars));
    }
    plan.push(generated(RULES_PATH, templates::RULES_TOML, &vars));
    plan
}

/// Render the settings snippet printed to stdout in local mode.
pub fn render_settings_snippet() -> String {
    templates::render(templates::SETTINGS_SNIPPET_JSON, &[])
}

/// Render the CLAUDE.md guidance block printed to stdout in local mode.
pub fn render_claude_md_block(root: &Path) -> String {
    let branch = templates::default_branch(root);
    templates::render(
        templates::CLAUDE_MD_BLOCK_MD,
        &[("DEFAULT_BRANCH", branch.as_str())],
    )
}

// ============================================================================
// Ownership + writing
// ============================================================================

/// How an existing (or missing) on-disk file relates to ctx's generation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Ownership {
    Missing,
    OwnedUnmodified,
    OwnedModified,
    Foreign,
}

/// Classify one on-disk file. Manifest entry wins; in-file `ctx:checksum`
/// is the fallback; anything else that exists is foreign.
fn classify(path: &Path, lock_entry: Option<&LockEntry>) -> Ownership {
    if !path.exists() {
        return Ownership::Missing;
    }
    let Ok(bytes) = fs::read(path) else {
        // Unreadable: treat as foreign so we never clobber it silently.
        return Ownership::Foreign;
    };
    let actual = content_checksum(&bytes);

    if let Some(entry) = lock_entry {
        let expected = entry
            .checksum
            .strip_prefix("sha256:")
            .unwrap_or(&entry.checksum);
        return if actual == expected {
            Ownership::OwnedUnmodified
        } else {
            Ownership::OwnedModified
        };
    }

    if let Ok(text) = std::str::from_utf8(&bytes) {
        if let Some(recorded) = recorded_checksum(text) {
            return if actual == recorded {
                Ownership::OwnedUnmodified
            } else {
                Ownership::OwnedModified
            };
        }
    }
    Ownership::Foreign
}

fn write_file(root: &Path, file: &GeneratedFile) -> Result<()> {
    let path = root.join(&file.rel_path);
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&path, &file.content)?;
    #[cfg(unix)]
    if file.executable {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(&path, fs::Permissions::from_mode(0o755))?;
    }
    Ok(())
}

/// Write a plan to disk, honoring the ownership model, and update
/// `.ctx/harness.lock`.
///
/// Returns one `(rel_path, action)` per planned file (plus the lock file
/// itself). This function does not print; callers surface warnings for
/// skipped files.
pub fn write_plan(
    root: &Path,
    plan: &[GeneratedFile],
    force: bool,
) -> Result<Vec<(String, FileAction)>> {
    let mut lock = read_lock(root).unwrap_or_default();
    lock.version = 1;
    let mut actions = Vec::with_capacity(plan.len() + 1);

    for file in plan {
        let path = root.join(&file.rel_path);
        let ownership = classify(&path, lock.files.get(&file.rel_path));

        let action = match ownership {
            Ownership::Missing => FileAction::Created,
            _ if file.never_overwrite => FileAction::SkippedPolicy,
            Ownership::OwnedUnmodified => FileAction::Regenerated,
            Ownership::OwnedModified if force => FileAction::Overwritten,
            Ownership::OwnedModified => FileAction::SkippedModified,
            Ownership::Foreign if force => FileAction::Overwritten,
            Ownership::Foreign => FileAction::SkippedForeign,
        };

        if action.wrote() {
            write_file(root, file)?;
            lock.files.insert(
                file.rel_path.clone(),
                LockEntry {
                    checksum: format!("sha256:{}", content_checksum(file.content.as_bytes())),
                    ctx_version: templates::CTX_VERSION.to_string(),
                },
            );
        }
        actions.push((file.rel_path.clone(), action));
    }

    let lock_existed = root.join(LOCK_PATH).exists();
    write_lock(root, &lock)?;
    actions.push((
        LOCK_PATH.to_string(),
        if lock_existed {
            FileAction::Regenerated
        } else {
            FileAction::Created
        },
    ));

    Ok(actions)
}

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

    fn plan_and_write(root: &Path, force: bool) -> Vec<(String, FileAction)> {
        let plan = plan_local(root);
        write_plan(root, &plan, force).unwrap()
    }

    fn action_for(actions: &[(String, FileAction)], rel: &str) -> FileAction {
        actions
            .iter()
            .find(|(p, _)| p == rel)
            .unwrap_or_else(|| panic!("no action for {rel}"))
            .1
    }

    #[test]
    fn test_no_residual_tokens_and_json_parses_in_both_modes() {
        let temp = TempDir::new().unwrap();
        for plan in [plan_local(temp.path()), plan_plugin(temp.path())] {
            for file in &plan {
                assert!(
                    !file.content.contains("{{"),
                    "unrendered token in {}: {}",
                    file.rel_path,
                    file.content
                );
                if file.rel_path.ends_with(".json") {
                    serde_json::from_str::<serde_json::Value>(&file.content)
                        .unwrap_or_else(|e| panic!("{} is not valid JSON: {e}", file.rel_path));
                }
            }
        }
        // The printed (not written) templates render clean too.
        assert!(!render_settings_snippet().contains("{{"));
        assert!(!render_claude_md_block(temp.path()).contains("{{"));
        serde_json::from_str::<serde_json::Value>(&render_settings_snippet()).unwrap();
    }

    #[test]
    fn test_plugin_manifest_fields_and_version() {
        let temp = TempDir::new().unwrap();
        let plan = plan_plugin(temp.path());
        let plugin = plan
            .iter()
            .find(|f| f.rel_path == ".claude-plugin/plugin.json")
            .unwrap();
        let value: serde_json::Value = serde_json::from_str(&plugin.content).unwrap();
        assert_eq!(value["name"], "ctx");
        assert_eq!(value["version"], env!("CARGO_PKG_VERSION"));
        assert!(value["description"].is_string());
        assert!(value["author"]["name"].is_string());

        // Permission block matches the spec (allow ctx, deny self-update and
        // policy-file edits).
        let settings = plan.iter().find(|f| f.rel_path == "settings.json").unwrap();
        let value: serde_json::Value = serde_json::from_str(&settings.content).unwrap();
        assert_eq!(
            value["permissions"]["allow"],
            serde_json::json!(["Bash(ctx *)"])
        );
        let deny = value["permissions"]["deny"].as_array().unwrap();
        assert!(deny.contains(&serde_json::json!("Bash(ctx self-update*)")));
        assert!(deny.contains(&serde_json::json!("Edit(.ctx/rules.toml)")));
        assert!(deny.contains(&serde_json::json!("Edit(.claude/hooks/ctx/**)")));
        assert!(deny.contains(&serde_json::json!("Edit(.claude/settings.json)")));
    }

    #[test]
    fn test_headers_carry_crate_version() {
        let temp = TempDir::new().unwrap();
        for file in plan_local(temp.path()) {
            assert!(
                file.content
                    .contains(&format!("generated by ctx v{}", env!("CARGO_PKG_VERSION"))),
                "no version header in {}",
                file.rel_path
            );
            assert!(
                checksum::recorded_checksum(&file.content).is_some(),
                "no checksum line in {}",
                file.rel_path
            );
        }
    }

    #[test]
    fn test_write_plan_ownership_lifecycle() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();

        // First run: everything created.
        let actions = plan_and_write(root, false);
        for (rel, action) in &actions {
            assert_eq!(*action, FileAction::Created, "{rel}");
        }

        // Second run: unmodified owned files regenerate; rules.toml is
        // policy-skipped.
        let actions = plan_and_write(root, false);
        assert_eq!(
            action_for(&actions, ".claude/hooks/ctx/stop.sh"),
            FileAction::Regenerated
        );
        assert_eq!(action_for(&actions, RULES_PATH), FileAction::SkippedPolicy);

        // Modify a hook: skipped without --force, content preserved.
        let stop = root.join(".claude/hooks/ctx/stop.sh");
        let modified = fs::read_to_string(&stop).unwrap() + "echo tampered\n";
        fs::write(&stop, &modified).unwrap();
        let actions = plan_and_write(root, false);
        assert_eq!(
            action_for(&actions, ".claude/hooks/ctx/stop.sh"),
            FileAction::SkippedModified
        );
        assert_eq!(fs::read_to_string(&stop).unwrap(), modified);

        // --force regenerates it; rules.toml still survives.
        fs::write(root.join(RULES_PATH), "version = 1\n# mine\n").unwrap();
        let actions = plan_and_write(root, true);
        assert_eq!(
            action_for(&actions, ".claude/hooks/ctx/stop.sh"),
            FileAction::Overwritten
        );
        assert!(!fs::read_to_string(&stop).unwrap().contains("tampered"));
        assert_eq!(action_for(&actions, RULES_PATH), FileAction::SkippedPolicy);
        assert_eq!(
            fs::read_to_string(root.join(RULES_PATH)).unwrap(),
            "version = 1\n# mine\n"
        );
    }

    #[test]
    fn test_foreign_file_is_skipped_without_force() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();
        let rel = ".claude/hooks/ctx/stop.sh";
        let path = root.join(rel);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(&path, "#!/bin/sh\necho my own hook\n").unwrap();

        let actions = plan_and_write(root, false);
        assert_eq!(action_for(&actions, rel), FileAction::SkippedForeign);
        assert!(fs::read_to_string(&path).unwrap().contains("my own hook"));

        let actions = plan_and_write(root, true);
        assert_eq!(action_for(&actions, rel), FileAction::Overwritten);
    }

    #[test]
    fn test_lock_tracks_json_files_in_plugin_mode() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();
        let plan = plan_plugin(root);
        write_plan(root, &plan, false).unwrap();

        let lock = read_lock(root).unwrap();
        // JSON files have no in-file header; the lock must know them.
        let entry = lock.files.get(".claude-plugin/plugin.json").unwrap();
        assert!(entry.checksum.starts_with("sha256:"));
        assert_eq!(entry.ctx_version, env!("CARGO_PKG_VERSION"));

        // Detect a JSON tamper via the lock (no in-file checksum exists).
        let manifest = root.join(".claude-plugin/plugin.json");
        fs::write(&manifest, "{\"name\": \"evil\"}\n").unwrap();
        let actions = write_plan(root, &plan, false).unwrap();
        assert_eq!(
            action_for(&actions, ".claude-plugin/plugin.json"),
            FileAction::SkippedModified
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_hook_scripts_are_executable() {
        use std::os::unix::fs::PermissionsExt;
        let temp = TempDir::new().unwrap();
        let root = temp.path();
        plan_and_write(root, false);
        let mode = fs::metadata(root.join(".claude/hooks/ctx/stop.sh"))
            .unwrap()
            .permissions()
            .mode();
        assert_eq!(mode & 0o111, 0o111, "mode: {:o}", mode);
    }

    #[test]
    fn test_starter_rules_toml_parses_and_constrains_nothing() {
        let temp = TempDir::new().unwrap();
        let plan = plan_local(temp.path());
        let rules = plan.iter().find(|f| f.rel_path == RULES_PATH).unwrap();
        let parsed: crate::rules::RulesFile = toml::from_str(&rules.content).unwrap();
        assert_eq!(parsed.version, 1);
        assert!(parsed.layers.is_empty());
        assert!(parsed.rules.forbidden.is_empty());
        assert!(parsed.rules.allowed_dependents.is_empty());
        assert!(parsed.rules.limit.is_empty());
        assert!(parsed.rules.no_new_dependents.is_empty());
    }
}