ckb/.agents/skills/ckb-lint/scripts/session_start.py
Michał Kopeć bf2cc8e8aa Template 1.23.0: agent-knowledge release 2, schema 1.6
Schema 1.6, all fields optional (D-0014):
- F7 review: `review: draft|reviewed|needs_update`, `reviewed_by`,
  `reviewed_on`; lint check 17 and a review queue; ckb-lint marks reviews
- F4 `> CONTRADICTION:` marker, lint check 18; validity dates deferred
- F21 `tags` against the new `wiki/tags.md`, lint check 19,
  retrieve_candidates.py --tag, DRAFT/NEEDS_UPDATE flags
- F9 profiles in workload/profiles/, protected `## Rules` on project
  scope pages, precedence AGENTS.md > Rules > profile
- F8 explicit lessons (profile or wiki/lessons.md); new ckb-profile skill

Carry-over: `.secrets-allow` `<glob> match:<hash>` entries (also in the
bash/PowerShell fallbacks); open threads no longer print twice.
ckb-upgrade migrates 1.5 -> 1.6; init/reset know tags.md; Starlight
shows review and tags. Smoke test covers a 1.6 KB. Docs in EN and PL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 20:06:02 +01:00

379 lines
16 KiB
Python

#!/usr/bin/env python3
"""Rule E in one call: everything the agent checks at session start, printed
as one short block so the prompt does not have to describe five commands.
session_start.py [--title "..."] [--root DIR] [--today YYYY-MM-DD] [--no-git]
session_start.py --hook # Claude Code SessionStart hook: hook JSON in, additionalContext out
What it prints, one line each (plus the tail of the latest workload note):
identity: Name <email> the git identity, or the OS user with a hint
title: <title> (set | kept | none) --title stores it unless one is already stored
announce: yes | no conversations.announce_title in ckb.yaml
git: <branch line>, N changed, M untracked -> "suggest ckb-sync-changes" when any
ckb check: clean | <counts> lint_report.py --quick -> "suggest ckb-lint"
autosave: ... autosave_hook.py --check, only when it needs action
start hook: ... start_hook.py --check, only when it needs action
routines: none due | DUE <name>: ... routines.py --due, one line per due routine
threads: N open ... unticked `- [ ]` under "Open threads" in workload/ notes; only when any
profile: workload/profiles/<slug>.md the session identity's own profile, printed; only when it exists
lessons: N new in wiki/lessons.md KB lessons dated after your previous workload note; only when any
workload: <file> (last block follows) latest workload/ note by filename date
Exit 0 unless the repo root is not a KB. Python 3.8+, standard library only.
The scripts it wraps keep their own single-purpose interfaces; this one only
sequences them so a session start costs one tool call instead of five.
"""
import argparse
import getpass
import json
import os
import re
import subprocess
import sys
import unicodedata
from datetime import date, datetime
from pathlib import Path
HERE = Path(__file__).resolve().parent
SKILLS = HERE.parent.parent
LINT = HERE / "lint_report.py"
SAVE = SKILLS / "ckb-add-conversation" / "scripts" / "save_conversation.py"
AUTOSAVE = SKILLS / "ckb-add-conversation" / "scripts" / "autosave_hook.py"
ROUTINES = SKILLS / "ckb-routine" / "scripts" / "routines.py"
START_HOOK = HERE / "start_hook.py"
TITLES_DIR = Path("tmp") / "conversation-titles"
WORKLOAD_TAIL_LINES = 40
OPEN_THREADS_RE = re.compile(r"^#{2,4}\s+Open threads\s*$", re.I)
THREAD_RE = re.compile(r"^\s*[-*]\s+\[ \]\s+(\S.*?)\s*$")
THREADS_SHOWN = 5
THREAD_STALE_DAYS = 30
SET_TITLE = ".agents/skills/ckb-add-conversation/scripts/save_conversation.py --set-title"
PROFILE_LINES = 40
LESSON_RE = re.compile(r"^###\s+(\d{4}-\d{2}-\d{2})\s+[—-]\s+(.+?)\s*$", re.M)
# Letters NFKD does not split into base + accent (Rule D: `Michał Kopeć` -> `michal-kopec`).
SLUG_MAP = str.maketrans({"ł": "l", "Ł": "L", "ø": "o", "Ø": "O", "đ": "d", "Đ": "D",
"ß": "ss", "æ": "ae", "Æ": "AE", "œ": "oe", "Œ": "OE"})
def run(cmd, cwd):
try:
p = subprocess.run(cmd, cwd=str(cwd), capture_output=True, text=True, timeout=120)
return p.returncode, (p.stdout or "").strip(), (p.stderr or "").strip()
except (OSError, subprocess.SubprocessError) as e:
return 127, "", str(e)
def py(script, args, cwd):
if not script.is_file():
return 127, "", f"{script} missing"
return run([sys.executable, "-I", str(script)] + args, cwd)
# ---------------------------------------------------------------- pieces
def identity(root):
name = run(["git", "config", "user.name"], root)[1]
email = run(["git", "config", "user.email"], root)[1]
if name or email:
return f"{name} <{email}>" if name and email else (name or email)
user = os.environ.get("USER") or os.environ.get("USERNAME") or getpass.getuser()
return f"{user} (OS user; git identity unset — set git config --global user.name / user.email)"
def author_slug(root):
"""The Rule D slug of the session identity's name, or None."""
name = run(["git", "config", "user.name"], root)[1] or os.environ.get("USER") or os.environ.get("USERNAME") or ""
ascii_name = unicodedata.normalize("NFKD", name.translate(SLUG_MAP)).encode("ascii", "ignore").decode()
return re.sub(r"[^a-z0-9]+", "-", ascii_name.lower()).strip("-") or None
def yaml_flag(root, block, key, default):
"""Minimal reader for `block:\\n key: value` in ckb.yaml; no YAML parser."""
path = root / "ckb.yaml"
if not path.exists():
return default
in_block = False
for raw in path.read_text(encoding="utf-8").splitlines():
line = raw.split("#", 1)[0].rstrip()
if not line.strip():
continue
if not line.startswith((" ", "\t")):
in_block = line.strip() == f"{block}:"
continue
if in_block and line.strip().startswith(f"{key}:"):
return line.split(":", 1)[1].strip().lower() in ("true", "yes", "on")
return default
def stored_title(root, session_id=None):
"""The title already stored for this session (by id), or for the newest
session of this project, if any."""
sys.path.insert(0, str(SAVE.parent))
try:
import save_conversation as sc # noqa: E402
except Exception:
return None
finally:
sys.path.pop(0)
try:
if session_id:
return sc.stored_title(root, session_id)
pdir = sc.project_dir_for(root)
sessions = sc.list_sessions(pdir) if pdir.is_dir() else []
if not sessions:
return None
return sc.stored_title(root, sessions[0]["id"])
except Exception:
return None
def title_line(root, wanted):
current = stored_title(root)
if wanted and wanted.strip():
if current:
return f"title: {current} (kept — already set this session)"
code, out, err = py(SAVE, ["--set-title", wanted.strip()], root)
if code == 0:
return f"title: {wanted.strip()} (set)"
return f"title: {wanted.strip()} (NOT stored: {err or out or code})"
return f"title: {current} (kept)" if current else "title: none (pass --title on a new session)"
def git_line(root):
code, out, _ = run(["git", "status", "--short", "--branch"], root)
if code != 0:
return "git: not a git repository", False
lines = out.splitlines()
branch = lines[0].lstrip("# ").strip() if lines else "?"
rest = lines[1:]
untracked = sum(1 for l in rest if l.startswith("??"))
changed = len(rest) - untracked
unsynced = "ahead" in branch or "behind" in branch or changed or untracked
parts = [branch]
if changed:
parts.append(f"{changed} changed")
if untracked:
parts.append(f"{untracked} untracked")
line = "git: " + ", ".join(parts)
if unsynced:
line += " -> suggest ckb-sync-changes"
return line, bool(unsynced)
def lint_line(root, today):
args = ["--quick"] + (["--today", today] if today else [])
code, out, err = py(LINT, args, root)
if code == 127:
return f"ckb check: unavailable ({err})"
# A crash prints a traceback to stderr; its last line names the error and keeps the block short.
tail = (out or err).strip().splitlines()
line = tail[-1] if tail else "ckb check: (no output)"
if not out.strip() and err.strip():
line = f"ckb check: failed ({line})"
return line + (" -> suggest ckb-lint" if code != 0 else "")
def autosave_line(root):
auto = yaml_flag(root, "conversations", "autosave", False)
hook = (root / ".claude" / "settings.local.json").exists()
if not auto and not hook:
return None # Rule E: skip entirely
code, out, err = py(AUTOSAVE, ["--check"], root)
if code == 0:
return None # consistent: stay quiet
return f"autosave: {out or err} -> ask once before changing .claude/settings.local.json"
def start_hook_line(root):
on = yaml_flag(root, "session", "start_hook", False)
if not on and not (root / ".claude" / "settings.local.json").exists():
return None
code, out, err = py(START_HOOK, ["--check"], root)
if code == 0:
return None
return f"start hook: {out or err} -> ask once before changing .claude/settings.local.json"
def routines_lines(root, today):
if not ROUTINES.is_file() or not (root / "ckb.yaml").exists():
return ["routines: none due"]
args = ["--due"] + (["--today", today] if today else [])
code, out, err = py(ROUTINES, args, root)
if code == 0:
return ["routines: none due"]
if code == 1 and out:
lines = out.splitlines()
return ["routines: DUE " + lines[0]] + [" DUE " + l for l in lines[1:]] + \
[" -> finish the user's request, then run each (ckb-routine)"]
return [f"routines: check failed ({err or out or code})"]
def open_threads(root):
"""[(date, note, text)] for every unticked `- [ ]` bullet under an
"Open threads" heading in a top-level workload/ note, oldest first.
A thread is closed where it was opened: `- [x]`, or `- [x] dropped: why`."""
wdir = root / "workload"
found = []
for f in sorted(wdir.glob("*.md")) if wdir.is_dir() else []:
m = re.match(r"(\d{4}-\d{2}-\d{2})", f.name)
if not m:
continue
opened = datetime.strptime(m.group(1), "%Y-%m-%d").date()
in_section = False
for line in f.read_text(encoding="utf-8", errors="replace").splitlines():
if line.startswith("#"):
in_section = bool(OPEN_THREADS_RE.match(line))
continue
t = THREAD_RE.match(line) if in_section else None
if t:
found.append((opened, f, t.group(1)))
return sorted(found, key=lambda x: (x[0], x[1].name))
def threads_lines(root, today):
threads = open_threads(root)
if not threads:
return []
out = [f"threads: {len(threads)} open in workload/ notes, oldest first"
" -> mention them; close one by ticking it where it was opened"]
for opened, note, text in threads[:THREADS_SHOWN]:
age = (today - opened).days
stale = f", {age}d old — still open?" if age > THREAD_STALE_DAYS else ""
out.append(f" - [ ] {text} ({note.name}{stale})")
if len(threads) > THREADS_SHOWN:
out.append(f" … {len(threads) - THREADS_SHOWN} more: grep -n -- '- \\[ \\]' workload/*.md")
return out
def strip_frontmatter(text):
if text.startswith("---\n"):
end = text.find("\n---\n", 4)
if end != -1:
return text[end + 5:]
return text
def profile_lines(root, slug):
"""The session identity's profile, printed so it is in context; nothing when absent."""
path = root / "workload" / "profiles" / f"{slug}.md" if slug else None
if not path or not path.is_file():
return []
body = [l for l in strip_frontmatter(path.read_text(encoding="utf-8", errors="replace")).strip().splitlines()]
if len(body) > PROFILE_LINES:
body = body[:PROFILE_LINES] + [f"… (rest in {path.relative_to(root).as_posix()})"]
return [f"profile: {path.relative_to(root).as_posix()} — yours; follow it where AGENTS.md and "
"project rules leave room"] + [" " + l if l else "" for l in body]
def lessons_lines(root, slug, today):
"""KB lessons dated after this person's previous workload note (all of them
on a first session), so a lesson someone else recorded is not missed."""
path = root / "wiki" / "lessons.md"
if not path.is_file():
return []
lessons = LESSON_RE.findall(path.read_text(encoding="utf-8", errors="replace"))
prev = None
if slug and (root / "workload").is_dir():
dates = [f.name[:10] for f in (root / "workload").glob(f"*_{slug}_summary.md") if f.name[:10] < today.isoformat()]
prev = max(dates) if dates else None
new = [(d, t) for d, t in lessons if prev is None or d > prev]
if not new:
return []
since = f"since your note of {prev}" if prev else "— first session here"
out = [f"lessons: {len(new)} in wiki/lessons.md {since} -> read the ones that bear on this session"]
out += [f" - {d} — {t}" for d, t in new[-THREADS_SHOWN:]]
return out
def latest_workload(root):
"""Newest workload note by the date prefix of its filename, any author;
ties broken by modification time. Returns (path, last block) or (None, '')."""
wdir = root / "workload"
if not wdir.is_dir():
return None, ""
files = [f for f in wdir.glob("*.md") if re.match(r"\d{4}-\d{2}-\d{2}", f.name)]
if not files:
return None, ""
files.sort(key=lambda f: (f.name[:10], f.stat().st_mtime))
latest = files[-1]
text = latest.read_text(encoding="utf-8", errors="replace")
blocks = re.split(r"(?m)^(?=## )", text)
block = blocks[-1].rstrip() if len(blocks) > 1 else text.rstrip()
# Open threads already print on the `threads:` line; don't show them twice.
block = re.sub(r"(?ms)^#{2,4}\s+Open threads\s*$.*?(?=^#|\Z)", "", block).rstrip()
lines = block.splitlines()
if len(lines) > WORKLOAD_TAIL_LINES:
lines = lines[:WORKLOAD_TAIL_LINES] + ["…"]
return latest, "\n".join(lines)
# ---------------------------------------------------------------- main
def brief(root, a, hook=None):
"""The session-start block as lines. `hook` is the SessionStart hook's
input JSON when called as a hook, else None."""
today = datetime.strptime(a.today, "%Y-%m-%d").date() if a.today else date.today()
announce = yaml_flag(root, "conversations", "announce_title", True)
if hook is None:
out = [f"identity: {identity(root)}", title_line(root, a.title)]
else:
current = stored_title(root, hook.get("session_id"))
out = [f"identity: {identity(root)}",
f"title: {current} (kept)" if current else
f"title: none — choose one and store it: <python> {SET_TITLE} \"<title>\""]
# Re-injected after a compaction, or on a resume: the title was already announced.
if hook.get("source") in ("compact", "resume"):
announce = False
out.append(f"announce: {'yes' if announce else 'no'}")
if not a.no_git:
out.append(git_line(root)[0])
out.append(lint_line(root, a.today))
for extra in (autosave_line(root), start_hook_line(root)):
if extra:
out.append(extra)
out.extend(routines_lines(root, a.today))
out.extend(threads_lines(root, today))
slug = author_slug(root)
out.extend(profile_lines(root, slug))
out.extend(lessons_lines(root, slug, today))
path, block = latest_workload(root)
if path:
out.append(f"workload: {path.relative_to(root).as_posix()} — last block:")
out.append(block)
else:
out.append("workload: none yet")
return out
def main(argv=None):
ap = argparse.ArgumentParser(description="Rule E session-start checks in one call.")
ap.add_argument("--title", help="store this title for the session unless one is already stored")
ap.add_argument("--root", default=".", help="KB root (default: current directory)")
ap.add_argument("--today", help="override today's date, YYYY-MM-DD (tests)")
ap.add_argument("--no-git", action="store_true", help="skip the git status line (tests)")
ap.add_argument("--hook", action="store_true",
help="run as a Claude Code SessionStart hook: read hook JSON on stdin, print additionalContext JSON")
a = ap.parse_args(argv)
root = Path(a.root).resolve()
if a.today and not re.fullmatch(r"\d{4}-\d{2}-\d{2}", a.today):
sys.exit("error: --today must be YYYY-MM-DD")
if not (root / "wiki").is_dir():
sys.exit(f"error: {root} has no wiki/ — not a Cascade KB root")
if not a.hook:
print("\n".join(brief(root, a)))
return 0
try:
hook = json.loads(sys.stdin.read() or "{}")
except ValueError:
hook = {}
source = hook.get("source", "startup")
text = "\n".join([f"ckb session brief (SessionStart hook, {source}) — Rule E already ran; "
"act on these lines and do not run session_start.py again"] + brief(root, a, hook))
print(json.dumps({"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": text}}))
return 0
if __name__ == "__main__":
sys.exit(main())