zig-core 0.5.6

Core library for zig — workflow orchestration engine for AI coding agents
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
//! Management commands for resource files: list / add / remove / show / where.
//!
//! These functions back the `zig resources …` subcommands. They operate on the
//! same tiered layout that [`crate::resources::ResourceCollector`] consumes at
//! run time:
//!
//! * `~/.zig/resources/_shared/` — the global shared tier
//! * `~/.zig/resources/<workflow>/` — the global per-workflow tier
//! * `<git-root>/.zig/resources/` — the project (cwd) tier
//!
//! Inline resources declared in `.zug` files are *not* manipulated by these
//! commands — they live inside the workflow file itself and the user edits
//! them by hand.

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

use crate::error::ZigError;
use crate::paths;

/// Which tier(s) a `list` or `where` command should consider.
///
/// `Both` (the default when neither `--global` nor `--cwd` is passed) walks
/// every tier that exists on disk.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResourceScope {
    /// Show only the global tiers under `~/.zig/resources/`.
    Global,
    /// Show only the project tier under `<git-root>/.zig/resources/`.
    Cwd,
    /// Show every tier (the default).
    Both,
}

impl ResourceScope {
    /// Build a scope from the mutually-exclusive `--global` / `--cwd` flags.
    pub fn from_flags(global: bool, cwd: bool) -> Self {
        match (global, cwd) {
            (true, false) => ResourceScope::Global,
            (false, true) => ResourceScope::Cwd,
            _ => ResourceScope::Both,
        }
    }
}

/// Where an `add` or `remove` command should place / look for a resource.
///
/// Constructed with [`ResourceTarget::from_flags`], which enforces the
/// mutually-exclusive flag rules (a target must be unambiguous).
#[derive(Debug, Clone)]
pub enum ResourceTarget {
    /// `~/.zig/resources/_shared/`
    GlobalShared,
    /// `~/.zig/resources/<workflow>/`
    GlobalWorkflow(String),
    /// `<git-root>/.zig/resources/` — falls back to `./.zig/resources/` when
    /// not inside a git repo.
    Cwd,
}

impl ResourceTarget {
    /// Resolve a target from the CLI flag combination passed by the user.
    ///
    /// Rules:
    /// * `--workflow <name>` always means the global per-workflow tier.
    /// * `--cwd` means the project tier.
    /// * `--global` (without `--workflow`) means the global shared tier.
    /// * No flags at all is treated as `--cwd` (the most local tier).
    pub fn from_flags(workflow: Option<&str>, global: bool, cwd: bool) -> Result<Self, ZigError> {
        if let Some(name) = workflow {
            if cwd {
                return Err(ZigError::Validation(
                    "--workflow cannot be combined with --cwd".into(),
                ));
            }
            return Ok(ResourceTarget::GlobalWorkflow(name.to_string()));
        }
        if cwd {
            return Ok(ResourceTarget::Cwd);
        }
        if global {
            return Ok(ResourceTarget::GlobalShared);
        }
        Ok(ResourceTarget::Cwd)
    }

    /// Resolve to an absolute directory path, creating it if it doesn't exist.
    pub fn ensure_dir(&self) -> Result<PathBuf, ZigError> {
        let dir = match self {
            ResourceTarget::GlobalShared => paths::ensure_global_resources_dir(Some("_shared"))?,
            ResourceTarget::GlobalWorkflow(name) => paths::ensure_global_resources_dir(Some(name))?,
            ResourceTarget::Cwd => ensure_cwd_resources_dir()?,
        };
        Ok(dir)
    }

    /// Resolve to an absolute directory path *without* creating it. Returns
    /// `None` when the directory cannot be derived (e.g. `$HOME` unset).
    pub fn existing_dir(&self) -> Option<PathBuf> {
        match self {
            ResourceTarget::GlobalShared => paths::global_shared_resources_dir(),
            ResourceTarget::GlobalWorkflow(name) => paths::global_resources_for(name),
            ResourceTarget::Cwd => paths::cwd_resources_dir().or_else(|| {
                std::env::current_dir()
                    .ok()
                    .map(|p| p.join(".zig").join("resources"))
            }),
        }
    }

    /// Short label for diagnostic messages.
    pub fn label(&self) -> String {
        match self {
            ResourceTarget::GlobalShared => "global:_shared".to_string(),
            ResourceTarget::GlobalWorkflow(n) => format!("global:{n}"),
            ResourceTarget::Cwd => "cwd".to_string(),
        }
    }
}

fn ensure_cwd_resources_dir() -> Result<PathBuf, ZigError> {
    if let Some(existing) = paths::cwd_resources_dir() {
        return Ok(existing);
    }
    let cwd = std::env::current_dir()
        .map_err(|e| ZigError::Io(format!("failed to read current directory: {e}")))?;
    let dir = cwd.join(".zig").join("resources");
    std::fs::create_dir_all(&dir)
        .map_err(|e| ZigError::Io(format!("failed to create {}: {e}", dir.display())))?;
    Ok(dir)
}

/// A single resource entry returned by [`list_resources`].
#[derive(Debug, Clone)]
pub struct ListedResource {
    pub tier: String,
    pub name: String,
    pub path: PathBuf,
}

/// List resources discovered under the requested scope.
///
/// Prints a human-readable table to stdout. When `workflow` is `Some`, the
/// global tier is restricted to that workflow's directory; otherwise every
/// `~/.zig/resources/<name>/` subdirectory is walked.
pub fn list_resources(workflow: Option<&str>, scope: ResourceScope) -> Result<(), ZigError> {
    let mut entries: Vec<ListedResource> = Vec::new();

    let walk_global = matches!(scope, ResourceScope::Global | ResourceScope::Both);
    let walk_cwd = matches!(scope, ResourceScope::Cwd | ResourceScope::Both);

    if walk_global {
        if let Some(shared) = paths::global_shared_resources_dir() {
            collect_listing(&shared, "global:_shared", &mut entries);
        }
        if let Some(name) = workflow {
            if let Some(wf_dir) = paths::global_resources_for(name) {
                collect_listing(&wf_dir, &format!("global:{name}"), &mut entries);
            }
        } else if let Some(root) = paths::global_resources_dir() {
            // Walk every immediate subdirectory of ~/.zig/resources/ (skipping
            // _shared which we already covered) and treat each one as a
            // workflow-scoped tier.
            if let Ok(read) = std::fs::read_dir(&root) {
                for entry in read.flatten() {
                    let path = entry.path();
                    if !path.is_dir() {
                        continue;
                    }
                    let name = match path.file_name().and_then(|n| n.to_str()) {
                        Some(n) => n,
                        None => continue,
                    };
                    if name == "_shared" {
                        continue;
                    }
                    collect_listing(&path, &format!("global:{name}"), &mut entries);
                }
            }
        }
    }

    if walk_cwd {
        if let Some(cwd_dir) = paths::cwd_resources_dir() {
            collect_listing(&cwd_dir, "cwd", &mut entries);
        }
    }

    if entries.is_empty() {
        println!("No resources found.");
        println!(
            "Hint: add one with `zig resources add <file> [--global|--cwd|--workflow <name>]`"
        );
        return Ok(());
    }

    let tier_w = entries
        .iter()
        .map(|e| e.tier.len())
        .max()
        .unwrap_or(4)
        .max(4);
    let name_w = entries
        .iter()
        .map(|e| e.name.len())
        .max()
        .unwrap_or(4)
        .max(4);

    println!(
        "{:<tier_w$}  {:<name_w$}  PATH",
        "TIER",
        "NAME",
        tier_w = tier_w,
        name_w = name_w,
    );
    for e in &entries {
        println!(
            "{:<tier_w$}  {:<name_w$}  {}",
            e.tier,
            e.name,
            e.path.display(),
            tier_w = tier_w,
            name_w = name_w,
        );
    }

    Ok(())
}

fn collect_listing(dir: &Path, tier: &str, out: &mut Vec<ListedResource>) {
    if !dir.is_dir() {
        return;
    }
    let mut stack = vec![dir.to_path_buf()];
    while let Some(current) = stack.pop() {
        let read = match std::fs::read_dir(&current) {
            Ok(r) => r,
            Err(_) => continue,
        };
        for entry in read.flatten() {
            let path = entry.path();
            let metadata = match std::fs::metadata(&path) {
                Ok(m) => m,
                Err(_) => continue,
            };
            if metadata.is_dir() {
                stack.push(path);
                continue;
            }
            if !metadata.is_file() {
                continue;
            }
            let name = path
                .file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_else(|| path.display().to_string());
            out.push(ListedResource {
                tier: tier.to_string(),
                name,
                path: path.clone(),
            });
        }
    }
}

/// Copy a file into the chosen tier directory, optionally renaming it.
///
/// Returns the absolute path of the destination file. Refuses to overwrite an
/// existing file (the user must `zig resources remove <name>` first).
pub fn add_resource(
    file: &str,
    target: ResourceTarget,
    name: Option<&str>,
) -> Result<PathBuf, ZigError> {
    let src = Path::new(file);
    if !src.exists() {
        return Err(ZigError::Io(format!("source file not found: {file}")));
    }
    if !src.is_file() {
        return Err(ZigError::Io(format!("not a regular file: {file}")));
    }

    let dir = target.ensure_dir()?;
    let dest = add_to_dir(src, &dir, name)?;
    println!(
        "added resource '{}' to {} ({})",
        dest.file_name()
            .map(|n| n.to_string_lossy())
            .unwrap_or_default(),
        target.label(),
        dest.display()
    );
    Ok(dest)
}

/// Lower-level helper: copy `src` into `dir`, optionally renaming it.
///
/// Refuses to overwrite. Used internally by [`add_resource`] and exposed for
/// tests that want to operate on an explicit directory without touching the
/// global `$HOME` layout.
pub fn add_to_dir(src: &Path, dir: &Path, name: Option<&str>) -> Result<PathBuf, ZigError> {
    if !src.exists() {
        return Err(ZigError::Io(format!(
            "source file not found: {}",
            src.display()
        )));
    }
    if !src.is_file() {
        return Err(ZigError::Io(format!(
            "not a regular file: {}",
            src.display()
        )));
    }

    if !dir.exists() {
        std::fs::create_dir_all(dir)
            .map_err(|e| ZigError::Io(format!("failed to create {}: {e}", dir.display())))?;
    }

    let dest_name = name
        .map(str::to_string)
        .or_else(|| src.file_name().map(|n| n.to_string_lossy().into_owned()))
        .ok_or_else(|| {
            ZigError::Io(format!(
                "could not derive a destination name from {}",
                src.display()
            ))
        })?;

    let dest = dir.join(&dest_name);
    if dest.exists() {
        return Err(ZigError::Io(format!(
            "resource '{}' already exists at {} — remove it first",
            dest_name,
            dest.display()
        )));
    }

    std::fs::copy(src, &dest).map_err(|e| {
        ZigError::Io(format!(
            "failed to copy {}{}: {e}",
            src.display(),
            dest.display()
        ))
    })?;
    Ok(dest)
}

/// Delete a resource by name from the chosen tier.
pub fn remove_resource(name: &str, target: ResourceTarget) -> Result<(), ZigError> {
    let dir = target
        .existing_dir()
        .ok_or_else(|| ZigError::Io("could not resolve target directory (HOME unset?)".into()))?;
    let path = remove_from_dir(name, &dir)?;
    println!(
        "removed resource '{}' from {} ({})",
        name,
        target.label(),
        path.display()
    );
    Ok(())
}

/// Lower-level helper: remove a single resource from an explicit directory.
pub fn remove_from_dir(name: &str, dir: &Path) -> Result<PathBuf, ZigError> {
    if !dir.is_dir() {
        return Err(ZigError::Io(format!(
            "tier directory does not exist: {}",
            dir.display()
        )));
    }
    let path = dir.join(name);
    if !path.exists() {
        return Err(ZigError::Io(format!(
            "resource '{}' not found in {}",
            name,
            dir.display()
        )));
    }
    std::fs::remove_file(&path)
        .map_err(|e| ZigError::Io(format!("failed to remove {}: {e}", path.display())))?;
    Ok(path)
}

/// Print the absolute path and contents of a resource discovered in any tier.
pub fn show_resource(name: &str, workflow: Option<&str>) -> Result<(), ZigError> {
    let candidates = candidate_dirs(workflow);
    for (label, dir) in &candidates {
        let path = dir.join(name);
        if path.is_file() {
            let contents = std::fs::read_to_string(&path)
                .map_err(|e| ZigError::Io(format!("failed to read {}: {e}", path.display())))?;
            println!("# {} ({})", path.display(), label);
            print!("{contents}");
            if !contents.ends_with('\n') {
                println!();
            }
            return Ok(());
        }
    }
    Err(ZigError::Io(format!(
        "resource '{name}' not found in any tier"
    )))
}

/// Print the directories the collector would search for the current
/// invocation, in tier order.
pub fn print_search_paths(workflow: Option<&str>) -> Result<(), ZigError> {
    println!("Resource search paths (in collection order):");
    for (label, dir) in candidate_dirs(workflow) {
        let exists = if dir.is_dir() { "" } else { " (missing)" };
        println!("  {label:<16}  {}{exists}", dir.display());
    }
    Ok(())
}

fn candidate_dirs(workflow: Option<&str>) -> Vec<(String, PathBuf)> {
    let mut out: Vec<(String, PathBuf)> = Vec::new();
    if let Some(d) = paths::global_shared_resources_dir() {
        out.push(("global:_shared".into(), d));
    }
    if let Some(name) = workflow {
        if let Some(d) = paths::global_resources_for(name) {
            out.push((format!("global:{name}"), d));
        }
    }
    if let Some(d) = paths::cwd_resources_dir() {
        out.push(("cwd".into(), d));
    } else if let Ok(cwd) = std::env::current_dir() {
        out.push(("cwd".into(), cwd.join(".zig").join("resources")));
    }
    out
}

#[cfg(test)]
#[path = "resources_manage_tests.rs"]
mod tests;