# Repository Agent Brief: Plan How to Open an API

A complete, copy-ready planning brief for inspecting an existing repository and designing a supported API, with evidence, authorization and staged delivery.

Published: 2026-07-18
Canonical: https://darrylwong.me/posts/plan-how-to-open-an-api
Topics: API Design, Agent Architecture

Published Gist: https://gist.github.com/oruenboi/aaca19e27a4da14797e2bb63b7d24b18

Use this brief when an existing software repository has no supported external API, or when its existing APIs may be insufficient for the intended consumers and workflows. The agent must inspect the implementation before proposing a new or revised architecture. This is a planning assignment, not permission to implement or publish an API.

Replace bracketed inputs where known. Unknown inputs may remain blank; the agent must record them as decisions rather than invent answers.

## Relationship to API-to-Agentification Workflow

This brief is the API architecture and planning component of [API-to-Agentification Workflow](https://gist.github.com/oruenboi/b8b01fb8c3da28d8c6e7cf323fa91b1e). Use it whether the target application has no supported API or has APIs whose coverage or design may be insufficient for the intended workflow.

After inventorying the current interfaces, assess each required capability against [Agentify Any App](https://gist.github.com/oruenboi/403ea8afcd3a68c7495e86f410306692) and classify it as `reuse`, `harden`, `extend`, `build`, or `block`. Agentify supplies requirements such as stable resource identity, workflow context, delegated authorization, previews, idempotency, readback, and auditability. This brief turns any resulting API gaps into an evidence-backed architecture and delivery plan.

This remains a planning assignment. Neither the capability classification nor the resulting plan authorizes implementation, publication, credential creation, or production access.

## Recommended Model and Reasoning

Configure the runtime before starting the assignment. Prompt text can request a level of care, but it cannot change the model or reasoning setting selected by the operator.

| Stage | Model | Reasoning | Use |
| --- | --- | --- | --- |
| Main planning agent | `gpt-5.6` | `high` | Default for repository tracing, architecture comparison, synthesis, and planning |
| Optional exploration workers | `gpt-5.6-terra` | `medium` | Large-repository file discovery and read-heavy subsystem reports |
| Final critical review | `gpt-5.6` | `xhigh` | Independent challenge of security, transaction, tenancy, and rollout assumptions |

For a normal single-agent run, use **`gpt-5.6` with `high` reasoning**. In interfaces that use display labels, `xhigh` may appear as **Extra High**.

Codex configuration:

```toml
model = "gpt-5.6"
model_reasoning_effort = "high"
```

Do not default the whole run to `max` or `ultra`. Use the lowest effort that passes the planning review checklist. Reserve higher settings for an independent final review when the repository is unusually complex or the API will control sensitive, regulated, financial, destructive, or cross-tenant operations.

For large repositories, parallel exploration workers should return concise, evidence-linked subsystem reports to the main planning agent. The main agent remains responsible for reconciling conflicts, tracing cross-system workflows, and producing the final recommendation.

## Copy-Ready Agent Assignment

````md
# Assignment: Inspect This Repository and Plan a Supported External API

## Role

Act as a principal backend and API architect. Inspect the repository deeply enough to produce an evidence-backed plan for exposing a supported API without coupling external consumers to unstable internals.

This is a planning task. Do not implement endpoints, change production configuration, publish documentation, generate credentials, alter infrastructure, or expose network access unless separately authorized.

## Recommended Execution Profile

- Main agent: `gpt-5.6` with `high` reasoning.
- Optional large-repository exploration workers: `gpt-5.6-terra` with `medium` reasoning.
- Optional independent final reviewer: `gpt-5.6` with `xhigh` reasoning.
- Record the model and reasoning setting actually used. If the recommended configuration is unavailable, use the strongest available repository-capable model with high reasoning and disclose the substitution.
- Do not claim that the requested model or reasoning level is active unless it was configured by the operator or confirmed by the runtime.

## Inputs

- Repository: [path or repository URL]
- Product or system: [name]
- Known API consumers: [internal teams, partners, customers, public developers, agents, unknown]
- Known priority workflows: [list or unknown]
- Agentic use intended: [yes, no, possible, unknown]
- Expected access model: [private, partner, registered public, anonymous public, unknown]
- Deployment model: [self-hosted, SaaS, customer-managed, hybrid, unknown]
- Compliance or data constraints: [list or unknown]
- Required planning-document location: [path or follow repository conventions]
- Active model and reasoning setting: [record actual runtime configuration]

## Operating Rules

1. Read every applicable `AGENTS.md`, contributor guide, architecture document, product requirement, and planning convention before analysis.
2. Inspect the repository and current Git state. Preserve user changes and do not modify application code.
3. Treat repository evidence as fact only when supported by a path and line reference, configuration, schema, migration, test, or generated contract.
4. Label every material statement as one of:
   - **Observed:** directly supported by repository evidence.
   - **Inferred:** a reasoned interpretation of observed evidence.
   - **Assumed:** needed for planning but not established.
   - **Decision required:** requires product, legal, security, or operational ownership.
5. Cite repository evidence as `path/to/file.ext:line` wherever practical.
6. Do not assume that UI routes, ORM models, database tables, internal RPC methods, or framework controllers are suitable public contracts.
7. Do not recommend exposing a generic execute-any-method or query-any-table interface.
8. Separate authentication, authorization, tenant isolation, business approval, and legal data-reuse rights.
9. Prefer the smallest external surface and narrowest audience that satisfy validated consumer workflows.
10. Record uncertainties and conflicting evidence explicitly. Do not hide them behind a confident recommendation.
11. Do not treat the existence of an endpoint as proof that it is supported, externally safe, or ready for agentic use.

## Phase 1: Establish Repository Context

Read and report:

- repository instructions and planning rules
- languages, frameworks, package manifests, and runtime versions
- application entry points and process topology
- deployment, container, proxy, and infrastructure configuration
- database technologies, schemas, migrations, and ownership boundaries
- existing architecture, product, security, and operations documentation
- test suites and CI/CD checks
- current public, private, undocumented, or accidental integration surfaces

Start with efficient repository discovery, for example:

```text
rg --files
rg -n "route|router|controller|endpoint|graphql|rpc|webhook|socket|auth|permission|role|scope|tenant|api[_-]?key"
```

Adapt searches to the discovered framework. Do not treat keyword matches as conclusions; trace them to registration, runtime configuration, authorization, business logic, and tests.

Deliver a concise current-state system map showing:

- clients and user interfaces
- application or service processes
- background workers and schedulers
- databases and file/object storage
- identity provider and authorization mechanisms
- third-party integrations
- queues, events, and webhooks
- trust boundaries and network boundaries

## Phase 2: Trace Existing Business Operations

Identify how important workflows currently enter the system and reach authoritative state changes. Trace at least one representative workflow end to end for each materially different risk class.

Create this inventory:

| Capability | Current entry point | Owning code | Actor | Read/write | Risk | Transaction boundary | Current authorization | Agent-readiness gaps | Treatment |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |

For each capability required by an agentic workflow, assign one treatment:

- **Reuse:** the supported API already has adequate context, controls, and verification.
- **Harden:** the operation exists but lacks security, safety, reliability, or operational controls.
- **Extend:** the API is sound but lacks required resources, context, business actions, or workflow coverage.
- **Build:** no suitable supported machine interface exists.
- **Block:** the operation should remain human-controlled or required safeguards cannot be enforced.

Assess stable resource identity, workflow context, actor attribution and delegation, authorization, schemas, preview and approval, idempotency, concurrency, async or unknown outcomes, readback, audit, interface blockers, and operational ownership. Score material gaps as `ready`, `partial`, `missing`, or `blocked`. Treat these as requirements for the proposed API plan, not as permission to implement an agent runtime.

Classify capabilities as:

- read
- draft or preparatory write
- preview or validation
- authoritative transaction
- destructive or irreversible operation
- administrative or security operation
- long-running job
- event or notification

For every mutation, determine:

- where business validation happens
- where authorization is enforced
- which transaction commits the change
- whether retries are safe
- whether an idempotency mechanism exists
- what concurrent modification protections exist
- how success can be read back independently
- what audit evidence is recorded

## Phase 3: Identify Intended Consumers and Access Policy

Use existing product evidence where available. Otherwise mark these as decisions required:

- named consumer types and their jobs to be done
- private, partner, registered-public, or anonymous-public access
- human-delegated versus machine-to-machine access
- read-only versus write access
- tenant and organization boundaries
- data classification and legal authority to expose each data category
- expected traffic, batch size, latency, availability, and freshness
- support, pricing, entitlement, and quota expectations

Keep these dimensions separate:

| Dimension | Required decision |
| --- | --- |
| Discoverability | Who can discover the API and read documentation? |
| Eligibility | Who can register or receive credentials? |
| Authorization | Which operations, fields, and records can each identity access? |
| Reuse rights | What can consumers legally do with returned data? |

## Phase 4: Evaluate Architecture Options

Evaluate at least these options against repository evidence:

1. **Embedded API adapter:** API controllers call an existing application or domain service layer in the same deployable system.
2. **External facade or anti-corruption layer:** a stable external contract translates into a legacy or vendor-specific internal interface.
3. **API gateway over existing services:** a gateway provides identity, routing, quotas, and observability while domain services retain business rules.
4. **Asynchronous integration:** jobs, webhooks, events, exports, or imports handle long-running or loosely coupled workflows.
5. **No API for a capability:** file export, managed integration, embedded UI, or manual approval remains safer or simpler.

Use a decision table:

| Option | Repository fit | Coupling | Transaction safety | Security boundary | Operational cost | Migration effort | Main risks |
| --- | --- | --- | --- | --- | --- | --- | --- |

Recommend one primary architecture and any complementary patterns. Explain why it fits the actual codebase. Do not choose an API gateway merely because the system needs an API; justify every new component.

## Phase 5: Define the Proposed Boundary

Describe separate northbound and southbound contracts:

- **Northbound:** the stable interface promised to external consumers.
- **Southbound:** internal calls from the API layer to existing services, modules, databases, or vendor APIs.

The northbound contract should model business capabilities and remain stable when internal implementation changes. Identify which internal details must not leak, including table names, unrestricted model names, framework methods, internal IDs, stack traces, and privileged credentials.

Provide a Mermaid architecture diagram that includes:

- consumers
- edge or gateway controls
- API/application-service layer
- policy and authorization enforcement
- existing system or domain services
- system of record
- asynchronous jobs/events where applicable
- logs, metrics, audit, and secrets boundaries

## Phase 6: Outline the API Contract

Do not write a complete implementation. Produce a contract outline covering:

- resource and business-action naming
- endpoint or operation summary
- request and response shapes
- pagination, filtering, sorting, and bounded collection behavior
- consistent error model
- idempotency requirements
- concurrency and conditional update behavior
- asynchronous job/status resources
- webhook or event schemas
- file upload/download handling
- API versioning and compatibility policy
- deprecation and retirement policy

Recommend OpenAPI for an HTTP API and identify where the canonical contract should live. For GraphQL, RPC, MCP, or event protocols, identify the corresponding machine-readable schema and ownership rules.

## Phase 7: Design Identity and Authorization

Trace the current identity model before recommending a protocol. Define:

- human-delegated and machine identities
- authentication flow for each consumer type
- token or credential lifecycle
- scopes and operation-level permissions
- object-, property-, and tenant-level authorization
- service-account permissions
- administrator separation
- credential storage, rotation, revocation, and incident response
- audit attribution for both the initiating human and executing service

Calculate effective permission as the intersection of all applicable controls:

```text
consumer identity
AND tenant membership
AND user role
AND granted scope
AND resource-level authorization
AND operation policy
AND downstream service authority
```

Explicitly test for confused-deputy behavior, cross-tenant access, object ID substitution, overbroad service accounts, mass assignment, excessive data exposure, and bypass through lower-level internal methods.

## Phase 8: Design Data, Transaction, and Async Behavior

For writes, specify:

- the authoritative transaction boundary
- atomic versus multi-step behavior
- idempotency-key ownership and retention
- duplicate and replay handling
- timeout and unknown-outcome handling
- readback verification
- compensation where atomic execution is impossible

For asynchronous operations, specify:

- command versus event ownership
- queue or job state model
- retry and backoff policy
- at-least-once delivery and deduplication behavior
- dead-letter ownership and replay procedure
- ordering requirements
- webhook signatures and delivery retries
- outbox/inbox requirements
- backpressure and concurrency limits

Do not promise exactly-once behavior without repository evidence and a defensible protocol.

## Phase 9: Define Non-Functional and Operational Requirements

Propose measurable initial targets or mark decisions required for:

- request volume and payload limits
- latency and throughput
- availability and error rate
- data freshness
- tenant-level quotas and noisy-neighbor controls
- rate and resource-consumption limits
- logs, metrics, traces, and correlation IDs
- audit retention
- dashboards, alerts, and runbooks
- backup, restore, recovery time, and recovery point
- deployment, rollback, feature flags, and tenant-cohort rollout
- cost and capacity guardrails
- API inventory, ownership, support, and vulnerability reporting

## Phase 10: Threat and Failure Analysis

Produce a concise threat and failure table:

| Scenario | Asset or workflow | Existing control | Gap | Proposed mitigation | Verification |
| --- | --- | --- | --- | --- | --- |

At minimum consider:

- broken object-, property-, and function-level authorization
- broken authentication and credential leakage
- unrestricted resource consumption
- automation of sensitive business flows
- server-side request forgery and unsafe outbound calls
- unsafe consumption of third-party APIs
- stale or undocumented API versions
- replayed write requests or approvals
- partial failure and unknown commit outcomes
- dependency outage, queue backlog, and webhook failure
- schema drift and breaking changes
- accidental exposure of secrets or personal data in logs

## Phase 11: Produce a Staged Delivery Plan

Recommend stages with entry and exit criteria:

1. **Discovery:** current-state evidence and consumer validation complete.
2. **Contract prototype:** reviewed API contract with no production exposure.
3. **Internal alpha:** representative read and low-risk write workflows.
4. **Restricted pilot:** selected partners or customers, production-like controls.
5. **Beta:** documented limits, support, monitoring, migration policy, and security testing.
6. **General availability:** stable contract, service ownership, lifecycle policy, and retirement process.

Each stage must include:

- capabilities included and excluded
- security and operational gates
- required tests
- migration or compatibility work
- rollback criteria
- evidence needed to proceed

## Required Deliverable

Follow the repository's planning conventions. Unless they require multiple documents, create one Markdown planning pack with this structure:

1. Document control, including the model and reasoning setting used
2. Executive summary
3. Observed current state
4. Consumers, requirements, non-objectives, assumptions, and decisions required
5. Capability and risk inventory
6. Agent-readiness assessment and `reuse`, `harden`, `extend`, `build`, or `block` classification, when agentic use is intended or possible
7. Architecture options and trade-off matrix
8. Recommended architecture and diagram
9. Proposed API boundary and contract outline
10. Identity, authorization, tenancy, and data governance
11. Transactions, idempotency, async processing, and webhooks
12. Security and threat analysis
13. Reliability, observability, deployment, and operations
14. Testing and contract-verification strategy
15. Migration and staged delivery plan
16. Risks, dependencies, and open questions
17. Architecture decision records
18. Repository evidence index
19. Official sources

The recommendation must distinguish clearly between:

- what the repository does today
- what should remain internal
- what is suitable for external exposure
- what requires refactoring before exposure
- what must remain blocked
- what cannot be decided from code alone

## Completion Criteria

The planning task is complete only when:

- major claims are backed by repository evidence
- at least one representative workflow is traced end to end
- trust and transaction boundaries are explicit
- architecture alternatives are compared rather than implied
- the proposed external contract does not expose unstable internals
- authentication and authorization are separately designed
- tenancy and data sensitivity are addressed
- idempotency and unknown outcomes are addressed for writes
- operational ownership and API lifecycle are included
- agent-required capabilities are classified as `reuse`, `harden`, `extend`, `build`, or `block` when agentic use is intended or possible
- rollout begins with a restricted, testable slice
- unresolved product, legal, security, and operational decisions have named owners where known
- the model and reasoning setting actually used are recorded
- no implementation or production exposure occurred during planning
````

## Planning Review Checklist

Use this shorter checklist when reviewing the agent's result:

- Did it read the target repository's instructions before proposing files or architecture?
- Are factual claims linked to repository evidence?
- Did it trace actual business logic instead of only listing routes?
- Did it identify where authorization and transactions truly occur?
- Did it distinguish the external contract from internal implementation interfaces?
- Did it compare embedded adapter, facade, gateway, async, and no-API options?
- Did it avoid generic database, ORM, or method exposure?
- Are service accounts constrained and human actions attributable?
- Are tenant isolation, idempotency, retries, and unknown outcomes covered?
- Does the rollout start with a narrow internal or partner pilot?
- Are documentation, support, observability, compatibility, and retirement included?
- Are business and legal decisions clearly separated from code-derived findings?

## Related Pages

- [API-to-Agentification Workflow](https://gist.github.com/oruenboi/b8b01fb8c3da28d8c6e7cf323fa91b1e)
- [Agentify Any App](https://gist.github.com/oruenboi/403ea8afcd3a68c7495e86f410306692)
- Opening an API - Decision Framework and Best Practices
- Open API Strategy - Research Sources

## Authoritative References

- OpenAI latest model guidance: https://developers.openai.com/api/docs/guides/latest-model
- OpenAI Codex model and reasoning guidance: https://learn.chatgpt.com/docs/agent-configuration/subagents#choosing-models-and-reasoning
- OpenAI reasoning-effort guidance: https://learn.chatgpt.com/docs/models#pick-a-reasoning-effort
- OpenAPI Initiative: https://www.openapis.org/what-is-openapi
- Google Cloud API Design Guide: https://cloud.google.com/apis/design
- Microsoft REST API design guidance: https://learn.microsoft.com/en-sg/azure/architecture/best-practices/api-design
- OWASP API Security Top 10: https://owasp.org/API-Security/editions/2023/en/0x11-t10/
- NIST SP 800-228: https://www.nist.gov/publications/guidelines-api-protection-cloud-native-systems
- OAuth 2.0 Security Best Current Practice: https://www.rfc-editor.org/info/rfc9700/


## Sources

- [Read the source Gist](https://gist.github.com/oruenboi/aaca19e27a4da14797e2bb63b7d24b18)
