netsky 0.2.0

netsky CLI: the viable system launcher and subcommand dispatcher
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
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::process::Command;

use netsky_core::agent::AgentId;
use netsky_prompts::layers::{
    PromptAgentKind, PromptContext, PromptLayer, PromptLayerKind, PromptLayerOrigin, compose,
    resolve_catalog_layers,
};
use serde::Serialize;
use serde_json::json;

use crate::cli::{PromptOutputFormat, PromptsCommand};

const BYTES_PER_TOKEN_X10: usize = 33;
const LAYER_WARN_TOKENS: usize = 2_000;
const COMPOSED_WARN_TOKENS: usize = 12_000;
const SKILL_WARN_TOKENS: usize = 1_500;
const CADENCE_DENYLIST: &[&str] = &[
    "we made a big update",
    "in the time it takes",
    "this change improves",
];
const CONTRADICTION_RULES: &[(&str, &str, &str)] = &[
    (
        "always use clones",
        "do it inline",
        "clone dispatch guidance disagrees",
    ),
    ("do not browse", "must browse", "browse guidance disagrees"),
    (
        "banned at clone level",
        "requires",
        "tool policy says both banned and required",
    ),
];

pub fn run(sub: PromptsCommand) -> netsky_core::Result<()> {
    match sub {
        PromptsCommand::Ls { agent, cwd, format } => ls(agent.as_deref(), cwd.as_deref(), format),
        PromptsCommand::Cat { layer, agent, cwd } => cat(&layer, agent.as_deref(), cwd.as_deref()),
        PromptsCommand::Diff {
            layer,
            commit,
            agent,
            cwd,
        } => diff(&layer, &commit, agent.as_deref(), cwd.as_deref()),
        PromptsCommand::Compose {
            agent,
            cwd,
            skills,
            format,
        } => compose_cmd(agent.as_deref(), cwd.as_deref(), &skills, format),
        PromptsCommand::Audit {
            agent,
            cwd,
            skills,
            format,
        } => audit(agent.as_deref(), cwd.as_deref(), &skills, format),
    }
}

fn ls(
    agent: Option<&str>,
    cwd: Option<&Path>,
    format: PromptOutputFormat,
) -> netsky_core::Result<()> {
    let query = PromptQuery::new(agent, cwd)?;
    let layers = resolve_catalog_layers(query.context(), &query.cwd, &[])?;
    match format {
        PromptOutputFormat::Text => print_layers_text(&layers),
        PromptOutputFormat::Json => {
            println!("{}", serde_json::to_string_pretty(&layers)?);
        }
    }
    Ok(())
}

fn cat(layer_id: &str, agent: Option<&str>, cwd: Option<&Path>) -> netsky_core::Result<()> {
    let query = PromptQuery::new(agent, cwd)?;
    let layers = resolve_catalog_layers(query.context(), &query.cwd, &[])?;
    let layer = find_layer(&layers, layer_id)?;
    if layer.body.is_empty() {
        netsky_core::bail!("layer `{layer_id}` is empty");
    }
    print!("{}", layer.body);
    if !layer.body.ends_with('\n') {
        println!();
    }
    Ok(())
}

fn diff(
    layer_id: &str,
    commit: &str,
    agent: Option<&str>,
    cwd: Option<&Path>,
) -> netsky_core::Result<()> {
    let query = PromptQuery::new(agent, cwd)?;
    let layers = resolve_catalog_layers(query.context(), &query.cwd, &[])?;
    let layer = find_layer(&layers, layer_id)?;
    let Some(git_path) = layer.git_path.as_ref() else {
        netsky_core::bail!("layer {layer_id} is not git-backed");
    };
    let output = Command::new("git")
        .arg("-C")
        .arg(&query.cwd)
        .arg("diff")
        .arg(format!("{commit}..HEAD"))
        .arg("--")
        .arg(git_path)
        .output()
        .map_err(|err| {
            std::io::Error::other(format!("run git diff for {}: {err}", git_path.display()))
        })?;
    if !output.status.success() {
        netsky_core::bail!("{}", String::from_utf8_lossy(&output.stderr).trim());
    }
    print!("{}", String::from_utf8_lossy(&output.stdout));
    Ok(())
}

fn compose_cmd(
    agent: Option<&str>,
    cwd: Option<&Path>,
    skills: &[String],
    format: PromptOutputFormat,
) -> netsky_core::Result<()> {
    let query = PromptQuery::new(agent, cwd)?;
    let layers = resolve_catalog_layers(query.context(), &query.cwd, skills)?;
    let active = active_layers(&layers);
    let body = compose(&active)?;
    match format {
        PromptOutputFormat::Text => print!("{body}"),
        PromptOutputFormat::Json => {
            println!(
                "{}",
                serde_json::to_string_pretty(&json!({
                    "layers": active,
                    "body": body,
                }))?
            );
        }
    }
    Ok(())
}

fn audit(
    agent: Option<&str>,
    cwd: Option<&Path>,
    skills: &[String],
    format: PromptOutputFormat,
) -> netsky_core::Result<()> {
    let query = PromptQuery::new(agent, cwd)?;
    let layers = resolve_catalog_layers(query.context(), &query.cwd, skills)?;
    let report = build_audit_report(&query.cwd, &layers, skills);
    match format {
        PromptOutputFormat::Text => print_audit_text(&report),
        PromptOutputFormat::Json => println!("{}", serde_json::to_string_pretty(&report)?),
    }
    if report
        .findings
        .iter()
        .any(|finding| finding.severity == "error")
    {
        std::process::exit(1);
    }
    Ok(())
}

fn active_layers(layers: &[PromptLayer]) -> Vec<PromptLayer> {
    layers
        .iter()
        .filter(|layer| layer.active)
        .cloned()
        .collect()
}

fn print_layers_text(layers: &[PromptLayer]) {
    println!(
        "{:<24} {:<16} {:<10} {:>6} {:<8} note",
        "id", "kind", "origin", "bytes", "status"
    );
    for layer in layers {
        let status = if layer.active { "active" } else { "catalog" };
        println!(
            "{:<24} {:<16} {:<10} {:>6} {:<8} {}",
            layer.id,
            kind_name(layer.kind),
            origin_name(layer.origin),
            layer.bytes(),
            status,
            layer.note.as_deref().unwrap_or("")
        );
    }
}

fn print_audit_text(report: &AuditReport) {
    if report.findings.is_empty() {
        println!("ok: no prompt audit findings");
        return;
    }
    for finding in &report.findings {
        println!(
            "{}: {} [{}]",
            finding.severity, finding.message, finding.layer_id
        );
    }
}

fn kind_name(kind: PromptLayerKind) -> &'static str {
    match kind {
        PromptLayerKind::Base => "base",
        PromptLayerKind::Identity => "identity",
        PromptLayerKind::CwdAddendum => "cwd_addendum",
        PromptLayerKind::RuntimeAddendum => "runtime_addendum",
        PromptLayerKind::Skill => "skill",
        PromptLayerKind::HarnessDoc => "harness_doc",
        PromptLayerKind::InstallAsset => "install_asset",
    }
}

fn origin_name(origin: PromptLayerOrigin) -> &'static str {
    match origin {
        PromptLayerOrigin::LiveFile => "live",
        PromptLayerOrigin::BundledFile => "bundled",
        PromptLayerOrigin::RuntimeConfig => "runtime",
        PromptLayerOrigin::Virtual => "virtual",
    }
}

fn find_layer<'a>(
    layers: &'a [PromptLayer],
    layer_id: &str,
) -> netsky_core::Result<&'a PromptLayer> {
    layers
        .iter()
        .find(|layer| layer.id == layer_id)
        .ok_or_else(|| std::io::Error::other(format!("unknown layer `{layer_id}`")).into())
}

#[derive(Debug, Clone, Serialize)]
struct AuditReport {
    findings: Vec<AuditFinding>,
}

#[derive(Debug, Clone, Serialize)]
struct AuditFinding {
    severity: &'static str,
    code: &'static str,
    layer_id: String,
    message: String,
}

fn build_audit_report(
    cwd: &Path,
    layers: &[PromptLayer],
    requested_skills: &[String],
) -> AuditReport {
    let mut findings = Vec::new();
    let active = active_layers(layers);
    let composed = compose(&active).unwrap_or_default();
    let active_ids: BTreeSet<_> = active.iter().map(|layer| layer.id.as_str()).collect();

    let mut paragraph_map: BTreeMap<String, String> = BTreeMap::new();
    for layer in &active {
        for paragraph in paragraphs(&layer.body) {
            let normalized = normalize(&paragraph);
            if normalized.len() < 24 {
                continue;
            }
            if let Some(first) = paragraph_map.get(&normalized) {
                findings.push(AuditFinding {
                    severity: "warn",
                    code: "duplication",
                    layer_id: layer.id.clone(),
                    message: format!("duplicate paragraph also appears in {first}"),
                });
            } else {
                paragraph_map.insert(normalized, layer.id.clone());
            }
        }
    }

    for layer in &active {
        let tokens = estimated_tokens(&layer.body);
        let limit = if layer.kind == PromptLayerKind::Skill {
            SKILL_WARN_TOKENS
        } else {
            LAYER_WARN_TOKENS
        };
        if tokens > limit {
            findings.push(AuditFinding {
                severity: "warn",
                code: "token_bloat",
                layer_id: layer.id.clone(),
                message: format!("estimated {tokens} tokens exceeds {limit}"),
            });
        }
        for phrase in CADENCE_DENYLIST {
            if normalize(&layer.body).contains(&normalize(phrase)) {
                findings.push(AuditFinding {
                    severity: "warn",
                    code: "cadence",
                    layer_id: layer.id.clone(),
                    message: format!("contains denylisted cadence phrase `{phrase}`"),
                });
            }
        }
    }

    let composed_limit = if requested_skills.is_empty() {
        COMPOSED_WARN_TOKENS
    } else {
        usize::MAX
    };
    let composed_tokens = estimated_tokens(&composed);
    if composed_tokens > composed_limit {
        findings.push(AuditFinding {
            severity: "warn",
            code: "token_bloat",
            layer_id: "compose".to_string(),
            message: format!(
                "estimated composed prompt {composed_tokens} tokens exceeds {COMPOSED_WARN_TOKENS}"
            ),
        });
    }

    let normalized_layers: Vec<_> = active
        .iter()
        .map(|layer| (layer.id.clone(), normalize(&layer.body)))
        .collect();
    for (left, right, message) in CONTRADICTION_RULES {
        let left_hits: Vec<_> = normalized_layers
            .iter()
            .filter(|(_, body)| body.contains(&normalize(left)))
            .map(|(id, _)| id.clone())
            .collect();
        let right_hits: Vec<_> = normalized_layers
            .iter()
            .filter(|(_, body)| body.contains(&normalize(right)))
            .map(|(id, _)| id.clone())
            .collect();
        if !left_hits.is_empty() && !right_hits.is_empty() {
            findings.push(AuditFinding {
                severity: "error",
                code: "contradiction",
                layer_id: format!("{},{}", left_hits.join(","), right_hits.join(",")),
                message: message.to_string(),
            });
        }
    }

    for layer in layers {
        if layer.kind == PromptLayerKind::InstallAsset && layer.id.starts_with("bundled:prompts:") {
            let live_id = layer.id.replacen("bundled:prompts:", "", 1);
            let live_id = if live_id == "base" {
                "base".to_string()
            } else if live_id == "agent0" {
                "agent:root".to_string()
            } else if live_id == "clone" {
                "agent:clone".to_string()
            } else if live_id == "agentinfinity" {
                "agent:watchdog".to_string()
            } else {
                continue;
            };
            if let Some(live) = layers.iter().find(|candidate| candidate.id == live_id)
                && live.body != layer.body
            {
                findings.push(AuditFinding {
                    severity: "error",
                    code: "bundled_drift",
                    layer_id: layer.id.clone(),
                    message: format!("bundled asset drift from live layer {}", live.id),
                });
            }
        }
    }

    let harness_live = [
        ("harness:agents", "AGENTS.md"),
        ("harness:claude", "CLAUDE.md"),
    ];
    for (id, name) in harness_live {
        let bundled_id = format!("bundled:{}", name.trim_end_matches(".md").to_lowercase());
        let live = layers.iter().find(|layer| layer.id == id);
        let bundled = layers.iter().find(|layer| layer.id == bundled_id);
        if let (Some(live), Some(bundled)) = (live, bundled)
            && normalize(&live.body) != normalize(&bundled.body)
        {
            findings.push(AuditFinding {
                severity: "warn",
                code: "harness_mismatch",
                layer_id: id.to_string(),
                message: format!("{name} differs from bundled install asset"),
            });
        }
    }

    let expected = match inferred_addendum_file(agent_kind_from_layers(&active_ids), cwd) {
        Some(path) => path,
        None => cwd.join("0.md"),
    };
    if !expected.exists() && !active_ids.contains("cwd:addendum") {
        findings.push(AuditFinding {
            severity: "warn",
            code: "missing_addendum",
            layer_id: "cwd:addendum".to_string(),
            message: format!("configured addendum missing at {}", expected.display()),
        });
    }

    AuditReport { findings }
}

fn agent_kind_from_layers(active_ids: &BTreeSet<&str>) -> PromptAgentKind {
    if active_ids.contains("agent:watchdog") {
        PromptAgentKind::Agentinfinity
    } else if active_ids.contains("agent:clone") {
        PromptAgentKind::Clone
    } else {
        PromptAgentKind::Agent0
    }
}

fn inferred_addendum_file(kind: PromptAgentKind, cwd: &Path) -> Option<PathBuf> {
    let name = match kind {
        PromptAgentKind::Agent0 => "0.md",
        PromptAgentKind::Clone => return Some(cwd.join("1.md")),
        PromptAgentKind::Agentinfinity => "agentinfinity.md",
    };
    Some(cwd.join(name))
}

fn paragraphs(body: &str) -> Vec<String> {
    body.split("\n\n")
        .map(str::trim)
        .filter(|part| !part.is_empty())
        .map(ToOwned::to_owned)
        .collect()
}

fn normalize(body: &str) -> String {
    body.to_ascii_lowercase()
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
}

fn estimated_tokens(body: &str) -> usize {
    (body.len() * 10).div_ceil(BYTES_PER_TOKEN_X10)
}

#[derive(Clone)]
struct PromptQuery {
    agent: AgentId,
    cwd: PathBuf,
}

impl PromptQuery {
    fn new(agent: Option<&str>, cwd: Option<&Path>) -> netsky_core::Result<Self> {
        let cwd = match cwd {
            Some(path) => path.to_path_buf(),
            None => std::env::current_dir()?,
        };
        let agent = parse_agent(agent)?;
        Ok(Self { agent, cwd })
    }

    fn context(&self) -> PromptContext<AgentId> {
        PromptContext::new(self.agent, self.cwd.display().to_string())
    }
}

fn parse_agent(agent: Option<&str>) -> netsky_core::Result<AgentId> {
    match agent {
        Some("0") | Some("agent0") => Ok(AgentId::Agent0),
        Some("infinity") | Some("agentinfinity") => Ok(AgentId::Agentinfinity),
        Some(raw) => {
            let raw = raw.trim_start_matches("agent");
            let n = raw.parse::<u32>()?;
            Ok(AgentId::from_number(n))
        }
        None => match std::env::var("AGENT_N").ok().as_deref() {
            Some("0") => Ok(AgentId::Agent0),
            Some("infinity") => Ok(AgentId::Agentinfinity),
            Some(raw) => Ok(AgentId::from_number(raw.parse::<u32>()?)),
            None => Ok(AgentId::Agent0),
        },
    }
}

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

    #[test]
    fn detects_exact_duplicate_paragraph() {
        let report = build_audit_report(
            Path::new("."),
            &[
                PromptLayer {
                    id: "base".to_string(),
                    kind: PromptLayerKind::Base,
                    origin: PromptLayerOrigin::LiveFile,
                    path: None,
                    git_path: None,
                    body: "this is a duplicated paragraph with enough words\n\nsecond".to_string(),
                    active: true,
                    note: None,
                },
                PromptLayer {
                    id: "skill:x".to_string(),
                    kind: PromptLayerKind::Skill,
                    origin: PromptLayerOrigin::LiveFile,
                    path: None,
                    git_path: None,
                    body: "this is a duplicated paragraph with enough words".to_string(),
                    active: true,
                    note: None,
                },
            ],
            &[],
        );
        assert!(report.findings.iter().any(|f| f.code == "duplication"));
    }

    #[test]
    fn detects_contradiction_pair() {
        let report = build_audit_report(
            Path::new("."),
            &[
                PromptLayer {
                    id: "base".to_string(),
                    kind: PromptLayerKind::Base,
                    origin: PromptLayerOrigin::LiveFile,
                    path: None,
                    git_path: None,
                    body: "always use clones".to_string(),
                    active: true,
                    note: None,
                },
                PromptLayer {
                    id: "cwd:addendum".to_string(),
                    kind: PromptLayerKind::CwdAddendum,
                    origin: PromptLayerOrigin::LiveFile,
                    path: None,
                    git_path: None,
                    body: "do it inline".to_string(),
                    active: true,
                    note: None,
                },
            ],
            &[],
        );
        assert!(
            report
                .findings
                .iter()
                .any(|f| f.code == "contradiction" && f.severity == "error")
        );
    }
}