Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/pull-request.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ jobs:
go-version-file: go.mod
- run: go build ./...
- run: go test -race ./...
- name: Test the rollback rehearsal skill
if: runner.os == 'Linux'
run: python3 -m unittest discover -s tests/skills

lint:
runs-on: ubuntu-latest
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,6 @@
/website/public/
/website/resources/
/website/.hugo_build.lock

# Python bytecode generated by skill tests.
__pycache__/
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ Reading works against any Flagsmith instance. Changing flags — `flag update`,
- `flagsmith auth token` — print the active Admin API credential for curl/scripts.
- `flagsmith api <path>` — call any Flagsmith endpoint with the CLI's credentials applied (curl-like; `--sdk` for the SDK API, `-F`/`-f` fields).

## Agent skills

[Rehearse a flag rollback](skills/rehearse-flag-rollback/SKILL.md) compares how different retirement policies affect new and in-flight work in a disposable environment.

## Conventions

- `--json` (or `FLAGSMITH_JSON_OUTPUT`) for machine-readable output; `--jq <expr>` to filter it.
Expand Down
15 changes: 15 additions & 0 deletions skills/rehearse-flag-rollback/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
name: rehearse-flag-rollback
description: Use the Flagsmith CLI to rehearse a flag rollback against fresh and in-flight application work, compare rollback policies, and report which application invariants hold.
---

Use this when turning a flag off (or back on) could strand work started under its previous assignment. A successful flag write establishes configuration state. Only a probe of the application can establish what happens to that work.

1. **Define the decision.** Identify the project, environment, flag, before/after assignment, audience, and candidate retirement policies. Ask what must stay true for a new visitor and for work already in progress. Phrase each check as something you can observe. Can the user reopen a saved draft? Does a retried job deliver exactly once? Agree on required checks before inspecting results.
2. **Find the application probe.** Look for an existing integration test or fixture. Adapt it to the [probe contract](references/probe.md) if needed. Confirm equivalent work completes before the rollback. Capture one piece of synthetic work and replay independent copies with the same dependencies and inputs under each candidate policy. Sample the actual application outcome, including side effects. If the necessary fixture or observation is unavailable, report the missing evidence.
3. **Confirm scope.** Identify both API origins and the numeric project ID with the operator. Establish permission to create and remove a disposable clone and to run the selected application fixture. Use staging dependencies and an authorized credential for that instance. Review the probe before running it. Flag isolation alone does not isolate queues, databases, payments or webhooks.
4. **Run the rehearsal.** Run the helper from the installed skill directory, using Flagsmith CLI v2, Flagsmith 2.263.0 or newer, Python 3 and an executable probe (the example uses a POSIX shebang). The helper reads the source, creates a uniquely named clone, checks the environment default and the SDK assignment before capture and after the change, then runs the named plans and verifies clone removal. The source receives no flag writes. Pass the application's own check names and policies. For an executable local example, see the [queue rehearsal](references/probe.md#try-the-queue-example).
5. **Report the decision.** Read the compact JSON receipt and exit code. Name the audience, failing or unobservable invariants, and cleanup status. Recommend a plan only after its required checks pass and cleanup is verified. A mixed comparison exits 1 even when one plan passed. If cleanup is unverified, resolve the run's generated name to its ID and verify ownership before removal. If interrupted by a hard kill, use the name printed before cloning. Never retry a mutation blindly.
6. **Hand off the release.** State which traffic, versions and dependencies were exercised. Report missing evidence or unverified cleanup before recommending any action. For additional audiences run separate rehearsals using synthetic identities and known traits. Cloning omits identity-specific state. Applying anything to a shared or production environment requires a separate decision. Present the proposed change, re-read current state and obtain explicit approval. A rehearsal does not establish production-wide safety.

The helper changes the environment default's Boolean state. For a value, variant-weight or override rollback, rehearse that exact scope in a disposable environment with the CLI and evaluate the relevant identities and values. Do not substitute a Boolean toggle as evidence for a different change.
64 changes: 64 additions & 0 deletions skills/rehearse-flag-rollback/examples/queue_probe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""A synthetic queue migration. Each replay starts with a fresh database."""
import json
import os
import sqlite3
import sys
from urllib.request import Request, urlopen
from uuid import uuid4


def assignment():
req = Request(os.environ["REHEARSAL_SDK_URL"] + "/api/v1/flags/",
headers={"X-Environment-Key": os.environ["REHEARSAL_SDK_KEY"]})
with urlopen(req, timeout=5) as res:
flags = json.load(res)
return next(row["enabled"] for row in flags if row["feature"]["name"] == os.environ["REHEARSAL_FLAG"])


def job(enabled):
return {"id": str(uuid4()), "payload": {"units": 7} if enabled else 7}


def replay(plan, pending, fresh):
if plan not in {"immediate", "drain"}:
raise ValueError("unknown schedule")
db = sqlite3.connect(":memory:")
db.execute("create table deliveries(job text primary key, units integer)")

def deliver(item, v2_reader):
units = item["payload"]
if isinstance(units, dict):
if not v2_reader:
return
units = units["units"]
db.execute("insert or ignore into deliveries values (?, ?)", (item["id"], units))

deliver(fresh, False)
deliver(pending, plan == "drain")
deliver(pending, plan == "drain") # retry while the same reader is available
deliver(pending, False) # late retry after retirement

def delivered_once(item):
return db.execute("select count(*), sum(units) from deliveries where job = ?",
(item["id"],)).fetchone() == (1, 7)

checks = {"fresh_legacy_job": fresh["payload"] == 7 and delivered_once(fresh),
"inflight_delivered_once": delivered_once(pending)}
db.close()
return checks


if __name__ == "__main__":
request = json.load(sys.stdin)
if request["identity"] is not None or request["traits"]:
sys.exit("the example supports anonymous assignments only")
if sys.argv[1] == "capture":
if assignment() is not True:
raise ValueError("capture did not use the new writer")
result = job(True)
if not replay("drain", result, job(True))["inflight_delivered_once"]:
raise ValueError("the pending job could not complete before rollback")
else:
result = replay(request["plan"], request["snapshot"], job(assignment()))
print(json.dumps(result))
30 changes: 30 additions & 0 deletions skills/rehearse-flag-rollback/references/probe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Application probe

Run the helper with explicit Admin and SDK origins, a numeric project ID, a source environment, and the flag name. Use the CLI's normal login or host-scoped credentials. Keep CLI output filtered; never print tokens, full environment documents, or raw sessions into the agent transcript.

The probe is a trusted executable invoked without a shell. It gets the clone's client-side SDK key in `REHEARSAL_SDK_KEY`, its SDK origin in `REHEARSAL_SDK_URL`, and `REHEARSAL_FLAG`. The helper passes only those three variables plus PATH, LANG and SYSTEMROOT if set. The probe must bind its app to this clone and isolate its own resources. It owns cleanup of any application fixtures it creates. Use an isolated OS account or container for untrusted code; filtering environment variables is not a process sandbox. The probe exercises the retirement policies in its test environment.

| Invocation | JSON on stdin | Required JSON on stdout |
| --- | --- | --- |
| `probe capture` | `identity`, `traits`, null `plan` and `snapshot` | One non-null JSON snapshot of in-flight work under the before assignment |
| `probe replay` | The selected `plan`, the original `snapshot`, the same identity and traits | Exactly the declared check names, each with a Boolean or null |

Return true only when the application assertion was observed; false for an observed violation; null for missing evidence. Exit nonzero on infrastructure errors. Repeating a replay must start from the same captured input with clean application state. Before returning a capture, verify an equivalent item can finish on the original path. A snapshot may reference a fixture that the probe restores per plan. Use compact, synthetic JSON. Avoid live customer data. For asynchronous jobs use a bounded completion condition and check observable side effects after retries.

## Try the queue example

The example fetches the clone's assignment from the Flagsmith SDK endpoint and uses a fresh in-memory SQLite database per plan. It exercises the anonymous audience of a Boolean flag. It compares retiring a versioned queue reader immediately with allowing previously encoded jobs to complete. Use your own flag in an authorized test project.

From the skill directory, set `ADMIN_ORIGIN`, `SDK_ORIGIN`, `PROJECT_ID`, `SOURCE_ENV` and `FLAG` to your authorized target.

```sh
python3 scripts/rehearse.py \
--api-url "$ADMIN_ORIGIN" --sdk-api-url "$SDK_ORIGIN" \
--project "$PROJECT_ID" --source "$SOURCE_ENV" --flag "$FLAG" \
--probe examples/queue_probe.py --plan immediate --plan drain \
--check fresh_legacy_job --check inflight_delivered_once
```

The two plans share an immutable capture. The example expects the old reader to handle fresh work under both policies. The new-format job fails to deliver under immediate retirement and delivers seven units exactly once under the drain policy. Replace both the probe and its expectations for a different application.

Exit 0 means every required observation passed in every plan. Exit 1 means the comparison completed and at least one check failed. Exit 2 means incomplete evidence, an unexpected SDK assignment, a failed command, or unverified cleanup. An inconclusive run can still contain observations from completed plans. The queue example captures work with the flag on. For an off-to-on rehearsal, use `--before off` with a probe that captures work under the off assignment. For targeted users supply `--identity` and repeated `--trait name=value`; implement that audience in the probe too. Targeted rehearsals stop before cloning if the active identity store cannot list overrides reliably or the flag has any identity overrides. Supply the full synthetic traits required by your probe; percentage-based assignments may vary by environment. The SDK convergence wait defaults to 90 seconds per switch; set `--convergence-timeout SECONDS` to match your cache lifetime. A flag hidden from the SDK when disabled cannot prove an explicit false assignment with this helper.
Loading