beads/internal/hooks/hooks.go
Pierre-Alexandre Entraygues 6e4ad9b283
feat(otel): opt-in OpenTelemetry instrumentation (#1940)
* feat(otel): comprehensive OpenTelemetry instrumentation

Phase 1 (telemetry foundation + SQL + CLI + AI):
- Add internal/telemetry package: Init/Shutdown, Tracer/Meter helpers,
  stdout + OTLP/gRPC exporters, noop providers when disabled
- Add internal/telemetry/storage.go: InstrumentedStorage decorator for
  SDK consumers with bd.storage.* counters and duration histograms
- Instrument DoltStore SQL layer (execContext, queryContext, queryRowContext)
  with dolt.exec / dolt.query / dolt.query_row spans
- Instrument Anthropic API calls in compact/haiku.go and find_duplicates.go
  with bd.ai.input_tokens, bd.ai.output_tokens, bd.ai.request.duration
- Add bd.command.<name> span in PersistentPreRun/PostRun with actor attribute

Phase 2 (VC ops, hooks, sync, metrics):
- Add dolt.commit / dolt.push / dolt.force_push / dolt.pull / dolt.branch /
  dolt.checkout / dolt.merge spans for Dolt version-control procedures
  (these bypass execContext so needed dedicated spans)
- Add bd.db.retry_count counter in withRetry (server mode retries)
- Add bd.db.lock_wait_ms histogram in AcquireAccessLock (flock contention)
- Add ephemeral.count / ephemeral.nuke spans for SQLite ephemeral store
- Add hook.exec spans in hooks_unix/windows runHook (background root spans)
- Add tracker.sync / tracker.pull / tracker.push / tracker.detect_conflicts
  spans with per-phase stats attributes in tracker/engine.go
- Add bd.issue.count gauge (by status) in InstrumentedStorage.GetStatistics
- Fix: call initAIMetrics via sync.Once in newHaikuClient so ai metrics
  are actually registered

Configuration:
  BD_OTEL_ENABLED=true              enable (default: off, zero overhead)
  BD_OTEL_STDOUT=true               write to stdout for dev/debug
  OTEL_EXPORTER_OTLP_ENDPOINT=...  ship to Jaeger/Grafana/Honeycomb/etc.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(otel): align with VictoriaMetrics HTTP stack

- Switch metric exporter: gRPC → HTTP (otlpmetrichttp)
- Activation: BD_OTEL_METRICS_URL presence (no more BD_OTEL_ENABLED flag)
  matches GT_OTEL_METRICS_URL convention from the local observability stack
- BD_OTEL_METRICS_URL=http://localhost:8428/opentelemetry/api/v1/push
- BD_OTEL_LOGS_URL=http://localhost:9428/insert/opentelemetry/v1/logs (reserved)
- Traces: stdout only (BD_OTEL_STDOUT=true); noop otherwise since VictoriaMetrics
  is a metrics-only backend — no trace overhead in production
- Remove: otlptracegrpc, otlpmetricgrpc
- Update docs/OBSERVABILITY.md to match the diffusiontown README style

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(otel): capture hook stdout/stderr and bd.args in spans

- hook.exec span now records stdout and stderr as span events after
  the hook process exits (including partial output on timeout)
- Output is truncated to 1024 bytes; the event carries both the text
  (output) and the original size (bytes) as attributes
- bd.command.<name> span now includes bd.args with the raw CLI
  arguments (e.g. "create 'title' -p 2")

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(otel): address review feedback — stale comment, span leak, hot-path alloc

1. Fix stale BD_OTEL_ENABLED comment in main.go (actual env vars are
   BD_OTEL_METRICS_URL and BD_OTEL_STDOUT)
2. Use defer+named returns in Merge() to prevent span leaks
3. Cache doltSpanAttrs() via sync.Once to avoid per-call allocation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: beads/crew/emma <steve.yegge@gmail.com>
2026-02-22 15:36:57 -08:00

136 lines
3.2 KiB
Go

// Package hooks provides a hook system for extensibility.
// Hooks are executable scripts in .beads/hooks/ that run after certain events.
package hooks
import (
"os"
"path/filepath"
"time"
"github.com/steveyegge/beads/internal/types"
)
// Event types
const (
EventCreate = "create"
EventUpdate = "update"
EventClose = "close"
)
// Hook file names
const (
HookOnCreate = "on_create"
HookOnUpdate = "on_update"
HookOnClose = "on_close"
)
// Runner handles hook execution
type Runner struct {
hooksDir string
timeout time.Duration
}
// NewRunner creates a new hook runner.
// hooksDir is typically .beads/hooks/ relative to workspace root.
func NewRunner(hooksDir string) *Runner {
return &Runner{
hooksDir: hooksDir,
timeout: 10 * time.Second,
}
}
// NewRunnerFromWorkspace creates a hook runner for a workspace.
func NewRunnerFromWorkspace(workspaceRoot string) *Runner {
return NewRunner(filepath.Join(workspaceRoot, ".beads", "hooks"))
}
// Run executes a hook if it exists.
// Runs asynchronously - returns immediately, hook runs in background.
func (r *Runner) Run(event string, issue *types.Issue) {
hookName := eventToHook(event)
if hookName == "" {
return
}
hookPath := filepath.Join(r.hooksDir, hookName)
// Check if hook exists and is executable
info, err := os.Stat(hookPath)
if err != nil || info.IsDir() {
return // Hook doesn't exist, skip silently
}
// Check if executable (Unix)
if info.Mode()&0111 == 0 {
return // Not executable, skip
}
// Run asynchronously (ignore error as this is fire-and-forget)
go func() {
_ = r.runHook(hookPath, event, issue) // Best effort: hook failures should not block the triggering operation
}()
}
// RunSync executes a hook synchronously and returns any error.
// Useful for testing or when you need to wait for the hook.
func (r *Runner) RunSync(event string, issue *types.Issue) error {
hookName := eventToHook(event)
if hookName == "" {
return nil
}
hookPath := filepath.Join(r.hooksDir, hookName)
// Check if hook exists and is executable
info, err := os.Stat(hookPath)
if err != nil || info.IsDir() {
return nil // Hook doesn't exist, skip silently
}
if info.Mode()&0111 == 0 {
return nil // Not executable, skip
}
return r.runHook(hookPath, event, issue)
}
// HookExists checks if a hook exists for an event
func (r *Runner) HookExists(event string) bool {
hookName := eventToHook(event)
if hookName == "" {
return false
}
hookPath := filepath.Join(r.hooksDir, hookName)
info, err := os.Stat(hookPath)
if err != nil || info.IsDir() {
return false
}
return info.Mode()&0111 != 0
}
// maxOutputBytes is the maximum number of bytes captured from hook stdout/stderr
// before truncation. Keeps span attributes reasonably sized.
const maxOutputBytes = 1024
// truncateOutput truncates hook output to maxOutputBytes, appending a note when truncated.
func truncateOutput(s string) string {
if len(s) <= maxOutputBytes {
return s
}
return s[:maxOutputBytes] + "... (truncated)"
}
func eventToHook(event string) string {
switch event {
case EventCreate:
return HookOnCreate
case EventUpdate:
return HookOnUpdate
case EventClose:
return HookOnClose
default:
return ""
}
}