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..9d860e5 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 @@ -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 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. + +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` | 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/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..bb1736a --- /dev/null +++ b/skills/hourlog/SKILL.md @@ -0,0 +1,123 @@ +--- +name: hourlog +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: + - Read + - Grep + - Glob + - Bash + - Edit +--- + +# Hour log + +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 table. + +## Setup (once per machine) + +Check all three before anything else; stop with the missing step if not. + +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: `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 + +```sh +python3 <skill-dir>/scripts/scan-activity.py --week last +``` + +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. + +What the numbers mean, and their limits: + +- 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. + +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; never silently drop it. +- **`unmapped time excluded`** — a path with no rule, left out of that day. + Either a client directory the config is missing, or personal work belonging + in `exclude`. Ask; never guess it into a client project. + +`--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 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. + +**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. + +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. + +## 3. Ask + +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. Silence, a timeout, or "user +may be away" is not approval — leave the timesheet alone and say the run is +waiting. + +## 4. Submit + +```sh +# confirm a planned day +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 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 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. Re-read the schedule afterwards and report what actually landed, not what +was sent. + +## Scope + +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 new file mode 100644 index 0000000..38e410c --- /dev/null +++ b/skills/hourlog/config.example.json @@ -0,0 +1,27 @@ +{ + "_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", + "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..73de70a --- /dev/null +++ b/skills/hourlog/scripts/scan-activity.py @@ -0,0 +1,328 @@ +#!/usr/bin/env python3 +"""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 + +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, 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 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. + +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 +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", + "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-3-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 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: + 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): + """[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") + 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 + + # 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), + (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 + hit = False + 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 + hit = True + grid[t.date().isoformat()][proj][t.hour].add( + int(t.timestamp()) // slot) + nfiles += hit + del stamps + + mins = cfg["slot_minutes"] + report = [] + d = since + while d <= until: + per = grid.get(d.isoformat(), {}) + 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": len(owners) * mins, + "projects": [], + } + 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": share.get(proj, raw[proj]), + "raw_minutes": raw[proj], + "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"] + ], + }) + 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']}") + print("measured active time, nothing extrapolated; " + "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"]) + if not p.startswith("unmapped:")] + if not cols: + print("no mapped project activity in this range") + return 0 + + rows = [["day"] + cols + ["total", "window", "flags"]] + week = collections.Counter() + week_total = 0 + for e in report: + if not e["projects"]: + continue + by = {p["project"]: p for p in e["projects"]} + cells = [] + for c in cols: + p = by.get(c) + cells.append(fmt_dur(p["active_minutes"]) if p else "—") + if p: + 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 = [] + 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_dur(e["active_minutes"]), window, "; ".join(flags)]) + + rows.append(["**total**"] + + [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)) + + if unmapped: + print("\nunmapped 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..3542d59 --- /dev/null +++ b/systemd/hourlog.timer @@ -0,0 +1,11 @@ +[Unit] +Description=Friday hour log, 18:00 Europe/Lisbon + +[Timer] +# 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 + +[Install] +WantedBy=timers.target