Skip to content

Latest commit

 

History

History
205 lines (157 loc) · 11.4 KB

fc_common.md

File metadata and controls

205 lines (157 loc) · 11.4 KB

fc_common.sh / fc_common.py

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

Overview

These two files are the shared conventions layer for every spec-004 fastcycle tool (contracts/common-conventions.md, rows C-001..C-004). They are documented in one guide because they share one guide slot: the documentation convention keys a guide on the script's stem, and both are fc_common.

File Kind Role
scripts/fastcycle/lib/fc_common.sh source-only shell library The shell-side accessor for the canonical body_hash.
scripts/fastcycle/lib/fc_common.py CLI + importable Python library The real implementation: emit path, canonical hash, control needle, determinism check, --as-of freshness guard.

Together they exist to make one class of defect impossible: every fastcycle tool emits a JSON result document plus a process exit status, and those two must never disagree. When each tool grew its own print / json.dump / sys.exit, the same failure family returned four times — an exit status corrupted by a broken pipe, a half-written document left behind by an exception, a BLIND verdict reported as a plain failure. Centralising the emit path, the hash and the checks means a sibling tool inherits correct behaviour instead of re-deriving it (§11.4.250 — stop stacking per-site patches on one primitive defect; §11.4.227 — extend, don't duplicate).

The reason both halves must share one hash definition: body_hash deliberately excludes run_meta. That exclusion is what makes a verdict cacheable and a determinism check meaningful — run_meta legitimately changes on every run, so hashing it would make every run look different. A shell caller that inlined its own sha256sum over the whole file would produce a different hash than the Python tools for the same document, and the two would disagree forever without either being obviously wrong.

Prerequisites

  • fc_common.sh: bash (it uses BASH_SOURCE; POSIX sh is not sufficient), python3, and fc_common.py beside it (resolved relative to ${BASH_SOURCE[0]}, not the caller's cwd).
  • fc_common.py: python3 (stdlib for the common path; the device-sandbox helpers probe for extra tooling). Callers of determinism-check must let the command write its document to $FC_OUT.
  • No files are read from the repository.

Environment variables read — names only:

Variable Read by Effect
FC_DETERMINISM_TIMEOUT_S fc_common.py determinism-check Per-run timeout in seconds (default 60). A timeout yields exit 4, not a pass.
FC_OUT fc_common.py determinism-check Path the command under test must write its document to.

Usage examples

Shell library (source, never execute):

. "$(git rev-parse --show-toplevel)/scripts/fastcycle/lib/fc_common.sh"

# canonical hash, for cache keys or equality checks
if [ "$(fc_body_hash "$doc")" = "$(fc_body_hash "$other")" ]; then
  echo "same body (run_meta ignored)"
fi

Python CLI:

# emit a result document at exit code 0
python3 scripts/fastcycle/lib/fc_common.py emit \
  --schema verdict_cache/v1 --body-json '{"hits":3}' \
  --run-meta-json '{"started":"2026-12-04T19:00:00Z"}' --out /tmp/r.json

# canonical body_hash (run_meta excluded); --verify compares against the recorded value
python3 scripts/fastcycle/lib/fc_common.py body-hash --doc /tmp/r.json
python3 scripts/fastcycle/lib/fc_common.py body-hash --doc /tmp/r.json --verify

# C-004 control needle: the present value must be found, the fabricated one must not
python3 scripts/fastcycle/lib/fc_common.py needle \
  --present "PASS" --fabricated "NEEDLE-ABSENT-9f3a" --haystack /tmp/r.json

# is this command deterministic? run it twice and compare (body_hash, rc)
FC_OUT=/tmp/doc.json python3 scripts/fastcycle/lib/fc_common.py determinism-check -- some-tool --out /tmp/doc.json

# is a document fresh enough to gate on?
python3 scripts/fastcycle/lib/fc_common.py require-as-of --as-of 2026-12-04
python3 scripts/fastcycle/lib/fc_common.py require-as-of --windowed

--schema must match the form <tool>/v<N>; anything else is refused.

Exit codes

fc_common.sh never exits — it is sourced. Its one function, fc_body_hash <path>, prints the hash on stdout and propagates the Python exit status unchanged. A caller that needs to distinguish "unreadable document" from "different hash" must check $?; an empty string and a failure are not the same thing.

fc_common.py — the full C-001 table:

Code Meaning
0 OK / verdict reached.
1 A finding (needle not found, determinism mismatch, stale --as-of). A legitimate verdict, not a tool fault.
2 Usage error, config error, or unparseable input. Also a non-finite number (NaN, Infinity, 1e999) and a duplicate JSON key.
3 Self-test failed — no result file is written.
4 BLIND: no honest verdict was possible.

Exit 4 has two producers a caller must tell apart:

  1. emit --code 4 writes a document flagged "BLIND": true (C-001 row 4) — a deliberate, recorded blindness.
  2. An uncaught internal error also exits 4 but writes no file. C-001 has no other row for a tool fault, and it is deliberately never 1, because 1 is reserved for findings.

For determinism-check specifically:

Code Meaning
0 Stable — both runs agreed on body_hash and rc.
1 body_hash or rc differed (a diff is printed).
3 The command under test failed its own self-test.
4 No honest verdict.

Within determinism-check the only legitimate command codes are 0 and 1 (each with a JSON-object document) and 3. Every other code — 2, 4, 5, 70, 128+, death by signal — plus a missing command or a missing/non-JSON document collapses to 4 even when the two runs agree with each other. Two identical crashes are not determinism.

Exported surface

fc_common.sh

Name Kind Contract
FC_LIB_DIR variable Absolute directory of fc_common.sh, set on source, so a caller can reach sibling libraries without recomputing BASH_SOURCE.
fc_body_hash <path> function Prints the canonical body_hash on stdout; returns the Python call's status.

fc_common.py — importable helpers (no CLI subcommand of their own)

Helper Purpose
strict_loads(text) The one shared parse-time entry for caller-controlled JSON. Rejects non-finite constants and duplicate keys — closing every downstream write-site crash once.
SAFE_EXCEPTIONS A shared (TypeError, ValueError, OSError, OverflowError) tuple sibling tools OR onto their own narrower except clauses rather than each guessing a set.
is_strict_nonneg_int(v) "Is this a genuine non-negative JSON integer?" Rejects bool and negative.
canon(obj) / body_hash_of(doc) Canonicalisation and the body hash itself.
atomic_backup_and_replace(target, text, tag) Atomic write with a tagged backup.
merkle_over_dir_lstat(root) Content-addressed directory digest; lstat-based so symlinks are not followed.
run_gate_reaped(cmd, timeout_s, env, cwd) → GateRunResult Runs a gate in its own process group and reaps the whole group.
safe_killpg(pgid, sig) Guarded process-group signal (refuses pgid <= 1, §11.4.263).
device_sandbox_env(...), wrap_device_sandbox_argv(...), device_sandbox_namespace_available(...), build_device_sandbox_bin_dir(...), DeviceSandboxUnavailable Device-reach sandboxing for gate runs. Reports availability rather than assuming kernel namespace support.
cgroup_runner_available(...), _own_cgroup_v2_base() cgroup-v2 run isolation probe.

Edge cases

  • Sourcing fc_common.sh under sh. BASH_SOURCE is unset, so the $0 fallback resolves to the sourcing script, making FC_LIB_DIR (and the Python lookup) wrong. Use bash.
  • fc_common.py absent or renamed. Sourcing still succeeds; the first fc_body_hash call fails.
  • Sourcing twice. Safe — the variable and function are simply redefined identically.
  • Non-finite numbers (NaN, Infinity, 1e999). Refused everywhere with exit 2, once, at parse time.
  • Duplicate JSON keys. Refused (exit 2) — "the last one wins" is a silent ambiguity.
  • run_meta that is empty or not a JSON object. Refused (exit 2); never read as "absent".
  • Needle type semantics (C-004). Numbers compare by value (1 equals 1.0), a bool never equals a number, a string never equals a number — so a needle tested against the wrong JSON type fails rather than coincidentally passing.
  • File mode. Result files honour the caller's umask (0666 & ~umask); the module does not override it.
  • A command outliving its budget. The whole process group is reaped; the timeout surfaces as 4.
  • --as-of in the future, or absent from the document. Treated as stale — a finding (1), not a pass.

Internal behaviour

fc_common.sh: on source, computes FC_LIB_DIR from the sourced file's directory and defines fc_body_hash, which shells out to python3 "$FC_LIB_DIR/fc_common.py" body-hash --doc "$1". That is the whole file — no argument parsing, no validation.

fc_common.py:

  1. Parses the subcommand out of argv.
  2. emit — validates --schema against <tool>/v<N>, refuses a non-object run_meta, serialises the body canonically, computes body_hash over the body excluding run_meta, and writes atomically.
  3. body-hash — loads through strict_loads, canonicalises, hashes the body minus run_meta; with --verify, compares against the recorded hash and reports a finding on mismatch.
  4. needle — searches for the present value (must be found) and the fabricated value (must not), applying the C-004 type rules.
  5. determinism-check — runs the command twice inside a reaped, time-bounded scope, reads $FC_OUT each time, normalises to (body_hash, rc), and reduces the pair to one of the four codes.
  6. require-as-of — parses the date (or derives the window), compares against the document's recorded date, and returns freshness as a verdict.

Related scripts

fc_common.py is imported by the whole fastcycle toolset: gates/flake_ledger.py, gates/lib/io_trace_build_map.py, orchestration/handoff.py, orchestration/custody_sweep.py, orchestration/completion_probe.sh, review/review_record.py, verify/plan_struct_check.py, verify/repo_verify.py, verify/gate_determinism_sweep.py, tokens/transcript_ingest.py and host/host_report.py.

fc_common.sh is sourced by scripts/fastcycle/tests/test_fc_common_red.sh, test_gate_audit_red.sh, test_affected_set_red.sh, test_cycle_report_red.sh, test_catchset_compare_red.sh, test_catchset_compare_seed_independence_r2_regression.sh, and scripts/gates/cm_killpg_pgid_guard_mutation_test.sh.

Tested by scripts/fastcycle/tests/test_fc_common_red.sh.

See also docs/scripts/fc_entry.md (the sibling entry primitive) and docs/scripts/gate_determinism_sweep.md (the main consumer of determinism-check).

Last verified

2026-12-04 — bash -n scripts/fastcycle/lib/fc_common.sh → exit 0. python3 -c "import ast;ast.parse(open('scripts/fastcycle/lib/fc_common.py').read())" → exit 0. python3 scripts/fastcycle/lib/fc_common.py with no subcommand prints a usage error and exits 2, confirming the C-001 usage row.