diff --git a/.agents/skills/ckb-add-conversation/SKILL.md b/.agents/skills/ckb-add-conversation/SKILL.md index 27c9412..9d071f0 100644 --- a/.agents/skills/ckb-add-conversation/SKILL.md +++ b/.agents/skills/ckb-add-conversation/SKILL.md @@ -1,6 +1,6 @@ --- name: ckb-add-conversation -description: Save the current Claude Code conversation (or an earlier session of this project) verbatim into raw/saved-conversations// as the original JSONL plus a readable Markdown rendering, and search those saved conversations when asked what was discussed or instructed before. Saved conversations never enter retrieval or the wiki on their own. Use for "save this conversation", "save the chat", "archive this session", "keep a copy of our talk", for "did we discuss X", "what did I tell you about X", "what did I ask you to do about Y last time", "find the conversation where ...", and for toggling the autosave switch: "save conversations automatically", "turn on/off conversation autosave", "stop saving every conversation". +description: Save the current Claude Code conversation (or an earlier session of this project) verbatim into raw/saved-conversations// as the original JSONL plus a readable Markdown rendering, and search those saved conversations when asked what was discussed or instructed before. Saved conversations never enter retrieval or the wiki on their own. Use for "save this conversation", "save the chat", "archive this session", "keep a copy of our talk", for "did we discuss X", "what did I tell you about X", "what did I ask you to do about Y last time", "find the conversation where ...", and for naming a session ("rename this conversation to X", "call this session X") and the session-start title question, and for toggling the switches: "save conversations automatically", "turn on/off conversation autosave", "stop saving every conversation", "stop asking for a title", "ask me for a title again". --- # Add conversation skill @@ -74,7 +74,7 @@ Markdown but remain in the JSONL copy. ```bash .agents/skills/ckb-add-conversation/scripts/save_conversation.py # current session .agents/skills/ckb-add-conversation/scripts/save_conversation.py --session - .agents/skills/ckb-add-conversation/scripts/save_conversation.py --title "Short name" # override the derived title + .agents/skills/ckb-add-conversation/scripts/save_conversation.py --title "Short name" # override the title for this save only ``` The script writes, under `raw/saved-conversations//`: @@ -91,9 +91,13 @@ The script writes, under `raw/saved-conversations//`: and updates `raw/saved-conversations/index.md` (one row per session, newest first; re-saving a session that continued replaces its files and its row). -The slug comes from Claude Code's own session title when present, otherwise -from the first user line. `--author "Name "` overrides the git -identity. `--dry-run` shows the paths without writing. +The title, and so the slug, is the first of: `--title`; the title stored +for the session by `--set-title` (see below); Claude Code's own title for +the session (`/rename`, else its AI title); the first user line. Re-saving a +session under a changed title replaces the earlier pair of files for that +session in the same day folder, so a rename never leaves orphans. +`--author "Name "` overrides the git identity. `--dry-run` shows the +paths without writing. ### Step 4 — Report and log @@ -124,6 +128,29 @@ with the header the script would write, see `INDEX_HEADER` in the script). Tell the user once that the readable `.md` can be produced later by re-running the script with `--from ` once Python is available. +## Naming a session + +Rule E asks for the conversation's title as the first thing in a new +session. The answer is stored per machine so the Stop hook and every later +save pick it up: + +```bash + .agents/skills/ckb-add-conversation/scripts/save_conversation.py --set-title "Billing cut-over plan" + .agents/skills/ckb-add-conversation/scripts/save_conversation.py --set-title "..." --session # an earlier session +``` + +It writes `tmp/conversation-titles/.title` (gitignored, like +the hook that reads it) and exits without saving. The same command serves +"rename this conversation to X" mid-session; if a copy of the session was +already saved today, save again so the files and index row follow the new +name. The title also heads the session's block in the workload note. + +The question itself is controlled by `conversations.ask_title` (default +`true`; absent means `true`). "Stop asking for a title" / "ask me for a +title again" flips it the same way as autosave below — change only that +key. With it off, titles come from Claude Code's own session title or the +first user line, as before 1.16.0. + ## The autosave switch `ckb.yaml` carries: @@ -131,6 +158,7 @@ the script with `--from ` once Python is available. ```yaml conversations: autosave: false # true: save every session's transcript at session end without asking + ask_title: true # true: the first reply of every session asks what to call the conversation ``` With `autosave: true`, Rule E saves the conversation at session end without @@ -141,8 +169,8 @@ KB gets the same behaviour. **Toggling it on request** ("save conversations automatically", "turn off autosave"): read `ckb.yaml`, change only the `autosave` value, write the -file back with everything else byte-for-byte intact (`template:` and -`kb_modules:` belong to other skills). Add the `conversations:` block if it +file back with everything else byte-for-byte intact (`template:`, +`kb_modules:` and `routines:` belong to other skills). Add the `conversations:` block if it is missing. Confirm the new value in one line, then run the per-machine check described below and ask about the hook. When turning it on, say once that every session will become a tracked file in the repo, including diff --git a/.agents/skills/ckb-add-conversation/scripts/save_conversation.py b/.agents/skills/ckb-add-conversation/scripts/save_conversation.py index 95522d7..b1607fe 100644 --- a/.agents/skills/ckb-add-conversation/scripts/save_conversation.py +++ b/.agents/skills/ckb-add-conversation/scripts/save_conversation.py @@ -10,9 +10,14 @@ Markdown rendering next to it, then updates raw/saved-conversations/index.md. save_conversation.py --session # save a specific session (id or unique prefix) save_conversation.py --from # save a transcript file given explicitly save_conversation.py --from-hook # Claude Code hook: read {"transcript_path": ...} from stdin - save_conversation.py --title "..." # override the derived title + save_conversation.py --title "..." # override the derived title for this save only + save_conversation.py --set-title "..." # remember a title for the session (tmp/conversation-titles/), then exit save_conversation.py --dry-run # say what would be written, write nothing +Title precedence: --title, then the title stored by --set-title for this +session, then Claude Code's own custom (/rename) or AI title, then the first +user line. + Python 3.8+, standard library only. Exit 0 on success, 1 on a usage/lookup error, 2 when nothing was found to save. """ @@ -27,6 +32,7 @@ from datetime import datetime, timezone from pathlib import Path DEST_ROOT = Path("raw") / "saved-conversations" +TITLES_DIR = Path("tmp") / "conversation-titles" # per machine (tmp/ is gitignored); the Stop hook reads it RESULT_CHARS = 400 INPUT_CHARS = 200 SYSTEM_REMINDER = re.compile(r".*?\s*", re.DOTALL) @@ -104,10 +110,13 @@ def session_meta(entries, path: Path): meta = {"session_id": path.stem, "title": None, "cwd": None, "version": None, "started": None, "ended": None, "user_turns": 0, "assistant_turns": 0, "tool_calls": 0, "git_branch": None} + custom = None for e in entries: t = e.get("type") if t == "ai-title" and e.get("aiTitle"): meta["title"] = e["aiTitle"] + if t == "custom-title" and e.get("customTitle"): # /rename in Claude Code + custom = e["customTitle"] if t in ("user", "assistant"): ts = e.get("timestamp") if ts: @@ -124,9 +133,37 @@ def session_meta(entries, path: Path): if any(b.get("type") == "text" and b.get("text", "").strip() for b in blocks if isinstance(b, dict)): meta["assistant_turns"] += 1 meta["tool_calls"] += sum(1 for b in blocks if isinstance(b, dict) and b.get("type") == "tool_use") + if custom: + meta["title"] = custom return meta +def stored_title(root: Path, session_id: str): + """Title remembered by --set-title for this session, or None.""" + f = root / TITLES_DIR / f"{session_id}.title" + if f.is_file(): + t = f.read_text(encoding="utf-8").strip() + return t or None + return None + + +def store_title(root: Path, session_id: str, title: str) -> Path: + d = root / TITLES_DIR + d.mkdir(parents=True, exist_ok=True) + f = d / f"{session_id}.title" + f.write_text(title.strip() + "\n", encoding="utf-8") + return f + + +def remove_stale_copies(dest_dir: Path, sid8: str, keep_base: str): + """A re-save under a new title changes the slug; drop the old pair for this session.""" + if not dest_dir.is_dir(): + return + for f in dest_dir.iterdir(): + if f.is_file() and f.stem.endswith(f"_{sid8}") and f.stem != keep_base and f.suffix in (".md", ".jsonl"): + f.unlink() + + def user_text(entry): """Plain text a user typed in this entry, with harness reminders stripped.""" content = (entry.get("message") or {}).get("content") @@ -290,7 +327,9 @@ def main(argv=None): ap.add_argument("--from", dest="from_file", help="save this transcript file instead of looking one up") ap.add_argument("--from-hook", action="store_true", help="read Claude Code hook JSON from stdin and save its transcript_path") - ap.add_argument("--title", help="override the derived title") + ap.add_argument("--title", help="override the derived title for this save only") + ap.add_argument("--set-title", metavar="TITLE", + help="remember TITLE for the session (current, --session or --from-hook) and exit without saving") ap.add_argument("--author", help="'Name ' to record; default: the repo's git identity") ap.add_argument("--root", default=".", help="KB root (default: current directory)") ap.add_argument("--today", help="override the save date, YYYY-MM-DD (tests)") @@ -320,9 +359,11 @@ def main(argv=None): sessions = list_sessions(pdir) if args.list: for s in sessions: - meta = session_meta(read_entries(s["path"]), s["path"]) + entries = read_entries(s["path"]) + meta = session_meta(entries, s["path"]) when = datetime.fromtimestamp(s["mtime"]).strftime("%Y-%m-%d %H:%M") - print(f"{s['id'][:8]} {when} {s['size'] // 1024:6d} KB {meta['user_turns']:3d} turns {meta['title'] or first_user_line(read_entries(s['path']))[:60]}") + shown = stored_title(root, s["id"]) or meta["title"] or first_user_line(entries)[:60] + print(f"{s['id'][:8]} {when} {s['size'] // 1024:6d} KB {meta['user_turns']:3d} turns {shown}") return 0 chosen = pick_session(sessions, args.session) if not chosen: @@ -330,10 +371,19 @@ def main(argv=None): return 2 src = chosen["path"] + if args.set_title is not None: + if not args.set_title.strip(): + sys.exit("error: --set-title needs a non-empty title") + f = store_title(root, src.stem, args.set_title) + print(f"title set: {args.set_title.strip()} (session {src.stem[:8]}, {f.relative_to(root).as_posix()})") + return 0 + entries = read_entries(src) meta = session_meta(entries, src) if args.title: meta["title"] = args.title + else: + meta["title"] = stored_title(root, meta["session_id"]) or stored_title(root, src.stem) or meta["title"] title = meta["title"] or first_user_line(entries) or "Conversation" data = src.read_bytes() digest = hashlib.sha256(data).hexdigest()[:8] @@ -351,6 +401,7 @@ def main(argv=None): if not args.dry_run: dest_dir.mkdir(parents=True, exist_ok=True) + remove_stale_copies(dest_dir, meta["session_id"][:8], base) jsonl_path.write_bytes(data) md_path.write_text(md, encoding="utf-8") update_index(root / DEST_ROOT / "index.md", { diff --git a/.agents/skills/ckb-init/SKILL.md b/.agents/skills/ckb-init/SKILL.md index 5d8d89c..8d619c5 100644 --- a/.agents/skills/ckb-init/SKILL.md +++ b/.agents/skills/ckb-init/SKILL.md @@ -264,10 +264,11 @@ a fresh KB by accident is easy, and the local working tree is exactly how it happens. `ckb.yaml` is also the modules manifest (`ckb-module` owns the `kb_modules:` -list) and carries the conversation autosave switch (`ckb-add-conversation` -owns `conversations:`). A fresh KB has no modules, so at init time the file -holds the `template:` block, an empty `kb_modules: []`, and -`conversations:` with `autosave: false`. +list), carries the conversation settings (`ckb-add-conversation` owns +`conversations:`) and the routines (`ckb-routine` owns `routines:`). A fresh +KB has no modules and no routines, so at init time the file holds the +`template:` block, an empty `kb_modules: []`, `conversations:` with +`autosave: false` and `ask_title: true`, and an empty `routines: []`. For `LICENSE`, copy the Apache License 2.0 text, but **ask the user first** whether to keep the copyright line as-is (appropriate if this new KB is diff --git a/.agents/skills/ckb-reset/SKILL.md b/.agents/skills/ckb-reset/SKILL.md index a91e741..a85249e 100644 --- a/.agents/skills/ckb-reset/SKILL.md +++ b/.agents/skills/ckb-reset/SKILL.md @@ -64,7 +64,7 @@ just said "reset the wiki" — the narrowest reading that satisfies the request. | **3 — Source material** | `raw/inbox/*`, `raw/archive/*`, `raw/saved-conversations/*` | Ask — this is the user's original material and may exist nowhere else | | **4 — Generated artifacts** | `outputs/*` | Ask — cheap to regenerate, usually safe | | **5 — External sources** | `libs/*`, `linked/*` | Ask — **default no.** `linked/` holds symlinks to *other people's* KBs, and deleting a symlink target by accident is a real risk | -| **6 — Installed modules** | `ckb.yaml` + module-installed skills + the marked blocks in `AGENTS.md`/`.gitignore` | Ask — **default no.** That's `ckb-module uninstall`'s job, not this skill's | +| **6 — Installed modules** | `ckb.yaml` (modules, conversation settings, routines) + module-installed skills + the marked blocks in `AGENTS.md`/`.gitignore` | Ask — **default no.** That's `ckb-module uninstall`'s job (and `ckb-routine --remove`'s), not this skill's | For a template being prepared for distribution, tiers 1–4 are the usual answer. diff --git a/.agents/skills/ckb-routine/SKILL.md b/.agents/skills/ckb-routine/SKILL.md new file mode 100644 index 0000000..3541973 --- /dev/null +++ b/.agents/skills/ckb-routine/SKILL.md @@ -0,0 +1,121 @@ +--- +name: ckb-routine +description: Set up, list, run or remove routines — KB actions ("Lint", "Index external sources", any routing-table phrase) that fire automatically at session start once a period has elapsed since they last ran. Definitions and the last-run date live in ckb.yaml under routines:, committed and shared by everyone using the repo. Use for "every week run lint", "lint automatically every 7 days", "add a routine", "list routines", "what routines are set up", "which routines are due", "run the routines now", "remove the weekly lint", "stop the monthly index". Not Claude Code's cloud scheduler or /loop — a routine needs no running agent; it is checked whenever someone opens a session. +--- + +# Routine skill + +## Purpose + +Let the user say once "do X every N days" and have X happen without being +asked again. A routine is **time-since-last**, not a calendar: it fires at +the first session start after `every` has elapsed since `last_run`. Nothing +runs while nobody is working in the KB, and a routine fired by one person +counts for everyone, because the state is committed. + +## Where routines live + +`ckb.yaml`, block `routines:`, owned by this skill: + +```yaml +routines: + - name: weekly-lint + do: "Lint" # any phrase from the AGENTS.md §3 routing table, or a plain instruction + every: 7d # Nh | Nd | Nw — day granularity; 24h behaves like 1d + confirm: false # true: ask at the end of the reply instead of running + last_run: 2026-10-21 # set by --mark when the action completes; blank = never ran +``` + +`do` is executed exactly as if the user had typed it, so it routes through +the same table ("Lint" → `ckb-lint`, "Index external sources" → +`ckb-index-external`, "Give me a project summary" → `ckb-project-summary`). +Two actions are refused by the script: anything naming `ckb-reset` or +`ckb-sync-changes` — one is destructive, the other touches the remote. + +## The script + +```bash + .agents/skills/ckb-routine/scripts/routines.py --due # due routines, one per line; exit 1 if any + .agents/skills/ckb-routine/scripts/routines.py --list # all routines with last run and next due date + .agents/skills/ckb-routine/scripts/routines.py --mark # last_run = today + .agents/skills/ckb-routine/scripts/routines.py --add --name --do "" --every 7d [--confirm] + .agents/skills/ckb-routine/scripts/routines.py --remove +``` + +All edits are line-level and leave the rest of `ckb.yaml` byte for byte +(`template:`, `kb_modules:`, `conversations:` belong to other skills). Never +hand-edit the block — use the script, so the file stays parseable by it. +Resolve `` as `AGENTS.md` §3 describes; without Python, routines are +simply not checked — say so once per session. + +## How to run this skill + +### Add ("every week, lint" / "index external sources monthly, but ask me first") + +1. Derive `name` (lower-case, hyphens: `weekly-lint`), `do` (the routing + phrase, quoted) and `every` (`7d`, `2w`, `30d`). "Ask me first" → + `--confirm`. +2. Run `--add`. On "already exists", offer `--remove` then `--add`. +3. Confirm in one line. Say that `last_run` is blank, so it fires at the + **next** session start — or offer `--mark ` now if the user just + did the action by hand and wants the clock to start today. +4. `ckb.yaml` changed: mention it in the workload note. It is a template + file, not `wiki/`, so `wiki/log.md` is not touched. + +### List / which are due + +`--list` and relay it. `DUE` rows are what will run at the next session +start; `[confirm]` rows will be asked about instead. + +### Remove + +`--remove `, confirm in one line. Removing the last routine leaves +`routines: []`. + +### Run now ("run the routines", "run the weekly lint now") + +Perform `do` for the named routine (or every due one) in this turn, then +`--mark` each one that completed. A routine that is not yet due can still be +run on request — marking it restarts its period from today. + +## The firing rule (what Rule E does at session start) + +1. Session start runs `--due`. Exit 0 or no block: nothing to do, stay + quiet. Exit 1: remember the due list; **finish the user's request + first**. +2. Then, in the same turn, for each due routine: + - `confirm: false` — perform `do` through the normal skill, run + `--mark `, and add one line to the reply: + `Routine weekly-lint ran: `. + - `confirm: true` — do not run it. End the reply with one question: + "Routine `` (``) is due — run it now?" On a yes in the next + turn, run and mark. On a no, say it will be asked again next session + and leave `last_run` alone. In a non-interactive session, skip + `confirm: true` routines and note that in the workload note. +3. **Only a completed action is marked.** If the skill fails, is declined, + or stops for input it never gets, `last_run` stays as it was so the + routine comes back next session — say so in one line. +4. **Manual runs count.** Whenever a skill is run for any reason and some + routine's `do` names that action (the user said "Lint" themselves), + run `--mark` for that routine too. One lint a week is the point, not + one lint a week plus whatever the user did by hand. +5. Logging: the action's own skill logs whatever it changes under `wiki/` + as usual (Rule B); write `**Source:** routine ()` on those + entries so the log shows it was not a human request. The workload note + gets one line per routine fired. + +## Edge cases + +- **Unreadable `every` or `last_run`** — `--list` shows the problem text in + place of the next date; `--due` treats an unreadable `last_run` as "never + ran" (so it fires) and an unreadable `every` as "never due" (so it does + not). Tell the user and offer to fix the value with `--remove`/`--add`. +- **Two people fire the same routine the same day** — both `--mark` the + same line to the same date; git merges that cleanly. Different dates + conflict on one line; the later date is the right resolution. +- **`ckb-upgrade` and `ckb-module`** never touch `routines:`; `ckb-init` + writes `routines: []`; `ckb-reset` keeps `ckb.yaml` (tier 6, default no). +- **Claude Code's `schedule` / `/loop`** are a different thing: they need a + running agent and live outside the repo. A routine is the right tool when + the action should happen "whenever someone next opens this KB after N + days", shared by the whole team. diff --git a/.agents/skills/ckb-routine/scripts/routines.py b/.agents/skills/ckb-routine/scripts/routines.py new file mode 100755 index 0000000..a4cfda3 --- /dev/null +++ b/.agents/skills/ckb-routine/scripts/routines.py @@ -0,0 +1,275 @@ +#!/usr/bin/env python3 +"""Routines: actions that fire when a period has elapsed since they last ran. + +Definitions and state both live in the `routines:` block of ckb.yaml: + + routines: + - name: weekly-lint + do: "Lint" # any phrase from the AGENTS.md routing table, or a plain instruction + every: 7d # Nh | Nd | Nw + confirm: false # true: ask before running instead of running after the request + last_run: 2026-10-21 # written by --mark when the action completes; blank = never ran + + routines.py --due [--today YYYY-MM-DD] # one line per due routine; exit 1 when any is due, 0 otherwise + routines.py --list # every routine with last run, next due date and confirm flag + routines.py --mark [--today ...] # set last_run to today + routines.py --add --name X --do "..." --every 7d [--confirm] + routines.py --remove + +Edits are line-level: only the lines of the routine named are touched, the +rest of ckb.yaml is left byte for byte. Python 3.8+, standard library only. +""" +import argparse +import re +import sys +from datetime import date, datetime, timedelta +from pathlib import Path + +PERIOD = re.compile(r"^(\d+)([hdw])$") +NAME = re.compile(r"^[a-z0-9][a-z0-9-]*$") +FORBIDDEN = ("ckb-reset", "ckb-sync-changes", "reset the wiki", "sync changes", "sync with origin") +KEYS = ("name", "do", "every", "confirm", "last_run") + + +# ---------------------------------------------------------------- parsing + +def strip_comment(line: str) -> str: + out, quote = [], None + for ch in line: + if quote: + out.append(ch) + if ch == quote: + quote = None + elif ch in "\"'": + quote = ch + out.append(ch) + elif ch == "#": + break + else: + out.append(ch) + return "".join(out).rstrip() + + +def unquote(v: str) -> str: + v = v.strip() + if len(v) >= 2 and v[0] == v[-1] and v[0] in "\"'": + return v[1:-1] + return v + + +def parse(path: Path): + """Return (lines, block) where block is None when there is no `routines:` key, + else a dict with start/end line indexes and a list of routine items, each + carrying its own line span and key->(value, line_index).""" + lines = path.read_text(encoding="utf-8").splitlines() if path.exists() else [] + start = None + for i, raw in enumerate(lines): + if strip_comment(raw).strip() == "routines:" and not raw.startswith((" ", "\t")): + start = i + break + if strip_comment(raw).strip().startswith("routines:") and not raw.startswith((" ", "\t")): + # `routines: []` or similar inline value + start = i + break + if start is None: + return lines, None + end = len(lines) + for j in range(start + 1, len(lines)): + raw = lines[j] + if raw.strip() and not raw.startswith((" ", "\t")) and not raw.lstrip().startswith("#"): + end = j + break + items, cur = [], None + for j in range(start + 1, end): + text = strip_comment(lines[j]) + if not text.strip(): + continue + m = re.match(r"^(\s*)-\s*(.*)$", text) + if m: + cur = {"first": j, "last": j, "indent": len(m.group(1)), "fields": {}} + items.append(cur) + rest = m.group(2) + if ":" in rest: + k, v = rest.split(":", 1) + cur["fields"][k.strip()] = (unquote(v), j) + continue + if cur is not None and ":" in text: + k, v = text.strip().split(":", 1) + cur["fields"][k.strip()] = (unquote(v), j) + cur["last"] = j + inline = strip_comment(lines[start]).split(":", 1)[1].strip() + return lines, {"start": start, "end": end, "items": items, "inline_empty": inline in ("[]", "")} + + +def routine(item): + f = item["fields"] + get = lambda k: f.get(k, ("", None))[0] + return { + "name": get("name"), "do": get("do"), "every": get("every"), + "confirm": get("confirm").lower() in ("true", "yes", "on"), + "last_run": get("last_run"), + } + + +def period_delta(spec: str) -> timedelta: + m = PERIOD.match(spec.strip()) + if not m: + raise ValueError(f"bad period {spec!r}: use Nh, Nd or Nw (e.g. 24h, 7d, 2w)") + n, unit = int(m.group(1)), m.group(2) + return {"h": timedelta(hours=n), "d": timedelta(days=n), "w": timedelta(weeks=n)}[unit] + + +def parse_day(s: str): + try: + return datetime.strptime(s.strip(), "%Y-%m-%d") + except ValueError: + return None + + +def status(r, today: datetime): + """(due: bool, next_due: datetime|None, detail: str). last_run is a date, taken at 00:00, + so hour periods are coarse: 24h behaves like 1d.""" + if not r["every"]: + return False, None, "no period" + try: + every = period_delta(r["every"]) + except ValueError as e: + return False, None, str(e) + if not r["last_run"]: + return True, today, "never ran" + last = parse_day(r["last_run"]) + if last is None: + return True, today, f"unreadable last_run {r['last_run']!r}" + nxt = last + every + if nxt <= today: + over = today - nxt + return True, nxt, f"overdue by {over.days}d" if over.days else "due today" + return False, nxt, f"next {nxt.strftime('%Y-%m-%d')}" + + +# ---------------------------------------------------------------- writing + +def write(path: Path, lines): + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + + +def find(block, name): + for it in block["items"]: + if it["fields"].get("name", ("",))[0] == name: + return it + return None + + +def cmd_mark(path, name, today): + lines, block = parse(path) + it = block and find(block, name) + if not it: + sys.exit(f"error: no routine named {name!r} in {path}") + stamp = today.strftime("%Y-%m-%d") + if "last_run" in it["fields"]: + j = it["fields"]["last_run"][1] + lines[j] = re.sub(r"(last_run:\s*)\S*", r"\g<1>" + stamp, lines[j], count=1) + else: + pad = " " * (it["indent"] + 2) + lines.insert(it["last"] + 1, f"{pad}last_run: {stamp}") + write(path, lines) + print(f"marked {name}: last_run {stamp}") + + +def cmd_add(path, name, do, every, confirm): + if not NAME.match(name): + sys.exit("error: name must be lower-case letters, digits and hyphens") + period_delta(every) + low = do.lower() + if any(f in low for f in FORBIDDEN): + sys.exit("error: a routine may not run ckb-reset or ckb-sync-changes (destructive / touches the remote)") + lines, block = parse(path) + if block and find(block, name): + sys.exit(f"error: routine {name!r} already exists; --remove it first") + do_q = '"' + do.replace('"', "'") + '"' + item = [f" - name: {name}", f" do: {do_q}", f" every: {every}", + f" confirm: {'true' if confirm else 'false'}", f" last_run:"] + if block is None: + if lines and lines[-1].strip(): + lines.append("") + lines.append("routines: # actions that fire when `every` has elapsed since `last_run`") + lines.extend(item) + else: + if block["inline_empty"]: + # `routines: [] # comment` -> `routines: # comment`: drop the brackets, keep the width + lines[block["start"]] = lines[block["start"]].replace("[]", " ", 1).rstrip() + lines[block["end"]:block["end"]] = item + write(path, lines) + print(f"added {name}: {do} every {every}" + (" (confirm first)" if confirm else "") + " — fires at the next session start") + + +def cmd_remove(path, name): + lines, block = parse(path) + it = block and find(block, name) + if not it: + sys.exit(f"error: no routine named {name!r} in {path}") + del lines[it["first"]:it["last"] + 1] + if len(block["items"]) == 1: # that was the last one: leave an explicit empty list + head = lines[block["start"]] + if re.match(r"^routines:\s{3,}#", head): # width was kept by --add: put the brackets back + lines[block["start"]] = re.sub(r"^routines: ", "routines: []", head, count=1) + else: + lines[block["start"]] = "routines: []" + write(path, lines) + print(f"removed {name}") + + +# ---------------------------------------------------------------- main + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + g = ap.add_mutually_exclusive_group(required=True) + g.add_argument("--due", action="store_true") + g.add_argument("--list", action="store_true") + g.add_argument("--mark", metavar="NAME") + g.add_argument("--add", action="store_true") + g.add_argument("--remove", metavar="NAME") + ap.add_argument("--name"); ap.add_argument("--do"); ap.add_argument("--every") + ap.add_argument("--confirm", action="store_true") + ap.add_argument("--root", default=".", help="KB root (default: current directory)") + ap.add_argument("--today", help="override today's date, YYYY-MM-DD (tests)") + a = ap.parse_args(argv) + + path = Path(a.root) / "ckb.yaml" + today = parse_day(a.today) if a.today else datetime.combine(date.today(), datetime.min.time()) + if today is None: + sys.exit("error: --today must be YYYY-MM-DD") + + if a.mark: + cmd_mark(path, a.mark, today); return 0 + if a.add: + if not (a.name and a.do and a.every): + sys.exit("error: --add needs --name, --do and --every") + cmd_add(path, a.name, a.do, a.every, a.confirm); return 0 + if a.remove: + cmd_remove(path, a.remove); return 0 + + _, block = parse(path) + items = [routine(it) for it in (block["items"] if block else [])] + if a.list: + if not items: + print("no routines in ckb.yaml"); return 0 + for r in items: + due, _, detail = status(r, today) + flag = "DUE " if due else " " + print(f"{flag}{r['name']:<20} every {r['every']:<5} last {r['last_run'] or 'never':<10} {detail}" + + (" [confirm]" if r["confirm"] else "") + f" — {r['do']}") + return 0 + # --due + due_items = [] + for r in items: + due, _, detail = status(r, today) + if due: + due_items.append((r, detail)) + for r, detail in due_items: + print(f"{r['name']} {r['do']} {detail}" + (" [confirm]" if r["confirm"] else "")) + return 1 if due_items else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.agents/skills/ckb-upgrade/SKILL.md b/.agents/skills/ckb-upgrade/SKILL.md index ba069f3..32eb520 100644 --- a/.agents/skills/ckb-upgrade/SKILL.md +++ b/.agents/skills/ckb-upgrade/SKILL.md @@ -302,9 +302,9 @@ Only if `template_upgrade_available` and at least one item was accepted: - If the user switched channel for this run (Step 0), write the new `branch:` into `ckb.yaml`'s `template:` block now that the switch has actually happened. Create the file with just that block if it doesn't - exist; if it does, edit only `template:` and leave `kb_modules:` and - `conversations:` exactly as found — those belong to `ckb-module` and - `ckb-add-conversation`. Persisting the branch is + exist; if it does, edit only `template:` and leave `kb_modules:`, + `conversations:` and `routines:` exactly as found — those belong to + `ckb-module`, `ckb-add-conversation` and `ckb-routine`. Persisting the branch is what stops the *next* upgrade from silently pulling the KB back to whichever channel it was on before. diff --git a/AGENTS.md b/AGENTS.md index 6d0bd4a..9aa838e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,7 +15,7 @@ Maintain this root layout: ``` ├── .agents/modules/ # Optional modules, inert until installed -├── ckb.yaml # Repo manifest: template branch, installed modules, conversation autosave +├── ckb.yaml # Repo manifest: template branch, installed modules, conversation settings, routines ├── docs/ # Manual, changelog, OpenSpec guide, template design records │ └── decisions/ # The template's own ADRs (D-0001…) — not KB content ├── tests/ # Template repo only: smoke test for the scripts; never shipped to a KB @@ -171,6 +171,7 @@ file. | Health-check or repair wiki/index structure | `ckb-lint` | | Sync this repo with `origin` | `ckb-sync-changes` | | Save this conversation, or ask what was discussed or instructed in a past one | `ckb-add-conversation` | +| Set up, list, run, or remove a routine (an action that repeats once a period has elapsed) | `ckb-routine` | | Upgrade template or wiki schema | `ckb-upgrade` | | Bootstrap a new empty KB (from local files or a fresh clone of the template repo) | `ckb-init` | | Install, list, or uninstall an optional module | `ckb-module` | @@ -193,6 +194,9 @@ Disambiguation, only where the table alone is ambiguous: in `ckb-retrieve`, which never reads saved conversations. Saving is always on request; to ingest a saved conversation the user copies its `.md` into `raw/inbox/` themselves. +- `ckb-routine` owns "do X every N days": a routine is repo-level and + time-since-last, stored in `ckb.yaml` and fired at session start. It is not + Claude Code's cloud scheduler or `/loop`, which need a running agent. - `ckb-upgrade` also takes a request naming a release channel. The template repo keeps `main` (stable), `test` (release candidate) and `experimental` (development); which branch this KB tracks lives in `ckb.yaml`'s `template:` @@ -284,6 +288,18 @@ once, and point to `git config --global user.name`. This identity goes into every workload note, every log entry's `**Author:**` line, and every saved conversation; it is also what the commits will carry, so the three agree. +Unless `ckb.yaml` has `conversations.ask_title: false`, the **first reply of +a new session is one question and nothing else**: "What should this +conversation be called?" Do no work until it is answered. Skip the question +when the first message already names a title ("title: …", "call this …"), +when the session is a resume that already has a stored title, or when no +human can answer (non-interactive run — use the derived title and say so once +in the workload note). On the answer, run +` .agents/skills/ckb-add-conversation/scripts/save_conversation.py --set-title ""` +once, then handle the request that arrived with the first message. The title +heads the session's block in the workload note and names the saved +conversation. Ask once per session, never again, even on "no title". + Then read `wiki/index.md`, the latest `workload/` summary by filename date regardless of author, and run two cheap checks: @@ -313,6 +329,21 @@ after autosave was turned off). Ask once whether to change `ckb-add-conversation` owns the details. Skip the check entirely when autosave is off and no hook file exists; stay quiet on exit 0. +When `ckb.yaml` has a non-empty `routines:` block, run a fourth check: + +```bash +<python> .agents/skills/ckb-routine/scripts/routines.py --due +``` + +Exit 1 lists the routines whose period has elapsed. Finish the user's +request first; then, in the same turn, perform each due routine's `do` as if +the user had asked for it, run `--mark <name>` once it completes, and report +it in one line. A routine with `confirm: true` is asked about at the end of +the reply instead, and runs only on a yes. A failed or declined routine is +not marked, so it returns next session. Whenever a skill that some routine's +`do` names is run by hand, mark that routine too. `ckb-routine` owns the +details; without Python, skip the check and say so once. + `git status` covers unsynchronized history — if there are uncommitted changes or the branch is ahead/behind its remote-tracking branch, say so and suggest `ckb-sync-changes`. `--quick` covers knowledge rot: one line stating diff --git a/README.md b/README.md index 9530ddc..a3947cb 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ A KB with no `ckb.yaml` (or no `template:` block) is treated as tracking ## Directory Structure ``` -├── ckb.yaml # Repo manifest: template branch tracked, installed modules +├── ckb.yaml # Repo manifest: template branch tracked, installed modules, conversation settings, routines ├── docs/ # Manual, changelog, OpenSpec guide, and decisions/ — the template's own ADRs ├── tests/ # Template repo only: fixture KB + smoke test (tests/smoke.sh); not copied into KBs ├── libs/ # Read-only external sources — git-copy clones (gitignored) OR @@ -417,10 +417,13 @@ harness - nothing in `.claude/` runs on its own. If you want any of them enforced mechanically, that is a Claude Code hook or a scheduled agent you add yourself. -- **Session start** → read `wiki/index.md` and the latest workload summary; - run `git status` and `lint_report.py --quick`; suggest `ckb-sync-changes` - or `ckb-lint` only when either reports something; when conversation - autosave is on, also check this machine has the gitignored Stop hook in +- **Session start** → ask what the conversation should be called and wait + for the answer (unless `conversations.ask_title: false`); then read + `wiki/index.md` and the latest workload summary; run `git status`, + `lint_report.py --quick` and `routines.py --due`; suggest + `ckb-sync-changes` or `ckb-lint` only when either reports something; run + due routines after the first request; when conversation autosave is on, + also check this machine has the gitignored Stop hook in `.claude/settings.local.json` and ask before installing it - **Session end** → append to `workload/`; repeat the unsynchronized-change check; after a session that did real work, ask once whether to save the @@ -429,8 +432,9 @@ add yourself. - **Every turn that touches the KB** → a note in `workload/` (Rule D) - **Unanswerable question** → a `wiki/query-gaps.md` entry, the one write `ckb-retrieve` owns; answers are never filed back as pages automatically -- **Lint on demand** → "Lint" runs the full check; there is no built-in - schedule +- **Lint on demand or by routine** → "Lint" runs the full check; "lint + every week" makes it a routine in `ckb.yaml` that fires at the first + session start after the period has elapsed (`ckb-routine`) ### Demand-Driven Context (DDC) The wiki grows based on actual agent failures rather than upfront curation: @@ -527,8 +531,9 @@ X", "what did I tell you about Y") and get the exact exchange quoted back. To bring one into the wiki, copy its `.md` into `raw/inbox/` and say "Ingest". Say "save conversations automatically" to flip `conversations.autosave` in `ckb.yaml`, after which every session is saved -at its end without a question. Skill: -`.agents/skills/ckb-add-conversation/SKILL.md`. +at its end without a question. Every session opens by asking for its title, +which names the saved transcript; "stop asking for a title" turns that off. +Skill: `.agents/skills/ckb-add-conversation/SKILL.md`. ### Quiz Mode (on demand) Ask to be quizzed on the wiki ("quiz me on X", "test my knowledge") for a diff --git a/README.pl.md b/README.pl.md index 5d17480..052a699 100644 --- a/README.pl.md +++ b/README.pl.md @@ -53,7 +53,7 @@ KB bez `ckb.yaml` (albo bez bloku `template:`) jest traktowana jako śledząca ## Struktura katalogów ``` -├── ckb.yaml # Manifest repozytorium: śledzona gałąź szablonu, zainstalowane moduły +├── ckb.yaml # Manifest repozytorium: śledzona gałąź szablonu, zainstalowane moduły, ustawienia rozmów, rutyny ├── docs/ # Podręcznik, changelog, przewodnik OpenSpec i decisions/ — własne ADR-y szablonu ├── tests/ # Tylko w repo szablonu: baza-fixture + test dymny (tests/smoke.sh); nie kopiowany do KB ├── libs/ # Zewnętrzne źródła tylko do odczytu — kopie git (w .gitignore) LUB @@ -458,10 +458,12 @@ wpięte w narzędzie — nic w `.claude/` nie uruchamia się samo. Jeśli chcesz by któraś była wymuszana mechanicznie, dodajesz ją sam jako hook Claude Code albo zaplanowanego agenta. -- **Start sesji** → odczyt `wiki/index.md` i ostatniego podsumowania - workload; `git status` i `lint_report.py --quick`; sugestia - `ckb-sync-changes` lub `ckb-lint` tylko wtedy, gdy któreś coś zgłosi; - przy włączonym autozapisie rozmów sprawdza też, czy ta maszyna ma hook +- **Start sesji** → pytanie, jak nazwać rozmowę, i czekanie na odpowiedź + (chyba że `conversations.ask_title: false`); potem odczyt `wiki/index.md` + i ostatniego podsumowania workload; `git status`, `lint_report.py --quick` + i `routines.py --due`; sugestia `ckb-sync-changes` lub `ckb-lint` tylko + wtedy, gdy któreś coś zgłosi; zaległe rutyny wykonywane po pierwszej + prośbie; przy włączonym autozapisie rozmów sprawdza też, czy ta maszyna ma hook `Stop` w ignorowanym przez gita `.claude/settings.local.json`, i pyta przed jego zainstalowaniem - **Koniec sesji** → dopisanie do `workload/`; powtórzenie sprawdzenia @@ -470,8 +472,9 @@ albo zaplanowanego agenta. - **Pytanie bez odpowiedzi** → wpis w `wiki/query-gaps.md`, jedyny zapis, który należy do `ckb-retrieve`; odpowiedzi nigdy nie są automatycznie zapisywane jako strony -- **Lint na żądanie** → „Lint" uruchamia pełną kontrolę; nie ma wbudowanego - harmonogramu +- **Lint na żądanie lub przez rutynę** → „Lint" uruchamia pełną kontrolę; + „lint every week" robi z tego rutynę w `ckb.yaml`, która odpala się na + pierwszym starcie sesji po upływie okresu (`ckb-routine`) ### Kontekst napędzany zapotrzebowaniem (Demand-Driven Context, DDC) Wiki rośnie na podstawie rzeczywistych niepowodzeń agenta, a nie z góry @@ -578,7 +581,9 @@ rozmowy („czy rozmawialiśmy o X", „co ci mówiłem o Y") i dostać zacytowa dokładną wymianę zdań. Aby przenieść rozmowę do wiki, skopiuj jej `.md` do `raw/inbox/` i powiedz „Ingest". Powiedz „save conversations automatically", aby przełączyć `conversations.autosave` w `ckb.yaml` - od tej pory każda -sesja jest zapisywana na końcu bez pytania. Skill: +sesja jest zapisywana na końcu bez pytania. Każda sesja zaczyna się od +pytania o tytuł, który nadaje nazwę zapisanemu transkryptowi; „stop asking +for a title" to wyłącza. Skill: `.agents/skills/ckb-add-conversation/SKILL.md`. ### Tryb quizu (na żądanie) diff --git a/VERSION b/VERSION index 141f2e8..15b989e 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.15.0 +1.16.0 diff --git a/ckb.yaml b/ckb.yaml index 9e90777..386770c 100644 --- a/ckb.yaml +++ b/ckb.yaml @@ -1,7 +1,7 @@ # Cascade KB manifest — repo-level configuration, not the wiki's content contract # (kb_schema_version stays in wiki/index.md). Written by ckb-init, read by -# ckb-upgrade (template:), ckb-module (kb_modules:) and ckb-add-conversation -# (conversations:). +# ckb-upgrade (template:), ckb-module (kb_modules:), ckb-add-conversation +# (conversations:) and ckb-routine (routines:). template: repo: https://git.wierzbowa.cloud/michal/ckb.git branch: main # main | test | experimental @@ -10,3 +10,6 @@ kb_modules: [] conversations: autosave: false # true: save every session's transcript at session end without asking + ask_title: true # true: the first reply of every session asks what to call the conversation + +routines: [] # actions that fire when `every` has elapsed since `last_run`; see ckb-routine diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 63880c5..b2d5049 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -284,7 +284,8 @@ docs. Independent of the content schema above. | Version | Date | What landed | Schema | |---|---|---|---| -| **1.15.0** | 2026-10-16 | `tests/` is template-repo only: `ckb-init` no longer copies it, `ckb-upgrade` no longer ships it (and offers once to delete a leftover copy), directory contract and docs say so. The smoke test itself is unchanged | 1.5 | +| **1.16.0** | 2026-10-21 | Session titles and routines. Rule E's first reply in a new session is the question "What should this conversation be called?" (switch `conversations.ask_title`, default `true`); the answer is stored with `save_conversation.py --set-title` in gitignored `tmp/conversation-titles/` and names the saved transcript (slug, heading, index row) and the workload block; a re-save under a new title replaces the old pair. New `ckb-routine`: `routines:` in `ckb.yaml` (`name`/`do`/`every`/`confirm`/`last_run`), checked at session start by `routines.py --due`; due routines run after the user's request in the same turn and are `--mark`ed only when they complete, `confirm: true` asks instead, manual runs count, `ckb-reset`/`ckb-sync-changes` refused. `ckb-init` writes both blocks, `ckb-upgrade` leaves them alone; smoke test covers both scripts. D-0005 | 1.5 | +| 1.15.0 | 2026-10-16 | `tests/` is template-repo only: `ckb-init` no longer copies it, `ckb-upgrade` no longer ships it (and offers once to delete a leftover copy), directory contract and docs say so. The smoke test itself is unchanged | 1.5 | | 1.14.0 | 2026-10-16 | Authorship for shared repos: the session identity (`git config user.name`/`user.email`, resolved once at session start) stamps every workload note, every `wiki/log.md` entry (new `**Author:**` line, optional, lint-neutral) and every saved conversation (`save_conversation.py --author`). Workload files become one per person per day, `YYYY-MM-DD_<author>_summary.md` with `type: session` frontmatter, so two people never merge-conflict in `workload/`; older files are read as before. D-0004 | 1.5 | | 1.13.0 | 2026-10-16 | Conversation autosave switch: `conversations.autosave` in `ckb.yaml` (default `false`). On, Rule E saves every session at its end without asking; `ckb-add-conversation` toggles it on request ("save conversations automatically"). Per-machine half: `autosave_hook.py --check/--install/--remove` manages a Claude Code `Stop` hook in gitignored `.claude/settings.local.json`; Rule E runs the check at session start when autosave is on and asks before changing machine configuration; `save_conversation.py --from-hook` takes the transcript path from hook stdin. `ckb-init` writes the block, `ckb-upgrade` leaves it alone | 1.5 | | 1.12.0 | 2026-10-16 | `ckb-add-conversation`: on request, copies the session's Claude Code transcript (JSONL, byte for byte) into `raw/saved-conversations/<date>/` with a readable `.md` rendering and an `index.md`; answers "did we discuss X" / "what did I tell you about Y" from those files. Saved conversations are outside retrieval and outside ingest until the user copies one into `raw/inbox/`. Rule E asks once at session end whether to save; `ckb-retrieve`, `ckb-ingest`, `ckb-reset` (tier 3) and `ckb-init` know the folder; smoke test renders a fixture transcript | 1.5 | diff --git a/docs/CHANGELOG.pl.md b/docs/CHANGELOG.pl.md index 30aa27f..8a38347 100644 --- a/docs/CHANGELOG.pl.md +++ b/docs/CHANGELOG.pl.md @@ -291,7 +291,8 @@ Niezależna od schematu treści powyżej. | Wersja | Data | Co weszło | Schemat | |---|---|---|---| -| **1.15.0** | 2026-10-16 | `tests/` tylko w repo szablonu: `ckb-init` już go nie kopiuje, `ckb-upgrade` go nie dostarcza (i raz proponuje usunięcie pozostałej kopii), kontrakt katalogów i dokumentacja o tym mówią. Sam test dymny bez zmian | 1.5 | +| **1.16.0** | 2026-10-21 | Tytuły sesji i rutyny. Pierwsza odpowiedź w nowej sesji (Reguła E) to pytanie „Jak nazwać tę rozmowę?” (przełącznik `conversations.ask_title`, domyślnie `true`); odpowiedź zapisuje `save_conversation.py --set-title` w ignorowanym przez gita `tmp/conversation-titles/` i nadaje nazwę zapisanemu transkryptowi (slug, nagłówek, wiersz indeksu) oraz blokowi w workload; ponowny zapis pod nowym tytułem zastępuje starą parę plików. Nowy `ckb-routine`: blok `routines:` w `ckb.yaml` (`name`/`do`/`every`/`confirm`/`last_run`), sprawdzany na starcie sesji przez `routines.py --due`; zaległe rutyny wykonują się po obsłużeniu prośby użytkownika w tej samej turze i są oznaczane `--mark` tylko po ukończeniu, `confirm: true` zamiast tego pyta, ręczne uruchomienia się liczą, `ckb-reset`/`ckb-sync-changes` odrzucane. `ckb-init` zapisuje oba bloki, `ckb-upgrade` ich nie rusza; test dymny obejmuje oba skrypty. D-0005 | 1.5 | +| 1.15.0 | 2026-10-16 | `tests/` tylko w repo szablonu: `ckb-init` już go nie kopiuje, `ckb-upgrade` go nie dostarcza (i raz proponuje usunięcie pozostałej kopii), kontrakt katalogów i dokumentacja o tym mówią. Sam test dymny bez zmian | 1.5 | | 1.14.0 | 2026-10-16 | Autorstwo we współdzielonych repozytoriach: tożsamość sesji (`git config user.name`/`user.email`, ustalana raz na starcie) opisuje każdą notatkę workload, każdy wpis `wiki/log.md` (nowa linia `**Author:**`, opcjonalna, neutralna dla lintu) i każdą zapisaną rozmowę (`save_conversation.py --author`). Pliki workload stają się jednym na osobę na dzień, `YYYY-MM-DD_<autor>_summary.md` z frontmatterem `type: session`, więc dwie osoby nigdy nie konfliktują w `workload/`; starsze pliki czytane jak dotąd. D-0004 | 1.5 | | 1.13.0 | 2026-10-16 | Przełącznik autozapisu rozmów: `conversations.autosave` w `ckb.yaml` (domyślnie `false`). Po włączeniu Reguła E zapisuje każdą sesję na jej końcu bez pytania; `ckb-add-conversation` przełącza go na żądanie („save conversations automatically”). Połowa per maszyna: `autosave_hook.py --check/--install/--remove` zarządza hookiem `Stop` Claude Code w ignorowanym przez gita `.claude/settings.local.json`; Reguła E uruchamia kontrolę na starcie sesji przy włączonym autozapisie i pyta przed zmianą konfiguracji maszyny; `save_conversation.py --from-hook` bierze ścieżkę transkryptu ze stdin hooka. `ckb-init` zapisuje blok, `ckb-upgrade` go nie rusza | 1.5 | | 1.12.0 | 2026-10-16 | `ckb-add-conversation`: na żądanie kopiuje transkrypt sesji Claude Code (JSONL, bajt w bajt) do `raw/saved-conversations/<data>/` wraz z czytelną wersją `.md` i `index.md`; odpowiada na „did we discuss X” / „what did I tell you about Y” z tych plików. Zapisane rozmowy są poza wyszukiwaniem i poza ingestem, dopóki użytkownik nie skopiuje jednej do `raw/inbox/`. Reguła E pyta raz na końcu sesji, czy zapisać; `ckb-retrieve`, `ckb-ingest`, `ckb-reset` (poziom 3) i `ckb-init` znają ten folder; test smoke renderuje transkrypt z fixture | 1.5 | diff --git a/docs/MANUAL.md b/docs/MANUAL.md index 3887ec4..073fb09 100644 --- a/docs/MANUAL.md +++ b/docs/MANUAL.md @@ -285,8 +285,8 @@ local wiki; this just gives repeated questions a better starting area. ## 3. Keeping it tidy -Say, whenever you like (there's no fixed schedule - do it after a big -ingest, or just periodically): +Say, whenever you like - after a big ingest, or just periodically (or let a +[routine](#routines-do-it-for-me-every-n-days) do it for you): > "Lint." @@ -336,6 +336,31 @@ safely can on its own and reports the rest for you to decide. Like Ingest, it finishes by reminding you to review and sync. Skill: `.agents/skills/ckb-lint/SKILL.md`. +### Routines: do it for me every N days + +Anything you would say to the agent can be made a routine: + +> "Lint every week." +> "Index external sources every 30 days, but ask me first." + +The agent records it in `ckb.yaml` under `routines:` (name, the phrase to +run, the period, whether to ask first, and the date it last ran). A routine +is time-since-last, not a calendar: at the start of every session the agent +checks which routines' periods have elapsed, answers whatever you asked +first, and then runs the due ones in the same turn, reporting each in one +line. One marked "ask me first" is offered at the end of the reply instead +and runs only on a yes. A routine that fails or is declined is not marked +done, so it comes back next session. Doing the action by hand counts too - +saying "Lint" yourself resets the weekly lint's clock. + +Because the last-run date is committed with the repo, a routine fires once +per period for everyone sharing the KB, not once per machine. Two actions +cannot be made routines: resetting the wiki and syncing with git. "List +routines", "which routines are due", "run the routines now" and "remove the +weekly lint" do what they say. This is not Claude Code's cloud scheduler: +nothing runs while nobody has the KB open. +Skill: `.agents/skills/ckb-routine/SKILL.md`. + ### Starting over: resetting to a clean template Sometimes you want the *shape* of a knowledge base without its contents - @@ -679,6 +704,14 @@ small enough to state directly. ### Save a conversation +Every new session starts with one question: "What should this conversation +be called?" The agent waits for the answer before doing anything else, and +the title then names the saved transcript and the session's block in +`workload/`. Say "rename this conversation to X" to change it later. If you +would rather not be asked, say "stop asking for a title" - the agent flips +`ask_title: false` under `conversations:` in `ckb.yaml` and falls back to +Claude Code's own session title. + Say "save this conversation" and the agent copies the session's transcript into `raw/saved-conversations/<YYYY-MM-DD>/` - the original JSONL that Claude Code keeps, byte for byte, plus a readable `.md` rendering of the @@ -882,6 +915,9 @@ ship it, so a knowledge base never carries it. | "Sync changes" / "Sync with git" | Commits, pulls, resolves conflicts, pushes to `origin` | `ckb-sync-changes` | | "Save this conversation" | Copies the session transcript (JSONL + readable `.md`) into `raw/saved-conversations/<date>/`; outside retrieval | `ckb-add-conversation` | | "Save conversations automatically" / "Turn off autosave" | Flips `conversations.autosave` in `ckb.yaml`; on, every session is saved at its end without asking | `ckb-add-conversation` | +| "Rename this conversation to X" / "Stop asking for a title" | Sets the session's title (used by the saved transcript and the workload note) / flips `conversations.ask_title` | `ckb-add-conversation` | +| "Lint every week" / "Index external sources every 30 days, ask me first" | Adds a routine to `ckb.yaml`; due routines run at session start, after your request | `ckb-routine` | +| "List routines" / "Which routines are due" / "Remove the weekly lint" | Shows, checks or removes routines | `ckb-routine` | | "Did we discuss X" / "What did I tell you about X" | Searches saved conversations and quotes the exchange | `ckb-add-conversation` | | "Quiz me on X" | One-off scored knowledge test | `ckb-quiz` | | "Teach me the wiki" / "Teach me about X" | Plans and runs a spaced-out course with progress tracking | `ckb-teach-me` | diff --git a/docs/MANUAL.pl.md b/docs/MANUAL.pl.md index c1eb8df..4c41265 100644 --- a/docs/MANUAL.pl.md +++ b/docs/MANUAL.pl.md @@ -297,8 +297,8 @@ jedną lokalną wiki; to tylko daje powracającym pytaniom lepszy punkt startowy ## 3. Utrzymanie porządku -Powiedz, kiedy chcesz (nie ma sztywnego harmonogramu — zrób to po dużym -ingest lub po prostu okresowo): +Powiedz, kiedy chcesz — po dużym ingest lub po prostu okresowo (albo niech +robi to za ciebie [rutyna](#rutyny-rób-to-za-mnie-co-n-dni)): > „Lint.” @@ -352,6 +352,34 @@ decyzja, co naprawić, a co oddać tobie). Naprawia samodzielnie to, co może zrobić bezpiecznie, a resztę zgłasza do twojej decyzji. Podobnie jak Ingest, na koniec przypomina o przejrzeniu i synchronizacji. Skill: `.agents/skills/ckb-lint/SKILL.md`. +### Rutyny: rób to za mnie co N dni + +Wszystko, co można powiedzieć agentowi, można zamienić w rutynę: + +> „Lint co tydzień.” +> „Indeksuj zewnętrzne źródła co 30 dni, ale najpierw mnie zapytaj.” + +Agent zapisuje ją w `ckb.yaml` w bloku `routines:` (nazwa, fraza do +wykonania, okres, czy pytać najpierw i data ostatniego uruchomienia). +Rutyna liczy czas od ostatniego uruchomienia, nie według kalendarza: na +starcie każdej sesji agent sprawdza, którym rutynom minął okres, najpierw +odpowiada na to, o co prosisz, a potem w tej samej turze wykonuje zaległe, +raportując każdą jedną linijką. Rutyna oznaczona „najpierw zapytaj” jest +zamiast tego proponowana na końcu odpowiedzi i uruchamia się tylko po +twojej zgodzie. Rutyna, która się nie powiodła albo została odrzucona, nie +jest oznaczana jako wykonana, więc wraca w następnej sesji. Ręczne +wykonanie też się liczy — gdy sam powiesz „Lint”, licznik tygodniowego +lintu startuje od nowa. + +Ponieważ data ostatniego uruchomienia jest commitowana z repozytorium, +rutyna odpala się raz na okres dla wszystkich pracujących w tej KB, a nie +raz na maszynę. Dwóch akcji nie da się zrobić rutyną: resetu wiki i +synchronizacji z gitem. „List routines”, „which routines are due”, „run the +routines now” i „remove the weekly lint” robią to, co mówią. To nie jest +chmurowy harmonogram Claude Code: nic się nie dzieje, gdy nikt nie ma KB +otwartej. +Skill: `.agents/skills/ckb-routine/SKILL.md`. + ### Zaczynanie od zera: reset do czystego szablonu Czasem chcesz zachować *kształt* bazy wiedzy bez jej zawartości — zwykle @@ -712,6 +740,14 @@ rozmowie, jeśli to wystarczająco krótkie, żeby podać wprost. ### Zapisywanie rozmowy +Każda nowa sesja zaczyna się od jednego pytania: „Jak nazwać tę rozmowę?” +Agent czeka na odpowiedź, zanim zrobi cokolwiek innego, a tytuł nadaje +potem nazwę zapisanemu transkryptowi i blokowi sesji w `workload/`. Powiedz +„rename this conversation to X”, by go później zmienić. Jeśli wolisz nie +być pytany, powiedz „stop asking for a title” — agent przestawi +`ask_title: false` w bloku `conversations:` w `ckb.yaml` i wróci do +własnego tytułu sesji Claude Code. + Powiedz „save this conversation”, a agent skopiuje transkrypt sesji do `raw/saved-conversations/<RRRR-MM-DD>/` — oryginalny plik JSONL, który przechowuje Claude Code, bajt w bajt, plus czytelną wersję `.md` tej samej @@ -924,6 +960,9 @@ wiedzy nigdy go nie zawiera. | „Save this conversation” | Kopiuje transkrypt sesji (JSONL + czytelne `.md`) do `raw/saved-conversations/<data>/`; poza wyszukiwaniem | `ckb-add-conversation` | | „Did we discuss X” / „What did I tell you about X” | Przeszukuje zapisane rozmowy i cytuje wymianę zdań | `ckb-add-conversation` | | „Save conversations automatically” / „Turn off autosave” | Przestawia `conversations.autosave` w `ckb.yaml`; po włączeniu każda sesja jest zapisywana na końcu bez pytania | `ckb-add-conversation` | +| „Rename this conversation to X” / „Stop asking for a title” | Ustawia tytuł sesji (używany przez zapisany transkrypt i notatkę workload) / przestawia `conversations.ask_title` | `ckb-add-conversation` | +| „Lint every week” / „Index external sources every 30 days, ask me first” | Dodaje rutynę do `ckb.yaml`; zaległe rutyny wykonują się na starcie sesji, po twojej prośbie | `ckb-routine` | +| „List routines” / „Which routines are due” / „Remove the weekly lint” | Pokazuje, sprawdza lub usuwa rutyny | `ckb-routine` | | „Quiz me on X” | Jednorazowy, punktowany sprawdzian wiedzy | `ckb-quiz` | | „Teach me the wiki” / „Teach me about X” | Planuje i prowadzi rozłożony w czasie kurs ze śledzeniem postępu | `ckb-teach-me` | | „Onboard me on X” / „Where do I start with X” | Krótka, prowadzona kolejność czytania po grafie | `ckb-onboard-me` | diff --git a/docs/decisions/0005-session-titles-and-routines.md b/docs/decisions/0005-session-titles-and-routines.md new file mode 100644 index 0000000..2727a27 --- /dev/null +++ b/docs/decisions/0005-session-titles-and-routines.md @@ -0,0 +1,88 @@ +--- +type: decision +tldr: A new session opens by asking for its title and waits for the answer; routines are repo-level, time-since-last actions declared in ckb.yaml, fired at session start after the user's request, with the last-run date committed so one person's run counts for everyone. +status: accepted +decided_on: 2026-10-21 +decided_by: Michał Kopeć +affects: AGENTS.md, ckb.yaml, .agents/skills/ckb-add-conversation/, .agents/skills/ckb-routine/, .agents/skills/ckb-init/, .agents/skills/ckb-upgrade/, docs/MANUAL.md +confidence: 0.85 +quality: 0.8 +last_updated: 2026-10-21 +freshness_window_days: 365 +retention: high +--- + +# D-0005 — Sessions are named up front; routines are time-since-last and shared + +**Status:** Accepted · **Decided:** 2026-10-21 · **Deciders:** Michał Kopeć + +## Context + +Saved conversations (1.12.0) and workload notes were named from Claude Code's +own AI title or the first user line, which produced names like "ckb-reset" +or "Commit first, clean everything". Separately, maintenance that should +happen regularly (lint, re-indexing an external source) happened only when +somebody remembered to ask, and nothing in the template could express +"do this every week". + +## Decision + +1. **Ask for the title first, and wait.** When `conversations.ask_title` + is `true` (the default), the first reply of a new session is the single + question "What should this conversation be called?" and no work starts + until it is answered. The title is stored per machine + (`tmp/conversation-titles/<session-id>.title`, via + `save_conversation.py --set-title`) so the autosave Stop hook and every + later save use it; it names the saved transcript and the workload block. + A first message that already names a title, a resumed session with a + stored title, and a non-interactive run skip the question. +2. **Routines are declared in `ckb.yaml`**, one item per routine with + `name`, `do` (a routing-table phrase, executed as if the user had said + it), `every` (`Nh|Nd|Nw`), `confirm` and `last_run`. A new skill, + `ckb-routine`, owns the block through a script that edits only the + routine's own lines. +3. **Due routines run after the user's request, in the same turn.** The + session-start check (`routines.py --due`) only collects them; the + user's first request is answered first, then each due routine runs and + is reported in one line. `confirm: true` turns that into a question at + the end of the reply. Only a completed action is marked; a failed or + declined one returns next session. A manual run of the same action + also marks the routine. +4. **`last_run` is committed**, so a routine fires once per period for the + whole repo, not once per clone. The trade-off is an occasional one-line + merge conflict when two people fire the same routine on different days; + the later date wins. +5. `ckb-reset` and `ckb-sync-changes` cannot be routines: one is + destructive, the other touches the remote. + +## Alternatives considered + +- *Ask the title inline and keep working.* Cheaper by one round-trip, but + the first turn's work would be saved under a derived title until the + answer arrived, and the hook would have already written files under the + wrong slug. The user chose the hard ask. +- *Run due routines before the first request.* Simplest rule, but a slow + routine (ingest, external index) would sit between the user and their + answer. +- *Always ask before running a routine.* Not automatic; kept as the + per-routine `confirm` option instead. +- *Per-machine routine state under `tmp/`.* Would make a weekly lint run + once per clone per week; the repo is what needs linting, not the clone. +- *Derive the last run from `wiki/log.md`.* Fragile: not every action + writes to the wiki log, and parsing free-text `Source:` lines to decide + whether to run something is guesswork. +- *Claude Code's cloud scheduler / `/loop`.* Needs a running agent and + lives outside the repo, so it is neither shared nor offline. Documented + as a different tool, not a replacement. + +## Consequences + +- `ckb.yaml` gains `conversations.ask_title` and `routines:`; `ckb-init` + writes both, `ckb-upgrade` and `ckb-module` leave them as found. +- Rule E grows two steps (the title question first, the routine check + last). Without Python the routine check is skipped, consistent with + D-0003. +- The smoke test covers `--set-title` (slug and heading follow the stored + title, the old pair is removed) and `routines.py` (`--due` golden output, + `--mark`/`--add`/`--remove` touch only the expected lines). +- Schema stays 1.5: no page field changes. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 4bdbc75..46161e9 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -18,3 +18,4 @@ but they live here, in the template layer, because: | [D-0002](0002-software-module-design.md) | The `software` module: gitignored `src/` clones, two OpenSpec spec levels, hybrid vendoring | | [D-0003](0003-python-runtime-with-degraded-fallbacks.md) | Python stays the only scripting runtime; portable interpreter resolution, per-OS install guidance, a native fallback for the session-start check, degraded paths per skill | | [D-0004](0004-session-identity-from-git.md) | The git identity is the session's author; one workload file per person per day; `**Author:**` on log entries and saved conversations | +| [D-0005](0005-session-titles-and-routines.md) | A new session asks for its title first and waits; routines are time-since-last actions in `ckb.yaml`, run after the user's request, with `last_run` committed | diff --git a/tests/expected/routines-due.txt b/tests/expected/routines-due.txt new file mode 100644 index 0000000..8b028b4 --- /dev/null +++ b/tests/expected/routines-due.txt @@ -0,0 +1 @@ +weekly-lint Lint overdue by 7d diff --git a/tests/fixtures/minimal-kb/ckb.yaml b/tests/fixtures/minimal-kb/ckb.yaml new file mode 100644 index 0000000..f98a515 --- /dev/null +++ b/tests/fixtures/minimal-kb/ckb.yaml @@ -0,0 +1,22 @@ +# Fixture manifest for the smoke test. +template: + repo: https://git.wierzbowa.cloud/michal/ckb.git + branch: main + +kb_modules: [] + +conversations: + autosave: false + ask_title: true + +routines: + - name: weekly-lint + do: "Lint" + every: 7d + confirm: false + last_run: 2026-09-10 # due at TODAY=2026-09-24 (overdue by 7d) + - name: monthly-index + do: "Index external sources" + every: 30d + confirm: true + last_run: 2026-09-20 # not due until 2026-10-20 diff --git a/tests/smoke.sh b/tests/smoke.sh index a0869a2..c2b6bf1 100755 --- a/tests/smoke.sh +++ b/tests/smoke.sh @@ -22,11 +22,26 @@ python3 "$RETR" "how many times does Atlas retry a failed batch" --root "$FIX" - # Conversation rendering must be stable: same fixture transcript, same Markdown. mkdir -p "$TMP/conv" && python3 "$SAVE" --from tests/fixtures/conversation/session.jsonl --root "$TMP/conv" --today "$TODAY" --author "Fixture User <fixture@example.com>" > /dev/null cp "$TMP"/conv/raw/saved-conversations/"$TODAY"/*.md "$TMP/conversation.md" +# A title set with --set-title must win over the transcript's own title and rename the saved pair. +mkdir -p "$TMP/titled" && ENC=$(python3 -c "import re,sys;print(re.sub(r'[^A-Za-z0-9]','-',sys.argv[1]))" "$(cd "$TMP/titled" && pwd -P)") \ + && mkdir -p "$TMP/cfg/projects/$ENC" && cp tests/fixtures/conversation/session.jsonl "$TMP/cfg/projects/$ENC/" +( cd "$TMP/titled" && CLAUDE_CONFIG_DIR="$TMP/cfg" python3 "$OLDPWD/$SAVE" --today "$TODAY" --author "Fixture User <fixture@example.com>" >/dev/null \ + && CLAUDE_CONFIG_DIR="$TMP/cfg" python3 "$OLDPWD/$SAVE" --set-title "Smoke Title" >/dev/null \ + && CLAUDE_CONFIG_DIR="$TMP/cfg" python3 "$OLDPWD/$SAVE" --today "$TODAY" --author "Fixture User <fixture@example.com>" >/dev/null ) +ls "$TMP/titled/raw/saved-conversations/$TODAY" > "$TMP/titled.txt" +# Routines: due list is deterministic for the fixture; edits touch only the routine's own lines. +ROUT=.agents/skills/ckb-routine/scripts/routines.py +( python3 "$ROUT" --due --root "$FIX" --today "$TODAY" || true ) > "$TMP/routines-due.txt" +cp "$FIX/ckb.yaml" "$TMP/ckb.yaml" +python3 "$ROUT" --root "$TMP" --mark weekly-lint --today "$TODAY" >/dev/null +python3 "$ROUT" --root "$TMP" --add --name smoke --do "Lint" --every 2w >/dev/null +python3 "$ROUT" --root "$TMP" --remove smoke >/dev/null if [[ "${1:-}" == "--update" ]]; then cp "$TMP/lint.json" tests/expected/lint.json cp "$TMP/retrieve.json" tests/expected/retrieve.json cp "$TMP/conversation.md" tests/expected/conversation.md + cp "$TMP/routines-due.txt" tests/expected/routines-due.txt echo "golden files updated"; exit 0 fi @@ -35,6 +50,11 @@ for f in lint retrieve; do if ! diff -u "tests/expected/$f.json" "$TMP/$f.json"; then echo "DRIFT: $f"; fail=1; fi done if ! diff -u tests/expected/conversation.md "$TMP/conversation.md"; then echo "DRIFT: conversation"; fail=1; fi +[[ "$(cat "$TMP/titled.txt")" == $'smoke-title_0f1e2d3c.jsonl\nsmoke-title_0f1e2d3c.md' ]] || { echo "set-title: unexpected files: $(cat "$TMP/titled.txt")"; fail=1; } +grep -q '^# Smoke Title$' "$TMP/titled/raw/saved-conversations/$TODAY/smoke-title_0f1e2d3c.md" || { echo "set-title: heading not applied"; fail=1; } +if ! diff -u tests/expected/routines-due.txt "$TMP/routines-due.txt"; then echo "DRIFT: routines-due"; fail=1; fi +[[ "$(diff "$FIX/ckb.yaml" "$TMP/ckb.yaml" | grep -c '^[<>]')" == "2" ]] || { echo "routines: --mark/--add/--remove changed more than the last_run line"; diff "$FIX/ckb.yaml" "$TMP/ckb.yaml"; fail=1; } +grep -q 'last_run: 2026-09-24' "$TMP/ckb.yaml" || { echo "routines: --mark did not stamp today"; fail=1; } if ! diff -u "$TMP/quick.py.txt" "$TMP/quick.sh.txt"; then echo "DRIFT: lint_quick.sh disagrees with lint_report.py --quick"; fail=1; fi top=$(python3 -c "import json;print(json.load(open('$TMP/retrieve.json'))['candidates'][0]['path'])") [[ "$top" == "wiki/entities/atlas-retry-policy.md" ]] || { echo "retrieve: expected atlas-retry-policy first, got $top"; fail=1; } diff --git a/workload/2026-10-21_michal-kopec_summary.md b/workload/2026-10-21_michal-kopec_summary.md new file mode 100644 index 0000000..7779874 --- /dev/null +++ b/workload/2026-10-21_michal-kopec_summary.md @@ -0,0 +1,28 @@ +--- +type: session +author: Michał Kopeć +author_email: michal.kopec@aol.pl +date: 2026-10-21 +--- + +# 2026-10-21 — Michał Kopeć + +## Template 1.16.0: session titles and routines + +- Planned with the user (plan mode): title question is ask-first-and-wait; + due routines run after the user's request in the same turn; `last_run` + committed in `ckb.yaml`. Recorded as D-0005. +- `save_conversation.py`: `--set-title` stores a per-session title in + `tmp/conversation-titles/`; precedence `--title` → stored → `/rename` → + AI title → first line; a re-save under a new title removes the old pair. +- New skill `ckb-routine` with `routines.py` (`--due/--list/--mark/--add/--remove`, + line-level edits of the `routines:` block; refuses reset/sync). +- `AGENTS.md` Rule E: title question first; fourth cheap check `routines.py --due`; + firing and marking rules. Routing table and disambiguation gain `ckb-routine`. +- `ckb.yaml`: `conversations.ask_title: true`, `routines: []`; `ckb-init`, + `ckb-upgrade`, `ckb-reset` SKILL.md updated accordingly. +- Docs: CHANGELOG (EN/PL) 1.16.0 row, MANUAL (EN/PL) routines subsection, + title paragraph and quick-reference rows, README (EN/PL), `VERSION` 1.16.0. +- Tests: fixture `ckb.yaml`, golden `routines-due.txt`, smoke checks for + `--set-title` and routine edits. `tests/smoke.sh`: OK. `lint --quick`: clean. +- Nothing under `wiki/` changed; no `wiki/log.md` entry. Not committed.