No slash command · from bitfab
Instrument phase of the Bitfab Setup flow. Invoked by the setup flow; not run directly
Ships in bitfab. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Mode: you were dispatched with a mode (wizard or instrument); which steps apply and where they route below depend on it.
Run only when mode is wizard or instrument.
Instrument the codebase with Bitfab tracing. Requires authentication (run Login first if needed).
Bitfab captures every AI function call, inputs, outputs, and errors, so you can see exactly what your AI is doing and discover what's going wrong. The goal is to have enough context in each trace to tell whether a call succeeded or failed, and why.
Detection and search below are mechanical: run the probes and report what you found, without narrating each command. Combine related read-only checks into one command (separate them with ;, not &&, since a no-match grep exits non-zero and would abort an && chain) and read multiple files in a single batch; adaptive follow-up greps that depend on a prior result are expected. A risk, ambiguity, or unexpected finding (unserializable inputs, a shim with lazy init, an ambiguous root) is never the narration to suppress: raise it immediately, even mid-probe.
Detect the project language (TypeScript, Python, Ruby, or Go). In a monorepo, identify which directories are applications (services, APIs, agents) vs libraries (SDKs, shared packages). Focus on application directories. The only output of this step is that language-and-framework verdict; finding the AI workflows to instrument comes later, at step 7, so a grep hit here is a framework signal, not a workflow to read and characterize. Also scan imports and package manifests for supported framework signals, and note which framework each application directory uses, step 5 fetches the matching framework page alongside the language reference:
@langchain/langgraph, @langchain/core; Python: langgraph, langchain, langchain_coredeepagents, createDeepAgent (takes precedence over LangGraph / LangChain when present); Python: deepagents, create_deep_agent (takes precedence over LangGraph / LangChain when present)@openai/agents, setTraceProcessors; Python: agents (from agents import ...)@anthropic-ai/claude-agent-sdk, query(; Python: claude_agent_sdk, ClaudeSDKClient, query(@boundaryml/baml, baml_client import; Python: baml-py, from baml_client import bai, wrapLanguageModel, streamText, generateText (TypeScript only)@earendil-works/pi-agent-core, @mariozechner/pi-agent-core, @earendil-works/pi-coding-agent (createAgentSession); instrument with getPiIntegration(key).instrument(agent) (TypeScript only)@livekit/agents (voice.AgentSession, voice.Agent); instrument the session with getLiveKitIntegration(key).instrument(session) and register runTurn({ buildSession, buildAgent }) for replay; Python: livekit-agents (from livekit.agents import AgentSession, Agent); instrument the session with get_livekit_integration(key).instrument(session) and register run_turn(build_session=..., build_agent=...) for replaySearch for existing SDK usage (withTrace, trace, withNode, node, withSpan, @span, bitfab_span, client.Span, getFunction, get_function, and the TypeScript transform/build adapter). In a monorepo, search each application directory separately: a root-level search can miss subdirectories. Classify each result as opt-out tracing, framework auto-capture, or opt-in spans. Existing spans elsewhere in the repository do not establish a house style for new instrumentation.
AskUserQuestion, listing the existing trace function keys inside the question's own text (<key> · its root function, or its handler registration site for handler-only keys), so the user picks against the actual list instead of a message scrolled above the prompt:A) Search for more workflows: find workflows that aren't traced yet (recommended) → step 3 B) I'll name the workflow to instrument: type the file, function, or directory and I read only that, no codebase scan → step 3 C) Change what an existing trace captures: adjust what one of the keys above records; type its key to go straight to it → the
setup-modifyskill
B and C are both free-text options, and this is the earliest point either answer can land. Say so in the question: they can type a workflow to instrument, or the key of an existing trace to change, instead of picking anything.
There is deliberately no "done, finish setup" option here. The user invoked setup and nothing has been instrumented this session, so an exit offered as a peer of the two real options invites them to undo the thing they just asked for. A user who genuinely wants out says so in free text, which is the last of the runtime routes below; do not manufacture a menu item for it.
Routes that are conditions rather than options:
setup-cleanup skillwithTrace / trace / withNode / node / withSpan / @span / bitfab_span / getCurrentTrace / getCurrentSpan with custom init, often named lib/bitfab.* or after a predecessor SDK such as lib/simforge.*), audit the shim before instrumenting anything new. The shim must (a) construct the SDK client (new Bitfab(...), bitfab_init(), Bitfab::Client.new, etc.) at module load, synchronously, never lazily inside the wrapped function; and (b) hand off to the SDK trace, node, or span call synchronously, with no await between the user's entry to the shim and that SDK call. Lazy or async client init (e.g. await getOrCreateTraceFunction(key) inside the wrapped body) breaks the SDK's nesting context (TypeScript AsyncLocalStorage, Python contextvars) under any parallel fan-out (Promise.all, Promise.allSettled, asyncio.gather, parallel workers): captured calls become separate top-level traces instead of nesting inside their caller. Fix the shim before instrumenting anything new. (Direct callers of the SDK with no shim already satisfy this rule, skip the audit.)Next:
wizard or instrument): invoke the setup-modify skill with the current mode (wizard or instrument), forwarding $ARGUMENTS minus the leading mode keyword (if the user typed one).wizard or instrument): invoke the setup-cleanup skill with the current mode (wizard or instrument), forwarding $ARGUMENTS minus the leading mode keyword (if the user typed one).Use the API key from the Login phase (or retrieve it now if already authenticated)
Say one line before you install anything. This is the deliberate exception to the "do not pre-announce" execution-style rule, and the only one in this phase. The workflow and application workspace are settled now. Name both, then say that you are installing the SDK and opt-out capture support and setting the API key before instrumenting that workflow. One line, nothing around it, then get on with it.
Install the SDK now. Detect the project's package manager from its manifest (pyproject.toml → uv/poetry; package.json → pnpm/npm/yarn/bun; Gemfile → bundle; go.mod → go get; requirements.txt → edit file + pip install -r) and run its canonical add command, do NOT stop to ask about version pinning, dependency groups, package publishing, or whether a supported transform adapter should be added. The user's request to instrument authorizes the dependencies and build wiring required by the selected approach. Prefer uv add/poetry add over bare pip install (bare pip install doesn't persist to pyproject.toml). In monorepos, scope to the correct workspace (e.g. pnpm add --filter <pkg>, or cd into the app directory first), running from the repo root will install into the wrong package. Install the SDK as a runtime dependency whenever instrumented code ships or executes from the package, including published libraries and CLIs. Use a development dependency only when the instrumented code is excluded from the published/runtime artifact. Then set the BITFAB_API_KEY environment variable.
Install opt-out capture support at the same time, without being asked. Never set up a TypeScript withTrace/trace root without its transform adapter. Without the adapter only the root is recorded, so a replay records and mocks nothing beneath the root, runs every read and write there for real (including against the developer's real database), and reports results that mean nothing. The SDK's missing-transform warning is not a substitute for wiring it. For TypeScript, the SDK already includes every transform adapter; do not install a second transform package. Wire the matching @bitfab/sdk/transform adapter into the actual server build before instrumenting. Inspect the build tool and use the matching documented adapter. For Next.js, wrap the existing config with @bitfab/sdk/transform/next while preserving existing wrappers such as Sentry; do not replace or bypass them. For tsup, add the @bitfab/sdk/transform/esbuild plugin to the existing tsup esbuild options. For direct Node or tsx, update the real start command to register @bitfab/sdk/transform/register. The package also ships documented adapters for Vite, Rollup, webpack, Rspack, Rsbuild, Rolldown, Bun, SWC, Babel, Nest, and the TypeScript compiler. Verify the transformed build path covers the production entrypoint, then confirm the wiring by reading back the build config or start command and finding the adapter import in it. Do not call a build unsupported until you have checked these adapters and the language guide. For Python, verify the runtime is 3.12+ before choosing trace/node. Fall back to opt-in spans only when the language/runtime or build path truly cannot support subtree capture, or when the selected root returns a live stream that opt-out tracing cannot finalize without changing behavior. A published package, a framework-generated span model, or the need to add a supported transform adapter is not a fallback reason. State the concrete technical blocker to the user and keep the whole selected call stack on one tracing surface.
Keep organization-specific keys isolated. Inspect how the selected application already names and loads Bitfab keys before changing its client initialization. A TypeScript client whose configured apiKey is missing or resolves empty falls back to BITFAB_API_KEY. If this client intentionally uses a dedicated key for another organization or environment, also set captureEnabled from the presence of that dedicated key. Never rely on an empty dedicated key to disable tracing because the fallback can send traces to the organization bound to BITFAB_API_KEY. Do not replace an existing general-purpose BITFAB_API_KEY when the application deliberately keeps these destinations separate.
Tell the user what you did. Pick the env-handling approach that fits the project's existing convention. Whatever you do, surface it explicitly: name the file (with absolute path) or mechanism you used, so the user knows where the key now lives. Do not print the key value itself. If the key landed in a .env-style file, additionally tell the user that any already-running dev server, REPL, or test runner may need a restart to pick it up, since most file watchers reload code on save but not env files.
Read the SDK reference. Fetch the dense canonical reference page first (/reference/typescript.md, /reference/python.md, /reference/ruby.md, or /reference/go.md) for every signature, type, default, and error semantic you need (initialization, withSpan / @span / bitfab_span / client.Span, the subtree primitives withTrace / trace and withNode / node in TypeScript and Python, getFunction / get_function / GetFunction / bitfab_function, SpanType, getCurrentSpan/getCurrentTrace, wrapBAML/wrap_baml). Ask the page for all three primitives by name, not just spans: the fetch returns an answer to your prompt rather than the page, so a prompt about withSpan/@span alone comes back documenting spans alone, and you will instrument without ever learning that trace (a root that captures every first-party call beneath it, no decorators) and node (naming, typing, capture, and replay-mock policy for one call inside that subtree) exist. If step 1 detected a framework in this application directory, also fetch the matching framework page; it documents the handler/processor/wrapper the SDK exposes for that framework, which is usually preferable to hand-wrapping every node/agent call with withSpan/@span: LangGraph / LangChain → /frameworks/langgraph.md (getLangGraphCallbackHandler / get_langgraph_callback_handler; in a LangChain-only project, prefer the identical aliases getLangChainCallbackHandler / get_langchain_callback_handler so the code reads naturally; Experimental (alpha) tool replay: getLangGraphIntegration / get_langgraph_integration with instrument / instrument); LangChain Deep Agents → /frameworks/deep-agents.md (getDeepAgentsIntegration / get_deep_agents_integration; Experimental (alpha) tool replay: getDeepAgentsIntegration / get_deep_agents_integration with createDeepAgent / create_deep_agent); OpenAI Agents SDK → /frameworks/openai-agents.md (getOpenAiTracingProcessor / get_openai_tracing_processor, plus the replayable run wrapper getOpenAiAgentHandler / get_openai_agent_handler (drop-in for the run call)); Claude Agent SDK → /frameworks/claude-agent-sdk.md (getClaudeAgentHandler / get_claude_agent_handler); BAML → /frameworks/baml.md (wrapBAML / wrap_baml; beneath an opt-out withTrace / trace root its calls are recorded as llm spans with no wrapBAML / wrap_baml, so add that wrapper only under opt-in withSpan / @span code, and configure one call with withNode / node() on the bound method; in TypeScript the @bitfab/sdk/transform build adapter is what records those calls, so they are recorded only once that adapter is wired into the build); Vercel AI SDK → /frameworks/vercel-ai-sdk.md (getVercelAiMiddleware); Pi agent harness → /frameworks/pi.md (getPiIntegration); LiveKit Agents → /frameworks/livekit-agents.md (getLiveKitIntegration / get_livekit_integration). Then fetch the language guide (/typescript-sdk.md, /python-sdk.md, /ruby-sdk.md, /go-sdk.md), including the Replay section for non-Go projects, for the install command, the multi-file project layout example, the BAML auto-instrumentation walkthrough, and the replay registry module template. Read the replay section upfront (not later) because step 12 reuses it to write the replay pipeline in the same cycle, and it should not re-fetch these pages. Fetch all of these as parallel WebFetch calls in a single message (they are independent URLs, so do not fetch them one at a time), or ask the user to share the pages. Do not improvise instrumentation from memory: the API has moved and guessing will produce broken code.
Instrumentation must produce a replayable trace. There are exactly two ways to get one: (1) a withTrace/trace root, or an opt-in fallback root span, has serializable inputs; or (2) the workflow runs on a supported framework integration that records a replayable root (LangGraph / LangChain, LangChain Deep Agents, OpenAI Agents SDK, Claude Agent SDK, Vercel AI SDK, Pi agent harness, or LiveKit Agents), which captures the framework's own serializable input as the root. Establish one of these before writing any instrumentation. Trace-processor integrations (OpenAI Agents SDK) are a special case: the processor auto-captures the agent run, but on its own records a root span with an empty input (verified against a live run: the OpenAI Agents agent span is the root and carries no recorded input), so the processor ALONE is NOT replayable. Pair it with its run wrapper (getOpenAiAgentHandler / get_openai_agent_handler), a drop-in for the run call that opens a keyed root carrying the run input as a serializable argument, with the processor's spans nesting underneath, which turns it into case (1). In an opt-out workflow, use a withTrace/trace root and configure descendants with withNode/node; use a hand-written withSpan/@span root only for a documented opt-in fallback.
The root exists so the replay harness can re-invoke it as a plain lambda with serialized inputs: that's what makes traces searchable (a coherent unit of behavior) and replayable (runnable against current code). The root must own its state setup, not consume a pre-built stateful object the replay registry module can't reconstruct. Frameworks are the sharpest case (LangGraph compiled graphs, Claude Agent SDK clients, LangChain chains all require constructors + special setup), but the rule generalizes to anything stateful, configured SDK clients, prepared models, cached routers, DB sessions. The root is therefore the outer workflow function that builds the framework / stateful object + invokes it + processes the output (API handler, message processor, job runner, pipeline coordinator), almost never the SDK's run() / invoke() itself. Framework handlers and processors keep their native agent, LLM, and tool spans beneath the opt-out root; their span model complements subtree capture rather than replacing it. The replay callable rebuilds the framework/stateful object around the recorded root input. Put the opt-out trace root around the application workflow boundary whenever the runtime supports it, including when the workflow is mostly one framework invocation. Use withNode/node for first-party calls that need explicit naming, typing, capture, finalization, or replay-mocking policy. Use a hand-written root span only for a documented technical fallback, and never put it beneath an opt-out trace.
Wrap the code path that runs the real workload (serves traffic, processes the actual jobs), not an entrypoint that exists only to test or explore locally. The test is role, not form: a cron-driven batch script or an ETL job is production and worth wrapping; a dev CLI or notebook that exists only to poke at the workflow is not. Instrument the real path even when you'll run it in dev to generate traces.
Hard constraint: every wrapped function's inputs and outputs must be serializable by the SDK's tracing layer so traces can be replayed. Every span input and output gets serialized into the trace using the SDK's language-native serialization (TypeScript/JSON, Python/JSON via Pydantic, Ruby/to_json, Go/json.Marshal). If a wrapped function takes live runtime objects that don't round-trip through that serialization, the trace can't be replayed, and badly-failing inputs can drop the entire span on the floor (not just garble the input field). Examples of unserializable inputs:
MediaStream, RTCPeerConnection, WebSocket, DOM refs)Request / Response, stream writers, open socketsOpenAI / Anthropic / Bedrock, configured agents, DB connection objects, HTTP agents): class instances whose internals carry circular references, function members, or platform handles all sink superjson and JSON.stringify. Watch especially for an options/config bag (e.g. options.llmProvider, ctx.db) that smuggles a live client into an otherwise-serializable signature.Unserializable OUTPUTS (live streams) are a separate case from unserializable inputs, and in the TypeScript SDK they do NOT require a refactor. A function whose inputs are serializable but which returns a live stream the caller consumes directly (a Vercel AI SDK streamText result, a ReadableStream, an SSE / streaming Response) is the common shape for chat and agent endpoints. Serializing that object as-is captures nothing replayable, and awaiting it to completion before returning would break streaming and first-byte latency. Record a drained, serializable view of the stream as the span output instead:
withSpan finalize option (withSpan(key, { type, finalize }, fn)). Keep this call stack entirely opt-in; never put this span beneath withTrace. The wrapped function returns the live stream to the caller unchanged; the span records await finalize(result) (e.g. { text, usage, toolCalls }). Pass the prebuilt finalizers.aiSdk for the Vercel AI SDK, or finalizers.readableStream for a raw ReadableStream (reading the AI SDK result's promises does not disturb the caller's stream, since it tees internally). This is purely-additive instrumentation, NOT a refactor: do it in the write-instrumentation step with no second confirmation. The trace stays replayable as long as the function's inputs are serializable. Never push the user into a structural rewrite of a streaming endpoint when finalize covers it.finalize option (@client.span(key, type=..., finalize=...)). The idiomatic, non-destructive shape is an async generator that yields its chunks (the caller still receives every chunk); finalize then receives the collected chunks and returns a serializable summary. Pass finalizers.openai_chunks for OpenAI streaming or finalizers.anthropic_events for Anthropic. Same rule: purely-additive, NOT a refactor, no second confirmation. (Python streams are single-consumer, so prefer the async-generator form over draining a returned stream object.)finalize yet): introduce a serializable completion. Trace a core that runs the turn to completion and returns { text, usage, ... }, with the streaming wired around it (the structural refactor below).Module-level dependencies (DB clients, env vars, config loaders, LLM clients) do not count when accessed via module scope or closure: replay resolves them from the app's runtime wiring instead of serializing them as span inputs. The same client passed as a function argument IS captured as input and WILL fail. The fix when an SDK client is the only unserializable piece is usually trivial: hoist it to module scope (or capture via closure) and drop it from the argument list, leaving the wrapped function's serializable args (issue, request, options-without-the-client) intact. When the natural outer boundary still has unserializable inputs after that, do one of the following before writing code:
getLangGraphCallbackHandler / get_langgraph_callback_handler, LangChain Deep Agents via getDeepAgentsIntegration / get_deep_agents_integration, OpenAI Agents SDK via getOpenAiTracingProcessor / get_openai_tracing_processor, Claude Agent SDK via getClaudeAgentHandler / get_claude_agent_handler, Vercel AI SDK via getVercelAiMiddleware, Pi agent harness via getPiIntegration, LiveKit Agents via getLiveKitIntegration / get_livekit_integration). These split into two replayability cases, do not conflate them:
getOpenAiAgentHandler / get_openai_agent_handler) does it: a drop-in for the run call that records a keyed root carrying the run input, with the processor's auto-captured spans nesting underneath. Either way, the unserializable arguments above it (live dependency objects, billing callbacks, request contexts) never enter the trace, and no decorated root function needs to exist in the app code: the replay registry module passes the key to replay() with a plain callable that re-invokes the same framework entrypoint production calls with the recorded root input plus reconstructed runtime wiring (framework config and dependencies); the SDK wraps the callable internally. Unsafe calls made by that wiring still need replay-mockable marked spans; use no-op values only for replay-only callback slots with no recorded call to mock. On SDKs that predate explicit-key replay, wrap the callable under the same key yourself (Python @bitfab.span("<key>"), TS getFunction(key).withSpan(...)). The pattern is documented in the SDK docs' Replay section (handler subsection) and wired up in step 12 11b. Never report one of these workflows as "not replayable" because no @span-decorated function exists in production code.getOpenAiAgentHandler / get_openai_agent_handler), the drop-in for the run call above, or, in a supported subtree runtime, a withTrace/trace root that takes the run input: the processor's auto-captured spans nest under that root, and replay runs against the root's serializable input. Use a hand-written span root only when opt-out is technically unavailable. Do not treat a bare processor-only trace as replayable.processTurn(transcript, context) instead of handleSession(stream, peerConnection)). This is not a refactor.finalize option above, not a structural refactor; only fall back here for streaming on Ruby/Go.)Raise this with the user in step 10 (not later); never instrument a root with unserializable inputs and try to fix it in the Replay phase.
Use the target or discovery choice already supplied in this conversation. If a target is known, read it directly; if the user already requested a scan, scan now. Ask only when the target is still unclear. - a target file, function, or directory is already known: continue → step 9
B) I'll name the target → step 9
Read the codebase to identify ALL AI workflows, every place the app makes LLM calls, runs agents, or makes AI-driven decisions. For each, find the outer workflow boundary (per the rule in step 6), and also note any meaningful work above the agent/LLM call (auth, validation, input prep, retry/orchestration loops, multi-agent coordination), alongside it (custom LLM calls outside the SDK, tools that aren't registered with the SDK, downstream services), and below it (post-processing, parsing, persistence). In supported TypeScript and Python workflows, this is the opt-out trace subtree; identify only the descendants that need explicit node policy. Only in fallback runtimes, identify the spans needed around auto-captured SDK content. Framework integrations in supported runtimes stay inside the opt-out trace subtree.
The user named a specific file, function, or directory to instrument. Read just that location and its immediate surroundings, do NOT scan the rest of the codebase. Find the outer workflow boundary there (per the rule in step 6), and note the meaningful work above the agent/LLM call (auth, validation, input prep, retry/orchestration loops, multi-agent coordination), alongside it (custom LLM calls outside the SDK, tools that aren't registered with the SDK, downstream services), and below it (post-processing, parsing, persistence). In supported TypeScript and Python workflows, this is the opt-out trace subtree; identify only the descendants that need explicit node policy. Only in fallback runtimes, identify the spans needed around auto-captured SDK content. Framework integrations in supported runtimes stay inside the opt-out trace subtree. If the location holds more than one distinct AI workflow, note each.
Present a numbered list of workflows found, ordered by value (most complex or LLM-heavy first). For each, give:
replay() with a callable that invokes the same production framework entrypoint, using a same-key wrapper only on SDKs that predate explicit-key replay; for trace processors, OpenAI Agents SDK, use the run wrapper (getOpenAiAgentHandler / get_openai_agent_handler) in place of the run call so it records a replayable keyed root that takes the run input; a bare processor over plain run() records an empty-input root and is not replayable on its own), (b) move the boundary inward to <specific inner function with serializable inputs> (recommended when no framework handler applies and an obvious candidate exists; not a refactor), or (c) refactor. Do not proceed to step 11 until the user picks one, never instrument an unserializable root. If the user picks (c), present a refactor plan, labeled as visibility (extract + export, logic unchanged) or structural (new pure-core fn), and get an explicit second confirmation before modifying code. See the "Refactor confirmation" rule below.withNode/node capture controls at the smallest sensitive first-party boundary so the call remains in the trace without recording its content. If the sensitive value is inline in the root input/output and cannot be isolated additively, state that concrete blocker before writing instrumentation.streamText result, a ReadableStream, an SSE / streaming Response), note it here. In the TypeScript and Python SDKs this is NOT a refactor: treat the streaming root as the explicit opt-in fallback, keep its selected call stack entirely opt-in, and instrument with the finalize option (TS withSpan(key, { finalize }, fn) with finalizers.aiSdk / finalizers.readableStream; Python @client.span(key, finalize=...) over an async generator with finalizers.openai_chunks / finalizers.anthropic_events), which records a serializable view while the live stream still reaches the caller (per step 6). Present it as the instrumentation approach, do not offer a structural rewrite for a streaming output when finalize covers it. On Ruby/Go, fall back to a serializable run-to-completion core.Bitfab(trace_across_threads=True); Ruby child threads, pre-created consumers, and other processes do not inherit replay interception, so move the unsafe boundary into the replay context. For TypeScript, note any synchronous unsafe span because lazy mock: "marked" cannot substitute it; the replay registry module must use mock: "all" only when freezing every matched child is acceptable, otherwise the existing boundary must already return a Promise or the workflow is not safely replayable without a behavior-changing refactor. Separately, list runtime values the replay callable must synthesize because no value exists to pass (stream writers, request/session objects, sockets, or replay-only callback slots); these are wiring, not the replay safety boundary./bitfab:setup db-snapshot (TypeScript, Python, Ruby) so replay runs against the per-trace DB branch instead. If the function only writes, or never touches the DB, say so and skip it.The description must commit to the actual scope. If the instrumentation will only auto-capture an SDK's internals, say so explicitly, do NOT use language like "complete tracing of X workflow" when the trace will only cover an SDK call's internals.
Recommend one to start with. Ask the user to pick exactly ONE workflow to instrument first. Never accept "multiple" or "all", instrumenting one workflow produces exactly one trace function with one set of code changes. If the user wants to instrument several, they will be done sequentially via the loop in step 14, one at a time.
11. Read the selected root function, its exact signature, callers, stateful dependencies, and transitive calls that already use Bitfab instrumentation. Choose a stable trace function key from the existing conventions. Preserve the real production entrypoint and caller behavior. Verify that recorded inputs can reconstruct the same root during replay; rebuild clients and framework objects inside the replay callable. For live stream outputs, use the documented finalize support and preserve streaming behavior. Read the SDK reference and use its native integration for the detected framework. If any manual span can execute beneath the selected opt-out root, plan its conversion before writing. Inspect every production caller of each span-bearing helper, not only calls reachable from the selected root. Convert a helper in place only when every caller belongs to the same opt-out surface; otherwise choose a disjoint trace boundary or stop for refactor confirmation so existing opt-in callers cannot encounter withNode. Remove a redundant span wrapper or replace it with a node while preserving its name, type, capture controls, finalizer, and replay-mocking behavior. For TypeScript, confirm every withNode target is a named function; preserve its existing name or use an additive named function form, and stop if that requires a non-additive rewrite. An existing span in this call stack does not make opt-out technically impossible. Once this is established, proceed directly to instrumentation and replay setup. Ask only if the workflow itself remains ambiguous or a non-additive application refactor is required; follow the refactor-confirmation appendix for that case.
12. Write the instrumentation edits (11a) and the replay registry module (11b) for this trace function in the same cycle. Reuse the Replay section already in context. The project owns the registry module only; the installed SDK owns the executable. For Go, 11b is the compiled registry command cmd/registry/main.go.
Delegate 11b to a subagent only when 11a is itself a large mechanical fan-out (>10 files) whose generation genuinely overlaps the registry work. The subagent must follow the same registry-only contract.
Default instrumentation policy: use opt-out tracing whenever the selected TypeScript or Python workflow supports it. TypeScript setup must configure the bundled @bitfab/sdk/transform adapter in the application build first, whether or not the user asked for it, and must find that adapter in the build config or start command before writing the root. If it is not there, go back to step 4 and wire it. Then put withTrace/trace on the existing workflow root. Python 3.12+ uses trace on the root. Let first-party descendants be discovered automatically and use withNode/node for external reads, unsafe side effects, model calls, naming, typing, capture overrides, finalization, and replay mocking. Do not add withSpan inside an opt-out trace. Existing withSpan usage is not a reason to extend the opt-in pattern. When a manual span already runs inside the selected call stack, migrate the call stack instead of abandoning opt-out. Before converting a span-bearing helper in place, inspect every production caller and confirm each caller belongs to the same opt-out surface; if an opt-in caller remains, use a disjoint trace boundary or stop for refactor confirmation. Remove redundant span wrappers. Replace spans that carry policy with nodes and preserve that policy. TypeScript withNode requires a named function, so preserve an existing name or use an additive named function form; stop for refactor confirmation if naming it requires a non-additive rewrite. This tracing-surface migration is instrumentation work, not an application refactor. Stop for refactor confirmation only if preserving application behavior requires changing the underlying function or its callers. Spans remain supported, but during setup choose them only when opt-out is technically impossible: Ruby, Go, unsupported Python runtimes, a TypeScript build path unsupported by every documented transform adapter, or a live streaming root whose output opt-out tracing cannot finalize without changing behavior. Framework integrations and their generated spans remain nested beneath the opt-out root; they do not justify a span root. Adding a supported transform adapter, including the esbuild adapter used by tsup, is required setup work rather than a fallback reason. Report the concrete technical blocker and keep the selected call stack on one tracing surface.
11a. Instrumentation edits: follow the SDK reference exactly, purely additive. Never change behavior, arguments, return values, error handling, variable names, types, control flow, or code structure. Wrapping means wrapping, not silently rewriting. Attach the opt-out trace to the existing root and configure only the discovered nodes that need policy. Rewriting, re-implementing, inlining, or hand-reconstructing a framework/SDK call to seat a root is sometimes genuinely necessary, but it is a refactor, not additive instrumentation: never do it silently as part of the write step. Any such rewrite must preserve behavior exactly (labeled visibility or structural in the refactor plan); a rewrite that would change behavior is never allowed, fall back to an additive root or move the boundary inward instead. Try the additive root first, when the natural root is opaque or stream-returning, reach for the framework handler/middleware or the finalize option wrapped around the unchanged call. If none of those fit and a rewrite really is required, STOP, present the refactor plan to the user in plain terms and get an explicit yes before touching the code (the "Refactor confirmation" rules below say what the plan must contain), then proceed once they approve. Likewise, if the additive wrap doesn't typecheck, STOP and surface it rather than dropping or loosening an argument, weakening validation, or otherwise quietly changing runtime behavior to make it compile (the same "no type-checker escape hatches, don't paper over it" rule the replay step enforces): a compile error on a purely-additive wrap means the wrap isn't additive, so either find the additive form or present it to the user as a refactor and get approval first. Batch repetitive edits into one message (many Edit calls); for large mechanical fan-outs (>10 files of the same wrapper pattern), validate the pattern on one file, then delegate the rest to a subagent. For each external read or unsafe side effect that replay must mock, configure the discovered node with replay mocking (TypeScript withNode({ type, mockOnReplay: true }, fn) / @client.node(...); Python @client.node(type=..., mock_on_replay=True)). Under opt-in fallback, put the equivalent option on the span. This lets replay's mock: "marked" strategy serve its recorded output without mixing tracing surfaces.
11b. Replay registry module: write or update the project registry (scripts/replayRegistry.ts, scripts/replay_registry.py, scripts/replay_registry.rb, or the project equivalent), grounded in the Replay section already fetched.
runX, processX, or generateX. Handler roots register a plain callable that re-invokes the same framework entrypoint production calls with an explicit trace function key.replay() (Python: client.replay("<key>", fn, ...); TypeScript: bitfab.replay("<key>", fn, opts)), and the callable re-invokes the same framework entrypoint production calls with the recorded root input. The SDK wraps the callable internally; on SDKs that predate explicit-key replay, wrap it under the same key yourself (Python @bitfab.span("<key>"), TS getFunction(key).withSpan(...)). Brief the subagent on: the production framework entrypoint + import path (e.g. the compiled graph's invoke/ainvoke, the agent run call), the recorded root-input shape (a dict root input like a LangGraph state arrives as a single positional argument on the explicit-key path; on the older same-key-wrapper path it splats into kwargs, so legacy Python wrappers take (**state)), and the runtime wiring the wrapper must construct (framework config, dependency objects). Every unsafe call made by that wiring must sit behind a replay-mockable marked span; use a no-op value only for a replay-only callback slot with no recorded call to mock. The handler-recorded production traces and the replay callable share the key and production entrypoint; never report a handler-instrumented key as not replayable.defineReplayRegistry, Python variable registry, Ruby constant REGISTRY.cmd/registry/main.go), and bitfab-replay runs from that package's directory. When the root is defined in a lower-level library and an app package calls it with tools or clients it built, the registry goes in the app package, even when the Bitfab SDK is so far installed only in the library. Add the SDK to the app package's dependencies. That is normal setup, not a refactor or an architecture change, so it needs no confirmation. Name the added dependency in the summary you give the user. Never copy the app's dependencies into the library.adaptInputs / adapt_inputs / AdaptInputs) by calling the same code production uses. If production builds them inline, extract that code into an exported function that production and the registry both call. That edits production code, so confirm it first. Show the user the function being extracted, the file it moves to, and each call site that changes, state that the logic moves unchanged, and wait for a yes before editing. Present it as a small visibility change, not an architecture change. If the user declines, stop and say that replay cannot rebuild these arguments without it.mockOnReplay / mock_on_replay / WithMockOnReplay). Tool calls recorded by a framework handler, such as the Claude Agent SDK handler's tool spans, are records only, so those tools run for real. Before any replay, list every tool the registry wires in and put each one that writes, sends, charges, or calls a paid API behind a marked span. If a tool cannot be marked because it runs where replay cannot reach it, stop and tell the user that replaying this workflow runs that tool for real.optionsFactory / options_factory only changes replay options such as mocking, never how the app builds the root. Never add a second registry entry with the setting written into it.--dry-run first. Every replay command, dry runs included, names its code change, and a wiring check has none, so pass --code-change skip. The first real replay of an unchanged trace (after the replay safety check) should take the same tool path as the original. A real replay, unlike a dry run, needs an experiment group: pass a new UUID with --experiment-group-id and a name for what it tests with --experiment-group-name. A tool the original called that the replay skips means production wiring is still missing.replay(), invokes a runner, installs lifecycle callbacks, prints output, or handles BITFAB_REPLAY_RESULT_PATH. Put the safety-audited mock strategy and input adapter on the registry entry. The SDK-installed bitfab-replay --registry <path> <pipeline> [options] command owns all common behavior.mock: "marked" output; use all only when freezing every matched child is acceptable. Python worker-thread dispatch requires trace_across_threads=True. A Ruby child-thread, pre-created consumer, or process does not inherit replay interception. Do not hand-mock DB clients or other unsafe dependencies; keep the real call behind a selected replay-mockable marked span so its recorded output is served.bitfab-replay --registry ... command. Surface signature mismatches or import side effects.Include the replay registry module in the change summary alongside the instrumented files. For a TypeScript opt-out root, also include the build config or start command that now carries the transform adapter.
13. Give the user a clear completion message that explains how to run the instrumented workflow and, once traces exist, the SDK-installed replay command with this registry. If the repository reveals an exact command or user action that drives the real instrumented path, provide it. If it does not, name the application path or workflow that must be exercised without inventing a command. Always give the exact bitfab-replay --registry ... command when a registry was created, with --experiment-group-id <new UUID> --experiment-group-name "<what the run tests>": every replay outside a dry run needs an experiment group, one series of experiments testing one thing, and a later run testing the same thing passes that group's id again. Do NOT run either command yourself. (Omit the replay command for Go-only projects.) If step 10 flagged this function as reading stored DB state (or reading the workflow at step 11 noted a captured node that reads stored database state, an external_read with readKind: db_read specifically, not an http_read / vector_search / cache_read / filesystem_read) (TypeScript, Python, Ruby), add one line: replay currently reads today's data, run /bitfab:setup db-snapshot to make it replay against the database state at trace time.
Generate the trace by driving the instrumented path, not by instrumenting a new one. If the convenient local entrypoint (a dev CLI, script, or REPL) bypasses the wrapped root and calls the inner function directly, common when prod runs behind an orchestrator (Temporal, a job/queue worker), its trace won't match production. Say so, then steer to driving the real path or rerouting the harness through the wrapped entrypoint, never add a span to a dev/test-only entrypoint just to make its trace look right.
For a TypeScript opt-out root, say where the transform adapter is wired and how to tell it ran. Name the adapter and the build config or start command that carries it. Tell the user the app must run through that build path, because a run that skips it (for example a script started without --import @bitfab/sdk/transform/register) records only the root. Tell them what to look for in the first trace: calls beneath the root. A trace that is the root alone, or a [bitfab] warning in the app log naming the root, means the transform did not run, and replays of that trace will mock nothing.
End with this required verification section. Include the transform lines only for a TypeScript opt-out root:
Replay root parity:
- Production root symbol:
- Production import/path:
- Replay symbol:
- Replay import/path:
- Same symbol? yes/no
- If no, why is this impossible?
Tracing transform (TypeScript opt-out root):
- Adapter:
- Wired in (build config or start command):
B) I'll name another target → step 9 C) Done (recommended) → the
setup-cleanupskill
Next:
wizard or instrument): invoke the setup-cleanup skill with the current mode (wizard or instrument), forwarding $ARGUMENTS minus the leading mode keyword (if the user typed one).Whenever the user picks "refactor to extract a pure core" (or any option that modifies existing functions/call sites, not just adds new wrappers), you must:
Build a refactor plan listing:
getFunction(...) / SDK trace wrap after the refactorPresent the plan verbatim to the user, in the same format above.
Use AskUserQuestion with exactly two options:
Never modify existing code on a refactor path without completing this three-step confirmation. Adding new instrumentation wrappers to unchanged functions is not a refactor and does not need this confirmation (purely-additive instrumentation). But if the write-instrumentation step itself turns out to require modifying, re-implementing, or hand-reconstructing an existing call to seat a root (the wrap is not actually additive), that IS a refactor: stop and run this three-step confirmation before touching the code.
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub project-white-rabbit/bitfab-claude-plugin --plugin bitfab19 skills in this plugin
/assistantBitfab Assistant (retired)Retired. Only use when the user explicitly types the bitfab assistant command by name; it tells them the assistant has been retired. Never use it for requests about traces, datasets, labels, verdicts, replays, experiments, or improving a traced function: handle those directly with the Bitfab MCP tools/setupBitfab SetupSet up and maintain Bitfab tracing, replay registries, and cloud replay. Use for instrumenting AI/LLM code, adding observability or evaluation, tracing another workflow, changing captured inputs/outputs, re-instrumenting a function, moving side effects across trace boundaries, inspecting missing traces, explaining Bitfab, login, organization switching, session-log consent, database snapshots, templates, or read-only repo instrumentation recommendations (analyze-repo). Also use for 'setup cloud', 'set up cloud replay', or 'replay on GitHub'. Re-enter this skill for each additional function to instrument, even after earlier setup. Do not use for improving output quality, pass rates, verdicts (labeling), or experiments (the agent does those directly with the Bitfab MCP tools), or upgrading SDK/plugin versions (use bitfab:update)