Skip to content

feat(selfhost): PostHog AI observability across ORB and AMS#8623

Merged
loopover-orb[bot] merged 1 commit into
JSONbored:mainfrom
oktofeesh1:feat/posthog-ai-observability-8296
Jul 25, 2026
Merged

feat(selfhost): PostHog AI observability across ORB and AMS#8623
loopover-orb[bot] merged 1 commit into
JSONbored:mainfrom
oktofeesh1:feat/posthog-ai-observability-8296

Conversation

@oktofeesh1

Copy link
Copy Markdown
Contributor

Summary

  • Closes AI observability: $ai_generation capture over the ORB's review-pipeline AI calls (spike-first) #8296 (epic Epic: PostHog consolidation — errors, analytics, replay, AI observability (Sentry/Umami sunset) #8286 Phase 3): comprehensive PostHog AI observability across both ORB and AMS, per the maintainer's explicit scope confirmation to cover everything in one PR rather than only the ORB review-pipeline slice the issue text originally named. Also implements PostHog error tracking for the miner CLI (opt-in seam swap; egress-allowlist + env-reference coupling) #8292's foundation (the miner CLI's PostHog client) as a genuine prerequisite for the AMS half, since it didn't exist yet.
  • ORB: every self-host AI provider attempt (AI_PROVIDER chain — ollama/openai/openai-compatible/anthropic/claude-code/codex — plus the three standalone AI_EMBED/AI_VISION/AI_ADVISORY bindings) now emits a PostHog $ai_generation ($ai_embedding for embed requests) event: model, provider, latency, tokens, cost (when derivable), effort, and repo/PR correlation — metadata only, never prompt/response content. Wired at the single real chokepoint (runProviderWithOtel, src/selfhost/ai.ts) plus a new withAiGenerationCapture wrapper for the three ungoverned bindings.
  • AMS: new opt-in packages/loopover-miner/lib/posthog.ts (mirrors sentry.ts's contract, runs alongside it per the epic's parallel-run posture) plus $ai_generation capture for all three coding-agent driver types (claude-cli/codex-cli/agent-sdk), wired at constructProductionCodingAgentDriver. Honestly represents the data it actually has: CodingAgentDriverResult only reports a single blended costUsd/tokensUsed (no input/output split like ORB's AiUsage), so the new capture never fabricates a split — token count rides in a plain tokens_used property, $ai_total_cost_usd (one of PostHog's own recognized fields, needs no split) is populated directly.
  • Egress allowlist, _FILE secret-mount support (free via the existing generic <NAME>_FILE scanner), env-reference regeneration, and DEPLOYMENT.md updated for the two new miner env vars.

Scope

  • The PR title follows type(scope): short summary Conventional Commit format.
  • This PR is focused and does not mix unrelated backend, UI, MCP, docs, dependency, and deploy changes.
  • This follows CONTRIBUTING.md and does not reintroduce GitHub Pages, VitePress, site/, or CNAME.
  • I linked a currently open issue this PR resolves (Closes #8296).

Validation

  • git diff --check
  • npm run actionlint
  • npm run typecheck
  • npm run test:coverage locally — full unsharded run: 21,576 tests passed, 0 failed. Every changed file at 100% line+branch coverage on the diff (verified via scoped v8 runs); the two pre-existing sub-100% lines in ai.ts/posthog.ts (ORB) are outside this diff's hunks, confirmed via git diff line-range comparison.
  • npm run test:workers
  • npm run build:mcp
  • npm run test:mcp-pack
  • npm run build:miner
  • npm run test:miner-pack
  • npm run test:miner-deployment-docs-audit
  • npm run miner:env-reference:check
  • npm run ui:openapi:check
  • npm run ui:lint
  • npm run ui:typecheck
  • npm run ui:build
  • npm run docs:drift-check
  • npm run engine-parity:drift-check
  • npm audit --audit-level=moderate — 5 pre-existing high-severity findings, all transitive dev-tooling (eslint/minimatch/brace-expansion); zero new dependencies added by this PR (package.json/package-lock.json untouched).
  • New or changed behavior has unit/integration tests for new branches, fallback paths, and sanitizer boundaries

If any required check was skipped, explain why:

  • None skipped — the full npm run test:ci chain was run end-to-end on the final, rebased tree.

Safety

  • No secrets, wallet details, hotkeys, coldkeys, user PATs, private keys, raw trust scores, private rankings, or private maintainer evidence are exposed.
  • Public GitHub text stays sanitized, low-noise, and does not imply compensation guarantees or optimization tactics.
  • Auth, cookie, CORS, GitHub App, Cloudflare, or session changes include negative-path tests — no such surface touched.
  • API/OpenAPI/MCP behavior is updated and tested where needed — unchanged (no API/schema touched).
  • UI changes use live API data or real empty/error/loading states — the one doc page addition (self-hosting-operations.mdx) is prose only, no new UI component.
  • Visible UI changes include a UI Evidence section — not applicable, no visible UI/frontend change.
  • Public docs/changelogs are updated where needed; changelogs are only edited for release-prep PRs — no changelog edit.

UI Evidence

Not applicable — backend + miner-CLI observability instrumentation and doc prose only, no visible UI/frontend/extension change.

Notes

Captures $ai_generation/$ai_embedding events for every self-host AI
provider attempt (the AI_PROVIDER chain plus the AI_EMBED/AI_VISION/
AI_ADVISORY bindings) and for every AMS coding-agent driver attempt
(claude-cli/codex-cli/agent-sdk), metadata only -- model, provider,
latency, tokens, cost, never prompt/response content.

Adds the miner CLI's own opt-in PostHog client (packages/loopover-miner/
lib/posthog.ts) as the foundation the AMS side needs, running alongside
the existing Sentry integration during the parallel-run window. Includes
egress-allowlist entries, env-reference regeneration, and DEPLOYMENT.md
updates for the two new miner env vars.
@oktofeesh1
oktofeesh1 requested a review from JSONbored as a code owner July 25, 2026 15:13
@superagent-security

Copy link
Copy Markdown
Contributor

Superagent didn't find any vulnerabilities or security issues in this PR.

@codecov

codecov Bot commented Jul 25, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.41%. Comparing base (5f5f52b) to head (8450043).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #8623      +/-   ##
==========================================
- Coverage   92.76%   90.41%   -2.36%     
==========================================
  Files         797      103     -694     
  Lines       79355    23434   -55921     
  Branches    24034     4221   -19813     
==========================================
- Hits        73616    21187   -52429     
+ Misses       4592     2031    -2561     
+ Partials     1147      216     -931     
Flag Coverage Δ
backend 87.04% <100.00%> (-6.60%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
packages/loopover-miner/bin/loopover-miner-mcp.ts 69.47% <ø> (ø)
packages/loopover-miner/bin/loopover-miner.ts 0.00% <ø> (ø)
...es/loopover-miner/lib/coding-agent-construction.ts 100.00% <100.00%> (ø)
packages/loopover-miner/lib/egress-allowlist.ts 100.00% <100.00%> (ø)
packages/loopover-miner/lib/posthog.ts 100.00% <100.00%> (ø)
src/selfhost/ai.ts 98.25% <100.00%> (+0.05%) ⬆️
src/selfhost/posthog.ts 99.31% <100.00%> (+0.07%) ⬆️

... and 695 files with indirect coverage changes

@loopover-orb loopover-orb Bot added gittensor:bug Gittensor-scored bug fix — scores a 0.05x multiplier. gittensor:priority Maintainer-selected Gittensor priority — scores a 1.5x multiplier. labels Jul 25, 2026
@loopover-orb

loopover-orb Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

Tip

✅ LoopOver review result - approve/merge recommended

Review updated: 2026-07-25 15:23:45 UTC

17 files · 1 AI reviewer · no blockers · readiness 100/100 · CI green · clean

✅ Suggested Action - Approve/Merge

  • safe to merge

Review summary
This PR wires PostHog `$ai_generation`/`$ai_embedding` capture into every self-host AI provider path (ORB's `runProviderWithOtel` chain plus the three standalone AI_EMBED/AI_VISION/AI_ADVISORY bindings via a new `withAiGenerationCapture` wrapper) and into AMS's coding-agent driver construction via a new opt-in `packages/loopover-miner/lib/posthog.ts` module. The capture call sites are correctly placed at the real chokepoints, metadata-only (no prompt/response content), fail-safe (try/catch around every `client.capture`/`captureException` call so a PostHog SDK failure can't break the instrumented caller), and the egress allowlist/env-reference/docs are updated in step with the new env vars. Test coverage is thorough on both success/failure branches and the finite/non-finite numeric branches for tokens/cost.

Nits — 6 non-blocking
  • packages/loopover-miner/lib/posthog.ts:25 hardcodes `https:​//us.i.posthog.com` as the default ingestion host, duplicated as `us.i.posthog.com` in egress-allowlist.ts:81 — consider exporting one constant from posthog.ts and importing it in egress-allowlist.ts to avoid the two literals drifting.
  • The external brief flags a possible secret literal at test/unit/miner-posthog.test.ts:112 — this is `"phc_test_key"`, a test fixture API key, not a real credential, so no action needed.
  • src/selfhost/posthog.ts's `capturePostHogAiGeneration` and packages/loopover-miner/lib/posthog.ts's `captureMinerPostHogAiGeneration` duplicate the same `.slice(0, 500)` error-truncation and 200/500 status-code logic — minor duplication given the two files can't share code across the package boundary (documented rationale), so this is acceptable as-is.
  • packages/loopover-miner/lib/coding-agent-construction.ts's `withCodingAgentAiGenerationCapture` and src/selfhost/ai.ts's `withAiGenerationCapture` are structurally near-identical wrappers (try/capture-success, catch/capture-failure-rethrow) — expected given the cross-package boundary, just noting for future maintainers who touch one to check the other.
  • Extract a single `DEFAULT_POSTHOG_HOST` constant shared between packages/loopover-miner/lib/posthog.ts and lib/egress-allowlist.ts (e.g. export it from posthog.ts) to remove the duplicated `us.i.posthog.com` literal.
  • Possible secret-shaped assignment in the diff (generic_secret_assignment) — Verify the value is not a real credential.

Decision drivers

  • ✅ Code review — No blockers (1 reviewer)
  • ✅ Gate result — Passing (No configured blocker found.)
Context & advisory signals — never blocks the verdict
Signal Result Evidence
Linked issue ✅ Linked #8296
Related work ✅ No active overlap found No same-issue or scoped active PR overlap found.
Change scope ✅ 20/20 Low review scope from cached public metadata (1 linked issue).
Validation posture ✅ 25/25 PR body includes validation/test evidence.
Contributor workload ✅ 10/10 Author activity: 44 registered-repo PR(s), 36 merged, 0 issue(s).
Contributor context ✅ Confirmed Gittensor contributor oktofeesh1; Gittensor profile; 44 PR(s), 0 issue(s).
Improvement ✅ Minor risk: clean · value: minor · LLM: significant
Linked issue satisfaction

Addressed
The PR wires attempt-level $ai_generation/$ai_embedding capture at the ai.ts chokepoint (runProviderWithOtel) and the three standalone AI_EMBED/AI_VISION/AI_ADVISORY bindings, captures metadata only (no prompt/response content), and includes unit tests verifying per-attempt capture and unconfigured no-op behavior, matching the issue's spike, wiring, privacy, and test scope items. The PR expands be

Review context
  • Author: oktofeesh1
  • Role context: outside_contributor
  • Public audience mode: oss maintainer
  • Lane context: Repository is configured for direct PR review.
  • Public profile languages: JavaScript, MDX, Python, TypeScript
  • Official Gittensor activity: 44 PR(s), 0 issue(s).
  • PR-specific overlap: none found.
Contributor next steps
  • Keep the PR focused and include validation evidence before maintainer review.
Signal definitions
  • Related work = same linked issue, overlapping active PRs, or title/path similarity.
  • Change scope = cached public metadata such as size labels, draft state, and review-burden hints.
  • Validation posture = whether the PR provides enough public validation/test evidence for maintainer review.
  • Contributor workload = public contributor activity and cleanup pressure, not a repo-wide quality failure.
  • Contributor context = public GitHub/Gittensor identity context; non-Gittensor status is not a blocker.
🧪 Chat with LoopOver

Ask LoopOver a question about this PR directly in a comment — grounded only in the same cached, public-safe facts shown above, never a new claim.

  • @loopover ask &lt;question&gt; answers contribution-quality Q&A with source citations and freshness.
  • @loopover chat &lt;question&gt; answers in natural prose from cached decision-pack facts via local inference (maintainer/collaborator; read-only).
  • A plain-language @loopover mention with a real question is routed to the closest matching read-only command automatically — no exact syntax required.

Full command reference: https://loopover.ai/docs/loopover-commands

🧪 Experimental — new and may change.

Visual preview
Route Viewport Before (production) After (this PR's preview) Diff
/ desktop before /
before /
after /
after /
/ mobile before / (mobile)
before / (mobile)
after / (mobile)
after / (mobile)

Click any thumbnail to open the full-size screenshot. Before = production · After = this PR's preview deploy.

Scroll preview
Route Before (production) After (this PR's preview)
/ before / (scroll)
before / (scroll)
after / (scroll)
after / (scroll)

A short scroll-through clip (desktop) — click either thumbnail to open the full animation. Evidence for scroll-linked behavior a single screenshot can't show.

🟩 Safe / merged · 🟦 Advisory · 🟨 Held for review · 🟥 Blocked / closed


💰 Earn for open-source contributions like this. Gittensor lets GitHub contributors earn for the work they already do — register to start earning →.

Checked by LoopOver, a quiet PR intelligence layer for OSS maintainers.

  • Re-run LoopOver review

@loopover-orb loopover-orb Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LoopOver approves — the gate is satisfied and CI is green.

@loopover-orb
loopover-orb Bot merged commit a9d9c0e into JSONbored:main Jul 25, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gittensor:bug Gittensor-scored bug fix — scores a 0.05x multiplier. gittensor:priority Maintainer-selected Gittensor priority — scores a 1.5x multiplier.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AI observability: $ai_generation capture over the ORB's review-pipeline AI calls (spike-first)

1 participant