ms-ai-architect/scripts/kb-eval/apply-skill-op.mjs
Kjell Tore Guttormsen 4ac18a76c8 feat(ms-ai-architect): Sesjon 18 — B3 apply-path (sanitize+retire), merge→S19 [skip-docs]
Apply-path = den destruktive frontieren: eksekver en operatør-godkjent
(status:approved) ledger-entry → faktisk skills/-mutasjon. Staget per
operatør-beslutning til single-skill ops (sanitize+retire); merge-apply
isoleres til S19 (krever taksonomi-persistering + cross-skill flytt).

- revalidateApply (ren, skill-ops.mjs): idempotent revalidering mot fersk
  re-plan — nekter ved status≠approved, op-mismatch, fersk guardrail≠ok,
  eller drift (isDeepStrictEqual fresh vs approved guardrail-snapshot).
- applyApprovedAction (impur): arkiver-så-slett (rename skills/…→archive/…
  atomisk; retire rmdir'er tom katalog sist) + flipp ledger approved→applied.
  apply:false = preview (0 mutasjon). merge_skills → throw (S19).
- setActionStatus (ren, decisions-io.mjs): ledger status-transisjon, bevarer
  targets+guardrail, audit-record beholdes.
- CLI apply-skill-op.mjs {list|sanitize|retire} — default PREVIEW, --apply =
  dobbel-gate utover ledger-approved.

TDD, tmpdir-fixtures: 0 ekte skills/-mutasjon. Tester: kb-eval 66→78,
kb-update 132→137; validate 239 · kb-integrity 192/192 uendret.

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

123 lines
5.4 KiB
JavaScript

#!/usr/bin/env node
// apply-skill-op.mjs — Spor B / B3 (Sesjon 18) CLI: the DESTRUCTIVE apply-path.
//
// Executes an operator-APPROVED (status:approved) skill-lifecycle entry from
// decisions.json into a real skills/ mutation. Single-skill ops only this
// session: sanitize_skill + retire_skill (merge_skills is staged to S19).
//
// Two gates, in order: (1) the entry must already be status:approved in the
// ledger (the operator's sign-off on a prior `plan-skill-op … --write` dry-run);
// (2) this CLI mutates skills/ ONLY with --apply. Without --apply it is a PREVIEW
// that re-plans from fresh disk, revalidates (drift-safe), and mutates nothing.
//
// Apply archives every file under archive/ BEFORE removing it, then flips the
// ledger entry approved -> applied. Verify before/after: `git status`.
//
// Usage:
// node scripts/kb-eval/apply-skill-op.mjs list
// node scripts/kb-eval/apply-skill-op.mjs sanitize <skill> [--apply] [--date YYYY-MM-DD]
// node scripts/kb-eval/apply-skill-op.mjs retire <skill> [--apply] [--date YYYY-MM-DD]
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { loadTaxonomy } from '../kb-update/lib/taxonomy.mjs';
import { loadDecisions, listActions, actionKey } from '../kb-update/lib/decisions-io.mjs';
import { applyApprovedAction, SANITIZE_OPERATION, RETIRE_OPERATION } 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 OP_BY_VERB = { sanitize: SANITIZE_OPERATION, retire: RETIRE_OPERATION };
const USAGE =
'Usage:\n' +
' node scripts/kb-eval/apply-skill-op.mjs list\n' +
' node scripts/kb-eval/apply-skill-op.mjs sanitize <skill> [--apply] [--date YYYY-MM-DD]\n' +
' node scripts/kb-eval/apply-skill-op.mjs retire <skill> [--apply] [--date YYYY-MM-DD]';
/** List approved actions awaiting apply (operator's apply queue). */
function listApproved() {
const led = loadDecisions(LEDGER_DATA_DIR);
const approved = listActions(led, 'approved');
const applied = listActions(led, 'applied');
console.log(`\nGodkjente handlinger som venter på apply (${approved.length}):`);
if (!approved.length) console.log(' (ingen — kjør plan-skill-op … --write og sett status:approved i decisions.json)');
for (const a of approved) {
const t = a.targets ?? {};
const tgt = t.skill ?? `${t.absorbed} -> ${t.absorber}`;
console.log(`${a.operation_type}: ${tgt} [guardrail ${a.guardrail?.ok ? 'OK' : 'FAILED'}]`);
}
if (applied.length) console.log(`\nAllerede anvendt (${applied.length}): ${applied.map((a) => actionKey(a)).join(', ')}`);
console.log('');
}
function printResult(res, verb, skill, apply) {
const r = res.revalidate;
console.log(`\n${verb}_skill — ${apply ? 'APPLY' : 'PREVIEW'}: ${skill}\n`);
console.log(`Revalidering (mot fersk disk):`);
console.log(` fersk-guardrail-ok=${r.freshOk} drift=${r.drift} => ${r.ok ? 'OK' : 'BLOKKERT'}`);
if (r.reason) console.log(` grunn: ${r.reason}`);
if (!res.applied) {
if (res.preview && r.ok) {
const d = res.plan?.diff ?? {};
const n = verb === 'sanitize' ? (d.removals?.length ?? 0) : (d.archiveMoves?.length ?? 0);
console.log(`\n Ville arkivert+fjernet ${n} fil(er). Kjør på nytt med --apply for å eksekvere.`);
}
console.log(`\nStatus: INGEN mutasjon utført.${res.preview && r.ok ? '' : ' (revalidering blokkerte eller ingen --apply.)'}\n`);
return;
}
const rep = res.report;
console.log(`\nUtført:`);
console.log(` arkivert: ${rep.moves} fil(er) -> archive/`);
if (rep.removedDir) console.log(` fjernet katalog: ${rep.removedDir}`);
console.log(` ledger: ${actionKey({ operation_type: rep.op, targets: rep.target })} -> ${rep.ledgerStatus}`);
console.log(`\nStatus: APPLIED. Verifiser med 'git status' og re-kjør validate/kb-integrity/kb-eval.\n`);
}
function main() {
const args = process.argv.slice(2);
const verb = args[0];
if (verb === 'list') return listApproved();
const positional = args.filter((a) => !a.startsWith('--'));
const apply = args.includes('--apply');
const dateIdx = args.indexOf('--date');
const decided_at = dateIdx >= 0 ? args[dateIdx + 1] : new Date().toISOString().slice(0, 10);
const op = OP_BY_VERB[verb];
if (!op || positional.length < 2) {
console.error(USAGE);
process.exit(2);
}
const skill = positional[1];
const led = loadDecisions(LEDGER_DATA_DIR);
const key = `${op}:${skill}`;
const entry = led.actions?.[key];
if (!entry) {
console.error(`Fant ingen ledger-handling "${key}". Kjør 'apply-skill-op.mjs list' for å se godkjente.`);
process.exit(1);
}
if (entry.status !== 'approved') {
console.error(`Handling "${key}" har status "${entry.status}" (må være "approved"). Avbryter.`);
process.exit(1);
}
const res = applyApprovedAction(entry, {
pluginRoot: PLUGIN_ROOT,
skillsDir: SKILLS_DIR,
agentsDir: AGENTS_DIR,
dataDir: LEDGER_DATA_DIR,
apply,
decided_at: apply ? decided_at : null,
categorySkill: op === RETIRE_OPERATION ? loadTaxonomy(LEDGER_DATA_DIR).category_skill : undefined,
});
printResult(res, verb, skill, apply);
}
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
main();
}