manage-database-usage

How to correctly access the Doltgres manage database with branch-scoped connections. Use when reading or writing manage data (agents, tools, projects, credentials, triggers, evaluators, etc.). Triggers on: manage database, withRef, c.get('db'), manageDbPool, branch checkout, doltgres, ref-scope, branchScopedDb, AgentsManageDatabaseClient.

1,059 stars

Best use case

manage-database-usage is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

How to correctly access the Doltgres manage database with branch-scoped connections. Use when reading or writing manage data (agents, tools, projects, credentials, triggers, evaluators, etc.). Triggers on: manage database, withRef, c.get('db'), manageDbPool, branch checkout, doltgres, ref-scope, branchScopedDb, AgentsManageDatabaseClient.

Teams using manage-database-usage should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/manage-database-usage/SKILL.md --create-dirs "https://raw.githubusercontent.com/inkeep/agents/main/.agents/skills/manage-database-usage/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/manage-database-usage/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How manage-database-usage Compares

Feature / Agentmanage-database-usageStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

How to correctly access the Doltgres manage database with branch-scoped connections. Use when reading or writing manage data (agents, tools, projects, credentials, triggers, evaluators, etc.). Triggers on: manage database, withRef, c.get('db'), manageDbPool, branch checkout, doltgres, ref-scope, branchScopedDb, AgentsManageDatabaseClient.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Manage Database Usage (Doltgres)

The manage database is a Doltgres instance (PostgreSQL with Git-like versioning). Every read or write **must** happen on the correct branch. Failing to scope connections to a branch will read/write the wrong data.

---

## Branch Naming

Each project has its own main branch: `<tenantId>_<projectId>_main`.

Custom branches follow: `<tenantId>_<projectId>_<branchName>`.

Connections default to the `main` branch (which is empty/root), so you **must always** check out the correct project branch before any operation.

---

## Decision Table

| Where is your code? | What to use |
|---|---|
| `/manage` route handler | `c.get('db')` — middleware handles checkout and commit |
| `/run` or `/evals` route handler | `withRef(manageDbPool, resolvedRef, (db) => ...)` |
| Service class or utility outside manage routes | `withRef(manageDbPool, resolvedRef, (db) => ...)` |
| Already inside a `withRef` callback | Use the `db` from the callback argument directly |

---

## Mechanism 1: Middleware (`/manage` routes)

The `branchScopedDbMiddleware` (in `agents-api/src/middleware/branchScopedDb.ts`) runs on all `/manage` routes. It:

1. Acquires a dedicated connection from the pool
2. Checks out the correct branch (from the request's resolved `ref`)
3. Creates a Drizzle client scoped to that connection
4. Injects it into context as `'db'`
5. Executes the route handler
6. Auto-commits on success for write operations
7. Cleans up: checks out `main` and releases connection

### Usage

```typescript
async (c) => {
  const db: AgentsManageDatabaseClient = c.get('db');
  const { tenantId, projectId } = c.req.valid('param');

  const tools = await listTools(db)({
    scopes: { tenantId, projectId },
  });

  return c.json({ data: tools });
}
```

### Rules

- **ALWAYS** use `c.get('db')` inside manage routes — never import and use the global `manageDbClient` directly (it isn't checked out to any branch)
- **Don't manually commit** — the middleware auto-commits successful writes and resets on failure
- The `resolvedRef` is also available via `c.get('resolvedRef')` if needed

---

## Mechanism 2: `withRef` (outside manage routes)

Use `withRef` from `@inkeep/agents-core` (defined in `packages/agents-core/src/dolt/ref-scope.ts`) when accessing manage data from `/run`, `/evals`, services, or other packages.

### Read

```typescript
import { withRef } from '@inkeep/agents-core';
import manageDbPool from '../data/db/manageDbPool';

const agent = await withRef(manageDbPool, resolvedRef, (db) =>
  getFullAgent(db)({
    scopes: { tenantId, projectId, agentId },
  })
);
```

### Write with auto-commit

```typescript
await withRef(
  manageDbPool,
  resolvedRef,
  async (db) => {
    await updateAgent(db, agentId, data);
  },
  { commit: true, commitMessage: 'Update agent config' }
);
```

### Batching operations

Batch multiple operations in a single `withRef` to use one connection and one checkout:

```typescript
const result = await withRef(
  manageDbPool,
  resolvedRef,
  async (db) => {
    await createCredential(db, credData);
    await updateTool(db, toolId, { credentialId });
    return { success: true };
  },
  {
    commit: true,
    commitMessage: 'Link credential to tool',
    author: { name: 'oauth-flow', email: 'oauth@inkeep.com' },
  }
);
```

### Rules

- `withRef` acquires, scopes, and releases the connection — don't manage connections yourself
- For reads, omit the options (no `commit` needed)
- For writes, pass `{ commit: true }` with an appropriate `commitMessage`
- On failure, if `commit: true`, uncommitted changes are automatically reset

---

## Obtaining a `resolvedRef`

Most code paths already have a `resolvedRef` available:

- **Hono routes**: `c.get('resolvedRef')` (set by ref middleware)
- **Agent runtime**: `this.executionContext.resolvedRef`
- **Service params**: passed as a function parameter

If you need to resolve a branch ref manually:

```typescript
import { getProjectScopedRef, resolveRef } from '@inkeep/agents-core';

const projectScopedRef = getProjectScopedRef(tenantId, projectId, 'main');
const resolvedRef = await resolveRef(agentsManageDbClient)(projectScopedRef);
```

The `ResolvedRef` type has three fields:

```typescript
type ResolvedRef = {
  type: 'branch' | 'tag' | 'commit';
  name: string;  // e.g. "acme_proj_123_main"
  hash: string;  // commit hash
};
```

---

## Key Files

| File | Purpose |
|---|---|
| `agents-api/src/middleware/branchScopedDb.ts` | Middleware for `/manage` routes |
| `packages/agents-core/src/dolt/ref-scope.ts` | `withRef` wrapper and nesting detection |
| `packages/agents-core/src/dolt/ref-middleware.ts` | Ref resolution middleware (resolves `ref` query param) |
| `packages/agents-core/src/dolt/ref-helpers.ts` | Helper functions (`getProjectScopedRef`, `resolveProjectMainRef`) |
| `packages/agents-core/src/validation/dolt-schemas.ts` | `ResolvedRef` type and Zod schemas |
| `agents-api/src/data/db/manageDbPool.ts` | Connection pool singleton |
| `agents-api/src/data/db/manageDbClient.ts` | Global Drizzle client (don't use directly in scoped contexts) |

Related Skills

weather-safety-guardrails

1059
from inkeep/agents

Keep activity suggestions safe and respect local conditions

structured-itinerary-responses

1059
from inkeep/agents

Present time-aware itineraries with clear actions and citations

write-docs

1059
from inkeep/agents

Write or update documentation for the Inkeep docs site (agents-docs package). Use when: creating new docs, modifying existing docs, introducing features that need documentation, touching MDX files in agents-docs/content/. Triggers on: docs, documentation, MDX, agents-docs, write docs, update docs, add page, new tutorial, API reference, integration guide.

web-design-guidelines

1059
from inkeep/agents

Review UI code for Web Interface Guidelines compliance. Use when asked to "review my UI", "check accessibility", "audit design", "review UX", or "check my site against best practices".

vercel-react-best-practices

1059
from inkeep/agents

React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.

vercel-composition-patterns

1059
from inkeep/agents

React composition patterns that scale. Use when refactoring components with boolean prop proliferation, building flexible component libraries, or designing reusable APIs. Triggers on tasks involving compound components, render props, context providers, or component architecture. Includes React 19 API changes.

slack-manifest

1059
from inkeep/agents

Guide for modifying the Slack app manifest — adding/removing bot scopes, event subscriptions, slash commands, shortcuts, or OAuth config. Ensures single-source-of-truth via slack-app-manifest.json. Triggers on: slack scope, bot scope, slack manifest, slack permission, add slack scope, remove slack scope, slack event subscription, slash command, slack OAuth, slack-app-manifest.

shadcn

1059
from inkeep/agents

Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI. Provides project context, component docs, and usage examples. Applies when working with shadcn/ui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for "shadcn init", "create an app with --preset", or "switch to --preset".

route-handler-authoring

1059
from inkeep/agents

Conventions for writing Hono route handlers that forward validated bodies to DAL functions, and CRUD test requirements for round-trip field persistence. Triggers on: creating new routes, modifying handlers, adding CRUD tests, route handler patterns, field-picking, spread pattern, DAL forwarding, check:route-handler-patterns, CI check failure.

product-surface-areas

1059
from inkeep/agents

Consolidated dependency graph of Inkeep customer-facing surface areas (UIs, CLIs, SDKs, APIs, protocols, config formats). Example use: as a prd-time (planning/brainstorming phase) or post-change checklist to understand the full scope of side-effects or what making one change to the product means for the rest. Use whenever you need to understand the "ripple" out effects of any change.

pr-review-appsec-vendored

1059
from inkeep/agents

Stack-specific application security checklist for this repo's frameworks: better-auth, SpiceDB/AuthZed, and Next.js RSC. Extends the generalizable pr-review-appsec agent with patterns that require framework-specific knowledge to detect. Loaded by pr-review-appsec.

next-upgrade

1059
from inkeep/agents

Upgrade Next.js to the latest version following official migration guides and codemods