diff --git a/AGENTS.md b/AGENTS.md index 6ce9d92a..3b8ac487 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,7 @@ Model: 2 release PR Integration branch: `main` Deliver and verify: a merge into `main` publishes nothing; release-please keeps the release pull request, Bruno merges it, and `release.yml` publishes after he approves the `npm` environment (`docs/release.md`); verify with `npm view @brunosouzas/stackledger version` -Implemented: the catalogue format and `stackledger validate` (`catalogue-model`), the SVG map engine and `stackledger map` (`metro-map-engine`), the read-only MCP server with the `full` and `staff` views (`mcp-server`), `stackledger build` with the static `full` and `staff` sites (`catalogue-site`), the licence report: `stackledger report`, the Reports page and `renewals.ics` of the `full` site (`licence-reports`), and Mac discovery: `stackledger discover`, `stackledger drift` with `--scaffold` and the `stackledger/` annotations (`mac-discovery`), and `stackledger skills validate`, which reads and checks a set of agent skills, playbooks, agents and rules (`skills-source`, code in `src/skills/`), skipping what a `.stackledgerignore` file at the top of a given folder lists (`skills-ignore`, `src/skills/ignore.ts`), and `stackledger skills map`, which writes Markdown pages with Mermaid diagrams of the set's declared relations into a folder it owns, with `--check` for pipelines (`skills-mermaid`, `src/skills/graph.ts`, `mermaid.ts`, `map-command.ts`), and the Skills section of `stackledger build` with `--skills` and `spec.skills.folders`: the skills map file `stackledger-skills.yaml` (`src/skills/lines.ts`), the skills metro map (`src/skills/metro.ts`), the relation diagram (`src/map/relations.ts`), the page data (`src/site/skills-data.ts`, `skills-build.ts`) and the Astro pages under `site/src/pages/{skills,skill-map,rules,playbooks,agents}/` (`skills-site`), and reading Claude Code plugin marketplaces: a given folder with `.claude-plugin/marketplace.json` is read through its plugins, items are named `plugin:name`, plain names resolve by plugin first, remote plugins are skipped with a warning (`skills-marketplaces`, `src/skills/marketplace.ts`, `resolve.ts`, `examples/northwind-marketplace/`), and journeys as the lines of the skills map with marketplaces (or `loose`, or playbooks) as zones, qualified stops, and the skills map file named by `spec.skills.map` or `skills validate --map` (`skill-journeys`, `src/skills/lines.ts` zones, `metro.ts`, `examples/northwind-journeys/`), and station labels that wrap instead of being cut, with the rule count on skills stations (`station-labels-and-rules`, `src/map/labels.ts`, `layout.ts`), and the home page at `/` with the map at `/map/`, the default title `stackledger` and `spec.site.home` (`site-home`, `site/src/pages/index.astro`, `src/site/relative.ts` for the home links' exemption), and the city backdrop of the software map: `spec.map.backdrop` and `stackledger map --backdrop`, `neutral` or `london`, its OpenStreetMap credit in the SVG and under the site's map frame (`map-backgrounds`, `src/map/backdrops/` generated by `scripts/backdrops/`, `src/map/svg.ts`, colours from the design system's `backdrop` tokens in `src/map/themes.ts`). The publishable npm package, owner-approved release workflow, catalogue repository pipeline template and protected hosting recipes (`catalogue-deployment`) are implemented. Released on npm: 0.1.0 to 0.4.0 as `stackledger` (deprecated), 0.4.1 as `@brunosouzas/stackledger` (the same code under the npm organisation's scope; the command stays `stackledger`), 0.5.0, with the identity of `@brunosouzas/design-system`, since renamed `@brunosouzas/signwright` (`design-system-identity`, `home-banner`, `design-system-pieces`, `round-bends`), 0.5.1, with maps never shown larger than drawn (`map-scale`) and the design system 0.4.0, 0.6.0, with the city backdrop of the software map (`map-backgrounds`) and the design system 0.5.3, and 0.7.0, with the script of interpreter jobs (`launchd-script`) and the helpers apps declare (`app-helpers`), and 0.8.0, with the identity v2 on design system 0.8.1 (`identity-v2`).; the fictitious demo is rebuilt by hand following `docs/demo.md`. Where the identity v2 lives: Source fonts through Astro's Fonts API with the local provider (`src/site/build.ts`), its build-time font server bound to loopback (`src/site/loopback.ts`), the font CSS moved into `_astro/fonts.css` before the scan (`moveFontCss` in `src/site/relative.ts`), stackledger's accent, the outline frame, the map's `color.state.*` colours and quoted `font.sans` stack (`src/map/themes.ts`, `src/map/xml.ts`), the wordmark, the footer endorsement and the redrawn art (`scripts/site-art.mjs`). The rest of the roadmap is not implemented: say so instead of describing files that do not exist. +Implemented: the catalogue format and `stackledger validate` (`catalogue-model`), the SVG map engine and `stackledger map` (`metro-map-engine`), the read-only MCP server with the `full` and `staff` views (`mcp-server`), `stackledger build` with the static site (`catalogue-site`; since `single-site` one site at the root), the licence report: `stackledger report`, the Reports page and `renewals.ics` of the site (`licence-reports`), and Mac discovery: `stackledger discover`, `stackledger drift` with `--scaffold` and the `stackledger/` annotations (`mac-discovery`), and `stackledger skills validate`, which reads and checks a set of agent skills, playbooks, agents and rules (`skills-source`, code in `src/skills/`), skipping what a `.stackledgerignore` file at the top of a given folder lists (`skills-ignore`, `src/skills/ignore.ts`), and `stackledger skills map`, which writes Markdown pages with Mermaid diagrams of the set's declared relations into a folder it owns, with `--check` for pipelines (`skills-mermaid`, `src/skills/graph.ts`, `mermaid.ts`, `map-command.ts`), and the Skills section of `stackledger build` with `--skills` and `spec.skills.folders`: the skills map file `stackledger-skills.yaml` (`src/skills/lines.ts`), the skills metro map (`src/skills/metro.ts`), the relation diagram (`src/map/relations.ts`), the page data (`src/site/skills-data.ts`, `skills-build.ts`) and the Astro pages under `site/src/pages/{skills,skill-map,rules,playbooks,agents}/` (`skills-site`), and reading Claude Code plugin marketplaces: a given folder with `.claude-plugin/marketplace.json` is read through its plugins, items are named `plugin:name`, plain names resolve by plugin first, remote plugins are skipped with a warning (`skills-marketplaces`, `src/skills/marketplace.ts`, `resolve.ts`, `examples/northwind-marketplace/`), and journeys as the lines of the skills map with marketplaces (or `loose`, or playbooks) as zones, qualified stops, and the skills map file named by `spec.skills.map` or `skills validate --map` (`skill-journeys`, `src/skills/lines.ts` zones, `metro.ts`, `examples/northwind-journeys/`), and station labels that wrap instead of being cut, with the rule count on skills stations (`station-labels-and-rules`, `src/map/labels.ts`, `layout.ts`), and the home page at `/` with the map at `/map/`, the default title `stackledger` and `spec.site.home` (`site-home`, `site/src/pages/index.astro`, `src/site/relative.ts` for the home links' exemption), and the city backdrop of the software map: `spec.map.backdrop` and `stackledger map --backdrop`, `neutral` or `london`, its OpenStreetMap credit in the SVG and under the site's map frame (`map-backgrounds`, `src/map/backdrops/` generated by `scripts/backdrops/`, `src/map/svg.ts`, colours from the design system's `backdrop` tokens in `src/map/themes.ts`). The publishable npm package, owner-approved release workflow, catalogue repository pipeline template and protected hosting recipes (`catalogue-deployment`) are implemented. Released on npm: 0.1.0 to 0.4.0 as `stackledger` (deprecated), 0.4.1 as `@brunosouzas/stackledger` (the same code under the npm organisation's scope; the command stays `stackledger`), 0.5.0, with the identity of `@brunosouzas/design-system`, since renamed `@brunosouzas/signwright` (`design-system-identity`, `home-banner`, `design-system-pieces`, `round-bends`), 0.5.1, with maps never shown larger than drawn (`map-scale`) and the design system 0.4.0, 0.6.0, with the city backdrop of the software map (`map-backgrounds`) and the design system 0.5.3, and 0.7.0, with the script of interpreter jobs (`launchd-script`) and the helpers apps declare (`app-helpers`), and 0.8.0, with the identity v2 on design system 0.8.1 (`identity-v2`); unreleased: the one private site at the root, with `/full/` redirects and the `staff` view deprecated (`single-site`, ADR 13: `src/site/policy.ts` `REDIRECTS`, `publish.ts`, `staging.ts`).; the fictitious demo is rebuilt by hand following `docs/demo.md`. Where the identity v2 lives: Source fonts through Astro's Fonts API with the local provider (`src/site/build.ts`), its build-time font server bound to loopback (`src/site/loopback.ts`), the font CSS moved into `_astro/fonts.css` before the scan (`moveFontCss` in `src/site/relative.ts`), stackledger's accent, the outline frame, the map's `color.state.*` colours and quoted `font.sans` stack (`src/map/themes.ts`, `src/map/xml.ts`), the wordmark, the footer endorsement and the redrawn art (`scripts/site-art.mjs`). The rest of the roadmap is not implemented: say so instead of describing files that do not exist. Layout: `src/` the CLI and its modules (`src/map/` map engine and diagrams, `src/site/` site data, build, publication, `src/discovery/` the Mac sources, sandboxed runner and snapshot); `site/` the Astro project shipped in the package and copied into the build's staging folder; `test/unit`, `test/integration` (vitest) and `test/browser` (Playwright); `examples/northwind/` the fictitious example catalogue and `examples/northwind-machine/` its fictitious Mac snapshot, `examples/northwind-skills/` a fictitious skill set with a skills map file and `examples/northwind-journeys/` a fictitious setup of three marketplaces, a loose skill and a catalogue with journeys, `examples/northwind-marketplace/` a fictitious plugin marketplace. diff --git a/README.md b/README.md index 9452ea2f..e875af44 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ What it does: - **A software list with one page per item.** Owner, lifecycle, licence, the journeys it serves, a diagram of what it depends on and what depends on it, and what breaks if you remove it. - **Licence reports.** Renewals, cost per month and year for each currency by owner, payer and zone, and items nobody owns, with a calendar file of renewal dates. - **Drift on a Mac.** What is installed but not declared, and what is declared but missing. -- **Two views.** A `full` view for owners and finance, and a `staff` view without costs or renewal dates. +- **One private site.** Everything in the catalogue on one site behind sign-in, for the people who may see all of it, costs and renewal dates included. (The `staff` view that hid them is deprecated.) - **An MCP server**, so your AI agent can query and check the catalogue. - **Your agent skills on the same site.** Skills, playbooks and agents with their declared relations, rules and a skills metro map whose lines are your journeys (kinds of work) and whose zones are your plugin marketplaces. @@ -54,7 +54,7 @@ What it does: ![How stackledger works: the catalogue in a private Git repository, GitHub Actions validates and builds it with stackledger from npm, and publishes the static site to Cloudflare Pages behind Cloudflare Access; discovery stays on your Mac](https://raw.githubusercontent.com/brunosouzas/stackledger/main/docs/images/how-it-works.svg) -The diagram as Mermaid, and the personal and corporate modes: [docs/how-it-works.md](https://github.com/brunosouzas/stackledger/blob/main/docs/how-it-works.md). +The diagram as Mermaid, and the one private site: [docs/how-it-works.md](https://github.com/brunosouzas/stackledger/blob/main/docs/how-it-works.md). 1. **The catalogue lives in its own repository**, private when it holds real data. stackledger never holds your data. A company that already uses Backstage can point it at the same files. Why: [ADR 2](docs/adr/0002-catalogue-in-backstage-format-in-its-own-repository.md). 2. **Lines are journeys, not categories.** A journey has an order; a category does not. Categories become zones. Why: [ADR 3](docs/adr/0003-lines-are-journeys.md). @@ -67,17 +67,17 @@ The diagram as Mermaid, and the personal and corporate modes: [docs/how-it-works The context, the main flows and the module map are in [the architecture](docs/architecture.md). -[How it works, end to end](docs/how-it-works.md) draws the publication path (a push to `main` of the private catalogue repository, GitHub Actions, Cloudflare Pages behind Cloudflare Access) and explains the personal (one site, one reader) and corporate (two sites) modes. +[How it works, end to end](docs/how-it-works.md) draws the publication path (a push to `main` of the private catalogue repository, GitHub Actions, Cloudflare Pages behind Cloudflare Access) and explains the one private site. ## Security A software catalogue maps its owner's attack surface: which VPN, which secret store, which versions. stackledger is designed around that: - **No sign-in code in the tool.** The site sits behind an identity-aware proxy that uses your existing accounts (Google Workspace, Microsoft 365). [ADR 6](docs/adr/0006-authentication-at-an-identity-aware-proxy.md) -- **Two views, built as two sites (today).** The `staff` site does not contain costs, renewal dates, payers, seats, password-manager references or notes at all, so nothing leaks through the browser. You choose the hidden fields. Planned: one private site at the root where whoever has access sees everything, licences included, and the `staff` view becomes deprecated and unreachable; this supersedes [ADR 7](docs/adr/0007-two-views-built-as-separate-sites.md) with [ADR 13](docs/adr/0013-one-private-site-at-the-root.md), change `single-site` in the [roadmap](docs/roadmap.md#v21-one-site-marketplaces-journeys-and-named-maps). +- **One private site.** The site shows everything, licences and costs included, so it is served only behind sign-in, with one access rule on the whole address for the people who may see it all ([ADR 13](docs/adr/0013-one-private-site-at-the-root.md), which supersedes [ADR 7](docs/adr/0007-two-views-built-as-separate-sites.md)). The `staff` view, which hid the costs, stays in the code but is deprecated: nothing builds or serves it. Older `/full/...` addresses redirect to the root. - **No secrets in the catalogue.** `validate` rejects fields named like secrets, private keys and card numbers, and never repeats the value in its message. - **Nothing leaves your machine.** No telemetry, no analytics, no third-party scripts; discovery only reads and never uses `sudo`. -- **Read access to the catalogue repository equals the `full` view.** Give everyone else the website. +- **Read access to the catalogue repository equals the site.** Everyone who may open the site sees all of the catalogue. To report a vulnerability, see [SECURITY.md](SECURITY.md). @@ -106,7 +106,7 @@ npm ci npm run build node dist/cli.js validate /path/to/catalogue node dist/cli.js validate /path/to/catalogue --json -node dist/cli.js mcp /path/to/catalogue --view staff +node dist/cli.js mcp /path/to/catalogue node dist/cli.js map examples/northwind --date 2027-06-01 > map.svg node dist/cli.js build examples/northwind --out ./public --date 2027-06-01 node dist/cli.js build examples/northwind --out ./public --date 2027-06-01 --skills examples/northwind-skills @@ -122,7 +122,7 @@ cd /path/to/skills && node /path/to/stackledger/dist/cli.js skills map . --out d | `stackledger validate [folder]` | Checks a catalogue and reports each problem with file, line and field. Exit 0: no errors (warnings allowed); 1: catalogue errors; 2: usage or folder problem | Available (npm 0.8.0, source) | | `stackledger mcp [--view full\|staff]` | Serves the catalogue read-only to AI agents over MCP on stdio; see [docs/mcp.md](docs/mcp.md). Exit 2: usage or folder problem | Available (npm 0.8.0, source) | | `stackledger map [--view full\|staff] [--theme light\|dark] [--backdrop neutral\|london] [--date YYYY-MM-DD]` | Draws a self-contained SVG on stdout; diagnostics and suggestions on stderr. Exit 0 even with catalogue errors; 2 for usage/folder problems. See [docs/map.md](docs/map.md) | Available (npm 0.8.0, source) | -| `stackledger build --out [--date YYYY-MM-DD] [--skills ]...` | Builds the `full` and `staff` static sites into `/full/` and `/staff/` (only `full` in the personal mode), with `_headers`, `robots.txt` and `_redirects`, replacing an earlier build atomically; with a skill set, both sites get the Skills section ([Skills on the site](#skills-on-the-site)); report on stderr. Exit 0 even with catalogue or skill-set errors; 1: internal failure, a broken `Settings` that sets `spec.skills`, a skills folder with nothing in it or two items with one page name (the earlier build is left as it was); 2: usage or folder problem. See [docs/site.md](docs/site.md) | Available (npm 0.8.0, source) | +| `stackledger build --out [--date YYYY-MM-DD] [--skills ]...` | Builds one static site at the root of ``, with `renewals.ics`, `_headers`, `robots.txt` and `_redirects` (which sends the old `/full/...` addresses to the root), replacing an earlier build atomically; with a skill set, the site gets the Skills section ([Skills on the site](#skills-on-the-site)); report on stderr. Exit 0 even with catalogue or skill-set errors; 1: internal failure, a broken `Settings` that sets `spec.skills`, a skills folder with nothing in it or two items with one page name (the earlier build is left as it was); 2: usage or folder problem. See [docs/site.md](docs/site.md) | Available (npm 0.8.0, source) | | `stackledger report [--date YYYY-MM-DD] [--days N] [--format text\|json\|csv\|ics]` | Prints the licence report of the `full` view on stdout: renewals in the next `--days` (default 90), recurring cost per currency by owner, payer and zone, one-off and planned costs, incomplete licences; or the renewal calendar. Exit 0 even with catalogue errors; 1: the report could not be computed or written; 2: usage or folder problem. See [docs/reports.md](docs/reports.md) | Available (npm 0.8.0, source) | | `stackledger discover` | Reads what this Mac has installed (Homebrew, App Store, applications, launchd and the helpers apps declare, mise, npm, pipx), with every program in the macOS sandbox, and writes `~/.stackledger//snapshot.json`; one summary line per source on stdout. Exit 0 also with skipped sources; 1: not macOS, no sandbox or the file could not be written safely; 2: usage problem. See [docs/discovery.md](docs/discovery.md) | Available (npm 0.8.0, source) | | `stackledger drift [--snapshot ] [--format text\|json] [--scaffold ]` | Compares the snapshot with the catalogue through `stackledger/` annotations: what is not declared (with the annotation to add), what is missing, what could not be checked, and `dependsOn` relations to confirm; `--scaffold` writes draft component files into a new folder outside the catalogue. Exit 0 even with catalogue errors; 1: internal or write failure; 2: usage, folder or snapshot problem. See [docs/discovery.md](docs/discovery.md) | Available (npm 0.8.0, source) | @@ -133,7 +133,7 @@ cd /path/to/skills && node /path/to/stackledger/dist/cli.js skills map . --out d ## The website -`stackledger build` makes two static sites from one catalogue: `full` for owners and finance, `staff` for everyone else, without costs, renewal dates, payers, seats, password-manager references or notes. Each has a **Software** division (the map at `/map/`, list, journeys and, in `full`, reports) and, when given a skill set, a **Skills** division. The site title (`stackledger` unless `spec.site.title` sets one) opens a **home page** at `/` with a card per division and, if you list them in `spec.site.home.links`, your own links. Serve them behind an identity-aware proxy, publishing only `full/`, `staff/`, `_headers`, `robots.txt` and `_redirects`; with `spec.sites: [full]` (the personal mode) only `full` is built; `spec.map.backdrop: london` (from 0.6.0) draws the software map over central London from OpenStreetMap data, with the credit in the map and under it on the map page ([the map](docs/map.md#backdrop)). [docs/site.md](docs/site.md) explains the pages, the hosting and the security rules. Screenshots from the fictitious [Northwind catalogue](examples/northwind/), dated 2027-06-01: +`stackledger build` makes one static site from one catalogue, with every field: costs, renewal dates, payers, seats, password-manager references and notes. It has a **Software** division (the map at `/map/`, list, journeys and reports) and, when given a skill set, a **Skills** division. The site title (`stackledger` unless `spec.site.title` sets one) opens a **home page** at `/` with a card per division and, if you list them in `spec.site.home.links`, your own links. Serve it only behind sign-in, for people who may see all of it, publishing every file of the output folder except its `.stackledger-build` marker; `spec.map.backdrop: london` (from 0.6.0) draws the software map over central London from OpenStreetMap data, with the credit in the map and under it on the map page ([the map](docs/map.md#backdrop)). [docs/site.md](docs/site.md) explains the pages, the hosting and the security rules. Screenshots from the fictitious [Northwind catalogue](examples/northwind/), dated 2027-06-01: | | | |---|---| @@ -143,16 +143,16 @@ cd /path/to/skills && node /path/to/stackledger/dist/cli.js skills map . --out d | **Dark theme**, remembered across pages | | | ![Software list with search and filters](docs/images/site-software.png) | ![Component page for GitHub with its licence and neighbourhood diagram](docs/images/site-component.png) | | **Software**: every component and licence, with search and filters | **Component**: licence, journeys, what it depends on and what depends on it, removal impact | -| ![Licence page in the full site with cost and renewal](docs/images/site-licence-full.png) | ![The same licence page in the staff site without cost or renewal](docs/images/site-licence-staff.png) | -| **Licence, `full` site** | **The same licence, `staff` site**: the hidden fields are not in the files at all | +| ![Licence page with cost and renewal](docs/images/site-licence-full.png) | | +| **Licence**: cost, renewal, payer and seats | | | ![Journeys list with each line's badge and stop count](docs/images/site-journeys.png) | ![Journey page with its stops on a strip and the interchanges](docs/images/site-journey.png) | | **Journeys** | **Journey**: stops in order, with the other lines at each interchange | | ![Reports page with the recurring cost per currency and the renewals](docs/images/site-reports.png) | | -| **Reports**, `full` site only: renewals, cost per month and year per currency and group, and the calendar file | | +| **Reports**: renewals, cost per month and year per currency and group, and the calendar file | | ## Skills on the site -Give `stackledger build` a skill set and both sites get a **Skills** division next to **Software**: a list of every skill, playbook and agent, a skills metro map, one page per item with a diagram of its declared relations, and an index of every rule. The pages are the same in the `full` and `staff` sites: nothing about a skill is hidden from staff. +Give `stackledger build` a skill set and the site gets a **Skills** division next to **Software**: a list of every skill, playbook and agent, a skills metro map, one page per item with a diagram of its declared relations, and an index of every rule. There are two ways to say where the skills are, and **the option always wins**: @@ -182,7 +182,7 @@ The skills map is drawn from `stackledger-skills.yaml`: `Line` and `MapLayout` d ## Catalogue format -A catalogue is a folder of YAML files: Backstage `Component` documents for software, `Resource` documents with `spec.type: licence` for licences, plus `Line` journeys, one `MapLayout` with station positions and zones, and an optional `Settings` document that chooses the fields the staff view hides. The [format reference](docs/catalogue-format.md) describes every field, how references work, which problems are warnings, and how to share the folder with a Backstage instance. Keep real data in its own private repository; this example is fictitious. Save it as `catalogue.yaml` in an empty folder and run `validate` on that folder: +A catalogue is a folder of YAML files: Backstage `Component` documents for software, `Resource` documents with `spec.type: licence` for licences, plus `Line` journeys, one `MapLayout` with station positions and zones, and an optional `Settings` document for the site's title, home page, colours and map. The [format reference](docs/catalogue-format.md) describes every field, how references work, which problems are warnings, and how to share the folder with a Backstage instance. Keep real data in its own private repository; this example is fictitious. Save it as `catalogue.yaml` in an empty folder and run `validate` on that folder: ```yaml apiVersion: backstage.io/v1alpha1 diff --git a/docs/architecture.md b/docs/architecture.md index 4319f108..e72c9b8d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -12,7 +12,7 @@ flowchart LR skills["Skill folders
SKILL.md, agents, rules"] machine["A Mac"] tool["stackledger"] - site["Static sites
full and staff"] + site["One static site
at the root"] files["SVG map, reports,
calendar file"] pages["Markdown pages
with Mermaid"] agent["AI agent
(MCP client)"] @@ -37,7 +37,7 @@ Three properties shape the design: - Publishing needs only what a pipeline can see. Reading a machine happens on that machine: `discover` writes a snapshot there, which `drift` compares with a catalogue. - Skills are read where they are. Only what a folder cannot say, the skills map, is written by hand. -## Main flow: build the sites +## Main flow: build the site ```mermaid sequenceDiagram @@ -53,11 +53,7 @@ sequenceDiagram C->>S: read the skill set, when one is given C->>O: check the folder, create a staging folder C->>B: prepare the build - B->>B: apply the staff view, unless the mode is full only - B->>A: build the staff site - B->>B: make its URLs relative and scan it - B->>B: apply the full view - B->>A: build the full site + B->>A: build the site from the full view B->>B: make its URLs relative and scan it C->>O: publish by renames C-->>U: build report on stderr @@ -93,7 +89,7 @@ Kept by hand: update it in the pull request that adds, moves or removes a module |---|---| | `src/cli.ts` | Command dispatch and exit codes | | `src/source.ts`, `schema.ts`, `validate.ts`, `secrets.ts`, `identity.ts` | Read the catalogue, check shapes and references, refuse secrets | -| `src/views.ts` | `full` and `staff`, rebuilt from allow-lists | +| `src/views.ts` | `full` and the deprecated `staff` view, rebuilt from allow-lists; the build uses `full` only | | `src/graph.ts`, `reports.ts`, `money.ts`, `ics.ts`, `report-*.ts` | Relations, impact, licence report and calendar | | `src/map/` | Positions, routing, labels, zones, themes, SVG and the other diagrams; `backdrops/` is generated | | `src/site/` | Site data, build, output scan and publication | @@ -119,8 +115,9 @@ Status is in the [ADR index](adr/README.md). - [ADR 4](adr/0004-own-map-engine-with-stored-positions.md): the project's own map engine, with positions stored as data. - [ADR 5](adr/0005-static-site-no-server.md): the website is static. - [ADR 6](adr/0006-authentication-at-an-identity-aware-proxy.md): sign-in happens at an identity-aware proxy. -- [ADR 7](adr/0007-two-views-built-as-separate-sites.md): two views, built as separate sites (superseded by ADR 13; still what the code builds). +- [ADR 7](adr/0007-two-views-built-as-separate-sites.md): two views, built as separate sites (superseded by ADR 13 for the site; the `staff` view stays in the code, deprecated). - [ADR 8](adr/0008-read-only-mcp-early-no-ai-in-the-core.md): a read-only MCP server and no AI model in the core. - [ADR 9](adr/0009-typescript-end-to-end.md): TypeScript end to end. - [ADR 10](adr/0010-agent-skills-are-a-second-ledger-read-from-their-folders.md): agent skills are a second ledger in the same tool. -- [ADR 11](adr/0011-skills-are-read-from-plugin-marketplaces.md): plugin marketplaces are read (`skills-marketplaces`), and the skills map's lines are journeys with marketplaces as zones (`skill-journeys`); project journeys are planned. [ADR 12](adr/0012-several-named-maps-and-stations-of-any-kind.md) and [ADR 13](adr/0013-one-private-site-at-the-root.md): planned, not built; see the [roadmap](roadmap.md). +- [ADR 11](adr/0011-skills-are-read-from-plugin-marketplaces.md): plugin marketplaces are read (`skills-marketplaces`), and the skills map's lines are journeys with marketplaces as zones (`skill-journeys`); project journeys are planned. [ADR 12](adr/0012-several-named-maps-and-stations-of-any-kind.md): planned, not built; see the [roadmap](roadmap.md). +- [ADR 13](adr/0013-one-private-site-at-the-root.md): one private site at the root, built (the `staff` view stays in the code, deprecated). diff --git a/docs/catalogue-format.md b/docs/catalogue-format.md index 5e904863..ebd9ba75 100644 --- a/docs/catalogue-format.md +++ b/docs/catalogue-format.md @@ -45,7 +45,7 @@ Every checked document has `apiVersion`, `kind`, and `metadata.name`. A name is | `Resource` | `backstage.io/v1alpha1` | Licence when `spec.type` is exactly `licence` | | `Line` | `stackledger/v1alpha1` | Ordered journey through components | | `MapLayout` | `stackledger/v1alpha1` | Station positions and zones | -| `Settings` | `stackledger/v1alpha1` | Fields hidden from the staff view; the site's title and colours | +| `Settings` | `stackledger/v1alpha1` | The site's title, home page, colours and map backdrop, and the skills folders (the hidden-field list of the deprecated staff view too) | Any other pair is an error, except `System`, `API`, `Group`, `User`, `Domain`, `Location` and `Template`: these are counted as ignored regardless of apiVersion, without checking names, fields or secrets. The one use of them is the [site](site.md#pages): it shows an owner such as `group:northwind` by the title of the `Group` or `User` document of that name, when that document has apiVersion `backstage.io/v1alpha1`, a valid name and nothing the secret scan rejects. @@ -170,9 +170,9 @@ Station references must match existing components. Two entries cannot occupy the ## Settings and views -> **Planned:** [ADR 13](adr/0013-one-private-site-at-the-root.md) makes the site a single one where everyone with access sees every field; the `staff` view then stays in the code, deprecated and unused (change `single-site`). [ADR 12](adr/0012-several-named-maps-and-stations-of-any-kind.md) allows several named maps (change `named-maps`). Both are described here only once built. +> **Planned:** [ADR 12](adr/0012-several-named-maps-and-stations-of-any-kind.md) allows several named maps (change `named-maps`); it is described here only once built. -stackledger has two views ([ADR 7](adr/0007-two-views-built-as-separate-sites.md)): `full` shows every field, and `staff` drops licence fields so that everyone can see the software without seeing what it costs. By default `staff` hides `cost`, `currency`, `cycle`, `renewsOn`, `paidBy`, `seats`, `vaultItem` and `note`. One `Settings` document changes that list. Keep it by convention in `stackledger.yaml` at the top of the catalogue; any file name works. +The site shows every field ([ADR 13](adr/0013-one-private-site-at-the-root.md), which supersedes [ADR 7](adr/0007-two-views-built-as-separate-sites.md)'s two sites), so the `Settings` document now sets the site's title, home page, colours and map. Two things in it are **deprecated** and still accepted, each with a warning: `spec.views.staff.hide` and `spec.sites`. They change nothing in the site. The `staff` view they belonged to stays in the code, used only by `stackledger mcp --view staff` and `stackledger map --view staff`, which are deprecated too (a line on stderr says so). One `Settings` document holds the settings. Keep it by convention in `stackledger.yaml` at the top of the catalogue; any file name works. ```yaml apiVersion: stackledger/v1alpha1 @@ -180,9 +180,6 @@ kind: Settings metadata: name: settings spec: - views: - staff: - hide: [cost, currency, renewsOn, paidBy, vaultItem, note] site: title: Northwind software colors: @@ -194,23 +191,23 @@ spec: | `metadata.name`, `metadata.namespace` | Identity and namespace rules above | | `metadata.title` | Optional non-empty string | | `spec` | Required mapping; may be empty (`spec: {}`) | -| `spec.views.staff.hide` | Optional list of licence field names without repeats, each one of `vendor`, `status`, `cycle`, `cost`, `currency`, `renewsOn`, `seats`, `paidBy`, `vaultItem` and `note` | -| `spec.site.title` | Optional title of both [sites](site.md), a non-empty string of at most 60 characters; default `stackledger` (up to 0.3.0, `Software map`) | +| `spec.views.staff.hide` | **Deprecated** (a warning; the site shows every field). Optional list of licence field names without repeats, each one of `vendor`, `status`, `cycle`, `cost`, `currency`, `renewsOn`, `seats`, `paidBy`, `vaultItem` and `note` | +| `spec.site.title` | Optional title of the [site](site.md), a non-empty string of at most 60 characters; default `stackledger` (up to 0.3.0, `Software map`) | | `spec.site.home.text` | Optional text of the home page's banner, a non-empty string of at most 200 characters | | `spec.site.home.links` | Optional list of 1 to 20 links for the home page, each with `title` (at most 60 characters), `url` (`http://` or `https://`, with a host, no user name or password, at most 2,048 characters) optionally `description` (at most 200 characters) and optionally `icon` (`github`, `website`, `linkedin`, `email`, `stackledger` or `brunosouzas`: the design system's link icon, in the light or dark version). A link with `icon` is shown as that icon alone, in a row before the other links, named by its `title` and " (opens in a new tab)" for screen readers (`aria-label`, no tooltip); every link opens in a new tab, and its name for screen readers ends with " (opens in a new tab)" (hidden text after a text link's title); the `description` is not shown when `icon` is set, and is accepted without a warning. With the OpenStreetMap credit under a city map (`spec.map.backdrop`), the only links from the site to other sites | | `spec.site.colors` | Optional mapping with any of `primary`, `accent`, `body` and `text`, each `#` and six hexadecimal digits (quote it: `#` starts a YAML comment). They replace the matching colours of the light theme only; the dark theme keeps its own | | `spec.map.backdrop` | Optional backdrop of the software map, `neutral` (the default, a flat panel) or `london` (central London from OpenStreetMap data, with its credit). Any other value, or any other field under `spec.map`, is an error, and the map then draws `neutral`. `stackledger map --backdrop` overrides it. See [the map](map.md#backdrop) | | `spec.skills.folders` | Optional list of 1 to 20 skills folders for `stackledger build`, without repeats, each relative to the catalogue folder (`..` allowed; no leading `/`, `\\` or `~`, and no drive letter such as `C:`). `--skills` replaces it. From 0.3.0; 0.2.0 reads it as an error: pin one version everywhere. See [Skills on the site](../README.md#skills-on-the-site) | | `spec.skills.map` | Optional path, relative to the catalogue folder in the same way, of the [skills map file](skills.md#the-skills-map-file) of journeys and marketplace zones; its last part must be exactly `stackledger-skills.yaml`. Read first when a skill set is read. | -| `spec.sites` | Optional list of the sites `stackledger build` writes: `[full]` (personal mode) or `[full, staff]` (corporate mode, the default), in any order, without repeats. `[staff]` alone, an empty list or any other value is an error | +| `spec.sites` | **Deprecated** (a warning, ignored): `stackledger build` always writes the one site. Still checked as before: `[full]` or `[full, staff]` in any order, without repeats; `[staff]` alone, an empty list or any other value is an error | -Unlisted fields anywhere in a Settings document are errors, so `spec.view` instead of `spec.views` is reported, and so is `spec.site.logo`. While the Settings document has an error, the sites use the default title and colours, and the home page shows the default text and no links. When `hide` is given it replaces the default list entirely: `[cost]` hides only the cost, and `[]` hides nothing. Without `hide`, the default list applies. +Unlisted fields anywhere in a Settings document are errors, so `spec.view` instead of `spec.views` is reported, and so is `spec.site.logo`. While the Settings document has an error, the site uses the default title and colours, and the home page shows the default text and no links. When `hide` is given it replaces the default list entirely: `[cost]` hides only the cost, and `[]` hides nothing. Without `hide`, the default list applies. -**Personal or corporate.** Without `spec.sites`, `stackledger build` writes both sites: the corporate mode, where finance reads `full` and everyone else `staff`. When you are the only reader, `sites: [full]` is the personal mode: only the `full` site is built and published, and `/` leads to it. While the Settings document has an error, the build uses the default and writes both sites. See [docs/hosting.md](hosting.md) for the access setup of each mode. +**One site.** `stackledger build` writes one site at the root, whatever `spec.sites` says, and warns when it is set. See [docs/hosting.md](hosting.md) for the access setup. At most one Settings document is allowed; the earliest is used. A later one with another name gets an error naming the earlier file; one with the same name gets only the duplicate-name error. -**Broken settings hide everything.** While any document whose kind is `Settings` in any case has an error, or any file named `stackledger.yaml` or `stackledger.yml` has an error, the `staff` view hides every licence field above, until it is fixed. A document that reads as `Settings` in a file with a YAML syntax error, or that cannot be expanded, counts too. A typo can never hide less than you asked for. Keep the document in `stackledger.yaml`: any error in that file, even one that stops it from being read at all (too large, unreadable), also hides everything, whereas a broken file of another name is recognised only on a best-effort reading of its `kind`, and a symbolic link is never followed. +**Broken settings hide everything (the deprecated `staff` view only).** While any document whose kind is `Settings` in any case has an error, or any file named `stackledger.yaml` or `stackledger.yml` has an error, the `staff` view hides every licence field above, until it is fixed. A document that reads as `Settings` in a file with a YAML syntax error, or that cannot be expanded, counts too. A typo can never hide less than you asked for. Keep the document in `stackledger.yaml`: any error in that file, even one that stops it from being read at all (too large, unreadable), also hides everything, whereas a broken file of another name is recognised only on a best-effort reading of its `kind`, and a symbolic link is never followed. In `staff`, components and licences are rebuilt from the fields this reference lists, so a field written in the wrong place (for example `spec.cost` next to `spec.licence`, or a `spec.licence` block on a component) never reaches staff. Free text is not filtered: **keep prices, renewal terms and payment details in licence fields**, not in `metadata.description`, annotations, tags or titles, which staff can read. diff --git a/docs/demo.md b/docs/demo.md index 4bd39b26..2e1442d8 100644 --- a/docs/demo.md +++ b/docs/demo.md @@ -1,15 +1,17 @@ # The demo - shows the fictitious Northwind example in the corporate mode: the `full` and `staff` sites, each with the Software and Skills divisions. It is built from the files in this repository, never from real data: + shows the fictitious Northwind example as one private site at the root, with the Software and Skills divisions. It is built from the files in this repository, never from real data: - `examples/northwind/`: the software and licence catalogue; - `examples/northwind-skills/`: the skill set, its playbooks and agents, and its skills map file. -It sits behind Cloudflare Access as described in [Hosting](hosting.md#corporate-mode-two-applications). Only the owner can sign in, so everyone else sees the sign-in page, which is the point. +It sits behind Cloudflare Access as described in [Hosting](hosting.md#one-site-one-application). Only the owner can sign in, so everyone else sees the sign-in page, which is the point. ## Rebuild and deploy -The owner deploys by hand with the released package and the same handoff as the [pipeline template](../examples/catalogue-repository/): only `full/`, `staff/`, `_headers`, `robots.txt` and `_redirects` are uploaded. +The owner deploys by hand with the released package and the same handoff as the [pipeline template](../examples/catalogue-repository/): every entry of the build folder except its `.stackledger-build` marker is uploaded (and none if a `.stackledger-tmp-*` staging folder is left in it). + +The pinned release must be the first one with the one-site layout: with an older one the build writes `full/` and `staff/`, and the handoff below would upload both. Move the pin (and the template's) when that release is out. You need Node.js 22.12 or later and a wrangler sign-in to the account that owns the `stackledger-demo` Pages project (`wrangler login`, or `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID` in the environment). Run the block from the top of this repository, on `main`, with no local changes. @@ -30,7 +32,8 @@ The package is installed into a temporary folder because, inside this repository "$bin/stackledger" skills validate examples/northwind-skills "$bin/stackledger" build examples/northwind --out "$out/site" --date "$date" --skills examples/northwind-skills mkdir -p "$out/deploy/site" - for entry in full staff _headers robots.txt _redirects; do cp -R "$out/site/$entry" "$out/deploy/site/"; done + ! compgen -G "$out/site/.stackledger-tmp-*" > /dev/null || { echo "The build left a staging folder" >&2; exit 1; } + cp -R "$out/site/." "$out/deploy/site/" && rm "$out/deploy/site/.stackledger-build" cd "$out/deploy" WRANGLER_SEND_METRICS=false "$bin/wrangler" pages deploy site --project-name stackledger-demo --branch main \ --commit-hash "$commit" --commit-message "demo $date $commit" @@ -41,4 +44,4 @@ The package is installed into a temporary folder because, inside this repository ## Check after the deploy -Run the anonymous checks of [Check the corporate sites](hosting.md#check-the-corporate-sites) on `stackledger-demo.pages.dev` and on the preview address wrangler printed: `/`, `/staff/`, `/full/`, `/full/renewals.ics` and one real asset below `/full/_astro/` and `/staff/_astro/` (take the file names from the built HTML). Every request must answer `302` to the Access sign-in. The staff-only sign-in check is skipped for the demo: only the owner's identity is allowed, so there is no staff-only identity to test with. +Run the anonymous checks of [Check the site](hosting.md#check-the-site) on `stackledger-demo.pages.dev` and on the preview address wrangler printed: `/`, `/reports/`, `/renewals.ics`, `/full/` and one real asset below `/_astro/` (take the file name from the built HTML). Every request must answer `302` to the Access sign-in. Then sign in as the owner: `/` opens the home page. diff --git a/docs/hosting.md b/docs/hosting.md index f9d67e74..4737ef76 100644 --- a/docs/hosting.md +++ b/docs/hosting.md @@ -1,19 +1,14 @@ # Hosting the catalogue -> **Planned, not built:** [ADR 13](adr/0013-one-private-site-at-the-root.md) moves the site to the root with one Access application and no `/full/` or `/staff/` paths (change `single-site`). The Access application covering the root on every address must allow only people who may see everything before the first deploy there. This page describes the two-site setup the build produces today. - -A catalogue maps its owner's attack surface. Every published site must be behind sign-in, including its assets and calendar file. Publish only `full/`, `staff/` (corporate mode), `_headers`, `robots.txt` and `_redirects` after a successful build. Never serve the build folder while it is being built: staging files can hold finance data outside `/full/` ([site publication rules](site.md#publishing-the-output)). +A catalogue maps its owner's attack surface. The site shows everything, licences included, so it must be behind sign-in on **every address**, assets and calendar file included, and only people who may see everything may pass ([ADR 13](adr/0013-one-private-site-at-the-root.md)). Publish only the site's files after a successful build: every entry of the output folder except its `.stackledger-build` marker and any `.stackledger-tmp-*` folder. Never serve the build folder while it is being built: staging files hold the whole catalogue ([site publication rules](site.md#publishing-the-output)). The [catalogue repository template](../examples/catalogue-repository/) checks and builds a separate catalogue repository and deploys it to Cloudflare Pages. Its README lists the secrets and variable. Protect the project before its first deployment. [How it works](how-it-works.md) draws the whole path. -## Two modes +## One site, one application -| Mode | Settings | Sites | Access | `/` leads to | -| --- | --- | --- | --- | --- | -| Personal: you are the only reader | `spec.sites: [full]` in `stackledger.yaml` | `full` | one application, you only | `/full/` | -| Corporate (the default) | no `sites`, or `sites: [full, staff]` | `full` and `staff` | two applications: finance on `/full/*`, staff on the rest | `/staff/` | +The build writes one site at the root. `/` is its home page, with no redirect to another path. The old two-site addresses redirect to the same path at the root (`/full/software/` goes to `/software/`, `/full/renewals.ics` to `/renewals.ics`), through the `_redirects` file the build writes, which Cloudflare Pages follows; on another host, add the same redirect (the Caddy example below does). -The build writes `_redirects` for `/`, which Cloudflare Pages follows. The [catalogue format](catalogue-format.md#settings-and-views) has the `Settings` rules. Choose the mode before the first deploy. To switch, change Access first, then `sites`. +Access has one application on the whole address, with one policy that allows only the people who may see everything. There is no second application and no path rule: whoever passes sees it all. To go from the two-site layout, change Access first (replace the two applications with the one below, allowing only the people who were on `/full/*`), then deploy. **Access covering the root on every address comes before the first deploy of this layout.** ## Cloudflare Pages with Access @@ -25,82 +20,43 @@ Follow this order, so there is never an unprotected deployment. See [Pages Acces npx wrangler pages project create --production-branch main ``` -2. In the Pages project's settings, enable its Access policy ("Enable access policy"). Cloudflare creates an application for preview addresses. Edit that application, and add another in the corporate mode, so the applications of your mode below exist. Do not leave an extra, weaker application matching the same paths. -3. Choose an identity provider: one-time PIN by e-mail needs no provider setup; a company can use Google or Microsoft ([identity providers](https://developers.cloudflare.com/cloudflare-one/integrations/identity-providers/)). -4. Configure the self-hosted applications of your mode below, each with **every address** as an application destination: the custom domain if present, the production Pages address and the wildcard Pages address. The wildcard covers branch aliases and deployment previews. Use your own project, domain and groups; the examples are fictitious. -5. Only then run the template's first deploy. Check the requests of your mode before sharing any link. - -### Personal mode: one application +2. In the Pages project's settings, enable its Access policy ("Enable access policy"). Cloudflare creates an application for preview addresses. Edit that application so it is the one below. Do not leave an extra, weaker application matching the same addresses. +3. Choose an identity provider: Google, Microsoft or another provider you trust ([identity providers](https://developers.cloudflare.com/cloudflare-one/integrations/identity-providers/)); one-time PIN by e-mail needs no provider setup. Sign-in is Cloudflare Access's: stackledger has no sign-in code. +4. Configure the self-hosted application below with **every address** as a destination: the custom domain if present, the production Pages address and the wildcard Pages address. The wildcard covers branch aliases and deployment previews. Use your own project, domain and people; the examples are fictitious. +5. Only then run the template's first deploy. Check the requests below before sharing any link. -The simplest setup: one site, one reader. +### The application #### stackledger -Policy **owner**: Allow only your own identity (your e-mail address with one-time PIN). No Bypass policy and no public Allow policy. +Policy **readers**: Allow only the people or the identity-provider group who may see every cost, renewal and contract in the catalogue. No Bypass policy and no public Allow policy. -Destinations (whole address): +Destinations (the whole address): - `catalogue.example.org` (custom domain, if any) - `.pages.dev` - `*..pages.dev` -#### Check the personal site - -On each address (custom domain, production Pages address, and a real preview or branch address), make anonymous requests with `curl -sI` to: - -- `/` -- `/full/` -- `/full/renewals.ics` -- one actual asset below `/full/_astro/` (pick the filename from the built HTML, not a made-up filename) -- `/staff/`: a personal build publishes no staff site, but an older deployment or preview built in the corporate mode may still hold one - -Every request must answer **302**, with `Location` pointing to `.cloudflareaccess.com`. A 200, a direct asset response or a public error page is a failed check: do not share the address. Then sign in: `/` leads to `/full/` and the site opens. - -### Corporate mode: two applications - -#### stackledger full - -Policy **finance**: Allow only the people or identity-provider group allowed to read costs and contracts. No Bypass policy and no public Allow policy. - -Destinations (one path per address): +When adding a domain later, add its destination to this application before serving it. -- `catalogue.example.org/full/*` (custom domain, if any) -- `.pages.dev/full/*` -- `*..pages.dev/full/*` - -#### stackledger staff - -Policy **staff**: Allow staff and finance identities. Finance must belong to this policy too so they can open staff pages. - -Destinations (whole address): - -- `catalogue.example.org` (custom domain, if any) -- `.pages.dev` -- `*..pages.dev` - -Access uses the most specific matching path, so `/full/*` uses finance on **every address**, not the broader staff policy. When adding a domain later, add its destinations to both applications before serving it. - -#### Check the corporate sites +### Check the site On each address (custom domain, production Pages address, and a real preview or branch address), make anonymous requests with `curl -sI` to: - `/` -- `/staff/` -- `/full/` -- `/full/renewals.ics` -- one actual asset below `/full/_astro/` -- one actual asset below `/staff/_astro/` +- `/reports/` +- `/renewals.ics` +- one actual asset below `/_astro/` (pick the filename from the built HTML, not a made-up filename) +- `/full/` and `/full/renewals.ics`: the old addresses must be refused too, since Access answers before the redirect -Pick the asset filenames from the built HTML, not a made-up filename. For example: +For example: ```sh -curl -sI https://catalogue.example.org/full/ -curl -sI https://catalogue.example.org/full/renewals.ics +curl -sI https://catalogue.example.org/ +curl -sI https://catalogue.example.org/renewals.ics ``` -Every request must answer **302**, with `Location` pointing to `.cloudflareaccess.com`. A 200, a direct asset response or a public error page is a failed check: do not share the deployment. Check policy destinations and precedence first. - -Then sign in with a **staff-only** identity. `/staff/` and its assets must open; `/full/`, `/full/renewals.ics` and a full asset must be refused. Sign in as finance and verify both sites open. Repeat on every address. Changing an Access policy means repeating these checks. +Every request must answer **302**, with `Location` pointing to `.cloudflareaccess.com`. A 200, a direct asset response or a public error page is a failed check: do not share the address. Check the policy destinations first. Then sign in as one of the people in the policy: `/` opens the home page, and `/full/software/` redirects to `/software/`. Repeat on every address. Changing an Access policy means repeating these checks. ### Rollback @@ -108,13 +64,13 @@ Pages keeps production deployments labelled with the commit and build date by th ## Any host: Caddy and oauth2-proxy -The tested example is [`examples/hosting/Caddyfile`](../examples/hosting/Caddyfile). It is written for the corporate mode. Caddy serves `full/`, `staff/`, `_headers` and `robots.txt` (it does not read `_redirects`) and asks oauth2-proxy to authenticate **every site request** before serving files. The `/oauth2/*` endpoints themselves are routed to oauth2-proxy for sign-in and callbacks. +The tested example is [`examples/hosting/Caddyfile`](../examples/hosting/Caddyfile). Caddy serves the site's files (it does not read `_redirects` or `_headers`; the example writes the same rules itself) and asks oauth2-proxy to authenticate **every site request** before serving files. The `/oauth2/*` endpoints themselves are routed to oauth2-proxy for sign-in and callbacks. -- `/full/*` (and `/full`) requires the exact group `finance`. -- All other site paths require `staff` or `finance`. +- Every path requires the exact group `readers`: it is the one audience, so put in it only the people who may see everything. - Any other signed-in identity receives 403. - Only `X-Auth-Request-Groups` returned by oauth2-proxy counts. Caddy drops the client's copy first, including when the auth answer has no groups. - Anonymous requests go to sign-in. An unavailable auth service fails closed (502, no site content). +- `/full` and `/full/` redirect to `/` with 301, after the check, so only a reader is redirected. Use a real identity provider that returns group claims. This fictitious OIDC setup shows the relevant oauth2-proxy flags ([oauth2-proxy configuration](https://oauth2-proxy.github.io/oauth2-proxy/configuration/overview/)): @@ -135,12 +91,12 @@ oauth2-proxy \ --cookie-secure=true ``` -Configure the provider to return `staff` and `finance` group claims. Do not use e-mail domains as a replacement for authorisation: Caddy still checks the groups. Use your provider's documented scopes (not all providers call the groups scope `groups`). oauth2-proxy must listen only on loopback or a private network reachable by Caddy, never publicly. Protect its client and cookie secrets in the host's secret store. The site's origin must not be reachable directly around Caddy. +Configure the provider to return the `readers` group claim. Do not use e-mail domains as a replacement for authorisation: Caddy still checks the group. Use your provider's documented scopes (not all providers call the groups scope `groups`). oauth2-proxy must listen only on loopback or a private network reachable by Caddy, never publicly. Protect its client and cookie secrets in the host's secret store. The site's origin must not be reachable directly around Caddy. -Copy the Caddyfile, replace `catalogue.example.org`, `127.0.0.1:4180` and `/srv/stackledger/publish`, and run Caddy with it. Caddy manages HTTPS for the configured domain. Deploy only those four entries into that root, never build in it. The example repeats the security headers from `_headers` because Caddy does not interpret that file; it also serves `.ics` as `text/calendar` and redirects `/` to `/staff/` after authentication, its own version of `_redirects`. In the personal mode, there is no `staff/`: change that redirect to `/full/`, and replace the rule that lets `staff` or `finance` read every other path with one that allows only your own group (for example `finance` with you as its only member), so no other signed-in identity can read anything. +Copy the Caddyfile, replace `catalogue.example.org`, `127.0.0.1:4180` and `/srv/stackledger/publish`, and run Caddy with it. Caddy manages HTTPS for the configured domain. Deploy only the site's files into that root (everything in the build folder except `.stackledger-build` and any `.stackledger-tmp-*`), never build in it. The example repeats the security headers from `_headers` and serves `.ics` as `text/calendar`. -Run the same anonymous, staff and finance checks as above, plus: send a client `X-Auth-Request-Groups: finance` header as staff (still refused on full), and stop oauth2-proxy (every site request must fail with no content). The integration test does these with the real example Caddyfile and a small local stand-in for oauth2-proxy; it does not replace checking your identity provider's claims and network boundary. +Run the same anonymous checks as above, plus: sign in as a reader and as a signed-in identity outside `readers` (refused everywhere), send a client `X-Auth-Request-Groups: readers` header as that identity (still refused), and stop oauth2-proxy (every site request must fail with no content). The integration test does these with the real example Caddyfile and a small local stand-in for oauth2-proxy; it does not replace checking your identity provider's claims and network boundary. ## Calendar files are downloads, not subscriptions -`/full/renewals.ics` is for download and import. Calendar services fetch subscriptions without the reader's sign-in, so Access or the generic proxy refuses them. Never move it outside the protected path to make subscriptions work: it holds costs ([calendar rules](site.md#one-host-two-audiences)). +`/renewals.ics` is for download and import. Calendar services fetch subscriptions without the reader's sign-in, so Access or the generic proxy refuses them. Never publish the file outside the protected address to make subscriptions work: it holds costs ([calendar rules](site.md#one-host-one-audience)). diff --git a/docs/how-it-works.md b/docs/how-it-works.md index d9b6dcc5..50f78b94 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -36,14 +36,8 @@ flowchart TB 4. **Pull requests never deploy.** They run the same checks and build, so a broken catalogue is caught before it reaches `main`. 5. **Readers sign in first.** Cloudflare Access sits in front of every address of the Pages project ([hosting](hosting.md)). The site is static files only: it never reads GitHub, has no server code and makes no outside requests. -## Personal or corporate +## One private site -| | Personal | Corporate (default) | -| --- | --- | --- | -| Who reads it | you alone | finance and the rest of the company | -| `spec.sites` in `stackledger.yaml` | `[full]` | not set, or `[full, staff]` | -| Sites | `full`, with costs | `full` for finance, `staff` without costs for everyone else | -| Cloudflare Access | one application, only you | two: finance on `/full/*`, staff on the rest | -| `/` leads to | `/full/` | `/staff/` | +stackledger builds one site, at the root of the address, with everything in it: costs, renewals, payers and contract details ([ADR 13](adr/0013-one-private-site-at-the-root.md)). Whoever can open it sees all of it, so there is one Cloudflare Access application on the whole address, with a policy that lets in only the people who may see everything. `/` is the home page. Older `/full/...` addresses redirect to the same path at the root. The `staff` view that hid the costs is deprecated: it stays in the code, but nothing builds or serves it. The diagram is drawn by [`@brunosouzas/signwright`](https://www.npmjs.com/package/@brunosouzas/signwright) from the spec [`scripts/how-it-works.json`](../scripts/how-it-works.json), which follows the Mermaid block above, with its Source faces embedded as subsets (GitHub shows the file as an image, which never loads a page's fonts): after changing either, run `npm run build && node scripts/site-art.mjs`. diff --git a/docs/map.md b/docs/map.md index 2c930546..eee2e92a 100644 --- a/docs/map.md +++ b/docs/map.md @@ -6,10 +6,10 @@ Draw a local catalogue with Node.js 22 or later, from this checkout: npm ci npm run build node dist/cli.js map examples/northwind --date 2027-06-01 > map.svg -node dist/cli.js map examples/northwind --view staff --theme dark --date 2027-06-01 > map-staff.svg +node dist/cli.js map examples/northwind --theme dark --date 2027-06-01 > map-dark.svg ``` -`stackledger map [--view full|staff] [--theme light|dark] [--backdrop neutral|london] [--date YYYY-MM-DD]` prints one self-contained SVG followed by a newline. Defaults are `full`, `light`, the catalogue's `spec.map.backdrop` (`neutral` without it) and the machine's local calendar date. `--help` anywhere prints usage and exits 0, even alongside invalid arguments. An invalid option, impossible date, missing folder, extra folder or unreadable/non-directory folder exits 2 with the reason and usage on stderr and no stdout. A catalogue with errors still draws its served documents and exits 0. An unexpected failure while laying out or drawing the map is a bug in stackledger: it exits 1 with one `internal error` line on stderr, no usage text and no stdout. Run `stackledger validate` to gate a catalogue on validity. +`stackledger map [--view full|staff] [--theme light|dark] [--backdrop neutral|london] [--date YYYY-MM-DD]` prints one self-contained SVG followed by a newline. `--view staff` is deprecated ([ADR 13](adr/0013-one-private-site-at-the-root.md)): it still draws, and prints one line on stderr saying so. Defaults are `full`, `light`, the catalogue's `spec.map.backdrop` (`neutral` without it) and the machine's local calendar date. `--help` anywhere prints usage and exits 0, even alongside invalid arguments. An invalid option, impossible date, missing folder, extra folder or unreadable/non-directory folder exits 2 with the reason and usage on stderr and no stdout. A catalogue with errors still draws its served documents and exits 0. An unexpected failure while laying out or drawing the map is a bug in stackledger: it exits 1 with one `internal error` line on stderr, no usage text and no stdout. Run `stackledger validate` to gate a catalogue on validity. The command reads local files only. It does not write the catalogue, open network connections or send telemetry. Shell redirection in these examples writes the SVG you requested. Recoverable problem counts, suggested positions and unrouted hops go to stderr. Counts appear only in `full`, and only when there are errors or warnings. When an invalid layout is excluded, both views explain that its stored positions are not used. diff --git a/docs/mcp.md b/docs/mcp.md index 5beaf0a2..6a439baf 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10,22 +10,22 @@ With Node.js 22.12 or later, `npx --yes @brunosouzas/stackledger@0.8.0 mcp /path npm ci npm run build node dist/cli.js mcp /path/to/catalogue -node dist/cli.js mcp /path/to/catalogue --view staff +node dist/cli.js mcp /path/to/catalogue --view staff # deprecated ``` `stackledger mcp [--view full|staff]`: - The folder is required, because MCP clients often start servers in `/` or the home folder. It is resolved to an absolute path at start. -- `--view` is `full` (the default) or `staff`. +- `--view` is `full` (the default) or `staff`. The `staff` view is **deprecated** ([ADR 13](adr/0013-one-private-site-at-the-root.md)): the site shows everything now and nothing builds a staff view, so choosing it prints one extra line on stderr saying so. It still works, and will be removed in a later release. - `--help` anywhere prints usage and exits 0. A missing folder argument, an unknown option, another view, two folders, or a folder that does not exist, is not a folder or cannot be read prints the reason and usage on stderr, nothing on stdout, and exits 2 before serving. - The server stops with exit 0 when the client closes its input. -- stdout carries only protocol messages. stderr gets one line at start (folder, view, number of tools) and one line per failed tool call (tool and reason). Logs never contain catalogue values. +- stdout carries only protocol messages. stderr gets one line at start (folder, view, number of tools; a deprecation line after it with `--view staff`) and one line per failed tool call (tool and reason). Logs never contain catalogue values. Every tool call reads and checks the folder again, so an agent that edits a YAML file sees its edit on the next call. The server keeps no state and no cache. ## Views -The two views are those of [ADR 7](adr/0007-two-views-built-as-separate-sites.md): +The two views come from [ADR 7](adr/0007-two-views-built-as-separate-sites.md), which [ADR 13](adr/0013-one-private-site-at-the-root.md) supersedes for the site: `full` is the view to use, and `staff` is kept only for old setups and is deprecated. | View | Shows | Tools | |---|---|---| @@ -64,7 +64,7 @@ A failed call returns a tool error: a result marked `isError` with one text givi ## Client configuration -Use absolute paths: the client may start the server from any folder. Replace `/path/to/stackledger` with your clone and `/path/to/catalogue` with your catalogue folder. Add `--view staff` to serve the staff view, for example on a machine you hand to a colleague who should not see costs. +Use absolute paths: the client may start the server from any folder. Replace `/path/to/stackledger` with your clone and `/path/to/catalogue` with your catalogue folder. The deprecated `--view staff` serves the staff view; do not rely on it. ### Claude Code diff --git a/docs/reports.md b/docs/reports.md index 7ed48c1f..f5be4eee 100644 --- a/docs/reports.md +++ b/docs/reports.md @@ -1,12 +1,12 @@ # Licence reports -stackledger adds up what the catalogue's licences cost and when they renew. The same report appears in three places, all from the `full` view only ([ADR 7](adr/0007-two-views-built-as-separate-sites.md)): +stackledger adds up what the catalogue's licences cost and when they renew. The same report appears in three places, all from the `full` view ([ADR 13](adr/0013-one-private-site-at-the-root.md): the site shows everything): -- the **Reports** page of the `full` site (`/reports/`), with a link to the calendar file `renewals.ics`, both written by `stackledger build` ([docs/site.md](site.md)); +- the **Reports** page of the site (`/reports/`), with a link to the calendar file `renewals.ics`, both written by `stackledger build` ([docs/site.md](site.md)); - `stackledger report`, which prints it as text, JSON, CSV or an iCalendar file; - the calendar file itself, for import into a calendar program. -The `staff` site has no Reports page, no calendar file and no link to either. +The deprecated `staff` view has no licence costs or dates, so it has no report. ## What is counted @@ -115,7 +115,7 @@ ref,title,vendor,status,cycle,cost,currency,monthly,yearly,renewsOn,owner,paidBy ## The calendar file -`renewals.ics` (in the `full` site) and `stackledger report --format ics` are the same iCalendar file ([RFC 5545](https://www.rfc-editor.org/rfc/rfc5545)) for the report's renewals: +`renewals.ics` (in the site) and `stackledger report --format ics` are the same iCalendar file ([RFC 5545](https://www.rfc-editor.org/rfc/rfc5545)) for the report's renewals: - One all-day event per licence renewing in the window (overdue licences and dates outside the window are not in it): it starts on the renewal date and ends the next day. - Summary `Renewal: `; description with the vendor, the cost and currency, and the cycle. @@ -129,7 +129,7 @@ ref,title,vendor,status,cycle,cost,currency,monthly,yearly,renewsOn,owner,paidBy **Event stamp.** `DTSTAMP` is the report date at midnight UTC, and the file has no `METHOD`, so RFC 5545 reads `DTSTAMP` as the time the information was last revised. This keeps the file reproducible: the same catalogue and date give the same bytes. The trade-off: after editing a licence, a file exported again with the same `--date` has the same `DTSTAMP`. Calendar programs that import a file replace events by `UID`; one that relies on `DTSTAMP` to accept an update needs a new `--date`. -**Download, not subscription.** The file is meant to be downloaded and imported. A calendar subscription will not work for the copy in the `full` site: calendar services such as Google Calendar and Outlook fetch a feed from their own servers, without the reader's sign-in, and the identity-aware proxy in front of the site refuses them. Do not publish the file outside the proxy to make it subscribable: it holds costs and vendors. A pipeline that must publish it elsewhere should put it behind its own access control. +**Download, not subscription.** The file is meant to be downloaded and imported. A calendar subscription will not work for the copy in the site: calendar services such as Google Calendar and Outlook fetch a feed from their own servers, without the reader's sign-in, and the identity-aware proxy in front of the site refuses them. Do not publish the file outside the proxy to make it subscribable: it holds costs and vendors. A pipeline that must publish it elsewhere should put it behind its own access control. ## Example diff --git a/docs/roadmap.md b/docs/roadmap.md index 4ff1119d..31a1a78f 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -49,7 +49,7 @@ Decided on 2026-12-05 by [ADR 11](adr/0011-skills-are-read-from-plugin-marketpla | # | Change | Delivers | Status | |---|---|---|---| -| 1 | `single-site` | One private site served at the root, with no `full`/`staff` split and no `/full/` or `/staff/` paths; whoever has access sees everything, licences included; the `staff` view stays in the code, deprecated and not built into a reachable address; old `/full/` links redirect to the root; the hosting recipes and pipeline template follow, and the Access application covering the root must allow only people who may see everything before the first deploy ([ADR 13](adr/0013-one-private-site-at-the-root.md)) | Planned (SW-345) | +| 1 | `single-site` | One private site served at the root, with no `full`/`staff` split and no `/full/` or `/staff/` paths; whoever has access sees everything, licences included; the `staff` view stays in the code, deprecated and not built into a reachable address; old `/full/` links redirect to the root; the hosting recipes and pipeline template follow, and the Access application covering the root must allow only people who may see everything before the first deploy ([ADR 13](adr/0013-one-private-site-at-the-root.md)) | Built (SW-345, unreleased) | | 2 | `skills-marketplaces` | Reading Claude Code plugin marketplaces (`marketplace.json`, each plugin's `skills/` and `agents/`), names as `plugin:skill`, same-named agents of two plugins both kept; loose folders keep working ([ADR 11](adr/0011-skills-are-read-from-plugin-marketplaces.md)) | Delivered in [#65](https://github.com/brunosouzas/stackledger/pull/65) | | 3 | `skill-journeys` | Skills map lines are journeys (kinds of work) without playbooks as zones; zones are marketplaces, and skills outside one get a zone of their own; shared skills and agents show as interchanges; the skills map file may live in the catalogue repository | Delivered in [#69](https://github.com/brunosouzas/stackledger/pull/69) | | 4 | `project-journeys` | A project component declares the journeys it follows (the annotation key is set by the spec); a per-project view computed from the journeys | Planned (SW-348) | @@ -74,7 +74,7 @@ Decided on 2026-12-05 by [ADR 11](adr/0011-skills-are-read-from-plugin-marketpla ## Out of scope -A server with a database, a multi-tenant hosted service, sign-in code inside stackledger, roles inside the site (from `single-site`, [ADR 13](adr/0013-one-private-site-at-the-root.md): whoever has access sees everything, and the `staff` view will be deprecated; until then `full` and `staff` exist), AI model calls inside the tool, hardware asset management (Snipe-IT covers it), measuring how much a licence is used, and payments. +A server with a database, a multi-tenant hosted service, sign-in code inside stackledger, roles inside the site (from `single-site`, [ADR 13](adr/0013-one-private-site-at-the-root.md): whoever has access sees everything, and the `staff` view is deprecated and unused), AI model calls inside the tool, hardware asset management (Snipe-IT covers it), measuring how much a licence is used, and payments. ## Background diff --git a/docs/site.md b/docs/site.md index cff5dded..adabb78a 100644 --- a/docs/site.md +++ b/docs/site.md @@ -1,8 +1,6 @@ # The catalogue site -> **Planned, not built:** [ADR 13](adr/0013-one-private-site-at-the-root.md) replaces the two sites below with one private site at the root, where whoever has access sees everything, and `/full/` links redirect to it (change `single-site`). This page describes what the build does today. - -`stackledger build` turns a catalogue folder into two static websites: `full/` for the people allowed to see costs and contracts (owners and finance), and `staff/` for everyone else. In the personal mode (`spec.sites: [full]` in the [Settings document](catalogue-format.md#settings-and-views)), when you are the only reader, it builds only `full/`. Each is a complete site built only from its view ([ADR 7](adr/0007-two-views-built-as-separate-sites.md)), meant to be served behind an identity-aware proxy ([ADR 6](adr/0006-authentication-at-an-identity-aware-proxy.md)). +`stackledger build` turns a catalogue folder into one static website, at the root of the address. It shows everything, licences and their costs included, so it is meant to be served only behind sign-in, for people who may see all of it ([ADR 13](adr/0013-one-private-site-at-the-root.md), which replaces [ADR 7](adr/0007-two-views-built-as-separate-sites.md)'s two sites; [ADR 6](adr/0006-authentication-at-an-identity-aware-proxy.md) keeps sign-in out of stackledger). Addresses of the older two-site layout, `/full/...`, redirect to the same path at the root. ## Build @@ -14,17 +12,17 @@ npm run build node dist/cli.js build examples/northwind --out ./public --date 2027-06-01 ``` -`stackledger build <folder> --out <dir> [--date YYYY-MM-DD] [--skills <folder>]...` writes `<dir>/full/`, `<dir>/staff/`, `<dir>/_headers`, `<dir>/robots.txt`, `<dir>/_redirects` and the marker `<dir>/.stackledger-build`. In the personal mode there is no `staff/`, and one left by an earlier build is removed with the rest of that build. `_redirects` sends `/` to `/staff/`, or to `/full/` in the personal mode, as `/ /staff/ 302` (the Cloudflare Pages and Netlify format). `--date` sets the map date and the report date of the `full` site (renewals within 30 days are ringed on the map; the Reports page and `renewals.ics` cover the 90 days from it); the default is the machine's local date. The `staff` site never depends on the date. +`stackledger build <folder> --out <dir> [--date YYYY-MM-DD] [--skills <folder>]...` writes the site into `<dir>`: `index.html` and the page folders (`map/`, `software/`, `licences/`, `journeys/`, `reports/`, and with a skill set `skills/` and the rest), `renewals.ics`, `<dir>/_headers`, `<dir>/robots.txt`, `<dir>/_redirects` and the marker `<dir>/.stackledger-build`. A `full/` or `staff/` folder left by an earlier build is removed with the rest of that build. `_redirects` sends the old two-site addresses to the root, as `/full / 301` and `/full/* /:splat 301` (the Cloudflare Pages and Netlify format), `renewals.ics` included. `--date` sets the map date and the report date (renewals within 30 days are ringed on the map; the Reports page and `renewals.ics` cover the 90 days from it); the default is the machine's local date. | Exit | When | | --- | --- | -| 0 | The sites are published. A catalogue with errors still builds from what the views serve. | +| 0 | The site is published. A catalogue with errors still builds from what the catalogue serves. | | 1 | An internal failure. Nothing published changed: the previous build, if any, is still there byte for byte. The exceptions are a failed undo and a staging folder an earlier failed undo left behind: stderr names the staging folder, and [Restoring after a failed publication](#restoring-after-a-failed-publication) says what to do. | | 2 | A usage or folder problem: `--help` aside, a missing folder or `--out`, an unknown option, an impossible date, more than one folder, a catalogue folder that is missing, not a folder or unreadable, an `--out` that is a file, or a `.stackledger-tmp-*` entry in it that is a symbolic link or a file. Nothing is created or changed. | -The output folder is refused (exit 2) when, after resolving symbolic links, it is the catalogue folder, inside it, contains it, or is a non-empty folder without the marker of an earlier build. The marker counts only as a regular file (not a link or a folder) holding exactly the text stackledger writes. The folder is also refused when `full`, `staff`, `_headers`, `robots.txt`, `_redirects` or the marker is a symbolic link: the build never renames or removes through a link. A missing output folder is created. Building again into the same folder replaces the previous build completely. +The output folder is refused (exit 2) when, after resolving symbolic links, it is the catalogue folder, inside it, contains it, or is a non-empty folder without the marker of an earlier build. The marker counts only as a regular file (not a link or a folder) holding exactly the text stackledger writes. The folder is also refused when any of its entries, or the marker, is a symbolic link: the build never renames or removes through a link. A missing output folder is created. Building again into the same folder replaces the previous build completely. -stderr holds the report, in this order: the catalogue's error and warning counts with a hint to run `stackledger validate` (only when there is at least one), the map's suggested positions, unrouted hops and unused layout as [`stackledger map`](map.md) writes them for the `full` view, the skill set's lines (see [Skills](#skills)), one line per site built with its folder and page count, and a reminder that the folders must be served behind an identity-aware proxy. +stderr holds the report, in this order: the catalogue's error and warning counts with a hint to run `stackledger validate` (only when there is at least one), the map's suggested positions, unrouted hops and unused layout as [`stackledger map`](map.md) writes them, the skill set's lines (see [Skills](#skills)), one line with the site's folder and page count, and a reminder that the site shows everything and must be served only behind a sign-in for people who may see it all. **What it writes.** Only inside `--out`. Astro runs from a copy of the site project in a staging folder `--out/.stackledger-tmp-*`, with every cache there too; nothing is written to the catalogue, the installed package, the system temporary folder or your home folder, and there is no telemetry. The build connects to no host; Astro's Fonts API opens a server during the build, which stackledger binds to loopback (127.0.0.1). You can check it with the Node.js permission model (Node 22.13 or later): @@ -39,7 +37,7 @@ Create `/path/to/out` first and give real paths (without symbolic links): the bu From Node 25 (not 22 or 24), the permission model also restricts the network, so add `--allow-net` for that server. It allows every connection, so it no longer checks the network claim; stackledger's own tests add a trap that refuses any host other than loopback and reports any server bound elsewhere (`test/helpers/net-trap.mjs`). -**Atomic replace.** Both sites are fully built in the staging folder before anything published changes. Then each entry (`staff`, `full`, `_headers`, `robots.txt`, `_redirects`, `.stackledger-build`) is swapped by renames: the previous entry moves into the staging folder's `old/`, created just before the first rename, and the new one moves into place. A personal build has no new `staff`: it writes an empty `full-only` file in the staging folder, and an earlier `staff` only moves into `old/`. The rename of the marker is the commit point. A failure before it undoes every rename, so the previous build stays as it was. After the commit the replaced entries and the staging folder are removed; a failure there is only a warning. +**Atomic replace.** The site is fully built in the staging folder before anything published changes. The staging folder holds `site/` (every entry of the new site, `_headers`, `robots.txt` and `_redirects` included), `root/.stackledger-build` (the new marker) and `entries`, a file with one entry name per line. Then each name, in sorted order, is swapped by renames: the previous entry of that name in `--out` moves into the staging folder's `old/`, created just before the first rename, and the new one moves into place; the names are those of the new site and of the previous build, so a folder the new build no longer has (`full/` and `staff/` of the two-site layout) only moves into `old/`. The marker comes last, and its rename is the commit point. A failure before it undoes every rename, so the previous build stays as it was. After the commit the replaced entries and the staging folder are removed; a failure there is only a warning. **Interrupted publication.** A staging folder without `old/` never touched a published entry (a build that crashed or failed before publishing): the next build removes it. A staging folder with `old/` may hold the only copy of the previous build, after a failed undo (for example a folder made read-only during the build) or a process killed during publication. stackledger never moves those entries back by itself: while such a folder exists, every build exits 1, names it and changes nothing, until you restore by hand as described below. Automatic recovery was tried and dropped, because trusting what a staging folder says about itself could move or delete the published site. @@ -47,7 +45,7 @@ From Node 25 (not 22 or 24), the permission model also restricts the network, so ### Skills -With a skill set, both sites get the Skills pages ([docs/skills.md](skills.md#skills-on-the-site)). The folders in use are the `--skills` folders, as given, when there is at least one; otherwise `spec.skills.folders` of a `Settings` without errors, each resolved from the catalogue folder; otherwise there is no skill set. The set is read as `stackledger skills validate` reads it. +With a skill set, the site gets the Skills pages ([docs/skills.md](skills.md#skills-on-the-site)). The folders in use are the `--skills` folders, as given, when there is at least one; otherwise `spec.skills.folders` of a `Settings` without errors, each resolved from the catalogue folder; otherwise there is no skill set. The set is read as `stackledger skills validate` reads it. | Exit | When | | --- | --- | @@ -64,39 +62,30 @@ The report adds, after the map's lines: `Skills: <n> skills, <n> playbooks, <n> When a build says a staging folder `<out>/.stackledger-tmp-…` was kept, or refuses an output folder because of one, put the output folder back by hand. Nothing else runs meanwhile: each build refuses that output folder and changes nothing. Below, `<out>` is the output folder and `<staging>` the staging folder the message names. 1. Look for `<staging>/root/.stackledger-build`. If it is **not** there, the publication had reached its commit point: `<out>` already holds the new build, and `<staging>/old/` only the build it replaced. Go to step 4. -2. Otherwise the publication stopped before its commit point. For each entry below whose new version is **no longer** in the staging folder, the entry of that name in `<out>` belongs to the failed build: delete it. - - | Entry in `<out>` | Its new version in the staging folder | - | --- | --- | - | `staff` | `<staging>/site-staff` | - | `full` | `<staging>/site-full` | - | `_headers` | `<staging>/root/_headers` | - | `robots.txt` | `<staging>/root/robots.txt` | - | `_redirects` | `<staging>/root/_redirects` | - - When `<staging>/full-only` exists, the failed build was a personal one and never had a staff site: skip the `staff` row, and keep any `staff` in `<out>`. - -3. Move every entry of `<staging>/old/` (`ls -A` shows `.stackledger-build` too) back into `<out>`, keeping its name, for example `mv "<staging>/old/full" "<out>/full"`. +2. Otherwise the publication stopped before its commit point. Read the names in `<staging>/entries`, one per line. For each name whose new version is **no longer** in `<staging>/site/` (it was moved into `<out>`), the entry of that name in `<out>` belongs to the failed build: delete it. +3. Move every entry of `<staging>/old/` (`ls -A` shows `.stackledger-build` too) back into `<out>`, keeping its name, for example `mv "<staging>/old/index.html" "<out>/index.html"`. 4. Delete the staging folder: `rm -rf "<staging>"` (it removes symbolic links inside without following them). 5. Run the build again. +A staging folder kept by 0.10.1 or earlier has no `entries` file: it holds `site-full/`, `site-staff/`, `root/_headers`, `root/robots.txt`, `root/_redirects` and maybe `full-only`. For it, delete from `<out>` the entries that came from the failed build (`full`, `staff`, `_headers`, `robots.txt`, `_redirects`) unless their new version is still in `<staging>/` as named above, then do steps 3 to 5. + After step 3, `<out>` holds the previous build byte for byte; the build tests follow these steps to prove it (`test/manual-restore.ts`). ## Pages -Each site has the same pages, filled from its own view; the `full` site also has the Reports page and the calendar file. The site title in the header (`spec.site.title`, default `stackledger`) opens the home page. The header links two divisions: **Software** (the pages below) and, with a skill set, **Skills** ([its pages](skills.md#what-the-site-shows), the same in both sites). Each division has its own menu under the header: Map, List, Journeys and Reports for Software; List, Map and Rules for Skills. +The site has these pages, every field of the catalogue shown, with the Reports page and the calendar file always there. The site title in the header (`spec.site.title`, default `stackledger`) opens the home page. The header links two divisions: **Software** (the pages below) and, with a skill set, **Skills** ([its pages](skills.md#what-the-site-shows)). Each division has its own menu under the header: Map, List, Journeys and Reports for Software; List, Map and Rules for Skills. | Page | Path | Shows | | --- | --- | --- | -| Home | `/` | A banner with the site title and `spec.site.home.text` (default "Your software and skills, mapped."); a Software card with the view's numbers of components, licences and journeys and links to Map, List, Journeys and, in `full`, Reports; with a skill set, a Skills card with its counts and links; then, when `spec.site.home.links` is set, **Links**: the links with `icon` as a row of icons (no title text, no description), then the others as a list (title, description, URL), each group in the order given; every link opens in a new tab, and says so to screen readers (see the security rules below). The home has no sub-menu. Up to 0.3.0 the map was at `/`. | +| Home | `/` | A banner with the site title and `spec.site.home.text` (default "Your software and skills, mapped."); a Software card with the numbers of components, licences and journeys and links to Map, List, Journeys and Reports; with a skill set, a Skills card with its counts and links; then, when `spec.site.home.links` is set, **Links**: the links with `icon` as a row of icons (no title text, no description), then the others as a list (title, description, URL), each group in the order given; every link opens in a new tab, and says so to screen readers (see the security rules below). The home has no sub-menu. Up to 0.3.0 the map was at `/`. | | Map | `/map/` | The metro map in the page's theme, over the catalogue's `spec.map.backdrop` ([backdrop](map.md#backdrop); the skills map stays flat; over a city, the line "Map data © OpenStreetMap contributors" right under the frame, linking to the OpenStreetMap copyright page in a new tab, in the backdrop credit colour and at least 12 pixels high), never larger than drawn (one map unit per pixel; smaller when the page is narrower), in a frame as wide as the map and centred, with zoom in, zoom out, reset and drag to pan; a zone filter; the lines as buttons under the map (choose one to dim the others, choose it again to restore); the map symbols. Each station opens its item page by click, or by focus and Enter. | | Software list | `/software/` | Every component and licence in one table: name, kind, type, lifecycle or status, owner and zone, sorted by reference. Search (any shown cell, ignoring case) and filters work on the table itself. | -| Component | `/software/<name>/` | Title, name, description, type, lifecycle, owner, zone and tags; its licences with the licence fields of the view; the journeys that stop at it; a neighbourhood diagram (what it depends on, what depends on it) with the same items as text links; the impact of removing it; references that match nothing. | -| Licence | `/licences/<name>/` | Title, name, owner and the licence fields of the view; the components that use it; the impact of removing it. | +| Component | `/software/<name>/` | Title, name, description, type, lifecycle, owner, zone and tags; its licences with their licence fields; the journeys that stop at it; a neighbourhood diagram (what it depends on, what depends on it) with the same items as text links; the impact of removing it; references that match nothing. | +| Licence | `/licences/<name>/` | Title, name, owner and the licence fields; the components that use it; the impact of removing it. | | Journeys | `/journeys/` | Every drawn line in line order, with badge, title and number of stops. | | Journey | `/journeys/<name>/` | A strip diagram of the line's stops in order, with the badges of other lines at interchanges, and the same stops and lines as text links. | -| Reports (`full` only) | `/reports/` | Renewals in the next 90 days, overdue renewals and unknown dates; recurring cost per month and per year for each currency, with the number of incomplete licences; the same totals by owner, by payer and by zone; one-off costs, planned purchases and incomplete licences; a link to `renewals.ics`. Each licence links to its page. The rules are in [docs/reports.md](reports.md). | -| Calendar (`full` only) | `/renewals.ics` | The renewals of the Reports page as an iCalendar file to download and import ([docs/reports.md](reports.md#the-calendar-file)). | +| Reports | `/reports/` | Renewals in the next 90 days, overdue renewals and unknown dates; recurring cost per month and per year for each currency, with the number of incomplete licences; the same totals by owner, by payer and by zone; one-off costs, planned purchases and incomplete licences; a link to `renewals.ics`. Each licence links to its page. The rules are in [docs/reports.md](reports.md). | +| Calendar | `/renewals.ics` | The renewals of the Reports page as an iCalendar file to download and import ([docs/reports.md](reports.md#the-calendar-file)). | `<name>` is the item's `metadata.name` in lower case. The diagrams are SVG drawn by stackledger itself, in the map's style. Owners show by name when the catalogue has a `Group` or `User` document for them (its `metadata.title`, else `spec.profile.displayName`, else its name); otherwise the reference, such as `group:northwind`, is shown. @@ -104,11 +93,11 @@ Without JavaScript every page still works as a document: the whole map, both leg ### Look and settings -The look follows brunosouzas.com (based on the Astroplate theme, MIT). Its palette and type scale come from the `site` tokens of `@brunosouzas/signwright`: the build copies the package's `tokens.css` into each site, so no stylesheet is fetched. The accent, which is also the focus colour, is stackledger's own brand colour in the package (`--ds-brand-<theme>-stackledger-accent`: `#3B5BDB` light, `#7D8CFF` dark); `spec.site.colors.accent` overrides the light one only. Cards, buttons, line chips and tag chips have the identity's ink frame: a 3px outline, ink (`#121212`) in light and the dark surface's muted colour (`#ADA79D`) in dark, with no shadow and no rim (the design system's shadow and rim width are 0). The text on a primary-coloured button is the page's body colour. +The look follows brunosouzas.com (based on the Astroplate theme, MIT). Its palette and type scale come from the `site` tokens of `@brunosouzas/signwright`: the build copies the package's `tokens.css` into the site, so no stylesheet is fetched. The accent, which is also the focus colour, is stackledger's own brand colour in the package (`--ds-brand-<theme>-stackledger-accent`: `#3B5BDB` light, `#7D8CFF` dark); `spec.site.colors.accent` overrides the light one only. Cards, buttons, line chips and tag chips have the identity's ink frame: a 3px outline, ink (`#121212`) in light and the dark surface's muted colour (`#ADA79D`) in dark, with no shadow and no rim (the design system's shadow and rim width are 0). The text on a primary-coloured button is the page's body colour. **Fonts.** Source Sans 3 for text, labels, the map and the diagrams, Source Serif 4 for headings and the site title, Source Code Pro for code, as on brunosouzas.com. They are delivered by Astro's Fonts API with its local provider, which reads the `@fontsource/source-sans-3`, `source-serif-4` and `source-code-pro` files (SIL Open Font License 1.1) shipped in the package, so the build makes no network call. The Fonts API names each family `<name>-<hash>` and defines `--font-primary`, `--font-secondary` and `--font-mono`; the site's CSS reads only those. It writes its CSS in inline `<style>` elements; the build moves that CSS, and only that (its `:root` font variables and `@font-face` rules), into one file `_astro/fonts.css`, which every page links where the first element was, so the pages keep the fixed policy below with no inline style. Any other `<style>`, font CSS that differs between two pages, a page without it or a missing font file fails the build before anything is published. Only Source Sans 3 400 and Source Serif 4 700 are preloaded; the other faces load when a page uses them (about 73 KB of fonts on the home, up to about 103 KB on the map page). The map and the diagrams name the design system's plain family (`'Source Sans 3'`) in their SVG; a site rule points them at the shipped face, while `stackledger map` and the README images keep the plain name. -**Marks and art.** The header's site title is the wordmark: Source Serif 4, italic, 700. The favicon is the family mark of `@brunosouzas/signwright` (`scripts/favicon.json`, `brand: stackledger`): a cream tile with stackledger's lowercase blue `s` and the parent's orange moon, the same in both themes. The mark beside the site title in the header is that same file, decorative (empty `alt`). The ledger page (`ledgerMark`) stays only in the home banner and the maps. The footer, after the view and the stackledger version, shows the parent brand's endorsement: the package's `symbol` (`symbol-light.svg` or `symbol-dark.svg`, by theme, decorative) and "by Bruno Souza", not a link. Below its title and text, the home shows the package's banner, "From the ledger to the map": stackledger's mark on the left, three of its rows leaving it as orange, blue and ink metro lines that cross at an interchange and run to Sinal at the end of the line, on the cream page, with no words and no motion, the same in both themes (`site/public/home-banner.svg`). A home link with `icon` is the package's link icon alone (`link-icons/<icon>-light.svg` or `-dark.svg`, by theme), 2rem (32 pixels on wide pages, about 26 under 768 pixels, where the root text is smaller), in a row of separate anchors before the other links; its title is the anchor's accessible name, not shown as text. These images are static files in `site/public/`, written by `scripts/site-art.mjs` from the package and checked by tests against it; none holds a `style` element. The map and the diagrams use the style of the site's illustrations (ink outlines and casings, see [the map](map.md#routes-and-themes)). A theme switch in the header follows the system's light or dark setting until the reader chooses, then remembers the choice in the browser for every page of that site; it shows the package's sun and moon icons. The zoom buttons of the maps and the renewal calendar button of the Reports page start with the package's interface icons (`uiIcon`), inlined in the page so they take the button's text colour, also on hover. `spec.site` in the `Settings` document sets the site title and up to four light-theme colours; see [the catalogue format](catalogue-format.md#settings-and-views). +**Marks and art.** The header's site title is the wordmark: Source Serif 4, italic, 700. The favicon is the family mark of `@brunosouzas/signwright` (`scripts/favicon.json`, `brand: stackledger`): a cream tile with stackledger's lowercase blue `s` and the parent's orange moon, the same in both themes. The mark beside the site title in the header is that same file, decorative (empty `alt`). The ledger page (`ledgerMark`) stays only in the home banner and the maps. The footer, after the stackledger version, shows the parent brand's endorsement: the package's `symbol` (`symbol-light.svg` or `symbol-dark.svg`, by theme, decorative) and "by Bruno Souza", not a link. Below its title and text, the home shows the package's banner, "From the ledger to the map": stackledger's mark on the left, three of its rows leaving it as orange, blue and ink metro lines that cross at an interchange and run to Sinal at the end of the line, on the cream page, with no words and no motion, the same in both themes (`site/public/home-banner.svg`). A home link with `icon` is the package's link icon alone (`link-icons/<icon>-light.svg` or `-dark.svg`, by theme), 2rem (32 pixels on wide pages, about 26 under 768 pixels, where the root text is smaller), in a row of separate anchors before the other links; its title is the anchor's accessible name, not shown as text. These images are static files in `site/public/`, written by `scripts/site-art.mjs` from the package and checked by tests against it; none holds a `style` element. The map and the diagrams use the style of the site's illustrations (ink outlines and casings, see [the map](map.md#routes-and-themes)). A theme switch in the header follows the system's light or dark setting until the reader chooses, then remembers the choice in the browser for every page of that site; it shows the package's sun and moon icons. The zoom buttons of the maps and the renewal calendar button of the Reports page start with the package's interface icons (`uiIcon`), inlined in the page so they take the button's text colour, also on hover. `spec.site` in the `Settings` document sets the site title and up to four light-theme colours; see [the catalogue format](catalogue-format.md#settings-and-views). **Known limitation:** a remembered theme is applied by a script file after the page starts to load (the policy forbids inline scripts), so a page can show the system theme for a moment before switching. @@ -116,31 +105,24 @@ The look follows brunosouzas.com (based on the Astroplate theme, MIT). Its palet - One fixed Content Security Policy on every page, in a `meta` element and in `_headers`: `default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'` (plus `frame-ancestors 'none'` in `_headers`). Pages have no inline script or style, no `style` attribute and no event-handler attribute. No page links another site except the home's **Links** and, over a city backdrop, the map page's OpenStreetMap credit (`https://www.openstreetmap.org/copyright`): the home links' URLs are checked by `stackledger validate` (`http://` or `https://`, a host, no user name or password), each such anchor opens in a new tab (`target="_blank"`) with `rel="noopener noreferrer"`, so the other page gets no handle on the site's tab, and its accessible name ends with " (opens in a new tab)" (in `aria-label` for an icon link, in visually hidden text otherwise, so nothing changes on screen; WCAG technique G201); every link inside the site opens in the same tab; `Referrer-Policy: no-referrer` keeps the site's address out of the other site's logs. The build fails if such a URL shows up anywhere else. - Every URL is relative and stays inside its site, so the same files work under any path prefix. No font, script or image comes from another site; there are no analytics. -- `noindex, nofollow` on every page, `X-Robots-Tag` in `_headers`, and a `robots.txt` that disallows everything, at the root of the output and in each site. -- The `staff` site is built first, from the staff view only: no file of it contains a hidden field's value. It has no Reports page, no calendar file and no link to either. +- `noindex, nofollow` on every page, `X-Robots-Tag` in `_headers`, and a `robots.txt` that disallows everything, at the root of the output. +- The site shows every field, so the access rule is the only protection: it is served only behind a sign-in for people who may see everything ([hosting](hosting.md)). The `staff` view stays in the code, deprecated and not built into any page. - Catalogue text is escaped everywhere; titles such as `<img onerror=…>` show as text. - The build writes only inside the output folder and never renames or removes through a symbolic link: entries are looked at with `lstat`, and a staging folder is removed only when it is a real folder. Node.js cannot hold a folder open, so the build works with paths: it records the output folder's real path and identity (device and inode) once the folder is checked, compares them again immediately before it creates the staging folder, before each rename (an undo's included) and before each removal, and stops with exit 1, changing nothing more, when they differ. **Trust assumption:** no other process renames or replaces the output folder or its parents during a build. A swap between a check and the change right after it, or while the sites are being prepared in the staging folder, is outside what the build can detect; this is the same trust you give any program you run as yourself. ## Publishing the output -The output folder holds more than the two sites while a build runs: the build prepares everything in a staging folder `.stackledger-tmp-*` inside it, and that staging folder holds `full` view files outside the protected `/full/` path. +The output folder holds more than the site while a build runs: the build prepares everything in a staging folder `.stackledger-tmp-*` inside it, and that staging folder holds a copy of the whole site, unfinished. - Never serve the output folder while a build runs, and never serve the output folder itself. -- Publish only these entries of the output folder: `full/`, `staff/` (not in the personal mode), `_headers`, `robots.txt` and `_redirects`, and only after the command exits with code 0. For example, copy them into a clean folder and deploy that, or let a CI job build into a fresh folder and upload only those entries. - -### One host, two audiences +- Publish only the site's files, and only after the command exits with code 0: every entry of the output folder except the `.stackledger-build` marker and any `.stackledger-tmp-*` folder, that is the pages, `renewals.ics`, `_headers`, `robots.txt` and `_redirects`. For example, copy them into a clean folder and deploy that, or let a CI job build into a fresh folder and upload everything in it but the marker. -In the corporate mode, serve both sites from one host, with a stricter rule on `/full/`: - -| Path | Who | Site | -| --- | --- | --- | -| `/full/*` | Owners and finance | the `full` view: costs, renewals, payers, seats, password-manager references, notes | -| `/staff/*` (and the rest of the host) | Everyone in the company | the `staff` view | +### One host, one audience -In the personal mode there is only `/full/*`, for you. Without the proxy, anyone with the address can read the catalogue. The host has no page at `/`: Cloudflare Pages and Netlify follow `_redirects` to `/staff/` (or `/full/`); on another host, add the same redirect there. +Serve the site from one host, behind a sign-in that lets in only the people who may see everything, on the whole address: whoever passes sees all of it. There is no stricter path and no second audience. Without the proxy, anyone with the address can read the catalogue. The old two-site addresses redirect: `/full` and `/full/*` go to the same path at the root with 301, through `_redirects` on Cloudflare Pages and Netlify; on another host, add the same redirect there (the Caddy example does). -**Trailing slash.** Every page is a folder with an `index.html`, and its links are relative, so a page must be served at its address with a trailing slash. The host must redirect a folder address without it (`/staff/software/slack`) to the address with it (`/staff/software/slack/`), and serve `index.html` for a folder. Cloudflare Pages, Netlify and most static hosts do both by default; for nginx, `try_files $uri $uri/ =404;` does. +**Trailing slash.** Every page is a folder with an `index.html`, and its links are relative, so a page must be served at its address with a trailing slash. The host must redirect a folder address without it (`/software/slack`) to the address with it (`/software/slack/`), and serve `index.html` for a folder. Cloudflare Pages, Netlify and most static hosts do both by default; for nginx, `try_files $uri $uri/ =404;` does. -**Calendar file.** Serve `renewals.ics` with the type `text/calendar` (check how your host types `.ics` files). It is for download and import only: calendar services fetch a subscribed feed from their own servers, without the reader's sign-in, so the proxy in front of `/full/` refuses them and a subscription to it cannot work. Do not publish the file outside the proxy to make it subscribable; it holds costs. +**Calendar file.** Serve `renewals.ics` with the type `text/calendar` (check how your host types `.ics` files). It is for download and import only: calendar services fetch a subscribed feed from their own servers, without the reader's sign-in, so the proxy in front of the site refuses them and a subscription to it cannot work. Do not publish the file outside the proxy to make it subscribable; it holds costs. **Hosting recipes.** [docs/hosting.md](hosting.md) covers Cloudflare Pages with Access on every project address, and a generic Caddy proxy in front of oauth2-proxy. Set up access control before the first deployment. The [catalogue repository template](../examples/catalogue-repository/) builds and deploys only the publishable entries. diff --git a/docs/skills.md b/docs/skills.md index 826611f6..4cb4ef15 100644 --- a/docs/skills.md +++ b/docs/skills.md @@ -361,5 +361,5 @@ The catalogue pipeline needs the skills too. Check out the skills repository fro - The site changes when the skills change: rebuild on a schedule, or trigger the catalogue pipeline from the skills repository's main branch. - Any Git host works the same way: two checkouts, then one command. - A map file kept in the catalogue repository is read from the catalogue checkout (`spec.skills.map`); no extra step. -- No software catalogue yet? A catalogue folder with only `stackledger.yaml` (`spec.sites: [full]` and `spec.skills.folders`) builds a site whose Software map is empty and whose Skills section is complete. +- No software catalogue yet? A catalogue folder with only `stackledger.yaml` (`spec.skills.folders`) builds a site whose Software map is empty and whose Skills section is complete. diff --git a/examples/catalogue-repository/.github/workflows/stackledger.yml b/examples/catalogue-repository/.github/workflows/stackledger.yml index 30c3302d..403f6710 100644 --- a/examples/catalogue-repository/.github/workflows/stackledger.yml +++ b/examples/catalogue-repository/.github/workflows/stackledger.yml @@ -1,14 +1,13 @@ name: stackledger -# Checks this catalogue and publishes its stackledger sites to Cloudflare Pages: full/ and staff/ -# (the corporate mode, the default), or full/ only with `sites: [full]` in catalog/stackledger.yaml -# (the personal mode). +# Checks this catalogue and publishes its stackledger site to Cloudflare Pages: one private site at +# the root, which shows everything, so Cloudflare Access must cover the whole address. # Setup (secrets, variable, Cloudflare Access before the first deploy, rollback): README.md. # # - site: on every run. Scans the repository and its history for secrets (gitleaks), validates the -# catalogue in catalog/ (errors fail, warnings do not), builds the sites dated today in UTC into -# a folder outside the repository, and hands on only full/, staff/ (corporate mode), _headers, -# robots.txt and _redirects. +# catalogue in catalog/ (errors fail, warnings do not), builds the site dated today in UTC into +# a folder outside the repository, and hands on the site's files (every entry of the build +# except its marker file, .stackledger-build). # - deploy: only for main, never for a pull request, on a fresh runner with no checkout. Wrangler is # installed without its install scripts before any secret exists, and runs from a folder holding # only the site, so nothing else of this repository can be uploaded. @@ -67,18 +66,19 @@ jobs: npx --yes "$STACKLEDGER" validate catalog - name: Build date (UTC, computed once) run: echo "BUILD_DATE=$(date -u +%F)" >> "$GITHUB_ENV" - - name: Build the sites + - name: Build the site run: npx --yes "$STACKLEDGER" build catalog --out "$RUNNER_TEMP/site" --date "$BUILD_DATE" - name: Keep only what is published run: | - mkdir -p "$RUNNER_TEMP/handoff/site" - for entry in full _headers robots.txt _redirects; do - cp -R "$RUNNER_TEMP/site/$entry" "$RUNNER_TEMP/handoff/site/" - done - # staff/ exists only in the corporate mode. - if [ -d "$RUNNER_TEMP/site/staff" ]; then - cp -R "$RUNNER_TEMP/site/staff" "$RUNNER_TEMP/handoff/site/" + # Hand on the whole build folder but its marker file. A staging folder the build could not + # remove (a warning, exit 0) would hold the site's working copy: stop instead of uploading it. + if compgen -G "$RUNNER_TEMP/site/.stackledger-tmp-*" > /dev/null; then + echo "The build left a staging folder in the build folder; not publishing it" >&2 + exit 1 fi + mkdir -p "$RUNNER_TEMP/handoff/site" + cp -R "$RUNNER_TEMP/site/." "$RUNNER_TEMP/handoff/site/" + rm "$RUNNER_TEMP/handoff/site/.stackledger-build" echo "$BUILD_DATE" > "$RUNNER_TEMP/handoff/build-date" - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: diff --git a/examples/catalogue-repository/README.md b/examples/catalogue-repository/README.md index 146e0d33..6b5992ee 100644 --- a/examples/catalogue-repository/README.md +++ b/examples/catalogue-repository/README.md @@ -1,6 +1,6 @@ # Catalogue repository template -A starting point for a Git repository that holds your [stackledger](https://github.com/brunosouzas/stackledger) catalogue and publishes its sites with GitHub Actions to Cloudflare Pages, behind Cloudflare Access. +A starting point for a Git repository that holds your [stackledger](https://github.com/brunosouzas/stackledger) catalogue and publishes its site with GitHub Actions to Cloudflare Pages, behind Cloudflare Access. Copy everything in this folder, including `.github/` and `.gitignore`, to the root of a new **private** repository. Read access to the repository means reading the whole catalogue, costs included. @@ -12,27 +12,13 @@ README.md this file; replace it with your own The catalogue lives in `catalog/` so that stackledger never reads the workflow's own YAML (0.3.0 and earlier read hidden folders such as `.github/`; this template pins 0.8.0 (`@brunosouzas/stackledger`), which skips them, so the folder now only keeps the catalogue apart from the repository files). `catalog/catalog-info.yaml` holds one fictitious component, so the copy validates and builds as it is; replace it with yours ([catalogue format](https://github.com/brunosouzas/stackledger/blob/main/docs/catalogue-format.md)). -## Personal or corporate +## One private site -Choose one before the first deploy. +stackledger builds one site at the root of the address, with everything in it: costs, renewals, payers and contract details ([ADR 13](https://github.com/brunosouzas/stackledger/blob/main/docs/adr/0013-one-private-site-at-the-root.md)). Whoever can open the address sees all of it, so you need **one** Cloudflare Access application, on the whole address, that lets in only the people who may see everything. The address `/` is the home page. Addresses of the older two-site layout (`/full/...`) redirect to the same path at the root, `renewals.ics` included. -- **Personal**: you are the only reader. stackledger builds one site, `full`, with everything in it, costs included. Add `catalog/stackledger.yaml`: +Coming from the two-site layout, change Cloudflare Access first: replace the two applications (`/full/*` and the rest) by one on the whole address, and allow only the people who were on `/full/*`. Then deploy. - ```yaml - apiVersion: stackledger/v1alpha1 - kind: Settings - metadata: - name: settings - spec: - sites: [full] - ``` - - You need one Cloudflare Access application that lets in only you. The address `/` takes you to `/full/`. -> **Planned:** [ADR 13](../../docs/adr/0013-one-private-site-at-the-root.md) replaces the two sites with one at the root. Before that change, the root's Access application must allow only people who may see everything. - -- **Corporate** (the default, when `sites` is not set): a company where only some people may see costs. stackledger builds two sites: `full` for finance and `staff`, without costs and contract details, for everyone else. You need two Access applications: finance on `/full/*`, staff on the rest. The address `/` takes people to `/staff/`. - -Both modes and the `_redirects` file need stackledger 0.1.0 or later, the version the workflow pins. You can switch later by changing `sites`; the next deploy publishes the new set of sites. Change Cloudflare Access first, so no site is ever open to the wrong people. +The workflow pins the stackledger release it runs (`STACKLEDGER`). The one-site layout comes with the first release after 0.10.1; with an older pin the build still writes `full/` and `staff/`, and the workflow would publish both, so move the pin to that release in the same pull request that adopts this template. ## What the workflow does @@ -47,8 +33,8 @@ The `site` job: 1. scans the repository and its whole history for secrets with [gitleaks](https://github.com/gitleaks/gitleaks), a pinned release checked against its SHA-256; a finding fails the job; 2. runs `stackledger validate catalog`: an error fails the job before the build, a warning does not; -3. builds the sites dated today in UTC, into a folder outside the repository; -4. hands on only `full/`, `staff/` (corporate mode only), `_headers`, `robots.txt` and `_redirects` (it sends `/` to the right site), with the build date. +3. builds the site dated today in UTC, into a folder outside the repository; +4. hands on the site: every entry of the build folder except its marker file `.stackledger-build` (the job stops if a `.stackledger-tmp-*` staging folder is left there) (the pages, `renewals.ics`, `_headers`, `robots.txt` and `_redirects`), with the build date. The `deploy` job runs on a fresh runner without a checkout. It installs wrangler with `--ignore-scripts` before any secret is present, then runs it from a folder that holds only the site. Each deployment is labelled with the commit and the build date, for example `stackledger 2026-10-21 <commit>`. @@ -56,9 +42,9 @@ A re-run on the same UTC day deploys the same files. ## Setup -Do these steps in this order, so the sites are never public. +Do these steps in this order, so the site is never public. -1. **Protect the sites first.** Create the Cloudflare Pages project empty and set up Cloudflare Access for it, as [docs/hosting.md](https://github.com/brunosouzas/stackledger/blob/main/docs/hosting.md) describes for your mode, on every address of the project: one Access application for you (personal), or two, one for `/full/*` and one for the rest (corporate). Do this **before** the first deploy. +1. **Protect the site first.** Create the Cloudflare Pages project empty and set up Cloudflare Access for it, as [docs/hosting.md](https://github.com/brunosouzas/stackledger/blob/main/docs/hosting.md) describes, on every address of the project: one Access application on the whole address, with a policy that allows only the people who may see everything. Do this **before** the first deploy. 2. **API token.** In the Cloudflare dashboard, My Profile → API Tokens → Create Token → Custom token, with the single permission Account → Cloudflare Pages → Edit, for one account only ([Cloudflare docs](https://developers.cloudflare.com/fundamentals/api/get-started/create-token/)). 3. **Repository secrets and variable.** In the repository settings, Secrets and variables → Actions: - secret `CLOUDFLARE_API_TOKEN`: the token from step 2; @@ -66,7 +52,7 @@ Do these steps in this order, so the sites are never public. - variable `PAGES_PROJECT`: the name of the Pages project from step 1. Only the deploy step reads them. Pull requests never deploy. -4. **Push to `main`.** The first run deploys. Then check the sites as `docs/hosting.md` says: anonymous requests must be sent to the sign-in page, and, in the corporate mode, a staff identity must be refused on `/full/`. +4. **Push to `main`.** The first run deploys. Then check the site as `docs/hosting.md` says: anonymous requests, to `/` and to `/renewals.ics`, must be sent to the sign-in page. ## Versions diff --git a/examples/hosting/Caddyfile b/examples/hosting/Caddyfile index bba707da..5316c4e1 100644 --- a/examples/hosting/Caddyfile +++ b/examples/hosting/Caddyfile @@ -1,15 +1,16 @@ # stackledger behind Caddy and oauth2-proxy: a fictitious example (Northwind, example.org). # The recipe, with the oauth2-proxy flags, is in docs/hosting.md. # -# Every request is authenticated first, by oauth2-proxy at 127.0.0.1:4180. Only the groups that -# oauth2-proxy returns in X-Auth-Request-Groups count: -# /full/* finance -# every other staff or finance -# anything else 403 -# A request without a session is sent to the sign-in page. When oauth2-proxy cannot be reached, -# Caddy answers 502 and serves nothing (it fails closed). +# One site, one audience: every request is authenticated first, by oauth2-proxy at 127.0.0.1:4180. +# Only the group `readers` in X-Auth-Request-Groups counts: whoever is in it sees everything, so +# put in it only the people who may see costs and contracts. Anyone else gets 403. An address of +# the old two-site layout (/full, /full/...) redirects to the same path at the root, after the +# check, so a reader's old links and bookmarks keep working. A request without a session is sent +# to the sign-in page. When oauth2-proxy cannot be reached, Caddy answers 502 and serves nothing +# (it fails closed). # -# /srv/stackledger/publish holds only full/, staff/, _headers and robots.txt from stackledger build. +# /srv/stackledger/publish holds the site files from stackledger build (everything except the +# .stackledger-build marker): index.html, the page folders, renewals.ics, _headers and robots.txt. # Tested by test/integration/hosting-caddy.test.ts. catalogue.example.org { @@ -40,17 +41,13 @@ catalogue.example.org { } # oauth2-proxy sends the groups as a comma-separated list. - @full_refused { - path /full /full/* - not header_regexp X-Auth-Request-Groups (^|,)\s*finance\s*(,|$) - } - respond @full_refused 403 - - @refused not header_regexp X-Auth-Request-Groups (^|,)\s*(staff|finance)\s*(,|$) + @refused not header_regexp X-Auth-Request-Groups (^|,)\s*readers\s*(,|$) respond @refused 403 - # The host has no page at /. - redir / /staff/ 302 + # Old two-site addresses: /full and /full/<path> are now /<path>. A path that starts with a + # second slash does not match, so the target can never be //other-host. + @old path_regexp old ^/full(?:/([^/].*)?)?$ + redir @old /{re.old.1} 301 # The same headers stackledger writes into _headers, which Caddy does not read. header { diff --git a/examples/northwind/stackledger.yaml b/examples/northwind/stackledger.yaml index d0927613..b584b648 100644 --- a/examples/northwind/stackledger.yaml +++ b/examples/northwind/stackledger.yaml @@ -2,15 +2,4 @@ apiVersion: stackledger/v1alpha1 kind: Settings metadata: name: settings -spec: - views: - staff: - hide: - - cost - - currency - - cycle - - renewsOn - - paidBy - - seats - - vaultItem - - note +spec: {} diff --git a/openspec/changes/archive/2026-12-06-single-site/design.md b/openspec/changes/archive/2026-12-06-single-site/design.md new file mode 100644 index 00000000..5d1efa5f --- /dev/null +++ b/openspec/changes/archive/2026-12-06-single-site/design.md @@ -0,0 +1,9 @@ +# Design: one private site at the root + +No real choice between alternatives beyond what ADR 13 decided; these are the decisions the ADR left to this change. + +1. **`spec.sites`: accepted, checked, ignored, warned.** Removing the key from the schema would make an existing catalogue fail with an unknown-field error, a behaviour change by surprise. Keeping its checks and adding a warning tells the owner what happened and lets them delete it. `spec.views.staff.hide` likewise (the MCP and map staff views still read it). +2. **Old links: 301.** The move is permanent and the redirect rules are cheap. A browser that cached it keeps working because `/full/*` never returns. +3. **Publication by entry set.** The staged site is the `site/` folder in staging (the top-level files and folders Astro wrote, plus `_headers`, `robots.txt` and `_redirects`); the marker stays in `root/` and is renamed last (the commit point). The old fixed list of six entries becomes the entries of the output folder at publication time plus the staged ones; every existing one other than the marker and staging folders moves to `old/`. The manual restore of `docs/site.md` is reworded to the same steps (delete what is no longer in the staging `site/` folder and has the name of a staged entry; move `old/` back). +4. **`--view staff` stays.** ADR 13 keeps it while the view exists in the code; only a deprecation line is added. The `full` view stays the default. +5. **Caddy group `readers`.** One policy, one group. The old `staff` and `finance` groups no longer admit anyone; the docs say to rename or add the group in the provider. diff --git a/openspec/changes/archive/2026-12-06-single-site/proposal.md b/openspec/changes/archive/2026-12-06-single-site/proposal.md new file mode 100644 index 00000000..dea59f33 --- /dev/null +++ b/openspec/changes/archive/2026-12-06-single-site/proposal.md @@ -0,0 +1,54 @@ +# One private site at the root (SW-345) + +## Problem + +`stackledger build` writes two sites, `full/` and `staff/`, behind two Access policies and two path prefixes (ADR 7). The catalogue is read by its owner, who builds only `full`; the second site, the two modes and the `/full/` and `/staff/` prefixes cost setup and documentation with no reader. [ADR 13](../../../docs/adr/0013-one-private-site-at-the-root.md), accepted on 2026-12-05, replaces them with one private site served at the root, where whoever can open it sees everything. + +## What changes + +- **One site at the root.** The build writes the home page `index.html`, the pages, the Reports page and `renewals.ics` at the top of `--out`, next to `_headers`, `robots.txt`, `_redirects` and the marker. There is no `full/` or `staff/` folder and no personal or corporate mode. The site is built from the `full` view; licences show every field. +- **Old links redirect.** `_redirects` holds `/full / 301` and `/full/* /:splat 301`, so `/full/map/` and `/full/renewals.ics` reach `/map/` and `/renewals.ics`. `/staff/` has no destination and no rule. The Caddy example redirects the same way after sign-in. +- **Publication replaces the whole folder.** The set of top-level entries now depends on the catalogue (pages, `skills/`, `reports/`), so every entry of a marked output folder other than the marker and staging folders belongs to the build and is replaced, `full/` and `staff/` of a two-site build included. The publishable entries are the folder's content except the marker and staging folders. +- **The staff view is deprecated, not removed.** It stays in the code for `stackledger mcp --view staff` and `stackledger map --view staff`; each prints one stderr line saying it is deprecated and unused by the site. No build writes it. +- **Settings are never silently ignored.** `spec.sites` (valid or not, checks unchanged) gets a warning when valid: it is ignored. `spec.views.staff.hide` gets a warning: the site shows every licence field. Warnings do not fail the build. The example catalogue's `stackledger.yaml` drops the hide list, which equalled the default. +- **The footer** drops the view name ("full view"). +- **Hosting.** One Access application on the whole address, anonymous 302 checks on `/`, `/map/`, `/renewals.ics`, an asset and `/full/`; Access must cover the root, and allow only people who may see everything, before the first deploy. The Caddy example has one group, `readers`. The catalogue repository template hands on the whole site and its README loses the two modes. +- **Release.** A breaking change (output paths, Caddy groups, ignored settings): PR title `feat!:`. Release-please reads it; the version is not set by hand. + +Out of scope: + +- the private `stackledger-catalog` repository and its pipeline (SW-350), marketplaces, journeys and named maps (SW-346 to SW-349), the brand mark (SW-304), the tenavu.com site; +- any sign-in code: Cloudflare Access signs people in, Google can be its identity provider (ADRs 5 and 6); +- removing the `staff` view from the code, the `Settings` hide list's schema or `--view` (deprecated here, removed by a later change); +- a redirect of `/staff/` links; +- the demo site, rebuilt by hand at the next release (`docs/demo.md`), and the published `docs/images`. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `build-command`: one site at the root; old-address redirects; replacement of every entry of a marked folder; modes removed. +- `site-security`: "One site from the full view" replaces "One view per site"; wording for one site. +- `hosting-recipes`: one group, redirects after sign-in. +- `catalogue-pipeline`: what is published. +- `catalogue`: deprecated site settings and hide list (warnings). +- `catalogue-views`: the staff view is deprecated. +- `mcp-server`: deprecation line. +- `catalogue-site`, `licence-reports`, `skills-site`: one site, footer, Reports always present. + +## Implicit requirements + +- Errors and invalid input: an invalid `spec.sites` stays an error; a catalogue with errors still builds. Exit codes are unchanged; a symbolic-link entry in a marked output folder is refused (exit 2) as before, for every entry now. +- Limits: `_redirects` has two rules, far below the host limits. Publication moves as many entries as the site has top-level entries (about a dozen). +- Repetition and idempotency: the build stays deterministic and a rebuild replaces the previous one completely; an old two-site folder is replaced in one build. +- Concurrency: n/a, one build at a time per process as before; publication keeps its identity checks and undo. +- Security: every rule of `docs/site.md` stays (fixed CSP, no third-party request, `noindex`, relative URLs, output checks, atomic publication). New risk, stated: whoever has access sees costs, renewal dates, payers, notes and password-manager item names, and in a corporate setup the old `staff` Access application would cover the root. The docs and the pipeline README say to fix Access before the first deploy and to check it with anonymous requests (302) and a refused sign-in as an identity that may not see everything. +- Logs and observability: the build report, the warnings and the deprecation lines above; no new telemetry. + +## Documentation + +`docs/site.md`, `docs/hosting.md`, `docs/how-it-works.md`, `docs/catalogue-format.md` (the `sites` and hide settings), `docs/mcp.md`, `docs/map.md`, `docs/reports.md`, `docs/architecture.md` (module map if it changes), `docs/roadmap.md` (row 1 delivered), `docs/demo.md`, `README.md`, `examples/catalogue-repository/` (workflow and README), `examples/hosting/Caddyfile`, `examples/northwind/stackledger.yaml`, and the Purpose lines of the capabilities above. ADR 13 is already merged; its consequence about the spec is answered by this change. Vault note after the merge. diff --git a/openspec/changes/archive/2026-12-06-single-site/specs/build-command/spec.md b/openspec/changes/archive/2026-12-06-single-site/specs/build-command/spec.md new file mode 100644 index 00000000..7a3fbb61 --- /dev/null +++ b/openspec/changes/archive/2026-12-06-single-site/specs/build-command/spec.md @@ -0,0 +1,211 @@ +## ADDED Requirements + +### Requirement: Build command +`stackledger build <folder> --out <dir> [--date YYYY-MM-DD] [--skills <folder>]...` SHALL build one site at the root of `<dir>`, with `index.html`, `_headers`, `robots.txt`, `_redirects` and the marker `.stackledger-build`, write no `full/` or `staff/` folder, and exit 0. `--date` sets the map date and the report date (default: the machine's local date, captured once); a date whose 90-day report window ends after `9999-12-30` is a usage error. A missing `<dir>` is created. + +#### Scenario: One site at the root +- **WHEN** the command runs as `stackledger build ./catalogue --out ./public` +- **THEN** `./public/index.html`, `./public/map/index.html`, `./public/reports/index.html` and `./public/renewals.ics` exist, `./public/full` and `./public/staff` do not, and the exit code is 0 + +#### Scenario: One site with skills +- **WHEN** the command runs as `stackledger build ./catalogue --out ./public --skills ./skills` +- **THEN** `./public/skills/index.html` exists and the exit code is 0 + +#### Scenario: The staff view is not built +- **WHEN** the catalogue's Settings have `spec.views.staff.hide: [vendor]` and `spec.sites: [full, staff]` +- **THEN** the site is the same as without those two settings, the licences show every field including the vendor, and no `staff` folder exists + +### Requirement: Replace the whole folder +Every entry of a marked output folder other than the marker and the staging folders belongs to the build: publication SHALL move it into the staging folder's `old/` and move the new build's entries into place, so nothing of an earlier build remains, the `full/` and `staff/` folders of a two-site build included. + +#### Scenario: A two-site build is replaced +- **WHEN** `--out` holds a marked build of an earlier version with `full/`, `staff/`, `_redirects` and the marker, and the command runs +- **THEN** the exit code is 0, `full` and `staff` are gone and the folder equals a build into an empty folder + +#### Scenario: A failed replacement keeps the two-site build +- **WHEN** the same build fails at any rename before the commit +- **THEN** the exit code is 1 and the two-site build, `full/` and `staff/` included, is unchanged byte for byte + +### Requirement: Old addresses redirect +`_redirects` SHALL hold exactly the lines `/full / 301` and `/full/* /:splat 301`, each followed by a newline (the Cloudflare Pages and Netlify format), so a link to the former `/full/` site, `renewals.ics` included, reaches the same path at the root. It SHALL hold no rule for `/` or `/staff/`: the former staff site has no destination. + +#### Scenario: Redirect file +- **WHEN** a build succeeds +- **THEN** `_redirects` in the output folder holds exactly `/full / 301`, a newline, `/full/* /:splat 301` and a newline + +#### Scenario: No rule for the staff site +- **WHEN** `_redirects` is read +- **THEN** no line starts with `/staff` and none starts with `/ ` + +## MODIFIED Requirements + +### Requirement: Safe output folder +After resolving symbolic links, the output folder SHALL be refused, with exit 2 and no change, when it is the catalogue folder, inside it, contains it, or is a non-empty folder without the marker `.stackledger-build`: a regular file with fixed content, no date or version. It SHALL also be refused when any entry of the folder, the marker and a `.stackledger-tmp-*` entry included, is a symbolic link, or a `.stackledger-tmp-*` entry is a file. + +#### Scenario: Output inside the catalogue +- **WHEN** `--out` is `./catalogue/site` +- **THEN** the exit code is 2 and nothing is written + +#### Scenario: Unrelated non-empty folder +- **WHEN** `--out` is a folder holding `notes.txt` and no marker +- **THEN** the exit code is 2 and `notes.txt` is untouched + +#### Scenario: Marker that is not a file +- **WHEN** `.stackledger-build` in `--out` is a folder, a symbolic link or has other content +- **THEN** the exit code is 2 and nothing changes + +#### Scenario: Linked published entry +- **WHEN** `map` in a marked `--out` is a symbolic link to another folder +- **THEN** the exit code is 2 and the link's target is untouched + +### Requirement: Atomic replace +The site and the root files SHALL be fully prepared in a staging folder `.stackledger-tmp-*` inside the output folder before anything published changes, then published by renames whose last one is the commit point. A failure before the commit SHALL restore every previous entry byte for byte and exit 1. After the commit, a failure to remove the staging folder is a warning, with exit 0. + +#### Scenario: Rebuild +- **WHEN** the command runs twice with the same `--out` +- **THEN** the second build replaces the first and no file of the first remains unless rebuilt + +#### Scenario: Failure leaves the old site +- **WHEN** a build fails, at any step before the commit, after an earlier successful build into the same `--out` +- **THEN** the earlier site and root files are unchanged, no `.stackledger-tmp-*` folder remains and the exit code is 1 + +### Requirement: Publishing the output +The output folder SHALL NOT be served while a build runs. After an exit code 0, only the content of the output folder other than the marker `.stackledger-build` and any `.stackledger-tmp-*` entry SHALL be published; `docs/site.md` SHALL say so, because a staging folder holds the build's working files. + +#### Scenario: Documented +- **WHEN** a reader opens `docs/site.md` +- **THEN** it says not to serve the output folder during a build and which entries to publish + +### Requirement: Build report +stderr SHALL show, in order: with a catalogue error or warning, one line with both counts and a hint to run `stackledger validate`; the map's suggestion, unrouted-hop and unused-layout lines as `stackledger map` writes them; the lines of "Skills build report"; one line for the site built with its page count; a last line saying the site shows everything and must be served only behind a sign-in for people who may see it all. A catalogue with errors SHALL still be built, with exit 0. + +#### Scenario: One error +- **WHEN** the catalogue has one error +- **THEN** the site is built, the exit code is 0 and stderr says there is 1 error + +#### Scenario: Proxy reminder +- **WHEN** a build succeeds +- **THEN** the last stderr line says the site shows everything and must be served only behind an identity-aware proxy for the people allowed to see all of it + +### Requirement: Deterministic build +The same catalogue, skill files, `--date` and stackledger version SHALL produce byte-identical files, whatever the order of files and documents in the catalogue folder, the order in which folders list their entries, and where the catalogue and skills folders are on disk, as long as the same documents and items are served. + +#### Scenario: Built twice +- **WHEN** the same catalogue is built twice with the same `--date` +- **THEN** every file of both builds is identical + +#### Scenario: Skills folder elsewhere +- **WHEN** the same catalogue and skill files are built from two different absolute paths, with the same `--date` +- **THEN** every file of both builds is identical + +### Requirement: Build time +The site for a catalogue of 300 items and 20 lines SHALL be built within 90 seconds. + +#### Scenario: Large catalogue +- **WHEN** a generated catalogue of 300 items and 20 lines is built +- **THEN** the command finishes within 90 seconds + +### Requirement: Writes +The build reads only the catalogue folder and the skill set's files. The build connects to no host; Astro's Fonts API opens a server during the build, which stackledger binds to loopback (127.0.0.1). It SHALL write only inside the output folder, with Astro's working copy, generated files and every cache (Astro's and Vite's `cacheDir`) under the staging folder, and SHALL NOT write in the catalogue or skills folders, the installed package, the system temporary directory or the user's home folder. + +#### Scenario: Sandboxed build +- **WHEN** the command runs with `--skills` under the Node.js permission model with read access to the catalogue folder, the skills folder and the package, write access only to `--out`, and `--allow-addons --allow-child-process --allow-worker`, with `--allow-net` where Node has it and a network trap preloaded that refuses any host other than loopback and reports every server the process opens +- **THEN** the site is built with its Skills pages, no connection to a host other than loopback is attempted, no server listens on an address other than loopback, and child processes, which the model does not restrict, are outside this check + +#### Scenario: Font server on loopback +- **WHEN** a build runs +- **THEN** every server the build opens listens on 127.0.0.1 and none remains open after the build + +### Requirement: Skill folders +The skill set SHALL be read as `stackledger skills validate` reads it, from the folders in use: the `--skills` folders, in the order given and used as received, when there is at least one; otherwise, when the Settings in use has no error, its `spec.skills.folders`, each resolved from the catalogue folder; otherwise there is no skill set and no Skills section. Only folders in use are checked. + +#### Scenario: Folders from the settings +- **WHEN** the catalogue `cat` has `spec.skills.folders: [../kit]` and the command has no `--skills` +- **THEN** the skill set is read from `cat/../kit` and the site has the Skills pages + +#### Scenario: The option replaces the settings +- **WHEN** the catalogue has `spec.skills.folders: [../missing]`, a folder that does not exist, and the command has `--skills team` +- **THEN** the skill set is read from `team` only and the exit code is 0 + +#### Scenario: Several option folders +- **WHEN** the command has `--skills team --skills vendor` +- **THEN** one skill set is read from both folders, `team` first + +#### Scenario: No skill set +- **WHEN** the catalogue has no `spec.skills` and the command has no `--skills` +- **THEN** no skill folder is read and no site has a Skills page + +### Requirement: Skills settings with problems +Without `--skills`, when the Settings in use has an error (as catalogue-views defines it) and any parsed document whose `kind` is `Settings`, ignoring case, has a `spec.skills` key, the command SHALL exit 1 before anything is written, naming `stackledger validate`, with nothing published changed and no folder in use. Without such a key there is no skill set; when a file that may hold a Settings could not be parsed, stderr says skill folders could not be read. + +#### Scenario: Error elsewhere in the settings +- **WHEN** an earlier build exists in `--out`, the Settings has `spec.skills.folders: [../kit]` and an error in `spec.site.colors`, and the command has no `--skills` +- **THEN** the exit code is 1, stderr names `stackledger validate`, and the earlier build is unchanged + +#### Scenario: Error in the skills settings +- **WHEN** the Settings has `spec.skills.folders: [/home/northwind/kit]`, a folder that does not exist, and the command has no `--skills` +- **THEN** the exit code is 1, not 2, and nothing is created + +#### Scenario: Broken settings and the option +- **WHEN** the Settings has an invalid `spec.skills` and the command has `--skills team` +- **THEN** the skill set is read from `team`, the settings' folders are not checked, and the exit code is 0 + +#### Scenario: Unreadable settings file +- **WHEN** `settings.yaml` holds a `Settings` document and a YAML syntax error, and the command has no `--skills` +- **THEN** the site is built without a Skills section, the exit code is 0, and stderr says skill folders could not be read from the settings + +#### Scenario: Broken settings without skills +- **WHEN** the Settings has an error in `spec.site.colors` and no `spec.skills` +- **THEN** the site is built without a Skills section and the exit code is 0, as before this change + +### Requirement: Output folder and the skill set +After resolving symbolic links, the output folder SHALL also be refused, with exit 2 and no change, when it is or contains a skills folder or the real path of any skill folder, agent file or file read of the set (rejected ones, ignore files and the skills map file included), or is inside such a skill folder or a skills folder's top-level `agents/`. Elsewhere inside a skills folder it is allowed, as for `skills map`. + +#### Scenario: Output inside a skill folder +- **WHEN** `--out` is `./skills/writer/site`, `./skills/writer/SKILL.md` exists and the command has `--skills ./skills` +- **THEN** the exit code is 2 and nothing is written + +#### Scenario: Output in the agents folder +- **WHEN** `--out` is `./skills/agents/site` and the command has `--skills ./skills` +- **THEN** the exit code is 2 and nothing is written + +#### Scenario: Output contains the skills folder +- **WHEN** `--out` is `./public`, an empty folder, and the command has `--skills ./public/skills`, a folder holding skills +- **THEN** the exit code is 2 and nothing is written + +#### Scenario: Output holds a linked input +- **WHEN** an earlier build exists in `public`, and `skills/writer/rules.md` is a link to `public/notes.md` +- **THEN** the command with `--skills skills --out public` exits 2 and `public/notes.md` is unchanged + +#### Scenario: Building inside the skills repository +- **WHEN** the command runs at the top of a repository holding `catalog/` and skills as `stackledger build catalog --skills . --out public`, and `public` does not exist +- **THEN** the site is built into `public` and the exit code is 0 + +#### Scenario: Output inside a linked skill folder +- **WHEN** `tool/writer` links to `kit/skills/writer`, the command has `--skills tool`, and `--out` is `kit/skills/writer/site` +- **THEN** the exit code is 2 and nothing is written + +### Requirement: Build time with skills +The site for a catalogue of 300 items and 20 lines, with a skill set of 200 skills, 20 playbooks, 10 agents, 2,000 rules and 10 skill lines, SHALL be built within 150 seconds. + +#### Scenario: Large catalogue and skill set +- **WHEN** a generated catalogue of 300 items and 20 lines is built with a generated skill set of that size +- **THEN** the command finishes within 150 seconds + +## REMOVED Requirements + +### Requirement: Command +**Reason**: ADR 13: one private site at the root: one site at the root, so the command writes different entries +**Migration**: Build command, the same requirement under a new name (its scenarios changed). + +### Requirement: Root redirect +**Reason**: ADR 13: one private site at the root: the home page is at `/`, so no redirect leads there +**Migration**: Old `/full/...` links redirect to the root path (Old addresses redirect). + +### Requirement: Personal mode +**Reason**: ADR 13: one private site at the root: there is no corporate mode to choose against +**Migration**: Remove `spec.sites`; the build warns about it and writes the one site. + +### Requirement: Personal publication +**Reason**: ADR 13: one private site at the root: no staff site exists, so no build needs the `full-only` marker +**Migration**: None: publication replaces every entry of a marked folder. diff --git a/openspec/changes/archive/2026-12-06-single-site/specs/catalogue-pipeline/spec.md b/openspec/changes/archive/2026-12-06-single-site/specs/catalogue-pipeline/spec.md new file mode 100644 index 00000000..f8474039 --- /dev/null +++ b/openspec/changes/archive/2026-12-06-single-site/specs/catalogue-pipeline/spec.md @@ -0,0 +1,22 @@ +## ADDED Requirements + +### Requirement: Published entries +The `site` job SHALL build into a fresh folder outside the repository and hand on the site only: every entry of the build folder except the marker `.stackledger-build` and any `.stackledger-tmp-*` entry. The `deploy` job SHALL run wrangler from an otherwise empty folder, so no `functions/` folder or wrangler configuration of the catalogue repository can be uploaded. + +#### Scenario: Only the site is published +- **WHEN** the `site` job's commands run on the Northwind example +- **THEN** the publish folder holds the build's entries at its root (`index.html`, `map`, `_headers`, `robots.txt`, `_redirects`, `renewals.ics`), whose `_redirects` sends `/full/*` to the root, and no `full`, no `staff`, no marker and no staging folder + +#### Scenario: The settings do not change what is published +- **WHEN** the `site` and deploy commands run on the template with `spec.sites: [full]` in `catalog/stackledger.yaml` +- **THEN** the publish and deploy folders hold the same entries as without it + +#### Scenario: Repository extras are not deployed +- **WHEN** the catalogue repository also holds `functions/` and `wrangler.toml` and the `site` and collect commands run +- **THEN** the deploy folder holds only `site/` with the publishable entries, and the deploy step's working directory is that folder + +## REMOVED Requirements + +### Requirement: What is published +**Reason**: ADR 13: one private site at the root +**Migration**: Published entries, the same requirement under a new name (its scenarios changed). diff --git a/openspec/changes/archive/2026-12-06-single-site/specs/catalogue-site/spec.md b/openspec/changes/archive/2026-12-06-single-site/specs/catalogue-site/spec.md new file mode 100644 index 00000000..43d0a9aa --- /dev/null +++ b/openspec/changes/archive/2026-12-06-single-site/specs/catalogue-site/spec.md @@ -0,0 +1,215 @@ +## ADDED Requirements + +### Requirement: Site pages +The site SHALL have a home page at `/`, a map page at `/map/`, a software list at `/software/`, one page per served component at `/software/<name>/`, one page per served licence at `/licences/<name>/`, a journeys list at `/journeys/`, one page per drawn line at `/journeys/<name>/`, and `/reports/` and `/renewals.ics`, as `licence-reports` defines, with `<name>` the item's `metadata.name` in lower case. It SHALL have no page under `/full/` or `/staff/`. + +#### Scenario: Item pages +- **WHEN** the catalogue has components `editor` and `forge` and licence `licence-editor` +- **THEN** the site has `/software/editor/`, `/software/forge/` and `/licences/licence-editor/` + +#### Scenario: No journeys +- **WHEN** the catalogue has no drawn line +- **THEN** the map page shows `No journeys yet` and the journeys list says there are none + +#### Scenario: Reports at the root +- **WHEN** the site is built +- **THEN** it has `/reports/` and `/renewals.ics`, and no file under `full/` or `staff/` + +#### Scenario: Map at /map/ +- **WHEN** a site is built +- **THEN** `/map/` holds the map, `/` holds the home page with no map on it, and every link labelled `Map` to the software map, in the sub-navigation and the footer, targets `/map/` + +### Requirement: Home page content +The home page SHALL show a banner with the site title as its `h1`, `spec.site.home.text` or `Your software and skills, mapped.` when unset, and the banner art ("Home banner art"); then a Software card with the view's counts of components, licences and drawn journeys, linking Map, List, Journeys and Reports; and, with a skill set, a Skills card with the counts of skills, playbooks, agents and rules, linking List, Map and Rules. + +#### Scenario: Home counts and links +- **WHEN** the site is built from a catalogue with 3 components, 2 licences and 1 drawn journey, and a skill set of 2 skills, 1 playbook, 1 agent and 4 rules +- **THEN** the home shows those counts, links `/map/`, `/reports/`, `/skills/`, `/skill-map/` and `/rules/`, and shows the default text + +#### Scenario: Home text +- **WHEN** `spec.site.home.text` is `Northwind tools` +- **THEN** the home banner shows `Northwind tools` and not the default sentence + +#### Scenario: Home without skills +- **WHEN** a site is built without a skill set +- **THEN** its home has no Skills card and no link to `/skills/` + +#### Scenario: Empty catalogue +- **WHEN** the catalogue has no component, licence or journey +- **THEN** the home shows the Software card with three zero counts + +### Requirement: Licence page content +A licence page SHALL show its title, name, owner and all the `spec.licence` fields, the components that use it (each linking to its page), and the impact of removing it. + +#### Scenario: Every licence field +- **WHEN** the site shows licence `licence-editor`, which has every licence field +- **THEN** the page shows vendor, status, cost, currency, cycle, renewal date, payer, seats, vault item and note + +## MODIFIED Requirements + +### Requirement: Layout +Every page SHALL share one layout: a header with the site title (from `spec.site.title`, default `stackledger`) linking the home page `/`, and the divisions Software (`/map/`) and, with a skill set, Skills (`/skills/`); under it the division's sub-navigation, for Software: Map (`/map/`), List (`/software/`), Journeys and Reports; a footer with the stackledger version and no view name; and a theme switch following `prefers-color-scheme` until the reader picks one, then remembering it. + +#### Scenario: Theme remembered +- **WHEN** the reader chooses dark on one page and opens another page +- **THEN** the other page opens in dark + +#### Scenario: Site title +- **WHEN** `spec.site.title` is `Northwind software` +- **THEN** every page's header and `title` element show `Northwind software` + +#### Scenario: Default title +- **WHEN** the catalogue has no `spec.site.title`, or its `Settings` has an error +- **THEN** every page's header and `title` element show `stackledger`, also on the Skills pages + +#### Scenario: Title opens the home +- **WHEN** the reader clicks the site title on `/skills/` or on `/software/editor/` +- **THEN** the home page `/` of the same site opens + +#### Scenario: View in the footer +- **WHEN** any page is opened +- **THEN** its footer shows `stackledger` and its version and no view name + +#### Scenario: Reports link +- **WHEN** any Software page is opened +- **THEN** its sub-navigation links Reports (`/reports/`) + +#### Scenario: Software sub-navigation +- **WHEN** the reader opens `/journeys/`, then the page of the journey `ship` +- **THEN** the header marks Software, the sub-navigation links Map (`/map/`), List and Journeys, and only on `/journeys/` is Journeys marked with `aria-current="page"` + +#### Scenario: Skills link +- **WHEN** the site is built with a skill set, and again without one +- **THEN** every page's header links Skills (`/skills/`) in the first build and none does in the second + +### Requirement: Brand mark +The favicon SHALL be the design system's `ledgerMark` at size 32 in a 32 × 32 SVG. The header SHALL show the mark before the site title as decorative images (`alt=""`) loaded from the site's own folder: `favicon.svg` in the light theme, and `brand-mark-dark.svg`, the `ledgerMark` drawn for the dark surface, in the dark theme. The site's templates SHALL write `img` elements only for the header marks, the footer symbols, the home banner and the home link icons. + +#### Scenario: Favicon is the mark +- **WHEN** `site/public/favicon.svg` is read +- **THEN** it is a 32 × 32 SVG whose shapes equal those of `ledgerMark({ x: 0, y: 0, size: 32 })` + +#### Scenario: Favicon is the page mark +- **WHEN** `site/public/favicon.svg` is read +- **THEN** its first shape is a `rect` at (0.625, 0.625), 30.75 × 30.75, `rx` 6.6, filled `#FFFFFF` and stroked `#121212` with width 1.25, and it has no other `rect` + +#### Scenario: Dark mark is the dark ledgerMark +- **WHEN** `site/public/brand-mark-dark.svg` is read +- **THEN** it is a 32 × 32 SVG whose shapes equal those of `ledgerMark({ x: 0, y: 0, size: 32, surface: "dark" })`, whose page `rect` is stroked `#ADA79D`, with no other `rect` + +#### Scenario: Header mark with a custom title +- **WHEN** `spec.site.title` is `Northwind software` and any page is opened +- **THEN** the header link to the home holds an `img` with `alt=""` and a relative `src` ending in `favicon.svg`, then one ending in `brand-mark-dark.svg`, followed by `Northwind software` + +#### Scenario: Mark follows the theme +- **WHEN** any page is shown in the light theme, then in the dark theme +- **THEN** only `favicon.svg` is visible in the header in light and only `brand-mark-dark.svg` in dark, inline before the title + +#### Scenario: No other images +- **WHEN** the site is built from the example with `spec.site.home.links` holding a link with an icon +- **THEN** every `img` element of every page is a header mark, a footer symbol (`symbol-light.svg` or `symbol-dark.svg`), the home banner or a home link icon + +### Requirement: Interface icons +The zoom in, zoom out and reset buttons of `/map/` and `/skill-map/`, and the link to `renewals.ics` on `/reports/`, SHALL start with the design system's `uiIcon` `zoomIn`, `zoomOut`, `reset` and `download` in `currentColor`, so each follows its button's text colour, also on hover. The theme switch SHALL show `uiIcon` `sun` in `color.white` in the light theme and `moon` in `color.ink` in the dark theme. + +#### Scenario: Zoom buttons with icons +- **WHEN** `/map/` and `/skill-map/` of the example are built +- **THEN** each page's zoom in, zoom out and reset buttons hold, in that order, an inline `svg` equal to the `zoomIn`, `zoomOut` and `reset` icon, the first two with `aria-label` `Zoom in` and `Zoom out`, the third followed by the text `Reset` + +#### Scenario: Calendar button with an icon +- **WHEN** the site of the example is built +- **THEN** the link to `renewals.ics` on `/reports/` starts with an inline `svg` equal to the `download` icon, followed by its text + +#### Scenario: Icon follows the button colour +- **WHEN** the reader hovers the zoom in button, in the light theme and in the dark theme +- **THEN** before and during the hover, the computed `stroke` of the icon's magnifier `path` equals the button's computed text colour and its computed `fill` stays `none` + +#### Scenario: Theme switch icons +- **WHEN** any page is shown in the light theme, then in the dark theme, with JavaScript +- **THEN** the switch shows only the `sun` icon in light and only the `moon` icon in dark, each equal to its site icon + +### Requirement: Wordmark +The header's site title SHALL be set in Source Serif 4, italic, weight 700, on every page and whatever `spec.site.title` holds, in the face the site ships ("Font delivery"). + +#### Scenario: Wordmark face +- **WHEN** any page is opened in the light theme, then in the dark theme +- **THEN** the first family of the site title's computed `font-family`, unquoted, starts with `Source Serif 4-`, the family the Fonts API generates, its `font-style` is `italic`, its `font-weight` is 700, and `document.fonts` holds a loaded italic 700 face of that family + +#### Scenario: Wordmark with the longest title +- **WHEN** `spec.site.title` holds 60 characters and a page is opened +- **THEN** the whole title is set in the same face, style and weight as the default title + +### Requirement: Parent brand endorsement +The footer SHALL show, after the stackledger version, the design system's `symbol` as decorative images (`alt=""`, `width` and `height` 16) from the site's own folder, `symbol-light.svg` in the light theme and `symbol-dark.svg` in the dark one, as the header marks do, then `by Bruno Souza`, none inside a link. `scripts/site-art.mjs` SHALL write both from the `symbol` piece on each surface. No SVG file of the sites SHALL hold a `style` element. + +#### Scenario: Footer endorsement +- **WHEN** any page is opened +- **THEN** its footer shows the stackledger version, then an `img` with `alt=""`, `width` 16, `height` 16 and a relative `src` ending in `symbol-light.svg`, then the same with `symbol-dark.svg`, then `by Bruno Souza`, and no `a` element holds the images or the text + +#### Scenario: Symbol follows the theme +- **WHEN** any page is shown in the light theme, then in the dark theme +- **THEN** only `symbol-light.svg` is visible in the footer in light and only `symbol-dark.svg` in dark, inline before `by Bruno Souza` + +#### Scenario: Symbol files are the design system's +- **WHEN** `site/public/symbol-light.svg` and `site/public/symbol-dark.svg` are read +- **THEN** each equals the drawing of the package's `symbol` piece on its surface, `light` and `dark`, as `scripts/site-art.mjs` writes it + +#### Scenario: Symbol files are inert +- **WHEN** `site/public/symbol-light.svg` and `site/public/symbol-dark.svg` are parsed +- **THEN** neither has a `script`, `foreignObject` or `style` element, a `style` attribute, an attribute starting with `on`, or an `href` or `url(…)` other than an internal `url(#id)` + +#### Scenario: No SVG of the sites holds a style +- **WHEN** the site is built from the example with a home link icon +- **THEN** no `.svg` file of the site holds a `style` element + +### Requirement: External links in a new tab +On every page, an anchor to another site (an `href` that is an absolute URL: the home links and the map credit, the only ones site-security allows) SHALL have `target="_blank"` and `rel="noopener noreferrer"`, and its accessible name SHALL end with ` (opens in a new tab)`: in `aria-label` for an icon link, in visually hidden text inside the anchor otherwise, so the text on screen does not change. It SHALL NOT get a `title` attribute. + +#### Scenario: Text link in a new tab +- **WHEN** `spec.site.home.links` lists `Blog` (`https://blog.example.com/`, no icon) +- **THEN** its anchor has `target="_blank"` and `rel="noopener noreferrer"`, no `title`, the text `Blog` followed by a `span` with the class `visually-hidden` holding ` (opens in a new tab)`, and in a browser its accessible name is `Blog (opens in a new tab)` and the span's box is at most 1 × 1 pixel + +#### Scenario: Icon link in a new tab +- **WHEN** `spec.site.home.links` lists `Source` (`https://github.example.com/northwind/`, `icon: github`) +- **THEN** its anchor has `target="_blank"`, `rel="noopener noreferrer"`, `aria-label="Source (opens in a new tab)"`, no `title` and no text other than whitespace + +#### Scenario: Map credit in a new tab +- **WHEN** the map page of a site built with `spec.map.backdrop: london` is opened in a browser +- **THEN** the credit line reads `Map data © OpenStreetMap contributors` on screen, and its link has `target="_blank"`, `rel="noopener noreferrer"` and the accessible name `OpenStreetMap contributors (opens in a new tab)` + +#### Scenario: The reader keeps their place +- **WHEN** the reader clicks the `Blog` link on the home in a browser +- **THEN** a new tab opens on `https://blog.example.com/`, it has no `window.opener` and an empty `document.referrer`, and the home stays open at its own address in the first tab + +#### Scenario: Hostile title in a new-tab link +- **WHEN** an icon link's title is `"><script>alert(1)</script>` +- **THEN** its `aria-label` is that title escaped followed by ` (opens in a new tab)`, and the home holds no `script` element from it + +### Requirement: Internal links in the same tab +Every anchor whose `href` is relative (a page or file of the same site: header, sub-navigation, cards, tables, item, journey, report and skills pages, the calendar download) SHALL have no `target` attribute and no ` (opens in a new tab)` in its name or text. + +#### Scenario: Only external anchors open a new tab +- **WHEN** the site is built from catalogues with home icon links, home text links and `spec.map.backdrop: london`, and from a catalogue with a skill set +- **THEN** across every HTML page, each anchor with `target` has an absolute `href` and `target="_blank"`, each anchor with an absolute `href` has `target="_blank"`, `rel="noopener noreferrer"` and no `title`, and no anchor with a relative `href` has `target` or the text `opens in a new tab` + +#### Scenario: No external link, no new tab +- **WHEN** the site is built from the example catalogue, which has no home links and no city backdrop +- **THEN** no page has an anchor with `target` or the text `opens in a new tab` + +#### Scenario: Internal link in the same tab +- **WHEN** the reader clicks the home card's `Map` link in a browser +- **THEN** the map page opens in the same tab and no new tab opens + +## REMOVED Requirements + +### Requirement: Pages +**Reason**: ADR 13: one private site at the root +**Migration**: Site pages, the same requirement under a new name (its scenarios changed). + +### Requirement: Home page +**Reason**: ADR 13: one private site at the root +**Migration**: Home page content, the same requirement under a new name (its scenarios changed). + +### Requirement: Licence page +**Reason**: ADR 13: one private site at the root +**Migration**: Licence page content, the same requirement under a new name (its scenario changed). diff --git a/openspec/changes/archive/2026-12-06-single-site/specs/catalogue-views/spec.md b/openspec/changes/archive/2026-12-06-single-site/specs/catalogue-views/spec.md new file mode 100644 index 00000000..888b35a8 --- /dev/null +++ b/openspec/changes/archive/2026-12-06-single-site/specs/catalogue-views/spec.md @@ -0,0 +1,16 @@ +## ADDED Requirements + +### Requirement: Staff view deprecated +The `staff` view SHALL stay in the code and be offered only by `stackledger mcp --view staff` and `stackledger map --view staff`; no site SHALL be built from it. Each of those commands, when given `--view staff`, SHALL write one stderr line saying the staff view is deprecated and unused by the site, and the `full` view SHALL stay the default. The `full` view SHALL write no such line. + +#### Scenario: Map in the staff view +- **WHEN** `stackledger map ./catalogue --view staff` runs +- **THEN** the SVG is as before on stdout, the exit code is 0 and stderr has one line saying the staff view is deprecated + +#### Scenario: Map in the full view +- **WHEN** `stackledger map ./catalogue` runs on a catalogue with no problem +- **THEN** stderr is empty + +#### Scenario: Staff view still hides its fields +- **WHEN** a licence has `cost: 120` and the view is `staff` +- **THEN** the view has no `cost`, as before diff --git a/openspec/changes/archive/2026-12-06-single-site/specs/catalogue/spec.md b/openspec/changes/archive/2026-12-06-single-site/specs/catalogue/spec.md new file mode 100644 index 00000000..0b6e4bb9 --- /dev/null +++ b/openspec/changes/archive/2026-12-06-single-site/specs/catalogue/spec.md @@ -0,0 +1,66 @@ +## ADDED Requirements + +### Requirement: Deprecated site settings +`spec.sites` is deprecated and has no effect: `stackledger build` writes one site whatever it holds. A valid `spec.sites` (a list of `full` and `staff` without repeats that includes `full`) SHALL get a warning on `spec.sites` saying it is ignored because the build writes one site at the root. An invalid one (a value other than `full` or `staff`, a repeated value, a list without `full`, or a value that is not a list) SHALL be an error with the file, line and field, as before. + +#### Scenario: Personal list +- **WHEN** a `Settings` document has `spec.sites: [full]` +- **THEN** it has no error and one warning on `spec.sites`, and the build writes the one site + +#### Scenario: Corporate list +- **WHEN** a `Settings` document has `spec.sites: [full, staff]` or `[staff, full]` +- **THEN** it has no error and one warning on `spec.sites`, and the build writes the one site, with no `staff` folder + +#### Scenario: No sites setting +- **WHEN** the catalogue has no `Settings` document, or one without `spec.sites` +- **THEN** there is no warning about sites + +#### Scenario: Staff site alone +- **WHEN** `stackledger.yaml` has `spec.sites: [staff]` on line 6, or an empty list +- **THEN** it gets an error at `stackledger.yaml` line 6 on `spec.sites` saying `full` is required + +#### Scenario: Unknown site +- **WHEN** `spec.sites` lists `full` and, on line 8, `finance` +- **THEN** it gets an error at line 8 on `spec.sites[1]` listing `full` and `staff` + +#### Scenario: Repeated site +- **WHEN** `spec.sites` is `[full, full]` +- **THEN** the second `full` gets exactly one error + +### Requirement: Deprecated staff hide list +A valid `spec.views.staff.hide` SHALL get a warning on it saying the site shows every licence field, so a catalogue that hid fields from a staff site learns they are no longer hidden. The list is still read by the deprecated staff view of `stackledger mcp` and `stackledger map`. + +#### Scenario: Hide list warning +- **WHEN** a `Settings` document has `spec.views.staff.hide: [cost]` +- **THEN** it has one warning on `spec.views.staff.hide` and the built site shows the cost + +#### Scenario: Invalid hide list +- **WHEN** `spec.views.staff.hide` lists `price` +- **THEN** it gets the error on `spec.views.staff.hide[0]`, not the warning + +## MODIFIED Requirements + +### Requirement: Settings +A `Settings` document SHALL have `metadata.name` and MAY have `metadata.namespace` and `metadata.title`. It SHALL have `spec`, a mapping, possibly empty. `spec.views.staff.hide` MAY be a list of licence field names without repeats, each one of `vendor`, `status`, `cycle`, `cost`, `currency`, `renewsOn`, `seats`, `paidBy`, `vaultItem` and `note`. It MAY have `spec.site`, `spec.skills` and `spec.map`, each with its own requirement. By convention it is in `stackledger.yaml`; any file name works. + +#### Scenario: Staff hide list +- **WHEN** a `Settings` document has `spec.views.staff.hide: [cost, renewsOn]` +- **THEN** it has no error and one warning on `spec.views.staff.hide`, and the build reports the warning + +#### Scenario: Unknown field name in the hide list +- **WHEN** `spec.views.staff.hide` lists `price` +- **THEN** it gets an error on `spec.views.staff.hide[0]` listing the allowed names + +#### Scenario: Repeated field name +- **WHEN** `spec.views.staff.hide` is `[cost, cost]` +- **THEN** the second `cost` gets an error + +## REMOVED Requirements + +### Requirement: Site modes +**Reason**: ADR 13: one private site at the root: no personal and corporate modes +**Migration**: Deprecated site settings keeps the checks and adds the warning. + +### Requirement: Broken settings choose the corporate mode +**Reason**: ADR 13: one private site at the root: there is no second site that broken settings could expose +**Migration**: None: broken settings no longer change which site is built. diff --git a/openspec/changes/archive/2026-12-06-single-site/specs/hosting-recipes/spec.md b/openspec/changes/archive/2026-12-06-single-site/specs/hosting-recipes/spec.md new file mode 100644 index 00000000..5d8f44ac --- /dev/null +++ b/openspec/changes/archive/2026-12-06-single-site/specs/hosting-recipes/spec.md @@ -0,0 +1,38 @@ +## ADDED Requirements + +### Requirement: Proxy example +`examples/hosting/Caddyfile` SHALL authenticate every request through `forward_auth` to oauth2-proxy before serving any file. Using only the groups the auth service returns, it SHALL serve every path to the group `readers` and answer 403 to any other signed-in request. After authentication it SHALL send `/full` and `/full/*` to the same path under the root with a permanent redirect, and it SHALL NOT redirect `/staff/`. + +#### Scenario: Anonymous request +- **WHEN** a request without a session asks for `/`, `/map/`, `/renewals.ics`, an asset of the site, `/full/` or `/full/renewals.ics` +- **THEN** no site content is returned and no redirect to a site path is sent + +#### Scenario: Reader +- **WHEN** a signed-in identity whose groups hold `readers` asks for `/`, `/map/`, `/reports/` and `/renewals.ics` +- **THEN** each is served, `/renewals.ics` as `text/calendar` + +#### Scenario: Old addresses +- **WHEN** a reader asks for `/full/`, `/full` and `/full/renewals.ics` +- **THEN** each answers 301 with `Location` `/`, `/` and `/renewals.ics` + +#### Scenario: Former staff paths +- **WHEN** a reader asks for `/staff/` +- **THEN** the answer is 404 and nothing redirects it + +#### Scenario: Signed in without the group +- **WHEN** a signed-in identity with no groups, or only the groups `staff` or `contractors`, asks for `/`, `/map/` and `/full/` +- **THEN** every path answers 403 + +#### Scenario: Forged group header +- **WHEN** a request of an identity with no group carries its own `X-Auth-Request-Groups: readers` +- **THEN** `/` still answers 403 + +#### Scenario: Auth service down +- **WHEN** the auth service cannot be reached +- **THEN** every path answers an error with no site content + +## REMOVED Requirements + +### Requirement: Generic proxy example +**Reason**: ADR 13: one private site at the root: one group instead of two +**Migration**: Proxy example, the same requirement under a new name (its scenarios changed). diff --git a/openspec/changes/archive/2026-12-06-single-site/specs/licence-reports/spec.md b/openspec/changes/archive/2026-12-06-single-site/specs/licence-reports/spec.md new file mode 100644 index 00000000..82193d85 --- /dev/null +++ b/openspec/changes/archive/2026-12-06-single-site/specs/licence-reports/spec.md @@ -0,0 +1,27 @@ +## ADDED Requirements + +### Requirement: Report source and date +The report SHALL be computed from the `full` view only, for a report date and a renewal window of `days` days (default 90). In the site the report date is the same resolved date as the map (`build --date`, or the local date captured once) and the window is 90 days. + +#### Scenario: Reports at the root +- **WHEN** the site is built +- **THEN** it has `/reports/` and `/renewals.ics`, and the site's sub-navigation links the Reports page + +#### Scenario: Site report date +- **WHEN** the site is built with `--date 2027-06-01` +- **THEN** the Reports page and the calendar use `2027-06-01` as the report date + +## MODIFIED Requirements + +### Requirement: Reports page +The site SHALL have a Reports page at `/reports/` with the renewals, overdue and unknown dates; the recurring totals per currency with their incomplete counts; the three groupings; the one-off and planned lists; the incomplete licences; and a link to `renewals.ics`. Each licence links to its page. + +#### Scenario: Page content +- **WHEN** the site of the example is built +- **THEN** `/reports/` shows the GBP totals per month and per year and links `renewals.ics` + +## REMOVED Requirements + +### Requirement: Source and date +**Reason**: ADR 13: one private site at the root +**Migration**: Report source and date, the same requirement under a new name (its scenario changed). diff --git a/openspec/changes/archive/2026-12-06-single-site/specs/mcp-server/spec.md b/openspec/changes/archive/2026-12-06-single-site/specs/mcp-server/spec.md new file mode 100644 index 00000000..def17962 --- /dev/null +++ b/openspec/changes/archive/2026-12-06-single-site/specs/mcp-server/spec.md @@ -0,0 +1,12 @@ +## MODIFIED Requirements + +### Requirement: Logs +The server SHALL write to stderr one line when it starts, with the absolute folder, the view and the number of tools, then, with `--view staff`, one line saying the staff view is deprecated and unused by the site, and one line for each tool error, with the tool name and the reason. No log line SHALL contain a catalogue value other than the arguments of the call. + +#### Scenario: Start line +- **WHEN** the server starts with `--view staff` +- **THEN** stderr has one line naming the folder, `staff` and 4 tools, then one line saying the staff view is deprecated + +#### Scenario: Failed call line +- **WHEN** `get_item` is called with `component:ghost` +- **THEN** stderr gets one line naming `get_item` and the reason diff --git a/openspec/changes/archive/2026-12-06-single-site/specs/site-security/spec.md b/openspec/changes/archive/2026-12-06-single-site/specs/site-security/spec.md new file mode 100644 index 00000000..3b7ce3cf --- /dev/null +++ b/openspec/changes/archive/2026-12-06-single-site/specs/site-security/spec.md @@ -0,0 +1,82 @@ +## ADDED Requirements + +### Requirement: URLs relative to the site +Every URL SHALL be relative to the file that holds it and resolve inside its site's folder: HTML URL attributes, CSS `url()` and `@import`, JavaScript static and dynamic imports, and asset references through `import.meta.url`. The anchors exempt by "No external requests" are exempt here too. A generated URL form the build does not handle SHALL fail the build before publication. + +#### Scenario: Any path prefix +- **WHEN** the site is served at `/` of one host and again under `/catalogue/` of another, and every page is opened +- **THEN** no request leaves the site's prefix and none fails + +### Requirement: One site from the full view +The site SHALL be built from the `full` view only, in one Astro build with its own data file and cache, and no file of the output SHALL come from the `staff` view: its allow-lists and its hidden-field list have no effect on the site, which shows every field of every item. Whoever can open the site sees all of it, so `docs/site.md` and `docs/hosting.md` SHALL say that the access policy must name only people allowed to see everything. + +#### Scenario: Staff settings have no effect +- **WHEN** two catalogues differ only in `spec.views.staff.hide` and `spec.sites`, and are built with the same `--date` +- **THEN** every file of the two sites is identical + +#### Scenario: Costs are in the site +- **WHEN** a licence has `cost: 98765` and `note: ZETA-NOTE` +- **THEN** both values appear on the licence page and in the Reports page + +#### Scenario: Hosting says who may sign in +- **WHEN** a reader opens `docs/hosting.md` +- **THEN** it says the Access application covers the root on every address and allows only people who may see everything, including costs, renewal dates, payers, notes and password-manager item names + +## MODIFIED Requirements + +### Requirement: No inline code +Pages SHALL contain no inline `script` or `style` element, no `style` attribute and no event-handler attribute; scripts and styles are files of the site. Every page SHALL carry the same Content Security Policy. + +#### Scenario: Same policy everywhere +- **WHEN** the site is built from the example +- **THEN** every HTML page has the same CSP and none has an inline script, inline style or `style` attribute + +### Requirement: No external requests +No `href`, `src`, `srcset`, `action`, `formaction`, `poster` or `data` attribute and no CSS `url()` or `@import` SHALL hold an absolute or protocol-relative URL. Exempt: the SVG namespace in `xmlns`, an `href` of an `a` element in the site's root `index.html` whose decoded value equals a URL of `spec.site.home.links`, and the anchor of "Map credit link". Any other absolute URL, on any page or attribute, fails the build. There are no analytics. + +#### Scenario: Only local URLs +- **WHEN** the site is built from the example +- **THEN** no such attribute or CSS value starts with a scheme or `//` + +#### Scenario: Home links are the only external URLs +- **WHEN** the site is built from the example with `spec.site.home.links` listing `https://example.org/articles/` +- **THEN** the build succeeds, and the only attributes holding an absolute URL are the `href` of that `Links` anchor on each home page + +#### Scenario: Link URL outside the home +- **WHEN** the build's URL scan meets `https://example.org/articles/`, one of the home links, in an `href` of a page other than the root `index.html`, or in a `src` of the root `index.html` +- **THEN** the scan reports it and the build fails before publication + +### Requirement: Map credit link +When the software map has a city backdrop (catalogue-site, Map backdrop), an `href` of an `a` element in the site's `map/index.html` whose decoded value equals `https://www.openstreetmap.org/copyright` SHALL be exempt from "No external requests" and "Relative URLs". Anywhere else, in any other attribute, or in a site whose map has no city backdrop, that URL SHALL fail the build like any other absolute URL. + +#### Scenario: Map credit is the only other external URL +- **WHEN** the site is built from the example with `spec.site.home.links` and `spec.map.backdrop: london` +- **THEN** the build succeeds, and apart from the home links the only attribute holding an absolute URL is the `href` of the credit anchor on the map page, `https://www.openstreetmap.org/copyright` + +#### Scenario: Credit URL outside the map page +- **WHEN** the build's URL scan meets `https://www.openstreetmap.org/copyright` in an `href` of a page other than `map/index.html`, in a `src` of `map/index.html`, or in an `href` of `map/index.html` of a site whose map has no city backdrop +- **THEN** the scan reports it and the build fails before publication + +### Requirement: Headers file +The build SHALL write `_headers` at the root of the output folder, which is the site's root, applying to `/*` the Content Security Policy above plus `frame-ancestors 'none'`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`, `X-Robots-Tag: noindex, nofollow` and `Permissions-Policy: camera=(), microphone=(), geolocation=()`. + +#### Scenario: Root headers +- **WHEN** a build succeeds +- **THEN** `<out>/_headers` holds those headers for `/*` + +### Requirement: Not indexed +Every page SHALL have `<meta name="robots" content="noindex, nofollow">`. The build SHALL write `robots.txt` with `User-agent: *` and `Disallow: /` at the root of the output folder, which is the site's root. + +#### Scenario: Root robots +- **WHEN** a build succeeds +- **THEN** `<out>/robots.txt` disallows everything + +## REMOVED Requirements + +### Requirement: Relative URLs +**Reason**: ADR 13: one private site at the root: one site, so no two prefixes +**Migration**: URLs relative to the site, the same requirement under a new name (its scenario changed). + +### Requirement: One view per site +**Reason**: ADR 13: one private site at the root: no staff site is built, so there is no second site to keep clean +**Migration**: The `staff` view stays in the code for `stackledger mcp` and `stackledger map`, deprecated (catalogue-views). diff --git a/openspec/changes/archive/2026-12-06-single-site/specs/skills-site/spec.md b/openspec/changes/archive/2026-12-06-single-site/specs/skills-site/spec.md new file mode 100644 index 00000000..37db97e8 --- /dev/null +++ b/openspec/changes/archive/2026-12-06-single-site/specs/skills-site/spec.md @@ -0,0 +1,58 @@ +## MODIFIED Requirements + +### Requirement: Skills pages +When a skill set is built, the site SHALL have the list `/skills/`, the map `/skill-map/`, the rules index `/rules/`, and one page per item: `/skills/<file>/` for a skill, `/playbooks/<file>/` for a playbook and `/agents/<file>/` for an agent, `<file>` being the page file name `stackledger skills map` gives the item, without `.md`. Without a skill set, none of these pages SHALL exist. + +#### Scenario: Item pages +- **WHEN** the set has the skill `writer`, the playbook `release` and the agent `reviewer` +- **THEN** the site has `/skills/writer/`, `/playbooks/release/` and `/agents/reviewer/` + +#### Scenario: Name that is not a file name +- **WHEN** a skill is named `Writer` +- **THEN** its page is `/skills/_577269746572/` + +#### Scenario: Skill and agent with one name +- **WHEN** the set has a skill and an agent both named `reviewer` +- **THEN** the site has `/skills/reviewer/` and `/agents/reviewer/` + +#### Scenario: No skill set +- **WHEN** a site is built without a skill set +- **THEN** it has no `/skills/`, `/skill-map/`, `/rules/`, `/playbooks/` or `/agents/` folder and no page links to one + +### Requirement: Skills map shown size +`/skill-map/` SHALL size the skills map and its frame as the software map page does (catalogue-site, "Map shown size"): the initial viewBox width in CSS pixels, or narrower when the frame's room is smaller, the frame's content box as wide as the map and centred, and the same size while zooming and panning, with no inline style or script. + +#### Scenario: Skills map not enlarged +- **GIVEN** a 1360-pixel-wide window and the example skills map, whose viewBox is narrower than the room +- **WHEN** the reader opens `/skill-map/` +- **THEN** the map is as wide as its viewBox, the frame's content box is as wide as the map, and the frame's left and right distances to the content column's edges are equal (each within 1 pixel) + +#### Scenario: Same ink as the software map +- **GIVEN** a 1360-pixel-wide window +- **WHEN** the reader opens `/map/` and `/skill-map/` +- **THEN** neither map shows more than 1.01 pixels per initial viewBox unit, and the software map's pixels per unit are within 5% of the skills map's + +#### Scenario: Skills map just wider than the room +- **GIVEN** a 677-pixel-wide window, so that the room is narrower than the skills map's 675.6-unit viewBox +- **WHEN** the reader opens `/skill-map/` +- **THEN** the map is as wide as the frame's content box (within 1 pixel) and the page has no horizontal scroll + +#### Scenario: Skills map on a phone +- **GIVEN** a 390-pixel-wide window +- **WHEN** the reader opens `/skill-map/` +- **THEN** the map is as wide as the frame's content box (within 1 pixel) and the page has no horizontal scroll + +#### Scenario: Skills zoom keeps the shown size +- **WHEN** the reader presses zoom in twice on `/skill-map/`, then drags the map +- **THEN** the map's width and height on the page are the same as before (within 1 pixel) + +#### Scenario: Skills shown size without JavaScript +- **GIVEN** JavaScript is disabled and a 1360-pixel-wide window +- **WHEN** the reader opens `/skill-map/` +- **THEN** the whole map is shown, as wide as its viewBox (within 1 pixel) + +## REMOVED Requirements + +### Requirement: Same skills in every site +**Reason**: ADR 13: one private site at the root: one site, so there is no second site to compare +**Migration**: None: the Skills pages are built once from the set. diff --git a/openspec/changes/archive/2026-12-06-single-site/tasks.md b/openspec/changes/archive/2026-12-06-single-site/tasks.md new file mode 100644 index 00000000..a8d51ca2 --- /dev/null +++ b/openspec/changes/archive/2026-12-06-single-site/tasks.md @@ -0,0 +1,35 @@ +# Tasks: one private site at the root + +Levels: unit and integration are vitest (`npm test`, after `npm run build`); e2e is Playwright (`npm run test:browser`). A scenario is written as capability / requirement / scenario. + +## 1. Build and publication + +- [x] 1.1 `src/site/build.ts`, `policy.ts`, `staging.ts`, `publish.ts`, `command.ts`: build once from the `full` view into `<staging>/site/` (site files, `_headers`, `robots.txt`, `_redirects`), the marker in `<staging>/root/`; publish every top-level entry of the staged site, after moving every entry of the marked output folder (other than the marker and staging folders) into `old/`; marker last; refuse a linked entry; the new `_redirects` and report lines. Proves build-command / Build command (all), Old addresses redirect (both), Safe output folder / "Linked published entry", Atomic replace (both), Replace the whole folder (both), Deterministic build, Build report (both) (`test/integration/build.test.ts`, `test/unit/site-publish.test.ts`, `test/integration/build-with-faults.mjs` callers; integration and unit). +- [x] 1.2 Interrupted publication and the manual restore: `docs/site.md` steps rewritten for the new layout and `test/manual-restore.ts` follows them. Proves build-command / Interrupted publication (all three scenarios), Replace the whole folder / "A failed replacement keeps the two-site build" (`test/integration/build.test.ts`, integration). +- [x] 1.3 Output folder and skills scenarios, sandbox and time: existing scenarios re-run on the new layout. Proves build-command / Skill folders, Skills settings with problems, Output folder and the skill set, Writes, Build time, Build time with skills (`test/integration/build-skills.test.ts`, `sandbox.test.ts`, `build.test.ts`, integration). + +## 2. Site + +- [x] 2.1 `site/src/components/Footer.astro`, `Header.astro`, `SubNav.astro`, pages and `src/site/data.ts`: no view name; Reports link and page always present. Proves catalogue-site / Site pages, Layout / "View in the footer", "Reports link", Home page content, Licence page content, Parent brand endorsement (`test/integration/site.test.ts`, integration). +- [x] 2.2 `src/site/relative.ts` scan and comments for one site; no page below `full/` or `staff/`. Proves site-security / URLs relative to the site, No inline code, No external requests, Map credit link, Headers file, Not indexed (`test/integration/site.test.ts`, `test/unit/site-relative.test.ts`, integration and unit). +- [x] 2.3 Replace `test/integration/staff-leak.test.ts` with a test that the staff settings do not change the site. Proves site-security / One site from the full view (all three) (integration). +- [x] 2.4 Reports and calendar at the root. Proves licence-reports / Report source and date, Reports page; skills-site / Skills pages, Skills map shown size (`test/integration/site.test.ts`, `site-skills.test.ts`, `test/browser/site.spec.ts`, `site-skills.spec.ts`, `skills-map.spec.ts`; integration and e2e: the browser server serves the site at `/` and the pages open without `/full/`). + +## 3. Settings, views, commands + +- [x] 3.1 `src/validate.ts`, `views.ts`: warning on a valid `spec.sites`, warning on `spec.views.staff.hide`, `resolveSites` removed; the example's `stackledger.yaml` loses the hide list. Proves catalogue / Deprecated site settings (all), Deprecated staff hide list (both), Settings / "Staff hide list" (`test/unit/settings.test.ts`, `test/unit/views.test.ts`, unit). +- [x] 3.2 `src/cli.ts`, `src/mcp.ts`, `src/map/command.ts`: deprecation line for `--view staff`. Proves catalogue-views / Staff view deprecated (all), mcp-server / Logs / "Start line" (`test/integration/mcp.test.ts`, `map.test.ts`, integration). + +## 4. Hosting and pipeline + +- [x] 4.1 `examples/hosting/Caddyfile`: group `readers`, redirects of `/full` and `/full/*`, no rule for `/staff/`. Proves hosting-recipes / Proxy example (all seven scenarios) (`test/integration/hosting-caddy.test.ts`, integration, real Caddy when installed as before). +- [x] 4.2 `examples/catalogue-repository/` workflow and README: hand on the build folder without the marker and staging entries; no modes. Proves catalogue-pipeline / Published entries (all three) (`test/integration/catalogue-template.test.ts`, integration). +- [x] 4.3 `test/unit/hosting-docs.test.ts` and `test/integration/docs.test.ts` follow the rewritten docs. Proves site-security / One site from the full view / "Hosting says who may sign in" (unit). + +## 5. Documentation + +- [x] 5.1 `docs/site.md`, `docs/hosting.md`, `docs/how-it-works.md`, `docs/catalogue-format.md`, `docs/mcp.md`, `docs/map.md`, `docs/reports.md`, `docs/architecture.md`, `docs/demo.md`, `docs/roadmap.md`, `README.md`, the Purpose lines of the capabilities. Verified by the review and the docs tests in `npm test`. + +## 6. Release + +- [x] 6.1 Pull request titled `feat!: one private site at the root, no full or staff split (SW-345)`; do not set the version. Release-please proposes the version; Bruno merges it and approves the `npm` environment (`docs/release.md`). Verified by `npm view @brunosouzas/stackledger version` after his release. diff --git a/openspec/specs/build-command/spec.md b/openspec/specs/build-command/spec.md index 2d7354c5..590e29c1 100644 --- a/openspec/specs/build-command/spec.md +++ b/openspec/specs/build-command/spec.md @@ -5,39 +5,6 @@ Defines `stackledger build`, the command that turns a catalogue folder into the ## Requirements -### Requirement: Command -`stackledger build <folder> --out <dir> [--date YYYY-MM-DD] [--skills <folder>]...` SHALL build the `full` site into `<dir>/full/` and, unless in the personal mode, the `staff` site into `<dir>/staff/`, write the root redirect `<dir>/_redirects`, and exit 0. `--date` sets the map date and the report date of the `full` site (default: the machine's local date, captured once); a date whose 90-day report window ends after `9999-12-30` is a usage error. A missing `<dir>` is created. - -#### Scenario: Two sites -- **WHEN** the command runs as `stackledger build ./catalogue --out ./public` -- **THEN** `./public/full/index.html` and `./public/staff/index.html` exist and the exit code is 0 - -#### Scenario: Two sites with skills -- **WHEN** the command runs as `stackledger build ./catalogue --out ./public --skills ./skills` -- **THEN** `./public/full/skills/index.html` and `./public/staff/skills/index.html` exist and the exit code is 0 - -### Requirement: Root redirect -`_redirects` SHALL hold exactly `/ /staff/ 302` followed by a newline, or `/ /full/ 302` followed by a newline in the personal mode. - -#### Scenario: Root redirect -- **WHEN** a catalogue without `spec.sites` is built -- **THEN** `_redirects` in the output folder holds exactly `/ /staff/ 302` and a newline - -### Requirement: Personal mode -When the catalogue's Settings choose the personal mode (`spec.sites: [full]`), the command SHALL build and write no file of a staff site. - -#### Scenario: Personal build -- **WHEN** a catalogue whose Settings have `spec.sites: [full]` is built into an empty folder -- **THEN** the exit code is 0, the folder holds `full`, `_headers`, `robots.txt`, `_redirects` holding `/ /full/ 302` and the marker, no `staff`, and stderr names no staff site - -#### Scenario: Stale staff site removed -- **WHEN** a personal build runs into a folder holding an earlier corporate build -- **THEN** `staff` is gone and the folder equals a personal build into an empty folder; a later corporate build brings `staff` back - -#### Scenario: A failed personal build leaves the corporate site -- **WHEN** a personal build over a corporate one fails at any rename before the commit -- **THEN** the exit code is 1 and the corporate build, `staff` included, is unchanged - ### Requirement: Usage errors When `--help` is among the arguments, the command SHALL print usage on stdout and exit 0. Otherwise a missing folder or `--out`, an unknown option, a `--date` that is not a real `YYYY-MM-DD` date, more than one folder, a catalogue folder that does not exist, is not a folder or cannot be read, or an `--out` that is a file SHALL print the reason and usage on stderr and exit 2, without creating or changing anything. @@ -50,7 +17,7 @@ When `--help` is among the arguments, the command SHALL print usage on stdout an - **THEN** the exit code is 2 and nothing is written ### Requirement: Safe output folder -After resolving symbolic links, the output folder SHALL be refused, with exit 2 and no change, when it is the catalogue folder, inside it, contains it, or is a non-empty folder without the marker `.stackledger-build`: a regular file with fixed content, no date or version. It SHALL also be refused when `full`, `staff`, `_headers`, `robots.txt`, `_redirects`, the marker or a `.stackledger-tmp-*` entry is a symbolic link, or a `.stackledger-tmp-*` entry is a file. +After resolving symbolic links, the output folder SHALL be refused, with exit 2 and no change, when it is the catalogue folder, inside it, contains it, or is a non-empty folder without the marker `.stackledger-build`: a regular file with fixed content, no date or version. It SHALL also be refused when any entry of the folder, the marker and a `.stackledger-tmp-*` entry included, is a symbolic link, or a `.stackledger-tmp-*` entry is a file. #### Scenario: Output inside the catalogue - **WHEN** `--out` is `./catalogue/site` @@ -65,7 +32,7 @@ After resolving symbolic links, the output folder SHALL be refused, with exit 2 - **THEN** the exit code is 2 and nothing changes #### Scenario: Linked published entry -- **WHEN** `full` in a marked `--out` is a symbolic link to another folder +- **WHEN** `map` in a marked `--out` is a symbolic link to another folder - **THEN** the exit code is 2 and the link's target is untouched ### Requirement: Interrupted publication @@ -91,7 +58,7 @@ The command SHALL record the output folder's real path and file identity after v - **THEN** the exit code is 1 and the other folder is untouched ### Requirement: Atomic replace -The sites and the root files SHALL be fully prepared in a staging folder `.stackledger-tmp-*` inside the output folder before anything published changes, then published by renames whose last one is the commit point. A failure before the commit SHALL restore every previous entry byte for byte and exit 1. After the commit, a failure to remove the staging folder is a warning, with exit 0. +The site and the root files SHALL be fully prepared in a staging folder `.stackledger-tmp-*` inside the output folder before anything published changes, then published by renames whose last one is the commit point. A failure before the commit SHALL restore every previous entry byte for byte and exit 1. After the commit, a failure to remove the staging folder is a warning, with exit 0. #### Scenario: Rebuild - **WHEN** the command runs twice with the same `--out` @@ -99,17 +66,10 @@ The sites and the root files SHALL be fully prepared in a staging folder `.stack #### Scenario: Failure leaves the old site - **WHEN** a build fails, at any step before the commit, after an earlier successful build into the same `--out` -- **THEN** the earlier sites and root files are unchanged, no `.stackledger-tmp-*` folder remains and the exit code is 1 - -### Requirement: Personal publication -A personal build SHALL mark its staging folder with an empty `full-only` file and move an earlier `staff` into `old/` without putting a new one in place. - -#### Scenario: Undo failed in a personal build -- **WHEN** a personal build over a corporate one fails at a rename and its undo fails too, and the manual restore of `docs/site.md` is followed -- **THEN** the corporate build, `staff` included, is back byte for byte +- **THEN** the earlier site and root files are unchanged, no `.stackledger-tmp-*` folder remains and the exit code is 1 ### Requirement: Publishing the output -The output folder SHALL NOT be served while a build runs. Only `full/`, `staff/` (absent in the personal mode), `_headers`, `robots.txt` and `_redirects` SHALL be published, after an exit code 0; `docs/site.md` SHALL say so, because staging folders hold `full` view files outside the protected `/full/` path. +The output folder SHALL NOT be served while a build runs. After an exit code 0, only the content of the output folder other than the marker `.stackledger-build` and any `.stackledger-tmp-*` entry SHALL be published; `docs/site.md` SHALL say so, because a staging folder holds the build's working files. #### Scenario: Documented - **WHEN** a reader opens `docs/site.md` @@ -120,25 +80,25 @@ The build reads only the catalogue folder and the skill set's files. The build c #### Scenario: Sandboxed build - **WHEN** the command runs with `--skills` under the Node.js permission model with read access to the catalogue folder, the skills folder and the package, write access only to `--out`, and `--allow-addons --allow-child-process --allow-worker`, with `--allow-net` where Node has it and a network trap preloaded that refuses any host other than loopback and reports every server the process opens -- **THEN** both sites are built with their Skills pages, no connection to a host other than loopback is attempted, no server listens on an address other than loopback, and child processes, which the model does not restrict, are outside this check +- **THEN** the site is built with its Skills pages, no connection to a host other than loopback is attempted, no server listens on an address other than loopback, and child processes, which the model does not restrict, are outside this check #### Scenario: Font server on loopback - **WHEN** a build runs - **THEN** every server the build opens listens on 127.0.0.1 and none remains open after the build ### Requirement: Build report -stderr SHALL show, in order: with a catalogue error or warning, one line with both counts and a hint to run `stackledger validate`; the map's suggestion, unrouted-hop and unused-layout lines as `stackledger map` writes them for `full`; the lines of "Skills build report"; one line per site built with its folder and page count; a last line saying the folders must be served behind an identity-aware proxy. A catalogue with errors SHALL still be built, with exit 0. +stderr SHALL show, in order: with a catalogue error or warning, one line with both counts and a hint to run `stackledger validate`; the map's suggestion, unrouted-hop and unused-layout lines as `stackledger map` writes them; the lines of "Skills build report"; one line for the site built with its page count; a last line saying the site shows everything and must be served only behind a sign-in for people who may see it all. A catalogue with errors SHALL still be built, with exit 0. #### Scenario: One error - **WHEN** the catalogue has one error -- **THEN** both sites are built, the exit code is 0 and stderr says there is 1 error +- **THEN** the site is built, the exit code is 0 and stderr says there is 1 error #### Scenario: Proxy reminder - **WHEN** a build succeeds -- **THEN** the last stderr line says the folders must be served behind an identity-aware proxy +- **THEN** the last stderr line says the site shows everything and must be served only behind an identity-aware proxy for the people allowed to see all of it ### Requirement: Deterministic build -The same catalogue, skill files, `--date` and stackledger version SHALL produce byte-identical files in both sites, whatever the order of files and documents in the catalogue folder, the order in which folders list their entries, and where the catalogue and skills folders are on disk, as long as the same documents and items are served. +The same catalogue, skill files, `--date` and stackledger version SHALL produce byte-identical files, whatever the order of files and documents in the catalogue folder, the order in which folders list their entries, and where the catalogue and skills folders are on disk, as long as the same documents and items are served. #### Scenario: Built twice - **WHEN** the same catalogue is built twice with the same `--date` @@ -149,7 +109,7 @@ The same catalogue, skill files, `--date` and stackledger version SHALL produce - **THEN** every file of both builds is identical ### Requirement: Build time -Both sites for a catalogue of 300 items and 20 lines SHALL be built within 90 seconds. +The site for a catalogue of 300 items and 20 lines SHALL be built within 90 seconds. #### Scenario: Large catalogue - **WHEN** a generated catalogue of 300 items and 20 lines is built @@ -160,7 +120,7 @@ The skill set SHALL be read as `stackledger skills validate` reads it, from the #### Scenario: Folders from the settings - **WHEN** the catalogue `cat` has `spec.skills.folders: [../kit]` and the command has no `--skills` -- **THEN** the skill set is read from `cat/../kit` and both sites have the Skills pages +- **THEN** the skill set is read from `cat/../kit` and the site has the Skills pages #### Scenario: The option replaces the settings - **WHEN** the catalogue has `spec.skills.folders: [../missing]`, a folder that does not exist, and the command has `--skills team` @@ -191,11 +151,11 @@ Without `--skills`, when the Settings in use has an error (as catalogue-views de #### Scenario: Unreadable settings file - **WHEN** `settings.yaml` holds a `Settings` document and a YAML syntax error, and the command has no `--skills` -- **THEN** both sites are built without a Skills section, the exit code is 0, and stderr says skill folders could not be read from the settings +- **THEN** the site is built without a Skills section, the exit code is 0, and stderr says skill folders could not be read from the settings #### Scenario: Broken settings without skills - **WHEN** the Settings has an error in `spec.site.colors` and no `spec.skills` -- **THEN** both sites are built without a Skills section and the exit code is 0, as before this change +- **THEN** the site is built without a Skills section and the exit code is 0, as before this change ### Requirement: Skill folder errors An empty `--skills` value, or a skills folder in use that does not exist, is not a folder or cannot be listed, SHALL be a usage error: exit 2, stderr naming the folder as given or written (and `spec.skills.folders` when it comes from there), nothing created or changed. Every exit-2 check, refused output folders included, comes before any exit-1 check; a skills folder in which nothing is found SHALL exit 1 before anything is written, with nothing published changed. @@ -243,12 +203,12 @@ After resolving symbolic links, the output folder SHALL also be refused, with ex - **THEN** the exit code is 2 and nothing is written #### Scenario: Output holds a linked input -- **WHEN** an earlier build exists in `public`, and `skills/writer/rules.md` is a link to `public/full/notes.md` -- **THEN** the command with `--skills skills --out public` exits 2 and `public/full/notes.md` is unchanged +- **WHEN** an earlier build exists in `public`, and `skills/writer/rules.md` is a link to `public/notes.md` +- **THEN** the command with `--skills skills --out public` exits 2 and `public/notes.md` is unchanged #### Scenario: Building inside the skills repository - **WHEN** the command runs at the top of a repository holding `catalog/` and skills as `stackledger build catalog --skills . --out public`, and `public` does not exist -- **THEN** both sites are built into `public` and the exit code is 0 +- **THEN** the site is built into `public` and the exit code is 0 #### Scenario: Output inside a linked skill folder - **WHEN** `tool/writer` links to `kit/skills/writer`, the command has `--skills tool`, and `--out` is `kit/skills/writer/site` @@ -278,12 +238,49 @@ With a skill set, the report SHALL hold, in order: `Skills: <n> skills, <n> play - **THEN** no stderr line holds U+001B ### Requirement: Build time with skills -Both sites for a catalogue of 300 items and 20 lines, with a skill set of 200 skills, 20 playbooks, 10 agents, 2,000 rules and 10 skill lines, SHALL be built within 150 seconds. +The site for a catalogue of 300 items and 20 lines, with a skill set of 200 skills, 20 playbooks, 10 agents, 2,000 rules and 10 skill lines, SHALL be built within 150 seconds. #### Scenario: Large catalogue and skill set - **WHEN** a generated catalogue of 300 items and 20 lines is built with a generated skill set of that size - **THEN** the command finishes within 150 seconds +### Requirement: Build command +`stackledger build <folder> --out <dir> [--date YYYY-MM-DD] [--skills <folder>]...` SHALL build one site at the root of `<dir>`, with `index.html`, `_headers`, `robots.txt`, `_redirects` and the marker `.stackledger-build`, write no `full/` or `staff/` folder, and exit 0. `--date` sets the map date and the report date (default: the machine's local date, captured once); a date whose 90-day report window ends after `9999-12-30` is a usage error. A missing `<dir>` is created. + +#### Scenario: One site at the root +- **WHEN** the command runs as `stackledger build ./catalogue --out ./public` +- **THEN** `./public/index.html`, `./public/map/index.html`, `./public/reports/index.html` and `./public/renewals.ics` exist, `./public/full` and `./public/staff` do not, and the exit code is 0 + +#### Scenario: One site with skills +- **WHEN** the command runs as `stackledger build ./catalogue --out ./public --skills ./skills` +- **THEN** `./public/skills/index.html` exists and the exit code is 0 + +#### Scenario: The staff view is not built +- **WHEN** the catalogue's Settings have `spec.views.staff.hide: [vendor]` and `spec.sites: [full, staff]` +- **THEN** the site is the same as without those two settings, the licences show every field including the vendor, and no `staff` folder exists + +### Requirement: Replace the whole folder +Every entry of a marked output folder other than the marker and the staging folders belongs to the build: publication SHALL move it into the staging folder's `old/` and move the new build's entries into place, so nothing of an earlier build remains, the `full/` and `staff/` folders of a two-site build included. + +#### Scenario: A two-site build is replaced +- **WHEN** `--out` holds a marked build of an earlier version with `full/`, `staff/`, `_redirects` and the marker, and the command runs +- **THEN** the exit code is 0, `full` and `staff` are gone and the folder equals a build into an empty folder + +#### Scenario: A failed replacement keeps the two-site build +- **WHEN** the same build fails at any rename before the commit +- **THEN** the exit code is 1 and the two-site build, `full/` and `staff/` included, is unchanged byte for byte + +### Requirement: Old addresses redirect +`_redirects` SHALL hold exactly the lines `/full / 301` and `/full/* /:splat 301`, each followed by a newline (the Cloudflare Pages and Netlify format), so a link to the former `/full/` site, `renewals.ics` included, reaches the same path at the root. It SHALL hold no rule for `/` or `/staff/`: the former staff site has no destination. + +#### Scenario: Redirect file +- **WHEN** a build succeeds +- **THEN** `_redirects` in the output folder holds exactly `/full / 301`, a newline, `/full/* /:splat 301` and a newline + +#### Scenario: No rule for the staff site +- **WHEN** `_redirects` is read +- **THEN** no line starts with `/staff` and none starts with `/ ` + ### Requirement: Plugin agents folders in the output check The output folder SHALL also be refused, with exit 2 and no change, when it is or is inside the folder an agent file was read from (the folder it was found in, not that of a link's target), a plugin's `agents/` included. diff --git a/openspec/specs/catalogue-pipeline/spec.md b/openspec/specs/catalogue-pipeline/spec.md index 77d3e5a7..87f23d3f 100644 --- a/openspec/specs/catalogue-pipeline/spec.md +++ b/openspec/specs/catalogue-pipeline/spec.md @@ -49,21 +49,6 @@ The `site` job SHALL build with `--date` set to the run's date in UTC, so a re-r - **WHEN** the template workflow is read - **THEN** the build command passes `--date` with the UTC date of the run -### Requirement: What is published -The `site` job SHALL build into a fresh folder outside the repository and hand on only `full/`, `staff/` when the build wrote it (the corporate mode), `_headers`, `robots.txt` and `_redirects`. The `deploy` job SHALL run wrangler from an otherwise empty folder, so no `functions/` folder or wrangler configuration of the catalogue repository can be uploaded. - -#### Scenario: Only the publishable entries -- **WHEN** the `site` job's commands run on the Northwind example -- **THEN** the publish folder holds exactly `full`, `staff`, `_headers`, `robots.txt` and `_redirects`, which sends `/` to `/staff/` - -#### Scenario: Personal mode publishes no staff site -- **WHEN** the `site` and deploy commands run on the template with `spec.sites: [full]` in `catalog/stackledger.yaml` -- **THEN** the publish and deploy folders hold exactly `full`, `_headers`, `robots.txt` and `_redirects`, which sends `/` to `/full/` - -#### Scenario: Repository extras are not deployed -- **WHEN** the catalogue repository also holds `functions/` and `wrangler.toml` and the `site` and collect commands run -- **THEN** the deploy folder holds only `site/` with the publishable entries, and the deploy step's working directory is that folder - ### Requirement: Deploy job A separate `deploy` job, on a fresh runner, SHALL run only after `site` succeeds, on `refs/heads/main`, and not for a pull request. With no checkout, it SHALL install wrangler with `--ignore-scripts` before any secret is present, then run that binary in the only step given `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID`. @@ -163,3 +148,18 @@ The spec SHALL draw the Mermaid block of `docs/how-it-works.md` and nothing else #### Scenario: Diagram sources not published - **WHEN** `package.json` is read - **THEN** its `files` list includes neither `scripts` nor `docs`, nor any path under them + +### Requirement: Published entries +The `site` job SHALL build into a fresh folder outside the repository and hand on the site only: every entry of the build folder except the marker `.stackledger-build` and any `.stackledger-tmp-*` entry. The `deploy` job SHALL run wrangler from an otherwise empty folder, so no `functions/` folder or wrangler configuration of the catalogue repository can be uploaded. + +#### Scenario: Only the site is published +- **WHEN** the `site` job's commands run on the Northwind example +- **THEN** the publish folder holds the build's entries at its root (`index.html`, `map`, `_headers`, `robots.txt`, `_redirects`, `renewals.ics`), whose `_redirects` sends `/full/*` to the root, and no `full`, no `staff`, no marker and no staging folder + +#### Scenario: The settings do not change what is published +- **WHEN** the `site` and deploy commands run on the template with `spec.sites: [full]` in `catalog/stackledger.yaml` +- **THEN** the publish and deploy folders hold the same entries as without it + +#### Scenario: Repository extras are not deployed +- **WHEN** the catalogue repository also holds `functions/` and `wrangler.toml` and the `site` and collect commands run +- **THEN** the deploy folder holds only `site/` with the publishable entries, and the deploy step's working directory is that folder diff --git a/openspec/specs/catalogue-site/spec.md b/openspec/specs/catalogue-site/spec.md index 91ba311a..648cfb59 100644 --- a/openspec/specs/catalogue-site/spec.md +++ b/openspec/specs/catalogue-site/spec.md @@ -5,27 +5,8 @@ Defines the pages of the static catalogue site, what each shows from its view, h ## Requirements -### Requirement: Pages -Each site SHALL have a home page at `/`, a map page at `/map/`, a software list at `/software/`, one page per served component at `/software/<name>/`, one page per served licence at `/licences/<name>/`, a journeys list at `/journeys/` and one page per drawn line at `/journeys/<name>/`, with `<name>` the item's `metadata.name` in lower case. The `full` site SHALL also have `/reports/` and `/renewals.ics`, as `licence-reports` defines. - -#### Scenario: Item pages -- **WHEN** the catalogue has components `editor` and `forge` and licence `licence-editor` -- **THEN** the site has `/software/editor/`, `/software/forge/` and `/licences/licence-editor/` - -#### Scenario: No journeys -- **WHEN** the catalogue has no drawn line -- **THEN** the map page shows `No journeys yet` and the journeys list says there are none - -#### Scenario: Reports in full only -- **WHEN** both sites are built -- **THEN** the `full` site has `/reports/` and `/renewals.ics` and the `staff` site has neither - -#### Scenario: Map at /map/ -- **WHEN** a site is built -- **THEN** `/map/` holds the map of its view, `/` holds the home page with no map on it, and every link labelled `Map` to the software map, in the sub-navigation and the footer, targets `/map/` - ### Requirement: Layout -Every page SHALL share one layout: a header with the site title (from `spec.site.title`, default `stackledger`) linking the home page `/`, and the divisions Software (`/map/`) and, with a skill set, Skills (`/skills/`); under it the division's sub-navigation, for Software: Map (`/map/`), List (`/software/`), Journeys, and Reports in `full`; a footer with the view name and stackledger version; and a theme switch following `prefers-color-scheme` until the reader picks one, then remembering it. +Every page SHALL share one layout: a header with the site title (from `spec.site.title`, default `stackledger`) linking the home page `/`, and the divisions Software (`/map/`) and, with a skill set, Skills (`/skills/`); under it the division's sub-navigation, for Software: Map (`/map/`), List (`/software/`), Journeys and Reports; a footer with the stackledger version and no view name; and a theme switch following `prefers-color-scheme` until the reader picks one, then remembering it. #### Scenario: Theme remembered - **WHEN** the reader chooses dark on one page and opens another page @@ -44,20 +25,20 @@ Every page SHALL share one layout: a header with the site title (from `spec.site - **THEN** the home page `/` of the same site opens #### Scenario: View in the footer -- **WHEN** a page of the `staff` site is opened -- **THEN** its footer says `staff view` +- **WHEN** any page is opened +- **THEN** its footer shows `stackledger` and its version and no view name #### Scenario: Reports link - **WHEN** any Software page is opened -- **THEN** its sub-navigation links Reports in the `full` site and not in the `staff` site +- **THEN** its sub-navigation links Reports (`/reports/`) #### Scenario: Software sub-navigation - **WHEN** the reader opens `/journeys/`, then the page of the journey `ship` - **THEN** the header marks Software, the sub-navigation links Map (`/map/`), List and Journeys, and only on `/journeys/` is Journeys marked with `aria-current="page"` #### Scenario: Skills link -- **WHEN** both sites are built with a skill set, and again without one -- **THEN** every page's header links Skills (`/skills/`) in both sites of the first build and in neither site of the second +- **WHEN** the site is built with a skill set, and again without one +- **THEN** every page's header links Skills (`/skills/`) in the first build and none does in the second ### Requirement: Look and theme The default look SHALL follow brunosouzas.com: its colour tokens for light and dark, its type scale, and its fonts, delivered as "Font delivery" says: Source Sans 3 for text, labels, the map and the diagrams, Source Serif 4 for headings and the wordmark, Source Code Pro for code. `spec.site.colors` SHALL override the matching light-theme tokens only. When the `Settings` in use has an error, the site uses the default title and colours. @@ -126,13 +107,6 @@ A component page SHALL show its title, name, description, type, lifecycle, owner - **WHEN** `editor` is a stop of `old`, a line left with one served stop - **THEN** its page names `old` without a link -### Requirement: Licence page -A licence page SHALL show its title, name, owner and the `spec.licence` fields of the view, the components that use it (each linking to its page), and the impact of removing it. - -#### Scenario: Staff licence page -- **WHEN** the `staff` site shows licence `licence-editor` with default hidden fields -- **THEN** the page shows vendor and status and no cost, currency, cycle, renewal date, payer, seats, vault item or note - ### Requirement: Neighbourhood diagram The neighbourhood diagram SHALL be a safe SVG drawn by stackledger: the item in the centre, its resolved direct dependencies on the left and direct dependants on the right. Next to it, a text list SHALL hold the same items: components and licences link to their pages, other resources are plain text. The page script opens a linked item's page when its box is clicked, or focused and Enter is pressed. @@ -188,25 +162,6 @@ The neighbourhood and strip diagrams SHALL use the map's theme and the design sy - **WHEN** `forge` depends on resource `orders-db`, which is not a licence - **THEN** the `orders-db` box has a dashed outline and no shadow shape, and shows `orders-db` at the box's left inset with `resource` under it, both in the muted colour ("Neighbourhood placeholder box") -### Requirement: Home page -The home page SHALL show a banner with the site title as its `h1`, `spec.site.home.text` or `Your software and skills, mapped.` when unset, and the banner art ("Home banner art"); then a Software card with the view's counts of components, licences and drawn journeys, linking Map, List, Journeys and, in `full`, Reports; and, with a skill set, a Skills card with the counts of skills, playbooks, agents and rules, linking List, Map and Rules. - -#### Scenario: Home in full and staff -- **WHEN** both sites are built from a catalogue with 3 components, 2 licences and 1 drawn journey, and a skill set of 2 skills, 1 playbook, 1 agent and 4 rules -- **THEN** each home shows those counts, both link `/map/`, `/skills/`, `/skill-map/` and `/rules/`, only the `full` home links `/reports/`, and both show the default text - -#### Scenario: Home text -- **WHEN** `spec.site.home.text` is `Northwind tools` -- **THEN** the home banner shows `Northwind tools` and not the default sentence - -#### Scenario: Home without skills -- **WHEN** a site is built without a skill set -- **THEN** its home has no Skills card and no link to `/skills/` - -#### Scenario: Empty catalogue -- **WHEN** the catalogue has no component, licence or journey -- **THEN** the home shows the Software card with three zero counts - ### Requirement: Home page chrome The home page SHALL have no sub-navigation (overriding "Layout" for this page), its header SHALL mark no division, and its `title` element SHALL be the site title alone. @@ -354,7 +309,7 @@ The favicon SHALL be the design system's family mark for stackledger, built from - **THEN** `favicon.svg` is the only image visible in the header in both, inline before the title #### Scenario: No other images -- **WHEN** both sites are built from the example with `spec.site.home.links` holding a link with an icon +- **WHEN** the site is built from the example with `spec.site.home.links` holding a link with an icon - **THEN** every `img` element of every page is the header mark, a footer symbol (`symbol-light.svg` or `symbol-dark.svg`), the home banner or a home link icon ### Requirement: Strip interchange @@ -398,7 +353,7 @@ The zoom in, zoom out and reset buttons of `/map/` and `/skill-map/`, and the li - **THEN** each page's zoom in, zoom out and reset buttons hold, in that order, an inline `svg` equal to the `zoomIn`, `zoomOut` and `reset` icon, the first two with `aria-label` `Zoom in` and `Zoom out`, the third followed by the text `Reset` #### Scenario: Calendar button with an icon -- **WHEN** the `full` site of the example is built +- **WHEN** the site of the example is built - **THEN** the link to `renewals.ics` on `/reports/` starts with an inline `svg` equal to the `download` icon, followed by its text #### Scenario: Icon follows the button colour @@ -470,7 +425,7 @@ The map page SHALL show the map at its initial viewBox width in CSS pixels (one - **THEN** no page contains `OpenStreetMap` ### Requirement: Wordmark -The header's site title SHALL be set in Source Serif 4, italic, weight 700, on every page of both sites and whatever `spec.site.title` holds, in the face the site ships ("Font delivery"). +The header's site title SHALL be set in Source Serif 4, italic, weight 700, on every page and whatever `spec.site.title` holds, in the face the site ships ("Font delivery"). #### Scenario: Wordmark face - **WHEN** any page is opened in the light theme, then in the dark theme @@ -481,11 +436,11 @@ The header's site title SHALL be set in Source Serif 4, italic, weight 700, on e - **THEN** the whole title is set in the same face, style and weight as the default title ### Requirement: Parent brand endorsement -The footer SHALL show, after the view name and stackledger version, the design system's `symbol` as decorative images (`alt=""`, `width` and `height` 16) from the site's own folder, `symbol-light.svg` in the light theme and `symbol-dark.svg` in the dark one, as the header marks do, then `by Bruno Souza`, none inside a link. `scripts/site-art.mjs` SHALL write both from the `symbol` piece on each surface. No SVG file of the sites SHALL hold a `style` element. +The footer SHALL show, after the stackledger version, the design system's `symbol` as decorative images (`alt=""`, `width` and `height` 16) from the site's own folder, `symbol-light.svg` in the light theme and `symbol-dark.svg` in the dark one, as the header marks do, then `by Bruno Souza`, none inside a link. `scripts/site-art.mjs` SHALL write both from the `symbol` piece on each surface. No SVG file of the sites SHALL hold a `style` element. #### Scenario: Footer endorsement -- **WHEN** any page of the `full` or the `staff` site is opened -- **THEN** its footer shows the view name and the stackledger version, then an `img` with `alt=""`, `width` 16, `height` 16 and a relative `src` ending in `symbol-light.svg`, then the same with `symbol-dark.svg`, then `by Bruno Souza`, and no `a` element holds the images or the text +- **WHEN** any page is opened +- **THEN** its footer shows the stackledger version, then an `img` with `alt=""`, `width` 16, `height` 16 and a relative `src` ending in `symbol-light.svg`, then the same with `symbol-dark.svg`, then `by Bruno Souza`, and no `a` element holds the images or the text #### Scenario: Symbol follows the theme - **WHEN** any page is shown in the light theme, then in the dark theme @@ -500,8 +455,8 @@ The footer SHALL show, after the view name and stackledger version, the design s - **THEN** neither has a `script`, `foreignObject` or `style` element, a `style` attribute, an attribute starting with `on`, or an `href` or `url(…)` other than an internal `url(#id)` #### Scenario: No SVG of the sites holds a style -- **WHEN** both sites are built from the example with a home link icon -- **THEN** no `.svg` file of either site holds a `style` element +- **WHEN** the site is built from the example with a home link icon +- **THEN** no `.svg` file of the site holds a `style` element ### Requirement: Font delivery The build SHALL deliver the fonts with Astro's Fonts API and its local provider, naming its files by root-relative paths (`./src/fonts/<file>`). It SHALL move the Fonts API's `<style>` elements ("Accepted font CSS") into one file `_astro/fonts.css`, each `url()` relative to it, linked once where the first was. Every HTML page, in sorted path order, SHALL yield the first one's font CSS; a page that differs or has none, or any other `<style>`, SHALL fail the build before publication. @@ -569,7 +524,7 @@ The icon links SHALL be a `ul` with `role="list"` (VoiceOver drops list semantic - **THEN** the row wraps: at least one anchor has a top different from the first anchor's, the vertical gap between the lines equals the gap between neighbours on a line, both more than 10 pixels, no anchor extends past the page's container, and each is still at least 24 × 24 ### Requirement: External links in a new tab -On every page of both sites, an anchor to another site (an `href` that is an absolute URL: the home links and the map credit, the only ones site-security allows) SHALL have `target="_blank"` and `rel="noopener noreferrer"`, and its accessible name SHALL end with ` (opens in a new tab)`: in `aria-label` for an icon link, in visually hidden text inside the anchor otherwise, so the text on screen does not change. It SHALL NOT get a `title` attribute. +On every page, an anchor to another site (an `href` that is an absolute URL: the home links and the map credit, the only ones site-security allows) SHALL have `target="_blank"` and `rel="noopener noreferrer"`, and its accessible name SHALL end with ` (opens in a new tab)`: in `aria-label` for an icon link, in visually hidden text inside the anchor otherwise, so the text on screen does not change. It SHALL NOT get a `title` attribute. #### Scenario: Text link in a new tab - **WHEN** `spec.site.home.links` lists `Blog` (`https://blog.example.com/`, no icon) @@ -592,16 +547,61 @@ On every page of both sites, an anchor to another site (an `href` that is an abs - **THEN** its `aria-label` is that title escaped followed by ` (opens in a new tab)`, and the home holds no `script` element from it ### Requirement: Internal links in the same tab -Every anchor of both sites whose `href` is relative (a page or file of the same site: header, sub-navigation, cards, tables, item, journey, report and skills pages, the calendar download) SHALL have no `target` attribute and no ` (opens in a new tab)` in its name or text. +Every anchor whose `href` is relative (a page or file of the same site: header, sub-navigation, cards, tables, item, journey, report and skills pages, the calendar download) SHALL have no `target` attribute and no ` (opens in a new tab)` in its name or text. #### Scenario: Only external anchors open a new tab -- **WHEN** the `full` and `staff` sites are built from catalogues with home icon links, home text links and `spec.map.backdrop: london`, and from a catalogue with a skill set +- **WHEN** the site is built from catalogues with home icon links, home text links and `spec.map.backdrop: london`, and from a catalogue with a skill set - **THEN** across every HTML page, each anchor with `target` has an absolute `href` and `target="_blank"`, each anchor with an absolute `href` has `target="_blank"`, `rel="noopener noreferrer"` and no `title`, and no anchor with a relative `href` has `target` or the text `opens in a new tab` #### Scenario: No external link, no new tab -- **WHEN** the sites are built from the example catalogue, which has no home links and no city backdrop +- **WHEN** the site is built from the example catalogue, which has no home links and no city backdrop - **THEN** no page has an anchor with `target` or the text `opens in a new tab` #### Scenario: Internal link in the same tab - **WHEN** the reader clicks the home card's `Map` link in a browser - **THEN** the map page opens in the same tab and no new tab opens + +### Requirement: Site pages +The site SHALL have a home page at `/`, a map page at `/map/`, a software list at `/software/`, one page per served component at `/software/<name>/`, one page per served licence at `/licences/<name>/`, a journeys list at `/journeys/`, one page per drawn line at `/journeys/<name>/`, and `/reports/` and `/renewals.ics`, as `licence-reports` defines, with `<name>` the item's `metadata.name` in lower case. It SHALL have no page under `/full/` or `/staff/`. + +#### Scenario: Item pages +- **WHEN** the catalogue has components `editor` and `forge` and licence `licence-editor` +- **THEN** the site has `/software/editor/`, `/software/forge/` and `/licences/licence-editor/` + +#### Scenario: No journeys +- **WHEN** the catalogue has no drawn line +- **THEN** the map page shows `No journeys yet` and the journeys list says there are none + +#### Scenario: Reports at the root +- **WHEN** the site is built +- **THEN** it has `/reports/` and `/renewals.ics`, and no file under `full/` or `staff/` + +#### Scenario: Map at /map/ +- **WHEN** a site is built +- **THEN** `/map/` holds the map, `/` holds the home page with no map on it, and every link labelled `Map` to the software map, in the sub-navigation and the footer, targets `/map/` + +### Requirement: Home page content +The home page SHALL show a banner with the site title as its `h1`, `spec.site.home.text` or `Your software and skills, mapped.` when unset, and the banner art ("Home banner art"); then a Software card with the view's counts of components, licences and drawn journeys, linking Map, List, Journeys and Reports; and, with a skill set, a Skills card with the counts of skills, playbooks, agents and rules, linking List, Map and Rules. + +#### Scenario: Home counts and links +- **WHEN** the site is built from a catalogue with 3 components, 2 licences and 1 drawn journey, and a skill set of 2 skills, 1 playbook, 1 agent and 4 rules +- **THEN** the home shows those counts, links `/map/`, `/reports/`, `/skills/`, `/skill-map/` and `/rules/`, and shows the default text + +#### Scenario: Home text +- **WHEN** `spec.site.home.text` is `Northwind tools` +- **THEN** the home banner shows `Northwind tools` and not the default sentence + +#### Scenario: Home without skills +- **WHEN** a site is built without a skill set +- **THEN** its home has no Skills card and no link to `/skills/` + +#### Scenario: Empty catalogue +- **WHEN** the catalogue has no component, licence or journey +- **THEN** the home shows the Software card with three zero counts + +### Requirement: Licence page content +A licence page SHALL show its title, name, owner and all the `spec.licence` fields, the components that use it (each linking to its page), and the impact of removing it. + +#### Scenario: Every licence field +- **WHEN** the site shows licence `licence-editor`, which has every licence field +- **THEN** the page shows vendor, status, cost, currency, cycle, renewal date, payer, seats, vault item and note diff --git a/openspec/specs/catalogue-views/spec.md b/openspec/specs/catalogue-views/spec.md index f5f9a662..3ec73d31 100644 --- a/openspec/specs/catalogue-views/spec.md +++ b/openspec/specs/catalogue-views/spec.md @@ -78,3 +78,18 @@ In the `staff` view a hidden field SHALL be absent, not emptied or masked, and n #### Scenario: Order does not reveal the hidden field - **WHEN** the view is `staff` with `renewsOn` hidden and a consumer lists licences - **THEN** they are ordered by reference, not by renewal date + +### Requirement: Staff view deprecated +The `staff` view SHALL stay in the code and be offered only by `stackledger mcp --view staff` and `stackledger map --view staff`; no site SHALL be built from it. Each of those commands, when given `--view staff`, SHALL write one stderr line saying the staff view is deprecated and unused by the site, and the `full` view SHALL stay the default. The `full` view SHALL write no such line. + +#### Scenario: Map in the staff view +- **WHEN** `stackledger map ./catalogue --view staff` runs +- **THEN** the SVG is as before on stdout, the exit code is 0 and stderr has one line saying the staff view is deprecated + +#### Scenario: Map in the full view +- **WHEN** `stackledger map ./catalogue` runs on a catalogue with no problem +- **THEN** stderr is empty + +#### Scenario: Staff view still hides its fields +- **WHEN** a licence has `cost: 120` and the view is `staff` +- **THEN** the view has no `cost`, as before diff --git a/openspec/specs/catalogue/spec.md b/openspec/specs/catalogue/spec.md index 7114f1a0..6868ed37 100644 --- a/openspec/specs/catalogue/spec.md +++ b/openspec/specs/catalogue/spec.md @@ -401,7 +401,7 @@ A `Settings` document SHALL have `metadata.name` and MAY have `metadata.namespac #### Scenario: Staff hide list - **WHEN** a `Settings` document has `spec.views.staff.hide: [cost, renewsOn]` -- **THEN** it has no problem +- **THEN** it has no error and one warning on `spec.views.staff.hide`, and the build reports the warning #### Scenario: Unknown field name in the hide list - **WHEN** `spec.views.staff.hide` lists `price` @@ -478,39 +478,6 @@ An identifier that an earlier component (in document order) already lists for th - **WHEN** one component has `stackledger/brew: forge` and another has `stackledger/npm: forge` - **THEN** neither gets a warning -### Requirement: Site modes -A `Settings` document MAY have `spec.sites`, the list of sites `stackledger build` writes: `[full]` is the personal mode and `[full, staff]`, in any order, the corporate mode. Without `spec.sites` the corporate mode applies. A value other than `full` or `staff`, a repeated value, a list without `full` (`[staff]` alone or an empty list) or a value that is not a list SHALL be an error with the file, line and field. -#### Scenario: Personal mode -- **WHEN** a `Settings` document has `spec.sites: [full]` -- **THEN** it has no problem and the sites to build are `full` only - -#### Scenario: Corporate mode in any order -- **WHEN** a `Settings` document has `spec.sites: [full, staff]` or `[staff, full]` -- **THEN** it has no problem and the sites to build are `full` and `staff` - -#### Scenario: Corporate mode by default -- **WHEN** the catalogue has no `Settings` document, or one without `spec.sites` -- **THEN** the sites to build are `full` and `staff` - -#### Scenario: Staff site alone -- **WHEN** `stackledger.yaml` has `spec.sites: [staff]` on line 6 -- **THEN** it gets an error at `stackledger.yaml` line 6 on `spec.sites` saying `full` is required, and an empty list gets the same error - -#### Scenario: Unknown site -- **WHEN** `spec.sites` lists `full` and, on line 8, `finance` -- **THEN** it gets an error at line 8 on `spec.sites[1]` listing `full` and `staff` - -#### Scenario: Repeated site -- **WHEN** `spec.sites` is `[full, full]` -- **THEN** the second `full` gets exactly one error - -### Requirement: Broken settings choose the corporate mode -While the Settings in use has an error, the corporate mode SHALL apply, on purpose, to fail safe: the staff view then hides every licence field and both sites stay behind the same access control, so a typo never leaves fewer protections than intended. - -#### Scenario: Broken settings build both sites -- **WHEN** the Settings document has `spec.sites: [full]` and an error elsewhere, or `spec.sites: [staff]` -- **THEN** the sites to build are `full` and `staff` - ### Requirement: Skills settings `spec.skills` MAY have `folders`: a list of 1 to 20 paths without repeats, where `stackledger build` reads a skill set, each a non-empty string relative to the catalogue folder: not starting with `/`, `\` or `~`, and not starting with a letter and `:`. `..` is allowed. It MAY also have `map`: one path, relative in the same way, whose last part is exactly `stackledger-skills.yaml`. Any other field under `spec.skills` SHALL be an error. @@ -637,3 +604,41 @@ A home link's `icon` SHALL be one of `github`, `website`, `linkedin`, `email`, ` #### Scenario: Typo under map - **WHEN** a `Settings` document has `spec.map.background: london` - **THEN** it gets an error on `spec.map.background` + +### Requirement: Deprecated site settings +`spec.sites` is deprecated and has no effect: `stackledger build` writes one site whatever it holds. A valid `spec.sites` (a list of `full` and `staff` without repeats that includes `full`) SHALL get a warning on `spec.sites` saying it is ignored because the build writes one site at the root. An invalid one (a value other than `full` or `staff`, a repeated value, a list without `full`, or a value that is not a list) SHALL be an error with the file, line and field, as before. + +#### Scenario: Personal list +- **WHEN** a `Settings` document has `spec.sites: [full]` +- **THEN** it has no error and one warning on `spec.sites`, and the build writes the one site + +#### Scenario: Corporate list +- **WHEN** a `Settings` document has `spec.sites: [full, staff]` or `[staff, full]` +- **THEN** it has no error and one warning on `spec.sites`, and the build writes the one site, with no `staff` folder + +#### Scenario: No sites setting +- **WHEN** the catalogue has no `Settings` document, or one without `spec.sites` +- **THEN** there is no warning about sites + +#### Scenario: Staff site alone +- **WHEN** `stackledger.yaml` has `spec.sites: [staff]` on line 6, or an empty list +- **THEN** it gets an error at `stackledger.yaml` line 6 on `spec.sites` saying `full` is required + +#### Scenario: Unknown site +- **WHEN** `spec.sites` lists `full` and, on line 8, `finance` +- **THEN** it gets an error at line 8 on `spec.sites[1]` listing `full` and `staff` + +#### Scenario: Repeated site +- **WHEN** `spec.sites` is `[full, full]` +- **THEN** the second `full` gets exactly one error + +### Requirement: Deprecated staff hide list +A valid `spec.views.staff.hide` SHALL get a warning on it saying the site shows every licence field, so a catalogue that hid fields from a staff site learns they are no longer hidden. The list is still read by the deprecated staff view of `stackledger mcp` and `stackledger map`. + +#### Scenario: Hide list warning +- **WHEN** a `Settings` document has `spec.views.staff.hide: [cost]` +- **THEN** it has one warning on `spec.views.staff.hide` and the built site shows the cost + +#### Scenario: Invalid hide list +- **WHEN** `spec.views.staff.hide` lists `price` +- **THEN** it gets the error on `spec.views.staff.hide[0]`, not the warning diff --git a/openspec/specs/hosting-recipes/spec.md b/openspec/specs/hosting-recipes/spec.md index 39d484b4..a15e5838 100644 --- a/openspec/specs/hosting-recipes/spec.md +++ b/openspec/specs/hosting-recipes/spec.md @@ -5,28 +5,32 @@ Defines the access-control examples shipped with stackledger: the generic proxy ## Requirements -### Requirement: Generic proxy example -`examples/hosting/Caddyfile` SHALL authenticate every request through `forward_auth` to oauth2-proxy before serving any file. Using only the groups the auth service returns, it SHALL serve `/full/*` to `finance`, every other path to `staff` or `finance`, and answer 403 to any other signed-in request. +### Requirement: Proxy example +`examples/hosting/Caddyfile` SHALL authenticate every request through `forward_auth` to oauth2-proxy before serving any file. Using only the groups the auth service returns, it SHALL serve every path to the group `readers` and answer 403 to any other signed-in request. After authentication it SHALL send `/full` and `/full/*` to the same path under the root with a permanent redirect, and it SHALL NOT redirect `/staff/`. #### Scenario: Anonymous request -- **WHEN** a request without a session asks for `/`, `/staff/`, `/full/`, `/full/renewals.ics` or an asset of either site -- **THEN** no site content is returned +- **WHEN** a request without a session asks for `/`, `/map/`, `/renewals.ics`, an asset of the site, `/full/` or `/full/renewals.ics` +- **THEN** no site content is returned and no redirect to a site path is sent -#### Scenario: Staff identity -- **WHEN** a signed-in identity whose groups hold only `staff` asks for `/staff/` and for `/full/`, `/full/renewals.ics` and an asset under `/full/` -- **THEN** `/staff/` is served and every `/full/` path answers 403 +#### Scenario: Reader +- **WHEN** a signed-in identity whose groups hold `readers` asks for `/`, `/map/`, `/reports/` and `/renewals.ics` +- **THEN** each is served, `/renewals.ics` as `text/calendar` -#### Scenario: Finance identity -- **WHEN** a signed-in identity whose groups hold `finance` asks for `/full/` and `/staff/` -- **THEN** both are served +#### Scenario: Old addresses +- **WHEN** a reader asks for `/full/`, `/full` and `/full/renewals.ics` +- **THEN** each answers 301 with `Location` `/`, `/` and `/renewals.ics` -#### Scenario: Signed in without an allowed group -- **WHEN** a signed-in identity with no groups, or only the group `contractors`, asks for `/`, `/staff/` and `/full/` +#### Scenario: Former staff paths +- **WHEN** a reader asks for `/staff/` +- **THEN** the answer is 404 and nothing redirects it + +#### Scenario: Signed in without the group +- **WHEN** a signed-in identity with no groups, or only the groups `staff` or `contractors`, asks for `/`, `/map/` and `/full/` - **THEN** every path answers 403 #### Scenario: Forged group header -- **WHEN** a staff identity's request, or one with no group, carries its own `X-Auth-Request-Groups: finance` -- **THEN** `/full/` still answers 403, and for the identity with no group `/staff/` too +- **WHEN** a request of an identity with no group carries its own `X-Auth-Request-Groups: readers` +- **THEN** `/` still answers 403 #### Scenario: Auth service down - **WHEN** the auth service cannot be reached diff --git a/openspec/specs/licence-reports/spec.md b/openspec/specs/licence-reports/spec.md index cfb07e9a..cbd67c8b 100644 --- a/openspec/specs/licence-reports/spec.md +++ b/openspec/specs/licence-reports/spec.md @@ -5,17 +5,6 @@ Defines the licence report stackledger computes from the `full` view and a date: ## Requirements -### Requirement: Source and date -The report SHALL be computed from the `full` view only, for a report date and a renewal window of `days` days (default 90). In the `full` site the report date is the same resolved date as the map (`build --date`, or the local date captured once) and the window is 90 days. Nothing of the report SHALL be computed for, or reach any file of, the `staff` site. - -#### Scenario: Not in staff -- **WHEN** both sites are built -- **THEN** the `staff` site has no `/reports/` page, no `renewals.ics` and no link to either - -#### Scenario: Site report date -- **WHEN** the sites are built with `--date 2027-06-01` -- **THEN** the Reports page and the calendar use `2027-06-01` as the report date - ### Requirement: Renewals Among licences with status `active` or `to-confirm`, of any cycle, the report SHALL list those renewing from the report date to the date plus `days`, both included; those renewing before the report date (overdue); and those whose `renewsOn` is `unknown`. Entries are sorted by date, then reference, as the MCP `renewals` tool does. @@ -151,8 +140,19 @@ Each event's `UID` SHALL be derived from the catalogue's calendar namespace (the - **THEN** their events have different UIDs ### Requirement: Reports page -The `full` site SHALL have a Reports page at `/reports/` with the renewals, overdue and unknown dates; the recurring totals per currency with their incomplete counts; the three groupings; the one-off and planned lists; the incomplete licences; and a link to `renewals.ics`. Each licence links to its page. +The site SHALL have a Reports page at `/reports/` with the renewals, overdue and unknown dates; the recurring totals per currency with their incomplete counts; the three groupings; the one-off and planned lists; the incomplete licences; and a link to `renewals.ics`. Each licence links to its page. #### Scenario: Page content -- **WHEN** the `full` site of the example is built +- **WHEN** the site of the example is built - **THEN** `/reports/` shows the GBP totals per month and per year and links `renewals.ics` + +### Requirement: Report source and date +The report SHALL be computed from the `full` view only, for a report date and a renewal window of `days` days (default 90). In the site the report date is the same resolved date as the map (`build --date`, or the local date captured once) and the window is 90 days. + +#### Scenario: Reports at the root +- **WHEN** the site is built +- **THEN** it has `/reports/` and `/renewals.ics`, and the site's sub-navigation links the Reports page + +#### Scenario: Site report date +- **WHEN** the site is built with `--date 2027-06-01` +- **THEN** the Reports page and the calendar use `2027-06-01` as the report date diff --git a/openspec/specs/mcp-server/spec.md b/openspec/specs/mcp-server/spec.md index ce3af0fa..b7f51d2e 100644 --- a/openspec/specs/mcp-server/spec.md +++ b/openspec/specs/mcp-server/spec.md @@ -274,11 +274,11 @@ The server SHALL NOT create, change or delete any file and SHALL NOT open networ - **THEN** every line the server wrote on stdout parses as a JSON-RPC message ### Requirement: Logs -The server SHALL write to stderr one line when it starts, with the absolute folder, the view and the number of tools, and one line for each tool error, with the tool name and the reason. No log line SHALL contain a catalogue value other than the arguments of the call. +The server SHALL write to stderr one line when it starts, with the absolute folder, the view and the number of tools, then, with `--view staff`, one line saying the staff view is deprecated and unused by the site, and one line for each tool error, with the tool name and the reason. No log line SHALL contain a catalogue value other than the arguments of the call. #### Scenario: Start line - **WHEN** the server starts with `--view staff` -- **THEN** stderr has one line naming the folder, `staff` and 4 tools +- **THEN** stderr has one line naming the folder, `staff` and 4 tools, then one line saying the staff view is deprecated #### Scenario: Failed call line - **WHEN** `get_item` is called with `component:ghost` diff --git a/openspec/specs/site-security/spec.md b/openspec/specs/site-security/spec.md index bcacdefe..75b8fec5 100644 --- a/openspec/specs/site-security/spec.md +++ b/openspec/specs/site-security/spec.md @@ -5,30 +5,11 @@ Defines what the built sites may and may not contain or request: one view per si ## Requirements -### Requirement: One view per site -Each site SHALL be built only from its view, in its own Astro build with its own data file and cache. The `staff` site SHALL be built first and contain no hidden value in any file. Its files SHALL NOT depend on `--date` nor on valid values of hidden fields; as `catalogue-views` says, an invalid hidden value MAY unserve its licence, and that is the only allowed effect. - -#### Scenario: No trace of the cost -- **WHEN** a licence has `cost: 98765` and `note: ZETA-NOTE` and the default hidden fields apply -- **THEN** neither `98765` nor `ZETA-NOTE` appears in any file of the `staff` site - -#### Scenario: Staff ignores hidden fields and the date -- **WHEN** two catalogues differ only in valid values of default-hidden licence fields and are built with different `--date` values -- **THEN** their `staff` sites are byte-identical - -#### Scenario: Custom-hidden vendor and status -- **WHEN** `Settings` hides `vendor` and `status`, and two catalogues differ only in valid values of those fields -- **THEN** their `staff` sites are byte-identical and contain no vendor or status text, filter option or marker derived from them - -#### Scenario: Broken settings hide the defaults -- **WHEN** the `Settings` in use has an error -- **THEN** the `staff` site hides the default fields, as the `staff` view does - ### Requirement: No inline code -Pages SHALL contain no inline `script` or `style` element, no `style` attribute and no event-handler attribute; scripts and styles are files of the site. Every page of both sites SHALL carry the same Content Security Policy. +Pages SHALL contain no inline `script` or `style` element, no `style` attribute and no event-handler attribute; scripts and styles are files of the site. Every page SHALL carry the same Content Security Policy. #### Scenario: Same policy everywhere -- **WHEN** both sites are built from the example +- **WHEN** the site is built from the example - **THEN** every HTML page has the same CSP and none has an inline script, inline style or `style` attribute ### Requirement: Content Security Policy @@ -42,11 +23,11 @@ Every HTML page SHALL carry, in a `meta` element, exactly `default-src 'none'; s No `href`, `src`, `srcset`, `action`, `formaction`, `poster` or `data` attribute and no CSS `url()` or `@import` SHALL hold an absolute or protocol-relative URL. Exempt: the SVG namespace in `xmlns`, an `href` of an `a` element in the site's root `index.html` whose decoded value equals a URL of `spec.site.home.links`, and the anchor of "Map credit link". Any other absolute URL, on any page or attribute, fails the build. There are no analytics. #### Scenario: Only local URLs -- **WHEN** both sites are built from the example +- **WHEN** the site is built from the example - **THEN** no such attribute or CSS value starts with a scheme or `//` #### Scenario: Home links are the only external URLs -- **WHEN** both sites are built from the example with `spec.site.home.links` listing `https://example.org/articles/` +- **WHEN** the site is built from the example with `spec.site.home.links` listing `https://example.org/articles/` - **THEN** the build succeeds, and the only attributes holding an absolute URL are the `href` of that `Links` anchor on each home page #### Scenario: Link URL outside the home @@ -57,29 +38,22 @@ No `href`, `src`, `srcset`, `action`, `formaction`, `poster` or `data` attribute When the software map has a city backdrop (catalogue-site, Map backdrop), an `href` of an `a` element in the site's `map/index.html` whose decoded value equals `https://www.openstreetmap.org/copyright` SHALL be exempt from "No external requests" and "Relative URLs". Anywhere else, in any other attribute, or in a site whose map has no city backdrop, that URL SHALL fail the build like any other absolute URL. #### Scenario: Map credit is the only other external URL -- **WHEN** both sites are built from the example with `spec.site.home.links` and `spec.map.backdrop: london` -- **THEN** the build succeeds, and apart from the home links the only attribute holding an absolute URL is the `href` of the credit anchor on each map page, `https://www.openstreetmap.org/copyright` +- **WHEN** the site is built from the example with `spec.site.home.links` and `spec.map.backdrop: london` +- **THEN** the build succeeds, and apart from the home links the only attribute holding an absolute URL is the `href` of the credit anchor on the map page, `https://www.openstreetmap.org/copyright` #### Scenario: Credit URL outside the map page - **WHEN** the build's URL scan meets `https://www.openstreetmap.org/copyright` in an `href` of a page other than `map/index.html`, in a `src` of `map/index.html`, or in an `href` of `map/index.html` of a site whose map has no city backdrop - **THEN** the scan reports it and the build fails before publication -### Requirement: Relative URLs -Every URL SHALL be relative to the file that holds it and resolve inside its site's folder: HTML URL attributes, CSS `url()` and `@import`, JavaScript static and dynamic imports, and asset references through `import.meta.url`. The anchors exempt by "No external requests" are exempt here too. A generated URL form the build does not handle SHALL fail the build before publication. - -#### Scenario: Two sites on one host -- **WHEN** the `full` and `staff` sites are served at `/full/` and `/staff/` of one host and every page is opened -- **THEN** no request leaves the site's prefix and none fails - ### Requirement: Headers file -The build SHALL write `_headers` at the root of the output folder and in each site, applying to `/*` the Content Security Policy above plus `frame-ancestors 'none'`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`, `X-Robots-Tag: noindex, nofollow` and `Permissions-Policy: camera=(), microphone=(), geolocation=()`. +The build SHALL write `_headers` at the root of the output folder, which is the site's root, applying to `/*` the Content Security Policy above plus `frame-ancestors 'none'`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`, `X-Robots-Tag: noindex, nofollow` and `Permissions-Policy: camera=(), microphone=(), geolocation=()`. #### Scenario: Root headers - **WHEN** a build succeeds - **THEN** `<out>/_headers` holds those headers for `/*` ### Requirement: Not indexed -Every page SHALL have `<meta name="robots" content="noindex, nofollow">`. The build SHALL write `robots.txt` with `User-agent: *` and `Disallow: /` at the root of the output folder and in each site. +Every page SHALL have `<meta name="robots" content="noindex, nofollow">`. The build SHALL write `robots.txt` with `User-agent: *` and `Disallow: /` at the root of the output folder, which is the site's root. #### Scenario: Root robots - **WHEN** a build succeeds @@ -95,3 +69,25 @@ Every catalogue text in a page SHALL be HTML-escaped by the template engine. Onl #### Scenario: No icon from catalogue text - **WHEN** the catalogue's site title, line titles and item titles hold `<svg onload=alert(1)>` - **THEN** the built pages show that text literally, and the only inline icons are the six of the site + +### Requirement: URLs relative to the site +Every URL SHALL be relative to the file that holds it and resolve inside its site's folder: HTML URL attributes, CSS `url()` and `@import`, JavaScript static and dynamic imports, and asset references through `import.meta.url`. The anchors exempt by "No external requests" are exempt here too. A generated URL form the build does not handle SHALL fail the build before publication. + +#### Scenario: Any path prefix +- **WHEN** the site is served at `/` of one host and again under `/catalogue/` of another, and every page is opened +- **THEN** no request leaves the site's prefix and none fails + +### Requirement: One site from the full view +The site SHALL be built from the `full` view only, in one Astro build with its own data file and cache, and no file of the output SHALL come from the `staff` view: its allow-lists and its hidden-field list have no effect on the site, which shows every field of every item. Whoever can open the site sees all of it, so `docs/site.md` and `docs/hosting.md` SHALL say that the access policy must name only people allowed to see everything. + +#### Scenario: Staff settings have no effect +- **WHEN** two catalogues differ only in `spec.views.staff.hide` and `spec.sites`, and are built with the same `--date` +- **THEN** every file of the two sites is identical + +#### Scenario: Costs are in the site +- **WHEN** a licence has `cost: 98765` and `note: ZETA-NOTE` +- **THEN** both values appear on the licence page and in the Reports page + +#### Scenario: Hosting says who may sign in +- **WHEN** a reader opens `docs/hosting.md` +- **THEN** it says the Access application covers the root on every address and allows only people who may see everything, including costs, renewal dates, payers, notes and password-manager item names diff --git a/openspec/specs/skills-site/spec.md b/openspec/specs/skills-site/spec.md index 43758aa7..368ae2e2 100644 --- a/openspec/specs/skills-site/spec.md +++ b/openspec/specs/skills-site/spec.md @@ -6,11 +6,11 @@ Defines the Skills section that `stackledger build` adds to each site when it is ## Requirements ### Requirement: Skills pages -When a skill set is built, each site SHALL have the list `/skills/`, the map `/skill-map/`, the rules index `/rules/`, and one page per item: `/skills/<file>/` for a skill, `/playbooks/<file>/` for a playbook and `/agents/<file>/` for an agent, `<file>` being the page file name `stackledger skills map` gives the item, without `.md`. Without a skill set, none of these pages SHALL exist. +When a skill set is built, the site SHALL have the list `/skills/`, the map `/skill-map/`, the rules index `/rules/`, and one page per item: `/skills/<file>/` for a skill, `/playbooks/<file>/` for a playbook and `/agents/<file>/` for an agent, `<file>` being the page file name `stackledger skills map` gives the item, without `.md`. Without a skill set, none of these pages SHALL exist. #### Scenario: Item pages - **WHEN** the set has the skill `writer`, the playbook `release` and the agent `reviewer` -- **THEN** each site has `/skills/writer/`, `/playbooks/release/` and `/agents/reviewer/` +- **THEN** the site has `/skills/writer/`, `/playbooks/release/` and `/agents/reviewer/` #### Scenario: Name that is not a file name - **WHEN** a skill is named `Writer` @@ -31,17 +31,6 @@ Every Skills page SHALL have the Skills division's sub-navigation (catalogue-sit - **WHEN** the reader opens `/rules/` - **THEN** its sub-navigation links the three pages and only `Rules` has `aria-current="page"` -### Requirement: Same skills in every site -The Skills pages SHALL be built from one skill set for every site built, and each Skills page's `main` element SHALL be byte-identical in the `full` and `staff` sites: no field of a skill set is hidden from `staff`. - -#### Scenario: Both sites -- **WHEN** a corporate build has a skill set -- **THEN** every Skills page exists in both sites and its `main` element is the same in both - -#### Scenario: Personal build -- **WHEN** a personal build (`spec.sites: [full]`) has a skill set -- **THEN** the `full` site has the Skills pages and there is no `staff` site - ### Requirement: Skills list `/skills/` SHALL give the counts of skills, playbooks, agents and rules, and a table of every skill, playbook and agent with its name, kind, description and number of rules, sorted by name then kind (skill, playbook, agent) by code point, each row linking to its page. A search box and a kind filter SHALL hide rows as the software list does; without JavaScript the whole table is shown. @@ -257,31 +246,31 @@ On a relation diagram, skills SHALL be `nodeBlock` boxes with radius 6, playbook #### Scenario: Skills map not enlarged - **GIVEN** a 1360-pixel-wide window and the example skills map, whose viewBox is narrower than the room -- **WHEN** the reader opens `/full/skill-map/` +- **WHEN** the reader opens `/skill-map/` - **THEN** the map is as wide as its viewBox, the frame's content box is as wide as the map, and the frame's left and right distances to the content column's edges are equal (each within 1 pixel) #### Scenario: Same ink as the software map - **GIVEN** a 1360-pixel-wide window -- **WHEN** the reader opens `/full/map/` and `/full/skill-map/` +- **WHEN** the reader opens `/map/` and `/skill-map/` - **THEN** neither map shows more than 1.01 pixels per initial viewBox unit, and the software map's pixels per unit are within 5% of the skills map's #### Scenario: Skills map just wider than the room - **GIVEN** a 677-pixel-wide window, so that the room is narrower than the skills map's 675.6-unit viewBox -- **WHEN** the reader opens `/full/skill-map/` +- **WHEN** the reader opens `/skill-map/` - **THEN** the map is as wide as the frame's content box (within 1 pixel) and the page has no horizontal scroll #### Scenario: Skills map on a phone - **GIVEN** a 390-pixel-wide window -- **WHEN** the reader opens `/full/skill-map/` +- **WHEN** the reader opens `/skill-map/` - **THEN** the map is as wide as the frame's content box (within 1 pixel) and the page has no horizontal scroll #### Scenario: Skills zoom keeps the shown size -- **WHEN** the reader presses zoom in twice on `/full/skill-map/`, then drags the map +- **WHEN** the reader presses zoom in twice on `/skill-map/`, then drags the map - **THEN** the map's width and height on the page are the same as before (within 1 pixel) #### Scenario: Skills shown size without JavaScript - **GIVEN** JavaScript is disabled and a 1360-pixel-wide window -- **WHEN** the reader opens `/full/skill-map/` +- **WHEN** the reader opens `/skill-map/` - **THEN** the whole map is shown, as wide as its viewBox (within 1 pixel) ### Requirement: Plugin on skills pages diff --git a/playwright.config.ts b/playwright.config.ts index f359e68d..0ec1d19b 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -1,7 +1,7 @@ /** Browser test of the built sites (catalogue-site task 5.1) and of the skills map's Mermaid diagrams * (skills-mermaid task 2.2, test/browser/skills-map.spec.ts, which renders offline and does not use the * server). Run npm run test:browser; it builds the CLI, then test/browser/serve.mjs builds - * examples/northwind and serves both sites on one origin. + * examples/northwind and serves the site. * Chromium only: npx playwright install chromium once. Kept apart from npm test (vitest). */ import { defineConfig, devices } from '@playwright/test'; @@ -18,7 +18,7 @@ export default defineConfig({ projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'], viewport: { width: 1360, height: 900 } } }], webServer: { command: 'node test/browser/serve.mjs', - url: `http://127.0.0.1:${port}/full/`, + url: `http://127.0.0.1:${port}/`, reuseExistingServer: false, timeout: 120_000, stdout: 'pipe', diff --git a/site/src/components/Footer.astro b/site/src/components/Footer.astro index 088f0240..902e7e10 100644 --- a/site/src/components/Footer.astro +++ b/site/src/components/Footer.astro @@ -21,6 +21,6 @@ const { root } = Astro.props; </ul> </div> <div class="footer-bottom"> - <p class="container">{site.view} view · stackledger {site.version} · <span class="endorsement"><img class="symbol-mark themed-light" src={href(root, 'symbol-light.svg')} alt="" width="16" height="16" /><img class="symbol-mark themed-dark" src={href(root, 'symbol-dark.svg')} alt="" width="16" height="16" /> by Bruno Souza</span> · Look based on the Astroplate theme (MIT)</p> + <p class="container">stackledger {site.version} · <span class="endorsement"><img class="symbol-mark themed-light" src={href(root, 'symbol-light.svg')} alt="" width="16" height="16" /><img class="symbol-mark themed-dark" src={href(root, 'symbol-dark.svg')} alt="" width="16" height="16" /> by Bruno Souza</span> · Look based on the Astroplate theme (MIT)</p> </div> </footer> diff --git a/site/src/components/SubNav.astro b/site/src/components/SubNav.astro index 9b2fc255..1ddd3838 100644 --- a/site/src/components/SubNav.astro +++ b/site/src/components/SubNav.astro @@ -1,6 +1,6 @@ --- // Sub-navigation of a division (catalogue-site, Layout; skills-site, Skills sub-navigation): the -// Software division's Map, List, Journeys and (full site) Reports; the Skills division's List, Map +// Software division's Map, List, Journeys and Reports; the Skills division's List, Map // and Rules. The page itself is marked with aria-current; an item page marks nothing. import { href, site, type Page } from '../lib/site'; @@ -14,7 +14,7 @@ const software = [ { key: 'map', title: 'Map', path: 'map/' }, { key: 'software', title: 'List', path: 'software/' }, { key: 'journeys', title: 'Journeys', path: 'journeys/' }, - ...('report' in site ? [{ key: 'reports', title: 'Reports', path: 'reports/' }] : []), + { key: 'reports', title: 'Reports', path: 'reports/' }, ]; const skills = [ { key: 'skills', title: 'List', path: 'skills/' }, diff --git a/site/src/pages/[reports].astro b/site/src/pages/[reports].astro index b5777659..79ecce95 100644 --- a/site/src/pages/[reports].astro +++ b/site/src/pages/[reports].astro @@ -1,15 +1,13 @@ --- // Reports page (licence-reports, Reports page): renewals, recurring cost per currency and per -// group, one-off and planned costs, incomplete licences and the calendar link. The full site only: -// the route is dynamic so that getStaticPaths can return no page at all when SiteData has no -// report (the staff site), instead of a page that would have to hide itself. All text and amounts +// group, one-off and planned costs, incomplete licences and the calendar link. All text and amounts // are prepared by src/site/data.ts; the tables are plain HTML, with no script. import Base from '../layouts/Base.astro'; import LinkOrText from '../components/LinkOrText.astro'; import { href, rootFor, site } from '../lib/site'; export function getStaticPaths() { - return 'report' in site ? [{ params: { reports: 'reports' }, props: { report: site.report } }] : []; + return [{ params: { reports: 'reports' }, props: { report: site.report } }]; } const { report } = Astro.props; diff --git a/site/src/pages/index.astro b/site/src/pages/index.astro index 7ae260d2..f8044181 100644 --- a/site/src/pages/index.astro +++ b/site/src/pages/index.astro @@ -40,7 +40,7 @@ const textLinks = links.filter(link => !link.icon); <li><a href={href(root, 'map/')}>Map</a></li> <li><a href={href(root, 'software/')}>List</a></li> <li><a href={href(root, 'journeys/')}>Journeys</a></li> - {'report' in site && <li><a href={href(root, 'reports/')}>Reports</a></li>} + <li><a href={href(root, 'reports/')}>Reports</a></li> </ul> </article> { diff --git a/site/src/pages/licences/[name].astro b/site/src/pages/licences/[name].astro index 9ae38891..06a90488 100644 --- a/site/src/pages/licences/[name].astro +++ b/site/src/pages/licences/[name].astro @@ -1,6 +1,6 @@ --- -// Licence page (catalogue-site, Licence page): the licence fields of the view, the components -// that use it and the impact of removing it. The staff view has already dropped hidden fields. +// Licence page (catalogue-site, Licence page content): every licence field, the components +// that use it and the impact of removing it. import Base from '../../layouts/Base.astro'; import Impact from '../../components/Impact.astro'; import LinkOrText from '../../components/LinkOrText.astro'; diff --git a/src/map/command.ts b/src/map/command.ts index 3d58f65f..330791f2 100644 --- a/src/map/command.ts +++ b/src/map/command.ts @@ -7,7 +7,7 @@ import { parseArgs } from 'node:util'; import { resolve } from 'node:path'; import { loadFolder, type Loaded } from '../source.js'; import { validateLoaded, type Catalogue } from '../validate.js'; -import { applyView, resolveBackdrop, resolveHidden, viewNames, type ViewName } from '../views.js'; +import { applyView, resolveBackdrop, resolveHidden, STAFF_DEPRECATED, viewNames, type ViewName } from '../views.js'; import { isDate, localDate } from '../graph.js'; import { buildMapModel } from './model.js'; import { layoutMap, type MapGeometry } from './layout.js'; @@ -76,6 +76,7 @@ export async function mapCommand(args: string[]): Promise<void> { const diagnostics: string[] = []; if (view === 'full') diagnostics.push(...problemCounts('map', catalogue)); + else diagnostics.push(STAFF_DEPRECATED('map').trimEnd()); diagnostics.push(...mapNotes(loaded, catalogue, geometry)); if (diagnostics.length) process.stderr.write(diagnostics.join('\n') + '\n'); process.stdout.write(svg + '\n'); diff --git a/src/mcp.ts b/src/mcp.ts index 5f96e210..ac6aaa6f 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -8,7 +8,7 @@ import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js'; import { z } from 'zod'; import { validateFolder, type Summary } from './validate.js'; import type { Problem } from './source.js'; -import { applyView, resolveHidden, type ViewName } from './views.js'; +import { applyView, resolveHidden, STAFF_DEPRECATED, type ViewName } from './views.js'; import { buildGraph, findItems, gaps, impact, isDate, itemDetail, localDate, lookup, renewals, addDays, type Graph, type ItemKind } from './graph.js'; const version = '0.1.0'; const kinds: readonly ItemKind[] = ['component', 'licence', 'resource', 'line']; @@ -139,4 +139,5 @@ export async function serve(folder: string, view: ViewName): Promise<void> { logToolErrors(transport); // When the client closes stdin, nothing keeps the event loop alive: pending calls finish and the process exits with 0. process.stderr.write(`stackledger mcp: serving ${oneLine(folder)} in the ${view} view with ${offered.length} tools\n`); + if (view === 'staff') process.stderr.write(STAFF_DEPRECATED('mcp')); } diff --git a/src/site/build.ts b/src/site/build.ts index 348801ce..7deb3809 100644 --- a/src/site/build.ts +++ b/src/site/build.ts @@ -1,13 +1,12 @@ -/** Build both sites of a catalogue into a staging folder: the internal building block of - * `stackledger build` (design D1, D2, D8). +/** Build the one site of a catalogue into a staging folder: the internal building block of + * `stackledger build` (design D1, D2, D8; ADR 13). * - * What: prepareBuild(folder or loaded folder, staging, date) validates the catalogue, builds the staff site and then - * the full site, each from its own SiteData, working copy and caches, and writes the root files: - * <staging>/site-staff/ <staging>/site-full/ <staging>/root/{_headers, robots.txt, _redirects, .stackledger-build} - * In the personal mode (Settings spec.sites: [full]) there is no site-staff; the empty file - * <staging>/full-only says so to the publication and to the manual restore. - * Each site also holds `_headers` and `robots.txt`; the full site also holds `renewals.ics`. - * Nothing is written outside `staging`. + * What: prepareBuild(folder or loaded folder, staging, date) validates the catalogue, builds the site + * from the `full` view (one SiteData, working copy and cache) and writes: + * <staging>/site/ the site's entries: pages, `_astro/`, `renewals.ics`, `_headers`, `robots.txt`, `_redirects` + * <staging>/root/.stackledger-build the marker, published last + * <staging>/entries the names of the entries of site/, one per line, for the manual restore + * Nothing is written outside `staging`. The `staff` view is not built: no site comes from it. * * The command (src/site/command.ts) checks the options and the output folder, creates `staging` as * `<out>/.stackledger-tmp-*`, publishes the entries (src/site/publish.ts) and writes the report; @@ -32,13 +31,12 @@ import { basename, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { loadFolder, type Loaded } from '../source.js'; import { validateLoaded, type Catalogue } from '../validate.js'; -import { resolveSites, type ViewName } from '../views.js'; import { siteColorNames } from '../schema.js'; import { mapNotes } from '../map/command.js'; import { buildSiteData, CALENDAR_FILE, type SiteData } from './data.js'; import { ownerNames } from './owners.js'; -import { HEADERS, MARKER, MARKER_NAME, POLICY, redirects, ROBOTS } from './policy.js'; -import { FULL_ONLY } from './staging.js'; +import { HEADERS, MARKER, MARKER_NAME, POLICY, REDIRECTS, ROBOTS } from './policy.js'; +import { ENTRIES_NAME, ROOT_NAME, SITE_NAME } from './staging.js'; import { listFiles, moveFontCss, relativise, scan } from './relative.js'; import { withLoopbackServers } from './loopback.js'; import { buildSkillsData } from './skills-data.js'; @@ -103,9 +101,8 @@ const HEX_COLOUR = /^#[0-9a-fA-F]{6}$/; const ASTRO_PREFERENCES = { devToolbar: { enabled: false } }; export interface BuiltSite { dir: string; pages: number } -/** `notes` are the map's diagnostic lines for the full view, as `stackledger map` writes them; - * `staff` is absent in the personal mode. */ -export interface PreparedBuild { catalogue: Catalogue; staff?: BuiltSite; full: BuiltSite; root: string; notes: string[] } +/** `notes` are the map's diagnostic lines, as `stackledger map` writes them. */ +export interface PreparedBuild { catalogue: Catalogue; site: BuiltSite; root: string; notes: string[] } export function packageVersion(): string { return (JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8')) as { version: string }).version; @@ -133,8 +130,8 @@ function makeWritable(dir: string): void { } } -function prepareWorkingCopy(staging: string, view: ViewName, data: SiteData, hooks: BuildHooks): string { - const work = join(staging, `work-${view}`); +function prepareWorkingCopy(staging: string, data: SiteData, hooks: BuildHooks): string { + const work = join(staging, 'work'); cpSync(siteSource, work, { recursive: true }); makeWritable(work); mkdirSync(join(work, 'src', 'data'), { recursive: true }); @@ -179,7 +176,7 @@ export interface FontConfig { /** The Astro configuration of one build. Exported for test/unit/site-fonts.test.ts: the fonts use only * the local provider and root-relative paths, so the build makes no network call for them. Astro's * own `security.csp` stays off: the site writes its own policy meta, and the scan requires one. */ -export async function astroConfig(staging: string, view: ViewName, work: string): Promise<{ fonts: FontConfig[] } & Record<string, unknown>> { +export async function astroConfig(staging: string, work: string): Promise<{ fonts: FontConfig[] } & Record<string, unknown>> { const { fontProviders } = await import('astro/config'); const fonts = FONT_FAMILIES.map((family): FontConfig => ({ name: family.name, @@ -196,14 +193,14 @@ export async function astroConfig(staging: string, view: ViewName, work: string) output: 'static' as const, trailingSlash: 'always' as const, outDir: join(work, 'dist'), - cacheDir: join(staging, `cache-${view}`, 'astro'), + cacheDir: join(staging, 'cache', 'astro'), integrations: [], fonts, devToolbar: { enabled: false }, prefetch: false, build: { format: 'directory' as const, inlineStylesheets: 'never' as const }, vite: { - cacheDir: join(staging, `cache-${view}`, 'vite'), + cacheDir: join(staging, 'cache', 'vite'), build: { assetsInlineLimit: 0, modulePreload: false }, // Bundle every dependency into the render step, so a package of the same name hoisted // elsewhere in the tree (cookie 0.7 from the MCP SDK) is never picked up instead of Astro's. @@ -214,13 +211,13 @@ export async function astroConfig(staging: string, view: ViewName, work: string) }; } -/** Build one site; `calendar` (full site only) is written as renewals.ics before the scan, so it is - * checked and published with the pages. */ -async function buildView(staging: string, view: ViewName, data: SiteData, hooks: BuildHooks, calendar?: string): Promise<BuiltSite> { - const work = prepareWorkingCopy(staging, view, data, hooks); +/** Build the site; `calendar` is written as renewals.ics before the scan, so it is checked and + * published with the pages. */ +async function buildSite(staging: string, data: SiteData, hooks: BuildHooks, calendar: string): Promise<BuiltSite> { + const work = prepareWorkingCopy(staging, data, hooks); // Telemetry must be off before Astro is first loaded. process.env.ASTRO_TELEMETRY_DISABLED = '1'; - const config = await astroConfig(staging, view, work); + const config = await astroConfig(staging, work); const { build } = await import('astro'); // Astro writes its prerender bundle inside outDir only when outDir is inside the current directory. const previous = process.cwd(); @@ -231,45 +228,39 @@ async function buildView(staging: string, view: ViewName, data: SiteData, hooks: } finally { process.chdir(previous); } - const dir = join(staging, `site-${view}`); + const dir = join(staging, SITE_NAME); renameSync(join(work, 'dist'), dir); - if (calendar !== undefined) writeFileSync(join(dir, CALENDAR_FILE), calendar); + writeFileSync(join(dir, CALENDAR_FILE), calendar); hooks.afterAstro?.(dir); // The Fonts API's inline <style> elements become one stylesheet file, so no page holds inline style. const fontProblems = moveFontCss(dir); - if (fontProblems.length) throw new Error(`The ${view} site has style the build does not allow: ${fontProblems.join('; ')}`); + if (fontProblems.length) throw new Error(`The site has style the build does not allow: ${fontProblems.join('; ')}`); relativise(dir); // The staging folder's absolute path and random name, and the working copy, must not leak into a file. const problems = scan(dir, [staging, work, basename(staging)], data.home.links.map(link => link.url), data.map.credit); - if (problems.length) throw new Error(`The ${view} site has URL forms or inline code the build does not allow: ${problems.join('; ')}`); + if (problems.length) throw new Error(`The site has URL forms or inline code the build does not allow: ${problems.join('; ')}`); writeFileSync(join(dir, '_headers'), HEADERS); writeFileSync(join(dir, 'robots.txt'), ROBOTS); + writeFileSync(join(dir, '_redirects'), REDIRECTS); return { dir, pages: listFiles(dir).filter(file => file.endsWith('.html')).length }; } -/** Build both sites and the root files into `staging`, which must exist and be empty. */ +/** Build the site and the marker into `staging`, which must exist and be empty. */ export async function prepareBuild(folder: string | Loaded, stagingPath: string, date: string, version = packageVersion(), skillSet?: SkillSet, hooks: BuildHooks = {}): Promise<PreparedBuild> { // Astro compares module paths with process.cwd(), which is always the real path (on macOS the - // temporary folder /var is a link to /private/var), so the working copies use the real path too. + // temporary folder /var is a link to /private/var), so the working copy uses the real path too. const staging = realpathSync(stagingPath); const loaded = typeof folder === 'string' ? await loadFolder(folder) : folder; const catalogue = validateLoaded(loaded); - // The staff site is built first, before the full data exists anywhere (site-security, One view per site). const owners = ownerNames(loaded.sources); - const sites = resolveSites(catalogue); - // One Skills section for every site (skills-site, Same skills in every site): built once, copied into each. const skills = skillSet ? buildSkillsData(skillSet) : undefined; - const withSkills = <T extends SiteData>(data: T): T => (skills ? { ...data, skills: skills.data } : data); - const staff = sites.includes('staff') ? await buildView(staging, 'staff', withSkills(buildSiteData(catalogue, 'staff', version, undefined, owners).data), hooks) : undefined; - if (!staff) writeFileSync(join(staging, FULL_ONLY), ''); - const fullData = buildSiteData(catalogue, 'full', version, date, owners); - const full = await buildView(staging, 'full', withSkills(fullData.data), hooks, fullData.calendar); - const root = join(staging, 'root'); + // The site comes from the `full` view only (site-security, One site from the full view). + const siteData = buildSiteData(catalogue, 'full', version, date, owners); + const site = await buildSite(staging, skills ? { ...siteData.data, skills: skills.data } : siteData.data, hooks, siteData.calendar!); + writeFileSync(join(staging, ENTRIES_NAME), readdirSync(site.dir).sort().join('\n') + '\n'); + const root = join(staging, ROOT_NAME); mkdirSync(root); - writeFileSync(join(root, '_headers'), HEADERS); - writeFileSync(join(root, 'robots.txt'), ROBOTS); - writeFileSync(join(root, '_redirects'), redirects(sites)); writeFileSync(join(root, MARKER_NAME), MARKER); - const notes = [...mapNotes(loaded, catalogue, fullData.geometry), ...(skills && skillSet ? skillsReport(skillSet, skills.geometry) : [])]; - return { ...(staff ? { staff } : {}), catalogue, full, root, notes }; + const notes = [...mapNotes(loaded, catalogue, siteData.geometry), ...(skills && skillSet ? skillsReport(skillSet, skills.geometry) : [])]; + return { catalogue, site, root, notes }; } diff --git a/src/site/command.ts b/src/site/command.ts index dcc11c50..0b903a75 100644 --- a/src/site/command.ts +++ b/src/site/command.ts @@ -6,7 +6,7 @@ * not containing it; no staging folder holding `old/` and no `.stackledger-tmp-*` link or file * (staging.ts); then empty or marked by an earlier build with a regular marker file holding the * marker text, and no published entry that is a symbolic link). Only then is the output folder - * created, stale staging folders removed, a new staging folder made, both sites prepared in it + * created, stale staging folders removed, a new staging folder made, the site prepared in it * (build.ts) and published by renames (publish.ts). * * The output folder's real path, device and inode are recorded when it is checked (or created) and @@ -38,11 +38,10 @@ import { refuseSkillsOutput, skillsInUse, skillsStops } from './skills-build.js' import { NODE_FS, type FsOps } from './fs-ops.js'; import { MARKER, MARKER_NAME } from './policy.js'; import { assertSameFolder, FolderChanged, folderIdentity, lstatOrUndefined, within, type FolderIdentity } from './paths.js'; -import { ENTRIES, publish, UndoFailed } from './publish.js'; +import { buildEntries, publish, UndoFailed } from './publish.js'; import { OLD_NAME, removeStaging, STAGING_PREFIX, staleStaging } from './staging.js'; -const PROXY_REMINDER = 'Serve both folders only behind an identity-aware proxy: full/ for the people allowed to see costs, staff/ for everyone else.'; -const PERSONAL_PROXY_REMINDER = 'Serve full/ only behind an identity-aware proxy, for the people allowed to see costs.'; +const PROXY_REMINDER = 'The site shows everything, licences included: serve it only behind a sign-in for people who may see it all.'; /** The real path of `path`, or of its nearest existing ancestor joined with the missing rest. */ function realTarget(path: string, ops: FsOps): string { @@ -94,8 +93,8 @@ function checkOutput(out: string, catalogue: string, ops: FsOps): CheckedOutput throw new Error(`Output folder is not empty and was not written by stackledger build (no ${MARKER_NAME} file with the marker text)`); } // A rename or removal through a link would act outside the output folder: refuse it up front. - const linked = ENTRIES.find(entry => lstatOrUndefined(join(target, entry.name), ops)?.isSymbolicLink()); - if (linked) throw new Error(`Output folder entry ${linked.name} is a symbolic link; stackledger build does not replace links`); + const linked = [...buildEntries(existing.entries), MARKER_NAME].find(name => lstatOrUndefined(join(target, name), ops)?.isSymbolicLink()); + if (linked) throw new Error(`Output folder entry ${linked} is a symbolic link; stackledger build does not replace links`); const identity = { path: target, real: target, dev: existing.stats.dev, ino: existing.stats.ino }; return { target, identity, stale }; } @@ -152,9 +151,8 @@ function report(prepared: PreparedBuild, out: string, warnings: string[]): strin ...problemCounts('build', prepared.catalogue), ...prepared.notes, ...warnings, - ...(prepared.staff ? [`Built the staff site in ${join(out, 'staff')} (${plural(prepared.staff.pages, 'page')})`] : []), - `Built the full site in ${join(out, 'full')} (${plural(prepared.full.pages, 'page')})`, - prepared.staff ? PROXY_REMINDER : PERSONAL_PROXY_REMINDER, + `Built the site in ${out} (${plural(prepared.site.pages, 'page')})`, + PROXY_REMINDER, ]; return lines.join('\n') + '\n'; } diff --git a/src/site/policy.ts b/src/site/policy.ts index 82b3d7c3..0bce151a 100644 --- a/src/site/policy.ts +++ b/src/site/policy.ts @@ -1,4 +1,4 @@ -/** Fixed files and policy of every built site: the Content Security Policy, `_headers`, `robots.txt` +/** Fixed files and policy of the built site: the Content Security Policy, `_headers`, `robots.txt` * and the output-folder marker (site-security, build-command specs). * * Why one module: the layout's CSP meta (written into each working copy as src/data/policy.json), @@ -20,9 +20,10 @@ export const HEADERS = [ export const ROBOTS = 'User-agent: *\nDisallow: /\n'; -/** Cloudflare Pages / Netlify style root redirect: `/` leads to the staff site, or to the full site - * in the personal mode, where there is no staff site. */ -export const redirects = (sites: readonly string[]) => `/ /${sites.includes('staff') ? 'staff' : 'full'}/ 302\n`; +/** Cloudflare Pages / Netlify style redirects: a link to the former `/full/` site (`renewals.ics` + * included) reaches the same path at the root (build-command, Old addresses redirect). There is no + * rule for `/staff/`: that site has no destination (ADR 13). */ +export const REDIRECTS = '/full / 301\n/full/* /:splat 301\n'; /** Written at the root of the output folder; its presence lets a later build replace the folder. */ export const MARKER_NAME = '.stackledger-build'; diff --git a/src/site/publish.ts b/src/site/publish.ts index 27f6f073..eebd8c08 100644 --- a/src/site/publish.ts +++ b/src/site/publish.ts @@ -1,14 +1,16 @@ -/** Atomic publication of a prepared build into the output folder (build-command, Atomic replace and - * Interrupted publication; design D8). Called by src/site/command.ts. +/** Atomic publication of a prepared build into the output folder (build-command: Atomic replace, + * Replace the whole folder and Interrupted publication; design D8). Called by src/site/command.ts. * - * For each entry `staff`, `full`, `_headers`, `robots.txt`, `_redirects` and `.stackledger-build`, in - * that order, the existing entry (if any) is renamed into `<staging>/old/`, then the new one is renamed - * into place. A personal build (FULL_ONLY in the staging folder) has no new `staff`: an earlier one - * only moves into `old/`, so it is removed after the commit. `old/` is created just before the first rename, so a staging folder without it never held - * a published entry (staging.ts). The renames done are recorded in memory only. The rename of the - * marker is the commit point: a failure before it undoes the renames in reverse, so the output - * folder is byte for byte what it was. Renames stay on one filesystem because the staging folder is - * inside the output folder, and none goes through a symbolic link. + * The staged site is `<staging>/site/`: the top-level entries of the one site (index.html, the pages' + * folders, `_astro/`, `renewals.ics`, `_headers`, `robots.txt`, `_redirects`). Every entry of a marked + * output folder other than the marker and the staging folders belongs to the build, so for each name + * in the union of the existing entries and the staged ones, in sorted order, the existing entry (if + * any) is renamed into `<staging>/old/` and the staged one (if any) is renamed into place. The + * staged marker, in `<staging>/root/`, is the last: its rename is the commit point. `old/` is created + * just before the first rename, so a staging folder without it never held a published entry + * (staging.ts). The renames done are recorded in memory only. A failure before the commit undoes + * them in reverse, so the output folder is byte for byte what it was. Renames stay on one filesystem + * because the staging folder is inside the output folder, and none goes through a symbolic link. * * The output folder's identity (paths.ts) is checked immediately before creating `old/` and before * every rename, the undo's included. A mismatch (FolderChanged) stops at once: no further rename, @@ -23,23 +25,18 @@ import { InternalError } from '../errors.js'; import { NODE_FS, type FsOps } from './fs-ops.js'; import { assertSameFolder, FolderChanged, lstatOrUndefined, type FolderIdentity } from './paths.js'; import { MARKER_NAME } from './policy.js'; -import { FULL_ONLY, OLD_NAME, RESTORE_GUIDE } from './staging.js'; - -/** Published entries, in publication order, with their place in the staging folder. The marker is last. */ -export const ENTRIES: readonly { name: string; staged: string }[] = [ - { name: 'staff', staged: 'site-staff' }, - { name: 'full', staged: 'site-full' }, - { name: '_headers', staged: join('root', '_headers') }, - { name: 'robots.txt', staged: join('root', 'robots.txt') }, - { name: '_redirects', staged: join('root', '_redirects') }, - { name: MARKER_NAME, staged: join('root', MARKER_NAME) }, -]; +import { OLD_NAME, RESTORE_GUIDE, ROOT_NAME, SITE_NAME, STAGING_PREFIX } from './staging.js'; /** A publication failed and its undo failed too: the staging folder must be kept. */ export class UndoFailed extends InternalError {} interface Move { from: string; to: string } +/** The entries of `out` that belong to a build: everything but the marker and the staging folders. */ +export function buildEntries(names: readonly string[]): string[] { + return names.filter(name => name !== MARKER_NAME && !name.startsWith(STAGING_PREFIX)).sort(); +} + /** Publish the staged entries of `staging` into `out`. On a failure before the commit, undo every * rename and rethrow; throws FolderChanged or UndoFailed when that is not possible. */ export function publish(out: string, staging: string, identity: FolderIdentity, ops: FsOps = NODE_FS): void { @@ -50,16 +47,19 @@ export function publish(out: string, staging: string, identity: FolderIdentity, done.push({ from, to }); }; try { + // Reads first, the identity check right before the first change: a swap after it is caught by the next rename. + const staged = new Set(buildEntries(ops.readdir(join(staging, SITE_NAME)))); + const names = [...new Set([...buildEntries(ops.readdir(out)), ...staged])].sort(); assertSameFolder(identity, ops); ops.mkdir(join(staging, OLD_NAME)); - const fullOnly = lstatOrUndefined(join(staging, FULL_ONLY), ops) !== undefined; - for (const entry of ENTRIES) { - const target = join(out, entry.name); + for (const name of [...names, MARKER_NAME]) { + const target = join(out, name); const existing = lstatOrUndefined(target, ops); // Never rename through a link (command.ts refuses them before the build; this is the last check). if (existing?.isSymbolicLink()) throw new Error(`${target} is a symbolic link`); - if (existing) move(target, join(staging, OLD_NAME, entry.name)); - if (!(fullOnly && entry.name === 'staff')) move(join(staging, entry.staged), target); + if (existing) move(target, join(staging, OLD_NAME, name)); + if (name === MARKER_NAME) move(join(staging, ROOT_NAME, MARKER_NAME), target); + else if (staged.has(name)) move(join(staging, SITE_NAME, name), target); } } catch (error) { if (error instanceof FolderChanged) throw error; diff --git a/src/site/staging.ts b/src/site/staging.ts index 1e7a0d4a..fffca83b 100644 --- a/src/site/staging.ts +++ b/src/site/staging.ts @@ -23,10 +23,15 @@ export const STAGING_PREFIX = '.stackledger-tmp-'; /** Folder of the staging folder that holds the entries a publication replaces. */ export const OLD_NAME = 'old'; -/** Empty file in the staging folder of a personal build (spec.sites: [full]): it has no staff site, - * so its publication only moves an earlier `staff` into `old/`, and the manual restore keeps a - * `staff` it finds in the output folder. */ -export const FULL_ONLY = 'full-only'; +/** The staged site: the entries of the new build, renamed one by one into the output folder. */ +export const SITE_NAME = 'site'; + +/** The staged marker lives in this folder, so its rename, the commit point, comes last. */ +export const ROOT_NAME = 'root'; + +/** One name per line: the entries of the staged site, so the manual restore knows which names in the + * output folder came from a failed publication (docs/site.md, Restoring after a failed publication). */ +export const ENTRIES_NAME = 'entries'; /** Where a reader learns to restore an output folder by hand. */ export const RESTORE_GUIDE = 'docs/site.md, section "Restoring after a failed publication"'; diff --git a/src/validate.ts b/src/validate.ts index 506a999a..fca5604f 100644 --- a/src/validate.ts +++ b/src/validate.ts @@ -54,6 +54,22 @@ export function sortProblems(problems: Problem[]): Problem[] { return problems.sort((a, b) => compareText(a.path, b.path) || a.line - b.line || a.column - b.column || compareText(a.field ?? '', b.field ?? '') || (a.severity === b.severity ? 0 : a.severity === 'error' ? -1 : 1) || compareText(a.message, b.message)); } +/** Warnings for settings the one-site build no longer uses (ADR 13): `spec.sites` is ignored and + * `spec.views.staff.hide` no longer hides anything on the site. A key with an error of its own gets + * the error only. */ +function deprecatedSettings(source: Source, fieldProblems: readonly Problem[]): Problem[] { + const spec = object(source.value.spec); + const broken = (key: string) => fieldProblems.some(p => p.field === key || p.field?.startsWith(`${key}[`) || p.field?.startsWith(`${key}.`)); + const warnings: Problem[] = []; + if (Object.hasOwn(spec, 'sites') && !broken('spec.sites')) { + warnings.push(problem(source, ['spec', 'sites'], 'Ignored: stackledger build writes one site at the root, so spec.sites has no effect; remove it', 'warning')); + } + const hide = Object.hasOwn(object(object(spec.views).staff), 'hide'); + if (hide && !broken('spec.views.staff.hide')) { + warnings.push(problem(source, ['spec', 'views', 'staff', 'hide'], 'Deprecated: the site shows every licence field, so this list hides nothing on it; only the deprecated staff view of stackledger mcp and map reads it', 'warning')); + } + return warnings; +} export function validateLoaded(loaded: Loaded): Catalogue { const problems = [...loaded.problems]; const identities: Identified[] = []; @@ -101,6 +117,8 @@ export function validateLoaded(loaded: Loaded): Catalogue { } } } + // Deprecated settings (catalogue: Deprecated site settings, Deprecated staff hide list): a warning, never a silent change. + if (kind === 'Settings') problems.push(...deprecatedSettings(source, fieldProblems)); if (fieldProblems.length || !parsed.success) { problems.push(...fieldProblems); return; } entities.push(parsed.data); const secrets = scanSecrets(source); diff --git a/src/views.ts b/src/views.ts index 5717ae74..4adef847 100644 --- a/src/views.ts +++ b/src/views.ts @@ -1,8 +1,9 @@ -/** The full and staff views of a served catalogue. Used by the MCP server and the future site. +/** The full and staff views of a served catalogue. The site is built from `full` only; `staff` is + * deprecated (ADR 13) and kept for `stackledger mcp --view staff` and `stackledger map --view staff`. * Staff entities are rebuilt from allow-lists, never by deleting keys, so a misplaced field cannot pass. * Broken settings fail closed: every licence field is hidden until they are fixed. */ -import { licenceFields, type Component, type Licence, type Line, type MapLayout, type LicenceField, type SiteName, type mapBackdrops } from './schema.js'; +import { licenceFields, type Component, type Licence, type Line, type MapLayout, type LicenceField, type mapBackdrops } from './schema.js'; export type MapBackdrop = typeof mapBackdrops[number]; import type { Catalogue, OtherResource, Served } from './validate.js'; export type ViewName = 'full' | 'staff'; @@ -28,11 +29,8 @@ export function resolveBackdrop(catalogue: Pick<Catalogue, 'problems' | 'served' if (settingsInError(catalogue)) return 'neutral'; return catalogue.served.settings[0]?.spec.map?.backdrop ?? 'neutral'; } -/** Sites to build, in build order: the earliest valid Settings `sites`, or both (the default, also when broken). */ -export function resolveSites(catalogue: Pick<Catalogue, 'problems' | 'served' | 'settingsBroken'>): SiteName[] { - const sites = settingsInError(catalogue) ? undefined : catalogue.served.settings[0]?.spec.sites; - return sites && !sites.includes('staff') ? ['full'] : ['full', 'staff']; -} +/** The stderr line of a command run with `--view staff` (catalogue-views: Staff view deprecated). */ +export const STAFF_DEPRECATED = (command: string) => `stackledger ${command}: the staff view is deprecated and unused by the site, which shows everything (ADR 13); it will be removed\n`; function pick(source: Record<string, unknown>, keys: readonly string[]): Record<string, unknown> { const result: Record<string, unknown> = {}; for (const key of keys) if (Object.hasOwn(source, key) && source[key] !== undefined) result[key] = structuredClone(source[key]); diff --git a/test/browser/serve.mjs b/test/browser/serve.mjs index 2cca89bc..c8ea6cc3 100644 --- a/test/browser/serve.mjs +++ b/test/browser/serve.mjs @@ -1,13 +1,13 @@ /** Local host for the browser test (test/browser/site.spec.ts): builds examples/northwind with the - * built CLI into a new temporary folder, then serves its `full/` and `staff/` sites under /full/ and - * /staff/ of one origin, as a host behind the proxy would. The example is built with its skill set, + * built CLI into a new temporary folder, then serves its one site at the root of the origin, as a host + * behind the proxy would. The example is built with its skill set, * examples/northwind-skills (skills-site). A second, small catalogue (a zone named `Team tools`, a skill - * set with one line, no zones and no rules, `spec.map.backdrop: london`, a 60-character title) is built too, its full site served under /extra/ and its staff site under /extra-staff/. + * set with one line, no zones and no rules, `spec.map.backdrop: london`, a 60-character title) is built too, its site served under /extra/. * * Run through `npm run test:browser` (Playwright starts it as its webServer); needs `npm run build` * first. Port: STACKLEDGER_BROWSER_PORT, default 4410. Like the hosts in docs/site.md it redirects a * folder path without a trailing slash to the path with one, serves index.html for folders, sends the - * headers of `_headers`, and answers 404 for anything else (including the output folder's root). + * headers of `_headers`, and answers 404 for anything else. * The temporary folder is removed when the process ends. */ import { execFileSync } from 'node:child_process'; @@ -57,7 +57,7 @@ for (const plugin of ['writing', 'review']) { execFileSync(process.execPath, [join(root, 'dist', 'cli.js'), 'build', join(extra, 'catalogue'), '--out', join(extra, 'out'), '--date', '2027-06-01', '--skills', join(extra, 'kit'), '--skills', join(extra, 'market')], { stdio: 'inherit' }); -// The journeys example (skills-site, Skills map page): three marketplaces and a loose skill as zones, the map file named by the Settings; its full site is served under /journeys/. +// The journeys example (skills-site, Skills map page): three marketplaces and a loose skill as zones, the map file named by the Settings; its site is served under /skills-journeys/. execFileSync(process.execPath, [join(root, 'dist', 'cli.js'), 'build', join(root, 'examples', 'northwind-journeys', 'catalogue'), '--out', join(base, 'journeys'), '--date', '2027-06-01'], { stdio: 'inherit' }); /** `_headers` lines under `/*` as [name, value] pairs. */ @@ -79,18 +79,18 @@ function isFolder(path) { const server = createServer((request, response) => { const url = new URL(request.url ?? '/', 'http://localhost'); - const path = decodeURIComponent(url.pathname); - const site = /^\/(full|staff|extra-staff|extra|journeys)(\/|$)/.exec(path)?.[1]; - // /extra/ and /extra-staff/ are the small catalogue's full and staff sites, /journeys/ the journeys example's full site. - const small = { extra: 'full', 'extra-staff': 'staff', journeys: 'full' }[site]; - const top = small ? join(site === 'journeys' ? base : extra, site === 'journeys' ? 'journeys' : 'out', small) : join(out, site ?? ''); - const file = small ? normalize(join(top, path.slice(site.length + 1))) : normalize(join(out, path)); - if (!site || !file.startsWith(top) || file.includes(`${sep}.`)) { + // The example is also served under /catalogue/, to prove that nothing depends on the site's own path prefix. + const path = decodeURIComponent(url.pathname).replace(/^\/catalogue(?=\/)/, ''); + // /extra/ is the small catalogue's site and /skills-journeys/ the journeys example's; everything else is the example's, at the root. + const prefix = /^\/(extra|skills-journeys)(\/|$)/.exec(path)?.[1]; + const top = prefix === 'extra' ? join(extra, 'out') : prefix ? join(base, 'journeys') : out; + const file = normalize(join(top, prefix ? path.slice(prefix.length + 1) : path)); + if (!file.startsWith(top) || file.includes(`${sep}.`)) { response.writeHead(404).end('Not found'); return; } if (isFolder(file) && !path.endsWith('/')) { - response.writeHead(301, { Location: `${path}/` }).end(); + response.writeHead(301, { Location: `${url.pathname}/` }).end(); return; } const target = isFolder(file) ? join(file, 'index.html') : file; @@ -110,4 +110,4 @@ const stop = () => { }; process.on('SIGINT', stop); process.on('SIGTERM', stop); -server.listen(port, '127.0.0.1', () => console.log(`Serving ${out} at http://127.0.0.1:${port}/full/ and /staff/`)); +server.listen(port, '127.0.0.1', () => console.log(`Serving ${out} at http://127.0.0.1:${port}/`)); diff --git a/test/browser/site-skills.spec.ts b/test/browser/site-skills.spec.ts index 1e32e190..852a78f5 100644 --- a/test/browser/site-skills.spec.ts +++ b/test/browser/site-skills.spec.ts @@ -1,6 +1,6 @@ /** Browser checks of the Skills section (skills-site spec) and of the zone filter with a multi-word * software zone (catalogue-site, Map interaction). Sites are built by test/browser/serve.mjs: the - * example with examples/northwind-skills under /full/ and /staff/, and a small catalogue under /extra/ + * example with examples/northwind-skills at the root, and a small catalogue under /extra/ * (a zone named `Team tools`, one skill line, no playbook zones, no rules). Run npm run test:browser. */ import { expect, test, type Page } from '@playwright/test'; @@ -22,12 +22,10 @@ test('Pages work under the policy', async ({ page }) => { page.on('console', message => { if (message.type() === 'error') problems.push(message.text()); }); page.on('pageerror', error => problems.push(error.message)); page.on('response', response => { if (response.status() >= 400) problems.push(`HTTP ${response.status()} ${response.url()}`); }); - for (const site of ['full', 'staff']) { - for (const path of ['skills/', 'skill-map/', 'rules/', 'skills/writer/', 'playbooks/publishing/', 'agents/reviewer/']) { - await page.goto(`/${site}/${path}`); - await page.waitForLoadState('networkidle'); - expect(await page.evaluate(() => window.cspViolations), path).toEqual([]); - } + for (const path of ['skills/', 'skill-map/', 'rules/', 'skills/writer/', 'playbooks/publishing/', 'agents/reviewer/']) { + await page.goto(`/${path}`); + await page.waitForLoadState('networkidle'); + expect(await page.evaluate(() => window.cspViolations), path).toEqual([]); } expect(problems).toEqual([]); }); @@ -45,7 +43,7 @@ test('Agents with one name in two plugins', async ({ page }) => { }); test.describe('Skills list', () => { - test.beforeEach(async ({ page }) => { await page.goto('/full/skills/'); }); + test.beforeEach(async ({ page }) => { await page.goto('/skills/'); }); test('Search', async ({ page }) => { await page.locator('[data-search]').fill('REVIEW'); const rows = visibleRows(page); @@ -64,15 +62,15 @@ test.describe('Skills list', () => { }); test.describe('Skills map page', () => { - test.beforeEach(async ({ page }) => { await page.goto('/full/skill-map/'); }); + test.beforeEach(async ({ page }) => { await page.goto('/skill-map/'); }); const svg = (page: Page) => page.locator('.map-canvas.themed-light svg'); test('Station link', async ({ page }) => { await svg(page).locator('g[data-ref="skill:writer"]').click(); - await expect(page).toHaveURL(/\/full\/skills\/writer\/$/); + await expect(page).toHaveURL(/\/skills\/writer\/$/); await page.goBack(); await svg(page).locator('g[data-ref="skill:writer"]').focus(); await page.keyboard.press('Enter'); - await expect(page).toHaveURL(/\/full\/skills\/writer\/$/); + await expect(page).toHaveURL(/\/skills\/writer\/$/); }); test('Highlight a skill line', async ({ page }) => { const chip = page.locator('[data-map-lines] button[data-line="line:publish"]'); @@ -99,19 +97,19 @@ test.describe('Skills map page', () => { }); test('Box link', async ({ page }) => { - await page.goto('/full/skills/writer/'); + await page.goto('/skills/writer/'); const box = page.locator('[data-diagram] .themed-light svg g[data-ref="playbook:publishing"]'); await box.click(); - await expect(page).toHaveURL(/\/full\/playbooks\/publishing\/$/); + await expect(page).toHaveURL(/\/playbooks\/publishing\/$/); await page.goBack(); await box.focus(); await page.keyboard.press('Enter'); - await expect(page).toHaveURL(/\/full\/playbooks\/publishing\/$/); + await expect(page).toHaveURL(/\/playbooks\/publishing\/$/); }); test.describe('Rules index', () => { test('Search rules', async ({ page }) => { - await page.goto('/full/rules/'); + await page.goto('/rules/'); await page.locator('[data-search]').fill('voi-01'); await expect(visibleRows(page)).toHaveCount(1); expect((await visibleRows(page).innerText()).toLowerCase()).toContain('voi-01'); @@ -133,13 +131,13 @@ test('Zone with a space in its name', async ({ page }) => { test.describe('Without JavaScript', () => { test.use({ javaScriptEnabled: false }); test('Without JavaScript', async ({ page }) => { - await page.goto('/staff/skills/'); + await page.goto('/skills/'); const rows = page.locator('[data-software] tbody tr'); await expect(visibleRows(page)).toHaveCount(await rows.count()); await expect(page.locator('[data-list-tools]')).toBeHidden(); }); test('Map without JavaScript', async ({ page }) => { - await page.goto('/staff/skill-map/'); + await page.goto('/skill-map/'); await expect(page.locator('.map-canvas.themed-light svg')).toBeVisible(); await expect(page.locator('[data-map-tools]')).toBeHidden(); // Whole, at the size "Skills map shown size" gives (the example map fits the 1360-pixel window). @@ -148,7 +146,7 @@ test.describe('Without JavaScript', () => { }); test('Skills shown size without JavaScript', async ({ page }) => { await page.setViewportSize({ width: 1360, height: 900 }); - await page.goto('/full/skill-map/'); + await page.goto('/skill-map/'); await expect(page.locator('.map-canvas.themed-light svg')).toBeVisible(); const size = await mapSize(page); expect(Math.abs(size.width - size.viewBoxWidth)).toBeLessThanOrEqual(1); @@ -159,7 +157,7 @@ test.describe('Without JavaScript', () => { test.describe('Skills map shown size', () => { test('Skills map not enlarged', async ({ page }) => { await page.setViewportSize({ width: 1360, height: 900 }); - await page.goto('/full/skill-map/'); + await page.goto('/skill-map/'); const size = await mapSize(page); expect(Math.abs(size.width - size.viewBoxWidth)).toBeLessThanOrEqual(1); expect(Math.abs(size.frameContentWidth - size.width)).toBeLessThanOrEqual(1); @@ -167,9 +165,9 @@ test.describe('Skills map shown size', () => { }); test('Same ink as the software map', async ({ page }) => { await page.setViewportSize({ width: 1360, height: 900 }); - await page.goto('/full/map/'); + await page.goto('/map/'); const software = await mapSize(page); - await page.goto('/full/skill-map/'); + await page.goto('/skill-map/'); const skills = await mapSize(page); const softwareScale = software.width / software.viewBoxWidth; const skillsScale = skills.width / skills.viewBoxWidth; @@ -179,7 +177,7 @@ test.describe('Skills map shown size', () => { }); test('Skills map just wider than the room', async ({ page }) => { await page.setViewportSize({ width: 677, height: 900 }); - await page.goto('/full/skill-map/'); + await page.goto('/skill-map/'); const size = await mapSize(page); expect(size.frameContentWidth).toBeLessThan(size.viewBoxWidth); expect(Math.abs(size.width - size.frameContentWidth)).toBeLessThanOrEqual(1); @@ -187,13 +185,13 @@ test.describe('Skills map shown size', () => { }); test('Skills map on a phone', async ({ page }) => { await page.setViewportSize({ width: 390, height: 900 }); - await page.goto('/full/skill-map/'); + await page.goto('/skill-map/'); const size = await mapSize(page); expect(Math.abs(size.width - size.frameContentWidth)).toBeLessThanOrEqual(1); expect(size.pageScrolls).toBe(false); }); test('Skills zoom keeps the shown size', async ({ page }) => { - await page.goto('/full/skill-map/'); + await page.goto('/skill-map/'); const before = await mapSize(page); await page.getByRole('button', { name: 'Zoom in' }).click(); await page.getByRole('button', { name: 'Zoom in' }).click(); @@ -210,7 +208,7 @@ test.describe('Skills map shown size', () => { test.describe('Journeys and marketplace zones', () => { const svg = (page: Page) => page.locator('[data-map] svg').first(); - test.beforeEach(async ({ page }) => { await page.goto('/journeys/skill-map/'); }); + test.beforeEach(async ({ page }) => { await page.goto('/skills-journeys/skill-map/'); }); test('Filter label and options', async ({ page }) => { await expect(page.locator('label.map-zone')).toContainText('Marketplace'); await expect(page.locator('[data-zone-filter] option').first()).toHaveText('All marketplaces'); diff --git a/test/browser/site.spec.ts b/test/browser/site.spec.ts index 502fb873..a98dff19 100644 --- a/test/browser/site.spec.ts +++ b/test/browser/site.spec.ts @@ -1,11 +1,11 @@ -/** Browser checks of the built Northwind sites (catalogue-site task 5.1), served under /full/ and - * /staff/ of one origin by test/browser/serve.mjs. Run npm run test:browser (Chromium). +/** Browser checks of the built Northwind sites (catalogue-site task 5.1), served at the root of one origin by + * test/browser/serve.mjs. Run npm run test:browser (Chromium). * * Every page of both sites is opened under the fixed CSP: no policy violation (DOM event and console), * no failed request, no request outside the page's site prefix and none to another origin. Then the * interactions of the catalogue-site spec: zoom, reset, pan, zone filter, line highlight, station * links (click and Enter), diagram links, search, nothing matches, the remembered theme, and the - * map and table without JavaScript, and the full site's Reports page and calendar file (licence-reports). + * map and table without JavaScript, and the Reports page and calendar file (licence-reports). * Data is the fictitious example in examples/northwind. */ import { expect, test, type Locator, type Page } from '@playwright/test'; @@ -67,29 +67,26 @@ async function crawl(page: Page, prefix: string): Promise<string[]> { return [...seen].sort(); } -for (const site of ['full', 'staff']) { - test(`Pages work under the policy and stay in /${site}/ (Two sites on one host)`, async ({ page }) => { - test.setTimeout(120_000); - const prefix = `/${site}/`; - const watched = await watch(page, prefix); - const paths = await crawl(page, prefix); - // Map, list, journeys list, reports, 17 components, 14 licences and 7 journeys. - expect(paths.length).toBeGreaterThanOrEqual(40); - for (const kind of ['software/', 'licences/', 'journeys/']) expect(paths.some(path => path.startsWith(prefix + kind) && path !== prefix + kind)).toBe(true); - for (const path of paths) { - await page.goto(path); - await page.waitForLoadState('networkidle'); - expect(await violations(page), path).toEqual([]); - // The page script ran (the theme switch is shown by it). - await expect(page.locator('[data-theme-switch]'), path).toBeVisible(); - } - expect(watched.problems).toEqual([]); - }); -} +for (const prefix of ['/', '/catalogue/']) test(`Pages work under the policy and stay in ${prefix} (One site on one host, any path prefix)`, async ({ page }) => { + test.setTimeout(120_000); + const watched = await watch(page, prefix); + const paths = await crawl(page, prefix); + // Map, list, journeys list, reports, 17 components, 14 licences and 7 journeys. + expect(paths.length).toBeGreaterThanOrEqual(40); + for (const kind of ['software/', 'licences/', 'journeys/']) expect(paths.some(path => path.startsWith(prefix + kind) && path !== prefix + kind)).toBe(true); + for (const path of paths) { + await page.goto(path); + await page.waitForLoadState('networkidle'); + expect(await violations(page), path).toEqual([]); + // The page script ran (the theme switch is shown by it). + await expect(page.locator('[data-theme-switch]'), path).toBeVisible(); + } + expect(watched.problems).toEqual([]); +}); test('The violation detector works (positive control)', async ({ page }) => { - await watch(page, '/full/'); - await page.goto('/full/'); + await watch(page, '/'); + await page.goto('/'); await page.evaluate(() => document.body.setAttribute('style', 'color: red')); await expect.poll(() => violations(page)).toContainEqual(expect.stringMatching(/^style-src/)); }); @@ -102,7 +99,7 @@ async function viewBox(page: Page): Promise<number[]> { test.describe('Map page', () => { test.beforeEach(async ({ page }) => { - await page.goto('/full/map/'); + await page.goto('/map/'); }); test('Zoom', async ({ page }) => { @@ -129,7 +126,7 @@ test.describe('Map page', () => { const moved = await viewBox(page); expect(moved[0]).toBeLessThan(initial[0]!); expect(moved[1]).toBeGreaterThan(initial[1]!); - expect(page.url()).toMatch(/\/full\/map\/$/); + expect(page.url()).toMatch(/\/map\/$/); }); test('Highlight a line', async ({ page }) => { @@ -162,7 +159,7 @@ test.describe('Map page', () => { test('Station link (click)', async ({ page }) => { await page.locator('.map-canvas.themed-light svg g[data-ref="component:slack"]').click(); - await expect(page).toHaveURL(/\/full\/software\/slack\/$/); + await expect(page).toHaveURL(/\/software\/slack\/$/); await expect(page.locator('h1')).toHaveText('Slack'); }); @@ -171,31 +168,31 @@ test.describe('Map page', () => { await expect(station).toHaveAttribute('role', 'link'); await station.focus(); await page.keyboard.press('Enter'); - await expect(page).toHaveURL(/\/full\/software\/slack\/$/); + await expect(page).toHaveURL(/\/software\/slack\/$/); }); }); test.describe('Diagram links', () => { test('Neighbourhood box (click and Enter)', async ({ page }) => { - await page.goto('/full/software/slack/'); + await page.goto('/software/slack/'); const box = page.locator('.diagram.themed-light svg g[data-ref="resource:licence-slack"]'); await box.click(); - await expect(page).toHaveURL(/\/full\/licences\/licence-slack\/$/); + await expect(page).toHaveURL(/\/licences\/licence-slack\/$/); await page.goBack(); await page.locator('.diagram.themed-light svg g[data-ref="resource:licence-slack"]').focus(); await page.keyboard.press('Enter'); - await expect(page).toHaveURL(/\/full\/licences\/licence-slack\/$/); + await expect(page).toHaveURL(/\/licences\/licence-slack\/$/); }); test('Journey strip stop and interchange badge', async ({ page }) => { - await page.goto('/staff/journeys/ship/'); + await page.goto('/journeys/ship/'); await page.locator('.diagram.themed-light svg g[data-ref="component:linear"]').click(); - await expect(page).toHaveURL(/\/staff\/software\/linear\/$/); + await expect(page).toHaveURL(/\/software\/linear\/$/); await page.goBack(); const badge = page.locator('.diagram.themed-light svg g[data-ref^="line:"]:not([data-ref="line:ship"])').first(); const ref = await badge.getAttribute('data-ref'); await badge.click(); - await expect(page).toHaveURL(new RegExp(`/staff/journeys/${ref!.slice('line:'.length)}/$`)); + await expect(page).toHaveURL(new RegExp(`/journeys/${ref!.slice('line:'.length)}/$`)); }); }); @@ -203,7 +200,7 @@ test.describe('Software list', () => { const visibleRows = (page: Page) => page.locator('[data-software] tbody tr:visible'); test('Search', async ({ page }) => { - await page.goto('/full/software/'); + await page.goto('/software/'); const total = await visibleRows(page).count(); await page.locator('[data-search]').fill('north'); for (const text of await visibleRows(page).allTextContents()) expect(text.toLowerCase()).toContain('north'); @@ -218,7 +215,7 @@ test.describe('Software list', () => { }); test('Filters', async ({ page }) => { - await page.goto('/full/software/'); + await page.goto('/software/'); await page.locator('select[data-filter="kind"]').selectOption('licence'); const kinds = await page.locator('[data-software] tbody tr:visible td[data-column="kind"]').allTextContents(); expect(kinds.length).toBeGreaterThan(0); @@ -226,7 +223,7 @@ test.describe('Software list', () => { }); test('Nothing matches', async ({ page }) => { - await page.goto('/full/software/'); + await page.goto('/software/'); await page.locator('[data-search]').fill('zzz-no-such-item'); await expect(visibleRows(page)).toHaveCount(0); await expect(page.locator('[data-no-match]')).toBeVisible(); @@ -235,11 +232,11 @@ test.describe('Software list', () => { }); test('Theme remembered', async ({ page }) => { - await page.goto('/full/map/'); + await page.goto('/map/'); await expect(page.locator('.map-canvas.themed-light')).toBeVisible(); await page.locator('[data-theme-switch]').click(); await expect(page.locator('html')).toHaveAttribute('data-theme', 'dark'); - await page.goto('/full/software/slack/'); + await page.goto('/software/slack/'); await expect(page.locator('html')).toHaveAttribute('data-theme', 'dark'); await expect(page.locator('[data-theme-switch]')).toHaveAttribute('aria-checked', 'true'); await expect(page.locator('.diagram.themed-dark')).toBeVisible(); @@ -256,7 +253,7 @@ const frameOf = (page: Page, selector: string) => page.locator(selector).first() test('Banner keeps its ratio', async ({ page }) => { for (const width of [375, 1440]) { await page.setViewportSize({ width, height: 900 }); - await page.goto('/full/'); + await page.goto('/'); const sizes = await page.locator('.home-banner-art').evaluate(image => { const box = image.getBoundingClientRect(), container = image.parentElement!; const style = getComputedStyle(container); @@ -296,7 +293,7 @@ for (const [how, set] of [ ] as const) { test(`Mark follows the theme (${how})`, async ({ page }) => { for (const scheme of ['light', 'dark'] as const) { - await page.goto('/full/map/'); + await page.goto('/map/'); await set(page, scheme); // The brand link is a flex box, so its shown mark is a flex item (computed display block). expect((await shownImages(page, '.navbar-brand img')).map(([src]) => src), scheme).toEqual(['favicon.svg']); @@ -309,7 +306,7 @@ for (const [how, set] of [ // catalogue-site "Parent brand endorsement": one symbol per theme, inline before "by Bruno Souza". test(`Symbol follows the theme (${how})`, async ({ page }) => { for (const scheme of ['light', 'dark'] as const) { - await page.goto('/staff/software/'); + await page.goto('/software/'); await set(page, scheme); expect(await shownImages(page, '.footer-bottom img'), scheme).toEqual([[`symbol-${scheme}.svg`, 'inline']]); const after = await page.locator(`.footer-bottom img.themed-${scheme}`).evaluate(image => { @@ -334,7 +331,7 @@ for (const [how, set] of [ // (:root[data-theme]), which tokens.css styles in separate blocks. for (const scheme of ['light', 'dark'] as const) { test(`Card frame in ${scheme} (${how})`, async ({ page }) => { - await page.goto('/full/'); + await page.goto('/'); await set(page, scheme); expect(await frameOf(page, '.card')).toEqual(FRAME[scheme]); expect(await page.evaluate(() => getComputedStyle(document.body).backgroundColor)).toBe(BODY[scheme]); @@ -343,7 +340,7 @@ for (const [how, set] of [ test(`Pressed button keeps its frame (${how})`, async ({ page }) => { for (const scheme of ['light', 'dark'] as const) { - await page.goto('/full/map/'); + await page.goto('/map/'); await set(page, scheme); const chip = page.locator('.line-chips .btn').first(); await chip.hover(); @@ -359,7 +356,7 @@ for (const [how, set] of [ test('Colour on primary', async ({ page }) => { for (const scheme of ['light', 'dark'] as const) { await page.emulateMedia({ colorScheme: scheme }); - await page.goto('/full/map/'); + await page.goto('/map/'); const button = page.getByRole('button', { name: 'Zoom in' }); await button.hover(); // The button's colour transition is 0.2s. @@ -370,7 +367,7 @@ test('Colour on primary', async ({ page }) => { test('Accent readable on the page', async ({ page }) => { for (const scheme of ['light', 'dark'] as const) { await page.emulateMedia({ colorScheme: scheme }); - await page.goto('/full/'); + await page.goto('/'); const colours = await page.evaluate(() => { const probe = document.createElement('span'); probe.style.setProperty('color', 'var(--color-accent)'); @@ -392,7 +389,7 @@ test('Accent readable on the page', async ({ page }) => { test('Focus still visible', async ({ page }) => { for (const [scheme, accent] of [['light', ACCENT.light], ['dark', ACCENT.dark]] as const) { await page.emulateMedia({ colorScheme: scheme }); - await page.goto('/full/map/'); + await page.goto('/map/'); const chips = page.locator('.line-chips .btn'); // Reach the second chip with the keyboard, so the browser treats the focus as keyboard focus. await chips.first().focus(); @@ -517,10 +514,10 @@ test('No combined image', async ({ page }) => { }); test('The Reports page under the CSP', async ({ page }) => { - const watched = await watch(page, '/full/'); - await page.goto('/full/'); + const watched = await watch(page, '/'); + await page.goto('/'); await page.getByRole('link', { name: 'Reports', exact: true }).first().click(); - await expect(page).toHaveURL(/\/full\/reports\/$/); + await expect(page).toHaveURL(/\/reports\/$/); await page.waitForLoadState('networkidle'); await expect(page.getByRole('heading', { level: 1, name: 'Reports' })).toBeVisible(); await expect(page.locator('table[data-report="recurring"] tbody tr').first()).toContainText('GBP'); @@ -532,21 +529,17 @@ test('The Reports page under the CSP', async ({ page }) => { expect(await calendar.text()).toMatch(/^BEGIN:VCALENDAR\r\n/); expect(await violations(page)).toEqual([]); expect(watched.problems).toEqual([]); - // The staff site has neither the page nor a link to it. - await page.goto('/staff/'); - await expect(page.getByRole('link', { name: 'Reports', exact: true })).toHaveCount(0); - expect((await page.request.get('/staff/reports/')).status()).toBe(404); }); test.describe('Without JavaScript', () => { test.use({ javaScriptEnabled: false }); test('The map and the full table are shown', async ({ page }) => { - await page.goto('/staff/map/'); + await page.goto('/map/'); await expect(page.locator('.map-canvas.themed-light svg')).toBeVisible(); await expect(page.locator('[data-map-tools]')).toBeHidden(); await expect(page.locator('[data-map-lines]')).toBeVisible(); - await page.goto('/staff/software/'); + await page.goto('/software/'); const rows = page.locator('[data-software] tbody tr'); expect(await rows.count()).toBeGreaterThan(20); await expect(page.locator('[data-software] tbody tr:visible')).toHaveCount(await rows.count()); @@ -558,7 +551,7 @@ test.describe('Without JavaScript', () => { test('Icon follows the button colour', async ({ page }) => { for (const scheme of ['light', 'dark'] as const) { await page.emulateMedia({ colorScheme: scheme }); - await page.goto('/full/map/'); + await page.goto('/map/'); const button = page.getByRole('button', { name: 'Zoom in' }); const paint = () => button.evaluate(element => { const path = element.querySelector('svg path')!; @@ -579,14 +572,14 @@ test('Icon follows the button colour', async ({ page }) => { test('Theme switch icons', async ({ page }) => { for (const scheme of ['light', 'dark'] as const) { await page.emulateMedia({ colorScheme: scheme }); - await page.goto('/full/'); + await page.goto('/'); const shown = await page.locator('[data-theme-switch] svg').evaluateAll(icons => icons .filter(icon => icon.getBoundingClientRect().width > 0) .map(icon => icon.parentElement!.className)); expect(shown, scheme).toEqual([scheme === 'light' ? 'icon-sun' : 'icon-moon']); } // Each wrapper holds its own icon, as the build wrote it (not swapped). - const html = await (await page.request.get('/full/')).text(); + const html = await (await page.request.get('/')).text(); expect(html).toContain(`<span class="icon-sun">${siteIcons().sun}</span>`); expect(html).toContain(`<span class="icon-moon">${siteIcons().moon}</span>`); }); @@ -604,14 +597,14 @@ test.describe('Map shown size', () => { }); test('Map wider than the page', async ({ page }) => { await page.setViewportSize({ width: 390, height: 900 }); - await page.goto('/full/map/'); + await page.goto('/map/'); const size = await mapSize(page); expect(Math.abs(size.width - size.frameContentWidth)).toBeLessThanOrEqual(1); expect(Math.abs(size.height - size.width * size.viewBoxHeight / size.viewBoxWidth)).toBeLessThanOrEqual(1); expect(size.pageScrolls).toBe(false); }); test('Zoom keeps the shown size', async ({ page }) => { - await page.goto('/full/map/'); + await page.goto('/map/'); const before = await mapSize(page); await page.getByRole('button', { name: 'Zoom in' }).click(); await page.getByRole('button', { name: 'Zoom in' }).click(); @@ -679,16 +672,16 @@ test('The reader keeps their place', async ({ context, page }) => { // catalogue-site, Internal links in the same tab. test('Internal link in the same tab', async ({ context, page }) => { - await page.goto('/full/'); + await page.goto('/'); const card = page.locator('.home-cards .card').filter({ has: page.getByRole('heading', { name: 'Software' }) }); await card.getByRole('link', { name: 'Map', exact: true }).click(); - await expect(page).toHaveURL(/\/full\/map\/$/); + await expect(page).toHaveURL(/\/map\/$/); expect(context.pages()).toEqual([page]); }); -// catalogue-site, Map backdrop: /extra/ and /extra-staff/ are the full and staff sites of a scratch catalogue +// catalogue-site, Map backdrop: /extra/ is the site of a scratch catalogue // with spec.map.backdrop: london (test/browser/serve.mjs). -const cityViews = ['/extra/', '/extra-staff/']; +const cityViews = ['/extra/']; test.describe('Map backdrop', () => { test('London map on the page', async ({ page }) => { for (const view of cityViews) { @@ -758,7 +751,7 @@ test.describe('Map backdrop', () => { } }); test('No credit without a city', async ({ page }) => { - for (const path of ['/full/', '/full/map/', '/staff/map/', '/full/software/', '/full/skill-map/']) { + for (const path of ['/', '/map/', '/map/', '/software/', '/skill-map/']) { await page.goto(path); expect(await page.content(), path).not.toContain('OpenStreetMap'); } @@ -780,9 +773,9 @@ async function loadedFaces(page: Page): Promise<string[]> { const computedFamily = (page: Page, selector: string) => page.locator(selector).first().evaluate(element => getComputedStyle(element).fontFamily); test('Fonts load under the policy', async ({ page }) => { - const watched = await watch(page, '/full/'); + const watched = await watch(page, '/'); const loaded = new Set<string>(); - for (const path of ['/full/', '/full/software/slack/', '/full/map/']) { + for (const path of ['/', '/software/slack/', '/map/']) { await page.goto(path); for (const face of await loadedFaces(page)) loaded.add(face); expect(await violations(page), path).toEqual([]); @@ -795,22 +788,22 @@ test('Fonts load under the policy', async ({ page }) => { test('Map drawn in the shipped face', async ({ page }) => { for (const scheme of ['light', 'dark'] as const) { await page.emulateMedia({ colorScheme: scheme }); - await page.goto('/full/map/'); + await page.goto('/map/'); const map = await computedFamily(page, `.map-canvas.themed-${scheme} svg`); expect(firstFamily(map), scheme).toMatch(/^Source Sans 3-/); const label = await computedFamily(page, `.map-canvas.themed-${scheme} svg text[data-line]`); expect(firstFamily(label), scheme).toBe(firstFamily(map)); - await page.goto('/full/software/slack/'); + await page.goto('/software/slack/'); const diagram = await computedFamily(page, `.diagram.themed-${scheme} svg`); expect(firstFamily(diagram), scheme).toBe(firstFamily(map)); } }); test('Body and code faces', async ({ page }) => { - await page.goto('/full/'); + await page.goto('/'); expect(firstFamily(await computedFamily(page, 'body'))).toMatch(/^Source Sans 3-/); expect(firstFamily(await computedFamily(page, 'h1'))).toMatch(/^Source Serif 4-/); - await page.goto('/full/software/slack/'); + await page.goto('/software/slack/'); const code = firstFamily(await computedFamily(page, 'main code')); expect(code).toMatch(/^Source Code Pro-/); expect(await loadedFaces(page)).toContain('Source Code Pro 400 normal'); @@ -828,7 +821,7 @@ async function wordmark(page: Page) { test('Wordmark face', async ({ page }) => { for (const scheme of ['light', 'dark'] as const) { await page.emulateMedia({ colorScheme: scheme }); - for (const path of ['/full/', '/staff/map/']) { + for (const path of ['/', '/map/']) { await page.goto(path); const mark = await wordmark(page); expect(mark.family, `${scheme} ${path}`).toMatch(/^Source Serif 4-[0-9a-f]{16}$/); @@ -839,7 +832,7 @@ test('Wordmark face', async ({ page }) => { }); test('Wordmark with the longest title', async ({ page }) => { - await page.goto('/full/'); + await page.goto('/'); const standard = await wordmark(page); await page.goto('/extra/'); const longest = await wordmark(page); diff --git a/test/integration/build-skills.test.ts b/test/integration/build-skills.test.ts index 41040230..69a7edff 100644 --- a/test/integration/build-skills.test.ts +++ b/test/integration/build-skills.test.ts @@ -82,7 +82,7 @@ afterAll(() => { if (base) rmSync(base, { recursive: true, force: true }); }); test('Two sites with skills', () => { const { out, result } = withSkills; expect(result.status, result.stderr).toBe(0); - for (const site of ['full', 'staff']) expect(existsSync(join(out, site, 'skills', 'index.html'))).toBe(true); + expect(existsSync(join(out, 'skills', 'index.html'))).toBe(true); }); test('Counts line', () => { expect(lines(withSkills.result.stderr)).toContain('Skills: 3 skills, 1 playbook, 2 agents, 10 rules'); @@ -106,11 +106,11 @@ test.concurrent('Folders from the settings', async () => { const out = fresh('settings-out'); const result = await build([cat, '--out', out, '--date', DATE]); expect(result.status, result.stderr).toBe(0); - for (const site of ['full', 'staff']) expect(existsSync(join(out, site, 'skills', 'writer', 'index.html'))).toBe(true); + expect(existsSync(join(out, 'skills', 'writer', 'index.html'))).toBe(true); }, 180_000); const JOURNEY = 'apiVersion: stackledger/v1alpha1\nkind: Line\nmetadata:\n name: ship\n title: Ship a change\nspec:\n color: "#E4002B"\n stops: ["skill:writer", "agent:reviewer"]\n'; -const page = (out: string, path: string) => readFileSync(join(out, 'full', path, 'index.html'), 'utf8'); +const page = (out: string, path: string) => readFileSync(join(out, path, 'index.html'), 'utf8'); test.concurrent('Journeys in the catalogue', async () => { const top = fresh('journeys'); @@ -139,7 +139,7 @@ test.concurrent('Map setting without folders', async () => { const out = fresh('map-only-out'); const result = await build([cat, '--out', out, '--date', DATE]); expect(result.status, result.stderr).toBe(0); - expect(existsSync(join(out, 'full', 'skill-map'))).toBe(false); + expect(existsSync(join(out, 'skill-map'))).toBe(false); }, 180_000); test.concurrent('The option replaces the settings', async () => { @@ -147,7 +147,7 @@ test.concurrent('The option replaces the settings', async () => { const out = fresh('replace-out'); const result = await build([cat, '--out', out, '--date', DATE, '--skills', kit]); expect(result.status, result.stderr).toBe(0); - expect(existsSync(join(out, 'full', 'skills', 'writer', 'index.html'))).toBe(true); + expect(existsSync(join(out, 'skills', 'writer', 'index.html'))).toBe(true); }, 180_000); test.concurrent('Several option folders', async () => { @@ -157,8 +157,8 @@ test.concurrent('Several option folders', async () => { const result = await build([catalogue, '--out', out, '--date', DATE, '--skills', team, '--skills', vendor]); expect(result.status, result.stderr).toBe(0); // One set, team first: the vendor's writer is a duplicate name (an error), linter joins. - expect(readFileSync(join(out, 'full', 'skills', 'writer', 'index.html'), 'utf8')).toContain('Helps the Northwind team with writer.'); - expect(existsSync(join(out, 'full', 'skills', 'linter', 'index.html'))).toBe(true); + expect(readFileSync(join(out, 'skills', 'writer', 'index.html'), 'utf8')).toContain('Helps the Northwind team with writer.'); + expect(existsSync(join(out, 'skills', 'linter', 'index.html'))).toBe(true); expect(result.stderr).toMatch(/Skill set: 1 error/); }, 180_000); @@ -166,7 +166,7 @@ test.concurrent('No skill set', async () => { const out = fresh('none-out'); const result = await build([catalogue, '--out', out, '--date', DATE]); expect(result.status, result.stderr).toBe(0); - for (const site of ['full', 'staff']) for (const folder of ['skills', 'skill-map', 'rules', 'playbooks', 'agents']) expect(existsSync(join(out, site, folder))).toBe(false); + for (const folder of ['skills', 'skill-map', 'rules', 'playbooks', 'agents']) expect(existsSync(join(out, folder))).toBe(false); expect(result.stderr).not.toContain('Skills:'); }, 180_000); @@ -192,7 +192,7 @@ test.concurrent('Broken settings and the option', async () => { const out = fresh('broken-option-out'); const result = await build([cat, '--out', out, '--date', DATE, '--skills', kit]); expect(result.status, result.stderr).toBe(0); - expect(existsSync(join(out, 'full', 'skills', 'writer', 'index.html'))).toBe(true); + expect(existsSync(join(out, 'skills', 'writer', 'index.html'))).toBe(true); }, 180_000); test.concurrent('Unreadable settings file', async () => { @@ -200,7 +200,7 @@ test.concurrent('Unreadable settings file', async () => { const out = fresh('unreadable-out'); const result = await build([cat, '--out', out, '--date', DATE]); expect(result.status, result.stderr).toBe(0); - expect(existsSync(join(out, 'full', 'skills'))).toBe(false); + expect(existsSync(join(out, 'skills'))).toBe(false); expect(result.stderr).toMatch(/Skill folders could not be read from the settings/); }, 180_000); @@ -209,7 +209,7 @@ test.concurrent('Broken settings without skills', async () => { const out = fresh('broken-no-skills-out'); const result = await build([cat, '--out', out, '--date', DATE]); expect(result.status, result.stderr).toBe(0); - for (const site of ['full', 'staff']) expect(existsSync(join(out, site, 'skills'))).toBe(false); + expect(existsSync(join(out, 'skills'))).toBe(false); }, 180_000); test.concurrent('Missing skills folder', async () => { @@ -245,8 +245,8 @@ test.concurrent('Skill set with errors', async () => { const out = fresh('with-errors-out'); const result = await build([catalogue, '--out', out, '--date', DATE, '--skills', set]); expect(result.status, result.stderr).toBe(0); - expect(existsSync(join(out, 'full', 'skills', 'writer', 'index.html'))).toBe(true); - expect(existsSync(join(out, 'full', 'skills', 'editor'))).toBe(false); + expect(existsSync(join(out, 'skills', 'writer', 'index.html'))).toBe(true); + expect(existsSync(join(out, 'skills', 'editor'))).toBe(false); }, 180_000); test.concurrent('Colliding page names', async () => { @@ -289,18 +289,18 @@ test.concurrent('Output holds a linked input', async () => { const top = fresh('linked-input'); const out = join(top, 'public'); expect((await build([catalogue, '--out', out, '--date', DATE])).status).toBe(0); - writeFileSync(join(out, 'full', 'notes.md'), '# Notes\n'); + writeFileSync(join(out, 'notes.md'), '# Notes\n'); writeFolder(join(top, 'skills'), { 'writer/SKILL.md': skill('writer') }); - symlinkSync(join(out, 'full', 'notes.md'), join(top, 'skills', 'writer', 'rules.md')); + symlinkSync(join(out, 'notes.md'), join(top, 'skills', 'writer', 'rules.md')); const result = await build([catalogue, '--out', 'public', '--date', DATE, '--skills', 'skills'], { cwd: top }); - expect(result.status).toBe(2); expect(readFileSync(join(out, 'full', 'notes.md'), 'utf8')).toBe('# Notes\n'); + expect(result.status).toBe(2); expect(readFileSync(join(out, 'notes.md'), 'utf8')).toBe('# Notes\n'); }, 180_000); test.concurrent('Building inside the skills repository', async () => { const repo = writeFolder(fresh('repo'), { ...kitFiles(), ...Object.fromEntries(Object.entries(catalogueFiles()).map(([file, text]) => [`catalog/${file}`, text])) }); const result = await build(['catalog', '--skills', '.', '--out', 'public', '--date', DATE], { cwd: repo }); expect(result.status, result.stderr).toBe(0); - expect(existsSync(join(repo, 'public', 'full', 'skills', 'writer', 'index.html'))).toBe(true); + expect(existsSync(join(repo, 'public', 'skills', 'writer', 'index.html'))).toBe(true); }, 180_000); test.concurrent('Output inside a linked skill folder', async () => { @@ -368,7 +368,7 @@ test.concurrent('Sandboxed build', async context => { // exit 1, so an output inside a skill folder that holds one must still be refused with exit 2. test.concurrent('Output inside a skill folder, with a staging folder left behind', async () => { const top = fresh('order'); - writeFolder(join(top, 'skills'), { ...kitFiles(), 'writer/site/.stackledger-tmp-0123456789abcdef/old/full/index.html': 'old\n' }); + writeFolder(join(top, 'skills'), { ...kitFiles(), 'writer/site/.stackledger-tmp-0123456789abcdef/old/index.html': 'old\n' }); const result = await build([catalogue, '--out', './skills/writer/site', '--date', DATE, '--skills', './skills'], { cwd: top }); expect(result.status, result.stderr).toBe(2); }, 60_000); diff --git a/test/integration/build-with-faults.mjs b/test/integration/build-with-faults.mjs index 14af17ea..5b0f3b3c 100644 --- a/test/integration/build-with-faults.mjs +++ b/test/integration/build-with-faults.mjs @@ -10,7 +10,7 @@ * The plan is the one wrapOps documents, for example {"out": "/tmp/x", "fail": [{"op": "rename", "nth": 3}]}, * plus two build hooks (src/site/build.ts BuildHooks): `missingFont` names a font file of the fonts * configuration that the installed packages then lack (catalogue-site, Missing font file), and - * `pageEdit` { site: 'full' | 'staff', page, kind } changes one page right after Astro wrote it: kind + * `pageEdit` { page, kind } changes one page right after Astro wrote it: kind * `style` adds <style>p{color:red}</style> to its head (Other style still fails), kind `font-css` * changes one character of its font CSS (Font CSS differs between pages). * Failures are reported as src/cli.ts reports them (exit 1 for internal errors, 2 for usage errors). @@ -22,7 +22,7 @@ import { reportFailure } from '../../dist/errors.js'; import { wrapOps } from '../fs-wrapper.mjs'; import { readFileSync, writeFileSync } from 'node:fs'; import { createRequire } from 'node:module'; -import { basename, join } from 'node:path'; +import { join } from 'node:path'; const require = createRequire(import.meta.url); const [json, ...args] = process.argv.slice(2); @@ -36,9 +36,8 @@ if (plan.missingFont) { }; } if (plan.pageEdit) { - const { site, page, kind } = plan.pageEdit; + const { page, kind } = plan.pageEdit; hooks.afterAstro = dir => { - if (basename(dir) !== `site-${site}`) return; const path = join(dir, page); const html = readFileSync(path, 'utf8'); const edited = kind === 'style' ? html.replace('</head>', '<style>p{color:red}</style></head>') : html.replace('font-display:swap', 'font-display:swaq'); diff --git a/test/integration/build.test.ts b/test/integration/build.test.ts index 645bd20a..b1b9e49c 100644 --- a/test/integration/build.test.ts +++ b/test/integration/build.test.ts @@ -20,7 +20,7 @@ import { manualRestore } from '../manual-restore.js'; import { largeCatalogue } from '../large-catalogue.js'; const DATE = '2027-06-01'; -const PROXY = /identity-aware proxy/; +const PROXY = /serve it only behind a sign-in/; interface Result { status: number; stdout: string; stderr: string; ms: number } @@ -32,7 +32,7 @@ interface Plan { out: string; /** build-with-faults.mjs build hooks: a font file the packages lack, a page Astro wrote changed. */ missingFont?: string; - pageEdit?: { site: 'full' | 'staff'; page: string; kind: 'style' | 'font-css' }; + pageEdit?: { page: string; kind: 'style' | 'font-css' }; fail?: Fault[]; swap?: { to: string; kind: 'link' | 'folder'; after?: Fault; atCheck?: number }; readOnlyStaging?: boolean; @@ -111,14 +111,14 @@ function smallCatalogue(extra: unknown[] = []): Record<string, string> { } let catalogue = ''; -let twoSites: { out: string; result: Result }; +let oneSite: { out: string; result: Result }; beforeAll(async () => { // The real path: the permission model grants paths as written, and macOS links /var to /private/var. base = realpathSync(mkdtempSync(join(tmpdir(), 'stackledger-build-'))); catalogue = writeFolder(join(base, 'catalogue'), smallCatalogue()); const out = join(base, 'public'); - twoSites = { out, result: await build(['build', catalogue, '--out', out, '--date', DATE]) }; + oneSite = { out, result: await build(['build', catalogue, '--out', out, '--date', DATE]) }; }, 120_000); afterAll(() => { @@ -134,77 +134,57 @@ afterAll(() => { }); describe('Command', () => { - test('Two sites', () => { - const { out, result } = twoSites; + test('One site at the root', () => { + const { out, result } = oneSite; expect(result.status, result.stderr).toBe(0); expect(result.stdout).toBe(''); - expect(existsSync(join(out, 'full', 'index.html'))).toBe(true); - expect(existsSync(join(out, 'staff', 'index.html'))).toBe(true); - expect(readdirSync(out).sort()).toEqual(['.stackledger-build', '_headers', '_redirects', 'full', 'robots.txt', 'staff']); - // The report date of the full site is the build date too (licence-reports, Site report date). - expect(readFileSync(join(out, 'full', 'reports', 'index.html'), 'utf8')).toContain(`renewals on ${DATE},`); - expect(existsSync(join(out, 'staff', 'reports'))).toBe(false); + expect(existsSync(join(out, 'index.html'))).toBe(true); + expect(existsSync(join(out, 'software', 'forge', 'index.html'))).toBe(true); + expect(existsSync(join(out, 'full'))).toBe(false); + expect(existsSync(join(out, 'staff'))).toBe(false); + const names = readdirSync(out); + for (const name of ['.stackledger-build', '_headers', '_redirects', 'robots.txt', 'index.html', 'map', 'reports', 'renewals.ics']) expect(names).toContain(name); + // The report date is the build date too (licence-reports, Site report date). + expect(readFileSync(join(out, 'reports', 'index.html'), 'utf8')).toContain(`renewals on ${DATE},`); }); test('Proxy reminder', () => { - const { out, result } = twoSites; + const { out, result } = oneSite; const report = lines(result.stderr); expect(report.at(-1)).toMatch(PROXY); - expect(pagesIn(join(out, 'staff'))).toBeGreaterThanOrEqual(8); - expect(report).toContain(`Built the staff site in ${join(out, 'staff')} (${pagesIn(join(out, 'staff'))} pages)`); - expect(report).toContain(`Built the full site in ${join(out, 'full')} (${pagesIn(join(out, 'full'))} pages)`); + expect(pagesIn(out)).toBeGreaterThanOrEqual(8); + expect(report).toContain(`Built the site in ${out} (${pagesIn(out)} pages)`); }); -}); - -describe('Site modes', () => { - const personal = () => writeFolder(fresh('personal'), { ...smallCatalogue(), 'stackledger.yaml': yaml(settings('settings', { sites: ['full'] })) }); - test('Root redirect', () => { - expect(readFileSync(join(twoSites.out, '_redirects'), 'utf8')).toBe('/ /staff/ 302\n'); + test('Old addresses redirect', () => { + expect(readFileSync(join(oneSite.out, '_redirects'), 'utf8')).toBe('/full / 301\n/full/* /:splat 301\n'); }); +}); - test.concurrent('Personal build', async () => { - const out = fresh('personal-out'); - const result = await build(['build', personal(), '--out', out, '--date', DATE]); - expect(result.status, result.stderr).toBe(0); - expect(readdirSync(out).sort()).toEqual(['.stackledger-build', '_headers', '_redirects', 'full', 'robots.txt']); - expect(readFileSync(join(out, '_redirects'), 'utf8')).toBe('/ /full/ 302\n'); - expect(existsSync(join(out, 'full', 'reports', 'index.html'))).toBe(true); - const report = lines(result.stderr); - expect(report.some(text => /staff/.test(text))).toBe(false); - expect(report).toContain(`Built the full site in ${join(out, 'full')} (${pagesIn(join(out, 'full'))} pages)`); - expect(report.at(-1)).toMatch(PROXY); - }, 120_000); - - test.concurrent('Stale staff site removed', async () => { - const out = fresh('to-personal'); - expect((await build(['build', catalogue, '--out', out, '--date', DATE])).status).toBe(0); - expect(existsSync(join(out, 'staff', 'index.html'))).toBe(true); - const folder = personal(); - const result = await build(['build', folder, '--out', out, '--date', DATE]); +describe('Earlier builds', () => { + test.concurrent('Stale full and staff sites removed', async () => { + const out = fresh('from-two-sites'); + writeFolder(out, { [MARKER_NAME]: MARKER, 'full/index.html': 'old full\n', 'staff/index.html': 'old staff\n', '_headers': 'old\n', 'robots.txt': 'old\n', '_redirects': '/ /staff/ 302\n' }); + const result = await build(['build', catalogue, '--out', out, '--date', DATE]); expect(result.status, result.stderr).toBe(0); + expect(existsSync(join(out, 'full'))).toBe(false); expect(existsSync(join(out, 'staff'))).toBe(false); expect(staging(out)).toEqual([]); - const clean = fresh('personal-clean'); - expect((await build(['build', folder, '--out', clean, '--date', DATE])).status).toBe(0); + const clean = fresh('clean-one-site'); + expect((await build(['build', catalogue, '--out', clean, '--date', DATE])).status).toBe(0); expect(snapshot(out)).toEqual(snapshot(clean)); - // Back to the corporate mode: the staff site comes back. - expect((await build(['build', catalogue, '--out', out, '--date', DATE])).status).toBe(0); - expect(existsSync(join(out, 'staff', 'index.html'))).toBe(true); }, 180_000); - test.concurrent('A failed personal build leaves the corporate site', async () => { - const out = fresh('to-personal-fails'); - expect((await build(['build', catalogue, '--out', out, '--date', DATE])).status).toBe(0); - const before = snapshot(out); - // Personal over corporate renames 11 times: the old staff into old/, then old and new for full, - // _headers, robots.txt, _redirects and the marker (the commit). Rename 10 is the last before it. - for (const nth of [1, 10]) { - const result = await build(['build', personal(), '--out', out, '--date', DATE], { plan: { out, fail: [{ op: 'rename', nth }] } }); - expect(result.status, result.stderr).toBe(1); - expect(snapshot(out)).toEqual(before); - } - }, 180_000); + test.concurrent('Deprecated site settings warn and change nothing', async () => { + const folder = writeFolder(fresh('deprecated'), { ...smallCatalogue(), 'stackledger.yaml': yaml(settings('settings', { sites: ['full'] })) }); + const out = fresh('deprecated-out'); + const result = await build(['build', folder, '--out', out, '--date', DATE]); + expect(result.status, result.stderr).toBe(0); + const warnings = (text: string) => Number(/(\d+) warnings?/.exec(text)![1]); + expect(warnings(result.stderr)).toBe(warnings(oneSite.result.stderr) + 1); + expect(existsSync(join(out, 'index.html'))).toBe(true); + expect(existsSync(join(out, 'full'))).toBe(false); + }, 120_000); }); describe('Usage errors', () => { @@ -334,7 +314,7 @@ describe('Safe output folder', () => { const out = join(dirname(folder), `..sibling-${++counter}`); const result = await build(['build', folder, '--out', out, '--date', DATE]); expect(result.status, result.stderr).toBe(0); - expect(existsSync(join(out, 'staff', 'index.html'))).toBe(true); + expect(existsSync(join(out, 'index.html'))).toBe(true); }, 120_000); test('Unrelated non-empty folder', async () => { @@ -373,7 +353,7 @@ describe('Marker and published entries', () => { }, 120_000); test('A published entry that is a symbolic link is refused', async () => { - const names = ['full', 'staff', '_headers', 'robots.txt']; + const names = ['index.html', 'map', '_headers', 'robots.txt']; const cases = names.map(name => { const out = writeFolder(fresh('linked'), { [MARKER_NAME]: MARKER }); const target = writeFolder(fresh('link-target'), { 'keep.txt': 'keep me\n' }); @@ -396,15 +376,15 @@ describe('Atomic replace', () => { const out = fresh('rebuild'); const first = await build(['build', catalogue, '--out', out, '--date', DATE]); expect(first.status, first.stderr).toBe(0); - expect(existsSync(join(out, 'full', 'software', 'forge', 'index.html'))).toBe(true); + expect(existsSync(join(out, 'software', 'forge', 'index.html'))).toBe(true); // A crashed earlier build left a staging folder: the next build removes it first. - writeFolder(join(out, '.stackledger-tmp-crashed'), { 'full/secret.html': 'old full-view file\n' }); + writeFolder(join(out, '.stackledger-tmp-crashed'), { 'site/secret.html': 'old file\n' }); const smaller = writeFolder(fresh('smaller'), { 'catalog-info.yaml': yaml(component('editor'), component('linear'), stops('ship', ['linear', 'editor'])), }); const second = await build(['build', smaller, '--out', out, '--date', DATE]); expect(second.status, second.stderr).toBe(0); - expect(existsSync(join(out, 'full', 'software', 'forge'))).toBe(false); + expect(existsSync(join(out, 'software', 'forge'))).toBe(false); expect(staging(out)).toEqual([]); // Nothing of the first build remains: the output equals a build into an empty folder. const clean = fresh('clean'); @@ -428,27 +408,34 @@ describe('Atomic replace', () => { const otherCatalogue = () => writeFolder(fresh('other'), smallCatalogue([component('extra')])); // A rebuild over an earlier build creates the staging folder (mkdir 1) and its old/ (mkdir 2), - // then renames 12 times: old then new, for staff, full, _headers, robots.txt, _redirects and the - // marker. The twelfth rename (the marker) is the commit point. - const steps: [string, Omit<Plan, 'out'>][] = [ - ['prepare', { readOnlyStaging: true }], - ['old/', { fail: [{ op: 'mkdir', nth: 2 }] }], - ...Array.from({ length: 12 }, (_, i): [string, Omit<Plan, 'out'>] => [`rename ${i + 1}`, { fail: [{ op: 'rename', nth: i + 1 }] }]), - ]; - test.concurrent.each(steps)('Failure leaves the old site (%s)', async (_, plan) => { - const out = copySeed('fail'); - const before = snapshot(out); - const result = await build(['build', otherCatalogue(), '--out', out, '--date', '2031-01-01'], { plan: { out, ...plan } }); - expect(result.status, result.stderr).toBe(1); - expect(result.stderr).toMatch(/^stackledger build: internal error: /); - expect(staging(out)).toEqual([]); - expect(snapshot(out)).toEqual(before); - }, 120_000); + // then renames twice per entry (the old one into old/, the new one into place) and twice for the + // marker, which comes last: the last rename is the commit point. + let renames = 0; + beforeAll(() => { renames = 2 * (readdirSync(seed).filter(name => name !== MARKER_NAME).length + 1); }); + test('Failure leaves the old site at every step', async () => { + const steps: [string, Omit<Plan, 'out'>][] = [ + ['prepare', { readOnlyStaging: true }], + ['old/', { fail: [{ op: 'mkdir', nth: 2 }] }], + ...Array.from({ length: renames }, (_, i): [string, Omit<Plan, 'out'>] => [`rename ${i + 1}`, { fail: [{ op: 'rename', nth: i + 1 }] }]), + ]; + expect(steps.length).toBeGreaterThan(20); + for (let from = 0; from < steps.length; from += 6) { + await Promise.all(steps.slice(from, from + 6).map(async ([label, plan]) => { + const out = copySeed('fail'); + const before = snapshot(out); + const result = await build(['build', otherCatalogue(), '--out', out, '--date', '2031-01-01'], { plan: { out, ...plan } }); + expect(result.status, `${label}: ${result.stderr}`).toBe(1); + expect(result.stderr, label).toMatch(/^stackledger build: internal error: /); + expect(staging(out), label).toEqual([]); + expect(snapshot(out), label).toEqual(before); + })); + } + }, 600_000); test.concurrent('Undo failed; Next build after a failed undo; the documented manual restore', async () => { const out = copySeed('undo'); const before = snapshot(out); - // Rename 5 (the old _headers into old/) fails, then the first undo rename fails too. + // Rename 5 (the old _redirects into old/) fails, then the first undo rename fails too. const failed = await build(['build', otherCatalogue(), '--out', out, '--date', '2031-01-01'], { plan: { out, fail: [{ op: 'rename', nth: 5 }, { op: 'rename', nth: 6 }] } }); expect(failed.status, failed.stderr).toBe(1); expect(staging(out)).toHaveLength(1); @@ -479,8 +466,8 @@ describe('Atomic replace', () => { const rebuilt = copySeed('stale'); const first = fresh('stale-first'); for (const out of [rebuilt, first]) { - writeFolder(join(out, '.stackledger-tmp-crashed'), { 'site-full/secret.html': 'full view file\n' }); - symlinkSync(elsewhere, join(out, '.stackledger-tmp-crashed', 'site-staff')); + writeFolder(join(out, '.stackledger-tmp-crashed'), { 'site/secret.html': 'a file\n' }); + symlinkSync(elsewhere, join(out, '.stackledger-tmp-crashed', 'link')); } // `first` holds only the staging folder: a first build that crashed, so there is no marker yet. const results = await Promise.all([rebuilt, first].map(out => build(['build', catalogue, '--out', out, '--date', DATE]))); @@ -519,18 +506,19 @@ describe('Atomic replace', () => { // The build cannot hold the output folder open; it re-checks the folder's real path and identity // immediately before each change, and stops when the folder was swapped for a link or for another // real folder. Check 1 records the identity; check 2 comes before the staging folder is created, - // check 3 after the sites are prepared (before old/); rename 12 is the commit, before the cleanup. - const swaps: [string, 'link' | 'folder', { atCheck?: number; after?: Fault }][] = []; + // check 3 after the site is prepared (before old/); the last rename is the commit, before the cleanup. + const swaps: [string, 'link' | 'folder', { atCheck?: number; afterCommit?: true }][] = []; for (const kind of ['link', 'folder'] as const) { swaps.push([`${kind}, before the staging folder`, kind, { atCheck: 2 }]); swaps.push([`${kind}, before publication`, kind, { atCheck: 3 }]); - swaps.push([`${kind}, before the cleanup`, kind, { after: { op: 'rename', nth: 12 } }]); + swaps.push([`${kind}, before the cleanup`, kind, { afterCommit: true }]); } test.concurrent.each(swaps)('Folder swapped during a build (%s)', async (label, kind, point) => { const out = copySeed('swapped'); - const other = writeFolder(fresh('elsewhere'), { [MARKER_NAME]: MARKER, 'staff/index.html': 'another site\n' }); + const other = writeFolder(fresh('elsewhere'), { [MARKER_NAME]: MARKER, 'index.html': 'another site\n' }); const otherBefore = snapshot(other); - const result = await build(['build', otherCatalogue(), '--out', out, '--date', DATE], { plan: { out, swap: { to: other, kind, ...point } } }); + const swap = { to: other, kind, ...(point.afterCommit ? { after: { op: 'rename' as const, nth: renames } } : { atCheck: point.atCheck }) }; + const result = await build(['build', otherCatalogue(), '--out', out, '--date', DATE], { plan: { out, swap } }); expect(result.status, result.stderr).toBe(1); expect(result.stderr).toBe(`stackledger build: the output folder ${out} was moved or replaced during the build; stopped without further changes\nchanges after the swap: none\n`); expect(snapshot(kind === 'link' ? other : out)).toEqual(otherBefore); @@ -539,15 +527,15 @@ describe('Atomic replace', () => { const moved = `${out}-moved`; expect(readFileSync(join(moved, MARKER_NAME), 'utf8')).toBe(MARKER); expect(staging(moved)).toHaveLength(point.atCheck === 2 ? 0 : 1); - if (!point.after) { + if (!point.afterCommit) { const published = (dir: string) => Object.fromEntries(Object.entries(snapshot(dir)).filter(([path]) => !path.startsWith('.stackledger-tmp-'))); expect(published(moved), label).toEqual(snapshot(seed)); } }, 120_000); - test.concurrent('There is no thirteenth step: the marker rename is the last one', async () => { - const out = copySeed('thirteen'); - const result = await build(['build', catalogue, '--out', out, '--date', DATE], { plan: { out, fail: [{ op: 'rename', nth: 13 }] } }); + test.concurrent('There is no step after the marker rename', async () => { + const out = copySeed('after-marker'); + const result = await build(['build', catalogue, '--out', out, '--date', DATE], { plan: { out, fail: [{ op: 'rename', nth: renames + 1 }] } }); expect(result.status, result.stderr).toBe(0); expect(snapshot(out)).toEqual(snapshot(seed)); }, 120_000); @@ -582,20 +570,21 @@ test.concurrent('Catalogue text that mentions staging folders builds', async () const out = fresh('mentions-staging-out'); const result = await build(['build', folder, '--out', out, '--date', DATE]); expect(result.status, result.stderr).toBe(0); - expect(readFileSync(join(out, 'staff', 'software', 'janitor', 'index.html'), 'utf8')).toContain(text); + expect(readFileSync(join(out, 'software', 'janitor', 'index.html'), 'utf8')).toContain(text); }, 120_000); test.concurrent('The shipped CLI ignores the old STACKLEDGER_TEST_FAIL variable', async () => { const out = fresh('no-env-hook'); const result = await build(['build', catalogue, '--out', out, '--date', DATE], { env: { STACKLEDGER_TEST_FAIL: 'prepare' } }); expect(result.status, result.stderr).toBe(0); - expect(existsSync(join(out, 'full', 'index.html'))).toBe(true); + expect(existsSync(join(out, 'index.html'))).toBe(true); }, 120_000); test('Documented', () => { const text = readFileSync(join(root, 'docs', 'site.md'), 'utf8').replace(/\s+/g, ' '); expect(text).toMatch(/Never serve the output folder while a build runs/); - expect(text).toMatch(/Publish only these entries of the output folder: `full\/`, `staff\/` \(not in the personal mode\), `_headers`, `robots\.txt` and `_redirects`/); + expect(text).toMatch(/Publish only the site's files, and only after the command exits with code 0/); + expect(text).toMatch(/every entry of the output folder except the `\.stackledger-build` marker/); // The manual restore that an Undo failed message points to. expect(text).toContain('### Restoring after a failed publication'); }); @@ -625,7 +614,7 @@ test.concurrent('Sandboxed build', async context => { expect(existsSync(fakeHome)).toBe(false); expect(snapshot(folder)).toEqual(before); // The same files as the unrestricted build of the same catalogue and date. - expect(snapshot(out)).toEqual(snapshot(twoSites.out)); + expect(snapshot(out)).toEqual(snapshot(oneSite.out)); }, 120_000); // Every server the build opens (Astro's Fonts API opens one per site) listens on 127.0.0.1 and is @@ -636,7 +625,7 @@ test.concurrent('Font server on loopback', async () => { expect(result.status, result.stderr).toBe(0); expect(trapProblems(result.stderr)).toEqual([]); const bound = trapBound(result.stderr); - expect(bound.length).toBeGreaterThanOrEqual(readdirSync(out).filter(entry => entry === 'full' || entry === 'staff').length); + expect(bound.length).toBeGreaterThanOrEqual(1); for (const address of bound) expect(address).toMatch(/^127\.0\.0\.1:\d+$/); }, 120_000); @@ -648,7 +637,7 @@ test.concurrent('One error', async () => { build(['map', folder, '--date', DATE]), ]); expect(result.status, result.stderr).toBe(0); - for (const site of ['full', 'staff']) expect(existsSync(join(out, site, 'index.html'))).toBe(true); + expect(existsSync(join(out, 'index.html'))).toBe(true); // The report: counts with the hint, the map's lines as `stackledger map` writes them, the sites, the reminder. const mapLines = lines(map.stderr); expect(mapLines[0]).toMatch(/^stackledger map: 1 error, \d+ warnings?; run stackledger validate for details$/); @@ -656,8 +645,7 @@ test.concurrent('One error', async () => { expect(lines(result.stderr)).toEqual([ mapLines[0]!.replace('stackledger map:', 'stackledger build:'), ...mapLines.slice(1), - `Built the staff site in ${join(out, 'staff')} (${pagesIn(join(out, 'staff'))} pages)`, - `Built the full site in ${join(out, 'full')} (${pagesIn(join(out, 'full'))} pages)`, + `Built the site in ${out} (${pagesIn(out)} pages)`, expect.stringMatching(PROXY), ]); }, 120_000); @@ -667,8 +655,8 @@ test.concurrent('One error', async () => { describe('Font delivery faults', () => { const faults: [string, Omit<Plan, 'out'>, RegExp][] = [ ['Missing font file', { missingFont: 'source-serif-4-latin-700-italic.woff2' }, /@fontsource\/source-serif-4\/files\/source-serif-4-latin-700-italic\.woff2 is missing/], - ['Other style still fails', { pageEdit: { site: 'full', page: 'map/index.html', kind: 'style' } }, /The full site has style the build does not allow: map\/index\.html: a <style> element with "p"/], - ['Font CSS differs between pages', { pageEdit: { site: 'staff', page: 'software/index.html', kind: 'font-css' } }, /The staff site has style the build does not allow: software\/index\.html: font CSS differs from index\.html's/], + ['Other style still fails', { pageEdit: { page: 'map/index.html', kind: 'style' } }, /The site has style the build does not allow: map\/index\.html: a <style> element with "p"/], + ['Font CSS differs between pages', { pageEdit: { page: 'software/index.html', kind: 'font-css' } }, /The site has style the build does not allow: software\/index\.html: font CSS differs from index\.html's/], ]; test.concurrent.each(faults)('%s', async (_, plan, message) => { const out = fresh('font-fault'); @@ -713,7 +701,7 @@ test('Large catalogue', async () => { console.info(`build-command: 300 items, 20 lines: ${(result.ms / 1000).toFixed(1)} s`); expect(result.status, result.stderr).toBe(0); // At least 280 components + 20 licences + 20 journeys + map, software list and journeys list. - expect(pagesIn(join(out, 'full'))).toBeGreaterThanOrEqual(323); - expect(result.stderr).toContain(`Built the full site in ${join(out, 'full')} (${pagesIn(join(out, 'full'))} pages)`); + expect(pagesIn(out)).toBeGreaterThanOrEqual(323); + expect(result.stderr).toContain(`Built the site in ${out} (${pagesIn(out)} pages)`); expect(result.ms).toBeLessThan(90_000); }, 180_000); diff --git a/test/integration/catalogue-template.test.ts b/test/integration/catalogue-template.test.ts index 1b31504f..137f5c34 100644 --- a/test/integration/catalogue-template.test.ts +++ b/test/integration/catalogue-template.test.ts @@ -129,8 +129,8 @@ function runDeploy(site: Run, date: string) { } const publishedEntries = (run: Run) => readdirSync(join(artifactFolder(run), 'site')).sort(); -const corporate = ['_headers', '_redirects', 'full', 'robots.txt', 'staff']; -const personal = ['_headers', '_redirects', 'full', 'robots.txt']; +/** What a build writes at the root, the marker aside: the site's entries and the three policy files. */ +const siteEntries = ['_astro', '_headers', '_redirects', 'index.html', 'map', 'renewals.ics', 'reports', 'robots.txt', 'software']; const statuses = (run: Run) => run.steps.map(step => step.status); function catalogue(repo: string, documents: string) { @@ -149,7 +149,8 @@ test('Copied template passes as is: every site command exits 0 beside the workfl 'stackledger validate catalog', `stackledger build catalog --out ${join(run.temp, 'site')} --date 2026-10-21`, ]); - expect(publishedEntries(run)).toEqual(corporate); + expect(publishedEntries(run)).toEqual(expect.arrayContaining(siteEntries)); + expect(publishedEntries(run)).not.toContain('.stackledger-build'); // The log names the stackledger version the job used. expect(run.steps.map(step => step.output).join('\n')).toContain(workflow.env.STACKLEDGER); }, 240_000); @@ -167,30 +168,36 @@ test('Catalogue warning does not stop the job: every command exits 0 and the pub const run = runSite(repository(repo => catalogue(repo, component(' namespace: northwind\n')))); expect(run.steps.filter(step => step.status !== 0)).toEqual([]); expect(run.steps.map(step => step.output).join('\n')).toMatch(/warnings: 1\b/); - expect(publishedEntries(run)).toEqual(corporate); + expect(publishedEntries(run)).toEqual(expect.arrayContaining(siteEntries)); + expect(publishedEntries(run)).not.toContain('.stackledger-build'); }, 240_000); -test('Only the publishable entries: the Northwind example publishes full, staff, _headers, robots.txt and _redirects', () => { +test('Only the publishable entries: the Northwind example publishes the site at the root without the marker', () => { const run = runSite(repository(repo => { rmSync(join(repo, 'catalog'), { recursive: true }); cpSync(join(root, 'examples', 'northwind'), join(repo, 'catalog'), { recursive: true }); })); expect(run.steps.filter(step => step.status !== 0)).toEqual([]); - expect(publishedEntries(run)).toEqual(corporate); - expect(readFileSync(join(artifactFolder(run), 'site', '_redirects'), 'utf8')).toBe('/ /staff/ 302\n'); + expect(publishedEntries(run)).toEqual(expect.arrayContaining(siteEntries)); + expect(publishedEntries(run)).not.toContain('.stackledger-build'); + expect(readFileSync(join(artifactFolder(run), 'site', '_redirects'), 'utf8')).toBe('/full / 301\n/full/* /:splat 301\n'); // The build's own marker and staging folders stay behind in the build folder. expect(readdirSync(join(run.temp, 'site'))).toContain('.stackledger-build'); }, 240_000); -test('Personal mode publishes no staff site: full, _headers, robots.txt and _redirects to /full/', () => { - const run = runSite(repository(repo => writeFileSync(join(repo, 'catalog', 'stackledger.yaml'), +test('Only the site is published: no full, staff, marker or staging entry, and spec.sites changes nothing', () => { + const plain = runSite(repository()); + const withSites = runSite(repository(repo => writeFileSync(join(repo, 'catalog', 'stackledger.yaml'), 'apiVersion: stackledger/v1alpha1\nkind: Settings\nmetadata:\n name: settings\nspec:\n sites: [full]\n'))); - expect(run.steps.filter(step => step.status !== 0)).toEqual([]); - expect(publishedEntries(run)).toEqual(personal); - expect(readFileSync(join(artifactFolder(run), 'site', '_redirects'), 'utf8')).toBe('/ /full/ 302\n'); - const deployed = runDeploy(run, '2026-10-21'); - expect(deployed.results.filter(step => step.status !== 0)).toEqual([]); - expect(readdirSync(join(deployed.deployFolder, 'site')).sort()).toEqual(personal); + expect(withSites.steps.filter(step => step.status !== 0)).toEqual([]); + for (const run of [plain, withSites]) { + const entries = publishedEntries(run); + expect(entries).not.toContain('full'); + expect(entries).not.toContain('staff'); + expect(entries).not.toContain('.stackledger-build'); + expect(entries.filter(name => name.startsWith('.stackledger-tmp-'))).toEqual([]); + } + expect(publishedEntries(withSites)).toEqual(publishedEntries(plain)); }, 240_000); test('Repository extras are not deployed: the deploy folder holds only site/ with the publishable entries', () => { @@ -204,7 +211,8 @@ test('Repository extras are not deployed: the deploy folder holds only site/ wit const deployed = runDeploy(run, '2026-10-21'); expect(deployed.results.filter(step => step.status !== 0)).toEqual([]); expect(readdirSync(deployed.deployFolder)).toEqual(['site']); - expect(readdirSync(join(deployed.deployFolder, 'site')).sort()).toEqual(corporate); + expect(readdirSync(join(deployed.deployFolder, 'site')).sort()).toEqual(publishedEntries(run)); + expect(readdirSync(join(deployed.deployFolder, 'site'))).not.toContain('.stackledger-build'); // wrangler ran in that folder and saw only site/. expect(deployed.wrangler).toContain(`cwd ${realpathSync(deployed.deployFolder)}\n`); expect(deployed.wrangler).toContain('entries site \n'); diff --git a/test/integration/hosting-caddy.test.ts b/test/integration/hosting-caddy.test.ts index d3b492b2..15bb05a0 100644 --- a/test/integration/hosting-caddy.test.ts +++ b/test/integration/hosting-caddy.test.ts @@ -24,7 +24,7 @@ const example = readFileSync(join(root, 'examples', 'hosting', 'Caddyfile'), 'ut const placeholders = { site: 'catalogue.example.org', auth: '127.0.0.1:4180', root: '/srv/stackledger/publish' }; /** Groups the stand-in returns per X-Test-Session value; null means signed in without groups. */ -const sessions: Record<string, string | null> = { staff: 'staff', finance: 'staff,finance', contractors: 'contractors', nogroups: null }; +const sessions: Record<string, string | null> = { reader: 'readers', both: 'staff,readers', staff: 'staff', contractors: 'contractors', nogroups: null }; const freePort = () => new Promise<number>(resolve => { const probe = createServer().listen(0, '127.0.0.1', () => { const { port } = probe.address() as AddressInfo; probe.close(() => resolve(port)); }); @@ -32,22 +32,19 @@ const freePort = () => new Promise<number>(resolve => { describe.runIf(caddy)('Caddy in front of oauth2-proxy (examples/hosting/Caddyfile)', () => { let proxy: ChildProcess | undefined, auth: Server | undefined, base = '', publish = '', caddyLog = ''; - let fullAsset = '', staffAsset = '', work = ''; + let asset = '', work = ''; beforeAll(async () => { - // A built Northwind site, published as the template does: only the four entries. + // A built Northwind site, published as the template does: everything except the marker. work = tempFolder('hosting'); const out = join(work, 'out'); publish = join(work, 'publish'); const built = spawnSync(process.execPath, [cli, 'build', join(root, 'examples', 'northwind'), '--out', out, '--date', '2027-06-01'], { encoding: 'utf8', timeout: 240_000, env: { ...process.env, NODE_OPTIONS: '' } }); if (built.status !== 0) throw new Error(`build failed: ${built.stderr}`); mkdirSync(publish); - for (const entry of ['full', 'staff', '_headers', 'robots.txt']) cpSync(join(out, entry), join(publish, entry), { recursive: true }); - const asset = (site: string) => { - const files = readdirSync(join(publish, site), { recursive: true, withFileTypes: true }).filter(entry => entry.isFile() && /\.(css|js)$/.test(entry.name)); - return `/${relative(publish, join(files[0]!.parentPath, files[0]!.name))}`; - }; - fullAsset = asset('full'); staffAsset = asset('staff'); + for (const entry of readdirSync(out).filter(name => name !== '.stackledger-build')) cpSync(join(out, entry), join(publish, entry), { recursive: true }); + const files = readdirSync(join(publish, '_astro'), { recursive: true, withFileTypes: true }).filter(entry => entry.isFile() && /\.(css|js)$/.test(entry.name)); + asset = `/${relative(publish, join(files[0]!.parentPath, files[0]!.name))}`; // The oauth2-proxy stand-in. auth = createServer((request, response) => { @@ -108,38 +105,50 @@ describe.runIf(caddy)('Caddy in front of oauth2-proxy (examples/hosting/Caddyfil const servesNothing = (body: string) => !/<html|Northwind/i.test(body); test('Anonymous request: no site content on any path', async () => { - for (const path of ['/', '/staff/', '/full/', '/full/renewals.ics', fullAsset, staffAsset]) { + for (const path of ['/', '/software/', '/renewals.ics', '/full/', '/full/renewals.ics', asset]) { const answer = await get(path); expect(answer.status, path).not.toBe(200); expect(servesNothing(answer.body), path).toBe(true); - // The host has no page at /; every other path names a published file. - if (path !== '/') expect(answer.body, path).not.toBe(file(path)); + // Every path but / and the old ones names a published file. + if (path !== '/' && !path.startsWith('/full')) expect(answer.body, path).not.toBe(file(path)); } }); - test('Staff identity: /staff/ is served, every /full/ path answers 403', async () => { - const staff = await get('/staff/', 'staff'); - expect(staff.status).toBe(200); - expect(staff.body).toBe(file('/staff/')); - for (const path of ['/full/', '/full/renewals.ics', fullAsset]) { - const answer = await get(path, 'staff'); - expect(answer.status, path).toBe(403); - expect(answer.body, path).toBe(''); + test('Reader identity: everything is served, with no split', async () => { + for (const session of ['reader', 'both']) { + for (const path of ['/', '/software/', '/reports/', '/renewals.ics', asset]) { + const answer = await get(path, session); + expect(answer.status, `${session} ${path}`).toBe(200); + expect(answer.body, `${session} ${path}`).toBe(file(path)); + } } + expect((await get('/renewals.ics', 'reader')).type).toMatch(/^text\/calendar/); }); - test('Finance identity: /full/ and /staff/ are served', async () => { - for (const path of ['/full/', '/staff/', '/full/renewals.ics']) { - const answer = await get(path, 'finance'); - expect(answer.status, path).toBe(200); - expect(answer.body, path).toBe(file(path)); + test('Old addresses redirect to the same path at the root, for a reader only', async () => { + const cases: [string, string][] = [['/full', '/'], ['/full/', '/'], ['/full/software/', '/software/'], ['/full/renewals.ics', '/renewals.ics']]; + for (const [from, to] of cases) { + const answer = await fetch(`${base}${from}`, { headers: { 'X-Test-Session': 'reader' }, redirect: 'manual' }); + expect(answer.status, from).toBe(301); + expect(new URL(answer.headers.get('location')!, base).pathname, from).toBe(to); + // Without the group there is no redirect, only the refusal. + expect((await get(from, 'staff')).status, from).toBe(403); + expect((await get(from)).status, from).not.toBe(301); } - expect((await get('/full/renewals.ics', 'finance')).type).toMatch(/^text\/calendar/); }); - test('Signed in without an allowed group: every path answers 403', async () => { - for (const session of ['nogroups', 'contractors']) { - for (const path of ['/', '/staff/', '/full/']) { + test('Former staff paths and a double slash are not redirected', async () => { + const staff = await fetch(`${base}/staff/`, { headers: { 'X-Test-Session': 'reader' }, redirect: 'manual' }); + expect(staff.status).toBe(404); + expect(staff.headers.get('location')).toBeNull(); + const double = await fetch(`${base}/full//example.org/`, { headers: { 'X-Test-Session': 'reader' }, redirect: 'manual' }); + const location = double.headers.get('location'); + expect(location === null || new URL(location, base).origin === new URL(base).origin).toBe(true); + }); + + test('Signed in without the readers group: every path answers 403', async () => { + for (const session of ['nogroups', 'contractors', 'staff']) { + for (const path of ['/', '/software/', '/renewals.ics', '/full/']) { const answer = await get(path, session); expect(answer.status, `${session} ${path}`).toBe(403); expect(answer.body, `${session} ${path}`).toBe(''); @@ -147,19 +156,18 @@ describe.runIf(caddy)('Caddy in front of oauth2-proxy (examples/hosting/Caddyfil } }); - test('Forged group header: the client cannot claim finance', async () => { - expect((await get('/full/', 'staff', 'finance')).status).toBe(403); - expect((await get('/full/', 'nogroups', 'finance')).status).toBe(403); - expect((await get('/staff/', 'nogroups', 'finance')).status).toBe(403); - expect((await get('/staff/', 'nogroups', 'staff')).status).toBe(403); + test('Forged group header: the client cannot claim readers', async () => { + expect((await get('/', 'staff', 'readers')).status).toBe(403); + expect((await get('/', 'nogroups', 'readers')).status).toBe(403); + expect((await get('/renewals.ics', 'contractors', 'readers')).status).toBe(403); }); // Last: it stops the stand-in for good. test('Auth service down: every path answers an error with no site content', async () => { await new Promise<void>(resolve => auth!.close(() => resolve())); auth = undefined; - for (const session of [undefined, 'finance']) { - for (const path of ['/', '/staff/', '/full/', '/full/renewals.ics', fullAsset]) { + for (const session of [undefined, 'reader']) { + for (const path of ['/', '/software/', '/renewals.ics', '/full/', asset]) { const answer = await get(path, session); expect(answer.status, `${session} ${path}`).toBeGreaterThanOrEqual(500); expect(servesNothing(answer.body), `${session} ${path}`).toBe(true); diff --git a/test/integration/map.test.ts b/test/integration/map.test.ts index 266e4094..87e285b5 100644 --- a/test/integration/map.test.ts +++ b/test/integration/map.test.ts @@ -38,15 +38,16 @@ test('Map usage errors print a reason and usage on stderr only',()=>{ const r=run(args);expect(r.status,args.join(' ')).toBe(2);expect(r.stdout).toBe('');expect(r.stderr).toMatch(/.+\nUsage:/); } }); +const STAFF_NOTE='stackledger map: the staff view is deprecated and unused by the site, which shows everything (ADR 13); it will be removed\n'; test('Map help wins over invalid arguments',()=>{const r=run(['map','--theme','blue','--help','a','b']);expect(r.status).toBe(0);expect(r.stdout).toContain('stackledger map <folder>');expect(r.stderr).toBe('');}); -test('One error in full',()=>{const f=folder({'catalogue.yaml':yaml(component('a'),component('b'),line(),layout(),set(component('broken'),'spec.owner',undefined))});const r=run(['map',f]);expect(r.status).toBe(0);parse(r.stdout);expect(r.stderr).toBe('stackledger map: 1 error, 0 warnings; run stackledger validate for details\n');expect(run(['map',f,'--view','staff']).stderr).toBe('');}); +test('One error in full',()=>{const f=folder({'catalogue.yaml':yaml(component('a'),component('b'),line(),layout(),set(component('broken'),'spec.owner',undefined))});const r=run(['map',f]);expect(r.status).toBe(0);parse(r.stdout);expect(r.stderr).toBe('stackledger map: 1 error, 0 warnings; run stackledger validate for details\n');expect(run(['map',f,'--view','staff']).stderr).toBe(STAFF_NOTE);}); test('Clean catalogue',()=>{const r=run(['map',fixture()]);expect(r.status).toBe(0);expect(r.stderr).toBe('');}); test('Broken layout',()=>{const f=folder({'catalogue.yaml':yaml(component('a'),component('b'),line(),set(layout(),'spec.stations',{'component:a':[2.5,1]}))});for(const view of ['full','staff']){const r=run(['map',f,'--view',view]);expect(r.status).toBe(0);expect(r.stderr).toContain('Stored positions are not used because the layout has errors\n');expect(r.stderr).toContain(' component:a: [0, 0]\n component:b: [1, 0]\n');parse(r.stdout);}}); -test('Two unplaced stops',()=>{const f=folder({'catalogue.yaml':yaml(component('b'),component('a'),line())}),r=run(['map',f,'--view','staff']);expect(r.status).toBe(0);expect(r.stderr).toBe('Suggested positions for MapLayout spec.stations:\n component:a: [0, 0]\n component:b: [1, 0]\n');}); +test('Two unplaced stops',()=>{const f=folder({'catalogue.yaml':yaml(component('b'),component('a'),line())}),r=run(['map',f,'--view','staff']);expect(r.status).toBe(0);expect(r.stderr).toBe(STAFF_NOTE+'Suggested positions for MapLayout spec.stations:\n component:a: [0, 0]\n component:b: [1, 0]\n');}); test('Unroutable hop',()=>{const f=folder({'catalogue.yaml':yaml(component('a'),component('b'),line(),set(layout(),'spec.stations',{'component:a':[0,0],'component:b':[100000,100000]}))}),r=run(['map',f]);expect(r.status).toBe(0);expect(r.stderr).toBe('Unrouted hop: line:ship component:a -> component:b (drawn straight)\n');parse(r.stdout);}); test('Parseable output',()=>{const f=folder({'catalogue.yaml':yaml(component('a'),component('b'),line(),set(component('broken'),'spec.owner',undefined))}),r=run(['map',f]);expect(r.status).toBe(0);const doc=parse(r.stdout);expect(doc.documentElement.tagName).toBe('svg');expect(r.stdout).toMatch(/^<svg[\s\S]*<\/svg>\n$/);expect(r.stdout).not.toContain('Suggested positions');expect(r.stderr).toContain('1 error');expect(r.stderr).toContain('Suggested positions');}); test('Global help lists both commands',()=>{const r=run(['--help']);expect(r.status).toBe(0);for(const c of ['validate','mcp','map'])expect(r.stdout).toContain(`stackledger ${c}`);}); -test('Explicit staff and dark options select their output',()=>{const r=run(['map',fixture(),'--view','staff','--theme','dark','--date','2027-06-01']);expect(r.status).toBe(0);expect(r.stderr).toBe('');expect(r.stdout).toContain(`fill="${themes.dark.background}"`);expect(parse(r.stdout).documentElement.textContent).toContain('staff view');expect(r.stdout).not.toContain('Renewal within 30 days');}); +test('Explicit staff and dark options select their output',()=>{const r=run(['map',fixture(),'--view','staff','--theme','dark','--date','2027-06-01']);expect(r.status).toBe(0);expect(r.stderr).toBe(STAFF_NOTE);expect(r.stdout).toContain(`fill="${themes.dark.background}"`);expect(parse(r.stdout).documentElement.textContent).toContain('staff view');expect(r.stdout).not.toContain('Renewal within 30 days');}); test('Map library bundles for the browser without Node filesystem imports',()=>{ // esbuild is a pinned development dependency (Vite 8 no longer brings it in). const source=['model:buildMapModel','layout:layoutMap','svg:renderSvg'].map(entry=>{const [file,name]=entry.split(':');return `export { ${name} } from './src/map/${file}.ts';`;}).join('\n'); diff --git a/test/integration/mcp.test.ts b/test/integration/mcp.test.ts index 57a3c7c2..5877c8ce 100644 --- a/test/integration/mcp.test.ts +++ b/test/integration/mcp.test.ts @@ -277,8 +277,8 @@ test('Clean stdout', async () => { test('Start line', async () => { const root = catalogue(component()); await withSession(root, 'staff', async session => { - const lines = (await waitFor(session.stderr, '\n')).split('\n').filter(Boolean); - expect(lines).toHaveLength(1); expect(lines[0]).toContain(root); expect(lines[0]).toContain('staff'); expect(lines[0]).toContain('4 tools'); + const lines = (await waitFor(session.stderr, 'tools\n')).split('\n').filter(Boolean); + expect(lines).toHaveLength(2); expect(lines[0]).toContain(root); expect(lines[0]).toContain('staff'); expect(lines[0]).toContain('4 tools'); expect(lines[1]).toContain('staff view is deprecated'); }); }); test('Failed call line', async () => { @@ -294,6 +294,6 @@ test('Failed call line for a tool the view does not offer', async () => { await waitFor(session.stderr, 'tools\n'); failed(await session.call('renewals', { from: '2027-06-01' })); const lines = (await waitFor(session.stderr, 'renewals')).split('\n').filter(Boolean); - expect(lines).toHaveLength(2); expect(lines[1]).toMatch(/renewals.*not found/); + expect(lines).toHaveLength(3); expect(lines[2]).toMatch(/renewals.*not found/); }); }); diff --git a/test/integration/site-helpers.ts b/test/integration/site-helpers.ts index 296c4def..7e59cb48 100644 --- a/test/integration/site-helpers.ts +++ b/test/integration/site-helpers.ts @@ -1,4 +1,4 @@ -/** Build fixture catalogues into both sites with the built package, in a child process. +/** Build fixture catalogues into the site with the built package, in a child process. * Build first with npm run build. Each build runs dist/site/build.js prepareBuild in its own Node * process (Astro changes the current directory and must not run inside the test runner's module * system). Folders live in the test's temporary directory and are removed by cleanup(). @@ -15,7 +15,7 @@ import { root } from './helpers.js'; const run = promisify(execFile); const created: string[] = []; -export interface Built { catalogue: string; staging: string; staff: string; full: string; root: string } +export interface Built { catalogue: string; staging: string; site: string; root: string } export async function buildSites(files: Record<string, string>, date = '2027-06-01'): Promise<Built> { const base = mkdtempSync(join(tmpdir(), 'stackledger-site-')); @@ -31,7 +31,7 @@ export async function buildSites(files: Record<string, string>, date = '2027-06- const module = pathToFileURL(join(root, 'dist/site/build.js')).href; const script = `const { prepareBuild } = await import(${JSON.stringify(module)}); await prepareBuild(...JSON.parse(process.argv[1]));`; await run(process.execPath, ['--input-type=module', '-e', script, JSON.stringify([catalogue, staging, date])], { env: { ...process.env, NODE_OPTIONS: '' }, timeout: 120_000 }); - return { catalogue, staging, staff: join(staging, 'site-staff'), full: join(staging, 'site-full'), root: join(staging, 'root') }; + return { catalogue, staging, site: join(staging, 'site'), root: join(staging, 'root') }; } export function cleanup(): void { diff --git a/test/integration/site-skills.test.ts b/test/integration/site-skills.test.ts index 10cc731f..2ec3af4b 100644 --- a/test/integration/site-skills.test.ts +++ b/test/integration/site-skills.test.ts @@ -27,7 +27,7 @@ function writeFolder(path: string, files: Record<string, string>): string { /** Every file below `dir`, relative, `/`-separated. */ const files = (dir: string) => readdirSync(dir, { recursive: true, withFileTypes: true }).filter(entry => entry.isFile()) .map(entry => join(entry.parentPath, entry.name).slice(dir.length + 1).split('\\').join('/')); -const html = (out: string, site: string, path: string) => readFileSync(join(out, site, path, 'index.html'), 'utf8'); +const html = (out: string, path: string) => readFileSync(join(out, path, 'index.html'), 'utf8'); const main = (text: string) => /<main[\s\S]*<\/main>/.exec(text)![0]; const stops = (name: string, names: string[]) => set(line(name), 'spec.stops', names.map(item => `component:${item}`)); const catalogueFiles = (extra: unknown[] = []) => ({ 'catalog-info.yaml': yaml(component('editor'), component('forge'), stops('ship', ['editor', 'forge']), ...extra) }); @@ -64,11 +64,11 @@ afterAll(() => { if (base) rmSync(base, { recursive: true, force: true }); }); // catalogue-site, Internal links in the same tab, "Only external anchors open a new tab": the Skills // pages link only inside the site, so none of their anchors has a target or a new-tab note. test('Only external anchors open a new tab (Skills pages)', () => { - for (const site of ['full', 'staff']) { - const htmlFiles = files(join(out, site)).filter(file => file.endsWith('.html')); + { + const htmlFiles = files(out).filter(file => file.endsWith('.html')); expect(htmlFiles.filter(file => file.startsWith('skills/')).length).toBeGreaterThan(0); for (const file of htmlFiles) { - const text = readFileSync(join(out, site, file), 'utf8'); + const text = readFileSync(join(out, file), 'utf8'); for (const [anchor] of text.matchAll(/<a\b(?:"[^"]*"|'[^']*'|[^>"'])*>/g)) expect(anchor, file).not.toMatch(/\starget\s*=/); expect(text, file).not.toContain('opens in a new tab'); } @@ -76,34 +76,34 @@ test('Only external anchors open a new tab (Skills pages)', () => { }); test('Skills link', () => { - for (const site of ['full', 'staff']) { + { for (const page of ['', 'software/editor', 'skills', 'skills/writer']) { - const header = /<header[\s\S]*?<\/header>/.exec(html(out, site, page))![0]; - expect(header, `${site}/${page}`).toMatch(/href="(?:\.\.\/)*skills\/"[^>]*>\s*Skills\s*</); + const header = /<header[\s\S]*?<\/header>/.exec(html(out, page))![0]; + expect(header, page).toMatch(/href="(?:\.\.\/)*skills\/"[^>]*>\s*Skills\s*</); } - expect(html(plain, site, '')).not.toMatch(/skills\//); + expect(html(plain, '')).not.toMatch(/skills\//); } }); // catalogue-site, Layout and Home page, with a skill set. test('Default title (Skills pages)', () => { - for (const site of ['full', 'staff']) { + { for (const page of ['skills', 'skill-map', 'rules', 'skills/writer']) { - const text = html(out, site, page); - expect(text, `${site}/${page}`).toMatch(/<title>[^<]* \| stackledger<\/title>/); - expect(text, `${site}/${page}`).toMatch(/<a class="navbar-brand" href="[^"]*"><img class="brand-mark" src="(?:\.\.\/)*favicon\.svg" alt="" width="28" height="28">stackledger<\/a>/); + const text = html(out, page); + expect(text, page).toMatch(/<title>[^<]* \| stackledger<\/title>/); + expect(text, page).toMatch(/<a class="navbar-brand" href="[^"]*"><img class="brand-mark" src="(?:\.\.\/)*favicon\.svg" alt="" width="28" height="28">stackledger<\/a>/); } } }); test('Title opens the home', () => { - for (const site of ['full', 'staff']) { - expect(html(out, site, 'skills')).toContain('<a class="navbar-brand" href="../">'); - expect(html(out, site, 'software/editor')).toContain('<a class="navbar-brand" href="../../">'); - expect(html(out, site, '')).toContain('<a class="navbar-brand" href="./">'); + { + expect(html(out, 'skills')).toContain('<a class="navbar-brand" href="../">'); + expect(html(out, 'software/editor')).toContain('<a class="navbar-brand" href="../../">'); + expect(html(out, '')).toContain('<a class="navbar-brand" href="./">'); } }); test('Home without skills', () => { - for (const site of ['full', 'staff']) { - const home = main(html(plain, site, '')); + { + const home = main(html(plain, '')); expect(home).not.toContain('>Skills<'); expect(home).not.toMatch(/skills\//); } }); @@ -119,17 +119,17 @@ test.concurrent('Home in full and staff', async () => { const target = join(base, 'home-out'); const result = await run([counted, '--out', target, '--date', DATE, '--skills', kit]); expect(result.status, result.stderr).toBe(0); - for (const site of ['full', 'staff']) { - const home = main(html(target, site, '')); - expect(home, site).toMatch(/3 components, 2 licences and 1 journey\./); - expect(home, site).toMatch(/2 skills, 1 playbook, 1 agent and 4 rules\./); - for (const path of ['map/', 'skills/', 'skill-map/', 'rules/']) expect(home, `${site} ${path}`).toContain(`href="${path}"`); - expect(home.includes('href="reports/"'), site).toBe(site === 'full'); - expect(home, site).toContain('Your software and skills, mapped.'); + { + const home = main(html(target, '')); + expect(home).toMatch(/3 components, 2 licences and 1 journey\./); + expect(home).toMatch(/2 skills, 1 playbook, 1 agent and 4 rules\./); + for (const path of ['map/', 'skills/', 'skill-map/', 'rules/']) expect(home, path).toContain(`href="${path}"`); + expect(home).toContain('href="reports/"'); + expect(home).toContain('Your software and skills, mapped.'); } }, 180_000); test('Item pages', () => { - for (const site of ['full', 'staff']) for (const page of ['skills/writer', 'playbooks/release', 'agents/reviewer']) expect(existsSync(join(out, site, page, 'index.html'))).toBe(true); + for (const page of ['skills/writer', 'playbooks/release', 'agents/reviewer']) expect(existsSync(join(out, page, 'index.html'))).toBe(true); }); // Its own set: `writer` and `Writer` are one folder on a case-insensitive file system (macOS, Windows). test.concurrent('Name that is not a file name', async () => { @@ -137,37 +137,24 @@ test.concurrent('Name that is not a file name', async () => { const target = join(base, 'upper-out'); const result = await run([catalogue, '--out', target, '--date', DATE, '--skills', kit]); expect(result.status, result.stderr).toBe(0); - expect(html(target, 'full', 'skills/_577269746572')).toContain('<h1>Writer</h1>'); + expect(html(target, 'skills/_577269746572')).toContain('<h1>Writer</h1>'); }, 180_000); test('Skill and agent with one name', () => { - expect(existsSync(join(out, 'full', 'skills', 'reviewer', 'index.html'))).toBe(true); expect(existsSync(join(out, 'full', 'agents', 'reviewer', 'index.html'))).toBe(true); + expect(existsSync(join(out, 'skills', 'reviewer', 'index.html'))).toBe(true); expect(existsSync(join(out, 'agents', 'reviewer', 'index.html'))).toBe(true); }); test('No skill set', () => { - for (const site of ['full', 'staff']) { - for (const folder of ['skills', 'skill-map', 'rules', 'playbooks', 'agents']) expect(existsSync(join(plain, site, folder))).toBe(false); - for (const file of files(join(plain, site)).filter(file => file.endsWith('.html'))) { - expect(readFileSync(join(plain, site, file), 'utf8'), file).not.toMatch(/href="[^"]*(?:skills|skill-map|rules|playbooks|agents)\//); + { + for (const folder of ['skills', 'skill-map', 'rules', 'playbooks', 'agents']) expect(existsSync(join(plain, folder))).toBe(false); + for (const file of files(plain).filter(file => file.endsWith('.html'))) { + expect(readFileSync(join(plain, file), 'utf8'), file).not.toMatch(/href="[^"]*(?:skills|skill-map|rules|playbooks|agents)\//); } } }); test('Rules page', () => { - const nav = /<nav class="sub-nav[^"]*" aria-label="Skills">[\s\S]*?<\/nav>/.exec(html(out, 'full', 'rules'))![0]; + const nav = /<nav class="sub-nav[^"]*" aria-label="Skills">[\s\S]*?<\/nav>/.exec(html(out, 'rules'))![0]; for (const path of ['skills/', 'skill-map/', 'rules/']) expect(nav).toContain(`href="../${path}"`); expect([...nav.matchAll(/aria-current="page"[^>]*>\s*([^<]+?)\s*</g)].map(match => match[1])).toEqual(['Rules']); }); -test('Both sites', () => { - const pages = files(join(out, 'full')).filter(file => /^(skills|skill-map|rules|playbooks|agents)\/.*index\.html$/.test(file)); - expect(pages.length).toBeGreaterThan(8); - for (const page of pages) expect(main(readFileSync(join(out, 'staff', page), 'utf8')), page).toBe(main(readFileSync(join(out, 'full', page), 'utf8'))); -}); -test.concurrent('Personal build', async () => { - const cat = writeFolder(join(base, 'personal'), catalogueFiles([settings('settings', { sites: ['full'] })])); - const kit = writeFolder(join(base, 'personal-kit'), { 'writer/SKILL.md': skill('writer') }); - const target = join(base, 'personal-out'); - const result = await run([cat, '--out', target, '--date', DATE, '--skills', kit]); - expect(result.status, result.stderr).toBe(0); - expect(existsSync(join(target, 'full', 'skills', 'writer', 'index.html'))).toBe(true); expect(existsSync(join(target, 'staff'))).toBe(false); -}, 180_000); test.concurrent('Relative skills folder', async () => { const top = join(base, 'relative'); writeFolder(join(top, 'northwind-kit'), { 'skills/writer/SKILL.md': skill('writer') }); @@ -175,7 +162,7 @@ test.concurrent('Relative skills folder', async () => { const target = join(base, 'relative-out'); const result = await run([catalogue, '--out', target, '--date', DATE, '--skills', '../northwind-kit'], join(top, 'work')); expect(result.status, result.stderr).toBe(0); - expect(html(target, 'full', 'skills/writer')).toContain('<code>skills/writer/SKILL.md</code>'); + expect(html(target, 'skills/writer')).toContain('<code>skills/writer/SKILL.md</code>'); for (const file of files(target)) expect(readFileSync(join(target, file), 'utf8'), file).not.toContain('northwind-kit'); }, 180_000); /** The page without the site's own images (catalogue-site "Family mark", "Parent brand endorsement"): class, empty alt, the only allowed attributes and a site art src. */ @@ -183,51 +170,51 @@ const SITE_IMAGE = /<img class="(?:brand-mark|symbol-mark themed-(?:light|dark)| const withoutSiteImages = (html: string) => html.replace(SITE_IMAGE, ''); test('Description with HTML', () => { - for (const file of files(join(out, 'full')).filter(file => file.endsWith('.html'))) expect(withoutSiteImages(readFileSync(join(out, 'full', file), 'utf8')), file).not.toMatch(/<img\b/); - expect(html(out, 'full', 'skills/writer')).toContain('<img src=x onerror=alert(1)>'); + for (const file of files(out).filter(file => file.endsWith('.html'))) expect(withoutSiteImages(readFileSync(join(out, file), 'utf8')), file).not.toMatch(/<img\b/); + expect(html(out, 'skills/writer')).toContain('<img src=x onerror=alert(1)>'); }); test('Hostile script text', () => { - for (const file of files(join(out, 'full')).filter(file => file.endsWith('.html'))) { - for (const script of readFileSync(join(out, 'full', file), 'utf8').match(/<script\b[^>]*>/g) ?? []) expect(script, file).toMatch(/src="[^"]+\.js"/); + for (const file of files(out).filter(file => file.endsWith('.html'))) { + for (const script of readFileSync(join(out, file), 'utf8').match(/<script\b[^>]*>/g) ?? []) expect(script, file).toMatch(/src="[^"]+\.js"/); } }); test('Bidirectional override', () => { - for (const site of ['full', 'staff']) for (const file of files(join(out, site))) expect(readFileSync(join(out, site, file), 'utf8'), file).not.toContain(RLO); - expect(existsSync(join(out, 'full', 'skills', 'writer', 'index.html'))).toBe(true); + for (const file of files(out)) expect(readFileSync(join(out, file), 'utf8'), file).not.toContain(RLO); + expect(existsSync(join(out, 'skills', 'writer', 'index.html'))).toBe(true); // The skill named with U+202E has its page at its page file name, and its name and source path lose the character. - expect(html(out, 'full', `skills/_${Buffer.from(`w${RLO}r`).toString('hex')}`)).toContain('<h1>wr</h1>'); + expect(html(out, `skills/_${Buffer.from(`w${RLO}r`).toString('hex')}`)).toContain('<h1>wr</h1>'); }); test('Tool folder in the home folder', () => { - expect(html(out, 'full', 'skills/writer')).toContain('<code>writer/SKILL.md</code>'); - for (const site of ['full', 'staff']) for (const file of files(join(out, site))) expect(readFileSync(join(out, site, file), 'utf8'), file).not.toContain('/home/northwind'); + expect(html(out, 'skills/writer')).toContain('<code>writer/SKILL.md</code>'); + for (const file of files(out)) expect(readFileSync(join(out, file), 'utf8'), file).not.toContain('/home/northwind'); }); test('Shared rule ID', () => { - const rules = html(out, 'full', 'rules'); + const rules = html(out, 'rules'); const developer = rules.indexOf('href="../skills/developer/"'), documentation = rules.indexOf('href="../skills/documentation/"'); expect(developer).toBeGreaterThan(-1); expect(documentation).toBeGreaterThan(developer); expect(rules.match(/<code>DOC-1<\/code>/g)).toHaveLength(2); }); test('Rule of a playbook', () => { - expect(html(out, 'full', 'rules')).toMatch(/<code>REL-1<\/code>[\s\S]*?href="\.\.\/playbooks\/release\/"/); + expect(html(out, 'rules')).toMatch(/<code>REL-1<\/code>[\s\S]*?href="\.\.\/playbooks\/release\/"/); }); // metro-map "Legend of a skills map", as the site shows it: the symbols are listed under the map. test('Legend of a skills map on the site', () => { - const symbols = /<ul class="map-symbols">([\s\S]*?)<\/ul>/.exec(html(out, 'full', 'skill-map'))![1]!; + const symbols = /<ul class="map-symbols">([\s\S]*?)<\/ul>/.exec(html(out, 'skill-map'))![1]!; const labels = ['Interchange', 'Number of rules', 'Suggested position']; for (const label of labels) expect(symbols).toContain(label); expect(labels.map(label => symbols.indexOf(label))).toEqual([...labels.map(label => symbols.indexOf(label))].sort((a, b) => a - b)); expect(symbols).not.toContain('Licence'); }); test('Relation error keeps the page', () => { - expect(html(out, 'full', 'skills')).toContain('href="../playbooks/release/"'); expect(html(out, 'full', 'playbooks/release')).not.toContain('ghost'); + expect(html(out, 'skills')).toContain('href="../playbooks/release/"'); expect(html(out, 'playbooks/release')).not.toContain('ghost'); }); test.concurrent('No rules and no skill lines', async () => { const kit = writeFolder(join(base, 'bare-kit'), { 'notes/SKILL.md': skill('notes') }); const target = join(base, 'bare-out'); const result = await run([catalogue, '--out', target, '--date', DATE, '--skills', kit]); expect(result.status, result.stderr).toBe(0); - expect(html(target, 'full', 'rules')).toContain('No rules'); - const map = html(target, 'full', 'skill-map'); + expect(html(target, 'rules')).toContain('No rules'); + const map = html(target, 'skill-map'); expect(map).toContain('No skill lines yet'); expect(map).toContain('stackledger-skills.yaml'); }, 180_000); test.concurrent('Every item rejected', async () => { @@ -235,18 +222,18 @@ test.concurrent('Every item rejected', async () => { const target = join(base, 'rejected-out'); const result = await run([catalogue, '--out', target, '--date', DATE, '--skills', kit]); expect(result.status, result.stderr).toBe(0); - expect(html(target, 'full', 'skills')).toContain('No skills'); - expect(html(target, 'full', 'skill-map')).toContain('No skill lines yet'); expect(html(target, 'full', 'rules')).toContain('No rules'); + expect(html(target, 'skills')).toContain('No skills'); + expect(html(target, 'skill-map')).toContain('No skill lines yet'); expect(html(target, 'rules')).toContain('No rules'); }, 180_000); // catalogue-site "Interface icons": the skills map page's zoom buttons carry the same icons as the map page. test('Zoom buttons with icons (skills map)', () => { const icons = siteIcons(); - for (const site of ['full', 'staff']) { - const page = html(out, site, 'skill-map'); + { + const page = html(out, 'skill-map'); for (const [zoom, icon] of [['in', icons.zoomIn], ['out', icons.zoomOut], ['reset', icons.reset]] as const) { const button = new RegExp(`<button[^>]*data-zoom="${zoom}"[^>]*>([\\s\\S]*?)</button>`).exec(page)![1]!; - expect(button, `${site} ${zoom}`).toContain(icon); + expect(button, zoom).toContain(icon); } expect(page).toMatch(/<button[^>]*data-zoom="in"[^>]*aria-label="Zoom in"/); } diff --git a/test/integration/site.test.ts b/test/integration/site.test.ts index 7226d5c8..f219ee9c 100644 --- a/test/integration/site.test.ts +++ b/test/integration/site.test.ts @@ -113,25 +113,30 @@ const svgCatalogue = { // catalogue-site "Diagram box titles": a title of spaces is valid in the catalogue. const blankCatalogue = { 'catalogue.yaml': yaml(set(depends(component('forge'), ['component:vault']), 'metadata.title', ' '), component('vault'), depends(component('editor'), ['component:forge'])) }; -let main: Built, other: Built, customA: Built, customB: Built, broken: Built, hostile: Built, example: Built, linked: Built, empty: Built, blank: Built, iconed: Built, svgHostile: Built, city: Built, iconOnly: Built; +let main: Built, withStaffSettings: Built, other: Built, customA: Built, customB: Built, broken: Built, hostile: Built, example: Built, linked: Built, empty: Built, blank: Built, iconed: Built, svgHostile: Built, city: Built, iconOnly: Built; beforeAll(async () => { const exampleFiles = Object.fromEntries(['catalog-info.yaml', 'stackledger.yaml'].map(file => [file, read(join(root, 'examples/northwind'), file)])); - [main, other, customA, customB, broken, hostile, example, linked, empty, blank, iconed, svgHostile, city, iconOnly] = await Promise.all([ + // The example's Settings is `spec: {}`; the cases below put their settings under it. + const withSpec = (extra: string) => exampleFiles['stackledger.yaml']!.replace('spec: {}\n', `spec:\n${extra}`); + [main, withStaffSettings, other, customA, customB, broken, hostile, example, linked, empty, blank, iconed, svgHostile, city, iconOnly] = await Promise.all([ buildSites(mainCatalogue(DEFAULT_HIDDEN), '2027-06-01'), + // The same catalogue with the two deprecated settings: they must change nothing in the site. + buildSites({ ...mainCatalogue(DEFAULT_HIDDEN), 'stackledger.yaml': settingsFile({ site: { title: 'Northwind software', colors: { accent: '#E4002B' } }, + sites: ['full', 'staff'], views: { staff: { hide: ['cost', 'note'] } } }) }, '2027-06-01'), buildSites(mainCatalogue(OTHER_HIDDEN), '2031-01-01'), buildSites(customHidden('Northwind Studio', 'to-confirm'), '2027-06-01'), buildSites(customHidden('Zeta Supplies', 'expired'), '2027-06-01'), buildSites(brokenCatalogue), buildSites(hostileCatalogue), buildSites(exampleFiles), - buildSites({ ...exampleFiles, 'stackledger.yaml': exampleFiles['stackledger.yaml']! + HOME_SETTINGS }), + buildSites({ ...exampleFiles, 'stackledger.yaml': withSpec(HOME_SETTINGS) }), buildSites(emptyCatalogue), buildSites(blankCatalogue), - buildSites({ ...exampleFiles, 'stackledger.yaml': exampleFiles['stackledger.yaml']! + ICON_SETTINGS }), + buildSites({ ...exampleFiles, 'stackledger.yaml': withSpec(ICON_SETTINGS) }), buildSites(svgCatalogue), - buildSites({ ...exampleFiles, 'stackledger.yaml': exampleFiles['stackledger.yaml']! + HOME_SETTINGS + CITY_SETTINGS }), - buildSites({ ...exampleFiles, 'stackledger.yaml': exampleFiles['stackledger.yaml']! + ICON_ONLY_SETTINGS }), + buildSites({ ...exampleFiles, 'stackledger.yaml': withSpec(HOME_SETTINGS + CITY_SETTINGS) }), + buildSites({ ...exampleFiles, 'stackledger.yaml': withSpec(ICON_ONLY_SETTINGS) }), ]); }, 180_000); @@ -147,21 +152,21 @@ const decode = (value: string) => value.replaceAll(''', "'").replaceAll('&qu // catalogue-site test('Item pages', () => { - for (const site of [main.full, main.staff]) { + for (const site of [main.site]) { for (const page of ['software/editor/index.html', 'software/forge/index.html', 'licences/licence-editor/index.html']) expect(pages(site)).toContain(page); } - expect(pages(main.full)).not.toContain('licences/orders-db/index.html'); + expect(pages(main.site)).not.toContain('licences/orders-db/index.html'); }); test('No journeys', () => { - for (const site of [broken.full, broken.staff]) { + for (const site of [broken.site]) { expect(read(site, 'map/index.html')).toContain('No journeys yet'); expect(read(site, 'journeys/index.html')).toContain('There are no journeys yet.'); } }); test('Site title', () => { - for (const site of [main.full, main.staff]) { + for (const site of [main.site]) { for (const page of pages(site)) { const html = read(site, page); // The home's title is the site title alone (catalogue-site, Home page chrome). @@ -172,17 +177,21 @@ test('Site title', () => { }); test('View in the footer', () => { - for (const page of pages(main.staff)) expect(read(main.staff, page), page).toMatch(/<footer[\s\S]*staff view · stackledger \d+\.\d+\.\d+/); - expect(read(main.full, 'index.html')).toMatch(/<footer[\s\S]*full view · stackledger/); + // The footer says the stackledger version and no view name (catalogue-site, Layout). + for (const page of pages(main.site)) { + const footer = /<footer[\s\S]*<\/footer>/.exec(read(main.site, page))![0]; + expect(footer, page).toMatch(/stackledger \d+\.\d+\.\d+/); + expect(footer, page).not.toMatch(/\b(full|staff) view\b/); + } }); // catalogue-site "Parent brand endorsement". test('Footer endorsement', () => { - for (const [view, site] of [['full', main.full], ['staff', main.staff]] as const) { + for (const site of [main.site]) { for (const page of pages(site)) { const footer = /<footer[\s\S]*<\/footer>/.exec(read(site, page))![0]; const depth = '(?:\\.\\.\\/)*'; - expect(footer, page).toMatch(new RegExp(`${view} view · stackledger \\d+\\.\\d+\\.\\d+ · <span class="endorsement">` + expect(footer, page).toMatch(new RegExp(`<p class="container">stackledger \\d+\\.\\d+\\.\\d+ · <span class="endorsement">` + `<img class="symbol-mark themed-light" src="${depth}symbol-light\\.svg" alt="" width="16" height="16">` + `<img class="symbol-mark themed-dark" src="${depth}symbol-dark\\.svg" alt="" width="16" height="16"> by Bruno Souza</span>`)); // No link holds the symbols or the words. @@ -192,7 +201,7 @@ test('Footer endorsement', () => { }); test('No SVG of the sites holds a style', () => { - for (const site of [iconed.full, iconed.staff]) { + for (const site of [iconed.site]) { const svgs = [...tree(site)].filter(([file]) => file.endsWith('.svg')); expect(svgs.map(([file]) => file)).toEqual(expect.arrayContaining(['symbol-light.svg', 'symbol-dark.svg', 'home-banner.svg', 'favicon.svg', 'link-icons/github-light.svg'])); for (const [file, content] of svgs) expect(content, file).not.toMatch(/<style\b/i); @@ -202,7 +211,7 @@ test('No SVG of the sites holds a style', () => { // catalogue-site "Family mark": the templates write img elements only for these files. test('No other images', () => { const allowed = /^(?:\.\.\/)*(?:favicon\.svg|symbol-light\.svg|symbol-dark\.svg|home-banner\.svg|link-icons\/[a-z]+-(?:light|dark)\.svg)$/; - for (const site of [iconed.full, iconed.staff]) { + for (const site of [iconed.site]) { let icons = 0; for (const page of pages(site)) { for (const tag of tagsOf(read(site, page)).filter(tag => tag.name === 'img')) { @@ -253,20 +262,19 @@ function systemDark(site: string, name: string): string | undefined { } test('Accent override', () => { - expect(accents(main.full)).toEqual({ light: '#e4002b', dark: DEFAULT_ACCENTS.dark }); - expect(accents(main.staff)).toEqual({ light: '#e4002b', dark: DEFAULT_ACCENTS.dark }); + expect(accents(main.site)).toEqual({ light: '#e4002b', dark: DEFAULT_ACCENTS.dark }); }); // catalogue-site "Override keeps the dark accent". test('Override keeps the dark accent', () => { - for (const site of [main.full, main.staff]) { + for (const site of [main.site]) { expect(resolved(site, '--color-accent', 'light')).toBe('#e4002b'); expect(resolved(site, '--color-accent', 'dark')).toBe('#7d8cff'); } }); test('Broken settings', () => { - for (const site of [broken.full, broken.staff]) { + for (const site of [broken.site]) { expect(accents(site)).toEqual(DEFAULT_ACCENTS); expect(read(site, 'map/index.html')).toContain('<title>Map | stackledger'); expect(read(site, 'map/index.html')).not.toContain('Northwind software'); @@ -275,7 +283,7 @@ test('Broken settings', () => { // catalogue-site "Site tokens from the design system". test('Palette from the design system', () => { - for (const site of [example.full, example.staff]) { + for (const site of [example.site]) { expect(themeVar(site, '--ds-site-light-body').light).toBe('#f6f3ec'); expect(themeVar(site, '--ds-site-dark-body').light).toBe('#121110'); expect(themeVar(site, '--color-body')).toEqual({ light: 'var(--ds-site-light-body)', dark: 'var(--ds-site-dark-body)' }); @@ -283,7 +291,7 @@ test('Palette from the design system', () => { }); test("Accent stays stackledger's", () => { - for (const site of [example.full, example.staff]) { + for (const site of [example.site]) { expect(accents(site)).toEqual(DEFAULT_ACCENTS); expect(systemDark(site, '--color-accent')).toBe(DEFAULT_ACCENTS.dark); expect([resolved(site, '--color-accent', 'light'), resolved(site, '--color-accent', 'dark')]).toEqual(['#3b5bdb', '#7d8cff']); @@ -292,7 +300,7 @@ test("Accent stays stackledger's", () => { // catalogue-site "Family mark": the header shows the mark before a custom title. test('Header mark with a custom title', () => { - for (const site of [main.full, main.staff]) { + for (const site of [main.site]) { for (const page of ['index.html', 'map/index.html', 'software/editor/index.html']) { const html = read(site, page); expect(html, page).toMatch(/Northwind software<\/a>/); @@ -304,7 +312,7 @@ test('Header mark with a custom title', () => { // catalogue-site "Diagram box titles": the build succeeds and every neighbourhood diagram shows the reference. test('Blank title', () => { - for (const site of [blank.full, blank.staff]) { + for (const site of [blank.site]) { for (const page of ['software/forge/index.html', 'software/vault/index.html', 'software/editor/index.html']) { const html = read(site, page); const box = /[\s\S]*?<\/g>/.exec(html)![0]; @@ -314,13 +322,13 @@ test('Blank title', () => { }); test('Journeys', () => { - const html = read(main.full, 'software/editor/index.html'); + const html = read(main.site, 'software/editor/index.html'); expect(html).toContain('href="../../journeys/design/"'); expect(html).toContain('href="../../journeys/ship/"'); }); test('Line with one served stop', () => { - for (const site of [main.full, main.staff]) { + for (const site of [main.site]) { const html = read(site, 'software/editor/index.html'); expect(html).toContain('old'); expect(html).not.toContain('journeys/old/'); @@ -328,24 +336,22 @@ test('Line with one served stop', () => { } }); -test('Staff licence page', () => { - const html = read(main.staff, 'licences/licence-editor/index.html'); - expect(html).toContain('
Vendor
Northwind Studio
'); - expect(html).toContain('
Status
active
'); - for (const label of ['Cost', 'Currency', 'Cycle', 'Renews on', 'Paid by', 'Seats', 'Vault item', 'Note']) expect(html).not.toContain(`
${label}
`); - for (const value of Object.values(DEFAULT_HIDDEN)) expect(html).not.toContain(String(value)); - // The full site shows them. - expect(read(main.full, 'licences/licence-editor/index.html')).toContain('
Cost
98765
'); +test('Every licence field', () => { + // catalogue-site, Licence page content: the site shows every field, the default-hidden ones too. + const html = read(main.site, 'licences/licence-editor/index.html'); + for (const label of ['Vendor', 'Status', 'Cost', 'Currency', 'Cycle', 'Renews on', 'Paid by', 'Seats', 'Vault item', 'Note']) expect(html).toContain(`
${label}
`); + expect(html).toContain('
Cost
98765
'); + for (const value of Object.values(DEFAULT_HIDDEN)) expect(html).toContain(String(value)); }); test('Indirect dependant', () => { - const html = read(main.full, 'software/vault/index.html'); + const html = read(main.site, 'software/vault/index.html'); expect(html).toContain('
forge1'); expect(html).toContain('Northwind Editor2'); }); test('Interchange on a strip', () => { - const html = read(main.full, 'journeys/ship/index.html'); + const html = read(main.site, 'journeys/ship/index.html'); // The strip shows slack's stop with the design badge, which links to the design journey. expect(html).toMatch(//); expect(html).toMatch(/design<\/title>/); @@ -355,7 +361,7 @@ test('Interchange on a strip', () => { }); test('Diagram alternative', () => { - const html = read(main.full, 'software/forge/index.html'); + const html = read(main.site, 'software/forge/index.html'); expect(html).toMatch(/<div class="diagram[^"]* themed-light"><svg [^>]*role="img"/); const dependencies = /<ul class="plain-list" data-dependencies>([\s\S]*?)<\/ul>/.exec(html)![1]!; expect(dependencies).toContain('<span>orders-db</span>'); @@ -365,7 +371,7 @@ test('Diagram alternative', () => { }); test('Without JavaScript (table present)', () => { - const html = read(example.full, 'software/index.html'); + const html = read(example.site, 'software/index.html'); const rows = /<tbody>([\s\S]*?)<\/tbody>/.exec(html)![1]!.match(/<tr>/g) ?? []; expect(rows).toHaveLength(17 + 14); expect(html).not.toMatch(/<tr[^>]*hidden/); @@ -373,7 +379,7 @@ test('Without JavaScript (table present)', () => { }); test('Map page legends in HTML, not in the map', () => { - for (const site of [example.full, example.staff]) { + for (const site of [example.site]) { const html = read(site, 'map/index.html'); const svg = /<div class="map-canvas themed-light">([\s\S]*?)<\/div>/.exec(html)![1]!; for (const chrome of ['Lines (journeys)', '>Symbols<', 'stackledger · ']) expect(svg).not.toContain(chrome); @@ -382,12 +388,12 @@ test('Map page legends in HTML, not in the map', () => { expect(html).toMatch(/<div class="map-lines" data-map-lines>/); const symbols = /<ul class="map-symbols">([\s\S]*?)<\/ul>/.exec(html)![1]!; for (const label of ['Interchange', 'Licence', 'Licence to buy']) expect(symbols).toContain(label); - expect(symbols.includes('Renewal within 30 days')).toBe(site === example.full); + expect(symbols.includes('Renewal within 30 days')).toBe(site === example.site); } }); test('Owners by name', () => { - for (const site of [example.full, example.staff]) { + for (const site of [example.site]) { expect(read(site, 'software/slack/index.html')).toContain('<dt>Owner</dt><dd>Northwind team</dd>'); expect(read(site, 'licences/licence-slack/index.html')).toContain('<dt>Owner</dt><dd>Northwind team</dd>'); const list = read(site, 'software/index.html'); @@ -396,15 +402,15 @@ test('Owners by name', () => { expect(list).not.toContain('group:northwind'); } // Without an owner document, the reference itself is shown. - expect(read(main.full, 'software/editor/index.html')).toContain('<dt>Owner</dt><dd>user:alex</dd>'); + expect(read(main.site, 'software/editor/index.html')).toContain('<dt>Owner</dt><dd>user:alex</dd>'); }); -test('Reports in full only', () => { +test('Reports at the root', () => { + // catalogue-site, Site pages / "Reports at the root": the Reports page and the calendar, and nothing under full/ or staff/. for (const built of [main, example]) { - expect(pages(built.full)).toContain('reports/index.html'); - expect(tree(built.full).has('renewals.ics')).toBe(true); - expect(pages(built.staff)).not.toContain('reports/index.html'); - expect(tree(built.staff).has('renewals.ics')).toBe(false); + expect(pages(built.site)).toContain('reports/index.html'); + expect(tree(built.site).has('renewals.ics')).toBe(true); + for (const file of tree(built.site).keys()) expect(file, file).not.toMatch(/^(full|staff)\//); } }); @@ -413,16 +419,15 @@ const subNav = (html: string) => /<nav class="sub-nav[^"]*" aria-label="Software test('Reports link', () => { // The home has no sub-navigation (Home page chrome); its Software card links Reports in full only. - for (const page of pages(main.full).filter(page => page !== 'index.html')) expect(subNav(read(main.full, page)), page).toMatch(REPORTS_LINK); - for (const page of pages(main.staff)) expect(read(main.staff, page), page).not.toContain('Reports'); + for (const page of pages(main.site).filter(page => page !== 'index.html')) expect(subNav(read(main.site, page)), page).toMatch(REPORTS_LINK); // Relative from a nested page too. - expect(subNav(read(main.full, 'software/editor/index.html'))).toMatch(/href="\.\.\/\.\.\/reports\/"/); + expect(subNav(read(main.site, 'software/editor/index.html'))).toMatch(/href="\.\.\/\.\.\/reports\/"/); }); const homeMain = (html: string) => /<main[\s\S]*<\/main>/.exec(html)![0]; test('Map at /map/', () => { - for (const site of [example.full, example.staff]) { + for (const site of [example.site]) { expect(read(site, 'map/index.html')).toContain('data-ref="component:slack"'); const home = read(site, 'index.html'); expect(home).not.toContain('map-canvas'); @@ -437,7 +442,7 @@ test('Map at /map/', () => { }); test('Default title', () => { - for (const site of [example.full, example.staff, broken.full, broken.staff]) { + for (const site of [example.site, broken.site]) { for (const page of pages(site)) { const html = read(site, page); expect(html, page).toMatch(page === 'index.html' ? /<title>stackledger<\/title>/ : /<title>[^<]* \| stackledger<\/title>/); @@ -447,31 +452,31 @@ test('Default title', () => { }); test('Home chrome', () => { - for (const site of [main.full, main.staff, example.full]) { + for (const site of [main.site, example.site]) { const html = read(site, 'index.html'); expect(html).not.toContain('class="sub-nav'); const header = /<header[\s\S]*?<\/header>/.exec(html)![0]; expect(header).not.toContain('aria-current'); } - expect(read(main.full, 'index.html')).toContain('<title>Northwind software'); + expect(read(main.site, 'index.html')).toContain('Northwind software'); }); test('Home text', () => { - const html = homeMain(read(linked.full, 'index.html')); + const html = homeMain(read(linked.site, 'index.html')); expect(html).toContain('Northwind tools'); expect(html).not.toContain('Your software and skills, mapped.'); - expect(homeMain(read(example.full, 'index.html'))).toContain('Your software and skills, mapped.'); + expect(homeMain(read(example.site, 'index.html'))).toContain('Your software and skills, mapped.'); }); test('Empty catalogue', () => { - for (const site of [empty.full, empty.staff]) { + for (const site of [empty.site]) { const html = homeMain(read(site, 'index.html')); expect(html).toMatch(/0 components, 0 licences and 0 journeys\./); } }); test('Two links', () => { - for (const site of [linked.full, linked.staff]) { + for (const site of [linked.site]) { const html = homeMain(read(site, 'index.html')); expect(html).toContain('

Links

'); // Each anchor shows only its title; the new-tab note after it is visually hidden (External links in a new tab). @@ -482,12 +487,12 @@ test('Two links', () => { expect(html.indexOf('What I write')).toBeGreaterThan(html.indexOf('>Articles<')); expect(html.indexOf('What I write')).toBeLessThan(html.indexOf('>Team wiki<')); } - expect(homeMain(read(example.full, 'index.html'))).not.toContain('

Links

'); + expect(homeMain(read(example.site, 'index.html'))).not.toContain('

Links

'); }); // catalogue-site "Home banner art": after the h1 and the text, a decorative image from the site's folder. test('Banner on the home', () => { - for (const site of [example.full, example.staff, linked.full]) { + for (const site of [example.site, linked.site]) { const banner = /
([\s\S]*?)<\/section>/.exec(read(site, 'index.html'))![1]!; expect(banner).toMatch(/

[^<]+<\/h1>\s*

[^<]+<\/p>\s*/); expect(existsSync(join(site, 'home-banner.svg'))).toBe(true); @@ -523,7 +528,7 @@ const iconImages = (icon: string) => (['light', 'dark'] as const).map(surface => ({ class: `themed-${surface}`, src: `link-icons/${icon}-${surface}.svg`, alt: '', width: '32', height: '32' })); test('Icon row before text links', () => { - for (const site of [iconed.full, iconed.staff]) { + for (const site of [iconed.site]) { const html = homeMain(read(site, 'index.html')); const heading = html.indexOf('

Links

'); expect(heading).toBeGreaterThan(-1); @@ -542,18 +547,18 @@ test('Icon row before text links', () => { }); test('Only icon links', () => { - for (const site of [iconOnly.full, iconOnly.staff]) { + for (const site of [iconOnly.site]) { const html = homeMain(read(site, 'index.html')); expect(html).toContain('

Links

'); expect(iconRow(html)!.map(anchor => anchor.attrs['aria-label'])).toEqual(['Site', 'Source', 'Catalogue'].map(newTab)); expect(html).not.toContain('home-external'); } // And a home with text links only has no row. - for (const site of [linked.full, linked.staff]) expect(homeMain(read(site, 'index.html'))).not.toContain('home-icon-links'); + for (const site of [linked.site]) expect(homeMain(read(site, 'index.html'))).not.toContain('home-icon-links'); }); test('Link with an icon', () => { - for (const site of [iconed.full, iconed.staff]) { + for (const site of [iconed.site]) { const html = read(site, 'index.html'); const source = iconRow(html)!.find(anchor => anchor.attrs['aria-label'] === newTab('Source'))!; expect(source.attrs).toEqual({ href: 'https://github.example.com/northwind/', target: '_blank', rel: 'noopener noreferrer', 'aria-label': 'Source (opens in a new tab)' }); @@ -568,7 +573,7 @@ test('Link with an icon', () => { test('Each icon link holds only its own icon', () => { const icons: Record = { Site: 'website', Source: 'github', Catalogue: 'stackledger', Mirror: 'github', 'Bruno Souza': 'brunosouzas' }; - for (const site of [iconed.full, iconed.staff, iconOnly.full, iconOnly.staff]) { + for (const site of [iconed.site, iconOnly.site]) { const row = iconRow(read(site, 'index.html'))!; expect(row.length).toBeGreaterThan(0); for (const anchor of row) expect(anchor.images, anchor.attrs['aria-label']).toEqual(iconImages(icons[anchor.attrs['aria-label']!.replace(NEW_TAB, '')]!)); @@ -576,7 +581,7 @@ test('Each icon link holds only its own icon', () => { }); test('Same icon twice', () => { - for (const site of [iconed.full, iconed.staff]) { + for (const site of [iconed.site]) { const github = iconRow(read(site, 'index.html'))!.filter(anchor => anchor.images.some(image => image.src!.includes('github'))); expect(github.map(anchor => [anchor.attrs.href, anchor.attrs['aria-label'], anchor.attrs.title])).toEqual([ ['https://github.example.com/northwind/', newTab('Source'), undefined], @@ -587,7 +592,7 @@ test('Same icon twice', () => { }); test('Link with the stackledger icon', () => { - for (const site of [iconed.full, iconed.staff]) { + for (const site of [iconed.site]) { const catalogue = iconRow(read(site, 'index.html'))!.find(anchor => anchor.attrs.href === 'https://catalogue.example.com/')!; expect([catalogue.attrs['aria-label'], catalogue.attrs.title]).toEqual([newTab('Catalogue'), undefined]); expect(catalogue.images).toEqual(iconImages('stackledger')); @@ -596,7 +601,7 @@ test('Link with the stackledger icon', () => { }); test('Link with the brunosouzas icon', () => { - for (const site of [iconed.full, iconed.staff]) { + for (const site of [iconed.site]) { const bruno = iconRow(read(site, 'index.html'))!.find(anchor => anchor.attrs['aria-label'] === newTab('Bruno Souza'))!; expect(bruno.attrs).toEqual({ href: 'https://www.example.com/', target: '_blank', rel: 'noopener noreferrer', 'aria-label': 'Bruno Souza (opens in a new tab)' }); expect(bruno.images).toEqual(iconImages('brunosouzas')); @@ -605,7 +610,7 @@ test('Link with the brunosouzas icon', () => { }); test('Hostile icon title', () => { - for (const site of [hostile.full, hostile.staff]) { + for (const site of [hostile.site]) { const html = read(site, 'index.html'); const [anchor] = iconRow(html)!; expect([anchor!.attrs['aria-label'], anchor!.attrs.title]).toEqual([newTab(HOSTILE_ICON), undefined]); @@ -618,7 +623,7 @@ test('Hostile icon title', () => { }); test('Icon with broken settings', () => { - for (const site of [broken.full, broken.staff]) { + for (const site of [broken.site]) { const html = homeMain(read(site, 'index.html')); expect(html).not.toContain('link-icons/'); expect(html).not.toContain('home-icon-links'); @@ -626,7 +631,7 @@ test('Icon with broken settings', () => { }); test('Broken settings, no links', () => { - for (const site of [broken.full, broken.staff]) { + for (const site of [broken.site]) { const html = homeMain(read(site, 'index.html')); expect(html).not.toContain('

Links

'); expect(html).not.toContain('example.org'); @@ -635,14 +640,14 @@ test('Broken settings, no links', () => { }); test('Hostile link text', () => { - const html = read(linked.full, 'index.html'); + const html = read(linked.site, 'index.html'); expect(html).toContain('<script>alert(1)</script>'); expect(html).not.toContain(HOSTILE_LINK); }); // catalogue-site, External links in a new tab: every anchor to another site opens in a new tab and says so. test('Text link in a new tab', () => { - for (const site of [iconed.full, iconed.staff]) { + for (const site of [iconed.site]) { const anchor = tagsOf(homeMain(read(site, 'index.html'))).filter(tag => tag.name === 'a') .map(tag => Object.fromEntries(attrsOf(tag.attrs).map(attr => [attr.name, decodeAll(attr.value)]))) .find(attrs => attrs.href === 'https://blog.example.com/')!; @@ -652,7 +657,7 @@ test('Text link in a new tab', () => { }); test('Icon link in a new tab', () => { - for (const site of [iconed.full, iconed.staff]) { + for (const site of [iconed.site]) { const source = iconRow(read(site, 'index.html'))!.find(anchor => anchor.attrs.href === 'https://github.example.com/northwind/')!; expect(source.attrs).toEqual({ href: 'https://github.example.com/northwind/', target: '_blank', rel: 'noopener noreferrer', 'aria-label': 'Source (opens in a new tab)' }); expect(source.text.trim()).toBe(''); @@ -660,7 +665,7 @@ test('Icon link in a new tab', () => { }); test('Map credit in a new tab', () => { - for (const site of [city.full, city.staff]) { + for (const site of [city.site]) { const credit = /

([\s\S]*?)<\/p>/.exec(read(site, 'map/index.html'))![1]!; expect(credit.trim()).toBe(`Map data © OpenStreetMap contributors${NEW_TAB_NOTE}`); } @@ -676,7 +681,7 @@ const absolute = (url = '') => /^(?:[A-Za-z][A-Za-z0-9+.-]*:|\/\/)/.test(url); // catalogue-site, Internal links in the same tab: only the anchors to other sites have a target. test('Only external anchors open a new tab', () => { - for (const site of [iconed.full, iconed.staff, linked.full, linked.staff, city.full, city.staff]) { + for (const site of [iconed.site, linked.site, city.site]) { const anchors = anchorsOf(site); const external = anchors.filter(anchor => absolute(anchor.attrs.href)); expect(external.length, site).toBeGreaterThan(0); @@ -692,12 +697,12 @@ test('Only external anchors open a new tab', () => { } } // Both kinds of page: the city sites' map pages hold the credit, the home pages the links. - expect(anchorsOf(city.full).filter(anchor => absolute(anchor.attrs.href)).map(anchor => anchor.page)) + expect(anchorsOf(city.site).filter(anchor => absolute(anchor.attrs.href)).map(anchor => anchor.page)) .toEqual(['index.html', 'index.html', 'index.html', 'map/index.html']); }); test('No external link, no new tab', () => { - for (const site of [example.full, example.staff]) { + for (const site of [example.site]) { for (const page of pages(site)) { const html = read(site, page); expect(tagsOf(html).filter(tag => tag.name === 'a' && /\starget\s*=/.test(tag.attrs)), page).toEqual([]); @@ -709,7 +714,7 @@ test('No external link, no new tab', () => { // site-security, No external requests: the configured links are the only absolute URLs, on the home only. test('Home links are the only external URLs', () => { const external = /^(?:[A-Za-z][A-Za-z0-9+.-]*:|\/\/)/; - for (const site of [linked.full, linked.staff]) { + for (const site of [linked.site]) { const found: string[] = []; for (const [file, content] of tree(site)) { if (!file.endsWith('.html')) continue; @@ -726,7 +731,7 @@ test('Home links are the only external URLs', () => { // site-security, Map credit link: over a city backdrop, the map page's credit anchor is the only other absolute URL. test('Map credit is the only other external URL', () => { const external = /^(?:[A-Za-z][A-Za-z0-9+.-]*:|\/\/)/; - for (const site of [city.full, city.staff]) { + for (const site of [city.site]) { const found: string[] = []; for (const [file, content] of tree(site)) { if (!file.endsWith('.html')) continue; @@ -743,7 +748,7 @@ test('Map credit is the only other external URL', () => { test('Software sub-navigation', () => { for (const page of ['journeys/index.html', 'journeys/ship/index.html']) { - const html = read(main.full, page); + const html = read(main.site, page); const header = //.exec(html)![0]; expect(header).toMatch(/aria-current="page"[^>]*>\s*Software|>\s*Software\s*<\/a>/); expect(header).not.toContain('Journeys'); @@ -757,28 +762,23 @@ test('Software sub-navigation', () => { // licence-reports -test('Not in staff', () => { - for (const built of [main, example, broken]) { - expect(pages(built.staff).some(page => page.startsWith('reports/'))).toBe(false); - for (const [file, content] of tree(built.staff)) { - for (const value of ['renewals.ics', 'reports/', '>Reports<', 'Recurring cost']) expect(content.includes(value), `${file} ${value}`).toBe(false); - } - } +test('Home links Reports', () => { + expect(homeMain(read(main.site, 'index.html'))).toContain('href="reports/"'); }); test('Site report date', () => { - const html = read(example.full, 'reports/index.html'); + const html = read(example.site, 'reports/index.html'); expect(html).toContain('Licence costs and renewals on 2027-06-01, with renewals up to 2027-08-30 (90 days).'); - const calendar = read(example.full, 'renewals.ics'); + const calendar = read(example.site, 'renewals.ics'); const stamps = [...calendar.matchAll(/^DTSTAMP:(.*)\r$/gm)].map(match => match[1]); expect(stamps.length).toBeGreaterThan(0); for (const stamp of stamps) expect(stamp).toBe('20270601T000000Z'); // Another build date moves the report with it. - expect(read(other.full, 'reports/index.html')).toContain('renewals on 2031-01-01, with renewals up to 2031-04-01'); + expect(read(other.site, 'reports/index.html')).toContain('renewals on 2031-01-01, with renewals up to 2031-04-01'); }); test('Page content', () => { - const html = read(example.full, 'reports/index.html'); + const html = read(example.site, 'reports/index.html'); const recurring = /([\s\S]*?)<\/table>/.exec(html)![1]!; expect(recurring).toContain(''); expect(recurring).toContain(''); @@ -792,41 +792,33 @@ test('Page content', () => { }); test('Empty report', () => { - expect(read(hostile.full, 'reports/index.html')).toContain('There are no licences.'); - expect(read(hostile.full, 'renewals.ics')).not.toContain('BEGIN:VEVENT'); + expect(read(hostile.site, 'reports/index.html')).toContain('There are no licences.'); + expect(read(hostile.site, 'renewals.ics')).not.toContain('BEGIN:VEVENT'); }); // site-security -test('No trace of the cost', () => { - for (const [file, content] of tree(main.staff)) for (const value of ['98765', 'ZETA-NOTE']) expect(content.includes(value), `${file} ${value}`).toBe(false); - expect([...tree(main.full).values()].some(content => content.includes('98765'))).toBe(true); +// site-security, One site from the full view. +test('Costs are in the site', () => { + expect([...tree(main.site).values()].some(content => content.includes('98765'))).toBe(true); + expect(read(main.site, 'licences/licence-editor/index.html')).toContain('ZETA-NOTE'); + expect(read(main.site, 'reports/index.html')).toContain('98765'); }); -test('Staff ignores hidden fields and the date', () => { - expect(tree(other.staff)).toEqual(tree(main.staff)); - // The full sites do differ, so the fixtures really carry different values. - expect(tree(other.full)).not.toEqual(tree(main.full)); +test('Staff settings have no effect', () => { + expect(tree(withStaffSettings.site)).toEqual(tree(main.site)); + // customHidden hides vendor and status for the staff view; the site shows them. + expect(read(customA.site, 'licences/licence-editor/index.html')).toContain('Northwind Studio'); + expect(read(customB.site, 'licences/licence-editor/index.html')).toContain('Zeta Supplies'); + expect(tree(other.site)).not.toEqual(tree(main.site)); }); -test('Custom-hidden vendor and status', () => { - expect(tree(customB.staff)).toEqual(tree(customA.staff)); - for (const [file, content] of tree(customA.staff)) { - for (const value of ['Northwind Studio', 'to-confirm', '
Vendor
', '
Status
']) expect(content.includes(value), `${file} ${value}`).toBe(false); - } - for (const [file, content] of tree(customB.staff)) for (const value of ['Zeta Supplies', 'expired']) expect(content.includes(value), `${file} ${value}`).toBe(false); - expect(read(customA.full, 'licences/licence-editor/index.html')).toContain('Northwind Studio'); -}); - -test('Broken settings hide the defaults', () => { - for (const [file, content] of tree(broken.staff)) { - for (const value of Object.values(DEFAULT_HIDDEN)) expect(content.includes(String(value)), `${file} ${value}`).toBe(false); - } - expect(read(broken.full, 'licences/licence-editor/index.html')).toContain('98765'); +test('Broken settings still show every field', () => { + expect(read(broken.site, 'licences/licence-editor/index.html')).toContain('98765'); }); test('Same policy everywhere', () => { - for (const site of [example.full, example.staff]) { + for (const site of [example.site]) { expect(pages(site).length).toBeGreaterThan(30); for (const page of pages(site)) { const tags = tagsOf(read(site, page)); @@ -849,7 +841,7 @@ test('Same policy everywhere', () => { test('Only local URLs', () => { const external = /^(?:[A-Za-z][A-Za-z0-9+.-]*:|\/\/)/; let checked = 0; - for (const site of [example.full, example.staff]) { + for (const site of [example.site]) { for (const [file, content] of tree(site)) { if (file.endsWith('.html')) { for (const tag of tagsOf(content)) { @@ -883,12 +875,12 @@ const HEADERS = `/* `; test('Root headers', () => { - for (const dir of [example.root, example.full, example.staff]) expect(read(dir, '_headers')).toBe(HEADERS); + for (const dir of [example.site]) expect(read(dir, '_headers')).toBe(HEADERS); expect(read(example.root, '.stackledger-build')).toBe('This folder is written by stackledger build. The next build replaces it.\n'); }); test('Root robots', () => { - for (const dir of [example.root, example.full, example.staff]) expect(read(dir, 'robots.txt')).toBe('User-agent: *\nDisallow: /\n'); + for (const dir of [example.site]) expect(read(dir, 'robots.txt')).toBe('User-agent: *\nDisallow: /\n'); }); // catalogue-site "Look and theme": the Source families replace Heebo, Signika and Lato. @@ -901,7 +893,7 @@ const fontsourceFiles = () => FONT_PACKAGES.flatMap(name => { }); test('Lato shipped locally', () => { - for (const site of [example.full, example.staff]) { + for (const site of [example.site]) { for (const [file, content] of tree(site)) { if (/\.(?:woff2?|ttf)$/.test(file)) continue; expect(content, file).not.toMatch(/Heebo|Signika|Lato/); @@ -913,7 +905,7 @@ test('Lato shipped locally', () => { test('Source font packages', () => { for (const name of FONT_PACKAGES) expect(pkg.dependencies[name], name).toBe('5.3.1'); const shipped = new Set(fontsourceFiles()); - for (const site of [example.full, example.staff]) { + for (const site of [example.site]) { const fonts = [...tree(site)].filter(([file]) => /\.(?:woff2?|ttf|otf)$/.test(file)); expect(fonts.length).toBe(7); for (const [file, bytes] of fonts) expect(shipped.has(bytes), file).toBe(true); @@ -932,7 +924,7 @@ function faces(site: string): { family: string; weight: string; style: string; u // catalogue-site "Font delivery". test('Source fonts shipped locally', () => { - for (const site of [example.full, example.staff]) { + for (const site of [example.site]) { const real = faces(site).filter(face => face.url); const named = real.map(face => `${face.family.replace(/^"|"$/g, '').replace(/-[0-9a-f]{16}$/, '')} ${face.weight} ${face.style}`).sort(); expect(named).toEqual(['Source Code Pro 400 normal', 'Source Sans 3 400 normal', 'Source Sans 3 600 normal', 'Source Sans 3 700 normal', @@ -954,7 +946,7 @@ test('Source fonts shipped locally', () => { }); test('Font CSS moved to a file', () => { - for (const site of [example.full, example.staff]) { + for (const site of [example.site]) { const css = read(site, '_astro/fonts.css'); const urls = [...css.matchAll(/url\(([^)]*)\)/g)].map(match => match[1]!.replace(/^"|"$/g, '')); expect(urls.length).toBe(7); @@ -975,12 +967,12 @@ test('Font CSS moved to a file', () => { for (const preload of html.matchAll(/]*as="font"/g)) expect(preload.index, page).toBeGreaterThan(csp); } } - for (const site of [main.full, main.staff]) expect(read(site, 'software/editor/index.html')).toContain(''); + for (const site of [main.site]) expect(read(site, 'software/editor/index.html')).toContain(''); }); // catalogue-site "Font variables": only _astro/fonts.css defines --font-*. test('Font variables only from the Fonts API', () => { - for (const site of [example.full, example.staff]) { + for (const site of [example.site]) { for (const [file, content] of tree(site)) { if (!file.endsWith('.css')) continue; const defined = [...content.matchAll(/(--font-[a-z-]+)\s*:/g)].map(match => match[1]); @@ -991,7 +983,7 @@ test('Font variables only from the Fonts API', () => { }); test('Hostile title', () => { - for (const site of [hostile.full, hostile.staff]) { + for (const site of [hostile.site]) { let shown = 0; for (const page of pages(site)) { const html = read(site, page); @@ -1016,7 +1008,7 @@ const inlineIcons = (html: string) => [...html.matchAll(/]*aria-hidden= const button = (html: string, attr: string) => new RegExp(`]*${attr}[^>]*>([\\s\\S]*?)`).exec(html)![1]!; test('Zoom buttons with icons', () => { - for (const site of [example.full, example.staff]) { + for (const site of [example.site]) { const html = read(site, 'map/index.html'); const zoomIn = button(html, 'data-zoom="in"'), zoomOut = button(html, 'data-zoom="out"'), reset = button(html, 'data-zoom="reset"'); expect(inlineIcons(zoomIn)).toEqual([ICONS.zoomIn]);expect(inlineIcons(zoomOut)).toEqual([ICONS.zoomOut]);expect(inlineIcons(reset)).toEqual([ICONS.reset]); @@ -1030,7 +1022,7 @@ test('Zoom buttons with icons', () => { }); test('Calendar button with an icon', () => { - const html = read(example.full, 'reports/index.html'); + const html = read(example.site, 'reports/index.html'); const link = /]*download="renewals.ics"[^>]*>([\s\S]*?)<\/a>/.exec(html)![1]!; expect(link.trimStart().startsWith('' + ICONS.download)).toBe(true); expect(link.replace(/<[^>]+>/g, '').trim()).toBe('Download the renewal calendar (renewals.ics)'); @@ -1039,7 +1031,7 @@ test('Calendar button with an icon', () => { test('Interface icons are inert', () => { const known = new Set(Object.values(ICONS)); let seen = 0; - for (const built of [example, main, svgHostile]) for (const site of [built.full, built.staff]) for (const page of pages(site)) { + for (const built of [example, main, svgHostile]) for (const site of [built.site]) for (const page of pages(site)) { for (const icon of inlineIcons(read(site, page))) { seen++; expect(known.has(icon), page).toBe(true); @@ -1055,7 +1047,7 @@ test('Interface icons are inert', () => { test('No icon from catalogue text', () => { const known = new Set(Object.values(ICONS)); - for (const site of [svgHostile.full, svgHostile.staff]) { + for (const site of [svgHostile.site]) { let shown = 0; for (const page of pages(site)) { const html = read(site, page); diff --git a/test/integration/skills-marketplace.test.ts b/test/integration/skills-marketplace.test.ts index 8a02c5ba..4c8b0ba7 100644 --- a/test/integration/skills-marketplace.test.ts +++ b/test/integration/skills-marketplace.test.ts @@ -54,12 +54,10 @@ test('Site pages of the same-named agents', () => { const out = join(temp, 'site'); const result = run(['build', 'examples/northwind', '--out', out, '--date', '2027-06-01', '--skills', MARKET]); expect(result.status).toBe(0); - for (const view of ['full', 'staff']) { - for (const plugin of ['writing', 'review']) { - const file = join(out, view, 'agents', `${plugin}--reviewer`, 'index.html'); - expect(existsSync(file)).toBe(true); - expect(readFileSync(file, 'utf8')).toContain('data-plugin'); - } + for (const plugin of ['writing', 'review']) { + const file = join(out, 'agents', `${plugin}--reviewer`, 'index.html'); + expect(existsSync(file)).toBe(true); + expect(readFileSync(file, 'utf8')).toContain('data-plugin'); } }, 240_000); diff --git a/test/manual-restore.ts b/test/manual-restore.ts index 7f1c01ad..934cf6ec 100644 --- a/test/manual-restore.ts +++ b/test/manual-restore.ts @@ -2,22 +2,16 @@ * tests prove that following the documentation brings the previous build back byte for byte. * Used by test/unit/site-publish.test.ts and test/integration/build.test.ts. */ -import { existsSync, readdirSync, renameSync, rmSync } from 'node:fs'; +import { existsSync, readdirSync, readFileSync, renameSync, rmSync } from 'node:fs'; import { join } from 'node:path'; -/** Each published entry with the place of its new version in the staging folder (marker excluded: - * its rename is the commit point, so before the commit the new marker is always still staged). */ -const STAGED: readonly [string, string][] = [['staff', 'site-staff'], ['full', 'site-full'], ['_headers', 'root/_headers'], ['robots.txt', 'root/robots.txt'], ['_redirects', 'root/_redirects']]; - export function manualRestore(out: string, staging: string): void { // Step 1: no staged marker means the publication had committed; only the staging folder goes. if (existsSync(join(staging, 'root', '.stackledger-build'))) { - // Step 2: an entry whose new version left the staging folder belongs to the failed build. A - // personal build (the full-only note) never had a staff site: its staff/ in is the old one. - const personal = existsSync(join(staging, 'full-only')); - for (const [name, place] of STAGED) { - if (personal && name === 'staff') continue; - if (!existsSync(join(staging, place))) rmSync(join(out, name), { recursive: true, force: true }); + // Step 2: a name listed in `entries` whose staged copy left the staging folder came from the + // failed build: delete it from . + for (const name of readFileSync(join(staging, 'entries'), 'utf8').split('\n').filter(Boolean)) { + if (!existsSync(join(staging, 'site', name))) rmSync(join(out, name), { recursive: true, force: true }); } // Step 3: move every entry of old/ back. for (const name of readdirSync(join(staging, 'old'))) renameSync(join(staging, 'old', name), join(out, name)); diff --git a/test/perf/build-skills.perf.test.ts b/test/perf/build-skills.perf.test.ts index 872fde45..7693e603 100644 --- a/test/perf/build-skills.perf.test.ts +++ b/test/perf/build-skills.perf.test.ts @@ -49,6 +49,6 @@ test('Large catalogue and skill set', async () => { console.info(`build-command: 300 items, 20 lines, 230 skill items, 2,000 rules, 10 skill lines: ${(ms / 1000).toFixed(1)} s`); expect(result.status, result.stderr).toBe(0); expect(result.stderr).toContain('Skills: 200 skills, 20 playbooks, 10 agents, 2000 rules'); - expect(readdirSync(join(out, 'full', 'skills')).length).toBe(201); + expect(readdirSync(join(out, 'skills')).length).toBe(201); expect(ms).toBeLessThan(150_000); }, 300_000); diff --git a/test/unit/hosting-docs.test.ts b/test/unit/hosting-docs.test.ts index d53f8359..ce357962 100644 --- a/test/unit/hosting-docs.test.ts +++ b/test/unit/hosting-docs.test.ts @@ -17,35 +17,23 @@ function section(text: string, heading: string): string { } const addresses = ['catalogue.example.org', '.pages.dev', '*..pages.dev']; -test('docs/hosting.md describes the personal mode first, with one application and its anonymous checks', () => { +test('docs/hosting.md has one application on the whole address of every project address, and checks every anonymous path', () => { const hosting = read('docs/hosting.md'); - const personal = section(hosting, 'Personal mode: one application'); - const corporate = section(hosting, 'Corporate mode: two applications'); - expect(personal).not.toBe(''); - expect(hosting.indexOf('Personal mode: one application')).toBeLessThan(hosting.indexOf('Corporate mode: two applications')); - const application = section(personal, 'stackledger'); + const application = section(hosting, 'stackledger'); for (const address of addresses) expect(application).toContain(address); - const checks = section(personal, 'Check the personal site'); - // /staff/ too: an older deployment or preview may still hold a staff site. - for (const path of ['/', '/full/', '/full/renewals.ics', '/full/_astro/', '/staff/']) expect(checks).toContain(`\`${path}\``); + // The destinations are whole addresses: no path rule, no second application. + expect(application).not.toMatch(/\/\*`/); + expect(hosting).not.toMatch(/stackledger (full|staff)/); + expect(hosting).not.toContain('staff-only'); + expect(hosting).not.toContain('sites: [full]'); + const checks = section(hosting, 'Check the site'); + for (const path of ['/', '/reports/', '/renewals.ics', '/_astro/', '/full/', '/full/renewals.ics']) expect(checks).toContain(`\`${path}\``); expect(checks).toMatch(/actual asset/); for (const term of ['302', 'cloudflareaccess.com']) expect(checks).toContain(term); - // One reader: no staff-only identity to test. - expect(personal).not.toContain('staff-only'); - expect(corporate).toContain('staff-only'); - expect(hosting).toContain('sites: [full]'); -}); - -test('docs/hosting.md protects every address under both corporate applications and checks every anonymous path', () => { - const hosting = read('docs/hosting.md'); - const corporate = section(hosting, 'Corporate mode: two applications'); - for (const application of ['stackledger full', 'stackledger staff']) { - for (const address of addresses) expect(section(corporate, application)).toContain(address); - } - const checks = section(corporate, 'Check the corporate sites'); - for (const path of ['/', '/staff/', '/full/', '/full/renewals.ics', '/full/_astro/', '/staff/_astro/']) expect(checks).toContain(`\`${path}\``); - for (const term of ['302', 'cloudflareaccess.com', 'staff-only']) expect(checks).toContain(term); - for (const term of ['before', 'oauth2-proxy', '--set-xauthrequest', 'Rollback', '_redirects']) expect(hosting).toContain(term); + // Access covers the root before the first deploy, and sign-in stays Access's. + expect(hosting).toMatch(/Access covering the root on every address comes before the first deploy/); + expect(hosting).toContain('stackledger has no sign-in code'); + for (const term of ['before', 'oauth2-proxy', '--set-xauthrequest', 'Rollback', '_redirects', 'readers']) expect(hosting).toContain(term); }); test('docs/release.md has each first-version bootstrap step', () => { diff --git a/test/unit/settings.test.ts b/test/unit/settings.test.ts index 4c42ea1b..5b55a28a 100644 --- a/test/unit/settings.test.ts +++ b/test/unit/settings.test.ts @@ -6,7 +6,6 @@ import { join } from 'node:path'; import { stringify } from 'yaml'; import { folder } from '../helpers.js'; import { run } from '../integration/helpers.js'; -import { resolveSites } from '../../src/views.js'; const hiding = (hide: unknown, name = 'settings') => settings(name, { views: { staff: { hide } } }); test('Settings is a supported kind', () => { expect(check(settings()).problems).toEqual([]); }); test('Unsupported pair', () => { const result = errors(set(settings(), 'apiVersion', 'backstage.io/v1alpha1')); expect(result).toMatchObject([{ field: 'apiVersion' }]); expect(result[0].message).toContain('stackledger/v1alpha1 Settings'); }); @@ -17,14 +16,22 @@ test('Settings needs a spec and accepts only its metadata', () => { expect(check(set(set(settings(), 'metadata.title', 'Northwind Studio'), 'metadata.namespace', 'default')).problems).toEqual([]); expect(errors(set(settings(), 'metadata.labels', { a: 'b' }))).toMatchObject([{ field: 'metadata.labels' }]); }); -test('Staff hide list', () => { expect(check(hiding(['cost', 'renewsOn'])).problems).toEqual([]); }); +test('Staff hide list', () => { + // catalogue, Settings / "Staff hide list" and Deprecated staff hide list: valid, with one warning. + const result = check(hiding(['cost', 'renewsOn'])); + expect(result.problems).toMatchObject([{ field: 'spec.views.staff.hide', severity: 'warning' }]); + expect(result.problems[0]!.message).toContain('shows every licence field'); + expect(check(hiding([])).problems).toMatchObject([{ field: 'spec.views.staff.hide', severity: 'warning' }]); +}); +test('Invalid hide list gets the error, not the warning', () => { expect(check(hiding(['price'])).problems).toMatchObject([{ field: 'spec.views.staff.hide[0]', severity: 'error' }]); }); +test('Settings without a hide list have no warning', () => { expect(check(settings()).problems).toEqual([]); }); test('Unknown field name in the hide list', () => { const result = errors(hiding(['price'])); expect(result).toMatchObject([{ field: 'spec.views.staff.hide[0]' }]); for (const field of ['vendor', 'status', 'cycle', 'cost', 'currency', 'renewsOn', 'seats', 'paidBy', 'vaultItem', 'note']) expect(result[0].message).toContain(field); }); test('Repeated field name', () => { expect(errors(hiding(['cost', 'cost']))).toMatchObject([{ field: 'spec.views.staff.hide[1]' }]); expect(errors(hiding(['cost', 'cost']))).toHaveLength(1); }); test('Second settings document', () => { - const result = checkFiles({ 'a.yaml': [settings('settings')], 'b.yaml': [hiding(['vendor'], 'company')] }); + const result = checkFiles({ 'a.yaml': [settings('settings')], 'b.yaml': [settings('company', { map: { backdrop: 'london' } })] }); expect(result.problems).toHaveLength(1); expect(result.problems[0]).toMatchObject({ path: 'b.yaml', severity: 'error' }); expect(result.problems[0]!.message).toContain('a.yaml'); expect(result.served.settings.map(s => s.metadata.name)[0]).toBe('settings'); }); @@ -82,21 +89,18 @@ test('Logo not supported', () => { }); const sites = (value: unknown) => settings('settings', { sites: value }); const settingsText = (sitesText: string) => `apiVersion: stackledger/v1alpha1\nkind: Settings\nmetadata:\n name: settings\nspec:\n${sitesText}`; -test('Personal mode', () => { +// catalogue, Deprecated site settings: a valid list is ignored by the build and warned about. +test('Personal list', () => { const result = check(sites(['full'])); - expect(result.problems).toEqual([]); - expect(resolveSites(result)).toEqual(['full']); + expect(result.problems).toMatchObject([{ field: 'spec.sites', severity: 'warning' }]); + expect(result.problems[0]!.message).toContain('one site at the root'); }); -test('Corporate mode in any order', () => { - for (const value of [['full', 'staff'], ['staff', 'full']]) { - const result = check(sites(value)); - expect(result.problems).toEqual([]); - expect(resolveSites(result)).toEqual(['full', 'staff']); - } +test('Corporate list in any order', () => { + for (const value of [['full', 'staff'], ['staff', 'full']]) expect(check(sites(value)).problems).toMatchObject([{ field: 'spec.sites', severity: 'warning' }]); }); -test('Corporate mode by default', () => { - expect(resolveSites(check(settings()))).toEqual(['full', 'staff']); - expect(resolveSites(check(component()))).toEqual(['full', 'staff']); +test('No sites setting, no warning', () => { + expect(check(settings()).problems).toEqual([]); + expect(check(component()).problems).toEqual([]); }); test('Staff site alone', () => { const result = checkFiles({ 'stackledger.yaml': [settingsText(' sites: [staff]\n')] }); @@ -115,11 +119,6 @@ test('Repeated site', () => { expect(result).toMatchObject([{ field: 'spec.sites[1]' }]); expect(result).toHaveLength(1); }); -test('Broken settings build both sites', () => { - // A Settings document in error is not used, so the default applies: both sites (staff hides every licence field). - expect(resolveSites(check(sites(['staff'])))).toEqual(['full', 'staff']); - expect(resolveSites(check(settings('settings', { sites: ['full'], site: { logo: 'logo.png' } })))).toEqual(['full', 'staff']); -}); // catalogue spec, Skills settings. const skills = (value: unknown) => settings('settings', { skills: value }); test('Two skills folders', () => { expect(check(skills({ folders: ['../kit', '../openspec'] })).problems).toEqual([]); }); @@ -150,8 +149,6 @@ test('Invalid backdrop falls back to neutral', () => { const out = join(folder(), 'site'); const built = run(['build', f, '--out', out, '--date', '2027-06-01']); expect(built.status, built.stderr).toBe(0); - for (const view of ['full', 'staff']) { - const page = readFileSync(join(out, view, 'map', 'index.html'), 'utf8'); - expect(page).toContain(' boole const wrap = (plan: Plan) => wrapOps(NODE_FS, plan) as unknown as Wrapper; const STAGING = '.stackledger-tmp-test'; +/** An earlier build of this version: a site at the root, with a page the new build no longer has. */ const PREVIOUS = { + 'index.html': 'old home\n', 'map/index.html': 'old map\n', 'reports/index.html': 'old reports\n', '_headers': 'old headers\n', 'robots.txt': 'old robots\n', + '_redirects': 'old redirects\n', [MARKER_NAME]: MARKER, +}; +/** An earlier two-site build (0.10.1 and before): `full/`, `staff/` and the root redirect. */ +const TWO_SITES = { 'staff/index.html': 'old staff\n', 'full/index.html': 'old full\n', '_headers': 'old headers\n', 'robots.txt': 'old robots\n', '_redirects': '/ /staff/ 302\n', [MARKER_NAME]: MARKER, }; +/** The staged one-site build: a page (`skills/`) the earlier one lacked, none of its `reports/`. */ const PREPARED = { - 'site-staff/index.html': 'new staff\n', 'site-full/index.html': 'new full\n', - 'root/_headers': 'new headers\n', 'root/robots.txt': 'new robots\n', 'root/_redirects': '/ /staff/ 302\n', [`root/${MARKER_NAME}`]: MARKER, + 'site/index.html': 'new home\n', 'site/map/index.html': 'new map\n', 'site/skills/index.html': 'new skills\n', + 'site/_headers': 'new headers\n', 'site/robots.txt': 'new robots\n', 'site/_redirects': 'new redirects\n', + entries: '_headers\n_redirects\nindex.html\nmap\nrobots.txt\nskills\n', [`root/${MARKER_NAME}`]: MARKER, }; -/** A personal build (spec.sites: [full]): no staff site, and the full-only note that says so. */ -const { 'site-staff/index.html': _staff, ...PERSONAL_BASE } = PREPARED; -const PERSONAL = { ...PERSONAL_BASE, 'root/_redirects': '/ /full/ 302\n', [FULL_ONLY]: '' }; function write(dir: string, files: Record): string { mkdirSync(dir, { recursive: true }); @@ -49,11 +54,11 @@ function write(dir: string, files: Record): string { /** An output folder (with an earlier build unless `previous` is false), its staging folder holding a * prepared build, and another folder that a swap puts in its place. */ -function fixture(previous = true, prepared: Record = PREPARED) { +function fixture(previous: Record | false = PREVIOUS, prepared: Record = PREPARED) { const base = realpathSync(folder()); - const out = write(join(base, 'out'), previous ? PREVIOUS : {}); + const out = write(join(base, 'out'), previous || {}); const staging = write(join(out, STAGING), prepared); - const other = write(join(base, 'other'), { [MARKER_NAME]: MARKER, 'staff/index.html': 'another site\n' }); + const other = write(join(base, 'other'), { [MARKER_NAME]: MARKER, 'index.html': 'another site\n' }); return { base, out, staging, other }; } @@ -72,37 +77,40 @@ function snapshot(dir: string, skip: (path: string) => boolean = () => false): R } const published = (out: string) => snapshot(out, path => path.startsWith('.stackledger-tmp-')); -// A rebuild renames 12 times (old then new, for staff, full, _headers, robots.txt, _redirects and the marker). -const RENAMES = Array.from({ length: 12 }, (_, i) => i + 1); -// A personal build over a corporate one renames 11 times: the old staff into old/, then the rest as above. -const PERSONAL_RENAMES = Array.from({ length: 11 }, (_, i) => i + 1); +// A rebuild over a one-site build renames 14 times: _headers, _redirects, index.html, map and robots.txt are in +// both builds (an old one into old/, a new one into place: 2 each), reports/ only in the old build and skills/ +// only in the new one (1 each), and the marker 2. +const RENAMES = Array.from({ length: 14 }, (_, i) => i + 1); describe('Atomic replace', () => { test('A publication puts every new entry in place and the replaced ones under old/', () => { const { out, staging } = fixture(); publish(out, staging, folderIdentity(out)); - expect(readFileSync(join(out, 'full', 'index.html'), 'utf8')).toBe('new full\n'); - expect(readdirSync(join(staging, 'old')).sort()).toEqual([MARKER_NAME, '_headers', '_redirects', 'full', 'robots.txt', 'staff']); + expect(readFileSync(join(out, 'index.html'), 'utf8')).toBe('new home\n'); + expect(readFileSync(join(out, 'skills', 'index.html'), 'utf8')).toBe('new skills\n'); + expect(readdirSync(join(staging, 'old')).sort()).toEqual([MARKER_NAME, '_headers', '_redirects', 'index.html', 'map', 'reports', 'robots.txt']); + expect(readdirSync(out).filter(name => !name.startsWith('.stackledger-tmp-')).sort()).toEqual([MARKER_NAME, '_headers', '_redirects', 'index.html', 'map', 'robots.txt', 'skills']); }); - test('Stale staff site removed: a personal build moves the old staff/ into old/ and publishes no staff/', () => { - const { out, staging } = fixture(true, PERSONAL); + test('A two-site build is replaced: full/ and staff/ move into old/ and the site is at the root', () => { + const { out, staging } = fixture(TWO_SITES); publish(out, staging, folderIdentity(out)); - expect(readdirSync(out).filter(name => !name.startsWith('.stackledger-tmp-')).sort()).toEqual([MARKER_NAME, '_headers', '_redirects', 'full', 'robots.txt']); - expect(readFileSync(join(out, '_redirects'), 'utf8')).toBe('/ /full/ 302\n'); + expect(readdirSync(out).filter(name => !name.startsWith('.stackledger-tmp-')).sort()).toEqual([MARKER_NAME, '_headers', '_redirects', 'index.html', 'map', 'robots.txt', 'skills']); expect(readFileSync(join(staging, 'old', 'staff', 'index.html'), 'utf8')).toBe('old staff\n'); + expect(readFileSync(join(staging, 'old', 'full', 'index.html'), 'utf8')).toBe('old full\n'); }); - test('A missing staff site without the full-only note is a failure, undone', () => { - const { 'site-staff/index.html': _, ...missing } = PREPARED; - const { out, staging } = fixture(true, missing); + test('A staged site folder that is missing is a failure, undone', () => { + const { out, staging } = fixture(); + rmSync(join(staging, 'site'), { recursive: true }); const before = published(out); expect(() => publish(out, staging, folderIdentity(out))).toThrow(); expect(published(out)).toEqual(before); }); - test.each(PERSONAL_RENAMES)('A failed personal build leaves the corporate site (rename %i)', nth => { - const { out, staging } = fixture(true, PERSONAL); + // The same earlier two-site build, replaced: 13 renames (full, staff, index.html, map, skills once; the rest twice). + test.each(Array.from({ length: 13 }, (_, i) => i + 1))('A failed replacement keeps the two-site build (rename %i)', nth => { + const { out, staging } = fixture(TWO_SITES); const before = published(out); const { ops } = wrap({ out, fail: [{ op: 'rename', nth }] }); expect(() => publish(out, staging, folderIdentity(out), ops)).toThrow(`injected rename failure (call ${nth})`); @@ -150,9 +158,9 @@ describe('Interrupted publication', () => { expect(snapshot(out)).toEqual(before); }); - // Personal over corporate: rename 1 moves the old staff into old/; from rename 2 on, the undo fails too. - test.each(PERSONAL_RENAMES.slice(1))('Undo failed in a personal build (rename %i): the manual restore brings the corporate site back', nth => { - const { out, staging } = fixture(true, PERSONAL); + // Two sites replaced: from rename 2 on, the undo fails too. + test.each(Array.from({ length: 12 }, (_, i) => i + 2))('Undo failed over a two-site build (rename %i): the manual restore brings both sites back', nth => { + const { out, staging } = fixture(TWO_SITES); const before = published(out); const { ops } = wrap({ out, fail: [{ op: 'rename', nth }, { op: 'rename', nth: nth + 1 }] }); expect(() => publish(out, staging, folderIdentity(out), ops)).toThrow(UndoFailed); @@ -160,11 +168,10 @@ describe('Interrupted publication', () => { expect(snapshot(out)).toEqual(before); }); - test('Personal publication stopped after old/ was created, before any rename: the manual restore keeps the published staff/', () => { - const { out, staging } = fixture(true, PERSONAL); + test('Publication stopped after old/ was created, before any rename: the manual restore keeps the published entries', () => { + const { out, staging } = fixture(); const before = published(out); - // A process killed right after creating old/: old/ is empty, the staged entries are all there and - // staff/ was never moved. The restore must not delete it, although site-staff is not staged. + // A process killed right after creating old/: old/ is empty and every staged entry is still there. mkdirSync(join(staging, 'old')); manualRestore(out, staging); expect(snapshot(out)).toEqual(before); @@ -190,13 +197,13 @@ describe('Interrupted publication', () => { test('Stale staging before publication: only real folders without old/ are removed, links inside are not followed', () => { const { out, other } = fixture(); - const crashed = write(join(out, '.stackledger-tmp-crashed'), { 'site-full/index.html': 'full view\n' }); - symlinkSync(other, join(crashed, 'site-staff')); + const crashed = write(join(out, '.stackledger-tmp-crashed'), { 'site/index.html': 'new home\n' }); + symlinkSync(other, join(crashed, 'site-link')); const otherBefore = snapshot(other); const stale = staleStaging(out, readdirSync(out)); expect(stale).toEqual([crashed, join(out, STAGING)]); removeStaging(stale, folderIdentity(out)); - expect(readdirSync(out).sort()).toEqual(Object.keys(PREVIOUS).map(path => path.split('/')[0]).sort()); + expect(readdirSync(out).sort()).toEqual([...new Set(Object.keys(PREVIOUS).map(path => path.split('/')[0]!))].sort()); expect(snapshot(other)).toEqual(otherBefore); }); @@ -206,7 +213,7 @@ describe('Interrupted publication', () => { ['a symbolic link', (path: string) => symlinkSync('/nonexistent-target', path)], ])('Next build after a failed undo: a staging folder whose old is %s is refused, nothing changes', (_, make) => { const { out } = fixture(); - const kept = write(join(out, '.stackledger-tmp-kept'), { 'site-full/index.html': 'new full\n' }); + const kept = write(join(out, '.stackledger-tmp-kept'), { 'site/index.html': 'new home\n' }); make(join(kept, 'old')); const before = snapshot(out); const refuse = () => staleStaging(out, readdirSync(out));
Per monthPer year
GBP131.501578.001