diff --git a/.github/workflows/board_tests.yml b/.github/workflows/board_tests.yml index 89ee247..6cd20f0 100644 --- a/.github/workflows/board_tests.yml +++ b/.github/workflows/board_tests.yml @@ -14,9 +14,16 @@ jobs: with: repository: PyAutoLabs/PyAutoBrain path: PyAutoBrain + # Canonical repository identity input; relationships remain in Scientist. + - uses: actions/checkout@v4 + with: + repository: PyAutoLabs/PyAutoMind + path: PyAutoMind + - uses: actions/setup-python@v5 with: python-version: '3.12' - run: python -m pip install pytest pyyaml + - run: python scripts/organism_board.py --repos PyAutoMind/repos.yaml --check-projects - run: python -m pytest tests -q - run: node --test tests/overview.cjs diff --git a/.github/workflows/organism_board.yml b/.github/workflows/organism_board.yml index db76b26..8fd3dd9 100644 --- a/.github/workflows/organism_board.yml +++ b/.github/workflows/organism_board.yml @@ -42,16 +42,24 @@ jobs: repository: PyAutoLabs/PyAutoBrain path: PyAutoBrain + # Canonical repository identity input; relationships remain in Scientist. + - uses: actions/checkout@v4 + with: + repository: PyAutoLabs/PyAutoMind + path: PyAutoMind + - uses: actions/setup-python@v5 with: python-version: "3.12" + - run: python -m pip install pyyaml + - name: Render every surface (public HTTPS only) run: | mkdir -p _site - python scripts/organism_board.py --html > _site/index.html - python scripts/organism_board.py --badge > _site/badge.json - python scripts/organism_board.py --md > board.md + python scripts/organism_board.py --repos PyAutoMind/repos.yaml --html > _site/index.html + python scripts/organism_board.py --repos PyAutoMind/repos.yaml --badge > _site/badge.json + python scripts/organism_board.py --repos PyAutoMind/repos.yaml --md > board.md cp board.md _site/dashboard.md - name: Write the board to the job step summary diff --git a/PROJECTS.md b/PROJECTS.md new file mode 100644 index 0000000..bba91e3 --- /dev/null +++ b/PROJECTS.md @@ -0,0 +1,111 @@ +# Connected projects + +The Scientist home shows **software families** and, when explicitly configured, +**scientific investigations** as separate kinds of project. A software family +is not a Cortex investigation. Cards are a navigational inventory; source +repositories and organs retain their authoritative records. An empty card means +no public resources were configured, not that work or evidence does not exist. + +## Connect or change a project + +Edit the instance-owned `config/projects.json`. Keep stable IDs when renaming a +project or resource. Add repository identities to your canonical Mind +`repos.yaml`, then refer to those keys here; never copy GitHub owners/remotes +into a second repository inventory. Resource IDs can appear in multiple project +cards, including as shared dependencies. Associations are curated, not a complete +package dependency lockfile and not inferred from naming prefixes. + +Each project has `name`, `kind` (`software_family` or `scientific_project`), +optional `description`, `public`, and a `resources` object. Its optional lists +are `software`, `dependencies`, `workspaces`, `tutorials`, `documentation`, +`assistants` and `records`. Each list contains resource IDs, in display order. +An assistant is never required. An empty project catalogue is supported. + +Each resource has `name`, `public`, and one or both of: + +- `repo`: a key from the canonical identity map. Optional repository-relative + `path` and `ref` point at a folder or file. With a path and no ref, `main` is + used; set ref explicitly for other default branches or a pinned revision. +- `published_url`: an explicit HTTPS destination, such as external documentation + or an owning organ's board. This is a published location, not a second repo ID. + +The version-1 format is a JSON object with `schema_version: 1`, `resources` +and `projects` objects keyed by stable lowercase, hyphen-separated IDs. +For example, given `analysis-code` in your own identity map: + +```json +{ + "schema_version": 1, + "resources": { + "analysis-guide": { + "name": "Analysis guide", "repo": "analysis-code", + "path": "docs", "ref": "main", "public": true + } + }, + "projects": { + "spectra": { + "name": "Spectra", "kind": "scientific_project", "public": true, + "resources": {"documentation": ["analysis-guide"]} + } + } +} +``` + +Validate without collecting feeds: + +```bash +python scripts/organism_board.py --projects config/projects.json \ + --repos /path/to/YourMind/repos.yaml --check-projects +``` + +Use the same arguments with `--html`, `--md` or `--json` to render. A configured +workspace can supply `PYAUTO_MIND`; otherwise Brain's manifest-backed resolver +locates Mind. An unavailable map or invalid relationship fails rendering instead +of publishing a misleading empty catalogue. Rendering never fetches linked +content or executes project code. Ordinary organ feed refresh remains unchanged. + +## Publication and ownership + +Only projects **and** resources explicitly marked `public: true` enter the +rendered snapshot. Omitted/false values exclude them from HTML, Markdown and +embedded JSON. This flag records an owner's publication decision; it does not +check remote repository permissions. Review links and metadata before enabling +it. The configuration in this repository is itself public: never put private +project details here, even under `public: false`. Use a private instance/local +configuration for private material. Connecting resources changes no permissions. + +Project repositories own software, docs, notebooks, scripts, assistant definitions +and runners. Scientist owns these explicit project associations and links. The +agreed Broca expansion covers communication/documentation relationships and +upkeep evidence, with documentation, tutorials, user-facing workspaces and +assistants as first-class surfaces. Its current published implementation still +covers assistant evidence; the broader contract and evidence migration are +separate Mind tasks. These IDs/categories provide a coordination point, not a +new Broca evidence schema or copied ledger. A shared Broca inventory link does +not imply a project-specific assessment. + +Ears retains listening and feedback collection; Brain interprets and routes; +Mind tracks implementation; Memory holds knowledge and citations; Cortex owns +scientific records and human conclusions; Eyes owns gallery evidence; Heart +owns readiness; Hands owns builds/releases. A project may link any relevant +owner record without transferring ownership. Inventory presence, technical +validation, freshness and explanatory quality remain distinct. No external +messages, publication actions, evaluation runs or setup actions happen on a +card click or dashboard refresh. + +## Adoption and upgrades + +`config/projects.json` is user-owned configuration. `scripts/project_resources.py` +is framework logic; it contains no project names, GitHub owners or repository +suffix assumptions. The canonical identity map remains independently owned in +Mind. Rename displays or change canonical locations without changing stable IDs. +Unsupported schema versions fail explicitly; an upgrade must preserve the +configuration and user records or supply a reviewable migration. + +This phase does **not** yet make the complete Scientist independently named or +organs optional. Existing hero branding, organ membership, check-in prompt, +workflow checkout identities and framework discovery still reflect the current +instance. Starter packaging, configurable capability locations, optional-organ +activation and record-preserving upgrades are recorded follow-ups. No +collaborator project or access is assumed. Shared multi-contributor operation is +a later milestone. diff --git a/README.md b/README.md index a7f0f59..bcadd8e 100644 --- a/README.md +++ b/README.md @@ -119,3 +119,7 @@ summary across all organs over the last 24 hours, a chosen date range, or help coordinating work across organs. [Reporting guidance](REPORTING.md) defines source coverage, event dates and concise evidence-linked summaries. Detailed work and authoritative records remain with each organ. + +## Connected projects + +The dashboard includes expandable project cards linking software, shared dependencies, documentation, tutorials, workspaces, assistants and owner records. See [the project configuration contract](PROJECTS.md) to connect resources; an assistant is optional and source records remain with their owners. diff --git a/config/projects.json b/config/projects.json new file mode 100644 index 0000000..c1d5983 --- /dev/null +++ b/config/projects.json @@ -0,0 +1,339 @@ +{ + "schema_version": 1, + "resources": { + "fit": { + "name": "PyAutoFit", + "public": true, + "repo": "PyAutoFit" + }, + "fit-workspace": { + "name": "autofit_workspace", + "public": true, + "repo": "autofit_workspace" + }, + "fit-tutorials": { + "name": "HowToFit", + "public": true, + "repo": "HowToFit" + }, + "fit-docs": { + "name": "PyAutoFit documentation", + "public": true, + "repo": "PyAutoFit", + "path": "docs", + "published_url": "https://pyautofit.readthedocs.io/en/latest/" + }, + "fit-assistant": { + "name": "autofit_assistant", + "public": true, + "repo": "autofit_assistant" + }, + "fit-profiling": { + "name": "autofit_profiling", + "public": true, + "repo": "autofit_profiling" + }, + "fit-inference": { + "name": "autofit_inference", + "public": true, + "repo": "autofit_inference" + }, + "fit-visualization": { + "name": "autofit_visualization", + "public": true, + "repo": "autofit_visualization" + }, + "array": { + "name": "PyAutoArray", + "public": true, + "repo": "PyAutoArray" + }, + "galaxy": { + "name": "PyAutoGalaxy", + "public": true, + "repo": "PyAutoGalaxy" + }, + "galaxy-workspace": { + "name": "autogalaxy_workspace", + "public": true, + "repo": "autogalaxy_workspace" + }, + "galaxy-tutorials": { + "name": "HowToGalaxy", + "public": true, + "repo": "HowToGalaxy" + }, + "galaxy-docs": { + "name": "PyAutoGalaxy documentation", + "public": true, + "repo": "PyAutoGalaxy", + "path": "docs", + "published_url": "https://pyautogalaxy.readthedocs.io/en/latest/" + }, + "galaxy-assistant": { + "name": "autogalaxy_assistant", + "public": true, + "repo": "autogalaxy_assistant" + }, + "lens": { + "name": "PyAutoLens", + "public": true, + "repo": "PyAutoLens" + }, + "lens-workspace": { + "name": "autolens_workspace", + "public": true, + "repo": "autolens_workspace" + }, + "lens-tutorials": { + "name": "HowToLens", + "public": true, + "repo": "HowToLens" + }, + "lens-docs": { + "name": "PyAutoLens documentation", + "public": true, + "repo": "PyAutoLens", + "path": "docs", + "published_url": "https://pyautolens.readthedocs.io/en/latest/" + }, + "lens-assistant": { + "name": "autolens_assistant", + "public": true, + "repo": "autolens_assistant" + }, + "lens-profiling": { + "name": "autolens_profiling", + "public": true, + "repo": "autolens_profiling" + }, + "lens-inference": { + "name": "autolens_inference", + "public": true, + "repo": "autolens_inference" + }, + "lens-visualization": { + "name": "autolens_visualization", + "public": true, + "repo": "autolens_visualization" + }, + "reduce": { + "name": "PyAutoReduce", + "public": true, + "repo": "PyAutoReduce" + }, + "reduce-workspace": { + "name": "autoreduce_workspace", + "public": true, + "repo": "autoreduce_workspace" + }, + "cti": { + "name": "PyAutoCTI", + "public": true, + "repo": "PyAutoCTI" + }, + "cti-workspace": { + "name": "autocti_workspace", + "public": true, + "repo": "autocti_workspace" + }, + "cti-docs": { + "name": "PyAutoCTI documentation", + "public": true, + "repo": "PyAutoCTI", + "path": "docs", + "published_url": "https://pyautocti.readthedocs.io/en/latest/" + }, + "cti-assistant": { + "name": "autocti_assistant", + "public": true, + "repo": "autocti_assistant" + }, + "nerves": { + "name": "PyAutoNerves", + "public": true, + "repo": "PyAutoNerves" + }, + "broca-assistants": { + "name": "Broca assistant evidence (shared inventory)", + "public": true, + "repo": "PyAutoBroca", + "path": "assistants.json", + "published_url": "https://pyautolabs.github.io/PyAutoBroca/" + }, + "array-docs": { + "name": "PyAutoArray documentation source", + "repo": "PyAutoArray", + "path": "docs", + "public": true + }, + "reduce-guide": { + "name": "PyAutoReduce project guide", + "repo": "PyAutoReduce", + "path": "README.md", + "public": true + } + }, + "projects": { + "fit": { + "name": "PyAutoFit", + "kind": "software_family", + "public": true, + "description": "Model fitting and non-linear inference.", + "resources": { + "software": [ + "fit" + ], + "dependencies": [ + "nerves" + ], + "workspaces": [ + "fit-workspace" + ], + "tutorials": [ + "fit-tutorials" + ], + "documentation": [ + "fit-docs" + ], + "assistants": [ + "fit-assistant" + ], + "records": [ + "broca-assistants", + "fit-profiling", + "fit-inference", + "fit-visualization" + ] + } + }, + "array": { + "name": "PyAutoArray", + "kind": "software_family", + "public": true, + "description": "Arrays, grids, masks and inversions shared across software families.", + "resources": { + "software": [ + "array" + ], + "dependencies": [ + "nerves" + ], + "documentation": [ + "array-docs" + ] + } + }, + "galaxy": { + "name": "PyAutoGalaxy", + "kind": "software_family", + "public": true, + "description": "Galaxy profiles and modelling.", + "resources": { + "software": [ + "galaxy" + ], + "dependencies": [ + "array", + "fit", + "nerves" + ], + "workspaces": [ + "galaxy-workspace" + ], + "tutorials": [ + "galaxy-tutorials" + ], + "documentation": [ + "galaxy-docs" + ], + "assistants": [ + "galaxy-assistant" + ], + "records": [ + "broca-assistants" + ] + } + }, + "lens": { + "name": "PyAutoLens", + "kind": "software_family", + "public": true, + "description": "Strong-lensing modelling.", + "resources": { + "software": [ + "lens" + ], + "dependencies": [ + "galaxy", + "array", + "fit", + "nerves" + ], + "workspaces": [ + "lens-workspace" + ], + "tutorials": [ + "lens-tutorials" + ], + "documentation": [ + "lens-docs" + ], + "assistants": [ + "lens-assistant" + ], + "records": [ + "broca-assistants", + "lens-profiling", + "lens-inference", + "lens-visualization" + ] + } + }, + "reduce": { + "name": "PyAutoReduce", + "kind": "software_family", + "public": true, + "description": "Imaging reduction into modelling-ready datasets.", + "resources": { + "software": [ + "reduce" + ], + "workspaces": [ + "reduce-workspace" + ], + "documentation": [ + "reduce-guide" + ] + } + }, + "cti": { + "name": "PyAutoCTI", + "kind": "software_family", + "public": true, + "description": "Charge transfer inefficiency modelling and calibration.", + "resources": { + "software": [ + "cti" + ], + "dependencies": [ + "array", + "fit", + "nerves" + ], + "workspaces": [ + "cti-workspace" + ], + "documentation": [ + "cti-docs" + ], + "assistants": [ + "cti-assistant" + ], + "records": [ + "broca-assistants" + ] + } + } + } +} diff --git a/scripts/organism_board.py b/scripts/organism_board.py index 8c7c695..b9f7d9e 100644 --- a/scripts/organism_board.py +++ b/scripts/organism_board.py @@ -203,6 +203,9 @@ def _render_md(snapshot: dict) -> str: head = b.get("headline") or "unavailable" link = f"[{b['name']}]({b['url']})" if b.get("url") else b["name"] lines.append(f"| {link} | {head} | {b['role']} |") + if "project_resources" in snapshot: + from project_resources import render_markdown + lines.extend(["", render_markdown(snapshot["project_resources"])]) return "\n".join(lines) @@ -240,6 +243,8 @@ def _row_id(name: str) -> str: .organ-content a{display:inline-block;min-height:44px} .organ-foot{display:flex;justify-content:space-between;gap:1rem;align-items:center;margin:.8rem 0 0;font-size:.82rem;color:var(--muted);flex-wrap:wrap} .organ-foot a{min-height:44px;display:inline-flex;align-items:center} +.project-card ul{list-style:none;padding:0;margin:0} +.project-card li{margin:0 0 .35rem} .organ-grid :focus-visible{outline:3px solid var(--accent);outline-offset:3px} @media(max-width:64rem){.organ-grid{grid-template-columns:repeat(2,minmax(0,1fr))}} @media(max-width:40rem){.organ-grid{grid-template-columns:1fr}.organ-content .summary-row{grid-template-columns:1fr;gap:.15rem}} @@ -255,6 +260,8 @@ def _render_html(snapshot: dict) -> str: refreshed_at=(snapshot.get("generated") if snapshot.get("boards") and all(row.get("headline") is not None for row in snapshot["boards"]) else None), refresh_url=(f"https://github.com/{owner}/PyAutoScientist/actions/workflows/organism_board.yml" if owner else None)) + from project_resources import render_html as render_projects + projects_html = render_projects(snapshot["project_resources"]) if "project_resources" in snapshot else "" rows = [] for row in snapshot.get("boards") or []: key = row.get("key", row["name"].lower()) @@ -275,6 +282,7 @@ def _render_html(snapshot: dict) -> str: PyAutoScientist Dashboard {t.hero(BOARD_KEY, "Dashboard")}{panel} +{projects_html}
{''.join(rows)}
@@ -307,6 +315,7 @@ def render(snapshot: dict, fmt: str = "md") -> str: def main(argv: list[str] | None = None) -> int: import argparse + import yaml ap = argparse.ArgumentParser(prog="organism_board", description=__doc__) g = ap.add_mutually_exclusive_group() @@ -315,8 +324,31 @@ def main(argv: list[str] | None = None) -> int: g.add_argument("--html", action="store_true") g.add_argument("--badge", action="store_true") g.add_argument("--json", action="store_true") + ap.add_argument("--projects", type=Path, default=HOME / "config" / "projects.json", + help="instance-owned project/resource configuration") + ap.add_argument("--repos", type=Path, help="canonical Mind repos.yaml (required outside a configured workspace)") + ap.add_argument("--check-projects", action="store_true", help="validate relationships offline; do not collect feeds") ns = ap.parse_args(argv) + from project_resources import load + repos_path = ns.repos + if repos_path is None: + if os.environ.get("PYAUTO_MIND"): + repos_path = Path(os.environ["PYAUTO_MIND"]) / "repos.yaml" + else: + # Use Brain's manifest-backed resolver rather than guessing a layout. + brain = Path(theme().__file__).resolve().parents[1] + sys.path.insert(0, str(brain / "agents")) + from _repo_paths import repo_path + repos_path = repo_path(_workspace_root(), "PyAutoMind", required=True) / "repos.yaml" + try: + projects = load(ns.projects, repos_path) + except (OSError, ValueError, yaml.YAMLError) as exc: + ap.error(f"project configuration unavailable or invalid: {exc}") + if ns.check_projects: + print(f"Project configuration valid: {len(projects['projects'])} public projects") + return 0 snap = collect() + snap["project_resources"] = projects fmt = "md" for name, label in (("md", "md"), ("md_brief", "md-brief"), ("html", "html"), ("badge", "badge"), ("json", "json")): diff --git a/scripts/project_resources.py b/scripts/project_resources.py new file mode 100644 index 0000000..b5eff71 --- /dev/null +++ b/scripts/project_resources.py @@ -0,0 +1,173 @@ +"""Versioned, instance-owned project relationships; no collection or execution. + +Repository identities come only from the supplied Mind body map. The output is +a publication projection: private/unapproved entries never enter the snapshot. +""" + +from __future__ import annotations + +import html +import json +import re +from pathlib import Path +from urllib.parse import quote, urlsplit + +import yaml + + +RELATIONS = { + "software": "Software", + "dependencies": "Shared dependencies", + "workspaces": "Workspaces", + "tutorials": "Tutorials", + "documentation": "Documentation", + "assistants": "Assistants", + "records": "Organ records", +} +KINDS = {"software_family": "Software family", "scientific_project": "Scientific investigation"} +ID = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*\Z") + + +def _text(value, label): + if not isinstance(value, str) or not value.strip(): + raise ValueError(f"{label} must be nonempty text") + return value + + +def _https(value): + value = _text(value, "published_url") + url = urlsplit(value) + if (url.scheme != "https" or not url.hostname or url.username or url.password + or "\\" in value or any(c.isspace() or ord(c) < 32 for c in value)): + raise ValueError("published_url must be an absolute HTTPS URL without credentials") + return value + + +def _entries(value, label): + if not isinstance(value, dict): + raise ValueError(f"{label} must be an object keyed by stable IDs") + for key, item in value.items(): + if not ID.fullmatch(key) or not isinstance(item, dict): + raise ValueError(f"invalid {label} ID or entry") + _text(item.get("name"), f"{label} name") + if "public" in item and type(item["public"]) is not bool: + raise ValueError(f"{label} public must be boolean") + return value + + +def resolve(config: dict, body_map: dict) -> dict: + """Resolve explicit relationships without inferring projects from repo names.""" + if not isinstance(config, dict) or type(config.get("schema_version")) is not int or config["schema_version"] != 1: + raise ValueError("unsupported project configuration schema_version") + if set(config) - {"schema_version", "resources", "projects"}: + raise ValueError("unknown project configuration field") + repos = body_map.get("repos") if isinstance(body_map, dict) else None + if not isinstance(repos, dict): + raise ValueError("canonical identity map must contain repos") + resources = _entries(config.get("resources", {}), "resource") + projects = _entries(config.get("projects", {}), "project") + resolved = {} + for key, item in resources.items(): + if set(item) - {"name", "public", "repo", "path", "ref", "published_url"}: + raise ValueError(f"resource {key}: unknown field") + links = [] + if "repo" in item: + _text(item["repo"], "repo") + identity = repos.get(item["repo"]) + if not isinstance(identity, dict): + raise ValueError(f"resource {key}: unknown canonical repository") + remote = identity.get("github") + if not isinstance(remote, str) or not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", remote): + raise ValueError(f"resource {key}: invalid canonical GitHub identity") + url = f"https://github.com/{remote}" + if "path" in item or "ref" in item: + path = item.get("path", "") + ref = item.get("ref", "main") + if (not isinstance(path, str) or path.startswith("/") or "\\" in path + or any(p in (".", "..") for p in path.split("/")) + or any(ord(c) < 32 for c in path)): + raise ValueError(f"resource {key}: invalid repository-relative path") + _text(ref, "ref") + if ref in (".", "..") or "\\" in ref or any(c.isspace() or ord(c) < 32 for c in ref): + raise ValueError(f"resource {key}: invalid revision") + url += "/tree/" + quote(ref, safe="") + if path: + url += "/" + quote(path, safe="/") + links.append({"label": "Source", "url": url}) + elif "path" in item or "ref" in item: + raise ValueError(f"resource {key}: path/ref requires repo") + if "published_url" in item: + links.append({"label": "Published", "url": _https(item["published_url"])}) + if not links: + raise ValueError(f"resource {key}: repo or published_url required") + resolved[key] = {"id": key, "name": item["name"], "links": links} + + public_projects = [] + for key, item in projects.items(): + if set(item) - {"name", "public", "kind", "description", "resources"}: + raise ValueError(f"project {key}: unknown field") + if not isinstance(item.get("kind"), str) or item["kind"] not in KINDS: + raise ValueError(f"project {key}: unknown project kind") + relations = item.get("resources", {}) + if not isinstance(relations, dict) or set(relations) - RELATIONS.keys(): + raise ValueError(f"project {key}: unknown resource relationship") + groups = [] + for relation, label in RELATIONS.items(): + ids = relations.get(relation, []) + if (not isinstance(ids, list) or any(not isinstance(i, str) for i in ids) + or len(ids) != len(set(ids))): + raise ValueError(f"project {key}: relationships must be unique ID lists") + if any(i not in resources for i in ids): + raise ValueError(f"project {key}: unknown resource reference") + visible = [resolved[i] for i in ids if resources[i].get("public") is True] + if visible: + groups.append({"relation": relation, "label": label, "resources": visible}) + description = item.get("description", "") + if not isinstance(description, str): + raise ValueError(f"project {key}: description must be text") + if item.get("public") is True: + public_projects.append({"id": key, "name": item["name"], "kind": item["kind"], + "description": description, "groups": groups}) + return {"schema_version": 1, "projects": public_projects} + + +def load(config_path: Path, repos_path: Path) -> dict: + return resolve(json.loads(config_path.read_text(encoding="utf-8")), + yaml.safe_load(repos_path.read_text(encoding="utf-8"))) + + +def render_markdown(snapshot: dict) -> str: + def text(value): + return re.sub(r"([\\\[\]*_`#|])", r"\\\1", html.escape(value)).replace("\n", " ") + + lines = ["## Projects", "", "Connected resources; inventory is not a quality or readiness verdict."] + for project in snapshot.get("projects", []): + lines.extend(["", "### " + text(project["name"]), "", text(project["description"])]) + for group in project["groups"]: + for resource in group["resources"]: + links = " · ".join(f"[{text(link['label'])}]({quote(link['url'], safe='/:?=&%+#@~;,-_')})" + for link in resource["links"]) + lines.append(f"- {text(group['label'])}: {text(resource['name'])} — {links}") + return "\n".join(lines) + + +def render_html(snapshot: dict) -> str: + esc = html.escape + cards = [] + for project in snapshot.get("projects", []): + groups = [] + for group in project["groups"]: + entries = [] + for resource in group["resources"]: + links = " · ".join(f'{esc(link["label"])}' + for link in resource["links"]) + entries.append(f'
  • {esc(resource["name"])} — {links}
  • ') + groups.append(f'
    {esc(group["label"])}
    ') + content = f'
    {"".join(groups)}
    ' if groups else '

    No public resources configured.

    ' + cards.append(f'''
    +{esc(project['name'])}{esc(KINDS[project['kind']])} +

    {esc(project['description'])}

    {content}
    ''') + empty = '

    No public projects configured.

    ' if not cards else '' + return f'''

    Projects

    +

    Connected resources. Follow the source links for current records; listed resources do not establish quality or readiness.

    +{empty}
    {''.join(cards)}
    ''' diff --git a/tests/projects_browser.cjs b/tests/projects_browser.cjs new file mode 100644 index 0000000..7f0be86 --- /dev/null +++ b/tests/projects_browser.cjs @@ -0,0 +1,61 @@ +// Optional rendered-page check: NODE_PATH= node +// tests/projects_browser.cjs +const { chromium } = require('playwright'); +const { pathToFileURL } = require('node:url'); +const path = require('node:path'); +const fs = require('node:fs'); +const assert = require('node:assert/strict'); + +(async () => { + const browser = await chromium.launch({ headless: true, channel: "chromium" }); + const destination = pathToFileURL(path.resolve(process.argv[2])).href; + const evidence = path.resolve(process.argv[3]); + fs.mkdirSync(evidence, { recursive: true }); + let cases = 0; + try { + for (const width of [390, 768, 1440]) { + for (const colorScheme of ['light', 'dark']) { + const context = await browser.newContext({ viewport: { width, height: 1000 }, colorScheme }); + await context.route('https://**/*', route => route.fulfill({ status: 503, body: '{}' })); + const page = await context.newPage(); + const errors = []; + page.on('pageerror', error => errors.push(error.message)); + await page.goto(destination); + await page.waitForFunction(() => !refreshing); + assert.equal(await page.locator('.project-card').count(), 6); + assert.equal(await page.locator('.project-card[open]').count(), 0); + const summary = page.locator('#project-lens > summary'); + await summary.focus(); + await page.keyboard.press('Enter'); + assert.equal(await page.locator('#project-lens').getAttribute('open'), ''); + assert.equal(await page.evaluate(() => document.activeElement.parentElement.id), 'project-lens'); + // Feed refresh never rebuilds project disclosures or steals their focus. + await page.evaluate(() => refresh()); + assert.equal(await page.locator('#project-lens').getAttribute('open'), ''); + assert.equal(await page.evaluate(() => document.activeElement.parentElement.id), 'project-lens'); + const grid = await page.locator('#projects .organ-grid').boundingBox(); + const card = await page.locator('#project-lens').boundingBox(); + assert(Math.abs(grid.width - card.width) < 2, 'expanded card spans full row'); + assert.equal(await page.locator('#project-reduce [data-resource$="assistant"]').count(), 0); + assert(await page.locator('#project-lens [data-resource="array"]').count()); + assert(await page.locator('#project-galaxy [data-resource="array"]').count()); + await page.evaluate(() => document.querySelectorAll('details').forEach(d => { d.open = true; })); + assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), 'whole-page overflow'); + assert(await page.locator('#project-lens a').first().isVisible()); + assert.deepEqual(errors, []); + await page.screenshot({ path: path.join(evidence, `projects-${width}-${colorScheme}.png`), fullPage: true }); + await context.close(); + cases++; + } + } + const context = await browser.newContext({ javaScriptEnabled: false, viewport: { width: 390, height: 1000 } }); + const page = await context.newPage(); + await page.goto(destination); + await page.locator('#project-fit > summary').click(); + assert(await page.locator('#project-fit a').first().isVisible()); + await context.close(); + console.log(`${cases} responsive/theme cases and no-JavaScript disclosure passed`); + } finally { + await browser.close(); + } +})().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/tests/test_project_resources.py b/tests/test_project_resources.py new file mode 100644 index 0000000..e3eedd0 --- /dev/null +++ b/tests/test_project_resources.py @@ -0,0 +1,126 @@ +"""Publication boundaries and reusable relationship semantics (offline).""" + +import copy +import json +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) +import project_resources as pr +import organism_board as ob + + +@pytest.fixture +def inputs(): + return ({"schema_version": 1, + "resources": { + "library": {"name": "Shared code", "repo": "stable-code", "public": True}, + "docs": {"name": "Guide", "repo": "stable-code", "path": "guide/start here.md", + "ref": "release/1", "published_url": "https://docs.example.org/", "public": True}, + "private": {"name": "Secret records", "repo": "hidden", "public": False}}, + "projects": { + "alpha": {"name": "Alpha", "kind": "software_family", "public": True, + "resources": {"software": ["library"], "documentation": ["docs"], "records": ["private"]}}, + "beta": {"name": "Beta", "kind": "scientific_project", "public": True, + "resources": {"dependencies": ["library"]}}}}, + {"repos": {"stable-code": {"github": "OtherLab/renamed-code"}, + "hidden": {"github": "PrivateOwner/secret"}}}) + + +def test_shared_resources_optional_assistants_and_distinct_project_kinds(inputs): + result = pr.resolve(*inputs) + first, second = result["projects"] + assert first["groups"][0]["resources"][0] == second["groups"][0]["resources"][0] + assert not any(g["relation"] == "assistants" for p in result["projects"] for g in p["groups"]) + assert first["kind"] != second["kind"] + doc = first["groups"][1]["resources"][0] + assert doc["links"][0]["url"] == "https://github.com/OtherLab/renamed-code/tree/release%2F1/guide/start%20here.md" + assert doc["links"][1]["url"] == "https://docs.example.org/" + + +def test_private_and_unapproved_items_never_reach_snapshot_or_html(inputs): + config, body_map = inputs + config["projects"]["secret"] = {"name": "Hidden project", "kind": "scientific_project"} + del config["resources"]["docs"]["public"] + result = pr.resolve(config, body_map) + output = json.dumps(result) + pr.render_html(result) + for hidden in ("Hidden project", "Secret records", "PrivateOwner", "secret", "Guide", "docs.example.org"): + assert hidden not in output + assert inputs[0]["resources"]["private"]["public"] is False + + +@pytest.mark.parametrize("field,value", [ + ("repo", "not-registered"), ("repo", []), ("path", "../private"), + ("path", "/etc/passwd"), ("path", "docs\\private"), + ("published_url", "javascript:alert(1)"), ("published_url", "//evil.test"), + ("published_url", "https://name:password@example.org"), + ("published_url", "https://example.org\n.evil.test"), + ("published_url", "https://example.org\\evil"), ("public", "true"), + ("unexpected", True), + ("ref", ".."), ("ref", "bad\nref"), +]) +def test_invalid_resource_configuration_fails_closed(inputs, field, value): + config, body_map = inputs + config["resources"]["library"][field] = value + with pytest.raises(ValueError): + pr.resolve(config, body_map) + + +@pytest.mark.parametrize("relations", [{"software": ["missing"]}, {"software": ["library", "library"]}, + {"unknown": []}, {"software": "library"}, {"software": [{}]}]) +def test_bad_relationships_are_not_silently_omitted(inputs, relations): + inputs[0]["projects"]["alpha"]["resources"] = relations + with pytest.raises(ValueError): + pr.resolve(*inputs) + + +def test_versions_empty_projects_and_external_only_resource(inputs): + config, body_map = inputs + config["schema_version"] = 2 + with pytest.raises(ValueError): + pr.resolve(config, body_map) + assert pr.resolve({"schema_version": 1}, {"repos": {}}) == {"schema_version": 1, "projects": []} + config["schema_version"] = 1 + config["projects"]["alpha"]["resources"] = {} + del config["resources"]["docs"]["repo"] + del config["resources"]["docs"]["path"] + del config["resources"]["docs"]["ref"] + assert "No public resources configured" in pr.render_html(pr.resolve(config, body_map)) + + +def test_labels_are_escaped_and_disclosures_work_without_javascript(inputs): + inputs[0]["projects"]["alpha"]["name"] = '' + result = pr.resolve(*inputs) + html = pr.render_html(result) + assert "