Steam-style achievements for using this marketplace's skills: a toast on unlock, an /achievements pane, trophy:list in conversation, and a view of which skills…

English · 한국어
Steam-style achievements for using this marketplace's skills. Use a skill and a ◆ plugin:skill toast shows it; an unlock adds a toast and a gold card above the prompt (8 s) telling you what you unlocked; /achievements shows what you have, what is locked and how far along you are, and which of your prompts contained a skill's trigger phrase without the skill running. It also keeps a local record of this marketplace's skills and MCP tools failing (the Failures tab). Anonymous daily counts and fixed error codes go to the maintainer only if you say yes. Off by default.
It is a Claude Code hooks module (hooks/mod.tsx). It needs Claude Code 2.1.292 or later and an interactive session; removing the modules line from hooks/hooks.json leaves nothing behind.
/plugin install trophy@newkayak12-claude-skills
/plugin uninstall trophy@newkayak12-claude-skills
The UI is in English by default and switches to Korean when Claude Code's language setting is Korean; the consent question lists the same data in both languages. This file and KOR.md move together.
| I want to… | Do |
|---|---|
| See my achievements and progress | /achievements (a pane: Achievements, Triggers and Failures tabs) |
| See what failed | the Failures tab, or View on the ✘ N trophy <last failure> row above the prompt |
| Report a problem with the last skill | /trophy-bug <note> (the note stays local; only the code user_report can be sent) |
| See them in the conversation | the trophy:list skill (reads ~/.claude/trophy/profile.json) |
| Turn anonymous counts on / off / check | /trophy-telemetry on, off, status |
A skill use is recorded when it runs: typed as /name, called by the model through the Skill tool, or preloaded. The 80 achievements are in data/achievements.ts: first use of each plugin, collecting 1–100 distinct skills (overall and per plugin), streaks from 3 to 365 days, repeat counts of favourite skills, 15 skill combos in one session, and 5 hidden ones.
A failure is recorded when one of this marketplace's skills fails to load or reports no success, one of its MCP tools fails, or a harness run writes a failed subgoal or goal gate (harness outcomes stay local). Each record keeps the failing plugin's version and the Claude Code release. The raw error text stays on your machine; the Copy button copies it as a bug body.
Keyboard: only the consent question has keys. ctrl+x tab focuses the band, then press s/n/p, or move with Tab/arrows and Enter. Esc returns; ctrl+x ctrl+a collapses the band.
Sessions that are not interactive (claude -p, so every teams/graph adapter session) record nothing.
Real captures from Claude Code 2.1.293 (terminal, English UI).
The gold card above the prompt right after a skill unlocks an achievement.
/achievements: the Achievements tab with unlocked rows and ▰▱ progress on locked ones.
The Triggers tab: a prompt had write:writer-verification's trigger phrase but the skill did not run.
The Failures tab with a /trophy-bug report and its Copy button.
The consent question above the prompt; nothing is sent until you answer.
Show contents: the exact JSON of the next send (here 0 events).
/trophy-telemetry status after declining. (Older capture: status now also shows the last send.)
Nothing is sent unless you opt in. Once your first achievement unlocks, trophy asks in a double-framed box above the prompt (what is sent, what is never sent, and three buttons drawn alike); [Show contents] shows the exact JSON of the next send before you decide. Until you answer, nothing leaves your machine. Declining is remembered; it is never asked again. The answer is saved with the version of the question (v3 adds plugin and Claude Code versions, OS type and run results): a yes given to an older question (v1, v2) is asked once more, and trophy sends nothing until you answer. A no is never re-asked.
When you answer yes ([Send] or /trophy-telemetry on) the days up to yesterday are sent at once, and the reply or toast says how many events went. After that the plugin sends again at the start of the first interactive session of each new UTC day, to PostHog (https://us.i.posthog.com/batch/, the maintainer's project). Events are dated by the day they count, not by the send time. Per day:
| Event | Properties |
|---|---|
skill_used | skill name, plugin name, day, count, plugin_version |
trigger_result | skill name, day, counts of: prompt had its trigger phrase and the skill ran / did not run / ran without a phrase; plugin_version |
achievement_unlocked | achievement id |
plugins_installed | plugin name, day — one per plugin of this marketplace whose skills the session lists |
daily_active | day, Claude Code release (cc_version), OS type (darwin, linux, win32, other), sessions |
mcp_tool_result | day, plugin name, MCP tool name, ok and error counts, plugin_version |
run_outcome | day, system (graph, teams, harness), outcome (pass, reject, fail), count |
diag_* | skill, plugin, MCP tool name, error code (reason), count, day, the plugin's version (plugin_version) and the Claude Code release (cc_version) — fixed codes; no messages, paths or prompts. |
$exception | the message of a failure inside this module, with every file path replaced by <path>, 300 characters at most |
Every event also carries a random install id (made on first run, not derived from you or your machine) and $process_person_profile: false. Never sent: prompt text, working directory, project or file names, file paths, session ids, your username or email. The PostHog project discards client IP addresses ("Discard client IP data" is on); the project token in the code is write-only.
A failed send changes nothing and is tried again at the next interactive start or /trophy-telemetry on.
What the new rows mean:
sessions counts interactive session starts that day (resume, /clear and a mod reload may each count). A day reached only because a session stayed open past midnight UTC sends sessions: 0.ok is transport ok: the tool answered without isError. A tool that returns {"error": …} as a normal result counts as ok.run_outcome counts the outcomes the graph, teams and harness mods saw and published (no ids, only the two labels), not runs. pass / (pass + reject + fail) is not a per-run success rate. One run can count several outcomes (a graph run that is blocked and later completes counts fail and pass; a harness run with a failed subgoal and a failed goal gate counts fail and reject). Runs that end outside an interactive session, or in a session closed before the end, are not counted, and the same outcome seen by two open sessions counts twice.Turn it off: /trophy-telemetry off (stored in the Claude Code store; takes effect at once), or uninstall the plugin. /trophy-telemetry status shows the current answer and the last send (when, which days, how many events, the result). Locally, everything the mod keeps is in Claude Code's plugin store and ~/.claude/trophy/profile.json (achievements and counts, no prompts).
trophy:listPrints the same lists as the pane as a table, from ~/.claude/trophy/profile.json: unlocked achievements with dates, locked ones with progress bars (hidden ones as ???), and the 7-day trigger view (most hit, most missed, never fired).
skill.prompt hooks still record: the plugin also listens to the Skill tool call and to the typed-command expansion; one use is counted once.PostToolUseFailure never runs, so no diag_mcp_error or skill is_error code is recorded there. MCP counts use tool.call, which still runs.mcp_tool_result.error counts every isError result; diag_mcp_error counts only where PostToolUseFailure runs. The two can disagree and neither is derived from the other.subgoal_failed and goal_failed come only from the outcome the harness mod publishes; trophy no longer reads harness files or gate output (records no longer carry the run slug).tool.call), run outcomes the graph, teams and harness mods publish, a last-send line in /trophy-telemetry status, consent text v3.trophy:list; Claude hooks and achievements are unchanged.portfolio:feedback-beta and assist skills.done no longer fires inside abandoned..codex-plugin/plugin.json, ${PLUGIN_ROOT}); Claude reads them from plugin.json.mods plugin: one ◆ <plugin:skill> toast per Skill tool call of this marketplace, skipped when that call unlocks an achievement (the 🏆 toast stands for it). Interactive sessions only.View [v], a new Dismiss [d] (clears the badge without opening the pane), the pane tabs [t] [r] [f], and the consent buttons s/n/p. /achievements opens the pane with the keys. What is recorded or sent, and the consent version, are unchanged.anyUnlocked and lang, so claude plugin validate passes again (0.6.0 failed it; the mod still loaded and worked). No behaviour change.language is Korean: every pane, band and command reply, and all 80 achievements (the Korean text kept as it was). The consent question now stands out: a double-framed box with what is sent and what is never sent on their own lines and three buttons drawn alike; what is sent, when it is asked and the consent version are unchanged. Real Claude Code captures EN/KO.✘ row, /trophy-bug) and, on the same yes, sends diag_* codes with the plugin and Claude Code versions. Every other plugin of this marketplace now lists trophy in dependencies, so installing one installs trophy.diag_* rows listed in the telemetry table./skill commands are recorded: under a team organization skill.prompt and UserPromptExpansion are skipped for user-tier hooks, so the typed command is now read from prompt.submit (raw or expanded form).hooks/mod.tsx 793 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import { achievements } from '../data/achievements.ts'
5import { triggers } from '../data/triggers.ts'
6import {
7 achievementRow,
8 cells,
9 addActivity,
10 addMcp,
11 addOutcome,
12 addTurn,
13 buildBatch,
14 buildProfile,
15 closeTurn,
16 CONSENT_VERSION,
17 dayOf,
18 effectiveConsent,
19 evaluate,
20 markActive,
21 matchTriggers,
22 osOf,
23 outcomeOf,
24 ownedMcpByName,
25 POSTHOG_URL,
26 recordUse,
27 resolveSkill,
28 scrub,
29 sumDays,
30 triggerLists,
31 typedCommand,
32} from './logic.ts'
33import type { Achievement, Activity, BatchStore, DayCounts, McpCalls, Os, Outcomes, System, Use, Versions } from './logic.ts'
34import {
35 appendEntry, copyBody, marketplaceCandidates, newest, outcomeFailure, ownedMcpTool, ownedSkill,
36 rowDetail, rowTitle,
37} from './failures.ts'
38import type { Entry } from './failures.ts'
39
40const active = atom({ plugin: 'trophy', key: 'active' } as const, false)
41const turnMatched = atom({ plugin: 'trophy', key: 'turnMatched' } as const, [] as string[])
42const turnFired = atom({ plugin: 'trophy', key: 'turnFired' } as const, [] as string[])
43const turnTyped = atom({ plugin: 'trophy', key: 'turnTyped' } as const, false)
44const tab = atom({ plugin: 'trophy', key: 'tab' } as const, 'trophies' as 'trophies' | 'triggers' | 'failures')
45const consent = atom({ plugin: 'trophy', key: 'consent' } as const, 'unasked' as 'unasked' | 'yes' | 'no')
46const celebrate = atom({ plugin: 'trophy', key: 'celebrate' } as const, null as { ids: string[]; until: number } | null)
47const consentVersion = atom({ plugin: 'trophy', key: 'consentVersion' } as const, 0)
48// The consent question waits for the first unlock: nothing is asked at a bare start.
49const anyUnlocked = atom({ plugin: 'trophy', key: 'anyUnlocked' } as const, false)
50// The last `plugin:skill` of this marketplace used or typed; failures recorded since the pane last showed them.
51const lastSkill = atom({ plugin: 'trophy', key: 'lastSkill' } as const, '')
52const unseen = atom({ plugin: 'trophy', key: 'unseen' } as const, 0)
53const lastTitle = atom({ plugin: 'trophy', key: 'lastTitle' } as const, '')
54const lang = atom({ plugin: 'trophy', key: 'lang' } as const, 'en' as 'en' | 'ko')
55// The last UTC day this session was counted active; a session left open past midnight marks the new day on its next prompt.
56const lastActiveDay = atom({ plugin: 'trophy', key: 'lastActiveDay' } as const, '')
57
58const CARD_MS = 8000
59const BAR = 10
60const PANE = 'trophy'
61const BATCH_PANE = 'trophy-batch'
62type Consent = 'unasked' | 'yes' | 'no'
63
64// The one place consent changes: the store keeps it, the state redraws the band.
65async function setConsent($: EngineInterface, value: Consent) {
66 await $.store.set('trophy.consent', value)
67 await $.store.set('trophy.consentVersion', CONSENT_VERSION)
68 await update($, consent, () => value)
69 await update($, consentVersion, () => CONSENT_VERSION)
70}
71
72const DAY_MS = 86_400_000
73const MARKETPLACE_PLUGINS = new Set(triggers.map(t => t.plugin))
74const TEXT_MAX = 2000
75
76const en = {
77 paneTitle: 'Achievements', previewTitle: 'Telemetry preview',
78 cmdAchievements: 'Show your skill achievements',
79 cmdTelemetry: 'Anonymous usage counts: on, off or status',
80 cmdBug: "Report a problem with this marketplace's last skill; the note stays local",
81 bugUsage: 'usage: /trophy-bug <note>', bugRecorded: 'Recorded.', bugFailed: 'Could not record the report.',
82 paneOpened: 'Achievements pane opened.', unlockedCount: '{done} / {n} unlocked',
83 tabTrophies: 'Achievements', tabTriggers: 'Triggers', tabFailures: 'Failures',
84 copy: 'Copy', noFailures: 'No failures recorded.',
85 headHit: 'Most-hit skills (7 days)', headMiss: 'Most-missed skills (had a trigger phrase, not used)',
86 headNever: 'Never-used skills ({n})',
87 telemetryUsage: 'usage: /trophy-telemetry on|off|status',
88 telemetryReconsent: 'unasked (earlier yes — needs re-consent)',
89 consentAsk: '📊 trophy · Send anonymous usage stats?',
90 consentSent: 'Sent: skill and tool names · daily counts · run results · error codes · plugin/Claude Code versions · OS type',
91 consentNotSent: 'Never sent: prompts · file paths · project or task names',
92 lastSendNone: 'last send: none yet',
93 lastSend: 'last send: {at} · days {from}–{through} · {events} events · {result}',
94 lastSendFirst: 'last send: {at} · first send, through {through} · {events} events · {result}',
95 sendNow: 'trophy telemetry: yes — sent {events} events ({result})',
96 sendNotDue: 'trophy telemetry: yes — nothing due (sent through {through})',
97 send: 'Send', decline: "Don't send", show: 'Show contents',
98 unlockHead: '🏆 Achievement unlocked!', see: 'View',
99}
100
101// one table, two languages; the type keeps the keys identical
102export const STRINGS: Record<'en' | 'ko', Record<keyof typeof en, string>> = {
103 en,
104 ko: {
105 paneTitle: '업적', previewTitle: '전송 내용 미리보기',
106 cmdAchievements: '스킬 업적 보기',
107 cmdTelemetry: '익명 사용 통계: on, off, status',
108 cmdBug: '이 마켓플레이스의 마지막 스킬 문제 신고 (메모는 로컬에만 저장)',
109 bugUsage: '사용법: /trophy-bug <메모>', bugRecorded: '기록했습니다.', bugFailed: '신고를 기록하지 못했습니다.',
110 paneOpened: '업적 창을 열었습니다.', unlockedCount: '{done} / {n} 해금',
111 tabTrophies: '업적', tabTriggers: '트리거', tabFailures: '실패',
112 copy: '복사', noFailures: '기록된 실패가 없습니다.',
113 headHit: '가장 많이 맞은 스킬 (7일)', headMiss: '가장 많이 놓친 스킬 (트리거 문구는 있었는데 안 쓴)',
114 headNever: '한 번도 안 쓴 스킬 ({n})',
115 telemetryUsage: '사용법: /trophy-telemetry on|off|status',
116 telemetryReconsent: 'unasked (이전 동의 — 재동의 필요)',
117 consentAsk: '📊 trophy · 익명 사용 통계를 보낼까요?',
118 consentSent: '보내는 것: 스킬·도구 이름 · 일별 횟수 · 실행 결과 · 오류 코드 · 플러그인/Claude Code 버전 · OS 종류',
119 consentNotSent: '보내지 않는 것: 프롬프트 · 파일 경로 · 프로젝트/작업 이름',
120 lastSendNone: '마지막 전송: 아직 없음',
121 lastSend: '마지막 전송: {at} · {from}–{through} · 이벤트 {events}개 · {result}',
122 lastSendFirst: '마지막 전송: {at} · 첫 전송, {through}까지 · 이벤트 {events}개 · {result}',
123 sendNow: 'trophy telemetry: yes — 이벤트 {events}개 전송 ({result})',
124 sendNotDue: 'trophy telemetry: yes — 보낼 것 없음 ({through}까지 전송됨)',
125 send: '보내기', decline: '안 보내기', show: '내용 보기',
126 unlockHead: '🏆 업적 해금!', see: '보기',
127 },
128}
129
130const fmt = (text: string | undefined, vars: Record<string, string | number> = {}) =>
131 (text ?? '').replace(/\{(\w+)\}/g, (_, k: string) => String(vars[k] ?? ''))
132// An achievement's title and description in the session's language (the top-level fields are English).
133const localize = (a: Achievement, l: 'en' | 'ko'): Achievement => (l === 'ko' ? { ...a, ...a.ko } : a)
134const str = async ($: EngineInterface, key: keyof typeof en, vars?: Record<string, string | number>) =>
135 fmt(STRINGS[await read($, lang)][key], vars)
136
137type Owned = { skills: Record<string, string[]>; servers: Record<string, string[]>; versions: Record<string, string> }
138
139// What this marketplace ships and at which version, read once per session from $.plugin.root; empty when
140// unreadable, so no failure is recorded (fails toward privacy). `cc` is Claude Code's release.
141let owned: Owned = { skills: {}, servers: {}, versions: {} }
142let cc = ''
143// A label from HOME/USERPROFILE, computed once per session; the variables themselves are never kept.
144let os: Os = 'other'
145
146const readJson = async ($: EngineInterface, path: string) => JSON.parse(await $.fs.read(path))
147
148async function loadOwned($: EngineInterface): Promise<Owned> {
149 const out: Owned = { skills: {}, servers: {}, versions: {} }
150 const parts = String($.plugin.root).replace(/\/+$/, '').split('/')
151 for (const path of marketplaceCandidates($.plugin.root, parts[parts.length - 3])) {
152 let plugins: { name: string; version?: unknown; source?: unknown }[]
153 try {
154 plugins = (await readJson($, path)).plugins
155 } catch {
156 continue // try the next candidate
157 }
158 const base = path.slice(0, -'/.claude-plugin/marketplace.json'.length)
159 for (const p of plugins) {
160 out.skills[p.name] = []
161 out.servers[p.name] = []
162 if (typeof p.version === 'string') out.versions[p.name] = p.version
163 if (typeof p.source !== 'string' || !p.source.startsWith('./')) continue
164 const dir = `${base}/${p.source.slice(2)}`
165 try {
166 const entries = (await $.fs.list(`${dir}/skills`)) as { name: string; kind: string }[]
167 out.skills[p.name] = entries.filter(x => x.kind === 'dir').map(x => x.name)
168 } catch {}
169 try {
170 const manifest = await readJson($, `${dir}/.claude-plugin/plugin.json`).catch(() => ({}))
171 const inline = manifest.mcpServers
172 out.servers[p.name] = Object.keys(
173 inline && typeof inline === 'object' ? inline : ((await readJson($, `${dir}/.mcp.json`)).mcpServers ?? {}),
174 )
175 } catch {}
176 }
177 break
178 }
179 return out
180}
181
182async function record($: EngineInterface, entry: Omit<Entry, 'ts' | 'day' | 'session' | 'version' | 'cc'>) {
183 const ts = await $.clock.now()
184 const session = await $.session.id()
185 const log = ((await $.store.get('trophy.failures')) ?? []) as Entry[]
186 const version = entry.plugin ? owned.versions[entry.plugin] : undefined
187 const full: Entry = { ...entry, ts, day: dayOf(ts), session, ...(version ? { version } : {}), ...(cc ? { cc } : {}) }
188 await $.store.set('trophy.failures', appendEntry(log, full))
189 if (entry.kind === 'bug' || entry.kind === 'outcome') {
190 await update($, unseen, n => n + 1)
191 await update($, lastTitle, () => rowTitle(full))
192 }
193}
194
195// Recording a failure never changes what the engine returns: any failure here is swallowed.
196const safe = async (work: () => Promise<unknown>) => {
197 try {
198 await work()
199 } catch {}
200}
201
202const cut = (v: unknown) => String(v ?? '').slice(0, TEXT_MAX)
203
204const showFailures = async ($: EngineInterface) => {
205 await update($, unseen, () => 0)
206 await update($, tab, () => 'failures')
207 await $.ui.open({ id: PANE, title: await str($, 'paneTitle') })
208}
209
210// Every hook fails open: the event goes on, and the failure is kept (scrubbed) for the next send.
211async function failOpen($: EngineInterface, e: unknown, next: any) {
212 try {
213 const errors = (((await $.store.get('trophy.errors')) ?? []) as BatchStore['errors']).slice(-49)
214 const day = dayOf(await $.clock.now())
215 await $.store.set('trophy.errors', [...errors, { day, message: scrub(String(next.error?.message ?? 'hook failed')) }])
216 } catch {
217 // keeping the error is best effort
218 }
219 return next(e)
220}
221
222async function readBatchStore($: EngineInterface): Promise<BatchStore> {
223 const get = async (key: string, empty: unknown) => (await $.store.get(key)) ?? empty
224 return {
225 installId: String(await get('trophy.installId', '')),
226 sentThrough: (await $.store.get('trophy.sentThrough')) as string | undefined,
227 uses: (await get('trophy.uses', [])) as Use[],
228 triggers: (await get('trophy.triggers', {})) as DayCounts,
229 unlocked: (await get('trophy.unlocked', {})) as Record<string, string>,
230 errors: (await get('trophy.errors', [])) as BatchStore['errors'],
231 plugins: (await get('trophy.plugins', {})) as Record<string, string[]>,
232 failures: (await get('trophy.failures', [])) as Entry[],
233 versions: (await get('trophy.versions', {})) as Versions,
234 activity: (await get('trophy.activity', {})) as Activity,
235 mcpCalls: (await get('trophy.mcpCalls', {})) as McpCalls,
236 outcomes: (await get('trophy.outcomes', {})) as Outcomes,
237 }
238}
239
240const yesterday = async ($: EngineInterface) => dayOf((await $.clock.now()) - DAY_MS)
241
242// Which of this marketplace's plugins the session lists skills from, kept per day.
243async function recordPlugins($: EngineInterface) {
244 const usage = await $.session.usage({ breakdown: 'summary' })
245 const names = (usage.context.breakdown?.skills?.skillFrontmatter ?? []).flatMap(s =>
246 s.pluginName && MARKETPLACE_PLUGINS.has(s.pluginName) ? [s.pluginName] : [],
247 )
248 if (names.length === 0) return
249 const day = dayOf(await $.clock.now())
250 const all = ((await $.store.get('trophy.plugins')) ?? {}) as Record<string, string[]>
251 await $.store.set('trophy.plugins', { ...all, [day]: [...new Set([...(all[day] ?? []), ...names])].sort() })
252}
253
254type LastSend = {
255 at: string
256 from: string | null
257 through: string
258 events: number
259 result: string
260 error?: string
261}
262type SendOutcome = { due: false; through: string | undefined } | { due: true; last: LastSend }
263
264// One send at a time: a button press and a session start share the same promise.
265let sending: Promise<SendOutcome> | null = null
266
267// Sends the days not yet sent, up to yesterday, for a person who said yes; a failed send changes nothing
268// but is recorded in `trophy.lastSend`. Nothing due: no fetch and `lastSend` stays.
269function sendIfDue($: EngineInterface): Promise<SendOutcome> {
270 sending ??= sendDue($).finally(() => {
271 sending = null
272 })
273 return sending
274}
275
276async function sendDue($: EngineInterface): Promise<SendOutcome> {
277 const sent = (await $.store.get('trophy.sentThrough')) as string | undefined
278 const answer = effectiveConsent(
279 (await $.store.get('trophy.consent')) as Consent | undefined,
280 (await $.store.get('trophy.consentVersion')) as number | undefined,
281 )
282 const through = await yesterday($)
283 if (answer !== 'yes' || (sent !== undefined && sent >= through)) return { due: false, through: sent }
284 const body = buildBatch(await readBatchStore($), through)
285 const last: LastSend = {
286 at: new Date(await $.clock.now()).toISOString(), from: sent ?? null, through, events: body.batch.length, result: 'empty',
287 }
288 let landed = true
289 if (body.batch.length > 0) {
290 try {
291 const res = await $.http.fetch(POSTHOG_URL, {
292 method: 'POST',
293 headers: { 'content-type': 'application/json' },
294 body: JSON.stringify(body),
295 })
296 last.result = res.ok ? 'ok' : `http_${res.status}`
297 landed = res.ok
298 } catch (err) {
299 last.result = 'error'
300 last.error = scrub(String((err as { message?: unknown })?.message ?? err))
301 landed = false
302 }
303 }
304 if (landed) {
305 const errors = (((await $.store.get('trophy.errors')) ?? []) as BatchStore['errors']).filter(e => e.day > through)
306 await $.store.set('trophy.errors', errors)
307 await $.store.set('trophy.sentThrough', through)
308 }
309 await $.store.set('trophy.lastSend', last)
310 return { due: true, last }
311}
312
313// The one line `on` and the Send button answer with.
314async function sendLine($: EngineInterface): Promise<string> {
315 const r = await sendIfDue($).catch(() => undefined)
316 if (r?.due) return str($, 'sendNow', { events: r.last.events, result: r.last.result })
317 return str($, 'sendNotDue', { through: r?.through ?? '-' })
318}
319
320async function lastSendLine($: EngineInterface): Promise<string> {
321 const last = (await $.store.get('trophy.lastSend')) as LastSend | undefined
322 if (!last) return str($, 'lastSendNone')
323 const vars = { at: last.at, from: last.from ?? '', through: last.through, events: last.events, result: last.result }
324 return str($, last.from === null ? 'lastSendFirst' : 'lastSend', vars)
325}
326
327export async function countOutcome($: EngineInterface, system: System, value: unknown) {
328 const hit = outcomeOf(value, system)
329 if (!hit) return
330 const outcomes = ((await $.store.get('trophy.outcomes')) ?? {}) as Outcomes
331 await $.store.set('trophy.outcomes', addOutcome(outcomes, dayOf(await $.clock.now()), hit.system, hit.outcome))
332}
333
334// The file trophy:list reads. Written after every store change; a failed write never blocks the prompt.
335async function mirror($: EngineInterface) {
336 try {
337 const get = async (key: string, empty: unknown) => (await $.store.get(key)) ?? empty
338 const profile = buildProfile(
339 (await get('trophy.uses', [])) as Use[],
340 (await get('trophy.unlocked', {})) as Record<string, string>,
341 (await get('trophy.triggers', {})) as DayCounts,
342 achievements,
343 triggers,
344 await $.clock.now(),
345 )
346 await $.fs.write(`${await $.env.get('HOME')}/.claude/trophy/profile.json`, JSON.stringify(profile, null, 2))
347 } catch {
348 // the mirror is a convenience
349 }
350}
351
352// Records one skill use; always called before `next`, so a throw here falls to the hook's `.catch`.
353// Returns true when this use unlocked an achievement (its 🏆 toast then stands for the skill toast).
354async function note($: EngineInterface, name: string): Promise<boolean> {
355 if (!(await read($, active))) return false
356 const hit = resolveSkill(name, triggers)
357 if (!hit) return false
358 const uses = ((await $.store.get('trophy.uses')) ?? []) as Use[]
359 const now = await $.clock.now()
360 const recorded = recordUse(uses, hit.skill, now, await $.session.id())
361 await $.store.set('trophy.uses', recorded)
362 await update($, turnFired, list => [...list, hit.skill])
363
364 const unlocked = ((await $.store.get('trophy.unlocked')) ?? {}) as Record<string, string>
365 const fresh = evaluate(recorded, achievements, unlocked)
366 if (fresh.length > 0) {
367 await $.store.set('trophy.unlocked', { ...unlocked, ...Object.fromEntries(fresh.map(id => [id, dayOf(now)])) })
368 await update($, anyUnlocked, () => true)
369 const l = await read($, lang)
370 for (const a of achievements.filter(a => fresh.includes(a.id)).map(a => localize(a, l))) {
371 $.ui.toast(`🏆 ${a.title} — ${a.description}`)
372 }
373 // The card lists every unlock of the last few seconds; the timer clears it and redraws the band.
374 const until = now + CARD_MS
375 await update($, celebrate, card => ({ ids: [...(card && card.until > now ? card.ids : []), ...fresh], until }))
376 $.clock.after(CARD_MS, () => {
377 void update($, celebrate, card => (card && card.until === until ? null : card))
378 })
379 }
380 await mirror($)
381 return fresh.length > 0
382}
383
384export const register: Register = on => {
385 // Non-interactive sessions (every `claude -p`, so every teams/graph adapter) stay idle.
386 on('session.start', async ($, e, next) => {
387 if ((await $.session.surfaces()).length === 0) return next(e)
388
389 // The stored answer first: until then the band stays hidden, so a yes never flashes the question.
390 const savedVersion = (await $.store.get('trophy.consentVersion')) as number | undefined
391 // An older yes reads as unasked (the band asks once more); the stored value stays until answered.
392 const saved = effectiveConsent((await $.store.get('trophy.consent')) as Consent | undefined, savedVersion)
393 await update($, consent, () => saved)
394 await update($, consentVersion, () => savedVersion ?? 0)
395 const unlocked = ((await $.store.get('trophy.unlocked')) ?? {}) as Record<string, string>
396 await update($, anyUnlocked, () => Object.keys(unlocked).length > 0)
397 await update($, active, () => true)
398 await update($, lastSkill, () => '')
399 await update($, unseen, () => 0)
400 await update($, lastTitle, () => '')
401 // Claude Code's own language setting, read once per session, before the commands are described
402 const language = ((await $.settings.read().catch(() => ({}))) as { language?: unknown }).language
403 await update($, lang, () => (typeof language === 'string' && /^(ko|korean|한국어)/i.test(language) ? 'ko' : 'en'))
404 owned = await loadOwned($).catch(() => ({ skills: {}, servers: {}, versions: {} }))
405 cc = (await $.session.version().catch(() => undefined))?.base ?? ''
406 if ((await $.store.get('trophy.installId')) === undefined) {
407 await $.store.set('trophy.installId', crypto.randomUUID())
408 }
409 await $.command.register({
410 name: 'achievements',
411 description: await str($, 'cmdAchievements'),
412 })
413 await $.command.register({
414 name: 'trophy-telemetry',
415 description: await str($, 'cmdTelemetry'),
416 argumentHint: 'on|off|status',
417 })
418 await $.command.register({
419 name: 'trophy-bug',
420 description: await str($, 'cmdBug'),
421 argumentHint: '<note>',
422 })
423 await recordPlugins($).catch(() => {})
424 await safe(async () => {
425 os = osOf(await $.env.get('HOME'), await $.env.get('USERPROFILE'))
426 const day = dayOf(await $.clock.now())
427 if (Object.keys(owned.versions).length > 0) {
428 const versions = ((await $.store.get('trophy.versions')) ?? {}) as Versions
429 await $.store.set('trophy.versions', { ...versions, [day]: { ...versions[day], ...owned.versions } })
430 }
431 const activity = ((await $.store.get('trophy.activity')) ?? {}) as Activity
432 await $.store.set('trophy.activity', addActivity(activity, day, cc, os))
433 await update($, lastActiveDay, () => day)
434 })
435 await sendIfDue($).catch(() => {})
436
437 return next(e)
438 }).catch(failOpen)
439
440 // skill.prompt is skipped for user-tier hooks under some organizations' policy (00-spike-findings),
441 // so the Skill tool and the typed command report the same uses.
442 on('skill.prompt', async ($, e, next) => {
443 await note($, e.skill)
444 return next(e)
445 }).catch(failOpen)
446
447 // Also: the Skill tool answered but the skill did not succeed; remembers the last owned skill.
448 on('tool.call', { tool: 'Skill' }, async ($, e, next) => {
449 const unlocked = await note($, e.skill)
450 const result = await next(e)
451 if (e.tool !== 'Skill' || !(await read($, active))) return result
452 await safe(async () => {
453 const hit = ownedSkill(e.skill, owned.skills)
454 if (!hit) return
455 if (!unlocked) $.ui.toast(`◆ ${hit.plugin}:${hit.skill}`)
456 await update($, lastSkill, () => `${hit.plugin}:${hit.skill}`)
457 const r = result as { deny?: string; isError?: boolean; result?: any }
458 if (r.deny !== undefined || r.isError || !r.result || r.result.success !== false) return
459 const forked = r.result.status === 'forked'
460 await record($, {
461 kind: 'bug',
462 reason: forked ? 'forked_unsuccessful' : 'unsuccessful',
463 plugin: hit.plugin,
464 skill: hit.skill,
465 local: forked ? { text: cut(r.result.result) } : {},
466 })
467 })
468 return result
469 }).catch(failOpen)
470
471 // Counts this marketplace's MCP tools once per call: isError decides ok or error. Names only; the result goes back unchanged.
472 on('tool.call', async ($, e, next) => {
473 const tool = String(e.tool)
474 if (!tool.startsWith('mcp__plugin_') || !(await read($, active))) return next(e)
475 const result = await next(e)
476 await safe(async () => {
477 const hit = ownedMcpByName(tool, owned.servers)
478 if (!hit) return
479 const kind = (result as { isError?: unknown } | undefined)?.isError === true ? 'error' : 'ok'
480 const calls = ((await $.store.get('trophy.mcpCalls')) ?? {}) as McpCalls
481 await $.store.set('trophy.mcpCalls', addMcp(calls, dayOf(await $.clock.now()), hit.plugin, hit.tool, kind))
482 })
483 return result
484 }).catch(failOpen)
485
486 // Run outcomes the graph, teams and harness mods publish: only the system and the outcome label are counted.
487 on('state.set', { plugin: 'graph', key: 'outcome' }, async ($, e, next) => {
488 const result = await next(e)
489 await safe(async () => {
490 if (await read($, active)) await countOutcome($, 'graph', e.value)
491 })
492 return result
493 }).catch(failOpen)
494 on('state.set', { plugin: 'teams', key: 'outcome' }, async ($, e, next) => {
495 const result = await next(e)
496 await safe(async () => {
497 if (await read($, active)) await countOutcome($, 'teams', e.value)
498 })
499 return result
500 }).catch(failOpen)
501 on('state.set', { plugin: 'harness', key: 'outcome' }, async ($, e, next) => {
502 const result = await next(e)
503 await safe(async () => {
504 if (!(await read($, active))) return
505 await countOutcome($, 'harness', e.value)
506 const reason = outcomeFailure(e.value)
507 if (reason) await record($, { kind: 'outcome', reason, local: {} })
508 })
509 return result
510 }).catch(failOpen)
511
512 // An owned skill failed to load, or an owned MCP tool failed. An interrupt is the person's, not a bug.
513 on('classic.PostToolUseFailure', async ($, e, next) => {
514 if (!(await read($, active)) || e.is_interrupt === true) return next(e)
515 await safe(async () => {
516 const text = cut(e.error)
517 if (e.tool_name === 'Skill') {
518 const hit = ownedSkill((e.tool_input as { skill?: unknown } | undefined)?.skill, owned.skills)
519 if (hit) await record($, { kind: 'bug', reason: 'is_error', plugin: hit.plugin, skill: hit.skill, local: { text } })
520 return
521 }
522 const mcp = ownedMcpTool(e.tool_name, e.mcp_server, owned.servers)
523 if (mcp) await record($, { kind: 'bug', reason: 'mcp_error', plugin: mcp.plugin, tool: mcp.tool, local: { text } })
524 })
525 return next(e)
526 }).catch(failOpen)
527
528 // `/trophy-bug <note>`: the note stays local; only the code `user_report` can be sent.
529 on('command.run', { command: 'trophy-bug' }, async ($, e) => {
530 const note = e.args.trim()
531 if (!note) return { text: await str($, 'bugUsage') }
532 try {
533 const hit = ownedSkill(await read($, lastSkill), owned.skills)
534 await record($, {
535 kind: 'report',
536 reason: 'user_report',
537 ...(hit ? { plugin: hit.plugin, skill: hit.skill } : {}),
538 local: { note: cut(note) },
539 })
540 return { text: await str($, 'bugRecorded') }
541 } catch {
542 return { text: await str($, 'bugFailed') }
543 }
544 }).catch(failOpen)
545
546 on('classic.UserPromptExpansion', async ($, e, next) => {
547 if (e.expansion_type === 'slash_command') await note($, e.command_name)
548 return next(e)
549 }).catch(failOpen)
550
551 // A prompt's trigger phrases are matched on the way in and judged against the skills that fired when the turn ends.
552 on('prompt.submit', async ($, e, next) => {
553 if (await read($, active)) {
554 await safe(async () => {
555 const day = dayOf(await $.clock.now())
556 if (day === (await read($, lastActiveDay))) return
557 const activity = ((await $.store.get('trophy.activity')) ?? {}) as Activity
558 await $.store.set('trophy.activity', markActive(activity, day, cc, os))
559 await update($, lastActiveDay, () => day)
560 })
561 await update($, turnMatched, () => matchTriggers(e.text, triggers))
562 await update($, turnFired, () => [])
563 const typed = typedCommand(e.text)
564 await update($, turnTyped, () => typed !== undefined)
565 // The one path that still sees a typed skill when skill.prompt and UserPromptExpansion are skipped.
566 if (typed) await note($, typed)
567 // Only a name this marketplace ships becomes the last skill; whatever else was typed is never stored.
568 const hit = ownedSkill(typed, owned.skills)
569 if (hit) await update($, lastSkill, () => `${hit.plugin}:${hit.skill}`)
570 }
571 return next(e)
572 }).catch(failOpen)
573
574 on('turn.complete', async ($, e, next) => {
575 if ((await read($, active)) && e.agentId === undefined && !(await read($, turnTyped))) {
576 const turn = closeTurn(await read($, turnMatched), await read($, turnFired))
577 await update($, turnMatched, () => [])
578 await update($, turnFired, () => [])
579 if (turn.hit.length + turn.miss.length + turn.unmatched.length > 0) {
580 const counts = ((await $.store.get('trophy.triggers')) ?? {}) as DayCounts
581 await $.store.set('trophy.triggers', addTurn(counts, dayOf(await $.clock.now()), turn))
582 await mirror($)
583 }
584 }
585 return next(e)
586 }).catch(failOpen)
587
588 // The pane opens only from its command.
589 on('command.run', { command: 'achievements' }, async $ => {
590 if ((await read($, tab)) === 'failures') await update($, unseen, () => 0)
591 await $.ui.open({ id: PANE, title: await str($, 'paneTitle') })
592 return { text: await str($, 'paneOpened') }
593 }).catch(failOpen)
594
595 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
596 const { Box, Button, Text } = $.ui.resolve(e)
597 const lang$ = await read($, lang)
598 const current = await read($, tab)
599 const t = (key: keyof typeof en, vars?: Record<string, string | number>) => fmt(STRINGS[lang$][key], vars)
600 const unlocked = ((await $.store.get('trophy.unlocked')) ?? {}) as Record<string, string>
601 const done = Object.keys(unlocked).length
602 const filled = achievements.length === 0 ? 0 : Math.round((done / achievements.length) * BAR)
603 const header = (
604 <Box borderStyle="round" borderColor="claude">
605 <Text key="count" bold>
606 {'▰'.repeat(filled)}
607 {'▱'.repeat(BAR - filled)} {t('unlockedCount', { done, n: achievements.length })}{' '}
608 </Text>
609 <Button
610 key="tab-trophies"
611 label={t('tabTrophies')}
612 variant={current === 'trophies' ? 'primary' : undefined}
613 onPress={() => update($, tab, () => 'trophies')}
614 />
615 <Button
616 key="tab-triggers"
617 label={t('tabTriggers')}
618 variant={current === 'triggers' ? 'primary' : undefined}
619 onPress={() => update($, tab, () => 'triggers')}
620 />
621 <Button
622 key="tab-failures"
623 label={t('tabFailures')}
624 variant={current === 'failures' ? 'primary' : undefined}
625 onPress={() => showFailures($)}
626 />
627 </Box>
628 )
629
630 if (current === 'failures') {
631 const rows = newest(((await $.store.get('trophy.failures')) ?? []) as Entry[])
632 return (
633 <Box flexDirection="column">
634 {header}
635 {rows.length === 0 && <Text dimColor>{t('noFailures')}</Text>}
636 {rows.map((r, i) => (
637 <Box key={`fail-${i}`} flexDirection="column" borderStyle="round" borderColor="error" borderDimColor paddingX={1}>
638 <Box justifyContent="space-between" gap={1}>
639 <Box flexShrink={1}>
640 <Text color="error">✘ </Text>
641 <Text wrap="truncate-end">{rowTitle(r)}</Text>
642 </Box>
643 <Box flexShrink={0}>
644 <Button
645 key={`copy-${i}`}
646 label={t('copy')}
647 onPress={press => {
648 void $.ui.copy({ text: copyBody(r), surface: press.surface }).catch(() => {})
649 }}
650 />
651 </Box>
652 </Box>
653 {rowDetail(r).map((line, j) => <Text key={`d-${i}-${j}`} dimColor>{line}</Text>)}
654 </Box>
655 ))}
656 </Box>
657 )
658 }
659
660 if (current === 'triggers') {
661 const counts = ((await $.store.get('trophy.triggers')) ?? {}) as DayCounts
662 const lists = triggerLists(sumDays(counts, dayOf(await $.clock.now()), 7), triggers)
663 const never = lists.never.slice(0, 5).join(', ')
664 return (
665 <Box flexDirection="column">
666 {header}
667 <Text bold color="success">{t('headHit')}</Text>
668 {lists.hit.map(([skill, n]) => (
669 <Text key={`hit-${skill}`}>{skill} · {n}</Text>
670 ))}
671 <Text bold color="warning">{t('headMiss')}</Text>
672 {lists.miss.map(([skill, n]) => (
673 <Text key={`miss-${skill}`}>{skill} · {n}</Text>
674 ))}
675 <Text bold color="subtle">{t('headNever', { n: lists.never.length })}</Text>
676 <Text dimColor wrap="truncate-end">{never}</Text>
677 </Box>
678 )
679 }
680
681 const uses = ((await $.store.get('trophy.uses')) ?? []) as Use[]
682 return (
683 <Box flexDirection="column">
684 {header}
685 {achievements.map(a => (
686 <Box key={`row-${a.id}`} gap={1}>
687 {unlocked[a.id] ? (
688 <Text key="mark" color="success">✔</Text>
689 ) : (
690 <Text key="mark" dimColor>○</Text>
691 )}
692 <Text key="row" wrap="truncate-end">{achievementRow(localize(a, lang$), uses, unlocked[a.id], false)}</Text>
693 {unlocked[a.id] || a.hidden ? null : (
694 <Text key="bar" color="claude" wrap="truncate-end">{cells(a, uses)}</Text>
695 )}
696 </Box>
697 ))}
698 </Box>
699 )
700 }).catch(failOpen)
701
702 on('command.run', { command: 'trophy-telemetry' }, async ($, e) => {
703 const arg = e.args.trim()
704 if (arg === 'on') {
705 await setConsent($, 'yes')
706 return { text: await sendLine($) }
707 }
708 if (arg === 'off') {
709 await setConsent($, 'no')
710 return { text: 'trophy telemetry: no' }
711 }
712 if (arg === 'status') {
713 const now = await read($, consent)
714 const old = now === 'unasked' && (await $.store.get('trophy.consent')) === 'yes'
715 const answer = old ? await str($, 'telemetryReconsent') : now === 'yes' ? `yes (v${CONSENT_VERSION})` : now
716 return { text: `trophy telemetry: ${answer} · ${await lastSendLine($)}` }
717 }
718 return { text: await str($, 'telemetryUsage') }
719 }).catch(failOpen)
720
721 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
722 if (e.props.hasSurvey || !(await read($, active))) return next(e)
723
724 const { Box, Button, Text } = $.ui.resolve(e)
725 const lang$ = await read($, lang)
726 const t = (key: keyof typeof en) => STRINGS[lang$][key]
727 const asking = (await read($, consent)) === 'unasked' && (await read($, anyUnlocked))
728 const card = await read($, celebrate)
729 const shown = card && card.until > (await $.clock.now()) ? achievements.filter(a => card.ids.includes(a.id)).map(a => localize(a, lang$)) : []
730 const failed = await read($, unseen)
731 if (!asking && shown.length === 0 && failed === 0) return next(e)
732
733 const mine = (
734 <Box flexDirection="column">
735 {asking ? (
736 // a question, not a notice: a double frame, every line in full, three buttons drawn alike (no nudge to yes)
737 <Box key="consent" flexDirection="column" borderStyle="double" borderColor="warning" paddingX={1}>
738 <Text bold color="warning">{t('consentAsk')}</Text>
739 <Text>{` ${t('consentSent')}`}</Text>
740 <Text>{` ${t('consentNotSent')}`}</Text>
741 <Box marginTop={1} marginLeft={3} columnGap={3}>
742 <Button key="send" hotkey="s" plain label={t('send')} onPress={async () => {
743 await setConsent($, 'yes')
744 $.ui.toast(await sendLine($))
745 }} />
746 <Button key="decline" hotkey="n" plain label={t('decline')} onPress={() => setConsent($, 'no')} />
747 <Button key="show" hotkey="p" plain label={t('show')} onPress={() => $.ui.open({ id: BATCH_PANE, title: t('previewTitle') })} />
748 </Box>
749 </Box>
750 ) : null}
751 {shown.length > 0 ? (
752 <Box key="celebrate" borderStyle="round" borderColor="#d4a017" flexDirection="column" paddingX={1}>
753 <Text key="head" bold color="#d4a017">{t('unlockHead')}</Text>
754 {shown.map(a => (
755 <Text key={`card-${a.id}`} wrap="truncate-end">
756 <Text bold>{a.title}</Text> — {a.description}
757 </Text>
758 ))}
759 </Box>
760 ) : null}
761 {failed > 0 ? (
762 <Box key="failed" gap={1}>
763 <Box flexShrink={0}><Text color="error" bold>{`✘ ${failed}`}</Text></Box>
764 <Box flexShrink={0}><Text dimColor>trophy</Text></Box>
765 <Box flexShrink={1}><Text wrap="truncate-end">{await read($, lastTitle)}</Text></Box>
766 <Box flexShrink={0}><Button key="see" label={t('see')} onPress={() => showFailures($)} /></Box>
767 </Box>
768 ) : null}
769 </Box>
770 )
771 return (
772 <Box flexDirection="column">
773 {mine}
774 {await next(e)}
775 </Box>
776 )
777 }).catch(failOpen)
778
779 // Exactly what the next send would carry.
780 on('ui.render', { component: 'Pane', requestId: BATCH_PANE }, async ($, e) => {
781 const { Box, Text } = $.ui.resolve(e)
782 const body = buildBatch(await readBatchStore($), await yesterday($))
783 return (
784 <Box flexDirection="column">
785 <Text dimColor>POST {POSTHOG_URL} — {body.batch.length} events</Text>
786 <Box borderStyle="round" borderDimColor>
787 <Text>{JSON.stringify(body, null, 2)}</Text>
788 </Box>
789 </Box>
790 )
791 }).catch(failOpen)
792}
793data/achievements.ts 85 lines1import type { Achievement } from '../hooks/logic.ts'
2
3export const achievements: Achievement[] = [
4 { id: 'first-blood', title: 'First Blood', description: 'Your first skill. Here we go', ko: { title: 'First Blood', description: '첫 스킬을 썼다. 이제 시작이다' }, rule: { kind: 'collect', count: 1 } },
5 { id: 'first-develop', title: 'Hello, World', description: 'First develop use', ko: { title: 'Hello, World', description: 'develop 첫 사용' }, rule: { kind: 'first_use', plugin: 'develop' } },
6 { id: 'first-think', title: 'Thinking Cap On', description: 'First think use', ko: { title: '생각의 시작', description: 'think 첫 사용' }, rule: { kind: 'first_use', plugin: 'think' } },
7 { id: 'first-write', title: 'First Sentence', description: 'First write use', ko: { title: '첫 문장', description: 'write 첫 사용' }, rule: { kind: 'first_use', plugin: 'write' } },
8 { id: 'first-knowledge', title: 'Library Card', description: 'First knowledge use', ko: { title: '도서관 출입증', description: 'knowledge 첫 사용' }, rule: { kind: 'first_use', plugin: 'knowledge' } },
9 { id: 'first-agents', title: 'You Have Minions Now', description: 'First agents use', ko: { title: '부하 직원이 생겼다', description: 'agents 첫 사용' }, rule: { kind: 'first_use', plugin: 'agents' } },
10 { id: 'first-planning', title: 'Everything Goes to Plan', description: 'First planning use', ko: { title: '다 계획이 있구나', description: 'planning 첫 사용' }, rule: { kind: 'first_use', plugin: 'planning' } },
11 { id: 'first-skill', title: 'Into the Meta', description: 'First skill use — skills driving skills', ko: { title: '메타의 세계로', description: 'skill 첫 사용 — 스킬로 스킬을 다룬다' }, rule: { kind: 'first_use', plugin: 'skill' } },
12 { id: 'first-completion', title: 'The Art of Finishing', description: 'First completion use', ko: { title: '끝맺음의 미학', description: 'completion 첫 사용' }, rule: { kind: 'first_use', plugin: 'completion' } },
13 { id: 'first-portfolio', title: 'Résumé Dusted Off', description: 'First portfolio use', ko: { title: '이력서를 꺼냈다', description: 'portfolio 첫 사용' }, rule: { kind: 'first_use', plugin: 'portfolio' } },
14 { id: 'first-cognition', title: 'Brain Upgrade', description: 'First cognition use', ko: { title: '뇌 업그레이드', description: 'cognition 첫 사용' }, rule: { kind: 'first_use', plugin: 'cognition' } },
15 { id: 'first-harness', title: 'Seatbelt On', description: 'First harness use', ko: { title: '안전벨트 착용', description: 'harness 첫 사용' }, rule: { kind: 'first_use', plugin: 'harness' } },
16 { id: 'first-graph', title: 'Nodes and Edges', description: 'First graph use', ko: { title: '노드와 엣지', description: 'graph 첫 사용' }, rule: { kind: 'first_use', plugin: 'graph' } },
17 { id: 'first-teams', title: 'Team Assembled', description: 'First teams use', ko: { title: '팀 결성', description: 'teams 첫 사용' }, rule: { kind: 'first_use', plugin: 'teams' } },
18 { id: 'collector-10', title: 'Collector', description: '10 different skills', ko: { title: '수집가', description: '서로 다른 스킬 10종' }, rule: { kind: 'collect', count: 10 } },
19 { id: 'collector-30', title: 'Filling the Dex', description: '30 different skills', ko: { title: '도감 채우는 중', description: '서로 다른 스킬 30종' }, rule: { kind: 'collect', count: 30 } },
20 { id: 'collector-50', title: 'Half-Mad Collector', description: '50 different skills', ko: { title: '반쯤 미친 수집가', description: '서로 다른 스킬 50종' }, rule: { kind: 'collect', count: 50 } },
21 { id: 'collector-80', title: 'Skill Hoarder', description: '80 different skills', ko: { title: '스킬 호더', description: '서로 다른 스킬 80종' }, rule: { kind: 'collect', count: 80 } },
22 { id: 'collector-100', title: 'Dex Complete (Almost)', description: '100 different skills. Seriously?', ko: { title: '도감 완성(거의)', description: '서로 다른 스킬 100종. 진심이세요?' }, rule: { kind: 'collect', count: 100 } },
23 { id: 'thinker', title: 'The Thinker', description: '5 think skills', ko: { title: '생각하는 사람', description: 'think 스킬 5종' }, rule: { kind: 'collect', count: 5, plugin: 'think' } },
24 { id: 'think-all', title: 'Thought Overload', description: 'All 8 think skills', ko: { title: '생각 과부하', description: 'think 스킬 8종 전부' }, rule: { kind: 'collect', count: 8, plugin: 'think' } },
25 { id: 'cognition-5', title: 'Bias Hunter', description: '5 cognition skills', ko: { title: '편향 사냥꾼', description: 'cognition 스킬 5종' }, rule: { kind: 'collect', count: 5, plugin: 'cognition' } },
26 { id: 'cognition-all', title: 'Metacognition Itself', description: 'All 10 cognition skills', ko: { title: '메타인지 그 자체', description: 'cognition 스킬 10종 전부' }, rule: { kind: 'collect', count: 10, plugin: 'cognition' } },
27 { id: 'develop-10', title: 'Not Full Stack, Full Skill', description: '10 develop skills', ko: { title: '풀스택 말고 풀스킬', description: 'develop 스킬 10종' }, rule: { kind: 'collect', count: 10, plugin: 'develop' } },
28 { id: 'develop-25', title: 'Dev Encyclopedia', description: '25 develop skills', ko: { title: '개발 백과사전', description: 'develop 스킬 25종' }, rule: { kind: 'collect', count: 25, plugin: 'develop' } },
29 { id: 'teams-5', title: 'Team Lead', description: '5 teams skills', ko: { title: '팀장님', description: 'teams 스킬 5종' }, rule: { kind: 'collect', count: 5, plugin: 'teams' } },
30 { id: 'teams-10', title: 'One-Person Company', description: '10 teams skills', ko: { title: '1인 회사', description: 'teams 스킬 10종' }, rule: { kind: 'collect', count: 10, plugin: 'teams' } },
31 { id: 'portfolio-5', title: 'Job-Hunt Ready', description: '5 portfolio skills', ko: { title: '이직 준비 완료', description: 'portfolio 스킬 5종' }, rule: { kind: 'collect', count: 5, plugin: 'portfolio' } },
32 { id: 'knowledge-5', title: 'Librarian', description: '5 knowledge skills', ko: { title: '사서', description: 'knowledge 스킬 5종' }, rule: { kind: 'collect', count: 5, plugin: 'knowledge' } },
33 { id: 'write-all', title: 'Author Debut', description: 'All 5 write skills', ko: { title: '작가 데뷔', description: 'write 스킬 5종 전부' }, rule: { kind: 'collect', count: 5, plugin: 'write' } },
34 { id: 'skill-all', title: 'Skill Workshop Owner', description: 'All 5 skill skills', ko: { title: '스킬 공방 주인', description: 'skill 스킬 5종 전부' }, rule: { kind: 'collect', count: 5, plugin: 'skill' } },
35 { id: 'harness-4', title: 'Harness Mechanic', description: '4 harness skills', ko: { title: '하네스 정비공', description: 'harness 스킬 4종' }, rule: { kind: 'collect', count: 4, plugin: 'harness' } },
36 { id: 'agents-all', title: 'Agent Legion', description: 'All 3 agents skills', ko: { title: '에이전트 군단', description: 'agents 스킬 3종 전부' }, rule: { kind: 'collect', count: 3, plugin: 'agents' } },
37 { id: 'streak-3', title: 'Beat the Quitting Point', description: '3 days in a row', ko: { title: '작심삼일 돌파', description: '3일 연속 사용' }, rule: { kind: 'streak', days: 3 } },
38 { id: 'streak-7', title: 'Perfect Week', description: '7 days in a row', ko: { title: '일주일 개근', description: '7일 연속 사용' }, rule: { kind: 'streak', days: 7 } },
39 { id: 'streak-14', title: 'Fortnight Streak', description: '14 days in a row', ko: { title: '2주 개근', description: '14일 연속 사용' }, rule: { kind: 'streak', days: 14 } },
40 { id: 'streak-30', title: 'Full Month', description: '30 days in a row', ko: { title: '한 달 개근', description: '30일 연속 사용' }, rule: { kind: 'streak', days: 30 } },
41 { id: 'streak-100', title: 'Hundred-Day Party', description: '100 days in a row. Time to hand out treats', ko: { title: '백일 기념', description: '100일 연속 사용. 떡 돌리세요' }, rule: { kind: 'streak', days: 100 } },
42 { id: 'streak-365', title: 'One Whole Year', description: '365 days in a row. Ever taken a vacation?', ko: { title: '1주년', description: '365일 연속. 휴가는 가셨나요?' }, hidden: true, rule: { kind: 'streak', days: 365 } },
43 { id: 'punching-bag', title: 'Punching Bag', description: 'Got roughed up by devils-advocate 3 times', ko: { title: '샌드백', description: 'devils-advocate에게 3번 털렸다' }, hidden: true, rule: { kind: 'repeat', skill: 'think:devils-advocate', count: 3 } },
44 { id: 'devils-10', title: 'Masochist\'s Delight', description: 'devils-advocate 10 times', ko: { title: '자학의 즐거움', description: 'devils-advocate 10회' }, rule: { kind: 'repeat', skill: 'think:devils-advocate', count: 10 } },
45 { id: 'brainstorm-10', title: 'Idea Bank', description: 'brainstorming 10 times', ko: { title: '아이디어 뱅크', description: 'brainstorming 10회' }, rule: { kind: 'repeat', skill: 'think:brainstorming', count: 10 } },
46 { id: 'brainstorm-50', title: 'Diverge Addict', description: 'brainstorming 50 times. When do you converge?', ko: { title: '발산 중독', description: 'brainstorming 50회. 수렴은 언제?' }, rule: { kind: 'repeat', skill: 'think:brainstorming', count: 50 } },
47 { id: 'plans-10', title: 'Born Planner', description: 'plans 10 times', ko: { title: '계획형 인간', description: 'plans 10회' }, rule: { kind: 'repeat', skill: 'write:plans', count: 10 } },
48 { id: 'grill-5', title: 'Well Done', description: 'grill 5 times', ko: { title: '통구이', description: 'grill 5회' }, rule: { kind: 'repeat', skill: 'think:grill', count: 5 } },
49 { id: 'mentor-10', title: 'No Senior? No Problem', description: 'mentor 10 times', ko: { title: '사수 없어도 괜찮아', description: 'mentor 10회' }, rule: { kind: 'repeat', skill: 'think:mentor', count: 10 } },
50 { id: 'redefine-5', title: 'The Problem Is the Problem', description: 'redefine-problem 5 times', ko: { title: '문제가 문제다', description: 'redefine-problem 5회' }, rule: { kind: 'repeat', skill: 'think:redefine-problem', count: 5 } },
51 { id: 'negotiate-3', title: 'Master of the Table', description: 'negotiate 3 times', ko: { title: '협상 테이블의 주인', description: 'negotiate 3회' }, rule: { kind: 'repeat', skill: 'think:negotiate', count: 3 } },
52 { id: 'bug-10', title: 'Bug Hunter', description: 'bug-diagnoser 10 times', ko: { title: '버그 사냥꾼', description: 'bug-diagnoser 10회' }, rule: { kind: 'repeat', skill: 'develop:bug-diagnoser', count: 10 } },
53 { id: 'bug-50', title: 'Living With Bugs', description: 'bug-diagnoser 50 times', ko: { title: '벌레와 공존하는 법', description: 'bug-diagnoser 50회' }, rule: { kind: 'repeat', skill: 'develop:bug-diagnoser', count: 50 } },
54 { id: 'tdd-20', title: 'Test-First Disciple', description: 'test-driven-development 20 times', ko: { title: '테스트 먼저 교 신도', description: 'test-driven-development 20회' }, rule: { kind: 'repeat', skill: 'develop:test-driven-development', count: 20 } },
55 { id: 'clean-20', title: 'Review Craftsman', description: 'clean-code 20 times', ko: { title: '리뷰 장인', description: 'clean-code 20회' }, rule: { kind: 'repeat', skill: 'develop:clean-code', count: 20 } },
56 { id: 'flaky-5', title: 'CI Lies', description: 'flaky-test-analyzer 5 times', ko: { title: 'CI는 거짓말을 한다', description: 'flaky-test-analyzer 5회' }, rule: { kind: 'repeat', skill: 'develop:flaky-test-analyzer', count: 5 } },
57 { id: 'security-5', title: 'White Hat', description: 'security-auditor 5 times', ko: { title: '화이트햇', description: 'security-auditor 5회' }, rule: { kind: 'repeat', skill: 'develop:security-auditor', count: 5 } },
58 { id: 'sql-10', title: 'SELECT * FROM life', description: 'sql-pro 10 times', ko: { title: 'SELECT * FROM 인생', description: 'sql-pro 10회' }, rule: { kind: 'repeat', skill: 'develop:sql-pro', count: 10 } },
59 { id: 'incident-3', title: 'Firefighter', description: 'incident-response-playbook 3 times', ko: { title: '소방관', description: 'incident-response-playbook 3회' }, rule: { kind: 'repeat', skill: 'develop:incident-response-playbook', count: 3 } },
60 { id: 'incident-10', title: 'Accidental Outage Expert', description: 'incident-response-playbook 10 times. Are you okay?', ko: { title: '원치 않은 장애 전문가', description: 'incident-response-playbook 10회. 괜찮으세요?' }, hidden: true, rule: { kind: 'repeat', skill: 'develop:incident-response-playbook', count: 10 } },
61 { id: 'harness-10', title: 'Do It Properly ×10', description: 'harness 10 times', ko: { title: '제대로 해줘 ×10', description: 'harness 10회' }, rule: { kind: 'repeat', skill: 'harness:harness', count: 10 } },
62 { id: 'harness-50', title: 'Can\'t Live Without a Harness', description: 'harness 50 times', ko: { title: '하네스 없인 못 살아', description: 'harness 50회' }, rule: { kind: 'repeat', skill: 'harness:harness', count: 50 } },
63 { id: 'verify-20', title: 'No Proof, No Claim', description: 'verification-before-completion 20 times', ko: { title: '증거 없인 말 안 함', description: 'verification-before-completion 20회' }, rule: { kind: 'repeat', skill: 'completion:verification-before-completion', count: 20 } },
64 { id: 'bias-5', title: 'I Catch My Own Biases', description: 'bias-auditor 5 times', ko: { title: '내 편향은 내가 잡는다', description: 'bias-auditor 5회' }, rule: { kind: 'repeat', skill: 'cognition:bias-auditor', count: 5 } },
65 { id: 'fallacy-5', title: 'Logic Police', description: 'fallacy-detector 5 times', ko: { title: '논리 경찰', description: 'fallacy-detector 5회' }, rule: { kind: 'repeat', skill: 'cognition:fallacy-detector', count: 5 } },
66 { id: 'mock-10', title: 'Interview Veteran', description: 'mock-interview 10 times', ko: { title: '면접 백전노장', description: 'mock-interview 10회' }, rule: { kind: 'repeat', skill: 'portfolio:mock-interview', count: 10 } },
67 { id: 'like-me-5', title: 'More Me Than Me', description: 'like-me 5 times', ko: { title: '나보다 나 같은', description: 'like-me 5회' }, rule: { kind: 'repeat', skill: 'write:like-me', count: 5 } },
68 { id: 'human-10', title: 'Doesn\'t Sound Like AI', description: 'writer-verification 10 times', ko: { title: 'AI 티 안 나요', description: 'writer-verification 10회' }, rule: { kind: 'repeat', skill: 'write:writer-verification', count: 10 } },
69 { id: 'full-cycle', title: 'Design to Verification', description: 'In one session: brainstorming → plans → harness', ko: { title: '설계부터 검증까지', description: '한 세션에서 brainstorming → plans → harness' }, rule: { kind: 'combo', sequence: ['think:brainstorming', 'write:plans', 'harness:harness'] } },
70 { id: 'red-green', title: 'Red, Then Green', description: 'In one session: TDD → verification-before-completion', ko: { title: '빨강 다음 초록', description: '한 세션에서 TDD → verification-before-completion' }, rule: { kind: 'combo', sequence: ['develop:test-driven-development', 'completion:verification-before-completion'] } },
71 { id: 'grilled-plan', title: 'Plan After the Roasting', description: 'In one session: grill → plans', ko: { title: '털리고 나서 계획', description: '한 세션에서 grill → plans' }, rule: { kind: 'combo', sequence: ['think:grill', 'write:plans'] } },
72 { id: 'carrot-stick', title: 'Stick, Then Carrot', description: 'In one session: devils-advocate → mentor', ko: { title: '병 주고 약 주고', description: '한 세션에서 devils-advocate → mentor' }, rule: { kind: 'combo', sequence: ['think:devils-advocate', 'think:mentor'] } },
73 { id: 'textbook-debug', title: 'Textbook Debugging', description: 'In one session: bug-diagnoser → TDD → verification', ko: { title: '교과서 디버깅', description: '한 세션에서 bug-diagnoser → TDD → verification' }, rule: { kind: 'combo', sequence: ['develop:bug-diagnoser', 'develop:test-driven-development', 'completion:verification-before-completion'] } },
74 { id: 'never-again', title: 'Never Again Pledge', description: 'In one session: incident-response → sre-engineer', ko: { title: '재발 방지 약속', description: '한 세션에서 incident-response → sre-engineer' }, rule: { kind: 'combo', sequence: ['develop:incident-response-playbook', 'develop:sre-engineer'] } },
75 { id: 'job-hunt', title: 'Full Job-Hunt Course', description: 'In one session: fit → rewrite → mock-interview', ko: { title: '취준 풀코스', description: '한 세션에서 fit → rewrite → mock-interview' }, rule: { kind: 'combo', sequence: ['portfolio:fit', 'portfolio:rewrite', 'portfolio:mock-interview'] } },
76 { id: 'domain-driven-life', title: 'Domain-Driven Life', description: 'In one session: event-storming → DDD → service-boundary-validator', ko: { title: '도메인 주도 인생', description: '한 세션에서 event-storming → DDD → service-boundary-validator' }, rule: { kind: 'combo', sequence: ['develop:event-storming', 'develop:domain-driven-design', 'develop:service-boundary-validator'] } },
77 { id: 'db-triple', title: 'Triple DB Combo', description: 'In one session: sql-pro → database-optimizer → connection-pool-tuner', ko: { title: 'DB 3단 콤보', description: '한 세션에서 sql-pro → database-optimizer → connection-pool-tuner' }, rule: { kind: 'combo', sequence: ['develop:sql-pro', 'develop:database-optimizer', 'develop:connection-pool-tuner'] } },
78 { id: 'skill-factory', title: 'Skill Factory Foreman', description: 'In one session: create → trigger-validator → quality-assurance', ko: { title: '스킬 공장장', description: '한 세션에서 create → trigger-validator → quality-assurance' }, rule: { kind: 'combo', sequence: ['skill:create', 'skill:trigger-validator', 'skill:quality-assurance'] } },
79 { id: 'ticket-loop', title: 'Full Ticket Loop', description: 'In one session: teams plan → take → submit', ko: { title: '티켓 한 바퀴', description: '한 세션에서 teams plan → take → submit' }, rule: { kind: 'combo', sequence: ['teams:plan', 'teams:take', 'teams:submit'] } },
80 { id: 'knowledge-graph', title: 'Knowledge Graph Artisan', description: 'In one session: base-builder → graph-builder → query', ko: { title: '지식 그래프 장인', description: '한 세션에서 base-builder → graph-builder → query' }, rule: { kind: 'combo', sequence: ['knowledge:base-builder', 'knowledge:graph-builder', 'knowledge:query'] } },
81 { id: 'doubt-ladder', title: 'Three Rungs of Doubt', description: 'In one session: assumption-extractor → bias-auditor → epistemic-reasoner', ko: { title: '의심의 삼단계', description: '한 세션에서 assumption-extractor → bias-auditor → epistemic-reasoner' }, rule: { kind: 'combo', sequence: ['cognition:assumption-extractor', 'cognition:bias-auditor', 'cognition:epistemic-reasoner'] } },
82 { id: 'overthinker', title: 'Too Many Thoughts', description: 'In one session: brainstorming → devils-advocate → redefine-problem → back-to-basics', ko: { title: '생각이 너무 많아', description: '한 세션에서 brainstorming → devils-advocate → redefine-problem → back-to-basics' }, hidden: true, rule: { kind: 'combo', sequence: ['think:brainstorming', 'think:devils-advocate', 'think:redefine-problem', 'think:back-to-basics'] } },
83 { id: 'commitment-issues', title: 'Installed, Then Uninstalled', description: 'In one session: harness install → remove', ko: { title: '설치했다 지웠다', description: '한 세션에서 harness install → remove' }, hidden: true, rule: { kind: 'combo', sequence: ['harness:install', 'harness:remove'] } },
84]
85data/triggers.ts 1125 lines1// Generated by _repo/scripts/build-trophy-index.mjs - do not edit.
2export const triggers = [
3 {
4 "skill": "agents:agent-task-decomposer",
5 "plugin": "agents",
6 "phrases": [
7 "agent에게 어떻게 전달해?",
8 "subtask로 나눠줘",
9 "task decomposition",
10 "병렬 작업 계획 잡아줘",
11 "에이전트 분리해줘",
12 "이 작업 어떻게 나눠야 해?",
13 "큰 작업 분해해줘"
14 ]
15 },
16 {
17 "skill": "agents:dispatching-parallel-agents",
18 "plugin": "agents",
19 "phrases": [
20 "multiple independent failures",
21 "parallel agents",
22 "각자 전문가한테 맡겨줘",
23 "독립적인 작업들 한번에",
24 "동시에 여러 작업",
25 "병렬로 처리해줘"
26 ]
27 },
28 {
29 "skill": "agents:subagent-driven-development",
30 "plugin": "agents",
31 "phrases": [
32 "subagent-driven",
33 "두 단계 리뷰로 구현",
34 "서브에이전트로 구현해줘",
35 "태스크별로 에이전트 배포해줘",
36 "현재 세션에서 서브에이전트로 실행"
37 ]
38 },
39 {
40 "skill": "cognition:assumption-extractor",
41 "plugin": "cognition",
42 "phrases": []
43 },
44 {
45 "skill": "cognition:bias-auditor",
46 "plugin": "cognition",
47 "phrases": [
48 "audit my reasoning",
49 "bias check",
50 "내 판단 비뚤어진 것 같아",
51 "편향 점검",
52 "확신이 과한 것 같아"
53 ]
54 },
55 {
56 "skill": "cognition:clarity-toolkit",
57 "plugin": "cognition",
58 "phrases": [
59 "overthinking",
60 "too vague",
61 "목표가 너무 막연해",
62 "분석만 하다 결정을 못 해",
63 "정보가 너무 많아서 뭐가 중요한지 모르겠어"
64 ]
65 },
66 {
67 "skill": "cognition:critical-thinking-workflow",
68 "plugin": "cognition",
69 "phrases": [
70 "critical thinking full process",
71 "decision stress-test",
72 "high-stakes decision review",
73 "결정 제대로 검토해줘",
74 "논리 전체 점검",
75 "전략 검토 전체"
76 ]
77 },
78 {
79 "skill": "cognition:epistemic-reasoner",
80 "plugin": "cognition",
81 "phrases": []
82 },
83 {
84 "skill": "cognition:fallacy-detector",
85 "plugin": "cognition",
86 "phrases": [
87 "post hoc",
88 "spot the fallacy",
89 "strawman",
90 "논리에 허점 있어?",
91 "원인이 너무 깔끔한데",
92 "이거 억지 아냐?"
93 ]
94 },
95 {
96 "skill": "cognition:mental-model-toolkit",
97 "plugin": "cognition",
98 "phrases": [
99 "blind spots",
100 "mental model",
101 "unknown unknowns",
102 "내가 뭘 놓치고 있지?",
103 "다른 관점이 필요해",
104 "해볼 건 다 해봤는데"
105 ]
106 },
107 {
108 "skill": "cognition:question-upgrader",
109 "plugin": "cognition",
110 "phrases": [
111 "am i asking the right question",
112 "better question",
113 "이 질문이 맞는 질문일까?",
114 "질문 자체가 틀린 건 아닐까?",
115 "질문 좀 더 좋게"
116 ]
117 },
118 {
119 "skill": "cognition:second-order-thinker",
120 "plugin": "cognition",
121 "phrases": []
122 },
123 {
124 "skill": "cognition:tradeoff-articulator",
125 "plugin": "cognition",
126 "phrases": [
127 "tradeoff",
128 "장단점",
129 "트레이드오프"
130 ]
131 },
132 {
133 "skill": "completion:verification-before-completion",
134 "plugin": "completion",
135 "phrases": [
136 "bug is fixed",
137 "done",
138 "pr 올릴게",
139 "should pass",
140 "버그 고쳤어",
141 "빌드 성공",
142 "완료했어",
143 "커밋할게",
144 "테스트 통과"
145 ]
146 },
147 {
148 "skill": "develop:architecture-designer",
149 "plugin": "develop",
150 "phrases": []
151 },
152 {
153 "skill": "develop:architecture-review",
154 "plugin": "develop",
155 "phrases": [
156 "where should we refactor this repo",
157 "어디부터 리팩토링할까",
158 "코드가 얽혀서 손대기 힘들어"
159 ]
160 },
161 {
162 "skill": "develop:architecture-workflow",
163 "plugin": "develop",
164 "phrases": [
165 "system architecture from scratch"
166 ]
167 },
168 {
169 "skill": "develop:bug-diagnoser",
170 "plugin": "develop",
171 "phrases": [
172 "debug this",
173 "fix this bug",
174 "why is this failing",
175 "갑자기 안 돼",
176 "고쳐줘",
177 "디버깅",
178 "안 돼요",
179 "에러 나요",
180 "왜 이러죠"
181 ]
182 },
183 {
184 "skill": "develop:chaos-engineer",
185 "plugin": "develop",
186 "phrases": [
187 "chaos experiment",
188 "game day 준비",
189 "kill a pod in staging",
190 "pod 죽여보고 싶어",
191 "simulate zone outage",
192 "장애 주입 테스트"
193 ]
194 },
195 {
196 "skill": "develop:circuit-breaker-tuner",
197 "plugin": "develop",
198 "phrases": [
199 "cascading failure",
200 "circuit breaker tuning",
201 "서킷 브레이커 설정",
202 "서킷이 자주 열려"
203 ]
204 },
205 {
206 "skill": "develop:clean-architecture",
207 "plugin": "develop",
208 "phrases": [
209 "레이어 아키텍처",
210 "의존성 규칙"
211 ]
212 },
213 {
214 "skill": "develop:clean-code",
215 "plugin": "develop",
216 "phrases": [
217 "code review",
218 "pr 리뷰",
219 "review this branch",
220 "리팩토링",
221 "어떻게 구현해?",
222 "이 브랜치 리뷰해줘",
223 "코드 리뷰"
224 ]
225 },
226 {
227 "skill": "develop:cli-developer",
228 "plugin": "develop",
229 "phrases": [
230 "build a cli",
231 "cli 도구 만들어줘",
232 "서브커맨드 설계"
233 ]
234 },
235 {
236 "skill": "develop:connection-pool-tuner",
237 "plugin": "develop",
238 "phrases": [
239 "connection timeout",
240 "hikaricp 사이즈 어떻게 잡아?",
241 "pgbouncer tuning",
242 "pool exhaustion",
243 "커넥션 풀 고갈",
244 "트래픽 몰리면 타임아웃"
245 ]
246 },
247 {
248 "skill": "develop:database-optimizer",
249 "plugin": "develop",
250 "phrases": [
251 "innodb buffer pool",
252 "lock contention",
253 "shared_buffers 튜닝",
254 "stale statistics",
255 "vacuum 밀림",
256 "락 경합",
257 "파티셔닝 설계"
258 ]
259 },
260 {
261 "skill": "develop:database-workflow",
262 "plugin": "develop",
263 "phrases": [
264 "database performance investigation",
265 "database workflow",
266 "db 성능 전체",
267 "db 전체 점검"
268 ]
269 },
270 {
271 "skill": "develop:deprecation-and-migration",
272 "plugin": "develop",
273 "phrases": [
274 "drop this column",
275 "이 api 없애자",
276 "컬럼 지우는 마이그레이션"
277 ]
278 },
279 {
280 "skill": "develop:dockerfile-optimizer",
281 "plugin": "develop",
282 "phrases": [
283 "docker optimize",
284 "dockerfile",
285 "도커 최적화",
286 "빌드 시간",
287 "이거 좀 봐줘",
288 "이미지 크기"
289 ]
290 },
291 {
292 "skill": "develop:documentation-strategy",
293 "plugin": "develop",
294 "phrases": [
295 "doc coverage map",
296 "documentation audit",
297 "openapi 문서 만들어줘",
298 "런북/adr 체계",
299 "문서 뭐부터 써야 해?",
300 "온보딩 문서 정리",
301 "주석/독스트링 달아줘"
302 ]
303 },
304 {
305 "skill": "develop:domain-driven-design",
306 "plugin": "develop",
307 "phrases": [
308 "bounded context",
309 "ddd",
310 "domain-driven design",
311 "도메인 모델링",
312 "바운디드 컨텍스트"
313 ]
314 },
315 {
316 "skill": "develop:event-storming",
317 "plugin": "develop",
318 "phrases": [
319 "map our business flow",
320 "workshop with domain experts",
321 "도메인 모델링 워크숍",
322 "도메인 이벤트 뽑아보자",
323 "이벤트 스토밍"
324 ]
325 },
326 {
327 "skill": "develop:flaky-test-analyzer",
328 "plugin": "develop",
329 "phrases": [
330 "flaky test"
331 ]
332 },
333 {
334 "skill": "develop:frontend-developer",
335 "plugin": "develop",
336 "phrases": [
337 "build a react component",
338 "next.js 폼",
339 "react 컴포넌트"
340 ]
341 },
342 {
343 "skill": "develop:incident-response-playbook",
344 "plugin": "develop",
345 "phrases": [
346 "prod is down",
347 "severity 분류",
348 "write an rca",
349 "장애 났어",
350 "포스트모템 써줘",
351 "프로덕션 터졌어"
352 ]
353 },
354 {
355 "skill": "develop:kotlin-specialist",
356 "plugin": "develop",
357 "phrases": [
358 "flow 취소 처리",
359 "kotlin coroutines",
360 "코루틴",
361 "코틀린으로 전환"
362 ]
363 },
364 {
365 "skill": "develop:like-my-code",
366 "plugin": "develop",
367 "phrases": [
368 "extract conventions from this repo",
369 "like my code",
370 "내 코드 스타일로 컨벤션 뽑아줘",
371 "이 레포 스타일을 정책으로"
372 ]
373 },
374 {
375 "skill": "develop:operations-workflow",
376 "plugin": "develop",
377 "phrases": [
378 "going to prod",
379 "pre-launch ops check",
380 "production readiness review",
381 "system hardening",
382 "운영 준비"
383 ]
384 },
385 {
386 "skill": "develop:performance-profiling-optimization",
387 "plugin": "develop",
388 "phrases": [
389 "api가 느려요",
390 "high cpu",
391 "p99 latency spike",
392 "profile this endpoint",
393 "메모리 계속 늘어나",
394 "병목 찾아줘"
395 ]
396 },
397 {
398 "skill": "develop:scenario-actor",
399 "plugin": "develop",
400 "phrases": [
401 "run this scenario",
402 "spec=… base_url=…",
403 "이 spec 실행해줘",
404 "이 시나리오 하나만 돌려줘"
405 ]
406 },
407 {
408 "skill": "develop:scenario-director",
409 "plugin": "develop",
410 "phrases": [
411 "api 시나리오 테스트",
412 "flow test",
413 "시나리오 ci 붙여줘",
414 "시나리오 md 읽고 서버에 돌려줘"
415 ]
416 },
417 {
418 "skill": "develop:security-auditor",
419 "plugin": "develop",
420 "phrases": [
421 "is this exploitable",
422 "보안 점검",
423 "취약점 찾아줘"
424 ]
425 },
426 {
427 "skill": "develop:service-boundary-validator",
428 "plugin": "develop",
429 "phrases": [
430 "db 공유 문제 없나?",
431 "distributed monolith",
432 "split or merge",
433 "validate this service boundary",
434 "결합도 너무 높은 것 같아",
435 "서비스 쪼개도 될까?"
436 ]
437 },
438 {
439 "skill": "develop:spec-driven-development",
440 "plugin": "develop",
441 "phrases": [
442 "spec first",
443 "spec-driven development",
444 "명세부터 쓰고 구현",
445 "수용 기준 먼저",
446 "스펙 먼저"
447 ]
448 },
449 {
450 "skill": "develop:spring-boot-engineer",
451 "plugin": "develop",
452 "phrases": [
453 "jpa 연동",
454 "spring boot api",
455 "스프링 시큐리티 설정"
456 ]
457 },
458 {
459 "skill": "develop:sql-pro",
460 "plugin": "develop",
461 "phrases": []
462 },
463 {
464 "skill": "develop:sre-engineer",
465 "plugin": "develop",
466 "phrases": [
467 "burn-rate alert",
468 "golden signals dashboard",
469 "slo 정하고 싶어",
470 "반복 작업(toil) 줄이기",
471 "알람 피로",
472 "에러 버짓"
473 ]
474 },
475 {
476 "skill": "develop:test-driven-development",
477 "plugin": "develop",
478 "phrases": [
479 "red-green-refactor",
480 "tdd",
481 "test-first",
482 "테스트 먼저 작성"
483 ]
484 },
485 {
486 "skill": "develop:test-master",
487 "plugin": "develop",
488 "phrases": [
489 "defect report",
490 "test case writing",
491 "test plan",
492 "단위 테스트",
493 "커버리지 분석",
494 "테스트 작성",
495 "테스트 케이스 작성"
496 ]
497 },
498 {
499 "skill": "develop:testing-workflow",
500 "plugin": "develop",
501 "phrases": [
502 "tdd부터 커버리지까지",
503 "testing workflow",
504 "테스트 전체 프로세스"
505 ]
506 },
507 {
508 "skill": "develop:transaction-boundary-reviewer",
509 "plugin": "develop",
510 "phrases": [
511 "@transactional 범위",
512 "deadlock under load",
513 "isolation level",
514 "two writes atomic",
515 "데이터 정합성 깨져",
516 "트랜잭션 락 타임아웃"
517 ]
518 },
519 {
520 "skill": "graph:install",
521 "plugin": "graph",
522 "phrases": []
523 },
524 {
525 "skill": "graph:orchestrate",
526 "plugin": "graph",
527 "phrases": [
528 "graph-engineering 노드 루프",
529 "graph-engineering으로 돌려줘",
530 "graph-owned harness flow"
531 ]
532 },
533 {
534 "skill": "harness:codex-control",
535 "plugin": "harness",
536 "phrases": []
537 },
538 {
539 "skill": "harness:harness",
540 "plugin": "harness",
541 "phrases": [
542 "6단계로 처리해줘",
543 "do this properly with verification",
544 "run the harness",
545 "검증까지 해서",
546 "메타스크립트로",
547 "이거 제대로 해줘",
548 "하네스 돌려줘"
549 ]
550 },
551 {
552 "skill": "harness:install",
553 "plugin": "harness",
554 "phrases": [
555 "convention 스캐폴딩해줘",
556 "harness install",
557 "set up the harness here",
558 "게이트 켜줘",
559 "이 프로젝트에 하네스 적용해줘",
560 "하네스 설치해줘"
561 ]
562 },
563 {
564 "skill": "harness:remove",
565 "plugin": "harness",
566 "phrases": [
567 "harness remove",
568 "uninstall harness",
569 "하네스 삭제",
570 "하네스 제거"
571 ]
572 },
573 {
574 "skill": "harness:update",
575 "plugin": "harness",
576 "phrases": [
577 "harness update",
578 "refresh harness copies",
579 "하네스 업데이트",
580 "하네스 최신으로"
581 ]
582 },
583 {
584 "skill": "knowledge:base-builder",
585 "plugin": "knowledge",
586 "phrases": []
587 },
588 {
589 "skill": "knowledge:graph-builder",
590 "plugin": "knowledge",
591 "phrases": []
592 },
593 {
594 "skill": "knowledge:ontology-builder",
595 "plugin": "knowledge",
596 "phrases": [
597 "class·relation 정리",
598 "controlled vocabulary",
599 "design an ontology",
600 "온톨로지 설계",
601 "용어/관계 체계 잡아줘"
602 ]
603 },
604 {
605 "skill": "knowledge:query",
606 "plugin": "knowledge",
607 "phrases": [
608 "answer with citations",
609 "vault에서 알려줘",
610 "근거 달아서 답해줘",
611 "이 knowledge base에서 찾아줘"
612 ]
613 },
614 {
615 "skill": "knowledge:rag-corpus-builder",
616 "plugin": "knowledge",
617 "phrases": []
618 },
619 {
620 "skill": "knowledge:render-graph-view",
621 "plugin": "knowledge",
622 "phrases": []
623 },
624 {
625 "skill": "knowledge:sqlite-index-builder",
626 "plugin": "knowledge",
627 "phrases": []
628 },
629 {
630 "skill": "knowledge:workflow",
631 "plugin": "knowledge",
632 "phrases": [
633 "eval 점수 개선 루프",
634 "repair retrieval loop",
635 "vault 처음부터 끝까지",
636 "검색 품질이 안 올라"
637 ]
638 },
639 {
640 "skill": "planning:executing-plans",
641 "plugin": "planning",
642 "phrases": [
643 "execute this plan",
644 "plan 리뷰하고 가자",
645 "plan 실행",
646 "계획 실행해줘",
647 "실행 전에 기준 잡아줘"
648 ]
649 },
650 {
651 "skill": "portfolio:deck-builder",
652 "plugin": "portfolio",
653 "phrases": []
654 },
655 {
656 "skill": "portfolio:feedback",
657 "plugin": "portfolio",
658 "phrases": [
659 "고친 버전 비교",
660 "서류 통과할까",
661 "숫자 근거 있어?",
662 "시니어로 읽혀?",
663 "포트폴리오 피드백 해줘"
664 ]
665 },
666 {
667 "skill": "portfolio:fit",
668 "plugin": "portfolio",
669 "phrases": [
670 "jd랑 비교해줘",
671 "which companies fit me",
672 "네이버 지원하려는데 어때?",
673 "서류 통과할까?",
674 "어느 회사에 잘 맞아?",
675 "이 공고에 맞아?"
676 ]
677 },
678 {
679 "skill": "portfolio:interview-plan",
680 "plugin": "portfolio",
681 "phrases": [
682 "interview prep plan",
683 "면접 준비 계획"
684 ]
685 },
686 {
687 "skill": "portfolio:job-application-workflow",
688 "plugin": "portfolio",
689 "phrases": [
690 "career transition",
691 "job application workflow",
692 "job search process",
693 "이직 준비 전체",
694 "취업 프로세스 시작"
695 ]
696 },
697 {
698 "skill": "portfolio:manage",
699 "plugin": "portfolio",
700 "phrases": []
701 },
702 {
703 "skill": "portfolio:material",
704 "plugin": "portfolio",
705 "phrases": [
706 "collect my material",
707 "글감 모아줘",
708 "회고로 포트폴리오 재료"
709 ]
710 },
711 {
712 "skill": "portfolio:mock-interview",
713 "plugin": "portfolio",
714 "phrases": [
715 "grill me on my portfolio",
716 "mock interview",
717 "모의 면접 해줘",
718 "인터뷰 연습"
719 ]
720 },
721 {
722 "skill": "portfolio:pattern",
723 "plugin": "portfolio",
724 "phrases": [
725 "오너십이 잘 드러나나",
726 "패턴 분석해줘",
727 "피동형 많이 썼나"
728 ]
729 },
730 {
731 "skill": "portfolio:rewrite",
732 "plugin": "portfolio",
733 "phrases": [
734 "rewrite my resume bullet",
735 "tailor resume to jd",
736 "공고에 맞게 이력서 최적화",
737 "이력서 문장 고쳐줘",
738 "포트폴리오 임팩트 있게 바꿔줘"
739 ]
740 },
741 {
742 "skill": "skill:audit",
743 "plugin": "skill",
744 "phrases": [
745 "what am i missing",
746 "what skills or plugins do i have here",
747 "뭘 더 설치하면 좋아?",
748 "워크스페이스 점검"
749 ]
750 },
751 {
752 "skill": "skill:create",
753 "plugin": "skill",
754 "phrases": [
755 "create a skill",
756 "새 스킬 뼈대",
757 "스킬 만들어줘",
758 "우리 스킬처럼 만들어줘",
759 "이걸 스킬로"
760 ]
761 },
762 {
763 "skill": "skill:quality-assurance",
764 "plugin": "skill",
765 "phrases": []
766 },
767 {
768 "skill": "skill:retro",
769 "plugin": "skill",
770 "phrases": [
771 "session retro",
772 "stop repeating this mistake",
773 "또 같은 실수네",
774 "이번 세션 회고해서 다음에 같은 실수 안 하게 해줘"
775 ]
776 },
777 {
778 "skill": "skill:trigger-validator",
779 "plugin": "skill",
780 "phrases": [
781 "description 개선해줘",
782 "skill not firing",
783 "skill.md가 안 떠",
784 "trigger coverage audit",
785 "스킬이 트리거 안 돼"
786 ]
787 },
788 {
789 "skill": "teams:board",
790 "plugin": "teams",
791 "phrases": [
792 "show me the board",
793 "what epics are running",
794 "보드 보여줘",
795 "티켓 현황"
796 ]
797 },
798 {
799 "skill": "teams:develop",
800 "plugin": "teams",
801 "phrases": []
802 },
803 {
804 "skill": "teams:document",
805 "plugin": "teams",
806 "phrases": []
807 },
808 {
809 "skill": "teams:inbox",
810 "plugin": "teams",
811 "phrases": [
812 "show my inbox",
813 "what's waiting on me",
814 "나 기다리는 카드 있어?",
815 "내 할 일 뭐 있어"
816 ]
817 },
818 {
819 "skill": "teams:install",
820 "plugin": "teams",
821 "phrases": []
822 },
823 {
824 "skill": "teams:log",
825 "plugin": "teams",
826 "phrases": [
827 "p2 지금 뭐 하고 있어",
828 "tail the log for e-xxx/p2",
829 "what is this story doing",
830 "로그 보여줘"
831 ]
832 },
833 {
834 "skill": "teams:orchestrate",
835 "plugin": "teams",
836 "phrases": [
837 "orchestrate this run",
838 "run it through the mcp",
839 "그래프 돌려줘",
840 "노드 단위로 돌려줘"
841 ]
842 },
843 {
844 "skill": "teams:patch",
845 "plugin": "teams",
846 "phrases": []
847 },
848 {
849 "skill": "teams:plan",
850 "plugin": "teams",
851 "phrases": []
852 },
853 {
854 "skill": "teams:qa",
855 "plugin": "teams",
856 "phrases": []
857 },
858 {
859 "skill": "teams:remove",
860 "plugin": "teams",
861 "phrases": []
862 },
863 {
864 "skill": "teams:sprint",
865 "plugin": "teams",
866 "phrases": [
867 "run this as a sprint",
868 "sprint this backlog",
869 "다음 스프린트로 이어가줘",
870 "스프린트 돌려줘"
871 ]
872 },
873 {
874 "skill": "teams:submit",
875 "plugin": "teams",
876 "phrases": [
877 "submit my answer",
878 "완료 보고할게",
879 "이 카드 제출할게",
880 "작업 다 했어 제출해줘"
881 ]
882 },
883 {
884 "skill": "teams:take",
885 "plugin": "teams",
886 "phrases": [
887 "assign this to me",
888 "take e-xxx/p2",
889 "나한테 배정해줘",
890 "이 카드 내가 할게"
891 ]
892 },
893 {
894 "skill": "teams:ticket",
895 "plugin": "teams",
896 "phrases": [
897 "last verdict on this story",
898 "p2 상태가 뭐야",
899 "show me ticket e-xxx/p2",
900 "이 티켓 상세"
901 ]
902 },
903 {
904 "skill": "think:back-to-basics",
905 "plugin": "think",
906 "phrases": [
907 "first principles",
908 "가정을 의심해봐",
909 "기본부터 다시 생각해",
910 "왜 이렇게 해야 해?",
911 "이 방식이 뭔가 잘못된 것 같아",
912 "이 제약이 진짜 필요한지",
913 "처음부터 설계하면"
914 ]
915 },
916 {
917 "skill": "think:brainstorming",
918 "plugin": "think",
919 "phrases": [
920 "design this feature",
921 "how should we build x?",
922 "기능 설계해줘",
923 "발산해줘",
924 "아키텍처 잡아줘",
925 "어떻게 만들지?",
926 "옵션 더 뽑아줘"
927 ]
928 },
929 {
930 "skill": "think:devils-advocate",
931 "plugin": "think",
932 "phrases": [
933 "devil's advocate",
934 "punch holes in",
935 "steel-man this",
936 "반론 던져줘",
937 "비판해줘",
938 "약점 찾아줘",
939 "이 계획 문제점이 뭐야?",
940 "치명적 약점"
941 ]
942 },
943 {
944 "skill": "think:grill",
945 "plugin": "think",
946 "phrases": [
947 "grill me",
948 "interview me about this plan",
949 "나 좀 빡세게 질문해줘",
950 "내 계획 질문으로 털어줘",
951 "설계하기 전에 질문으로 털어줘"
952 ]
953 },
954 {
955 "skill": "think:mentor",
956 "plugin": "think",
957 "phrases": [
958 "how would a senior think about this",
959 "mentor me",
960 "멘토링 해줘",
961 "선배처럼 조언",
962 "커리어 고민"
963 ]
964 },
965 {
966 "skill": "think:negotiate",
967 "plugin": "think",
968 "phrases": [
969 "negotiate my offer",
970 "계약 조건 봐줘",
971 "상사한테 어떻게 말해",
972 "설득해야 해",
973 "연봉 협상",
974 "협상 준비"
975 ]
976 },
977 {
978 "skill": "think:redefine-problem",
979 "plugin": "think",
980 "phrases": [
981 "the metric doesn't move",
982 "wrong problem",
983 "계속 이 문제가 반복돼",
984 "문제를 다른 각도로 정의해야 할 것 같아",
985 "이 문제 자체가 맞는 건지",
986 "증상만 자꾸 잡는 느낌"
987 ]
988 },
989 {
990 "skill": "think:untangle-thoughts",
991 "plugin": "think",
992 "phrases": [
993 "mind map",
994 "outline 만들어줘",
995 "글 쓰기 전에 구조 잡아줘",
996 "노트 정리",
997 "머릿속이 복잡해",
998 "산만한 생각 정리",
999 "생각 정리해줘",
1000 "아이디어 구조화",
1001 "이거 어떻게 엮어야 해?"
1002 ]
1003 },
1004 {
1005 "skill": "trophy:list",
1006 "plugin": "trophy",
1007 "phrases": [
1008 "achievements",
1009 "trophy list",
1010 "내 트로피",
1011 "스킬 사용 현황",
1012 "어떤 스킬을 놓쳤지?",
1013 "업적 보여줘"
1014 ]
1015 },
1016 {
1017 "skill": "write:adr",
1018 "plugin": "write",
1019 "phrases": [
1020 "adr 남겨줘",
1021 "run a design review",
1022 "write an adr",
1023 "설계 리뷰 해줘"
1024 ]
1025 },
1026 {
1027 "skill": "write:diagram",
1028 "plugin": "write",
1029 "phrases": [
1030 "draw this as a figure",
1031 "그림으로 그려줘",
1032 "도식화해줘",
1033 "시퀀스 다이어그램",
1034 "책에 넣을 그림"
1035 ]
1036 },
1037 {
1038 "skill": "write:like-me",
1039 "plugin": "write",
1040 "phrases": [
1041 "sound like me",
1042 "write it in my voice",
1043 "내 말투로",
1044 "내 문체로",
1045 "내가 쓴 것처럼"
1046 ]
1047 },
1048 {
1049 "skill": "write:plans",
1050 "plugin": "write",
1051 "phrases": [
1052 "break into tickets",
1053 "write a blog",
1054 "write a plan",
1055 "write feedback",
1056 "구현 계획 써줘",
1057 "기술 블로그",
1058 "티켓으로 쪼개줘",
1059 "피드백 써줘"
1060 ]
1061 },
1062 {
1063 "skill": "write:prd",
1064 "plugin": "write",
1065 "phrases": [
1066 "draft an rfc",
1067 "prd 작성",
1068 "write a design doc",
1069 "기획서 써줘"
1070 ]
1071 },
1072 {
1073 "skill": "write:requirements",
1074 "plugin": "write",
1075 "phrases": [
1076 "split this requirement",
1077 "기획서 쪼개줘"
1078 ]
1079 },
1080 {
1081 "skill": "write:spec",
1082 "plugin": "write",
1083 "phrases": [
1084 "turn this conversation into a spec",
1085 "대화 내용으로 스펙 써줘",
1086 "방금 얘기한 거 spec으로 정리해줘"
1087 ]
1088 },
1089 {
1090 "skill": "write:tech-book",
1091 "plugin": "write",
1092 "phrases": [
1093 "write a tech book",
1094 "개념부터 심화까지 책으로",
1095 "기술서적 써줘",
1096 "책 목차→검수→퇴고로 가자",
1097 "책 집필"
1098 ]
1099 },
1100 {
1101 "skill": "write:writer-verification",
1102 "plugin": "write",
1103 "phrases": [
1104 "ai 티 나",
1105 "pr 설명 써줘",
1106 "proofread",
1107 "글 검토해줘",
1108 "글 다듬어줘",
1109 "맞춤법 확인",
1110 "사람이 쓴 것처럼"
1111 ]
1112 },
1113 {
1114 "skill": "write:writing-skills",
1115 "plugin": "write",
1116 "phrases": [
1117 "fix this skill",
1118 "skill documentation",
1119 "skill 개선해줘",
1120 "skill.md 고쳐줘",
1121 "스킬 문서 작성"
1122 ]
1123 }
1124]
1125hooks/logic.ts 421 lines1// Pure functions of the trophy module: no `$`, no store, no clock.
2
3import { failureEvents, ownedMcpTool } from './failures.ts'
4import type { Entry } from './failures.ts'
5
6export type Use = { skill: string; plugin: string; day: string; session: string; ts: number }
7
8export type Rule =
9 | { kind: 'first_use'; plugin: string }
10 | { kind: 'collect'; count: number; plugin?: string }
11 | { kind: 'combo'; sequence: string[] }
12 | { kind: 'streak'; days: number }
13 | { kind: 'repeat'; skill: string; count: number }
14
15export type Achievement = {
16 id: string
17 title: string
18 description: string
19 ko: { title: string; description: string }
20 hidden?: true
21 rule: Rule
22}
23
24export type TriggerEntry = { skill: string; plugin: string; phrases: string[] }
25
26export const MAX_USES = 5000
27const DUPLICATE_MS = 5000
28
29export const dayOf = (ts: number) => new Date(ts).toISOString().slice(0, 10)
30
31// `plugin:skill` of this marketplace stays; a bare name maps through the index (two owners: kept bare, no plugin).
32export function resolveSkill(name: string, index: readonly TriggerEntry[]): { skill: string; plugin: string } | null {
33 if (name.includes(':')) {
34 return index.some(t => t.skill === name) ? { skill: name, plugin: name.split(':')[0]! } : null
35 }
36 const owners = index.filter(t => t.skill.endsWith(`:${name}`))
37 if (owners.length === 0) return null
38 if (owners.length === 1) return { skill: owners[0]!.skill, plugin: owners[0]!.plugin }
39 return { skill: name, plugin: '' }
40}
41
42// The Skill tool, skill.prompt and the typed command all report one use: same skill, same session, within 5 s is one.
43// The command a prompt typed, raw (`/think:grill …`) or as the engine expands it (`<command-name>/think:grill</command-name>`).
44export function typedCommand(text: string): string | undefined {
45 return (/^\s*\/(\S+)/.exec(text) ?? /<command-name>\/([^<\s]+)<\/command-name>/.exec(text))?.[1]
46}
47
48export function recordUse(uses: readonly Use[], skill: string, now: number, session: string): Use[] {
49 const last = uses[uses.length - 1]
50 if (last && last.skill === skill && last.session === session && now - last.ts < DUPLICATE_MS) return [...uses]
51 const plugin = skill.includes(':') ? skill.split(':')[0]! : ''
52 return [...uses, { skill, plugin, day: dayOf(now), session, ts: now }].slice(-MAX_USES)
53}
54
55const distinct = (uses: readonly Use[], plugin?: string) =>
56 new Set(uses.filter(u => plugin === undefined || u.plugin === plugin).map(u => u.skill)).size
57
58// How many of a combo's skills appear in order inside one session; the best session counts.
59function comboSteps(uses: readonly Use[], sequence: readonly string[]) {
60 const sessions = new Map<string, Use[]>()
61 for (const u of uses) sessions.set(u.session, [...(sessions.get(u.session) ?? []), u])
62 let best = 0
63 for (const list of sessions.values()) {
64 let step = 0
65 for (const u of [...list].sort((a, b) => a.ts - b.ts)) if (u.skill === sequence[step]) step += 1
66 best = Math.max(best, step)
67 }
68 return best
69}
70
71function longestStreak(uses: readonly Use[]) {
72 const days = [...new Set(uses.map(u => Date.parse(u.day) / 86_400_000))].sort((a, b) => a - b)
73 let best = 0
74 let run = 0
75 days.forEach((d, i) => {
76 run = i > 0 && d - days[i - 1]! === 1 ? run + 1 : 1
77 best = Math.max(best, run)
78 })
79 return best
80}
81
82// [have, need] for one achievement; the pane draws it and evaluate compares it.
83export function progress(uses: readonly Use[], { rule }: Achievement): [number, number] {
84 switch (rule.kind) {
85 case 'first_use':
86 return [uses.some(u => u.plugin === rule.plugin) ? 1 : 0, 1]
87 case 'collect':
88 return [Math.min(distinct(uses, rule.plugin), rule.count), rule.count]
89 case 'combo':
90 return [comboSteps(uses, rule.sequence), rule.sequence.length]
91 case 'streak':
92 return [Math.min(longestStreak(uses), rule.days), rule.days]
93 case 'repeat':
94 return [Math.min(uses.filter(u => u.skill === rule.skill).length, rule.count), rule.count]
95 }
96}
97
98// Ids newly met: never one already unlocked.
99export function evaluate(uses: readonly Use[], catalog: readonly Achievement[], unlocked: Readonly<Record<string, string>>) {
100 return catalog
101 .filter(a => unlocked[a.id] === undefined)
102 .filter(a => {
103 const [have, need] = progress(uses, a)
104 return have >= need
105 })
106 .map(a => a.id)
107}
108
109// Skills whose trigger phrase appears in a prompt. A typed `/command` is not natural language.
110export function matchTriggers(text: string, index: readonly TriggerEntry[]): string[] {
111 if (text.trimStart().startsWith('/')) return []
112 const lower = text.toLowerCase()
113 return index.filter(t => t.phrases.some(p => contains(lower, p))).map(t => t.skill)
114}
115
116// A phrase edged by an ASCII letter or digit must not start or end inside a longer word ("done" in "abandoned").
117function contains(lower: string, phrase: string): boolean {
118 for (let i = lower.indexOf(phrase); i !== -1; i = lower.indexOf(phrase, i + 1)) {
119 const before = i > 0 && /[a-z0-9]/.test(lower[i - 1]!) && /[a-z0-9]/.test(phrase[0]!)
120 const end = i + phrase.length
121 const after = end < lower.length && /[a-z0-9]/.test(lower[end]!) && /[a-z0-9]/.test(phrase[phrase.length - 1]!)
122 if (!before && !after) return true
123 }
124 return false
125}
126
127export type TurnResult = { hit: string[]; miss: string[]; unmatched: string[] }
128
129// hit: matched and fired; miss: matched, not fired; unmatched: fired, not matched.
130export function closeTurn(matched: readonly string[], fired: readonly string[]): TurnResult {
131 return {
132 hit: matched.filter(s => fired.includes(s)),
133 miss: matched.filter(s => !fired.includes(s)),
134 unmatched: [...new Set(fired)].filter(s => !matched.includes(s)),
135 }
136}
137
138export type Counts = { hit: number; miss: number; unmatched: number }
139export type DayCounts = Record<string, Record<string, Counts>>
140
141export function addTurn(counts: DayCounts, day: string, turn: TurnResult): DayCounts {
142 const today = { ...counts[day] }
143 for (const kind of ['hit', 'miss', 'unmatched'] as const) {
144 for (const skill of turn[kind]) {
145 today[skill] = { hit: 0, miss: 0, unmatched: 0, ...today[skill] }
146 today[skill]![kind] += 1
147 }
148 }
149 return { ...counts, [day]: today }
150}
151
152const BAR_CELLS = 5
153
154export function bar(have: number, need: number) {
155 const filled = Math.round((have / need) * BAR_CELLS)
156 return '▓'.repeat(filled) + '░'.repeat(BAR_CELLS - filled)
157}
158
159// The pane's progress: eight ▰▱ cells and have/need.
160export function cells(a: Achievement, uses: readonly Use[]) {
161 const [have, need] = progress(uses, a)
162 const filled = Math.round((have / need) * 8)
163 return `${'▰'.repeat(filled)}${'▱'.repeat(8 - filled)} ${have}/${need}`
164}
165
166// One row of the achievements list, as the pane and trophy:list draw it; the pane draws its own bar (`withBar` false).
167export function achievementRow(a: Achievement, uses: readonly Use[], unlockedOn: string | undefined, withBar = true) {
168 if (unlockedOn !== undefined) return `🏆 ${a.title} · ${unlockedOn}`
169 if (a.hidden) return '🔒 ???'
170 if (!withBar) return `🔒 ${a.title}`
171 const [have, need] = progress(uses, a)
172 return `🔒 ${a.title} ${bar(have, need)} ${have}/${need}`
173}
174
175// Counts of the last `days` days up to and including `today`, summed per skill.
176export function sumDays(counts: DayCounts, today: string, days: number): Record<string, Counts> {
177 const from = Date.parse(today) - (days - 1) * 86_400_000
178 const sum: Record<string, Counts> = {}
179 for (const [day, skills] of Object.entries(counts)) {
180 const t = Date.parse(day)
181 if (t < from || t > Date.parse(today)) continue
182 for (const [skill, c] of Object.entries(skills)) {
183 const s = (sum[skill] ??= { hit: 0, miss: 0, unmatched: 0 })
184 s.hit += c.hit
185 s.miss += c.miss
186 s.unmatched += c.unmatched
187 }
188 }
189 return sum
190}
191
192export type TriggerLists = { hit: [string, number][]; miss: [string, number][]; never: string[] }
193
194// Most hit, most missed (routing gaps), and skills that never fired in the window.
195export function triggerLists(sum: Record<string, Counts>, index: readonly TriggerEntry[], top = 5): TriggerLists {
196 const ranked = (kind: 'hit' | 'miss') =>
197 Object.entries(sum)
198 .filter(([, c]) => c[kind] > 0)
199 .sort((a, b) => b[1][kind] - a[1][kind])
200 .slice(0, top)
201 .map(([skill, c]): [string, number] => [skill, c[kind]])
202 return {
203 hit: ranked('hit'),
204 miss: ranked('miss'),
205 never: index.filter(t => !sum[t.skill] || sum[t.skill]!.hit + sum[t.skill]!.unmatched === 0).map(t => t.skill),
206 }
207}
208
209// What trophy:list reads: no `uses`, no session ids.
210export function buildProfile(
211 uses: readonly Use[],
212 unlocked: Record<string, string>,
213 counts: DayCounts,
214 catalog: readonly Achievement[],
215 index: readonly TriggerEntry[],
216 now: number,
217) {
218 return {
219 updated: new Date(now).toISOString(),
220 unlocked,
221 progress: Object.fromEntries(catalog.map(a => [a.id, progress(uses, a)])),
222 triggers7d: triggerLists(sumDays(counts, dayOf(now), 7), index),
223 }
224}
225
226// Error text may carry paths; keep none of them, and no more than 300 characters.
227export function scrub(message: string) {
228 return message.replace(/(?<![\w.])(?:[A-Za-z]:\\[^\s'"():;,]*|~?\/[^\s'"():;,]*)/g, '<path>').slice(0, 300)
229}
230
231// v1 = the first band text (no version stored); v2 names error codes; v3 adds versions, OS type and run results.
232export const CONSENT_VERSION = 3
233export type ConsentAnswer = 'unasked' | 'yes' | 'no'
234
235// A yes counts only for the text version it answered; an older yes reads as unasked, a no stays no.
236export function effectiveConsent(stored: ConsentAnswer | undefined, version: number | undefined): ConsentAnswer {
237 if (stored === 'no') return 'no'
238 if (stored === 'yes' && version === CONSENT_VERSION) return 'yes'
239 return 'unasked'
240}
241
242export const POSTHOG_URL = 'https://us.i.posthog.com/batch/'
243// Write-only project token: public by design.
244export const POSTHOG_KEY = 'phc_r4NATbMFBZvmQYiJ8MPMJSWHprgbsTkbCddtc6aYAoUg'
245
246export type Activity = Record<string, Record<string, number>>
247export type McpCalls = Record<string, Record<string, { ok: number; error: number }>>
248export type Outcomes = Record<string, Record<string, number>>
249export type Versions = Record<string, Record<string, string>>
250
251export type BatchStore = {
252 installId: string
253 sentThrough?: string
254 uses: readonly Use[]
255 triggers: DayCounts
256 unlocked: Record<string, string>
257 errors: readonly { day: string; message: string }[]
258 plugins: Record<string, string[]>
259 failures: readonly Entry[]
260 versions?: Versions
261 activity?: Activity
262 mcpCalls?: McpCalls
263 outcomes?: Outcomes
264}
265
266export type Os = 'darwin' | 'linux' | 'win32' | 'other'
267
268// The engine has no OS API: HOME / USERPROFILE decide a label, and only the label is kept.
269export function osOf(home?: string, userprofile?: string): Os {
270 if (home) {
271 if (home.startsWith('/Users/')) return 'darwin'
272 if (home.startsWith('/home/') || home === '/root') return 'linux'
273 if (/^[A-Za-z]:[\\/]/.test(home) || /^\/[a-z]\//i.test(home)) return 'win32'
274 return 'other'
275 }
276 return userprofile ? 'win32' : 'other'
277}
278
279// The newest `versions` entry on or before `day` that names the plugin.
280export function versionOn(versions: Versions, day: string, plugin: string): string | undefined {
281 const days = Object.keys(versions).filter(d => d <= day && versions[d]?.[plugin] !== undefined).sort()
282 const last = days[days.length - 1]
283 return last === undefined ? undefined : versions[last]![plugin]
284}
285
286export function addActivity(activity: Activity, day: string, cc: string, os: Os): Activity {
287 const key = `${cc}|${os}`
288 const today = { ...activity[day] }
289 today[key] = (today[key] ?? 0) + 1
290 return { ...activity, [day]: today }
291}
292
293// Marks the day active without counting a session.
294export function markActive(activity: Activity, day: string, cc: string, os: Os): Activity {
295 const key = `${cc}|${os}`
296 const today = { ...activity[day] }
297 today[key] = today[key] ?? 0
298 return { ...activity, [day]: today }
299}
300
301export function addMcp(calls: McpCalls, day: string, plugin: string, tool: string, kind: 'ok' | 'error'): McpCalls {
302 const key = `${plugin}|${tool}`
303 const today = { ...calls[day] }
304 const cell = { ok: 0, error: 0, ...today[key] }
305 cell[kind] += 1
306 today[key] = cell
307 return { ...calls, [day]: today }
308}
309
310// `mcp__plugin_<plugin>_<server>__<tool>` by name only: tool.call carries no provenance.
311export function ownedMcpByName(
312 name: unknown,
313 servers: Readonly<Record<string, readonly string[]>>,
314): { plugin: string; server: string; tool: string } | undefined {
315 return ownedMcpTool(name, { source: 'plugin' }, servers)
316}
317
318const SYSTEMS = ['graph', 'teams', 'harness'] as const
319const OUTCOME_KINDS = ['pass', 'reject', 'fail'] as const
320export type System = (typeof SYSTEMS)[number]
321export type OutcomeKind = (typeof OUTCOME_KINDS)[number]
322
323// A producer's published outcome, reduced to its two fixed labels; anything else is dropped.
324export function outcomeOf(value: unknown, system: System): { system: System; outcome: OutcomeKind } | undefined {
325 if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined
326 const v = value as { system?: unknown; outcome?: unknown }
327 if (v.system !== system) return undefined
328 const outcome = OUTCOME_KINDS.find(o => o === v.outcome)
329 return outcome === undefined ? undefined : { system, outcome }
330}
331
332export function addOutcome(outcomes: Outcomes, day: string, system: System, outcome: OutcomeKind): Outcomes {
333 const key = `${system}|${outcome}`
334 const today = { ...outcomes[day] }
335 today[key] = (today[key] ?? 0) + 1
336 return { ...outcomes, [day]: today }
337}
338
339// Required and optional property keys of every event; buildBatch builds each from these names only.
340export const EVENT_KEYS: Record<string, { required: string[]; optional: string[] }> = {
341 skill_used: { required: ['skill', 'plugin', 'day', 'count'], optional: ['plugin_version'] },
342 trigger_result: { required: ['skill', 'day', 'hit', 'miss', 'unmatched'], optional: ['plugin_version'] },
343 achievement_unlocked: { required: ['id'], optional: [] },
344 plugins_installed: { required: ['plugin', 'day'], optional: [] },
345 daily_active: { required: ['day', 'cc_version', 'os', 'sessions'], optional: [] },
346 mcp_tool_result: { required: ['day', 'plugin', 'tool', 'ok', 'error'], optional: ['plugin_version'] },
347 run_outcome: { required: ['day', 'system', 'outcome', 'count'], optional: [] },
348 diag_skill_error: { required: ['skill', 'plugin', 'reason', 'count', 'day'], optional: ['plugin_version', 'cc_version'] },
349 diag_mcp_error: { required: ['tool', 'plugin', 'reason', 'count', 'day'], optional: ['plugin_version', 'cc_version'] },
350 diag_user_report: { required: ['reason', 'count', 'day'], optional: ['skill', 'plugin', 'plugin_version', 'cc_version'] },
351 $exception: { required: ['$exception_message'], optional: [] },
352}
353
354// The events of every day after `sentThrough` up to `through`. Only names, days, labels and counts.
355export function buildBatch(store: BatchStore, through: string) {
356 const inRange = (day: string) => day > (store.sentThrough ?? '') && day <= through
357 const versions = store.versions ?? {}
358 const withVersion = (day: string, plugin: string) => {
359 const v = plugin ? versionOn(versions, day, plugin) : undefined
360 return v === undefined ? {} : { plugin_version: v }
361 }
362 const event = (name: string, day: string, properties: Record<string, unknown>) => ({
363 event: name,
364 distinct_id: store.installId,
365 timestamp: `${day}T12:00:00Z`,
366 properties: { ...properties, $process_person_profile: false },
367 })
368 const batch: ReturnType<typeof event>[] = []
369
370 const used = new Map<string, { day: string; skill: string; plugin: string; count: number }>()
371 const pluginsByDay: Record<string, Set<string>> = {}
372 for (const [day, list] of Object.entries(store.plugins)) pluginsByDay[day] = new Set(list)
373 for (const u of store.uses.filter(u => inRange(u.day))) {
374 const row = used.get(`${u.day} ${u.skill}`) ?? { day: u.day, skill: u.skill, plugin: u.plugin, count: 0 }
375 used.set(`${u.day} ${u.skill}`, { ...row, count: row.count + 1 })
376 if (u.plugin) (pluginsByDay[u.day] ??= new Set()).add(u.plugin)
377 }
378 for (const r of used.values()) {
379 batch.push(event('skill_used', r.day, { skill: r.skill, plugin: r.plugin, day: r.day, count: r.count, ...withVersion(r.day, r.plugin) }))
380 }
381 for (const [day, skills] of Object.entries(store.triggers).filter(([d]) => inRange(d))) {
382 for (const [skill, c] of Object.entries(skills)) {
383 batch.push(event('trigger_result', day, {
384 skill, day, hit: c.hit, miss: c.miss, unmatched: c.unmatched, ...withVersion(day, skill.split(':')[0]!),
385 }))
386 }
387 }
388 for (const [id, day] of Object.entries(store.unlocked).filter(([, d]) => inRange(d))) {
389 batch.push(event('achievement_unlocked', day, { id }))
390 }
391 for (const [day, set] of Object.entries(pluginsByDay).filter(([d]) => inRange(d))) {
392 for (const plugin of [...set].sort()) batch.push(event('plugins_installed', day, { plugin, day }))
393 }
394 for (const [day, cells] of Object.entries(store.activity ?? {}).filter(([d]) => inRange(d))) {
395 for (const [key, sessions] of Object.entries(cells)) {
396 const i = key.lastIndexOf('|')
397 batch.push(event('daily_active', day, { day, cc_version: key.slice(0, i), os: key.slice(i + 1), sessions }))
398 }
399 }
400 for (const [day, cells] of Object.entries(store.mcpCalls ?? {}).filter(([d]) => inRange(d))) {
401 for (const [key, c] of Object.entries(cells)) {
402 const [plugin = '', tool = ''] = key.split('|')
403 batch.push(event('mcp_tool_result', day, { day, plugin, tool, ok: c.ok, error: c.error, ...withVersion(day, plugin) }))
404 }
405 }
406 for (const [day, cells] of Object.entries(store.outcomes ?? {}).filter(([d]) => inRange(d))) {
407 for (const [key, count] of Object.entries(cells)) {
408 const [system, outcome, ...rest] = key.split('|')
409 if (rest.length > 0 || !SYSTEMS.some(s => s === system) || !OUTCOME_KINDS.some(o => o === outcome)) continue
410 batch.push(event('run_outcome', day, { day, system, outcome, count }))
411 }
412 }
413 for (const e of store.errors.filter(e => e.day <= through)) {
414 batch.push(event('$exception', e.day, { $exception_message: e.message }))
415 }
416 for (const f of failureEvents(store.failures, store.sentThrough, through)) {
417 batch.push(event(f.event, String(f.properties.day), f.properties))
418 }
419 return { api_key: POSTHOG_KEY, batch }
420}
421hooks/failures.ts 164 lines1// Failures of this marketplace's skills and MCP tools: pure logic, no `$`, no I/O. mod.tsx captures, logic.ts sends.
2
3export type Reason =
4 | 'is_error'
5 | 'unsuccessful'
6 | 'forked_unsuccessful'
7 | 'mcp_error'
8 | 'user_report'
9 | 'subgoal_failed'
10 | 'goal_failed'
11
12export type Entry = {
13 ts: number
14 day: string
15 kind: 'bug' | 'outcome' | 'report'
16 reason: Reason
17 plugin?: string
18 skill?: string
19 tool?: string
20 // the failing plugin's version (its marketplace entry) and Claude Code's release, when known
21 version?: string
22 cc?: string
23 session: string
24 // Raw text stays on this machine: never read by buildBatch. slug/subgoal/path are kept only because stored
25 // pre-change outcome entries still carry them; new outcome entries have an empty local.
26 local: { text?: string; note?: string; slug?: string; subgoal?: string; path?: string }
27}
28
29export type SentEvent = { event: string; properties: Record<string, string | number> }
30
31const DEDUPE_MS = 5000
32const KEEP = 500
33
34// The two places a marketplace.json can sit relative to the plugin root.
35export function marketplaceCandidates(root: string, marketplace?: string): string[] {
36 const parts = root.replace(/\/+$/, '').split('/')
37 const up = (n: number) => parts.slice(0, Math.max(parts.length - n, 0)).join('/')
38 const out = [up(1) + '/.claude-plugin/marketplace.json']
39 if (marketplace) out.push(up(4) + '/marketplaces/' + marketplace + '/.claude-plugin/marketplace.json')
40 return out
41}
42
43// `plugin:skill` only, and the skill must be one this marketplace ships (`skills` maps each plugin to
44// its skill dir names): a bare name, a foreign plugin or typed free text after the colon is not ours.
45export function ownedSkill(
46 name: unknown,
47 skills: Readonly<Record<string, readonly string[]>>,
48): { plugin: string; skill: string } | undefined {
49 if (typeof name !== 'string') return undefined
50 const i = name.indexOf(':')
51 if (i <= 0 || i === name.length - 1) return undefined
52 const plugin = name.slice(0, i)
53 const skill = name.slice(i + 1)
54 return Object.hasOwn(skills, plugin) && skills[plugin]?.includes(skill) ? { plugin, skill } : undefined
55}
56
57const norm = (s: string) => s.replace(/[^a-zA-Z0-9_]/g, '_')
58
59// `mcp__plugin_<plugin>_<server>__<tool>`, provenance `plugin`, server declared by that plugin.
60export function ownedMcpTool(
61 name: unknown,
62 provenance: { source?: string } | undefined,
63 servers: Readonly<Record<string, readonly string[]>>,
64): { plugin: string; server: string; tool: string } | undefined {
65 if (typeof name !== 'string' || provenance?.source !== 'plugin') return undefined
66 for (const plugin of Object.keys(servers)) {
67 for (const p of [plugin, norm(plugin)]) {
68 const prefix = 'mcp__plugin_' + p + '_'
69 if (!name.startsWith(prefix)) continue
70 const rest = name.slice(prefix.length)
71 for (const server of servers[plugin] ?? []) {
72 for (const s of [server, norm(server)]) {
73 const head = s + '__'
74 if (rest.startsWith(head) && rest.length > head.length) {
75 return { plugin, server, tool: rest.slice(head.length) }
76 }
77 }
78 }
79 }
80 }
81 return undefined
82}
83
84// The harness's published outcome as a local failure reason: fail is a failed subgoal, reject a failed goal gate.
85export function outcomeFailure(value: unknown): Reason | undefined {
86 if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined
87 const v = value as { system?: unknown; outcome?: unknown }
88 if (v.system !== 'harness') return undefined
89 return v.outcome === 'fail' ? 'subgoal_failed' : v.outcome === 'reject' ? 'goal_failed' : undefined
90}
91
92const sameTarget = (a: Entry, b: Entry) => (a.skill ?? a.tool) === (b.skill ?? b.tool)
93
94// Same reason + skill/tool + session within 5 s counts once; the newest 500 are kept.
95export function appendEntry(log: readonly Entry[], entry: Entry): Entry[] {
96 const dup = log.some(
97 e => e.reason === entry.reason && e.session === entry.session && sameTarget(e, entry) &&
98 Math.abs(entry.ts - e.ts) <= DEDUPE_MS,
99 )
100 if (dup) return log.slice()
101 return log.concat([entry]).slice(-KEEP)
102}
103
104const SKILL_REASONS: readonly Reason[] = ['is_error', 'unsuccessful', 'forked_unsuccessful']
105
106// One event per (day, reason, plugin, skill|tool, versions). Each property object lists its keys explicitly,
107// so a field added to Entry later cannot leak. Outcomes, `local` and session ids never appear.
108export function failureEvents(log: readonly Entry[], sentThrough: string | undefined, through: string): SentEvent[] {
109 const groups = new Map<string, SentEvent>()
110 for (const e of log) {
111 if (e.day > through || (sentThrough !== undefined && e.day <= sentThrough)) continue
112 let event: string
113 let properties: Record<string, string | number>
114 if (e.kind === 'bug' && SKILL_REASONS.includes(e.reason) && e.skill && e.plugin) {
115 event = 'diag_skill_error'
116 properties = { skill: e.skill, plugin: e.plugin, reason: e.reason, count: 1, day: e.day }
117 } else if (e.kind === 'bug' && e.reason === 'mcp_error' && e.tool && e.plugin) {
118 event = 'diag_mcp_error'
119 properties = { tool: e.tool, plugin: e.plugin, reason: 'mcp_error', count: 1, day: e.day }
120 } else if (e.kind === 'report' && e.reason === 'user_report') {
121 event = 'diag_user_report'
122 properties = { reason: 'user_report', count: 1, day: e.day }
123 if (e.skill) properties.skill = e.skill
124 if (e.plugin) properties.plugin = e.plugin
125 } else {
126 continue
127 }
128 if (e.version) properties.plugin_version = e.version
129 if (e.cc) properties.cc_version = e.cc
130 const key = [event, e.day, e.reason, e.plugin ?? '', e.skill ?? e.tool ?? '', e.version ?? '', e.cc ?? ''].join('|')
131 const hit = groups.get(key)
132 if (hit) hit.properties.count = (hit.properties.count as number) + 1
133 else groups.set(key, { event, properties })
134 }
135 return Array.from(groups.values())
136}
137
138export const PANE_ROWS = 30
139
140// Newest first, at most 30.
141export const newest = (log: readonly Entry[]): Entry[] => log.slice(-PANE_ROWS).reverse()
142
143export const rowTitle = (e: Entry): string =>
144 [e.day, e.kind, e.reason, e.plugin && e.skill ? `${e.plugin}:${e.skill}` : (e.tool ?? e.plugin ?? '-')].join(' · ')
145
146// First five lines of the local raw text, note or slug.
147export function rowDetail(e: Entry): string[] {
148 const raw = e.local.text ?? e.local.note ?? [e.local.slug, e.local.subgoal].filter(Boolean).join(' ')
149 return (raw ?? '').split('\n').slice(0, 5)
150}
151
152// A ready-to-file bug body; raw text stays on this machine unless the person pastes it.
153export function copyBody(e: Entry): string {
154 const target = e.plugin && e.skill ? `${e.plugin}:${e.skill}` : (e.tool ?? e.plugin ?? '-')
155 return [
156 `skill: ${target}`,
157 `reason: ${e.reason}`,
158 `day: ${e.day}`,
159 `version: ${e.version ?? '-'} · Claude Code ${e.cc ?? '-'}`,
160 `text:`,
161 e.local.text ?? e.local.note ?? [e.local.slug, e.local.subgoal].filter(Boolean).join(' '),
162 ].join('\n')
163}
164types/index.d.ts 31 lines1declare module 'claude-code' {
2 interface PluginState {
3 trophy: {
4 active: boolean
5 turnMatched: string[]
6 turnFired: string[]
7 turnTyped: boolean
8 consent: 'unasked' | 'yes' | 'no'
9 consentVersion: number
10 celebrate: { ids: string[]; until: number } | null
11 tab: 'trophies' | 'triggers' | 'failures'
12 // last `plugin:skill` of this marketplace used or typed this session; '' when none
13 lastSkill: string
14 // failures recorded since the failures tab was last shown, and the newest one's title
15 unseen: number
16 lastTitle: string
17 // any achievement unlocked yet (stored or this session): the consent question waits for it
18 anyUnlocked: boolean
19 // UI language, from Claude Code's `language` setting
20 lang: 'en' | 'ko'
21 // last UTC day this session was counted active ('' before the first start)
22 lastActiveDay: string
23 }
24 // Run outcomes the graph, teams and harness mods publish. trophy reads them through `state.set` hooks;
25 // each declaration repeats the producer's own type and must stay identical to it.
26 graph: { outcome: { system: 'graph' | 'teams' | 'harness'; outcome: 'pass' | 'reject' | 'fail'; at: number } | null }
27 teams: { outcome: { system: 'graph' | 'teams' | 'harness'; outcome: 'pass' | 'reject' | 'fail'; at: number } | null }
28 harness: { outcome: { system: 'graph' | 'teams' | 'harness'; outcome: 'pass' | 'reject' | 'fail'; at: number } | null }
29 }
30}
31