Compare commits

..

3 Commits

14 changed files with 258 additions and 11 deletions
+1
View File
@@ -8,6 +8,7 @@ One row per feature, with its analysis document (CLAUDE.md §5.1). Gaps live in
| Workspace, contracts, gates, PWA shell | 0 | Merged to `main` 2026-11-01 (`d11d242`); built, not deployed. Phase 0 gate still open | [phase0-workspace.md](features/phase0-workspace.md) | [feature-phase0-workspace.md](reviews/feature-phase0-workspace.md) | | Workspace, contracts, gates, PWA shell | 0 | Merged to `main` 2026-11-01 (`d11d242`); built, not deployed. Phase 0 gate still open | [phase0-workspace.md](features/phase0-workspace.md) | [feature-phase0-workspace.md](reviews/feature-phase0-workspace.md) |
| Roadmap and gameplay docs, read against the code | 0 | Merged 2026-11-01; Q1–Q7 answered by the author | — | [docs-roadmap-gameplay.md](reviews/docs-roadmap-gameplay.md) | | Roadmap and gameplay docs, read against the code | 0 | Merged 2026-11-01; Q1–Q7 answered by the author | — | [docs-roadmap-gameplay.md](reviews/docs-roadmap-gameplay.md) |
| The Letter slot: page at `#letter`, empty `docs/LETTER.md` | 0 | Merged to `main`; built, not deployed. Invisible until the author writes | [letter-slot.md](features/letter-slot.md) | [feature-letter-slot.md](reviews/feature-letter-slot.md) | | The Letter slot: page at `#letter`, empty `docs/LETTER.md` | 0 | Merged to `main`; built, not deployed. Invisible until the author writes | [letter-slot.md](features/letter-slot.md) | [feature-letter-slot.md](reviews/feature-letter-slot.md) |
| The CPU guard: full runs wait for, then refuse, a busy machine | 0 | Merged to `main` | — | [fix-cpu-guard.md](reviews/fix-cpu-guard.md) |
| Keep her safe: the browser's promise, save her to a file, bring her back | 0–1 | Merged to `main`; built, not deployed | [keep-her-safe.md](features/keep-her-safe.md) | [feature-keep-her-safe.md](reviews/feature-keep-her-safe.md) | | Keep her safe: the browser's promise, save her to a file, bring her back | 0–1 | Merged to `main`; built, not deployed | [keep-her-safe.md](features/keep-her-safe.md) | [feature-keep-her-safe.md](reviews/feature-keep-her-safe.md) |
| The rose: care by feel, growth from days of care, drift, moods, her numbers; the care log and the identity | 1 | Merged to `main`; built, not deployed. Tuning is the author's | [rose.md](features/rose.md) | [feature-rose-care.md](reviews/feature-rose-care.md) | | The rose: care by feel, growth from days of care, drift, moods, her numbers; the care log and the identity | 1 | Merged to `main`; built, not deployed. Tuning is the author's | [rose.md](features/rose.md) | [feature-rose-care.md](reviews/feature-rose-care.md) |
| Where the sunset is: choose a town (or skip to a guess from the device's zone), kept on the device; tonight's sunset in the garden | 1 | Merged to `main`; built, not deployed | [sunset-place.md](features/sunset-place.md) | [feature-sunset-place.md](reviews/feature-sunset-place.md) | | Where the sunset is: choose a town (or skip to a guess from the device's zone), kept on the device; tonight's sunset in the garden | 1 | Merged to `main`; built, not deployed | [sunset-place.md](features/sunset-place.md) | [feature-sunset-place.md](reviews/feature-sunset-place.md) |
+1
View File
@@ -42,6 +42,7 @@ board exist, and the first real picture is the author's to make.
| G0.23 | Source maps are built and would be published | Open. `sourcemap: true`; maps are not precached. Decide with G0.13 whether the repository is public. If not, use `'hidden'`. | | G0.23 | Source maps are built and would be published | Open. `sourcemap: true`; maps are not precached. Decide with G0.13 whether the repository is public. If not, use `'hidden'`. |
| G0.24 | No art pipeline: `docs/ART.md`, `art/STYLE.md` (drafted with the author), `art/manifest.json` for Phase 1 assets, SVG placeholders, `tools/art-prep` | **Pipeline built 2026-11-01** (`feature/art-board`): docs/ART.md, the Phase 1 manifest (25 pictures), 29 generated stand-ins, `tools/art-prep` (50 tests; 5 of 5 put-back bugs caught), the art board published. STYLE.md approved by the author 2026-11-01 (S1–S5 kept as drafted; `docs/style-approved`). The board grew to 53 pictures with Phases 2–3 (`art/phase2-3-pictures`); the fox's look F1–F4 approved with a deep red-orange coat (`art/fox-coat`). **Still open:** the **Phase 0 gate**, one real picture through every step into `art/final/`. | | G0.24 | No art pipeline: `docs/ART.md`, `art/STYLE.md` (drafted with the author), `art/manifest.json` for Phase 1 assets, SVG placeholders, `tools/art-prep` | **Pipeline built 2026-11-01** (`feature/art-board`): docs/ART.md, the Phase 1 manifest (25 pictures), 29 generated stand-ins, `tools/art-prep` (50 tests; 5 of 5 put-back bugs caught), the art board published. STYLE.md approved by the author 2026-11-01 (S1–S5 kept as drafted; `docs/style-approved`). The board grew to 53 pictures with Phases 2–3 (`art/phase2-3-pictures`); the fox's look F1–F4 approved with a deep red-orange coat (`art/fox-coat`). **Still open:** the **Phase 0 gate**, one real picture through every step into `art/final/`. |
| ~~G0.25~~ | ~~No slot for *A Letter from the Gardener*~~ | Closed 2026-11-01, merged to `main`. `docs/LETTER.md` holds slots as comments only; the page opens at `#letter` once it has words. 16 ui tests, and e2e on both the empty and a temporary written letter. Mutations caught: the link while empty, any link scheme, focus not moving, *heal* in the letter. | | ~~G0.25~~ | ~~No slot for *A Letter from the Gardener*~~ | Closed 2026-11-01, merged to `main`. `docs/LETTER.md` holds slots as comments only; the page opens at `#letter` once it has words. 16 ui tests, and e2e on both the empty and a temporary written letter. Mutations caught: the link while empty, any link scheme, focus not moving, *heal* in the letter. |
| ~~G0.28~~ | ~~CLAUDE.md §5.7's CPU limit was only read, and broken three times on 2026-11-02~~ | Closed 2026-11-02 on `fix/cpu-guard`: `pnpm guard:cpu` runs before every full run, waits up to 3 min, then refuses. 13 tests; seen waiting 51 s on a busy machine, refusing, and stopping `pnpm test` before any test ran. |
| G0.27 | The quiet door to real help has no numbers (§5.6 rule 5) | Open. The slot is in `docs/LETTER.md`. Support lines are real-world facts the author must verify, per country, so the door exists only once the letter does. | | G0.27 | The quiet door to real help has no numbers (§5.6 rule 5) | Open. The slot is in `docs/LETTER.md`. Support lines are real-world facts the author must verify, per country, so the door exists only once the letter does. |
| ~~G0.26~~ | ~~Not decided: how the sunset invitation reaches the player on the web~~ | Closed 2026-11-01 by the author (Q6): in-app only on the web, no push server; local notifications through the Tauri shell in Phase 6. Recorded in ROADMAP Phase 0 and CLAUDE.md §8. | | ~~G0.26~~ | ~~Not decided: how the sunset invitation reaches the player on the web~~ | Closed 2026-11-01 by the author (Q6): in-app only on the web, no push server; local notifications through the Tauri shell in Phase 6. Recorded in ROADMAP Phase 0 and CLAUDE.md §8. |
+3 -3
View File
@@ -42,6 +42,6 @@ because the check and the run were chained in one command that did not depend on
**Why it bit.** A rule that relies on a person reading a number before acting holds only **Why it bit.** A rule that relies on a person reading a number before acting holds only
while nothing else is competing for attention. while nothing else is competing for attention.
**How to apply it.** Make the run refuse to start: a gate script that samples the load **How to apply it.** Make the run refuse to start. Done: `pnpm guard:cpu` (in
and exits above 80 %, waiting or saying so. Until it exists, read the number in its own `tools/cpu-guard`) runs before every full run, waits up to three minutes, then refuses. Do
step and decide before starting the run. not set `ROSEA_CPU_MAX` to get past a busy desktop; it is for dedicated machines.
+1 -1
View File
@@ -32,7 +32,7 @@ Counts are on the merge; HANDOVER repeats them. New here: engine +4, storage +6,
| 5 | Privacy | The file is a diary of when someone was in the app. | Made only on request; the screen says what it holds; no town and no private key (tested in unit and e2e). It goes wherever the player puts it, which Rosea cannot see. | | 5 | Privacy | The file is a diary of when someone was in the app. | Made only on request; the screen says what it holds; no town and no private key (tested in unit and e2e). It goes wherever the player puts it, which Rosea cannot see. |
| 6 | Privacy | A file brought back could have been edited by hand to give her days she was never given. | It only changes the player's own garden; nothing is counted against anyone (CLAUDE.md §1). Phase 3 must not treat imported care as proof towards friends: noted in the analysis. | | 6 | Privacy | A file brought back could have been edited by hand to give her days she was never given. | It only changes the player's own garden; nothing is counted against anyone (CLAUDE.md §1). Phase 3 must not treat imported care as proof towards friends: noted in the analysis. |
| 7 | Soul | "This browser may clear her" can frighten. | Shown only behind *Keep her safe*, with the remedy in the same sentence; a refusal is said calmly. Nothing reminds or nags. | | 7 | Soul | "This browser may clear her" can frighten. | Shown only behind *Keep her safe*, with the remedy in the same sentence; a refusal is said calmly. Nothing reminds or nags. |
| 8 | Process | The first e2e run **and the full gate run** both started with the CPU at 100 %, above the 80 % rule (CLAUDE.md §5.7). The load was another project's test run on this machine. The second time the reading was taken, but the run was chained after it without depending on it. Both passed. | **Not fixed by intention alone**: a gate script that refuses to start above 80 % would make the rule real. Lesson: `process.md`. | | 8 | Process | The first e2e run **and the full gate run** both started with the CPU at 100 %, above the 80 % rule (CLAUDE.md §5.7). The load was another project's test run on this machine. The second time the reading was taken, but the run was chained after it without depending on it. Both passed. | **Fixed on `fix/cpu-guard`**: `pnpm guard:cpu` now runs before every full run. Lesson: `process.md`. |
| 9 | Accessibility | A file input styled as a button. | The real input stays in place, labelled by its text, keyboard-operable; axe passes on the restored garden. Not tested with a screen reader. | | 9 | Accessibility | A file input styled as a button. | The real input stays in place, labelled by its text, keyboard-operable; axe passes on the restored garden. Not tested with a screen reader. |
## What was not verified ## What was not verified
+47
View File
@@ -0,0 +1,47 @@
# Review — `fix/cpu-guard`
Adversarial self-review (CLAUDE.md §5.3). Reviewed 2026-11-02 on Node 22.11.0, Windows 10.
There is no PR: the only remote is Gitea.
## Why and what
CLAUDE.md §5.7: *do not start a full run above ~80 % CPU.* On 2026-11-02 that was broken three times
(lessons/process.md), twice right after reading the number. Now `pnpm test`, `test:e2e` and
`test:offline` first run `pnpm guard:cpu` (`tools/cpu-guard`):
```mermaid
flowchart LR
run["pnpm test / test:e2e / test:offline"] --> guard["guard:cpu<br/>sample 2 s with os.cpus()"]
guard -->|"≤ 80 %"| go["the run starts"]
guard -->|"> 80 %"| wait["wait 10 s, sample again"] --> guard
wait -->|"after 180 s"| stop["exit 1: not starting"]
```
Node's `os.cpus()`, not a shell command, so it works the same on Windows, Linux and macOS. A
dedicated machine sets `ROSEA_CPU_MAX` (100 never refuses) and `ROSEA_CPU_WAIT_SECONDS`; a value
that is not a whole number in range is refused, never quietly the default.
## Checks
| Check | Result |
|:--|:--|
| Unit tests, `tools/cpu-guard` | **13 passed**: the busy share between two readings (not since boot), system time as busy, no NaN on equal readings, defaults, overrides, five bad settings, start / wait / refuse |
| On this machine, busy with another project's tests | waited 51 s at 93–100 %, then started at 61 % |
| Forced refusal (`ROSEA_CPU_MAX=1`, no wait) | exit 1 with the reason |
| `pnpm test` behind a refusal | stopped before Turbo ran a single test |
| The guard's reading beside Windows' own counter, sampled together | 64 / 75, 93 / 96, 96 / 98 % |
## Findings
| # | Finding | Resolution |
|:--|:--|:--|
| 1 | The guard measures before the run, not during it: a machine that becomes busy mid-run is not seen. | Accepted: §5.7 is about starting. Stopping a run halfway would leave browsers and servers half-closed, the very mess §5.7 exists to avoid. |
| 2 | `ROSEA_CPU_MAX=100` is a way round the rule. | Documented as for dedicated machines only, in CLAUDE.md §5.7 and the lesson. An override nobody can use would push people to edit the script instead. |
| 3 | The guard adds 2 s to every full run on a quiet machine. | Accepted. |
| 4 | Filtered runs (`pnpm --filter X test`) and drills are not guarded. | By design: they are not full runs. |
| 5 | Its own 2 s sample could read its own start-up as load. | It samples after Node has started. Not measured on a quiet machine: this one was busy all session. Beside Windows' counter it read 2–11 points lower, never higher. |
## Not verified
- macOS and Linux (only Windows 10 here).
- A CI runner: there is none yet (G0.22).
+5 -1
View File
@@ -220,6 +220,7 @@ pnpm test:e2e # builds, then Playwright against the B
pnpm test:offline # builds, loads once, CLOSES the server, reloads pnpm test:offline # builds, loads once, CLOSES the server, reloads
pnpm validate:library # every hope sentence; fixtures must FAIL pnpm validate:library # every hope sentence; fixtures must FAIL
pnpm lint:copy # forbidden words and names (§5.6) pnpm lint:copy # forbidden words and names (§5.6)
pnpm guard:cpu # waits for, then refuses, a machine above 80 % CPU (§5.7)
pnpm art:board # prompts + stand-ins -> tools/art-prep/dist/board/ (docs/ART.md) pnpm art:board # prompts + stand-ins -> tools/art-prep/dist/board/ (docs/ART.md)
pnpm art:accept <id> <file> # an accepted picture -> art/final/*.webp, sheets cut pnpm art:accept <id> <file> # an accepted picture -> art/final/*.webp, sheets cut
tsx scripts/build-places.ts <folder> # rebuilds the town list from downloaded Natural Earth + tzdb (by hand) tsx scripts/build-places.ts <folder> # rebuilds the town list from downloaded Natural Earth + tzdb (by hand)
@@ -412,7 +413,10 @@ happened twice.)*
### 5.7 A test run leaves the machine as it found it ### 5.7 A test run leaves the machine as it found it
Nothing binds to anything but `127.0.0.1`. Every browser a test starts is closed in `finally`. Do not Nothing binds to anything but `127.0.0.1`. Every browser a test starts is closed in `finally`. Do not
start a full run above ~80% CPU. *(Imported from Ludus and Aeterna.)* start a full run above ~80% CPU. *(Imported from Ludus and Aeterna.)* **Enforced, not trusted:**
`pnpm test`, `test:e2e` and `test:offline` first run `pnpm guard:cpu`, which waits up to three minutes
for the machine to calm and then refuses (`tools/cpu-guard`, lessons/process.md). A dedicated machine
such as CI sets `ROSEA_CPU_MAX` (100 never refuses); never set it to get past a busy desktop.
--- ---
+5 -2
View File
@@ -12,8 +12,8 @@ Rewritten at the end of each session (CLAUDE.md §5.1).
Gitea hashes match. Analysis: [`.agents/features/phase0-workspace.md`](.agents/features/phase0-workspace.md). Gitea hashes match. Analysis: [`.agents/features/phase0-workspace.md`](.agents/features/phase0-workspace.md).
Review, with counts and the mutation results: Review, with counts and the mutation results:
[`.agents/reviews/feature-phase0-workspace.md`](.agents/reviews/feature-phase0-workspace.md). [`.agents/reviews/feature-phase0-workspace.md`](.agents/reviews/feature-phase0-workspace.md).
- **Gates:** all pass on this machine. Unit tests: 373 (identity 5, schema 16, content 71, - **Gates:** all pass on this machine. Unit tests: 386 (cpu-guard 13, identity 5, schema 16,
storage 51, art-prep 56, engine 136, ui 38). E2E: 13. Offline: 1. `lint:copy`: 19 files, 0 problems. content 71, storage 51, art-prep 56, engine 136, ui 38). E2E: 13. Offline: 1. `lint:copy`: 19 files, 0 problems.
`validate:library`: 13 of 13 fixtures rejected. `validate:library`: 13 of 13 fixtures rejected.
- **Built, not deployed:** there is no host yet. - **Built, not deployed:** there is no host yet.
- **Roadmap and gameplay docs:** `docs/ROADMAP.md` and `docs/GAMEPLAY.md` are on - **Roadmap and gameplay docs:** `docs/ROADMAP.md` and `docs/GAMEPLAY.md` are on
@@ -91,6 +91,9 @@ The notification decision is made: in-app only on the web (G0.26).
**How this machine works** (not in the code): **How this machine works** (not in the code):
- **The CPU guard:** the full runs wait for this machine to drop to 80 % CPU (§5.7). Other projects'
test runs share it, so a wait of a minute or two is normal; three minutes, and the run is refused.
- **Commit identity:** `mnovak <giteatruenasadminacc.from729@passmail.net>`, set in - **Commit identity:** `mnovak <giteatruenasadminacc.from729@passmail.net>`, set in
this repository only. this repository only.
- **Pushing:** it uses a repo-local `credential.helper`, copied from Ludus. Do not - **Pushing:** it uses a repo-local `credential.helper`, copied from Ludus. Do not
+5 -4
View File
@@ -12,13 +12,14 @@
"build": "turbo run build", "build": "turbo run build",
"typecheck": "turbo run typecheck && tsc -p tsconfig.json --noEmit", "typecheck": "turbo run typecheck && tsc -p tsconfig.json --noEmit",
"lint": "eslint .", "lint": "eslint .",
"test": "turbo run test", "test": "pnpm guard:cpu && turbo run test",
"test:e2e": "turbo run build --filter=@rosea/app && playwright test --config=e2e/playwright.config.ts", "test:e2e": "pnpm guard:cpu && 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", "test:offline": "pnpm guard:cpu && turbo run build --filter=@rosea/app && playwright test --config=e2e/playwright.offline.config.ts",
"validate:library": "tsx scripts/validate-library.ts", "validate:library": "tsx scripts/validate-library.ts",
"lint:copy": "tsx scripts/lint-copy.ts", "lint:copy": "tsx scripts/lint-copy.ts",
"art:board": "tsx tools/art-prep/src/cli-board.ts", "art:board": "tsx tools/art-prep/src/cli-board.ts",
"art:accept": "tsx tools/art-prep/src/cli-accept.ts" "art:accept": "tsx tools/art-prep/src/cli-accept.ts",
"guard:cpu": "tsx tools/cpu-guard/src/cli.ts"
}, },
"devDependencies": { "devDependencies": {
"@axe-core/playwright": "4.13.0", "@axe-core/playwright": "4.13.0",
+12
View File
@@ -238,6 +238,18 @@ importers:
specifier: 3.2.7 specifier: 3.2.7
version: 3.2.7(@types/node@22.20.1)(jsdom@25.0.1)(terser@5.51.2)(tsx@4.23.12) version: 3.2.7(@types/node@22.20.1)(jsdom@25.0.1)(terser@5.51.2)(tsx@4.23.12)
tools/cpu-guard:
devDependencies:
'@types/node':
specifier: 22.20.1
version: 22.20.1
typescript:
specifier: 5.9.3
version: 5.9.3
vitest:
specifier: 3.2.7
version: 3.2.7(@types/node@22.20.1)(jsdom@25.0.1)(terser@5.51.2)(tsx@4.23.12)
packages: packages:
'@apideck/better-ajv-errors@0.3.7': '@apideck/better-ajv-errors@0.3.7':
+16
View File
@@ -0,0 +1,16 @@
{
"name": "@rosea/cpu-guard",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "Refuses to start a full test run while the machine is busy (CLAUDE.md §5.7). Never imported by the app.",
"scripts": {
"typecheck": "tsc -p tsconfig.json",
"test": "vitest run --reporter=verbose"
},
"devDependencies": {
"@types/node": "22.20.1",
"typescript": "5.9.3",
"vitest": "3.2.7"
}
}
+45
View File
@@ -0,0 +1,45 @@
/**
* `pnpm guard:cpu` — samples the machine for 2 s; starts if it is at or under the
* limit, waits and samples again while it is not, and exits 1 once the wait is used
* up. The full runs (`pnpm test`, `test:e2e`, `test:offline`) call it first.
*/
import { cpus } from 'node:os';
import { setTimeout as sleep } from 'node:timers/promises';
import { busyPercent, decide, limitsFrom } from './guard.js';
const SAMPLE_MS = 2_000;
const PAUSE_MS = 10_000;
async function sample(): Promise<number> {
const before = cpus();
await sleep(SAMPLE_MS);
return busyPercent(before, cpus());
}
let limits;
try {
limits = limitsFrom(process.env);
} catch (error) {
console.error(`guard:cpu: ${(error as Error).message}`);
process.exit(2);
}
const started = Date.now();
for (;;) {
const busy = await sample();
const waited = Math.round((Date.now() - started) / 1000);
const verdict = decide(busy, waited, limits);
if (verdict === 'start') {
console.log(`guard:cpu: ${busy} % busy, at or under ${limits.max} %. Starting.`);
break;
}
if (verdict === 'refuse') {
console.error(
`guard:cpu: still ${busy} % busy after ${waited} s, above ${limits.max} % (CLAUDE.md §5.7). Not starting.\n` +
' Close what is busy, or on a dedicated machine set ROSEA_CPU_MAX (100 never refuses).'
);
process.exit(1);
}
console.log(`guard:cpu: ${busy} % busy, above ${limits.max} %. Waiting (${waited} of ${limits.waitSeconds} s).`);
await sleep(PAUSE_MS);
}
+53
View File
@@ -0,0 +1,53 @@
/**
* CLAUDE.md §5.7: do not start a full run above ~80 % CPU. Read by a person, the rule
* was broken three times in one day (lessons/process.md), so a full run now asks
* this guard first. The logic is pure; `cli.ts` does the sampling and the waiting.
*/
import type { CpuInfo } from 'node:os';
/** The default limit, CLAUDE.md §5.7. */
export const DEFAULT_MAX = 80;
/** How long a busy machine is waited for before the run is refused. */
export const DEFAULT_WAIT_SECONDS = 180;
/** Whole-machine busy share between two `os.cpus()` readings, 0–100. */
export function busyPercent(before: readonly CpuInfo[], after: readonly CpuInfo[]): number {
let busy = 0;
let total = 0;
for (let i = 0; i < Math.min(before.length, after.length); i++) {
const a = before[i]!.times;
const b = after[i]!.times;
const idle = b.idle - a.idle;
const all = b.user - a.user + (b.nice - a.nice) + (b.sys - a.sys) + (b.irq - a.irq) + idle;
busy += all - idle;
total += all;
}
return total <= 0 ? 0 : Math.round((busy / total) * 100);
}
export interface Limits {
readonly max: number;
readonly waitSeconds: number;
}
/**
* The limits, from the environment. `ROSEA_CPU_MAX` is for a dedicated machine such as
* CI (100 never refuses); `ROSEA_CPU_WAIT_SECONDS` for how long to wait. A value that
* is not a whole number in range is an error, never quietly the default.
*/
export function limitsFrom(env: Readonly<Record<string, string | undefined>>): Limits {
const read = (name: string, fallback: number, min: number, max: number): number => {
const raw = env[name];
if (raw === undefined || raw.trim() === '') return fallback;
const n = Number(raw);
if (!Number.isInteger(n) || n < min || n > max) throw new RangeError(`${name} must be a whole number from ${min} to ${max}, got '${raw}'`);
return n;
};
return { max: read('ROSEA_CPU_MAX', DEFAULT_MAX, 1, 100), waitSeconds: read('ROSEA_CPU_WAIT_SECONDS', DEFAULT_WAIT_SECONDS, 0, 3600) };
}
/** Start once a sample is at or under the limit; refuse once the wait is used up. */
export function decide(busy: number, waitedSeconds: number, limits: Limits): 'start' | 'wait' | 'refuse' {
if (busy <= limits.max) return 'start';
return waitedSeconds >= limits.waitSeconds ? 'refuse' : 'wait';
}
+57
View File
@@ -0,0 +1,57 @@
import type { CpuInfo } from 'node:os';
import { describe, expect, it } from 'vitest';
import { busyPercent, decide, DEFAULT_MAX, DEFAULT_WAIT_SECONDS, limitsFrom } from '../src/guard.js';
const core = (user: number, idle: number, sys = 0): CpuInfo => ({ model: 'test', speed: 1, times: { user, nice: 0, sys, idle, irq: 0 } });
describe('busyPercent', () => {
it('measures the whole machine between two readings, not since boot', () => {
// Since boot both cores look idle; between the readings one is full and one is idle.
const before = [core(1_000, 99_000), core(1_000, 99_000)];
const after = [core(2_000, 99_000), core(1_000, 100_000)];
expect(busyPercent(before, after)).toBe(50);
});
it('counts system time as busy, and an idle machine as 0', () => {
expect(busyPercent([core(0, 0)], [core(300, 100, 600)])).toBe(90);
expect(busyPercent([core(5, 5)], [core(5, 1005)])).toBe(0);
});
it('two readings with no time between them are 0, never NaN', () => {
expect(busyPercent([core(1, 1)], [core(1, 1)])).toBe(0);
});
});
describe('limitsFrom', () => {
it('defaults to CLAUDE.md §5.7: 80 %, waiting three minutes', () => {
expect(limitsFrom({})).toEqual({ max: DEFAULT_MAX, waitSeconds: DEFAULT_WAIT_SECONDS });
expect(DEFAULT_MAX).toBe(80);
});
it('reads a dedicated machine\'s limit and wait', () => {
expect(limitsFrom({ ROSEA_CPU_MAX: '100', ROSEA_CPU_WAIT_SECONDS: '0' })).toEqual({ max: 100, waitSeconds: 0 });
});
it.each(['abc', '0', '101', '80.5', '-5'])('refuses ROSEA_CPU_MAX=%s rather than quietly using the default', (raw) => {
expect(() => limitsFrom({ ROSEA_CPU_MAX: raw })).toThrow(/ROSEA_CPU_MAX must be a whole number from 1 to 100/);
});
});
describe('decide', () => {
const limits = { max: 80, waitSeconds: 180 };
it('starts at or under the limit', () => {
expect(decide(80, 0, limits)).toBe('start');
expect(decide(12, 500, limits)).toBe('start');
});
it('waits while busy, then refuses once the wait is used up', () => {
expect(decide(81, 0, limits)).toBe('wait');
expect(decide(100, 179, limits)).toBe('wait');
expect(decide(100, 180, limits)).toBe('refuse');
});
it('with no wait, refuses at once', () => {
expect(decide(95, 0, { max: 80, waitSeconds: 0 })).toBe('refuse');
});
});
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node"]
},
"include": ["src/**/*.ts", "test/**/*.ts"]
}