@nanobpm/urban-pr-review-codefirst 1.0.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.
@@ -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,22 @@
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
+
8
+ # [1.1.0](https://github.com/jwulf/urban-pr-review-codefirst/compare/v1.0.0...v1.1.0) (2026-07-31)
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * **ci:** sync package-lock to @nanobpm/workflow@0.4.0 ([57aa919](https://github.com/jwulf/urban-pr-review-codefirst/commit/57aa919e4f5f1dbc2e9022cda19b2aa1594dff50)), closes [#1](https://github.com/jwulf/urban-pr-review-codefirst/issues/1)
14
+
15
+
16
+ ### Features
17
+
18
+ * emit senior:pr-review so one reviewer serves both apps ([#1](https://github.com/jwulf/urban-pr-review-codefirst/issues/1)) ([0d3e39b](https://github.com/jwulf/urban-pr-review-codefirst/commit/0d3e39b112ce6cfb9d56874247f7d34d85e3e4fd))
19
+
1
20
  # 1.0.0 (2026-07-31)
2
21
 
3
22
 
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 `@nanobpm/workflow` declarative surface (`defineFlow`, ADR
9
- 0044/0045). The SDK derives the executable BPMN (with DI), the job types, and the
10
- message names — no diagram, no task-type wiring, no correlation plumbing.
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
@@ -17,6 +19,155 @@ them (`convergence-loop.bpmn` + `workers/*/worker.ts`), code-first writes them
17
19
  (`workflows/convergence-loop.ts`, with the record steps hosted in-process). See
18
20
  [Persistence](#persistence) and [Frontend](#frontend) below.
19
21
 
22
+ ## HOWTO: run agents that converge PRs for you, all day
23
+
24
+ ### The problem this solves
25
+
26
+ Driving a PR to convergence is mostly *waiting*: open a review, wait 5–15 min for
27
+ the reviewer, address the comments, re-request, wait again — often ten rounds
28
+ deep, escalating to a human only when the reviewer is stuck. If a single agent
29
+ babysits one PR, it spends almost all of its time **idle-polling** a review that
30
+ hasn't landed yet. That is wasted wall-clock and a wasted worker slot.
31
+
32
+ This app inverts that. **The BPMN process the SDK derives owns the durable wait**
33
+ between rounds (a real `w.signal` message-catch event), so no agent is ever parked
34
+ holding a job slot while a review is pending. Instead you **hire a couple of agent
35
+ workers once**, and they pull `senior:pr-review` jobs from *whatever PR is ready
36
+ right now* — alternating across all in-flight reviews. Two agents can keep a dozen
37
+ PRs converging in parallel, and they only run when there is actual work to do.
38
+
39
+ Because the `review-round` task overrides its job type to **`senior:pr-review`**
40
+ (via `w.task("review-round", { jobType: "senior:pr-review" })`), the *same* hired
41
+ reviewer services both this code-first app and the model-first
42
+ [urban-pr-review](../urban-pr-review). Set it up by: **(1)** running this app,
43
+ **(2)** submitting PRs, and **(3)** hiring agent workers with
44
+ [`c8ctl nano`](https://github.com/jwulf/c8ctl-plugin-nano).
45
+
46
+ ### 0. Prerequisites
47
+
48
+ - A running **Nano gateway/engine** (default `http://localhost:8080`). This is
49
+ what the app deploys to and what agents pull jobs from.
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).
55
+ - On each machine that will *host an agent*: the **GitHub CLI** logged in
56
+ (`gh auth login`) or a `GITHUB_TOKEN`/`GH_TOKEN` in the environment, and the
57
+ agent harness itself — e.g. the **[Copilot CLI](https://github.com/github/copilot-cli)**
58
+ (`copilot`).
59
+
60
+ ### 1. Install the app into your Nano IDE
61
+
62
+ Open the Nano console and **Projects → Import by reference**, pointing at this
63
+ app's folder (ADR 0041), or drop a `*.project-ref.json` next to your other
64
+ projects. `nano-ide.ext.json` marks it as an example. You can also just run it
65
+ standalone (next step) — the IDE import is only needed to launch/manage it from
66
+ the console.
67
+
68
+ ### 2. Start the app
69
+
70
+ ```sh
71
+ npm start # → http://localhost:3000
72
+ ```
73
+
74
+ That applies the DB migrations, deploys the derived flow, hosts the in-process
75
+ `w.run` record steps, serves the web UI at **<http://localhost:3000>**, and runs
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`.
79
+
80
+ ### 3. Submit a PR
81
+
82
+ From the web UI, or from the CLI:
83
+
84
+ ```sh
85
+ npm run submit -- https://github.com/owner/repo/pull/42 5 # 5 = maxRounds
86
+ ```
87
+
88
+ Each submitted PR starts one durable `convergence-loop` instance that parks until
89
+ an agent services its `senior:pr-review` round.
90
+
91
+ ### 4. Hire an agent worker
92
+
93
+ An agent is a CLI harness (Copilot CLI here) turned into a Nano job worker. Hire a
94
+ profile whose **rank + capability** produce the `senior:pr-review` token this
95
+ flow's task emits:
96
+
97
+ ```sh
98
+ c8ctl nano hire \
99
+ --name reviewer \
100
+ --rank senior \
101
+ --capabilities pr-review \
102
+ --command 'copilot -p - --allow-all-tools' \
103
+ --model <your-model>
104
+ ```
105
+
106
+ - `--rank senior` + `--capabilities pr-review` makes the worker subscribe to the
107
+ `senior:pr-review` job type — exactly the token this flow's `review-round` task
108
+ emits (thanks to the SDK job-type override), so **one profile serves both apps.**
109
+ - `--command 'copilot -p - --allow-all-tools'` starts the Copilot CLI reading its
110
+ prompt from **stdin** (`-p -`). The harness pipes the whole job JSON (prompt +
111
+ `job.variables`: `prUrl`, `repo`, `prNumber`, `round`, `answer?`) to stdin; the
112
+ review-round instructions tell the agent how to read it and where to write its
113
+ result.
114
+ - **`--allow-all-tools` is the crucial flag.** Without it, Copilot pauses to ask
115
+ permission before each tool call — and an unattended worker has no human to
116
+ answer, so the job stalls. `--allow-all-tools` lets it run the whole round
117
+ non-interactively. (Pair with `--deny-tool` to blocklist specific tools.)
118
+
119
+ > ⚠️ **Only enable `--allow-all-tools` for code and hosts you trust.** It grants
120
+ > the agent unattended, broad permissions (shell, file writes, network). Each
121
+ > job runs in a throwaway per-job workspace (see below), but the worker still
122
+ > runs as your user on the host — don't point it at untrusted PRs on a shared
123
+ > machine. Use `--deny-tool` to narrow it, or a container sandbox for stronger
124
+ > isolation.
125
+
126
+ > If you'd rather not override the job type in the flow, you can instead leave the
127
+ > derived `convergence-loop:review-round` type and point a worker at it explicitly
128
+ > with `c8ctl nano work reviewer --job-type convergence-loop:review-round`. This
129
+ > app ships with the `senior:pr-review` override so it shares a reviewer with the
130
+ > model-first app out of the box.
131
+
132
+ ### 5. Put the agent to work
133
+
134
+ ```sh
135
+ c8ctl nano work reviewer # polls for senior:pr-review jobs until Ctrl-C
136
+ ```
137
+
138
+ Now every PR you submit gets picked up automatically. Start a **second** worker
139
+ (same command, another terminal or another machine) and the two alternate across
140
+ whichever PRs are ready — that is the idle-time you reclaim. Run more than one job
141
+ at once per worker with `--max-parallel 2`.
142
+
143
+ ### Isolation — each job gets its own clean workspace
144
+
145
+ In the default **host mode** (`--sandbox none`), the worker provisions a
146
+ **throwaway, per-job workspace**: a fresh clone under `<state>/agent-runs/run-*`
147
+ checked out on the PR's head branch, exposed to the agent as `AGENT_WORKSPACE` /
148
+ `REPO_URL` / `REPO_BRANCH` / `REPO_REF`, and **reaped after the job**. So multiple
149
+ agents on one host don't step on each other. Host workers inherit *your*
150
+ `gh`/`GITHUB_TOKEN` login, so no extra auth is needed. Docker/podman sandboxes
151
+ exist (`--sandbox docker --image …`) for stronger isolation, but container-side
152
+ git provisioning is a later increment — container jobs don't clone yet, and don't
153
+ inherit your host login (pass credentials via `--secret-resolver host` /
154
+ `secretRefs`). For the review loop, **host mode is the recommended setup.**
155
+
156
+ ### Run it across spare hardware (incl. a Raspberry Pi)
157
+
158
+ Nano ships ARM binaries (arm64/armv7/armv6), so the whole thing scales down nicely:
159
+
160
+ - **All-in-one:** run the gateway, this app, and one or two workers on your laptop.
161
+ - **Distributed:** run the **Nano gateway on a Raspberry Pi** (always-on, low
162
+ power), run this app anywhere, and put **agent workers on spare machines** — each
163
+ worker just needs the c8ctl CLI, the Copilot CLI logged in, and
164
+ `NANOBPMN_BASE_URL` pointed at the Pi. Add or remove workers at will; the BPMN
165
+ process holds all durable state, so workers are stateless and disposable.
166
+
167
+ The payoff: instead of one agent burning wall-clock polling a single PR, a small
168
+ pool of always-available workers keeps every open review converging — and idles to
169
+ zero cost when there's nothing to do.
170
+
20
171
  ## The flow
21
172
 
22
173
  `workflows/convergence-loop.ts`:
@@ -35,8 +186,10 @@ loop:
35
186
  ```
36
187
 
37
188
  - **`review-round`** is a `w.task` — an **external** worker. Point a coding-agent
38
- harness at the job type `convergence-loop:review-round` (e.g. `c8ctl nano hire`).
39
- The app never hosts or names it; it only owns the durable orchestration around it.
189
+ harness at the job type `senior:pr-review` (e.g. a `c8ctl nano hire`d rank
190
+ `senior` + capability `pr-review` profile — the same one that services the
191
+ model-first app). The app never hosts or names it; it only owns the durable
192
+ orchestration around it.
40
193
  - **`persist-*`** and **`persist-converged`** are `w.run` — app-hosted handlers.
41
194
  `persist-round` returns `{ round: round + 1 }`; that return value (not an
42
195
  ioMapping) is the loop's only state mutation.
@@ -55,7 +208,7 @@ the generated BPMN as `nano:shape` + `io.nanobpm.dataEnvelope` properties.
55
208
 
56
209
  | Step | Derived job type / message |
57
210
  | --- | --- |
58
- | `review-round` (external) | `convergence-loop:review-round` |
211
+ | `review-round` (external) | `senior:pr-review` (overridden via `w.task("review-round", { jobType: "senior:pr-review" })`) |
59
212
  | `persist-round` | `convergence-loop:persist-round` |
60
213
  | `persist-escalation` | `convergence-loop:persist-escalation` |
61
214
  | `persist-escalation-maxrounds` | `convergence-loop:persist-escalation-maxrounds` |
@@ -71,10 +224,10 @@ Requires a running Nano gateway (default `http://localhost:8080`; override with
71
224
  ```sh
72
225
  # The one service: applies DB migrations, deploys the flow, hosts the app-owned
73
226
  # w.run record steps, AND serves the web frontend + review-ready poller.
74
- deno task start # → http://localhost:3000
227
+ npm start # → http://localhost:3000
75
228
  ```
76
229
 
77
- `deno task start` now does everything: it applies the `db/migrations/` on boot
230
+ `npm start` now does everything: it applies the `db/migrations/` on boot
78
231
  (creating `app.db`), deploys the flow, hosts the `persist-*` handlers, serves the
79
232
  schema-driven page runtime at `http://localhost:3000`, and runs the review-ready
80
233
  poller. Submit and answer PRs directly from the web UI, or drive the same actions
@@ -82,59 +235,93 @@ from the CLI:
82
235
 
83
236
  ```sh
84
237
  # submit a PR (parks after review-round at wait-review or wait-answer)
85
- deno task submit https://github.com/owner/repo/pull/42 5 # 5 = maxRounds
238
+ npm run submit -- https://github.com/owner/repo/pull/42 5 # 5 = maxRounds
86
239
 
87
240
  # nudge a re-review (resumes an instance parked at wait-review)
88
- deno task review-ready owner/repo#42
241
+ npm run review-ready -- owner/repo#42
89
242
 
90
243
  # answer an escalation (resumes an instance parked at wait-answer)
91
- deno task answer owner/repo#42 "merge as-is"
244
+ npm run answer -- owner/repo#42 "merge as-is"
92
245
 
93
246
  # wipe all persisted PRs/rounds/escalations (drops + re-migrates app.db)
94
- deno task purge
247
+ npm run purge
95
248
  ```
96
249
 
97
- The reviewer itself is not started by `deno task start` — it is the external
98
- `convergence-loop:review-round` job. Host it with a coding-agent harness so the
99
- automated review is fully decoupled from the durable orchestration.
250
+ The reviewer itself is not started by `npm start` — it is the external
251
+ `senior:pr-review` job. Host it with a coding-agent harness so the automated
252
+ review is fully decoupled from the durable orchestration.
100
253
 
101
254
  Environment overrides: `PR_REVIEW_PORT` (default `3000`), `NANOBPMN_BASE_URL`
102
255
  (gateway), `NANO_APP_DB_URL` (default `file:./app.db`), `NANO_PR_POLL_MS`
103
256
  (poller interval, default `60000`), `NANO_PR_MAX_ROUNDS` (default `10`),
104
- `GITHUB_TOKEN` (enables the poller — without it the poller idles and re-reviews
105
- come only from the CLI/UI).
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
+
106
290
 
107
291
  ## Persistence
108
292
 
109
293
  Parity with the model-first app: the same three-table SQLite schema
110
294
  (`pull_requests`, `rounds`, `escalations`), the same `db/migrations/*.sql`, and
111
- the same generated typed data facade (`nano-generated/domain.ts`, exposing
112
- `db.pull_requests` / `db.rounds` / `db.escalations`). The `nano.app.json` manifest
113
- declares the `app` sqlite datasource (`${NANO_APP_DB_URL:-file:./app.db}`) and the
114
- 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.
115
300
 
116
301
  The record steps that write these rows are the code-first counterpart of the
117
302
  model-first `workers/{persist-round,persist-escalation,finalize}` — but instead of
118
303
  standalone `defineWorker`s, they are the `w.run` handlers in
119
- `workflows/convergence-loop.ts`, hosted **in-process** by the `@nanobpm/workflow`
120
- `Worker` that `deno task start` runs. The datasource is opened lazily and memoised
121
- on first persist, so the thin CLI scripts (`submit`/`answer`/`review-ready`) can
122
- import the flow to start/signal instances without ever opening the DB — only the
123
- worker host does.
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.
124
310
 
125
311
  ## Frontend
126
312
 
127
- The same schema-driven page runtime as the model-first app (`pages/home.page.json`
128
- + the `nano-generated/app-pages.ts` engine), served by `main.ts` at
129
- `http://localhost:3000`. It lists active + historical PRs, submits new ones, and
130
- answers or cancels runs inline. Because both apps commit the identical page schema
131
- and generated runtime, the UI is byte-for-byte the same; `main.ts` supplies the
132
- code-first action bindings (`start` → `wf.start`, escalation `message` →
133
- `wf.signal wait-answer`, `cancel` → gateway cancellation) behind it.
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.
134
320
 
135
321
  ## Link it into your Nano projects
136
322
 
137
- This is a standalone Deno project. Import it by reference (ADR 0041) so the
323
+ This is a standalone Node project (Deno is used only as the cross-compiler).
324
+ Import it by reference (ADR 0041) so the
138
325
  console reads it live from this directory:
139
326
 
140
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;
@@ -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
+ }