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>
This commit is contained in:
Kjell Tore Guttormsen 2026-06-20 20:32:51 +02:00
commit 4ac18a76c8
5 changed files with 603 additions and 2 deletions

View file

@ -12,12 +12,15 @@
// preserved (ref-file count-invariant + set-equality) and refuse (ok=false)
// when two reference files would clobber on the same target path.
import { readdirSync, readFileSync, existsSync, statSync } from 'node:fs';
import { join, relative, basename, sep } from 'node:path';
import { readdirSync, readFileSync, existsSync, statSync, mkdirSync, renameSync, rmSync } from 'node:fs';
import { join, relative, basename, dirname, sep } from 'node:path';
import { isDeepStrictEqual } from 'node:util';
import {
loadDecisions,
saveDecisions,
recordAction,
actionKey,
setActionStatus,
} from '../../kb-update/lib/decisions-io.mjs';
export const MERGE_OPERATION = 'merge_skills';
@ -393,3 +396,107 @@ export function runRetirePlan(skill, opts) {
}
return result;
}
// ===========================================================================
// Apply-path (Sesjon 18) — the DESTRUCTIVE frontier. An operator-approved
// ledger entry is executed into a real skills/ mutation. Single-skill ops only
// (sanitize/retire); merge-apply is staged to S19 (needs taxonomy persistence).
//
// Invariants:
// - Idempotent revalidation: re-plan from FRESH disk and refuse unless the
// fresh guardrail is ok AND deep-equals the approved snapshot (no drift).
// - Archive BEFORE delete: every removal is a rename skills/… -> archive/…,
// which moves (archives) and removes atomically; retire then rmdir's the
// emptied skill directory last.
// ===========================================================================
/**
* Pure: re-check an operator-approved entry against a FRESH re-plan. Refuses if
* the entry is not approved, the op-type differs, the fresh guardrail is not ok,
* or the fresh guardrail differs from the approved snapshot (disk drifted since
* approval). Reads no disk the caller supplies the fresh plan.
* @param {object} approvedEntry the ledger entry (status must be 'approved')
* @param {{ entry: object, guardrail: object }} freshResult output of a fresh re-plan
* @returns {{ ok: boolean, drift: boolean, freshOk: boolean, reason: string|null }}
*/
export function revalidateApply(approvedEntry, freshResult) {
const reasons = [];
const status = approvedEntry?.status;
if (status !== 'approved') reasons.push(`entry status "${status}" is not "approved"`);
const op = approvedEntry?.operation_type;
const freshOp = freshResult?.entry?.operation_type;
if (op !== freshOp) reasons.push(`operation_type mismatch (approved=${op}, fresh=${freshOp})`);
const freshOk = freshResult?.guardrail?.ok === true;
if (!freshOk) reasons.push('fresh guardrail not ok — applying would lose or clobber content');
const drift = !isDeepStrictEqual(approvedEntry?.guardrail, freshResult?.guardrail);
if (drift) reasons.push('disk drifted since approval (fresh guardrail differs from approved snapshot)');
return { ok: reasons.length === 0, drift, freshOk, reason: reasons.length ? reasons.join('; ') : null };
}
/** Archive a single file: mkdir -p the destination dir, then rename (atomic move). */
function archiveMove(absFrom, absTo) {
mkdirSync(dirname(absTo), { recursive: true });
renameSync(absFrom, absTo);
}
/**
* Execute an operator-approved single-skill op into a real skills/ mutation.
* Re-plans from fresh disk, revalidates (drift-safe), and only with apply:true
* performs the move(s) archiving every file under archive/ BEFORE removing it,
* then (retire) removing the emptied skill dir. On success the ledger entry is
* flipped approved -> applied. apply:false is a preview that mutates nothing.
*
* @param {object} approvedEntry ledger entry with status:'approved'
* @param {{ pluginRoot: string, skillsDir: string, agentsDir?: string, dataDir: string,
* apply?: boolean, decided_at?: string|null, categorySkill?: Record<string,string> }} opts
* @returns {{ applied: boolean, preview?: boolean, revalidate: object, plan?: object, report?: object }}
*/
export function applyApprovedAction(approvedEntry, opts) {
const { pluginRoot, skillsDir, agentsDir, dataDir, apply = false, decided_at = null, categorySkill } = opts;
const op = approvedEntry?.operation_type;
const target = approvedEntry?.targets ?? {};
// 1. Re-plan from fresh disk (read-only) for the supported single-skill ops.
let fresh;
if (op === SANITIZE_OPERATION) {
fresh = runSanitizePlan(target.skill, { skillsDir, agentsDir, dataDir, write: false });
} else if (op === RETIRE_OPERATION) {
fresh = runRetirePlan(target.skill, { skillsDir, dataDir, write: false, categorySkill });
} else {
throw new Error(`applyApprovedAction: unsupported operation_type "${op}" — S18 applies sanitize/retire only (merge staged to S19)`);
}
// 2. Idempotent revalidation against fresh disk — refuse on any failure.
const revalidate = revalidateApply(approvedEntry, fresh);
if (!revalidate.ok || !apply) {
return { applied: false, preview: !apply, revalidate, plan: fresh };
}
// 3. Build the move list (archive destination = archive/ + repo-relative path).
const moves =
op === SANITIZE_OPERATION
? fresh.diff.removals.map((r) => ({ from: r.path, to: join('archive', r.path) }))
: fresh.diff.archiveMoves.map((m) => ({ from: m.from, to: m.to }));
// 4. Execute: archive (rename) every file FIRST, then (retire) drop the dir.
const archived = [];
for (const m of moves) {
archiveMove(join(pluginRoot, m.from), join(pluginRoot, m.to));
archived.push(m.to);
}
let removedDir = null;
if (op === RETIRE_OPERATION) {
removedDir = fresh.diff.removeSkillDir;
rmSync(join(pluginRoot, removedDir), { recursive: true, force: true });
}
// 5. Flip the ledger entry approved -> applied (gated write; audit record kept).
const key = actionKey(approvedEntry);
saveDecisions(setActionStatus(loadDecisions(dataDir), key, 'applied', decided_at), dataDir);
return {
applied: true,
revalidate,
report: { op, target, moves: moves.length, archived, removedDir, ledgerStatus: 'applied' },
};
}