[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:
2026-11-01 00:27:33 +01:00
parent 1e4c5a06b6
commit 49c8def037
78 changed files with 9015 additions and 0 deletions
+26
View File
@@ -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"
}
}
+1
View File
@@ -0,0 +1 @@
export { isLocalDay, localDay, type LocalDay } from './time/localDay.js';
+67
View File
@@ -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);
}
+88
View File
@@ -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)));
});
});
+66
View File
@@ -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([]);
});
});
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node"]
},
"include": ["src/**/*.ts", "test/**/*.ts"]
}