@nanobpm/nano-workforce 0.114.0 → 0.114.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,10 @@
1
+ ## [0.114.1](https://github.com/nanobpm/nano-workforce/compare/v0.114.0...v0.114.1) (2026-08-20)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * **convergence-loop:** give the scope-integrity gate a human-override door ([#395](https://github.com/nanobpm/nano-workforce/issues/395)) ([#401](https://github.com/nanobpm/nano-workforce/issues/401)) ([23f8354](https://github.com/nanobpm/nano-workforce/commit/23f83541c57b3474b36a92baa1d88bdd6535df9b))
7
+
1
8
  # [0.114.0](https://github.com/nanobpm/nano-workforce/compare/v0.113.0...v0.114.0) (2026-08-20)
2
9
 
3
10
 
@@ -218,11 +218,14 @@ async function makeUnderTest(deps: {
218
218
  readThreads: (repo: string, n: number) => Promise<ReviewThread[] | null>;
219
219
  readReviewBody: (repo: string, n: number) => Promise<string | null>;
220
220
  readPrBody?: (repo: string, n: number) => Promise<string | null>;
221
+ readHeadSha?: (repo: string, n: number) => Promise<string | null>;
221
222
  }) {
222
223
  const { makeHandler } = await import("../workers/converge-gate/worker.ts");
223
224
  // Default the scope-guard PR-body read to a verified-empty description so the comment-gate tests
224
- // below exercise only the review-comment dimension; scope-guard tests pass an explicit body.
225
- return makeHandler({ readPrBody: async () => "", ...deps });
225
+ // below exercise only the review-comment dimension; scope-guard tests pass an explicit body. The
226
+ // HEAD read defaults to null (unreadable) so a scope block stays blocked unless a test opts into
227
+ // the #395 override door with an explicit HEAD — see workers/converge-gate/worker.test.ts.
228
+ return makeHandler({ readPrBody: async () => "", readHeadSha: async () => null, ...deps });
226
229
  }
227
230
 
228
231
  test("converge-gate: a clean PR is allowed to converge", async () => {
@@ -212,3 +212,36 @@ test("a control-flow arm with a blank question opens nothing so gw-escalated re-
212
212
  assertEquals(inserts.escalations.length, 0, "no dead escalation is fabricated");
213
213
  assertEquals(updates.pull_requests?.length ?? 0, 0, "the PR is never flipped to escalated");
214
214
  });
215
+
216
+ // The scope-integrity arm (persist-escalation-blockedcomments) binds the escalation to the reviewed
217
+ // commit (issue #395): it stamps `head_sha` and marks `scope_block` so the converge-gate can honour
218
+ // a same-HEAD human answer as an override instead of re-deriving the block and re-escalating forever.
219
+ test("persist-escalation binds a scope-integrity escalation to the reviewed HEAD (head_sha + scope_block)", async () => {
220
+ const { app, inserts } = fakeApp();
221
+ const job = {
222
+ variables: {
223
+ prKey: "o/r#5",
224
+ round: 2,
225
+ status: "blocked",
226
+ question: "Scope integrity blocked: ...",
227
+ recordRound: false,
228
+ headSha: "HEAD1",
229
+ scopeBlock: true,
230
+ },
231
+ };
232
+ await handler(job as any, app as any);
233
+ assertEquals(inserts.escalations.length, 1);
234
+ assertEquals((inserts.escalations[0] as any).head_sha, "HEAD1", "the escalation carries the reviewed commit");
235
+ assertEquals((inserts.escalations[0] as any).scope_block, 1, "flagged as a scope-integrity block");
236
+ });
237
+
238
+ // Every other escalation arm (agent verdict, no-progress, max-rounds, stalled) omits the scope
239
+ // binding: head_sha stays absent and scope_block defaults to 0, so the override door opens ONLY for
240
+ // the block a human can actually answer.
241
+ test("persist-escalation: a non-scope escalation records no HEAD binding and scope_block 0", async () => {
242
+ const { app, inserts } = fakeApp();
243
+ const job = { variables: { prKey: "o/r#1", round: 3, status: "blocked", question: "max rounds" } };
244
+ await handler(job as any, app as any);
245
+ assertEquals((inserts.escalations[0] as any).head_sha, undefined, "no reviewed HEAD to bind");
246
+ assertEquals((inserts.escalations[0] as any).scope_block, 0, "not a scope-integrity block");
247
+ });
@@ -14,6 +14,7 @@ import {
14
14
  findClosingKeywordRefs,
15
15
  hasDeferralMarker,
16
16
  hasFollowupIssueRef,
17
+ isScopeOverridden,
17
18
  } from "./scopeGuard.ts";
18
19
 
19
20
  // ── The canonical router ────────────────────────────────────────────────────
@@ -145,3 +146,40 @@ test("hasFollowupIssueRef: only an explicit tracking marker + issue ref counts",
145
146
  "Follow-up marker with a full issue URL",
146
147
  );
147
148
  });
149
+
150
+ // ── The human-override door (#395) ──────────────────────────────────────────
151
+ // The scope-integrity gate re-derives `scopeBlocked` from the PR body every round, so answering
152
+ // its escalation used to re-block identically (an infinite loop). An answer bound to the SAME
153
+ // reviewed HEAD is now honoured as an explicit override; a different HEAD (a new push) is not.
154
+
155
+ test("isScopeOverridden: an answer bound to the same HEAD overrides the block", () => {
156
+ assert(
157
+ isScopeOverridden("abc123", { escalationId: 7, headSha: "abc123", answer: "Full delivery — keep Closes." }),
158
+ "same-HEAD answered escalation is an override",
159
+ );
160
+ });
161
+
162
+ test("isScopeOverridden: an answer for a DIFFERENT HEAD does not override (a new push re-opens)", () => {
163
+ assert(
164
+ !isScopeOverridden("newHEAD", { escalationId: 7, headSha: "oldHEAD", answer: "Full delivery." }),
165
+ "an override never carries across a new push",
166
+ );
167
+ });
168
+
169
+ test("isScopeOverridden: no recorded answer is never an override", () => {
170
+ assertEquals(isScopeOverridden("abc123", null), false);
171
+ assertEquals(isScopeOverridden("abc123", undefined), false);
172
+ });
173
+
174
+ test("isScopeOverridden: a missing/blank HEAD on either side fails closed (no override)", () => {
175
+ assertEquals(isScopeOverridden(null, { headSha: "abc123", answer: "x" }), false, "unreadable current HEAD");
176
+ assertEquals(isScopeOverridden("", { headSha: "abc123", answer: "x" }), false, "blank current HEAD");
177
+ assertEquals(isScopeOverridden("abc123", { headSha: null, answer: "x" }), false, "unrecorded escalation HEAD");
178
+ assertEquals(isScopeOverridden("abc123", { headSha: " ", answer: "x" }), false, "blank escalation HEAD");
179
+ });
180
+
181
+ test("isScopeOverridden: the answer text is not parsed for intent — presence at the HEAD is the signal", () => {
182
+ // On an unchanged HEAD, the operator completing the escalation IS the explicit approval: had they
183
+ // wanted a real split, the servicing agent would have pushed a fix, moving the HEAD.
184
+ assert(isScopeOverridden("abc123", { headSha: "abc123", answer: null }), "a null answer at the HEAD still overrides");
185
+ });
package/app/scopeGuard.ts CHANGED
@@ -129,3 +129,37 @@ export function evaluateScopeGuard(input: ScopeGuardInput): ScopeGuardResult {
129
129
  scopeBlockReason: `Scope integrity blocked: ${reasons.join("; ")}.`,
130
130
  };
131
131
  }
132
+
133
+ // A recorded human answer to a scope-integrity escalation, bound to the PR HEAD it was raised
134
+ // against (issue #395). This is the override door the deterministic scope gate lacked: without it,
135
+ // the gate re-derives `scopeBlocked` from the PR body every round and re-escalates the identical
136
+ // question, so a legitimate human override ("this fully delivers the issue — keep the closing
137
+ // keyword") is unresolvable through the escalation the loop itself opens (infinite loop).
138
+ export interface ScopeEscalationAnswer {
139
+ /** The escalation row id, for the audit trail. */
140
+ escalationId?: number;
141
+ /** The PR HEAD sha this scope escalation was raised against (`escalations.head_sha`). */
142
+ headSha: string | null | undefined;
143
+ /** The operator's recorded answer/rationale (`escalations.answer`), surfaced in the audit. */
144
+ answer: string | null | undefined;
145
+ }
146
+
147
+ /** Decide whether a recorded human answer overrides the scope-integrity block for the commit
148
+ * currently under review. The override is honoured ONLY when the human answered a scope-integrity
149
+ * escalation that was raised against the SAME HEAD sha now being checked — binding the override to
150
+ * the reviewed commit so a later push (a different HEAD) re-opens the gate instead of silently
151
+ * carrying the override forward. Pure and total: a missing/blank current HEAD or a missing/blank
152
+ * recorded HEAD never matches, so an unverifiable HEAD fails closed (no override) rather than
153
+ * waving the gate through. The answer TEXT is not parsed for intent: on an unchanged HEAD the human
154
+ * completing the escalation IS the explicit approval (had they wanted a real fix, the servicing
155
+ * agent would have pushed a new commit, moving the HEAD and side-stepping this override). */
156
+ export function isScopeOverridden(
157
+ currentHeadSha: string | null | undefined,
158
+ answered: ScopeEscalationAnswer | null | undefined,
159
+ ): boolean {
160
+ if (!answered) return false;
161
+ const current = typeof currentHeadSha === "string" ? currentHeadSha.trim() : "";
162
+ const recorded = typeof answered.headSha === "string" ? answered.headSha.trim() : "";
163
+ if (current === "" || recorded === "") return false;
164
+ return current === recorded;
165
+ }
@@ -0,0 +1,23 @@
1
+ -- Bind a scope-integrity escalation to the reviewed commit so a human answer can override it
2
+ -- (issue #395). The review-convergence scope-integrity gate (`workers/converge-gate`) raises a
3
+ -- human question ("this partial delivery closes a broader-scoped parent") but then re-derives the
4
+ -- block from scratch off the PR body every round, ignoring the recorded `answer` — so answering
5
+ -- the escalation re-enters the loop, the gate re-blocks identically, and the operator is trapped in
6
+ -- an infinite escalation with no human-override door. The only escape was mangling the PR body into
7
+ -- a non-closing ref, i.e. changing the PR to what the machine wants rather than answering it.
8
+ --
9
+ -- The fix gives the gate a real override door: an escalation now records the PR HEAD sha it was
10
+ -- raised against (`head_sha`) and whether it was a scope-integrity block (`scope_block`). When the
11
+ -- gate would re-block on scope, it consults the answered escalation for THIS PR at the SAME HEAD:
12
+ -- a human answer bound to the reviewed commit is honoured as an explicit override (audited), and
13
+ -- the gate is satisfied. Binding to the HEAD sha is deliberate — a later push (a new HEAD)
14
+ -- legitimately re-opens the gate rather than silently carrying the override forward, and if the
15
+ -- human instead asked for a real split the agent pushes a fix (new HEAD) so the stale override
16
+ -- never applies. This categorically kills the infinite-escalation loop on an unchanged HEAD.
17
+ --
18
+ -- Both columns are nullable/defaulted (expand phase, additive). Only the scope-integrity arm
19
+ -- (`persist-escalation-blockedcomments`) populates them; every other escalation arm leaves them
20
+ -- NULL/0 and is unaffected. Numbered after the current highest prefix (055); the runner wraps each
21
+ -- file in its own transaction, so this file must NOT contain BEGIN/COMMIT.
22
+ ALTER TABLE escalations ADD COLUMN head_sha TEXT;
23
+ ALTER TABLE escalations ADD COLUMN scope_block INTEGER NOT NULL DEFAULT 0;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nanobpm/nano-workforce",
3
- "version": "0.114.0",
3
+ "version": "0.114.1",
4
4
  "description": "Nano Workforce — an Agent Graph Orchestration application for Agentic SDLC: durable BPMN processes that coordinate a graph of AI agents across the software delivery lifecycle.",
5
5
  "type": "module",
6
6
  "main": "main.ts",
@@ -50,6 +50,8 @@
50
50
  <nano:shape id="PrConvergeGateOut" name="Converge gate — result">
51
51
  <nano:extend name="convergeBlocked" type="boolean" />
52
52
  <nano:extend name="convergeBlockReason" type="string" optional="true" />
53
+ <nano:extend name="headSha" type="string" optional="true" />
54
+ <nano:extend name="scopeBlocked" type="boolean" optional="true" />
53
55
  </nano:shape>
54
56
  <nano:shape id="EscalationIn" name="Record escalation — input">
55
57
  <nano:extend name="prKey" type="string" />
@@ -62,6 +64,8 @@
62
64
  <nano:extend name="prNumber" type="integer" optional="true" />
63
65
  <nano:extend name="prUrl" type="string" optional="true" />
64
66
  <nano:extend name="abandonUrl" type="string" optional="true" />
67
+ <nano:extend name="headSha" type="string" optional="true" />
68
+ <nano:extend name="scopeBlock" type="boolean" optional="true" />
65
69
  </nano:shape>
66
70
  <nano:shape id="EscalationOut" name="Record escalation — result">
67
71
  <nano:extend name="escalationId" type="integer" optional="true" />
@@ -299,6 +303,8 @@
299
303
  <zeebe:input source="=&#34;blocked&#34;" target="status" />
300
304
  <zeebe:input source="=false" target="recordRound" />
301
305
  <zeebe:input source="=convergeBlockReason" target="question" />
306
+ <zeebe:input source="=headSha" target="headSha" />
307
+ <zeebe:input source="=scopeBlocked" target="scopeBlock" />
302
308
  </zeebe:ioMapping>
303
309
  </bpmn:extensionElements>
304
310
  <bpmn:incoming>f_convergeBlocked</bpmn:incoming>
@@ -0,0 +1,116 @@
1
+ // pr.converge-gate — the human-override door for the scope-integrity block (issue #395).
2
+ //
3
+ // The scope-integrity gate re-derives `scopeBlocked` from the PR body every converged round. Before
4
+ // this fix, answering its escalation re-entered the loop, the gate re-blocked identically, and the
5
+ // operator was trapped in an infinite escalation (a fresh escalationId each cycle) — the only escape
6
+ // was mangling the PR body into a non-closing ref. These tests pin the override door: an escalation
7
+ // answer bound to the SAME reviewed HEAD satisfies the gate (audited), a different HEAD (a new push)
8
+ // re-opens it, and an unreadable HEAD keeps the block (fail closed).
9
+ import { test } from "node:test";
10
+ import { assert, assertEquals } from "#test-assert";
11
+ import { noopLog } from "../../test/log.ts";
12
+ import { makeHandler } from "./worker.ts";
13
+
14
+ // A PR body that trips the scope-integrity guard: it defers scope (`## Scope`) yet closes a
15
+ // broader-scoped parent (`Closes #631`) and links no filed follow-up.
16
+ const SCOPE_BLOCKING_BODY =
17
+ "Delivers the first half.\n\n## Scope\nThe embedded tools remain the deferred refinement.\n\nCloses #631";
18
+
19
+ // biome-ignore lint/suspicious/noExplicitAny: tiny in-memory app double, mirrors persist-escalation.test
20
+ function fakeApp(escalations: Record<string, unknown>[]): any {
21
+ const stores: Record<string, Record<string, unknown>[]> = { escalations };
22
+ return {
23
+ stores,
24
+ data: {
25
+ table(name: string, key: string) {
26
+ const store = (stores[name] ??= []);
27
+ return {
28
+ // biome-ignore lint/suspicious/noExplicitAny: test double
29
+ find: (q: any) => Promise.resolve(store.filter((r) => Object.entries(q).every(([f, v]) => r[f] === v))),
30
+ };
31
+ },
32
+ },
33
+ log: noopLog(),
34
+ };
35
+ }
36
+
37
+ function deps(overrides: {
38
+ headSha?: string | null;
39
+ prBody?: string;
40
+ headThrows?: boolean;
41
+ }) {
42
+ const headSha = "headSha" in overrides ? (overrides.headSha ?? null) : "HEAD1";
43
+ return {
44
+ readThreads: () => Promise.resolve([]),
45
+ readReviewBody: () => Promise.resolve(""),
46
+ readPrBody: () => Promise.resolve(overrides.prBody ?? SCOPE_BLOCKING_BODY),
47
+ readHeadSha: () => (overrides.headThrows ? Promise.reject(new Error("gh down")) : Promise.resolve(headSha)),
48
+ };
49
+ }
50
+
51
+ const job = { variables: { prKey: "o/r#5", repo: "o/r", prNumber: 5 } } as never;
52
+
53
+ test("scope blocks with no answered escalation → blocked, and surfaces the reviewed HEAD to bind the escalation", async () => {
54
+ const app = fakeApp([]);
55
+ const out = (await makeHandler(deps({ headSha: "HEAD1" }))(job, app)) as Record<string, unknown>;
56
+ assertEquals(out.convergeBlocked, true);
57
+ assertEquals(out.scopeBlocked, true);
58
+ assertEquals(out.headSha, "HEAD1", "the reviewed HEAD is returned so persist-escalation can bind it");
59
+ });
60
+
61
+ test("scope blocks but a human answered the escalation for the SAME HEAD → override honoured (loop broken)", async () => {
62
+ const app = fakeApp([
63
+ { id: 7, pr_key: "o/r#5", status: "answered", scope_block: 1, head_sha: "HEAD1", answer: "Full delivery — keep Closes." },
64
+ ]);
65
+ const out = (await makeHandler(deps({ headSha: "HEAD1" }))(job, app)) as Record<string, unknown>;
66
+ assertEquals(out.convergeBlocked, false, "the same-HEAD human answer satisfies the scope gate");
67
+ assertEquals(out.convergeBlockReason, "");
68
+ // A cleared scope block routes to finalize, so the block-only binding fields are not emitted.
69
+ assertEquals(out.scopeBlocked, undefined);
70
+ });
71
+
72
+ test("scope blocks and the answer was for a DIFFERENT HEAD (a new push) → still blocked", async () => {
73
+ const app = fakeApp([
74
+ { id: 7, pr_key: "o/r#5", status: "answered", scope_block: 1, head_sha: "OLDHEAD", answer: "Full delivery." },
75
+ ]);
76
+ const out = (await makeHandler(deps({ headSha: "HEAD1" }))(job, app)) as Record<string, unknown>;
77
+ assertEquals(out.convergeBlocked, true, "a stale override never carries across a new push");
78
+ assertEquals(out.scopeBlocked, true);
79
+ });
80
+
81
+ test("scope blocks and an answered NON-scope escalation sits at the same HEAD → not an override", async () => {
82
+ const app = fakeApp([
83
+ { id: 7, pr_key: "o/r#5", status: "answered", scope_block: 0, head_sha: "HEAD1", answer: "unrelated" },
84
+ ]);
85
+ const out = (await makeHandler(deps({ headSha: "HEAD1" }))(job, app)) as Record<string, unknown>;
86
+ assertEquals(out.convergeBlocked, true, "only a scope-integrity escalation opens the scope override door");
87
+ });
88
+
89
+ test("scope blocks but the reviewed HEAD is unreadable → keep the block (fail closed)", async () => {
90
+ const app = fakeApp([
91
+ { id: 7, pr_key: "o/r#5", status: "answered", scope_block: 1, head_sha: "HEAD1", answer: "override" },
92
+ ]);
93
+ const nullHead = (await makeHandler(deps({ headSha: null }))(job, app)) as Record<string, unknown>;
94
+ assertEquals(nullHead.convergeBlocked, true, "cannot verify an override against an unknown HEAD");
95
+ const throwHead = (await makeHandler(deps({ headThrows: true }))(job, app)) as Record<string, unknown>;
96
+ assertEquals(throwHead.convergeBlocked, true, "a HEAD read error keeps the block");
97
+ });
98
+
99
+ test("scope passes → not blocked, and no override lookup is needed", async () => {
100
+ const app = fakeApp([]);
101
+ const out = (await makeHandler(deps({ prBody: "Implements the whole thing.\n\nCloses #631" }))(job, app)) as Record<
102
+ string,
103
+ unknown
104
+ >;
105
+ assertEquals(out.convergeBlocked, false);
106
+ assertEquals(out.scopeBlocked, undefined);
107
+ });
108
+
109
+ test("newest answered scope escalation wins when a re-escalation was answered again at the same HEAD", async () => {
110
+ const app = fakeApp([
111
+ { id: 7, pr_key: "o/r#5", status: "answered", scope_block: 1, head_sha: "HEAD1", answer: "first" },
112
+ { id: 9, pr_key: "o/r#5", status: "answered", scope_block: 1, head_sha: "HEAD1", answer: "latest" },
113
+ ]);
114
+ const out = (await makeHandler(deps({ headSha: "HEAD1" }))(job, app)) as Record<string, unknown>;
115
+ assertEquals(out.convergeBlocked, false, "a re-answered override at the unchanged HEAD is honoured");
116
+ });
@@ -19,6 +19,15 @@
19
19
  // This is the enforcement backstop for the Magikcraft/nano-bpm#631 → PR #863 (`Closes #631`, `##
20
20
  // Scope` deferral, no follow-up → re-filed by hand as #872) failure class. See app/scopeGuard.ts.
21
21
  //
22
+ // The scope-integrity block also carries a HUMAN-OVERRIDE door (#395): before it re-blocks, it
23
+ // reads the commit now under review and consults the `escalations` answer bound to that SAME HEAD.
24
+ // An operator who answered the scope question for this exact commit ("this fully delivers the issue
25
+ // — keep the closing keyword") has explicitly overridden it, so the gate honours that answer
26
+ // (audited) instead of re-deriving `scopeBlocked` from the PR body and re-escalating the identical
27
+ // question forever. Binding to the HEAD sha keeps the override from carrying across a new push, and
28
+ // (via `PrConvergeGateOut.headSha`/`scopeBlocked`) lets `persist-escalation-blockedcomments` stamp
29
+ // the escalation with the reviewed commit so the door can open on the next round.
30
+ //
22
31
  // It FAILS CLOSED: if the live GitHub state cannot be read, it blocks (escalates) rather than
23
32
  // letting an unverifiable "converged" through — the opposite of the no-progress guard, because a
24
33
  // merge-gating check must escalate-on-uncertainty so #770 cannot recur.
@@ -26,13 +35,14 @@ import type { AppJobHandler } from "@nanobpm/urban";
26
35
  import { type ConvergeGateResult, evaluateConvergeGate } from "../../app/convergeGate.ts";
27
36
  import {
28
37
  fetchLatestCopilotReviewBody,
38
+ fetchPrHead,
29
39
  fetchPrMeta,
30
40
  fetchReviewThreads,
31
41
  parseAckedAdvisories,
32
42
  parseSuppressedAdvisories,
33
43
  type ReviewThread,
34
44
  } from "../../app/github.ts";
35
- import { evaluateScopeGuard } from "../../app/scopeGuard.ts";
45
+ import { evaluateScopeGuard, isScopeOverridden, type ScopeEscalationAnswer } from "../../app/scopeGuard.ts";
36
46
  import { parsePr } from "../../app/service.ts";
37
47
  import type { WorkerInputs, WorkerOutputs } from "../../nano-generated/worker-io.d.ts";
38
48
 
@@ -50,6 +60,9 @@ export type ReviewBodyReader = (repo: string, prNumber: number) => Promise<strin
50
60
  // Reads the PR's own description body. `null` = no usable transport (unverifiable → fail closed);
51
61
  // `""` = transport usable but the PR has an empty description (verified: nothing to scope-check).
52
62
  export type PrBodyReader = (repo: string, prNumber: number) => Promise<string | null>;
63
+ // Reads the PR's current HEAD sha (the commit under review). `null` = unreadable/no transport — the
64
+ // scope override cannot be verified or bound to a commit, so the gate keeps blocking (fail closed).
65
+ export type HeadShaReader = (repo: string, prNumber: number) => Promise<string | null>;
53
66
 
54
67
  const defaultReadThreads: ThreadsReader = (repo, prNumber) =>
55
68
  fetchReviewThreads(repo, prNumber, process.env.GITHUB_TOKEN ?? "");
@@ -59,6 +72,10 @@ const defaultReadPrBody: PrBodyReader = async (repo, prNumber) => {
59
72
  const meta = await fetchPrMeta(repo, prNumber, process.env.GITHUB_TOKEN ?? "");
60
73
  return meta ? meta.body : null;
61
74
  };
75
+ const defaultReadHeadSha: HeadShaReader = async (repo, prNumber) => {
76
+ const head = await fetchPrHead(repo, prNumber, process.env.GITHUB_TOKEN ?? "");
77
+ return head ? head.headSha : null;
78
+ };
62
79
 
63
80
  const BLOCK_UNVERIFIABLE =
64
81
  "Convergence blocked: could not verify the PR's review comments against GitHub. A human must confirm every Copilot review thread is resolved and every suppressed advisory acknowledged before this PR converges (reply to resume the loop).";
@@ -66,14 +83,56 @@ const BLOCK_UNVERIFIABLE =
66
83
  const BLOCK_UNVERIFIABLE_BODY =
67
84
  "Convergence blocked: could not read the PR description from GitHub to verify scope integrity. A human must confirm this PR does not close a broader-scoped parent with an untracked deferred remainder before it converges (reply to resume the loop).";
68
85
 
86
+ // An `escalations` row as this worker reads it back when looking for a recorded human override.
87
+ interface EscalationRow extends Record<string, unknown> {
88
+ id: number;
89
+ head_sha: string | null;
90
+ answer: string | null;
91
+ scope_block: number | boolean | null;
92
+ }
93
+
94
+ // Find the newest ANSWERED scope-integrity escalation for this PR whose recorded HEAD matches the
95
+ // commit now under review (issue #395). This is the human-override door: `persist-escalation` binds
96
+ // a scope block to the HEAD it was raised against, `answer-escalation` marks the row `answered`, and
97
+ // here we honour that answer for the SAME HEAD so the gate stops re-deriving `scopeBlocked` from the
98
+ // PR body and re-escalating the identical question forever. Newest-first so a re-escalated-then-
99
+ // answered duplicate resolves to the operator's latest reply. Returns `null` on any read failure —
100
+ // the caller then keeps the block (fail closed), never fabricates an override.
101
+ async function findScopeOverride(
102
+ app: Parameters<AppJobHandler<In, Out>>[1],
103
+ prKey: string,
104
+ headSha: string,
105
+ ): Promise<ScopeEscalationAnswer | null> {
106
+ try {
107
+ // `scope_block` is a first-class column (persist-escalation writes it as 0/1), so filter on it
108
+ // in the query rather than reading every answered escalation and filtering in memory — a PR with
109
+ // many answered non-scope escalations no longer loads them all just to discard them.
110
+ const rows = await app.data.table<EscalationRow>("escalations", "id").find({
111
+ pr_key: prKey,
112
+ status: "answered",
113
+ scope_block: 1,
114
+ });
115
+ const scoped = rows
116
+ .map((r) => ({ escalationId: Number(r.id), headSha: r.head_sha ?? null, answer: r.answer ?? null }))
117
+ .sort((a, b) => (b.escalationId ?? 0) - (a.escalationId ?? 0));
118
+ for (const candidate of scoped) {
119
+ if (isScopeOverridden(headSha, candidate)) return candidate;
120
+ }
121
+ return null;
122
+ } catch {
123
+ return null;
124
+ }
125
+ }
126
+
69
127
  /** Build the handler with injectable GitHub readers. The default export binds the real readers;
70
128
  * tests inject stubs. Fails CLOSED — any unreadable/errored state blocks convergence. */
71
129
  export function makeHandler(deps: {
72
130
  readThreads: ThreadsReader;
73
131
  readReviewBody: ReviewBodyReader;
74
132
  readPrBody: PrBodyReader;
133
+ readHeadSha: HeadShaReader;
75
134
  }): AppJobHandler<In, Out> {
76
- return async (job) => {
135
+ return async (job, app) => {
77
136
  const { prKey, repo, prNumber } = job.variables;
78
137
  // `parsePr` is total on any input (fails closed to `null` on a missing/non-string prKey), so
79
138
  // pass it straight through — a malformed prKey degrades to the fail-closed target check below.
@@ -83,6 +142,9 @@ export function makeHandler(deps: {
83
142
  if (!ghRepo || typeof ghNumber !== "number") {
84
143
  return { convergeBlocked: true, convergeBlockReason: BLOCK_UNVERIFIABLE };
85
144
  }
145
+ // The canonical escalations key. Prefer the carried prKey; fall back to the parsed identity so
146
+ // the override lookup still keys off `owner/repo#N` when only repo/prNumber survived.
147
+ const escPrKey = typeof prKey === "string" && prKey !== "" ? prKey : `${ghRepo}#${ghNumber}`;
86
148
 
87
149
  let result: ConvergeGateResult;
88
150
  let scopeReason: string;
@@ -127,13 +189,58 @@ export function makeHandler(deps: {
127
189
  return { convergeBlocked: true, convergeBlockReason: BLOCK_UNVERIFIABLE_BODY };
128
190
  }
129
191
 
192
+ // The human-override door for the scope-integrity block (issue #395). When the deterministic
193
+ // scope guard would re-block, read the commit now under review and consult the recorded
194
+ // escalation answer bound to that SAME HEAD: an operator who answered the scope question for
195
+ // this exact commit has explicitly overridden it ("this fully delivers the issue — keep the
196
+ // closing keyword"), so honour it (audited) instead of re-deriving the block from the body and
197
+ // re-escalating forever. Binding to the HEAD sha keeps the override from carrying across a new
198
+ // push (a different HEAD legitimately re-opens the gate); and if the human instead asked for a
199
+ // real split, the servicing agent pushes a fix — moving the HEAD so this stale override never
200
+ // fires. This is what turns the infinite escalation loop into a resolvable one.
201
+ let headSha: string | null = null;
202
+ let scopeBlocked = scopeReason !== "";
203
+ if (scopeBlocked) {
204
+ try {
205
+ headSha = await deps.readHeadSha(ghRepo, ghNumber);
206
+ } catch {
207
+ headSha = null;
208
+ }
209
+ if (headSha) {
210
+ const override = await findScopeOverride(app, escPrKey, headSha);
211
+ if (override) {
212
+ app.log.info("converge-gate: scope-integrity block overridden by human answer", {
213
+ prKey: escPrKey,
214
+ headSha,
215
+ escalationId: override.escalationId ?? null,
216
+ // The human answer is free-form operator input — never log it verbatim (it can carry
217
+ // sensitive content into application logs). Record only stable identifiers plus a
218
+ // minimal presence/length signal for debugging.
219
+ hasAnswer: override.answer != null && override.answer !== "",
220
+ answerLength: override.answer?.length ?? 0,
221
+ });
222
+ scopeReason = "";
223
+ scopeBlocked = false;
224
+ }
225
+ }
226
+ }
227
+
130
228
  // Both guards gate the same handoff to the merge loop: block if EITHER the review-comment gate
131
229
  // or the scope-integrity gate blocks, joining their reasons so the human sees every cause.
132
230
  const reason = [result.convergeBlockReason, scopeReason].filter((r) => r !== "").join(" ");
133
- return {
134
- convergeBlocked: result.convergeBlocked || scopeReason !== "",
231
+ const out: Out = {
232
+ convergeBlocked: result.convergeBlocked || scopeBlocked,
135
233
  convergeBlockReason: reason,
136
234
  };
235
+ // Surface the reviewed HEAD and the scope-block flag ONLY when scope actually blocks — the
236
+ // `persist-escalation-blockedcomments` arm (which runs only on a blocked gate) binds the
237
+ // escalation to this commit with them, opening the override door on the next round. A clean
238
+ // converge keeps its original `{ convergeBlocked, convergeBlockReason }` shape.
239
+ if (scopeBlocked) {
240
+ out.scopeBlocked = true;
241
+ out.headSha = headSha ?? undefined;
242
+ }
243
+ return out;
137
244
  };
138
245
  }
139
246
 
@@ -141,5 +248,6 @@ const handler = makeHandler({
141
248
  readThreads: defaultReadThreads,
142
249
  readReviewBody: defaultReadReviewBody,
143
250
  readPrBody: defaultReadPrBody,
251
+ readHeadSha: defaultReadHeadSha,
144
252
  });
145
253
  export default handler;
@@ -50,7 +50,7 @@ function workerOf(vars: Record<string, unknown>): string | undefined {
50
50
  }
51
51
 
52
52
  const handler: AppJobHandler<In> = async (job, app) => {
53
- const { prKey, round, summary, repo, prNumber, prUrl, abandonUrl } = job.variables;
53
+ const { prKey, round, summary, repo, prNumber, prUrl, abandonUrl, headSha, scopeBlock } = job.variables;
54
54
  // `status` drives the escalation kind (control flow); a blank/absent status is an
55
55
  // unclassified escalation -> a question needing input. `question` is returned as a
56
56
  // process variable below so the downstream `wait-answer` userTask + `pr-escalation.form`
@@ -116,6 +116,13 @@ const handler: AppJobHandler<In> = async (job, app) => {
116
116
  worker,
117
117
  status: "open",
118
118
  asked_at: now,
119
+ // Bind a scope-integrity escalation to the reviewed commit (issue #395) so the converge-gate
120
+ // can honour a human answer as an override for THIS HEAD instead of re-deriving the block from
121
+ // the PR body and re-escalating forever. Only the scope-integrity arm passes these; every other
122
+ // arm leaves them absent (→ head_sha NULL, scope_block DEFAULT 0), so the override door opens
123
+ // exclusively for the block the human can actually answer.
124
+ head_sha: headSha,
125
+ scope_block: scopeBlock === true ? 1 : 0,
119
126
  });
120
127
  await app.data.table("pull_requests", "pr_key").update(prKey, {
121
128
  status: "escalated",