ms-ai-architect/scripts/kb-eval/plan-skill-op.mjs
Kjell Tore Guttormsen f7b622b318 feat(ms-ai-architect): Sesjon 17 — B3 sanitize_skill + retire_skill dry-run-planners [skip-docs]
Speiler S16 merge-mønsteret: rene planners (leser ingen disk, anvender
ingenting) + impurt skall med gated --write. 0 skriving til skills/.
Intern kb-eval maintenance-tooling — ingen brukervendt /architect-kommando.

- planSanitizeSkill: fjerner KUN dødt innhold (kb-integrity orphan/dead-path).
  Guardrail refuserer fjerning av kuratert/manglende innhold (illegalRemovals/
  missingRemovals MÅ være tom). Dateless = kuratert, behandles ikke her.
- planRetireSkill: hel-skill m/ obligatorisk arkivering; guardrail refuserer
  hard delete (--hard -> archiveDir=null, ok=false). taxonomyOrphaned flagget.
- loadSkillOrphans (read-only) + runSanitizePlan/runRetirePlan (gated).
- CLI plan-skill-op.mjs utvidet: {sanitize|retire} <skill> [--hard].

Ekte dry-runs: sanitize ms-ai-security 62/33 orphans OK · retire
ms-ai-infrastructure 35 arkivert OK · --hard FAILED (blokkert). git clean.

TDD: test-skill-ops-sanitize-retire.test.mjs (16). kb-eval 50->66.
Baseline uendret: validate 239 · kb-update 132 · kb-integrity 192/192.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 17:45:37 +02:00

160 lines
7.9 KiB
JavaScript

#!/usr/bin/env node
// plan-skill-op.mjs — Spor B / B3 CLI: GATED DRY-RUN for skill-lifecycle ops.
//
// Ships merge_skills (S16) + sanitize_skill + retire_skill (S17). Each dry-run
// loads refs/orphans/taxonomy READ-ONLY, plans the op, prints the full diff +
// guardrail, and with --write records a PENDING entry in decisions.json (the
// operator gate's queue). It NEVER writes under skills/ — the destructive apply
// is a separate approved step. Verify after a run: `git status skills/` clean.
//
// Usage:
// node scripts/kb-eval/plan-skill-op.mjs merge <absorber> <absorbed> [--json] [--write [--date YYYY-MM-DD]]
// node scripts/kb-eval/plan-skill-op.mjs sanitize <skill> [--json] [--write [--date YYYY-MM-DD]]
// node scripts/kb-eval/plan-skill-op.mjs retire <skill> [--hard] [--json] [--write [--date YYYY-MM-DD]]
import { readFileSync, readdirSync, existsSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { splitFrontmatter, extractDescription } from './eval.mjs';
import { loadTaxonomy } from '../kb-update/lib/taxonomy.mjs';
import { runMergePlan, runSanitizePlan, runRetirePlan } from './lib/skill-ops.mjs';
const __dirname = dirname(fileURLToPath(import.meta.url));
const PLUGIN_ROOT = join(__dirname, '..', '..');
const SKILLS_DIR = join(PLUGIN_ROOT, 'skills');
const AGENTS_DIR = join(PLUGIN_ROOT, 'agents');
const LEDGER_DATA_DIR = join(__dirname, '..', 'kb-update', 'data');
const TAX_DATA_DIR = LEDGER_DATA_DIR;
/** Read the SKILL.md descriptions from disk (read-only). */
function loadDescriptions() {
const out = {};
for (const e of readdirSync(SKILLS_DIR, { withFileTypes: true })) {
if (!e.isDirectory()) continue;
const md = join(SKILLS_DIR, e.name, 'SKILL.md');
if (!existsSync(md)) continue;
out[e.name] = extractDescription(splitFrontmatter(readFileSync(md, 'utf8')).frontmatter);
}
return out;
}
function printPlan({ entry, diff, guardrail }) {
const g = guardrail;
console.log(`\nmerge_skills — DRY-RUN: ${entry.targets.absorbed} -> ${entry.targets.absorber}\n`);
console.log(`Guardrail (ingen kuratert verdi tapt):`);
console.log(` absorber-refs=${g.preCountAbsorber} absorbed-refs=${g.preCountAbsorbed} forventet post=${g.expectedPostCount} faktisk post=${g.postCount}`);
console.log(` count-invariant=${g.countInvariant} set-equality=${g.setEquality} kollisjoner=${g.collisions.length ? g.collisions.join(', ') : '0'}`);
console.log(` => ${g.ok ? 'OK (trygt å merge)' : 'FAILED (ville tapt/klobret innhold — blokkert)'}\n`);
console.log(`Diff:`);
console.log(` fil-flytt: ${diff.fileMoves.length} (alle ${entry.targets.absorbed}/references/* -> ${entry.targets.absorber}/references/*)`);
if (diff.taxonomyReassignments.length) {
console.log(` taksonomi-reassign:`);
for (const t of diff.taxonomyReassignments) console.log(`${t.category}: ${t.from} -> ${t.to}`);
}
console.log(` retire: ${diff.retire}`);
console.log(` description-reconciliation: MANUELL (planner auto-merger aldri semantisk scope)`);
console.log(` ${entry.targets.absorber}: ${diff.descriptionReconciliation.absorber?.slice(0, 80) ?? '(mangler)'}`);
console.log(` ${entry.targets.absorbed}: ${diff.descriptionReconciliation.absorbed?.slice(0, 80) ?? '(mangler)'}\n`);
console.log(`Status: ${entry.status} (forslag — anvender INGENTING; krever operatør-godkjenning + apply-sesjon).\n`);
}
function printSanitizePlan({ entry, diff, guardrail }) {
const g = guardrail;
console.log(`\nsanitize_skill — DRY-RUN: ${entry.targets.skill}\n`);
console.log(`Guardrail (kun dødt innhold; aldri kuratert):`);
console.log(` refs=${g.preCount} dead(orphan)=${g.deadCount} fjernes=${g.removalCount} kuratert-beholdt=${g.curatedCount} post=${g.postCount}`);
console.log(` ulovlige-fjerninger(kuratert)=${g.illegalRemovals.length ? g.illegalRemovals.join(', ') : '0'} manglende=${g.missingRemovals.length ? g.missingRemovals.join(', ') : '0'}`);
console.log(` => ${g.ok ? 'OK (trygt å sanere)' : 'FAILED (ville rørt kuratert/manglende innhold — blokkert)'}\n`);
console.log(`Diff — fjernes (${diff.removals.length}):`);
for (const r of diff.removals.slice(0, 20)) console.log(`${r.path}`);
if (diff.removals.length > 20) console.log(` … +${diff.removals.length - 20} til`);
console.log(` beholdt (kuratert): ${diff.retainedCount}\n`);
console.log(`Status: ${entry.status} (forslag — anvender INGENTING; krever operatør-godkjenning + apply-sesjon).\n`);
}
function printRetirePlan({ entry, diff, guardrail }) {
const g = guardrail;
console.log(`\nretire_skill — DRY-RUN: ${entry.targets.skill}\n`);
console.log(`Guardrail (obligatorisk arkivering; aldri hard delete):`);
console.log(` refs=${g.refCount} forventet-arkivert=${g.expectedArchiveCount} (refs + SKILL.md) faktisk-arkivert=${g.archivedCount}`);
console.log(` arkiv-mål=${g.archiveDir ?? '(ingen)'} hard-delete-bedt=${g.hardDeleteRequested}`);
console.log(` => ${g.ok ? 'OK (arkivert — trygt å pensjonere)' : 'FAILED (hard delete uten arkiv — blokkert)'}\n`);
console.log(`Diff:`);
console.log(` arkiv-flytt: ${diff.archiveMoves.length} (alle skills/${entry.targets.skill}/* -> ${g.archiveDir}/*)`);
console.log(` fjern katalog: ${diff.removeSkillDir}`);
if (diff.taxonomyOrphaned.length) {
console.log(` taksonomi forelder-løs (manuell reassign):`);
for (const t of diff.taxonomyOrphaned) console.log(`${t.category} (var eid av ${t.wasOwner})`);
}
console.log(`\nStatus: ${entry.status} (forslag — anvender INGENTING; krever operatør-godkjenning + apply-sesjon).\n`);
}
const USAGE =
'Usage:\n' +
' node scripts/kb-eval/plan-skill-op.mjs merge <absorber> <absorbed> [--json] [--write [--date YYYY-MM-DD]]\n' +
' node scripts/kb-eval/plan-skill-op.mjs sanitize <skill> [--json] [--write [--date YYYY-MM-DD]]\n' +
' node scripts/kb-eval/plan-skill-op.mjs retire <skill> [--hard] [--json] [--write [--date YYYY-MM-DD]]';
function main() {
const args = process.argv.slice(2);
const op = args[0];
const positional = args.filter((a) => !a.startsWith('--'));
const jsonOut = args.includes('--json');
const doWrite = args.includes('--write');
const hardDelete = args.includes('--hard');
const dateIdx = args.indexOf('--date');
const decided_at = doWrite ? (dateIdx >= 0 ? args[dateIdx + 1] : new Date().toISOString().slice(0, 10)) : null;
let result;
let printer;
let label;
if (op === 'merge' && positional.length >= 3) {
const [, absorber, absorbed] = positional;
result = runMergePlan(absorber, absorbed, {
skillsDir: SKILLS_DIR,
dataDir: LEDGER_DATA_DIR,
write: doWrite,
decided_at,
descriptions: loadDescriptions(),
categorySkill: loadTaxonomy(TAX_DATA_DIR).category_skill,
});
printer = printPlan;
label = 'merge_skills';
} else if (op === 'sanitize' && positional.length >= 2) {
result = runSanitizePlan(positional[1], {
skillsDir: SKILLS_DIR,
agentsDir: AGENTS_DIR,
dataDir: LEDGER_DATA_DIR,
write: doWrite,
decided_at,
});
printer = printSanitizePlan;
label = 'sanitize_skill';
} else if (op === 'retire' && positional.length >= 2) {
result = runRetirePlan(positional[1], {
skillsDir: SKILLS_DIR,
dataDir: LEDGER_DATA_DIR,
write: doWrite,
decided_at,
hardDelete,
categorySkill: loadTaxonomy(TAX_DATA_DIR).category_skill,
});
printer = printRetirePlan;
label = 'retire_skill';
} else {
console.error(USAGE);
process.exit(2);
}
if (jsonOut) {
process.stdout.write(JSON.stringify(result) + '\n');
return;
}
printer(result);
if (doWrite) console.log(`(Pending ${label}-entry skrevet til decisions.json — 0 skriving til skills/.)\n`);
}
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
main();
}