portable-skill-learning 0.1.1__py3-none-any.whl
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.
- portable_skill_learning/__init__.py +1 -0
- portable_skill_learning/adapters/__init__.py +1 -0
- portable_skill_learning/adapters/antigravity.py +243 -0
- portable_skill_learning/adapters/claude.py +219 -0
- portable_skill_learning/adapters/codex.py +280 -0
- portable_skill_learning/assessment.py +85 -0
- portable_skill_learning/cli.py +250 -0
- portable_skill_learning/install.py +331 -0
- portable_skill_learning/probe.py +117 -0
- portable_skill_learning/replay.py +470 -0
- portable_skill_learning/schedule.py +72 -0
- portable_skill_learning/store.py +369 -0
- portable_skill_learning/trials.py +294 -0
- portable_skill_learning/worker.py +144 -0
- portable_skill_learning-0.1.1.dist-info/METADATA +429 -0
- portable_skill_learning-0.1.1.dist-info/RECORD +20 -0
- portable_skill_learning-0.1.1.dist-info/WHEEL +5 -0
- portable_skill_learning-0.1.1.dist-info/entry_points.txt +2 -0
- portable_skill_learning-0.1.1.dist-info/licenses/LICENSE +21 -0
- portable_skill_learning-0.1.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Project-scoped procedural learning."""
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Tool-specific producers of shared observations and completion evidence."""
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""Experimental observation of Antigravity inputs and selected transcripts."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from shlex import join
|
|
9
|
+
from subprocess import list2cmdline
|
|
10
|
+
|
|
11
|
+
from ..store import Event, atomic_write, digest
|
|
12
|
+
from ..trials import TrialBook
|
|
13
|
+
from .codex import A2A, MAX_LINE, MAX_PROMPT
|
|
14
|
+
|
|
15
|
+
HOOK_GROUP = "portable-skill-learning-probe"
|
|
16
|
+
SURFACES = ("standalone", "standalone-app")
|
|
17
|
+
ACP_SURFACE = "traycer-acp"
|
|
18
|
+
IMPORT_SURFACES = (*SURFACES, ACP_SURFACE)
|
|
19
|
+
TRANSCRIPT = (".system_generated", "logs", "transcript_full.jsonl")
|
|
20
|
+
CONVERSATION = re.compile(r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\Z")
|
|
21
|
+
REQUEST = re.compile(r"\A<USER_REQUEST>\n(.*?)\n</USER_REQUEST>(?:\n|\Z)", re.DOTALL)
|
|
22
|
+
FILE_HEADER = re.compile(r"Showing lines 1-([1-9][0-9]{0,3}) of \1")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _scope(store, project, profile, transcript, *, surfaces=SURFACES):
|
|
26
|
+
path = Path(transcript).resolve()
|
|
27
|
+
if path.parts[-3:] != TRANSCRIPT or len(path.parents) < 4:
|
|
28
|
+
raise ValueError("Expected an Antigravity conversation transcript")
|
|
29
|
+
conversation = path.parents[2].name
|
|
30
|
+
if not CONVERSATION.fullmatch(conversation):
|
|
31
|
+
raise ValueError("Expected an Antigravity conversation transcript")
|
|
32
|
+
bindings = [row for row in store.bindings(project)
|
|
33
|
+
if row["tool"] == "antigravity" and row["surface"] in surfaces
|
|
34
|
+
and (profile is None or row["profile"] == profile)
|
|
35
|
+
and path.parents[3] == Path(row["sessions"]).resolve()]
|
|
36
|
+
if len(bindings) != 1:
|
|
37
|
+
raise ValueError("Transcript does not identify one bound Antigravity profile")
|
|
38
|
+
return path, conversation, bindings[0]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _steps(path):
|
|
42
|
+
previous = -1
|
|
43
|
+
with path.open("rb") as source:
|
|
44
|
+
while line := source.readline(MAX_LINE + 1):
|
|
45
|
+
if len(line) > MAX_LINE:
|
|
46
|
+
raise ValueError("Oversized Antigravity transcript step")
|
|
47
|
+
if not line.endswith(b"\n"):
|
|
48
|
+
break
|
|
49
|
+
row = json.loads(line)
|
|
50
|
+
index = row.get("step_index") if isinstance(row, dict) else None
|
|
51
|
+
if type(index) is not int or index <= previous:
|
|
52
|
+
raise ValueError("Antigravity step indexes must be distinct and ordered")
|
|
53
|
+
previous = index
|
|
54
|
+
yield row
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _input(row):
|
|
58
|
+
if (row.get("type"), row.get("source"), row.get("status")) != ("USER_INPUT", "USER_EXPLICIT", "DONE"):
|
|
59
|
+
return None
|
|
60
|
+
body = row.get("content")
|
|
61
|
+
match = REQUEST.match(body) if isinstance(body, str) else None
|
|
62
|
+
text = match[1] if match else None
|
|
63
|
+
if text and len(text) <= MAX_PROMPT and not A2A.search(text):
|
|
64
|
+
return text
|
|
65
|
+
return None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _event(cwd, binding, conversation, path, row, text):
|
|
69
|
+
return Event(str(cwd), "antigravity", binding["surface"], binding["profile"], conversation,
|
|
70
|
+
f"step-{row['step_index']}", "input", transcript=str(path),
|
|
71
|
+
prompt_hash=digest(text.encode()))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def capture(store, payload):
|
|
75
|
+
"""Observe a validated input and offer an explicitly activated trial."""
|
|
76
|
+
event_name = payload.get("hookEventName")
|
|
77
|
+
if event_name != "PreInvocation":
|
|
78
|
+
return
|
|
79
|
+
cwd = payload.get("cwd")
|
|
80
|
+
paths = payload.get("workspacePaths")
|
|
81
|
+
initial = payload.get("initialNumSteps")
|
|
82
|
+
if (not isinstance(cwd, str) or not Path(cwd).is_absolute()
|
|
83
|
+
or not isinstance(paths, list) or not paths or type(initial) is not int or initial < 1):
|
|
84
|
+
return
|
|
85
|
+
project = store.route(cwd)
|
|
86
|
+
root = store.root_for(project, cwd)
|
|
87
|
+
if root is None or any(not isinstance(path, str) or store.root_for(project, path) != root for path in paths):
|
|
88
|
+
return
|
|
89
|
+
path, conversation, binding = _scope(store, project, None, payload.get("transcriptPath"))
|
|
90
|
+
if conversation != payload.get("conversationId"):
|
|
91
|
+
return
|
|
92
|
+
row = None
|
|
93
|
+
for step in _steps(path):
|
|
94
|
+
if step["step_index"] == initial - 1:
|
|
95
|
+
row = step
|
|
96
|
+
break
|
|
97
|
+
if step["step_index"] >= initial:
|
|
98
|
+
break
|
|
99
|
+
text = _input(row) if row else None
|
|
100
|
+
if not text or text != payload.get("lastUserInput"):
|
|
101
|
+
return
|
|
102
|
+
event = _event(cwd, binding, conversation, path, row, text)
|
|
103
|
+
if store.ingest(event, same_project=project) == "stored":
|
|
104
|
+
store.set_capability(project, "antigravity", event.surface, event.profile, "collect", "insufficient",
|
|
105
|
+
f"{event.turn}: input verified; completion correlation unavailable",
|
|
106
|
+
preserve_passed=True)
|
|
107
|
+
if text.startswith("SKILL CORRECTION "):
|
|
108
|
+
return
|
|
109
|
+
work = {"project": project, "tool": event.tool, "profile": event.profile,
|
|
110
|
+
"session": event.session, "turn": event.turn}
|
|
111
|
+
pins = TrialBook(store).pin(work, text, once_per_session=True)
|
|
112
|
+
if pins:
|
|
113
|
+
paths = "\n".join(f'{pin["skill"]}: {pin["path"]}' for pin in pins)
|
|
114
|
+
message = ("For this user request only, if the procedure matches, read these exact local files "
|
|
115
|
+
"with the native file-reading tool before applying them. The current user request takes "
|
|
116
|
+
"precedence. Do not reuse this notice to select versions for a later request.\n" + paths)
|
|
117
|
+
return {"injectSteps": [{"systemMessage": {"systemMessage": message}}]}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _file_lines(content):
|
|
121
|
+
if not isinstance(content, str):
|
|
122
|
+
return None
|
|
123
|
+
lines = content.splitlines()
|
|
124
|
+
for index, line in enumerate(lines):
|
|
125
|
+
if line.startswith(("Created At: ", "Completed At: ")):
|
|
126
|
+
continue
|
|
127
|
+
header = FILE_HEADER.fullmatch(line)
|
|
128
|
+
if header:
|
|
129
|
+
body = lines[index + 1:]
|
|
130
|
+
prefixes = [f"{number}: " for number in range(1, len(body) + 1)]
|
|
131
|
+
if len(body) == int(header[1]) and all(row.startswith(prefix) for prefix, row in zip(prefixes, body)):
|
|
132
|
+
return [row[len(prefix):] for prefix, row in zip(prefixes, body)]
|
|
133
|
+
break
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def reconcile_reads(store, book, work):
|
|
138
|
+
"""Match a real planner read call and its native result within the pinned input."""
|
|
139
|
+
if not book.has_pin(work):
|
|
140
|
+
return 0
|
|
141
|
+
events = store.observed_turn(work)
|
|
142
|
+
paths = {event.transcript for event in events if event.kind == "input" and event.transcript}
|
|
143
|
+
hashes = {event.prompt_hash for event in events if event.kind == "input" and event.prompt_hash}
|
|
144
|
+
if len(paths) != 1 or len(hashes) != 1:
|
|
145
|
+
return 0
|
|
146
|
+
try:
|
|
147
|
+
path, session, binding = _scope(store, work["project"], work["profile"], paths.pop())
|
|
148
|
+
if session != work["session"] or binding["surface"] != work["surface"]:
|
|
149
|
+
return 0
|
|
150
|
+
turn_index = int(work["turn"].removeprefix("step-"))
|
|
151
|
+
rows = []
|
|
152
|
+
for row in _steps(path):
|
|
153
|
+
index = row["step_index"]
|
|
154
|
+
if index < turn_index:
|
|
155
|
+
continue
|
|
156
|
+
if index > turn_index and row.get("type") == "USER_INPUT":
|
|
157
|
+
break
|
|
158
|
+
rows.append(row)
|
|
159
|
+
if not rows or rows[0]["step_index"] != turn_index:
|
|
160
|
+
return 0
|
|
161
|
+
text = _input(rows[0])
|
|
162
|
+
if not text or digest(text.encode()) not in hashes:
|
|
163
|
+
return 0
|
|
164
|
+
count = 0
|
|
165
|
+
for plan, result in zip(rows, rows[1:]):
|
|
166
|
+
calls = plan.get("tool_calls")
|
|
167
|
+
if ((plan.get("type"), plan.get("source"), plan.get("status")) != ("PLANNER_RESPONSE", "MODEL", "DONE")
|
|
168
|
+
or not isinstance(calls, list) or len(calls) != 1 or not isinstance(calls[0], dict)
|
|
169
|
+
or calls[0].get("name") != "read_file" or not isinstance(calls[0].get("args"), dict)
|
|
170
|
+
or (result.get("type"), result.get("source"), result.get("status")) != ("GENERIC", "MODEL", "DONE")
|
|
171
|
+
or result["step_index"] != plan["step_index"] + 1):
|
|
172
|
+
continue
|
|
173
|
+
lines = _file_lines(result.get("content"))
|
|
174
|
+
if lines is not None:
|
|
175
|
+
count += book.note_file_read(work, calls[0]["args"].get("Path"), lines,
|
|
176
|
+
f"step-{result['step_index']}")
|
|
177
|
+
return count
|
|
178
|
+
except (OSError, TypeError, ValueError):
|
|
179
|
+
return 0
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def import_transcript(store, project, root, profile, transcript):
|
|
183
|
+
"""Import step keys and hashes from the one source selected by the operator."""
|
|
184
|
+
root = Path(root).resolve(strict=True)
|
|
185
|
+
if store.root_for(project, root) != root:
|
|
186
|
+
raise ValueError("Choose a registered project root")
|
|
187
|
+
path, conversation, binding = _scope(store, project, profile, transcript, surfaces=IMPORT_SURFACES)
|
|
188
|
+
events = []
|
|
189
|
+
for row in _steps(path):
|
|
190
|
+
text = _input(row)
|
|
191
|
+
if text:
|
|
192
|
+
events.append(_event(root, binding, conversation, path, row, text))
|
|
193
|
+
results = {event.turn: store.ingest(event, same_project=project) for event in events}
|
|
194
|
+
if any(result in ("stored", "spooled") for result in results.values()):
|
|
195
|
+
store.set_capability(project, "antigravity", binding["surface"], binding["profile"], "collect", "insufficient",
|
|
196
|
+
f"{conversation}: imported inputs; completion correlation unavailable",
|
|
197
|
+
preserve_passed=True)
|
|
198
|
+
return {"conversation": conversation, "input_steps": results, "state": "observed"}
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def hook_path(root):
|
|
202
|
+
root = Path(root).resolve()
|
|
203
|
+
path = root / ".agents" / "hooks.json"
|
|
204
|
+
if path.parent.resolve() != path.parent or path.is_symlink():
|
|
205
|
+
raise ValueError("Antigravity hook file must be within the project")
|
|
206
|
+
return path
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def generated_hooks(store):
|
|
210
|
+
args = [sys.executable, "-m", "portable_skill_learning.cli", "--state", str(store.directory),
|
|
211
|
+
"hook", "--tool", "antigravity"]
|
|
212
|
+
command = list2cmdline(args) if os.name == "nt" else join(args)
|
|
213
|
+
return {HOOK_GROUP: {"PreInvocation": [{"type": "command", "command": command, "timeout": 5}]}}
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _settings(root, store):
|
|
217
|
+
root = Path(root).resolve()
|
|
218
|
+
if store.root_for(store.route(root), root) != root:
|
|
219
|
+
raise ValueError("Install Antigravity hooks at a registered project root")
|
|
220
|
+
return hook_path(root), generated_hooks(store)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def install_hooks(store, root):
|
|
224
|
+
bindings = [row for row in store.bindings(store.route(root)) if row["tool"] == "antigravity"]
|
|
225
|
+
if bindings and all(row["surface"] == ACP_SURFACE for row in bindings):
|
|
226
|
+
raise ValueError("Traycer ACP supports selected transcript import only")
|
|
227
|
+
path, settings = _settings(root, store)
|
|
228
|
+
if path.exists():
|
|
229
|
+
if json.loads(path.read_bytes()) != settings:
|
|
230
|
+
raise ValueError("Review existing Antigravity hook settings before installation")
|
|
231
|
+
else:
|
|
232
|
+
atomic_write(path, json.dumps(settings, indent=2).encode() + b"\n")
|
|
233
|
+
return path
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def uninstall_hooks(store, root):
|
|
237
|
+
path, settings = _settings(root, store)
|
|
238
|
+
if not path.exists():
|
|
239
|
+
return False
|
|
240
|
+
if json.loads(path.read_bytes()) != settings:
|
|
241
|
+
raise ValueError("The Antigravity hook settings changed outside this package")
|
|
242
|
+
path.unlink()
|
|
243
|
+
return True
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""Claude Code hook intake and verification against the native project transcript."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from shlex import quote
|
|
9
|
+
|
|
10
|
+
from ..store import Event, atomic_write, configured_path, digest, identifier, normalized
|
|
11
|
+
from .codex import A2A, EVALUATION, MAX_LINE, MAX_PROMPT, NativeTurn
|
|
12
|
+
|
|
13
|
+
EVENTS = {"UserPromptSubmit": "input", "Stop": "stop",
|
|
14
|
+
"SubagentStop": "child", "StopFailure": "child", "PostToolUse": "tool"}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def from_hook(payload, surface, profile, env):
|
|
18
|
+
if env.get(EVALUATION) or payload.get("permission_mode") == "plan":
|
|
19
|
+
return None
|
|
20
|
+
kind = EVENTS.get(payload.get("hook_event_name"))
|
|
21
|
+
if kind is None or not identifier(payload.get("prompt_id")):
|
|
22
|
+
return None
|
|
23
|
+
child = payload.get("agent_id") or ""
|
|
24
|
+
if child:
|
|
25
|
+
kind = "child"
|
|
26
|
+
prompt = payload.get("prompt")
|
|
27
|
+
response = payload.get("last_assistant_message")
|
|
28
|
+
return Event(
|
|
29
|
+
cwd=payload.get("cwd"), tool="claude", surface=surface, profile=profile,
|
|
30
|
+
session=payload.get("session_id"), turn=payload.get("prompt_id"), kind=kind,
|
|
31
|
+
active=payload.get("stop_hook_active") is True, transcript=payload.get("transcript_path") or "",
|
|
32
|
+
prompt_hash=digest(prompt.encode()) if kind == "input" and isinstance(prompt, str)
|
|
33
|
+
and len(prompt) <= MAX_PROMPT else "",
|
|
34
|
+
child_id=child, detail_hash=digest(response.strip().encode()) if kind == "stop"
|
|
35
|
+
and isinstance(response, str) and response.strip() else "",
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def locate_binding(store, payload, env=os.environ):
|
|
40
|
+
cwd = payload.get("cwd")
|
|
41
|
+
if not isinstance(cwd, str) or not Path(cwd).is_absolute():
|
|
42
|
+
return None
|
|
43
|
+
project = store.route(cwd)
|
|
44
|
+
if project is None:
|
|
45
|
+
return None
|
|
46
|
+
default = Path.home() / ".claude"
|
|
47
|
+
home = Path(env.get("CLAUDE_CONFIG_DIR") or default)
|
|
48
|
+
surface = "standalone"
|
|
49
|
+
if env.get("TRAYCER_AGENT_ID"):
|
|
50
|
+
surface = "traycer-ambient" if configured_path(home) == configured_path(default) else "traycer-managed"
|
|
51
|
+
matches = [row for row in store.bindings(project)
|
|
52
|
+
if row["tool"] == "claude" and row["surface"] == surface
|
|
53
|
+
and row["sessions"] == configured_path(home / "projects")]
|
|
54
|
+
return matches[0] if len(matches) == 1 else None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _rows(path):
|
|
58
|
+
with path.open("rb") as source:
|
|
59
|
+
while line := source.readline(MAX_LINE + 1):
|
|
60
|
+
if len(line) > MAX_LINE:
|
|
61
|
+
raise ValueError("Oversized native Claude record")
|
|
62
|
+
if not line.endswith(b"\n"):
|
|
63
|
+
break
|
|
64
|
+
row = json.loads(line)
|
|
65
|
+
if isinstance(row, dict):
|
|
66
|
+
yield row
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _plain(content):
|
|
70
|
+
if isinstance(content, str):
|
|
71
|
+
return content
|
|
72
|
+
if isinstance(content, list) and content and all(
|
|
73
|
+
isinstance(item, dict) and item.get("type") == "text" and isinstance(item.get("text"), str)
|
|
74
|
+
for item in content):
|
|
75
|
+
return "\n".join(item["text"] for item in content)
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _clock(row):
|
|
80
|
+
try:
|
|
81
|
+
time = datetime.fromisoformat(row["timestamp"])
|
|
82
|
+
return int(time.timestamp()) if time.tzinfo else None
|
|
83
|
+
except (TypeError, ValueError, KeyError):
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _native_reads(rows):
|
|
88
|
+
commands = {}
|
|
89
|
+
files = {}
|
|
90
|
+
for row in rows:
|
|
91
|
+
message = row.get("message", {})
|
|
92
|
+
content = message.get("content")
|
|
93
|
+
if not isinstance(content, list):
|
|
94
|
+
continue
|
|
95
|
+
for block in content:
|
|
96
|
+
if not isinstance(block, dict):
|
|
97
|
+
continue
|
|
98
|
+
if row.get("type") == "assistant" and block.get("type") == "tool_use" and identifier(block.get("id")):
|
|
99
|
+
args = block.get("input")
|
|
100
|
+
if not isinstance(args, dict):
|
|
101
|
+
continue
|
|
102
|
+
if block.get("name") in ("Bash", "PowerShell") and isinstance(args.get("command"), str):
|
|
103
|
+
commands[block["id"]] = args["command"]
|
|
104
|
+
if block.get("name") == "Read" and set(args) == {"file_path"} and isinstance(args["file_path"], str):
|
|
105
|
+
files[block["id"]] = args["file_path"]
|
|
106
|
+
if row.get("type") == "user" and block.get("type") == "tool_result":
|
|
107
|
+
call = block.get("tool_use_id")
|
|
108
|
+
output = _plain(block.get("content"))
|
|
109
|
+
if not isinstance(call, str) or output is None or block.get("is_error"):
|
|
110
|
+
continue
|
|
111
|
+
if call in commands:
|
|
112
|
+
yield {"type": "CommandExecution", "status": "completed", "exit_code": 0,
|
|
113
|
+
"id": call, "command": commands[call], "aggregated_output": output,
|
|
114
|
+
"cwd": row.get("cwd")}
|
|
115
|
+
if call in files:
|
|
116
|
+
numbered = [line.partition("\t") for line in output.splitlines()]
|
|
117
|
+
if numbered and all(number == str(i) and tab for i, (number, tab, _) in enumerate(numbered, 1)):
|
|
118
|
+
lines = [line[2] for line in numbered]
|
|
119
|
+
if lines[-1] == "":
|
|
120
|
+
lines.pop()
|
|
121
|
+
yield {"type": "NativeFileRead", "id": call, "path": files[call], "lines": lines}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def read_turn(path, sessions_root, session, turn, surface, prompt_hash, stop_hashes):
|
|
125
|
+
if not prompt_hash or not stop_hashes:
|
|
126
|
+
return NativeTurn("observed", "Claude input or parent Stop evidence is missing")
|
|
127
|
+
try:
|
|
128
|
+
transcript = Path(path).resolve(strict=True)
|
|
129
|
+
if transcript.name != session + ".jsonl" or not transcript.is_relative_to(Path(sessions_root).resolve()):
|
|
130
|
+
return NativeTurn("observed", "Claude transcript lies outside the bound session")
|
|
131
|
+
turn_rows = []
|
|
132
|
+
for row in _rows(transcript):
|
|
133
|
+
if row.get("sessionId") != session or row.get("isSidechain") is True:
|
|
134
|
+
continue
|
|
135
|
+
content = row.get("message", {}).get("content")
|
|
136
|
+
if (row.get("type") == "user" and row.get("promptId") and not row.get("isMeta")
|
|
137
|
+
and (row.get("promptSource") or _plain(content) is not None)):
|
|
138
|
+
if row["promptId"] == turn:
|
|
139
|
+
if turn_rows:
|
|
140
|
+
return NativeTurn("observed", "Claude prompt identity is repeated")
|
|
141
|
+
turn_rows.append(row)
|
|
142
|
+
continue
|
|
143
|
+
if turn_rows:
|
|
144
|
+
break
|
|
145
|
+
if turn_rows:
|
|
146
|
+
turn_rows.append(row)
|
|
147
|
+
if not turn_rows:
|
|
148
|
+
return NativeTurn("observed", "Claude transcript has not recorded the prompt")
|
|
149
|
+
source = turn_rows[0]
|
|
150
|
+
text = _plain(source["message"]["content"])
|
|
151
|
+
if (source.get("isMeta") or source.get("promptSource") not in ("sdk", "repl", "user")
|
|
152
|
+
or text is None or A2A.search(text)):
|
|
153
|
+
return NativeTurn("excluded", "Claude input is injected or has unverified origin")
|
|
154
|
+
if not identifier(source.get("uuid")) or digest(text.encode()) != prompt_hash:
|
|
155
|
+
return NativeTurn("observed", "Claude user input does not match the hook")
|
|
156
|
+
assistants = [row for row in turn_rows[1:] if row.get("type") == "assistant"]
|
|
157
|
+
final = assistants[-1] if assistants else {}
|
|
158
|
+
message = final.get("message", {})
|
|
159
|
+
answer = _plain(message.get("content"))
|
|
160
|
+
if (message.get("stop_reason") != "end_turn" or answer is None
|
|
161
|
+
or digest(answer.strip().encode()) not in stop_hashes):
|
|
162
|
+
return NativeTurn("observed", "Claude final transcript and parent Stop do not match yet")
|
|
163
|
+
summaries = [row for row in turn_rows[turn_rows.index(final) + 1:]
|
|
164
|
+
if row.get("type") == "system" and row.get("subtype") == "stop_hook_summary"]
|
|
165
|
+
if not summaries or summaries[-1].get("preventedContinuation") is not False:
|
|
166
|
+
return NativeTurn("observed", "Claude Stop has not settled or another hook continued the turn")
|
|
167
|
+
cwd = source.get("cwd", "")
|
|
168
|
+
scoped = [row.get("cwd") for row in turn_rows if isinstance(row.get("cwd"), str)]
|
|
169
|
+
if not Path(cwd).is_absolute() or any(normalized(item) != normalized(cwd) for item in scoped):
|
|
170
|
+
return NativeTurn("excluded", "Claude work changed its native root")
|
|
171
|
+
model = message.get("model")
|
|
172
|
+
proof = f"Claude native Stop and attributed user input; model {model}" if identifier(model) else (
|
|
173
|
+
"Claude native Stop and attributed user input; model unverified")
|
|
174
|
+
return NativeTurn("confirmed", proof, cwd, source["uuid"], text, tuple(_native_reads(turn_rows)),
|
|
175
|
+
(cwd,), _clock(source), _clock(final))
|
|
176
|
+
except (OSError, TypeError, ValueError, KeyError, AttributeError):
|
|
177
|
+
return NativeTurn("observed", "Claude transcript is delayed, missing or invalid")
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def hook_path(root, *, project_settings=False):
|
|
181
|
+
root = Path(root).resolve()
|
|
182
|
+
directory = root / ".claude"
|
|
183
|
+
if directory.resolve().parent != root:
|
|
184
|
+
raise ValueError("Claude hook folder resolves outside the project")
|
|
185
|
+
return directory / ("settings.json" if project_settings else "settings.local.json")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def generated_hooks(store):
|
|
189
|
+
# Claude's command hooks use its Bash command line on Windows and POSIX.
|
|
190
|
+
executable = quote(Path(sys.executable).as_posix())
|
|
191
|
+
state = quote(store.directory.as_posix())
|
|
192
|
+
command = f"{executable} -m portable_skill_learning.cli --state {state} hook --tool claude"
|
|
193
|
+
return {"hooks": {event: [{"hooks": [{"type": "command", "command": command, "timeout": 5}]}]
|
|
194
|
+
for event in EVENTS}}
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def install_hooks(store, root, *, project_settings=False):
|
|
198
|
+
path = hook_path(root, project_settings=project_settings)
|
|
199
|
+
if store.root_for(store.route(root), root) != Path(normalized(root)):
|
|
200
|
+
raise ValueError("Install Claude hooks at an unambiguous registered root")
|
|
201
|
+
generated = generated_hooks(store)
|
|
202
|
+
if path.is_symlink():
|
|
203
|
+
raise ValueError("Claude hook file is a symbolic link")
|
|
204
|
+
if path.exists():
|
|
205
|
+
if json.loads(path.read_bytes()) != generated:
|
|
206
|
+
raise ValueError("Review existing Claude local settings before installation")
|
|
207
|
+
else:
|
|
208
|
+
atomic_write(path, json.dumps(generated, indent=2).encode() + b"\n")
|
|
209
|
+
return path
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def uninstall_hooks(store, root, *, project_settings=False):
|
|
213
|
+
path = hook_path(root, project_settings=project_settings)
|
|
214
|
+
if not path.exists():
|
|
215
|
+
return False
|
|
216
|
+
if path.is_symlink() or json.loads(path.read_bytes()) != generated_hooks(store):
|
|
217
|
+
raise ValueError("The Claude local settings changed outside this package")
|
|
218
|
+
path.unlink()
|
|
219
|
+
return True
|