# Repository structure implementation

## Implementation map

| Responsibility | Location | Boundary |
| --- | --- | --- |
| Agent core and SDK | `openprogram/` | Shared runtime code |
| HTTP and WebSocket server | `openprogram/interfaces/server/` | `server.py` assembles; the modules beside it own transport handlers and helpers; routes, Agent profiles included, are grouped by product domain under `routes/` |
| Web application | `apps/web/` | Source; generated assets are staged for serving and packaging |
| Desktop application | `apps/desktop/` | Electron lifecycle, native integration, embedded browser, packaging |
| Python CLI | `openprogram/interfaces/cli/` | Parser, commands, interactive execution, setup |
| Ink terminal UI | `apps/cli/` | Node workspace and terminal UI build |
| Release assembly | `scripts/release/` | Runtime construction, asset staging, release verification |
| Repository maintenance | `scripts/` | One folder per purpose: local instances, publishing, generators, checks, maintenance commands, documentation builder, test selection, benchmarks, Git hooks |

## Entries and compatibility

| Entry | Runs |
| --- | --- |
| `openprogram`, `python -m openprogram`, `python -m openprogram.interfaces.cli` | `openprogram.interfaces.cli.application.main` |
| `python -m openprogram.interfaces.server` | A foreground Server |

Every importer, tests and scripts included, names the real module. Editable installs and wheels both need no `PYTHONPATH`.

### Core-to-interface ports

The core never imports an interface. It calls a port the interface registers when it loads.

| Port | Carries | Registered by; if nothing is |
| --- | --- | --- |
| `openprogram/host/resources/desktop_link.py` | Desktop windows and Pages: binding, resolving, capturing, closing, sending a command to one exact connection | `ws_actions/webtab.py`. An agentic subprocess installs its parent bridge on the same port and forwards Page requests without loading the Server. Unregistered: as if no client were connected. |
| `openprogram/runtime/interface_link.py` | Client notices (goal, todo, open work, title, branch list, native window and execution-stream frames, context ring), the Server's in-memory session, HEAD moves that update it, the busy check for session migration, shipped documentation pages | `server_runtime/interface_link.py`, registered by `server.py`. Unregistered: as if no client were connected. |
| `openprogram/runtime/channel_link.py` | Sending to a channel conversation (reminders, always-on reports), accounts and peer bindings for always-on delivery, the running channel turn `chat_send` posts into | `interfaces/channels/link_registration.py`, on import of `openprogram.interfaces.channels`. Unregistered: raises `ChannelsUnavailable`, recorded as a failed send. |
| `openprogram/runtime/speech_link.py` | Speech to text for computer-use recordings | `interfaces/speech/link_registration.py`, on import of `openprogram.interfaces.speech`. Unregistered: raises `SpeechUnavailable`, a `TranscriptionError` the tool reports as not transcribed. |

The worker runner imports channels and speech before its job dispatcher starts, the Server when it loads, a CLI turn before running tools in process.

Only composition roots import an interface: `openprogram/__main__.py` runs the CLI; `openprogram/operations/worker/runner.py` starts the Server, its runtime and frontend. The [core interface import contract](https://github.com/Fzkuji/OpenProgram/blob/main/tests/contracts/repository/test_core_interface_imports.py) scans every module, function-local and string imports included.

**Logic that lives in the core and the Server imports**

| Logic | Location |
| --- | --- |
| Session graph | `openprogram/state/store/session/graph/` |
| Execution DAG projection, live progress | `openprogram/runtime/execution/projections/dag.py` |
| `/spawn`, `/merge` | `openprogram/runtime/conversation/turn_runtime/slash_actions.py` |
| Runtime-control submission | `openprogram/runtime/execution/control/submission.py` |
| Model listing | `openprogram/models/listing/` |
| Credential masking | `openprogram/host/security/credential_mask.py` |

**Installer, dependencies and the installed App**

- `scripts/install-release.sh` stays the public installer entry; its implementation is under `scripts/release/`.
- The root npm workspace and lock coordinate Web, Desktop and CLI. Do not assume a separate lock or install below an application.
- A dependency patch keeps the application manifest, root lock and installed version aligned. Integrating duplicate dependency branches keeps both ancestries without duplicating the version change.
- The lock keeps transitive entries installed consumers need, optional graphs included. A clean installer exit does not prove consumers load, so public consumer import checks accompany cold installation, and the combined source runs the shared verification manifest before publication.
- The default runtime uses port `18100` and `~/.openprogram`. Layout changes preserve packaging and installed imports as well as source-checkout execution.

## Verification

```
uv run --locked --extra dev python -m pytest -q tests/contracts/repository/test_repository_layout.py
```

The [contract](https://github.com/Fzkuji/OpenProgram/blob/main/tests/contracts/repository/test_repository_layout.py) checks directory ownership, application locations and compatibility, not runtime behaviour. An implementation change also exercises the affected public CLI or HTTP/WebSocket entry, builds a wheel and checks imports outside the checkout, and verifies affected packaging. [Contributor checks](https://github.com/Fzkuji/OpenProgram/blob/main/.github/CONTRIBUTING.md) and the [test-system design](https://fzkuji.github.io/OpenProgram/docs/reference/design/testing/test-system.html) select the gates.

Documentation changes rebuild first, because the checker reads `docs/_site/`:

```
python -m scripts.docs_site.build
python -m scripts.docs_site.checklinks
```

## Module organization and file-operation safety

| Unit | Rule |
| --- | --- |
| Feature module | Owns its types, state and private helpers |
| Folder | One concern: modules that share a meaning sit in a sub-package named for what they are for. None is made for one or two files, and none is a utility bucket |
| Large file | Splits at independently testable responsibilities; public entries stay stable; no wildcard forwarding, duplicate implementations or dynamic source execution to meet a line count |

### File-operation contract

| Operation | Rule |
| --- | --- |
| Clipboard | Entries identify their source project; cross-project paste is unavailable until an explicit transfer operation exists |
| Mutation | Acts on the selected entry. Symbolic-link targets are never implicitly renamed or deleted; unsafe paths fail without changing either entry |
| Deletion | Recoverable where supported. Exporting an unsaved draft does not authorize erasing the only confirmed copy; an unconfirmed browser download keeps the local draft |
| Refresh | Repeats the active search with its unchanged query, with request-generation isolation |

Public WebSocket regression tests cover symbolic links; mounted Web tests cover clipboard ownership, active-search refresh and draft preservation.

**Module responsibilities**

| Area | Split |
| --- | --- |
| Execution control | Activation, cancellation, waits, branch operations, recovery, safe points, on one service instance |
| Execution storage | Records, commands, events, state blobs, projections, finish repair, with one store and its transactions |
| Conversation | `session_settings/` what a session or branch runs with; `turn_admission/` typed text or an owner event becoming a turn; `rewinds/` rewind, undo and redo; `peer_agents/` turns agents run for each other; `layer_registrations/` what the package registers with the layers below on import |
| Execution views, recovery and admission | `projections/` read-only views of run state (Activity, foreground, DAG, execution tree); `recovery/` checkpoints, effects, startup and restart recovery; `admission_input/` what is frozen on a turn or Job at admission |
| Context | `token_accounting/` estimating, budgeting and reporting tokens; `prompt_assembly/` system-prompt components, guides and per-turn notes; `session_dag/` reading the DAG as model history; `compaction/` fitting history into the window |
| Session storage | `files/` the files of a session directory and how they are placed, locked and written; `reading/` transcript, export, search, summaries, provenance |
| Permissions | `auto_mode/` Auto mode's review of an operation; `approvals/` approval waits and their file preconditions; the decision vocabulary stays at the package top |
| Channels | `inbound/` from a platform message to an agent turn; `delivery/` getting a reply onto the platform |
| Provider utilities | `streams/` the event stream of one response; `http_transport/` clients, proxy, timeouts, rate limits; `failures/` classifying a failed request and mending or failing it over |
| CLI | Command modules sit in `commands/capabilities/`, `commands/conversations/`, `commands/services/`, `commands/maintenance/` and `commands/updates/`; `print_mode/` holds an `openprogram --print` run |
| Jobs, resource governance, Agent production execution, workflow runtime, session storage | Operation modules share the owning instance and canonical module state |
| Desktop main | Composes window and IPC registration with modules for transfers, native views, layout, menus, downloads, overlays. The manifest includes nested modules; the refresh script keeps their relative paths |
| Web Desktop bridge | State, restoration, transfers, menus, events, surfaces; file-tree actions and query helpers keep the request lifecycle |
| Server runtime | Operations share the canonical Server state |
| Self-update verification | Binds the packaged WebSocket dispatch module that enforces its command restrictions; accepts previous package layouts for rollback |
| Server files | File actions and turn-file history are separate packages |
| Authentication, self-update | Authentication groups account and login orchestration; self-update groups verification, repair and delivery |
| Tests | Keep their execution layer, add feature directories; discovery includes nested tests. Large check files keep all scenarios, common fixtures and deterministic discovery. Subprocess acceptance is integration layer. Relocation preserves collected test identities and installed imports |
| Test feature folders | Named after the source package or concern they exercise. Unit: `context/` (compaction, system_prompt, render, tool_results, statistics), `store/` (session, file_history, project), `webui/` (transcript, branches, chat, settings), `providers/adapters/` (anthropic, openai, openai_codex), `programs/tools/computer_use/`. Component: `store/` (session, file_history), `execution/` (store, control), `webui/` (transcript, owner_auth), `providers/adapters/` (openai_codex, openai_completions, structured_output), `config/` (windows, docs_site, office_editor). `tests/e2e/web/`: chat, files, browser_tabs, applications. A new folder is a package exactly when its parent is one |
| Application tests | A test sits in the folder of what it exercises. A test that spans groups, and shared helpers, stay directly in the feature folder |
| `apps/web/tests` | A second level inside a feature where the source has one: `chat/messages/` (bubbles, cards, execution, list), `chat/composer/` (attach, input, controls, submit), `chat/transcript/` (rows, streaming, with the contract and replay tests beside them), `browser/` (pip, control, bookmarks, web-tab), `files/` (explorer, documents, paths), `settings/` (providers, memory, scheduler, appearance), `execution/` (activity, recovery, debugger), `tabs/` (canvas, strip), `ui/` (popups, rails) |
| `apps/desktop/tests` | Follows `apps/desktop/main`: windows, web-views, self-update, terminal, worker |
| `apps/cli/tests` | startup, input, rendering, repl, commands |
| Activity panel | `apps/web/components/right-sidebar/running/` keeps the overview panel; `pages/` the second-level pages (frame, row, geometry, wording, one page per kind); `runs/` the run list and one run opened in place; `agent-chart/` an Agent's time chart |
| Left whole | Generated Yoga bindings, vendored Ink renderer, peer provider adapters, Desktop main's composition, native terminal rendering, cohesive route collections, checkpoint transactions, security HTTP policy |

Direct code files (Python, JavaScript, TypeScript) per directory; feature subdirectories hold the rest.

| Directory | Direct code files |
| --- | --- |
| `apps/web/lib` | 7 |
| `apps/web/tests` | 0 |
| `openprogram/operations/self_update` | 3 |
| `openprogram/interfaces/server/routes` | 7 |
| `tests/component/webui` | 4 |
| `tests/unit/providers` | 5 |

**Release acceptance for structure changes**

| Area | Requirement |
| --- | --- |
| Review | Independent specification and quality review |
| Python | Three consecutive complete runs with four workers |
| Web and CLI | Tests and type checks |
| Desktop and applications | Desktop checks; application builds |
| Docs and browser | Documentation links; browser interaction tests |
| Packaging | Installed-wheel imports outside the checkout |
| Test cleanup | Uses the canonical SessionStore cache |
| Native recovery | Waits for actual startup and shutdown within explicit deadlines |
| External Office pack | Only when that pack is supplied |

## Implementation status

| Area | State | Covered by, or remaining |
| --- | --- | --- |
| Application roots, CLI ownership, maintenance scripts | Verified | Workspace checks and installed-wheel acceptance |
| Server ownership | Verified | Grouped routes, packaged assets and Server operations in the shared regression manifest |
| Desktop and Web decomposition | Verified | Native-view ownership, bridge state, transfer coordination, file operations and nested packaging keep executable coverage |
| Documentation structure | Under `reference/design/` | One current topic owner |
| Release and installed App | Per target | Installed-App checks and remote publication are separate from source regression results |

Long files are not automatically pending work. A further split needs a separate responsibility and behavioural coverage.
