fix: Refactor context hook to use proper SessionStart hookSpecificOutput format

The context hook was not appearing in Claude Code sessions because it was
outputting plain text to stdout instead of using the required JSON structure
for SessionStart hooks.

Changes:
- src/hooks/context.ts: Changed contextHook to return string instead of void,
  removing direct console.log calls to make it more reusable
- src/bin/hooks/context-hook.ts: Wrap contextHook output in hookSpecificOutput
  JSON structure with hookEventName "SessionStart" and additionalContext field
- Both TTY and stdin code paths now properly format and exit with code 0

Fixes the issue where recent session context was not being injected at session
start. Tested with npm run test:context - hook now properly outputs JSON with
recent sessions formatted as markdown.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Alex Newman
2025-10-18 21:03:57 -04:00
parent 56167c47a2
commit 5dd663730b
3 changed files with 27 additions and 15 deletions
+4 -7
View File
@@ -14,9 +14,9 @@ export interface SessionStartInput {
* Context Hook - SessionStart
* Shows user what happened in recent sessions
*
* Output: stdout is injected as context to Claude (exit code 0)
* Output: Returns formatted context string to be wrapped in hookSpecificOutput
*/
export function contextHook(input?: SessionStartInput): void {
export function contextHook(input?: SessionStartInput): string {
const cwd = input?.cwd ?? process.cwd();
const project = cwd ? path.basename(cwd) : 'unknown-project';
@@ -26,9 +26,7 @@ export function contextHook(input?: SessionStartInput): void {
const sessions = db.getRecentSessionsWithStatus(project, 3);
if (sessions.length === 0) {
// Output directly to stdout for injection into context
console.log('# Recent Session Context\n\nNo previous sessions found for this project yet.');
return;
return '# Recent Session Context\n\nNo previous sessions found for this project yet.';
}
const output: string[] = [];
@@ -138,8 +136,7 @@ export function contextHook(input?: SessionStartInput): void {
output.push('');
}
// Output directly to stdout for injection into context
console.log(output.join('\n'));
return output.join('\n');
} finally {
db.close();
}