@topline-build/harness-mcp 0.9.16 → 0.9.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,244 @@
1
+ import { mkdirSync, writeFileSync } from "node:fs";
2
+ import path from "node:path";
3
+
4
+ // Starter from the Build cookbook recipe "table-approvals-app": people submit
5
+ // requests, see their own, and approvers decide them. Every read and write runs
6
+ // in this server code through server table SQL (manifest `serverTables: true`);
7
+ // the manifest declares no `tables[]`, so the browser can't list rows itself.
8
+ // Create the two tables first (the recipe has the SQL), then rename them here.
9
+ const TITLE = "__ARTIFACT_TITLE__";
10
+ const REQUESTS = "company_data.approval_requests";
11
+ const APPROVERS = "company_data.approval_approvers";
12
+ const STATUSES = ["approved", "rejected"];
13
+
14
+ /** POST one statement to the platform's server table SQL endpoint. Server code only. */
15
+ export async function tablesSql(req, sql, params = {}, actingUser) {
16
+ const url = header(req, "x-platform-tables-sql-url");
17
+ const token = header(req, "x-platform-tables-token");
18
+ if (!url || !token) throw Object.assign(new Error("server_tables_unavailable"), { status: 503 });
19
+ const response = await fetch(url, {
20
+ method: "POST",
21
+ headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
22
+ body: JSON.stringify({ sql, params, ...(actingUser ? { actingUser } : {}) })
23
+ });
24
+ const body = await response.json().catch(() => ({}));
25
+ if (!response.ok || body.ok === false) {
26
+ const code = `${body.error ?? `table_sql_http_${response.status}`}${body.sqlstate ? `:${body.sqlstate}` : ""}`;
27
+ throw Object.assign(new Error(code), { status: response.status, hint: body.hint });
28
+ }
29
+ // Every value comes back as a string; convert what you need.
30
+ return { rows: body.rows ?? [], rowCount: Number(body.rowCount ?? 0) };
31
+ }
32
+
33
+ function header(req, name) {
34
+ const value = req.headers?.[name];
35
+ return Array.isArray(value) ? value[0] : value;
36
+ }
37
+
38
+ const LIST_COLUMNS = `_row_id as id, _version as version, requester_email, title, details, status, decided_by, decision_note,
39
+ to_char(_created_at at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') as created_at`;
40
+
41
+ /** The app's rules, over an injected `sql(statement, params)` so --test can run them without a table. */
42
+ export function approvalsService(sql, viewer) {
43
+ const email = String(viewer ?? "").trim().toLowerCase();
44
+ async function isApprover() {
45
+ const { rows } = await sql(`select 1 as ok from ${APPROVERS} where lower(email) = :email and active and _deleted_at is null limit 1`, { email });
46
+ return rows.length > 0;
47
+ }
48
+ return {
49
+ async overview() {
50
+ const approver = await isApprover();
51
+ const mine = await sql(`select ${LIST_COLUMNS} from ${REQUESTS} where lower(requester_email) = :email and _deleted_at is null order by _created_at desc limit 200`, { email });
52
+ const queue = approver
53
+ ? await sql(`select ${LIST_COLUMNS} from ${REQUESTS} where status = 'pending' and _deleted_at is null order by _created_at limit 200`, {})
54
+ : { rows: [] };
55
+ return { status: 200, body: { ready: true, viewer: email, approver, mine: mine.rows, queue: queue.rows } };
56
+ },
57
+ async submit(input) {
58
+ const title = typeof input?.title === "string" ? input.title.trim() : "";
59
+ const details = typeof input?.details === "string" ? input.details.trim() : "";
60
+ if (!title || title.length > 200 || details.length > 4000) return { status: 400, body: { error: "invalid_request", fields: ["title (1-200 characters)", "details (up to 4000)"] } };
61
+ await sql(`insert into ${REQUESTS} (requester_email, title, details, status) values (:email, :title, :details, 'pending')`, { email, title, details });
62
+ return { status: 201, body: { ok: true } };
63
+ },
64
+ async decide(input) {
65
+ const id = typeof input?.id === "string" ? input.id : "";
66
+ const version = Number(input?.version);
67
+ const status = input?.decision;
68
+ const note = typeof input?.note === "string" ? input.note.trim().slice(0, 2000) : "";
69
+ if (!/^[0-9a-f-]{36}$/i.test(id) || !Number.isInteger(version) || !STATUSES.includes(status)) return { status: 400, body: { error: "invalid_decision" } };
70
+ if (status === "rejected" && !note) return { status: 400, body: { error: "note_required" } };
71
+ if (!(await isApprover())) return { status: 403, body: { error: "approver_required" } };
72
+ const { rowCount } = await sql(
73
+ `update ${REQUESTS} set status = :status, decided_by = :email, decided_at = CAST(:now AS timestamptz), decision_note = :note
74
+ where _row_id = :id and _version = :version and status = 'pending' and lower(requester_email) <> :email and _deleted_at is null`,
75
+ { status, email, now: new Date().toISOString(), note, id, version }
76
+ );
77
+ if (rowCount > 0) return { status: 200, body: { ok: true } };
78
+ const { rows } = await sql(`select ${LIST_COLUMNS} from ${REQUESTS} where _row_id = :id`, { id });
79
+ const row = rows[0];
80
+ if (!row) return { status: 404, body: { error: "request_not_found" } };
81
+ if (String(row.requester_email).toLowerCase() === email) return { status: 403, body: { error: "cannot_decide_own_request" } };
82
+ return { status: 409, body: { error: "request_changed", row } };
83
+ }
84
+ };
85
+ }
86
+
87
+ async function readJson(req) {
88
+ if (req.body !== undefined) return typeof req.body === "string" ? JSON.parse(req.body || "{}") : req.body;
89
+ const chunks = [];
90
+ for await (const chunk of req) chunks.push(Buffer.from(chunk));
91
+ const text = Buffer.concat(chunks).toString("utf8");
92
+ return text ? JSON.parse(text) : {};
93
+ }
94
+
95
+ function send(res, status, body) {
96
+ res.statusCode = status;
97
+ res.setHeader("content-type", "application/json; charset=utf-8");
98
+ res.setHeader("cache-control", "no-store");
99
+ res.end(JSON.stringify(body));
100
+ }
101
+
102
+ export async function artifactApp(req, res) {
103
+ const url = new URL(req.url ?? "/", "http://artifact.local");
104
+ const method = req.method ?? "GET";
105
+ const api = ["/_artifact/api/requests", "/_artifact/api/decisions"].find((route) => url.pathname.endsWith(route));
106
+ if (!api) {
107
+ res.setHeader("content-type", "text/html; charset=utf-8");
108
+ res.end(page);
109
+ return;
110
+ }
111
+ const viewer = header(req, "x-platform-viewer-email");
112
+ if (!viewer) return send(res, 401, { error: "viewer_required" });
113
+ const service = approvalsService((statement, params) => tablesSql(req, statement, params, viewer), viewer);
114
+ try {
115
+ let result;
116
+ if (api === "/_artifact/api/requests" && method === "GET") result = await service.overview();
117
+ else if (api === "/_artifact/api/requests" && method === "POST") result = await service.submit(await readJson(req));
118
+ else if (api === "/_artifact/api/decisions" && method === "POST") result = await service.decide(await readJson(req));
119
+ else return send(res, 405, { error: "method_not_allowed" });
120
+ send(res, result.status, result.body);
121
+ } catch (error) {
122
+ const code = error instanceof Error ? error.message : "request_failed";
123
+ // Before the tables exist (or on a sandbox preview) answer 200 with a setup state,
124
+ // so the page and the smoke check stay healthy and say what is missing.
125
+ const notSetUp = ["server_tables_unavailable", "server_tables_not_declared", "company_table_not_found", "company_table_sql_failed:42P01"];
126
+ if (method === "GET" && notSetUp.some((prefix) => code.startsWith(prefix))) {
127
+ return send(res, 200, { ready: false, reason: code });
128
+ }
129
+ if (code.startsWith("preview_writes_not_allowed")) return send(res, 403, { error: "draft_is_read_only" });
130
+ console.error(`[approvals] ${code}`);
131
+ send(res, error?.status && error.status < 500 ? 400 : 502, { error: "request_failed", code });
132
+ }
133
+ }
134
+
135
+ const escapeHtml = (value) => String(value).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
136
+
137
+ const page = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
138
+ <title>${escapeHtml(TITLE)}</title>
139
+ <style>
140
+ body{font:15px/1.5 system-ui,sans-serif;margin:0;color:#1d1d1b;background:#fafaf7}main{max-width:880px;margin:0 auto;padding:24px 16px}
141
+ h1{font-size:24px;margin:0 0 4px}h2{font-size:17px;margin:28px 0 8px}form,li{background:#fff;border:1px solid #dcdcd4;border-radius:8px;padding:12px}
142
+ label{display:block;font-weight:600;margin-top:8px}input,textarea{width:100%;box-sizing:border-box;font:inherit;padding:6px;margin-top:4px}
143
+ button{font:inherit;margin-top:10px;padding:6px 12px;cursor:pointer}ul{list-style:none;padding:0;display:grid;gap:8px}
144
+ .meta{color:#5d5d55;font-size:13px}.status{font-weight:600;text-transform:capitalize}[role=alert]{color:#a22}
145
+ </style></head><body><main data-platform-artifact-root>
146
+ <h1>${escapeHtml(TITLE)}</h1><p class="meta" id="state">Loading requests...</p>
147
+ <section aria-labelledby="new-h"><h2 id="new-h">New request</h2>
148
+ <form id="new"><label for="title">Title</label><input id="title" name="title" maxlength="200" required>
149
+ <label for="details">Details</label><textarea id="details" name="details" rows="3" maxlength="4000"></textarea>
150
+ <button type="submit">Submit request</button><p id="new-msg" role="status"></p></form></section>
151
+ <section aria-labelledby="mine-h"><h2 id="mine-h">My requests</h2><ul id="mine"></ul></section>
152
+ <section aria-labelledby="queue-h" id="queue-section" hidden><h2 id="queue-h">Waiting for your decision</h2><ul id="queue"></ul></section>
153
+ </main><script type="module">
154
+ const api = (p) => new URL("_artifact/api/" + p, document.baseURI);
155
+ const esc = (v) => String(v ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
156
+ const state = document.getElementById("state");
157
+ function item(r, decide) {
158
+ const note = r.decision_note ? '<div class="meta">Note: ' + esc(r.decision_note) + '</div>' : "";
159
+ const who = decide ? esc(r.requester_email) + " - " : "";
160
+ const actions = decide ? '<label>Note (required to reject)<input data-note></label><button data-d="approved">Approve</button> <button data-d="rejected">Reject</button><p role="alert"></p>' : "";
161
+ return '<li data-id="' + esc(r.id) + '" data-version="' + esc(r.version) + '"><strong>' + esc(r.title) + '</strong> <span class="status">' + esc(r.status) + '</span>'
162
+ + '<div class="meta">' + who + esc(r.created_at) + (r.decided_by ? " - decided by " + esc(r.decided_by) : "") + '</div>'
163
+ + (r.details ? '<div>' + esc(r.details) + '</div>' : "") + note + actions + '</li>';
164
+ }
165
+ async function load() {
166
+ const res = await fetch(api("requests"), { cache: "no-store" });
167
+ const data = await res.json().catch(() => ({}));
168
+ if (!res.ok) { state.textContent = "Requests could not load (" + (data.code || data.error || res.status) + ")."; return; }
169
+ if (!data.ready) { state.textContent = "Not set up yet: the request tables don't exist or server table access is off (" + esc(data.reason) + ")."; return; }
170
+ state.textContent = data.approver ? "You can submit requests and decide others' requests." : "You can submit requests and follow their status.";
171
+ document.getElementById("mine").innerHTML = data.mine.length ? data.mine.map((r) => item(r, false)).join("") : "<li>No requests yet.</li>";
172
+ document.getElementById("queue-section").hidden = !data.approver;
173
+ document.getElementById("queue").innerHTML = data.queue.length ? data.queue.map((r) => item(r, true)).join("") : "<li>Nothing is waiting.</li>";
174
+ }
175
+ document.getElementById("new").addEventListener("submit", async (e) => {
176
+ e.preventDefault();
177
+ const msg = document.getElementById("new-msg");
178
+ const res = await fetch(api("requests"), { method: "POST", headers: { "content-type": "application/json" },
179
+ body: JSON.stringify({ title: e.target.title.value, details: e.target.details.value }) });
180
+ const data = await res.json().catch(() => ({}));
181
+ msg.textContent = res.ok ? "Submitted." : "Not submitted (" + (data.code || data.error || res.status) + ").";
182
+ if (res.ok) { e.target.reset(); load(); }
183
+ });
184
+ document.getElementById("queue").addEventListener("click", async (e) => {
185
+ const button = e.target.closest("button[data-d]"); if (!button) return;
186
+ const li = button.closest("li");
187
+ const res = await fetch(api("decisions"), { method: "POST", headers: { "content-type": "application/json" },
188
+ body: JSON.stringify({ id: li.dataset.id, version: Number(li.dataset.version), decision: button.dataset.d, note: li.querySelector("[data-note]").value }) });
189
+ const data = await res.json().catch(() => ({}));
190
+ if (res.ok) return load();
191
+ li.querySelector("[role=alert]").textContent = res.status === 409 ? "Someone changed this request first; reloading." : "Not saved (" + (data.code || data.error) + ").";
192
+ if (res.status === 409) setTimeout(load, 1200);
193
+ });
194
+ load();
195
+ </script></body></html>`;
196
+
197
+ async function scaffoldChecks() {
198
+ // A fake table, so the app's rules run without a deployment. Not proof of the deployed app.
199
+ const rows = [{ id: "00000000-0000-4000-8000-000000000001", version: "1", requester_email: "sam@example.com", status: "pending" }];
200
+ const approvers = new Set(["ana@example.com"]);
201
+ const fake = async (statement, params) => {
202
+ if (statement.includes(APPROVERS)) return { rows: approvers.has(params.email) ? [{ ok: "1" }] : [], rowCount: 0 };
203
+ if (statement.startsWith("insert")) { rows.push({ id: "new", version: "1", requester_email: params.email, status: "pending" }); return { rows: [], rowCount: 1 }; }
204
+ if (statement.startsWith("update")) {
205
+ const row = rows.find((r) => r.id === params.id && Number(r.version) === params.version && r.status === "pending" && r.requester_email !== params.email);
206
+ if (row) { row.status = params.status; row.version = String(params.version + 1); }
207
+ return { rows: [], rowCount: row ? 1 : 0 };
208
+ }
209
+ if (statement.includes("where _row_id = :id")) return { rows: rows.filter((r) => r.id === params.id), rowCount: 0 };
210
+ return { rows: rows.filter((r) => r.status === "pending"), rowCount: 0 };
211
+ };
212
+ const sam = approvalsService(fake, "sam@example.com");
213
+ const ana = approvalsService(fake, "ana@example.com");
214
+ const results = [
215
+ ["a request without a title is refused", (await sam.submit({ title: " " })).status === 400],
216
+ ["a person submits a request", (await sam.submit({ title: "Day off", details: "Friday" })).status === 201],
217
+ ["a non-approver cannot decide", (await sam.decide({ id: rows[0].id, version: 1, decision: "approved" })).status === 403],
218
+ ["rejecting needs a note", (await ana.decide({ id: rows[0].id, version: 1, decision: "rejected" })).status === 400],
219
+ ["an approver approves the version they saw", (await ana.decide({ id: rows[0].id, version: 1, decision: "approved" })).status === 200],
220
+ ["a stale decision gets 409", (await ana.decide({ id: rows[0].id, version: 1, decision: "approved" })).status === 409]
221
+ ];
222
+ return [
223
+ { description: "Scaffold check: the page renders a visible app root.", required: true, status: page.includes("data-platform-artifact-root") ? "passed" : "failed", summary: "Generated starter check; not proof of implemented behavior.", evidence: { selector: "data-platform-artifact-root", scaffold: true } },
224
+ ...results.map(([name, ok]) => ({ description: `Scaffold check: ${name} (fake table).`, required: false, status: ok ? "passed" : "failed", summary: "Starter rule check against an in-memory table; replace with checks of your real rules.", evidence: { scaffold: true } }))
225
+ ];
226
+ }
227
+
228
+ if (process.argv.includes("--build")) {
229
+ mkdirSync("dist", { recursive: true });
230
+ writeFileSync(path.join("dist", "index.html"), page, "utf8");
231
+ }
232
+
233
+ if (process.argv.includes("--test")) {
234
+ const tests = await scaffoldChecks();
235
+ if (process.argv.includes("--artifact-tests-json")) console.log(JSON.stringify({ tests }));
236
+ else {
237
+ const failed = tests.filter((test) => test.status !== "passed");
238
+ for (const test of failed) console.error(`failed: ${test.description}`);
239
+ if (failed.length) process.exitCode = 1;
240
+ else console.log("artifact app starter ok");
241
+ }
242
+ } else if (process.argv.includes("--build")) {
243
+ console.log("artifact app starter ok");
244
+ }