@nanobpm/urban-pr-review-codefirst 0.1.0

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.
package/main.ts ADDED
@@ -0,0 +1,352 @@
1
+ // urban-pr-review-codefirst — the code-first twin of `urban-pr-review`.
2
+ //
3
+ // Same behaviour, same UI, same durable multi-round convergence loop — but the
4
+ // process is authored in code (`workflows/convergence-loop.ts`, ADR 0044/0045)
5
+ // instead of a hand-drawn BPMN + manifest. `@nanobpm/workflow` derives the
6
+ // executable model, the job types and the message names from `defineFlow`.
7
+ //
8
+ // This entrypoint brings the code-first twin to full parity with the model-first
9
+ // app. It:
10
+ // 1. migrates + deploys the derived BPMN and hosts the app-owned record
11
+ // workers in-process (the `w.run` steps persist through `@nanobpm/domain`),
12
+ // 2. serves the schema-driven page runtime (ADR 0042) from `pages/home.page.json`,
13
+ // intercepting only the three app-specific actions (start/cancel/answer),
14
+ // 3. runs the review-ready poller.
15
+ //
16
+ // The reviewer agent (`convergence-loop:review-round`) is deliberately NOT hosted
17
+ // here — it is an EXTERNAL worker. Point a coding-agent harness at that job type
18
+ // (e.g. `c8ctl nano hire`) so the automated review stays decoupled from the
19
+ // durable orchestration.
20
+ import { externalJobTypes, Worker, WorkflowClient } from "@nanobpm/workflow";
21
+ import type { JsonObject } from "@nanobpm/workflow";
22
+ import { openDomain } from "@nanobpm/domain";
23
+ import { createPagesHandler } from "@nanobpm/app";
24
+ import { convergenceLoop } from "./workflows/convergence-loop.ts";
25
+
26
+ const BASE_URL = (Deno.env.get("NANOBPMN_BASE_URL") ?? "http://localhost:8080").replace(/\/+$/, "");
27
+ const PORT = Number(Deno.env.get("PR_REVIEW_PORT") ?? 3000);
28
+ const POLL_MS = Number(Deno.env.get("NANO_PR_POLL_MS") ?? 60_000);
29
+ const MAX_ROUNDS = Number(Deno.env.get("NANO_PR_MAX_ROUNDS") ?? 10);
30
+ const GITHUB_TOKEN = Deno.env.get("GITHUB_TOKEN") ?? "";
31
+ const WEBHOOK_SECRET = Deno.env.get("NANO_PR_WEBHOOK_SECRET") ?? "";
32
+
33
+ // ── helpers ──────────────────────────────────────────────────────────────────
34
+ const now = () => new Date().toISOString();
35
+ const json = (body: unknown, status = 200) =>
36
+ new Response(JSON.stringify(body), {
37
+ status,
38
+ headers: { "content-type": "application/json" },
39
+ });
40
+
41
+ /** Run pending `db/migrations/*.sql` through the generated data gateway (records
42
+ * them in the `_nano_migrations` ledger), so `deno task start` comes up against a
43
+ * correct schema without a manual `deno task purge` first. Idempotent. */
44
+ async function migrateDb(): Promise<void> {
45
+ const cmd = new Deno.Command("deno", {
46
+ args: ["run", "--allow-read", "--allow-write", "--allow-env", "nano-generated/data-cli.ts"],
47
+ stdin: "piped",
48
+ stdout: "piped",
49
+ stderr: "inherit",
50
+ });
51
+ const child = cmd.spawn();
52
+ const w = child.stdin.getWriter();
53
+ await w.write(new TextEncoder().encode(JSON.stringify({ op: "migrate" })));
54
+ await w.close();
55
+ const { stdout } = await child.output();
56
+ const out = new TextDecoder().decode(stdout).trim();
57
+ try {
58
+ const parsed = JSON.parse(out) as { ok: boolean; applied?: string[]; error?: string };
59
+ if (!parsed.ok) throw new Error(parsed.error ?? "unknown error");
60
+ console.log(`migrated app db (${(parsed.applied ?? []).length} file(s) applied)`);
61
+ } catch (err) {
62
+ console.error(`migrate failed: ${err} — output: ${out}`);
63
+ throw err;
64
+ }
65
+ }
66
+
67
+ /** Cancel a running engine instance via the Camunda v2 REST endpoint. */
68
+ async function cancelInstance(processInstanceKey: string): Promise<void> {
69
+ const res = await fetch(`${BASE_URL}/v2/process-instances/${processInstanceKey}/cancellation`, {
70
+ method: "POST",
71
+ headers: { "content-type": "application/json" },
72
+ body: "{}",
73
+ });
74
+ if (!res.ok) {
75
+ throw new Error(`cancel ${processInstanceKey}: ${res.status} ${await res.text().catch(() => "")}`);
76
+ }
77
+ }
78
+
79
+ /** Parse "owner/repo#123" or a canonical PR URL into its parts. */
80
+ function parsePr(input: string): { repo: string; number: number; url: string; prKey: string } | null {
81
+ const s = input.trim();
82
+ let m = s.match(/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/i);
83
+ if (m) {
84
+ const repo = `${m[1]}/${m[2]}`;
85
+ const number = Number(m[3]);
86
+ return { repo, number, url: `https://github.com/${repo}/pull/${number}`, prKey: `${repo}#${number}` };
87
+ }
88
+ m = s.match(/^([^/]+\/[^#]+)#(\d+)$/);
89
+ if (m) {
90
+ const repo = m[1];
91
+ const number = Number(m[2]);
92
+ return { repo, number, url: `https://github.com/${repo}/pull/${number}`, prKey: `${repo}#${number}` };
93
+ }
94
+ return null;
95
+ }
96
+
97
+ // ── boot ───────────────────────────────────────────────────────────────────
98
+ // 1) Migrate the app database (idempotent — only pending files apply), then
99
+ // deploy the derived BPMN and host the app-owned `w.run` workers in-process.
100
+ await migrateDb();
101
+
102
+ const wf = new WorkflowClient({ baseUrl: BASE_URL });
103
+ await wf.deploy(convergenceLoop);
104
+ console.log(`deployed ${convergenceLoop.id}`);
105
+
106
+ const worker = new Worker({
107
+ baseUrl: BASE_URL,
108
+ workflows: [convergenceLoop],
109
+ onError: (err) => console.error("worker error:", err.message),
110
+ });
111
+ worker.start();
112
+
113
+ for (const jt of externalJobTypes(convergenceLoop)) {
114
+ console.log(`external job type (host it yourself, e.g. a coding-agent harness): ${jt}`);
115
+ }
116
+
117
+ // The app's own sqlite datasource as a typed data object — the same store the
118
+ // `w.run` handlers persist through, read here for the poller + action overrides.
119
+ const db = await openDomain("app");
120
+
121
+ // The prompt asset is read once at submit time and carried on the instance, so a
122
+ // PR keeps the instructions it started with for its whole run.
123
+ const REVIEW_PROMPT = await Deno.readTextFile("prompts/review-round.md").catch(() => "");
124
+
125
+ /** Register a PR row (if new) and start the convergence process. Idempotent on prKey. */
126
+ async function submitPr(repo: string, number: number, url: string, prKey: string) {
127
+ const existing = await db.pull_requests.get(prKey);
128
+ if (existing && !["converged", "abandoned"].includes(existing.status)) {
129
+ return { prKey, alreadyRunning: true };
130
+ }
131
+ const ts = now();
132
+ if (existing) {
133
+ // Re-open a previously converged/abandoned PR for a fresh convergence run.
134
+ await db.pull_requests.update(prKey, {
135
+ status: "converging", current_round: 1, url,
136
+ waiting_since: null, last_review_id: null, outcome: null, converged_at: null,
137
+ updated_at: ts,
138
+ });
139
+ } else {
140
+ await db.pull_requests.insert({
141
+ pr_key: prKey, repo, number, url, status: "converging", current_round: 1,
142
+ created_at: ts, updated_at: ts,
143
+ });
144
+ }
145
+ // `client.start` seeds a declarative flow's instance variables directly, and
146
+ // derives the message correlation from the `prKey` variable.
147
+ const { processInstanceKey } = await wf.start(convergenceLoop, {
148
+ repo, prNumber: number, prUrl: url, prKey, round: 1, maxRounds: MAX_ROUNDS, prompt: REVIEW_PROMPT,
149
+ });
150
+ if (processInstanceKey != null) {
151
+ await db.pull_requests.update(prKey, { process_key: String(processInstanceKey) });
152
+ }
153
+ return { prKey, processKey: processInstanceKey };
154
+ }
155
+
156
+ /** Answer an open escalation → record it and resume the process at `wait-answer`. */
157
+ async function answerEscalation(prKey: string, answer: string) {
158
+ const open = (await db.escalations.find({ pr_key: prKey, status: "open" }))
159
+ .sort((a, b) => b.id - a.id)[0];
160
+ if (!open) return { ok: false, reason: "no open escalation" };
161
+ const escalationId = open.id;
162
+ const ts = now();
163
+ await db.escalations.update(escalationId, { answer, status: "answered", answered_at: ts });
164
+ await db.pull_requests.update(prKey, {
165
+ status: "converging", updated_at: ts,
166
+ open_escalation_id: null, open_escalation_question: null,
167
+ });
168
+ // Correlate the `wait-answer` signal (derived message `convergence-loop:wait-answer`)
169
+ // to the parked instance by its `prKey`.
170
+ await wf.signal(convergenceLoop, "wait-answer", prKey, { answer, escalationId });
171
+ return { ok: true, escalationId };
172
+ }
173
+
174
+ /** Cancel a PR's running convergence instance and mark it abandoned. Terminating
175
+ * the engine instance emits no completion event (no worker runs), so the app-tier
176
+ * flips the PR's status here. */
177
+ async function cancelRun(processInstanceKey: string) {
178
+ const [pr] = await db.pull_requests.find({ process_key: processInstanceKey });
179
+ try {
180
+ await cancelInstance(processInstanceKey);
181
+ } catch (err) {
182
+ // The instance may already be gone (converged/cancelled) — still reconcile
183
+ // the app row so a stale "converging" PR can't linger in the UI.
184
+ console.warn(`[cancel] engine cancel for ${processInstanceKey}: ${err}`);
185
+ }
186
+ if (pr) {
187
+ await db.pull_requests.update(String(pr.pr_key), {
188
+ status: "abandoned", updated_at: now(),
189
+ open_escalation_id: null, open_escalation_question: null,
190
+ });
191
+ return { ok: true, prKey: pr.pr_key };
192
+ }
193
+ return { ok: false, reason: "no PR for that instance" };
194
+ }
195
+
196
+ // ── review-ready poller ───────────────────────────────────────────────────────
197
+ async function pollOnce() {
198
+ if (!GITHUB_TOKEN) return; // no token → poller idles (webhook/manual still work)
199
+ const waiting = await db.pull_requests.find({ status: "waiting_review" });
200
+ for (const pr of waiting) {
201
+ const { repo, number, pr_key: prKey } = pr;
202
+ const lastId = pr.last_review_id ?? 0;
203
+ try {
204
+ const r = await fetch(`https://api.github.com/repos/${repo}/pulls/${number}/reviews?per_page=100`, {
205
+ headers: { authorization: `Bearer ${GITHUB_TOKEN}`, accept: "application/vnd.github+json" },
206
+ });
207
+ if (!r.ok) continue;
208
+ const reviews = (await r.json()) as Array<{ id: number; state: string; submitted_at?: string }>;
209
+ const fresh = reviews
210
+ .filter((rv) => rv.id > lastId && rv.submitted_at && (!pr.waiting_since || rv.submitted_at >= pr.waiting_since))
211
+ .sort((a, b) => a.id - b.id)
212
+ .pop();
213
+ if (!fresh) continue;
214
+ await db.pull_requests.update(prKey, {
215
+ last_review_id: fresh.id, status: "converging", updated_at: now(),
216
+ });
217
+ // Resume the instance parked at `wait-review` (derived message
218
+ // `convergence-loop:wait-review`), then it loops back to review-round.
219
+ await wf.signal(convergenceLoop, "wait-review", prKey, {
220
+ reviewId: fresh.id, reviewState: fresh.state, submittedAt: fresh.submitted_at ?? null,
221
+ });
222
+ console.log(`[poller] review ${fresh.id} (${fresh.state}) → ${prKey}`);
223
+ } catch (err) {
224
+ console.error(`[poller] ${prKey}: ${err}`);
225
+ }
226
+ }
227
+ }
228
+ const pollTimer = setInterval(() => void pollOnce(), POLL_MS);
229
+
230
+ // ── HTTP: schema-driven page runtime (ADR 0042) + app-specific action overrides ──
231
+ // The screen is authored declaratively in `pages/home.page.json` and served by the
232
+ // generic Urban page runtime — no hand-written SPA or list/detail API. Only the
233
+ // three actions that carry *app-specific* business logic are intercepted here; the
234
+ // runtime handles rendering, data, filtering and the rest.
235
+ //
236
+ // The injected engine adapter bridges the generic runtime to the code-first
237
+ // surface: cancel/publish hit the gateway's Camunda v2 REST endpoints directly,
238
+ // and createProcessInstance delegates to the workflow client. In practice all
239
+ // three page actions are overridden below, so the adapter only backstops any
240
+ // non-overridden action the runtime might serve.
241
+ const pagesHandler = createPagesHandler({
242
+ db: db.raw,
243
+ nano: {
244
+ createProcessInstance: async (input) => {
245
+ // Runtime contract boundary: the generic page runtime hands us loosely-typed
246
+ // variables (Record<string, unknown>); the workflow client wants a JsonObject.
247
+ const vars = (input.variables ?? {}) as JsonObject;
248
+ const { processInstanceKey } = await wf.start(convergenceLoop, vars);
249
+ return { processInstanceKey };
250
+ },
251
+ cancelProcessInstance: (input) => cancelInstance(String(input.processInstanceKey)),
252
+ publishMessage: async (input) => {
253
+ const res = await fetch(`${BASE_URL}/v2/messages/publication`, {
254
+ method: "POST",
255
+ headers: { "content-type": "application/json" },
256
+ body: JSON.stringify({
257
+ name: input.name,
258
+ correlationKey: input.correlationKey,
259
+ variables: input.variables ?? {},
260
+ }),
261
+ });
262
+ if (!res.ok) throw new Error(`publishMessage ${input.name}: ${res.status}`);
263
+ return res.json().catch(() => ({}));
264
+ },
265
+ },
266
+ pagesDir: "pages",
267
+ homePage: "home",
268
+ sourceName: "app",
269
+ });
270
+
271
+ Deno.serve({ port: PORT }, async (req) => {
272
+ const url = new URL(req.url);
273
+ const { pathname } = url;
274
+
275
+ // Override: start the convergence loop for a PR. Parse the PR reference and
276
+ // create the aggregate before starting the instance.
277
+ if (req.method === "POST" && pathname === "/app/actions/start/convergence-loop") {
278
+ const body = await req.json().catch(() => ({} as Record<string, unknown>));
279
+ const vars = (body.variables ?? {}) as Record<string, unknown>;
280
+ const raw = String((vars.pr ?? vars.url ?? "") as string).trim();
281
+ const parsed = parsePr(raw);
282
+ if (!parsed) return json({ error: "could not parse PR (use owner/repo#123 or a PR URL)" }, 400);
283
+ return json(await submitPr(parsed.repo, parsed.number, parsed.url, parsed.prKey), 202);
284
+ }
285
+
286
+ // Override: cancel a run. Terminating the instance emits no completion event, so
287
+ // reconcile the app row (status='abandoned', clear open escalation) here.
288
+ if (req.method === "POST" && pathname === "/app/actions/cancel") {
289
+ const body = await req.json().catch(() => ({} as Record<string, unknown>));
290
+ const key = body.processInstanceKey;
291
+ if (key == null || String(key) === "") return json({ error: "processInstanceKey is required" }, 400);
292
+ const r = await cancelRun(String(key));
293
+ return json(r, r.ok ? 200 : 404);
294
+ }
295
+
296
+ // Override: answer an escalation (signal `wait-answer`). Runs the app's answer
297
+ // flow (record the answer, clear the open escalation) instead of a bare publish.
298
+ if (req.method === "POST" && pathname === "/app/actions/message") {
299
+ const body = await req.json().catch(() => ({} as Record<string, unknown>));
300
+ if (String(body.name ?? "") === "escalation-answered") {
301
+ const prKey = String(body.correlationKey ?? "");
302
+ const vars = (body.variables ?? {}) as Record<string, unknown>;
303
+ const answer = String((vars.answer ?? "") as string).trim();
304
+ if (!prKey) return json({ error: "correlationKey is required" }, 400);
305
+ if (!answer) return json({ error: "answer is required" }, 400);
306
+ const r = await answerEscalation(prKey, answer);
307
+ return json(r, r.ok ? 200 : 404);
308
+ }
309
+ // Fall through to the generic runtime for any other message.
310
+ }
311
+
312
+ // Webhook: submit (shared-secret auth via X-Hook-Secret). Not part of the page UI.
313
+ if (req.method === "POST" && pathname === "/hooks/submit") {
314
+ if (WEBHOOK_SECRET && req.headers.get("x-hook-secret") !== WEBHOOK_SECRET) {
315
+ return json({ error: "unauthorized" }, 401);
316
+ }
317
+ const body = await req.json().catch(() => ({} as Record<string, unknown>));
318
+ const parsed = parsePr(String((body.url ?? body.pr ?? "") as string));
319
+ if (!parsed) return json({ error: "could not parse PR url" }, 400);
320
+ return json(await submitPr(parsed.repo, parsed.number, parsed.url, parsed.prKey), 202);
321
+ }
322
+
323
+ // Everything else — the screen, its data, filtering, and the non-overridden
324
+ // actions — is served by the generic page runtime.
325
+ return pagesHandler(req);
326
+ });
327
+
328
+ console.log(
329
+ `urban-pr-review-codefirst serving on :${PORT} against ${BASE_URL} (poll ${POLL_MS}ms, maxRounds ${MAX_ROUNDS})`,
330
+ );
331
+
332
+ // ── graceful shutdown ─────────────────────────────────────────────────────────
333
+ let shuttingDown = false;
334
+ const drainAndExit = async () => {
335
+ if (shuttingDown) return;
336
+ shuttingDown = true;
337
+ console.log("\nshutting down…");
338
+ clearInterval(pollTimer);
339
+ await worker.stop();
340
+ db.close();
341
+ Deno.exit(0);
342
+ };
343
+ const shutdown = (): void => {
344
+ void drainAndExit();
345
+ };
346
+ for (const sig of ["SIGINT", "SIGTERM"] as const) {
347
+ try {
348
+ Deno.addSignalListener(sig, shutdown);
349
+ } catch {
350
+ // Signal not supported on this OS (e.g. SIGTERM on Windows) — skip it.
351
+ }
352
+ }