Skip to content

PyModel/pythinker-code / .agents/skills/agent-core-dev

agent-core-dev

Verified

Use when developing in packages/agent-core-v2 (the DI × Scope agent engine) — adding or modifying a domain Service, choosing a LifecycleScope, wiring DI dependencies, splitting a domain across scopes, owning or migrating a config section, gating behavior behind an experimental flag, raising coded errors, working on the permission system, writing DI/Scope tests, porting business logic from agent-core (v1) to v2, triaging a main-branch commit against v2, or exposing a v2 domain over server-v2 while keeping the /api/v1 wire contract compatible with released clients. Self-contained guide organized by development stage (orient → design → implement → test → verify) plus align workflows for v1→v2 migration, main-branch commit triage, and server-v2 wire exposure; each file carries the rules, examples, and red lines for its step.

FileKindSize
SKILL.mdskill md8.8 KB
align.mdmarkdown14.9 KB
config.mdmarkdown25.6 KB
design.mdmarkdown16.4 KB
domain-boundaries.mdmarkdown10.5 KB
edge-exposure.mdmarkdown10.7 KB
orient.mdmarkdown5.5 KB
permission.mdmarkdown16.7 KB
server-align.mdmarkdown18.6 KB
service-authoring.mdmarkdown20.8 KB
telemetry.mdmarkdown8.4 KB
test.mdmarkdown15.2 KB
verify.mdmarkdown2.3 KB
# Stage 2 — Design a service

Decide *where things live and who knows whom* before writing code. Every rule here derives from two questions:

1. **What is the identity of the state it owns?** → decides the **Scope**.
2. **Who owns the decision, and who needs the result?** → decides the **calling style** and **dependency direction**.

## 1. What a Service is

A Service = a bundle of **state** + a set of **behaviors**, bound to a **lifetime**.

- **Behavior** is almost free — the same logic runs anywhere, so it does not by itself decide a scope.
- **State** pins a Service to a scope. State has an **identity** (what it is keyed by) and a **lifetime** (when it is born, when it dies).
- **Dependencies / calling style** answer a different question: who controls whom, and who knows whom.

## 2. Choosing a scope

> Scope = the identity + lifetime of the owned state.

| Owner | State identity (keyed by) | Lifetime |
|---|---|---|
| `LifecycleScope.App` | none (single global instance) | the process |
| workspace `Program` | `workspaceId` | one materialized workspace instance or runtime generation |
| `LifecycleScope.Session` | `sessionId` | one session |
| `LifecycleScope.Agent` | `agentId` | one agent |

### Decision tree

**Q1. Does it own mutable state?**

- No (pure behavior) → jump to Q3.
- Yes → Q2.

**Q2. What is the identity of that state?**

- one global instance → **`App`**
- one per workspace (shared by every session of that workspace) → a program-owned **workspace component**
- one per session → **`Session`**
- one per agent → **`Agent`**
- a mix (a global registry *and* per-instance state) → **split it** (see §3).

**Q3 (stateless). What is the shortest-lived dependency it must inject?**

A stateless Service is pulled *down* by its shortest-lived dependency: if it injects an `Agent`-scoped Service, it cannot be `App`. Among the scopes that still satisfy every dependency, **default to the longest-lived one** (usually `App`) to maximize reuse. Push it down only when it must inject a shorter-lived Service, or when you want to limit its visibility.

### The core anti-pattern (a litmus test)

> **Do not store per-session state in a `Map<sessionId, …>` inside an `App` Service.**

This is the tell-tale sign of "should have been `Session`-scoped but was parked at `App`". Consequences: nobody cleans the entry up when the session ends (leak); every consumer threads `sessionId` around (loss of type safety); it cannot inject `Session`/`Agent`-scoped collaborators.

### One-sentence self-check

> "When this scope is disposed, should this state disappear with it?"
>
> - Yes → the scope is right.
> - It must outlive the scope → too short; move up one tier.
> - It should be one-per-unit but is shared → too long; move down one tier.

## Scope is not a domain

Scope answers **lifetime and visibility**. Domain answers **responsibility and data ownership**. A Service registered at `Session` or `Agent` scope is not automatically part of the `session` or `agent` domain, and an entity Service must not be named `I{Scope}EntityService` just because its data is scoped that way.

Use the data-ownership test and the `session` / `agent` / `turn` split conclusions in [domain-boundaries.md](domain-boundaries.md) before naming a Service or adding `I{Domain}EntityService`.

## 3. Multi-Scope splitting

> One Service owns state at exactly one identity / lifetime. If a domain owns state at several lifetimes, split it along those boundaries — one Service per lifetime.

The standard split is "global registry / factory" + "per-instance":

| Tier | Role | Naming tends to |
|---|---|---|
| `App` | global registry / catalog / factory — knows "all of them" and how to create one | `XxxStore` / `XxxRegistry` / `XxxCatalog` |
| workspace program / `Session` / `Agent` | one instance — only the state of "this one" | `XxxService` / `IWorkspaceXxx` / `ISessionXxx` / `IAgentXxx` |

Canonical splits in the codebase:

- **`records`** — `ISessionStore` (`App`) + `ISessionMetaStore` (`Session`) + `IAgentRecords` (`Agent`).
- **`config`** — `IConfigRegistry` / `IConfigService` (`App`).
- **`kosong`** — `IProtocolHandlerRegistry` (`App`) + `IProviderManager` (`Session`). Generation is driven by `ILLMRequester` (`Agent`) in the `llmRequester` domain.
- **`tool`** — `IToolDefinitionRegistry` (`App`) + `IToolService` (`Agent`).

Split when the domain genuinely has both a global view and per-instance state. Do **not** split when state lives at only one lifetime (e.g. purely `App` like `log`; purely `Agent` like `prompt`). Do not pre-split for symmetry.

After the split, the `App` Service usually plays the **factory**; most consumers inject the **per-instance** Service. Inject the `App` factory only when you genuinely need cross-instance management.

## 4. Choosing a calling style

Three mechanisms answer three different questions:

| Mechanism | Nature | Coupling | Returns a value? | Consumers |
|---|---|---|---|---|
| **Direct call** | command: A tells B to do | A → B | yes | one (known) |
| **Event** | fact: A announces "X happened" | both depend only on the bus | no | zero / one / many (unknown) |
| **Hook** (`onWill` / `onDid`, `OrderedHookSlot`) | participation: observers step into an operation, in order | both depend only on the bus | can observe / veto | many, but ordered |

### Decision tree

**Q1. Does A need a return value from B?** → Yes: **direct call**. Events cannot return a value (request/reply over events is an anti-pattern).

**Q2. Is B's reaction part of A's responsibility, or B's own concern?**

- A's responsibility *includes* B's behavior (A orchestrates B) → **direct call**. E.g. `session` drives `agentLifecycle`; `loop` drives `llmRequester` / `toolExecutor`.
- B's reaction is B's own concern, A merely states a fact → **event**. E.g. `flag` reacts to `config.onDidChange`.

**Q3. How many consumers?**

- exactly one, known → **direct call**.
- zero / one / many, producer should not know → **event**.

**Q4. Would a direct A→B call create a cycle or violate scope direction?** → A *consequence check*, not a primary reason. Decide by Q1–Q3 first; do not turn a genuine direct call into an event just to break a cycle.

**Q5. Is this fact part of the durable record / replay / cross-agent projection?** → Yes: **emit it on the wire** (`wireRecord`). State changes that must be recorded, replayed, or synchronized across agents are projected onto the wire, not handled by a direct call alone (`permission.set_mode`, `goal.create/update/clear`, `plan_mode.enter/exit`). The wire is the *durable record*, not the live notification channel.

### One-sentence rule

> "I am telling you to do this, and I may need the result" → **direct call.**
> "I am announcing that something happened; react if you care" → **event.**
> "I am announcing something, and you may step in, in order, possibly to veto" → **hook.**

### As extension points (open-closed)

The three mechanisms above are also where a domain accepts new behavior without being edited. When adding a scenario would otherwise require changing this domain's `if/else`, expose the right extension point instead:

| Need | Extension point | Typical scope |
|---|---|---|
| Register a new implementation / definition | a **registry / catalog** the domain queries | `App` |
| React to a fact the domain announces | an **event** on the bus | the announcing scope |
| Step into an operation in order / veto | a **hook** (`onWill`/`onDid`, `OrderedHookSlot`) | the owning scope |
| Swap a backend (File ↔ DB ↔ S3) | a **Store / Storage token** at the byte layer (see persistence.md) | `App` (composition root) |

The standard shape of a "registry / catalog the domain queries" row is an L3 contribution point: the target domain owns a `collection<T>` token, contributors call `this.provide(token, record)` from a unit, and a fold service in the target domain injects the `CollectionView` (incremental `onDidChange`; provider death withdraws the record). The four in-repo seams are `ConfigSectionContribution` → `ConfigRegistry`, `AgentToolContribution` → `AgentToolActivationService`, `AgentProfileContribution` → `IAgentProfileRegistry`, and `WireModelContribution` → `WireService` (file-level pointers: `packages/agent-core-v2/AGENTS.md` §Units and contribution points).

Closed-for-modification means: the domain's own file is not where new scenarios branch. If a new scenario forces an edit here, an extension point is missing or misplaced.

## 5. Dependency direction

Two layers are involved:

- **Scope direction**: short-lived → long-lived, **enforced by the container** (see orient.md).
- **Domain direction**: which domain may depend on which — **a matter of judgment**, not enforced by the container.

> **A depends on B iff A needs B's data or behavior to do its own job.**

Add one anti-rot heuristic to keep the graph from collapsing into a clique:

> **Do not let a more foundational / more-reused Service come to know a more specific / more-upstream one.**

Once a foundational component knows about an upstream scenario, it can no longer be reused by other scenarios and will almost always create a cycle.

### The boundaries of this repo

`agent-core-v2` has no mechanical domain-layer numbering — dependency direction is the judgment rule above, applied per domain. What remains enforceable is a small set of specific boundaries (`lint:imports`, `scripts/check-import-boundaries.mjs`):

- v2 never imports v1 (`@pymodel/agent-core`).
- The kosong subtree keeps its strict internal order (`contract ← protocol ← provider/model`, purity bans, the `provider/bases` registration boundary).

Two standing red lines on top of that:

- The **base substrate** (`_base`, errors, wire types) never depends on any business domain.
- Business logic never depends on the **edge** (`gateway`, `rpc`, the `*Legacy` v1 adapters) — business code should not know REST / WebSocket exist.
- A cycle means knowledge was placed backwards: extract a third, more foundational Service, or invert the "notification" half into an event.

> Capability → orchestrator (e.g. `prompt → turn`) is allowed and present in this repo; the real red line is *inverted reuse* — a foundational / lower Service depending on a specific / upper one.

> When a Service is meant to be reached over the wire (`/api/v2`, WS), see [edge-exposure.md](edge-exposure.md) for the per-scope `resource:action` map, which Services may be exposed directly vs wrapped in a facade, and how events stream.

## 6. New-Service checklist

1. **What does it remember, and what is the state's identity?** → pick the scope (§2).
2. **What is the shortest-lived dependency it must inject?** → the scope cannot be longer than that.
3. **Does it own state at both a global and a per-instance lifetime?** → if yes, split Multi-Scope (§3).
4. **For each collaborator: am I commanding it, notifying it, or letting it participate?** → pick the calling style (§4).
5. **Does each dependency arrow make a more foundational thing know a more specific thing?** → if yes, invert it (§5).

## 7. Render the placement tree

After the checklist, render the result as a plaintext tree — the deliverable reviewers read. Keep it in the design doc or PR description.

```text
domain: `<name>`   (owning lifetime: <Owner>)
├─ serves (who uses me)              tag = HOW they reach me
│   ├─ (inject)   <ConsumerDomain>   @<Scope>   — <what they use me for>
│   └─ (accessor) <ConsumerDomain>   @<Scope>   — <what they use me for>
├─ exposes (interfaces I provide, by scope)
│   ├─ App       : <IXxxRegistry>   — <role>
│   ├─ Workspace program : <IWorkspaceXxx>  — <role>
│   ├─ Session   : <ISessionXxx>    — <role>
│   └─ Agent     : <IAgentXxx>      — <role>
└─ depends (what I inject)           tag = calling style
    └─ <DepDomain>  @<Scope>   direct/event/hook  — <what for>
```

Conventions:

- List **only real interfaces**; write `—` for a scope with no exposed interface. Most domains are single-scope — do not invent symmetry.
- On `depends`, tag each arrow with its calling style: `direct`, `event`, or `hook`.
- On `serves`, tag each consumer with its **access mechanism**, grouped `inject` first then `accessor`:
  - `inject` — a descendant or peer scope DI-injects me. Resolved by the container; lifetime-safe.
  - `accessor` — an ancestor or edge scope borrows me through `IScopeHandle.accessor.get(...)`. Valid only while this scope lives; never cache the result; must run before the child scope is disposed. See the cross-scope borrow diagram below.
- An empty `(inject)` group with a non-empty `(accessor)` group is a signal: the interface is currently an edge / lifecycle command surface — check it is not leaking internals.
- A consumer is upstream of you. If you cannot name one business consumer, the domain may be dead or mis-scoped.

### Cross-scope borrow diagram

When a domain has `accessor` consumers, draw the reverse-direction borrow next to the tree so it is never mistaken for injection:

```text
App scope
  <AncestorService> ──holds──► IScopeHandle(<id>)
                                      │
                                      │  accessor.get(<IMyService>)
                                      │   └── resolve runs inside the child scope
                                      ▼
                                <Child> scope (<id>)
                                  <MyService>  ← the interface lives here
```

Read it as:

- `──holds──►` = the ancestor owns a handle to the child scope (it stores the key, not the service). DI allows this.
- `accessor.get(...)` = a **runtime borrow**, not a dependency edge. It must cross an `IScopeHandle`, run on demand, never be cached, and finish before the child scope is disposed.

Worked example — `sessionLifecycle`:

```text
domain: `sessionLifecycle`   (owning lifetime: workspace Program)
├─ serves
│   └─ SessionManager @App — creates, resumes, forks, closes, and archives sessions
├─ exposes
│   └─ workspace Program : ISessionLifecycleService — owns this controller's live Session scopes
└─ depends
    ├─ workspace context/resources  @Program  direct — identity, fs, dirs, skills, MCP, profiles
    └─ App services                 @App      direct — persistence, config, telemetry, events
```

The App-scoped `IWorkspaceInstanceManager` owns `WorkspaceInstance` objects. Each instance owns a
`Program`. The Program constructs workspace resources and creates a `SessionLifecycleService`
with them. That service creates real `LifecycleScope.Session` children, and each session creates
`LifecycleScope.Agent` children. There is no workspace `IScopeHandle` and no Workspace value in
`LifecycleScope`.

How the three lenses shape it:

- **Lifetime (§2)** → workspace state belongs to the Program; per-session state belongs to Session
  scopes; per-agent state belongs to Agent scopes.
- **Dependency direction (§5)** → the Program receives App dependencies and passes workspace
  resources into the session controller; business code does not import the edge.
- **Extension points (§4)** → new per-session behavior belongs in Session-scoped services; new
  transports stay at the edge.
For a multi-scope split, the `exposes` block fills more than one scope — see the `records` pattern in §3.

## Red lines (this stage)

- Scope is not a domain; ownership follows write authority and invariants, not read consumption.
- Do not create `I{Scope}EntityService` bundles (`IAgentEntityService`, `ISessionEntityService`) that re-merge multiple domains.
- No `Map<sessionId, …>` at `App` to fake per-session state.
- Scope follows state identity; stateless Services are pulled down by their shortest-lived dependency, otherwise default to `App`.
- Do not pre-split a domain that has state at only one lifetime.
- Need a result / I orchestrate → direct call; stating a fact → event; ordered participation / may veto → hook.
- Foundational layers never know upstream ones; business code never depends on the edge layer.
- A cycle means knowledge is placed backwards — refactor, do not route around it.
- Render the placement tree with real interfaces only — never pad an empty scope for symmetry.
- Tag `serves` consumers with `inject` / `accessor`; an empty `inject` group is a signal to check the interface is not leaking internals.
- An `accessor` consumer is a runtime borrow across a scope boundary, not DI injection — never cache the result and finish before the child scope disposes.
- A `serves` list with no business consumer (or only edge consumers) signals a dead or leaking interface.
finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the workStars: 318kUpdated Claude CodeCodexVerifiedInstall
systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixesStars: 318kUpdated Claude CodeCodexVerifiedInstall
test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation codeStars: 318kUpdated Claude CodeCodexVerifiedInstall
skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Stars: 196kUpdated Claude CodeCodexVerifiedInstall