Skip to content

Latest commit

 

History

History
150 lines (114 loc) · 7.52 KB

fc_entry.md

File metadata and controls

150 lines (114 loc) · 7.52 KB

fc_entry.py

Revision: 1 Last modified: 2026-12-04T19:00:00Z

Overview

Primarily a library you import. It has one small CLI (ast-gate, see below) but its main purpose is to be the single shared CLI-entry primitive for the three spec-004 orchestration tools handoff.py, limit_class.py and custody_sweep.py.

It exists because one defect family — "exit status or --out truth corrupted by stream I/O or an unguarded edge" — came back four times in a row. Each round patched a syntactic proxy (first per-site write guards, then the catch set, then stderr prints, then argparse and shutdown flush), and because the three tools were near-forks, every round had to patch the same defect in three places. This module is the deliberate stop (§11.4.250): it is now the only place any of those three tools writes to stdout or stderr at all, and that is enforced mechanically rather than by convention (check_no_bare_io, wired as an AST gate in the regression tests).

The concrete failure it prevents: a tool computes the correct verdict, then print()s it to a pipe whose reader has gone away, raises BrokenPipeError during interpreter shutdown, and exits 120 — so a correct PASS is recorded as a crash. Centralising the emit path and using os._exit(rc) after an explicit flush removes the whole class.

Anyone writing a new fastcycle orchestration tool should route its entry through this module rather than calling sys.exit(main(sys.argv[1:])).

Prerequisites

  • python3 (stdlib only: argparse, ast, os, sys).
  • Import it from a sibling tool; there is no packaging step. The three consumers add scripts/fastcycle/lib to sys.path (or import by relative path).
  • No environment variables are read.
  • No files are required unless you invoke ast-gate, which needs the file paths you name.

Usage examples

Library — the intended use:

from fc_entry import FcArgumentParser, emit_result, diag, run_cli_main

def main(argv):
    ap = FcArgumentParser(prog="my_tool.py")
    ap.add_argument("--out", required=True)
    a = ap.parse_args(argv)
    payload = '{"ok":true}'
    emit_result(payload)          # the ONLY stdout write
    return 0

if __name__ == "__main__":
    run_cli_main(main, sys.argv[1:])
```text

CLI — the AST gate, used by the regression tests and runnable standalone:

```bash
# exit 0 if every named file confines its stdout/stderr writes to fc_entry
python3 scripts/fastcycle/lib/fc_entry.py ast-gate scripts/fastcycle/orchestration/handoff.py

# exit 1 and print each violation if a file writes stdout/stderr directly
python3 scripts/fastcycle/lib/fc_entry.py ast-gate scripts/fastcycle/orchestration/*.py

# no subcommand → usage on stderr, exit 2
python3 scripts/fastcycle/lib/fc_entry.py
```text

## Exported surface

| Name | Kind | Contract |
| --- | --- | --- |
| `emit_result(*a, **kw)` | function | The **only** sanctioned stdout write. Flushes and survives a broken pipe without corrupting the exit status. |
| `diag(*a, **kw)` | function | The **only** sanctioned stderr write (diagnostics). |
| `safe_str(exc)` | function | `str(exc)` that cannot itself raise (encoding failures, surrogate escapes). |
| `scan_argv_for_out(argv, flag="--out")` | function | Extracts the `--out` target from raw `argv` **before** argparse, so a stale output file can be invalidated even if parsing later fails. |
| `invalidate_stale_out(out_path)` | function | Removes a stale output document so a crashed run cannot leave yesterday's verdict in place to be read as today's. |
| `FcArgumentParser` | class | `argparse.ArgumentParser` subclass whose errors go through `diag` and exit `2` deterministically. |
| `run_cli_main(main_fn, argv)` | function | The wrapper. Converts `main_fn`'s return value into the process exit status, flushes, then calls `os._exit(rc)` — **never** `sys.exit(rc)`. |
| `check_no_bare_io(path)` | function | Static AST check: returns violations for direct stdout/stderr writes in `path`. |
| `check_no_bare_io_excluding(path, exempt_function_names)` | function | Same, with named functions exempted. |

The `os._exit` choice is deliberate and is the load-bearing detail: `sys.exit` runs interpreter
shutdown, which re-flushes streams, which can raise on a closed pipe *after* the status was decided.
`run_cli_main` flushes explicitly first, then exits without unwinding.

## Exit codes

As a library, `run_cli_main` propagates whatever integer `main_fn` returns. The module's own
conventions follow the shared `fc_common.py` C-001 table: `0` ok, `1` finding, `2` usage/config,
`3` self-test failed, `4` BLIND.

`ast-gate` specifically:

| Code | Meaning |
| --- | --- |
| `0` | Every named file is clean. |
| `1` | At least one violation found; each is printed to stderr. |
| `2` | No subcommand given (`usage: fc_entry.py ast-gate <file> ...`). |

Note that `ast-gate` with **zero file arguments** after the subcommand exits `0` vacuously — it
scanned nothing. Pass at least one path if you want the result to mean anything.

## Edge cases

- **Broken pipe on stdout.** `emit_result` contains it; the exit status stays whatever `main_fn`
  returned. This is the exact bug the module was created to kill.
- **A tool that prints directly.** Caught by `check_no_bare_io` / `ast-gate`, not at runtime. This is
  a static gate by design — a runtime check would be a fifth per-site patch.
- **`--out` pointing at a stale file plus a later parse error.** `scan_argv_for_out` runs before
  argparse precisely so the stale document is invalidated anyway.
- **An exception inside `main_fn`.** It is not caught here; the tool decides. Note that an uncaught
  exception exits `1` in CPython, which `fc_common.py`'s table reserves for *findings* — so a tool
  should catch broadly and return `4` (BLIND) instead.
- **Encoding-hostile exception messages.** Use `safe_str(exc)` rather than `str(exc)`.

## Internal behaviour

1. Tool code builds an `FcArgumentParser` and parses.
2. Tool computes a verdict and calls `emit_result` for the machine-readable document; diagnostics go
   to `diag`.
3. Tool returns an integer.
4. `run_cli_main` maps that integer to the process status, flushes stdout and stderr explicitly, and
   terminates via `os._exit(rc)`.

For `ast-gate`: parse each file with `ast`, walk for direct `print`/`sys.stdout.write`/
`sys.stderr.write` calls outside the sanctioned helpers, report each violation to stderr, and return
`1` if any exist.

## Related scripts

**Imported by** `scripts/fastcycle/orchestration/handoff.py`,
`scripts/fastcycle/orchestration/limit_class.py` and
`scripts/fastcycle/orchestration/custody_sweep.py`.

**Tested by** the round-6 through round-11 regression suites under `scripts/fastcycle/tests/`
(`test_handoff_r6_regression.sh`, `test_handoff_r7_regression.sh`, `test_limit_class_r7_regression.sh`,
`test_limit_class_r8_regression.sh`, `test_limit_class_r11_regression.sh`,
`test_custody_sweep_r9_regression.sh`, `test_custody_sweep_r11_regression.sh`,
`test_custody_sweep_r21_regression.sh`, `test_custody_sweep_stash_patch_r22_regression.sh`, and
`test_fc_entry_r10_regression.sh` which runs the AST gate itself).

See also `docs/scripts/fc_common.py.md` — the sibling shared-conventions module that defines the
C-001 exit-code table this module's callers use.

## Last verified

2026-12-04 — `python3 scripts/fastcycle/lib/fc_entry.py` (no subcommand) → usage line on stderr,
exit `2`. `python3 -c "import ast;ast.parse(open('scripts/fastcycle/lib/fc_entry.py').read())"` →
exit `0`. `python3 scripts/fastcycle/lib/fc_entry.py ast-gate
scripts/fastcycle/orchestration/handoff.py` → exit `0` (no violations).