// engine/observability/span-helpers.ts — High-level span helpers (SPEC-165)
// Provides domain-specific wrappers over the raw Tracer interface.
import { getTracer } from './tracer.js';
// ---------------------------------------------------------------------------
// Tool spans
// ---------------------------------------------------------------------------
/**
 * Starts a root span for a tool call.
 * Attributes include toolName, inputSize, and any extra attrs provided.
 *
 * Usage:
 *   const span = startToolSpan('create_spec', { projectId: 'abc' });
 *   // ... do work ...
 *   span.end('ok');
 */
export function startToolSpan(toolName, extraAttributes) {
    const attrs = {
        'tool.name': toolName,
        ...extraAttributes,
    };
    return getTracer().startSpan(`tool/${toolName}`, attrs);
}
// ---------------------------------------------------------------------------
// Spec lifecycle spans
// ---------------------------------------------------------------------------
/**
 * Starts a span representing a spec lifecycle event (e.g. status transition).
 * Intended to be used as a child of a per-spec root trace.
 *
 * @param specId  The spec identifier, e.g. "SPEC-042"
 * @param event   A lifecycle event name, e.g. "draft_to_approved"
 * @param parent  Parent span handle (the per-spec root span). May be null.
 * @param extraAttributes  Additional attributes.
 */
export function startSpecLifecycleSpan(specId, event, parent, extraAttributes) {
    const attrs = {
        'spec.id': specId,
        'spec.event': event,
        ...extraAttributes,
    };
    return getTracer().startChildSpan(`spec/${specId}/${event}`, parent, attrs);
}
// ---------------------------------------------------------------------------
// Instrumented execution helper
// ---------------------------------------------------------------------------
/**
 * Runs `fn` inside a tool span, automatically recording duration and status.
 * Returns the result of `fn`.
 * If `fn` throws, records the error on the span, ends it with 'error', then re-throws.
 */
export async function withToolSpan(toolName, fn, extraAttributes) {
    const start = Date.now();
    const span = startToolSpan(toolName, extraAttributes);
    try {
        const result = await fn(span);
        span.setAttribute('tool.duration_ms', Date.now() - start);
        span.end('ok');
        return result;
    }
    catch (error) {
        span.setAttribute('tool.duration_ms', Date.now() - start);
        const message = error instanceof Error ? error.message : String(error);
        span.recordError(message);
        span.end('error');
        throw error;
    }
}
//# sourceMappingURL=span-helpers.js.map