xrf-visualizer 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. xrf_visualizer-0.1.0/.github/workflows/ci.yml +44 -0
  2. xrf_visualizer-0.1.0/.github/workflows/publish-testpypi.yml +61 -0
  3. xrf_visualizer-0.1.0/.github/workflows/publish.yml +59 -0
  4. xrf_visualizer-0.1.0/.gitignore +41 -0
  5. xrf_visualizer-0.1.0/.python-version +1 -0
  6. xrf_visualizer-0.1.0/AGENTS.md +284 -0
  7. xrf_visualizer-0.1.0/LICENSE +21 -0
  8. xrf_visualizer-0.1.0/PKG-INFO +252 -0
  9. xrf_visualizer-0.1.0/README.md +230 -0
  10. xrf_visualizer-0.1.0/deploy/apptainer/README.md +25 -0
  11. xrf_visualizer-0.1.0/deploy/apptainer/xrf-viz.def +14 -0
  12. xrf_visualizer-0.1.0/deploy/docker/Dockerfile +14 -0
  13. xrf_visualizer-0.1.0/deploy/docker/README.md +30 -0
  14. xrf_visualizer-0.1.0/deploy/how_to_deploy_apptainer.md +73 -0
  15. xrf_visualizer-0.1.0/deploy/how_to_deploy_docker.md +68 -0
  16. xrf_visualizer-0.1.0/deploy/how_to_deploy_pip.md +78 -0
  17. xrf_visualizer-0.1.0/deploy/how_to_deploy_uv.md +57 -0
  18. xrf_visualizer-0.1.0/deploy/how_to_deploy_wslc.md +73 -0
  19. xrf_visualizer-0.1.0/deploy/uv/README.md +64 -0
  20. xrf_visualizer-0.1.0/deploy/wslc/Containerfile +14 -0
  21. xrf_visualizer-0.1.0/deploy/wslc/README.md +33 -0
  22. xrf_visualizer-0.1.0/example.ipynb +146 -0
  23. xrf_visualizer-0.1.0/first_prompt_general_rules.md +29 -0
  24. xrf_visualizer-0.1.0/first_prompt_telegram.md +26 -0
  25. xrf_visualizer-0.1.0/operational_plan.md +200 -0
  26. xrf_visualizer-0.1.0/pyproject.toml +47 -0
  27. xrf_visualizer-0.1.0/scientific_notes.md +109 -0
  28. xrf_visualizer-0.1.0/src/xrf_visualizer/__init__.py +6 -0
  29. xrf_visualizer-0.1.0/src/xrf_visualizer/data/XRFlines.json +1390 -0
  30. xrf_visualizer-0.1.0/src/xrf_visualizer/data/__init__.py +166 -0
  31. xrf_visualizer-0.1.0/src/xrf_visualizer/processing/__init__.py +22 -0
  32. xrf_visualizer-0.1.0/src/xrf_visualizer/processing/backend.py +32 -0
  33. xrf_visualizer-0.1.0/src/xrf_visualizer/processing/reductions.py +91 -0
  34. xrf_visualizer-0.1.0/src/xrf_visualizer/ui/__init__.py +4 -0
  35. xrf_visualizer-0.1.0/src/xrf_visualizer/ui/app.py +1118 -0
  36. xrf_visualizer-0.1.0/tests/fixtures/golden.json +14231 -0
  37. xrf_visualizer-0.1.0/tests/fixtures/synthetic_cube.h5 +0 -0
  38. xrf_visualizer-0.1.0/tests/fixtures/synthetic_cube.npy +0 -0
  39. xrf_visualizer-0.1.0/tests/fixtures/synthetic_cube.npz +0 -0
  40. xrf_visualizer-0.1.0/tests/make_fixture.py +86 -0
  41. xrf_visualizer-0.1.0/tests/test_baseline_reductions.py +110 -0
  42. xrf_visualizer-0.1.0/tests/test_fixture_consistency.py +17 -0
  43. xrf_visualizer-0.1.0/tests/test_processing.py +154 -0
  44. xrf_visualizer-0.1.0/tests/test_readers.py +92 -0
  45. xrf_visualizer-0.1.0/tests/test_transfer.py +99 -0
  46. xrf_visualizer-0.1.0/tests/test_ui_app.py +714 -0
  47. xrf_visualizer-0.1.0/timeline.md +213 -0
  48. xrf_visualizer-0.1.0/to_do.md +70 -0
  49. xrf_visualizer-0.1.0/uv.lock +1105 -0
@@ -0,0 +1,44 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ pull_request:
6
+ workflow_dispatch:
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ test-and-build:
13
+ runs-on: ubuntu-latest
14
+ strategy:
15
+ fail-fast: false
16
+ matrix:
17
+ python-version: ["3.12", "3.13"]
18
+ steps:
19
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
20
+ - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
21
+ with:
22
+ enable-cache: true
23
+ - run: uv python install ${{ matrix.python-version }}
24
+ - run: uv sync --locked --python ${{ matrix.python-version }}
25
+ - run: uv run --locked --python ${{ matrix.python-version }} pytest -q
26
+ - run: uv build
27
+ - name: Validate built distributions
28
+ run: |
29
+ uvx --from twine twine check dist/*
30
+ python - <<'PY'
31
+ import tarfile
32
+ import zipfile
33
+ from pathlib import Path
34
+
35
+ wheel, source = list(Path("dist").glob("*.whl")), list(Path("dist").glob("*.tar.gz"))
36
+ assert len(wheel) == len(source) == 1
37
+ assert any(name.endswith("xrf_visualizer/data/XRFlines.json") for name in zipfile.ZipFile(wheel[0]).namelist())
38
+ assert any(name.endswith("xrf_visualizer/data/XRFlines.json") for name in tarfile.open(source[0]).getnames())
39
+ PY
40
+ - uses: actions/upload-artifact@v4
41
+ with:
42
+ name: dist-py${{ matrix.python-version }}
43
+ path: dist/*
44
+ if-no-files-found: error
@@ -0,0 +1,61 @@
1
+ name: Publish to TestPyPI
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ inputs:
6
+ tag:
7
+ description: Version tag to test (for example v0.1.0)
8
+ required: true
9
+ type: string
10
+
11
+ permissions:
12
+ contents: read
13
+
14
+ jobs:
15
+ build:
16
+ runs-on: ubuntu-latest
17
+ steps:
18
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
19
+ with:
20
+ ref: ${{ inputs.tag }}
21
+ - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
22
+ with:
23
+ enable-cache: true
24
+ - name: Verify tag matches package version
25
+ env:
26
+ RELEASE_TAG: ${{ inputs.tag }}
27
+ run: |
28
+ test "$(git describe --tags --exact-match HEAD)" = "$RELEASE_TAG"
29
+ python - <<'PY'
30
+ import os
31
+ import tomllib
32
+ from pathlib import Path
33
+
34
+ version = tomllib.loads(Path("pyproject.toml").read_text())["project"]["version"]
35
+ assert f"v{version}" == os.environ["RELEASE_TAG"], f"tag v{version} does not match input {os.environ['RELEASE_TAG']}"
36
+ PY
37
+ - run: uv build
38
+ - run: uvx --from twine twine check dist/*
39
+ - uses: actions/upload-artifact@v4
40
+ with:
41
+ name: testpypi-dist
42
+ path: dist/*
43
+ if-no-files-found: error
44
+
45
+ publish:
46
+ needs: build
47
+ runs-on: ubuntu-latest
48
+ environment:
49
+ name: testpypi
50
+ url: https://test.pypi.org/p/xrf-visualizer
51
+ permissions:
52
+ contents: read
53
+ id-token: write
54
+ steps:
55
+ - uses: actions/download-artifact@v4
56
+ with:
57
+ name: testpypi-dist
58
+ path: dist
59
+ - uses: pypa/gh-action-pypi-publish@release/v1
60
+ with:
61
+ repository-url: https://test.pypi.org/legacy/
@@ -0,0 +1,59 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ inputs:
6
+ tag:
7
+ description: Reviewed version tag to publish (for example v0.1.0)
8
+ required: true
9
+ type: string
10
+
11
+ permissions:
12
+ contents: read
13
+
14
+ jobs:
15
+ build:
16
+ runs-on: ubuntu-latest
17
+ steps:
18
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
19
+ with:
20
+ ref: ${{ inputs.tag }}
21
+ - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
22
+ with:
23
+ enable-cache: true
24
+ - name: Verify tag matches package version
25
+ env:
26
+ RELEASE_TAG: ${{ inputs.tag }}
27
+ run: |
28
+ test "$(git describe --tags --exact-match HEAD)" = "$RELEASE_TAG"
29
+ python - <<'PY'
30
+ import os
31
+ import tomllib
32
+ from pathlib import Path
33
+
34
+ version = tomllib.loads(Path("pyproject.toml").read_text())["project"]["version"]
35
+ assert f"v{version}" == os.environ["RELEASE_TAG"], f"tag v{version} does not match input {os.environ['RELEASE_TAG']}"
36
+ PY
37
+ - run: uv build
38
+ - run: uvx --from twine twine check dist/*
39
+ - uses: actions/upload-artifact@v4
40
+ with:
41
+ name: pypi-dist
42
+ path: dist/*
43
+ if-no-files-found: error
44
+
45
+ publish:
46
+ needs: build
47
+ runs-on: ubuntu-latest
48
+ environment:
49
+ name: pypi
50
+ url: https://pypi.org/project/xrf-visualizer/
51
+ permissions:
52
+ contents: read
53
+ id-token: write
54
+ steps:
55
+ - uses: actions/download-artifact@v4
56
+ with:
57
+ name: pypi-dist
58
+ path: dist
59
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,41 @@
1
+ # Merge with the existing repository .gitignore; do not blindly overwrite it.
2
+
3
+ # Bootstrap/reference-only original. Never use as the runtime source package.
4
+ /dash-xrf-analyzer/
5
+
6
+ # example data
7
+ data_example/
8
+
9
+ # Python cache, test/build output and local Python environments
10
+ __pycache__/
11
+ *.py[cod]
12
+ .ipynb_checkpoints/
13
+ .pytest_cache/
14
+ .ruff_cache/
15
+ .mypy_cache/
16
+ .coverage
17
+ htmlcov/
18
+ .venv/
19
+ venv/
20
+ build/
21
+ dist/
22
+ *.egg-info/
23
+ # added by ale
24
+ .windows-env/
25
+ windows-env/
26
+
27
+ # Local/editor files
28
+ .DS_Store
29
+ .vscode/
30
+
31
+ # Generated XRF outputs (dedicated, not raw inputs)
32
+ /outputs/
33
+ /results/
34
+ /data/raw/
35
+
36
+ # Optional LaTeX output
37
+ /notes/build/
38
+
39
+ # Do NOT ignore pyproject.toml or uv.lock: lock file must be versioned.
40
+ # Do NOT globally ignore .h5/.hdf5/.npy/.npz: allow small reviewed tests/fixtures.
41
+ # Check whether legacy files are already tracked: .gitignore alone will not untrack.
@@ -0,0 +1 @@
1
+ 3.12
@@ -0,0 +1,284 @@
1
+ # Project agent rules — XRF-only Dash / Jupyter / JAX refactor
2
+
3
+ These rules apply to Hermes and any other agent working in the XRF visualizer repository. Prioritize scientific correctness, readable maintainable Python, resource limits, reproducibility and user-authorized scope over speed. **M0–M28 completed (2026-11-10/13):** data readers, JAX float64 processing, Dash UI and callbacks, calibration/line-window selection, full-field multi-line map/spectrum gallery with ZIP export, scale and ROI controls, square-pixel rectangular selection, matrix-exact PNG export, and user-confirmed notebook fixes for calibration and log-scale behavior. WSLC was user-tested; Docker and Apptainer recipes remain NOT TESTED. `operational_plan.md` is the single source of truth for exact feature decisions and the proposed layout. The legacy repository was audited read-only during M0; findings are in `scientific_notes.md` and `timeline.md`.
4
+
5
+ ## Project snapshot — original user requirements (implementation status in README/timeline)
6
+
7
+ - Repository root as seen by Hermes: `/workspace/exchange/dash-xrf-visualizer`; verify first.
8
+ - Goal: **visualizer only**. Retain HDF5 XRF reading, left 2-D intensity map, right spectrum, spectral interval selection → map recomputation, spatial ROI selection → spectrum recomputation; **add** `.npz` / `.npy` support.
9
+ - **Remove AIRES** and its model/training/inference UI/dependencies after collecting baseline evidence and receiving implementation authorization. This feature-removal decision has **already** been made by the user; do not ask whether to keep AIRES. Postpone legacy custom-file ingestion.
10
+ - Preferred execution: JupyterLab notebook with a Python `path_to_file` variable, Dash built-in Jupyter integration, JAX numerical kernels with correct actual CPU/GPU backend detection.
11
+ - Target layout: minimal root; `src/xrf_visualizer/` for importable package, **separate** `data/`, `processing/`, `ui/layout.py`, `ui/callbacks.py` and `ui/figures.py` where justified; `tests/` (conventional plural), and `deploy/docker/`, `deploy/wslc/`, `deploy/apptainer/`, `deploy/uv/`. `pyproject.toml` and tracked `uv.lock` belong to repository root.
12
+ - Root-relative `dash-xrf-analyzer/` is *legacy bootstrap/reference only*: inspect read-only if useful, never depend on it in new code, and ignore in `.gitignore`. Never remove it until the user explicitly requests deletion; ignoring tracked files may require a separately approved Git index action.
13
+ - Container recipes for Docker, Microsoft's WSLC and Apptainer are documentation/build deliverables, **not execution/test claims**. Hermes can use `uv` **after explicit M0 approval** to create the local environment and Jupyter kernel, but may not install anything in M0.
14
+
15
+ ## XRF-specific invariants and engineering rules
16
+
17
+ 1. **M0 audit only:** verify project path and `git status`, map actual entry points/callbacks/file schema and AIRES connections, inspect only small file metadata/slices, report evidenced findings and M1 plan. NO modifications, package installs, downloads, servers, commits or pushes. STOP for approval.
18
+ 2. **Scope is already decided:** don't ask the user to reapprove the basic visualizer features above. Escalate only unverified file layouts, ambiguous algorithms/units, ROI interaction semantics or other truly new functionality.
19
+ 3. **Scientific fidelity:** distinguish discrete channel sums versus energy-weighted integration, axis order, calibration metadata, normalization, dtype, NaN/Inf behavior, empty selections and spatial mask semantics. Preserve read-only raw data and establish deterministic synthetic/golden tests.
20
+ 4. **Real separation of concerns:** file readers and schema validation should not import Dash; numerical kernels should not import UI; layout should not perform numerical processing; callbacks bind UI state to pure transforms; Plotly figure construction is separate where it improves clarity. Do not create boilerplate submodules just to mirror a diagram.
21
+ 5. **Notebook user experience:** public API accepts a Python string/Path; no file reads, server start or JAX compilation on package import. Prefer modern built-in Dash notebook integration (when supported) and account for kernel reruns, port conflicts and proxy/containers.
22
+ 6. **JAX where appropriate:** use JAX for retained numerical reductions; NumPy/h5py may remain for loading, conversion and plotting. Remove PyTorch if only used by AIRES. Inspect actual JAX devices in notebook/kernel, prefer usable GPU, otherwise CPU; log backend explicitly, never promise untested acceleration. Control copies/compilations and precision.
23
+ 7. **uv / deploy:** `pyproject.toml` and committed `uv.lock` in root, `.venv/` ignored. Document `uv sync`, `ipykernel`, kernel registration and notebook use once authorized; isolate Docker, Compose, WSLC `Containerfile` and Apptainer definition. No claim of tested runtime where tools are absent.
24
+ 8. **Document roles:** `AGENTS.md` = stable rules; `operational_plan.md` = detailed agreed intent; `to_do.md` = near-term actions; `timeline.md` = historical evidence; `README.md` = human guide (bootstrap version to be replaced only when authorized). Synchronize meaningfully without duplicating huge text.
25
+
26
+ ## 0. Bootstrap, context and document ownership
27
+
28
+ Start by identifying which of these evidence paths applies:
29
+
30
+ - **Code-first:** the repository already contains code, tests or data contracts. Inspect
31
+ it read-only first; infer only what is supported by observable behavior and docs.
32
+ - **Plan-first:** the user supplies a research question, proposed methodology or a
33
+ populated `operational_plan.md`. Treat it as *intended work*, not completed results.
34
+ Critically review assumptions, literature, baseline parity and feasibility.
35
+ - **Hybrid:** both exist; compare the plan to the code and flag conflicts explicitly.
36
+
37
+ Read `operational_plan.md`, `to_do.md`, `timeline.md` and applicable project docs.
38
+ Use `scientific_notes.md` only when scientific notes are relevant. The optional
39
+ `first_prompt_general_rules.md` summarizes this file; it never supersedes it.
40
+
41
+ **Document roles and synchronization:** `AGENTS.md` defines enduring agent rules;
42
+ `operational_plan.md` defines scientific/technical intent, requirements, evaluation
43
+ and milestones; `to_do.md` tracks near-term prospective actions; `timeline.md` is an
44
+ evidence-backed retrospective; `README.md` explains the actual project to humans.
45
+ When scope changes, update the **affected** Markdown files coherently, rather than
46
+ copying long text into all of them. If `README.md` contains the marker
47
+ `BOOTSTRAP_TEMPLATE_README`, it is a temporary template instruction guide; once
48
+ initialization edits are authorized, **replace** it with a project-specific README.
49
+ If a real README already exists, preserve it and update only what is justified.
50
+
51
+ During the first interaction, inspect in read-only mode and propose a small
52
+ initialization plan. Do not rewrite docs, code or data until the user authorizes
53
+ that scope, unless the user has already explicitly requested those edits. Never
54
+ invent project facts to fill template placeholders; label unknowns as `TBD`.
55
+
56
+ ## 1. Start with evidence, not implementation
57
+
58
+ - Inspect the relevant project files, `git status` (if applicable), and existing scripts before proposing changes.
59
+ - Identify the objective, available data, current workflow, constraints, and what is already implemented.
60
+ - Inspect data incrementally: filenames, schemas, shapes, types, missing values, and small samples first.
61
+ Do not dump entire datasets into the conversation or into external services.
62
+ - For nontrivial tasks, briefly state the intended approach and an explicit definition of done.
63
+ - Reuse the project's tools and conventions; do not introduce a new architecture to solve a local problem.
64
+ - Ask for a decision when requirements, scientific methodology, or data permissions are genuinely ambiguous.
65
+
66
+ ## 2. Lean, human-readable code
67
+
68
+ **Write the least code that clearly solves the problem.** Code must be easy for a researcher
69
+ or maintainer to read and change, not impressive or over-engineered.
70
+
71
+ - Use descriptive English identifiers; avoid cryptic abbreviations (standard scientific terms are fine).
72
+ Name booleans as predicates (`is_valid`), and functions with clear verbs (`load_data`, `fit_model`).
73
+ - Follow the project language/framework conventions; for Python, follow PEP 8.
74
+ Prefer straightforward control flow.
75
+ - Favor simple functions and standard data structures. Introduce a class only when it captures
76
+ meaningful state, lifecycle, or behavior. Prefer composition over deep inheritance.
77
+ - A function should have one coherent responsibility; **do not** split simple logic into
78
+ gratuitous wrappers or single-use microfunctions.
79
+ - Use Python's standard library and already-installed project dependencies first.
80
+ Do **not** add, upgrade, or install dependencies unless necessary and explicitly approved.
81
+ Do not reimplement reliable functionality already available in the existing stack.
82
+ - Avoid premature generalization, speculative features, plugin systems, elaborate configuration,
83
+ excess defensive scaffolding, and compatibility layers with no demonstrated need.
84
+ - Reduce duplication where the common abstraction actually simplifies the code; a little
85
+ repetition is preferable to a complicated abstraction.
86
+ - Keep related code close together; do not create files or packages solely to appear modular.
87
+ - Use explicit inputs/outputs, limited side effects, and no unnecessary global mutable state.
88
+ Avoid surprising boolean mode flags when clearer interfaces are available.
89
+ - Use exceptions idiomatically: fail early on invalid inputs; catch only errors you can handle
90
+ meaningfully; never silently swallow a failure or use broad `except` without justification.
91
+ - Comments should explain **why**, assumptions, non-obvious formulas, and scientific decisions,
92
+ not restate the code. Use useful docstrings for public or non-obvious interfaces.
93
+ - Optimize for readability first. Optimize performance only after identifying a bottleneck.
94
+
95
+ ### Mandatory simplification pass
96
+
97
+ After each meaningful implementation milestone, perform **one focused cleanup pass**:
98
+
99
+ 1. Remove dead code, unused imports, duplicate logic, unnecessary helpers, and obsolete comments.
100
+ 2. Simplify complex control flow and misleading names without changing validated behavior.
101
+ 3. Review the diff: can any new file, abstraction, dependency, or line be avoided?
102
+ 4. Run the smallest relevant verification after cleanup, then stop. Do not endlessly refactor.
103
+
104
+ ### Optional Ponytail-assisted review
105
+
106
+ - When Ponytail is **already installed and available in the active agent**, use its
107
+ lean-code principles during implementation and **prefer one focused Ponytail review**
108
+ (`/ponytail-review`, or the equivalent available skill) after a meaningful code milestone.
109
+ - For Hermes, use Ponytail **directly only if its skill is available**; otherwise, when
110
+ delegating coding to an OpenCode instance that has the plugin, request the review
111
+ through OpenCode. Installing Ponytail in OpenCode does **not** automatically install
112
+ the skill in Hermes. Do not assume the same slash commands work in both agents.
113
+ - Use `/ponytail-audit` only for an explicitly requested repository-wide audit, not
114
+ as a default step. Never trigger repeated reviews, recursive delegation, or extra
115
+ refactoring loops. The mandatory simplification pass and Ponytail review should be
116
+ **the same bounded activity**, not two separate cleanup cycles.
117
+ - Treat Ponytail as a reviewer, not as an authority that overrides scientific validity,
118
+ reproducibility, safety, existing conventions, or the agreed scope. Prefer its
119
+ actionable findings; reject cosmetic or speculative changes that add work.
120
+ - If Ponytail is absent or unavailable, continue normally with the rules above.
121
+ **Do not install plugins, add dependencies, or change configuration without approval.**
122
+
123
+ ## 3. Scientific rigor and reproducibility
124
+
125
+ - Distinguish observations, hypotheses, implementation choices, and conclusions.
126
+ - Never invent measurements, citations, experimental results, or claims of successful execution.
127
+ - Record essential provenance: data origin/version, preprocessing, experimental conditions,
128
+ models, hyperparameters, random seeds, and software versions when relevant.
129
+ - Avoid data leakage; keep training, validation, and test roles clear. Never use the test set
130
+ for iterative model selection. Compare against a meaningful baseline when appropriate.
131
+ - Report metrics with units, sample sizes, uncertainty or variability where warranted,
132
+ and limitations. Document negative or inconclusive findings rather than hiding them.
133
+ - Keep raw inputs unchanged. Write derived data and results to separate, clearly named paths.
134
+ Do not overwrite existing outputs or human work without checking and obtaining approval.
135
+ - Prefer scripts or notebooks that can be rerun with documented inputs and commands.
136
+ Do not create a new framework or packaging layer just for reproducibility.
137
+
138
+ ## 4. Bounded testing and autonomous work
139
+
140
+ Tests and scientific checks are important, but **testing is not an end in itself**.
141
+
142
+ - Before executing a task, choose the smallest checks that demonstrate the requested behavior:
143
+ usually a smoke test, one or two targeted checks, and a relevant scientific sanity check.
144
+ - Prefer existing tests and fixtures. Add a test only for an actual failure mode, scientific
145
+ invariant, or meaningful regression risk; do not chase arbitrary coverage percentages.
146
+ - Run each relevant check once after a change. On failure, investigate and allow at most
147
+ **two focused fix-and-retest cycles for the same failure**. If still unresolved, stop,
148
+ record the evidence and blocker, and ask the user what to do next.
149
+ - Do not repeatedly run almost-identical experiments hoping for a better outcome.
150
+ Before expensive experiments, establish a finite budget (runs, seeds, time/compute) and
151
+ clear stopping criteria with the user if not already specified.
152
+ - Never launch unattended long-running tasks, large hyperparameter sweeps, recursive
153
+ subagents, or indefinite loops without explicit authorization and resource limits.
154
+ - A completed milestone with documented limitations is better than uncontrolled retries.
155
+ If the agreed acceptance criteria pass, **stop** instead of inventing more work.
156
+
157
+ ## 5. Resource awareness and execution budget
158
+
159
+ **Inspect before launching; budget before scaling; monitor while running.**
160
+ Available hardware is not automatically authorized capacity. Apply these rules to local machines,
161
+ containers, WSL, shared servers, schedulers, and cloud environments. Keep checks proportional:
162
+ small inspections and bounded smoke tests need not become an elaborate profiling exercise.
163
+
164
+ ### Preflight: effective resource limits
165
+
166
+ Before any nontrivial computation, data movement, or parallel job:
167
+
168
+ - **Environment and ownership:** Identify the execution context, applicable quotas or scheduler
169
+ allocation, current resource consumers, and whether an equivalent job is already running.
170
+ Respect shared workloads and existing jobs; never start duplicate experiments blindly.
171
+ - **CPU:** Check effective CPU availability (affinity/cpuset, cgroup quota, scheduler allocation,
172
+ and current load), not `nproc` or host logical-core count alone. Set explicit limits for
173
+ processes, MPI ranks, data-loader workers, and numerical-library threads. Avoid CPU
174
+ oversubscription and nested MPI/OpenMP/BLAS parallelism unless measured to be beneficial.
175
+ - **GPU and VRAM:** For GPU workloads, inspect visible/allocated devices, current utilization,
176
+ free VRAM, competing processes, and applicable GPU partition or scheduler limits. Estimate
177
+ model, batch, activation, and optimizer memory before training; do not assume a visible GPU
178
+ is idle or exclusively available.
179
+ - **RAM:** Check available system memory, process/container/job memory limits, and swap pressure
180
+ where relevant. Estimate peak memory, including duplicated worker state, caching, and temporary
181
+ arrays. Leave headroom; avoid configurations likely to trigger swapping or OOM termination.
182
+ - **Storage and I/O:** Check free space, quotas, and inode availability on the *actual* input,
183
+ output, cache, temporary, and checkpoint filesystems. Estimate download, intermediate, and
184
+ output sizes. Consider disk throughput, concurrent I/O, and shared/network-filesystem load;
185
+ prevent unbounded logs, temporary files, and excessive small or HDF5 writes.
186
+ - **Uncertain capacity:** If effective limits or resource ownership cannot be established,
187
+ restrict work to lightweight diagnostics or a conservative smoke test; do not launch a heavy job.
188
+
189
+ ### Authorization and bounded execution
190
+
191
+ - **Resource gate:** Do not start bulk downloads, dependency/environment installations, GPU
192
+ training, large CPU/MPI simulations, extensive sweeps, cloud uploads, or unattended long-running
193
+ jobs without explicit user authorization of the scope and resource budget. An existing,
194
+ sufficiently specific authorization need not be requested again. Small, bounded inspections
195
+ and local synthetic-data checks are allowed within the current task.
196
+ - Before expensive work, establish finite bounds for relevant dimensions: runtime, concurrency,
197
+ CPU/GPU usage, memory, disk space/I/O, transfer size, runs/seeds, and stopping criteria.
198
+ If the estimate exceeds the approved budget, stop and request a decision; do not silently scale.
199
+ - Start with the smallest representative smoke test. Increase dataset size, batch size, worker
200
+ count, MPI ranks, or concurrency only after checking correctness, throughput, and resource use.
201
+ For MPI jobs, start with one thread per rank (`OMP_NUM_THREADS=1`,
202
+ `OPENBLAS_NUM_THREADS=1`) unless the workload has an established, measured configuration.
203
+ - When a scheduler or orchestrator is present, request and stay within its allocation; do not
204
+ bypass quotas by launching unmanaged workers, subprocess trees, or parallel agents.
205
+
206
+ ### Monitoring, recovery, and cleanup
207
+
208
+ - For substantial jobs, monitor useful progress (not CPU utilization alone), elapsed time,
209
+ CPU/GPU load, RAM/VRAM, swapping, disk activity, output growth, and error logs. Detect stalls,
210
+ runaway subprocesses, resource contention, and unexpected I/O amplification.
211
+ - Stop or downscale promptly on sustained stalls, resource exhaustion risk, or exceeded budgets.
212
+ Prefer resumable outputs and appropriately spaced checkpoints; avoid checkpoint/write storms.
213
+ - Before restarting, inspect existing processes, partial outputs, logs, and checkpoints.
214
+ Never launch a second copy or repeatedly retry expensive failures without renewed approval.
215
+ Clean up only temporary resources owned by the task; do not kill unrelated processes.
216
+ - Record material resource settings, observed limits or bottlenecks, and the actual outcome when
217
+ relevant to reproducibility. Report when an execution was skipped or halted for resource reasons.
218
+
219
+ ## 6. Documentation: concise, scientific, maintained
220
+
221
+ - Document important decisions, assumptions, methods, results, limitations, and reproducible
222
+ commands. Keep explanations compact but sufficient to audit the work months later.
223
+ - Prefer updating an existing genuine README or relevant document to creating another
224
+ overlapping file. Replace a bootstrap README with a project-specific one after
225
+ initialization is authorized; do not retain template prose in the real README.
226
+ - After a meaningful milestone, update `timeline.md` with a short, dated, factual entry.
227
+ - Revisit `operational_plan.md` when the scientific scope, method, baseline, evaluation
228
+ or major milestones change; do not rewrite it for every small coding task.
229
+ - Maintain `to_do.md` only when a multi-step plan is useful; keep it actionable and current.
230
+ Do not turn it into a second activity log.
231
+ - Periodically (e.g., every 3 milestones, or before changing direction) reread `timeline.md`,
232
+ check the outstanding tasks, summarize the key findings, and prune obsolete plans.
233
+ - Ensure documentation agrees with the code and actual experiments. Never describe planned
234
+ results as completed results.
235
+
236
+ ### `timeline.md`: retrospective record
237
+
238
+ Append entries in chronological order. Each entry should include, as applicable:
239
+ - Date and milestone / question addressed.
240
+ - Changes made and relevant paths or commit references.
241
+ - Validation or experiment performed (commands, data, seeds, outcome).
242
+ - Scientific observations, decisions, limitations, and unresolved blockers.
243
+ - A concise next step, only if useful.
244
+
245
+ Do not fabricate entries, retroactively rewrite outcomes, or log trivial edits.
246
+
247
+ ### `to_do.md`: prospective plan (optional)
248
+
249
+ - Keep a short list of **Now / Next / Later / Blocked** items.
250
+ - Every active task should have a clear deliverable or criterion for completion.
251
+ - Mark completed tasks and move important outcomes to `timeline.md` rather than accumulating
252
+ an exhaustive history in `to_do.md`.
253
+ - Revise the plan when evidence changes; avoid detailed schedules without a concrete need.
254
+
255
+ ## 7. Safety and scope
256
+
257
+ - Treat original datasets as read-only unless the user expressly authorizes modifications.
258
+ - Never delete, overwrite, migrate, publish, or upload files outside the agreed scope.
259
+ Confirm before destructive commands, changing permissions, `sudo`, or network installs.
260
+ - Do not expose API keys, passwords, private identifiers, or sensitive dataset contents.
261
+ Verify authorization before sending restricted material to external services or models.
262
+ - Do not overwrite unrelated Git changes. Inspect the diff before reporting completion.
263
+ - Do not `git push`, merge to protected branches, publish releases or open public PRs
264
+ unless the user has authorized that external action; never commit secrets.
265
+ - Delegate to OpenCode or other agents only for a clearly bounded subtask; require a concise
266
+ summary and review the resulting changes. Avoid uncontrolled chains of delegation.
267
+
268
+ ## 8. End-of-task report
269
+
270
+ At the end of each milestone, report briefly:
271
+
272
+ 1. **Done:** what changed and where.
273
+ 2. **Evidence:** tests/experiments run and their actual outcomes.
274
+ 3. **Caveats:** uncertainties, failures, or unverified claims.
275
+ 4. **Next:** the single most useful follow-up, or say that the task is complete.
276
+
277
+ Do not claim tests ran unless they actually ran. Do not continue autonomously after the
278
+ agreed task is complete.
279
+
280
+ ## References (adapted, not copied verbatim)
281
+
282
+ - https://gist.github.com/evaera/fee751d4e228dd262fe1174ba142a719
283
+ - https://www.pyopensci.org/lessons/write-better-code/clean-modular-code/index.html
284
+ - https://peps.python.org/pep-0008/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alessandro Bombini
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.