From e4ffd5d93d0b20821795968894a4f82c7f05be0f Mon Sep 17 00:00:00 2001 From: naps62 Date: Fri, 14 Aug 2026 17:35:21 +0000 Subject: [PATCH 01/12] feat: hourlog skill + Friday timer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Turns Claude Code and Codex session activity into a half-day-per-project proposal, reconciles it against the timesheet API, and submits only what the user approves in-session. Activity is measured in 5-minute active slots, deduplicated per project, not message counts — otherwise one overnight autonomous run outweighs a real morning's work. The path-to-project mapping and the API credentials stay in ~/.config/hourlog/ and ~/.env.claude. This repo is public. Co-Authored-By: Claude Opus 5 --- .gitignore | 1 + README.md | 29 +++ bin/hourlog-session.sh | 62 +++++++ bin/link.sh | 5 +- skills/hourlog/SKILL.md | 122 ++++++++++++ skills/hourlog/config.example.json | 28 +++ skills/hourlog/scripts/me-api.py | 139 ++++++++++++++ skills/hourlog/scripts/scan-activity.py | 234 ++++++++++++++++++++++++ systemd/hourlog.service | 12 ++ systemd/hourlog.timer | 11 ++ 10 files changed, 641 insertions(+), 2 deletions(-) create mode 100755 bin/hourlog-session.sh create mode 100644 skills/hourlog/SKILL.md create mode 100644 skills/hourlog/config.example.json create mode 100755 skills/hourlog/scripts/me-api.py create mode 100755 skills/hourlog/scripts/scan-activity.py create mode 100644 systemd/hourlog.service create mode 100644 systemd/hourlog.timer diff --git a/.gitignore b/.gitignore index fb2e8c7..6be0230 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ *.bak .DS_Store +__pycache__/ diff --git a/README.md b/README.md index da1575d..f072050 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,34 @@ systemctl --user list-timers week-review.timer Needs `loginctl enable-linger` so the timer runs while logged out. Logs are in `~/.local/state/week-review/run.log`. The nix module deliberately omits the timer for the same one-machine reason. +## Hour log timer + +`systemd/hourlog.timer` fires Fridays at 16:00 Europe/Lisbon and runs +`bin/hourlog-session.sh`, which opens an Agent of Empires session on a scratch +dir, sends it `/hourlog --week this`, and pushes an ntfy notification. + +Same shape as the weekly review and interactive for the same reason: the skill +proposes hours and stops for approval before writing anything to the timesheet. +An unattended run would be deciding a company record on your behalf. It skips +if a previous `hourlog-*` session is still open, and `Persistent=true` makes a +missed Friday fire on the next boot. + +Enable on one machine only: + +```sh +systemctl --user daemon-reload +systemctl --user enable --now hourlog.timer +``` + +Setup lives outside this repo, which is public: + +- `~/.config/hourlog/projects.json` — path prefix to project mapping, copied + from `skills/hourlog/config.example.json`. +- `HOURLOG_API` and `HOURLOG_TOKEN` in `~/.env.claude` — API base URL and a + personal access token (`profile:read`, `schedule:read`, `schedule:write`). + +No project, client, or host name belongs in a committed file here. + ## Adding a skill Drop a new `skills//SKILL.md` (+ optional `scripts/`, `references/`, `assets/`). Commit. Non-Nix: re-run `bin/link.sh`. Nix: rebuild. @@ -85,6 +113,7 @@ Drop a new `skills//SKILL.md` (+ optional `scripts/`, `references/`, `asse | `nightshift` | hours-long unattended build; architect delegating to subagents, backs off before the 5h limit | | `linear-common` | shared config/setup/worktree conventions + local verification budget (dependency of work/yolo/blitz/nightshift) | | `week-review` | review the past week's sessions for recurring friction; reads open issues here as carry-over | +| `hourlog` | half-day-per-project proposal from session activity, reconciled against the timesheet; submits only what you approve | | `crit`, `improve-codebase-architecture` | misc | ## Vendored skills diff --git a/bin/hourlog-session.sh b/bin/hourlog-session.sh new file mode 100755 index 0000000..44a758e --- /dev/null +++ b/bin/hourlog-session.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# Friday hour-logging session: create it in Agent of Empires, prompt it with +# /hourlog, ping the phone. Interactive, not `-p`: the run stops for approval +# before writing to the timesheet. See README "Hour log timer". +set -euo pipefail + +PROMPT="${HOURLOG_PROMPT:-/hourlog --week this}" +TOPIC="${HOURLOG_NTFY_TOPIC:-homelab}" +AOE="${HOURLOG_AOE:-$HOME/.local/bin/aoe}" +LOG="$HOME/.local/state/hourlog/run.log" + +WEEK="$(date +%G-W%V)" +TITLE="hourlog-$WEEK" + +mkdir -p "$(dirname "$LOG")" +exec >>"$LOG" 2>&1 +echo "=== $(date -Is) starting $TITLE ===" + +# NTFY_URL/NTFY_TOKEN and HOURLOG_API/HOURLOG_TOKEN live here; ~/.zshrc only +# sources it for interactive shells. +# shellcheck disable=SC1091 +[ -f "$HOME/.env.claude" ] && . "$HOME/.env.claude" + +notify() { # notify <priority> <message> + [ -n "${NTFY_URL:-}" ] || { echo "no NTFY_URL, skipping notify"; return 0; } + curl -sS -m 10 -o /dev/null \ + -H "Authorization: Bearer ${NTFY_TOKEN:-}" \ + -H "Title: $1" -H "Priority: $2" -H "Tags: hourglass_flowing_sand" \ + -d "$3" "$NTFY_URL/$TOPIC" || echo "notify failed" +} + +if [ -z "${HOURLOG_TOKEN:-}" ] || [ -z "${HOURLOG_API:-}" ]; then + echo "HOURLOG_API/HOURLOG_TOKEN missing from ~/.env.claude" + notify "Hour log not configured" high \ + "HOURLOG_API/HOURLOG_TOKEN missing — the session would stall at setup." + exit 1 +fi + +open="$("$AOE" list 2>/dev/null | awk '$1 ~ /^hourlog-/ { print $1 }' || true)" +if [ -n "$open" ]; then + echo "already open: $open — not starting a second one" + notify "Hour log skipped" default \ + "An earlier hour log is still open ($open). Finish or remove it." + exit 0 +fi + +# --scratch keeps the session's cwd under the agent-of-empires app dir, which +# the hourlog config excludes — otherwise it lands in next week's scan. +"$AOE" add --scratch --title "$TITLE" --cmd claude --yolo --trust-hooks +"$AOE" session start "$TITLE" + +# The agent needs its TUI up before it can take a prompt; `send` into a +# still-booting pane is dropped silently. +sleep 25 +if "$AOE" send "$TITLE" "$PROMPT"; then + echo "session $TITLE launched and prompted" + notify "Hour log ready" default "aoe: $TITLE — proposal waiting on your OK" +else + echo "failed to send prompt to $TITLE" + notify "Hour log failed to start" high "session $TITLE — see $LOG" + exit 1 +fi diff --git a/bin/link.sh b/bin/link.sh index 3a81b3b..c421102 100755 --- a/bin/link.sh +++ b/bin/link.sh @@ -83,5 +83,6 @@ fi echo "done." echo "hooks still need wiring in ~/.claude/settings.json — see hooks/README.md" -echo "weekly review timer (one machine only):" -echo " systemctl --user daemon-reload && systemctl --user enable --now week-review.timer" +echo "timers (one machine only):" +echo " systemctl --user daemon-reload" +echo " systemctl --user enable --now week-review.timer hourlog.timer" diff --git a/skills/hourlog/SKILL.md b/skills/hourlog/SKILL.md new file mode 100644 index 0000000..36fcc84 --- /dev/null +++ b/skills/hourlog/SKILL.md @@ -0,0 +1,122 @@ +--- +name: hourlog +description: Work out which client project each morning and afternoon went to, by reading Claude Code and Codex session activity, then reconcile that against the company timesheet and confirm the week's hours. Use when the user asks to log hours, fill in their timesheet, check what they worked on last week, or runs the Friday hour-logging session. +user-invocable: true +argument-hint: "[--week last|this | --since YYYY-MM-DD [--until YYYY-MM-DD]]" +allowed-tools: + - Read + - Grep + - Glob + - Bash + - Edit + - Write +--- + +# Hour log + +Turn session activity into a half-day-per-project proposal, check it against +the timesheet, and submit only what the user approves. + +The timesheet is a company record. Nothing is written to it without the user +saying go, in this session, after seeing the table. An unattended run stops at +the proposal. + +## Setup (once per machine) + +Three things must exist. Check them before anything else and stop with the +missing step if not. + +1. `~/.config/hourlog/projects.json` — path prefix to project mapping. Copy + `<skill-dir>/config.example.json` and fill it in. **Never commit a filled + config, and never put a project, client, or host name in this repo** — it + is public. +2. `HOURLOG_API` and `HOURLOG_TOKEN` in `~/.env.claude`. The token is a + personal access token from the timesheet app's profile page. Scopes: + `profile:read`, `schedule:read`, and `schedule:write` only if submitting. + Never echo the token. +3. Project names in the config must match the app exactly. Verify with + `me-api.py projects` and fix the config, not the app. + +## 1. Scan the sessions + +```sh +python3 <skill-dir>/scripts/scan-activity.py --week last +``` + +Reports, per half-day, how many minutes each project was active and over which +hours. The unit is a 5-minute slot in which at least one message was written, +deduplicated per project — so a 40-subagent swarm on one project counts once, +and two projects worked in parallel each keep their own slots. Message counts +would let one overnight autonomous run outweigh a real morning. + +Two things in the output need judgement, not arithmetic: + +- **`[outside HHh]` flags.** Activity at 02:00 is usually an unattended run, + not work. Discount it unless the user says otherwise. +- **`unmapped:` lines.** A path with no rule. Either it is a new client + directory the config is missing — say so and ask — or it is personal work + that belongs in `exclude`. Never guess it into a client project. + +## 2. Propose the hours + +Half-days, not minutes. The user's own framing: a morning on one project is +just four hours on that project. + +- One project at 70% or more of the half-day's active minutes: all 4h to it. +- Otherwise split 4h between the top two, in 15-minute steps, rounded to + whatever matches the share. +- Under 30 minutes of activity in a half-day: propose nothing and say the day + looks empty. Do not invent a full day from a single message. + +Session activity is evidence of what was worked on, not proof of hours. Meetings, +review, and thinking leave no transcript. Say this when the proposal is thin, +and let the user correct upward. + +## 3. Reconcile against the timesheet + +```sh +python3 <skill-dir>/scripts/me-api.py schedule --start YYYY-MM-DD --end YYYY-MM-DD +``` + +Each day comes back either already planned (an allocation with an entry id and +planned hours) or absent. That splits the proposal in two: + +- **Planned and matching** — confirm at the planned hours. +- **Planned but the sessions disagree** — confirm at the observed hours, and + show both numbers in the table so the user sees what changed. +- **Not planned at all** — needs a new entry, which is a bigger claim. Flag it + separately rather than folding it in. + +## 4. Show the table, then ask + +One row per half-day: date, weekday, half, project, proposed hours, what the +timesheet currently says, and the action (confirm / adjust / add / skip). +Flag every row where the evidence was weak or outside working hours. + +Then ask once, plainly, whether to submit. Wait for an answer. Silence, a +timeout, or "user may be away" is not approval — leave the timesheet alone and +say the run is waiting. + +## 5. Submit what was approved + +```sh +# confirm a planned day +python3 <skill-dir>/scripts/me-api.py confirm --entry ID --hours 4 --dry-run +# log a day with no allocation +python3 <skill-dir>/scripts/me-api.py log --project ID --dates D,D --hours 4 --dry-run +``` + +Run every write with `--dry-run` first and show the requests. Drop the flag +only for the rows the user approved — not the whole table, if they approved +part of it. + +A `423` means the period is locked and ops has to reopen it. Report it and +move on; it is not a failure to retry. + +Re-read the schedule afterwards and confirm what landed. Report the diff, not +an assumption. + +## Scope + +Which project a half-day went to, and confirming hours already worked. Not +future allocations, not time off, not anyone else's schedule. diff --git a/skills/hourlog/config.example.json b/skills/hourlog/config.example.json new file mode 100644 index 0000000..971659d --- /dev/null +++ b/skills/hourlog/config.example.json @@ -0,0 +1,28 @@ +{ + "_comment": [ + "Copy to ~/.config/hourlog/projects.json and fill in real values there.", + "This repo is public: no client names, no project names, no hostnames.", + "'name' must match the project name in the timesheet app exactly — check", + "it with `scripts/me-api.py projects`. 'match' is a list of path prefixes;", + "the longest matching prefix wins, so a worktree can override its parent." + ], + "timezone": "Europe/Lisbon", + "afternoon_start_hour": 13, + "slot_minutes": 5, + "day_start_hour": 8, + "day_end_hour": 20, + "projects": [ + { + "name": "<project name exactly as the timesheet app shows it>", + "match": ["~/<client-dir>", "~/<client-dir>-worktrees"] + }, + { + "name": "<another project>", + "match": ["~/<org>/<repo>", "~/<org>/<repo>-worktrees"] + } + ], + "exclude": [ + "~/<personal-code-root>", + "~/.config/agent-of-empires" + ] +} diff --git a/skills/hourlog/scripts/me-api.py b/skills/hourlog/scripts/me-api.py new file mode 100755 index 0000000..9a811af --- /dev/null +++ b/skills/hourlog/scripts/me-api.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""Thin client for the company timesheet REST API. + +Auth is a personal access token in $HOURLOG_TOKEN (scopes: profile:read, +schedule:read, and schedule:write only if you intend to submit). The base URL +is $HOURLOG_API. Both live in ~/.env.claude — never pass a token on argv, it +lands in shell history and in the process table. + +Commands: + whoami GET /auth/me + projects GET /my/projects + categories GET /investment-categories + schedule --start D --end D GET /my-schedule + overdue GET /my-schedule/overdue + confirm --entry ID --hours H PUT /day-entries/ID + log --project ID --dates D,D --hours H POST /my/day-entries + log --category ID --dates D,D --hours H POST /my/day-entries + raw METHOD PATH [JSON] escape hatch + +Every write takes --dry-run, which prints the exact request and sends nothing. +""" +import argparse +import json +import os +import sys +import urllib.error +import urllib.parse +import urllib.request + +def request(method, path, body=None, dry=False): + api = os.environ.get("HOURLOG_API") + if not api: + sys.exit("HOURLOG_API is not set — add the API base URL to " + "~/.env.claude (it ends in /api)") + url = api.rstrip("/") + path + payload = json.dumps(body).encode() if body is not None else None + if dry: + print(f"DRY RUN {method} {url}") + if body is not None: + print(json.dumps(body, indent=1)) + return None + + token = os.environ.get("HOURLOG_TOKEN") + if not token: + sys.exit("HOURLOG_TOKEN is not set — add it to ~/.env.claude " + "(create one under profile > personal access tokens)") + req = urllib.request.Request(url, data=payload, method=method, headers={ + "Content-Type": "application/json", + "Authorization": f"Bearer {token}", + }) + try: + with urllib.request.urlopen(req, timeout=30) as r: + raw = r.read() + return json.loads(raw) if raw else None + except urllib.error.HTTPError as e: + detail = e.read().decode(errors="replace")[:400] + if e.code == 401: + sys.exit("401 — token missing, expired, or lacking the scope") + if e.code == 423: + sys.exit("423 — that period is locked; ops has to reopen it") + sys.exit(f"{e.code} {method} {path}: {detail}") + except urllib.error.URLError as e: + sys.exit(f"cannot reach the API: {e.reason}") + + +def show(obj): + json.dump(obj, sys.stdout, indent=1) + print() + + +def main(): + ap = argparse.ArgumentParser() + sub = ap.add_subparsers(dest="cmd", required=True) + sub.add_parser("whoami") + sub.add_parser("projects") + sub.add_parser("categories") + sub.add_parser("overdue") + + s = sub.add_parser("schedule") + s.add_argument("--start", required=True) + s.add_argument("--end", required=True) + + c = sub.add_parser("confirm") + c.add_argument("--entry", required=True, help="day entry id") + c.add_argument("--hours", required=True, help="decimal hours, e.g. 4 or 7.5") + c.add_argument("--dry-run", action="store_true") + + l = sub.add_parser("log") + g = l.add_mutually_exclusive_group(required=True) + g.add_argument("--project", help="project id") + g.add_argument("--category", help="investment category id") + l.add_argument("--dates", required=True, help="comma-separated YYYY-MM-DD") + l.add_argument("--hours", required=True, help="decimal hours per day") + l.add_argument("--dry-run", action="store_true") + + r = sub.add_parser("raw") + r.add_argument("method") + r.add_argument("path") + r.add_argument("body", nargs="?") + r.add_argument("--dry-run", action="store_true") + + a = ap.parse_args() + + if a.cmd == "whoami": + show(request("GET", "/auth/me")) + elif a.cmd == "projects": + show(request("GET", "/my/projects")) + elif a.cmd == "categories": + show(request("GET", "/investment-categories")) + elif a.cmd == "overdue": + show(request("GET", "/my-schedule/overdue")) + elif a.cmd == "schedule": + q = urllib.parse.urlencode({"start_date": a.start, "end_date": a.end}) + show(request("GET", f"/my-schedule?{q}")) + elif a.cmd == "confirm": + body = {"day_entry": {"actual_hours": a.hours}} + out = request("PUT", f"/day-entries/{a.entry}", body, a.dry_run) + if out is not None: + show(out) + elif a.cmd == "log": + entry = {"dates": [d.strip() for d in a.dates.split(",") if d.strip()], + "hours": a.hours} + if a.project: + entry["project_id"] = a.project + else: + entry["investment_category_id"] = a.category + out = request("POST", "/my/day-entries", {"day_entry": entry}, a.dry_run) + if out is not None: + show(out) + elif a.cmd == "raw": + body = json.loads(a.body) if a.body else None + out = request(a.method.upper(), a.path, body, a.dry_run) + if out is not None: + show(out) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/skills/hourlog/scripts/scan-activity.py b/skills/hourlog/scripts/scan-activity.py new file mode 100755 index 0000000..1528fff --- /dev/null +++ b/skills/hourlog/scripts/scan-activity.py @@ -0,0 +1,234 @@ +#!/usr/bin/env python3 +"""Bucket Claude Code and Codex session activity into half-days per project. + +Usage: scan-activity.py --since YYYY-MM-DD [--until YYYY-MM-DD] [--json] + scan-activity.py --week last|this + +Reads ~/.config/hourlog/projects.json for the path-prefix -> project mapping +(see config.example.json). The mapping is machine-local on purpose: this repo +is public and client names are not. + +The unit is an "active slot" — a 5-minute window in which at least one message +was written. Slots are a set per (day, half, project), so a swarm of 40 +subagent transcripts on one project counts once, and two projects worked in +parallel each keep their own slots. Message counts would make one overnight +autonomous run outweigh a real morning; wall-clock presence does not. +""" +import argparse +import collections +import datetime as dt +import glob +import json +import os +import sys +from zoneinfo import ZoneInfo + +CONFIG = os.path.expanduser("~/.config/hourlog/projects.json") +DEFAULTS = { + "timezone": "Europe/Lisbon", + "afternoon_start_hour": 13, + "slot_minutes": 5, + "day_start_hour": 8, + "day_end_hour": 20, + "projects": [], + "exclude": [], +} + + +def load_config(path): + cfg = dict(DEFAULTS) + if os.path.exists(path): + with open(path) as fh: + cfg.update(json.load(fh)) + else: + print(f"no config at {path} — every path will land in 'unmapped'", + file=sys.stderr) + # Longest prefix wins, so a worktree dir can override its parent. + rules = [] + for p in cfg["projects"]: + for m in p["match"]: + rules.append((os.path.expanduser(m).rstrip("/"), p["name"])) + for m in cfg["exclude"]: + rules.append((os.path.expanduser(m).rstrip("/"), None)) + cfg["_rules"] = sorted(rules, key=lambda r: -len(r[0])) + return cfg + + +def classify(cwd, rules): + """-> project name, or None if excluded, or 'unmapped:<top-2-dirs>'.""" + if not cwd: + return "unmapped:?" + for prefix, name in rules: + if cwd == prefix or cwd.startswith(prefix + "/"): + return name + short = cwd.replace(os.path.expanduser("~"), "~") + return "unmapped:" + "/".join(short.split("/")[:3]) + + +def claude_files(root, cutoff): + for f in glob.glob(os.path.join(root, "*", "*.jsonl")): + try: + if os.stat(f).st_mtime >= cutoff: + yield f + except OSError: + continue + + +def codex_files(root, cutoff): + for f in glob.glob(os.path.join(root, "*", "*", "*", "*.jsonl")): + try: + if os.stat(f).st_mtime >= cutoff: + yield f + except OSError: + continue + + +def read_session(path): + """-> (cwd, [timestamp strings]). Handles both Claude and Codex layouts.""" + cwd, stamps = None, [] + try: + fh = open(path, errors="replace") + except OSError: + return None, [] + with fh: + for line in fh: + try: + d = json.loads(line) + except ValueError: + continue + if cwd is None: + cwd = d.get("cwd") or (d.get("payload") or {}).get("cwd") + ts = d.get("timestamp") + if ts: + stamps.append(ts) + return cwd, stamps + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--since") + ap.add_argument("--until") + ap.add_argument("--week", choices=["last", "this"]) + ap.add_argument("--config", default=CONFIG) + ap.add_argument("--json", action="store_true") + a = ap.parse_args() + + cfg = load_config(a.config) + tz = ZoneInfo(cfg["timezone"]) + today = dt.datetime.now(tz).date() + + if a.week: + monday = today - dt.timedelta(days=today.weekday()) + if a.week == "last": + monday -= dt.timedelta(days=7) + since, until = monday, monday + dt.timedelta(days=6) + elif a.since: + since = dt.date.fromisoformat(a.since) + until = dt.date.fromisoformat(a.until) if a.until else today + else: + ap.error("need --since or --week") + + start = dt.datetime.combine(since, dt.time(0), tz) + end = dt.datetime.combine(until, dt.time(23, 59, 59), tz) + slot = cfg["slot_minutes"] * 60 + noon = cfg["afternoon_start_hour"] + + # (date, half) -> project -> set of slot indices + grid = collections.defaultdict(lambda: collections.defaultdict(set)) + hours = collections.defaultdict(lambda: collections.defaultdict(set)) + seen_cwds = collections.Counter() + + sources = [ + (os.path.expanduser("~/.claude/projects"), claude_files), + (os.path.expanduser("~/.codex/sessions"), codex_files), + ] + nfiles = 0 + for root, lister in sources: + if not os.path.isdir(root): + continue + for f in lister(root, start.timestamp()): + cwd, stamps = read_session(f) + proj = classify(cwd, cfg["_rules"]) + if proj is None: + continue + nfiles += 1 + seen_cwds[cwd or "?"] += 1 + for ts in stamps: + try: + t = dt.datetime.fromisoformat( + ts.replace("Z", "+00:00")).astimezone(tz) + except ValueError: + continue + if not (start <= t <= end): + continue + key = (t.date().isoformat(), "AM" if t.hour < noon else "PM") + grid[key][proj].add(int(t.timestamp()) // slot) + hours[key][proj].add(t.hour) + del stamps + + mins = cfg["slot_minutes"] + report = [] + d = since + while d <= until: + for half in ("AM", "PM"): + key = (d.isoformat(), half) + per = grid.get(key, {}) + total = sum(len(v) for v in per.values()) + entry = { + "date": d.isoformat(), + "weekday": d.strftime("%a"), + "half": half, + "total_active_minutes": total * mins, + "projects": [], + } + for proj, slots in sorted(per.items(), key=lambda kv: -len(kv[1])): + hs = sorted(hours[key][proj]) + entry["projects"].append({ + "project": proj, + "active_minutes": len(slots) * mins, + "share": round(len(slots) / total, 3) if total else 0, + "hours": hs, + "outside_workday": [ + h for h in hs + if h < cfg["day_start_hour"] or h >= cfg["day_end_hour"] + ], + }) + report.append(entry) + d += dt.timedelta(days=1) + + unmapped = sorted( + {p for e in report for p in + (x["project"] for x in e["projects"]) if p.startswith("unmapped:")}) + + if a.json: + json.dump({"since": since.isoformat(), "until": until.isoformat(), + "slot_minutes": mins, "sessions": nfiles, + "unmapped": unmapped, "report": report}, sys.stdout, indent=1) + print() + return 0 + + print(f"{since} .. {until} ({nfiles} sessions, {mins}-min slots, " + f"{cfg['timezone']})\n") + for e in report: + if not e["projects"]: + continue + print(f"{e['date']} {e['weekday']} {e['half']} " + f"{e['total_active_minutes']:>4}min active") + for p in e["projects"]: + flag = "" + if p["outside_workday"]: + flag = " [outside " + ",".join( + f"{h:02d}h" for h in p["outside_workday"]) + "]" + span = f"{p['hours'][0]:02d}-{p['hours'][-1]:02d}h" if p["hours"] else "" + print(f" {p['share']*100:5.1f}% {p['active_minutes']:>4}min " + f"{span:<8} {p['project']}{flag}") + print() + if unmapped: + print("unmapped paths — add them to the config or the exclude list:") + for u in unmapped: + print(" ", u) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/systemd/hourlog.service b/systemd/hourlog.service new file mode 100644 index 0000000..1519c01 --- /dev/null +++ b/systemd/hourlog.service @@ -0,0 +1,12 @@ +[Unit] +Description=Start the Friday hour log in a tmux session +Documentation=https://git.naps.pt/yolo/agent-skills +ConditionPathIsDirectory=%h/tea/yolo/agent-skills + +[Service] +Type=oneshot +Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin +ExecStart=%h/tea/yolo/agent-skills/bin/hourlog-session.sh +# When no tmux server is running yet this unit starts one; the default +# control-group kill would take it back down as soon as ExecStart returns. +KillMode=process diff --git a/systemd/hourlog.timer b/systemd/hourlog.timer new file mode 100644 index 0000000..07e468b --- /dev/null +++ b/systemd/hourlog.timer @@ -0,0 +1,11 @@ +[Unit] +Description=Friday hour log, 16:00 Europe/Lisbon + +[Timer] +# System clock is UTC; the zone suffix keeps this at 16:00 wall time year-round. +OnCalendar=Fri 16:00 Europe/Lisbon +Persistent=true +AccuracySec=1min + +[Install] +WantedBy=timers.target From 95e98a1e777194e89be5d79be265c67b52425e9b Mon Sep 17 00:00:00 2001 From: naps62 <naps62@users.noreply.github.com> Date: Fri, 14 Aug 2026 18:36:34 +0000 Subject: [PATCH 02/12] refactor: hourlog reports whole days, timer to 18:00 Half-days forced every result into a 4h bucket. Days with hours split by share give the same answer at finer granularity and drop a concept. Session minutes are now stated as a floor on real work, not a measure: the day's length comes from the calendar and only the split between projects comes from the sessions. Meetings and review leave no transcript, so a thin day is still a full day. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --- README.md | 6 +- skills/hourlog/SKILL.md | 57 ++++++---- skills/hourlog/config.example.json | 2 +- skills/hourlog/scripts/scan-activity.py | 138 +++++++++++++++--------- systemd/hourlog.timer | 6 +- 5 files changed, 130 insertions(+), 79 deletions(-) diff --git a/README.md b/README.md index f072050..f283401 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ commands/ # slash commands — Claude Code only (Codex ignores) hooks/ # Claude Code hooks — see hooks/README.md, wiring is manual claude-md/ # shared instruction fragments — imported by both entry files entry/ # entry files: ~/.claude/CLAUDE.md and ~/.codex/AGENTS.md -systemd/ # user timer that starts the weekly review — one machine only, see below +systemd/ # user timers: weekly review + hour log — one machine only, see below bin/link.sh # bootstrap symlinks for non-Nix machines nix/home.nix # home-manager module for NixOS machines flake.nix # exposes homeModules.default @@ -72,7 +72,7 @@ Needs `loginctl enable-linger` so the timer runs while logged out. Logs are in ` ## Hour log timer -`systemd/hourlog.timer` fires Fridays at 16:00 Europe/Lisbon and runs +`systemd/hourlog.timer` fires Fridays at 18:00 Europe/Lisbon and runs `bin/hourlog-session.sh`, which opens an Agent of Empires session on a scratch dir, sends it `/hourlog --week this`, and pushes an ntfy notification. @@ -113,7 +113,7 @@ Drop a new `skills/<name>/SKILL.md` (+ optional `scripts/`, `references/`, `asse | `nightshift` | hours-long unattended build; architect delegating to subagents, backs off before the 5h limit | | `linear-common` | shared config/setup/worktree conventions + local verification budget (dependency of work/yolo/blitz/nightshift) | | `week-review` | review the past week's sessions for recurring friction; reads open issues here as carry-over | -| `hourlog` | half-day-per-project proposal from session activity, reconciled against the timesheet; submits only what you approve | +| `hourlog` | hours-per-project-per-day proposal from session activity, reconciled against the timesheet; submits only what you approve | | `crit`, `improve-codebase-architecture` | misc | ## Vendored skills diff --git a/skills/hourlog/SKILL.md b/skills/hourlog/SKILL.md index 36fcc84..69a2ec7 100644 --- a/skills/hourlog/SKILL.md +++ b/skills/hourlog/SKILL.md @@ -1,6 +1,6 @@ --- name: hourlog -description: Work out which client project each morning and afternoon went to, by reading Claude Code and Codex session activity, then reconcile that against the company timesheet and confirm the week's hours. Use when the user asks to log hours, fill in their timesheet, check what they worked on last week, or runs the Friday hour-logging session. +description: Work out how many hours each client project got on each day, by reading Claude Code and Codex session activity, then reconcile that against the company timesheet and confirm the week's hours. Use when the user asks to log hours, fill in their timesheet, check what they worked on last week, or runs the Friday hour-logging session. user-invocable: true argument-hint: "[--week last|this | --since YYYY-MM-DD [--until YYYY-MM-DD]]" allowed-tools: @@ -14,7 +14,7 @@ allowed-tools: # Hour log -Turn session activity into a half-day-per-project proposal, check it against +Turn session activity into an hours-per-project-per-day proposal, check it against the timesheet, and submit only what the user approves. The timesheet is a company record. Nothing is written to it without the user @@ -43,34 +43,45 @@ missing step if not. python3 <skill-dir>/scripts/scan-activity.py --week last ``` -Reports, per half-day, how many minutes each project was active and over which -hours. The unit is a 5-minute slot in which at least one message was written, -deduplicated per project — so a 40-subagent swarm on one project counts once, -and two projects worked in parallel each keep their own slots. Message counts -would let one overnight autonomous run outweigh a real morning. +Reports one line per project per day: suggested hours, share of the day, active +minutes, and the hour range they fell in. The unit is a 5-minute slot in which +at least one message was written, deduplicated per project — so a 40-subagent +swarm on one project counts once, and two projects worked in parallel each keep +their own slots. Message counts would let one overnight autonomous run outweigh +a real morning. Two things in the output need judgement, not arithmetic: -- **`[outside HHh]` flags.** Activity at 02:00 is usually an unattended run, - not work. Discount it unless the user says otherwise. +- **`outside working hours` lines.** Activity at 02:00 is usually an unattended + run, not work. Discount it unless the user says otherwise. - **`unmapped:` lines.** A path with no rule. Either it is a new client directory the config is missing — say so and ask — or it is personal work that belongs in `exclude`. Never guess it into a client project. ## 2. Propose the hours -Half-days, not minutes. The user's own framing: a morning on one project is -just four hours on that project. +**Active minutes are a floor on real work, never a measure of it.** Meetings, +review, reading, whiteboarding, and thinking leave no transcript at all. A day +showing 160 active minutes was not a two-hour day. Read the numbers as +*proportions between projects*, and get the day's length from the calendar. -- One project at 70% or more of the half-day's active minutes: all 4h to it. -- Otherwise split 4h between the top two, in 15-minute steps, rounded to - whatever matches the share. -- Under 30 minutes of activity in a half-day: propose nothing and say the day - looks empty. Do not invent a full day from a single message. +The scan already does the arithmetic: it splits `nominal_day_hours` (config, +default 8) across the day's mapped projects by share, in 15-minute steps. Your +job is the judgement it cannot do: -Session activity is evidence of what was worked on, not proof of hours. Meetings, -review, and thinking leave no transcript. Say this when the proposal is thin, -and let the user correct upward. +- One project at 85% or more: round it up to the whole day rather than leaving + a token 1h on the other. +- Discount hours flagged `outside`. If most of a project's minutes came from + 21h-02h, its share is inflated by an unattended run — say so and shift the + split rather than passing the number through. +- Days marked `under 30min, treat as empty` get nothing proposed. +- An `unmapped:` line with real minutes means the split is wrong, not just + incomplete: those minutes were excluded from the division. Resolve the + mapping before proposing hours for that day. + +Never scale a day *down* because its transcripts are thin. A quiet day is a +normal working day unless the user says it was not, or the timesheet already +marks it as time off or a holiday. ## 3. Reconcile against the timesheet @@ -89,7 +100,7 @@ planned hours) or absent. That splits the proposal in two: ## 4. Show the table, then ask -One row per half-day: date, weekday, half, project, proposed hours, what the +One row per project per day: date, weekday, project, proposed hours, what the timesheet currently says, and the action (confirm / adjust / add / skip). Flag every row where the evidence was weak or outside working hours. @@ -101,9 +112,9 @@ say the run is waiting. ```sh # confirm a planned day -python3 <skill-dir>/scripts/me-api.py confirm --entry ID --hours 4 --dry-run +python3 <skill-dir>/scripts/me-api.py confirm --entry ID --hours 8 --dry-run # log a day with no allocation -python3 <skill-dir>/scripts/me-api.py log --project ID --dates D,D --hours 4 --dry-run +python3 <skill-dir>/scripts/me-api.py log --project ID --dates D,D --hours 8 --dry-run ``` Run every write with `--dry-run` first and show the requests. Drop the flag @@ -118,5 +129,5 @@ an assumption. ## Scope -Which project a half-day went to, and confirming hours already worked. Not +How a day divided between projects, and confirming hours already worked. Not future allocations, not time off, not anyone else's schedule. diff --git a/skills/hourlog/config.example.json b/skills/hourlog/config.example.json index 971659d..d04ab00 100644 --- a/skills/hourlog/config.example.json +++ b/skills/hourlog/config.example.json @@ -7,10 +7,10 @@ "the longest matching prefix wins, so a worktree can override its parent." ], "timezone": "Europe/Lisbon", - "afternoon_start_hour": 13, "slot_minutes": 5, "day_start_hour": 8, "day_end_hour": 20, + "nominal_day_hours": 8, "projects": [ { "name": "<project name exactly as the timesheet app shows it>", diff --git a/skills/hourlog/scripts/scan-activity.py b/skills/hourlog/scripts/scan-activity.py index 1528fff..6e5fdf2 100755 --- a/skills/hourlog/scripts/scan-activity.py +++ b/skills/hourlog/scripts/scan-activity.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Bucket Claude Code and Codex session activity into half-days per project. +"""Bucket Claude Code and Codex session activity into days per project. Usage: scan-activity.py --since YYYY-MM-DD [--until YYYY-MM-DD] [--json] scan-activity.py --week last|this @@ -9,10 +9,16 @@ Reads ~/.config/hourlog/projects.json for the path-prefix -> project mapping is public and client names are not. The unit is an "active slot" — a 5-minute window in which at least one message -was written. Slots are a set per (day, half, project), so a swarm of 40 -subagent transcripts on one project counts once, and two projects worked in -parallel each keep their own slots. Message counts would make one overnight -autonomous run outweigh a real morning; wall-clock presence does not. +was written. Slots are a set per (day, project), so a swarm of 40 subagent +transcripts on one project counts once, and two projects worked in parallel +each keep their own slots. Message counts would make one overnight autonomous +run outweigh a real morning; wall-clock presence does not. + +Output is one line per project per day: suggested hours, share of the day, and +the active minutes behind it. The suggestion splits a nominal working day by +share, in 15-minute steps — active minutes are a floor on real work, never a +measure of it, so the day's length comes from the calendar and only the split +between projects comes from the sessions. See SKILL.md. """ import argparse import collections @@ -26,10 +32,10 @@ from zoneinfo import ZoneInfo CONFIG = os.path.expanduser("~/.config/hourlog/projects.json") DEFAULTS = { "timezone": "Europe/Lisbon", - "afternoon_start_hour": 13, "slot_minutes": 5, "day_start_hour": 8, "day_end_hour": 20, + "nominal_day_hours": 8, "projects": [], "exclude": [], } @@ -55,7 +61,7 @@ def load_config(path): def classify(cwd, rules): - """-> project name, or None if excluded, or 'unmapped:<top-2-dirs>'.""" + """-> project name, or None if excluded, or 'unmapped:<top-3-dirs>'.""" if not cwd: return "unmapped:?" for prefix, name in rules: @@ -104,6 +110,37 @@ def read_session(path): return cwd, stamps +def split_day(entry, nominal_hours): + """Split a nominal working day across the day's mapped projects by share. + + Largest-remainder over 15-minute steps, so the parts add back up to the + whole day exactly. Unmapped paths get nothing: they are not known to be + client work, and silently handing them hours would hide a missing rule. + """ + for p in entry["projects"]: + p["suggested_hours"] = 0.0 + entry["thin"] = entry["total_active_minutes"] < 30 + mapped = [p for p in entry["projects"] + if not p["project"].startswith("unmapped:")] + weight = sum(p["active_minutes"] for p in mapped) + if not weight or entry["thin"]: + return + quarters = int(round(nominal_hours * 4)) + exact = [(p, quarters * p["active_minutes"] / weight) for p in mapped] + given = [(p, int(v)) for p, v in exact] + left = quarters - sum(v for _, v in given) + order = sorted(range(len(exact)), key=lambda i: -(exact[i][1] % 1)) + for i in order[:left]: + given[i] = (given[i][0], given[i][1] + 1) + for p, q in given: + p["suggested_hours"] = q / 4 + + +def fmt_hours(h): + whole, rem = int(h), round((h - int(h)) * 60) + return f"{whole}h" if not rem else f"{whole}h{rem:02d}" + + def main(): ap = argparse.ArgumentParser() ap.add_argument("--since") @@ -131,12 +168,10 @@ def main(): start = dt.datetime.combine(since, dt.time(0), tz) end = dt.datetime.combine(until, dt.time(23, 59, 59), tz) slot = cfg["slot_minutes"] * 60 - noon = cfg["afternoon_start_hour"] - # (date, half) -> project -> set of slot indices - grid = collections.defaultdict(lambda: collections.defaultdict(set)) - hours = collections.defaultdict(lambda: collections.defaultdict(set)) - seen_cwds = collections.Counter() + # date -> project -> hour -> set of slot indices + grid = collections.defaultdict( + lambda: collections.defaultdict(lambda: collections.defaultdict(set))) sources = [ (os.path.expanduser("~/.claude/projects"), claude_files), @@ -152,7 +187,6 @@ def main(): if proj is None: continue nfiles += 1 - seen_cwds[cwd or "?"] += 1 for ts in stamps: try: t = dt.datetime.fromisoformat( @@ -161,39 +195,39 @@ def main(): continue if not (start <= t <= end): continue - key = (t.date().isoformat(), "AM" if t.hour < noon else "PM") - grid[key][proj].add(int(t.timestamp()) // slot) - hours[key][proj].add(t.hour) + grid[t.date().isoformat()][proj][t.hour].add( + int(t.timestamp()) // slot) del stamps mins = cfg["slot_minutes"] report = [] d = since while d <= until: - for half in ("AM", "PM"): - key = (d.isoformat(), half) - per = grid.get(key, {}) - total = sum(len(v) for v in per.values()) - entry = { - "date": d.isoformat(), - "weekday": d.strftime("%a"), - "half": half, - "total_active_minutes": total * mins, - "projects": [], - } - for proj, slots in sorted(per.items(), key=lambda kv: -len(kv[1])): - hs = sorted(hours[key][proj]) - entry["projects"].append({ - "project": proj, - "active_minutes": len(slots) * mins, - "share": round(len(slots) / total, 3) if total else 0, - "hours": hs, - "outside_workday": [ - h for h in hs - if h < cfg["day_start_hour"] or h >= cfg["day_end_hour"] - ], - }) - report.append(entry) + per = grid.get(d.isoformat(), {}) + totals = {p: sum(len(s) for s in hrs.values()) for p, hrs in per.items()} + day_total = sum(totals.values()) + entry = { + "date": d.isoformat(), + "weekday": d.strftime("%a"), + "total_active_minutes": day_total * mins, + "nominal_day_hours": cfg["nominal_day_hours"], + "projects": [], + } + for proj, n in sorted(totals.items(), key=lambda kv: -kv[1]): + hrs = sorted(per[proj]) + entry["projects"].append({ + "project": proj, + "active_minutes": n * mins, + "share": round(n / day_total, 3) if day_total else 0, + "first_hour": hrs[0], + "last_hour": hrs[-1], + "outside_workday": [ + h for h in hrs + if h < cfg["day_start_hour"] or h >= cfg["day_end_hour"] + ], + }) + split_day(entry, cfg["nominal_day_hours"]) + report.append(entry) d += dt.timedelta(days=1) unmapped = sorted( @@ -203,25 +237,31 @@ def main(): if a.json: json.dump({"since": since.isoformat(), "until": until.isoformat(), "slot_minutes": mins, "sessions": nfiles, + "nominal_day_hours": cfg["nominal_day_hours"], "unmapped": unmapped, "report": report}, sys.stdout, indent=1) print() return 0 print(f"{since} .. {until} ({nfiles} sessions, {mins}-min slots, " - f"{cfg['timezone']})\n") + f"{cfg['timezone']}, {cfg['nominal_day_hours']}h day)") + print("hours are a suggested split of a full day, not measured time\n") + label_w = max([12] + [len(p["project"]) for e in report + for p in e["projects"]]) for e in report: if not e["projects"]: continue - print(f"{e['date']} {e['weekday']} {e['half']} " - f"{e['total_active_minutes']:>4}min active") + note = " — under 30min, treat as empty" if e["thin"] else "" + print(f"{e['date']} {e['weekday']} " + f"{e['total_active_minutes']}min active{note}") for p in e["projects"]: - flag = "" + out = "" if p["outside_workday"]: - flag = " [outside " + ",".join( - f"{h:02d}h" for h in p["outside_workday"]) + "]" - span = f"{p['hours'][0]:02d}-{p['hours'][-1]:02d}h" if p["hours"] else "" - print(f" {p['share']*100:5.1f}% {p['active_minutes']:>4}min " - f"{span:<8} {p['project']}{flag}") + out = " outside " + ",".join( + f"{h:02d}h" for h in p["outside_workday"]) + print(f" {p['project']:<{label_w}} " + f"{fmt_hours(p['suggested_hours']):>6} " + f"{p['share']*100:3.0f}% {p['active_minutes']:>4}min " + f"{p['first_hour']:02d}-{p['last_hour']:02d}h{out}") print() if unmapped: print("unmapped paths — add them to the config or the exclude list:") diff --git a/systemd/hourlog.timer b/systemd/hourlog.timer index 07e468b..3542d59 100644 --- a/systemd/hourlog.timer +++ b/systemd/hourlog.timer @@ -1,9 +1,9 @@ [Unit] -Description=Friday hour log, 16:00 Europe/Lisbon +Description=Friday hour log, 18:00 Europe/Lisbon [Timer] -# System clock is UTC; the zone suffix keeps this at 16:00 wall time year-round. -OnCalendar=Fri 16:00 Europe/Lisbon +# System clock is UTC; the zone suffix keeps this at 18:00 wall time year-round. +OnCalendar=Fri 18:00 Europe/Lisbon Persistent=true AccuracySec=1min From cd63a4c18e67c30d5330ffe18ee16e6aadafc896 Mon Sep 17 00:00:00 2001 From: naps62 <naps62@users.noreply.github.com> Date: Fri, 14 Aug 2026 18:38:45 +0000 Subject: [PATCH 03/12] refactor: hourlog prints a day-by-project table One row per day, one column per project, hours in the cell. The per-day blocks repeated the project name on every line and buried the totals. Share, active minutes, hour ranges, and the outside-working-hours flags move to --json, which is where the skill reads them anyway. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --- skills/hourlog/SKILL.md | 48 ++++++++++++---------- skills/hourlog/scripts/scan-activity.py | 54 +++++++++++++++---------- 2 files changed, 59 insertions(+), 43 deletions(-) diff --git a/skills/hourlog/SKILL.md b/skills/hourlog/SKILL.md index 69a2ec7..715a5e8 100644 --- a/skills/hourlog/SKILL.md +++ b/skills/hourlog/SKILL.md @@ -43,20 +43,25 @@ missing step if not. python3 <skill-dir>/scripts/scan-activity.py --week last ``` -Reports one line per project per day: suggested hours, share of the day, active -minutes, and the hour range they fell in. The unit is a 5-minute slot in which -at least one message was written, deduplicated per project — so a 40-subagent -swarm on one project counts once, and two projects worked in parallel each keep -their own slots. Message counts would let one overnight autonomous run outweigh -a real morning. +Prints a table: one row per day, one column per project, hours in each cell. +That table is the deliverable — show it as-is rather than restating it. -Two things in the output need judgement, not arithmetic: +The unit behind it is a 5-minute slot in which at least one message was +written, deduplicated per project — so a 40-subagent swarm on one project +counts once, and two projects worked in parallel each keep their own slots. +Message counts would let one overnight autonomous run outweigh a real morning. -- **`outside working hours` lines.** Activity at 02:00 is usually an unattended - run, not work. Discount it unless the user says otherwise. -- **`unmapped:` lines.** A path with no rule. Either it is a new client - directory the config is missing — say so and ask — or it is personal work - that belongs in `exclude`. Never guess it into a client project. +Add `--json` for the evidence behind each cell: active minutes, share, hour +range, and which hours fell outside working hours. Read it before proposing +anything, and note two things there: + +- **Hours flagged `outside_workday`.** Activity at 02:00 is usually an + unattended run, not work. If most of a project's minutes came from 21h-02h, + its share is inflated — say so and shift the split. +- **`unmapped` entries.** A path with no rule, excluded from the split, so the + affected days are wrong rather than merely incomplete. Either it is a new + client directory the config is missing — say so and ask — or it is personal + work that belongs in `exclude`. Never guess it into a client project. ## 2. Propose the hours @@ -71,13 +76,8 @@ job is the judgement it cannot do: - One project at 85% or more: round it up to the whole day rather than leaving a token 1h on the other. -- Discount hours flagged `outside`. If most of a project's minutes came from - 21h-02h, its share is inflated by an unattended run — say so and shift the - split rather than passing the number through. -- Days marked `under 30min, treat as empty` get nothing proposed. -- An `unmapped:` line with real minutes means the split is wrong, not just - incomplete: those minutes were excluded from the division. Resolve the - mapping before proposing hours for that day. +- Days marked `*` in the table get nothing proposed. +- Correct the split for the two things flagged in step 1 before proposing it. Never scale a day *down* because its transcripts are thin. A quiet day is a normal working day unless the user says it was not, or the timesheet already @@ -100,9 +100,13 @@ planned hours) or absent. That splits the proposal in two: ## 4. Show the table, then ask -One row per project per day: date, weekday, project, proposed hours, what the -timesheet currently says, and the action (confirm / adjust / add / skip). -Flag every row where the evidence was weak or outside working hours. +The scan's table, one row per day and one column per project, with the +timesheet's current hours beside each proposed cell where the two differ. Mark +any day that needs a new entry rather than a confirmation. + +Keep it to that table plus a line for anything you had to judge — a discounted +overnight run, an unmapped path, a day you left empty. No commentary on days +that were straightforward. Then ask once, plainly, whether to submit. Wait for an answer. Silence, a timeout, or "user may be away" is not approval — leave the timesheet alone and diff --git a/skills/hourlog/scripts/scan-activity.py b/skills/hourlog/scripts/scan-activity.py index 6e5fdf2..d297349 100755 --- a/skills/hourlog/scripts/scan-activity.py +++ b/skills/hourlog/scripts/scan-activity.py @@ -242,29 +242,41 @@ def main(): print() return 0 - print(f"{since} .. {until} ({nfiles} sessions, {mins}-min slots, " - f"{cfg['timezone']}, {cfg['nominal_day_hours']}h day)") - print("hours are a suggested split of a full day, not measured time\n") - label_w = max([12] + [len(p["project"]) for e in report - for p in e["projects"]]) + cols = [p for p in dict.fromkeys( + x["project"] for e in report for x in e["projects"]) + if not p.startswith("unmapped:")] + widths = [max(len(c), 6) for c in cols] + head = "day " + " ".join( + f"{c:>{w}}" for c, w in zip(cols, widths)) + " total" + print(head) + print("-" * len(head)) + + totals = collections.Counter() + flagged = False for e in report: - if not e["projects"]: - continue - note = " — under 30min, treat as empty" if e["thin"] else "" - print(f"{e['date']} {e['weekday']} " - f"{e['total_active_minutes']}min active{note}") - for p in e["projects"]: - out = "" - if p["outside_workday"]: - out = " outside " + ",".join( - f"{h:02d}h" for h in p["outside_workday"]) - print(f" {p['project']:<{label_w}} " - f"{fmt_hours(p['suggested_hours']):>6} " - f"{p['share']*100:3.0f}% {p['active_minutes']:>4}min " - f"{p['first_hour']:02d}-{p['last_hour']:02d}h{out}") - print() + hours = {p["project"]: p["suggested_hours"] for p in e["projects"]} + day_sum = sum(hours.get(c, 0) for c in cols) + cells = " ".join( + f"{fmt_hours(hours[c]) if hours.get(c) else '—':>{w}}" + for c, w in zip(cols, widths)) + mark = " *" if e["thin"] and e["total_active_minutes"] else "" + flagged = flagged or bool(mark) + print(f"{e['date']} {e['weekday']} {cells} " + f"{fmt_hours(day_sum) if day_sum else '—':>5}{mark}") + for c in cols: + totals[c] += hours.get(c, 0) + + print("-" * len(head)) + print("total " + " ".join( + f"{fmt_hours(totals[c]):>{w}}" for c, w in zip(cols, widths)) + + f" {fmt_hours(sum(totals.values())):>5}") + + if flagged: + print("\n* under 30min of activity — treat as empty unless you know " + "otherwise") if unmapped: - print("unmapped paths — add them to the config or the exclude list:") + print("\nunmapped paths, excluded from the split — add them to the " + "config or the exclude list:") for u in unmapped: print(" ", u) return 0 From 39d88899af31704ffd60c3b17f48dd445d292e82 Mon Sep 17 00:00:00 2001 From: naps62 <naps62@users.noreply.github.com> Date: Fri, 14 Aug 2026 18:40:44 +0000 Subject: [PATCH 04/12] refactor: back to per-day blocks, add a totals line MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The matrix table dropped the evidence — share, active minutes, hour range, and the outside-working-hours flags — which are what make a proposed number checkable rather than asserted. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --- skills/hourlog/SKILL.md | 27 +++++------ skills/hourlog/scripts/scan-activity.py | 61 ++++++++++++------------- 2 files changed, 44 insertions(+), 44 deletions(-) diff --git a/skills/hourlog/SKILL.md b/skills/hourlog/SKILL.md index 715a5e8..1a171e5 100644 --- a/skills/hourlog/SKILL.md +++ b/skills/hourlog/SKILL.md @@ -43,26 +43,27 @@ missing step if not. python3 <skill-dir>/scripts/scan-activity.py --week last ``` -Prints a table: one row per day, one column per project, hours in each cell. -That table is the deliverable — show it as-is rather than restating it. +Prints one block per day — a line per project with suggested hours, share, +active minutes, and the hour range — then a totals line. That output is the +deliverable: show it as-is rather than restating it in prose. The unit behind it is a 5-minute slot in which at least one message was written, deduplicated per project — so a 40-subagent swarm on one project counts once, and two projects worked in parallel each keep their own slots. Message counts would let one overnight autonomous run outweigh a real morning. -Add `--json` for the evidence behind each cell: active minutes, share, hour -range, and which hours fell outside working hours. Read it before proposing -anything, and note two things there: +Two things in the output need judgement, not arithmetic: -- **Hours flagged `outside_workday`.** Activity at 02:00 is usually an - unattended run, not work. If most of a project's minutes came from 21h-02h, - its share is inflated — say so and shift the split. -- **`unmapped` entries.** A path with no rule, excluded from the split, so the +- **`outside` hours.** Activity at 02:00 is usually an unattended run, not + work. If most of a project's minutes came from 21h-02h, its share is + inflated — say so and shift the split. +- **`unmapped:` lines.** A path with no rule, excluded from the split, so the affected days are wrong rather than merely incomplete. Either it is a new client directory the config is missing — say so and ask — or it is personal work that belongs in `exclude`. Never guess it into a client project. +`--json` carries the same fields if you need to compute against them. + ## 2. Propose the hours **Active minutes are a floor on real work, never a measure of it.** Meetings, @@ -76,7 +77,7 @@ job is the judgement it cannot do: - One project at 85% or more: round it up to the whole day rather than leaving a token 1h on the other. -- Days marked `*` in the table get nothing proposed. +- Days marked `under 30min, treat as empty` get nothing proposed. - Correct the split for the two things flagged in step 1 before proposing it. Never scale a day *down* because its transcripts are thin. A quiet day is a @@ -100,9 +101,9 @@ planned hours) or absent. That splits the proposal in two: ## 4. Show the table, then ask -The scan's table, one row per day and one column per project, with the -timesheet's current hours beside each proposed cell where the two differ. Mark -any day that needs a new entry rather than a confirmation. +One row per project per day: date, weekday, project, proposed hours, what the +timesheet says now, and the action (confirm / adjust / add / skip). Mark any +day that needs a new entry rather than a confirmation. Keep it to that table plus a line for anything you had to judge — a discounted overnight run, an unmapped path, a day you left empty. No commentary on days diff --git a/skills/hourlog/scripts/scan-activity.py b/skills/hourlog/scripts/scan-activity.py index d297349..9f26136 100755 --- a/skills/hourlog/scripts/scan-activity.py +++ b/skills/hourlog/scripts/scan-activity.py @@ -242,41 +242,40 @@ def main(): print() return 0 - cols = [p for p in dict.fromkeys( - x["project"] for e in report for x in e["projects"]) - if not p.startswith("unmapped:")] - widths = [max(len(c), 6) for c in cols] - head = "day " + " ".join( - f"{c:>{w}}" for c, w in zip(cols, widths)) + " total" - print(head) - print("-" * len(head)) - - totals = collections.Counter() - flagged = False + print(f"{since} .. {until} ({nfiles} sessions, {mins}-min slots, " + f"{cfg['timezone']}, {cfg['nominal_day_hours']}h day)") + print("hours are a suggested split of a full day, not measured time\n") + label_w = max([12] + [len(p["project"]) for e in report + for p in e["projects"]]) for e in report: - hours = {p["project"]: p["suggested_hours"] for p in e["projects"]} - day_sum = sum(hours.get(c, 0) for c in cols) - cells = " ".join( - f"{fmt_hours(hours[c]) if hours.get(c) else '—':>{w}}" - for c, w in zip(cols, widths)) - mark = " *" if e["thin"] and e["total_active_minutes"] else "" - flagged = flagged or bool(mark) - print(f"{e['date']} {e['weekday']} {cells} " - f"{fmt_hours(day_sum) if day_sum else '—':>5}{mark}") - for c in cols: - totals[c] += hours.get(c, 0) + if not e["projects"]: + continue + note = " — under 30min, treat as empty" if e["thin"] else "" + print(f"{e['date']} {e['weekday']} " + f"{e['total_active_minutes']}min active{note}") + for p in e["projects"]: + out = "" + if p["outside_workday"]: + out = " outside " + ",".join( + f"{h:02d}h" for h in p["outside_workday"]) + print(f" {p['project']:<{label_w}} " + f"{fmt_hours(p['suggested_hours']):>6} " + f"{p['share']*100:3.0f}% {p['active_minutes']:>4}min " + f"{p['first_hour']:02d}-{p['last_hour']:02d}h{out}") + print() - print("-" * len(head)) - print("total " + " ".join( - f"{fmt_hours(totals[c]):>{w}}" for c, w in zip(cols, widths)) + - f" {fmt_hours(sum(totals.values())):>5}") + week = collections.Counter() + for e in report: + for p in e["projects"]: + if p["suggested_hours"]: + week[p["project"]] += p["suggested_hours"] + if week: + print("total " + " ".join( + f"{p} {fmt_hours(h)}" for p, h in week.most_common()) + + f" ({fmt_hours(sum(week.values()))})\n") - if flagged: - print("\n* under 30min of activity — treat as empty unless you know " - "otherwise") if unmapped: - print("\nunmapped paths, excluded from the split — add them to the " - "config or the exclude list:") + print("unmapped paths — add them to the config or the exclude list:") for u in unmapped: print(" ", u) return 0 From 658b9850bb7e056af8f1ae379bd9ec8d60c23ee5 Mon Sep 17 00:00:00 2001 From: naps62 <naps62@users.noreply.github.com> Date: Fri, 14 Aug 2026 18:42:15 +0000 Subject: [PATCH 05/12] style: rule off the report, count only sessions in range The session count came from the mtime prefilter, so an old date range reported every file on disk as if it had contributed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --- skills/hourlog/scripts/scan-activity.py | 45 ++++++++++++++++--------- 1 file changed, 30 insertions(+), 15 deletions(-) diff --git a/skills/hourlog/scripts/scan-activity.py b/skills/hourlog/scripts/scan-activity.py index 9f26136..7c3c47d 100755 --- a/skills/hourlog/scripts/scan-activity.py +++ b/skills/hourlog/scripts/scan-activity.py @@ -186,7 +186,7 @@ def main(): proj = classify(cwd, cfg["_rules"]) if proj is None: continue - nfiles += 1 + hit = False for ts in stamps: try: t = dt.datetime.fromisoformat( @@ -195,8 +195,10 @@ def main(): continue if not (start <= t <= end): continue + hit = True grid[t.date().isoformat()][proj][t.hour].add( int(t.timestamp()) // slot) + nfiles += hit del stamps mins = cfg["slot_minutes"] @@ -242,40 +244,53 @@ def main(): print() return 0 - print(f"{since} .. {until} ({nfiles} sessions, {mins}-min slots, " - f"{cfg['timezone']}, {cfg['nominal_day_hours']}h day)") - print("hours are a suggested split of a full day, not measured time\n") + head = [ + f"{since} .. {until} ({nfiles} sessions, {mins}-min slots, " + f"{cfg['timezone']}, {cfg['nominal_day_hours']}h day)", + "hours are a suggested split of a full day, not measured time", + ] label_w = max([12] + [len(p["project"]) for e in report for p in e["projects"]]) + body = [] for e in report: if not e["projects"]: continue + if body: + body.append("") note = " — under 30min, treat as empty" if e["thin"] else "" - print(f"{e['date']} {e['weekday']} " - f"{e['total_active_minutes']}min active{note}") + body.append(f"{e['date']} {e['weekday']} " + f"{e['total_active_minutes']}min active{note}") for p in e["projects"]: out = "" if p["outside_workday"]: out = " outside " + ",".join( f"{h:02d}h" for h in p["outside_workday"]) - print(f" {p['project']:<{label_w}} " - f"{fmt_hours(p['suggested_hours']):>6} " - f"{p['share']*100:3.0f}% {p['active_minutes']:>4}min " - f"{p['first_hour']:02d}-{p['last_hour']:02d}h{out}") - print() + body.append(f" {p['project']:<{label_w}} " + f"{fmt_hours(p['suggested_hours']):>6} " + f"{p['share']*100:3.0f}% {p['active_minutes']:>4}min " + f"{p['first_hour']:02d}-{p['last_hour']:02d}h{out}") week = collections.Counter() for e in report: for p in e["projects"]: if p["suggested_hours"]: week[p["project"]] += p["suggested_hours"] + total = "" if week: - print("total " + " ".join( - f"{p} {fmt_hours(h)}" for p, h in week.most_common()) + - f" ({fmt_hours(sum(week.values()))})\n") + total = "total " + " ".join( + f"{p} {fmt_hours(h)}" for p, h in week.most_common()) + \ + f" ({fmt_hours(sum(week.values()))})" + + rule = "-" * max(len(x) for x in head + body + [total]) + print("\n".join(head)) + print(rule) + print("\n".join(body)) + if total: + print(rule) + print(total) if unmapped: - print("unmapped paths — add them to the config or the exclude list:") + print("\nunmapped paths — add them to the config or the exclude list:") for u in unmapped: print(" ", u) return 0 From ea9c3acecfd5f0dbccb9b6e62a3c822900d16561 Mon Sep 17 00:00:00 2001 From: naps62 <naps62@users.noreply.github.com> Date: Fri, 14 Aug 2026 19:26:06 +0000 Subject: [PATCH 06/12] feat: emit the day report as a markdown table Padded pipes, so it reads as a grid in the terminal and renders as a real table when pasted anywhere else. Each cell carries hours, share and active minutes; a flags column carries what needs judgement. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --- skills/hourlog/SKILL.md | 24 +++--- skills/hourlog/scripts/scan-activity.py | 105 +++++++++++++++--------- 2 files changed, 77 insertions(+), 52 deletions(-) diff --git a/skills/hourlog/SKILL.md b/skills/hourlog/SKILL.md index 1a171e5..e1b0f22 100644 --- a/skills/hourlog/SKILL.md +++ b/skills/hourlog/SKILL.md @@ -43,24 +43,24 @@ missing step if not. python3 <skill-dir>/scripts/scan-activity.py --week last ``` -Prints one block per day — a line per project with suggested hours, share, -active minutes, and the hour range — then a totals line. That output is the -deliverable: show it as-is rather than restating it in prose. +Prints a markdown table: one row per day, one column per project holding +`hours · share · active minutes`, then a totals row. That table is the +deliverable — paste it as-is rather than restating it in prose. The unit behind it is a 5-minute slot in which at least one message was written, deduplicated per project — so a 40-subagent swarm on one project counts once, and two projects worked in parallel each keep their own slots. Message counts would let one overnight autonomous run outweigh a real morning. -Two things in the output need judgement, not arithmetic: +The `flags` column carries the two things that need judgement, not arithmetic: -- **`outside` hours.** Activity at 02:00 is usually an unattended run, not - work. If most of a project's minutes came from 21h-02h, its share is - inflated — say so and shift the split. -- **`unmapped:` lines.** A path with no rule, excluded from the split, so the - affected days are wrong rather than merely incomplete. Either it is a new - client directory the config is missing — say so and ask — or it is personal - work that belongs in `exclude`. Never guess it into a client project. +- **`outside HHh`.** Activity at 02:00 is usually an unattended run, not work. + If most of a project's minutes came from 21h-02h, its share is inflated — + say so and shift the split. +- **`unmapped time excluded`.** A path with no rule, left out of the split, so + that day is wrong rather than merely incomplete. Either it is a new client + directory the config is missing — say so and ask — or it is personal work + that belongs in `exclude`. Never guess it into a client project. `--json` carries the same fields if you need to compute against them. @@ -77,7 +77,7 @@ job is the judgement it cannot do: - One project at 85% or more: round it up to the whole day rather than leaving a token 1h on the other. -- Days marked `under 30min, treat as empty` get nothing proposed. +- Days flagged `under 30min, treat as empty` get nothing proposed. - Correct the split for the two things flagged in step 1 before proposing it. Never scale a day *down* because its transcripts are thin. A quiet day is a diff --git a/skills/hourlog/scripts/scan-activity.py b/skills/hourlog/scripts/scan-activity.py index 7c3c47d..0925a0f 100755 --- a/skills/hourlog/scripts/scan-activity.py +++ b/skills/hourlog/scripts/scan-activity.py @@ -141,6 +141,33 @@ def fmt_hours(h): return f"{whole}h" if not rem else f"{whole}h{rem:02d}" +def fmt_hour_list(hours): + """[0,7,20,21,22] -> '00h, 07h, 20-22h'.""" + out, run = [], [] + for h in sorted(set(hours)) + [None]: + if run and h == run[-1] + 1: + run.append(h) + continue + if run: + out.append(f"{run[0]:02d}h" if len(run) == 1 + else f"{run[0]:02d}-{run[-1]:02d}h") + run = [h] if h is not None else [] + return ", ".join(out) + + +def md_table(rows, align_right=()): + """Render rows (first is the header) as a padded markdown table.""" + w = [max(len(r[i]) for r in rows) for i in range(len(rows[0]))] + def line(cells): + return "| " + " | ".join( + c.rjust(w[i]) if i in align_right else c.ljust(w[i]) + for i, c in enumerate(cells)) + " |" + sep = "|" + "|".join( + ("-" * (w[i] + 1) + ":") if i in align_right else ("-" * (w[i] + 2)) + for i in range(len(w))) + "|" + return "\n".join([line(rows[0]), sep] + [line(r) for r in rows[1:]]) + + def main(): ap = argparse.ArgumentParser() ap.add_argument("--since") @@ -244,50 +271,48 @@ def main(): print() return 0 - head = [ - f"{since} .. {until} ({nfiles} sessions, {mins}-min slots, " - f"{cfg['timezone']}, {cfg['nominal_day_hours']}h day)", - "hours are a suggested split of a full day, not measured time", - ] - label_w = max([12] + [len(p["project"]) for e in report - for p in e["projects"]]) - body = [] + print(f"{since} .. {until} — {nfiles} sessions, {mins}-min slots, " + f"{cfg['timezone']}, {cfg['nominal_day_hours']}h day") + print("hours are a suggested split of a full day, not measured time\n") + + cols = [p for p in dict.fromkeys( + x["project"] for e in report for x in e["projects"]) + if not p.startswith("unmapped:")] + if not cols: + print("no mapped project activity in this range") + return 0 + + rows = [["day"] + cols + ["total", "flags"]] + week = collections.Counter() for e in report: if not e["projects"]: continue - if body: - body.append("") - note = " — under 30min, treat as empty" if e["thin"] else "" - body.append(f"{e['date']} {e['weekday']} " - f"{e['total_active_minutes']}min active{note}") - for p in e["projects"]: - out = "" - if p["outside_workday"]: - out = " outside " + ",".join( - f"{h:02d}h" for h in p["outside_workday"]) - body.append(f" {p['project']:<{label_w}} " - f"{fmt_hours(p['suggested_hours']):>6} " - f"{p['share']*100:3.0f}% {p['active_minutes']:>4}min " - f"{p['first_hour']:02d}-{p['last_hour']:02d}h{out}") + by = {p["project"]: p for p in e["projects"]} + cells = [] + for c in cols: + p = by.get(c) + cells.append("—" if not p or not p["suggested_hours"] else + f"{fmt_hours(p['suggested_hours'])} · " + f"{p['share']*100:.0f}% · {p['active_minutes']}min") + if p: + week[c] += p["suggested_hours"] + day_sum = sum(by[c]["suggested_hours"] for c in cols if c in by) + flags = [] + if e["thin"]: + flags.append("under 30min, treat as empty") + outside = sorted({h for p in e["projects"] for h in p["outside_workday"]}) + if outside: + flags.append("outside " + fmt_hour_list(outside)) + if any(p["project"].startswith("unmapped:") for p in e["projects"]): + flags.append("unmapped time excluded") + rows.append([f"{e['date']} {e['weekday']}"] + cells + + [fmt_hours(day_sum) if day_sum else "—", "; ".join(flags)]) - week = collections.Counter() - for e in report: - for p in e["projects"]: - if p["suggested_hours"]: - week[p["project"]] += p["suggested_hours"] - total = "" - if week: - total = "total " + " ".join( - f"{p} {fmt_hours(h)}" for p, h in week.most_common()) + \ - f" ({fmt_hours(sum(week.values()))})" - - rule = "-" * max(len(x) for x in head + body + [total]) - print("\n".join(head)) - print(rule) - print("\n".join(body)) - if total: - print(rule) - print(total) + rows.append(["**total**"] + + [f"**{fmt_hours(week[c])}**" for c in cols] + + [f"**{fmt_hours(sum(week.values()))}**", ""]) + right = set(range(1, len(cols) + 2)) + print(md_table(rows, align_right=right)) if unmapped: print("\nunmapped paths — add them to the config or the exclude list:") From bf1dc761256b8e6fd582f1e01b22f6515ec1f58f Mon Sep 17 00:00:00 2001 From: naps62 <naps62@users.noreply.github.com> Date: Fri, 14 Aug 2026 19:51:28 +0000 Subject: [PATCH 07/12] feat: draw the grid by default, --markdown to opt out A markdown table carries no borders of its own; whether any get drawn is up to the renderer, and terminal renderers mostly draw none. Emitting the grid directly makes the output look the same everywhere it lands. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --- skills/hourlog/SKILL.md | 8 +++- skills/hourlog/scripts/scan-activity.py | 57 ++++++++++++++++++------- 2 files changed, 48 insertions(+), 17 deletions(-) diff --git a/skills/hourlog/SKILL.md b/skills/hourlog/SKILL.md index e1b0f22..5b5ff4d 100644 --- a/skills/hourlog/SKILL.md +++ b/skills/hourlog/SKILL.md @@ -43,9 +43,13 @@ missing step if not. python3 <skill-dir>/scripts/scan-activity.py --week last ``` -Prints a markdown table: one row per day, one column per project holding +Prints a drawn grid: one row per day, one column per project holding `hours · share · active minutes`, then a totals row. That table is the -deliverable — paste it as-is rather than restating it in prose. +deliverable — show it as-is, inside a fenced code block so the terminal +renderer leaves the borders alone, rather than restating it in prose. + +`--markdown` swaps the grid for pipes when the destination renders tables +itself (a PR body, an issue, a doc). The unit behind it is a 5-minute slot in which at least one message was written, deduplicated per project — so a 40-subagent swarm on one project diff --git a/skills/hourlog/scripts/scan-activity.py b/skills/hourlog/scripts/scan-activity.py index 0925a0f..1c96b34 100755 --- a/skills/hourlog/scripts/scan-activity.py +++ b/skills/hourlog/scripts/scan-activity.py @@ -14,11 +14,16 @@ transcripts on one project counts once, and two projects worked in parallel each keep their own slots. Message counts would make one overnight autonomous run outweigh a real morning; wall-clock presence does not. -Output is one line per project per day: suggested hours, share of the day, and -the active minutes behind it. The suggestion splits a nominal working day by -share, in 15-minute steps — active minutes are a floor on real work, never a -measure of it, so the day's length comes from the calendar and only the split -between projects comes from the sessions. See SKILL.md. +Output is a table: one row per day, one column per project, each cell holding +suggested hours, share of the day, and the active minutes behind it. The +suggestion splits a nominal working day by share, in 15-minute steps — active +minutes are a floor on real work, never a measure of it, so the day's length +comes from the calendar and only the split between projects comes from the +sessions. See SKILL.md. + +Default rendering is a drawn grid, because a markdown table has no borders of +its own and terminal renderers vary in whether they draw any. --markdown emits +pipes instead, for pasting somewhere that does render them. """ import argparse import collections @@ -155,17 +160,35 @@ def fmt_hour_list(hours): return ", ".join(out) +def widths(rows): + return [max(len(r[i]) for r in rows) for i in range(len(rows[0]))] + + +def _cells(row, w, align_right): + return "| " + " | ".join( + c.rjust(w[i]) if i in align_right else c.ljust(w[i]) + for i, c in enumerate(row)) + " |" + + +def box_table(rows, align_right=()): + """Render rows (first is the header) as a grid with every cell bordered.""" + w = widths(rows) + rule = "+" + "+".join("-" * (n + 2) for n in w) + "+" + out = [rule] + for row in rows: + out += [_cells(row, w, align_right), rule] + return "\n".join(out) + + def md_table(rows, align_right=()): """Render rows (first is the header) as a padded markdown table.""" - w = [max(len(r[i]) for r in rows) for i in range(len(rows[0]))] - def line(cells): - return "| " + " | ".join( - c.rjust(w[i]) if i in align_right else c.ljust(w[i]) - for i, c in enumerate(cells)) + " |" + w = widths(rows) sep = "|" + "|".join( ("-" * (w[i] + 1) + ":") if i in align_right else ("-" * (w[i] + 2)) for i in range(len(w))) + "|" - return "\n".join([line(rows[0]), sep] + [line(r) for r in rows[1:]]) + return "\n".join( + [_cells(rows[0], w, align_right), sep] + + [_cells(r, w, align_right) for r in rows[1:]]) def main(): @@ -175,6 +198,8 @@ def main(): ap.add_argument("--week", choices=["last", "this"]) ap.add_argument("--config", default=CONFIG) ap.add_argument("--json", action="store_true") + ap.add_argument("--markdown", action="store_true", + help="pipe table for pasting, instead of a drawn grid") a = ap.parse_args() cfg = load_config(a.config) @@ -308,11 +333,13 @@ def main(): rows.append([f"{e['date']} {e['weekday']}"] + cells + [fmt_hours(day_sum) if day_sum else "—", "; ".join(flags)]) - rows.append(["**total**"] + - [f"**{fmt_hours(week[c])}**" for c in cols] + - [f"**{fmt_hours(sum(week.values()))}**", ""]) + bold = (lambda s: f"**{s}**") if a.markdown else (lambda s: s) + rows.append([bold("total")] + + [bold(fmt_hours(week[c])) for c in cols] + + [bold(fmt_hours(sum(week.values()))), ""]) right = set(range(1, len(cols) + 2)) - print(md_table(rows, align_right=right)) + render = md_table if a.markdown else box_table + print(render(rows, align_right=right)) if unmapped: print("\nunmapped paths — add them to the config or the exclude list:") From b453e72d42b6c238e2840b4c274777a6f6637267 Mon Sep 17 00:00:00 2001 From: naps62 <naps62@users.noreply.github.com> Date: Fri, 14 Aug 2026 19:52:30 +0000 Subject: [PATCH 08/12] Revert "feat: draw the grid by default, --markdown to opt out" The drawn grid was solving the wrong problem: the script output was already right, and fencing it in chat is what turned a rendered table into raw dashes. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --- skills/hourlog/SKILL.md | 8 +--- skills/hourlog/scripts/scan-activity.py | 57 +++++++------------------ 2 files changed, 17 insertions(+), 48 deletions(-) diff --git a/skills/hourlog/SKILL.md b/skills/hourlog/SKILL.md index 5b5ff4d..e1b0f22 100644 --- a/skills/hourlog/SKILL.md +++ b/skills/hourlog/SKILL.md @@ -43,13 +43,9 @@ missing step if not. python3 <skill-dir>/scripts/scan-activity.py --week last ``` -Prints a drawn grid: one row per day, one column per project holding +Prints a markdown table: one row per day, one column per project holding `hours · share · active minutes`, then a totals row. That table is the -deliverable — show it as-is, inside a fenced code block so the terminal -renderer leaves the borders alone, rather than restating it in prose. - -`--markdown` swaps the grid for pipes when the destination renders tables -itself (a PR body, an issue, a doc). +deliverable — paste it as-is rather than restating it in prose. The unit behind it is a 5-minute slot in which at least one message was written, deduplicated per project — so a 40-subagent swarm on one project diff --git a/skills/hourlog/scripts/scan-activity.py b/skills/hourlog/scripts/scan-activity.py index 1c96b34..0925a0f 100755 --- a/skills/hourlog/scripts/scan-activity.py +++ b/skills/hourlog/scripts/scan-activity.py @@ -14,16 +14,11 @@ transcripts on one project counts once, and two projects worked in parallel each keep their own slots. Message counts would make one overnight autonomous run outweigh a real morning; wall-clock presence does not. -Output is a table: one row per day, one column per project, each cell holding -suggested hours, share of the day, and the active minutes behind it. The -suggestion splits a nominal working day by share, in 15-minute steps — active -minutes are a floor on real work, never a measure of it, so the day's length -comes from the calendar and only the split between projects comes from the -sessions. See SKILL.md. - -Default rendering is a drawn grid, because a markdown table has no borders of -its own and terminal renderers vary in whether they draw any. --markdown emits -pipes instead, for pasting somewhere that does render them. +Output is one line per project per day: suggested hours, share of the day, and +the active minutes behind it. The suggestion splits a nominal working day by +share, in 15-minute steps — active minutes are a floor on real work, never a +measure of it, so the day's length comes from the calendar and only the split +between projects comes from the sessions. See SKILL.md. """ import argparse import collections @@ -160,35 +155,17 @@ def fmt_hour_list(hours): return ", ".join(out) -def widths(rows): - return [max(len(r[i]) for r in rows) for i in range(len(rows[0]))] - - -def _cells(row, w, align_right): - return "| " + " | ".join( - c.rjust(w[i]) if i in align_right else c.ljust(w[i]) - for i, c in enumerate(row)) + " |" - - -def box_table(rows, align_right=()): - """Render rows (first is the header) as a grid with every cell bordered.""" - w = widths(rows) - rule = "+" + "+".join("-" * (n + 2) for n in w) + "+" - out = [rule] - for row in rows: - out += [_cells(row, w, align_right), rule] - return "\n".join(out) - - def md_table(rows, align_right=()): """Render rows (first is the header) as a padded markdown table.""" - w = widths(rows) + w = [max(len(r[i]) for r in rows) for i in range(len(rows[0]))] + def line(cells): + return "| " + " | ".join( + c.rjust(w[i]) if i in align_right else c.ljust(w[i]) + for i, c in enumerate(cells)) + " |" sep = "|" + "|".join( ("-" * (w[i] + 1) + ":") if i in align_right else ("-" * (w[i] + 2)) for i in range(len(w))) + "|" - return "\n".join( - [_cells(rows[0], w, align_right), sep] + - [_cells(r, w, align_right) for r in rows[1:]]) + return "\n".join([line(rows[0]), sep] + [line(r) for r in rows[1:]]) def main(): @@ -198,8 +175,6 @@ def main(): ap.add_argument("--week", choices=["last", "this"]) ap.add_argument("--config", default=CONFIG) ap.add_argument("--json", action="store_true") - ap.add_argument("--markdown", action="store_true", - help="pipe table for pasting, instead of a drawn grid") a = ap.parse_args() cfg = load_config(a.config) @@ -333,13 +308,11 @@ def main(): rows.append([f"{e['date']} {e['weekday']}"] + cells + [fmt_hours(day_sum) if day_sum else "—", "; ".join(flags)]) - bold = (lambda s: f"**{s}**") if a.markdown else (lambda s: s) - rows.append([bold("total")] + - [bold(fmt_hours(week[c])) for c in cols] + - [bold(fmt_hours(sum(week.values()))), ""]) + rows.append(["**total**"] + + [f"**{fmt_hours(week[c])}**" for c in cols] + + [f"**{fmt_hours(sum(week.values()))}**", ""]) right = set(range(1, len(cols) + 2)) - render = md_table if a.markdown else box_table - print(render(rows, align_right=right)) + print(md_table(rows, align_right=right)) if unmapped: print("\nunmapped paths — add them to the config or the exclude list:") From f0c301b3a3ab76449c7bfae09100d008312f5f76 Mon Sep 17 00:00:00 2001 From: naps62 <naps62@users.noreply.github.com> Date: Fri, 14 Aug 2026 20:10:03 +0000 Subject: [PATCH 09/12] docs: hourlog table goes in the reply unfenced Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --- skills/hourlog/SKILL.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/skills/hourlog/SKILL.md b/skills/hourlog/SKILL.md index e1b0f22..d37948e 100644 --- a/skills/hourlog/SKILL.md +++ b/skills/hourlog/SKILL.md @@ -47,6 +47,9 @@ Prints a markdown table: one row per day, one column per project holding `hours · share · active minutes`, then a totals row. That table is the deliverable — paste it as-is rather than restating it in prose. +Paste it as plain markdown in the reply. Never wrap it in a code fence: a +fence shows the raw pipes and dashes instead of a rendered table. + The unit behind it is a 5-minute slot in which at least one message was written, deduplicated per project — so a 40-subagent swarm on one project counts once, and two projects worked in parallel each keep their own slots. From 439d3601b49529af694537fa99678a9e70eea121 Mon Sep 17 00:00:00 2001 From: naps62 <naps62@users.noreply.github.com> Date: Fri, 14 Aug 2026 20:33:34 +0000 Subject: [PATCH 10/12] feat: report measured time, drop the nominal-day fit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Splitting a fixed 8h day by share turned 160 minutes of Friday morning into "7h Tesser". The number looked measured and was not, and no column in the table said which. Cells now carry the time each project was actually active. The total column is wall-clock presence — the union of active slots — so it reads lower than the row sum when sessions overlapped. Measured time is a floor; the skill says so and leaves adding the rest to the user. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --- README.md | 2 +- skills/hourlog/SKILL.md | 74 +++++++++----------- skills/hourlog/config.example.json | 1 - skills/hourlog/scripts/scan-activity.py | 90 ++++++++++--------------- 4 files changed, 69 insertions(+), 98 deletions(-) diff --git a/README.md b/README.md index f283401..9d860e5 100644 --- a/README.md +++ b/README.md @@ -113,7 +113,7 @@ Drop a new `skills/<name>/SKILL.md` (+ optional `scripts/`, `references/`, `asse | `nightshift` | hours-long unattended build; architect delegating to subagents, backs off before the 5h limit | | `linear-common` | shared config/setup/worktree conventions + local verification budget (dependency of work/yolo/blitz/nightshift) | | `week-review` | review the past week's sessions for recurring friction; reads open issues here as carry-over | -| `hourlog` | hours-per-project-per-day proposal from session activity, reconciled against the timesheet; submits only what you approve | +| `hourlog` | measured active time per project per day from session transcripts, reconciled against the timesheet; submits only what you approve | | `crit`, `improve-codebase-architecture` | misc | ## Vendored skills diff --git a/skills/hourlog/SKILL.md b/skills/hourlog/SKILL.md index d37948e..ebc8b45 100644 --- a/skills/hourlog/SKILL.md +++ b/skills/hourlog/SKILL.md @@ -14,8 +14,8 @@ allowed-tools: # Hour log -Turn session activity into an hours-per-project-per-day proposal, check it against -the timesheet, and submit only what the user approves. +Report how long each client project was actually active on each day, check +that against the timesheet, and submit only the hours the user gives you. The timesheet is a company record. Nothing is written to it without the user saying go, in this session, after seeing the table. An unattended run stops at @@ -43,9 +43,13 @@ missing step if not. python3 <skill-dir>/scripts/scan-activity.py --week last ``` -Prints a markdown table: one row per day, one column per project holding -`hours · share · active minutes`, then a totals row. That table is the -deliverable — paste it as-is rather than restating it in prose. +Prints a markdown table: one row per day, one column per project holding the +time that project was actually active, plus wall-clock `total`, the day's +`window`, and `flags`. That table is the deliverable — paste it as-is rather +than restating it in prose. + +`total` is the union of active slots, so on a day with parallel sessions it is +less than the row sum. Both numbers are true; they answer different questions. Paste it as plain markdown in the reply. Never wrap it in a code fence: a fence shows the raw pipes and dashes instead of a rendered table. @@ -55,37 +59,26 @@ written, deduplicated per project — so a 40-subagent swarm on one project counts once, and two projects worked in parallel each keep their own slots. Message counts would let one overnight autonomous run outweigh a real morning. -The `flags` column carries the two things that need judgement, not arithmetic: - -- **`outside HHh`.** Activity at 02:00 is usually an unattended run, not work. - If most of a project's minutes came from 21h-02h, its share is inflated — - say so and shift the split. -- **`unmapped time excluded`.** A path with no rule, left out of the split, so - that day is wrong rather than merely incomplete. Either it is a new client - directory the config is missing — say so and ask — or it is personal work - that belongs in `exclude`. Never guess it into a client project. - `--json` carries the same fields if you need to compute against them. -## 2. Propose the hours +## 2. Report what was measured -**Active minutes are a floor on real work, never a measure of it.** Meetings, -review, reading, whiteboarding, and thinking leave no transcript at all. A day -showing 160 active minutes was not a two-hour day. Read the numbers as -*proportions between projects*, and get the day's length from the calendar. +**Do not extrapolate.** No fitting to an 8-hour day, no scaling a thin day up, +no rounding a dominant project to the whole day. Some days start at 06:00, +some run past midnight, and none of them are the same length. A guessed number +is worse than a small true one, because the user cannot tell it was guessed. -The scan already does the arithmetic: it splits `nominal_day_hours` (config, -default 8) across the day's mapped projects by share, in 15-minute steps. Your -job is the judgement it cannot do: +State the measured time and say plainly that it is a floor: meetings, review, +reading and thinking leave no transcript, so real hours are higher by an +amount only the user knows. They add that back — you never do. -- One project at 85% or more: round it up to the whole day rather than leaving - a token 1h on the other. -- Days flagged `under 30min, treat as empty` get nothing proposed. -- Correct the split for the two things flagged in step 1 before proposing it. +Where judgement genuinely belongs is the `flags` column: -Never scale a day *down* because its transcripts are thin. A quiet day is a -normal working day unless the user says it was not, or the timesheet already -marks it as time off or a holiday. +- **`outside HHh`** — time at 02:00 is usually an unattended run, not work. + Name it so the user can discount it; do not silently drop it. +- **`unmapped time excluded`** — a path with no rule, left out of that day. + Either it is a new client directory the config is missing, or it is personal + work belonging in `exclude`. Ask; never guess it into a client project. ## 3. Reconcile against the timesheet @@ -93,24 +86,21 @@ marks it as time off or a holiday. python3 <skill-dir>/scripts/me-api.py schedule --start YYYY-MM-DD --end YYYY-MM-DD ``` -Each day comes back either already planned (an allocation with an entry id and -planned hours) or absent. That splits the proposal in two: +Each day comes back either already planned — an allocation carrying an entry +id and planned hours — or absent, which needs a new entry instead of a +confirmation. -- **Planned and matching** — confirm at the planned hours. -- **Planned but the sessions disagree** — confirm at the observed hours, and - show both numbers in the table so the user sees what changed. -- **Not planned at all** — needs a new entry, which is a bigger claim. Flag it - separately rather than folding it in. +Show the planned hours next to the measured ones and let the user set the +number. The measured figure is almost always lower, and that gap is real work +off the keyboard, not evidence that the plan is wrong. ## 4. Show the table, then ask -One row per project per day: date, weekday, project, proposed hours, what the -timesheet says now, and the action (confirm / adjust / add / skip). Mark any +The scan's table with the timesheet's planned hours beside each cell. Mark any day that needs a new entry rather than a confirmation. -Keep it to that table plus a line for anything you had to judge — a discounted -overnight run, an unmapped path, a day you left empty. No commentary on days -that were straightforward. +Keep it to that table plus a line for anything flagged. No commentary on days +that were straightforward, and no proposed totals the user did not give you. Then ask once, plainly, whether to submit. Wait for an answer. Silence, a timeout, or "user may be away" is not approval — leave the timesheet alone and diff --git a/skills/hourlog/config.example.json b/skills/hourlog/config.example.json index d04ab00..38e410c 100644 --- a/skills/hourlog/config.example.json +++ b/skills/hourlog/config.example.json @@ -10,7 +10,6 @@ "slot_minutes": 5, "day_start_hour": 8, "day_end_hour": 20, - "nominal_day_hours": 8, "projects": [ { "name": "<project name exactly as the timesheet app shows it>", diff --git a/skills/hourlog/scripts/scan-activity.py b/skills/hourlog/scripts/scan-activity.py index 0925a0f..fdb1d7f 100755 --- a/skills/hourlog/scripts/scan-activity.py +++ b/skills/hourlog/scripts/scan-activity.py @@ -14,11 +14,16 @@ transcripts on one project counts once, and two projects worked in parallel each keep their own slots. Message counts would make one overnight autonomous run outweigh a real morning; wall-clock presence does not. -Output is one line per project per day: suggested hours, share of the day, and -the active minutes behind it. The suggestion splits a nominal working day by -share, in 15-minute steps — active minutes are a floor on real work, never a -measure of it, so the day's length comes from the calendar and only the split -between projects comes from the sessions. See SKILL.md. +Output is a markdown table: one row per day, one column per project, each cell +holding the time that project was actually active. Nothing is extrapolated and +nothing is fitted to a nominal day — some days start early, some run late, and +a guessed number is worse than a small true one. + +Measured time is a floor. Meetings, review and thinking leave no transcript, +so the user adds those back; the script never does. + +The 'total' column is wall-clock presence, the union of active slots across +projects, so on days with parallel sessions it is less than the row sum. """ import argparse import collections @@ -35,7 +40,6 @@ DEFAULTS = { "slot_minutes": 5, "day_start_hour": 8, "day_end_hour": 20, - "nominal_day_hours": 8, "projects": [], "exclude": [], } @@ -110,35 +114,14 @@ def read_session(path): return cwd, stamps -def split_day(entry, nominal_hours): - """Split a nominal working day across the day's mapped projects by share. - - Largest-remainder over 15-minute steps, so the parts add back up to the - whole day exactly. Unmapped paths get nothing: they are not known to be - client work, and silently handing them hours would hide a missing rule. - """ - for p in entry["projects"]: - p["suggested_hours"] = 0.0 - entry["thin"] = entry["total_active_minutes"] < 30 - mapped = [p for p in entry["projects"] - if not p["project"].startswith("unmapped:")] - weight = sum(p["active_minutes"] for p in mapped) - if not weight or entry["thin"]: - return - quarters = int(round(nominal_hours * 4)) - exact = [(p, quarters * p["active_minutes"] / weight) for p in mapped] - given = [(p, int(v)) for p, v in exact] - left = quarters - sum(v for _, v in given) - order = sorted(range(len(exact)), key=lambda i: -(exact[i][1] % 1)) - for i in order[:left]: - given[i] = (given[i][0], given[i][1] + 1) - for p, q in given: - p["suggested_hours"] = q / 4 - - -def fmt_hours(h): - whole, rem = int(h), round((h - int(h)) * 60) - return f"{whole}h" if not rem else f"{whole}h{rem:02d}" +def fmt_dur(minutes): + """45 -> '45min', 155 -> '2h35', 180 -> '3h', 0 -> '—'.""" + if not minutes: + return "—" + if minutes < 60: + return f"{minutes}min" + h, m = divmod(minutes, 60) + return f"{h}h" if not m else f"{h}h{m:02d}" def fmt_hour_list(hours): @@ -234,12 +217,14 @@ def main(): while d <= until: per = grid.get(d.isoformat(), {}) totals = {p: sum(len(s) for s in hrs.values()) for p, hrs in per.items()} - day_total = sum(totals.values()) + # Wall clock, not the row sum: a slot with two projects live is one + # minute of the user's day, counted once here and once per project. + union = len({s for hrs in per.values() for ss in hrs.values() + for s in ss}) entry = { "date": d.isoformat(), "weekday": d.strftime("%a"), - "total_active_minutes": day_total * mins, - "nominal_day_hours": cfg["nominal_day_hours"], + "active_minutes": union * mins, "projects": [], } for proj, n in sorted(totals.items(), key=lambda kv: -kv[1]): @@ -247,7 +232,6 @@ def main(): entry["projects"].append({ "project": proj, "active_minutes": n * mins, - "share": round(n / day_total, 3) if day_total else 0, "first_hour": hrs[0], "last_hour": hrs[-1], "outside_workday": [ @@ -255,7 +239,6 @@ def main(): if h < cfg["day_start_hour"] or h >= cfg["day_end_hour"] ], }) - split_day(entry, cfg["nominal_day_hours"]) report.append(entry) d += dt.timedelta(days=1) @@ -266,14 +249,14 @@ def main(): if a.json: json.dump({"since": since.isoformat(), "until": until.isoformat(), "slot_minutes": mins, "sessions": nfiles, - "nominal_day_hours": cfg["nominal_day_hours"], "unmapped": unmapped, "report": report}, sys.stdout, indent=1) print() return 0 print(f"{since} .. {until} — {nfiles} sessions, {mins}-min slots, " - f"{cfg['timezone']}, {cfg['nominal_day_hours']}h day") - print("hours are a suggested split of a full day, not measured time\n") + f"{cfg['timezone']}") + print("measured active time, nothing extrapolated; " + "total is wall clock, so it can be less than the row\n") cols = [p for p in dict.fromkeys( x["project"] for e in report for x in e["projects"]) @@ -282,8 +265,9 @@ def main(): print("no mapped project activity in this range") return 0 - rows = [["day"] + cols + ["total", "flags"]] + rows = [["day"] + cols + ["total", "window", "flags"]] week = collections.Counter() + week_total = 0 for e in report: if not e["projects"]: continue @@ -291,26 +275,24 @@ def main(): cells = [] for c in cols: p = by.get(c) - cells.append("—" if not p or not p["suggested_hours"] else - f"{fmt_hours(p['suggested_hours'])} · " - f"{p['share']*100:.0f}% · {p['active_minutes']}min") + cells.append(fmt_dur(p["active_minutes"]) if p else "—") if p: - week[c] += p["suggested_hours"] - day_sum = sum(by[c]["suggested_hours"] for c in cols if c in by) + week[c] += p["active_minutes"] + week_total += e["active_minutes"] + hrs = [h for p in e["projects"] for h in (p["first_hour"], p["last_hour"])] + window = f"{min(hrs):02d}-{max(hrs):02d}h" if hrs else "" flags = [] - if e["thin"]: - flags.append("under 30min, treat as empty") outside = sorted({h for p in e["projects"] for h in p["outside_workday"]}) if outside: flags.append("outside " + fmt_hour_list(outside)) if any(p["project"].startswith("unmapped:") for p in e["projects"]): flags.append("unmapped time excluded") rows.append([f"{e['date']} {e['weekday']}"] + cells + - [fmt_hours(day_sum) if day_sum else "—", "; ".join(flags)]) + [fmt_dur(e["active_minutes"]), window, "; ".join(flags)]) rows.append(["**total**"] + - [f"**{fmt_hours(week[c])}**" for c in cols] + - [f"**{fmt_hours(sum(week.values()))}**", ""]) + [f"**{fmt_dur(week[c])}**" for c in cols] + + [f"**{fmt_dur(week_total)}**", "", ""]) right = set(range(1, len(cols) + 2)) print(md_table(rows, align_right=right)) From b485cee634e19310983b7345cb9230bae0ed2b89 Mon Sep 17 00:00:00 2001 From: naps62 <naps62@users.noreply.github.com> Date: Fri, 14 Aug 2026 22:05:13 +0000 Subject: [PATCH 11/12] feat: split overlapping minutes between projects Five minutes with two projects open was counted as five for each, so Wednesday's columns summed to 18h against 13h10 of wall clock and no column said which number to trust. Each slot's minutes are now divided evenly among the projects live in it, largest remainder over whole minutes, so the columns add up to the total exactly. That ratio is what a submission scales the user's stated day length by. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --- skills/hourlog/SKILL.md | 9 ++++-- skills/hourlog/scripts/scan-activity.py | 43 ++++++++++++++++++------- 2 files changed, 39 insertions(+), 13 deletions(-) diff --git a/skills/hourlog/SKILL.md b/skills/hourlog/SKILL.md index ebc8b45..4800510 100644 --- a/skills/hourlog/SKILL.md +++ b/skills/hourlog/SKILL.md @@ -48,8 +48,13 @@ time that project was actually active, plus wall-clock `total`, the day's `window`, and `flags`. That table is the deliverable — paste it as-is rather than restating it in prose. -`total` is the union of active slots, so on a day with parallel sessions it is -less than the row sum. Both numbers are true; they answer different questions. +Overlap is divided, not double-counted: five minutes with two projects open is +five minutes of the day, half to each. The project columns therefore add up to +`total`, which is wall-clock presence. + +That division is also the ratio to submit with. The user gives the day's real +total; you split it by these proportions. Never submit the measured numbers as +the hours unless the user says they are right. Paste it as plain markdown in the reply. Never wrap it in a code fence: a fence shows the raw pipes and dashes instead of a rendered table. diff --git a/skills/hourlog/scripts/scan-activity.py b/skills/hourlog/scripts/scan-activity.py index fdb1d7f..73de70a 100755 --- a/skills/hourlog/scripts/scan-activity.py +++ b/skills/hourlog/scripts/scan-activity.py @@ -22,8 +22,9 @@ a guessed number is worse than a small true one. Measured time is a floor. Meetings, review and thinking leave no transcript, so the user adds those back; the script never does. -The 'total' column is wall-clock presence, the union of active slots across -projects, so on days with parallel sessions it is less than the row sum. +Overlap is divided, not double-counted: five minutes with two projects open is +five minutes of the day, half to each. So the project columns add up to the +'total' column, which is wall-clock presence. """ import argparse import collections @@ -114,6 +115,21 @@ def read_session(path): return cwd, stamps +def attribute(slots_of, owners, mins): + """Divide each slot's minutes evenly among the projects live in it. + + Five minutes with two projects open is five minutes of the user's day, not + ten, so each project gets half. Largest remainder over whole minutes keeps + the parts summing to wall clock exactly. + """ + exact = {p: sum(mins / owners[s] for s in ss) for p, ss in slots_of.items()} + floors = {p: int(v) for p, v in exact.items()} + left = round(sum(exact.values())) - sum(floors.values()) + for p in sorted(exact, key=lambda p: -(exact[p] - floors[p]))[:left]: + floors[p] += 1 + return floors + + def fmt_dur(minutes): """45 -> '45min', 155 -> '2h35', 180 -> '3h', 0 -> '—'.""" if not minutes: @@ -216,22 +232,27 @@ def main(): d = since while d <= until: per = grid.get(d.isoformat(), {}) - totals = {p: sum(len(s) for s in hrs.values()) for p, hrs in per.items()} - # Wall clock, not the row sum: a slot with two projects live is one - # minute of the user's day, counted once here and once per project. - union = len({s for hrs in per.values() for ss in hrs.values() - for s in ss}) + slots_of = {p: {s for ss in hrs.values() for s in ss} + for p, hrs in per.items() + if not p.startswith("unmapped:")} + owners = collections.Counter() + for ss in slots_of.values(): + owners.update(ss) + share = attribute(slots_of, owners, mins) entry = { "date": d.isoformat(), "weekday": d.strftime("%a"), - "active_minutes": union * mins, + "active_minutes": len(owners) * mins, "projects": [], } - for proj, n in sorted(totals.items(), key=lambda kv: -kv[1]): + raw = {p: sum(len(s) for s in hrs.values()) * mins + for p, hrs in per.items()} + for proj in sorted(per, key=lambda p: -raw[p]): hrs = sorted(per[proj]) entry["projects"].append({ "project": proj, - "active_minutes": n * mins, + "active_minutes": share.get(proj, raw[proj]), + "raw_minutes": raw[proj], "first_hour": hrs[0], "last_hour": hrs[-1], "outside_workday": [ @@ -256,7 +277,7 @@ def main(): print(f"{since} .. {until} — {nfiles} sessions, {mins}-min slots, " f"{cfg['timezone']}") print("measured active time, nothing extrapolated; " - "total is wall clock, so it can be less than the row\n") + "overlapping minutes split evenly between projects\n") cols = [p for p in dict.fromkeys( x["project"] for e in report for x in e["projects"]) From 5792d6454b6a4147bb55c6fcaa630e70a4158e5d Mon Sep 17 00:00:00 2001 From: naps62 <naps62@users.noreply.github.com> Date: Fri, 14 Aug 2026 22:11:06 +0000 Subject: [PATCH 12/12] docs: tighten hourlog, add the confirmed-entry check Scan and report had grown into two sections saying the same thing, and step 4 repeated step 1's "show the table". Down to four steps. Adds what nearly went wrong on the first real run: a day already confirmed weeks ago looks identical to a planned one in a bulk approval, and overwriting it needs its own yes. Also records the 15-minute rounding the app enforces, and the ${VAR:-x} expansion that prints a token instead of hiding it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --- skills/hourlog/SKILL.md | 135 ++++++++++++++++++---------------------- 1 file changed, 61 insertions(+), 74 deletions(-) diff --git a/skills/hourlog/SKILL.md b/skills/hourlog/SKILL.md index 4800510..bb1736a 100644 --- a/skills/hourlog/SKILL.md +++ b/skills/hourlog/SKILL.md @@ -9,126 +9,113 @@ allowed-tools: - Glob - Bash - Edit - - Write --- # Hour log -Report how long each client project was actually active on each day, check -that against the timesheet, and submit only the hours the user gives you. +Report how long each client project was active on each day, check that against +the timesheet, and submit only the hours the user gives you. The timesheet is a company record. Nothing is written to it without the user saying go, in this session, after seeing the table. An unattended run stops at -the proposal. +the table. ## Setup (once per machine) -Three things must exist. Check them before anything else and stop with the -missing step if not. +Check all three before anything else; stop with the missing step if not. -1. `~/.config/hourlog/projects.json` — path prefix to project mapping. Copy - `<skill-dir>/config.example.json` and fill it in. **Never commit a filled - config, and never put a project, client, or host name in this repo** — it - is public. +1. `~/.config/hourlog/projects.json` — path prefix to project mapping, copied + from `<skill-dir>/config.example.json`. **Never commit a filled config, and + never put a project, client, or host name in this repo** — it is public. 2. `HOURLOG_API` and `HOURLOG_TOKEN` in `~/.env.claude`. The token is a - personal access token from the timesheet app's profile page. Scopes: - `profile:read`, `schedule:read`, and `schedule:write` only if submitting. - Never echo the token. -3. Project names in the config must match the app exactly. Verify with + personal access token from the timesheet app's profile page: `profile:read`, + `schedule:read`, and `schedule:write` only if submitting. Never echo it — + `${VAR:-x}` prints the value when the variable is set; use `${VAR:+set}`. +3. Config project names must match the app exactly. Verify with `me-api.py projects` and fix the config, not the app. -## 1. Scan the sessions +## 1. Scan ```sh python3 <skill-dir>/scripts/scan-activity.py --week last ``` -Prints a markdown table: one row per day, one column per project holding the -time that project was actually active, plus wall-clock `total`, the day's -`window`, and `flags`. That table is the deliverable — paste it as-is rather -than restating it in prose. +A markdown table, one row per day, one column per project. Paste it into the +reply as plain markdown — never in a code fence, which shows raw pipes instead +of a rendered table — and don't restate it in prose. -Overlap is divided, not double-counted: five minutes with two projects open is -five minutes of the day, half to each. The project columns therefore add up to -`total`, which is wall-clock presence. +What the numbers mean, and their limits: -That division is also the ratio to submit with. The user gives the day's real -total; you split it by these proportions. Never submit the measured numbers as -the hours unless the user says they are right. +- The unit is a 5-minute slot containing at least one message, deduplicated + per project, so a 40-subagent swarm counts once. Overlapping minutes are + split evenly between the projects live in them, so the columns add up to + `total`, which is wall-clock presence. +- **Measured time is a floor, never a total.** Meetings, review, reading and + thinking leave no transcript. Say so; the user adds them back. +- **Do not extrapolate.** No fitting to an 8-hour day, no scaling a thin day + up, no rounding a dominant project to the whole day. Days start at 06:00 and + run past midnight, and a guessed number is worse than a small true one + because the user cannot tell it was guessed. -Paste it as plain markdown in the reply. Never wrap it in a code fence: a -fence shows the raw pipes and dashes instead of a rendered table. - -The unit behind it is a 5-minute slot in which at least one message was -written, deduplicated per project — so a 40-subagent swarm on one project -counts once, and two projects worked in parallel each keep their own slots. -Message counts would let one overnight autonomous run outweigh a real morning. - -`--json` carries the same fields if you need to compute against them. - -## 2. Report what was measured - -**Do not extrapolate.** No fitting to an 8-hour day, no scaling a thin day up, -no rounding a dominant project to the whole day. Some days start at 06:00, -some run past midnight, and none of them are the same length. A guessed number -is worse than a small true one, because the user cannot tell it was guessed. - -State the measured time and say plainly that it is a floor: meetings, review, -reading and thinking leave no transcript, so real hours are higher by an -amount only the user knows. They add that back — you never do. - -Where judgement genuinely belongs is the `flags` column: +Two flags need a judgement call: - **`outside HHh`** — time at 02:00 is usually an unattended run, not work. - Name it so the user can discount it; do not silently drop it. + Name it so the user can discount it; never silently drop it. - **`unmapped time excluded`** — a path with no rule, left out of that day. - Either it is a new client directory the config is missing, or it is personal - work belonging in `exclude`. Ask; never guess it into a client project. + Either a client directory the config is missing, or personal work belonging + in `exclude`. Ask; never guess it into a client project. -## 3. Reconcile against the timesheet +`--json` carries the same fields for computing against. + +## 2. Reconcile ```sh python3 <skill-dir>/scripts/me-api.py schedule --start YYYY-MM-DD --end YYYY-MM-DD ``` -Each day comes back either already planned — an allocation carrying an entry -id and planned hours — or absent, which needs a new entry instead of a +Each day is either planned — an allocation carrying an entry id, planned +hours, and a status — or absent, which needs a new entry rather than a confirmation. -Show the planned hours next to the measured ones and let the user set the -number. The measured figure is almost always lower, and that gap is real work -off the keyboard, not evidence that the plan is wrong. +**Check the status of every entry before proposing a value.** `planned` with +`actual_hours: null` is untouched and safe to fill. `confirmed` or `edited` +means the user already set that number, possibly weeks ago. Overwriting one is +a separate decision: show the current value against the proposed value, say +which day it is, and get a specific yes for that entry. Do not fold it into a +bulk approval. -## 4. Show the table, then ask +Show planned hours beside measured ones and let the user set the number. The +measured figure is almost always lower, and that gap is work off the keyboard, +not evidence the plan is wrong. -The scan's table with the timesheet's planned hours beside each cell. Mark any -day that needs a new entry rather than a confirmation. +## 3. Ask -Keep it to that table plus a line for anything flagged. No commentary on days -that were straightforward, and no proposed totals the user did not give you. +The table, plus one line for anything flagged. No commentary on days that were +straightforward, and no totals the user did not give you. -Then ask once, plainly, whether to submit. Wait for an answer. Silence, a -timeout, or "user may be away" is not approval — leave the timesheet alone and -say the run is waiting. +Then ask once, plainly, whether to submit. Wait. Silence, a timeout, or "user +may be away" is not approval — leave the timesheet alone and say the run is +waiting. -## 5. Submit what was approved +## 4. Submit ```sh # confirm a planned day -python3 <skill-dir>/scripts/me-api.py confirm --entry ID --hours 8 --dry-run +python3 <skill-dir>/scripts/me-api.py confirm --entry ID --hours 5.25 --dry-run # log a day with no allocation -python3 <skill-dir>/scripts/me-api.py log --project ID --dates D,D --hours 8 --dry-run +python3 <skill-dir>/scripts/me-api.py log --project ID --dates D,D --hours 4 --dry-run ``` +Hours are decimal and the app enforces 15-minute steps, so round to a multiple +of 0.25 before sending. When the user gives a day's total rather than +per-project numbers, split it by the measured proportions. + Run every write with `--dry-run` first and show the requests. Drop the flag -only for the rows the user approved — not the whole table, if they approved -part of it. +only for the rows approved — not the whole table, if they approved part of it. -A `423` means the period is locked and ops has to reopen it. Report it and -move on; it is not a failure to retry. - -Re-read the schedule afterwards and confirm what landed. Report the diff, not -an assumption. +A `423` means the period is locked and ops has to reopen it; report it and move +on. Re-read the schedule afterwards and report what actually landed, not what +was sent. ## Scope