ms-ai-architect/scripts/kb-update/relabel-dato.mjs

139 lines
7.2 KiB
JavaScript

#!/usr/bin/env node
// Enhet 2 (decision-b dialect pass, path A, ⊥ R7) — pure value-preserving relabel of the third
// Norwegian header date label to its English equivalent:
// **Dato:** → **Last updated:** (16 files)
//
// This is a LABEL rename only: the date value (`2026-06-19`, `2026-04`, `5. februar 2026`, …) is
// byte-preserved, so no fact is ever fabricated. It reuses the Enhet-1 primitive relabelHeaderDialect()
// — header-scoped (above the first `---`/`## `), multi-occurrence-guarded, target-collision-guarded,
// with a hard per-file byte invariant re-proven before any write.
//
// Why **Dato:** needed its own unit (deferred from Enhet 1): unlike **Sist oppdatert:**/**Kategori:**,
// **Dato:** ALSO appears in BODY templates as a placeholder (`**Dato:** [YYYY-MM-DD]`, `YYYY-MM-DD`,
// `[Dato]`). Header-scoping already excludes those, but this unit adds isRealDateValue() as an explicit
// defense-in-depth guard that documents — and enforces — the trap: a manifest file's header **Dato:**
// value must be a real date, never a placeholder.
//
// Scope is EXACTLY 16 files: those where **Dato:** is the SOLE date field. Ground-truth audit
// (2026-07-06) found 21 header **Dato:** candidates; 5 of them ALSO carry **Last updated:** (a distinct
// creation-vs-modified date pair) → carved out to a later dedup unit, and the collision-guard aborts on
// them regardless. 8 further occurrences are body/list/placeholder and are never in scope.
//
// Usage: node scripts/kb-update/relabel-dato.mjs [--dry]
import { readFileSync, writeFileSync, existsSync, realpathSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { relabelHeaderDialect } from './relabel-dialect.mjs';
const __dirname = dirname(fileURLToPath(import.meta.url));
const PLUGIN_ROOT = join(__dirname, '..', '..');
// The single Dato→English pair for this unit.
export const DATO_LABEL_MAP = [['**Dato:**', '**Last updated:**']];
/**
* Placeholder guard: a real **Dato:** value carries a 20xx year and no template markers.
* Accepts every real dialect in the corpus (`2026-06-19`, `2026-04`, `5. februar 2026`);
* rejects the body-template traps (`[YYYY-MM-DD]`, `YYYY-MM-DD`, `[Dato]`, empty, `TBD`).
* @param {string} value the text following `**Dato:**` on the header line
* @returns {boolean}
*/
export function isRealDateValue(value) {
const v = String(value ?? '').trim();
if (/[[\]]/.test(v)) return false; // bracketed placeholder: [YYYY-MM-DD], [Dato]
if (/Y{2,}|M{2,}|D{2,}/.test(v)) return false; // literal placeholder: YYYY-MM-DD
return /20\d\d/.test(v); // must carry a real year
}
// Frozen manifest — the 16 files where **Dato:** is the SOLE date field (header block, real date,
// NO pre-existing **Last updated:**), verified against ground truth 2026-07-06. The per-file invariant
// below re-proves each write; the manifest only bounds WHICH files may be touched. The 5 dual-label
// files (which carry both **Dato:** and **Last updated:**) are DELIBERATELY absent.
export const MANIFEST = [
'skills/ms-ai-engineering/references/mlops-genaiops/cost-optimization-mlops-pipelines.md',
'skills/ms-ai-engineering/references/mlops-genaiops/governance-audit-ml-operations.md',
'skills/ms-ai-engineering/references/mlops-genaiops/inferencing-optimization-caching.md',
'skills/ms-ai-engineering/references/mlops-genaiops/infrastructure-as-code-mlops.md',
'skills/ms-ai-engineering/references/mlops-genaiops/monitoring-observability-ml-systems.md',
'skills/ms-ai-governance/references/monitoring-observability/anomaly-detection-ai-systems.md',
'skills/ms-ai-governance/references/monitoring-observability/application-insights-llm-monitoring.md',
'skills/ms-ai-governance/references/monitoring-observability/distributed-tracing-ai-pipelines.md',
'skills/ms-ai-governance/references/monitoring-observability/log-analytics-kql-ai-queries.md',
'skills/ms-ai-governance/references/monitoring-observability/token-usage-tracking-attribution.md',
'skills/ms-ai-governance/references/responsible-ai/ai-governance-structure-framework.md',
'skills/ms-ai-governance/references/responsible-ai/red-teaming-ai-models.md',
'skills/ms-ai-security/references/ai-security-engineering/adversarial-input-robustness-testing.md',
'skills/ms-ai-security/references/ai-security-engineering/model-fingerprinting-watermarking.md',
'skills/ms-ai-security/references/ai-security-engineering/secure-model-deployment-hardening.md',
'skills/ms-ai-security/references/ai-security-engineering/supply-chain-security-ai-models.md',
];
function run({ dry }) {
const planned = [];
const missing = [];
let relabels = 0;
for (const rel of MANIFEST) {
const abs = join(PLUGIN_ROOT, rel);
if (!existsSync(abs)) { missing.push(rel); continue; }
const old = readFileSync(abs, 'utf8');
const { content: out, applied } = relabelHeaderDialect(old, DATO_LABEL_MAP);
if (applied.length === 0) continue; // idempotent — already relabeled (re-run)
const o = old.split('\n');
const n = out.split('\n');
// Placeholder guard: every relabeled **Dato:** value must be a real date, not a template.
for (const a of applied) {
const value = o[a.line].split('**Dato:**')[1] ?? '';
if (!isRealDateValue(value)) {
throw new Error(`ABORT ${rel}: **Dato:** value is not a real date (placeholder trap): "${value.trim()}"`);
}
}
// Hard invariant: exactly `applied.length` lines changed, each is the old line with ONLY the
// label token swapped; line count unchanged; everything else byte-identical.
if (n.length !== o.length) throw new Error(`ABORT ${rel}: line count changed (${o.length}${n.length})`);
let diffs = 0;
for (let i = 0; i < o.length; i++) {
if (o[i] === n[i]) continue;
diffs++;
const hit = applied.find((a) => a.line === i);
if (!hit) throw new Error(`ABORT ${rel}: line ${i} changed but not in applied set`);
if (n[i].replace(hit.to, hit.from) !== o[i]) throw new Error(`ABORT ${rel}: line ${i} changed beyond the label token`);
}
if (diffs !== applied.length) throw new Error(`ABORT ${rel}: ${diffs} lines changed ≠ ${applied.length} applied`);
relabels += applied.length;
planned.push({ rel, applied, out });
}
if (missing.length) {
console.error(`ABORT — ${missing.length} manifest target(s) not found (corpus drift):`);
missing.forEach((m) => console.error(' ' + m));
process.exit(1);
}
console.log(`Manifest: ${MANIFEST.length} | files to relabel: ${planned.length} | already-english (skipped): ${MANIFEST.length - planned.length}`);
console.log(` ${relabels} **Dato:** → **Last updated:**`);
if (dry) {
console.log('\n(dry run — no writes)');
for (const p of planned) {
const value = p.out.split('\n')[p.applied[0].line].split('**Last updated:**')[1].trim();
console.log(` ~ ${p.rel} [${value}]`);
}
return;
}
for (const p of planned) writeFileSync(join(PLUGIN_ROOT, p.rel), p.out);
console.log(`\nWrote ${planned.length} files.`);
}
const isMain = (() => {
try {
return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
} catch {
return false;
}
})();
if (isMain) run({ dry: process.argv.includes('--dry') });