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

Adapter app shape: sync an external system into the forge, with a contract the forge can audit #459

Closed opened this
Closed without merging

scout/forge:scout/437-adapter-app-shape-sync-an-external-syste → main 5 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
25 files changed +1586 −5
docs/ADAPTERS.md added +85
@@ -0,0 +1,85 @@
1 # Adapters
2
3 An **adapter** is an app that syncs one external system into the forge's
4 world. Bringing an old system in used to mean custom pull code per system,
5 each an ad-hoc app; an adapter gives it one shape the forge can schedule,
6 inspect and audit, and an agent can write by copying
7 [`examples/adapter-template`](../examples/adapter-template) and filling in
8 the source. (`docs/APPS.md` says what an app is; this says what an adapter
9 adds.)
10
11 ## The declaration
12
13 `forge.json` gains an optional `adapter` block, validated at the boundary in
14 `src/apps/adapter.ts` and failing the deploy, with the field named, when it
15 is wrong:
16
17 ```json
18 "adapter": {
19 "source": { "name": "ledger", "hosts": ["api.ledger.example"] },
20 "schedule": { "every": 900 },
21 "config": {
22 "account": { "type": "string", "default": "main" },
23 "token": { "type": "secret", "ref": "LEDGER_TOKEN" }
24 }
25 }
26 ```
27
28 - `source.name` — lowercase letters, digits, `-`, `_`. `source.hosts` — one
29 to eight bare lowercase host names (no scheme, port, path or wildcard):
30 the only hosts the adapter may reach.
31 - `schedule.every` — seconds between pulls, 10 to 604800.
32 - `config` — named, typed fields: `string`, `number`, `boolean` (each with
33 an optional `default`) or `secret`. **A secret is a reference**: `ref`
34 names an environment variable the operator sets, sealed, in the app's
35 environment settings. A secret with a value in `forge.json` is refused.
36 A non-secret field is read from the environment variable of its upper-cased
37 name, else its `default`.
38
39 ## The contract
40
41 The adapter serves `POST /pull`. The forge sends no body and the header
42 `x-forge-pull: 1`; the adapter must refuse a request without it, and any
43 with an `Origin` (a browser page), so nobody can pull by link.
44
45 It answers `200` with
46
47 ```json
48 { "pulled": 3, "skipped": 2, "cursor": "evt_9041", "errors": [] }
49 ```
50
51 `pulled` is records newly written, `skipped` records already held, `cursor`
52 a single line of at most 200 characters, `errors` a list of messages (or a
53 count). The forge validates this answer; anything else is a failed pull.
54
55 - **Idempotent.** The same cursor gives the same result, and a replay writes
56 nothing new: records are keyed by the source's own id and a held one is
57 skipped. A crash between pages repeats work and writes nothing twice.
58 - **State under `FORGE_APP_DATA`.** The cursor and the records, in one
59 SQLite file, moved together in one transaction. Nothing else is written.
60 - **Failure holds the cursor.** A failing pull reports `errors` and leaves
61 the cursor where the last whole page ended.
62 - **Only the declared hosts.** Every outbound request goes through one
63 guarded fetch that refuses any URL whose host is not in `source.hosts`
64 (and any non-`https`, credentialed or redirected one). The forge cannot
65 intercept a child's network; the guard is the adapter's half, proven by a
66 test the template carries, and the declaration is what an auditor reads.
67
68 ## What the forge does
69
70 `src/apps/pull.ts` calls `/pull` on the schedule for the **production**
71 environment (previews hold a copy of production's data; a second sync of the
72 same source would race it) and records each call as a `pull` run: state
73 (`failed` when the call fails, answers badly, or reports errors), the
74 one-line summary, and the counts, cursor and duration. The schedule is read
75 from those runs — next pull is the last one's start plus `every` — so a
76 restart neither forgets nor doubles one, a failed pull waits out its interval
77 like any other, and one pull per app runs at a time. A pull the last forge
78 left running is failed on boot. The app page shows last pull, next pull and
79 cursor.
80
81 ## Not here
82
83 Any real external system (each is its own adapter), a manual "pull now"
84 button, backoff beyond the interval, and enforcing the host list on the
85 child's network — that needs the placement seam (`docs/SPAWN.md`).
docs/APPS.md +3
@@ -36,6 +36,9 @@ primitives underneath; nobody gets a second system.
3636 is granted access the way a person is (collaborator or team), and its
3737 name appears on the pull it opened.
3838 - **Crew** — the agents with write access to a repository.
39 - **Adapter** — an app whose `forge.json` has an `adapter` block: it syncs
40 one external system, the forge calls its `POST /pull` on a schedule and
41 records each pull as a `pull` run. `docs/ADAPTERS.md` is its contract.
3942
4043 ## Rules that are mechanical
4144
docs/CONTRACT.md +8
@@ -254,3 +254,11 @@ Two more places the table reaches, so it is never only a page:
254254 something enforces them, not before.
255255 - Identities beyond `user` and `admin`. The forge signs one role today; the
256256 evaluator already takes a list.
257
258 ## An adapter's contract
259
260 An adapter app (`docs/ADAPTERS.md`) is audited against a different, smaller
261 contract: `POST /pull` is idempotent, state stays under `FORGE_APP_DATA`,
262 secrets are references, and outbound hosts are the declared source's. Each
263 pull is a run the forge records, so the audit reads what was pulled, when,
264 and where the cursor stands.
examples/adapter-template/README.md added +15
@@ -0,0 +1,15 @@
1 # adapter-template
2
3 Copy this directory, rename `source.name` in `forge.json`, and replace
4 `fetchPage` in `src/pull.ts` with your source's paging. The contract is in
5 [`docs/ADAPTERS.md`](../../docs/ADAPTERS.md): `POST /pull` answers
6 `{pulled, skipped, cursor, errors}`, is idempotent, and keeps its cursor and
7 records under `FORGE_APP_DATA` (`src/store.ts`).
8
9 - `src/source.ts` — the only door out: refuses any host not in `forge.json`.
10 - `src/config.ts` — reads the `adapter` block and the environment; the secret
11 is read from the variable its `ref` names and never printed.
12 - `src/pull.ts` — one pull. `src/server.ts` — `/pull`, `/`, `/healthz`.
13
14 Zero dependencies. `bun test` runs `test/adapter.test.ts`: replay writes
15 nothing, a failing source holds the cursor, another host is refused.
examples/adapter-template/forge.json added +17
@@ -0,0 +1,17 @@
1 {
2 "app": {
3 "run": "bun run src/server.ts",
4 "install": "",
5 "health": "/healthz",
6 "test": "bun test"
7 },
8 "adapter": {
9 "source": { "name": "example", "hosts": ["api.example.com"] },
10 "schedule": { "every": 900 },
11 "config": {
12 "base_url": { "type": "string", "default": "https://api.example.com/v1" },
13 "page_size": { "type": "number", "default": 100 },
14 "token": { "type": "secret", "ref": "EXAMPLE_TOKEN" }
15 }
16 }
17 }
examples/adapter-template/package.json added +6
@@ -0,0 +1,6 @@
1 {
2 "name": "adapter-template",
3 "private": true,
4 "type": "module",
5 "scripts": { "start": "bun run src/server.ts", "test": "bun test" }
6 }
examples/adapter-template/src/config.ts added +46
@@ -0,0 +1,46 @@
1 /**
2 * What this adapter was told: the `adapter` block of its own `forge.json`
3 * (the forge validated it at deploy; this reads only what it needs) and
4 * the operator's environment. A secret is read from the variable its `ref`
5 * names and is never logged, rendered or written to the data directory.
6 */
7
8 import { readFileSync } from "node:fs";
9 import { join } from "node:path";
10
11 export interface Config {
12 readonly source: string;
13 readonly hosts: readonly string[];
14 readonly baseUrl: string;
15 readonly pageSize: number;
16 readonly token: string;
17 }
18
19 type Field = { type?: string; ref?: string; default?: unknown };
20
21 export function loadConfig(
22 dir: string,
23 env: Record<string, string | undefined>,
24 ): Config {
25 const forge = JSON.parse(readFileSync(join(dir, "forge.json"), "utf8"));
26 const adapter = forge.adapter;
27 const fields: Record<string, Field> = adapter.config ?? {};
28 const text = (name: string): string => {
29 const field = fields[name];
30 const given = env[name.toUpperCase()];
31 return given !== undefined && given !== ""
32 ? given
33 : typeof field?.default === "string"
34 ? field.default
35 : "";
36 };
37 const size = Number(env["PAGE_SIZE"] ?? fields["page_size"]?.default ?? 100);
38 const secretRef = fields["token"]?.ref;
39 return {
40 source: String(adapter.source.name),
41 hosts: (adapter.source.hosts as unknown[]).map(String),
42 baseUrl: text("base_url"),
43 pageSize: Number.isInteger(size) && size > 0 && size <= 1000 ? size : 100,
44 token: secretRef === undefined ? "" : (env[secretRef] ?? ""),
45 };
46 }
examples/adapter-template/src/pull.ts added +77
@@ -0,0 +1,77 @@
1 /**
2 * One pull: read the cursor, fetch pages after it from the source, keep
3 * what is new, move the cursor. Idempotent by construction — the same
4 * cursor asks the source the same question, and a record already held is
5 * skipped, so a replay returns `pulled: 0` and writes nothing.
6 *
7 * The source contract this template assumes (replace `fetchPage` for a
8 * real one): `GET {base}/items?after=<cursor>&limit=<n>` answers
9 * `{ "items": [{ "id": "…", … }], "next": "<cursor>" | null }`.
10 */
11
12 import type { Config } from "./config.ts";
13 import type { Fetch } from "./source.ts";
14 import type { Item, Store } from "./store.ts";
15
16 export interface PullResult {
17 pulled: number;
18 skipped: number;
19 cursor: string;
20 errors: string[];
21 }
22
23 const MAX_PAGES = 20;
24
25 interface Page {
26 items: Item[];
27 next: string | null;
28 }
29
30 async function fetchPage(
31 fetchFrom: Fetch,
32 config: Config,
33 cursor: string,
34 ): Promise<Page> {
35 const url = `${config.baseUrl}/items?after=${encodeURIComponent(cursor)}&limit=${config.pageSize}`;
36 const res = await fetchFrom(url, {
37 headers: config.token ? { authorization: `Bearer ${config.token}` } : {},
38 });
39 if (!res.ok) throw new Error(`the source answered ${res.status}`);
40 const body: unknown = await res.json();
41 const list = (body as { items?: unknown })?.items;
42 if (!Array.isArray(list)) throw new Error("the source's items were not a list");
43 const items: Item[] = list.map((raw) => {
44 const id = (raw as { id?: unknown })?.id;
45 if (typeof id !== "string" || id === "" || id.length > 200)
46 throw new Error("a record had no usable id");
47 return { id, body: JSON.stringify(raw) };
48 });
49 const next = (body as { next?: unknown }).next;
50 return { items, next: typeof next === "string" && next.length <= 200 ? next : null };
51 }
52
53 /** Never throws: a failure is an entry in `errors` and the cursor stays put. */
54 export async function pull(
55 store: Store,
56 config: Config,
57 fetchFrom: Fetch,
58 ): Promise<PullResult> {
59 let cursor = store.cursor();
60 let pulled = 0;
61 let skipped = 0;
62 const errors: string[] = [];
63 for (let page = 0; page < MAX_PAGES; page++) {
64 try {
65 const got = await fetchPage(fetchFrom, config, cursor);
66 const added = store.keep(got.items, got.next ?? cursor);
67 pulled += added;
68 skipped += got.items.length - added;
69 if (got.next === null || got.next === cursor) break;
70 cursor = got.next;
71 } catch (error) {
72 errors.push(error instanceof Error ? error.message : "pull failed");
73 break;
74 }
75 }
76 return { pulled, skipped, cursor, errors };
77 }
examples/adapter-template/src/server.ts added +78
@@ -0,0 +1,78 @@
1 /**
2 * The adapter's one process: `POST /pull` (the forge's schedule calls it),
3 * `/` (a server-rendered look at the cursor and record count), `/healthz`.
4 * State lives under FORGE_APP_DATA. Zero dependencies.
5 */
6
7 import { loadConfig, type Config } from "./config.ts";
8 import { pull, type PullResult } from "./pull.ts";
9 import { guardedFetch, type Fetch } from "./source.ts";
10 import { Store } from "./store.ts";
11
12 const escape = (text: string): string =>
13 text.replace(
14 /[&<>"']/g,
15 (c) =>
16 ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]!,
17 );
18
19 const SECURITY = {
20 "content-security-policy":
21 "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
22 "x-content-type-options": "nosniff",
23 "referrer-policy": "no-referrer",
24 "cache-control": "no-store",
25 };
26
27 const reply = (body: string, type: string, status = 200): Response =>
28 new Response(body, {
29 status,
30 headers: { ...SECURITY, "content-type": `${type}; charset=utf-8` },
31 });
32 const json = (value: unknown, status = 200): Response =>
33 reply(JSON.stringify(value), "application/json", status);
34
35 export function makeHandler(store: Store, config: Config, fetchFrom: Fetch) {
36 let running: Promise<PullResult> | undefined;
37 return async (req: Request): Promise<Response> => {
38 const { pathname } = new URL(req.url);
39 if (pathname === "/healthz") return reply("ok", "text/plain");
40 if (pathname === "/") {
41 return reply(
42 `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>${escape(config.source)} adapter</title>
43 <h1>${escape(config.source)}</h1>
44 <p>${store.count()} records · cursor <code>${escape(store.cursor() || "none yet")}</code></p>`,
45 "text/html",
46 );
47 }
48 if (pathname === "/pull") {
49 if (req.method !== "POST") return json({ error: "method_not_allowed" }, 405);
50 // A mutation from a page in a browser carries an Origin; the forge's
51 // own schedule does not, and says so with a header a page cannot add.
52 if (req.headers.get("origin") !== null || req.headers.get("x-forge-pull") !== "1")
53 return json({ error: "forbidden" }, 403);
54 // One pull at a time: a second caller shares the first's answer.
55 running ??= pull(store, config, fetchFrom).finally(
56 () => (running = undefined),
57 );
58 return json(await running);
59 }
60 return json({ error: "not_found" }, 404);
61 };
62 }
63
64 if (import.meta.main) {
65 const dataDir = process.env["FORGE_APP_DATA"];
66 if (!dataDir) throw new Error("FORGE_APP_DATA is not set");
67 const config = loadConfig(import.meta.dir + "/..", process.env);
68 const handler = makeHandler(
69 new Store(dataDir),
70 config,
71 guardedFetch(config.hosts),
72 );
73 Bun.serve({
74 hostname: process.env["HOST"] ?? "127.0.0.1",
75 port: Number(process.env["PORT"] ?? 3000),
76 fetch: handler,
77 });
78 }
examples/adapter-template/src/source.ts added +51
@@ -0,0 +1,51 @@
1 /**
2 * The only door out. Every request this adapter makes goes through a fetch
3 * built here, which refuses any URL whose host is not one `forge.json`
4 * declares under `adapter.source.hosts` — and refuses redirects, so an
5 * allowed host cannot send a request on to one that is not.
6 */
7
8 export type Fetch = (url: string, init?: RequestInit) => Promise<Response>;
9
10 export class HostRefused extends Error {
11 constructor(readonly host: string) {
12 super(`outbound host not allowed: ${host}`);
13 }
14 }
15
16 /** `https` to exactly a declared host, no credentials in the URL. */
17 export function hostAllowed(hosts: readonly string[], url: string): boolean {
18 let parsed: URL;
19 try {
20 parsed = new URL(url);
21 } catch {
22 return false;
23 }
24 return (
25 parsed.protocol === "https:" &&
26 parsed.username === "" &&
27 parsed.password === "" &&
28 hosts.includes(parsed.hostname.toLowerCase())
29 );
30 }
31
32 /** Wrap a fetch (the real one, or a test's) so it can only reach `hosts`. */
33 export function guardedFetch(
34 hosts: readonly string[],
35 inner: Fetch = (url, init) => fetch(url, init),
36 ): Fetch {
37 return (url, init) => {
38 if (!hostAllowed(hosts, url)) {
39 let host = "unparseable";
40 try {
41 host = new URL(url).host;
42 } catch {}
43 return Promise.reject(new HostRefused(host));
44 }
45 return inner(url, {
46 ...init,
47 redirect: "error",
48 signal: init?.signal ?? AbortSignal.timeout(30_000),
49 });
50 };
51 }
examples/adapter-template/src/store.ts added +72
@@ -0,0 +1,72 @@
1 /**
2 * The adapter's state, one SQLite file under FORGE_APP_DATA: the records it
3 * has pulled, keyed by the source's own id, and the cursor. Records and the
4 * cursor move together in one transaction, so a crash leaves the cursor
5 * where the last whole page ended and the next pull repeats the rest — which
6 * writes nothing new, because a record already held is skipped.
7 */
8
9 import { Database } from "bun:sqlite";
10 import { mkdirSync } from "node:fs";
11 import { join } from "node:path";
12
13 export interface Item {
14 readonly id: string;
15 readonly body: string;
16 }
17
18 export class Store {
19 private readonly db: Database;
20
21 constructor(dataDir: string) {
22 if (dataDir !== ":memory:") mkdirSync(dataDir, { recursive: true });
23 this.db = new Database(
24 dataDir === ":memory:" ? ":memory:" : join(dataDir, "adapter.db"),
25 );
26 this.db.exec(`
27 PRAGMA journal_mode = WAL;
28 CREATE TABLE IF NOT EXISTS record (
29 id TEXT PRIMARY KEY, body TEXT NOT NULL,
30 pulled_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
31 );
32 CREATE TABLE IF NOT EXISTS state (key TEXT PRIMARY KEY, value TEXT NOT NULL);
33 `);
34 }
35
36 cursor(): string {
37 return (
38 this.db
39 .query<{ value: string }, []>(
40 "SELECT value FROM state WHERE key = 'cursor'",
41 )
42 .get()?.value ?? ""
43 );
44 }
45
46 count(): number {
47 return this.db
48 .query<{ n: number }, []>("SELECT COUNT(*) AS n FROM record")
49 .get()!.n;
50 }
51
52 /** Keep a page and move the cursor, atomically. Returns how many were new. */
53 keep(items: readonly Item[], cursor: string): number {
54 let added = 0;
55 this.db.transaction(() => {
56 const insert = this.db.query(
57 "INSERT OR IGNORE INTO record (id, body) VALUES (?1, ?2)",
58 );
59 for (const item of items) added += insert.run(item.id, item.body).changes;
60 this.db
61 .query(
62 "INSERT INTO state (key, value) VALUES ('cursor', ?1) ON CONFLICT(key) DO UPDATE SET value = ?1",
63 )
64 .run(cursor);
65 })();
66 return added;
67 }
68
69 close(): void {
70 this.db.close();
71 }
72 }
examples/adapter-template/test/adapter.test.ts added +138
@@ -0,0 +1,138 @@
1 import { describe, expect, test } from "bun:test";
2 import { loadConfig, type Config } from "../src/config.ts";
3 import { pull } from "../src/pull.ts";
4 import { makeHandler } from "../src/server.ts";
5 import { guardedFetch, HostRefused, type Fetch } from "../src/source.ts";
6 import { Store } from "../src/store.ts";
7
8 const config: Config = {
9 source: "example",
10 hosts: ["api.example.com"],
11 baseUrl: "https://api.example.com/v1",
12 pageSize: 2,
13 token: "s3cret",
14 };
15
16 /** A source of five records, two to a page, cursor = last id served. */
17 const ids = ["a", "b", "c", "d", "e"];
18 const source: Fetch & { calls: string[] } = Object.assign(
19 async (url: string) => {
20 source.calls.push(url);
21 const after = new URL(url).searchParams.get("after") ?? "";
22 const from = after === "" ? 0 : ids.indexOf(after) + 1;
23 const items = ids.slice(from, from + 2).map((id) => ({ id, n: id }));
24 const last = items.at(-1)?.id;
25 return Response.json({ items, next: last ?? null });
26 },
27 { calls: [] as string[] },
28 );
29
30 describe("pull", () => {
31 test("keeps records and the cursor; a replay writes nothing new", async () => {
32 const store = new Store(":memory:");
33 const first = await pull(store, config, source);
34 expect(first).toEqual({ pulled: 5, skipped: 0, cursor: "e", errors: [] });
35 expect(store.count()).toBe(5);
36
37 const again = await pull(store, config, source);
38 expect(again.pulled).toBe(0);
39 expect(again.cursor).toBe("e");
40 expect(store.count()).toBe(5);
41 });
42
43 test("the same cursor gives the same result", async () => {
44 const a = new Store(":memory:");
45 const b = new Store(":memory:");
46 expect(await pull(a, config, source)).toEqual(await pull(b, config, source));
47 });
48
49 test("a failing source is an error, and the cursor stays put", async () => {
50 const store = new Store(":memory:");
51 store.keep([], "b");
52 const down: Fetch = async () => new Response("no", { status: 503 });
53 const result = await pull(store, config, down);
54 expect(result.errors).toEqual(["the source answered 503"]);
55 expect(result.pulled).toBe(0);
56 expect(store.cursor()).toBe("b");
57 });
58
59 test("a malformed record is refused, not stored", async () => {
60 const store = new Store(":memory:");
61 const bad: Fetch = async () => Response.json({ items: [{ nope: 1 }], next: "x" });
62 const result = await pull(store, config, bad);
63 expect(result.errors.length).toBe(1);
64 expect(store.count()).toBe(0);
65 });
66 });
67
68 describe("outbound hosts", () => {
69 test("another host is refused, and never reached", async () => {
70 let reached = false;
71 const guarded = guardedFetch(["api.example.com"], async () => {
72 reached = true;
73 return new Response("");
74 });
75 for (const url of [
76 "https://evil.example.org/x",
77 "https://api.example.com.evil.org/x",
78 "http://api.example.com/x",
79 "https://user:[email protected]/x",
80 "not a url",
81 ])
82 await expect(guarded(url)).rejects.toBeInstanceOf(HostRefused);
83 expect(reached).toBe(false);
84 await guarded("https://api.example.com/v1/items");
85 expect(reached).toBe(true);
86 });
87
88 test("a pull whose base_url names another host records an error and fetches nothing", async () => {
89 const store = new Store(":memory:");
90 const result = await pull(
91 store,
92 { ...config, baseUrl: "https://evil.example.org" },
93 guardedFetch(config.hosts, source),
94 );
95 expect(result.errors[0]).toContain("not allowed");
96 expect(source.calls.some((u) => u.includes("evil"))).toBe(false);
97 });
98 });
99
100 describe("server", () => {
101 const handler = () => makeHandler(new Store(":memory:"), config, source);
102 const post = (headers: Record<string, string>) =>
103 new Request("http://app/pull", { method: "POST", headers });
104
105 test("POST /pull answers the contract's shape", async () => {
106 const res = await handler()(post({ "x-forge-pull": "1" }));
107 expect(res.status).toBe(200);
108 expect(await res.json()).toEqual({ pulled: 5, skipped: 0, cursor: "e", errors: [] });
109 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
110 });
111
112 test("a browser's cross-site POST, or one without the forge's header, is refused", async () => {
113 const h = handler();
114 expect((await h(post({ origin: "https://evil.example" }))).status).toBe(403);
115 expect((await h(post({}))).status).toBe(403);
116 expect((await h(new Request("http://app/pull"))).status).toBe(405);
117 });
118
119 test("the page escapes what it prints and never shows the token", async () => {
120 const store = new Store(":memory:");
121 store.keep([], "<script>x</script>");
122 const res = await makeHandler(store, config, source)(new Request("http://app/"));
123 const text = await res.text();
124 expect(text).not.toContain("<script>x");
125 expect(text).toContain("&lt;script&gt;");
126 expect(text).not.toContain("s3cret");
127 expect(res.headers.get("content-security-policy")).toContain("default-src 'none'");
128 });
129 });
130
131 describe("config", () => {
132 test("reads the declared block; a secret comes from the variable its ref names", () => {
133 const c = loadConfig(import.meta.dir + "/..", { EXAMPLE_TOKEN: "t0k" });
134 expect(c.hosts).toEqual(["api.example.com"]);
135 expect(c.token).toBe("t0k");
136 expect(c.baseUrl).toBe("https://api.example.com/v1");
137 });
138 });
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/fork*.test.ts test/cross-repo-pull.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/adapter*.test.ts test/pull*.test.ts test/web-apps.test.ts test/fleet-ops.test.ts && (cd examples/adapter-template && bun test)",
1010 "timeout": 1800
1111 }
1212 }
src/apps/adapter.ts added +192
@@ -0,0 +1,192 @@
1 /**
2 * The adapter block of `forge.json`: an app that declares itself a process
3 * the forge can schedule, inspect and audit, which syncs one external
4 * system into its own data. Validated here and nowhere else, and failing
5 * closed like the rest of the manifest — a block that is present and wrong
6 * fails the deploy with the field named.
7 *
8 * "adapter": {
9 * "source": { "name": "ledger", "hosts": ["api.ledger.example"] },
10 * "schedule": { "every": 900 },
11 * "config": { "account": { "type": "string", "default": "main" },
12 * "token": { "type": "secret", "ref": "LEDGER_TOKEN" } }
13 * }
14 *
15 * A secret is a reference to one of the app's environment variables (the
16 * operator sets it, sealed, in the app's environment settings); the value
17 * is never in the repository and a `default` on a secret is refused.
18 */
19
20 import { err, ok, type Result } from "../kernel/result.ts";
21
22 export type AdapterFieldType = "string" | "number" | "boolean" | "secret";
23
24 export interface AdapterField {
25 readonly type: AdapterFieldType;
26 /** The environment variable a `secret` is read from. Only for secrets. */
27 readonly ref: string | null;
28 /** The value when the operator sets none. Never for a secret. */
29 readonly default: string | number | boolean | null;
30 }
31
32 export interface AdapterManifest {
33 readonly source: { readonly name: string; readonly hosts: readonly string[] };
34 /** Seconds between pulls. */
35 readonly every: number;
36 readonly config: Readonly<Record<string, AdapterField>>;
37 }
38
39 export const EVERY_MIN = 10;
40 export const EVERY_MAX = 7 * 24 * 3600;
41 const HOSTS_MAX = 8;
42 const FIELDS_MAX = 32;
43 const NAME = /^[a-z][a-z0-9_-]{0,63}$/;
44 const FIELD = /^[a-z][a-z0-9_]{0,63}$/;
45 const REF = /^[A-Z][A-Z0-9_]{0,127}$/;
46 /** A bare DNS name: labels of letters, digits, hyphens; no port, no scheme, no wildcard. */
47 const HOST =
48 /^(?=.{1,253}$)[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/;
49 const TYPES: readonly AdapterFieldType[] = [
50 "string",
51 "number",
52 "boolean",
53 "secret",
54 ];
55 const STRING_MAX = 1_000;
56
57 type Json = Record<string, unknown>;
58 const isObject = (v: unknown): v is Json =>
59 typeof v === "object" && v !== null && !Array.isArray(v);
60 const bad = (message: string): Result<never, string> =>
61 err(`forge.json: adapter${message}`);
62
63 /** The block `forge.json` carries, `null` when it declares none. */
64 export function parseAdapter(value: unknown): Result<AdapterManifest | null, string> {
65 if (value === undefined) return ok(null);
66 if (!isObject(value)) return bad(" must be an object");
67 for (const key of Object.keys(value))
68 if (!["source", "schedule", "config"].includes(key))
69 return bad(`.${key} is not a known field`);
70
71 const source = value["source"];
72 if (!isObject(source)) return bad(".source is required and must be an object");
73 const name = source["name"];
74 if (typeof name !== "string" || !NAME.test(name))
75 return bad(".source.name must be lowercase letters, digits, - or _");
76 const hosts = source["hosts"];
77 if (!Array.isArray(hosts) || hosts.length < 1 || hosts.length > HOSTS_MAX)
78 return bad(`.source.hosts must list 1–${HOSTS_MAX} host names`);
79 const seen: string[] = [];
80 for (const host of hosts) {
81 if (typeof host !== "string" || !HOST.test(host))
82 return bad(
83 ".source.hosts entries must be bare lowercase host names (no scheme, port, path or wildcard)",
84 );
85 if (!seen.includes(host)) seen.push(host);
86 }
87
88 const schedule = value["schedule"];
89 if (!isObject(schedule)) return bad(".schedule is required and must be an object");
90 const every = schedule["every"];
91 if (
92 typeof every !== "number" ||
93 !Number.isInteger(every) ||
94 every < EVERY_MIN ||
95 every > EVERY_MAX
96 )
97 return bad(
98 `.schedule.every must be a whole number of seconds, ${EVERY_MIN}–${EVERY_MAX}`,
99 );
100
101 const rawConfig = value["config"] ?? {};
102 if (!isObject(rawConfig)) return bad(".config must be an object");
103 const names = Object.keys(rawConfig);
104 if (names.length > FIELDS_MAX) return bad(`.config may name at most ${FIELDS_MAX} fields`);
105 const config: Record<string, AdapterField> = {};
106 for (const field of names) {
107 if (!FIELD.test(field))
108 return bad(`.config.${field.slice(0, 40)} is not a valid field name`);
109 const parsed = fieldOf(field, rawConfig[field]);
110 if (!parsed.ok) return parsed;
111 config[field] = parsed.value;
112 }
113 return ok({ source: { name, hosts: seen }, every, config });
114 }
115
116 function fieldOf(name: string, raw: unknown): Result<AdapterField, string> {
117 const at = `.config.${name}`;
118 if (!isObject(raw)) return bad(`${at} must be an object`);
119 for (const key of Object.keys(raw))
120 if (!["type", "ref", "default"].includes(key))
121 return bad(`${at}.${key} is not a known field`);
122 const type = raw["type"];
123 if (typeof type !== "string" || !TYPES.includes(type as AdapterFieldType))
124 return bad(`${at}.type must be one of ${TYPES.join(", ")}`);
125 if (type === "secret") {
126 if (raw["default"] !== undefined)
127 return bad(`${at} is a secret: it takes a ref, never a value`);
128 const ref = raw["ref"];
129 if (typeof ref !== "string" || !REF.test(ref))
130 return bad(`${at}.ref must name an environment variable, like MY_TOKEN`);
131 return ok({ type, ref, default: null });
132 }
133 if (raw["ref"] !== undefined) return bad(`${at}.ref is only for secrets`);
134 const def = raw["default"];
135 if (def === undefined) return ok({ type: type as AdapterFieldType, ref: null, default: null });
136 const matches =
137 (type === "string" && typeof def === "string" && def.length <= STRING_MAX) ||
138 (type === "number" && typeof def === "number" && Number.isFinite(def)) ||
139 (type === "boolean" && typeof def === "boolean");
140 if (!matches) return bad(`${at}.default must be a ${type}`);
141 return ok({
142 type: type as AdapterFieldType,
143 ref: null,
144 default: def as string | number | boolean,
145 });
146 }
147
148 /**
149 * Whether an outbound URL may be fetched: `https` to exactly a declared host
150 * The same rule the template adapter applies before every request.
151 */
152 export function hostAllowed(hosts: readonly string[], url: string): boolean {
153 let parsed: URL;
154 try {
155 parsed = new URL(url);
156 } catch {
157 return false;
158 }
159 if (parsed.protocol !== "https:") return false;
160 if (parsed.username !== "" || parsed.password !== "") return false;
161 return hosts.includes(parsed.hostname.toLowerCase());
162 }
163
164 /** What `/pull` answers. */
165 export interface PullResult {
166 readonly pulled: number;
167 readonly skipped: number;
168 readonly cursor: string;
169 readonly errors: number;
170 }
171
172 /** Validate a `/pull` response body at the boundary: counts and a bounded cursor. */
173 export function parsePullResult(body: unknown): Result<PullResult, string> {
174 if (!isObject(body)) return err("the pull did not answer with an object");
175 const count = (k: string): number | undefined => {
176 const v = body[k];
177 // `errors` may be a list of messages; its count is what the forge keeps.
178 if (k === "errors" && Array.isArray(v)) return v.length;
179 return typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 1e9
180 ? v
181 : undefined;
182 };
183 const pulled = count("pulled");
184 const skipped = count("skipped");
185 const errors = count("errors");
186 const cursor = body["cursor"];
187 if (pulled === undefined || skipped === undefined || errors === undefined)
188 return err("the pull's pulled, skipped and errors must be counts");
189 if (typeof cursor !== "string" || cursor.length > 200 || /[\x00-\x1f\x7f]/.test(cursor))
190 return err("the pull's cursor must be a short single-line string");
191 return ok({ pulled, skipped, cursor, errors });
192 }
src/apps/manifest.ts +7
@@ -11,6 +11,7 @@
1111 */
1212
1313 import { err, ok, type Result } from "../kernel/result.ts";
14 import { parseAdapter, type AdapterManifest } from "./adapter.ts";
1415
1516 export interface AppManifest {
1617 /** The command that serves on `$PORT`. Run through `sh -c`, `exec`-ed. */
@@ -35,6 +36,8 @@ export interface AppManifest {
3536 * before this field existed.
3637 */
3738 readonly looks: readonly string[];
39 /** Set when the app declares itself an adapter (`apps/adapter.ts`). */
40 readonly adapter: AdapterManifest | null;
3841 }
3942
4043 export type ManifestError =
@@ -75,6 +78,7 @@ export function parseManifest(
7578 ready: READY_DEFAULT,
7679 tty: null,
7780 looks: ["/"],
81 adapter: null,
7882 });
7983 }
8084
@@ -117,6 +121,8 @@ export function parseManifest(
117121 );
118122 const looks = looksField(app);
119123 if (!looks.ok) return looks;
124 const adapter = parseAdapter(parsed.value["adapter"]);
125 if (!adapter.ok) return invalid(adapter.error);
120126
121127 return ok({
122128 run: runCommand,
@@ -133,6 +139,7 @@ export function parseManifest(
133139 ready: ready ?? READY_DEFAULT,
134140 tty: tty.value || null,
135141 looks: looks.value,
142 adapter: adapter.value,
136143 });
137144 }
138145
src/apps/pull.ts added +170
@@ -0,0 +1,170 @@
1 /**
2 * Pulling: the forge calls an adapter's `POST /pull` on the schedule its
3 * `forge.json` declares and records each call as a `pull` run — outcome,
4 * counts, cursor, duration — so a pull is as inspectable as a deploy.
5 *
6 * The schedule is read from the run table, never from a timer's memory: the
7 * next pull is the last pull's start plus the interval, so a restart
8 * neither forgets nor doubles one, and a failed pull waits out the interval
9 * like any other (nothing loops). One pull per app at a time. Only
10 * production is pulled: a preview holds a copy of production's data and a
11 * second sync of the same source would race it.
12 *
13 * Idempotence is the adapter's half of the contract (`docs/ADAPTERS.md`):
14 * the forge never retries inside a tick and never sends a body, so a
15 * repeated or replayed pull is the adapter being asked the same question.
16 */
17
18 import type { Database } from "bun:sqlite";
19 import { createLog } from "../kernel/log.ts";
20 import {
21 claimRun,
22 createRun,
23 finishRun,
24 listRuns,
25 type Run,
26 } from "../core/runs.ts";
27 import {
28 parsePullResult,
29 type AdapterManifest,
30 type PullResult,
31 } from "./adapter.ts";
32
33 const log = createLog("pull");
34
35 export interface PullTarget {
36 readonly repoId: string;
37 readonly port: number;
38 readonly adapter: AdapterManifest;
39 }
40
41 const TICK_MS = 5_000;
42 const TIMEOUT_MS = 5 * 60_000;
43 const BODY_MAX = 64 * 1024;
44
45 /** When the next pull is due: the last one's start plus the interval; null before any. */
46 export function nextPullAt(
47 db: Database,
48 repoId: string,
49 every: number,
50 ): string | null {
51 const last = lastPull(db, repoId);
52 if (last === undefined) return null;
53 return new Date(Date.parse(last.createdAt) + every * 1000).toISOString();
54 }
55
56 export const lastPull = (db: Database, repoId: string): Run | undefined =>
57 listRuns(db, repoId, { kind: "pull", env: "production", limit: 1 })[0];
58
59 export interface PullOptions {
60 readonly tickMs?: number | undefined;
61 readonly timeoutMs?: number | undefined;
62 }
63
64 export class PullSchedule {
65 private timer: ReturnType<typeof setInterval> | undefined;
66 private readonly inflight = new Set<string>();
67 private stopped = false;
68
69 constructor(
70 private readonly db: Database,
71 private readonly targets: () => readonly PullTarget[],
72 private readonly options: PullOptions = {},
73 ) {}
74
75 start(): void {
76 // A pull running when the last forge died never finished; say so.
77 this.db
78 .query(
79 `UPDATE run SET state = 'failed', summary = 'the forge stopped',
80 finished_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
81 WHERE kind = 'pull' AND state IN ('queued','running')`,
82 )
83 .run();
84 this.timer = setInterval(
85 () => void this.tick(),
86 this.options.tickMs ?? TICK_MS,
87 );
88 }
89
90 stop(): void {
91 this.stopped = true;
92 if (this.timer !== undefined) clearInterval(this.timer);
93 }
94
95 /** Pull every target that is due. */
96 async tick(now = Date.now()): Promise<void> {
97 const due = this.targets().filter((t) => {
98 const next = nextPullAt(this.db, t.repoId, t.adapter.every);
99 return next === null || Date.parse(next) <= now;
100 });
101 await Promise.all(due.map((t) => this.pull(t, "schedule")));
102 }
103
104 /** One pull, recorded. Returns undefined when this app is already mid-pull. */
105 async pull(target: PullTarget, reason: string): Promise<Run | undefined> {
106 if (this.stopped || this.inflight.has(target.repoId)) return undefined;
107 this.inflight.add(target.repoId);
108 try {
109 const run = createRun(this.db, {
110 repoId: target.repoId,
111 kind: "pull",
112 env: "production",
113 reason,
114 summary: `pulling ${target.adapter.source.name}`,
115 });
116 if (claimRun(this.db, run.id) === undefined) return undefined;
117 const started = Date.now();
118 const outcome = await this.call(target);
119 const durationMs = Date.now() - started;
120 if (this.stopped) return undefined;
121 if (!outcome.ok)
122 return finishRun(this.db, run.id, {
123 state: "failed",
124 summary: `${target.adapter.source.name}: ${outcome.error}`,
125 });
126 const r = outcome.value;
127 return finishRun(this.db, run.id, {
128 state: r.errors > 0 ? "failed" : "ok",
129 summary: `${target.adapter.source.name}: pulled ${r.pulled}, skipped ${r.skipped}, ${r.errors} errors`,
130 pullDetail: { ...r, durationMs },
131 });
132 } catch (error) {
133 log.error("pull failed", { error: String(error) });
134 return undefined;
135 } finally {
136 this.inflight.delete(target.repoId);
137 }
138 }
139
140 private async call(
141 target: PullTarget,
142 ): Promise<{ ok: true; value: PullResult } | { ok: false; error: string }> {
143 try {
144 const res = await fetch(`http://127.0.0.1:${target.port}/pull`, {
145 method: "POST",
146 headers: { "x-forge-pull": "1" },
147 redirect: "error",
148 signal: AbortSignal.timeout(this.options.timeoutMs ?? TIMEOUT_MS),
149 });
150 const text = await res.text();
151 if (!res.ok) return { ok: false, error: `/pull answered ${res.status}` };
152 if (text.length > BODY_MAX)
153 return { ok: false, error: "the pull's answer was too large" };
154 let body: unknown;
155 try {
156 body = JSON.parse(text);
157 } catch {
158 return { ok: false, error: "the pull did not answer with JSON" };
159 }
160 const parsed = parsePullResult(body);
161 return parsed.ok ? { ok: true, value: parsed.value } : { ok: false, error: parsed.error };
162 } catch (error) {
163 const timedOut = error instanceof Error && error.name === "TimeoutError";
164 return {
165 ok: false,
166 error: timedOut ? "/pull timed out" : "could not reach /pull",
167 };
168 }
169 }
170 }
src/apps/runtime.ts +31
@@ -61,7 +61,9 @@ import {
6161 reseedEmpty,
6262 type EnvName,
6363 } from "./data.ts";
64 import type { AdapterManifest } from "./adapter.ts";
6465 import { parseManifest, type AppManifest } from "./manifest.ts";
66 import { PullSchedule, type PullTarget } from "./pull.ts";
6567 import { identityKey } from "./proxy.ts";
6668 import {
6769 startProcess,
@@ -93,6 +95,8 @@ export interface RuntimeOptions {
9395 | undefined;
9496 /** How often the runtime looks for environments to put to sleep. */
9597 readonly sweepEveryMs?: number | undefined;
98 /** How often the adapter schedule looks for a pull that is due. */
99 readonly pullTickMs?: number | undefined;
96100 /**
97101 * How long a pull may go without a push or a comment before its preview
98102 * is stopped (not removed: its row, data and pictures stay) and reads as
@@ -263,6 +267,8 @@ export interface LiveEnv {
263267 readonly commitOid: string;
264268 readonly url: string;
265269 readonly tty: string | null;
270 /** The adapter block, when this app declares itself one. */
271 readonly adapter: AdapterManifest | null;
266272 }
267273
268274 interface Environment {
@@ -318,6 +324,7 @@ export class AppsRuntime {
318324 private readonly gate: Gate;
319325 private unsubscribe: (() => void) | undefined;
320326 private sweeper: ReturnType<typeof setInterval> | undefined;
327 readonly pulls: PullSchedule;
321328 private stopped = false;
322329
323330 constructor(
@@ -325,9 +332,30 @@ export class AppsRuntime {
325332 readonly options: RuntimeOptions,
326333 ) {
327334 this.gate = new Gate(options.concurrency ?? 2);
335 this.pulls = new PullSchedule(
336 app.db,
337 () => this.pullTargets(),
338 { tickMs: options.pullTickMs },
339 );
328340 runtimes.set(app, this);
329341 }
330342
343 /** Production environments that are up and declare an adapter. */
344 private pullTargets(): PullTarget[] {
345 const targets: PullTarget[] = [];
346 for (const state of this.envs.values()) {
347 const adapter = state.live?.manifest.adapter;
348 if (state.env !== "production" || state.live === undefined || !adapter)
349 continue;
350 targets.push({
351 repoId: state.app.repoId,
352 port: state.live.handle.port,
353 adapter,
354 });
355 }
356 return targets;
357 }
358
331359 // ---- addressing ----
332360
333361 hostFor(slug: string, env: EnvName): string {
@@ -539,6 +567,7 @@ export class AppsRuntime {
539567 await this.reconcileApp(record, repo, "boot");
540568 }
541569 this.pruneDirs(known);
570 this.pulls.start();
542571 this.sweeper = setInterval(
543572 () => void this.sweep(),
544573 this.options.sweepEveryMs ?? SWEEP_EVERY_MS,
@@ -549,6 +578,7 @@ export class AppsRuntime {
549578 async stop(): Promise<void> {
550579 this.stopped = true;
551580 if (this.sweeper !== undefined) clearInterval(this.sweeper);
581 this.pulls.stop();
552582 this.unsubscribe?.();
553583 const stops: Promise<void>[] = [];
554584 for (const state of this.envs.values()) {
@@ -1144,6 +1174,7 @@ export class AppsRuntime {
11441174 commitOid: live.commitOid,
11451175 url: this.urlFor(record, env),
11461176 tty: live.manifest.tty,
1177 adapter: live.manifest.adapter,
11471178 };
11481179 }
11491180
src/core/runs.ts +24 −3
@@ -11,7 +11,7 @@
1111 import type { Database } from "bun:sqlite";
1212 import { id } from "../kernel/id.ts";
1313
14 export type RunKind = "deploy" | "agent" | "check";
14 export type RunKind = "deploy" | "agent" | "check" | "pull";
1515
1616 /**
1717 * The one summary a run cancelled by the forge's own restart carries — never
@@ -23,7 +23,12 @@ export const STOPPED_SUMMARY = "the forge stopped";
2323
2424 /** The kinds that pass judgement on a commit: a preview's deploy, or a repository's own check. */
2525 export const CHECK_KINDS: readonly RunKind[] = ["deploy", "check"];
26 export const RUN_KINDS: readonly RunKind[] = ["deploy", "agent", "check"];
26 export const RUN_KINDS: readonly RunKind[] = [
27 "deploy",
28 "agent",
29 "check",
30 "pull",
31 ];
2732 export type RunState = "queued" | "running" | "ok" | "failed" | "cancelled";
2833
2934 export const RUN_TERMINAL: readonly RunState[] = ["ok", "failed", "cancelled"];
@@ -42,6 +47,15 @@ export interface CheckDetail {
4247 readonly names: readonly string[];
4348 }
4449
50 /** What an adapter's pull did, as the app reported it (`apps/pull.ts`). */
51 export interface PullDetail {
52 readonly pulled: number;
53 readonly skipped: number;
54 readonly errors: number;
55 readonly cursor: string;
56 readonly durationMs: number;
57 }
58
4559 export interface Run {
4660 readonly id: string;
4761 readonly repoId: string;
@@ -77,6 +91,8 @@ export interface Run {
7791 readonly sandboxNote: string;
7892 /** A failed check's own detail, when its output was recognised; null otherwise. */
7993 readonly checkDetail: CheckDetail | null;
94 /** A pull's counts, cursor and duration; null on any other run. */
95 readonly pullDetail: PullDetail | null;
8096 readonly createdAt: string;
8197 readonly startedAt: string | null;
8298 /** When this deploy's environment started serving — set once, at the swap-in. */
@@ -105,6 +121,7 @@ interface RunRow {
105121 sandbox_enforced: number | null;
106122 sandbox_note: string;
107123 check_detail: string;
124 pull_detail: string;
108125 created_at: string;
109126 started_at: string | null;
110127 serving_at: string | null;
@@ -133,6 +150,7 @@ const toRun = (r: RunRow): Run => ({
133150 r.sandbox_enforced === null ? null : r.sandbox_enforced !== 0,
134151 sandboxNote: r.sandbox_note,
135152 checkDetail: r.check_detail ? (JSON.parse(r.check_detail) as CheckDetail) : null,
153 pullDetail: r.pull_detail ? (JSON.parse(r.pull_detail) as PullDetail) : null,
136154 createdAt: r.created_at,
137155 startedAt: r.started_at,
138156 servingAt: r.serving_at,
@@ -256,13 +274,15 @@ export function finishRun(
256274 turns?: number | undefined;
257275 /** A failed check's own detail, when its output was recognised. */
258276 checkDetail?: CheckDetail | undefined;
277 /** A pull's counts, cursor and duration. */
278 pullDetail?: PullDetail | undefined;
259279 },
260280 ): Run | undefined {
261281 const changes = db
262282 .query(
263283 `UPDATE run SET state = ?2, summary = ?3,
264284 session_id = COALESCE(?4, session_id), cost_usd = COALESCE(?5, cost_usd),
265 turns = COALESCE(?6, turns), check_detail = ?7,
285 turns = COALESCE(?6, turns), check_detail = ?7, pull_detail = ?8,
266286 finished_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
267287 WHERE id = ?1 AND state = 'running'`,
268288 )
@@ -274,6 +294,7 @@ export function finishRun(
274294 outcome.costUsd ?? null,
275295 outcome.turns ?? null,
276296 outcome.checkDetail ? JSON.stringify(outcome.checkDetail) : "",
297 outcome.pullDetail ? JSON.stringify(outcome.pullDetail) : "",
277298 ).changes;
278299 return changes > 0 ? getRun(db, runId) : undefined;
279300 }
src/core/schema.ts +53
@@ -1081,4 +1081,57 @@ export const migrations: readonly string[] = [
10811081 PRIMARY KEY (operation_id, position)
10821082 );
10831083 `,
1084 // 41 — a pull (`apps/pull.ts`) is a run: its kind joins the list, and the
1085 // adapter's counts, cursor and duration are kept as JSON on the row. The
1086 // kind is a CHECK, so the table is rebuilt; `usage` cascades from `run`,
1087 // so its rows are set aside across the drop and put back.
1088 `
1089 CREATE TEMP TABLE usage_keep AS SELECT * FROM usage;
1090 CREATE TABLE run_v3 (
1091 id TEXT PRIMARY KEY,
1092 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
1093 kind TEXT NOT NULL CHECK (kind IN ('deploy','agent','check','pull')),
1094 issue_id TEXT REFERENCES issue(id) ON DELETE CASCADE,
1095 env TEXT NOT NULL DEFAULT '',
1096 commit_oid TEXT NOT NULL DEFAULT '',
1097 branch TEXT NOT NULL DEFAULT '',
1098 state TEXT NOT NULL DEFAULT 'queued'
1099 CHECK (state IN ('queued','running','ok','failed','cancelled')),
1100 summary TEXT NOT NULL DEFAULT '',
1101 actor_id TEXT REFERENCES user(id) ON DELETE SET NULL,
1102 reason TEXT NOT NULL DEFAULT '',
1103 session_id TEXT NOT NULL DEFAULT '',
1104 cost_usd REAL NOT NULL DEFAULT 0,
1105 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
1106 started_at TEXT,
1107 finished_at TEXT,
1108 not_before TEXT,
1109 attempt INTEGER NOT NULL DEFAULT 0,
1110 heartbeat_at TEXT,
1111 turns INTEGER NOT NULL DEFAULT 0,
1112 subscription_id TEXT,
1113 serving_at TEXT,
1114 check_detail TEXT NOT NULL DEFAULT '',
1115 sandbox_enforced INTEGER,
1116 sandbox_note TEXT NOT NULL DEFAULT '',
1117 pull_detail TEXT NOT NULL DEFAULT ''
1118 );
1119 INSERT INTO run_v3 (id, repo_id, kind, issue_id, env, commit_oid, branch, state,
1120 summary, actor_id, reason, session_id, cost_usd, created_at,
1121 started_at, finished_at, not_before, attempt, heartbeat_at,
1122 turns, subscription_id, serving_at, check_detail,
1123 sandbox_enforced, sandbox_note)
1124 SELECT id, repo_id, kind, issue_id, env, commit_oid, branch, state,
1125 summary, actor_id, reason, session_id, cost_usd, created_at,
1126 started_at, finished_at, not_before, attempt, heartbeat_at,
1127 turns, subscription_id, serving_at, check_detail,
1128 sandbox_enforced, sandbox_note FROM run;
1129 DROP TABLE run;
1130 ALTER TABLE run_v3 RENAME TO run;
1131 CREATE INDEX run_repo ON run(repo_id, id DESC);
1132 CREATE INDEX run_issue ON run(issue_id, id DESC) WHERE issue_id IS NOT NULL;
1133 CREATE INDEX run_queue ON run(state, id) WHERE state IN ('queued','running');
1134 INSERT INTO usage SELECT * FROM usage_keep;
1135 DROP TABLE usage_keep;
1136 `,
10841137 ];
src/web/studio/adapter.ts added +54
@@ -0,0 +1,54 @@
1 /**
2 * The adapter card on the app page: when the source was last pulled, what
3 * came of it, when the next pull is due and where the cursor stands. Drawn
4 * only for an app that declares an adapter and is up in production; every
5 * value comes from the pull run the forge recorded, escaped by `html`.
6 */
7
8 import { appsRuntime } from "../../apps/runtime.ts";
9 import { lastPull, nextPullAt } from "../../apps/pull.ts";
10 import type { AppRecord } from "../../core/apps.ts";
11 import type { Ctx } from "../../http/context.ts";
12 import { html, type Html } from "../html.ts";
13 import { card, icon, time } from "../ui.ts";
14
15 const utc = (iso: string): string =>
16 `${new Date(iso).toISOString().slice(0, 16).replace("T", " ")} UTC`;
17
18 export function adapterCard(ctx: Ctx, record: AppRecord): Html | null {
19 const adapter = appsRuntime(ctx.app)?.liveFor(record, "production")?.adapter;
20 if (!adapter) return null;
21 const last = lastPull(ctx.app.db, record.repoId);
22 const next = nextPullAt(ctx.app.db, record.repoId, adapter.every);
23 const detail = last?.pullDetail ?? null;
24 return card(
25 html`<dl>
26 <dt>Source</dt>
27 <dd>${adapter.source.name}</dd>
28 <dt>Last pull</dt>
29 <dd>
30 ${last === undefined
31 ? "Not yet"
32 : html`${time(last.createdAt)} · ${last.state}
33 <span class="muted small">· ${last.summary}</span>
34 ${detail === null
35 ? null
36 : html`<span class="muted small">
37 · ${(detail.durationMs / 1000).toFixed(1)}s</span
38 >`}`}
39 </dd>
40 <dt>Next pull</dt>
41 <dd>
42 ${next === null ? "On the next tick" : utc(next)}
43 <span class="muted small">· every ${adapter.every}s</span>
44 </dd>
45 <dt>Cursor</dt>
46 <dd class="mono">${detail?.cursor || "none yet"}</dd>
47 </dl>`,
48 {
49 head: html`${icon("activity")}
50 <h2>Adapter</h2>`,
51 extra: "about",
52 },
53 );
54 }
src/web/studio/app.ts +2 −1
@@ -40,6 +40,7 @@ import {
4040 time,
4141 userTag,
4242 } from "../ui.ts";
43 import { adapterCard } from "./adapter.ts";
4344 import { changesHref, tellsHref } from "./nouns.ts";
4445 import { nowCard, nowRegion } from "./now.ts";
4546 import { appPanels } from "./previews.ts";
@@ -433,7 +434,7 @@ export async function studioApp(
433434 ${nowRegion(repo, now)}
434435 </div>
435436 <aside class="dash-rail stack">
436 ${crewCard} ${weekCard} ${ownCard} ${more}
437 ${adapterCard(ctx, record)} ${crewCard} ${weekCard} ${ownCard} ${more}
437438 </aside>
438439 </div>
439440 ${liveMount({ repo: base, app: true })}`;
test/adapter-page.test.ts added +134
@@ -0,0 +1,134 @@
1 /** The app page of an adapter: last pull, next pull and cursor — and nothing for an app that is not one. */
2
3 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { enableApp } from "../src/actions/apps.ts";
8 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
9 import { createApp, type App } from "../src/app.ts";
10 import { parseAdapter } from "../src/apps/adapter.ts";
11 import { AppsRuntime } from "../src/apps/runtime.ts";
12 import { getAppByRepo, type AppRecord } from "../src/core/apps.ts";
13 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16
17 describe("the app page of an adapter", () => {
18 let dir: string;
19 let app: App;
20 let servers: Servers;
21 let record: AppRecord;
22 let runtime: AppsRuntime;
23 let cookie = "";
24
25 const page = async (): Promise<string> =>
26 (
27 await fetch(`${servers.url}/alice/ledger`, {
28 headers: { cookie: `${cookie}; forge_mode=studio` },
29 })
30 ).text();
31
32 const put = (adapter: unknown): void => {
33 const parsed = parseAdapter(adapter);
34 if (!parsed.ok) throw new Error(parsed.error);
35 (runtime as unknown as { envs: Map<string, unknown> }).envs.set(
36 `${record.id}/production`,
37 {
38 app: record,
39 env: "production",
40 chain: Promise.resolve(),
41 restarts: [],
42 live: {
43 commitOid: "cafebabe",
44 handle: { port: 4999 },
45 dir: dir,
46 runId: "x",
47 since: new Date().toISOString(),
48 manifest: { tty: null, looks: ["/"], adapter: parsed.value },
49 },
50 },
51 );
52 };
53
54 beforeAll(async () => {
55 dir = await mkdtemp(join(tmpdir(), "forge-adapter-page-"));
56 app = createApp({ dataDir: dir, port: 0 });
57 servers = await serve(app);
58 runtime = new AppsRuntime(app, {
59 domain: "apps.test",
60 scheme: "http",
61 publicPort: servers.port,
62 forgeUrl: servers.url,
63 concurrency: 1,
64 });
65 const u = await createUser(app.db, {
66 username: "alice",
67 email: "[email protected]",
68 password: "a-good-passphrase",
69 adminIfFirst: true,
70 });
71 if (!u.ok) throw new Error(u.error);
72 const made = await createRepo(app, u.value, { name: "ledger", visibility: "public" });
73 if (!made.ok) throw new Error(String(made.error));
74 const seeded = await commitToBranch(app, u.value, made.value, {
75 message: "Start",
76 files: [{ path: "README.md", content: "ledger\n" }],
77 });
78 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
79 const enabled = await enableApp(app, u.value, made.value, { slug: "ledger" });
80 if (!enabled.ok) throw new Error(String(enabled.error));
81 record = getAppByRepo(app.db, made.value.id)!;
82 cookie = (
83 (
84 await fetch(`${servers.url}/signin`, {
85 method: "POST",
86 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
87 redirect: "manual",
88 })
89 ).headers.get("set-cookie") ?? ""
90 ).split(";")[0]!;
91 });
92
93 afterAll(async () => {
94 servers.stop();
95 app.close();
96 await rm(dir, { recursive: true, force: true });
97 });
98
99 const block = {
100 source: { name: "ledger", hosts: ["api.ledger.example"] },
101 schedule: { every: 900 },
102 };
103
104 test("an app that is not an adapter shows no adapter card", async () => {
105 expect(await page()).not.toContain("<h2>Adapter</h2>");
106 });
107
108 test("before any pull: not yet, and the cursor is none", async () => {
109 put(block);
110 const html = await page();
111 expect(html).toContain("<h2>Adapter</h2>");
112 expect(html).toContain("Not yet");
113 expect(html).toContain("none yet");
114 expect(html).toContain("every 900s");
115 });
116
117 test("after a pull: last pull, next pull and cursor, escaped", async () => {
118 put(block);
119 const run = createRun(app.db, { repoId: record.repoId, kind: "pull", env: "production" });
120 claimRun(app.db, run.id);
121 finishRun(app.db, run.id, {
122 state: "ok",
123 summary: "ledger: pulled 3, skipped 0, 0 errors",
124 pullDetail: { pulled: 3, skipped: 0, errors: 0, cursor: "<i>42</i>", durationMs: 1200 },
125 });
126 const html = await page();
127 expect(html).toContain("pulled 3, skipped 0, 0 errors");
128 expect(html).toContain("&lt;i&gt;42&lt;/i&gt;");
129 expect(html).not.toContain("<i>42");
130 expect(html).toContain("1.2s");
131 expect(html).toContain("Next pull");
132 expect(html).toMatch(/\d{4}-\d\d-\d\d \d\d:\d\d UTC/);
133 });
134 });
test/adapter.test.ts added +129
@@ -0,0 +1,129 @@
1 /** The `adapter` block of forge.json: validated at the boundary, in one module. */
2
3 import { Database } from "bun:sqlite";
4 import { describe, expect, test } from "bun:test";
5 import { hostAllowed, parseAdapter, parsePullResult } from "../src/apps/adapter.ts";
6 import { parseManifest } from "../src/apps/manifest.ts";
7 import { migrations } from "../src/core/schema.ts";
8
9 const good = {
10 source: { name: "ledger", hosts: ["api.ledger.example"] },
11 schedule: { every: 900 },
12 config: {
13 account: { type: "string", default: "main" },
14 batch: { type: "number", default: 50 },
15 dry: { type: "boolean" },
16 token: { type: "secret", ref: "LEDGER_TOKEN" },
17 },
18 };
19
20 const message = (block: unknown): string => {
21 const r = parseAdapter(block);
22 if (r.ok) throw new Error("expected a refusal");
23 return r.error;
24 };
25
26 describe("parseAdapter", () => {
27 test("absent is no adapter; a good block parses", () => {
28 expect(parseAdapter(undefined)).toEqual({ ok: true, value: null });
29 const r = parseAdapter(good);
30 expect(r.ok && r.value).toMatchObject({
31 source: { name: "ledger", hosts: ["api.ledger.example"] },
32 every: 900,
33 });
34 expect(r.ok && r.value?.config["token"]).toEqual({ type: "secret", ref: "LEDGER_TOKEN", default: null });
35 });
36
37 test("a secret is a reference, never a value", () => {
38 const withValue = { ...good, config: { token: { type: "secret", ref: "T", default: "hunter2" } } };
39 expect(message(withValue)).toContain("never a value");
40 expect(message({ ...good, config: { token: { type: "secret" } } })).toContain("ref");
41 expect(message({ ...good, config: { token: { type: "secret", ref: "lower" } } })).toContain("ref");
42 expect(message({ ...good, config: { a: { type: "string", ref: "X" } } })).toContain("only for secrets");
43 });
44
45 test("hosts are bare names", () => {
46 for (const host of ["https://a.example", "a.example:8080", "*.example", "a.example/x", "", "A.Example", "a b"])
47 expect(message({ ...good, source: { name: "x", hosts: [host] } })).toContain("hosts");
48 expect(message({ ...good, source: { name: "x", hosts: [] } })).toContain("hosts");
49 expect(message({ ...good, source: { name: "X y" } })).toContain("name");
50 });
51
52 test("schedule and config types are bounded and typed", () => {
53 for (const every of [0, 9, 1.5, "900", 8 * 24 * 3600])
54 expect(message({ ...good, schedule: { every } })).toContain("every");
55 expect(message({ ...good, config: { n: { type: "number", default: "1" } } })).toContain("number");
56 expect(message({ ...good, config: { n: { type: "date" } } })).toContain("type");
57 expect(message({ ...good, config: { "Bad Name": { type: "string" } } })).toContain("field name");
58 expect(message({ ...good, extra: 1 })).toContain("not a known field");
59 expect(message("x")).toContain("object");
60 });
61 });
62
63 describe("the manifest carries it", () => {
64 const forge = (adapter: unknown) =>
65 JSON.stringify({ app: { run: "bun run src/server.ts" }, adapter });
66
67 test("an app with the block is an adapter; one without is not", () => {
68 const m = parseManifest(forge(good), undefined);
69 expect(m.ok && m.value.adapter?.source.name).toBe("ledger");
70 const none = parseManifest(JSON.stringify({ app: { run: "x" } }), undefined);
71 expect(none.ok && none.value.adapter).toBeNull();
72 });
73
74 test("a wrong block fails the deploy, naming the field", () => {
75 const m = parseManifest(forge({ ...good, schedule: {} }), undefined);
76 expect(!m.ok && m.error).toMatchObject({ kind: "invalid" });
77 expect(!m.ok && m.error.kind === "invalid" && m.error.message).toContain("adapter.schedule.every");
78 });
79 });
80
81 describe("outbound hosts", () => {
82 test("https to exactly a declared host", () => {
83 const hosts = ["api.ledger.example"];
84 expect(hostAllowed(hosts, "https://api.ledger.example/v1/x")).toBe(true);
85 for (const url of [
86 "http://api.ledger.example/",
87 "https://other.example/",
88 "https://api.ledger.example.evil.org/",
89 "https://evil.org/@api.ledger.example",
90 "https://u:[email protected]/",
91 "nonsense",
92 ])
93 expect(hostAllowed(hosts, url)).toBe(false);
94 });
95 });
96
97 describe("parsePullResult", () => {
98 test("counts and a bounded cursor; errors may be a list", () => {
99 expect(parsePullResult({ pulled: 1, skipped: 2, cursor: "c", errors: ["x"] })).toEqual({
100 ok: true,
101 value: { pulled: 1, skipped: 2, cursor: "c", errors: 1 },
102 });
103 for (const body of [
104 null,
105 { pulled: -1, skipped: 0, cursor: "", errors: 0 },
106 { pulled: 1, skipped: 0, errors: 0 },
107 { pulled: 1, skipped: 0, cursor: "a\nb", errors: 0 },
108 { pulled: 1, skipped: 0, cursor: "x".repeat(201), errors: 0 },
109 ])
110 expect(parsePullResult(body).ok).toBe(false);
111 });
112 });
113
114 describe("migration 41", () => {
115 test("a run may be a pull, and the usage rows survive the rebuild", () => {
116 const db = new Database(":memory:");
117 db.exec("PRAGMA foreign_keys = ON");
118 for (const m of migrations.slice(0, 40)) db.exec(m);
119 db.exec(`INSERT INTO user (id, username, email, password_hash) VALUES ('u','u','u@x','x')`);
120 db.exec(`INSERT INTO repo (id, owner_id, name) VALUES ('r','u','r')`);
121 db.exec(`INSERT INTO run (id, repo_id, kind) VALUES ('d','r','deploy')`);
122 db.exec(`INSERT INTO usage (run_id, repo_id, outcome, at) VALUES ('d','r','ok','2026-01-01')`);
123 expect(() => db.exec(`INSERT INTO run (id, repo_id, kind) VALUES ('p','r','pull')`)).toThrow();
124 db.transaction(() => db.exec(migrations[40]!))();
125 db.exec(`INSERT INTO run (id, repo_id, kind) VALUES ('p','r','pull')`);
126 expect(db.query("SELECT COUNT(*) AS n FROM usage").get()).toEqual({ n: 1 });
127 expect(db.query("SELECT kind FROM run WHERE id = 'd'").get()).toEqual({ kind: "deploy" });
128 });
129 });
test/apps.test.ts +1
@@ -2017,6 +2017,7 @@ describe("a start that fails reports the message, not its last line (issue #270)
20172017 ready: 2,
20182018 tty: null,
20192019 looks: ["/"],
2020 adapter: null,
20202021 };
20212022
20222023 // A realistic crash: the message, a blank line, three frames, then the
test/pull.test.ts added +192
@@ -0,0 +1,192 @@
1 /**
2 * The forge pulling an adapter on schedule (`apps/pull.ts`), end to end
3 * against the template adapter's own handler: every pull a recorded run, a
4 * replay writes nothing new, a failure is a failed run and never a retry
5 * loop, and the declared host list is what the adapter can reach.
6 */
7
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createRepo } from "../src/actions/repos.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import { parseAdapter } from "../src/apps/adapter.ts";
15 import { lastPull, nextPullAt, PullSchedule, type PullTarget } from "../src/apps/pull.ts";
16 import { listRuns } from "../src/core/runs.ts";
17 import { createUser } from "../src/core/users.ts";
18 import type { Config } from "../examples/adapter-template/src/config.ts";
19 import { makeHandler } from "../examples/adapter-template/src/server.ts";
20 import { guardedFetch, type Fetch } from "../examples/adapter-template/src/source.ts";
21 import { Store } from "../examples/adapter-template/src/store.ts";
22
23 const adapter = (() => {
24 const r = parseAdapter({
25 source: { name: "example", hosts: ["api.example.com"] },
26 schedule: { every: 60 },
27 });
28 if (!r.ok || r.value === null) throw new Error("bad fixture");
29 return r.value;
30 })();
31
32 const config: Config = {
33 source: "example",
34 hosts: ["api.example.com"],
35 baseUrl: "https://api.example.com/v1",
36 pageSize: 2,
37 token: "",
38 };
39
40 const ids = ["a", "b", "c", "d", "e"];
41 let status = 200;
42 const calls: string[] = [];
43 const source: Fetch = async (url) => {
44 calls.push(url);
45 if (status !== 200) return new Response("down", { status });
46 const after = new URL(url).searchParams.get("after") ?? "";
47 const items = ids
48 .slice(after === "" ? 0 : ids.indexOf(after) + 1)
49 .slice(0, 2)
50 .map((id) => ({ id }));
51 return Response.json({ items, next: items.at(-1)?.id ?? null });
52 };
53
54 describe("the forge pulls an adapter", () => {
55 let dir: string;
56 let app: App;
57 let repoId: string;
58 let store: Store;
59 let server: ReturnType<typeof Bun.serve>;
60 let target: PullTarget;
61 let schedule: PullSchedule;
62
63 const serveAdapter = (cfg: Config): ReturnType<typeof Bun.serve> =>
64 Bun.serve({
65 port: 0,
66 hostname: "127.0.0.1",
67 fetch: makeHandler(store, cfg, guardedFetch(cfg.hosts, source)),
68 });
69
70 beforeAll(async () => {
71 dir = await mkdtemp(join(tmpdir(), "forge-pull-"));
72 app = createApp({ dataDir: dir, port: 0 });
73 const u = await createUser(app.db, {
74 username: "alice",
75 email: "[email protected]",
76 password: "a-good-passphrase",
77 adminIfFirst: true,
78 });
79 if (!u.ok) throw new Error(u.error);
80 const made = await createRepo(app, u.value, { name: "sync", visibility: "public" });
81 if (!made.ok) throw new Error(String(made.error));
82 repoId = made.value.id;
83 store = new Store(":memory:");
84 server = serveAdapter(config);
85 target = { repoId, port: server.port!, adapter };
86 schedule = new PullSchedule(app.db, () => [target]);
87 });
88
89 afterAll(async () => {
90 server.stop(true);
91 schedule.stop();
92 app.close();
93 await rm(dir, { recursive: true, force: true });
94 });
95
96 test("a pull is recorded as a run: counts, cursor, duration", async () => {
97 expect(nextPullAt(app.db, repoId, 60)).toBeNull();
98 const run = await schedule.pull(target, "schedule");
99 expect(run?.kind).toBe("pull");
100 expect(run?.state).toBe("ok");
101 expect(run?.pullDetail).toMatchObject({ pulled: 5, skipped: 0, errors: 0, cursor: "e" });
102 expect(run?.pullDetail?.durationMs).toBeGreaterThanOrEqual(0);
103 expect(store.count()).toBe(5);
104 expect(nextPullAt(app.db, repoId, 60)).toBe(
105 new Date(Date.parse(run!.createdAt) + 60_000).toISOString(),
106 );
107 });
108
109 test("not due means not pulled; due means pulled once, and a repeat writes nothing", async () => {
110 const before = listRuns(app.db, repoId, { kind: "pull" }).length;
111 await schedule.tick(Date.now());
112 expect(listRuns(app.db, repoId, { kind: "pull" })).toHaveLength(before);
113
114 await schedule.tick(Date.now() + 61_000);
115 const runs = listRuns(app.db, repoId, { kind: "pull" });
116 expect(runs).toHaveLength(before + 1);
117 expect(runs[0]?.pullDetail).toMatchObject({ pulled: 0, skipped: 0, cursor: "e" });
118 expect(store.count()).toBe(5);
119
120 // Replaying from the start (a lost cursor) skips what is held.
121 store.keep([], "");
122 const replay = await schedule.pull(target, "manual");
123 expect(replay?.pullDetail).toMatchObject({ pulled: 0, skipped: 5 });
124 expect(store.count()).toBe(5);
125 });
126
127 test("a failing source is a failed run, the cursor holds, nothing is double-written", async () => {
128 status = 503;
129 const run = await schedule.pull(target, "schedule");
130 expect(run?.state).toBe("failed");
131 expect(run?.pullDetail?.errors).toBe(1);
132 expect(store.count()).toBe(5);
133 expect(lastPull(app.db, repoId)?.id).toBe(run!.id);
134 status = 200;
135 });
136
137 test("an adapter that cannot be reached is a failed run", async () => {
138 const dead = { ...target, port: 1 };
139 const run = await schedule.pull(dead, "schedule");
140 expect(run?.state).toBe("failed");
141 expect(run?.summary).toContain("could not reach");
142 expect(run?.pullDetail).toBeNull();
143 });
144
145 test("an answer that is not the contract is a failed run", async () => {
146 const odd = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => Response.json({ pulled: "many" }) });
147 const run = await schedule.pull({ ...target, port: odd.port! }, "schedule");
148 odd.stop(true);
149 expect(run?.state).toBe("failed");
150 expect(run?.summary).toContain("counts");
151 });
152
153 test("one pull at a time per app", async () => {
154 const slow = Bun.serve({
155 port: 0,
156 hostname: "127.0.0.1",
157 fetch: async () => {
158 await Bun.sleep(150);
159 return Response.json({ pulled: 0, skipped: 0, cursor: "x", errors: [] });
160 },
161 });
162 const t = { ...target, port: slow.port! };
163 const [a, b] = await Promise.all([schedule.pull(t, "schedule"), schedule.pull(t, "schedule")]);
164 slow.stop(true);
165 expect([a, b].filter((r) => r !== undefined)).toHaveLength(1);
166 });
167
168 test("the adapter reaches only its declared host: another is refused and recorded", async () => {
169 const other = new Store(":memory:");
170 const evil = Bun.serve({
171 port: 0,
172 hostname: "127.0.0.1",
173 fetch: makeHandler(other, { ...config, baseUrl: "https://evil.example.org/v1" }, guardedFetch(config.hosts, source)),
174 });
175 calls.length = 0;
176 const run = await schedule.pull({ ...target, port: evil.port! }, "schedule");
177 evil.stop(true);
178 expect(run?.state).toBe("failed");
179 expect(run?.pullDetail?.errors).toBe(1);
180 expect(calls).toEqual([]);
181 expect(other.count()).toBe(0);
182 });
183
184 test("a restart fails a pull the last forge left running", () => {
185 app.db
186 .query("INSERT INTO run (id, repo_id, kind, state) VALUES ('stuck', ?1, 'pull', 'running')")
187 .run(repoId);
188 new PullSchedule(app.db, () => []).start();
189 const stuck = listRuns(app.db, repoId, { kind: "pull" }).find((r) => r.id === "stuck");
190 expect(stuck?.state).toBe("failed");
191 });
192 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs