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 #520

Closed opened this
Closed without merging

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

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
13 files changed +905 −5
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 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 test/slider.test.ts",
1010 "timeout": 1800
1111 }
1212 }
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 +9
@@ -1081,4 +1081,13 @@ 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 CREATE TABLE forge_setting (
1089 key TEXT PRIMARY KEY,
1090 value TEXT NOT NULL
1091 );
1092 `,
10841093 ];
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/slider.test.ts added +374
@@ -0,0 +1,374 @@
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 {
16 duration,
17 parseMarginPct,
18 parsePosition,
19 policyAt,
20 policyWords,
21 } from "../src/core/slider.ts";
22 import { createUser } from "../src/core/users.ts";
23 import { serve, type Servers } from "../src/http/server.ts";
24 import { quietLogs } from "./helpers/globals.ts";
25
26 quietLogs();
27
28 const MIN = 60_000;
29 const HOUR = 60 * MIN;
30 const DAY = 24 * HOUR;
31
32 describe("policyAt", () => {
33 test("the three anchors are the rows of docs/PROFIT.md", () => {
34 expect(policyAt(0)).toEqual({
35 sleepAfterMs: { production: 10 * MIN, preview: 5 * MIN },
36 idlePullMs: 1 * DAY,
37 spillAtOwnedUse: 1,
38 });
39 expect(policyAt(50)).toEqual({
40 sleepAfterMs: { production: 86_400_000, preview: 1_800_000 },
41 idlePullMs: 259_200_000,
42 spillAtOwnedUse: 0.85,
43 });
44 expect(policyAt(100)).toEqual({
45 sleepAfterMs: { production: null, preview: 86_400_000 },
46 idlePullMs: null,
47 spillAtOwnedUse: 0.6,
48 });
49 });
50
51 test("50 is the runtime's constants today, so landing this changes nothing", () => {
52 const p = policyAt(50);
53 expect(p.sleepAfterMs.production).toBe(SLEEP_AFTER_MS.production);
54 expect(p.sleepAfterMs.preview).toBe(SLEEP_AFTER_MS.preview);
55 expect(p.idlePullMs).toBe(IDLE_PULL_DAYS * DAY);
56 });
57
58 test("25 is halfway between 0 and 50, worked by hand", () => {
59 // production: 600 000 + (86 400 000 − 600 000) / 2 = 43 500 000 (12 h 5 min)
60 // preview: 300 000 + (1 800 000 − 300 000) / 2 = 1 050 000 (17 min 30 s)
61 // idle pull: 1 d + (3 d − 1 d) / 2 = 2 d
62 // spill: 100 % + (85 % − 100 %) / 2 = 92.5 %
63 expect(policyAt(25)).toEqual({
64 sleepAfterMs: { production: 43_500_000, preview: 1_050_000 },
65 idlePullMs: 2 * DAY,
66 spillAtOwnedUse: 0.925,
67 });
68 });
69
70 test("75 is halfway between 50 and 100, with never read as 7 days", () => {
71 // production: 24 h + (7 d − 24 h) / 2 = 4 d = 345 600 000
72 // preview: 30 min + (24 h − 30 min) / 2 = 12 h 15 min = 44 100 000
73 // idle pull: 3 d + (7 d − 3 d) / 2 = 5 d
74 // spill: 85 % + (60 % − 85 %) / 2 = 72.5 %
75 expect(policyAt(75)).toEqual({
76 sleepAfterMs: { production: 345_600_000, preview: 44_100_000 },
77 idlePullMs: 5 * DAY,
78 spillAtOwnedUse: 0.725,
79 });
80 });
81
82 test("99 still sleeps; only 100 never does", () => {
83 // 24 h + (7 d − 24 h) × 0.98 = 86 400 000 + 508 032 000
84 expect(policyAt(99).sleepAfterMs.production).toBe(594_432_000);
85 expect(policyAt(99).idlePullMs).not.toBeNull();
86 });
87
88 test("every window grows and the spill line falls as the position rises", () => {
89 for (let p = 1; p < 100; p++) {
90 const a = policyAt(p - 1);
91 const b = policyAt(p);
92 expect(b.sleepAfterMs.production!).toBeGreaterThan(
93 a.sleepAfterMs.production!,
94 );
95 expect(b.sleepAfterMs.preview!).toBeGreaterThan(a.sleepAfterMs.preview!);
96 expect(b.spillAtOwnedUse).toBeLessThan(a.spillAtOwnedUse);
97 }
98 });
99 });
100
101 describe("the policy in words", () => {
102 test("50 reads as the issue says it should", () => {
103 expect(policyWords(policyAt(50))).toBe(
104 "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",
105 );
106 });
107
108 test("the ends say never and full", () => {
109 expect(policyWords(policyAt(100))).toBe(
110 "production never sleeps · previews after 24 h · cloud takes work above 60% of owned capacity · a quiet pull's preview never stops",
111 );
112 expect(policyWords(policyAt(0))).toContain(
113 "cloud takes work only when owned capacity is full",
114 );
115 });
116
117 test("durations keep the two largest units", () => {
118 expect(duration(43_500_000)).toBe("12 h 5 min");
119 expect(duration(1_050_000)).toBe("17 min 30 s");
120 expect(duration(345_600_000)).toBe("4 days");
121 expect(duration(44_100_000)).toBe("12 h 15 min");
122 expect(duration(5 * MIN)).toBe("5 min");
123 });
124 });
125
126 describe("parsing a position at the boundary", () => {
127 test("whole numbers 0–100, as a number or as digits", () => {
128 expect(parsePosition(0)).toBe(0);
129 expect(parsePosition(100)).toBe(100);
130 expect(parsePosition("42")).toBe(42);
131 expect(parsePosition(" 7 ")).toBe(7);
132 });
133
134 test("out of range, fractional and non-numeric are refused", () => {
135 for (const bad of [
136 -1,
137 101,
138 "101",
139 "-1",
140 50.5,
141 "50.5",
142 "1e2",
143 "0x10",
144 "abc",
145 "",
146 " ",
147 NaN,
148 Infinity,
149 true,
150 null,
151 undefined,
152 [50],
153 { position: 50 },
154 ])
155 expect(parsePosition(bad)).toBeUndefined();
156 });
157
158 test("the margin is a whole percent 0–500", () => {
159 expect(parseMarginPct(0)).toBe(0);
160 expect(parseMarginPct("500")).toBe(500);
161 expect(parseMarginPct(501)).toBeUndefined();
162 expect(parseMarginPct(12.5)).toBeUndefined();
163 expect(parseMarginPct("ten")).toBeUndefined();
164 });
165 });
166
167 describe("the forge's economics, stored and set", () => {
168 let dataDir = "";
169 let app: App;
170 let servers: Servers;
171 let adminToken = "";
172 let bobToken = "";
173
174 const mint = async (username: string): Promise<string> =>
175 (
176 (await (
177 await fetch(`${servers.url}/api/v1/tokens`, {
178 method: "POST",
179 headers: { "content-type": "application/json" },
180 body: JSON.stringify({
181 username,
182 password: "a-good-passphrase",
183 name: "t",
184 scope: "admin",
185 }),
186 })
187 ).json()) as { token: string }
188 ).token;
189 const api = (path: string, init: RequestInit = {}, token = adminToken) =>
190 fetch(`${servers.url}${path}`, {
191 ...init,
192 headers: {
193 authorization: `Bearer ${token}`,
194 "content-type": "application/json",
195 },
196 });
197 const put = (body: unknown, token = adminToken) =>
198 api(
199 "/api/v1/forge/economics",
200 { method: "PUT", body: JSON.stringify(body) },
201 token,
202 );
203 const login = async (username: string): Promise<string> => {
204 const res = await fetch(`${servers.url}/signin`, {
205 method: "POST",
206 redirect: "manual",
207 headers: {
208 "content-type": "application/x-www-form-urlencoded",
209 origin: servers.url,
210 },
211 body: new URLSearchParams({ username, password: "a-good-passphrase" }),
212 });
213 return (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
214 };
215 const post = (cookie: string, fields: Record<string, string>, origin: string) =>
216 fetch(`${servers.url}/settings/economics`, {
217 method: "POST",
218 redirect: "manual",
219 headers: {
220 cookie,
221 "content-type": "application/x-www-form-urlencoded",
222 origin,
223 },
224 body: new URLSearchParams(fields),
225 });
226
227 beforeAll(async () => {
228 dataDir = await mkdtemp(join(tmpdir(), "forge-slider-"));
229 app = createApp({ dataDir, port: 0 });
230 servers = await serve(app);
231 for (const [username, adminIfFirst] of [
232 ["alice", true],
233 ["bob", false],
234 ] as const) {
235 const made = await createUser(app.db, {
236 username,
237 email: `${username}@forge.test`,
238 password: "a-good-passphrase",
239 adminIfFirst,
240 });
241 if (!made.ok) throw new Error(made.error);
242 }
243 adminToken = await mint("alice");
244 bobToken = await mint("bob");
245 });
246
247 afterAll(async () => {
248 servers.stop();
249 app.close();
250 await rm(dataDir, { recursive: true, force: true });
251 });
252
253 test("an empty table is position 50 and no margin", () => {
254 expect(getEconomics(app.db)).toEqual({ position: 50, marginPct: 0 });
255 });
256
257 test("the store refuses what the boundary would, and reads garbage as the default", () => {
258 expect(setEconomics(app.db, { position: 50.5, marginPct: 0 })).toBe(false);
259 expect(setEconomics(app.db, { position: 50, marginPct: 501 })).toBe(false);
260 app.db
261 .query("INSERT INTO forge_setting (key, value) VALUES (?1, ?2)")
262 .run("economics.position", "lots");
263 expect(getEconomics(app.db).position).toBe(50);
264 app.db.query("DELETE FROM forge_setting").run();
265 });
266
267 test("the API reads the position and the policy it means", async () => {
268 const res = await api("/api/v1/forge/economics");
269 expect(res.status).toBe(200);
270 const got = (await res.json()) as Record<string, unknown>;
271 expect(got.position).toBe(50);
272 expect(got.marginPct).toBe(0);
273 expect(got.policy).toEqual(policyAt(50) as unknown as Record<string, unknown>);
274 expect(got.words).toBe(policyWords(policyAt(50)));
275 });
276
277 test("only a forge admin reads or sets it; anyone else is told nothing exists", async () => {
278 expect((await api("/api/v1/forge/economics", {}, bobToken)).status).toBe(404);
279 expect((await put({ position: 0 }, bobToken)).status).toBe(404);
280 expect(
281 (await fetch(`${servers.url}/api/v1/forge/economics`)).status,
282 ).toBe(401);
283 expect(getEconomics(app.db).position).toBe(50);
284 });
285
286 test("PUT sets whole numbers and refuses the rest, changing nothing", async () => {
287 const ok = await put({ position: 75, marginPct: 20 });
288 expect(ok.status).toBe(200);
289 const body = (await ok.json()) as { position: number; policy: unknown };
290 expect(body.position).toBe(75);
291 expect(body.policy).toEqual(policyAt(75));
292 expect(getEconomics(app.db)).toEqual({ position: 75, marginPct: 20 });
293
294 for (const bad of [
295 { position: 101 },
296 { position: -1 },
297 { position: 12.5 },
298 { position: "lots" },
299 { position: null },
300 { position: true },
301 { position: 10, marginPct: 501 },
302 { position: 10, marginPct: 2.5 },
303 ]) {
304 const res = await put(bad);
305 expect(res.status).toBe(422);
306 expect(((await res.json()) as { error: string }).error).toMatch(
307 /^invalid_(position|margin)$/,
308 );
309 }
310 expect(getEconomics(app.db)).toEqual({ position: 75, marginPct: 20 });
311
312 // One left out keeps its value.
313 expect((await put({ marginPct: 5 })).status).toBe(200);
314 expect(getEconomics(app.db)).toEqual({ position: 75, marginPct: 5 });
315 });
316
317 test("a change is an event, for admins only", () => {
318 const row = app.db
319 .query<{ payload: string; actor_id: string }, []>(
320 "SELECT payload, actor_id FROM event WHERE kind = 'forge.economics_updated' ORDER BY created_at DESC, rowid DESC LIMIT 1",
321 )
322 .get()!;
323 expect(JSON.parse(row.payload)).toEqual({
324 before: { position: 75, marginPct: 20 },
325 after: { position: 75, marginPct: 5 },
326 });
327 expect(eventAudience("forge.economics_updated")).toBe("admins");
328 });
329
330 test("Settings → Economics: the slider and its words, admins only, same-origin", async () => {
331 const alice = await login("alice");
332 const page = await (
333 await fetch(`${servers.url}/settings/economics`, {
334 headers: { cookie: alice },
335 })
336 ).text();
337 expect(page).toContain('type="range"');
338 expect(page).toContain('name="position"');
339 expect(page).toContain('value="75"');
340 // Escaped like every output: the apostrophe in "pull's" is an entity.
341 expect(page).toContain(
342 policyWords(policyAt(75)).replace("'", "&#39;"),
343 );
344 expect(page).toContain('href="/settings/economics"');
345
346 const bob = await login("bob");
347 expect(
348 (
349 await fetch(`${servers.url}/settings/economics`, {
350 headers: { cookie: bob },
351 })
352 ).status,
353 ).toBe(404);
354 expect(
355 (await post(bob, { position: "0", marginPct: "0" }, servers.url)).status,
356 ).toBe(404);
357
358 const cross = await post(
359 alice,
360 { position: "0", marginPct: "0" },
361 "http://evil.test",
362 );
363 expect(cross.status).toBe(403);
364 expect(getEconomics(app.db).position).toBe(75);
365
366 const bad = await post(alice, { position: "50.5", marginPct: "0" }, servers.url);
367 expect(bad.status).toBe(303);
368 expect(getEconomics(app.db).position).toBe(75);
369
370 const set = await post(alice, { position: "25", marginPct: "10" }, servers.url);
371 expect(set.status).toBe(303);
372 expect(getEconomics(app.db)).toEqual({ position: 25, marginPct: 10 });
373 });
374 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs