Clew Module (stx.clew)
Hash-based provenance tracking for reproducible science. Clew (Ariadne’s
thread) records file hashes during @stx.session runs and traces
dependency chains back to source.
How It Works
@stx.sessionstarts a tracking sessionstx.io.load()records input file hashesstx.io.save()records output file hashesSession close computes a combined hash of all inputs/outputs
Later,
stx.clewcan verify nothing has changed
import scitex as stx
# Automatic -- just use @stx.session + stx.io
@stx.session
def main():
data = stx.io.load("input.csv") # Tracked as input
result = process(data)
stx.io.save(result, "output.png") # Tracked as output
return 0
# Verify later
stx.clew.status() # Like git status
stx.clew.run("session_id") # Verify by hash
stx.clew.chain("output.png") # Trace to source
CLI Commands
scitex clew status # Show changed files
scitex clew list # List all tracked runs
scitex clew run <session_id> # Verify a specific run
scitex clew chain <file> # Trace dependency chain
scitex clew stats # Database statistics
Verification Levels
CACHE – Hash comparison only (fast). Checks if files match stored hashes.
RERUN – Re-execute scripts and compare outputs (thorough). Catches logic errors.
# Fast: hash comparison
result = stx.clew.run("session_id")
# Thorough: re-execute and compare
result = stx.clew.run("session_id", from_scratch=True)
Dependency Chains
Clew traces parent_session links to build a DAG from final output
back to original source:
chain = stx.clew.chain("final_figure.png")
# Shows: source.py → intermediate.csv → analysis.py → final_figure.png
# Visualize as Mermaid DAG
stx.clew.mermaid("session_id")
Verification Statuses
VERIFIED– Files match expected hashesMISMATCH– Files differ from stored hashesMISSING– Files no longer existUNKNOWN– No prior tracking data
Key Functions
status()– Show changed items (likegit status)run(session_id)– Verify a specific runchain(target_file)– Trace dependency chainlist_runs(limit, status)– List tracked runsstats()– Database statistics
API Reference
scitex-clew — Hash-based verification for reproducible science.
Provenance is recorded in THE store this host uses — the per-host
PostgreSQL, resolved by scitex_dev.store.host_store().
When used with scitex, integration is automatic via @stx.session + stx.io.
Public API:
import scitex_clew as clew
# Verification
clew.status() # git-status-like overview
clew.run(session_id) # verify one run (hash check)
clew.chain(target_file) # trace file → source chain
clew.slice(target_or_claim) # minimal file-level provenance slice
clew.dag(targets) # verify full DAG
clew.rerun(target) # re-execute & compare (sandbox)
clew.rerun_dag(targets) # rerun full DAG in topo order
clew.rerun_claims() # rerun all claim-backing sessions
clew.list_runs(limit=100) # list tracked runs
clew.stats() # database statistics
clew.estimate(script_or_target) # pre-flight runtime/success estimate
# Claims
clew.add_claim(...) # register manuscript assertion
clew.list_claims(...) # list registered claims
clew.verify_claim(...) # verify a specific claim
clew.verify_all_claims(...) # verify every claim -> fail-loud code
# Citations (\cite -> scholar-verified source gate)
clew.add_citation(...) # register (push) a scholar-resolved cite
clew.list_citations(...) # list registered citation nodes
clew.verify_citations(entries) # per-key {status,doi,source_id,link,reason}
clew.verify_all_citations(entries) # fail-loud VerificationResult (same-run)
# Stamping
clew.stamp(...) # create temporal proof
clew.list_stamps(...) # list stamps
clew.check_stamp(...) # verify a stamp
# Hashing
clew.hash_file(path) # SHA256 of a file
clew.hash_directory(path) # SHA256 of all files in dir
# Visualization
clew.mermaid(...) # generate Mermaid DAG diagram
# Examples
clew.init_examples(dest) # scaffold example pipeline
# Session lifecycle hooks (invoked by @scitex.session)
clew.on_session_start(session_id) # open a tracked run
clew.on_session_close(status=...) # finalize run + combined hash
clew.recover_journals() # replay runs killed before close
Implementation note (audit-all §10 cold-start):
This module uses the PEP 562 ``__getattr__`` lazy-import pattern. All
submodules and re-exports below ``__version__`` are loaded on first
access only, so ``import scitex_clew`` stays well under the 500ms
cold-start threshold. The public attribute names listed above (and in
``__all__``) resolve exactly as before — no caller-visible change.
- scitex.clew.chain(target, minimal=False, level=1)[source]
Verify the dependency chain for a target file.
minimal=Trueverifies only the file-level minimal slice (seeslice()) atlevel.
- scitex.clew.slice(target, level=1)[source]
File-level minimal provenance slice of a target file or claim.
Returns only the file nodes and runs on paths that end at the target.
- Parameters:
target (str, Path, or list of them) – Target file(s), claim id(s), or
paper.tex:L42claim locations.level (
int) – 0 = run-level closure (every input/output of every ancestor run); 1 = path-pruned (default): drop runs/files not on any path to the target, sibling outputs and their consumers; 2 = additionally use per-outputderived_fromdeclarations where a tool recorded them (falls back to level 1 per run otherwise).
- Returns:
.runs,.files,.edges,.counts()and the dropped / fallback diagnostics;.to_dict()for JSON.- Return type:
ProvenanceSlice
- scitex.clew.dag(targets=None, claims=False, strict=False, minimal=False, level=1)[source]
Verify the DAG for multiple targets or all claims.
- Parameters:
targets (list of str or Path, optional) – Target files to verify (mutually exclusive with
claims).claims (bool, optional) – If True, build the DAG from every registered claim.
strict (bool, optional) – If True (F2), return a failure-attribution dict with
failed_node/root_cause/invalidated_claims/still_valid_claimsinstead of aDAGVerification.minimal (bool, optional) – Verify only the file-level minimal slice (see
slice()).level (int, optional) – Slice level when
minimal.
- scitex.clew.rerun(target, timeout=300, cleanup=True)[source]
Re-execute a session in a sandbox and compare outputs.
- scitex.clew.rerun_dag(targets=None, timeout=300, cleanup=True, skip_unchanged=False)[source]
Rerun-verify an entire DAG in topological order.
Each session is re-executed against its ORIGINAL stored inputs then compared to its original outputs. When
skip_unchanged=Truea freshness check short-circuits the subprocess for unchanged sessions.- Parameters:
targets (
list[str] |None) – Target output files. If None all recorded outputs are used.timeout (
int) – Max execution time per session in seconds (default: 300).cleanup (
bool) – Remove sandbox output directories after each rerun.skip_unchanged (
bool) – OPT-IN incremental skip (default: False). When True, each session is tested for freshness BEFORE the expensive subprocess launch. A session is fresh when: (1) script_hash is recorded; (2) script file exists and matches script_hash; (3) every recorded INPUT file exists and its hash matches the recorded value. Fresh sessions are marked status=VERIFIED / level=CACHE sois_verified_from_scratchis False — clearly distinct from an actual re-execution. Non-fresh sessions fall through to the normal_execute_scriptpath. Default is False: behavior is byte-identical to the original.
- Returns:
Unified verification result for the entire DAG.
- Return type:
DAGVerification
- scitex.clew.rerun_claims(file_path=None, claim_type=None, timeout=300, cleanup=True)[source]
Rerun-verify all sessions that produced files referenced by claims.
- Parameters:
file_path (
str|None) – Filter claims by manuscript file path.claim_type (
str|None) – Filter claims by type (statistic, figure, table, text, value).timeout (
int) – Maximum execution time per session in seconds (default: 300).cleanup (
bool) – Whether to remove sandbox output directories after each rerun.
- Returns:
Unified verification result for the upstream DAG.
- Return type:
DAGVerification
- scitex.clew.estimate(script_or_target, *, heavy_threshold=None)[source]
Pre-flight runtime/success estimate for a script or target file.
- Parameters:
- Returns:
Estimation result with match_tier, p50/p90 runtime, success rate, typical #outputs, heavy flag, and hint text.
- Return type:
EstimateResult
- scitex.clew.add_claim(file_path, claim_type, line_number=None, claim_value=None, source_file=None, source_session=None, *, claim_id=None, value=None, source_keys=None, tolerance=None, metadata=None, project_root=None)[source]
Register a claim linking a manuscript assertion to the verification chain.
- Parameters:
file_path (
str) – Path to the manuscript file (e.g., paper.tex).claim_type (
str) – One of: statistic, figure, table, text, value.claim_value (
str|None) – The asserted value (e.g., “p = 0.003”).source_file (
str|None) – Path to the source file that produced this claim.source_session (
str|None) – Session ID that produced the source.claim_id (
str|None) – Explicit, stable claim id used VERBATIM as the primary key (keyword- only). Supply this when the caller owns a meaningful identity — e.g. a figure’s image save-path, or a semantic key per manuscript number — so the id never collapses and downstream\clew*{id}render macros can join on it deterministically. When omitted, the id is DERIVED from(file_path, line_number, claim_type, claim_value)— folding the value in so two distinct numbers on one line no longer collapse. Re- registering the same explicit id (or the same derived tuple) overwrites idempotently.value (scalar or dict, optional) – Structured claimed value (keyword-only), e.g.
0.91or{"auc": 0.91, "n": 120}.claim_valuestays the display string; whenvalueis omitted the display string is the checked value.source_keys (
dict|None) –{field | ".": locator}— where each value field lives insidesource_file:{"pointer": "/test/auc"}(RFC 6901, json/yaml) or{"row": 3 | {"col": "v"}, "column": "auc" | 2}(csv/tsv), each optionally withabs_tol/rel_tol. Verification then compares the claimed value with the value read there (VALUE_MISMATCHon disagreement). Same shape as scitex-writer’ssource_keys; seescitex_clew._claim._locator. Validated here.tolerance (
dict|None) – Claim-level{"abs_tol", "rel_tol"}. Without any declared tolerance the precision the value was written with is used (0.91 -> ±0.005).metadata (
dict|None) – Free-form JSON-serialisable caller data, stored verbatim.project_root (
str|Path|None) – Register into this project’s scope (and resolve relative paths against it) withoutchdir. Default: resolved from the cwd.
- Returns:
The registered claim object.
- Return type:
Claim
- scitex.clew.list_claims(file_path=None, claim_type=None, status=None, limit=100, *, include_superseded=False, file_path_prefix=None)[source]
List registered claims with optional filters.
- Parameters:
file_path (
str|None) – Filter by manuscript file path (exact match).limit (
int) – Maximum number of claims to return.include_superseded (
bool) – When False (default), excludes claims with status"superseded"so they do not pollute the active-claim view or fail-loud gate. Pass True to see the full audit trail including superseded rows.file_path_prefix (
str|None) – Prefix-match on file_path (resolved). Only claims whosefile_pathstarts with this prefix are returned. If bothfile_pathandfile_path_prefixare given, both filters apply (intersection).
- Return type:
list[Claim]
- scitex.clew.verify_claim(claim_id_or_location, hash_cache=None, chain_cache=None, env_cache=None, records=None)[source]
Verify a specific claim by checking its source against the verification chain.
- Parameters:
claim_id_or_location (
str) – Either a claim_id or a location string like “paper.tex:L42”.hash_cache (
dict[str,str] |None) – Per-pass cache mapping resolved-path -> hash (seescitex_clew._hash.hash_file()). When provided, a source file shared by multiple claims is hashed at most once per pass. PassNone(default) to disable caching — direct callers are unaffected.chain_cache (
dict[str,object] |None) – Per-pass memo mappingstr(resolved source_file)->ChainVerification. When provided, the full chain walk (verify_chain) for a source_file that appears on multiple claims is executed at most once perverify_all_claims()pass. PassNone(default) to disable memoization — direct callers are unaffected.env_cache (
dict|None) – Per-pass cache of this environment’s installed distributions (seescitex_clew._chain._env_requirements.current_distribution()).records (PassRecords or None, optional) – Per-pass read cache of the provenance store (
scitex_clew._chain._pass_cache.pass_records()). When provided, a run shared by several claims’ slices is read from the store once per pass.None(default) uses a cache scoped to this claim.
- Returns:
Verification result with claim details and chain status.
environment_findingslists the slice’s environment requirements that are not reproducible from the record (a distribution installed from a local build, edited after installation, or with other content here under the same version); empty when all are reproducible.- Return type:
- scitex.clew.verify_all_claims(file_path=None, claim_type=None, *, strict=False, config=None)[source]
Verify every registered claim and reduce to a fail-loud result.
This is the reusable core behind
clew verify(claim-set mode). It re-verifies each claim (re-hashing its source and, instrictmode, checking upstream@stx.sessionlineage), updates each claim’s stored status as a side effect (viaverify_claim()), and reduces the per-claim outcomes to a singleVerificationResult.- Parameters:
file_path (
str|None) – Restrict to claims registered against this manuscript path.strict (
bool) – When True, a claim only passes if its source additionally has upstream computation lineage (its provenance chain verifies). A hand-written leaf (no@stx.sessionbehind it) fails withNO_LINEAGEeven though its hash matches.strictalso promotesNO_LINEAGEto ERROR severity regardless of config. Default False.config (
str|Path|None) – Explicit.scitex/clewconfig file/dir overriding the resolved user/project severity map (seescitex_clew._core._config).
- Returns:
Structured outcome.
result.exit_code == 0(result.ok) is the DONE-gate; any nonzero code means the agent MUST abstain honestly instead of claiming success. Per-pattern severity (configurable via.scitex/clew) decides which fired patterns areerrors(fail) vswarnings(tolerated). Seescitex_clew._cli._exit_codes.- Return type:
VerificationResult
- scitex.clew.export_claims_json(path=None, *, file_path_filter=None, read_only=True, include_superseded=False)[source]
Export every registered claim to a canonical JSON artifact.
The exported file is the single human-readable + machine-consumable view of the claims store. The store remains the source of truth; this JSON is a regenerable artifact.
Path resolution for the artifact (the STORE has no path):
1. Explicit ``path`` argument. 2. ``$SCITEX_CLEW_CLAIMS_JSON`` env var (escape hatch). 3. ``<project_root>/.scitex/clew/runtime/claims.json`` (project root = nearest ancestor dir with ``.git`` or ``pyproject.toml``; falls back to cwd if none found).
- Parameters:
path (
str|Path|None) – Override the resolved path. Useful for tests / one-off dumps.file_path_filter (
str|None) – When set, only claims registered against this manuscript file path are exported. Default: every claim in the DB.read_only (
bool) – After writing,chmod 0o444the file so accidental edits fail loudly at the OS layer. Default True (the file IS derived). Set False for tests that need to mutate the file.include_superseded (
bool) – When False (default), superseded claims are excluded from the exported JSON — consumers should only see active claims. Pass True to include them (audit/debug use).
- Returns:
The path the artifact was written to (absolute).
- Return type:
Examples
>>> import scitex_clew as clew >>> clew.add_claim("paper.tex", "value", 42, "0.94", source_file="r.csv") >>> # claims.json now auto-exported under ./.scitex/clew/runtime/ >>> clew.export_claims_json() # idempotent — re-emit on demand PosixPath('.../.scitex/clew/runtime/claims.json')
- scitex.clew.export_manuscript_claims(path=None, *, read_only=True)[source]
Emit the unified render feed (value + citation + figure) to claims.json.
Reads both clew ledgers and writes ONE
claimslist in scitex-writer’s frozen render schema. This is the compile-time exporter behindclew export-claims --unified; the compiler calls it last so render_clew reads the complete unified shape.- Parameters:
path (
Union[str,Path,None]) – Output path. Resolution mirrorsexport_claims_json(): explicitpath>$SCITEX_CLEW_CLAIMS_JSON><project_root>/.scitex/clew/runtime/claims.json(the canonical file render_clew reads). Pass an explicit path for a dedicated file.read_only (
bool) –chmod 0o444the file after writing (default True — it is derived).
- Returns:
The path written (absolute).
- Return type:
- scitex.clew.export_manuscript_hints(path=None, *, read_only=True)[source]
Emit clew’s prose-level manuscript hints to
.scitex/writer/hints.json.Reads clew’s claim ledger + ingested citation ledger and emits ONE
hintslist in scitex-writer’smanuscript-hints/1schema — the author-facing “what needs fixing” feed. This is a DIFFERENT, separate concern fromexport_manuscript_claims()(the per-claim render/ verification feed) — see the module docstring; do not confuse the two.MERGE-BY-SOURCE: if
hints.jsonalready exists with entries from other producers (e.g. figrecipe, or scitex-writer’s own hints), this function replaces ONLY the entries wheresource == "scitex-clew"and leaves every other entry untouched (verbatim, original relative order). A missing or unparsable file is treated as empty and (re)created fresh with schemamanuscript-hints/1.- Parameters:
path (
Union[str,Path,None]) – Output path. Resolution mirrorsexport_manuscript_claims(): explicitpath>$SCITEX_CLEW_HINTS_JSON><project_root>/.scitex/writer/hints.json(the canonical file scitex-writer reads). Pass an explicit path for a dedicated file.read_only (
bool) –chmod 0o444the file after writing (default True — it is derived).
- Returns:
The path written (absolute).
- Return type:
- scitex.clew.register_intermediate(name, value, supports=None, session_id=None, claim_type='value')[source]
Register a computed intermediate as a Clew claim.
Use this from inside a @stx.session script (or from an agent loop) to record any non-trivial intermediate value with explicit upstream support. The claim becomes part of the DAG and can be queried via clew.chain, clew.dag, or the MCP clew_chain / clew_dag tools.
- Parameters:
name (
str) – Descriptive identifier (e.g. “acute_n_sig_pathways”). Avoid generic names like “result_3” — the id is the only handle a future inspector has on the value.value (
Any) – The computed result. Coerced to string for storage; the hash chain sees repr(value) so types matter.supports (
Optional[List[str]]) – List of upstream claim ids or session ids that this value depends on. Stored as JSON in the claim’s value field for retrieval. None means no explicit upstream (use sparingly).session_id (
Optional[str]) – The session this value belongs to. If None, read from the SCITEX_SESSION_ID env var that @stx.session sets at start.claim_type (
str) – One of statistic, figure, table, text, value. Defaults to value since intermediates are usually scalar / categorical results.
- Returns:
The registered claim object.
- Return type:
Claim- Raises:
ValueError – If no session_id can be determined (env var unset and not passed).
Examples
Inside a @stx.session script:
>>> from scitex_clew import register_intermediate >>> n_sig = sum(1 for p in pathways if p.padj < 0.05) >>> register_intermediate( ... name="chronic_r2_n_sig_pathways", ... value=n_sig, ... supports=["chronic_r2_min_pvals", "reactome_pathways_v2024"], ... )
- scitex.clew.remove_claim(claim_id_or_location)[source]
Hard-delete a claim from the database.
Permanently removes the claim row identified by
claim_id_or_location(a claim_id string, a location like"paper.tex:L42", or a bare file path — resolved via the same logic asverify_claim()).After deletion
export_claims_json()is called so the JSON artifact stays in sync with the DB.
- scitex.clew.supersede_claim(claim_id_or_location)[source]
Soft-retire a claim by setting its status to
"superseded".The row is kept in the database (audit trail) but excluded from the default
list_claims()view (include_superseded=Falseis the default), fromverify_all_claims(), and from the defaultexport_claims_json()output.This allows a user to retire stale/dead claims so that
clew verifycan reach exit 0 without deleting the historical record.- Parameters:
claim_id_or_location (
str) – Claim identifier resolved the same way asremove_claim().- Returns:
Trueif the claim existed and was updated;Falseif nothing matched.- Return type:
- scitex.clew.add_citation(cite_key, *, manuscript_file=None, line_number=None, doi=None, source_id=None, metadata=None, url=None, is_stub=False, resolved=True)[source]
Register (push) a citation node resolved by scitex-scholar.
This is the ledger-write half of the push model: scholar resolves a
\citekey to a real source and records the outcome here. clew stores the node plus a content hash over the normalized metadata so a later out-of-band edit to the bib entry is caught (drift -> hash mismatch).- Parameters:
cite_key (
str) – The BibTeX citation key (e.g."Berens2009CircStat").manuscript_file (
Optional[str]) – Manuscript the key is cited from (e.g.paper.tex).line_number (
Optional[int]) – Line number of the\citein the manuscript.doi (
Optional[str]) – Resolved DOI of the real source (None for a stub / unresolved).source_id (
Optional[str]) – Scholar’s internal source identifier for the resolved record.metadata (
Optional[Dict]) – Bib fields (author/year/title/journal/doi) used for the content hash.url (
Optional[str]) – Explicit source URL. Takes precedence over the derivedhttps://doi.org/<doi>link — supply it for no-DOI records (e.g. SemanticScholar CorpusId-only) so the renderer has an href.is_stub (
bool) – True if scholar flagged this as a stub / placeholder. Default False.resolved (
bool) – True if scholar resolved the key to a real source. Default True.
- Returns:
The stored citation node.
- Return type:
Citation
- scitex.clew.list_citations(manuscript_file=None, status=None, limit=1000)[source]
List registered citation nodes with optional filters.
- Return type:
List[Citation]
- scitex.clew.verify_citations(entries)[source]
Verify a set of cited keys against the clew citation ledger.
This is the primitive the compiler’s pre-flight calls. For each entry it returns the per-key verdict the writer gate branches on.
- Parameters:
entries (list[dict] | list[str]) – Cited keys. Each dict carries at least
"key"plus any bib fields the compiler extracted (doi/journal/note/title/author/year). A bare string is treated as{"key": ...}.- Returns:
{cite_key: {"status", "doi", "source_id", "link", "reason"}}wherestatusis one of{verified, stub, unverified, unknown}andlinkis the resolved source URL for an href (scholar-supplied url, elsehttps://doi.org/<doi>, else None). The compiler treats anything other than"verified"as a gate hit and renders the marker fromstatus(style) +link(href) +reason(tooltip).- Return type:
- scitex.clew.verify_all_citations(entries, *, strict=False, config=None)[source]
Reduce a set of cited keys to a fail-loud
VerificationResult.Same aggregate contract as
scitex_clew.verify_all_claims(), so the compiler gets a singleresult.okDONE-gate covering citations. Per-key verdicts reduce onto the citation exit codes (CITATION_STUB / _UNRESOLVED / _UNLINKED, plus HASH_MISMATCH on drift), each config-tunable via.scitex/clewverify.severity.- Parameters:
entries (list[dict] | list[str]) – Cited keys (see
verify_citations()).strict (
bool) – Reserved for parity with the claim gate; currently a no-op for citations (every citation pattern already defaults to ERROR).config (str | pathlib.Path, optional) – Explicit
.scitex/clewconfig overriding the resolved severity map.
- Returns:
result.ok(exit 0) iff every cited key isverified.- Return type:
VerificationResult
- scitex.clew.register_source(files, *, sources_path=None, root=None)[source]
Register one or more files as trusted sources (idempotent).
Computes each file’s full sha256 and appends/updates a
{path, sha256}entry in the manifest, creating it at the tier-3 path if absent. Re- registering a path updates its hash (idempotent).- Parameters:
files (
Union[str,Path,List[Union[str,Path]]]) – File(s) to register. Each must exist (its content is hashed now).sources_path (
Union[str,Path,None]) – Explicit manifest path (else tier-2 env / tier-3 default).root (
Union[str,Path,None]) – Project root that relpaths are stored against (default: cwd walk).
- Returns:
The manifest path written to (absolute).
- Return type:
- scitex.clew.unregister_source(files, *, sources_path=None, root=None)[source]
Remove one or more registered sources (idempotent; no-op if absent).
- Return type:
- scitex.clew.list_sources(*, sources_path=None, root=None)[source]
Return the manifest entries with a per-entry validity check.
Each dict carries
path,sha256,abspath,valid(bool), andreason(OK/TAMPERED/MISSING). Returns[]when no manifest exists.
- scitex.clew.is_grounded(claim, manifest, db)[source]
Return
Trueiff the claim’s chain reaches a VALID registered source.- Parameters:
claim (Claim) – The claim (needs
source_file,source_hash,source_session).manifest (
SourcesManifest) – A loaded, tamper-checked manifest. When it has no VALID anchors the function returnsTrue(defensive: nothing to demote against — the caller normally gates onmanifest.activebefore calling).db (VerificationDB) – Provides the file-hash + producer lookups the chain walk needs.
- Returns:
True(grounded) iff at least one chain candidate matches a valid anchor by absolute path AND hash-consistency;False(unsourced) when every root is unregistered.- Return type:
- scitex.clew.is_claim_grounded(claim_location, *, workdir='.')[source]
Per-claim grounding verdict for a live inline editor.
Resolves
claim_location(a bareclaim_idOR afile.tex:L42location — reusingscitex_clew._claim._model._resolve_claim(), the SAME resolutionverify_claimuses) against the clew DB + registered- source manifest found underworkdir, and returns a richer verdict thanis_grounded()’s bare bool.This function OWNS opening the sources manifest and the clew DB internally (via
workdir) — callers must never construct aSourcesManifestor a DB handle directly.- Parameters:
claim_location (
str) – A claim_id or afile.tex:L42-style location.workdir (
str) – Directory the clew DB + sources manifest are resolved under (default"."— the current working directory, byte-identical to every other clew call that resolves implicitly from cwd sincePath(".").resolve()is the cwd).
- Returns:
The
GroundingVerdict:{ "grounded": bool, # see Notes — never disagrees with # the aggregate gate "claim_id": str, "matched_source": {"path": str, "sha256": str} | None, "reason": str, # one of GROUNDING_REASONS "fix_hint": str, }
- Return type:
Notes
groundedNEVER disagrees with the aggregateverify_all_claims/export_claims_jsongate on the same claim: when a manifest is present,groundedis the LITERAL return value ofis_grounded()(including its defensive-True when the manifest has no valid anchors at all — reason folds to"grounded", there is no separate reason for that edge case); when no manifest exists at all, the aggregate gate is INACTIVE (it never demotes a claim), sogrounded=Truehere too — reason"no_manifest"carries the “amber, not a failure” nuance the bool alone cannot express.
- scitex.clew.load_sources_manifest(sources_path=None, *, root=None)[source]
Load + tamper-check the registered-source manifest.
- Parameters:
sources_path (
Union[str,Path,None]) – Explicit manifest path (tier 1). Falls through to$SCITEX_CLEW_SOURCES(tier 2) then the tier-3 default.root (
Union[str,Path,None]) – Project root the manifest relpaths resolve against. WhenNone, derived from the manifest location (canonical layout) or the cwd project-root walk.
- Returns:
Nonewhen the manifest file does not exist — the gate is then INACTIVE (opt-in: zero behavior change). A present manifest is parsed, schema-validated, and every entry tamper-checked (recompute each file’s sha256 vs the pinned value).- Return type:
- Raises:
ValueError – On a malformed manifest (not JSON, wrong schema string, missing
sourceslist, or a malformed entry). Fail-loud, never silent-empty.
- scitex.clew.resolve_sources_path(sources_path=None)[source]
Resolve the manifest path via the three-tier precedence.
tier1 explicit arg > tier2
$SCITEX_CLEW_SOURCES> tier3<project_root>/.scitex/clew/sources.json. The store-path resolver this once mirrored is gone — the store is not a file.
- class scitex.clew.SourcesManifest(schema, root, path, entries=list(), signature=None, signing_enforced=False, signature_valid=None)[source]
A loaded, tamper-checked registered-source manifest.
activeis the OPT-IN switch: the gate only fires when at least one VALID entry is present. An absent manifest loads asNone(seeload_sources_manifest()); a present-but-empty or all-invalid manifest isactive is Falseso the gate stays dormant.- property trusted: bool
False iff signing is ENFORCED but the manifest’s signature is missing/invalid — an untrusted manifest anchors NOTHING (so a tampered or unsigned-under-an-enforcing-key manifest cannot ground any claim: “without the key it can’t be run/edited”).
- property active: bool
Gate FIRES iff signing is enforced (a committed signing.pub) OR >=1 VALID anchor exists.
When signing is enforced the gate fires even for an UNTRUSTED manifest — so is_grounded blocks ALL its claims (an unsigned or tampered manifest must not silently pass by making the gate go dormant).
- scitex.clew.stamp(backend='file', service_url=None, session_ids=None, output_dir=None)[source]
Record root hash with external timestamp.
- Parameters:
backend (
str) – One of: file, rfc3161, zenodo.service_url (
Optional[str]) – URL for RFC 3161 TSA or Zenodo API.session_ids (
Optional[List[str]]) – Specific sessions to stamp. If None, stamps all successful runs.output_dir (
Optional[str]) – Directory for file-based stamps (default: <db_dir>/stamps, i.e. .scitex/clew/runtime/stamps/).
- Returns:
The timestamp proof record.
- Return type:
Stamp
- scitex.clew.hash_file(path, algorithm='sha256', chunk_size=8192, hash_cache=None)[source]
Compute hash of a file.
- Parameters:
algorithm (
str) – Hash algorithm (default: sha256)chunk_size (
int) – Size of chunks to read (default: 8192)hash_cache (
dict[str,str] |None) – Per-pass cache mapping resolved-path -> hash. When provided, the resolved path is looked up first; on a miss the file is hashed and the result is stored so subsequent calls within the same pass reuse the cached value. PassNone(default) to disable caching — direct calls tohash_fileare unaffected.
- Returns:
Full hexadecimal hash digest (64 characters for sha256)
- Return type:
Examples
>>> hash_file("data.csv") 'a1b2c3d4e5f6...'
Notes
Prior to this fix, the result was truncated to the first 32 hex characters (128 bits) of the digest. That truncation made the “obvious” external check
get_file_hashes(session)[path] == hashlib.sha256(open(path, "rb").read()).hexdigest()silently and permanently False for every tracked file — a confident-wrong-answer bug (clew-fix-truncated-hash-comparison). The full digest is now returned; every internal comparison site goes throughhashes_match(), which requires full equality and tolerates ONLY the legacy 32-char truncated width, so pre-existing truncated rows still verify.
- scitex.clew.hash_directory(path, pattern='*', recursive=True, algorithm='sha256')[source]
Compute hashes for all files in a directory.
- Parameters:
- Returns:
Mapping of relative paths to hashes
- Return type:
Examples
>>> hash_directory("./data/") {'input.csv': 'a1b2...', 'config.yaml': 'c3d4...'}
Notes
Transparently accepts a compressed session archive: if
pathis a<dir>.tar.gzfile (or a directory whose<dir>.tar.gzsibling exists because it was archived away), the members are hashed in place and returned with the same{relpath: hash}shape a loose dir would yield.
- scitex.clew.mermaid(session_id=None, target_file=None, target_files=None, claims=False, grouper=None, **kwargs)[source]
Generate a Mermaid DAG diagram.
- Parameters:
session_id (str, optional) – Start from this session.
target_file (str, optional) – Start from the session that produced this file.
target_files (list of str, optional) – Multiple target files (multi-target DAG).
claims (bool, optional) – If True, build DAG from all registered claims.
grouper (callable | dict | None, optional) – File grouping strategy. Callable or JSON/dict spec (see
scitex_clew.groupers.resolve_spec). IfNone, falls back to.scitex/clew/config.yaml(keygrouper) if present.
- scitex.clew.init_examples(dest, variant='sequential', *, find_examples_dir=<function _find_examples_dir>)[source]
Copy Clew example scripts to a destination directory.
Copies only the runnable scripts (.py, .sh) and README — not the output directories. Users run
00_run_all.shthemselves to generate outputs and populate the verification database.- Parameters:
dest (
str|Path) – Destination directory. Created if it does not exist. Existing script files are overwritten.variant (
str) – Example variant: “sequential” (default) or “multi_parent”.find_examples_dir (callable, optional) – Locator callable
(variant: str) -> Optional[Path]used to resolve the bundled examples source. Production callers should not pass this; it is the canonical PA-306 §1 DI seam — tests inject a hand-rolled fake that returns atmp_path-rooted directory orNone.
- Returns:
{"path": str, "files": list[str], "file_count": int, "variant": str}- Return type:
- Raises:
FileNotFoundError – If the bundled examples cannot be located.
ValueError – If variant is not recognized.
- scitex.clew.on_session_start(session_id, script_path=None, parent_session=None, verbose=False, metadata=None)[source]
Hook called when a session starts.
- Parameters:
- Raises:
Exception – Whatever opening the run record raised — after it was warned and recorded (see module docstring).
- Return type:
- scitex.clew.on_session_close(status='success', exit_code=0, verbose=False, register=None, metadata=None)[source]
Hook called when a session closes.
- Parameters:
status (
str) – Final status (success, failed, error)exit_code (
int) – Exit code of the scriptverbose (
bool) – Kept for signature compatibility; failures are warned regardless.register (
bool|None) – If True, register session hashes with remote Clew Registry. If None, checks SCITEX_AUTO_REGISTER environment variable.metadata (
dict|None) – Close-time payload (e.g.{"hook_failures": [...]}/{"capture_errors": [...]}) merged into the run’s metadata.
- Raises:
Exception – Whatever finalizing the run raised — after it was warned and recorded.
- Return type:
- scitex.clew.recover_journals(dry_run=False)[source]
Replay the journals of dead processes (see
_recover).
- scitex.clew.project_root(root)[source]
Run clew calls against
root’s project withoutchdir.Inside the block, the project scope (claims, runs, the per-project id and claims.json export location) resolves from
rootinstead of the current working directory.Noneis a no-op. Context-local, so it is safe across threads / asyncio tasks (unlikeos.chdir).
- scitex.clew.project_root_info(start=None)[source]
The project root clew uses here, and WHICH RULE chose it.
Order: an explicit
project_root()block > the active scitex-session’s recorded root > the standalone rule ofscitex_clew._core._project_root, resolved fromstart(default: the working directory).Returns
project_root,project_root_source(the rule:argument/env/git/marker/cwd/script_dir),project_root_markerandvia(argument/session/detected).- Return type: