Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 47 additions & 15 deletions plugin/engram/hooks/pre-tool-use.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,37 +52,69 @@ async function handlePreToolUse(ctx, input) {
return '';
}

// Build <file-context> block for systemMessage injection
let context = '<file-context>\n';
context += `# Known Context for ${escapeXmlTags(filePath)}\n`;
context += `Found ${observations.length} relevant observation(s) about this file.\n\n`;
// Separate warnings (bugfix, guidance, anti-pattern) from general context
const warnings = [];
const contextObs = [];
const warningTypes = { bugfix: true, guidance: true };
const warningConcepts = { 'anti-pattern': true, gotcha: true, 'error-handling': true, security: true };

for (const obs of observations) {
if (!obs || typeof obs !== 'object') continue;
const title = escapeXmlTags(getString(obs.title));
const obsType = escapeXmlTags(getString(obs.type)).toUpperCase();
const narrative = escapeXmlTags(getString(obs.narrative));
const obsType = getString(obs.type).toLowerCase();
const concepts = Array.isArray(obs.concepts) ? obs.concepts : [];
const isWarning = warningTypes[obsType] || concepts.some((c) => warningConcepts[c]);
if (isWarning) {
warnings.push(obs);
} else {
contextObs.push(obs);
}
}

context += `## [${obsType}] ${title}\n`;
if (narrative) {
context += `${narrative}\n`;
// Build <file-context> block for systemMessage injection
let context = '<file-context>\n';
context += `# Known Context for ${escapeXmlTags(filePath)}\n`;

// Warnings first — guardrails the agent must respect before editing
if (warnings.length > 0) {
context += `\n## WARNINGS (${warnings.length}) — review before editing\n\n`;
for (const obs of warnings) {
const title = escapeXmlTags(getString(obs.title));
const type = escapeXmlTags(getString(obs.type)).toUpperCase();
const narrative = escapeXmlTags(getString(obs.narrative));
context += `### [${type}] ${title}\n`;
if (narrative) context += `${narrative}\n`;
const facts = Array.isArray(obs.facts) ? obs.facts : [];
for (const fact of facts) {
if (typeof fact === 'string' && fact !== '') {
context += `- ${escapeXmlTags(fact)}\n`;
}
}
context += '\n';
}
}

const facts = Array.isArray(obs.facts) ? obs.facts : [];
if (facts.length > 0) {
context += 'Key facts:\n';
// General context observations
if (contextObs.length > 0) {
context += `\n## Context (${contextObs.length} observations)\n\n`;
for (const obs of contextObs) {
const title = escapeXmlTags(getString(obs.title));
const type = escapeXmlTags(getString(obs.type)).toUpperCase();
const narrative = escapeXmlTags(getString(obs.narrative));
context += `### [${type}] ${title}\n`;
if (narrative) context += `${narrative}\n`;
const facts = Array.isArray(obs.facts) ? obs.facts : [];
for (const fact of facts) {
if (typeof fact === 'string' && fact !== '') {
context += `- ${escapeXmlTags(fact)}\n`;
}
}
context += '\n';
}
context += '\n';
}
Comment on lines +77 to 113
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

There's significant code duplication in how warnings and contextObs are formatted and added to the context string. This can be refactored into a single helper function to improve maintainability and reduce redundancy. Using map() can also make the code more concise.

  const formatObservationForContext = (obs) => {
    const title = escapeXmlTags(getString(obs.title));
    const type = escapeXmlTags(getString(obs.type)).toUpperCase();
    const narrative = escapeXmlTags(getString(obs.narrative));
    let obsContext = `### [${type}] ${title}\n`;
    if (narrative) obsContext += `${narrative}\n`;
    const facts = Array.isArray(obs.facts) ? obs.facts : [];
    for (const fact of facts) {
      if (typeof fact === 'string' && fact !== '') {
        obsContext += `- ${escapeXmlTags(fact)}\n`;
      }
    }
    obsContext += '\n';
    return obsContext;
  };

  // Warnings first — guardrails the agent must respect before editing
  if (warnings.length > 0) {
    context += `\n## WARNINGS (${warnings.length}) — review before editing\n\n`;
    context += warnings.map(formatObservationForContext).join('');
  }

  // General context observations
  if (contextObs.length > 0) {
    context += `\n## Context (${contextObs.length} observations)\n\n`;
    context += contextObs.map(formatObservationForContext).join('');
  }


context += '</file-context>';

console.error(`[pre-tool-use] Injecting ${observations.length} file-context observations for ${filePath}`);
console.error(`[pre-tool-use] Injecting ${warnings.length} warnings + ${contextObs.length} context for ${filePath}`);

// Return systemMessage — no decision field needed (approve by default)
return JSON.stringify({ systemMessage: context });
Expand Down
34 changes: 34 additions & 0 deletions plugin/engram/hooks/session-start.js
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,40 @@ async function handleSessionStart(ctx, input) {
}
}

// Trigger summarization of recent unsummarized sessions (fire-and-forget).
// Stop hook doesn't fire reliably (CC bug #19225), so we summarize here instead.
// Limited to 1 session per start to avoid flooding the LLM.
if (dbSessionId) {
try {
const sessionsResp = await lib.requestGet('/api/sessions/list?limit=5', 3000);
const sessions = sessionsResp && Array.isArray(sessionsResp.sessions)
? sessionsResp.sessions
: [];

for (const sess of sessions) {
if (!sess || typeof sess.id !== 'number') continue;
// Skip current session
if (sess.id === dbSessionId) continue;
// Skip empty sessions (0 prompts)
if (typeof sess.prompt_counter === 'number' && sess.prompt_counter === 0) continue;
// Skip sessions that already have a summary
if (sess.summary && typeof sess.summary === 'string' && sess.summary.length > 0) continue;

// Fire-and-forget summarization (5s timeout)
lib.requestPost(`/api/sessions/${sess.id}/summarize`, {
lastUserMessage: '',
lastAssistant: '',
}, 5000).catch((err) => {
console.error(`[engram] session ${sess.id} summarize failed: ${err.message}`);
});
console.error(`[engram] Triggered summarization for session ${sess.id}`);
break; // Only 1 per session-start
}
Comment on lines +213 to +231
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The for loop with multiple continue statements and a break can be made more declarative and arguably more readable by using the Array.prototype.find() method. This would cleanly express the intent of finding the first session that meets all the necessary criteria for summarization.

      const sessionToSummarize = sessions.find(sess => {
        if (!sess || typeof sess.id !== 'number') return false;
        // Skip current session
        if (sess.id === dbSessionId) return false;
        // Skip empty sessions (0 prompts)
        if (typeof sess.prompt_counter === 'number' && sess.prompt_counter === 0) return false;
        // Skip sessions that already have a summary
        if (sess.summary && typeof sess.summary === 'string' && sess.summary.length > 0) return false;
        return true;
      });

      if (sessionToSummarize) {
        // Fire-and-forget summarization (5s timeout)
        lib.requestPost(`/api/sessions/${sessionToSummarize.id}/summarize`, {
          lastUserMessage: '',
          lastAssistant: '',
        }, 5000).catch((err) => {
          console.error(`[engram] session ${sessionToSummarize.id} summarize failed: ${err.message}`);
        });
        console.error(`[engram] Triggered summarization for session ${sessionToSummarize.id}`);
      }

} catch (err) {
console.error(`[engram] Unsummarized session check failed: ${err.message}`);
}
}

return contextBuilder;
}

Expand Down
Loading