1
0

Spaces: the inside of the world, and a sun that is actually where it should be

Ten agents wrote this in parallel against CONTRACT.md, which exists because the
five design agents before them collided on fifteen blocking points — four files
specified twice with incompatible contents, three separate backends for one box,
and `Environment` exported twice meaning different things.

What landed: a Stage owning only the renderer and the loop, with the city and an
office as two scenes over it. They cannot share one — San Francisco is ~94 m per
scene unit with 3.6x vertical exaggeration and an office is 1 unit = 1 m — and
the city is paused rather than disposed on the way in, because rebuilding its
336,864-point heightfield costs about a second on the way back out.

Offices are data. `src/offices/lumbridge-hq.ts` is fifteen rooms and seventy-six
seats, and it is the file a self-hoster copies. Walls are a segment list with
1-D openings, so doors and windows are holes punched in a wall rather than
placed objects, and the pass that splits a wall around its openings hands the
walk-mode collider its segments for free.

The sun is real. `solar.ts` is a NOAA/Meeus implementation with no imports at
all — not even three.js — so time of day keeps working on a laptop in a field.
Verified against known values: 75.45 degrees at the June solstice in SF, 28.79
at December, sunset at 03:15Z. The first screenshot after wiring it was a black
rectangle, which turned out to be correct: it was midnight in San Francisco.

Presence binds to a seat id and never to a coordinate. The pack knows where
`eng-04` is; who is sitting in it is private data behind an API. Same shape as
the marker rule, one level in.

Two corrections to ARCHITECTURE.md are in here. Containment does not discharge
ODbL — publishing OSM-derived coordinates is Public Use of a Derivative Database
wherever the rows live, so the rule is about the geocoder (US Census, public
domain) and not the storage. And a person at a desk is not a Marker; markers are
geographic.

One contract gap surfaced only in a screenshot: two agents read `height` on a
viewpoint differently, so the establishing shot aimed at empty air fourteen
metres above the roof. It now means what the same field means for a city.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Karti Tripathi
2026-08-05 00:11:01 -07:00
parent 36471bbad7
commit d464459838
77 changed files with 14266 additions and 216 deletions
+158
View File
@@ -0,0 +1,158 @@
/**
* The acceptance test: a stranger with no keys, no account and no environment.
*
* This is CONTRACT.md §5.1 written as code, because it is the thing two
* independent server designs got wrong in the same way — a weather source that
* defaults to a provider needing a contact string, and a hard failure when it is
* absent. The last test in this file starts the real entry point under a
* genuinely empty environment and asks it for its health, which is the same
* assertion the `docker compose up` CI job makes from outside.
*/
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { after, describe, it } from "node:test";
import { buildApp } from "../app.ts";
import { loadConfig } from "../config.ts";
import type {
FlightsBody,
HealthBody,
MarkersBody,
WeatherBody,
} from "../../../src/server/wire.ts";
/** `loadConfig({})` is exactly what `env -i` produces, minus the process. */
function emptyEnvApp() {
const config = loadConfig({});
config.logLevel = "silent";
return buildApp(config);
}
describe("a box handed nothing", () => {
it("defaults every source to its keyless setting and reports no demotions", () => {
const config = loadConfig({});
assert.equal(config.weather.source, "none");
assert.equal(config.flights.source, "sim");
assert.equal(config.markers.source, "none");
assert.equal(config.auth.mode, "none");
assert.equal(config.host, "127.0.0.1");
assert.equal(config.port, 8431);
assert.deepEqual(config.degraded, []);
});
it("answers health", async () => {
const app = emptyEnvApp();
after(() => app.close());
const res = await app.inject({ method: "GET", url: "/api/v1/health" });
assert.equal(res.statusCode, 200);
const body = res.json<HealthBody>();
assert.equal(body.ok, true);
assert.equal(body.auth.mode, "none");
assert.equal(body.auth.entryUrl, null);
assert.deepEqual(body.degraded, []);
});
it("serves a synthetic clear day rather than failing on a missing contact", async () => {
const app = emptyEnvApp();
after(() => app.close());
const res = await app.inject({ method: "GET", url: "/api/v1/weather" });
assert.equal(res.statusCode, 200);
const body = res.json<WeatherBody>();
assert.equal(body.synthetic, true);
assert.equal(body.source, "none");
assert.equal(body.condition, "clear");
});
it("serves the simulated sky as a plan, not as positions", async () => {
const app = emptyEnvApp();
after(() => app.close());
const body = (await app.inject({ method: "GET", url: "/api/v1/flights" })).json<FlightsBody>();
assert.equal(body.mode, "plan");
assert.equal(body.source, "sim");
assert.ok(body.mode === "plan" && body.routes.length > 0);
// A fixed origin, so a restart does not teleport every aircraft.
assert.ok(body.mode === "plan" && body.t0 < Date.now());
});
it("serves no markers and says so, rather than 404ing the route", async () => {
const app = emptyEnvApp();
after(() => app.close());
const res = await app.inject({ method: "GET", url: "/api/v1/markers" });
assert.equal(res.statusCode, 200);
assert.deepEqual(res.json<MarkersBody>().markers, []);
});
it("has no offices", async () => {
const app = emptyEnvApp();
after(() => app.close());
const res = await app.inject({ method: "GET", url: "/api/v1/offices/anything" });
assert.equal(res.statusCode, 404);
});
});
describe("cache-control is fail-closed", () => {
it("stamps private, no-store on anything that did not opt in", async () => {
const app = emptyEnvApp();
after(() => app.close());
const health = await app.inject({ method: "GET", url: "/api/v1/health" });
assert.equal(health.headers["cache-control"], "private, no-store");
const missing = await app.inject({ method: "GET", url: "/api/v1/nope" });
assert.equal(missing.statusCode, 404);
assert.equal(missing.headers["cache-control"], "private, no-store");
});
it("lets a route opt in explicitly", async () => {
const app = emptyEnvApp();
after(() => app.close());
const res = await app.inject({ method: "GET", url: "/api/v1/flights" });
assert.match(String(res.headers["cache-control"]), /^public, max-age=\d+$/);
});
it("refuses to opt in when the request carried a credential", async () => {
const app = emptyEnvApp();
after(() => app.close());
const res = await app.inject({
method: "GET",
url: "/api/v1/flights",
headers: { authorization: "Bearer something" },
});
assert.equal(res.headers["cache-control"], "private, no-store");
});
});
describe("the real process under env -i", () => {
it("boots and answers health with no environment at all", async () => {
const entry = new URL("../index.ts", import.meta.url).pathname;
// A genuinely empty environment: no PATH, no HOME, no TERA_*. `execPath` is
// absolute, so the child needs nothing from the parent to start.
const child = spawn(process.execPath, [entry], { env: {}, stdio: "ignore" });
after(() => child.kill("SIGKILL"));
const url = "http://127.0.0.1:8431/api/v1/health";
const deadline = Date.now() + 15_000;
let body: HealthBody | null = null;
while (Date.now() < deadline && body === null) {
try {
const res = await fetch(url);
if (res.ok) body = (await res.json()) as HealthBody;
} catch {
await new Promise((resolve) => setTimeout(resolve, 200));
}
}
assert.ok(body !== null, "the server never answered on 127.0.0.1:8431");
assert.equal(body.ok, true);
assert.equal(body.service, "tera-api");
});
});
+94
View File
@@ -0,0 +1,94 @@
/**
* Demotion, not fatality.
*
* Every case here is a misconfiguration that an earlier design would have
* thrown on at boot. The rule is that the server comes up, says exactly what it
* gave up on, and serves the degraded body — a self-hoster who typed the wrong
* thing gets a working map and a sentence explaining it, not a process that
* refuses to start. CONTRACT.md §5.1.
*/
import assert from "node:assert/strict";
import { after, describe, it } from "node:test";
import { buildApp } from "../app.ts";
import { loadConfig } from "../config.ts";
import type { HealthBody, WeatherBody } from "../../../src/server/wire.ts";
function appWith(env: Record<string, string>) {
const config = loadConfig(env);
config.logLevel = "silent";
return { config, app: buildApp(config) };
}
describe("a weather source configured without a contact", () => {
it("demotes to synthetic and says why", async () => {
const { config, app } = appWith({ TERA_WEATHER_SOURCE: "nws" });
after(() => app.close());
assert.equal(config.weather.source, "none");
assert.equal(config.degraded.length, 1);
assert.match(config.degraded[0] ?? "", /TERA_WEATHER_CONTACT/);
const health = (await app.inject({ method: "GET", url: "/api/v1/health" })).json<HealthBody>();
assert.equal(health.ok, true);
assert.equal(health.sources.weather, "none");
assert.equal(health.degraded.length, 1);
const weather = (
await app.inject({ method: "GET", url: "/api/v1/weather" })
).json<WeatherBody>();
assert.equal(weather.synthetic, true);
});
it("keeps the source once a contact is present", () => {
const { config, app } = appWith({
TERA_WEATHER_SOURCE: "nws",
TERA_WEATHER_CONTACT: "ops@example.com",
});
after(() => app.close());
assert.equal(config.weather.source, "nws");
assert.deepEqual(config.degraded, []);
});
});
describe("other misconfigurations", () => {
it("falls back on an unknown source name rather than exiting", () => {
const { config, app } = appWith({ TERA_WEATHER_SOURCE: "accuweather" });
after(() => app.close());
assert.equal(config.weather.source, "none");
assert.match(config.degraded[0] ?? "", /accuweather/);
});
it("falls back on a port that is not a number", () => {
const config = loadConfig({ TERA_PORT: "banana" });
assert.equal(config.port, 8431);
assert.match(config.degraded[0] ?? "", /TERA_PORT/);
});
it("records that Open-Meteo is a non-commercial tier without disabling it", () => {
const config = loadConfig({ TERA_WEATHER_SOURCE: "openmeteo" });
assert.equal(config.weather.source, "openmeteo");
assert.match(config.degraded[0] ?? "", /non-commercial/);
});
it("demotes sso with nowhere to revalidate, taking private offices with it", () => {
const config = loadConfig({ TERA_AUTH_MODE: "sso", TERA_AUTH_ENTRY_URL: "https://example" });
assert.equal(config.auth.mode, "none");
assert.match(config.degraded[0] ?? "", /TERA_AUTH_REVALIDATE_URL/);
});
it("demotes jwt with no secret and no JWKS", () => {
const config = loadConfig({ TERA_AUTH_MODE: "jwt" });
assert.equal(config.auth.mode, "none");
});
it("demotes dump1090 with no path to read", () => {
const config = loadConfig({ TERA_FLIGHTS_SOURCE: "dump1090" });
assert.equal(config.flights.source, "sim");
});
it("demotes a file marker source with no file", () => {
const config = loadConfig({ TERA_MARKERS_SOURCE: "file" });
assert.equal(config.markers.source, "none");
});
});
+80
View File
@@ -0,0 +1,80 @@
/**
* The provenance gate, which is the sharpest correction in CONTRACT.md and the
* one with an actual licence behind it.
*
* The row that must be refused is the one that looks completely fine: correct
* fields, plausible coordinates, and a provenance of `nominatim`. Serving it
* would make this endpoint a Publicly Used Derivative Database and pull ODbL
* §4.3 and §4.4 onto everything served next to it. See CONTRACT.md §8.
*/
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { DEFAULT_PROVENANCE_ALLOWLIST } from "../config.ts";
import { assertPublicShape } from "../markers/gate.ts";
const good = {
id: "acme-hq",
label: "Acme",
colorKey: "sector.industrial",
lat: 37.79,
lng: -122.4,
provenance: "us-census",
};
describe("the public-shape gate", () => {
it("accepts a US Census row", () => {
const { accepted, refused } = assertPublicShape([good], DEFAULT_PROVENANCE_ALLOWLIST);
assert.equal(accepted.length, 1);
assert.deepEqual(refused, []);
assert.equal(accepted[0]?.provenance, "us-census");
});
it("refuses an OSM-derived row that is otherwise perfect", () => {
const row = { ...good, provenance: "nominatim" };
const { accepted, refused } = assertPublicShape([row], DEFAULT_PROVENANCE_ALLOWLIST);
assert.equal(accepted.length, 0);
assert.equal(refused.length, 1);
assert.match(refused[0]?.reason ?? "", /allowlist/);
});
it("refuses a row with no provenance at all", () => {
const { provenance: _omitted, ...row } = good;
const { accepted } = assertPublicShape([row], DEFAULT_PROVENANCE_ALLOWLIST);
assert.equal(accepted.length, 0);
});
it("refuses commercial geocoders too — 'not OSM' is not the test", () => {
for (const provenance of ["google", "mapbox", "here"]) {
const { accepted } = assertPublicShape(
[{ ...good, provenance }],
DEFAULT_PROVENANCE_ALLOWLIST,
);
assert.equal(accepted.length, 0, `${provenance} must not pass`);
}
});
it("refuses the whole row when it carries a field nobody reviewed", () => {
const row = { ...good, ownerEmail: "someone@example.com" };
const { accepted, refused } = assertPublicShape([row], DEFAULT_PROVENANCE_ALLOWLIST);
assert.equal(accepted.length, 0);
assert.match(refused[0]?.reason ?? "", /unknown field "ownerEmail"/);
});
it("refuses malformed coordinates", () => {
const rows = [
{ ...good, lat: 200 },
{ ...good, lng: "west" },
{ ...good, id: "" },
];
const { accepted } = assertPublicShape(rows, DEFAULT_PROVENANCE_ALLOWLIST);
assert.equal(accepted.length, 0);
});
it("aggregates refusals so a broken sync is one line, not ten thousand", () => {
const rows = Array.from({ length: 500 }, () => ({ ...good, provenance: "osm" }));
const { refused } = assertPublicShape(rows, DEFAULT_PROVENANCE_ALLOWLIST);
assert.equal(refused.length, 1);
assert.equal(refused[0]?.count, 500);
});
});
+149
View File
@@ -0,0 +1,149 @@
/**
* Offices, visibility, and the 404 rule.
*
* The assertion that matters is the negative one: a private office and an office
* that was never created must be indistinguishable from outside. If they differ
* — by status code, by body, by timing anybody could measure — the endpoint
* becomes a way to enumerate tenants. CONTRACT.md §6.
*
* HS256 is exercised directly here because it is the primary path: the issuer
* this runs against signs `{"alg":"HS256"}`, and a JWKS-only implementation
* would reject every real token.
*/
import assert from "node:assert/strict";
import { createHmac } from "node:crypto";
import { mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, describe, it } from "node:test";
import { buildApp } from "../app.ts";
import { loadConfig } from "../config.ts";
import type { OfficeDoc } from "../../../src/server/wire.ts";
const SECRET = "not-a-real-secret-and-never-was";
/** A minimal floor. `Plan` is what makes sense of it; the API only carries it. */
const floor = { id: "hq", name: "HQ", levels: [], viewpoints: [] };
let dir = "";
before(async () => {
dir = await mkdtemp(join(tmpdir(), "tera-offices-"));
await writeFile(
join(dir, "open.json"),
JSON.stringify({ id: "open", name: "Open office", visibility: "public", floor }),
);
await writeFile(
join(dir, "closed.json"),
JSON.stringify({ id: "closed", name: "Closed office", visibility: "private", floor }),
);
await writeFile(
join(dir, "quiet.json"),
JSON.stringify({ id: "quiet", name: "Unlisted office", visibility: "unlisted", floor }),
);
// No `visibility` at all: the fail-closed reading is `private`.
await writeFile(join(dir, "vague.json"), JSON.stringify({ id: "vague", name: "?", floor }));
});
function appWith(env: Record<string, string>) {
const config = loadConfig({ TERA_OFFICES_DIR: dir, ...env });
config.logLevel = "silent";
return buildApp(config);
}
function hs256(claims: Record<string, unknown>): string {
const encode = (value: unknown): string =>
Buffer.from(JSON.stringify(value)).toString("base64url");
const signed = `${encode({ alg: "HS256", typ: "JWT" })}.${encode(claims)}`;
return `${signed}.${createHmac("sha256", SECRET).update(signed).digest("base64url")}`;
}
describe("with auth off", () => {
it("serves a public office and lets it be cached", async () => {
const app = appWith({});
after(() => app.close());
const res = await app.inject({ method: "GET", url: "/api/v1/offices/open" });
assert.equal(res.statusCode, 200);
assert.equal(res.json<OfficeDoc>().floor.id, "hq");
assert.match(String(res.headers["cache-control"]), /^public, max-age=/);
});
it("serves an unlisted office but never lets a shared cache keep it", async () => {
const app = appWith({});
after(() => app.close());
const res = await app.inject({ method: "GET", url: "/api/v1/offices/quiet" });
assert.equal(res.statusCode, 200);
assert.equal(res.headers["cache-control"], "private, no-store");
});
it("answers 404 for a private office, identically to one that does not exist", async () => {
const app = appWith({});
after(() => app.close());
const priv = await app.inject({ method: "GET", url: "/api/v1/offices/closed" });
const absent = await app.inject({ method: "GET", url: "/api/v1/offices/no-such-office" });
assert.equal(priv.statusCode, 404);
assert.equal(absent.statusCode, 404);
assert.deepEqual(priv.json(), absent.json());
});
it("treats a pack that forgot to declare visibility as private", async () => {
const app = appWith({});
after(() => app.close());
assert.equal((await app.inject({ method: "GET", url: "/api/v1/offices/vague" })).statusCode, 404);
});
it("refuses an id that could climb out of the directory", async () => {
const app = appWith({});
after(() => app.close());
for (const id of ["..", "..%2f..%2fetc%2fpasswd", "Open", "open.json"]) {
const res = await app.inject({ method: "GET", url: `/api/v1/offices/${id}` });
assert.equal(res.statusCode, 404, `${id} must not resolve`);
}
});
});
describe("with TERA_AUTH_MODE=jwt", () => {
const env = { TERA_AUTH_MODE: "jwt", TERA_AUTH_JWT_SECRET: SECRET };
it("opens a private office to a valid HS256 token", async () => {
const app = appWith(env);
after(() => app.close());
const res = await app.inject({
method: "GET",
url: "/api/v1/offices/closed",
headers: { authorization: `Bearer ${hs256({ sub: "someone", exp: now() + 600 })}` },
});
assert.equal(res.statusCode, 200);
assert.equal(res.headers["cache-control"], "private, no-store");
});
it("still answers 404 to an expired token, a wrong secret, or alg: none", async () => {
const app = appWith(env);
after(() => app.close());
const expired = hs256({ sub: "someone", exp: now() - 3600 });
const wrong = `${hs256({ sub: "someone" }).split(".").slice(0, 2).join(".")}.deadbeef`;
const none = `${Buffer.from(JSON.stringify({ alg: "none" })).toString("base64url")}.${Buffer.from(
JSON.stringify({ sub: "someone" }),
).toString("base64url")}.`;
for (const token of [expired, wrong, none, "not-a-jwt"]) {
const res = await app.inject({
method: "GET",
url: "/api/v1/offices/closed",
headers: { authorization: `Bearer ${token}` },
});
assert.equal(res.statusCode, 404);
}
});
});
function now(): number {
return Math.floor(Date.now() / 1000);
}