Files
2026-11-20 18:22:13 +03:00

172 lines
7.3 KiB
Markdown

# Agent instructions
This file describes the engineering rules, architecture, and workflow for
coding agents working on `omg-pgs`.
## What this project is
`omg-pgs` is a single Rust binary that contains:
1. a database-aware PostgreSQL language server (LSP over stdin/stdout);
2. a REST API that executes the SQL statement located at a file and line.
The database used for a statement is selected by a line comment in the SQL
file:
```sql
-- @database: postgresql://user:password@localhost:5432/main
SELECT * FROM users;
```
A file may contain any number of directives. Each directive changes the
database for all following statements.
## Non-negotiable behavior
These invariants define the product. Do not change them without an explicit
request:
1. **Directive-scoped work.** A statement is connected to, checked against,
completed from, and executed against the database of the last non-empty
`-- @database:` directive before it. Never fall back to a default database.
2. **No directive means no database work.** If a document contains no
directive, do not open connections, do not publish diagnostics, and return
no completion/hover/semantic tokens/formatting/symbols. The REST API must
return an error.
3. **No false-positive diagnostics.** If the LSP shows no diagnostics for a
statement, the REST API must be able to execute it. Use `libpg_query` for
syntax and `PREPARE` for name/type resolution. Do not invent diagnostics
from heuristics in the lexer or catalog cache.
4. **Connection failure is shown on the URL.** If a directed database cannot
be reached, underline the URL range in red and skip query diagnostics for
that database. A successful connection produces no connection diagnostic.
5. **Passwords never leak.** Use `redact_url` for logs and API responses. Do
not log raw connection strings.
6. **Statement context follows directives.** Directives apply from their
position forward. Comments before the first significant token are not part
of the statement text passed to PostgreSQL.
7. **REST port is explicit; LSP is stdio.** `--rest-port` is required and the
REST listener binds to `127.0.0.1`. The LSP uses stdin/stdout; stdout must
contain only LSP protocol frames. If the REST port cannot be bound, log a
warning and keep the LSP running in LSP-only mode.
8. **English only.** Code comments, doc comments, diagnostics, documentation,
commit messages, and agent-facing text are written in English.
## Architecture map
| Path | Responsibility |
| --- | --- |
| `src/sql/lexer.rs` | PostgreSQL-aware lexer that keeps working on malformed SQL. Used for splitting and editing features. |
| `src/sql/document.rs` | Directive parsing, statement splitting, line/offset lookup, REST query selection. |
| `src/sql/analysis.rs` | Alias extraction, clause detection, identifier helpers, `libpg_query` error-token location. |
| `src/db/connection.rs` | URL validation, rustls connector, connection setup, URL redaction. |
| `src/db/schema.rs` | `pg_catalog` introspection and schema lookup helpers. |
| `src/db/validate.rs` | Classification of `PREPARE` errors and error positions. |
| `src/db/execute.rs` | REST query execution over the simple query protocol. |
| `src/db/mod.rs` | `DbManager`, per-URL connection, schema cache, validation. |
| `src/lsp/backend.rs` | Stdio transport, document state, request handlers. |
| `src/lsp/diagnostics.rs` | Connection, syntax and semantic diagnostics. |
| `src/lsp/completion.rs` | Schema-aware completion. |
| `src/lsp/hover.rs` | Schema-aware hover. |
| `src/lsp/semantic_tokens.rs` | `libpg_query` scanner + schema classification + delta encoding. |
| `src/lsp/formatting.rs` | Whole-document whitespace formatting. |
| `src/lsp/symbols.rs` | One outline entry per statement. |
| `src/rest.rs` | Axum router, JSON/CSV rendering, REST errors. |
| `src/position.rs` | UTF-8 byte offsets ↔ LSP UTF-16 positions. |
Keep the pure SQL core independent of I/O so it can be unit tested without a
database. Database-dependent logic belongs in `src/db`.
## Editing rules
- Keep changes minimal and consistent with the surrounding code.
- Public items need doc comments when their purpose is not obvious.
- Business errors use `anyhow::Result` with `.context(...)`; domain errors use
`thiserror`.
- Production code must not use `unwrap`, `expect`, `panic!`, or
`unreachable!` on user input. Test code may use them.
- Do not log or return unredacted connection strings.
- Prefer existing dependencies. Adding a dependency requires a concrete
justification.
- Do not add comments that restate code. Explain non-obvious constraints.
- Preserve the no-diagnostics-means-executable invariant when changing parsing
or validation.
- Semantic checks use the live database state. Do not silently start executing
DDL from the document to make later statements validate; that would be a
side-effecting validation step.
- When behavior changes, update `README.md` and this file.
## Common tasks
### Add a completion feature
1. Add a pure helper or branch in `src/lsp/completion.rs`.
2. Use `analysis::Aliases` for alias-aware scopes.
3. Add a unit test with a hand-built `Schema`; never require a DB in unit tests.
4. If a new clause changes context detection, update `analysis::current_clause`
and its tests.
### Add a diagnostic
1. Decide whether it is authoritative. Syntax must come from `libpg_query`;
name/type errors must come from the server (`PREPARE`).
2. Map every error to a document byte span using `LineIndex`.
3. Add tests for both the valid and invalid cases.
4. Do not add heuristic diagnostics that could reject a valid query.
### Change directive or statement parsing
1. Update `src/sql/document.rs`.
2. Cover semicolons in strings, quoted identifiers, dollar strings, nested
block comments, and line comments in tests.
3. Verify directive assignment across multiple databases and CRLF files.
4. Update the REST selection tests.
### Change REST output
1. Update `src/rest.rs` for both JSON and CSV.
2. Keep values as PostgreSQL text; represent `NULL` as JSON `null` and an
empty CSV field.
3. Keep the 60-second timeout and the documented status codes.
4. Add an Axum `oneshot` test for request-validation paths.
## Validation
Before finishing a change, run:
```bash
cargo fmt --all -- --check
cargo clippy --all-targets -- -D warnings
cargo test --all-targets
```
Native build prerequisites for `pg_query` are a C compiler, libclang, and
`protoc`.
Unit tests must pass without a PostgreSQL server. Opt-in integration tests
run when `OMG_PGS_TEST_DATABASE_URL` is set:
```bash
OMG_PGS_TEST_DATABASE_URL=postgresql://user:password@localhost:5432/db \
cargo test --test database
```
For end-to-end changes
involving real metadata, validation, or query execution, test against a local
PostgreSQL instance with at least two databases and verify:
- per-statement database switching in one file;
- connection error highlighting on the directive URL;
- a missing table producing a server-side diagnostic with SQLSTATE;
- JSON and CSV REST output;
- LSP completion, hover, semantic tokens, formatting, and shutdown.
Do not claim that a test passed unless it was actually run and the output was
seen.
## Scope discipline
Do not fix unrelated bugs, reformat unrelated files, or broaden the change.
If a limitation is intentional (DDL semantic checks, no inlay hints, stdio-only
transport), document it instead of silently adding a large subsystem.