DataOps Sentinel
by Tutusvip
README.md
# DataOps Sentinel
[](https://github.com/Tutusvip/dataops-sentinel/actions/workflows/tests.yml)



[](LICENSE)
**PT-BR:** O DataOps Sentinel é um auditor de governança de dados para PostgreSQL que **só lê** e nunca altera o banco. Ele funciona como **servidor MCP**, para agentes de IA como Claude, Cursor e Copilot, e como **CLI**, para pessoas e pipelines de CI.
- **O que verifica no banco:** nomenclatura, estrutura, arquitetura em camadas (raw → trusted → refined / Medallion), qualidade de SQL, segurança, operação e qualidade de dados.
- **O que verifica no ETL:** Pentaho, SQL, dbt e Airflow.
- **O que devolve:** cada achado com o SQL de correção sugerido.
Foi validado contra a cópia de um banco analítico de produção com cerca de 250 tabelas.
**EN:** Read-only governance auditor for PostgreSQL, exposed as an **MCP server** (for any MCP client) and a **CLI** (for people and CI).
It checks naming, structure, layered architecture, SQL quality, operations, security and (opt-in) data quality against a built-in best-practice profile that each project customizes in `sentinel.yaml`, and returns findings with suggested fix SQL. It also audits the ETL that feeds the database (Pentaho, SQL scripts, dbt, Python/Airflow). **It never changes the database.**
### Destaques / Highlights
- 67 built-in rules in 8 categories (naming, structure, layers, SQL, data, security, ops, ETL)
- 9 MCP tools with a token budget enforced by tests, so agents get compact, paginated answers
- Audits a `pg_dump` file in a throwaway Docker container (`--from-dump`), with no live database needed
- Safe ETL reorganization: dry-run plan with a hash, backup, verification and automatic rollback
- History and diff between runs, and consolidated Jira/GitHub issues (dry-run by default)
- 700+ automated tests
### Stack
Python 3.12 · PostgreSQL · MCP (Model Context Protocol) · Typer · Pydantic · SQLite · Docker · pytest · uv
## Install
```bash
uv sync
```
## Read-only database role (recommended)
```sql
CREATE ROLE sentinel_ro LOGIN PASSWORD 'change-me';
GRANT CONNECT ON DATABASE mydb TO sentinel_ro;
```
Catalog metadata is readable by any role; table data is read only when the opt-in data checks are enabled (see below). The connection also forces `default_transaction_read_only=on` and a `statement_timeout`.
Supported PostgreSQL versions: 13+ (SQL-standard `BEGIN ATOMIC` function bodies are analyzed on 14+).
## CLI
```bash
export SENTINEL_DSN=postgresql://sentinel_ro:change-me@localhost:5432/mydb
uv run sentinel audit # summary + sentinel-reports/sentinel-run-N.md
uv run sentinel audit --format html --fail-on CRITICAL
uv run sentinel rules # built-in rules
uv run sentinel audit --from-dump backup.dump # audit a pg_dump file (needs Docker)
uv run sentinel etl audit [FOLDER] # audit an ETL folder, no database needed
uv run sentinel etl organize [FOLDER] # plan safe ETL renames (dry run); see "Organize an ETL folder"
uv run sentinel check-query "DELETE FROM app.orders" # lint SQL without running it
uv run sentinel profile -c sentinel.yaml # effective profile
uv run sentinel diff # new/resolved findings between two runs
uv run sentinel issues [--apply] # Jira/GitHub issues (dry run by default)
uv run sentinel suggest-profile # starter sentinel.yaml inferred from the database
uv run sentinel catalog # naming conventions in use + adherence -> catalog-<timestamp>.md
```
Exit codes: `0` ok, `1` findings at or above `--fail-on`, `2` configuration/connection error.
## MCP clients
All clients run the same command; only the config file differs. Replace `<path>` with the absolute project path.
**Claude Code**
```bash
claude mcp add sentinel -e SENTINEL_DSN=postgresql://... -- uv --directory <path> run sentinel serve -c <absolute path to your sentinel.yaml>
```
**Claude Desktop** (`claude_desktop_config.json`), **Cursor** (`.cursor/mcp.json`), **Gemini CLI** (`settings.json`):
```json
{
"mcpServers": {
"sentinel": {
"command": "uv",
"args": ["--directory", "<path>", "run", "sentinel", "serve", "-c", "<absolute path to your sentinel.yaml>"],
"env": { "SENTINEL_DSN": "postgresql://..." }
}
}
}
```
**VS Code / Copilot** (`.vscode/mcp.json`):
```json
{
"servers": {
"sentinel": {
"type": "stdio",
"command": "uv",
"args": ["--directory", "<path>", "run", "sentinel", "serve", "-c", "<absolute path to your sentinel.yaml>"],
"env": { "SENTINEL_DSN": "postgresql://..." }
}
}
}
```
`report_dir` and `store_path` in `sentinel.yaml` are relative to the server's working directory (set by the MCP client) unless you make them absolute, so prefer absolute paths there.
**Shared server:** `uv run sentinel serve --transport streamable-http --port 8000` (endpoint `/mcp`).
## Tools
| Tool | What it returns |
|---|---|
| `run_audit` | run id, counts by severity/category, top 5 findings |
| `list_findings` | one page of findings (`id\|sev\|rule\|object\|message`) + `next_cursor` |
| `explain_finding` | why it matters + suggested fix SQL |
| `describe_object` | columns, indexes, FKs, layer, open findings of one table/view, of one ETL file (`etl:<path>`), or the read-only organize plan (`etl:organize`) |
| `export_report` | (`--full` only) path of the full md/json/html report (zero tokens of findings) |
| `get_profile` | effective rules, layers and budgets |
| `check_query` | lint one SQL statement without running it (QRY rules); uses index info from this database's latest audit |
| `compare_runs` | new, resolved and persistent findings between two audits of the same database (counts + top new) |
| `catalog_conventions` | naming conventions in use per layer (and per source in raw) with adherence to the profile standard; no filters = summary, `aspect`/`layer`/`source` = variants + deviations with suggested names |
The server exposes 9 tools by default. `sentinel serve --analysis-only` hides `export_report` (it writes files) and the organize plan view (`etl:organize`), leaving 8. In both modes the server never writes to the database nor applies renames. Issue trackers are never reachable from MCP: creating issues is a CLI/CI action (see below).
## Conventions catalog
`sentinel catalog` (CLI) and `catalog_conventions` (MCP, both modes) answer "which naming conventions are in use here, and how far is each layer from the standard?". The CLI takes a fresh snapshot of the database (with the ETL when `etl.root` is set); the MCP tool uses the snapshot of the latest audit run (call `run_audit` first, with `etl.root` set to include the ETL). Both read names and types only, never data values, and never change anything. `conventions.applies_to_layers` must name layers defined in `layers`.
- Described everywhere: column and table name styles (snake, concatenated, camel, upper, `__c`, `u_`), view prefixes, concept prefixes (`dt_` vs `data_`), prefix/type mismatches, redundant words (`dt_data_entrega`), word separation (`dt_dataentrega`), table names, ETL names. In `raw` the catalog is split per source (ETL connection or table glob).
- Adherence (ok/total plus a suggested name per deviation) is computed only for layers in `conventions.applies_to_layers` and only for aspects that have a configured standard. Raw is described, never charged.
```yaml
# sentinel.yaml (full approved example: sentinel.example.yaml)
conventions:
applies_to_layers: [trusted, refined]
view_prefix: vw_
concepts:
data: {prefix: dt_, alternatives: [data_, date_], types: [date, timestamp, timestamptz], detect_by_type: true}
valor: {prefix: vl_, alternatives: [valor_, vlr_], types: [numeric]}
redundant_words:
dt_: [data, dat, date, dt]
vl_: [valor, vlr, value, vl]
vocabulary: [frete, carga] # optional extra words for the word-separation check
sources:
- {name: erp, connections: [ERP_HANA]}
- {name: crm, tables: ["raw.account", "raw.*__c"]}
```
- Word separation uses a vocabulary built from the catalog itself (every standalone `_` segment of 3+ letters in any table/column name, plus `conventions.vocabulary`): `id_fiscalvendedor` -> `id_fiscal_vendedor`, while single long words (`dt_fabricacao`) stay clean.
- `detect_by_type: true` on a concept flags columns of its `types` that lack the prefix (a date column without `dt_`), with a suggested name. Suggestions that would leave an empty name (`status__c`) are omitted and say "rename by hand".
```bash
uv run sentinel catalog # writes catalog-<timestamp>.md to report_dir, prints the summary
uv run sentinel catalog --format json
```
The markdown file has one section per aspect (variant tables, every deviation with its suggestion, and an `Escolha: [ ]` line where no standard is configured yet, to record the decision). Over MCP, call `catalog_conventions()` for the compact summary, then `catalog_conventions(aspect="concept_prefix", layer="trusted")` for variants, examples and a page of deviations (`cursor` continues).
## Rule categories
67 built-in rules; run `uv run sentinel rules` for ids, severities and rationale.
| Category | Rules | What it checks |
|---|---|---|
| NAM | 10 | naming conventions (snake_case, length, reserved words, key/boolean/temporal names) |
| STR | 12 | structure (primary keys, FK indexes, duplicate/unused indexes, types, comments) |
| LAY | 4 | layered architecture (prefixes, dependency direction, orphans, cycles) |
| QRY | 9 | SQL quality in views, SQL functions, workload and `check_query` |
| DAT | 5 | data quality on a sample (opt-in, counts only) |
| SEC | 2 | PUBLIC grants and superuser login roles (only when there is more than one, keeping one break-glass account) |
| OPS | 2 | table bloat and stale statistics (`operations.min_dead_tuples` is the row floor for both rules) |
| ETL | 23 | ETL files (Pentaho, SQL scripts, dbt, Python/Airflow): security, robustness, organization, layers and database cross-checks (see [ETL governance](#etl-governance)) |
Note: PostgreSQL expands `*` when it stores a view definition, so `QRY_SELECT_STAR` cannot be seen on views; it is detected in SQL function bodies, workload statements and `check_query`.
## Audit a backup file
`sentinel audit --from-dump FILE` audits a `pg_dump` file (custom format `-Fc` or plain `.sql`) without a live database. Sentinel restores it into a throwaway Postgres container, audits that copy with the normal read-only engine and the same rules, and removes the container afterwards (even after a failure or Ctrl+C).
```bash
uv run sentinel audit --from-dump backup.dump
uv run sentinel audit --from-dump backup.sql --pg-version 15 # when the dump does not state its server version
uv run sentinel audit --from-dump backup.dump --keep # keep the container to explore it
```
- **Requirements:** Docker (Desktop or engine) running. The image `postgres:<major>` is pulled on first use; the major version is read from the dump header unless you pass `--pg-version N` (N >= 13; for custom dumps the version implied by the archive format is also respected, and a restore that fails with "unsupported version" tells you to pass the pg_dump client version).
- **Skipped rules:** `STR_UNUSED_INDEX`, `OPS_TABLE_BLOAT`, `OPS_STALE_STATS` and `QRY_TOP_COST` depend on usage statistics that a restored copy does not have, so they are disabled and the report says so. The other rules (including ETL cross-checks when `etl.root` is set) run normally.
- **Restore errors:** missing extensions or roles do not stop the audit; a note reports how many errors the restore had ("some objects may be missing").
- **`--keep`:** prints the container name and `docker exec -it <name> psql -U postgres restored`; remove it with `docker rm -f <name>`.
- **Privacy:** everything stays on your machine. The container listens on `127.0.0.1` only, on a random port, with a random password that is never printed or logged.
- **Trust:** the restore runs the dump as superuser inside a local container; only use dumps from a trusted source.
- **History and `--name`:** runs are keyed by the database name found in the dump (file name when the dump has none; the report then carries a note). Pass `--name NAME` to choose the key, e.g. to compare successive plain dumps with different file names.
- **`diff` and `issues`:** `sentinel diff --from-dump FILE` and `sentinel issues --from-dump FILE [--name NAME]` select the history of that dump's database (no restore, no Docker needed):
```bash
uv run sentinel audit --from-dump jan.dump --name vendas
uv run sentinel audit --from-dump feb.dump --name vendas
uv run sentinel diff --from-dump feb.dump --name vendas
```
## Organize an ETL folder
`sentinel etl organize [FOLDER] [-c sentinel.yaml] [--relative-paths]` is a dry run: it prints `kind|path|old|new|status` for generic step names, file-name casing, job references and obsolete folders (status `planned` or `unsafe: <reason>`), the counts, `plan hash: <h>` and the exact command to apply.
- Apply only on the CLI: `sentinel etl organize FOLDER --apply --plan-hash <h>`. Without the hash it exits 2. If the folder changed since the dry run, the hash no longer matches and nothing is touched.
- Before changing anything it writes a backup zip next to the folder (`backup: <zip>`), edits only the planned spans (other bytes and the file encoding stay identical), verifies that no new broken references appeared and rolls everything back on failure. Items marked `unsafe` are never applied.
- Moving obsolete folders needs `etl.archive_dir`. `--relative-paths` also rewrites job references to the renamed files as relative paths.
- MCP never applies: `describe_object("etl:organize")` returns the same plan (at most 40 rows, plus counts and hash).
## ETL governance
Sentinel also audits the ETL that feeds the database. It reads files only and never runs, edits or moves them.
- **Readers:** Pentaho Data Integration (`.ktr` transformations, `.kjb` jobs), SQL scripts (`.sql`), dbt projects and Python/Airflow files (`.py`; see below). Each file becomes a neutral model (steps, hops, connections, tables read and written, SQL commands). SQL sent to the database is also checked by the QRY rules (for example `QRY_SELECT_STAR` on a source query).
- **Audit without a database:** `uv run sentinel etl audit [FOLDER] [-c sentinel.yaml] [--format md|json|html] [--fail-on HIGH]`. `FOLDER` defaults to `etl.root`. Rules that need the database are skipped and the summary carries a note (`ETL-only audit: database cross-checks skipped (...)`).
- **Audit with a database:** set `etl.root` in `sentinel.yaml`; `sentinel audit` and the MCP `run_audit` then include the ETL and the cross-checks against the catalog become active.
- **MCP:** `describe_object("etl:<relative path>")` summarizes one file (steps, reads, writes, commands in one line, connections without secrets). ETL findings use `etl:<path>` or `etl:<path>#<step>` as object name.
- **Privacy:** passwords are never stored, logged or reported. The reader keeps only a yes/no flag that a connection has a password; XML with DTDs or entities is rejected as unsafe. Folders that match `etl.obsolete_dir_patterns` (backup, obsolete...) are listed (`ETL_OBSOLETE_IN_TREE`) but their files are not parsed.
```yaml
etl:
root: "C:/projeto/etl"
exclude: ["**/*.bak"]
folder_layers: {RAW: raw, TRUSTED: trusted, REFINED: refined} # default: folder name = layer name
generic_step_patterns: [] # extra regexes, on top of the built-in ones
file_name_pattern: "" # e.g. "^(HANA|SALESFORCE)_(RAW|TRUSTED)_[A-Za-z]+\.ktr$"
min_commit_size: 1000
full_reload_max_rows: 1000000
required_target_columns: [] # e.g. [loaded_at]
```
Layer rules use the same `layers:` of the profile (`schema`, `reads_from`).
### dbt projects
A folder with a `dbt_project.yml` is read as a dbt project; every `.sql` under its `model-paths` (default `models`) becomes a unit of kind `dbt_model`. Jinja is never rendered and nothing is executed (no `dbt compile`/`run`): `ref()`, `source()` and `this` are replaced textually, other Jinja is dropped.
- **What is read:** model SQL, `config(materialized=, schema=, alias=)`, folder-level config in `dbt_project.yml`, and `sources`/`models` YAML (schemas, descriptions). The write target follows `generate_schema_name` (`<target schema>_<custom schema>`) and the materialization (table, incremental, view...). Views, ephemeral and materialized-view models are listed under `defines` (they create objects without loading data, so `ETL_UNLOADED_TABLE` counts them as loaded).
- **`etl.dbt_target_schema`:** the dbt `target.schema` is not in the project files. Set it (for example `analytics`) so custom schemas resolve to `analytics_staging`; when empty, Sentinel uses the custom schema as written and adds one note per project saying the schema was assumed.
- **Skipped:** `target/`, `dbt_packages/` and `logs/` of the project, plus `.venv`, `venv`, `site-packages`, `__pycache__` and `.git` anywhere.
- **Rules:** layer rules work on the resolved schemas; `ETL_MISSING_DESCRIPTION` covers dbt models (use the YAML `description`); `ETL_FULL_RELOAD` does not apply to dbt models.
### Python and Airflow files
`.py` files are parsed with `ast` only. Sentinel never imports or executes user code.
- **SQL:** string literals passed to `execute`, `executemany`, `read_sql*`, `run`, `get_records`, `get_first`, `get_pandas_df`, `text` and SQL operators (`sql=`) become statements (also checked by the QRY rules). A name assigned once at module level to a string is resolved. f-strings, concatenation and `.format` are not analyzed and add the note `dynamic SQL at line N not analyzed`; a `.sql` template reference adds `sql file reference <x> at line N not analyzed`.
- **Connections:** `create_engine(...)` and `connect(...)` with literal arguments give a connection (host, database). The password is reduced to a yes/no flag and never stored, logged or reported, so `ETL_STORED_PASSWORD` and `ETL_HARDCODED_HOST` apply to Python code too.
- **Airflow:** a `DAG(...)` or `@dag` becomes a job (its tasks and the `>>`, `<<`, `set_upstream`/`set_downstream` dependencies); Airflow logs every task, so `ETL_NO_LOGGING` does not fire. `describe_object("etl:<file>.py")` shows the DAG and the file's SQL together.
- Files that are neither (plain utility modules) are ignored; files with syntax errors get the note `python unparseable`.
| Group | Rules |
|---|---|
| Security | `ETL_STORED_PASSWORD` (HIGH), `ETL_HARDCODED_HOST` |
| Robustness | `ETL_POSITIONAL_MAPPING`, `ETL_SMALL_COMMIT`, `ETL_FULL_RELOAD`, `ETL_NO_ERROR_PATH`, `ETL_NO_LOGGING`, `ETL_ABSOLUTE_PATH`, `ETL_BROKEN_REFERENCE`, `ETL_ORPHAN_STEP`, `ETL_DISABLED_HOP`, `ETL_UNPARSEABLE_FILE` |
| Organization | `ETL_GENERIC_STEP_NAME`, `ETL_FILE_NAMING`, `ETL_OBSOLETE_IN_TREE`, `ETL_MISSING_DESCRIPTION` |
| Layers and load contract | `ETL_LAYER_FOLDER_MISMATCH`, `ETL_LAYER_READ_DIRECTION`, `ETL_JOB_ORDER`, `ETL_MULTIPLE_WRITERS` |
| Database cross-checks | `ETL_TARGET_MISSING`, `ETL_UNLOADED_TABLE`, `ETL_TARGET_REQUIRED_COLUMN` |
That is 16 file rules (security, robustness, organization) plus 7 layer and database cross-checks. The layer rules need `layers:`; the last three need a database. `uv run sentinel rules` prints severity and rationale of each.
Notes:
- `ETL_GENERIC_STEP_NAME` is a heuristic: it flags default names (`Table input 2`) and a word plus separator plus number such as `HANA 10` or `RAW_4`. Names glued to a number (`SAP2`, `Q4`) and names equal to a table the step reads or writes are not flagged. Add `exceptions` (rule + object `etl:<path>#<step>`, with reason and expiry) or tune `etl.generic_step_patterns`, or disable the rule under `rules:`.
- ETL-only mode skips `ETL_TARGET_MISSING`, `ETL_UNLOADED_TABLE` and `ETL_TARGET_REQUIRED_COLUMN`; the note lists them.
## Workload analysis
QRY rules also read the top statements of `pg_stat_statements` (`queries.workload_top_n`, default 50). It is optional: when the extension is missing or unreadable, the audit still runs and the summary carries a note. Only DML statements (`SELECT`, `WITH`, `INSERT`, `UPDATE`, `DELETE`, `MERGE`, `VALUES`, `TABLE`) are kept; utility/DDL statements are dropped with a note, since they may carry unnormalized literals such as passwords on PostgreSQL 15 and older. Statements are truncated to 2,000 characters, and `QRY_DESTRUCTIVE_DDL` / `QRY_UPDATE_DELETE_NO_WHERE` do not apply to workload statements (ETL reloads are legitimate). To enable it:
```
# postgresql.conf (restart required)
shared_preload_libraries = 'pg_stat_statements'
```
```sql
CREATE EXTENSION pg_stat_statements;
GRANT pg_read_all_stats TO sentinel_ro; -- to see statements from other roles
```
## Data checks (opt-in)
Off by default (`data.enabled: false` in `sentinel.yaml`). When enabled, Sentinel reads a **sample** (`data.sample_rows`, default 1000) of the tables in `data.tables` (globs; empty = all) and reports **only counts**: sampled values are never stored, logged or returned. Checks: NOT NULL candidates, duplicate natural keys, orphan rows, domain violations and PII detection. Only tables are checked (views are not). Non-text and sensitive columns are probed only with `(col IS NULL)`, never read; columns listed in `data.domains` are read as text so any type compares safely. Data checks run only when `DAT` is among the selected categories.
Natural-key and orphan probes are not sampled: they scan the full table (bounded to 1000 groups/rows and by `budgets.db_statement_timeout_ms`), so enable them on large tables knowingly.
PII detection (text columns not listed in `data.sensitive_columns`): e-mail always; CPF only when punctuated or when at least 50% of the column's values match; card numbers only when grouped with separators or at least 50% match (Luhn checked).
The role must be able to read data:
```sql
GRANT pg_read_all_data TO sentinel_ro; -- PostgreSQL 14+
-- or: GRANT SELECT ON ALL TABLES IN SCHEMA app TO sentinel_ro;
```
Queries are bounded by the `statement_timeout`; a failure becomes a note, not an audit error.
## Documented relationships
Warehouses loaded with `TRUNCATE` cannot keep real foreign keys. Declare the logical ones in `sentinel.yaml`:
```yaml
relationships:
- child: dw.fato_vendas
columns: [id_cliente]
parent: dw.dim_cliente
parent_columns: [id_cliente] # default: same as columns
```
`STR_RELATIONSHIP_INVALID` (MEDIUM) reports missing tables or columns, differing column types and parent keys without a PK/UNIQUE. `DAT_RELATIONSHIP_ORPHANS` (MEDIUM) counts child rows (non-null keys) with no match in the parent: "N of M rows in child have no match in parent". The probe is a read-only `count(*)` with the statement timeout, runs whenever `relationships` is set (even with `data.enabled: false`), only for valid relationships, and only counts are stored. `describe_object` lists each table's relationships.
## Low token consumption (guaranteed by tests)
Guaranteed limit, with the cost measured on a 20,000-finding database:
| Item | Limit | Measured |
|---|---|---|
| Tool definitions + instructions (per turn) | 2,500 | 1,069 |
| `run_audit` | 600 | 171 |
| Default `list_findings` page | 1,200 | 412 |
| `list_findings` with `limit=100` | 4,000 | 1,967 |
| `explain_finding` | 800 | 108 |
| `compare_runs` (thousands of new and resolved findings) | 800 | 237 |
| `catalog_conventions` summary | 600 | within cap (budget test, 15 sources, 6 layers) |
| `catalog_conventions` detail page | 1,200 | within cap (budget test) |
| `export_report` | - | 25 |
(`check_query` is covered by the same budget tests; the fixed cost is measured with all 9 tools and in analysis-only mode, 8 tools.)
- Any response is capped at `budgets.max_response_tokens` (4,000).
- `budgets.max_tool_calls_per_session` (200) stops runaway agents.
- Full results go to a file via `export_report`, never into the context.
## History
Every audit is stored, so you can see what changed between two runs of the same database:
```bash
uv run sentinel diff # previous run -> latest run
uv run sentinel diff --a 3 --b 7 # explicit run ids (older first)
```
The output lists new, resolved and persistent findings (matched by fingerprint = rule + object), with the top new and resolved ones. The MCP tool `compare_runs` returns the same data.
## Issues (Jira / GitHub)
`sentinel issues` turns recurring findings into tracker issues. It is a CLI/CI command only: the tracker is contacted solely by `sentinel issues --apply`, and MCP tools never create issues.
```yaml
# sentinel.yaml
issues:
provider: github # none | jira | github
min_severity: HIGH # only findings at least this severe
min_runs: 2 # present in at least this many recent runs...
window_runs: 5 # ...out of the last N runs of the same database
max_objects: 50 # objects listed in the issue body (max 200)
github: {repo: acme/data} # token_env: GITHUB_TOKEN, api_url: https://api.github.com
# jira: {url: "https://acme.atlassian.net", project_key: DATA, issue_type: Task}
```
Credentials come only from environment variables (names configurable with `token_env` / `email_env`); they are never written to the config, logs or messages:
| Provider | Variables | Minimum permissions |
|---|---|---|
| GitHub | `GITHUB_TOKEN` | fine-grained token with Issues read/write on the repo |
| Jira Cloud | `JIRA_EMAIL`, `JIRA_API_TOKEN` | create issues and add comments in the project |
How it behaves:
- **Dry run by default.** `uv run sentinel issues` prints `would-sync|-|label|title` lines and changes nothing; pass `--apply` to write. Each result line is printed as soon as it is produced, so a failure part-way keeps the earlier lines and ends with the error (exit 2).
- **One issue per (database, rule)**, not per occurrence: findings at or above `min_severity` that recur in at least `min_runs` of the last `window_runs` runs are consolidated into one draft listing up to `max_objects` objects and the path of the full report.
- **Deduplication by label** `sentinel-<target>-<rule>`: if an open issue with that label exists, Sentinel adds a comment with the current count instead of creating another.
- **GitHub labels**: dedupe relies on the per-rule label `sentinel-<target>-<rule>`, which GitHub creates on the fly only when the token may set labels (triage/push access). If it cannot, GitHub silently drops the labels and every run would open a duplicate; Sentinel detects this right after creating the issue and stops with an error naming the issue to close. Creating only the `sentinel` label does not fix it: fix the token permissions.
- `--run N` picks a specific run (default: latest of this database); run ids are positive. Without `--run`, the database is taken from the DSN variable (`SENTINEL_DSN`); if neither is set the command refuses to guess and exits 2. The first output line is always `run <id> on <database> (target <id8 or local>)`. The recurrence window only counts runs up to the chosen run.
- The dry run also writes the markdown report to `report_dir`. The `Full report:` path in an issue body refers to the machine that ran the sync; in CI, upload the report as an artifact.
Example CI schedule (GitHub Actions). History must survive between scheduled runs, so the store lives in the workspace and is persisted with `actions/cache`:
```yaml
# sentinel.ci.yaml (committed next to sentinel.yaml; add your other settings here too)
store_path: .sentinel/sentinel.db
report_dir: sentinel-reports
issues: {provider: github, github: {repo: acme/data}}
```
```yaml
on:
schedule: [{cron: "0 6 * * 1-5"}]
permissions: {contents: read, issues: write}
jobs:
sentinel:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v5
- run: uv sync
- uses: actions/cache@v4 # restores the newest cache, saves a new one per run
with:
path: .sentinel
key: sentinel-history-${{ github.run_id }}
restore-keys: sentinel-history-
- run: uv run sentinel audit -c sentinel.ci.yaml --fail-on NONE
env: {SENTINEL_DSN: "${{ secrets.SENTINEL_DSN }}"}
- run: uv run sentinel issues -c sentinel.ci.yaml --apply
env: {GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}", SENTINEL_DSN: "${{ secrets.SENTINEL_DSN }}"}
- uses: actions/upload-artifact@v4
with: {name: sentinel-reports, path: sentinel-reports}
```
`min_runs` needs at least that many cached runs before any issue appears (the default needs 2 scheduled runs). Without the cache step the history is lost on every run and no issue is ever created.
## Plugins
Rules too complex for `custom_rules` can be written in Python. A plugin is an importable module that registers rules with `@rule`; list it in `sentinel.yaml`:
```yaml
plugins: [acme_rules]
```
```python
# acme_rules.py (must be importable: on PYTHONPATH or installed)
from sentinel.models import Category, Severity
from sentinel.rules.base import Hit, rule
@rule("ACME_NO_TMP_TABLES", Category.CUSTOM, Severity.LOW, "Temporary tables must not live in production schemas.")
def no_tmp_tables(snap, profile):
for t in snap.tables:
if t.name.startswith("tmp_"):
yield Hit(t.kind, t.fqn, "temporary table in production schema")
```
Rules are pure functions of the snapshot (no I/O) and can be tuned under `rules:` like any other. A plugin's rules run only for profiles that list it. **Importing a plugin executes its code**: only list modules you trust. An import failure or a duplicate rule id stops with an instructive error, and the MCP tool `get_profile` warns (`plugins without active rules: x`) when a listed plugin registered nothing.
The `sentinel` console script does not put the current directory on the import path, so make the plugin importable explicitly:
```powershell
$env:PYTHONPATH = "C:\path\to\plugins"; uv run sentinel audit
```
```bash
PYTHONPATH=/path/to/plugins uv run sentinel audit
```
## Suggest a profile
```bash
uv run sentinel suggest-profile -o sentinel.suggested.yaml
```
Inspects the database and writes a commented starter profile for human review: the dominant table plurality, layers by schema with a dominant prefix (at least 60% of at least 3 objects) or a well-known layer name (raw, landing, bronze, staging, stg, silver, trusted, intermediate, int, gold, refined, curated, mart, marts; also `<name>_...`) even without a prefix, with `reads_from` taken from catalog dependencies or else from the conventional raw -> trusted -> refined order, `NAM_NO_HUNGARIAN` disabled when most tables already use such a prefix, and `naming.boolean_prefixes` extended with a dominant boolean-column prefix (e.g. `flag_`). Each suggestion is printed with its reason. It refuses to overwrite an existing file unless you pass `--force`.
## Customizing
Copy `sentinel.example.yaml` to `sentinel.yaml`. Unknown keys and unknown rule ids are rejected with a suggestion.
`queries.allow_truncate_reload: true` (default false) makes `QRY_DESTRUCTIVE_DDL` skip functions/procedures whose only destructive statements are `TRUNCATE` of tables the same routine also `INSERT`s into (the ETL reload pattern); `DROP`, `ALTER` and a `TRUNCATE` without a matching `INSERT` still fire.
Profile notes: `naming.timestamp_prefixes` / `naming.date_prefixes` (default none) let `NAM_TEMPORAL_SUFFIX` accept `dt_created` as well as `created_at` (case-insensitive); the fix SQL still appends the suffix.
`naming.pk_column` (default `"id"`) sets the primary key name `NAM_PK_NAME` expects; `{table}` expands to the lowercase table name with every run of non `[a-z0-9]` characters replaced by `_` and trimmed, so `pk_column: "id_{table}"` expects `id_carga` on `carga` and `id_minhatabela` on `@MINHATABELA`. The message and the fix SQL use the rendered name. To accept a view prefix such as `vw_`, simply leave it out of `naming.forbidden_prefixes` (`NAM_NO_HUNGARIAN`).
## Development
```bash
uv run pytest -m "not integration" # fast suite, no database
docker compose up -d --wait # Postgres 16 on port 54329
uv run pytest -m integration
```
## Roadmap
See [docs/ROADMAP.md](docs/ROADMAP.md): Power BI reader, end-to-end lineage, PyPI/Docker distribution.
## Author
**Thales Sousa**, Data Engineer: [LinkedIn](https://www.linkedin.com/in/thales-sousa-249062234/) · [GitHub](https://github.com/Tutusvip)
## License
[MIT](LICENSE)