hubkit-cli 0.2.2__tar.gz → 0.2.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/CHANGELOG.md +14 -0
  2. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/PKG-INFO +1 -1
  3. hubkit_cli-0.2.4/dist-0.2.4/.gitignore +1 -0
  4. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/docs/architecture.md +3 -2
  5. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/docs/commands.md +1 -0
  6. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/docs/configuration.md +1 -1
  7. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/pyproject.toml +1 -1
  8. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/scripts/hubcore/cli.py +27 -1
  9. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/scripts/hubcore/gate.py +4 -2
  10. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/scripts/hubcore/hooks.py +80 -12
  11. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/scripts/hubcore/install.py +1 -0
  12. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/scripts/hubcore/lessons.py +40 -0
  13. hubkit_cli-0.2.4/scripts/hubcore/playbooks.py +132 -0
  14. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/scripts/hubcore/routed.py +24 -9
  15. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/scripts/hubcore/status.py +1 -1
  16. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/tests/run_reverts.py +2 -0
  17. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/tests/test_hubkit.py +42 -0
  18. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/tests/test_install.py +1 -1
  19. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/tests/test_lessons.py +51 -0
  20. hubkit_cli-0.2.4/tests/test_playbooks.py +64 -0
  21. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/tests/test_review_chain.py +38 -0
  22. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/tests/test_state_rules.py +14 -0
  23. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/.gitignore +0 -0
  24. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/CLAUDE.md +0 -0
  25. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/CONTRIBUTING.md +0 -0
  26. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/LICENSE +0 -0
  27. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/README.md +0 -0
  28. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/SECURITY.md +0 -0
  29. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/SKILL.md +0 -0
  30. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/config.example.toml +0 -0
  31. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/docs/troubleshooting.md +0 -0
  32. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/intents.example.toml +0 -0
  33. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/references/design-sources.md +0 -0
  34. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/references/research.md +0 -0
  35. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/scripts/hubcore/__init__.py +0 -0
  36. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/scripts/hubcore/compat.py +0 -0
  37. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/scripts/hubcore/config.py +0 -0
  38. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/scripts/hubcore/inbound.py +0 -0
  39. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/scripts/hubcore/learnings.py +0 -0
  40. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/scripts/hubcore/ledger.py +0 -0
  41. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/scripts/hubcore/orders.py +0 -0
  42. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/scripts/hubcore/redact.py +0 -0
  43. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/scripts/hubcore/slow.py +0 -0
  44. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/scripts/hubcore/store.py +0 -0
  45. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/scripts/hubcore/trust.py +0 -0
  46. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/scripts/hubcore/watcher.py +0 -0
  47. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/scripts/hubkit +0 -0
  48. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/scripts/learn.py +0 -0
  49. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/skills/hub-mep/SKILL.md +0 -0
  50. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/skills/hubkit-setup/SKILL.md +0 -0
  51. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/tests/conftest.py +0 -0
  52. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/tests/test_blockers.py +0 -0
  53. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/tests/test_compat.py +0 -0
  54. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/tests/test_guards2.py +0 -0
  55. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/tests/test_inbound.py +0 -0
  56. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/tests/test_learning_rules.py +0 -0
  57. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/tests/test_ledger.py +0 -0
  58. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/tests/test_own_work.py +0 -0
  59. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/tests/test_peer_reports.py +0 -0
  60. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/tests/test_slow.py +0 -0
  61. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/tests/test_tool_guards.py +0 -0
  62. {hubkit_cli-0.2.2 → hubkit_cli-0.2.4}/tests/test_watcher.py +0 -0
@@ -4,6 +4,20 @@ All notable changes to this project are recorded here. The format follows [Keep
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.2.4] - 2026-11-09
8
+
9
+ ### Added
10
+ - `hubkit how ls|show|save|match`: playbooks (command -> how -> do). Matching steps are injected on a matching prompt; a NO PLAYBOOK flag and a Stop hold until `how save` runs.
11
+
12
+ ### Fixed
13
+ - Text inside `<pasted_content>` is stripped before order, playbook and draft matching, so pasted text opens no order.
14
+
15
+ ## [0.2.3] - 2026-11-06
16
+
17
+ ### Fixed
18
+ - A job whose title leads with a change verb ("Fix #7 review findings") is not a review item, unless one of its sentences naming the PR leads with a review.
19
+ - The review hard limit (`routed.review_overdue_min`) is raised to the item's own stated `Estimate:` when that is longer.
20
+
7
21
  ## [0.2.2] - 2026-11-06
8
22
 
9
23
  ### Fixed
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: hubkit-cli
3
- Version: 0.2.2
3
+ Version: 0.2.4
4
4
  Summary: Session supervisor for Claude Code: hooks-based multi-agent orchestration with order clocks, routed-work tracking, a watchdog and a stop gate, standard library only.
5
5
  Project-URL: Repository, https://github.com/ankitkpandey1/hubkit
6
6
  Project-URL: Documentation, https://github.com/ankitkpandey1/hubkit/tree/main/docs
@@ -0,0 +1 @@
1
+ *
@@ -41,10 +41,11 @@ State lives in `$HUBKIT_STATE`, else `$XDG_STATE_HOME/hubkit` (default `~/.local
41
41
 
42
42
  | Event | Hook | What it does |
43
43
  |---|---|---|
44
- | SessionStart | `session` | Prints the `hubkit:` status block. If the bind is dead and this session resumed the bound session id (or has the configured hub name in the bound cwd), re-binds and prints one line. Never takes over a live hub. |
44
+ | SessionStart | `session` | Prints the `hubkit:` status block. If the bind is dead and this session resumed the bound session id (or has the configured hub name in the bound cwd), re-binds and prints one line. Never takes over a live hub. Also sets the `needs_reload` marker in the state dir; the prompt hook prints, and the Stop hook blocks on, "hub skill not loaded since compaction" until the `skill` hook sees the `hub` skill load. |
45
45
  | UserPromptSubmit | `prompt` | Runs the intake on the typed prompt (see Orders), prints the order lines, `OVERDUE` clock breaches, the status block, and a `CORRECTION` line when the learn loop applies. |
46
46
  | PostToolUse `AskUserQuestion` | `answer` | A card answer goes through the same intake and human-only filter as a typed prompt, and closes `ask` work items. |
47
47
  | PostToolUse `SendMessage\|Agent` | `routed` | Records or refreshes a routed-work item (see Routed work). One `gh` baseline read per named PR, 3 s in total. |
48
+ | PostToolUse `Skill` | `skill` | Loading the `hub` skill clears the `needs_reload` marker. Any other skill leaves it. |
48
49
  | Stop | `stop` | The gate. Prints JSON `{"decision": "block", "reason": ...}` while the hub owes something. |
49
50
  | PreToolUse `Bash\|TaskStop\|AskUserQuestion` | `pretool` | Warn-only guard; the warning goes in as additional context and nothing is ever denied. It warns on: `gh pr merge` with no live order and none of his typed words naming the PR; a post to a person or thread (`mep send|reply|post`, a chat send, `gh pr|issue comment|review`, a `gh api` comments or reviews call, or a Slack post or send) with no typed yes of his in the last 10 minutes; a banned command (`rm -rf`, `pkill`, `git reset --hard`, `git stash`, `git clean`, a forced push, `git checkout <ref> -- <path>`); the same command run 3 times in 10 minutes; `pytest` with no path, `-k` or `-m`; `TaskStop` without a stop word of his in the last 30 minutes; a decision card whose first option is not marked (Recommended). Register it with `hubkit hooks --merge-guard`, or add it to `settings.json` yourself. |
50
51
  | any | `record` | Schema canary. Every hub run writes the real payload's keys and value types (never values) to `payload-samples/`. |
@@ -67,7 +68,7 @@ A routed item is one outcome per (owner, PR number), or per owner when no PR is
67
68
 
68
69
  - **Tracked:** a message naming a PR (URL, `PR 12`, bare `#123` resolved against `routed.repo`) or at least `min_chars` characters, and background `Agent` launches whose brief asks for a result (`Done-when`, `Output`, a PR). **Not tracked:** acknowledgements, short messages without a PR, `skip_owners`, foreground agents, standing watchers (`skip_briefs`), and a reply to a peer who wrote to the hub within `reply_window_min`.
69
70
  - **Asks and chases.** Only a new brief is a new ask. Any later non-acknowledgement message to the same owner is a chase: it is counted, never resets the ask's clock, and clears a moved-head or old-head-verdict flag.
70
- - **Reviews.** A message naming a PR and a `review_words` word ("review #N", "needs a review", "can I get a review on #N") makes a review item, unless it opens with a change verb (fix, address, resolve, apply, ...) and the review word names an existing review ("fix the findings in his review of #N"), on a short clock (`review_stall_min`, hard `OVERDUE` at `review_overdue_min`). It closes itself, PR by PR, when GitHub shows a review by someone other than the author at the PR's current head (on a PR written by `user.github_login`, a COMMENT review with a body counts too, because the reviewer peer posts as that account; an empty-body COMMENT is an inline-thread reply and does not). A review on an older head never closes it. One PR per clock: a message naming several PRs is a queue; "after X's queue" phrasing delays the clock by `queued_wait_min`.
71
+ - **Reviews.** A message naming a PR and a `review_words` word ("review #N", "needs a review", "can I get a review on #N") makes a review item, unless it opens with a change verb (fix, address, resolve, apply, ...) and the review word names an existing review ("fix the findings in his review of #N"), on a short clock (`review_stall_min`, hard `OVERDUE` at `review_overdue_min`, or at the brief's own `Estimate:` when that is longer). A job whose title leads with a change verb is not a review item unless a sentence naming the PR leads with a review. It closes itself, PR by PR, when GitHub shows a review by someone other than the author at the PR's current head (on a PR written by `user.github_login`, a COMMENT review with a body counts too, because the reviewer peer posts as that account; an empty-body COMMENT is an inline-thread reply and does not). A review on an older head never closes it. One PR per clock: a message naming several PRs is a queue; "after X's queue" phrasing delays the clock by `queued_wait_min`.
71
72
  - **Heard-from.** A peer message or task notification in the hub transcript, a review on the PR, or a background agent whose transcript or output file is still growing (`routed.activity_globs`) updates the last-heard time.
72
73
  - **Ladder.** Silence past `stall_min` climbs: step 1 a one-line state ask, step 2 a re-brief to another owner (not while the owner reported within the limit), step 3 tell the user. Every item shows one `NEXT:` action.
73
74
 
@@ -19,6 +19,7 @@
19
19
  | `hubkit digest [--since 12h]` | What finished, which orders closed, the latest alerts, what waits on the user, the PRs his account opened and what each peer session was asked, for a user coming back. |
20
20
  | `hubkit inbound ingest [--file F]` | Turns the inbox watcher's lines into `reply` work items (one per asker, no duplicates). |
21
21
  | `hubkit trust record --class C --outcome O` / `trust ls` | Per-class record of approved and corrected outcomes; a class with repeated corrections is shown as ask-first. |
22
+ | `hubkit how ls` / `show NAME` / `match TEXT` / `save NAME --trigger X --steps-file F --quote Q [--replace]` | Playbooks in `<config dir>/playbooks/`: a prompt that matches a trigger gets the steps injected; an order or imperative prompt with none is told to save one, and the Stop hook holds the turn end until it is. `--replace` keeps the old file as `.bak-<date>`. |
22
23
  | `hubkit work verify ID` | Stamp the item as checked against reality just now. An `active` or `priority` item not verified for `watcher.verify_stale_min` raises an alert. It runs no check itself. |
23
24
  | `hubkit find WORD [--since 2d]` | Searches orders, work, the archive, his asks, peer session prompts and the PRs his account opened (title, body, changed file paths). Needs `gh` for the PR part; a `gh` failure is printed as UNKNOWN, never skipped. Read only on peer sessions; prompts are redacted. |
24
25
  | `hubkit asks ls [--since 12h]` | His recent prompts (from `recent-prompts.jsonl`), one line each, newest last. Marks the asks as re-read for the Stop gate. |
@@ -102,7 +102,7 @@ Estimates and the slowness check (hub-internal, see architecture).
102
102
  | `stall_min` | `15` | Silence from the owner this long is STALLED; the ladder steps at multiples of it. |
103
103
  | `review_words` | `["review"]` | A message naming a PR and one of these is a review item. |
104
104
  | `review_stall_min` | `5` | Reviews: chase after this. |
105
- | `review_overdue_min` | `10` | Reviews: hard OVERDUE this long after routing, whatever the owner said. |
105
+ | `review_overdue_min` | `10` | Reviews: hard OVERDUE this long after routing, whatever the owner said. A review brief with its own `Estimate: Nm` line (not a defaulted one) gets the larger of this and N. |
106
106
  | `skip_owners` | `["inbox"]` | Owners that are never tracked. |
107
107
  | `max_agents` | `4` | More distinct agents than this holding live routed work makes the routed hook warn. |
108
108
  | `min_chars` | `200` | A message without a PR is work only from this length. |
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "hubkit-cli"
7
- version = "0.2.2"
7
+ version = "0.2.4"
8
8
  description = "Session supervisor for Claude Code: hooks-based multi-agent orchestration with order clocks, routed-work tracking, a watchdog and a stop gate, standard library only."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.14"
@@ -11,11 +11,28 @@ import time
11
11
  import tomllib
12
12
  from pathlib import Path
13
13
 
14
- from . import compat, config, hooks, inbound, install, ledger, lessons, routed, status, store, trust, watcher
14
+ from . import compat, config, hooks, inbound, install, ledger, lessons, playbooks, routed, status, store, trust, watcher
15
15
  from .orders import Orders
16
16
  from .redact import count_hits_text
17
17
 
18
18
 
19
+ def cmd_how(a: argparse.Namespace, cfg: dict) -> int:
20
+ if a.action == "ls":
21
+ print("\n".join(f"{pb['name']}: {', '.join(pb['triggers'])}" for pb in playbooks.load_all()) or "no playbooks")
22
+ elif a.action == "show":
23
+ pb = playbooks.get(a.arg)
24
+ print(f"{pb['name']} (updated {pb['updated']}; triggers: {', '.join(pb['triggers'])})\n{pb['steps']}")
25
+ print("".join(f"quote: {q}\n" for q in pb["quotes"]), end="")
26
+ elif a.action == "match":
27
+ print("\n".join(playbooks.inject(playbooks.match(a.arg))) or "NO PLAYBOOK")
28
+ else:
29
+ if not a.steps_file:
30
+ raise ValueError("save needs --steps-file")
31
+ print(playbooks.save(a.arg, a.trigger, Path(a.steps_file).expanduser().read_text(encoding="utf-8"), a.quote, a.replace))
32
+ playbooks.note_saved(cfg, time.time())
33
+ return 0
34
+
35
+
19
36
  def kv(pairs: list[str]) -> dict[str, str]:
20
37
  """Parse repeated NAME=VALUE arguments into a dict."""
21
38
  out = {}
@@ -270,6 +287,13 @@ def main(argv: list[str] | None = None) -> int:
270
287
  fd.add_argument("--since", default="2d", help="how far back for asks, peer prompts and PRs, for example 12h, 2d")
271
288
  dg = sub.add_parser("digest")
272
289
  dg.add_argument("--since", default="12h", help="how far back, for example 30m, 12h, 2d")
290
+ hw = sub.add_parser("how", help="playbooks: how his recurring commands are done")
291
+ hw.add_argument("action", choices=["ls", "show", "save", "match"])
292
+ hw.add_argument("arg", nargs="?", default="", help="show/save: the playbook name; match: the text")
293
+ hw.add_argument("--trigger", action="append", default=[], help="save: a word or phrase, or re:<regex>; repeatable")
294
+ hw.add_argument("--steps-file", default="")
295
+ hw.add_argument("--quote", action="append", default=[], help="save: his words that asked for this")
296
+ hw.add_argument("--replace", action="store_true", help="save: overwrite an existing playbook (the old one is kept as .bak-<date>)")
273
297
  e = sub.add_parser("eod")
274
298
  e.add_argument("--day")
275
299
  e.add_argument("--note", default="")
@@ -304,6 +328,8 @@ def main(argv: list[str] | None = None) -> int:
304
328
  print(trust.record(cfg, a.cls, a.outcome) if a.action == "record" else "\n".join(f"{c}: {m}" for c, m in sorted(trust.mode(cfg).items())) or "no outcomes recorded")
305
329
  elif a.cmd == "inbound":
306
330
  print("\n".join(inbound.ingest(cfg, Path(a.file).read_text(encoding="utf-8") if a.file else sys.stdin.read())) or "nothing new")
331
+ elif a.cmd == "how":
332
+ return cmd_how(a, cfg)
307
333
  elif a.cmd == "asks":
308
334
  print("\n".join(lessons.asks_lines(cfg, a.since)))
309
335
  elif a.cmd == "watch":
@@ -5,7 +5,7 @@ from __future__ import annotations
5
5
  import re
6
6
  import time
7
7
 
8
- from . import lessons, routed, slow, store
8
+ from . import lessons, playbooks, routed, slow, store
9
9
  from .orders import PR_REF, Orders
10
10
  from .status import work_load
11
11
 
@@ -149,7 +149,7 @@ def stop_reasons(cfg: dict, last: str, now: float | None = None, transcript: str
149
149
  reasons += blocker_reasons(cfg, last, now)
150
150
  if r := lessons.unpushed_work(last, cwd, transcript):
151
151
  reasons.append(r)
152
- reasons += [r for r in (lessons.unswept_asks(cfg, last, now), lessons.unchecked_claim(cfg, last, transcript), lessons.unrun_claim(cfg, last, transcript)) if r]
152
+ reasons += [r for r in (lessons.unswept_asks(cfg, last, now), lessons.unchecked_claim(cfg, last, transcript), lessons.pending_claim(cfg, last, transcript), lessons.unrun_claim(cfg, last, transcript)) if r]
153
153
  if refs := lessons.bare_refs(cfg, last):
154
154
  reasons.append(f"hubkit: your message names {', '.join(refs[:4])} with no link. NEXT: give the full URL of each PR or issue so he can click it")
155
155
  try:
@@ -165,6 +165,8 @@ def stop_reasons(cfg: dict, last: str, now: float | None = None, transcript: str
165
165
  "(agent words are not evidence). NEXT: correct the message; relay a verdict only after the item closes itself")
166
166
  if ci_bad:
167
167
  reasons.append(f"hubkit: your message approves {', '.join(ci_bad)} but CI at the head is not green. NEXT: say CI is not green, or wait for it, before relaying an approval")
168
+ if cmd := playbooks.missing(cfg):
169
+ reasons.append(f"hubkit: '{cmd}' was done with no playbook to follow, and none was saved. NEXT: hubkit how save <name> --trigger <word> --steps-file <file> --quote \"<his words>\"")
168
170
  if (r := lessons.prose_ask(last, transcript, is_question(cfg, last) and blocked_on_user(cfg))):
169
171
  reasons.append(r)
170
172
  if is_question(cfg, last) and not blocked_on_user(cfg):
@@ -11,8 +11,8 @@ import traceback
11
11
  from pathlib import Path
12
12
  from typing import TypeGuard
13
13
 
14
- from . import compat, config, gate, lessons, routed, store
15
- from .orders import Orders, hook_intake
14
+ from . import compat, config, gate, lessons, playbooks, routed, status, store
15
+ from .orders import Orders, _word_re, hook_intake
16
16
  from .redact import redact
17
17
  from .status import read_status, render_block
18
18
 
@@ -103,6 +103,15 @@ def is_hub(cfg: dict, payload: dict) -> bool:
103
103
 
104
104
  # ---- the hooks ----
105
105
 
106
+ RELOAD_MARK = "needs_reload"
107
+ RELOAD_LINE = "hubkit: hub skill not loaded since compaction. NEXT: Skill hub, then read the overlay (hubkit doctor prints its path)"
108
+
109
+
110
+ def reload_line(cfg: dict) -> str:
111
+ """The reload order while the hub skill has not been loaded since the last SessionStart, else empty."""
112
+ return RELOAD_LINE if (store.state(cfg, create=False) / RELOAD_MARK).exists() else ""
113
+
114
+
106
115
  def _session_by_id(cfg: dict, session_id: str | None) -> tuple[int | None, dict | None]:
107
116
  """The running session file for this session id (the hook payload names it)."""
108
117
  for f in config.sessions_dir(cfg).glob("*.json"):
@@ -137,7 +146,9 @@ def hook_session(cfg: dict, payload: dict) -> str:
137
146
  if pid is None:
138
147
  return "" # nothing printed, nothing written outside the bound hub
139
148
  rebound = f"hubkit: {bind(cfg, pid)}; the old bind was dead (re-bound by the SessionStart hook)\n"
140
- store.touch_seen(store.state(cfg), "session")
149
+ sd = store.state(cfg)
150
+ store.touch_seen(sd, "session")
151
+ store.write_atomic(sd / RELOAD_MARK, str(time.time()))
141
152
  return rebound + render_block(cfg, Orders(cfg), read_status(cfg))
142
153
 
143
154
 
@@ -145,7 +156,7 @@ def _words(text: str) -> set[str]:
145
156
  return {w for w in re.findall(r"[a-z0-9']+", text.lower()) if len(w) > 2}
146
157
 
147
158
 
148
- def correction_line(orders: Orders, sd: Path, text: str, now: float) -> str:
159
+ def correction_line(orders: Orders, sd: Path, text: str, now: float, matched: list[str] | None = None) -> str:
149
160
  """Detect a correction (configured phrases, or the same instruction repeated) and inject a record prompt."""
150
161
  cfg = orders.intents.get("corrections", {})
151
162
  why = ""
@@ -168,9 +179,12 @@ def correction_line(orders: Orders, sd: Path, text: str, now: float) -> str:
168
179
  if not why:
169
180
  return ""
170
181
  quote = redact(text)[0][:200]
182
+ for name in matched or []:
183
+ playbooks.add_quote(name, quote)
184
+ kept = "".join(f"\nhubkit: update playbook {n} if a step was wrong (the quote is added to it)" for n in matched or [])
171
185
  return (f'hubkit CORRECTION ({why}): record it this turn. Quote: "{quote}". '
172
186
  "Run learn.py add --class <existing-or-new-kebab> --gate <G1..G8> --quote <the words> "
173
- "--situation .. --wrong .. --right .. --evidence .. (reuse a class from the block if it is the same mistake).")
187
+ "--situation .. --wrong .. --right .. --evidence .. (reuse a class from the block if it is the same mistake)." + kept)
174
188
 
175
189
 
176
190
  def unordered_chase_lines(cfg: dict, orders: Orders, text: str, now: float) -> list[str]:
@@ -186,23 +200,63 @@ def unordered_chase_lines(cfg: dict, orders: Orders, text: str, now: float) -> l
186
200
  return ["hubkit: no order is live, so this chase is on the job list:", *(slow.block_lines(jobs, now) or ["no live job either: say so plainly"])]
187
201
 
188
202
 
203
+ PASTED = re.compile(r"(?is)<pasted_content>.*?</pasted_content>")
204
+ DRAFT = re.compile(r"(?i)\bdraft\b")
205
+ DISCARD = re.compile(r"(?i)\b(?:discard|drop|scrap|forget)\b[^.\n]{0,30}\bdraft\b")
206
+ SEND = re.compile(r"\bmep\s+send\b")
207
+
208
+
209
+ def draft_items(cfg: dict) -> list[dict]:
210
+ return [i for i in status.work_load(store.state(cfg)) if i.get("kind") == "active" and i["title"].startswith("draft: ")]
211
+
212
+
213
+ def close_drafts(cfg: dict, note: str) -> None:
214
+ for i in draft_items(cfg):
215
+ status.work_done(cfg, i["id"], note)
216
+
217
+
218
+ def draft_intake(cfg: dict, text: str) -> None:
219
+ """A typed ask for a draft opens one work item; discarding the draft closes it (`mep send` closes it in the pretool hook)."""
220
+ if DISCARD.search(text):
221
+ close_drafts(cfg, "discarded")
222
+ elif DRAFT.search(text) and not draft_items(cfg):
223
+ status.work_add(cfg, "active", "draft: " + " ".join(text.split())[:80], note="open until `mep send` or discarded")
224
+
225
+
226
+ def no_playbook(cfg: dict, orders: Orders, text: str, before: set[str], pbs: list[dict], now: float) -> list[str]:
227
+ """When an order opened or the prompt is an imperative statement and no playbook matched: owe a playbook once it is done."""
228
+ words = orders.intents.get("intake", {}).get("imperative", [])
229
+ imperative = bool(words) and len(text) <= 300 and not text.rstrip().endswith("?") and bool(_word_re(words).search(text))
230
+ if pbs or not ({o["id"] for o in orders.live()} - before or imperative):
231
+ return []
232
+ cmd = " ".join(text.split())[:60]
233
+ playbooks.note_missing(cfg, cmd, now)
234
+ return [f"NO PLAYBOOK for '{cmd}': when done, save the steps with hubkit how save <name> --trigger ... --steps-file ..."]
235
+
236
+
189
237
  def hook_prompt(cfg: dict, payload: dict) -> str:
190
238
  """UserPromptSubmit hook: open, chase, hold or cancel orders from the user's words; inject correction and overdue lines."""
191
239
  if not is_hub(cfg, payload):
192
240
  return ""
193
241
  sd = store.state(cfg)
194
242
  store.touch_seen(sd, "prompt")
195
- text = payload.get("prompt") or ""
243
+ text = PASTED.sub(" ", payload.get("prompt") or "") # words inside pasted content are quoted text, not his order
196
244
  origin = (payload.get("origin") or {}).get("kind")
197
245
  now = time.time()
246
+ reload = reload_line(cfg)
198
247
  routed.scan_transcript(cfg, payload.get("transcript_path")) # heard-from before the stall clock is read
199
248
  if peer := routed.peer_name(text): # a peer message that did reach this hook: heard now, opens nothing
200
249
  routed.heard(cfg, [(now, peer, text)])
201
250
  if not store.is_human(text, origin):
202
- return ""
251
+ return reload
252
+ draft_intake(cfg, text)
203
253
  orders = Orders(cfg)
204
- corr = correction_line(orders, sd, text, now)
205
- return "\n".join([*routed.prompt_lines(cfg, now), *hook_intake(orders, text), *unordered_chase_lines(cfg, orders, text, now), *([corr] if corr else [])])
254
+ before = {o["id"] for o in orders.live()}
255
+ intake = hook_intake(orders, text)
256
+ pbs = playbooks.match(text)
257
+ playbooks.note_turn(cfg, [pb["name"] for pb in pbs])
258
+ corr = correction_line(orders, sd, text, now, [pb["name"] for pb in pbs])
259
+ return "\n".join([*([reload] if reload else []), *routed.prompt_lines(cfg, now), *intake, *playbooks.inject(pbs), *no_playbook(cfg, orders, text, before, pbs, now), *unordered_chase_lines(cfg, orders, text, now), *([corr] if corr else [])])
206
260
 
207
261
 
208
262
  def _answer_text(resp: object) -> str:
@@ -233,7 +287,8 @@ def hook_routed(cfg: dict, payload: dict) -> str:
233
287
  store.touch_seen(store.state(cfg), "routed")
234
288
  routed.scan_transcript(cfg, payload.get("transcript_path"))
235
289
  ti = payload.get("tool_input") or {}
236
- forbids = lessons.brief_forbids_fix(cfg, str(ti.get("message") or ti.get("prompt") or ""))
290
+ brief = str(ti.get("message") or ti.get("prompt") or "")
291
+ forbids = "\n".join(w for w in (lessons.brief_forbids_fix(cfg, brief), lessons.release_ban_warning(cfg, brief)) if w)
237
292
  item = routed.from_tool(cfg, tool, payload.get("tool_input") or {}, payload.get("tool_response"),
238
293
  str(payload.get("tool_use_id") or ""))
239
294
  if not item:
@@ -250,11 +305,23 @@ def hook_routed(cfg: dict, payload: dict) -> str:
250
305
  return out + (f"\n{forbids}" if forbids else "")
251
306
 
252
307
 
308
+ def hook_skill(cfg: dict, payload: dict) -> str:
309
+ """PostToolUse on Skill: loading the hub skill clears the reload marker."""
310
+ if not is_hub(cfg, payload) or payload.get("tool_name") != "Skill":
311
+ return ""
312
+ store.touch_seen(store.state(cfg), "skill")
313
+ if (payload.get("tool_input") or {}).get("skill") == "hub":
314
+ (store.state(cfg) / RELOAD_MARK).unlink(missing_ok=True)
315
+ return ""
316
+
317
+
253
318
  def hook_pretool(cfg: dict, payload: dict) -> str:
254
319
  """PreToolUse on Bash and TaskStop: warn (never deny) about an unordered merge, an unconfirmed post, a banned command, a stopped agent."""
255
320
  tool = str(payload.get("tool_name") or "")
256
321
  if not is_hub(cfg, payload) or tool not in ("Bash", "TaskStop", "AskUserQuestion"):
257
322
  return ""
323
+ if tool == "Bash" and SEND.search(str((payload.get("tool_input") or {}).get("command") or "")):
324
+ close_drafts(cfg, "sent")
258
325
  warning = lessons.tool_warning(cfg, tool, payload.get("tool_input") or {})
259
326
  if not warning:
260
327
  return ""
@@ -279,7 +346,8 @@ def hook_stop(cfg: dict, payload: dict) -> str:
279
346
  store.touch_seen(sd, "stop")
280
347
  routed.scan_transcript(cfg, payload.get("transcript_path"))
281
348
  last = (payload.get("last_assistant_message") or "").strip()
282
- reasons = gate.stop_reasons(cfg, last, transcript=payload.get("transcript_path"), cwd=payload.get("cwd"))
349
+ reasons = [r for r in [reload_line(cfg)] if r]
350
+ reasons += gate.stop_reasons(cfg, last, transcript=payload.get("transcript_path"), cwd=payload.get("cwd"))
283
351
  if not reasons:
284
352
  return ""
285
353
  store.append_row(sd / "stop-guard.jsonl", {"blocked": True, "reasons": [store.safe(r, 300) for r in reasons]})
@@ -299,7 +367,7 @@ def hook_record(cfg: dict, payload: dict) -> str:
299
367
  return ""
300
368
 
301
369
 
302
- HOOKS = {"session": hook_session, "prompt": hook_prompt, "stop": hook_stop, "record": hook_record, "answer": hook_answer, "routed": hook_routed, "pretool": hook_pretool}
370
+ HOOKS = {"session": hook_session, "prompt": hook_prompt, "stop": hook_stop, "record": hook_record, "answer": hook_answer, "routed": hook_routed, "pretool": hook_pretool, "skill": hook_skill}
303
371
 
304
372
 
305
373
  def main(event: str) -> int:
@@ -14,6 +14,7 @@ EVENTS = (
14
14
  ("UserPromptSubmit", "", "prompt", 5),
15
15
  ("PostToolUse", "AskUserQuestion", "answer", 5),
16
16
  ("PostToolUse", "SendMessage|Agent", "routed", 6),
17
+ ("PostToolUse", "Skill", "skill", 5),
17
18
  ("Stop", "", "stop", 5),
18
19
  )
19
20
  IGNORE = shutil.ignore_patterns("__pycache__", "*.pyc", ".pytest_cache", ".ruff_cache", ".mypy_cache", "data")
@@ -113,6 +113,15 @@ UNCHECKED_WORDS = [
113
113
  "needs her call",
114
114
  "needs a human decision",
115
115
  ]
116
+ PENDING_WORDS = [
117
+ "pending on you",
118
+ "pending on the user",
119
+ "waiting on you",
120
+ "waiting for you",
121
+ "open on you",
122
+ "still on you",
123
+ "on your plate",
124
+ ]
116
125
  LOOKUP_TOOLS = ("Read", "Grep", "Glob", "Bash")
117
126
 
118
127
 
@@ -182,6 +191,20 @@ def unchecked_claim(cfg: dict, last: str, transcript: str | Path | None) -> str
182
191
  )
183
192
 
184
193
 
194
+ def pending_claim(cfg: dict, last: str, transcript: str | Path | None) -> str | None:
195
+ """A reason when the message lists items pending on the user and this turn made no lookup: that list is read now, not remembered."""
196
+ from .gate import _asserted
197
+
198
+ words = Orders(cfg).intents.get("stop_gate", {}).get("pending_words", PENDING_WORDS)
199
+ hit = next((s.strip()[:100] for s in re.split(r"(?<=[.!?])\s+|\n", last) if any(_asserted(s.lower(), w.lower()) for w in words)), None)
200
+ if not hit or lookups_this_turn(transcript) != 0:
201
+ return None
202
+ return (
203
+ f"hubkit: your message lists what is pending on him ({hit!r}) but this turn read nothing. That list goes stale in minutes. "
204
+ "NEXT: read the open items now (mep ls, or the record that holds them), then say it"
205
+ )
206
+
207
+
185
208
  VERIFIED_WORDS = [
186
209
  "tests pass",
187
210
  "tests passed",
@@ -297,6 +320,23 @@ def brief_forbids_fix(cfg: dict, brief: str) -> str | None:
297
320
  return None
298
321
 
299
322
 
323
+ RELEASE_COMMANDS = ["--admin"] # flags release.py itself runs: a brief must not ban them while a release order is open
324
+
325
+
326
+ def release_ban_warning(cfg: dict, brief: str) -> str | None:
327
+ """The line of a brief that bans a command release.py runs itself, while a release order is open."""
328
+ orders = Orders(cfg)
329
+ words = orders.intents.get("stop_gate", {}).get("release_commands", RELEASE_COMMANDS)
330
+ oid = next((o["id"] for o in orders.live() if o["state"] == "open" and o["kind"] == "release"), None)
331
+ line = next((ln for ln in brief.splitlines() if oid and FORBID.search(ln) and any(w in ln for w in words)), None)
332
+ if not line:
333
+ return None
334
+ return (
335
+ f"hubkit WARNING: this brief says {line.strip()[:100]!r} while release order {oid} is open, but release.py runs that itself "
336
+ "(master needs --admin because a required check never reports). NEXT: remove the ban; the release runner does exactly what the script does"
337
+ )
338
+
339
+
300
340
  # ---- merge guard (warn only) ----
301
341
 
302
342
  MERGE_CMD = re.compile(r"\bgh\s+pr\s+merge\b([^\n;&|]*)")
@@ -0,0 +1,132 @@
1
+ """Playbooks: how the user's recurring commands are done, saved once and replayed.
2
+
3
+ One file per playbook at `<config dir>/playbooks/<name>.md`: a frontmatter block (`name`, `trigger` lines, `updated`,
4
+ `quote` lines) and numbered steps. A human prompt that matches a trigger gets the steps injected verbatim. A trigger is a
5
+ word or phrase (whole words, any case), or a regex when it starts with `re:`. `hubkit how save` writes one; the
6
+ hooks and the stop gate use `matched_this_turn` / `missing` to make sure a command with no playbook leaves one behind."""
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import time
12
+ from pathlib import Path
13
+
14
+ from . import config, store
15
+
16
+ NAME = re.compile(r"[a-z0-9][a-z0-9-]*")
17
+
18
+
19
+ def pdir() -> Path:
20
+ return config.config_path().parent / "playbooks"
21
+
22
+
23
+ def _parse(path: Path) -> dict:
24
+ text = path.read_text(encoding="utf-8")
25
+ head, _, body = text.removeprefix("---\n").partition("\n---\n")
26
+ out: dict = {"name": path.stem, "triggers": [], "quotes": [], "updated": "", "steps": body.strip()}
27
+ for ln in head.splitlines():
28
+ key, _, val = ln.partition(": ")
29
+ if key == "name":
30
+ out["name"] = val.strip()
31
+ elif key == "trigger":
32
+ out["triggers"].append(val.strip())
33
+ elif key == "quote":
34
+ out["quotes"].append(val.strip())
35
+ elif key == "updated":
36
+ out["updated"] = val.strip()
37
+ return out
38
+
39
+
40
+ def _write(path: Path, pb: dict) -> None:
41
+ head = ["---", f"name: {pb['name']}", *(f"trigger: {t}" for t in pb["triggers"]), f"updated: {pb['updated']}",
42
+ *(f"quote: {' '.join(q.split())}" for q in pb["quotes"]), "---"]
43
+ store.write_atomic(path, "\n".join(head) + "\n" + pb["steps"].strip() + "\n")
44
+
45
+
46
+ def load_all() -> list[dict]:
47
+ """Every playbook, by name."""
48
+ return [_parse(p) for p in sorted(pdir().glob("*.md"))]
49
+
50
+
51
+ def get(name: str) -> dict:
52
+ path = pdir() / f"{name}.md"
53
+ if not path.exists():
54
+ raise ValueError(f"no playbook {name}; see: hubkit how ls")
55
+ return _parse(path)
56
+
57
+
58
+ def _hits(trigger: str, text: str) -> bool:
59
+ if trigger.startswith("re:"):
60
+ return bool(re.search(trigger[3:], text, re.I))
61
+ return bool(re.search(rf"(?<!\w){re.escape(trigger)}(?!\w)", text, re.I))
62
+
63
+
64
+ def match(text: str) -> list[dict]:
65
+ """Playbooks with a trigger in `text`."""
66
+ return [pb for pb in load_all() if any(_hits(t, text) for t in pb["triggers"])]
67
+
68
+
69
+ def save(name: str, triggers: list[str], steps: str, quotes: list[str], replace: bool = False) -> str:
70
+ """Write a playbook. An existing one is replaced only with `replace`, and the old file is kept as `.md.bak-<date>`."""
71
+ if not NAME.fullmatch(name):
72
+ raise ValueError("playbook name must be kebab-case (a-z, 0-9, -)")
73
+ if not triggers or not steps.strip():
74
+ raise ValueError("a playbook needs at least one --trigger and steps")
75
+ for t in triggers:
76
+ if t.startswith("re:"):
77
+ re.compile(t[3:])
78
+ path = pdir() / f"{name}.md"
79
+ day = time.strftime("%Y-%m-%d")
80
+ if path.exists():
81
+ if not replace:
82
+ raise ValueError(f"playbook {name} exists; pass --replace to overwrite (the old one is kept as {path.name}.bak-{day})")
83
+ path.replace(path.with_name(f"{path.name}.bak-{day}"))
84
+ pdir().mkdir(parents=True, exist_ok=True)
85
+ _write(path, {"name": name, "triggers": triggers, "updated": day, "quotes": quotes, "steps": steps})
86
+ return f"saved playbook {name} ({len(triggers)} triggers)"
87
+
88
+
89
+ def add_quote(name: str, quote: str) -> None:
90
+ pb = get(name)
91
+ pb["quotes"].append(quote[:200])
92
+ pb["updated"] = time.strftime("%Y-%m-%d")
93
+ _write(pdir() / f"{name}.md", pb)
94
+
95
+
96
+ def inject(pbs: list[dict]) -> list[str]:
97
+ return [f"PLAYBOOK {pb['name']}: follow these steps\n{pb['steps']}" for pb in pbs]
98
+
99
+
100
+ # ---- per-turn memory: what matched, and what has no playbook yet ----
101
+
102
+ def note_turn(cfg: dict, names: list[str]) -> None:
103
+ store.write_atomic(store.state(cfg) / "playbook-turn.json", ",".join(names))
104
+
105
+
106
+ def matched_this_turn(cfg: dict) -> list[str]:
107
+ p = store.state(cfg) / "playbook-turn.json"
108
+ return [n for n in p.read_text(encoding="utf-8").split(",") if n] if p.exists() else []
109
+
110
+
111
+ def note_missing(cfg: dict, cmd: str, now: float) -> None:
112
+ store.append_row(store.state(cfg) / "playbook-missing.jsonl", {"ts": now, "cmd": store.safe(cmd, 80)})
113
+
114
+
115
+ def note_saved(cfg: dict, now: float) -> None:
116
+ store.append_row(store.state(cfg) / "playbook-saved.jsonl", {"ts": now})
117
+
118
+
119
+ def missing(cfg: dict) -> str | None:
120
+ """The command of a prompt that matched no playbook, when an order has closed or work been archived since and no
121
+ playbook was saved since: the steps were done but not kept."""
122
+ sd = store.state(cfg)
123
+ asked = store.read_rows(sd / "playbook-missing.jsonl")[0]
124
+ if not asked:
125
+ return None
126
+ last = asked[-1]
127
+ saved = max([r["ts"] for r in store.read_rows(sd / "playbook-saved.jsonl")[0]], default=0.0)
128
+ if saved >= last["ts"]:
129
+ return None
130
+ done = [r for r in store.read_rows(sd / "orders.jsonl")[0] if r.get("op") == "close"]
131
+ done += [r for f in (sd / "archive").glob("archive_*.jsonl") for r in store.read_rows(f)[0] if r.get("type") == "work"]
132
+ return last["cmd"] if any(r.get("ts", 0) >= last["ts"] for r in done) else None
@@ -85,6 +85,11 @@ LEADS_CHANGE = re.compile(
85
85
  )
86
86
 
87
87
 
88
+ REVIEW_LEAD = re.compile(
89
+ r"(?i)^\W*(?:(?:please|then|and|also)\s+)*(?:full\s+|gated\s+|re-?)*review\b"
90
+ )
91
+
92
+
88
93
  def _kinds(cfg: dict, sentence: str) -> set[str]:
89
94
  """What the owner may be asked to do in one sentence. A review word beside a PR is a review ask by default
90
95
  ("review #7", "needs a review", "can I get a review on #7"). The one exception: the sentence opens with a change
@@ -126,7 +131,16 @@ def is_review(cfg: dict, text: str, summary: str = "") -> bool:
126
131
  """A review ask: the owner is asked to review a PR, i.e. a sentence naming a PR leads with a review word (or the
127
132
  summary does). A review word elsewhere (a handover, a status) or as a noun after another action ("fix the
128
133
  findings in his review of #7") does not make it one."""
129
- return "review" in _asks(cfg, strip_examples(text), summary)
134
+ body = strip_examples(text)
135
+ if "review" not in _asks(cfg, body, summary):
136
+ return False
137
+ # a job titled as a change ("Fix #7 review findings") asks for changes, not a verdict, unless a sentence leads with a review
138
+ leads_review = any(
139
+ REVIEW_LEAD.match(x)
140
+ for x in re.split(r"(?<=[.!?])\s+|\n", body)
141
+ if PR_REF.search(x)
142
+ )
143
+ return not (LEADS_CHANGE.match(summary.strip().lower()) and not leads_review)
130
144
 
131
145
 
132
146
  def pushes_to_pr(cfg: dict, text: str, summary: str = "") -> bool:
@@ -793,11 +807,12 @@ def limit(cfg: dict, item: dict) -> float:
793
807
  def overdue(cfg: dict, item: dict, now: float) -> int | None:
794
808
  """Minutes since the ask when a review passes its hard limit (hearing from the owner does not stop it)."""
795
809
  age = int((now - started_at(cfg, item)) / 60)
796
- return (
797
- age
798
- if item.get("review") and age > float(opts(cfg)["review_overdue_min"])
799
- else None
800
- )
810
+ hard = float(opts(cfg)["review_overdue_min"])
811
+ if item.get("estimate_min") is not None and not item.get("estimate_defaulted"):
812
+ hard = max(
813
+ hard, float(item["estimate_min"])
814
+ ) # the job's own stated estimate sets its limit
815
+ return age if item.get("review") and age > hard else None
801
816
 
802
817
 
803
818
  def level(cfg: dict, item: dict, now: float) -> int | None:
@@ -1227,7 +1242,7 @@ def _mtime(path: str) -> float | None:
1227
1242
  return None
1228
1243
 
1229
1244
 
1230
- def _advance(item: dict, det: dict, now: float) -> dict:
1245
+ def _advance(cfg: dict, item: dict, det: dict, now: float) -> dict:
1231
1246
  """A queue item's current PR has its review: move to the next PR with a fresh clock."""
1232
1247
  done, rest = item["queue"][0], item["queue"][1:]
1233
1248
  item["queue"] = rest if len(rest) > 1 else []
@@ -1249,7 +1264,7 @@ def _advance(item: dict, det: dict, now: float) -> dict:
1249
1264
  return {
1250
1265
  "key": f"{item['id']}:queue_advanced:{pr_num(done)}",
1251
1266
  "msg": (
1252
- f"{item['id']} to {item['owner']}: {_pr_no(done)} {det['state']} at {det['commit'][:7]}; the clock restarts on the next PR. NEXT: read the review on GitHub and act on it"
1267
+ f"{item['id']} to {item['owner']}: {_pr_no(done)} {det['state']} at {det['commit'][:7]}; the clock restarts on the next PR. NEXT: {next_step(cfg, det, item['owner'])}"
1253
1268
  ),
1254
1269
  }
1255
1270
 
@@ -1449,7 +1464,7 @@ def refresh_prs(cfg: dict, now: float) -> list[dict]:
1449
1464
  if done and i.get("queue"):
1450
1465
  cur = i["prs"][0]
1451
1466
  if cur in done:
1452
- msgs.append(_advance(i, done[cur], now))
1467
+ msgs.append(_advance(cfg, i, done[cur], now))
1453
1468
  elif done:
1454
1469
  msgs.append(_close_landed(cfg, i, done, now))
1455
1470
  if not i["prs"]:
@@ -313,7 +313,7 @@ def render_block(cfg: dict, orders: Orders, st: dict | None, now: float | None =
313
313
  ahead = ""
314
314
  if kind == "priority" and any(i["kind"] == "active" for i in st["work"]):
315
315
  ahead = " | AHEAD: active work is running while this waits; switch, or say why not"
316
- out.append(f"{kind}: " + "; ".join(f"{i['id']} {i['title']}" for i in mine) + ahead)
316
+ out.append(f"{kind}: " + "; ".join(f"{i['id']} {i['title']} (checked {int((now - float(i.get('verified') or i['added'])) / 60)}m ago)" for i in mine) + ahead)
317
317
  from . import routed, trust
318
318
 
319
319
  out += routed.block_lines(cfg, st["work"], now)
@@ -351,6 +351,8 @@ REVERTS = [
351
351
  ('eod lists PRs and peers', 'hubcore/status.py', 'glance(cfg, day) + [""] + ledger.day_lines(cfg, day)', 'glance(cfg, day)', 'tests/test_ledger.py::test_digest_and_eod_list_todays_prs_and_what_each_peer_was_asked'),
352
352
  ('digest lists PRs and peers', 'hubcore/status.py', 'return out + ledger.day_lines(cfg, store.day_of(cfg, since))', 'return out', 'tests/test_ledger.py::test_digest_and_eod_list_todays_prs_and_what_each_peer_was_asked'),
353
353
  ('fix job push is not a stall', 'hubcore/routed.py', ' bool(PR_REF.search(text + " " + summary))\n and bool(PUSH', ' False\n and bool(PUSH', 'tests/test_review_chain.py::test_an_owners_pushes_to_a_fix_job_are_not_a_stalled_head_but_a_reviews_moved_head_still_is'),
354
+ ('fix-titled job is not a review', 'hubcore/routed.py', 'return not (LEADS_CHANGE.match(summary.strip().lower()) and not leads_review)', 'return True', 'tests/test_review_chain.py::test_a_fix_job_titled_with_review_findings_has_no_review_clock_but_a_real_review_does'),
355
+ ('stated estimate sets the hard limit', 'hubcore/routed.py', ' hard = max(\n hard, float(item["estimate_min"])\n )', ' hard = hard', 'tests/test_review_chain.py::test_a_reviews_own_stated_estimate_sets_its_hard_limit'),
354
356
  ]
355
357
 
356
358
 
@@ -2205,3 +2205,45 @@ def test_a_pr_with_review_as_a_noun_is_still_a_review_item(env, text):
2205
2205
  env.bind()
2206
2206
  send(env, "peer-a", text, "ask")
2207
2207
  assert [i["review"] for i in routed_items(env)] == [True]
2208
+
2209
+
2210
+ RELOAD = "hubkit: hub skill not loaded since compaction. NEXT: Skill hub, then read the overlay"
2211
+
2212
+
2213
+ def skill_payload(sid="sess-hub", skill="hub"):
2214
+ return {"hook_event_name": "PostToolUse", "session_id": sid, "tool_name": "Skill", "tool_input": {"skill": skill}}
2215
+
2216
+
2217
+ def stop_payload(sid="sess-hub"):
2218
+ return {"hook_event_name": "Stop", "session_id": sid, "last_assistant_message": "ok"}
2219
+
2220
+
2221
+ def test_stop_blocks_until_the_hub_skill_is_loaded_after_session_start(env):
2222
+ env.bind()
2223
+ assert env.hook("stop", stop_payload()).stdout == "" # no SessionStart yet: nothing owed
2224
+ env.hook("session", {"session_id": "sess-hub", "source": "compact"})
2225
+ out = json.loads(env.hook("stop", stop_payload()).stdout)
2226
+ assert out["decision"] == "block" and RELOAD in out["reason"]
2227
+ assert RELOAD in env.prompt("what is the status").stdout # the prompt hook says it too
2228
+ env.hook("skill", skill_payload(skill="other")) # another skill does not clear it
2229
+ assert "block" in env.hook("stop", stop_payload()).stdout
2230
+ r = env.hook("skill", skill_payload())
2231
+ assert r.returncode == 0 and r.stdout == ""
2232
+ assert env.hook("stop", stop_payload()).stdout == ""
2233
+ assert RELOAD not in env.prompt("what is the status").stdout
2234
+
2235
+
2236
+ def test_reload_gate_is_a_noop_outside_the_bound_hub(env):
2237
+ hub = env.bind()
2238
+ env.session(sid="other")
2239
+ env.hook("session", {"session_id": "sess-hub", "source": "startup"})
2240
+ assert env.hook("session", {"session_id": "other", "source": "startup"}).stdout == ""
2241
+ assert env.hook("stop", stop_payload("other")).stdout == ""
2242
+ assert env.hook("skill", skill_payload("other")).stdout == ""
2243
+ assert "block" in env.hook("stop", stop_payload()).stdout # the other session's skill call did not clear the hub's marker
2244
+ f = env.sessions / f"{hub.pid}.json" # headless: the gate stays silent
2245
+ d = json.loads(f.read_text())
2246
+ d["kind"] = "sdk-cli"
2247
+ f.write_text(json.dumps(d))
2248
+ r = env.hook("stop", stop_payload())
2249
+ assert r.returncode == 0 and r.stdout == ""
@@ -38,7 +38,7 @@ def test_hooks_block_is_valid_settings_json_with_every_event(env):
38
38
  block = json.loads(env.run("hooks", "--skills-dir", "$HOME/.claude/skills").stdout)["hooks"]
39
39
  assert set(block) == {"SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"}
40
40
  cmds = [h["command"] for g in block["PostToolUse"] for h in g["hooks"]]
41
- assert any("hook answer" in c for c in cmds) and any("hook routed" in c for c in cmds)
41
+ assert any("hook answer" in c for c in cmds) and any("hook routed" in c for c in cmds) and any("hook skill" in c for c in cmds)
42
42
  assert all("$HOME/.claude/skills/hub/scripts/hubkit" in h["command"] for gs in block.values() for g in gs for h in g["hooks"])
43
43
  guarded = json.loads(env.run("hooks", "--merge-guard").stdout)["hooks"]
44
44
  assert guarded["PreToolUse"][0]["matcher"] == "Bash|TaskStop|AskUserQuestion" and "hook pretool" in guarded["PreToolUse"][0]["hooks"][0]["command"]
@@ -219,3 +219,54 @@ def test_a_machine_named_release_server_opens_no_order_and_an_insult_at_a_tool_i
219
219
  assert "opened from the user's prompt" in env.prompt("do the release now, merge both PRs").stdout
220
220
  assert "CORRECTION" not in env.prompt("remove stupid ci from the workflow list").stdout
221
221
  assert "CORRECTION" in env.prompt("you are stupid").stdout
222
+
223
+
224
+ # ---- pending-on-the-user lists need a lookup in the same turn ----
225
+
226
+
227
+ def test_a_list_of_items_pending_on_the_user_with_no_lookup_is_held(env):
228
+ env.bind()
229
+ msg = "Three items are pending on you: the merge, the draft and the invoice."
230
+ held = stop(env, last_assistant_message=msg, transcript_path=transcript(env, []))
231
+ assert "pending on him" in held["reason"] and "read nothing" in held["reason"]
232
+ assert stop(env, last_assistant_message=msg, transcript_path=transcript(env, ["Bash"])) is None
233
+ assert stop(env, last_assistant_message="Nothing is pending on you.", transcript_path=transcript(env, [])) is None
234
+
235
+
236
+ # ---- a draft asked for is a work item until it is sent or discarded ----
237
+
238
+
239
+ def work_titles(env):
240
+ p = env.state / "work.json"
241
+ return [i["title"] for i in json.loads(p.read_text())] if p.exists() else []
242
+
243
+
244
+ def test_a_draft_ask_opens_one_work_item_closed_by_send_or_discard(env):
245
+ env.bind()
246
+ env.prompt("write me a standup draft for today")
247
+ env.prompt("make the draft shorter")
248
+ assert [t for t in work_titles(env) if t.startswith("draft: ")] == ["draft: write me a standup draft for today"]
249
+ env.hook("pretool", {"hook_event_name": "PreToolUse", "session_id": "sess-hub", "tool_name": "Bash", "tool_input": {"command": "mep send standup.md"}})
250
+ assert work_titles(env) == []
251
+ env.prompt("draft a reply to the invoice mail")
252
+ assert len(work_titles(env)) == 1
253
+ env.prompt("discard the draft")
254
+ assert work_titles(env) == []
255
+ env.prompt("what is the status")
256
+ assert work_titles(env) == []
257
+
258
+
259
+ def test_a_brief_banning_admin_while_a_release_order_is_open_is_warned(env):
260
+ env.bind()
261
+ env.prompt("do the release now, finish it asap")
262
+ brief = "Run the release. Output: prod live. " + LONG + "\nNever use --admin to merge."
263
+ assert "release.py runs that itself" in send(env, "peer-a", brief, "release").stdout
264
+ assert "release.py runs that itself" not in send(env, "peer-b", brief.replace("Never use --admin", "Never touch billing"), "other").stdout
265
+
266
+
267
+ def test_words_inside_pasted_content_open_no_order(env):
268
+ env.bind()
269
+ env.prompt("<pasted_content>status: the release is blocked on smoke</pasted_content> what do you think?")
270
+ assert env.rows("orders.jsonl") == []
271
+ env.prompt("do the release now, finish it asap <pasted_content>old report</pasted_content>")
272
+ assert len([r for r in env.rows("orders.jsonl") if r["op"] == "open"]) == 1
@@ -0,0 +1,64 @@
1
+ """Playbooks: how a recurring command is done, replayed on a matching prompt, owed when missing, corrected on a correction."""
2
+
3
+ import json
4
+
5
+ from test_hubkit import HOTFIX, stop
6
+
7
+ STEPS = "1. open the release PRs\n2. have the reviewer review them\n3. merge with --match-head-commit\n"
8
+
9
+
10
+ def save(env, name="release", *extra, steps=STEPS):
11
+ f = env.root / f"{name}.steps"
12
+ f.write_text(steps)
13
+ return env.run("how", "save", name, "--trigger", "release pr", "--trigger", "re:cut a rel\\w+", "--steps-file", str(f), "--quote", "release pr aint it created by bot?", *extra)
14
+
15
+
16
+ def test_save_ls_show_match_round_trip_in_the_config_dir(env):
17
+ assert save(env).returncode == 0
18
+ assert (env.root / "playbooks" / "release.md").exists()
19
+ assert "release: release pr, re:cut a rel" in env.run("how", "ls").stdout
20
+ shown = env.run("how", "show", "release").stdout
21
+ assert "3. merge with --match-head-commit" in shown and "quote: release pr aint it created by bot?" in shown
22
+ assert "PLAYBOOK release: follow these steps" in env.run("how", "match", "please Cut a release now").stdout
23
+ assert env.run("how", "match", "unrelated words").stdout.strip() == "NO PLAYBOOK"
24
+
25
+
26
+ def test_save_overwrites_only_with_replace_and_keeps_a_backup(env):
27
+ save(env)
28
+ r = save(env, steps="1. new\n")
29
+ assert r.returncode == 2 and "--replace" in r.stderr
30
+ assert "3. merge" in env.run("how", "show", "release").stdout
31
+ assert save(env, "release", "--replace", steps="1. new\n").returncode == 0
32
+ assert "1. new" in env.run("how", "show", "release").stdout
33
+ (bak,) = (env.root / "playbooks").glob("release.md.bak-*")
34
+ assert "3. merge" in bak.read_text()
35
+
36
+
37
+ def test_a_matching_prompt_injects_every_matching_playbook_verbatim(env):
38
+ env.bind()
39
+ save(env)
40
+ save(env, "second", steps="1. review blockers only\n") # same trigger: both match
41
+ out = env.prompt("release pr time").stdout
42
+ assert "PLAYBOOK release: follow these steps\n1. open the release PRs" in out and "PLAYBOOK second: follow these steps\n1. review blockers only" in out
43
+ assert "NO PLAYBOOK" not in out
44
+
45
+
46
+ def test_an_order_with_no_playbook_is_told_to_save_one_and_the_stop_waits_until_it_is_saved(env):
47
+ env.bind()
48
+ out = env.prompt(HOTFIX).stdout
49
+ assert "NO PLAYBOOK for 'we need a hotfix" in out and "hubkit how save" in out
50
+ assert "how save" not in stop(env, last_assistant_message="Working on it.")["reason"] # nothing was closed yet
51
+ env.run("work", "add", "--kind", "active", "--title", "the hotfix")
52
+ env.run("work", "done", "W1", "--note", "shipped")
53
+ held = stop(env, last_assistant_message="Hotfix shipped.")
54
+ assert "hubkit how save" in held["reason"] and "no playbook" in held["reason"]
55
+ save(env, "hotfix")
56
+ assert "how save" not in stop(env, last_assistant_message="Hotfix shipped.")["reason"]
57
+
58
+
59
+ def test_a_correction_in_a_matched_turn_adds_the_quote_and_says_to_update_it(env):
60
+ env.bind()
61
+ save(env)
62
+ out = env.prompt("release pr again, I told you the bot opens it").stdout
63
+ assert "update playbook release if a step was wrong" in out
64
+ assert "quote: release pr again, I told you the bot opens it" in env.run("how", "show", "release").stdout
@@ -54,3 +54,41 @@ def test_an_owners_pushes_to_a_fix_job_are_not_a_stalled_head_but_a_reviews_move
54
54
  items = {i["owner"]: i for i in routed_items(env)}
55
55
  assert items["peer-fix"]["head_moved"] is None and items["peer-fix"]["heads"][PR1] == "bbb2222"
56
56
  assert items["peer-rev"]["head_moved"] and "ALERT" in out
57
+
58
+
59
+ def test_a_fix_job_titled_with_review_findings_has_no_review_clock_but_a_real_review_does(env):
60
+ from test_hubkit import age_routed
61
+
62
+ fake_gh(env, head="aaa1111")
63
+ env.bind()
64
+ fix = f"Fix the findings from the review of {PR1}. Done-when: tests pass. Output: the PR updated, ready for re-review of {PR1}.\nEstimate: 45m"
65
+ send(env, "peer-fix", fix, "Fix #101 review findings")
66
+ assert routed_items(env)[0]["review"] is False
67
+ age_routed(env, 29)
68
+ assert "past the hard limit" not in env.prompt("carry on").stdout
69
+ send(env, "peer-rev", f"Full gated review of {PR2}. Done-when: a verdict. Output: the verdict", "review 102")
70
+ age_routed(env, 29)
71
+ out = env.prompt("carry on").stdout
72
+ assert "peer-rev" in out and "past the hard limit" in out and out.count("past the hard limit") == 1
73
+
74
+
75
+ def test_a_reviews_own_stated_estimate_sets_its_hard_limit(env):
76
+ from test_hubkit import age_routed
77
+
78
+ fake_gh(env, head="aaa1111")
79
+ env.bind()
80
+ send(env, "peer-rev", f"Full gated review of {PR1}. Done-when: a verdict. Output: the verdict.\nEstimate: 60m", "review 101")
81
+ age_routed(env, 29)
82
+ assert "past the hard limit" not in env.prompt("carry on").stdout
83
+ age_routed(env, 40)
84
+ assert "past the hard limit" in env.prompt("carry on").stdout
85
+
86
+
87
+ def test_a_queue_advance_after_an_approval_names_the_merge_step_not_read_the_review(env):
88
+ fake_gh(env, head="aaa1111")
89
+ env.bind()
90
+ urls = [f"https://github.com/acme/repo/pull/{n}" for n in (201, 202, 203)]
91
+ send(env, "peer-a", "Gated review of the queue: " + " ".join(urls), "review the queue")
92
+ gh_json(env, "aaa1111", [review("aaa1111")], statusCheckRollup=[{"conclusion": "SUCCESS"}])
93
+ out = env.run("tick", "--no-notify").stdout
94
+ assert "restarts on the next PR" in out and "--match-head-commit aaa1111" in out and "read the review" not in out
@@ -80,3 +80,17 @@ def test_digest_lists_what_finished_and_what_waits_on_the_user(env):
80
80
  out = env.run("digest", "--since", "1h").stdout
81
81
  assert "finished" in out and "Fix the importer" in out and "merged as 1a2b3c4" in out
82
82
  assert "waits on you" in out and "Merge #101 now?" in out
83
+
84
+
85
+ def test_the_block_shows_when_each_work_item_was_last_checked(env):
86
+ env.bind()
87
+ env.run("work", "add", "--kind", "tracked", "--title", "the invoice run")
88
+ p = env.state / "work.json"
89
+ rows = json.loads(p.read_text())
90
+ rows[0]["added"] -= 90 * 60
91
+ p.write_text(json.dumps(rows))
92
+ env.run("tick", "--no-notify")
93
+ assert "the invoice run (checked 90m ago)" in env.hook("session", {"session_id": "sess-hub", "source": "compact"}).stdout
94
+ env.run("work", "verify", "W1")
95
+ env.run("tick", "--no-notify")
96
+ assert "the invoice run (checked 0m ago)" in env.hook("session", {"session_id": "sess-hub", "source": "compact"}).stdout
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes