#12966: feat(logging): Add session context and breadcrumbs to error logs
stale
Cluster:
Error Handling in Agent Tools
# PR: feat(logging): Add session context and breadcrumbs to error logs
## Summary
Adds enhanced error context tracking for better debugging in multi-session and multi-agent setups. This module provides structured error context with session correlation, operation tracing, and automatic sanitization.
## Motivation
In multi-agent or multi-session deployments, errors can be difficult to trace back to their source. This feature adds:
- **Session keys** to correlate errors to specific sessions
- **Breadcrumbs** to trace the path leading to an error
- **Automatic sanitization** to safely transmit errors without leaking secrets
## Features
### Operation Context Stack
```typescript
import { pushOperation, popOperation, addBreadcrumb } from './error-context.js';
// Track operation context
pushOperation({ sessionKey: 'sess-abc123', operation: 'tool-exec', tool: 'exec' });
addBreadcrumb('Starting command execution');
addBreadcrumb('Command completed, parsing output');
// ... error occurs ...
popOperation();
```
### Contextual Errors
```typescript
import { createContextualError, formatContextualError } from './error-context.js';
const err = createContextualError('Tool execution failed', {
code: 'TOOL_EXEC_FAIL',
context: { sessionKey: 'sess-abc123', operation: 'exec' }
});
console.log(formatContextualError(err));
// Output: [sess-abc] {exec} ERR_TOOL_EXEC_FAIL Tool execution failed
// Breadcrumbs:
// [2026-02-09T00:00:00.000Z] Starting command execution
// [2026-02-09T00:00:01.000Z] Command completed, parsing output
```
### Automatic Sanitization
```typescript
import { sanitizeError, sanitizeContextualErrorForSlack } from './error-context.js';
// Redacts tokens, secret URLs, and sensitive file paths
const result = sanitizeError(new Error('Failed with token abc123...def456'));
// result.message: "Failed with token [REDACTED_TOKEN]"
// Safe for external delivery (Slack, webhooks, etc.)
const safeErr = sanitizeContextualErrorForSlack(contextualError);
```
## API
| Function | Description |
|----------|-------------|
| `pushOperation(ctx)` | Push operation context onto stack |
| `popOperation()` | Pop current operation context |
| `getCurrentOperation()` | Get current operation context |
| `clearOperationStack()` | Clear all operation contexts |
| `addBreadcrumb(message)` | Add breadcrumb to current operation |
| `sanitizeError(err)` | Sanitize error for safe transmission |
| `createContextualError(msg, opts)` | Create error with context |
| `formatContextualError(err)` | Format error for human-readable logs |
| `sanitizeContextualErrorForSlack(err)` | Sanitize contextual error for external delivery |
## Types
```typescript
type OperationContext = {
sessionKey?: string;
operation?: string;
tool?: string;
timestamp?: number;
breadcrumbs?: string[];
};
type ContextualError = {
message: string;
code?: string;
context: OperationContext;
originalError?: Error;
sanitized?: boolean;
};
```
## Benefits
1. **Debugging**: Easily correlate errors to specific sessions in multi-agent deployments
2. **Tracing**: Follow operation chains with breadcrumb trails
3. **Security**: Automatic redaction prevents secret leakage in error reports
4. **Flexibility**: Works standalone or integrates with existing logging
## Performance
- **Negligible overhead**: Simple array operations for context stack
- **No async operations**: Purely synchronous, no event loop impact
- **Memory efficient**: Breadcrumbs are timestamp-prefixed strings
## Test Coverage
16 test cases covering:
- Operation stack management (push/pop/clear)
- Breadcrumb tracking
- Token/URL/path sanitization
- Context inheritance from stack
- Formatted output generation
- Slack-safe sanitization
## Backward Compatibility
- **No breaking changes**: New standalone module
- **No dependencies**: Zero imports, self-contained
- **Optional adoption**: Consumers can gradually integrate
## Files Changed
- `src/logging/error-context.ts` - Main module (156 lines)
- `src/logging/error-context.test.ts` - Tests (189 lines)
## Branch
`feature/enhanced-error-context` based on `upstream/main`
## PR Metadata
- **Title**: feat(logging): Add session context and breadcrumbs to error logs
- **Labels**: enhancement, logging, debugging
- **Reviewers**: (maintainers)
<!-- greptile_comment -->
<h2>Greptile Overview</h2>
<h3>Greptile Summary</h3>
This PR introduces a new `src/logging/error-context.ts` module plus unit tests to support attaching session/operation context and breadcrumb trails to errors, formatting those contextual errors for logs, and sanitizing error messages/breadcrumbs for external delivery (e.g., Slack).
The module is currently standalone and not wired into any existing logging pipeline in `src/`, so its impact depends on follow-up integration. The core API (push/pop stack, breadcrumb capture, contextual error creation/formatting, and sanitization) is straightforward, but there are a couple of correctness issues around concurrency/isolation and sanitization behavior that should be addressed before merging.
<h3>Confidence Score: 2/5</h3>
- Not safe to merge as-is due to incorrect context isolation across concurrent operations.
- The module uses a process-global mutable stack for operation context, which will produce wrong/merged context in real multi-session or overlapping async usage. Additionally, sanitization behavior is currently overly broad (redacting many non-secret identifiers) and reports inconsistent sanitized status for non-Error inputs, making downstream behavior hard to trust.
- src/logging/error-context.ts
<!-- greptile_other_comments_section -->
<sub>(5/5) You can turn off certain types of comments like style [here](https://app.greptile.com/review/github)!</sub>
**Context used:**
- Context from `dashboard` - CLAUDE.md ([source](https://app.greptile.com/review/custom-context?memory=fd949e91-5c3a-4ab5-90a1-cbe184fd6ce8))
- Context from `dashboard` - AGENTS.md ([source](https://app.greptile.com/review/custom-context?memory=0d0c8278-ef8e-4d6c-ab21-f5527e322f13))
<!-- /greptile_comment -->
Most Similar PRs
#18997: fix: improve context overflow error messages and docs
by realhoratiobot · 2026-02-17
76.0%
#8312: fix: add logging and markers for tool result repair
by ekson73 · 2026-02-03
74.8%
#19923: feat: track held messages during compaction gate and split verifica...
by PrivacySmurf · 2026-02-18
74.6%
#13318: fix(agents): prevent sanitizeUserFacingText from rewriting conversa...
by hleliofficiel · 2026-02-10
74.4%
#6888: feat: PowerShell completion install/uninstall + templates script + ...
by ThinkIbrokeIt · 2026-02-02
74.3%
#13889: feat: Slack channel cache, session cost alerts & checkpoint/recover...
by trevorgordon981 · 2026-02-11
74.1%
#21446: feat(ra2): implement Context Sovereignty Layer (Phase 1)
by davyvalekestrel · 2026-02-19
74.0%
#15726: fix(sessions): use model contextWindow instead of agent contextToke...
by lailoo · 2026-02-13
73.9%
#12075: feat(browser): session-aware context isolation for multi-agent brow...
by xiaoyaner0201 · 2026-02-08
73.7%
#3647: fix: sanitize tool arguments in session history
by nhangen · 2026-01-29
73.7%