@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/README.md +141 -0
- package/components/review-round.json +69 -0
- package/db/migrations/001_init.sql +46 -0
- package/db/migrations/002_transcript.sql +7 -0
- package/db/migrations/003_open_escalation.sql +8 -0
- package/deno.json +22 -0
- package/deno.lock +77 -0
- package/main.ts +352 -0
- package/nano-generated/app-pages.ts +676 -0
- package/nano-generated/data-cli.ts +552 -0
- package/nano-generated/data-sdk.ts +536 -0
- package/nano-generated/domain-rows.d.ts +87 -0
- package/nano-generated/domain-types.ts +1418 -0
- package/nano-generated/domain.ts +36 -0
- package/nano-generated/llm-worker.ts +403 -0
- package/nano-generated/message-io.d.ts +17 -0
- package/nano-generated/messages.ts +26 -0
- package/nano-generated/meta.ts +18 -0
- package/nano-generated/node-deno-shim.mjs +250 -0
- package/nano-generated/node-loader.mjs +60 -0
- package/nano-generated/node-register.mjs +11 -0
- package/nano-generated/worker-io.d.ts +28 -0
- package/nano-generated/worker-sdk.ts +468 -0
- package/nano-generated/workers.ts +29 -0
- package/nano.app.json +17 -0
- package/nanobpm.project.json +22 -0
- package/package.json +28 -0
- package/pages/home.page.json +127 -0
- package/prompts/review-round.md +119 -0
- package/scripts/answer.ts +20 -0
- package/scripts/purge-db.ts +70 -0
- package/scripts/review-ready.ts +20 -0
- package/scripts/submit.ts +32 -0
- package/tsconfig.json +14 -0
- package/workflows/convergence-loop.ts +299 -0
|
@@ -0,0 +1,468 @@
|
|
|
1
|
+
// nanobpmn embedded worker SDK (Deno-preferred, Node-capable).
|
|
2
|
+
//
|
|
3
|
+
// This file is written verbatim into <workspace>/nano-generated/worker-sdk.ts by the
|
|
4
|
+
// console worker supervisor and imported by each worker's `worker.ts`. It speaks
|
|
5
|
+
// the nanobpmn Falcon protocol directly over the platform's native WebSocket
|
|
6
|
+
// (no `ws`, no node:events) so a worker is a single self-contained process.
|
|
7
|
+
//
|
|
8
|
+
// It runs under **Deno** (preferred) or, on hosts with no Deno build (e.g.
|
|
9
|
+
// 32-bit ARM), under **Node** (>= 22.6, launched with type stripping + the
|
|
10
|
+
// import-map loader). The only host calls that differ between the two runtimes
|
|
11
|
+
// are isolated behind the `RT` adapter below; see ADR 0036.
|
|
12
|
+
//
|
|
13
|
+
// A worker file looks like:
|
|
14
|
+
//
|
|
15
|
+
// import { defineWorker } from "@nanobpm/worker";
|
|
16
|
+
// defineWorker({
|
|
17
|
+
// type: "my-job",
|
|
18
|
+
// maxParallelJobs: 10,
|
|
19
|
+
// async handle(job) {
|
|
20
|
+
// // ...do work with job.variables...
|
|
21
|
+
// return { result: 42 }; // resolves -> completeJob({ result: 42 })
|
|
22
|
+
// // or: await job.fail("boom"); // or job.error("CODE", "msg")
|
|
23
|
+
// },
|
|
24
|
+
// });
|
|
25
|
+
//
|
|
26
|
+
// The handler may either return output variables (the job is completed with
|
|
27
|
+
// them) or call one of job.complete/job.fail/job.error explicitly. Throwing
|
|
28
|
+
// fails the job. npm libraries are available via `npm:` specifiers.
|
|
29
|
+
|
|
30
|
+
/** A row from a datasource query. */
|
|
31
|
+
export type WorkerRow = Record<string, unknown>;
|
|
32
|
+
|
|
33
|
+
/** A typed table gateway (the RAD "TTable") over one table — manipulate rows as
|
|
34
|
+
* typed records instead of hand-writing SQL. Structurally mirrors `Table` in the
|
|
35
|
+
* `@nanobpm/data` SDK; `T` comes from the generated `domain-rows.d.ts` (ADR 0029 §6).
|
|
36
|
+
* For the full named accessor (`db.orders.insert(...)`) import `openDomain` from
|
|
37
|
+
* `@nanobpm/domain`. */
|
|
38
|
+
export interface WorkerTable<T extends object = WorkerRow> {
|
|
39
|
+
insert(row: Partial<T>): Promise<number | bigint>;
|
|
40
|
+
get(id: unknown): Promise<T | undefined>;
|
|
41
|
+
all(limit?: number): Promise<T[]>;
|
|
42
|
+
find(where?: Partial<T>): Promise<T[]>;
|
|
43
|
+
findOne(where?: Partial<T>): Promise<T | undefined>;
|
|
44
|
+
update(id: unknown, patch: Partial<T>): Promise<number>;
|
|
45
|
+
delete(id: unknown): Promise<number>;
|
|
46
|
+
count(where?: Partial<T>): Promise<number>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The datasource handle returned by `ctx.data()`. Mirrors the DataSource
|
|
50
|
+
* contract in the `@nanobpm/data` SDK (ADR 0024); typed structurally here so the
|
|
51
|
+
* worker SDK stays a single self-contained file. `query` is generic so a caller
|
|
52
|
+
* can supply a row type from the generated `domain-rows.d.ts` (ADR 0029 §4.1):
|
|
53
|
+
* `db.query<DomainTables["customers"]>("SELECT * FROM customers")`. */
|
|
54
|
+
export interface WorkerDataSource {
|
|
55
|
+
query<T extends object = WorkerRow>(sql: string, params?: unknown[]): Promise<T[]>;
|
|
56
|
+
exec(
|
|
57
|
+
sql: string,
|
|
58
|
+
params?: unknown[],
|
|
59
|
+
): Promise<{ changed: number; lastInsertId?: number | bigint }>;
|
|
60
|
+
tx<T>(fn: (t: WorkerDataSource) => Promise<T>): Promise<T>;
|
|
61
|
+
schema(): Promise<unknown[]>;
|
|
62
|
+
/** A typed table gateway (the RAD "TTable", ADR 0029 §6): manipulate rows as
|
|
63
|
+
* records instead of hand-writing SQL. `pk` defaults to "id". */
|
|
64
|
+
table<T extends object = WorkerRow>(name: string, pk?: string): WorkerTable<T>;
|
|
65
|
+
close(): void;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The App runtime handed to a worker handler as its 2nd argument. */
|
|
69
|
+
export interface WorkerContext {
|
|
70
|
+
/** Open a declared datasource by name (default when omitted), per ADR 0024. */
|
|
71
|
+
data(name?: string): Promise<WorkerDataSource>;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A worker's variable shapes default to untyped JSON; declaring them (from the
|
|
75
|
+
* generated `domain-rows.d.ts` or the manifest `types` registry, ADR 0029) types the
|
|
76
|
+
* handler's inputs and outputs while authoring — erased at runtime. */
|
|
77
|
+
export type WorkerVars = Record<string, unknown>;
|
|
78
|
+
|
|
79
|
+
/** The untyped custom-header fallback. A worker whose model declares `zeebe:header`
|
|
80
|
+
* keys gets a typed shape (known keys → `string`, ADR 0033 §3) via the generated
|
|
81
|
+
* typed `defineWorker`; otherwise `customHeaders` stays this untyped bag. */
|
|
82
|
+
export type WorkerHdrs = Record<string, unknown>;
|
|
83
|
+
|
|
84
|
+
export interface WorkerJob<
|
|
85
|
+
In extends object = WorkerVars,
|
|
86
|
+
Out extends object = WorkerVars,
|
|
87
|
+
Hdr extends object = WorkerHdrs,
|
|
88
|
+
> {
|
|
89
|
+
readonly jobKey: string;
|
|
90
|
+
readonly type: string;
|
|
91
|
+
readonly processInstanceKey: string;
|
|
92
|
+
readonly processDefinitionId?: string;
|
|
93
|
+
readonly processDefinitionKey?: string;
|
|
94
|
+
readonly elementId?: string;
|
|
95
|
+
readonly retries?: number;
|
|
96
|
+
readonly variables: In;
|
|
97
|
+
readonly customHeaders: Hdr;
|
|
98
|
+
/** Complete the job, optionally setting output variables. */
|
|
99
|
+
complete(variables?: Out): void;
|
|
100
|
+
/** Fail the job (optionally with remaining retries and a message). */
|
|
101
|
+
fail(opts?: { retries?: number; errorMessage?: string } | string): void;
|
|
102
|
+
/** Throw a BPMN error from the job. */
|
|
103
|
+
error(errorCode: string, errorMessage?: string): void;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export interface WorkerOptions<
|
|
107
|
+
In extends object = WorkerVars,
|
|
108
|
+
Out extends object = WorkerVars,
|
|
109
|
+
Hdr extends object = WorkerHdrs,
|
|
110
|
+
> {
|
|
111
|
+
/** BPMN job type to work on. */
|
|
112
|
+
type: string;
|
|
113
|
+
/** Handler invoked per job. Return output vars, or call a job action. The
|
|
114
|
+
* optional 2nd arg exposes the App runtime: `ctx.data(name?)` opens a
|
|
115
|
+
* declared datasource (ADR 0024). Single-arg handlers keep working. */
|
|
116
|
+
handle: (
|
|
117
|
+
job: WorkerJob<In, Out, Hdr>,
|
|
118
|
+
ctx: WorkerContext,
|
|
119
|
+
) => Promise<void | Out> | void | Out;
|
|
120
|
+
/** Max jobs in flight (also the streaming credit window). Default 10. */
|
|
121
|
+
maxParallelJobs?: number;
|
|
122
|
+
/** Job activation lock timeout in ms. Default 60000. */
|
|
123
|
+
timeoutMs?: number;
|
|
124
|
+
/** Restrict fetched variables to these names (default: all). */
|
|
125
|
+
fetchVariables?: string[];
|
|
126
|
+
/** Gateway base URL. Defaults to env NANOBPMN_BASE_URL or http://127.0.0.1:8080. */
|
|
127
|
+
baseUrl?: string;
|
|
128
|
+
/** Worker name recorded on activation. Defaults to env NANOBPMN_WORKER_NAME. */
|
|
129
|
+
worker?: string;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Control lines the supervisor parses out of stdout. Anything else on stdout is
|
|
133
|
+
// treated as worker log output.
|
|
134
|
+
const METRIC = "@@NBPM_METRIC@@";
|
|
135
|
+
const STATUS = "@@NBPM_STATUS@@";
|
|
136
|
+
|
|
137
|
+
// Runtime adapter: the handful of host calls that differ between Deno (native
|
|
138
|
+
// `Deno.*`) and Node (`process`). Everything else the worker uses — WebSocket,
|
|
139
|
+
// fetch, timers, TextEncoder — is standard on both. Detected once at load.
|
|
140
|
+
interface Runtime {
|
|
141
|
+
env(key: string): string | undefined;
|
|
142
|
+
write(line: string): void;
|
|
143
|
+
onSigterm(handler: () => void): void;
|
|
144
|
+
exit(code: number): void;
|
|
145
|
+
}
|
|
146
|
+
const RT: Runtime = ((): Runtime => {
|
|
147
|
+
const g = globalThis as unknown as {
|
|
148
|
+
Deno?: {
|
|
149
|
+
env: { get(k: string): string | undefined };
|
|
150
|
+
stdout: { writeSync(b: Uint8Array): number };
|
|
151
|
+
addSignalListener(sig: string, h: () => void): void;
|
|
152
|
+
exit(code: number): void;
|
|
153
|
+
};
|
|
154
|
+
process?: {
|
|
155
|
+
env: Record<string, string | undefined>;
|
|
156
|
+
stdout: { write(s: string): boolean };
|
|
157
|
+
on(sig: string, h: () => void): void;
|
|
158
|
+
exit(code: number): void;
|
|
159
|
+
};
|
|
160
|
+
};
|
|
161
|
+
if (g.Deno) {
|
|
162
|
+
const d = g.Deno;
|
|
163
|
+
const enc = new TextEncoder();
|
|
164
|
+
return {
|
|
165
|
+
env: (k) => d.env.get(k),
|
|
166
|
+
write: (line) => void d.stdout.writeSync(enc.encode(line)),
|
|
167
|
+
onSigterm: (h) => d.addSignalListener("SIGTERM", h),
|
|
168
|
+
exit: (c) => d.exit(c),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
const p = g.process!;
|
|
172
|
+
return {
|
|
173
|
+
env: (k) => p.env[k],
|
|
174
|
+
write: (line) => void p.stdout.write(line),
|
|
175
|
+
onSigterm: (h) => p.on("SIGTERM", h),
|
|
176
|
+
exit: (c) => p.exit(c),
|
|
177
|
+
};
|
|
178
|
+
})();
|
|
179
|
+
|
|
180
|
+
function emit(prefix: string, payload: unknown): void {
|
|
181
|
+
// Write directly so it is one atomic line, independent of console.log.
|
|
182
|
+
RT.write(prefix + JSON.stringify(payload) + "\n");
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function falconUrl(baseUrl: string, worker?: string): string {
|
|
186
|
+
let base = baseUrl.replace(/\/+$/, "").replace(/\/v2$/, "");
|
|
187
|
+
if (base.startsWith("http://")) base = "ws://" + base.slice("http://".length);
|
|
188
|
+
else if (base.startsWith("https://")) base = "wss://" + base.slice("https://".length);
|
|
189
|
+
const url = new URL(base + "/falcon");
|
|
190
|
+
if (worker) url.searchParams.set("worker", worker);
|
|
191
|
+
return url.toString();
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Untyped fallback payload for a message with no declared envelope. */
|
|
195
|
+
export type MessageVars = Record<string, unknown>;
|
|
196
|
+
|
|
197
|
+
/** Options for [`publishMessage`]. `variables` is the message payload (typed by
|
|
198
|
+
* the generated `messages.ts` wrapper against the model's envelope). */
|
|
199
|
+
export interface PublishMessageOptions<V extends object = MessageVars> {
|
|
200
|
+
/** The correlation key selecting the target subscription (default ""). */
|
|
201
|
+
correlationKey?: string;
|
|
202
|
+
/** The message payload delivered to correlated instances. */
|
|
203
|
+
variables?: V;
|
|
204
|
+
/** Buffer lifetime in ms. nanobpmn does not buffer, so this is advisory. */
|
|
205
|
+
timeToLive?: number;
|
|
206
|
+
/** Idempotency id for the publish (dedup on the gateway when supported). */
|
|
207
|
+
messageId?: string;
|
|
208
|
+
/** Gateway base URL. Defaults to env NANOBPMN_BASE_URL or http://127.0.0.1:8080. */
|
|
209
|
+
baseUrl?: string;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** The result of a successful [`publishMessage`]. */
|
|
213
|
+
export interface PublishMessageResult {
|
|
214
|
+
/** The minted message key. */
|
|
215
|
+
messageKey: string;
|
|
216
|
+
/** The tenant the message was published to, when the gateway reports one. */
|
|
217
|
+
tenantId?: string;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Publish a message and correlate it to any matching open subscription, via the
|
|
222
|
+
* gateway's `POST /v2/messages/publication` endpoint (the same call an SDK client
|
|
223
|
+
* makes, ADR 0025). nanobpmn does not buffer messages: the message is minted,
|
|
224
|
+
* correlated to every matching open subscription, then dropped. The generated
|
|
225
|
+
* `messages.ts` wrapper narrows `name` to the model's declared message names and
|
|
226
|
+
* types `variables` from the message's data envelope (ADR 0040 slice 2); this raw
|
|
227
|
+
* form moves untyped JSON on the wire. Throws on a non-2xx response.
|
|
228
|
+
*/
|
|
229
|
+
export async function publishMessage(
|
|
230
|
+
name: string,
|
|
231
|
+
opts: PublishMessageOptions = {},
|
|
232
|
+
): Promise<PublishMessageResult> {
|
|
233
|
+
const baseUrl = opts.baseUrl ?? RT.env("NANOBPMN_BASE_URL") ?? "http://127.0.0.1:8080";
|
|
234
|
+
const url = baseUrl.replace(/\/+$/, "").replace(/\/v2$/, "") + "/v2/messages/publication";
|
|
235
|
+
const body: Record<string, unknown> = {
|
|
236
|
+
name,
|
|
237
|
+
correlationKey: opts.correlationKey ?? "",
|
|
238
|
+
variables: opts.variables ?? {},
|
|
239
|
+
};
|
|
240
|
+
if (opts.timeToLive != null) body.timeToLive = opts.timeToLive;
|
|
241
|
+
if (opts.messageId != null) body.messageId = opts.messageId;
|
|
242
|
+
const resp = await fetch(url, {
|
|
243
|
+
method: "POST",
|
|
244
|
+
headers: { "content-type": "application/json" },
|
|
245
|
+
body: JSON.stringify(body),
|
|
246
|
+
});
|
|
247
|
+
if (!resp.ok) {
|
|
248
|
+
const detail = await resp.text().catch(() => "");
|
|
249
|
+
throw new Error(`publishMessage "${name}" failed: ${resp.status} ${detail}`.trim());
|
|
250
|
+
}
|
|
251
|
+
// The gateway mints and returns a `messageKey` on every 2xx (ADR 0025), so a
|
|
252
|
+
// missing/empty key or an unparseable body is a broken response, not a success
|
|
253
|
+
// — fail fast rather than hand back an empty key.
|
|
254
|
+
const json = (await resp.json().catch(() => null)) as
|
|
255
|
+
| { messageKey?: unknown; tenantId?: unknown }
|
|
256
|
+
| null;
|
|
257
|
+
if (json?.messageKey == null || json.messageKey === "") {
|
|
258
|
+
throw new Error(
|
|
259
|
+
`publishMessage "${name}" returned HTTP ${resp.status} but no messageKey`,
|
|
260
|
+
);
|
|
261
|
+
}
|
|
262
|
+
return {
|
|
263
|
+
messageKey: String(json.messageKey),
|
|
264
|
+
tenantId: json.tenantId == null ? undefined : String(json.tenantId),
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export function defineWorker<
|
|
269
|
+
In extends object = WorkerVars,
|
|
270
|
+
Out extends object = WorkerVars,
|
|
271
|
+
Hdr extends object = WorkerHdrs,
|
|
272
|
+
>(typedOpts: WorkerOptions<In, Out, Hdr>): void {
|
|
273
|
+
// The machinery below is type-agnostic (it moves JSON on the wire); the
|
|
274
|
+
// generics are an authoring-time contract only, so erase them internally.
|
|
275
|
+
const opts = typedOpts as unknown as WorkerOptions;
|
|
276
|
+
const baseUrl = opts.baseUrl ?? RT.env("NANOBPMN_BASE_URL") ?? "http://127.0.0.1:8080";
|
|
277
|
+
const workerName = opts.worker ?? RT.env("NANOBPMN_WORKER_NAME") ?? "embedded-worker";
|
|
278
|
+
const maxParallel = opts.maxParallelJobs ?? 10;
|
|
279
|
+
const timeoutMs = opts.timeoutMs ?? 60_000;
|
|
280
|
+
const url = falconUrl(baseUrl, workerName);
|
|
281
|
+
|
|
282
|
+
let corr = 0;
|
|
283
|
+
const nextCorr = () => (corr = (corr + 1) >>> 0);
|
|
284
|
+
|
|
285
|
+
let completed = 0;
|
|
286
|
+
let failed = 0;
|
|
287
|
+
let inFlight = 0;
|
|
288
|
+
let lastError: string | null = null;
|
|
289
|
+
const startedAt = Date.now();
|
|
290
|
+
let lastTotal = 0;
|
|
291
|
+
let lastTick = startedAt;
|
|
292
|
+
let connected = false;
|
|
293
|
+
|
|
294
|
+
let heartbeat: ReturnType<typeof setInterval> | undefined;
|
|
295
|
+
let metricTimer: ReturnType<typeof setInterval> | undefined;
|
|
296
|
+
let ws: WebSocket;
|
|
297
|
+
|
|
298
|
+
const acted = new Set<string>();
|
|
299
|
+
|
|
300
|
+
function send(frame: Record<string, unknown>): void {
|
|
301
|
+
if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(frame));
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function snapshot() {
|
|
305
|
+
return {
|
|
306
|
+
completed,
|
|
307
|
+
failed,
|
|
308
|
+
inFlight,
|
|
309
|
+
lastError,
|
|
310
|
+
uptimeMs: Date.now() - startedAt,
|
|
311
|
+
connected,
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function emitMetrics(): void {
|
|
316
|
+
const now = Date.now();
|
|
317
|
+
const total = completed + failed;
|
|
318
|
+
const dt = (now - lastTick) / 1000;
|
|
319
|
+
const throughput = dt > 0 ? (total - lastTotal) / dt : 0;
|
|
320
|
+
lastTotal = total;
|
|
321
|
+
lastTick = now;
|
|
322
|
+
emit(METRIC, { ...snapshot(), throughput: Math.round(throughput * 100) / 100 });
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function enrich(raw: Record<string, unknown>): WorkerJob {
|
|
326
|
+
const jobKey = String(raw.jobKey ?? raw.key ?? "");
|
|
327
|
+
const markActed = () => acted.add(jobKey);
|
|
328
|
+
return {
|
|
329
|
+
jobKey,
|
|
330
|
+
type: String(raw.type ?? opts.type),
|
|
331
|
+
processInstanceKey: String(raw.processInstanceKey ?? ""),
|
|
332
|
+
processDefinitionId: raw.processDefinitionId as string | undefined,
|
|
333
|
+
processDefinitionKey: raw.processDefinitionKey as string | undefined,
|
|
334
|
+
elementId: raw.elementId as string | undefined,
|
|
335
|
+
retries: raw.retries as number | undefined,
|
|
336
|
+
variables: (raw.variables as Record<string, unknown>) ?? {},
|
|
337
|
+
customHeaders: (raw.customHeaders as Record<string, unknown>) ?? {},
|
|
338
|
+
complete: (variables?: Record<string, unknown>) => {
|
|
339
|
+
markActed();
|
|
340
|
+
send({ type: "completeJob", corr: nextCorr(), jobKey, variables: variables ?? null });
|
|
341
|
+
completed += 1;
|
|
342
|
+
},
|
|
343
|
+
fail: (o?: { retries?: number; errorMessage?: string } | string) => {
|
|
344
|
+
markActed();
|
|
345
|
+
const n = typeof o === "string" ? { errorMessage: o } : o ?? {};
|
|
346
|
+
send({
|
|
347
|
+
type: "failJob",
|
|
348
|
+
corr: nextCorr(),
|
|
349
|
+
jobKey,
|
|
350
|
+
retries: n.retries ?? null,
|
|
351
|
+
errorMessage: n.errorMessage ?? null,
|
|
352
|
+
});
|
|
353
|
+
failed += 1;
|
|
354
|
+
},
|
|
355
|
+
error: (errorCode: string, errorMessage?: string) => {
|
|
356
|
+
markActed();
|
|
357
|
+
send({ type: "throwError", corr: nextCorr(), jobKey, errorCode, errorMessage: errorMessage ?? null });
|
|
358
|
+
completed += 1;
|
|
359
|
+
},
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// The App runtime handed to handlers. `ctx.data()` lazily loads the sibling
|
|
364
|
+
// datasource SDK (materialised next to this file as ./data-sdk.ts) so a worker
|
|
365
|
+
// that never touches data pays nothing and needs no import-map entry.
|
|
366
|
+
const ctx: WorkerContext = {
|
|
367
|
+
data: (name?: string) =>
|
|
368
|
+
import("./data-sdk.ts").then((m) =>
|
|
369
|
+
(m as { openDataSource(n?: string): Promise<WorkerDataSource> }).openDataSource(name)
|
|
370
|
+
),
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
async function dispatch(raw: Record<string, unknown>): Promise<void> {
|
|
374
|
+
const job = enrich(raw);
|
|
375
|
+
inFlight += 1;
|
|
376
|
+
try {
|
|
377
|
+
const out = await opts.handle(job, ctx);
|
|
378
|
+
if (!acted.has(job.jobKey)) {
|
|
379
|
+
// Handler returned without acting: complete with any returned vars.
|
|
380
|
+
job.complete(out && typeof out === "object" ? (out as Record<string, unknown>) : undefined);
|
|
381
|
+
}
|
|
382
|
+
} catch (err) {
|
|
383
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
384
|
+
lastError = msg;
|
|
385
|
+
if (!acted.has(job.jobKey)) job.fail({ errorMessage: msg });
|
|
386
|
+
} finally {
|
|
387
|
+
acted.delete(job.jobKey);
|
|
388
|
+
inFlight -= 1;
|
|
389
|
+
// Replenish one credit so demand stays at maxParallel.
|
|
390
|
+
send({ type: "jobCredits", jobType: opts.type, n: 1 });
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function connect(): void {
|
|
395
|
+
ws = new WebSocket(url);
|
|
396
|
+
ws.onopen = () => {
|
|
397
|
+
emit(STATUS, { state: "connecting", message: `socket open to ${url}` });
|
|
398
|
+
};
|
|
399
|
+
ws.onmessage = (ev: MessageEvent) => {
|
|
400
|
+
let frame: Record<string, unknown>;
|
|
401
|
+
try {
|
|
402
|
+
frame = JSON.parse(typeof ev.data === "string" ? ev.data : "");
|
|
403
|
+
} catch {
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
switch (frame.type) {
|
|
407
|
+
case "welcome": {
|
|
408
|
+
connected = true;
|
|
409
|
+
lastError = null;
|
|
410
|
+
emit(STATUS, { state: "running", message: "subscribed to " + opts.type });
|
|
411
|
+
send({
|
|
412
|
+
type: "subscribe",
|
|
413
|
+
jobType: opts.type,
|
|
414
|
+
jobCredits: maxParallel,
|
|
415
|
+
worker: workerName,
|
|
416
|
+
timeout: timeoutMs,
|
|
417
|
+
fetchVariable: opts.fetchVariables ?? null,
|
|
418
|
+
});
|
|
419
|
+
const hbMs = Number(frame.heartbeatMs ?? 0);
|
|
420
|
+
if (hbMs > 0) {
|
|
421
|
+
clearInterval(heartbeat);
|
|
422
|
+
heartbeat = setInterval(() => send({ type: "heartbeat" }), hbMs);
|
|
423
|
+
}
|
|
424
|
+
break;
|
|
425
|
+
}
|
|
426
|
+
case "job":
|
|
427
|
+
void dispatch((frame.job as Record<string, unknown>) ?? {});
|
|
428
|
+
break;
|
|
429
|
+
case "commandResult": {
|
|
430
|
+
const status = Number(frame.status ?? 0);
|
|
431
|
+
// 404/409 on a fire-and-forget completion is benign (job already gone).
|
|
432
|
+
if (status >= 400 && status !== 404 && status !== 409) {
|
|
433
|
+
lastError = `command failed with status ${status}`;
|
|
434
|
+
}
|
|
435
|
+
break;
|
|
436
|
+
}
|
|
437
|
+
// pressure / submissionCredits / heartbeat: nothing to do for a worker.
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
ws.onerror = () => {
|
|
441
|
+
connected = false;
|
|
442
|
+
lastError = "websocket error";
|
|
443
|
+
emit(STATUS, { state: "error", message: "websocket error" });
|
|
444
|
+
};
|
|
445
|
+
ws.onclose = (ev: CloseEvent) => {
|
|
446
|
+
connected = false;
|
|
447
|
+
clearInterval(heartbeat);
|
|
448
|
+
emit(STATUS, { state: "reconnecting", message: `socket closed (${ev.code}); retrying` });
|
|
449
|
+
setTimeout(connect, 1000);
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
metricTimer = setInterval(emitMetrics, 1000);
|
|
454
|
+
emit(STATUS, { state: "starting", message: `worker '${workerName}' type '${opts.type}'` });
|
|
455
|
+
connect();
|
|
456
|
+
|
|
457
|
+
const shutdown = () => {
|
|
458
|
+
clearInterval(heartbeat);
|
|
459
|
+
clearInterval(metricTimer);
|
|
460
|
+
try {
|
|
461
|
+
ws?.close(1000, "shutdown");
|
|
462
|
+
} catch { /* ignore */ }
|
|
463
|
+
};
|
|
464
|
+
RT.onSigterm(() => {
|
|
465
|
+
shutdown();
|
|
466
|
+
RT.exit(0);
|
|
467
|
+
});
|
|
468
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// AUTO-GENERATED by nanobpmn (ADR 0033 §3): the typed `defineWorker`.
|
|
2
|
+
// Re-exports the worker SDK and overrides `defineWorker` with a taskType-keyed
|
|
3
|
+
// typed signature (job.variables, job.customHeaders + result typed from the
|
|
4
|
+
// worker's declared input/output/header contract). Erased to a pass-through at
|
|
5
|
+
// runtime. Do not edit.
|
|
6
|
+
// eslint-disable
|
|
7
|
+
|
|
8
|
+
import { defineWorker as defineWorkerRaw } from "./worker-sdk.ts";
|
|
9
|
+
import type { WorkerOptions } from "./worker-sdk.ts";
|
|
10
|
+
import type { WorkerInputs, WorkerOutputs, WorkerHeaders, WorkerTaskType, WorkerVars, WorkerHdrs } from "./worker-io.d.ts";
|
|
11
|
+
|
|
12
|
+
export * from "./worker-sdk.ts";
|
|
13
|
+
|
|
14
|
+
type InFor<K extends WorkerTaskType> = K extends keyof WorkerInputs ? WorkerInputs[K] : WorkerVars;
|
|
15
|
+
type OutFor<K extends WorkerTaskType> = K extends keyof WorkerOutputs ? WorkerOutputs[K] : WorkerVars;
|
|
16
|
+
type HdrFor<K extends WorkerTaskType> = K extends keyof WorkerHeaders ? WorkerHeaders[K] : WorkerHdrs;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Typed `defineWorker`: `type` is constrained to the model's declared job types
|
|
20
|
+
* (`WorkerTaskType`, ADR 0033 §3) so it autocompletes and rejects unknown jobs,
|
|
21
|
+
* and the handler's `job.variables`, `job.customHeaders` + result are typed from
|
|
22
|
+
* the worker's declared `inputType`/`outputType`/header keys. A declared job type
|
|
23
|
+
* with no declared type falls back to WorkerVars / WorkerHdrs.
|
|
24
|
+
*/
|
|
25
|
+
export function defineWorker<K extends WorkerTaskType>(
|
|
26
|
+
opts: { type: K } & WorkerOptions<InFor<K> & object, OutFor<K> & object, HdrFor<K> & object>,
|
|
27
|
+
): void {
|
|
28
|
+
defineWorkerRaw(opts as unknown as WorkerOptions);
|
|
29
|
+
}
|
package/nano.app.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://nanobpm.io/spec-app/nano-app.schema.json",
|
|
3
|
+
"schemaVersion": 1,
|
|
4
|
+
"id": "urban-pr-review-codefirst",
|
|
5
|
+
"name": "PR Review Convergence (code-first)",
|
|
6
|
+
"codename": "urban-pr-review-codefirst",
|
|
7
|
+
"data": {
|
|
8
|
+
"default": "app",
|
|
9
|
+
"sources": {
|
|
10
|
+
"app": {
|
|
11
|
+
"driver": "sqlite",
|
|
12
|
+
"url": "${NANO_APP_DB_URL:-file:./app.db}",
|
|
13
|
+
"migrations": "db/migrations"
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "urban-pr-review-codefirst",
|
|
3
|
+
"description": "Code-first (defineFlow) durable, multi-round GitHub PR convergence orchestrated by Nano.",
|
|
4
|
+
"main": "main.ts",
|
|
5
|
+
"lang": "deno",
|
|
6
|
+
"app": "console",
|
|
7
|
+
"autoDeploy": [],
|
|
8
|
+
"template": "workflow-starter",
|
|
9
|
+
"toolchain": {
|
|
10
|
+
"run": [
|
|
11
|
+
"deno",
|
|
12
|
+
"run",
|
|
13
|
+
"--allow-net",
|
|
14
|
+
"--allow-read",
|
|
15
|
+
"--allow-write",
|
|
16
|
+
"--allow-env",
|
|
17
|
+
"--allow-run=deno",
|
|
18
|
+
"main.ts"
|
|
19
|
+
],
|
|
20
|
+
"compile": []
|
|
21
|
+
}
|
|
22
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@nanobpm/urban-pr-review-codefirst",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Code-first (defineFlow) expression of the Nano Urban PR-review convergence app: one durable multi-round loop per PR, BPMN model derived from TypeScript.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "main.ts",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"nano-ide-ext",
|
|
9
|
+
"nano-ide-agentic-sdlc"
|
|
10
|
+
],
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public"
|
|
13
|
+
},
|
|
14
|
+
"scripts": {
|
|
15
|
+
"start": "deno task start",
|
|
16
|
+
"purge": "deno task purge",
|
|
17
|
+
"submit": "deno task submit",
|
|
18
|
+
"review-ready": "deno task review-ready",
|
|
19
|
+
"answer": "deno task answer"
|
|
20
|
+
},
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@nanobpm/workflow": "^0.3.0"
|
|
23
|
+
},
|
|
24
|
+
"devDependencies": {
|
|
25
|
+
"@types/node": "^22",
|
|
26
|
+
"bpmn-auto-layout": "^2.0.0-alpha.2"
|
|
27
|
+
}
|
|
28
|
+
}
|