bricksentry 0.1.27__tar.gz → 0.1.28__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. {bricksentry-0.1.27 → bricksentry-0.1.28}/CHANGELOG.md +12 -0
  2. {bricksentry-0.1.27 → bricksentry-0.1.28}/PKG-INFO +10 -5
  3. {bricksentry-0.1.27 → bricksentry-0.1.28}/README.md +8 -4
  4. bricksentry-0.1.28/deploy/databricks-app/requirements.txt +1 -0
  5. {bricksentry-0.1.27 → bricksentry-0.1.28}/examples/databricks/bricksentry_validation.ipynb +1 -1
  6. {bricksentry-0.1.27 → bricksentry-0.1.28}/examples/databricks/bricksentry_validation.py +1 -1
  7. {bricksentry-0.1.27 → bricksentry-0.1.28}/pyproject.toml +2 -1
  8. {bricksentry-0.1.27 → bricksentry-0.1.28}/server.json +2 -2
  9. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/__init__.py +1 -1
  10. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/agent_tools.py +22 -5
  11. bricksentry-0.1.28/src/bricksentry/agent_view.py +267 -0
  12. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/backends/base.py +5 -0
  13. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/backends/databricks_backend.py +35 -0
  14. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/changes.py +20 -7
  15. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/cli.py +22 -6
  16. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/diff.py +26 -6
  17. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/explain.py +3 -2
  18. bricksentry-0.1.28/src/bricksentry/mcp_server.py +192 -0
  19. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/models.py +3 -1
  20. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/policy.py +4 -0
  21. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/validation.py +26 -1
  22. {bricksentry-0.1.27 → bricksentry-0.1.28}/templates/job-check/databricks_template_schema.json +2 -2
  23. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/test_0110.py +2 -1
  24. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/test_0123.py +1 -1
  25. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/test_0127.py +1 -1
  26. bricksentry-0.1.28/tests/test_0128.py +235 -0
  27. bricksentry-0.1.27/deploy/databricks-app/requirements.txt +0 -1
  28. bricksentry-0.1.27/src/bricksentry/agent_view.py +0 -125
  29. bricksentry-0.1.27/src/bricksentry/mcp_server.py +0 -110
  30. {bricksentry-0.1.27 → bricksentry-0.1.28}/.gitignore +0 -0
  31. {bricksentry-0.1.27 → bricksentry-0.1.28}/CONTRIBUTING.md +0 -0
  32. {bricksentry-0.1.27 → bricksentry-0.1.28}/LICENSE +0 -0
  33. {bricksentry-0.1.27 → bricksentry-0.1.28}/SECURITY.md +0 -0
  34. {bricksentry-0.1.27 → bricksentry-0.1.28}/action.yml +0 -0
  35. {bricksentry-0.1.27 → bricksentry-0.1.28}/deploy/container/Dockerfile +0 -0
  36. {bricksentry-0.1.27 → bricksentry-0.1.28}/deploy/databricks-app/README.md +0 -0
  37. {bricksentry-0.1.27 → bricksentry-0.1.28}/deploy/databricks-app/app.yaml +0 -0
  38. {bricksentry-0.1.27 → bricksentry-0.1.28}/deploy/databricks-app/bricksentry.yml +0 -0
  39. {bricksentry-0.1.27 → bricksentry-0.1.28}/deploy/databricks-app/databricks.yml +0 -0
  40. {bricksentry-0.1.27 → bricksentry-0.1.28}/deploy/databricks-app/grants.sql +0 -0
  41. {bricksentry-0.1.27 → bricksentry-0.1.28}/examples/databricks/bricksentry.yml +0 -0
  42. {bricksentry-0.1.27 → bricksentry-0.1.28}/examples/databricks/bricksentry_check_my_table.ipynb +0 -0
  43. {bricksentry-0.1.27 → bricksentry-0.1.28}/examples/databricks/bricksentry_check_my_table.py +0 -0
  44. {bricksentry-0.1.27 → bricksentry-0.1.28}/examples/databricks/bricksentry_hr_walkthrough.ipynb +0 -0
  45. {bricksentry-0.1.27 → bricksentry-0.1.28}/examples/databricks/bricksentry_hr_walkthrough.py +0 -0
  46. {bricksentry-0.1.27 → bricksentry-0.1.28}/examples/databricks/bricksentry_quickstart.ipynb +0 -0
  47. {bricksentry-0.1.27 → bricksentry-0.1.28}/examples/databricks/bricksentry_quickstart.py +0 -0
  48. {bricksentry-0.1.27 → bricksentry-0.1.28}/examples/databricks/github-workflow.yml +0 -0
  49. {bricksentry-0.1.27 → bricksentry-0.1.28}/examples/databricks/policy.yml +0 -0
  50. {bricksentry-0.1.27 → bricksentry-0.1.28}/examples/demo/agent_loop_demo.py +0 -0
  51. {bricksentry-0.1.27 → bricksentry-0.1.28}/scripts/build_notebook.py +0 -0
  52. {bricksentry-0.1.27 → bricksentry-0.1.28}/scripts/render_demo_image.py +0 -0
  53. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/__main__.py +0 -0
  54. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/assess.py +0 -0
  55. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/backends/__init__.py +0 -0
  56. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/backends/duckdb_backend.py +0 -0
  57. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/config.py +0 -0
  58. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/demo.py +0 -0
  59. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/github.py +0 -0
  60. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/history.py +0 -0
  61. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/job.py +0 -0
  62. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/job_demo.py +0 -0
  63. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/lineage.py +0 -0
  64. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/measures.py +0 -0
  65. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/netguard.py +0 -0
  66. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/notify.py +0 -0
  67. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/policy_templates.py +0 -0
  68. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/preview.py +0 -0
  69. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/py.typed +0 -0
  70. {bricksentry-0.1.27 → bricksentry-0.1.28}/src/bricksentry/report.py +0 -0
  71. {bricksentry-0.1.27 → bricksentry-0.1.28}/templates/job-check/README.md +0 -0
  72. {bricksentry-0.1.27 → bricksentry-0.1.28}/templates/job-check/template/{{.project_name}}/.gitignore +0 -0
  73. {bricksentry-0.1.27 → bricksentry-0.1.28}/templates/job-check/template/{{.project_name}}/README.md.tmpl +0 -0
  74. {bricksentry-0.1.27 → bricksentry-0.1.28}/templates/job-check/template/{{.project_name}}/databricks.yml.tmpl +0 -0
  75. {bricksentry-0.1.27 → bricksentry-0.1.28}/templates/job-check/template/{{.project_name}}/resources/bricksentry_check.job.yml.tmpl +0 -0
  76. {bricksentry-0.1.27 → bricksentry-0.1.28}/templates/job-check/template/{{.project_name}}/src/bricksentry_check.py +0 -0
  77. {bricksentry-0.1.27 → bricksentry-0.1.28}/templates/job-check/template/{{.project_name}}/src/bricksentry_demo.py +0 -0
  78. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/conftest.py +0 -0
  79. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/test_0112.py +0 -0
  80. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/test_0114.py +0 -0
  81. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/test_0120.py +0 -0
  82. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/test_0121.py +0 -0
  83. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/test_0122.py +0 -0
  84. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/test_0126.py +0 -0
  85. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/test_018.py +0 -0
  86. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/test_019.py +0 -0
  87. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/test_assess_policy.py +0 -0
  88. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/test_check_notebook.py +0 -0
  89. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/test_databricks_and_uc.py +0 -0
  90. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/test_demo.py +0 -0
  91. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/test_diff.py +0 -0
  92. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/test_hr_notebook.py +0 -0
  93. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/test_notebook.py +0 -0
  94. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/test_notify_templates.py +0 -0
  95. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/test_preview_agents.py +0 -0
  96. {bricksentry-0.1.27 → bricksentry-0.1.28}/tests/test_sample_guard_and_store.py +0 -0
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.28 (2026-11-17)
4
+
5
+ Security fixes from live-test round 9 on 0.1.27 (MERGE, allowlist bypasses, metadata injection, remote access, governance features). Agents still never received production values; these close the remaining ways to learn about tables they shouldn't. Every round-9 attack was re-run on the fixes and refused or handled; the 15-scenario battery passed 15 of 15 on Databricks, and a live Unity Catalog row filter gave `needs_human` instead of a silent pass.
6
+
7
+ - **`agent_tables` covers every table an agent touches.** It only checked the target, so an agent could read a forbidden table inside an allowed write (subquery, join, CTE, `MERGE ... USING`, `INSERT ... SELECT`) or name it as the candidate in `assess_change`, and learn its row counts. Statements are now parsed with a real SQL parser (sqlglot, a new dependency) and every table they read must be listed; agent-named candidates too; `explain_diff` and `safe_to_ship` refuse assessments of unlisted tables. What can't be checked by name is refused: table functions (`table_changes`, `read_files`), `IDENTIFIER(...)`, path-based tables, and SQL that doesn't parse. **If you use `agent_tables`:** sources of MERGE and INSERT ... SELECT must now be listed too, written with their full name (e.g. `main.sales.updates`), or agent previews that read them are refused. The CLI and Python API are unaffected.
8
+ - **Column masks and row filters can't pass silently.** A masked column with 50 real changes diffed as unchanged. bricksentry now reads masks and row filters from Unity Catalog: masked columns aren't compared (`columns-not-compared`) and a row filter on either table gets `needs_human` (`row-filter`).
9
+ - **Behavior change: the MCP server needs a token on the network.** Over HTTP on anything but localhost it had no authentication, so anyone who could reach the port could call the tools. It now refuses to start there unless `BRICKSENTRY_MCP_TOKEN` is set (clients send `Authorization: Bearer <token>`) or `--insecure-no-auth` is passed for a network behind your own authenticating proxy. Databricks Apps needs no token (its sign-in is in front). Localhost gets DNS-rebinding protection again; `BRICKSENTRY_ALLOWED_HOSTS` lists extra host names.
10
+ - **Free text in tags and owners no longer reaches agents.** Tag values such as "IGNORE ALL PREVIOUS INSTRUCTIONS…" were passed to agents verbatim. Short, plain names and values (`pii`, `true`, `finance-team`) still are; longer or free text shows as `[text hidden: N chars]`, also where it was copied into summaries. Verdicts were never affected.
11
+ - `assess --from-git` gives one clear line (exit 2) when git fails or isn't installed, instead of a traceback.
12
+ - Quoted-value redaction in agent errors no longer eats apostrophes in words ("can't") and catches values that contain one ('O'Brien').
13
+ - New validation scenario `agent_allowlist` (the battery is now 15).
14
+
3
15
  ## 0.1.27 (2026-11-17)
4
16
 
5
17
  A safety release. A live round of leak, data-shape and race tests on 0.1.26 found four problems; two could mislead. A verification round re-ran every original attack on the fixes: no production value reached an agent, mid-diff rewrites returned the pinned state 3 of 3 times, MAP diffs and the key-order trap were exact, and the 14-scenario battery passed 14 of 14. Pinning makes a diff slower (a 1M-row diff took about 10 s instead of 5 s); that will be reduced in a later release.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: bricksentry
3
- Version: 0.1.27
3
+ Version: 0.1.28
4
4
  Summary: Change impact analysis and deployment guardrails for data changes on Databricks, for pipelines and the AI agents that edit them: data diffs, Unity Catalog blast radius, policy verdicts and rollback plans.
5
5
  Project-URL: Homepage, https://bricksentry.org
6
6
  Project-URL: Documentation, https://bricksentry.org/docs
@@ -26,6 +26,7 @@ Classifier: Typing :: Typed
26
26
  Requires-Python: >=3.10
27
27
  Requires-Dist: click>=8.1
28
28
  Requires-Dist: pyyaml>=6.0
29
+ Requires-Dist: sqlglot>=25
29
30
  Provides-Extra: all
30
31
  Requires-Dist: databricks-sdk>=0.30; extra == 'all'
31
32
  Requires-Dist: duckdb>=1.0; extra == 'all'
@@ -179,7 +180,7 @@ claude mcp add bricksentry -- uvx bricksentry-mcp --config /full/path/to/brickse
179
180
 
180
181
  The JSON works for the Claude desktop app, Cursor and other MCP clients. Use a **full path** to `bricksentry.yml`, because clients start the server from their own working folder. If an app can't find `uvx`, use its full path (`which uvx`). To share the setup through a repo, `claude mcp add -s project ...` writes it to `.mcp.json`; a relative path then works when Claude Code starts from the repo root. No config yet? `uvx --from bricksentry bricksentry init` writes a starter one.
181
182
 
182
- Already installed bricksentry with pip? `pip install "bricksentry[mcp,databricks]"` and run `bricksentry mcp --config /full/path/to/bricksentry.yml` instead. Add `--transport streamable-http` for remote agents.
183
+ Already installed bricksentry with pip? `pip install "bricksentry[mcp,databricks]"` and run `bricksentry mcp --config /full/path/to/bricksentry.yml` instead. Add `--transport streamable-http` for remote agents. Over HTTP the server listens on 127.0.0.1; to listen on any other address, set `BRICKSENTRY_MCP_TOKEN` and have clients send `Authorization: Bearer <token>` (it refuses to start otherwise). Databricks Apps needs no token, because its sign-in is in front.
183
184
 
184
185
  bricksentry is listed in the [official MCP Registry](https://registry.modelcontextprotocol.io/v0/servers?search=io.github.bricksentry/bricksentry) as `io.github.bricksentry/bricksentry`.
185
186
 
@@ -212,13 +213,15 @@ bricksentry usually runs with more read access than the agent that calls it, so
212
213
 
213
214
  The new value is hidden too, because an agent can write `SET note = ssn` and read its own "new" value. Humans keep the detail: the CLI, the Python API and the pull-request report show example values, except in tables or columns tagged `pii`, whose values a report never shows.
214
215
 
215
- **Counts can still leak information.** An agent could preview `DELETE ... WHERE ssn LIKE '1%'` and read the number of removed rows, then narrow it down. No masking stops that, so list the tables agents may assess or preview:
216
+ **Counts can still leak information.** An agent could preview `DELETE ... WHERE ssn LIKE '1%'` and read the number of removed rows, then narrow it down. No masking stops that, so list the tables agents may use:
216
217
 
217
218
  ```yaml
218
219
  agent_tables: ["main.sales_dev.*", "main.sales.orders"] # globs, any case; others are refused
219
220
  ```
220
221
 
221
- Without `agent_tables`, agents can check any table bricksentry can read. Run the MCP server under an identity that can read only what the agent should. Every agent `assess_change` and `preview_write`, refused or not, is logged to `bricksentry.audit` and to `audit.jsonl` in the assessment store (time, actor, tables, verdict, row counts), so a run of small probing previews is visible.
222
+ The list covers every table an agent touches: the target, every table its statement reads (subqueries, joins, CTEs, `MERGE ... USING`), and any candidate it names. Statements that can't be checked by name are refused: table functions such as `table_changes()` or `read_files()`, `IDENTIFIER(...)`, path-based tables and SQL that doesn't parse. Write full names (`main.sales.orders`) when your patterns have three parts. Sources count too: for an agent to preview `MERGE INTO {{target}} USING main.sales.updates ...`, list `main.sales.updates` (or a pattern covering it) as well; a source left off the list, or written without its catalog, is refused. Without `agent_tables`, agents can check any table bricksentry can read.
223
+
224
+ **Metadata is data, not instructions.** Tag names and values and owners reach agents only when short and plain (`pii`, `true`, `finance-team`); longer or free text, which anyone who can tag a table could write, shows as `[text hidden: N chars]`. Policies still see the full tags. Run the MCP server under an identity that can read only what the agent should. Every agent `assess_change` and `preview_write`, refused or not, is logged to `bricksentry.audit` and to `audit.jsonl` in the assessment store (time, actor, tables, verdict, row counts), so a run of small probing previews is visible.
222
225
 
223
226
  The same tools are plain Python functions in `bricksentry.agent_tools`, so you can use them from LangGraph, the OpenAI Agents SDK or the Databricks Agent Framework without MCP.
224
227
 
@@ -396,6 +399,8 @@ lineage:
396
399
 
397
400
  Typos are caught: an unknown key such as `sample_pc` prints a warning that names the right one (`did you mean 'sample_pct'?`) instead of being silently ignored.
398
401
 
402
+ **Column masks and row filters.** If a table in the diff has a Unity Catalog column mask, that column isn't compared (bricksentry's identity may see masked values, which hide changes); with a row filter, the diff may not see every row. Either way the check asks a human (`columns-not-compared`, `row-filter`).
403
+
399
404
  **Consistent reads.** Every diff reads both tables at the Delta version they had when it started (`VERSION AS OF`), so a job writing to them mid-check can't mix two states into one result. If the candidate gets a new version during the check, the result says so and asks a human to re-run. Views and other objects without time travel are read as they are, with a before-and-after version check.
400
405
 
401
406
  **Floats.** FLOAT and DOUBLE are compared exactly by default, so `0.1 + 0.2` and `0.3` differ. If a column changes everywhere but its total stays the same, the diff says it's likely rounding. Set `float_tolerance` to compare within a relative tolerance; NaN, infinity and NULL still compare exactly, and DECIMAL is always exact. MAP columns are compared by their entries sorted by key, so a map written in a different order isn't a change. A column the engine can't compare at all is left out with a note, and the check asks a human.
@@ -489,7 +494,7 @@ Every assessment records when it ran (UTC), the bricksentry version, a SHA-256 f
489
494
  - **Lineage is recorded at runtime.** Brand-new tables have no downstream history yet. Unity Catalog doesn't capture RDD operations, and UDFs hide column-level mapping; column lineage records source-to-target derivations, so a column used only in a filter or join may not appear.
490
495
  - **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
491
496
  - **Changed-table detection uses path globs** from config. It doesn't parse Asset Bundles yet.
492
- - **Validated on Databricks** (serverless, November 2026): a 2-million-row table with 0.1.4 (lineage, rollback plans, previews on shallow clones, every verdict level, the sampling guard catching a single changed row), then live runs of every release up to 0.1.27 on a Free Edition workspace with an HR pipeline: pull-request gating with comment updates, the bundle demo job, `check-last-change` and the newer-changes warning in the CLI, report, JSON and Slack, the refused-statement guards, outbound-URL checks, one-to-one matching of 2,000 NULL keys, exact totals over a million decimal rows, the audit trail, an AI agent attempting six risky changes on the live pipeline, the job task blocking a bad MERGE inside a real Databricks job, and worst-case rounds (50,000 NULL keys, near-max decimals, exotic types, 200-column tables) whose five findings were fixed in 0.1.26, and a round of leak, data-shape and race tests whose four findings were fixed in 0.1.27. Every run, with its numbers and the bugs it found, is in [VALIDATION.md](VALIDATION.md). The automated tests use DuckDB and a mocked SDK, so please run the [validation notebook](examples/databricks/bricksentry_validation.py) on your workspace and [share a validation report](https://github.com/bricksentry/bricksentry/issues/new?template=validation_report.yml), whether it passes or not.
497
+ - **Validated on Databricks** (serverless, November 2026): a 2-million-row table with 0.1.4 (lineage, rollback plans, previews on shallow clones, every verdict level, the sampling guard catching a single changed row), then live runs of every release up to 0.1.28 on a Free Edition workspace with an HR pipeline: pull-request gating with comment updates, the bundle demo job, `check-last-change` and the newer-changes warning in the CLI, report, JSON and Slack, the refused-statement guards, outbound-URL checks, one-to-one matching of 2,000 NULL keys, exact totals over a million decimal rows, the audit trail, an AI agent attempting six risky changes on the live pipeline, the job task blocking a bad MERGE inside a real Databricks job, and worst-case rounds (50,000 NULL keys, near-max decimals, exotic types, 200-column tables) whose five findings were fixed in 0.1.26, a round of leak, data-shape and race tests whose four findings were fixed in 0.1.27, and a round on MERGE, allowlist bypasses, metadata injection, remote access and governance features whose findings were fixed in 0.1.28. Every run, with its numbers and the bugs it found, is in [VALIDATION.md](VALIDATION.md). The automated tests use DuckDB and a mocked SDK, so please run the [validation notebook](examples/databricks/bricksentry_validation.py) on your workspace and [share a validation report](https://github.com/bricksentry/bricksentry/issues/new?template=validation_report.yml), whether it passes or not.
493
498
 
494
499
  ## Roadmap
495
500
 
@@ -132,7 +132,7 @@ claude mcp add bricksentry -- uvx bricksentry-mcp --config /full/path/to/brickse
132
132
 
133
133
  The JSON works for the Claude desktop app, Cursor and other MCP clients. Use a **full path** to `bricksentry.yml`, because clients start the server from their own working folder. If an app can't find `uvx`, use its full path (`which uvx`). To share the setup through a repo, `claude mcp add -s project ...` writes it to `.mcp.json`; a relative path then works when Claude Code starts from the repo root. No config yet? `uvx --from bricksentry bricksentry init` writes a starter one.
134
134
 
135
- Already installed bricksentry with pip? `pip install "bricksentry[mcp,databricks]"` and run `bricksentry mcp --config /full/path/to/bricksentry.yml` instead. Add `--transport streamable-http` for remote agents.
135
+ Already installed bricksentry with pip? `pip install "bricksentry[mcp,databricks]"` and run `bricksentry mcp --config /full/path/to/bricksentry.yml` instead. Add `--transport streamable-http` for remote agents. Over HTTP the server listens on 127.0.0.1; to listen on any other address, set `BRICKSENTRY_MCP_TOKEN` and have clients send `Authorization: Bearer <token>` (it refuses to start otherwise). Databricks Apps needs no token, because its sign-in is in front.
136
136
 
137
137
  bricksentry is listed in the [official MCP Registry](https://registry.modelcontextprotocol.io/v0/servers?search=io.github.bricksentry/bricksentry) as `io.github.bricksentry/bricksentry`.
138
138
 
@@ -165,13 +165,15 @@ bricksentry usually runs with more read access than the agent that calls it, so
165
165
 
166
166
  The new value is hidden too, because an agent can write `SET note = ssn` and read its own "new" value. Humans keep the detail: the CLI, the Python API and the pull-request report show example values, except in tables or columns tagged `pii`, whose values a report never shows.
167
167
 
168
- **Counts can still leak information.** An agent could preview `DELETE ... WHERE ssn LIKE '1%'` and read the number of removed rows, then narrow it down. No masking stops that, so list the tables agents may assess or preview:
168
+ **Counts can still leak information.** An agent could preview `DELETE ... WHERE ssn LIKE '1%'` and read the number of removed rows, then narrow it down. No masking stops that, so list the tables agents may use:
169
169
 
170
170
  ```yaml
171
171
  agent_tables: ["main.sales_dev.*", "main.sales.orders"] # globs, any case; others are refused
172
172
  ```
173
173
 
174
- Without `agent_tables`, agents can check any table bricksentry can read. Run the MCP server under an identity that can read only what the agent should. Every agent `assess_change` and `preview_write`, refused or not, is logged to `bricksentry.audit` and to `audit.jsonl` in the assessment store (time, actor, tables, verdict, row counts), so a run of small probing previews is visible.
174
+ The list covers every table an agent touches: the target, every table its statement reads (subqueries, joins, CTEs, `MERGE ... USING`), and any candidate it names. Statements that can't be checked by name are refused: table functions such as `table_changes()` or `read_files()`, `IDENTIFIER(...)`, path-based tables and SQL that doesn't parse. Write full names (`main.sales.orders`) when your patterns have three parts. Sources count too: for an agent to preview `MERGE INTO {{target}} USING main.sales.updates ...`, list `main.sales.updates` (or a pattern covering it) as well; a source left off the list, or written without its catalog, is refused. Without `agent_tables`, agents can check any table bricksentry can read.
175
+
176
+ **Metadata is data, not instructions.** Tag names and values and owners reach agents only when short and plain (`pii`, `true`, `finance-team`); longer or free text, which anyone who can tag a table could write, shows as `[text hidden: N chars]`. Policies still see the full tags. Run the MCP server under an identity that can read only what the agent should. Every agent `assess_change` and `preview_write`, refused or not, is logged to `bricksentry.audit` and to `audit.jsonl` in the assessment store (time, actor, tables, verdict, row counts), so a run of small probing previews is visible.
175
177
 
176
178
  The same tools are plain Python functions in `bricksentry.agent_tools`, so you can use them from LangGraph, the OpenAI Agents SDK or the Databricks Agent Framework without MCP.
177
179
 
@@ -349,6 +351,8 @@ lineage:
349
351
 
350
352
  Typos are caught: an unknown key such as `sample_pc` prints a warning that names the right one (`did you mean 'sample_pct'?`) instead of being silently ignored.
351
353
 
354
+ **Column masks and row filters.** If a table in the diff has a Unity Catalog column mask, that column isn't compared (bricksentry's identity may see masked values, which hide changes); with a row filter, the diff may not see every row. Either way the check asks a human (`columns-not-compared`, `row-filter`).
355
+
352
356
  **Consistent reads.** Every diff reads both tables at the Delta version they had when it started (`VERSION AS OF`), so a job writing to them mid-check can't mix two states into one result. If the candidate gets a new version during the check, the result says so and asks a human to re-run. Views and other objects without time travel are read as they are, with a before-and-after version check.
353
357
 
354
358
  **Floats.** FLOAT and DOUBLE are compared exactly by default, so `0.1 + 0.2` and `0.3` differ. If a column changes everywhere but its total stays the same, the diff says it's likely rounding. Set `float_tolerance` to compare within a relative tolerance; NaN, infinity and NULL still compare exactly, and DECIMAL is always exact. MAP columns are compared by their entries sorted by key, so a map written in a different order isn't a change. A column the engine can't compare at all is left out with a note, and the check asks a human.
@@ -442,7 +446,7 @@ Every assessment records when it ran (UTC), the bricksentry version, a SHA-256 f
442
446
  - **Lineage is recorded at runtime.** Brand-new tables have no downstream history yet. Unity Catalog doesn't capture RDD operations, and UDFs hide column-level mapping; column lineage records source-to-target derivations, so a column used only in a filter or join may not appear.
443
447
  - **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
444
448
  - **Changed-table detection uses path globs** from config. It doesn't parse Asset Bundles yet.
445
- - **Validated on Databricks** (serverless, November 2026): a 2-million-row table with 0.1.4 (lineage, rollback plans, previews on shallow clones, every verdict level, the sampling guard catching a single changed row), then live runs of every release up to 0.1.27 on a Free Edition workspace with an HR pipeline: pull-request gating with comment updates, the bundle demo job, `check-last-change` and the newer-changes warning in the CLI, report, JSON and Slack, the refused-statement guards, outbound-URL checks, one-to-one matching of 2,000 NULL keys, exact totals over a million decimal rows, the audit trail, an AI agent attempting six risky changes on the live pipeline, the job task blocking a bad MERGE inside a real Databricks job, and worst-case rounds (50,000 NULL keys, near-max decimals, exotic types, 200-column tables) whose five findings were fixed in 0.1.26, and a round of leak, data-shape and race tests whose four findings were fixed in 0.1.27. Every run, with its numbers and the bugs it found, is in [VALIDATION.md](VALIDATION.md). The automated tests use DuckDB and a mocked SDK, so please run the [validation notebook](examples/databricks/bricksentry_validation.py) on your workspace and [share a validation report](https://github.com/bricksentry/bricksentry/issues/new?template=validation_report.yml), whether it passes or not.
449
+ - **Validated on Databricks** (serverless, November 2026): a 2-million-row table with 0.1.4 (lineage, rollback plans, previews on shallow clones, every verdict level, the sampling guard catching a single changed row), then live runs of every release up to 0.1.28 on a Free Edition workspace with an HR pipeline: pull-request gating with comment updates, the bundle demo job, `check-last-change` and the newer-changes warning in the CLI, report, JSON and Slack, the refused-statement guards, outbound-URL checks, one-to-one matching of 2,000 NULL keys, exact totals over a million decimal rows, the audit trail, an AI agent attempting six risky changes on the live pipeline, the job task blocking a bad MERGE inside a real Databricks job, and worst-case rounds (50,000 NULL keys, near-max decimals, exotic types, 200-column tables) whose five findings were fixed in 0.1.26, a round of leak, data-shape and race tests whose four findings were fixed in 0.1.27, and a round on MERGE, allowlist bypasses, metadata injection, remote access and governance features whose findings were fixed in 0.1.28. Every run, with its numbers and the bugs it found, is in [VALIDATION.md](VALIDATION.md). The automated tests use DuckDB and a mocked SDK, so please run the [validation notebook](examples/databricks/bricksentry_validation.py) on your workspace and [share a validation report](https://github.com/bricksentry/bricksentry/issues/new?template=validation_report.yml), whether it passes or not.
446
450
 
447
451
  ## Roadmap
448
452
 
@@ -0,0 +1 @@
1
+ bricksentry[databricks,mcp]==0.1.28
@@ -6,7 +6,7 @@
6
6
  "source": [
7
7
  "# Validate bricksentry on your own workspace\n",
8
8
  "\n",
9
- "**14 risky changes, about 3 minutes, nothing outside a scratch schema touched.** This notebook runs the same\n",
9
+ "**15 risky changes, about 4 minutes, nothing outside a scratch schema touched.** This notebook runs the same\n",
10
10
  "validation battery we publish in [VALIDATION.md](https://github.com/bricksentry/bricksentry/blob/main/VALIDATION.md),\n",
11
11
  "so you can check the results yourself instead of taking our word for them.\n",
12
12
  "\n",
@@ -2,7 +2,7 @@
2
2
  # MAGIC %md
3
3
  # MAGIC # Validate bricksentry on your own workspace
4
4
  # MAGIC
5
- # MAGIC **14 risky changes, about 3 minutes, nothing outside a scratch schema touched.** This notebook runs the same
5
+ # MAGIC **15 risky changes, about 4 minutes, nothing outside a scratch schema touched.** This notebook runs the same
6
6
  # MAGIC validation battery we publish in [VALIDATION.md](https://github.com/bricksentry/bricksentry/blob/main/VALIDATION.md),
7
7
  # MAGIC so you can check the results yourself instead of taking our word for them.
8
8
  # MAGIC
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "bricksentry"
7
- version = "0.1.27"
7
+ version = "0.1.28"
8
8
  description = "Change impact analysis and deployment guardrails for data changes on Databricks, for pipelines and the AI agents that edit them: data diffs, Unity Catalog blast radius, policy verdicts and rollback plans."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -32,6 +32,7 @@ classifiers = [
32
32
  dependencies = [
33
33
  "click>=8.1",
34
34
  "pyyaml>=6.0",
35
+ "sqlglot>=25",
35
36
  ]
36
37
 
37
38
  [project.optional-dependencies]
@@ -8,12 +8,12 @@
8
8
  "source": "github"
9
9
  },
10
10
  "websiteUrl": "https://bricksentry.org",
11
- "version": "0.1.27",
11
+ "version": "0.1.28",
12
12
  "packages": [
13
13
  {
14
14
  "registryType": "pypi",
15
15
  "identifier": "bricksentry-mcp",
16
- "version": "0.1.27",
16
+ "version": "0.1.28",
17
17
  "runtimeHint": "uvx",
18
18
  "transport": {
19
19
  "type": "stdio"
@@ -23,4 +23,4 @@ __all__ = [
23
23
  "TableDiff",
24
24
  "Verdict",
25
25
  ]
26
- __version__ = "0.1.27"
26
+ __version__ = "0.1.28"
@@ -99,7 +99,7 @@ def whats_downstream(
99
99
  out["column_tags"] = {c: col_tags[c] for c in columns if col_tags.get(c)}
100
100
  feeds = s.lineage.column_downstream(table, list(columns), int(s.config.lineage.get("column_depth", 2)))
101
101
  out["column_downstream"] = [c.to_dict() for c in feeds]
102
- return out
102
+ return agent_view.scrub_metadata(out)
103
103
 
104
104
 
105
105
  @_safe
@@ -130,7 +130,9 @@ def assess_change(
130
130
  rollback}]}. Pass `id` to safe_to_ship (and optionally explain_diff)."""
131
131
  s = get_sentry()
132
132
  tables = list(tables)
133
- _gate(s, "assess_change", tables)
133
+ # Candidates an agent names are checked too: pointing an allowed table's candidate
134
+ # at a forbidden table would otherwise diff the forbidden one.
135
+ _gate(s, "assess_change", tables + [c for c in (candidates or {}).values() if c])
134
136
  a = s.assess(tables, candidates=candidates, pr=pr)
135
137
  out = agent_view.for_agent(a, s)
136
138
  agent_view.audit(s, "assess_change", tables, out)
@@ -163,6 +165,9 @@ def preview_write(
163
165
  {error} if the statement is refused or fails."""
164
166
  s = get_sentry()
165
167
  _gate(s, "preview_write", [target])
168
+ # Every table the statement reads must be allowed too (a subquery, MERGE USING, a
169
+ # join or a CTE could otherwise turn the counts into facts about a forbidden table).
170
+ _gate_sql(s, "preview_write", [target], sql.replace("{{target}}", target))
166
171
  raw = s.preview_write(sql, target, keys=keys)
167
172
  a = s.get_assessment(raw["id"])
168
173
  out = agent_view.for_agent(a, s, {"preview": raw.get("preview")}) if a else agent_view.scrub(raw)
@@ -193,9 +198,11 @@ def explain_diff(
193
198
  a = s.get_assessment(assessment_id)
194
199
  if a is None:
195
200
  return {"error": f"unknown assessment id {assessment_id}"}
201
+ _gate(s, "explain_diff", [t.table for t in a.tables])
196
202
  safe = agent_view.for_agent(a, s)
197
203
  return {"assessment_id": a.id, "explanations": {t["table"]: t["summary"] for t in safe["tables"]}}
198
204
  if table:
205
+ _gate(s, "explain_diff", [table])
199
206
  d = s.get_diff(table)
200
207
  if d is None:
201
208
  return {"error": f"no diff for {table} yet; call assess_change or preview_write first"}
@@ -219,15 +226,17 @@ def safe_to_ship(
219
226
  Returns {assessment_id, safe_to_ship: bool, verdict, risk_tier, rule_hits:
220
227
  [{rule, verdict, table, reason}], notify, next_step}, or {error} if the id
221
228
  is unknown."""
222
- a = get_sentry().get_assessment(assessment_id)
229
+ s = get_sentry()
230
+ a = s.get_assessment(assessment_id)
223
231
  if a is None:
224
232
  return {"error": f"unknown assessment id {assessment_id}"}
233
+ _gate(s, "safe_to_ship", [t.table for t in a.tables])
225
234
  v = a.verdict.value
226
235
  next_step = {
227
236
  "pass": "Proceed: open or merge the pull request.",
228
237
  "warn": "Proceed, but include the warnings in the pull request description.",
229
238
  "needs_human": "Do not merge. Open the pull request with the report and request review from: "
230
- + (", ".join(a.notify) or "a data owner") + ".",
239
+ + (", ".join(str(agent_view._plain(n)) for n in a.notify) or "a data owner") + ".",
231
240
  "block": "Stop. Fix the blocking issues listed in rule_hits, rebuild the candidate and assess again.",
232
241
  }[v]
233
242
  return {
@@ -236,7 +245,7 @@ def safe_to_ship(
236
245
  "verdict": v,
237
246
  "risk_tier": a.verdict.risk_tier,
238
247
  "rule_hits": agent_view.scrub([h.to_dict() for h in a.hits], "rule_hits"),
239
- "notify": a.notify,
248
+ "notify": [agent_view._plain(n) for n in a.notify],
240
249
  "next_step": next_step,
241
250
  }
242
251
 
@@ -264,6 +273,14 @@ def rollback_plan(
264
273
  }
265
274
 
266
275
 
276
+ def _gate_sql(s: Sentry, tool: str, tables: list[str], sql: str) -> None:
277
+ try:
278
+ agent_view.check_statement(s, sql)
279
+ except PermissionError as e:
280
+ agent_view.audit(s, tool, tables, refused=str(e))
281
+ raise
282
+
283
+
267
284
  def _gate(s: Sentry, tool: str, tables: list[str]) -> None:
268
285
  try:
269
286
  agent_view.check_allowed(s, tables)
@@ -0,0 +1,267 @@
1
+ """What an AI agent is allowed to see.
2
+
3
+ bricksentry usually runs with more read access than the agent calling it (the MCP
4
+ server or a job identity can read production; the agent should not). So everything
5
+ returned to an agent goes through :func:`for_agent`:
6
+
7
+ * no row values: ``samples`` (before -> after values) are removed;
8
+ * no absolute totals: ``base_sum`` / ``candidate_sum`` are removed and the percentage
9
+ change is rounded to one decimal (a total over a few rows *is* the values);
10
+ * no segment values: segments keep their column and row count, not the value;
11
+ * engine errors lose quoted literals (``The value '123-45-6789' cannot be cast``);
12
+ * summaries are rebuilt without values.
13
+
14
+ Counts, column names, schema, verdicts and rule reasons stay: the agent needs them to
15
+ act. Counts can still be used as an oracle (preview ``DELETE ... WHERE ssn LIKE '1%'``
16
+ and read the row count), which no masking can stop, so ``agent_tables`` in
17
+ bricksentry.yml limits which tables an agent may assess or preview at all.
18
+ Humans (CLI, reports, pull-request comments) keep the full detail, except values in
19
+ pii-tagged tables and columns, which reports never show.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import fnmatch
25
+ import json
26
+ import logging
27
+ import re
28
+ import time
29
+ from typing import TYPE_CHECKING, Any
30
+
31
+ from bricksentry.explain import explain_diff, redact_values
32
+
33
+ if TYPE_CHECKING:
34
+ from bricksentry.assess import Sentry
35
+ from bricksentry.models import Assessment
36
+
37
+ log = logging.getLogger("bricksentry.audit")
38
+
39
+ _DROP = {"samples", "base_sum", "candidate_sum"}
40
+
41
+
42
+ def for_agent(a: Assessment, sentry: Sentry, extra: dict[str, Any] | None = None) -> dict[str, Any]:
43
+ """The agent-safe dict of an assessment."""
44
+ out = a.to_dict()
45
+ for t_obj, t in zip(a.tables, out.get("tables") or [], strict=False):
46
+ if t_obj.diff is not None:
47
+ measures = sentry.config.spec(t_obj.table).measures
48
+ human = explain_diff(t_obj.diff, measures)
49
+ rest = t_obj.summary[len(human):] if t_obj.summary.startswith(human) else ""
50
+ t["summary"] = explain_diff(t_obj.diff, measures, for_agent=True) + rest
51
+ if extra:
52
+ out.update(extra)
53
+ return scrub(out)
54
+
55
+
56
+ _SIMPLE = re.compile(r"^[\w.\-:/@+]{0,64}(?: [\w.\-:/@+]{1,64})?$")
57
+
58
+
59
+ def _plain(text: Any) -> Any:
60
+ """Tag names and values, owners: kept when short and simple ("pii", "true",
61
+ "finance-team", "a@b.com"); anything longer or free text is replaced, because
62
+ metadata anyone can write could carry instructions aimed at the agent."""
63
+ if text is None or isinstance(text, (bool, int, float)):
64
+ return text
65
+ t = str(text)
66
+ if len(t) <= 64 and _SIMPLE.match(t):
67
+ return t
68
+ return f"[text hidden: {len(t)} chars]"
69
+
70
+
71
+ def _tags(d: Any) -> Any:
72
+ if not isinstance(d, dict):
73
+ return d
74
+ return {_plain(k): _plain(v) for k, v in d.items()}
75
+
76
+
77
+ def scrub_metadata(x: Any, key: str | None = None) -> Any:
78
+ """Free text in tags and owners is replaced (see :func:`_plain`), also where it was
79
+ copied into other text such as a summary ("owners: ..."); everything else stays."""
80
+ bad: set[str] = set()
81
+ _collect(x, bad)
82
+ out = _scrub_meta(x, key)
83
+ if bad:
84
+ out = _replace_all(out, sorted(bad, key=len, reverse=True))
85
+ return out
86
+
87
+
88
+ def _collect(x: Any, bad: set[str], key: str | None = None) -> None:
89
+ def note(t: Any) -> None:
90
+ if isinstance(t, str) and _plain(t) != t:
91
+ bad.add(t)
92
+
93
+ if isinstance(x, dict):
94
+ for k, v in x.items():
95
+ if k == "tags" and isinstance(v, dict):
96
+ for tk, tv in v.items():
97
+ note(tk)
98
+ note(tv)
99
+ elif k == "column_tags" and isinstance(v, dict):
100
+ for tags in v.values():
101
+ if isinstance(tags, dict):
102
+ for tk, tv in tags.items():
103
+ note(tk)
104
+ note(tv)
105
+ elif k in ("owner", "owners", "notify"):
106
+ for o in v if isinstance(v, list) else [v]:
107
+ note(o)
108
+ else:
109
+ _collect(v, bad, k)
110
+ elif isinstance(x, list):
111
+ for v in x:
112
+ _collect(v, bad, key)
113
+
114
+
115
+ def _replace_all(x: Any, bad: list[str]) -> Any:
116
+ if isinstance(x, dict):
117
+ return {k: _replace_all(v, bad) for k, v in x.items()}
118
+ if isinstance(x, list):
119
+ return [_replace_all(v, bad) for v in x]
120
+ if isinstance(x, str):
121
+ for b in bad:
122
+ if b in x:
123
+ x = x.replace(b, _plain(b))
124
+ return x
125
+
126
+
127
+ def _scrub_meta(x: Any, key: str | None = None) -> Any:
128
+ if isinstance(x, dict):
129
+ out: dict[str, Any] = {}
130
+ for k, v in x.items():
131
+ if k == "tags":
132
+ out[k] = _tags(v)
133
+ elif k == "column_tags" and isinstance(v, dict):
134
+ out[k] = {c: _tags(t) for c, t in v.items()}
135
+ elif k in ("owner", "owners", "notify"):
136
+ out[k] = [_plain(o) for o in v] if isinstance(v, list) else _plain(v)
137
+ else:
138
+ out[k] = _scrub_meta(v, k)
139
+ return out
140
+ if isinstance(x, list):
141
+ return [_scrub_meta(v, key) for v in x]
142
+ return x
143
+
144
+
145
+ def scrub(x: Any, key: str | None = None) -> Any:
146
+ """Remove values from any result dict (see the module docstring), and free text from metadata."""
147
+ return scrub_metadata(_scrub_values(x, key))
148
+
149
+
150
+ def _scrub_values(x: Any, key: str | None = None) -> Any:
151
+ if isinstance(x, dict):
152
+ out: dict[str, Any] = {}
153
+ for k, v in x.items():
154
+ if k in _DROP:
155
+ continue
156
+ if k == "sum_change_pct" and isinstance(v, (int, float)):
157
+ out[k] = round(v, 1)
158
+ elif k == "segments" and isinstance(v, list):
159
+ out[k] = [{"column": s.get("column"), "affected_rows": s.get("affected_rows")}
160
+ for s in v if isinstance(s, dict)]
161
+ else:
162
+ out[k] = _scrub_values(v, k)
163
+ return out
164
+ if isinstance(x, list):
165
+ return [_scrub_values(v, key) for v in x]
166
+ if isinstance(x, str) and key in ("error", "notes", "reason", "summary", "rollback_warning"):
167
+ return redact_values(x)
168
+ return x
169
+
170
+
171
+ def allowed(sentry: Sentry, table: str) -> bool:
172
+ """Whether ``agent_tables`` (glob patterns, any case) lets an agent assess or preview ``table``.
173
+ Unset means every table, as before 0.1.27."""
174
+ patterns = sentry.config.agent_tables
175
+ if patterns is None:
176
+ return True
177
+ name = table.lower()
178
+ return any(fnmatch.fnmatchcase(name, p.lower()) for p in patterns)
179
+
180
+
181
+ def tables_read(sql: str, dialect: str) -> list[str]:
182
+ """Every table a statement touches, as written (``catalog.schema.table``), via a real
183
+ SQL parser. Raises PermissionError for anything that can't be checked by name:
184
+ unparseable SQL, table functions (``table_changes(...)``, ``read_files(...)``,
185
+ ``IDENTIFIER(...)``) and path-based tables (``delta.`/path```)."""
186
+ try:
187
+ import sqlglot
188
+ from sqlglot import exp
189
+ except ImportError: # pragma: no cover - sqlglot is a dependency
190
+ raise PermissionError("Can't check which tables this statement reads (sqlglot is not installed).") from None
191
+ try:
192
+ trees = [t for t in sqlglot.parse(sql, read=dialect) if t is not None]
193
+ except Exception:
194
+ raise PermissionError(
195
+ "Couldn't parse the statement to check which tables it reads, so it's refused for agents. "
196
+ "Simplify it (plain table names, no dynamic SQL)."
197
+ ) from None
198
+ if len(trees) != 1:
199
+ raise PermissionError("Exactly one statement is allowed.")
200
+ tree = trees[0]
201
+ ctes = {c.alias_or_name.lower() for c in tree.find_all(exp.CTE)}
202
+ out: list[str] = []
203
+ for t in tree.find_all(exp.Table):
204
+ if not isinstance(t.this, exp.Identifier):
205
+ raise PermissionError(
206
+ "Table functions and dynamic table names (table_changes, read_files, IDENTIFIER, ...) can't be "
207
+ "checked against agent_tables, so they're refused for agents. Name the tables directly."
208
+ )
209
+ parts = [x for x in (t.catalog, t.db, t.name) if x]
210
+ name = ".".join(parts)
211
+ if not t.catalog and not t.db and t.name.lower() in ctes:
212
+ continue
213
+ if "/" in name or ":" in name:
214
+ raise PermissionError(f"Path-based tables ({name}) are refused for agents. Use a Unity Catalog table name.")
215
+ out.append(name)
216
+ return out
217
+
218
+
219
+ def check_statement(sentry: Sentry, sql: str) -> None:
220
+ """With ``agent_tables`` set, every table the statement reads or writes must be listed.
221
+ A table named with fewer parts than the pattern (``sales.orders`` for ``main.sales.*``)
222
+ doesn't match: write the full name."""
223
+ if sentry.config.agent_tables is None:
224
+ return
225
+ dialect = "duckdb" if getattr(sentry.backend, "name", "") == "duckdb" else "databricks"
226
+ check_allowed(sentry, tables_read(sql, dialect))
227
+
228
+
229
+ def check_allowed(sentry: Sentry, tables: list[str]) -> None:
230
+ refused = [t for t in tables if not allowed(sentry, t)]
231
+ if refused:
232
+ raise PermissionError(
233
+ f"Not allowed for agents: {', '.join(refused)}. This bricksentry only lets agents assess "
234
+ "or preview the tables listed under agent_tables in bricksentry.yml."
235
+ )
236
+
237
+
238
+ def audit(sentry: Sentry, tool: str, tables: list[str], result: dict[str, Any] | None = None,
239
+ refused: str | None = None) -> None:
240
+ """One line per agent assess or preview: who, which tables, what came back.
241
+ Logged to ``bricksentry.audit`` and appended to ``audit.jsonl`` in the assessment store."""
242
+ from bricksentry.assess import _actor
243
+
244
+ rows = {}
245
+ for t in (result or {}).get("tables") or []:
246
+ d = t.get("diff") or {}
247
+ rows[t.get("table")] = {k: d.get(k) for k in ("added_rows", "removed_rows", "changed_rows")}
248
+ entry = {
249
+ "time": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
250
+ "tool": tool,
251
+ "actor": _actor(),
252
+ "tables": tables,
253
+ "verdict": (result or {}).get("verdict"),
254
+ "assessment_id": (result or {}).get("id"),
255
+ "rows": rows or None,
256
+ "refused": refused,
257
+ }
258
+ log.info(json.dumps(entry))
259
+ folder = sentry.config.store_dir()
260
+ if folder is None:
261
+ return
262
+ try:
263
+ folder.mkdir(parents=True, exist_ok=True)
264
+ with (folder / "audit.jsonl").open("a") as f:
265
+ f.write(json.dumps(entry) + "\n")
266
+ except OSError:
267
+ pass
@@ -39,6 +39,11 @@ class Backend(ABC):
39
39
  def qualified(self, table: str) -> str:
40
40
  return ".".join(self.quote(p) for p in table.split("."))
41
41
 
42
+ def protections(self, tables: list[str]) -> dict[str, dict[str, Any]]:
43
+ """Column masks and row filters per table: ``{table: {"masked": [cols], "row_filter": bool}}``.
44
+ Engines without them return nothing."""
45
+ return {}
46
+
42
47
  def columns_at(self, table: str, version: int | None) -> dict[str, str]:
43
48
  """Like :meth:`columns`, for ``table`` at ``version``."""
44
49
  return self.columns(table)
@@ -147,6 +147,41 @@ class DatabricksBackend(Backend):
147
147
  f"CREATE OR REPLACE TABLE {self.qualified(target)} SHALLOW CLONE {self.qualified(source)}"
148
148
  )
149
149
 
150
+ def protections(self, tables: list[str]) -> dict[str, dict[str, Any]]:
151
+ # Unity Catalog lists masks and row filters in each catalog's information_schema.
152
+ # One query per catalog. If it can't be read (no UC, no access), say nothing:
153
+ # tables outside UC can't have them.
154
+ out: dict[str, dict[str, Any]] = {}
155
+ by_catalog: dict[str, list[tuple[str, str, str]]] = {}
156
+ for t in tables:
157
+ parts = [p.strip("`") for p in t.split(".")]
158
+ if len(parts) == 3:
159
+ by_catalog.setdefault(parts[0], []).append((t, parts[1].lower(), parts[2].lower()))
160
+ for cat, items in by_catalog.items():
161
+ where = " OR ".join(f"(lower(table_schema) = {self._lit(s)} AND lower(table_name) = {self._lit(n)})"
162
+ for _, s, n in items)
163
+ sql = (f"SELECT 'mask' AS kind, table_schema, table_name, column_name "
164
+ f"FROM {self.quote(cat)}.information_schema.column_masks WHERE {where} "
165
+ f"UNION ALL SELECT 'filter' AS kind, table_schema, table_name, NULL AS column_name "
166
+ f"FROM {self.quote(cat)}.information_schema.row_filters WHERE {where}")
167
+ try:
168
+ rows = self.query(sql)
169
+ except Exception:
170
+ continue
171
+ for r in rows:
172
+ for t, s, n in items:
173
+ if str(r.get("table_schema", "")).lower() == s and str(r.get("table_name", "")).lower() == n:
174
+ e = out.setdefault(t, {"masked": [], "row_filter": False})
175
+ if r.get("kind") == "mask" and r.get("column_name"):
176
+ e["masked"].append(str(r["column_name"]))
177
+ elif r.get("kind") == "filter":
178
+ e["row_filter"] = True
179
+ return out
180
+
181
+ @staticmethod
182
+ def _lit(v: str) -> str:
183
+ return "'" + v.replace("\\", "\\\\").replace("'", "\\'") + "'"
184
+
150
185
  def columns_at(self, table: str, version: int | None) -> dict[str, str]:
151
186
  if version is None:
152
187
  return self.columns(table)