Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion openhcs/agent/capabilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@
class LocalCapabilitySurfaceProfile(ABC, metaclass=AutoRegisterMeta):
"""Registered local MCP surface policy over declared exposition metadata."""

__registry__: ClassVar[dict[str, type["LocalCapabilitySurfaceProfile"]]] = {}

Check failure on line 396 in openhcs/agent/capabilities.py

View workflow job for this annotation

GitHub Actions / code-quality

ruff (UP037)

openhcs/agent/capabilities.py:396:43: UP037 Remove quotes from type annotation help: Remove quotes
__registry_key__ = "name"
__skip_if_no_key__ = True

Expand All @@ -402,7 +402,7 @@
distribution_base_extras: ClassVar[tuple[str, ...]] = ("mcp",)

@classmethod
def for_name(cls, name: str) -> "LocalCapabilitySurfaceProfile":

Check failure on line 405 in openhcs/agent/capabilities.py

View workflow job for this annotation

GitHub Actions / code-quality

ruff (UP037)

openhcs/agent/capabilities.py:405:37: UP037 Remove quotes from type annotation help: Remove quotes
try:
return cls.__registry__[name]()
except KeyError as exc:
Expand All @@ -415,7 +415,7 @@
@classmethod
def names_including(
cls,
capability: "AgentCapabilitySpec",

Check failure on line 418 in openhcs/agent/capabilities.py

View workflow job for this annotation

GitHub Actions / code-quality

ruff (UP037)

openhcs/agent/capabilities.py:418:21: UP037 Remove quotes from type annotation help: Remove quotes
) -> tuple[str, ...]:
"""Return registered surface names that include one capability."""

Expand All @@ -425,14 +425,14 @@
if capability.supports_surface_profile(cls.for_name(name))
)

def includes(self, capability: "AgentCapabilitySpec") -> bool:

Check failure on line 428 in openhcs/agent/capabilities.py

View workflow job for this annotation

GitHub Actions / code-quality

ruff (UP037)

openhcs/agent/capabilities.py:428:36: UP037 Remove quotes from type annotation help: Remove quotes
"""Return whether this profile includes one nominal capability."""
del capability
return True

def distribution_extras(
self,
capabilities: tuple["AgentCapabilitySpec", ...],

Check failure on line 435 in openhcs/agent/capabilities.py

View workflow job for this annotation

GitHub Actions / code-quality

ruff (UP037)

openhcs/agent/capabilities.py:435:29: UP037 Remove quotes from type annotation help: Remove quotes
) -> tuple[str, ...]:
"""Return package extras required by this selected local surface."""
extras = dict.fromkeys(self.distribution_base_extras)
Expand Down Expand Up @@ -2073,7 +2073,10 @@
"Read-only query of image/result file records exposed "
"by a local plate inventory. Returns virtual image names, source "
"paths, result artifact paths, and metadata from the same inventory "
"API used by the Image Browser."
"API used by the Image Browser. For retained outputs outside the standard "
"plate layout, pass result_directory with kind='result'. This inspects "
"persisted files and bounded native previews without microscope detection "
"or inferred acquisition identity; it does not attest writer success."
)
service = "plate_inspection"
data_exposure = (
Expand Down
5 changes: 5 additions & 0 deletions openhcs/agent/dto/plate.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,7 @@ class PlateFileQueryRequest:
"""Query image/result files exposed by a local plate inventory."""

plate_path: str
result_directory: str | None = None
microscope_type: str = PlateInspectionDefaults.MICROSCOPE_AUTO
pattern_format: str | None = None
kind: PlateFileKind | None = PlateFileKind.IMAGE
Expand All @@ -333,6 +334,7 @@ def from_fields(
cls,
*,
plate_path: str,
result_directory: str | None = None,
microscope_type: str = PlateInspectionDefaults.MICROSCOPE_AUTO,
pattern_format: str | None = None,
kind: PlateFileKindSelection = PlateFileKind.IMAGE,
Expand All @@ -346,6 +348,7 @@ def from_fields(
) -> "PlateFileQueryRequest":
return cls(
plate_path=plate_path,
result_directory=result_directory,
microscope_type=microscope_type,
pattern_format=pattern_format,
kind=PlateFileInventoryQuery.kind_from_value(kind),
Expand All @@ -361,6 +364,7 @@ def from_fields(
def as_tool_arguments(self) -> dict[str, JsonValue]:
return {
"plate_path": self.plate_path,
"result_directory": self.result_directory,
"microscope_type": self.microscope_type,
"pattern_format": self.pattern_format,
"kind": PlateFileInventoryQuery.kind_value(self.kind),
Expand Down Expand Up @@ -983,6 +987,7 @@ class PlateFileQueryResult(AgentResultEnvelope):
"""Bounded plate file query result."""

plate_path: str
result_directory: str | None = None
requested_microscope_type: str
detected_microscope_type: str | None = None
handler_class: str | None = None
Expand Down
9 changes: 9 additions & 0 deletions openhcs/agent/path_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import os
from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path

Expand Down Expand Up @@ -171,6 +172,14 @@ def assert_readable_location(self, path: str | Path) -> Path:
)
return candidate

def iter_readable_files(self, directory: str | Path) -> Iterator[Path]:
"""Yield regular files only after admitting each path, including symlinks."""
root = self.assert_readable(directory)
for path in root.rglob("*"):
self.assert_readable(path)
if path.is_file():
yield path

def assert_writable(self, path: str | Path) -> Path:
candidate = Path(path).expanduser().resolve(strict=False)
if candidate not in self.writable_roots:
Expand Down
71 changes: 71 additions & 0 deletions openhcs/agent/services/plate_inspection_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -1139,6 +1139,9 @@ def _query_files(
),
)

if request.result_directory is not None:
return self._query_explicit_result_directory(request, plate_path)

query_kind = request.kind
if (
query_kind is PlateFileKind.RESULT
Expand Down Expand Up @@ -1226,6 +1229,69 @@ def _query_files(
warnings=tuple(warnings),
)

def _query_explicit_result_directory(
self,
request: PlateFileQueryRequest,
plate_path: Path,
) -> PlateFileQueryResult:
"""Read persisted files without inventing a microscope/source identity."""
if request.kind is not PlateFileKind.RESULT or request.well is not None:
return self._query_files_error(
request,
AgentError(
code="plate_result_directory_selection_invalid",
message=(
"Explicit result-directory inspection requires kind='result' "
"and no acquisition-component filter. Native previews do not "
"establish a file's source or writer success."
),
),
plate_path=plate_path,
)

result_path, errors = self._resolve_plate_path(request.result_directory)
if errors:
return self._query_files_error(
request,
errors[0],
plate_path=plate_path,
)
if result_path is None:
raise RuntimeError("Result directory resolution returned no path or error.")
from openhcs.microscopes.microscope_interfaces import AnalysisResultDirectory

try:
result_inventory = PlateResultFileInventory.from_directory_files(
plate_path=result_path,
result_directory=AnalysisResultDirectory(
subdirectory_name=result_path.name,
path=result_path,
),
file_paths=self._path_policy.iter_readable_files(result_path),
)
except AgentPathPolicyError as exc:
return self._query_files_error(
request,
AgentError.from_exception(
PlateInspectionIssueCode.PATH_POLICY_REJECTED.value,
exc,
path=request.result_directory,
),
plate_path=plate_path,
)
return self._query_files_from_inventory(
request=request,
plate_path=plate_path,
file_inventory=PlateFileInventory.from_inventories(
image_inventory=PlateImageInventory(plate_path=result_path, records=()),
result_inventory=result_inventory,
),
detected_microscope_type=None,
handler_class=None,
parser_class=None,
warnings=(),
)

@staticmethod
def _query_files_from_inventory(
*,
Expand All @@ -1249,6 +1315,11 @@ def _query_files_from_inventory(
return PlateFileQueryResult(
schema_version=SCHEMA_VERSION,
plate_path=str(plate_path),
result_directory=(
str(file_inventory.plate_path)
if request.result_directory is not None
else None
),
requested_microscope_type=request.microscope_type,
detected_microscope_type=detected_microscope_type,
handler_class=handler_class,
Expand Down
36 changes: 31 additions & 5 deletions openhcs/core/plate_image_inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from __future__ import annotations

import csv
from collections.abc import Mapping, Sequence
from collections.abc import Iterable, Mapping, Sequence
from dataclasses import asdict, dataclass, field, is_dataclass
from datetime import datetime
from pathlib import Path
Expand Down Expand Up @@ -854,11 +854,33 @@ def _records_from_directory(
result_directory: "AnalysisResultDirectory",
parser: "FilenameParser | None",
) -> tuple[tuple[PlateResultFileRecord, ...], int]:
inventory = cls.from_directory_files(
plate_path=plate_path,
result_directory=result_directory,
file_paths=(
path for path in result_directory.path.rglob("*") if path.is_file()
),
parser=parser,
)
return inventory.records, inventory.scanned_file_count

@classmethod
def from_directory_files(
cls,
*,
plate_path: Path,
result_directory: "AnalysisResultDirectory",
file_paths: Iterable[Path],
parser: "FilenameParser | None" = None,
) -> "PlateResultFileInventory":
"""Project exact directory files admitted by a caller's read authority.

This is also the shared record builder for handler-declared directories.
Without a parser, paths identify files only, not acquisition components.
"""
records: list[PlateResultFileRecord] = []
scanned_file_count = 0
for file_path in sorted(result_directory.path.rglob("*")):
if not file_path.is_file():
continue
for file_path in sorted(file_paths):
scanned_file_count += 1
file_format = cls._result_file_format(file_path)
if file_format is None:
Expand Down Expand Up @@ -892,7 +914,11 @@ def _records_from_directory(
),
)
)
return tuple(records), scanned_file_count
return cls(
plate_path=plate_path,
records=tuple(records),
scanned_file_count=scanned_file_count,
)

@staticmethod
def _result_file_format(file_path: Path) -> FileFormat | None:
Expand Down
131 changes: 131 additions & 0 deletions paper/plans/materialized_result_followup_20260929.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
# Explicit materialized-result review follow-up

Owner: OpenHCS blind-analysis integration coordinator. Issue #134 remains open.
Base: ed129d85054f8ac0c8d4661dc58c7e87ba1bcd7c, verified remote main.
Worktree: /home/ts/wt/openhcs-materialized-result-route-20260929.
Branch: fix/mcp-materialized-result-followup-20260929.

PR #153 is merged: paired native POINT codec dependency plus shared manual
image/ROI calibration are installed and live-verified in the isolated candidate
environment. Six same-coordinate synthetic raw/result/combined bitmaps under
two numeric windows were opened; the extra viewer was closed through MCP.
This does not repair historical malformed FREEHAND archives, upgrade the dirty
shared H002 process, or biologically accept the frozen count of 28.

## Required working workflow

1. Admit a retained, exact artifact output from its existing runtime owner,
including semantic address, actual disk location and source/axis/object
provenance. Distinguish a compiled candidate path from observed writer success.
2. Query bounded files and schema-bearing CSV/ROI previews at that admitted
explicit location without manufacturing a microscope handler, relocating
files, guessing filename identity or rerunning analysis.
3. Reopen persisted images and ROI projections through the same managed-viewer
streaming service. Preserve coordinates, calibration, source domain and
label/object identity; automatically project the typed request to MCP.
4. Verify the installed public journey on tiny native materialized outputs:
compile/run once, retained observation, explicit-directory query/sample,
viewer reopen, exact payload reconciliation and opened matched captures.
Reject unauthorized roots, stale/wrong identities and oversized previews.
5. Apply that working route to the frozen H002 artifacts without tuning or
overwriting them. Any derived diagnostic POINT archive needs explicit
provenance and a distinct destination; it is not a new blinded analysis.

## Current source evidence and crossing

### Inspection checkpoint ownership decision

Initial corpus at 86868031: plate DTO, inspection service and core plate inventory.
NRA ModuleSyntaxIndex enumerated all 78 original ClassDefs; all 78 uniquely
joined CompactClassFamilyIndex. The final corpus adds AgentPathPolicy and has
82/82 unique joins (1.17 s, 68892 KiB maximum RSS). Global R1/MRO/equivalence
proofs remain OPEN.
This is an intentional feature extension, not a proved-equivalent DSL replay.

Task authority: inspect the retained arbitrary result directory without rerun,
relocation or invented source identity. The existing PlateFileQueryRequest owns
the explicit directory selection, AgentPathPolicy owns readable admission,
PlateResultFileInventory owns file record construction, and its existing native
preview reader owns bounded decoding. Capability schema derives from the DTO.
BOUND-2 forbids bypassing the native preview owner; IDEN-1 forbids treating a
file path as source/axis/object provenance or proof of successful execution.

New-case check: a supported native result format added to the existing inventory
format/preview owner automatically reaches explicit-directory queries without a
second registry. Missing directories, unauthorized roots and escaping symlinks
must fail before preview. A misleading acquisition-like filename must not gain
well/channel/source metadata. Component filtering is rejected for this route.
The plate/context path and result-file location retain separate roles.

This checkpoint delivers file inspection only. It does not substitute for the
remaining observed-artifact admission, schema-bearing measurement preview and
provenance-aware image/ROI reopening in the required workflow above.

### Installed checkpoint evidence at 30ea44fd

- Forty focused inventory, inspection and generated MCP-schema checks passed
against source (5.68 s) and installed wheels (5.54 s). The installed suite
imports application modules from the owned venv; the source path supplies
test fixtures only. Its first collection attempt lacked the tests package,
exited before running, and is not counted as an installed pass.
- The earlier missing-directory test expected the wrong issue code. The actual
AgentPathPolicy contract rejects absent readable paths before directory-type
checking; the assertion now checks that exact contract, not a permissive code.
- Bounded five-module debt census: 8094 to 8201 code lines; unchanged string-key,
type-identity, long-chain, enum/class, broad-except and long-function counts.
Three additional foreign-absence probes implement the genuinely optional
result-directory selection and existing boundary resolution contract; no
parallel source identity, schema store or registry was added. Native overlay
found no raw shape/string dispatch/roster additions. Existing large procedures
and the owning service remain debt; bounded dead-module results are not valid
deletion claims because consumers lie outside the selected five modules.
Census/overlay took 3.33 s, maximum RSS 179096 KiB.
- The owned installed resident MCP was restarted after the wheel update and
returned a fresh healthy handshake with 56 resources and no stale paths.
Its read roots add only the already-frozen H002 trial to the installed defaults;
the private evaluator and unrelated repositories remain outside the policy.
- Five complete public MCP envelopes inspect the explicit H002 results directory:
three bounded centre CSV rows; two examples from a native Z032 ROI archive;
a truthful missing-sidecar omission for the historical centres.roi.zip; rejected
out-of-scope directory; rejected acquisition-component filtering. No filename
components are promoted into inventory metadata.
- SCIENCE_SHA256SUMS checked successfully. No pipeline execution, artifact rewrite,
parameter tuning or held-out/reference-answer access occurred. Current H002 GUI,
execution worker, viewer TCP5690 and desktop Xorg remained alive. No new viewer
or agent fleet was started. Available RAM remains constrained; do not expand.

Complete envelopes and the inspection disposition are retained under
/home/ts/wt/openhcs-live-point-evidence-20260929/materialized-inspection-20260929.
This proves native installed file inspection, not writer provenance, image/ROI
reopening from an arbitrary result directory, biological acceptance or completion
of issue #134. Ship this tested checkpoint; continue those requirements in the
same integration-owned follow-up rather than leaving the working feature stranded.

RuntimeArtifactAddress/RuntimeArtifactLocation own semantic artifact/storage
identity. RuntimeArtifactProgressPayload currently retains addresses only.
LiveMeasurementTablePreview already retains schema, bounded rows, locations
and object/source identity for measurements. Reuse these existing owners,
not another manifest/store or a duplicate public artifact registry.

PlateInspectionService._query_files reconstructs configured result directories;
PlateStreamingService.stream_files still opens a handler context before record
admission. Arbitrary configured materialization locations are not yet admitted
through those consumers. Existing ImageJ native decoding stays with PolyStore.

PR #157 remains open with an active owner and changes worker_execution,
runtime_exports and function_artifact_materialization. It preserves lightweight
export paths before outcome-only cleanup; it is not independently a complete
writer-success/provenance receipt for this workflow. Coordinate any required
writer/progress extension with that owner, rather than competing in their files.

The prior source investigation and explicit bounded NRA/class/census evidence
remain in materialized_result_route_fix_20260929.md. Historical global FULL/R1
scan holds there are superseded by the owner's bounded-audit authorization.
No complete raw-record/global audit or native equivalence proof is claimed.
Orthogonal MCP control is separate issue #152 / draft PR #154.

The owned point-codec live venv/cache remains in use for this follow-up under
/home/ts/.cache/agent-scratch/openhcs-point-codec-20260929. Persistent live
receipts, six witness copies and disposition are in
/home/ts/wt/openhcs-live-point-evidence-20260929. Frozen scientific files and
held-out/reference-answer boundaries stay unchanged; no parallel fleet is live.
1 change: 1 addition & 0 deletions tests/unit/agent/test_mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -826,6 +826,7 @@ def test_mcp_tool_descriptions_expose_debugging_result_contracts():
assert "image/result file records" in descriptions["openhcs_query_plate_files"]
query_plate_files_properties = schemas["openhcs_query_plate_files"]["properties"]
assert "kind" in query_plate_files_properties
assert "result_directory" in query_plate_files_properties
assert "path_contains" in query_plate_files_properties
assert "well" in query_plate_files_properties
assert "include_previews" in query_plate_files_properties
Expand Down
Loading
Loading