From 5934523e45ff670f77819e6939a1e2c5ad863067 Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 2 Nov 2026 08:55:06 +0100 Subject: [PATCH] [content] DaySentence: Candidates held to every rule; library:verify for the author --- package.json | 1 + packages/content/package.json | 1 + packages/content/src/candidates.ts | 102 +++++++++++++++++++++++ packages/content/test/candidates.test.ts | 87 +++++++++++++++++++ scripts/validate-library.ts | 35 ++++++-- scripts/verify-sentences.ts | 59 +++++++++++++ 6 files changed, 280 insertions(+), 5 deletions(-) create mode 100644 packages/content/src/candidates.ts create mode 100644 packages/content/test/candidates.test.ts create mode 100644 scripts/verify-sentences.ts diff --git a/package.json b/package.json index 3280588..0e06fc2 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "test:e2e": "pnpm guard:cpu && turbo run build --filter=@rosea/app && playwright test --config=e2e/playwright.config.ts", "test:offline": "pnpm guard:cpu && turbo run build --filter=@rosea/app && playwright test --config=e2e/playwright.offline.config.ts", "validate:library": "tsx scripts/validate-library.ts", + "library:verify": "tsx scripts/verify-sentences.ts", "lint:copy": "tsx scripts/lint-copy.ts", "art:board": "tsx tools/art-prep/src/cli-board.ts", "art:accept": "tsx tools/art-prep/src/cli-accept.ts", diff --git a/packages/content/package.json b/packages/content/package.json index 9074095..c339e5d 100644 --- a/packages/content/package.json +++ b/packages/content/package.json @@ -9,6 +9,7 @@ "exports": { ".": "./src/index.ts", "./validate": "./src/validator.ts", + "./candidates": "./src/candidates.ts", "./places": "./src/places/places.ts", "./guess": "./src/places/guess.ts" }, diff --git a/packages/content/src/candidates.ts b/packages/content/src/candidates.ts new file mode 100644 index 0000000..c320a55 --- /dev/null +++ b/packages/content/src/candidates.ts @@ -0,0 +1,102 @@ +/** + * Candidate sentences and their verification (.agents/features/day-sentence.md P8). + * + * An agent may propose a sentence; only a person may say it was checked + * (phase0-workspace.md D4). A candidate is a library entry without `publicDomain`, + * `verifiedBy` and `verifiedAt`, and with a `check`: where to read it. It is held to + * every library rule but verification, so the author is never asked to verify a + * line that would fail anyway. + * + * `verifyCandidates` is what `pnpm library:verify --by ` does. It is the + * author's command. **Agents never run it.** + */ +import { validateEntry, validateLibrary, type Problem } from './validator.js'; + +/** A file's worth of entries: its name (`biblical.json`) and what it holds. */ +export type Files = Readonly>; + +const isRecord = (x: unknown): x is Record => typeof x === 'object' && x !== null && !Array.isArray(x); +const idOf = (x: unknown): string => (isRecord(x) && typeof x['id'] === 'string' ? x['id'] : '(no id)'); + +/** The library entry a candidate becomes once a person has checked it. */ +export function asVerified(candidate: unknown, by: string, day: string): unknown { + if (!isRecord(candidate) || !isRecord(candidate['source'])) return candidate; + const { check: _check, ...entry } = candidate; + return { ...entry, source: { ...candidate['source'], publicDomain: true, verifiedBy: by, verifiedAt: day } }; +} + +/** Every reason a candidate could not become a library entry, even once verified. */ +export function validateCandidate(candidate: unknown): Problem[] { + const id = idOf(candidate); + const problems: Problem[] = []; + const check = isRecord(candidate) ? candidate['check'] : undefined; + if (!isRecord(check) || typeof check['url'] !== 'string' || !/^https:\/\//.test(check['url']) || typeof check['where'] !== 'string' || typeof check['publicDomain'] !== 'string') { + problems.push({ id, rule: 'schema', message: 'a candidate needs check.url (https), check.where and check.publicDomain, so the person verifying knows where to read it' }); + } + const source = isRecord(candidate) ? candidate['source'] : undefined; + for (const field of ['publicDomain', 'verifiedBy', 'verifiedAt']) { + if (isRecord(source) && field in source) { + problems.push({ id, rule: 'schema', message: `a candidate must not carry source.${field}: only the person who verifies it adds that` }); + } + } + return [...problems, ...validateEntry(asVerified(candidate, 'candidate', '2000-01-01'))]; +} + +/** Every candidate, and ids unique across the candidates and the library together. */ +export function validateCandidates(candidates: readonly unknown[], library: readonly unknown[]): Problem[] { + const problems = candidates.flatMap(validateCandidate); + const inLibrary = new Set(library.map(idOf)); + const seen = new Set(); + for (const c of candidates) { + const id = idOf(c); + if (inLibrary.has(id)) problems.push({ id, rule: 'duplicate-id', message: `id '${id}' is already in the library` }); + else if (seen.has(id)) problems.push({ id, rule: 'duplicate-id', message: `id '${id}' is proposed more than once` }); + seen.add(id); + } + return problems; +} + +export type VerifyResult = + | { readonly ok: true; readonly library: Files; readonly candidates: Files; readonly moved: readonly string[] } + | { readonly ok: false; readonly problems: readonly string[] }; + +/** + * Moves the candidates named by `ids` into the library, as checked by `by` on `day`. + * Each lands in the library file named like its candidate file. Refuses, and moves + * nothing, if an id is unknown, the name is empty, or the library would fail. + */ +export function verifyCandidates(p: { + readonly candidates: Files; + readonly library: Files; + readonly ids: readonly string[]; + readonly by: string; + readonly day: string; +}): VerifyResult { + const by = p.by.trim(); + if (by === '' || by.toLowerCase() === 'candidate') return { ok: false, problems: ['--by needs the name of the person who checked the sentences'] }; + if (!/^\d{4}-\d{2}-\d{2}$/.test(p.day)) return { ok: false, problems: [`not a day: '${p.day}'`] }; + if (p.ids.length === 0) return { ok: false, problems: ['name at least one candidate id'] }; + + const wanted = new Set(p.ids); + const library: Record = Object.fromEntries(Object.entries(p.library).map(([f, e]) => [f, [...e]])); + const candidates: Record = {}; + const moved: string[] = []; + for (const [file, entries] of Object.entries(p.candidates)) { + candidates[file] = []; + for (const c of entries) { + const id = idOf(c); + if (wanted.has(id) && !moved.includes(id)) { + (library[file] ??= []).push(asVerified(c, by, p.day)); + moved.push(id); + } else { + candidates[file].push(c); + } + } + } + + const unknown = p.ids.filter((id) => !moved.includes(id)); + if (unknown.length > 0) return { ok: false, problems: unknown.map((id) => `no candidate '${id}'`) }; + const problems = validateLibrary(Object.values(library).flat()).map((x) => `${x.id} [${x.rule}] ${x.message}`); + if (problems.length > 0) return { ok: false, problems }; + return { ok: true, library, candidates, moved }; +} diff --git a/packages/content/test/candidates.test.ts b/packages/content/test/candidates.test.ts new file mode 100644 index 0000000..fa69fa4 --- /dev/null +++ b/packages/content/test/candidates.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from 'vitest'; +import { asVerified, validateCandidate, validateCandidates, verifyCandidates } from '../src/candidates.js'; +import { validateEntry } from '../src/validator.js'; + +const candidate = (id: string, over: Record = {}): Record => ({ + id, + text: { en: 'Fixture text for a candidate, not a real sentence.' }, + source: { work: 'Fixture 1:1', author: null, tradition: 'biblical', translation: 'KJV' }, + use: ['sunset'], + tone: 'gentle', + promisesOutcome: false, + check: { url: 'https://example.org/fixture', where: 'chapter 1, verse 1', publicDomain: 'KJV, 1611/1769' }, + ...over +}); + +describe('a candidate (day-sentence.md P8)', () => { + it('becomes a valid library entry once a person has checked it, with no check field left', () => { + const entry = asVerified(candidate('fx-1'), 'Mark', '2026-11-02') as Record; + expect(validateEntry(entry)).toEqual([]); + expect(entry).not.toHaveProperty('check'); + expect(entry['source']).toMatchObject({ publicDomain: true, verifiedBy: 'Mark', verifiedAt: '2026-11-02' }); + }); + + it('passes when it would pass the library', () => { + expect(validateCandidate(candidate('fx-1'))).toEqual([]); + }); + + it('is held to every library rule: length, forbidden words, promises, translations', () => { + expect(validateCandidate(candidate('fx-long', { text: { en: 'x'.repeat(241) } })).map((p) => p.rule)).toContain('too-long'); + expect(validateCandidate(candidate('fx-word', { text: { en: 'A lonely road.' } })).map((p) => p.rule)).toContain('forbidden-word'); + expect(validateCandidate(candidate('fx-promise', { text: { en: 'Everything will be well.' } })).map((p) => p.rule)).toContain('promises-outcome'); + expect( + validateCandidate(candidate('fx-niv', { source: { work: 'Fixture', author: null, tradition: 'biblical', translation: 'NIV' } })).map((p) => p.rule) + ).toContain('translation-under-copyright'); + }); + + it('needs a check that says where to read it', () => { + const { check: _, ...noCheck } = candidate('fx-1'); + expect(validateCandidate(noCheck)[0]?.message).toMatch(/check\.url/); + expect(validateCandidate(candidate('fx-1', { check: { url: 'http://example.org', where: 'x', publicDomain: 'x' } }))[0]?.message).toMatch(/https/); + }); + + it('may not say it was verified: only the person who verifies adds that', () => { + for (const field of ['publicDomain', 'verifiedBy', 'verifiedAt']) { + const c = candidate('fx-1', { source: { work: 'F', author: null, tradition: 'biblical', translation: 'KJV', [field]: field === 'publicDomain' ? true : 'x' } }); + expect(validateCandidate(c).map((p) => p.message).join(' '), field).toMatch(new RegExp(`source\\.${field}`)); + } + }); + + it('may not reuse an id the library or another candidate has', () => { + const library = [asVerified(candidate('fx-1'), 'Mark', '2026-11-01')]; + const problems = validateCandidates([candidate('fx-1'), candidate('fx-2'), candidate('fx-2')], library); + expect(problems.map((p) => `${p.id} ${p.rule}`)).toEqual(['fx-1 duplicate-id', 'fx-2 duplicate-id']); + }); +}); + +describe('library:verify — the author’s command', () => { + const files = { candidates: { 'biblical.json': [candidate('fx-1'), candidate('fx-2')], 'poetry.json': [candidate('fx-3', { source: { work: 'P', author: 'A Poet', tradition: 'poetry', translation: null } })] }, library: {} }; + + it('moves the named candidates into the library file of the same name, stamped with the name and the day', () => { + const result = verifyCandidates({ ...files, ids: ['fx-1', 'fx-3'], by: 'Mark', day: '2026-11-02' }); + expect(result.ok).toBe(true); + if (!result.ok) return; + expect(result.moved).toEqual(['fx-1', 'fx-3']); + expect(Object.keys(result.library).sort()).toEqual(['biblical.json', 'poetry.json']); + expect(result.library['biblical.json']).toEqual([asVerified(candidate('fx-1'), 'Mark', '2026-11-02')]); + expect(result.candidates['biblical.json']).toEqual([candidate('fx-2')]); + expect(result.candidates['poetry.json']).toEqual([]); + }); + + it('adds to what the library already holds, never replaces it', () => { + const kept = asVerified(candidate('old-1'), 'Mark', '2026-11-01'); + const result = verifyCandidates({ ...files, library: { 'biblical.json': [kept] }, ids: ['fx-2'], by: 'Mark', day: '2026-11-02' }); + expect(result.ok && result.library['biblical.json']).toEqual([kept, asVerified(candidate('fx-2'), 'Mark', '2026-11-02')]); + }); + + it('refuses, moving nothing, without a person’s name, with an unknown id, or with a line the library would refuse', () => { + expect(verifyCandidates({ ...files, ids: ['fx-1'], by: ' ', day: '2026-11-02' })).toMatchObject({ ok: false }); + expect(verifyCandidates({ ...files, ids: ['fx-1'], by: 'candidate', day: '2026-11-02' })).toMatchObject({ ok: false }); + expect(verifyCandidates({ ...files, ids: [], by: 'Mark', day: '2026-11-02' })).toMatchObject({ ok: false }); + expect(verifyCandidates({ ...files, ids: ['fx-1', 'nope'], by: 'Mark', day: '2026-11-02' })).toEqual({ ok: false, problems: ["no candidate 'nope'"] }); + const bad = { candidates: { 'biblical.json': [candidate('fx-bad', { text: { en: 'A lonely road.' } })] }, library: {} }; + const result = verifyCandidates({ ...bad, ids: ['fx-bad'], by: 'Mark', day: '2026-11-02' }); + expect(result.ok).toBe(false); + expect(!result.ok && result.problems.join(' ')).toMatch(/forbidden-word/); + }); +}); diff --git a/scripts/validate-library.ts b/scripts/validate-library.ts index 908c113..847e7cf 100644 --- a/scripts/validate-library.ts +++ b/scripts/validate-library.ts @@ -5,14 +5,21 @@ * Passes when the library has no problems AND every fixture fails with the rule * it names. A fixture that passes means a rule has stopped firing: that fails * the run, the same as a bad sentence. + * + * It also holds the candidates in content/candidates/ to every rule but + * verification (day-sentence.md P8), and the app's build runs it first, so what + * ships is what passed (P5). ROSEA_LIBRARY_DIR swaps the library folder, for the + * e2e build only; the app's Vite config reads the same variable. */ -import { readFileSync, readdirSync } from 'node:fs'; -import { join } from 'node:path'; +import { existsSync, readFileSync, readdirSync } from 'node:fs'; +import { join, relative, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { validateCandidates } from '@rosea/content/candidates'; import { validateEntry, validateLibrary, type Rule } from '@rosea/content/validate'; const root = fileURLToPath(new URL('..', import.meta.url)); -const libraryDir = join(root, 'content', 'library'); +const libraryDir = resolve(root, process.env['ROSEA_LIBRARY_DIR'] ?? join('content', 'library')); +const candidatesDir = join(root, 'content', 'candidates'); const fixturesDir = join(root, 'content', 'fixtures'); const jsonIn = (dir: string): string[] => @@ -27,7 +34,7 @@ const entries: unknown[] = []; for (const file of jsonIn(libraryDir)) { const data: unknown = JSON.parse(readFileSync(join(libraryDir, file), 'utf8')); if (!Array.isArray(data)) { - console.error(`content/library/${file}: must be an array of entries`); + console.error(`${relative(root, libraryDir)}/${file}: must be an array of entries`); failed = true; continue; } @@ -44,9 +51,27 @@ const sunset = entries.filter( ).length; console.log( - `library: ${entries.length} entr${entries.length === 1 ? 'y' : 'ies'} in ${jsonIn(libraryDir).length} files, ${sunset} sunset (release needs 365)` + `library (${relative(root, libraryDir).replaceAll('\\', '/')}): ${entries.length} entr${entries.length === 1 ? 'y' : 'ies'} in ${jsonIn(libraryDir).length} files, ${sunset} sunset (release needs 365)` ); +// ── the candidates: proposed, not verified ───────────────────────────────── +const candidates: unknown[] = []; +const candidateFiles = existsSync(candidatesDir) ? jsonIn(candidatesDir) : []; +for (const file of candidateFiles) { + const data: unknown = JSON.parse(readFileSync(join(candidatesDir, file), 'utf8')); + if (!Array.isArray(data)) { + console.error(`content/candidates/${file}: must be an array of candidates`); + failed = true; + continue; + } + candidates.push(...data); +} +for (const p of validateCandidates(candidates, entries)) { + console.error(`candidate ${p.id} [${p.rule}] ${p.message}`); + failed = true; +} +console.log(`candidates: ${candidates.length} in ${candidateFiles.length} files, waiting for a person to verify them`); + // ── the fixtures: each must FAIL, with its named rule ─────────────────────── interface Fixture { expect: Rule; diff --git a/scripts/verify-sentences.ts b/scripts/verify-sentences.ts new file mode 100644 index 0000000..d884894 --- /dev/null +++ b/scripts/verify-sentences.ts @@ -0,0 +1,59 @@ +/** + * `pnpm library:verify --by ` — the author's command (day-sentence.md P8). + * + * Run it only after reading each sentence at its `check.url` and confirming the words + * and their public-domain status yourself. It moves those candidates from + * content/candidates/ into content/library/, stamped with your name and today's + * date, and refuses (changing nothing) if the library would then fail + * `validate:library`. + * + * **Agents never run this.** `verifiedBy` records that a person checked the source + * (phase0-workspace.md D4); an agent that runs it makes that record false. + */ +import { readFileSync, readdirSync, writeFileSync, existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { verifyCandidates, type Files } from '@rosea/content/candidates'; +import { localDay } from '@rosea/engine'; + +const root = fileURLToPath(new URL('..', import.meta.url)); +const libraryDir = join(root, 'content', 'library'); +const candidatesDir = join(root, 'content', 'candidates'); + +const args = process.argv.slice(2); +const byAt = args.indexOf('--by'); +const by = byAt >= 0 ? (args[byAt + 1] ?? '') : ''; +const ids = args.filter((a, i) => a !== '--by' && i !== byAt + 1 && !a.startsWith('--')); + +if (byAt < 0 || ids.length === 0) { + console.error('usage: pnpm library:verify […] --by '); + process.exit(2); +} + +const read = (dir: string): Files => { + if (!existsSync(dir)) return {}; + const files: Record = {}; + for (const f of readdirSync(dir).filter((f) => f.endsWith('.json')).sort()) { + const data: unknown = JSON.parse(readFileSync(join(dir, f), 'utf8')); + if (!Array.isArray(data)) throw new Error(`${dir}/${f}: must be an array`); + files[f] = data; + } + return files; +}; + +// The day on this machine's own clock and zone, as a person would write it. +const day = localDay(Date.now(), Intl.DateTimeFormat().resolvedOptions().timeZone); +const result = verifyCandidates({ candidates: read(candidatesDir), library: read(libraryDir), ids, by, day }); + +if (!result.ok) { + for (const p of result.problems) console.error(p); + console.error('Nothing was moved.'); + process.exit(1); +} + +const write = (dir: string, files: Files): void => { + for (const [f, entries] of Object.entries(files)) writeFileSync(join(dir, f), `${JSON.stringify(entries, null, 2)}\n`); +}; +write(libraryDir, result.library); +write(candidatesDir, result.candidates); +console.log(`Verified by ${by.trim()} on ${day}: ${result.moved.join(', ')}. Run pnpm validate:library, then commit.`);