feat(ms-ai-architect): C2.3 onboarding skriver scheduled_detection cadence+enabled via gated CLI (TDD) [skip-docs]

K5 oppfylt: onboarding skriver scheduled_detection-blokka (enabled +
os_scheduler_cadence) til bruker-eid config; parseScheduleConfig leser den
tilbake til samme verdier (round-trip bevist deterministisk).

- serializeScheduleConfig(config) i detection-schedule.mjs — invers av
  parseScheduleConfig, rett ved parseren (én formatsannhet).
- write-schedule-config.mjs (NY, gated CLI, Claude-fri): merger på eksisterende
  config (override kun de to onboarding-eide nøklene; interval_days/
  include_skill_lifecycle overlever). backupFile + atomicWriteSync — ingen rå
  fs-write.
- backupFile(filePath, backupRoot) i lib/backup.mjs — presis enkeltfil-backup.
- onboard.md (orkestrator): «Planlagt deteksjon»-seksjon + scheduler i --status.
  onboarding-agent.md: note om at scheduler er orkestratorens jobb (ingen Bash).
- Avvik fra plan-tekst (dokumentert): scheduler-spørsmål i orkestrator, ikke agent.

Verifisert: detection-schedule 33/33 (+10) · backup-restore 15/15 (+3) ·
kb-update 213 · kb-eval 100 · validate 239/0/0 · test-hooks 11/11 ·
kb-integrity 192/192 · discovery 13/13 · gitleaks 3 pre-eksisterende.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Kjell Tore Guttormsen 2026-06-22 14:53:03 +02:00
commit afd75c4fed
8 changed files with 340 additions and 4 deletions

View file

@ -15,7 +15,7 @@ import {
unlinkSync,
mkdirSync,
} from 'node:fs';
import { join } from 'node:path';
import { join, basename } from 'node:path';
import { atomicWriteJson } from './atomic-write.mjs';
const META_FILENAME = '.backup-meta.json';
@ -127,6 +127,36 @@ export function backupDir(srcDir, backupRoot, opts = {}) {
return { backupPath, retentionDays, restore };
}
/**
* Back up a SINGLE file into backupRoot/<timestamp>/<basename>. No-op (returns
* null) when the source file does not exist a first-time write has nothing to
* preserve. Used to guard the C2.3 scheduler-config write: atomic-write handles
* partial-write safety; this keeps the prior version recoverable. Precise by
* design (does not copy the surrounding dir, so onboarding's org/ data is not
* dragged into a backup on every cadence change).
*
* @param {string} filePath file to back up
* @param {string} backupRoot parent dir for the timestamped backup subdir
* @param {object} [opts]
* @param {Date} [opts.now] override clock for testing
* @returns {{backupPath: string}|null}
*/
export function backupFile(filePath, backupRoot, opts = {}) {
if (!filePath || typeof filePath !== 'string') {
throw new Error('backupFile: filePath is required');
}
if (!backupRoot || typeof backupRoot !== 'string') {
throw new Error('backupFile: backupRoot is required');
}
if (!existsSync(filePath)) return null;
const now = opts.now ?? new Date();
const destDir = join(backupRoot, backupTimestamp(now));
mkdirSync(destDir, { recursive: true });
const backupPath = join(destDir, basename(filePath));
cpSync(filePath, backupPath, { force: true, preserveTimestamps: true });
return { backupPath };
}
/**
* True if a stale rollback sentinel exists at backupRoot.
* @param {string} backupRoot

View file

@ -88,6 +88,41 @@ export function parseScheduleConfig(text) {
return cfg;
}
/**
* Serialize a schedule config to a full config-file text: a `---`-fenced
* frontmatter with the `scheduled_detection:` block (all four known keys) plus a
* short human header. The inverse of parseScheduleConfig C2.3's onboarding
* write-path uses THIS (no second format definition): values are normalized
* exactly as coerce() would read them, so
* parseScheduleConfig(serializeScheduleConfig(c))
* yields a DEFAULT-merged, normalized c (round-trip, acceptance K5). Pure.
* @param {Partial<typeof DEFAULT_SCHEDULE_CONFIG>} [config]
* @returns {string}
*/
export function serializeScheduleConfig(config = {}) {
const c = { ...DEFAULT_SCHEDULE_CONFIG, ...config };
const interval =
Number.isInteger(c.interval_days) && c.interval_days > 0
? c.interval_days
: DEFAULT_SCHEDULE_CONFIG.interval_days;
return [
'---',
'scheduled_detection:',
` enabled: ${c.enabled === true}`,
` interval_days: ${interval}`,
` include_skill_lifecycle: ${c.include_skill_lifecycle !== false}`,
` os_scheduler_cadence: ${c.os_scheduler_cadence === 'interval' ? 'interval' : 'daily'}`,
'---',
'',
'# ms-ai-architect — planlagt deteksjon',
'',
'Skrevet av `/architect:onboard`. Styrer den opt-in, Claude-frie deteksjonen',
'(poll → rapport → discovery → skill-livssyklus). Endre `scheduled_detection`-',
'blokka over, eller kjør `/architect:onboard` på nytt.',
'',
].join('\n');
}
/**
* Load the opt-in schedule config. C2.1: the user-owned path
* (~/.claude/ms-ai-architect/ms-ai-architect.local.md) takes precedence so the

View file

@ -0,0 +1,75 @@
#!/usr/bin/env node
// write-schedule-config.mjs — Spor C / C2.3: onboarding writes the opt-in
// scheduled-detection config to the USER-owned config path
// (~/.claude/ms-ai-architect/ms-ai-architect.local.md), so the user never has to
// hand-edit the gitignored file. Operator: "avgjøres i onboardingen, egen
// innstilling, daglig default".
//
// STRUCTURAL ToS GUARANTEE: pure node — it only reads/writes a local config
// file and NEVER contacts Anthropic/Claude (same boundary as the rest of the
// detection layer; see detection-schedule.mjs for the Consumer Terms §3.7
// rationale). It is not a DETECTION_STEP — it is the onboarding write-path.
//
// GATED: it MERGES onto the existing config (parse → override only the two
// onboarding-owned keys: enabled + os_scheduler_cadence → serialize), backs up
// any prior file via lib/backup, and writes atomically via lib/atomic-write —
// never a raw fs write. interval_days / include_skill_lifecycle set elsewhere
// survive the rewrite.
//
// node scripts/kb-update/write-schedule-config.mjs --enabled true --cadence daily
// node scripts/kb-update/write-schedule-config.mjs --enabled false --cadence interval
//
// --home <dir> overrides the home dir (tests). Prints the resolved config path.
import { existsSync, readFileSync, mkdirSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import { resolveConfigPath, resolveUserDataDir } from './lib/user-data.mjs';
import { parseScheduleConfig, serializeScheduleConfig } from './lib/detection-schedule.mjs';
import { atomicWriteSync } from './lib/atomic-write.mjs';
import { backupFile } from './lib/backup.mjs';
function parseArgs(argv) {
const out = {};
for (let i = 0; i < argv.length; i++) {
if (argv[i] === '--enabled') out.enabled = argv[++i];
else if (argv[i] === '--cadence') out.cadence = argv[++i];
else if (argv[i] === '--home') out.home = argv[++i];
}
return out;
}
/**
* Write (merge onto) the user-owned scheduler config from onboarding answers.
* @param {{enabled: boolean|string, cadence: string, home?: string}} args
* @returns {{configPath: string, config: object}}
*/
export function writeScheduleConfig({ enabled, cadence, home = homedir() }) {
const configPath = resolveConfigPath(home);
const existing = existsSync(configPath) ? readFileSync(configPath, 'utf8') : '';
const parsed = parseScheduleConfig(existing); // existing values (or OFF defaults)
// Only the two onboarding-owned keys are overridden; everything else is
// carried forward from `parsed`. coerce() in detection-schedule normalizes on
// read, so we just hand it values it understands.
const merged = {
...parsed,
enabled: enabled === true || enabled === 'true',
os_scheduler_cadence: cadence === 'interval' ? 'interval' : 'daily',
};
mkdirSync(resolveUserDataDir(home), { recursive: true });
backupFile(configPath, join(resolveUserDataDir(home), '.backups')); // no-op if absent
atomicWriteSync(configPath, serializeScheduleConfig(merged));
return { configPath, config: merged };
}
// CLI entry — only when run directly (not when imported by tests).
if (import.meta.url === `file://${process.argv[1]}`) {
const { enabled, cadence, home } = parseArgs(process.argv.slice(2));
const { configPath, config } = writeScheduleConfig({ enabled, cadence, home });
console.log(configPath);
console.error(
`scheduled_detection: enabled=${config.enabled} os_scheduler_cadence=${config.os_scheduler_cadence} (interval_days=${config.interval_days})`,
);
}