SLOPSHOPPER

worklog

Hours, reminders and ticket context from worklog inside Claude Code.

panespinnerguardcommandtoastprompt
v0.1.0no licenseupdated 2026-10-26TomasPalsson/worklog/mods/worklog
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · worklog
│ ┃ worklog-ticket ✕ › fix the failing auth test and add an audit log call │ ┃ ╭─────────────────────────────────────────── │ ┃ │ type to filter, Enter picks the first ⏎ pi ⏺ Read(src/auth.ts) │ ┃ │ ▾ ⎿ Read 6 lines │ ┃ ╰─────────────────────────────────────────── ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /wl │ ⎿ worklog: usage: /wl today|week|review|install|ticket|ask <questi │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · worklog-ticket
╭──────────────────────────────────────────────────────────╮ │ type to filter, Enter picks the first ⏎ pick │ │ ▾ │ ╰──────────────────────────────────────────────────────────╯
Pane · worklog-review
╭──────────────────────────────────────────────────────────╮ │ Nothing to review today. │ ╰──────────────────────────────────────────────────────────╯
README

worklog

Personal time-tracker for the developer who hates timers. Pulls activity from Claude Code, GitHub, Google Calendar, and Jira into one local SQLite file, clusters it into blocks, uses claude -p to pick a ticket and write a description for each block, and syncs the result to Tempo Cloud after you review it in a local web UI.

Everything runs on your machine. Nothing leaves until you push a Tempo sync — and you review every block before that happens.

Install

curl -fsSL https://raw.githubusercontent.com/TomasPalsson/worklog/main/install.sh | bash

The script downloads a signed release binary for your platform (macOS arm64 or linux x86_64) from GitHub Releases, verifies it, and drops it at ~/.local/bin/worklog. After that:

worklog setup          # one-shot onboarding: db + secrets + Claude hook
worklog day            # end-of-day: collect → infer → estimate → review UI

Upgrading is a single command and always verifies the signature:

worklog upgrade        # signed self-update via the release pipeline

Migrating from the old uv tool install? See docs/MIGRATION.md — one step.

Architecture

┌──────────────────────────── your Mac ─────────────────────────────┐
│                                                                    │
│   ~/.local/share/worklog/worklog.db   (single source of truth,     │
│                                        WAL mode — safe RO readers  │
│                                        during concurrent writes)   │
│             ▲                     ▲                                │
│             │                     │                                │
│     writes (unix socket           │ reads direct                   │
│      OR TCP 127.0.0.1:9323)       │ via bun:sqlite                 │
│             │                     │                                │
│    ┌────────┴────────┐        ┌───┴───────────────────┐            │
│    │ worklog (Rust)  │        │ Docker: worklog-web   │            │
│    │  · CLI          │        │  · Bun + Next.js 15   │            │
│    │  · Collectors   │        │  · Server Components  │            │
│    │  · Estimator    │───────▶│  · Server Actions →   │            │
│    │  · axum daemon  │  TCP   │     host.docker       │            │
│    │  · web orch.    │        │     .internal:9323    │            │
│    └────────┬────────┘        └───────────────────────┘            │
│             │  spawns/manages                                       │
│             ▼                                                       │
└─────────────────────────────────────────────────────────────────────┘

Events are classified to a Jira ticket by the AI estimator; unmatched ones appear as "unassigned" in the web UI and are reassigned by hand. The web container reads SQLite directly (WAL mode = concurrent reads are safe), and writes flow through Next.js Server Actions → the Rust daemon over TCP (Docker Desktop can't proxy live unix sockets through its macOS VM, hence TCP between the container and host).

Only the Rust daemon writes to the DB — Server Actions are a thin shim that forwards the mutation and calls revalidatePath.

Quickstart

worklog setup          # preflight + interactive secrets + db migrate
worklog hook install   # register the Claude Code hook
worklog day            # full daily pipeline (collect → infer → estimate → UI)

To pull everything without running the UI:

worklog day --no-serve

Commands

CommandPurpose
worklog versionPrint the embedded version
worklog setupPreflight + secrets capture + db migrate
worklog doctorEnvironment, DB, secrets sanity report
worklog statusOne-screen health dashboard plus today's tracked time
worklog completions <shell>Shell completion script
worklog skillInstall / refresh / remove the Claude Code skill
worklog summaryToday's hours and per-ticket breakdown (alias: today)
worklog week [--day]Per-ticket breakdown for the 7 days ending on --day
worklog undoReverse your newest block change
worklog ask <query>Search saved blocks and Claude prompts
worklog standupDraft today's standup and post it to Slack
worklog reportOne customer's hours for a month, grouped by deild
worklog export [--day]Billing line items as text, CSV or JSON
worklog ticketJira assistant: get, start, find, move, create
worklog accountBilling accounts: allowed, suggest, relearn
worklog blockList and edit individual time blocks
worklog tagPersonal/work classification rules
worklog pinPin a customer to a Claude Code session
worklog verdictOptional project classifier helper
worklog day [--day] [--no-serve] [--model]Full daily pipeline: collect → infer → estimate → web UI
`worklog collect [all\jira\github\gcal] [--days]`Pull remote activity
worklog collect gcal --authLog in to Google Calendar (browser consent)
worklog infer [--day]Gap-timeout clustering of events into blocks
worklog estimate [--day] [--model]claude -p fills jira + description + minutes
worklog sync [--day] [--dry-run]POST reviewed blocks to Tempo Cloud
worklog web up [--port]Bring up the dockerised Next.js UI
worklog web down / status / logs / buildContainer lifecycle
worklog daemon [--socket] [--tcp]Axum API server (unix + TCP)
`worklog hook [install\uninstall\status]`Claude Code hook wiring
`worklog schedule [install\uninstall\status]`Scheduled collection (launchd / systemd --user)
`worklog secret [set\get\rm\list]`Credentials in the OS keychain
`worklog db [migrate\info\path]`DB operations
`worklog self-update [--check\--dry-run\--force]`Signed self-update (alias: upgrade)
`worklog dev [keygen\sign\make-patch\apply-patch]`Maintainer tooling

Every subcommand accepts --json for structured output.

Google Calendar login

worklog uses your own Google OAuth client; none is built in.

  1. In Google Cloud Console, create a project and enable the Google Calendar API.
  2. Configure the OAuth consent screen and add yourself as a test user.
  3. Create credentials: OAuth client ID, application type Desktop app.
  4. Download the JSON and save it as ~/.config/worklog/google_credentials.json ($WORKLOG_HOME/google_credentials.json when $WORKLOG_HOME is set).
  5. Run worklog collect gcal --auth, click "Allow" in the browser, and the token is saved to google_token.json. If no browser opens, open the printed link on the same machine. The login times out after 5 minutes.

Re-run the same command if Google revokes the token.

Storage

  • DB: ~/.local/share/worklog/worklog.db (SQLite, WAL mode).
  • Config: ~/.config/worklog/ (.env, google_credentials.json, google_token.json).
  • Secrets: OS keychain under service name worklog (macOS Keychain, Linux secret-service, Windows Credential Manager). The .env file still works — secrets migrate lazily as you set them via worklog secret set … or re-run worklog setup.
  • Binaries + releases: ~/.local/share/worklog/{bin,releases}/.

Override everything with $WORKLOG_HOME=<dir> — collapses db, socket, config, bin, logs, releases into one root. Primarily for tests and power users.

Switching estimator provider

The estimator has two interchangeable backends:

  • claude_subprocess (default) — shells out to claude -p. Zero configuration. Requires the Claude Code CLI on PATH.
  • litellm — POSTs to any OpenAI-compatible proxy (LiteLLM is the reference implementation). Lets you route to Anthropic, OpenAI, local Ollama, Bedrock, etc. without changing worklog.

Select via worklog setup (interactive) or set the env var:

export WORKLOG_ESTIMATOR_PROVIDER=litellm
worklog secret set litellm_base_url http://localhost:4000
worklog secret set litellm_api_key  <your-proxy-key>   # empty OK for unauthed local
worklog secret set litellm_model    anthropic/claude-haiku-4-5

worklog doctor reports the active provider and a reachability probe. Unset WORKLOG_ESTIMATOR_PROVIDER (and run worklog secret rm worklog_estimator_provider) to fall back to the subprocess path.

Dev

cargo test  --manifest-path rust/Cargo.toml
cargo clippy --manifest-path rust/Cargo.toml --all-targets --all-features -- -D warnings
cargo fmt   --manifest-path rust/Cargo.toml --all

cd web && bun test && bun run typecheck && bun run build

Local release smoke (no network, no tag push):

bash scripts/release-smoke.sh
bash tests/install/smoke.sh

CI: .github/workflows/rust.yml runs fmt + clippy + tests on Linux and macOS on every push / PR; .github/workflows/release.yml builds, signs, and publishes on every v* tag.

Files of interest

  • rust/crates/worklog-core/ — data layer: paths, db, repo, secrets, collectors, infer, estimator, signed updater
  • rust/crates/worklog-cli/ — the worklog binary: CLI + setup wizard
  • rust/crates/worklog-core/sql/schema.sql — canonical SQL schema
  • web/ — the Next.js + Bun review UI (dockerised)
  • install.sh — curl-piped installer
  • scripts/release-smoke.sh — host-side dry-run of the release pipeline
Source 7 files
hooks/register.tsx 11 lines
1import type { Register } from 'claude-code'
2import { registerCommand } from './command'
3import { registerStatus } from './status'
4import { registerTicket } from './ticket'
5
6export const register: Register = on => {
7  registerStatus(on)
8  registerTicket(on)
9  registerCommand(on)
10}
11
hooks/command.tsx 246 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On, RenderInput } from 'claude-code'
3import { REVIEW_PANE_ID } from './contract'
4import type { DaySummary, Io, ReviewAction, WeekCloseout } from './contract'
5import {
6  daemonGet,
7  daemonPost,
8  daemonToday,
9  formatHours,
10  mondayOf,
11  reviewRequest,
12  workSeconds,
13} from './lib'
14
15type ReviewBlock = DaySummary['blocks'][number]
16
17type AskHit = { day: string; started_at: string; ended_at: string; jira_issue: string | null }
18
19type ReviewState = {
20  blocks: ReviewBlock[]
21  selected: number | undefined
22  editing: 'ticket' | 'description' | undefined
23  error: string | undefined
24}
25
26const USAGE = 'usage: /wl today|week|review|install|ticket|ask <question>'
27
28const review = atom(
29  { plugin: 'worklog', key: 'review' } as const,
30  { blocks: [], selected: undefined, editing: undefined, error: undefined } as ReviewState,
31)
32
33function change($: EngineInterface, patch: Partial<ReviewState>): Promise<unknown> {
34  return update($, review, state => ({ ...state, ...patch }))
35}
36
37async function makeIo($: EngineInterface): Promise<Io> {
38  return {
39    fetch: (url, init) => $.http.fetch(url, init),
40    run: (argv, cwd) => $.process.run(argv, { cwd }),
41    after: (milliseconds, callback) => $.clock.after(milliseconds, callback),
42    now: () => $.clock.now(),
43    home: await $.env.get('HOME'),
44  }
45}
46
47async function loadReview($: EngineInterface, io: Io): Promise<void> {
48  const today = await daemonToday(io)
49  const summary = today.ok ? await daemonGet<DaySummary>(io, `/days/${today.value}`) : today
50  if (!summary.ok) {
51    await change($, { error: summary.error })
52    return
53  }
54  const blocks = summary.value.blocks.filter(block => block.ignored_at === null)
55  await update($, review, state => ({
56    blocks,
57    selected: blocks.some(block => block.id === state.selected) ? state.selected : blocks[0]?.id,
58    editing: undefined,
59    error: undefined,
60  }))
61}
62
63async function sendReview(
64  $: EngineInterface,
65  io: Io,
66  toAction: (block: ReviewBlock) => ReviewAction,
67): Promise<void> {
68  const { blocks, selected } = await read($, review)
69  const target = blocks.find(block => block.id === selected)
70  if (target === undefined) return
71  const request = reviewRequest(target.id, toAction(target))
72  const result = await daemonPost<unknown>(io, request.path, request.body)
73  if (result.ok) await loadReview($, io)
74  else await change($, { error: result.error })
75}
76
77async function summarise($: EngineInterface, io: Io, period: 'today' | 'week'): Promise<string> {
78  const today = await daemonToday(io)
79  if (!today.ok) return `worklog: ${today.error}`
80  if (period === 'today') {
81    const summary = await daemonGet<DaySummary>(io, `/days/${today.value}`)
82    return summary.ok
83      ? `worklog today: ${formatHours(workSeconds(summary.value.blocks))}`
84      : `worklog: ${summary.error}`
85  }
86  const week = await daemonGet<WeekCloseout>(io, `/weeks/${mondayOf(today.value)}/closeout`)
87  if (!week.ok) return `worklog: ${week.error}`
88  const seconds = week.value.days.reduce((total, day) => total + day.logged_seconds, 0)
89  return `worklog week: ${formatHours(seconds)}`
90}
91
92async function ask(io: Io, question: string): Promise<string> {
93  const hits = await daemonGet<AskHit[]>(io, `/ask?q=${encodeURIComponent(question)}`)
94  if (!hits.ok) return `worklog: ${hits.error}`
95  if (hits.value.length === 0) return 'worklog ask: no matches'
96  return hits.value
97    .map(hit => `${hit.day}  ${hit.started_at.slice(11, 16)}–${hit.ended_at.slice(11, 16)}  ${hit.jira_issue ?? '—'}`)
98    .join('\n')
99}
100
101const WORKLOG_ORIGIN_RE = /^(https:\/\/|ssh:\/\/git@|git@)github\.com[:/]TomasPalsson\/worklog(\.git)?\/?$/
102
103const tail = (text: string): string => text.trim().split('\n').slice(-10).join('\n')
104
105async function install($: EngineInterface, cwd: string | undefined): Promise<string> {
106  const refused = 'worklog install: run /wl install from inside the worklog repo'
107  if (cwd === undefined) return refused
108  const git = async (...argv: string[]) => {
109    const result = await $.process.run(['git', ...argv], { cwd })
110    return result.exitCode === 0 ? result.stdout.trim() : undefined
111  }
112  let root: string | undefined
113  try {
114    root = await git('rev-parse', '--show-toplevel')
115    if (root === undefined || !WORKLOG_ORIGIN_RE.test((await git('remote', 'get-url', 'origin')) ?? '')) {
116      return refused
117    }
118  } catch (error) {
119    return `worklog install failed: ${error instanceof Error ? error.message : String(error)}`
120  }
121  const result = await $.process
122    .run(['bash', 'scripts/install-local.sh'], { cwd: root })
123    .catch((error: unknown) => `worklog install failed: ${error instanceof Error ? error.message : String(error)}`)
124  if (typeof result === 'string') return result
125  return result.exitCode === 0
126    ? `worklog install: ok\n${tail(result.stdout)}`
127    : `worklog install failed (exit ${result.exitCode})\n${tail(result.stderr || result.stdout)}`
128}
129
130function typedAction(editing: 'ticket' | 'description', value: string): ReviewAction {
131  return editing === 'ticket'
132    ? { kind: 'ticket', jira_issue: value.trim() === '' ? null : value.trim() }
133    : { kind: 'description', description: value }
134}
135
136function blockLabel(block: ReviewBlock): string {
137  const description = block.description ?? ''
138  const text = description.length > 40 ? `${description.slice(0, 39)}…` : description
139  const time = `${block.started_at.slice(11, 16)}–${block.ended_at.slice(11, 16)}`
140  const hours = formatHours(block.duration_seconds).padStart(5)
141  const ticket = (block.jira_issue ?? '—').padEnd(12)
142  return `${time}  ${hours}  ${ticket}  ${block.is_personal ? 'personal  ' : ''}${text}`.trimEnd()
143}
144
145async function reviewPane($: EngineInterface, event: RenderInput<'Pane'>) {
146  const { Box, Text, Button, Input, Select } = $.ui.resolve(event)
147  const io = await makeIo($)
148  const { blocks, editing, error, selected } = await read($, review)
149  const current = blocks.find(block => block.id === selected)
150  const personalSeconds = blocks
151    .filter(block => block.is_personal)
152    .reduce((total, block) => total + block.duration_seconds, 0)
153
154  return (
155    <Box flexDirection="column" borderStyle="round" borderDimColor paddingX={1}>
156      {current === undefined ? (
157        <>
158          {error !== undefined && <Text color="red">{error}</Text>}
159          <Text dimColor>Nothing to review today.</Text>
160        </>
161      ) : (
162        <>
163          <Box justifyContent="space-between">
164            <Text bold>{current.day}</Text>
165            <Text dimColor>
166              work {formatHours(workSeconds(blocks))} · personal {formatHours(personalSeconds)}
167            </Text>
168          </Box>
169          {error !== undefined && <Text color="red">{error}</Text>}
170          <Box marginY={1}>
171            <Select
172              key="block"
173              value={String(current.id)}
174              options={blocks.map(block => ({ value: String(block.id), label: blockLabel(block) }))}
175              onSelect={value => change($, { selected: Number(value) })}
176            />
177          </Box>
178          <Box gap={3}>
179            <Button plain key="personal" hotkey="p" onPress={() => sendReview($, io, block => ({ kind: 'personal', is_personal: !block.is_personal }))}>
180              {current.is_personal ? 'work' : 'personal'}
181            </Button>
182            <Button plain key="ignore" hotkey="i" onPress={() => sendReview($, io, () => ({ kind: 'ignore', ignored: true }))}>
183              ignore
184            </Button>
185            <Button plain key="ticket" hotkey="t" onPress={() => change($, { editing: 'ticket' })}>
186              ticket
187            </Button>
188            <Button plain key="description" hotkey="d" onPress={() => change($, { editing: 'description' })}>
189              description
190            </Button>
191          </Box>
192          {editing !== undefined && (
193            <Box marginTop={1} gap={2}>
194              <Input
195                key="edit"
196                label={editing}
197                value={(editing === 'ticket' ? current.jira_issue : current.description) ?? ''}
198                onSubmit={value => sendReview($, io, () => typedAction(editing, value))}
199                onCancel={() => change($, { editing: undefined })}
200              />
201              <Button plain dimColor key="cancel" onPress={() => change($, { editing: undefined })}>
202                cancel
203              </Button>
204            </Box>
205          )}
206        </>
207      )}
208    </Box>
209  )
210}
211
212export function registerCommand(on: On): void {
213  let sessionCwd: string | undefined
214
215  on('session.start', { isInteractive: true }, async ($, event, next) => {
216    sessionCwd = event.cwd
217    await $.command.register({
218      name: 'wl',
219      description: 'Show logged hours, review today in a pane, or install origin/main',
220      argumentHint: 'today|week|review|install|ticket|ask',
221    })
222    return next(event)
223  })
224
225  on('command.run', { command: 'wl' }, async ($, event, next) => {
226    const argument = event.args.trim()
227    if (argument === 'ticket') return next(event)
228    const question = /^ask\s+(\S[\s\S]*)$/.exec(argument)?.[1]
229    if (question !== undefined) return { text: await ask(await makeIo($), question) }
230    if (argument === 'install') return { text: await install($, sessionCwd) }
231    if (argument !== 'today' && argument !== 'week' && argument !== 'review') {
232      return { text: USAGE }
233    }
234    const io = await makeIo($)
235    if (argument !== 'review') return { text: await summarise($, io, argument) }
236    await change($, { selected: undefined })
237    await loadReview($, io)
238    await $.ui.open({ id: REVIEW_PANE_ID, title: 'worklog review', focus: true, closeOnEscape: true })
239    return { text: 'worklog review opened' }
240  })
241
242  on('ui.render', { component: 'Pane', requestId: REVIEW_PANE_ID }, ($, event) =>
243    reviewPane($, event),
244  )
245}
246
hooks/status.ts 125 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On } from 'claude-code'
3import { DEFAULT_REQUIRED_SECONDS, NUDGE_STORE_PREFIX, POLL_MS } from './contract'
4import type { DaySummary, Io, WeekCloseout } from './contract'
5import {
6  daemonGet,
7  daemonToday,
8  formatHours,
9  lastWorkday,
10  mondayOf,
11  workContext,
12  workSeconds,
13} from './lib'
14
15const hours = atom(
16  { plugin: 'worklog', key: 'hours' } as const,
17  '',
18)
19
20const nudgeLine = atom(
21  { plugin: 'worklog', key: 'nudge' } as const,
22  '',
23)
24
25/** GET /recap, the fields the mod reads. */
26type Recap = {
27  day: string
28  sent: unknown[]
29  held_back: unknown[]
30  coverage_percent: number
31  gaps: unknown[]
32}
33
34const recapState = atom(
35  { plugin: 'worklog', key: 'recap' } as const,
36  { line: '', gaps: 0 },
37)
38
39async function makeIo($: EngineInterface): Promise<Io> {
40  return {
41    fetch: (url, init) => $.http.fetch(url, init),
42    run: (argv, cwd) => $.process.run(argv, { cwd }),
43    after: (milliseconds, callback) => $.clock.after(milliseconds, callback),
44    now: () => $.clock.now(),
45    home: await $.env.get('HOME'),
46  }
47}
48
49export function registerStatus(on: On): void {
50  on('session.start', async ($, event, next) => {
51    const io = await makeIo($)
52
53    async function showHours(): Promise<void> {
54      const today = await daemonToday(io)
55      const [summary, recap] = today.ok
56        ? await Promise.all([daemonGet<DaySummary>(io, `/days/${today.value}`), daemonGet<Recap | null>(io, '/recap')])
57        : [today, today]
58      const text = summary.ok ? `worklog ${formatHours(workSeconds(summary.value.blocks))}` : ''
59      await update($, hours, () => text)
60      const current = recap.ok && recap.value?.day === (today.ok ? today.value : '') ? recap.value : null
61      const shown = current
62        ? {
63            line: [
64              `recap: ${current.sent.length} sent`,
65              `${current.held_back.length} held`,
66              `${current.coverage_percent}%`,
67              ...(current.gaps.length > 0 ? [`${current.gaps.length} gaps`] : []),
68            ].join(' · '),
69            gaps: current.gaps.length,
70          }
71        : { line: '', gaps: 0 }
72      await update($, recapState, () => shown)
73    }
74
75    async function remind(): Promise<void> {
76      const context = await workContext(io, event.cwd)
77      const today = await daemonToday(io)
78      if (!context.isWork || !today.ok) return
79      const marker = `${NUDGE_STORE_PREFIX}${today.value}`
80      if (await $.store.get(marker)) return
81      const previous = lastWorkday(today.value)
82      const week = await daemonGet<WeekCloseout>(io, `/weeks/${mondayOf(previous)}/closeout`)
83      const day = week.ok ? week.value.days.find(candidate => candidate.day === previous) : undefined
84      if (day === undefined) return
85      const required = day.required_seconds ?? DEFAULT_REQUIRED_SECONDS
86      if (required === 0) return
87      const problems: string[] = []
88      if (day.pending_lines > 0) problems.push(`${day.pending_lines} unsynced lines`)
89      const worked = Math.max(day.logged_seconds, day.tempo_seconds)
90      if (worked < required) {
91        problems.push(`${formatHours(worked)} logged of ${formatHours(required)}`)
92      }
93      if (problems.length === 0) return
94      await $.ui.toast(`worklog: ${previous} has ${problems.join(' and ')}`)
95      await $.store.set(marker, true)
96    }
97
98    void showHours()
99    void remind()
100    $.clock.every(POLL_MS, () => {
101      void showHours()
102    })
103    return next(event)
104  })
105
106  let prompts = 0
107  on('prompt.submit', { origin: { kind: 'composer' } }, async ($, event, next) => {
108    const turn = prompts++
109    const io = await makeIo($)
110    void (async () => {
111      const list = await daemonGet<{ text: string }[]>(io, '/nudges')
112      const shown = list.ok && list.value.length > 0 ? list.value[turn % list.value.length].text : ''
113      await update($, nudgeLine, () => shown)
114    })()
115    return next(event)
116  })
117
118  on('ui.render', { component: 'PromptHint' }, async ($, event, next) => {
119    const recap = await read($, recapState)
120    const nudgeText = recap.gaps > 0 ? '' : await read($, nudgeLine)
121    const parts = [event.props.tail, await read($, hours), recap.line, nudgeText].filter(Boolean)
122    return next(parts.length > 0 ? { ...event, props: { ...event.props, tail: parts.join(' · ') } } : event)
123  })
124}
125
hooks/ticket.tsx 253 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On } from 'claude-code'
3import { JIRA_KEY_RE, MORE_TICKETS, TICKET_ASKED_STORE_PREFIX, TICKET_PANE_ID } from './contract'
4import type { Io, RecentTask } from './contract'
5import { cut, daemonGet, filterPickerOptions, keyOfChoice, ticketChoices, ticketPickerOptions, workContext } from './lib'
6
7const TASKS_CAP_MS = 1500
8const PICK_CAP_MS = 8000
9const EXACT_KEY_RE = new RegExp(`^${JIRA_KEY_RE.source}$`)
10
11async function makeIo($: EngineInterface): Promise<Io> {
12  return {
13    fetch: (url, init) => $.http.fetch(url, init),
14    run: (argv, cwd) => $.process.run(argv, { cwd }),
15    after: (milliseconds, callback) => $.clock.after(milliseconds, callback),
16    now: () => $.clock.now(),
17    home: await $.env.get('HOME'),
18  }
19}
20
21type TicketState = {
22  cwd: string | undefined
23  ticket: string | undefined
24  askable: boolean
25  recorded: string | undefined
26  handoff: string | undefined
27}
28
29const picker = atom({ plugin: 'worklog', key: 'picker' } as const, {
30  options: [] as { value: string; label: string }[],
31  query: '',
32})
33
34const handoffFor = (answer: string, id: string): string =>
35  answer === 'Create a new ticket'
36    ? `Instruction "create a ticket": the Owner wants a new Jira ticket for this session. Once the first request makes the task clear, create it (worklog skill, Jira recipe, one confirm), then run worklog ticket use <KEY> --session ${id}.`
37    : `Instruction "find the ticket for: ${answer}": run worklog ticket find, confirm the match with the Owner, then run worklog ticket use <KEY> --session ${id}.`
38
39async function refresh($: EngineInterface, state: TicketState): Promise<boolean> {
40  if (state.cwd === undefined) return false
41  const context = await workContext(await makeIo($), state.cwd)
42  state.ticket = context.isWork ? context.ticket : undefined
43  return context.isWork
44}
45
46async function recentTasks(io: Io): Promise<RecentTask[]> {
47  let timer: { cancel: () => void } | undefined
48  const cap = new Promise<undefined>(resolve => {
49    timer = io.after(TASKS_CAP_MS, () => resolve(undefined))
50  })
51  try {
52    const result = await Promise.race([daemonGet<{ tasks: RecentTask[] }>(io, '/tasks'), cap])
53    return result?.ok && Array.isArray(result.value.tasks) ? result.value.tasks : []
54  } finally {
55    timer?.cancel()
56  }
57}
58
59type Pick = { picked: string | undefined; likely: string | undefined }
60
61// Verdict reads the first prompt; any failure means "no pick" and the Owner is asked.
62async function verdictPick($: EngineInterface, cwd: string, id: string, ticket: string | undefined, text: string): Promise<Pick> {
63  const none: Pick = { picked: undefined, likely: undefined }
64  let timer: { cancel: () => void } | undefined
65  const cap = new Promise<undefined>(resolve => {
66    timer = $.clock.after(PICK_CAP_MS, () => resolve(undefined))
67  })
68  try {
69    const argv = ['worklog', '--json', 'ticket', 'pick', '--session', id, ...(ticket ? ['--also', ticket] : []), '--', text]
70    const result = await Promise.race([$.process.run(argv, { cwd }), cap])
71    if (result === undefined || result.exitCode !== 0) return none
72    const body = JSON.parse(result.stdout.trim()) as { picked?: unknown; likely?: unknown }
73    const key = (value: unknown) => (typeof value === 'string' && EXACT_KEY_RE.test(value) ? value : undefined)
74    return { picked: key(body.picked), likely: key(body.likely) }
75  } catch {
76    return none
77  } finally {
78    timer?.cancel()
79  }
80}
81
82async function openPicker(
83  $: EngineInterface,
84  state: TicketState,
85  tasks: RecentTask[],
86  likely?: string,
87): Promise<void> {
88  await update($, picker, () => ({ options: ticketPickerOptions(state.ticket, tasks, likely), query: '' }))
89  const opened = await $.ui.open({ id: TICKET_PANE_ID, title: 'worklog ticket', focus: true, closeOnEscape: true })
90  if (!opened.isPlaced) await $.ui.log('worklog: widen the terminal or run /wl ticket')
91}
92
93async function recordKey($: EngineInterface, cwd: string, state: TicketState, key: string, id: string): Promise<boolean> {
94  try {
95    const result = await $.process.run(['worklog', 'ticket', 'use', key, '--session', id], { cwd })
96    if (result.exitCode !== 0) throw new Error(result.stderr.trim())
97    state.recorded = key
98    state.handoff = undefined
99    await $.ui.toast(`worklog: ${key}`)
100    return true
101  } catch (error) {
102    await $.ui.log(`worklog: could not record ${key} — ${error instanceof Error ? error.message : String(error)}`)
103    return false
104  }
105}
106
107async function skipSession($: EngineInterface, cwd: string | undefined, id: string): Promise<void> {
108  try {
109    const result = await $.process.run(['worklog', 'ticket', 'skip', '--session', id], { cwd })
110    if (result.exitCode !== 0) throw new Error(result.stderr.trim())
111  } catch (error) {
112    await $.ui.log(`worklog: could not skip — ${error instanceof Error ? error.message : String(error)}`)
113  }
114}
115
116async function choose($: EngineInterface, state: TicketState, value: string): Promise<void> {
117  await $.ui.close({ id: TICKET_PANE_ID })
118  const id = await $.session.id()
119  // a pick before the first prompt must stop askTicket asking again
120  await $.store.set(`${TICKET_ASKED_STORE_PREFIX}${id}`, value)
121  if (value === 'skip') return skipSession($, state.cwd, id)
122  let note: string | undefined
123  if (value === 'create') note = state.handoff = handoffFor('Create a new ticket', id)
124  else if (state.cwd !== undefined && (await recordKey($, state.cwd, state, value, id))) {
125    note = `Session ticket: ${value} (the Owner picked it in the worklog ticket picker).`
126  }
127  // prompt.context was cached at the first prompt, so a pick from the pane is told as a row now
128  if (note !== undefined) {
129    await $.session.append({ message: { type: 'user', content: [{ type: 'text', text: note }] } }).catch(() => undefined)
130  }
131}
132
133async function askTicket($: EngineInterface, cwd: string, state: TicketState, text: string): Promise<void> {
134  const id = await $.session.id()
135  const marker = `${TICKET_ASKED_STORE_PREFIX}${id}`
136  if (await $.store.get(marker)) return
137  const { picked, likely } = await verdictPick($, cwd, id, state.ticket, text)
138  if (picked !== undefined) {
139    state.recorded = picked
140    state.handoff = undefined
141    await $.store.set(marker, picked)
142    await $.ui.toast(`worklog: ${picked} (Verdict)`)
143    return
144  }
145  const tasks = await recentTasks(await makeIo($))
146  const options = ticketChoices(state.ticket, tasks, likely).map(cut)
147  let answer: string
148  try {
149    answer = await $.ui.ask('Which Jira ticket is this session for?', { options, header: 'Ticket' })
150  } catch {
151    await $.store.set(marker, true)
152    await $.ui.log(`worklog: no ticket question shown — run worklog ticket use KEY --session ${id}`)
153    return
154  }
155  await $.store.set(marker, answer)
156  if (answer === MORE_TICKETS) return openPicker($, state, tasks, likely)
157  if (answer === 'Skip') return skipSession($, cwd, id)
158  const key = options.includes(answer) ? keyOfChoice(answer) : EXACT_KEY_RE.exec(answer)?.[1]
159  if (key === undefined) {
160    state.handoff = handoffFor(answer, id)
161    return
162  }
163  await recordKey($, cwd, state, key, id)
164}
165
166export function registerTicket(on: On): void {
167  const state: TicketState = { cwd: undefined, ticket: undefined, askable: false, recorded: undefined, handoff: undefined }
168
169  on('session.start', { surface: 'terminal' }, async ($, event, next) => {
170    state.cwd = event.cwd
171    const isWork = await refresh($, state)
172    if (state.ticket !== undefined) await $.ui.toast(`worklog: ${state.ticket}`)
173    state.askable = isWork && event.isInteractive
174    return next(event)
175  })
176
177  on('command.run', { command: 'wl' }, async ($, event, next) => {
178    if (event.args.trim() !== 'ticket') return next(event)
179    if (!state.askable || state.cwd === undefined) return { text: 'worklog ticket: not a work session' }
180    await openPicker($, state, await recentTasks(await makeIo($)))
181    return { text: 'worklog ticket picker opened' }
182  })
183
184  on('ui.render', { component: 'Pane', requestId: TICKET_PANE_ID }, async ($, event) => {
185    const { Box, Input, Select } = $.ui.resolve(event)
186    const { options, query } = await read($, picker)
187    const shown = filterPickerOptions(options, query)
188    return (
189      <Box flexDirection="column" borderStyle="round" borderDimColor paddingX={1}>
190        <Input
191          key="filter"
192          autoFocus
193          placeholder="type to filter, Enter picks the first"
194          value={query}
195          submitLabel="pick"
196          onInput={value => update($, picker, current => ({ ...current, query: value }))}
197          onSubmit={async value => {
198            const first = filterPickerOptions(options, value).find(option => option.value !== 'create' && option.value !== 'skip')
199            if (first !== undefined) await choose($, state, first.value)
200          }}
201        />
202        <Select key="ticket" options={shown} onSelect={value => choose($, state, value)} />
203      </Box>
204    )
205  })
206
207  on('session.end', async ($, event, next) => {
208    if (event.reason === 'clear') {
209      state.recorded = undefined
210      state.handoff = undefined
211    }
212    return next(event)
213  })
214
215  // The first prompt (and the first after /clear) picks or asks the ticket before it enters.
216  // The hand-off rides on each prompt: prompt.context is computed once and cached, so it would never carry it.
217  on('prompt.submit', async ($, event, next) => {
218    if (state.askable && state.cwd !== undefined) await askTicket($, state.cwd, state, event.text).catch(() => undefined)
219    return next(state.handoff === undefined ? event : { ...event, context: [...(event.context ?? []), state.handoff] })
220  })
221
222  on('prompt.context', async ($, event, next) => {
223    const result = await next(event)
224    const ticket = state.recorded ?? state.ticket
225    const text = state.recorded === undefined ? `Current branch ticket: ${ticket}` : `Session ticket: ${ticket}`
226    return ticket === undefined ? result : { ...result, blocks: [...result.blocks, { name: 'worklog', text }] }
227  })
228
229  for (const kind of ['commit', 'pr'] as const) {
230    on('attribution.text', { kind }, async ($, event, next) => {
231      const result = await next(event)
232      const ticket = state.recorded ?? state.ticket
233      return ticket === undefined ? result : { ...result, text: `${result.text}\n\nTicket: ${ticket}` }
234    })
235  }
236
237  on('tool.call', { tool: 'Bash' }, async ($, event, next) => {
238    const result = await next(event)
239    if (result.deny !== undefined || result.isError === true) return result
240    const [, key, id] = /worklog ticket use (\S+) --session (\S+)/.exec(event.command) ?? []
241    if (key !== undefined && EXACT_KEY_RE.test(key) && id === (await $.session.id())) {
242      state.recorded = key
243      state.handoff = undefined
244    }
245    return result
246  })
247
248  on('turn.complete', async ($, event, next) => {
249    void refresh($, state)
250    return next(event)
251  })
252}
253
hooks/contract.ts 99 lines
1// Shared shapes for the worklog Claude Code mod. Owned by the spec
2// orchestrator: task code imports from here and never redeclares these.
3// Field names mirror the daemon's JSON exactly (rust/crates/worklog-core).
4
5export const DAEMON_URL = 'http://127.0.0.1:9323'
6export const POLL_MS = 60_000
7export const DEFAULT_REQUIRED_SECONDS = 8 * 3600
8export const NUDGE_STORE_PREFIX = 'nudge:'
9export const TICKET_ASKED_STORE_PREFIX = 'ticket-asked:'
10export const REVIEW_PANE_ID = 'worklog-review'
11export const TICKET_PANE_ID = 'worklog-ticket'
12export const MORE_TICKETS = 'More tickets…'
13export const JIRA_KEY_RE = /\b([A-Z][A-Z0-9]{1,9}-\d+)\b/
14
15/** A local calendar day, `YYYY-MM-DD`, in the daemon's WORKLOG_TZ. */
16export type LocalDay = string
17
18/** What a session knows about where it runs; computed from the cwd. */
19export type WorkContext = {
20  cwd: string
21  /** Under ~/Work/ (or legacy ~/Desktop/Work/) or the git `origin` remote is in the aproorg org. */
22  isWork: boolean
23  branch: string | undefined
24  /** First Jira key in the branch name, if any. */
25  ticket: string | undefined
26}
27
28/** `Block` from models.rs, the fields the mod reads. */
29export type Block = {
30  id: number
31  day: LocalDay
32  jira_issue: string | null
33  started_at: string
34  ended_at: string
35  duration_seconds: number
36  description: string | null
37  is_personal: boolean
38  ignored_at: string | null
39  tempo_worklog_id: string | null
40  exported_at: string | null
41}
42
43/** GET /days/:day — `DaySummary`, the fields the mod reads. */
44export type DaySummary = {
45  day: LocalDay
46  total_seconds: number
47  blocks: (Block & { project: string | null })[]
48}
49
50/** GET /logged?from&to — `LoggedRange`; the mod reads only `today`. */
51export type LoggedRange = { today: LocalDay }
52
53/** `GET /tasks` entry, the fields the mod reads. */
54export type RecentTask = {
55  key: string
56  summary: string
57  assigned: boolean
58  last_worked_day: string | null
59}
60
61/** One day of GET /weeks/:monday/closeout. */
62export type CloseoutDay = {
63  day: LocalDay
64  logged_seconds: number
65  synced_seconds: number
66  tempo_seconds: number
67  required_seconds: number | null
68  pending_lines: number
69}
70
71/** GET /weeks/:monday/closeout, the fields the mod reads. */
72export type WeekCloseout = { days: CloseoutDay[] }
73
74/**
75 * The engine capabilities lib.ts needs. The validator only follows `$` into
76 * functions declared in the same file, so lib.ts never receives `$`: each hook
77 * file builds an `Io` from closures over its own `$` and passes that instead.
78 */
79export type Io = {
80  fetch: (
81    url: string,
82    init?: { method?: string; headers?: Record<string, string>; body?: string },
83  ) => Promise<{ status: number; ok: boolean; text: string }>
84  run: (argv: string[], cwd: string) => Promise<{ exitCode: number; stdout: string }>
85  after: (ms: number, fn: () => void) => { cancel(): void }
86  now: () => Promise<number>
87  home: string | undefined
88}
89
90/** Every daemon call resolves to this; never throws. */
91export type DaemonResult<T> = { ok: true; value: T } | { ok: false; error: string }
92
93/** The four review actions (D-09) and their daemon routes + bodies. */
94export type ReviewAction =
95  | { kind: 'personal'; is_personal: boolean }
96  | { kind: 'ignore'; ignored: boolean }
97  | { kind: 'ticket'; jira_issue: string | null }
98  | { kind: 'description'; description: string }
99
hooks/lib.ts 208 lines
1import { DAEMON_URL, JIRA_KEY_RE, MORE_TICKETS } from './contract'
2import type {
3  Block,
4  DaemonResult,
5  Io,
6  LocalDay,
7  RecentTask,
8  ReviewAction,
9  WorkContext,
10} from './contract'
11
12const TIMEOUT_MS = 2000
13const DAY_MS = 24 * 3600 * 1000
14const WORK_ORIGIN_RE = /github\.com[:/]aproorg\//
15
16function shiftDay(day: LocalDay, days: number): LocalDay {
17  return new Date(Date.parse(`${day}T00:00:00Z`) + days * DAY_MS).toISOString().slice(0, 10)
18}
19
20function weekdayOf(day: LocalDay): number {
21  return new Date(`${day}T00:00:00Z`).getUTCDay()
22}
23
24export function lastWorkday(today: LocalDay): LocalDay {
25  const weekday = weekdayOf(today)
26  if (weekday === 1) return shiftDay(today, -3)
27  if (weekday === 0) return shiftDay(today, -2)
28  return shiftDay(today, -1)
29}
30
31export function mondayOf(day: LocalDay): LocalDay {
32  return shiftDay(day, -((weekdayOf(day) + 6) % 7))
33}
34
35export function workSeconds(blocks: readonly Block[]): number {
36  return blocks
37    .filter(block => !block.is_personal && block.ignored_at === null)
38    .reduce((total, block) => total + block.duration_seconds, 0)
39}
40
41export function formatHours(seconds: number): string {
42  const minutes = Math.round(seconds / 60)
43  return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, '0')}`
44}
45
46export function ticketFromBranch(branch: string | undefined): string | undefined {
47  return branch?.match(JIRA_KEY_RE)?.[1]
48}
49
50const LABEL_MAX = 60
51
52export const cut = (label: string): string =>
53  label.length > LABEL_MAX ? `${label.slice(0, LABEL_MAX - 1)}…` : label
54
55const leadKeys = (branchTicket: string | undefined, likely: string | undefined): string[] =>
56  [likely, branchTicket !== likely ? branchTicket : undefined].filter(
57    (key): key is string => key !== undefined,
58  )
59
60const newestFirst = (tasks: readonly RecentTask[], skip: readonly string[]): RecentTask[] =>
61  tasks
62    .filter((task) => task.assigned && !skip.includes(task.key))
63    .sort((a, b) => (b.last_worked_day ?? '').localeCompare(a.last_worked_day ?? ''))
64
65export function ticketChoices(
66  branchTicket: string | undefined,
67  recentTasks: readonly RecentTask[],
68  likely?: string,
69): string[] {
70  const label = (key: string) => {
71    const task = recentTasks.find((t) => t.key === key)
72    return task ? `${key} ${task.summary}` : key
73  }
74  const lead = leadKeys(branchTicket, likely)
75  const candidates = newestFirst(recentTasks, lead)
76  const recent = candidates.slice(0, Math.max(0, 2 - lead.length))
77  return [
78    ...lead.map((key) => (key === likely ? label(key) : key)),
79    ...recent.map((task) => `${task.key} ${task.summary}`),
80    candidates.length > recent.length ? MORE_TICKETS : 'Create a new ticket',
81    'Skip',
82  ]
83}
84
85export function ticketPickerOptions(
86  branchTicket: string | undefined,
87  recentTasks: readonly RecentTask[],
88  likely?: string,
89): { value: string; label: string }[] {
90  const label = (key: string) => {
91    const task = recentTasks.find((t) => t.key === key)
92    return cut(task ? `${key} ${task.summary}` : key)
93  }
94  const lead = leadKeys(branchTicket, likely)
95  return [
96    ...lead.map((key) => ({ value: key, label: label(key) })),
97    ...newestFirst(recentTasks, lead).map((task) => ({ value: task.key, label: label(task.key) })),
98    { value: 'create', label: 'Create a new ticket' },
99    { value: 'skip', label: 'Skip' },
100  ]
101}
102
103// Every word of the query must appear in the label, any case; 'create' and 'skip' always stay.
104export function filterPickerOptions(
105  options: readonly { value: string; label: string }[],
106  query: string,
107): { value: string; label: string }[] {
108  const words = query.toLowerCase().split(/\s+/).filter(Boolean)
109  return options.filter(
110    (option) =>
111      option.value === 'create' || option.value === 'skip' || words.every((word) => option.label.toLowerCase().includes(word)),
112  )
113}
114
115export function keyOfChoice(label: string): string | undefined {
116  return label.match(new RegExp(`^${JIRA_KEY_RE.source}(?:\\s|$)`))?.[1]
117}
118
119export function reviewRequest(
120  blockId: number,
121  action: ReviewAction,
122): { path: string; body: unknown } {
123  const path = `/blocks/${blockId}`
124  switch (action.kind) {
125    case 'personal':
126      return { path: `${path}/personal`, body: { is_personal: action.is_personal } }
127    case 'ignore':
128      return { path: `${path}/ignore`, body: { ignored: action.ignored } }
129    case 'ticket':
130      return { path: `${path}/ticket`, body: { jira_issue: action.jira_issue } }
131    case 'description':
132      return { path: `${path}/description`, body: { description: action.description } }
133  }
134}
135
136async function daemonRequest<T>(
137  io: Io,
138  path: string,
139  init?: { method: string; headers: Record<string, string>; body: string },
140): Promise<DaemonResult<T>> {
141  const request = async (): Promise<DaemonResult<T>> => {
142    try {
143      const response = await io.fetch(`${DAEMON_URL}${path}`, init)
144      let body: unknown
145      try {
146        body = JSON.parse(response.text)
147      } catch {
148        body = undefined
149      }
150      if (response.ok && body !== undefined) return { ok: true, value: body as T }
151      const message = (body as { error?: unknown } | undefined)?.error
152      return { ok: false, error: typeof message === 'string' ? message : `HTTP ${response.status}` }
153    } catch (error) {
154      return { ok: false, error: error instanceof Error ? error.message : String(error) }
155    }
156  }
157  let timer: { cancel: () => void } | undefined
158  const timeout = new Promise<DaemonResult<T>>(resolve => {
159    timer = io.after(TIMEOUT_MS, () => resolve({ ok: false, error: 'timeout' }))
160  })
161  try {
162    return await Promise.race([request(), timeout])
163  } finally {
164    timer?.cancel()
165  }
166}
167
168export function daemonGet<T>(io: Io, path: string): Promise<DaemonResult<T>> {
169  return daemonRequest<T>(io, path)
170}
171
172export function daemonPost<T>(io: Io, path: string, body: unknown): Promise<DaemonResult<T>> {
173  return daemonRequest<T>(io, path, {
174    method: 'POST',
175    headers: { 'content-type': 'application/json' },
176    body: JSON.stringify(body),
177  })
178}
179
180export async function daemonToday(io: Io): Promise<DaemonResult<LocalDay>> {
181  const utcDay = new Date(await io.now()).toISOString().slice(0, 10)
182  const result = await daemonGet<{ today: LocalDay }>(io, `/logged?from=${utcDay}&to=${utcDay}`)
183  return result.ok ? { ok: true, value: result.value.today } : result
184}
185
186async function gitOutput(io: Io, cwd: string, argv: string[]): Promise<string | undefined> {
187  try {
188    const result = await io.run(['git', ...argv], cwd)
189    return result.exitCode === 0 ? result.stdout.trim() : undefined
190  } catch {
191    return undefined
192  }
193}
194
195export async function workContext(io: Io, cwd: string): Promise<WorkContext> {
196  // `~/Work` is live; `~/Desktop/Work` is the legacy root historical sessions used.
197  const workFolders = io.home === undefined ? [] : [`${io.home}/Work`, `${io.home}/Desktop/Work`]
198  const inWorkFolder = workFolders.some((w) => cwd === w || cwd.startsWith(`${w}/`))
199  const branch = (await gitOutput(io, cwd, ['branch', '--show-current'])) || undefined
200  const origin = inWorkFolder ? undefined : await gitOutput(io, cwd, ['remote', 'get-url', 'origin'])
201  return {
202    cwd,
203    isWork: inWorkFolder || WORK_ORIGIN_RE.test(origin ?? ''),
204    branch,
205    ticket: ticketFromBranch(branch),
206  }
207}
208
types/index.d.ts 32 lines
1export type WorklogReviewBlock = {
2  id: number
3  day: string
4  jira_issue: string | null
5  started_at: string
6  ended_at: string
7  duration_seconds: number
8  description: string | null
9  is_personal: boolean
10  ignored_at: string | null
11  tempo_worklog_id: string | null
12  exported_at: string | null
13  project: string | null
14}
15
16export type WorklogReview = {
17  blocks: WorklogReviewBlock[]
18  selected: number | undefined
19  editing: 'ticket' | 'description' | undefined
20  error: string | undefined
21}
22
23declare module 'claude-code' {
24  interface PluginState {
25    worklog: {
26      review: WorklogReview
27      hours: string
28      picker: { options: { value: string; label: string }[]; query: string }
29    }
30  }
31}
32