feat(ms-ai-architect): R20 — Category-backfill på 25 kategorisløse ref-filer via insertMetaField [skip-docs]

Ny testet primitiv transform.insertMetaField (anker + 500B-back-off som insertHeaderFields, idempotent på eksakt label, body byte-identisk; 6 tester) + backfill-category.mjs (deterministisk folder->category-regel, hard per-fil-invariant, insert-only, aborterer for skriving ved avvik).

Fordeling: 14 Solution Architecture & Advisory (architecture/), 6 Microsoft AI Platforms (platforms/+development/), 4 Responsible AI & Governance, 1 MLOps & GenAIOps. Label = engelsk Category (322 vs 42 Kategori). Eksisterende recommended-mcp-servers/rag-maturity-model urort.

Roadmap: R20 done + R21 (Status/Last-updated not-due) encoded. Verifisering: 0 kategorislose filer (var 25); diff +25/-0; idempotent re-run; suite 764/764 exit 0.
This commit is contained in:
Kjell Tore Guttormsen 2026-07-06 07:39:54 +02:00
commit a583599ab1
29 changed files with 262 additions and 1 deletions

View file

@ -0,0 +1,82 @@
#!/usr/bin/env node
// Backfill **Category:** on the reference files that carry NO category label (R20).
//
// Deterministic folder→category rule (operator-approved taxonomy 2026-07-06): insert-only
// via the tested `insertMetaField` primitive, with a hard per-file invariant asserted BEFORE
// any write — exactly one line is inserted, it is the Category line, and the body is
// byte-identical. If any target falls outside the approved folder rule, or any file would
// change by more than that single line, the run aborts and writes nothing. Idempotent:
// files that already carry **Category:**/**Kategori:** are skipped, so a re-run is a no-op.
//
// Usage: node scripts/kb-update/backfill-category.mjs [--dry]
import { readFileSync, writeFileSync } from 'node:fs';
import { execSync } from 'node:child_process';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { insertMetaField } from './lib/transform.mjs';
const __dirname = dirname(fileURLToPath(import.meta.url));
const PLUGIN_ROOT = join(__dirname, '..', '..');
const dry = process.argv.includes('--dry');
// Immediate-parent-directory basename → Category. Operator-approved 2026-07-06.
const FOLDER_CATEGORY = {
architecture: 'Solution Architecture & Advisory',
platforms: 'Microsoft AI Platforms',
development: 'Microsoft AI Platforms',
'responsible-ai': 'Responsible AI & Governance',
'mlops-genaiops': 'MLOps & GenAIOps',
};
const RE_CAT = /^\s*\*\*(Category|Kategori):\*\*/im;
const files = execSync("find skills/*/references -name '*.md'", { cwd: PLUGIN_ROOT, encoding: 'utf8' })
.trim()
.split('\n');
const targets = files.filter((rel) => !RE_CAT.test(readFileSync(join(PLUGIN_ROOT, rel), 'utf8')));
const planned = [];
const unmatched = [];
for (const rel of targets) {
const folder = rel.split('/').slice(-2, -1)[0];
const cat = FOLDER_CATEGORY[folder];
if (!cat) {
unmatched.push(`${rel} (folder=${folder})`);
continue;
}
const old = readFileSync(join(PLUGIN_ROOT, rel), 'utf8');
const out = insertMetaField(old, 'Category', cat);
// Hard invariant: exactly one line inserted (the Category line), body byte-identical.
const o = old.split('\n');
const n = out.split('\n');
if (n.length !== o.length + 1) throw new Error(`ABORT ${rel}: not exactly one line inserted`);
let d = 0;
while (d < o.length && o[d] === n[d]) d++;
if (n[d] !== `**Category:** ${cat}`) {
throw new Error(`ABORT ${rel}: inserted line mismatch → ${JSON.stringify(n[d])}`);
}
if (o.slice(d).join('\n') !== n.slice(d + 1).join('\n')) {
throw new Error(`ABORT ${rel}: body not byte-identical below the insertion`);
}
planned.push({ rel, cat, out });
}
if (unmatched.length) {
console.error(`ABORT — ${unmatched.length} target(s) outside the approved folder rule:`);
unmatched.forEach((u) => console.error(' ' + u));
process.exit(1);
}
const byCat = {};
for (const p of planned) byCat[p.cat] = (byCat[p.cat] || 0) + 1;
console.log(`Reference files: ${files.length} | without a category: ${targets.length} | planned: ${planned.length}`);
console.log('By category:');
for (const [c, n] of Object.entries(byCat).sort()) console.log(` ${n} ${c}`);
if (dry) {
console.log('\n(dry run — no writes)');
process.exit(0);
}
for (const p of planned) writeFileSync(join(PLUGIN_ROOT, p.rel), p.out);
console.log(`\nWrote ${planned.length} files.`);

View file

@ -359,6 +359,65 @@ export function insertHeaderFields(content, meta) {
return lines.join('\n');
}
/**
* Surgically insert ONE bold-label meta line `**<label>:** <value>` into an EXISTING KB
* file that lacks it: the R20/R21 base-field backfill primitive (**Category:** in R20;
* **Status:** / **Last updated:** in R21). Reuses insertHeaderFields' anchor + 500-byte
* back-off discipline the line lands immediately after the last line of the first
* contiguous bold-label meta run that still leaves room in the window, with a title fallback
* for the "None" dialect (no meta lines). Idempotent on the EXACT label: a file already
* carrying `**<label>:**` anywhere in the header region is returned unchanged. The body (from
* the first `## ` section) is byte-identical.
*
* Unlike insertHeaderFields (Port-1 Type/Source, with type validation) this is field-agnostic
* it keys on the label shape only, so it never re-derives a value or touches other lines.
*
* @param {string} content full existing file content
* @param {string} label the bold label WITHOUT the `**`/`:` decoration, e.g. 'Category'
* @param {string} value the field value
* @returns {string} content with the meta line inserted, or unchanged if the label is present
* @throws if label or value is blank
*/
export function insertMetaField(content, label, value) {
const s = String(content ?? '');
const lab = String(label ?? '').trim();
const val = String(value ?? '').trim();
if (lab === '') throw new Error('insertMetaField: label is required');
if (val === '') throw new Error('insertMetaField: value is required');
const lines = s.split('\n');
const esc = lab.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const labelRe = new RegExp('^\\s*\\*\\*' + esc + ':\\*\\*', 'i');
// Idempotent: if the exact label already appears in the header region, return unchanged.
for (const line of lines) {
if (/^##\s/.test(line) || /^---\s*$/.test(line)) break; // reached body / rule
if (labelRe.test(line)) return s;
}
// Anchor: last line of the first contiguous meta run whose insertion point still fits the
// 500-byte window; title fallback for the "None" dialect (mirrors insertHeaderFields).
let anchorIdx = -1;
let titleIdx = -1;
let cum = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (/^##\s/.test(line) || /^---\s*$/.test(line)) break; // reached body / rule
if (titleIdx === -1 && /^#\s+\S/.test(line)) titleIdx = i;
const nextCum = cum + line.length + 1; // byte offset just AFTER this line
if (RE_META_LINE.test(line)) {
if (nextCum > HEADER_REGION_BYTES) break; // back off — insertion point past the window
anchorIdx = i;
} else if (anchorIdx !== -1) {
break; // first non-meta line after the run — the contiguous run is over
}
cum = nextCum;
}
const at = (anchorIdx !== -1 ? anchorIdx : titleIdx) + 1; // -1 + 1 = 0 → very top if no title
lines.splice(at, 0, `**${lab}:** ${val}`);
return lines.join('\n');
}
/**
* Surgically insert-or-update ONLY the `**Verified:**` and `**Verified by:**` header lines
* on an EXISTING KB file the R7R10 born-verified STAMP primitive. Unlike composeKbFile