@nanobpm/urban-pr-review-codefirst 1.1.0 → 1.2.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/.github/workflows/ci.yml +40 -0
- package/CHANGELOG.md +7 -0
- package/README.md +75 -36
- package/actions/cancel.ts +16 -0
- package/actions/message.ts +34 -0
- package/actions/start.ts +17 -0
- package/actions/webhook-submit.ts +19 -0
- package/app/engine.ts +22 -0
- package/app/github.ts +92 -0
- package/app/rows.ts +47 -0
- package/app/service.ts +164 -0
- package/deno.json +9 -8
- package/deno.lock +44 -9
- package/main.ts +61 -318
- package/nano-ide.ext.json +1 -1
- package/nano.app.json +27 -1
- package/nanobpm.project.json +8 -9
- package/package.json +20 -11
- package/scripts/answer.ts +6 -6
- package/scripts/purge-db.ts +45 -59
- package/scripts/review-ready.ts +6 -6
- package/scripts/submit.ts +7 -7
- package/tsconfig.json +2 -1
- package/workflows/convergence-loop.ts +65 -53
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
pull_request:
|
|
5
|
+
branches: [main]
|
|
6
|
+
push:
|
|
7
|
+
branches: [main]
|
|
8
|
+
|
|
9
|
+
permissions:
|
|
10
|
+
contents: read
|
|
11
|
+
|
|
12
|
+
jobs:
|
|
13
|
+
typecheck:
|
|
14
|
+
name: typecheck (Node + Deno)
|
|
15
|
+
runs-on: ubuntu-latest
|
|
16
|
+
steps:
|
|
17
|
+
- name: Checkout
|
|
18
|
+
uses: actions/checkout@v4
|
|
19
|
+
|
|
20
|
+
- name: Setup Node.js
|
|
21
|
+
uses: actions/setup-node@v4
|
|
22
|
+
with:
|
|
23
|
+
node-version: "24"
|
|
24
|
+
|
|
25
|
+
- name: Install dependencies
|
|
26
|
+
run: npm ci
|
|
27
|
+
|
|
28
|
+
- name: Typecheck (Node / tsc)
|
|
29
|
+
run: npm run typecheck
|
|
30
|
+
|
|
31
|
+
- name: Validate manifest (urban check)
|
|
32
|
+
run: npm run check
|
|
33
|
+
|
|
34
|
+
- name: Setup Deno
|
|
35
|
+
uses: denoland/setup-deno@v2
|
|
36
|
+
with:
|
|
37
|
+
deno-version: v2.x
|
|
38
|
+
|
|
39
|
+
- name: Typecheck (Deno)
|
|
40
|
+
run: deno check main.ts 'workflows/**/*.ts'
|
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
# [1.2.0](https://github.com/jwulf/urban-pr-review-codefirst/compare/v1.1.0...v1.2.0) (2026-08-03)
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
### Features
|
|
5
|
+
|
|
6
|
+
* **poller:** read GitHub reviews via the host `gh` CLI ([#6](https://github.com/jwulf/urban-pr-review-codefirst/issues/6)) ([5d50416](https://github.com/jwulf/urban-pr-review-codefirst/commit/5d50416e778332c5d6ab70962f574124c24a2042))
|
|
7
|
+
|
|
1
8
|
# [1.1.0](https://github.com/jwulf/urban-pr-review-codefirst/compare/v1.0.0...v1.1.0) (2026-07-31)
|
|
2
9
|
|
|
3
10
|
|
package/README.md
CHANGED
|
@@ -5,9 +5,11 @@ multi-round loop that drives a GitHub PR to convergence against an automated
|
|
|
5
5
|
reviewer, escalating to a human when the reviewer is stuck or a round cap is hit.
|
|
6
6
|
|
|
7
7
|
The model-first app draws this loop in `convergence-loop.bpmn`. Here the same loop
|
|
8
|
-
is written with the
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
is written with the code-first declarative surface (`defineFlow`, ADR 0044/0045),
|
|
9
|
+
consumed through the published **[`@nanobpm/urban`](https://www.npmjs.com/package/@nanobpm/urban)**
|
|
10
|
+
runtime (which re-exports `defineFlow`/`WorkflowClient`/`Worker` alongside the data
|
|
11
|
+
+ pages + actions surfaces). The SDK derives the executable BPMN (with DI), the job
|
|
12
|
+
types, and the message names — no diagram, no task-type wiring, no correlation plumbing.
|
|
11
13
|
|
|
12
14
|
**Feature parity with the model-first app.** This app persists to the same SQLite
|
|
13
15
|
schema and serves the same schema-driven web frontend as
|
|
@@ -45,8 +47,11 @@ reviewer services both this code-first app and the model-first
|
|
|
45
47
|
|
|
46
48
|
- A running **Nano gateway/engine** (default `http://localhost:8080`). This is
|
|
47
49
|
what the app deploys to and what agents pull jobs from.
|
|
48
|
-
- **[
|
|
49
|
-
`
|
|
50
|
+
- **[Node](https://nodejs.org/)** ≥ 22.6 (to run this app — it hosts on Node's
|
|
51
|
+
built-ins: `node:sqlite`, `node:http`; `@nanobpm/urban` declares
|
|
52
|
+
`engines.node >=22.6`). **[Deno](https://deno.land/)** is *optional*, used only
|
|
53
|
+
to cross-compile a standalone binary (`npm run compile`). Also install the
|
|
54
|
+
**c8ctl CLI with the `nano` plugin** (to hire/run agents).
|
|
50
55
|
- On each machine that will *host an agent*: the **GitHub CLI** logged in
|
|
51
56
|
(`gh auth login`) or a `GITHUB_TOKEN`/`GH_TOKEN` in the environment, and the
|
|
52
57
|
agent harness itself — e.g. the **[Copilot CLI](https://github.com/github/copilot-cli)**
|
|
@@ -63,21 +68,21 @@ the console.
|
|
|
63
68
|
### 2. Start the app
|
|
64
69
|
|
|
65
70
|
```sh
|
|
66
|
-
|
|
71
|
+
npm start # → http://localhost:3000
|
|
67
72
|
```
|
|
68
73
|
|
|
69
74
|
That applies the DB migrations, deploys the derived flow, hosts the in-process
|
|
70
75
|
`w.run` record steps, serves the web UI at **<http://localhost:3000>**, and runs
|
|
71
|
-
the review-ready poller (which
|
|
72
|
-
re-reviews come only from the UI/CLI). Point it at
|
|
73
|
-
`NANOBPMN_BASE_URL`; change the port with `PR_REVIEW_PORT`.
|
|
76
|
+
the review-ready poller (which reads GitHub via the host `gh` CLI by default, or a
|
|
77
|
+
`GITHUB_TOKEN` — without either, re-reviews come only from the UI/CLI). Point it at
|
|
78
|
+
a non-default gateway with `NANOBPMN_BASE_URL`; change the port with `PR_REVIEW_PORT`.
|
|
74
79
|
|
|
75
80
|
### 3. Submit a PR
|
|
76
81
|
|
|
77
82
|
From the web UI, or from the CLI:
|
|
78
83
|
|
|
79
84
|
```sh
|
|
80
|
-
|
|
85
|
+
npm run submit -- https://github.com/owner/repo/pull/42 5 # 5 = maxRounds
|
|
81
86
|
```
|
|
82
87
|
|
|
83
88
|
Each submitted PR starts one durable `convergence-loop` instance that parks until
|
|
@@ -219,10 +224,10 @@ Requires a running Nano gateway (default `http://localhost:8080`; override with
|
|
|
219
224
|
```sh
|
|
220
225
|
# The one service: applies DB migrations, deploys the flow, hosts the app-owned
|
|
221
226
|
# w.run record steps, AND serves the web frontend + review-ready poller.
|
|
222
|
-
|
|
227
|
+
npm start # → http://localhost:3000
|
|
223
228
|
```
|
|
224
229
|
|
|
225
|
-
`
|
|
230
|
+
`npm start` now does everything: it applies the `db/migrations/` on boot
|
|
226
231
|
(creating `app.db`), deploys the flow, hosts the `persist-*` handlers, serves the
|
|
227
232
|
schema-driven page runtime at `http://localhost:3000`, and runs the review-ready
|
|
228
233
|
poller. Submit and answer PRs directly from the web UI, or drive the same actions
|
|
@@ -230,59 +235,93 @@ from the CLI:
|
|
|
230
235
|
|
|
231
236
|
```sh
|
|
232
237
|
# submit a PR (parks after review-round at wait-review or wait-answer)
|
|
233
|
-
|
|
238
|
+
npm run submit -- https://github.com/owner/repo/pull/42 5 # 5 = maxRounds
|
|
234
239
|
|
|
235
240
|
# nudge a re-review (resumes an instance parked at wait-review)
|
|
236
|
-
|
|
241
|
+
npm run review-ready -- owner/repo#42
|
|
237
242
|
|
|
238
243
|
# answer an escalation (resumes an instance parked at wait-answer)
|
|
239
|
-
|
|
244
|
+
npm run answer -- owner/repo#42 "merge as-is"
|
|
240
245
|
|
|
241
246
|
# wipe all persisted PRs/rounds/escalations (drops + re-migrates app.db)
|
|
242
|
-
|
|
247
|
+
npm run purge
|
|
243
248
|
```
|
|
244
249
|
|
|
245
|
-
The reviewer itself is not started by `
|
|
250
|
+
The reviewer itself is not started by `npm start` — it is the external
|
|
246
251
|
`senior:pr-review` job. Host it with a coding-agent harness so the automated
|
|
247
252
|
review is fully decoupled from the durable orchestration.
|
|
248
253
|
|
|
249
254
|
Environment overrides: `PR_REVIEW_PORT` (default `3000`), `NANOBPMN_BASE_URL`
|
|
250
255
|
(gateway), `NANO_APP_DB_URL` (default `file:./app.db`), `NANO_PR_POLL_MS`
|
|
251
256
|
(poller interval, default `60000`), `NANO_PR_MAX_ROUNDS` (default `10`),
|
|
252
|
-
`
|
|
253
|
-
|
|
257
|
+
`NANO_PR_GITHUB_TRANSPORT` (`auto` | `gh` | `token`, default `auto` — prefer the
|
|
258
|
+
host `gh` CLI, else the token), `GITHUB_TOKEN` (token for the `token`/`auto`
|
|
259
|
+
transport — without any usable transport the poller idles and re-reviews come
|
|
260
|
+
only from the CLI/UI).
|
|
261
|
+
|
|
262
|
+
## Compile to a native binary (no runtime install required)
|
|
263
|
+
|
|
264
|
+
The app is authored on Node's built-ins (`node:sqlite`, `node:http`, `process.env`),
|
|
265
|
+
which lets **Deno** cross-compile it into a native executable that bundles the Deno
|
|
266
|
+
runtime (its `denort` binary, which supplies the `node:*` compatibility APIs), the
|
|
267
|
+
npm dependencies and the app's entry code — so the target box needs **no
|
|
268
|
+
Node/Deno/`node_modules` install**:
|
|
269
|
+
|
|
270
|
+
```sh
|
|
271
|
+
npm run compile # → dist/urban-pr-review-codefirst (via `deno compile`)
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
> **Not (yet) a single self-contained file.** The binary bundles the runtime + deps
|
|
275
|
+
> + entry code, but the Urban runtime loads the app's declarative files —
|
|
276
|
+
> `nano.app.json`, `pages/`, `db/migrations/`, `prompts/` and the `actions/`
|
|
277
|
+
> modules — from the **working directory at runtime** (via `readTextFile` + dynamic
|
|
278
|
+
> `import`). `deno compile` *can* embed data dirs into its virtual filesystem with
|
|
279
|
+
> [`--include`](https://docs.deno.com/runtime/reference/cli/compile/#including-data-files-or-directories),
|
|
280
|
+
> but embedded files are only reachable relative to `import.meta.dirname`, whereas
|
|
281
|
+
> the runtime resolves them against `Deno.cwd()` — so today you must ship the binary
|
|
282
|
+
> **alongside those app files** and run it from that directory (it then boots
|
|
283
|
+
> identically to `npm start`, same env vars). Making a truly self-contained binary
|
|
284
|
+
> needs an *embeddable Urban app* capability in `@nanobpm/urban` (resolve the app
|
|
285
|
+
> root from `import.meta.dirname` + `--include` the non-statically-analyzable
|
|
286
|
+
> `actions/` dynamic imports), tracked separately. Add `--target` in the `deno.json`
|
|
287
|
+
> `compile` task to cross-compile for another OS/arch. (Only Node's *built-in*
|
|
288
|
+
> `node:sqlite` survives this — a native npm addon like `better-sqlite3` would not.)
|
|
289
|
+
|
|
254
290
|
|
|
255
291
|
## Persistence
|
|
256
292
|
|
|
257
293
|
Parity with the model-first app: the same three-table SQLite schema
|
|
258
294
|
(`pull_requests`, `rounds`, `escalations`), the same `db/migrations/*.sql`, and
|
|
259
|
-
the same
|
|
260
|
-
`
|
|
261
|
-
|
|
262
|
-
migrations directory
|
|
295
|
+
the same typed rows (`app/rows.ts`), written through the **`@nanobpm/urban`** data
|
|
296
|
+
layer (`DataLayer.table<T>(name, pk)`, exposing `pull_requests` / `rounds` /
|
|
297
|
+
`escalations`). The `nano.app.json` manifest declares the `app` sqlite datasource
|
|
298
|
+
(`${NANO_APP_DB_URL:-file:./app.db}`) and the migrations directory; the Urban
|
|
299
|
+
runtime provisions the datasource and applies migrations on boot.
|
|
263
300
|
|
|
264
301
|
The record steps that write these rows are the code-first counterpart of the
|
|
265
302
|
model-first `workers/{persist-round,persist-escalation,finalize}` — but instead of
|
|
266
303
|
standalone `defineWorker`s, they are the `w.run` handlers in
|
|
267
|
-
`workflows/convergence-loop.ts`, hosted **in-process** by the `@nanobpm/
|
|
268
|
-
`Worker` that `
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
304
|
+
`workflows/convergence-loop.ts`, hosted **in-process** by the `@nanobpm/urban`
|
|
305
|
+
`Worker` that `npm start` runs. Those handlers get no `AppApi`, so `main.ts`
|
|
306
|
+
injects the provisioned data layer into them via `setPersistData(app.data)` before
|
|
307
|
+
the worker starts. The thin CLI scripts (`submit`/`answer`/`review-ready`) import
|
|
308
|
+
the flow to start/signal instances without ever opening the DB — only the worker
|
|
309
|
+
host injects the data layer.
|
|
272
310
|
|
|
273
311
|
## Frontend
|
|
274
312
|
|
|
275
|
-
The same schema-driven page runtime as the model-first app (`pages/home.page.json`
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
313
|
+
The same schema-driven page runtime as the model-first app (`pages/home.page.json`),
|
|
314
|
+
served by the **`@nanobpm/urban`** pages surface at `http://localhost:3000`. It
|
|
315
|
+
lists active + historical PRs, submits new ones, and answers or cancels runs
|
|
316
|
+
inline. Because both apps commit the identical page schema, the UI is byte-for-byte
|
|
317
|
+
the same; the code-first action bindings in `actions/*` (`start` → `wf.start`,
|
|
318
|
+
escalation `message` → `wf.signal wait-answer`, `cancel` → gateway cancellation)
|
|
319
|
+
sit behind it, mounted by Urban ahead of the generic page actions.
|
|
282
320
|
|
|
283
321
|
## Link it into your Nano projects
|
|
284
322
|
|
|
285
|
-
This is a standalone
|
|
323
|
+
This is a standalone Node project (Deno is used only as the cross-compiler).
|
|
324
|
+
Import it by reference (ADR 0041) so the
|
|
286
325
|
console reads it live from this directory:
|
|
287
326
|
|
|
288
327
|
- In the console **Projects → Import by reference**, point at this folder, or
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// POST /app/actions/cancel — override the generic row-cancel action. Terminating the engine
|
|
2
|
+
// instance emits no completion event, so reconcile the app row (status='abandoned', clear the
|
|
3
|
+
// open escalation) here.
|
|
4
|
+
import type { ActionHandler } from "@nanobpm/urban";
|
|
5
|
+
import { cancelRun } from "../app/service.ts";
|
|
6
|
+
|
|
7
|
+
const handler: ActionHandler = async ({ body }, app) => {
|
|
8
|
+
const key = (body as { processInstanceKey?: unknown })?.processInstanceKey;
|
|
9
|
+
if (key == null || String(key) === "") {
|
|
10
|
+
return { status: 400, body: { error: "processInstanceKey is required" } };
|
|
11
|
+
}
|
|
12
|
+
const r = await cancelRun(app.data, app.engine, String(key));
|
|
13
|
+
return { status: r.ok ? 200 : 404, body: r };
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export default handler;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// POST /app/actions/message — override the generic publishMessage action. For the
|
|
2
|
+
// `escalation-answered` message we run the app's answer flow (record the answer, clear the
|
|
3
|
+
// open escalation, and signal `wait-answer`); any other message falls back to a plain
|
|
4
|
+
// publishMessage (this override shadows the generic route entirely, so the fallback preserves it).
|
|
5
|
+
import type { ActionHandler } from "@nanobpm/urban";
|
|
6
|
+
import { answerEscalation } from "../app/service.ts";
|
|
7
|
+
|
|
8
|
+
const handler: ActionHandler = async ({ body }, app) => {
|
|
9
|
+
const b = (body ?? {}) as {
|
|
10
|
+
name?: unknown;
|
|
11
|
+
correlationKey?: unknown;
|
|
12
|
+
variables?: Record<string, unknown>;
|
|
13
|
+
};
|
|
14
|
+
const name = String(b.name ?? "");
|
|
15
|
+
if (!name) return { status: 400, body: { error: "name is required" } };
|
|
16
|
+
|
|
17
|
+
if (name === "escalation-answered") {
|
|
18
|
+
const prKey = String(b.correlationKey ?? "");
|
|
19
|
+
const answer = String((b.variables?.answer ?? "") as string).trim();
|
|
20
|
+
if (!prKey) return { status: 400, body: { error: "correlationKey is required" } };
|
|
21
|
+
if (!answer) return { status: 400, body: { error: "answer is required" } };
|
|
22
|
+
const r = await answerEscalation(app.data, prKey, answer);
|
|
23
|
+
return { status: r.ok ? 200 : 404, body: r };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
await app.engine.publishMessage({
|
|
27
|
+
name,
|
|
28
|
+
correlationKey: b.correlationKey != null ? String(b.correlationKey) : undefined,
|
|
29
|
+
variables: b.variables,
|
|
30
|
+
});
|
|
31
|
+
return { status: 200, body: { ok: true } };
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export default handler;
|
package/actions/start.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// POST /app/actions/start/convergence-loop — override the generic "start process" action.
|
|
2
|
+
// Parse the PR reference and register/refresh the PR aggregate (idempotent on prKey) before
|
|
3
|
+
// starting the code-first convergence loop via the workflow client.
|
|
4
|
+
import type { ActionHandler } from "@nanobpm/urban";
|
|
5
|
+
import { parsePr, submitPr } from "../app/service.ts";
|
|
6
|
+
|
|
7
|
+
const handler: ActionHandler = async ({ body }, app) => {
|
|
8
|
+
const vars = ((body as { variables?: Record<string, unknown> })?.variables ?? {}) as Record<string, unknown>;
|
|
9
|
+
const raw = String((vars.pr ?? vars.url ?? "") as string).trim();
|
|
10
|
+
const parsed = parsePr(raw);
|
|
11
|
+
if (!parsed) {
|
|
12
|
+
return { status: 400, body: { error: "could not parse PR (use owner/repo#123 or a PR URL)" } };
|
|
13
|
+
}
|
|
14
|
+
return { status: 202, body: await submitPr(app.data, parsed) };
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export default handler;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// POST /hooks/submit — submit a PR out-of-band (shared-secret auth via X-Hook-Secret). Not
|
|
2
|
+
// part of the page UI; lets an external system (a GitHub webhook relay, a CI job) kick off a
|
|
3
|
+
// convergence run. Same idempotent submit path as the page's "Start review" action.
|
|
4
|
+
import type { ActionHandler } from "@nanobpm/urban";
|
|
5
|
+
import { parsePr, submitPr } from "../app/service.ts";
|
|
6
|
+
|
|
7
|
+
const WEBHOOK_SECRET = process.env.NANO_PR_WEBHOOK_SECRET ?? "";
|
|
8
|
+
|
|
9
|
+
const handler: ActionHandler = async ({ req, body }, app) => {
|
|
10
|
+
if (WEBHOOK_SECRET && req.headers.get("x-hook-secret") !== WEBHOOK_SECRET) {
|
|
11
|
+
return { status: 401, body: { error: "unauthorized" } };
|
|
12
|
+
}
|
|
13
|
+
const b = (body ?? {}) as { url?: unknown; pr?: unknown };
|
|
14
|
+
const parsed = parsePr(String((b.url ?? b.pr ?? "") as string));
|
|
15
|
+
if (!parsed) return { status: 400, body: { error: "could not parse PR url" } };
|
|
16
|
+
return { status: 202, body: await submitPr(app.data, parsed) };
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export default handler;
|
package/app/engine.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Shared code-first engine seam. The convergence process is authored in code
|
|
2
|
+
// (`workflows/convergence-loop.ts`) and driven through `@nanobpm/workflow`'s
|
|
3
|
+
// `WorkflowClient` (re-exported from `@nanobpm/urban`), which derives the
|
|
4
|
+
// executable model, job types and message names from the flow. Both the action
|
|
5
|
+
// handlers and the poller reach the engine through this one client.
|
|
6
|
+
import { WorkflowClient } from "@nanobpm/urban";
|
|
7
|
+
import { convergenceLoop } from "../workflows/convergence-loop.ts";
|
|
8
|
+
|
|
9
|
+
/** Engine REST base (no trailing slash, no `/v2`). */
|
|
10
|
+
export const BASE_URL = (process.env.NANOBPMN_BASE_URL ?? "http://localhost:8080").replace(/\/+$/, "");
|
|
11
|
+
|
|
12
|
+
/** Round cap carried onto each instance at submit time. */
|
|
13
|
+
export const MAX_ROUNDS = Number(process.env.NANO_PR_MAX_ROUNDS ?? 10);
|
|
14
|
+
|
|
15
|
+
let _wf: WorkflowClient | null = null;
|
|
16
|
+
|
|
17
|
+
/** The shared workflow client, lazily constructed against `BASE_URL`. */
|
|
18
|
+
export function workflow(): WorkflowClient {
|
|
19
|
+
return (_wf ??= new WorkflowClient({ baseUrl: BASE_URL }));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export { convergenceLoop };
|
package/app/github.ts
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// GitHub review fetch for the review-ready poller (SPEC §10).
|
|
2
|
+
//
|
|
3
|
+
// Two transports, selected by `NANO_PR_GITHUB_TRANSPORT` (auto | gh | token):
|
|
4
|
+
// • gh — shell out to the host `gh` CLI. It uses the user's own GitHub login, so the
|
|
5
|
+
// poller reaches every repository the user can reach — including private repos
|
|
6
|
+
// that no PAT is (or can be) issued for. This is the default on a workstation.
|
|
7
|
+
// • token — HTTP `fetch` to api.github.com with `GITHUB_TOKEN`. Used in headless/CI where
|
|
8
|
+
// no interactive `gh` login exists.
|
|
9
|
+
// • auto — prefer `gh` when the binary is present; otherwise fall back to `token`.
|
|
10
|
+
//
|
|
11
|
+
// The poller is app-side host glue (main.ts), so host-specific subprocess I/O is allowed here.
|
|
12
|
+
// Cross-runtime: runs under Node (`node:child_process`) and Deno (`Deno.Command`).
|
|
13
|
+
|
|
14
|
+
/** A GitHub pull-request review, narrowed to the fields the poller needs. */
|
|
15
|
+
export interface GhReview {
|
|
16
|
+
id: number;
|
|
17
|
+
state: string;
|
|
18
|
+
submitted_at?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export type GithubTransport = "gh" | "token" | "auto";
|
|
22
|
+
|
|
23
|
+
/** Resolve the configured transport, defaulting to `auto`. */
|
|
24
|
+
export function githubTransport(): GithubTransport {
|
|
25
|
+
const t = (process.env.NANO_PR_GITHUB_TRANSPORT ?? "auto").trim().toLowerCase();
|
|
26
|
+
return t === "gh" || t === "token" ? t : "auto";
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
interface DenoCommandCtor {
|
|
30
|
+
new (
|
|
31
|
+
command: string,
|
|
32
|
+
options: { args: string[]; stdout: "piped"; stderr: "piped" },
|
|
33
|
+
): { output(): Promise<{ code: number; stdout: Uint8Array; stderr: Uint8Array }> };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Run the host `gh` CLI with the given args (no shell — args are passed as a vector, so a
|
|
37
|
+
* `repo`/`number` from the datastore cannot inject a command). Resolves stdout, rejects on a
|
|
38
|
+
* non-zero exit with stderr as the message. */
|
|
39
|
+
async function runGh(args: string[]): Promise<string> {
|
|
40
|
+
const g = globalThis as { Deno?: { Command?: DenoCommandCtor } };
|
|
41
|
+
if (g.Deno?.Command) {
|
|
42
|
+
const { code, stdout, stderr } = await new g.Deno.Command("gh", {
|
|
43
|
+
args,
|
|
44
|
+
stdout: "piped",
|
|
45
|
+
stderr: "piped",
|
|
46
|
+
}).output();
|
|
47
|
+
if (code !== 0) {
|
|
48
|
+
throw new Error(new TextDecoder().decode(stderr).trim() || `gh exited ${code}`);
|
|
49
|
+
}
|
|
50
|
+
return new TextDecoder().decode(stdout);
|
|
51
|
+
}
|
|
52
|
+
const { execFile } = await import("node:child_process");
|
|
53
|
+
return await new Promise<string>((resolve, reject) => {
|
|
54
|
+
execFile(
|
|
55
|
+
"gh",
|
|
56
|
+
args,
|
|
57
|
+
{ maxBuffer: 16 * 1024 * 1024 },
|
|
58
|
+
(err, stdout, stderr) => {
|
|
59
|
+
if (err) reject(new Error(String(stderr || "").trim() || err.message));
|
|
60
|
+
else resolve(String(stdout));
|
|
61
|
+
},
|
|
62
|
+
);
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
let ghAvailable: Promise<boolean> | undefined;
|
|
67
|
+
/** Whether the host `gh` CLI is present (memoized — probed at most once per process). */
|
|
68
|
+
function isGhAvailable(): Promise<boolean> {
|
|
69
|
+
return (ghAvailable ??= runGh(["--version"]).then(() => true, () => false));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Fetch the reviews for one PR via the configured transport. Throws on transport failure so
|
|
73
|
+
* the caller can log-and-continue; returns `null` when no transport is usable (idle). */
|
|
74
|
+
export async function fetchPrReviews(
|
|
75
|
+
repo: string,
|
|
76
|
+
number: number | string,
|
|
77
|
+
token: string,
|
|
78
|
+
): Promise<GhReview[] | null> {
|
|
79
|
+
const mode = githubTransport();
|
|
80
|
+
const useGh = mode === "gh" || (mode === "auto" && (await isGhAvailable()));
|
|
81
|
+
const path = `repos/${repo}/pulls/${number}/reviews?per_page=100`;
|
|
82
|
+
if (useGh) {
|
|
83
|
+
const out = await runGh(["api", path, "-H", "Accept: application/vnd.github+json"]);
|
|
84
|
+
return JSON.parse(out) as GhReview[];
|
|
85
|
+
}
|
|
86
|
+
if (!token) return null; // token mode with no token → poller idles
|
|
87
|
+
const r = await fetch(`https://api.github.com/${path}`, {
|
|
88
|
+
headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json" },
|
|
89
|
+
});
|
|
90
|
+
if (!r.ok) throw new Error(`github ${r.status} ${r.statusText}`.trim());
|
|
91
|
+
return (await r.json()) as GhReview[];
|
|
92
|
+
}
|
package/app/rows.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// Row shapes for the app's sqlite datasource (`db/migrations/*.sql`). These used
|
|
2
|
+
// to be generated into `nano-generated/domain-rows.d.ts`; with the app now on the
|
|
3
|
+
// published `@nanobpm/urban` data layer (`DataLayer.table<T>(name, pk)`), we keep
|
|
4
|
+
// the handful of types the app actually persists here as plain source.
|
|
5
|
+
|
|
6
|
+
export interface Escalations {
|
|
7
|
+
id: number;
|
|
8
|
+
pr_key: string;
|
|
9
|
+
round_no: number;
|
|
10
|
+
kind: string;
|
|
11
|
+
question: string;
|
|
12
|
+
answer: string | null;
|
|
13
|
+
status: string;
|
|
14
|
+
asked_at: string;
|
|
15
|
+
answered_at: string | null;
|
|
16
|
+
transcript: string | null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface PullRequests {
|
|
20
|
+
pr_key: string;
|
|
21
|
+
repo: string;
|
|
22
|
+
number: number;
|
|
23
|
+
url: string;
|
|
24
|
+
title: string | null;
|
|
25
|
+
status: string;
|
|
26
|
+
current_round: number;
|
|
27
|
+
process_key: string | null;
|
|
28
|
+
waiting_since: string | null;
|
|
29
|
+
last_review_id: number | null;
|
|
30
|
+
outcome: string | null;
|
|
31
|
+
created_at: string;
|
|
32
|
+
updated_at: string;
|
|
33
|
+
converged_at: string | null;
|
|
34
|
+
open_escalation_id: number | null;
|
|
35
|
+
open_escalation_question: string | null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface Rounds {
|
|
39
|
+
id: number;
|
|
40
|
+
pr_key: string;
|
|
41
|
+
round_no: number;
|
|
42
|
+
status: string | null;
|
|
43
|
+
summary: string | null;
|
|
44
|
+
started_at: string;
|
|
45
|
+
ended_at: string | null;
|
|
46
|
+
transcript: string | null;
|
|
47
|
+
}
|
package/app/service.ts
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// urban-pr-review-codefirst — the app's business logic over the Urban runtime
|
|
2
|
+
// seams. Shared by the action handlers (`actions/*`) and the review-ready poller.
|
|
3
|
+
//
|
|
4
|
+
// Data access goes through the injected `@nanobpm/urban` `DataLayer`
|
|
5
|
+
// (`data.table<T>(name, pk)`); engine calls go through the code-first
|
|
6
|
+
// `WorkflowClient` in `app/engine.ts`, which derives the process id and the
|
|
7
|
+
// `wait-*` message names from `convergence-loop`.
|
|
8
|
+
import type { DataLayer, EngineClient } from "@nanobpm/urban";
|
|
9
|
+
import { convergenceLoop, MAX_ROUNDS, workflow } from "./engine.ts";
|
|
10
|
+
import type { Escalations, PullRequests, Rounds } from "./rows.ts";
|
|
11
|
+
import { fetchPrReviews } from "./github.ts";
|
|
12
|
+
|
|
13
|
+
export interface ParsedPr {
|
|
14
|
+
repo: string;
|
|
15
|
+
number: number;
|
|
16
|
+
url: string;
|
|
17
|
+
prKey: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const now = (): string => new Date().toISOString();
|
|
21
|
+
|
|
22
|
+
const prs = (data: DataLayer) => data.table<PullRequests>("pull_requests", "pr_key");
|
|
23
|
+
const rounds = (data: DataLayer) => data.table<Rounds>("rounds", "id");
|
|
24
|
+
const escalations = (data: DataLayer) => data.table<Escalations>("escalations", "id");
|
|
25
|
+
|
|
26
|
+
/** Parse "owner/repo#123" or a canonical PR URL into its parts. */
|
|
27
|
+
export function parsePr(input: string): ParsedPr | null {
|
|
28
|
+
const s = input.trim();
|
|
29
|
+
let m = s.match(/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/i);
|
|
30
|
+
if (m) {
|
|
31
|
+
const repo = `${m[1]}/${m[2]}`;
|
|
32
|
+
const number = Number(m[3]);
|
|
33
|
+
return { repo, number, url: `https://github.com/${repo}/pull/${number}`, prKey: `${repo}#${number}` };
|
|
34
|
+
}
|
|
35
|
+
m = s.match(/^([^/]+\/[^#]+)#(\d+)$/);
|
|
36
|
+
if (m) {
|
|
37
|
+
const repo = m[1];
|
|
38
|
+
const number = Number(m[2]);
|
|
39
|
+
return { repo, number, url: `https://github.com/${repo}/pull/${number}`, prKey: `${repo}#${number}` };
|
|
40
|
+
}
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// The review prompt is read once (host-agnostic: Deno.readTextFile under a
|
|
45
|
+
// compiled binary, node:fs under Node) and carried on the instance, so a PR keeps
|
|
46
|
+
// the instructions it started with for its whole run.
|
|
47
|
+
let _prompt: string | null = null;
|
|
48
|
+
async function reviewPrompt(): Promise<string> {
|
|
49
|
+
if (_prompt !== null) return _prompt;
|
|
50
|
+
const path = "prompts/review-round.md";
|
|
51
|
+
try {
|
|
52
|
+
const g = globalThis as { Deno?: { readTextFile(p: string): Promise<string> } };
|
|
53
|
+
_prompt = g.Deno?.readTextFile
|
|
54
|
+
? await g.Deno.readTextFile(path)
|
|
55
|
+
: await (await import("node:fs/promises")).readFile(path, "utf8");
|
|
56
|
+
} catch {
|
|
57
|
+
_prompt = "";
|
|
58
|
+
}
|
|
59
|
+
return _prompt;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Register a PR row (if new) and start the convergence process. Idempotent on prKey. */
|
|
63
|
+
export async function submitPr(data: DataLayer, parsed: ParsedPr) {
|
|
64
|
+
const { repo, number, url, prKey } = parsed;
|
|
65
|
+
const table = prs(data);
|
|
66
|
+
const existing = await table.get(prKey);
|
|
67
|
+
if (existing && !["converged", "abandoned"].includes(existing.status)) {
|
|
68
|
+
return { prKey, alreadyRunning: true };
|
|
69
|
+
}
|
|
70
|
+
const ts = now();
|
|
71
|
+
if (existing) {
|
|
72
|
+
// Re-open a previously converged/abandoned PR for a fresh convergence run.
|
|
73
|
+
await table.update(prKey, {
|
|
74
|
+
status: "converging", current_round: 1, url,
|
|
75
|
+
waiting_since: null, last_review_id: null, outcome: null, converged_at: null,
|
|
76
|
+
updated_at: ts,
|
|
77
|
+
});
|
|
78
|
+
} else {
|
|
79
|
+
await table.insert({
|
|
80
|
+
pr_key: prKey, repo, number, url, status: "converging", current_round: 1,
|
|
81
|
+
created_at: ts, updated_at: ts,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
const { processInstanceKey } = await workflow().start(convergenceLoop, {
|
|
85
|
+
repo, prNumber: number, prUrl: url, prKey, round: 1, maxRounds: MAX_ROUNDS,
|
|
86
|
+
prompt: await reviewPrompt(),
|
|
87
|
+
});
|
|
88
|
+
if (processInstanceKey != null) {
|
|
89
|
+
await table.update(prKey, { process_key: String(processInstanceKey) });
|
|
90
|
+
}
|
|
91
|
+
return { prKey, processKey: processInstanceKey };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Answer an open escalation → record it and resume the process at `wait-answer`. */
|
|
95
|
+
export async function answerEscalation(data: DataLayer, prKey: string, answer: string) {
|
|
96
|
+
const open = (await escalations(data).find({ pr_key: prKey, status: "open" }))
|
|
97
|
+
.sort((a, b) => b.id - a.id)[0];
|
|
98
|
+
if (!open) return { ok: false, reason: "no open escalation" };
|
|
99
|
+
const escalationId = open.id;
|
|
100
|
+
const ts = now();
|
|
101
|
+
await escalations(data).update(escalationId, { answer, status: "answered", answered_at: ts });
|
|
102
|
+
await prs(data).update(prKey, {
|
|
103
|
+
status: "converging", updated_at: ts,
|
|
104
|
+
open_escalation_id: null, open_escalation_question: null,
|
|
105
|
+
});
|
|
106
|
+
// Correlate the `wait-answer` signal (derived message `convergence-loop:wait-answer`)
|
|
107
|
+
// to the parked instance by its `prKey`.
|
|
108
|
+
await workflow().signal(convergenceLoop, "wait-answer", prKey, { answer, escalationId });
|
|
109
|
+
return { ok: true, escalationId };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Cancel a PR's running convergence instance and mark it abandoned. Terminating
|
|
113
|
+
* the engine instance emits no completion event (no worker runs), so the app-tier
|
|
114
|
+
* flips the PR's status here. */
|
|
115
|
+
export async function cancelRun(data: DataLayer, engine: EngineClient, processInstanceKey: string) {
|
|
116
|
+
const [pr] = await prs(data).find({ process_key: processInstanceKey });
|
|
117
|
+
try {
|
|
118
|
+
await engine.cancelInstance({ processInstanceKey });
|
|
119
|
+
} catch (err) {
|
|
120
|
+
// The instance may already be gone (converged/cancelled) — still reconcile the
|
|
121
|
+
// app row so a stale "converging" PR can't linger in the UI.
|
|
122
|
+
console.warn(`[cancel] engine cancel for ${processInstanceKey}: ${err}`);
|
|
123
|
+
}
|
|
124
|
+
if (pr) {
|
|
125
|
+
await prs(data).update(String(pr.pr_key), {
|
|
126
|
+
status: "abandoned", updated_at: now(),
|
|
127
|
+
open_escalation_id: null, open_escalation_question: null,
|
|
128
|
+
});
|
|
129
|
+
return { ok: true, prKey: pr.pr_key };
|
|
130
|
+
}
|
|
131
|
+
return { ok: false, reason: "no PR for that instance" };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** One poll pass: for each PR waiting on review, fetch fresh GitHub reviews (via the host
|
|
135
|
+
* `gh` CLI or a token — see `app/github.ts`) and, when one has landed, resume the instance
|
|
136
|
+
* parked at `wait-review`. */
|
|
137
|
+
export async function pollOnce(data: DataLayer) {
|
|
138
|
+
const token = process.env.GITHUB_TOKEN ?? "";
|
|
139
|
+
const waiting = await prs(data).find({ status: "waiting_review" });
|
|
140
|
+
for (const pr of waiting) {
|
|
141
|
+
const { repo, number, pr_key: prKey } = pr;
|
|
142
|
+
const lastId = pr.last_review_id ?? 0;
|
|
143
|
+
try {
|
|
144
|
+
const reviews = await fetchPrReviews(repo, number, token);
|
|
145
|
+
if (reviews === null) return; // no usable transport (no gh, no token) → idle
|
|
146
|
+
const fresh = reviews
|
|
147
|
+
.filter((rv) => rv.id > lastId && rv.submitted_at && (!pr.waiting_since || rv.submitted_at >= pr.waiting_since))
|
|
148
|
+
.sort((a, b) => a.id - b.id)
|
|
149
|
+
.pop();
|
|
150
|
+
if (!fresh) continue;
|
|
151
|
+
await prs(data).update(prKey, {
|
|
152
|
+
last_review_id: fresh.id, status: "converging", updated_at: now(),
|
|
153
|
+
});
|
|
154
|
+
// Resume the instance parked at `wait-review` (derived message
|
|
155
|
+
// `convergence-loop:wait-review`), then it loops back to review-round.
|
|
156
|
+
await workflow().signal(convergenceLoop, "wait-review", prKey, {
|
|
157
|
+
reviewId: fresh.id, reviewState: fresh.state, submittedAt: fresh.submitted_at ?? null,
|
|
158
|
+
});
|
|
159
|
+
console.log(`[poller] review ${fresh.id} (${fresh.state}) → ${prKey}`);
|
|
160
|
+
} catch (err) {
|
|
161
|
+
console.error(`[poller] ${prKey}: ${err}`);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|