feat(ms-ai-architect): Sesjon 19 — B3 merge-apply (cross-skill + taksonomi-persist) [skip-docs]

Merge-apply = den tyngste destruktive op-en: eksekver en operatør-godkjent
merge_skills-entry → faktisk cross-skill skills/-mutasjon. Tre mekanismer
som sanitize/retire ikke trengte: kuratert relokasjon (ikke arkiv),
taksonomi-persistering, retire-av-absorbert.

- taxonomy.mjs (ny persist): saveTaxonomy (atomisk .tmp+rename, speiler
  saveDecisions) + ren applyCategoryReassignments (repointer KUN der eier
  === from; absent/allerede-flyttet = no-op). Lag-0 er normalt read-only;
  ENESTE writer = gated merge-apply.
- applyApprovedAction merge-gren (skill-ops.mjs): re-plan fersk → revalidér
  (kollisjon → guardrail.ok=false → abort) → flytt absorbed-refs → absorber
  (moveFile; flyttingen ER bevaringen set-equality beviser) → persister
  taksonomi-repoint fra FERSK plan (drift-sikker) → arkivér absorbed-SKILL.md
  FØR rmdir → flipp ledger approved→applied. Description-forsoning forblir
  MANUELL (planner-kontrakt: apply rører aldri absorber-SKILL.md).
  archiveMove→moveFile (generisk: arkiv + kuratert flytt).
- CLI apply-skill-op.mjs merge <absorber> <absorbed> — lookup via actionKey
  (merge_skills:<sortert par>); default PREVIEW, --apply = dobbel-gate.

TDD, tmpdir-fixtures: 0 ekte skills/-mutasjon. Ny test-skill-ops-merge-apply
(7) + 2 taksonomi-tester; fjernet foreldet merge-throws fra S18-fila. Tester:
kb-eval 78→84, kb-update 137→139; validate 239 · kb-integrity 192/192 uendret.
eval --json deterministisk uendret (K10 eng+infra FAIL, øvrige PASS).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Kjell Tore Guttormsen 2026-06-20 20:54:13 +02:00
commit de3a9a483b
6 changed files with 434 additions and 55 deletions

View file

@ -22,6 +22,7 @@ import {
actionKey,
setActionStatus,
} from '../../kb-update/lib/decisions-io.mjs';
import { loadTaxonomy, saveTaxonomy, applyCategoryReassignments } from '../../kb-update/lib/taxonomy.mjs';
export const MERGE_OPERATION = 'merge_skills';
export const SANITIZE_OPERATION = 'sanitize_skill';
@ -398,16 +399,23 @@ export function runRetirePlan(skill, opts) {
}
// ===========================================================================
// 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).
// Apply-path (Sesjon 1819) — the DESTRUCTIVE frontier. An operator-approved
// ledger entry is executed into a real skills/ mutation. Single-skill ops
// (sanitize/retire) shipped in S18; merge-apply (cross-skill, the heaviest op)
// in S19. create_skill (dvelende) comes last.
//
// 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
// - Archive BEFORE delete: a removal is a rename skills/… -> archive/…, which
// moves (archives) and removes atomically; retire/merge then rmdir the
// emptied skill directory last.
// - Merge preserves curated value by RELOCATION, not archival: the absorbed
// skill's references move under the absorber (the guardrail's set-equality
// made real on disk), the taxonomy's category ownership is repointed +
// persisted, and only the now-empty absorbed shell (SKILL.md) is archived.
// Description reconciliation stays MANUAL (planner contract): merge-apply
// never edits the absorber's SKILL.md.
// ===========================================================================
/**
@ -433,37 +441,48 @@ export function revalidateApply(approvedEntry, freshResult) {
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) {
/** Move a single file: mkdir -p the destination dir, then rename (atomic). Used
* both for archival (skills/ -> archive/) and curated relocation (merge). */
function moveFile(absFrom, absTo) {
mkdirSync(dirname(absTo), { recursive: true });
renameSync(absFrom, absTo);
}
/**
* Execute an operator-approved single-skill op into a real skills/ mutation.
* Execute an operator-approved skill-lifecycle 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
* mutates. Single-skill ops (sanitize/retire) archive every file under archive/
* BEFORE removing it, then (retire) drop the emptied skill dir. merge_skills
* RELOCATES the absorbed skill's references under the absorber (preservation),
* persists the taxonomy's category-ownership reassignment, then archives the
* absorbed shell (SKILL.md) + removes its 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
* taxonomyDataDir?: string, apply?: boolean, decided_at?: string|null,
* categorySkill?: Record<string,string> }} opts
* taxonomyDataDir where domain-taxonomy.json lives (merge persist); defaults to dataDir.
* @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 {
pluginRoot, skillsDir, agentsDir, dataDir, taxonomyDataDir,
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.
// 1. Re-plan from fresh disk (read-only) for the supported 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 if (op === MERGE_OPERATION) {
fresh = runMergePlan(target.absorber, target.absorbed, { skillsDir, dataDir, write: false, categorySkill });
} else {
throw new Error(`applyApprovedAction: unsupported operation_type "${op}" — S18 applies sanitize/retire only (merge staged to S19)`);
throw new Error(`applyApprovedAction: unsupported operation_type "${op}" — applies sanitize/retire/merge only (create_skill staged later)`);
}
// 2. Idempotent revalidation against fresh disk — refuse on any failure.
@ -472,16 +491,52 @@ export function applyApprovedAction(approvedEntry, opts) {
return { applied: false, preview: !apply, revalidate, plan: fresh };
}
// 3. Build the move list (archive destination = archive/ + repo-relative path).
// 3a. merge — curated RELOCATION (not archival) + taxonomy persist + shell archive.
if (op === MERGE_OPERATION) {
const { absorber, absorbed } = target;
// Relocate every absorbed reference under the absorber — the move IS the
// preservation the guardrail's set-equality proved.
for (const m of fresh.diff.fileMoves) moveFile(join(pluginRoot, m.from), join(pluginRoot, m.to));
// Persist taxonomy ownership repoint (absorbed -> absorber). Reassignments
// come from the FRESH plan, so this stays drift-safe by construction.
const taxDir = taxonomyDataDir ?? dataDir;
const reassignments = fresh.diff.taxonomyReassignments;
if (reassignments.length) {
saveTaxonomy(applyCategoryReassignments(loadTaxonomy(taxDir), reassignments), taxDir);
}
// Archive the now-empty absorbed shell (SKILL.md) BEFORE removing its dir.
let archivedSkillMd = null;
if (existsSync(join(pluginRoot, `skills/${absorbed}/SKILL.md`))) {
archivedSkillMd = `archive/skills/${absorbed}/SKILL.md`;
moveFile(join(pluginRoot, `skills/${absorbed}/SKILL.md`), join(pluginRoot, archivedSkillMd));
}
const removedDir = `skills/${absorbed}`;
rmSync(join(pluginRoot, removedDir), { recursive: true, force: true });
// Flip the ledger entry approved -> applied (gated write; audit record kept).
saveDecisions(setActionStatus(loadDecisions(dataDir), actionKey(approvedEntry), 'applied', decided_at), dataDir);
return {
applied: true,
revalidate,
report: {
op, target,
refMoves: fresh.diff.fileMoves.length,
taxonomyReassignments: reassignments.length,
archivedSkillMd,
removedDir,
ledgerStatus: 'applied',
},
};
}
// 3b. sanitize/retire — archive (rename) every file FIRST, then (retire) drop the dir.
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));
moveFile(join(pluginRoot, m.from), join(pluginRoot, m.to));
archived.push(m.to);
}
let removedDir = null;
@ -490,7 +545,7 @@ export function applyApprovedAction(approvedEntry, opts) {
rmSync(join(pluginRoot, removedDir), { recursive: true, force: true });
}
// 5. Flip the ledger entry approved -> applied (gated write; audit record kept).
// Flip the ledger entry approved -> applied (gated write; audit record kept).
const key = actionKey(approvedEntry);
saveDecisions(setActionStatus(loadDecisions(dataDir), key, 'applied', decided_at), dataDir);