asoftime 0.1.0__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.
Files changed (46) hide show
  1. adapters/__init__.py +0 -0
  2. adapters/antigravity/__init__.py +0 -0
  3. adapters/antigravity/asof_antigravity_orchestrator.py +362 -0
  4. adapters/antigravity/install.py +105 -0
  5. adapters/claude_code/__init__.py +0 -0
  6. adapters/claude_code/install.py +152 -0
  7. adapters/claude_code/post_tool.py +50 -0
  8. adapters/claude_code/session_init.py +79 -0
  9. adapters/claude_code/watch.py +75 -0
  10. adapters/generic/__init__.py +0 -0
  11. adapters/generic/examples/anthropic_sdk_wrapper.py +115 -0
  12. adapters/generic/examples/crewai_step.py +78 -0
  13. adapters/generic/examples/langgraph_node.py +79 -0
  14. asof_core/__init__.py +16 -0
  15. asof_core/cli.py +235 -0
  16. asof_core/cutoffs.py +133 -0
  17. asof_core/hooks/__init__.py +29 -0
  18. asof_core/hooks/post_tool.py +159 -0
  19. asof_core/hooks/session_init.py +118 -0
  20. asof_core/hooks/watch.py +193 -0
  21. asof_core/output.py +240 -0
  22. asof_core/patterns/__init__.py +112 -0
  23. asof_core/patterns/domains/__init__.py +25 -0
  24. asof_core/patterns/domains/crypto.py +28 -0
  25. asof_core/patterns/domains/devops.py +31 -0
  26. asof_core/patterns/domains/finance.py +33 -0
  27. asof_core/patterns/domains/news.py +28 -0
  28. asof_core/patterns/domains/sports.py +27 -0
  29. asof_core/patterns/domains/stocks.py +32 -0
  30. asof_core/patterns/domains/travel.py +32 -0
  31. asof_core/patterns/domains/weather.py +24 -0
  32. asof_core/patterns/high_confidence.py +61 -0
  33. asof_core/patterns/medium_confidence.py +69 -0
  34. asof_core/provenance.py +205 -0
  35. asof_core/query.py +294 -0
  36. asof_core/stat.py +233 -0
  37. asof_core/timestamps.py +266 -0
  38. asof_core/url_freshness.py +152 -0
  39. asof_core/version.py +61 -0
  40. asof_core/watchlist.py +171 -0
  41. asoftime-0.1.0.dist-info/METADATA +208 -0
  42. asoftime-0.1.0.dist-info/RECORD +46 -0
  43. asoftime-0.1.0.dist-info/WHEEL +5 -0
  44. asoftime-0.1.0.dist-info/entry_points.txt +2 -0
  45. asoftime-0.1.0.dist-info/licenses/LICENSE +21 -0
  46. asoftime-0.1.0.dist-info/top_level.txt +2 -0
adapters/__init__.py ADDED
File without changes
File without changes
@@ -0,0 +1,362 @@
1
+ #!/usr/bin/env python
2
+ """asof_antigravity_orchestrator.py
3
+
4
+ Orchestrator script for the AsOf temporal-awareness skill in Google Antigravity.
5
+ Synthesizes SessionStart, UserPromptSubmit, and PostToolUse events from PreInvocation.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import sys
11
+ import io
12
+ import json
13
+ import re
14
+ from pathlib import Path
15
+ from datetime import datetime, timezone
16
+
17
+ ASOF_DIR = Path.home() / ".asof"
18
+ TOOL_LOG_DIR = ASOF_DIR / "tool_log"
19
+ STATE_DIR = ASOF_DIR / "state"
20
+
21
+
22
+ # Training Cutoffs mapping (Standard Cutoff database fallback)
23
+ TRAINING_CUTOFFS = {
24
+ "gemini-3.5-flash": "2025-10-01",
25
+ "gemini-3.5-pro": "2025-10-01",
26
+ "gemini-3.1-pro-preview": "2025-05-01",
27
+ "default": "2025-10-01"
28
+ }
29
+
30
+ # Volatility classification lookup
31
+ VOLATILITY_MAP = {
32
+ "view_file": "session",
33
+ "read_file": "session",
34
+ "list_dir": "session",
35
+ "glob": "session",
36
+ "grep_search": "session",
37
+ "replace_file_content": "session",
38
+ "write_to_file": "session",
39
+ "multi_replace_file_content": "session",
40
+ "run_command": "external",
41
+ "search_web": "external",
42
+ "read_url_content": "external",
43
+ "invoke_subagent": "session"
44
+ }
45
+
46
+ # Regex Patterns for Tiers
47
+ TIER1_PATTERNS = [
48
+ r"\b(current|latest|now|live)\s+(price|rate|version|cost|status|news|forecast|data|figures|quote|fare|value)\b",
49
+ r"\bwhat'?s\s+(the\s+)?(current|latest|live)\b",
50
+ r"\bis\s+\w+\s+still\s+(at|in|on|the\s+same|current|active|available|valid|live|open)\b",
51
+ r"\bhas\s+\w+\s+changed\s+(since|in|after)\b",
52
+ r"\b(stock|share)\s+(price|quote|value)\s+(of|for)\b",
53
+ r"\b(real[-]?time)\s+\w+",
54
+ r"\bup[-\s]?to[-\s]?date\b",
55
+ r"\b(today'?s|yesterday'?s|this\s+(week|month|year)'?s)\s+(price|rate|data|figures|report|update|news)\b"
56
+ ]
57
+
58
+ TIER2_PATTERNS = [
59
+ r"\b(recently|lately|just\s+now)\b",
60
+ r"\b(yesterday|today|tomorrow)\b",
61
+ r"\b(last|next)\s+(week|month|year|quarter|day|hour|night|morning|afternoon|evening)\b",
62
+ r"\b\d+\s+(days?|weeks?|months?|years?|hours?|minutes?)\s+ago\b",
63
+ r"\b(this|next|last)\s+(month|quarter|year|fiscal\s+year)\b",
64
+ r"\b(forecast|projection|estimate|prediction|outlook)\b",
65
+ r"\b(deadline|expires?|expiring|due\s+date|cutoff)\b",
66
+ r"\b(schedule|booking|reservation|appointment)\b",
67
+ r"\b(when|how\s+long\s+ago)\b"
68
+ ]
69
+
70
+ def _read_input() -> dict:
71
+ try:
72
+ raw = sys.stdin.read()
73
+ if not raw.strip():
74
+ return {}
75
+ return json.loads(raw)
76
+ except Exception:
77
+ return {}
78
+
79
+ def get_last_processed_step(conv_id: str) -> int:
80
+ state_file = STATE_DIR / f"state_{conv_id}.json"
81
+ if not state_file.exists():
82
+ return -1
83
+ try:
84
+ data = json.loads(state_file.read_text(encoding="utf-8"))
85
+ return data.get("last_processed_step_index", -1)
86
+ except Exception:
87
+ return -1
88
+
89
+ def save_last_processed_step(conv_id: str, step_index: int):
90
+ state_file = STATE_DIR / f"state_{conv_id}.json"
91
+ try:
92
+ state_file.write_text(json.dumps({"last_processed_step_index": step_index}), encoding="utf-8")
93
+ except Exception:
94
+ pass
95
+
96
+ def parse_tool_arg(tool_name: str, args: dict) -> str:
97
+ """Extract a target description from tool arguments."""
98
+ if not args:
99
+ return ""
100
+ if tool_name in ("view_file", "read_file", "write_to_file", "replace_file_content", "multi_replace_file_content"):
101
+ return args.get("AbsolutePath", args.get("TargetFile", ""))
102
+ if tool_name == "list_dir":
103
+ return args.get("DirectoryPath", "")
104
+ if tool_name == "run_command":
105
+ return args.get("CommandLine", "")
106
+ if tool_name == "read_url_content":
107
+ return args.get("Url", "")
108
+ if tool_name == "search_web":
109
+ return args.get("query", "")
110
+ return str(args)
111
+
112
+ def process_transcript_events(conv_id: str, transcript_path: str):
113
+ """Scan transcript.jsonl for new completed tool calls and log them to tool_log."""
114
+ if not transcript_path or not os.path.exists(transcript_path):
115
+ return
116
+
117
+ last_idx = get_last_processed_step(conv_id)
118
+ max_idx = last_idx
119
+
120
+ tool_log_file = TOOL_LOG_DIR / f"{conv_id}.jsonl"
121
+ events_to_write = []
122
+
123
+ try:
124
+ with open(transcript_path, "r", encoding="utf-8", errors="replace") as f:
125
+ for line in f:
126
+ if not line.strip():
127
+ continue
128
+ try:
129
+ entry = json.loads(line)
130
+ step_index = entry.get("step_index", -1)
131
+ if step_index <= last_idx:
132
+ continue
133
+
134
+ if step_index > max_idx:
135
+ max_idx = step_index
136
+
137
+ # Detect tool usage in model responses
138
+ if entry.get("source") == "MODEL" and entry.get("type") == "PLANNER_RESPONSE":
139
+ tool_calls = entry.get("tool_calls", [])
140
+ for call in tool_calls:
141
+ name = call.get("name")
142
+ args = call.get("args", {})
143
+ if isinstance(args, str):
144
+ try:
145
+ args = json.loads(args)
146
+ except Exception:
147
+ pass
148
+ target = parse_tool_arg(name, args)
149
+ volatility = VOLATILITY_MAP.get(name, "static")
150
+
151
+ log_entry = {
152
+ "ts": entry.get("created_at", datetime.now(timezone.utc).isoformat()),
153
+ "step_index": step_index,
154
+ "tool_name": name,
155
+ "target": target,
156
+ "volatility": volatility
157
+ }
158
+ events_to_write.append(log_entry)
159
+ except (json.JSONDecodeError, TypeError):
160
+ continue
161
+ except Exception:
162
+ return
163
+
164
+ if events_to_write:
165
+ try:
166
+ with open(tool_log_file, "a", encoding="utf-8") as out_f:
167
+ for ev in events_to_write:
168
+ out_f.write(json.dumps(ev) + "\n")
169
+ except Exception:
170
+ pass
171
+
172
+ if max_idx > last_idx:
173
+ save_last_processed_step(conv_id, max_idx)
174
+
175
+ def get_latest_user_prompt(transcript_path: str) -> str:
176
+ """Find the most recent user prompt in the transcript."""
177
+ if not transcript_path or not os.path.exists(transcript_path):
178
+ return ""
179
+
180
+ prompts = []
181
+ try:
182
+ with open(transcript_path, "r", encoding="utf-8", errors="replace") as f:
183
+ for line in f:
184
+ if not line.strip():
185
+ continue
186
+ try:
187
+ entry = json.loads(line)
188
+ if entry.get("source") == "USER_EXPLICIT" and entry.get("type") == "USER_INPUT":
189
+ prompts.append(entry.get("content", ""))
190
+ except Exception:
191
+ continue
192
+ except Exception:
193
+ pass
194
+
195
+ return prompts[-1] if prompts else ""
196
+
197
+ def check_file_freshness(conv_id: str) -> list[str]:
198
+ """Check if any file read during the session is now stale on disk."""
199
+ tool_log_file = TOOL_LOG_DIR / f"{conv_id}.jsonl"
200
+ if not tool_log_file.exists():
201
+ return []
202
+
203
+ # Map file to the datetime it was last read
204
+ file_reads: dict[str, datetime] = {}
205
+
206
+ try:
207
+ with open(tool_log_file, "r", encoding="utf-8") as f:
208
+ for line in f:
209
+ if not line.strip():
210
+ continue
211
+ try:
212
+ ev = json.loads(line)
213
+ vol = ev.get("volatility")
214
+ target = ev.get("target")
215
+ if vol == "session" and target and os.path.isfile(target):
216
+ # Parse UTC timestamp
217
+ ts_str = ev.get("ts").replace("Z", "+00:00")
218
+ dt = datetime.fromisoformat(ts_str)
219
+ file_reads[target] = dt
220
+ except Exception:
221
+ continue
222
+ except Exception:
223
+ return []
224
+
225
+ stale_alerts = []
226
+ for filepath, read_dt in file_reads.items():
227
+ try:
228
+ mtime = os.path.getmtime(filepath)
229
+ mtime_dt = datetime.fromtimestamp(mtime, timezone.utc)
230
+ if mtime_dt > read_dt:
231
+ age_delta = datetime.now(timezone.utc) - read_dt
232
+ hours = int(age_delta.total_seconds() // 3600)
233
+ minutes = int((age_delta.total_seconds() % 3600) // 60)
234
+ age_str = f"{hours}h{minutes}m" if hours > 0 else f"{minutes}m"
235
+
236
+ mtime_delta = datetime.now(timezone.utc) - mtime_dt
237
+ mtime_hours = int(mtime_delta.total_seconds() // 3600)
238
+ mtime_minutes = int((mtime_delta.total_seconds() % 3600) // 60)
239
+ mtime_str = f"{mtime_hours}h{mtime_minutes}m" if mtime_hours > 0 else f"{mtime_minutes}m"
240
+
241
+ stale_alerts.append(
242
+ f" STALE {age_str} {filepath} (mtime moved {mtime_str} ago)"
243
+ )
244
+ except OSError:
245
+ continue
246
+
247
+ return stale_alerts
248
+
249
+ def parse_prompt_temporal_cues(prompt: str) -> list[str]:
250
+ """Parse user prompt for time-sensitive phrasing using Tiers 1 and 2."""
251
+ if not prompt:
252
+ return []
253
+
254
+ matched_phrases = []
255
+ # Test Tier 1
256
+ for pat in TIER1_PATTERNS:
257
+ match = re.search(pat, prompt, re.IGNORECASE)
258
+ if match:
259
+ matched_phrases.append(f"High-Confidence: '{match.group(0)}'")
260
+
261
+ # Test Tier 2
262
+ for pat in TIER2_PATTERNS:
263
+ match = re.search(pat, prompt, re.IGNORECASE)
264
+ if match:
265
+ matched_phrases.append(f"Medium-Confidence: '{match.group(0)}'")
266
+
267
+ return matched_phrases
268
+
269
+ def main() -> int:
270
+ # Ensure directories exist
271
+ TOOL_LOG_DIR.mkdir(parents=True, exist_ok=True)
272
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
273
+
274
+ input_data = _read_input()
275
+ conv_id = input_data.get("conversationId")
276
+ invocation_num = input_data.get("invocationNum", 0)
277
+ transcript_path = input_data.get("transcriptPath")
278
+
279
+ if not conv_id:
280
+ print(json.dumps({"injectSteps": []}))
281
+ return 0
282
+
283
+ # Parse and log new tool execution events if invocation_num > 0
284
+ if invocation_num > 0 and transcript_path:
285
+ process_transcript_events(conv_id, transcript_path)
286
+
287
+ # State checks for session wake
288
+ state_file = ASOF_DIR / "session_state.json"
289
+ is_wake = False
290
+
291
+ try:
292
+ session_state = {}
293
+ if state_file.exists():
294
+ session_state = json.loads(state_file.read_text(encoding="utf-8"))
295
+ if conv_id != session_state.get("last_conversation_id"):
296
+ is_wake = True
297
+ session_state["last_conversation_id"] = conv_id
298
+ state_file.write_text(json.dumps(session_state), encoding="utf-8")
299
+ except Exception:
300
+ pass
301
+
302
+ steps = []
303
+
304
+ # 1. SessionStart (Wake) Injection
305
+ if is_wake and invocation_num == 0:
306
+ now_dt = datetime.now(timezone.utc)
307
+ weekday = now_dt.strftime("%A")
308
+ date_str = now_dt.strftime("%Y-%m-%d %H:%M")
309
+
310
+ # Resolve model name to fetch cutoff
311
+ # Example subset of env check
312
+ model_name = os.environ.get("GEMINI_MODEL", "default")
313
+ cutoff = TRAINING_CUTOFFS.get(model_name, TRAINING_CUTOFFS["default"])
314
+ cutoff_dt = datetime.strptime(cutoff, "%Y-%m-%d").replace(tzinfo=timezone.utc)
315
+ gap = now_dt - cutoff_dt
316
+ gap_days = gap.days
317
+ gap_months = int(gap_days // 30.4)
318
+ gap_str = f"~{gap_months} months" if gap_months > 0 else f"{gap_days} days"
319
+
320
+ wake_msg = (
321
+ f"=== AsOf v1.0.0 ===\n"
322
+ f"Today: {weekday} {date_str} UTC\n"
323
+ f"Training cutoff: {cutoff} ({gap_str} ago)\n\n"
324
+ f"Directive: Consider time-decay when grounding claims. When in-context "
325
+ f"data may be stale (files read earlier, dated content in prompts, "
326
+ f"training-era facts), query asof_query for specifics rather than "
327
+ f"computing date math yourself."
328
+ )
329
+ steps.append({"ephemeralMessage": wake_msg})
330
+
331
+ # 2. UserPromptSubmit Injection (Invocation 0 only)
332
+ if invocation_num == 0 and transcript_path:
333
+ stale_files = check_file_freshness(conv_id)
334
+ user_prompt = get_latest_user_prompt(transcript_path)
335
+ temporal_cues = parse_prompt_temporal_cues(user_prompt)
336
+
337
+ turn_blocks = []
338
+ if stale_files:
339
+ turn_blocks.append("## File freshness (this session)")
340
+ turn_blocks.extend(stale_files)
341
+
342
+ if temporal_cues:
343
+ turn_blocks.append("\n## Time-sensitive phrasing detected")
344
+ for cue in temporal_cues:
345
+ turn_blocks.append(f" {cue} → potential training cutoff skew.")
346
+
347
+ if stale_files:
348
+ turn_blocks.append("\n## Alert")
349
+ turn_blocks.append(f" WARNING: {len(stale_files)} files in working set are stale. Re-read before grounding.")
350
+
351
+ if turn_blocks:
352
+ prompt_alert = "=== AsOf Freshness Watch ===\n" + "\n".join(turn_blocks)
353
+ steps.append({"ephemeralMessage": prompt_alert})
354
+
355
+ print(json.dumps({"injectSteps": steps}))
356
+ return 0
357
+
358
+ if __name__ == "__main__":
359
+ # Force UTF-8 encoding
360
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace", line_buffering=True)
361
+ sys.stdin = io.TextIOWrapper(sys.stdin.buffer, encoding="utf-8", errors="replace")
362
+ sys.exit(main())
@@ -0,0 +1,105 @@
1
+ #!/usr/bin/env python
2
+ """install.py
3
+
4
+ Installer script for the AsOf temporal-awareness skill Antigravity adapter.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import sys
10
+ import json
11
+ import shutil
12
+ from pathlib import Path
13
+
14
+ def main() -> int:
15
+ print("[AsOf Install] Starting installation of Antigravity adapter...")
16
+
17
+ # 1. Define paths
18
+ home_dir = Path.home()
19
+ gemini_config_dir = home_dir / ".gemini" / "config"
20
+ hooks_file = gemini_config_dir / "hooks.json"
21
+ sidecars_dir = gemini_config_dir / "sidecars" / "asof"
22
+ plugins_dir = gemini_config_dir / "plugins" / "asof"
23
+
24
+ script_dir = Path(__file__).resolve().parent
25
+ orchestrator_source = script_dir / "asof_antigravity_orchestrator.py"
26
+ snippet_source = script_dir / "hooks_snippet.json"
27
+ skill_source = script_dir / "SKILL.md"
28
+
29
+ # Verify source files exist
30
+ for f in (orchestrator_source, snippet_source, skill_source):
31
+ if not f.exists():
32
+ print(f"[AsOf Install] ERROR: Source file {f.name} missing in installation package.")
33
+ return 1
34
+
35
+ # 2. Create target directories
36
+ sidecars_dir.mkdir(parents=True, exist_ok=True)
37
+ plugins_dir.mkdir(parents=True, exist_ok=True)
38
+
39
+ # 3. Copy files to sidecar and plugin directory
40
+ orchestrator_target = sidecars_dir / "asof_antigravity_orchestrator.py"
41
+ shutil.copy2(orchestrator_source, orchestrator_target)
42
+ os.chmod(orchestrator_target, 0o755)
43
+ print(f"[AsOf Install] Copied orchestrator script to {orchestrator_target}")
44
+
45
+ skill_target = plugins_dir / "SKILL.md"
46
+ shutil.copy2(skill_source, skill_target)
47
+ print(f"[AsOf Install] Copied SKILL.md to {skill_target}")
48
+
49
+ # 4. Patch hooks.json
50
+ hooks_data = {}
51
+ if hooks_file.exists():
52
+ try:
53
+ hooks_data = json.loads(hooks_file.read_text(encoding="utf-8"))
54
+ print(f"[AsOf Install] Found existing hooks configuration at {hooks_file}")
55
+ except Exception as e:
56
+ print(f"[AsOf Install] WARNING: Failed to read existing hooks.json ({e}). Re-initializing.")
57
+ hooks_data = {}
58
+
59
+ # Read and process hook snippet template
60
+ try:
61
+ snippet_text = snippet_source.read_text(encoding="utf-8")
62
+ # Fully resolve paths with forward slashes for Windows compatibility
63
+ resolved_orch_path = str(orchestrator_target.resolve()).replace("\\", "/")
64
+ snippet_text = snippet_text.replace("{{ORCHESTRATOR_PATH}}", resolved_orch_path)
65
+ snippet_json = json.loads(snippet_text)
66
+ except Exception as e:
67
+ print(f"[AsOf Install] ERROR: Failed to process hook snippet ({e}).")
68
+ return 1
69
+
70
+ # Merge hook config under the "current" agent block
71
+ if "current" not in hooks_data:
72
+ hooks_data["current"] = {}
73
+ if "PreInvocation" not in hooks_data["current"]:
74
+ hooks_data["current"]["PreInvocation"] = []
75
+
76
+ # Check if hook already exists to make registration idempotent
77
+ existing_hooks = hooks_data["current"]["PreInvocation"]
78
+ new_hook = snippet_json["current"]["PreInvocation"][0]
79
+
80
+ hook_found = False
81
+ for hook in existing_hooks:
82
+ if hook.get("command") == new_hook.get("command"):
83
+ hook_found = True
84
+ break
85
+
86
+ if not hook_found:
87
+ existing_hooks.append(new_hook)
88
+ print("[AsOf Install] Appended PreInvocation orchestrator hook.")
89
+ else:
90
+ print("[AsOf Install] PreInvocation hook is already registered (idempotency check passed).")
91
+
92
+ # Write back hooks.json
93
+ try:
94
+ hooks_file.parent.mkdir(parents=True, exist_ok=True)
95
+ hooks_file.write_text(json.dumps(hooks_data, indent=2), encoding="utf-8")
96
+ print(f"[AsOf Install] Successfully updated {hooks_file}")
97
+ except Exception as e:
98
+ print(f"[AsOf Install] ERROR: Failed to write hooks.json ({e}).")
99
+ return 1
100
+
101
+ print("[AsOf Install] Installation completed successfully.")
102
+ return 0
103
+
104
+ if __name__ == "__main__":
105
+ sys.exit(main())
File without changes
@@ -0,0 +1,152 @@
1
+ """Claude Code adapter installer.
2
+
3
+ Idempotently:
4
+ 1. Creates ~/.claude/skills/asof/ and copies SKILL.md there
5
+ 2. Patches ~/.claude/settings.json to add AsOf hook entries
6
+ 3. Verifies the install via a dry-run hook fire
7
+
8
+ Run via: asof install --adapter claude_code (recommended)
9
+ Or directly: python -m adapters.claude_code.install
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import shutil
15
+ import sys
16
+ from pathlib import Path
17
+
18
+
19
+ CLAUDE_HOME = Path.home() / ".claude"
20
+ SKILL_DIR = CLAUDE_HOME / "skills" / "asof"
21
+ SETTINGS_PATH = CLAUDE_HOME / "settings.json"
22
+
23
+ ADAPTER_DIR = Path(__file__).resolve().parent
24
+
25
+
26
+ def install_skill_file() -> None:
27
+ """Copy SKILL.md from the adapter to ~/.claude/skills/asof/."""
28
+ SKILL_DIR.mkdir(parents=True, exist_ok=True)
29
+ src = ADAPTER_DIR / "SKILL.md"
30
+ dst = SKILL_DIR / "SKILL.md"
31
+ shutil.copyfile(src, dst)
32
+ print(f" SKILL.md installed at {dst}")
33
+
34
+
35
+ def patch_settings() -> bool:
36
+ """Add AsOf hooks to settings.json. Idempotent.
37
+
38
+ Returns True if changes were made, False if already present.
39
+ """
40
+ snippet_path = ADAPTER_DIR / "hooks_snippet.json"
41
+ with snippet_path.open(encoding="utf-8") as f:
42
+ snippet = json.load(f)
43
+ asof_hooks = snippet["hooks"]
44
+
45
+ # Load existing settings
46
+ if SETTINGS_PATH.is_file():
47
+ with SETTINGS_PATH.open(encoding="utf-8") as f:
48
+ settings = json.load(f)
49
+ else:
50
+ settings = {}
51
+
52
+ if "hooks" not in settings:
53
+ settings["hooks"] = {}
54
+
55
+ changed = False
56
+ for event_name, event_hooks in asof_hooks.items():
57
+ existing = settings["hooks"].get(event_name, [])
58
+
59
+ # Check if our hook is already there (by command match)
60
+ for asof_block in event_hooks:
61
+ for asof_cmd in asof_block.get("hooks", []):
62
+ cmd_str = asof_cmd.get("command", "")
63
+ already_present = False
64
+ for existing_block in existing:
65
+ for existing_cmd in existing_block.get("hooks", []):
66
+ if existing_cmd.get("command") == cmd_str:
67
+ already_present = True
68
+ break
69
+ if already_present:
70
+ break
71
+ if not already_present:
72
+ # Append our block
73
+ existing.append({"hooks": [asof_cmd]})
74
+ changed = True
75
+
76
+ settings["hooks"][event_name] = existing
77
+
78
+ if changed:
79
+ SETTINGS_PATH.parent.mkdir(parents=True, exist_ok=True)
80
+ with SETTINGS_PATH.open("w", encoding="utf-8") as f:
81
+ json.dump(settings, f, indent=2)
82
+ f.write("\n")
83
+ print(f" settings.json patched at {SETTINGS_PATH}")
84
+ else:
85
+ print(f" settings.json already contains AsOf hooks; no change")
86
+
87
+ return changed
88
+
89
+
90
+ def verify() -> bool:
91
+ """Quick verification: can we import asof_core, do the hook scripts
92
+ exist on disk, does settings.json have the entries?"""
93
+ print("\nVerifying installation:")
94
+ ok = True
95
+
96
+ try:
97
+ import asof_core
98
+ print(f" asof_core importable (v{asof_core.__version__})")
99
+ except ImportError as e:
100
+ print(f" FAIL: asof_core not importable: {e}")
101
+ ok = False
102
+
103
+ for hook_script in ["session_init.py", "watch.py", "post_tool.py"]:
104
+ p = ADAPTER_DIR / hook_script
105
+ if p.is_file():
106
+ print(f" {hook_script} present")
107
+ else:
108
+ print(f" FAIL: {hook_script} missing at {p}")
109
+ ok = False
110
+
111
+ if SETTINGS_PATH.is_file():
112
+ with SETTINGS_PATH.open(encoding="utf-8") as f:
113
+ settings = json.load(f)
114
+ hooks = settings.get("hooks", {})
115
+ for event in ["SessionStart", "UserPromptSubmit", "PostToolUse"]:
116
+ entries = hooks.get(event, [])
117
+ has_asof = any(
118
+ "asof" in (cmd.get("command", "") or "")
119
+ for block in entries
120
+ for cmd in block.get("hooks", [])
121
+ )
122
+ if has_asof:
123
+ print(f" {event} hook wired")
124
+ else:
125
+ print(f" WARN: {event} hook not found in settings.json")
126
+ ok = False
127
+ else:
128
+ print(f" FAIL: settings.json not found at {SETTINGS_PATH}")
129
+ ok = False
130
+
131
+ return ok
132
+
133
+
134
+ def main() -> int:
135
+ print("Installing AsOf for Claude Code...")
136
+ print()
137
+
138
+ install_skill_file()
139
+ patch_settings()
140
+ ok = verify()
141
+
142
+ print()
143
+ if ok:
144
+ print("Install complete. Restart Claude Code to activate.")
145
+ return 0
146
+ else:
147
+ print("Install completed with warnings. See output above.")
148
+ return 1
149
+
150
+
151
+ if __name__ == "__main__":
152
+ sys.exit(main())
@@ -0,0 +1,50 @@
1
+ """Claude Code PostToolUse hook entry.
2
+
3
+ Invoked by Claude Code after every tool call. Reads the event JSON
4
+ from stdin, captures tool metadata (including mtime at read time for
5
+ file ops) into the session-scoped tool log.
6
+
7
+ Silent-fail discipline: never crash, never break the substrate.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import sys
13
+ from datetime import datetime, timezone
14
+
15
+ from asof_core.hooks import post_tool
16
+
17
+
18
+ def main() -> int:
19
+ try:
20
+ raw = sys.stdin.read()
21
+ if not raw:
22
+ return 0
23
+ event = json.loads(raw)
24
+ if not isinstance(event, dict):
25
+ return 0
26
+
27
+ tool_name = event.get("tool_name") or ""
28
+ if not isinstance(tool_name, str) or not tool_name:
29
+ return 0
30
+
31
+ tool_input = event.get("tool_input") or {}
32
+ if not isinstance(tool_input, dict):
33
+ tool_input = {}
34
+
35
+ session_id = event.get("session_id") or "unknown-session"
36
+
37
+ post_tool(
38
+ session_id=session_id,
39
+ tool_name=tool_name,
40
+ tool_input=tool_input,
41
+ now=datetime.now(timezone.utc),
42
+ )
43
+ except (json.JSONDecodeError, OSError, ValueError, TypeError):
44
+ # Silent failure — never break the substrate
45
+ pass
46
+ return 0
47
+
48
+
49
+ if __name__ == "__main__":
50
+ sys.exit(main())