/* RFC-0886: nachweis.screenshot.upload command handler — uploads a website screenshot to R2 and updates EvidenceSource.websiteScreenshot. Does not validate screenshot content or dimensions — only uploads and records the hash. Does not generate screenshots — use external tooling or nachweis.measure.* commands. RFC-0886: initial nachweis.screenshot.upload command handler. RFC-1097: step 6 — compass.migrate codemod run Mechanical v1 to v2 header migration across the workspace: 942 files rewritten — CHANGE_SUMMARY windows collapsed into history, forbidden v1 blocks stripped, KEY_DECISIONS seeded from @ai-invariant comments (5 files) or TODO placeholders (103 files), blocks reordered to canonical order. RFC-1097: sweep — werkstatt-engine clean Sweep batch 4: 73 Compass headers on headerless engine files (certification, component-runtime, isolation, evolution, testing), real KEY_DECISIONS on 75 files (kernel, cache, dht, swim, gitmesh, runtime), ~80 purpose expansions (CONTRACT-02/PURPOSE-02), non-goals on 13 CONTRACT-03 files, CS-07 history literal fix repo-wide (253 files). Policy: .template.ts/.template.astro excludedPaths. werkstatt-engine now 0 diagnostics. RFC-1237: resolve dry-run via context.dryRun fallback — consumeCommonFlags strips --dry-run into context.dryRun before dispatch, so a flags-only read was permanently false under werkstatt run (enforced by KERNEL-FLAG-10). RFC-1254: drop unused io-migration leftovers */ import path from "node:path"; import type { KernelCommandInput, KernelCommandResult, KernelRuntimeContext, } from "@warpgogol/werkstatt-engine/kernel"; import { parseMarkdownFrontmatter, stringifyMarkdownFrontmatter, } from "@warpgogol/werkstatt-shared/content"; import { appendAndCommitBordbuch } from "../bordbuch/bordbuch-commit-helper.ts"; import { acquireLock, releaseLock, generateOperationId } from "../werkstatt/index.ts"; import { isNachweisEntitled, makeSkipResult, resolveNachweisCachePath, resolvePbpEntityDir, resolveDefaultLang, resolveNachweisScreenshotR2Path, computeSourceSha256, uploadToR2, type NachweisScreenshotUploadResult, } from "./nachweis-io.ts"; function flagString(input: KernelCommandInput, key: string): string | undefined { const v = input.flags[key]; return typeof v === "string" ? v : undefined; } function flagBool(input: KernelCommandInput, key: string): boolean { const v = input.flags[key]; return v === true || v === "true"; } const EXT_TO_MEDIA_TYPE: Record = { ".webp": "image/webp", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", }; export async function runNachweisScreenshotUpload( input: KernelCommandInput, context: KernelRuntimeContext, ): Promise> { const { workspaceRoot, logger } = context; const systemId = flagString(input, "system") ?? context.site?.name; const slug = flagString(input, "slug"); const filePath = flagString(input, "file"); const dryRun = context.dryRun === true || flagBool(input, "dry-run"); if (!systemId) throw new Error("[nachweis.screenshot.upload] --system is required"); if (!slug) throw new Error("[nachweis.screenshot.upload] --slug is required"); if (!filePath) throw new Error("[nachweis.screenshot.upload] --file is required"); const ext = path.extname(filePath).toLowerCase(); const mediaType = EXT_TO_MEDIA_TYPE[ext]; if (!mediaType) { throw new Error( `[nachweis.screenshot.upload] unsupported file extension '${ext}'. Must be one of: .webp, .png, .jpg, .jpeg`, ); } const entitled = await isNachweisEntitled(workspaceRoot, systemId); if (!entitled) { return makeSkipResult( "nachweis.screenshot.upload", systemId, ) as unknown as KernelCommandResult; } const cachePath = await resolveNachweisCachePath(workspaceRoot, systemId); const lang = await resolveDefaultLang(cachePath); const evidenceDir = resolvePbpEntityDir(cachePath, lang, "evidence-source"); const evidenceFile = path.join(evidenceDir, `${slug}.md`); if (!(await context.io.exists(evidenceFile))) { throw new Error( `[nachweis.screenshot.upload] NOT_FOUND: evidence-source '${slug}' not found at ${evidenceFile}`, ); } if (!(await context.io.exists(filePath))) { throw new Error(`[nachweis.screenshot.upload] NOT_FOUND: file '${filePath}' not found`); } const sha256 = await computeSourceSha256(filePath); const r2Key = resolveNachweisScreenshotR2Path(systemId, slug, ext); if (dryRun) { return { data: { slug, systemId, sha256, mediaType, storage: "public", r2Key, bordbuchEventId: "", }, exitCode: 0, summary: `[nachweis.screenshot.upload] ${systemId}: DRY RUN — would upload screenshot for '${slug}' to ${r2Key}`, }; } const fileBuffer = await context.io.readFileBytes(filePath); await uploadToR2(fileBuffer, r2Key, mediaType); const rawEvidence = await context.io.readFile(evidenceFile); const { data: evidenceData, content: evidenceContent } = parseMarkdownFrontmatter(rawEvidence); evidenceData.websiteScreenshot = { sha256, mediaType, storage: "public", url: r2Key, }; const updatedContent = stringifyMarkdownFrontmatter(evidenceContent, evidenceData); await context.io.writeFile(evidenceFile, updatedContent); logger.info(`[nachweis.screenshot.upload] uploaded screenshot for '${slug}' to ${r2Key}`); const operationId = generateOperationId(); await acquireLock( workspaceRoot, `system:${systemId}`, operationId, "nachweis.screenshot.upload", "agent", ); await acquireLock( workspaceRoot, `bordbuch:${systemId}`, operationId, "nachweis.screenshot.upload", "agent", ); let bordbuchEventId: string; try { const { entry } = await appendAndCommitBordbuch( workspaceRoot, systemId, "nachweis-record", `Screenshot uploaded for '${slug}'`, "agent", { writerRole: "nachweis", metadata: { slug, screenshotSha256: sha256, mediaType, }, }, `Bordbuch: nachweis-record ${systemId} ${slug} screenshot`, ); bordbuchEventId = entry.id; } finally { await releaseLock(workspaceRoot, `bordbuch:${systemId}`); await releaseLock(workspaceRoot, `system:${systemId}`); } return { data: { slug, systemId, sha256, mediaType, storage: "public", r2Key, bordbuchEventId, }, exitCode: 0, summary: `[nachweis.screenshot.upload] ${systemId}: screenshot for '${slug}' uploaded (bordbuch: ${bordbuchEventId})`, nextSteps: [ { action: `Process the screenshot: pnpm exec werkstatt run nachweis.screenshot.process --site ${systemId} --slug ${slug}`, kind: "optional", }, ], }; }