Metadata-Version: 2.3
Name: porifera
Version: 0.2.0
Summary: PORIFERA: PHP code rewriting instrumentation for expression in AST
Requires-Dist: php-parser-py>=1.2.6
Requires-Dist: filelock>=3.29
Requires-Dist: typing-extensions>=4.0
Requires-Python: >=3.10
Description-Content-Type: text/markdown

# PORIFERA: Php cOde Rewriting Instrumentation For ExpRession in Ast

> Porifera is named for the sponges (phylum *Porifera*): water streams through their pores and exits unchanged while nutrients are filtered out — here, PHP execution streams through probe-injected pores in the AST and continues unchanged while expression values are filtered out.

PHP AST instrumentation library. Captures runtime values of arbitrary expressions without debuggers or manual logging.

## Install

```bash
# via uv
uv add porifera

# or via pip
pip install porifera
```

Requires Python >=3.10.

## Usage

```python
from php_parser_py import Parser
import porifera

ast = Parser().parse_file("path/to/project/index.php")

# targets: {ast_node_id: probe_label}
# - key: node ID from php-parser-py AST (e.g. "a1b2c3d4_5")
# - value: label string written to probe output for identification
targets = {
    "a1b2c3d4_5": "user_query",
    "e5f6g7h8_12": "config_value",
}

with porifera.session(targets, ast) as sess:
    for probe in sess.installed:      # targets that received a probe
        print(probe.expr_key, probe.node_id)

    # Run the PHP project (HTTP request or CLI). Probes append to
    # .porifera_data_<timestamp>.jsonl in the project root.

    data = sess.collect()             # {expr_key: ProbeData}
    for key, pd in data.items():
        print(key, pd.values, pd.value_types, pd.timestamps)
# Deinstrument and output cleanup guaranteed on exit
```

Porifera automatically selects the probe method based on AST context:

**Expression Wrap** — target is in a safe rvalue position:

```php
// before
$row = $db->query($sql);
// after: wrap the expression inline
$row = __porifera_probe_a1b2("user_query", $db->query($sql));
```

**Statement Probe** — target is in a lvalue, reference, or language-construct position:

```php
// before: $x is an assignment target (lvalue)
$x = getPrice();
// after: standalone probe inserted after the statement
$x = getPrice();
__porifera_probe_a1b2("price", $x);
```

```php
// before: $arr is passed to by-ref function
sort($arr);
// after: probe before the call captures value without breaking reference
__porifera_probe_a1b2("arr", $arr);
sort($arr);
```

The probe returns the original value transparently and logs it to `.porifera_data_<timestamp>.jsonl` with fields: `key`, `value`, `value_type`, `ts`.

**Custom write strategy** — every write into the project root (instrumented source, `require_once` injection, runtime helper, backup restore) goes through `write_strategy`. The default writes a temp file, `os.replace`s it over the target, and fsyncs the file and parent directory — correct for any ordinary filesystem. Inject your own when the deployment needs different post-write visibility, e.g. an OrbStack bind mount that caches the inode and serves stale bytes to the container after a rename:

```python
import os
from pathlib import Path
import porifera

def same_inode_write(path: Path, content: bytes) -> None:
    # Overwrite in place (no os.replace) so the inode is preserved and the
    # container reads the new bytes immediately.
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o644)
    try:
        os.write(fd, content)
        os.fsync(fd)
    finally:
        os.close(fd)

with porifera.session(targets, ast, write_strategy=same_inode_write) as sess:
    sess.collect()
```

`write_strategy` is `Callable[[Path, bytes], None]` — inject a plain function, no porifera type to import.

## API

**`porifera.session(targets, project_ast, output_dir=None, *, tolerant=False, write_strategy=..., invalidation_trigger=None)`** — Context manager. Instruments targets on enter, deinstruments on exit. Yields `Session`. `tolerant=True` records uninstrumentable targets in `skipped` instead of raising. `write_strategy` defaults to the built-in atomic replace. `invalidation_trigger` runs the opcache invalidation script inside the PHP runtime; `None` skips invalidation, correct when `opcache.validate_timestamps` is on.

**`porifera.Session`** — `installed: list[InstalledProbe]`, `skipped: list[SkippedTarget]`, `modified_files: list[Path]`, and `collect() -> dict[str, ProbeData]`.

**`porifera.InstalledProbe`** — `node_id: str`, `expr_key: str`.

**`porifera.SkippedTarget`** — `node_id: str`, `expr_key: str`, `reason: str`. Non-empty only with `tolerant=True`.

**`porifera.ProbeData`** — `values: list[object]`, `value_types: list[str]`, `timestamps: list[float]`. One element per probe invocation.

**`porifera.recover(root)`** — Roll back a crashed session's residual snapshot on a root. Recovers only from `.porifera_backup/`; if the backup is lost while probes remain, the root is not recoverable and this returns `[]` without raising. Sole standalone restore path — also the defensive cleanup for stale probes from a prior failed run.

**`porifera.is_declaration_site(ast, node)`** — `True` if the node is a name-binding declaration (parameter, closure use, foreach binding, catch variable). Use to filter candidates before building `targets`.

**`porifera.InstrumentResult`** — `installed`, `skipped`, `modified_files`; returned by the layer-1 `InstrumentationManager.instrument()` for custom lifecycles.

**`porifera.InstrumentationError`** / **`porifera.DeinstrumentationError`** — Raised on failure.

**`porifera.WriteStrategy`** — `Callable[[Path, bytes], None]`. Type of the `write_strategy` injection hook; every write into the project root goes through it.

**`porifera.InvalidationTrigger`** — `Callable[[Path], None]`. Type of the `invalidation_trigger` hook; runs a generated script inside the PHP runtime holding the opcache.

See [design.md](docs/design.md) for full specifications.

## Documentation

- [Concepts](docs/concept.md) — problem context, core terminology, data flow
- [Design](docs/design.md) — class structure, session API, exception types
- [Algorithm](docs/spec.md) — wrap safety classification, statement probe placement
- [Implementation](docs/impl.md) — php-parser-py API, developer notes

## For Agents

Agent-consumable documentation index at `docs/llms.txt` (llmstxt.org format).

## Citation

If you use this project in academic work, please cite our paper. BibTeX (placeholder until the paper is released):

```bibtex
@misc{beluga_placeholder,
  title  = {{TODO: paper title — not yet released}},
  author = {{TODO: authors}},
  year   = {{TODO}},
  note   = {Paper not yet released. Citation entry will be updated on publication.}
}
```

## License

GPL-2.0 — see [LICENSE](LICENSE).
