diff --git a/README.md b/README.md index 42053f2d..db83083d 100644 --- a/README.md +++ b/README.md @@ -620,7 +620,12 @@ denies: and `pdm run`; a direct path with a script extension or interpreter shebang; a script fed on stdin; `source`; `python -m` for a project module; `Rscript -e "source(...)"`; and code inside `sh -c`, `bash -c`, or `eval`. - The hook reads the script itself, up to 1 MB. Scripts that do not touch + A script that runs another file the hook cannot resolve before it runs + (`source(f)`, `eval(parse(f))`, `source` passed to `lapply`, `runpy`, + `exec`/`eval` of a computed string, `importlib.import_module(name)`) is + denied too; literal paths, including `file.path(...)` and `here(...)` over + literals, are followed and checked. The hook reads the script itself, up to + 1 MB. Scripts that do not touch data, or that only read aggregate tables that pass the check below, run as before. - Workflow runners (`make`, `snakemake`, `nextflow`, `dvc repro`, `pytest`, @@ -637,6 +642,16 @@ strictest wins. Unquoted shell wildcards are expanded (up to 256 matches) and checked like the files they name; in schema-only mode a wildcard that matches more than that is treated as data. +Database MCP tools (Postgres, DuckDB, SQLite, Snowflake, BigQuery, MongoDB, +Neo4j, and similar, recognized by a database word in the tool name or by SQL +or Cypher statement text in the arguments) return query results straight +into the context, so in schema-only mode they are denied unless the call only +inspects the schema: a tool that lists or describes tables, or a single +`DESCRIBE`, `SHOW TABLES`/`COLUMNS`, `PRAGMA table_info`, or plain select from +`information_schema.tables`/`columns`. Run real queries in a script through +the safe runner, write an aggregate table, and read it with +`method-aggregate-read`. Literature and search connectors are not affected. + **Safe runner.** `scripts/method-safe-run -- ` runs the command and writes its full stdout and stderr to `.methodsmith/runs/-.log` (gitignored). It prints only the exit code, the duration, the files created or @@ -646,7 +661,13 @@ timestamps), and a stderr summary that keeps only traceback file and line frames and exception type names, plus a count of withheld lines; identifier values in file names are masked. It never prints stdout or other stderr text: open the log yourself. It refuses to run when no `.methodsmith/` or `.git` is -found above the working directory. +found above the working directory. The command gets its own temp directory +(`TMPDIR`, `TMP`, `TEMP`) outside the project, which counts as data and is +removed when the run finishes. While a run, or anything it started, is still +going, project files changed since it began count as data; a run that was +killed before recording its outputs keeps that rule in force until the next +run or `method-safe-run --reconcile` records what it wrote. Processes a +command leaves running are stopped about 10 seconds after it exits. The hook's deny message gives the runner's full path. It accepts only the plugin's own runner (or a byte-identical copy) and still checks uploads inside it. @@ -722,7 +743,14 @@ If it is missing, the launcher prints a warning and exits successfully, so the guard is inactive and calls are not blocked. The script check is heuristic static analysis: a script that builds a data path at run time, or reads data through a function the hook does not recognize, can still print values, and -programs it cannot parse (deliberate obfuscation) are out of scope. Values +programs it cannot parse (deliberate obfuscation) are out of scope. Files a +safe-runner command writes to hard-coded paths outside the project and its +temp directory (`/tmp/x.csv`, Java's `java.io.tmpdir`, Spark's local +directory), and processes that leave the run's process group with `setsid`, +are not tracked. A database server whose tools have no database word in +their names and take no SQL text is not recognized, and MCP resources are not +checked. Editing a file while a safe-runner command is still running makes +that file data until the run ends. Values that are not in identifier columns, such as free-text notes, are not indexed, and the identifier patterns catch common shapes, not every one. A patient who shares a full name with an author you search for blocks that name. A config diff --git a/docs/plans/2026-10-26-2330-fix-remaining-schema-only-leak-paths-plan.md b/docs/plans/2026-10-26-2330-fix-remaining-schema-only-leak-paths-plan.md new file mode 100644 index 00000000..093c326d --- /dev/null +++ b/docs/plans/2026-10-26-2330-fix-remaining-schema-only-leak-paths-plan.md @@ -0,0 +1,251 @@ +--- +title: Close Remaining Schema-Only Leak Paths - Plan +type: fix +date: 2026-10-26 +artifact_contract: ce-unified-plan/v1 +artifact_readiness: implementation-ready +product_contract_source: ce-plan-bootstrap +execution: code +--- + +# Close Remaining Schema-Only Leak Paths - Plan + +## Goal Capsule + +- **Objective:** In a schema-only methodsmith project, data values cannot reach the model context through a recognized database MCP tool, through files a `method-safe-run` run writes inside the project or to its own temp directory (including while it is still running or after it crashed), or through a script whose sourced path is computed at run time. The remaining limits are the ones listed under Scope Boundaries. +- **Means:** Four targeted guard and runner changes (KTD1-KTD4) that close the three leak paths, each landed with a synthetic-data test that fails first. +- **Authority:** This plan's Requirements and KTDs, then `AGENTS.md`, then the guard docstring, which U5 updates. +- **Stop conditions:** Stop and report if a fix would change access in `approved` or `no-sensitive-data` projects, would block literature tools (PubMed, Paperclip, web search), or would push a guard decision past the latency budget in R9. +- **Execution profile:** Test-first per leak path, on a new branch from `main`. +- **Tail ownership:** The calling pipeline (LFG) owns review, commit, push, and the PR. + +--- + +## Product Contract + +### Summary + +Close the three schema-only leak paths PR #171 left as residuals: database MCP tools that return rows, `method-safe-run` output that lands in the run's temp directory or before the run finishes, and scripts that `source()` or `exec()` a path built at run time. Every fix ships with a test that fails before the change. + +### Problem Frame + +PR #171 hardened the PHI data-boundary guard but left three documented gaps. A database MCP server (Postgres, DuckDB, Snowflake, and similar) answers `SELECT * FROM patients` straight into the model's context because the guard only checks MCP arguments for file paths and code that names data files. `method-safe-run` records only files written inside the project, after the run exits, so a script that writes rows to a temp file, or writes anything while running in the background or after being killed, leaves a copy the model can read. And a script that sources another script through a variable (`source(f)`, `runpy.run_path(p)`, `exec(open(p).read())`) is never scanned. Each gap lets row-level values into the model context in exactly the mode meant to prevent it. + +### Key Decisions + +- **No `!` or `BREAKING CHANGE:` marker.** (session-settled: user-directed — chosen over marking the change breaking: release-version decisions belong to the maintainer.) Governs R12. +- **The guard file is not split in this PR.** (session-settled: user-approved — chosen over splitting `data-boundary-guard.py` here: mixing a refactor into security fixes makes them harder to review.) Governs R13. +- **Unresolvable dynamic source paths are denied in schema-only.** (session-settled: user-approved — chosen over leaving them as a documented heuristic limit: closes a known leak at the cost of routing such scripts through `method-safe-run`.) Governs R7, R8. + +### Requirements + +**Database MCP tools** + +- R1. In schema-only, an MCP call to a database tool that carries a row-returning query is denied, with a reason that points to running the query in a script through `method-safe-run`, writing an aggregate table, and reading it with `method-aggregate-read`. +- R2. Schema inspection stays allowed, and nothing else: a database tool with no query text whose name has an inspection word (`list`, `describe`, `schema`, `tables`, `columns`, `info`, `metadata`, `indexes`); or one single statement that is `DESCRIBE `, `SHOW TABLES|COLUMNS ...`, `PRAGMA table_info()`, or a select whose projection is `*` or bare column names, whose FROM is exactly one `information_schema.tables` or `information_schema.columns`, and whose WHERE uses only column-to-literal comparisons (`=`, `LIKE`, `IN` over literals, `AND`/`OR`). Any function call, join, comma-separated source, CTE, subquery, or `UNION` denies. +- R3. Literature and search tools (PubMed, Paperclip including its `sql` tool, Exa, Tavily, Notion, web search) are unaffected, and approved / no-sensitive-data access to database tools is unchanged (egress identifier checks still apply). + +**method-safe-run** + +- R4. Files a run writes to its temp directory are data: the child's `TMPDIR`, `TMP`, and `TEMP` point at a per-run owner-only directory the guard treats as data; the runner deletes it when the run finishes normally. +- R5. While a run or any process it started is still alive, or after it died without finishing, project files created, modified, or renamed in at or after that run's start are data until the run is reconciled. +- R6. A stale run (runner and its whole process group gone, outputs never recorded) is reconciled by the next `method-safe-run` invocation or by `method-safe-run --reconcile`, which records only files changed between the run's start and its last heartbeat, then clears the marker. The guard's boundary state (`runs/active/`, `runs/temp-roots.txt`) cannot be removed or edited by other commands in schema-only. + +**Dynamic source paths** + +- R7. In schema-only, code that runs another file or module whose target cannot be statically resolved is denied, inline (`-e`/`-c`, every occurrence) and inside scanned script files, unless run through `method-safe-run`. This covers R `source`, `sys.source`, `eval(parse(...))`, and `source` passed to a higher-order function; Python `runpy.run_path`, `runpy.run_module`, `exec`/`eval` of anything other than a string literal (including `compile(...)` and `open(...).read()`), `importlib.import_module`, `__import__`, and `spec_from_file_location`. +- R8. Statically resolvable targets are followed and scanned rather than denied: string literals, including inside `file.path`, `paste0`, `paste(..., sep=)`, `here::here`/`here()`, and named `file=`/`path=` arguments, and literal module names for `runpy.run_module` / `importlib.import_module`. A resolved file that does not exist, or a call preceded by `setwd(`/`os.chdir(` or given `chdir=`, counts as unresolvable. + +**Contract** + +- R9. One guard decision stays under 1 second on the test fixtures; marker and temp-root checks never walk a directory tree at hook time. +- R10. Every fix has a synthetic-data test that fails before the change, and deny reasons never echo data values. +- R11. The guard docstring and the shared sensitive-data boundary section in `README.md`, `plugins/methodsmith/README.md`, and `docs/setup.md` describe the new coverage and the remaining limits identically. +- R12. No `!` or `BREAKING CHANGE:` marker. +- R13. `data-boundary-guard.py` is not split. + +### Scope Boundaries + +- Writes to absolute paths outside both the project and the run's temp directory (for example a hard-coded `/tmp/x.csv`, Java `java.io.tmpdir`, Spark `spark.local.dir`) are not tracked; they are documented as a limit. +- The guard does not inspect MCP results (only `PreToolUse` is registered); routing MCP calls through `method-aggregate-read` is not possible and is not attempted. +- Files the model itself edits during a background run count as data until the run ends and may be recorded as run outputs; this is documented, not fixed. +- A database tool is recognized by its server or tool name (KTD1 vocabulary) or by SQL- or Cypher-shaped text under a query key; an unrecognized server whose tools return rows without either signal is not detected. +- MCP resources read through `ReadMcpResourceTool` are not matched by the hook. +- A run marker written on another machine (a synced project folder) stays in force and is never reconciled from here. + +--- + +## Planning Contract + +### Key Technical Decisions + +- KTD1. **Database tools fail closed; inspection is an allowlist.** Split MCP server and tool names on `_`, `-`, and `__`. A call is a database call when a whole word matches the vocabulary (`postgres`, `postgresql`, `pg`, `mysql`, `mariadb`, `sqlite`, `duckdb`, `motherduck`, `bigquery`, `snowflake`, `databricks`, `mssql`, `sqlserver`, `oracle`, `redshift`, `athena`, `clickhouse`, `trino`, `presto`, `neo4j`, `kusto`, `cosmos`, `supabase`, `mongodb`, `mongo`, `elasticsearch`, `opensearch`, `redis`, `dynamodb`, `firestore`, `cassandra`, `influxdb`, `airtable`, `sql`, `database`, `db`), or when a query key (`sql`, `query`, `statement`, `cypher`, `kql`, `filter`, `pipeline`, found anywhere in the arguments via `_strings`) holds SQL- or Cypher-shaped text (`SELECT|WITH|MATCH|FROM|PRAGMA|SHOW|DESCRIBE` as the first keyword), unless the server is exempt (`pubmed`, `paperclip`, `exa`, `tavily`, `notion`, `granola`, `vercel`, and the `claude_ai_*` literature connectors). `command` is a router sub-command name, not query text: a router call is allowed only when that name is an inspection word, and any nested query is checked like any other. A database call with query text passes only the R2 statement shape; a database call without query text passes only when a name segment is an inspection word. Everything else denies in schema-only. Implements R1-R3. +- KTD2. **Short temp dir outside the project, registered as a data root.** `method-safe-run` creates the child's temp dir with `tempfile.mkdtemp(prefix="msr-")` (mode 0700) in the system temp root (short path: avoids the ~104-byte Unix-socket limit, spaces, and cloud-synced folders), sets `TMPDIR`/`TMP`/`TEMP` for the child, and appends it to `.methodsmith/runs/temp-roots.txt` before the child starts. The guard adds each listed dir and its realpath to `data_roots`. The runner removes the temp dir after a normal finish and prunes listed dirs that no longer exist on its next start. Appends to `temp-roots.txt` and `outputs.txt` use `O_APPEND` under an `fcntl` lock. Implements R4. +- KTD3. **Process-group marker with heartbeat; stale means the whole group is gone.** The runner starts the child with `start_new_session=True` and, before the child runs, writes `.methodsmith/runs/active/.json` holding the runner pid, its process start time, the child process-group id, hostname, and the filesystem-clock start (the existing sentinel ctime). It touches the marker every 10 s while the child runs (heartbeat). On SIGTERM/SIGINT it forwards the signal to the child's process group, waits up to 10 s, escalates to SIGKILL, and finalizes only once the group is gone; normal exit also waits for the group. A marker is stale when the runner pid is gone or its start time no longer matches, and the process group has no live member, on the same host; a marker from another host is never stale here. Reconcile (next run start, or `--reconcile`) records project files whose `max(mtime, ctime)` lies between the marker start and its last heartbeat plus 2 s, then removes the marker. The guard lists `runs/active/` only (no tree walk): a referenced path counts as data when it, or its parent directory, changed at or after the start of any marker. Schema-only Bash, Write, and Edit calls that would remove, move, truncate, or write `runs/active/*` or `runs/temp-roots.txt` are denied. Implements R5, R6. +- KTD4. **Run-a-file sinks: resolve literals, deny the rest.** Generalize `SOURCED` into a sink table (R7's list) whose patterns capture the first argument the way `READ_CALL` does. A target is resolvable when it is a string literal, a named `file=`/`path=` literal, or `file.path`/`paste0`/`paste`/`here`/`here::here` over literals only (relative to the effective directory; `here` relative to the project root). Literal module names (`run_module`, `import_module`) resolve with the existing `module_files(module, cwd, env)`. Resolvable targets are scanned with `script_reads_data` (recursion capped by `_SCANNING`). A target denies when it is not resolvable, when the resolved file does not exist, or when `setwd(`, `os.chdir(`, or a `chdir=` argument appears before the call. `source`/`sys.source` as a function value is detected only as an argument of `lapply`, `sapply`, `vapply`, `Map`, `mapply`, `Reduce`, `Filter`, `do.call`, or `purrr`/bare `walk*`/`map*`, so a data column named `source` is not misread. Apply in `judge` for every `-e`/`-c` argument and in `script_reads_data` for scanned files. Implements R7, R8. + +### Assumptions + +- Schema inspection uses the strict allowlist in R2; anything outside it denies. A user who needs more schema detail runs a script through `method-safe-run`. +- Editing a file during a live background run makes that file data until the run ends (accepted friction; the deny reason says to wait or run the edit through the run's completion). +- A dead run's marker fails closed until reconciled, which may deny reads of files the user edited after the crash; the deny reason names `method-safe-run --reconcile`. + +### Risks + +| Risk | Mitigation | +|---|---| +| Blocking legitimate MCP tools that use `query` or `sql` keys | Whole-word name matching plus the exemption list; tests keep `NORMAL_QUERIES`, PubMed, Paperclip `sql`, and Notion query tools allowed. | +| A stale marker blocks work indefinitely | Reconcile on the next run and via `--reconcile`; deny reason names the command. | +| Reconcile records files edited long after a crash | The reconcile window ends at the run's last heartbeat. | +| PID reuse makes a dead run look alive | The marker stores the runner's process start time and the child process group. | +| Edits during a live run become data until it ends | Documented; test pins the behavior. | +| Temp redirect breaks tools that ignore or dislike `TMPDIR` | Short system-temp path; tests run Python `tempfile` and R `tempdir()` under the runner. | +| Guard latency from marker checks | Only `runs/active/` is listed and only referenced paths are stat'd; latency test. | + +--- + +## Implementation Units + +### U1. Deny row-returning database MCP calls in schema-only + +- **Goal:** R1-R3. +- **Requirements:** R1, R2, R3, R9, R10. KTD1. +- **Dependencies:** None. +- **Files:** `plugins/methodsmith/hooks/data-boundary-guard.py`, `tests/data-boundary-guard.test.ts`. +- **Approach:** + 1. Add failing tests next to the existing MCP access tests. + 2. Add the DB vocabulary, exemption list, query keys, and row-tool segments as module constants near `MCP_CODE_KEYS`. + 3. Add a database check to `mcp_access_violation` returning an access reason that names `method-safe-run` and `method-aggregate-read`. +- **Patterns to follow:** `UPLOADISH_TOOL`, `mcp_access_violation`, `aggregate_hint` deny text. +- **Test scenarios:** schema-only unless noted: + - `mcp__postgres__query {sql: "SELECT * FROM patients"}` -> deny. + - `mcp__postgres__query {sql: "select column_name from information_schema.columns where table_name='x'"}` -> allow. + - `information_schema` select with `UNION SELECT ssn FROM p` -> deny. + - `mcp__pg__q {sql: "SELECT * FROM pg_stats"}` -> deny. + - `mcp__duckdb__run {query: "SUMMARIZE t"}` -> deny. + - `mcp__duckdb__list_tables {}` -> allow; `mcp__duckdb__describe_table {table: "t"}` -> allow. + - `mcp__sqlite__read_rows {table: "t"}` -> deny; `mcp__duckdb__preview_table {table: "t"}` -> deny; `mcp__postgres__get_table_data {table: "t"}` -> deny. + - `mcp__postgres__query {sql: "SELECT pg_read_file('data/cohort.csv') AS column_name FROM information_schema.tables"}` -> deny. + - `mcp__duckdb__run {query: "SELECT * FROM information_schema.tables, read_csv('data/cohort.csv')"}` -> deny. + - `mcp__mongodb__find {collection: "patients", filter: {}}` -> deny. + - `mcp__Azure_MCP_Server__cosmos {command: "database_list", parameters: {}}` -> allow; the same tool with `parameters: {query: "SELECT * FROM c"}` -> deny. + - `mcp__mydb__exec {params: {statement: "SELECT * FROM t"}}` (no DB word in the name) -> deny via SQL-shaped text. + - `mcp__neo4j__run {query: "MATCH (p:Patient) RETURN p"}` -> deny. + - `mcp__claude_ai_Paperclip__sql {query: "SELECT title FROM papers"}` -> allow. + - `mcp__pubmed__pubmed_search_articles {query: "select sepsis outcomes ICU"}` -> allow. + - `mcp__claude_ai_Notion__notion-query-data-sources {query: "x"}` -> allow. + - Approved project: `mcp__postgres__query {sql: "SELECT * FROM patients"}` -> allow. + - The deny reason contains no query text. +- **Verification:** New tests pass; `NORMAL_QUERIES` and all existing MCP tests pass. + +### U2. Temp directory and in-progress runs in method-safe-run + +- **Goal:** R4-R6 on the runner side. +- **Requirements:** R4, R5, R6, R10. KTD2, KTD3. +- **Dependencies:** None. +- **Files:** `plugins/methodsmith/scripts/method-safe-run`, `tests/data-boundary-limits.test.ts`. +- **Approach:** + 1. Add failing tests in the "limit 1b" block. + 2. Create the short temp dir, register it in `runs/temp-roots.txt`, and pass the env to the child. + 3. Start the child in its own session; write `runs/active/.json` (KTD3 fields) before it runs; heartbeat every 10 s; on exit or SIGTERM/SIGINT forward to the process group, wait for it, then record outputs, remove the temp dir, and remove the marker. + 4. At startup, and for `--reconcile`, reconcile stale markers whose pid is gone. + 5. Append to `outputs.txt` and `temp-roots.txt` with `O_APPEND` under an `fcntl` lock. +- **Patterns to follow:** existing sentinel/`since_ns`, `record_outputs`, `legacy_refusal` exit style. +- **Test scenarios:** + - Child Python `tempfile.mkstemp()` writes a file; it lies under a dir listed in `runs/temp-roots.txt`. + - `Rscript -e 'cat(tempdir())'` under the runner prints a path under a registered temp root (skip when Rscript is absent). + - A run killed with SIGTERM forwards it to the child, records its outputs, and removes its marker. + - The child starts a background writer that writes after the runner gets SIGTERM: the marker stays until the writer exits, and the late file is recorded. + - After a SIGKILL of the runner, a file edited after the last heartbeat is not added to `outputs.txt` by `--reconcile`. + - A marker whose recorded process start time does not match the live process with that pid is treated as stale. + - The temp dir is created with mode 0700 and removed after a normal finish. + - A marker whose pid is dead remains after a SIGKILL; the next run (or `--reconcile`) records the dead run's written file in `outputs.txt` and removes the marker. + - Two concurrent runs each writing a file: both paths end up in `outputs.txt`, and both temp dirs in `temp-roots.txt`. +- **Verification:** New tests pass; existing limit 1b tests pass. + +### U3. Guard consumes temp roots and active-run markers + +- **Goal:** R4, R5 on the guard side. +- **Requirements:** R4, R5, R9, R10. KTD2, KTD3. +- **Dependencies:** U2 (file formats). +- **Files:** `plugins/methodsmith/hooks/data-boundary-guard.py`, `tests/data-boundary-limits.test.ts`. +- **Approach:** + 1. Read `runs/temp-roots.txt` in `_project_mode` (and the legacy runs dir) and add each entry and its realpath to `data_roots`. + 2. Load `runs/active/*.json` markers; in `is_data_path`, a referenced path under the project counts as data when it or its parent directory changed at or after any marker's start. + 3. Deny reasons for marker hits name `method-safe-run --reconcile` when the marker is stale. + 4. Deny schema-only Bash/Write/Edit mutations of `runs/active/*` and `runs/temp-roots.txt` (rm, mv, cp over, redirects, truncation) outside the plugin's `method-safe-run`. +- **Patterns to follow:** `run_outputs` / `output_lists`, `_project_mode` data_roots. +- **Test scenarios:** + - After a run, `Read /rows.txt` and `cat /rows.txt` -> deny (schema-only); approved -> allow. + - With a live marker (written by the test), `Read results/out.csv` modified after the marker start -> deny; a file last modified before the start -> allow. + - Stale marker (dead pid) -> deny with a reason naming `--reconcile`. + - A file renamed into the project during a live run (`mv /tmp/r.csv results/`) -> deny. + - Editing `R/x.R` during a live run, then reading it -> deny (documented friction). + - `rm .methodsmith/runs/active/123.json` and `echo > .methodsmith/runs/temp-roots.txt` -> deny. + - Latency: a decision with 20 markers present stays under 1 s. +- **Verification:** New tests pass; existing guard tests pass. + +### U4. Deny unresolvable dynamic source targets + +- **Goal:** R7, R8. +- **Requirements:** R7, R8, R10. KTD4. +- **Dependencies:** None. +- **Files:** `plugins/methodsmith/hooks/data-boundary-guard.py`, `tests/data-boundary-limits.test.ts`. +- **Approach:** + 1. Add failing tests in the "limit 1a" block. + 2. Extend `SOURCED` with first-argument capture and the resolvable-literal forms; add the function-value forms. + 3. In `judge`, scan every `-e`/`-c` argument; in `script_reads_data`, follow resolvable sourced scripts and deny unresolvable ones. +- **Patterns to follow:** `READ_CALL` variable-argument rule, `_SCANNING` recursion cap. +- **Test scenarios:** schema-only, where `R/x.R` is clean and `R/bad.R` reads `data/cohort.csv`: + - `Rscript -e 'source(file.path("R","x.R"))'` -> allow; with `"bad.R"` -> deny. + - `Rscript -e 'source(file="R/x.R")'` -> allow. + - `Rscript -e 'source(here::here("R","x.R"))'` -> allow. + - `Rscript -e 'source(paste0("R/", step, ".R"))'` -> deny; reason names `method-safe-run`. + - `Rscript -e 'invisible(lapply(list.files("R", full.names=TRUE), source))'` -> deny. + - `Rscript -e 'f<-"R/x.R"' -e 'source(f)'` -> deny. + - `python3 -c "exec(open(p).read())"` -> deny; `python3 -c "import runpy; runpy.run_path('s.py')"` with clean `s.py` -> allow. + - `Rscript -e 'sys.source(f)'`, `Rscript -e 'eval(parse(f))'`, `Rscript -e 'eval(parse(file = f))'` -> deny. + - `python3 -c "exec(compile(open(p).read(), p, 'exec'))"`, `python3 -c "import importlib; importlib.import_module(m)"`, `python3 -c "exec(Path(p).read_text())"` -> deny. + - `python3 -c "import runpy; runpy.run_module(name)"` -> deny; `runpy.run_module('pkg.bad')` where `pkg/bad.py` reads data -> deny; `runpy.run_module('pkg.ok')` (clean) -> allow. + - `Rscript -e 'source("R/missing.R")'` -> deny (resolved file absent). + - `Rscript -e 'setwd("sub"); source("R/x.R")'` -> deny. + - Script file with `dplyr::count(df, source)` -> allow. + - Script file `analysis/main.R` containing `for (f in fs) source(f)` run as `Rscript analysis/main.R` -> deny. + - Script file containing `source("R/bad.R")` -> deny (followed); `source("R/x.R")` -> allow. + - The plugin's `method-safe-run -- Rscript -e 'source(f)'` -> allow. + - Approved project: the unresolvable forms -> allow. +- **Verification:** New tests pass; existing launch-shape tests pass. + +### U5. Docs and docstring + +- **Goal:** R11. +- **Requirements:** R11. +- **Dependencies:** U1-U4. +- **Files:** `plugins/methodsmith/hooks/data-boundary-guard.py` (docstring), `README.md`, `plugins/methodsmith/README.md`, `docs/setup.md`. +- **Approach:** Update the coverage and Safe runner paragraphs and the Limits paragraph identically in the three docs: database MCP tools, temp-dir and in-progress handling with `--reconcile`, unresolvable sources, and the remaining limits from Scope Boundaries. +- **Test expectation:** none -- documentation; `tests/phi-environment-gate.test.ts` enforces identical sections and required phrases. +- **Verification:** `tests/phi-environment-gate.test.ts` and `tests/migration-docs.test.ts` pass. + +--- + +## Verification Contract + +| Gate | Command | Applies to | +|---|---|---| +| Dependencies | `bun install` | Before the first test run | +| Baseline | Record failing test names on the starting tree | Before edits | +| Tests | `bun test` | All units; no failures beyond the 9 known DOCX/number-registry failures on this machine | +| Types | `bun run typecheck` | All units | +| Release metadata | `bun run release:validate` | U5 | +| Eval cases | `bun run eval:validate` | All units | +| Rebrand residue | `bun run scripts/rebrand/rename.ts --check` | All units | + +--- + +## Definition of Done + +- Every deny scenario in U1-U4 that reproduces an open leak has a test that failed before the change and passes after it. +- Allow scenarios and latency checks pass before and after. +- All Verification Contract gates pass. +- The guard docstring and the three setup docs describe the new coverage and limits identically. +- No abandoned-attempt code or scratch fixtures remain in the diff. diff --git a/docs/setup.md b/docs/setup.md index c49d6249..fa3c0f5f 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -443,7 +443,12 @@ denies: and `pdm run`; a direct path with a script extension or interpreter shebang; a script fed on stdin; `source`; `python -m` for a project module; `Rscript -e "source(...)"`; and code inside `sh -c`, `bash -c`, or `eval`. - The hook reads the script itself, up to 1 MB. Scripts that do not touch + A script that runs another file the hook cannot resolve before it runs + (`source(f)`, `eval(parse(f))`, `source` passed to `lapply`, `runpy`, + `exec`/`eval` of a computed string, `importlib.import_module(name)`) is + denied too; literal paths, including `file.path(...)` and `here(...)` over + literals, are followed and checked. The hook reads the script itself, up to + 1 MB. Scripts that do not touch data, or that only read aggregate tables that pass the check below, run as before. - Workflow runners (`make`, `snakemake`, `nextflow`, `dvc repro`, `pytest`, @@ -460,6 +465,16 @@ strictest wins. Unquoted shell wildcards are expanded (up to 256 matches) and checked like the files they name; in schema-only mode a wildcard that matches more than that is treated as data. +Database MCP tools (Postgres, DuckDB, SQLite, Snowflake, BigQuery, MongoDB, +Neo4j, and similar, recognized by a database word in the tool name or by SQL +or Cypher statement text in the arguments) return query results straight +into the context, so in schema-only mode they are denied unless the call only +inspects the schema: a tool that lists or describes tables, or a single +`DESCRIBE`, `SHOW TABLES`/`COLUMNS`, `PRAGMA table_info`, or plain select from +`information_schema.tables`/`columns`. Run real queries in a script through +the safe runner, write an aggregate table, and read it with +`method-aggregate-read`. Literature and search connectors are not affected. + **Safe runner.** `scripts/method-safe-run -- ` runs the command and writes its full stdout and stderr to `.methodsmith/runs/-.log` (gitignored). It prints only the exit code, the duration, the files created or @@ -469,7 +484,13 @@ timestamps), and a stderr summary that keeps only traceback file and line frames and exception type names, plus a count of withheld lines; identifier values in file names are masked. It never prints stdout or other stderr text: open the log yourself. It refuses to run when no `.methodsmith/` or `.git` is -found above the working directory. +found above the working directory. The command gets its own temp directory +(`TMPDIR`, `TMP`, `TEMP`) outside the project, which counts as data and is +removed when the run finishes. While a run, or anything it started, is still +going, project files changed since it began count as data; a run that was +killed before recording its outputs keeps that rule in force until the next +run or `method-safe-run --reconcile` records what it wrote. Processes a +command leaves running are stopped about 10 seconds after it exits. The hook's deny message gives the runner's full path. It accepts only the plugin's own runner (or a byte-identical copy) and still checks uploads inside it. @@ -545,7 +566,14 @@ If it is missing, the launcher prints a warning and exits successfully, so the guard is inactive and calls are not blocked. The script check is heuristic static analysis: a script that builds a data path at run time, or reads data through a function the hook does not recognize, can still print values, and -programs it cannot parse (deliberate obfuscation) are out of scope. Values +programs it cannot parse (deliberate obfuscation) are out of scope. Files a +safe-runner command writes to hard-coded paths outside the project and its +temp directory (`/tmp/x.csv`, Java's `java.io.tmpdir`, Spark's local +directory), and processes that leave the run's process group with `setsid`, +are not tracked. A database server whose tools have no database word in +their names and take no SQL text is not recognized, and MCP resources are not +checked. Editing a file while a safe-runner command is still running makes +that file data until the run ends. Values that are not in identifier columns, such as free-text notes, are not indexed, and the identifier patterns catch common shapes, not every one. A patient who shares a full name with an author you search for blocks that name. A config diff --git a/plugins/methodsmith/README.md b/plugins/methodsmith/README.md index fe3d1150..c3f084a4 100644 --- a/plugins/methodsmith/README.md +++ b/plugins/methodsmith/README.md @@ -526,7 +526,12 @@ denies: and `pdm run`; a direct path with a script extension or interpreter shebang; a script fed on stdin; `source`; `python -m` for a project module; `Rscript -e "source(...)"`; and code inside `sh -c`, `bash -c`, or `eval`. - The hook reads the script itself, up to 1 MB. Scripts that do not touch + A script that runs another file the hook cannot resolve before it runs + (`source(f)`, `eval(parse(f))`, `source` passed to `lapply`, `runpy`, + `exec`/`eval` of a computed string, `importlib.import_module(name)`) is + denied too; literal paths, including `file.path(...)` and `here(...)` over + literals, are followed and checked. The hook reads the script itself, up to + 1 MB. Scripts that do not touch data, or that only read aggregate tables that pass the check below, run as before. - Workflow runners (`make`, `snakemake`, `nextflow`, `dvc repro`, `pytest`, @@ -543,6 +548,16 @@ strictest wins. Unquoted shell wildcards are expanded (up to 256 matches) and checked like the files they name; in schema-only mode a wildcard that matches more than that is treated as data. +Database MCP tools (Postgres, DuckDB, SQLite, Snowflake, BigQuery, MongoDB, +Neo4j, and similar, recognized by a database word in the tool name or by SQL +or Cypher statement text in the arguments) return query results straight +into the context, so in schema-only mode they are denied unless the call only +inspects the schema: a tool that lists or describes tables, or a single +`DESCRIBE`, `SHOW TABLES`/`COLUMNS`, `PRAGMA table_info`, or plain select from +`information_schema.tables`/`columns`. Run real queries in a script through +the safe runner, write an aggregate table, and read it with +`method-aggregate-read`. Literature and search connectors are not affected. + **Safe runner.** `scripts/method-safe-run -- ` runs the command and writes its full stdout and stderr to `.methodsmith/runs/-.log` (gitignored). It prints only the exit code, the duration, the files created or @@ -552,7 +567,13 @@ timestamps), and a stderr summary that keeps only traceback file and line frames and exception type names, plus a count of withheld lines; identifier values in file names are masked. It never prints stdout or other stderr text: open the log yourself. It refuses to run when no `.methodsmith/` or `.git` is -found above the working directory. +found above the working directory. The command gets its own temp directory +(`TMPDIR`, `TMP`, `TEMP`) outside the project, which counts as data and is +removed when the run finishes. While a run, or anything it started, is still +going, project files changed since it began count as data; a run that was +killed before recording its outputs keeps that rule in force until the next +run or `method-safe-run --reconcile` records what it wrote. Processes a +command leaves running are stopped about 10 seconds after it exits. The hook's deny message gives the runner's full path. It accepts only the plugin's own runner (or a byte-identical copy) and still checks uploads inside it. @@ -628,7 +649,14 @@ If it is missing, the launcher prints a warning and exits successfully, so the guard is inactive and calls are not blocked. The script check is heuristic static analysis: a script that builds a data path at run time, or reads data through a function the hook does not recognize, can still print values, and -programs it cannot parse (deliberate obfuscation) are out of scope. Values +programs it cannot parse (deliberate obfuscation) are out of scope. Files a +safe-runner command writes to hard-coded paths outside the project and its +temp directory (`/tmp/x.csv`, Java's `java.io.tmpdir`, Spark's local +directory), and processes that leave the run's process group with `setsid`, +are not tracked. A database server whose tools have no database word in +their names and take no SQL text is not recognized, and MCP resources are not +checked. Editing a file while a safe-runner command is still running makes +that file data until the run ends. Values that are not in identifier columns, such as free-text notes, are not indexed, and the identifier patterns catch common shapes, not every one. A patient who shares a full name with an author you search for blocks that name. A config diff --git a/plugins/methodsmith/hooks/data-boundary-guard.py b/plugins/methodsmith/hooks/data-boundary-guard.py index 9d152833..918664db 100644 --- a/plugins/methodsmith/hooks/data-boundary-guard.py +++ b/plugins/methodsmith/hooks/data-boundary-guard.py @@ -40,7 +40,8 @@ path, unless the command runs through the plugin's method-safe-run, however the script is launched: python/Rscript/bash/sh/quarto render/jupyter nbconvert --execute, run wrappers (uv/pdm/poetry run), a direct path with a script -extension or interpreter shebang, stdin, source/., python -m for a project +extension or interpreter shebang (scanned in the shebang's or interpreter's +language even without an extension), stdin, source/., python -m for a project module, Rscript -e source(), and sh -c/bash -c/eval code. Workflow runners (make, snakemake, pytest, dvc, npm/pnpm/yarn/bun run scripts, targets::tar_make, rmarkdown::render, and similar) are denied unless run through method-safe-run. @@ -48,15 +49,34 @@ reach, so a call from outside a project gets that project's boundary (strictest wins). Unquoted shell wildcards are expanded (bounded) and checked match by match; an over-cap expansion is data in schema-only access checks. +Code that runs another file (R source/sys.source/parse(), str2lang/ +str2expression of computed text, source passed to apply-style functions, Python +runpy, exec/eval of computed code, import_module, __import__) follows literal +targets and denies computed, missing, or setwd/chdir-relative ones; after a +run-time import path change (sys.path, site.addsitedir, PYTHONPATH) a literal +module name with no project file is denied too. Database MCP tools (named with a +database word, or carrying SQL/Cypher statement text) deny in schema-only unless +the call only inspects the schema (list/describe tools, or one DESCRIBE, SHOW +TABLES|COLUMNS, PRAGMA table_info, or plain information_schema select); on a +database-named tool a statement under any argument key counts, and an exempt +literature server word does not exempt a server name that also has a database +word. Inside method-safe-run only the copy rule still applies (output stays in the log), -and files a run wrote (runs/outputs.txt) are data afterwards. Tables under +and files a run wrote (runs/outputs.txt) are data afterwards, as are its temp +directories (runs/temp-roots.txt) and, while a run is live or was never +reconciled (runs/active/*.json), project files changed since it started. Those +state files can only be changed by method-safe-run itself, also not by shell code +it runs (method-safe-run -- bash -c 'rm ...'). Tables under phi_environment.aggregate_dirs print through the plugin's method-aggregate-read, which reads once and checks the bytes it prints (no identifier headers or indexed cells, no counts 1-10, at most 500 rows); a hook-time check of a later shell or script read could be raced. Markdown tables, which are not data files, are also checked on Read and cat. Limits: the script check is -heuristic; obfuscation the parser cannot see is out of scope; this is defense -in depth, not a sandbox. +heuristic; obfuscation the parser cannot see is out of scope; writes to +hard-coded paths outside the project and the run's temp directory, processes +that leave the run's process group, database servers with no database word and +no SQL text, and MCP resources are not covered; this is defense in depth, not a +sandbox. Fail mode: config problems resolve to schema-only. An unexpected internal error denies only calls that mention a data-like path or an upload; anything else is @@ -149,9 +169,29 @@ PY_WORKFLOW_MODULES = {"pytest", "tox", "nox", "invoke", "papermill", "snakemake", "unittest", "kedro", "dbt"} R_WORKFLOW = re.compile(r"\b(?:targets::)?tar_make\w*\s*\(|\b(?:rmarkdown::)?render(?:_site)?\s*\(|" r"\bquarto::quarto_render\s*\(|\bbookdown::render_book\s*\(|\bknitr::(?:knit|purl)\s*\(") -# Inline code that runs a script file: R source()/sys.source(), Python runpy.run_path() and exec(open(...)). -SOURCED = re.compile(r"\b(?:sys\.)?source\s*\(\s*['\"]([^'\"]+)['\"]|\brun_path\s*\(\s*['\"]([^'\"]+)['\"]|" - r"\bexec\s*\(\s*open\s*\(\s*['\"]([^'\"]+)['\"]") +# Code that runs another file or module (sink table, R7). The group name says how the target is read. +# parse() is a sink wherever it appears (its expressions can be eval'd later); str2expression/str2lang turn text +# into code, so only a literal argument is resolvable. +R_SINKS = re.compile(r"(?sys\.source|source)\s*\(|" + r"(?parse)\s*\(|" + r"(?str2expression|str2lang)\s*\(") +PY_SINKS = re.compile(r"(?run_path)\s*\(|" + r"(?run_module|import_module|__import__)\s*\(|" + r"(?spec_from_file_location)\s*\(|" + r"(?exec|eval)\s*\(") +# R higher-order calls that can take source/sys.source as a function value (a bare `source` elsewhere is a name). +R_HIGHER_ORDER = re.compile(r"(?", ">>", "<>", ">|", "&>", "&>>", ">&", "<&"} @@ -366,6 +406,8 @@ def _header_patterns(): INDEX_REL = os.path.join(STATE_DIR, "identifier-index.local.json") LEGACY_INDEX_REL = os.path.join(LEGACY_STATE_DIR, "identifier-index.local.json") OUTPUTS = "outputs.txt" # method-safe-run lists the files its runs wrote here, one project-relative path per line +TEMP_ROOTS = "temp-roots.txt" # method-safe-run lists each run's temp directory here, one absolute path per line +ACTIVE = "active" # method-safe-run marks each run in progress with active/-.json def run_outputs(mode): @@ -382,6 +424,196 @@ def run_outputs(mode): return mode["_outputs"] +def temp_roots(runs, base): + """Each temp directory listed in a runs folder's temp-roots.txt, as written and resolved: run output.""" + roots = set() + try: + with open(os.path.join(runs, TEMP_ROOTS), encoding="utf-8", errors="replace") as fh: + lines = fh.read().splitlines() + except OSError: + return roots + for line in lines: + line = line.strip() + if line: + path = os.path.normpath(os.path.join(base, os.path.expanduser(line))) + roots.update({path, os.path.realpath(path)}) + return roots + + +def run_markers(mode): + """The in-progress run markers of schema-only projects, read once per decision. Only runs/active/ is listed. + + A marker that cannot be read, or has no integer start, counts as a run of unknown start (fail closed). + """ + if "_markers" not in mode: + mode["_markers"] = [] + for active, root in mode.get("marker_dirs", []): + try: + names = sorted(n for n in os.listdir(active) if n.endswith(".json") and not n.startswith(".")) + except OSError: + continue + roots = sorted({root, os.path.realpath(root)}) + for name in names: + try: + with open(os.path.join(active, name), encoding="utf-8") as fh: + fields = json.load(fh) + except FileNotFoundError: + continue # the run finished between the listing and the read; its outputs are recorded + except (OSError, ValueError): + fields = None + start = fields.get("start") if isinstance(fields, dict) else None + if type(start) is not int: # unreadable: count from when the marker file was created, still live + fields, start = None, _created_ns(os.path.join(active, name)) + tmp = fields.get("tmp") if fields else None + tmps = sorted({tmp, os.path.realpath(tmp)}) if isinstance(tmp, str) and os.path.isabs(tmp) else [] + mode["_markers"].append({"start": start, "roots": roots, "fields": fields, "hit": False, "tmp": tmps, + "lists_changed": _lists_changed(os.path.dirname(active), fields, start)}) + return mode["_markers"] + + +def _lists_changed(runs, fields, start): + """outputs.txt changed or went missing since an in-progress run started (the runner creates it first): the + run's own code may have erased entries, its own or another run's, which the runner puts back only at its next + heartbeat, so the list cannot be trusted. The marker's outputs_stamp is the list's [mtime, ctime] at the start; + markers without it but with outputs_lines compare against the start; older markers keep the per-file rule.""" + if not fields: + return False + stamp = fields.get("outputs_stamp") + exact = isinstance(stamp, list) and len(stamp) == 2 and all(type(t) is int for t in stamp) + if not exact and type(fields.get("outputs_lines")) is not int: + return False + try: + st = os.lstat(os.path.join(runs, OUTPUTS)) + except OSError: + return True + if exact: + return [st.st_mtime_ns, st.st_ctime_ns] != stamp + return max(st.st_mtime_ns, st.st_ctime_ns) >= start + + +def marker_tmp_hit(path, mode): + """A path under the temp directory an in-progress run's marker names, listed in temp-roots.txt or not.""" + return any(m["tmp"] and _under(c, m["tmp"]) for m in run_markers(mode) for c in {path, os.path.realpath(path)}) + + +def _changed_ns(path, mode): + cache = mode.setdefault("_changed", {}) + if path not in cache: + try: + st = os.lstat(path) + cache[path] = max(st.st_mtime_ns, st.st_ctime_ns) + except OSError: + cache[path] = None + return cache[path] + + +def marker_hit(path, mode): + """An existing project path that, or whose directory, changed at or after the start of an in-progress run.""" + markers = run_markers(mode) + if not markers or not os.path.lexists(path): + return False + hit = False + for candidate in {path, os.path.realpath(path)}: + parent = os.path.dirname(candidate) + for marker in markers: + if candidate in marker["roots"] or not _under(candidate, marker["roots"]): + continue + if marker["lists_changed"]: + marker["hit"] = hit = True + continue + times = [_changed_ns(candidate, mode)] + if _under(parent, marker["roots"]): + times.append(_changed_ns(parent, mode)) + if any(t is not None and t >= marker["start"] for t in times): + marker["hit"] = hit = True + return hit + + +def _pid_alive(pid, group=False): + try: + (os.killpg if group else os.kill)(pid, 0) + except PermissionError: + return True + except (OSError, OverflowError, ValueError): + return False + return True + + +def _process_start(pid, cache): + """The process start time as `ps -o lstart=` prints it (whitespace collapsed); "" when unknown.""" + if pid not in cache: + import subprocess # only a marker hit on a live runner needs it + + try: + out = subprocess.run(["ps", "-o", "lstart=", "-p", str(pid)], capture_output=True, text=True, timeout=2, + env={**os.environ, "LC_ALL": "C"}) + cache[pid] = " ".join(out.stdout.split()) if out.returncode == 0 else "" + except (OSError, ValueError, subprocess.SubprocessError): + cache[pid] = "" + return cache[pid] + + +def _created_ns(path): + """A file's creation time (birth time where the filesystem records it, else its change time), or 0.""" + try: + st = os.stat(path) + except OSError: + return 0 + birth = getattr(st, "st_birthtime", None) + return int(birth * 1e9) if birth else min(st.st_ctime_ns, st.st_mtime_ns) + + +def marker_state(marker, cache): + """"stale" (runner and its process group gone, this host), "foreign" (another host), else "live". + + Mirrors method-safe-run's own staleness test; anything it cannot tell is live. + """ + import socket + + fields = marker["fields"] + if fields is None: + return "live" + pid, pgid, host = fields.get("pid"), fields.get("pgid"), fields.get("host") + if isinstance(host, str) and host != socket.gethostname(): + return "foreign" + if host is None or type(pid) is not int: + return "live" + if _pid_alive(pid): + recorded = fields.get("pid_start") + if not isinstance(recorded, str) or not recorded: + return "live" + current = _process_start(pid, cache) + if not current or current == recorded: + return "live" + if pgid is not None and (type(pgid) is not int or _pid_alive(pgid, group=True)): + return "live" + return "stale" + + +def marker_note(mode): + """Why a marker hit is data, and what clears it. None when no marker matched this decision.""" + hits = [m for m in mode.get("_markers", []) if m["hit"]] + if not hits: + return None + cache = {} + states = {marker_state(m, cache) for m in hits} + notes = [] + if "stale" in states: + notes.append("a method-safe-run that changed files here ended without recording its outputs, so files " + f"changed since it started count as data; run `{SAFE_RUNNER} --reconcile` to record them " + "and clear its marker") + if any(m["lists_changed"] for m in hits): + notes.append("a method-safe-run's outputs.txt changed while the run is in progress, so until it finishes " + "every project file counts as data") + if "live" in states: + notes.append("a method-safe-run is still in progress (or its marker cannot be read), so files changed " + "since it started count as data until it finishes") + if "foreign" in states: + notes.append("a method-safe-run marker from another host is in force, so files changed since that run " + "started count as data until it is cleared on that host") + return "; ".join(notes) + + def load_index(mode): """The project's identifier index, loaded once and only for calls that need it.""" if "_index" not in mode: @@ -594,9 +826,18 @@ def _project_mode(ce_root, main): mode, why, detail = mode_from_config(phi, error) runs = os.path.join(ce_root, STATE_DIR, "runs") # method-safe-run logs hold raw output data_roots = {runs, os.path.realpath(runs)} + runs_dirs = [runs] for base in bases: # logs left in an unmoved pre-rename folder are still data legacy_runs = os.path.join(base, LEGACY_STATE_DIR, "runs") data_roots.update({legacy_runs, os.path.realpath(legacy_runs)}) + runs_dirs.append(legacy_runs) + for runs_dir in runs_dirs: # files a run wrote to its own temp directory are data + data_roots.update(temp_roots(runs_dir, ce_root)) + boundary_state = set() # only method-safe-run may change these + for runs_dir in runs_dirs: + for rel in (ACTIVE, TEMP_ROOTS, OUTPUTS): + path = os.path.join(runs_dir, rel) + boundary_state.update({path, os.path.realpath(path)}) for root in (data_root, legacy_root): if not root: continue @@ -625,7 +866,8 @@ def _project_mode(ce_root, main): break return {"mode": mode, "why": why, "detail": detail, "roots": [ce_root], "data_roots": sorted(data_roots), "aggregate_dirs": aggregate, "index_paths": index_paths, "output_lists": output_lists, - "locale": locale or None} + "locale": locale or None, "marker_dirs": [[os.path.join(runs, ACTIVE), ce_root]], + "boundary_state": sorted(boundary_state)} RANK = {"off": 0, "approved": 1, "no-sensitive-data": 1, "schema-only": 2} @@ -736,6 +978,7 @@ def resolve_mode(context): cwd, anchors = _anchors(context) cache, projects = {}, {} best, data_roots, roots, aggregate, index_paths, output_lists = None, set(), [], set(), [], [] + marker_dirs, boundary_state = [], set() for anchor in anchors: found = _locate(anchor, cache) if not found or found in projects: @@ -746,13 +989,18 @@ def resolve_mode(context): index_paths.extend(p for p in project["index_paths"] if p not in index_paths) output_lists.extend(p for p in project["output_lists"] if p not in output_lists) roots.extend(r for r in project["roots"] if r not in roots) + if project["mode"] == "schema-only": # in-progress runs and their state matter only where access is limited + marker_dirs.extend(project["marker_dirs"]) + boundary_state.update(project["boundary_state"]) if best is None or RANK[project["mode"]] > RANK[best["mode"]]: best = project if best is None: return {"mode": "off", "why": None, "detail": "", "roots": [], "data_roots": [], "aggregate_dirs": [], - "index_paths": [], "output_lists": [], "cwd": cwd, "locale": None} + "index_paths": [], "output_lists": [], "cwd": cwd, "locale": None, "marker_dirs": [], + "boundary_state": []} return dict(best, roots=roots, data_roots=sorted(data_roots), aggregate_dirs=sorted(aggregate), - index_paths=index_paths, output_lists=output_lists, cwd=cwd) + index_paths=index_paths, output_lists=output_lists, cwd=cwd, marker_dirs=marker_dirs, + boundary_state=sorted(boundary_state)) # ------------------------------------------------------------------- data refs @@ -913,6 +1161,8 @@ def is_data_path(raw, cwd, mode, over_cap_is_data=False): if parts and parts[-1].lower() in DATAISH_DIRS: return True continue + if mode.get("marker_dirs") and (marker_hit(path, mode) or marker_tmp_hit(path, mode)): + return True if os.path.lexists(path): real = os.path.realpath(path) if real != path and (DATA_REF.search(real) or _under(real, mode["data_roots"])): @@ -1428,6 +1678,8 @@ def script_reads_data(path, cwd, mode, kind=None): _SCANNING.discard(path) if lists_dataish_dir(text, cwd, mode): return True + if ext in SINK_LANGS and run_problem(text, SINK_LANGS[ext], cwd, mode): + return True # runs a file it cannot resolve, or one that reads data if any(first not in ("'", '"', "") for first in READ_CALL.findall(text)): return True # reads a path held in a variable or argument for literal in (a or b for a, b in LITERAL.findall(text)): @@ -1436,6 +1688,203 @@ def script_reads_data(path, cwd, mode, kind=None): return False +_ARG_TOKEN = re.compile(r"'(?:\\.|[^'\\\n])*'|\"(?:\\.|[^\"\\\n])*\"|[()\[\]{},]|[^'\"()\[\]{},]+") +_NAMED_ARG = re.compile(r"^([A-Za-z_.][\w.]*)\s*=(?!=)\s*(.*)$", re.S) +_R_STRING = re.compile(r"'([^'\\\n]*)'|\"([^\"\\\n]*)\"") +_PY_STRING = re.compile(r"[rRuUbB]{0,2}(?:'([^'\\\n]*)'|\"([^\"\\\n]*)\")") +_CALL_WINDOW = 4000 +UNRESOLVED = ("unresolved", None) + + +def _call_args(text, start): + """(positional, named, end) for the call whose `(` ends just before start, or None when it does not close. + + Splits top-level commas outside strings and brackets; looks at most _CALL_WINDOW characters ahead. + """ + parts, current, depth = [], [], 0 + for m in _ARG_TOKEN.finditer(text, start, min(len(text), start + _CALL_WINDOW)): + token = m.group() + if token in ("(", "[", "{"): + depth += 1 + elif token in (")", "]", "}"): + if depth == 0: + parts.append("".join(current).strip()) + positional, named = [], {} + for part in filter(None, parts): + found = _NAMED_ARG.match(part) + if found: + named[found.group(1)] = found.group(2).strip() + else: + positional.append(part) + return positional, named, m.end() + depth -= 1 + elif token == "," and depth == 0: + parts.append("".join(current).strip()) + current = [] + continue + current.append(token) + return None + + +def _whole_call(expr, pattern): + """(positional, named) when expr is exactly one call matching pattern at its start, else None.""" + head = re.match(pattern, expr) + parsed = head and _call_args(expr, head.end()) + if not parsed or expr[parsed[2]:].strip(): + return None + return parsed[0], parsed[1] + + +def _r_value(expr, root): + """The string an R expression evaluates to when it is built from literals only, else None. + + Literals, and file.path / paste0 / paste(sep=) / here() / here::here() over literals (here() is relative to + the project root). + """ + expr = expr.strip() + literal = _R_STRING.fullmatch(expr) + if literal: + return literal.group(1) if literal.group(1) is not None else literal.group(2) + head = re.match(r"(?:base::)?(file\.path|paste0|paste|(?:here::)?here)\s*\(", expr) + call = head and _whole_call(expr, re.escape(head.group(0))) + if not call: + return None + positional, named = call + func = head.group(1) + seps = {"file.path": ("fsep", "/"), "paste0": (None, ""), "paste": ("sep", " ")}.get(func, (None, "/")) + if set(named) - {seps[0]}: + return None + sep = _r_value(named[seps[0]], root) if seps[0] in named else seps[1] + values = [_r_value(p, root) for p in positional] + if sep is None or None in values: + return None + joined = sep.join(values) + return os.path.join(root, joined) if func.endswith("here") else joined + + +def _py_value(expr): + """The string a Python literal holds (no f-strings), else None.""" + literal = _PY_STRING.fullmatch(expr.strip()) # the prefix set has no f, so f-strings never match + if not literal: + return None + return literal.group(1) if literal.group(1) is not None else literal.group(2) + + +def _py_code_file(expr): + """For exec/eval: ("code", None) for a string literal, ("file", path) for open(LIT).read(), + Path(LIT).read_text(), or compile(, ...); None otherwise.""" + expr = expr.strip() + if _py_value(expr) is not None: + return "code", None + compiled = _whole_call(expr, r"(?:builtins\.)?compile\s*\(") + if compiled: + return _py_code_file(compiled[0][0]) if compiled[0] else None + reader = re.match(r"(?:io\.)?open\s*\(|(?:pathlib\.)?Path\s*\(", expr) + parsed = reader and _call_args(expr, reader.end()) + if not parsed or not parsed[0]: + return None + method = "read_text" if "Path" in reader.group(0) else "read" + if not re.fullmatch(r"\s*\.\s*" + method + r"\s*\(\s*\)\s*", expr[parsed[2]:]): + return None + path = _py_value(parsed[0][0]) + return ("file", path) if path is not None else None + + +def _sink_target(lang, kind, positional, named, root): + """("file", path), ("module", name), ("code", None), ("none", None), or UNRESOLVED for one sink call.""" + if lang == "r": + if kind == "source": + if named.get("chdir", "FALSE") not in ("FALSE", "F"): + return UNRESOLVED # nested relative paths resolve against the sourced file's directory + expr = named.get("file", positional[0] if positional else None) + elif kind == "str2": + expr = named.get("text", named.get("s", positional[0] if positional else None)) + return ("code", None) if expr is not None and _r_value(expr, root) is not None else UNRESOLVED + else: # parse(...): a file, or text that is code + if "file" not in named and not positional and "text" in named: + return ("code", None) if _r_value(named["text"], root) is not None else UNRESOLVED + expr = named.get("file", positional[0] if positional else None) + if expr is None: + return "none", None + value = _r_value(expr, root) + return ("file", value) if value is not None else UNRESOLVED + if kind == "exec": + expr = positional[0] if positional else named.get("source", named.get("expression")) + if expr is None: + return "none", None + return _py_code_file(expr) or UNRESOLVED + if kind == "module": + expr = named.get("mod_name", named.get("name", positional[0] if positional else None)) + if expr is None: + return "none", None + value = _py_value(expr) + return ("module", value) if value and re.fullmatch(r"[A-Za-z_][\w.]*", value) else UNRESOLVED + if kind == "spec": + expr = named.get("location", positional[1] if len(positional) > 1 else None) + else: # run_path + expr = named.get("path_name", named.get("path", positional[0] if positional else None)) + if expr is None: + return "none", None + value = _py_value(expr) + return ("file", value) if value is not None else UNRESOLVED + + +def run_problem(code, langs, cwd, mode, env=()): + """None, UNRESOLVED, or ("reads", shown) for code that runs another file or module (R7, R8). + + A literal target (see _r_value / _py_value) is followed and scanned with script_reads_data; a target that is + not built from literals, a file that does not exist, a working-directory change before the call, or R's + source passed as a function value to an apply/map-style call cannot be checked and is unresolved. A literal + module name that resolves to no project file is an installed module and is not scanned. + """ + code = re.sub(r"(?m)^[ \t]*#.*$", "", code) # whole-line comments (and Quarto/R Markdown headings) + root = (mode.get("roots") or [cwd])[0] + moved = CHDIR_CALL.search(code) + moved_at = moved.start() if moved else len(code) + 1 + for lang in langs: + sinks = R_SINKS if lang == "r" else PY_SINKS + for m in sinks.finditer(code): + kind = m.lastgroup + if lang == "py-file" and m.group(kind) == "eval": + continue # R's eval() in a mixed document; Python exec() is still checked + if m.start() > moved_at: + return UNRESOLVED + parsed = _call_args(code, m.end()) + if parsed is None: + return UNRESOLVED + what, target = _sink_target("r" if lang == "r" else "py", kind, parsed[0], parsed[1], root) + if what == "unresolved": + return UNRESOLVED + if what == "module": + paths = [(target, path) for path in module_files(target, cwd, env)] + if not paths and IMPORT_PATH_CHANGE.search(code, 0, m.start()): + return UNRESOLVED # may be a module on the changed path, not an installed one + elif what == "file": + path = _resolve(target, cwd) + if not os.path.isfile(path): + return UNRESOLVED + paths = [(target, path)] + else: + continue + for shown, path in paths: + if path in _SCANNING: + continue + if len(_SCANNING) >= 8: + return UNRESOLVED # too deep to follow + _SCANNING.add(path) + try: + if script_reads_data(path, cwd, mode, "r" if lang == "r" else "py"): + return "reads", shown + finally: + _SCANNING.discard(path) + if lang == "r": + for m in R_HIGHER_ORDER.finditer(code): + parsed = _call_args(code, m.end()) + if parsed and any(R_SOURCE_VALUE.match(v) for v in parsed[0] + list(parsed[1].values())): + return UNRESOLVED + return None + + AGGREGATE_EXTS = {"csv": ",", "tsv": "\t", "tab": "\t", "md": None} AGGREGATE_MAX_ROWS = 500 AGGREGATE_CAP = 2 << 20 @@ -1551,15 +2000,25 @@ def script_kind(path, interpreter=None): """ ext = _ext(path) if interpreter: - return "sh" if program(interpreter) in SHELLS else (ext or "code") + return "sh" if program(interpreter) in SHELLS else (ext if ext in SINK_LANGS else _lang_of(interpreter, ext)) if ext in SCRIPT_EXTS or ext == "ipynb": return ext found = shebang(path) if found: - return "sh" if found in SHELLS else "code" + return "sh" if found in SHELLS else _lang_of(found, "") return None +def _lang_of(interpreter, ext): + """The SINK_LANGS key for an interpreter (python/pypy/ipython -> py, Rscript/R -> r), else ext or "code".""" + name = program(interpreter) + if re.match(r"^(?:python|pypy|ipython)", name): + return "py" + if name in ("rscript", "r"): + return "r" + return ext or "code" + + def _script_ops(verb, args): """An interpreter's operands: no options, option values, or redirects and their targets.""" out, skip = [], False @@ -1794,14 +2253,22 @@ def judge(cmd, cwd, mode, tainted, written, fed=(), env=()): refs = any(token_ref(t, cwd, mode, tainted) for t in cmd) inline_index = next((i for i, t in enumerate(args) if INLINE_FLAG.match(t)), None) if INTERPRETERS.match(verb) and inline_index is not None and args[inline_index] != "-": # `-`: code on stdin - code = " ".join(args[inline_index + 1:inline_index + 2]) + # Every code argument (`Rscript -e A -e B` runs both), in order, as one program. + code = "\n".join(args[i + 1] for i in range(inline_index, len(args) - 1) + if INLINE_FLAG.match(args[i]) and args[i] != "-") if refs or text_ref(code, cwd, mode) or lists_dataish_dir(code, cwd, mode): return f"inline `{verb}` code that opens data returns its values", False if verb in ("rscript", "r") and R_WORKFLOW.search(code): return workflow_reason(f"{cmd[0]} -e"), False - for target in (a or b or c for a, b, c in SOURCED.findall(code)): - if script_reads_data(_resolve(target, cwd), cwd, mode): - return f"the script `{target}` reads data and can print its values", False + langs = ("r",) if verb in ("rscript", "r") else ("py",) if re.match(r"^(?:i?python|pypy)", verb) else () + problem = run_problem(code, langs, cwd, mode, env) + if problem == UNRESOLVED: + return (f"inline `{verb}` code runs a file or module whose path is only known when it runs (or after " + "a working-directory change), so the guard cannot check it; run it as " + f"`method-safe-run -- {cmd[0]} ...` so its output stays in the run log"), False + if problem: + return (f"the script `{problem[1]}` reads data and can print its values; run it as " + f"`method-safe-run -- {cmd[0]} ...` so its output stays in the run log"), False return None, False runner = next((t for t in args if not t.startswith("-")), "") if re.match(r"^python", verb) else cmd[0] if os.path.basename(runner) == "method-aggregate-read" and is_plugin_script(runner, cwd, AGGREGATE_READER): @@ -1822,7 +2289,8 @@ def judge(cmd, cwd, mode, tainted, written, fed=(), env=()): return workflow_reason(workflow), False for shown, path, kind in launched_scripts(cmd, cwd, fed, env): if not token_ref(shown, cwd, mode, tainted) and script_reads_data(path, cwd, mode, kind): - return f"the script `{shown}` reads data and can print its values", False + return (f"the script `{shown}` reads data, or runs a file it names only at run time, and can print " + f"its values; run it as `method-safe-run -- {cmd[0]} ...` so its output stays in the run log"), False if verb == "find": reason, unrestricted = find_exec_violation(args, cwd, mode) if reason or not refs: @@ -1859,6 +2327,94 @@ def judge(cmd, cwd, mode, tainted, written, fed=(), env=()): return f"`{verb}` on a data file prints its values", False +STATE_REASON = ("`.methodsmith/runs/active/`, `.methodsmith/runs/temp-roots.txt`, and `.methodsmith/runs/outputs.txt` " + "are the boundary's record of " + "method-safe-run runs, and only method-safe-run changes them (a dead run's marker is cleared by " + f"`{SAFE_RUNNER} --reconcile`)") +STATE_REMOVERS = {"rm", "unlink", "rmdir", "shred", "srm"} +STATE_WRITERS = {"cp", "ln", "rsync", "install", "truncate", "tee", "touch", "chmod", "chown", "chgrp", "dd"} +WRITE_REDIRECTS = {">", ">>", ">|", "&>", "&>>", "<>", ">&"} + + +def _state_part(pattern, name, globbed): + if not globbed: + return pattern == name + if name.startswith(".") and not pattern.startswith("."): + return False # a shell wildcard does not match a leading dot + return fnmatch.fnmatchcase(name, pattern) + + +def names_state(raw, cwd, mode, remove=False): + """A path (or unquoted wildcard) that is, or lies under, the boundary state; remove=True adds its ancestors.""" + targets = mode.get("boundary_state") or [] + if not targets or not raw: + return False + for variant in expand_braces(raw): + globbed = isinstance(raw, GlobToken) and any(ch in variant for ch in "*?[") + path = _resolve(variant, cwd) + for candidate in {path} if globbed else {path, os.path.realpath(path)}: + parts = [p for p in candidate.split(os.sep) if p] + for target in targets: + tparts = [p for p in target.split(os.sep) if p] + if len(parts) < len(tparts) and not remove: + continue + if all(_state_part(a, b, globbed) for a, b in zip(parts, tparts)): + return True + return False + + +def state_redirect(seg, cwd, mode): + """A shell redirect in this segment that writes the boundary state.""" + for index, token in enumerate(seg[:-1]): + target = seg[index + 1] + if token in WRITE_REDIRECTS and not (token == ">&" and re.match(r"^(?:\d+|-)$", target)): + if names_state(target, cwd, mode): + return True + return False + + +def _find_removes(args): + """find -delete, or an -exec/-ok command line that removes or moves files.""" + if "-delete" in args: + return True + return any(t in FIND_EXEC and i + 1 < len(args) and program(args[i + 1]) in STATE_REMOVERS | {"mv"} + for i, t in enumerate(args)) + + +def state_violation(cmd, cwd, mode): + """A command that removes, moves, truncates, or writes the boundary state (runs/active/, runs/temp-roots.txt, runs/outputs.txt).""" + verb, args = program(cmd[0]), cmd[1:] + values = [t.split("=", 1)[1] for t in args if t.startswith("--") and "=" in t] + ops = [t for t in args if not t.startswith("-") and t not in REDIRECTS] + if verb in STATE_REMOVERS: + return any(names_state(t, cwd, mode, remove=True) for t in ops + values) + if verb == "mv": + dest = None if any(t == "-t" or t.startswith("--target-directory") for t in args) else (ops[-1:] or [None])[0] + return any(names_state(t, cwd, mode, remove=t is not dest) for t in ops + values) + if verb == "dd": + return any(t.startswith("of=") and names_state(t[3:], cwd, mode) for t in args) + if verb in STATE_WRITERS or (verb in ("sed", "perl") and any(re.match(r"^(?:-[A-Za-z]*i|--in-place)", t) for t in args)): + return any(names_state(t, cwd, mode) for t in ops + values) + if verb == "find" and _find_removes(args): + starts = [] + for t in args: + if t.startswith("-") or t in ("!", "("): + break + starts.append(t) + if not _find_negates_or_alternates(args): # a -name filter that cannot match a state file keeps it safe + names = [(args[i], args[i + 1]) for i in range(len(args) - 1) if args[i] in FIND_NAME_ONLY_OPTS] + state_names = (TEMP_ROOTS, OUTPUTS, ACTIVE, "0.json") + if names and not any(fnmatch.fnmatchcase(n.lower() if opt == "-iname" else n, + p.lower() if opt == "-iname" else p) + for opt, p in names for n in state_names): + return False + return any(names_state(t, cwd, mode, remove=True) for t in starts or ["."]) + if verb == "git" and _git_sub(args)[:1] == ["clean"]: + cleans_ignored = any(re.match(r"^-[A-Za-z]*[xX]", t) for t in args) + return cleans_ignored and names_state(".", cwd, mode, remove=True) + return False + + def safe_companion(cmd): """A command that may share a Bash call with method-safe-run: metadata only, or a reader of the pipe (no files).""" verb = program(cmd[0]) @@ -1939,6 +2495,9 @@ def bash_violations(command, cwd, mode, depth=0): name, value = assignment.split("=", 1) if token_ref(value, cur, mode, tainted): tainted.add(name) + if mode["mode"] == "schema-only" and state_redirect(seg, run_cwd, mode): + access = access or STATE_REASON + mode["_state_hits"] = mode.get("_state_hits", 0) + 1 if not cmd: continue safe = False @@ -1950,14 +2509,20 @@ def bash_violations(command, cwd, mode, depth=0): egress = egress or upload_violation(cmd, cur, mode) or ncbi_violation(cmd, mode) inner = shell_code(cmd) if inner is not None: + hits = mode.get("_state_hits", 0) e, a = bash_violations(inner, cur, mode, depth + 1) egress = egress or e if not safe: # under the plugin's method-safe-run the inner code's output stays in the log access = access or a + elif mode.get("_state_hits", 0) > hits: # but it must not change the boundary state + access = access or STATE_REASON feeding, fed = fed, (tuple(t for t in operands(cmd[1:]) if t != "-") if program(cmd[0]) == "cat" else ()) if mode["mode"] != "schema-only": continue verb = program(cmd[0]) + if state_violation(cmd, run_cwd, mode): # also under method-safe-run: only the runner itself changes it + access = access or STATE_REASON + mode["_state_hits"] = mode.get("_state_hits", 0) + 1 if safe: # output stays in the run log; a copy to a readable path still leaks if verb in COPY_VERBS: access = access or judge(cmd, cur, mode, tainted, written)[0] @@ -2053,6 +2618,226 @@ def mcp_access_violation(tool_input, cwd, mode): return None +# Database MCP tools answer queries straight into the context, and PreToolUse cannot filter MCP results, so in +# schema-only a database call passes only as schema inspection. A call is a database call when a whole word of +# its server or tool name is in DB_WORDS, or when a query key anywhere in its arguments holds SQL- or +# Cypher-shaped text. Literature and search servers are exempt. +DB_WORDS = {"postgres", "postgresql", "pg", "mysql", "mariadb", "sqlite", "duckdb", "motherduck", "bigquery", + "snowflake", "databricks", "mssql", "sqlserver", "oracle", "redshift", "athena", "clickhouse", "trino", + "presto", "neo4j", "kusto", "cosmos", "supabase", "mongodb", "mongo", "elasticsearch", "opensearch", + "redis", "dynamodb", "firestore", "cassandra", "influxdb", "airtable", "sql", "database", "db"} +DB_EXEMPT_SERVERS = {"pubmed", "paperclip", "exa", "tavily", "notion", "granola", "vercel"} +DB_QUERY_KEYS = {"sql", "query", "statement", "cypher", "kql", "filter", "pipeline"} +DB_INSPECTION_WORDS = {"list", "describe", "schema", "tables", "columns", "info", "metadata", "indexes"} +# A tool name with one of these words reads rows even when it also has an inspection word (list_records_for_table). +DB_ROW_WORDS = {"row", "rows", "record", "records", "data", "value", "values", "preview", "sample", "head", "tail", + "read", "find", "fetch", "select", "query", "scan", "dump", "export", "search", + "aggregate", "document", "documents", "item", "items", "content", "contents", "run", "exec", + "execute", "count", "distinct", "summarize"} +DB_QUERY_SHAPE = re.compile(r"(?:select|with|match|from|pragma|show|describe)\b", re.IGNORECASE) +DB_LEADING_NOISE = re.compile(r"(?:\s+|\(|--[^\n]*(?:\n|$)|/\*.*?\*/)*", re.DOTALL) +DB_TOKEN = re.compile(r"\s*(?:('(?:[^']|'')*')|(\"(?:[^\"]|\"\")*\"|`[^`]*`)|(\d+(?:\.\d+)?)|([A-Za-z_][\w$]*)|" + r"(<>|!=|<=|>=|[=<>(),.;*])|(\S))", re.DOTALL) +DB_SCHEMA_SOURCES = {("information_schema", "tables"), ("information_schema", "columns")} +DB_DENY = ("a database MCP tool returns query results straight into the model context, and in schema-only only " + "schema inspection passes (a list/describe tool, DESCRIBE, SHOW TABLES|COLUMNS, PRAGMA table_info, or a " + "plain information_schema.tables|columns select); run the query in a script through `method-safe-run` " + "that writes an aggregate table under output/, then print that table with `method-aggregate-read `") + + +def _name_words(name): + return [w for w in re.split(r"[\s_\-.]+", name.lower()) if w] + + +def _db_shaped(text): + """SQL- or Cypher-shaped: the first keyword (after whitespace, parentheses, and comments) opens a statement.""" + return bool(DB_QUERY_SHAPE.match(text, DB_LEADING_NOISE.match(text).end())) + + +# On a tool whose name has no database word, a leading keyword is not enough ("show deploy notes" is a search): +# the text must carry a statement's structure. +DB_STATEMENT = re.compile( + r"\bselect\b[\s\S]*?\bfrom\s+[\w`\"\[.(]|\bwith\s+\w+\s+as\s*\(|\bmatch\s*\([\s\S]*?\)[\s\S]*?\breturn\b|" + r"^\s*pragma\s+\w+|^\s*show\s+(?:tables|columns|databases|schemas|create)\b|^\s*desc(?:ribe)?\s+[\w`\".]+\s*;?\s*$", + re.IGNORECASE) + + +def _db_statement(text): + """Text that is structurally a SQL or Cypher statement, not prose that starts with a SQL keyword.""" + return _db_shaped(text) and bool(DB_STATEMENT.search(text)) + + +def _db_queries(value, key=""): + """Every value held under a query key, found recursively; non-string values (a filter object) included.""" + if key in DB_QUERY_KEYS and not (isinstance(value, str) and not value.strip()): + yield value + elif isinstance(value, dict): + for k, v in value.items(): + yield from _db_queries(v, str(k).lower()) + elif isinstance(value, list): + for v in value: + yield from _db_queries(v, key) + + +def _sql_tokens(text): + """(kind, text) tokens, or None when the text cannot be tokenized or carries a comment.""" + tokens, pos, text = [], 0, text.strip() + while pos < len(text): + match = DB_TOKEN.match(text, pos) + if not match or match.end() == pos: + return None + pos = match.end() + literal, quoted, number, word, punct, other = match.groups() + if other is not None: # `-`, `/`, and anything unexpected: comments and operators never pass + return None + if literal is not None: + if "\\" in literal: # MySQL reads `\'` as an escape, so the statement could end somewhere else + return None + tokens.append(("lit", literal)) + elif number is not None: + tokens.append(("lit", number)) + elif quoted is not None: + tokens.append(("name", quoted[1:-1].replace('""', '"'))) + elif word is not None: + low = word.lower() + tokens.append(("lit", low) if low in ("true", "false", "null") else ("word", low)) + else: + tokens.append(("punct", punct)) + while tokens and tokens[-1] == ("punct", ";"): + tokens.pop() + return tokens + + +def _is_name(token): + return token[0] in ("word", "name") + + +def _qualified(tokens, i): + """A dotted name starting at i: (lowercased parts, next index), or (None, i).""" + if i >= len(tokens) or not _is_name(tokens[i]): + return None, i + parts = [tokens[i][1].lower()] + i += 1 + while i + 1 < len(tokens) and tokens[i] == ("punct", ".") and _is_name(tokens[i + 1]): + parts.append(tokens[i + 1][1].lower()) + i += 2 + return parts, i + + +SQL_RESERVED = {"select", "from", "where", "and", "or", "not", "in", "like", "ilike", "union", "join", "on", "with", + "as", "distinct", "all", "except", "intersect", "lateral", "using", "into", "values", "limit", + "order", "group", "having", "by", "case", "when", "then", "else", "end", "exists", "is"} + + +def _bare(token): + return token[0] == "name" or (token[0] == "word" and token[1] not in SQL_RESERVED) + + +def _where_ok(tokens): + """Column-to-literal comparisons joined by AND/OR: `col = 'x'`, `col LIKE 'x%'`, `col IN ('a', 'b')`.""" + i, n = 0, len(tokens) + while True: + if i >= n or not _bare(tokens[i]): + return False + i += 1 + if i < n and tokens[i] in (("punct", "="), ("punct", "<>"), ("punct", "!="), ("word", "like"), ("word", "ilike")): + if i + 1 >= n or tokens[i + 1][0] != "lit": + return False + i += 2 + elif i < n and tokens[i] == ("word", "in") and i + 1 < n and tokens[i + 1] == ("punct", "("): + i += 2 + while True: + if i >= n or tokens[i][0] != "lit": + return False + i += 1 + if i < n and tokens[i] == ("punct", ","): + i += 1 + continue + break + if i >= n or tokens[i] != ("punct", ")"): + return False + i += 1 + else: + return False + if i == n: + return True + if tokens[i] not in (("word", "and"), ("word", "or")): + return False + i += 1 + + +def db_inspection_statement(text): + """True only for one schema-inspection statement: DESCRIBE , SHOW TABLES|COLUMNS ..., PRAGMA + table_info(), or a select of `*` or bare columns from exactly one information_schema.tables|columns + whose WHERE holds only column-to-literal comparisons. Any function call, join, comma source, CTE, subquery, + UNION, comment, or second statement fails.""" + tokens = _sql_tokens(text) + if not tokens or ("punct", ";") in tokens: + return False + head = tokens[0] + if head == ("word", "describe"): + parts, end = _qualified(tokens, 1) + return bool(parts) and end == len(tokens) and not set(parts) & SQL_RESERVED + if head == ("word", "show"): + return (len(tokens) >= 2 and tokens[1] in (("word", "tables"), ("word", "columns")) + and all(t[0] in ("word", "name", "lit") or t == ("punct", ".") for t in tokens[2:]) + and not any(t[0] == "word" and t[1] in SQL_RESERVED - {"from", "in", "like"} for t in tokens[2:])) + if head == ("word", "pragma"): + return (len(tokens) == 5 and tokens[1] == ("word", "table_info") and tokens[2] == ("punct", "(") + and (_bare(tokens[3]) or tokens[3][0] == "lit") and tokens[4] == ("punct", ")")) + if head != ("word", "select"): + return False + i, n = 1, len(tokens) + if i < n and tokens[i] == ("punct", "*"): + i += 1 + else: + while True: + if i >= n or not _bare(tokens[i]): + return False + i += 1 + if i < n and tokens[i] == ("punct", ","): + i += 1 + continue + break + if i >= n or tokens[i] != ("word", "from"): + return False + parts, i = _qualified(tokens, i + 1) + if not parts or tuple(parts[-2:]) not in DB_SCHEMA_SOURCES or len(parts) > 3: + return False + if i == n: + return True + return tokens[i] == ("word", "where") and _where_ok(tokens[i + 1:]) + + +def mcp_database_violation(tool, tool_input): + """Schema-only: why a database MCP call would return rows, or None for schema inspection and non-database tools.""" + name = tool[len("mcp__"):] + server, _, short = name.rpartition("__") + server = server or short + server_words = set(_name_words(server)) + if server_words & DB_EXEMPT_SERVERS and not server_words & DB_WORDS: # vercel_postgres is a database server + return None + queries = list(_db_queries(tool_input)) + named_db = bool(set(_name_words(name)) & DB_WORDS) + if not (named_db or any(isinstance(q, str) and _db_statement(q) for q in queries)): + return None + if named_db: # a statement under any key (sql_text, q, options.raw) is query text too + queries += [text for _, text in _strings(tool_input) if _db_statement(text)] + command = tool_input.get("command") + if command is not None: # a router tool: `command` names a sub-command, it is not query text + if not (isinstance(command, str) and re.fullmatch(r"[A-Za-z0-9_.\-]+", command)): + return DB_DENY + words = set(_name_words(command)) + if not words & DB_INSPECTION_WORDS or words & DB_ROW_WORDS: + return DB_DENY + if queries: + return None if all(isinstance(q, str) and db_inspection_statement(q) for q in queries) else DB_DENY + if command is not None: + return None + words = set(_name_words(short)) + return None if words & DB_INSPECTION_WORDS and not words & DB_ROW_WORDS else DB_DENY + + HTTP_CLIENTS = {"curl", "wget", "http", "https", "xh"} # Where an HTTP request carries the caller's own contact by convention: credentials, the From header # (RFC 9110: the human user's email), and the User-Agent (polite-pool "mailto:"). An email there is not a patient's. @@ -2103,7 +2888,7 @@ def classify(call, mode): if reason: return {"kind": "egress", "reason": reason} if mode["mode"] == "schema-only": - reason = mcp_access_violation(tool_input, cwd, mode) + reason = mcp_access_violation(tool_input, cwd, mode) or mcp_database_violation(tool, tool_input) return {"kind": "access", "reason": reason} if reason else None return None if tool in ("WebFetch", "WebSearch"): @@ -2118,6 +2903,10 @@ def classify(call, mode): if mode["mode"] != "schema-only": return None reason = access + if tool in ("Write", "Edit", "MultiEdit", "NotebookEdit"): + path = tool_input.get("file_path") or tool_input.get("notebook_path") or "" + if isinstance(path, str) and names_state(path, cwd, mode): + return {"kind": "access", "reason": STATE_REASON} if tool in ("Read", "NotebookRead", "Edit", "MultiEdit", "NotebookEdit"): # edits return a snippet path = tool_input.get("file_path") or tool_input.get("notebook_path") or "" resolved = _resolve(path, cwd) if path else "" @@ -2133,6 +2922,9 @@ def classify(call, mode): reason = "reading a data file returns its values" elif tool == "Grep": reason = grep_tool_violation(tool_input, cwd, mode) + if reason and reason != STATE_REASON: + note = marker_note(mode) + reason = f"{reason}; {note}" if note else reason return {"kind": "access", "reason": reason} if reason else None diff --git a/plugins/methodsmith/scripts/method-safe-run b/plugins/methodsmith/scripts/method-safe-run index 6bc02dd3..d3139a3c 100755 --- a/plugins/methodsmith/scripts/method-safe-run +++ b/plugins/methodsmith/scripts/method-safe-run @@ -2,6 +2,7 @@ """Run a command that may print data values, without showing its output. Usage: method-safe-run -- [args...] + method-safe-run --reconcile Full stdout and stderr go to .methodsmith/runs/-.log in the project; `.methodsmith/runs/` is added to .gitignore when git does not @@ -25,13 +26,62 @@ renv, caches), are not tracked. It refuses to run (exit 2) outside a project: some folder at or above the working directory must hold .methodsmith/ or .git. In schema-only mode the guard requires method-safe-run to run as its own command, so nothing in the same call reads a file before it is recorded. + +Temp files are data too. The command gets its own owner-only (0700) temp +directory, made with mkdtemp in the system temp root (prefix msr-), and +TMPDIR, TMP, and TEMP point at it. Its absolute path is appended to +.methodsmith/runs/temp-roots.txt (one path per line) before the command starts, +so the guard treats it as data; it is deleted when the run finishes, and lines +for directories that no longer exist are pruned when the next run starts. + +While a run is in progress, .methodsmith/runs/active/-.json +marks it (unique per run, so a reused pid never overwrites an unreconciled +marker; JSON keys: pid, pid_start, pgid, host, start, tmp, outputs_lines, +outputs_stamp; start is the run +start on the filesystem clock in ns). A small keeper (this script in a hidden +--keeper mode) leads its own session and process group; it starts the command +in that group only after the marker naming the group is on disk, and touches +the marker every 10 s (recreating it if deleted) while any other member of the +group is alive, so processes that outlive a killed runner keep the run +heartbeating. The runner touches it too. SIGTERM, SIGINT, or SIGHUP is +forwarded to the whole group, which gets 10 s before SIGKILL; after a normal +exit, processes the command left behind get 10 s, then the same SIGTERM/SIGKILL +sequence. Outputs are recorded only once the group is gone, then the temp +directory and the marker are removed. A marker is stale when its runner is gone +(or the pid now belongs to a process with another start time), no member of its +process group is alive, and it was written on this host; an unreadable or +malformed marker is stale once the pid in its name is gone and it has missed +several heartbeats. Each run start, and `method-safe-run --reconcile` (prints +one count line), records the project files a stale run changed between its +start and its last heartbeat (plus 2 s) in outputs.txt and removes the marker. +Appends to outputs.txt and temp-roots.txt are O_APPEND writes under an fcntl +lock. The command's own code could erase those lists, so the runner snapshots +them before the command starts and re-appends any missing line at every +heartbeat and again before recording outputs; an erased entry is missing for at +most one heartbeat interval. At each heartbeat the runner first merges the lists' current +lines into its saved set, so entries other runs record later are kept too. +Meanwhile the guard does not trust the list: outputs.txt exists before the +start, the marker records its line count (outputs_lines) and its [mtime, ctime] +(outputs_stamp) then, and while outputs.txt's stamp differs or the file is gone, +every project file counts as +data until the run finishes. The marker's tmp directory is data whether or not +temp-roots.txt still lists it. + +Environment: METHOD_SAFE_RUN_HEARTBEAT_SECONDS overrides the 10 s heartbeat +interval (tests use a short one). """ +import fcntl import json import os import re +import shutil +import signal +import socket import subprocess import sys +import tempfile +import threading import time # --- identifier index: patterns, normalize, hash, lookup (keep identical across plugin scripts; tested) --- @@ -260,18 +310,434 @@ def changed_files(before, after, since_ns=None): return out +def _read_fd(fd): + os.lseek(fd, 0, os.SEEK_SET) + chunks = [] + while True: + chunk = os.read(fd, 1 << 16) + if not chunk: + return b"".join(chunks).decode("utf-8", errors="replace") + chunks.append(chunk) + + +def append_lines(path, lines): + """Append lines not already in the file: an O_APPEND write under an exclusive fcntl lock. Returns the count added.""" + fd = os.open(path, os.O_RDWR | os.O_APPEND | os.O_CREAT, 0o600) + try: + fcntl.flock(fd, fcntl.LOCK_EX) + known = set(_read_fd(fd).splitlines()) + new = [] + for line in lines: + if line not in known: + known.add(line) + new.append(line) + if new: + os.write(fd, "".join(line + "\n" for line in new).encode("utf-8")) + return len(new) + finally: + os.close(fd) # releases the lock + + +def read_lists(runs): + """The current outputs.txt and temp-roots.txt lines, so a run can put back any its own code erases.""" + saved = {} + for name in ("outputs.txt", "temp-roots.txt"): + try: + with open(os.path.join(runs, name), encoding="utf-8", errors="replace") as fh: + saved[name] = [line for line in fh.read().splitlines() if line] + except OSError: + saved[name] = [] + return saved + + +def list_stamp(runs): + """outputs.txt's [mtime, ctime] in ns, or None: the guard distrusts the list once it differs during the run.""" + try: + st = os.lstat(os.path.join(runs, "outputs.txt")) + except OSError: + return None + return [st.st_mtime_ns, st.st_ctime_ns] + + +def restore_lists(runs, saved): + """Merge the lists' current lines into saved (never replace: the file may already be truncated), then + re-append saved lines the run's code removed. The lists only grow while a run is live.""" + for name, lines in read_lists(runs).items(): + known = set(saved[name]) + saved[name].extend(line for line in lines if line not in known and not known.add(line)) + for name, lines in saved.items(): + if lines: + try: + append_lines(os.path.join(runs, name), lines) + except OSError: + pass + + def record_outputs(runs, changed): """Add written files to runs/outputs.txt; the boundary guard treats them as data. Raster figures are exempt.""" - path = os.path.join(runs, "outputs.txt") + return append_lines(os.path.join(runs, "outputs.txt"), [rel for rel in changed if not rel.lower().endswith(RASTER)]) + + +# --- per-run temp directory and in-progress run markers --- +HEARTBEAT_SECONDS = 10.0 +GRACE_SECONDS = 10.0 # how long a process group gets after SIGTERM (or after the command exits) before the next step +HEARTBEAT_MARGIN_NS = 2 * 10**9 + + +def heartbeat_seconds(): try: - with open(path, encoding="utf-8") as fh: - known = set(fh.read().splitlines()) + value = float(os.environ.get("METHOD_SAFE_RUN_HEARTBEAT_SECONDS", HEARTBEAT_SECONDS)) + except ValueError: + return HEARTBEAT_SECONDS + return value if value > 0 else HEARTBEAT_SECONDS + + +def prune_temp_roots(runs): + """Drop temp-roots.txt lines whose directory no longer exists (in place, under the same lock as appends).""" + path = os.path.join(runs, "temp-roots.txt") + try: + fd = os.open(path, os.O_RDWR) + except OSError: + return + try: + fcntl.flock(fd, fcntl.LOCK_EX) + lines = _read_fd(fd).splitlines() + keep = [line for line in lines if line and os.path.isdir(line)] + if keep != lines: + os.ftruncate(fd, 0) + os.lseek(fd, 0, os.SEEK_SET) + os.write(fd, "".join(line + "\n" for line in keep).encode("utf-8")) + finally: + os.close(fd) + + +def process_start(pid): + """The process start time as ps prints it (whitespace collapsed), or "" when unknown or gone.""" + try: + out = subprocess.run(["ps", "-o", "lstart=", "-p", str(pid)], capture_output=True, text=True, timeout=5, + env={**os.environ, "LC_ALL": "C"}) + except (OSError, subprocess.SubprocessError): + return "" + return " ".join(out.stdout.split()) if out.returncode == 0 else "" + + +def _alive(target, group=False): + """True while a process (or, with group=True, any member of a process group) exists.""" + try: + (os.killpg if group else os.kill)(target, 0) + except PermissionError: + return True + except (OSError, OverflowError, ValueError): + return False + return True + + +def pid_alive(pid): + return _alive(pid) + + +def group_alive(pgid): + return _alive(pgid, group=True) + + +def signal_group(pgid, signum): + try: + os.killpg(pgid, signum) except OSError: - known = set() - new = [rel for rel in changed if rel not in known and not rel.lower().endswith(RASTER)] - if new: - with open(path, "a", encoding="utf-8") as fh: - fh.write("".join(rel + "\n" for rel in new)) + pass + + +def write_marker(path, fields): + """Write the marker atomically (temp file + rename) so a reader never sees half a marker.""" + tmp = os.path.join(os.path.dirname(path), "." + os.path.basename(path) + ".tmp") + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as fh: + json.dump(fields, fh) + os.replace(tmp, path) + + +def marker_is_stale(marker): + """Runner gone (or its pid reused), whole process group gone, same host. Callers handle malformed markers.""" + pid, pgid = marker.get("pid"), marker.get("pgid") + if marker.get("host") != socket.gethostname(): + return False + if pid_alive(pid): + recorded, current = marker.get("pid_start"), process_start(pid) + if not isinstance(recorded, str) or not recorded or not current or recorded == current: + return False # the runner is alive (or we cannot tell): fail closed + return pgid is None or not group_alive(pgid) # pgid None: the runner died before the command started + + +def marker_malformed(marker): + """Unreadable, or a field the staleness test needs has the wrong type.""" + return (not isinstance(marker, dict) or type(marker.get("start")) is not int or type(marker.get("pid")) is not int + or not (marker.get("pgid") is None or type(marker.get("pgid")) is int)) + + +def reconcile(root, runs): + """Record what each stale run changed between its start and its last heartbeat, then remove its marker. + Returns (stale runs reconciled, files newly recorded, markers left in place).""" + active = os.path.join(runs, "active") + try: + names = sorted(n for n in os.listdir(active) if n.endswith(".json") and not n.startswith(".")) + except OSError: + return 0, 0, 0 + stale, recorded, left = 0, 0, 0 + files = None + for name in names: + path = os.path.join(active, name) + try: + st = os.stat(path) + except OSError: + continue + heartbeat_ns = st.st_mtime_ns + try: + with open(path, encoding="utf-8") as fh: + marker = json.load(fh) + except (OSError, ValueError): + marker = None + if marker_malformed(marker): + # Unreadable or malformed: stale once its writer (the pid in -.json) is gone and it has + # missed several heartbeats; the window then runs from its start (or the marker's creation) to its + # last heartbeat. A marker from another host is never stale here. + marker = marker if isinstance(marker, dict) else {} + writer = name[:-5].split("-")[0] + silent = time.time_ns() - heartbeat_ns > 6 * heartbeat_seconds() * 1_000_000_000 + host = marker.get("host") + if (isinstance(host, str) and host != socket.gethostname()) or not ( + writer.isdigit() and silent and not pid_alive(int(writer))): + left += 1 + continue + start = marker.get("start") + if type(start) is not int: + birth = getattr(st, "st_birthtime", None) + start = int(birth * 1e9) if birth else min(st.st_ctime_ns, st.st_mtime_ns) + elif not marker_is_stale(marker): + left += 1 + continue + else: + start = marker["start"] + if files is None: + files, _ = snapshot(root, None) + end = heartbeat_ns + HEARTBEAT_MARGIN_NS + written = [rel for rel, (mtime, _, ctime) in sorted(files.items()) if start <= max(mtime, ctime) <= end] + recorded += record_outputs(runs, written) + tmp = marker.get("tmp") + if isinstance(tmp, str) and os.path.basename(tmp).startswith("msr-"): + shutil.rmtree(tmp, ignore_errors=True) + try: + os.unlink(path) + except FileNotFoundError: + pass + stale += 1 + return stale, recorded, left + + +FORWARDED = (signal.SIGTERM, signal.SIGINT, signal.SIGHUP) + + +def _read_all(fd): + chunks = [] + try: + for chunk in iter(lambda: os.read(fd, 1 << 16), b""): + chunks.append(chunk) + except OSError: + pass + finally: + os.close(fd) + return b"".join(chunks) + + +def _others_in_group(pgid, child): + """True while a live (non-zombie) process other than this one is in process group pgid. Falls back to the + direct child when ps cannot be run.""" + try: + ps = subprocess.Popen(["ps", "-A", "-o", "pid=,pgid=,stat="], stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, text=True, env={**os.environ, "LC_ALL": "C"}) + out, _ = ps.communicate(timeout=5) + except (OSError, subprocess.SubprocessError): + return child.poll() is None + if ps.returncode != 0: + return child.poll() is None + skip = {str(os.getpid()), str(ps.pid)} + for line in out.splitlines(): + parts = line.split() + if len(parts) >= 3 and parts[1] == str(pgid) and parts[0] not in skip and not parts[2].startswith("Z"): + return True + return False + + +def keeper(argv): + """Hidden `--keeper -- ` mode: the session and group leader of a run. + + Blocks until the runner sends the marker path and contents on the go pipe (sent only after the marker with + pgid = this pid is on disk; EOF without them means the runner died first, so nothing runs), starts the + command in this process group, writes its exit code to the status pipe, and touches the marker every + heartbeat (recreating it if deleted) while any other member of the group is alive. Then it exits with the + command's code. Forwarded signals are caught, so the keeper outlives a SIGTERM to the group. + """ + for signum in FORWARDED: + signal.signal(signum, lambda s, f: None) # a handler, not SIG_IGN: the command gets default dispositions + go_fd, status_fd, cmd = int(argv[0]), int(argv[1]), argv[3:] + try: + go = json.loads(_read_all(go_fd)) + path, marker = go["path"], go["marker"] + except (ValueError, KeyError, TypeError): + os.close(status_fd) + return 125 + + def report(code): + try: + os.write(status_fd, str(code).encode()) + except OSError: + pass + os.close(status_fd) + + def touch(): + try: + os.utime(path) + except FileNotFoundError: + try: + os.makedirs(os.path.dirname(path), exist_ok=True) + write_marker(path, marker) + except OSError: + pass + except OSError: + pass + + try: + child = subprocess.Popen(cmd) + except OSError as exc: + sys.stderr.write(f"method-safe-run: could not start the command ({type(exc).__name__})\n") + report(127) + return 127 + pgid, beat, code = os.getpgrp(), heartbeat_seconds(), None + next_beat, next_check = time.monotonic() + beat, 0.0 + while True: + if code is None: + try: + code = child.wait(timeout=0.05) + report(code) + except subprocess.TimeoutExpired: + pass + now = time.monotonic() + if code is not None and now >= next_check: + if not _others_in_group(pgid, child): + touch() # a last heartbeat covers the final writes + break + next_check = now + min(beat, 0.2) + if now >= next_beat: + touch() + next_beat = now + beat + if code is not None: + time.sleep(0.05) + return code if code >= 0 else 128 - code + + +def run_command(cmd, env, marker_path, marker, on_beat=lambda: None): + """Run cmd under a keeper (see keeper()) that leads its own session and process group, heartbeat the marker, + and return (code, stdout, stderr, group_gone, signaled) once the whole group has exited. SIGTERM, SIGINT, + and SIGHUP are forwarded to the group.""" + state = {"proc": None, "signal": None, "at": None} + + def forward(signum, frame): + if state["signal"] is None: + state["signal"], state["at"] = signum, time.monotonic() + if state["proc"] is not None: + signal_group(state["proc"].pid, signum) + + for signum in FORWARDED: + signal.signal(signum, forward) + go_r, go_w = os.pipe() + status_r, status_w = os.pipe() + try: + proc = subprocess.Popen([sys.executable, "-I", os.path.realpath(__file__), "--keeper", str(go_r), + str(status_w), "--", *cmd], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, env=env, start_new_session=True, pass_fds=(go_r, status_w)) + except OSError as exc: + for fd in (go_w, status_r): + os.close(fd) + return 127, b"", f"method-safe-run: could not start the command ({type(exc).__name__})\n".encode(), True, None + finally: + os.close(go_r) + os.close(status_w) + state["proc"] = proc + pgid = proc.pid # start_new_session: the keeper leads its own group + marker["pgid"] = pgid + try: + write_marker(marker_path, marker) + except OSError: + pass + try: # the keeper starts the command only after this: the marker on disk already names its group + os.write(go_w, json.dumps({"path": marker_path, "marker": marker}).encode()) + except OSError: + pass + os.close(go_w) + if state["signal"] is not None: + signal_group(pgid, state["signal"]) + + buffers = {"out": [], "err": []} + status = {} + + def drain(stream, key): + for chunk in iter(lambda: stream.read1(1 << 16), b""): + buffers[key].append(chunk) + + def wait_status(): + text = _read_all(status_r).decode("ascii", errors="replace").strip() + if re.fullmatch(r"-?\d+", text): + status["code"] = int(text) + status["done"] = True + + readers = [threading.Thread(target=drain, args=(proc.stdout, "out"), daemon=True), + threading.Thread(target=drain, args=(proc.stderr, "err"), daemon=True)] + status_reader = threading.Thread(target=wait_status, daemon=True) + for reader in readers + [status_reader]: + reader.start() + beat = heartbeat_seconds() + next_beat = time.monotonic() + beat + term_at = kill_at = give_up_at = None + exited_at = None + while True: + done = proc.poll() is not None + now = time.monotonic() + if exited_at is None and (status.get("done") or done): # the command exited (or the keeper died) + exited_at = now + if done and not group_alive(pgid): + break + if term_at is None: + if state["signal"] is not None: + term_at = state["at"] + elif exited_at is not None and now - exited_at >= GRACE_SECONDS: + signal_group(pgid, signal.SIGTERM) # the command exited but left processes behind + term_at = now + if term_at is not None and kill_at is None and now - term_at >= GRACE_SECONDS: + signal_group(pgid, signal.SIGKILL) + kill_at = now + if kill_at is not None and now - kill_at >= GRACE_SECONDS: + give_up_at = now # an unkillable member: finalize, but keep the marker + break + if now >= next_beat: + try: + os.utime(marker_path) + except OSError: + pass + on_beat() + next_beat = now + beat + try: + proc.wait(timeout=0.05) + except subprocess.TimeoutExpired: + pass + if done: + time.sleep(0.05) + for reader in readers + [status_reader]: + reader.join(timeout=2) + code = status.get("code", proc.poll()) # the keeper's report first: it is the command's own status + if code is None: + code = -signal.SIGKILL + if code < 0: # killed by a signal: the shell's 128 + N, not a wrapped negative exit status + code = 128 - code + return code, b"".join(buffers["out"]), b"".join(buffers["err"]), give_up_at is None, state["signal"] def changes(changed, before, after, root, index, capped): @@ -388,10 +854,13 @@ def legacy_refusal(tool, start): def main(argv): - if "--" not in argv or argv.index("--") == len(argv) - 1: + if argv[:1] == ["--keeper"] and len(argv) >= 4 and argv[3] == "--": + return keeper(argv[1:]) + reconcile_only = argv == ["--reconcile"] + if not reconcile_only and ("--" not in argv or argv.index("--") == len(argv) - 1): print(__doc__.strip()) return 2 - cmd = argv[argv.index("--") + 1:] + cmd = [] if reconcile_only else argv[argv.index("--") + 1:] refused = legacy_refusal("method-safe-run", os.getcwd()) if refused: return refused @@ -404,16 +873,33 @@ def main(argv): runs = os.path.join(root, ".methodsmith", "runs") os.makedirs(runs, exist_ok=True) ensure_ignored(root, ".methodsmith/runs/", ".methodsmith/runs/probe.log") + prune_temp_roots(runs) + stale, recorded, left = reconcile(root, runs) + if reconcile_only: + print(f"method-safe-run: reconciled {stale} stale run{'' if stale == 1 else 's'}, recorded {recorded} " + f"file{'' if recorded == 1 else 's'} as run outputs; {left} run marker{'' if left == 1 else 's'} " + "still active or from another host.") + return 0 name = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()) + f"-{os.getpid()}.log" log_path = os.path.join(runs, name) before, capped = snapshot(root) - since_ns = run_start_ns(runs) if capped else None + append_lines(os.path.join(runs, "outputs.txt"), []) # exists before the start, so any later change is a change + run_start = run_start_ns(runs) + since_ns = run_start if capped else None + active = os.path.join(runs, "active") + os.makedirs(active, exist_ok=True) + tmp = tempfile.mkdtemp(prefix="msr-") + os.chmod(tmp, 0o700) + append_lines(os.path.join(runs, "temp-roots.txt"), [os.path.abspath(tmp)]) + saved = read_lists(runs) # includes this run's temp dir + marker_path = os.path.join(active, f"{os.getpid()}-{run_start}.json") # unique per run, even on pid reuse + marker = {"pid": os.getpid(), "pid_start": process_start(os.getpid()), "pgid": None, + "host": socket.gethostname(), "start": run_start, "tmp": os.path.abspath(tmp), + "outputs_lines": len(saved["outputs.txt"]), "outputs_stamp": list_stamp(runs)} + write_marker(marker_path, marker) + env = {**os.environ, "TMPDIR": tmp, "TMP": tmp, "TEMP": tmp} start = time.monotonic() - try: - proc = subprocess.run(cmd, stdin=subprocess.DEVNULL, capture_output=True) - code, out, err = proc.returncode, proc.stdout, proc.stderr - except OSError as exc: - code, out, err = 127, b"", f"method-safe-run: could not start the command ({type(exc).__name__})\n".encode() + code, out, err, group_gone, signaled = run_command(cmd, env, marker_path, marker, lambda: restore_lists(runs, saved)) duration = time.monotonic() - start fd = os.open(log_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(fd, "wb") as fh: @@ -423,7 +909,14 @@ def main(argv): index = find_index(root) after, _ = snapshot(root, None) # always complete: the run may push the project past the cap written = changed_files(before, after, since_ns) + restore_lists(runs, saved) record_outputs(runs, written) + if group_gone: # recorded first, so the marker covers every write until outputs.txt does + shutil.rmtree(tmp, ignore_errors=True) + try: + os.unlink(marker_path) + except FileNotFoundError: + pass changed = changes(written, before, after, root, index, capped) print("Files created or modified:" if changed else "Files created or modified: none") for line in changed[:MAX_LISTED]: @@ -441,7 +934,7 @@ def main(argv): if withheld: print(f" {withheld} line{'' if withheld == 1 else 's'} withheld; full stderr in " f"{os.path.relpath(log_path, root)}") - return code + return 128 + signaled if signaled is not None else code if __name__ == "__main__": diff --git a/tests/data-boundary-guard.test.ts b/tests/data-boundary-guard.test.ts index baf24feb..b2fe7955 100644 --- a/tests/data-boundary-guard.test.ts +++ b/tests/data-boundary-guard.test.ts @@ -702,3 +702,117 @@ describe("schema-only: searches and MCP tools that slipped past the access check expectAll(project(APPROVED), "allow", [["mcp__filesystem__read_text_file", { path: "My Data/a.csv" }]]) }) }) + +describe("schema-only: database MCP tools return rows into the context", () => { + const SELECT_ALL = "SELECT * FROM patients" + + test("row-returning database calls deny; the reason routes to method-safe-run and method-aggregate-read", () => { + const root = project(SCHEMA_ONLY) + const denied = verdicts(root, [ + ["mcp__postgres__query", { sql: SELECT_ALL }], + ["mcp__postgres__query", { sql: "select column_name from information_schema.columns where table_name='x' UNION SELECT ssn FROM p" }], + ["mcp__pg__q", { sql: "SELECT * FROM pg_stats" }], + ["mcp__duckdb__run", { query: "SUMMARIZE t" }], + ["mcp__sqlite__read_rows", { table: "t" }], + ["mcp__duckdb__preview_table", { table: "t" }], + ["mcp__postgres__get_table_data", { table: "t" }], + ["mcp__postgres__query", { sql: "SELECT pg_read_file('data/cohort.csv') AS column_name FROM information_schema.tables" }], + ["mcp__duckdb__run", { query: "SELECT * FROM information_schema.tables, read_csv('data/cohort.csv')" }], + ["mcp__mongodb__find", { collection: "patients", filter: {} }], + ["mcp__Azure_MCP_Server__cosmos", { command: "database_list", parameters: { query: "SELECT * FROM c" } }], + ["mcp__mydb__exec", { params: { statement: "SELECT * FROM t" } }], + ["mcp__neo4j__run", { query: "MATCH (p:Patient) RETURN p" }], + ]) + for (const v of denied) expect(v).toEqual({ tool: v.tool, input: v.input, decision: "deny", kind: "access" }) + const message = runGuard(root, "mcp__postgres__query", { sql: SELECT_ALL }) + expect(message.decision).toBe("deny") + expect(message.reason).toContain("method-safe-run") + expect(message.reason).toContain("method-aggregate-read") + for (const fragment of [SELECT_ALL, "patients"]) expect(message.stdout).not.toContain(fragment) + }) + + test("on a database-named tool, a statement under any key is inspected", () => { + const root = project(SCHEMA_ONLY) + expectAll(root, "deny", [ + ["mcp__postgres__query", { sql_text: SELECT_ALL }], + ["mcp__postgres__query", { q: "select * from patients" }], + ["mcp__duckdb__describe_table", { table: "t", options: { raw: "SELECT name, dob FROM patients" } }], + ]) + expectAll(root, "allow", [ + ["mcp__postgres__inspect", { q: "SHOW TABLES" }], + ["mcp__duckdb__describe_table", { table: "t", note: "select a table to describe" }], + ]) + }) + + test("an exempt server word does not exempt a server that also names a database", () => { + const root = project(SCHEMA_ONLY) + expectAll(root, "deny", [ + ["mcp__vercel_postgres__query", { sql: SELECT_ALL }], + ["mcp__notion-sqlite__run", { query: SELECT_ALL }], + ]) + expectAll(root, "allow", [ + ["mcp__claude_ai_Vercel__list_projects", { query: "select the production project" }], + ["mcp__claude_ai_Paperclip__sql", { query: "SELECT title FROM papers" }], + ]) + }) + + test("search tools without a database name keep prose queries that start with a SQL keyword", () => { + const root = project(SCHEMA_ONLY) + expectAll(root, "allow", [ + ["mcp__claude_ai_Slack__slack_search_public", { query: "show deploy notes from last week" }], + ["mcp__claude_ai_Google_Drive__search_files", { query: "select committee minutes" }], + ["mcp__claude_ai_Gmail__search_threads", { query: "from: the IRB about describe study" }], + ]) + expectAll(root, "deny", [["mcp__mydb__exec", { params: { statement: "select name, dob from patients" } }]]) + }) + + test("the R2 statement shape is strict: functions, joins, CTEs, subqueries, and unions deny", () => { + const root = project(SCHEMA_ONLY) + const q = (sql: string): [string, Record] => ["mcp__postgres__query", { sql }] + expectAll(root, "deny", [ + q("WITH x AS (SELECT * FROM patients) SELECT column_name FROM information_schema.columns"), + q("SELECT column_name FROM information_schema.columns WHERE table_name IN (SELECT name FROM patients)"), + q("SELECT column_name FROM information_schema.columns c JOIN patients p ON true"), + q("SELECT column_name FROM information_schema.columns WHERE table_name = lower('X')"), + q("SELECT column_name FROM information_schema.columns; SELECT * FROM patients"), + q("SELECT column_name FROM patients"), + q("SELECT count(*) FROM information_schema.tables"), + q("PRAGMA table_info(t); SELECT * FROM t"), + q("SHOW TABLES; SELECT * FROM t"), + q("DESCRIBE SELECT * FROM t"), + q("SELECT * FROM information_schema.columns WHERE table_name = 'x' -- trailing comment"), + q("SELECT * FROM information_schema.columns WHERE table_name = 'x\\' AND table_name = ' UNION SELECT ssn FROM p -- '"), + q("SELECT * FROM information_schema.columns WHERE table_name = 'x' OR 1 = 1"), + q("SHOW TABLES FROM (SELECT * FROM t)"), + ]) + expectAll(root, "allow", [ + q("select column_name from information_schema.columns where table_name='x'"), + q("SELECT table_name, table_schema FROM information_schema.tables WHERE table_schema = 'public' AND table_type LIKE 'BASE%'"), + q("SELECT * FROM information_schema.columns WHERE table_name IN ('a', 'b') OR table_name = 'c';"), + q("DESCRIBE t"), + q("SHOW TABLES"), + q("SHOW COLUMNS FROM t"), + q("PRAGMA table_info(t)"), + ]) + }) + + test("schema inspection, literature tools, and approved projects stay allowed", () => { + const root = project(SCHEMA_ONLY) + expectAll(root, "allow", [ + ["mcp__duckdb__list_tables", {}], + ["mcp__duckdb__describe_table", { table: "t" }], + ["mcp__Azure_MCP_Server__cosmos", { command: "database_list", parameters: {} }], + ["mcp__claude_ai_Paperclip__sql", { query: "SELECT title FROM papers" }], + ["mcp__pubmed__pubmed_search_articles", { query: "select sepsis outcomes ICU" }], + ["mcp__claude_ai_Notion__notion-query-data-sources", { query: "x" }], + ["mcp__pubmed-mcp-server__pubmed_search_articles", { query: "sepsis bundle compliance mortality cohort" }], + ]) + for (const config of [APPROVED, "phi_environment:\n mode: no-sensitive-data\n"]) { + expectAll(project(config), "allow", [ + ["mcp__postgres__query", { sql: SELECT_ALL }], + ["mcp__sqlite__read_rows", { table: "t" }], + ["mcp__mongodb__find", { collection: "patients", filter: {} }], + ]) + } + }) +}) diff --git a/tests/data-boundary-limits.test.ts b/tests/data-boundary-limits.test.ts index a23084ff..97c753a8 100644 --- a/tests/data-boundary-limits.test.ts +++ b/tests/data-boundary-limits.test.ts @@ -1,7 +1,8 @@ import { describe, expect, test } from "bun:test" -import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, utimesSync, writeFileSync } from "fs" +import { appendFileSync, chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "fs" +import os from "os" import path from "path" -import { APPROVED, SCHEMA_ONLY, bash, expectAll, guard, helper, pluginRoot, project, py, runGuard, tempDir, verdicts } from "./data-boundary-harness" +import { APPROVED, SCHEMA_ONLY, bash, expectAll, guard, helper, pluginRoot, project, py, runGuard, tempDir, tempRoots, verdicts } from "./data-boundary-harness" const safeRun = path.join(pluginRoot, "scripts", "method-safe-run") const indexer = path.join(pluginRoot, "scripts", "method-identifier-index") @@ -231,6 +232,135 @@ describe("limit 1a: agent-written scripts that read data (schema-only)", () => { expectAll(root, "allow", [["Bash", bash("R --version")], ["Bash", bash("R -f analysis/clean.R")]]) expectAll(launchProject(APPROVED), "allow", [["Bash", bash("ipython analysis/run.py")], ["Bash", bash("R -f analysis/run.R")]]) }) + + // Code that runs another file or module: literal targets are followed and scanned, the rest denied (R7, R8). + function sourceProject(config = SCHEMA_ONLY) { + const root = project(config) + withFile(root, "R/x.R", "x <- c(1, 2, 3)\nprint(mean(x))\n") + withFile(root, "R/bad.R", "d <- read.csv('data/cohort.csv')\nprint(d)\n") + withFile(root, "s.py", "print(1 + 1)\n") + withFile(root, "pkg/__init__.py", "") + withFile(root, "pkg/ok.py", "print('ok')\n") + withFile(root, "pkg/bad.py", "import pandas as pd\nprint(pd.read_csv('data/cohort.csv'))\n") + mkdirSync(path.join(root, "sub"), { recursive: true }) + return root + } + const calls = (commands: string[]) => commands.map((c) => ["Bash", bash(c)] as [string, Record]) + const DYNAMIC_SOURCE_DENIES = [ + `Rscript -e 'source(file.path("R","bad.R"))'`, + `Rscript -e 'source(paste0("R/", step, ".R"))'`, + `Rscript -e 'invisible(lapply(list.files("R", full.names=TRUE), source))'`, + `Rscript -e 'f<-"R/x.R"' -e 'source(f)'`, + `python3 -c "exec(open(p).read())"`, + `Rscript -e 'sys.source(f)'`, + `Rscript -e 'eval(parse(f))'`, + `Rscript -e 'eval(parse(file = f))'`, + `python3 -c "exec(compile(open(p).read(), p, 'exec'))"`, + `python3 -c "import importlib; importlib.import_module(m)"`, + `python3 -c "exec(Path(p).read_text())"`, + `python3 -c "import runpy; runpy.run_module(name)"`, + `python3 -c "import runpy; runpy.run_module('pkg.bad')"`, + `Rscript -e 'source("R/missing.R")'`, + `Rscript -e 'setwd("sub"); source("R/x.R")'`, + ] + + test("inline code that runs a file whose target cannot be resolved, or reads data, is denied (R7, R8)", () => { + const root = sourceProject() + expectAll(root, "deny", calls(DYNAMIC_SOURCE_DENIES)) + const reason = runGuard(root, "Bash", bash(`Rscript -e 'source(paste0("R/", step, ".R"))'`)).reason + expect(reason).toContain("method-safe-run") + const results = py(DYNAMIC_SOURCE_DENIES.map((c) => ({ fn: "classify" as const, call: { cwd: root, tool_name: "Bash", tool_input: bash(c) } }))) + for (const [i, result] of results.entries()) { + const text = JSON.stringify(result) + expect({ command: DYNAMIC_SOURCE_DENIES[i], named: text.includes("method-safe-run"), leaked: ["Zed", "Testperson", "FAKE0001"].some((v) => text.includes(v)) }) + .toEqual({ command: DYNAMIC_SOURCE_DENIES[i], named: true, leaked: false }) + } + }) + + test("inline code that runs a statically resolvable clean file is followed and allowed (R8)", () => { + const root = sourceProject() + expectAll(root, "allow", calls([ + `Rscript -e 'source(file.path("R","x.R"))'`, + `Rscript -e 'source(file="R/x.R")'`, + `Rscript -e 'source(here::here("R","x.R"))'`, + `python3 -c "import runpy; runpy.run_path('s.py')"`, + `python3 -c "import runpy; runpy.run_module('pkg.ok')"`, + ])) + }) + + test("scanned script files follow literal sourced scripts and deny unresolvable ones (R7, R8)", () => { + const root = sourceProject() + withFile(root, "analysis/count.R", "df <- data.frame(source = c('a', 'b', 'a'))\nprint(dplyr::count(df, source))\n") + withFile(root, "analysis/main.R", "fs <- list.files('R', full.names = TRUE)\nfor (f in fs) source(f)\n") + withFile(root, "analysis/follow-bad.R", "source(\"R/bad.R\")\n") + withFile(root, "analysis/follow-ok.R", "source(\"R/x.R\")\n") + expectAll(root, "allow", calls(["Rscript analysis/count.R", "Rscript analysis/follow-ok.R"])) + expectAll(root, "deny", calls(["Rscript analysis/main.R", "Rscript analysis/follow-bad.R"])) + expect(runGuard(root, "Bash", bash("Rscript analysis/main.R")).reason).toContain("method-safe-run") + }) + + test("extensionless and shebang scripts get the run-a-file check in the interpreter's or shebang's language", () => { + const root = sourceProject() + withFile(root, "analysis/runner", "#!/usr/bin/env python3\nimport runpy, sys\nrunpy.run_path(sys.argv[1])\n") + withFile(root, "analysis/runall", "#!/usr/bin/env Rscript\nfs <- list.files('R', full.names = TRUE)\nfor (f in fs) source(f)\n") + withFile(root, "analysis/plain", "import runpy\nrunpy.run_path('s.py')\n") + chmodSync(path.join(root, "analysis", "runner"), 0o755) + chmodSync(path.join(root, "analysis", "runall"), 0o755) + expectAll(root, "deny", calls(["./analysis/runner x", "python3 analysis/runner x", "Rscript analysis/runall", "./analysis/runall"])) + expectAll(root, "allow", calls(["python3 analysis/plain"])) + expectAll(sourceProject(APPROVED), "allow", calls(["python3 s.py"])) + }) + + test("Python literals that start with f are literals, not f-strings", () => { + const root = sourceProject() + withFile(root, "features.py", "print('features')\n") + expectAll(root, "allow", calls([ + `python3 -c "import runpy; runpy.run_path('features.py')"`, + `python3 -c "__import__('functools')"`, + ])) + expectAll(root, "deny", calls([`python3 -c "import runpy; runpy.run_path(f'{x}.py')"`])) + }) + + test("R parse() of a file is followed, and str2expression/str2lang of computed text is denied", () => { + const root = sourceProject() + expectAll(root, "deny", calls([ + `Rscript -e 'for (e in parse("R/bad.R")) eval(e)'`, + `Rscript -e 'lapply(parse("R/bad.R"), eval)'`, + `Rscript -e 'eval(str2expression(readLines(f)))'`, + `Rscript -e 'eval(str2lang(code))'`, + `Rscript -e 'exprs <- parse(f); for (e in exprs) eval(e)'`, + ])) + expectAll(root, "allow", calls([ + `Rscript -e 'parse(text = "1 + 1")'`, + `Rscript -e 'for (e in parse("R/x.R")) eval(e)'`, + `Rscript -e 'eval(str2lang("1 + 1"))'`, + ])) + }) + + test("an import path changed at run time makes an unresolved literal module name unresolvable", () => { + const root = sourceProject() + withFile(root, "lib/hidden.py", "import pandas as pd\nprint(pd.read_csv('data/cohort.csv'))\n") + withFile(root, "analysis/load.py", "import sys, importlib\nsys.path.insert(0, 'lib')\nimportlib.import_module('hidden')\n") + expectAll(root, "deny", calls([ + `python3 -c "import sys, importlib; sys.path.insert(0, 'lib'); importlib.import_module('hidden')"`, + `python3 -c "import sys; sys.path.append('lib'); __import__('hidden')"`, + `python3 -c "import sys, runpy; sys.path += ['lib']; runpy.run_module('hidden')"`, + `python3 -c "import site, importlib; site.addsitedir('lib'); importlib.import_module('hidden')"`, + `python3 -c "import os, importlib; os.environ['PYTHONPATH'] = 'lib'; importlib.import_module('hidden')"`, + "python3 analysis/load.py", + ])) + expectAll(root, "allow", calls([ + `python3 -c "import importlib; importlib.import_module('numpy')"`, + `python3 -c "import sys, importlib; sys.path.insert(0, 'lib'); importlib.import_module('pkg.ok')"`, + ])) + }) + + test("unresolvable run-a-file code is allowed under the plugin's method-safe-run and in approved projects", () => { + expectAll(sourceProject(), "allow", calls([`${safeRun} -- Rscript -e 'source(f)'`])) + const approved = sourceProject(APPROVED) + withFile(approved, "analysis/main.R", "fs <- list.files('R', full.names = TRUE)\nfor (f in fs) source(f)\n") + expectAll(approved, "allow", calls([...DYNAMIC_SOURCE_DENIES.filter((c) => !c.includes("bad")), "Rscript analysis/main.R"])) + }) }) describe("wildcards and find patterns (schema-only)", () => { @@ -323,6 +453,12 @@ describe("wildcards and find patterns (schema-only)", () => { }) describe("limit 1b: method-safe-run keeps script output out of the context", () => { + test("a command killed by a signal exits 128 + the signal number", () => { + const { code, out } = runSafe(project(SCHEMA_ONLY), "sh", "-c", "kill -TERM $$") + expect(code).toBe(143) + expect(out).toContain("exit code: 143") + }) + test("runs the command, logs stdout and stderr locally, and prints only the exit code and log path", () => { const root = withFile(project(SCHEMA_ONLY), "analysis/leak.py", "import sys\nprint('Zed Testperson FAKE0001')\nprint('to stderr', file=sys.stderr)\nsys.exit(3)\n") @@ -331,7 +467,7 @@ describe("limit 1b: method-safe-run keeps script output out of the context", () expect(out).toContain("exit code: 3") expect(out).not.toContain("Zed Testperson") expect(out).not.toContain("FAKE0001") - const logs = readdirSync(path.join(root, ".methodsmith", "runs")) + const logs = readdirSync(path.join(root, ".methodsmith", "runs")).filter((f) => f.endsWith(".log")) expect(logs).toHaveLength(1) expect(logs[0]).toMatch(/^\d{8}T\d{6}Z-\d+\.log$/) expect(out).toContain(`.methodsmith/runs/${logs[0]}`) @@ -502,6 +638,588 @@ describe("limit 1b: method-safe-run keeps script output out of the context", () ]) expectAll(root, "allow", [["Bash", bash("ls .methodsmith/runs")], ["Read", { file_path: ".methodsmith/config.local.yaml" }]]) }) + + // --- per-run temp directory and in-progress run markers (R4-R6) --- + const runsDir = (root: string) => path.join(root, ".methodsmith", "runs") + const listFile = (file: string) => (existsSync(file) ? readFileSync(file, "utf8").split("\n").filter(Boolean) : []) + const outputsOf = (root: string) => listFile(path.join(runsDir(root), "outputs.txt")) + const tempRootsOf = (root: string) => listFile(path.join(runsDir(root), "temp-roots.txt")) + const markersOf = (root: string) => { + const dir = path.join(runsDir(root), "active") + return existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith(".json")) : [] + } + const markerJson = (root: string, name: string) => JSON.parse(readFileSync(path.join(runsDir(root), "active", name), "utf8")) + // macOS reports /var/... and /private/var/... for the same directory. + const norm = (p: string) => p.trim().replace(/^\/private(?=\/)/, "") + const underTempRoot = (root: string, p: string) => tempRootsOf(root).some((r) => norm(p).startsWith(norm(r) + "/") || norm(p) === norm(r)) + function runStdout(root: string) { + const log = readdirSync(runsDir(root)).filter((f) => f.endsWith(".log")).sort().at(-1)! + const text = readFileSync(path.join(runsDir(root), log), "utf8") + return text.slice(text.indexOf("== stdout ==\n") + 13, text.indexOf("\n== stderr ==")) + } + const FAST_ENV = { ...process.env, METHOD_SAFE_RUN_HEARTBEAT_SECONDS: "0.2" } + const startSafe = (cwd: string, ...cmd: string[]) => + Bun.spawn([safeRun, "--", ...cmd], { cwd, env: FAST_ENV, stdout: "pipe", stderr: "pipe" }) + async function waitFor(check: () => boolean, ms = 10000) { + const end = Date.now() + ms + while (!check()) { + if (Date.now() > end) throw new Error("timed out waiting for the run") + await Bun.sleep(50) + } + } + const killGroup = (pgid: number) => Bun.spawnSync(["kill", "-KILL", "--", `-${pgid}`]) + const deadPid = () => { + const proc = Bun.spawnSync(["true"]) + return proc.pid + } + + test("a child's tempfile.mkstemp() file lies under a temp dir registered in runs/temp-roots.txt", () => { + const root = project(SCHEMA_ONLY) + const { code } = runSafe(root, "python3", "-c", + "import os, tempfile\nfd, p = tempfile.mkstemp()\nos.write(fd, b'synthetic')\nos.close(fd)\nprint(p)") + expect(code).toBe(0) + const made = runStdout(root).trim() + expect(made).not.toBe("") + expect(underTempRoot(root, path.dirname(made))).toBe(true) + }) + + test.skipIf(!Bun.which("Rscript"))("Rscript tempdir() under the runner lies under a registered temp root", () => { + const root = project(SCHEMA_ONLY) + const { code } = runSafe(root, "Rscript", "-e", "cat(tempdir())") + expect(code).toBe(0) + expect(underTempRoot(root, runStdout(root))).toBe(true) + }, 30000) + + test("the run's temp dir is owner-only (0700), set as TMPDIR/TMP/TEMP, and removed after a normal finish", () => { + const root = project(SCHEMA_ONLY) + const { code } = runSafe(root, "python3", "-c", + "import os, tempfile\nd = tempfile.gettempdir()\nprint(oct(os.stat(d).st_mode & 0o777))\nprint(d)\n" + + "print(os.environ['TMPDIR'].rstrip('/') == os.environ['TMP'].rstrip('/') == os.environ['TEMP'].rstrip('/'))") + expect(code).toBe(0) + const [mode, dir, same] = runStdout(root).trim().split("\n") + expect(mode).toBe("0o700") + expect(same).toBe("True") + expect(path.basename(dir)).toStartWith("msr-") + expect(tempRootsOf(root).map(norm)).toContain(norm(dir)) + expect(existsSync(dir)).toBe(false) + expect(markersOf(root)).toEqual([]) + }) + + test("a SIGTERM to the runner is forwarded to the child; its outputs are recorded and its marker removed", async () => { + const root = withFile(project(SCHEMA_ONLY), "analysis/term.py", + "import signal, sys, time\n" + + "def stop(signum, frame):\n open('results/got_term.txt', 'w').write('synthetic\\n')\n sys.exit(0)\n" + + "signal.signal(signal.SIGTERM, stop)\nopen('results/partial.txt', 'w').write('synthetic\\n')\ntime.sleep(60)\n") + mkdirSync(path.join(root, "results")) + const proc = startSafe(root, "python3", "analysis/term.py") + await waitFor(() => existsSync(path.join(root, "results", "partial.txt")) && markersOf(root).length === 1) + const marker = markerJson(root, markersOf(root)[0]) + expect(marker.pid).toBe(proc.pid) + expect(typeof marker.pid_start).toBe("string") + expect(marker.host).toBe(os.hostname()) + expect(typeof marker.start).toBe("number") + proc.kill("SIGTERM") + await proc.exited + expect(existsSync(path.join(root, "results", "got_term.txt"))).toBe(true) + expect(outputsOf(root)).toEqual(expect.arrayContaining([path.join("results", "got_term.txt"), path.join("results", "partial.txt")])) + expect(markersOf(root)).toEqual([]) + expect(await new Response(proc.stdout).text()).not.toContain("synthetic") + }, 30000) + + // A writer in the run's process group that waits (at most 20 s) for a release file, then writes results/late.txt. + const WRITER = "import os, signal, sys, time\nsignal.signal(signal.SIGTERM, signal.SIG_IGN)\n" + + "open('results/writer_ready.txt', 'w').write('synthetic\\n')\ndeadline = time.time() + 20\n" + + "while not os.path.exists(sys.argv[1]) and time.time() < deadline:\n time.sleep(0.05)\n" + + "open('results/late.txt', 'w').write('synthetic\\n')\n" + const groupAlive = (pgid: number) => Bun.spawnSync(["kill", "-0", "--", `-${pgid}`], { stderr: "ignore" }).exitCode === 0 + + test("a background writer that outlives the SIGTERM keeps the marker until it exits, and its late file is recorded", async () => { + const root = project(SCHEMA_ONLY) + withFile(root, "analysis/writer.py", WRITER) + withFile(root, "analysis/bg.py", + "import subprocess, sys, time\nsubprocess.Popen([sys.executable, 'analysis/writer.py', sys.argv[1]])\ntime.sleep(60)\n") + mkdirSync(path.join(root, "results")) + const release = path.join(tempDir(), "release") + const proc = startSafe(root, "python3", "analysis/bg.py", release) + let pgid = 0 + try { + await waitFor(() => existsSync(path.join(root, "results", "writer_ready.txt")) && markersOf(root).length === 1 + && typeof markerJson(root, markersOf(root)[0]).pgid === "number") + pgid = markerJson(root, markersOf(root)[0]).pgid + proc.kill("SIGTERM") + await Bun.sleep(800) + expect(proc.exitCode).toBeNull() + expect(markersOf(root)).toHaveLength(1) + writeFileSync(release, "") + await proc.exited + expect(outputsOf(root)).toContain(path.join("results", "late.txt")) + expect(markersOf(root)).toEqual([]) + } finally { + writeFileSync(release, "") + proc.kill("SIGKILL") + if (pgid) killGroup(pgid) + } + }, 30000) + + test("a child that outlives a SIGKILLed runner keeps the run heartbeating; reconcile records its late write", async () => { + const root = project(SCHEMA_ONLY) + withFile(root, "analysis/writer.py", WRITER) + withFile(root, "analysis/bg.py", "import subprocess, sys\nsubprocess.Popen([sys.executable, 'analysis/writer.py', sys.argv[1]])\n") + mkdirSync(path.join(root, "results")) + const release = path.join(tempDir(), "release") + const proc = startSafe(root, "python3", "analysis/bg.py", release) + let pgid = 0 + try { + await waitFor(() => existsSync(path.join(root, "results", "writer_ready.txt")) && markersOf(root).length === 1 + && typeof markerJson(root, markersOf(root)[0]).pgid === "number") + pgid = markerJson(root, markersOf(root)[0]).pgid + proc.kill("SIGKILL") + await proc.exited + await Bun.sleep(2600) // past the runner's last heartbeat plus the 2 s margin + writeFileSync(release, "") + await waitFor(() => existsSync(path.join(root, "results", "late.txt")) && !groupAlive(pgid)) + const rec = Bun.spawnSync([safeRun, "--reconcile"], { cwd: root, env: FAST_ENV }) + expect(rec.stdout.toString()).toMatch(/reconciled 1 stale run/) + expect(outputsOf(root)).toContain(path.join("results", "late.txt")) + expect(markersOf(root)).toEqual([]) + } finally { + writeFileSync(release, "") + proc.kill("SIGKILL") + if (pgid) killGroup(pgid) + } + }, 30000) + + test("a marker is unique per run: a new runner that reuses an old pid leaves that pid's marker alone", () => { + const root = project(SCHEMA_ONLY) + const active = path.join(runsDir(root), "active") + mkdirSync(active, { recursive: true }) + const planted = `{"pid": 1, "pid_start": "", "pgid": null, "host": "elsewhere.invalid", "start": 1}` + const proc = Bun.spawnSync(["sh", "-c", `printf '%s' '${planted}' > .methodsmith/runs/active/$$.json; exec "$0" -- python3 -c "import os, glob; print(sorted(os.path.basename(p) for p in glob.glob('.methodsmith/runs/active/*.json')))"`, safeRun], + { cwd: root, env: FAST_ENV }) + expect(proc.exitCode).toBe(0) + const names = markersOf(root) + expect(names).toHaveLength(1) + expect(JSON.parse(readFileSync(path.join(active, names[0]), "utf8")).host).toBe("elsewhere.invalid") + expect(runStdout(root)).toMatch(/'\d+-\d+\.json'/) + }) + + test("a marker with a malformed pgid is reconciled once its writer is gone and it stopped heartbeating", () => { + const root = project(SCHEMA_ONLY) + const active = path.join(runsDir(root), "active") + mkdirSync(active, { recursive: true }) + const dead = deadPid() + const file = path.join(active, `${dead}-1.json`) + writeFileSync(file, `{"pid": ${dead}, "pid_start": "", "pgid": "abc", "host": ${JSON.stringify(os.hostname())}, "start": 1}`) + const old = new Date(Date.now() - 600_000) + utimesSync(file, old, old) + const proc = Bun.spawnSync([safeRun, "--reconcile"], { cwd: root, env: { ...process.env, METHOD_SAFE_RUN_HEARTBEAT_SECONDS: "1" } }) + expect(proc.stdout.toString()).toMatch(/reconciled 1 stale run/) + expect(existsSync(file)).toBe(false) + }) + + // A run whose runner and process group were SIGKILLed: the marker stays behind. + async function crashedRun(root: string) { + withFile(root, "analysis/slow.py", "import time\nopen('results/written.txt', 'w').write('synthetic\\n')\ntime.sleep(60)\n") + mkdirSync(path.join(root, "results"), { recursive: true }) + const proc = startSafe(root, "python3", "analysis/slow.py") + await waitFor(() => existsSync(path.join(root, "results", "written.txt")) && markersOf(root).length === 1 + && typeof markerJson(root, markersOf(root)[0]).pgid === "number") + await Bun.sleep(500) // at least one heartbeat after the write + const { pgid } = markerJson(root, markersOf(root)[0]) + proc.kill("SIGKILL") + killGroup(pgid) + await proc.exited + await Bun.sleep(200) + expect(markersOf(root)).toHaveLength(1) + } + + test("after a SIGKILL, --reconcile records the dead run's file but not a file edited after its last heartbeat", async () => { + const root = project(SCHEMA_ONLY) + await crashedRun(root) + expect(outputsOf(root)).not.toContain(path.join("results", "written.txt")) + await Bun.sleep(2600) // past the last heartbeat plus the 2 s margin + writeFileSync(path.join(root, "results", "later.txt"), "synthetic later\n") + const proc = Bun.spawnSync([safeRun, "--reconcile"], { cwd: root }) + const out = proc.stdout.toString() + proc.stderr.toString() + expect(proc.exitCode).toBe(0) + expect(out).toMatch(/reconciled 1 stale run/) + expect(out.trim().split("\n")).toHaveLength(1) + expect(outputsOf(root)).toContain(path.join("results", "written.txt")) + expect(outputsOf(root)).not.toContain(path.join("results", "later.txt")) + expect(markersOf(root)).toEqual([]) + }, 30000) + + test("a dead run's marker is reconciled by the next run: its written file is recorded and the marker removed", async () => { + const root = project(SCHEMA_ONLY) + await crashedRun(root) + const { code, out } = runSafe(root, "true") + expect(code).toBe(0) + expect(out).not.toMatch(/reconcil/i) + expect(outputsOf(root)).toContain(path.join("results", "written.txt")) + expect(markersOf(root)).toEqual([]) + }, 30000) + + test("staleness: a mismatched start time is stale; a live runner, a live group, or another host is not", async () => { + const root = project(SCHEMA_ONLY) + const active = path.join(runsDir(root), "active") + mkdirSync(active, { recursive: true }) + const now = BigInt(Date.now()) * 1000000n + const lstart = (pid: number) => Bun.spawnSync(["ps", "-o", "lstart=", "-p", String(pid)], { env: { ...process.env, LC_ALL: "C" } }) + .stdout.toString().trim().replace(/\s+/g, " ") + const group = Bun.spawn(["python3", "-c", "import os, time\nos.setsid()\ntime.sleep(30)\n"]) + await Bun.sleep(400) + const marker = (name: string, pid: number, pidStart: string, pgid: number, host: string) => + writeFileSync(path.join(active, name), + `{"pid": ${pid}, "pid_start": ${JSON.stringify(pidStart)}, "pgid": ${pgid}, "host": ${JSON.stringify(host)}, "start": ${now}}`) + try { + marker("1.json", process.pid, "Thu Jan 1 00:00:00 1970", deadPid(), os.hostname()) // pid reused: stale + marker("2.json", process.pid, lstart(process.pid), deadPid(), os.hostname()) // runner alive + marker("3.json", deadPid(), "Thu Jan 1 00:00:00 1970", group.pid, os.hostname()) // group alive + marker("4.json", deadPid(), "Thu Jan 1 00:00:00 1970", deadPid(), "elsewhere.invalid") // another host + const proc = Bun.spawnSync([safeRun, "--reconcile"], { cwd: root }) + expect(proc.exitCode).toBe(0) + expect(proc.stdout.toString()).toMatch(/reconciled 1 stale run/) + expect(markersOf(root).sort()).toEqual(["2.json", "3.json", "4.json"]) + } finally { + group.kill("SIGKILL") + } + }, 30000) + + test("a run's own code cannot erase earlier outputs.txt or temp-roots.txt entries", () => { + const root = project(SCHEMA_ONLY) + mkdirSync(runsDir(root), { recursive: true }) + writeFileSync(path.join(runsDir(root), "outputs.txt"), "results/earlier.csv\n") + const kept = mkdtempSync(path.join(os.tmpdir(), "msr-kept-")) + writeFileSync(path.join(runsDir(root), "temp-roots.txt"), `${kept}\n`) + // Erase both lists, wait (up to 10 s) until the runner has put both entries back, then copy what the + // guard would see mid-run. + const code = "import shutil, sys, time\nruns = '.methodsmith/runs/'\nfor f in ('outputs.txt', 'temp-roots.txt'):\n" + + " open(runs + f, 'w').close()\nend = time.time() + 10\n" + + "while not ('results/earlier.csv' in open(runs + 'outputs.txt').read() and sys.argv[1] in open(runs + 'temp-roots.txt').read()):\n" + + " if time.time() > end: break\n time.sleep(0.05)\n" + + "shutil.copy(runs + 'outputs.txt', 'seen-outputs.txt')\nshutil.copy(runs + 'temp-roots.txt', 'seen-temp-roots.txt')\n" + const proc = Bun.spawnSync([safeRun, "--", "python3", "-c", code, kept], { cwd: root, env: FAST_ENV }) + expect(proc.exitCode).toBe(0) + expect(listFile(path.join(root, "seen-outputs.txt"))).toContain("results/earlier.csv") + expect(listFile(path.join(root, "seen-temp-roots.txt"))).toContain(kept) + expect(outputsOf(root)).toContain("results/earlier.csv") + expect(tempRootsOf(root)).toContain(kept) + rmSync(kept, { recursive: true, force: true }) + }) + + test("a live first run in a fresh project leaves unrelated files readable until its code touches outputs.txt", async () => { + const root = withFile(project(SCHEMA_ONLY), "notes/before.txt", "synthetic note\n") + await Bun.sleep(2200) // older than the runner's 2 s start margin, so only the list rule can deny it + // The child waits for go, then erases outputs.txt and idles; until then it changes nothing. + const code = "import os, time\nend = time.time() + 10\n" + + "while not os.path.exists('go') and time.time() < end: time.sleep(0.05)\n" + + "open('.methodsmith/runs/outputs.txt', 'w').close()\n" + + "while not os.path.exists('done') and time.time() < end: time.sleep(0.05)\n" + const run = startSafe(root, "python3", "-c", code) + await waitFor(() => markersOf(root).length === 1) + expectAll(root, "allow", [["Read", { file_path: "notes/before.txt" }]]) // outputs.txt was created inside the start margin + const list = path.join(runsDir(root), "outputs.txt") + const stamp = statSync(list, { bigint: true }).ctimeNs + writeFileSync(path.join(root, "go"), "") + await waitFor(() => statSync(list, { bigint: true }).ctimeNs !== stamp) + expectAll(root, "deny", [["Read", { file_path: "notes/before.txt" }]]) + writeFileSync(path.join(root, "done"), "") + expect(await run.exited).toBe(0) + }) + + test("an output another run records after this run started survives this run's code erasing the list", async () => { + const root = project(SCHEMA_ONLY) + mkdirSync(runsDir(root), { recursive: true }) + // The child waits for go, erases outputs.txt, then idles past several heartbeats. + const code = "import os, time\nend = time.time() + 10\n" + + "while not os.path.exists('go') and time.time() < end: time.sleep(0.05)\n" + + "open('.methodsmith/runs/outputs.txt', 'w').close()\ntime.sleep(1)\n" + const run = startSafe(root, "python3", "-c", code) + await waitFor(() => markersOf(root).length === 1) + await Bun.sleep(500) // past a heartbeat, so the runner has already re-read the list once + appendFileSync(path.join(runsDir(root), "outputs.txt"), "results/b-summary\n") // another run finished + await Bun.sleep(500) // and past another, so this run has seen the new entry + writeFileSync(path.join(root, "go"), "") + expect(await run.exited).toBe(0) + expect(outputsOf(root)).toContain("results/b-summary") // extensionless: only outputs.txt marks it as data + }) + + test("two concurrent runs: both written files land in outputs.txt and both temp dirs in temp-roots.txt", async () => { + const root = project(SCHEMA_ONLY) + mkdirSync(path.join(root, "results")) + const writer = (name: string) => `import tempfile, time\nopen('results/${name}.txt', 'w').write(tempfile.gettempdir())\ntime.sleep(1.5)\n` + const a = startSafe(root, "python3", "-c", writer("a")) + const b = startSafe(root, "python3", "-c", writer("b")) + expect(await a.exited).toBe(0) + expect(await b.exited).toBe(0) + expect(outputsOf(root)).toEqual(expect.arrayContaining([path.join("results", "a.txt"), path.join("results", "b.txt")])) + const dirs = ["a", "b"].map((n) => norm(readFileSync(path.join(root, "results", `${n}.txt`), "utf8"))) + expect(dirs[0]).not.toBe(dirs[1]) + expect(tempRootsOf(root).map(norm)).toEqual(expect.arrayContaining(dirs)) + expect(markersOf(root)).toEqual([]) + }, 30000) +}) + +describe("limit 1c: the guard reads method-safe-run temp roots and in-progress run markers (R4, R5)", () => { + const runs = (root: string) => path.join(root, ".methodsmith", "runs") + const psField = (field: string, pid: number) => + Bun.spawnSync(["ps", "-o", `${field}=`, "-p", String(pid)], { env: { ...process.env, LC_ALL: "C" } }) + .stdout.toString().trim().replace(/\s+/g, " ") + const deadPid = () => Bun.spawnSync(["true"]).pid + // The filesystem clock, read the way the runner reads it (a file's ctime), from outside the project. + function fsNow() { + const probe = path.join(tempDir(), "clock") + writeFileSync(probe, "") + return statSync(probe, { bigint: true }).ctimeNs + } + function marker(root: string, name: string, fields: { pid: number; pid_start: string; pgid: number | null; host: string; start: bigint }, + extra: { tmp?: string; outputs_lines?: number } = {}) { + const dir = path.join(runs(root), "active") + mkdirSync(dir, { recursive: true }) + const more = extra.outputs_lines === undefined ? "" : `, "outputs_lines": ${extra.outputs_lines}` + writeFileSync(path.join(dir, name), `{"pid": ${fields.pid}, "pid_start": ${JSON.stringify(fields.pid_start)}, ` + + `"pgid": ${fields.pgid}, "host": ${JSON.stringify(fields.host)}, "start": ${fields.start}, ` + + `"tmp": ${JSON.stringify(extra.tmp ?? "/nonexistent/msr-x")}${more}}`) + } + const liveMarker = (start: bigint) => ({ + pid: process.pid, pid_start: psField("lstart", process.pid), pgid: Number(psField("pgid", process.pid)), host: os.hostname(), start, + }) + const pause = () => Bun.sleepSync(30) + // notes/ and R/ and incoming/ exist before the run starts; results/out.txt is written after it. + function runProject(config = SCHEMA_ONLY) { + const root = project(config) + for (const dir of ["results", "notes", "R", "incoming"]) mkdirSync(path.join(root, dir)) + writeFileSync(path.join(root, "notes", "before.txt"), "synthetic note\n") + writeFileSync(path.join(root, "R", "x.R"), "x <- 1\n") + pause() + const start = fsNow() + pause() + return { root, start } + } + function writeAfterStart(root: string) { + writeFileSync(path.join(root, "results", "out.txt"), "FAKE0001 synthetic row\n") + } + + test("a file in a registered temp root is data: Read and cat deny in schema-only, allow when approved", () => { + for (const [config, decision] of [[SCHEMA_ONLY, "deny"], [APPROVED, "allow"]] as const) { + const root = project(config) + const tmp = mkdtempSync(path.join(os.tmpdir(), "msr-")) + tempRoots.push(tmp) + writeFileSync(path.join(tmp, "rows.txt"), "FAKE0001 synthetic row\n") + mkdirSync(runs(root), { recursive: true }) + writeFileSync(path.join(runs(root), "temp-roots.txt"), `${tmp}\n`) // as mkdtemp returns it, not realpath'd + const viaReal = path.join(realpathSync(tmp), "rows.txt") + expectAll(root, decision, [ + ["Read", { file_path: path.join(tmp, "rows.txt") }], + ["Read", { file_path: viaReal }], + ["Bash", bash(`cat ${path.join(tmp, "rows.txt")}`)], + ["Bash", bash(`cat ${viaReal}`)], + ]) + } + }) + + test("the pre-rename runs folder's temp-roots.txt is read too", () => { + const root = project(SCHEMA_ONLY) + const tmp = tempDir("msr-") + writeFileSync(path.join(tmp, "rows.txt"), "FAKE0001 synthetic row\n") + mkdirSync(path.join(root, ".ce-datascience", "runs"), { recursive: true }) // rebrand:keep + writeFileSync(path.join(root, ".ce-datascience", "runs", "temp-roots.txt"), `${tmp}\n`) // rebrand:keep + expectAll(root, "deny", [["Read", { file_path: path.join(tmp, "rows.txt") }]]) + }) + + test("with a live run marker, a file changed after its start is data; one last changed before it is not", () => { + const { root, start } = runProject() + writeAfterStart(root) + marker(root, `${process.pid}.json`, liveMarker(start)) + expectAll(root, "deny", [ + ["Read", { file_path: "results/out.txt" }], + ["Bash", bash("cat results/out.txt")], + ]) + expectAll(root, "allow", [["Read", { file_path: "notes/before.txt" }], ["Bash", bash("cat notes/before.txt")]]) + const denied = runGuard(root, "Read", { file_path: "results/out.txt" }) + expect(denied.reason).toContain("still in progress") + expect(denied.reason).not.toContain("--reconcile") + expect(denied.reason).not.toContain("FAKE0001") + }) + + test("during a live run, a file renamed into the project and a script edited in place are data", () => { + const { root, start } = runProject() + const outside = path.join(tempDir(), "r.txt") + writeFileSync(outside, "FAKE0001 synthetic row\n") + utimesSync(outside, new Date(2020, 0, 1), new Date(2020, 0, 1)) // an old mtime survives the rename + marker(root, `${process.pid}.json`, liveMarker(start)) + renameSync(outside, path.join(root, "incoming", "r.txt")) + writeFileSync(path.join(root, "R", "x.R"), "x <- 2\n") + expectAll(root, "deny", [ + ["Read", { file_path: "incoming/r.txt" }], + ["Read", { file_path: "R/x.R" }], + ["Bash", bash("cat R/x.R")], + ]) + }) + + test("during a live run, an outputs.txt changed since the run started makes every project file data", () => { + const root = project(SCHEMA_ONLY) + for (const dir of ["results", "notes"]) mkdirSync(path.join(root, dir)) + writeFileSync(path.join(root, "results", "earlier.txt"), "FAKE0001,synthetic\n") + writeFileSync(path.join(root, "notes", "before.txt"), "synthetic note\n") + mkdirSync(runs(root), { recursive: true }) + writeFileSync(path.join(runs(root), "outputs.txt"), "results/earlier.txt\n") + pause() + const start = fsNow() + pause() + marker(root, `${process.pid}.json`, liveMarker(start), { outputs_lines: 1 }) + // Untouched since the run started: the list is trusted, the earlier output is data, other files read. + expectAll(root, "deny", [["Read", { file_path: "results/earlier.txt" }]]) + expectAll(root, "allow", [["Read", { file_path: "notes/before.txt" }]]) + writeFileSync(path.join(runs(root), "outputs.txt"), "") // the run's own code erased it + expectAll(root, "deny", [ + ["Read", { file_path: "results/earlier.txt" }], + ["Bash", bash("cat results/earlier.txt")], + ["Read", { file_path: "notes/before.txt" }], + ]) + rmSync(path.join(runs(root), "outputs.txt")) + expectAll(root, "deny", [["Read", { file_path: "results/earlier.txt" }]]) + // Empty at the start, but another run may record outputs into it later: any change is untrusted too. + marker(root, `${process.pid}.json`, liveMarker(start), { outputs_lines: 0 }) + expectAll(root, "deny", [["Read", { file_path: "notes/before.txt" }]]) + // A marker from before outputs_lines existed keeps the per-file rule. + marker(root, `${process.pid}.json`, liveMarker(start)) + expectAll(root, "allow", [["Read", { file_path: "notes/before.txt" }]]) + }) + + test("a live run's own temp directory is data even when temp-roots.txt no longer lists it", () => { + const { root, start } = runProject() + const tmp = mkdtempSync(path.join(os.tmpdir(), "msr-")) + tempRoots.push(tmp) + writeFileSync(path.join(tmp, "rows.txt"), "FAKE0001 synthetic row\n") + marker(root, `${process.pid}.json`, liveMarker(start), { tmp }) + writeFileSync(path.join(runs(root), "temp-roots.txt"), "") + expectAll(root, "deny", [ + ["Read", { file_path: path.join(tmp, "rows.txt") }], + ["Bash", bash(`cat ${path.join(realpathSync(tmp), "rows.txt")}`)], + ]) + expectAll(project(APPROVED), "allow", [["Read", { file_path: path.join(tmp, "rows.txt") }]]) + }) + + test("a stale marker denies and names --reconcile; another host's marker denies without offering it", () => { + const stale = runProject() + writeAfterStart(stale.root) + marker(stale.root, "123.json", { pid: deadPid(), pid_start: "", pgid: deadPid(), host: os.hostname(), start: stale.start }) + const staleDeny = runGuard(stale.root, "Read", { file_path: "results/out.txt" }) + expect(staleDeny.decision).toBe("deny") + expect(staleDeny.reason).toContain("method-safe-run --reconcile") + + const foreign = runProject() + writeAfterStart(foreign.root) + marker(foreign.root, "123.json", { pid: deadPid(), pid_start: "", pgid: deadPid(), host: "elsewhere", start: foreign.start }) + const foreignDeny = runGuard(foreign.root, "Read", { file_path: "results/out.txt" }) + expect(foreignDeny.decision).toBe("deny") + expect(foreignDeny.reason).toContain("another host") + expect(foreignDeny.reason).not.toContain("--reconcile") + expectAll(foreign.root, "allow", [["Read", { file_path: "notes/before.txt" }]]) + }) + + test("an unreadable marker counts as an active run starting when the marker was created (fail closed)", () => { + const { root } = runProject() + const old = new Date(Date.now() - 3600_000) + utimesSync(path.join(root, "notes", "before.txt"), old, old) // also sets its ctime to now + mkdirSync(path.join(runs(root), "active"), { recursive: true }) + pause() // coarse filesystem clocks (Linux): keep that ctime strictly before the marker's creation + writeFileSync(path.join(runs(root), "active", "77.json"), "{not json") + writeFileSync(path.join(runs(root), "active", ".77.json.tmp"), "{not json") // half-written, ignored by name + withFile(root, "results/after.csv", "group,n\na,120\n") + expectAll(root, "deny", [["Read", { file_path: "results/after.csv" }]]) + expectAll(root, "allow", [["Read", { file_path: "notes/before.txt" }]]) + }) + + test("--reconcile clears an unreadable marker once its writer is gone and it stopped heartbeating", () => { + const { root } = runProject() + const marker = path.join(runs(root), "active", "999999.json") + mkdirSync(path.dirname(marker), { recursive: true }) + writeFileSync(marker, "{not json") + const old = new Date(Date.now() - 600_000) + utimesSync(marker, old, old) + const proc = Bun.spawnSync([safeRun, "--reconcile"], { cwd: root, env: { ...process.env, METHOD_SAFE_RUN_HEARTBEAT_SECONDS: "1" } }) + expect(proc.exitCode).toBe(0) + expect(existsSync(marker)).toBe(false) + }) + + test("in an approved project a marker changes nothing", () => { + const { root, start } = runProject(APPROVED) + writeAfterStart(root) + marker(root, `${process.pid}.json`, liveMarker(start)) + expectAll(root, "allow", [["Read", { file_path: "results/out.txt" }], ["Bash", bash("cat results/out.txt")]]) + }) + + test("schema-only commands and edits cannot remove, move, truncate, or write the boundary state", () => { + const root = project(SCHEMA_ONLY) + mkdirSync(path.join(runs(root), "active"), { recursive: true }) + writeFileSync(path.join(runs(root), "temp-roots.txt"), "/nonexistent/msr-x\n") + marker(root, "123.json", { pid: deadPid(), pid_start: "", pgid: null, host: "elsewhere", start: 10n ** 19n }) // starts later than any file here + const deny: Array<[string, Record]> = [ + ["Bash", bash("rm .methodsmith/runs/active/123.json")], + ["Bash", bash(`${safeRun} -- rm .methodsmith/runs/active/123.json`)], + ["Bash", bash("rm -f .methodsmith/runs/active/*.json")], + ["Bash", bash("rm -rf .methodsmith/runs")], + ["Bash", bash("unlink .methodsmith/runs/active/123.json")], + ["Bash", bash("mv .methodsmith/runs/active/123.json /tmp/")], + ["Bash", bash("cp /dev/null .methodsmith/runs/temp-roots.txt")], + ["Bash", bash("echo > .methodsmith/runs/temp-roots.txt")], + ["Bash", bash(": > .methodsmith/runs/temp-roots.txt")], + ["Bash", bash("echo x >> .methodsmith/runs/temp-roots.txt")], + ["Bash", bash("echo x | tee .methodsmith/runs/temp-roots.txt")], + ["Bash", bash("sed -i '' -e d .methodsmith/runs/temp-roots.txt")], + ["Bash", bash("truncate -s 0 .methodsmith/runs/temp-roots.txt")], + ["Bash", bash("rm .methodsmith/runs/outputs.txt")], + ["Bash", bash(": > .methodsmith/runs/outputs.txt")], + ["Bash", bash("find .methodsmith/runs -name outputs.txt -delete")], + ["Write", { file_path: ".methodsmith/runs/outputs.txt", content: "" }], + ["Bash", bash("touch .methodsmith/runs/active/123.json")], + ["Bash", bash("find .methodsmith/runs/active -name '*.json' -delete")], + ["Bash", bash("find . -type f -exec rm {} +")], + ["Bash", bash("cd .methodsmith/runs && rm temp-roots.txt")], + ["Bash", bash("bash -c 'rm .methodsmith/runs/active/123.json'")], + ["Bash", bash(`${safeRun} -- bash -c 'rm .methodsmith/runs/active/123.json'`)], + ["Bash", bash(`${safeRun} -- sh -c 'cat notes.txt; echo x > .methodsmith/runs/temp-roots.txt'`)], + ["Bash", bash(`${safeRun} -- bash -c "eval 'rm -f .methodsmith/runs/active/*.json'"`)], + ["Monitor", bash("rm .methodsmith/runs/active/123.json")], + ["Write", { file_path: ".methodsmith/runs/temp-roots.txt", content: "" }], + ["Write", { file_path: ".methodsmith/runs/active/9.json", content: "{}" }], + ["Edit", { file_path: ".methodsmith/runs/temp-roots.txt", old_string: "x", new_string: "" }], + ] + expectAll(root, "deny", deny) + expectAll(root, "allow", [ + ["Bash", bash("ls .methodsmith/runs/active")], + ["Bash", bash(`${safeRun} --reconcile`)], + ["Bash", bash("rm -f notes.txt")], + ["Bash", bash("rm -f .methodsmith/runs/*.log")], + ["Bash", bash("find . -name '*.pyc' -delete")], + ["Bash", bash("cp src/load.py src/load_copy.py")], + ["Write", { file_path: "analysis/new.py", content: "print(1)\n" }], + ]) + const reason = runGuard(root, "Bash", bash("rm .methodsmith/runs/active/123.json")).reason + expect(reason).toContain("method-safe-run") + const approved = project(APPROVED) + expectAll(approved, "allow", [["Bash", bash("rm .methodsmith/runs/active/123.json")], + ["Write", { file_path: ".methodsmith/runs/temp-roots.txt", content: "" }]]) + }) + + test("with 20 run markers present a guard decision stays under 1 s (R9)", () => { + const { root, start } = runProject() + writeAfterStart(root) + const live = liveMarker(start) + for (let i = 0; i < 20; i++) { + marker(root, `${1000 + i}.json`, i % 2 ? live : { pid: deadPid(), pid_start: "", pgid: deadPid(), host: os.hostname(), start }) + } + const t0 = performance.now() + const result = runGuard(root, "Read", { file_path: "results/out.txt" }) + const elapsed = performance.now() - t0 + expect(result.decision).toBe("deny") + expect(elapsed).toBeLessThan(1000) + const t1 = performance.now() + expect(runGuard(root, "Bash", bash("cat notes/before.txt results/out.txt R/x.R src/load.py")).decision).toBe("deny") + expect(performance.now() - t1).toBeLessThan(1000) + }) }) describe("limit 2a: method-identifier-index stores salted hashes of identifier values", () => {