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

126 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-06-04 12:21 -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 threading 

35from pathlib import Path 

36from typing import Any 

37 

38import yaml 

39 

40from little_loops.config.core import deep_merge, resolve_config_path 

41from little_loops.config.features import feature_enabled 

42from little_loops.hooks.types import LLHookEvent, LLHookResult 

43 

44logger = logging.getLogger(__name__) 

45 

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

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

48_LARGE_CONFIG_THRESHOLD = 5000 

49 

50 

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

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

53 

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

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

56 explicit nulls survive. Not interchangeable with 

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

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

59 """ 

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

61 return {} 

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

63 if len(parts) < 3: 

64 return {} 

65 text = parts[1].strip() 

66 if not text: 

67 return {} 

68 try: 

69 loaded = yaml.safe_load(text) 

70 except yaml.YAMLError: 

71 return {} 

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

73 

74 

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

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

77 

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

79 """ 

80 del event # SessionStart consumes no payload fields today; cwd is implicit (os.getcwd()). 

81 

82 cwd = Path.cwd() 

83 feedback_lines: list[str] = [] 

84 

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

86 with contextlib.suppress(OSError): 

87 _PRIOR_SESSION_STATE.unlink() 

88 

89 # 2. Resolve base config. 

90 config_path = resolve_config_path(cwd) 

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

92 if config_path is not None: 

93 try: 

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

95 except (OSError, json.JSONDecodeError): 

96 base_config = {} 

97 

98 # 3. Apply local overrides if present. 

99 local_file = cwd / _LOCAL_OVERRIDE_FILE 

100 overrides_applied = False 

101 merged_config: dict[str, Any] = base_config 

102 if local_file.is_file(): 

103 try: 

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

105 except OSError: 

106 override_text = "" 

107 local_overrides = _parse_frontmatter(override_text) 

108 if local_overrides: 

109 merged_config = deep_merge(base_config, local_overrides) 

110 overrides_applied = True 

111 

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

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

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

115 _project_context_block = "" 

116 if config_path is not None: 

117 with contextlib.suppress(Exception): 

118 from little_loops.session_store import ensure_db 

119 

120 ensure_db(cwd / ".ll" / "history.db") 

121 

122 # ENH-1830: trigger incremental JSONL backfill in a background daemon thread 

123 # so historical session data reaches history.db without manual intervention. 

124 # All errors are suppressed so backfill failures never block session startup. 

125 _db_path = cwd / ".ll" / "history.db" 

126 

127 def _run_backfill() -> None: 

128 try: 

129 from little_loops.session_store import backfill_incremental 

130 from little_loops.user_messages import get_project_folder 

131 

132 project_folder = get_project_folder(cwd) 

133 if project_folder is not None: 

134 jsonl_files = list(project_folder.glob("*.jsonl")) 

135 backfill_incremental(_db_path, jsonl_files=jsonl_files) 

136 except Exception: 

137 logger.warning("session_start: backfill_incremental failed", exc_info=True) 

138 

139 threading.Thread(target=_run_backfill, daemon=True).start() 

140 

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

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

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

144 with contextlib.suppress(Exception): 

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

146 from little_loops.config.features import HistoryConfig 

147 from little_loops.history_reader import project_digest, render_project_context 

148 

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

150 _sd = _hist.session_digest 

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

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

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

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

155 _project_context_block = render_project_context( 

156 _digest, char_cap=_sd.char_cap, days=_sd.days 

157 ) 

158 

159 # 4. Compose the rendered stdout payload. 

160 if config_path is not None and not overrides_applied: 

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

162 try: 

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

164 except OSError: 

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

166 elif config_path is not None or overrides_applied: 

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

168 else: 

169 stdout_payload = None 

170 

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

172 if _project_context_block: 

173 if stdout_payload is not None: 

174 stdout_payload = stdout_payload + "\n\n" + _project_context_block 

175 else: 

176 stdout_payload = _project_context_block 

177 

178 # 5. Compose feedback (stderr). 

179 if config_path is not None: 

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

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

182 if overrides_applied: 

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

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

185 feedback_lines.append( 

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

187 ) 

188 else: 

189 feedback_lines.append( 

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

191 ) 

192 

193 # 6. Feature-flag validation warnings. 

194 feedback_lines.extend(_validate_features(merged_config)) 

195 

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

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

198 

199 

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

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

202 

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

204 

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

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

207 

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

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

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

211 """ 

212 warnings_out: list[str] = [] 

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

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

215 github = sync.get("github") 

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

217 warnings_out.append( 

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

219 ) 

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

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

222 categories = documents.get("categories") 

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

224 warnings_out.append( 

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

226 " configured" 

227 ) 

228 design_tokens = ( 

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

230 ) 

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

232 from pathlib import Path 

233 

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

235 if not token_path.exists(): 

236 warnings_out.append( 

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

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

239 ) 

240 else: 

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

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

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

244 profiles_root = token_path / profiles_dir 

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

246 warnings_out.append( 

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

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

249 ) 

250 return warnings_out