agent-config 0.3.0

Install hooks/integrations into AI coding harnesses (Claude Code, Cursor, Gemini CLI, OpenCode, Codex CLI, Cline, Windsurf, ...) without learning each one's filesystem layout.
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
//! Shared side-effect-free planning helpers.

use std::fs;
use std::path::{Path, PathBuf};

use serde_json::{Map, Value};

use crate::error::AgentConfigError;
use crate::plan::{PlannedChange, RefusalReason};
use crate::util::{fs_atomic, json_patch, md_block};

/// Plan an atomic file write without touching disk.
pub(crate) fn plan_write_file(
    changes: &mut Vec<PlannedChange>,
    path: &Path,
    content: &[u8],
    make_backup: bool,
) -> Result<(), AgentConfigError> {
    let Some(current) = fs_atomic::read_capped(path)? else {
        plan_parent_dirs(changes, path);
        changes.push(PlannedChange::CreateFile {
            path: path.to_path_buf(),
        });
        return Ok(());
    };
    if current == content {
        changes.push(PlannedChange::NoOp {
            path: path.to_path_buf(),
            reason: "already up to date".into(),
        });
        return Ok(());
    }
    if make_backup {
        let backup = fs_atomic::backup_path(path);
        if !backup.exists() {
            changes.push(PlannedChange::CreateBackup {
                backup,
                target: path.to_path_buf(),
            });
        }
    }
    changes.push(PlannedChange::PatchFile {
        path: path.to_path_buf(),
    });
    Ok(())
}

/// Plan removal of a file if it exists.
pub(crate) fn plan_remove_file(changes: &mut Vec<PlannedChange>, path: &Path) {
    if path.exists() {
        changes.push(PlannedChange::RemoveFile {
            path: path.to_path_buf(),
        });
    } else {
        changes.push(PlannedChange::NoOp {
            path: path.to_path_buf(),
            reason: "file is already absent".into(),
        });
    }
}

/// Plan restoring `<path>.bak` to `path` only when that backup already matches
/// the desired post-uninstall bytes, otherwise remove `path`.
pub(crate) fn plan_restore_backup_or_remove(
    changes: &mut Vec<PlannedChange>,
    path: &Path,
    desired_content: &[u8],
) -> Result<(), AgentConfigError> {
    let backup = fs_atomic::backup_path(path);
    // Defense in depth: a hostile process could swap a giant file in for our
    // `.bak`. ConfigTooLarge counts as "doesn't match", same as a stale or
    // missing backup, so we plan a RemoveFile rather than abort the uninstall.
    let backup_matches = match fs_atomic::read_capped(&backup) {
        Ok(Some(content)) => content == desired_content,
        Ok(None) => false,
        Err(AgentConfigError::ConfigTooLarge { .. }) => false,
        Err(e) => return Err(e),
    };
    if backup_matches {
        changes.push(PlannedChange::RestoreBackup {
            backup,
            target: path.to_path_buf(),
        });
        return Ok(());
    }
    changes.push(PlannedChange::RemoveFile {
        path: path.to_path_buf(),
    });
    Ok(())
}

/// Plan ownership ledger creation/update.
pub(crate) fn plan_write_ledger(
    changes: &mut Vec<PlannedChange>,
    path: &Path,
    key: &str,
    owner: &str,
) {
    plan_parent_dirs(changes, path);
    changes.push(PlannedChange::WriteLedger {
        path: path.to_path_buf(),
        key: key.to_string(),
        owner: owner.to_string(),
    });
}

/// Plan ownership ledger entry removal.
pub(crate) fn plan_remove_ledger_entry(changes: &mut Vec<PlannedChange>, path: &Path, key: &str) {
    changes.push(PlannedChange::RemoveLedgerEntry {
        path: path.to_path_buf(),
        key: key.to_string(),
    });
}

/// Plan chmod on Unix-like hosts.
pub(crate) fn plan_set_permissions(changes: &mut Vec<PlannedChange>, path: &Path, mode: u32) {
    #[cfg(unix)]
    {
        changes.push(PlannedChange::SetPermissions {
            path: path.to_path_buf(),
            mode,
        });
    }
    #[cfg(not(unix))]
    {
        let _ = (changes, path, mode);
    }
}

/// Plan upserting an agent-config fenced markdown block.
pub(crate) fn plan_markdown_upsert(
    changes: &mut Vec<PlannedChange>,
    path: &Path,
    tag: &str,
    body: &str,
) -> Result<(), AgentConfigError> {
    let host = fs_atomic::read_to_string_or_empty(path)?;
    let new_host = md_block::upsert(&host, tag, body);
    plan_write_file(changes, path, new_host.as_bytes(), true)
}

/// Plan removing an agent-config fenced markdown block.
pub(crate) fn plan_markdown_remove(
    changes: &mut Vec<PlannedChange>,
    path: &Path,
    tag: &str,
) -> Result<(), AgentConfigError> {
    let host = fs_atomic::read_to_string_or_empty(path)?;
    let (stripped, removed) = md_block::remove(&host, tag);
    if !removed {
        changes.push(PlannedChange::NoOp {
            path: path.to_path_buf(),
            reason: "tagged markdown block is already absent".into(),
        });
        return Ok(());
    }
    if stripped.trim().is_empty() {
        plan_restore_backup_or_remove(changes, path, stripped.as_bytes())?;
    } else {
        plan_write_file(changes, path, stripped.as_bytes(), false)?;
    }
    Ok(())
}

/// Plan upserting an instruction-fenced markdown block (uses
/// `AGENT-CONFIG-INSTR` prefix).
pub(crate) fn plan_markdown_upsert_instruction(
    changes: &mut Vec<PlannedChange>,
    path: &Path,
    name: &str,
    body: &str,
) -> Result<(), AgentConfigError> {
    let host = fs_atomic::read_to_string_or_empty(path)?;
    let new_host = md_block::upsert_instruction(&host, name, body);
    plan_write_file(changes, path, new_host.as_bytes(), true)
}

/// Plan removing an instruction-fenced markdown block. If the new-prefix
/// block is absent but a legacy `AGENT-CONFIG:<name>` block exists, plan its
/// removal instead so pre-rename installs drain on uninstall.
pub(crate) fn plan_markdown_remove_instruction(
    changes: &mut Vec<PlannedChange>,
    path: &Path,
    name: &str,
) -> Result<(), AgentConfigError> {
    let host = fs_atomic::read_to_string_or_empty(path)?;
    let (stripped, removed) = md_block::remove_instruction(&host, name);
    let (stripped, removed) = if removed {
        (stripped, true)
    } else {
        md_block::remove_legacy_instruction(&host, name)
    };
    if !removed {
        changes.push(PlannedChange::NoOp {
            path: path.to_path_buf(),
            reason: "instruction markdown block is already absent".into(),
        });
        return Ok(());
    }
    if stripped.trim().is_empty() {
        plan_restore_backup_or_remove(changes, path, stripped.as_bytes())?;
    } else {
        plan_write_file(changes, path, stripped.as_bytes(), false)?;
    }
    Ok(())
}

/// Plan upserting a tagged JSON array entry at `entry_path`.
pub(crate) fn plan_tagged_json_upsert<F>(
    changes: &mut Vec<PlannedChange>,
    path: &Path,
    entry_path: &[&str],
    tag: &str,
    entry: Value,
    configure_root: F,
) -> Result<(), AgentConfigError>
where
    F: FnOnce(&mut Value),
{
    let mut root = match json_patch::read_or_empty(path) {
        Ok(root) => root,
        Err(AgentConfigError::JsonInvalid { .. }) => {
            changes.push(PlannedChange::Refuse {
                path: Some(path.to_path_buf()),
                reason: RefusalReason::InvalidConfig,
            });
            return Ok(());
        }
        Err(e) => return Err(e),
    };
    configure_root(&mut root);
    let changed = json_patch::upsert_tagged_array_entry(&mut root, entry_path, tag, entry)?;
    if changed {
        let bytes = json_patch::to_pretty(&root);
        plan_write_file(changes, path, &bytes, true)?;
    } else {
        changes.push(PlannedChange::NoOp {
            path: path.to_path_buf(),
            reason: "tagged JSON entry is already up to date".into(),
        });
    }
    Ok(())
}

/// Plan removing tagged JSON array entries under `parent_path`.
pub(crate) fn plan_tagged_json_remove_under<F>(
    changes: &mut Vec<PlannedChange>,
    path: &Path,
    parent_path: &[&str],
    tag: &str,
    is_empty_after: F,
    restore_when_empty: bool,
) -> Result<(), AgentConfigError>
where
    F: FnOnce(&Value) -> bool,
{
    if !path.exists() {
        changes.push(PlannedChange::NoOp {
            path: path.to_path_buf(),
            reason: "config file is already absent".into(),
        });
        return Ok(());
    }

    let mut root = match json_patch::read_or_empty(path) {
        Ok(root) => root,
        Err(AgentConfigError::JsonInvalid { .. }) => {
            changes.push(PlannedChange::Refuse {
                path: Some(path.to_path_buf()),
                reason: RefusalReason::InvalidConfig,
            });
            return Ok(());
        }
        Err(e) => return Err(e),
    };
    let changed = json_patch::remove_tagged_array_entries_under(&mut root, parent_path, tag)?;
    if !changed {
        changes.push(PlannedChange::NoOp {
            path: path.to_path_buf(),
            reason: "tagged JSON entry is already absent".into(),
        });
        return Ok(());
    }

    if is_empty_after(&root) {
        if restore_when_empty {
            let bytes = json_patch::to_pretty(&root);
            plan_restore_backup_or_remove(changes, path, &bytes)?;
        } else {
            changes.push(PlannedChange::RemoveFile {
                path: path.to_path_buf(),
            });
            let backup = fs_atomic::backup_path(path);
            if backup.exists() {
                changes.push(PlannedChange::RemoveFile { path: backup });
            }
        }
    } else {
        let bytes = json_patch::to_pretty(&root);
        plan_write_file(changes, path, &bytes, false)?;
    }
    Ok(())
}

/// True when a JSON root object is empty.
pub(crate) fn json_object_empty(root: &Value) -> bool {
    root.as_object().map(Map::is_empty).unwrap_or(true)
}

/// Plan pruning empty parent directories after removing `path`, stopping
/// before `stop_at`.
pub(crate) fn plan_remove_empty_parents(
    changes: &mut Vec<PlannedChange>,
    path: &Path,
    stop_at: &Path,
) {
    let Some(mut parent) = path.parent().map(Path::to_path_buf) else {
        return;
    };
    while parent != stop_at {
        let Ok(mut entries) = fs::read_dir(&parent) else {
            break;
        };
        if entries.next().is_some() {
            break;
        }
        changes.push(PlannedChange::RemoveDir {
            path: parent.clone(),
        });
        let Some(next) = parent.parent().map(Path::to_path_buf) else {
            break;
        };
        parent = next;
    }
}

fn plan_parent_dirs(changes: &mut Vec<PlannedChange>, path: &Path) {
    let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) else {
        return;
    };
    if parent.exists() {
        return;
    }
    let mut missing = Vec::<PathBuf>::new();
    let mut cur = parent;
    while !cur.exists() {
        missing.push(cur.to_path_buf());
        let Some(next) = cur.parent() else {
            break;
        };
        if next.as_os_str().is_empty() {
            break;
        }
        cur = next;
    }
    missing.reverse();
    for path in missing {
        if !changes
            .iter()
            .any(|c| matches!(c, PlannedChange::CreateDir { path: existing } if existing == &path))
        {
            changes.push(PlannedChange::CreateDir { path });
        }
    }
}

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

    #[test]
    fn plan_write_file_propagates_config_too_large() {
        use std::fs::File;
        let dir = tempfile::tempdir().unwrap();
        let cfg = dir.path().join("huge.json");
        File::create(&cfg)
            .unwrap()
            .set_len(crate::util::fs_atomic::MAX_CONFIG_BYTES + 1)
            .unwrap();
        let mut changes = Vec::new();
        let err = plan_write_file(&mut changes, &cfg, b"x", true).unwrap_err();
        assert!(matches!(
            err,
            crate::error::AgentConfigError::ConfigTooLarge { .. }
        ));
    }

    #[test]
    fn plan_restore_treats_oversize_backup_as_non_matching() {
        use std::fs::File;
        let dir = tempfile::tempdir().unwrap();
        let cfg = dir.path().join("settings.json");
        let backup = crate::util::fs_atomic::backup_path(&cfg);
        File::create(&backup)
            .unwrap()
            .set_len(crate::util::fs_atomic::MAX_CONFIG_BYTES + 1)
            .unwrap();
        let mut changes = Vec::new();
        plan_restore_backup_or_remove(&mut changes, &cfg, b"desired").unwrap();
        // Should plan a remove, NOT a restore.
        assert!(changes
            .iter()
            .any(|c| matches!(c, crate::plan::PlannedChange::RemoveFile { .. })));
        assert!(!changes
            .iter()
            .any(|c| matches!(c, crate::plan::PlannedChange::RestoreBackup { .. })));
    }
}