From 0cf4fb19cdab004ec11cc386ce03c0e8b68d1daf Mon Sep 17 00:00:00 2001 From: "Maksym Hryzodub [DREAM]" Date: Tue, 1 Dec 2026 00:12:03 +0200 Subject: [PATCH] chore(skills): the timesheet reads solidtime and Plane instead of Jira (RANCH-4) The monthly table used to estimate hours from Jira events and commits, because Jira held no worklogs. The tracker is Plane now and time is kept in solidtime, so the hours are the ones tracked: one row per task per day, in quarter hours. - collect.mjs reads the key owner's solidtime entries, the RANCH work items with their state changes and comments, and the git clones as before - build-csv.mjs links rows to Plane and needs no key - the two commands, the CSV columns and the file name are unchanged - no Jira call and no JIRA_* read is left; months before 2026-11-30 cannot be rebuilt through the skill, and it says so --- .claude/skills/timesheet/SKILL.md | 139 ++++--- .../skills/timesheet/scripts/build-csv.mjs | 27 +- .claude/skills/timesheet/scripts/collect.mjs | 375 +++++++++++------- .claude/skills/timesheet/scripts/env.mjs | 98 ++++- 4 files changed, 405 insertions(+), 234 deletions(-) diff --git a/.claude/skills/timesheet/SKILL.md b/.claude/skills/timesheet/SKILL.md index 52ca0dc4e..4c5e8d258 100644 --- a/.claude/skills/timesheet/SKILL.md +++ b/.claude/skills/timesheet/SKILL.md @@ -2,104 +2,110 @@ name: timesheet description: Use when someone asks for their monthly hours, a timesheet, a work report for a month, "таблица часов", "отчёт за месяц", "табель", or a - Jira/git activity table to import into Google Sheets. + table of tracked time and git activity to import into Google Sheets. --- # timesheet -Builds one person's month as a table — date, day, ticket, link, description, -hours — from Jira and the git clones, as a CSV that Google Sheets imports. +Builds one person's month as a table — date, day, task, link, description, +hours — from solidtime, Plane and the git clones, as a CSV that Google Sheets +imports. -Two scripts do the mechanical part. Deciding the hours and wording each row is -yours: Jira holds no worklogs, so every number is an estimate from evidence. +Two scripts do the mechanical part. The hours are the ones solidtime tracked; +wording each row is yours. + +Hours exist in solidtime from 2026-11-30. Earlier months were estimated from +Jira, which this skill no longer reads, so they cannot be rebuilt here. The delivery cycle in `CLAUDE.md` is for changes to the repo. This report makes -none, so it takes no Jira ticket, no branch and no commit. +none, so it takes no task, no branch, no commit and no time entry. ## 1 · Collect ```bash -node .claude/skills/timesheet/scripts/collect.mjs --month 2026-09 +node .claude/skills/timesheet/scripts/collect.mjs --month 2026-12 ``` Without `--month` it takes the current month from the 15th on, the previous one before that. It scans this clone plus the `runtime` and `bridle` clones beside it (`--repos a,b` to override, `--out file.json` to choose where the -data lands). +data lands). It reads `TIME_API_KEY` and `TASKS_API_KEY` from `.env.project` +and only reads: nothing is written to solidtime or Plane. It prints a short header and two paths. Read the `digest` file in full: it is -the month day by day, each ticket with its Jira events and commits. `data` is -the same as JSON. +the month day by day, each task with its time entries, its Plane events and +its commits. `data` is the same as JSON. + +Everything in the digest is the person's own: time they tracked, commits they +authored, tasks they created, status changes and comments they made. Work +before 05:00 is already filed under the evening before and marked `+1d`; a +time entry belongs, whole, to the working day it started on. -Everything in the digest is the person's own: commits they authored, tickets -they created, status changes and comments they made. Work before 05:00 is -already filed under the evening before and marked `+1d`. +A time entry counts for ranch when its description, or its solidtime task, +names a `RANCH-` id, or when it sits in a solidtime project called ranch. +The rest of the person's entries (other projects, no id) stay out, and the +header counts them. ## 2 · Read the identity line first -The first line of the header says whose month this is. +The first line of the header says whose month this is. It is always the owner +of the two keys in `.env.project`: solidtime answers with nobody else's time. | First line | What to do | |---|---| -| `identity: … (verified)` | `git config user.email` was found in Jira. Carry on. | -| `WARNING identity: …` | The git address is unset or unknown to Jira, and the data is the **default person's**. Build the table all the same, and open your reply with the warning, naming both addresses, before anything else. | +| `identity: … (verified)` | `git config user.email` is the key owner's address. Carry on. | +| `WARNING identity: …` | The git address is unset or is somebody else's, and the data is the **key owner's**. Build the table all the same, and open your reply with the warning, naming both addresses, before anything else. | | `timesheet: …` and exit 1 | Nothing was collected. Report the message and stop. | The person is never chosen by name, by guess, or from the conversation. To -report for someone else, that person runs it from their own clone. +report for someone else, that person runs it from their own clone, with their +own keys. -## 3 · Turn evidence into rows +## 3 · Turn the digest into rows -One row per ticket per day. Take the first line of this table that fits: +One row per task per day. Take the first line of this table that fits: -| The ticket that day | Row | +| The task that day | Row | |---|---| -| is `absent in Jira` | no | -| is marked `assignee: …` (someone else, or nobody) and has no commit | no | -| has a commit | yes | -| has a comment | yes | -| was `created`, and is a `subtask of` a ticket with a row that day | no, it is part of the parent's row | -| was `created` | yes, 1 hour, as the write-up of the task | -| only changed status | no | - -`(no ticket)` commits join a ticket when the subject names the same feature as -that ticket's title or its other commits; they count as that ticket's commits, -and may give it a row on a day it has nothing else. The rest stay out. List -both kinds under assumptions. +| has `tracked H:MM -> N` | yes, with `N` hours | +| is `(no task)` with tracked time | joins a task when the entry's description names the same work as that task's title or commits; otherwise no | +| shows `no time tracked` | no | + +`(no task)` commits join a task when the subject names the same feature as +that task's title or its other commits; they help word its row and never add +hours. **Hours** -- Whole numbers, 1 at the least. -- Each row is weighed on its own evidence: the number of commits, the span - between the first and last event, spec/plan/tasks commits, a release bump. - A ticket opened and sent to testing within minutes on one commit is 1. A - ticket with a spec and a dozen commits is 3 or more. A lone `(#NN)` merge - days after the work is 1: review and merge. -- Tickets worked side by side in the same hour share that hour. Commits that - carry one timestamp were rebased together; count them, ignore their span. -- A commit naming two tickets counts for both, and its weight is shared, not - doubled. -- A day is the sum of its rows. A full weekday usually comes to 6–8; that is - what to expect, not a number to reach. -- Above 10 hours `build-csv.mjs` names the day. Take hours off its largest - rows, unless the 1-hour minimums alone make the day that long. +- The number after the arrow, as it is: tracked time to the nearest quarter of + an hour, a quarter at the least. Never estimate, never round up to a whole + hour, never move time to another task or day. +- `(running)` means the entry had no end yet and was counted up to the moment + of the run. Say so. +- `days with work that has no time tracked` — those tasks get no row. List the + days and their tasks, and ask. Hours the person then names for them go in as + rows and under assumptions, as their word. +- `days where entries overlap` — two entries ran at once, so the day's rows add + up to more than the clock. Rows keep each task's own time; name the day with + both numbers. +- Above 10 hours `build-csv.mjs` names the day. Look for an overlap or a timer + left running and report what you find. Do not trim it yourself. +- A `CLEAN-` id is from Jira, the tracker before Plane. Tracked time under + one still gets its row, without a link and worded from its commits. **Days** - `weekdays still ahead` — leave them out and say so. - `today` — today gets what it shows so far. Say the day was not over. -- `weekdays without any activity` — leave them out, list them, and ask what - was done on them. -- When the person has said they worked every weekday in full, and only then: - a weekday under 6 is raised to 6 on its largest row, and a weekday without - activity gets the nearest large ticket at 6. List every such day under - assumptions. +- `weekdays without any activity` — leave them out and list them. - A weekend day gets what it shows. +- `solidtime holds hours from …` — the days before that date have no rows. + Say so, with the date. **Descriptions** — Russian, one line, up to about 100 characters, no full stop. -Say what landed that day, from the commit subjects. When a ticket spans -several days, each day names its own part. A row without commits is worded -from the ticket title: `Постановка: …` when the ticket was created that day, +Say what landed that day, from the commit subjects. When a task spans several +days, each day names its own part. A row without commits is worded from the +task title: `Постановка: …` when the task was created that day, `Проверка и обсуждение: …` otherwise. ## 4 · Build the CSV @@ -107,8 +113,8 @@ from the ticket title: `Постановка: …` when the ticket was created t Write the rows to a file in the scratchpad or temp directory: ```json -{ "month": "2026-09", "rows": [ - { "date": "2026-09-01", "key": "CLEAN-55", "text": "Статус «unreachable», когда рантайм не подключён к хабу", "hours": 2 } +{ "month": "2026-12", "rows": [ + { "date": "2026-12-01", "key": "RANCH-4", "text": "Табель читает часы из solidtime и задачи из Plane", "hours": 1.25 } ] } ``` @@ -122,20 +128,27 @@ Exit 1 lists rows to fix; fix them and run it again. A `days above 10h` line comes with exit 0 and a written file: see Hours. Do not write the CSV by hand. `рабочих дней` in the last row counts every day worked, weekends too. +Hours are written with a decimal comma (`1,25`), which a sheet with a Russian +or Ukrainian locale reads as a number. For a sheet with an English locale add +`--decimal dot`. + ## 5 · Report In the language the person wrote in, in this order: -1. Whose month it is: the Jira name and the address. With the identity - warning, if there was one, in front of it. +1. Whose month it is: the name and the address. With the identity warning, if + there was one, in front of it. 2. The path of the CSV, the number of rows and days, the total hours. 3. Hours per day. -4. Assumptions: days filled on the person's word, commits without a ticket, - tickets of other people, weekend rows, days left out, today if unfinished. -5. That the hours are estimates, to be looked over before the table is sent. +4. What is not in the table: days and tasks with work and no time tracked, + entries that name no task, entries of other projects, days before solidtime + held hours, days left out. +5. Assumptions: hours taken on the person's word, overlapping entries, an entry + still running, today if unfinished, weekend rows. ## Never - Print or paste values from `.env.project`. -- Invent a ticket, a day or a commit the digest does not show. +- Invent a task, a day, a commit or an hour the digest does not show. +- Write to solidtime or Plane: this skill only reads. - Leave the CSV inside the repo. diff --git a/.claude/skills/timesheet/scripts/build-csv.mjs b/.claude/skills/timesheet/scripts/build-csv.mjs index ede1f61cf..adefa1614 100644 --- a/.claude/skills/timesheet/scripts/build-csv.mjs +++ b/.claude/skills/timesheet/scripts/build-csv.mjs @@ -1,37 +1,40 @@ // Turns the agreed rows into the CSV that Google Sheets imports. // -// node .claude/skills/timesheet/scripts/build-csv.mjs --rows rows.json [--out file.csv] +// node .claude/skills/timesheet/scripts/build-csv.mjs --rows rows.json [--out file.csv] [--decimal dot] // -// rows.json: { "month": "2026-09", "rows": [{ "date": "2026-09-01", "key": "CLEAN-55", "text": "…", "hours": 2 }] } +// rows.json: { "month": "2026-12", "rows": [{ "date": "2026-12-01", "key": "RANCH-4", "text": "…", "hours": 1.25 }] } import { existsSync, readFileSync, writeFileSync } from 'node:fs'; import { homedir, tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; -import { DAY_NAMES, jiraBase, loadEnv, monthBounds, parseArgs, repoRoot } from './env.mjs'; +import { DAY_NAMES, QUARTER, monthBounds, parseArgs, taskUrl } from './env.mjs'; const HEADER = ['Дата', 'День', 'Задача', 'Ссылка', 'Описание', 'Часы']; const LONG_DAY_HOURS = 10; const args = parseArgs(process.argv.slice(2)); if (typeof args.rows !== 'string') throw new Error('--rows is required.'); +const decimal = args.decimal ?? 'comma'; +if (decimal !== 'comma' && decimal !== 'dot') throw new Error(`--decimal expects comma or dot, got "${decimal}".`); const { month, rows } = JSON.parse(readFileSync(resolve(args.rows), 'utf8')); monthBounds(month); if (!Array.isArray(rows) || rows.length === 0) throw new Error('rows.json has no rows.'); -const base = jiraBase(loadEnv(repoRoot())); const problems = []; rows.forEach((row, index) => { const where = `row ${index + 1} (${row.date} ${row.key})`; if (!/^\d{4}-\d{2}-\d{2}$/.test(row.date ?? '') || !row.date.startsWith(`${month}-`)) { problems.push(`${where}: date is outside ${month}`); } - if (!/^[A-Z][A-Z0-9]+-\d+$/.test(row.key ?? '')) problems.push(`${where}: key is not a ticket id`); - if (!Number.isInteger(row.hours) || row.hours < 1) problems.push(`${where}: hours must be a whole number, 1 or more`); + if (!/^[A-Z][A-Z0-9]+-\d+$/.test(row.key ?? '')) problems.push(`${where}: key is not a task id`); + if (typeof row.hours !== 'number' || row.hours < QUARTER || !Number.isInteger(row.hours / QUARTER)) { + problems.push(`${where}: hours must be a number of quarter hours, ${QUARTER} or more`); + } if (typeof row.text !== 'string' || !row.text.trim()) problems.push(`${where}: description is empty`); }); const pairs = rows.map((row) => `${row.date} ${row.key}`); for (const pair of new Set(pairs.filter((value, index) => pairs.indexOf(value) !== index))) { - problems.push(`${pair}: the same ticket appears twice on one day, merge the rows`); + problems.push(`${pair}: the same task appears twice on one day, merge the rows`); } if (problems.length) { console.error(problems.join('\n')); @@ -47,16 +50,20 @@ const cell = (value) => { return /[",\r\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text; }; +// A sheet in a Russian or Ukrainian locale reads "1.5" as the first of May, and one in an +// English locale reads "1,5" as text. The headers are Russian, so comma is the default. +const hoursCell = (hours) => (decimal === 'comma' ? String(hours).replace('.', ',') : String(hours)); + const perDay = new Map(); const lines = [HEADER]; for (const row of sorted) { const [year, monthNumber, day] = row.date.split('-'); const name = DAY_NAMES[new Date(`${row.date}T12:00:00`).getDay()]; - lines.push([`${day}.${monthNumber}.${year}`, name, row.key, `${base}/browse/${row.key}`, row.text.trim(), row.hours]); + lines.push([`${day}.${monthNumber}.${year}`, name, row.key, taskUrl(row.key), row.text.trim(), hoursCell(row.hours)]); perDay.set(row.date, (perDay.get(row.date) ?? 0) + row.hours); } const total = [...perDay.values()].reduce((sum, hours) => sum + hours, 0); -lines.push(['ИТОГО', '', '', '', `${perDay.size} рабочих дней`, total]); +lines.push(['ИТОГО', '', '', '', `${perDay.size} рабочих дней`, hoursCell(total)]); const downloads = join(homedir(), 'Downloads'); const folder = existsSync(downloads) ? downloads : tmpdir(); @@ -67,4 +74,4 @@ console.log(`csv ${out}`); console.log(`rows ${rows.length} · days ${perDay.size} · hours ${total}`); console.log([...perDay].map(([date, hours]) => `${date.slice(8)}:${hours}`).join(' ')); const long = [...perDay].filter(([, hours]) => hours > LONG_DAY_HOURS).map(([date, hours]) => `${date} (${hours}h)`); -if (long.length) console.log(`days above ${LONG_DAY_HOURS}h, bring them down: ${long.join(', ')}`); +if (long.length) console.log(`days above ${LONG_DAY_HOURS}h, check them for overlap: ${long.join(', ')}`); diff --git a/.claude/skills/timesheet/scripts/collect.mjs b/.claude/skills/timesheet/scripts/collect.mjs index 6fbde006e..2887c23e1 100644 --- a/.claude/skills/timesheet/scripts/collect.mjs +++ b/.claude/skills/timesheet/scripts/collect.mjs @@ -1,91 +1,81 @@ -// Collects one person's month from Jira and the local git clones. +// Collects one person's month from solidtime, Plane and the local git clones. // // node .claude/skills/timesheet/scripts/collect.mjs [--month YYYY-MM] [--repos a,b] [--out file.json] // -// The person is whoever `git config user.email` says, confirmed against Jira. Anyone can -// run this, so an address Jira does not know never silently becomes somebody's hours: -// the script falls back to the default address and says so in the first lines it prints. +// The person is whoever owns the two keys in `.env.project`: solidtime only ever answers +// with its key owner's entries. `git config user.email` has to name the same person; when +// it does not, the month is still the key owner's and the first lines printed say so. import { existsSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { basename, dirname, join, resolve } from 'node:path'; import { DAY_NAMES, + LEGACY_PREFIX, + TASK_PREFIX, + TIME_ORGANIZATION_ID, + TRACKED_SINCE, + clock, defaultMonth, git, - jiraBase, - jiraClient, loadEnv, localDate, localTime, monthBounds, parseArgs, + planeClient, repoRoot, + taskUrl, + timeClient, + toHours, tryGit, } from './env.mjs'; -const DEFAULT_EMAIL = 'maksym.hryzodub@dreamvention.com'; const SIBLING_REPOS = ['runtime', 'bridle']; const FIELD_SEPARATOR = '\x1f'; const NIGHT_ENDS_AT = 5; +const NO_TASK = '(no task)'; const args = parseArgs(process.argv.slice(2)); const root = repoRoot(); const env = loadEnv(root); -const jira = jiraClient(env); -const project = env.JIRA_PROJECT || 'CLEAN'; +const plane = planeClient(env); +const time = timeClient(env); const month = typeof args.month === 'string' ? args.month : defaultMonth(); const { start, end } = monthBounds(month); const now = new Date(); const inMonth = (date) => date >= start && date < end; const sameAddress = (a, b) => (a ?? '').toLowerCase() === (b ?? '').toLowerCase(); +const keyPattern = () => new RegExp(`\\b(?:${TASK_PREFIX}|${LEGACY_PREFIX})-\\d+\\b`, 'g'); +const isLegacy = (key) => key.startsWith(`${LEGACY_PREFIX}-`); -// Jira hides addresses in its answers, so the proof is the query itself: the full address -// goes in, and exactly one person of the project has to come back. Names are never tried, -// a name is not a credential. -async function findJiraUser(email) { - if (sameAddress(email, env.JIRA_EMAIL)) return jira('/rest/api/3/myself'); - const query = encodeURIComponent(email); - // The plain user search needs a global permission most tokens lack and then answers []. - const searches = [ - `/rest/api/3/user/assignable/search?project=${project}&query=${query}`, - `/rest/api/3/user/search?query=${query}`, - ]; - for (const path of searches) { - const found = (await jira(path, { allowMissing: true })) ?? []; - const people = found.filter((user) => user.accountType === 'atlassian' && user.active !== false); - const exact = people.filter((user) => sameAddress(user.emailAddress, email)); - if (exact.length === 1) return exact[0]; - if (people.length === 1) return people[0]; - } - return null; -} - +// Both keys are personal, so who they belong to is the answer to "whose month is this". async function resolveIdentity() { - const gitEmail = tryGit(root, ['config', 'user.email']); - const gitName = tryGit(root, ['config', 'user.name']); - const fallback = env.TIMESHEET_DEFAULT_EMAIL || DEFAULT_EMAIL; - - if (gitEmail) { - const user = await findJiraUser(gitEmail); - if (user) return { source: 'git', gitEmail, gitName, email: gitEmail, user, warning: null }; + const timeUser = (await time('/users/me')).data; + const planeUser = await plane('/users/me/'); + if (!sameAddress(timeUser.email, planeUser.email)) { + throw new Error( + `TIME_API_KEY belongs to ${timeUser.email} and TASKS_API_KEY to ${planeUser.email}. ` + + 'A month is one person: both keys have to be theirs.', + ); } + const memberships = (await time('/users/me/memberships')).data ?? []; + const membership = memberships.find((item) => item.organization?.id === TIME_ORGANIZATION_ID); + if (!membership) throw new Error(`${timeUser.email} is not a member of the solidtime organization.`); - const reason = gitEmail - ? `git user.email ${gitEmail} was not found in Jira` - : 'git user.email is not set in this clone'; - const user = await findJiraUser(fallback); - if (!user) { - throw new Error(`${reason}, and the default address ${fallback} was not found in Jira either. Nothing to report.`); - } + const gitEmail = tryGit(root, ['config', 'user.email']); + const warning = sameAddress(gitEmail, timeUser.email) + ? null + : `${gitEmail ? `git user.email ${gitEmail} is not` : 'git user.email is not set, so it cannot be checked against'} ` + + `the owner of the keys in .env.project, ${timeUser.email} (${timeUser.name}). ` + + "This table is the key owner's: their hours, their tasks, their commits. " + + 'It is not necessarily the month of whoever ran the command.'; return { - source: 'default', gitEmail: gitEmail || null, - gitName: gitName || null, - email: fallback, - user, - warning: - `${reason}. Fell back to the default address ${fallback} (Jira: ${user.displayName}). ` + - 'This table belongs to that person, not necessarily to whoever ran the command.', + email: timeUser.email, + name: timeUser.name, + memberId: membership.id, + planeUserId: planeUser.id, + warning, }; } @@ -133,82 +123,109 @@ function ownCommits(commits, email) { .sort((a, b) => a.date - b.date); } -const ISSUE_FIELDS = 'summary,status,created,creator,assignee,comment,parent'; +// solidtime entries of the month, each told apart as ranch's or somebody else's project. +// A ranch entry names its task in the description, `RANCH-12 · title`; once the +// organization has a project and tasks for ranch, their names say the same. +async function readEntries(memberId) { + const [projects, tasks, raw] = await Promise.all([ + time(`${time.organization}/projects`, { allowMissing: true }), + time(`${time.organization}/tasks`, { allowMissing: true }), + time.entries(memberId, start, end), + ]); + const projectName = new Map((projects?.data ?? []).map((item) => [item.id, item.name])); + const taskName = new Map((tasks?.data ?? []).map((item) => [item.id, item.name])); -async function searchIssues() { - const next = new Date(end); - const jql = - `project = ${project} AND updated >= "${localDate(start)}" ` + - `AND created < "${localDate(next)}" ORDER BY key ASC`; - const issues = []; - let token; - do { - const query = new URLSearchParams({ jql, fields: ISSUE_FIELDS, expand: 'changelog', maxResults: '50' }); - if (token) query.set('nextPageToken', token); - const page = await jira(`/rest/api/3/search/jql?${query}`); - issues.push(...(page.issues ?? [])); - token = page.nextPageToken; - } while (token); - return issues; + const ranch = []; + const other = new Map(); + for (const entry of raw) { + const from = new Date(entry.start); + if (!inMonth(from)) continue; + const running = !entry.end; + const to = running ? now : new Date(entry.end); + const seconds = Math.max(0, Math.round((to - from) / 1000)); + const project = projectName.get(entry.project_id) ?? null; + const label = [taskName.get(entry.task_id), entry.description].filter(Boolean).join(' '); + const key = label.match(keyPattern())?.[0] ?? null; + if (key || /ranch/i.test(project ?? '')) { + ranch.push({ from, to, seconds, running, key: key ?? NO_TASK, description: entry.description ?? '', project }); + } else { + const group = project ?? 'no project'; + const sum = other.get(group) ?? { entries: 0, seconds: 0 }; + other.set(group, { entries: sum.entries + 1, seconds: sum.seconds + seconds }); + } + } + ranch.sort((a, b) => a.from - b.from); + return { ranch, other }; } -function issueEvents(issue, accountId) { - const events = []; - const fields = issue.fields; - const created = new Date(fields.created); - if (fields.creator?.accountId === accountId && inMonth(created)) { - events.push({ date: created, kind: 'created', text: 'created' }); - } - for (const history of issue.changelog?.histories ?? []) { - const date = new Date(history.created); - if (history.author?.accountId !== accountId || !inMonth(date)) continue; - for (const item of history.items) { - if (item.field === 'status') events.push({ date, kind: 'status', text: `${item.fromString} → ${item.toString}` }); +async function readTasks(userId) { + const base = plane.project; + const [all, states, members] = await Promise.all([ + plane.list(`${base}/issues/`), + plane.list(`${base}/states/`), + plane.list(`${base}/members/`), + ]); + const stateName = new Map(states.map((state) => [state.id, state.name])); + const memberName = new Map(members.map((member) => [member.id, member.display_name])); + const keyOf = (issue) => `${TASK_PREFIX}-${issue.sequence_id}`; + const keyById = new Map(all.map((issue) => [issue.id, keyOf(issue)])); + + const tasks = new Map(); + for (const issue of all) { + const created = new Date(issue.created_at); + const touched = new Date(issue.updated_at) >= start && created < end; + const events = []; + if (touched) { + const [activities, comments] = await Promise.all([ + plane.list(`${base}/issues/${issue.id}/activities/`), + plane.list(`${base}/issues/${issue.id}/comments/`), + ]); + for (const activity of activities) { + const date = new Date(activity.created_at); + if (activity.actor !== userId || !inMonth(date)) continue; + if (activity.verb === 'created' && !activity.field) events.push({ date, kind: 'created', text: 'created' }); + if (activity.field === 'state') { + events.push({ date, kind: 'status', text: `${activity.old_value} → ${activity.new_value}` }); + } + } + for (const comment of comments) { + const date = new Date(comment.created_at); + if ((comment.actor ?? comment.created_by) === userId && inMonth(date)) { + events.push({ date, kind: 'comment', text: 'comment' }); + } + } } + tasks.set(keyOf(issue), { + key: keyOf(issue), + summary: issue.name, + status: stateName.get(issue.state) ?? null, + assignee: (issue.assignees ?? []).map((id) => memberName.get(id) ?? 'someone').join(', ') || null, + mine: (issue.assignees ?? []).includes(userId), + parent: issue.parent ? (keyById.get(issue.parent) ?? null) : null, + touched, + events: events.sort((a, b) => a.date - b.date), + }); } - for (const comment of fields.comment?.comments ?? []) { - const date = new Date(comment.created); - if (comment.author?.accountId === accountId && inMonth(date)) events.push({ date, kind: 'comment', text: 'comment' }); - } - return events.sort((a, b) => a.date - b.date); + return tasks; } const identity = await resolveIdentity(); -const accountId = identity.user.accountId; const repos = reposToScan(); const commits = ownCommits(repos.flatMap(readCommits), identity.email); -const keyPattern = new RegExp(`\\b${project}-\\d+\\b`, 'g'); -for (const commit of commits) commit.keys = [...new Set(commit.subject.match(keyPattern) ?? [])]; +for (const commit of commits) commit.keys = [...new Set(commit.subject.match(keyPattern()) ?? [])]; -const found = new Map((await searchIssues()).map((issue) => [issue.key, issue])); -const missing = []; -for (const key of new Set(commits.flatMap((commit) => commit.keys))) { - if (found.has(key)) continue; - const issue = await jira(`/rest/api/3/issue/${key}?fields=${ISSUE_FIELDS}&expand=changelog`, { allowMissing: true }); - if (issue) found.set(key, issue); - else missing.push(key); -} +const { ranch: entries, other: otherEntries } = await readEntries(identity.memberId); +const planeTasks = await readTasks(identity.planeUserId); -const committedKeys = new Set(commits.flatMap((commit) => commit.keys)); -const issues = []; -for (const issue of found.values()) { - const events = issueEvents(issue, accountId); - const mine = issue.fields.assignee?.accountId === accountId; - if (!mine && events.length === 0 && !committedKeys.has(issue.key)) continue; - issues.push({ - key: issue.key, - summary: issue.fields.summary, - status: issue.fields.status?.name ?? null, - assignee: issue.fields.assignee?.displayName ?? null, - mine, - parent: issue.fields.parent?.key ?? null, - events, - }); -} -issues.sort((a, b) => Number(a.key.split('-')[1]) - Number(b.key.split('-')[1])); +const namedKeys = new Set([...commits.flatMap((commit) => commit.keys), ...entries.map((entry) => entry.key)]); +namedKeys.delete(NO_TASK); +const missing = [...namedKeys].filter((key) => !isLegacy(key) && !planeTasks.has(key)); +const issues = [...planeTasks.values()] + .filter((task) => namedKeys.has(task.key) || task.events.length > 0 || (task.mine && task.touched)) + .sort((a, b) => Number(a.key.split('-')[1]) - Number(b.key.split('-')[1])); -// One bucket per local day, holding what happened on each ticket that day. +// One bucket per local day, holding what happened on each task that day. const days = new Map(); // An evening that runs past midnight is still that evening's working day, so anything @@ -220,26 +237,48 @@ function workday(date) { } function place(date, key) { - const { day, time } = workday(date); - if (!days.has(day)) days.set(day, new Map()); - const tickets = days.get(day); - if (!tickets.has(key)) tickets.set(key, { jira: [], git: [] }); - return { activity: tickets.get(key), time }; + const { day, time: at } = workday(date); + if (!days.has(day)) days.set(day, { tickets: new Map(), spans: [] }); + const tickets = days.get(day).tickets; + if (!tickets.has(key)) tickets.set(key, { seconds: 0, running: false, time: [], plane: [], git: [] }); + return { activity: tickets.get(key), at, day }; } +// An entry belongs to the working day it started on, whole, even when it ends after midnight. +for (const entry of entries) { + const { activity, at, day } = place(entry.from, entry.key); + const until = entry.running ? 'now, still running' : localTime(entry.to); + activity.seconds += entry.seconds; + activity.running ||= entry.running; + activity.time.push(`${at}–${until} ${clock(entry.seconds)}`); + days.get(day).spans.push([entry.from.getTime(), entry.to.getTime()]); +} for (const issue of issues) { for (const event of issue.events) { - const { activity, time } = place(event.date, issue.key); - activity.jira.push(`${time} ${event.text}`); + const { activity, at } = place(event.date, issue.key); + activity.plane.push(`${at} ${event.text}`); } } for (const commit of commits) { - for (const key of commit.keys.length ? commit.keys : ['(no ticket)']) { - const { activity, time } = place(commit.date, key); - activity.git.push(`${time} ${commit.repo}: ${commit.subject}`); + for (const key of commit.keys.length ? commit.keys : [NO_TASK]) { + const { activity, at } = place(commit.date, key); + activity.git.push(`${at} ${commit.repo}: ${commit.subject}`); } } +// Two entries running at once (two agents, or a timer left on) add up to more than the +// clock shows. Both numbers are reported; which one counts is the person's call. +function wallClock(spans) { + let seconds = 0; + let reach = -Infinity; + for (const [from, to] of [...spans].sort((a, b) => a[0] - b[0])) { + if (to <= reach) continue; + seconds += (to - Math.max(from, reach)) / 1000; + reach = to; + } + return Math.round(seconds); +} + const weekdaysWithoutActivity = []; const daysNotYetWorked = []; for (let date = new Date(start); date < end; date.setDate(date.getDate() + 1)) { @@ -251,26 +290,57 @@ for (let date = new Date(start); date < end; date.setDate(date.getDate() + 1)) { } const byKey = new Map(issues.map((issue) => [issue.key, issue])); +const reportDays = [...days.keys()].sort().map((day) => { + const { tickets, spans } = days.get(day); + const list = [...tickets].map(([key, activity]) => ({ + key, + seconds: activity.seconds, + hours: activity.seconds > 0 ? toHours(activity.seconds) : 0, + running: activity.running, + time: activity.time, + plane: activity.plane, + git: activity.git, + })); + return { + date: day, + day: DAY_NAMES[new Date(`${day}T12:00:00`).getDay()], + trackedSeconds: list.reduce((sum, ticket) => sum + ticket.seconds, 0), + wallClockSeconds: wallClock(spans), + tickets: list, + }; +}); + +const trackedTotal = reportDays.reduce((sum, day) => sum + day.trackedSeconds, 0); +const untrackedDays = reportDays.filter((day) => day.tickets.some((ticket) => ticket.seconds === 0)); +const overlapDays = reportDays.filter((day) => day.trackedSeconds - day.wallClockSeconds >= 60); +const running = entries.filter((entry) => entry.running); +const unnamed = entries.filter((entry) => entry.key === NO_TASK); + const report = { month, generatedAt: now.toISOString(), identity: { - source: identity.source, gitEmail: identity.gitEmail, - gitName: identity.gitName, email: identity.email, - jiraUser: identity.user.displayName, + person: identity.name, warning: identity.warning, }, - jiraBase: jiraBase(env), + taskBase: taskUrl(`${TASK_PREFIX}-0`).replace(/[^/]+\/$/, ''), + trackedSince: TRACKED_SINCE, repos: repos.map((repo) => basename(repo)), - issues, + issues: issues.map(({ touched, ...issue }) => issue), missingIssues: missing, - days: [...days.keys()].sort().map((day) => ({ - date: day, - day: DAY_NAMES[new Date(`${day}T12:00:00`).getDay()], - tickets: [...days.get(day)].map(([key, activity]) => ({ key, ...activity })), + entries: entries.map((entry) => ({ + key: entry.key, + start: entry.from.toISOString(), + end: entry.running ? null : entry.to.toISOString(), + seconds: entry.seconds, + description: entry.description, + project: entry.project, })), + otherEntries: [...otherEntries].map(([group, sum]) => ({ group, ...sum })), + trackedSeconds: trackedTotal, + days: reportDays, weekdaysWithoutActivity, daysNotYetWorked, }; @@ -279,33 +349,54 @@ const out = typeof args.out === 'string' ? resolve(args.out) : join(tmpdir(), `t writeFileSync(out, JSON.stringify(report, null, 1), 'utf8'); const list = (values) => (values.length ? values.join(', ') : 'none'); +const sumClock = (items) => clock(items.reduce((sum, item) => sum + item.seconds, 0)); const header = [ identity.warning ? `WARNING identity: ${identity.warning}` - : `identity: git user.email ${identity.gitEmail} -> Jira "${identity.user.displayName}" (verified)`, + : `identity: git user.email ${identity.gitEmail} -> solidtime and Plane "${identity.name}" (verified)`, '', - `month ${month} · repos ${report.repos.join(', ')} · ${issues.length} tickets · ${commits.length} commits`, + `month ${month} · repos ${report.repos.join(', ')} · ${issues.length} tasks · ${commits.length} commits · ` + + `${entries.length} time entries · tracked ${clock(trackedTotal)}`, `today ${localDate(now)} ${localTime(now)}`, - `tickets named in commits but absent in Jira: ${list(missing)}`, +]; +if (localDate(start) < TRACKED_SINCE) { + header.push( + TRACKED_SINCE < localDate(end) + ? `solidtime holds hours from ${TRACKED_SINCE}: the days of this month before it have none here` + : `solidtime holds hours from ${TRACKED_SINCE}: this month has none here, it was reported from Jira`, + ); +} +header.push( + `entries still running, counted up to now: ${list(running.map((entry) => `${entry.key} since ${workday(entry.from).time}`))}`, + `ranch entries that name no task: ${unnamed.length ? `${unnamed.length}, ${sumClock(unnamed)}` : 'none'}`, + `other entries of the month, not in this table: ${list([...otherEntries].map(([group, sum]) => `${group} ${sum.entries} × ${clock(sum.seconds)}`))}`, + `tasks named in commits or entries but absent in Plane: ${list(missing)}`, + `days with work that has no time tracked: ${list(untrackedDays.map((day) => day.date))}`, + `days where entries overlap: ${list(overlapDays.map((day) => `${day.date} (tracked ${clock(day.trackedSeconds)} in ${clock(day.wallClockSeconds)})`))}`, `weekdays without any activity: ${list(weekdaysWithoutActivity)}`, `weekdays still ahead, leave them out: ${list(daysNotYetWorked)}`, -]; +); const digest = [...header]; for (const day of report.days) { - digest.push('', `${day.date} ${day.day}`); + digest.push('', `${day.date} ${day.day} · tracked ${clock(day.trackedSeconds)}`); for (const ticket of day.tickets) { const issue = byKey.get(ticket.key); + const unknown = isLegacy(ticket.key) ? 'Jira id, not looked up' : ticket.key === NO_TASK ? '' : 'absent in Plane'; const notes = issue ? [ `[${issue.status}]`, issue.parent ? `subtask of ${issue.parent}` : '', issue.mine ? '' : `assignee: ${issue.assignee ?? 'nobody'}`, - ].filter(Boolean) - : []; - digest.push(` ${ticket.key}${issue ? ` ${issue.summary.slice(0, 100)} ${notes.join(' · ')}` : ''}`); - if (ticket.jira.length) digest.push(` jira ${ticket.jira.join('; ')}`); - for (const line of ticket.git) digest.push(` git ${line}`); + ] + : [unknown]; + const tracked = ticket.seconds + ? `tracked ${clock(ticket.seconds)} -> ${ticket.hours}${ticket.running ? ' (running)' : ''}` + : 'no time tracked'; + digest.push(` ${[ticket.key, issue?.summary.slice(0, 100), ...notes, tracked].filter(Boolean).join(' · ')}`); + if (ticket.time.length) digest.push(` time ${ticket.time.join('; ')}`); + if (ticket.plane.length) digest.push(` plane ${ticket.plane.join('; ')}`); + for (const line of ticket.git) digest.push(` git ${line}`); } } diff --git a/.claude/skills/timesheet/scripts/env.mjs b/.claude/skills/timesheet/scripts/env.mjs index 47873c9b7..b54b7cf6d 100644 --- a/.claude/skills/timesheet/scripts/env.mjs +++ b/.claude/skills/timesheet/scripts/env.mjs @@ -1,4 +1,4 @@ -// Shared plumbing for the timesheet scripts: git calls, `.env.project`, Jira requests. +// Shared plumbing for the timesheet scripts: git calls, `.env.project`, Plane and solidtime requests. import { execFileSync } from 'node:child_process'; import { existsSync, readFileSync } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; @@ -9,6 +9,25 @@ process.on('uncaughtException', (error) => { process.exit(1); }); +// Where the tasks and the hours live. The same values as the project card, `.cursor/rules/project.mdc`. +export const TASKS_SITE = 'https://tasks.dreamvention.com'; +export const TASKS_WORKSPACE = 'dreamvention'; +export const TASKS_PROJECT_ID = '1bb00764-cb1b-4293-a28c-3a9c2fd4b8f8'; +export const TIME_SITE = 'https://time.dreamvention.com'; +export const TIME_ORGANIZATION_ID = '56b70c8c-e381-43da-a80a-6f8e045271dd'; + +// Task ids look like RANCH-12. CLEAN- is the Jira project RANCH replaced: such an id can +// still name work in a commit or a time entry, but nothing is looked up for it any more. +export const TASK_PREFIX = 'RANCH'; +export const LEGACY_PREFIX = 'CLEAN'; + +// The first day solidtime holds hours for this repo. Before it, hours were estimated from +// Jira, which these scripts no longer read. +export const TRACKED_SINCE = '2026-11-30'; + +export const taskUrl = (key) => + key.startsWith(`${TASK_PREFIX}-`) ? `${TASKS_SITE}/${TASKS_WORKSPACE}/browse/${key}/` : ''; + export function git(cwd, args) { return execFileSync('git', args, { cwd, @@ -38,46 +57,87 @@ export function loadEnv(root) { const common = tryGit(root, ['rev-parse', '--git-common-dir']); if (common) candidates.push(join(dirname(resolve(root, common)), '.env.project')); const file = candidates.find((path) => existsSync(path)); - if (!file) throw new Error('.env.project not found. It holds JIRA_DOMAIN, JIRA_EMAIL and JIRA_API_TOKEN.'); + if (!file) throw new Error('.env.project not found. It holds TASKS_API_KEY and TIME_API_KEY.'); const env = {}; for (const line of readFileSync(file, 'utf8').split(/\r?\n/)) { const match = line.match(/^([A-Z0-9_]+)=(.*)$/); - if (match) env[match[1]] = match[2].trim(); + if (match) env[match[1]] = match[2].trim().replace(/^(["'])(.*)\1$/, '$2'); } - for (const key of ['JIRA_DOMAIN', 'JIRA_EMAIL', 'JIRA_API_TOKEN']) { - if (!env[key]) throw new Error(`${key} is missing in .env.project. Add it there.`); + for (const key of ['TASKS_API_KEY', 'TIME_API_KEY']) { + if (!env[key]) throw new Error(`${key} is missing in .env.project. It comes from Infisical: bun run env:pull.`); } return env; } -export function jiraBase(env) { - const domain = env.JIRA_DOMAIN.replace(/\/+$/, ''); - return /^https?:\/\//.test(domain) ? domain : `https://${domain}`; -} - -export function jiraClient(env) { - const base = jiraBase(env); - const headers = { - Authorization: 'Basic ' + Buffer.from(`${env.JIRA_EMAIL}:${env.JIRA_API_TOKEN}`).toString('base64'), - Accept: 'application/json', - }; - return async function jira(path, { allowMissing = false } = {}) { - const response = await fetch(base + path, { headers }); +function client(name, base, headers) { + return async function request(path, { allowMissing = false } = {}) { + const response = await fetch(base + path, { headers: { Accept: 'application/json', ...headers } }); if (allowMissing && (response.status === 404 || response.status === 403)) return null; if (!response.ok) { const body = (await response.text()).slice(0, 300); - throw new Error(`Jira ${response.status} on ${path.split('?')[0]}: ${body}`); + throw new Error(`${name} ${response.status} on ${path.split('?')[0]}: ${body}`); } return response.json(); }; } +// Plane. Lists come back in pages: `results` plus a cursor for the next one. +export function planeClient(env) { + const plane = client('Plane', `${TASKS_SITE}/api/v1`, { 'X-API-Key': env.TASKS_API_KEY }); + plane.project = `/workspaces/${TASKS_WORKSPACE}/projects/${TASKS_PROJECT_ID}`; + plane.list = async (path) => { + const items = []; + let cursor; + do { + const query = new URLSearchParams({ per_page: '100' }); + if (cursor) query.set('cursor', cursor); + const page = await plane(`${path}?${query}`); + if (Array.isArray(page)) return page; + items.push(...(page.results ?? [])); + cursor = page.next_page_results ? page.next_cursor : null; + } while (cursor); + return items; + }; + return plane; +} + +// solidtime. An employee's key reads only its owner's entries, and only when it names them. +export function timeClient(env) { + const time = client('solidtime', `${TIME_SITE}/api/v1`, { Authorization: `Bearer ${env.TIME_API_KEY}` }); + time.organization = `/organizations/${TIME_ORGANIZATION_ID}`; + time.entries = async (memberId, from, to) => { + const limit = 500; + const stamp = (date) => date.toISOString().replace(/\.\d+Z$/, 'Z'); + const entries = []; + for (;;) { + const query = new URLSearchParams({ + member_id: memberId, + start: stamp(from), + end: stamp(to), + limit: String(limit), + offset: String(entries.length), + }); + const page = await time(`${time.organization}/time-entries?${query}`); + entries.push(...(page.data ?? [])); + if (!page.data?.length || entries.length >= (page.meta?.total ?? 0)) return entries; + } + }; + return time; +} + const pad = (n) => String(n).padStart(2, '0'); export const localDate = (date) => `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`; export const localTime = (date) => `${pad(date.getHours())}:${pad(date.getMinutes())}`; +// 835 seconds -> "0:13". Seconds are dropped, not rounded up: a minute not finished is not a minute. +export const clock = (seconds) => `${Math.floor(seconds / 3600)}:${pad(Math.floor((seconds % 3600) / 60))}`; + +// The table counts in quarter hours. Anything tracked at all is at least one quarter. +export const QUARTER = 0.25; +export const toHours = (seconds) => Math.max(QUARTER, Math.round(seconds / 900) * QUARTER); + export const DAY_NAMES = ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб']; // "2026-09" -> local-time bounds of the month and its name for file names.