Coverage for little_loops / hooks / session_start.py: 0%

126 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-06-08 15:34 -0500

1"""SessionStart hook handler: load config + apply ``.ll/ll.local.md`` overrides. 

2 

3Python port of ``hooks/scripts/session-start.sh`` (FEAT-1450). The ``handle`` 

4function is invoked by the dispatcher in 

5``little_loops.hooks.__init__::main_hooks`` after the Claude Code adapter 

6(``hooks/adapters/claude-code/session-start.sh``) reads the host's stdin 

7payload. 

8 

9Observable side-effects preserved from the bash version: 

10 

111. Removes ``.ll/ll-context-state.json`` from the prior session (best-effort). 

122. Resolves the project config via :func:`little_loops.config.core.resolve_config_path`. 

133. If ``.ll/ll.local.md`` exists, parses its YAML frontmatter with 

14 ``yaml.safe_load`` and deep-merges it into the base config — arrays 

15 replace, explicit ``None`` removes keys. 

164. Emits the rendered config JSON via ``LLHookResult.stdout`` so Claude Code 

17 ingests it as session context. 

185. Composes stderr feedback covering the ``Config loaded`` line, the optional 

19 ``Local overrides applied`` line, a ``Warning: Large config`` line when the 

20 rendered config exceeds 5000 chars, the ``Warning: No config found`` line 

21 when neither candidate exists, and feature-flag validation warnings for 

22 ``sync.enabled`` / ``documents.enabled``. 

23 

24The bash version had a stdout/stderr inconsistency for the no-config warning; 

25this port chooses stderr in both branches (per the issue's Step-resolved 

26decision). 

27""" 

28 

29from __future__ import annotations 

30 

31import contextlib 

32import json 

33import logging 

34import subprocess 

35import sys 

36from pathlib import Path 

37from typing import Any 

38 

39import yaml 

40 

41from little_loops.config.core import deep_merge, resolve_config_path 

42from little_loops.config.features import feature_enabled 

43from little_loops.hooks.types import LLHookEvent, LLHookResult 

44 

45logger = logging.getLogger(__name__) 

46 

47_LOCAL_OVERRIDE_FILE = Path(".ll/ll.local.md") 

48_PRIOR_SESSION_STATE = Path(".ll/ll-context-state.json") 

49_LARGE_CONFIG_THRESHOLD = 5000 

50 

51 

52def _parse_frontmatter(content: str) -> dict[str, Any]: 

53 """Extract YAML frontmatter (arbitrary nested shapes) from a markdown doc. 

54 

55 Mirrors the bash version's behaviour: returns ``{}`` for any malformed or 

56 missing frontmatter, and uses ``yaml.safe_load`` so nested dicts / lists / 

57 explicit nulls survive. Not interchangeable with 

58 ``little_loops.frontmatter.parse_frontmatter`` (which is a key:value subset 

59 parser) — local-override frontmatter needs full YAML. 

60 """ 

61 if not content or not content.startswith("---"): 

62 return {} 

63 parts = content.split("---", 2) 

64 if len(parts) < 3: 

65 return {} 

66 text = parts[1].strip() 

67 if not text: 

68 return {} 

69 try: 

70 loaded = yaml.safe_load(text) 

71 except yaml.YAMLError: 

72 return {} 

73 return loaded if isinstance(loaded, dict) else {} 

74 

75 

76def handle(event: LLHookEvent) -> LLHookResult: 

77 """Build the merged session-start config and validate feature flags. 

78 

79 Returns ``LLHookResult(exit_code=0, feedback=<stderr>, stdout=<config-json>)``. 

80 """ 

81 # ENH-1945: _run_backfill() consumes transcript_path from the payload for 

82 # non-Claude-Code hosts (Codex, OpenCode). The event object must be preserved 

83 # so the backfill daemon thread can read it. 

84 

85 cwd = Path.cwd() 

86 feedback_lines: list[str] = [] 

87 

88 # 1. Clean up prior-session state (best-effort, suppress all errors). 

89 with contextlib.suppress(OSError): 

90 _PRIOR_SESSION_STATE.unlink() 

91 

92 # 2. Resolve base config. 

93 config_path = resolve_config_path(cwd) 

94 base_config: dict[str, Any] = {} 

95 if config_path is not None: 

96 try: 

97 base_config = json.loads(config_path.read_text(encoding="utf-8")) 

98 except (OSError, json.JSONDecodeError): 

99 base_config = {} 

100 

101 # 3. Apply local overrides if present. 

102 local_file = cwd / _LOCAL_OVERRIDE_FILE 

103 overrides_applied = False 

104 merged_config: dict[str, Any] = base_config 

105 if local_file.is_file(): 

106 try: 

107 override_text = local_file.read_text(encoding="utf-8") 

108 except OSError: 

109 override_text = "" 

110 local_overrides = _parse_frontmatter(override_text) 

111 if local_overrides: 

112 merged_config = deep_merge(base_config, local_overrides) 

113 overrides_applied = True 

114 

115 # 3b. Bootstrap the unified session store (FEAT-1112). Best-effort and only 

116 # for initialized projects — uninitialized projects (no config) are a no-op 

117 # so the hook never creates a stray .ll/ directory. 

118 _project_context_block = "" 

119 if config_path is not None: 

120 with contextlib.suppress(Exception): 

121 from little_loops.session_store import ensure_db, resolve_history_db 

122 

123 ensure_db(resolve_history_db(cwd / ".ll" / "history.db")) 

124 

125 # ENH-1830 / BUG-1882: trigger incremental JSONL backfill in a detached 

126 # subprocess so it outlives the short-lived hook process. A daemon thread 

127 # is killed when the hook subprocess exits (typically in <0.5s), so it 

128 # never commits. Path discovery runs synchronously here (fast) to produce 

129 # the concrete path arg passed to the worker. 

130 import os as _os 

131 

132 _db_path = ( 

133 Path(_os.environ["LL_HISTORY_DB"]) 

134 if _os.environ.get("LL_HISTORY_DB") 

135 else cwd / ".ll" / "history.db" 

136 ) 

137 

138 with contextlib.suppress(Exception): 

139 from little_loops.user_messages import get_project_folder 

140 

141 # ENH-1945: consume transcript_path from hook payload when available. 

142 payload = event.payload or {} 

143 _transcript = (payload.get("transcript_path") or "").strip() 

144 if _transcript and Path(_transcript).is_file(): 

145 _backfill_path: str | None = _transcript 

146 else: 

147 _pf = get_project_folder(cwd) 

148 _backfill_path = str(_pf) if _pf is not None else None 

149 

150 if _backfill_path is not None: 

151 subprocess.Popen( 

152 [ 

153 sys.executable, 

154 "-m", 

155 "little_loops.cli.backfill_worker", 

156 str(_db_path), 

157 _backfill_path, 

158 ], 

159 start_new_session=True, 

160 stdin=subprocess.DEVNULL, 

161 stdout=subprocess.DEVNULL, 

162 stderr=subprocess.DEVNULL, 

163 cwd=str(cwd), 

164 ) 

165 

166 # ENH-1907: Inject project-context digest (best-effort, opt-in). 

167 # Runs after the backfill thread launches so the digest reflects only 

168 # already-persisted rows from prior sessions, not this session's backfill. 

169 with contextlib.suppress(Exception): 

170 if feature_enabled(merged_config, "history.session_digest.enabled"): 

171 from little_loops.config.features import HistoryConfig 

172 from little_loops.history_reader import project_digest, render_project_context 

173 

174 _hist = HistoryConfig.from_dict(merged_config.get("history", {})) 

175 _sd = _hist.session_digest 

176 # Convert empty sections list to None so the default config renders 

177 # all providers; a non-empty list restricts/orders the output. 

178 _sections = _sd.sections if _sd.sections else None 

179 _digest = project_digest(_db_path, days=_sd.days, sections=_sections) 

180 _project_context_block = render_project_context( 

181 _digest, char_cap=_sd.char_cap, days=_sd.days 

182 ) 

183 

184 # 4. Compose the rendered stdout payload. 

185 if config_path is not None and not overrides_applied: 

186 # Match bash: preserve original on-disk formatting when no overrides. 

187 try: 

188 stdout_payload: str | None = config_path.read_text(encoding="utf-8") 

189 except OSError: 

190 stdout_payload = json.dumps(merged_config, indent=2) 

191 elif config_path is not None or overrides_applied: 

192 stdout_payload = json.dumps(merged_config, indent=2) 

193 else: 

194 stdout_payload = None 

195 

196 # Append project-context block (ENH-1907) if populated. 

197 if _project_context_block: 

198 if stdout_payload is not None: 

199 stdout_payload = stdout_payload + "\n\n" + _project_context_block 

200 else: 

201 stdout_payload = _project_context_block 

202 

203 # 5. Compose feedback (stderr). 

204 if config_path is not None: 

205 # Match bash output format: print() uses a space separator, not a colon-space. 

206 feedback_lines.append(f"[little-loops] Config loaded: {config_path}") 

207 if overrides_applied: 

208 feedback_lines.append(f"[little-loops] Local overrides applied from: {local_file}") 

209 if stdout_payload is not None and len(stdout_payload) > _LARGE_CONFIG_THRESHOLD: 

210 feedback_lines.append( 

211 f"[little-loops] Warning: Large config ({len(stdout_payload)} chars)" 

212 ) 

213 else: 

214 feedback_lines.append( 

215 "[little-loops] Warning: No config found. Run /ll:init to create one." 

216 ) 

217 

218 # 6. Feature-flag validation warnings. 

219 feedback_lines.extend(_validate_features(merged_config)) 

220 

221 feedback = "\n".join(feedback_lines) if feedback_lines else None 

222 return LLHookResult(exit_code=0, feedback=feedback, stdout=stdout_payload) 

223 

224 

225def _validate_features(config: dict[str, Any]) -> list[str]: 

226 """Return stderr warning lines for misconfigured enabled features. 

227 

228 Mirrors ``validate_enabled_features`` in the bash version exactly: 

229 

230 - ``sync.enabled: true`` with empty ``sync.github`` → warn. 

231 - ``documents.enabled: true`` with empty ``documents.categories`` → warn. 

232 

233 Other ``*.enabled`` flags (e.g. ``product.enabled``) are intentionally not 

234 validated — the existing ``TestSessionStartValidation`` test fixture 

235 enables ``product`` and asserts no ``Warning:`` substring appears. 

236 """ 

237 warnings_out: list[str] = [] 

238 sync = config.get("sync") if isinstance(config.get("sync"), dict) else {} 

239 if isinstance(sync, dict) and sync.get("enabled") is True: 

240 github = sync.get("github") 

241 if not isinstance(github, dict) or not github: 

242 warnings_out.append( 

243 "[little-loops] Warning: sync.enabled is true but sync.github is not configured" 

244 ) 

245 documents = config.get("documents") if isinstance(config.get("documents"), dict) else {} 

246 if isinstance(documents, dict) and documents.get("enabled") is True: 

247 categories = documents.get("categories") 

248 if not isinstance(categories, dict) or not categories: 

249 warnings_out.append( 

250 "[little-loops] Warning: documents.enabled is true but no document categories" 

251 " configured" 

252 ) 

253 design_tokens = ( 

254 config.get("design_tokens") if isinstance(config.get("design_tokens"), dict) else {} 

255 ) 

256 if isinstance(design_tokens, dict) and design_tokens.get("enabled") is True: 

257 from pathlib import Path 

258 

259 token_path = Path(design_tokens.get("path", ".ll/design-tokens")) 

260 if not token_path.exists(): 

261 warnings_out.append( 

262 "[little-loops] Warning: design_tokens.enabled is true but path" 

263 f" '{token_path}' does not exist" 

264 ) 

265 else: 

266 # ENH-1768: warn when active profile is configured but missing. 

267 profiles_dir = design_tokens.get("profiles_dir") or "profiles" 

268 active = design_tokens.get("active", "default") 

269 profiles_root = token_path / profiles_dir 

270 if profiles_root.is_dir() and not (profiles_root / active).is_dir(): 

271 warnings_out.append( 

272 "[little-loops] Warning: design_tokens.active=" 

273 f"'{active}' but '{profiles_root / active}' does not exist" 

274 ) 

275 return warnings_out