claude-dev-env 8.120.0 → 8.121.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/bin/ever-registered-hooks.mjs +1 -0
- package/hooks/advisory/auto_mode_denial_quick_fix.py +275 -27
- package/hooks/advisory/auto_mode_rule_flow_eval/auto_mode_rule_flow_cases.json +3475 -0
- package/hooks/advisory/auto_mode_rule_flow_eval/auto_mode_rule_flow_runner.py +849 -0
- package/hooks/advisory/auto_mode_rule_flow_eval/stub_allow_hook.py +20 -0
- package/hooks/advisory/auto_mode_rule_flow_eval/stub_hold_hook.py +54 -0
- package/hooks/advisory/auto_mode_rule_flow_eval/test_auto_mode_rule_flow_runner.py +143 -0
- package/hooks/advisory/test_auto_mode_denial_quick_fix.py +533 -9
- package/hooks/auto_mode_question_transcript.py +215 -0
- package/hooks/auto_mode_refusal_ledger.py +481 -0
- package/hooks/auto_mode_refusal_ledger_files.py +336 -0
- package/hooks/auto_mode_rule_steps.py +177 -0
- package/hooks/blocking/auto_mode_refusal_stop_gate.py +384 -0
- package/hooks/blocking/test_auto_mode_refusal_stop_gate.py +484 -0
- package/hooks/features/README.md +1 -1
- package/hooks/features/session-context.md +5 -2
- package/hooks/hooks.json +5 -0
- package/hooks/hooks_constants/auto_mode_denial_quick_fix_constants.py +51 -3
- package/hooks/hooks_constants/auto_mode_refusal_ledger_constants.py +85 -0
- package/hooks/hooks_constants/auto_mode_refusal_stop_gate_constants.py +80 -0
- package/hooks/hooks_constants/auto_mode_rule_flow_runner_constants.py +225 -0
- package/hooks/hooks_constants/auto_mode_rule_steps_constants.py +82 -0
- package/hooks/test_auto_mode_question_transcript.py +113 -0
- package/hooks/test_auto_mode_refusal_ledger.py +398 -0
- package/hooks/test_auto_mode_refusal_ledger_files.py +155 -0
- package/hooks/test_auto_mode_rule_steps.py +210 -0
- package/package.json +1 -1
- package/scripts/policy_lint/adapter_configuration.py +5 -0
- package/scripts/policy_lint/config/constants.py +1 -0
- package/scripts/tests/test_adapter_configuration.py +8 -0
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""Read the answered ``AskUserQuestion`` calls from a session transcript.
|
|
2
|
+
|
|
3
|
+
The refusal ledger matches each answer to a question record by exact text
|
|
4
|
+
and by where the call sits in the transcript::
|
|
5
|
+
|
|
6
|
+
byte 0 {"type": "assistant", ... AskUserQuestion call toolu_1 ...}
|
|
7
|
+
byte 812 {"type": "user", "toolUseResult": {"answers": {"Q?": "Allow it"}}}
|
|
8
|
+
-> AskedQuestions(call_offset=0, answer_by_question={"Q?": "Allow it"})
|
|
9
|
+
|
|
10
|
+
A call whose result is error text has no ``answers`` object and is left out.
|
|
11
|
+
``read_tool_calls`` reads every finished call of any tool, with its input and
|
|
12
|
+
error flag, for the Stop gate's card and rule tool checks. ``read_transcript``
|
|
13
|
+
returns both from one read, so the Stop gate parses the file once.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
from collections.abc import Iterator
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
from hooks_constants.auto_mode_refusal_ledger_constants import ASK_TOOL_NAME
|
|
24
|
+
|
|
25
|
+
JsonObject = dict[str, object]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class AskedQuestions:
|
|
30
|
+
"""One answered ``AskUserQuestion`` call read from the transcript.
|
|
31
|
+
|
|
32
|
+
Attributes:
|
|
33
|
+
call_offset: The byte offset where the call's transcript line starts.
|
|
34
|
+
answer_by_question: Each asked question text mapped to the answer text.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
call_offset: int
|
|
38
|
+
answer_by_question: dict[str, str]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class TranscriptCall:
|
|
43
|
+
"""One finished tool call read from the transcript.
|
|
44
|
+
|
|
45
|
+
Attributes:
|
|
46
|
+
call_offset: The byte offset where the call's transcript line starts.
|
|
47
|
+
tool_name: The tool the call used.
|
|
48
|
+
tool_input: The call's input as the transcript stores it.
|
|
49
|
+
is_error: Whether the call's result is marked as an error.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
call_offset: int
|
|
53
|
+
tool_name: str
|
|
54
|
+
tool_input: object
|
|
55
|
+
is_error: bool
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _records_with_offsets(transcript_bytes: bytes) -> Iterator[tuple[int, JsonObject]]:
|
|
59
|
+
line_start = 0
|
|
60
|
+
for each_line in transcript_bytes.splitlines(keepends=True):
|
|
61
|
+
current_offset = line_start
|
|
62
|
+
line_start += len(each_line)
|
|
63
|
+
try:
|
|
64
|
+
record = json.loads(each_line)
|
|
65
|
+
except ValueError:
|
|
66
|
+
continue
|
|
67
|
+
if isinstance(record, dict):
|
|
68
|
+
yield current_offset, record
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _all_content_blocks(record: JsonObject) -> list[JsonObject]:
|
|
72
|
+
message = record.get("message")
|
|
73
|
+
content = message.get("content") if isinstance(message, dict) else None
|
|
74
|
+
if not isinstance(content, list):
|
|
75
|
+
return []
|
|
76
|
+
return [each_block for each_block in content if isinstance(each_block, dict)]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _ask_call_ids(record: JsonObject) -> list[str]:
|
|
80
|
+
return [
|
|
81
|
+
str(each_block.get("id"))
|
|
82
|
+
for each_block in _all_content_blocks(record)
|
|
83
|
+
if each_block.get("type") == "tool_use" and each_block.get("name") == ASK_TOOL_NAME
|
|
84
|
+
]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _answered_call_ids(record: JsonObject) -> list[str]:
|
|
88
|
+
return [
|
|
89
|
+
str(each_block.get("tool_use_id"))
|
|
90
|
+
for each_block in _all_content_blocks(record)
|
|
91
|
+
if each_block.get("type") == "tool_result"
|
|
92
|
+
]
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _answers_of(record: JsonObject) -> dict[str, str] | None:
|
|
96
|
+
tool_use_result = record.get("toolUseResult")
|
|
97
|
+
all_answers = tool_use_result.get("answers") if isinstance(tool_use_result, dict) else None
|
|
98
|
+
if not isinstance(all_answers, dict):
|
|
99
|
+
return None
|
|
100
|
+
return {
|
|
101
|
+
str(each_question): str(each_answer) for each_question, each_answer in all_answers.items()
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@dataclass(frozen=True)
|
|
106
|
+
class TranscriptReading:
|
|
107
|
+
"""Everything the refusal hooks read from one pass over a transcript.
|
|
108
|
+
|
|
109
|
+
Attributes:
|
|
110
|
+
all_asked: The answered ``AskUserQuestion`` calls.
|
|
111
|
+
all_calls: Every finished tool call.
|
|
112
|
+
"""
|
|
113
|
+
|
|
114
|
+
all_asked: list[AskedQuestions]
|
|
115
|
+
all_calls: list[TranscriptCall]
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _transcript_records(transcript_path: Path | None) -> list[tuple[int, JsonObject]]:
|
|
119
|
+
if transcript_path is None:
|
|
120
|
+
return []
|
|
121
|
+
try:
|
|
122
|
+
transcript_bytes = transcript_path.read_bytes()
|
|
123
|
+
except OSError:
|
|
124
|
+
return []
|
|
125
|
+
return list(_records_with_offsets(transcript_bytes))
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _asked_from(all_records: list[tuple[int, JsonObject]]) -> list[AskedQuestions]:
|
|
129
|
+
call_offset_by_id: dict[str, int] = {}
|
|
130
|
+
all_asked: list[AskedQuestions] = []
|
|
131
|
+
for each_offset, each_record in all_records:
|
|
132
|
+
call_offset_by_id.update(dict.fromkeys(_ask_call_ids(each_record), each_offset))
|
|
133
|
+
answer_by_question = _answers_of(each_record)
|
|
134
|
+
if answer_by_question is None:
|
|
135
|
+
continue
|
|
136
|
+
all_asked.extend(
|
|
137
|
+
AskedQuestions(call_offset_by_id[each_id], answer_by_question)
|
|
138
|
+
for each_id in _answered_call_ids(each_record)
|
|
139
|
+
if each_id in call_offset_by_id
|
|
140
|
+
)
|
|
141
|
+
return all_asked
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _calls_from(all_records: list[tuple[int, JsonObject]]) -> list[TranscriptCall]:
|
|
145
|
+
call_by_id: dict[str, tuple[int, str, object]] = {}
|
|
146
|
+
all_calls: list[TranscriptCall] = []
|
|
147
|
+
for each_offset, each_record in all_records:
|
|
148
|
+
all_blocks = _all_content_blocks(each_record)
|
|
149
|
+
call_by_id.update(
|
|
150
|
+
(str(each.get("id")), (each_offset, str(each.get("name")), each.get("input")))
|
|
151
|
+
for each in all_blocks
|
|
152
|
+
if each.get("type") == "tool_use"
|
|
153
|
+
)
|
|
154
|
+
all_calls.extend(
|
|
155
|
+
TranscriptCall(
|
|
156
|
+
*call_by_id[str(each.get("tool_use_id"))], is_error=each.get("is_error") is True
|
|
157
|
+
)
|
|
158
|
+
for each in all_blocks
|
|
159
|
+
if each.get("type") == "tool_result" and str(each.get("tool_use_id")) in call_by_id
|
|
160
|
+
)
|
|
161
|
+
return all_calls
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def read_transcript(transcript_path: Path | None) -> TranscriptReading:
|
|
165
|
+
"""Read the answered asks and the finished calls in one pass.
|
|
166
|
+
|
|
167
|
+
::
|
|
168
|
+
|
|
169
|
+
transcript with one answered AskUserQuestion call
|
|
170
|
+
-> TranscriptReading(all_asked=[AskedQuestions(0, {...})],
|
|
171
|
+
all_calls=[TranscriptCall(0, "AskUserQuestion", ...)])
|
|
172
|
+
missing file -> TranscriptReading([], [])
|
|
173
|
+
|
|
174
|
+
Args:
|
|
175
|
+
transcript_path: The session transcript JSONL file, or None.
|
|
176
|
+
|
|
177
|
+
Returns:
|
|
178
|
+
What ``read_asked_questions`` and ``read_tool_calls`` return, from
|
|
179
|
+
one read and one parse of the file.
|
|
180
|
+
"""
|
|
181
|
+
all_records = _transcript_records(transcript_path)
|
|
182
|
+
return TranscriptReading(all_asked=_asked_from(all_records), all_calls=_calls_from(all_records))
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def read_asked_questions(transcript_path: Path | None) -> list[AskedQuestions]:
|
|
186
|
+
"""Return every answered ``AskUserQuestion`` call in a transcript.
|
|
187
|
+
|
|
188
|
+
Args:
|
|
189
|
+
transcript_path: The session transcript JSONL file, or None.
|
|
190
|
+
|
|
191
|
+
Returns:
|
|
192
|
+
One item per call whose result holds an ``answers`` object, in the
|
|
193
|
+
order the results appear.
|
|
194
|
+
"""
|
|
195
|
+
return _asked_from(_transcript_records(transcript_path))
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def read_tool_calls(transcript_path: Path | None) -> list[TranscriptCall]:
|
|
199
|
+
"""Return every tool call in a transcript that has a result.
|
|
200
|
+
|
|
201
|
+
::
|
|
202
|
+
|
|
203
|
+
byte 0 {"type": "assistant", ... Bash call toolu_1 {"command": "ls"} ...}
|
|
204
|
+
byte 300 {"type": "user", ... tool_result toolu_1 ...}
|
|
205
|
+
-> TranscriptCall(0, "Bash", {"command": "ls"}, is_error=False)
|
|
206
|
+
a call with no result yet -> left out
|
|
207
|
+
|
|
208
|
+
Args:
|
|
209
|
+
transcript_path: The session transcript JSONL file, or None.
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
One item per call whose result is in the transcript, in the order
|
|
213
|
+
the results appear.
|
|
214
|
+
"""
|
|
215
|
+
return _calls_from(_transcript_records(transcript_path))
|
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
"""The auto mode refusal ledger: refused steps, their questions, their answers.
|
|
2
|
+
|
|
3
|
+
One session's ledger is a folder of JSON files::
|
|
4
|
+
|
|
5
|
+
<config>/state/auto-mode-refusals/<session_id>/
|
|
6
|
+
3f9a0c1d2e4b5a6c.json one refused step, "answer": null
|
|
7
|
+
question-8d7e6f5a4b3c2d1e.json one question text and the ids it covers
|
|
8
|
+
|
|
9
|
+
A step's id comes from its tool name and its ``tool_input`` without the
|
|
10
|
+
``description`` key, so the same refusal twice is one entry, a retry with a
|
|
11
|
+
new description is the same entry, and two edits of one file are two. Pending entries
|
|
12
|
+
group by tool name and exact rule label, and one question covers up to the
|
|
13
|
+
five oldest of a group. An answer counts only when an ``AskUserQuestion``
|
|
14
|
+
call that starts at or after the record's ``transcript_offset`` asks the
|
|
15
|
+
record's exact question text and gets ``Allow it`` or ``Keep refusing``. A
|
|
16
|
+
call that asks the card question for the record's tool counts too, when no
|
|
17
|
+
other record of that tool was written at or before the call.
|
|
18
|
+
``auto_mode_refusal_ledger_files.py`` reads each file into a typed entry or
|
|
19
|
+
record and skips a file that does not parse. A refusal writes its entry and
|
|
20
|
+
the question records under ``ledger_lock``, one writer at a time.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import os
|
|
26
|
+
import time
|
|
27
|
+
from collections.abc import Iterator
|
|
28
|
+
from contextlib import contextmanager
|
|
29
|
+
from dataclasses import dataclass
|
|
30
|
+
from datetime import datetime, timezone
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
|
|
33
|
+
from auto_mode_question_transcript import AskedQuestions, read_asked_questions
|
|
34
|
+
from auto_mode_refusal_ledger_files import (
|
|
35
|
+
JsonObject,
|
|
36
|
+
LedgerEntry,
|
|
37
|
+
QuestionRecord,
|
|
38
|
+
entry_file_path,
|
|
39
|
+
entry_id_for,
|
|
40
|
+
ledger_directory_for,
|
|
41
|
+
load_entries,
|
|
42
|
+
load_question_records,
|
|
43
|
+
parse_entry,
|
|
44
|
+
parse_question_record,
|
|
45
|
+
question_file_path,
|
|
46
|
+
read_json_object,
|
|
47
|
+
write_json_object,
|
|
48
|
+
)
|
|
49
|
+
from auto_mode_rule_steps import RuleFlowSetting, is_rule_flow_step
|
|
50
|
+
from hooks_constants.auto_mode_refusal_ledger_constants import (
|
|
51
|
+
ALL_RULE_ROOT_MARKER_PATHS,
|
|
52
|
+
ALLOWED_ANSWER,
|
|
53
|
+
ANSWER_BY_OPTION_LABEL,
|
|
54
|
+
LEDGER_LOCK_FILE_NAME,
|
|
55
|
+
LEDGER_LOCK_POLL_SECONDS,
|
|
56
|
+
LEDGER_LOCK_WAIT_SECONDS,
|
|
57
|
+
MAXIMUM_STEPS_PER_QUESTION,
|
|
58
|
+
PLAYBOOK_ENVIRONMENT_VARIABLE,
|
|
59
|
+
PLAYBOOK_ROOT_DEPTH,
|
|
60
|
+
QUESTION_RECORD_KIND,
|
|
61
|
+
SEVERAL_STEPS_QUESTION_TEMPLATE,
|
|
62
|
+
SINGLE_STEP_QUESTION_TEMPLATE,
|
|
63
|
+
TIMESTAMP_FORMAT,
|
|
64
|
+
)
|
|
65
|
+
from hooks_constants.auto_mode_refusal_stop_gate_constants import CARD_QUESTION_TEMPLATE
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True)
|
|
69
|
+
class QuestionGroup:
|
|
70
|
+
"""One question the user is asked about a group of pending entries.
|
|
71
|
+
|
|
72
|
+
Attributes:
|
|
73
|
+
question: The exact question text.
|
|
74
|
+
tool_name: The tool every entry in the group used.
|
|
75
|
+
rule_label: The rule label every entry in the group was refused under.
|
|
76
|
+
all_entry_ids: The ids the question covers, oldest first.
|
|
77
|
+
all_action_summaries: One short line per covered step, oldest first.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
question: str
|
|
81
|
+
tool_name: str
|
|
82
|
+
rule_label: str
|
|
83
|
+
all_entry_ids: tuple[str, ...]
|
|
84
|
+
all_action_summaries: tuple[str, ...]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass(frozen=True)
|
|
88
|
+
class RefusedStep:
|
|
89
|
+
"""One refusal as the PermissionDenied hook hands it to the ledger.
|
|
90
|
+
|
|
91
|
+
Attributes:
|
|
92
|
+
session_id: The session id from the hook input.
|
|
93
|
+
transcript_path: The session transcript, or None when unknown.
|
|
94
|
+
tool_name: The refused call's tool name.
|
|
95
|
+
tool_input: The refused call's full ``tool_input``.
|
|
96
|
+
working_folder: The ``cwd`` from the hook input, or None.
|
|
97
|
+
rule_label: The parsed rule label, or None for a reason with none.
|
|
98
|
+
reason: The refusal reason on one display line.
|
|
99
|
+
action_summary: One short line that names the step.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
session_id: str
|
|
103
|
+
transcript_path: Path | None
|
|
104
|
+
tool_name: str
|
|
105
|
+
tool_input: object
|
|
106
|
+
working_folder: str | None
|
|
107
|
+
rule_label: str | None
|
|
108
|
+
reason: str
|
|
109
|
+
action_summary: str
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def playbook_path_from_environment() -> Path | None:
|
|
113
|
+
"""Return the rule playbook path when the flow switch names an existing file.
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
The path ``CLAUDE_AUTO_MODE_RULE_PLAYBOOK`` names, or None when the
|
|
117
|
+
variable is unset or empty or the file does not exist.
|
|
118
|
+
"""
|
|
119
|
+
configured_path = os.environ.get(PLAYBOOK_ENVIRONMENT_VARIABLE, "")
|
|
120
|
+
if not configured_path or not Path(configured_path).is_file():
|
|
121
|
+
return None
|
|
122
|
+
return Path(configured_path)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def rule_repository_root(playbook_path: Path) -> Path | None:
|
|
126
|
+
"""Return the repository that holds the rule playbook.
|
|
127
|
+
|
|
128
|
+
::
|
|
129
|
+
|
|
130
|
+
/work/agent-channels/docs/auto-mode-rule.md -> /work/agent-channels
|
|
131
|
+
(it holds .git and setup/add_auto_mode_rule.py)
|
|
132
|
+
/docs/auto-mode-rule.md -> None, / holds no rule tool
|
|
133
|
+
/auto-mode-rule.md -> None
|
|
134
|
+
|
|
135
|
+
Args:
|
|
136
|
+
playbook_path: The rule playbook the flow switch names.
|
|
137
|
+
|
|
138
|
+
Returns:
|
|
139
|
+
The folder two levels above the resolved playbook when it holds
|
|
140
|
+
``.git`` and ``setup/add_auto_mode_rule.py``, else None.
|
|
141
|
+
"""
|
|
142
|
+
all_parent_folders = playbook_path.resolve().parents
|
|
143
|
+
if len(all_parent_folders) < PLAYBOOK_ROOT_DEPTH:
|
|
144
|
+
return None
|
|
145
|
+
repository_root = all_parent_folders[PLAYBOOK_ROOT_DEPTH - 1]
|
|
146
|
+
if not all((repository_root / each).exists() for each in ALL_RULE_ROOT_MARKER_PATHS):
|
|
147
|
+
return None
|
|
148
|
+
return repository_root
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def question_text_for(tool_name: str, rule_label: str, step_count: int) -> str:
|
|
152
|
+
"""Return the exact question for a group of refused steps.
|
|
153
|
+
|
|
154
|
+
::
|
|
155
|
+
|
|
156
|
+
Bash, Git Destructive, 1 -> "Auto mode refused 1 Bash step under the
|
|
157
|
+
Git Destructive rule. Should auto mode
|
|
158
|
+
have refused it?"
|
|
159
|
+
Bash, Git Destructive, 2 -> "... 2 Bash steps ... refused them?"
|
|
160
|
+
|
|
161
|
+
Args:
|
|
162
|
+
tool_name: The tool the steps used.
|
|
163
|
+
rule_label: The rule label they were refused under.
|
|
164
|
+
step_count: How many steps the question covers.
|
|
165
|
+
|
|
166
|
+
Returns:
|
|
167
|
+
The question text.
|
|
168
|
+
"""
|
|
169
|
+
if step_count == 1:
|
|
170
|
+
return SINGLE_STEP_QUESTION_TEMPLATE.format(tool_name=tool_name, rule_label=rule_label)
|
|
171
|
+
return SEVERAL_STEPS_QUESTION_TEMPLATE.format(
|
|
172
|
+
step_count=step_count, tool_name=tool_name, rule_label=rule_label
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def add_entry(ledger_directory: Path, entry_fields: JsonObject) -> bool:
|
|
177
|
+
"""Write one pending entry unless an entry with its id exists.
|
|
178
|
+
|
|
179
|
+
Args:
|
|
180
|
+
ledger_directory: One session's ledger folder.
|
|
181
|
+
entry_fields: The entry's fields; ``id`` names the file.
|
|
182
|
+
|
|
183
|
+
Returns:
|
|
184
|
+
Whether a new entry file was written.
|
|
185
|
+
"""
|
|
186
|
+
entry_path = entry_file_path(ledger_directory, str(entry_fields["id"]))
|
|
187
|
+
if entry_path.exists():
|
|
188
|
+
return False
|
|
189
|
+
all_sequences = [each.sequence for each in load_entries(ledger_directory)]
|
|
190
|
+
write_json_object(
|
|
191
|
+
entry_path,
|
|
192
|
+
{
|
|
193
|
+
**entry_fields,
|
|
194
|
+
"sequence": max(all_sequences, default=0) + 1,
|
|
195
|
+
"refused_at": datetime.now(timezone.utc).strftime(TIMESTAMP_FORMAT),
|
|
196
|
+
"answer": None,
|
|
197
|
+
},
|
|
198
|
+
)
|
|
199
|
+
return True
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def question_groups(all_entries: list[LedgerEntry]) -> list[QuestionGroup]:
|
|
203
|
+
"""Return the questions the pending entries need, in order of first refusal.
|
|
204
|
+
|
|
205
|
+
::
|
|
206
|
+
|
|
207
|
+
pending Bash/Git Destructive x2, WebFetch/Data Exfiltration x1
|
|
208
|
+
-> "2 Bash steps ... Git Destructive", "1 WebFetch step ... Data Exfiltration"
|
|
209
|
+
pending Bash/Git Destructive x7 -> one question for the five oldest
|
|
210
|
+
|
|
211
|
+
Args:
|
|
212
|
+
all_entries: The ledger entries, oldest first.
|
|
213
|
+
|
|
214
|
+
Returns:
|
|
215
|
+
One group per tool name and exact rule label that has a pending entry.
|
|
216
|
+
"""
|
|
217
|
+
pending_by_group: dict[tuple[str, str], list[LedgerEntry]] = {}
|
|
218
|
+
for each_entry in all_entries:
|
|
219
|
+
if each_entry.answer is None:
|
|
220
|
+
group_key = (each_entry.tool_name, each_entry.rule_label)
|
|
221
|
+
pending_by_group.setdefault(group_key, []).append(each_entry)
|
|
222
|
+
return [
|
|
223
|
+
QuestionGroup(
|
|
224
|
+
question=question_text_for(each_tool_name, each_rule_label, len(each_covered)),
|
|
225
|
+
tool_name=each_tool_name,
|
|
226
|
+
rule_label=each_rule_label,
|
|
227
|
+
all_entry_ids=tuple(each.entry_id for each in each_covered),
|
|
228
|
+
all_action_summaries=tuple(each.action_summary for each in each_covered),
|
|
229
|
+
)
|
|
230
|
+
for (each_tool_name, each_rule_label), each_group_entries in pending_by_group.items()
|
|
231
|
+
if (each_covered := each_group_entries[:MAXIMUM_STEPS_PER_QUESTION])
|
|
232
|
+
]
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _transcript_size(transcript_path: Path | None) -> int:
|
|
236
|
+
if transcript_path is None:
|
|
237
|
+
return 0
|
|
238
|
+
try:
|
|
239
|
+
return transcript_path.stat().st_size
|
|
240
|
+
except OSError:
|
|
241
|
+
return 0
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def write_question_records(
|
|
245
|
+
ledger_directory: Path, all_groups: list[QuestionGroup], transcript_path: Path | None
|
|
246
|
+
) -> None:
|
|
247
|
+
"""Write one question record per group, the one writer both hooks use.
|
|
248
|
+
|
|
249
|
+
::
|
|
250
|
+
|
|
251
|
+
question-<digest>.json
|
|
252
|
+
{"record": "question", "question": "<exact text>",
|
|
253
|
+
"entry_ids": ["3f9a..."], "tool_name": "Bash",
|
|
254
|
+
"rule_label": "Git Destructive", "transcript_offset": 18233,
|
|
255
|
+
"written_at": "2026-11-15T14:02:11.120000Z"}
|
|
256
|
+
|
|
257
|
+
A record whose text already covers the same ids stays as it is, so its
|
|
258
|
+
``transcript_offset`` keeps the transcript size from its first write. A
|
|
259
|
+
record whose ids changed, or that does not parse, is rewritten with the
|
|
260
|
+
current size. Asks that start before the offset never answer it.
|
|
261
|
+
|
|
262
|
+
Args:
|
|
263
|
+
ledger_directory: One session's ledger folder.
|
|
264
|
+
all_groups: The groups from ``question_groups``.
|
|
265
|
+
transcript_path: The session transcript, or None when unknown.
|
|
266
|
+
"""
|
|
267
|
+
for each_group in all_groups:
|
|
268
|
+
question_path = question_file_path(ledger_directory, each_group.question)
|
|
269
|
+
existing_record = parse_question_record(read_json_object(question_path))
|
|
270
|
+
if existing_record and existing_record.all_entry_ids == each_group.all_entry_ids:
|
|
271
|
+
continue
|
|
272
|
+
write_json_object(
|
|
273
|
+
question_path,
|
|
274
|
+
{
|
|
275
|
+
"record": QUESTION_RECORD_KIND,
|
|
276
|
+
"question": each_group.question,
|
|
277
|
+
"tool_name": each_group.tool_name,
|
|
278
|
+
"rule_label": each_group.rule_label,
|
|
279
|
+
"entry_ids": list(each_group.all_entry_ids),
|
|
280
|
+
"transcript_offset": _transcript_size(transcript_path),
|
|
281
|
+
"written_at": datetime.now(timezone.utc).strftime(TIMESTAMP_FORMAT),
|
|
282
|
+
},
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _is_sole_card_owner(
|
|
287
|
+
record: QuestionRecord, all_records: list[QuestionRecord], call_offset: int
|
|
288
|
+
) -> bool:
|
|
289
|
+
all_candidate_records = [
|
|
290
|
+
each
|
|
291
|
+
for each in all_records
|
|
292
|
+
if each.tool_name == record.tool_name and each.transcript_offset <= call_offset
|
|
293
|
+
]
|
|
294
|
+
return bool(record.tool_name) and all_candidate_records == [record]
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _answer_for(
|
|
298
|
+
record: QuestionRecord, all_records: list[QuestionRecord], all_asked: list[AskedQuestions]
|
|
299
|
+
) -> str | None:
|
|
300
|
+
card_question = CARD_QUESTION_TEMPLATE.format(tool_name=record.tool_name)
|
|
301
|
+
for each_asked in all_asked:
|
|
302
|
+
if each_asked.call_offset < record.transcript_offset:
|
|
303
|
+
continue
|
|
304
|
+
answer_label = each_asked.answer_by_question.get(record.question)
|
|
305
|
+
if answer_label is None and _is_sole_card_owner(
|
|
306
|
+
record, all_records, each_asked.call_offset
|
|
307
|
+
):
|
|
308
|
+
answer_label = each_asked.answer_by_question.get(card_question)
|
|
309
|
+
answer = ANSWER_BY_OPTION_LABEL.get(answer_label or "")
|
|
310
|
+
if answer is not None:
|
|
311
|
+
return answer
|
|
312
|
+
return None
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def apply_transcript_answers(ledger_directory: Path, transcript_path: Path | None) -> None:
|
|
316
|
+
"""Set the answer of each pending entry whose question the user answered.
|
|
317
|
+
|
|
318
|
+
::
|
|
319
|
+
|
|
320
|
+
record "Auto mode refused 1 Bash step ...", ids [a], offset 900
|
|
321
|
+
ask at offset 1200 with that exact text, answer "Allow it" -> a: "allowed"
|
|
322
|
+
ask at offset 400 with that exact text -> ignored
|
|
323
|
+
ask with other text, or answer "allow it" -> ignored
|
|
324
|
+
ask "Should auto mode have refused this Bash step?" at 1200,
|
|
325
|
+
and this is the only Bash record at or before 1200 -> a: "allowed"
|
|
326
|
+
the same ask with a second Bash record at or before it -> ignored
|
|
327
|
+
|
|
328
|
+
Only ids a record names change, and only while their answer is null.
|
|
329
|
+
|
|
330
|
+
Args:
|
|
331
|
+
ledger_directory: One session's ledger folder.
|
|
332
|
+
transcript_path: The session transcript, or None.
|
|
333
|
+
"""
|
|
334
|
+
if not load_question_records(ledger_directory):
|
|
335
|
+
return
|
|
336
|
+
apply_asked_answers(ledger_directory, read_asked_questions(transcript_path))
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def apply_asked_answers(ledger_directory: Path, all_asked: list[AskedQuestions]) -> None:
|
|
340
|
+
"""Set pending answers from asks the caller already read.
|
|
341
|
+
|
|
342
|
+
::
|
|
343
|
+
|
|
344
|
+
record ids [a], ask with its text answered "Keep refusing" -> a: "kept"
|
|
345
|
+
|
|
346
|
+
Args:
|
|
347
|
+
ledger_directory: One session's ledger folder.
|
|
348
|
+
all_asked: The answered asks from ``read_asked_questions`` or
|
|
349
|
+
``read_transcript``.
|
|
350
|
+
"""
|
|
351
|
+
all_records = load_question_records(ledger_directory)
|
|
352
|
+
for each_record in all_records:
|
|
353
|
+
answer = _answer_for(each_record, all_records, all_asked)
|
|
354
|
+
if answer is not None:
|
|
355
|
+
_set_pending_answers(ledger_directory, each_record.all_entry_ids, answer)
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _set_pending_answers(
|
|
359
|
+
ledger_directory: Path, all_entry_ids: tuple[str, ...], answer: str
|
|
360
|
+
) -> None:
|
|
361
|
+
for each_entry_id in all_entry_ids:
|
|
362
|
+
entry_path = entry_file_path(ledger_directory, each_entry_id)
|
|
363
|
+
raw_entry = read_json_object(entry_path)
|
|
364
|
+
parsed_entry = parse_entry(raw_entry)
|
|
365
|
+
if raw_entry is not None and parsed_entry is not None and parsed_entry.answer is None:
|
|
366
|
+
write_json_object(entry_path, {**raw_entry, "answer": answer})
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def merge_entry_fields(
|
|
370
|
+
ledger_directory: Path, fields_by_entry_id: dict[str, JsonObject]
|
|
371
|
+
) -> None:
|
|
372
|
+
"""Merge new fields into existing entry files and keep every other field.
|
|
373
|
+
|
|
374
|
+
::
|
|
375
|
+
|
|
376
|
+
{"3f9a...": {"question_holds": 1}} -> 3f9a....json gains question_holds 1
|
|
377
|
+
an id with no file, or a file that does not parse -> nothing written
|
|
378
|
+
|
|
379
|
+
Args:
|
|
380
|
+
ledger_directory: One session's ledger folder.
|
|
381
|
+
fields_by_entry_id: The fields to set, by entry id.
|
|
382
|
+
"""
|
|
383
|
+
for each_entry_id, each_fields in fields_by_entry_id.items():
|
|
384
|
+
entry_path = entry_file_path(ledger_directory, each_entry_id)
|
|
385
|
+
raw_entry = read_json_object(entry_path)
|
|
386
|
+
if raw_entry is not None and parse_entry(raw_entry) is not None:
|
|
387
|
+
write_json_object(entry_path, {**raw_entry, **each_fields})
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _entry_fields_for(step: RefusedStep, rule_label: str) -> JsonObject:
|
|
391
|
+
return {
|
|
392
|
+
"id": entry_id_for(step.tool_name, step.tool_input),
|
|
393
|
+
"session_id": step.session_id,
|
|
394
|
+
"tool_name": step.tool_name,
|
|
395
|
+
"tool_input": step.tool_input,
|
|
396
|
+
"rule_label": rule_label,
|
|
397
|
+
"reason": step.reason,
|
|
398
|
+
"action_summary": step.action_summary,
|
|
399
|
+
"cwd": step.working_folder,
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
@contextmanager
|
|
404
|
+
def ledger_lock(ledger_directory: Path) -> Iterator[None]:
|
|
405
|
+
"""Hold one session's ledger for a single writer.
|
|
406
|
+
|
|
407
|
+
::
|
|
408
|
+
|
|
409
|
+
two refusals from one message, two hook processes
|
|
410
|
+
-> the second waits, so each entry gets its own sequence and
|
|
411
|
+
the question record lists both ids
|
|
412
|
+
a lock file left by a killed process
|
|
413
|
+
-> the wait ends after LEDGER_LOCK_WAIT_SECONDS, the stale file is
|
|
414
|
+
removed, and the write goes on
|
|
415
|
+
|
|
416
|
+
Args:
|
|
417
|
+
ledger_directory: One session's ledger folder; it is created when missing.
|
|
418
|
+
"""
|
|
419
|
+
ledger_directory.mkdir(parents=True, exist_ok=True)
|
|
420
|
+
lock_path = ledger_directory / LEDGER_LOCK_FILE_NAME
|
|
421
|
+
wait_deadline = time.monotonic() + LEDGER_LOCK_WAIT_SECONDS
|
|
422
|
+
is_lock_held = False
|
|
423
|
+
while not is_lock_held and time.monotonic() < wait_deadline:
|
|
424
|
+
try:
|
|
425
|
+
os.close(os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY))
|
|
426
|
+
is_lock_held = True
|
|
427
|
+
except FileExistsError:
|
|
428
|
+
time.sleep(LEDGER_LOCK_POLL_SECONDS)
|
|
429
|
+
if not is_lock_held:
|
|
430
|
+
lock_path.unlink(missing_ok=True)
|
|
431
|
+
try:
|
|
432
|
+
yield
|
|
433
|
+
finally:
|
|
434
|
+
if is_lock_held:
|
|
435
|
+
lock_path.unlink(missing_ok=True)
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def record_refusal(step: RefusedStep, repository_root: Path) -> str | None:
|
|
439
|
+
"""Keep the refusal ledger for one denial and return the question to ask.
|
|
440
|
+
|
|
441
|
+
::
|
|
442
|
+
|
|
443
|
+
"[Git Destructive] force push", new step -> entry written,
|
|
444
|
+
"Auto mode refused 1 Bash step under the Git Destructive rule. ..."
|
|
445
|
+
same step again -> no new entry, same question
|
|
446
|
+
prose reason, or a rule flow step -> None
|
|
447
|
+
|
|
448
|
+
The user's answers are read from the transcript before the skip rule, so
|
|
449
|
+
an entry answered in this turn already reads ``allowed``.
|
|
450
|
+
|
|
451
|
+
Args:
|
|
452
|
+
step: The refusal, parsed by the PermissionDenied hook.
|
|
453
|
+
repository_root: The repository that holds the rule playbook.
|
|
454
|
+
|
|
455
|
+
Returns:
|
|
456
|
+
The exact question for the group that holds this step while the
|
|
457
|
+
step is pending, else None.
|
|
458
|
+
"""
|
|
459
|
+
ledger_directory = ledger_directory_for(step.session_id)
|
|
460
|
+
apply_transcript_answers(ledger_directory, step.transcript_path)
|
|
461
|
+
if step.rule_label is None:
|
|
462
|
+
return None
|
|
463
|
+
has_allowed_entry = any(
|
|
464
|
+
each.answer == ALLOWED_ANSWER for each in load_entries(ledger_directory)
|
|
465
|
+
)
|
|
466
|
+
setting = RuleFlowSetting(repository_root, has_allowed_entry)
|
|
467
|
+
if is_rule_flow_step(step.tool_name, step.tool_input, step.working_folder, setting):
|
|
468
|
+
return None
|
|
469
|
+
entry_fields = _entry_fields_for(step, step.rule_label)
|
|
470
|
+
with ledger_lock(ledger_directory):
|
|
471
|
+
add_entry(ledger_directory, entry_fields)
|
|
472
|
+
all_groups = question_groups(load_entries(ledger_directory))
|
|
473
|
+
write_question_records(ledger_directory, all_groups, step.transcript_path)
|
|
474
|
+
return next(
|
|
475
|
+
(
|
|
476
|
+
each_group.question
|
|
477
|
+
for each_group in all_groups
|
|
478
|
+
if entry_fields["id"] in each_group.all_entry_ids
|
|
479
|
+
),
|
|
480
|
+
None,
|
|
481
|
+
)
|