From 6551bb8ce81ff6e85bedc46301fca20379334cd0 Mon Sep 17 00:00:00 2001 From: "Ali G." Date: Tue, 24 Nov 2026 19:56:31 +0100 Subject: [PATCH 1/7] chore: ignore local mise configuration Keep each contributor's Node version pin in mise.local.toml out of the repository. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 2fc3574..7094293 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ node_modules/ .astro/ .generated/ dist/ +mise.local.toml \ No newline at end of file From e2991dbe91d25161af1484af228003ed2b3a4568 Mon Sep 17 00:00:00 2001 From: "Ali G." Date: Tue, 24 Nov 2026 19:57:39 +0100 Subject: [PATCH 2/7] feat: render conformance profiles, options and verification method Render the Specification Framework changes proposed in ARCH-ADR-7, ARCH-ADR-6 and ARCH-ADR-8, which the Wallet Building Block 2.0 draft uses. - Conformance profiles: toc.yml subsections under conformance-profiles resolve relative to each profile folder. Each introduction is served at /conformance-profiles// with a summary from its front matter. Functionality pages name their profile, the home page lists the profiles, and the sidebar groups them with Core and Extension badges. Generation fails without exactly one core, or on unknown or cyclic requires. - Options and conditions: options render nested beneath their variation point, with select, key, extension, presented_by and applies_when. A generated Options and conditions page lists what applies for each key and extension. Options count towards the requirement total. - Verification: derived from interaction (tested at the boundary, or audited for INTERNAL). observability is shown only when there is no interaction. - Root-absolute links and assets resolve against the specification root under the build base, so each specification only refers to its own files. - ADR pages linked from published pages are published under Resources. - toc.yml folder entries, empty sections, and terminology.yml and references.yml render instead of failing or showing raw YAML. - Fix "null" for empty documentation, trailing breaks in block-scalar descriptions, and URN contracts becoming broken links. Specifications that still use requirements/ render as before, with warnings, so Building Blocks can migrate one at a time. Co-Authored-By: Claude Opus 5.5 --- README.md | 14 + adapters/framework-model.mjs | 426 +++++++++++++++++++++ adapters/framework.mjs | 558 ++++++++++++++++++++++++---- src/styles/govstack.css | 18 + tests/conformance-profiles.test.mjs | 451 ++++++++++++++++++++++ tests/framework.test.mjs | 19 +- 6 files changed, 1401 insertions(+), 85 deletions(-) create mode 100644 adapters/framework-model.mjs create mode 100644 tests/conformance-profiles.test.mjs diff --git a/README.md b/README.md index 6e401d1..703c68f 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,20 @@ Every profile requires an explicit source, either `--source` or the `DOCS_SOURCE_ROOT` environment variable. There is no default, so a build cannot silently pick up a different or dirty checkout. +## Conformance profiles, options and verification + +Framework sources can use the layout of the Specification Framework's ARCH-ADR-7, ARCH-ADR-6 and ARCH-ADR-8. Sources that still use `requirements/` render as before, with warnings, so Building Blocks can migrate one at a time. + +- **Conformance profiles (ARCH-ADR-7).** `toc.yml` lists `conformance-profiles` as one subsection per profile folder, with `introduction.md` first. The pages of a subsection resolve relative to that folder. Each introduction is served at the folder's route (`/conformance-profiles//`), because the folder name is the profile id. Its front matter (`type`, `description`, `requires`, `role`, `reference_architecture`) becomes a summary above the page. Functionality pages name their profile, the home page lists the profiles, and the sidebar groups each profile with a Core or Extension badge. Generation fails unless there is exactly one `CORE`, `requires` names only extension profiles without cycles, and the core requires nothing. A functionality missing from its introduction's links, `conformance` and `extension` fields, and `metadata.yml` `extensions` produce warnings and are ignored. +- **Options and conditions (ARCH-ADR-6).** Options listed under a variation point's `options` render as cards nested beneath it, with `select`, `key`, `extension` (linked to the profile that meets the option), `presented_by`, `applies_when` and `applies_when_all`. A generated *Options and conditions* page lists, for every option key and every extension profile used in a condition, the requirements that apply when it holds. Conditions link to it. Options count towards the requirement total. Structural rules (at least two options, `select.min`, `n.m` ids, no `interaction` on a variation point, the core meeting `min` without extensions) are reported as warnings. +- **Verification (ARCH-ADR-8).** With an `interaction`, a card shows how the requirement is verified: tested at that boundary, or audited against evidence for `INTERNAL`. `observability` is then not shown, and a value that disagrees is reported. Without an `interaction`, as in the cross-functional requirements, `observability` is shown as before. + +A local link or image path that starts with `/` resolves against the specification's root, and is published under the build's `--base`. With `--base /bb/wallet/`, `/assets/cover.svg` becomes `/bb/wallet/assets/cover.svg`, so a specification only ever refers to its own assets. A path that escapes the root fails. + +Decision records are not part of `toc.yml` yet. A Markdown page under `ADR/` that a published page links to is published as if it were listed under `resources`, with a warning, and its own links to other decision records are followed. Unlinked records are not published, and a link to any other unlisted Markdown page still fails. + +`toc.yml` entries ending in `/` publish that folder's files with a download index, relative to their section, and fail if the folder does not exist. `terminology.yml` (`terms` with `term`/`definition`, or `entry` with `designation`/`description`) and `references.yml` render as pages, with one heading per term. Any other YAML page is shown verbatim. + ## OpenAPI references Framework sources can opt into Scalar references with `api-references.yml`: diff --git a/adapters/framework-model.mjs b/adapters/framework-model.mjs new file mode 100644 index 0000000..09b0aa2 --- /dev/null +++ b/adapters/framework-model.mjs @@ -0,0 +1,426 @@ +// Source model of a framework-format specification: toc.yml structure, conformance +// profiles (ARCH-ADR-7), options and conditions (ARCH-ADR-6), and the verification +// method that follows from a requirement's interaction (ARCH-ADR-8). +// +// Nothing here changes normative content. It reads front matter, checks the +// structural rules the renderer depends on, and reports the rest as warnings. + +import path from 'node:path'; + +import YAML from 'yaml'; + +export const PROFILE_SECTION = 'conformance-profiles'; +const KEBAB = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; +const PROFILE_TYPES = new Set(['CORE', 'EXTENSION']); + +function assertSafeEntry(entry, where) { + if (typeof entry !== 'string' || !entry.trim()) { + throw new Error(`toc.yml: ${where}: every entry must be a file or folder name`); + } + if (path.posix.isAbsolute(entry) || entry.split('/').includes('..')) { + throw new Error(`toc.yml: ${where}: entry must stay inside its section: ${entry}`); + } +} + +// Reads toc.yml into ordered sections. A section's items are pages, folders (an +// entry ending in "/"), titled subsections, or, under conformance-profiles, one +// subsection per profile whose pages resolve relative to the profile's folder. +export function parseToc(toc) { + const sections = []; + const ordered = ['README.md']; + const seen = new Set(ordered); + const folders = []; + const profiles = []; + + function entryItem(directory, entry, where) { + assertSafeEntry(entry, where); + const source = path.posix.join(directory, entry); + if (entry.endsWith('/')) { + const folder = source.replace(/\/+$/, ''); + folders.push(folder); + return { kind: 'folder', source: folder }; + } + if (seen.has(source)) throw new Error(`toc.yml: ${source} is listed twice`); + seen.add(source); + ordered.push(source); + return { kind: 'page', source }; + } + + for (const [section, entries] of Object.entries(toc)) { + if (entries === null || entries === undefined) { + sections.push({ key: section, items: [] }); + continue; + } + if (!Array.isArray(entries)) throw new Error(`toc.yml: ${section} must be a list`); + const items = entries.map((entry) => { + if (!entry || typeof entry !== 'object' || Array.isArray(entry)) { + if (section === PROFILE_SECTION) { + throw new Error( + `toc.yml: ${PROFILE_SECTION} lists one subsection per profile folder, not the page ${JSON.stringify(entry)}`, + ); + } + return entryItem(section, entry, section); + } + const names = Object.keys(entry); + if (names.length !== 1 || !names[0].trim()) { + throw new Error(`toc.yml: ${section}: a subsection has exactly one non-empty title`); + } + const [name] = names; + const children = entry[name]; + if (!Array.isArray(children) || !children.length) { + throw new Error(`toc.yml: ${section}: subsection ${name} has no pages`); + } + for (const child of children) { + if (child && typeof child === 'object') { + throw new Error(`toc.yml: ${section}: subsection ${name} contains another subsection; subsections are one level deep`); + } + } + if (section !== PROFILE_SECTION) { + return { + kind: 'group', + label: name, + items: children.map((child) => entryItem(section, child, `${section}/${name}`)), + }; + } + if (!KEBAB.test(name)) { + throw new Error(`toc.yml: conformance profile folder ${name} must be kebab-case; the folder name is the profile id`); + } + if (profiles.some((profile) => profile.id === name)) { + throw new Error(`toc.yml: conformance profile ${name} is listed twice`); + } + if (children[0] !== 'introduction.md') { + throw new Error(`toc.yml: conformance profile ${name} must list introduction.md first`); + } + const directory = path.posix.join(section, name); + const profileItems = children.map((child) => entryItem(directory, child, directory)); + const pages = profileItems.filter((item) => item.kind === 'page').map((item) => item.source); + profiles.push({ id: name, directory, introduction: pages[0], pages }); + return { kind: 'profile', id: name, items: profileItems }; + }); + sections.push({ key: section, items }); + } + return { sections, ordered, pageSources: new Set(ordered), folders, profiles }; +} + +// The profile that a page belongs to, by where its file is. +export function profileForSource(profiles, source) { + return profiles.find((profile) => source.startsWith(`${profile.directory}/`)); +} + +function asList(value) { + if (value === undefined || value === null || value === '') return []; + return Array.isArray(value) ? value.map(String) : [String(value)]; +} + +// Completes each profile from the front matter of its introduction and checks the +// rules of ARCH-ADR-7 that the rendered navigation and links depend on. +export function resolveProfiles(tocProfiles, pagesBySource, warnings) { + const profiles = tocProfiles.map((profile) => { + const page = pagesBySource.get(profile.introduction); + const frontmatter = page.frontmatter; + if (!PROFILE_TYPES.has(frontmatter.type)) { + throw new Error(`${profile.introduction}: type must be CORE or EXTENSION, found ${JSON.stringify(frontmatter.type ?? null)}`); + } + const functionalities = profile.pages.filter((source) => source !== profile.introduction); + for (const source of functionalities) { + if (!source.startsWith(`${profile.directory}/functionalities/`)) { + warnings.push(`${source}: pages of a conformance profile other than its introduction belong in its functionalities/ folder`); + } + } + if (!functionalities.length) warnings.push(`${profile.introduction}: conformance profile ${profile.id} lists no functionality`); + return { + ...profile, + title: page.title, + type: frontmatter.type, + description: typeof frontmatter.description === 'string' ? frontmatter.description.trim() : '', + requires: asList(frontmatter.requires), + role: frontmatter.role ? String(frontmatter.role) : '', + referenceArchitecture: frontmatter.reference_architecture ? String(frontmatter.reference_architecture) : '', + functionalities, + }; + }); + if (!profiles.length) return profiles; + const cores = profiles.filter((profile) => profile.type === 'CORE'); + if (cores.length !== 1) { + throw new Error( + `toc.yml: a specification has exactly one CORE conformance profile, found ${cores.length}${cores.length ? ` (${cores.map((profile) => profile.id).join(', ')})` : ''}`, + ); + } + const byId = new Map(profiles.map((profile) => [profile.id, profile])); + for (const profile of profiles) { + if (profile.type === 'CORE' && profile.requires.length) { + throw new Error(`${profile.introduction}: the core never depends on an extension, but requires ${profile.requires.join(', ')}`); + } + for (const id of profile.requires) { + if (byId.get(id)?.type !== 'EXTENSION') { + throw new Error(`${profile.introduction}: requires ${id}, which is not an extension profile in toc.yml`); + } + } + } + const visiting = new Set(); + const done = new Set(); + function visit(profile, trail) { + if (done.has(profile.id)) return; + if (visiting.has(profile.id)) { + throw new Error(`toc.yml: conformance profiles require each other in a cycle: ${[...trail, profile.id].join(' → ')}`); + } + visiting.add(profile.id); + for (const id of profile.requires) visit(byId.get(id), [...trail, profile.id]); + visiting.delete(profile.id); + done.add(profile.id); + } + for (const profile of profiles) visit(profile, []); + return profiles; +} + +// Each functionality listed in an introduction's Functionalities table is a file of +// that profile, and each file of the profile is listed (ARCH-ADR-7, compiler checks). +export function checkProfileFunctionalityLinks(profile, linkedTargets, warnings) { + const listed = new Set(linkedTargets.filter((target) => target.startsWith(`${profile.directory}/functionalities/`))); + for (const target of linkedTargets) { + if (/\/functionalities\/[^/]+\.md$/.test(target) && !target.startsWith(`${profile.directory}/`)) { + warnings.push(`${profile.introduction}: links to ${target}, a functionality of another conformance profile`); + } + } + for (const source of profile.functionalities) { + if (!listed.has(source)) warnings.push(`${profile.introduction}: does not link to its functionality ${source}`); + } +} + +// All requirements of a functionality, with options flattened after their +// variation point, each with the anchor its card is rendered under. +export function flattenRequirements(requirements = []) { + const flat = []; + requirements.forEach((requirement, index) => { + const anchor = `requirement-${index + 1}`; + flat.push({ requirement, anchor, parent: undefined }); + (Array.isArray(requirement?.options) ? requirement.options : []).forEach((option, optionIndex) => { + flat.push({ requirement: option, anchor: `${anchor}-option-${optionIndex + 1}`, parent: requirement }); + }); + }); + return flat; +} + +// Indexes the keys of options and the ids of extension profiles, which are the +// names applies_when, applies_when_all and presented_by may use, and collects the +// requirements that each name makes apply (the views by key of ARCH-ADR-6). +export function collectConditions(functionalityPages, profiles, warnings) { + const names = new Map(); + for (const profile of profiles) { + if (profile.type === 'EXTENSION') names.set(profile.id, { kind: 'extension', name: profile.id, profile, uses: [] }); + } + for (const page of functionalityPages) { + for (const entry of flattenRequirements(page.frontmatter.requirements)) { + const key = entry.requirement?.key; + if (!entry.parent || key === undefined || key === null || key === '') continue; + const name = String(key); + if (names.has(name)) { + warnings.push(`${page.sourceName}: option key ${name} is not unique across the options and extension profiles of the specification`); + continue; + } + names.set(name, { kind: 'option', name, page, ...entry, uses: [] }); + } + } + const profileIds = new Set(profiles.map((profile) => profile.id)); + for (const page of functionalityPages) { + const fileConditions = asList(page.frontmatter.applies_when); + const fileAllConditions = asList(page.frontmatter.applies_when_all); + for (const name of [...fileConditions, ...fileAllConditions]) { + if (!names.has(name)) warnings.push(`${page.sourceName}: applies_when names ${name}, which is neither an option key nor an extension profile`); + else names.get(name).uses.push({ page, anchor: undefined, requirement: undefined, mode: fileAllConditions.includes(name) ? 'all' : 'any' }); + } + for (const entry of flattenRequirements(page.frontmatter.requirements)) { + const requirement = entry.requirement ?? {}; + for (const [field, mode] of [['applies_when', 'any'], ['applies_when_all', 'all']]) { + for (const name of asList(requirement[field])) { + if (!names.has(name)) { + warnings.push(`${page.sourceName}: ${field} names ${name}, which is neither an option key nor an extension profile`); + continue; + } + names.get(name).uses.push({ page, ...entry, mode }); + } + } + for (const name of asList(requirement.presented_by)) { + if (!names.has(name)) warnings.push(`${page.sourceName}: presented_by names ${name}, which is neither an option key nor an extension profile`); + } + if (requirement.extension !== undefined && requirement.extension !== null && requirement.extension !== '') { + const extension = String(requirement.extension); + if (!entry.parent) { + // A requirement-level `extension` is the legacy ARCH-ADR-7 Option 3 field, handled by the caller. + } else if (!profileIds.size) { + warnings.push(`${page.sourceName}: option is met by claiming ${extension}, but the specification declares no conformance profiles`); + } else if (names.get(extension)?.kind !== 'extension') { + warnings.push(`${page.sourceName}: option is met by claiming ${extension}, which is not an extension profile in toc.yml`); + } + } + } + } + return names; +} + +// Structural checks on variation points and options (ARCH-ADR-6). They are warnings: +// drafts are rendered as written so that Working Groups can see what to correct. +export function checkOptions(page, profile, warnings) { + for (const requirement of page.frontmatter.requirements ?? []) { + if (!requirement || typeof requirement !== 'object') continue; + if (requirement.option_of !== undefined) { + warnings.push(`${page.sourceName}: option_of is replaced by listing options beneath their variation point (ARCH-ADR-6)`); + } + const options = Array.isArray(requirement.options) ? requirement.options : undefined; + if (requirement.level === 'OPTION' && !options) { + warnings.push(`${page.sourceName}: a requirement with level OPTION sits in the options list of a variation point`); + } + if (!requirement.select && !options) continue; + if (!requirement.select || !options) { + warnings.push(`${page.sourceName}: a variation point needs both select and options`); + continue; + } + const min = requirement.select.min ?? 1; + if (options.length < 2) warnings.push(`${page.sourceName}: a variation point has at least two options`); + if (!(Number.isInteger(min) && min >= 1 && min <= options.length)) { + warnings.push(`${page.sourceName}: select.min must be at least 1 and no greater than the number of options`); + } + if (requirement.select.max !== undefined && !(Number.isInteger(requirement.select.max) && requirement.select.max >= min)) { + warnings.push(`${page.sourceName}: select.max must be at least select.min`); + } + for (const field of ['interaction', 'test', 'api_operation_id']) { + if (requirement[field]) warnings.push(`${page.sourceName}: a variation point carries no ${field}; it is verified by counting the options that pass`); + } + const parentId = requirement.id ? String(requirement.id) : ''; + for (const option of options) { + if (option?.level !== 'OPTION') warnings.push(`${page.sourceName}: option ${option?.key || option?.id || '(unnamed)'} must have level OPTION`); + if (option?.select || option?.options) warnings.push(`${page.sourceName}: an option has no select and no options`); + const optionId = option?.id ? String(option.id) : ''; + if (optionId && (!parentId || !optionId.startsWith(`${parentId}.`) || !/^\d+$/.test(optionId.slice(parentId.length + 1)))) { + warnings.push(`${page.sourceName}: option ${optionId} must be numbered ${parentId || 'n'}.m after its variation point`); + } + } + if (profile?.type === 'CORE') { + const withoutExtension = options.filter((option) => !option?.extension).length; + if (withoutExtension < min) { + warnings.push(`${page.sourceName}: in the core, at least select.min options of a variation point are met without an extension`); + } + } + } +} + +const BOUNDARY = { + SERVICE_API: 'Service API', + CONSUMED_API: 'consumed API', + PROTOCOL: 'protocol', + EVENT: 'event', + USER_INTERFACE: 'user interface', + DEVICE: 'device', + FILE: 'file', +}; + +// How a requirement is verified (ARCH-ADR-8). With an interaction, the method +// follows from it and observability is no longer read. Without one, as in the +// cross-functional requirements, observability is read as before. +export function verificationOf(requirement, { isVariationPoint, isExtensionOption }) { + if (isVariationPoint) return { method: 'counted', label: 'Counts the options that pass' }; + if (isExtensionOption) return { method: 'extension', label: "By the extension's tests" }; + const interaction = requirement.interaction; + if (interaction === 'INTERNAL') { + return { method: 'auditable', label: 'Audited against evidence' }; + } + if (BOUNDARY[interaction]) { + return { method: 'observable', label: `Tested at the ${BOUNDARY[interaction]} boundary` }; + } + if (interaction) return { method: 'unknown', label: `Unknown interaction ${interaction}` }; + if (requirement.observability) return { method: 'legacy', label: undefined }; + return { method: 'unclassified', label: 'Unclassified' }; +} + +export function observabilityWarning(requirement, verification, sourceName) { + if (!requirement.observability || verification.method === 'legacy') return undefined; + const derived = { observable: 'OBSERVABLE', auditable: 'AUDITABLE' }[verification.method]; + if (derived && derived !== requirement.observability) { + return `${sourceName}: observability ${requirement.observability} disagrees with interaction ${requirement.interaction}, which is verified as ${derived}; correct the interaction`; + } + return `${sourceName}: observability is no longer read in a Building Block specification; the verification method follows from interaction`; +} + +function yamlText(value) { + if (value === undefined || value === null) return ''; + return String(value).trim(); +} + +function terminologyEntries(data) { + const list = Array.isArray(data) ? data : data?.terms ?? data?.entries ?? data?.terminology; + if (!Array.isArray(list)) return undefined; + return list.map((item) => { + const entry = item?.entry ?? item ?? {}; + return { + term: yamlText(entry.term ?? entry.designation), + abbreviation: yamlText(entry.abbreviation), + definition: yamlText(entry.definition ?? entry.description), + source: yamlText(entry.source ?? entry.designated_at), + origin: yamlText(entry.origin), + notes: asList(entry.notes ?? entry.note).map(yamlText).filter(Boolean), + related: asList(entry.related).map(yamlText).filter(Boolean), + }; + }); +} + +function referenceEntries(data) { + const list = Array.isArray(data) ? data : data?.references; + if (!Array.isArray(list)) return undefined; + return list.map((item) => ({ + title: yamlText(item?.title ?? item?.name), + url: yamlText(item?.url ?? item?.link), + date: yamlText(item?.date), + abstract: yamlText(item?.abstract ?? item?.description), + })); +} + +function markdownLinkText(value) { + return value.replace(/([\\[\]])/g, '\\$1'); +} + +// Renders terminology.yml and references.yml as Markdown, so that they go through +// the same heading, anchor and link handling as every other page. Any other YAML +// page is shown verbatim, so that nothing it says is lost or reinterpreted. +export function yamlPage(sourceName, text) { + const base = path.posix.basename(sourceName).replace(/\.ya?ml$/, ''); + const data = YAML.parse(text); + if (base === 'terminology') { + const entries = terminologyEntries(data); + if (entries) { + const body = entries + .filter((entry) => entry.term) + .map((entry) => { + const heading = entry.abbreviation ? `${entry.term} (${entry.abbreviation})` : entry.term; + const lines = [`## ${heading}`, '', entry.definition || '*No definition.*']; + for (const note of entry.notes) lines.push('', `*Note:* ${note}`); + const facts = [ + entry.source ? `Source: ${entry.source}` : '', + entry.origin ? `Origin: ${entry.origin}` : '', + entry.related.length ? `Related: ${entry.related.join(', ')}` : '', + ].filter(Boolean); + if (facts.length) lines.push('', `

${facts.map((fact) => fact.replaceAll('&', '&').replaceAll('<', '<')).join(' · ')}

`); + return lines.join('\n'); + }) + .join('\n\n'); + return { title: 'Terminology', markdown: `${body}\n` }; + } + } + if (base === 'references') { + const entries = referenceEntries(data); + if (entries) { + const body = entries + .filter((entry) => entry.title || entry.url) + .map((entry) => { + const title = markdownLinkText(entry.title || entry.url); + const link = entry.url ? `[${title}](<${entry.url}>)` : title; + const lines = [`- ${link}${entry.date ? ` (${entry.date})` : ''}`]; + if (entry.abstract) lines.push(`\n ${entry.abstract.replaceAll('\n', ' ')}`); + return lines.join('\n'); + }) + .join('\n'); + return { title: 'References', markdown: `${body}\n` }; + } + } + const fence = '`'.repeat(Math.max(3, ...[...text.matchAll(/`+/g)].map((match) => match[0].length + 1))); + return { title: base, markdown: `${fence}yaml\n${text.replace(/\n$/, '')}\n${fence}\n` }; +} diff --git a/adapters/framework.mjs b/adapters/framework.mjs index 43af18e..a06cfaa 100644 --- a/adapters/framework.mjs +++ b/adapters/framework.mjs @@ -24,6 +24,19 @@ import YAML from 'yaml'; import { robotsContent } from '../scripts/publication.mjs'; import { isPublishableSupportPath } from '../scripts/support-paths.mjs'; import { apiReferenceMarkup, apiReferenceSidebar, prepareApiReferences } from '../scripts/api-references.mjs'; +import { + PROFILE_SECTION, + checkOptions, + checkProfileFunctionalityLinks, + collectConditions, + flattenRequirements, + observabilityWarning, + parseToc, + profileForSource, + resolveProfiles, + verificationOf, + yamlPage, +} from './framework-model.mjs'; const execFileAsync = promisify(execFile); const parser = unified().use(remarkParse).use(remarkGfm).use(remarkFrontmatter, ['yaml']); @@ -46,7 +59,7 @@ export function routeFor(source) { if (source === 'README.md') return ''; const route = source.endsWith('/README.md') ? source.slice(0, -'/README.md'.length) - : source.slice(0, -'.md'.length); + : source.replace(/\.(?:md|ya?ml)$/i, ''); return route .split('/') .map((segment) => slug(segment)) @@ -74,6 +87,19 @@ function safeRelativeTarget(sourceName, target, directory = path.posix.dirname(s return normalized; } +function isExternalReference(reference) { + return /^[A-Za-z][A-Za-z+.-]*:/.test(reference) || reference.startsWith('//'); +} + +// A local reference resolves against its page, or, with a leading "/", against the +// specification root. The build's base is that root, so a specification published +// under a project subpath only ever refers to its own pages and assets. +function localTarget(sourceName, pathname) { + if (!pathname.startsWith('/')) return safeRelativeTarget(sourceName, pathname); + const relative = pathname.replace(/^\/+/, ''); + return relative ? safeRelativeTarget(sourceName, relative, '.') : '.'; +} + function sourceFrontmatter(tree) { const node = tree.children.find((child) => child.type === 'yaml'); if (!node) return { node: undefined, value: {} }; @@ -234,13 +260,6 @@ function localReferences(tree) { return references; } -function discoverPages(toc) { - const ordered = ['README.md']; - for (const [section, entries] of Object.entries(toc)) { - ordered.push(...entries.map((entry) => path.posix.join(section, entry))); - } - return { ordered, pages: new Set(ordered) }; -} function splitReference(url) { const hashAt = url.indexOf('#'); @@ -266,20 +285,11 @@ function collectReferencedSupportPaths(pages, pageSources) { const references = new Set(); for (const page of pages) { for (const reference of localReferences(page.tree)) { - if ( - /^[A-Za-z][A-Za-z+.-]*:/.test(reference) || - reference.startsWith('//') || - reference.startsWith('/') || - reference.startsWith('#') - ) { - continue; - } + if (isExternalReference(reference) || reference.startsWith('#')) continue; const { pathname } = splitReference(reference); if (!pathname) continue; - const target = safeRelativeTarget( - page.sourceName, - decodedPathname(page.sourceName, pathname), - ); + const target = localTarget(page.sourceName, decodedPathname(page.sourceName, pathname)); + if (target === '.') continue; if (target.endsWith('.md')) { if (!pageSources.has(target)) { throw new Error( @@ -292,7 +302,7 @@ function collectReferencedSupportPaths(pages, pageSources) { if ([...pageSources].some((source) => source.startsWith(`${directory}/`))) continue; references.add(target); } - for (const requirement of page.frontmatter.requirements ?? []) { + for (const { requirement } of flattenRequirements(page.frontmatter.requirements)) { for (const [field, value] of [ ['contract', requirement?.contract], ['test', requirement?.test], @@ -337,7 +347,7 @@ function referencedSupportPathIncludes(relative, referencedPaths) { } function rewriteReference({ url, sourceName, pageRoutes, pageAnchors, base }) { - if (/^[A-Za-z][A-Za-z+.-]*:/.test(url) || url.startsWith('//') || url.startsWith('/')) return url; + if (isExternalReference(url)) return url; if (url.startsWith('#')) { const id = decodeURIComponent(url.slice(1)); if (id && !pageAnchors.get(sourceName)?.has(id)) { @@ -346,7 +356,8 @@ function rewriteReference({ url, sourceName, pageRoutes, pageAnchors, base }) { return url; } const { pathname, query, fragment } = splitReference(url); - const target = safeRelativeTarget(sourceName, pathname); + const target = localTarget(sourceName, pathname); + if (target === '.') return `${baseUrl(base)}${query}${fragment}`; if (pageRoutes.has(target)) { if (fragment) { const id = decodeURIComponent(fragment.slice(1)); @@ -457,7 +468,8 @@ function documentationSections(documentation = '') { } function rootReference(value, pageRoutes, base) { - const { pathname, query, fragment } = splitReference(value); + const { query, fragment, ...parts } = splitReference(value); + const pathname = parts.pathname.replace(/^\/+/, ''); if (pageRoutes.has(pathname)) { const route = pageRoutes.get(pathname); return `${baseUrl(base, route ? `${route}/` : '')}${query}${fragment}`; @@ -465,15 +477,74 @@ function rootReference(value, pageRoutes, base) { return `${baseUrl(base, pathname)}${query}${fragment}`; } -function requirementCard(requirement, index, pageRoutes, base) { +function asNames(value) { + if (value === undefined || value === null || value === '') return []; + return (Array.isArray(value) ? value : [value]).map(String); +} + +// A condition, option key or extension id, linked to its view when there is one. +function conditionChip(name, context) { + const label = `${htmlEscape(name)}`; + const anchor = context.keyView?.anchors.get(name); + if (!anchor) return label; + return `${label}`; +} + +function conditionList(names, context) { + return names.map((name) => conditionChip(name, context)).join(', '); +} + +function profileHref(profile, context) { + const route = context.pageRoutes.get(profile.introduction); + return baseUrl(context.base, route ? `${route}/` : ''); +} + +function profileLink(id, context) { + const profile = context.profilesById?.get(id); + if (!profile) return `${htmlEscape(id)}`; + return `${htmlEscape(profile.title)}`; +} + +function profileTypeLabel(profile) { + return profile.type === 'CORE' ? 'Core' : 'Extension'; +} + +function conditionRow(field, names, context) { + if (!names.length) return undefined; + const label = names.length === 1 ? 'Applies when' : field === 'applies_when_all' ? 'Applies when all of' : 'Applies when any of'; + return [label, conditionList(names, context)]; +} + +// A contract or test: a source path links to its published page or file, a web URL +// links as written, and any other identifier, such as a specification URN, is shown +// as written without a link. +function referenceValue(value, context) { + const text = String(value); + const label = `${htmlEscape(text)}`; + if (/^https?:\/\//i.test(text)) return `${label}`; + if (isExternalReference(text)) return label; + return `${label}`; +} + +function requirementCard(requirement, anchor, context, parent) { + const options = !parent && Array.isArray(requirement.options) ? requirement.options : []; + const isVariationPoint = !parent && Boolean(requirement.select || options.length); + const isOption = Boolean(parent || requirement.option_of); + const extension = parent && requirement.extension ? String(requirement.extension) : ''; const permanentId = requirement.id ? String(requirement.id) : 'Unnumbered draft'; - const key = requirement.key ? `${htmlEscape(requirement.key)}` : ''; - const kind = requirement.select ? 'Variation point' : requirement.option_of ? 'Option' : 'Requirement'; + const kind = isVariationPoint ? 'Variation point' : isOption ? 'Option' : 'Requirement'; const cssKind = kind.toLowerCase().replaceAll(' ', '-'); + const verification = verificationOf(requirement, { isVariationPoint, isExtensionOption: Boolean(extension) }); + const observability = observabilityWarning(requirement, verification, context.sourceName); + if (observability) context.warnings.push(observability); + if (verification.method === 'unclassified' && !requirement.option_of && !(requirement.select && !options.length)) { + context.warnings.push(`${context.sourceName}: requirement ${requirement.id || `“${String(requirement.statement ?? '').slice(0, 60)}”`} has no interaction and is reported as unclassified`); + } + const key = requirement.key ? conditionChip(String(requirement.key), context).replace('', '') : ''; const badges = [ ['Lifecycle', requirement.status], ['Level', requirement.level], - ['Observability', requirement.observability], + ['Observability', verification.method === 'legacy' ? requirement.observability : undefined], ['Mutability', requirement.mutability], ['Interaction', requirement.interaction], ] @@ -484,27 +555,36 @@ function requirementCard(requirement, index, pageRoutes, base) { ) .join(''); const rows = []; - if (requirement.select?.min !== undefined) rows.push(['Minimum selections', requirement.select.min]); + if (isVariationPoint && options.length) { + const min = requirement.select?.min ?? 1; + const max = requirement.select?.max; + rows.push([ + 'Selection', + htmlEscape(`Meet at least ${min} of its ${options.length} options${max !== undefined ? `, and declare at most ${max}` : ''}`), + ]); + } else if (requirement.select?.min !== undefined) { + rows.push(['Minimum selections', htmlEscape(requirement.select.min)]); + } if (requirement.option_of) { - rows.push(['Option of', requirement.option_of]); - rows.push(['Inherited option obligation', `Selected option under ${requirement.option_of}`]); + rows.push(['Option of', htmlEscape(requirement.option_of)]); + rows.push(['Inherited option obligation', htmlEscape(`Selected option under ${requirement.option_of}`)]); } - if (requirement.applies_when) rows.push(['Any of', requirement.applies_when.join(', ')]); - if (requirement.applies_when_all) rows.push(['All of', requirement.applies_when_all.join(', ')]); - if (requirement.contract) { - const href = rootReference(requirement.contract, pageRoutes, base); - rows.push(['Contract', `${htmlEscape(requirement.contract)}`]); + if (extension) rows.push(['Met by claiming', `${profileLink(extension, context)} extension`]); + const presentedBy = asNames(requirement.presented_by); + if (presentedBy.length) rows.push(['Presented by', conditionList(presentedBy, context)]); + for (const field of ['applies_when', 'applies_when_all']) { + const row = conditionRow(field, asNames(requirement[field]), context); + if (row) rows.push(row); } + if (verification.label) rows.push(['Verification', htmlEscape(verification.label)]); + if (requirement.contract) rows.push(['Contract', referenceValue(requirement.contract, context)]); if (requirement.api_operation_id) rows.push(['Operation', `${htmlEscape(requirement.api_operation_id)}`]); - if (requirement.test) { - const href = rootReference(requirement.test, pageRoutes, base); - rows.push(['Test', `${htmlEscape(requirement.test)}`]); - } + if (requirement.test) rows.push(['Test', referenceValue(requirement.test, context)]); const rowMarkup = rows .map(([label, value]) => `
${htmlEscape(label)}
${String(value)}
`) .join(''); - const documentation = documentationSections(requirement.documentation); + const documentation = documentationSections(requirement.documentation ?? ''); const visibleLabels = new Set(['Purpose', 'Prerequisite', 'Condition', 'Scope', 'Constraint', 'Documentation']); const visible = documentation .filter((section) => visibleLabels.has(section.label)) @@ -523,11 +603,16 @@ function requirementCard(requirement, index, pageRoutes, base) { const proofMarkup = proof ? `
Evidence and verification${proof}
` : ''; + const optionMarkup = options.length + ? `
+${options.map((option, index) => requirementCard(option ?? {}, `${anchor}-option-${index + 1}`, context, requirement)).join('\n')} +
` + : ''; - return `
+ return `
${kind} -
${inlineHtml(requirement.statement)}
+
${inlineHtml(requirement.statement)}
${htmlEscape(permanentId)}
${key ? `
Key${key}
` : ''} @@ -535,31 +620,67 @@ function requirementCard(requirement, index, pageRoutes, base) { ${rowMarkup ? `
${rowMarkup}
` : ''} ${visible} ${proofMarkup} + ${optionMarkup}
`; } -function functionalityMarkup(frontmatter, pageRoutes, base) { +function capabilityTitles(ids, context) { + return ids + .map((id) => { + const capability = context.capabilities.get(id); + if (!capability) { + context.warnings.push(`${context.sourceName}: realises ${id}, which is not a capability in metadata.yml`); + return `${htmlEscape(id)}`; + } + return htmlEscape(capability.title ?? id); + }) + .join(', '); +} + +function functionalityMarkup(frontmatter, context) { const requirements = frontmatter.requirements ?? []; if (!requirements.length) return undefined; const facts = []; - if (frontmatter.realises?.length) facts.push(['Capabilities', frontmatter.realises.join(', ')]); - if (frontmatter.conformance) facts.push(['Conformance', frontmatter.conformance]); - if (frontmatter.conformance === 'EXTENSION') facts.push(['Type', 'Extension']); - if (frontmatter.extension) facts.push(['Extension', String(frontmatter.extension)]); + if (context.profile) { + facts.push([ + 'Conformance profile', + `${profileLink(context.profile.id, context)} (${profileTypeLabel(context.profile).toLowerCase()})`, + ]); + if (frontmatter.conformance !== undefined || frontmatter.extension !== undefined) { + context.warnings.push(`${context.sourceName}: conformance and extension are ignored; a functionality belongs to the conformance profile whose folder holds it`); + } + } else { + if (frontmatter.conformance) facts.push(['Conformance', htmlEscape(frontmatter.conformance)]); + if (frontmatter.conformance === 'EXTENSION') facts.push(['Type', 'Extension']); + if (frontmatter.extension) facts.push(['Extension', htmlEscape(frontmatter.extension)]); + } + const realises = asNames(frontmatter.realises); + if (realises.length) facts.splice(context.profile ? 1 : 0, 0, ['Capabilities', capabilityTitles(realises, context)]); + for (const field of ['applies_when', 'applies_when_all']) { + const row = conditionRow(field, asNames(frontmatter[field]), context); + if (row) facts.push(row); + } const factMarkup = facts - .map(([label, value]) => `
${htmlEscape(label)}
${inlineHtml(value)}
`) + .map(([label, value]) => `
${htmlEscape(label)}
${value}
`) .join(''); const cards = requirements - .map((requirement, index) => requirementCard(requirement, index + 1, pageRoutes, base)) + .map((requirement, index) => requirementCard(requirement ?? {}, `requirement-${index + 1}`, context)) .join('\n'); + const optionCount = requirements.reduce( + (total, requirement) => total + (Array.isArray(requirement?.options) ? requirement.options.length : 0), + 0, + ); + const unnumbered = flattenRequirements(requirements).some(({ requirement }) => !requirement?.id); + const counted = `${requirements.length} requirement${requirements.length === 1 ? '' : 's'}`; + const optionText = optionCount ? `, and ${optionCount} option${optionCount === 1 ? '' : 's'} beneath its variation points` : ''; return { summary: `
-

${inlineHtml(frontmatter.description)}

+

${inlineHtml(String(frontmatter.description ?? '').trim())}

${factMarkup ? `
${factMarkup}
` : ''}
`, requirements: `## Requirements -

This functionality defines ${requirements.length} authoring-draft requirement${requirements.length === 1 ? '' : 's'}. “Unnumbered draft” reflects the source metadata and does not invent a permanent requirement identifier.

+

This functionality defines ${counted}${optionText}.${unnumbered ? ' “Unnumbered draft” reflects the source metadata and does not invent a permanent requirement identifier.' : ''}

${cards} @@ -568,6 +689,26 @@ ${cards} }; } +// The facts of a conformance profile, from the front matter of its introduction. +function profileMarkup(profile, context) { + const core = context.profiles.find((candidate) => candidate.type === 'CORE'); + const buildsOn = profile.type === 'CORE' + ? 'Every conformant software solution meets this profile' + : [core.id, ...profile.requires].map((id) => profileLink(id, context)).join(', '); + const facts = [ + ['Type', profile.type === 'CORE' ? 'Core' : 'Extension'], + ['Id', `${htmlEscape(profile.id)}`], + [profile.type === 'CORE' ? 'Claimed by' : 'Builds on', buildsOn], + ['Role', profile.role ? htmlEscape(profile.role) : ''], + ['Reference architecture', profile.referenceArchitecture ? `${htmlEscape(profile.referenceArchitecture)}` : ''], + ['Functionalities', htmlEscape(profile.functionalities.length)], + ].filter(([, value]) => value); + return `
+

${inlineHtml(profile.description)}

+
${facts.map(([label, value]) => `
${htmlEscape(label)}
${value}
`).join('')}
+
`; +} + function markdownTableCell(value) { return String(value ?? '').replaceAll('|', '\\|').replaceAll('\n', ' ').trim(); } @@ -596,7 +737,26 @@ function extensionsMetadata(extensions) { return rendered.length ? rendered.join('
') : 'None declared'; } -function homeMetadataMarkup(metadata, authors) { +function profilesTable(context) { + const core = context.profiles.find((profile) => profile.type === 'CORE'); + const rows = context.profiles.map((profile) => { + const href = profileHref(profile, context); + const buildsOn = profile.type === 'CORE' + ? '' + : [core.id, ...profile.requires].map((id) => `\`${id}\``).join(', '); + return `| [${markdownTableCell(profile.title)}](${href}) | \`${profile.id}\` | ${profileTypeLabel(profile)} | ${buildsOn} | ${markdownTableCell(profile.description)} |`; + }); + return `## Conformance profiles + +Every conformant software solution meets the core. A software solution may claim extensions in addition to it, and meets each extension it claims in full. + +| Profile | Id | Type | Builds on | Description | +| --- | --- | --- | --- | --- | +${rows.join('\n')} +`; +} + +function homeMetadataMarkup(metadata, authors, context) { const versions = metadata.versions ?? []; const version = versions.find((item) => item.latest) ?? versions[0] ?? {}; const facts = [ @@ -607,8 +767,14 @@ function homeMetadataMarkup(metadata, authors) { ['Owner group', metadata.owner_group ?? ''], ['Canonical URL', metadata.url ?? ''], ['Repository', metadata.repository ?? ''], - ['Extensions', extensionsMetadata(metadata.extensions)], ]; + if (context.profiles.length) { + if (metadata.extensions !== undefined) { + context.warnings.push('metadata.yml: extensions is ignored; conformance profiles are declared in the introduction.md of each profile folder'); + } + } else { + facts.push(['Extensions', extensionsMetadata(metadata.extensions)]); + } const capabilities = (metadata.capabilities ?? []) .map( (capability) => @@ -629,6 +795,7 @@ function homeMetadataMarkup(metadata, authors) { | --- | --- | ${facts.map(([label, value]) => `| ${markdownTableCell(label)} | ${markdownTableCell(value)} |`).join('\n')} +${context.profiles.length ? profilesTable(context) : ''} ## Capabilities ${capabilities} @@ -654,7 +821,7 @@ function generatedFrontmatter({ title, description, pagefind, apiReference }, un })}---\n\n`; } -function transformBody({ page, pageRoutes, pageAnchors, base, metadata, authors, unofficial }) { +function transformBody({ page, pageRoutes, pageAnchors, base, metadata, authors, unofficial, context }) { const { sourceName, source, tree, frontmatter, headings, title } = page; const replacements = []; if (page.frontmatterNode) { @@ -683,18 +850,23 @@ function transformBody({ page, pageRoutes, pageAnchors, base, metadata, authors, value: '##', }); } - replacements.push( - ...referenceReplacements({ tree, source, sourceName, pageRoutes, pageAnchors, base }), - ); + if (!page.generated) { + replacements.push( + ...referenceReplacements({ tree, source, sourceName, pageRoutes, pageAnchors, base }), + ); + } let body = applyReplacements(source, replacements, sourceName).replace(/^\s+/, ''); if (page.compatibilityAnchors?.size) { body = `${[...page.compatibilityAnchors].map((id) => ``).join('\n')}\n\n${body}`; } - const functionality = functionalityMarkup(frontmatter, pageRoutes, base); + const pageContext = { ...context, sourceName, profile: profileForSource(context.profiles, sourceName) }; + const profile = context.profiles.find((candidate) => candidate.introduction === sourceName); + if (profile) body = `${profileMarkup(profile, pageContext)}\n\n${body}`; + const functionality = profile ? undefined : functionalityMarkup(frontmatter, pageContext); if (functionality) { body = [functionality.summary, body, functionality.requirements].filter(Boolean).join('\n\n'); } - if (sourceName === 'README.md') body = `${homeMetadataMarkup(metadata, authors)}\n\n${body}`; + if (sourceName === 'README.md') body = `${homeMetadataMarkup(metadata, authors, context)}\n\n${body}`; const isArchive = sourceName.startsWith('resources/history/') || sourceName.includes('/legacy/'); if (isArchive) { body = `:::caution[Archived source]\nThis page preserves historical material and is not current conformance text.\n:::\n\n${body}`; @@ -708,15 +880,40 @@ function transformBody({ page, pageRoutes, pageAnchors, base, metadata, authors, return `${generatedFrontmatter({ title, description, pagefind: isArchive ? false : undefined }, unofficial)}${body}`; } -function sidebarFromToc(toc, pagesBySource) { +function sectionLabel(section) { + const words = section.replaceAll('-', ' ').replaceAll('_', ' '); + return words[0].toUpperCase() + words.slice(1); +} + +function sidebarFromToc(tocModel, pagesBySource, { profiles, keyView }) { const sidebar = [{ label: 'Home', slug: '' }]; - for (const [section, entries] of Object.entries(toc)) { - const items = entries.map((entry) => { - const source = path.posix.join(section, entry); - const page = pagesBySource.get(source); - return { label: page.title, slug: page.route }; - }); - sidebar.push({ label: section[0].toUpperCase() + section.slice(1), items }); + const link = (source, label) => { + const page = pagesBySource.get(source); + return { label: label ?? page.title, slug: page.route }; + }; + const item = (entry) => { + if (entry.kind === 'page') return link(entry.source); + if (entry.kind === 'folder') { + // Starlight adds the base to sidebar links itself. + return { label: `${path.posix.basename(entry.source)}/`, link: `/${entry.source}/` }; + } + if (entry.kind === 'group') return { label: entry.label, items: entry.items.map(item) }; + const profile = profiles.find((candidate) => candidate.id === entry.id); + return { + label: profile.title, + badge: { text: profile.type === 'CORE' ? 'Core' : 'Extension', variant: profile.type === 'CORE' ? 'note' : 'default' }, + items: entry.items.map((child) => + child.kind === 'page' && child.source === profile.introduction ? link(child.source, 'Introduction') : item(child), + ), + }; + }; + for (const section of tocModel.sections) { + const items = section.items.map(item); + if (section.key === PROFILE_SECTION && keyView) items.push({ label: keyView.title, slug: keyView.route }); + sidebar.push({ label: sectionLabel(section.key), items }); + } + if (keyView && !tocModel.sections.some((section) => section.key === PROFILE_SECTION)) { + sidebar.push({ label: keyView.title, slug: keyView.route }); } return sidebar; } @@ -939,7 +1136,7 @@ function redirectHtml(target, unofficial) { async function writeRedirects(siteRoot, pages, base, unofficial) { const redirects = []; for (const page of pages) { - if (page.sourceName === 'README.md') continue; + if (page.sourceName === 'README.md' || page.generated || !page.sourceName.endsWith('.md')) continue; const legacy = page.sourceName.replace(/\.md$/, '.html'); const target = baseUrl(base, page.route ? `${page.route}/` : ''); const output = path.join(siteRoot, 'public', legacy); @@ -959,16 +1156,18 @@ async function writeSupportDirectoryIndexes( referencedPaths, supportFiles, unofficial, + listedFolders = [], ) { const indexes = []; - const directories = new Set(); + const directories = new Set(listedFolders); const sourceReal = await realpath(sourceRoot); for (const page of pages) { for (const reference of localReferences(page.tree)) { - if (/^[A-Za-z][A-Za-z+.-]*:/.test(reference) || reference.startsWith('//')) continue; + if (isExternalReference(reference)) continue; const { pathname } = splitReference(reference); if (!pathname.endsWith('/')) continue; - const target = safeRelativeTarget(page.sourceName, pathname).replace(/\/+$/, ''); + const target = localTarget(page.sourceName, pathname).replace(/\/+$/, ''); + if (target === '.') continue; if ([...pageRoutes.keys()].some((source) => source.startsWith(`${target}/`))) continue; try { const sourcePath = path.join(sourceRoot, target); @@ -1045,10 +1244,10 @@ function addArchiveCompatibilityAnchors(loaded, warnings) { const bySource = new Map(loaded.map((page) => [page.sourceName, page])); for (const page of loaded) { for (const reference of localReferences(page.tree)) { - if (/^[A-Za-z][A-Za-z+.-]*:/.test(reference) || reference.startsWith('//')) continue; + if (isExternalReference(reference)) continue; const { pathname, fragment } = splitReference(reference); if (!fragment) continue; - const targetName = pathname ? safeRelativeTarget(page.sourceName, pathname) : page.sourceName; + const targetName = pathname ? localTarget(page.sourceName, pathname) : page.sourceName; const target = bySource.get(targetName); const id = decodeURIComponent(fragment.slice(1)); if (!target || !id || target.anchors.has(id)) continue; @@ -1061,6 +1260,110 @@ function addArchiveCompatibilityAnchors(loaded, warnings) { } } +const KEY_VIEW_TITLE = 'Options and conditions'; + +function pageHref(page, base, anchor) { + return `${baseUrl(base, page.route ? `${page.route}/` : '')}${anchor ? `#${anchor}` : ''}`; +} + +function htmlLink(href, label) { + return `${label}`; +} + +// The views by key of ARCH-ADR-6: for every option key and extension profile, the +// requirements whose applies_when names it, grouped by functionality. It is +// generated from the functionality files, so it never disagrees with them, and it +// is informative: conformance is still assessed per requirement. +function keyViewPage({ conditions, profiles, pageRoutes, base, metadata }) { + const entries = [...conditions.values()]; + const options = entries.filter((entry) => entry.kind === 'option'); + if (!options.length && !entries.some((entry) => entry.uses.length)) return undefined; + const route = profiles.length ? `${PROFILE_SECTION}/options-and-conditions` : 'options-and-conditions'; + const slugger = new GithubSlugger(); + const anchors = new Map(); + const profileOf = (page) => profileForSource(profiles, page.sourceName); + const profileLabel = (profile) => + profile ? `${htmlLink(baseUrl(base, `${pageRoutes.get(profile.introduction)}/`), htmlEscape(profile.title))} (${profile.type === 'CORE' ? 'core' : 'extension'})` : ''; + + function usesTable(entry) { + if (!entry.uses.length) return '

No requirement names it in applies_when.

'; + const rows = entry.uses.map((use) => { + const requirement = use.requirement; + const statement = requirement + ? htmlLink(pageHref(use.page, base, use.anchor), inlineHtml(requirement.statement)) + : `Every requirement of ${htmlLink(pageHref(use.page, base), htmlEscape(use.page.title))}`; + const field = use.mode === 'all' ? 'applies_when_all' : 'applies_when'; + const names = asNames((requirement ?? use.page.frontmatter)[field]); + const condition = names.length === 1 ? '' : use.mode === 'all' ? 'all of ' : 'any of '; + return `${statement}${htmlLink(pageHref(use.page, base), htmlEscape(use.page.title))}${htmlEscape(requirement?.level ?? '')}${condition}${names.map((name) => `${htmlEscape(name)}`).join(', ')}`; + }); + return `${rows.join('')}
RequirementFunctionalityLevelApplies when
`; + } + + const sections = [ + `

Each option of a variation point that other requirements refer to has a key. A requirement whose applies_when names a key, or the id of an extension profile, applies only to a software solution that meets that option or claims that extension. Otherwise it is reported as not applicable, neither passed nor failed. This page lists them by key. It is generated from the functionality files and adds no requirement of its own.

`, + ]; + if (options.length) { + sections.push('## Options'); + slugger.slug('Options'); + for (const entry of options) { + sections.push(`### ${entry.name}`); + anchors.set(entry.name, slugger.slug(entry.name)); + const variationAnchor = entry.anchor.replace(/-option-\d+$/, ''); + const id = entry.requirement.id ? `Option ${htmlEscape(entry.requirement.id)} of the` : 'An option of the'; + const where = [htmlLink(pageHref(entry.page, base), htmlEscape(entry.page.title)), profileLabel(profileOf(entry.page))].filter(Boolean).join(', '); + const extension = entry.requirement.extension ? profiles.find((profile) => profile.id === String(entry.requirement.extension)) : undefined; + sections.push( + `

${id} variation point ${htmlLink(pageHref(entry.page, base, variationAnchor), `“${inlineHtml(entry.parent.statement)}”`)} in ${where}.

`, + `

${htmlLink(pageHref(entry.page, base, entry.anchor), inlineHtml(entry.requirement.statement))}

`, + ...(extension ? [`

It is met by claiming the ${htmlLink(baseUrl(base, `${pageRoutes.get(extension.introduction)}/`), htmlEscape(extension.title))} extension.

`] : []), + usesTable(entry), + ); + } + } + const extensions = entries.filter((entry) => entry.kind === 'extension' && (entry.uses.length || options.some((option) => String(option.requirement.extension ?? '') === entry.name))); + if (extensions.length) { + sections.push('## Extensions'); + slugger.slug('Extensions'); + for (const entry of extensions) { + sections.push(`### ${entry.name}`); + anchors.set(entry.name, slugger.slug(entry.name)); + sections.push( + `

Claiming the ${htmlLink(baseUrl(base, `${pageRoutes.get(entry.profile.introduction)}/`), htmlEscape(entry.profile.title))} extension. Its own functionalities apply in full; the requirements below sit in other functionalities and apply only when it is claimed.

`, + usesTable(entry), + ); + } + } + const source = `${sections.join('\n\n')}\n`; + const sourceName = `${route}.md`; + const tree = parser.parse(source); + const headings = headingDetails(tree, sourceName); + for (const [name, anchor] of anchors) { + if (!headings.some((heading) => heading.id === anchor)) throw new Error(`${sourceName}: generated anchor #${anchor} for ${name} is missing`); + } + return { + title: KEY_VIEW_TITLE, + route, + href: baseUrl(base, `${route}/`), + anchors, + page: { + sourceName, + source, + tree, + frontmatterNode: undefined, + frontmatter: { + title: KEY_VIEW_TITLE, + description: `What follows from each option and extension of ${metadata.name}, by key.`, + }, + headings, + title: KEY_VIEW_TITLE, + route, + anchors: new Set(headings.map((heading) => heading.id)), + generated: true, + }, + }; +} + export async function generateSite({ sourceRoot, siteRoot, base = '/', unofficial = false }) { if (!sourceRoot || !siteRoot) throw new Error('generateSite requires sourceRoot and siteRoot'); const absoluteSourceRoot = await realpath(path.resolve(sourceRoot)); @@ -1078,7 +1381,8 @@ export async function generateSite({ sourceRoot, siteRoot, base = '/', unofficia } if (!Array.isArray(authors?.authors)) throw new Error('authors.yml: authors list is required'); - const { ordered, pages: pageSources } = discoverPages(toc); + const tocModel = parseToc(toc); + const { ordered, pageSources } = tocModel; const warnings = []; const loaded = []; const snapshots = new Map([ @@ -1087,19 +1391,42 @@ export async function generateSite({ sourceRoot, siteRoot, base = '/', unofficia ['authors.yml', authorsBuffer], ]); let requirementCount = 0; + const linkedDecisionRecords = []; + // ordered grows while it is read, as linked decision records are found. for (const sourceName of ordered) { const sourceBuffer = await readFile(path.join(absoluteSourceRoot, sourceName)); snapshots.set(sourceName, sourceBuffer); - const normalized = normalizeDuplicateAnchors(sourceBuffer.toString('utf8'), sourceName); + // terminology.yml and references.yml are rendered from their data; the source bytes stay in the digest. + const yaml = /\.ya?ml$/i.test(sourceName) ? yamlPage(sourceName, sourceBuffer.toString('utf8')) : undefined; + const normalized = normalizeDuplicateAnchors(yaml ? yaml.markdown : sourceBuffer.toString('utf8'), sourceName); warnings.push(...normalized.warnings); const source = normalized.source; const tree = parser.parse(source); const { node: frontmatterNode, value: frontmatter } = sourceFrontmatter(tree); const headings = headingDetails(tree, sourceName); - const title = pageLabel(sourceName, frontmatter, headings); + const title = yaml?.title ?? pageLabel(sourceName, frontmatter, headings); const route = routeFor(sourceName); const anchors = new Set([...headings.map((heading) => heading.id), ...standaloneAnchors(tree)]); - requirementCount += frontmatter.requirements?.length ?? 0; + // Decision records are not yet part of toc.yml. One that a published page links to + // is published as a resource, so that the link resolves; it is followed in turn. + for (const reference of localReferences(tree)) { + if (isExternalReference(reference) || reference.startsWith('#')) continue; + const { pathname } = splitReference(reference); + if (!pathname.endsWith('.md')) continue; + const target = localTarget(sourceName, decodedPathname(sourceName, pathname)); + if (!target.startsWith('ADR/') || pageSources.has(target)) continue; + try { + if (!(await stat(path.join(absoluteSourceRoot, target))).isFile()) continue; + } catch (error) { + if (error.code === 'ENOENT') continue; + throw error; + } + ordered.push(target); + pageSources.add(target); + linkedDecisionRecords.push(target); + warnings.push(`${target}: not listed in toc.yml; published under resources because ${sourceName} links to it`); + } + requirementCount += flattenRequirements(frontmatter.requirements).length; loaded.push({ sourceName, source, @@ -1112,11 +1439,53 @@ export async function generateSite({ sourceRoot, siteRoot, base = '/', unofficia anchors, }); } + if (linkedDecisionRecords.length) { + let resources = tocModel.sections.find((section) => section.key === 'resources'); + if (!resources) { + resources = { key: 'resources', items: [] }; + tocModel.sections.push(resources); + } + resources.items.push(...linkedDecisionRecords.map((source) => ({ kind: 'page', source }))); + } const pagesBySource = new Map(loaded.map((page) => [page.sourceName, page])); + const profiles = resolveProfiles(tocModel.profiles, pagesBySource, warnings); + for (const profile of profiles) { + // A profile is cited by its folder name, so its introduction is served at the folder's route. + const page = pagesBySource.get(profile.introduction); + page.route = page.route.replace(/\/introduction$/, ''); + } + if (profiles.length && tocModel.sections.some((section) => section.key === 'requirements')) { + warnings.push('toc.yml: requirements is replaced by conformance-profiles; list every functionality under its profile'); + } addArchiveCompatibilityAnchors(loaded, warnings); const pageRoutes = new Map(loaded.map((page) => [page.sourceName, page.route])); const pageAnchors = new Map(loaded.map((page) => [page.sourceName, page.anchors])); + for (const profile of profiles) { + const page = pagesBySource.get(profile.introduction); + const targets = localReferences(page.tree) + .filter((reference) => !isExternalReference(reference) && !reference.startsWith('#')) + .map((reference) => splitReference(reference).pathname) + .filter((pathname) => pathname.endsWith('.md')) + .map((pathname) => localTarget(page.sourceName, decodedPathname(page.sourceName, pathname))); + checkProfileFunctionalityLinks(profile, targets, warnings); + } + const functionalityPages = loaded.filter((page) => page.frontmatter.requirements?.length); + for (const page of functionalityPages) checkOptions(page, profileForSource(profiles, page.sourceName), warnings); + const conditions = collectConditions(functionalityPages, profiles, warnings); + const keyView = keyViewPage({ conditions, profiles, pageRoutes, base: normalizedBase, metadata, warnings }); const referencedSupportPaths = collectReferencedSupportPaths(loaded, pageSources); + for (const folder of tocModel.folders) { + let details; + try { + details = await stat(path.join(absoluteSourceRoot, folder)); + } catch (error) { + if (error.code !== 'ENOENT') throw error; + } + if (!details?.isDirectory()) { + throw new Error(`toc.yml: the folder entry ${path.posix.basename(folder)}/ resolves to ${folder}/, which is not a folder in the source`); + } + referencedSupportPaths.add(folder); + } assertReferencedSupportPathsAllowed(referencedSupportPaths); const supportFiles = await copySupportFiles( absoluteSourceRoot, @@ -1140,7 +1509,27 @@ export async function generateSite({ sourceRoot, siteRoot, base = '/', unofficia reference.title = page.title; reference.route = page.route; } - const sidebar = apiReferenceSidebar(sidebarFromToc(toc, pagesBySource), apiReferences.references, pagesBySource); + if (keyView) { + if ([...pageRoutes.values()].includes(keyView.route)) { + throw new Error(`${keyView.route}: a source page already uses the route of the generated ${keyView.title} page`); + } + loaded.push(keyView.page); + pageRoutes.set(keyView.page.sourceName, keyView.route); + } + const sidebar = apiReferenceSidebar( + sidebarFromToc(tocModel, pagesBySource, { profiles, keyView }), + apiReferences.references, + pagesBySource, + ); + const renderContext = { + pageRoutes, + base: normalizedBase, + profiles, + profilesById: new Map(profiles.map((profile) => [profile.id, profile])), + capabilities: new Map((metadata.capabilities ?? []).map((capability) => [String(capability.id), capability])), + keyView, + warnings, + }; await pruneFormerGeneratedPages(absoluteSiteRoot, loaded); @@ -1153,6 +1542,7 @@ export async function generateSite({ sourceRoot, siteRoot, base = '/', unofficia metadata, authors, unofficial, + context: renderContext, }); const reference = apiReferences.references.find((item) => item.page === page.sourceName); if (reference) { @@ -1175,6 +1565,7 @@ export async function generateSite({ sourceRoot, siteRoot, base = '/', unofficia referencedSupportPaths, supportFiles, unofficial, + tocModel.folders, ); const redirects = await writeRedirects(absoluteSiteRoot, loaded, normalizedBase, unofficial); const sourceState = await gitSourceState(absoluteSourceRoot); @@ -1198,6 +1589,15 @@ export async function generateSite({ sourceRoot, siteRoot, base = '/', unofficia route: page.route, title: page.title, anchors: [...page.anchors].map((id) => ({ id })), + ...(page.generated ? { generated: true } : {}), + })), + profiles: profiles.map((profile) => ({ + id: profile.id, + type: profile.type, + title: profile.title, + requires: profile.requires, + route: pageRoutes.get(profile.introduction), + functionalities: profile.functionalities, })), }; const manifestPath = path.join(absoluteSiteRoot, 'src/data/generated/spec.json'); diff --git a/src/styles/govstack.css b/src/styles/govstack.css index 0e412a2..1714d48 100644 --- a/src/styles/govstack.css +++ b/src/styles/govstack.css @@ -330,6 +330,24 @@ main h1 { .requirement-proof summary { width: fit-content; color: var(--sl-color-accent); cursor: pointer; font-size: 0.8125rem; font-weight: 600; } .requirement-proof-section { margin-top: 0.65rem; } :root[data-theme='dark'] .requirement-card { box-shadow: none; } +/* Options sit beneath their variation point, as the source lists them (ARCH-ADR-6). */ +.requirement-options { + display: grid; + gap: 0.75rem; + margin-top: 1rem; + padding-inline-start: 0.85rem; + border-inline-start: 1px dashed var(--sl-color-gray-5); +} +.sl-markdown-content .requirement-options > .requirement-card { margin-top: 0; } +.requirement-options > .requirement-card { padding: 0.85rem; box-shadow: none; } +.requirement-options .requirement-card-title { font-size: 0.9375rem; } +.sl-markdown-content a.requirement-condition { text-decoration: none; } +.sl-markdown-content a.requirement-condition:hover code { border-color: var(--sl-color-accent); } +.profile-summary { border-inline-start: 3px solid var(--sl-color-accent); } +.key-view-definition { color: var(--sl-color-gray-2); } +.key-view-empty { color: var(--sl-color-gray-3); font-size: 0.875rem; } +.sl-markdown-content .key-view-table { font-size: 0.875rem; } +.term-source { color: var(--sl-color-gray-3); font-size: 0.8125rem; } /* Page navigation is secondary to the article, with one quiet footer rhythm. */ .publication-footer { margin-top: 2rem; } diff --git a/tests/conformance-profiles.test.mjs b/tests/conformance-profiles.test.mjs new file mode 100644 index 0000000..601fcd3 --- /dev/null +++ b/tests/conformance-profiles.test.mjs @@ -0,0 +1,451 @@ +import assert from 'node:assert/strict'; +import { execFile } from 'node:child_process'; +import { access, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { promisify } from 'node:util'; +import test from 'node:test'; + +import { generateSite } from '../adapters/framework.mjs'; +import { parseToc } from '../adapters/framework-model.mjs'; + +const execFileAsync = promisify(execFile); + +async function write(root, relative, contents) { + const target = path.join(root, relative); + await mkdir(path.dirname(target), { recursive: true }); + await writeFile(target, contents); +} + +const TOC = `toc: + introduction: + - purpose.md + - terminology.yml + - references.yml + conformance-profiles: + - core-profile: + - introduction.md + - functionalities/functionality-a.md + - extension-x: + - introduction.md + - functionalities/functionality-x.md + - extension-y: + - introduction.md + - functionalities/functionality-y.md + resources: + - tests/ +`; + +// An abstract Building Block, as the Specification Framework's examples use: one +// core and two extensions, a variation point with an option met by an extension, +// and requirements conditional on an option key and on an extension id. +async function fixture({ toc = TOC, files = {} } = {}) { + const root = await mkdtemp(path.join(os.tmpdir(), 'conformance-profiles-')); + const sourceRoot = path.join(root, 'source'); + const siteRoot = path.join(root, 'site'); + const sources = { + 'toc.yml': toc, + 'metadata.yml': `name: Example Building Block +abstract: An abstract Building Block. +urn: govstack:spec:bb:example +capabilities: + - id: capability-one + title: Capability One + description: Does one thing. +extensions: + - id: stale +versions: + - version: 2.0.0-draft + latest: true +`, + 'authors.yml': 'authors:\n - name: Example Author\n roles: [Author]\n', + 'README.md': '# Example\n\nAn example.\n', + 'introduction/purpose.md': '# Purpose\n\nWhy.\n', + 'introduction/terminology.yml': `terms: + - term: Example Term + abbreviation: ET + definition: A term used in examples. + source: ISO 1234, 3.1 + notes: [A note to entry.] +`, + 'introduction/references.yml': `- title: Example Standard + url: https://example.invalid/standard + date: 2026 + abstract: A standard. +`, + 'conformance-profiles/core-profile/introduction.md': `--- +title: Core Profile +type: CORE +description: What every conformant software solution does. +requires: [] +role: Role A +--- + +## Functionalities + +| Functionality | Description | +|---|---| +| [Functionality A](functionalities/functionality-a.md) | Does A. | +`, + 'conformance-profiles/core-profile/functionalities/functionality-a.md': `--- +title: Functionality A +description: | + Does A. +realises: [capability-one] +conformance: CORE +requirements: + - id: '30' + status: PUBLISHED + level: REQUIRED + mutability: EXTENSIBLE + statement: The solution handles at least one of the kinds in requirements 30.1 to 30.3. + documentation: + select: + min: 1 + options: + - id: '30.1' + key: kind-one + status: PUBLISHED + level: OPTION + interaction: FILE + statement: The solution handles kind one. + test: resources/tests/kind-one.feature + - id: '30.2' + key: kind-two + status: DRAFT + level: OPTION + interaction: SERVICE_API + presented_by: [kind-one] + statement: The solution handles kind two. + - id: '30.3' + key: kind-x + status: DRAFT + level: OPTION + extension: extension-x + statement: The solution handles kind x as Extension X specifies. + - id: '31' + status: PUBLISHED + level: REQUIRED + interaction: FILE + applies_when: [kind-one] + statement: The solution checks kind one before keeping it. + - id: '32' + status: PUBLISHED + level: RECOMMENDED + interaction: INTERNAL + observability: OBSERVABLE + applies_when: [extension-y] + statement: The solution keeps a record when Extension Y is claimed. +--- + +Explanation of A. +`, + 'conformance-profiles/extension-x/introduction.md': `--- +title: Extension X +type: EXTENSION +description: Adds X. +requires: [] +reference_architecture: govstack:ra:example +--- + +[Functionality X](functionalities/functionality-x.md) +`, + 'conformance-profiles/extension-x/functionalities/functionality-x.md': `--- +title: Functionality X +description: Does X. +requirements: + - id: '40' + status: PUBLISHED + level: REQUIRED + interaction: PROTOCOL + statement: The solution speaks protocol X. +--- +`, + 'conformance-profiles/extension-y/introduction.md': `--- +title: Extension Y +type: EXTENSION +description: Adds Y. +requires: [extension-x] +--- + +No table yet. +`, + 'conformance-profiles/extension-y/functionalities/functionality-y.md': `--- +title: Functionality Y +description: Does Y. +requirements: + - id: '50' + status: DRAFT + level: REQUIRED + statement: The solution does Y. +--- +`, + 'resources/tests/kind-one.feature': 'Feature: kind one\n', + ...files, + }; + for (const [relative, contents] of Object.entries(sources)) { + if (contents !== null) await write(sourceRoot, relative, contents); + } + await execFileAsync('git', ['init', '-q', root]); + await execFileAsync('git', ['-C', root, 'add', 'source']); + await execFileAsync('git', ['-C', root, '-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qm', 'fixture']); + return { sourceRoot, siteRoot }; +} + +const page = (siteRoot, route) => readFile(path.join(siteRoot, 'src/content/docs', `${route}.md`), 'utf8'); + +test('toc subsections under conformance-profiles resolve relative to each profile folder', () => { + const model = parseToc({ + introduction: ['purpose.md'], + 'conformance-profiles': [{ core: ['introduction.md', 'functionalities/a.md'] }], + resources: null, + }); + assert.deepEqual(model.profiles, [ + { + id: 'core', + directory: 'conformance-profiles/core', + introduction: 'conformance-profiles/core/introduction.md', + pages: ['conformance-profiles/core/introduction.md', 'conformance-profiles/core/functionalities/a.md'], + }, + ]); + assert.deepEqual(model.sections.at(-1), { key: 'resources', items: [] }); + assert.throws(() => parseToc({ 'conformance-profiles': ['loose.md'] }), /one subsection per profile folder/); + assert.throws(() => parseToc({ 'conformance-profiles': [{ Core: ['introduction.md'] }] }), /kebab-case/); + assert.throws(() => parseToc({ 'conformance-profiles': [{ core: ['functionalities/a.md', 'introduction.md'] }] }), /introduction\.md first/); + assert.throws(() => parseToc({ 'conformance-profiles': [{ core: ['introduction.md', { nested: ['b.md'] }] }] }), /one level deep/); + assert.throws(() => parseToc({ introduction: ['a.md', 'a.md'] }), /listed twice/); +}); + +test('conformance profiles get their own pages, navigation and home table', async () => { + const { sourceRoot, siteRoot } = await fixture(); + const manifest = await generateSite({ sourceRoot, siteRoot, base: '/docs/' }); + + assert.deepEqual( + manifest.profiles.map(({ id, type, route, requires }) => [id, type, route, requires]), + [ + ['core-profile', 'CORE', 'conformance-profiles/core-profile', []], + ['extension-x', 'EXTENSION', 'conformance-profiles/extension-x', []], + ['extension-y', 'EXTENSION', 'conformance-profiles/extension-y', ['extension-x']], + ], + ); + const section = manifest.sidebar.find(({ label }) => label === 'Conformance profiles'); + assert.deepEqual(section.items[0], { + label: 'Core Profile', + badge: { text: 'Core', variant: 'note' }, + items: [ + { label: 'Introduction', slug: 'conformance-profiles/core-profile' }, + { label: 'Functionality A', slug: 'conformance-profiles/core-profile/functionalities/functionality-a' }, + ], + }); + assert.equal(section.items[1].badge.text, 'Extension'); + assert.deepEqual(section.items.at(-1), { label: 'Options and conditions', slug: 'conformance-profiles/options-and-conditions' }); + + const extensionY = await page(siteRoot, 'conformance-profiles/extension-y'); + assert.match(extensionY, /class="functionality-summary profile-summary"/); + assert.match(extensionY, /
Builds on<\/dt>
Core Profile<\/a>, Extension X<\/a><\/dd>/); + const extensionX = await page(siteRoot, 'conformance-profiles/extension-x'); + assert.match(extensionX, /
Reference architecture<\/dt>
govstack:ra:example<\/code><\/dd>/); + + const home = await page(siteRoot, 'index'); + assert.match(home, /## Conformance profiles/); + assert.match(home, /\| \[Extension Y\]\(\/docs\/conformance-profiles\/extension-y\/\) \| `extension-y` \| Extension \| `core-profile`, `extension-x` \| Adds Y\. \|/); + assert.doesNotMatch(home, /\| Extensions \|/); + + const functionality = await page(siteRoot, 'conformance-profiles/core-profile/functionalities/functionality-a'); + assert.match(functionality, /
Conformance profile<\/dt>
Core Profile<\/a> \(core\)<\/dd>/); + assert.match(functionality, /
Capabilities<\/dt>
Capability One<\/dd>/); + assert.doesNotMatch(functionality, /
Conformance<\/dt>/); + assert.doesNotMatch(functionality, /Does A\.
/); + + assert.ok(manifest.warnings.includes('metadata.yml: extensions is ignored; conformance profiles are declared in the introduction.md of each profile folder')); + assert.ok(manifest.warnings.some((warning) => warning.includes('functionality-a.md: conformance and extension are ignored'))); + assert.ok(manifest.warnings.includes('conformance-profiles/extension-y/introduction.md: does not link to its functionality conformance-profiles/extension-y/functionalities/functionality-y.md')); +}); + +test('options render beneath their variation point with conditions linked to their key view', async () => { + const { sourceRoot, siteRoot } = await fixture(); + const manifest = await generateSite({ sourceRoot, siteRoot, base: '/' }); + assert.equal(manifest.requirementCount, 8); + + const output = await page(siteRoot, 'conformance-profiles/core-profile/functionalities/functionality-a'); + assert.match(output, /defines 3 requirements, and 3 options beneath its variation points\./); + assert.doesNotMatch(output, /Unnumbered draft/); + const variationPoint = output.slice(output.indexOf('
Selection<\/dt>
Meet at least 1 of its 3 options<\/dd>/); + assert.match(variationPoint, /
Verification<\/dt>
Counts the options that pass<\/dd>/); + assert.match(variationPoint, /id="requirement-1-option-2"[\s\S]*30\.2<\/span>/); + assert.match(variationPoint, /Level<\/span>OPTION/); + assert.match(variationPoint, /href="\/conformance-profiles\/options-and-conditions\/#kind-one">kind-one<\/code>/); + assert.match(variationPoint, /
Met by claiming<\/dt>
Extension X<\/a> extension<\/dd>/); + assert.match(variationPoint, /
Verification<\/dt>
By the extension's tests<\/dd>/); + assert.match(variationPoint, /
Presented by<\/dt>
/); + assert.match(variationPoint, /href="\/resources\/tests\/kind-one\.feature"/); + assert.match(output, /
Applies when<\/dt>
extension-y<\/code><\/a><\/dd>/); + + const view = await page(siteRoot, 'conformance-profiles/options-and-conditions'); + assert.match(view, /^### kind-one$/m); + assert.match(view, /^### extension-y$/m); + assert.match(view, /Option 30\.1 of the variation point /); + assert.match(view, /The solution checks kind one before keeping it\.<\/a>/); + assert.match(view, /### kind-two\n\n[\s\S]*?No requirement names it/); + const generated = manifest.pages.find(({ route }) => route === 'conformance-profiles/options-and-conditions'); + assert.equal(generated.generated, true); + assert.ok(generated.anchors.some(({ id }) => id === 'kind-x')); + assert.equal(manifest.redirects.some(({ legacy }) => legacy.includes('options-and-conditions')), false); +}); + +test('verification follows from interaction, and observability is read only without one', async () => { + const { sourceRoot, siteRoot } = await fixture(); + const manifest = await generateSite({ sourceRoot, siteRoot, base: '/' }); + const output = await page(siteRoot, 'conformance-profiles/core-profile/functionalities/functionality-a'); + assert.match(output, /
Verification<\/dt>
Tested at the file boundary<\/dd>/); + assert.match(output, /
Verification<\/dt>
Audited against evidence<\/dd>/); + assert.doesNotMatch(output, /Observability<\/span>/); + assert.ok(manifest.warnings.some((warning) => warning.includes('observability OBSERVABLE disagrees with interaction INTERNAL'))); + const unclassified = await page(siteRoot, 'conformance-profiles/extension-y/functionalities/functionality-y'); + assert.match(unclassified, /
Verification<\/dt>
Unclassified<\/dd>/); + assert.ok(manifest.warnings.some((warning) => warning.includes('requirement 50 has no interaction'))); +}); + +test('profile rules that navigation and links depend on fail generation', async () => { + const cases = [ + [{ 'conformance-profiles/extension-x/introduction.md': '---\ntitle: X\ntype: CORE\n---\n' }, /exactly one CORE conformance profile, found 2/], + [{ 'conformance-profiles/extension-y/introduction.md': '---\ntitle: Y\ntype: EXTENSION\nrequires: [missing]\n---\n' }, /requires missing, which is not an extension profile/], + [{ 'conformance-profiles/extension-x/introduction.md': '---\ntitle: X\ntype: EXTENSION\nrequires: [extension-y]\n---\n' }, /cycle: extension-x → extension-y → extension-x/], + [{ 'conformance-profiles/core-profile/introduction.md': '---\ntitle: Core\ntype: CORE\nrequires: [extension-x]\n---\n' }, /the core never depends on an extension/], + [{ 'conformance-profiles/extension-x/introduction.md': '---\ntitle: X\ntype: OPTIONAL\n---\n' }, /type must be CORE or EXTENSION/], + ]; + for (const [files, error] of cases) { + const { sourceRoot, siteRoot } = await fixture({ files }); + await assert.rejects(generateSite({ sourceRoot, siteRoot, base: '/' }), error); + } +}); + +test('folder entries publish their files with an index, and a missing folder fails', async () => { + const { sourceRoot, siteRoot } = await fixture(); + const manifest = await generateSite({ sourceRoot, siteRoot, base: '/docs/' }); + assert.deepEqual(manifest.sidebar.find(({ label }) => label === 'Resources').items, [{ label: 'tests/', link: '/resources/tests/' }]); + assert.ok(manifest.supportIndexes.includes('resources/tests/index.html')); + assert.match(await readFile(path.join(siteRoot, 'public/resources/tests/index.html'), 'utf8'), /kind-one\.feature/); + + const missing = await fixture({ toc: TOC.replace(' - tests/', ' - research/') }); + await assert.rejects( + generateSite({ sourceRoot: missing.sourceRoot, siteRoot: missing.siteRoot, base: '/' }), + /folder entry research\/ resolves to resources\/research\/, which is not a folder/, + ); +}); + +test('terminology.yml and references.yml render as pages without legacy redirects', async () => { + const { sourceRoot, siteRoot } = await fixture(); + const manifest = await generateSite({ sourceRoot, siteRoot, base: '/' }); + const terminology = await page(siteRoot, 'introduction/terminology'); + assert.match(terminology, /^title: Terminology$/m); + assert.match(terminology, /^## Example Term \(ET\)$/m); + assert.match(terminology, /A term used in examples\./); + assert.match(terminology, /\*Note:\* A note to entry\./); + assert.match(terminology, /Source: ISO 1234, 3\.1/); + assert.ok(manifest.pages.find(({ source }) => source === 'introduction/terminology.yml').anchors.some(({ id }) => id === 'example-term-et')); + const references = await page(siteRoot, 'introduction/references'); + assert.match(references, /- \[Example Standard\]\(\) \(2026\)/); + assert.equal(manifest.redirects.some(({ legacy }) => legacy.endsWith('.yml')), false); + await assert.rejects(access(path.join(siteRoot, 'public/introduction/terminology.yml'))); +}); + +test('a specification without conformance profiles keeps its legacy layout', async () => { + const { sourceRoot, siteRoot } = await fixture({ + toc: 'toc:\n requirements:\n - functionality.md\n', + files: { + 'requirements/functionality.md': `--- +title: Legacy +description: Legacy functionality. +conformance: EXTENSION +extension: audit +requirements: + - id: '1' + status: PUBLISHED + level: REQUIRED + observability: AUDITABLE + statement: The solution is audited. +--- +`, + }, + }); + const manifest = await generateSite({ sourceRoot, siteRoot, base: '/' }); + assert.deepEqual(manifest.profiles, []); + const output = await page(siteRoot, 'requirements/functionality'); + assert.match(output, /
Extension<\/dt>
audit<\/dd>/); + assert.match(output, /Observability<\/span>AUDITABLE/); + assert.doesNotMatch(output, /
Verification<\/dt>/); + assert.match(await page(siteRoot, 'index'), /\| Extensions \| `stale` \|/); + await rm(path.dirname(sourceRoot), { recursive: true, force: true }); +}); + +test('root paths resolve against the specification root under the build base', async () => { + const { sourceRoot, siteRoot } = await fixture({ + files: { + 'README.md': '# Example\n\n
Cover
\n\n[Purpose](/introduction/purpose.md#purpose) and [tests](/resources/tests/).\n', + 'assets/cover.svg': '\n', + 'assets/unreferenced.svg': '\n', + }, + }); + await generateSite({ sourceRoot, siteRoot, base: '/bb/example/' }); + const home = await page(siteRoot, 'index'); + assert.match(home, /src="\/bb\/example\/assets\/cover\.svg"/); + assert.match(home, /\[Purpose\]\(\/bb\/example\/introduction\/purpose\/#purpose\)/); + assert.match(home, /\[tests\]\(\/bb\/example\/resources\/tests\/\)/); + await access(path.join(siteRoot, 'public/assets/cover.svg')); + await assert.rejects(access(path.join(siteRoot, 'public/assets/unreferenced.svg'))); + + const escaping = await fixture({ files: { 'README.md': '[Out](/../outside.md)\n' } }); + await assert.rejects(generateSite({ sourceRoot: escaping.sourceRoot, siteRoot: escaping.siteRoot, base: '/' }), /escapes the source root/); +}); + +test('decision records that a page links to are published under resources', async () => { + const { sourceRoot, siteRoot } = await fixture({ + files: { + 'introduction/purpose.md': '# Purpose\n\nSee [the decision](../ADR/EXAMPLE-ADR-1.md#context).\n', + 'ADR/EXAMPLE-ADR-1.md': '---\ntitle: First decision\n---\n\n## Context\n\nFollows [the second](EXAMPLE-ADR-2.md).\n', + 'ADR/EXAMPLE-ADR-2.md': '# Second decision\n\nText.\n', + 'ADR/EXAMPLE-ADR-3.md': '# Unlinked decision\n', + }, + }); + const manifest = await generateSite({ sourceRoot, siteRoot, base: '/' }); + assert.deepEqual( + manifest.sidebar.find(({ label }) => label === 'Resources').items.slice(1), + [ + { label: 'First decision', slug: 'adr/example-adr-1' }, + { label: 'Second decision', slug: 'adr/example-adr-2' }, + ], + ); + assert.match(await page(siteRoot, 'introduction/purpose'), /\[the decision\]\(\/adr\/example-adr-1\/#context\)/); + assert.equal(manifest.pages.some(({ source }) => source === 'ADR/EXAMPLE-ADR-3.md'), false); + assert.ok(manifest.warnings.includes('ADR/EXAMPLE-ADR-2.md: not listed in toc.yml; published under resources because ADR/EXAMPLE-ADR-1.md links to it')); + + const other = await fixture({ files: { 'introduction/purpose.md': '[Notes](../notes/draft.md)\n', 'notes/draft.md': '# Draft\n' } }); + await assert.rejects(generateSite({ sourceRoot: other.sourceRoot, siteRoot: other.siteRoot, base: '/' }), /notes\/draft\.md is not listed in toc\.yml/); +}); + +test('a contract or test given as a URN or web URL is not turned into a local link', async () => { + const { sourceRoot, siteRoot } = await fixture({ + files: { + 'conformance-profiles/extension-x/functionalities/functionality-x.md': `--- +title: Functionality X +description: Does X. +requirements: + - id: '40' + status: PUBLISHED + level: REQUIRED + interaction: CONSUMED_API + contract: "govstack:spec:bb:information-mediator" + test: https://example.invalid/tests/40 + statement: The solution uses another Building Block. +--- +`, + }, + }); + await generateSite({ sourceRoot, siteRoot, base: '/bb/example/' }); + const output = await page(siteRoot, 'conformance-profiles/extension-x/functionalities/functionality-x'); + assert.match(output, /
Contract<\/dt>
govstack:spec:bb:information-mediator<\/code><\/dd>/); + assert.match(output, /
Test<\/dt>
/); +}); diff --git a/tests/framework.test.mjs b/tests/framework.test.mjs index 41ed4bb..1871cbc 100644 --- a/tests/framework.test.mjs +++ b/tests/framework.test.mjs @@ -357,8 +357,9 @@ test('generator rewrites routes, renders requirement semantics, copies aliases, assert.match(requirements, /class="requirement-key-row">[\s\S]*registry-service/); assert.match(requirements, /Option of/); assert.match(requirements, /Inherited option obligation/); - assert.match(requirements, /Any of/); - assert.match(requirements, /All of/); + assert.match(requirements, /
Applies when any of<\/dt>/); + assert.match(requirements, /
Applies when all of<\/dt>/); + assert.match(requirements, /
Verification<\/dt>
Tested at the Service API boundary<\/dd>/); assert.match(requirements, /
Type<\/dt>
Extension<\/dd>/); assert.match(requirements, /consultation-retrieve/); assert.match(requirements, /class="requirement-documentation requirement-constraint">[\s\S]*Preserve source meaning/); @@ -690,17 +691,23 @@ test('canonical source integration renders its requirements without changing sou const manifest = await generateSite({ sourceRoot: canonicalSourceRoot, siteRoot, base: '/' }); - const sourceRows = await Promise.all(manifest.pages.map(async (page) => { + const sourceRows = await Promise.all(manifest.pages.filter((page) => !page.generated).map(async (page) => { const source = await readFile(path.join(canonicalSourceRoot, page.source), 'utf8'); const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---/.exec(source); return frontmatter ? YAML.parse(frontmatter[1])?.requirements ?? [] : []; })); - const expectedRequirements = sourceRows.reduce((total, rows) => total + rows.length, 0); + const expectedRequirements = sourceRows.reduce( + (total, rows) => total + rows.length + rows.reduce((options, row) => options + (row?.options?.length ?? 0), 0), + 0, + ); assert.ok(expectedRequirements > 0); assert.equal(manifest.requirementCount, expectedRequirements); const toc = YAML.parse(await readFile(path.join(canonicalSourceRoot, 'toc.yml'), 'utf8')).toc; for (const [section, entries] of Object.entries(toc)) { - for (const entry of entries) assert.ok(manifest.pages.some((page) => page.source === `${section}/${entry}`)); + for (const entry of entries ?? []) { + if (typeof entry !== 'string' || entry.endsWith('/')) continue; + assert.ok(manifest.pages.some((page) => page.source === `${section}/${entry}`)); + } } assert.equal(manifest.sourceRevision, beforeRevision.stdout.trim()); assert.equal(manifest.sourceDirty, beforeStatus.stdout.trim() !== ''); @@ -715,7 +722,7 @@ test('canonical source integration renders its requirements without changing sou assert.equal((requirements.match(/
Unnumbered draft/g) ?? []).length, unnumbered); - assert.match(requirements, /Any of/); + assert.match(requirements, /Applies when/); assert.match(requirements, /Minimum selections/); await assertArchivePagesExcluded(siteRoot, manifest.pages); From 7835a2e8692d7ac35277f95cea7bf436d1dfd55c Mon Sep 17 00:00:00 2001 From: "Ali G." Date: Tue, 24 Nov 2026 19:57:44 +0100 Subject: [PATCH 3/7] feat: publish listed Building Blocks to GitHub Pages Add publish/building-blocks.yml, listing the Building Blocks to publish (Wallet and Document Management), and scripts/publish.mjs (npm run publish). The script fetches each source at its ref, or uses local checkouts with --sources. It builds and checks each one under bb//, and writes a landing page naming the commit each was built from. The pages workflow runs the tests and the publish command on pushes to main, on demand and daily, and deploys the site to GitHub Pages as an unofficial preview. A failed build or check stops the deploy, so the live site keeps its previous version. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/pages.yml | 58 +++++++++++ README.md | 23 +++- package.json | 3 +- publish/building-blocks.yml | 26 +++++ scripts/publish.mjs | 202 ++++++++++++++++++++++++++++++++++++ tests/publish.test.mjs | 38 +++++++ 6 files changed, 348 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/pages.yml create mode 100644 publish/building-blocks.yml create mode 100644 scripts/publish.mjs create mode 100644 tests/publish.test.mjs diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 0000000..eebb7c8 --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,58 @@ +name: Publish specifications to GitHub Pages +# Builds every Building Block in publish/building-blocks.yml with this renderer and +# deploys them as one site: /bb//, with a landing page at the root. +# Every build runs the renderer's built-output and HTTP checks; one failure stops +# the deploy, so the published site keeps its previous version. +on: + push: + branches: [main] + workflow_dispatch: + schedule: + # Building Block repositories change independently of this one. + - cron: '17 4 * * *' +permissions: + contents: read +concurrency: + group: pages + cancel-in-progress: false +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version: '24' + - name: Install the renderer + run: npm ci --ignore-scripts --no-audit --no-fund + - name: Test the renderer + run: npm test + - name: Build and check every Building Block + env: + REPOSITORY_NAME: ${{ github.event.repository.name }} + REPOSITORY_OWNER: ${{ github.repository_owner }} + run: | + #!/usr/bin/env bash + set -euo pipefail + # A .github.io repository is served at the domain root; any other at //. + shopt -s nocasematch + if [[ "$REPOSITORY_NAME" == "$REPOSITORY_OWNER.github.io" ]]; then base=/; else base="/$REPOSITORY_NAME/"; fi + node scripts/publish.mjs --output "$RUNNER_TEMP/site" --checkouts "$RUNNER_TEMP/sources" --base "$base" --unofficial + - uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 + with: + path: ${{ runner.temp }}/site + deploy: + if: github.ref == 'refs/heads/main' + needs: build + runs-on: ubuntu-latest + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - id: deployment + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 diff --git a/README.md b/README.md index 703c68f..4674664 100644 --- a/README.md +++ b/README.md @@ -90,10 +90,31 @@ works as follows: npm run check -- --profile api-guide --source /absolute/path/to/api-design-guide --base /api-guide/ --output /absolute/path/to/scratch-output ``` -All previews bind to loopback. No deployment or publication command is included. +All previews bind to loopback. `npm run publish` builds several specifications into one site; see [Publishing several Building Blocks](#publishing-several-building-blocks). `dev` generates source content once; regenerate after editing the authoritative input. Use a static build plus `preview` to verify the Pagefind search index. +## Publishing several Building Blocks + +[`publish/building-blocks.yml`](publish/building-blocks.yml) lists the Building Blocks to publish, each with an `id`, `title`, `repository` (`owner/name` on GitHub), `ref` (branch, tag or commit) and an optional `description`. `npm run publish` builds them into one static site: + +```text +/index.html landing page listing the Building Blocks and the commit each was built from +/bb// one specification site per Building Block, built with the base bb// +``` + +Every Building Block is built and then checked as in `build` and `test-served`. Any failure stops the run. Root paths in a specification resolve under its own `bb//` folder. + +```sh +# Fetch each source at its ref, as CI does (checkouts go to .generated/publish-sources by default) +npm run publish -- --output /absolute/path/to/site --base / --unofficial +# Or build from local checkouts named after each repository, such as ../bb-wallet +npm run publish -- --sources .. --output /absolute/path/to/site --base / +python3 -m http.server 4336 --directory /absolute/path/to/site +``` + +[`.github/workflows/pages.yml`](.github/workflows/pages.yml) runs the tests and the same command on every push to `main`, on demand, and daily, and deploys the result to GitHub Pages. For this repository that is `https://basicavisual.github.io/govstack-specification-site/bb//`. The base is `//`, or `/` for a `.github.io` repository. Builds are marked unofficial. Before the first run, set **Settings → Pages → Source** to **GitHub Actions**. To add a Building Block, add it to the list; its repository must be public. + ## Unofficial deployments Pass `--unofficial` (or set `DOCS_UNOFFICIAL=1`) when a build is published diff --git a/package.json b/package.json index c43cf5d..5249331 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,8 @@ "test": "node --test tests/*.test.mjs", "check:built": "node scripts/site.mjs check-built", "test:served": "node scripts/site.mjs test-served", - "check": "node scripts/site.mjs check" + "check": "node scripts/site.mjs check", + "publish": "node scripts/publish.mjs" }, "dependencies": { "@astrojs/markdown-remark": "7.3.3", diff --git a/publish/building-blocks.yml b/publish/building-blocks.yml new file mode 100644 index 0000000..74ca62e --- /dev/null +++ b/publish/building-blocks.yml @@ -0,0 +1,26 @@ +# Building Blocks published to GitHub Pages by .github/workflows/pages.yml. +# +# Each entry is built from its repository at `ref` and served at +# https://basicavisual.github.io/govstack-specification-site/bb// +# +# id: folder name under /bb/; lowercase kebab-case, never reused +# title: name on the landing page +# repository: GitHub owner/name of the specification source +# ref: branch, tag or full commit to build; a commit makes the build reproducible +# description: optional line under the title on the landing page +# +# A Building Block that fails its build or checks stops the whole deploy, so that +# the published site never mixes checked and unchecked specifications. + +building_blocks: + - id: wallet + title: Wallet + repository: GovStackWorkingGroup/bb-wallet + ref: feat/v2.0 + description: Draft 2.0, organised into conformance profiles. + + - id: document-management + title: Document Management + repository: GovStackWorkingGroup/bb-file-management + ref: v0.6 + description: Test draft, not yet migrated to conformance profiles. diff --git a/scripts/publish.mjs b/scripts/publish.mjs new file mode 100644 index 0000000..ca306d6 --- /dev/null +++ b/scripts/publish.mjs @@ -0,0 +1,202 @@ +// Builds every Building Block in publish/building-blocks.yml into one static site: +// +// /index.html landing page listing the Building Blocks +// /bb// one specification site per Building Block +// +// Each specification is built and checked by scripts/site.mjs with the base +// bb//, so its pages and assets resolve only inside its own folder. +// The same command runs locally and in .github/workflows/pages.yml. + +import { execFile, spawn } from 'node:child_process'; +import { copyFile, mkdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parseArgs, promisify } from 'node:util'; + +import YAML from 'yaml'; + +const execFileAsync = promisify(execFile); +const rendererRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const DEFAULT_LIST = path.join(rendererRoot, 'publish/building-blocks.yml'); +const ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; +const REPOSITORY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/; +const REF = /^[A-Za-z0-9._/-]+$/; + +export function parseList(text, name = 'building-blocks.yml') { + const entries = YAML.parse(text)?.building_blocks; + if (!Array.isArray(entries) || !entries.length) throw new Error(`${name}: building_blocks must be a non-empty list`); + const seen = new Set(); + return entries.map((entry, index) => { + const where = `${name}: building_blocks[${index}]`; + if (!entry || typeof entry !== 'object') throw new Error(`${where} must be a mapping`); + const { id, title, repository, ref, description = '' } = entry; + if (typeof id !== 'string' || !ID.test(id)) throw new Error(`${where}: id must be lowercase kebab-case`); + if (seen.has(id)) throw new Error(`${where}: id ${id} is listed twice`); + seen.add(id); + if (typeof title !== 'string' || !title.trim()) throw new Error(`${where}: title is required`); + if (typeof repository !== 'string' || !REPOSITORY.test(repository)) throw new Error(`${where}: repository must be owner/name`); + if (typeof ref !== 'string' || !REF.test(ref) || ref.startsWith('-') || ref.includes('..')) { + throw new Error(`${where}: ref must be a branch, tag or commit`); + } + if (typeof description !== 'string') throw new Error(`${where}: description must be text`); + return { id, title: title.trim(), repository, ref, description: description.trim() }; + }); +} + +function normalizeBase(base) { + if (typeof base !== 'string' || !base.startsWith('/')) throw new Error(`--base must start with /, received ${JSON.stringify(base)}`); + return `${base.replace(/\/+$/, '')}/`; +} + +function run(command, args, options = {}) { + return new Promise((resolve, reject) => { + const child = spawn(command, args, { stdio: 'inherit', ...options }); + child.once('error', reject); + child.once('exit', (code, signal) => { + if (code === 0) resolve(); + else reject(new Error(`${path.basename(command)} ${args[0] ?? ''} exited with ${signal || code}`)); + }); + }); +} + +// Fetches one commit of the source without credentials, hooks or history. +async function checkout(entry, checkouts) { + const directory = path.join(checkouts, entry.id); + await rm(directory, { recursive: true, force: true }); + await mkdir(directory, { recursive: true }); + const git = (...args) => execFileAsync('git', ['-C', directory, ...args]); + await git('init', '-q'); + await git('remote', 'add', 'origin', `https://github.com/${entry.repository}.git`); + await git('-c', 'protocol.version=2', 'fetch', '-q', '--depth', '1', '--no-tags', 'origin', entry.ref); + await git('-c', 'advice.detachedHead=false', 'checkout', '-q', 'FETCH_HEAD'); + return directory; +} + +async function localSource(entry, sources) { + const directory = path.join(sources, entry.repository.split('/')[1]); + try { + if ((await stat(directory)).isDirectory()) return directory; + } catch (error) { + if (error.code !== 'ENOENT') throw error; + } + throw new Error(`${entry.id}: no local checkout at ${directory}`); +} + +function htmlEscape(value) { + return String(value) + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"') + .replaceAll("'", '''); +} + +export function landingHtml(entries, { base, unofficial }) { + const items = entries + .map((entry) => { + const source = `https://github.com/${entry.repository}/tree/${entry.commit ?? entry.ref}`; + const built = entry.commit ? `${entry.ref} @ ${entry.commit.slice(0, 7)}` : entry.ref; + return `
  • + ${htmlEscape(entry.title)} + ${entry.description ? `

    ${htmlEscape(entry.description)}

    ` : ''} +

    Built from ${htmlEscape(entry.repository)} ${htmlEscape(built)}

    +
  • `; + }) + .join('\n'); + return ` + + + + + +GovStack specifications + + + + +
    +${unofficial ? '' : ''} +

    GovStack specifications

    +

    Building Block specifications rendered from their source repositories.

    +
      +${items} +
    +
    + + +`; +} + +export async function publish({ list = DEFAULT_LIST, output, base = '/', unofficial = false, sources, checkouts }) { + if (!output) throw new Error('--output is required'); + const siteBase = normalizeBase(base); + const entries = parseList(await readFile(list, 'utf8'), path.relative(rendererRoot, list) || list); + const outputRoot = path.resolve(output); + await mkdir(outputRoot, { recursive: true }); + const checkoutRoot = sources ? undefined : path.resolve(checkouts ?? path.join(rendererRoot, '.generated/publish-sources')); + const site = path.join(rendererRoot, 'scripts/site.mjs'); + for (const entry of entries) { + console.log(`\n== ${entry.title}: ${entry.repository} @ ${entry.ref}`); + const source = sources ? await localSource(entry, path.resolve(sources)) : await checkout(entry, checkoutRoot); + entry.commit = (await execFileAsync('git', ['-C', source, 'rev-parse', 'HEAD'])).stdout.trim(); + const options = [ + '--profile', 'framework', + '--source', await realpath(source), + '--base', `${siteBase}bb/${entry.id}/`, + '--output', path.join(outputRoot, 'bb', entry.id), + ...(unofficial ? ['--unofficial'] : []), + ]; + await run(process.execPath, [site, 'build', ...options], { cwd: rendererRoot }); + await run(process.execPath, [site, 'test-served', ...options], { cwd: rendererRoot }); + } + await writeFile(path.join(outputRoot, 'index.html'), landingHtml(entries, { base: siteBase, unofficial })); + await copyFile(path.join(rendererRoot, 'public/favicon.svg'), path.join(outputRoot, 'favicon.svg')); + if (unofficial) await writeFile(path.join(outputRoot, 'robots.txt'), 'User-agent: *\nDisallow: /\n'); + console.log(`\nPublished ${entries.length} Building Blocks to ${outputRoot}`); + return entries; +} + +export async function main(args = process.argv.slice(2)) { + const { values } = parseArgs({ + args, + options: { + list: { type: 'string' }, + output: { type: 'string' }, + base: { type: 'string' }, + unofficial: { type: 'boolean' }, + sources: { type: 'string' }, + checkouts: { type: 'string' }, + }, + }); + await publish({ + list: values.list ? path.resolve(values.list) : DEFAULT_LIST, + output: values.output, + base: values.base ?? '/', + unofficial: values.unofficial ?? false, + sources: values.sources, + checkouts: values.checkouts, + }); +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + main().catch((error) => { + console.error(error.message); + process.exitCode = 1; + }); +} diff --git a/tests/publish.test.mjs b/tests/publish.test.mjs new file mode 100644 index 0000000..b94b1b2 --- /dev/null +++ b/tests/publish.test.mjs @@ -0,0 +1,38 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import path from 'node:path'; +import test from 'node:test'; + +import { landingHtml, parseList } from '../scripts/publish.mjs'; + +test('the published Building Block list is valid', async () => { + const list = await readFile(path.resolve(import.meta.dirname, '../publish/building-blocks.yml'), 'utf8'); + const entries = parseList(list); + assert.ok(entries.length > 0); + assert.ok(entries.some(({ id }) => id === 'wallet')); +}); + +test('the Building Block list rejects entries that would publish ambiguously or unsafely', () => { + const entry = (fields) => `building_blocks:\n - ${Object.entries({ id: 'wallet', title: 'Wallet', repository: 'org/bb-wallet', ref: 'main', ...fields }).map(([key, value]) => `${key}: ${JSON.stringify(value)}`).join('\n ')}\n`; + assert.deepEqual(parseList(entry({})), [{ id: 'wallet', title: 'Wallet', repository: 'org/bb-wallet', ref: 'main', description: '' }]); + assert.throws(() => parseList('building_blocks: []\n'), /non-empty list/); + assert.throws(() => parseList(entry({ id: 'Wallet' })), /kebab-case/); + assert.throws(() => parseList(entry({ repository: 'https://github.com/org/bb-wallet' })), /owner\/name/); + assert.throws(() => parseList(entry({ ref: '--upload-pack=x' })), /branch, tag or commit/); + assert.throws(() => parseList(entry({ ref: 'a..b' })), /branch, tag or commit/); + const twice = `${entry({})} - id: wallet\n title: Again\n repository: org/other\n ref: main\n`; + assert.throws(() => parseList(twice), /listed twice/); +}); + +test('the landing page links each Building Block under the base and names the built commit', () => { + const html = landingHtml( + [{ id: 'wallet', title: 'Wallet <2.0>', repository: 'org/bb-wallet', ref: 'feat/v2.0', description: 'Draft.', commit: 'ef465f8442070207e5f3bff4b594641f4fe9a92e' }], + { base: '/govstack-specification-site/', unofficial: true }, + ); + assert.match(html, /href="\/govstack-specification-site\/bb\/wallet\/">Wallet <2\.0><\/a>/); + assert.match(html, /href="https:\/\/github\.com\/org\/bb-wallet\/tree\/ef465f8442070207e5f3bff4b594641f4fe9a92e"/); + assert.match(html, /feat\/v2\.0 @ ef465f8<\/code>/); + assert.match(html, /Unofficial preview/); + assert.match(html, /content="noindex, nofollow"/); + assert.doesNotMatch(landingHtml([], { base: '/', unofficial: false }), /Unofficial preview/); +}); From c8f0abc1b0c00c0dced2a051ac8d4546dac41491 Mon Sep 17 00:00:00 2001 From: "Ali G." Date: Tue, 24 Nov 2026 19:57:44 +0100 Subject: [PATCH 4/7] docs: add a changelog Record the conformance profile, options and verification rendering, the related fixes, and GitHub Pages publishing under Unreleased. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..21bca75 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,72 @@ +# Changelog + +All notable changes to the GovStack specification renderer are recorded here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). + +## Unreleased + +This release renders the Specification Framework changes proposed for the Architecture Working Group meeting of 25 November 2026: conformance profiles (ARCH-ADR-7), options and conditional requirements (ARCH-ADR-6) and the removal of the `observability` classifier (ARCH-ADR-8). The Wallet Building Block 2.0 draft is the first specification to use all three. Specifications that still use `requirements/` render as before, with warnings, so that Building Blocks can migrate one at a time. + +### Added + +- **Conformance profiles (ARCH-ADR-7).** + - `toc.yml` accepts a `conformance-profiles` section with one subsection per profile folder. The subsection's pages resolve relative to `conformance-profiles//`, and its `introduction.md` comes first. + - Each profile's introduction is served at `/conformance-profiles//`, since the folder name is the profile id. A summary from its front matter (`type`, `description`, `requires`, `role`, `reference_architecture`) sits above it, along with the profiles it builds on and its number of functionalities. + - Every functionality page names the conformance profile whose folder holds it, and its capabilities by title from `metadata.yml`. + - The home page lists the profiles in a table: profile, id, type, what it builds on, description. + - The sidebar groups each profile, with a Core or Extension badge. + - The build manifest records each profile's id, type, title, `requires`, route and functionalities. + - Generation fails when: + - there is not exactly one `CORE` profile; + - a `type` is neither `CORE` nor `EXTENSION`; + - the core requires an extension; + - `requires` names something that is not an extension profile, or forms a cycle; + - a profile folder is not kebab-case, is listed twice, or does not list `introduction.md` first. + - Warnings report: + - functionalities that a profile's introduction does not link to, or that it links to in another profile; + - pages outside a profile's `functionalities/` folder; + - a remaining `requirements` section; + - ignored `conformance` and `extension` fields, and an ignored `extensions` block in `metadata.yml`. +- **Options and conditional requirements (ARCH-ADR-6).** + - Options listed under a variation point's `options` render as cards nested beneath it, each with its own id (such as `30.1`), level `OPTION`, key, badges, verification and test. + - A variation point shows its selection ("Meet at least *min* of its *n* options", plus *max* when set). + - An option met by claiming an extension links to that profile. + - `presented_by`, `applies_when` and `applies_when_all` (on a requirement, or on a functionality as a whole) show their keys, each linked to the key's view. + - A generated *Options and conditions* page is the "views by key" of ARCH-ADR-6. For every option key and every extension profile named in a condition, it lists the requirements that apply when it holds, grouped by functionality, with the option and its variation point at the top. It is in the sidebar under *Conformance profiles*. + - Options count towards the requirement total that the served checks compare. + - Warnings report: + - variation points with fewer than two options, an invalid `select`, or an `interaction`, `test` or `api_operation_id`; + - options without level `OPTION`, or with nested `select` or `options`; + - option ids not numbered `n.m` after their variation point; + - core variation points that cannot meet `min` without an extension; + - duplicate keys; + - conditions naming an unknown key or profile; + - options met by an unknown extension; + - `option_of`. +- **Verification method (ARCH-ADR-8).** A requirement with an `interaction` shows how it is verified: tested at that boundary, or, for `INTERNAL`, audited against evidence. Variation points are verified by counting the options that pass, and options met by an extension by the extension's tests. A requirement with neither `interaction` nor `observability` is shown as unclassified, with a warning. +- `toc.yml` entries ending in `/` publish that folder's files, relative to their section, with a download index and a sidebar link. A listed folder that does not exist fails the build. +- `terminology.yml` renders as a page with one heading per term. It shows the definition, abbreviation, notes, source, origin and related terms, and accepts both the `terms` (`term`/`definition`) and the `entry` (`designation`/`description`) forms. `references.yml` renders as a list of linked references with dates and abstracts. Any other YAML page is shown verbatim in a code block. +- Decision records: a Markdown page under `ADR/` that a published page links to is published under *Resources*, with a warning, and its links to other decision records are followed. Unlinked records are not published. +- Publishing several Building Blocks: + - [`publish/building-blocks.yml`](publish/building-blocks.yml) lists the Building Blocks to publish: Wallet (`feat/v2.0`) and Document Management (`v0.6`). + - [`scripts/publish.mjs`](scripts/publish.mjs) (`npm run publish`) fetches each source at its ref, or uses local checkouts with `--sources`. It builds and checks each one under `bb//`, and writes a landing page that names the commit each was built from. + - [`.github/workflows/pages.yml`](.github/workflows/pages.yml) runs the tests and the publish command on every push to `main`, on demand, and daily. It deploys the result to GitHub Pages at `https://basicavisual.github.io/govstack-specification-site/`. +- Tests: [`tests/conformance-profiles.test.mjs`](tests/conformance-profiles.test.mjs) covers profiles, options, conditions, verification, folder entries, YAML pages, root paths and decision records with an abstract Building Block. [`tests/publish.test.mjs`](tests/publish.test.mjs) covers the publish list and landing page. +- README sections on conformance profiles, options and verification, and on publishing several Building Blocks. + +### Changed + +- A local link or image path starting with `/` resolves against the specification's root and is published under the build base. For example, `/assets/cover.svg` built with `--base /bb/wallet/` becomes `/bb/wallet/assets/cover.svg`. A path that escapes the root fails. Previously such paths were left unchanged and their targets were not published. +- `observability` is shown only for requirements without an `interaction`, as in the cross-functional requirements. Where both are set, a warning says that `observability` is no longer read, and names both values when they disagree. +- Conditions are labelled *Applies when*, *Applies when any of* and *Applies when all of*, instead of *Any of* and *All of*. +- The requirements introduction counts options, and mentions "Unnumbered draft" only when a requirement has no id. It no longer calls every requirement an authoring draft. +- Sidebar section labels replace hyphens with spaces, so the section reads *Conformance profiles*, not *Conformance-profiles*. +- The adapter's source model (toc parsing, profiles, conditions, verification and YAML pages) moved into [`adapters/framework-model.mjs`](adapters/framework-model.mjs). + +### Fixed + +- `toc.yml` with subsections under any section, and an empty section such as `resources:` with no entries, no longer crash generation. +- Folder entries such as `api/` and `tests/` no longer fail with `EISDIR`, so `bb-template` builds again. +- `terminology.yml` and `references.yml` are no longer published as raw YAML under a Markdown page. They no longer get an HTML redirect written in place of the YAML file. +- An empty `documentation:` field no longer renders the text "null". +- A functionality description written as a YAML block scalar no longer ends with a stray line break. +- A `contract` or `test` given as a URN, such as `govstack:spec:bb:information-mediator`, is shown as written instead of becoming a broken local link. A web URL links as written. This fixes the Document Management build. From 521c413904025b0336d2a49d8293ba6ceb30aa2a Mon Sep 17 00:00:00 2001 From: "Ali G." Date: Tue, 24 Nov 2026 20:17:59 +0100 Subject: [PATCH 5/7] chore: release 0.2.0 Set the version to 0.2.0 and move the changelog entries under it. Add RELEASE_NOTES.md, with the steps for releasing a version and the actions maintainers, Building Block authors, renderer consumers and Pages publishers take to move to 0.2.0. Note that the Pages workflow is not triggered by Building Block repositories: their changes reach the site at the daily run, or sooner by running the workflow by hand. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/pages.yml | 3 +- CHANGELOG.md | 10 ++- README.md | 2 +- RELEASE_NOTES.md | 121 ++++++++++++++++++++++++++++++++++++ package-lock.json | 4 +- package.json | 2 +- 6 files changed, 136 insertions(+), 6 deletions(-) create mode 100644 RELEASE_NOTES.md diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index eebb7c8..ec88993 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -3,12 +3,13 @@ name: Publish specifications to GitHub Pages # deploys them as one site: /bb//, with a landing page at the root. # Every build runs the renderer's built-output and HTTP checks; one failure stops # the deploy, so the published site keeps its previous version. +# It is not triggered by the Building Block repositories: a change there reaches the site at the +# next daily run, or sooner by running this workflow by hand (Actions → Run workflow). on: push: branches: [main] workflow_dispatch: schedule: - # Building Block repositories change independently of this one. - cron: '17 4 * * *' permissions: contents: read diff --git a/CHANGELOG.md b/CHANGELOG.md index 21bca75..ad0f5ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ All notable changes to the GovStack specification renderer are recorded here. Th ## Unreleased +## 0.2.0 - 2026-11-24 + This release renders the Specification Framework changes proposed for the Architecture Working Group meeting of 25 November 2026: conformance profiles (ARCH-ADR-7), options and conditional requirements (ARCH-ADR-6) and the removal of the `observability` classifier (ARCH-ADR-8). The Wallet Building Block 2.0 draft is the first specification to use all three. Specifications that still use `requirements/` render as before, with warnings, so that Building Blocks can migrate one at a time. ### Added @@ -49,12 +51,14 @@ This release renders the Specification Framework changes proposed for the Archit - Publishing several Building Blocks: - [`publish/building-blocks.yml`](publish/building-blocks.yml) lists the Building Blocks to publish: Wallet (`feat/v2.0`) and Document Management (`v0.6`). - [`scripts/publish.mjs`](scripts/publish.mjs) (`npm run publish`) fetches each source at its ref, or uses local checkouts with `--sources`. It builds and checks each one under `bb//`, and writes a landing page that names the commit each was built from. - - [`.github/workflows/pages.yml`](.github/workflows/pages.yml) runs the tests and the publish command on every push to `main`, on demand, and daily. It deploys the result to GitHub Pages at `https://basicavisual.github.io/govstack-specification-site/`. + - [`.github/workflows/pages.yml`](.github/workflows/pages.yml) runs the tests and the publish command on every push to `main`, daily, and when started by hand. It deploys the result to GitHub Pages at `https://basicavisual.github.io/govstack-specification-site/`. Building Block repositories do not trigger it. - Tests: [`tests/conformance-profiles.test.mjs`](tests/conformance-profiles.test.mjs) covers profiles, options, conditions, verification, folder entries, YAML pages, root paths and decision records with an abstract Building Block. [`tests/publish.test.mjs`](tests/publish.test.mjs) covers the publish list and landing page. - README sections on conformance profiles, options and verification, and on publishing several Building Blocks. +- [`RELEASE_NOTES.md`](RELEASE_NOTES.md), with the steps for releasing a version of the renderer and the actions each kind of user takes when moving to it. ### Changed +- Version 0.2.0, up from 0.1.0. - A local link or image path starting with `/` resolves against the specification's root and is published under the build base. For example, `/assets/cover.svg` built with `--base /bb/wallet/` becomes `/bb/wallet/assets/cover.svg`. A path that escapes the root fails. Previously such paths were left unchanged and their targets were not published. - `observability` is shown only for requirements without an `interaction`, as in the cross-functional requirements. Where both are set, a warning says that `observability` is no longer read, and names both values when they disagree. - Conditions are labelled *Applies when*, *Applies when any of* and *Applies when all of*, instead of *Any of* and *All of*. @@ -70,3 +74,7 @@ This release renders the Specification Framework changes proposed for the Archit - An empty `documentation:` field no longer renders the text "null". - A functionality description written as a YAML block scalar no longer ends with a stray line break. - A `contract` or `test` given as a URN, such as `govstack:spec:bb:information-mediator`, is shown as written instead of becoming a broken local link. A web URL links as written. This fixes the Document Management build. + +## 0.1.0 + +First version: the shared Astro/Starlight renderer with the `api-guide` and `framework` profiles, native Scalar OpenAPI references, built-output and HTTP checks, and the composite build action. diff --git a/README.md b/README.md index 4674664..f37d9e3 100644 --- a/README.md +++ b/README.md @@ -113,7 +113,7 @@ npm run publish -- --sources .. --output /absolute/path/to/site --base / python3 -m http.server 4336 --directory /absolute/path/to/site ``` -[`.github/workflows/pages.yml`](.github/workflows/pages.yml) runs the tests and the same command on every push to `main`, on demand, and daily, and deploys the result to GitHub Pages. For this repository that is `https://basicavisual.github.io/govstack-specification-site/bb//`. The base is `//`, or `/` for a `.github.io` repository. Builds are marked unofficial. Before the first run, set **Settings → Pages → Source** to **GitHub Actions**. To add a Building Block, add it to the list; its repository must be public. +[`.github/workflows/pages.yml`](.github/workflows/pages.yml) runs the tests and the same command on every push to `main`, daily at 04:17 UTC, and when started by hand from the Actions tab (**Run workflow**). It then deploys the result to GitHub Pages. Building Block repositories do not trigger it: a new commit there reaches the site at the next daily run. To publish it sooner, run the workflow by hand. For this repository that is `https://basicavisual.github.io/govstack-specification-site/bb//`. The base is `//`, or `/` for a `.github.io` repository. Builds are marked unofficial. Before the first run, set **Settings → Pages → Source** to **GitHub Actions**. To add a Building Block, add it to the list; its repository must be public. ## Unofficial deployments diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md new file mode 100644 index 0000000..d9aa4ba --- /dev/null +++ b/RELEASE_NOTES.md @@ -0,0 +1,121 @@ +# Release Notes + +This file says what a developer does when the renderer's version goes up: the steps for releasing a version, and, for each version, the actions that maintainers, Building Block authors, renderer consumers and Pages publishers take to move to it. [CHANGELOG.md](CHANGELOG.md) lists every change in detail. + +## Releasing a version + +1. **Choose the number.** The renderer follows [Semantic Versioning](https://semver.org/). Until 1.0.0, the minor number marks changes that need action from anyone. The numbers go up as follows: + - **Major:** a specification source that built before now fails, or the command line, the composite action's inputs or the build manifest change incompatibly. + - **Minor:** the renderer accepts new source structures or renders more of them. + - **Patch:** fixes only. +2. **Set the version** in `package.json` and `package-lock.json` together, without creating a tag yet: + + ```sh + npm version --no-git-tag-version + ``` + +3. **Update [CHANGELOG.md](CHANGELOG.md).** Move the entries under *Unreleased* to a new `## - ` heading, and leave *Unreleased* empty above it. +4. **Add a section to this file** for the version, with the actions each kind of user takes, as for 0.2.0 below. Leave out a group that has nothing to do. +5. **Check the release** against the tests and every published Building Block: + + ```sh + npm ci --ignore-scripts + npm test + npm run publish -- --output /absolute/path/to/scratch-site --base / --unofficial + ``` + + The publish run fetches each Building Block in `publish/building-blocks.yml` at its ref, then builds and checks it. Read the warnings in each `.generated/framework-*/publication.json`, and note in this file the ones Building Block authors need to act on. +6. **Commit and tag** on a branch, then merge into `main`: + + ```sh + git commit -m "chore: release " + git tag -a v -m "Release " + git push ali v + ``` + + Push to the `ali` remote (`basicavisual/govstack-specification-site`), not `origin`. +7. **Publish the site.** Merging into `main` runs the Pages workflow and deploys the release. Check that the run in the **Actions** tab succeeded. +8. **Tell consumers** the full commit of the release, which they pin as `GOVSTACK_SITE_RENDERER_REF`, and point them to this file. + +*** + +## Version 0.2.0 + +*Version date: 24 November 2026* + +### Overview + +The renderer now renders the Specification Framework changes proposed for the Architecture Working Group meeting of 25 November 2026: + +- conformance profiles (ARCH-ADR-7); +- options and conditional requirements (ARCH-ADR-6); +- the verification method that follows from `interaction` (ARCH-ADR-8). + +It also publishes several Building Blocks to GitHub Pages as one site. The Wallet Building Block 2.0 draft is the first specification to use all three changes. Sources that still use `requirements/` render as before, with warnings, so nothing has to migrate at once. + +### Renderer maintainers + +- Use Node 24.11 or later, with npm. If your Node install has no npm, reinstall Node, or use `corepack npm@11.6.2`. +- Run `npm ci --ignore-scripts` after pulling. Only the version in the lockfile changed, but this keeps `node_modules` matched to it. +- The source model now lives in `adapters/framework-model.mjs`. Toc parsing, profiles, conditions, verification and YAML pages belong there. Rendering stays in `adapters/framework.mjs`. + +### Building Block authors + +Migrating is optional in this version, but the warnings tell you what to change. To move a specification to the new layout: + +1. **Conformance profiles.** + - Replace `requirements/` with `conformance-profiles//functionalities/`, one folder per profile. The folder name is the profile's permanent id, in kebab-case. + - Give each profile an `introduction.md` whose front matter declares `title`, `type` (`CORE` or `EXTENSION`), `description`, `requires`, and optionally `role` and `reference_architecture`. A specification has exactly one `CORE`. + - Link every functionality of the profile from its introduction. +2. **toc.yml.** Replace the `requirements` section with `conformance-profiles`, one subsection per profile folder, with `introduction.md` first: + + ```yaml + conformance-profiles: + - core-profile: + - introduction.md + - functionalities/functionality-a.md + ``` + +3. **Remove** the `conformance` and `extension` fields from functionality files, and the `extensions` block from `metadata.yml`. They are now ignored. +4. **Options.** + - List options under their variation point's `options`, with `level: OPTION` and ids `n.m`. + - Give a `key` to each option that other requirements name in `applies_when`, and an `extension` to each option met by claiming an extension profile. + - Replace `option_of` and file-level `cardinality` with `select` on the variation point. +5. **Verification.** + - Set `interaction` on every requirement except variation points, and remove `observability`. + - Use `INTERNAL` only for what cannot be seen at any boundary, and list the evidence in `documentation`. + - A requirement with neither field shows as *Unclassified*. + +Also check these behaviour changes, whether or not you migrate: + +- **Root paths.** A link or image path starting with `/` now means the specification's root. A site built with `--base /bb/wallet/` turns `/assets/x.png` into `/bb/wallet/assets/x.png`. Write links to other Building Blocks or to `specs.govstack.global` as full `https://` URLs. +- **Folder entries.** A `toc.yml` entry ending in `/` names a folder relative to its section, so `resources: [tests/]` means `resources/tests/`. A missing folder now fails the build instead of being skipped. +- **Decision records.** A link to a Markdown page under `ADR/` publishes that page under *Resources*, with a warning. A link to any other Markdown page that `toc.yml` does not list still fails. +- **Terminology and references.** `terminology.yml` and `references.yml` now render as pages instead of raw YAML. `references.md` works as before. +- **Contracts and tests.** A URN in `contract` or `test`, such as `govstack:spec:bb:information-mediator`, is shown as text instead of a broken link. + +After building, read `warnings` in `.generated/framework-*/publication.json`. It names each source line to correct. + +### Renderer consumers + +These steps apply to CI that pins the renderer or uses `action.yml`: + +- **Pin the new commit.** Set `GOVSTACK_SITE_RENDERER_REF` to the full commit of the 0.2.0 release, in `basicavisual/govstack-specification-site`. The action's inputs are unchanged. +- **Update anything that reads the build manifest (`publication.json`):** + - `requirementCount` now includes options; + - `profiles` lists the conformance profiles; + - a generated page is marked `generated: true` and has no source file; + - `.yml` pages have no legacy `.html` redirect. +- **Update anything that reads rendered requirement cards:** + - options are `requirement-card option` elements nested inside their variation point's card; + - conditions are labelled *Applies when*, *Applies when any of* and *Applies when all of*, instead of *Any of* and *All of*; + - *Verification* is a new row. + +### Pages publishers + +- **Enable GitHub Actions once.** On a fork they start disabled: open the **Actions** tab and enable workflows. +- **Set the Pages source:** in **Settings → Pages**, set **Source** to **GitHub Actions**. +- **List the Building Blocks** in `publish/building-blocks.yml`. Each needs an `id`, `title`, `repository` and `ref`, and its repository must be public. A Building Block that fails its checks stops the whole deploy. +- **When it runs.** The workflow runs on every push to `main` and daily at 04:17 UTC, and publishes at `https://basicavisual.github.io/govstack-specification-site/bb//`, marked as an unofficial preview. +- **Publishing a Building Block change sooner.** Building Block repositories do not trigger the workflow, so their changes otherwise wait for the next daily run. To publish one sooner, go to **Actions → Publish specifications to GitHub Pages → Run workflow** on `main`. +- **Re-enabling the schedule.** GitHub disables a scheduled workflow after 60 days without activity in this repository. If that happens, re-enable it from the **Actions** tab. diff --git a/package-lock.json b/package-lock.json index 4b6d15f..f423fa5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "govstack-specification-site", - "version": "0.1.0", + "version": "0.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "govstack-specification-site", - "version": "0.1.0", + "version": "0.2.0", "dependencies": { "@astrojs/markdown-remark": "7.3.3", "@astrojs/starlight": "0.42.6", diff --git a/package.json b/package.json index 5249331..a17c909 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "govstack-specification-site", - "version": "0.1.0", + "version": "0.2.0", "private": true, "type": "module", "engines": { From bf6526c7fc3de41a4449f90a898f0f2e8a8974da Mon Sep 17 00:00:00 2001 From: "Ali G." Date: Tue, 24 Nov 2026 20:27:25 +0100 Subject: [PATCH 6/7] docs: make Pages publishing independent of the hosting repository Describe the site address as https://.github.io// and the release steps without naming a particular fork or remote. Make deploying opt-in through the repository variable PUBLISH_PAGES: without it, pushes and manual runs still build and check every Building Block, the daily run is skipped, and nothing is deployed. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/pages.yml | 5 ++++- CHANGELOG.md | 2 +- README.md | 2 +- RELEASE_NOTES.md | 11 ++++++----- publish/building-blocks.yml | 2 +- 5 files changed, 13 insertions(+), 9 deletions(-) diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index ec88993..fb8895d 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -3,6 +3,8 @@ name: Publish specifications to GitHub Pages # deploys them as one site: /bb//, with a landing page at the root. # Every build runs the renderer's built-output and HTTP checks; one failure stops # the deploy, so the published site keeps its previous version. +# Deploying is opt-in: set the repository variable PUBLISH_PAGES to true. Without it, +# pushes and manual runs still build and check, and the daily run is skipped. # It is not triggered by the Building Block repositories: a change there reaches the site at the # next daily run, or sooner by running this workflow by hand (Actions → Run workflow). on: @@ -18,6 +20,7 @@ concurrency: cancel-in-progress: false jobs: build: + if: github.event_name != 'schedule' || vars.PUBLISH_PAGES == 'true' runs-on: ubuntu-latest steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 @@ -45,7 +48,7 @@ jobs: with: path: ${{ runner.temp }}/site deploy: - if: github.ref == 'refs/heads/main' + if: github.ref == 'refs/heads/main' && vars.PUBLISH_PAGES == 'true' needs: build runs-on: ubuntu-latest permissions: diff --git a/CHANGELOG.md b/CHANGELOG.md index ad0f5ad..5e655e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,7 +51,7 @@ This release renders the Specification Framework changes proposed for the Archit - Publishing several Building Blocks: - [`publish/building-blocks.yml`](publish/building-blocks.yml) lists the Building Blocks to publish: Wallet (`feat/v2.0`) and Document Management (`v0.6`). - [`scripts/publish.mjs`](scripts/publish.mjs) (`npm run publish`) fetches each source at its ref, or uses local checkouts with `--sources`. It builds and checks each one under `bb//`, and writes a landing page that names the commit each was built from. - - [`.github/workflows/pages.yml`](.github/workflows/pages.yml) runs the tests and the publish command on every push to `main`, daily, and when started by hand. It deploys the result to GitHub Pages at `https://basicavisual.github.io/govstack-specification-site/`. Building Block repositories do not trigger it. + - [`.github/workflows/pages.yml`](.github/workflows/pages.yml) runs the tests and the publish command on every push to `main`, daily, and when started by hand. It deploys the result to GitHub Pages at `https://.github.io//` when the repository variable `PUBLISH_PAGES` is `true`. Building Block repositories do not trigger it. - Tests: [`tests/conformance-profiles.test.mjs`](tests/conformance-profiles.test.mjs) covers profiles, options, conditions, verification, folder entries, YAML pages, root paths and decision records with an abstract Building Block. [`tests/publish.test.mjs`](tests/publish.test.mjs) covers the publish list and landing page. - README sections on conformance profiles, options and verification, and on publishing several Building Blocks. - [`RELEASE_NOTES.md`](RELEASE_NOTES.md), with the steps for releasing a version of the renderer and the actions each kind of user takes when moving to it. diff --git a/README.md b/README.md index f37d9e3..0e793b9 100644 --- a/README.md +++ b/README.md @@ -113,7 +113,7 @@ npm run publish -- --sources .. --output /absolute/path/to/site --base / python3 -m http.server 4336 --directory /absolute/path/to/site ``` -[`.github/workflows/pages.yml`](.github/workflows/pages.yml) runs the tests and the same command on every push to `main`, daily at 04:17 UTC, and when started by hand from the Actions tab (**Run workflow**). It then deploys the result to GitHub Pages. Building Block repositories do not trigger it: a new commit there reaches the site at the next daily run. To publish it sooner, run the workflow by hand. For this repository that is `https://basicavisual.github.io/govstack-specification-site/bb//`. The base is `//`, or `/` for a `.github.io` repository. Builds are marked unofficial. Before the first run, set **Settings → Pages → Source** to **GitHub Actions**. To add a Building Block, add it to the list; its repository must be public. +[`.github/workflows/pages.yml`](.github/workflows/pages.yml) runs the tests and the same command on every push to `main`, daily at 04:17 UTC, and when started by hand from the Actions tab (**Run workflow**). It then deploys the result to GitHub Pages. Building Block repositories do not trigger it: a new commit there reaches the site at the next daily run. To publish it sooner, run the workflow by hand. The site is at `https://.github.io//bb//`. The base is `//`, or `/` for a `.github.io` repository. Builds are marked unofficial. Deploying is opt-in: set the repository variable `PUBLISH_PAGES` to `true`, and set **Settings → Pages → Source** to **GitHub Actions**. Without the variable, pushes still build and check every Building Block, and the daily run is skipped. To add a Building Block, add it to the list; its repository must be public. ## Unofficial deployments diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index d9aa4ba..aa6cce5 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -30,11 +30,11 @@ This file says what a developer does when the renderer's version goes up: the st ```sh git commit -m "chore: release " git tag -a v -m "Release " - git push ali v + git push v ``` - Push to the `ali` remote (`basicavisual/govstack-specification-site`), not `origin`. -7. **Publish the site.** Merging into `main` runs the Pages workflow and deploys the release. Check that the run in the **Actions** tab succeeded. + Push to the repository you publish the renderer from. +7. **Publish the site.** Where `PUBLISH_PAGES` is set, merging into `main` runs the Pages workflow and deploys the release. Check that the run in the **Actions** tab succeeded. 8. **Tell consumers** the full commit of the release, which they pin as `GOVSTACK_SITE_RENDERER_REF`, and point them to this file. *** @@ -100,7 +100,7 @@ After building, read `warnings` in `.generated/framework-*/publication.json`. It These steps apply to CI that pins the renderer or uses `action.yml`: -- **Pin the new commit.** Set `GOVSTACK_SITE_RENDERER_REF` to the full commit of the 0.2.0 release, in `basicavisual/govstack-specification-site`. The action's inputs are unchanged. +- **Pin the new commit.** Set `GOVSTACK_SITE_RENDERER_REF` to the full commit of the 0.2.0 release in the renderer repository you use. The action's inputs are unchanged. - **Update anything that reads the build manifest (`publication.json`):** - `requirementCount` now includes options; - `profiles` lists the conformance profiles; @@ -114,8 +114,9 @@ These steps apply to CI that pins the renderer or uses `action.yml`: ### Pages publishers - **Enable GitHub Actions once.** On a fork they start disabled: open the **Actions** tab and enable workflows. +- **Opt in to deploying:** in **Settings → Secrets and variables → Actions → Variables**, set the repository variable `PUBLISH_PAGES` to `true`. Without it, the workflow builds and checks on pushes but never deploys, and skips the daily run. - **Set the Pages source:** in **Settings → Pages**, set **Source** to **GitHub Actions**. - **List the Building Blocks** in `publish/building-blocks.yml`. Each needs an `id`, `title`, `repository` and `ref`, and its repository must be public. A Building Block that fails its checks stops the whole deploy. -- **When it runs.** The workflow runs on every push to `main` and daily at 04:17 UTC, and publishes at `https://basicavisual.github.io/govstack-specification-site/bb//`, marked as an unofficial preview. +- **When it runs.** The workflow runs on every push to `main` and daily at 04:17 UTC, and publishes at `https://.github.io//bb//`, marked as an unofficial preview. - **Publishing a Building Block change sooner.** Building Block repositories do not trigger the workflow, so their changes otherwise wait for the next daily run. To publish one sooner, go to **Actions → Publish specifications to GitHub Pages → Run workflow** on `main`. - **Re-enabling the schedule.** GitHub disables a scheduled workflow after 60 days without activity in this repository. If that happens, re-enable it from the **Actions** tab. diff --git a/publish/building-blocks.yml b/publish/building-blocks.yml index 74ca62e..0d8a9a8 100644 --- a/publish/building-blocks.yml +++ b/publish/building-blocks.yml @@ -1,7 +1,7 @@ # Building Blocks published to GitHub Pages by .github/workflows/pages.yml. # # Each entry is built from its repository at `ref` and served at -# https://basicavisual.github.io/govstack-specification-site/bb// +# https://.github.io//bb// # # id: folder name under /bb/; lowercase kebab-case, never reused # title: name on the landing page From 9f764338b04b1c555073cf16630c8987def5e639 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Mon, 30 Nov 2026 20:16:50 +0000 Subject: [PATCH 7/7] fix: preserve specification links and verify publishing before merge Preserve GitBook aliases and render the Wallet and Document Management sources consistently. Validate combined builds on pull requests and promote only complete, checked output. Signed-off-by: Jeremi Joslin --- .github/workflows/pages.yml | 7 +- CHANGELOG.md | 15 +- README.md | 29 +++- RELEASE_NOTES.md | 11 +- adapters/framework-model.mjs | 76 +++++++--- adapters/framework.mjs | 209 +++++++++++++++++++++++----- scripts/publish.mjs | 108 ++++++++++---- tests/conformance-profiles.test.mjs | 92 +++++++++++- tests/framework-model.test.mjs | 122 ++++++++++++++++ tests/framework.test.mjs | 77 ++++++++++ tests/publish.test.mjs | 147 ++++++++++++++++++- 11 files changed, 790 insertions(+), 103 deletions(-) create mode 100644 tests/framework-model.test.mjs diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index fb8895d..483626d 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -4,12 +4,13 @@ name: Publish specifications to GitHub Pages # Every build runs the renderer's built-output and HTTP checks; one failure stops # the deploy, so the published site keeps its previous version. # Deploying is opt-in: set the repository variable PUBLISH_PAGES to true. Without it, -# pushes and manual runs still build and check, and the daily run is skipped. +# pushes, pull requests, and manual runs still build and check, and the daily run is skipped. # It is not triggered by the Building Block repositories: a change there reaches the site at the # next daily run, or sooner by running this workflow by hand (Actions → Run workflow). on: push: branches: [main] + pull_request: workflow_dispatch: schedule: - cron: '17 4 * * *' @@ -44,7 +45,9 @@ jobs: shopt -s nocasematch if [[ "$REPOSITORY_NAME" == "$REPOSITORY_OWNER.github.io" ]]; then base=/; else base="/$REPOSITORY_NAME/"; fi node scripts/publish.mjs --output "$RUNNER_TEMP/site" --checkouts "$RUNNER_TEMP/sources" --base "$base" --unofficial - - uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 + - name: Upload Pages artifact + if: github.ref == 'refs/heads/main' && vars.PUBLISH_PAGES == 'true' + uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 with: path: ${{ runner.temp }}/site deploy: diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e655e0..8f69b44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,16 +42,16 @@ This release renders the Specification Framework changes proposed for the Archit - core variation points that cannot meet `min` without an extension; - duplicate keys; - conditions naming an unknown key or profile; - - options met by an unknown extension; + - options met by an unknown extension or declaring their own interaction, operation, or test while met by an extension; - `option_of`. -- **Verification method (ARCH-ADR-8).** A requirement with an `interaction` shows how it is verified: tested at that boundary, or, for `INTERNAL`, audited against evidence. Variation points are verified by counting the options that pass, and options met by an extension by the extension's tests. A requirement with neither `interaction` nor `observability` is shown as unclassified, with a warning. +- **Verification method (ARCH-ADR-8).** A requirement with an `interaction` identifies the boundary to test or the evidence to audit for `INTERNAL`. Variation points count the options that pass. Options met by claiming an extension use the extension's tests. Other requirements without a verification method appear as unclassified. - `toc.yml` entries ending in `/` publish that folder's files, relative to their section, with a download index and a sidebar link. A listed folder that does not exist fails the build. -- `terminology.yml` renders as a page with one heading per term. It shows the definition, abbreviation, notes, source, origin and related terms, and accepts both the `terms` (`term`/`definition`) and the `entry` (`designation`/`description`) forms. `references.yml` renders as a list of linked references with dates and abstracts. Any other YAML page is shown verbatim in a code block. +- `terminology.yml` renders as a page with one heading per term. It shows the definition, abbreviation, notes, source, origin and related terms, and accepts both the `terms` (`term`/`definition`) and the `entry` (`designation`/`description`) forms. `references.yml` supports both flat and grouped citations. Other YAML pages display their source. - Decision records: a Markdown page under `ADR/` that a published page links to is published under *Resources*, with a warning, and its links to other decision records are followed. Unlinked records are not published. - Publishing several Building Blocks: - [`publish/building-blocks.yml`](publish/building-blocks.yml) lists the Building Blocks to publish: Wallet (`feat/v2.0`) and Document Management (`v0.6`). - - [`scripts/publish.mjs`](scripts/publish.mjs) (`npm run publish`) fetches each source at its ref, or uses local checkouts with `--sources`. It builds and checks each one under `bb//`, and writes a landing page that names the commit each was built from. - - [`.github/workflows/pages.yml`](.github/workflows/pages.yml) runs the tests and the publish command on every push to `main`, daily, and when started by hand. It deploys the result to GitHub Pages at `https://.github.io//` when the repository variable `PUBLISH_PAGES` is `true`. Building Block repositories do not trigger it. + - [`scripts/publish.mjs`](scripts/publish.mjs) (`npm run publish`) builds and checks the full site in staging, then moves it into a new or empty output directory. The landing page shows the fetched revision or the local checkout and any uncommitted changes. + - [`.github/workflows/pages.yml`](.github/workflows/pages.yml) runs the tests and builds every configured Building Block on pull requests, pushes to `main`, and manual runs. Setting `PUBLISH_PAGES` to `true` enables deployment from `main` and daily builds. - Tests: [`tests/conformance-profiles.test.mjs`](tests/conformance-profiles.test.mjs) covers profiles, options, conditions, verification, folder entries, YAML pages, root paths and decision records with an abstract Building Block. [`tests/publish.test.mjs`](tests/publish.test.mjs) covers the publish list and landing page. - README sections on conformance profiles, options and verification, and on publishing several Building Blocks. - [`RELEASE_NOTES.md`](RELEASE_NOTES.md), with the steps for releasing a version of the renderer and the actions each kind of user takes when moving to it. @@ -60,7 +60,7 @@ This release renders the Specification Framework changes proposed for the Archit - Version 0.2.0, up from 0.1.0. - A local link or image path starting with `/` resolves against the specification's root and is published under the build base. For example, `/assets/cover.svg` built with `--base /bb/wallet/` becomes `/bb/wallet/assets/cover.svg`. A path that escapes the root fails. Previously such paths were left unchanged and their targets were not published. -- `observability` is shown only for requirements without an `interaction`, as in the cross-functional requirements. Where both are set, a warning says that `observability` is no longer read, and names both values when they disagree. +- The renderer displays legacy `observability` when no requirement in the specification declares `interaction`. Once a requirement declares `interaction`, the renderer reports any legacy `observability` with a warning. - Conditions are labelled *Applies when*, *Applies when any of* and *Applies when all of*, instead of *Any of* and *All of*. - The requirements introduction counts options, and mentions "Unnumbered draft" only when a requirement has no id. It no longer calls every requirement an authoring draft. - Sidebar section labels replace hyphens with spaces, so the section reads *Conformance profiles*, not *Conformance-profiles*. @@ -68,6 +68,9 @@ This release renders the Specification Framework changes proposed for the Archit ### Fixed +- Former routes defined in `.gitbook.yaml` can continue to serve moved pages, including their links to anchors. +- Linked decision records use `resources/adr/` so both the canonical page and the source-shaped alias build on case-insensitive filesystems. +- Functionality pages with empty requirements retain their profile and capabilities. - `toc.yml` with subsections under any section, and an empty section such as `resources:` with no entries, no longer crash generation. - Folder entries such as `api/` and `tests/` no longer fail with `EISDIR`, so `bb-template` builds again. - `terminology.yml` and `references.yml` are no longer published as raw YAML under a Markdown page. They no longer get an HTML redirect written in place of the YAML file. diff --git a/README.md b/README.md index 0e793b9..b0b2514 100644 --- a/README.md +++ b/README.md @@ -24,13 +24,18 @@ Framework sources can use the layout of the Specification Framework's ARCH-ADR-7 - **Conformance profiles (ARCH-ADR-7).** `toc.yml` lists `conformance-profiles` as one subsection per profile folder, with `introduction.md` first. The pages of a subsection resolve relative to that folder. Each introduction is served at the folder's route (`/conformance-profiles//`), because the folder name is the profile id. Its front matter (`type`, `description`, `requires`, `role`, `reference_architecture`) becomes a summary above the page. Functionality pages name their profile, the home page lists the profiles, and the sidebar groups each profile with a Core or Extension badge. Generation fails unless there is exactly one `CORE`, `requires` names only extension profiles without cycles, and the core requires nothing. A functionality missing from its introduction's links, `conformance` and `extension` fields, and `metadata.yml` `extensions` produce warnings and are ignored. - **Options and conditions (ARCH-ADR-6).** Options listed under a variation point's `options` render as cards nested beneath it, with `select`, `key`, `extension` (linked to the profile that meets the option), `presented_by`, `applies_when` and `applies_when_all`. A generated *Options and conditions* page lists, for every option key and every extension profile used in a condition, the requirements that apply when it holds. Conditions link to it. Options count towards the requirement total. Structural rules (at least two options, `select.min`, `n.m` ids, no `interaction` on a variation point, the core meeting `min` without extensions) are reported as warnings. -- **Verification (ARCH-ADR-8).** With an `interaction`, a card shows how the requirement is verified: tested at that boundary, or audited against evidence for `INTERNAL`. `observability` is then not shown, and a value that disagrees is reported. Without an `interaction`, as in the cross-functional requirements, `observability` is shown as before. +- **Verification (ARCH-ADR-8).** A card identifies the boundary to test or the evidence to audit for `INTERNAL`. When any requirement declares `interaction`, requirements without it appear as unclassified, except variation points and options verified through an extension. The renderer warns about `observability` in that mode. It displays `observability` for specifications where no requirement declares `interaction`, such as the cross-functional requirements. A local link or image path that starts with `/` resolves against the specification's root, and is published under the build's `--base`. With `--base /bb/wallet/`, `/assets/cover.svg` becomes `/bb/wallet/assets/cover.svg`, so a specification only ever refers to its own assets. A path that escapes the root fails. -Decision records are not part of `toc.yml` yet. A Markdown page under `ADR/` that a published page links to is published as if it were listed under `resources`, with a warning, and its own links to other decision records are followed. Unlinked records are not published, and a link to any other unlisted Markdown page still fails. +A published page can link to an unlisted Markdown decision record under `ADR/`. The renderer adds the record to Resources at `resources/adr/` and follows its links to other decision records. Unlinked records stay outside the publication. Other Markdown pages must appear in `toc.yml`. -`toc.yml` entries ending in `/` publish that folder's files with a download index, relative to their section, and fail if the folder does not exist. `terminology.yml` (`terms` with `term`/`definition`, or `entry` with `designation`/`description`) and `references.yml` render as pages, with one heading per term. Any other YAML page is shown verbatim. +`toc.yml` entries ending in `/` publish that folder's files with a download index, relative to their section. The build fails if the folder is missing. `terminology.yml` (`terms` with `term`/`definition`, or `entry` with `designation`/`description`) renders with one heading per term. `references.yml` supports both lists of citations and citations grouped by subject. Other YAML pages display their source. + +The root `.gitbook.yaml` can map former URLs to published pages, anchors, and +support files. A page mapping from a directory-style URL emits a directory and an +`.html` alias. The mapping sets its explicit query values and fragment, with the +incoming URL supplying other query values and a fallback fragment. ## OpenAPI references @@ -103,17 +108,29 @@ input. Use a static build plus `preview` to verify the Pagefind search index. /bb// one specification site per Building Block, built with the base bb// ``` -Every Building Block is built and then checked as in `build` and `test-served`. Any failure stops the run. Root paths in a specification resolve under its own `bb//` folder. +Use a new or empty output directory. The publisher builds and checks every +Building Block in a staging directory and moves the complete site into the +output directory after all checks pass. Root paths in a specification resolve +under its own `bb//` folder. The landing page identifies local checkouts and +marks any uncommitted changes when you build with `--sources`. ```sh -# Fetch each source at its ref, as CI does (checkouts go to .generated/publish-sources by default) +# Fetch each source at its ref, as CI does npm run publish -- --output /absolute/path/to/site --base / --unofficial # Or build from local checkouts named after each repository, such as ../bb-wallet npm run publish -- --sources .. --output /absolute/path/to/site --base / python3 -m http.server 4336 --directory /absolute/path/to/site ``` -[`.github/workflows/pages.yml`](.github/workflows/pages.yml) runs the tests and the same command on every push to `main`, daily at 04:17 UTC, and when started by hand from the Actions tab (**Run workflow**). It then deploys the result to GitHub Pages. Building Block repositories do not trigger it: a new commit there reaches the site at the next daily run. To publish it sooner, run the workflow by hand. The site is at `https://.github.io//bb//`. The base is `//`, or `/` for a `.github.io` repository. Builds are marked unofficial. Deploying is opt-in: set the repository variable `PUBLISH_PAGES` to `true`, and set **Settings → Pages → Source** to **GitHub Actions**. Without the variable, pushes still build and check every Building Block, and the daily run is skipped. To add a Building Block, add it to the list; its repository must be public. +[`.github/workflows/pages.yml`](.github/workflows/pages.yml) tests and builds +the combined site on pull requests, pushes to `main`, and manual runs. To enable +deployments from `main` and the daily run at 04:17 UTC, set the repository +variable `PUBLISH_PAGES` to `true` and select **GitHub Actions** in **Settings → +Pages → Source**. The unofficial site is at +`https://.github.io//bb//`. The base is `//`, +or `/` for a `.github.io` repository. To publish a Building Block change +before the next daily run, start the workflow on `main` from the Actions tab. +Every repository in the publication list must be public. ## Unofficial deployments diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index aa6cce5..ae8ea0c 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -84,14 +84,15 @@ Migrating is optional in this version, but the warnings tell you what to change. 5. **Verification.** - Set `interaction` on every requirement except variation points, and remove `observability`. - Use `INTERNAL` only for what cannot be seen at any boundary, and list the evidence in `documentation`. - - A requirement with neither field shows as *Unclassified*. + - When any requirement declares `interaction`, the renderer uses the same verification model throughout the specification. A requirement without an interaction shows as *Unclassified* unless it is a variation point or an option verified through an extension. Also check these behaviour changes, whether or not you migrate: - **Root paths.** A link or image path starting with `/` now means the specification's root. A site built with `--base /bb/wallet/` turns `/assets/x.png` into `/bb/wallet/assets/x.png`. Write links to other Building Blocks or to `specs.govstack.global` as full `https://` URLs. - **Folder entries.** A `toc.yml` entry ending in `/` names a folder relative to its section, so `resources: [tests/]` means `resources/tests/`. A missing folder now fails the build instead of being skipped. -- **Decision records.** A link to a Markdown page under `ADR/` publishes that page under *Resources*, with a warning. A link to any other Markdown page that `toc.yml` does not list still fails. -- **Terminology and references.** `terminology.yml` and `references.yml` now render as pages instead of raw YAML. `references.md` works as before. +- **Decision records.** A link to an unlisted Markdown page under `ADR/` publishes the record under *Resources* at `resources/adr/`. List other Markdown pages in `toc.yml`. +- **Terminology and references.** `terminology.yml` and `references.yml` render as readable pages. References can be flat or grouped by subject. +- **Former URLs.** Add mappings to `redirects` in the root `.gitbook.yaml` to preserve links when pages move. The renderer verifies that each target resolves to a published page, anchor, or support file. - **Contracts and tests.** A URN in `contract` or `test`, such as `govstack:spec:bb:information-mediator`, is shown as text instead of a broken link. After building, read `warnings` in `.generated/framework-*/publication.json`. It names each source line to correct. @@ -114,9 +115,9 @@ These steps apply to CI that pins the renderer or uses `action.yml`: ### Pages publishers - **Enable GitHub Actions once.** On a fork they start disabled: open the **Actions** tab and enable workflows. -- **Opt in to deploying:** in **Settings → Secrets and variables → Actions → Variables**, set the repository variable `PUBLISH_PAGES` to `true`. Without it, the workflow builds and checks on pushes but never deploys, and skips the daily run. +- **Enable deployments.** In **Settings → Secrets and variables → Actions → Variables**, set `PUBLISH_PAGES` to `true` to enable deployment from `main` and the daily run. - **Set the Pages source:** in **Settings → Pages**, set **Source** to **GitHub Actions**. - **List the Building Blocks** in `publish/building-blocks.yml`. Each needs an `id`, `title`, `repository` and `ref`, and its repository must be public. A Building Block that fails its checks stops the whole deploy. -- **When it runs.** The workflow runs on every push to `main` and daily at 04:17 UTC, and publishes at `https://.github.io//bb//`, marked as an unofficial preview. +- **Check before merging.** Pull requests build and check every configured Building Block. Pushes to `main` and manual runs also build the site. With deployment enabled, the daily run starts at 04:17 UTC and the unofficial preview is published at `https://.github.io//bb//`. - **Publishing a Building Block change sooner.** Building Block repositories do not trigger the workflow, so their changes otherwise wait for the next daily run. To publish one sooner, go to **Actions → Publish specifications to GitHub Pages → Run workflow** on `main`. - **Re-enabling the schedule.** GitHub disables a scheduled workflow after 60 days without activity in this repository. If that happens, re-enable it from the **Actions** tab. diff --git a/adapters/framework-model.mjs b/adapters/framework-model.mjs index 09b0aa2..84bf45a 100644 --- a/adapters/framework-model.mjs +++ b/adapters/framework-model.mjs @@ -283,6 +283,9 @@ export function checkOptions(page, profile, warnings) { if (requirement.select.max !== undefined && !(Number.isInteger(requirement.select.max) && requirement.select.max >= min)) { warnings.push(`${page.sourceName}: select.max must be at least select.min`); } + if (Number.isInteger(requirement.select.max) && requirement.select.max > options.length) { + warnings.push(`${page.sourceName}: select.max must be no greater than the number of options`); + } for (const field of ['interaction', 'test', 'api_operation_id']) { if (requirement[field]) warnings.push(`${page.sourceName}: a variation point carries no ${field}; it is verified by counting the options that pass`); } @@ -290,6 +293,13 @@ export function checkOptions(page, profile, warnings) { for (const option of options) { if (option?.level !== 'OPTION') warnings.push(`${page.sourceName}: option ${option?.key || option?.id || '(unnamed)'} must have level OPTION`); if (option?.select || option?.options) warnings.push(`${page.sourceName}: an option has no select and no options`); + if (option?.extension) { + for (const field of ['interaction', 'api_operation_id', 'test']) { + if (option[field] !== undefined) { + warnings.push(`${page.sourceName}: extension-backed option ${option.key || option.id || option.extension} must not declare ${field}; the extension profile supplies its verification`); + } + } + } const optionId = option?.id ? String(option.id) : ''; if (optionId && (!parentId || !optionId.startsWith(`${parentId}.`) || !/^\d+$/.test(optionId.slice(parentId.length + 1)))) { warnings.push(`${page.sourceName}: option ${optionId} must be numbered ${parentId || 'n'}.m after its variation point`); @@ -314,10 +324,9 @@ const BOUNDARY = { FILE: 'file', }; -// How a requirement is verified (ARCH-ADR-8). With an interaction, the method -// follows from it and observability is no longer read. Without one, as in the -// cross-functional requirements, observability is read as before. -export function verificationOf(requirement, { isVariationPoint, isExtensionOption }) { +// ARCH-ADR-8 derives verification from interaction. Legacy observability +// applies when no requirement in the specification declares an interaction. +export function verificationOf(requirement, { isVariationPoint, isExtensionOption, legacyObservability = false }) { if (isVariationPoint) return { method: 'counted', label: 'Counts the options that pass' }; if (isExtensionOption) return { method: 'extension', label: "By the extension's tests" }; const interaction = requirement.interaction; @@ -328,7 +337,7 @@ export function verificationOf(requirement, { isVariationPoint, isExtensionOptio return { method: 'observable', label: `Tested at the ${BOUNDARY[interaction]} boundary` }; } if (interaction) return { method: 'unknown', label: `Unknown interaction ${interaction}` }; - if (requirement.observability) return { method: 'legacy', label: undefined }; + if (legacyObservability && requirement.observability) return { method: 'legacy', label: undefined }; return { method: 'unclassified', label: 'Unclassified' }; } @@ -363,15 +372,34 @@ function terminologyEntries(data) { }); } -function referenceEntries(data) { - const list = Array.isArray(data) ? data : data?.references; - if (!Array.isArray(list)) return undefined; - return list.map((item) => ({ +function referenceEntry(item) { + if (typeof item === 'string') { + return { title: yamlText(item), url: '', date: '', abstract: '' }; + } + return { title: yamlText(item?.title ?? item?.name), url: yamlText(item?.url ?? item?.link), date: yamlText(item?.date), abstract: yamlText(item?.abstract ?? item?.description), - })); + }; +} + +function referenceGroups(data) { + const references = Array.isArray(data) ? data : data?.references; + if (Array.isArray(references)) { + return [{ title: '', entries: references.map(referenceEntry) }]; + } + if (!references || typeof references !== 'object') return undefined; + const groups = []; + for (const [key, list] of Object.entries(references)) { + if (!Array.isArray(list)) return undefined; + const words = key.replaceAll('_', ' ').replaceAll('-', ' '); + groups.push({ + title: words ? `${words[0].toUpperCase()}${words.slice(1)}` : '', + entries: list.map(referenceEntry), + }); + } + return groups; } function markdownLinkText(value) { @@ -406,18 +434,24 @@ export function yamlPage(sourceName, text) { } } if (base === 'references') { - const entries = referenceEntries(data); - if (entries) { - const body = entries - .filter((entry) => entry.title || entry.url) - .map((entry) => { - const title = markdownLinkText(entry.title || entry.url); - const link = entry.url ? `[${title}](<${entry.url}>)` : title; - const lines = [`- ${link}${entry.date ? ` (${entry.date})` : ''}`]; - if (entry.abstract) lines.push(`\n ${entry.abstract.replaceAll('\n', ' ')}`); - return lines.join('\n'); + const groups = referenceGroups(data); + if (groups) { + const body = groups + .map((group) => { + const entries = group.entries + .filter((entry) => entry.title || entry.url) + .map((entry) => { + const title = markdownLinkText(entry.title || entry.url); + const link = entry.url ? `[${title}](<${entry.url}>)` : title; + const lines = [`- ${link}${entry.date ? ` (${entry.date})` : ''}`]; + if (entry.abstract) lines.push(`\n ${entry.abstract.replaceAll('\n', ' ')}`); + return lines.join('\n'); + }) + .join('\n'); + return [group.title ? `## ${markdownLinkText(group.title)}` : '', entries].filter(Boolean).join('\n\n'); }) - .join('\n'); + .filter(Boolean) + .join('\n\n'); return { title: 'References', markdown: `${body}\n` }; } } diff --git a/adapters/framework.mjs b/adapters/framework.mjs index a06cfaa..439eebc 100644 --- a/adapters/framework.mjs +++ b/adapters/framework.mjs @@ -534,7 +534,11 @@ function requirementCard(requirement, anchor, context, parent) { const permanentId = requirement.id ? String(requirement.id) : 'Unnumbered draft'; const kind = isVariationPoint ? 'Variation point' : isOption ? 'Option' : 'Requirement'; const cssKind = kind.toLowerCase().replaceAll(' ', '-'); - const verification = verificationOf(requirement, { isVariationPoint, isExtensionOption: Boolean(extension) }); + const verification = verificationOf(requirement, { + isVariationPoint, + isExtensionOption: Boolean(extension), + legacyObservability: context.legacyObservability, + }); const observability = observabilityWarning(requirement, verification, context.sourceName); if (observability) context.warnings.push(observability); if (verification.method === 'unclassified' && !requirement.option_of && !(requirement.select && !options.length)) { @@ -638,8 +642,8 @@ function capabilityTitles(ids, context) { } function functionalityMarkup(frontmatter, context) { - const requirements = frontmatter.requirements ?? []; - if (!requirements.length) return undefined; + const requirements = frontmatter.requirements; + if (!Array.isArray(requirements)) return undefined; const facts = []; if (context.profile) { facts.push([ @@ -663,29 +667,33 @@ function functionalityMarkup(frontmatter, context) { const factMarkup = facts .map(([label, value]) => `
    ${htmlEscape(label)}
    ${value}
    `) .join(''); - const cards = requirements - .map((requirement, index) => requirementCard(requirement ?? {}, `requirement-${index + 1}`, context)) - .join('\n'); - const optionCount = requirements.reduce( - (total, requirement) => total + (Array.isArray(requirement?.options) ? requirement.options.length : 0), - 0, - ); - const unnumbered = flattenRequirements(requirements).some(({ requirement }) => !requirement?.id); - const counted = `${requirements.length} requirement${requirements.length === 1 ? '' : 's'}`; - const optionText = optionCount ? `, and ${optionCount} option${optionCount === 1 ? '' : 's'} beneath its variation points` : ''; - return { - summary: `
    -

    ${inlineHtml(String(frontmatter.description ?? '').trim())}

    - ${factMarkup ? `
    ${factMarkup}
    ` : ''} -
    `, - requirements: `## Requirements + let requirementMarkup; + if (requirements.length) { + const cards = requirements + .map((requirement, index) => requirementCard(requirement ?? {}, `requirement-${index + 1}`, context)) + .join('\n'); + const optionCount = requirements.reduce( + (total, requirement) => total + (Array.isArray(requirement?.options) ? requirement.options.length : 0), + 0, + ); + const unnumbered = flattenRequirements(requirements).some(({ requirement }) => !requirement?.id); + const counted = `${requirements.length} requirement${requirements.length === 1 ? '' : 's'}`; + const optionText = optionCount ? `, and ${optionCount} option${optionCount === 1 ? '' : 's'} beneath its variation points` : ''; + requirementMarkup = `## Requirements

    This functionality defines ${counted}${optionText}.${unnumbered ? ' “Unnumbered draft” reflects the source metadata and does not invent a permanent requirement identifier.' : ''}

    ${cards}
    -`, +`; + } + return { + summary: `
    +

    ${inlineHtml(String(frontmatter.description ?? '').trim())}

    + ${factMarkup ? `
    ${factMarkup}
    ` : ''} +
    `, + requirements: requirementMarkup, }; } @@ -1129,22 +1137,137 @@ async function copySupportFiles( } function redirectHtml(target, unofficial) { - const encoded = JSON.stringify(target); - return `Redirecting…

    Continue to the Starlight page

    \n`; + const encoded = JSON.stringify(target).replaceAll('<', '\\u003c'); + return ` + + + + + +Redirecting… + + +

    Continue to the current page

    + + + +`; } -async function writeRedirects(siteRoot, pages, base, unofficial) { - const redirects = []; - for (const page of pages) { - if (page.sourceName === 'README.md' || page.generated || !page.sourceName.endsWith('.md')) continue; - const legacy = page.sourceName.replace(/\.md$/, '.html'); - const target = baseUrl(base, page.route ? `${page.route}/` : ''); +function safeLegacyRoute(legacy) { + const decoded = decodedPathname('.gitbook.yaml', legacy); + if (!decoded || decoded.trim() !== decoded || decoded.startsWith('/') || decoded.endsWith('/') + || /[\\?#\u0000-\u001f\u007f]/.test(decoded) || isExternalReference(decoded) + || path.posix.normalize(decoded) !== decoded || decoded === '.' + || decoded === '..' || decoded.startsWith('../') || !isPublishableSupportPath(decoded)) { + throw new Error(`.gitbook.yaml: unsafe legacy route ${JSON.stringify(legacy)}`); + } + return decoded; +} + +async function gitBookRedirects(sourceRoot, snapshots) { + const name = '.gitbook.yaml'; + let contents; + try { + contents = await readFile(path.join(sourceRoot, name)); + } catch (error) { + if (error.code === 'ENOENT') return []; + throw error; + } + snapshots.set(name, contents); + let redirects; + try { + redirects = YAML.parse(contents.toString('utf8'))?.redirects; + } catch (error) { + throw new Error(`${name}: invalid YAML: ${error.message}`); + } + if (redirects === undefined) return []; + if (!redirects || typeof redirects !== 'object' || Array.isArray(redirects)) { + throw new Error(`${name}: redirects must be a mapping`); + } + return Object.entries(redirects).map(([legacy, target]) => { + if (typeof target !== 'string' || !target.trim()) { + throw new Error(`${name}: redirect ${legacy} target must be a non-empty string`); + } + const reference = target.trim(); + if (isExternalReference(reference) || reference.startsWith('/')) { + throw new Error(`${name}: redirect target must be repository-relative: ${reference}`); + } + const { pathname, query, fragment } = splitReference(reference); + const source = pathname ? safeRelativeTarget(name, decodedPathname(name, pathname), '.') : 'README.md'; + return { legacy: safeLegacyRoute(legacy), source, query, fragment }; + }); +} + +function gitBookRedirectTarget({ source, query, fragment }, pageRoutes, pageAnchors, supportFiles, base) { + if (pageRoutes.has(source)) { + const id = decodeURIComponent(fragment.slice(1)); + if (id && !pageAnchors.get(source)?.has(id)) { + throw new Error(`.gitbook.yaml: unknown fragment ${fragment} on ${source}`); + } + const route = pageRoutes.get(source); + return `${baseUrl(base, route ? `${route}/` : '')}${query}${fragment}`; + } + if (!supportFiles.includes(source)) { + throw new Error(`.gitbook.yaml: target ${source} is not a navigation page or published support file`); + } + if (fragment) { + throw new Error(`.gitbook.yaml: support-file target ${source} cannot verify fragment ${fragment}`); + } + return `${baseUrl(base, source)}${query}`; +} + +async function writeRedirects({ + siteRoot, pages, pageRoutes, pageAnchors, supportFiles, supportIndexes, mappings, base, unofficial, +}) { + const redirects = new Map(); + const occupied = new Map([ + '404.html', + ...supportFiles, + ...supportIndexes, + ...pages.map((page) => page.route ? `${page.route}/index.html` : 'index.html'), + ].map((output) => [output.toLowerCase(), null])); + async function write(legacy, target) { const output = path.join(siteRoot, 'public', legacy); await mkdir(path.dirname(output), { recursive: true }); await writeFile(output, redirectHtml(target, unofficial)); - redirects.push({ legacy, target }); + occupied.set(legacy.toLowerCase(), target); + redirects.set(legacy, target); + } + + for (const page of pages) { + if (page.sourceName === 'README.md' || page.generated || !page.sourceName.endsWith('.md')) continue; + const legacy = page.sourceName.replace(/\.md$/, '.html'); + await write(legacy, baseUrl(base, page.route ? `${page.route}/` : '')); + } + for (const mapping of mappings) { + const { legacy, source } = mapping; + const aliases = legacy.endsWith('.html') ? [legacy] : [path.posix.join(legacy, 'index.html')]; + if (!legacy.endsWith('.html') && pageRoutes.has(source)) aliases.push(`${legacy}.html`); + const target = gitBookRedirectTarget(mapping, pageRoutes, pageAnchors, supportFiles, base); + for (const alias of aliases) { + const folded = alias.toLowerCase(); + const conflict = [...occupied].some(([output, existingTarget]) => + (output === folded && existingTarget !== target) + || output.startsWith(`${folded}/`) + || folded.startsWith(`${output}/`), + ); + if (conflict) { + throw new Error(`.gitbook.yaml: legacy route ${legacy} conflicts with generated publication output`); + } + if (!redirects.has(alias)) await write(alias, target); + } } - return redirects; + return [...redirects].map(([legacy, target]) => ({ legacy, target })); } async function writeSupportDirectoryIndexes( @@ -1390,6 +1513,7 @@ export async function generateSite({ sourceRoot, siteRoot, base = '/', unofficia ['metadata.yml', metadataBuffer], ['authors.yml', authorsBuffer], ]); + const redirectMappings = await gitBookRedirects(absoluteSourceRoot, snapshots); let requirementCount = 0; const linkedDecisionRecords = []; // ordered grows while it is read, as linked decision records are found. @@ -1405,7 +1529,9 @@ export async function generateSite({ sourceRoot, siteRoot, base = '/', unofficia const { node: frontmatterNode, value: frontmatter } = sourceFrontmatter(tree); const headings = headingDetails(tree, sourceName); const title = yaml?.title ?? pageLabel(sourceName, frontmatter, headings); - const route = routeFor(sourceName); + const route = linkedDecisionRecords.includes(sourceName) + ? path.posix.join('resources', routeFor(sourceName)) + : routeFor(sourceName); const anchors = new Set([...headings.map((heading) => heading.id), ...standaloneAnchors(tree)]); // Decision records are not yet part of toc.yml. One that a published page links to // is published as a resource, so that the link resolves; it is followed in turn. @@ -1474,6 +1600,9 @@ export async function generateSite({ sourceRoot, siteRoot, base = '/', unofficia const conditions = collectConditions(functionalityPages, profiles, warnings); const keyView = keyViewPage({ conditions, profiles, pageRoutes, base: normalizedBase, metadata, warnings }); const referencedSupportPaths = collectReferencedSupportPaths(loaded, pageSources); + for (const { source } of redirectMappings) { + if (!pageRoutes.has(source) && !/\.(?:md|ya?ml)$/i.test(source)) referencedSupportPaths.add(source); + } for (const folder of tocModel.folders) { let details; try { @@ -1528,6 +1657,9 @@ export async function generateSite({ sourceRoot, siteRoot, base = '/', unofficia profilesById: new Map(profiles.map((profile) => [profile.id, profile])), capabilities: new Map((metadata.capabilities ?? []).map((capability) => [String(capability.id), capability])), keyView, + legacyObservability: !loaded.some((page) => + flattenRequirements(page.frontmatter.requirements).some(({ requirement }) => requirement?.interaction), + ), warnings, }; @@ -1567,7 +1699,18 @@ export async function generateSite({ sourceRoot, siteRoot, base = '/', unofficia unofficial, tocModel.folders, ); - const redirects = await writeRedirects(absoluteSiteRoot, loaded, normalizedBase, unofficial); + const publishedSupportFiles = [...new Set([...supportFiles, ...apiReferences.supportFiles])].toSorted(); + const redirects = await writeRedirects({ + siteRoot: absoluteSiteRoot, + pages: loaded, + pageRoutes, + pageAnchors, + supportFiles: publishedSupportFiles, + supportIndexes, + mappings: redirectMappings, + base: normalizedBase, + unofficial, + }); const sourceState = await gitSourceState(absoluteSourceRoot); const version = (metadata.versions.find((item) => item.latest) ?? metadata.versions[0]).version; const manifest = { @@ -1578,7 +1721,7 @@ export async function generateSite({ sourceRoot, siteRoot, base = '/', unofficia sourceDigest: sourceDigest(snapshots), requirementCount, sidebar, - supportFiles: [...new Set([...supportFiles, ...apiReferences.supportFiles])].toSorted(), + supportFiles: publishedSupportFiles, apiReferences: apiReferences.references, supportIndexes, redirects, diff --git a/scripts/publish.mjs b/scripts/publish.mjs index ca306d6..966a41e 100644 --- a/scripts/publish.mjs +++ b/scripts/publish.mjs @@ -8,7 +8,7 @@ // The same command runs locally and in .github/workflows/pages.yml. import { execFile, spawn } from 'node:child_process'; -import { copyFile, mkdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises'; +import { copyFile, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from 'node:fs/promises'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { parseArgs, promisify } from 'node:util'; @@ -62,8 +62,7 @@ function run(command, args, options = {}) { // Fetches one commit of the source without credentials, hooks or history. async function checkout(entry, checkouts) { const directory = path.join(checkouts, entry.id); - await rm(directory, { recursive: true, force: true }); - await mkdir(directory, { recursive: true }); + await mkdir(directory); const git = (...args) => execFileAsync('git', ['-C', directory, ...args]); await git('init', '-q'); await git('remote', 'add', 'origin', `https://github.com/${entry.repository}.git`); @@ -95,11 +94,14 @@ export function landingHtml(entries, { base, unofficial }) { const items = entries .map((entry) => { const source = `https://github.com/${entry.repository}/tree/${entry.commit ?? entry.ref}`; - const built = entry.commit ? `${entry.ref} @ ${entry.commit.slice(0, 7)}` : entry.ref; + const built = entry.local + ? `${entry.commit.slice(0, 7)}${entry.dirty ? ' + uncommitted changes' : ''}` + : entry.commit ? `${entry.ref} @ ${entry.commit.slice(0, 7)}` : entry.ref; + const sourceKind = entry.local ? 'Built from local checkout of' : 'Built from'; return `
  • ${htmlEscape(entry.title)} ${entry.description ? `

    ${htmlEscape(entry.description)}

    ` : ''} -

    Built from ${htmlEscape(entry.repository)} ${htmlEscape(built)}

    +

    ${sourceKind} ${htmlEscape(entry.repository)} ${htmlEscape(built)}

  • `; }) .join('\n'); @@ -143,31 +145,87 @@ ${items} `; } -export async function publish({ list = DEFAULT_LIST, output, base = '/', unofficial = false, sources, checkouts }) { +async function outputState(outputRoot) { + try { + const details = await lstat(outputRoot); + if (!details.isDirectory()) throw new Error(`${outputRoot} must be a directory`); + if ((await readdir(outputRoot)).length) throw new Error(`${outputRoot} must be new or empty`); + return 'empty'; + } catch (error) { + if (error.code === 'ENOENT') return 'missing'; + throw error; + } +} + +async function buildBuildingBlock({ entry, source, output, base, unofficial }) { + const site = path.join(rendererRoot, 'scripts/site.mjs'); + const options = [ + '--profile', 'framework', + '--source', await realpath(source), + '--base', `${base}bb/${entry.id}/`, + '--output', path.join(output, 'bb', entry.id), + ...(unofficial ? ['--unofficial'] : []), + ]; + await run(process.execPath, [site, 'build', ...options], { cwd: rendererRoot }); + await run(process.execPath, [site, 'test-served', ...options], { cwd: rendererRoot }); +} + +export async function publish({ + list = DEFAULT_LIST, + output, + base = '/', + unofficial = false, + sources, + checkouts, + buildEntry = buildBuildingBlock, + checkoutEntry = checkout, +}) { if (!output) throw new Error('--output is required'); const siteBase = normalizeBase(base); const entries = parseList(await readFile(list, 'utf8'), path.relative(rendererRoot, list) || list); const outputRoot = path.resolve(output); - await mkdir(outputRoot, { recursive: true }); - const checkoutRoot = sources ? undefined : path.resolve(checkouts ?? path.join(rendererRoot, '.generated/publish-sources')); - const site = path.join(rendererRoot, 'scripts/site.mjs'); - for (const entry of entries) { - console.log(`\n== ${entry.title}: ${entry.repository} @ ${entry.ref}`); - const source = sources ? await localSource(entry, path.resolve(sources)) : await checkout(entry, checkoutRoot); - entry.commit = (await execFileAsync('git', ['-C', source, 'rev-parse', 'HEAD'])).stdout.trim(); - const options = [ - '--profile', 'framework', - '--source', await realpath(source), - '--base', `${siteBase}bb/${entry.id}/`, - '--output', path.join(outputRoot, 'bb', entry.id), - ...(unofficial ? ['--unofficial'] : []), - ]; - await run(process.execPath, [site, 'build', ...options], { cwd: rendererRoot }); - await run(process.execPath, [site, 'test-served', ...options], { cwd: rendererRoot }); + const initialOutputState = await outputState(outputRoot); + const outputParent = path.dirname(outputRoot); + await mkdir(outputParent, { recursive: true }); + const staging = await mkdtemp(path.join(outputParent, `.${path.basename(outputRoot)}.publish-`)); + let checkoutRun; + let published = false; + try { + if (!sources) { + const checkoutRoot = path.resolve(checkouts ?? path.join(rendererRoot, '.generated/publish-sources')); + await mkdir(checkoutRoot, { recursive: true }); + checkoutRun = await mkdtemp(path.join(checkoutRoot, '.publish-checkouts-')); + } + for (const entry of entries) { + console.log(`\n== ${entry.title}: ${entry.repository} @ ${entry.ref}`); + const source = sources + ? await localSource(entry, path.resolve(sources)) + : await checkoutEntry(entry, checkoutRun); + entry.commit = (await execFileAsync('git', ['-C', source, 'rev-parse', 'HEAD'])).stdout.trim(); + entry.local = Boolean(sources); + if (entry.local) { + entry.dirty = Boolean((await execFileAsync( + 'git', + ['-C', source, 'status', '--porcelain=v1', '--untracked-files=normal'], + )).stdout.trim()); + } + await buildEntry({ entry, source, output: staging, base: siteBase, unofficial }); + } + await writeFile(path.join(staging, 'index.html'), landingHtml(entries, { base: siteBase, unofficial })); + await copyFile(path.join(rendererRoot, 'public/favicon.svg'), path.join(staging, 'favicon.svg')); + if (unofficial) await writeFile(path.join(staging, 'robots.txt'), 'User-agent: *\nDisallow: /\n'); + + const finalOutputState = await outputState(outputRoot); + if (finalOutputState !== initialOutputState) { + throw new Error(`${outputRoot} changed while the site was being built`); + } + if (finalOutputState === 'empty') await rmdir(outputRoot); + await rename(staging, outputRoot); + published = true; + } finally { + if (!published) await rm(staging, { recursive: true, force: true }); + if (checkoutRun) await rm(checkoutRun, { recursive: true, force: true }); } - await writeFile(path.join(outputRoot, 'index.html'), landingHtml(entries, { base: siteBase, unofficial })); - await copyFile(path.join(rendererRoot, 'public/favicon.svg'), path.join(outputRoot, 'favicon.svg')); - if (unofficial) await writeFile(path.join(outputRoot, 'robots.txt'), 'User-agent: *\nDisallow: /\n'); console.log(`\nPublished ${entries.length} Building Blocks to ${outputRoot}`); return entries; } diff --git a/tests/conformance-profiles.test.mjs b/tests/conformance-profiles.test.mjs index 601fcd3..642de4d 100644 --- a/tests/conformance-profiles.test.mjs +++ b/tests/conformance-profiles.test.mjs @@ -308,6 +308,71 @@ test('verification follows from interaction, and observability is read only with assert.ok(manifest.warnings.some((warning) => warning.includes('requirement 50 has no interaction'))); }); +test('one nested interaction disables legacy observability across functionality pages', async () => { + const { sourceRoot, siteRoot } = await fixture({ + files: { + 'conformance-profiles/core-profile/functionalities/functionality-a.md': `--- +title: Functionality A +description: Does A. +requirements: + - id: '30' + status: PUBLISHED + level: REQUIRED + statement: The solution selects an option. + options: + - id: '30.1' + status: PUBLISHED + level: OPTION + interaction: FILE + statement: The solution handles a file. +--- +`, + 'conformance-profiles/extension-x/functionalities/functionality-x.md': `--- +title: Functionality X +description: Does X. +requirements: + - id: '40' + status: PUBLISHED + level: REQUIRED + observability: AUDITABLE + statement: The solution records X. +--- +`, + }, + }); + const manifest = await generateSite({ sourceRoot, siteRoot, base: '/' }); + const output = await page(siteRoot, 'conformance-profiles/extension-x/functionalities/functionality-x'); + assert.match(output, /
    Verification<\/dt>
    Unclassified<\/dd>/); + assert.doesNotMatch(output, /Observability<\/span>/); + assert.ok(manifest.warnings.some((warning) => warning.includes('requirement 40 has no interaction'))); +}); + +test('functionality metadata remains visible when its requirements list is empty', async () => { + const { sourceRoot, siteRoot } = await fixture({ + files: { + 'conformance-profiles/extension-y/functionalities/functionality-y.md': `--- +title: Functionality Y +description: Explains Y before its requirements are defined. +realises: [capability-one] +applies_when: [extension-x] +requirements: [] +--- + +Applicability details. +`, + }, + }); + await generateSite({ sourceRoot, siteRoot, base: '/docs/' }); + const output = await page(siteRoot, 'conformance-profiles/extension-y/functionalities/functionality-y'); + assert.match(output, /Explains Y before its requirements are defined\./); + assert.match(output, /
    Conformance profile<\/dt>
    Extension Y<\/a> \(extension\)<\/dd>/); + assert.match(output, /
    Capabilities<\/dt>
    Capability One<\/dd>/); + assert.match(output, /
    Applies when<\/dt>
    /); + assert.match(output, /Applicability details\./); + assert.doesNotMatch(output, /^## Requirements$/m); + assert.doesNotMatch(output, /class="requirements-list"/); +}); + test('profile rules that navigation and links depend on fail generation', async () => { const cases = [ [{ 'conformance-profiles/extension-x/introduction.md': '---\ntitle: X\ntype: CORE\n---\n' }, /exactly one CORE conformance profile, found 2/], @@ -414,11 +479,19 @@ test('decision records that a page links to are published under resources', asyn assert.deepEqual( manifest.sidebar.find(({ label }) => label === 'Resources').items.slice(1), [ - { label: 'First decision', slug: 'adr/example-adr-1' }, - { label: 'Second decision', slug: 'adr/example-adr-2' }, + { label: 'First decision', slug: 'resources/adr/example-adr-1' }, + { label: 'Second decision', slug: 'resources/adr/example-adr-2' }, + ], + ); + assert.match(await page(siteRoot, 'introduction/purpose'), /\[the decision\]\(\/resources\/adr\/example-adr-1\/#context\)/); + assert.match(await page(siteRoot, 'resources/adr/example-adr-1'), /\[the second\]\(\/resources\/adr\/example-adr-2\/\)/); + assert.deepEqual( + manifest.redirects.filter(({ legacy }) => legacy.startsWith('ADR/')), + [ + { legacy: 'ADR/EXAMPLE-ADR-1.html', target: '/resources/adr/example-adr-1/' }, + { legacy: 'ADR/EXAMPLE-ADR-2.html', target: '/resources/adr/example-adr-2/' }, ], ); - assert.match(await page(siteRoot, 'introduction/purpose'), /\[the decision\]\(\/adr\/example-adr-1\/#context\)/); assert.equal(manifest.pages.some(({ source }) => source === 'ADR/EXAMPLE-ADR-3.md'), false); assert.ok(manifest.warnings.includes('ADR/EXAMPLE-ADR-2.md: not listed in toc.yml; published under resources because ADR/EXAMPLE-ADR-1.md links to it')); @@ -426,6 +499,19 @@ test('decision records that a page links to are published under resources', asyn await assert.rejects(generateSite({ sourceRoot: other.sourceRoot, siteRoot: other.siteRoot, base: '/' }), /notes\/draft\.md is not listed in toc\.yml/); }); +test('a decision record listed in toc.yml keeps its canonical route and legacy alias', async () => { + const { sourceRoot, siteRoot } = await fixture({ + toc: `${TOC} ADR:\n - EXAMPLE-ADR-1.md\n`, + files: { + 'ADR/EXAMPLE-ADR-1.md': '# Listed decision\n', + }, + }); + const manifest = await generateSite({ sourceRoot, siteRoot, base: '/' }); + assert.equal(manifest.pages.find(({ source }) => source === 'ADR/EXAMPLE-ADR-1.md').route, 'adr/example-adr-1'); + assert.ok(manifest.redirects.some(({ legacy, target }) => + legacy === 'ADR/EXAMPLE-ADR-1.html' && target === '/adr/example-adr-1/')); +}); + test('a contract or test given as a URN or web URL is not turned into a local link', async () => { const { sourceRoot, siteRoot } = await fixture({ files: { diff --git a/tests/framework-model.test.mjs b/tests/framework-model.test.mjs new file mode 100644 index 0000000..c387bea --- /dev/null +++ b/tests/framework-model.test.mjs @@ -0,0 +1,122 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { + checkOptions, + verificationOf, + yamlPage, +} from '../adapters/framework-model.mjs'; + +test('references pages render grouped citation lists and retain flat reference lists', () => { + const grouped = yamlPage('introduction/references.yml', `references: + records_management: + - ISO 15489-1:2016, Information and documentation + - MoReq2010, Modular Requirements for Records Systems + interfaces: + - IETF RFC 4918, HTTP Extensions for WebDAV +`); + assert.equal(grouped.title, 'References'); + assert.equal(grouped.markdown, `## Records management + +- ISO 15489-1:2016, Information and documentation +- MoReq2010, Modular Requirements for Records Systems + +## Interfaces + +- IETF RFC 4918, HTTP Extensions for WebDAV +`); + + const flat = yamlPage('introduction/references.yml', `references: + - title: Example Standard + url: https://example.invalid/standard + date: 2026 + abstract: An example reference. +`); + assert.equal(flat.markdown, `- [Example Standard]() (2026) + + An example reference. +`); +}); + +test('option checks warn when select.max exceeds the declared option count', () => { + const warnings = []; + checkOptions({ + sourceName: 'functionalities/example.md', + frontmatter: { + requirements: [{ + id: '1', + select: { min: 1, max: 3 }, + options: [ + { id: '1.1', key: 'first', level: 'OPTION' }, + { id: '1.2', key: 'second', level: 'OPTION' }, + ], + }], + }, + }, undefined, warnings); + + assert.ok(warnings.some((warning) => /select\.max.*number of options/.test(warning))); +}); + +test('option checks warn when extension-backed options also declare local verification', () => { + const warnings = []; + checkOptions({ + sourceName: 'functionalities/example.md', + frontmatter: { + requirements: [{ + id: '1', + select: { min: 1 }, + options: [ + { + id: '1.1', + level: 'OPTION', + extension: 'audit-extension', + interaction: 'SERVICE_API', + api_operation_id: 'auditRecord', + test: 'tests/audit.feature', + }, + { id: '1.2', key: 'local', level: 'OPTION' }, + ], + }], + }, + }, undefined, warnings); + + for (const field of ['interaction', 'api_operation_id', 'test']) { + assert.ok( + warnings.some((warning) => warning.includes('extension-backed option') && warning.includes(field)), + `expected a warning for ${field}: ${warnings.join('\n')}`, + ); + } +}); + +test('legacy observability is opt-in for the whole specification', () => { + const requirement = { observability: 'AUDITABLE' }; + + assert.deepEqual( + verificationOf(requirement, { isVariationPoint: false, isExtensionOption: false }), + { method: 'unclassified', label: 'Unclassified' }, + ); + assert.deepEqual( + verificationOf(requirement, { + isVariationPoint: false, + isExtensionOption: false, + legacyObservability: true, + }), + { method: 'legacy', label: undefined }, + ); + assert.deepEqual( + verificationOf(requirement, { + isVariationPoint: true, + isExtensionOption: false, + legacyObservability: true, + }), + { method: 'counted', label: 'Counts the options that pass' }, + ); + assert.deepEqual( + verificationOf(requirement, { + isVariationPoint: false, + isExtensionOption: true, + legacyObservability: true, + }), + { method: 'extension', label: "By the extension's tests" }, + ); +}); diff --git a/tests/framework.test.mjs b/tests/framework.test.mjs index 1871cbc..6b8d9c6 100644 --- a/tests/framework.test.mjs +++ b/tests/framework.test.mjs @@ -4,6 +4,7 @@ import { lstat, mkdir, mkdtemp, readFile, symlink, writeFile } from 'node:fs/pro import os from 'node:os'; import path from 'node:path'; import { promisify } from 'node:util'; +import { runInNewContext } from 'node:vm'; import test from 'node:test'; import YAML from 'yaml'; @@ -516,6 +517,82 @@ test('home metadata renders structured extensions and null author URNs faithfull } }); +test('GitBook redirects preserve former functionality URLs, fragments, and support links', async () => { + const { sourceRoot, siteRoot } = await fixture(); + await write(sourceRoot, 'README.md', '# Digital Registries\n\n## Attribution\n\nFixture credits.\n'); + await write(sourceRoot, 'assets/legacy-vocabulary.ttl', '# Registry vocabulary fixture\n'); + await write(sourceRoot, '.gitbook.yaml', `redirects: + former-home: "#attribution" + Former-home: "#attribution" + requirements/old-service: requirements/service.md + former-overview: requirements/service.md?view=compact#data-structures + former-vocabulary: assets/legacy-vocabulary.ttl +`); + const manifest = await generateSite({ sourceRoot, siteRoot, base: '/registries/', unofficial: true }); + + for (const [legacy, target] of [ + ['former-home/index.html', '/registries/#attribution'], + ['Former-home/index.html', '/registries/#attribution'], + ['requirements/old-service/index.html', '/registries/requirements/service/'], + ['requirements/old-service.html', '/registries/requirements/service/'], + ['former-overview/index.html', '/registries/requirements/service/?view=compact#data-structures'], + ['former-vocabulary/index.html', '/registries/assets/legacy-vocabulary.ttl'], + ['requirements/service.html', '/registries/requirements/service/'], + ]) { + assert.ok(manifest.redirects.some((entry) => entry.legacy === legacy && entry.target === target)); + const output = await readFile(path.join(siteRoot, 'public', legacy), 'utf8'); + assert.ok(output.includes(`url=${target}`)); + assert.match(output, /content="noindex, nofollow"/); + } + assert.ok(manifest.supportFiles.includes('assets/legacy-vocabulary.ttl')); + await assert.rejects(readFile(path.join(siteRoot, 'public/former-vocabulary.html')), { code: 'ENOENT' }); +}); + +test('redirects keep incoming queries and fragments when the mapping leaves them open', async () => { + const { sourceRoot, siteRoot } = await fixture(); + await write(sourceRoot, '.gitbook.yaml', `redirects: + explicit: requirements/service.md?view=compact#data-structures + inherited: resources/linked.md +`); + await generateSite({ sourceRoot, siteRoot, base: '/registries/' }); + + async function redirectTo(legacy, href) { + const html = await readFile(path.join(siteRoot, 'public', legacy, 'index.html'), 'utf8'); + const script = /