beads/internal/hooks/hooks_windows.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

78 lines
1.9 KiB
Go

//go:build windows
package hooks
import (
"bytes"
"context"
"encoding/json"
"os/exec"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"github.com/steveyegge/beads/internal/types"
)
// runHook executes the hook and enforces a timeout on Windows.
// Windows lacks Unix-style process groups; on timeout we best-effort kill
// the started process. Descendant processes may survive if they detach,
// but this preserves previous behavior while keeping tests green on Windows.
func (r *Runner) runHook(hookPath, event string, issue *types.Issue) (retErr error) {
ctx, cancel := context.WithTimeout(context.Background(), r.timeout)
defer cancel()
// Hooks are fire-and-forget so they have no parent span; we create a root span
// to track execution time and errors for observability.
tracer := otel.Tracer("github.com/steveyegge/beads/hooks")
ctx, span := tracer.Start(ctx, "hook.exec",
trace.WithAttributes(
attribute.String("hook.event", event),
attribute.String("hook.path", hookPath),
attribute.String("bd.issue_id", issue.ID),
),
)
defer func() {
if retErr != nil {
span.RecordError(retErr)
span.SetStatus(codes.Error, retErr.Error())
}
span.End()
}()
issueJSON, err := json.Marshal(issue)
if err != nil {
return err
}
cmd := exec.CommandContext(ctx, hookPath, issue.ID, event)
cmd.Stdin = bytes.NewReader(issueJSON)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Start(); err != nil {
return err
}
done := make(chan error, 1)
go func() {
done <- cmd.Wait()
}()
select {
case <-ctx.Done():
if cmd.Process != nil {
_ = cmd.Process.Kill()
}
<-done
addHookOutputEvents(span, &stdout, &stderr)
return ctx.Err()
case err := <-done:
addHookOutputEvents(span, &stdout, &stderr)
return err
}
}