Gittensory Architecture#
High-Level Architecture Overview#
Gittensory is the deterministic base-agent layer for Gittensor OSS contribution mining . It helps miners and contributors make better decisions before they open work, and helps maintainers review Gittensor-driven PRs with less noise . The product is the signal: role-aware contributor context, official Gittensor stats, local MCP preflight, queue health, collision risk, reviewability, repo configuration quality, and copilot-only next-action planning . Gittensory is not a Gittensor frontend, not a public leaderboard, and not an autonomous PR bot . It ranks, explains, preflights, and drafts public-safe packets; it does not edit code, open PRs, post comments, close, merge, or label without an explicit user or maintainer-triggered flow .
The architecture follows a deterministic and auditable design philosophy . Core decisions are rule-based rather than AI-generated, with Cloudflare Workers AI optional and disabled by default . The system maintains a strict public/private boundary: metadata-only I/O through MCP means source code is never transmitted , and private scoring context never leaks into public GitHub output. All operations are Worker-safe, favoring async snapshots over inline computation to fit within Cloudflare Workers constraints.
Gittensory serves three primary audiences with distinct use cases :
- Miners — Work planning and PR preparation. Miners use the system to find the next move, clear queue pressure, preflight branches, and prepare PR packets that won't get flagged.
- Maintainers — Confirmed-miner context without check noise. Maintainers receive one sticky public-safe comment and a configured label on demand, plus access to private reviewability packets through the API.
- Coding Agents — Deterministic tool schemas via MCP. Agents gain structured Gittensor context through the Model Context Protocol without requiring source code upload.
Deployment Surfaces#
The system deploys across four independent surfaces :
-
Worker API — Cloudflare Workers + Hono + D1 + Queues . The canonical API at
https://gittensory-api.aethereal.devprovides REST endpoints for scoring, preflight checks, agent orchestration, repo intelligence, and contributor decision packs. -
Frontend Worker — Lovable/TanStack Start application deployed at
https://gittensory.aethereal.dev/. This separate Cloudflare Worker underapps/gittensory-uidelivers the web interface for miners, maintainers, and administrators. -
MCP Package —
@jsonbored/gittensory-mcp. The npm package provides local stdio wrapper functionality for coding agents and serves as the first-class base-agent surface. It exposes 21 MCP tools and 13 CLI commands for branch analysis, preflight checks, and agent planning. -
GitHub App — Quiet PR inspection . The app provides public-safe sticky comments, maintainer-configured labels, and explicit
@gittensorycommands on installed repos. Default behavior is low-noise: confirmed Gittensor miners receive one sticky comment and a label, while private reviewability and scoring context remains accessible only through the API.
Monorepo Structure#
The repository follows a standard monorepo layout :
src/— Worker API backend with 16 subdirectories covering API routes, auth, database, queues, signals, scoring, services, GitHub integration, and upstream syncpackages/— Shared packages includinggittensory-mcpapps/— Frontend applications:gittensory-uiweb app andgittensory-extensionbrowser extensionmigrations/— Drizzle ORM database migrations for D1 (SQLite)scripts/— Build and utility scriptstest/— Test suites with 97% coverage requirement
Configuration files at the root include wrangler.jsonc for Cloudflare Workers deployment, drizzle.config.ts for database ORM, and cliff.toml/cliff.mcp.toml for changelog generation across workspaces.
Key Components#
Gittensory's architecture divides responsibility across eleven major component groups, each handling a distinct aspect of the deterministic base-agent system.
A. Worker API (Hono + Cloudflare Workers)#
The entry point is src/index.ts, which exports a Cloudflare Worker with three handlers: fetch for HTTP requests, queue for asynchronous job processing, and scheduled for cron-triggered batch operations . The HTTP handler delegates to createApp() from src/api/routes.ts, a 2,447-line REST API handler covering GitHub OAuth/device-flow authentication, repository management, scoring previews, preflight analysis, agent run orchestration, decision packs, admin/operator dashboards, and product analytics .
The API enforces rate limiting, session authentication, and role-based access control at the middleware level. Private endpoints require either session tokens or static API tokens, while internal job endpoints require the INTERNAL_JOB_TOKEN secret.
B. Signals Engine (src/signals/)#
Core signal types are defined in engine.ts: ParticipationLane enumerates contributor paths (direct_pr, issue_discovery, split, inactive, unknown), LaneAdvice provides lane-specific guidance for contributors and maintainers, CollisionReport groups collision clusters by risk level (low, medium, high), and QueueHealth quantifies burden score, risk level, and open issues/PRs metrics .
The engine generates nine signal types per registered repo: queue-health, config-quality, label-audit, maintainer-lane, maintainer-cut-readiness, contributor-intake-health, issue-quality, contributor-outcome-history, and repo-outcome-patterns . Supporting modules include data-quality.ts for freshness SLO reporting, reward-risk.ts for PR reviewability scoring, and local-branch.ts for pre-PR diff analysis using metadata-only input.
C. Scoring System (src/scoring/)#
model.ts loads three model types from the scoringModelSnapshots database table: current_density_model, pending_saturation_model, and exponential_saturation_model . The scoring system supports both existing PRs and planned contributions via preview.ts, and pending-pr-scenarios.ts implements five scenario projections: current-gated, underlying-potential, after-clean-gate, after-pending-merges, and best-reasonable.
All scoring operations are deterministic; no AI inference is used. The scoring model is refreshed hourly from the upstream Gittensor ruleset.
D. Decision Pack Service (src/services/decision-pack.ts)#
The decision pack service aggregates multi-source data into per-contributor decision artifacts . It enforces a 6-hour freshness threshold (DECISION_PACK_MAX_AGE_MS) and a 15-second debounce window (DECISION_PACK_REBUILD_DEBOUNCE_MS) to prevent excessive rebuild storms .
Decision packs classify recommendations into five states: pursue, cleanup_first, maintainer_lane, avoid_for_now, and watch. Action kinds include PR cleanup/landing, new PR filing, issue discovery, and maintainer-specific work. Freshness states track whether a pack is fresh, stale, rebuilding, or missing.
E. Agent Orchestrator (src/services/agent-orchestrator.ts)#
The agent orchestrator implements a centralized deterministic pipeline: create → plan → preflight/prepare → explain → execute . It composes the data layer, external APIs (Gittensor, GitHub), signal builders, and the decision pack system .
Input types are AgentPlanRequest and AgentRunCreateRequest . Output is an AgentRunBundle containing the run record, action records, context snapshots, and an optional AI summary . The startAgentRun() function initiates execution by creating a run record with a plan_next_work payload and status queued, then enqueuing a run-agent job .
All orchestration logic is deterministic except for optional AI summarization, which is disabled by default.
F. GitHub Integration (src/github/)#
The GitHub integration layer consists of six modules:
backfill.ts: Syncs repos, issues, and PRs from GitHub's REST APIwebhook.ts: Handles incoming GitHub webhook eventsapp.ts: Manages GitHub App installation and token generationcommands.ts: Parses @... mention commands (help, preflight, blockers, duplicate-check, miner-context, next-action, reviewability, repo-fit, packet, queue-summary, review-now, needs-author, confirmed-miners, duplicate-clusters). The last five commands are maintainer-only queue digest commands that build from cached GitHub metadata rather than agent runscomments.ts: Posts public-safe intelligence comments to PRs/issueslabels.ts: Applies Gittensor labels based on repository settingspublic.ts: Fetches public GitHub user profiles
The public/private boundary is enforced at comment generation time using a forbidden-words list that prevents wallet, payout, and scoring terms from appearing in public GitHub comments.
G. Upstream & Registry (src/upstream/, src/registry/)#
upstream/ruleset.ts syncs the Gittensor registry, scoring model, and drift detection logic, then files GitHub issues for detected drift . The UpstreamDriftReports table tracks drift incidents with severity classification (none, low, medium, high, blocking) .
registry/sync.ts fetches and caches the Gittensor registry, including repo configs and emission shares. The registry snapshot is refreshed hourly and used to determine which repositories are registered for Gittensor contribution mining.
H. MCP Package (packages/gittensory-mcp)#
The @jsonbored/gittensory-mcp package (v0.3.0, Node >= 22) exposes 21 MCP tools in five categories: repo intelligence, PR preflight & scoring, contributor decisions, current branch analysis, and agent operations .
It also provides 13 CLI commands including login, logout, whoami, status, changelog, doctor, init-client, analyze-branch, preflight, and agent plan/status/explain/packet. Core dependencies are @modelcontextprotocol/sdk 1.26.0 and zod ^3.25.76 .
Local branch analysis uses metadata only — no source code is uploaded to the Worker API.
I. Database Layer (src/db/)#
The database uses Drizzle ORM with Cloudflare D1 (SQLite) . The schema spans 50+ tables across 16 migrations , grouped into six categories: GitHub integration (installations, repositories, repositorySettings), sync state (repoSyncState, repoSyncSegments), scoring (scoringModelSnapshots, scorePreviews, contributorEvidence), agent orchestration (agentRuns, agentActions, agentContextSnapshots), auth/compliance (authSessions, auditEvents), and analytics (productUsageEvents, productUsageDailyRollups) .
J. Queue Processor (src/queue/)#
The queue processor in processors.ts dispatches 20+ job types via a switch statement . Aggregate jobs like generate-signal-snapshots fan out to per-repo child jobs with staggered delays of 10–45 seconds to avoid overwhelming the queue .
K. Frontend & Extension (apps/)#
gittensory-ui is a TypeScript/Vite web application deployed as a Cloudflare Worker at https://gittensory.aethereal.dev/ . gittensory-extension is a Manifest V3 browser extension with a background service worker, content script, and authentication flow .
Both applications consume the Worker API and enforce the same public/private boundary logic used in GitHub comments.
Data Flow#
Gittensory moves data through the system via two primary input pathways: a local metadata-only path through the MCP client, and a remote path through the GitHub App and Worker API. The MCP client reads git metadata locally without uploading source code, then calls the Worker API with metadata-only payloads . The remote path begins with GitHub webhooks that trigger queue jobs, which invoke processors to backfill data from the GitHub API into D1 storage .
Scheduled Data Pipeline#
Cloudflare cron triggers run every 30 minutes to enqueue scheduled jobs . The scheduled handler dispatches three tiers of jobs based on timing :
- Every minute (30-min intervals):
backfill-registered-repos,repair-data-fidelity,refresh-installation-health - Every hour (minute 0):
refresh-registry,refresh-scoring-model,refresh-upstream-drift,rollup-product-usage - Every 6 hours (hour % 6 == 0):
generate-signal-snapshots,build-burden-forecasts,build-contributor-evidence,build-contributor-decision-packs,file-upstream-drift-issues
This three-tier schedule separates high-frequency sync jobs from expensive signal computation and decision pack assembly.
Queue Fan-Out Pattern#
Aggregate jobs without a specific repo fan out to per-repo child jobs with staggered delays to avoid thundering herd problems . For example, generate-signal-snapshots without a repoFullName enqueues one job per registered repository with a 10-second delay per index . Full-sync backfill jobs use a 45-second delay step, while light backfills use 15 seconds . Failed messages trigger message.retry() to allow Cloudflare Queues to re-deliver them .
Decision Pack Assembly#
The decision pack assembly flow aggregates multi-source data into contributor-specific decision artifacts :
- Fetch contributor profile from GitHub and Gittensor API
- Load scoring model snapshot and signal snapshots (queue-health, maintainer-lane, etc.)
- Build contributor evidence: PRs, issues, repo stats, language matches
- Compute role contexts, lane advice, and repo decisions
- Persist as timestamped signal snapshot with type
contributor-decision-pack
Decision packs enforce a 6-hour max age and debounce rebuilds with a 15-second minimum interval . A Map tracks pending rebuilds to prevent duplicate concurrent jobs . Batch jobs call loadDecisionPackSharedInputs() once and reuse the full-table datasets across all contributor logins instead of re-scanning per contributor .
Signal Snapshot Storage#
Signals are computed per-repo and persisted as timestamped snapshots with unique IDs . Nine signal types are generated per registered repository: queue-health, config-quality, label-audit, maintainer-lane, maintainer-cut-readiness, contributor-intake-health, issue-quality, contributor-outcome-history, and repo-outcome-patterns . Each snapshot includes a generatedAt timestamp and is stored in the signalSnapshots table. Freshness states—fresh, stale, partial, degraded—track data quality .
Scoring Data Flow#
The scoring model is cached in the scoringModelSnapshots table and loaded once per run via getOrCreateScoringModelSnapshot(). Score preview requests flow from API routes to scoring/preview.ts, which applies the active model to generate five-scenario scoreability results: current (gated), underlying potential, after clean-gate, after pending merges, and best reasonable . Model types—current density, pending saturation, exponential saturation—are auto-detected at runtime.
Public/Private Data Boundary#
Gittensory enforces a strict public/private boundary. A forbidden words list prevents sensitive data (wallet, payout, hotkey, raw trust score) from appearing in public GitHub comments . Private advisory data—score blockers, reward/risk context, reviewability packets—remains session-gated behind API authentication. Public-safe PR packets are generated by the agent orchestrator for safe sharing with maintainers.
Caching and Freshness Management#
Official miner detection results are cached with a 5-minute TTL for successful lookups and a 1-minute TTL when unavailable . The cache prevents redundant Gittensor API calls during high-frequency webhook processing. ETag and Last-Modified tracking for upstream sources minimizes redundant fetches during registry and model refresh. Decision packs are cached in the signalSnapshots table with a 6-hour max age; stale packs trigger rebuild jobs if enqueue is enabled.
System Organization#
Gittensory is organized as a TypeScript monorepo with a layered architecture that separates concerns across three primary workspaces: the Worker API backend, the MCP package, and two frontend applications. The repository root follows an npm workspace layout that enables shared tooling and coordinated versioning across all components .
Repository Structure#
The monorepo root contains four top-level code directories and shared configuration:
src/ # Worker API backend (16 subdirectories)
packages/gittensory-mcp/ # npm MCP package (@jsonbored/gittensory-mcp)
apps/gittensory-ui/ # web frontend (TypeScript/Vite)
apps/gittensory-extension/# browser extension (Manifest V3)
migrations/ # 16 Drizzle/D1 SQL migrations
scripts/ # utility and build scripts
test/ # test files
Configuration files at the root include wrangler.jsonc for Cloudflare Workers , drizzle.config.ts for database ORM, tsconfig.json for TypeScript, and vitest.config.ts for testing. Two changelog generators—cliff.toml for the main project and cliff.mcp.toml for the MCP package—maintain separate release histories. The repository uses .nvmrc to pin the Node version and renovate.json for automated dependency updates .
Worker API Module Layout#
The src/ directory organizes the Worker API into 16 subdirectories plus four root-level files :
Root files:
index.ts— entry point with fetch, queue, and scheduled handlerstypes.ts— 977 lines of shared TypeScript type definitions including discriminated union job typesqueue-intelligence.ts— PR prioritization logicenv.d.ts— Cloudflare Workers environment bindings
Core subdirectories:
api/— HTTP routes (routes.tswith 2,447 lines,workboard.ts)db/—client.ts,schema.ts, andrepositories.ts(3,500+ line data access layer)queue/—processors.tswith switch-based job dispatchersignals/—engine.tsplus modules for data-quality, reward-risk, local-branch, registration-readiness, contributor monitoring, and settings previewscoring/—model.ts,preview.ts,pending-pr-scenarios.tsservices/— agent-orchestrator, decision-pack, control-panel-roles, burden-forecast, mcp-compatibility, ai-summaries, client-telemetrygithub/— backfill, webhook, app, commands, comments, labels, public API clientupstream/—ruleset.tsfor sync and drift detectionregistry/— sync and normalize Gittensor registrygittensor/— upstream API clientbounties/— bounty metadata ingestionrules/— advisory generation (issue/PR advisories with findings and recommendations)mcp/—server.ts(MCP protocol handler)openapi/— OpenAPI spec generationauth/— github-oauth, rate-limit, securityutils/— crypto helpers, JSON utilities
MCP Package Structure#
The @jsonbored/gittensory-mcp package (v0.3.0) ships as a standalone npm module with Node >= 22 requirement :
packages/gittensory-mcp/
├── bin/gittensory-mcp.js # main CLI + MCP entry
├── lib/local-branch.js # local branch analysis
├── package.json
├── CHANGELOG.md
└── README.md
The package exposes 21 MCP tools via the Model Context Protocol and 13 CLI commands including login, logout, whoami, status, doctor, analyze-branch, preflight, and agent subcommands .
Configuration#
Cloudflare Workers configuration lives in wrangler.jsonc :
- D1 binding:
DB→ databasegittensory, migrations dirmigrations/ - Queue: producer
JOBS→gittensory-jobs(consumer: batch 10, timeout 5s) - Durable Objects:
RATE_LIMITERwith smart placement - Workers AI:
AIbinding (disabled by default:AI_SUMMARIES_ENABLED=false) - Custom domain:
gittensory-api.aethereal.dev - Cron trigger:
*/30 * * * *(every 30 minutes)
Code Organization Patterns#
Gittensory follows a layered architecture: HTTP routes in api/routes.ts call service-layer modules in services/, which compose signal builders from signals/ and scoring logic from scoring/, all backed by the data access layer in db/repositories.ts . This separation ensures deterministic business logic remains testable independent of I/O.
The system uses discriminated union job types in types.ts for type-safe async job dispatch . Each job type includes a type discriminator and a requestedBy field tracking the initiator ("schedule", "api", "test"). The queue processor in processors.ts switches on message.type to route jobs to domain-specific handlers .
Database tables store complex nested data as JSON in payload columns with queryable metadata fields extracted at the schema level. Operational tables include status fields implementing state machines and createdAt/updatedAt timestamps for time-series tracking. Analytical results are persisted as immutable timestamped snapshots with unique IDs.
Extension Points#
Developers adding new functionality follow these patterns:
- New MCP tools: Register in
bin/gittensory-mcp.jstool list - New job types: Add case to
processors.tsswitch and union member totypes.tsJobMessage - New signals: Create signal builder in
signals/and add toprocessJobfan-out inprocessors.ts - New GitHub commands: Extend command catalog in
github/commands.ts
The modular structure enables incremental feature development with clear boundaries between HTTP API, async job processing, signal generation, and data persistence layers.
Component Interactions#
Gittensory operates through three execution contexts: HTTP (synchronous request-response), Queue (asynchronous job processing), and Scheduled (periodic job dispatch). Each context has distinct communication patterns and responsibilities .
Execution Contexts#
1. HTTP context (fetch handler)
The Worker handles synchronous HTTP requests through the Hono routes in src/api/routes.ts. Requests flow from MCP clients, browser UI, or GitHub App webhooks through the service layer (agent-orchestrator, decision-pack, control-panel-roles) to the database layer . Responses return immediately with either computed data or queued job acknowledgments.
2. Queue context
Cloudflare Queues processes messages asynchronously in batches of up to 10 with a 5-second timeout . The queue handler (src/index.ts) dispatches each message to processJob(), which routes to domain-specific handlers . On error, messages are retried via message.retry() . API routes enqueue jobs via the JOBS binding, allowing long-running operations to proceed asynchronously without blocking HTTP responses.
3. Scheduled context
The cron trigger fires every 30 minutes, calling enqueueScheduledJobs() . Every execution enqueues backfill-registered-repos, repair-data-fidelity, and refresh-installation-health jobs . Hourly jobs (minute 0) include refresh-registry, refresh-scoring-model, refresh-upstream-drift, and rollup-product-usage . Every 6 hours (hour % 6 === 0), aggregate jobs spawn generate-signal-snapshots, build-burden-forecasts, build-contributor-evidence, build-contributor-decision-packs, and file-upstream-drift-issues . These aggregate jobs fan out to per-repo child jobs with staggered delays.
Communication Paths#
MCP communication
Coding agents (Claude, Cursor, Codex) or CLI users interact with the Worker API via @jsonbored/gittensory-mcp . The MCP package exposes 21 tools and 13 CLI commands over stdio or remote transport using @modelcontextprotocol/sdk . Each tool calls a specific Worker API endpoint at gittensory-api.aethereal.dev , transmitting metadata-only payloads. Authentication uses GitHub Device Flow, embedding session tokens in API requests.
GitHub App communication
GitHub events (PR opened/updated/commented, issue activity) trigger webhook POST requests to the Worker . The handler enqueues a job for asynchronous processing. processors.ts routes data events to github/backfill.ts for state synchronization and command events to github/commands.ts, which parses @... mentions and dispatches to appropriate services. Public-safe responses are written via github/comments.ts.
Agent orchestration flow
When an agent run is requested (via API or MCP), the orchestrator follows a deterministic pipeline :
startAgentRun()creates anagentRunrecord withstatus=queuedin the database- A
run-agentjob is enqueued - The job dispatcher calls
executeAgentRun() - The orchestrator fetches contributor evidence, loads signal snapshots, retrieves official Gittensor stats, and loads or rebuilds the decision pack
- Actions are generated using
DecisionActionKindtaxonomy and written toagentActionstable - Context snapshots are persisted to
agentContextSnapshotstable - The run record is updated to
status=completed - An
AgentRunBundle(run, actions, contexts, summary) is returned
Decision pack refresh protocol
On request, loadContributorDecisionPackForServing() checks decision pack freshness against a 6-hour maximum age . If stale, a rebuild is enqueued with a 15-second debounce . Pending rebuilds are tracked in a Map to deduplicate concurrent requests . Stale packs are returned immediately with a freshness: "rebuilding" flag while the rebuild proceeds asynchronously . This graceful degradation ensures contributors receive actionable recommendations even when snapshots are outdated.
Access Control#
Role-based gating
control-panel-roles.ts classifies users as miner, maintainer, owner, or operator . Decision pack data and private advisory information are gated by session scope checks. OAuth and device-flow sessions are restricted to admin allowlists. Repo-level command authorization policies control which users can invoke GitHub App commands via @... mentions.
Public/private boundary
The Worker enforces a strict separation between private scoreability data and public GitHub comments. A forbidden-words list (wallet, payout, farming, hotkey, coldkey, etc.) is applied to all public-safe summaries . Session-scoped API routes return private advisory data. GitHub comment handlers produce public-safe output with no sensitive scoring or identity context.
External Integrations#
GitHub API
The Worker calls GitHub REST and GraphQL endpoints via @octokit/core , authenticating with GitHub App installation tokens or OAuth sessions. github/backfill.ts syncs repos, issues, and PRs. github/webhook.ts handles inbound events.
Gittensor API
The gittensor/ module fetches official contributor snapshots, repo statistics, and scoring models from the upstream Gittensor network. This data is cached and compared with local state to detect drift.
Upstream ruleset sources
HTTP GET requests with ETag/Last-Modified caching retrieve registry, scoring model, and ruleset data from the Gittensor upstream repository.
Operation Modes#
Synchronous operations
HTTP request/response cycles handle score previews, local branch analysis, decision pack reads, and repo context fetches. These complete within the Worker's execution time limit.
Asynchronous operations
Long-running computations (registry refresh, signal snapshot generation, burden forecasts, contributor evidence building, agent runs, upstream drift detection) are enqueued as jobs and processed via the queue handler.
Periodic operations
Scheduled jobs run every 30 minutes (backfill), every hour (registry, model, drift, analytics), and every 6 hours (signal snapshots, forecasts, evidence, decision packs, drift issues). Each periodic job enqueues child jobs that execute over the following minutes.
Technology Stack#
Gittensory is built on a modern edge-first architecture, combining Cloudflare Workers infrastructure with TypeScript and a carefully selected set of frameworks and libraries optimized for deterministic, privacy-first operations.
Runtime & Infrastructure#
The system runs on Cloudflare Workers with three handler types: fetch (HTTP requests), queue (async job processing), and scheduled (cron triggers). Workers are configured with Node.js compatibility and smart placement for optimal performance. The API is deployed at gittensory-api.aethereal.dev, while the frontend serves from gittensory.aethereal.dev. A cron trigger fires every 30 minutes (*/30 * * * *) to initiate scheduled jobs.
Rate limiting is implemented via Cloudflare Durable Objects with a RATE_LIMITER class using smart placement to maintain per-user state across requests.
Data Layer#
Database: Cloudflare D1 (SQLite at the edge) with a binding named DB pointing to the gittensory database. The schema comprises 50+ tables across 16 migrations, spanning GitHub integration, sync state, scoring, agent orchestration, auth/compliance, and analytics.
ORM: Drizzle ORM ^0.45.0 provides type-safe query construction and schema management.
Queue: Cloudflare Queues handles asynchronous job processing through the gittensory-jobs queue with a maximum batch size of 10 and 5-second timeout.
Web Framework & Protocols#
HTTP Routing: Hono ^4.12.23 — a lightweight, edge-first web framework handles all REST API routing in the Worker environment.
MCP Protocol: @modelcontextprotocol/sdk 1.26.0 implements the Model Context Protocol, enabling coding agents to interact with Gittensory via a standardized interface. The MCP package requires Node >= 22.
GitHub Integration: @octokit/core ^7.0.6 provides GitHub REST and GraphQL API client functionality for syncing repositories, issues, PRs, and handling webhook events.
Schema & Validation#
Zod: zod ^3.25.76 validates runtime types for all API inputs and MCP tool schemas, ensuring type safety at system boundaries.
OpenAPI: @asteasolutions/zod-to-openapi ^7.3.4 automatically generates OpenAPI specifications from Zod schemas, maintaining consistency between validation and documentation.
Optional AI Layer#
Gittensory includes an optional AI layer using Cloudflare Workers AI with the @cf/meta/llama-3.1-8b-instruct-fp8-fast model. Both AI summaries and public comments are disabled by default, preserving the system's deterministic core while offering opt-in AI-assisted features.
Deterministic-Summary Rewrite Layer#
The optional AI layer implements a rewrite pattern that clarifies deterministic signal bundles into friendlier prose when enabled. This approach maintains the deterministic-first philosophy: AI never decides facts—it only restates compact structured signals that the system has already computed.
Core functions:
rewriteSignalBundleWithAi()— Generic rewrite function accepting signal bundles and fallback text. The returnedtextis always safe to use: disabled, unavailable, quota-exceeded, unsafe, and error paths return the caller-supplied deterministic template.rewritePublicPrIntelligenceComment()— Public-surface wrapper used by the GitHub App PR intelligence comment. Preserves the sticky-comment marker and guarantees the deterministic body is posted whenever AI produces unsafe output or is unavailable.buildPublicCommentSignalBundle()— Builds compact, source-free signal bundles (counts, levels, booleans, role context, public finding titles) that deliberately exclude PR titles, bodies, diffs, and source contents to prevent repository source from reaching the AI provider.
Safety guarantees:
- Deterministic templates remain authoritative; AI rewrites are optional enhancements
- Falls back to templates when AI is disabled, unavailable, over quota, or produces unsafe output
- All public AI output routes through the canonical public/private sanitizer (
sanitizePublicComment) - Signal bundles carry only public-safe structured data—no source code, diff contents, or sensitive scoring context
- Uses existing
AI_SUMMARIES_ENABLEDandAI_PUBLIC_COMMENTS_ENABLEDflags (both default to false) - Quota-limited via the existing
AI_DAILY_NEURON_BUDGETconfiguration
Integration:
Wired into the GitHub App's public PR intelligence comment workflow in src/queue/processors.ts. The deterministic comment is built first, then optionally rewritten by passing a source-free signal bundle to the rewrite layer. On any non-ok outcome, the unchanged deterministic body is posted to GitHub.
Frontend Applications#
Web UI: The gittensory-ui application uses TypeScript and Vite for build tooling and deploys as a Cloudflare Worker at gittensory.aethereal.dev.
Browser Extension: The gittensory-extension follows Manifest V3 standards with a background service worker, content scripts, and options page for browser-native GitHub integration.
Testing & Quality Assurance#
Vitest serves as the test runner with separate configurations for unit tests, integration tests, Workers-specific tests, and contract tests. The project enforces a 97% coverage requirement in continuous integration. The @cloudflare/vitest-pool-workers ^0.16.10 package enables testing in a Workers-like environment.
Developer Tooling#
Changelog Generation: git-cliff ^2.13.1 generates changelogs with separate configurations for the main workspace (cliff.toml) and MCP package (cliff.mcp.toml).
Secrets Scanning: gitleaks (.gitleaks.toml) prevents accidental credential commits.
Dependency Management: Renovate (renovate.json) automates dependency updates.
Node Version: .nvmrc pins the Node version to ensure consistent environments across development and CI.
CI/CD: GitHub Actions (.github/) orchestrates continuous integration workflows.
Key Scripts#
The package.json defines critical development and deployment workflows:
- Development:
npm run dev— local Workers development server via wrangler - Deployment:
npm run deploy— deploys API to Cloudflare Workers;npm run ui:deploy— builds and deploys UI - Database:
npm run db:migrate:local/npm run db:migrate:remote— applies migrations locally or to production - Testing:
npm run test:ci— full CI suite (type checking, 97% coverage, builds, linting, security audit) - Type Generation:
npm run cf-typegen— generates TypeScript bindings for Cloudflare Workers
Language & Build Tools#
TypeScript: Strict TypeScript (^5.9.3) throughout the codebase with Node >= 22 as the baseline runtime.
Wrangler: ^4.95.0 — Cloudflare's deployment and development CLI.
Drizzle Kit: ^0.31.7 — migration generation and schema management.
tsx: ^4.22.4 — TypeScript execution for scripts.
The technology stack prioritizes determinism, edge-native performance, and privacy-first design while maintaining comprehensive test coverage and automated quality gates.