@kw-yeh/vibeflow 4.11.51 → 4.11.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -28,7 +28,7 @@ vibeflow
28
28
  - **Web UI 與終端機 UI 共用同一個看板**:習慣瀏覽器用 Web UI,習慣終端機用 `vibeflow tui`。
29
29
  - **Jira 工作收件匣**:安裝 [Atlassian CLI(Windows)](https://developer.atlassian.com/cloud/acli/guides/install-windows/) 或 [Atlassian CLI(macOS)](https://developer.atlassian.com/cloud/acli/guides/install-macos/),再到設定登入,就能在「收件匣」的 Jira 分頁以固定四欄查看指派給自己的 ticket、選擇抓取範圍、開啟附件,並選擇本機專案建立 Backlog 卡片。
30
30
  - **GitHub Issues 與 PRs**:使用已登入的 `gh` 跨所有相關 repo 顯示 open 項目,即使該 repo 尚未出現在看板;建卡時可選擇本機專案資料夾。
31
- - **內建 skill,可自行調整**:每個人的 Library(設定 → Library)都附帶 `visual-parity`、`pr` 兩個 skill,可以直接編輯或刪除,隨時能還原成 VibeFlow 出貨的版本;沒改過的會跟著 VibeFlow 升級更新。Library 只負責保存,啟動任務時不會載入任何 Library 項目——agent 只收到你在設定填的 system prompt 與卡片內容。`visual-parity` 需要 Python 與 `pip install playwright && playwright install chromium`。
31
+ - **內建 skill,可自行調整**:每個人的 Library(設定 → Library)都附帶 `visual-parity`、`pr`、`pr-watch`、`address-review` 四個 skill,可以直接編輯、停用或刪除,隨時能還原成 VibeFlow 出貨的版本;沒改過的會跟著 VibeFlow 升級更新。啟用的 Library 項目會在啟動任務時投遞給 Claude 與 Codex。`pr-watch`:在卡片裡說「監聽這個 PR」,agent 會在背景等 PR 有新 review comment(交給 `address-review` 處理)或 base branch 前進(rebase)時才動作,PR merged/closed 就停止;需要 `gh` 已登入。`visual-parity` 需要 Python 與 `pip install playwright && playwright install chromium`。
32
32
  - **也能用指令操作**:`vibeflow task create` 不開 UI 直接建卡;agent 自己也能在看板上建立後續的卡片。
33
33
 
34
34
  ---
@@ -0,0 +1,121 @@
1
+ ---
2
+ name: address-review
3
+ description: Read the unanswered review comments on the current branch's GitHub PR, sort them into a change plan, apply the changes, commit and push, and reply to every comment handled (the commit for a fix, the reason for a no-change). Use when the user says "address review", "handle the review comments", "look at the PR review", "review comments", "看 review", "整理 review", "處理 review comment", or when pr-watch reports new comments.
4
+ ---
5
+
6
+ # Address PR review
7
+
8
+ Talk to the user in their language. Write PR replies in the language the reviewer used,
9
+ keeping code, identifiers, paths and SHAs verbatim.
10
+
11
+ Every GitHub call goes through the bundled script; do not call `gh` for these steps yourself.
12
+ `<skill>` below is this skill's directory (the folder holding this file):
13
+
14
+ ```bash
15
+ node "<skill>/scripts/review.mjs" fetch [PR] # unanswered items only
16
+ node "<skill>/scripts/review.mjs" commit [PR] # bullets on stdin → commit + push, prints short SHA
17
+ node "<skill>/scripts/review.mjs" reply [PR] # JSON array on stdin → replies
18
+ ```
19
+
20
+ `PR` is `36` or `#36`; omit it for the current branch's PR. A non-zero exit from `fetch`
21
+ (no PR, `gh` not signed in) is blocking: tell the user and stop.
22
+
23
+ ## When to stop for the user
24
+
25
+ Exactly one possible stop, step 4. Whether it happens:
26
+
27
+ | Situation | Step 4 |
28
+ | --- | --- |
29
+ | `VIBEFLOW_AUTO_MODE` is `1` | No stop. Apply the plan; items needing discussion are left unanswered and listed in the report. |
30
+ | Anything else (`0`, unset, invoked by hand) | Show the plan and wait for a yes. |
31
+
32
+ Everything else (fetch, reading code, commit, push, replies) runs without asking.
33
+
34
+ ## 1. Fetch
35
+
36
+ Run `fetch`. It lists only what nobody has answered: review summaries, inline comments
37
+ in unresolved threads with no marked reply after them, and conversation comments
38
+ (PR-level, including reports bots and CI workflows post). Resolved threads and this
39
+ skill's own earlier replies are already filtered out.
40
+
41
+ If it prints `NOTHING PENDING`, say so and stop.
42
+
43
+ Note each item's id: `id=` (inline), `issue-id=` (conversation), `review-id=` (summary).
44
+
45
+ ## 2. Read the code
46
+
47
+ The diff hunk under each inline comment is usually enough. Read the file around the line
48
+ only when it is not.
49
+
50
+ ## 3. Classify
51
+
52
+ | Class | Meaning | Action |
53
+ | --- | --- | --- |
54
+ | Must fix | real bug, security, logic or performance problem | change it, reply with the commit |
55
+ | Adopt | sound improvement (readability, naming, structure) | change it, reply with the commit |
56
+ | No change | misreads the intent, does not apply here, or a style preference against the project's conventions | reply with the reason |
57
+ | Discuss | architecture or trade-off nobody here can decide alone | leave unanswered, report to the user |
58
+
59
+ Judge each comment by its content, never by who wrote it: a bot's report is reviewed like
60
+ a person's. Check the project's own instructions (`AGENTS.md`, `CLAUDE.md`) for conventions.
61
+
62
+ ## 4. Plan
63
+
64
+ ```
65
+ ## PR #<n> review — <total> items: <fix> fix, <adopt> adopt, <no-change> no change, <discuss> discuss
66
+
67
+ ### Fix / adopt
68
+ 1. <path:line> — <summary> (@<reviewer>, id=<id>)
69
+ Change: <what will change>
70
+ Reply: <reply text>
71
+
72
+ ### No change
73
+ 1. <path:line> — <summary> (@<reviewer>, id=<id>)
74
+ Reply: <reason>
75
+
76
+ ### Discuss
77
+ 1. <path:line> — <summary> (@<reviewer>) — <the open question>
78
+ ```
79
+
80
+ If step 4 stops (see the table), ask whether to go ahead; the user may exclude items by
81
+ number. Adjust only what they named, then carry on without asking again.
82
+
83
+ ## 5. Apply, commit, push
84
+
85
+ 1. Edit the files for every fix/adopt item, then `git diff` to check it matches the plan.
86
+ 2. Run the project's affected checks (typecheck, tests) before committing. A failure you
87
+ cannot fix is reported, not committed around.
88
+ 3. Commit and push in one call:
89
+
90
+ ```bash
91
+ printf -- '- <change 1>\n- <change 2>\n' | node "<skill>/scripts/review.mjs" commit <PR>
92
+ ```
93
+
94
+ It prints the short SHA, or `NO CHANGES` when every item was no-change.
95
+
96
+ ## 6. Reply
97
+
98
+ One call, every reply at once:
99
+
100
+ ```bash
101
+ cat <<'JSON' | node "<skill>/scripts/review.mjs" reply <PR>
102
+ [
103
+ {"id": 123, "body": "Fixed in abc1234: <what changed>."},
104
+ {"id": 124, "body": "<why no change>"},
105
+ {"body": "<one answer to the conversation comments / review summaries>"}
106
+ ]
107
+ JSON
108
+ ```
109
+
110
+ - `{"id": …}` replies in an inline thread. Items without `id` become one PR-level comment;
111
+ merge all conversation and summary answers into it.
112
+ - The script appends a hidden marker to every reply. That marker is how the next `fetch`
113
+ (and pr-watch) knows these items are answered, so always reply through the script, and
114
+ post one PR-level reply whenever a round handled any review summary or conversation comment.
115
+ - No thank-you preamble when answering a bot.
116
+
117
+ ## 7. Report
118
+
119
+ Commit SHA and PR link; the items fixed, the items answered with no change, the items left
120
+ for discussion, and anything that failed. Inside a VibeFlow card with `VIBEFLOW_MASTER_ID`
121
+ set, the same report goes to the master with `task send`.
@@ -0,0 +1,142 @@
1
+ // Shared by the address-review and pr-watch skills; each ships an identical
2
+ // copy because a skill directory must stand on its own. Keep both copies equal
3
+ // (test/builtin-pr-skills.test.mjs fails otherwise).
4
+ import { execFileSync } from 'node:child_process'
5
+
6
+ /** Appended to every reply address-review posts; marks what came before it as handled. */
7
+ export const HANDLED_MARKER = '<!-- vibeflow:address-review -->'
8
+
9
+ /** `gh` argv prefix; VIBEFLOW_GH_CMD (a JSON array) replaces it in tests. */
10
+ function ghCommand() {
11
+ const raw = process.env.VIBEFLOW_GH_CMD
12
+ if (!raw) return ['gh']
13
+ const parsed = JSON.parse(raw)
14
+ if (!Array.isArray(parsed) || parsed.length === 0) throw new Error('VIBEFLOW_GH_CMD must be a JSON array')
15
+ return parsed.map(String)
16
+ }
17
+
18
+ export function gh(args, input) {
19
+ const [cmd, ...prefix] = ghCommand()
20
+ return execFileSync(cmd, [...prefix, ...args], {
21
+ encoding: 'utf8',
22
+ input,
23
+ stdio: ['pipe', 'pipe', 'pipe'],
24
+ maxBuffer: 64 * 1024 * 1024,
25
+ })
26
+ }
27
+
28
+ export function ghJson(args, input) {
29
+ return JSON.parse(gh(args, input))
30
+ }
31
+
32
+ /** `owner/name` of the repository in the current directory. */
33
+ export function repoNwo() {
34
+ return gh(['repo', 'view', '--json', 'nameWithOwner', '-q', '.nameWithOwner']).trim()
35
+ }
36
+
37
+ /** `36`, `#36`, or nothing (the current branch's PR). */
38
+ export function resolvePrNumber(arg) {
39
+ if (arg && /^#?\d+$/.test(arg)) return Number(arg.replace('#', ''))
40
+ if (arg) throw new Error(`not a PR number: ${arg}`)
41
+ return Number(gh(['pr', 'view', '--json', 'number', '-q', '.number']).trim())
42
+ }
43
+
44
+ const PR_QUERY = `query($owner:String!,$repo:String!,$number:Int!){
45
+ repository(owner:$owner,name:$repo){
46
+ pullRequest(number:$number){
47
+ number title state merged headRefName headRefOid baseRefName
48
+ isCrossRepository
49
+ reviews(last:50){nodes{databaseId author{login} state body createdAt}}
50
+ comments(last:100){nodes{databaseId author{login} body createdAt}}
51
+ reviewThreads(last:100){nodes{
52
+ isResolved
53
+ comments(last:50){nodes{databaseId author{login} body path line diffHunk createdAt}}
54
+ }}
55
+ }
56
+ }
57
+ }`
58
+
59
+ const COMPARE_QUERY = `query($owner:String!,$repo:String!,$base:String!,$head:String!){
60
+ repository(owner:$owner,name:$repo){
61
+ ref(qualifiedName:$base){ target{oid} compare(headRef:$head){ behindBy } }
62
+ }
63
+ }`
64
+
65
+ /** One GraphQL call: the PR with its reviews, conversation and review threads. */
66
+ export function fetchPr(nwo, number) {
67
+ const [owner, repo] = nwo.split('/')
68
+ const data = ghJson([
69
+ 'api', 'graphql',
70
+ '-f', `query=${PR_QUERY}`,
71
+ '-F', `owner=${owner}`, '-F', `repo=${repo}`, '-F', `number=${number}`,
72
+ ])
73
+ const pr = data?.data?.repository?.pullRequest
74
+ if (!pr) throw new Error(`PR #${number} not found in ${nwo}`)
75
+ return pr
76
+ }
77
+
78
+ /**
79
+ * Where the base branch is and how many of its commits the PR head lacks.
80
+ * Null for a PR from a fork, whose head branch this repository cannot name.
81
+ */
82
+ export function fetchBaseStatus(nwo, pr) {
83
+ if (pr.isCrossRepository) return null
84
+ const [owner, repo] = nwo.split('/')
85
+ const data = ghJson([
86
+ 'api', 'graphql',
87
+ '-f', `query=${COMPARE_QUERY}`,
88
+ '-F', `owner=${owner}`, '-F', `repo=${repo}`,
89
+ '-f', `base=refs/heads/${pr.baseRefName}`, '-f', `head=refs/heads/${pr.headRefName}`,
90
+ ])
91
+ const ref = data?.data?.repository?.ref
92
+ if (!ref?.target?.oid || !ref.compare) return null
93
+ return { oid: ref.target.oid, behindBy: ref.compare.behindBy }
94
+ }
95
+
96
+ const nodes = (conn) => conn?.nodes ?? []
97
+ const isMarked = (c) => (c.body ?? '').includes(HANDLED_MARKER)
98
+ const login = (c) => c.author?.login ?? 'ghost'
99
+
100
+ /**
101
+ * The review items nobody has answered yet. An inline comment counts as
102
+ * answered once a marked reply follows it in its thread; a review summary or
103
+ * conversation comment once any marked reply was posted after it, since every
104
+ * address-review round answers everything pending at once. Resolved threads,
105
+ * empty bodies and the marked replies themselves never count.
106
+ */
107
+ export function pendingItems(pr) {
108
+ const items = []
109
+ let lastMarked = ''
110
+ for (const c of nodes(pr.comments)) if (isMarked(c) && c.createdAt > lastMarked) lastMarked = c.createdAt
111
+ for (const thread of nodes(pr.reviewThreads)) {
112
+ for (const c of nodes(thread.comments)) if (isMarked(c) && c.createdAt > lastMarked) lastMarked = c.createdAt
113
+ }
114
+
115
+ for (const r of nodes(pr.reviews)) {
116
+ if (!(r.body ?? '').trim() || isMarked(r) || r.createdAt <= lastMarked) continue
117
+ items.push({ kind: 'review', id: r.databaseId, author: login(r), state: r.state, body: r.body, createdAt: r.createdAt })
118
+ }
119
+ for (const thread of nodes(pr.reviewThreads)) {
120
+ if (thread.isResolved) continue
121
+ const comments = nodes(thread.comments)
122
+ let start = 0
123
+ comments.forEach((c, i) => { if (isMarked(c)) start = i + 1 })
124
+ for (const c of comments.slice(start)) {
125
+ if (!(c.body ?? '').trim()) continue
126
+ items.push({
127
+ kind: 'inline', id: c.databaseId, author: login(c), body: c.body,
128
+ path: c.path, line: c.line, diffHunk: c.diffHunk, createdAt: c.createdAt,
129
+ })
130
+ }
131
+ }
132
+ for (const c of nodes(pr.comments)) {
133
+ if (!(c.body ?? '').trim() || isMarked(c) || c.createdAt <= lastMarked) continue
134
+ items.push({ kind: 'conversation', id: c.databaseId, author: login(c), body: c.body, createdAt: c.createdAt })
135
+ }
136
+ return items
137
+ }
138
+
139
+ /** A stable key per item, since review, inline and conversation ids are separate sequences. */
140
+ export function itemKey(item) {
141
+ return `${item.kind}:${item.id}`
142
+ }
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env node
2
+ // address-review's only interface to GitHub. Three subcommands:
3
+ // fetch [PR] compact list of the review items nobody has answered yet
4
+ // commit [PR] stage everything, commit with the bullets on stdin, push; prints the short SHA
5
+ // reply [PR] post the replies in the JSON array on stdin, each marked as handled
6
+ // PR is `36`, `#36`, or omitted for the current branch's PR.
7
+ import { execFileSync } from 'node:child_process'
8
+ import fs from 'node:fs'
9
+ import { pathToFileURL } from 'node:url'
10
+ import {
11
+ HANDLED_MARKER,
12
+ fetchPr,
13
+ gh,
14
+ pendingItems,
15
+ repoNwo,
16
+ resolvePrNumber,
17
+ } from './pr-lib.mjs'
18
+
19
+ const SUMMARY_LIMIT = 400
20
+
21
+ function oneLine(text, limit) {
22
+ const flat = text.replace(/\s*\n\s*/g, ' ').trim()
23
+ return flat.length > limit ? `${flat.slice(0, limit)} …(truncated)` : flat
24
+ }
25
+
26
+ export function formatPending(pr, items) {
27
+ const out = [`## PR #${pr.number} — ${pr.title} [${pr.state} ${pr.headRefName} → ${pr.baseRefName}]`, '']
28
+ const reviews = items.filter((i) => i.kind === 'review')
29
+ const inline = items.filter((i) => i.kind === 'inline')
30
+ const conversation = items.filter((i) => i.kind === 'conversation')
31
+
32
+ if (reviews.length) {
33
+ out.push('### Review summaries')
34
+ for (const r of reviews) out.push(`[review-id=${r.id}] @${r.author} (${r.state}): ${oneLine(r.body, SUMMARY_LIMIT)}`)
35
+ out.push('')
36
+ }
37
+ out.push(`### Unanswered inline comments (${inline.length})`, '')
38
+ if (!inline.length) out.push('_(none)_', '')
39
+ for (const c of inline) {
40
+ out.push(`[id=${c.id}] ${c.path}:${c.line ?? '?'} @${c.author}`, '```diff', c.diffHunk ?? '', '```', c.body, '')
41
+ }
42
+ out.push(`### Unanswered conversation comments (${conversation.length})`, '')
43
+ if (!conversation.length) out.push('_(none)_', '')
44
+ for (const c of conversation) out.push(`[issue-id=${c.id}] @${c.author}`, c.body, '')
45
+ if (!items.length) out.push('NOTHING PENDING')
46
+ return out.join('\n')
47
+ }
48
+
49
+ function readStdin() {
50
+ return fs.readFileSync(0, 'utf8')
51
+ }
52
+
53
+ function git(args) {
54
+ return execFileSync('git', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'] })
55
+ }
56
+
57
+ function commit(number, bullets) {
58
+ if (!bullets.trim()) throw new Error('commit needs the summary bullets on stdin')
59
+ git(['add', '-A'])
60
+ try {
61
+ execFileSync('git', ['diff', '--cached', '--quiet'], { stdio: 'ignore' })
62
+ return 'NO CHANGES'
63
+ } catch {
64
+ // staged changes present
65
+ }
66
+ git(['commit', '-q', '-m', `Address PR #${number} review comments\n\n${bullets.trim()}\n`])
67
+ execFileSync('git', ['push', '--quiet'], { stdio: ['ignore', 'inherit', 'inherit'] })
68
+ return git(['rev-parse', '--short=7', 'HEAD']).trim()
69
+ }
70
+
71
+ function reply(nwo, number, json) {
72
+ let rows
73
+ try {
74
+ rows = JSON.parse(json)
75
+ } catch {
76
+ throw new Error('reply needs a JSON array on stdin')
77
+ }
78
+ if (!Array.isArray(rows)) throw new Error('reply needs a JSON array on stdin')
79
+ let failed = 0
80
+ for (const row of rows) {
81
+ const body = `${String(row.body ?? '').trim()}\n\n${HANDLED_MARKER}`
82
+ const inline = row.id !== undefined && row.id !== null
83
+ const args = inline
84
+ ? ['api', `repos/${nwo}/pulls/${number}/comments`, '--method', 'POST', '-f', `body=${body}`, '-F', `in_reply_to=${row.id}`]
85
+ : ['api', `repos/${nwo}/issues/${number}/comments`, '--method', 'POST', '-f', `body=${body}`]
86
+ try {
87
+ gh([...args, '--jq', '.id'])
88
+ console.log(inline ? `ok replied to review comment ${row.id}` : 'ok posted PR conversation comment')
89
+ } catch (err) {
90
+ failed += 1
91
+ console.error(inline ? `FAILED reply to review comment ${row.id}` : 'FAILED to post PR conversation comment')
92
+ console.error(String(err.stderr || err.message).trim())
93
+ }
94
+ }
95
+ return failed
96
+ }
97
+
98
+ function main(argv) {
99
+ const [command, prArg] = argv
100
+ if (!['fetch', 'commit', 'reply'].includes(command)) {
101
+ console.error('usage: review.mjs fetch|commit|reply [PR]')
102
+ return 2
103
+ }
104
+ const number = resolvePrNumber(prArg)
105
+ if (command === 'commit') {
106
+ console.log(commit(number, readStdin()))
107
+ return 0
108
+ }
109
+ const nwo = repoNwo()
110
+ if (command === 'reply') return reply(nwo, number, readStdin()) ? 1 : 0
111
+ const pr = fetchPr(nwo, number)
112
+ console.log(formatPending(pr, pendingItems(pr)))
113
+ return 0
114
+ }
115
+
116
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
117
+ try {
118
+ process.exitCode = main(process.argv.slice(2))
119
+ } catch (err) {
120
+ console.error(`ERROR: ${String(err.stderr || err.message).trim()}`)
121
+ process.exitCode = 2
122
+ }
123
+ }
@@ -0,0 +1,77 @@
1
+ ---
2
+ name: pr-watch
3
+ description: Watch a GitHub pull request until it is merged or closed, waking only when it needs work — new review comments are handled with address-review, a base branch that moved ahead is rebased onto. Use when the user asks to watch, monitor, follow or babysit a PR, or says "監聽 PR", "盯著 PR", "看著這個 PR", "PR 有 comment 就處理", "watch the PR", "keep an eye on the PR".
4
+ ---
5
+
6
+ # Watch a PR
7
+
8
+ Talk to the user in their language.
9
+
10
+ The waiting is done by a script, not by you: it polls GitHub quietly and exits with one
11
+ JSON line only when there is something to do. Never poll GitHub yourself in a loop, and
12
+ never read the script's output while it runs — wait for it to exit.
13
+
14
+ `<skill>` below is this skill's directory (the folder holding this file).
15
+
16
+ ## 1. Start
17
+
18
+ Find the PR: the number the user gave, else the current branch's (`gh pr view --json number -q .number`).
19
+ No PR → tell the user and stop.
20
+
21
+ Launch the watcher:
22
+
23
+ ```bash
24
+ node "<skill>/scripts/pr-watch.mjs" --pr <n>
25
+ ```
26
+
27
+ - **Claude Code**: run it with `run_in_background: true`. You are woken when it exits; it
28
+ costs nothing while it waits. Tell the user in one line that the PR is being watched.
29
+ - **Codex** (no background notification): run it in the foreground with
30
+ `--max-wait 1500` and a command timeout above that; on `timeout`, run it again.
31
+
32
+ Options: `--interval <sec>` (default 60, min 20); `--since-now` to skip items that are
33
+ already there when watching starts (by default they are reported on the first poll, so a
34
+ backlog gets handled first); `--state <file>` (default: under `$VIBEFLOW_SCRATCH_DIR`, or
35
+ the system temp dir).
36
+
37
+ ## 2. On exit
38
+
39
+ | Exit | Event | Do |
40
+ | --- | --- | --- |
41
+ | 10 | `comments` | Run the **address-review** skill for this PR. |
42
+ | 11 | `base` | Rebase (step 3). |
43
+ | 0 | `merged` / `closed` | Report and stop. Do not restart. |
44
+ | 3 | `timeout` | Restart the watcher as it was. |
45
+ | 2 | `error` | Report the message and stop. |
46
+
47
+ After handling `comments` or `base`, restart the watcher with the same options unless
48
+ the handling stopped (see below). The watcher remembers what it already reported, so a
49
+ restart never re-reports the same comments or the same base commit.
50
+
51
+ Whether to stop for the user follows `VIBEFLOW_AUTO_MODE`:
52
+
53
+ - `1` → handle the event end to end (address-review applies and replies on its own; the
54
+ rebase is pushed), then restart.
55
+ - anything else → address-review shows its plan and waits; for a rebase, show what will be
56
+ rebased and wait. Watching is paused meanwhile; restart it once the user's answer is
57
+ carried out. Say so when you pause.
58
+
59
+ ## 3. Rebase
60
+
61
+ ```bash
62
+ git status --porcelain # must be empty; otherwise stop and tell the user
63
+ git fetch origin <base>
64
+ git rebase origin/<base>
65
+ ```
66
+
67
+ - Conflict → `git rebase --abort`, report the conflicting files, and **stop watching**,
68
+ whatever the auto mode. Never resolve conflicts unattended.
69
+ - Clean → run the project's affected checks (typecheck, tests). A failure stops watching
70
+ and is reported; nothing is pushed.
71
+ - Passed → `git push --force-with-lease`, then restart the watcher.
72
+
73
+ ## 4. Report
74
+
75
+ After every event: one or two lines on what happened (comments answered, rebased onto
76
+ which commit, or why watching stopped). Inside a VibeFlow card with `VIBEFLOW_MASTER_ID`
77
+ set, send the same lines to the master with `task send`.
@@ -0,0 +1,142 @@
1
+ // Shared by the address-review and pr-watch skills; each ships an identical
2
+ // copy because a skill directory must stand on its own. Keep both copies equal
3
+ // (test/builtin-pr-skills.test.mjs fails otherwise).
4
+ import { execFileSync } from 'node:child_process'
5
+
6
+ /** Appended to every reply address-review posts; marks what came before it as handled. */
7
+ export const HANDLED_MARKER = '<!-- vibeflow:address-review -->'
8
+
9
+ /** `gh` argv prefix; VIBEFLOW_GH_CMD (a JSON array) replaces it in tests. */
10
+ function ghCommand() {
11
+ const raw = process.env.VIBEFLOW_GH_CMD
12
+ if (!raw) return ['gh']
13
+ const parsed = JSON.parse(raw)
14
+ if (!Array.isArray(parsed) || parsed.length === 0) throw new Error('VIBEFLOW_GH_CMD must be a JSON array')
15
+ return parsed.map(String)
16
+ }
17
+
18
+ export function gh(args, input) {
19
+ const [cmd, ...prefix] = ghCommand()
20
+ return execFileSync(cmd, [...prefix, ...args], {
21
+ encoding: 'utf8',
22
+ input,
23
+ stdio: ['pipe', 'pipe', 'pipe'],
24
+ maxBuffer: 64 * 1024 * 1024,
25
+ })
26
+ }
27
+
28
+ export function ghJson(args, input) {
29
+ return JSON.parse(gh(args, input))
30
+ }
31
+
32
+ /** `owner/name` of the repository in the current directory. */
33
+ export function repoNwo() {
34
+ return gh(['repo', 'view', '--json', 'nameWithOwner', '-q', '.nameWithOwner']).trim()
35
+ }
36
+
37
+ /** `36`, `#36`, or nothing (the current branch's PR). */
38
+ export function resolvePrNumber(arg) {
39
+ if (arg && /^#?\d+$/.test(arg)) return Number(arg.replace('#', ''))
40
+ if (arg) throw new Error(`not a PR number: ${arg}`)
41
+ return Number(gh(['pr', 'view', '--json', 'number', '-q', '.number']).trim())
42
+ }
43
+
44
+ const PR_QUERY = `query($owner:String!,$repo:String!,$number:Int!){
45
+ repository(owner:$owner,name:$repo){
46
+ pullRequest(number:$number){
47
+ number title state merged headRefName headRefOid baseRefName
48
+ isCrossRepository
49
+ reviews(last:50){nodes{databaseId author{login} state body createdAt}}
50
+ comments(last:100){nodes{databaseId author{login} body createdAt}}
51
+ reviewThreads(last:100){nodes{
52
+ isResolved
53
+ comments(last:50){nodes{databaseId author{login} body path line diffHunk createdAt}}
54
+ }}
55
+ }
56
+ }
57
+ }`
58
+
59
+ const COMPARE_QUERY = `query($owner:String!,$repo:String!,$base:String!,$head:String!){
60
+ repository(owner:$owner,name:$repo){
61
+ ref(qualifiedName:$base){ target{oid} compare(headRef:$head){ behindBy } }
62
+ }
63
+ }`
64
+
65
+ /** One GraphQL call: the PR with its reviews, conversation and review threads. */
66
+ export function fetchPr(nwo, number) {
67
+ const [owner, repo] = nwo.split('/')
68
+ const data = ghJson([
69
+ 'api', 'graphql',
70
+ '-f', `query=${PR_QUERY}`,
71
+ '-F', `owner=${owner}`, '-F', `repo=${repo}`, '-F', `number=${number}`,
72
+ ])
73
+ const pr = data?.data?.repository?.pullRequest
74
+ if (!pr) throw new Error(`PR #${number} not found in ${nwo}`)
75
+ return pr
76
+ }
77
+
78
+ /**
79
+ * Where the base branch is and how many of its commits the PR head lacks.
80
+ * Null for a PR from a fork, whose head branch this repository cannot name.
81
+ */
82
+ export function fetchBaseStatus(nwo, pr) {
83
+ if (pr.isCrossRepository) return null
84
+ const [owner, repo] = nwo.split('/')
85
+ const data = ghJson([
86
+ 'api', 'graphql',
87
+ '-f', `query=${COMPARE_QUERY}`,
88
+ '-F', `owner=${owner}`, '-F', `repo=${repo}`,
89
+ '-f', `base=refs/heads/${pr.baseRefName}`, '-f', `head=refs/heads/${pr.headRefName}`,
90
+ ])
91
+ const ref = data?.data?.repository?.ref
92
+ if (!ref?.target?.oid || !ref.compare) return null
93
+ return { oid: ref.target.oid, behindBy: ref.compare.behindBy }
94
+ }
95
+
96
+ const nodes = (conn) => conn?.nodes ?? []
97
+ const isMarked = (c) => (c.body ?? '').includes(HANDLED_MARKER)
98
+ const login = (c) => c.author?.login ?? 'ghost'
99
+
100
+ /**
101
+ * The review items nobody has answered yet. An inline comment counts as
102
+ * answered once a marked reply follows it in its thread; a review summary or
103
+ * conversation comment once any marked reply was posted after it, since every
104
+ * address-review round answers everything pending at once. Resolved threads,
105
+ * empty bodies and the marked replies themselves never count.
106
+ */
107
+ export function pendingItems(pr) {
108
+ const items = []
109
+ let lastMarked = ''
110
+ for (const c of nodes(pr.comments)) if (isMarked(c) && c.createdAt > lastMarked) lastMarked = c.createdAt
111
+ for (const thread of nodes(pr.reviewThreads)) {
112
+ for (const c of nodes(thread.comments)) if (isMarked(c) && c.createdAt > lastMarked) lastMarked = c.createdAt
113
+ }
114
+
115
+ for (const r of nodes(pr.reviews)) {
116
+ if (!(r.body ?? '').trim() || isMarked(r) || r.createdAt <= lastMarked) continue
117
+ items.push({ kind: 'review', id: r.databaseId, author: login(r), state: r.state, body: r.body, createdAt: r.createdAt })
118
+ }
119
+ for (const thread of nodes(pr.reviewThreads)) {
120
+ if (thread.isResolved) continue
121
+ const comments = nodes(thread.comments)
122
+ let start = 0
123
+ comments.forEach((c, i) => { if (isMarked(c)) start = i + 1 })
124
+ for (const c of comments.slice(start)) {
125
+ if (!(c.body ?? '').trim()) continue
126
+ items.push({
127
+ kind: 'inline', id: c.databaseId, author: login(c), body: c.body,
128
+ path: c.path, line: c.line, diffHunk: c.diffHunk, createdAt: c.createdAt,
129
+ })
130
+ }
131
+ }
132
+ for (const c of nodes(pr.comments)) {
133
+ if (!(c.body ?? '').trim() || isMarked(c) || c.createdAt <= lastMarked) continue
134
+ items.push({ kind: 'conversation', id: c.databaseId, author: login(c), body: c.body, createdAt: c.createdAt })
135
+ }
136
+ return items
137
+ }
138
+
139
+ /** A stable key per item, since review, inline and conversation ids are separate sequences. */
140
+ export function itemKey(item) {
141
+ return `${item.kind}:${item.id}`
142
+ }