Public: anyone can read this; the crew can change it.

The profit slider's position: one number per forge, and the pure function from position to policy #529

Closed opened this
Closed without merging

torque/forge:torque/504-the-profit-slider-s-position-one-number → main 4 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
16 files changed +1015 −7
forge.json +1 −1
@@ -6,7 +6,7 @@
66 "ready": 90
77 },
88 "check": {
9 "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 test/crew.test.ts test/crew-wrapup.test.ts test/crew-limits.test.ts test/crew-sandbox.test.ts test/steer.test.ts test/landing.test.ts test/decide.test.ts test/ledger.test.ts test/checks.test.ts test/dependencies.test.ts test/autonomy.test.ts test/studio.test.ts test/studio-words.test.ts test/forks.test.ts test/fork-flow.test.ts test/cross-repo-pull.test.ts test/pulls.test.ts test/apps.test.ts test/apps-adversarial.test.ts test/apps-busy.test.ts test/apps-token.test.ts test/web.test.ts test/git-trust.test.ts test/helpers.test.ts test/shards.test.ts test/migrate.test.ts test/vitals.test.ts test/asks.test.ts test/feed.test.ts test/feed-page.test.ts test/offline.test.ts test/share.test.ts test/cloud.test.ts test/run-secrets.test.ts test/forge-cloudflare.test.ts test/usage.test.ts test/standing.test.ts test/board-windows.test.ts test/spawn-plan.test.ts test/spawn.test.ts test/web-apps.test.ts test/fleet-ops.test.ts",
9 "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 crew.test.ts crew-wrapup.test.ts crew-limits.test.ts crew-sandbox.test.ts steer.test.ts landing.test.ts decide.test.ts ledger.test.ts checks.test.ts dependencies.test.ts autonomy.test.ts studio.test.ts studio-words.test.ts forks.test.ts fork-flow.test.ts cross-repo-pull.test.ts pulls.test.ts apps.test.ts apps-adversarial.test.ts apps-busy.test.ts apps-token.test.ts web.test.ts git-trust.test.ts helpers.test.ts shards.test.ts migrate.test.ts vitals.test.ts asks.test.ts feed.test.ts feed-page.test.ts offline.test.ts share.test.ts cloud.test.ts run-secrets.test.ts forge-cloudflare.test.ts usage.test.ts standing.test.ts board-windows.test.ts spawn-plan.test.ts spawn.test.ts web-apps.test.ts fleet-ops.test.ts slider.test.ts",
1010 "timeout": 1800
1111 }
1212 }
scripts/shards.ts +10
@@ -79,6 +79,16 @@ export function splitFiles(
7979 /** How a test file is named: the same rule `scripts/test-shards.ts` uses. */
8080 export const TEST_FILE = /\.test\.[cm]?[jt]sx?$/;
8181
82 /**
83 * Where a named test file is, from the repository root. A bare name is one
84 * in `test/` (bunfig's test root), so `forge.json` can name `crew.test.ts`
85 * and `check.run` stays under the manifest's 1000 characters as the suite
86 * grows; a name with a directory in it is taken as given.
87 */
88 export function testPath(name: string): string {
89 return name.includes("/") ? name : `test/${name}`;
90 }
91
8292 /** A sane bound on one entry of the times table: a day, in seconds. */
8393 const TIME_MAX = 86_400;
8494
scripts/test-shards.ts +3 −2
@@ -5,7 +5,7 @@
55 * bun scripts/test-shards.ts --record [bun test flags…] test/a.test.ts …
66 *
77 * The files come from the command line, so `forge.json`'s `check.run`
8 * stays the one place that names them. Each shard is its own `bun test`
8 * stays the one place that names them; a bare name is one in `test/`. Each shard is its own `bun test`
99 * over a disjoint slice (`scripts/shards.ts` decides the slices); a
1010 * shard's output is written through whole when it finishes, so the log
1111 * reads one shard at a time, and the tail names every failing test from
@@ -27,6 +27,7 @@ import {
2727 shardCount,
2828 splitFiles,
2929 tally,
30 testPath,
3031 weigher,
3132 type ShardResult,
3233 } from "./shards.ts";
@@ -36,7 +37,7 @@ const TIMES = new URL("./test-times.json", import.meta.url).pathname;
3637 const argv = process.argv.slice(2);
3738 const record = argv.includes("--record");
3839 const args = argv.filter((arg) => arg !== "--record");
39 const files = args.filter((arg) => TEST_FILE.test(arg));
40 const files = args.filter((arg) => TEST_FILE.test(arg)).map(testPath);
4041 const flags = args.filter((arg) => !TEST_FILE.test(arg));
4142
4243 if (files.length === 0) {
src/actions/economics.ts added +82
@@ -0,0 +1,82 @@
1 /**
2 * The forge's economics, as its admins reach them: the profit slider's
3 * position and the margin (docs/PROFIT.md). A forge admin reads and sets
4 * them; anyone else is told `not_found`, never that the door exists. A
5 * change is an event for admins (`forge.economics_updated`) carrying both
6 * numbers, before and after, so the outbox says who moved the slider.
7 */
8
9 import type { App } from "../app.ts";
10 import {
11 getEconomics,
12 setEconomics,
13 type Economics,
14 } from "../core/economics.ts";
15 import {
16 parseMarginPct,
17 parsePosition,
18 policyAt,
19 policyWords,
20 type Policy,
21 } from "../core/slider.ts";
22 import type { User } from "../core/users.ts";
23 import { err, ok, type Result } from "../kernel/result.ts";
24
25 export interface EconomicsView extends Economics {
26 readonly policy: Policy;
27 /** The policy in words, as Settings → Economics shows it. */
28 readonly words: string;
29 }
30
31 export type EconomicsError = "not_found" | "invalid_position" | "invalid_margin";
32
33 export const ECONOMICS_MESSAGES: Record<EconomicsError, string> = {
34 not_found: "Not found.",
35 invalid_position: "The position is a whole number from 0 to 100.",
36 invalid_margin: "The margin is a whole percent from 0 to 500.",
37 };
38
39 export function economicsView(e: Economics): EconomicsView {
40 const policy = policyAt(e.position);
41 return { ...e, policy, words: policyWords(policy) };
42 }
43
44 export function readEconomics(
45 app: App,
46 actor: User | undefined,
47 ): Result<EconomicsView, "not_found"> {
48 if (!actor?.isAdmin) return err("not_found");
49 return ok(economicsView(getEconomics(app.db)));
50 }
51
52 /**
53 * Set either number or both; one left out (`undefined`) keeps its value.
54 * One given but not whole and in range refuses the whole change.
55 */
56 export function updateEconomics(
57 app: App,
58 actor: User | undefined,
59 input: { readonly position?: unknown; readonly marginPct?: unknown },
60 ): Result<EconomicsView, EconomicsError> {
61 if (!actor?.isAdmin) return err("not_found");
62 const before = getEconomics(app.db);
63 const position =
64 input.position === undefined
65 ? before.position
66 : parsePosition(input.position);
67 if (position === undefined) return err("invalid_position");
68 const marginPct =
69 input.marginPct === undefined
70 ? before.marginPct
71 : parseMarginPct(input.marginPct);
72 if (marginPct === undefined) return err("invalid_margin");
73 const next = { position, marginPct };
74 setEconomics(app.db, next);
75 if (position !== before.position || marginPct !== before.marginPct)
76 app.bus.append({
77 kind: "forge.economics_updated",
78 actorId: actor.id,
79 payload: { before, after: next },
80 });
81 return ok(economicsView(next));
82 }
src/apps/runtime.ts +7 −1
@@ -119,7 +119,13 @@ export type EnvState =
119119 | "asleep"
120120 | "failed";
121121
122 const SLEEP_AFTER_MS = { production: 24 * 3_600_000, preview: 30 * 60_000 };
122 /** Idle windows before an environment sleeps: the profit slider's 50 (`core/slider.ts`). */
123 export const SLEEP_AFTER_MS = {
124 production: 24 * 3_600_000,
125 preview: 30 * 60_000,
126 };
127 /** Days a quiet pull keeps its preview by default: the slider's 50 too. */
128 export const IDLE_PULL_DAYS = 3;
123129 const SWEEP_EVERY_MS = 60_000;
124130 const BUSY_GRACE_MS = 45 * 60_000;
125131
src/core/economics.ts added +55
@@ -0,0 +1,55 @@
1 /**
2 * The forge's economics: the profit slider's `position` and the margin on
3 * crew spend, kept in `forge_setting` one key per row (docs/PROFIT.md).
4 * Read back through the same parsers that guard the boundary, so a row a
5 * hand edited into nonsense reads as its default, never as a policy.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import {
10 MARGIN_DEFAULT,
11 parseMarginPct,
12 parsePosition,
13 POSITION_DEFAULT,
14 } from "./slider.ts";
15
16 export interface Economics {
17 /** 0 cheapest … 100 most responsive (`core/slider.ts`). */
18 readonly position: number;
19 /** Whole percent added to crew spend when it is billed, 0–500. */
20 readonly marginPct: number;
21 }
22
23 const POSITION = "economics.position";
24 const MARGIN = "economics.margin_pct";
25
26 export function getEconomics(db: Database): Economics {
27 const rows = db
28 .query<
29 { key: string; value: string },
30 [string, string]
31 >("SELECT key, value FROM forge_setting WHERE key IN (?1, ?2)")
32 .all(POSITION, MARGIN);
33 const value = (key: string): string | undefined =>
34 rows.find((r) => r.key === key)?.value;
35 return {
36 position: parsePosition(value(POSITION)) ?? POSITION_DEFAULT,
37 marginPct: parseMarginPct(value(MARGIN)) ?? MARGIN_DEFAULT,
38 };
39 }
40
41 /** Both numbers at once; false (and nothing written) if either is not whole and in range. */
42 export function setEconomics(db: Database, next: Economics): boolean {
43 const position = parsePosition(next.position);
44 const marginPct = parseMarginPct(next.marginPct);
45 if (position === undefined || marginPct === undefined) return false;
46 const put = db.query(
47 `INSERT INTO forge_setting (key, value) VALUES (?1, ?2)
48 ON CONFLICT (key) DO UPDATE SET value = excluded.value`,
49 );
50 db.transaction(() => {
51 put.run(POSITION, String(position));
52 put.run(MARGIN, String(marginPct));
53 })();
54 return true;
55 }
src/core/event_audience.ts +1
@@ -28,6 +28,7 @@ export function eventAudience(kind: string): EventAudience {
2828 kind.startsWith("app.domain.") ||
2929 kind.startsWith("prompt.") ||
3030 kind.startsWith("secret.") ||
31 kind.startsWith("forge.") ||
3132 kind === "repo.settings_updated"
3233 )
3334 return "admins";
src/core/schema.ts +41
@@ -1081,4 +1081,45 @@ export const migrations: readonly string[] = [
10811081 PRIMARY KEY (operation_id, position)
10821082 );
10831083 `,
1084 // 41 — forge-wide settings, one key per row (`core/economics.ts`): the
1085 // profit slider's position and the margin on crew spend. A missing key is
1086 // its default, so an empty table is today's forge.
1087 //
1088 // Written to survive one ordering accident: for a while this migration
1089 // was numbered 40, and a preview's database migrated then has
1090 // `forge_setting` at 40 and never ran the fleet receipt. So all three are
1091 // created only if missing — a no-op everywhere 40 was the receipt, the
1092 // repair where it was not. The receipt DDL is migration 40's, verbatim.
1093 `
1094 CREATE TABLE IF NOT EXISTS fleet_operation (
1095 id TEXT PRIMARY KEY,
1096 actor_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
1097 query TEXT NOT NULL,
1098 kind TEXT NOT NULL CHECK (kind IN ('repo','run','issue')),
1099 verb TEXT NOT NULL,
1100 value TEXT NOT NULL,
1101 reversible INTEGER NOT NULL,
1102 undo_of TEXT,
1103 undone_by TEXT,
1104 created_at TEXT NOT NULL
1105 );
1106 CREATE INDEX IF NOT EXISTS fleet_operation_actor ON fleet_operation(actor_id, id);
1107 CREATE TABLE IF NOT EXISTS fleet_operation_row (
1108 operation_id TEXT NOT NULL REFERENCES fleet_operation(id) ON DELETE CASCADE,
1109 position INTEGER NOT NULL,
1110 target_id TEXT NOT NULL,
1111 repo_id TEXT NOT NULL,
1112 label TEXT NOT NULL,
1113 before TEXT NOT NULL,
1114 after TEXT NOT NULL,
1115 outcome TEXT NOT NULL
1116 CHECK (outcome IN ('ok','failed','refused','unchanged')),
1117 reason TEXT NOT NULL DEFAULT '',
1118 PRIMARY KEY (operation_id, position)
1119 );
1120 CREATE TABLE IF NOT EXISTS forge_setting (
1121 key TEXT PRIMARY KEY,
1122 value TEXT NOT NULL
1123 );
1124 `,
10841125 ];
src/core/slider.ts added +161
@@ -0,0 +1,161 @@
1 /**
2 * The profit slider's policy: one forge-wide `position` (an integer 0–100)
3 * and the pure function from it to the windows and threshold it means
4 * (docs/PROFIT.md). 0 is cheapest — sleep early, cloud only when owned
5 * metal is full; 100 is most responsive — stay warm, spill to cloud early.
6 * 50 is today's behaviour exactly, so landing this changes nothing.
7 *
8 * Plain data in, plain data out: nothing here reads the database or acts.
9 */
10
11 const MIN = 60_000;
12 const HOUR = 60 * MIN;
13 const DAY = 24 * HOUR;
14
15 export const POSITION_MIN = 0;
16 export const POSITION_MAX = 100;
17 export const POSITION_DEFAULT = 50;
18 export const MARGIN_MAX = 500;
19 export const MARGIN_DEFAULT = 0;
20
21 /**
22 * "Never" stands in for infinity in the interpolation: above 50 a window
23 * that is "never" at 100 climbs toward this cap, and only 100 itself is
24 * `null` (docs/PROFIT.md, "The control").
25 */
26 export const NEVER_CAP_MS = 7 * DAY;
27
28 export interface Policy {
29 /** Idle milliseconds before an environment sleeps; `null` is never. */
30 readonly sleepAfterMs: {
31 readonly production: number | null;
32 readonly preview: number | null;
33 };
34 /** Idle milliseconds before a quiet pull's preview stops; `null` is never. */
35 readonly idlePullMs: number | null;
36 /** Share of owned capacity in use (0–1) above which cloud takes work. */
37 readonly spillAtOwnedUse: number;
38 }
39
40 interface Anchor {
41 readonly production: number | null;
42 readonly preview: number | null;
43 readonly idlePull: number | null;
44 /** Whole percent, so the arithmetic stays exact until the last step. */
45 readonly spillPct: number;
46 }
47
48 /** The three rows of docs/PROFIT.md; 50 is `SLEEP_AFTER_MS` and `IDLE_PULL_DAYS`. */
49 const ANCHORS: readonly [Anchor, Anchor, Anchor] = [
50 { production: 10 * MIN, preview: 5 * MIN, idlePull: 1 * DAY, spillPct: 100 },
51 { production: 24 * HOUR, preview: 30 * MIN, idlePull: 3 * DAY, spillPct: 85 },
52 { production: null, preview: 24 * HOUR, idlePull: null, spillPct: 60 },
53 ];
54
55 /** a + (b − a)·t, with "never" read as the cap; whole milliseconds. */
56 function lerpMs(a: number | null, b: number | null, t: number): number | null {
57 if (t === 1 && b === null) return null;
58 if (t === 0 && a === null) return null;
59 const from = a ?? NEVER_CAP_MS;
60 const to = b ?? NEVER_CAP_MS;
61 return Math.round(from + (to - from) * t);
62 }
63
64 /**
65 * The policy a position means: linear between the anchor at or below it and
66 * the one above. A position outside 0–100 or not whole is a programmer's
67 * mistake — the boundary (`parsePosition`) refuses it first — so it is
68 * clamped and rounded rather than trusted.
69 */
70 export function policyAt(position: number): Policy {
71 const p = Number.isFinite(position)
72 ? Math.min(POSITION_MAX, Math.max(POSITION_MIN, Math.round(position)))
73 : POSITION_DEFAULT;
74 const upper = p > 50;
75 const lo = upper ? ANCHORS[1] : ANCHORS[0];
76 const hi = upper ? ANCHORS[2] : ANCHORS[1];
77 const t = (upper ? p - 50 : p) / 50;
78 // Percent to one decimal (the interpolation steps by 0.3 % or 0.5 %), then
79 // a share: 72.5 % is 0.725.
80 const pct = lo.spillPct + (hi.spillPct - lo.spillPct) * t;
81 return {
82 sleepAfterMs: {
83 production: lerpMs(lo.production, hi.production, t),
84 preview: lerpMs(lo.preview, hi.preview, t),
85 },
86 idlePullMs: lerpMs(lo.idlePull, hi.idlePull, t),
87 spillAtOwnedUse: Math.round(pct * 10) / 1000,
88 };
89 }
90
91 /**
92 * A whole number in [min, max] from a form field or a JSON value; undefined
93 * for anything else — fractions, signs, exponents, blanks, booleans, null.
94 */
95 function wholeIn(input: unknown, min: number, max: number): number | undefined {
96 let n: number;
97 if (typeof input === "number") n = input;
98 else if (typeof input === "string" && /^\d{1,4}$/.test(input.trim()))
99 n = Number(input.trim());
100 else return undefined;
101 return Number.isInteger(n) && n >= min && n <= max ? n : undefined;
102 }
103
104 export const parsePosition = (input: unknown): number | undefined =>
105 wholeIn(input, POSITION_MIN, POSITION_MAX);
106
107 export const parseMarginPct = (input: unknown): number | undefined =>
108 wholeIn(input, 0, MARGIN_MAX);
109
110 /** "24 h", "12 h 5 min", "17 min 30 s", "4 days": the two largest units. */
111 export function duration(ms: number): string {
112 const s = Math.round(ms / 1000);
113 const parts: [number, string][] =
114 s >= 48 * 3600
115 ? [
116 [Math.floor(s / 86_400), "days"],
117 [Math.floor((s % 86_400) / 3600), "h"],
118 ]
119 : s >= 3600
120 ? [
121 [Math.floor(s / 3600), "h"],
122 [Math.floor((s % 3600) / 60), "min"],
123 ]
124 : s >= 60
125 ? [
126 [Math.floor(s / 60), "min"],
127 [s % 60, "s"],
128 ]
129 : [[s, "s"]];
130 return parts
131 .filter(([n], i) => i === 0 || n > 0)
132 .map(([n, unit]) => `${n} ${unit}`)
133 .join(" ");
134 }
135
136 function percent(share: number): string {
137 return `${Math.round(share * 1000) / 10}%`;
138 }
139
140 /**
141 * The policy in words, one clause per lever:
142 * "production sleeps after 24 h idle · previews after 30 min · cloud takes
143 * work above 85% of owned capacity · a quiet pull's preview stops after 3 days".
144 */
145 export function policyWords(policy: Policy): string {
146 const { production, preview } = policy.sleepAfterMs;
147 return [
148 production === null
149 ? "production never sleeps"
150 : `production sleeps after ${duration(production)} idle`,
151 preview === null
152 ? "previews never sleep"
153 : `previews after ${duration(preview)}`,
154 policy.spillAtOwnedUse >= 1
155 ? "cloud takes work only when owned capacity is full"
156 : `cloud takes work above ${percent(policy.spillAtOwnedUse)} of owned capacity`,
157 policy.idlePullMs === null
158 ? "a quiet pull's preview never stops"
159 : `a quiet pull's preview stops after ${duration(policy.idlePullMs)}`,
160 ].join(" · ");
161 }
src/http/api.ts +34
@@ -8,6 +8,11 @@
88 * back to continue); errors are `{ error, message }`.
99 */
1010
11 import {
12 ECONOMICS_MESSAGES,
13 readEconomics,
14 updateEconomics,
15 } from "../actions/economics.ts";
1116 import { listSecrets, putSecret, removeSecret } from "../actions/secrets.ts";
1217 import { proposeUpstream } from "../actions/upstream.ts";
1318 import { relationOf, syncFork, takeUpdates } from "../actions/forks.ts";
@@ -3110,6 +3115,35 @@ export function apiRoutes(router: Router<Handler>): void {
31103115 return json({}, 200);
31113116 });
31123117
3118 // The forge's economics: the profit slider's position, the margin, and
3119 // the policy the position means (docs/PROFIT.md). A forge admin's; anyone
3120 // else gets a 404. PUT takes `position` and/or `marginPct`, whole numbers.
3121 router.add("GET", "/api/v1/forge/economics", (ctx) => {
3122 const denied = requireScope(ctx, "ro");
3123 if (denied) return denied;
3124 const read = readEconomics(ctx.app, ctx.auth.user);
3125 if (!read.ok) return notFound();
3126 return json(read.value);
3127 });
3128
3129 router.add("PUT", "/api/v1/forge/economics", async (ctx) => {
3130 const denied = requireScope(ctx, "admin");
3131 if (denied) return denied;
3132 const input = await body(ctx.request);
3133 const set = updateEconomics(ctx.app, ctx.auth.user, {
3134 position: input.position,
3135 marginPct: input.marginPct,
3136 });
3137 if (!set.ok)
3138 return set.error === "not_found"
3139 ? notFound()
3140 : json(
3141 { error: set.error, message: ECONOMICS_MESSAGES[set.error] },
3142 422,
3143 );
3144 return json(set.value);
3145 });
3146
31133147 // The app's environment: names in, names out, and never a value back.
31143148 // `:var`, not `:name` — `:name` is the repository's.
31153149 router.add("GET", "/api/v1/repos/:owner/:name/app/env", (ctx) => {
src/http/server.ts +3
@@ -61,6 +61,7 @@ import {
6161 cloudVerify,
6262 cloudWrite,
6363 } from "../web/pages/cloud.ts";
64 import { economicsPage, economicsUpdate } from "../web/pages/economics.ts";
6465 import {
6566 subscriptionAdd,
6667 subscriptionDelete,
@@ -508,6 +509,8 @@ export function buildRouter(): Router<Handler> {
508509 router.add("POST", "/settings/cloud/write", cloudWrite);
509510 router.add("POST", "/settings/cloud/audit", cloudAudit);
510511 router.add("POST", "/settings/cloud/remove", cloudRemove);
512 router.add("GET", "/settings/economics", economicsPage);
513 router.add("POST", "/settings/economics", economicsUpdate);
511514 router.add("GET", "/settings/backups", backupsPage);
512515 router.add("POST", "/settings/backups/now", backupsNow);
513516 router.add("POST", "/settings/backups/destination", backupsDestination);
src/main.ts +2 −2
@@ -12,7 +12,7 @@ import { isHookName, runHookClient } from "./git/hooks.ts";
1212 import { serve } from "./http/server.ts";
1313 import { runSync } from "./origins/sync.ts";
1414 import { startForgeSsh } from "./tui/ssh.ts";
15 import { AppsRuntime } from "./apps/runtime.ts";
15 import { AppsRuntime, IDLE_PULL_DAYS } from "./apps/runtime.ts";
1616 import { resolveAppDomain } from "./apps/host.ts";
1717 import { requeueAbandonedChecks, startChecks } from "./checks/service.ts";
1818 import { startLooks } from "./looks/service.ts";
@@ -153,7 +153,7 @@ const apps = appDomain?.ok
153153 busyGraceMs: crewRunMs,
154154 // Days a pull may sit untouched before its preview sleeps; 0 keeps
155155 // every preview warm.
156 idlePullMs: nonNegative(process.env.FORGE_PREVIEW_IDLE_DAYS, 3) * 86_400_000,
156 idlePullMs: nonNegative(process.env.FORGE_PREVIEW_IDLE_DAYS, IDLE_PULL_DAYS) * 86_400_000,
157157 })
158158 : undefined;
159159 await apps?.start();
src/web/pages/economics.ts added +168
@@ -0,0 +1,168 @@
1 /**
2 * Economics, for a forge admin: the profit slider's position and the margin
3 * on crew spend (docs/PROFIT.md), with the policy the position means
4 * written out beside it. Server-rendered and usable without script: the
5 * table under the slider shows what the ticks mean before anything moves.
6 * Nothing acts on the position yet — the runtime keeps its own constants,
7 * which are what 50 says.
8 */
9
10 import {
11 ECONOMICS_MESSAGES,
12 readEconomics,
13 updateEconomics,
14 type EconomicsView,
15 } from "../../actions/economics.ts";
16 import {
17 MARGIN_MAX,
18 POSITION_MAX,
19 POSITION_MIN,
20 policyAt,
21 policyWords,
22 } from "../../core/slider.ts";
23 import type { Ctx } from "../../http/context.ts";
24 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
25 import { field, readForm } from "../form.ts";
26 import { html, raw, type Html } from "../html.ts";
27 import { flashTo, page } from "../layout.ts";
28 import { btn, card, icon } from "../ui.ts";
29 import { accountSections } from "./origins.ts";
30
31 const BACK = "/settings/economics";
32 const TICKS = [0, 25, 50, 75, 100] as const;
33
34 function requireAdmin(ctx: Ctx): Response | undefined {
35 if (!ctx.auth.user) return signInFirst(ctx);
36 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
37 return undefined;
38 }
39
40 function sliderCard(e: EconomicsView): Html {
41 return card(
42 html`<form method="post" action="${BACK}" class="stack">
43 <p class="muted small">
44 One control for the whole forge. 0 is cheapest: apps sleep early and
45 cloud takes work only when owned machines are full. 100 is most
46 responsive: apps stay warm and cloud takes work early. 50 is how the
47 forge has always run. Nothing acts on this yet — it is the number the
48 sleep windows and placement will read.
49 </p>
50 <label for="economics-position"
51 ><strong>Position</strong>
52 <span class="mono">${String(e.position)}</span>
53 <span class="muted">of ${String(POSITION_MAX)}</span></label
54 >
55 <input
56 id="economics-position"
57 type="range"
58 name="position"
59 min="${String(POSITION_MIN)}"
60 max="${String(POSITION_MAX)}"
61 step="1"
62 value="${String(e.position)}"
63 list="economics-ticks"
64 aria-describedby="economics-words"
65 />
66 <datalist id="economics-ticks">
67 ${TICKS.map((t) => html`<option value="${String(t)}"></option>`)}
68 </datalist>
69 <p id="economics-words">${e.words}</p>
70 <label for="economics-margin"
71 ><strong>Margin on crew spend</strong>
72 <span class="muted">— whole percent, 0 to ${String(MARGIN_MAX)};
73 it sets price, not cost, and does not move with the slider</span></label
74 >
75 <input
76 id="economics-margin"
77 class="input mono"
78 type="number"
79 name="marginPct"
80 min="0"
81 max="${String(MARGIN_MAX)}"
82 step="1"
83 inputmode="numeric"
84 value="${String(e.marginPct)}"
85 required
86 />
87 <div>${btn("Save", { variant: "primary", size: "sm", icon: "check" })}</div>
88 </form>`,
89 {
90 head: html`${icon("activity")}
91 <h2>Economics</h2>`,
92 },
93 );
94 }
95
96 /** What each tick means, so a position can be chosen before it is saved. */
97 function ticksCard(current: number): Html {
98 return card(
99 html`<div class="table-scroll">
100 <table class="table" data-dense>
101 <thead>
102 <tr>
103 <th>Position</th>
104 <th>Policy</th>
105 </tr>
106 </thead>
107 <tbody>
108 ${TICKS.map(
109 (t) =>
110 html`<tr ${t === current ? raw('aria-current="true"') : null}>
111 <td class="mono">${String(t)}${t === current ? " · now" : ""}</td>
112 <td>${policyWords(policyAt(t))}</td>
113 </tr>`,
114 )}
115 </tbody>
116 </table>
117 <p class="muted small card-body">
118 Between ticks every window moves in a straight line. “Never” counts
119 as 7 days on the way there, so 99 still sleeps; only 100 never does.
120 </p>
121 </div>`,
122 {
123 head: html`${icon("map")}
124 <h2>What the positions mean</h2>`,
125 pad: false,
126 },
127 );
128 }
129
130 // GET /settings/economics
131 export function economicsPage(ctx: Ctx): Response {
132 const denied = requireAdmin(ctx);
133 if (denied) return denied;
134 const read = readEconomics(ctx.app, ctx.auth.user);
135 if (!read.ok) return notFoundPage(ctx);
136 return page({
137 ctx,
138 title: "Economics",
139 body: html`<div class="page-head"><h1>Economics</h1></div>
140 ${settingsLayout(
141 accountSections("economics", { admin: true }),
142 html`${sliderCard(read.value)}
143 <div class="mt">${ticksCard(read.value.position)}</div>`,
144 "Account settings",
145 )}`,
146 });
147 }
148
149 // POST /settings/economics
150 export async function economicsUpdate(ctx: Ctx): Promise<Response> {
151 const denied = requireAdmin(ctx);
152 if (denied) return denied;
153 const form = await readForm(ctx, "admin");
154 if (form instanceof Response) return form;
155 const set = updateEconomics(ctx.app, ctx.auth.user, {
156 position: field(form, "position"),
157 marginPct: field(form, "marginPct"),
158 });
159 return flashTo(
160 ctx,
161 BACK,
162 set.ok
163 ? {
164 message: `Position ${set.value.position}: ${set.value.words}.`,
165 }
166 : { tone: "danger", message: ECONOMICS_MESSAGES[set.error] },
167 );
168 }
src/web/pages/origins.ts +8 −1
@@ -71,7 +71,8 @@ export type AccountSection =
7171 | "subscriptions"
7272 | "backups"
7373 | "secrets"
74 | "cloud";
74 | "cloud"
75 | "economics";
7576
7677 /**
7778 * The settings sidebar, with Origins on it. Kept here so the account pages
@@ -110,6 +111,12 @@ export function accountSections(
110111 icon: "key" as const,
111112 current: current === "cloud",
112113 },
114 {
115 label: "Economics",
116 href: "/settings/economics",
117 icon: "activity" as const,
118 current: current === "economics",
119 },
113120 {
114121 label: "Backups",
115122 href: "/settings/backups",
test/shards.test.ts +28
@@ -13,9 +13,11 @@ import {
1313 shardCount,
1414 splitFiles,
1515 tally,
16 testPath,
1617 weigher,
1718 type ShardResult,
1819 } from "../scripts/shards.ts";
20 import { parseCheck } from "../src/apps/manifest.ts";
1921
2022 const files = Array.from({ length: 23 }, (_, i) => `test/f${i}.test.ts`);
2123
@@ -271,3 +273,29 @@ describe("tally", () => {
271273 );
272274 });
273275 });
276
277 describe("testPath", () => {
278 test("a bare name is in test/, a path is taken as given", () => {
279 expect(testPath("crew.test.ts")).toBe("test/crew.test.ts");
280 expect(testPath("test/crew.test.ts")).toBe("test/crew.test.ts");
281 expect(testPath("./other/x.test.ts")).toBe("./other/x.test.ts");
282 });
283
284 test("this repository's own check is one the forge accepts, naming files that exist", () => {
285 const json = readFileSync(
286 new URL("../forge.json", import.meta.url),
287 "utf8",
288 );
289 const check = parseCheck(json, undefined);
290 expect(check.ok).toBe(true);
291 if (!check.ok || check.value === undefined) return;
292 const named = check.value.run
293 .split(/\s+/)
294 .filter((arg) => /\.test\.ts$/.test(arg));
295 expect(named.length).toBeGreaterThan(0);
296 for (const name of named)
297 expect(
298 Bun.file(new URL(`../${testPath(name)}`, import.meta.url)).size,
299 ).toBeGreaterThan(0);
300 });
301 });
test/slider.test.ts added +411
@@ -0,0 +1,411 @@
1 /**
2 * The profit slider's position (#504): the pure policy, its anchors worked
3 * by hand from docs/PROFIT.md, the forge-wide row, and the page and API that
4 * set it — admins only, whole numbers only, same-origin.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { IDLE_PULL_DAYS, SLEEP_AFTER_MS } from "../src/apps/runtime.ts";
13 import { getEconomics, setEconomics } from "../src/core/economics.ts";
14 import { eventAudience } from "../src/core/event_audience.ts";
15 import { migrations } from "../src/core/schema.ts";
16 import {
17 duration,
18 parseMarginPct,
19 parsePosition,
20 policyAt,
21 policyWords,
22 } from "../src/core/slider.ts";
23 import { createUser } from "../src/core/users.ts";
24 import { serve, type Servers } from "../src/http/server.ts";
25 import { openDb } from "../src/kernel/db.ts";
26 import { quietLogs } from "./helpers/globals.ts";
27
28 quietLogs();
29
30 const MIN = 60_000;
31 const HOUR = 60 * MIN;
32 const DAY = 24 * HOUR;
33
34 describe("policyAt", () => {
35 test("the three anchors are the rows of docs/PROFIT.md", () => {
36 expect(policyAt(0)).toEqual({
37 sleepAfterMs: { production: 10 * MIN, preview: 5 * MIN },
38 idlePullMs: 1 * DAY,
39 spillAtOwnedUse: 1,
40 });
41 expect(policyAt(50)).toEqual({
42 sleepAfterMs: { production: 86_400_000, preview: 1_800_000 },
43 idlePullMs: 259_200_000,
44 spillAtOwnedUse: 0.85,
45 });
46 expect(policyAt(100)).toEqual({
47 sleepAfterMs: { production: null, preview: 86_400_000 },
48 idlePullMs: null,
49 spillAtOwnedUse: 0.6,
50 });
51 });
52
53 test("50 is the runtime's constants today, so landing this changes nothing", () => {
54 const p = policyAt(50);
55 expect(p.sleepAfterMs.production).toBe(SLEEP_AFTER_MS.production);
56 expect(p.sleepAfterMs.preview).toBe(SLEEP_AFTER_MS.preview);
57 expect(p.idlePullMs).toBe(IDLE_PULL_DAYS * DAY);
58 });
59
60 test("25 is halfway between 0 and 50, worked by hand", () => {
61 // production: 600 000 + (86 400 000 − 600 000) / 2 = 43 500 000 (12 h 5 min)
62 // preview: 300 000 + (1 800 000 − 300 000) / 2 = 1 050 000 (17 min 30 s)
63 // idle pull: 1 d + (3 d − 1 d) / 2 = 2 d
64 // spill: 100 % + (85 % − 100 %) / 2 = 92.5 %
65 expect(policyAt(25)).toEqual({
66 sleepAfterMs: { production: 43_500_000, preview: 1_050_000 },
67 idlePullMs: 2 * DAY,
68 spillAtOwnedUse: 0.925,
69 });
70 });
71
72 test("75 is halfway between 50 and 100, with never read as 7 days", () => {
73 // production: 24 h + (7 d − 24 h) / 2 = 4 d = 345 600 000
74 // preview: 30 min + (24 h − 30 min) / 2 = 12 h 15 min = 44 100 000
75 // idle pull: 3 d + (7 d − 3 d) / 2 = 5 d
76 // spill: 85 % + (60 % − 85 %) / 2 = 72.5 %
77 expect(policyAt(75)).toEqual({
78 sleepAfterMs: { production: 345_600_000, preview: 44_100_000 },
79 idlePullMs: 5 * DAY,
80 spillAtOwnedUse: 0.725,
81 });
82 });
83
84 test("99 still sleeps; only 100 never does", () => {
85 // 24 h + (7 d − 24 h) × 0.98 = 86 400 000 + 508 032 000
86 expect(policyAt(99).sleepAfterMs.production).toBe(594_432_000);
87 expect(policyAt(99).idlePullMs).not.toBeNull();
88 });
89
90 test("every window grows and the spill line falls as the position rises", () => {
91 for (let p = 1; p < 100; p++) {
92 const a = policyAt(p - 1);
93 const b = policyAt(p);
94 expect(b.sleepAfterMs.production!).toBeGreaterThan(
95 a.sleepAfterMs.production!,
96 );
97 expect(b.sleepAfterMs.preview!).toBeGreaterThan(a.sleepAfterMs.preview!);
98 expect(b.spillAtOwnedUse).toBeLessThan(a.spillAtOwnedUse);
99 }
100 });
101 });
102
103 describe("the policy in words", () => {
104 test("50 reads as the issue says it should", () => {
105 expect(policyWords(policyAt(50))).toBe(
106 "production sleeps after 24 h idle · previews after 30 min · cloud takes work above 85% of owned capacity · a quiet pull's preview stops after 3 days",
107 );
108 });
109
110 test("the ends say never and full", () => {
111 expect(policyWords(policyAt(100))).toBe(
112 "production never sleeps · previews after 24 h · cloud takes work above 60% of owned capacity · a quiet pull's preview never stops",
113 );
114 expect(policyWords(policyAt(0))).toContain(
115 "cloud takes work only when owned capacity is full",
116 );
117 });
118
119 test("durations keep the two largest units", () => {
120 expect(duration(43_500_000)).toBe("12 h 5 min");
121 expect(duration(1_050_000)).toBe("17 min 30 s");
122 expect(duration(345_600_000)).toBe("4 days");
123 expect(duration(44_100_000)).toBe("12 h 15 min");
124 expect(duration(5 * MIN)).toBe("5 min");
125 });
126 });
127
128 describe("parsing a position at the boundary", () => {
129 test("whole numbers 0–100, as a number or as digits", () => {
130 expect(parsePosition(0)).toBe(0);
131 expect(parsePosition(100)).toBe(100);
132 expect(parsePosition("42")).toBe(42);
133 expect(parsePosition(" 7 ")).toBe(7);
134 });
135
136 test("out of range, fractional and non-numeric are refused", () => {
137 for (const bad of [
138 -1,
139 101,
140 "101",
141 "-1",
142 50.5,
143 "50.5",
144 "1e2",
145 "0x10",
146 "abc",
147 "",
148 " ",
149 NaN,
150 Infinity,
151 true,
152 null,
153 undefined,
154 [50],
155 { position: 50 },
156 ])
157 expect(parsePosition(bad)).toBeUndefined();
158 });
159
160 test("the margin is a whole percent 0–500", () => {
161 expect(parseMarginPct(0)).toBe(0);
162 expect(parseMarginPct("500")).toBe(500);
163 expect(parseMarginPct(501)).toBeUndefined();
164 expect(parseMarginPct(12.5)).toBeUndefined();
165 expect(parseMarginPct("ten")).toBeUndefined();
166 });
167 });
168
169 describe("the forge's economics, stored and set", () => {
170 let dataDir = "";
171 let app: App;
172 let servers: Servers;
173 let adminToken = "";
174 let bobToken = "";
175
176 const mint = async (username: string): Promise<string> =>
177 (
178 (await (
179 await fetch(`${servers.url}/api/v1/tokens`, {
180 method: "POST",
181 headers: { "content-type": "application/json" },
182 body: JSON.stringify({
183 username,
184 password: "a-good-passphrase",
185 name: "t",
186 scope: "admin",
187 }),
188 })
189 ).json()) as { token: string }
190 ).token;
191 const api = (path: string, init: RequestInit = {}, token = adminToken) =>
192 fetch(`${servers.url}${path}`, {
193 ...init,
194 headers: {
195 authorization: `Bearer ${token}`,
196 "content-type": "application/json",
197 },
198 });
199 const put = (body: unknown, token = adminToken) =>
200 api(
201 "/api/v1/forge/economics",
202 { method: "PUT", body: JSON.stringify(body) },
203 token,
204 );
205 const login = async (username: string): Promise<string> => {
206 const res = await fetch(`${servers.url}/signin`, {
207 method: "POST",
208 redirect: "manual",
209 headers: {
210 "content-type": "application/x-www-form-urlencoded",
211 origin: servers.url,
212 },
213 body: new URLSearchParams({ username, password: "a-good-passphrase" }),
214 });
215 return (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
216 };
217 const post = (cookie: string, fields: Record<string, string>, origin: string) =>
218 fetch(`${servers.url}/settings/economics`, {
219 method: "POST",
220 redirect: "manual",
221 headers: {
222 cookie,
223 "content-type": "application/x-www-form-urlencoded",
224 origin,
225 },
226 body: new URLSearchParams(fields),
227 });
228
229 beforeAll(async () => {
230 dataDir = await mkdtemp(join(tmpdir(), "forge-slider-"));
231 app = createApp({ dataDir, port: 0 });
232 servers = await serve(app);
233 for (const [username, adminIfFirst] of [
234 ["alice", true],
235 ["bob", false],
236 ] as const) {
237 const made = await createUser(app.db, {
238 username,
239 email: `${username}@forge.test`,
240 password: "a-good-passphrase",
241 adminIfFirst,
242 });
243 if (!made.ok) throw new Error(made.error);
244 }
245 adminToken = await mint("alice");
246 bobToken = await mint("bob");
247 });
248
249 afterAll(async () => {
250 servers.stop();
251 app.close();
252 await rm(dataDir, { recursive: true, force: true });
253 });
254
255 test("an empty table is position 50 and no margin", () => {
256 expect(getEconomics(app.db)).toEqual({ position: 50, marginPct: 0 });
257 });
258
259 test("the store refuses what the boundary would, and reads garbage as the default", () => {
260 expect(setEconomics(app.db, { position: 50.5, marginPct: 0 })).toBe(false);
261 expect(setEconomics(app.db, { position: 50, marginPct: 501 })).toBe(false);
262 app.db
263 .query("INSERT INTO forge_setting (key, value) VALUES (?1, ?2)")
264 .run("economics.position", "lots");
265 expect(getEconomics(app.db).position).toBe(50);
266 app.db.query("DELETE FROM forge_setting").run();
267 });
268
269 test("the API reads the position and the policy it means", async () => {
270 const res = await api("/api/v1/forge/economics");
271 expect(res.status).toBe(200);
272 const got = (await res.json()) as Record<string, unknown>;
273 expect(got.position).toBe(50);
274 expect(got.marginPct).toBe(0);
275 expect(got.policy).toEqual(policyAt(50) as unknown as Record<string, unknown>);
276 expect(got.words).toBe(policyWords(policyAt(50)));
277 });
278
279 test("only a forge admin reads or sets it; anyone else is told nothing exists", async () => {
280 expect((await api("/api/v1/forge/economics", {}, bobToken)).status).toBe(404);
281 expect((await put({ position: 0 }, bobToken)).status).toBe(404);
282 expect(
283 (await fetch(`${servers.url}/api/v1/forge/economics`)).status,
284 ).toBe(401);
285 expect(getEconomics(app.db).position).toBe(50);
286 });
287
288 test("PUT sets whole numbers and refuses the rest, changing nothing", async () => {
289 const ok = await put({ position: 75, marginPct: 20 });
290 expect(ok.status).toBe(200);
291 const body = (await ok.json()) as { position: number; policy: unknown };
292 expect(body.position).toBe(75);
293 expect(body.policy).toEqual(policyAt(75));
294 expect(getEconomics(app.db)).toEqual({ position: 75, marginPct: 20 });
295
296 for (const bad of [
297 { position: 101 },
298 { position: -1 },
299 { position: 12.5 },
300 { position: "lots" },
301 { position: null },
302 { position: true },
303 { position: 10, marginPct: 501 },
304 { position: 10, marginPct: 2.5 },
305 ]) {
306 const res = await put(bad);
307 expect(res.status).toBe(422);
308 expect(((await res.json()) as { error: string }).error).toMatch(
309 /^invalid_(position|margin)$/,
310 );
311 }
312 expect(getEconomics(app.db)).toEqual({ position: 75, marginPct: 20 });
313
314 // One left out keeps its value.
315 expect((await put({ marginPct: 5 })).status).toBe(200);
316 expect(getEconomics(app.db)).toEqual({ position: 75, marginPct: 5 });
317 });
318
319 test("a change is an event, for admins only", () => {
320 const row = app.db
321 .query<{ payload: string; actor_id: string }, []>(
322 "SELECT payload, actor_id FROM event WHERE kind = 'forge.economics_updated' ORDER BY created_at DESC, rowid DESC LIMIT 1",
323 )
324 .get()!;
325 expect(JSON.parse(row.payload)).toEqual({
326 before: { position: 75, marginPct: 20 },
327 after: { position: 75, marginPct: 5 },
328 });
329 expect(eventAudience("forge.economics_updated")).toBe("admins");
330 });
331
332 test("Settings → Economics: the slider and its words, admins only, same-origin", async () => {
333 const alice = await login("alice");
334 const page = await (
335 await fetch(`${servers.url}/settings/economics`, {
336 headers: { cookie: alice },
337 })
338 ).text();
339 expect(page).toContain('type="range"');
340 expect(page).toContain('name="position"');
341 expect(page).toContain('value="75"');
342 // Escaped like every output: the apostrophe in "pull's" is an entity.
343 expect(page).toContain(
344 policyWords(policyAt(75)).replace("'", "&#39;"),
345 );
346 expect(page).toContain('href="/settings/economics"');
347
348 const bob = await login("bob");
349 expect(
350 (
351 await fetch(`${servers.url}/settings/economics`, {
352 headers: { cookie: bob },
353 })
354 ).status,
355 ).toBe(404);
356 expect(
357 (await post(bob, { position: "0", marginPct: "0" }, servers.url)).status,
358 ).toBe(404);
359
360 const cross = await post(
361 alice,
362 { position: "0", marginPct: "0" },
363 "http://evil.test",
364 );
365 expect(cross.status).toBe(403);
366 expect(getEconomics(app.db).position).toBe(75);
367
368 const bad = await post(alice, { position: "50.5", marginPct: "0" }, servers.url);
369 expect(bad.status).toBe(303);
370 expect(getEconomics(app.db).position).toBe(75);
371
372 const set = await post(alice, { position: "25", marginPct: "10" }, servers.url);
373 expect(set.status).toBe(303);
374 expect(getEconomics(app.db)).toEqual({ position: 25, marginPct: 10 });
375 });
376 });
377
378 describe("the settings migration", () => {
379 test("repairs a database that took forge_setting as migration 40 and never ran the fleet receipt", async () => {
380 const dir = await mkdtemp(join(tmpdir(), "forge-slider-mig-"));
381 try {
382 const path = join(dir, "forge.db");
383 // What pull #520's preview migrated before the renumbering holds:
384 // 1–39, then forge_setting alone as 40 — no fleet_operation table.
385 const settings = migrations[40]!.slice(
386 migrations[40]!.indexOf("CREATE TABLE IF NOT EXISTS forge_setting"),
387 );
388 const before = openDb(path, [...migrations.slice(0, 39), settings]);
389 const has = (db: typeof before, name: string): boolean =>
390 db
391 .query<{ n: number }, [string]>(
392 "SELECT COUNT(*) AS n FROM sqlite_master WHERE type = 'table' AND name = ?1",
393 )
394 .get(name)!.n === 1;
395 setEconomics(before, { position: 70, marginPct: 5 });
396 expect(has(before, "forge_setting")).toBe(true);
397 expect(has(before, "fleet_operation")).toBe(false);
398 before.close();
399 // Today's list boots it: 40 is skipped as applied, 41 fills the gap
400 // and keeps the row the preview already had.
401 const after = openDb(path, migrations);
402 expect(has(after, "forge_setting")).toBe(true);
403 expect(has(after, "fleet_operation")).toBe(true);
404 expect(has(after, "fleet_operation_row")).toBe(true);
405 expect(getEconomics(after)).toEqual({ position: 70, marginPct: 5 });
406 after.close();
407 } finally {
408 await rm(dir, { recursive: true, force: true });
409 }
410 });
411 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs