agentis-ctx 0.3.4

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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
//! 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,
    Codex,
}

/// 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
}

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

pub fn plan_codex_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 = vec![generated(
        ".codex/hooks.json",
        templates::CODEX_HOOKS_JSON,
        &vars,
    )];
    plan.extend(codex_hook_files(".codex/hooks/ctx", &vars));
    plan.push(generated(RULES_PATH, templates::RULES_TOML, &vars));
    plan
}

pub fn plan_codex_plugin(root: &Path) -> Vec<GeneratedFile> {
    let branch = templates::default_branch(root);
    let author = templates::author_name();
    let vars = templates::standard_vars(&branch, &author);
    let manifest = if cfg!(feature = "mcp") {
        templates::CODEX_PLUGIN_MCP_JSON
    } else {
        templates::CODEX_PLUGIN_JSON
    };
    let mut plan = vec![
        generated(".codex-plugin/plugin.json", manifest, &vars),
        generated(
            ".agents/plugins/marketplace.json",
            templates::CODEX_MARKETPLACE_JSON,
            &vars,
        ),
        generated(
            "hooks/hooks.json",
            templates::CODEX_PLUGIN_HOOKS_JSON,
            &vars,
        ),
    ];
    plan.extend(codex_hook_files("hooks", &vars));
    plan.push(generated("skills/ctx/SKILL.md", templates::SKILL_MD, &vars));
    plan.push(generated(
        "README.md",
        templates::CODEX_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
}

pub fn render_agents_md_block(root: &Path) -> String {
    let branch = templates::default_branch(root);
    templates::render(
        templates::AGENTS_MD_BLOCK_MD,
        &[("DEFAULT_BRANCH", branch.as_str())],
    )
}

/// 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())],
    )
}

// ============================================================================
// Settings wiring (.claude/settings.json)
// ============================================================================

/// Outcome of merging the ctx snippet into `.claude/settings.json`.
#[derive(Debug, PartialEq)]
pub enum SettingsWireAction {
    /// No settings file existed; wrote a fresh one from the snippet.
    Created,
    /// Merged ctx's entries into an existing settings file.
    Merged,
    /// Settings already referenced ctx's hooks; nothing to add.
    AlreadyWired,
    /// Settings existed but were not valid JSON (object); left untouched.
    SkippedInvalid,
}

/// Idempotency marker: a hook group already wired for ctx references this
/// substring in its command. Mirrors the doctor's `check_settings_wiring`.
const CTX_HOOKS_MARKER: &str = ".claude/hooks/ctx/";

/// Merge the ctx hooks + permissions snippet into `.claude/settings.json`.
///
/// Additive, idempotent, and never clobbers unrelated user settings:
/// - a missing file is created from the snippet;
/// - an existing JSON object has ctx's permission entries unioned (dedup by
///   value) and ctx's hook groups appended only when no group in that event
///   already references [`CTX_HOOKS_MARKER`];
/// - a file that is not valid JSON (or not an object) is left byte-for-byte
///   untouched.
pub fn wire_local_settings(root: &Path) -> Result<SettingsWireAction> {
    let snippet = render_settings_snippet();
    let snippet_value: serde_json::Value = serde_json::from_str(&snippet)
        .map_err(|e| CtxError::Other(format!("settings snippet is not valid JSON: {e}")))?;
    let path = root.join(".claude/settings.json");

    let Ok(existing_raw) = fs::read_to_string(&path) else {
        // Missing (or unreadable): write the snippet fresh.
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        let body = serde_json::to_string_pretty(&snippet_value)
            .map_err(|e| CtxError::Other(format!("failed to serialize settings: {e}")))?;
        fs::write(&path, format!("{body}\n"))?;
        return Ok(SettingsWireAction::Created);
    };

    let Ok(serde_json::Value::Object(existing)) =
        serde_json::from_str::<serde_json::Value>(&existing_raw)
    else {
        // Present but not a JSON object: leave it exactly as-is.
        return Ok(SettingsWireAction::SkippedInvalid);
    };

    let mut merged = existing.clone();
    merge_settings(&mut merged, &snippet_value);

    if serde_json::Value::Object(merged.clone()) == serde_json::Value::Object(existing) {
        return Ok(SettingsWireAction::AlreadyWired);
    }

    let body = serde_json::to_string_pretty(&serde_json::Value::Object(merged))
        .map_err(|e| CtxError::Other(format!("failed to serialize settings: {e}")))?;
    fs::write(&path, format!("{body}\n"))?;
    Ok(SettingsWireAction::Merged)
}

/// Deep-merge ctx's snippet into an existing settings object, in place.
fn merge_settings(
    target: &mut serde_json::Map<String, serde_json::Value>,
    snippet: &serde_json::Value,
) {
    let Some(snippet_obj) = snippet.as_object() else {
        return;
    };

    // permissions.allow / permissions.deny: union with dedup by value.
    if let Some(perms) = snippet_obj.get("permissions").and_then(|v| v.as_object()) {
        let target_perms = target
            .entry("permissions")
            .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
        if let serde_json::Value::Object(ref mut target_perms) = target_perms {
            for key in ["allow", "deny"] {
                if let Some(add) = perms.get(key).and_then(|v| v.as_array()) {
                    union_array(target_perms, key, add);
                }
            }
        }
    }

    // hooks.<Event>: append ctx's group unless one already references the marker.
    if let Some(hooks) = snippet_obj.get("hooks").and_then(|v| v.as_object()) {
        let target_hooks = target
            .entry("hooks")
            .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
        if let serde_json::Value::Object(ref mut target_hooks) = target_hooks {
            for (event, groups) in hooks {
                if let Some(groups) = groups.as_array() {
                    append_hook_groups_if_absent(target_hooks, event, groups);
                }
            }
        }
    }
}

/// Append `additions` to `map[key]` (an array), keeping existing entries in
/// order and skipping any addition already present by value.
fn union_array(
    map: &mut serde_json::Map<String, serde_json::Value>,
    key: &str,
    additions: &[serde_json::Value],
) {
    let entry = map
        .entry(key)
        .or_insert_with(|| serde_json::Value::Array(Vec::new()));
    if let serde_json::Value::Array(ref mut arr) = entry {
        for add in additions {
            if !arr.contains(add) {
                arr.push(add.clone());
            }
        }
    }
}

/// Append ctx's hook groups for `event` unless a group in that event's array
/// already references [`CTX_HOOKS_MARKER`] (serialize-and-substring check,
/// the same idempotency marker the doctor uses).
fn append_hook_groups_if_absent(
    hooks: &mut serde_json::Map<String, serde_json::Value>,
    event: &str,
    additions: &[serde_json::Value],
) {
    let entry = hooks
        .entry(event)
        .or_insert_with(|| serde_json::Value::Array(Vec::new()));
    if let serde_json::Value::Array(ref mut arr) = entry {
        let already_wired = serde_json::Value::Array(arr.clone())
            .to_string()
            .contains(CTX_HOOKS_MARKER);
        if !already_wired {
            arr.extend(additions.iter().cloned());
        }
    }
}

// ============================================================================
// 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_codex_plans_render_valid_files() {
        let temp = TempDir::new().unwrap();
        for plan in [
            plan_codex_local(temp.path()),
            plan_codex_plugin(temp.path()),
        ] {
            for file in plan {
                assert!(
                    !file.content.contains("{{"),
                    "unrendered token in {}",
                    file.rel_path
                );
                if file.rel_path.ends_with(".json") {
                    serde_json::from_str::<serde_json::Value>(&file.content)
                        .unwrap_or_else(|e| panic!("{}: {e}", file.rel_path));
                }
            }
        }
        assert!(render_agents_md_block(temp.path()).contains("ctx map"));
    }

    #[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_wire_creates_settings_when_missing() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();
        let action = wire_local_settings(root).unwrap();
        assert_eq!(action, SettingsWireAction::Created);
        let content = fs::read_to_string(root.join(".claude/settings.json")).unwrap();
        assert!(content.contains(".claude/hooks/ctx/"), "content: {content}");
        serde_json::from_str::<serde_json::Value>(&content).unwrap();
    }

    #[test]
    fn test_wire_merges_additively_preserving_user_settings() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();
        fs::create_dir_all(root.join(".claude")).unwrap();
        // Unrelated top-level key + a user-defined hook under a different path.
        fs::write(
            root.join(".claude/settings.json"),
            r#"{
  "foo": "bar",
  "permissions": { "allow": ["Bash(git *)"] },
  "hooks": {
    "SessionStart": [
      { "hooks": [{ "type": "command", "command": "/my/own/hook.sh" }] }
    ]
  }
}"#,
        )
        .unwrap();

        let action = wire_local_settings(root).unwrap();
        assert_eq!(action, SettingsWireAction::Merged);

        let content = fs::read_to_string(root.join(".claude/settings.json")).unwrap();
        let value: serde_json::Value = serde_json::from_str(&content).unwrap();
        // Unrelated key preserved.
        assert_eq!(value["foo"], "bar");
        // Existing permission preserved, ctx permission added.
        let allow = value["permissions"]["allow"].as_array().unwrap();
        assert!(allow.contains(&serde_json::json!("Bash(git *)")));
        assert!(allow.contains(&serde_json::json!("Bash(ctx *)")));
        // User hook preserved, ctx hook appended in the same event.
        let session = value["hooks"]["SessionStart"].as_array().unwrap();
        assert_eq!(session.len(), 2, "user + ctx group: {session:?}");
        assert!(content.contains("/my/own/hook.sh"));
        assert!(content.contains(".claude/hooks/ctx/session-start.sh"));
    }

    #[test]
    fn test_wire_is_idempotent() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();
        assert_eq!(
            wire_local_settings(root).unwrap(),
            SettingsWireAction::Created
        );
        let first = fs::read_to_string(root.join(".claude/settings.json")).unwrap();

        assert_eq!(
            wire_local_settings(root).unwrap(),
            SettingsWireAction::AlreadyWired
        );
        let second = fs::read_to_string(root.join(".claude/settings.json")).unwrap();
        assert_eq!(first, second, "bytes must be unchanged on re-wire");
    }

    #[test]
    fn test_wire_leaves_invalid_json_untouched() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();
        fs::create_dir_all(root.join(".claude")).unwrap();
        let path = root.join(".claude/settings.json");
        fs::write(&path, "{not json").unwrap();

        let action = wire_local_settings(root).unwrap();
        assert_eq!(action, SettingsWireAction::SkippedInvalid);
        assert_eq!(fs::read_to_string(&path).unwrap(), "{not json");
    }

    #[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());
    }
}