@firstpick/pi-package-webui 0.6.8 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,38 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
7
+ const [app, css, pkg, server, payloadParser] = await Promise.all([
8
+ readFile(join(root, "public", "app.js"), "utf8"),
9
+ readFile(join(root, "public", "styles.css"), "utf8"),
10
+ readFile(join(root, "package.json"), "utf8"),
11
+ readFile(join(root, "bin", "pi-webui.mjs"), "utf8"),
12
+ readFile(join(root, "public", "aur-review-payload.mjs"), "utf8"),
13
+ ]);
14
+
15
+ assert.match(app, /const AUR_REVIEW_RPC_WIDGET_KEY = "aur-review:rpc"[\s\S]*AUR_REVIEW_RPC_PAYLOAD_PREFIX = "AUR_REVIEW_RPC_PAYLOAD "[\s\S]*AUR_REVIEW_RPC_PAYLOAD_TYPE = "firstpick\.pi-extension-aur-review\.review"[\s\S]*AUR_REVIEW_RPC_PAYLOAD_VERSION = 3/, "WebUI should identify the versioned AUR review payload");
16
+ assert.match(app, /parseValidatedAurReviewPayload[\s\S]*function parseAurReviewPayload\(lines\)[\s\S]*prefix: AUR_REVIEW_RPC_PAYLOAD_PREFIX/, "AUR review rendering should delegate parsing to the fail-closed payload module");
17
+ assert.match(payloadParser, /validTimestamp[\s\S]*Date\.parse\(payload\.createdAt\) > Date\.parse\(payload\.updatedAt\)/, "payload parsing should enforce ordered canonical timestamps");
18
+ assert.match(payloadParser, /stats\[key\] <= total[\s\S]*stats\.files !== total/, "payload parsing should enforce stats totals and bounds");
19
+ assert.match(payloadParser, /decision\.reviewedFingerprint !== payload\.fingerprint/, "payload parsing should bind terminal decisions to the snapshot fingerprint");
20
+ assert.match(payloadParser, /stagedPayload \? decision\.reviewedStagedContentHash !== payload\.stagedContentHash/, "payload parsing should bind staged terminal decisions to the staged-content hash");
21
+ assert.match(payloadParser, /payload\.changedFiles\.length >= payload\.changedFileTotal/, "payload parsing should reject equality at the truncated-file boundary");
22
+ assert.match(app, /function renderAurReviewWidget\(\)[\s\S]*Review changes[\s\S]*Refresh[\s\S]*Approve[\s\S]*Decline[\s\S]*Close[\s\S]*openAurReviewReportInViewer\(reportPath, payload\.repoRoot\)/, "renderer should open reports against the payload's repo root rather than the tab cwd");
23
+ assert.match(app, /async function openAurReviewReportInViewer\(path = "", repoRoot = ""\)[\s\S]*\/api\/aur-review\/report-content[\s\S]*readOnly: true/s, "report viewing must use the narrow read-only canonical-root endpoint");
24
+ assert.match(app, /viewer\.readOnly === true \|\| !viewer\.dirty[\s\S]*viewer\.readOnly === true \|\| !viewerPath/s, "repo-root report views must not enable generic save or default-editor actions");
25
+ assert.match(app, /function aurReviewActionButton\(label, action, className = ""\)[\s\S]*action === "review"[\s\S]*openGitChangesDialog\(\)[\s\S]*`\/aur-review \$\{action\}`/, "Review changes should reuse the current Git diff dialog and other controls should call canonical extension commands");
26
+ assert.match(app, /aurReviewActionButton\("Approve", "approve", "primary"\)/, "Approve should delegate to the extension slash command, which owns native confirmation");
27
+ assert.match(app, /id: "aurReview"[\s\S]*packageName: "@firstpick\/pi-extension-aur-review"[\s\S]*capabilityLabel: "\/aur-review or aur-review:rpc widget event"/, "optional feature discovery should identify the companion by command or payload");
28
+ assert.match(app, /optionalFeatureAvailability\.aurReview = hasAvailableCommand\("aur-review"\)[\s\S]*widgets\.has\(AUR_REVIEW_RPC_WIDGET_KEY\)/, "feature availability should detect commands and replayed widget state");
29
+ assert.match(app, /if \(key === AUR_REVIEW_RPC_WIDGET_KEY\) return "aurReview"[\s\S]*key === AUR_REVIEW_RPC_WIDGET_KEY/, "generic widget fallback should be preserved while the AUR review payload gets a specialized renderer");
30
+ assert.match(css, /\.aur-review-widget \{[\s\S]*\.aur-review-actions[\s\S]*\.aur-review-file-list[\s\S]*@media \(max-width: 720px\)[\s\S]*\.aur-review-action,[\s\S]*\.aur-review-report/, "AUR review card should be styled responsively for desktop and mobile");
31
+ assert.equal(JSON.parse(pkg).optionalDependencies?.["@firstpick/pi-extension-aur-review"], undefined, "WebUI must not reference the unpublished review extension from clean npm installs");
32
+ assert.equal(JSON.parse(pkg).pi?.extensions?.some((entry) => String(entry).includes("pi-extension-aur-review")), false, "WebUI must not bundle an unpublished nested review extension path");
33
+ assert.match(server, /\["aurReview", "@firstpick\/pi-extension-aur-review"\]/, "optional-feature installer should retain the future/local review companion mapping");
34
+ assert.match(server, /"aur-review-payload\.mjs", "guided-git-command-state\.mjs", "guided-git-review-state\.mjs"/, "server must serve every browser module used by the review gate");
35
+ assert.match(server, /STAGED_CONTENT_HASH_DOMAIN = "firstpick\/aur-review\/staged-content\/v1\\0"[\s\S]*git diff --cached[\s\S]*\/api\/git-workflow\/staged-content/, "server must expose the bounded read-only staged-content hash helper");
36
+ assert.match(server, /async function getAurReviewReportContentData\(tab, \{ path: requestedPath = "", repoRoot = "" \} = \{\}\)[\s\S]*repoRoot !== root[\s\S]*lstat\(targetPath\)[\s\S]*isSymbolicLink\(\)[\s\S]*readBoundedAurReviewReport[\s\S]*\/api\/aur-review\/report-content/s, "server must bind report reads to the canonical Git root and reject symlinked paths through a dedicated read-only route");
37
+ assert.match(server, /entry\.name\.startsWith\("pi-"\)[\s\S]*packageNameForResourcePath\(path\.join\(candidate, "package\.json"\)\)/, "workspace optional-package discovery must recognize the pi-extension-aur-review sibling by manifest name");
38
+ console.log("aur review widget static tests passed");
@@ -12,7 +12,12 @@ const serverScript = join(root, "bin", "pi-webui.mjs");
12
12
  const compactingPi = join(root, "tests", "fixtures", "compacting-pi.mjs");
13
13
  const port = 30000 + Math.floor(Math.random() * 20000);
14
14
  const COMPACTION_TRIGGER = "__pi_webui_test_start_compaction__";
15
+ const ABORTED_COMPACTION_TRIGGER = "__pi_webui_test_start_aborted_compaction__";
15
16
  const RESUME_PROMPT = "resume automatically after compaction";
17
+ const STEER_PROMPT = "steer automatically after compaction";
18
+ const FOLLOW_UP_PROMPT = "follow up automatically after compaction";
19
+ const QUEUED_SLASH_PROMPT = "/queued-extension-command";
20
+ const ABORTED_RESUME_PROMPT = "resume automatically after aborted compaction";
16
21
 
17
22
  async function request(pathname, { method = "GET", body, timeoutMs = 5_000 } = {}) {
18
23
  const response = await fetch(`http://127.0.0.1:${port}${pathname}`, {
@@ -87,22 +92,69 @@ try {
87
92
  assert.equal(queuedPrompt.body?.data?.queuedFor, "compaction");
88
93
  assert.equal(queuedPrompt.body?.data?.queueLength, 1);
89
94
 
95
+ const queuedSteer = await request("/api/steer", {
96
+ method: "POST",
97
+ body: { tab: tabId, message: STEER_PROMPT },
98
+ });
99
+ assert.equal(queuedSteer.status, 202, "steer sent during compaction should be accepted into the Web UI resume queue");
100
+ assert.equal(queuedSteer.body?.data?.queueLength, 2);
101
+
102
+ const queuedFollowUp = await request("/api/follow-up", {
103
+ method: "POST",
104
+ body: { tab: tabId, message: FOLLOW_UP_PROMPT },
105
+ });
106
+ assert.equal(queuedFollowUp.status, 202, "follow-up sent during compaction should be accepted into the Web UI resume queue");
107
+ assert.equal(queuedFollowUp.body?.data?.queueLength, 3);
108
+
109
+ const queuedSlashPrompt = await request("/api/prompt", {
110
+ method: "POST",
111
+ body: { tab: tabId, message: QUEUED_SLASH_PROMPT, streamingBehavior: "followUp" },
112
+ });
113
+ assert.equal(queuedSlashPrompt.status, 202, "slash prompt sent during compaction should remain a prompt in the resume queue");
114
+ assert.equal(queuedSlashPrompt.body?.data?.queueLength, 4);
115
+
90
116
  const messagesBeforeEnd = await request(`/api/messages?tab=${encodeURIComponent(tabId)}`);
91
117
  assert.equal(messagesBeforeEnd.status, 200);
92
- assert.equal((messagesBeforeEnd.body?.data?.messages || []).some((message) => String(message.content || "").includes(RESUME_PROMPT)), false, "queued prompt should not reach Pi before compaction_end");
118
+ const queuedMessages = [RESUME_PROMPT, STEER_PROMPT, FOLLOW_UP_PROMPT, QUEUED_SLASH_PROMPT];
119
+ for (const message of queuedMessages) {
120
+ assert.equal((messagesBeforeEnd.body?.data?.messages || []).some((entry) => String(entry.content || "").includes(message)), false, "queued messages should not reach Pi before compaction_end");
121
+ }
93
122
 
94
123
  await waitFor("compaction to finish", async () => {
95
124
  const state = await request(`/api/state?tab=${encodeURIComponent(tabId)}`);
96
125
  return state.body?.data?.isCompacting === false ? state : false;
97
126
  }, { attempts: 80, intervalMs: 100 });
98
127
 
99
- const resumedMessages = await waitFor("queued prompt to resume after compaction", async () => {
128
+ const resumedMessages = await waitFor("queued prompts to resume after compaction", async () => {
100
129
  const messages = await request(`/api/messages?tab=${encodeURIComponent(tabId)}`);
101
130
  const entries = messages.body?.data?.messages || [];
102
- return entries.some((message) => String(message.content || "").includes(`prompt:${RESUME_PROMPT}`)) ? messages : false;
131
+ const expected = [`prompt:${RESUME_PROMPT}`, `steer:${STEER_PROMPT}`, `follow_up:${FOLLOW_UP_PROMPT}`, `prompt:${QUEUED_SLASH_PROMPT}`];
132
+ return expected.every((content, index) => String(entries[index]?.content || "") === content) ? messages : false;
103
133
  }, { attempts: 80, intervalMs: 100 });
104
134
  assert.equal(resumedMessages.status, 200);
105
135
 
136
+ const startAbortedCompaction = await request("/api/prompt", {
137
+ method: "POST",
138
+ body: { tab: tabId, message: ABORTED_COMPACTION_TRIGGER },
139
+ });
140
+ assert.equal(startAbortedCompaction.status, 200);
141
+ await waitFor("aborted compaction_start state", async () => {
142
+ const state = await request(`/api/state?tab=${encodeURIComponent(tabId)}`);
143
+ return state.body?.data?.isCompacting === true ? state : false;
144
+ });
145
+
146
+ const queuedDuringAbortedCompaction = await request("/api/prompt", {
147
+ method: "POST",
148
+ body: { tab: tabId, message: ABORTED_RESUME_PROMPT, streamingBehavior: "steer" },
149
+ });
150
+ assert.equal(queuedDuringAbortedCompaction.status, 202);
151
+
152
+ await waitFor("queued prompt to resume after aborted compaction", async () => {
153
+ const messages = await request(`/api/messages?tab=${encodeURIComponent(tabId)}`);
154
+ const entries = messages.body?.data?.messages || [];
155
+ return entries.some((message) => String(message.content || "") === `prompt:${ABORTED_RESUME_PROMPT}`) ? messages : false;
156
+ }, { attempts: 80, intervalMs: 100 });
157
+
106
158
  await request("/api/shutdown", { method: "POST" }).catch(() => undefined);
107
159
  for (let attempt = 0; attempt < 50 && child.exitCode === null; attempt += 1) await delay(100);
108
160
  assert.notEqual(child.exitCode, null, "server should exit after /api/shutdown");
@@ -12,10 +12,10 @@ const [server, app] = await Promise.all([
12
12
  assert.match(server, /function maybeQueueCommandDuringCompaction\(tab, command\)[\s\S]*tab\?\.lastState\?\.isCompacting[\s\S]*enqueueCommandUntilCompactionEnds/, "server should queue prompt-like commands while the tab is compacting");
13
13
  assert.match(server, /url\.pathname === "\/api\/prompt" && req\.method === "POST"[\s\S]*maybeQueueCommandDuringCompaction\(tab, command\)[\s\S]*sendJson\(res, 202/, "POST /api/prompt should return 202 when a prompt is queued for post-compaction resume");
14
14
  assert.match(server, /if \(command\) \{[\s\S]*maybeQueueCommandDuringCompaction\(tab, command\)[\s\S]*sendJson\(res, 202/, "generic prompt-like POST commands should share the compaction queue path");
15
- assert.match(server, /event\?\.type === "compaction_end" && event\.aborted !== true\)[\s\S]*flushCompactionQueue\(tab, event\)/, "non-aborted compaction_end should flush the queued resume prompt");
16
- assert.match(server, /async function flushCompactionQueue\(tab, event = \{\}\)[\s\S]*queuedRetryCommand\(item\)/, "compaction queue flush should resume queued commands into active auto-retry runs");
15
+ assert.match(server, /event\?\.type === "compaction_end"\)[\s\S]*flushCompactionQueue\(tab, event\)/, "every compaction_end should flush queued prompts instead of stranding them after an abort");
16
+ assert.match(server, /async function flushCompactionQueue\(tab, event = \{\}\)[\s\S]*queuedRetryCommand\(item\)/, "compaction queue flush should preserve steering, follow-up, and slash-command delivery when joining an active run");
17
17
  assert.match(server, /async function flushCompactionQueue\(tab, event = \{\}\)[\s\S]*queuedPromptCommand\(item\)/, "compaction queue flush should start a new prompt when no run resumes automatically");
18
- assert.match(server, /async function flushCompactionQueue\(tab, event = \{\}\)[\s\S]*queuedStreamingCommand\(item\)/, "compaction queue flush should send later queued items as steering or follow-up messages");
18
+ assert.match(server, /function queuedRetryCommand\(item\)[\s\S]*queuedStreamingCommand\(item\)/, "post-compaction continuation should send later queued items as steering or follow-up messages");
19
19
  assert.match(server, /function stateWithPendingThinking\(tab, state\)[\s\S]*compactionQueueForTab\(tab\)\.length[\s\S]*pendingMessageCount/, "state responses should include Web UI compaction queue length while prompts wait to resume");
20
20
 
21
21
  assert.match(app, /function isRunActive\(\) \{\n\s+return !!currentState\?\.isStreaming \|\| !!currentState\?\.isCompacting/, "frontend should treat compaction as an active run for composer controls");
@@ -4,9 +4,11 @@
4
4
  import { createInterface } from "node:readline";
5
5
 
6
6
  const COMPACTION_TRIGGER = "__pi_webui_test_start_compaction__";
7
+ const ABORTED_COMPACTION_TRIGGER = "__pi_webui_test_start_aborted_compaction__";
7
8
 
8
9
  let isCompacting = false;
9
10
  let compactionTimer = null;
11
+ let compactionWillAbort = false;
10
12
  const received = [];
11
13
 
12
14
  function respond(payload) {
@@ -37,18 +39,21 @@ function statePayload() {
37
39
  function finishCompaction() {
38
40
  compactionTimer = null;
39
41
  isCompacting = false;
42
+ const aborted = compactionWillAbort;
43
+ compactionWillAbort = false;
40
44
  emit({
41
45
  type: "compaction_end",
42
46
  reason: "test",
43
- result: { summary: "fake compaction summary", tokensBefore: 1000, estimatedTokensAfter: 100 },
44
- aborted: false,
47
+ result: aborted ? null : { summary: "fake compaction summary", tokensBefore: 1000, estimatedTokensAfter: 100 },
48
+ aborted,
45
49
  willRetry: false,
46
50
  });
47
51
  }
48
52
 
49
- function startCompaction() {
53
+ function startCompaction({ aborted = false } = {}) {
50
54
  if (compactionTimer) clearTimeout(compactionTimer);
51
55
  isCompacting = true;
56
+ compactionWillAbort = aborted;
52
57
  emit({ type: "compaction_start", reason: "test" });
53
58
  compactionTimer = setTimeout(finishCompaction, 1500);
54
59
  }
@@ -91,8 +96,8 @@ rl.on("line", (line) => {
91
96
  return;
92
97
  case "prompt": {
93
98
  const message = String(command.message || "");
94
- if (message === COMPACTION_TRIGGER) {
95
- startCompaction();
99
+ if (message === COMPACTION_TRIGGER || message === ABORTED_COMPACTION_TRIGGER) {
100
+ startCompaction({ aborted: message === ABORTED_COMPACTION_TRIGGER });
96
101
  respond({ ...base, data: { compacting: true } });
97
102
  return;
98
103
  }
@@ -89,6 +89,12 @@ function logJsonLine(entry) {
89
89
  }
90
90
  }
91
91
 
92
+ logJsonLine({
93
+ direction: "startup",
94
+ recoveryUrl: String(process.env.PI_WEBUI_RECOVERY_URL || ""),
95
+ recoveryTokenConfigured: Boolean(process.env.PI_WEBUI_RECOVERY_TOKEN),
96
+ });
97
+
92
98
  function respond(payload) {
93
99
  process.stdout.write(`${JSON.stringify(payload)}\n`);
94
100
  }
@@ -255,6 +261,26 @@ function handleWebuiHelperPrompt(command, base) {
255
261
  currentToolArgs: "README.md",
256
262
  recentTools: [{ tool: "grep", args: "Subagents", endMs: Date.now() - 200 }],
257
263
  recentOutput: ["Inspecting current implementation", "Waiting for the next tool result"],
264
+ transcript: [
265
+ {
266
+ role: "assistant",
267
+ timestamp: "2026-07-19T12:00:00.000Z",
268
+ content: [
269
+ { type: "thinking", thinking: "Checking the fixture transcript." },
270
+ { type: "text", text: "Inspecting current implementation" },
271
+ { type: "toolCall", id: "fixture-read", name: "read", arguments: { path: "README.md", offset: 1 } },
272
+ { type: "text", text: "Waiting for the next tool result" },
273
+ ],
274
+ },
275
+ {
276
+ role: "toolResult",
277
+ timestamp: "2026-07-19T12:00:01.000Z",
278
+ toolCallId: "fixture-read",
279
+ toolName: "read",
280
+ isError: false,
281
+ content: [{ type: "text", text: "# Fixture README" }],
282
+ },
283
+ ],
258
284
  turnCount: 2,
259
285
  toolCount: 3,
260
286
  tokens: 420,
@@ -279,6 +305,31 @@ function handleDocumentArtifactFixturePrompt(command, base) {
279
305
  return true;
280
306
  }
281
307
 
308
+ function handleTransportFixturePrompt(command, base) {
309
+ const message = String(command.message || "").trim();
310
+ if (message === "fixture stderr diagnostic") {
311
+ process.stderr.write("fixture Pi RPC stderr diagnostic\n");
312
+ respond({ ...base, data: { output: "fake stderr diagnostic emitted" } });
313
+ return true;
314
+ }
315
+ if (message === "fixture oversized jsonl") {
316
+ const bytes = Math.max(0, Math.min(64 * 1024 * 1024, Number.parseInt(process.env.FAKE_PI_OVERSIZED_JSONL_BYTES || "0", 10) || 0));
317
+ if (bytes === 0) {
318
+ respond({ ...base, success: false, error: "FAKE_PI_OVERSIZED_JSONL_BYTES must be configured" });
319
+ return true;
320
+ }
321
+ // Intentionally leave this physical JSONL line unterminated long enough
322
+ // for the server to switch into discard mode before sending a valid reply.
323
+ process.stdout.write("x".repeat(bytes));
324
+ setTimeout(() => {
325
+ process.stdout.write("\n");
326
+ respond({ ...base, data: { output: "fake oversized JSONL line discarded" } });
327
+ }, 50);
328
+ return true;
329
+ }
330
+ return false;
331
+ }
332
+
282
333
  function handleSubagentFixturePrompt(command, base) {
283
334
  const message = String(command.message || "").trim();
284
335
  if (message !== "fixture subagents running" && message !== "fixture subagents clear") return false;
@@ -367,7 +418,13 @@ rl.on("line", (line) => {
367
418
  }
368
419
  const { id, type } = command || {};
369
420
  if (!id || !type) return;
370
- logJsonLine({ direction: "command", type, ...(command.message !== undefined ? { message: String(command.message) } : {}) });
421
+ logJsonLine({
422
+ direction: "command",
423
+ type,
424
+ ...(command.message !== undefined ? { message: String(command.message) } : {}),
425
+ ...(command.provider !== undefined ? { provider: String(command.provider) } : {}),
426
+ ...(command.modelId !== undefined ? { modelId: String(command.modelId) } : {}),
427
+ });
371
428
  const base = { type: "response", id, command: type, success: true };
372
429
 
373
430
  switch (type) {
@@ -435,6 +492,7 @@ rl.on("line", (line) => {
435
492
  }
436
493
  case "prompt":
437
494
  if (handleWebuiHelperPrompt(command, base)) return;
495
+ if (handleTransportFixturePrompt(command, base)) return;
438
496
  if (handleSubagentFixturePrompt(command, base)) return;
439
497
  if (handleDocumentArtifactFixturePrompt(command, base)) return;
440
498
  if (handleWorkflowFixturePrompt(command, base)) return;
@@ -449,6 +507,10 @@ rl.on("line", (line) => {
449
507
  thinkingLevel = String(command.level || "off");
450
508
  respond({ ...base, data: { level: thinkingLevel } });
451
509
  return;
510
+ case "set_model":
511
+ if (command.modelId === "missing-model") respond({ ...base, success: false, error: "Model not found: fake/missing-model" });
512
+ else respond({ ...base, data: { provider: command.provider, id: command.modelId } });
513
+ return;
452
514
  case "get_available_models":
453
515
  respond({ ...base, data: { models: [{ provider: "fake", id: "fake-model", name: "Fake Model" }] } });
454
516
  return;
@@ -0,0 +1,183 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import {
6
+ guidedGitReviewCanRequestStagedContent,
7
+ guidedGitReviewHasApprovedBinding,
8
+ guidedGitReviewProcessNavigationAllowed,
9
+ guidedGitReviewProcessSelectionPatch,
10
+ guidedGitReviewTransition,
11
+ guidedGitReviewWidgetRemovalTransition,
12
+ } from "../public/guided-git-review-state.mjs";
13
+ import { guidedGitReviewAvailableForTabCatalog, resolveRpcSlashCommandForTabCatalog } from "../public/guided-git-command-state.mjs";
14
+
15
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
16
+ const app = await readFile(join(root, "public", "app.js"), "utf8");
17
+ const fingerprint = "a".repeat(64);
18
+ const stagedContentHash = "c".repeat(64);
19
+ const repoRoot = "/workspace/repository";
20
+ const pendingPayload = {
21
+ scope: "staged",
22
+ origin: "guided-git",
23
+ repoRoot,
24
+ fingerprint,
25
+ stagedContentHash,
26
+ updatedAt: "2026-06-01T00:00:02.000Z",
27
+ decision: { state: "pending" },
28
+ };
29
+ const requestingWorkflow = {
30
+ active: true,
31
+ step: "reviewRequesting",
32
+ guidedReviewStatus: "requesting",
33
+ guidedReviewRequestedAt: Date.parse("2026-06-01T00:00:01.000Z"),
34
+ guidedReviewFingerprint: "",
35
+ guidedReviewRepoRoot: "",
36
+ guidedReviewStagedContentHash: "",
37
+ guidedReviewDeclinedStagedContentHash: "",
38
+ };
39
+ const pendingWorkflow = {
40
+ ...requestingWorkflow,
41
+ step: "review",
42
+ guidedReviewStatus: "pending",
43
+ guidedReviewRequired: true,
44
+ guidedReviewFingerprint: fingerprint,
45
+ guidedReviewRepoRoot: repoRoot,
46
+ guidedReviewStagedContentHash: stagedContentHash,
47
+ };
48
+
49
+ assert.equal(guidedGitReviewTransition(requestingWorkflow, pendingPayload), "pending", "only a fresh staged/guided-git pending payload may bind a request");
50
+ assert.equal(guidedGitReviewTransition(pendingWorkflow, { ...pendingPayload, decision: { state: "approved", decidedAt: "2026-06-01T00:00:03.000Z", reviewedFingerprint: fingerprint, reviewedStagedContentHash: stagedContentHash } }), "approved", "matching approval may advance the matching flow");
51
+ assert.equal(guidedGitReviewTransition(pendingWorkflow, { ...pendingPayload, decision: { state: "declined", decidedAt: "2026-06-01T00:00:03.000Z", reviewedFingerprint: fingerprint, reviewedStagedContentHash: stagedContentHash } }), "declined", "matching decline must reset the matching flow");
52
+ assert.equal(guidedGitReviewTransition(pendingWorkflow, { ...pendingPayload, decision: { state: "closed" } }), "closed", "a matching closed payload must return the pending flow to recovery without approval");
53
+ assert.equal(guidedGitReviewTransition(requestingWorkflow, { ...pendingPayload, decision: { state: "closed" } }), "closed", "a freshly requested review may close before its pending card is replayed");
54
+ assert.equal(guidedGitReviewTransition(pendingWorkflow, { ...pendingPayload, origin: "standalone", scope: "working-tree", decision: { state: "approved", decidedAt: "2026-06-01T00:00:03.000Z", reviewedFingerprint: fingerprint, reviewedStagedContentHash: stagedContentHash } }), "ignore", "standalone payloads cannot advance Guided Git");
55
+ assert.equal(guidedGitReviewTransition(pendingWorkflow, { ...pendingPayload, fingerprint: "b".repeat(64), decision: { state: "approved", decidedAt: "2026-06-01T00:00:03.000Z", reviewedFingerprint: "b".repeat(64), reviewedStagedContentHash: stagedContentHash } }), "ignore", "a stale/wrong review cannot advance Guided Git");
56
+ assert.equal(guidedGitReviewTransition(pendingWorkflow, { ...pendingPayload, decision: { state: "approved", decidedAt: "2026-06-01T00:00:03.000Z", reviewedFingerprint: fingerprint, reviewedStagedContentHash: "d".repeat(64) } }), "ignore", "approval must bind the exact staged-content hash");
57
+ assert.equal(guidedGitReviewTransition({ ...pendingWorkflow, active: false }, { ...pendingPayload, decision: { state: "approved", decidedAt: "2026-06-01T00:00:03.000Z", reviewedFingerprint: fingerprint, reviewedStagedContentHash: stagedContentHash } }), "ignore", "a payload for another tab's inactive flow cannot advance this tab");
58
+ assert.equal(guidedGitReviewWidgetRemovalTransition(pendingWorkflow), "closed", "clearing a matching pending widget is equivalent to close");
59
+ assert.equal(guidedGitReviewWidgetRemovalTransition({ ...pendingWorkflow, step: "add", guidedReviewStatus: "" }), "ignore", "a replayed widget removal cannot disturb a recovered staging flow");
60
+
61
+ const freshAvailableWorkflow = {
62
+ ...requestingWorkflow,
63
+ step: "add",
64
+ process: "stage",
65
+ guidedReviewRequired: true,
66
+ };
67
+ for (const process of ["message", "commit", "push"]) {
68
+ assert.equal(guidedGitReviewProcessNavigationAllowed(requestingWorkflow, process), false, `${process} navigation must be rejected while review request is outstanding`);
69
+ assert.equal(guidedGitReviewProcessNavigationAllowed(pendingWorkflow, process), false, `${process} navigation must be rejected while review is pending`);
70
+ assert.equal(guidedGitReviewProcessNavigationAllowed(freshAvailableWorkflow, process), false, `a fresh available-review flow must block ${process} before staging and approval`);
71
+ assert.equal(guidedGitReviewProcessSelectionPatch(freshAvailableWorkflow, process), null, `a fresh available-review flow must not transition to ${process}`);
72
+ }
73
+ assert.equal(guidedGitReviewProcessNavigationAllowed(pendingWorkflow, "stage"), true, "staging recovery remains available while review is pending");
74
+ assert.equal(guidedGitReviewProcessNavigationAllowed(pendingWorkflow, "review"), true, "review recovery remains available while review is pending");
75
+
76
+ const approvedWorkflow = {
77
+ ...pendingWorkflow,
78
+ step: "generate",
79
+ process: "message",
80
+ guidedReviewStatus: "approved",
81
+ guidedReviewRequired: false,
82
+ };
83
+ assert.equal(guidedGitReviewHasApprovedBinding(approvedWorkflow), true, "approval must carry the exact repo, fingerprint, and staged-content binding");
84
+ for (const process of ["message", "commit", "push"]) {
85
+ assert.equal(guidedGitReviewProcessNavigationAllowed(approvedWorkflow, process), true, `matching approval may navigate to ${process}`);
86
+ const patch = guidedGitReviewProcessSelectionPatch(approvedWorkflow, process);
87
+ assert.equal(patch?.guidedReviewStatus, "approved", `${process} navigation must preserve approval status`);
88
+ assert.equal(patch?.guidedReviewRepoRoot, repoRoot, `${process} navigation must preserve the approved repo root`);
89
+ assert.equal(patch?.guidedReviewFingerprint, fingerprint, `${process} navigation must preserve the approved fingerprint`);
90
+ assert.equal(patch?.guidedReviewStagedContentHash, stagedContentHash, `${process} navigation must preserve the approved staged-content hash`);
91
+ assert.equal(patch?.guidedReviewRequired, false, `${process} navigation must not convert matching approval to legacy state`);
92
+ }
93
+ for (const process of ["stage", "review"]) {
94
+ const patch = guidedGitReviewProcessSelectionPatch(approvedWorkflow, process);
95
+ assert.equal(patch?.guidedReviewRequired, true, `${process} must re-arm required review after approval`);
96
+ assert.equal(patch?.guidedReviewStatus, "", `${process} must clear prior approval status`);
97
+ assert.equal(patch?.guidedReviewRepoRoot, "", `${process} must clear prior repo binding`);
98
+ assert.equal(patch?.guidedReviewFingerprint, "", `${process} must clear prior fingerprint binding`);
99
+ assert.equal(patch?.guidedReviewStagedContentHash, "", `${process} must clear prior staged-content binding`);
100
+ const rearmedWorkflow = { ...approvedWorkflow, ...patch, step: process === "stage" ? "add" : "review", process };
101
+ for (const laterProcess of ["message", "commit", "push"]) {
102
+ assert.equal(guidedGitReviewProcessNavigationAllowed(rearmedWorkflow, laterProcess), false, `${laterProcess} must remain blocked after approval is cleared via ${process}`);
103
+ }
104
+ }
105
+
106
+ const legacyWorkflow = {
107
+ ...requestingWorkflow,
108
+ step: "add",
109
+ process: "stage",
110
+ guidedReviewRequired: false,
111
+ };
112
+ for (const process of ["message", "commit", "push"]) {
113
+ assert.equal(guidedGitReviewProcessNavigationAllowed(legacyWorkflow, process), true, `a flow started without aur-review retains legacy ${process} navigation`);
114
+ assert.equal(guidedGitReviewProcessSelectionPatch(legacyWorkflow, process)?.guidedReviewRequired, false, `legacy ${process} navigation must remain ungated`);
115
+ }
116
+
117
+ const recoveredWorkflow = {
118
+ ...pendingWorkflow,
119
+ step: "add",
120
+ process: "stage",
121
+ guidedReviewStatus: "",
122
+ guidedReviewFingerprint: "",
123
+ guidedReviewRepoRoot: "",
124
+ guidedReviewStagedContentHash: "",
125
+ guidedReviewDeclinedStagedContentHash: stagedContentHash,
126
+ guidedReviewRequired: true,
127
+ };
128
+ for (const process of ["message", "commit", "push"]) {
129
+ assert.equal(guidedGitReviewProcessNavigationAllowed(recoveredWorkflow, process), false, `${process} remains blocked after Stage/Review recovery`);
130
+ }
131
+ assert.equal(guidedGitReviewProcessNavigationAllowed(recoveredWorkflow, "stage"), true, "recovery stage remains available with durable requirement");
132
+ assert.equal(guidedGitReviewProcessNavigationAllowed(recoveredWorkflow, "review"), true, "recovery review remains available with durable requirement");
133
+ const rerequestedWorkflow = { ...pendingWorkflow, guidedReviewRequired: true };
134
+ assert.equal(guidedGitReviewTransition(rerequestedWorkflow, { ...pendingPayload, decision: { state: "approved", decidedAt: "2026-06-01T00:00:03.000Z", reviewedFingerprint: fingerprint, reviewedStagedContentHash: stagedContentHash } }), "approved", "a new matching approval advances the recovered review flow");
135
+ assert.equal(guidedGitReviewCanRequestStagedContent(recoveredWorkflow, stagedContentHash), false, "an unchanged declined staged hash must be rejected");
136
+ assert.equal(guidedGitReviewCanRequestStagedContent(recoveredWorkflow, "d".repeat(64)), true, "changed/restaged content may request a new review");
137
+
138
+ const catalogByTab = new Map();
139
+ const delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
140
+ await Promise.all([
141
+ (async () => { await delay(12); catalogByTab.set("tab-a", { raw: [{ name: "git-staged-msg", source: "extension" }], available: [{ name: "git-staged-msg", source: "extension" }] }); })(),
142
+ (async () => { await delay(1); catalogByTab.set("tab-b", { raw: [{ name: "aur-review:2", source: "extension" }], available: [{ name: "aur-review:2", invokeName: "aur-review:2", duplicateCount: 2, source: "extension" }] }); })(),
143
+ ]);
144
+ assert.equal(guidedGitReviewAvailableForTabCatalog(catalogByTab.get("tab-a")), false, "tab A cannot inherit tab B's review command after async tab switching");
145
+ assert.equal(resolveRpcSlashCommandForTabCatalog(catalogByTab.get("tab-a"), "/aur-review start --scope staged"), "/aur-review start --scope staged", "tab A cannot inherit tab B's alias");
146
+ assert.equal(guidedGitReviewAvailableForTabCatalog(catalogByTab.get("tab-b")), true, "tab B retains its own review command");
147
+ assert.equal(resolveRpcSlashCommandForTabCatalog(catalogByTab.get("tab-b"), "/aur-review start --scope staged"), "/aur-review:2 start --scope staged", "tab B resolves only its own alias");
148
+
149
+ const runGitAdd = app.slice(app.indexOf("async function runGitAdd"), app.indexOf("async function acceptCurrentGitStaging"));
150
+ const acceptStaging = app.slice(app.indexOf("async function acceptCurrentGitStaging"), app.indexOf("async function loadGitWorkflowDefaultCommitMessage"));
151
+ assert.match(runGitAdd, /guidedGitReviewAvailable\(tabId\) \|\| workflow\.guidedReviewRequired === true[\s\S]*await requestGuidedGitReview\(tabId, \{ output \}\)/s, "git add . must keep an already-required review gate fail-closed while preserving disabled-from-start fallback");
152
+ assert.match(acceptStaging, /guidedGitReviewAvailable\(tabId\) \|\| workflow\.guidedReviewRequired === true[\s\S]*await requestGuidedGitReview\(tabId, \{ output \}\)/s, "accepting a staged set must keep an already-required review gate fail-closed");
153
+ const reconcileReview = app.slice(app.indexOf("function reconcileGuidedGitReviewPayload"), app.indexOf("async function startGitWorkflow"));
154
+ assert.match(reconcileReview, /transition === "approved"[\s\S]*step: "generate"[\s\S]*guidedReviewDeclinedStagedContentHash: ""/s, "only approval advances to message generation and clears an older decline binding");
155
+ assert.match(reconcileReview, /transition === "pending"[\s\S]*guidedReviewDeclinedStagedContentHash[\s\S]*same staged content that was declined/s, "extension payload replay cannot retry an unchanged declined staged hash");
156
+ assert.match(reconcileReview, /transition === "closed"[\s\S]*resetGuidedGitReviewToStaging/s, "closed payloads must reset the matching flow to staging");
157
+ assert.match(reconcileReview, /function reconcileGuidedGitReviewWidgetRemoval[\s\S]*guidedGitReviewWidgetRemovalTransition[\s\S]*resetGuidedGitReviewToStaging/s, "matching widget removal must reset the gate rather than imply approval");
158
+ const resetReviewToStaging = app.slice(app.indexOf("function resetGuidedGitReviewToStaging"), app.indexOf("function reconcileGuidedGitReviewPayload"));
159
+ assert.match(resetReviewToStaging, /step: "add"[\s\S]*stage: false/s, "decline and close return the flow to staging and require restaging");
160
+ const workflowRender = app.slice(app.indexOf("function renderGitWorkflow"), app.indexOf("async function gitWorkflowRequest"));
161
+ assert.match(workflowRender, /item\.disabled = !!gitWorkflow\.busy \|\| !guidedGitReviewProcessNavigationAllowed\(gitWorkflow, process\.value\);/, "the UI must disable later process buttons while the review gate is active");
162
+ const processSelection = app.slice(app.indexOf("function selectGitWorkflowProcess"), app.indexOf("function gitWorkflowTitle"));
163
+ assert.match(processSelection, /const guidedReviewPatch = guidedGitReviewProcessSelectionPatch\(workflow, process\);[\s\S]*if \(!guidedReviewPatch\) return;[\s\S]*\.\.\.guidedReviewPatch/s, "process selection must use the tested patch that preserves approval or re-arms review");
164
+ assert.doesNotMatch(processSelection, /resetGuidedGitReviewPatch/, "process selection must not share a reset that drops an approved binding during later navigation");
165
+ const startWorkflow = app.slice(app.indexOf("async function startGitWorkflow"), app.indexOf("async function startGitInitWorkflow"));
166
+ assert.match(startWorkflow, /guidedReviewRequired: guidedGitReviewAvailable\(tabId\)/, "a fresh standard flow must require review when aur-review is available in its originating tab");
167
+ assert.match(app, /function guidedGitReviewAvailable\(tabId = activeTabId\)[\s\S]*commandCatalogForTab\(tabId\)/, "Guided Git availability must read the originating tab catalog");
168
+ assert.match(app, /resolveRpcSlashCommandMessage\(guidedGitReviewCommand\(\), \{ tabId \}\)/, "Guided Git review requests must resolve aliases from the originating tab catalog");
169
+ assert.match(app, /message = resolveRpcSlashCommandMessage\(message, \{ tabId: targetTabId \}\)/, "generic targeted slash-command dispatch must resolve aliases from its captured target tab");
170
+ for (const [name, action] of [["runGitMessagePrompt", "commit-message generation"], ["commitGitWorkflow", "commit"], ["createGitPrBranchWithSuggestion", "PR worktree creation"]]) {
171
+ const start = app.indexOf(`async function ${name}`);
172
+ const next = app.indexOf("\nasync function ", start + 1);
173
+ const source = app.slice(start, next === -1 ? undefined : next);
174
+ assert.match(source, /assertGuidedGitStagedContentBinding/, `${name} must recheck the approved staged-content hash at its action boundary`);
175
+ assert.match(source, /expectedStagedContentHash/, `${name} must send the approved staged-content hash to its gated endpoint`);
176
+ }
177
+ assert.match(app, /function requestGuidedGitReview[\s\S]*readGuidedGitStagedContent[\s\S]*git add \. produced no substantive staged changes[\s\S]*guideded|function requestGuidedGitReview[\s\S]*readGuidedGitStagedContent[\s\S]*git add \. produced no substantive staged changes/s, "manual-review requests must preflight no-staged content instead of waiting for a card");
178
+ assert.match(app, /guidedGitReviewUnavailableMessage[\s\S]*No message, commit, worktree, or push action was performed/, "a disappeared extension after a required gate must remain fail-closed with recovery guidance");
179
+ assert.match(app, /commandCatalogsByTab\.set\(tabContext\.tabId, catalog\)[\s\S]*if \(!isCurrentTabContext\(tabContext\)\) return;/, "async command refresh must cache inactive-tab results rather than discard or activate them");
180
+ assert.match(app, /widgetKey === AUR_REVIEW_RPC_WIDGET_KEY[\s\S]*else if \(!Array\.isArray\(request\.widgetLines\)\) reconcileGuidedGitReviewWidgetRemoval\(requestTabId\)/s, "active-tab widget clearing must reconcile a matching pending review");
181
+ assert.match(app, /AUR_REVIEW_RPC_WIDGET_KEY\)[\s\S]*else if \(!Array\.isArray\(event\.widgetLines\)\) reconcileGuidedGitReviewWidgetRemoval\(event\.tabId\)/s, "inactive-tab widget clearing must reconcile the owning tab only");
182
+ assert.match(app, /handleInactiveTabEvent[\s\S]*AUR_REVIEW_RPC_WIDGET_KEY[\s\S]*reconcileGuidedGitReviewPayload\(event\.tabId, payload\)/s, "tab-local review events must reconcile using their event tab id");
183
+ console.log("guided Git aur-review tests passed");