ms-ai-architect/scripts/kb-update/lib/decisions-io.mjs
Kjell Tore Guttormsen f03a0e08b2 feat(ms-ai-architect): Sesjon 16 — B3 ledger action-lag + merge_skills dry-run-planner
Spor B / B3 start. Operatør-gated dry-run for skill-livssyklus, merge først.

- decisions-io.mjs: additivt skill-nøklet `actions`-lag ved siden av urørt
  URL-nøklet `decisions` (14 URL-tester urørt = regresjonsbevis). version=1,
  loadDecisions backfiller manglende actions-nøkkel. Nye rene fn: actionKey
  (merge symmetrisk på paret), isActionDecided, recordAction (no-mutate),
  listActions. Policy A gjelder også actions.
- scripts/kb-eval/lib/skill-ops.mjs: ren planMergeSkills → {entry,diff,guardrail},
  leser ingen disk, anvender INGENTING. Guardrail = ingen kuratert verdi tapt
  (count-invariant + set-equality + kollisjons-deteksjon; ok=false ved klobring).
  Impur skall loadSkillRefs/runMergePlan + CLI plan-skill-op.mjs (gated --write).
- Ekte eng↔infra dry-run: guardrail OK (34+153=187, 0 kollisjoner), 153 fil-flytt
  + 7 taksonomi-reassign + retire eng; 0 skriving til skills/, ledger uendret
  (retning er operatør/judge-valg, ikke pushet gjennom gaten).
- TDD: test-decisions-actions (10) + test-skill-ops-merge (10, inkl. byte-for-byte
  skills/-snapshot som no-write-bevis). kb-eval 40→50, kb-update 122→132.
  Regresjon grønn: validate 239, kb-integrity 192/192.

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

160 lines
6.2 KiB
JavaScript

// decisions-io.mjs — Read/write + pure helpers for data/decisions.json (lag 2).
// The decision ledger is the ONLY write-authorized bridge between detection and
// the KB/registry: discovery READS it to filter, the operator gate WRITES it.
// Zero dependencies. Atomic writes via .tmp + rename (mirrors registry-io).
//
// Dedup policy = A (operatør 2026-06-19): isDecided(url) is true for ANY ledger
// entry (pending | approved | rejected). Discovery re-proposes only URLs that
// are entirely absent from the ledger; everything the operator has touched —
// approved, rejected, or explicitly deferred (pending) — stays off the list.
import { readFileSync, writeFileSync, renameSync, existsSync, mkdirSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const DEFAULT_DATA_DIR = join(__dirname, '..', 'data');
/**
* Empty ledger scaffold.
*
* Two parallel collections, both written ONLY through the operator gate:
* - decisions — URL-keyed (Spor A): which Microsoft Learn page belongs where.
* - actions — skill-keyed (Spor B / B3): skill-lifecycle ops (merge_skills,
* sanitize_skill, retire_skill, create_skill). Additive: version
* stays 1, and a pre-action ledger on disk normalizes cleanly
* (loadDecisions backfills the missing actions key).
* @returns {{version: number, updated_at: string|null, decisions: object, actions: object}}
*/
export function createLedger() {
return { version: 1, updated_at: null, decisions: {}, actions: {} };
}
/**
* Load the decision ledger from disk. Backward-compatible: a ledger written
* before the action layer existed (no `actions` key) is normalized to `{}` so
* callers never have to guard against undefined.
* @param {string} [dataDir] — defaults to ../data/ relative to lib/
* @returns {object} parsed ledger or empty scaffold
*/
export function loadDecisions(dataDir = DEFAULT_DATA_DIR) {
const path = join(dataDir, 'decisions.json');
if (!existsSync(path)) return createLedger();
const led = JSON.parse(readFileSync(path, 'utf8'));
if (!led.actions) led.actions = {};
return led;
}
/**
* Save the decision ledger atomically (write to .tmp, then rename).
* This is the gate's write path — detection scripts must NOT import it.
* @param {object} ledger
* @param {string} [dataDir]
*/
export function saveDecisions(ledger, dataDir = DEFAULT_DATA_DIR) {
if (!existsSync(dataDir)) mkdirSync(dataDir, { recursive: true });
const path = join(dataDir, 'decisions.json');
const tmp = path + '.tmp';
writeFileSync(tmp, JSON.stringify(ledger, null, 2) + '\n', 'utf8');
renameSync(tmp, path);
}
/**
* Has the operator already decided on this URL? Policy A: any entry counts.
* @param {object} ledger
* @param {string} url — normalized URL
* @returns {boolean}
*/
export function isDecided(ledger, url) {
return Boolean(ledger.decisions && ledger.decisions[url]);
}
/**
* Record a decision for a URL. Pure — returns a new ledger, does not mutate.
* @param {object} ledger
* @param {string} url — normalized URL
* @param {{status: string, decided_at?: string, suggested_skill?: string|null,
* suggested_category?: string, note?: string}} decision
* @returns {object} new ledger
*/
export function recordDecision(ledger, url, decision) {
return {
...ledger,
updated_at: decision.decided_at ?? ledger.updated_at,
decisions: { ...ledger.decisions, [url]: { ...decision } },
};
}
/**
* Drop candidates the operator has already decided on (policy A).
* Discovery applies this before emitting its report.
* @param {object} ledger
* @param {Array<{url: string}>} candidates
* @returns {Array<{url: string}>} candidates with no ledger entry
*/
export function filterUndecided(ledger, candidates) {
return candidates.filter((c) => !isDecided(ledger, c.url));
}
// ===========================================================================
// Skill-level action layer (Spor B / B3) — additive, mirrors the URL helpers.
// Detection/transformation produce a PENDING action entry; only the gate writes
// it. recordAction never mutates skills/ — it records a proposal in the ledger.
// ===========================================================================
/**
* Deterministic dedup key for a skill-lifecycle action. merge_skills is keyed
* symmetrically on the pair (merging A<-B and B<-A dedup to the same key);
* single-skill ops (sanitize/retire/create) are keyed by their one target.
* @param {{operation_type: string, targets?: object}} entry
* @returns {string}
*/
export function actionKey(entry) {
const op = entry.operation_type;
const t = entry.targets ?? {};
if (op === 'merge_skills') {
const pair = [t.absorber, t.absorbed].filter(Boolean).sort();
return `merge_skills:${pair.join('+')}`;
}
const single = t.skill ?? t.name ?? t.absorber ?? '?';
return `${op}:${single}`;
}
/**
* Has the operator already decided on this action? Policy A: any entry
* (pending | approved | rejected) counts — mirrors isDecided for URLs.
* @param {object} ledger
* @param {string} key — from actionKey()
* @returns {boolean}
*/
export function isActionDecided(ledger, key) {
return Boolean(ledger.actions && ledger.actions[key]);
}
/**
* Record a skill-lifecycle action. Pure — returns a new ledger, does not mutate.
* Keyed by actionKey(entry). Leaves the URL-keyed decisions map untouched.
* @param {object} ledger
* @param {{operation_type: string, status: string, decided_at?: string|null,
* targets?: object, guardrail?: object, note?: string}} entry
* @returns {object} new ledger
*/
export function recordAction(ledger, entry) {
const key = actionKey(entry);
return {
...ledger,
updated_at: entry.decided_at ?? ledger.updated_at,
actions: { ...(ledger.actions ?? {}), [key]: { ...entry } },
};
}
/**
* List recorded actions, optionally filtered by status.
* @param {object} ledger
* @param {string|null} [status] — when given, keep only entries with this status
* @returns {Array<object>}
*/
export function listActions(ledger, status = null) {
const all = Object.values(ledger.actions ?? {});
return status ? all.filter((a) => a.status === status) : all;
}