@nanobpm/nano-workforce 0.194.0 → 0.195.1

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/CHANGELOG.md CHANGED
@@ -1,3 +1,15 @@
1
+ ## [0.195.1](https://github.com/nanobpm/nano-workforce/compare/v0.195.0...v0.195.1) (2026-09-30)
2
+
3
+ ### Bug Fixes
4
+
5
+ * **service:** commit review/fix-ci/rebase rounds to the PR branch, not a nano/agent-work fallback ([#817](https://github.com/nanobpm/nano-workforce/issues/817)) ([212e0cc](https://github.com/nanobpm/nano-workforce/commit/212e0cc9755d2cbba34ed5f170952a5e6a142729)), closes [jwulf/c8ctl-plugin-nano#231](https://github.com/jwulf/c8ctl-plugin-nano/issues/231) [#776](https://github.com/nanobpm/nano-workforce/issues/776)
6
+
7
+ ## [0.195.0](https://github.com/nanobpm/nano-workforce/compare/v0.194.0...v0.195.0) (2026-09-30)
8
+
9
+ ### Features
10
+
11
+ * **feature:** add optional human approval before merge ([#827](https://github.com/nanobpm/nano-workforce/issues/827)) ([fea6b54](https://github.com/nanobpm/nano-workforce/commit/fea6b54ee3fd63f0adccd230e45ee46ed9df24f8)), closes [#826](https://github.com/nanobpm/nano-workforce/issues/826) [#826](https://github.com/nanobpm/nano-workforce/issues/826)
12
+
1
13
  ## [0.194.0](https://github.com/nanobpm/nano-workforce/compare/v0.193.2...v0.194.0) (2026-09-30)
2
14
 
3
15
  ### Features
package/README.md CHANGED
@@ -290,6 +290,12 @@ A single submission can choose its merge behavior explicitly with the positive
290
290
  `converged` regardless of the global default, while `true` enables the merge-loop
291
291
  after convergence only when `NANO_PR_AUTO_MERGE` is enabled.
292
292
 
293
+ A feature run started with `humanApproval` adds a human gate before the merge-loop
294
+ (so it applies only when the run would merge: `autoMerge` with `NANO_PR_AUTO_MERGE`
295
+ enabled): the converged PR waits in the Tasks inbox as "PR merge approval". Approve it
296
+ to merge, or request changes with guidance. The agent then updates the same PR,
297
+ convergence re-runs, and approval is asked again.
298
+
293
299
  ### Fleet mode: hand it an issue (plan → implement → converge)
294
300
 
295
301
  ```
package/SPEC.md CHANGED
@@ -101,7 +101,7 @@ known at submit time, carried as a process variable and stored on the DB row.
101
101
  │ <gateway: status>
102
102
  │ ├── converged → [Check review comments] (pr.converge-gate; ++ackRetryRound on ack-only block)
103
103
  │ │ → <gateway: comments addressed?>
104
- │ │ ├── addressed → [Scope classifier] → … → [Mark converged] → (end)
104
+ │ │ ├── addressed → [Scope classifier] → … → <human approval?> → [Mark converged] → (end)
105
105
  │ │ ├── review stale (#799) → [Record round] (re-solicit fresh review) ┐
106
106
  │ │ └── unaddressed → <gateway: auto-ack within budget?> │
107
107
  │ │ ├── convergeAckOnly and ackRetryRound ≤ ackRetryMax │
@@ -155,6 +155,24 @@ escalates, resolution failure fails open to the human, and re-submitting the PR
155
155
  loop feeds and reads this memory — a merge-loop answer (same `pr.answer-escalation` step)
156
156
  is tagged `answerContext = "merge"` and never recorded as a convergence adjudication.
157
157
 
158
+ **Human approval before merge (issue #826).** A feature run started with `humanApproval`
159
+ seeds `humanApproval = true` on its convergence instance — only when the PR would merge
160
+ (`autoMerge` on and `NANO_PR_AUTO_MERGE` enabled; otherwise it is pinned off).
161
+ After the scope gate passes, the `human approval?` gateway then parks the converged PR on the
162
+ native `merge-approval` user task (`merge-approval.form`, surfaced in the Tasks inbox as
163
+ "PR merge approval") instead of going straight to `[Mark converged]`. `mergeDecision = "approve"`
164
+ continues to `pr.finalize`, which hands the PR to the merge-loop. Approval covers the PR, not a
165
+ pinned SHA: as with any auto-merge, the merge-loop may still rebase it or fix CI before landing.
166
+ Anything else (the form's
167
+ `revise` plus required guidance) loops back to `capture-head` with the guidance as `answer`, so
168
+ the review agent updates the **same** PR. Convergence then re-runs and approval is asked again.
169
+ The default route is fail-closed: once parked, nothing merges without an explicit approval. A
170
+ gated run that adopts a PR already converging under a live loop (e.g. one an ungated run started)
171
+ narrows that loop to `humanApproval = true` rather than inheriting its auto-merge; a loop already
172
+ past its `human approval?` gateway can no longer be gated. The task is
173
+ human-only (never agent-answerable) and never auto-resumed from an adjudication. Without the
174
+ flag the gateway defaults straight through, so existing runs are unchanged.
175
+
158
176
  Guard: after progress classification, a **progressing** round with round ≥
159
177
  MAX_ROUNDS forces an escalation ("not converged after N rounds") so a human
160
178
  decides rather than looping forever. The guard sits *after* `check-progress`
@@ -25,7 +25,7 @@ import type { DataLayer, EngineClient, GatewayDataSource } from "@nanobpm/urban"
25
25
  import { invalidateAdjudication, invalidateAdjudicationByCompletion } from "./adjudications.ts";
26
26
  import { CONFORMANCE_ESCALATION_ELEMENT } from "./conformance.ts";
27
27
  import { DELIVERY_HUMAN_ELEMENT, isDeliveryHumanElement } from "./deliveryHuman.ts";
28
- import { ACP_PERMISSION_ELEMENT, EMPTY_PLAN_ELEMENT, READINESS_ESCALATION_ELEMENT, READINESS_ESCALATION_PF_ELEMENT } from "./userTasks.ts";
28
+ import { ACP_PERMISSION_ELEMENT, EMPTY_PLAN_ELEMENT, PR_MERGE_APPROVAL_ELEMENT, READINESS_ESCALATION_ELEMENT, READINESS_ESCALATION_PF_ELEMENT } from "./userTasks.ts";
29
29
 
30
30
  const now = () => new Date().toISOString();
31
31
 
@@ -136,6 +136,9 @@ export const HUMAN_COMPLETABLE_ELEMENTS: ReadonlySet<string> = new Set([
136
136
  READINESS_ESCALATION_PF_TASK_ELEMENT,
137
137
  READINESS_ESCALATION_TASK_ELEMENT,
138
138
  ACP_PERMISSION_ELEMENT,
139
+ // Human-only (issue #826): never agent-answerable, so it stays OUT of ESCALATION_TASK_ELEMENTS and the
140
+ // fleet can never auto-approve a merge.
141
+ PR_MERGE_APPROVAL_ELEMENT,
139
142
  ]);
140
143
 
141
144
  /** Each escalation `elementId` → the `.form` whose contract governs its completion variables (the
@@ -153,6 +156,7 @@ const ESCALATION_FORM_BY_ELEMENT: Readonly<Record<string, string>> = {
153
156
  [CONFORMANCE_ESCALATION_TASK_ELEMENT]: "conformance-escalation",
154
157
  [READINESS_ESCALATION_PF_TASK_ELEMENT]: "readiness-escalation",
155
158
  [READINESS_ESCALATION_TASK_ELEMENT]: "readiness-escalation",
159
+ [PR_MERGE_APPROVAL_ELEMENT]: "merge-approval",
156
160
  // NOTE: the delivery-graph `human` node (`DELIVERY_HUMAN_ELEMENT`, ADR 0005 S3) is intentionally
157
161
  // ABSENT here. Unlike the fixed-form escalations above, ONE `delivery-human-task` element is DESIGNED
158
162
  // to render DIFFERENT forms per node (explicit → category → generic → agent-router, `app/deliveryHuman.ts`
package/app/contracts.ts CHANGED
@@ -424,7 +424,7 @@ export const WIRE_CONTRACTS = {
424
424
  name: "io.nanobpm.agentTask.repository",
425
425
  owner: "app/repoEnvelope.ts",
426
426
  semantics:
427
- "Repo-provisioning envelope the app emits as a `createInstance` process variable (`repoEnvelopeVars`, app/repoEnvelope.ts) and the c8ctl worker harness consumes to provision an isolated clone — instead of the agent inheriting the worker's launch dir (issue #684). `ref` is the branch checked out: the PR HEAD branch on the PR-based paths (review-round / fix-ci / rebase), or — on the PRE-PR implementation path (feature.bpmn / plan-fanout's `implement-cell`, issue #684; the delivery-graph runner's agent cells, issue #686) — the BASE branch, off which the harness cuts a new feature branch named by the optional `branch.create` (the deterministic `feat/<task.id>`, emitted for a single-task feature run AND — per issue #776 — the deterministic `feat/<node.id>` for each single-instance delivery-graph agent cell, injected per-cell by `agentNodeRepoEnvelope`/`app/deliveryRunner.ts` so a forgetful agent can never be left committing on the base branch and stranding its run on a non-ff push; the epic plan-fanout seed still omits it because its MI children each cut a per-child `feat/<task.id>` the app can't name at compile time, so those agents branch themselves). Beyond `{provider,url,ref}`, it carries clone-shaping fields for large monorepos (issue #287): `singleBranch:true` + `filter:\"blob:none\"` (a branch-scoped, blobless partial clone — trees fetched up-front, blobs lazily, no `--depth 1` so the merge-base/3-dot diff stays valid) and an optional `baseRef` (the PR base branch, emitted only when resolvable, so the harness fetches its tip and keeps `origin/<base>` reachable) and a `cloneTimeoutMs` (from `NANO_PR_CLONE_TIMEOUT_MS`, default 600000 = 10 min) that raises the harness's 120s default so a large monorepo's blobless single-branch clone provisions instead of dying at 120s (issue #694). World-restore (issue #324, ADR 0062 Slice 4/5): an optional `sha` — the last durable push-checkpoint — is emitted so a REPLACEMENT activation on a fresh worktree reconstructs the tree to the EXACT pushed SHA (inverting the round's `git push` into `git fetch && git checkout <sha>`), omitted when the PR has no checkpoint yet. The field is named `sha` because that is the field the c8ctl harness's `provisionRepo` reads to drive the checkout — an earlier `commitSha` key was a silent no-op (issue #695). Alongside the `repository` slice the envelope carries a sibling `task.allowPr: true` (issue #770): c8ctl-plugin-nano (≥1.60.2) only resolves the git credential (GITHUB_TOKEN, or the `gh` default) for repo provisioning behind that flag, so every repo-backed envelope sets it or the clone dies with `unable to get password from user`; the repoless path emits no envelope and so no `task`. Gated on c8ctl provisioner support (jwulf/c8ctl-plugin-nano#91, branch-cut guard jwulf/c8ctl-plugin-nano#231).",
427
+ "Repo-provisioning envelope the app emits as a `createInstance` process variable (`repoEnvelopeVars`, app/repoEnvelope.ts) and the c8ctl worker harness consumes to provision an isolated clone — instead of the agent inheriting the worker's launch dir (issue #684). `ref` is the branch checked out: the PR HEAD branch on the PR-based paths (review-round / fix-ci / rebase), or — on the PRE-PR implementation path (feature.bpmn / plan-fanout's `implement-cell`, issue #684; the delivery-graph runner's agent cells, issue #686) — the BASE branch, off which the harness cuts a new feature branch named by the optional `branch.create`. On the PRE-PR path `branch.create` is the deterministic `feat/<task.id>` (emitted for a single-task feature run AND — per issue #776 — the deterministic `feat/<node.id>` for each single-instance delivery-graph agent cell, injected per-cell by `agentNodeRepoEnvelope`/`app/deliveryRunner.ts` so a forgetful agent can never be left committing on the base branch and stranding its run on a non-ff push; the epic plan-fanout seed still omits it because its MI children each cut a per-child `feat/<task.id>` the app can't name at compile time, so those agents branch themselves). On the PR-based paths `branch.create` is set to the PR HEAD branch itself (equal to `ref`, jwulf/c8ctl-plugin-nano#231): without it the harness's base-branch guard treats the checkout as base-like and cuts a throwaway `nano/agent-work/<base>-<run>` fallback, stranding the round's commits OFF the PR; with `ref == create == head` the harness does a no-op `checkout -B <head>` and commits/pushes to the PR head branch. So `branch.create` is present on both the pre-PR and PR-based paths (only a blank/omitted value drops the key). Beyond `{provider,url,ref}`, it carries clone-shaping fields for large monorepos (issue #287): `singleBranch:true` + `filter:\"blob:none\"` (a branch-scoped, blobless partial clone — trees fetched up-front, blobs lazily, no `--depth 1` so the merge-base/3-dot diff stays valid) and an optional `baseRef` (the PR base branch, emitted only when resolvable, so the harness fetches its tip and keeps `origin/<base>` reachable) and a `cloneTimeoutMs` (from `NANO_PR_CLONE_TIMEOUT_MS`, default 600000 = 10 min) that raises the harness's 120s default so a large monorepo's blobless single-branch clone provisions instead of dying at 120s (issue #694). World-restore (issue #324, ADR 0062 Slice 4/5): an optional `sha` — the last durable push-checkpoint — is emitted so a REPLACEMENT activation on a fresh worktree reconstructs the tree to the EXACT pushed SHA (inverting the round's `git push` into `git fetch && git checkout <sha>`), omitted when the PR has no checkpoint yet. The field is named `sha` because that is the field the c8ctl harness's `provisionRepo` reads to drive the checkout — an earlier `commitSha` key was a silent no-op (issue #695). Alongside the `repository` slice the envelope carries a sibling `task.allowPr: true` (issue #770): c8ctl-plugin-nano (≥1.60.2) only resolves the git credential (GITHUB_TOKEN, or the `gh` default) for repo provisioning behind that flag, so every repo-backed envelope sets it or the clone dies with `unable to get password from user`; the repoless path emits no envelope and so no `task`. Gated on c8ctl provisioner support (jwulf/c8ctl-plugin-nano#91, branch-cut guard jwulf/c8ctl-plugin-nano#231).",
428
428
  shape:
429
429
  'io.nanobpm.agentTask: { repository: { provider: "github", url: string, ref?: string, singleBranch: true, filter: "blob:none", cloneTimeoutMs: number, baseRef?: string, sha?: string, branch?: { create: string } }, task: { allowPr: true } }',
430
430
  },
@@ -1073,14 +1073,21 @@ test("classify-scope feeds gw-scope-gate, which blocks on scopeBlocked = true",
1073
1073
  assertStringIncludes(blocked, "scopeBlocked = true");
1074
1074
  });
1075
1075
 
1076
- test("gw-scope-gate default arm finalizes (scope ok → persist-converged)", () => {
1076
+ test("gw-scope-gate default arm continues to the optional merge approval, whose default finalizes", () => {
1077
1077
  const gw = flat.match(/<bpmn:exclusiveGateway\b[^>]*\bid="gw-scope-gate"[^>]*>/);
1078
1078
  assert(gw, "gw-scope-gate gateway missing");
1079
1079
  assertStringIncludes(gw[0], 'default="f_scopeOk"');
1080
1080
  const ok = flowElement("f_scopeOk");
1081
1081
  assert(ok, "f_scopeOk flow missing");
1082
- assertStringIncludes(ok, 'targetRef="persist-converged"');
1082
+ assertStringIncludes(ok, 'targetRef="gw-approval"');
1083
1083
  assert(!/conditionExpression/.test(ok), "the default arm must carry no conditionExpression");
1084
+ // Issue #826: without `humanApproval` the approval gateway's default arm finalizes as before.
1085
+ const approval = flat.match(/<bpmn:exclusiveGateway\b[^>]*\bid="gw-approval"[^>]*>/);
1086
+ assert(approval, "gw-approval gateway missing");
1087
+ assertStringIncludes(approval[0], 'default="f_noApproval"');
1088
+ const noApproval = flowElement("f_noApproval");
1089
+ assert(noApproval, "f_noApproval flow missing");
1090
+ assertStringIncludes(noApproval, 'targetRef="persist-converged"');
1084
1091
  });
1085
1092
 
1086
1093
  test("the scope escalation routes through gw-escalated with the classifier's specific reason", () => {
@@ -73,7 +73,7 @@ test("capture-head still precedes review-round on every loop entry (the reset is
73
73
  const el = serviceTask("capture-head");
74
74
  assert(el, "capture-head service task must exist");
75
75
  const incoming = [...el!.matchAll(/<bpmn:incoming>([^<]+)<\/bpmn:incoming>/g)].map((m) => m[1]);
76
- for (const flow of ["f_start", "f_reviewLoop", "f_answerLoop", "f_huskRetry", "f_ackRetry"]) {
76
+ for (const flow of ["f_start", "f_reviewLoop", "f_answerLoop", "f_huskRetry", "f_ackRetry", "f_revise"]) {
77
77
  assert(incoming.includes(flow), `capture-head must be the entry join for ${flow} so the reset covers that re-entry (issue #822)`);
78
78
  }
79
79
  const capture = flat.match(/<bpmn:sequenceFlow[^>]*\bid="f_capture"[^>]*\/>/);
@@ -124,6 +124,22 @@ test("startFeature: converge/autoMerge flags are persisted as 0/1", async () =>
124
124
  assertEquals(row.auto_merge, 1);
125
125
  });
126
126
 
127
+ test("startFeature: humanApproval is persisted as 0/1 and seeded onto the instance (issue #826)", async () => {
128
+ for (const humanApproval of [true, false]) {
129
+ const stores = { feature_runs: { rows: [] as any[], key: "feature_key" } };
130
+ let vars: any = null;
131
+ const engine = {
132
+ createInstance: (req: any) => {
133
+ vars = req.variables;
134
+ return Promise.resolve({ processInstanceKey: "PI-1" });
135
+ },
136
+ } as any;
137
+ await startFeature(memData(stores), engine, PARSED, "main", true, true, null, {}, humanApproval);
138
+ assertEquals(stores.feature_runs.rows[0].human_approval, humanApproval ? 1 : 0);
139
+ assertEquals(vars.humanApproval, humanApproval);
140
+ }
141
+ });
142
+
127
143
  test("startFeature: seeds the single task slice + base-branch brief onto the instance", async () => {
128
144
  let captured: any = null;
129
145
  const engine = {
package/app/feature.ts CHANGED
@@ -60,6 +60,9 @@ export interface FeatureRun {
60
60
  pr_key: string | null;
61
61
  converge: number;
62
62
  auto_merge: number;
63
+ /** 1 ⇒ a human must approve the converged PR before the merge-loop runs (issue #826). Only
64
+ * meaningful with `auto_merge = 1`; the `startFeature` operation pins it to 0 otherwise. */
65
+ human_approval: number;
63
66
  outcome: string | null;
64
67
  /** Human rollup detail. Projected by `pollFeatureDelivery` (fix: Feature history stuck at
65
68
  * `converging`) and also written by `pr.record-blocked-ack` with the operator's disposition
@@ -352,6 +355,7 @@ export async function startFeature(
352
355
  autoMerge: boolean,
353
356
  customInstructions: string | null = null,
354
357
  readiness: FeatureReadinessOptions = {},
358
+ humanApproval = false,
355
359
  ): Promise<StartFeatureResult> {
356
360
  // Intake-time readiness gate (issue #295): the probes the run must satisfy before it implements,
357
361
  // and the bound its preflight escalation timers fire off. Both are load-bearing together —
@@ -450,6 +454,7 @@ export async function startFeature(
450
454
  pr_key: null,
451
455
  converge: converge ? 1 : 0,
452
456
  auto_merge: autoMerge ? 1 : 0,
457
+ human_approval: humanApproval ? 1 : 0,
453
458
  outcome: null,
454
459
  delivery_label: null,
455
460
  // Clear the operator tick-off so a re-dispatched run is NOT silently dropped into History when
@@ -472,6 +477,7 @@ export async function startFeature(
472
477
  pr_key: null,
473
478
  converge: converge ? 1 : 0,
474
479
  auto_merge: autoMerge ? 1 : 0,
480
+ human_approval: humanApproval ? 1 : 0,
475
481
  outcome: null,
476
482
  delivery_label: null,
477
483
  created_at: ts,
@@ -507,6 +513,8 @@ export async function startFeature(
507
513
  // merge-loop. `converge=false` ⇒ merge is moot.
508
514
  converge,
509
515
  autoMerge,
516
+ // Park the converged PR at a human approval user task before the merge-loop (issue #826).
517
+ humanApproval,
510
518
  // A single-issue feature run OWNS its issue (the whole issue is the slice), so the agent may
511
519
  // claim it with a "starting work" comment on a first run (resources/prompts/feature.md). Epic slices
512
520
  // (plan-fanout) deliberately DO NOT set this — their `issue` is the shared parent epic, which
@@ -197,6 +197,27 @@ test("pollFeatureDelivery: a converging run whose PR row is MISSING is re-enroll
197
197
  assertEquals(stores.feature_runs[0].delivery_label, "PR record missing");
198
198
  });
199
199
 
200
+ test("pollFeatureDelivery: the re-enroll keeps the run's human approval gate (issue #826)", async () => {
201
+ const { data, stores } = memData();
202
+ stores.feature_runs = [
203
+ { feature_key: "o/r#7", status: "converging", pr_key: "o/r#407", auto_merge: 1, human_approval: 1, delivery_label: null },
204
+ ];
205
+ stores.pull_requests = [];
206
+ let vars: Record<string, unknown> | undefined;
207
+ const engine = {
208
+ searchProcessInstances: async () => [],
209
+ createInstance: async (req: { variables?: Record<string, unknown> }) => {
210
+ vars = req.variables;
211
+ return { processInstanceKey: "pi-407" };
212
+ },
213
+ } as any;
214
+
215
+ await pollFeatureDelivery(data, engine);
216
+
217
+ assertEquals(vars?.convergeOnly, false);
218
+ assertEquals(vars?.humanApproval, true, "a healed enrollment must not silently drop the approval gate");
219
+ });
220
+
200
221
  test("pollFeatureDelivery: a converging run whose PR row is PARTIALLY enrolled (present, non-terminal, process_key NULL) is re-enrolled — a create-instance crash after the row insert does not wedge it (PR #809)", async () => {
201
222
  const { data, stores } = memData();
202
223
  stores.feature_runs = [
@@ -115,7 +115,7 @@ test("feature.bpmn composes its converge step via callActivity to converge-cell
115
115
  /<zeebe:ioMapping>[\s\S]*?<\/zeebe:ioMapping>/.test(convergeBlock),
116
116
  "the converge callActivity must carry an explicit zeebe:ioMapping",
117
117
  );
118
- for (const field of ["featureKey", "prKey", "autoMerge"]) {
118
+ for (const field of ["featureKey", "prKey", "autoMerge", "humanApproval"]) {
119
119
  assert(
120
120
  new RegExp(`<zeebe:input\\b[^>]*\\btarget="${field}"`).test(convergeBlock),
121
121
  `the converge callActivity ioMapping must map ConvergeFeatureIn.${field} into the child scope`,
@@ -111,8 +111,13 @@ export const MCP_TOOL_COUNT_BUDGET = 60;
111
111
  * `getAgenticSupply`, and registry read schemas (plus the `StaleWorker` leaf) so an operator can spot
112
112
  * and drain a stale harness from the tool surface alone. Measured 86,509 bytes serialized — 9 over the
113
113
  * old ceiling's headroom. Deliberate, documented growth — not schema fat.
114
+ *
115
+ * RAISE PROVENANCE — 87_000 → 87_500 (#826): the per-run `humanApproval` start option on both
116
+ * `startFeature` body variants (`FeatureStartByIssue`/`FeatureStartByUrl`) — the Feature tab's
117
+ * "Human approval before merge" checkbox. Measured 87,293 bytes serialized (86,862 → 87,293 — over
118
+ * the old ceiling's 138-byte headroom). Deliberate, documented growth — not schema fat.
114
119
  */
115
- export const MCP_SURFACE_BYTES_BUDGET = 87_000;
120
+ export const MCP_SURFACE_BYTES_BUDGET = 87_500;
116
121
 
117
122
  /**
118
123
  * The eagerly-loaded curated subset MUST stay materially smaller than the full surface — otherwise it
@@ -0,0 +1,126 @@
1
+ // Human approval before merge (issue #826): an optional `merge-approval` user task in the convergence
2
+ // loop, between the scope gate and `persist-converged` (`pr.finalize`, the merge-loop handoff). These
3
+ // deploy the committed model into the WASM engine and drive tokens through it: flag off → finalizes
4
+ // straight away; flag on → parks for a human; approve → finalizes; request changes (or anything that is
5
+ // not an explicit approve) → the guidance goes back to the review agent on the same PR, then approval is
6
+ // asked again.
7
+ import { after, test } from "node:test";
8
+ import { readFileSync } from "node:fs";
9
+ import { assert, assertEquals } from "#test-assert";
10
+ import { assertThatInstance, byProcessId, createWasmEngineClient, type WasmEngineClient } from "@nanobpm/urban-testkit";
11
+ import { ESCALATION_TASK_ELEMENTS, HUMAN_COMPLETABLE_ELEMENTS, validateEscalationVariables } from "./agentCompletion.ts";
12
+ import { PR_MERGE_APPROVAL_ELEMENT } from "./userTasks.ts";
13
+
14
+ const MODEL = readFileSync("resources/processes/convergence-loop.bpmn", "utf8");
15
+
16
+ const engines: WasmEngineClient[] = [];
17
+ after(async () => {
18
+ await Promise.all(engines.map((e) => e.close()));
19
+ });
20
+
21
+ /** Boots one loop whose every round converges cleanly; `answers` records the `answer` each review round saw.
22
+ * Job types in `held` get no worker until `register(type)`, so a test can act while the loop waits there. */
23
+ async function boot(vars: Record<string, unknown>, held: string[] = []) {
24
+ const engine = await createWasmEngineClient();
25
+ engines.push(engine);
26
+ await engine.deployResources([{ name: "convergence-loop.bpmn", content: MODEL, contentType: "text/xml" }]);
27
+ const answers: unknown[] = [];
28
+ const workers: Record<string, (v: Record<string, unknown>) => Record<string, unknown>> = {
29
+ "senior:pr-review": (v) => {
30
+ answers.push(v.answer);
31
+ return { status: "converged", summary: "done" };
32
+ },
33
+ "pr.capture-head": () => ({ roundEntryHead: "sha" }),
34
+ "pr.persist-round": () => ({}),
35
+ "pr.progress-check": () => ({ progressed: true }),
36
+ "pr.converge-gate": () => ({ convergeBlocked: false, convergeBlockReason: "", convergeAckOnly: false }),
37
+ "senior:scope-classify": () => ({ scopeBlocked: false, scopeBlockReason: "" }),
38
+ "pr.finalize": () => ({}),
39
+ };
40
+ const register = (type: string) =>
41
+ engine.registerWorker(type, (job) => workers[type]((job as { variables: Record<string, unknown> }).variables));
42
+ for (const type of Object.keys(workers)) if (!held.includes(type)) await register(type);
43
+ const { processInstanceKey } = await engine.createInstance({
44
+ processDefinitionId: "convergence-loop",
45
+ awaitCompletion: false,
46
+ variables: { prKey: "o/r#1", repo: "o/r", prNumber: 1, round: 1, maxRounds: 20, answer: null, huskRetries: 0, ...vars },
47
+ });
48
+ return { engine, answers, register, processInstanceKey };
49
+ }
50
+
51
+ function completions(engine: WasmEngineClient, elementId: string): number {
52
+ const snap = engine.snapshot() as { elementStats?: { elementId: string; completed: number }[] };
53
+ return (snap.elementStats ?? []).find((s) => s.elementId === elementId)?.completed ?? 0;
54
+ }
55
+
56
+ async function openApproval(engine: WasmEngineClient): Promise<string | undefined> {
57
+ return (await engine.openUserTasks()).find((t) => t.elementId === PR_MERGE_APPROVAL_ELEMENT)?.userTaskKey;
58
+ }
59
+
60
+ const loop = (engine: WasmEngineClient) => assertThatInstance(engine, byProcessId("convergence-loop"));
61
+
62
+ test("without humanApproval a converged PR finalizes straight away — no approval task", async () => {
63
+ // `humanApproval` deliberately unseeded: a missing flag must behave exactly like `false`.
64
+ const { engine } = await boot({});
65
+ loop(engine).hasCompleted().hasNoIncident();
66
+ assertEquals(completions(engine, "persist-converged"), 1);
67
+ assertEquals(completions(engine, PR_MERGE_APPROVAL_ELEMENT), 0);
68
+ });
69
+
70
+ test("with humanApproval a converged PR parks for a human, and approve finalizes it", async () => {
71
+ const { engine } = await boot({ humanApproval: true });
72
+ loop(engine).isActive().hasActiveElement(PR_MERGE_APPROVAL_ELEMENT).hasNoIncident();
73
+ assertEquals(completions(engine, "persist-converged"), 0, "nothing hands off to the merge-loop before approval");
74
+
75
+ const key = await openApproval(engine);
76
+ assert(key !== undefined, "the approval task is open");
77
+ await engine.completeUserTask(key, { mergeDecision: "approve" });
78
+ loop(engine).hasCompleted().hasNoIncident();
79
+ assertEquals(completions(engine, "persist-converged"), 1);
80
+ });
81
+
82
+ test("request changes sends the guidance to the review agent on the same PR, then asks again", async () => {
83
+ const { engine, answers } = await boot({ humanApproval: true });
84
+ const first = await openApproval(engine);
85
+ assert(first !== undefined, "the approval task is open");
86
+ await engine.completeUserTask(first, { mergeDecision: "revise", answer: "Rename foo to bar." });
87
+
88
+ loop(engine).isActive().hasActiveElement(PR_MERGE_APPROVAL_ELEMENT).hasNoIncident();
89
+ assertEquals(answers.length, 2, "the review agent ran again");
90
+ assertEquals(answers[1], "Rename foo to bar.", "the revise round received the human's guidance");
91
+ assertEquals(completions(engine, "capture-head"), 2, "the revise re-entered the same loop");
92
+ assertEquals(completions(engine, "persist-converged"), 0);
93
+ const second = await openApproval(engine);
94
+ assert(second !== undefined && second !== first, "approval is asked again after the revision");
95
+ });
96
+
97
+ test("a live ungated loop narrowed to humanApproval (a gated submitPr adopting it) parks for approval", async () => {
98
+ // `submitPr` narrows an adopted live loop with setVariables (app/service.ts); the gateway must honour it.
99
+ const { engine, register, processInstanceKey } = await boot({ humanApproval: false }, ["senior:pr-review"]);
100
+ loop(engine).isActive().hasActiveElement("review-round");
101
+ await engine.setVariables({ scopeKey: String(processInstanceKey), variables: { humanApproval: true } });
102
+ await register("senior:pr-review");
103
+ loop(engine).isActive().hasActiveElement(PR_MERGE_APPROVAL_ELEMENT).hasNoIncident();
104
+ assertEquals(completions(engine, "persist-converged"), 0, "the adopted loop never merges unapproved");
105
+ });
106
+
107
+ test("fail-closed: a completion without an explicit approve never merges", async () => {
108
+ const { engine } = await boot({ humanApproval: true });
109
+ const key = await openApproval(engine);
110
+ assert(key !== undefined, "the approval task is open");
111
+ await engine.completeUserTask(key, {});
112
+ loop(engine).isActive().hasActiveElement(PR_MERGE_APPROVAL_ELEMENT).hasNoIncident();
113
+ assertEquals(completions(engine, "persist-converged"), 0);
114
+ });
115
+
116
+ test("merge-approval is human-only, and its form requires guidance only for request changes", () => {
117
+ assert(HUMAN_COMPLETABLE_ELEMENTS.has(PR_MERGE_APPROVAL_ELEMENT), "the human completer accepts it");
118
+ assert(!ESCALATION_TASK_ELEMENTS.has(PR_MERGE_APPROVAL_ELEMENT), "an agent must never approve a merge");
119
+ const check = (vars: Record<string, unknown>) => validateEscalationVariables(PR_MERGE_APPROVAL_ELEMENT, vars);
120
+ assertEquals(check({ mergeDecision: "approve" }), null);
121
+ assertEquals(check({ mergeDecision: "revise", answer: "Rename foo." }), null);
122
+ assert(check({}) !== null, "a decision is required");
123
+ assert(check({ mergeDecision: "revise" }) !== null, "request changes needs guidance");
124
+ assert(check({ mergeDecision: "revise", answer: " " }) !== null, "blank guidance is rejected");
125
+ assert(check({ mergeDecision: "merge" }) !== null, "only approve/revise are accepted");
126
+ });
@@ -133,8 +133,14 @@ export class RepoEnvelopeConflictError extends Error {
133
133
  * `implement-cell`) dispatches its agent BEFORE any PR exists, so it passes `ref = base` and a
134
134
  * `branchCreate` naming the deterministic `feat/<task.id>` feature branch the harness cuts off that
135
135
  * base itself (the agent-guide's `feat/*` convention) — instead of the agent branching by hand — so
136
- * the isolated clone lands on the right branch deterministically across a resume. `branchCreate` is
137
- * omitted on the PR-based paths, which check out an existing head. */
136
+ * the isolated clone lands on the right branch deterministically across a resume. The PR-based paths
137
+ * (review-round / fix-ci / rebase) ALSO pass `branchCreate = ref` (the PR HEAD branch, equal to
138
+ * `ref`): without an explicit `branch.create` the harness's base-branch guard
139
+ * (jwulf/c8ctl-plugin-nano#231) treats the checkout as base-like and cuts a throwaway
140
+ * `nano/agent-work/<base>-<run>` fallback, stranding the round's commits OFF the PR; with
141
+ * `ref == create == head` the harness does a no-op `checkout -B <head>` and commits/pushes to the PR
142
+ * head branch itself. `branchCreate` is therefore emitted on both the pre-PR and PR-based paths (only
143
+ * a blank/omitted value drops the key). */
138
144
  export function repoEnvelopeVars(
139
145
  repo: string,
140
146
  ref: string | null,
@@ -186,7 +192,10 @@ export function repoEnvelopeVars(
186
192
  // head. `branchCreate` asks the harness to cut the deterministic `feat/<task.id>` feature branch
187
193
  // off that base itself (the agent-guide's `feat/*` convention) instead of the agent branching by
188
194
  // hand — making the isolated clone land on the right branch deterministically across a resume.
189
- // Omitted (no key) on the PR-based paths (review/fix-ci/rebase), which check out an existing head.
195
+ // The PR-based paths (review/fix-ci/rebase) ALSO pass `branchCreate = ref` (the PR head): without
196
+ // it the harness's base-branch guard (jwulf/c8ctl-plugin-nano#231) cuts a throwaway
197
+ // `nano/agent-work/*` fallback OFF the PR; with `ref == create == head` it commits/pushes to the
198
+ // head branch. Only a blank/omitted value drops the key.
190
199
  ...(typeof branchCreate === "string" && branchCreate.trim() !== ""
191
200
  ? { branch: { create: branchCreate.trim() } }
192
201
  : {}),