@yasaswy.nagavolu/agents 0.16.6 → 0.17.0
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.
- package/content/global/CLAUDE.md +3 -2
- package/content/global/hooks/permission_mode_guard.py +144 -0
- package/content/global/keybindings.json +13 -0
- package/content/hooks/tracker_proof_gate.py +29 -1
- package/content/manifest.json +51 -0
- package/content/proxy/README.md +6 -2
- package/content/proxy/bg_process_reaper_hook.py +19 -0
- package/content/proxy/bg_process_registry.py +107 -3
- package/content/proxy/grilling_format_gate.py +298 -0
- package/content/proxy/switch_model.ps1 +1 -1
- package/content/skills/mattpocock-grilling/SKILL.md +1 -1
- package/content/skills/mattpocock-to-tickets/gitlab_phase.py +28 -8
- package/content/skills/mattpocock-to-tickets/tests/test_gitlab_phase.py +57 -4
- package/content/skills/switch-model/README.md +1 -1
- package/content/statusline/statusline-command.ps1 +11 -0
- package/package.json +1 -1
package/content/global/CLAUDE.md
CHANGED
|
@@ -5,6 +5,8 @@ When doing bug fixes, always start with reproducing the bug in an E2E setting as
|
|
|
5
5
|
If user has custom agent and other models in their custom agents respect them and launch with what was instructed. This takes higher priority.
|
|
6
6
|
Use git CLI for GitLab access, never glab — we use GitLab, not GitHub.
|
|
7
7
|
Always state all pending, open, or blocked items upfront and in full at the top of a response — never trail a reply with "one more thing pending" or drip-feed open items across later turns.
|
|
8
|
+
Always track multi-step work with TaskCreate/TaskList/TaskUpdate (persistent across sessions), falling back to TodoWrite only if Task tools are unavailable — never printed markdown checklists.
|
|
9
|
+
When planning or modifying work, start a wayfinder map for anything too big for one session, and always mirror the TODO items in that work's PRD/issue ticket so it stays current.
|
|
8
10
|
|
|
9
11
|
## Model Routing (HARD RULE)
|
|
10
12
|
|
|
@@ -24,8 +26,7 @@ Standalone non-Claude subagents (an agent whose entire multi-turn loop runs as a
|
|
|
24
26
|
- On Agent/Task dispatch without a custom agent, always pass `model: "sonnet"` explicitly. The bare `model:` tool parameter is schema-restricted to `sonnet`/`opus`/`haiku`/`fable` for unregistered dispatch types (`Explore`, `general-purpose`, `claude`) — they have no agent-definition file for the harness to read a model from, so any non-Claude slug there fails tool-schema validation (confirmed in production 2026-07-05). To actually get GLM-5.2 (or another LiteLLM-routed model) running a generic-purpose-shaped dispatch, use a REGISTERED project-specific agent whose own frontmatter names that model (e.g. `generic-purpose-subagent`) — that path reads the model server-side from the agent file, not from this parameter.
|
|
25
27
|
- Custom agents that specify their own model override this (rule above takes priority).
|
|
26
28
|
- Loop shape: Fable plans → a worker subagent executes → Fable adversarially reviews → return to user or re-instruct subagents.
|
|
27
|
-
|
|
28
|
-
|
|
29
|
+
- Context preservation (every chat, any task type): any step whose raw output isn't needed verbatim for a decision → subagent returning conclusions only, never file dumps. Main loop holds only decisions, dispatch, and review.
|
|
29
30
|
|
|
30
31
|
## Memory-First (every session)
|
|
31
32
|
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""permission_mode_guard.py — keeps a session from silently stranding off the
|
|
3
|
+
user's configured `permissions.defaultMode` in ~/.claude/settings.json.
|
|
4
|
+
|
|
5
|
+
Two hook events, one file:
|
|
6
|
+
|
|
7
|
+
- PreToolUse (matcher "EnterPlanMode"): when the configured default mode
|
|
8
|
+
is "bypassPermissions", deny EnterPlanMode. Exiting plan mode does not
|
|
9
|
+
restore bypassPermissions -- no harness mechanism does that -- so
|
|
10
|
+
switching into plan mode strands the session on a mode that stalls on
|
|
11
|
+
every permission prompt. The model should plan inline in its reply text
|
|
12
|
+
instead. Any other configured default: allow (no output, exit 0).
|
|
13
|
+
|
|
14
|
+
- Stop: read the live `permission_mode` the harness reports for this turn
|
|
15
|
+
and persist it to a per-session state file the statusline reads
|
|
16
|
+
(~/.claude/.mode_state/<session_id>), pruning state files older than 7
|
|
17
|
+
days (best-effort). Only when the configured default is
|
|
18
|
+
"bypassPermissions" AND the live mode is present and differs, emit a
|
|
19
|
+
systemMessage warning the user. Never blocks Stop -- informational only.
|
|
20
|
+
Warns every turn while drifted; no throttle.
|
|
21
|
+
|
|
22
|
+
Fails OPEN on all errors (malformed stdin, missing settings.json, IO
|
|
23
|
+
failures): exits 0 silently. Minimal imports, no third-party deps.
|
|
24
|
+
|
|
25
|
+
Wiring (settings.json):
|
|
26
|
+
PreToolUse, matcher "EnterPlanMode": python ~/.claude/hooks/permission_mode_guard.py
|
|
27
|
+
Stop (no matcher): python ~/.claude/hooks/permission_mode_guard.py
|
|
28
|
+
"""
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
# CLAUDE_HOOK_CHILD guard: hook-spawned child claude processes set this so
|
|
32
|
+
# this hook never re-fires recursively. Must run before any other I/O.
|
|
33
|
+
import os, sys
|
|
34
|
+
if os.environ.get("CLAUDE_HOOK_CHILD"):
|
|
35
|
+
sys.exit(0)
|
|
36
|
+
|
|
37
|
+
import json
|
|
38
|
+
import re
|
|
39
|
+
import time
|
|
40
|
+
from pathlib import Path
|
|
41
|
+
|
|
42
|
+
SETTINGS_PATH = Path.home() / ".claude" / "settings.json"
|
|
43
|
+
STATE_DIR = Path.home() / ".claude" / ".mode_state"
|
|
44
|
+
STATE_MAX_AGE_SECS = 7 * 24 * 3600
|
|
45
|
+
|
|
46
|
+
# Session IDs are harness-generated UUIDs; this is a defensive filename guard
|
|
47
|
+
# only, not a real-world constraint -- reject anything path-traversal-shaped.
|
|
48
|
+
_SAFE_ID_RE = re.compile(r"^[A-Za-z0-9_.-]+$")
|
|
49
|
+
|
|
50
|
+
PLAN_DENY_REASON = (
|
|
51
|
+
"EnterPlanMode denied: this session's configured default permission mode "
|
|
52
|
+
"is bypassPermissions. Exiting plan mode does not restore bypassPermissions "
|
|
53
|
+
"-- the session would strand on a mode that stalls on every permission "
|
|
54
|
+
"prompt. Plan inline in your reply text instead of switching modes."
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _configured_default_mode() -> str | None:
|
|
59
|
+
try:
|
|
60
|
+
with open(SETTINGS_PATH, "r", encoding="utf-8") as fh:
|
|
61
|
+
settings = json.load(fh)
|
|
62
|
+
return (settings.get("permissions") or {}).get("defaultMode")
|
|
63
|
+
except Exception:
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _deny(reason: str) -> None:
|
|
68
|
+
print(json.dumps({
|
|
69
|
+
"hookSpecificOutput": {
|
|
70
|
+
"hookEventName": "PreToolUse",
|
|
71
|
+
"permissionDecision": "deny",
|
|
72
|
+
"permissionDecisionReason": reason,
|
|
73
|
+
}
|
|
74
|
+
}))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _prune_state_dir() -> None:
|
|
78
|
+
try:
|
|
79
|
+
cutoff = time.time() - STATE_MAX_AGE_SECS
|
|
80
|
+
for entry in STATE_DIR.iterdir():
|
|
81
|
+
try:
|
|
82
|
+
if entry.is_file() and entry.stat().st_mtime < cutoff:
|
|
83
|
+
entry.unlink()
|
|
84
|
+
except Exception:
|
|
85
|
+
pass
|
|
86
|
+
except Exception:
|
|
87
|
+
pass
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _handle_pre_tool_use(data: dict) -> None:
|
|
91
|
+
if data.get("tool_name") != "EnterPlanMode":
|
|
92
|
+
return
|
|
93
|
+
if _configured_default_mode() != "bypassPermissions":
|
|
94
|
+
return
|
|
95
|
+
_deny(PLAN_DENY_REASON)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _handle_stop(data: dict) -> None:
|
|
99
|
+
session_id = data.get("session_id")
|
|
100
|
+
mode = data.get("permission_mode")
|
|
101
|
+
|
|
102
|
+
if isinstance(session_id, str) and _SAFE_ID_RE.match(session_id):
|
|
103
|
+
try:
|
|
104
|
+
STATE_DIR.mkdir(parents=True, exist_ok=True)
|
|
105
|
+
(STATE_DIR / session_id).write_text(mode or "", encoding="utf-8")
|
|
106
|
+
except Exception:
|
|
107
|
+
pass
|
|
108
|
+
_prune_state_dir()
|
|
109
|
+
|
|
110
|
+
if _configured_default_mode() != "bypassPermissions":
|
|
111
|
+
return
|
|
112
|
+
if not mode or mode == "bypassPermissions":
|
|
113
|
+
return
|
|
114
|
+
|
|
115
|
+
print(json.dumps({
|
|
116
|
+
"systemMessage": (
|
|
117
|
+
f"This session's live permission mode is '{mode}', but your "
|
|
118
|
+
"configured default is bypassPermissions. Press ctrl+x m to cycle "
|
|
119
|
+
"modes, or run /permissions, to get back to bypassPermissions."
|
|
120
|
+
)
|
|
121
|
+
}))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _safe_main() -> None:
|
|
125
|
+
try:
|
|
126
|
+
raw = sys.stdin.buffer.read().decode("utf-8")
|
|
127
|
+
data = json.loads(raw or "{}")
|
|
128
|
+
except Exception:
|
|
129
|
+
return
|
|
130
|
+
if not isinstance(data, dict):
|
|
131
|
+
return
|
|
132
|
+
|
|
133
|
+
event = data.get("hook_event_name")
|
|
134
|
+
if event == "PreToolUse":
|
|
135
|
+
_handle_pre_tool_use(data)
|
|
136
|
+
elif event == "Stop":
|
|
137
|
+
_handle_stop(data)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
if __name__ == "__main__":
|
|
141
|
+
try:
|
|
142
|
+
_safe_main()
|
|
143
|
+
except Exception:
|
|
144
|
+
pass
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://www.schemastore.org/claude-code-keybindings.json",
|
|
3
|
+
"$docs": "https://code.claude.com/docs/en/keybindings",
|
|
4
|
+
"bindings": [
|
|
5
|
+
{
|
|
6
|
+
"context": "Chat",
|
|
7
|
+
"bindings": {
|
|
8
|
+
"shift+tab": null,
|
|
9
|
+
"ctrl+x m": "chat:cycleMode"
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
]
|
|
13
|
+
}
|
|
@@ -53,11 +53,37 @@ ISSUE_URL_RE = re.compile(r"gitlab\.com/([\w./-]+?)/-/(?:issues|work_items)/(\d+
|
|
|
53
53
|
BARE_ISSUE_RE = re.compile(r"(?<![\w/])#(\d+)\b")
|
|
54
54
|
PROXIMITY_CHARS = 200 # "same sentence or nearby" -- a char-distance window
|
|
55
55
|
|
|
56
|
+
# A completion word immediately preceded by a negator is a NOT-done report
|
|
57
|
+
# ("not done", "cannot close", "isn't resolved"), not a completion claim --
|
|
58
|
+
# it must never anchor a block. The window is short and deliberately close
|
|
59
|
+
# (right before the word, not "anywhere earlier in the message") so an
|
|
60
|
+
# unrelated negation many words back ("Not sure about X, but shipped #139")
|
|
61
|
+
# does not suppress a real claim; that's a false negative on the negation
|
|
62
|
+
# check, but a false positive there (missing a real completion claim) is
|
|
63
|
+
# safer than this gate's opposite failure mode (blocking an honest
|
|
64
|
+
# not-done report), which is the bug this constant exists to fix.
|
|
65
|
+
#
|
|
66
|
+
# Bare "no" is deliberately EXCLUDED, even though it's a negator in
|
|
67
|
+
# isolation: "No further blockers, shipped #185" has "no" inside the
|
|
68
|
+
# window and would wrongly suppress a genuine completion claim. Do not
|
|
69
|
+
# add it back without a smarter (non-substring) check.
|
|
70
|
+
NEGATION_RE = re.compile(
|
|
71
|
+
r"\b(not|cannot|can't|couldn't|isn't|aren't|wasn't|weren't|hasn't|haven't|"
|
|
72
|
+
r"won't|doesn't|didn't|never|no longer|unable to|far from)\b",
|
|
73
|
+
re.I,
|
|
74
|
+
)
|
|
75
|
+
NEGATION_WINDOW_CHARS = 30
|
|
76
|
+
|
|
56
77
|
|
|
57
78
|
def _nearby(pos_a: int, pos_b: int) -> bool:
|
|
58
79
|
return abs(pos_a - pos_b) <= PROXIMITY_CHARS
|
|
59
80
|
|
|
60
81
|
|
|
82
|
+
def _is_negated(text: str, match_start: int) -> bool:
|
|
83
|
+
window = text[max(0, match_start - NEGATION_WINDOW_CHARS):match_start]
|
|
84
|
+
return NEGATION_RE.search(window) is not None
|
|
85
|
+
|
|
86
|
+
|
|
61
87
|
def _last_assistant_text(transcript_path: str) -> str:
|
|
62
88
|
"""Last assistant message's concatenated text blocks. Same pattern as
|
|
63
89
|
conclusion_scribe_hook.py's helper of the same name (that file is not
|
|
@@ -97,7 +123,9 @@ def _find_claim(text: str) -> tuple[str | None, int] | None:
|
|
|
97
123
|
https://gitlab.com/.../issues/42 for details." across two sentences. A
|
|
98
124
|
full URL match (explicit slug) wins over a bare #N. Deliberately simple:
|
|
99
125
|
false negatives here are safer than false positives."""
|
|
100
|
-
completions = [
|
|
126
|
+
completions = [
|
|
127
|
+
m.start() for m in COMPLETION_RE.finditer(text) if not _is_negated(text, m.start())
|
|
128
|
+
]
|
|
101
129
|
if not completions:
|
|
102
130
|
return None
|
|
103
131
|
for m in ISSUE_URL_RE.finditer(text):
|
package/content/manifest.json
CHANGED
|
@@ -627,6 +627,28 @@
|
|
|
627
627
|
"value": false
|
|
628
628
|
}
|
|
629
629
|
},
|
|
630
|
+
{
|
|
631
|
+
"path": "global/hooks/permission_mode_guard.py",
|
|
632
|
+
"targetPath": "hooks/permission_mode_guard.py",
|
|
633
|
+
"kind": "hook",
|
|
634
|
+
"note": "Denies EnterPlanMode when the configured default mode is bypassPermissions (exiting plan mode never restores it), and on Stop persists the live permission_mode to a per-session state file the statusline reads, warning the user on drift.",
|
|
635
|
+
"wiring": {
|
|
636
|
+
"event": "PreToolUse",
|
|
637
|
+
"matcher": "EnterPlanMode",
|
|
638
|
+
"type": "command",
|
|
639
|
+
"command": "python ~/.claude/hooks/permission_mode_guard.py"
|
|
640
|
+
}
|
|
641
|
+
},
|
|
642
|
+
{
|
|
643
|
+
"path": "global/hooks/permission_mode_guard.py",
|
|
644
|
+
"targetPath": "hooks/permission_mode_guard.py",
|
|
645
|
+
"kind": "hook",
|
|
646
|
+
"wiring": {
|
|
647
|
+
"event": "Stop",
|
|
648
|
+
"type": "command",
|
|
649
|
+
"command": "python ~/.claude/hooks/permission_mode_guard.py"
|
|
650
|
+
}
|
|
651
|
+
},
|
|
630
652
|
{
|
|
631
653
|
"path": "global/rules/context7.md",
|
|
632
654
|
"targetPath": "rules/context7.md",
|
|
@@ -928,6 +950,28 @@
|
|
|
928
950
|
{
|
|
929
951
|
"path": "skills/mattpocock-wayfinder",
|
|
930
952
|
"kind": "skill"
|
|
953
|
+
},
|
|
954
|
+
{
|
|
955
|
+
"path": "proxy/grilling_format_gate.py",
|
|
956
|
+
"kind": "hook",
|
|
957
|
+
"wiring": [
|
|
958
|
+
{
|
|
959
|
+
"event": "UserPromptSubmit",
|
|
960
|
+
"type": "command",
|
|
961
|
+
"command": "python ~/.claude/proxy/grilling_format_gate.py"
|
|
962
|
+
},
|
|
963
|
+
{
|
|
964
|
+
"event": "PreToolUse",
|
|
965
|
+
"matcher": "Skill",
|
|
966
|
+
"type": "command",
|
|
967
|
+
"command": "python ~/.claude/proxy/grilling_format_gate.py"
|
|
968
|
+
},
|
|
969
|
+
{
|
|
970
|
+
"event": "Stop",
|
|
971
|
+
"type": "command",
|
|
972
|
+
"command": "python ~/.claude/proxy/grilling_format_gate.py"
|
|
973
|
+
}
|
|
974
|
+
]
|
|
931
975
|
}
|
|
932
976
|
],
|
|
933
977
|
"deps": [],
|
|
@@ -1048,6 +1092,12 @@
|
|
|
1048
1092
|
"path": "global/CLAUDE.md",
|
|
1049
1093
|
"targetPath": "CLAUDE.md",
|
|
1050
1094
|
"kind": "rule"
|
|
1095
|
+
},
|
|
1096
|
+
{
|
|
1097
|
+
"path": "global/keybindings.json",
|
|
1098
|
+
"targetPath": "keybindings.json",
|
|
1099
|
+
"kind": "rule",
|
|
1100
|
+
"note": "Unbinds shift+tab (chat:cycleMode) so a stray keystroke can never flip a bypassPermissions session into plan/default mode mid-session (exiting plan mode never restores bypass — incident 2026-08-25); deliberate mode cycling moves to the ctrl+x m chord."
|
|
1051
1101
|
}
|
|
1052
1102
|
],
|
|
1053
1103
|
"deps": [],
|
|
@@ -1072,6 +1122,7 @@
|
|
|
1072
1122
|
}
|
|
1073
1123
|
],
|
|
1074
1124
|
"internal": [
|
|
1125
|
+
"hooks/test_tracker_proof_gate.py",
|
|
1075
1126
|
"agents/lint_agent_tools.py",
|
|
1076
1127
|
"agents/test_lint_agent_tools.py",
|
|
1077
1128
|
"agents/README.md",
|
package/content/proxy/README.md
CHANGED
|
@@ -178,7 +178,11 @@ Three files, sharing state via a JSON registry at `~/.claude/logs/bg_process_reg
|
|
|
178
178
|
|
|
179
179
|
**Escape hatch (intentionally-persistent servers)** — an entry is marked `keep_alive` and never killed if either:
|
|
180
180
|
1. the launching command contains the literal marker `# keep-alive`, or
|
|
181
|
-
2. the launching subagent's `agent_type` is in `KEEP_ALIVE_AGENT_ALLOWLIST` in `bg_process_registry.py` (currently `build-deploy`, `local-test-app`).
|
|
181
|
+
2. the launching subagent's `agent_type` is in `KEEP_ALIVE_AGENT_ALLOWLIST` in `bg_process_registry.py` (currently `build-deploy`, `local-test-app`, `maestro-launch-spine`).
|
|
182
|
+
|
|
183
|
+
**Registry-aware sparing (shared singletons under `maestro-launch-spine`)** — per PRD-maestro-launch-spine decision 8: before killing any matched pid, `reap()` calls `is_spine_claimed(pid, entry["cwd"])`, which shells out to `<cwd>/.claude/skills/maestro-launch-spine/scripts/spine_registry.py check-claimed-by-pid --pid <pid>` if that script exists for the project. A pid still claimed live by another agent (a shared Metro singleton, a device-serial lock) is spared and its registry entry is deliberately left in place (not removed) so a later reap pass — the next `SubagentStop`/`Stop`, or the TTL backstop once the entry ages past 45 minutes — re-checks and reaps it once the claim actually clears. This applies identically to the owned-session sweep and the TTL backstop, since both funnel through the same `reap()`. No project without the spine skill is affected — the script-existence check is the only gate, and its absence is silently treated as "no spine to consult," not an error. Any subprocess failure/timeout/unparseable-output (including valid-but-wrong-shape JSON, e.g. `null`) while the script DOES exist fails toward sparing (never toward killing), matching this hook's existing fail-open philosophy.
|
|
184
|
+
|
|
185
|
+
**Crash backstop for spine locks (decision 8, other half)** — every reaper invocation (`SubagentStop` and `Stop` alike) also unconditionally calls `sweep_spine_dead_locks(payload["cwd"])`, which shells out to `spine_registry.py reap-sweep` if that script exists for the project. This reuses the spine's own dead-PID `active_locks` cleanup (decision 5) rather than building a second orphan-detection mechanism here — a session/agent that crashed without calling `release` leaves its OS process dead, so the next reaper firing (any session's) clears that stale row. Silent no-op for projects without the spine skill; any subprocess failure/timeout is swallowed, never raised, since this is a best-effort maintenance sweep and must never risk blocking session/subagent stop.
|
|
182
186
|
|
|
183
187
|
**Why command-line matching, not PID** — every existing hook that touches Bash `tool_input`/`tool_response` in this repo was checked; none parse a `pid`/`bash_id`/`shell_id`/`task_id` field, confirming the hook payload for a backgrounded Bash call never exposes an OS process id (only `tool_input.command`/`run_in_background` and top-level `cwd`/`session_id`). So the reaper resolves real PID(s) best-effort at kill time via `Get-CimInstance Win32_Process`, filtered by `CommandLine` fragment + `CreationDate >= launch_ts`.
|
|
184
188
|
|
|
@@ -336,7 +340,7 @@ A local routing proxy lets `/switch-model` redirect the **main session** to any
|
|
|
336
340
|
| File | Role |
|
|
337
341
|
|---|---|
|
|
338
342
|
| `proxy/claude_router.py` | The routing daemon. Reads `LITELLM_MASTER_KEY` from env, listens on `127.0.0.1:3456`. **Routing is by model-name prefix, not caller identity**: `route_decision(model, is_subagent)` sends any `claude-*`/`anthropic/*` model to Anthropic, always — a claude-family model from a subagent never leaks to LiteLLM, even under a stale `model_override.txt` (the override only ever applies to the main session; see `is_subagent` guard in `apply_model_override`). Any `litellm_`-prefixed model id is forwarded verbatim to LiteLLM (`127.0.0.1:4000`); an unmapped (non-`litellm_`-prefixed, non-Claude) model fails loudly (502) rather than silently falling back to anything. The `X-Claude-Code-Agent-Id` header is used only to derive `is_subagent` for logging/override-eligibility — it plays no part in the host decision. This invariant is pinned by `proxy/tests/test_router_invariants.py`. Also raw-socket-splices WebSocket upgrades straight to `api.anthropic.com` (see WebSocket note below). |
|
|
339
|
-
| `proxy/switch_model.ps1` | `/switch-model` backend. Writes/clears `model_override.txt` next to itself (uses `$PSScriptRoot` — no hardcoded username). Aliases: `sonnet`→`claude-sonnet-5`, `opus`→`claude-opus-
|
|
343
|
+
| `proxy/switch_model.ps1` | `/switch-model` backend. Writes/clears `model_override.txt` next to itself (uses `$PSScriptRoot` — no hardcoded username). Aliases: `sonnet`→`claude-sonnet-5`, `opus`→`claude-opus-4-8`, `haiku`→`claude-haiku-4-5-20251001`, `fable`→`claude-fable-5`, plus the non-Claude aliases (glm/deepseek/qwen), which now route to LiteLLM. Any `claude-*` alias clears the override file. |
|
|
340
344
|
| `proxy/remote_mode.ps1` | `remote_mode.ps1 on\|off\|status` — toggles Remote-Control mode vs proxy mode by editing `ANTHROPIC_BASE_URL` in `settings.json`. The two are mutually exclusive (see "Remote Control vs proxy mode" below). |
|
|
341
345
|
| `proxy/start.ps1` | Manual recovery launcher (preferred path is the scheduled task). |
|
|
342
346
|
| `proxy/autostart_hook.py` | `UserPromptSubmit` hook — TCP-probes the proxy and warns if it's down; also warns (never silently) if `model_override.txt` is non-empty, since a leftover `/switch-model` override otherwise rewrites every main-session request without any visible sign. |
|
|
@@ -16,6 +16,22 @@ Same script is wired to both events:
|
|
|
16
16
|
- Both invocations additionally sweep any TTL-stale entry (>=45 min old)
|
|
17
17
|
regardless of session/owner, as a backstop for correlation misses (e.g.
|
|
18
18
|
a session that crashed instead of firing Stop cleanly).
|
|
19
|
+
- Before killing ANY matched pid (owned-session sweep or TTL backstop
|
|
20
|
+
alike), bg_process_registry.reap() consults the project's
|
|
21
|
+
maestro-launch-spine registry (if it has one) via
|
|
22
|
+
is_spine_claimed() and spares any pid a still-live agent legitimately
|
|
23
|
+
holds (a shared Metro singleton, a device-serial lock) -- per
|
|
24
|
+
PRD-maestro-launch-spine decision 8. Fails toward sparing if that
|
|
25
|
+
check is itself unreachable. See bg_process_registry.py for the
|
|
26
|
+
mechanics; this hook has no project-specific knowledge of it.
|
|
27
|
+
- Every invocation also opportunistically calls
|
|
28
|
+
bg_process_registry.sweep_spine_dead_locks(cwd), which shells out to
|
|
29
|
+
the project's own `spine_registry.py reap-sweep` (dead-PID active_locks
|
|
30
|
+
cleanup) if that script exists -- the other half of decision 8: a
|
|
31
|
+
session/agent that crashed without calling `release` gets its
|
|
32
|
+
active_locks row cleared via the spine's own dead-PID check, reused
|
|
33
|
+
rather than duplicated here. No-op, silently, for projects without the
|
|
34
|
+
spine skill.
|
|
19
35
|
|
|
20
36
|
Fail-open: any malformed input or internal error exits 0, never blocks
|
|
21
37
|
the session/subagent from actually stopping.
|
|
@@ -47,9 +63,12 @@ def _safe_main() -> int:
|
|
|
47
63
|
session_id = payload.get("session_id") or ""
|
|
48
64
|
agent_id = payload.get("agent_id")
|
|
49
65
|
hook_event = payload.get("hook_event_name") or ""
|
|
66
|
+
cwd = payload.get("cwd")
|
|
50
67
|
|
|
51
68
|
to_remove: set[str] = set()
|
|
52
69
|
|
|
70
|
+
registry.sweep_spine_dead_locks(cwd)
|
|
71
|
+
|
|
53
72
|
try:
|
|
54
73
|
if hook_event == "SubagentStop" and session_id and agent_id:
|
|
55
74
|
owned = registry.entries_for_session(session_id, agent_id=agent_id)
|
|
@@ -32,6 +32,7 @@ import os
|
|
|
32
32
|
import re
|
|
33
33
|
import shlex
|
|
34
34
|
import subprocess
|
|
35
|
+
import sys
|
|
35
36
|
import time
|
|
36
37
|
import uuid
|
|
37
38
|
|
|
@@ -50,8 +51,16 @@ TTL_SECONDS = 45 * 60
|
|
|
50
51
|
KEEP_ALIVE_AGENT_ALLOWLIST = {
|
|
51
52
|
"build-deploy",
|
|
52
53
|
"local-test-app",
|
|
54
|
+
"maestro-launch-spine",
|
|
53
55
|
}
|
|
54
56
|
|
|
57
|
+
# Filename of the (optional, per-project) maestro-launch-spine registry CLI,
|
|
58
|
+
# resolved relative to an entry's own `cwd` -- see is_spine_claimed() below.
|
|
59
|
+
# Most projects don't have this skill at all; its absence is not an error.
|
|
60
|
+
_SPINE_REGISTRY_RELPATH = os.path.join(
|
|
61
|
+
".claude", "skills", "maestro-launch-spine", "scripts", "spine_registry.py"
|
|
62
|
+
)
|
|
63
|
+
|
|
55
64
|
KEEP_ALIVE_MARKER = "# keep-alive"
|
|
56
65
|
|
|
57
66
|
_SEPARATOR_RE = re.compile(r"^[;&|]+$")
|
|
@@ -274,10 +283,95 @@ def kill_pid_tree(pid: int) -> bool:
|
|
|
274
283
|
return result.returncode == 0
|
|
275
284
|
|
|
276
285
|
|
|
286
|
+
def _spine_registry_script(cwd: str | None) -> str | None:
|
|
287
|
+
if not cwd:
|
|
288
|
+
return None
|
|
289
|
+
candidate = os.path.join(cwd, _SPINE_REGISTRY_RELPATH)
|
|
290
|
+
return candidate if os.path.isfile(candidate) else None
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def is_spine_claimed(pid: int, cwd: str | None) -> bool:
|
|
294
|
+
"""Best-effort: ask the project's maestro-launch-spine registry (if it
|
|
295
|
+
has one) whether `pid` is the live owner of an active_locks row --
|
|
296
|
+
i.e. a shared Metro singleton or device-serial lock another still-live
|
|
297
|
+
agent legitimately holds, per PRD-maestro-launch-spine decision 8.
|
|
298
|
+
|
|
299
|
+
Fails toward True (spare the process) whenever the check itself can't
|
|
300
|
+
be trusted: subprocess failure/timeout, output that doesn't parse as
|
|
301
|
+
JSON, or JSON that parses but isn't the expected object shape (e.g.
|
|
302
|
+
`null`) -- unreachable via the current CLI contract, but guarded so a
|
|
303
|
+
future CLI change can't turn into an uncaught AttributeError that
|
|
304
|
+
escapes this function's fail-open contract. A false-spare costs
|
|
305
|
+
nothing (the process just gets re-checked next reap pass); a
|
|
306
|
+
false-kill can destroy another agent's live shared-singleton work,
|
|
307
|
+
which is the whole failure mode this guards against.
|
|
308
|
+
|
|
309
|
+
Only returns False outright -- no spine to consult, proceed with normal
|
|
310
|
+
kill logic -- when the CLI script doesn't exist for this project at
|
|
311
|
+
all; most projects don't have this skill, and that's not an error.
|
|
312
|
+
Exit code 1 from the CLI is a valid "not claimed" answer (see
|
|
313
|
+
spine_registry.py main()), not a failure -- only exceptions and
|
|
314
|
+
unparseable output are treated as failures here.
|
|
315
|
+
"""
|
|
316
|
+
script = _spine_registry_script(cwd)
|
|
317
|
+
if script is None:
|
|
318
|
+
return False
|
|
319
|
+
try:
|
|
320
|
+
result = subprocess.run(
|
|
321
|
+
[sys.executable, script, "check-claimed-by-pid", "--pid", str(pid)],
|
|
322
|
+
capture_output=True, text=True, timeout=15,
|
|
323
|
+
)
|
|
324
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
325
|
+
return True
|
|
326
|
+
try:
|
|
327
|
+
payload = json.loads(result.stdout or "")
|
|
328
|
+
except json.JSONDecodeError:
|
|
329
|
+
return True
|
|
330
|
+
if not isinstance(payload, dict):
|
|
331
|
+
return True
|
|
332
|
+
return bool(payload.get("claimed"))
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def sweep_spine_dead_locks(cwd: str | None) -> None:
|
|
336
|
+
"""Crash backstop for PRD-maestro-launch-spine decision 8: "the existing
|
|
337
|
+
bg-process-reaper hook is extended to also clear the caller's registry
|
|
338
|
+
slot if a session ends without explicit release." Opportunistically
|
|
339
|
+
invokes the project's own `spine_registry.py reap-sweep` (its dead-PID
|
|
340
|
+
active_locks cleanup, already covers decision 5's stale-lock rule) on
|
|
341
|
+
every Stop/SubagentStop, rather than building a second orphan-detection
|
|
342
|
+
mechanism in this hook. A session/agent that crashed without calling
|
|
343
|
+
`release` leaves its OS process dead, so the spine's own dead-PID check
|
|
344
|
+
clears the row the next time anything triggers a sweep -- this just
|
|
345
|
+
makes "every reaper firing" one of those triggers.
|
|
346
|
+
|
|
347
|
+
Fail-open and silent: no spine script for this project, or any
|
|
348
|
+
subprocess failure/timeout, is not an error -- this is a best-effort
|
|
349
|
+
maintenance sweep, not the reaper's core kill duty, and must never risk
|
|
350
|
+
blocking session/subagent stop."""
|
|
351
|
+
script = _spine_registry_script(cwd)
|
|
352
|
+
if script is None:
|
|
353
|
+
return
|
|
354
|
+
try:
|
|
355
|
+
subprocess.run(
|
|
356
|
+
[sys.executable, script, "reap-sweep"],
|
|
357
|
+
capture_output=True, text=True, timeout=15,
|
|
358
|
+
)
|
|
359
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
360
|
+
pass
|
|
361
|
+
|
|
362
|
+
|
|
277
363
|
def reap(entries: list[dict], *, reason: str) -> list[dict]:
|
|
278
|
-
"""Kill every non-keep_alive entry's matched
|
|
279
|
-
list of entries actually processed (killed
|
|
280
|
-
the caller
|
|
364
|
+
"""Kill every non-keep_alive, non-spine-claimed entry's matched
|
|
365
|
+
process(es) and return the list of entries actually processed (killed
|
|
366
|
+
or skipped), for the caller to remove from the registry. Does not
|
|
367
|
+
remove entries itself -- caller decides.
|
|
368
|
+
|
|
369
|
+
An entry with at least one spine-claimed pid is deliberately NOT
|
|
370
|
+
included in the returned list, even if other pids under it were killed
|
|
371
|
+
-- it stays tracked so a later reap pass (the next Stop/SubagentStop,
|
|
372
|
+
or the TTL backstop once it ages past TTL_SECONDS) re-checks the claim
|
|
373
|
+
and reaps it once the claim is actually released. This differs from
|
|
374
|
+
keep_alive, which is a permanent, deliberate opt-out of tracking."""
|
|
281
375
|
processed = []
|
|
282
376
|
for entry in entries:
|
|
283
377
|
if entry.get("keep_alive"):
|
|
@@ -289,11 +383,21 @@ def reap(entries: list[dict], *, reason: str) -> list[dict]:
|
|
|
289
383
|
_log(f"NO-MATCH id={entry['id']} cmd={entry.get('command')!r} reason={reason}")
|
|
290
384
|
processed.append(entry)
|
|
291
385
|
continue
|
|
386
|
+
spared = False
|
|
292
387
|
for pid in pids:
|
|
388
|
+
if is_spine_claimed(pid, entry.get("cwd")):
|
|
389
|
+
spared = True
|
|
390
|
+
_log(
|
|
391
|
+
f"SPARE spine-claimed id={entry['id']} pid={pid} "
|
|
392
|
+
f"cmd={entry.get('command')!r} reason={reason}"
|
|
393
|
+
)
|
|
394
|
+
continue
|
|
293
395
|
killed = kill_pid_tree(pid)
|
|
294
396
|
_log(
|
|
295
397
|
f"{'KILLED' if killed else 'KILL-FAILED'} id={entry['id']} pid={pid} "
|
|
296
398
|
f"cmd={entry.get('command')!r} reason={reason}"
|
|
297
399
|
)
|
|
400
|
+
if spared:
|
|
401
|
+
continue
|
|
298
402
|
processed.append(entry)
|
|
299
403
|
return processed
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
grilling_format_gate.py — deterministic format enforcement for the
|
|
4
|
+
mattpocock-grilling skill's Q&A delivery.
|
|
5
|
+
|
|
6
|
+
mattpocock-grilling's own SKILL.md says to deliver each round's question(s)
|
|
7
|
+
via the interactive AskUserQuestion tool, not as prose — but that's advisory
|
|
8
|
+
text an LLM can silently drop mid-session (e.g. after a compaction, or once
|
|
9
|
+
the novelty of the instruction wears off). This hook is the mechanical
|
|
10
|
+
backstop, in three parts driven by `hook_event_name`:
|
|
11
|
+
|
|
12
|
+
1. UserPromptSubmit — if the prompt matches a grill trigger phrase ("grill
|
|
13
|
+
me", "stress-test", "poke holes", ...), write a session-scoped flag file
|
|
14
|
+
marking a grilling session active. Never blocks; UserPromptSubmit hooks
|
|
15
|
+
can't deny.
|
|
16
|
+
2. PreToolUse (matcher "Skill") — if tool_input names the mattpocock-grilling
|
|
17
|
+
skill, write/refresh the same flag. Always allows (no decision emitted).
|
|
18
|
+
3. Stop — if the flag is active and not expired: look at every assistant
|
|
19
|
+
message since the last genuine user turn (a real typed prompt, not a
|
|
20
|
+
tool_result echoed back with role "user"). If that segment contains an
|
|
21
|
+
AskUserQuestion tool_use, the format was followed — allow. If instead the
|
|
22
|
+
assistant's final text block ends a line in "?" (a prose question), block
|
|
23
|
+
the Stop event and tell the model to re-deliver it through AskUserQuestion.
|
|
24
|
+
The skill's own completion phrase ("shared understanding") always clears
|
|
25
|
+
the flag and allows. A block counter caps retries at 3 so a stubborn model
|
|
26
|
+
can never be trapped in a permanent Stop loop.
|
|
27
|
+
|
|
28
|
+
Flag file: `<transcript_dir>/.grilling_active_<session_id>.json`, content
|
|
29
|
+
`{"expires": <unix ts>, "blocks": <int>}`. Session-scoped by putting it next
|
|
30
|
+
to that session's own transcript file (same technique as reading
|
|
31
|
+
transcript_path in tracker_proof_gate.py) and keying the filename on
|
|
32
|
+
session_id so concurrent sessions sharing a project transcript dir never
|
|
33
|
+
collide. TTL 3 hours from the triggering event.
|
|
34
|
+
|
|
35
|
+
Fails OPEN on every error path (missing/malformed stdin, unreadable
|
|
36
|
+
transcript, unparseable JSON, any unexpected exception) — an enforcement hook
|
|
37
|
+
must never crash or wedge a user turn.
|
|
38
|
+
"""
|
|
39
|
+
from __future__ import annotations
|
|
40
|
+
|
|
41
|
+
# CLAUDE_HOOK_CHILD guard: hook-spawned child claude processes set this so
|
|
42
|
+
# this hook never re-fires recursively. Must run before any other I/O.
|
|
43
|
+
import os, sys
|
|
44
|
+
if os.environ.get("CLAUDE_HOOK_CHILD"):
|
|
45
|
+
sys.exit(0)
|
|
46
|
+
|
|
47
|
+
import json
|
|
48
|
+
import time
|
|
49
|
+
from pathlib import Path
|
|
50
|
+
|
|
51
|
+
FLAG_TTL_SECONDS = 3 * 60 * 60 # 3 hours
|
|
52
|
+
MAX_BLOCKS = 3
|
|
53
|
+
|
|
54
|
+
GRILL_PHRASES = (
|
|
55
|
+
"grill me",
|
|
56
|
+
"grill this",
|
|
57
|
+
"grill my",
|
|
58
|
+
"stress-test",
|
|
59
|
+
"stress test my thinking",
|
|
60
|
+
"poke holes",
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
COMPLETION_PHRASE = "shared understanding"
|
|
64
|
+
|
|
65
|
+
BLOCK_REASON = (
|
|
66
|
+
"Grilling in progress: deliver this round's question(s) via the "
|
|
67
|
+
"AskUserQuestion tool (2-4 concrete options, your recommended pick "
|
|
68
|
+
"first and labeled), not as prose. Re-ask the frontier through "
|
|
69
|
+
"AskUserQuestion."
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _flag_path(data: dict) -> Path | None:
|
|
74
|
+
"""Session-scoped flag path: next to this session's own transcript file,
|
|
75
|
+
keyed on session_id. Returns None if either is missing/unusable."""
|
|
76
|
+
transcript_path = data.get("transcript_path") or ""
|
|
77
|
+
session_id = data.get("session_id") or ""
|
|
78
|
+
if not transcript_path or not session_id:
|
|
79
|
+
return None
|
|
80
|
+
try:
|
|
81
|
+
transcript_dir = Path(transcript_path).resolve().parent
|
|
82
|
+
except Exception:
|
|
83
|
+
return None
|
|
84
|
+
return transcript_dir / f".grilling_active_{session_id}.json"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _read_flag(path: Path) -> dict | None:
|
|
88
|
+
try:
|
|
89
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
90
|
+
except Exception:
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _write_flag(path: Path, expires: float, blocks: int) -> None:
|
|
95
|
+
try:
|
|
96
|
+
path.write_text(json.dumps({"expires": expires, "blocks": blocks}), encoding="utf-8")
|
|
97
|
+
except Exception:
|
|
98
|
+
pass # fail open: a state-write failure must not crash the hook
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _activate(path: Path) -> None:
|
|
102
|
+
"""Set (or refresh) the flag, preserving any existing block count."""
|
|
103
|
+
existing = _read_flag(path) or {}
|
|
104
|
+
blocks = existing.get("blocks", 0) if isinstance(existing.get("blocks"), int) else 0
|
|
105
|
+
_write_flag(path, time.time() + FLAG_TTL_SECONDS, blocks)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _prompt_matches_grill(prompt: str) -> bool:
|
|
109
|
+
prompt_lower = prompt.lower()
|
|
110
|
+
return any(phrase in prompt_lower for phrase in GRILL_PHRASES)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _handle_user_prompt_submit(data: dict) -> None:
|
|
114
|
+
prompt = (data.get("prompt") or "").strip()
|
|
115
|
+
if not prompt or not _prompt_matches_grill(prompt):
|
|
116
|
+
return
|
|
117
|
+
path = _flag_path(data)
|
|
118
|
+
if path is None:
|
|
119
|
+
return
|
|
120
|
+
_activate(path)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _handle_pre_tool_use(data: dict) -> None:
|
|
124
|
+
if data.get("tool_name") != "Skill":
|
|
125
|
+
return
|
|
126
|
+
tool_input = data.get("tool_input") or {}
|
|
127
|
+
# The Skill tool's input schema isn't pinned down by any existing hook in
|
|
128
|
+
# this repo (nothing else keys on it yet) -- check the likely field names
|
|
129
|
+
# first, then fall back to a substring scan of the whole tool_input so a
|
|
130
|
+
# schema this hook didn't anticipate still matches rather than silently
|
|
131
|
+
# missing the flag.
|
|
132
|
+
skill_name = tool_input.get("skill") or tool_input.get("name") or tool_input.get("command") or ""
|
|
133
|
+
if "mattpocock-grilling" not in str(skill_name) and "mattpocock-grilling" not in json.dumps(tool_input):
|
|
134
|
+
return
|
|
135
|
+
path = _flag_path(data)
|
|
136
|
+
if path is None:
|
|
137
|
+
return
|
|
138
|
+
_activate(path)
|
|
139
|
+
# No decision emitted -> implicit allow.
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _iter_transcript_entries(transcript_path: str):
|
|
143
|
+
with open(transcript_path, "r", encoding="utf-8", errors="replace") as fh:
|
|
144
|
+
for line in fh:
|
|
145
|
+
line = line.strip()
|
|
146
|
+
if not line:
|
|
147
|
+
continue
|
|
148
|
+
try:
|
|
149
|
+
yield json.loads(line)
|
|
150
|
+
except Exception:
|
|
151
|
+
continue
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _is_genuine_user_turn(entry: dict) -> bool:
|
|
155
|
+
"""True for a real typed user prompt; False for a tool_result echoed
|
|
156
|
+
back under role "user", or a meta/system-injected entry."""
|
|
157
|
+
if entry.get("isMeta"):
|
|
158
|
+
return False
|
|
159
|
+
msg = entry.get("message") or {}
|
|
160
|
+
if msg.get("role") != "user":
|
|
161
|
+
return False
|
|
162
|
+
content = msg.get("content")
|
|
163
|
+
if isinstance(content, str):
|
|
164
|
+
return bool(content.strip())
|
|
165
|
+
if isinstance(content, list):
|
|
166
|
+
if not content:
|
|
167
|
+
return False
|
|
168
|
+
# Content that is entirely tool_result blocks is a tool response
|
|
169
|
+
# being replayed under role "user", not something the human typed.
|
|
170
|
+
return not all(
|
|
171
|
+
isinstance(item, dict) and item.get("type") == "tool_result"
|
|
172
|
+
for item in content
|
|
173
|
+
)
|
|
174
|
+
return False
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _assistant_text(msg: dict) -> str:
|
|
178
|
+
content = msg.get("content")
|
|
179
|
+
if isinstance(content, str):
|
|
180
|
+
return content
|
|
181
|
+
if isinstance(content, list):
|
|
182
|
+
return "".join(
|
|
183
|
+
item.get("text", "") for item in content
|
|
184
|
+
if isinstance(item, dict) and item.get("type") == "text"
|
|
185
|
+
)
|
|
186
|
+
return ""
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _segment_has_ask_user_question(entries: list, boundary_idx: int) -> bool:
|
|
190
|
+
for entry in entries[boundary_idx + 1:]:
|
|
191
|
+
msg = entry.get("message") or {}
|
|
192
|
+
if msg.get("role") != "assistant":
|
|
193
|
+
continue
|
|
194
|
+
content = msg.get("content")
|
|
195
|
+
if not isinstance(content, list):
|
|
196
|
+
continue
|
|
197
|
+
for item in content:
|
|
198
|
+
if isinstance(item, dict) and item.get("type") == "tool_use" and item.get("name") == "AskUserQuestion":
|
|
199
|
+
return True
|
|
200
|
+
return False
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _final_assistant_text(entries: list) -> str:
|
|
204
|
+
last = ""
|
|
205
|
+
for entry in entries:
|
|
206
|
+
msg = entry.get("message") or {}
|
|
207
|
+
if msg.get("role") != "assistant":
|
|
208
|
+
continue
|
|
209
|
+
text = _assistant_text(msg)
|
|
210
|
+
if text.strip():
|
|
211
|
+
last = text
|
|
212
|
+
return last
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _posed_prose_question(text: str) -> bool:
|
|
216
|
+
for line in text.splitlines():
|
|
217
|
+
if line.strip().endswith("?"):
|
|
218
|
+
return True
|
|
219
|
+
return False
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _block(reason: str) -> None:
|
|
223
|
+
print(json.dumps({"decision": "block", "reason": reason}))
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _handle_stop(data: dict) -> None:
|
|
227
|
+
path = _flag_path(data)
|
|
228
|
+
if path is None:
|
|
229
|
+
return
|
|
230
|
+
flag = _read_flag(path)
|
|
231
|
+
if flag is None:
|
|
232
|
+
return # no active grilling session -> nothing to enforce
|
|
233
|
+
|
|
234
|
+
now = time.time()
|
|
235
|
+
expires = flag.get("expires")
|
|
236
|
+
if not isinstance(expires, (int, float)) or now > expires:
|
|
237
|
+
path.unlink(missing_ok=True)
|
|
238
|
+
return
|
|
239
|
+
|
|
240
|
+
transcript_path = data.get("transcript_path") or ""
|
|
241
|
+
if not transcript_path or not os.path.isfile(transcript_path):
|
|
242
|
+
return # can't inspect the transcript -> fail open
|
|
243
|
+
|
|
244
|
+
entries = list(_iter_transcript_entries(transcript_path))
|
|
245
|
+
if not entries:
|
|
246
|
+
return
|
|
247
|
+
|
|
248
|
+
boundary_idx = -1
|
|
249
|
+
for idx in range(len(entries) - 1, -1, -1):
|
|
250
|
+
if _is_genuine_user_turn(entries[idx]):
|
|
251
|
+
boundary_idx = idx
|
|
252
|
+
break
|
|
253
|
+
|
|
254
|
+
if _segment_has_ask_user_question(entries, boundary_idx):
|
|
255
|
+
return # correct format was used -> allow
|
|
256
|
+
|
|
257
|
+
final_text = _final_assistant_text(entries)
|
|
258
|
+
if not final_text:
|
|
259
|
+
return
|
|
260
|
+
|
|
261
|
+
if COMPLETION_PHRASE in final_text.lower():
|
|
262
|
+
path.unlink(missing_ok=True)
|
|
263
|
+
return # grilling session concluded -> never block a completion turn
|
|
264
|
+
|
|
265
|
+
if not _posed_prose_question(final_text):
|
|
266
|
+
return # no question posed at all -> nothing to enforce here
|
|
267
|
+
|
|
268
|
+
blocks = flag.get("blocks", 0)
|
|
269
|
+
blocks = blocks + 1 if isinstance(blocks, int) else 1
|
|
270
|
+
if blocks >= MAX_BLOCKS:
|
|
271
|
+
path.unlink(missing_ok=True)
|
|
272
|
+
return # loop cap hit -> stop blocking, never trap the session
|
|
273
|
+
|
|
274
|
+
_write_flag(path, expires, blocks)
|
|
275
|
+
_block(BLOCK_REASON)
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _safe_main() -> None:
|
|
279
|
+
try:
|
|
280
|
+
raw = sys.stdin.buffer.read().decode("utf-8")
|
|
281
|
+
data = json.loads(raw or "{}")
|
|
282
|
+
except Exception:
|
|
283
|
+
return
|
|
284
|
+
|
|
285
|
+
event = data.get("hook_event_name")
|
|
286
|
+
if event == "UserPromptSubmit":
|
|
287
|
+
_handle_user_prompt_submit(data)
|
|
288
|
+
elif event == "PreToolUse":
|
|
289
|
+
_handle_pre_tool_use(data)
|
|
290
|
+
elif event == "Stop":
|
|
291
|
+
_handle_stop(data)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
if __name__ == "__main__":
|
|
295
|
+
try:
|
|
296
|
+
_safe_main()
|
|
297
|
+
except Exception:
|
|
298
|
+
pass # never wedge Claude Code
|
|
@@ -10,7 +10,7 @@ $OVERRIDE = Join-Path $PSScriptRoot "model_override.txt"
|
|
|
10
10
|
|
|
11
11
|
$MODELS = @{
|
|
12
12
|
"sonnet" = "claude-sonnet-5"
|
|
13
|
-
"opus" = "claude-opus-
|
|
13
|
+
"opus" = "claude-opus-4-8"
|
|
14
14
|
"haiku" = "claude-haiku-4-5-20251001"
|
|
15
15
|
"fable" = "claude-fable-5"
|
|
16
16
|
"deepseek" = "litellm_deepseek"
|
|
@@ -7,7 +7,7 @@ Interview the user relentlessly until you reach a shared understanding. Map this
|
|
|
7
7
|
|
|
8
8
|
Work the tree in **rounds**. The **frontier** is every decision whose prerequisites are already settled — the questions you can ask _now_ without guessing at answers you haven't heard yet. Ask the whole frontier in one round: number each question and give your recommended answer. Then wait for the user's answers before the next round.
|
|
9
9
|
|
|
10
|
-
**Delivery: use the `AskUserQuestion` tool, one question at a time — never dump a round as a markdown wall of text.** Compute the whole frontier first, but fire it as a sequence of single `AskUserQuestion` calls, waiting for each answer before asking the next. Each call must offer 2-4 concrete, mutually-exclusive options (not just yes/no) — genuine alternative answers to the decision, each with its own trade-off — plus your recommended option first, labeled "(Recommended)" per the tool's convention. Put nuance, multi-paragraph context, and the "why" in each option's `description`, not in a separate prose block.
|
|
10
|
+
**Delivery: use the `AskUserQuestion` tool, one question at a time — never dump a round as a markdown wall of text.** This is enforced: a Stop hook blocks any turn that yields prose questions during a grill without an `AskUserQuestion` call. Compute the whole frontier first, but fire it as a sequence of single `AskUserQuestion` calls, waiting for each answer before asking the next. Each call must offer 2-4 concrete, mutually-exclusive options (not just yes/no) — genuine alternative answers to the decision, each with its own trade-off — plus your recommended option first, labeled "(Recommended)" per the tool's convention. Put nuance, multi-paragraph context, and the "why" in each option's `description`, not in a separate prose block.
|
|
11
11
|
|
|
12
12
|
Each round the user answers reshapes the tree — settled decisions push the frontier outward and unblock questions that depended on them. Recompute the frontier and ask the next round, one `AskUserQuestion` call at a time. A question whose answer depends on another question still open in this round belongs to a _later_ round, not this one.
|
|
13
13
|
|
|
@@ -15,7 +15,7 @@ ship-the-code/ship.py.
|
|
|
15
15
|
|
|
16
16
|
Usage:
|
|
17
17
|
python gitlab_phase.py list-candidates --parent-iid IID
|
|
18
|
-
python gitlab_phase.py append-phase --iid IID --title T --body B [--reopen]
|
|
18
|
+
python gitlab_phase.py append-phase --iid IID --title T --body B [--reopen] [--if-absent]
|
|
19
19
|
python gitlab_phase.py mark-done --iid IID --title T --result R
|
|
20
20
|
|
|
21
21
|
Exit codes: 0 success, 1 usage/API error.
|
|
@@ -64,16 +64,26 @@ def _project_path(scribe) -> str:
|
|
|
64
64
|
return urllib.parse.unquote(scribe.discover_project())
|
|
65
65
|
|
|
66
66
|
|
|
67
|
+
PER_PAGE = 100
|
|
68
|
+
|
|
69
|
+
|
|
67
70
|
def cmd_list_candidates(args, scribe, token, pp: str) -> None:
|
|
68
71
|
quoted = urllib.parse.quote(pp, safe="")
|
|
69
|
-
children =
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
72
|
+
children: list[dict] = []
|
|
73
|
+
page = 1
|
|
74
|
+
while True:
|
|
75
|
+
batch = scribe.gl_get(
|
|
76
|
+
f"/projects/{quoted}/issues", token,
|
|
77
|
+
{"scope": "all", "state": "all", "per_page": PER_PAGE, "page": page},
|
|
78
|
+
) or []
|
|
79
|
+
children.extend(batch)
|
|
80
|
+
if len(batch) < PER_PAGE:
|
|
81
|
+
break
|
|
82
|
+
page += 1
|
|
73
83
|
out = [
|
|
74
84
|
{"iid": c["iid"], "title": c["title"], "state": c["state"],
|
|
75
85
|
"description": c.get("description") or "", "web_url": c.get("web_url", "")}
|
|
76
|
-
for c in
|
|
86
|
+
for c in children
|
|
77
87
|
]
|
|
78
88
|
print(json.dumps(out, indent=2))
|
|
79
89
|
|
|
@@ -87,11 +97,19 @@ def _append_phase_to_description(description: str, title: str, body: str) -> str
|
|
|
87
97
|
return description.rstrip() + f"\n{entry}\n"
|
|
88
98
|
|
|
89
99
|
|
|
100
|
+
def _phase_line_exists(description: str, title: str) -> bool:
|
|
101
|
+
pattern = re.compile(PHASE_LINE_RE_TEMPLATE.format(title=re.escape(title)), re.MULTILINE)
|
|
102
|
+
return bool(pattern.search(description))
|
|
103
|
+
|
|
104
|
+
|
|
90
105
|
def cmd_append_phase(args, scribe, token, pp: str) -> None:
|
|
91
106
|
quoted = urllib.parse.quote(pp, safe="")
|
|
92
107
|
issue = scribe.gl_get(f"/projects/{quoted}/issues/{args.iid}", token)
|
|
93
|
-
|
|
94
|
-
|
|
108
|
+
description = issue.get("description") or ""
|
|
109
|
+
if args.if_absent and _phase_line_exists(description, args.title):
|
|
110
|
+
print(json.dumps({"iid": args.iid, "skipped": True, "reason": "phase already present"}))
|
|
111
|
+
return
|
|
112
|
+
new_description = _append_phase_to_description(description, args.title, args.body)
|
|
95
113
|
scribe.gl_put(f"/projects/{quoted}/issues/{args.iid}", token,
|
|
96
114
|
{"description": new_description})
|
|
97
115
|
if args.reopen:
|
|
@@ -143,6 +161,8 @@ def main() -> None:
|
|
|
143
161
|
p2.add_argument("--title", required=True)
|
|
144
162
|
p2.add_argument("--body", required=True)
|
|
145
163
|
p2.add_argument("--reopen", action="store_true")
|
|
164
|
+
p2.add_argument("--if-absent", dest="if_absent", action="store_true",
|
|
165
|
+
help="Skip the write (exit 0) if a phase line for --title already exists.")
|
|
146
166
|
|
|
147
167
|
p3 = sub.add_parser("mark-done", help="Check a phase's box, append its result, post a completion comment.")
|
|
148
168
|
p3.add_argument("--iid", required=True, type=int)
|
|
@@ -107,7 +107,13 @@ class FakeScribe:
|
|
|
107
107
|
def gl_get(self, path, token, params=None):
|
|
108
108
|
self.calls.append(("gl_get", path, params))
|
|
109
109
|
if path.endswith("/issues"):
|
|
110
|
-
|
|
110
|
+
all_issues = list(self.issues.values())
|
|
111
|
+
if params and "page" in params:
|
|
112
|
+
per_page = params.get("per_page", 100)
|
|
113
|
+
page = params["page"]
|
|
114
|
+
start = (page - 1) * per_page
|
|
115
|
+
return all_issues[start:start + per_page]
|
|
116
|
+
return all_issues
|
|
111
117
|
iid = int(path.rsplit("/", 1)[-1])
|
|
112
118
|
return self.issues[iid]
|
|
113
119
|
|
|
@@ -146,23 +152,70 @@ def test_cmd_list_candidates_returns_open_and_closed(fake_scribe, capsys):
|
|
|
146
152
|
gp.cmd_list_candidates(args, fake_scribe, "tok", "ns/project")
|
|
147
153
|
out = capsys.readouterr().out
|
|
148
154
|
assert "Rate limiting" in out and "Old audit work" in out
|
|
149
|
-
assert ("gl_get", "/projects/ns%2Fproject/issues",
|
|
155
|
+
assert ("gl_get", "/projects/ns%2Fproject/issues",
|
|
156
|
+
{"scope": "all", "state": "all", "per_page": 100, "page": 1}) in fake_scribe.calls
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def test_cmd_list_candidates_paginates_past_100_issues(capsys):
|
|
160
|
+
issues = {
|
|
161
|
+
i: {"iid": i, "title": f"Issue {i}", "state": "opened",
|
|
162
|
+
"description": "", "web_url": f"https://gitlab.example/{i}"}
|
|
163
|
+
for i in range(1, 155)
|
|
164
|
+
}
|
|
165
|
+
scribe = FakeScribe(issues)
|
|
166
|
+
args = argparse.Namespace(parent_iid=None)
|
|
167
|
+
gp.cmd_list_candidates(args, scribe, "tok", "ns/project")
|
|
168
|
+
out = capsys.readouterr().out
|
|
169
|
+
assert out.count('"iid"') == 154
|
|
170
|
+
assert "Issue 1" in out and "Issue 154" in out
|
|
171
|
+
page_calls = [c for c in scribe.calls if c[0] == "gl_get"]
|
|
172
|
+
assert len(page_calls) == 2 # 100 + 54 -> short page stops the loop
|
|
173
|
+
assert page_calls[0][2]["page"] == 1
|
|
174
|
+
assert page_calls[1][2]["page"] == 2
|
|
150
175
|
|
|
151
176
|
|
|
152
177
|
def test_cmd_append_phase_appends_and_does_not_reopen_open_issue(fake_scribe, capsys):
|
|
153
|
-
args = argparse.Namespace(iid=7, title="New phase", body="Do the thing.", reopen=False)
|
|
178
|
+
args = argparse.Namespace(iid=7, title="New phase", body="Do the thing.", reopen=False, if_absent=False)
|
|
154
179
|
gp.cmd_append_phase(args, fake_scribe, "tok", "ns/project")
|
|
155
180
|
assert "New phase" in fake_scribe.issues[7]["description"]
|
|
156
181
|
assert not any(c[0] == "gl_put" and c[2].get("state_event") == "reopen" for c in fake_scribe.calls)
|
|
157
182
|
|
|
158
183
|
|
|
159
184
|
def test_cmd_append_phase_reopens_when_flagged(fake_scribe):
|
|
160
|
-
args = argparse.Namespace(iid=8, title="Follow-up step", body="Extra work found.", reopen=True)
|
|
185
|
+
args = argparse.Namespace(iid=8, title="Follow-up step", body="Extra work found.", reopen=True, if_absent=False)
|
|
161
186
|
gp.cmd_append_phase(args, fake_scribe, "tok", "ns/project")
|
|
162
187
|
assert "Follow-up step" in fake_scribe.issues[8]["description"]
|
|
163
188
|
assert fake_scribe.issues[8]["state"] == "opened"
|
|
164
189
|
|
|
165
190
|
|
|
191
|
+
def test_cmd_append_phase_if_absent_skips_existing_unchecked_phase(fake_scribe, capsys):
|
|
192
|
+
fake_scribe.issues[7]["description"] = gp._append_phase_to_description(
|
|
193
|
+
"Desc.", "Ship it", "Get it live.")
|
|
194
|
+
args = argparse.Namespace(iid=7, title="Ship it", body="Get it live.", reopen=False, if_absent=True)
|
|
195
|
+
gp.cmd_append_phase(args, fake_scribe, "tok", "ns/project")
|
|
196
|
+
out = capsys.readouterr().out
|
|
197
|
+
assert '"skipped": true' in out
|
|
198
|
+
assert not any(c[0] == "gl_put" for c in fake_scribe.calls)
|
|
199
|
+
assert fake_scribe.issues[7]["description"].count("Ship it") == 1
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def test_cmd_append_phase_if_absent_skips_existing_checked_phase(fake_scribe, capsys):
|
|
203
|
+
desc = gp._append_phase_to_description("Desc.", "Ship it", "Get it live.")
|
|
204
|
+
fake_scribe.issues[7]["description"] = gp._mark_phase_done_in_description(desc, "Ship it", "done")
|
|
205
|
+
args = argparse.Namespace(iid=7, title="Ship it", body="Get it live.", reopen=False, if_absent=True)
|
|
206
|
+
gp.cmd_append_phase(args, fake_scribe, "tok", "ns/project")
|
|
207
|
+
out = capsys.readouterr().out
|
|
208
|
+
assert '"skipped": true' in out
|
|
209
|
+
assert not any(c[0] == "gl_put" for c in fake_scribe.calls)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def test_cmd_append_phase_if_absent_appends_when_genuinely_absent(fake_scribe):
|
|
213
|
+
args = argparse.Namespace(iid=7, title="Brand new phase", body="Do it.", reopen=False, if_absent=True)
|
|
214
|
+
gp.cmd_append_phase(args, fake_scribe, "tok", "ns/project")
|
|
215
|
+
assert "Brand new phase" in fake_scribe.issues[7]["description"]
|
|
216
|
+
assert any(c[0] == "gl_put" for c in fake_scribe.calls)
|
|
217
|
+
|
|
218
|
+
|
|
166
219
|
def test_cmd_mark_done_updates_description_and_posts_comment(fake_scribe):
|
|
167
220
|
fake_scribe.issues[7]["description"] = gp._append_phase_to_description(
|
|
168
221
|
"Desc.", "Ship it", "Get it live.")
|
|
@@ -16,7 +16,7 @@ Switch the active AI model for your current session — between Claude (Anthropi
|
|
|
16
16
|
| Alias | Model ID | Provider | Notes |
|
|
17
17
|
|---|---|---|---|
|
|
18
18
|
| `sonnet` | claude-sonnet-5 | Anthropic | Default |
|
|
19
|
-
| `opus` | claude-opus-
|
|
19
|
+
| `opus` | claude-opus-4-8 | Anthropic | Most capable Claude (1M via settings default) |
|
|
20
20
|
| `haiku` | claude-haiku-4-5-20251001 | Anthropic | Fastest/cheapest Claude |
|
|
21
21
|
| `deepseek` | litellm_deepseek | LiteLLM | |
|
|
22
22
|
| `glm` | litellm_glm | LiteLLM | |
|
|
@@ -49,7 +49,18 @@ if (Test-Path $overridePath) {
|
|
|
49
49
|
}
|
|
50
50
|
$shownModel = if ($overrideModel) { $overrideModel } else { $model }
|
|
51
51
|
|
|
52
|
+
# Permission-mode drift warning: permission_mode_guard.py's Stop hook writes
|
|
53
|
+
# the live mode here every turn; only a value other than bypassPermissions is
|
|
54
|
+
# shown. Silent when absent/unreadable -- cosmetic, never load-bearing.
|
|
55
|
+
$modeStateFile = Join-Path $env:USERPROFILE ".claude/.mode_state/$($data.session_id)"
|
|
56
|
+
$driftedMode = $null
|
|
57
|
+
if ($data.session_id -and (Test-Path $modeStateFile)) {
|
|
58
|
+
$m = (Get-Content $modeStateFile -Raw -ErrorAction SilentlyContinue) -replace "`r?`n", ""
|
|
59
|
+
if ($m -and $m -ne "bypassPermissions") { $driftedMode = $m }
|
|
60
|
+
}
|
|
61
|
+
|
|
52
62
|
$parts = @()
|
|
63
|
+
if ($driftedMode) { $parts += "⚠ MODE:$driftedMode" }
|
|
53
64
|
if ($shortCwd) { $parts += $shortCwd }
|
|
54
65
|
if ($branch) { $parts += $branch }
|
|
55
66
|
if ($shownModel) { $parts += $shownModel }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yasaswy.nagavolu/agents",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.17.0",
|
|
4
4
|
"description": "CLI for installing the yasaswy.nagavolu agent/skill/hook bundle. `install` opens an interactive bundle menu in a TTY (or `--bundle <key> --yes` for non-interactive installs), with hash-tracked idempotent deploys, automatic hook wiring into settings.json, and masked secret prompting. `update` reconciles installed bundles against the current source (hash-tracked: silent overwrite, conflict diff+prompt, or --theirs/--keep-mine). `uninstall` removes a bundle's files and wiring. `secrets` re-runs secret prompting for already-installed bundles.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "commonjs",
|