[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79FNA3MSFZJJEY8K32KJ7VG":3,"skill-same:01M79FNA3MSFZJJEY8K32KJ7VG":49},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":26,"commitSha":27,"skillDirectory":28,"forksCount":29,"repositoryHtmlUrl":30,"repositoryHomepageUrl":31,"ownerHtmlUrl":32,"ownerBlogUrl":33,"ownerDescription":6,"updatedAt":34,"install":35,"resources":48},"01M79FNA3MSFZJJEY8K32KJ7VG","tracing-instrument",null,"Add structured `tracing`-crate instrumentation (spans + events + fields) to Penca Rust code — one combined plan emitted as kata tasks under `cha-NNN plan-draft` and gated once by `\u002Fplan-reviewer`, then one branch carrying every site as its own commit drained from the approved kata queue, gated once by `just check` at PR open. Scope is the `tracing` crate only (logs-as-events + spans); metrics and OpenTelemetry are out of scope. Use for observability tickets, ad-hoc instrumentation passes on a crate, or as the `\u002Fdo-issue` `orch:run-cleanup` cleanup-context pass.","penca-io\u002Fpenca","penca-io","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F294652540?v=4","01M79FKD3WVDHQXKBT43KMQFPR","Penca","01M79FKD4JJK7894AKV1R7RHTR",8,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fpenca-io\u002Fpenca\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Ftracing-instrument\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: tracing-instrument\ndescription: Add structured `tracing`-crate instrumentation (spans + events + fields) to Penca Rust code — one combined plan emitted as kata tasks under `cha-NNN plan-draft` and gated once by `\u002Fplan-reviewer`, then one branch carrying every site as its own commit drained from the approved kata queue, gated once by `just check` at PR open. Scope is the `tracing` crate only (logs-as-events + spans); metrics and OpenTelemetry are out of scope. Use for observability tickets, ad-hoc instrumentation passes on a crate, or as the `\u002Fdo-issue` `orch:run-cleanup` cleanup-context pass.\nargument-hint: \"[--in-cleanup-context cha-NNN] \u003Cscope>\"\nallowed-tools: Read Grep Glob Bash WebFetch Write Edit Skill mcp__language-server__definition mcp__language-server__references mcp__language-server__hover mcp__language-server__diagnostics\n---\n\n# Tracing instrument\n\nAdd structured `tracing`-crate instrumentation to Penca Rust code through a two-phase gated loop: **Plan** (one combined mechanism-bound plan covering every site the walk surfaces, emitted as kata tasks under `cha-NNN plan-draft`, gated once by `\u002Fplan-reviewer` to `APPROVED`) → **Execute** (one branch per batch, each site drained from `kata ready --label cha-NNN --label approved` and landed as its own commit, gated once by `just check` at PR open).\n\nEvery site is named against one of three reference exemplars (tokio `#[instrument]`, tower-http `TraceLayer`, sqlx query spans) so the *shape* the instrumentation moves toward is explicit, not vibes.\n\n**Single-PR default.** Every site the walk surfaces lands in **one batch, one branch, one PR**. Do not pre-split the batch into multiple PRs as a stylistic choice — the plan+review cycle is the expensive step, and one combined plan is cheaper for the reviewer than N serial plans with hidden cross-site dependencies. Split into multiple batches only when the scope is truly enormous — rule of thumb, ~20+ sites spanning unrelated module trees that no reviewer would sensibly evaluate as a single change. When in doubt, keep it one PR. Scope pruning (dropping a site the user doesn't want) happens during `\u002Fplan-reviewer` iteration by deleting the task from the kata queue, not pre-emptively at walk time.\n\n## When to use this skill\n\nThree invocation modes; see \"Invocation modes\" below for how the contract differs across them:\n\n- **Ad-hoc instrumentation pass** on a crate or binary — no ticket required. The plan goes through `cha-NNN plan-draft` → human-approval → drain on an instrument-themed branch.\n- **In-ticket instrumentation** during an observability ticket's implementation phase, when `\u002Fdo-issue` (or you) hands off to this skill. Same contract as ad-hoc, but scoped to a Linear `cha-NNN`.\n- **In-cleanup-context pass** invoked by `\u002Fdo-issue`'s `orch:run-cleanup` orchestration task on a non-instrumentation ticket. The cleanup-context contract is auto-approve after `\u002Fplan-reviewer` `APPROVED` (no human TUI step) and skip Phase 2 (the outer `\u002Fdo-issue` `\u002Floop` drains).\n\nIf you're driving a Linear ticket through its full lifecycle (status → In Progress, plan-on-ticket, PR with `Closes CHA-XX`, post-merge cleanup), **start with `\u002Fdo-issue`** — it handles ticket mechanics and hands off to this skill when the ticket's core ask is \"instrument X\" with no functional behavior change. `\u002Fdo-issue` retains the ticket-mechanics steps; this skill replaces the plan + implement steps for instrumentation work.\n\nDo **not** use this skill for:\n- Adding metrics (`metrics` crate, Prometheus exporters) — out of scope until Penca adopts a metrics stack.\n- Adding OpenTelemetry \u002F distributed-tracing exporters — out of scope until Penca adopts an exporter.\n- Refactoring code that happens to touch existing log sites — that's `\u002Fclean-code-refactor` work. Instrumentation passes are behavior-additive: existing logs are not rewritten unless they violate a grounding principle below.\n- Functional behavior changes, bug fixes, or new features — those are `feat:` \u002F `fix:` work; route through `\u002Fdo-issue` normally.\n- Subscriber \u002F pipeline configuration changes (env-filter defaults, formatter swaps) — those are infra concerns, handled outside this skill.\n\n## Invocation modes\n\nThe Phase-1 walk + `\u002Fplan-reviewer` gate is identical across all three modes. The differences are at the gate and in Phase 2.\n\n| | Ad-hoc \u002F in-ticket instrumentation (default) | **In-cleanup-context** (`--in-cleanup-context cha-NNN`) |\n|---|---|---|\n| Phase-1 emit label | `cha-NNN plan-draft` | `cha-NNN plan-draft cleanup-pass` |\n| `\u002Fplan-reviewer` gate | runs to APPROVED | runs to APPROVED |\n| Post-APPROVED label swap | **human** flips `plan-draft` → `approved` in `kata tui` (or via `\u002Fdo-issue` Step 3 bulk-approve) | **skill** auto-flips `plan-draft` → `approved` — no human gate |\n| `orch:open-pr` blocker extension | n\u002Fa (no orch task exists) | every new task `kata edit`'s `orch:open-pr` to add the new task as a `--blocked-by` |\n| Phase 2 (drain) | this skill drives the drain on its own branch | **skipped** — control returns to the outer `\u002Fdo-issue` `\u002Floop`, which drains via its uniform consumer |\n\nIn-cleanup-context invocation: `\u002Ftracing-instrument --in-cleanup-context cha-NNN \u003Ctouched-files-or-scope>`. Detect the flag before walking; the rest of the skill behaves the same up to the gate.\n\n## Grounding principles\n\nThe principles below are inlined here intentionally — this skill is a durable artifact and must remain self-sufficient.\n\n1. **Spans bracket units of work; events record facts.** A span has a start and an end and captures everything inside as context (timing, nested spans, fields-in-scope). An event is a point-in-time fact emitted inside (or outside) a span. Do not event-log what a span should bracket. Do not span-wrap a single emit.\n2. **Structured fields, never formatted strings.** `tracing::info!(query_id = %id, rows = n, \"query complete\")`, not `info!(\"query {} returned {} rows\", id, n)`. Fields are filterable, indexable, and machine-readable; format strings are none of those. The trailing static message is the *event name*, not a place to interpolate.\n3. **Span and event names are static literals.** `tracing` macro names must be string literals — dynamic strings defeat the macro-time optimization, break most exporters' aggregation, and silently downgrade your spans. Put dynamic values in fields.\n4. **Levels carry semantics; default to `debug`.** `error` = the operation cannot continue \u002F a contract was violated. `warn` = degraded but recoverable \u002F unexpected but handled. `info` = lifecycle events at a boundary (RPC handler entry, startup\u002Fshutdown, scheduler tick). `debug` = per-operation detail useful when investigating. `trace` = inside-the-loop noise that is normally filtered. A new site defaults to `debug` unless it crosses a service boundary or represents a failure.\n5. **Instrument at boundaries, not at every callsite.** Public async fns on RPC servicers, IO operations, transaction commits, scheduler ticks, lifecycle phase transitions. Pure internal helpers inherit the caller's span — adding `#[instrument]` there is noise and inflates exporter cardinality.\n6. **One `#[instrument]` per boundary fn, with explicit `skip` and `fields`.** `#[instrument(skip_all, fields(req_id = %req.id, kind = ?req.kind), err)]`. The default macro behavior logs every argument by `Debug`, which is noisy and can leak data. **Use** `skip_all` **(not** `skip(specific_args)`**)** so every surfaced field comes from the explicit `fields(...)` list; this is the only form that catches the case where an arg is reused as a field source (e.g. `fields(schema = %name)` would otherwise auto-record `name` as a duplicate Debug field on top of the explicit `schema` field).\n7. **Errors are logged once, at the boundary they cross out.** Library code returns `Result`; the binary \u002F RPC handler logs at the point the error becomes user-visible. `#[instrument(err)]` does this for you at the function boundary; do not also `tracing::error!` inside the function for the same path. Double-logging an error is worse than not logging it — it inflates alert volume and breaks dedup.\n8. **No PII, secrets, or unbounded blobs in fields.** Names, emails, tokens, raw query bodies that may contain user data, multi-MB payloads. Use `skip(...)` and emit a derived non-identifying summary (length, hash prefix, kind) instead. When in doubt, skip.\n9. **No `println!` \u002F `eprintln!` in library code.** Always `tracing` events. `println!` is fine in CLI binaries that produce user-facing stdout output, and `eprintln!` is fine for top-level binary panics before the subscriber is initialized — but inside `crates\u002F*\u002Fsrc\u002Flib.rs` and its descendants, the answer is always a `tracing` event.\n10. **Subscriber init lives in `main`, never in a library.** Libraries emit; binaries decide where the emissions go. Each binary entry point owns its `tracing_subscriber` setup. The skill does not touch subscriber initialization unless explicitly invoked for an init-site fix.\n11. **One commit per coherent site.** A \"site\" is one boundary fn + its enclosed events, or one previously-unstructured log site converted to structured form. Do not bundle \"instrument scheduler tick\" and \"instrument query planner\" into one commit — they read separately and may need to be reverted separately.\n12. **No semantic change inside an instrumentation commit.** Adding a span, adding `#[instrument]`, restructuring a `tracing::warn!` from format-string to fields — all behavior-preserving (in the functional sense). If the change would alter control flow or returned values, record it as a \"spin into own ticket\" finding and stop — do not bundle.\n13. **Route through `just` recipes, never bare `cargo`.** `just cargo-check`, `just cargo-test`, `just cargo-fmt`. Bare `cargo` skips the workspace's pinned flags.\n14. **Every instrumentation batch goes on its own branch — one batch per invocation by default.** One *batch* per branch (the full set of sites in the approved Phase-1 plan, or the single site from an ad-hoc invocation), each site landed as its own commit on the batch branch. Default to **one batch = one PR for the entire approved set**; only split into multiple batches when the scope is truly enormous (rule of thumb: ~20+ sites spanning unrelated module trees). The branch lifecycle is part of the contract, not a convenience.\n15. **Iterate kata task bodies in place via `kata edit \u003Cref> --body \"$(cat \u003Cbody-file>)\"`** (`kata edit` has no `--body-file`\u002F`--body-stdin` — those are `kata create`-only flags)**.** Phase-1 iteration with `\u002Fplan-reviewer` updates the relevant task bodies — no new tasks per REVISE pass. (The exception is when `\u002Fplan-reviewer` returns `REVISE` because a site is missing entirely — emit a new task with `--label cha-NNN --label plan-draft`.)\n\nIf you need conventions you don't already have in context, read `docs\u002Fstyle-guide.md` and `docs\u002Fdevelopment-methodology-guide.md` on demand.\n\n## Operational shape\n\nTwo sequential phases. Each phase produces an artifact the next phase reads — no implicit hand-offs, no shortcuts between phases.\n\n### Phase 1 — Plan (one combined batch plan, gated by `\u002Fplan-reviewer`)\n\nWalk the chosen scope (a crate, a module, a binary; or in cleanup-context mode, the touched-files list `\u002Fdo-issue` passes). Identify instrumentation sites against the principles above. Emit **one kata task per site**, all under `cha-NNN plan-draft` (and `cleanup-pass` as an additional source label when invoked in `--in-cleanup-context` mode). The set of tasks *is* the plan; the `\u002Fplan-reviewer` pass *decides* — if a site should not land, the user (or `\u002Fplan-reviewer`) calls it out during review and the task is dropped from the queue via `kata delete`. Do not self-censor sites pre-emptively at walk time.\n\nWhen invoked **standalone with no ticket**, use a per-invocation scope label of the user's choosing (e.g. `tracing-penca-lifecycle-2026-05-28`) in place of `cha-NNN`; the kata queue is still the source of truth.\n\nTypical sites a Phase-1 walk surfaces:\n\n- **Missing boundary spans** — public async fns on RPC servicers, scheduler entry points, IO operations that lack `#[instrument]`. Lens: tower-http `TraceLayer` for the outermost handler; tokio `#[instrument]` for inner async fns.\n- **Silent error sites** — `Result` returned from a boundary fn with no `#[instrument(err)]` and no caller-side log. Lens: tokio `#[instrument(err)]`.\n- **Format-string logs** — `info!(\"query {} returned {}\", id, n)` that should be `info!(query_id = %id, rows = n, \"query complete\")`. Lens: sqlx structured-field events.\n- **`println!` \u002F `eprintln!` in library code** — direct violations of principle #9.\n- **Over-instrumented hot loops** — `info!` inside a tight per-row loop that should be `trace!` or moved to a span field aggregated at loop exit.\n- **Unstructured spans** — spans created with `tracing::info_span!(\"name\")` with no fields, where the natural fields (request id, key, count) are right there at the callsite.\n\nFor each site, the kata task names (in the task body — title is one line summarizing the change):\n\n- `crate\u002Fpath\u002Ffile.rs:LINE` — the symbol or block.\n- **Site category** — one of the bullets above (or a justified new one).\n- **Lens applied** — tokio-instrument \u002F tower-http-trace-layer \u002F sqlx-query-span (see \"Reference exemplars\" below).\n- **Span name + field list** — the static literal span\u002Fevent name and the explicit `(field = %value, …)` list. PII gates from principle #8 must be called out per-site if the natural fields would carry user data.\n- **Level + justification** — which of `error`\u002F`warn`\u002F`info`\u002F`debug`\u002F`trace`, with the one-sentence reason tied to principle #4.\n- **Behavior-preservation note** — confirm the change is additive only (no control-flow or return-value changes). If a site cannot be done additively, mark it \"spin into own ticket\" and exclude from the batch.\n- **Inter-site dependencies** — anything earlier sites must do first (e.g. \"depends on #2's `#[instrument]` on the outer fn being in place so this site's nested span has a parent\"). Encode with `kata create --blocked-by \u003Cearlier-task-ref>` so the drain loop respects ordering.\n\nBatch-level meta (kept in one **batch-summary task** with `--label cha-NNN --label plan-draft --label batch-summary`):\n\n- One paragraph naming the scope, the sites included (qualified-ids), the execution order with one-line justifications. The `--blocked-by` graph captures the ordering at the task level; the summary is for the human reviewer.\n- **Batch-level gate** — `just check` exits 0 *after the last site is committed*; no semantic change in any commit; per-site atomicity (one commit per site, no bundling).\n\n**Invoke `\u002Fplan-reviewer` once** on the kata task set (`kata list --label cha-NNN --label plan-draft --json`). Iterate on `REVISE` items by editing the relevant task bodies via `kata edit \u003Cref> --body \"$(cat \u003Cbody-file>)\"` — no new tasks per pass. Re-invoke until the verdict is `APPROVED`.\n\n#### Self-audit before posting\n\nBefore invoking `\u002Fplan-reviewer`, audit the combined plan for:\n\n- **Nested-span field consistency.** When the plan instruments two or more spans on the same operation path (e.g. a planning span on the public fn + an IO span on a Stream \u002F Future the fn returns), every field name that appears in both spans must carry the same identifier type and value-format. Field name across nested spans = same kind of value, full stop. If two spans both need a `catalog` field but at one site only the UUID is available and at the other only the name, *use different field names* (`catalog_uuid` vs `catalog_name`) — never let the same field name carry different types across spans on the same op.\n\n**Hard stop:** no code edit happens before `\u002Fplan-reviewer` returns `APPROVED`. If three rounds fail to converge, halt and surface to the user.\n\n#### In-cleanup-context post-APPROVED handling\n\nWhen invoked with `--in-cleanup-context cha-NNN`, `\u002Fplan-reviewer` itself auto-flips `plan-draft` → `approved` on every cleanup-pass task and extends `orch:open-pr`'s `--blocked-by` after returning `APPROVED` (see `\u002Fplan-reviewer`'s \"Post-APPROVED — cleanup-pass auto-flip\" section). This skill does **no** post-APPROVED handling — return control to the caller (the outer `\u002Fdo-issue` `\u002Floop`); **skip Phase 2 entirely** — the outer drain claims and processes the now-approved cleanup-pass tasks via its uniform consumer.\n\n### Phase 2 — Execute (one branch per batch, drain from kata)\n\nPhase 2 runs only for the ad-hoc and in-ticket instrumentation modes. **In-cleanup-context mode skips Phase 2** — the outer `\u002Fdo-issue` `\u002Floop` is the drain.\n\nOnly after Phase 1 returns `APPROVED` *and* the user has flipped each task's label `plan-draft` → `approved` (in `kata tui`, or via the bulk-approve helper from `\u002Fdo-issue` Step 3).\n\n1. **Create the branch** via `git checkout -b \u003Cbranch>` from the repo root — one branch for the entire batch; name it after the batch theme (e.g. `nhobin219\u002Fcha-XYZ-instrument-lifecycle-scheduler`), not any single site.\n\n2. **Drain the approved kata queue.** The `--blocked-by` edges from Phase 1 give the execution order for free:\n   ```bash\n   while true; do\n     ref=$(kata ready --unowned --label cha-NNN --label approved --json | jq -r '.issues[0].qualified_id \u002F\u002F empty')\n     [ -z \"$ref\" ] && break\n     kata claim \"$ref\"\n     # ...apply the additive instrumentation change from the task body...\n     git commit -m \"chore(\u003Cscope>): instrument \u003Csite>\n\nCHA-XX\n\"\n     kata close \"$ref\" --done --commit \"$(git rev-parse HEAD)\"\n   done\n   ```\n   The change must match the task body's named span\u002Fevent name, fields, and level. If implementation reveals a structural blocker not in the task (e.g. the boundary fn is generic over a non-`Debug` type, blocking the planned field), halt and return to Phase 1 for that site — no silent substitution.\n\n   Commit as `chore(\u003Cscope>): instrument \u003Csite>` (default) or `feat(\u003Cscope>): add \u003Cthing> instrumentation` (only when the new visibility is the user-facing point of the change — e.g. enabling a new dashboard). **One commit per site; no bundling, no semantic change.** Intermediate gaps in instrumentation between commits are fine — the PR gate runs once at the end.\n\n3. **PR gate** — after the last site is committed, `just check` must exit 0 once before opening the PR. This is the project-wide gate that mirrors CI; it is a strict superset of `just cargo-check` (`lint` + `format-check` + `test` + `static-test` + `cargo-check`). The batch's atomicity is \"all commits green together\"; per-site gates are out.\n\n4. **Open the PR** with a title naming the batch theme and a body listing each commit's site with a one-line summary. After merge, sync main and delete the branch: `git checkout main && git pull && git branch -d \u003Cbranch>`.\n\n### Subagent default — single-agent, main session\n\nThis skill executes in the **main conversation** with no `Agent`-tool fan-out. Spawning a subagent (parallel Phase-1 walks across crates, parallel Phase-2 branches, etc.) requires **explicit in-session user authorization** — not just plan-time justification. The single-agent default exists because the project's review-loop discipline (`\u002Fplan-reviewer`, `\u002Fcode-quality-reviewer`) is built around one author per change; parallel subagent runs split that discipline across contexts that cannot see each other's findings.\n\n## Reference exemplars\n\nThree canonical shapes from the `tracing` ecosystem. Every Phase-1 site names which lens applies; every Phase-1 plan justifies the chosen lens.\n\n### tokio `#[instrument]` — span-per-async-fn at internal boundaries\n\n[`tokio\u002Fsrc\u002Fruntime\u002Fscheduler\u002Fmulti_thread\u002Fworker.rs`](https:\u002F\u002Fgithub.com\u002Ftokio-rs\u002Ftokio\u002Fblob\u002Fmaster\u002Ftokio\u002Fsrc\u002Fruntime\u002Fscheduler\u002Fmulti_thread\u002Fworker.rs) (fetch with `WebFetch` for the latest shape — search for `#[instrument]` and `tracing::`).\n\n`#[instrument]` brackets an async fn in a span whose lifetime matches the future's. Default behavior logs all args by `Debug`; tokio's usage overrides this aggressively: `skip(self, ...)`, explicit `fields(...)`, and `err` \u002F `ret` only where the return matters.\n\n**Operational insight:** the macro is the right tool for inner boundary fns — the span is created lazily, the field set is fixed at compile time, and the lifetime exactly matches the future. The wrong tool for hot inner-loop fns (every invocation allocates a span) and for fns that take large\u002Fsensitive args without `skip`.\n\n**When to apply this lens:** a candidate is an async fn at an internal boundary (one layer below an RPC handler, an IO operation, a scheduler tick subroutine) and currently has no span. Add `#[instrument(skip(...), fields(...), err)]` matching the plan's named fields and level.\n\n### tower-http `TraceLayer` — span-per-request at the service boundary\n\n[`tower-http\u002Fsrc\u002Ftrace\u002Fmod.rs`](https:\u002F\u002Fgithub.com\u002Ftower-rs\u002Ftower-http\u002Fblob\u002Fmain\u002Ftower-http\u002Fsrc\u002Ftrace\u002Fmod.rs) (fetch with `WebFetch` for the latest shape).\n\n`TraceLayer` is a `tower::Layer` that wraps a service and creates one span per request, with hooks for `make_span_with`, `on_request`, `on_response`, `on_failure`. Works with tonic (which is `tower`-based) the same way it works with axum.\n\n**Operational insight:** the outermost boundary of an RPC server is a `tower::Service`, not a Rust async fn — adding `#[instrument]` to a handler is one layer too deep. The request-lifecycle span (start, end, status, latency) belongs at the layer where the request first appears. Inner handlers get their own narrower `#[instrument]` spans nested inside.\n\n**When to apply this lens:** the scope is a tonic gRPC server (or any tower-based service) with no per-request span. Install `TraceLayer` at the server builder, then narrow with `#[instrument]` on the inner handlers.\n\n### sqlx query spans — structured-field events for fine-grained operations\n\n[`sqlx-core\u002Fsrc\u002Flogger.rs`](https:\u002F\u002Fgithub.com\u002Flaunchbadge\u002Fsqlx\u002Fblob\u002Fmain\u002Fsqlx-core\u002Fsrc\u002Flogger.rs) (fetch with `WebFetch` for the latest shape — search for `tracing::event!` and `QueryLogger`).\n\nEach query gets a span with `db.statement`, `db.system`, `rows_affected`, `rows_returned` as structured fields, emitted at a level chosen by latency (slow queries log warn; normal queries log debug). Field names follow OpenTelemetry semantic conventions even though sqlx doesn't ship OTel exporters.\n\n**Operational insight:** when a single operation has natural metadata (query id, key, count, duration, kind), the right shape is one span per operation with those metadata as fields — not one event per phase of the operation. Aggregate inside the span; emit one summary event at completion. The field names matter: `rows`, `query_id`, `req_id`, `kind` are reusable across collectors; `n`, `x`, `the_thing` are not.\n\n**When to apply this lens:** a candidate is a per-operation site (a query, a write, a lifecycle phase) that currently logs in pieces with format strings. Replace with one span per operation, structured fields for the metadata, and one summary event at the end.\n\n**Note on tracing 0.1 + Streams.** `tracing` 0.1 provides `Instrumented\u003CF>: Future` but not `Instrumented\u003CS>: Stream` — `.instrument(span)` on a `Stream` requires the (maintenance-mode) `tracing-futures` 0.2 crate with the `futures-03` feature. The workspace already pulls in `tracing-futures = \"0.2\"` via [CHA-310](https:\u002F\u002Flinear.app\u002Fchapala\u002Fissue\u002FCHA-310), so reach for `.instrument(span)` on streams freely; see [CHA-322](https:\u002F\u002Flinear.app\u002Fchapala\u002Fissue\u002FCHA-322) for the eventual removal path once `tracing` 0.2 absorbs Stream instrumentation. Considered-and-rejected alternative: `.instrument(span)` on the inner Future that produces the stream — closes the span before any streaming, captures only the handshake, misses streaming duration + mid-stream errors.\n\n### Lens routing — the three questions\n\nFor every site, answer:\n\n| | tokio `#[instrument]` | tower-http `TraceLayer` | sqlx query span |\n| --- | --- | --- | --- |\n| Where does the span begin? | at the macro-annotated fn entry | at the service layer, before the handler | at the operation start (manual `info_span!`) |\n| What's the natural lifetime? | the future | the request | the operation |\n| What populates the fields? | macro `fields(...)` + `skip(...)` | layer hooks (`make_span_with`, `on_response`) | callsite (`span.record(...)` as values become known) |\n\nIf a site fails all three (it's not a fn boundary, not a service boundary, and not a discrete operation), it is probably an *event*, not a span — emit a structured event at the appropriate level and move on.\n\n### Stream instrumentation convention\n\n`#[instrument]` doesn't attach cleanly to non-async fns that return a `Stream` — the work happens lazily inside the `async_stream::try_stream!` body, not in the fn call, and the `tracing` crate's `Instrument` trait only covers `Future`, not `Stream`. Two shapes, by what the site needs:\n\n- **Stream-level span (preferred when timing is wanted)** — create a `debug_span!` with counter fields declared `tracing::field::Empty`, attach it to the stream via `tracing_futures::Instrument`, accumulate counters in the body, and `Span::current().record(...)` them at end-of-stream (CHA-417). With `PENCA_SPAN_TIMING` the span-close line carries busy\u002Fidle for the whole stream lifetime. An errored or cancelled stream still closes the span with timing but leaves the counters unrecorded — a timed close with no counts reads as \"aborted\", not \"zero rows\". When the span wraps a *new* pass-through stream layer (rather than a pre-existing block), gate the wrapper on `span.is_disabled()` so the disabled path stays zero-cost.\n- **Bracket \u002F constructed events (fallback when a span is overkill)** — manual `tracing::debug!` events using one of two name patterns: **`\"\u003Cfn> start\"` \u002F `\"\u003Cfn> complete\"`** when the fn owns the stream body (partial-drop traces show start without complete — the operator-visible early-cancellation signal, not a bug), or **`\"\u003Cfn> constructed\"`** fire-and-yield when the fn builds a SQL string + delegates to a deeper streaming primitive without owning the cursor (cursor-lifecycle visibility comes from the downstream site).\n\nUse the full fn name in the span\u002Fevent literal, not an abbreviation — keeps names self-locating from a log grep. Field-set PII gates are identical to `#[instrument]` boundaries (principle #8).\n\nIn-repo precedent: `crates\u002Fpenca-storage-hot\u002Fsrc\u002Fquery.rs::stream_query_as_batches` carries the stream-level span (as do the response-stream siblings `ipc_encode` in `penca-server-grpc\u002Fsrc\u002Fipc.rs` and `flight_encode` in `penca-sql-server\u002Fsrc\u002Fflight_sql\u002Fservice.rs` — the latter with the `is_disabled` gate; all CHA-417); its three callers `read_stream` \u002F `audit_upserts_stream` \u002F `audit_deletes_stream` delegate (single `constructed` event).\n\n## References\n\nFetch on demand:\n\n- `docs\u002Fstyle-guide.md` — repo-local Rust + Python conventions.\n- `docs\u002Fdevelopment-methodology-guide.md` — three valid responses, two-loop TDD, KISS.\n- [`tracing` crate docs](https:\u002F\u002Fdocs.rs\u002Ftracing\u002Flatest\u002Ftracing\u002F) — `Span`, `Event`, level semantics, `#[instrument]` attribute options.\n- [`tracing-subscriber` docs](https:\u002F\u002Fdocs.rs\u002Ftracing-subscriber\u002Flatest\u002Ftracing_subscriber\u002F) — `EnvFilter`, `fmt::Subscriber`, layer composition. Read only for init-site fixes; this skill does not modify subscribers by default.\n- [OpenTelemetry semantic conventions](https:\u002F\u002Fopentelemetry.io\u002Fdocs\u002Fspecs\u002Fsemconv\u002F) — field naming reference (`db.system`, `rpc.service`, `http.request.method`). Useful for picking field names that will compose with OTel later, even though Penca does not export OTel today.\n\n## Three valid responses\n\nWhen an instrumentation site hits a wall — a planned field can't be derived without taking ownership of a moved value, the boundary fn is generic over a non-`Debug` type, `#[instrument]` on the candidate would change a public API (e.g. forcing a lifetime annotation) — the three valid responses are:\n\n1. **Execute** — apply the instrumentation as planned, gates green.\n2. **Clarify** — return to Phase 1 for that site, revise the plan, re-invoke `\u002Fplan-reviewer`.\n3. **Challenge** — push back on the site's premise; record it as out-of-scope or as a \"spin into own ticket\" finding.\n\nThere is no fourth option of silently bundling a functional change into an instrumentation commit, skipping `\u002Fplan-reviewer` for an \"obvious\" instrumentation, or substituting a different mechanism than the one the approved plan named. Behavior-preservation (in the functional sense) is the contract; the gates exist to enforce it.\n","# Tracing instrument\n\nAdd structured `tracing`-crate instrumentation to Penca Rust code through a two-phase gated loop: **Plan** (one combined mechanism-bound plan covering every site the walk surfaces, emitted as kata tasks under `cha-NNN plan-draft`, gated once by `\u002Fplan-reviewer` to `APPROVED`) → **Execute** (one branch per batch, each site drained from `kata ready --label cha-NNN --label approved` and landed as its own commit, gated once by `just check` at PR open).\n\nEvery site is named against one of three reference exemplars (tokio `#[instrument]`, tower-http `TraceLayer`, sqlx query spans) so the *shape* the instrumentation moves toward is explicit, not vibes.\n\n**Single-PR default.** Every site the walk surfaces lands in **one batch, one branch, one PR**. Do not pre-split the batch into multiple PRs as a stylistic choice — the plan+review cycle is the expensive step, and one combined plan is cheaper for the reviewer than N serial plans with hidden cross-site dependencies. Split into multiple batches only when the scope is truly enormous — rule of thumb, ~20+ sites spanning unrelated module trees that no reviewer would sensibly evaluate as a single change. When in doubt, keep it one PR. Scope pruning (dropping a site the user doesn't want) happens during `\u002Fplan-reviewer` iteration by deleting the task from the kata queue, not pre-emptively at walk time.\n\n## When to use this skill\n\nThree invocation modes; see \"Invocation modes\" below for how the contract differs across them:\n\n- **Ad-hoc instrumentation pass** on a crate or binary — no ticket required. The plan goes through `cha-NNN plan-draft` → human-approval → drain on an instrument-themed branch.\n- **In-ticket instrumentation** during an observability ticket's implementation phase, when `\u002Fdo-issue` (or you) hands off to this skill. Same contract as ad-hoc, but scoped to a Linear `cha-NNN`.\n- **In-cleanup-context pass** invoked by `\u002Fdo-issue`'s `orch:run-cleanup` orchestration task on a non-instrumentation ticket. The cleanup-context contract is auto-approve after `\u002Fplan-reviewer` `APPROVED` (no human TUI step) and skip Phase 2 (the outer `\u002Fdo-issue` `\u002Floop` drains).\n\nIf you're driving a Linear ticket through its full lifecycle (status → In Progress, plan-on-ticket, PR with `Closes CHA-XX`, post-merge cleanup), **start with `\u002Fdo-issue`** — it handles ticket mechanics and hands off to this skill when the ticket's core ask is \"instrument X\" with no functional behavior change. `\u002Fdo-issue` retains the ticket-mechanics steps; this skill replaces the plan + implement steps for instrumentation work.\n\nDo **not** use this skill for:\n- Adding metrics (`metrics` crate, Prometheus exporters) — out of scope until Penca adopts a metrics stack.\n- Adding OpenTelemetry \u002F distributed-tracing exporters — out of scope until Penca adopts an exporter.\n- Refactoring code that happens to touch existing log sites — that's `\u002Fclean-code-refactor` work. Instrumentation passes are behavior-additive: existing logs are not rewritten unless they violate a grounding principle below.\n- Functional behavior changes, bug fixes, or new features — those are `feat:` \u002F `fix:` work; route through `\u002Fdo-issue` normally.\n- Subscriber \u002F pipeline configuration changes (env-filter defaults, formatter swaps) — those are infra concerns, handled outside this skill.\n\n## Invocation modes\n\nThe Phase-1 walk + `\u002Fplan-reviewer` gate is identical across all three modes. The differences are at the gate and in Phase 2.\n\n| | Ad-hoc \u002F in-ticket instrumentation (default) | **In-cleanup-context** (`--in-cleanup-context cha-NNN`) |\n|---|---|---|\n| Phase-1 emit label | `cha-NNN plan-draft` | `cha-NNN plan-draft cleanup-pass` |\n| `\u002Fplan-reviewer` gate | runs to APPROVED | runs to APPROVED |\n| Post-APPROVED label swap | **human** flips `plan-draft` → `approved` in `kata tui` (or via `\u002Fdo-issue` Step 3 bulk-approve) | **skill** auto-flips `plan-draft` → `approved` — no human gate |\n| `orch:open-pr` blocker extension | n\u002Fa (no orch task exists) | every new task `kata edit`'s `orch:open-pr` to add the new task as a `--blocked-by` |\n| Phase 2 (drain) | this skill drives the drain on its own branch | **skipped** — control returns to the outer `\u002Fdo-issue` `\u002Floop`, which drains via its uniform consumer |\n\nIn-cleanup-context invocation: `\u002Ftracing-instrument --in-cleanup-context cha-NNN \u003Ctouched-files-or-scope>`. Detect the flag before walking; the rest of the skill behaves the same up to the gate.\n\n## Grounding principles\n\nThe principles below are inlined here intentionally — this skill is a durable artifact and must remain self-sufficient.\n\n1. **Spans bracket units of work; events record facts.** A span has a start and an end and captures everything inside as context (timing, nested spans, fields-in-scope). An event is a point-in-time fact emitted inside (or outside) a span. Do not event-log what a span should bracket. Do not span-wrap a single emit.\n2. **Structured fields, never formatted strings.** `tracing::info!(query_id = %id, rows = n, \"query complete\")`, not `info!(\"query {} returned {} rows\", id, n)`. Fields are filterable, indexable, and machine-readable; format strings are none of those. The trailing static message is the *event name*, not a place to interpolate.\n3. **Span and event names are static literals.** `tracing` macro names must be string literals — dynamic strings defeat the macro-time optimization, break most exporters' aggregation, and silently downgrade your spans. Put dynamic values in fields.\n4. **Levels carry semantics; default to `debug`.** `error` = the operation cannot continue \u002F a contract was violated. `warn` = degraded but recoverable \u002F unexpected but handled. `info` = lifecycle events at a boundary (RPC handler entry, startup\u002Fshutdown, scheduler tick). `debug` = per-operation detail useful when investigating. `trace` = inside-the-loop noise that is normally filtered. A new site defaults to `debug` unless it crosses a service boundary or represents a failure.\n5. **Instrument at boundaries, not at every callsite.** Public async fns on RPC servicers, IO operations, transaction commits, scheduler ticks, lifecycle phase transitions. Pure internal helpers inherit the caller's span — adding `#[instrument]` there is noise and inflates exporter cardinality.\n6. **One `#[instrument]` per boundary fn, with explicit `skip` and `fields`.** `#[instrument(skip_all, fields(req_id = %req.id, kind = ?req.kind), err)]`. The default macro behavior logs every argument by `Debug`, which is noisy and can leak data. **Use** `skip_all` **(not** `skip(specific_args)`**)** so every surfaced field comes from the explicit `fields(...)` list; this is the only form that catches the case where an arg is reused as a field source (e.g. `fields(schema = %name)` would otherwise auto-record `name` as a duplicate Debug field on top of the explicit `schema` field).\n7. **Errors are logged once, at the boundary they cross out.** Library code returns `Result`; the binary \u002F RPC handler logs at the point the error becomes user-visible. `#[instrument(err)]` does this for you at the function boundary; do not also `tracing::error!` inside the function for the same path. Double-logging an error is worse than not logging it — it inflates alert volume and breaks dedup.\n8. **No PII, secrets, or unbounded blobs in fields.** Names, emails, tokens, raw query bodies that may contain user data, multi-MB payloads. Use `skip(...)` and emit a derived non-identifying summary (length, hash prefix, kind) instead. When in doubt, skip.\n9. **No `println!` \u002F `eprintln!` in library code.** Always `tracing` events. `println!` is fine in CLI binaries that produce user-facing stdout output, and `eprintln!` is fine for top-level binary panics before the subscriber is initialized — but inside `crates\u002F*\u002Fsrc\u002Flib.rs` and its descendants, the answer is always a `tracing` event.\n10. **Subscriber init lives in `main`, never in a library.** Libraries emit; binaries decide where the emissions go. Each binary entry point owns its `tracing_subscriber` setup. The skill does not touch subscriber initialization unless explicitly invoked for an init-site fix.\n11. **One commit per coherent site.** A \"site\" is one boundary fn + its enclosed events, or one previously-unstructured log site converted to structured form. Do not bundle \"instrument scheduler tick\" and \"instrument query planner\" into one commit — they read separately and may need to be reverted separately.\n12. **No semantic change inside an instrumentation commit.** Adding a span, adding `#[instrument]`, restructuring a `tracing::warn!` from format-string to fields — all behavior-preserving (in the functional sense). If the change would alter control flow or returned values, record it as a \"spin into own ticket\" finding and stop — do not bundle.\n13. **Route through `just` recipes, never bare `cargo`.** `just cargo-check`, `just cargo-test`, `just cargo-fmt`. Bare `cargo` skips the workspace's pinned flags.\n14. **Every instrumentation batch goes on its own branch — one batch per invocation by default.** One *batch* per branch (the full set of sites in the approved Phase-1 plan, or the single site from an ad-hoc invocation), each site landed as its own commit on the batch branch. Default to **one batch = one PR for the entire approved set**; only split into multiple batches when the scope is truly enormous (rule of thumb: ~20+ sites spanning unrelated module trees). The branch lifecycle is part of the contract, not a convenience.\n15. **Iterate kata task bodies in place via `kata edit \u003Cref> --body \"$(cat \u003Cbody-file>)\"`** (`kata edit` has no `--body-file`\u002F`--body-stdin` — those are `kata create`-only flags)**.** Phase-1 iteration with `\u002Fplan-reviewer` updates the relevant task bodies — no new tasks per REVISE pass. (The exception is when `\u002Fplan-reviewer` returns `REVISE` because a site is missing entirely — emit a new task with `--label cha-NNN --label plan-draft`.)\n\nIf you need conventions you don't already have in context, read `docs\u002Fstyle-guide.md` and `docs\u002Fdevelopment-methodology-guide.md` on demand.\n\n## Operational shape\n\nTwo sequential phases. Each phase produces an artifact the next phase reads — no implicit hand-offs, no shortcuts between phases.\n\n### Phase 1 — Plan (one combined batch plan, gated by `\u002Fplan-reviewer`)\n\nWalk the chosen scope (a crate, a module, a binary; or in cleanup-context mode, the touched-files list `\u002Fdo-issue` passes). Identify instrumentation sites against the principles above. Emit **one kata task per site**, all under `cha-NNN plan-draft` (and `cleanup-pass` as an additional source label when invoked in `--in-cleanup-context` mode). The set of tasks *is* the plan; the `\u002Fplan-reviewer` pass *decides* — if a site should not land, the user (or `\u002Fplan-reviewer`) calls it out during review and the task is dropped from the queue via `kata delete`. Do not self-censor sites pre-emptively at walk time.\n\nWhen invoked **standalone with no ticket**, use a per-invocation scope label of the user's choosing (e.g. `tracing-penca-lifecycle-2026-05-28`) in place of `cha-NNN`; the kata queue is still the source of truth.\n\nTypical sites a Phase-1 walk surfaces:\n\n- **Missing boundary spans** — public async fns on RPC servicers, scheduler entry points, IO operations that lack `#[instrument]`. Lens: tower-http `TraceLayer` for the outermost handler; tokio `#[instrument]` for inner async fns.\n- **Silent error sites** — `Result` returned from a boundary fn with no `#[instrument(err)]` and no caller-side log. Lens: tokio `#[instrument(err)]`.\n- **Format-string logs** — `info!(\"query {} returned {}\", id, n)` that should be `info!(query_id = %id, rows = n, \"query complete\")`. Lens: sqlx structured-field events.\n- **`println!` \u002F `eprintln!` in library code** — direct violations of principle #9.\n- **Over-instrumented hot loops** — `info!` inside a tight per-row loop that should be `trace!` or moved to a span field aggregated at loop exit.\n- **Unstructured spans** — spans created with `tracing::info_span!(\"name\")` with no fields, where the natural fields (request id, key, count) are right there at the callsite.\n\nFor each site, the kata task names (in the task body — title is one line summarizing the change):\n\n- `crate\u002Fpath\u002Ffile.rs:LINE` — the symbol or block.\n- **Site category** — one of the bullets above (or a justified new one).\n- **Lens applied** — tokio-instrument \u002F tower-http-trace-layer \u002F sqlx-query-span (see \"Reference exemplars\" below).\n- **Span name + field list** — the static literal span\u002Fevent name and the explicit `(field = %value, …)` list. PII gates from principle #8 must be called out per-site if the natural fields would carry user data.\n- **Level + justification** — which of `error`\u002F`warn`\u002F`info`\u002F`debug`\u002F`trace`, with the one-sentence reason tied to principle #4.\n- **Behavior-preservation note** — confirm the change is additive only (no control-flow or return-value changes). If a site cannot be done additively, mark it \"spin into own ticket\" and exclude from the batch.\n- **Inter-site dependencies** — anything earlier sites must do first (e.g. \"depends on #2's `#[instrument]` on the outer fn being in place so this site's nested span has a parent\"). Encode with `kata create --blocked-by \u003Cearlier-task-ref>` so the drain loop respects ordering.\n\nBatch-level meta (kept in one **batch-summary task** with `--label cha-NNN --label plan-draft --label batch-summary`):\n\n- One paragraph naming the scope, the sites included (qualified-ids), the execution order with one-line justifications. The `--blocked-by` graph captures the ordering at the task level; the summary is for the human reviewer.\n- **Batch-level gate** — `just check` exits 0 *after the last site is committed*; no semantic change in any commit; per-site atomicity (one commit per site, no bundling).\n\n**Invoke `\u002Fplan-reviewer` once** on the kata task set (`kata list --label cha-NNN --label plan-draft --json`). Iterate on `REVISE` items by editing the relevant task bodies via `kata edit \u003Cref> --body \"$(cat \u003Cbody-file>)\"` — no new tasks per pass. Re-invoke until the verdict is `APPROVED`.\n\n#### Self-audit before posting\n\nBefore invoking `\u002Fplan-reviewer`, audit the combined plan for:\n\n- **Nested-span field consistency.** When the plan instruments two or more spans on the same operation path (e.g. a planning span on the public fn + an IO span on a Stream \u002F Future the fn returns), every field name that appears in both spans must carry the same identifier type and value-format. Field name across nested spans = same kind of value, full stop. If two spans both need a `catalog` field but at one site only the UUID is available and at the other only the name, *use different field names* (`catalog_uuid` vs `catalog_name`) — never let the same field name carry different types across spans on the same op.\n\n**Hard stop:** no code edit happens before `\u002Fplan-reviewer` returns `APPROVED`. If three rounds fail to converge, halt and surface to the user.\n\n#### In-cleanup-context post-APPROVED handling\n\nWhen invoked with `--in-cleanup-context cha-NNN`, `\u002Fplan-reviewer` itself auto-flips `plan-draft` → `approved` on every cleanup-pass task and extends `orch:open-pr`'s `--blocked-by` after returning `APPROVED` (see `\u002Fplan-reviewer`'s \"Post-APPROVED — cleanup-pass auto-flip\" section). This skill does **no** post-APPROVED handling — return control to the caller (the outer `\u002Fdo-issue` `\u002Floop`); **skip Phase 2 entirely** — the outer drain claims and processes the now-approved cleanup-pass tasks via its uniform consumer.\n\n### Phase 2 — Execute (one branch per batch, drain from kata)\n\nPhase 2 runs only for the ad-hoc and in-ticket instrumentation modes. **In-cleanup-context mode skips Phase 2** — the outer `\u002Fdo-issue` `\u002Floop` is the drain.\n\nOnly after Phase 1 returns `APPROVED` *and* the user has flipped each task's label `plan-draft` → `approved` (in `kata tui`, or via the bulk-approve helper from `\u002Fdo-issue` Step 3).\n\n1. **Create the branch** via `git checkout -b \u003Cbranch>` from the repo root — one branch for the entire batch; name it after the batch theme (e.g. `nhobin219\u002Fcha-XYZ-instrument-lifecycle-scheduler`), not any single site.\n\n2. **Drain the approved kata queue.** The `--blocked-by` edges from Phase 1 give the execution order for free:\n   ```bash\n   while true; do\n     ref=$(kata ready --unowned --label cha-NNN --label approved --json | jq -r '.issues[0].qualified_id \u002F\u002F empty')\n     [ -z \"$ref\" ] && break\n     kata claim \"$ref\"\n     # ...apply the additive instrumentation change from the task body...\n     git commit -m \"chore(\u003Cscope>): instrument \u003Csite>\n\nCHA-XX\n\"\n     kata close \"$ref\" --done --commit \"$(git rev-parse HEAD)\"\n   done\n   ```\n   The change must match the task body's named span\u002Fevent name, fields, and level. If implementation reveals a structural blocker not in the task (e.g. the boundary fn is generic over a non-`Debug` type, blocking the planned field), halt and return to Phase 1 for that site — no silent substitution.\n\n   Commit as `chore(\u003Cscope>): instrument \u003Csite>` (default) or `feat(\u003Cscope>): add \u003Cthing> instrumentation` (only when the new visibility is the user-facing point of the change — e.g. enabling a new dashboard). **One commit per site; no bundling, no semantic change.** Intermediate gaps in instrumentation between commits are fine — the PR gate runs once at the end.\n\n3. **PR gate** — after the last site is committed, `just check` must exit 0 once before opening the PR. This is the project-wide gate that mirrors CI; it is a strict superset of `just cargo-check` (`lint` + `format-check` + `test` + `static-test` + `cargo-check`). The batch's atomicity is \"all commits green together\"; per-site gates are out.\n\n4. **Open the PR** with a title naming the batch theme and a body listing each commit's site with a one-line summary. After merge, sync main and delete the branch: `git checkout main && git pull && git branch -d \u003Cbranch>`.\n\n### Subagent default — single-agent, main session\n\nThis skill executes in the **main conversation** with no `Agent`-tool fan-out. Spawning a subagent (parallel Phase-1 walks across crates, parallel Phase-2 branches, etc.) requires **explicit in-session user authorization** — not just plan-time justification. The single-agent default exists because the project's review-loop discipline (`\u002Fplan-reviewer`, `\u002Fcode-quality-reviewer`) is built around one author per change; parallel subagent runs split that discipline across contexts that cannot see each other's findings.\n\n## Reference exemplars\n\nThree canonical shapes from the `tracing` ecosystem. Every Phase-1 site names which lens applies; every Phase-1 plan justifies the chosen lens.\n\n### tokio `#[instrument]` — span-per-async-fn at internal boundaries\n\n[`tokio\u002Fsrc\u002Fruntime\u002Fscheduler\u002Fmulti_thread\u002Fworker.rs`](https:\u002F\u002Fgithub.com\u002Ftokio-rs\u002Ftokio\u002Fblob\u002Fmaster\u002Ftokio\u002Fsrc\u002Fruntime\u002Fscheduler\u002Fmulti_thread\u002Fworker.rs) (fetch with `WebFetch` for the latest shape — search for `#[instrument]` and `tracing::`).\n\n`#[instrument]` brackets an async fn in a span whose lifetime matches the future's. Default behavior logs all args by `Debug`; tokio's usage overrides this aggressively: `skip(self, ...)`, explicit `fields(...)`, and `err` \u002F `ret` only where the return matters.\n\n**Operational insight:** the macro is the right tool for inner boundary fns — the span is created lazily, the field set is fixed at compile time, and the lifetime exactly matches the future. The wrong tool for hot inner-loop fns (every invocation allocates a span) and for fns that take large\u002Fsensitive args without `skip`.\n\n**When to apply this lens:** a candidate is an async fn at an internal boundary (one layer below an RPC handler, an IO operation, a scheduler tick subroutine) and currently has no span. Add `#[instrument(skip(...), fields(...), err)]` matching the plan's named fields and level.\n\n### tower-http `TraceLayer` — span-per-request at the service boundary\n\n[`tower-http\u002Fsrc\u002Ftrace\u002Fmod.rs`](https:\u002F\u002Fgithub.com\u002Ftower-rs\u002Ftower-http\u002Fblob\u002Fmain\u002Ftower-http\u002Fsrc\u002Ftrace\u002Fmod.rs) (fetch with `WebFetch` for the latest shape).\n\n`TraceLayer` is a `tower::Layer` that wraps a service and creates one span per request, with hooks for `make_span_with`, `on_request`, `on_response`, `on_failure`. Works with tonic (which is `tower`-based) the same way it works with axum.\n\n**Operational insight:** the outermost boundary of an RPC server is a `tower::Service`, not a Rust async fn — adding `#[instrument]` to a handler is one layer too deep. The request-lifecycle span (start, end, status, latency) belongs at the layer where the request first appears. Inner handlers get their own narrower `#[instrument]` spans nested inside.\n\n**When to apply this lens:** the scope is a tonic gRPC server (or any tower-based service) with no per-request span. Install `TraceLayer` at the server builder, then narrow with `#[instrument]` on the inner handlers.\n\n### sqlx query spans — structured-field events for fine-grained operations\n\n[`sqlx-core\u002Fsrc\u002Flogger.rs`](https:\u002F\u002Fgithub.com\u002Flaunchbadge\u002Fsqlx\u002Fblob\u002Fmain\u002Fsqlx-core\u002Fsrc\u002Flogger.rs) (fetch with `WebFetch` for the latest shape — search for `tracing::event!` and `QueryLogger`).\n\nEach query gets a span with `db.statement`, `db.system`, `rows_affected`, `rows_returned` as structured fields, emitted at a level chosen by latency (slow queries log warn; normal queries log debug). Field names follow OpenTelemetry semantic conventions even though sqlx doesn't ship OTel exporters.\n\n**Operational insight:** when a single operation has natural metadata (query id, key, count, duration, kind), the right shape is one span per operation with those metadata as fields — not one event per phase of the operation. Aggregate inside the span; emit one summary event at completion. The field names matter: `rows`, `query_id`, `req_id`, `kind` are reusable across collectors; `n`, `x`, `the_thing` are not.\n\n**When to apply this lens:** a candidate is a per-operation site (a query, a write, a lifecycle phase) that currently logs in pieces with format strings. Replace with one span per operation, structured fields for the metadata, and one summary event at the end.\n\n**Note on tracing 0.1 + Streams.** `tracing` 0.1 provides `Instrumented\u003CF>: Future` but not `Instrumented\u003CS>: Stream` — `.instrument(span)` on a `Stream` requires the (maintenance-mode) `tracing-futures` 0.2 crate with the `futures-03` feature. The workspace already pulls in `tracing-futures = \"0.2\"` via [CHA-310](https:\u002F\u002Flinear.app\u002Fchapala\u002Fissue\u002FCHA-310), so reach for `.instrument(span)` on streams freely; see [CHA-322](https:\u002F\u002Flinear.app\u002Fchapala\u002Fissue\u002FCHA-322) for the eventual removal path once `tracing` 0.2 absorbs Stream instrumentation. Considered-and-rejected alternative: `.instrument(span)` on the inner Future that produces the stream — closes the span before any streaming, captures only the handshake, misses streaming duration + mid-stream errors.\n\n### Lens routing — the three questions\n\nFor every site, answer:\n\n| | tokio `#[instrument]` | tower-http `TraceLayer` | sqlx query span |\n| --- | --- | --- | --- |\n| Where does the span begin? | at the macro-annotated fn entry | at the service layer, before the handler | at the operation start (manual `info_span!`) |\n| What's the natural lifetime? | the future | the request | the operation |\n| What populates the fields? | macro `fields(...)` + `skip(...)` | layer hooks (`make_span_with`, `on_response`) | callsite (`span.record(...)` as values become known) |\n\nIf a site fails all three (it's not a fn boundary, not a service boundary, and not a discrete operation), it is probably an *event*, not a span — emit a structured event at the appropriate level and move on.\n\n### Stream instrumentation convention\n\n`#[instrument]` doesn't attach cleanly to non-async fns that return a `Stream` — the work happens lazily inside the `async_stream::try_stream!` body, not in the fn call, and the `tracing` crate's `Instrument` trait only covers `Future`, not `Stream`. Two shapes, by what the site needs:\n\n- **Stream-level span (preferred when timing is wanted)** — create a `debug_span!` with counter fields declared `tracing::field::Empty`, attach it to the stream via `tracing_futures::Instrument`, accumulate counters in the body, and `Span::current().record(...)` them at end-of-stream (CHA-417). With `PENCA_SPAN_TIMING` the span-close line carries busy\u002Fidle for the whole stream lifetime. An errored or cancelled stream still closes the span with timing but leaves the counters unrecorded — a timed close with no counts reads as \"aborted\", not \"zero rows\". When the span wraps a *new* pass-through stream layer (rather than a pre-existing block), gate the wrapper on `span.is_disabled()` so the disabled path stays zero-cost.\n- **Bracket \u002F constructed events (fallback when a span is overkill)** — manual `tracing::debug!` events using one of two name patterns: **`\"\u003Cfn> start\"` \u002F `\"\u003Cfn> complete\"`** when the fn owns the stream body (partial-drop traces show start without complete — the operator-visible early-cancellation signal, not a bug), or **`\"\u003Cfn> constructed\"`** fire-and-yield when the fn builds a SQL string + delegates to a deeper streaming primitive without owning the cursor (cursor-lifecycle visibility comes from the downstream site).\n\nUse the full fn name in the span\u002Fevent literal, not an abbreviation — keeps names self-locating from a log grep. Field-set PII gates are identical to `#[instrument]` boundaries (principle #8).\n\nIn-repo precedent: `crates\u002Fpenca-storage-hot\u002Fsrc\u002Fquery.rs::stream_query_as_batches` carries the stream-level span (as do the response-stream siblings `ipc_encode` in `penca-server-grpc\u002Fsrc\u002Fipc.rs` and `flight_encode` in `penca-sql-server\u002Fsrc\u002Fflight_sql\u002Fservice.rs` — the latter with the `is_disabled` gate; all CHA-417); its three callers `read_stream` \u002F `audit_upserts_stream` \u002F `audit_deletes_stream` delegate (single `constructed` event).\n\n## References\n\nFetch on demand:\n\n- `docs\u002Fstyle-guide.md` — repo-local Rust + Python conventions.\n- `docs\u002Fdevelopment-methodology-guide.md` — three valid responses, two-loop TDD, KISS.\n- [`tracing` crate docs](https:\u002F\u002Fdocs.rs\u002Ftracing\u002Flatest\u002Ftracing\u002F) — `Span`, `Event`, level semantics, `#[instrument]` attribute options.\n- [`tracing-subscriber` docs](https:\u002F\u002Fdocs.rs\u002Ftracing-subscriber\u002Flatest\u002Ftracing_subscriber\u002F) — `EnvFilter`, `fmt::Subscriber`, layer composition. Read only for init-site fixes; this skill does not modify subscribers by default.\n- [OpenTelemetry semantic conventions](https:\u002F\u002Fopentelemetry.io\u002Fdocs\u002Fspecs\u002Fsemconv\u002F) — field naming reference (`db.system`, `rpc.service`, `http.request.method`). Useful for picking field names that will compose with OTel later, even though Penca does not export OTel today.\n\n## Three valid responses\n\nWhen an instrumentation site hits a wall — a planned field can't be derived without taking ownership of a moved value, the boundary fn is generic over a non-`Debug` type, `#[instrument]` on the candidate would change a public API (e.g. forcing a lifetime annotation) — the three valid responses are:\n\n1. **Execute** — apply the instrumentation as planned, gates green.\n2. **Clarify** — return to Phase 1 for that site, revise the plan, re-invoke `\u002Fplan-reviewer`.\n3. **Challenge** — push back on the site's premise; record it as out-of-scope or as a \"spin into own ticket\" finding.\n\nThere is no fourth option of silently bundling a functional change into an instrumentation commit, skipping `\u002Fplan-reviewer` for an \"obvious\" instrumentation, or substituting a different mechanism than the one the approved plan named. Behavior-preservation (in the functional sense) is the contract; the gates exist to enforce it.\n",{"name":5,"description":7,"allowed-tools":24,"argument-hint":25},"Read Grep Glob Bash WebFetch Write Edit Skill mcp__language-server__definition mcp__language-server__references mcp__language-server__hover mcp__language-server__diagnostics","[--in-cleanup-context cha-NNN] \u003Cscope>","main","5857ef2d015e3d9011c5e73b01660da6043e0f0e",".claude\u002Fskills\u002Ftracing-instrument",0,"https:\u002F\u002Fgithub.com\u002Fpenca-io\u002Fpenca","https:\u002F\u002Fpenca.io\u002F","https:\u002F\u002Fgithub.com\u002Fpenca-io","https:\u002F\u002Fpenca.io","2026-08-01 08:29:37",{"source":8,"skillName":5,"commands":36,"prompt":46,"zipAvailable":47},[37,40,43],{"tool":38,"command":39},"npx","npx skills add penca-io\u002Fpenca --skill tracing-instrument",{"tool":41,"command":42},"bunx","bunx skills add penca-io\u002Fpenca --skill tracing-instrument",{"tool":44,"command":45},"pnpm","pnpm dlx skills add penca-io\u002Fpenca --skill tracing-instrument","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fpenca-io\u002Fpenca\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Ftracing-instrument\u002FSKILL.md",true,[],[50,57,64,71,78,85],{"skillNo":51,"name":52,"nameZh":6,"description":53,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":54,"categories":55,"keywords":56,"publishedAt":19},"01M79FN8FWKKYX3PG3MPHFBMSP","test","Run the test suite with pytest","https:\u002F\u002Fgithub.com\u002Fpenca-io\u002Fpenca\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Ftest\u002FSKILL.md",[],[],{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":19},"01M79FN4G6C2KG7D737QDQCJFM","software-architect","High-level architecture analysis for Penca design questions — bounded contexts, microservice boundaries, cross-service interfaces, storage tier separations (hot vs cold), CQRS-shaped splits, design-stamina trade-offs, and incremental-replacement strategies. Use when a Linear ticket needs design framing, when an existing plan has a structural concern, or when a proposed change crosses bounded-context boundaries. Advisory — does not edit code.","https:\u002F\u002Fgithub.com\u002Fpenca-io\u002Fpenca\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsoftware-architect\u002FSKILL.md",[],[],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M79FN1Y86PSSG0A6A4QZSVKW","save-memory","Save or update a memory entry. Always targets the **current repo root's** `.claude\u002Fmemory\u002F`, resolved via `git rev-parse --show-toplevel`; never the runtime `~\u002F.claude\u002Fprojects\u002F\u003Cslug>\u002Fmemory\u002F` path.","https:\u002F\u002Fgithub.com\u002Fpenca-io\u002Fpenca\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsave-memory\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M79FMXG15K3SFKP8FVYASF8Q","review-pr","Review a Penca PR against project conventions and architecture","https:\u002F\u002Fgithub.com\u002Fpenca-io\u002Fpenca\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Freview-pr\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":19},"01M79FMQVW8TEK002D5SY7N22Z","plan-reviewer","Audit a Penca `\u002Fdo-issue` plan — a set of kata tasks under `cha-NNN plan-draft` — for the mechanism-bound rule + dependency-graph sanity. Use after `\u002Fdo-issue` Step 2 emits the task set and before the user flips `plan-draft` → `approved`. Checks that every task names symbols\u002Ffiles to change AND symbols the new code path must invoke, has mechanism non-goals where relevant, avoids parallel-path workarounds, and that every implementation task is `--blocked-by` at least one red-test task with no cycles in the graph.","https:\u002F\u002Fgithub.com\u002Fpenca-io\u002Fpenca\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fplan-reviewer\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M79FMJW8GZX5SK0GBFTXTJFK","perf-engineer","Algorithmic and profile-driven performance analysis on Penca Rust changes — query-count audits, materialize-vs-stream regressions, allocation patterns under benchmark, hot-path code review backed by samply or cargo bench output. Use post-implementation for profiling, or during planning to flag perf risks. Routing test — if it can be spotted from reading the diff alone, it belongs to code-quality-reviewer; if it needs measurement to know it matters, use this skill.","https:\u002F\u002Fgithub.com\u002Fpenca-io\u002Fpenca\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fperf-engineer\u002FSKILL.md",[],[]]