@iceinvein/agent-skills 0.24.0 → 0.25.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.
Files changed (30) hide show
  1. package/README.md +2 -1
  2. package/package.json +1 -1
  3. package/skills/index.json +1 -1
  4. package/skills/magpie/README.md +14 -0
  5. package/skills/magpie/SKILL.md +7 -5
  6. package/skills/magpie/bin/magpie.ts +63 -3
  7. package/skills/magpie/evals/README.md +1 -1
  8. package/skills/magpie/evals/post-folds-selection-events/fixture.sh +35 -0
  9. package/skills/magpie/evals/post-folds-selection-events/graders/selection-read-from-magpie-view.md +6 -0
  10. package/skills/magpie/evals/post-folds-selection-events/prompt.md +2 -2
  11. package/skills/magpie/evals/rules.json +2 -2
  12. package/skills/magpie/package.json +1 -1
  13. package/skills/magpie/scripts/__tests__/helper.test.ts +300 -0
  14. package/skills/magpie/scripts/__tests__/labels.test.ts +46 -1
  15. package/skills/magpie/scripts/__tests__/mark-cmd.test.ts +129 -0
  16. package/skills/magpie/scripts/__tests__/post-cmd.test.ts +298 -1
  17. package/skills/magpie/scripts/__tests__/render-cmd.test.ts +15 -1
  18. package/skills/magpie/scripts/__tests__/render-findings.test.ts +13 -0
  19. package/skills/magpie/scripts/__tests__/server.test.ts +96 -1
  20. package/skills/magpie/scripts/__tests__/skill-lint.test.ts +23 -0
  21. package/skills/magpie/scripts/__tests__/view-cmd.test.ts +219 -0
  22. package/skills/magpie/scripts/helper.js +44 -4
  23. package/skills/magpie/scripts/labels.ts +11 -0
  24. package/skills/magpie/scripts/mark-cmd.ts +56 -0
  25. package/skills/magpie/scripts/post-cmd.ts +75 -5
  26. package/skills/magpie/scripts/render-cmd.ts +3 -1
  27. package/skills/magpie/scripts/render-findings.ts +3 -1
  28. package/skills/magpie/scripts/server.ts +31 -2
  29. package/skills/magpie/scripts/view-cmd.ts +143 -0
  30. package/skills/magpie/skill.json +1 -1
package/README.md CHANGED
@@ -36,6 +36,7 @@ Each skill is also a plugin in the `iceinvein-skills` marketplace:
36
36
  - Activation modes do not apply: sluice's hooks always run while the plugin is enabled, and terse is never auto-activated.
37
37
  - Do not install sluice through both routes, or its hooks run twice. Its statusline segment is bunx-only.
38
38
  - magpie, migrate and scope-estimate need Bun on PATH.
39
+ - The magpie-panel mod shows a magpie PR review in a pane beside the chat. It needs the magpie plugin: `/plugin install magpie-panel@iceinvein-skills`.
39
40
  - improve-my-codebase's plugin carries every audit, so under the plugin route its audits do not need installing separately.
40
41
 
41
42
  ## Skills
@@ -138,7 +139,7 @@ Skills that compose the other audit skills into higher-level workflows.
138
139
  | Skill | What it does |
139
140
  |-------|--------------|
140
141
  | **improve-my-codebase** | Runs every applicable audit skill in parallel against your codebase, ranks findings by convergence (multiple audits agreeing) and per-file rollup, and writes a prioritized improvement report. Default sweeps everything; positional args switch modes (`quick`, `diff`, `interactive`) or narrow scope (`focus <area>`, `module <path>`). |
141
- | **magpie** | Interactive PR review pipeline. Runs five parallel specialist subagents (security, bugs, performance, code-smells, architecture), dedupes findings, applies a critic rubric, peer-reviews via `codex exec`, and serves an interactive HTML report for selecting findings to post via `gh`. A local mode reviews the current branch diff before a PR exists and hands the findings back in the terminal. Claude Code only. |
142
+ | **magpie** | Interactive PR review pipeline. Runs five parallel specialist subagents (security, bugs, performance, code-smells, architecture), dedupes findings, applies a critic rubric, peer-reviews via `codex exec`, and serves an interactive HTML report for selecting findings to post via `gh`, mirrored in a pane beside the chat when the magpie-panel mod is installed. A local mode reviews the current branch diff before a PR exists and hands the findings back in the terminal. Claude Code only. |
142
143
 
143
144
  ## Commands
144
145
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iceinvein/agent-skills",
3
- "version": "0.24.0",
3
+ "version": "0.25.0",
4
4
  "description": "Install agent skills into AI coding tools",
5
5
  "author": "iceinvein",
6
6
  "license": "MIT",
package/skills/index.json CHANGED
@@ -227,7 +227,7 @@
227
227
  "name": "magpie",
228
228
  "description": "Interactive PR review pipeline. Runs five parallel specialist subagents (security, bugs, performance, code-smells, architecture) plus a once-per-PR checks pass that finds tests and controls able to pass without proving their purpose, drops findings whose quoted evidence is not in the code, dedupes, runs critic subagents that re-check each finding against the worktree and set its risk label, peer-reviews via codex exec (falling back to a Claude second opinion when codex is unavailable), and serves an interactive HTML report for selecting or dismissing findings to post via gh, recording the outcome per finding as labels. Bundles a Bun CLI put on PATH by the skill's postinstall step under a bunx install, or by the plugin's bin/ under a Claude Code plugin install. Use when the user asks to review a GitHub pull request. Local mode (setup --local) runs the same pipeline on the current branch's diff from its merge base, uncommitted and untracked work included, against the caller's live tree, with no server or posting, and hands the ranked findings back in the terminal for an implementing or orchestrating agent to address. Splits oversized diffs into budgeted shards and rebuilds the diff from the local clone when gh pr diff refuses it.",
229
229
  "type": "prompt",
230
- "version": "0.16.1"
230
+ "version": "0.17.0"
231
231
  },
232
232
  {
233
233
  "name": "migrate",
@@ -37,6 +37,20 @@ Inside Claude Code, ask: "Review PR 1234" (or paste a PR URL). The agent reads S
37
37
 
38
38
  An implementing or orchestrating agent can also ask for a review of its own branch before a PR exists: local mode (`magpie setup <run-dir> --local [--base <ref>]`) reviews the merge base to working tree diff in place and hands the ranked findings back as terminal text via `magpie handoff`, with no server, report or posting. `/magpie` with no arguments runs local mode; pass a PR number or URL to review a PR.
39
39
 
40
+ ### Review panel
41
+
42
+ The [magpie-panel](../../mods/magpie-panel) mod shows a PR run's findings in a pane beside the chat, alongside the HTML report. With it installed, stage 8 opens the pane; without it nothing changes.
43
+
44
+ ```
45
+ /plugin install magpie-panel@iceinvein-skills
46
+ ```
47
+
48
+ The pane and the report share their ticks through the run's `state/events`, and the pane reaches the run only through these commands, which also work on their own:
49
+
50
+ - `magpie view <run-dir> [--top N]` prints a PR run's findings as one JSON object, each with its diff hunk, post status, dismissal and whether it is selected or recommended. Stage 9 reads the selection from it when you reply `post`.
51
+ - `magpie mark <run-dir> <id> select|deselect|undismiss` and `magpie mark <run-dir> <id> dismiss <reason>` record a selection or dismissal event, as the report's checkboxes and Dismiss button do.
52
+ - `magpie post <run-dir> --ids a,b --review [--via recommended|selected|one|cli]` posts the findings as one GitHub review, as the report's Post buttons do, skipping ids already posted; `--via` records which button the post came from in `labels.json`. Without `--review`, `post` keeps posting separate inline comments plus a summary comment.
53
+
40
54
  ## Development
41
55
 
42
56
  ```
@@ -215,15 +215,17 @@ The report shows the top 10 recommended (`must-fix`/`should-fix`, highest score
215
215
 
216
216
  Append `{stage: report, status: done}` to `$RUN_DIR/log.jsonl` and re-render progress (the render CLI does not log this itself, and `magpie status` needs the `done` entry to resume past `report`).
217
217
 
218
- Print to the terminal: "Findings ready at <url>. Tick the ones you want and click **Post Selected**, or reply `post` here and I'll post whatever you've ticked."
218
+ If `mcp__magpie-panel__show_findings` is available, resolve `$RUN_DIR`, `command -v magpie` and `$PATH` in Bash, then call it with them as `runDir`, `magpieBin` and `path` to open the findings panel.
219
+
220
+ Print to the terminal: "Findings ready at <url> and in the magpie panel. Tick the ones you want and click **Post Selected**, or reply `post` here and I'll post whatever you've ticked." Drop "and in the magpie panel" unless the call succeeded.
219
221
 
220
222
  End the turn.
221
223
 
222
224
  ### 9. Post
223
225
 
224
- Most users tick the checkboxes in the served report and click **Post Selected** (or **Post Recommended**, which takes only the top N above the fold; **Select recommended** ticks the same set); the server posts that batch as one GitHub review with inline threads. **Dismiss** on a finding records a reason (`wrong`, `not-worth-it`, `duplicate`, `style`) and drops it from the recommended set. The agent posts only when the user types `post` (optionally `post 1,3,7` for indices), which takes the CLI path below: separate inline comments plus a top-level summary comment. Either path records posted ids in `post-status.json`, so the two cannot double-post the same finding.
226
+ Most users tick findings in the report or panel and click **Post Selected** (or **Post Recommended**, which takes only the top N above the fold; **Select recommended** ticks the same set); the server posts that batch as one GitHub review with inline threads. **Dismiss** on a finding records a reason (`wrong`, `not-worth-it`, `duplicate`, `style`) and drops it from the recommended set. The agent posts only when the user types `post` (optionally `post 1,3,7` for indices), which takes the CLI path below. Either path records posted ids in `post-status.json`, so the two cannot double-post the same finding.
225
227
 
226
- When the user types `post`, read `$RUN_DIR/state/events` and fold them in order, keeping the LAST event per finding id; ids whose last event is `select` are selected (a later `dismiss` therefore unselects). (Not union-minus: the UI emits one event per toggle, so select, deselect, select again resolves to selected.) Merge any explicit indices the user named (1-based, against `findings.final.json` in file order). If nothing is selected, say so and ask rather than posting an empty batch. Then post via the CLI:
228
+ When the user types `post`, run `magpie view "$RUN_DIR"` and take the ids whose `selected` is true (report and panel ticks, already folded). Merge any explicit indices the user named (1-based, against `findings.final.json` in file order). If nothing is selected, say so and ask rather than posting an empty batch. Then post via the CLI:
227
229
 
228
230
  ```
229
231
  magpie post "$RUN_DIR" --ids id1,id2,id3
@@ -231,8 +233,8 @@ magpie post "$RUN_DIR" --ids id1,id2,id3
231
233
 
232
234
  That delegates to `runPost`, which:
233
235
 
234
- - For a finding with a `line`, picks `formatInlineBody` (severity heading, `<sub>` risk metaline, parsed `Observation`/`Why it matters`/`Suggested direction`/`Needs verification` sections, optional `` ```suggestion `` block, hidden `magpie:finding` marker) and opens an inline review thread via `gh api repos/<owner>/<repo>/pulls/<n>/comments`.
235
- - Falls back to `formatConversationBody` (same shape plus a `Location · <file>:<line>` metaline) via `gh pr comment <n>` when there is no anchor, or GitHub rejects the inline anchor with 422.
236
+ - For a finding with a `line`, picks `formatInlineBody` (severity heading, risk metaline, parsed sections, optional `` ```suggestion `` block, hidden `magpie:finding` marker) and opens an inline review thread via `gh api repos/<owner>/<repo>/pulls/<n>/comments`.
237
+ - Falls back to `formatConversationBody` (same shape plus a location line) via `gh pr comment <n>` when there is no anchor, or GitHub rejects the inline anchor with 422.
236
238
  - When at least one new finding is in the batch (default `auto` mode), prepends one top-level summary comment (verdict line, "Needs Attention" top three, `<details>` risk breakdown) and persists the `__summary__` sentinel in `post-status.json` so re-runs don't duplicate it. Override with `--include-summary always|never`.
237
239
  - Appends `{stage: post, ...}` events to `log.jsonl` and updates `$RUN_DIR/post-status.json` per finding id.
238
240
 
@@ -13,6 +13,12 @@ Subcommands:
13
13
  (default origin/HEAD), committed and uncommitted
14
14
  target <run-dir> Print the directory findings are anchored against
15
15
  handoff <run-dir> Print local review findings as a ranked list
16
+ view <run-dir> [--top N] Print a PR run's findings with diff hunks, post status and
17
+ selection as JSON (recommends the top N, default 10)
18
+ mark <run-dir> <id> select|deselect|undismiss
19
+ mark <run-dir> <id> dismiss <reason>
20
+ Record a selection or dismissal in state/events, as the
21
+ HTML report does (reason: wrong|not-worth-it|duplicate|style)
16
22
  history <run-dir> Print what is already on the PR (open threads, comments,
17
23
  dismissals, failing checks) for the specialist prompts
18
24
  serve <run-dir-or-id> Start the HTML server (accepts active or archived run id)
@@ -38,7 +44,10 @@ Subcommands:
38
44
  delete saved refs of closed PRs
39
45
  status <run-dir> Print highest completed stage
40
46
  open [id] Open findings.html in your browser (defaults to latest run)
41
- post <run-dir> --ids a,b Post the given finding ids via gh (rich body + optional summary)
47
+ post <run-dir> --ids a,b [--review] [--via recommended|selected|one|cli] [--dry-run]
48
+ Post the given finding ids via gh (rich body + optional
49
+ summary); --review posts them as one GitHub review, as the
50
+ HTML report does, and prints its id and per-id results
42
51
  preview [opts] Render the UI from a bundled fixture (no PR needed). See --help-preview.
43
52
  --list-runs List archived runs
44
53
  --cleanup-run <id> Delete an archived run
@@ -150,6 +159,38 @@ const HANDLERS: Record<string, Handler> = {
150
159
  const { runHandoff } = await import('../scripts/handoff-cmd.ts')
151
160
  return runHandoff(runDir, { gitBin: process.env.MAGPIE_GIT_BIN || 'git' })
152
161
  },
162
+ view: async (args) => {
163
+ const runDir = args[0]
164
+ if (!runDir || runDir.startsWith('-')) {
165
+ process.stderr.write('view: missing <run-dir> [--top <n>]\n')
166
+ return 2
167
+ }
168
+ const flag = args.indexOf('--top')
169
+ const raw = flag !== -1 ? args[flag + 1] : undefined
170
+ const { DEFAULT_TOP_N } = await import('../scripts/render-issues-list.ts')
171
+ let topN = DEFAULT_TOP_N
172
+ if (flag !== -1) {
173
+ const n = Number(raw)
174
+ if (!Number.isInteger(n) || n <= 0) {
175
+ process.stderr.write(`view: invalid --top ${raw} (want a positive integer)\n`)
176
+ return 2
177
+ }
178
+ topN = n
179
+ }
180
+ const { runView } = await import('../scripts/view-cmd.ts')
181
+ return runView(runDir, topN)
182
+ },
183
+ mark: async (args) => {
184
+ const [runDir, id, verb, reason] = args
185
+ if (!runDir || runDir.startsWith('-') || !id || !verb) {
186
+ process.stderr.write(
187
+ 'mark: missing <run-dir> <id> (select|deselect|undismiss | dismiss <reason>)\n',
188
+ )
189
+ return 2
190
+ }
191
+ const { runMark } = await import('../scripts/mark-cmd.ts')
192
+ return runMark({ runDir, id, verb, ...(reason !== undefined ? { reason } : {}) })
193
+ },
153
194
  serve: async (args) => {
154
195
  const idOrPath = args[0]
155
196
  if (!idOrPath) {
@@ -428,7 +469,7 @@ const HANDLERS: Record<string, Handler> = {
428
469
  const runDir = args[0]
429
470
  if (!runDir) {
430
471
  process.stderr.write(
431
- 'post: missing <run-dir> --ids <a,b,c> [--include-summary auto|always|never] [--dry-run]\n',
472
+ 'post: missing <run-dir> --ids <a,b,c> [--review] [--via recommended|selected|one|cli] [--include-summary auto|always|never] [--dry-run]\n',
432
473
  )
433
474
  return 2
434
475
  }
@@ -456,13 +497,32 @@ const HANDLERS: Record<string, Handler> = {
456
497
  process.stderr.write(`post: invalid --include-summary ${summaryRaw}\n`)
457
498
  return 2
458
499
  }
500
+ const viaFlag = args.indexOf('--via')
501
+ const viaRaw = viaFlag !== -1 ? args[viaFlag + 1] : undefined
502
+ const { POST_VIAS, parseVia } = await import('../scripts/labels.ts')
503
+ const via = viaFlag !== -1 ? parseVia(viaRaw) : 'cli'
504
+ if (!via) {
505
+ process.stderr.write(`post: invalid --via ${viaRaw} (want ${POST_VIAS.join('|')})\n`)
506
+ return 2
507
+ }
459
508
  const dryRun = args.includes('--dry-run')
509
+ if (args.includes('--review')) {
510
+ const { runPostReview } = await import('../scripts/post-cmd.ts')
511
+ const review = await runPostReview({ runDir, findingIds, via, dryRun })
512
+ if (review.error) {
513
+ process.stderr.write(`post: ${review.error}\n`)
514
+ return 2
515
+ }
516
+ const { ok, reviewId, results } = review
517
+ process.stdout.write(`${JSON.stringify({ ok, reviewId, results })}\n`)
518
+ return ok ? 0 : 1
519
+ }
460
520
  const { runPost } = await import('../scripts/post-cmd.ts')
461
521
  const outcome = await runPost({
462
522
  runDir,
463
523
  findingIds,
464
524
  dryRun,
465
- via: 'cli',
525
+ via,
466
526
  ...(includeSummary ? { includeSummary } : {}),
467
527
  })
468
528
  process.stdout.write(`${JSON.stringify(outcome)}\n`)
@@ -12,7 +12,7 @@ must not touch.
12
12
  | `shard-gate-stops-and-asks` | A resume at stage 4 with seven shards | Stops before dispatching, names 7 shards and 35 subagents, offers all three options |
13
13
  | `codex-missing-falls-back` | No codex on the machine at stage 7 | Claude path with the independence preamble, `provider: claude`, never `status: error` |
14
14
  | `report-ends-the-turn` | Stage 8 reached | Renders, logs the stage done, hands back for selection, posts nothing |
15
- | `post-folds-selection-events` | The user typed `post` after re-ticking | Folds `state/events` last-event-wins, posts `bugs-1,perf-1` only |
15
+ | `post-folds-selection-events` | The user typed `post` after re-ticking | Reads the selection from `magpie view`, posts `bugs-1,perf-1` only |
16
16
  | `resume-finds-active-run` | A fresh review ask on a PR with a live run | Checks `--list-runs` first, never calls `setup`, surfaces the interrupted run |
17
17
  | `local-mode-hands-back` | A local run resumed after peer review | Runs `handoff` then `cleanup`, replies with both finding titles, never serves, renders, posts or calls `gh` |
18
18
  | `bare-invocation-goes-local` | A bare `/magpie` on a branch with an open PR | Runs `setup --local`, never `--pr`, never calls `gh` |
@@ -90,6 +90,41 @@ buttons = '<button>Post Selected</button><button>Post Recommended</button>' if r
90
90
  RENDER
91
91
  echo "rendered ${3:-progress} -> $RUN_DIR/screen/${3:-progress}.html"
92
92
  ;;
93
+ view)
94
+ # Folds state/events last-event-wins as the real view does, so the
95
+ # selection follows the events the case writes rather than a canned list.
96
+ python3 - "${2:-$RUN_DIR}" <<'VIEW'
97
+ import json, pathlib, sys
98
+
99
+ run = pathlib.Path(sys.argv[1])
100
+ selected = set()
101
+ events = run / 'state' / 'events'
102
+ for line in (events.read_text().splitlines() if events.exists() else []):
103
+ if not line.strip():
104
+ continue
105
+ event = json.loads(line)
106
+ if event['type'] == 'select':
107
+ selected.add(event['findingId'])
108
+ elif event['type'] in ('deselect', 'dismiss'):
109
+ selected.discard(event['findingId'])
110
+ status_path = run / 'post-status.json'
111
+ status = json.loads(status_path.read_text()) if status_path.exists() else {}
112
+ pr = json.loads((run / 'pr.json').read_text())
113
+ findings = []
114
+ for f in json.loads((run / 'findings.final.json').read_text()):
115
+ raw = status.get(f['id'])
116
+ state = raw if isinstance(raw, str) or raw is None else raw.get('status')
117
+ findings.append({
118
+ 'id': f['id'], 'file': f['file'], 'line': f['line'], 'severity': f['severity'],
119
+ 'action': f['risk']['action'], 'title': f['title'], 'description': f['description'],
120
+ 'suggestion': None, 'proof': None, 'hunk': None, 'fileDiff': None,
121
+ 'postStatus': state, 'postMessage': None if isinstance(raw, str) or raw is None else raw.get('message'),
122
+ 'dismissed': None, 'selected': f['id'] in selected,
123
+ 'recommended': f['risk']['action'] in ('must-fix', 'should-fix') and state != 'posted',
124
+ })
125
+ print(json.dumps({'pr': {'number': pr['number'], 'title': pr['title'], 'url': pr['url']}, 'findings': findings}))
126
+ VIEW
127
+ ;;
93
128
  post)
94
129
  ids=""
95
130
  while [ $# -gt 0 ]; do
@@ -0,0 +1,6 @@
1
+ ---
2
+ type: regex
3
+ pattern: 'magpie view \S+[\s\S]*magpie post [^\n]*--ids'
4
+ target: { source: file, path: .magpie-calls.log }
5
+ weight: 2
6
+ ---
@@ -1,11 +1,11 @@
1
1
  ---
2
2
  name: post-folds-selection-events
3
- description: Typing `post` posts what state/events leaves selected, folded last-event-wins per finding id.
3
+ description: Typing `post` posts the findings `magpie view` reports as selected.
4
4
  tags: [magpie, post, selection, scaffold]
5
5
  max_turns: 25
6
6
  timeout_seconds: 900
7
7
  allowed_tools: [Read, Glob, Grep, Skill, Write, Edit, Bash]
8
- expected_outcome: Posts exactly bugs-1 and perf-1 via magpie post --ids, leaves the deselected security-1 alone, logs the post stage done and re-renders the report.
8
+ expected_outcome: Reads the selection from magpie view, posts exactly bugs-1 and perf-1 via magpie post --ids, leaves the deselected security-1 alone, logs the post stage done and re-renders the report.
9
9
  ---
10
10
 
11
11
  I've been ticking through the magpie report for PR 1337. post
@@ -112,9 +112,9 @@
112
112
  ]
113
113
  },
114
114
  {
115
- "id": "post-folds-events-last-event-wins",
115
+ "id": "post-reads-selection-from-magpie-view",
116
116
  "states": "SKILL.md: 9. Post",
117
- "origin": "commit:1762265",
117
+ "origin": "docs/specs/2026-11-20-magpie-panel.md",
118
118
  "cases": [
119
119
  "post-folds-selection-events"
120
120
  ]
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "magpie",
3
- "version": "0.11.0",
3
+ "version": "0.17.0",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "scripts": {
@@ -240,3 +240,303 @@ test('each page post path sends its via to the server', async () => {
240
240
  'JSON.stringify({ findingIds: ids, via })',
241
241
  )
242
242
  })
243
+
244
+ // A page small enough to run helper.js against: two findings, each with a card
245
+ // and a checkbox, plus the action bar's count, status line and post button.
246
+ type FakeResponse = { ok: boolean; status: number; body: unknown }
247
+
248
+ class FakeElement {
249
+ tagName: string
250
+ attrs: Map<string, string>
251
+ dataset: Record<string, string> = {}
252
+ checked = false
253
+ disabled = false
254
+ hidden = false
255
+ className = ''
256
+ private text = ''
257
+ onText: (() => void) | null = null
258
+
259
+ constructor(tag: string, attrs: Record<string, string>) {
260
+ this.tagName = tag.toUpperCase()
261
+ this.attrs = new Map(Object.entries(attrs))
262
+ for (const [name, value] of Object.entries(attrs)) {
263
+ if (!name.startsWith('data-')) continue
264
+ const key = name.slice(5).replace(/-([a-z])/g, (_, c: string) => c.toUpperCase())
265
+ this.dataset[key] = value
266
+ }
267
+ }
268
+
269
+ get type(): string | undefined {
270
+ return this.attrs.get('type')
271
+ }
272
+
273
+ get textContent(): string {
274
+ return this.text
275
+ }
276
+
277
+ set textContent(value: string) {
278
+ this.text = value
279
+ this.onText?.()
280
+ }
281
+
282
+ getAttribute(name: string): string | null {
283
+ return this.attrs.get(name) ?? null
284
+ }
285
+
286
+ setAttribute(name: string, value: string): void {
287
+ this.attrs.set(name, value)
288
+ }
289
+
290
+ hasAttribute(name: string): boolean {
291
+ return this.attrs.has(name)
292
+ }
293
+
294
+ removeAttribute(name: string): void {
295
+ this.attrs.delete(name)
296
+ }
297
+
298
+ querySelector(): null {
299
+ return null
300
+ }
301
+
302
+ closest(selector: string): FakeElement | null {
303
+ return this.matches(selector) ? this : null
304
+ }
305
+
306
+ // Only compound tag and attribute selectors, which is all the paths under test use.
307
+ matches(selector: string): boolean {
308
+ const m = selector.match(/^(\w+)?((?:\[[^\]]+\])*)(?::not\((\w+)\))?$/)
309
+ if (!m) return false
310
+ const [, tag, attrPart, notTag] = m
311
+ if (tag && tag.toUpperCase() !== this.tagName) return false
312
+ if (notTag && notTag.toUpperCase() === this.tagName) return false
313
+ for (const [, name, value] of (attrPart ?? '').matchAll(/\[([\w-]+)(?:="([^"]*)")?\]/g)) {
314
+ if (name === undefined || !this.attrs.has(name)) return false
315
+ if (value !== undefined && this.attrs.get(name) !== value) return false
316
+ }
317
+ return true
318
+ }
319
+ }
320
+
321
+ type Page = {
322
+ checkbox: (id: string) => FakeElement
323
+ card: (id: string) => FakeElement
324
+ status: FakeElement
325
+ postSelected: FakeElement
326
+ requests: string[]
327
+ answers: Record<string, FakeResponse>
328
+ focus: () => void
329
+ click: (el: FakeElement) => void
330
+ selectionApplied: (n: number) => Promise<void>
331
+ statusShown: (match: RegExp) => Promise<void>
332
+ }
333
+
334
+ async function openPage(opts: {
335
+ protocol?: string
336
+ persisted?: string[]
337
+ answers: Record<string, FakeResponse>
338
+ }): Promise<Page> {
339
+ const src = await readFile(HELPER, 'utf8')
340
+ const elements: FakeElement[] = []
341
+ for (const id of ['bugs-1', 'perf-2']) {
342
+ elements.push(new FakeElement('div', { 'data-finding-id': id }))
343
+ elements.push(new FakeElement('input', { type: 'checkbox', 'data-finding-id': id }))
344
+ }
345
+ const count = new FakeElement('span', { 'data-role': 'selected-count' })
346
+ const status = new FakeElement('p', { 'data-role': 'post-status' })
347
+ const postSelected = new FakeElement('button', { 'data-action': 'post-selected' })
348
+ elements.push(count, status, postSelected)
349
+
350
+ const requests: string[] = []
351
+ const answers = opts.answers
352
+ let selectionAnswers = 0
353
+ let selectionApplied = 0
354
+ const appliedWaiters: Array<{ n: number; resolve: () => void }> = []
355
+ count.onText = () => {
356
+ selectionApplied = selectionAnswers
357
+ for (const w of appliedWaiters.splice(0)) {
358
+ if (selectionApplied >= w.n) w.resolve()
359
+ else appliedWaiters.push(w)
360
+ }
361
+ }
362
+ const statusWaiters: Array<{ match: RegExp; resolve: () => void }> = []
363
+ status.onText = () => {
364
+ for (const w of statusWaiters.splice(0)) {
365
+ if (w.match.test(status.textContent)) w.resolve()
366
+ else statusWaiters.push(w)
367
+ }
368
+ }
369
+
370
+ const docListeners = new Map<string, Array<(e: unknown) => void>>()
371
+ const winListeners = new Map<string, Array<(e: unknown) => void>>()
372
+ const listen =
373
+ (map: Map<string, Array<(e: unknown) => void>>) => (type: string, fn: (e: unknown) => void) => {
374
+ map.set(type, [...(map.get(type) ?? []), fn])
375
+ }
376
+ const document = {
377
+ readyState: 'complete',
378
+ body: { dataset: { runId: 'pr-1337-test' } },
379
+ documentElement: { dataset: {} as Record<string, string> },
380
+ querySelectorAll: (sel: string) => elements.filter((el) => el.matches(sel)),
381
+ querySelector: (sel: string) => elements.find((el) => el.matches(sel)) ?? null,
382
+ addEventListener: listen(docListeners),
383
+ }
384
+ const window = { addEventListener: listen(winListeners) }
385
+ const store = new Map<string, string>()
386
+ if (opts.persisted) store.set('magpie:selection:pr-1337-test', JSON.stringify(opts.persisted))
387
+ const localStorage = {
388
+ getItem: (k: string) => store.get(k) ?? null,
389
+ setItem: (k: string, v: string) => store.set(k, v),
390
+ }
391
+ const fetch = async (url: string) => {
392
+ requests.push(url)
393
+ const answer = answers[url]
394
+ if (!answer) throw new Error(`no answer for ${url}`)
395
+ if (url === '/selection') selectionAnswers++
396
+ return { ok: answer.ok, status: answer.status, json: async () => answer.body }
397
+ }
398
+ const noTimer = () => 0
399
+ new Function(
400
+ 'document',
401
+ 'window',
402
+ 'location',
403
+ 'localStorage',
404
+ 'fetch',
405
+ 'HTMLElement',
406
+ 'HTMLInputElement',
407
+ 'HTMLButtonElement',
408
+ 'HTMLTextAreaElement',
409
+ 'setInterval',
410
+ 'setTimeout',
411
+ 'clearTimeout',
412
+ src,
413
+ )(
414
+ document,
415
+ window,
416
+ { protocol: opts.protocol ?? 'http:' },
417
+ localStorage,
418
+ fetch,
419
+ FakeElement,
420
+ FakeElement,
421
+ FakeElement,
422
+ class {},
423
+ noTimer,
424
+ noTimer,
425
+ noTimer,
426
+ )
427
+
428
+ const find = (tag: string, id: string) => {
429
+ const el = elements.find((e) => e.tagName === tag && e.getAttribute('data-finding-id') === id)
430
+ if (!el) throw new Error(`no ${tag} for ${id}`)
431
+ return el
432
+ }
433
+ return {
434
+ checkbox: (id) => find('INPUT', id),
435
+ card: (id) => find('DIV', id),
436
+ status,
437
+ postSelected,
438
+ requests,
439
+ answers,
440
+ focus: () => {
441
+ for (const fn of winListeners.get('focus') ?? []) fn({})
442
+ },
443
+ click: (el) => {
444
+ for (const fn of docListeners.get('click') ?? []) fn({ target: el })
445
+ },
446
+ selectionApplied: (n) =>
447
+ new Promise((resolve) => {
448
+ if (selectionApplied >= n) resolve()
449
+ else appliedWaiters.push({ n, resolve })
450
+ }),
451
+ statusShown: (match) =>
452
+ new Promise((resolve) => {
453
+ if (match.test(status.textContent)) resolve()
454
+ else statusWaiters.push({ match, resolve })
455
+ }),
456
+ }
457
+ }
458
+
459
+ const live = { ok: true, status: 200, body: null }
460
+
461
+ function selection(selected: string[], posted: string[] = []): FakeResponse {
462
+ return { ok: true, status: 200, body: { selected, posted } }
463
+ }
464
+
465
+ test('a live page ticks the ids /selection answers and posts no event for them', async () => {
466
+ const page = await openPage({
467
+ answers: { '/heartbeat': live, '/selection': selection(['bugs-1']) },
468
+ })
469
+ await page.selectionApplied(1)
470
+ expect(page.checkbox('bugs-1').checked).toBe(true)
471
+ expect(page.checkbox('perf-2').checked).toBe(false)
472
+ expect(page.requests).not.toContain('/events')
473
+ })
474
+
475
+ test('a focus after the selection changes to empty unticks the finding', async () => {
476
+ const page = await openPage({
477
+ answers: { '/heartbeat': live, '/selection': selection(['bugs-1']) },
478
+ })
479
+ await page.selectionApplied(1)
480
+ page.answers['/selection'] = selection([])
481
+ page.focus()
482
+ await page.selectionApplied(2)
483
+ expect(page.checkbox('bugs-1').checked).toBe(false)
484
+ expect(page.requests).not.toContain('/events')
485
+ })
486
+
487
+ test('a focus answer listing a finding as posted leaves it checked and disabled', async () => {
488
+ const page = await openPage({
489
+ answers: { '/heartbeat': live, '/selection': selection([]) },
490
+ })
491
+ await page.selectionApplied(1)
492
+ page.answers['/selection'] = selection([], ['bugs-1'])
493
+ page.focus()
494
+ await page.selectionApplied(2)
495
+ expect(page.checkbox('bugs-1').checked).toBe(true)
496
+ expect(page.checkbox('bugs-1').disabled).toBe(true)
497
+ })
498
+
499
+ test('a live page takes its ticks from /selection, not from localStorage', async () => {
500
+ const page = await openPage({
501
+ persisted: ['perf-2'],
502
+ answers: { '/heartbeat': live, '/selection': selection([]) },
503
+ })
504
+ await page.selectionApplied(1)
505
+ expect(page.checkbox('perf-2').checked).toBe(false)
506
+ })
507
+
508
+ test('a report opened from file still ticks from localStorage', async () => {
509
+ const page = await openPage({ protocol: 'file:', persisted: ['perf-2'], answers: {} })
510
+ expect(page.checkbox('perf-2').checked).toBe(true)
511
+ expect(page.requests).toEqual([])
512
+ })
513
+
514
+ test('a failed /selection fetch shows the status line', async () => {
515
+ const page = await openPage({
516
+ answers: {
517
+ '/heartbeat': live,
518
+ '/selection': { ok: false, status: 500, body: { error: 'bad events line' } },
519
+ },
520
+ })
521
+ await page.statusShown(/bad events line/)
522
+ expect(page.status.hidden).toBe(false)
523
+ })
524
+
525
+ test('an already-posted result from Post Selected marks the finding posted', async () => {
526
+ const page = await openPage({
527
+ answers: {
528
+ '/heartbeat': live,
529
+ '/selection': selection(['bugs-1']),
530
+ '/api/post-review': {
531
+ ok: true,
532
+ status: 200,
533
+ body: { reviewId: null, comments: [{ id: 'bugs-1', status: 'already-posted' }] },
534
+ },
535
+ },
536
+ })
537
+ await page.selectionApplied(1)
538
+ page.click(page.postSelected)
539
+ await page.statusShown(/already posted/)
540
+ expect(page.card('bugs-1').getAttribute('data-posted')).toBe('true')
541
+ expect(page.checkbox('bugs-1').disabled).toBe(true)
542
+ })
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, expect, test } from 'bun:test'
2
2
  import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
3
3
  import { tmpdir } from 'node:os'
4
4
  import { join } from 'node:path'
5
- import { foldLabels, readDismissed } from '../labels.ts'
5
+ import { foldLabels, foldSelection, readDismissed } from '../labels.ts'
6
6
 
7
7
  test('a posted id is labelled posted with the via from its post log entry', () => {
8
8
  const labels = foldLabels({
@@ -150,3 +150,48 @@ test('readDismissed returns an empty map when state/events does not exist', asyn
150
150
  const dismissed = await readDismissed(runDir)
151
151
  expect(dismissed.size).toBe(0)
152
152
  })
153
+
154
+ test('an id selected and then deselected is not selected', () => {
155
+ const selected = foldSelection([
156
+ { type: 'select', findingId: 'a', timestamp: 1 },
157
+ { type: 'deselect', findingId: 'a', timestamp: 2 },
158
+ ])
159
+ expect([...selected]).toEqual([])
160
+ })
161
+
162
+ test('an id selected again after a deselect is selected', () => {
163
+ const selected = foldSelection([
164
+ { type: 'select', findingId: 'a', timestamp: 1 },
165
+ { type: 'deselect', findingId: 'a', timestamp: 2 },
166
+ { type: 'select', findingId: 'a', timestamp: 3 },
167
+ ])
168
+ expect([...selected]).toEqual(['a'])
169
+ })
170
+
171
+ test('a dismiss after a select unselects the id', () => {
172
+ const selected = foldSelection([
173
+ { type: 'select', findingId: 'a', timestamp: 1 },
174
+ { type: 'dismiss', findingId: 'a', reason: 'wrong', timestamp: 2 },
175
+ ])
176
+ expect([...selected]).toEqual([])
177
+ })
178
+
179
+ test('undismiss leaves the selection alone and a later select still selects', () => {
180
+ const selected = foldSelection([
181
+ { type: 'dismiss', findingId: 'a', reason: 'style', timestamp: 1 },
182
+ { type: 'undismiss', findingId: 'a', timestamp: 2 },
183
+ { type: 'select', findingId: 'a', timestamp: 3 },
184
+ { type: 'select', findingId: 'b', timestamp: 4 },
185
+ { type: 'undismiss', findingId: 'b', timestamp: 5 },
186
+ ])
187
+ expect([...selected].sort()).toEqual(['a', 'b'])
188
+ })
189
+
190
+ test('events without a string findingId are skipped', () => {
191
+ const selected = foldSelection([
192
+ { type: 'select', findingId: 'a', timestamp: 1 },
193
+ { type: 'deselect', findingId: 7, timestamp: 2 },
194
+ { type: 'select', timestamp: 3 },
195
+ ])
196
+ expect([...selected]).toEqual(['a'])
197
+ })