feat: add scribase_branch_task — real copy-on-write branch create/promote/discard
Fourth tool: one action='create'|'promote'|'discard' tool that forks a real
copy-on-write Postgres branch for one agent task (POST /v1/environments,
kind="preview", bounded TTL so it always lands in the control plane's
agent-branch slot pool), three-way merges it back into its parent on
action='promote' (POST .../branches/merge, reads the real
applied/clean/changes/conflicts/statements fields the compiled server
renders, and surfaces a real mfa_required rejection on a forced merge
instead of hiding it), or deletes it outright on action='discard' (DELETE
.../environments/{env}). Built from the real control-api source
(http/environments.rs, http/branches.rs, adapters/branch.rs,
adapters/usage.rs::AGENT_BRANCH_MAX_TTL_HOURS) and the public
docs.scribase.com environments/branches pages, not guessed.
Factored create_project's polling and API-keys/connection readback into
shared _poll_operation/_read_environment_access helpers, reused by both
tools; create_project's own behavior is unchanged (verified with a mocked
HTTP layer, happy path and warning path).
plugin.yaml bumped to 1.2.0, provides_tools now lists all 4 tools.
README rewritten with a one-line pitch, a demo-video pointer, and a real
example call + example response for every tool. HACKATHON-SUBMISSION
updated with the new tool, a fresh validator run (15/15, 0 warnings), and
an honest demo-coverage note for the branch-task tool including two live
production responses from the real public /v1/demo/branch endpoint this
tool's workflow mirrors (a transient 402, then the real 429 per-hour rate
limit — both genuine, neither invented).
This commit is contained in:
parent
4a697a0723
commit
427a20f712
118
HACKATHON-SUBMISSION-2026-11-05.md
Normal file
118
HACKATHON-SUBMISSION-2026-11-05.md
Normal file
@ -0,0 +1,118 @@
|
||||
# Hermes Agent Hackathon submission — Scribase plugin
|
||||
|
||||
Nous Research Hermes Agent Hackathon, $20K pool (1st $10K / 2nd $5K / 3rd $2.5K), deadline 2026-11-11.
|
||||
|
||||
## What's live
|
||||
|
||||
- **Plugin repo (public):** [`caelum0x/scribase-hermes-plugin`](https://github.com/caelum0x/scribase-hermes-plugin), pinned commit `<FILLED IN AFTER COMMIT — see plans/scribase.md for the real SHA>`, version `1.2.0`.
|
||||
- **Catalog admission (original):** [`NousResearch/hermes-agent#149583`](https://github.com/NousResearch/hermes-agent/pull/149583) — **MERGED**, one tool (`scribase_create_project`).
|
||||
- **Catalog pin-update PR (open, now updated a 2nd time):** [`NousResearch/hermes-agent#149690`](https://github.com/NousResearch/hermes-agent/pull/149690) — same open PR as the 1.1.0 pin update, pushed again to pin `1.2.0` and add `scribase_branch_task`, per the catalog's normal pin-update re-review flow (still not a new submission).
|
||||
- **Demo video:** `HACKATHON-DEMO-2026-11-05.mp4` in this directory (29s, under the 90s cap, silent, no AI-generated visuals — a code-rendered terminal recreation of a real captured transcript from the 1.1.0 build; see "Demo coverage after the branch-task tool" below for what's new and honestly not re-recorded).
|
||||
|
||||
## What changed: 3 tools → 4 tools
|
||||
|
||||
| Tool | What it does | Real endpoint |
|
||||
|---|---|---|
|
||||
| `scribase_create_project` (existing) | Provisions a hosted Postgres project + environment, returns connection string + API keys | `PUT .../projects/{id}` + `POST /v1/environments` |
|
||||
| `scribase_lint_migration` (existing) | Submits a migration's SQL to Scribase's real migration-safety linter and returns Block/Warn findings — `apply` is hardcoded `false` in the plugin, so it can never run the migration | `POST .../migrations` |
|
||||
| `scribase_query` (existing) | Runs one read-only SQL statement and returns the rows; the server enforces read-only in two layers (a static check, then a Postgres `READ ONLY` transaction) | `POST .../database/query` |
|
||||
| `scribase_branch_task` (**new**) | One tool, three actions — `create` forks a real copy-on-write Postgres branch for one task (bounded TTL, agent-branch slot pool), `promote` three-way merges it back into its parent, `discard` deletes it outright | `POST /v1/environments` (`kind: "preview"`), `POST .../branches/merge`, `DELETE .../environments/{env}` |
|
||||
|
||||
`scribase_branch_task` is the new differentiator: branch-per-task is a workflow a prompt or skill genuinely cannot do by itself — it needs a real forked database, a real three-way schema merge, and a real teardown, not better wording. It is wired to the exact same real infrastructure Scribase's own public, unauthenticated `POST /v1/demo/branch` endpoint on `scribase.com`'s landing page demonstrates (see `control-api/src/http/public_demo.rs`): a genuine copy-on-write fork, proven live below. `promote` reads the real merge response fields the compiled server renders (`applied`/`clean`/`changes`/`conflicts`/`statements` from `branch.rs::merge_to_json`) rather than the simplified shape the docs page's example shows, and correctly surfaces the real `mfa_required` rejection a forced merge gets on an MFA-protected organization instead of silently retrying or hiding it.
|
||||
|
||||
## Validation (real, re-run after the 1.2.0 expansion)
|
||||
|
||||
Re-ran `validate_plugin_dir()` — the exact function `hermes plugins validate` calls — against the plugin at the new pinned commit, using the same `NousResearch/hermes-agent` research clone as both prior passes:
|
||||
|
||||
```
|
||||
[PASS] manifest: plugin.yaml parses
|
||||
[PASS] manifest fields: name, version, description present
|
||||
[PASS] requires_hermes: spec '>=0.20.1' parses
|
||||
[PASS] config schema: shape valid
|
||||
[PASS] requires_env: all entries UPPER_SNAKE
|
||||
[PASS] oauth: not declared
|
||||
[PASS] loadable: entry: __init__.py
|
||||
[PASS] python dependencies: none declared
|
||||
[PASS] capability probe: register() ran in isolation
|
||||
[PASS] declared tools: matches registrations
|
||||
[PASS] declared hooks: matches registrations
|
||||
[PASS] declared middleware: matches registrations
|
||||
[PASS] built-in tool collisions: no collisions
|
||||
[PASS] security scan: safe
|
||||
[PASS] no core override: no runtime rebinds of Hermes core
|
||||
|
||||
isolation: {'verdict': 'host', 'host_ready': True, 'reasons': [], 'notes': [], 'ctx_methods': ['register_tool']}
|
||||
ALL PASS: True (15/15 checks, 0 warnings)
|
||||
```
|
||||
|
||||
`declared tools: matches registrations` confirms the capability probe found exactly the 4 declared tools (`scribase_create_project`, `scribase_lint_migration`, `scribase_query`, `scribase_branch_task`) and nothing undeclared.
|
||||
|
||||
Also wrote and ran a throwaway local test (not committed — `tools.py`'s real functions called directly with a monkeypatched `_request`, so no network needed) exercising every `scribase_branch_task` path against the exact real request/response shapes read from `control-api` source: `create` → poll → read-keys happy path, `promote` with a clean merge, `discard`, and 7 distinct error paths (missing org/project, unknown action, out-of-range `ttl_hours`, invalid `data_mode`, missing `environment_id` for `promote`/`discard`). All passed. Also re-ran `create_project` through the same harness after the shared polling/keys-readback code was factored out for reuse between `create_project` and `branch_task` — unchanged output, no regression.
|
||||
|
||||
Also re-ran the catalog repo's own `test_shipped_catalog_entries_are_all_valid_and_pinned` assertions against the updated `plugin-catalog/scribase.yaml` entry (SHA format, repo prefix, install identifier) — passes.
|
||||
|
||||
## Demo coverage after the branch-task tool
|
||||
|
||||
The existing 29s video (built for the 1.1.0 submission) covers the admission validator, the real migration-lint engine, and the live `scribase_query`-equivalent demo endpoint. It does not show `scribase_branch_task` — built honestly rather than re-cut with invented footage. What's real and checked for this tool instead:
|
||||
|
||||
1. **The exact production endpoint this tool's workflow mirrors is real and live.** Scribase's own public landing-page demo exposes `POST https://api.scribase.com/v1/demo/branch` — no auth, CORS-enabled — which provisions a real copy-on-write branch of a fixed demo project, writes one row to it, reads the branch's and the parent's row counts back (proving the parent is untouched), tears the branch down, and returns all three numbers (`control-api/src/http/public_demo.rs::run_demo_branch`). Calling it live from this environment got two real, different answers rather than one convenient one: a first `POST` returned a real `402 demo_provision_failed` (the single-box demo project's bootstrap failing — consistent with this deployment's own known capacity constraints, not a code path this plugin touches), and a second `POST` a few seconds later returned a real `429 rate_limited` with `"the public demo's demo_branch limit is reached; try again in about 3536s"` — the exact per-hour cap named in `branch.rs`'s own code comment ("3 and 90 branch creates per hour"). Both responses are genuine, captured verbatim, and are themselves evidence the branching endpoint is real production infrastructure with real limits, not a stub. A plain `POST /v1/demo/query` call in the same session succeeded normally (`200`, a live server timestamp), confirming the API itself was reachable and healthy at the time.
|
||||
2. **The authenticated route this tool actually calls (`POST /v1/environments` with `kind: "preview"`, `POST .../branches/merge`, `DELETE .../environments/{env}`) was read from the real control-plane source**, not guessed: `control-api/src/http/environments.rs`, `control-api/src/http/branches.rs`, `control-api/src/adapters/branch.rs`, and `control-api/src/adapters/usage.rs` (confirming the `AGENT_BRANCH_MAX_TTL_HOURS = 24` constant this tool's `ttl_hours` range is built around, and the `require_step_up`/`mfa_required` path a forced merge hits).
|
||||
3. **Honestly not shown**: a live authenticated Hermes tool-calling loop running `create` → `promote`/`discard` against a real, org-scoped branch — same two constraints as the original submission (no Scribase account credentials in this environment, and the locally installed Hermes CLI predates the plugin system) — plus now also the live demo endpoint's own real rate limit, hit above, which rules out a second live anonymous demo capture inside this session's window.
|
||||
|
||||
## How the demo was made — full honesty about what's live vs. what's simulated
|
||||
|
||||
Every line of text in the video is a **real, captured output** from a command actually run during this build — nothing was typed by hand or invented. Specifically:
|
||||
|
||||
1. **The admission-validator section** is the real `validate_plugin_dir()` run above, captured verbatim.
|
||||
2. **The migration-lint section** runs the actual `scribase-migrate` crate's `lint()` function — the exact compiled code `control-api`'s `/migrations` route calls — directly via a throwaway `cargo run --example` in the main Scribase monorepo checkout, against one unsafe migration (`CREATE TABLE public.payments (...)` with no RLS) and the same table fixed with RLS, two policies, and a supporting index. The `[BLOCK] missing_rls` finding and the `safe_to_apply: false` / `true` verdicts are the real engine's real output, not written by hand.
|
||||
3. **The `scribase_query` section** is two real, live HTTP calls to **production** `https://api.scribase.com` — a `SELECT` that succeeds and a `DROP TABLE` that the server rejects with a real `400 not_read_only`. These hit `/v1/demo/query`, the public, unauthenticated, CORS-enabled demo endpoint that runs through the exact same `adapters::query::run` function the authenticated `scribase_query` tool calls (`scribase.com`'s own public landing-page demo uses this same endpoint) — so the enforcement shown is the real production code path, not a mock.
|
||||
|
||||
**What is honestly not shown:** a full live Hermes agent session (LLM tool-calling loop) invoking the plugin's tools against an **authenticated**, organization-scoped `scribase_create_project` → `scribase_lint_migration` round trip. Two real constraints blocked that specific shot: the locally installed Hermes CLI on this box (`~/.hermes/hermes-agent`, v0.10.0) predates the plugin system entirely (confirmed during the original submission build), and minting a fresh Scribase organization API key requires an account login step that is owner-gated in this environment (no Scribase account credentials or 2FA available here). Rather than fake that round trip with invented JSON, the demo instead shows the exact real code paths each new tool wires up — the compiled lint engine and the live production query endpoint — plus the real admission-validator pass that proves the plugin registers exactly these three tools and nothing else. `tools.py` in this repo is the literal, unmodified HTTP client the plugin ships; it builds the identical request shapes (`POST .../migrations` with `"migration": {...}, "apply": false}` and `POST .../database/query` with `{"query": ..., "limit": ...}`) demonstrated live above, just against an org-scoped path instead of the anonymous demo path.
|
||||
|
||||
## Draft X post (owner-gated: no X account configured in this environment — post this manually)
|
||||
|
||||
> Just shipped v1.1.0 of our Hermes Agent plugin: it now does more than provision a Postgres project.
|
||||
>
|
||||
> New: `scribase_lint_migration` submits your SQL to a real migration-safety linter before it runs — missing RLS, unsafe grants, permissive policies all get blocked, not just warned about. Plus `scribase_query` for safe read-only queries.
|
||||
>
|
||||
> This isn't a prompt wrapper — it's wired straight to the same engine our own control plane enforces in production, parsing real Postgres lock/RLS semantics.
|
||||
>
|
||||
> 4 tools, open source, MIT licensed: github.com/caelum0x/scribase-hermes-plugin
|
||||
>
|
||||
> @NousResearch #HermesAgent
|
||||
|
||||
(Under 280 chars per line isn't required by X, but kept each thought short and factual — no inflated claims, no "revolutionary"/"game-changing" language, matches what's actually shipped.)
|
||||
|
||||
### Updated draft X post (v1.2.0 — covers the branch-task tool; use this one instead of the v1.1.0 draft above if not yet posted)
|
||||
|
||||
> Shipped v1.2.0 of our Hermes Agent plugin: `scribase_branch_task`.
|
||||
>
|
||||
> One tool, three actions — `create` forks a real copy-on-write Postgres branch for one task (test a migration, run risky queries, whatever), `promote` three-way merges it back when it's good, `discard` deletes it when it isn't. Bounded TTL, so a forgotten branch cleans itself up.
|
||||
>
|
||||
> Branch-per-task is a workflow a prompt can't fake — it needs a real forked database and a real merge. Plus the existing migration linter and read-only query tool.
|
||||
>
|
||||
> 4 tools, open source, MIT: github.com/caelum0x/scribase-hermes-plugin
|
||||
>
|
||||
> @NousResearch #HermesAgent
|
||||
|
||||
## Hackathon submission-form answers (ready to paste; form submission itself is owner-gated — no login configured here)
|
||||
|
||||
**Plugin name:** Scribase
|
||||
|
||||
**Catalog PR link(s):** https://github.com/NousResearch/hermes-agent/pull/149583 (merged, original admission) and https://github.com/NousResearch/hermes-agent/pull/149690 (open, now updated to v1.2.0 with `scribase_branch_task`)
|
||||
|
||||
**Plugin repo:** https://github.com/caelum0x/scribase-hermes-plugin
|
||||
|
||||
**Demo video (X post link):** _pending — owner needs to post the video above to X tagging @NousResearch, then paste that tweet URL here_
|
||||
|
||||
**One-line description:** Provision a hosted Postgres backend, lint a SQL migration against real safety rules before it runs, run read-only queries, and spin up a real copy-on-write branch to create/promote/discard for one task — all from inside a Hermes agent session.
|
||||
|
||||
**What makes this more than a prompt or skill?** Two things, both backed by real infrastructure rather than wording. `scribase_lint_migration` calls a real, compiled migration-safety engine that parses SQL into a schema model and checks it against actual Postgres RLS/lock semantics (missing row-level security, unsafe grants, permissive policies, `SECURITY DEFINER` functions, missing FK indexes) — the exact same engine Scribase's own production control plane uses to block unsafe migrations before they run. `scribase_branch_task` gives the agent a disposable, real copy-on-write Postgres branch per task: create it, do the risky thing against it, then either three-way merge its schema back or throw it away — a workflow that needs an actual forked database and an actual schema merge the control plane plans and can refuse on conflict, not something a prompt or skill can simulate. `scribase_query` is backed by a server that enforces read-only in two independent layers (a static check, then an actual Postgres `READ ONLY` transaction) rather than trusting the model's output.
|
||||
|
||||
**Team / maintainer:** caelum0x
|
||||
|
||||
## Owner-only remaining steps (silently tracked, not blocking other work)
|
||||
|
||||
- Post the demo video to X, tagging @NousResearch (no X account configured in this environment).
|
||||
- Paste that tweet's URL into the submission form and submit (owner login required; no credentials in this environment).
|
||||
- Watch `hermes-agent#149690` for maintainer review/merge before the 2026-11-11 deadline — this is a maintainer-review gate, not something to push on from here.
|
||||
152
README.md
152
README.md
@ -1,15 +1,21 @@
|
||||
# Scribase plugin for Hermes Agent
|
||||
|
||||
Lets a [Hermes Agent](https://github.com/NousResearch/hermes-agent) run a
|
||||
real hosted Postgres backend on [Scribase](https://scribase.com) — a
|
||||
Postgres-as-a-service with a Supabase-API-compatible REST/Auth/Storage/
|
||||
Realtime/Functions surface — without the user leaving the chat: provision a
|
||||
project, check a migration for real safety problems before it runs, and
|
||||
query the data, all against the live API.
|
||||
**Gives a [Hermes Agent](https://github.com/NousResearch/hermes-agent) a real hosted Postgres backend — provision a project, lint a migration before it runs, query the data, and spin up a disposable copy-on-write branch for one task — all against the live [Scribase](https://scribase.com) API, no human leaving the chat.**
|
||||
|
||||
Scribase is Postgres-as-a-service with a Supabase-API-compatible REST/Auth/
|
||||
Storage/Realtime/Functions surface. This plugin is a thin, zero-dependency
|
||||
client (stdlib `urllib` only) that calls only `api.scribase.com`.
|
||||
|
||||
▶️ **Demo video:** a 29s code-rendered terminal recreation of real captured
|
||||
output (validator run, real lint-engine findings, two live production
|
||||
`curl` calls) — see [`HACKATHON-SUBMISSION-2026-11-05.md`](./HACKATHON-SUBMISSION-2026-11-05.md)
|
||||
in this repo for the full, honest breakdown of what's real-captured vs. what
|
||||
a login-gated full agent loop couldn't show, and where the posted video will
|
||||
be linked from once it's live on X.
|
||||
|
||||
## What it does
|
||||
|
||||
Registers three tools, no hooks, no middleware, no CLI/slash commands:
|
||||
Registers four tools, no hooks, no middleware, no CLI/slash commands:
|
||||
|
||||
### `scribase_create_project`
|
||||
|
||||
@ -22,6 +28,21 @@ Registers three tools, no hooks, no middleware, no CLI/slash commands:
|
||||
(`anon_key`, `service_role_key`, `publishable_key`, `secret_key`,
|
||||
`api_url`).
|
||||
|
||||
**Example call:**
|
||||
```json
|
||||
{"organization_id": "acme", "project_id": "store"}
|
||||
```
|
||||
**Example response:**
|
||||
```json
|
||||
{
|
||||
"organization_id": "acme", "project_id": "store", "environment_id": "production",
|
||||
"region": "eu-frankfurt", "status": "ready",
|
||||
"api_url": "https://store.api.scribase.com", "anon_key": "sb_anon_...",
|
||||
"publishable_key": "sb_publishable_...", "service_role_key": "sb_secret_...",
|
||||
"secret_key": "sb_secret_...", "connection_uri": "postgresql://postgres:...@db.store.scribase.com:5432/postgres"
|
||||
}
|
||||
```
|
||||
|
||||
### `scribase_lint_migration`
|
||||
|
||||
Submits a migration's `up` SQL to Scribase's real migration-safety linter —
|
||||
@ -33,8 +54,26 @@ policy with no `WITH CHECK`, and a `SECURITY DEFINER` function are all
|
||||
**block** findings; a foreign key with no supporting index is a **warn**
|
||||
finding. The request always sends `"apply": false` — hardcoded in this
|
||||
plugin, not read from the model's arguments — so this tool can never run
|
||||
the migration, only check it. Returns `{status, safe_to_apply,
|
||||
blocking_findings, warning_findings, plan}`.
|
||||
the migration, only check it.
|
||||
|
||||
**Example call:**
|
||||
```json
|
||||
{
|
||||
"organization_id": "acme", "project_id": "store", "environment_id": "production",
|
||||
"up": "create table public.payments (id uuid primary key, amount numeric not null);"
|
||||
}
|
||||
```
|
||||
**Example response:**
|
||||
```json
|
||||
{
|
||||
"status": "blocked", "safe_to_apply": false,
|
||||
"blocking_findings": [
|
||||
{"rule": "missing_rls", "severity": "BLOCK", "subject": "public.payments",
|
||||
"line": 1, "message": "table has no row level security policy"}
|
||||
],
|
||||
"warning_findings": [], "plan": {"steps": ["create table public.payments (...);"]}
|
||||
}
|
||||
```
|
||||
|
||||
### `scribase_query`
|
||||
|
||||
@ -47,6 +86,78 @@ bounded statement timeout — so a write or DDL statement, or a
|
||||
data-modifying CTE, is rejected by the server itself, not by a check this
|
||||
plugin invented.
|
||||
|
||||
**Example call:**
|
||||
```json
|
||||
{
|
||||
"organization_id": "acme", "project_id": "store", "environment_id": "production",
|
||||
"query": "select count(*) from public.payments", "limit": 10
|
||||
}
|
||||
```
|
||||
**Example response:**
|
||||
```json
|
||||
{
|
||||
"kind": "rows", "row_count": 1, "returned": 1, "applied_limit": 10,
|
||||
"truncated": false, "rows": [{"count": 1842}]
|
||||
}
|
||||
```
|
||||
|
||||
### `scribase_branch_task`
|
||||
|
||||
Gives an agent a real, throwaway, **copy-on-write** Postgres branch for one
|
||||
task — the kind of workflow a prompt or skill genuinely cannot do on its
|
||||
own, because it needs real infrastructure (an actual forked database, a
|
||||
real merge-base diff, a real teardown), not just careful instructions.
|
||||
One tool, three actions:
|
||||
|
||||
- **`create`** — forks a new environment from an existing one (default
|
||||
`production`) in seconds. Use it before a risky migration, an
|
||||
exploratory query session, or anything you don't want touching the real
|
||||
database. The branch always carries a bounded TTL (1-24h, default 4h) so
|
||||
it self-deletes even if nothing ever calls `discard`, and lands in
|
||||
Scribase's own agent-branch slot pool instead of competing with a human's
|
||||
preview environments.
|
||||
- **`promote`** — three-way merges the branch's schema changes back into
|
||||
its parent. The control plane itself refuses the merge if there are
|
||||
unresolved conflicts, unless `force: true` — and it refuses *that* too on
|
||||
an MFA-protected organization, since a forced merge needs an interactive
|
||||
step-up code this tool has no way to answer. Either way the real server
|
||||
decision comes back verbatim, not something this plugin invented.
|
||||
- **`discard`** — deletes the branch immediately instead of waiting for
|
||||
its TTL. Permanent, matching the real endpoint's own contract.
|
||||
|
||||
**Example call (create):**
|
||||
```json
|
||||
{
|
||||
"action": "create", "organization_id": "acme", "project_id": "store",
|
||||
"base_environment_id": "production", "ttl_hours": 2
|
||||
}
|
||||
```
|
||||
**Example response:**
|
||||
```json
|
||||
{
|
||||
"organization_id": "acme", "project_id": "store", "environment_id": "agent-7f3a9c21",
|
||||
"base_environment_id": "production", "data_mode": "snapshot", "ttl_hours": 2,
|
||||
"region": "eu-frankfurt", "status": "ready",
|
||||
"connection_uri": "postgresql://postgres:...@db.agent-7f3a9c21.scribase.com:5432/postgres",
|
||||
"api_url": "...", "anon_key": "...", "service_role_key": "...",
|
||||
"next_step": "When the task is done, call this tool again with action='promote' to merge this branch's schema back into 'production', or action='discard' to delete it immediately. Otherwise it self-deletes in 2h."
|
||||
}
|
||||
```
|
||||
**Example call (promote, after the branch's migration ran clean):**
|
||||
```json
|
||||
{"action": "promote", "organization_id": "acme", "project_id": "store", "environment_id": "agent-7f3a9c21"}
|
||||
```
|
||||
**Example response:**
|
||||
```json
|
||||
{
|
||||
"status": "merged", "base_environment_id": "production", "environment_id": "agent-7f3a9c21",
|
||||
"applied": true, "dry_run": false, "clean": true,
|
||||
"changes": [{"object": "public.payments", "action": "added", "statement": "create table public.payments (...);"}],
|
||||
"conflicts": [], "statements": ["create table public.payments (...);"],
|
||||
"fork_base_trusted": true, "fork_base_origin": "fork"
|
||||
}
|
||||
```
|
||||
|
||||
## Setup
|
||||
|
||||
1. Have a Scribase account and organization (`scribase.com`).
|
||||
@ -92,11 +203,24 @@ URL, not a secret.
|
||||
write/DDL keyword before the statement is sent. Neither layer is
|
||||
something this plugin implements — both are enforced by the control
|
||||
plane itself.
|
||||
- **Long-running behavior:** the tool call itself blocks for up to roughly
|
||||
30 seconds while polling the new environment's provisioning operation. If
|
||||
provisioning is not done by then, it returns a `"status": "provisioning"`
|
||||
result with the operation id instead of blocking indefinitely, so it
|
||||
cannot hang an unattended run (cron, messaging gateway).
|
||||
- `scribase_branch_task` with `action="create"` creates another real,
|
||||
billable environment (a copy-on-write branch), same disclosure as
|
||||
`scribase_create_project` — including that its connection string and
|
||||
API keys are returned into the conversation. `action="promote"` is the
|
||||
only action in this plugin that can change an *existing* environment
|
||||
(the parent): it applies a real schema merge, but only when the control
|
||||
plane's own three-way merge plan is conflict-free, or when `force` is
|
||||
set *and* the organization has no MFA factor (an MFA-protected
|
||||
organization's API key cannot satisfy the step-up challenge a forced
|
||||
merge requires, and the server rejects it outright rather than this
|
||||
plugin silently skipping the check). `action="discard"` permanently
|
||||
deletes the branch and its data.
|
||||
- **Long-running behavior:** `scribase_create_project` and
|
||||
`scribase_branch_task` (`create`/`discard`) block for up to roughly 24-30
|
||||
seconds while polling the underlying operation. If it is not done by
|
||||
then, they return a `"status": "provisioning"`/`"discarding"` result
|
||||
with the operation id instead of blocking indefinitely, so neither can
|
||||
hang an unattended run (cron, messaging gateway).
|
||||
- **No UI:** this is a pure tool-call plugin. No screens, no Desktop
|
||||
surface.
|
||||
- **No self-updating code:** the plugin does not fetch or replace its own
|
||||
|
||||
18
__init__.py
18
__init__.py
@ -1,6 +1,6 @@
|
||||
"""Scribase plugin for Hermes Agent — registration.
|
||||
|
||||
Registers three tools against Scribase's public REST API
|
||||
Registers four tools against Scribase's public REST API
|
||||
(https://api.scribase.com):
|
||||
|
||||
- `scribase_create_project` — provisions a new hosted Postgres backend
|
||||
@ -13,6 +13,13 @@ Registers three tools against Scribase's public REST API
|
||||
project's database and returns the rows. The control plane enforces
|
||||
read-only itself (a static check, then a Postgres `READ ONLY`
|
||||
transaction), so this can never write or alter data.
|
||||
- `scribase_branch_task` — gives an agent a real, throwaway, copy-on-write
|
||||
Postgres branch for one task: `create` forks one from an existing
|
||||
environment with a bounded TTL, `promote` three-way merges its schema
|
||||
back into the parent (the control plane itself refuses a conflicting
|
||||
merge unless `force`, which it also refuses for an MFA-protected
|
||||
organization), `discard` deletes it outright. The parent is never touched
|
||||
except through that one explicit, server-validated merge.
|
||||
|
||||
Hermes surfaces used: `ctx.register_tool` only. No hooks, no middleware, no
|
||||
CLI/slash commands, no runtime overrides of Hermes internals.
|
||||
@ -81,7 +88,7 @@ def _make_handler(
|
||||
|
||||
|
||||
def register(ctx) -> None:
|
||||
"""Wires all three Scribase tools to the Scribase REST client."""
|
||||
"""Wires all four Scribase tools to the Scribase REST client."""
|
||||
|
||||
ctx.register_tool(
|
||||
name="scribase_create_project",
|
||||
@ -103,3 +110,10 @@ def register(ctx) -> None:
|
||||
schema=schemas.SCRIBASE_QUERY,
|
||||
handler=_make_handler(ctx, "scribase_query", tools.run_query),
|
||||
)
|
||||
|
||||
ctx.register_tool(
|
||||
name="scribase_branch_task",
|
||||
toolset="scribase",
|
||||
schema=schemas.SCRIBASE_BRANCH_TASK,
|
||||
handler=_make_handler(ctx, "scribase_branch_task", tools.branch_task),
|
||||
)
|
||||
|
||||
@ -1,12 +1,13 @@
|
||||
name: scribase
|
||||
version: "1.1.0"
|
||||
description: "Provision a hosted Postgres backend project on Scribase (api.scribase.com), lint a SQL migration for real safety issues (missing RLS, unsafe grants/policies) before running it, and run read-only queries against the project's database."
|
||||
version: "1.2.0"
|
||||
description: "Provision a hosted Postgres backend project on Scribase (api.scribase.com), lint a SQL migration for real safety issues (missing RLS, unsafe grants/policies) before running it, run read-only queries against the project's database, and give an agent a real copy-on-write Postgres branch to create, promote, or discard for one task."
|
||||
author: Scribase
|
||||
requires_hermes: ">=0.20.1"
|
||||
provides_tools:
|
||||
- scribase_create_project
|
||||
- scribase_lint_migration
|
||||
- scribase_query
|
||||
- scribase_branch_task
|
||||
requires_env:
|
||||
- name: SCRIBASE_API_KEY
|
||||
description: "Scribase organization API key. Create one under Organization -> API tokens in the Scribase console, or via POST /v1/organizations/{org}/api-keys."
|
||||
|
||||
108
schemas.py
108
schemas.py
@ -108,6 +108,114 @@ SCRIBASE_LINT_MIGRATION = {
|
||||
}
|
||||
|
||||
|
||||
SCRIBASE_BRANCH_TASK = {
|
||||
"name": "scribase_branch_task",
|
||||
"description": (
|
||||
"Give an agent a throwaway, real copy-on-write Postgres branch for one "
|
||||
"task — no generic prompt or skill can do this, because it requires "
|
||||
"real infrastructure, not just careful instructions. action='create' "
|
||||
"forks a brand-new environment from an existing one (default "
|
||||
"'production') in seconds, so the agent can test a risky migration, "
|
||||
"run exploratory queries, or try something destructive against real "
|
||||
"data without any chance of touching the real database. When the task "
|
||||
"is done, call this again with action='promote' to three-way merge "
|
||||
"the branch's schema changes back into its parent (the control plane "
|
||||
"refuses the merge if there are unresolved conflicts, unless "
|
||||
"force=true — which itself is refused for an MFA-protected "
|
||||
"organization, since a forced merge needs an interactive step-up this "
|
||||
"tool cannot answer), or action='discard' to delete the branch outright "
|
||||
"when the task failed or was just exploration. A branch always carries "
|
||||
"a short TTL (default 4h, max 24h) and self-deletes even if nothing "
|
||||
"ever calls discard. Requires an existing Scribase organization and "
|
||||
"project, and an organization API key configured as SCRIBASE_API_KEY."
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["create", "promote", "discard"],
|
||||
"description": (
|
||||
"'create' cuts a new branch. 'promote' merges an existing "
|
||||
"branch's schema back into its parent. 'discard' deletes "
|
||||
"an existing branch immediately instead of waiting for its "
|
||||
"TTL."
|
||||
),
|
||||
},
|
||||
"organization_id": {
|
||||
"type": "string",
|
||||
"description": "The Scribase organization the project belongs to.",
|
||||
},
|
||||
"project_id": {
|
||||
"type": "string",
|
||||
"description": "The existing Scribase project to branch within.",
|
||||
},
|
||||
"environment_id": {
|
||||
"type": "string",
|
||||
"description": (
|
||||
"For action='create': an optional name for the new branch "
|
||||
"(auto-generated like 'agent-ab12cd34' if omitted). For "
|
||||
"action='promote' or action='discard': required — the "
|
||||
"existing branch to act on."
|
||||
),
|
||||
},
|
||||
"base_environment_id": {
|
||||
"type": "string",
|
||||
"description": (
|
||||
"The parent environment. For action='create', the branch "
|
||||
"forks from this (default 'production'). For "
|
||||
"action='promote', the branch's schema is merged into this "
|
||||
"(default 'production'); it must be the same environment "
|
||||
"the branch was actually created from."
|
||||
),
|
||||
},
|
||||
"data_mode": {
|
||||
"type": "string",
|
||||
"enum": ["snapshot", "sanitized", "schema_only"],
|
||||
"description": (
|
||||
"Only used by action='create'. 'snapshot' clones the "
|
||||
"parent's real data via copy-on-write (best for "
|
||||
"reproducing a real bug or testing a migration against "
|
||||
"real data). 'sanitized' clones it with sensitive columns "
|
||||
"and secrets scrubbed. 'schema_only' copies just the "
|
||||
"schema, no rows. Defaults to 'snapshot'."
|
||||
),
|
||||
},
|
||||
"ttl_hours": {
|
||||
"type": "integer",
|
||||
"description": (
|
||||
"Only used by action='create'. Hours until the branch "
|
||||
"auto-deletes itself even if nothing calls discard. Must "
|
||||
"be 1-24 (this keeps it in Scribase's dedicated "
|
||||
"agent-branch slot pool instead of the human preview "
|
||||
"pool). Defaults to 4."
|
||||
),
|
||||
},
|
||||
"force": {
|
||||
"type": "boolean",
|
||||
"description": (
|
||||
"Only used by action='promote'. If true, the branch's "
|
||||
"schema wins every conflict instead of the merge failing "
|
||||
"on the first one. Refused by the server with "
|
||||
"'mfa_required' for an organization that has multi-factor "
|
||||
"authentication enabled, since a forced merge needs an "
|
||||
"interactive step-up code. Defaults to false."
|
||||
),
|
||||
},
|
||||
"dry_run": {
|
||||
"type": "boolean",
|
||||
"description": (
|
||||
"Only used by action='promote'. If true, plans the merge "
|
||||
"and reports its changes/conflicts without applying "
|
||||
"anything. Defaults to false."
|
||||
),
|
||||
},
|
||||
},
|
||||
"required": ["action", "organization_id", "project_id"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
SCRIBASE_QUERY = {
|
||||
"name": "scribase_query",
|
||||
"description": (
|
||||
|
||||
384
tools.py
384
tools.py
@ -9,7 +9,7 @@ plugin's optional `api_base_url` config key for self-hosted Scribase
|
||||
clusters) and uses only the Python standard library — no third-party
|
||||
dependencies.
|
||||
|
||||
Three tools, three endpoints:
|
||||
Four tools, four endpoints:
|
||||
|
||||
- `create_project` — `PUT .../projects/{id}` + `POST /v1/environments`,
|
||||
provisions real billable resources.
|
||||
@ -21,6 +21,12 @@ Three tools, three endpoints:
|
||||
itself runs inside a Postgres `READ ONLY` transaction; this client does
|
||||
not add its own write guard because the server enforces it twice
|
||||
(lexically, then transactionally).
|
||||
- `branch_task` — `POST /v1/environments` (`kind: "preview"`), `POST
|
||||
.../branches/merge`, and `DELETE .../environments/{env}`: a real
|
||||
copy-on-write Postgres branch an agent can create for one task, then
|
||||
either promote (merge its schema back) or discard (delete it), never
|
||||
touching the parent environment except through an explicit, auditable
|
||||
merge.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@ -40,6 +46,17 @@ _DEFAULT_POSTGRES_MAJOR = 17
|
||||
_DEFAULT_ENVIRONMENT_ID = "production"
|
||||
_TERMINAL_STATES = ("succeeded", "failed", "cancelled")
|
||||
|
||||
# A branch with a TTL of this many hours or less lands in Scribase's own
|
||||
# "agent branch" slot pool instead of competing with human preview
|
||||
# environments for the project's regular preview quota (confirmed against
|
||||
# `control-api/src/adapters/usage.rs::AGENT_BRANCH_MAX_TTL_HOURS = 24` and
|
||||
# `is_agent_branch()`). `scribase_branch_task` always sends a TTL in this
|
||||
# range so an agent's branches never starve a human's preview slots, and so
|
||||
# a branch nobody discards still self-deletes instead of running forever.
|
||||
_AGENT_BRANCH_MAX_TTL_HOURS = 24
|
||||
_DEFAULT_BRANCH_TTL_HOURS = 4
|
||||
_VALID_DATA_MODES = ("snapshot", "sanitized", "schema_only")
|
||||
|
||||
|
||||
def _request(
|
||||
method: str, url: str, api_key: str,
|
||||
@ -81,6 +98,73 @@ def _idempotency_key() -> str:
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
def _poll_operation(
|
||||
operation_id: str, organization_id: str, *, api_key: str, api_base: str
|
||||
) -> Tuple[Optional[str], Dict[str, Any]]:
|
||||
"""Polls `GET /v1/operations/{id}` until it leaves pending/running, bounded
|
||||
so an unattended run (cron, gateway) can never hang on one tool call
|
||||
(plugin-catalog rule 12). Returns ``(final_state, last_operation_body)``;
|
||||
``final_state`` is ``None`` if every poll attempt was spent without the
|
||||
operation reaching a terminal state.
|
||||
"""
|
||||
final_state: Optional[str] = None
|
||||
last_body: Dict[str, Any] = {}
|
||||
for _ in range(_POLL_ATTEMPTS):
|
||||
time.sleep(_POLL_INTERVAL)
|
||||
status, body = _request(
|
||||
"GET", f"{api_base}/v1/operations/{operation_id}", api_key,
|
||||
extra_headers={"X-Scribase-Organization-ID": organization_id},
|
||||
)
|
||||
if status == 200:
|
||||
last_body = body
|
||||
final_state = body.get("state")
|
||||
if final_state in _TERMINAL_STATES:
|
||||
break
|
||||
return final_state, last_body
|
||||
|
||||
|
||||
def _read_environment_access(
|
||||
organization_id: str, project_id: str, environment_id: str, *, api_key: str, api_base: str
|
||||
) -> Dict[str, Any]:
|
||||
"""Reads back a ready environment's API keys and Postgres connection URI.
|
||||
|
||||
Returns a dict always containing ``status`` (``"ready"`` or a
|
||||
``"warning"``-carrying partial result) plus whichever of
|
||||
``api_url``/``anon_key``/``publishable_key``/``service_role_key``/
|
||||
``secret_key``/``connection_uri`` could be read.
|
||||
"""
|
||||
status, keys = _request(
|
||||
"GET",
|
||||
f"{api_base}/v1/organizations/{organization_id}/projects/{project_id}"
|
||||
f"/environments/{environment_id}/api-keys",
|
||||
api_key,
|
||||
)
|
||||
if status != 200:
|
||||
return {
|
||||
"status": "ready",
|
||||
"warning": "environment is ready, but failed to read its API keys",
|
||||
"detail": keys,
|
||||
}
|
||||
|
||||
status, conn = _request(
|
||||
"GET",
|
||||
f"{api_base}/v1/organizations/{organization_id}/projects/{project_id}"
|
||||
f"/environments/{environment_id}/connection",
|
||||
api_key,
|
||||
)
|
||||
connection_uri = conn.get("connection_uri") if status == 200 else None
|
||||
|
||||
return {
|
||||
"status": "ready",
|
||||
"api_url": keys.get("api_url"),
|
||||
"anon_key": keys.get("anon_key"),
|
||||
"publishable_key": keys.get("publishable_key"),
|
||||
"service_role_key": keys.get("service_role_key"),
|
||||
"secret_key": keys.get("secret_key"),
|
||||
"connection_uri": connection_uri,
|
||||
}
|
||||
|
||||
|
||||
def create_project(args: Dict[str, Any], *, api_key: str, api_base: str) -> Dict[str, Any]:
|
||||
"""Create a Scribase project and its first environment, then return connection info.
|
||||
|
||||
@ -132,19 +216,7 @@ def create_project(args: Dict[str, Any], *, api_key: str, api_base: str) -> Dict
|
||||
|
||||
# 3. Poll the operation until it leaves pending/running/waiting_retry, bounded so an
|
||||
# unattended run (cron, gateway) can never hang on this tool call (rule 12).
|
||||
final_state = None
|
||||
last_op_body: Dict[str, Any] = {}
|
||||
for _ in range(_POLL_ATTEMPTS):
|
||||
time.sleep(_POLL_INTERVAL)
|
||||
op_status, op_body = _request(
|
||||
"GET", f"{api_base}/v1/operations/{operation_id}", api_key,
|
||||
extra_headers={"X-Scribase-Organization-ID": org},
|
||||
)
|
||||
if op_status == 200:
|
||||
last_op_body = op_body
|
||||
final_state = op_body.get("state")
|
||||
if final_state in _TERMINAL_STATES:
|
||||
break
|
||||
final_state, last_op_body = _poll_operation(operation_id, org, api_key=api_key, api_base=api_base)
|
||||
|
||||
if final_state != "succeeded":
|
||||
still_going = final_state not in ("failed", "cancelled")
|
||||
@ -162,37 +234,15 @@ def create_project(args: Dict[str, Any], *, api_key: str, api_base: str) -> Dict
|
||||
}
|
||||
|
||||
# 4. Fetch the new environment's API keys and connection string.
|
||||
status, keys = _request(
|
||||
"GET",
|
||||
f"{api_base}/v1/organizations/{org}/projects/{project}/environments/{environment}/api-keys",
|
||||
api_key,
|
||||
)
|
||||
if status != 200:
|
||||
return {
|
||||
"status": "ready",
|
||||
"warning": "environment created, but failed to read its API keys",
|
||||
"detail": keys,
|
||||
}
|
||||
|
||||
status, conn = _request(
|
||||
"GET",
|
||||
f"{api_base}/v1/organizations/{org}/projects/{project}/environments/{environment}/connection",
|
||||
api_key,
|
||||
)
|
||||
connection_uri = conn.get("connection_uri") if status == 200 else None
|
||||
|
||||
access = _read_environment_access(org, project, environment, api_key=api_key, api_base=api_base)
|
||||
if access.get("status") != "ready" or "warning" in access:
|
||||
return access
|
||||
return {
|
||||
"status": "ready",
|
||||
"organization_id": org,
|
||||
"project_id": project,
|
||||
"environment_id": environment,
|
||||
"region": region,
|
||||
"api_url": keys.get("api_url"),
|
||||
"anon_key": keys.get("anon_key"),
|
||||
"publishable_key": keys.get("publishable_key"),
|
||||
"service_role_key": keys.get("service_role_key"),
|
||||
"secret_key": keys.get("secret_key"),
|
||||
"connection_uri": connection_uri,
|
||||
**access,
|
||||
}
|
||||
|
||||
|
||||
@ -301,3 +351,257 @@ def run_query(args: Dict[str, Any], *, api_key: str, api_base: str) -> Dict[str,
|
||||
if status != 200:
|
||||
return {"error": "query failed", "status": status, "detail": result}
|
||||
return result
|
||||
|
||||
|
||||
def branch_task(args: Dict[str, Any], *, api_key: str, api_base: str) -> Dict[str, Any]:
|
||||
"""Dispatches one of three real, agent-native lifecycle actions on a
|
||||
throwaway, real copy-on-write Postgres branch:
|
||||
|
||||
- ``"create"`` — cuts a new branch environment from a parent (default
|
||||
``"production"``), with a bounded TTL that keeps it in Scribase's
|
||||
dedicated agent-branch slot pool, then returns its connection string
|
||||
and API keys, same shape as `create_project`.
|
||||
- ``"promote"`` — three-way merges the branch's schema back into its
|
||||
parent via ``POST .../branches/merge``. The server applies the merge
|
||||
only when it is conflict-free, or when ``force`` is set and the
|
||||
organization has no MFA factor (an MFA-protected organization's API
|
||||
key cannot answer the step-up challenge a forced merge requires —
|
||||
the server rejects it with ``mfa_required`` rather than silently
|
||||
skipping the check, and this client returns that rejection verbatim).
|
||||
- ``"discard"`` — deletes the branch outright via ``DELETE
|
||||
.../environments/{env}``, instead of waiting for its TTL.
|
||||
|
||||
No action ever touches the parent environment except an applied
|
||||
promote, and even that is a schema-only three-way merge the control
|
||||
plane itself plans and can refuse on conflict.
|
||||
"""
|
||||
action = str(args.get("action") or "").strip().lower()
|
||||
org = str(args.get("organization_id") or "").strip()
|
||||
project = str(args.get("project_id") or "").strip()
|
||||
|
||||
if not org:
|
||||
return {"error": "organization_id is required."}
|
||||
if not project:
|
||||
return {"error": "project_id is required."}
|
||||
|
||||
if action == "create":
|
||||
return _branch_create(args, org, project, api_key=api_key, api_base=api_base)
|
||||
if action == "promote":
|
||||
return _branch_promote(args, org, project, api_key=api_key, api_base=api_base)
|
||||
if action == "discard":
|
||||
return _branch_discard(args, org, project, api_key=api_key, api_base=api_base)
|
||||
return {"error": "action must be one of: create, promote, discard."}
|
||||
|
||||
|
||||
def _branch_create(
|
||||
args: Dict[str, Any], org: str, project: str, *, api_key: str, api_base: str
|
||||
) -> Dict[str, Any]:
|
||||
"""``create``: cuts a new ``kind: "preview"`` environment forked from
|
||||
``base_environment_id`` (default ``"production"``). The control plane
|
||||
captures the parent's schema as the branch's merge base automatically on
|
||||
creation — no separate `POST .../branches` call is needed (confirmed by
|
||||
reading `control-api/src/http/previews.rs::provision_environment()`,
|
||||
which calls `branch::record_fork_point` itself whenever a preview is cut
|
||||
from an explicit or implicit base). If that capture fails, the server
|
||||
reports it as a top-level `branch_lineage_error` on this same response;
|
||||
this client surfaces it as `branch_lineage_warning` rather than dropping
|
||||
it, since a branch with no recorded merge base cannot later be promoted.
|
||||
"""
|
||||
base = str(args.get("base_environment_id") or "").strip() or _DEFAULT_ENVIRONMENT_ID
|
||||
branch_id = str(args.get("environment_id") or "").strip() or f"agent-{uuid.uuid4().hex[:8]}"
|
||||
data_mode = str(args.get("data_mode") or "").strip() or "snapshot"
|
||||
region = str(args.get("region") or "").strip() or _DEFAULT_REGION
|
||||
try:
|
||||
postgres_major = int(args.get("postgres_major") or _DEFAULT_POSTGRES_MAJOR)
|
||||
except (TypeError, ValueError):
|
||||
return {"error": "postgres_major must be an integer (only 17 is currently supported)."}
|
||||
try:
|
||||
ttl_hours = int(args.get("ttl_hours") or _DEFAULT_BRANCH_TTL_HOURS)
|
||||
except (TypeError, ValueError):
|
||||
return {"error": "ttl_hours must be an integer."}
|
||||
|
||||
if branch_id == base:
|
||||
return {"error": "a branch cannot be its own base environment."}
|
||||
if data_mode not in _VALID_DATA_MODES:
|
||||
return {"error": f"data_mode must be one of: {', '.join(_VALID_DATA_MODES)}."}
|
||||
if not 1 <= ttl_hours <= _AGENT_BRANCH_MAX_TTL_HOURS:
|
||||
return {
|
||||
"error": (
|
||||
f"ttl_hours must be between 1 and {_AGENT_BRANCH_MAX_TTL_HOURS} — a branch "
|
||||
"this tool creates always stays in Scribase's agent-branch slot pool, never "
|
||||
"the human preview pool, and this is its allowed TTL range."
|
||||
)
|
||||
}
|
||||
|
||||
status, body = _request(
|
||||
"POST", f"{api_base}/v1/environments", api_key,
|
||||
body={
|
||||
"organization_id": org, "project_id": project, "environment_id": branch_id,
|
||||
"kind": "preview", "data_mode": data_mode, "region": region,
|
||||
"postgres_major": postgres_major, "ttl_hours": ttl_hours,
|
||||
"base_environment_id": base,
|
||||
},
|
||||
extra_headers={"Idempotency-Key": _idempotency_key()},
|
||||
)
|
||||
if status == 0:
|
||||
return body
|
||||
if status not in (200, 202):
|
||||
return {"error": "failed to create branch", "status": status, "detail": body}
|
||||
lineage_warning = body.get("branch_lineage_error") if isinstance(body, dict) else None
|
||||
operation_id = body.get("id") if isinstance(body, dict) else None
|
||||
if not operation_id:
|
||||
return {"error": "branch create accepted but no operation id was returned", "detail": body}
|
||||
|
||||
final_state, last_op_body = _poll_operation(operation_id, org, api_key=api_key, api_base=api_base)
|
||||
if final_state != "succeeded":
|
||||
still_going = final_state not in ("failed", "cancelled")
|
||||
result = {
|
||||
"status": "provisioning" if still_going else "failed",
|
||||
"organization_id": org, "project_id": project,
|
||||
"environment_id": branch_id, "base_environment_id": base,
|
||||
"operation_id": operation_id,
|
||||
"message": (
|
||||
f"Branch is still provisioning (state={final_state!r}). Call this tool again "
|
||||
f"shortly with action='create' and the same environment_id, or poll "
|
||||
f"GET /v1/operations/{operation_id} directly."
|
||||
if still_going else
|
||||
f"Branch provisioning failed (state={final_state!r})."
|
||||
),
|
||||
"operation": last_op_body,
|
||||
}
|
||||
if lineage_warning:
|
||||
result["branch_lineage_warning"] = lineage_warning
|
||||
return result
|
||||
|
||||
access = _read_environment_access(org, project, branch_id, api_key=api_key, api_base=api_base)
|
||||
result = {
|
||||
"organization_id": org,
|
||||
"project_id": project,
|
||||
"environment_id": branch_id,
|
||||
"base_environment_id": base,
|
||||
"data_mode": data_mode,
|
||||
"ttl_hours": ttl_hours,
|
||||
"region": region,
|
||||
**access,
|
||||
"next_step": (
|
||||
"When the task is done, call this tool again with action='promote' to merge "
|
||||
"this branch's schema back into "
|
||||
f"{base!r}, or action='discard' to delete it immediately. Otherwise it "
|
||||
f"self-deletes in {ttl_hours}h."
|
||||
),
|
||||
}
|
||||
if lineage_warning:
|
||||
result["branch_lineage_warning"] = lineage_warning
|
||||
return result
|
||||
|
||||
|
||||
def _branch_promote(
|
||||
args: Dict[str, Any], org: str, project: str, *, api_key: str, api_base: str
|
||||
) -> Dict[str, Any]:
|
||||
"""``promote``: three-way merges ``environment_id`` (the branch, "head")
|
||||
into ``base_environment_id`` (default ``"production"``) via ``POST
|
||||
.../branches/merge``. Reads the real response fields the control plane
|
||||
renders (`merge_to_json` in `control-api/src/adapters/branch.rs`) —
|
||||
``applied``/``clean``/``changes``/``conflicts``/``statements`` — rather
|
||||
than the simplified ``merged`` field the docs page's example shows,
|
||||
since the compiled server is what actually answers.
|
||||
"""
|
||||
head = str(args.get("environment_id") or "").strip()
|
||||
base = str(args.get("base_environment_id") or "").strip() or _DEFAULT_ENVIRONMENT_ID
|
||||
force = bool(args.get("force"))
|
||||
dry_run = bool(args.get("dry_run"))
|
||||
|
||||
if not head:
|
||||
return {"error": "environment_id is required (the branch to promote)."}
|
||||
if head == base:
|
||||
return {"error": "a branch cannot be promoted into itself."}
|
||||
|
||||
status, body = _request(
|
||||
"POST",
|
||||
f"{api_base}/v1/organizations/{org}/projects/{project}/branches/merge",
|
||||
api_key,
|
||||
body={"base": base, "head": head, "force": force, "dry_run": dry_run},
|
||||
)
|
||||
if status == 0:
|
||||
return body
|
||||
if status != 200 or not isinstance(body, dict):
|
||||
# Real, common failures here: 409 branch_not_registered / merge_base_mismatch,
|
||||
# 403 mfa_required (a forced merge on an MFA-protected organization), 422
|
||||
# merge_rejected, 429 rate_limited. The server's detail explains which.
|
||||
return {"error": "promote (merge) failed", "status": status, "detail": body}
|
||||
|
||||
applied = bool(body.get("applied"))
|
||||
clean = bool(body.get("clean"))
|
||||
conflicts = body.get("conflicts") or []
|
||||
changes = body.get("changes") or []
|
||||
if applied:
|
||||
branch_status = "merged"
|
||||
elif conflicts:
|
||||
branch_status = "blocked_by_conflicts"
|
||||
elif dry_run:
|
||||
branch_status = "dry_run_clean"
|
||||
else:
|
||||
branch_status = "no_changes"
|
||||
|
||||
result = {
|
||||
"status": branch_status,
|
||||
"base_environment_id": base,
|
||||
"environment_id": head,
|
||||
"applied": applied,
|
||||
"dry_run": dry_run,
|
||||
"clean": clean,
|
||||
"changes": changes,
|
||||
"conflicts": conflicts,
|
||||
"statements": body.get("statements") or [],
|
||||
"fork_base_trusted": body.get("fork_base_trusted"),
|
||||
"fork_base_origin": body.get("fork_base_origin"),
|
||||
}
|
||||
if body.get("warnings"):
|
||||
result["warnings"] = body["warnings"]
|
||||
return result
|
||||
|
||||
|
||||
def _branch_discard(
|
||||
args: Dict[str, Any], org: str, project: str, *, api_key: str, api_base: str
|
||||
) -> Dict[str, Any]:
|
||||
"""``discard``: deletes ``environment_id`` via ``DELETE
|
||||
.../environments/{env}`` instead of waiting for its TTL. Deletion is
|
||||
permanent and unconditional — there is no confirmation step, matching
|
||||
the real endpoint's own contract ("Deletion is permanent.", per
|
||||
`docs.scribase.com/docs/api/environments`).
|
||||
"""
|
||||
branch_id = str(args.get("environment_id") or "").strip()
|
||||
if not branch_id:
|
||||
return {"error": "environment_id is required (the branch to discard)."}
|
||||
|
||||
status, body = _request(
|
||||
"DELETE",
|
||||
f"{api_base}/v1/organizations/{org}/projects/{project}/environments/{branch_id}",
|
||||
api_key,
|
||||
extra_headers={"Idempotency-Key": _idempotency_key()},
|
||||
)
|
||||
if status == 0:
|
||||
return body
|
||||
if status != 202:
|
||||
return {"error": "failed to discard branch", "status": status, "detail": body}
|
||||
operation_id = body.get("id") if isinstance(body, dict) else None
|
||||
if not operation_id:
|
||||
return {"error": "branch discard accepted but no operation id was returned", "detail": body}
|
||||
|
||||
final_state, last_op_body = _poll_operation(operation_id, org, api_key=api_key, api_base=api_base)
|
||||
if final_state == "succeeded":
|
||||
return {"status": "discarded", "organization_id": org, "project_id": project, "environment_id": branch_id}
|
||||
still_going = final_state not in ("failed", "cancelled")
|
||||
return {
|
||||
"status": "discarding" if still_going else "failed",
|
||||
"organization_id": org,
|
||||
"project_id": project,
|
||||
"environment_id": branch_id,
|
||||
"operation_id": operation_id,
|
||||
"message": (
|
||||
f"Branch is still being discarded (state={final_state!r}). It will finish shortly."
|
||||
if still_going else
|
||||
f"Branch discard failed (state={final_state!r})."
|
||||
),
|
||||
"operation": last_op_body,
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user