apoc 0.9.1

Agentic process control for LLMs
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
//! Embedded apoc skill distribution.

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

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use thiserror::Error;

const SKILL_NAME: &str = "apoc";
const SKILL_MD: &str = include_str!("../skills/apoc/SKILL.md");
const OPENAI_YAML: &str = include_str!("../skills/apoc/agents/openai.yaml");
const REFERENCES: &[(&str, &str)] = &[
    (
        "references/execution.md",
        include_str!("../skills/apoc/references/execution.md"),
    ),
    (
        "references/workflows.md",
        include_str!("../skills/apoc/references/workflows.md"),
    ),
    (
        "references/debugging.md",
        include_str!("../skills/apoc/references/debugging.md"),
    ),
];
const MANIFEST_FILE: &str = ".apoc-skill.json";
const MANIFEST_VERSION: u32 = 1;
const RELATIVE_CANONICAL: &str = "../../.agents/skills/apoc";

/// Result state for the embedded apoc skill installation.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct SkillStatus {
    /// Overall installation state.
    pub state: String,
    /// Whether an apoc skill target is usable from the managed roots.
    pub ready: bool,
    /// Canonical `.agents` root state.
    pub canonical_state: String,
    /// Codex root state.
    pub codex_state: String,
    /// Claude root state.
    pub claude_state: String,
    /// Prefix used to resolve agent skill roots.
    pub prefix: String,
    /// Canonical skill directory under `.agents`.
    pub canonical: String,
    /// Codex skill path.
    pub codex: String,
    /// Claude skill path.
    pub claude: String,
    /// Digest expected for the embedded apoc skill payload.
    pub digest: String,
    /// Human-readable state details.
    pub details: Vec<String>,
}

/// Error returned while inspecting or installing the embedded apoc skill.
#[derive(Debug, Error)]
pub enum SkillError {
    /// Prefix did not resolve to an OS user home.
    #[error("Could not determine the current user's home directory")]
    MissingHome,
    /// Filesystem operation failed.
    #[error("{action} \"{path}\": {source}")]
    Io {
        /// Filesystem action being attempted.
        action: &'static str,
        /// Path affected by the operation.
        path: String,
        /// Underlying I/O failure.
        #[source]
        source: std::io::Error,
    },
    /// Existing unmanaged target blocks installation.
    #[error("{0}")]
    Conflict(String),
}

/// Return the current embedded apoc skill status under the OS user home.
pub fn status() -> Result<SkillStatus, SkillError> {
    let prefix = dirs::home_dir().ok_or(SkillError::MissingHome)?;
    status_with_prefix(prefix)
}

/// Install or update the embedded apoc skill under the OS user home.
pub fn install(force: bool) -> Result<SkillStatus, SkillError> {
    let prefix = dirs::home_dir().ok_or(SkillError::MissingHome)?;
    install_with_prefix(prefix, force)
}

/// Return the current embedded apoc skill status under `prefix`.
pub fn status_with_prefix(prefix: impl AsRef<Path>) -> Result<SkillStatus, SkillError> {
    let paths = SkillPaths::new(prefix.as_ref());
    Ok(status_for(&paths))
}

/// Install or update the embedded apoc skill under `prefix`.
pub fn install_with_prefix(
    prefix: impl AsRef<Path>,
    force: bool,
) -> Result<SkillStatus, SkillError> {
    let paths = SkillPaths::new(prefix.as_ref());
    let state = classify(&paths);

    if !force {
        let conflicts = state.conflicts();
        if !conflicts.is_empty() {
            return Err(SkillError::Conflict(conflicts.join("; ")));
        }
    }

    match state.canonical {
        RootState::Current | RootState::External => {}
        RootState::Missing | RootState::ManagedOutdated => {
            write_managed_skill(&paths)?;
        }
        RootState::Conflict if force => {
            replace_exact_target(&paths.canonical)?;
            write_managed_skill(&paths)?;
        }
        RootState::Conflict => unreachable!("non-force conflict returned earlier"),
    }

    ensure_consumer_link(&paths.codex, force)?;
    ensure_consumer_link(&paths.claude, force)?;
    for root in framework_consumer_roots(&paths) {
        ensure_consumer_link(&root, force)?;
    }

    Ok(status_for(&paths))
}

/// Returns one consumer root for every non-universal agent the framework currently detects.
///
/// The framework owns the agent registry, so apoc reaches new agent families as incurs adds
/// them rather than tracking its own list. Universal agents are excluded because they read the
/// canonical `.agents/skills` directory this installer already writes. Roots outside the user
/// home, and any root deeper than the relative canonical target, are skipped so the symlink a
/// consumer receives always resolves back to that canonical directory.
fn framework_consumer_roots(paths: &SkillPaths) -> Vec<PathBuf> {
    let Some(home) = dirs::home_dir() else {
        return Vec::new();
    };
    let mut roots = Vec::new();
    for agent in incurs::agents::detect() {
        if agent.universal {
            continue;
        }
        let Ok(relative) = agent.global_skills_dir.strip_prefix(&home) else {
            continue;
        };
        if relative.components().count() != 2 {
            continue;
        }
        let root = paths.prefix.join(relative).join(SKILL_NAME);
        if root != paths.claude && root != paths.codex && !roots.contains(&root) {
            roots.push(root);
        }
    }
    roots
}

#[derive(Debug)]
struct SkillPaths {
    prefix: PathBuf,
    canonical: PathBuf,
    codex: PathBuf,
    claude: PathBuf,
}

impl SkillPaths {
    fn new(prefix: &Path) -> Self {
        let prefix = prefix.to_path_buf();
        Self {
            canonical: prefix.join(".agents/skills").join(SKILL_NAME),
            codex: prefix.join(".codex/skills").join(SKILL_NAME),
            claude: prefix.join(".claude/skills").join(SKILL_NAME),
            prefix,
        }
    }
}

#[derive(Debug)]
struct Classified {
    state: String,
    ready: bool,
    canonical: RootState,
    codex: RootState,
    claude: RootState,
    details: Vec<String>,
}

impl Classified {
    fn conflicts(&self) -> Vec<String> {
        let mut details = Vec::new();
        if self.canonical == RootState::Conflict {
            details.extend(self.details_for_root("canonical"));
        }
        if self.codex == RootState::Conflict {
            details.extend(self.details_for_root("codex"));
        }
        if self.claude == RootState::Conflict {
            details.extend(self.details_for_root("claude"));
        }
        if details.is_empty()
            && self
                .details
                .iter()
                .any(|detail| detail.contains("conflict"))
        {
            self.details.clone()
        } else {
            details
        }
    }

    fn details_for_root(&self, root: &str) -> Vec<String> {
        self.details
            .iter()
            .filter(|detail| detail.starts_with(root))
            .cloned()
            .collect()
    }
}

#[derive(Debug, Serialize, Deserialize)]
struct Manifest {
    product: String,
    version: u32,
    digest: String,
}

fn status_for(paths: &SkillPaths) -> SkillStatus {
    let state = classify(paths);
    SkillStatus {
        state: state.state,
        ready: state.ready,
        canonical_state: state.canonical.public_state().to_string(),
        codex_state: state.codex.public_state().to_string(),
        claude_state: state.claude.public_state().to_string(),
        prefix: display(&paths.prefix),
        canonical: display(&paths.canonical),
        codex: display(&paths.codex),
        claude: display(&paths.claude),
        digest: embedded_digest(),
        details: state.details,
    }
}

fn classify(paths: &SkillPaths) -> Classified {
    let mut details = Vec::new();
    let canonical = classify_canonical(paths, &mut details);
    let codex = classify_consumer("codex", &paths.codex, &mut details);
    let claude = classify_consumer("claude", &paths.claude, &mut details);
    let roots = [canonical, codex, claude];
    let state =
        if roots.contains(&RootState::Conflict) || roots.contains(&RootState::ManagedOutdated) {
            "conflict"
        } else if canonical == RootState::External {
            "external"
        } else if roots.contains(&RootState::Missing) {
            "missing"
        } else {
            "current"
        };

    Classified {
        state: state.to_string(),
        ready: matches!(state, "current" | "external") && !roots.contains(&RootState::Missing),
        canonical,
        codex,
        claude,
        details,
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RootState {
    Current,
    Missing,
    External,
    ManagedOutdated,
    Conflict,
}

impl RootState {
    fn public_state(self) -> &'static str {
        match self {
            Self::Current => "current",
            Self::Missing => "missing",
            Self::External => "external",
            Self::ManagedOutdated | Self::Conflict => "conflict",
        }
    }
}

fn classify_canonical(paths: &SkillPaths, details: &mut Vec<String>) -> RootState {
    let Ok(meta) = fs::symlink_metadata(&paths.canonical) else {
        details.push(format!(
            "canonical {} is missing",
            display(&paths.canonical)
        ));
        return RootState::Missing;
    };
    if meta.file_type().is_symlink() {
        return if valid_external_symlink(&paths.canonical) {
            RootState::External
        } else {
            details.push(format!(
                "canonical {} is a symlink but not a valid external apoc skill",
                display(&paths.canonical)
            ));
            RootState::Conflict
        };
    }
    if !meta.is_dir() {
        details.push(format!(
            "canonical {} is not a directory",
            display(&paths.canonical)
        ));
        return RootState::Conflict;
    }
    if managed_current(&paths.canonical) {
        RootState::Current
    } else if managed_marker(&paths.canonical) {
        details.push(format!(
            "canonical {} is apoc-managed but not current",
            display(&paths.canonical)
        ));
        RootState::ManagedOutdated
    } else {
        details.push(format!(
            "canonical {} exists but is not an apoc-managed skill",
            display(&paths.canonical)
        ));
        RootState::Conflict
    }
}

fn valid_external_symlink(path: &Path) -> bool {
    let Ok(target) = fs::canonicalize(path) else {
        return false;
    };
    target.join("SKILL.md").is_file() && target.join("agents/openai.yaml").is_file()
}

fn classify_consumer(root: &str, path: &Path, details: &mut Vec<String>) -> RootState {
    let Ok(meta) = fs::symlink_metadata(path) else {
        details.push(format!("{root} {} is missing", display(path)));
        return RootState::Missing;
    };
    if !meta.file_type().is_symlink() {
        details.push(format!(
            "{root} {} is not the managed apoc symlink",
            display(path)
        ));
        return RootState::Conflict;
    }
    match fs::read_link(path) {
        Ok(target) if target.as_path() == Path::new(RELATIVE_CANONICAL) => RootState::Current,
        Ok(target) => {
            details.push(format!(
                "{root} {} points to {}, expected {}",
                display(path),
                target.display(),
                RELATIVE_CANONICAL
            ));
            RootState::Conflict
        }
        Err(error) => {
            details.push(format!("{root} could not read {}: {error}", display(path)));
            RootState::Conflict
        }
    }
}

fn managed_current(path: &Path) -> bool {
    let Ok(bytes) = fs::read(path.join(MANIFEST_FILE)) else {
        return false;
    };
    let Ok(manifest) = serde_json::from_slice::<Manifest>(&bytes) else {
        return false;
    };
    manifest.product == SKILL_NAME
        && manifest.version == MANIFEST_VERSION
        && manifest.digest == embedded_digest()
        && fs::read_to_string(path.join("SKILL.md")).is_ok_and(|text| text == SKILL_MD)
        && fs::read_to_string(path.join("agents/openai.yaml")).is_ok_and(|text| text == OPENAI_YAML)
        && REFERENCES.iter().all(|(relative, expected)| {
            fs::read_to_string(path.join(relative)).is_ok_and(|text| text == *expected)
        })
}

fn managed_marker(path: &Path) -> bool {
    let Ok(bytes) = fs::read(path.join(MANIFEST_FILE)) else {
        return false;
    };
    serde_json::from_slice::<Manifest>(&bytes).is_ok_and(|manifest| manifest.product == SKILL_NAME)
}

fn write_managed_skill(paths: &SkillPaths) -> Result<(), SkillError> {
    create_dir_all(&paths.canonical)?;
    create_dir_all(&paths.canonical.join("agents"))?;
    write_atomic(&paths.canonical.join("SKILL.md"), SKILL_MD.as_bytes())?;
    write_atomic(
        &paths.canonical.join("agents/openai.yaml"),
        OPENAI_YAML.as_bytes(),
    )?;
    for (relative, contents) in REFERENCES {
        let path = paths.canonical.join(relative);
        create_dir_all(path.parent().expect("reference path has a parent"))?;
        write_atomic(&path, contents.as_bytes())?;
    }
    write_atomic(
        &paths.canonical.join(MANIFEST_FILE),
        serde_json::to_vec_pretty(&Manifest {
            product: SKILL_NAME.to_string(),
            version: MANIFEST_VERSION,
            digest: embedded_digest(),
        })
        .expect("manifest serializes")
        .as_slice(),
    )
}

fn ensure_consumer_link(path: &Path, force: bool) -> Result<(), SkillError> {
    create_dir_all(path.parent().expect("skill path has a parent"))?;
    match classify_consumer("consumer", path, &mut Vec::new()) {
        RootState::Current => return Ok(()),
        RootState::Missing => {}
        RootState::Conflict if force => {}
        RootState::Conflict => {
            return Err(SkillError::Conflict(format!(
                "{} is not the managed apoc symlink",
                display(path)
            )));
        }
        RootState::External | RootState::ManagedOutdated => unreachable!("consumer state"),
    }
    symlink_atomic(Path::new(RELATIVE_CANONICAL), path, force)
}

fn replace_exact_target(path: &Path) -> Result<(), SkillError> {
    let Ok(meta) = fs::symlink_metadata(path) else {
        return Ok(());
    };
    if meta.is_dir() && !meta.file_type().is_symlink() {
        fs::remove_dir_all(path).map_err(|source| SkillError::Io {
            action: "Remove directory",
            path: display(path),
            source,
        })
    } else {
        fs::remove_file(path).map_err(|source| SkillError::Io {
            action: "Remove file",
            path: display(path),
            source,
        })
    }
}

fn create_dir_all(path: &Path) -> Result<(), SkillError> {
    fs::create_dir_all(path).map_err(|source| SkillError::Io {
        action: "Create directory",
        path: display(path),
        source,
    })
}

fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), SkillError> {
    let tmp = temp_sibling(path);
    fs::write(&tmp, bytes).map_err(|source| SkillError::Io {
        action: "Write",
        path: display(&tmp),
        source,
    })?;
    fs::rename(&tmp, path).map_err(|source| SkillError::Io {
        action: "Rename",
        path: display(path),
        source,
    })
}

#[cfg(unix)]
fn symlink_atomic(target: &Path, link: &Path, force: bool) -> Result<(), SkillError> {
    let tmp = temp_sibling(link);
    let result = std::os::unix::fs::symlink(target, &tmp).map_err(|source| SkillError::Io {
        action: "Create symlink",
        path: display(&tmp),
        source,
    });
    if result.is_err() {
        let _ = fs::remove_file(&tmp);
    }
    result?;

    if force
        && let Ok(meta) = fs::symlink_metadata(link)
        && meta.is_dir()
        && !meta.file_type().is_symlink()
    {
        fs::remove_dir_all(link).map_err(|source| SkillError::Io {
            action: "Remove directory",
            path: display(link),
            source,
        })?;
    }

    match fs::rename(&tmp, link) {
        Ok(()) => Ok(()),
        Err(source) => {
            let _ = fs::remove_file(&tmp);
            Err(SkillError::Io {
                action: "Rename",
                path: display(link),
                source,
            })
        }
    }
}

fn embedded_digest() -> String {
    let mut digest = Sha256::new();
    digest.update(SKILL_MD.as_bytes());
    digest.update([0]);
    digest.update(OPENAI_YAML.as_bytes());
    for (relative, contents) in REFERENCES {
        digest.update([0]);
        digest.update(relative.as_bytes());
        digest.update([0]);
        digest.update(contents.as_bytes());
    }
    format!("{:x}", digest.finalize())
}

fn display(path: &Path) -> String {
    path.display().to_string()
}

fn temp_sibling(path: &Path) -> PathBuf {
    let name = path
        .file_name()
        .map(|value| value.to_string_lossy())
        .unwrap_or_else(|| "apoc".into());
    path.with_file_name(format!(".{name}.apoc-tmp-{}", process::id()))
}