hermes-pilot 0.0.0-stage → 0.2.2
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/LICENSE +21 -0
- package/README.ja.md +419 -0
- package/README.md +428 -2
- package/__init__.py +15 -0
- package/apps/bridge/src/api-errors.js +165 -0
- package/apps/bridge/src/architect.js +1298 -0
- package/apps/bridge/src/auth.js +202 -0
- package/apps/bridge/src/capabilities.js +256 -0
- package/apps/bridge/src/capture.js +145 -0
- package/apps/bridge/src/chat-profile.js +95 -0
- package/apps/bridge/src/config.js +73 -0
- package/apps/bridge/src/discord.js +89 -0
- package/apps/bridge/src/gitinfo.js +211 -0
- package/apps/bridge/src/hermes.js +97 -0
- package/apps/bridge/src/inbox.js +347 -0
- package/apps/bridge/src/kanban.js +361 -0
- package/apps/bridge/src/lang.js +60 -0
- package/apps/bridge/src/live.js +285 -0
- package/apps/bridge/src/memos.js +150 -0
- package/apps/bridge/src/ops.js +201 -0
- package/apps/bridge/src/pair-codes.js +125 -0
- package/apps/bridge/src/pipeline-optimizer.js +513 -0
- package/apps/bridge/src/pipeline-watcher.js +1022 -0
- package/apps/bridge/src/qr.js +808 -0
- package/apps/bridge/src/repos.js +544 -0
- package/apps/bridge/src/review-watcher.js +271 -0
- package/apps/bridge/src/review.js +1749 -0
- package/apps/bridge/src/search.js +162 -0
- package/apps/bridge/src/server.js +1745 -0
- package/apps/bridge/src/snippets.js +373 -0
- package/apps/bridge/src/specs.js +806 -0
- package/apps/bridge/src/tail.js +28 -0
- package/apps/bridge/src/telemetry.js +667 -0
- package/apps/bridge/src/term-snippets.js +228 -0
- package/apps/bridge/src/transcript.js +231 -0
- package/apps/bridge/src/usage.js +294 -0
- package/apps/bridge/src/workerFeed.js +72 -0
- package/apps/dashboard/index.js +2014 -0
- package/apps/dashboard/manifest.json +14 -0
- package/apps/dashboard/pilot_dashboard.py +1466 -0
- package/apps/dashboard/plugin_api.py +237 -0
- package/apps/dashboard/plugin_init.py +15 -0
- package/apps/dashboard/style.css +928 -0
- package/apps/web/dist/assets/TermPane-DYP7pi_n.css +32 -0
- package/apps/web/dist/assets/TermPane-q4f5Zu0I.js +12 -0
- package/apps/web/dist/assets/index-BzUof8lw.js +94 -0
- package/apps/web/dist/assets/index-DwZdbPU7.css +1 -0
- package/apps/web/dist/favicon.ico +0 -0
- package/apps/web/dist/icon-180-v6.png +0 -0
- package/apps/web/dist/icon-192-v6.png +0 -0
- package/apps/web/dist/icon-512-v6.png +0 -0
- package/apps/web/dist/icon-maskable-192-v6.png +0 -0
- package/apps/web/dist/icon-maskable-512-v6.png +0 -0
- package/apps/web/dist/icon-v6.svg +15 -0
- package/apps/web/dist/index.html +21 -0
- package/apps/web/dist/manifest.webmanifest +49 -0
- package/apps/web/dist/sw.js +69 -0
- package/bin/hermes-pilot.mjs +964 -0
- package/dashboard/dist/index.js +2014 -0
- package/dashboard/dist/style.css +928 -0
- package/dashboard/manifest.json +14 -0
- package/dashboard/pilot_dashboard.py +1466 -0
- package/dashboard/plugin_api.py +237 -0
- package/package.json +75 -4
- package/plugin.json +70 -0
- package/plugin.yaml +4 -0
- package/scripts/deploy.mjs +58 -0
- package/scripts/migrate-to-hermes-pilot.mjs +472 -0
- package/scripts/postinstall.mjs +32 -0
- package/scripts/sync-dashboard.mjs +98 -0
- package/skills/annotation/SKILL.md +138 -0
- package/skills/quick-review/SKILL.md +200 -0
- package/skills/quick-review/assets/sheet-template.html +175 -0
- package/skills/spec-architect/SKILL.md +226 -0
|
@@ -0,0 +1,1749 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import os from 'node:os'
|
|
4
|
+
import crypto from 'node:crypto'
|
|
5
|
+
import { execFile } from 'node:child_process'
|
|
6
|
+
import { DatabaseSync } from 'node:sqlite'
|
|
7
|
+
import { readTailText } from './tail.js'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* レビュー(review)パイプラインのブリッジ側。
|
|
11
|
+
*
|
|
12
|
+
* 契約は `docs/REVIEW-VIEW.md` と `docs/SPEC-PUBLIC-PLUGIN.md` §4。カンバン(board `mobile`)が唯一の真実で、
|
|
13
|
+
* シートはボードの default_workdir 配下に置かれる。ここは**読み取り + 回答の書き込み**だけを行い、
|
|
14
|
+
* 実装判断はしない(生成も反映も worker の仕事)。
|
|
15
|
+
*
|
|
16
|
+
* パスの解決規則:
|
|
17
|
+
* - シートの場所はタスク本文の `[review] ... sheet=...` 行から取る(リクエストのパスは使わない)
|
|
18
|
+
* - 解決後 realpath が workdir 配下でなければ拒否する(allowlist)
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* タスク本文の機械可読行(SPEC §4.1)。
|
|
23
|
+
*
|
|
24
|
+
* 正は `[review]`。移行前のボード(`kanban.db` の `[akapen]` 置換が済んでいない)でも
|
|
25
|
+
* レビューが消えないよう、旧タグも読むだけ受ける(書き込み側は常に `[review]`)。
|
|
26
|
+
*/
|
|
27
|
+
const LINE_RE = /^\[(?:review|akapen)\]\s+(.+)$/m
|
|
28
|
+
const LABEL_RE = /^[a-z0-9][a-z0-9._-]{0,40}$/i
|
|
29
|
+
|
|
30
|
+
/** 旧名(`【赤ペン回答】` / `全体への赤ペン:`)も移行前のシート資産のために受ける。 */
|
|
31
|
+
const REPLY_HEAD_RE = /^【(?:レビュー|赤ペン)回答】/
|
|
32
|
+
const GLOBAL_LABEL_RE = /^(?:全体への(?:レビュー|赤ペン)|Overall Note):\s*(.*)$/
|
|
33
|
+
|
|
34
|
+
/** タスク本文から `[review] label=... round=... mode=... sheet=...` を取り出す。 */
|
|
35
|
+
export function parseReviewLine(body) {
|
|
36
|
+
const m = LINE_RE.exec(String(body || ''))
|
|
37
|
+
if (!m) return null
|
|
38
|
+
const out = {}
|
|
39
|
+
for (const token of m[1].trim().split(/\s+/)) {
|
|
40
|
+
const idx = token.indexOf('=')
|
|
41
|
+
if (idx > 0) out[token.slice(0, idx)] = token.slice(idx + 1)
|
|
42
|
+
}
|
|
43
|
+
// シートは `sheet=` が正だが、`image=<....html>` と書かれた実例がある(NO_SHEET になった)。
|
|
44
|
+
// html を指しているときだけ別名として受ける。
|
|
45
|
+
if (!out.sheet && out.image && /\.html?$/i.test(out.image)) out.sheet = out.image
|
|
46
|
+
if (!out.sheet && !out.label) return null
|
|
47
|
+
if (out.sheet && !isSafeRel(out.sheet)) return null
|
|
48
|
+
return out
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 相対パスとして妥当か(親ディレクトリ・絶対パスを弾く)。 */
|
|
52
|
+
export function isSafeRel(rel) {
|
|
53
|
+
const s = String(rel || '')
|
|
54
|
+
if (!s || s.startsWith('/') || s.includes('..') || s.includes('\0')) return false
|
|
55
|
+
return /^[A-Za-z0-9._/-]+$/.test(s)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* シートパスから「設問 JSON」と「回答 JSON」のパスを作る。
|
|
60
|
+
*
|
|
61
|
+
* `mode=sheet`(.html シート)と `mode=standard`(.json シート)の両方で、
|
|
62
|
+
* 回答が**設問ファイルを上書きしない**ようにする。以前は `.html` だけを置換して
|
|
63
|
+
* いたため、`.json` シートでは `replace` が効かず、回答が設問 JSON にそのまま
|
|
64
|
+
* 書き込まれて設問構造が失われていた(実測: p5-fasttrack-01-1.json が回答文に置換)。
|
|
65
|
+
* @param {string} sheetRel `sheets/<label>-<round>.html|.json`
|
|
66
|
+
* @returns {{dataRel: string, answerRel: string}} 設問と回答の相対パス
|
|
67
|
+
*/
|
|
68
|
+
export function sheetPaths(sheetRel) {
|
|
69
|
+
const rel = String(sheetRel || '')
|
|
70
|
+
const dataRel = rel.replace(/\.html?$/i, '.json')
|
|
71
|
+
const answerRel = dataRel.replace(/\.json$/i, '.answer.json')
|
|
72
|
+
return { dataRel, answerRel }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* 比較用(Before)画像の候補パスを優先順に返す(存在確認はしない純粋関数)。
|
|
77
|
+
*
|
|
78
|
+
* After = いまの下地画像(最新のスクショ)。Before = 前回の赤入れ/前ラウンドの画像。
|
|
79
|
+
* 実測の命名は `<label>-<stamp>-<round>[.<kind>].png`(例 `1385.jpg-202611131208-1.jpg`)で
|
|
80
|
+
* round はほぼ常に 1。比較相手は 3 通りで見つかる:
|
|
81
|
+
* 1. 同名 `.before`(`shots/x-1.before.png` / `x-1.after.png` → `x-1.before.png`)
|
|
82
|
+
* 2. 同じ命名の前ラウンド(末尾の `-<round>` を 1 つ戻す。round >= 2 のときだけ)
|
|
83
|
+
* 3. 同一 label の別タスク(前回のレビュー)の `.annotated`、無ければその元画像
|
|
84
|
+
*
|
|
85
|
+
* 3 は「前ラウンドのタスクは archived のことが多い」(実測)ので status では絞らない。
|
|
86
|
+
*
|
|
87
|
+
* @param {{image?: string, round?: number, others?: Array<{image: string, round?: number}>}} input
|
|
88
|
+
* `others` は同一 label の他タスクの画像(新しい順)。**このタスク自身は含めない**
|
|
89
|
+
* @returns {string[]} 相対パスの候補(優先順・重複なし)
|
|
90
|
+
*/
|
|
91
|
+
export function compareCandidates({ image, round = 1, others = [] } = {}) {
|
|
92
|
+
const out = []
|
|
93
|
+
const rel = String(image ?? '').trim()
|
|
94
|
+
if (!rel) return out
|
|
95
|
+
const ext = path.extname(rel)
|
|
96
|
+
if (!/\.(png|jpe?g|webp)$/i.test(ext)) return out
|
|
97
|
+
const noExt = rel.slice(0, -ext.length)
|
|
98
|
+
const push = (p) => {
|
|
99
|
+
if (p && p !== rel && !out.includes(p)) out.push(p)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// 1) 同名 .before(いまの画像の 1 つ前を撮ったもの)
|
|
103
|
+
push(`${noExt}.before${ext}`)
|
|
104
|
+
if (/\.after$/i.test(noExt)) push(`${noExt.replace(/\.after$/i, '')}.before${ext}`)
|
|
105
|
+
|
|
106
|
+
// 2) 前ラウンド(`shots/x-2.png` → `shots/x-1.png`)
|
|
107
|
+
const current = Math.max(1, Number(round) || 1)
|
|
108
|
+
const m = /^(.*-)(\d+)$/.exec(noExt.replace(/\.(after|before)$/i, ''))
|
|
109
|
+
if (m && Number(m[2]) >= 2) {
|
|
110
|
+
const prev = `${m[1]}${Number(m[2]) - 1}`
|
|
111
|
+
push(`${prev}${ext}`)
|
|
112
|
+
push(`${prev}.after${ext}`)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// 3) 同一 label の前ラウンドタスク(近い順)。赤入れ済みを優先する
|
|
116
|
+
for (const o of Array.isArray(others) ? others : []) {
|
|
117
|
+
const r = String(o?.image ?? '').trim()
|
|
118
|
+
if (!r) continue
|
|
119
|
+
if (Number(o?.round ?? 1) > current) continue
|
|
120
|
+
const e = path.extname(r)
|
|
121
|
+
const base = r.slice(0, -e.length)
|
|
122
|
+
push(`${base}.annotated${e}`)
|
|
123
|
+
push(r)
|
|
124
|
+
}
|
|
125
|
+
return out
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** 回答の安定ハッシュ(キー順を固定して二重投稿を検出する)。 */
|
|
129
|
+
export function answerHash({ answers = [], global = '', annotations = [] }) {
|
|
130
|
+
const norm = {
|
|
131
|
+
answers: [...answers]
|
|
132
|
+
.map((a) => ({ id: String(a.id ?? ''), choice: a.choice ?? null, note: String(a.note ?? '') }))
|
|
133
|
+
.sort((x, y) => x.id.localeCompare(y.id)),
|
|
134
|
+
global: String(global ?? ''),
|
|
135
|
+
annotations: [...annotations].map((a) => ({ region: a.region ?? null, note: String(a.note ?? '') })),
|
|
136
|
+
}
|
|
137
|
+
return crypto.createHash('sha256').update(JSON.stringify(norm)).digest('hex')
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* 回答テキストを構造化する(シートが直接送ってきた場合に使う)。
|
|
142
|
+
*
|
|
143
|
+
* EN 見出し(`[Review Answer]` / `Overall Note:`)と JA 見出しの両方、および旧
|
|
144
|
+
* `【赤ペン回答】` / `全体への赤ペン:` を受理する(SPEC §4.1)。
|
|
145
|
+
*/
|
|
146
|
+
export function parseReplyText(text) {
|
|
147
|
+
const out = { answers: [], global: '' }
|
|
148
|
+
const lines = String(text || '').split(/\r?\n/)
|
|
149
|
+
let inGlobal = false
|
|
150
|
+
for (const line of lines) {
|
|
151
|
+
if (line.trim() === '---') break
|
|
152
|
+
const q = /^Q(\d+)\.\s*(.*?):\s*(.*)$/.exec(line)
|
|
153
|
+
if (q) {
|
|
154
|
+
const rest = q[3]
|
|
155
|
+
const m = /^(.*?)(?:\s*\/\s*補足:\s*(.*))?$/.exec(rest)
|
|
156
|
+
const choice = (m?.[1] || '').trim()
|
|
157
|
+
out.answers.push({
|
|
158
|
+
id: `q${q[1]}`,
|
|
159
|
+
choice: choice.startsWith('(未選択') ? null : choice,
|
|
160
|
+
note: (m?.[2] || '').trim(),
|
|
161
|
+
})
|
|
162
|
+
inGlobal = false
|
|
163
|
+
continue
|
|
164
|
+
}
|
|
165
|
+
const g = GLOBAL_LABEL_RE.exec(line)
|
|
166
|
+
if (g) {
|
|
167
|
+
out.global = g[1] || ''
|
|
168
|
+
inGlobal = true
|
|
169
|
+
continue
|
|
170
|
+
}
|
|
171
|
+
if (inGlobal) out.global += `\n${line}`
|
|
172
|
+
}
|
|
173
|
+
out.global = out.global.trim()
|
|
174
|
+
return out
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* 回答を貼り戻し用テキストにする(`parseReplyText` と往復できる形)。
|
|
179
|
+
*
|
|
180
|
+
* @param {string} label ラベル
|
|
181
|
+
* @param {Array<{id: string, choice: string|null, note?: string}>} answers 回答
|
|
182
|
+
* @param {string} global 全体コメント
|
|
183
|
+
* @param {Array<{id: string, text?: string}>} [questions] 設問(見出しに使う)
|
|
184
|
+
* @param {'ja'|'en'} [lang] 見出しの言語(既定は日本語)
|
|
185
|
+
*/
|
|
186
|
+
export function toReplyText(label, answers, global, questions = [], lang = 'ja') {
|
|
187
|
+
const title = new Map(questions.map((q) => [String(q.id), String(q.text ?? '')]))
|
|
188
|
+
const en = lang === 'en'
|
|
189
|
+
const lines = [en ? `[Review Answer] ${label}` : `【レビュー回答】${label}`]
|
|
190
|
+
for (const a of answers) {
|
|
191
|
+
const q = title.get(String(a.id)) || String(a.id)
|
|
192
|
+
const choice = a.choice === null || a.choice === undefined ? '(未選択 = お任せ)' : String(a.choice)
|
|
193
|
+
const note = a.note ? ` / 補足: ${String(a.note).replace(/\n/g, ' ')}` : ''
|
|
194
|
+
lines.push(`Q${String(a.id).replace(/^q/i, '')}. ${q}: ${choice}${note}`)
|
|
195
|
+
}
|
|
196
|
+
lines.push(`${en ? 'Overall Note' : '全体へのレビュー'}: ${String(global ?? '').replace(/\r/g, '')}`)
|
|
197
|
+
lines.push('---')
|
|
198
|
+
lines.push('上の回答を反映して作業を続けてください。お任せの項目は推奨案で確定してください。')
|
|
199
|
+
return `${lines.join('\n')}\n`
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* HTML のテキストとして安全な文字列にする(`&` `<` `>` `"` `'`)。
|
|
204
|
+
*
|
|
205
|
+
* JSON シート(外部から来る `title` / 設問文 / 選択肢)を HTML に埋め込む前に必ず通す。
|
|
206
|
+
* `&` を最初に置換しないと二重エスケープになるので順序は固定。
|
|
207
|
+
*
|
|
208
|
+
* @param {unknown} value 任意の値
|
|
209
|
+
* @returns {string} エスケープ済み文字列
|
|
210
|
+
*/
|
|
211
|
+
export function escapeHtmlText(value) {
|
|
212
|
+
return String(value ?? '')
|
|
213
|
+
.replace(/&/g, '&')
|
|
214
|
+
.replace(/</g, '<')
|
|
215
|
+
.replace(/>/g, '>')
|
|
216
|
+
.replace(/"/g, '"')
|
|
217
|
+
.replace(/'/g, ''')
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* 選択肢が推奨か(生成 HTML のバッジ用)。
|
|
222
|
+
*
|
|
223
|
+
* シートを作る側は `recommended: true` を付けるが、既存資産にはラベルに「推奨」と
|
|
224
|
+
* 書いただけのものがある。否定(「非推奨」「not recommended」)を先に落とす。
|
|
225
|
+
*
|
|
226
|
+
* @param {{id?: string, label?: string, detail?: string, recommended?: boolean|string}} option 選択肢
|
|
227
|
+
* @returns {boolean} 推奨か
|
|
228
|
+
*/
|
|
229
|
+
function isRecommendedDataOption(option) {
|
|
230
|
+
if (option?.recommended === true || option?.recommended === 'true') return true
|
|
231
|
+
const text = `${option?.label ?? ''} ${option?.detail ?? ''}`
|
|
232
|
+
if (/非推奨|not\s+recommended/i.test(text)) return false
|
|
233
|
+
return /推奨|recommend/i.test(text)
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* `sheet.json` からスタンドアロンな閲覧用 HTML を組み立てる(SPEC-PILOT-V8 §3.1 / D38)。
|
|
238
|
+
*
|
|
239
|
+
* 手書き `.html` が無いシートでも「シート全体を開く ↗」を成立させるためのフォールバック。
|
|
240
|
+
* 回答はアプリのドロワー(`<StandardForm>`)で行う前提なので、ここは**閲覧ビュー**にして
|
|
241
|
+
* 送信フォームは置かない(`.json` だけで完結する JSON ファースト運用の受け皿)。
|
|
242
|
+
*
|
|
243
|
+
* @param {object} data `sheet.json`(`{title, topic, questions:[{id,text,options}]}`)
|
|
244
|
+
* @param {{label?: string, round?: number|string, target?: string}} [ak] レビュー行の情報
|
|
245
|
+
* @returns {string} `<!DOCTYPE html>` で始まる完全な HTML
|
|
246
|
+
*/
|
|
247
|
+
export function renderSheetHtmlFromData(data, ak = {}) {
|
|
248
|
+
const esc = escapeHtmlText
|
|
249
|
+
const title = esc(data?.title ?? ak?.title ?? ak?.label ?? 'Review')
|
|
250
|
+
const label = esc(ak?.label ?? data?.label ?? '')
|
|
251
|
+
const topic = esc(data?.topic ?? '')
|
|
252
|
+
const round = Number(ak?.round ?? data?.round ?? 1) || 1
|
|
253
|
+
const target = esc(ak?.target ?? '')
|
|
254
|
+
const questions = Array.isArray(data?.questions) ? data.questions : []
|
|
255
|
+
|
|
256
|
+
const sections = questions.map((q, i) => {
|
|
257
|
+
const qtext = esc(q?.text ?? q?.question ?? '')
|
|
258
|
+
const options = Array.isArray(q?.options) ? q.options : []
|
|
259
|
+
const items = options.map((o) => {
|
|
260
|
+
const rec = isRecommendedDataOption(o)
|
|
261
|
+
const detail = esc(o?.detail ?? o?.note ?? '')
|
|
262
|
+
return [
|
|
263
|
+
` <li class="opt${rec ? ' rec' : ''}">`,
|
|
264
|
+
` <span class="oid">${esc(o?.id ?? '')}</span>`,
|
|
265
|
+
` <span class="olabel">${esc(o?.label ?? '')}${rec ? '<span class="rec-badge">推奨</span>' : ''}</span>`,
|
|
266
|
+
detail ? ` <span class="odetail">${detail}</span>` : '',
|
|
267
|
+
' </li>',
|
|
268
|
+
]
|
|
269
|
+
.filter(Boolean)
|
|
270
|
+
.join('\n')
|
|
271
|
+
})
|
|
272
|
+
return [
|
|
273
|
+
' <section class="q">',
|
|
274
|
+
` <h3>Q${i + 1}. ${qtext}</h3>`,
|
|
275
|
+
items.length ? ` <ul class="opts">\n${items.join('\n')}\n </ul>` : '',
|
|
276
|
+
' </section>',
|
|
277
|
+
]
|
|
278
|
+
.filter(Boolean)
|
|
279
|
+
.join('\n')
|
|
280
|
+
})
|
|
281
|
+
|
|
282
|
+
const meta = [
|
|
283
|
+
label ? `<span class="meta-label">${label}</span>` : '',
|
|
284
|
+
`<span class="meta-round">r${esc(round)}</span>`,
|
|
285
|
+
target ? `<span class="meta-target">${target}</span>` : '',
|
|
286
|
+
]
|
|
287
|
+
.filter(Boolean)
|
|
288
|
+
.join('')
|
|
289
|
+
|
|
290
|
+
return `<!DOCTYPE html>
|
|
291
|
+
<html lang="ja">
|
|
292
|
+
<head>
|
|
293
|
+
<meta charset="utf-8">
|
|
294
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
295
|
+
<title>${title}</title>
|
|
296
|
+
<style>
|
|
297
|
+
:root{color-scheme:light dark}
|
|
298
|
+
*{box-sizing:border-box}
|
|
299
|
+
body{margin:0;padding:16px 14px 40px;font:15px/1.7 -apple-system,BlinkMacSystemFont,"Hiragino Sans","Noto Sans JP",sans-serif;
|
|
300
|
+
background:#f6f6f4;color:#1c1c1e}
|
|
301
|
+
main{max-width:720px;margin:0 auto}
|
|
302
|
+
h1{font-size:19px;line-height:1.45;margin:0 0 6px}
|
|
303
|
+
.meta{display:flex;flex-wrap:wrap;gap:8px;font-size:12px;color:#5c5c66;margin:0 0 14px}
|
|
304
|
+
.meta span{padding:2px 8px;border-radius:999px;background:#e8e8e4}
|
|
305
|
+
.note{font-size:13px;line-height:1.6;color:#3a3a40;background:#fff;border:1px solid #dedcd4;
|
|
306
|
+
border-radius:12px;padding:10px 12px;margin:0 0 18px}
|
|
307
|
+
.topic{font-size:14px;line-height:1.7;white-space:pre-wrap;background:#fff;border:1px solid #dedcd4;
|
|
308
|
+
border-radius:12px;padding:12px;margin:0 0 18px}
|
|
309
|
+
.q{background:#fff;border:1px solid #dedcd4;border-radius:14px;padding:14px;margin:0 0 14px}
|
|
310
|
+
.q h3{font-size:15px;line-height:1.6;margin:0 0 10px}
|
|
311
|
+
.opts{list-style:none;margin:0;padding:0}
|
|
312
|
+
.opt{display:flex;flex-wrap:wrap;gap:6px 10px;padding:9px 10px;border-radius:10px;border:1px solid #e6e4dc}
|
|
313
|
+
.opt + .opt{margin-top:8px}
|
|
314
|
+
.opt.rec{border-color:#1f9d63;background:#f2fbf6}
|
|
315
|
+
.oid{min-width:1.4em;font-weight:700}
|
|
316
|
+
.olabel{font-weight:600}
|
|
317
|
+
.odetail{flex-basis:100%;font-size:13px;color:#5c5c66}
|
|
318
|
+
.rec-badge{margin-left:8px;font-size:11px;font-weight:700;color:#0b5f45;background:#d6f5e6;
|
|
319
|
+
border-radius:999px;padding:1px 7px;vertical-align:1px}
|
|
320
|
+
.empty{font-size:14px;color:#5c5c66}
|
|
321
|
+
@media (prefers-color-scheme:dark){
|
|
322
|
+
body{background:#131315;color:#f2f2f4}
|
|
323
|
+
.meta{color:#a0a0aa} .meta span{background:#242428}
|
|
324
|
+
.q,.note,.topic{background:#1c1c1f;border-color:#2e2e33}
|
|
325
|
+
.opt{border-color:#2e2e33} .opt.rec{border-color:#2f9d6b;background:#152b21}
|
|
326
|
+
.odetail{color:#a0a0aa} .note{color:#d8d8de}
|
|
327
|
+
}
|
|
328
|
+
</style>
|
|
329
|
+
</head>
|
|
330
|
+
<body>
|
|
331
|
+
<main id="akForm">
|
|
332
|
+
<h1>${title}</h1>
|
|
333
|
+
<div class="meta">${meta}</div>
|
|
334
|
+
<p class="note">このシートは <code>sheet.json</code> から自動生成した閲覧ビューです。回答はアプリのレビュータブ(簡易回答フォーム)から送ってください。</p>
|
|
335
|
+
${topic ? ` <div class="topic">${topic}</div>` : ''}
|
|
336
|
+
${sections.length ? sections.join('\n') : ' <p class="empty">設問がありません。</p>'}
|
|
337
|
+
</main>
|
|
338
|
+
</body>
|
|
339
|
+
</html>
|
|
340
|
+
`
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* レビューシートの CSP(D57)。**条件分岐しない**。
|
|
345
|
+
*
|
|
346
|
+
* `sandbox allow-scripts allow-forms` を付けると、シートは不透明オリジンに落ちる。
|
|
347
|
+
* シートに同居するスクリプト(設問の描画・回答テキストの生成)は動くが、
|
|
348
|
+
* same-origin Cookie も `/ws/term` も `/api/*` も触れない。回答は postMessage で
|
|
349
|
+
* 親(PWA の iframe / `/api/review/:id/view` ラッパー)へ渡し、親が POST する。
|
|
350
|
+
*
|
|
351
|
+
* 以前は `sec-fetch-dest` を見て単体タブだけ same-origin を許していたが、
|
|
352
|
+
* 「ヘッダを付け替えれば same-origin に戻せる」抜け道になるので廃止した。
|
|
353
|
+
* 単体タブで開きたい場合は `/api/review/:id/view` を使う。
|
|
354
|
+
*/
|
|
355
|
+
export const REVIEW_SHEET_CSP =
|
|
356
|
+
"sandbox allow-scripts allow-forms; default-src 'none'; style-src 'unsafe-inline'; " +
|
|
357
|
+
"img-src data: blob:; script-src 'unsafe-inline'; font-src data:"
|
|
358
|
+
|
|
359
|
+
/** `/api/review/:id/sheet` のレスポンスヘッダ(常に sandbox)。 */
|
|
360
|
+
export function reviewSheetHeaders() {
|
|
361
|
+
return {
|
|
362
|
+
'content-type': 'text/html; charset=utf-8',
|
|
363
|
+
'content-security-policy': REVIEW_SHEET_CSP,
|
|
364
|
+
'cache-control': 'no-store',
|
|
365
|
+
'x-content-type-options': 'nosniff',
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* `/api/review/:id/view` ラッパー自身の CSP。
|
|
371
|
+
*
|
|
372
|
+
* ラッパーはブリッジが生成する最小 HTML なので same-origin を許可する必要がある
|
|
373
|
+
* (回答の POST と sheet の iframe 読み込みだけ)。`sandbox` は付けない —
|
|
374
|
+
* 付けると `allow-same-origin` 抜きでは fetch が不透明オリジン扱いになる。
|
|
375
|
+
*/
|
|
376
|
+
export const REVIEW_VIEW_CSP =
|
|
377
|
+
"default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; " +
|
|
378
|
+
"frame-src 'self'; connect-src 'self'; img-src data:"
|
|
379
|
+
|
|
380
|
+
/** `/api/review/:id/view` のレスポンスヘッダ。 */
|
|
381
|
+
export function reviewViewHeaders() {
|
|
382
|
+
return {
|
|
383
|
+
'content-type': 'text/html; charset=utf-8',
|
|
384
|
+
'content-security-policy': REVIEW_VIEW_CSP,
|
|
385
|
+
'cache-control': 'no-store',
|
|
386
|
+
'x-content-type-options': 'nosniff',
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** JSON を `<script>` の中へ安全に埋める(`</script>` での脱出を潰す)。 */
|
|
391
|
+
function scriptJson(value) {
|
|
392
|
+
return JSON.stringify(String(value)).replace(/</g, '\\u003c').replace(/>/g, '\\u003e')
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* 単体タブ用のラッパー HTML(D57)。
|
|
397
|
+
*
|
|
398
|
+
* `/api/review/:id/sheet` は常に sandbox なので、シート単体では回答を POST できない。
|
|
399
|
+
* このラッパーが same-origin の親として sandbox `<iframe>` を抱え、
|
|
400
|
+
* シートからの `postMessage` を `POST /api/review/:id/answer` へ中継する。
|
|
401
|
+
*
|
|
402
|
+
* @param {string} taskId タスク id
|
|
403
|
+
* @returns {string} HTML
|
|
404
|
+
*/
|
|
405
|
+
export function reviewViewHtml(taskId) {
|
|
406
|
+
const id = String(taskId)
|
|
407
|
+
const jsTask = scriptJson(id)
|
|
408
|
+
const jsSrc = scriptJson(`/api/review/${encodeURIComponent(id)}/sheet`)
|
|
409
|
+
return `<!doctype html>
|
|
410
|
+
<html lang="ja">
|
|
411
|
+
<head>
|
|
412
|
+
<meta charset="utf-8">
|
|
413
|
+
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
|
414
|
+
<title>レビューシート ${escapeHtmlText(id)}</title>
|
|
415
|
+
<style>
|
|
416
|
+
html,body{margin:0;height:100%;background:#f6f4ef;color:#1b1a17;font-family:-apple-system,BlinkMacSystemFont,"Hiragino Sans","Noto Sans JP",sans-serif}
|
|
417
|
+
#akViewSheet{display:block;width:100%;height:100%;border:0;background:#f6f4ef}
|
|
418
|
+
#akViewStatus{position:fixed;left:12px;right:12px;bottom:calc(12px + env(safe-area-inset-bottom));z-index:9;display:none;padding:10px 12px;border-radius:12px;font-size:13px;line-height:1.6;box-shadow:0 6px 20px rgba(0,0,0,.16)}
|
|
419
|
+
#akViewStatus.show{display:block}
|
|
420
|
+
#akViewStatus.ok{background:#e7f8f1;color:#0b5f45}
|
|
421
|
+
#akViewStatus.ng{background:#fdecea;color:#8a1f17}
|
|
422
|
+
</style>
|
|
423
|
+
</head>
|
|
424
|
+
<body>
|
|
425
|
+
<iframe id="akViewSheet" src="${escapeHtmlText(`/api/review/${encodeURIComponent(id)}/sheet`)}" sandbox="allow-scripts allow-forms" title="レビューシート"></iframe>
|
|
426
|
+
<div id="akViewStatus" role="status" aria-live="polite"></div>
|
|
427
|
+
<script>
|
|
428
|
+
(function () {
|
|
429
|
+
var TASK = ${jsTask};
|
|
430
|
+
var SHEET = ${jsSrc};
|
|
431
|
+
var box = document.getElementById('akViewStatus');
|
|
432
|
+
var timer = 0;
|
|
433
|
+
function note(ok, msg) {
|
|
434
|
+
box.textContent = msg;
|
|
435
|
+
box.className = 'show ' + (ok ? 'ok' : 'ng');
|
|
436
|
+
clearTimeout(timer);
|
|
437
|
+
// 成功は控えめに消す。失敗は読ませたいので残す。
|
|
438
|
+
if (ok) timer = setTimeout(function () { box.className = ''; }, 4000);
|
|
439
|
+
}
|
|
440
|
+
function title(el) {
|
|
441
|
+
return (el && ((el.error && el.error.message) || el.message)) || 'unknown';
|
|
442
|
+
}
|
|
443
|
+
window.addEventListener('message', function (ev) {
|
|
444
|
+
var d = ev.data;
|
|
445
|
+
if (!d) return;
|
|
446
|
+
// 旧シート(akapen:reply)も受ける。新しい注入スクリプトは review:reply を送る。
|
|
447
|
+
if (d.type !== 'review:reply' && d.type !== 'akapen:reply') return;
|
|
448
|
+
if (String(d.taskId) !== TASK) return;
|
|
449
|
+
var text = String(d.text || '');
|
|
450
|
+
if (!text) return;
|
|
451
|
+
note(true, '送信中…');
|
|
452
|
+
fetch('/api/review/' + encodeURIComponent(TASK) + '/answer', {
|
|
453
|
+
method: 'POST',
|
|
454
|
+
credentials: 'same-origin',
|
|
455
|
+
headers: { 'content-type': 'application/json', 'x-client': 'mobile' },
|
|
456
|
+
body: JSON.stringify({ text: text, by: 'web' })
|
|
457
|
+
}).then(function (r) {
|
|
458
|
+
return r.json().then(function (j) { return { ok: r.ok, j: j }; }, function () { return { ok: r.ok, j: null }; });
|
|
459
|
+
}).then(function (res) {
|
|
460
|
+
var ok = Boolean(res.ok && res.j && res.j.ok);
|
|
461
|
+
note(ok, ok ? '回答を送信しました(タスクは ' + (res.j.moved || '—') + ')' : '送信できませんでした: ' + title(res.j));
|
|
462
|
+
}).catch(function (e) {
|
|
463
|
+
note(false, '送信エラー: ' + (e && e.message ? e.message : e));
|
|
464
|
+
});
|
|
465
|
+
});
|
|
466
|
+
// シートが読めなかったとき(404 など)に無言の白画面を出さない
|
|
467
|
+
var frame = document.getElementById('akViewSheet');
|
|
468
|
+
if (frame) frame.addEventListener('error', function () { note(false, 'シートを読み込めません: ' + SHEET); });
|
|
469
|
+
})();
|
|
470
|
+
</script>
|
|
471
|
+
</body>
|
|
472
|
+
</html>
|
|
473
|
+
`
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* シート HTML に「回答をアプリへ送る」小さなブリッジを注入する(保存物は書き換えない)。
|
|
478
|
+
*
|
|
479
|
+
* アプリ内で開いたときだけ、設問見出し (Q1…) をマーカーで装飾する(レビュー注釈の指摘)。
|
|
480
|
+
* 保存済みのシート(file:// で開く原本)は書き換えないので、装飾はアプリ表示の担当。
|
|
481
|
+
*/
|
|
482
|
+
export function injectReviewBridge(html, taskId) {
|
|
483
|
+
const style = `
|
|
484
|
+
<style id="akBridgeStyle">
|
|
485
|
+
#akForm .q h3{
|
|
486
|
+
display:inline-block;
|
|
487
|
+
max-width:100%;
|
|
488
|
+
margin:0 0 10px -3px;
|
|
489
|
+
padding:1px 6px 2px;
|
|
490
|
+
font-size:16px;
|
|
491
|
+
font-weight:700;
|
|
492
|
+
line-height:1.6;
|
|
493
|
+
border-radius:3px;
|
|
494
|
+
background:linear-gradient(180deg,rgba(250,204,21,0) 44%,rgba(250,204,21,.62) 44%,rgba(250,204,21,.62) 96%,rgba(250,204,21,0) 96%);
|
|
495
|
+
}
|
|
496
|
+
</style>
|
|
497
|
+
`
|
|
498
|
+
const script = `
|
|
499
|
+
<script>
|
|
500
|
+
(function () {
|
|
501
|
+
var TASK = ${JSON.stringify(String(taskId))};
|
|
502
|
+
function replyText() { var o = document.getElementById('out'); return o ? o.value : ''; }
|
|
503
|
+
function report(ok, msg) {
|
|
504
|
+
var el = document.getElementById('akBridgeStatus');
|
|
505
|
+
if (!el) {
|
|
506
|
+
el = document.createElement('div');
|
|
507
|
+
el.id = 'akBridgeStatus';
|
|
508
|
+
el.style.cssText = 'margin:12px 0;padding:10px 12px;border-radius:10px;font:inherit;font-size:13px;line-height:1.6';
|
|
509
|
+
(document.getElementById('akForm') || document.body).appendChild(el);
|
|
510
|
+
}
|
|
511
|
+
el.style.background = ok ? '#e7f8f1' : '#fdecea';
|
|
512
|
+
el.style.color = ok ? '#0b5f45' : '#8a1f17';
|
|
513
|
+
el.textContent = msg;
|
|
514
|
+
}
|
|
515
|
+
function submit() {
|
|
516
|
+
var text = replyText();
|
|
517
|
+
// 移行前のシートは【赤ペン回答】を、新しいシートは【レビュー回答】を出す。
|
|
518
|
+
if (!text || !/【(?:レビュー|赤ペン)回答】|\[Review Answer\]/.test(text)) return;
|
|
519
|
+
if (window.parent && window.parent !== window) {
|
|
520
|
+
window.parent.postMessage({ type: 'review:reply', taskId: TASK, text: text }, '*');
|
|
521
|
+
report(true, 'アプリに回答を送りました(この画面は閉じてOK)');
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
// シートは常に sandbox(不透明オリジン)で配信されるので、自分では API を叩けない。
|
|
525
|
+
// 回答は必ず親(PWA の iframe / /api/review/:id/view ラッパー)へ postMessage する。
|
|
526
|
+
report(
|
|
527
|
+
false,
|
|
528
|
+
'この画面からは直接送信できません。アプリのレビュータブ、または /api/review/' +
|
|
529
|
+
TASK +
|
|
530
|
+
'/view から開いてください'
|
|
531
|
+
);
|
|
532
|
+
}
|
|
533
|
+
// アプリ経由で開いているときは「貼り付ける」ではなく「送信」として見せる
|
|
534
|
+
function relabel() {
|
|
535
|
+
var b = document.getElementById('genBtn');
|
|
536
|
+
if (b) b.textContent = '回答を送信';
|
|
537
|
+
var note = document.querySelector('#akForm p.m');
|
|
538
|
+
if (note) note.textContent = '選んで[回答を送信]を押すと、そのままアプリに送られます(未選択は推奨案で確定)。';
|
|
539
|
+
}
|
|
540
|
+
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', relabel);
|
|
541
|
+
else relabel();
|
|
542
|
+
|
|
543
|
+
document.addEventListener('click', function (ev) {
|
|
544
|
+
var t = ev.target;
|
|
545
|
+
if (t && (t.id === 'genBtn' || (t.closest && t.closest('#genBtn')))) setTimeout(submit, 80);
|
|
546
|
+
}, true);
|
|
547
|
+
window.__reviewSubmit = submit;
|
|
548
|
+
// 互換エイリアス: 移行前のシート資産はこちらを直接呼ぶ(SPEC §4.1)
|
|
549
|
+
window.__akapenSubmit = submit;
|
|
550
|
+
})();
|
|
551
|
+
</script>
|
|
552
|
+
`
|
|
553
|
+
const inject = `${style}${script}`
|
|
554
|
+
return html.includes('</body>') ? html.replace('</body>', `${inject}\n</body>`) : html + inject
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* @param {object} cfg ブリッジ設定(kanbanRoot を使う)
|
|
559
|
+
* @param {{board?: string, root?: string}} [opts]
|
|
560
|
+
*/
|
|
561
|
+
export function createReview(cfg, opts = {}) {
|
|
562
|
+
const board = opts.board || process.env.REVIEW_BOARD || 'mobile'
|
|
563
|
+
const boardDir = path.join(cfg.kanbanRoot, 'boards', board)
|
|
564
|
+
const dbPath = path.join(boardDir, 'kanban.db')
|
|
565
|
+
|
|
566
|
+
function homeDir() {
|
|
567
|
+
return path.dirname(cfg.kanbanRoot || path.join(os.homedir(), '.hermes', 'kanban'))
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/**
|
|
571
|
+
* データの根(D1 / §3.2)。`~/.hermes/plugin-data/hermes-pilot/` に一本化する。
|
|
572
|
+
* 旧 `plugin-data/akapen` や `~/Projects/akapen` は参照しない(移行スクリプトが物理コピーする)。
|
|
573
|
+
*/
|
|
574
|
+
function dataRoot() {
|
|
575
|
+
if (cfg.pluginDataDir) return cfg.pluginDataDir
|
|
576
|
+
return path.join(homeDir(), 'plugin-data', 'hermes-pilot')
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/** レビューのワークスペース(sheets / shots / library / *.jsonl)。 */
|
|
580
|
+
function reviewRoot() {
|
|
581
|
+
return path.join(dataRoot(), 'review')
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function sanitizeChatId(raw) {
|
|
585
|
+
return String(raw ?? '')
|
|
586
|
+
.trim()
|
|
587
|
+
.replace(/[^A-Za-z0-9_-]/g, '')
|
|
588
|
+
.slice(0, 128)
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
function taskChatsFile() {
|
|
592
|
+
return path.join(reviewRoot(), 'task-chats.json')
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
function readTaskChats() {
|
|
596
|
+
const obj = readJsonIfExists(taskChatsFile())
|
|
597
|
+
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return {}
|
|
598
|
+
const out = {}
|
|
599
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
600
|
+
const c = sanitizeChatId(v)
|
|
601
|
+
if (k && c) out[k] = c
|
|
602
|
+
}
|
|
603
|
+
return out
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
function rememberTaskChat(taskId, rawChat) {
|
|
607
|
+
const id = String(taskId ?? '').trim()
|
|
608
|
+
const chat = sanitizeChatId(rawChat)
|
|
609
|
+
if (!id || !chat) return
|
|
610
|
+
try {
|
|
611
|
+
const file = taskChatsFile()
|
|
612
|
+
const cur = readTaskChats()
|
|
613
|
+
cur[id] = chat
|
|
614
|
+
const keys = Object.keys(cur)
|
|
615
|
+
if (keys.length > 500) {
|
|
616
|
+
for (const k of keys.slice(0, keys.length - 500)) delete cur[k]
|
|
617
|
+
}
|
|
618
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
619
|
+
fs.writeFileSync(file, JSON.stringify(cur, null, 2), 'utf8')
|
|
620
|
+
} catch {
|
|
621
|
+
/* 補助情報なので失敗しても本処理を止めない */
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/** ボードの default_workdir(シート置き場のルート)。未設定なら review ワークスペース。 */
|
|
626
|
+
function workdir() {
|
|
627
|
+
if (opts.root) return path.resolve(opts.root.replace(/^~/, os.homedir()))
|
|
628
|
+
try {
|
|
629
|
+
const meta = JSON.parse(fs.readFileSync(path.join(boardDir, 'board.json'), 'utf8'))
|
|
630
|
+
if (meta.default_workdir) return path.resolve(String(meta.default_workdir).replace(/^~/, os.homedir()))
|
|
631
|
+
} catch {
|
|
632
|
+
/* fall through */
|
|
633
|
+
}
|
|
634
|
+
return reviewRoot()
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
function openDb() {
|
|
638
|
+
return new DatabaseSync(dbPath, { readOnly: true })
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
function rows(limit = 80) {
|
|
642
|
+
let db
|
|
643
|
+
try {
|
|
644
|
+
db = openDb()
|
|
645
|
+
} catch {
|
|
646
|
+
return []
|
|
647
|
+
}
|
|
648
|
+
try {
|
|
649
|
+
return db
|
|
650
|
+
.prepare(
|
|
651
|
+
`SELECT id, title, body, status, assignee, priority,
|
|
652
|
+
created_at, started_at, completed_at, result, last_heartbeat_at
|
|
653
|
+
FROM tasks
|
|
654
|
+
WHERE status IN ('review','ready','running','blocked','done')
|
|
655
|
+
ORDER BY CASE status WHEN 'review' THEN 0 WHEN 'ready' THEN 1 WHEN 'running' THEN 2
|
|
656
|
+
WHEN 'blocked' THEN 3 ELSE 4 END,
|
|
657
|
+
COALESCE(completed_at, started_at, created_at) DESC
|
|
658
|
+
LIMIT ?`,
|
|
659
|
+
)
|
|
660
|
+
.all(limit)
|
|
661
|
+
} catch {
|
|
662
|
+
return []
|
|
663
|
+
} finally {
|
|
664
|
+
db.close()
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/** 各タスクの最新イベント(進行が見えるように)。 */
|
|
669
|
+
function lastEvents(ids) {
|
|
670
|
+
if (!ids.length) return {}
|
|
671
|
+
let db
|
|
672
|
+
try {
|
|
673
|
+
db = openDb()
|
|
674
|
+
} catch {
|
|
675
|
+
return {}
|
|
676
|
+
}
|
|
677
|
+
try {
|
|
678
|
+
const placeholders = ids.map(() => '?').join(',')
|
|
679
|
+
const rs = db
|
|
680
|
+
.prepare(
|
|
681
|
+
`SELECT task_id, kind, created_at FROM task_events
|
|
682
|
+
WHERE id IN (SELECT MAX(id) FROM task_events WHERE task_id IN (${placeholders}) GROUP BY task_id)`,
|
|
683
|
+
)
|
|
684
|
+
.all(...ids)
|
|
685
|
+
const out = {}
|
|
686
|
+
for (const r of rs) out[r.task_id] = { kind: r.kind, at: Number(r.created_at ?? 0) * 1000 }
|
|
687
|
+
return out
|
|
688
|
+
} catch {
|
|
689
|
+
return {}
|
|
690
|
+
} finally {
|
|
691
|
+
db.close()
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
function bodyOf(id) {
|
|
696
|
+
let db
|
|
697
|
+
try {
|
|
698
|
+
db = openDb()
|
|
699
|
+
} catch {
|
|
700
|
+
return null
|
|
701
|
+
}
|
|
702
|
+
try {
|
|
703
|
+
// assignee も取る(回答後に担当を付けるかの判定に使う・§3.1)
|
|
704
|
+
return db.prepare('SELECT body, status, title, assignee FROM tasks WHERE id = ?').get(id) || null
|
|
705
|
+
} catch {
|
|
706
|
+
return null
|
|
707
|
+
} finally {
|
|
708
|
+
db.close()
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
/**
|
|
713
|
+
* 同一 label の他タスク(前ラウンド)を 1 回のクエリで索引にする(比較画像の解決用)。
|
|
714
|
+
*
|
|
715
|
+
* 前ラウンドのタスクは `archived` のことが多い(実測: `1379.jpg-…` の前回は archived)ので
|
|
716
|
+
* status では絞らない。キーは `[review]` 行の label、値は新しい順の `{id, image, round, createdAt}`。
|
|
717
|
+
*
|
|
718
|
+
* @returns {Map<string, Array<{id: string, image: string, round: number, createdAt: number}>>}
|
|
719
|
+
*/
|
|
720
|
+
function siblingIndex() {
|
|
721
|
+
const byLabel = new Map()
|
|
722
|
+
let db
|
|
723
|
+
try {
|
|
724
|
+
db = openDb()
|
|
725
|
+
} catch {
|
|
726
|
+
return byLabel
|
|
727
|
+
}
|
|
728
|
+
try {
|
|
729
|
+
const rs = db.prepare("SELECT id, body, created_at FROM tasks WHERE body LIKE '%[review]%'").all()
|
|
730
|
+
for (const r of rs) {
|
|
731
|
+
const ak = parseReviewLine(r.body)
|
|
732
|
+
if (!ak?.image || !ak.label) continue
|
|
733
|
+
const list = byLabel.get(ak.label) || []
|
|
734
|
+
list.push({
|
|
735
|
+
id: r.id,
|
|
736
|
+
image: ak.image,
|
|
737
|
+
round: Number(ak.round ?? 1),
|
|
738
|
+
createdAt: Number(r.created_at ?? 0) * 1000,
|
|
739
|
+
})
|
|
740
|
+
byLabel.set(ak.label, list)
|
|
741
|
+
}
|
|
742
|
+
} catch {
|
|
743
|
+
/* 索引は補助情報。壊れた DB でも一覧は返す */
|
|
744
|
+
} finally {
|
|
745
|
+
db.close()
|
|
746
|
+
}
|
|
747
|
+
for (const list of byLabel.values()) list.sort((a, b) => b.createdAt - a.createdAt)
|
|
748
|
+
return byLabel
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
/**
|
|
752
|
+
* 比較用(Before)画像の実在する相対パス(無ければ null)。
|
|
753
|
+
*
|
|
754
|
+
* @param {string} id タスク ID(自分自身を候補から外す)
|
|
755
|
+
* @param {object} ak `[review]` 行
|
|
756
|
+
* @param {Map} [index] `siblingIndex()` の結果(一覧では 1 回だけ作って渡す)
|
|
757
|
+
*/
|
|
758
|
+
function compareRelOf(id, ak, index) {
|
|
759
|
+
if (!ak?.image) return null
|
|
760
|
+
const others = (index?.get(ak.label) || []).filter((o) => o.id !== id)
|
|
761
|
+
const cands = compareCandidates({ image: ak.image, round: Number(ak.round ?? 1), others })
|
|
762
|
+
for (const rel of cands) {
|
|
763
|
+
if (resolveInside(rel)) return rel
|
|
764
|
+
}
|
|
765
|
+
return null
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
/**
|
|
769
|
+
* このタスクを実行している worker のセッション ID(無ければ null)。
|
|
770
|
+
*
|
|
771
|
+
* `session_id` がタスク行にあっても `db`(どのプロファイルの state.db か)は
|
|
772
|
+
* イベントにしか残らないので、必ず `task_events` も読んで補完する。
|
|
773
|
+
*/
|
|
774
|
+
function sessionId(id) {
|
|
775
|
+
let db
|
|
776
|
+
try {
|
|
777
|
+
db = openDb()
|
|
778
|
+
} catch {
|
|
779
|
+
return null
|
|
780
|
+
}
|
|
781
|
+
try {
|
|
782
|
+
const r = db.prepare('SELECT session_id, status FROM tasks WHERE id = ?').get(id)
|
|
783
|
+
const fromRow = r?.session_id ? String(r.session_id) : null
|
|
784
|
+
const evs = db
|
|
785
|
+
.prepare(
|
|
786
|
+
"SELECT payload FROM task_events WHERE task_id = ? AND kind IN ('owner_admitted','worker_bound','spawned') ORDER BY id DESC LIMIT 6",
|
|
787
|
+
)
|
|
788
|
+
.all(id)
|
|
789
|
+
let sid = fromRow
|
|
790
|
+
let evDb = null
|
|
791
|
+
for (const ev of evs) {
|
|
792
|
+
try {
|
|
793
|
+
const p = JSON.parse(ev.payload || '{}')
|
|
794
|
+
if (!sid && p.session_id) sid = String(p.session_id)
|
|
795
|
+
if (!evDb && p.db) evDb = String(p.db)
|
|
796
|
+
if (sid && evDb) break
|
|
797
|
+
} catch {
|
|
798
|
+
/* 壊れた payload は無視 */
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
if (!sid) return null
|
|
802
|
+
return { sessionId: sid, status: r?.status ?? null, db: evDb }
|
|
803
|
+
} catch {
|
|
804
|
+
return null
|
|
805
|
+
} finally {
|
|
806
|
+
db.close()
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
/** workdir 配下に収まることを realpath で確かめて絶対パスを返す。 */
|
|
811
|
+
function resolveInside(rel) {
|
|
812
|
+
if (!isSafeRel(rel)) return null
|
|
813
|
+
const root = workdir()
|
|
814
|
+
const abs = path.resolve(root, rel)
|
|
815
|
+
const relToRoot = path.relative(root, abs)
|
|
816
|
+
if (relToRoot.startsWith('..') || path.isAbsolute(relToRoot)) return null
|
|
817
|
+
try {
|
|
818
|
+
return fs.realpathSync(abs)
|
|
819
|
+
} catch {
|
|
820
|
+
return null
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
function readJsonIfExists(abs) {
|
|
825
|
+
try {
|
|
826
|
+
return JSON.parse(fs.readFileSync(abs, 'utf8'))
|
|
827
|
+
} catch {
|
|
828
|
+
return null
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
/** 一覧(PWA のレビュータブ)。 */
|
|
833
|
+
function list(limit = 80) {
|
|
834
|
+
const out = []
|
|
835
|
+
const base = rows(limit)
|
|
836
|
+
const events = lastEvents(base.map((r) => r.id))
|
|
837
|
+
const taskChats = readTaskChats()
|
|
838
|
+
const siblings = siblingIndex()
|
|
839
|
+
for (const r of base) {
|
|
840
|
+
const ak = parseReviewLine(r.body)
|
|
841
|
+
if (!ak) continue
|
|
842
|
+
const sheetAbs = ak.sheet ? resolveInside(ak.sheet) : null
|
|
843
|
+
const paths = ak.sheet ? sheetPaths(ak.sheet) : null
|
|
844
|
+
const dataRel = paths ? paths.dataRel : null
|
|
845
|
+
const dataAbs = dataRel ? resolveInside(dataRel) : null
|
|
846
|
+
const sheet = dataAbs ? readJsonIfExists(dataAbs) : null
|
|
847
|
+
const answerRel = paths ? paths.answerRel : null
|
|
848
|
+
const answered = answerRel ? readJsonIfExists(resolveInside(answerRel) || '\0') : null
|
|
849
|
+
out.push({
|
|
850
|
+
id: r.id,
|
|
851
|
+
board,
|
|
852
|
+
title: r.title,
|
|
853
|
+
status: r.status,
|
|
854
|
+
assignee: r.assignee,
|
|
855
|
+
createdAt: Number(r.created_at ?? 0) * 1000,
|
|
856
|
+
completedAt: r.completed_at ? Number(r.completed_at) * 1000 : null,
|
|
857
|
+
result: r.result ? String(r.result).slice(0, 400) : null,
|
|
858
|
+
progress: {
|
|
859
|
+
lastEvent: events[r.id]?.kind ?? null,
|
|
860
|
+
lastEventAt: events[r.id]?.at ?? null,
|
|
861
|
+
heartbeatAt: r.last_heartbeat_at ? Number(r.last_heartbeat_at) * 1000 : null,
|
|
862
|
+
startedAt: r.started_at ? Number(r.started_at) * 1000 : null,
|
|
863
|
+
},
|
|
864
|
+
review: {
|
|
865
|
+
label: ak.label ?? null,
|
|
866
|
+
image: ak.image ?? null,
|
|
867
|
+
// 比較用(Before=前回の赤入れ)画像があるか。UI はこれでトグルを出す
|
|
868
|
+
hasCompare: Boolean(compareRelOf(r.id, ak, siblings)),
|
|
869
|
+
target: ak.target ?? null,
|
|
870
|
+
repo: repoForTarget(ak.target),
|
|
871
|
+
chat: sanitizeChatId(ak.chat) || taskChats[r.id] || null,
|
|
872
|
+
mode: ak.mode ?? 'standard',
|
|
873
|
+
round: Number(ak.round ?? 1),
|
|
874
|
+
sheet: ak.sheet ?? null,
|
|
875
|
+
exists: Boolean(sheetAbs || dataAbs),
|
|
876
|
+
title: sheet?.title ?? null,
|
|
877
|
+
topic: sheet?.topic ?? null,
|
|
878
|
+
questions: Array.isArray(sheet?.questions) ? sheet.questions.length : 0,
|
|
879
|
+
answeredAt: answered?.answered_at ?? null,
|
|
880
|
+
},
|
|
881
|
+
})
|
|
882
|
+
}
|
|
883
|
+
return out
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
/**
|
|
887
|
+
* シート HTML(認可は呼び出し側)。
|
|
888
|
+
*
|
|
889
|
+
* `.html` があればそれをそのまま返す(後方互換)。無い(または `.json` を指している)
|
|
890
|
+
* ときは同じ場所の `.json` から閲覧用 HTML を動的生成して返す — JSON ファーストで
|
|
891
|
+
* 起票されたシートでも「シート全体を開く ↗」が常に動くようにするため(D38)。
|
|
892
|
+
*/
|
|
893
|
+
function sheetHtml(id) {
|
|
894
|
+
const b = bodyOf(id)
|
|
895
|
+
if (!b) return { ok: false, code: 'NOT_FOUND' }
|
|
896
|
+
const ak = parseReviewLine(b.body)
|
|
897
|
+
if (!ak?.sheet) return { ok: false, code: 'NO_SHEET' }
|
|
898
|
+
const abs = resolveInside(ak.sheet)
|
|
899
|
+
const isJson = Boolean(abs && /\.json$/i.test(abs))
|
|
900
|
+
if (abs && !isJson) return { ok: true, html: fs.readFileSync(abs, 'utf8'), path: abs }
|
|
901
|
+
const dataAbs = isJson ? abs : resolveInside(sheetPaths(ak.sheet).dataRel)
|
|
902
|
+
const data = dataAbs ? readJsonIfExists(dataAbs) : null
|
|
903
|
+
if (!data) return { ok: false, code: 'SHEET_MISSING' }
|
|
904
|
+
return { ok: true, html: renderSheetHtmlFromData(data, ak), path: dataAbs, generated: true }
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
/** シートの構造化データ(PWA のネイティブフォーム用)。 */
|
|
908
|
+
function sheetData(id) {
|
|
909
|
+
const b = bodyOf(id)
|
|
910
|
+
if (!b) return { ok: false, code: 'NOT_FOUND' }
|
|
911
|
+
const ak = parseReviewLine(b.body)
|
|
912
|
+
if (!ak?.sheet) return { ok: false, code: 'NO_SHEET' }
|
|
913
|
+
const abs = resolveInside(sheetPaths(ak.sheet).dataRel)
|
|
914
|
+
const data = abs ? readJsonIfExists(abs) : null
|
|
915
|
+
if (!data) return { ok: false, code: 'DATA_MISSING' }
|
|
916
|
+
// 回答の履歴(完了した項目を「なぜこの設計か」まで辿れるようにする)。
|
|
917
|
+
// 回答は無いことがある(回答前に片付けた等)ので、無ければ null。
|
|
918
|
+
const answer = readJsonIfExists(resolveInside(sheetPaths(ak.sheet).answerRel) || '\0')
|
|
919
|
+
return { ok: true, data, answer: answer || null, taskId: id, status: b.status }
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
/**
|
|
923
|
+
* 回答後にタスクへ付ける担当プロファイル。
|
|
924
|
+
* 未指定なら `HP_REVIEW_ASSIGNEE` → `opts.assignee` → `'mobile'`。
|
|
925
|
+
* @returns {string} プロファイル名
|
|
926
|
+
*/
|
|
927
|
+
const reviewAssignee = () =>
|
|
928
|
+
String(process.env.HP_REVIEW_ASSIGNEE ?? opts.assignee ?? '').trim() || 'mobile'
|
|
929
|
+
|
|
930
|
+
/** テストから差し替えられるように注入可能にしておく。 */
|
|
931
|
+
const runKanban = opts.runKanban || function runKanbanReal(args) {
|
|
932
|
+
return new Promise((resolve) => {
|
|
933
|
+
execFile(
|
|
934
|
+
'hermes',
|
|
935
|
+
['kanban', '--board', board, ...args],
|
|
936
|
+
{ timeout: 30000, maxBuffer: 1_000_000, env: { ...process.env } },
|
|
937
|
+
(err, stdout, stderr) => {
|
|
938
|
+
resolve({ code: err ? (err.code ?? 1) : 0, out: `${stdout ?? ''}${stderr ?? ''}`.trim() })
|
|
939
|
+
},
|
|
940
|
+
)
|
|
941
|
+
})
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
/**
|
|
945
|
+
* 回答を保存して状態を進める(冪等)。
|
|
946
|
+
*
|
|
947
|
+
* @param {string} id タスク ID
|
|
948
|
+
* @param {{answers: Array, global?: string, annotations?: Array, by?: string}} payload
|
|
949
|
+
*/
|
|
950
|
+
async function answer(id, payload) {
|
|
951
|
+
const b = bodyOf(id)
|
|
952
|
+
if (!b) return { ok: false, code: 'NOT_FOUND' }
|
|
953
|
+
const ak = parseReviewLine(b.body)
|
|
954
|
+
if (!ak?.sheet) return { ok: false, code: 'NO_SHEET' }
|
|
955
|
+
|
|
956
|
+
const sheetAbs = resolveInside(ak.sheet)
|
|
957
|
+
const dataAbs = resolveInside(ak.sheet.replace(/\.html$/, '.json'))
|
|
958
|
+
const data = dataAbs ? readJsonIfExists(dataAbs) : null
|
|
959
|
+
const questions = Array.isArray(data?.questions) ? data.questions : []
|
|
960
|
+
|
|
961
|
+
// シート HTML がそのまま送ってきた【レビュー回答】も受ける
|
|
962
|
+
const fromText =
|
|
963
|
+
payload?.text && !(Array.isArray(payload?.answers) && payload.answers.length)
|
|
964
|
+
? parseReplyText(payload.text)
|
|
965
|
+
: null
|
|
966
|
+
const answers = fromText ? fromText.answers : Array.isArray(payload?.answers) ? payload.answers : []
|
|
967
|
+
const global = fromText ? fromText.global : String(payload?.global ?? '')
|
|
968
|
+
const annotations = Array.isArray(payload?.annotations) ? payload.annotations : []
|
|
969
|
+
const hash = answerHash({ answers, global, annotations })
|
|
970
|
+
|
|
971
|
+
const answerRel = sheetPaths(ak.sheet).answerRel
|
|
972
|
+
const answerDir = path.dirname(path.resolve(workdir(), answerRel))
|
|
973
|
+
const answerFile = path.join(answerDir, path.basename(answerRel))
|
|
974
|
+
const textFile = answerFile.replace(/\.answer\.json$/, '.answer.txt')
|
|
975
|
+
|
|
976
|
+
if (payload?.chat) rememberTaskChat(id, payload.chat)
|
|
977
|
+
const existing = readJsonIfExists(answerFile)
|
|
978
|
+
if (existing && existing.sha256 === hash) {
|
|
979
|
+
// 回答は保存済み。遷移だけ未了なら(再送で)ここで進める — 冪等の本体はこの分岐
|
|
980
|
+
let moved = { code: 0, out: '' }
|
|
981
|
+
let status = b.status
|
|
982
|
+
if (b.status === 'blocked') {
|
|
983
|
+
moved = await runKanban(['unblock', id, '--reason', 'レビュー回答を受領(再送)'])
|
|
984
|
+
if (moved.code === 0) status = 'ready'
|
|
985
|
+
}
|
|
986
|
+
return {
|
|
987
|
+
ok: moved.code === 0,
|
|
988
|
+
duplicate: true,
|
|
989
|
+
sha256: hash,
|
|
990
|
+
status,
|
|
991
|
+
moved: status,
|
|
992
|
+
code: 'REVIEW_ALREADY_ANSWERED',
|
|
993
|
+
output: moved.out.slice(0, 400),
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
// 回答は「レビュー待ち(blocked)」のときだけ受け付ける。ready / running / review / done へ
|
|
997
|
+
// 送ると answer.json を上書きし、comment が二重に付く(レビューシートの付録 1-2)。
|
|
998
|
+
if (b.status !== 'blocked') {
|
|
999
|
+
return {
|
|
1000
|
+
ok: false,
|
|
1001
|
+
code: 'NOT_WAITING',
|
|
1002
|
+
status: b.status,
|
|
1003
|
+
params: { status: b.status },
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
const record = {
|
|
1008
|
+
label: ak.label ?? null,
|
|
1009
|
+
round: Number(ak.round ?? 1),
|
|
1010
|
+
task_id: id,
|
|
1011
|
+
answered_at: new Date().toISOString(),
|
|
1012
|
+
answers: answers.map((a) => ({
|
|
1013
|
+
id: String(a?.id ?? ''),
|
|
1014
|
+
choice: a?.choice ?? null,
|
|
1015
|
+
note: String(a?.note ?? ''),
|
|
1016
|
+
})),
|
|
1017
|
+
global,
|
|
1018
|
+
annotations,
|
|
1019
|
+
sha256: hash,
|
|
1020
|
+
}
|
|
1021
|
+
fs.mkdirSync(answerDir, { recursive: true })
|
|
1022
|
+
fs.writeFileSync(answerFile, JSON.stringify(record, null, 2), 'utf8')
|
|
1023
|
+
fs.writeFileSync(textFile, toReplyText(ak.label ?? id, record.answers, global, questions), 'utf8')
|
|
1024
|
+
|
|
1025
|
+
const summary = `レビュー回答: ${questions.length || answers.length}問 ` +
|
|
1026
|
+
`(選択 ${answers.filter((a) => a?.choice).length} / お任せ ${answers.filter((a) => !a?.choice).length}) ` +
|
|
1027
|
+
`— ${path.relative(workdir(), answerFile)}`
|
|
1028
|
+
const comment = await runKanban(['comment', id, summary, '--author', String(payload?.by ?? 'mobile')])
|
|
1029
|
+
let moved = { code: 0, out: '' }
|
|
1030
|
+
let status = b.status
|
|
1031
|
+
if (b.status === 'blocked') {
|
|
1032
|
+
moved = await runKanban(['unblock', id, '--reason', 'レビュー回答を受領'])
|
|
1033
|
+
if (moved.code === 0) status = 'ready'
|
|
1034
|
+
}
|
|
1035
|
+
/*
|
|
1036
|
+
* 回答を受けたタスクに担当が無いと、ready になっても**誰も走らない**
|
|
1037
|
+
* (「回答済みだが自律ワーカー起動待ち」で止まる・実測)。未割当ならここで付ける。
|
|
1038
|
+
*/
|
|
1039
|
+
let assigned = null
|
|
1040
|
+
if (status === 'ready' && !String(b.assignee ?? '').trim()) {
|
|
1041
|
+
const who = String(reviewAssignee() ?? '').trim()
|
|
1042
|
+
if (who) {
|
|
1043
|
+
const r = await runKanban(['assign', id, who])
|
|
1044
|
+
if (r.code === 0) {
|
|
1045
|
+
assigned = who
|
|
1046
|
+
moved = { code: 0, out: `${moved.out}\n${r.out}`.trim() }
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
return {
|
|
1051
|
+
ok: comment.code === 0 && moved.code === 0,
|
|
1052
|
+
duplicate: false,
|
|
1053
|
+
assigned,
|
|
1054
|
+
sha256: hash,
|
|
1055
|
+
files: { answer: path.relative(workdir(), answerFile), text: path.relative(workdir(), textFile) },
|
|
1056
|
+
status,
|
|
1057
|
+
moved: status,
|
|
1058
|
+
output: `${comment.out}\n${moved.out}`.trim().slice(0, 800),
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
/** 反映が違うとき review に戻す。 */
|
|
1063
|
+
async function reopen(id, reason) {
|
|
1064
|
+
const b = bodyOf(id)
|
|
1065
|
+
if (!b) return { ok: false, code: 'NOT_FOUND' }
|
|
1066
|
+
const out = await runKanban(['request-changes', id, String(reason || 'レビューの再確認をお願いします')])
|
|
1067
|
+
return { ok: out.code === 0, status: b.status, output: out.out.slice(0, 800) }
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
/**
|
|
1071
|
+
* 検収(1 タップ合格)の状態遷移。
|
|
1072
|
+
*
|
|
1073
|
+
* 「✅ Looks Good」の意味は **合格=完了**(SPEC §5.2.3 / D15②)。まず `complete` を試し、
|
|
1074
|
+
* それが通らない(ワーカーが抱えたまま等)ときだけ `unblock` に落とす — どちらでも
|
|
1075
|
+
* ワーカーは止まらず、人間の判断は失われない。
|
|
1076
|
+
*
|
|
1077
|
+
* @param {string} id タスク ID
|
|
1078
|
+
* @param {{status: string}} b `bodyOf()` の行
|
|
1079
|
+
* @param {string} reason unblock に落ちたときの理由
|
|
1080
|
+
* @returns {Promise<{code: number, out: string, status: string, moved: string|null}>}
|
|
1081
|
+
*/
|
|
1082
|
+
async function approveAdvance(id, b, reason) {
|
|
1083
|
+
if (b.status !== 'blocked') return { code: 0, out: '', status: b.status, moved: null }
|
|
1084
|
+
const done = await runKanban([
|
|
1085
|
+
'complete',
|
|
1086
|
+
id,
|
|
1087
|
+
'--result',
|
|
1088
|
+
'Visual check passed',
|
|
1089
|
+
'--metadata',
|
|
1090
|
+
JSON.stringify({ closed_from: 'review', approved_by: 'mobile', approved_at: new Date().toISOString() }),
|
|
1091
|
+
])
|
|
1092
|
+
if (done.code === 0) return { code: 0, out: done.out, status: 'done', moved: 'done' }
|
|
1093
|
+
const freed = await runKanban(['unblock', id, '--reason', reason])
|
|
1094
|
+
return {
|
|
1095
|
+
code: freed.code,
|
|
1096
|
+
out: `${done.out}\n${freed.out}`,
|
|
1097
|
+
status: freed.code === 0 ? 'ready' : b.status,
|
|
1098
|
+
moved: freed.code === 0 ? 'ready' : null,
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
/**
|
|
1103
|
+
* 赤入れせずに 1 タップ検収(SPEC §5.2.3 / D15②)。
|
|
1104
|
+
*
|
|
1105
|
+
* `answer()` と同じ方針:
|
|
1106
|
+
* - 注釈待ち(blocked)のときだけ受け付ける(それ以外は NOT_WAITING)
|
|
1107
|
+
* - 同じ検収の再送は `duplicate` を返し、コメントを二重に付けず遷移だけ補完する
|
|
1108
|
+
*
|
|
1109
|
+
* 記録は `<image>.approval.json`(注釈の `.annotation.json` と同じ場所)。
|
|
1110
|
+
*
|
|
1111
|
+
* @param {string} id タスク ID
|
|
1112
|
+
* @param {{note?: string, by?: string, chat?: string}} [payload]
|
|
1113
|
+
*/
|
|
1114
|
+
async function approve(id, payload = {}) {
|
|
1115
|
+
const b = bodyOf(id)
|
|
1116
|
+
if (!b) return { ok: false, code: 'NOT_FOUND' }
|
|
1117
|
+
const ak = parseReviewLine(b.body)
|
|
1118
|
+
if (!ak?.image) return { ok: false, code: 'NO_IMAGE' }
|
|
1119
|
+
if (payload?.chat) rememberTaskChat(id, payload.chat)
|
|
1120
|
+
|
|
1121
|
+
const note = String(payload?.note ?? '').slice(0, 400)
|
|
1122
|
+
const by = String(payload?.by ?? 'mobile').slice(0, 40)
|
|
1123
|
+
const rel = ak.image.replace(/\.(png|jpe?g|webp)$/i, '.approval.json')
|
|
1124
|
+
const abs = path.join(path.resolve(workdir(), rel))
|
|
1125
|
+
const reason = `検収 OK(Visual check passed)${note ? `: ${note}` : ''}`
|
|
1126
|
+
|
|
1127
|
+
const existing = readJsonIfExists(abs)
|
|
1128
|
+
if (existing) {
|
|
1129
|
+
// 冪等: 記録済みならコメントは増やさない(遷移だけ補完)
|
|
1130
|
+
const adv = await approveAdvance(id, b, `${reason}(再送)`)
|
|
1131
|
+
return {
|
|
1132
|
+
ok: adv.code === 0,
|
|
1133
|
+
duplicate: true,
|
|
1134
|
+
status: adv.status,
|
|
1135
|
+
moved: adv.moved,
|
|
1136
|
+
files: { approval: rel },
|
|
1137
|
+
code: 'APPROVAL_ALREADY_RECORDED',
|
|
1138
|
+
output: adv.out.slice(0, 400),
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
if (b.status !== 'blocked') {
|
|
1142
|
+
return {
|
|
1143
|
+
ok: false,
|
|
1144
|
+
code: 'NOT_WAITING',
|
|
1145
|
+
status: b.status,
|
|
1146
|
+
params: { status: b.status },
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
const record = {
|
|
1151
|
+
task_id: id,
|
|
1152
|
+
label: ak.label ?? null,
|
|
1153
|
+
round: Number(ak.round ?? 1),
|
|
1154
|
+
image: ak.image,
|
|
1155
|
+
note,
|
|
1156
|
+
approved_by: by,
|
|
1157
|
+
approved_at: new Date().toISOString(),
|
|
1158
|
+
verdict: 'visual-check-passed',
|
|
1159
|
+
}
|
|
1160
|
+
fs.mkdirSync(path.dirname(abs), { recursive: true })
|
|
1161
|
+
fs.writeFileSync(abs, JSON.stringify(record, null, 2), 'utf8')
|
|
1162
|
+
|
|
1163
|
+
const comment = await runKanban(['comment', id, 'Visual check passed', '--author', by])
|
|
1164
|
+
if (comment.code !== 0) {
|
|
1165
|
+
// コメントが残せなかったら検収の記録も消す(再挑戦でコメントを落とさないため)
|
|
1166
|
+
try {
|
|
1167
|
+
fs.unlinkSync(abs)
|
|
1168
|
+
} catch {
|
|
1169
|
+
/* 既に消えていれば noop */
|
|
1170
|
+
}
|
|
1171
|
+
return {
|
|
1172
|
+
ok: false,
|
|
1173
|
+
code: 'COMMENT_FAILED',
|
|
1174
|
+
status: b.status,
|
|
1175
|
+
moved: null,
|
|
1176
|
+
output: comment.out.slice(0, 400),
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
const adv = await approveAdvance(id, b, reason)
|
|
1180
|
+
return {
|
|
1181
|
+
ok: adv.code === 0,
|
|
1182
|
+
duplicate: false,
|
|
1183
|
+
status: adv.status,
|
|
1184
|
+
moved: adv.moved,
|
|
1185
|
+
files: { approval: rel },
|
|
1186
|
+
output: `${comment.out}\n${adv.out}`.trim().slice(0, 600),
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
|
|
1191
|
+
/** 挿絵(workdir/thumbs/... の PNG/JPEG/WebP のみ)。 */
|
|
1192
|
+
function thumb(rel) {
|
|
1193
|
+
const s = String(rel || '')
|
|
1194
|
+
if (!s.startsWith('thumbs/') || !/\.(png|jpe?g|webp)$/i.test(s)) {
|
|
1195
|
+
return { ok: false, code: 'BAD_THUMB' }
|
|
1196
|
+
}
|
|
1197
|
+
const abs = resolveInside(s)
|
|
1198
|
+
if (!abs) return { ok: false, code: 'THUMB_MISSING' }
|
|
1199
|
+
const ext = path.extname(abs).toLowerCase()
|
|
1200
|
+
const type = ext === '.png' ? 'image/png' : ext === '.webp' ? 'image/webp' : 'image/jpeg'
|
|
1201
|
+
return { ok: true, data: fs.readFileSync(abs), type }
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
|
|
1205
|
+
/** 注釈の下地画像(annotated=true なら赤入れ済み、compare=true なら前回の赤入れ)。 */
|
|
1206
|
+
function image(id, opts = {}) {
|
|
1207
|
+
const b = bodyOf(id)
|
|
1208
|
+
if (!b) return { ok: false, code: 'NOT_FOUND' }
|
|
1209
|
+
const ak = parseReviewLine(b.body)
|
|
1210
|
+
if (!ak?.image) return { ok: false, code: 'NO_IMAGE' }
|
|
1211
|
+
let rel = ak.image
|
|
1212
|
+
if (opts?.compare) {
|
|
1213
|
+
// 比較(Before): 前回の赤入れ/前ラウンドの画像。無ければ 404 で UI がトグルを隠す
|
|
1214
|
+
const cmp = compareRelOf(id, ak, siblingIndex())
|
|
1215
|
+
if (!cmp) return { ok: false, code: 'NO_COMPARE' }
|
|
1216
|
+
rel = cmp
|
|
1217
|
+
} else if (opts?.annotated) {
|
|
1218
|
+
const jsonAbs = resolveInside(ak.image.replace(/\.(png|jpe?g)$/i, '.annotation.json'))
|
|
1219
|
+
const data = jsonAbs ? readJsonIfExists(jsonAbs) : null
|
|
1220
|
+
if (data?.annotated_image) rel = data.annotated_image
|
|
1221
|
+
}
|
|
1222
|
+
const abs = resolveInside(rel)
|
|
1223
|
+
if (!abs) return { ok: false, code: 'IMAGE_MISSING' }
|
|
1224
|
+
const ext = path.extname(abs).toLowerCase()
|
|
1225
|
+
const type = ext === '.png' ? 'image/png' : ext === '.webp' ? 'image/webp' : 'image/jpeg'
|
|
1226
|
+
return { ok: true, data: fs.readFileSync(abs), type, path: abs, rel }
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
/** 送信済みの注釈(無ければ null)。 */
|
|
1230
|
+
function annotation(id) {
|
|
1231
|
+
const b = bodyOf(id)
|
|
1232
|
+
if (!b) return { ok: false, code: 'NOT_FOUND' }
|
|
1233
|
+
const ak = parseReviewLine(b.body)
|
|
1234
|
+
if (!ak?.image) return { ok: false, code: 'NO_IMAGE' }
|
|
1235
|
+
const rel = ak.image.replace(/\.(png|jpe?g)$/i, '.annotation.json')
|
|
1236
|
+
const abs = resolveInside(rel)
|
|
1237
|
+
const data = abs ? readJsonIfExists(abs) : null
|
|
1238
|
+
if (!data) return { ok: false, code: 'NO_ANNOTATION' }
|
|
1239
|
+
return { ok: true, data, status: b.status }
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
/**
|
|
1243
|
+
* 注釈の送信。annotated_image は data URL(JPEG/PNG)。
|
|
1244
|
+
* 冪等: 同じ画像(sha256)の再送は duplicate を返し、遷移だけ補完する。
|
|
1245
|
+
*/
|
|
1246
|
+
async function saveAnnotation(id, payload) {
|
|
1247
|
+
const b = bodyOf(id)
|
|
1248
|
+
if (!b) return { ok: false, code: 'NOT_FOUND' }
|
|
1249
|
+
const ak = parseReviewLine(b.body)
|
|
1250
|
+
if (!ak?.image) return { ok: false, code: 'NO_IMAGE' }
|
|
1251
|
+
if (b.status !== 'blocked') {
|
|
1252
|
+
return { ok: false, code: 'NOT_WAITING', status: b.status, params: { status: b.status } }
|
|
1253
|
+
}
|
|
1254
|
+
if (payload?.chat) rememberTaskChat(id, payload.chat)
|
|
1255
|
+
|
|
1256
|
+
const raw = String(payload?.annotated_image || '')
|
|
1257
|
+
const m = /^data:(image\/(?:png|jpeg));base64,([A-Za-z0-9+/=]+)$/.exec(raw)
|
|
1258
|
+
if (!m) return { ok: false, code: 'BAD_IMAGE' }
|
|
1259
|
+
const buf = Buffer.from(m[2], 'base64')
|
|
1260
|
+
const MAX = 12 * 1024 * 1024
|
|
1261
|
+
if (buf.length > MAX) return { ok: false, code: 'TOO_LARGE' }
|
|
1262
|
+
|
|
1263
|
+
const baseAbs = resolveInside(ak.image)
|
|
1264
|
+
if (!baseAbs) return { ok: false, code: 'IMAGE_MISSING' }
|
|
1265
|
+
const sha = crypto.createHash('sha256').update(buf).digest('hex')
|
|
1266
|
+
const baseSha = crypto.createHash('sha256').update(fs.readFileSync(baseAbs)).digest('hex')
|
|
1267
|
+
const ext = m[1] === 'image/png' ? '.png' : '.jpg'
|
|
1268
|
+
const relAnnotated = ak.image.replace(/\.(png|jpe?g)$/i, `.annotated${ext}`)
|
|
1269
|
+
const relJson = ak.image.replace(/\.(png|jpe?g)$/i, '.annotation.json')
|
|
1270
|
+
const annotatedAbs = path.join(path.resolve(workdir(), relAnnotated))
|
|
1271
|
+
const jsonAbs = path.join(path.resolve(workdir(), relJson))
|
|
1272
|
+
|
|
1273
|
+
const existing = readJsonIfExists(jsonAbs)
|
|
1274
|
+
if (existing && existing.image_sha256 === sha) {
|
|
1275
|
+
let moved = { code: 0, out: '' }
|
|
1276
|
+
let status = b.status
|
|
1277
|
+
if (b.status === 'blocked') {
|
|
1278
|
+
moved = await runKanban(['unblock', id, '--reason', '注釈を受領(再送)'])
|
|
1279
|
+
if (moved.code === 0) status = 'ready'
|
|
1280
|
+
}
|
|
1281
|
+
return { ok: moved.code === 0, duplicate: true, status, moved: status, sha256: sha }
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
const marks = Array.isArray(payload?.marks) ? payload.marks.slice(0, 200) : []
|
|
1285
|
+
const note = String(payload?.note ?? '').slice(0, 2000)
|
|
1286
|
+
fs.mkdirSync(path.dirname(annotatedAbs), { recursive: true })
|
|
1287
|
+
fs.writeFileSync(annotatedAbs, buf)
|
|
1288
|
+
const record = {
|
|
1289
|
+
task_id: id,
|
|
1290
|
+
label: ak.label ?? null,
|
|
1291
|
+
round: Number(ak.round ?? 1),
|
|
1292
|
+
note,
|
|
1293
|
+
marks: marks.map((k) => ({
|
|
1294
|
+
tool: String(k?.tool ?? 'pen'),
|
|
1295
|
+
points: Array.isArray(k?.points) ? k.points.slice(0, 400) : [],
|
|
1296
|
+
})),
|
|
1297
|
+
base_image: ak.image,
|
|
1298
|
+
annotated_image: relAnnotated,
|
|
1299
|
+
base_sha256: baseSha,
|
|
1300
|
+
image_sha256: sha,
|
|
1301
|
+
annotated_at: new Date().toISOString(),
|
|
1302
|
+
}
|
|
1303
|
+
fs.writeFileSync(jsonAbs, JSON.stringify(record, null, 2), 'utf8')
|
|
1304
|
+
|
|
1305
|
+
const summary = `注釈: ${marks.length} ストローク${note ? ` / メモ: ${note.slice(0, 60)}` : ''} — ${relAnnotated}`
|
|
1306
|
+
const comment = await runKanban(['comment', id, summary, '--author', String(payload?.by ?? 'mobile')])
|
|
1307
|
+
let moved = { code: 0, out: '' }
|
|
1308
|
+
let status = b.status
|
|
1309
|
+
if (b.status === 'blocked') {
|
|
1310
|
+
moved = await runKanban(['unblock', id, '--reason', '注釈を受領'])
|
|
1311
|
+
if (moved.code === 0) status = 'ready'
|
|
1312
|
+
}
|
|
1313
|
+
return {
|
|
1314
|
+
ok: comment.code === 0 && moved.code === 0,
|
|
1315
|
+
duplicate: false,
|
|
1316
|
+
sha256: sha,
|
|
1317
|
+
files: { annotated: relAnnotated, json: relJson },
|
|
1318
|
+
marks: marks.length,
|
|
1319
|
+
status,
|
|
1320
|
+
moved: status,
|
|
1321
|
+
output: `${comment.out}\n${moved.out}`.trim().slice(0, 600),
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
|
|
1325
|
+
|
|
1326
|
+
|
|
1327
|
+
/**
|
|
1328
|
+
* 注釈の反映先として選べるリポジトリ(`repos.list()` が唯一の一覧)。
|
|
1329
|
+
* 自由入力は受けない(存在しないパスへ誤って起票しないため)。
|
|
1330
|
+
*/
|
|
1331
|
+
function targets() {
|
|
1332
|
+
const list = typeof opts.targets === 'function' ? opts.targets() : []
|
|
1333
|
+
if (!Array.isArray(list)) return []
|
|
1334
|
+
const out = []
|
|
1335
|
+
for (const r of list) {
|
|
1336
|
+
const abs = String(r?.path ?? '')
|
|
1337
|
+
const id = String(r?.id ?? '').trim()
|
|
1338
|
+
if (!abs || !id) continue
|
|
1339
|
+
out.push({ id, label: String(r.label ?? id), path: abs })
|
|
1340
|
+
}
|
|
1341
|
+
return out
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
/** target を登録済みリポジトリに解決する(未登録なら null)。 */
|
|
1345
|
+
function resolveTarget(raw) {
|
|
1346
|
+
const list = targets()
|
|
1347
|
+
if (!list.length) return null
|
|
1348
|
+
const want = raw ? path.resolve(String(raw).replace(/^~/, os.homedir())) : null
|
|
1349
|
+
if (want) return list.find((x) => x.path === want) || null
|
|
1350
|
+
return list.find((x) => x.id === 'hermes-mobile-pwa') || list[0]
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
/**
|
|
1354
|
+
* 反映先パス → 登録済みリポジトリ(**最長一致**)。
|
|
1355
|
+
*
|
|
1356
|
+
* macOS は大文字小文字を区別しないので比較は小文字で行う(実測: ボードの
|
|
1357
|
+
* `target=` は `~/projects/hermes-mobile-pwa` と `~/Projects/hermes-mobile-pwa`
|
|
1358
|
+
* が混在している)。`~/.hermes` のような広いリポジトリがあるため、短い一致で
|
|
1359
|
+
* 打ち切らず最長一致を採る。
|
|
1360
|
+
*/
|
|
1361
|
+
function repoForTarget(target) {
|
|
1362
|
+
const raw = String(target || '')
|
|
1363
|
+
if (!raw || !(raw.startsWith('/') || raw.startsWith('~'))) return null
|
|
1364
|
+
const abs = path.resolve(raw.replace(/^~/, os.homedir())).toLowerCase()
|
|
1365
|
+
let best = null
|
|
1366
|
+
for (const t of targets()) {
|
|
1367
|
+
const p = t.path.toLowerCase()
|
|
1368
|
+
if (abs !== p && !abs.startsWith(p + path.sep)) continue
|
|
1369
|
+
if (!best || p.length > best.p.length) best = { id: t.id, label: t.label, p }
|
|
1370
|
+
}
|
|
1371
|
+
return best ? { id: best.id, label: best.label } : null
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
/**
|
|
1375
|
+
* 画像 → 反映先リポジトリの手掛かり。
|
|
1376
|
+
*
|
|
1377
|
+
* 画像そのものにリポジトリ情報は無い(library の名前は取得時刻と slug だけ)。
|
|
1378
|
+
* レビューのタスク本文 `[review] label=… image=shots/x.png target=<path>` の対応を集め、
|
|
1379
|
+
* `image=` の完全一致 → `label=` の前方一致の順で当てる。撮影名は
|
|
1380
|
+
* `<label>-<stamp>-<round>.<kind>.png`(実測 33 枚中 27 枚がこれで解決)。
|
|
1381
|
+
*/
|
|
1382
|
+
function imageRepos() {
|
|
1383
|
+
const byImage = new Map()
|
|
1384
|
+
const byLabel = new Map()
|
|
1385
|
+
let db
|
|
1386
|
+
try {
|
|
1387
|
+
db = openDb()
|
|
1388
|
+
} catch {
|
|
1389
|
+
return { byImage, labels: [] }
|
|
1390
|
+
}
|
|
1391
|
+
let rs = []
|
|
1392
|
+
try {
|
|
1393
|
+
rs = db.prepare("SELECT body FROM tasks WHERE body LIKE '%[review]%' OR body LIKE '%[akapen]%'").all()
|
|
1394
|
+
} catch {
|
|
1395
|
+
rs = []
|
|
1396
|
+
} finally {
|
|
1397
|
+
db.close()
|
|
1398
|
+
}
|
|
1399
|
+
for (const r of rs) {
|
|
1400
|
+
const ak = parseReviewLine(r.body)
|
|
1401
|
+
if (!ak?.target) continue
|
|
1402
|
+
if (ak.image) byImage.set(String(ak.image), ak.target)
|
|
1403
|
+
if (ak.label) byLabel.set(String(ak.label), ak.target)
|
|
1404
|
+
}
|
|
1405
|
+
// ラベルは丸ごと一致しないことが多い(`sheet-form` の撮影名に対し
|
|
1406
|
+
// タスクは `sheet-form-202611121013`)。ハイフン境界で切った前方部分も候補にする。
|
|
1407
|
+
const labels = []
|
|
1408
|
+
for (const [label, target] of byLabel) {
|
|
1409
|
+
const parts = label.split('-')
|
|
1410
|
+
const seen = new Set()
|
|
1411
|
+
for (let i = parts.length; i >= 2; i--) {
|
|
1412
|
+
const cand = parts.slice(0, i).join('-')
|
|
1413
|
+
if (seen.has(cand)) continue
|
|
1414
|
+
seen.add(cand)
|
|
1415
|
+
labels.push([cand, target])
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
labels.sort((a, b) => b[0].length - a[0].length)
|
|
1419
|
+
return { byImage, labels }
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
/** 撮影名から target を引く(ハイフン境界だけを見る。部分文字列の誤爆を避ける)。 */
|
|
1423
|
+
function labelTarget(name, labels) {
|
|
1424
|
+
const ext = path.extname(name)
|
|
1425
|
+
for (const [label, target] of labels) {
|
|
1426
|
+
if (
|
|
1427
|
+
name === `${label}${ext}` ||
|
|
1428
|
+
name === label ||
|
|
1429
|
+
name.startsWith(`${label}-`) ||
|
|
1430
|
+
name.startsWith(`${label}.`) ||
|
|
1431
|
+
name.includes(`-${label}-`) ||
|
|
1432
|
+
name.includes(`-${label}.`)
|
|
1433
|
+
) {
|
|
1434
|
+
return target
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1437
|
+
return null
|
|
1438
|
+
}
|
|
1439
|
+
|
|
1440
|
+
/** 注釈の下地にできる画像(library/** と shots/*.png|jpg、注釈済みは除く)。 */
|
|
1441
|
+
function library(limit = 60) {
|
|
1442
|
+
const root = workdir()
|
|
1443
|
+
const items = []
|
|
1444
|
+
const { byImage, labels } = imageRepos()
|
|
1445
|
+
const exts = new Set(['.png', '.jpg', '.jpeg', '.webp'])
|
|
1446
|
+
const walk = (dir, source) => {
|
|
1447
|
+
let ents = []
|
|
1448
|
+
try {
|
|
1449
|
+
ents = fs.readdirSync(dir, { withFileTypes: true })
|
|
1450
|
+
} catch {
|
|
1451
|
+
return
|
|
1452
|
+
}
|
|
1453
|
+
for (const e of ents) {
|
|
1454
|
+
const abs = path.join(dir, e.name)
|
|
1455
|
+
if (e.isDirectory()) {
|
|
1456
|
+
walk(abs, source || e.name)
|
|
1457
|
+
continue
|
|
1458
|
+
}
|
|
1459
|
+
const ext = path.extname(e.name).toLowerCase()
|
|
1460
|
+
if (!exts.has(ext) || /\.(annotated|answer)\./.test(e.name)) continue
|
|
1461
|
+
let st
|
|
1462
|
+
try {
|
|
1463
|
+
st = fs.statSync(abs)
|
|
1464
|
+
} catch {
|
|
1465
|
+
continue
|
|
1466
|
+
}
|
|
1467
|
+
const rel = path.relative(root, abs)
|
|
1468
|
+
const target = byImage.get(rel) || labelTarget(e.name, labels)
|
|
1469
|
+
items.push({
|
|
1470
|
+
path: rel,
|
|
1471
|
+
source: source || (rel.startsWith('shots') ? 'capture' : 'library'),
|
|
1472
|
+
name: e.name,
|
|
1473
|
+
bytes: st.size,
|
|
1474
|
+
// 取得日時: 一覧の並びもこれ。library への取り込みは copy2 なので
|
|
1475
|
+
// 元画像の撮影時刻が残る(実測: chat の取り込み 1746 のファイルが 16:42)
|
|
1476
|
+
mtime: Math.round(st.mtimeMs),
|
|
1477
|
+
repo: repoForTarget(target), // 分からなければ null(UI は '—')
|
|
1478
|
+
target: target || null,
|
|
1479
|
+
})
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
walk(path.join(root, 'library'), '')
|
|
1483
|
+
walk(path.join(root, 'shots'), 'capture')
|
|
1484
|
+
items.sort((a, b) => b.mtime - a.mtime)
|
|
1485
|
+
return items.slice(0, limit)
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
/**
|
|
1489
|
+
* 作業フィード(内蔵 reviewWatcher が書く 1 行ログ)。
|
|
1490
|
+
*
|
|
1491
|
+
* 旧来は外部 cron(`mobile-akapen-watch`)が Discord と `plugin-data/akapen/feed.jsonl` を
|
|
1492
|
+
* 書いていた。D7 でブリッジ内蔵の `reviewWatcher` に移し、`review/feed.jsonl` をここから読む。
|
|
1493
|
+
*
|
|
1494
|
+
* @param {number} [limit] 末尾から何行読むか(1..200)
|
|
1495
|
+
* @param {number} [since] この epoch ms より新しい行だけ返す(0 なら全部)
|
|
1496
|
+
* @returns {Array<{at: number, text: string}>} 古い順
|
|
1497
|
+
*/
|
|
1498
|
+
function feed(limit = 20, since = 0) {
|
|
1499
|
+
const file = path.join(reviewRoot(), 'feed.jsonl')
|
|
1500
|
+
let raw = ''
|
|
1501
|
+
try {
|
|
1502
|
+
raw = readTailText(file, 128 * 1024)
|
|
1503
|
+
} catch {
|
|
1504
|
+
return [] // まだ 1 行も無いだけなので空でよい
|
|
1505
|
+
}
|
|
1506
|
+
const tail = raw.split('\n').filter((l) => l.trim()).slice(-Math.min(200, Math.max(1, Number(limit) || 20)))
|
|
1507
|
+
const out = []
|
|
1508
|
+
for (const line of tail) {
|
|
1509
|
+
try {
|
|
1510
|
+
const j = JSON.parse(line)
|
|
1511
|
+
const at = Date.parse(String(j.at ?? ''))
|
|
1512
|
+
if (!Number.isFinite(at)) continue
|
|
1513
|
+
if (since && at <= Number(since)) continue
|
|
1514
|
+
out.push({ at, text: String(j.text ?? '') })
|
|
1515
|
+
} catch {
|
|
1516
|
+
// 書きかけ・壊れた行は捨てる(フィードは補助情報)
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
return out
|
|
1520
|
+
}
|
|
1521
|
+
|
|
1522
|
+
/**
|
|
1523
|
+
* レビューの完了報告の生データ(監視 cron `mobile-review-watch` が書く 1 行/タスク)。
|
|
1524
|
+
*
|
|
1525
|
+
* 1 会話だけを見る `chatReport` と、全会話を見る `chatReports` の共通読み取り。
|
|
1526
|
+
* ファイルが無い(=宛先つきのタスクがまだ完了していない)のは正常なので空で返す。
|
|
1527
|
+
*
|
|
1528
|
+
* @returns {Array<{at: number, sessionId: string, taskId: string, label: string|null, text: string}>} 古い順
|
|
1529
|
+
*/
|
|
1530
|
+
function readChatReportRows() {
|
|
1531
|
+
const file = path.join(reviewRoot(), 'chat-reports.jsonl')
|
|
1532
|
+
let raw = ''
|
|
1533
|
+
try {
|
|
1534
|
+
raw = readTailText(file, 256 * 1024)
|
|
1535
|
+
} catch {
|
|
1536
|
+
return []
|
|
1537
|
+
}
|
|
1538
|
+
const taskChats = readTaskChats()
|
|
1539
|
+
const out = []
|
|
1540
|
+
for (const line of raw.split('\n')) {
|
|
1541
|
+
if (!line.trim()) continue
|
|
1542
|
+
try {
|
|
1543
|
+
const j = JSON.parse(line)
|
|
1544
|
+
const at = Date.parse(String(j.at ?? ''))
|
|
1545
|
+
if (!Number.isFinite(at)) continue
|
|
1546
|
+
const taskId = String(j.task_id ?? '')
|
|
1547
|
+
let sessionId = String(j.session_id ?? '')
|
|
1548
|
+
if (!sessionId && taskId) {
|
|
1549
|
+
sessionId = taskChats[taskId] || sanitizeChatId(parseReviewLine(bodyOf(taskId)?.body)?.chat) || ''
|
|
1550
|
+
}
|
|
1551
|
+
if (!sessionId) continue
|
|
1552
|
+
// パイプライン統合レポート(`kind: 'pipeline'`)の追加フィールドは**透過的に**保持する。
|
|
1553
|
+
// 既存のレビュー 1 行レポート(at/session_id/task_id/label/text だけ)は今まで通り。
|
|
1554
|
+
out.push({
|
|
1555
|
+
at,
|
|
1556
|
+
sessionId,
|
|
1557
|
+
taskId,
|
|
1558
|
+
label: j.label ?? null,
|
|
1559
|
+
text: String(j.text ?? ''),
|
|
1560
|
+
kind: j.kind ? String(j.kind) : null,
|
|
1561
|
+
status: j.status ? String(j.status) : null,
|
|
1562
|
+
board: j.board ? String(j.board) : null,
|
|
1563
|
+
spec: j.spec ? String(j.spec) : null,
|
|
1564
|
+
repoPath: j.repo_path ? String(j.repo_path) : null,
|
|
1565
|
+
markdown: typeof j.markdown === 'string' ? j.markdown : '',
|
|
1566
|
+
followUpPrompt: typeof j.follow_up_prompt === 'string' ? j.follow_up_prompt : '',
|
|
1567
|
+
counts: j.counts && typeof j.counts === 'object' && !Array.isArray(j.counts) ? j.counts : null,
|
|
1568
|
+
})
|
|
1569
|
+
} catch {
|
|
1570
|
+
// 書きかけ・壊れた行は捨てる(補助情報)
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
return out
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1576
|
+
/**
|
|
1577
|
+
* ある会話に流すレビューの完了報告(監視 cron `mobile-review-watch` が書く)。
|
|
1578
|
+
*
|
|
1579
|
+
* 完了報告は Discord と作業フィードにしか出ておらず、**起票した会話**には戻らなかった
|
|
1580
|
+
* (実測: 回答 22:19 → 完了 22:26 の報告を、会話を開いても読めない)。起票時に本文へ
|
|
1581
|
+
* `chat=<session_id>` を書いたタスクだけ、完了の 1 行をその会話へ返す。
|
|
1582
|
+
*
|
|
1583
|
+
* @param {string} sessionId 会話のセッション ID
|
|
1584
|
+
* @param {{limit?: number, since?: number}} [opts] 末尾何件・この epoch ms より新しい行だけ
|
|
1585
|
+
* @returns {Array<{at: number, taskId: string, label: string|null, text: string}>} 古い順
|
|
1586
|
+
*/
|
|
1587
|
+
function chatReport(sessionId, opts = {}) {
|
|
1588
|
+
const id = String(sessionId ?? '').slice(0, 128)
|
|
1589
|
+
if (!id) return []
|
|
1590
|
+
const limit = Math.min(Math.max(Number(opts.limit) || 3, 1), 50)
|
|
1591
|
+
const since = Number(opts.since) || 0
|
|
1592
|
+
const out = readChatReportRows()
|
|
1593
|
+
.filter((r) => r.sessionId === id)
|
|
1594
|
+
.filter((r) => !since || r.at > since)
|
|
1595
|
+
.map(({ sessionId: _sid, ...rest }) => rest)
|
|
1596
|
+
return out.slice(-limit)
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
/**
|
|
1600
|
+
* 全会話ぶんの完了報告(未読の点を出すため)。
|
|
1601
|
+
*
|
|
1602
|
+
* 下部ナビのチャットタブと「会話」一覧の行に点を出すには「どの会話に新着があるか」を
|
|
1603
|
+
* 1 回で知る必要がある。会話ごとに問い合わせると N 回になるので、絞らずに返して
|
|
1604
|
+
* 端末側で既読時刻(localStorage)と突き合わせる。
|
|
1605
|
+
*
|
|
1606
|
+
* @param {{limit?: number, since?: number}} [opts] 末尾何件(既定 200)・この epoch ms より新しい行だけ
|
|
1607
|
+
* @returns {Array<{at: number, sessionId: string, taskId: string, label: string|null, text: string}>} 古い順
|
|
1608
|
+
*/
|
|
1609
|
+
function chatReports(opts = {}) {
|
|
1610
|
+
const limit = Math.min(Math.max(Number(opts.limit) || 200, 1), 500)
|
|
1611
|
+
const since = Number(opts.since) || 0
|
|
1612
|
+
const out = readChatReportRows().filter((r) => !since || r.at > since)
|
|
1613
|
+
return out.slice(-limit)
|
|
1614
|
+
}
|
|
1615
|
+
|
|
1616
|
+
/** library の画像を返す(allowlist 内のみ)。 */
|
|
1617
|
+
function libraryFile(rel) {
|
|
1618
|
+
if (!isSafeRel(rel)) return { ok: false, code: 'BAD_PATH' }
|
|
1619
|
+
const lower = String(rel).toLowerCase()
|
|
1620
|
+
if (!(lower.startsWith('library/') || lower.startsWith('shots/'))) {
|
|
1621
|
+
return { ok: false, code: 'OUTSIDE' }
|
|
1622
|
+
}
|
|
1623
|
+
if (!/\.(png|jpe?g|webp)$/.test(lower)) return { ok: false, code: 'BAD_EXT' }
|
|
1624
|
+
const abs = resolveInside(rel)
|
|
1625
|
+
if (!abs) return { ok: false, code: 'NOT_FOUND' }
|
|
1626
|
+
const ext = path.extname(abs).toLowerCase()
|
|
1627
|
+
const type = ext === '.png' ? 'image/png' : ext === '.webp' ? 'image/webp' : 'image/jpeg'
|
|
1628
|
+
return { ok: true, data: fs.readFileSync(abs), type }
|
|
1629
|
+
}
|
|
1630
|
+
|
|
1631
|
+
const slugOf = (s) =>
|
|
1632
|
+
String(s || 'anno')
|
|
1633
|
+
.toLowerCase()
|
|
1634
|
+
.replace(/[^a-z0-9._-]+/g, '-')
|
|
1635
|
+
.replace(/^-+|-+$/g, '')
|
|
1636
|
+
.slice(0, 40) || 'anno'
|
|
1637
|
+
|
|
1638
|
+
/**
|
|
1639
|
+
* 画像から注釈タスクを1件作る(upload の dataURL / library・shots の既存ファイル)。
|
|
1640
|
+
* 成功したら taskId を返すので、PWA はそのまま注釈エディタを開ける。
|
|
1641
|
+
*/
|
|
1642
|
+
async function createFromImage(payload) {
|
|
1643
|
+
const source = String(payload?.source || 'upload')
|
|
1644
|
+
const title = String(payload?.title || '').slice(0, 120) || '注釈(画像から作成)'
|
|
1645
|
+
let buf = null
|
|
1646
|
+
let ext = '.png'
|
|
1647
|
+
|
|
1648
|
+
if (source === 'upload') {
|
|
1649
|
+
const m = /^data:(image\/(?:png|jpeg));base64,([A-Za-z0-9+/=]+)$/.exec(String(payload?.image || ''))
|
|
1650
|
+
if (!m) return { ok: false, code: 'BAD_IMAGE' }
|
|
1651
|
+
buf = Buffer.from(m[2], 'base64')
|
|
1652
|
+
ext = m[1] === 'image/png' ? '.png' : '.jpg'
|
|
1653
|
+
if (buf.length > 12 * 1024 * 1024) return { ok: false, code: 'TOO_LARGE' }
|
|
1654
|
+
} else {
|
|
1655
|
+
const rel = String(payload?.path || '')
|
|
1656
|
+
if (!isSafeRel(rel)) return { ok: false, code: 'BAD_PATH' }
|
|
1657
|
+
if (!(rel.toLowerCase().startsWith('library/') || rel.toLowerCase().startsWith('shots/'))) {
|
|
1658
|
+
return { ok: false, code: 'OUTSIDE' }
|
|
1659
|
+
}
|
|
1660
|
+
const abs = resolveInside(rel)
|
|
1661
|
+
if (!abs) return { ok: false, code: 'NOT_FOUND' }
|
|
1662
|
+
buf = fs.readFileSync(abs)
|
|
1663
|
+
const e = path.extname(abs).toLowerCase()
|
|
1664
|
+
ext = e === '.jpg' || e === '.jpeg' ? '.jpg' : e === '.webp' ? '.webp' : '.png'
|
|
1665
|
+
}
|
|
1666
|
+
|
|
1667
|
+
const stamp = new Date()
|
|
1668
|
+
.toISOString()
|
|
1669
|
+
.slice(0, 16)
|
|
1670
|
+
.replace(/[-:T]/g, '')
|
|
1671
|
+
.slice(0, 12)
|
|
1672
|
+
const label = `${slugOf(payload?.slug || title)}-${stamp}`
|
|
1673
|
+
const relShot = `shots/${label}-1${ext}`
|
|
1674
|
+
const shotAbs = path.join(path.resolve(workdir(), relShot))
|
|
1675
|
+
fs.mkdirSync(path.dirname(shotAbs), { recursive: true })
|
|
1676
|
+
fs.writeFileSync(shotAbs, buf)
|
|
1677
|
+
|
|
1678
|
+
// 注釈の反映先は登録済みリポジトリから選ぶ(自由入力は受けない)
|
|
1679
|
+
const picked = resolveTarget(payload?.target)
|
|
1680
|
+
if (!picked) {
|
|
1681
|
+
return {
|
|
1682
|
+
ok: false,
|
|
1683
|
+
code: 'UNKNOWN_TARGET',
|
|
1684
|
+
targets: targets().map((x) => ({ id: x.id, label: x.label })),
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
const target = picked.path
|
|
1688
|
+
// 起票した会話へ完了報告を返す宛先(レビュー chat-badge-01 q1=A の「紐づけ」)。
|
|
1689
|
+
// 注釈タスクは bridge が本文を組み立てるので、端末が渡さないと `chat=` が付かず
|
|
1690
|
+
// 完了が会話に戻らない(従来の宛先つきはレビューシート経由だけだった)。
|
|
1691
|
+
const chat = sanitizeChatId(payload?.chat)
|
|
1692
|
+
const body =
|
|
1693
|
+
`[review] label=${label} round=1 mode=annotation image=${relShot} target=${target}` + (chat ? ` chat=${chat}` : '')
|
|
1694
|
+
// assignee が無いと dispatcher が拾わない(実測: ready のまま止まる)
|
|
1695
|
+
const created = await runKanban(['create', title, '--body', body, '--assignee', 'mobile'])
|
|
1696
|
+
const m = /t_[0-9a-f]{8}/.exec(created.out || '')
|
|
1697
|
+
if (created.code !== 0 || !m) {
|
|
1698
|
+
return { ok: false, code: 'CREATE_FAILED', message: created.out.slice(0, 300) }
|
|
1699
|
+
}
|
|
1700
|
+
const taskId = m[0]
|
|
1701
|
+
if (chat) rememberTaskChat(taskId, chat)
|
|
1702
|
+
const blocked = await runKanban(['block', taskId, '注釈待ち(画像から作成)', '--kind', 'needs_input'])
|
|
1703
|
+
return {
|
|
1704
|
+
ok: blocked.code === 0,
|
|
1705
|
+
taskId,
|
|
1706
|
+
image: relShot,
|
|
1707
|
+
label,
|
|
1708
|
+
blocked: blocked.code === 0,
|
|
1709
|
+
output: blocked.out.slice(0, 300),
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
|
|
1713
|
+
/**
|
|
1714
|
+
* タスクの宛先チャット(本文の `chat=` → `task-chats.json`)。
|
|
1715
|
+
* reviewWatcher が完了報告の宛先を決めるのに使う(SPEC §4.3)。
|
|
1716
|
+
*/
|
|
1717
|
+
function chatFor(id) {
|
|
1718
|
+
const b = bodyOf(id)
|
|
1719
|
+
const fromBody = sanitizeChatId(parseReviewLine(b?.body)?.chat)
|
|
1720
|
+
if (fromBody) return fromBody
|
|
1721
|
+
return readTaskChats()[id] || null
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
return {
|
|
1725
|
+
board,
|
|
1726
|
+
workdir,
|
|
1727
|
+
dataRoot,
|
|
1728
|
+
reviewRoot,
|
|
1729
|
+
chatFor,
|
|
1730
|
+
list,
|
|
1731
|
+
sheetHtml,
|
|
1732
|
+
sheetData,
|
|
1733
|
+
answer,
|
|
1734
|
+
reopen,
|
|
1735
|
+
approve,
|
|
1736
|
+
sessionId,
|
|
1737
|
+
image,
|
|
1738
|
+
annotation,
|
|
1739
|
+
saveAnnotation,
|
|
1740
|
+
thumb,
|
|
1741
|
+
library,
|
|
1742
|
+
libraryFile,
|
|
1743
|
+
createFromImage,
|
|
1744
|
+
targets,
|
|
1745
|
+
feed,
|
|
1746
|
+
chatReport,
|
|
1747
|
+
chatReports,
|
|
1748
|
+
}
|
|
1749
|
+
}
|