[repo] Workspace: Scaffold Phase 0 with schema, engine, content, ui and the PWA shell
pnpm + turbo workspace with the commands from CLAUDE.md §3. The contracts from §6 as JSON Schemas with generated types; localDay as the one place a day is computed; the forbidden-word list shared by lint:copy and the library validator, with 13 negative fixtures; a Svelte 5 PWA shell built under /Rosea/ with a meta CSP. E2E and offline suites run against the built bundle; the offline one closes the server rather than emulating. Analysis: .agents/features/phase0-workspace.md
This commit is contained in:
@@ -0,0 +1,117 @@
|
||||
# Phase 0 — the workspace
|
||||
|
||||
Status: **built on `feature/phase0-workspace`**, not yet merged.
|
||||
Gates closed and still open: [`GAP_ANALYSIS.md`](../GAP_ANALYSIS.md).
|
||||
|
||||
`docs/ROADMAP.md` does not exist yet, so this document defines Phase 0 itself. It
|
||||
covers what CLAUDE.md §2 calls "confirmed when Phase 0 scaffolds it" and what §3
|
||||
calls "proposed until Phase 0 scaffolds them", and nothing more. **No game code.**
|
||||
`docs/GAMEPLAY.md` must be read before any, and it has not been written.
|
||||
|
||||
---
|
||||
|
||||
## 1. Why and what, in the player's terms
|
||||
|
||||
The player gets nothing they can see. This is deliberate. When they open the link,
|
||||
they get a quiet page with the rose's name, and it still opens with the network off.
|
||||
|
||||
What Phase 0 buys is the ground everything else stands on. It proves four things
|
||||
before anything exists that could hurt a person:
|
||||
|
||||
- **The app opens with no network at all.** It is served from a sub-path, as
|
||||
GitHub Pages will serve it, and checked against the built bundle.
|
||||
- **Nothing leaves the device.** No third-party request, no cookie, no
|
||||
`localStorage`, enforced by a CSP in a `<meta>` tag.
|
||||
- **No word can reach a player that the rules forbid.** `lint:copy` and
|
||||
`validate:library` run, and they are proved to fire.
|
||||
- **The engine cannot read a clock or a die.** A lint rule refuses it, and a
|
||||
test proves the rule refuses it.
|
||||
|
||||
## 2. Technical architecture
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph apps
|
||||
app["apps/rosea<br/>@rosea/app<br/>Svelte 5 + Vite + PWA"]
|
||||
end
|
||||
subgraph packages
|
||||
ui["packages/ui<br/>@rosea/ui<br/>copy/ + shell components"]
|
||||
content["packages/content<br/>@rosea/content<br/>library validator, forbidden words"]
|
||||
engine["packages/engine<br/>@rosea/engine<br/>time/localDay.ts"]
|
||||
schema["packages/schema<br/>@rosea/schema<br/>JSON Schemas, generated types, constants"]
|
||||
end
|
||||
lib[("content/library/*.json<br/>content/fixtures/*.json")]
|
||||
scripts["scripts/<br/>lint-copy, validate-library,<br/>git hooks"]
|
||||
e2e["e2e/<br/>Playwright: built bundle,<br/>server killed for offline"]
|
||||
|
||||
app --> ui --> engine --> schema
|
||||
app --> content --> schema
|
||||
content --> engine
|
||||
app --> schema
|
||||
scripts --> content
|
||||
content -. reads .-> lib
|
||||
e2e -. serves .-> app
|
||||
```
|
||||
|
||||
### Decisions
|
||||
|
||||
| # | Decision | Why |
|
||||
|:--|:--|:--|
|
||||
| D1 | Create `schema`, `engine`, `content`, `ui` and `apps/rosea` now. **Defer** `storage`, `identity`, `sync`, `services/lucerna` and `tools/art-prep` to their first feature. | An empty package has a test suite that runs nothing and exits 0. That is the `pnpm test` trap (§3) built into the layout on purpose. Each package arrives with the feature that gives it a test. |
|
||||
| D2 | The build's base path is `/Rosea/` by default and `ROSEA_BASE` overrides it. The test server serves `dist/` **under that prefix**, never at `/`. | GitHub Pages serves a project at `/<repo>/` (§8, predicted). If Vite `base`, the manifest `scope`/`start_url` and the service-worker scope disagree, the installed app opens a 404. Testing at `/` would never see it. |
|
||||
| D3 | Engine purity is an **ESLint rule** scoped to `packages/engine/src`, plus a test that lints a deliberately impure snippet and asserts each ban fires. | CLAUDE.md §7 says "lint rule". Ludus said the same and shipped a source-scanning test instead. Here it really is a lint rule, and the test is what keeps it honest. The ban includes `Intl.DateTimeFormat().resolvedOptions()`: it reads the device's time zone, which must be a parameter. |
|
||||
| D4 | `content/library/` ships **empty**. The validator prints its counts and passes on zero entries, but it fails if any fixture passes. | Every sentence needs `verifiedBy` from the author (§6.1). An agent writing "verified" entries would be inventing a fact. The 365-sunset-sentence requirement is a release gate, not a Phase 0 gate. |
|
||||
| D5 | The event schema defines only the `care` kind, with `act: water \| shade \| weed \| petals`. | §6.2 contradicted itself: the example listed `wind \| light` and the comment listed `weed \| petals`. §1 describes weeds and fallen petals, so the comment wins, and CLAUDE.md is corrected in the same branch. The other kinds (`sunset`, `fox`, `harvest`…) wait for `docs/GAMEPLAY.md`, because their fields are game design. |
|
||||
| D6 | One forbidden-word list, in `packages/content/src/forbidden.ts`, used by **both** `lint:copy` and the library validator. Whole-word, case-insensitive. `treat` is banned outright. | Two lists drift. Banning `treat` means the fox's food is always *berries*, never *treats*. That is a little inconvenient and much cheaper than a medical-claim review. |
|
||||
| D7 | The CSP lives in a `<meta>` tag: `default-src 'self'`, no inline script. The service worker is registered from an emitted file, not an inline snippet. | GitHub Pages cannot set headers (§8, predicted). An inline registration script would need `'unsafe-inline'` and quietly widen the policy for everything. |
|
||||
| D8 | No deploy workflow yet. | There is no GitHub remote. A workflow for a host that does not exist is configuration nobody can test. |
|
||||
| D9 | `localDay(epochMs, timeZone)` is the only day computation. It formats with `Intl.DateTimeFormat` for an explicit IANA zone. | §7: one module computes a day. The zone is always passed in. A city the player chooses maps to a zone, and so does the device fallback, which the app reads and the engine never does. |
|
||||
|
||||
## 3. Risk analysis
|
||||
|
||||
Here "risk" means a person feeling worse, a person's location, or a person being
|
||||
reachable who did not ask to be.
|
||||
|
||||
| Risk | Where it could enter in Phase 0 | Defence |
|
||||
|:--|:--|:--|
|
||||
| A forbidden or medical word reaches a player | Shell copy, manifest description, `index.html` | `lint:copy` scans `packages/ui/src/copy/`, `apps/rosea/index.html`, the manifest fields in `vite.config.ts` and `store/`. Fixtures prove it fires. |
|
||||
| *Lonely* / *loneliness* appears in the product | Same | On the forbidden list (§5.6 rule 4). Allowed only in `.agents/` and `docs/`, which `lint:copy` does not scan. |
|
||||
| A byte leaves the device | Fonts, icons or a CDN pulled in by a dependency | CSP `default-src 'self'`. The e2e suite records every request and fails on any origin other than the test server's. |
|
||||
| Storage outside IndexedDB | A library writing `localStorage` | The e2e suite asserts `localStorage.length === 0` and `document.cookie === ''` after load. |
|
||||
| A day computed in UTC | The engine, later | D9, a purity-lint ban on `toISOString().slice`, and DST golden tests for `localDay`. |
|
||||
| The empty shell feels like a broken app | The placeholder page | One calm line from `copy/`, no spinner, no "coming soon". It says what is true and asks nothing. |
|
||||
|
||||
Looked for and not found in Phase 0: guilt, comparison, rejection, dependence. There
|
||||
is no mechanic yet that could carry any of them.
|
||||
|
||||
## 4. Gap analysis and the designed solution
|
||||
|
||||
| Gap | Solution in this branch |
|
||||
|:--|:--|
|
||||
| No workspace, no commands | `pnpm-workspace.yaml`, `turbo.json` and root scripts for every command in §3 that has something to run. |
|
||||
| `pnpm test` can exit 0 having run nothing | `test` is not cached (`cache: false`). Every package has at least one real test. Counts are quoted in the review. |
|
||||
| No proof the PWA works offline under a sub-path | `e2e/offline.spec.ts` starts a real static server at `/Rosea/`, waits for the worker to control the page, **kills the server**, reloads, and asserts the shell rendered. Ludus learned that `context.setOffline` acts before the service worker and tests the harness, not the cache. |
|
||||
| No guard on commits | `scripts/pre-commit` (5 MB) and `scripts/commit-msg` (AI attribution), installed by `pnpm install`. |
|
||||
| CRLF churn on Windows (`core.autocrlf=true` on this machine) | `.gitattributes` with `* text=auto eol=lf`. |
|
||||
|
||||
## 5. Verification matrix
|
||||
|
||||
| Case | Kind | Where |
|
||||
|:--|:--|:--|
|
||||
| Hope-sentence schema accepts a valid entry | unit | `packages/schema/test/schemas.test.ts` |
|
||||
| Care event rejects an unknown `act`, a missing `localDay`, free text in `messageId` | unit | same |
|
||||
| Trace rejects a timestamp finer than a day and extra properties | unit | same |
|
||||
| `localDay` in Prague on both 2026 DST days, Sydney, Anchorage, UTC±14 | unit (golden) | `packages/engine/test/localDay.test.ts` |
|
||||
| Monday 23:30 in Prague is Monday, not Tuesday | unit | same |
|
||||
| `localDay` is the same for every ms within one local day (property) | property | same, fast-check |
|
||||
| Each purity ban fires on an impure snippet; clean code passes | unit | `packages/engine/test/purity-lint.test.ts` |
|
||||
| Every fixture in `content/fixtures/` fails with its named message | unit | `packages/content/test/validator.test.ts` |
|
||||
| Forbidden words: whole-word, case-insensitive; no false hit on *treaty* or *cured meat*… | unit | `packages/content/test/forbidden.test.ts` |
|
||||
| Shell copy passes `lint:copy` | unit + script | `packages/ui/test/copy.test.ts`, `pnpm lint:copy` |
|
||||
| Built app renders its name at `/Rosea/` | e2e | `e2e/shell.spec.ts` |
|
||||
| No request to any other origin; no cookie; no `localStorage` | e2e | same |
|
||||
| Manifest `scope`/`start_url` and service-worker scope equal the base | e2e | same |
|
||||
| CSP meta present; no inline script in the built `index.html` | e2e | same |
|
||||
| No axe violations on the shell | e2e | same |
|
||||
| Shell loads with the server gone | offline | `e2e/offline.spec.ts` |
|
||||
| **Manual**: install from Chrome on a phone; open in airplane mode | manual | not done — needs a hosted build (D8) |
|
||||
@@ -0,0 +1,8 @@
|
||||
# This machine has core.autocrlf=true. Without this, every text file is
|
||||
# rewritten with CRLF on checkout and diffs fill with line-ending noise.
|
||||
* text=auto eol=lf
|
||||
|
||||
*.webp binary
|
||||
*.avif binary
|
||||
*.png binary
|
||||
*.ico binary
|
||||
@@ -28,3 +28,6 @@ art/exports/
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
*.log
|
||||
|
||||
# Generated from JSON Schema by packages/schema build
|
||||
packages/schema/src/generated/
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# As in Ludus. `engine-strict` is deliberately OFF: it fails the install on any
|
||||
# transitive package's declared Node range, and eslint-visitor-keys@5 declares
|
||||
# ^22.13 while running fine on 22.11 (this machine, and Ludus's).
|
||||
auto-install-peers=true
|
||||
strict-peer-dependencies=false
|
||||
@@ -0,0 +1,16 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="referrer" content="no-referrer" />
|
||||
<!-- One of the three places the product name lives (CLAUDE.md preamble). -->
|
||||
<title>Rosea Domi</title>
|
||||
<link rel="icon" href="./icon.svg" type="image/svg+xml" />
|
||||
<link rel="apple-touch-icon" href="./icon.svg" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="./src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "@rosea/app",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "The PWA. Renders what the engine returns; contains no growth, taming or sky logic.",
|
||||
"scripts": {
|
||||
"dev": "vite --host 127.0.0.1 --port 5173 --strictPort",
|
||||
"build": "vite build",
|
||||
"typecheck": "svelte-check --threshold error --output human"
|
||||
},
|
||||
"dependencies": {
|
||||
"@rosea/schema": "workspace:*",
|
||||
"@rosea/ui": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sveltejs/vite-plugin-svelte": "5.1.1",
|
||||
"svelte": "5.56.9",
|
||||
"svelte-check": "4.7.6",
|
||||
"typescript": "5.9.3",
|
||||
"vite": "6.4.3",
|
||||
"vite-plugin-pwa": "1.3.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||
<!-- Placeholder icon (CLAUDE.md §2 art/placeholders): form only, not art. Replaced through docs/ART.md. -->
|
||||
<rect width="512" height="512" rx="96" fill="#fbf6f1"/>
|
||||
<circle cx="256" cy="232" r="120" fill="#b4485e"/>
|
||||
<circle cx="256" cy="232" r="64" fill="#d97a8c"/>
|
||||
<rect x="246" y="340" width="20" height="112" rx="10" fill="#5f7a52"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 418 B |
@@ -0,0 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { Shell } from '@rosea/ui';
|
||||
</script>
|
||||
|
||||
<Shell />
|
||||
@@ -0,0 +1,8 @@
|
||||
import '@rosea/ui/tokens.css';
|
||||
import { mount } from 'svelte';
|
||||
import App from './App.svelte';
|
||||
|
||||
const target = document.getElementById('app');
|
||||
if (target === null) throw new Error('index.html has no #app element');
|
||||
|
||||
mount(App, { target });
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
/// <reference types="svelte" />
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1 @@
|
||||
export default {};
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node", "svelte", "vite/client"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.svelte", "vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { svelte } from '@sveltejs/vite-plugin-svelte';
|
||||
import { defineConfig, type Plugin } from 'vite';
|
||||
import { VitePWA } from 'vite-plugin-pwa';
|
||||
// A relative path, not '@rosea/schema', on purpose. Vite bundles a config's
|
||||
// relative imports but externalises anything under node_modules, and Node cannot
|
||||
// load a workspace package's .ts source, so `vite build` and `svelte-check` both
|
||||
// failed to load this file. The constants module is pure and dependency-free.
|
||||
import { PRODUCT_NAME, PRODUCT_SHORT_NAME } from '../../packages/schema/src/constants.js';
|
||||
|
||||
/**
|
||||
* GitHub Pages serves a project site at `/<repo>/`, not `/` (CLAUDE.md §8). Vite
|
||||
* `base`, the manifest's `scope`/`start_url` and the service worker's scope all
|
||||
* derive from this one value, so they cannot disagree. The e2e and offline
|
||||
* suites serve the build under the same prefix.
|
||||
*/
|
||||
const BASE = process.env['ROSEA_BASE'] ?? '/Rosea/';
|
||||
if (!BASE.startsWith('/') || !BASE.endsWith('/')) {
|
||||
throw new Error(`ROSEA_BASE must start and end with '/', got '${BASE}'`);
|
||||
}
|
||||
|
||||
/**
|
||||
* The content-security policy. GitHub Pages cannot send headers, so it lives in
|
||||
* a <meta> tag (CLAUDE.md §8). It is injected into the BUILT page only, because
|
||||
* the dev server injects inline <style> for hot reload and `style-src 'self'`
|
||||
* would blank it. E2E runs against the build, where the policy is real.
|
||||
*
|
||||
* `'self'` everywhere and nothing else: no CDN, no font host, no analytics
|
||||
* (CLAUDE.md §4). `frame-ancestors` is ignored in a meta tag and is omitted
|
||||
* rather than pretended.
|
||||
*/
|
||||
const CSP = [
|
||||
"default-src 'self'",
|
||||
"script-src 'self'",
|
||||
"style-src 'self'",
|
||||
"img-src 'self' data:",
|
||||
"font-src 'self'",
|
||||
"connect-src 'self'",
|
||||
"manifest-src 'self'",
|
||||
"worker-src 'self'",
|
||||
"object-src 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'none'"
|
||||
].join('; ');
|
||||
|
||||
function contentSecurityPolicy(): Plugin {
|
||||
return {
|
||||
name: 'rosea-csp',
|
||||
apply: 'build',
|
||||
transformIndexHtml: {
|
||||
order: 'post',
|
||||
handler: () => [
|
||||
{ tag: 'meta', attrs: { 'http-equiv': 'Content-Security-Policy', content: CSP }, injectTo: 'head-prepend' }
|
||||
]
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Nothing binds to anything but 127.0.0.1 (CLAUDE.md §5.7).
|
||||
export default defineConfig({
|
||||
base: BASE,
|
||||
plugins: [
|
||||
svelte(),
|
||||
contentSecurityPolicy(),
|
||||
VitePWA({
|
||||
strategies: 'generateSW',
|
||||
// Never swap a running app silently. A new worker waits until the player
|
||||
// is offered a calm refresh control (CLAUDE.md §8, GAP_ANALYSIS G0.10).
|
||||
registerType: 'prompt',
|
||||
// An emitted registerSW.js file, not an inline snippet: the CSP has no
|
||||
// 'unsafe-inline' for scripts.
|
||||
injectRegister: 'script',
|
||||
manifest: {
|
||||
// The web manifest: one of the three places the name lives, built from
|
||||
// the constants in @rosea/schema so the strings exist only there.
|
||||
name: PRODUCT_NAME,
|
||||
short_name: PRODUCT_SHORT_NAME,
|
||||
description: 'A rose to tend, a fox to befriend, and the time we give to people.',
|
||||
id: BASE,
|
||||
start_url: BASE,
|
||||
scope: BASE,
|
||||
display: 'standalone',
|
||||
orientation: 'portrait',
|
||||
background_color: '#fbf6f1',
|
||||
theme_color: '#b4485e',
|
||||
icons: [{ src: 'icon.svg', sizes: 'any', type: 'image/svg+xml', purpose: 'any' }]
|
||||
},
|
||||
workbox: {
|
||||
// The cache name never contains the build hash; Workbox invalidates
|
||||
// per entry from the precache manifest's revisions.
|
||||
cacheId: 'rosea',
|
||||
globPatterns: ['**/*.{js,css,html,svg,webmanifest}'],
|
||||
navigateFallback: 'index.html',
|
||||
// No runtime caching: the app makes no request it was not asked to make.
|
||||
runtimeCaching: [],
|
||||
cleanupOutdatedCaches: true,
|
||||
// The first worker controls the page that registered it, so a player who
|
||||
// opens the link once and loses signal still has the app.
|
||||
clientsClaim: true,
|
||||
skipWaiting: false
|
||||
},
|
||||
devOptions: { enabled: false }
|
||||
})
|
||||
],
|
||||
server: { host: '127.0.0.1', strictPort: true },
|
||||
preview: { host: '127.0.0.1', strictPort: true },
|
||||
build: { target: 'es2022', sourcemap: true }
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"expect": "duplicate-id",
|
||||
"why": "Two entries with one id: a message between players would be ambiguous.",
|
||||
"entries": [
|
||||
{
|
||||
"id": "fixture-entry",
|
||||
"text": {
|
||||
"en": "Fixture text, not a real sentence."
|
||||
},
|
||||
"source": {
|
||||
"work": "Fixture",
|
||||
"author": null,
|
||||
"tradition": "biblical",
|
||||
"translation": "KJV",
|
||||
"publicDomain": true,
|
||||
"verifiedBy": "Fixture",
|
||||
"verifiedAt": "2026-11-01"
|
||||
},
|
||||
"use": [
|
||||
"sunset"
|
||||
],
|
||||
"tone": "gentle",
|
||||
"promisesOutcome": false
|
||||
},
|
||||
{
|
||||
"id": "fixture-entry",
|
||||
"text": {
|
||||
"en": "Another fixture text."
|
||||
},
|
||||
"source": {
|
||||
"work": "Fixture",
|
||||
"author": null,
|
||||
"tradition": "biblical",
|
||||
"translation": "KJV",
|
||||
"publicDomain": true,
|
||||
"verifiedBy": "Fixture",
|
||||
"verifiedAt": "2026-11-01"
|
||||
},
|
||||
"use": [
|
||||
"sunset"
|
||||
],
|
||||
"tone": "gentle",
|
||||
"promisesOutcome": false
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"expect": "forbidden-word",
|
||||
"why": "A medical-claim word, inside a hyphenated compound.",
|
||||
"entry": {
|
||||
"id": "fixture-entry",
|
||||
"text": {
|
||||
"en": "Fixture text about self-healing."
|
||||
},
|
||||
"source": {
|
||||
"work": "Fixture",
|
||||
"author": null,
|
||||
"tradition": "biblical",
|
||||
"translation": "KJV",
|
||||
"publicDomain": true,
|
||||
"verifiedBy": "Fixture",
|
||||
"verifiedAt": "2026-11-01"
|
||||
},
|
||||
"use": [
|
||||
"sunset"
|
||||
],
|
||||
"tone": "gentle",
|
||||
"promisesOutcome": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"expect": "forbidden-word",
|
||||
"why": "A name from The Little Prince, in the Czech text.",
|
||||
"entry": {
|
||||
"id": "fixture-entry",
|
||||
"text": {
|
||||
"en": "Fixture text, not a real sentence.",
|
||||
"cs": "Fixture text, Malý princ."
|
||||
},
|
||||
"source": {
|
||||
"work": "Fixture",
|
||||
"author": null,
|
||||
"tradition": "biblical",
|
||||
"translation": "KJV",
|
||||
"publicDomain": true,
|
||||
"verifiedBy": "Fixture",
|
||||
"verifiedAt": "2026-11-01"
|
||||
},
|
||||
"use": [
|
||||
"sunset"
|
||||
],
|
||||
"tone": "gentle",
|
||||
"promisesOutcome": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"expect": "forbidden-word",
|
||||
"why": "A name from Tolkien.",
|
||||
"entry": {
|
||||
"id": "fixture-entry",
|
||||
"text": {
|
||||
"en": "Fixture text naming Gandalf."
|
||||
},
|
||||
"source": {
|
||||
"work": "Fixture",
|
||||
"author": null,
|
||||
"tradition": "biblical",
|
||||
"translation": "KJV",
|
||||
"publicDomain": true,
|
||||
"verifiedBy": "Fixture",
|
||||
"verifiedAt": "2026-11-01"
|
||||
},
|
||||
"use": [
|
||||
"sunset"
|
||||
],
|
||||
"tone": "gentle",
|
||||
"promisesOutcome": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"expect": "forbidden-word",
|
||||
"why": "Names the state the game never names, capitalised to prove case is ignored.",
|
||||
"entry": {
|
||||
"id": "fixture-entry",
|
||||
"text": {
|
||||
"en": "Fixture text for the Lonely."
|
||||
},
|
||||
"source": {
|
||||
"work": "Fixture",
|
||||
"author": null,
|
||||
"tradition": "biblical",
|
||||
"translation": "KJV",
|
||||
"publicDomain": true,
|
||||
"verifiedBy": "Fixture",
|
||||
"verifiedAt": "2026-11-01"
|
||||
},
|
||||
"use": [
|
||||
"sunset"
|
||||
],
|
||||
"tone": "gentle",
|
||||
"promisesOutcome": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"expect": "schema",
|
||||
"why": "An id is what travels between players; it can never be a sentence.",
|
||||
"entry": {
|
||||
"id": "meet me at the station",
|
||||
"text": {
|
||||
"en": "Fixture text, not a real sentence."
|
||||
},
|
||||
"source": {
|
||||
"work": "Fixture",
|
||||
"author": null,
|
||||
"tradition": "biblical",
|
||||
"translation": "KJV",
|
||||
"publicDomain": true,
|
||||
"verifiedBy": "Fixture",
|
||||
"verifiedAt": "2026-11-01"
|
||||
},
|
||||
"use": [
|
||||
"sunset"
|
||||
],
|
||||
"tone": "gentle",
|
||||
"promisesOutcome": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"expect": "no-source",
|
||||
"why": "Every sentence names its source.",
|
||||
"entry": {
|
||||
"id": "fixture-entry",
|
||||
"text": {
|
||||
"en": "Fixture text, not a real sentence."
|
||||
},
|
||||
"use": [
|
||||
"sunset"
|
||||
],
|
||||
"tone": "gentle",
|
||||
"promisesOutcome": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"expect": "no-tradition",
|
||||
"why": "Missing tradition tag.",
|
||||
"entry": {
|
||||
"id": "fixture-entry",
|
||||
"text": {
|
||||
"en": "Fixture text, not a real sentence."
|
||||
},
|
||||
"source": {
|
||||
"work": "Fixture",
|
||||
"author": null,
|
||||
"translation": "KJV",
|
||||
"publicDomain": true,
|
||||
"verifiedBy": "Fixture",
|
||||
"verifiedAt": "2026-11-01"
|
||||
},
|
||||
"use": [
|
||||
"sunset"
|
||||
],
|
||||
"tone": "gentle",
|
||||
"promisesOutcome": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"expect": "not-public-domain",
|
||||
"why": "A source not verified public domain, and not written by the author for Rosea.",
|
||||
"entry": {
|
||||
"id": "fixture-entry",
|
||||
"text": {
|
||||
"en": "Fixture text, not a real sentence."
|
||||
},
|
||||
"source": {
|
||||
"work": "Fixture",
|
||||
"author": null,
|
||||
"tradition": "stoic",
|
||||
"translation": null,
|
||||
"publicDomain": false,
|
||||
"verifiedBy": "Fixture",
|
||||
"verifiedAt": "2026-11-01"
|
||||
},
|
||||
"use": [
|
||||
"sunset"
|
||||
],
|
||||
"tone": "gentle",
|
||||
"promisesOutcome": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"expect": "promises-outcome",
|
||||
"why": "Honestly marked as promising an outcome.",
|
||||
"entry": {
|
||||
"id": "fixture-entry",
|
||||
"text": {
|
||||
"en": "Fixture text, not a real sentence."
|
||||
},
|
||||
"source": {
|
||||
"work": "Fixture",
|
||||
"author": null,
|
||||
"tradition": "biblical",
|
||||
"translation": "KJV",
|
||||
"publicDomain": true,
|
||||
"verifiedBy": "Fixture",
|
||||
"verifiedAt": "2026-11-01"
|
||||
},
|
||||
"use": [
|
||||
"sunset"
|
||||
],
|
||||
"tone": "gentle",
|
||||
"promisesOutcome": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"expect": "promises-outcome",
|
||||
"why": "Promises an outcome while marked promisesOutcome: false. Flagged for human review.",
|
||||
"entry": {
|
||||
"id": "fixture-entry",
|
||||
"text": {
|
||||
"en": "Fixture: everything will be fine."
|
||||
},
|
||||
"source": {
|
||||
"work": "Fixture",
|
||||
"author": null,
|
||||
"tradition": "biblical",
|
||||
"translation": "KJV",
|
||||
"publicDomain": true,
|
||||
"verifiedBy": "Fixture",
|
||||
"verifiedAt": "2026-11-01"
|
||||
},
|
||||
"use": [
|
||||
"sunset"
|
||||
],
|
||||
"tone": "gentle",
|
||||
"promisesOutcome": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"expect": "too-long",
|
||||
"why": "Over the length cap.",
|
||||
"entry": {
|
||||
"id": "fixture-entry",
|
||||
"text": {
|
||||
"en": "Fixture text that runs on far past the cap. Fixture text that runs on far past the cap. Fixture text that runs on far past the cap. Fixture text that runs on far past the cap. Fixture text that runs on far past the cap. Fixture text that runs on far past the cap."
|
||||
},
|
||||
"source": {
|
||||
"work": "Fixture",
|
||||
"author": null,
|
||||
"tradition": "biblical",
|
||||
"translation": "KJV",
|
||||
"publicDomain": true,
|
||||
"verifiedBy": "Fixture",
|
||||
"verifiedAt": "2026-11-01"
|
||||
},
|
||||
"use": [
|
||||
"sunset"
|
||||
],
|
||||
"tone": "gentle",
|
||||
"promisesOutcome": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"expect": "translation-under-copyright",
|
||||
"why": "A modern Bible translation that is still under copyright.",
|
||||
"entry": {
|
||||
"id": "fixture-entry",
|
||||
"text": {
|
||||
"en": "Fixture text, not a real sentence."
|
||||
},
|
||||
"source": {
|
||||
"work": "Fixture",
|
||||
"author": null,
|
||||
"tradition": "biblical",
|
||||
"translation": "NIV",
|
||||
"publicDomain": true,
|
||||
"verifiedBy": "Fixture",
|
||||
"verifiedAt": "2026-11-01"
|
||||
},
|
||||
"use": [
|
||||
"sunset"
|
||||
],
|
||||
"tone": "gentle",
|
||||
"promisesOutcome": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
# The hope library
|
||||
|
||||
One JSON file per source tradition (`biblical.json`, `stoic.json`, `rosea.json`, …).
|
||||
Each file is an array of entries in the shape of
|
||||
[`hope-sentence.schema.json`](../../packages/schema/schemas/hope-sentence.schema.json)
|
||||
(CLAUDE.md §6.1).
|
||||
|
||||
**It is empty on purpose.** Every entry carries `verifiedBy` and `verifiedAt`, which
|
||||
record that a person checked the source and its public-domain status. An agent
|
||||
cannot make that check, so agents do not add entries. They may prepare a candidate
|
||||
list elsewhere for the author to verify.
|
||||
|
||||
Run `pnpm validate:library` after any change. The validator also runs every file
|
||||
in [`../fixtures/`](../fixtures/), and **fails if any fixture passes**.
|
||||
|
||||
Before the first release: at least 365 entries with `"use": ["sunset", …]`, so that
|
||||
no sunset sentence repeats within a year.
|
||||
@@ -0,0 +1,66 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
import { PRODUCT_NAME } from '@rosea/schema';
|
||||
import { en } from '@rosea/ui/copy';
|
||||
import { startStaticServer } from './static-server.js';
|
||||
|
||||
/**
|
||||
* The offline suite. CLAUDE.md §3 describes its full shape: tend the rose, walk
|
||||
* a planet, watch a sunset, close the tab, reopen, assert everything survived.
|
||||
* Phase 0 has no rose, so this proves the part everything else will stand on:
|
||||
* the app opens with no server anywhere, under its real base path.
|
||||
*
|
||||
* The server is genuinely CLOSED, not emulated: `context.setOffline` acts before
|
||||
* the service worker and would test the harness instead (imported from Ludus).
|
||||
*/
|
||||
test('the shell opens from the service worker with the server gone', async ({ browser }) => {
|
||||
const server = await startStaticServer();
|
||||
const context = await browser.newContext();
|
||||
let serverOpen = true;
|
||||
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
await page.goto(server.url);
|
||||
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
|
||||
|
||||
// `clientsClaim` makes the FIRST worker control the page that registered it.
|
||||
// Without it, a player who opens the link once and loses signal has nothing.
|
||||
await page.waitForFunction(() => navigator.serviceWorker.controller !== null, null, { timeout: 20_000 });
|
||||
await page.waitForFunction(
|
||||
async () => {
|
||||
for (const name of await caches.keys()) {
|
||||
const cache = await caches.open(name);
|
||||
if ((await cache.keys()).some((r) => r.url.includes('index.html'))) return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
null,
|
||||
{ timeout: 20_000 }
|
||||
);
|
||||
|
||||
await server.close();
|
||||
serverOpen = false;
|
||||
|
||||
// Proof the network is really gone, from outside the browser.
|
||||
await expect(fetch(server.url)).rejects.toThrow();
|
||||
|
||||
// 1. Reload the open tab.
|
||||
await page.reload();
|
||||
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
|
||||
await expect(page.getByText(en.shell.preparing)).toBeVisible();
|
||||
|
||||
// 2. Close the tab and open a fresh one: a cold start, the shape of a player
|
||||
// coming back days later with no signal.
|
||||
await page.close();
|
||||
const again = await context.newPage();
|
||||
await again.goto(server.url);
|
||||
await expect(again.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
|
||||
|
||||
// 3. A deep link inside the scope falls back to the shell, not an error page.
|
||||
await again.goto(`${server.url}somewhere/deeper`);
|
||||
await expect(again.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
|
||||
} finally {
|
||||
// A test run leaves the machine as it found it (CLAUDE.md §5.7).
|
||||
await context.close();
|
||||
if (serverOpen) await server.close();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* The main e2e suite. Runs against the BUILT bundle (`pnpm test:e2e` builds it
|
||||
* first), served by a server each spec starts on a free port, so there is no
|
||||
* port table to keep and no dev server to mistake for the product (CLAUDE.md §3).
|
||||
*/
|
||||
export default defineConfig({
|
||||
testDir: '.',
|
||||
testMatch: /shell\.spec\.ts/,
|
||||
fullyParallel: false,
|
||||
workers: 1,
|
||||
retries: 0,
|
||||
reporter: [['list']],
|
||||
use: {
|
||||
...devices['Desktop Chrome'],
|
||||
trace: 'retain-on-failure'
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* The offline suite — the product's central claim (CLAUDE.md §3). Separate
|
||||
* from the main suite because it asks a different question: not "does it
|
||||
* render" but "does it render with no server in the world".
|
||||
*/
|
||||
export default defineConfig({
|
||||
testDir: '.',
|
||||
testMatch: /offline\.spec\.ts/,
|
||||
fullyParallel: false,
|
||||
workers: 1,
|
||||
retries: 0,
|
||||
reporter: [['list']],
|
||||
use: {
|
||||
...devices['Desktop Chrome'],
|
||||
trace: 'retain-on-failure'
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import AxeBuilder from '@axe-core/playwright';
|
||||
import { expect, test, type Page } from '@playwright/test';
|
||||
import { PRODUCT_NAME } from '@rosea/schema';
|
||||
import { en } from '@rosea/ui/copy';
|
||||
import { BASE, startStaticServer, type StaticServer } from './static-server.js';
|
||||
|
||||
let server: StaticServer;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
server = await startStaticServer();
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
await server.close();
|
||||
});
|
||||
|
||||
/** Opens the app and records every request and every CSP violation on the way. */
|
||||
async function open(page: Page): Promise<{ requests: string[]; cspViolations: string[] }> {
|
||||
const requests: string[] = [];
|
||||
const cspViolations: string[] = [];
|
||||
page.on('request', (r) => requests.push(r.url()));
|
||||
page.on('console', (m) => {
|
||||
if (m.type() === 'error' && /Content Security Policy/i.test(m.text())) cspViolations.push(m.text());
|
||||
});
|
||||
await page.goto(server.url);
|
||||
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
|
||||
// Let the worker register and precache, so its requests are counted too.
|
||||
await page.waitForFunction(() => navigator.serviceWorker.ready.then(() => true), null, { timeout: 20_000 });
|
||||
return { requests, cspViolations };
|
||||
}
|
||||
|
||||
test('the built app renders its name and its one line, under the base path', async ({ page }) => {
|
||||
await open(page);
|
||||
await expect(page.getByText(en.shell.preparing)).toBeVisible();
|
||||
await expect(page).toHaveTitle(PRODUCT_NAME);
|
||||
});
|
||||
|
||||
test('nothing is requested from any other origin', async ({ page }) => {
|
||||
const { requests } = await open(page);
|
||||
expect(requests.length, 'the page must have made requests for this to mean anything').toBeGreaterThan(0);
|
||||
expect(requests.filter((url) => !url.startsWith(server.origin + '/'))).toEqual([]);
|
||||
});
|
||||
|
||||
test('nothing is written to cookies or Web Storage', async ({ page }) => {
|
||||
await open(page);
|
||||
const written = await page.evaluate(() => ({
|
||||
cookie: document.cookie,
|
||||
localStorage: localStorage.length,
|
||||
sessionStorage: sessionStorage.length
|
||||
}));
|
||||
expect(written).toEqual({ cookie: '', localStorage: 0, sessionStorage: 0 });
|
||||
expect(await page.context().cookies()).toEqual([]);
|
||||
});
|
||||
|
||||
test('the built page carries the CSP and no inline script, and nothing violates it', async ({ page }) => {
|
||||
const { cspViolations } = await open(page);
|
||||
const html = await (await fetch(server.url)).text();
|
||||
|
||||
// Read from the DOM, not the raw HTML: Vite escapes the quotes as '.
|
||||
const csp = await page.locator('meta[http-equiv="Content-Security-Policy"]').getAttribute('content');
|
||||
expect(csp, 'CSP meta tag in the built index.html').toBeTruthy();
|
||||
expect(csp).toContain("default-src 'self'");
|
||||
expect(csp).not.toContain('unsafe-inline');
|
||||
expect(csp).not.toContain('unsafe-eval');
|
||||
|
||||
const inline = [...html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/g)].filter(
|
||||
([, attrs, body]) => !/\bsrc=/.test(attrs ?? '') && (body ?? '').trim() !== ''
|
||||
);
|
||||
expect(inline.map(([tag]) => tag)).toEqual([]);
|
||||
expect(cspViolations).toEqual([]);
|
||||
});
|
||||
|
||||
test('manifest scope, start_url and the service worker scope all equal the base path', async ({ page }) => {
|
||||
await open(page);
|
||||
|
||||
const manifestHref = await page.locator('link[rel="manifest"]').getAttribute('href');
|
||||
expect(manifestHref, 'manifest link').toBeTruthy();
|
||||
const manifest = (await (await fetch(new URL(manifestHref!, server.url))).json()) as Record<string, unknown>;
|
||||
|
||||
expect(manifest['scope']).toBe(BASE);
|
||||
expect(manifest['start_url']).toBe(BASE);
|
||||
expect(manifest['name']).toBe(PRODUCT_NAME);
|
||||
|
||||
const swScope = await page.evaluate(async () => (await navigator.serviceWorker.ready).scope);
|
||||
expect(swScope).toBe(server.url);
|
||||
|
||||
// The icon the manifest names must exist where the manifest says it is.
|
||||
const icons = manifest['icons'] as { src: string }[];
|
||||
for (const icon of icons) {
|
||||
const res = await fetch(new URL(icon.src, new URL(manifestHref!, server.url)));
|
||||
expect(res.status, icon.src).toBe(200);
|
||||
}
|
||||
});
|
||||
|
||||
test('the shell has no accessibility violations', async ({ page }) => {
|
||||
await open(page);
|
||||
const results = await new AxeBuilder({ page }).analyze();
|
||||
expect(results.violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import { createReadStream, statSync } from 'node:fs';
|
||||
import { createServer, type Server } from 'node:http';
|
||||
import { extname, join, normalize, sep } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
/**
|
||||
* A throwaway static server for the BUILT app, under the test's control.
|
||||
*
|
||||
* It serves `apps/rosea/dist` under the same base path GitHub Pages will use
|
||||
* (`/Rosea/` unless ROSEA_BASE says otherwise), and 404s everything outside it.
|
||||
* Serving at `/` would hide every base-path bug (CLAUDE.md §8).
|
||||
*
|
||||
* It exists for the offline suite too. Playwright's `context.setOffline` and
|
||||
* `route().abort()` both act before the service worker is consulted, so they
|
||||
* test the harness and not the cache (imported from Ludus). The only honest
|
||||
* "no network" is no server: start one, let the worker precache, close it.
|
||||
*
|
||||
* Binds 127.0.0.1 on port 0, so the OS picks a free port (CLAUDE.md §5.7).
|
||||
*/
|
||||
|
||||
export const BASE = process.env['ROSEA_BASE'] ?? '/Rosea/';
|
||||
const DIST = fileURLToPath(new URL('../apps/rosea/dist', import.meta.url));
|
||||
|
||||
const MIME: Record<string, string> = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
'.webmanifest': 'application/manifest+json; charset=utf-8',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.map': 'application/json; charset=utf-8'
|
||||
};
|
||||
|
||||
export interface StaticServer {
|
||||
/** The app's URL, base path included, e.g. http://127.0.0.1:53211/Rosea/ */
|
||||
readonly url: string;
|
||||
readonly origin: string;
|
||||
readonly close: () => Promise<void>;
|
||||
}
|
||||
|
||||
export async function startStaticServer(): Promise<StaticServer> {
|
||||
try {
|
||||
statSync(join(DIST, 'index.html'));
|
||||
} catch (error) {
|
||||
throw new Error(`No built app at ${DIST}. Run \`pnpm build\` first. (${String(error)})`);
|
||||
}
|
||||
|
||||
const server: Server = createServer((req, res) => {
|
||||
const path = decodeURIComponent((req.url ?? '/').split('?')[0] ?? '/');
|
||||
|
||||
if (!path.startsWith(BASE)) {
|
||||
res.writeHead(404, { 'content-type': 'text/plain' });
|
||||
res.end(`outside ${BASE}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const rel = normalize(path.slice(BASE.length) || 'index.html');
|
||||
const file = join(DIST, rel);
|
||||
// Confine to DIST: a test server is still a server.
|
||||
if (!file.startsWith(DIST + sep) && file !== DIST) {
|
||||
res.writeHead(403).end();
|
||||
return;
|
||||
}
|
||||
|
||||
let target = file;
|
||||
try {
|
||||
if (statSync(target).isDirectory()) target = join(target, 'index.html');
|
||||
statSync(target);
|
||||
} catch {
|
||||
// Not on disk: an honest 404, which is what Pages would send.
|
||||
res.writeHead(404, { 'content-type': 'text/plain' });
|
||||
res.end('not found');
|
||||
return;
|
||||
}
|
||||
|
||||
res.writeHead(200, {
|
||||
'content-type': MIME[extname(target)] ?? 'application/octet-stream',
|
||||
// No HTTP cache, so whatever loads after the server is gone came from the
|
||||
// service worker and not from the browser's own cache.
|
||||
'cache-control': 'no-store'
|
||||
});
|
||||
createReadStream(target).pipe(res);
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
const address = server.address();
|
||||
if (address === null || typeof address === 'string') throw new Error('static server did not bind a port');
|
||||
|
||||
const origin = `http://127.0.0.1:${address.port}`;
|
||||
return {
|
||||
origin,
|
||||
url: `${origin}${BASE}`,
|
||||
close: () =>
|
||||
new Promise<void>((resolve) => {
|
||||
server.closeAllConnections();
|
||||
server.close(() => resolve());
|
||||
})
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* The linter earns its place on the rules a compiler will not give: the ones
|
||||
* about intent. Types belong to `tsc --strict` and `svelte-check`; formatting
|
||||
* belongs to nobody.
|
||||
*
|
||||
* Two house rules live here:
|
||||
* - CLAUDE.md §7 "never swallow an error": `no-empty` with no empty catch.
|
||||
* - CLAUDE.md §7 "the engine is pure — enforced by a lint rule": the block
|
||||
* scoped to packages/engine/src below. `packages/engine/test/purity-lint.test.ts`
|
||||
* proves each ban fires, because a guard only ever seen not firing is untested.
|
||||
*/
|
||||
import js from '@eslint/js';
|
||||
import ts from 'typescript-eslint';
|
||||
import svelte from 'eslint-plugin-svelte';
|
||||
import svelteParser from 'svelte-eslint-parser';
|
||||
import globals from 'globals';
|
||||
|
||||
const CLOCK = 'Time is a parameter (`now: number`). A clock in the engine makes replaying the event log non-deterministic.';
|
||||
const DICE = 'Randomness is a parameter (`rng: () => number`) so a replay gives byte-identical derived state.';
|
||||
const IO = 'The engine performs no I/O. It returns values; packages/storage, packages/sync and the app do the rest.';
|
||||
const ZONE = 'The time zone is a parameter. The app reads the device zone; the engine never does.';
|
||||
const UTC_DAY = 'That is the UTC day. Days come from engine/src/time/localDay.ts and nowhere else (CLAUDE.md §7).';
|
||||
|
||||
export default [
|
||||
{
|
||||
ignores: [
|
||||
'**/dist/**',
|
||||
'**/node_modules/**',
|
||||
'**/.turbo/**',
|
||||
'**/generated/**',
|
||||
'**/playwright-report/**',
|
||||
'**/test-results/**'
|
||||
]
|
||||
},
|
||||
|
||||
js.configs.recommended,
|
||||
...ts.configs.recommended,
|
||||
...svelte.configs['flat/recommended'],
|
||||
|
||||
{
|
||||
languageOptions: {
|
||||
ecmaVersion: 2023,
|
||||
sourceType: 'module',
|
||||
globals: { ...globals.browser, ...globals.node }
|
||||
},
|
||||
rules: {
|
||||
'no-empty': ['error', { allowEmptyCatch: false }],
|
||||
eqeqeq: ['error', 'always', { null: 'ignore' }],
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'error',
|
||||
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_', caughtErrors: 'none' }
|
||||
]
|
||||
}
|
||||
},
|
||||
|
||||
{
|
||||
files: ['**/*.svelte', '**/*.svelte.ts', '**/*.svelte.js'],
|
||||
languageOptions: {
|
||||
parser: svelteParser,
|
||||
parserOptions: { parser: ts.parser }
|
||||
}
|
||||
},
|
||||
|
||||
{
|
||||
// THE ENGINE IS PURE. Scoped to src/: tests may read clocks to build fixtures.
|
||||
files: ['packages/engine/src/**/*.ts'],
|
||||
rules: {
|
||||
'no-restricted-globals': [
|
||||
'error',
|
||||
{ name: 'fetch', message: IO },
|
||||
{ name: 'XMLHttpRequest', message: IO },
|
||||
{ name: 'WebSocket', message: IO },
|
||||
{ name: 'localStorage', message: IO },
|
||||
{ name: 'sessionStorage', message: IO },
|
||||
{ name: 'indexedDB', message: IO },
|
||||
{ name: 'document', message: IO },
|
||||
{ name: 'window', message: IO },
|
||||
{ name: 'globalThis', message: IO },
|
||||
{ name: 'navigator', message: IO },
|
||||
{ name: 'crypto', message: DICE },
|
||||
{ name: 'performance', message: CLOCK },
|
||||
{ name: 'setTimeout', message: CLOCK },
|
||||
{ name: 'setInterval', message: CLOCK },
|
||||
{ name: 'requestAnimationFrame', message: CLOCK },
|
||||
{ name: 'process', message: IO }
|
||||
],
|
||||
'no-restricted-properties': [
|
||||
'error',
|
||||
{ object: 'Date', property: 'now', message: CLOCK },
|
||||
{ object: 'Math', property: 'random', message: DICE },
|
||||
{ property: 'resolvedOptions', message: ZONE }
|
||||
],
|
||||
'no-restricted-syntax': [
|
||||
'error',
|
||||
{ selector: "NewExpression[callee.name='Date'][arguments.length=0]", message: CLOCK },
|
||||
{ selector: "CallExpression[callee.name='Date']", message: CLOCK },
|
||||
{
|
||||
selector: "CallExpression[callee.property.name='slice'][callee.object.callee.property.name='toISOString']",
|
||||
message: UTC_DAY
|
||||
},
|
||||
{ selector: 'ImportDeclaration[source.value=/^node:/]', message: IO },
|
||||
{ selector: 'ImportExpression', message: IO }
|
||||
]
|
||||
}
|
||||
},
|
||||
|
||||
{
|
||||
files: ['**/test/**', '**/*.test.ts', '**/*.spec.ts', 'scripts/**', 'e2e/**'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-unused-expressions': 'off'
|
||||
}
|
||||
}
|
||||
];
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "rosea",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"packageManager": "pnpm@9.12.3",
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"scripts": {
|
||||
"prepare": "node scripts/install-hooks.mjs",
|
||||
"build": "turbo run build",
|
||||
"typecheck": "turbo run typecheck && tsc -p tsconfig.json --noEmit",
|
||||
"lint": "eslint .",
|
||||
"test": "turbo run test",
|
||||
"test:e2e": "turbo run build --filter=@rosea/app && playwright test --config=e2e/playwright.config.ts",
|
||||
"test:offline": "turbo run build --filter=@rosea/app && playwright test --config=e2e/playwright.offline.config.ts",
|
||||
"validate:library": "tsx scripts/validate-library.ts",
|
||||
"lint:copy": "tsx scripts/lint-copy.ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@axe-core/playwright": "4.13.0",
|
||||
"@eslint/js": "9.39.5",
|
||||
"@playwright/test": "1.62.1",
|
||||
"@rosea/content": "workspace:*",
|
||||
"@rosea/schema": "workspace:*",
|
||||
"@rosea/ui": "workspace:*",
|
||||
"@types/node": "22.20.1",
|
||||
"eslint": "9.39.5",
|
||||
"eslint-plugin-svelte": "3.23.0",
|
||||
"globals": "16.5.0",
|
||||
"svelte": "5.56.9",
|
||||
"svelte-eslint-parser": "1.8.1",
|
||||
"tsx": "4.23.12",
|
||||
"turbo": "2.10.10",
|
||||
"typescript": "5.9.3",
|
||||
"typescript-eslint": "8.69.0",
|
||||
"vitest": "3.2.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "@rosea/content",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "The hope library and planets' scripts as data, the library validator, and the one list of forbidden words.",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./validate": "./src/validator.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p tsconfig.json",
|
||||
"test": "vitest run --reporter=verbose"
|
||||
},
|
||||
"dependencies": {
|
||||
"@rosea/schema": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "5.9.3",
|
||||
"vitest": "3.2.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* The core of `pnpm lint:copy` (CLAUDE.md §5.6, §7): what a player could read in
|
||||
* a file, and what is wrong with it. The script walks files; this decides.
|
||||
*/
|
||||
import { findForbidden } from './forbidden.js';
|
||||
|
||||
export interface CopyProblem {
|
||||
readonly line: number;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes comments, keeping line numbers. Comments are where the rules are
|
||||
* explained, and a rule must be nameable in the file that enforces it.
|
||||
* `//` after a `:` is a URL, not a comment.
|
||||
*/
|
||||
export function stripComments(source: string): string {
|
||||
const blank = (m: string): string => m.replace(/[^\n]/g, ' ');
|
||||
return source
|
||||
.replace(/<!--[\s\S]*?-->/g, blank)
|
||||
.replace(/\/\*[\s\S]*?\*\//g, blank)
|
||||
.replace(/(?<![:\\])\/\/[^\n]*/g, blank);
|
||||
}
|
||||
|
||||
// *Domi* is the ecosystem's word and never stands alone (CLAUDE.md preamble).
|
||||
const DOMI_ALONE = /(?<!(?:Rosea|Panda|Amicitia)[\s\u00a0])\bDomi\b/g;
|
||||
|
||||
/** Problems in one file's player-visible text. */
|
||||
export function lintCopy(source: string): CopyProblem[] {
|
||||
const text = stripComments(source);
|
||||
const lineOf = (index: number): number => text.slice(0, index).split('\n').length;
|
||||
const problems: CopyProblem[] = [];
|
||||
|
||||
for (const hit of findForbidden(text)) {
|
||||
problems.push({ line: lineOf(hit.index), message: `'${hit.term}' (${hit.category}): ${hit.why}` });
|
||||
}
|
||||
|
||||
for (const m of text.matchAll(DOMI_ALONE)) {
|
||||
problems.push({
|
||||
line: lineOf(m.index),
|
||||
message: "'Domi' on its own: the product is always Rosea Domi, and Domi never appears alone"
|
||||
});
|
||||
}
|
||||
|
||||
return problems.sort((a, b) => a.line - b.line);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* The one list of words and names that never reach a player (CLAUDE.md §5.6
|
||||
* rules 3 and 4). `lint:copy` and the library validator both read it, so the two
|
||||
* can never disagree.
|
||||
*
|
||||
* Matching is whole-word and case-insensitive, with inflections spelled out.
|
||||
* A stem match (`heal*`) would also catch *health*, and a rose can be healthy.
|
||||
*
|
||||
* `treat` is banned outright, including the fox's food: he eats *berries*.
|
||||
* `patient` is banned too. Patience is the cure Gandalf's spirit offers, so the
|
||||
* product may say *patience* and *patiently* but never *patient*.
|
||||
*/
|
||||
|
||||
export type ForbiddenCategory = 'medical' | 'unnamed-state' | 'little-prince' | 'tolkien';
|
||||
|
||||
export interface ForbiddenTerm {
|
||||
readonly term: string;
|
||||
readonly category: ForbiddenCategory;
|
||||
readonly why: string;
|
||||
}
|
||||
|
||||
const MEDICAL =
|
||||
'A medical claim pulls the product toward EU medical-device rules (CLAUDE.md §5.6 rule 3). Rosea comforts; it does not treat.';
|
||||
const UNNAMED =
|
||||
'The game never names the state for the player (CLAUDE.md §5.6 rule 4). It lets them feel seen instead.';
|
||||
const PRINCE = 'Nothing from The Little Prince by name or quote: one idea is borrowed, never its text (CLAUDE.md §5.6 rule 3).';
|
||||
const TOLKIEN = "Gandalf's spirit, never a name or a quote from Tolkien's works (CLAUDE.md §5.6 rule 3).";
|
||||
|
||||
const terms = (category: ForbiddenCategory, why: string, list: readonly string[]): ForbiddenTerm[] =>
|
||||
list.map((term) => ({ term, category, why }));
|
||||
|
||||
export const FORBIDDEN: readonly ForbiddenTerm[] = [
|
||||
...terms('medical', MEDICAL, [
|
||||
'therapy', 'therapies', 'therapist', 'therapists', 'therapeutic', 'therapeutically',
|
||||
'treat', 'treats', 'treated', 'treating', 'treatment', 'treatments',
|
||||
'heal', 'heals', 'healed', 'healing', 'healer', 'healers',
|
||||
'cure', 'cures', 'cured', 'curing', 'curative',
|
||||
'diagnose', 'diagnoses', 'diagnosed', 'diagnosing', 'diagnosis', 'diagnostic',
|
||||
'symptom', 'symptoms', 'symptomatic',
|
||||
'patient', 'patients',
|
||||
'disorder', 'disorders'
|
||||
]),
|
||||
...terms('unnamed-state', UNNAMED, ['lonely', 'lonelier', 'loneliest', 'loneliness']),
|
||||
...terms('little-prince', PRINCE, [
|
||||
'Little Prince', 'Petit Prince', 'Malý princ', 'Saint-Exupéry', 'Saint-Exupery', 'Exupéry', 'Exupery', 'B-612', 'B612'
|
||||
]),
|
||||
...terms('tolkien', TOLKIEN, [
|
||||
'Tolkien', 'Gandalf', 'Mithrandir', 'Frodo', 'Bilbo', 'Samwise', 'Aragorn', 'Galadriel', 'Sauron',
|
||||
'Mordor', 'Rivendell', 'Middle-earth', 'Middle earth', 'hobbit', 'hobbits', 'Lothlórien', 'Lothlorien'
|
||||
])
|
||||
];
|
||||
|
||||
export interface ForbiddenHit {
|
||||
readonly term: string;
|
||||
readonly category: ForbiddenCategory;
|
||||
readonly why: string;
|
||||
/** Index into the scanned text. */
|
||||
readonly index: number;
|
||||
}
|
||||
|
||||
const escape = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/[\s-]+/g, '[\\s\\u00a0-]+');
|
||||
|
||||
// Letters and digits on either side mean it is part of a longer word: *treaty*
|
||||
// does not contain *treat*. Hyphens and apostrophes are boundaries, so
|
||||
// *self-healing* is caught.
|
||||
const PATTERNS = FORBIDDEN.map((entry) => ({
|
||||
entry,
|
||||
regex: new RegExp(`(?<![\\p{L}\\p{N}])${escape(entry.term)}(?![\\p{L}\\p{N}])`, 'giu')
|
||||
}));
|
||||
|
||||
/** Every forbidden term in `text`, in order of appearance. */
|
||||
export function findForbidden(text: string): ForbiddenHit[] {
|
||||
const hits: ForbiddenHit[] = [];
|
||||
for (const { entry, regex } of PATTERNS) {
|
||||
regex.lastIndex = 0;
|
||||
for (let m = regex.exec(text); m !== null; m = regex.exec(text)) {
|
||||
hits.push({ ...entry, index: m.index });
|
||||
}
|
||||
}
|
||||
return hits.sort((a, b) => a.index - b.index);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { lintCopy, stripComments, type CopyProblem } from './copy-lint.js';
|
||||
export { FORBIDDEN, findForbidden, type ForbiddenCategory, type ForbiddenHit, type ForbiddenTerm } from './forbidden.js';
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* The hope-library validator (CLAUDE.md §5.5, §5.6 rule 2, §6.1).
|
||||
*
|
||||
* The schema says what shape an entry has. This says whether it may be shown
|
||||
* to a person: sourced, public domain or the author's own, short enough to
|
||||
* read at sunset, free of forbidden words, and not promising anything.
|
||||
*
|
||||
* Its negative fixtures in `content/fixtures/` ARE the validator: a rule here
|
||||
* without a fixture proving it fires is a review blocker.
|
||||
*/
|
||||
import type { HopeSentence } from '@rosea/schema';
|
||||
import { validateHopeSentence } from '@rosea/schema/validate';
|
||||
import { findForbidden } from './forbidden.js';
|
||||
|
||||
export type Rule =
|
||||
| 'schema'
|
||||
| 'no-source'
|
||||
| 'not-public-domain'
|
||||
| 'translation-under-copyright'
|
||||
| 'too-long'
|
||||
| 'promises-outcome'
|
||||
| 'forbidden-word'
|
||||
| 'no-tradition'
|
||||
| 'duplicate-id';
|
||||
|
||||
export interface Problem {
|
||||
readonly id: string;
|
||||
readonly rule: Rule;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
/** Characters per language. A sentence opened at sunset is read on a phone, once. */
|
||||
export const LENGTH_CAP = 240;
|
||||
|
||||
/**
|
||||
* The tradition tag for a line the author wrote for Rosea. Those are not public
|
||||
* domain, and need not be: the author owns them (CLAUDE.md §5.6 rule 2).
|
||||
*/
|
||||
export const AUTHOR_TRADITION = 'rosea';
|
||||
|
||||
/**
|
||||
* Translations known to be in the public domain. Anything else is assumed to
|
||||
* be under copyright until someone checks and adds it here, with the source of
|
||||
* that check in the commit.
|
||||
*/
|
||||
export const PUBLIC_DOMAIN_TRANSLATIONS: ReadonlySet<string> = new Set([
|
||||
'KJV', // King James Version, 1611/1769
|
||||
'Bible kralická', // 1579–1613
|
||||
'ASV', // American Standard Version, 1901
|
||||
'Douay-Rheims', // 1582–1610, Challoner revision 1752
|
||||
'YLT', // Young's Literal Translation, 1862
|
||||
'WEB' // World English Bible, dedicated to the public domain
|
||||
]);
|
||||
|
||||
/**
|
||||
* Phrasings that promise an outcome. A heuristic, so a hit means "a human must
|
||||
* read this", and the entry fails until one does. An honest `promisesOutcome:
|
||||
* true` fails the same way.
|
||||
*/
|
||||
const OUTCOME_PHRASES: readonly RegExp[] = [
|
||||
/\beverything will be\b/i,
|
||||
/\b(it|you|things) will (all )?(be|get) (better|fine|okay|ok|alright|all right|well)\b/i,
|
||||
/\byou will (find|never|always|soon)\b/i,
|
||||
/\bi promise\b/i,
|
||||
/\bguarantee/i
|
||||
];
|
||||
|
||||
const idOf = (input: unknown): string =>
|
||||
typeof input === 'object' && input !== null && typeof (input as { id?: unknown }).id === 'string'
|
||||
? (input as { id: string }).id
|
||||
: '(no id)';
|
||||
|
||||
/** Every reason `input` may not be shown to a player. Empty means it may. */
|
||||
export function validateEntry(input: unknown): Problem[] {
|
||||
const id = idOf(input);
|
||||
const problem = (rule: Rule, message: string): Problem => ({ id, rule, message });
|
||||
const problems: Problem[] = [];
|
||||
|
||||
const schema = validateHopeSentence(input);
|
||||
if (!schema.ok) {
|
||||
for (const error of schema.errors) {
|
||||
if (/^\(root\) .*'source'/.test(error)) {
|
||||
problems.push(problem('no-source', 'has no source: every sentence names where it comes from'));
|
||||
} else if (/^\/source .*'tradition'|^\/source\/tradition /.test(error)) {
|
||||
problems.push(problem('no-tradition', 'has no tradition tag: the library stays mixed, so each line says which one it is from'));
|
||||
} else {
|
||||
problems.push(problem('schema', error));
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
const entry: HopeSentence = schema.value;
|
||||
const { source } = entry;
|
||||
|
||||
if (!source.publicDomain && source.tradition !== AUTHOR_TRADITION) {
|
||||
problems.push(
|
||||
problem('not-public-domain', `source '${source.work}' is not verified public domain, and the author did not write it for Rosea`)
|
||||
);
|
||||
}
|
||||
|
||||
if (source.translation !== null && !PUBLIC_DOMAIN_TRANSLATIONS.has(source.translation)) {
|
||||
problems.push(
|
||||
problem(
|
||||
'translation-under-copyright',
|
||||
`translation '${source.translation}' is not on the public-domain list; a modern translation is usually still under copyright`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
for (const [lang, text] of Object.entries(entry.text)) {
|
||||
if (text === undefined) continue;
|
||||
|
||||
const length = [...text].length;
|
||||
if (length > LENGTH_CAP) {
|
||||
problems.push(problem('too-long', `${lang} text is ${length} characters, over the length cap of ${LENGTH_CAP}`));
|
||||
}
|
||||
|
||||
for (const hit of findForbidden(text)) {
|
||||
problems.push(problem('forbidden-word', `${lang} text contains '${hit.term}' (${hit.category}): ${hit.why}`));
|
||||
}
|
||||
|
||||
const phrase = OUTCOME_PHRASES.find((p) => p.test(text));
|
||||
if (phrase !== undefined) {
|
||||
problems.push(problem('promises-outcome', `${lang} text may promise an outcome (${phrase.source}): needs human review`));
|
||||
}
|
||||
}
|
||||
|
||||
if (entry.promisesOutcome) {
|
||||
problems.push(problem('promises-outcome', 'is marked promisesOutcome: comfort never promises what will happen'));
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
/** Validates a whole library: every entry, plus ids unique across all of them. */
|
||||
export function validateLibrary(entries: readonly unknown[]): Problem[] {
|
||||
const problems = entries.flatMap(validateEntry);
|
||||
const seen = new Set<string>();
|
||||
for (const entry of entries) {
|
||||
const id = idOf(entry);
|
||||
if (seen.has(id)) {
|
||||
problems.push({ id, rule: 'duplicate-id', message: `id '${id}' is used more than once; a message between players would be ambiguous` });
|
||||
}
|
||||
seen.add(id);
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { lintCopy, stripComments } from '../src/copy-lint.js';
|
||||
|
||||
describe('lint:copy core', () => {
|
||||
it('reports a forbidden word in a string, with its line', () => {
|
||||
const problems = lintCopy("export const a = 'ok';\nexport const b = 'A gentle therapy';\n");
|
||||
expect(problems).toHaveLength(1);
|
||||
expect(problems[0]?.line).toBe(2);
|
||||
expect(problems[0]?.message).toContain('therapy');
|
||||
});
|
||||
|
||||
it('reports a forbidden word in Svelte markup', () => {
|
||||
expect(lintCopy('<p>For the lonely.</p>')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('ignores comments, where rules are explained', () => {
|
||||
expect(lintCopy('// never say therapy\n/* nor lonely */\n<!-- nor Gandalf -->\nconst ok = 1;')).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps line numbers when it strips a multi-line comment', () => {
|
||||
const problems = lintCopy("/*\n\n*/\nconst s = 'cure';");
|
||||
expect(problems[0]?.line).toBe(4);
|
||||
});
|
||||
|
||||
it('does not mistake a URL for a comment', () => {
|
||||
expect(stripComments("'https://example.invalid/cure'")).toContain('cure');
|
||||
});
|
||||
|
||||
it("reports 'Domi' standing alone", () => {
|
||||
expect(lintCopy("const title = 'Domi';")).toHaveLength(1);
|
||||
expect(lintCopy("const title = 'Welcome to Domi';")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("accepts 'Domi' after its first word", () => {
|
||||
expect(lintCopy("'Rosea Domi', 'Panda Domi', 'Amicitia Domi'")).toEqual([]);
|
||||
});
|
||||
|
||||
it('accepts clean shell copy', () => {
|
||||
expect(lintCopy("preparing: 'The garden is being prepared.'")).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { FORBIDDEN, findForbidden } from '../src/forbidden.js';
|
||||
|
||||
const terms = (text: string): string[] => findForbidden(text).map((h) => h.term);
|
||||
|
||||
describe('forbidden words — what is caught', () => {
|
||||
it('catches every listed term on its own', () => {
|
||||
const missed = FORBIDDEN.filter(({ term }) => !terms(`before ${term} after`).includes(term)).map((t) => t.term);
|
||||
expect(missed).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['A soft THERAPY for the soul', 'therapy'],
|
||||
['self-healing petals', 'healing'],
|
||||
["the rose's lonely planet", 'lonely'],
|
||||
['Loneliness.', 'loneliness'],
|
||||
['a treat for the fox', 'treat'],
|
||||
['be patient with yourself', 'patient'],
|
||||
['Middle-earth', 'Middle-earth'],
|
||||
['Middle earth', 'Middle-earth'],
|
||||
['Malý princ', 'Malý princ'],
|
||||
['Saint-Exupéry wrote', 'Saint-Exupéry']
|
||||
])('"%s" contains %s', (text, term) => {
|
||||
expect(terms(text)).toContain(term);
|
||||
});
|
||||
|
||||
it('reports hits in reading order', () => {
|
||||
expect(terms('cure first, then therapy')).toEqual(['cure', 'therapy']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('forbidden words — what is NOT caught', () => {
|
||||
it.each([
|
||||
'a treaty between two roses',
|
||||
'a healthy rose',
|
||||
'patience, and patiently waiting',
|
||||
'the lamplighter on his planet',
|
||||
'the king, the vain man, the businessman',
|
||||
'a fox among the berries',
|
||||
'Rosea Domi'
|
||||
])('"%s" is clean', (text) => {
|
||||
expect(terms(text)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import { readFileSync, readdirSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { LENGTH_CAP, validateEntry, validateLibrary, type Rule } from '../src/validator.js';
|
||||
|
||||
const fixturesDir = fileURLToPath(new URL('../../../content/fixtures', import.meta.url));
|
||||
|
||||
interface Fixture {
|
||||
readonly expect: Rule;
|
||||
readonly why: string;
|
||||
readonly entry?: unknown;
|
||||
readonly entries?: readonly unknown[];
|
||||
}
|
||||
|
||||
const fixtures = readdirSync(fixturesDir)
|
||||
.filter((f) => f.endsWith('.json'))
|
||||
.sort()
|
||||
.map((file) => ({ file, fixture: JSON.parse(readFileSync(join(fixturesDir, file), 'utf8')) as Fixture }));
|
||||
|
||||
const valid = {
|
||||
id: 'valid-entry',
|
||||
text: { en: 'Fixture text, not a real sentence.', cs: 'Testovací text.' },
|
||||
source: {
|
||||
work: 'Fixture',
|
||||
author: null,
|
||||
tradition: 'biblical',
|
||||
translation: 'KJV',
|
||||
publicDomain: true,
|
||||
verifiedBy: 'Fixture',
|
||||
verifiedAt: '2026-11-01'
|
||||
},
|
||||
use: ['sunset', 'comfort'],
|
||||
tone: 'gentle',
|
||||
promisesOutcome: false
|
||||
};
|
||||
|
||||
describe('library validator — negative fixtures', () => {
|
||||
it('finds the fixtures', () => {
|
||||
// A glob matching nothing would pass every case below.
|
||||
expect(fixtures.length).toBeGreaterThanOrEqual(13);
|
||||
});
|
||||
|
||||
it.each(fixtures)('$file fails with its named rule', ({ fixture }) => {
|
||||
const problems = fixture.entries !== undefined ? validateLibrary(fixture.entries) : validateEntry(fixture.entry);
|
||||
expect(problems.map((p) => p.rule), fixture.why).toContain(fixture.expect);
|
||||
for (const p of problems) expect(p.message.length, 'each problem says what is wrong').toBeGreaterThan(10);
|
||||
});
|
||||
|
||||
it('every rule the validator has is proved by at least one fixture', () => {
|
||||
const proved = new Set(fixtures.map(({ fixture }) => fixture.expect));
|
||||
const RULES: readonly Rule[] = [
|
||||
'schema',
|
||||
'no-source',
|
||||
'not-public-domain',
|
||||
'translation-under-copyright',
|
||||
'too-long',
|
||||
'promises-outcome',
|
||||
'forbidden-word',
|
||||
'no-tradition',
|
||||
'duplicate-id'
|
||||
];
|
||||
expect(RULES.filter((r) => !proved.has(r))).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('library validator — what passes', () => {
|
||||
it('accepts a sourced, public-domain, short, gentle entry', () => {
|
||||
expect(validateEntry(valid)).toEqual([]);
|
||||
});
|
||||
|
||||
it('accepts a line the author wrote for Rosea, though it is not public domain', () => {
|
||||
const own = { ...valid, source: { ...valid.source, tradition: 'rosea', translation: null, publicDomain: false } };
|
||||
expect(validateEntry(own)).toEqual([]);
|
||||
});
|
||||
|
||||
it('accepts text exactly at the length cap, counting characters and not UTF-16 units', () => {
|
||||
const atCap = { ...valid, text: { en: 'ř'.repeat(LENGTH_CAP) } };
|
||||
expect(validateEntry(atCap)).toEqual([]);
|
||||
});
|
||||
|
||||
it('accepts an empty library, and says nothing about it', () => {
|
||||
expect(validateLibrary([])).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "test/**/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "@rosea/engine",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Pure. No I/O, no DOM, no Date.now(), no Math.random(). Time and randomness are parameters.",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p tsconfig.json",
|
||||
"test": "vitest run --reporter=verbose"
|
||||
},
|
||||
"dependencies": {
|
||||
"@rosea/schema": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"eslint": "9.39.5",
|
||||
"fast-check": "3.23.2",
|
||||
"typescript": "5.9.3",
|
||||
"vitest": "3.2.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { isLocalDay, localDay, type LocalDay } from './time/localDay.js';
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* The ONLY place in the repository where a day is computed (CLAUDE.md §7).
|
||||
*
|
||||
* A day is always local to a named IANA time zone, and the zone is always a
|
||||
* parameter. The engine never asks the device which zone it is in: the app
|
||||
* passes the zone of the city the player chose, or the device's own zone as the
|
||||
* fallback (CLAUDE.md §4 `profile`).
|
||||
*
|
||||
* Never `toISOString().slice(0, 10)`: that is the UTC day, and in Prague it
|
||||
* records Monday-evening care as Tuesday's.
|
||||
*/
|
||||
|
||||
/** A calendar day, `YYYY-MM-DD`, in some player's local time. */
|
||||
export type LocalDay = string;
|
||||
|
||||
const LOCAL_DAY = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
// Memoised per zone. Constructing a DateTimeFormat costs far more than using one.
|
||||
// This is a cache of a pure function's machinery, not state: the output depends
|
||||
// only on the arguments.
|
||||
const formatters = new Map<string, Intl.DateTimeFormat>();
|
||||
|
||||
function formatterFor(timeZone: string): Intl.DateTimeFormat {
|
||||
let formatter = formatters.get(timeZone);
|
||||
if (formatter === undefined) {
|
||||
// Throws RangeError for an unknown zone, which is the right failure: a
|
||||
// mistyped zone silently falling back to UTC is the bug this module exists
|
||||
// to prevent.
|
||||
formatter = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone,
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
calendar: 'iso8601',
|
||||
numberingSystem: 'latn'
|
||||
});
|
||||
formatters.set(timeZone, formatter);
|
||||
}
|
||||
return formatter;
|
||||
}
|
||||
|
||||
/** The local calendar day of `epochMs` in `timeZone`. */
|
||||
export function localDay(epochMs: number, timeZone: string): LocalDay {
|
||||
if (!Number.isFinite(epochMs)) {
|
||||
throw new RangeError(`localDay: epochMs must be a finite number, got ${String(epochMs)}`);
|
||||
}
|
||||
|
||||
const parts = formatterFor(timeZone).formatToParts(epochMs);
|
||||
const part = (type: Intl.DateTimeFormatPartTypes): string => {
|
||||
const value = parts.find((p) => p.type === type)?.value;
|
||||
if (value === undefined) throw new RangeError(`localDay: no ${type} for ${epochMs} in ${timeZone}`);
|
||||
return value;
|
||||
};
|
||||
|
||||
const day = `${part('year')}-${part('month')}-${part('day')}`;
|
||||
if (!LOCAL_DAY.test(day)) {
|
||||
// Years before 1000 or after 9999 would not be four digits. No player tends
|
||||
// a rose then; refusing is better than writing an ambiguous day to the log.
|
||||
throw new RangeError(`localDay: ${epochMs} gives an unrepresentable day '${day}'`);
|
||||
}
|
||||
return day;
|
||||
}
|
||||
|
||||
/** Whether `value` has the shape of a LocalDay. Does not check that the date exists. */
|
||||
export function isLocalDay(value: string): value is LocalDay {
|
||||
return LOCAL_DAY.test(value);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import fc from 'fast-check';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { isLocalDay, localDay } from '../src/time/localDay.js';
|
||||
|
||||
const at = (iso: string): number => Date.parse(iso);
|
||||
|
||||
describe('localDay — golden cases', () => {
|
||||
it.each([
|
||||
// Prague, 2026 spring-forward day (29 March, 02:00 CET -> 03:00 CEST).
|
||||
['2026-03-28T23:30:00Z', 'Europe/Prague', '2026-03-29'], // 00:30 CET, first half-hour of the short day
|
||||
['2026-03-29T21:59:00Z', 'Europe/Prague', '2026-03-29'], // 23:59 CEST, last minute of it
|
||||
['2026-03-29T22:00:00Z', 'Europe/Prague', '2026-03-30'],
|
||||
// Prague, 2026 fall-back day (25 October, 03:00 CEST -> 02:00 CET), 25 hours long.
|
||||
['2026-10-24T22:00:00Z', 'Europe/Prague', '2026-10-25'],
|
||||
['2026-10-25T22:59:00Z', 'Europe/Prague', '2026-10-25'], // 23:59 CET
|
||||
['2026-10-25T23:00:00Z', 'Europe/Prague', '2026-10-26'],
|
||||
// Southern hemisphere: Sydney is ahead of UTC, so its morning is UTC's yesterday.
|
||||
['2026-11-01T21:00:00Z', 'Australia/Sydney', '2026-11-02'],
|
||||
// Reykjavík has no DST and sits on UTC: the one zone where UTC days are right.
|
||||
['2026-06-21T23:59:00Z', 'Atlantic/Reykjavik', '2026-06-21'],
|
||||
// The edges of the clock face.
|
||||
['2026-01-01T10:00:00Z', 'Pacific/Kiritimati', '2026-01-02'], // UTC+14
|
||||
['2026-01-01T10:00:00Z', 'Etc/GMT+12', '2025-12-31'] // UTC-12
|
||||
])('%s in %s is %s', (iso, zone, expected) => {
|
||||
expect(localDay(at(iso), zone)).toBe(expected);
|
||||
});
|
||||
|
||||
it('Monday evening in Anchorage is Monday, though UTC already says Tuesday', () => {
|
||||
// 2026-10-26 is a Monday. 20:00 AKDT = 04:00 UTC on Tuesday.
|
||||
const mondayEvening = at('2026-10-27T04:00:00Z');
|
||||
expect(localDay(mondayEvening, 'America/Anchorage')).toBe('2026-10-26');
|
||||
expect(new Date(mondayEvening).toISOString().slice(0, 10)).toBe('2026-10-27'); // the trap, measured
|
||||
});
|
||||
|
||||
it('just after midnight on Tuesday in Prague is Tuesday, though UTC still says Monday', () => {
|
||||
const tuesdayNight = at('2026-10-26T23:30:00Z'); // 00:30 CET on Tuesday 27th
|
||||
expect(localDay(tuesdayNight, 'Europe/Prague')).toBe('2026-10-27');
|
||||
});
|
||||
});
|
||||
|
||||
describe('localDay — refusals', () => {
|
||||
it('throws on an unknown zone instead of falling back to UTC', () => {
|
||||
expect(() => localDay(0, 'Europe/Atlantis')).toThrow(RangeError);
|
||||
});
|
||||
|
||||
it('throws on a non-finite time', () => {
|
||||
expect(() => localDay(Number.NaN, 'Europe/Prague')).toThrow(RangeError);
|
||||
expect(() => localDay(Number.POSITIVE_INFINITY, 'Europe/Prague')).toThrow(RangeError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('localDay — properties', () => {
|
||||
const ZONES = [
|
||||
'Europe/Prague',
|
||||
'Atlantic/Reykjavik',
|
||||
'Europe/Oslo', // Tromsø's zone
|
||||
'America/Guayaquil', // Quito's zone
|
||||
'Australia/Sydney',
|
||||
'America/Anchorage',
|
||||
'Pacific/Kiritimati',
|
||||
'Etc/GMT+12'
|
||||
] as const;
|
||||
|
||||
// 2000-01-01 .. 2100-01-01: every year a player could plausibly be in.
|
||||
const instant = fc.integer({ min: Date.UTC(2000, 0, 1), max: Date.UTC(2100, 0, 1) });
|
||||
const zone = fc.constantFrom(...ZONES);
|
||||
const HOUR = 3_600_000;
|
||||
|
||||
it('always returns a well-formed day', () => {
|
||||
fc.assert(fc.property(instant, zone, (t, z) => isLocalDay(localDay(t, z))));
|
||||
});
|
||||
|
||||
it('never goes backwards in time, across DST changes included', () => {
|
||||
fc.assert(
|
||||
fc.property(instant, fc.integer({ min: 0, max: 72 * HOUR }), zone, (t, dt, z) => {
|
||||
return localDay(t, z) <= localDay(t + dt, z);
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('always advances within 26 hours (no local day is longer than 25)', () => {
|
||||
fc.assert(fc.property(instant, zone, (t, z) => localDay(t, z) < localDay(t + 26 * HOUR, z)));
|
||||
});
|
||||
|
||||
it('is deterministic: the same arguments give the same day', () => {
|
||||
fc.assert(fc.property(instant, zone, (t, z) => localDay(t, z) === localDay(t, z)));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Proves the engine-purity lint rule (eslint.config.mjs, CLAUDE.md §7) fires.
|
||||
*
|
||||
* A guard that has only ever been seen NOT firing has not been tested. Each
|
||||
* banned construct is linted as if it lived in packages/engine/src, and must be
|
||||
* reported. The same snippet placed outside the engine must not be, which proves
|
||||
* the rule is scoped and not a global ban someone will turn off in anger.
|
||||
*/
|
||||
import { ESLint } from 'eslint';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const repoRoot = fileURLToPath(new URL('../../..', import.meta.url));
|
||||
const eslint = new ESLint({ cwd: repoRoot });
|
||||
|
||||
const ENGINE_FILE = 'packages/engine/src/__purity_probe__.ts';
|
||||
const OUTSIDE_FILE = 'packages/ui/src/__purity_probe__.ts';
|
||||
|
||||
async function messages(code: string, filePath: string): Promise<string[]> {
|
||||
const [result] = await eslint.lintText(code, { filePath });
|
||||
if (result === undefined) throw new Error('ESLint returned no result');
|
||||
return result.messages.map((m) => `${m.ruleId ?? 'fatal'}: ${m.message}`);
|
||||
}
|
||||
|
||||
const IMPURE: readonly [what: string, code: string][] = [
|
||||
['Date.now()', 'export const t = Date.now();'],
|
||||
['new Date() with no argument', 'export const d = new Date();'],
|
||||
['Date() called as a function', 'export const s = Date();'],
|
||||
['Math.random()', 'export const r = Math.random();'],
|
||||
['fetch()', "export const p = fetch('/x');"],
|
||||
['localStorage', "export const v = localStorage.getItem('x');"],
|
||||
['indexedDB', "export const o = indexedDB.open('x');"],
|
||||
['document', 'export const b = document.body;'],
|
||||
['window', 'export const w = window.innerWidth;'],
|
||||
['navigator', 'export const l = navigator.language;'],
|
||||
['crypto', 'export const c = crypto.randomUUID();'],
|
||||
['setTimeout', 'setTimeout(() => 0, 1);'],
|
||||
['performance.now()', 'export const n = performance.now();'],
|
||||
['the device time zone', 'export const z = Intl.DateTimeFormat().resolvedOptions().timeZone;'],
|
||||
['a UTC day', 'export const day = new Date(0).toISOString().slice(0, 10);'],
|
||||
['a Node built-in', "import { readFileSync } from 'node:fs'; export const f = readFileSync;"]
|
||||
];
|
||||
|
||||
describe('engine purity lint rule', () => {
|
||||
it.each(IMPURE)('reports %s inside packages/engine/src', async (_what, code) => {
|
||||
const found = await messages(code, ENGINE_FILE);
|
||||
expect(found.filter((m) => m.startsWith('fatal')), 'snippet must parse').toEqual([]);
|
||||
expect(found.some((m) => /^no-restricted-/.test(m)), found.join('\n')).toBe(true);
|
||||
});
|
||||
|
||||
it.each(IMPURE)('does not report %s outside the engine', async (_what, code) => {
|
||||
const found = await messages(code, OUTSIDE_FILE);
|
||||
expect(found.filter((m) => /^no-restricted-/.test(m))).toEqual([]);
|
||||
});
|
||||
|
||||
it('allows a Date built from an explicit instant', async () => {
|
||||
expect(await messages('export const d = new Date(1761500000000);', ENGINE_FILE)).toEqual([]);
|
||||
});
|
||||
|
||||
it('the real engine sources are clean', async () => {
|
||||
const results = await eslint.lintFiles(['packages/engine/src/**/*.ts']);
|
||||
expect(results.length, 'the glob must match engine sources').toBeGreaterThan(0);
|
||||
const problems = results.flatMap((r) => r.messages.map((m) => `${r.filePath}:${m.line} ${m.message}`));
|
||||
expect(problems).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "test/**/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "@rosea/schema",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "THE source of truth: JSON Schemas for hope sentences, care events and traces; generated types; the validator. Imports nothing from this repository.",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./validate": "./src/validate.ts",
|
||||
"./schemas/*": "./schemas/*"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "node scripts/generate-types.mjs && tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p tsconfig.json",
|
||||
"test": "vitest run --reporter=verbose"
|
||||
},
|
||||
"dependencies": {
|
||||
"ajv": "8.20.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"json-schema-to-typescript": "15.0.4",
|
||||
"typescript": "5.9.3",
|
||||
"vitest": "3.2.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$id": "https://rosea.invalid/schema/care-event.json",
|
||||
"title": "CareEvent",
|
||||
"description": "One act of care, append-only and never edited (CLAUDE.md §6.2). The other event kinds arrive with docs/GAMEPLAY.md.",
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["kind", "ts", "localDay", "from", "to", "act", "trace", "messageId", "clientVersion"],
|
||||
"properties": {
|
||||
"kind": { "const": "care" },
|
||||
"ts": { "description": "Epoch milliseconds. Stays on the device; never part of a trace.", "type": "integer", "minimum": 0 },
|
||||
"localDay": {
|
||||
"description": "The player's local day, from engine/src/time/localDay.ts and nowhere else.",
|
||||
"type": "string",
|
||||
"pattern": "^\\d{4}-\\d{2}-\\d{2}$"
|
||||
},
|
||||
"from": { "$ref": "#/definitions/publicKey" },
|
||||
"to": { "$ref": "#/definitions/publicKey" },
|
||||
"act": { "type": "string", "enum": ["water", "shade", "weed", "petals"] },
|
||||
"trace": { "type": "string", "pattern": "^petal:[a-z]+(-[a-z]+)*$" },
|
||||
"messageId": {
|
||||
"description": "A hope-library id or null. Never text: the pattern admits no space, so no sentence fits (CLAUDE.md §5.6 rule 1).",
|
||||
"oneOf": [
|
||||
{ "type": "string", "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$", "maxLength": 64 },
|
||||
{ "type": "null" }
|
||||
]
|
||||
},
|
||||
"clientVersion": { "type": "string", "pattern": "^\\d+\\.\\d+\\.\\d+$" }
|
||||
},
|
||||
"definitions": {
|
||||
"publicKey": {
|
||||
"description": "An opaque base64url public key. Its exact encoding is decided with packages/identity.",
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9_-]{32,128}$"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$id": "https://rosea.invalid/schema/hope-sentence.json",
|
||||
"title": "HopeSentence",
|
||||
"description": "One entry of the curated hope library (CLAUDE.md §6.1). The only words one player can send another are ids of these.",
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["id", "text", "source", "use", "tone", "promisesOutcome"],
|
||||
"properties": {
|
||||
"id": {
|
||||
"description": "Stable, lowercase, hyphenated. A message between players carries only this.",
|
||||
"type": "string",
|
||||
"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$",
|
||||
"maxLength": 64
|
||||
},
|
||||
"text": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["en"],
|
||||
"properties": {
|
||||
"en": { "type": "string", "minLength": 1 },
|
||||
"cs": { "type": "string", "minLength": 1 }
|
||||
}
|
||||
},
|
||||
"source": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["work", "author", "tradition", "translation", "publicDomain", "verifiedBy", "verifiedAt"],
|
||||
"properties": {
|
||||
"work": { "type": "string", "minLength": 1 },
|
||||
"author": { "type": ["string", "null"] },
|
||||
"tradition": {
|
||||
"description": "A lowercase tag such as `biblical` or `stoic`. `rosea` marks a line the author wrote for this game.",
|
||||
"type": "string",
|
||||
"pattern": "^[a-z]+(-[a-z]+)*$"
|
||||
},
|
||||
"translation": { "type": ["string", "null"] },
|
||||
"publicDomain": { "type": "boolean" },
|
||||
"verifiedBy": { "type": "string", "minLength": 1 },
|
||||
"verifiedAt": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$" }
|
||||
}
|
||||
},
|
||||
"use": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"uniqueItems": true,
|
||||
"items": { "type": "string", "enum": ["sunset", "comfort", "thanks"] }
|
||||
},
|
||||
"tone": { "type": "string", "pattern": "^[a-z]+(-[a-z]+)*$" },
|
||||
"promisesOutcome": { "type": "boolean" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$id": "https://rosea.invalid/schema/trace.json",
|
||||
"title": "Trace",
|
||||
"description": "An anonymous shared-sky trace, Phase 4, opt-in only (CLAUDE.md §6.3). No timestamp finer than a day, no precise location, no free text, no link to the friend graph.",
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["traceId", "geocell", "dayBucket", "gesture", "sig"],
|
||||
"properties": {
|
||||
"traceId": { "description": "Random and rotating.", "type": "string", "pattern": "^[A-Za-z0-9_-]{16,64}$" },
|
||||
"geocell": {
|
||||
"description": "A coarse cell id. The cell system and its density-adaptive size are decided in the Phase 4 feature doc.",
|
||||
"type": "string",
|
||||
"pattern": "^[a-z0-9]{4,16}$"
|
||||
},
|
||||
"dayBucket": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$" },
|
||||
"gesture": { "type": "string", "enum": ["petal", "light"] },
|
||||
"sig": { "type": "string", "pattern": "^[A-Za-z0-9_-]{16,256}$" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// Generates TypeScript types from the JSON Schemas (CLAUDE.md §7: contract types
|
||||
// are generated, never hand-written). Output is git-ignored; `build` runs first
|
||||
// in every turbo task that needs it.
|
||||
import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
|
||||
import { basename, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { compile } from 'json-schema-to-typescript';
|
||||
|
||||
const root = fileURLToPath(new URL('..', import.meta.url));
|
||||
const schemaDir = join(root, 'schemas');
|
||||
const outDir = join(root, 'src', 'generated');
|
||||
mkdirSync(outDir, { recursive: true });
|
||||
|
||||
const banner = '/* Generated by packages/schema/scripts/generate-types.mjs. Do not edit. */';
|
||||
const names = [];
|
||||
|
||||
for (const file of readdirSync(schemaDir).filter((f) => f.endsWith('.schema.json')).sort()) {
|
||||
const schema = JSON.parse(readFileSync(join(schemaDir, file), 'utf8'));
|
||||
const name = basename(file, '.schema.json');
|
||||
const ts = await compile(schema, schema.title, { bannerComment: banner, additionalProperties: false });
|
||||
writeFileSync(join(outDir, `${name}.ts`), ts);
|
||||
names.push(name);
|
||||
}
|
||||
|
||||
writeFileSync(
|
||||
join(outDir, 'index.ts'),
|
||||
`${banner}\n${names.map((n) => `export type * from './${n}.js';`).join('\n')}\n`
|
||||
);
|
||||
|
||||
console.log(`[schema] generated types for ${names.length} schemas: ${names.join(', ')}`);
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* The product's name, in one of the three places it may appear in source
|
||||
* (CLAUDE.md preamble). The other two are `apps/rosea/index.html` and the web
|
||||
* manifest, which `apps/rosea/vite.config.ts` builds from these constants.
|
||||
*
|
||||
* `Rosea` is a working name. Renaming must stay a one-commit operation: change
|
||||
* these, `index.html`, the `@rosea/*` scope and nothing else.
|
||||
*/
|
||||
|
||||
/** What the player reads. *Domi* never appears alone. */
|
||||
export const PRODUCT_NAME = 'Rosea Domi';
|
||||
|
||||
/** The short form, for the home-screen label. */
|
||||
export const PRODUCT_SHORT_NAME = 'Rosea';
|
||||
|
||||
/** The IndexedDB database name (CLAUDE.md §4). Changes together with the name. */
|
||||
export const DATABASE_NAME = 'rosea';
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './constants.js';
|
||||
export type * from './generated/index.js';
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Schema validation, for Node only: scripts, tests and the library validator.
|
||||
*
|
||||
* It is a separate entry point (`@rosea/schema/validate`) on purpose. Ajv
|
||||
* compiles validators with `new Function`, which the app's CSP forbids
|
||||
* (`script-src 'self'`, no `'unsafe-eval'`). Importing it from the browser bundle
|
||||
* would fail at runtime, not at build time. When the app needs to validate, it
|
||||
* gets standalone pre-compiled validators (GAP_ANALYSIS G0.12).
|
||||
*/
|
||||
import { Ajv, type ErrorObject, type ValidateFunction } from 'ajv';
|
||||
import careEvent from '../schemas/care-event.schema.json' with { type: 'json' };
|
||||
import hopeSentence from '../schemas/hope-sentence.schema.json' with { type: 'json' };
|
||||
import trace from '../schemas/trace.schema.json' with { type: 'json' };
|
||||
import type { CareEvent, HopeSentence, Trace } from './generated/index.js';
|
||||
|
||||
export type SchemaResult<T> =
|
||||
| { readonly ok: true; readonly value: T }
|
||||
| { readonly ok: false; readonly errors: readonly string[] };
|
||||
|
||||
const ajv = new Ajv({ allErrors: true, strict: true });
|
||||
|
||||
function wrap<T>(validate: ValidateFunction): (input: unknown) => SchemaResult<T> {
|
||||
return (input) =>
|
||||
validate(input)
|
||||
? { ok: true, value: input as T }
|
||||
: { ok: false, errors: (validate.errors ?? []).map(describe) };
|
||||
}
|
||||
|
||||
function describe(error: ErrorObject): string {
|
||||
const where = error.instancePath === '' ? '(root)' : error.instancePath;
|
||||
// Ajv already names a missing property in its message; an extra one it does not.
|
||||
const extra =
|
||||
error.keyword === 'additionalProperties'
|
||||
? ` '${String((error.params as { additionalProperty?: unknown }).additionalProperty)}'`
|
||||
: '';
|
||||
return `${where} ${error.message ?? error.keyword}${extra}`;
|
||||
}
|
||||
|
||||
export const validateHopeSentence = wrap<HopeSentence>(ajv.compile(hopeSentence));
|
||||
export const validateCareEvent = wrap<CareEvent>(ajv.compile(careEvent));
|
||||
export const validateTrace = wrap<Trace>(ajv.compile(trace));
|
||||
@@ -0,0 +1,112 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { validateCareEvent, validateHopeSentence, validateTrace } from '../src/validate.js';
|
||||
|
||||
const KEY_A = 'A'.repeat(43);
|
||||
const KEY_B = 'b_-'.repeat(15);
|
||||
|
||||
const careEvent = {
|
||||
kind: 'care',
|
||||
ts: 1761500000000,
|
||||
localDay: '2026-10-24',
|
||||
from: KEY_A,
|
||||
to: KEY_B,
|
||||
act: 'water',
|
||||
trace: 'petal:pale-pink',
|
||||
messageId: 'ps-23-4',
|
||||
clientVersion: '0.1.0'
|
||||
};
|
||||
|
||||
const sentence = {
|
||||
id: 'ps-23-4',
|
||||
text: { en: 'Placeholder text for a schema test.' },
|
||||
source: {
|
||||
work: 'Psalms 23:4',
|
||||
author: null,
|
||||
tradition: 'biblical',
|
||||
translation: 'KJV',
|
||||
publicDomain: true,
|
||||
verifiedBy: 'Test',
|
||||
verifiedAt: '2026-11-01'
|
||||
},
|
||||
use: ['sunset'],
|
||||
tone: 'gentle',
|
||||
promisesOutcome: false
|
||||
};
|
||||
|
||||
const trace = {
|
||||
traceId: 'r'.repeat(22),
|
||||
geocell: 'u2fkb',
|
||||
dayBucket: '2026-10-24',
|
||||
gesture: 'petal',
|
||||
sig: 's'.repeat(64)
|
||||
};
|
||||
|
||||
describe('hope sentence', () => {
|
||||
it('accepts a complete entry', () => {
|
||||
expect(validateHopeSentence(sentence)).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it('rejects an entry with no source', () => {
|
||||
const { source: _source, ...rest } = sentence;
|
||||
const result = validateHopeSentence(rest);
|
||||
expect(result.ok).toBe(false);
|
||||
expect(!result.ok && result.errors.join('\n')).toContain("'source'");
|
||||
});
|
||||
|
||||
it('rejects an id with a space, because an id is what travels between players', () => {
|
||||
expect(validateHopeSentence({ ...sentence, id: 'you are seen' }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects an unknown use', () => {
|
||||
expect(validateHopeSentence({ ...sentence, use: ['push-notification'] }).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('care event', () => {
|
||||
it('accepts every act the rose has', () => {
|
||||
for (const act of ['water', 'shade', 'weed', 'petals']) {
|
||||
expect(validateCareEvent({ ...careEvent, act }), act).toMatchObject({ ok: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects the acts §6.2 used to list by mistake', () => {
|
||||
for (const act of ['wind', 'light']) {
|
||||
expect(validateCareEvent({ ...careEvent, act }).ok, act).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('accepts a null messageId', () => {
|
||||
expect(validateCareEvent({ ...careEvent, messageId: null })).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it('rejects free text in messageId (CLAUDE.md §5.6 rule 1)', () => {
|
||||
expect(validateCareEvent({ ...careEvent, messageId: 'meet me at the station' }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a missing localDay', () => {
|
||||
const { localDay: _day, ...rest } = careEvent;
|
||||
expect(validateCareEvent(rest).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects any extra field, so nothing rides along unseen', () => {
|
||||
expect(validateCareEvent({ ...careEvent, note: 'hello' }).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('trace', () => {
|
||||
it('accepts a day-bucketed trace', () => {
|
||||
expect(validateTrace(trace)).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it('rejects a day bucket finer than a day', () => {
|
||||
expect(validateTrace({ ...trace, dayBucket: '2026-10-24T18:42' }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a timestamp field', () => {
|
||||
expect(validateTrace({ ...trace, ts: 1761500000000 }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a precise coordinate in place of a cell', () => {
|
||||
expect(validateTrace({ ...trace, geocell: '50.0755,14.4378' }).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "test/**/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "@rosea/ui",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Svelte components, tokens and copy/. Renders what the engine returns; decides nothing.",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"svelte": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"svelte": "./src/index.ts",
|
||||
"default": "./src/index.ts"
|
||||
},
|
||||
"./copy": "./src/copy/en.ts",
|
||||
"./tokens.css": "./src/tokens.css"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "svelte-check --threshold error --output human",
|
||||
"typecheck": "svelte-check --threshold error --output human",
|
||||
"test": "vitest run --reporter=verbose"
|
||||
},
|
||||
"dependencies": {
|
||||
"@rosea/schema": "workspace:*"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"svelte": "^5.56.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sveltejs/vite-plugin-svelte": "5.1.1",
|
||||
"@testing-library/svelte": "5.4.2",
|
||||
"jsdom": "25.0.1",
|
||||
"svelte": "5.56.9",
|
||||
"svelte-check": "4.7.6",
|
||||
"typescript": "5.9.3",
|
||||
"vite": "6.4.3",
|
||||
"vitest": "3.2.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<script lang="ts">
|
||||
import { PRODUCT_NAME } from '@rosea/schema';
|
||||
import { en } from './copy/en.js';
|
||||
</script>
|
||||
|
||||
<main class="shell">
|
||||
<h1>{PRODUCT_NAME}</h1>
|
||||
<p>{en.shell.preparing}</p>
|
||||
</main>
|
||||
|
||||
<style>
|
||||
.shell {
|
||||
min-height: 100dvh;
|
||||
display: grid;
|
||||
place-content: center;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-4);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-family: var(--font-display);
|
||||
font-weight: 400;
|
||||
font-size: clamp(2rem, 8vw, 3.5rem);
|
||||
letter-spacing: 0.02em;
|
||||
color: var(--rose);
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
color: var(--ink-soft);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Every string a player reads lives under copy/ (CLAUDE.md §7) and passes
|
||||
* `pnpm lint:copy`. Plain English; Czech arrives as `cs.ts` with the same shape.
|
||||
*
|
||||
* The product name is not repeated here: it comes from @rosea/schema, one of the
|
||||
* three places it may live.
|
||||
*/
|
||||
export const en = {
|
||||
shell: {
|
||||
/** The one line on the Phase 0 page. True, calm, and asks nothing. */
|
||||
preparing: 'The garden is being prepared.'
|
||||
}
|
||||
} as const;
|
||||
|
||||
export type Copy = typeof en;
|
||||
@@ -0,0 +1,2 @@
|
||||
export { default as Shell } from './Shell.svelte';
|
||||
export { en, type Copy } from './copy/en.js';
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Design tokens. Placeholders until docs/ART.md sets the palette: they exist so
|
||||
* components reference tokens from the first commit, never raw colours.
|
||||
* System fonts only: nothing is fetched from a CDN (CLAUDE.md §4).
|
||||
*/
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
|
||||
--paper: #fbf6f1;
|
||||
--ink: #2b2324;
|
||||
--ink-soft: #6b5d5e;
|
||||
--rose: #b4485e;
|
||||
|
||||
--font-body: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
|
||||
--font-display: Georgia, 'Times New Roman', serif;
|
||||
|
||||
--space-1: 0.25rem;
|
||||
--space-2: 0.5rem;
|
||||
--space-3: 1rem;
|
||||
--space-4: 1.5rem;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--paper: #1d1819;
|
||||
--ink: #f1e8e6;
|
||||
--ink-soft: #b8a9a8;
|
||||
--rose: #e8899b;
|
||||
}
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
font-family: var(--font-body);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
animation-duration: 0.01ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export default {};
|
||||
@@ -0,0 +1,26 @@
|
||||
import { PRODUCT_NAME } from '@rosea/schema';
|
||||
import { cleanup, render, screen } from '@testing-library/svelte';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import Shell from '../src/Shell.svelte';
|
||||
import { en } from '../src/copy/en.js';
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
describe('Shell', () => {
|
||||
it('names the product in the page heading, from the schema constant', () => {
|
||||
render(Shell);
|
||||
expect(screen.getByRole('heading', { level: 1 }).textContent).toBe(PRODUCT_NAME);
|
||||
});
|
||||
|
||||
it('shows its one line from copy/, and no control to press', () => {
|
||||
render(Shell);
|
||||
expect(screen.getByText(en.shell.preparing)).toBeTruthy();
|
||||
expect(screen.queryAllByRole('button')).toEqual([]);
|
||||
expect(screen.queryAllByRole('link')).toEqual([]);
|
||||
});
|
||||
|
||||
it('is a landmark, so a screen reader can find it', () => {
|
||||
render(Shell);
|
||||
expect(screen.getByRole('main')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node", "svelte"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.svelte", "test/**/*.ts", "vitest.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { svelte } from '@sveltejs/vite-plugin-svelte';
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [svelte()],
|
||||
// Svelte resolves its client build only under the `browser` condition.
|
||||
resolve: { conditions: ['browser'] },
|
||||
test: {
|
||||
environment: 'jsdom',
|
||||
include: ['test/**/*.test.ts']
|
||||
}
|
||||
});
|
||||
Generated
+6375
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,3 @@
|
||||
packages:
|
||||
- 'packages/*'
|
||||
- 'apps/*'
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
# Rosea commit-msg hook — CLAUDE.md §5.2: NO AI ATTRIBUTION IN COMMITS, EVER.
|
||||
# Imported from Ludus; NoAlgoTube needed a history rewrite to remove 18 of these.
|
||||
|
||||
msg_file="$1"
|
||||
|
||||
if grep -qiE '^(Co-Authored-By:.*(Claude|Anthropic|GPT|Copilot|Codex))|Claude-Session:|Generated with \[Claude Code\]|🤖 Generated with' "$msg_file"; then
|
||||
echo "BLOCKED: commit message contains an AI attribution trailer." >&2
|
||||
echo " Strip the trailer and commit again (CLAUDE.md §5.2)." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,35 @@
|
||||
// Installs the git hooks CLAUDE.md §5.2 relies on. Runs from `pnpm install` via
|
||||
// the root `prepare` script, so a fresh clone is guarded before its first commit.
|
||||
// Adapted from Ludus, including its worktree fix: in a worktree `.git` is a FILE
|
||||
// pointing at the real gitdir, and hooks resolve per worktree.
|
||||
import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const gitPath = join(root, '.git');
|
||||
|
||||
if (!existsSync(gitPath)) {
|
||||
console.log('[hooks] no .git — skipping hook install.');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
function resolveGitDir(path) {
|
||||
if (statSync(path).isDirectory()) return path;
|
||||
const target = /^gitdir:\s*(.+)$/.exec(readFileSync(path, 'utf8').trim())?.[1]?.trim();
|
||||
if (target === undefined) {
|
||||
console.log(`[hooks] ${path} is a file but not a gitdir pointer — skipping hook install.`);
|
||||
process.exit(0);
|
||||
}
|
||||
return isAbsolute(target) ? target : resolve(root, target);
|
||||
}
|
||||
|
||||
const hooksDir = join(resolveGitDir(gitPath), 'hooks');
|
||||
mkdirSync(hooksDir, { recursive: true });
|
||||
|
||||
for (const hook of ['pre-commit', 'commit-msg']) {
|
||||
const dest = join(hooksDir, hook);
|
||||
copyFileSync(join(root, 'scripts', hook), dest);
|
||||
chmodSync(dest, 0o755);
|
||||
console.log(`[hooks] installed ${hook}`);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* `pnpm lint:copy` — every file a player could read text from, checked for
|
||||
* forbidden words and names (CLAUDE.md §5.6). The rules live in
|
||||
* @rosea/content (copy-lint.ts, forbidden.ts) and are tested there.
|
||||
*
|
||||
* Not scanned: .agents/ and docs/, where the forbidden words may appear because
|
||||
* they are being discussed (§5.6 rule 4).
|
||||
*/
|
||||
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
|
||||
import { extname, join, relative } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { lintCopy } from '@rosea/content';
|
||||
|
||||
const root = fileURLToPath(new URL('..', import.meta.url));
|
||||
|
||||
/** Directories walked, and the extensions read in them. */
|
||||
const TARGETS: readonly { dir: string; ext: readonly string[] }[] = [
|
||||
{ dir: 'packages/ui/src', ext: ['.ts', '.svelte', '.css'] },
|
||||
{ dir: 'apps/rosea/src', ext: ['.ts', '.svelte', '.css'] },
|
||||
// Store listings, once they exist, live here and are player-facing too (§8).
|
||||
{ dir: 'store', ext: ['.md', '.txt', '.json'] }
|
||||
];
|
||||
|
||||
/** Single files: the page shell and the config that builds the web manifest. */
|
||||
const FILES: readonly string[] = ['apps/rosea/index.html', 'apps/rosea/vite.config.ts'];
|
||||
|
||||
function walk(dir: string, ext: readonly string[]): string[] {
|
||||
if (!existsSync(dir)) return [];
|
||||
return readdirSync(dir).flatMap((entry) => {
|
||||
const full = join(dir, entry);
|
||||
if (statSync(full).isDirectory()) return walk(full, ext);
|
||||
return ext.includes(extname(entry)) ? [full] : [];
|
||||
});
|
||||
}
|
||||
|
||||
const files = [
|
||||
...TARGETS.flatMap(({ dir, ext }) => walk(join(root, dir), ext)),
|
||||
...FILES.map((f) => join(root, f)).filter((f) => existsSync(f))
|
||||
];
|
||||
|
||||
if (files.length === 0) {
|
||||
console.error('lint:copy found no files to check. A check that reads nothing is not a pass.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let problems = 0;
|
||||
for (const file of files) {
|
||||
for (const p of lintCopy(readFileSync(file, 'utf8'))) {
|
||||
problems += 1;
|
||||
console.error(`${relative(root, file).replace(/\\/g, '/')}:${p.line} ${p.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`lint:copy: ${files.length} files checked, ${problems} problem${problems === 1 ? '' : 's'}`);
|
||||
process.exit(problems === 0 ? 0 : 1);
|
||||
@@ -0,0 +1,28 @@
|
||||
#!/bin/sh
|
||||
# Rosea pre-commit hook — CLAUDE.md §5.2.
|
||||
# .gitignore is a reminder; this is the enforcement. Rejects any staged blob over
|
||||
# 5 MB, because a raw image export cannot be removed without a history rewrite.
|
||||
|
||||
LIMIT=5242880
|
||||
report=$(mktemp)
|
||||
trap 'rm -f "$report"' EXIT
|
||||
|
||||
git diff --cached --name-only --diff-filter=ACM -z |
|
||||
while IFS= read -r -d '' path; do
|
||||
blob=$(git rev-parse ":$path" 2>/dev/null) || continue
|
||||
size=$(git cat-file -s "$blob" 2>/dev/null || echo 0)
|
||||
if [ "$size" -gt "$LIMIT" ]; then
|
||||
awk "BEGIN{printf \" %s — %.1f MB\n\", \"$path\", $size/1048576}" >> "$report"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -s "$report" ]; then
|
||||
echo "BLOCKED: staged files exceed the 5 MB limit:" >&2
|
||||
cat "$report" >&2
|
||||
echo "" >&2
|
||||
echo "Build output and raw image exports are never committed (CLAUDE.md §5.2)." >&2
|
||||
echo "Final art goes in art/final/ as optimised WebP/AVIF." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* `pnpm validate:library` — every hope sentence in content/library/, and every
|
||||
* negative fixture in content/fixtures/ (CLAUDE.md §5.5).
|
||||
*
|
||||
* Passes when the library has no problems AND every fixture fails with the rule
|
||||
* it names. A fixture that passes means a rule has stopped firing: that fails
|
||||
* the run, the same as a bad sentence.
|
||||
*/
|
||||
import { readFileSync, readdirSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { validateEntry, validateLibrary, type Rule } from '@rosea/content/validate';
|
||||
|
||||
const root = fileURLToPath(new URL('..', import.meta.url));
|
||||
const libraryDir = join(root, 'content', 'library');
|
||||
const fixturesDir = join(root, 'content', 'fixtures');
|
||||
|
||||
const jsonIn = (dir: string): string[] =>
|
||||
readdirSync(dir)
|
||||
.filter((f) => f.endsWith('.json'))
|
||||
.sort();
|
||||
|
||||
let failed = false;
|
||||
|
||||
// ── the library ────────────────────────────────────────────────────────────
|
||||
const entries: unknown[] = [];
|
||||
for (const file of jsonIn(libraryDir)) {
|
||||
const data: unknown = JSON.parse(readFileSync(join(libraryDir, file), 'utf8'));
|
||||
if (!Array.isArray(data)) {
|
||||
console.error(`content/library/${file}: must be an array of entries`);
|
||||
failed = true;
|
||||
continue;
|
||||
}
|
||||
entries.push(...data);
|
||||
}
|
||||
|
||||
for (const p of validateLibrary(entries)) {
|
||||
console.error(`library ${p.id} [${p.rule}] ${p.message}`);
|
||||
failed = true;
|
||||
}
|
||||
|
||||
const sunset = entries.filter(
|
||||
(e) => typeof e === 'object' && e !== null && Array.isArray((e as { use?: unknown }).use) && (e as { use: unknown[] }).use.includes('sunset')
|
||||
).length;
|
||||
|
||||
console.log(
|
||||
`library: ${entries.length} entr${entries.length === 1 ? 'y' : 'ies'} in ${jsonIn(libraryDir).length} files, ${sunset} sunset (release needs 365)`
|
||||
);
|
||||
|
||||
// ── the fixtures: each must FAIL, with its named rule ───────────────────────
|
||||
interface Fixture {
|
||||
expect: Rule;
|
||||
entry?: unknown;
|
||||
entries?: unknown[];
|
||||
}
|
||||
|
||||
const fixtureFiles = jsonIn(fixturesDir);
|
||||
let fixtureOk = 0;
|
||||
for (const file of fixtureFiles) {
|
||||
const fixture = JSON.parse(readFileSync(join(fixturesDir, file), 'utf8')) as Fixture;
|
||||
const problems = fixture.entries !== undefined ? validateLibrary(fixture.entries) : validateEntry(fixture.entry);
|
||||
if (problems.some((p) => p.rule === fixture.expect)) {
|
||||
fixtureOk += 1;
|
||||
} else {
|
||||
console.error(
|
||||
`fixture ${file} expected [${fixture.expect}], got ${problems.length === 0 ? 'a PASS' : problems.map((p) => `[${p.rule}]`).join(' ')}`
|
||||
);
|
||||
failed = true;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`fixtures: ${fixtureOk} of ${fixtureFiles.length} rejected as expected`);
|
||||
|
||||
if (fixtureFiles.length === 0) {
|
||||
console.error('fixtures: none found. The negative fixtures ARE the validator (CLAUDE.md §5.5).');
|
||||
failed = true;
|
||||
}
|
||||
|
||||
process.exit(failed ? 1 : 0);
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"exactOptionalPropertyTypes": true,
|
||||
"noImplicitOverride": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"isolatedModules": true,
|
||||
"resolveJsonModule": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"//": "Typechecks the repository's own tools: e2e specs and scripts. Packages typecheck themselves through turbo.",
|
||||
"extends": "./tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["e2e/**/*.ts", "scripts/**/*.ts"]
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"$schema": "https://turbo.build/schema.json",
|
||||
"ui": "stream",
|
||||
"globalDependencies": ["content/**"],
|
||||
"tasks": {
|
||||
"build": {
|
||||
"dependsOn": ["^build"],
|
||||
"outputs": ["dist/**", "src/generated/**"]
|
||||
},
|
||||
// Not cacheable. A test task's only output is its log, and a replayed log
|
||||
// is someone else's assertion about a tree you cannot see. Ludus measured
|
||||
// a cached `51 passed` against 50 in the real tree (CLAUDE.md §3 trap).
|
||||
"test": {
|
||||
"dependsOn": ["^build"],
|
||||
"outputs": [],
|
||||
"cache": false
|
||||
},
|
||||
"typecheck": {
|
||||
"dependsOn": ["^build", "build"],
|
||||
"outputs": [],
|
||||
"cache": false
|
||||
},
|
||||
"dev": {
|
||||
"dependsOn": ["^build"],
|
||||
"cache": false,
|
||||
"persistent": true
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user