skillnet 0.6.0

Manage canonical AI skill stores, derived views, and calibration data for multi-phase-plan.
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
use std::collections::{BTreeMap, BTreeSet};

use super::{inputs::PlanInputs, outcome::TriggerOutcome};

#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum HeuristicCategory {
    Coordination,
    Risk,
    PlanShape,
    QualityLint,
}

impl HeuristicCategory {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Coordination => "coordination",
            Self::Risk => "risk",
            Self::PlanShape => "plan-shape",
            Self::QualityLint => "quality-lint",
        }
    }
}

pub trait Heuristic: Send + Sync {
    fn name(&self) -> &'static str;
    fn category(&self) -> HeuristicCategory;
    fn default_threshold(&self) -> f64;
    fn description(&self) -> &'static str;
    fn section_added(&self, fired: bool) -> Option<&'static str>;
    fn evaluate(&self, plan: &PlanInputs, threshold: f64) -> TriggerOutcome;
}

pub struct Catalog;

impl Catalog {
    pub fn get(&self, name: &str) -> Option<&'static dyn Heuristic> {
        HEURISTICS
            .iter()
            .copied()
            .find(|heuristic| heuristic.name() == name)
    }

    pub fn by_category(
        &self,
        category: HeuristicCategory,
    ) -> impl Iterator<Item = &'static dyn Heuristic> {
        HEURISTICS
            .iter()
            .copied()
            .filter(move |heuristic| heuristic.category() == category)
    }

    pub fn iter(&self) -> impl Iterator<Item = &'static dyn Heuristic> {
        HEURISTICS.iter().copied()
    }
}

pub static CATALOG: Catalog = Catalog;

pub static HEURISTICS: &[&dyn Heuristic] = &[
    &SharedFileContention,
    &ExternalRepoPhases,
    &ConvergencePoint,
    &OwnershipBoundarySpread,
    &RiskConcentration,
    &RiskLateInPlan,
    &InfrastructureSpof,
    &RevendorPhase,
    &LongSerialChain,
    &MidPlanRerouting,
    &TrivialPhaseSwamp,
    &NoIntegratedVerification,
    &RoutingTierInversion,
    &MechanicalStreak,
    &HiddenPrerequisite,
];

macro_rules! outcome {
    ($heuristic:expr, $input:expr, $threshold:expr) => {{
        let input_value = $input;
        let threshold = $threshold;
        let fired = input_value >= threshold;
        TriggerOutcome {
            input_value,
            threshold,
            fired,
            section_added: $heuristic.section_added(fired).map(str::to_string),
        }
    }};
}

macro_rules! heuristic {
    ($type:ident, $name:literal, $category:ident, $threshold:literal, $description:literal, $section:expr, $eval:expr) => {
        pub struct $type;

        impl Heuristic for $type {
            fn name(&self) -> &'static str {
                $name
            }

            fn category(&self) -> HeuristicCategory {
                HeuristicCategory::$category
            }

            fn default_threshold(&self) -> f64 {
                $threshold
            }

            fn description(&self) -> &'static str {
                $description
            }

            fn section_added(&self, fired: bool) -> Option<&'static str> {
                fired.then_some($section).flatten()
            }

            fn evaluate(&self, plan: &PlanInputs, threshold: f64) -> TriggerOutcome {
                outcome!(self, $eval(plan), threshold)
            }
        }
    };
}

heuristic!(
    SharedFileContention,
    "shared-file-contention",
    Coordination,
    2.0,
    "Two or more phases touch the same file.",
    Some("Shared-file lockstep"),
    shared_file_contention
);

heuristic!(
    ExternalRepoPhases,
    "external-repo-phases",
    Coordination,
    1.0,
    "At least one phase works outside the primary working tree.",
    Some("External repo coordination"),
    external_repo_phases
);

heuristic!(
    ConvergencePoint,
    "convergence-point",
    Coordination,
    3.0,
    "A phase has three or more direct predecessors.",
    Some("Merge-readiness checklist"),
    convergence_point
);

heuristic!(
    OwnershipBoundarySpread,
    "ownership-boundary-spread",
    Coordination,
    2.0,
    "Phases span multiple repository or maintainer boundaries.",
    Some("PR sequencing & cross-owner coordination"),
    ownership_boundary_spread
);

heuristic!(
    RiskConcentration,
    "risk-concentration",
    Risk,
    2.0,
    "Two or more phases are routed to max.",
    Some("Risk-tier callout"),
    risk_concentration
);

heuristic!(
    RiskLateInPlan,
    "risk-late-in-plan",
    Risk,
    1.0,
    "A max-risk phase sits in the final third of waves.",
    Some("Late-risk warning"),
    risk_late_in_plan
);

heuristic!(
    InfrastructureSpof,
    "infrastructure-spof",
    Risk,
    1.0,
    "An infrastructure phase has downstream dependents.",
    Some("infra-SPOF"),
    infrastructure_spof
);

heuristic!(
    RevendorPhase,
    "revendor-phase",
    Risk,
    1.0,
    "A phase touches vendoring, dependency bumps, or lockfiles.",
    Some("Compat surface"),
    revendor_phase
);

heuristic!(
    LongSerialChain,
    "long-serial-chain",
    PlanShape,
    4.0,
    "The dependency chain is at least four phases deep.",
    Some("Serial-chain recovery"),
    long_serial_chain
);

heuristic!(
    MidPlanRerouting,
    "mid-plan-rerouting",
    PlanShape,
    10.0,
    "The plan has ten or more phases.",
    Some("Mid-plan re-routing checkpoint"),
    mid_plan_rerouting
);

heuristic!(
    TrivialPhaseSwamp,
    "trivial-phase-swamp",
    PlanShape,
    4.0,
    "Low/medium phases outnumber high/max phases by at least four to one.",
    Some("Cleanup batch"),
    trivial_phase_swamp
);

heuristic!(
    NoIntegratedVerification,
    "no-integrated-verification",
    PlanShape,
    1.0,
    "No phase appears to exercise the end-to-end outcome.",
    None,
    no_integrated_verification
);

heuristic!(
    RoutingTierInversion,
    "routing-tier-inversion",
    QualityLint,
    1.0,
    "A leaf phase routes at least as high as the plan orchestrator.",
    None,
    routing_tier_inversion
);

heuristic!(
    MechanicalStreak,
    "mechanical-streak",
    QualityLint,
    3.0,
    "Three or more consecutive phases are routed low.",
    None,
    mechanical_streak
);

heuristic!(
    HiddenPrerequisite,
    "hidden-prerequisite",
    QualityLint,
    1.0,
    "A phase has an invalid or implicit prerequisite edge.",
    None,
    hidden_prerequisite
);

fn shared_file_contention(plan: &PlanInputs) -> f64 {
    let mut counts: BTreeMap<&str, u32> = BTreeMap::new();
    for phase in &plan.phases {
        for file in &phase.files {
            *counts.entry(file.as_str()).or_default() += 1;
        }
    }
    counts.values().copied().max().unwrap_or(0).into()
}

fn external_repo_phases(plan: &PlanInputs) -> f64 {
    plan.phases
        .iter()
        .filter(|phase| phase.working_tree.is_some())
        .count() as f64
}

fn convergence_point(plan: &PlanInputs) -> f64 {
    plan.phases
        .iter()
        .map(|phase| phase.depends_on.len())
        .max()
        .unwrap_or(0) as f64
}

fn ownership_boundary_spread(plan: &PlanInputs) -> f64 {
    let mut working_trees = plan
        .phases
        .iter()
        .filter_map(|phase| phase.working_tree.as_deref())
        .collect::<BTreeSet<_>>();
    if plan.repo_spread > 0 {
        f64::from(plan.repo_spread)
    } else if working_trees.is_empty() {
        1.0
    } else {
        working_trees.insert("primary");
        working_trees.len() as f64
    }
}

fn risk_concentration(plan: &PlanInputs) -> f64 {
    f64::from(plan.routing_dist.get("max").copied().unwrap_or(0))
}

fn risk_late_in_plan(plan: &PlanInputs) -> f64 {
    if plan.waves.is_empty() {
        return 0.0;
    }

    let first_late_wave = (plan.waves.len() * 2) / 3;
    let max_phase_ordinals = plan
        .phases
        .iter()
        .filter(|phase| phase.routing_tier == "max")
        .map(|phase| phase.ordinal)
        .collect::<BTreeSet<_>>();
    plan.waves
        .iter()
        .enumerate()
        .filter(|(index, wave)| {
            *index >= first_late_wave
                && wave
                    .iter()
                    .any(|ordinal| max_phase_ordinals.contains(ordinal))
        })
        .count() as f64
}

fn infrastructure_spof(plan: &PlanInputs) -> f64 {
    let infra_ordinals = plan
        .phases
        .iter()
        .filter(|phase| phase.files.iter().any(|file| is_infra_file(file)))
        .map(|phase| phase.ordinal)
        .collect::<BTreeSet<_>>();
    if infra_ordinals.is_empty() {
        return 0.0;
    }
    plan.phases
        .iter()
        .filter(|phase| {
            phase
                .depends_on
                .iter()
                .any(|ordinal| infra_ordinals.contains(ordinal))
        })
        .count() as f64
}

fn revendor_phase(plan: &PlanInputs) -> f64 {
    plan.phases
        .iter()
        .filter(|phase| {
            let slug = phase.slug.to_ascii_lowercase();
            mentions_dependency_surface(&slug)
                || phase
                    .files
                    .iter()
                    .any(|file| mentions_dependency_surface(&file.to_ascii_lowercase()))
        })
        .count() as f64
}

fn long_serial_chain(plan: &PlanInputs) -> f64 {
    f64::from(plan.max_chain_depth)
}

fn mid_plan_rerouting(plan: &PlanInputs) -> f64 {
    f64::from(plan.phase_count)
}

fn trivial_phase_swamp(plan: &PlanInputs) -> f64 {
    let trivial = plan.routing_dist.get("low").copied().unwrap_or(0)
        + plan.routing_dist.get("medium").copied().unwrap_or(0);
    let non_trivial = plan.routing_dist.get("high").copied().unwrap_or(0)
        + plan.routing_dist.get("max").copied().unwrap_or(0);
    if non_trivial == 0 {
        f64::from(trivial)
    } else {
        f64::from(trivial) / f64::from(non_trivial)
    }
}

fn no_integrated_verification(plan: &PlanInputs) -> f64 {
    if plan.phases.iter().any(looks_like_integrated_verification) {
        0.0
    } else {
        1.0
    }
}

fn routing_tier_inversion(plan: &PlanInputs) -> f64 {
    let orchestrator_rank = plan
        .routing_dist
        .iter()
        .filter(|(_, count)| **count > 0)
        .map(|(tier, _)| tier_rank(tier))
        .max()
        .unwrap_or(0);
    plan.phases
        .iter()
        .filter(|phase| {
            let is_leaf = !plan
                .phases
                .iter()
                .any(|candidate| candidate.depends_on.contains(&phase.ordinal));
            is_leaf && tier_rank(&phase.routing_tier) >= orchestrator_rank && orchestrator_rank > 0
        })
        .count() as f64
}

fn mechanical_streak(plan: &PlanInputs) -> f64 {
    let mut longest = 0_u32;
    let mut current = 0_u32;
    let mut phases = plan.phases.iter().collect::<Vec<_>>();
    phases.sort_by_key(|phase| phase.ordinal);
    for phase in phases {
        if phase.routing_tier == "low" {
            current += 1;
            longest = longest.max(current);
        } else {
            current = 0;
        }
    }
    f64::from(longest)
}

fn hidden_prerequisite(plan: &PlanInputs) -> f64 {
    let ordinals = plan
        .phases
        .iter()
        .map(|phase| phase.ordinal)
        .collect::<BTreeSet<_>>();
    plan.phases
        .iter()
        .flat_map(|phase| &phase.depends_on)
        .filter(|ordinal| !ordinals.contains(ordinal))
        .count() as f64
}

fn is_infra_file(file: &str) -> bool {
    let file = file.to_ascii_lowercase();
    file.contains(".github/workflows/")
        || file.contains(".forgejo/workflows/")
        || file.contains("/ci/")
        || file.ends_with("flake.nix")
        || file.ends_with("flake.lock")
        || file.ends_with("cargo.lock")
        || file.ends_with("package-lock.json")
        || file.ends_with("pnpm-lock.yaml")
        || file.ends_with("yarn.lock")
        || file.contains("build.rs")
        || file.contains("justfile")
        || file.contains("makefile")
}

fn mentions_dependency_surface(value: &str) -> bool {
    value.contains("vendor")
        || value.contains("vendoring")
        || value.contains("bump")
        || value.contains("dependency")
        || value.contains("dependencies")
        || value.contains("lockfile")
        || value.ends_with("cargo.lock")
        || value.ends_with("flake.lock")
        || value.ends_with("package-lock.json")
        || value.ends_with("pnpm-lock.yaml")
        || value.ends_with("yarn.lock")
}

fn looks_like_integrated_verification(phase: &super::inputs::PhaseInputs) -> bool {
    let slug = phase.slug.to_ascii_lowercase();
    slug.contains("verify")
        || slug.contains("verification")
        || slug.contains("e2e")
        || slug.contains("end-to-end")
        || slug.contains("integration")
        || phase.files.iter().any(|file| {
            let file = file.to_ascii_lowercase();
            file.contains("e2e") || file.contains("integration") || file.contains("smoke")
        })
}

fn tier_rank(tier: &str) -> u8 {
    match tier {
        "low" | "5.5 low" => 1,
        "medium" | "5.5 medium" => 2,
        "high" | "5.5 high" => 3,
        "max" | "5.5 max" => 4,
        _ => 0,
    }
}