Initial import of DxDesigner part replacement tool (r21)

This commit is contained in:
阿白叔 committed 2026-09-29 15:42:21 +08:00
commit ffe066cb1e
151 files changed
+58745

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
Metadata-Version: 2.4
Name: dx-productivity
Version: 1.0.0
Requires-Python: <3.13,>=3.12
Requires-Dist: PySide6<7,>=6.7
Requires-Dist: pywin32>=306
Requires-Dist: pywinauto<1,>=0.6.9
Provides-Extra: dev
Requires-Dist: pytest<9,>=8; extra == "dev"
Requires-Dist: pytest-cov<7,>=5; extra == "dev"
Requires-Dist: coverage<8,>=7; extra == "dev"
Requires-Dist: build<2,>=1.2; extra == "dev"
Requires-Dist: pytest-qt<5,>=4.4; extra == "dev"
Requires-Dist: PyInstaller<7,>=6.10; extra == "dev"
+45
View File
@@ -0,0 +1,45 @@
pyproject.toml
src/dx_productivity/__init__.py
src/dx_productivity/__main__.py
src/dx_productivity.egg-info/PKG-INFO
src/dx_productivity.egg-info/SOURCES.txt
src/dx_productivity.egg-info/dependency_links.txt
src/dx_productivity.egg-info/entry_points.txt
src/dx_productivity.egg-info/requires.txt
src/dx_productivity.egg-info/top_level.txt
src/dx_productivity/part_replace/__init__.py
src/dx_productivity/part_replace/certification.py
src/dx_productivity/part_replace/cli.py
src/dx_productivity/part_replace/command_schema.py
src/dx_productivity/part_replace/compatibility_profile.py
src/dx_productivity/part_replace/controller.py
src/dx_productivity/part_replace/errors.py
src/dx_productivity/part_replace/inputs.py
src/dx_productivity/part_replace/mailbox.py
src/dx_productivity/part_replace/models.py
src/dx_productivity/part_replace/operator_runtime.py
src/dx_productivity/part_replace/protocol.py
src/dx_productivity/part_replace/reports.py
src/dx_productivity/part_replace/run_store.py
src/dx_productivity/part_replace/verification.py
src/dx_productivity/trial_task_center/__init__.py
src/dx_productivity/trial_task_center/application.py
src/dx_productivity/trial_task_center/comparison.py
src/dx_productivity/trial_task_center/errors.py
src/dx_productivity/trial_task_center/evidence.py
src/dx_productivity/trial_task_center/logging_setup.py
src/dx_productivity/trial_task_center/models.py
src/dx_productivity/trial_task_center/native_helper.py
src/dx_productivity/trial_task_center/quick_run.py
src/dx_productivity/trial_task_center/runner.py
src/dx_productivity/trial_task_center/scanner.py
src/dx_productivity/trial_task_center/service.py
src/dx_productivity/trial_task_center/store.py
src/dx_productivity/trial_task_center/ui/__init__.py
src/dx_productivity/trial_task_center/ui/main_window.py
src/dx_productivity/trial_task_center/ui/mapping_table.py
src/dx_productivity/trial_task_center/ui/project_table.py
src/dx_productivity/trial_task_center/ui/run_panel.py
src/dx_productivity/trial_task_center/ui/styles.py
src/dx_productivity/trial_task_center/ui/task_list.py
src/dx_productivity/trial_task_center/ui/workers.py
@@ -0,0 +1 @@
@@ -0,0 +1,3 @@
[console_scripts]
dx-part-replace = dx_productivity.part_replace.cli:main
dx-part-replace-gui = dx_productivity.trial_task_center.application:main
+11
View File
@@ -0,0 +1,11 @@
PySide6<7,>=6.7
pywin32>=306
pywinauto<1,>=0.6.9
[dev]
pytest<9,>=8
pytest-cov<7,>=5
coverage<8,>=7
build<2,>=1.2
pytest-qt<5,>=4.4
PyInstaller<7,>=6.10
@@ -0,0 +1 @@
dx_productivity
+1
View File
@@ -0,0 +1 @@
"""Dx Productivity Python package."""
+6
View File
@@ -0,0 +1,6 @@
"""Package entry point for the part-replacement CLI."""
from .part_replace.cli import main
raise SystemExit(main())
@@ -0,0 +1,22 @@
"""Immutable domain records for part replacement."""
from .models import (
ComponentSnapshot,
DesignSnapshot,
ExternalChecks,
ImpactCell,
Issue,
MappingRule,
PinSnapshot,
ProjectRef,
ProjectState,
Scope,
UnitSnapshot,
VerificationResult,
)
__all__ = [
"ComponentSnapshot", "DesignSnapshot", "ExternalChecks", "ImpactCell", "Issue",
"MappingRule", "PinSnapshot", "ProjectRef", "ProjectState", "Scope", "UnitSnapshot",
"VerificationResult",
]
@@ -0,0 +1,343 @@
"""Immutable, fail-closed trial compatibility certifications."""
from __future__ import annotations
from collections.abc import Sequence
from dataclasses import dataclass
from datetime import datetime, timezone
from decimal import Decimal, InvalidOperation
import hashlib
import json
from pathlib import Path
from typing import Any
from .models import ComponentSnapshot, DesignSnapshot, ExternalChecks, MappingRule, PinSnapshot, UnitSnapshot, VerificationResult
from .protocol import ProtocolError, atomic_write_text, snapshot_fingerprint
from .verification import verify_replacement
_FORMAT_VERSION = 1
_DXDESIGNER_BUILD = "7.9.5"
class CertificationError(ValueError):
"""A trial certification is incomplete, corrupt, or not applicable."""
def __init__(self, code: str, message: str) -> None:
self.code = code
self.message = message
super().__init__(f"{code}: {message}")
@dataclass(frozen=True, slots=True)
class Certification:
created_utc: str
dxdesigner_build: str
rule: MappingRule
target_fingerprint: str
library_identity: str | None
representative_project_fingerprint: str
evidence_paths: tuple[str, ...]
def __post_init__(self) -> None:
object.__setattr__(self, "evidence_paths", tuple(self.evidence_paths))
def _canonical_json(value: object) -> str:
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False)
def _normalized_identity(value: str) -> str:
return value.strip().casefold()
def _decimal_text(value: object) -> str:
try:
decimal = value if isinstance(value, Decimal) else Decimal(str(value))
except (InvalidOperation, ValueError) as error:
raise CertificationError("invalid_interface", "interface coordinates must be finite Decimals") from error
if not decimal.is_finite():
raise CertificationError("invalid_interface", "interface coordinates must be finite Decimals")
if decimal == 0:
return "0"
return format(decimal.normalize(), "f")
def _local_coordinates(
unit: UnitSnapshot,
x: Decimal,
y: Decimal,
) -> tuple[str, str]:
delta_x = x - unit.x
delta_y = y - unit.y
rotation = unit.rotation % 360
if rotation == 0:
transformed_x, transformed_y = delta_x, delta_y
elif rotation == 90:
transformed_x, transformed_y = delta_y, -delta_x
elif rotation == 180:
transformed_x, transformed_y = -delta_x, -delta_y
elif rotation == 270:
transformed_x, transformed_y = -delta_y, delta_x
else:
raise CertificationError("invalid_interface", "interface rotation must be a quarter turn")
local_x = -transformed_x if unit.mirrored else transformed_x
return _decimal_text(local_x), _decimal_text(transformed_y)
def _local_pin_coordinates(unit: UnitSnapshot, pin: PinSnapshot) -> tuple[str, str]:
return _local_coordinates(unit, pin.x, pin.y)
def _occurrence_interface(component: ComponentSnapshot) -> dict[str, object]:
if not component.units:
raise CertificationError("invalid_interface", "selected component has no observed units")
units: list[dict[str, object]] = []
gate_ids: set[str] = set()
for unit in component.units:
gate_id = _normalized_identity(unit.unit_id)
if not gate_id or gate_id in gate_ids:
raise CertificationError("invalid_interface", "unit identities must be nonempty and unique after normalization")
gate_ids.add(gate_id)
if not isinstance(unit.symbol, str) or not unit.symbol:
raise CertificationError("invalid_interface", "symbol identity must be nonempty")
if not unit.pins:
raise CertificationError("invalid_interface", "selected units must have observed pins")
pins: list[list[str]] = []
for pin in unit.pins:
if not pin.number or not pin.name:
raise CertificationError("invalid_interface", "pin number and name must be nonempty")
local_x, local_y = _local_pin_coordinates(unit, pin)
pins.append([pin.number, pin.name, local_x, local_y])
pins.sort(key=lambda pin: (pin[0], pin[1], pin[2], pin[3]))
units.append(
{
"gate_id": gate_id,
"pins": pins,
"symbol": unit.symbol,
"symbol_origin": list(
_local_coordinates(unit, unit.origin_x, unit.origin_y)
),
}
)
units.sort(key=_canonical_json)
return {"logical_unit_count": len(units), "units": units}
def interface_fingerprint(snapshot: DesignSnapshot, logical_keys: Sequence[str]) -> str:
"""Hash only the library-visible interface of the selected logical components."""
if not isinstance(snapshot, DesignSnapshot):
raise CertificationError("invalid_snapshot", "interface fingerprint requires a DesignSnapshot")
keys = tuple(logical_keys)
if not keys or any(not isinstance(key, str) or not key for key in keys) or len(keys) != len(set(keys)):
raise CertificationError("invalid_logical_keys", "logical keys must be nonempty unique strings")
components = {component.logical_key: component for component in snapshot.components}
if len(components) != len(snapshot.components) or any(key not in components for key in keys):
raise CertificationError("invalid_logical_keys", "logical keys must identify unambiguous snapshot components")
observed_interfaces = tuple(_occurrence_interface(components[key]) for key in keys)
canonical_interfaces = tuple(_canonical_json(interface) for interface in observed_interfaces)
if len(set(canonical_interfaces)) != 1:
raise CertificationError(
"heterogeneous_interface",
"selected target occurrences do not expose one identical normalized part interface",
)
return hashlib.sha256(canonical_interfaces[0].encode("utf-8")).hexdigest()
def _duplicate_rejecting_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
data: dict[str, Any] = {}
for name, value in pairs:
if name in data:
raise CertificationError("corrupt_certification", f"duplicate JSON field {name!r}")
data[name] = value
return data
def _load_data(path: Path) -> dict[str, Any]:
try:
text = path.read_text(encoding="utf-8")
except FileNotFoundError:
return {"format_version": _FORMAT_VERSION, "certifications": []}
except (OSError, UnicodeError) as error:
raise CertificationError("corrupt_certification", f"cannot read certifications: {path}") from error
try:
data = json.loads(text, object_pairs_hook=_duplicate_rejecting_object)
except (json.JSONDecodeError, CertificationError) as error:
raise CertificationError("corrupt_certification", f"invalid certifications JSON: {path}") from error
if not isinstance(data, dict) or set(data) != {"format_version", "certifications"}:
raise CertificationError("corrupt_certification", "certification document fields are invalid")
if type(data["format_version"]) is not int or data["format_version"] != _FORMAT_VERSION:
raise CertificationError("corrupt_certification", "certification document version is invalid")
if not isinstance(data["certifications"], list):
raise CertificationError("corrupt_certification", "certifications must be an array")
return data
def _valid_timestamp(value: object) -> bool:
if not isinstance(value, str) or not value.endswith("Z"):
return False
try:
parsed = datetime.fromisoformat(value[:-1] + "+00:00")
except ValueError:
return False
return parsed.tzinfo is not None and parsed.utcoffset() == timezone.utc.utcoffset(parsed)
def _certification_from_data(data: object) -> Certification:
if not isinstance(data, dict):
raise CertificationError("corrupt_certification", "certification record must be an object")
required = {
"created_utc", "dxdesigner_build", "evidence_paths", "library_identity",
"new_part_number", "old_part_number", "representative_project_fingerprint", "target_fingerprint",
}
if set(data) != required:
raise CertificationError("corrupt_certification", "certification record fields are invalid")
strings = (
"created_utc", "dxdesigner_build", "new_part_number", "old_part_number",
"representative_project_fingerprint", "target_fingerprint",
)
if any(not isinstance(data[name], str) or not data[name] for name in strings):
raise CertificationError("corrupt_certification", "certification record string fields are invalid")
if not _valid_timestamp(data["created_utc"]) or data["dxdesigner_build"] != _DXDESIGNER_BUILD:
raise CertificationError("corrupt_certification", "certification timestamp or build is invalid")
library_identity = data["library_identity"]
if library_identity is not None and (not isinstance(library_identity, str) or not library_identity):
raise CertificationError("corrupt_certification", "library identity is invalid")
evidence_paths = data["evidence_paths"]
if not isinstance(evidence_paths, list) or not evidence_paths or any(
not isinstance(path, str) or not path for path in evidence_paths
):
raise CertificationError("corrupt_certification", "evidence paths are invalid")
return Certification(
created_utc=data["created_utc"],
dxdesigner_build=data["dxdesigner_build"],
rule=MappingRule(data["old_part_number"], data["new_part_number"]),
target_fingerprint=data["target_fingerprint"],
library_identity=library_identity,
representative_project_fingerprint=data["representative_project_fingerprint"],
evidence_paths=tuple(evidence_paths),
)
def _certification_to_data(certification: Certification) -> dict[str, object]:
return {
"created_utc": certification.created_utc,
"dxdesigner_build": certification.dxdesigner_build,
"evidence_paths": list(certification.evidence_paths),
"library_identity": certification.library_identity,
"new_part_number": certification.rule.new_part_number,
"old_part_number": certification.rule.old_part_number,
"representative_project_fingerprint": certification.representative_project_fingerprint,
"target_fingerprint": certification.target_fingerprint,
}
class CertificationStore:
"""Persist and require records created by one verified representative trial."""
def __init__(
self,
path: Path,
*,
before: DesignSnapshot | None = None,
after: DesignSnapshot | None = None,
verification: VerificationResult | None = None,
evidence_paths: Sequence[str] = (),
) -> None:
self.path = Path(path)
self._before = before
self._after = after
self._verification = verification
self._evidence_paths = tuple(evidence_paths)
@staticmethod
def _require_complete_trial_observation(
before: DesignSnapshot,
after: DesignSnapshot,
logical_keys: Sequence[str],
) -> None:
for snapshot in (before, after):
components = {component.logical_key: component for component in snapshot.components}
for logical_key in logical_keys:
component = components.get(logical_key)
if component is None or not component.units:
raise CertificationError("trial_data_incomplete", "expected component has no observed units")
for unit in component.units:
if not unit.pins:
raise CertificationError("trial_data_incomplete", "expected unit has no observed pins")
if any(not isinstance(pin.net, str) or not pin.net.strip() for pin in unit.pins):
raise CertificationError("trial_data_incomplete", "expected pin has no network identity")
def _require_trial_context(self, rule: MappingRule, target_fingerprint: str) -> tuple[DesignSnapshot, DesignSnapshot, VerificationResult]:
before, after, verification = self._before, self._after, self._verification
if not isinstance(before, DesignSnapshot) or not isinstance(after, DesignSnapshot) or not isinstance(verification, VerificationResult):
raise CertificationError("trial_context_missing", "recording requires trial snapshots and hard verification")
self._require_complete_trial_observation(before, after, verification.expected_logical_keys)
recomputed = verify_replacement(before, after, rule, verification.expected_logical_keys)
if verification.passed is not True or verification.rule != rule or recomputed != verification or recomputed.passed is not True:
raise CertificationError("hard_verification_failed", "representative trial did not pass hard verification")
if before.project_id != after.project_id or verification.project_id != before.project_id:
raise CertificationError("hard_verification_failed", "trial verification does not match the representative project")
expected = interface_fingerprint(after, verification.expected_logical_keys)
if target_fingerprint != expected:
raise CertificationError("target_fingerprint_mismatch", "target fingerprint does not match the verified observed interface")
return before, after, verification
def record(
self,
rule: MappingRule,
target_fingerprint: str,
library_identity: str | None,
checks: ExternalChecks,
) -> Certification:
if not isinstance(rule, MappingRule) or not rule.old_part_number or not rule.new_part_number:
raise CertificationError("invalid_mapping_rule", "certification requires a nonempty MappingRule")
if not isinstance(target_fingerprint, str) or not target_fingerprint:
raise CertificationError("invalid_target_fingerprint", "target fingerprint must be a nonempty string")
if library_identity is not None and (not isinstance(library_identity, str) or not library_identity):
raise CertificationError("invalid_library_identity", "library identity must be a nonempty string or None")
if not isinstance(checks, ExternalChecks) or not (
checks.packager is True and checks.erc is True and checks.netlist is True
):
raise CertificationError("external_checks_incomplete", "Packager, ERC, and netlist must each explicitly pass")
before, _, _ = self._require_trial_context(rule, target_fingerprint)
if not self._evidence_paths or any(not isinstance(path, str) or not path for path in self._evidence_paths):
raise CertificationError("invalid_evidence_paths", "evidence paths must be nonempty strings")
certification = Certification(
created_utc=datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z"),
dxdesigner_build=_DXDESIGNER_BUILD,
rule=rule,
target_fingerprint=target_fingerprint,
library_identity=library_identity,
representative_project_fingerprint=snapshot_fingerprint(before),
evidence_paths=self._evidence_paths,
)
data = _load_data(self.path)
records = [_certification_from_data(record) for record in data["certifications"]]
records = [
record for record in records
if (record.rule, record.target_fingerprint, record.library_identity) != (
rule, target_fingerprint, library_identity
)
]
records.append(certification)
document = {"format_version": _FORMAT_VERSION, "certifications": [_certification_to_data(record) for record in records]}
try:
atomic_write_text(self.path, _canonical_json(document) + "\n")
except (OSError, ProtocolError) as error:
raise CertificationError("certification_write_failed", f"cannot persist certification: {self.path}") from error
return certification
def require(self, rule: MappingRule, target_fingerprint: str, library_identity: str | None) -> Certification:
if not isinstance(rule, MappingRule) or not isinstance(target_fingerprint, str):
raise CertificationError("certification_mismatch", "no matching certification exists")
records = [_certification_from_data(record) for record in _load_data(self.path)["certifications"]]
for certification in records:
if (
certification.rule == rule
and certification.target_fingerprint == target_fingerprint
and certification.library_identity == library_identity
):
return certification
raise CertificationError("certification_mismatch", "no matching certification exists")
+340
View File
@@ -0,0 +1,340 @@
"""Reproducible command-line interface for part-replacement jobs."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import sys
from typing import Sequence
from .certification import CertificationError
from .command_schema import command_data as _command_data
from .compatibility_profile import (
CompatibilityProfileError,
deploy_compatibility_profile,
promote_compatibility_profile,
)
from .controller import BatchController, ControllerError
from .inputs import InputError, discover_projects
from .models import ProjectRef, ProjectState, VerificationResult
from .operator_runtime import OperatorStepResult
from .protocol import ProtocolError, atomic_write_text
from .run_store import BackupError, StateError
class _UsageError(ValueError):
code = "invalid_arguments"
class _Parser(argparse.ArgumentParser):
def error(self, message: str) -> None:
raise _UsageError(message)
def _parser() -> argparse.ArgumentParser:
parser = _Parser(prog="dx-part-replace", description="DxDesigner 7.9.5 multi-project native part replacement")
commands = parser.add_subparsers(dest="command", required=True)
discover = commands.add_parser("discover", help="discover candidate project-definition files")
discover.add_argument("root", type=Path)
discover.add_argument("--suffix", action="append", dest="suffixes")
discover.add_argument("--output", type=Path)
create = commands.add_parser("create", help="create a validated immutable job")
create.add_argument("job", type=Path)
create.add_argument("--mapping", required=True, type=Path)
create.add_argument("--projects", required=True, type=Path)
create.add_argument("--certifications", required=True, type=Path)
create.add_argument("--suffix", action="append", dest="suffixes")
create.add_argument("--library-identity")
deploy_profile = commands.add_parser(
"deploy-profile",
help="validate and atomically deploy a compatibility profile",
)
deploy_profile.add_argument("source", type=Path)
deploy_profile.add_argument("destination", type=Path)
promote_profile = commands.add_parser(
"promote-profile",
help="bind completed live evidence and deploy an accepted profile",
)
promote_profile.add_argument("source", type=Path)
promote_profile.add_argument("acceptance", type=Path)
promote_profile.add_argument("destination", type=Path)
ingest = commands.add_parser("ingest")
ingest.add_argument("job", type=Path)
ingest.add_argument("project_id")
next_command = commands.add_parser("next")
next_command.add_argument("job", type=Path)
operator_step = commands.add_parser("operator-step")
operator_step.add_argument("job", type=Path)
inventory_command = commands.add_parser("prepare-inventory")
inventory_command.add_argument("job", type=Path)
inventory_command.add_argument("project_id")
for name in (
"prepare-close",
"confirm-close",
"prepare-open",
"confirm-open",
"prepare-undo",
"confirm-undo",
"prepare-save",
"confirm-saved",
"restore",
"reconcile",
):
control = commands.add_parser(name)
control.add_argument("job", type=Path)
control.add_argument("project_id")
for name in ("prepare-check", "confirm-check"):
check = commands.add_parser(name)
check.add_argument("job", type=Path)
check.add_argument("project_id")
check.add_argument("check", choices=("packager", "erc", "netlist"))
prepare = commands.add_parser("prepare")
prepare.add_argument("job", type=Path)
prepare.add_argument("project_id")
prepare.add_argument("rule_index", type=int)
verify = commands.add_parser("verify")
verify.add_argument("job", type=Path)
verify.add_argument("project_id")
verify.add_argument("rule_index", type=int)
report = commands.add_parser("report")
report.add_argument("job", type=Path)
status = commands.add_parser("status")
status.add_argument("job", type=Path)
return parser
def _suffixes(value: list[str] | None) -> tuple[str, ...]:
return tuple(value) if value else (".prj",)
def _project_data(project: ProjectRef) -> dict[str, str]:
return {
"display_name": project.display_name,
"project_id": project.project_id,
"project_path": project.project_path,
}
def _result_data(result: VerificationResult) -> dict[str, object]:
return {
"changed_logical_keys": list(result.changed_logical_keys),
"expected_logical_keys": list(result.expected_logical_keys),
"issues": [
{
"code": issue.code,
"details": dict(issue.details),
"message": issue.message,
"severity": issue.severity,
}
for issue in result.issues
],
"new_part_number": result.rule.new_part_number,
"old_part_number": result.rule.old_part_number,
"passed": result.passed,
"project_id": result.project_id,
}
def _operator_step_data(result: OperatorStepResult) -> dict[str, object]:
command = result.command
project = result.project
state = result.state
return {
"bridge_state": result.bridge_state,
"command": None if command is None else _command_data(command),
"complete": result.complete,
"consumed_action": result.consumed_action,
"instruction": result.instruction,
"manual_route": result.manual_route,
"project": None if project is None else _project_data(project),
"state": None if state is None else state.value,
}
def _run(args: argparse.Namespace) -> tuple[int, dict[str, object]]:
if args.command == "discover":
projects = discover_projects(args.root, _suffixes(args.suffixes))
if args.output is not None:
atomic_write_text(args.output, "".join(f"{project}\n" for project in projects))
return 0, {"projects": [str(project) for project in projects]}
if args.command == "create":
controller = BatchController.create_job(
args.job,
args.mapping,
args.projects,
certification_path=args.certifications,
allowed_suffixes=_suffixes(args.suffixes),
library_identity=args.library_identity,
)
return 0, {
"job_id": controller.job_id,
"projects": [_project_data(project) for project in controller.projects],
"states": {project.project_id: controller.project_state(project.project_id).value for project in controller.projects},
}
if args.command == "deploy-profile":
deployed = deploy_compatibility_profile(args.source, args.destination)
return 0, {"compatibility_profile": str(deployed.resolve())}
if args.command == "promote-profile":
promoted = promote_compatibility_profile(
args.source,
args.acceptance,
args.destination,
)
return 0, {"compatibility_profile": str(promoted.resolve())}
controller = BatchController.open(args.job)
if args.command == "ingest":
controller.ingest_inventory(args.project_id)
state = controller.project_state(args.project_id)
if state is ProjectState.BLOCKED:
return 3, {
"error": {
"code": "impact_blocked",
"message": "inventory impact contains blocking issues",
},
"project_id": args.project_id,
"state": state.value,
}
return 0, {"project_id": args.project_id, "state": state.value}
if args.command == "next":
project = controller.next_project()
if project is None:
return 0, {"complete": True, "project": None}
return 4, {"action": controller.action_for(project.project_id), "complete": False, "project": _project_data(project)}
if args.command == "operator-step":
result = controller.operator_step()
return (0 if result.complete else 4), _operator_step_data(result)
if args.command == "prepare-inventory":
return 0, _command_data(controller.prepare_inventory(args.project_id))
if args.command == "prepare-close":
return 4, _command_data(controller.prepare_close(args.project_id))
if args.command == "confirm-close":
controller.confirm_close(args.project_id)
return 0, {
"project_id": args.project_id,
"state": controller.project_state(args.project_id).value,
}
if args.command == "prepare-open":
return 4, _command_data(controller.prepare_open(args.project_id))
if args.command == "confirm-open":
controller.confirm_open(args.project_id)
return 0, {
"project_id": args.project_id,
"state": controller.project_state(args.project_id).value,
}
if args.command == "prepare":
command = controller.prepare_apply(args.project_id, args.rule_index)
return 4, _command_data(command)
if args.command == "verify":
result = controller.verify_apply(args.project_id, args.rule_index)
return (0 if result.passed else 3), _result_data(result)
if args.command == "prepare-undo":
return 4, _command_data(controller.prepare_undo(args.project_id))
if args.command == "confirm-undo":
controller.confirm_undo(args.project_id)
return 0, {
"project_id": args.project_id,
"state": controller.project_state(args.project_id).value,
}
if args.command == "prepare-save":
return 4, _command_data(controller.prepare_save(args.project_id))
if args.command == "confirm-saved":
state = controller.confirm_saved(args.project_id)
return (0 if state is ProjectState.VERIFIED_SAVED else 4), {"project_id": args.project_id, "state": state.value}
if args.command == "prepare-check":
return 4, _command_data(
controller.prepare_external_check(args.project_id, args.check)
)
if args.command == "confirm-check":
state = controller.confirm_external_check(args.project_id, args.check)
return (0 if state is ProjectState.VERIFIED_SAVED else 4), {
"project_id": args.project_id,
"state": state.value,
}
if args.command == "restore":
recovery = controller.restore(args.project_id)
return 0, {
"project_id": args.project_id,
"recovery_path": str(recovery),
"state": controller.project_state(args.project_id).value,
}
if args.command == "reconcile":
controller.reconcile(args.project_id)
return 0, {
"project_id": args.project_id,
"state": controller.project_state(args.project_id).value,
}
if args.command == "report":
return 0, controller.report()
if args.command == "status":
return 0, controller.status()
raise _UsageError(f"unknown command: {args.command}")
def _text(payload: dict[str, object]) -> str:
if "error" in payload:
error = payload["error"]
assert isinstance(error, dict)
return f"{error['code']}: {error['message']}"
if "action" in payload:
return f"{payload['action']}: {payload.get('project_id', payload.get('project', ''))}"
if "state" in payload:
return f"{payload.get('project_id', 'job')}: {payload['state']}"
if "job_id" in payload:
return f"job {payload['job_id']}"
if "projects" in payload and isinstance(payload["projects"], list):
return "\n".join(str(item) for item in payload["projects"])
return _canonical_display(payload)
def _canonical_display(payload: dict[str, object]) -> str:
return json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
def main(argv: Sequence[str] | None = None) -> int:
"""Run one CLI operation and return only the documented 0/2/3/4 status."""
arguments = list(sys.argv[1:] if argv is None else argv)
json_output = "--json" in arguments
arguments = [argument for argument in arguments if argument != "--json"]
try:
code, payload = _run(_parser().parse_args(arguments))
except (
InputError,
ProtocolError,
StateError,
BackupError,
CertificationError,
CompatibilityProfileError,
ControllerError,
_UsageError,
OSError,
) as error:
raw_code = getattr(error, "exit_code", 2)
code = raw_code if raw_code in {2, 3, 4} else 2
payload = {
"error": {
"code": getattr(error, "code", "invalid_input"),
"message": getattr(error, "message", str(error)),
}
}
output = _canonical_display(payload) if json_output else _text(payload)
print(output)
return code
if __name__ == "__main__": # pragma: no cover - exercised by the package entry point
raise SystemExit(main())
@@ -0,0 +1,101 @@
"""Exact durable dictionary schema for bridge commands."""
from __future__ import annotations
from .errors import ControllerError
from .models import Scope
from .protocol import BridgeCommand
_COMMAND_FIELDS = {
"action",
"command_id",
"expected_count",
"expected_fingerprint",
"expected_logical_keys",
"format_version",
"job_id",
"new_part_number",
"old_part_number",
"project_id",
"scope",
}
def command_data(command: BridgeCommand) -> dict[str, object]:
"""Return the canonical durable dictionary for a bridge command."""
return {
"action": command.action,
"command_id": command.command_id,
"expected_count": command.expected_count,
"expected_fingerprint": command.expected_fingerprint,
"expected_logical_keys": list(command.expected_logical_keys),
"format_version": command.format_version,
"job_id": command.job_id,
"new_part_number": command.new_part_number,
"old_part_number": command.old_part_number,
"project_id": command.project_id,
"scope": command.scope.value,
}
def command_from_data(value: object) -> BridgeCommand:
"""Parse one exact durable command dictionary and fail closed."""
if type(value) is not dict or set(value) != _COMMAND_FIELDS:
raise ControllerError(
"corrupt_publication",
"durable command fields are invalid",
)
strings = (
"action",
"command_id",
"expected_fingerprint",
"job_id",
"new_part_number",
"old_part_number",
"project_id",
"scope",
)
if any(type(value[name]) is not str for name in strings):
raise ControllerError(
"corrupt_publication",
"durable command strings are invalid",
)
command_id = value["command_id"]
expected_keys = value["expected_logical_keys"]
expected_count = value["expected_count"]
if (
value["format_version"] != 1
or type(value["format_version"]) is not int
or type(expected_count) is not int
or expected_count < 0
or type(expected_keys) is not list
or any(type(item) is not str for item in expected_keys)
or expected_count != len(expected_keys)
or len(command_id) != 32
or any(character not in "0123456789abcdef" for character in command_id)
):
raise ControllerError(
"corrupt_publication",
"durable command values are invalid",
)
try:
scope = Scope(value["scope"])
except ValueError as error:
raise ControllerError(
"corrupt_publication",
"durable command scope is invalid",
) from error
return BridgeCommand(
format_version=value["format_version"],
command_id=command_id,
action=value["action"],
job_id=value["job_id"],
project_id=value["project_id"],
scope=scope,
old_part_number=value["old_part_number"],
new_part_number=value["new_part_number"],
expected_logical_keys=tuple(expected_keys),
expected_count=expected_count,
expected_fingerprint=value["expected_fingerprint"],
)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,13 @@
"""Stable use-case errors shared by orchestration modules."""
from __future__ import annotations
class ControllerError(ValueError):
"""A stable orchestration failure suitable for CLI reporting."""
def __init__(self, code: str, message: str, *, exit_code: int = 2) -> None:
self.code = code
self.message = message
self.exit_code = exit_code
super().__init__(f"{code}: {message}")
+204
View File
@@ -0,0 +1,204 @@
"""Validation and discovery for replacement-job input files."""
from __future__ import annotations
import csv
import hashlib
import io
import os
from pathlib import Path
from .models import MappingRule, ProjectRef
class InputError(ValueError):
"""A user-correctable input error with a stable machine-readable code."""
def __init__(self, code: str, message: str) -> None:
self.code = code
self.message = message
super().__init__(f"{code}: {message}")
_MAPPING_HEADER = ("old_part_number", "new_part_number")
def _mapping_rows(data: bytes, source: Path) -> list[dict[str, str | None]]:
try:
with io.StringIO(data.decode("utf-8-sig"), newline="") as handle:
reader = csv.DictReader(handle, strict=True)
fields = tuple(reader.fieldnames or ())
if len(fields) != 2 or set(fields) != set(_MAPPING_HEADER):
raise InputError(
"mapping_header",
"mapping must have exactly old_part_number,new_part_number columns",
)
return list(reader)
except InputError:
raise
except UnicodeError as error:
raise InputError("mapping_encoding", f"mapping is not valid UTF-8: {source}") from error
except csv.Error as error:
raise InputError("mapping_csv", f"invalid mapping CSV: {source}") from error
def _read_input_bytes(path: Path, role: str) -> bytes:
try:
return path.read_bytes()
except OSError as error:
raise InputError(f"{role}_file", f"cannot read {role} file: {path}") from error
def _has_cycle(graph: dict[str, str]) -> bool:
visited: set[str] = set()
for source in graph:
path: set[str] = set()
node: str | None = source
while node is not None and node in graph:
if node in path:
return True
if node in visited:
break
path.add(node)
visited.add(node)
node = graph[node]
return False
def parse_mapping_bytes(data: bytes, source: Path) -> tuple[MappingRule, ...]:
"""Validate one immutable byte snapshot of an ordered replacement mapping."""
rows = _mapping_rows(data, source)
rules: list[MappingRule] = []
sources: set[str] = set()
graph: dict[str, str] = {}
for row_number, row in enumerate(rows, start=2):
if None in row:
raise InputError("mapping_columns", f"mapping row {row_number} has extra values")
old = (row.get("old_part_number") or "").strip()
new = (row.get("new_part_number") or "").strip()
if not old or not new:
raise InputError("blank_part_number", f"mapping row {row_number} has a blank part number")
old_identity = old.casefold()
new_identity = new.casefold()
if old_identity == new_identity:
raise InputError("equal_rule", f"mapping row {row_number} maps a part to itself")
if old_identity in sources:
raise InputError("duplicate_source", f"mapping row {row_number} repeats source {old!r}")
sources.add(old_identity)
graph[old_identity] = new_identity
rules.append(MappingRule(old, new))
if _has_cycle(graph):
raise InputError("mapping_cycle", "mapping contains a directed cycle")
if any(target in sources for target in graph.values()):
raise InputError("mapping_chain", "mapping contains a chained target")
return tuple(rules)
def load_mapping(path: Path) -> tuple[MappingRule, ...]:
"""Load and validate an ordered, non-chaining replacement mapping."""
source = Path(path)
return parse_mapping_bytes(_read_input_bytes(source, "mapping"), source)
def _canonical_path(path: Path) -> Path:
return path.resolve()
def _path_identity(path: Path) -> str:
canonical = os.path.normpath(str(path))
return os.path.normcase(canonical) if os.name == "nt" else canonical
def _project_id(path: Path) -> str:
return hashlib.sha256(_path_identity(path).encode("utf-8")).hexdigest()[:16]
def _allowed_suffixes(allowed_suffixes: tuple[str, ...]) -> set[str]:
return {suffix.casefold() for suffix in allowed_suffixes}
def _contains_path(parent: Path, child: Path) -> bool:
parent_identity = _path_identity(parent)
child_identity = _path_identity(child)
try:
return os.path.commonpath((parent_identity, child_identity)) == parent_identity
except ValueError:
return False
def parse_projects_bytes(
data: bytes,
source: Path,
allowed_suffixes: tuple[str, ...],
) -> tuple[ProjectRef, ...]:
"""Validate one immutable byte snapshot of a project list."""
try:
lines = data.decode("utf-8-sig").splitlines()
except UnicodeError as error:
raise InputError("projects_encoding", f"project list is not valid UTF-8: {source}") from error
suffixes = _allowed_suffixes(allowed_suffixes)
refs: list[ProjectRef] = []
identities: set[str] = set()
ownership_roots: list[Path] = []
for line_number, raw_line in enumerate(lines, start=1):
raw_path = raw_line.strip()
if not raw_path or raw_path.startswith("#"):
continue
project = Path(raw_path)
if not project.is_absolute():
raise InputError("project_path_not_absolute", f"line {line_number} is not an absolute path")
if not project.exists():
raise InputError("project_not_found", f"project on line {line_number} does not exist")
if not project.is_file():
raise InputError("project_not_file", f"project on line {line_number} is not a file")
if project.suffix.casefold() not in suffixes:
raise InputError("unsupported_project_suffix", f"project on line {line_number} has an unsupported suffix")
canonical = _canonical_path(project)
identity = _path_identity(canonical)
if identity in identities:
raise InputError("duplicate_project", f"project on line {line_number} duplicates an earlier path")
ownership_root = canonical.parent
if any(
_contains_path(existing, ownership_root)
or _contains_path(ownership_root, existing)
for existing in ownership_roots
):
raise InputError(
"overlapping_project_roots",
f"project on line {line_number} has an overlapping ownership root",
)
identities.add(identity)
ownership_roots.append(ownership_root)
refs.append(ProjectRef(_project_id(canonical), str(canonical), canonical.stem))
return tuple(refs)
def load_projects(path: Path, allowed_suffixes: tuple[str, ...]) -> tuple[ProjectRef, ...]:
"""Load an ordered list of existing absolute project-definition files."""
source = Path(path)
return parse_projects_bytes(
_read_input_bytes(source, "projects"),
source,
allowed_suffixes,
)
def discover_projects(root: Path, allowed_suffixes: tuple[str, ...]) -> tuple[Path, ...]:
"""Find project-definition candidates recursively without modifying inputs."""
if not root.exists():
raise InputError("discovery_root", f"discovery root does not exist: {root}")
if not root.is_dir():
raise InputError("discovery_root", f"discovery root is not a directory: {root}")
suffixes = _allowed_suffixes(allowed_suffixes)
candidates: dict[str, Path] = {}
for candidate in root.rglob("*"):
if not candidate.is_file() or candidate.suffix.casefold() not in suffixes:
continue
canonical = _canonical_path(candidate)
candidates.setdefault(_path_identity(canonical), canonical)
return tuple(sorted(candidates.values(), key=lambda path: str(path).casefold()))
+221
View File
@@ -0,0 +1,221 @@
"""Fail-closed correlation for bridge mailbox evidence."""
from __future__ import annotations
import os
from pathlib import Path
from .errors import ControllerError
from .models import DesignSnapshot, ProjectRef
from .protocol import (
BridgeCommand,
ProtocolError,
load_snapshot,
load_status,
snapshot_fingerprint,
)
_BLOCKING_EXIT = 3
def same_path(left: str | Path, right: str | Path) -> bool:
"""Compare paths using host-native absolute-path casing rules."""
return os.path.normcase(os.path.abspath(os.fspath(left))) == os.path.normcase(
os.path.abspath(os.fspath(right))
)
def validate_snapshot_identity(
project: ProjectRef,
snapshot: DesignSnapshot,
) -> None:
"""Require snapshot ownership to match the queued project exactly."""
if snapshot.project_id != project.project_id or not same_path(
snapshot.project_path,
project.project_path,
):
raise ControllerError(
"snapshot_project_mismatch",
f"snapshot identity does not match queued project {project.project_id}",
)
if not snapshot.fingerprint:
raise ControllerError(
"invalid_snapshot_fingerprint",
"snapshot fingerprint must be nonempty",
)
def consume_correlated_snapshot(
project: ProjectRef,
command: BridgeCommand,
expected_state: str,
status_path: Path,
snapshot_path: Path,
) -> tuple[DesignSnapshot, Path]:
"""Load a snapshot only when status and command lineage match exactly."""
try:
status = load_status(status_path)
except ProtocolError as error:
raise ControllerError(
"mailbox_evidence_uncorrelated",
"bridge status is missing or invalid",
exit_code=_BLOCKING_EXIT,
) from error
expected_details = (
("action", command.action),
("expected_count", str(command.expected_count)),
("job_id", command.job_id),
)
if (
status.command_id != command.command_id
or status.project_id != command.project_id
or status.details != expected_details
or (status.error_code is None) != (status.error_message is None)
):
raise ControllerError(
"mailbox_evidence_uncorrelated",
"bridge status does not match the durable command",
exit_code=_BLOCKING_EXIT,
)
if status.error_code is not None:
raise ControllerError(
status.error_code,
status.error_message or "bridge action failed",
exit_code=_BLOCKING_EXIT,
)
if (
status.state != expected_state
or status.snapshot_path is None
or not same_path(status.snapshot_path, snapshot_path)
):
raise ControllerError(
"mailbox_evidence_uncorrelated",
"bridge result state or snapshot path is not the expected mailbox output",
exit_code=_BLOCKING_EXIT,
)
try:
snapshot = load_snapshot(snapshot_path)
validate_snapshot_identity(project, snapshot)
except (ControllerError, ProtocolError) as error:
raise ControllerError(
"mailbox_evidence_uncorrelated",
"bridge snapshot is missing or invalid",
exit_code=_BLOCKING_EXIT,
) from error
if snapshot.fingerprint != snapshot_fingerprint(snapshot):
raise ControllerError(
"mailbox_evidence_uncorrelated",
"bridge snapshot fingerprint does not match its contents",
exit_code=_BLOCKING_EXIT,
)
return snapshot, snapshot_path.resolve()
def has_correlated_snapshot(
project: ProjectRef,
command: BridgeCommand,
status_path: Path,
snapshot_path: Path,
) -> bool:
"""Return whether mailbox outputs prove completion of this command."""
expected_state = {
"close_project": "project_closed",
"close_without_save": "project_closed",
"erc": "external_check_passed",
"inventory": "inventory_exported",
"netlist": "external_check_passed",
"open_project": "project_opened",
"packager": "external_check_passed",
"replace_part": "applied",
}.get(command.action)
if expected_state is None:
return False
try:
consume_correlated_snapshot(
project,
command,
expected_state,
status_path,
snapshot_path,
)
except (ControllerError, ProtocolError):
return False
return True
def operator_waiting_status(
status_path: Path,
command: BridgeCommand,
) -> tuple[str, str | None, str | None] | None:
"""Parse only status states that authorize an explicit operator wait."""
if not status_path.is_file():
return None
try:
status = load_status(status_path)
except ProtocolError:
return None
details = dict(status.details)
if (
status.command_id != command.command_id
or status.project_id != command.project_id
or status.snapshot_path is not None
or status.error_code is not None
or status.error_message is not None
or details.get("action") != command.action
or details.get("expected_count") != str(command.expected_count)
or details.get("job_id") != command.job_id
):
return None
if status.state == "native_dialog_opening" and command.action == "replace_part":
return status.state, None, details.get("instruction")
if status.state not in {
"manual_action_required",
"manual_project_open_required",
}:
return None
manual_route = details.get("manual_route")
allowed_routes = {
"close_project": {"manual_close_project"},
"close_without_save": {"manual_close_without_save"},
"open_project": {"manual_project_open"},
"replace_part": {"manual_exact_selection", "manual_native_dialog"},
"save": {"manual_native_save"},
"undo": {"manual_native_undo"},
}.get(command.action, set())
expected_state = (
"manual_project_open_required"
if manual_route == "manual_project_open"
else "manual_action_required"
)
if manual_route not in allowed_routes or status.state != expected_state:
return None
return status.state, manual_route, details.get("instruction")
def has_control_predecessor_status(
status_path: Path,
command: BridgeCommand,
) -> bool:
"""Recognize retained Apply evidence needed before native Undo or Save."""
if command.action not in {"save", "undo"} or not status_path.is_file():
return False
try:
status = load_status(status_path)
except ProtocolError:
return False
return (
status.command_id == command.command_id
and status.project_id == command.project_id
and status.state == "applied"
and status.snapshot_path is not None
and same_path(status.snapshot_path, status_path.parent / "snapshot.json")
and status.error_code is None
and status.error_message is None
and status.details
== (
("action", "replace_part"),
("expected_count", str(command.expected_count)),
("job_id", command.job_id),
)
)
+156
View File
@@ -0,0 +1,156 @@
"""Immutable protocol and domain records for part replacement."""
from dataclasses import dataclass
from decimal import Decimal
from enum import Enum
from typing import Mapping
class Scope(str, Enum):
FULL_PROJECT = "full_project"
CURRENT_SHEET = "current_sheet"
SELECTED_COMPONENT = "selected_component"
class ProjectState(str, Enum):
INVENTORY_PENDING = "inventory_pending"
INVENTORY_COMPLETE = "inventory_complete"
APPLY_PENDING = "apply_pending"
APPLYING = "applying"
AWAITING_SAVE_CONFIRMATION = "awaiting_save_confirmation"
AWAITING_EXTERNAL_CHECKS = "awaiting_external_checks"
VERIFIED_SAVED = "verified_saved"
BLOCKED = "blocked"
def _pairs(value: Mapping[str, str] | tuple[tuple[str, str], ...] | list[tuple[str, str]] | None) -> tuple[tuple[str, str], ...]:
if value is None:
return ()
return tuple(sorted((str(key), str(item)) for key, item in dict(value).items())) if isinstance(value, Mapping) else tuple(sorted((str(key), str(item)) for key, item in value))
def _detail_pairs(value: tuple[tuple[str, str], ...] | list[tuple[str, str]]) -> tuple[tuple[str, str], ...]:
pairs: list[tuple[str, str]] = []
for entry in value:
if len(entry) != 2:
raise ValueError("issue detail entries must contain exactly two values")
pairs.append((str(entry[0]), str(entry[1])))
return tuple(pairs)
@dataclass(frozen=True, slots=True)
class MappingRule:
old_part_number: str
new_part_number: str
@dataclass(frozen=True, slots=True)
class ProjectRef:
project_id: str
project_path: str
display_name: str
@dataclass(frozen=True, slots=True)
class PinSnapshot:
number: str
name: str
x: Decimal
y: Decimal
net: str | None = None
def __post_init__(self) -> None:
object.__setattr__(self, "x", Decimal(str(self.x)))
object.__setattr__(self, "y", Decimal(str(self.y)))
@dataclass(frozen=True, slots=True)
class UnitSnapshot:
unit_id: str
sheet: str
symbol: str
origin_x: Decimal
origin_y: Decimal
x: Decimal
y: Decimal
rotation: int
mirrored: bool
pins: tuple[PinSnapshot, ...] = ()
def __post_init__(self) -> None:
object.__setattr__(self, "origin_x", Decimal(str(self.origin_x)))
object.__setattr__(self, "origin_y", Decimal(str(self.origin_y)))
object.__setattr__(self, "x", Decimal(str(self.x)))
object.__setattr__(self, "y", Decimal(str(self.y)))
object.__setattr__(self, "rotation", int(self.rotation))
object.__setattr__(self, "pins", tuple(self.pins))
@dataclass(frozen=True, slots=True)
class ComponentSnapshot:
logical_key: str
refdes: str
part_number: str
units: tuple[UnitSnapshot, ...] = ()
attributes: tuple[tuple[str, str], ...] = ()
def __post_init__(self) -> None:
object.__setattr__(self, "units", tuple(self.units))
object.__setattr__(self, "attributes", _pairs(self.attributes))
@dataclass(frozen=True, slots=True)
class DesignSnapshot:
format_version: int
project_id: str
project_path: str
fingerprint: str
components: tuple[ComponentSnapshot, ...] = ()
def __post_init__(self) -> None:
object.__setattr__(self, "components", tuple(self.components))
@dataclass(frozen=True, slots=True)
class Issue:
code: str
severity: str
message: str
details: tuple[tuple[str, str], ...] = ()
def __post_init__(self) -> None:
object.__setattr__(self, "details", _detail_pairs(self.details))
@dataclass(frozen=True, slots=True)
class VerificationResult:
project_id: str
rule: MappingRule
expected_logical_keys: tuple[str, ...]
changed_logical_keys: tuple[str, ...] = ()
issues: tuple[Issue, ...] = ()
passed: bool = False
def __post_init__(self) -> None:
object.__setattr__(self, "expected_logical_keys", tuple(self.expected_logical_keys))
object.__setattr__(self, "changed_logical_keys", tuple(self.changed_logical_keys))
object.__setattr__(self, "issues", tuple(self.issues))
@dataclass(frozen=True, slots=True)
class ImpactCell:
project_id: str
rule: MappingRule
logical_count: int
unit_count: int
issues: tuple[Issue, ...] = ()
def __post_init__(self) -> None:
object.__setattr__(self, "issues", tuple(self.issues))
@dataclass(frozen=True, slots=True)
class ExternalChecks:
packager: bool | None = None
erc: bool | None = None
netlist: bool | None = None
@@ -0,0 +1,446 @@
"""Resumable operator-loop policy over controller use cases."""
from __future__ import annotations
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any, Protocol
from .errors import ControllerError
from .mailbox import has_control_predecessor_status, operator_waiting_status
from .models import MappingRule, ProjectRef, ProjectState
from .protocol import BridgeCommand
_MANUAL_EXIT = 4
@dataclass(frozen=True, slots=True)
class OperatorStepResult:
"""One resumable operator-loop outcome and, at most, one live command."""
complete: bool
project: ProjectRef | None
command: BridgeCommand | None
state: ProjectState | None
consumed_action: str | None = None
bridge_state: str | None = None
manual_route: str | None = None
instruction: str | None = None
class OperatorBackend(Protocol):
"""Controller operations and projections required by the operator policy."""
projects: Sequence[ProjectRef]
rules: Sequence[MappingRule]
def project_state(self, project_id: str) -> ProjectState: ...
def command_path(self, project_id: str) -> Any: ...
def _latest_event(
self,
project_id: str,
names: set[str],
) -> dict[str, Any] | None: ...
def _latest_cycle_event(
self,
project_id: str,
names: set[str],
) -> dict[str, Any] | None: ...
def _unfinished_command_publication(
self,
project_id: str,
intent_event: str,
prepared_event: str,
) -> dict[str, Any] | None: ...
def _pending_command_event(self, project_id: str) -> dict[str, Any] | None: ...
def _pending_auxiliary_event(
self,
project_id: str,
prepared_event: str,
completed_events: set[str],
) -> dict[str, Any] | None: ...
def _recorded_inventory_command(
self,
project_id: str,
prepared: dict[str, Any],
) -> BridgeCommand: ...
def _recorded_apply_command(
self,
project_id: str,
prepared: dict[str, Any],
) -> BridgeCommand: ...
def _verified_rule_indices(self, project_id: str) -> tuple[int, ...]: ...
def _matching_rule_indices(self, project_id: str) -> tuple[int, ...]: ...
def _finish_inventory_phase(self) -> None: ...
def _passed_external_checks(self, project_id: str) -> tuple[str, ...]: ...
def prepare_inventory(self, project_id: str) -> BridgeCommand: ...
def ingest_inventory(self, project_id: str) -> None: ...
def prepare_close(self, project_id: str) -> BridgeCommand: ...
def confirm_close(self, project_id: str) -> None: ...
def prepare_open(self, project_id: str) -> BridgeCommand: ...
def confirm_open(self, project_id: str) -> None: ...
def prepare_apply(self, project_id: str, rule_index: int) -> BridgeCommand: ...
def verify_apply(self, project_id: str, rule_index: int) -> Any: ...
def prepare_undo(self, project_id: str) -> BridgeCommand: ...
def confirm_undo(self, project_id: str) -> None: ...
def prepare_save(self, project_id: str) -> BridgeCommand: ...
def confirm_saved(self, project_id: str) -> ProjectState: ...
def prepare_external_check(
self,
project_id: str,
check: str,
) -> BridgeCommand: ...
def confirm_external_check(
self,
project_id: str,
check: str,
) -> ProjectState: ...
def reconcile(self, project_id: str) -> None: ...
def complete_verified_rules(self, project_id: str) -> None: ...
def _apply_rule_index(backend: OperatorBackend, project_id: str) -> int:
pending = backend._pending_command_event(project_id)
if pending is not None:
value = pending["payload"].get("rule_index")
if type(value) is int and 0 <= value < len(backend.rules):
return value
unfinished = backend._unfinished_command_publication(
project_id,
"apply_command_publication_started",
"command_prepared",
)
if unfinished is not None:
value = unfinished["payload"].get("rule_index")
if type(value) is int and 0 <= value < len(backend.rules):
return value
verified = set(backend._verified_rule_indices(project_id))
remaining = tuple(
index
for index in backend._matching_rule_indices(project_id)
if index not in verified
)
if not remaining:
raise ControllerError(
"rule_order",
"project has no remaining replacement rule to prepare",
)
return remaining[0]
def _current_command(
backend: OperatorBackend,
) -> tuple[ProjectRef | None, BridgeCommand | None]:
while True:
project = next_project(backend)
if project is None:
return None, None
project_id = project.project_id
action = action_for(backend, project_id)
if action == "ingest":
prepared = backend._latest_cycle_event(
project_id,
{"inventory_command_prepared"},
)
if prepared is not None:
return project, backend._recorded_inventory_command(
project_id,
prepared,
)
return project, backend.prepare_inventory(project_id)
if action == "prepare-close":
return project, backend.prepare_close(project_id)
if action == "prepare-open":
return project, backend.prepare_open(project_id)
if action in {"prepare-undo", "confirm-undo"}:
return project, backend.prepare_undo(project_id)
if action in {"prepare-save", "confirm-saved"}:
return project, backend.prepare_save(project_id)
if action == "prepare":
return project, backend.prepare_apply(
project_id,
_apply_rule_index(backend, project_id),
)
if action == "reconcile":
if backend.project_state(project_id) is ProjectState.APPLYING:
pending = backend._pending_command_event(project_id)
if pending is not None:
return project, backend._recorded_apply_command(
project_id,
pending,
)
matching = set(backend._matching_rule_indices(project_id))
verified = set(backend._verified_rule_indices(project_id))
if matching and matching.issubset(verified):
backend.complete_verified_rules(project_id)
continue
return project, backend.prepare_apply(
project_id,
_apply_rule_index(backend, project_id),
)
backend.reconcile(project_id)
continue
if action == "await_inventory":
backend._finish_inventory_phase()
if action_for(backend, project_id) == "await_inventory":
raise ControllerError(
"inventory_barrier_wait",
"another project inventory must complete before Apply",
exit_code=_MANUAL_EXIT,
)
continue
if action.startswith("prepare-") or action.startswith("confirm-"):
check = action.split("-", 1)[1]
if check in {"packager", "erc", "netlist"}:
pending = backend._pending_auxiliary_event(
project_id,
"external_check_command_prepared",
{"external_check_verified"},
)
if pending is None and action == "confirm-netlist":
backend.confirm_external_check(project_id, check)
continue
return project, backend.prepare_external_check(project_id, check)
raise ControllerError(
"operator_action_unsupported",
f"operator loop cannot dispatch action {action!r}",
)
def _consume(backend: OperatorBackend, command: BridgeCommand) -> None:
project_id = command.project_id
if command.action == "inventory":
backend.ingest_inventory(project_id)
return
if command.action in {"close_project", "close_without_save"}:
backend.confirm_close(project_id)
return
if command.action == "open_project":
backend.confirm_open(project_id)
return
if command.action == "replace_part":
backend.verify_apply(project_id, _apply_rule_index(backend, project_id))
return
if command.action == "undo":
backend.confirm_undo(project_id)
return
if command.action == "save":
backend.confirm_saved(project_id)
return
if command.action in {"packager", "erc", "netlist"}:
backend.confirm_external_check(project_id, command.action)
return
raise ControllerError(
"operator_action_unsupported",
f"operator loop cannot consume action {command.action!r}",
)
def _result(
backend: OperatorBackend,
project: ProjectRef | None,
command: BridgeCommand | None,
*,
consumed_action: str | None,
) -> OperatorStepResult:
if project is None or command is None:
return OperatorStepResult(
complete=True,
project=None,
command=None,
state=None,
consumed_action=consumed_action,
)
waiting = operator_waiting_status(
backend.command_path(command.project_id).parent / "status.json",
command,
)
bridge_state: str | None = None
manual_route: str | None = None
instruction: str | None = None
if waiting is not None:
bridge_state, manual_route, instruction = waiting
return OperatorStepResult(
complete=False,
project=project,
command=command,
state=backend.project_state(project.project_id),
consumed_action=consumed_action,
bridge_state=bridge_state,
manual_route=manual_route,
instruction=instruction,
)
def operator_step(backend: OperatorBackend) -> OperatorStepResult:
"""Consume at most one result and publish at most one next command."""
project, command = _current_command(backend)
if project is None or command is None:
return _result(
backend,
project,
command,
consumed_action=None,
)
status_path = backend.command_path(project.project_id).parent / "status.json"
if (
not status_path.exists()
or operator_waiting_status(status_path, command) is not None
or has_control_predecessor_status(status_path, command)
):
return _result(
backend,
project,
command,
consumed_action=None,
)
try:
_consume(backend, command)
except ControllerError as error:
if error.code != "recovery_snapshot_mismatch":
raise
return OperatorStepResult(
complete=False,
project=project,
command=None,
state=backend.project_state(project.project_id),
consumed_action=command.action,
instruction=error.message,
)
next_item, next_command = _current_command(backend)
return _result(
backend,
next_item,
next_command,
consumed_action=command.action,
)
def action_for(backend: OperatorBackend, project_id: str) -> str:
"""Project durable state projected to its next operator action."""
state = backend.project_state(project_id)
if state is ProjectState.INVENTORY_PENDING:
reconcile = backend._latest_event(project_id, {"reconcile"})
if (
reconcile is not None
and reconcile["payload"].get("recovery_event")
in {"close_without_save_verified", "restore_verified"}
and backend._latest_cycle_event(project_id, {"project_opened"}) is None
):
return "prepare-open"
return "ingest"
if state is ProjectState.INVENTORY_COMPLETE:
return "await_inventory"
if state is ProjectState.APPLY_PENDING:
backup = backend._latest_cycle_event(project_id, {"backup_verified"})
if backup is None:
return "prepare-close"
opened = backend._latest_cycle_event(project_id, {"project_opened"})
if opened is None or opened["sequence"] < backup["sequence"]:
return "prepare-open"
return "prepare"
if state is ProjectState.APPLYING:
return "reconcile"
if state is ProjectState.AWAITING_SAVE_CONFIRMATION:
if backend._pending_auxiliary_event(
project_id,
"save_command_prepared",
{"saved_snapshot_verified"},
) is not None:
return "confirm-saved"
return "prepare-save"
if state is ProjectState.AWAITING_EXTERNAL_CHECKS:
pending = backend._pending_auxiliary_event(
project_id,
"external_check_command_prepared",
{"external_check_verified"},
)
if pending is not None:
return f"confirm-{pending['payload'].get('check', 'external-check')}"
passed = set(backend._passed_external_checks(project_id))
remaining = tuple(
name for name in ("packager", "erc", "netlist") if name not in passed
)
return "confirm-netlist" if not remaining else f"prepare-{remaining[0]}"
if state is ProjectState.BLOCKED:
recovery = backend._latest_cycle_event(
project_id,
{"close_without_save_verified", "restore_verified", "undo_verified"},
)
mutation = backend._latest_cycle_event(
project_id,
{
"apply_command_publication_started",
"command_prepared",
"rule_verified",
"undo_required",
},
)
if recovery is not None and (
mutation is None or recovery["sequence"] > mutation["sequence"]
):
return "reconcile"
undo = backend._latest_cycle_event(project_id, {"undo_required"})
if undo is not None:
if backend._pending_auxiliary_event(
project_id,
"undo_command_prepared",
{"undo_verified"},
) is not None:
return "confirm-undo"
return "prepare-undo"
if mutation is not None:
return "prepare-close"
return "reconcile"
return "complete"
def next_project(backend: OperatorBackend) -> ProjectRef | None:
"""Choose the next incomplete project using fail-safe recovery priority."""
candidates = tuple(
project
for project in backend.projects
if backend.project_state(project.project_id) is not ProjectState.VERIFIED_SAVED
)
def priority(project: ProjectRef) -> int:
state = backend.project_state(project.project_id)
if state is ProjectState.INVENTORY_PENDING:
return 0
if state is ProjectState.BLOCKED:
return 2
if state is ProjectState.INVENTORY_COMPLETE:
return 3
return 1
return min(candidates, key=priority, default=None)
@@ -0,0 +1,405 @@
"""Versioned JSON snapshots and atomic mailbox publication."""
from __future__ import annotations
from dataclasses import dataclass
from decimal import Decimal, InvalidOperation
import hashlib
import json
import os
from pathlib import Path
import tempfile
from typing import Any
from .models import ComponentSnapshot, DesignSnapshot, PinSnapshot, Scope, UnitSnapshot
_SNAPSHOT_FORMAT_VERSION = 2
_MAILBOX_FORMAT_VERSION = 1
class ProtocolError(ValueError):
"""A malformed or unsupported bridge-protocol document."""
def __init__(self, code: str, message: str) -> None:
self.code = code
self.message = message
super().__init__(f"{code}: {message}")
@dataclass(frozen=True, slots=True)
class BridgeCommand:
format_version: int
command_id: str
action: str
job_id: str
project_id: str
scope: Scope
old_part_number: str
new_part_number: str
expected_logical_keys: tuple[str, ...]
expected_count: int
expected_fingerprint: str
def __post_init__(self) -> None:
object.__setattr__(self, "scope", Scope(self.scope))
object.__setattr__(self, "expected_logical_keys", tuple(self.expected_logical_keys))
@dataclass(frozen=True, slots=True)
class BridgeStatus:
format_version: int
command_id: str
project_id: str
state: str
snapshot_path: str | None
error_code: str | None
error_message: str | None
details: tuple[tuple[str, str], ...]
def __post_init__(self) -> None:
object.__setattr__(self, "details", tuple((str(key), str(value)) for key, value in self.details))
def _duplicate_rejecting_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
data: dict[str, Any] = {}
for name, value in pairs:
if name in data:
raise ProtocolError("duplicate_field", f"JSON object repeats field {name!r}")
data[name] = value
return data
def _load_json(path: Path, document_name: str) -> dict[str, Any]:
try:
text = path.read_text(encoding="utf-8")
except UnicodeError as error:
raise ProtocolError("invalid_encoding", f"{document_name} is not valid UTF-8: {path}") from error
except OSError as error:
raise ProtocolError("protocol_file", f"cannot read {document_name}: {path}") from error
try:
data = json.loads(text, object_pairs_hook=_duplicate_rejecting_object)
except ProtocolError:
raise
except json.JSONDecodeError as error:
raise ProtocolError("invalid_json", f"invalid {document_name} JSON: {path}") from error
if not isinstance(data, dict):
raise ProtocolError("wrong_type", f"{document_name} root must be an object")
return data
def _expect_fields(data: dict[str, Any], required: tuple[str, ...], context: str) -> None:
missing = set(required) - set(data)
if missing:
raise ProtocolError("missing_required_field", f"{context} is missing {sorted(missing)[0]!r}")
unknown = set(data) - set(required)
if unknown:
raise ProtocolError("unknown_field", f"{context} has unknown field {sorted(unknown)[0]!r}")
def _string(value: Any, context: str) -> str:
if not isinstance(value, str):
raise ProtocolError("wrong_type", f"{context} must be a string")
return value
def _optional_string(value: Any, context: str) -> str | None:
if value is None:
return None
return _string(value, context)
def _integer(value: Any, context: str) -> int:
if isinstance(value, bool) or not isinstance(value, int):
raise ProtocolError("wrong_type", f"{context} must be an integer")
return value
def _boolean(value: Any, context: str) -> bool:
if not isinstance(value, bool):
raise ProtocolError("wrong_type", f"{context} must be a boolean")
return value
def _array(value: Any, context: str) -> list[Any]:
if not isinstance(value, list):
raise ProtocolError("wrong_type", f"{context} must be an array")
return value
def _object(value: Any, context: str) -> dict[str, Any]:
if not isinstance(value, dict):
raise ProtocolError("wrong_type", f"{context} must be an object")
return value
def _decimal(value: Any, context: str) -> Decimal:
text = _string(value, context)
try:
decimal = Decimal(text)
except InvalidOperation as error:
raise ProtocolError("invalid_decimal", f"{context} is not a Decimal string") from error
if not decimal.is_finite():
raise ProtocolError("invalid_decimal", f"{context} must be finite")
return decimal
def _pin_from_data(data: Any, context: str) -> PinSnapshot:
pin = _object(data, context)
_expect_fields(pin, ("number", "name", "x", "y", "net"), context)
return PinSnapshot(
number=_string(pin["number"], f"{context}.number"),
name=_string(pin["name"], f"{context}.name"),
x=_decimal(pin["x"], f"{context}.x"),
y=_decimal(pin["y"], f"{context}.y"),
net=_optional_string(pin["net"], f"{context}.net"),
)
def _unit_from_data(data: Any, context: str) -> UnitSnapshot:
unit = _object(data, context)
_expect_fields(
unit,
(
"unit_id",
"sheet",
"symbol",
"origin_x",
"origin_y",
"x",
"y",
"rotation",
"mirrored",
"pins",
),
context,
)
pins = tuple(_pin_from_data(pin, f"{context}.pins[{index}]") for index, pin in enumerate(_array(unit["pins"], f"{context}.pins")))
numbers = [pin.number for pin in pins]
if len(numbers) != len(set(numbers)):
raise ProtocolError("duplicate_pin_number", f"{context} has duplicate pin numbers")
return UnitSnapshot(
unit_id=_string(unit["unit_id"], f"{context}.unit_id"),
sheet=_string(unit["sheet"], f"{context}.sheet"),
symbol=_string(unit["symbol"], f"{context}.symbol"),
origin_x=_decimal(unit["origin_x"], f"{context}.origin_x"),
origin_y=_decimal(unit["origin_y"], f"{context}.origin_y"),
x=_decimal(unit["x"], f"{context}.x"),
y=_decimal(unit["y"], f"{context}.y"),
rotation=_integer(unit["rotation"], f"{context}.rotation"),
mirrored=_boolean(unit["mirrored"], f"{context}.mirrored"),
pins=pins,
)
def _component_from_data(data: Any, context: str) -> ComponentSnapshot:
component = _object(data, context)
_expect_fields(component, ("logical_key", "refdes", "part_number", "units", "attributes"), context)
units = tuple(_unit_from_data(unit, f"{context}.units[{index}]") for index, unit in enumerate(_array(component["units"], f"{context}.units")))
unit_ids = [unit.unit_id for unit in units]
if len(unit_ids) != len(set(unit_ids)):
raise ProtocolError("duplicate_unit_id", f"{context} has duplicate unit IDs")
attributes: list[tuple[str, str]] = []
for index, raw_attribute in enumerate(_array(component["attributes"], f"{context}.attributes")):
attribute_context = f"{context}.attributes[{index}]"
attribute = _object(raw_attribute, attribute_context)
_expect_fields(attribute, ("name", "value"), attribute_context)
attributes.append((_string(attribute["name"], f"{attribute_context}.name"), _string(attribute["value"], f"{attribute_context}.value")))
attribute_names = [name for name, _ in attributes]
if len(attribute_names) != len(set(attribute_names)):
raise ProtocolError("duplicate_attribute_name", f"{context} has duplicate attribute names")
return ComponentSnapshot(
logical_key=_string(component["logical_key"], f"{context}.logical_key"),
refdes=_string(component["refdes"], f"{context}.refdes"),
part_number=_string(component["part_number"], f"{context}.part_number"),
units=units,
attributes=tuple(attributes),
)
def _snapshot_from_data(data: dict[str, Any]) -> DesignSnapshot:
if "format_version" not in data:
raise ProtocolError("missing_required_field", "snapshot is missing 'format_version'")
format_version = _integer(data["format_version"], "snapshot.format_version")
if format_version == 1:
raise ProtocolError(
"legacy_snapshot_missing_origin",
"snapshot format version 1 cannot prove unit origin preservation",
)
if format_version != _SNAPSHOT_FORMAT_VERSION:
raise ProtocolError("unsupported_format_version", f"unsupported snapshot format version {format_version}")
_expect_fields(data, ("format_version", "project_id", "project_path", "fingerprint", "components"), "snapshot")
components = tuple(_component_from_data(component, f"snapshot.components[{index}]") for index, component in enumerate(_array(data["components"], "snapshot.components")))
logical_keys = [component.logical_key for component in components]
if len(logical_keys) != len(set(logical_keys)):
raise ProtocolError("duplicate_logical_key", "snapshot has duplicate logical keys")
return DesignSnapshot(
format_version=format_version,
project_id=_string(data["project_id"], "snapshot.project_id"),
project_path=_string(data["project_path"], "snapshot.project_path"),
fingerprint=_string(data["fingerprint"], "snapshot.fingerprint"),
components=components,
)
def load_snapshot(path: Path) -> DesignSnapshot:
"""Load a fully validated snapshot with independent origin evidence."""
return _snapshot_from_data(_load_json(path, "snapshot"))
def _pin_to_data(pin: PinSnapshot) -> dict[str, object]:
if not isinstance(pin, PinSnapshot):
raise ProtocolError("wrong_type", "snapshot pins must be PinSnapshot records")
return {"number": pin.number, "name": pin.name, "x": str(pin.x), "y": str(pin.y), "net": pin.net}
def _unit_to_data(unit: UnitSnapshot) -> dict[str, object]:
if not isinstance(unit, UnitSnapshot):
raise ProtocolError("wrong_type", "snapshot units must be UnitSnapshot records")
return {
"unit_id": unit.unit_id,
"sheet": unit.sheet,
"symbol": unit.symbol,
"origin_x": str(unit.origin_x),
"origin_y": str(unit.origin_y),
"x": str(unit.x),
"y": str(unit.y),
"rotation": unit.rotation,
"mirrored": unit.mirrored,
"pins": [_pin_to_data(pin) for pin in unit.pins],
}
def _component_to_data(component: ComponentSnapshot) -> dict[str, object]:
if not isinstance(component, ComponentSnapshot):
raise ProtocolError("wrong_type", "snapshot components must be ComponentSnapshot records")
attributes: list[dict[str, object]] = []
for entry in component.attributes:
if not isinstance(entry, tuple) or len(entry) != 2:
raise ProtocolError("wrong_type", "snapshot attributes must be name/value pairs")
attributes.append({"name": entry[0], "value": entry[1]})
return {
"logical_key": component.logical_key,
"refdes": component.refdes,
"part_number": component.part_number,
"units": [_unit_to_data(unit) for unit in component.units],
"attributes": sorted(attributes, key=lambda attribute: str(attribute["name"])),
}
def _snapshot_to_data(snapshot: DesignSnapshot) -> dict[str, object]:
if not isinstance(snapshot, DesignSnapshot):
raise ProtocolError("wrong_type", "snapshot must be a DesignSnapshot")
data: dict[str, object] = {
"format_version": snapshot.format_version,
"project_id": snapshot.project_id,
"project_path": snapshot.project_path,
"fingerprint": snapshot.fingerprint,
"components": [_component_to_data(component) for component in snapshot.components],
}
_snapshot_from_data(data)
return data
def _canonical_json(data: object) -> str:
return json.dumps(data, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False)
def snapshot_fingerprint(snapshot: DesignSnapshot) -> str:
"""Hash the complete semantic snapshot except its stored fingerprint."""
data = _snapshot_to_data(snapshot)
del data["fingerprint"]
return hashlib.sha256(_canonical_json(data).encode("utf-8")).hexdigest()
def atomic_write_text(path: Path, text: str) -> None:
"""Atomically publish UTF-8 text after durable staging in the target directory."""
normalized = text.replace("\r\n", "\n").replace("\r", "\n")
temporary: Path | None = None
try:
descriptor, temporary_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
temporary = Path(temporary_name)
with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as handle:
handle.write(normalized)
handle.flush()
os.fsync(handle.fileno())
os.replace(temporary, path)
temporary = None
finally:
if temporary is not None:
try:
temporary.unlink()
except FileNotFoundError:
pass
def write_snapshot(path: Path, snapshot: DesignSnapshot) -> None:
"""Write one canonical version-1 snapshot through the atomic mailbox path."""
atomic_write_text(path, _canonical_json(_snapshot_to_data(snapshot)) + "\n")
def _command_to_data(command: BridgeCommand) -> dict[str, object]:
if not isinstance(command, BridgeCommand):
raise ProtocolError("wrong_type", "command must be a BridgeCommand")
_integer(command.format_version, "command.format_version")
if command.format_version != _MAILBOX_FORMAT_VERSION:
raise ProtocolError("unsupported_format_version", f"unsupported command format version {command.format_version}")
string_fields = (
(command.command_id, "command_id"), (command.action, "action"), (command.job_id, "job_id"),
(command.project_id, "project_id"), (command.old_part_number, "old_part_number"),
(command.new_part_number, "new_part_number"), (command.expected_fingerprint, "expected_fingerprint"),
)
for value, name in string_fields:
_string(value, f"command.{name}")
_integer(command.expected_count, "command.expected_count")
if any(not isinstance(key, str) for key in command.expected_logical_keys):
raise ProtocolError("wrong_type", "command.expected_logical_keys must contain strings")
return {
"format_version": command.format_version,
"command_id": command.command_id,
"action": command.action,
"job_id": command.job_id,
"project_id": command.project_id,
"scope": command.scope.value,
"old_part_number": command.old_part_number,
"new_part_number": command.new_part_number,
"expected_logical_keys": list(command.expected_logical_keys),
"expected_count": command.expected_count,
"expected_fingerprint": command.expected_fingerprint,
}
def write_command(path: Path, command: BridgeCommand) -> None:
"""Publish an apply command atomically in canonical JSON."""
atomic_write_text(path, _canonical_json(_command_to_data(command)) + "\n")
def load_status(path: Path) -> BridgeStatus:
"""Load a fully validated version-1 bridge status document."""
data = _load_json(path, "status")
_expect_fields(
data,
("format_version", "command_id", "project_id", "state", "snapshot_path", "error_code", "error_message", "details"),
"status",
)
format_version = _integer(data["format_version"], "status.format_version")
if format_version != _MAILBOX_FORMAT_VERSION:
raise ProtocolError("unsupported_format_version", f"unsupported status format version {format_version}")
details: list[tuple[str, str]] = []
for index, entry in enumerate(_array(data["details"], "status.details")):
if not isinstance(entry, list) or len(entry) != 2:
raise ProtocolError("wrong_type", f"status.details[{index}] must be a pair")
details.append((_string(entry[0], f"status.details[{index}][0]"), _string(entry[1], f"status.details[{index}][1]")))
detail_names = [name for name, _ in details]
if len(detail_names) != len(set(detail_names)):
raise ProtocolError("duplicate_detail_name", "status has duplicate detail names")
return BridgeStatus(
format_version,
_string(data["command_id"], "status.command_id"),
_string(data["project_id"], "status.project_id"),
_string(data["state"], "status.state"),
_optional_string(data["snapshot_path"], "status.snapshot_path"),
_optional_string(data["error_code"], "status.error_code"),
_optional_string(data["error_message"], "status.error_message"),
tuple(details),
)
+217
View File
@@ -0,0 +1,217 @@
"""Passive, deterministic operator reports for part-replacement batches."""
from __future__ import annotations
import csv
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from html import escape
import io
import json
from pathlib import Path
import re
from .certification import Certification
from .models import ExternalChecks, ImpactCell, Issue, ProjectState, VerificationResult
from .protocol import atomic_write_text
_REMOTE_URL = re.compile(r"(?i)\b(?:https?|ftp)://[^\s\"'<>]+")
_HARD_SEVERITIES = frozenset({"blocking", "error", "fatal", "hard"})
def _pairs(value: Mapping[str, object] | Sequence[tuple[str, object]]) -> tuple[tuple[str, object], ...]:
entries = value.items() if isinstance(value, Mapping) else value
return tuple(sorted(((str(key), item) for key, item in entries), key=lambda entry: entry[0]))
@dataclass(frozen=True, slots=True)
class BatchReport:
"""Immutable report inputs projected from signed-off records and event state."""
job_id: str
generated_time: str
input_hashes: Mapping[str, str] | Sequence[tuple[str, str]] = ()
project_states: Mapping[str, ProjectState] | Sequence[tuple[str, ProjectState]] = ()
impact_cells: Sequence[ImpactCell] = ()
verification_results: Sequence[VerificationResult] = ()
external_checks: Mapping[str, ExternalChecks] | Sequence[tuple[str, ExternalChecks]] = ()
certifications: Sequence[Certification] = ()
backup_path: str | None = None
resume_action: str | None = None
advisory_attachments: Sequence[str] = ()
def __post_init__(self) -> None:
object.__setattr__(self, "input_hashes", tuple((key, str(value)) for key, value in _pairs(self.input_hashes)))
object.__setattr__(
self,
"project_states",
tuple((key, ProjectState(value)) for key, value in _pairs(self.project_states)),
)
object.__setattr__(self, "impact_cells", tuple(self.impact_cells))
object.__setattr__(self, "verification_results", tuple(self.verification_results))
object.__setattr__(self, "external_checks", tuple(_pairs(self.external_checks)))
object.__setattr__(self, "certifications", tuple(self.certifications))
object.__setattr__(self, "advisory_attachments", tuple(str(item) for item in self.advisory_attachments))
def _canonical_json(value: object) -> str:
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False)
def _issue_data(issue: Issue) -> dict[str, object]:
return {
"code": issue.code,
"details": dict(sorted(issue.details)),
"message": issue.message,
"severity": issue.severity,
}
def _is_hard(issue: Issue) -> bool:
return issue.severity.casefold() in _HARD_SEVERITIES
def _result_data(result: VerificationResult) -> dict[str, object]:
hard_issues = [_issue_data(issue) for issue in result.issues if _is_hard(issue)]
nonblocking = [_issue_data(issue) for issue in result.issues if not _is_hard(issue)]
return {
"changed_logical_keys": list(result.changed_logical_keys),
"expected_logical_keys": list(result.expected_logical_keys),
"hard_issues": hard_issues,
"new_part_number": result.rule.new_part_number,
"nonblocking_differences": nonblocking,
"old_part_number": result.rule.old_part_number,
"passed": result.passed,
"project_id": result.project_id,
}
def _result_key(result: VerificationResult) -> tuple[str, str, str]:
return result.project_id, result.rule.old_part_number, result.rule.new_part_number
def write_impact_csv(path: Path, cells: Sequence[ImpactCell]) -> None:
"""Write the project-by-mapping impact matrix as a deterministic CSV file."""
stream = io.StringIO(newline="")
writer = csv.DictWriter(
stream,
fieldnames=("project_id", "old_part_number", "new_part_number", "logical_count", "unit_count", "issues"),
lineterminator="\n",
)
writer.writeheader()
for cell in sorted(cells, key=lambda item: (item.project_id, item.rule.old_part_number, item.rule.new_part_number)):
writer.writerow(
{
"project_id": cell.project_id,
"old_part_number": cell.rule.old_part_number,
"new_part_number": cell.rule.new_part_number,
"logical_count": cell.logical_count,
"unit_count": cell.unit_count,
"issues": "; ".join(f"{issue.code}: {issue.message}" for issue in cell.issues),
}
)
atomic_write_text(path, stream.getvalue())
def write_differences_json(path: Path, results: Sequence[VerificationResult]) -> None:
"""Write hard verification issues and advisory differences in canonical JSON."""
data = {"results": [_result_data(result) for result in sorted(results, key=_result_key)]}
atomic_write_text(path, _canonical_json(data) + "\n")
def _safe_text(value: object) -> str:
"""Escape display text and remove URL-like content from static local reports."""
return escape(_REMOTE_URL.sub("", str(value)), quote=True)
def _status(report: BatchReport) -> str:
states = tuple(state for _, state in report.project_states)
if states and all(state is ProjectState.VERIFIED_SAVED for state in states):
return "SUCCESS"
if any(state is ProjectState.VERIFIED_SAVED for state in states):
return "PARTIAL"
if any(state is ProjectState.BLOCKED for state in states):
return "BLOCKED"
return "IN PROGRESS"
def _table(headers: Sequence[str], rows: Sequence[Sequence[object]]) -> str:
header_html = "".join(f"<th>{_safe_text(header)}</th>" for header in headers)
row_html = "".join(
"<tr>" + "".join(f"<td>{_safe_text(value)}</td>" for value in row) + "</tr>"
for row in rows
)
return f"<table><thead><tr>{header_html}</tr></thead><tbody>{row_html}</tbody></table>"
def _check_text(name: str, value: bool | None) -> str:
outcome = "PASS" if value is True else "FAIL" if value is False else "NOT RUN"
return f"{name}: {outcome}"
def write_summary_html(path: Path, report: BatchReport) -> None:
"""Write an escaped, offline-only HTML projection of immutable batch evidence."""
state_rows = [(project_id, state.value.upper()) for project_id, state in report.project_states]
impact_rows = [
(cell.project_id, cell.rule.old_part_number, cell.rule.new_part_number, cell.logical_count, cell.unit_count)
for cell in sorted(report.impact_cells, key=lambda item: (item.project_id, item.rule.old_part_number, item.rule.new_part_number))
]
hard_rows: list[tuple[object, ...]] = []
advisory_rows: list[tuple[object, ...]] = []
for cell in sorted(report.impact_cells, key=lambda item: (item.project_id, item.rule.old_part_number, item.rule.new_part_number)):
for issue in cell.issues:
if _is_hard(issue):
hard_rows.append(
(cell.project_id, cell.rule.old_part_number, cell.rule.new_part_number, issue.code, issue.message)
)
for result in sorted(report.verification_results, key=_result_key):
for issue in result.issues:
row = (result.project_id, result.rule.old_part_number, result.rule.new_part_number, issue.code, issue.message)
(hard_rows if _is_hard(issue) else advisory_rows).append(row)
hard_rows.sort()
check_rows = [
(project_id, _check_text("packager", checks.packager), _check_text("erc", checks.erc), _check_text("netlist", checks.netlist))
for project_id, checks in report.external_checks
]
certification_rows = [
(
certification.rule.old_part_number,
certification.rule.new_part_number,
certification.target_fingerprint,
certification.library_identity or "not recorded",
certification.created_utc,
)
for certification in sorted(
report.certifications,
key=lambda item: (item.rule.old_part_number, item.rule.new_part_number, item.target_fingerprint),
)
]
attachments = "".join(f"<li>{_safe_text(item)}</li>" for item in report.advisory_attachments) or "<li>None</li>"
document = """<!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>Part replacement batch report</title>
<style>body{font-family:Arial,sans-serif;margin:2rem;color:#1d2731;background:#fff}h1,h2{margin:1.25rem 0 .5rem}table{border-collapse:collapse;width:100%;margin:.5rem 0 1.25rem}th,td{border:1px solid #aab4bd;padding:.45rem;text-align:left;vertical-align:top}th{background:#e9eff3}code{font-family:Consolas,monospace}p{margin:.4rem 0}.status{font-weight:bold}</style>
</head><body>"""
document += f"<h1>BATCH STATUS: {_safe_text(_status(report))}</h1>"
document += f"<p>Job ID: <code>{_safe_text(report.job_id)}</code></p>"
document += f"<p>Generated time: {_safe_text(report.generated_time)}</p>"
document += "<h2>Input hashes</h2>" + _table(("Input", "Hash"), report.input_hashes)
document += "<h2>Project states</h2>" + _table(("Project", "State"), state_rows)
document += "<h2>Project-by-mapping impact</h2>" + _table(
("Project", "Old part number", "New part number", "Logical components", "Placed units"), impact_rows
)
document += "<h2>Hard issues</h2>" + _table(
("Project", "Old part number", "New part number", "Code", "Message"), hard_rows
)
document += "<h2>Nonblocking attribute differences</h2>" + _table(
("Project", "Old part number", "New part number", "Code", "Message"), advisory_rows
)
document += "<h2>External checks</h2>" + _table(("Project", "Packager", "ERC", "Netlist"), check_rows)
document += "<h2>Certification identity</h2>" + _table(
("Old part number", "New part number", "Target fingerprint", "Library identity", "Created"), certification_rows
)
document += f"<h2>Backup path</h2><p>{_safe_text(report.backup_path or 'Not recorded')}</p>"
document += f"<h2>Resume action</h2><p>{_safe_text(report.resume_action or 'No resume action recorded.')}</p>"
document += f"<h2>Advisory attachments</h2><ul>{attachments}</ul>"
document += "</body></html>\n"
atomic_write_text(path, document)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,331 @@
"""Deterministic impact analysis and fail-closed replacement verification."""
from __future__ import annotations
from collections.abc import Iterable, Sequence
from decimal import Decimal, InvalidOperation
from .models import ComponentSnapshot, DesignSnapshot, ImpactCell, Issue, MappingRule, UnitSnapshot, VerificationResult
_DEFAULT_TOLERANCE = Decimal("0.000001")
def _part_identity(value: str) -> str:
return value.strip().casefold()
def _issue(code: str, message: str, *, severity: str = "error", **details: object) -> Issue:
return Issue(code, severity, message, tuple((name, str(value)) for name, value in details.items()))
def _component_index(snapshot: DesignSnapshot) -> tuple[dict[str, ComponentSnapshot], tuple[Issue, ...]]:
index: dict[str, ComponentSnapshot] = {}
issues: list[Issue] = []
for component in snapshot.components:
if component.logical_key in index:
issues.append(_issue(
"duplicate_logical_key",
"Snapshot contains a duplicate logical component identity.",
logical_key=component.logical_key,
))
continue
index[component.logical_key] = component
issues.extend(_component_structure_issues(component))
return index, tuple(issues)
def _component_structure_issues(component: ComponentSnapshot) -> tuple[Issue, ...]:
issues: list[Issue] = []
units: set[str] = set()
for unit in component.units:
if unit.unit_id in units:
issues.append(_issue(
"duplicate_unit_id",
"Component contains a duplicate unit identity.",
logical_key=component.logical_key,
unit_id=unit.unit_id,
))
continue
units.add(unit.unit_id)
pins: set[str] = set()
for pin in unit.pins:
if pin.number in pins:
issues.append(_issue(
"duplicate_pin_number",
"Unit contains a duplicate pin number.",
logical_key=component.logical_key,
unit_id=unit.unit_id,
pin_number=pin.number,
))
pins.add(pin.number)
return tuple(issues)
def _component_evidence_issues(component: ComponentSnapshot) -> tuple[Issue, ...]:
issues: list[Issue] = []
if not component.units:
return (_issue(
"missing_units",
"Matched component has no observed unit or gate evidence.",
logical_key=component.logical_key,
),)
for unit in component.units:
if not unit.pins:
issues.append(_issue(
"missing_pins",
"Matched component unit has no observed pin evidence.",
logical_key=component.logical_key,
unit_id=unit.unit_id,
))
continue
for pin in unit.pins:
if not isinstance(pin.net, str) or not pin.net.strip():
issues.append(_issue(
"missing_network_identity",
"Matched component pin has no observed network identity.",
logical_key=component.logical_key,
unit_id=unit.unit_id,
pin_number=pin.number,
))
return tuple(issues)
def _snapshot_ambiguity_issues(snapshot: DesignSnapshot) -> tuple[Issue, ...]:
_, issues = _component_index(snapshot)
result = list(issues)
refdes_keys: dict[str, str] = {}
for component in snapshot.components:
refdes_key = component.refdes.strip().casefold()
previous_key = refdes_keys.get(refdes_key)
if previous_key is not None and previous_key != component.logical_key:
result.append(_issue(
"duplicate_refdes",
"Snapshot contains a duplicate reference designator.",
refdes=component.refdes,
))
else:
refdes_keys[refdes_key] = component.logical_key
return tuple(result)
def _valid_rule(rule: MappingRule) -> bool:
return bool(_part_identity(rule.old_part_number)) and bool(_part_identity(rule.new_part_number))
def eligible_logical_keys(snapshot: DesignSnapshot, rule: MappingRule) -> tuple[str, ...]:
"""Return matching component identities in the snapshot's original order.
Directly-constructed ambiguous snapshots are ineligible. Protocol-loaded
snapshots already reject these shapes, but a verifier must not trust callers.
"""
if _snapshot_ambiguity_issues(snapshot) or not _valid_rule(rule):
return ()
old_part = _part_identity(rule.old_part_number)
return tuple(
component.logical_key
for component in snapshot.components
if _part_identity(component.part_number) == old_part
)
def build_impact_matrix(snapshots: Iterable[DesignSnapshot], rules: Sequence[MappingRule]) -> tuple[ImpactCell, ...]:
"""Build project-by-rule impact cells without changing source snapshots."""
cells: list[ImpactCell] = []
for snapshot in snapshots:
snapshot_issues = _snapshot_ambiguity_issues(snapshot)
for rule in rules:
rule_issues = () if _valid_rule(rule) else (
_issue("invalid_mapping_rule", "Mapping rule has a blank Part Number."),
)
keys = () if snapshot_issues or rule_issues else eligible_logical_keys(snapshot, rule)
components = {component.logical_key: component for component in snapshot.components}
matches = tuple(components[key] for key in keys)
evidence_issues = tuple(issue for component in matches for issue in _component_evidence_issues(component))
cells.append(ImpactCell(
project_id=snapshot.project_id,
rule=rule,
logical_count=len(matches),
unit_count=sum(len(component.units) for component in matches),
issues=snapshot_issues + rule_issues + evidence_issues,
))
return tuple(cells)
def _tolerance_issue(coordinate_tolerance: Decimal) -> Issue | None:
try:
tolerance = Decimal(str(coordinate_tolerance))
except (InvalidOperation, ValueError):
return _issue("invalid_coordinate_tolerance", "Coordinate tolerance is not a finite Decimal.")
if not tolerance.is_finite() or tolerance < 0:
return _issue("invalid_coordinate_tolerance", "Coordinate tolerance must be a non-negative finite Decimal.")
return None
def _within_tolerance(before: Decimal, after: Decimal, tolerance: Decimal) -> bool:
return before.is_finite() and after.is_finite() and abs(before - after) <= tolerance
def _changed(before: ComponentSnapshot, after: ComponentSnapshot) -> bool:
return before != after
def _compare_unit(
logical_key: str,
before: UnitSnapshot,
after: UnitSnapshot,
tolerance: Decimal,
) -> tuple[Issue, ...]:
issues: list[Issue] = []
if before.sheet != after.sheet:
issues.append(_issue("sheet_changed", "Component unit moved to a different sheet.", logical_key=logical_key, unit_id=before.unit_id))
if not (
_within_tolerance(before.origin_x, after.origin_x, tolerance)
and _within_tolerance(before.origin_y, after.origin_y, tolerance)
):
issues.append(
_issue(
"origin_changed",
"Component unit origin changed.",
logical_key=logical_key,
unit_id=before.unit_id,
)
)
if not (_within_tolerance(before.x, after.x, tolerance) and _within_tolerance(before.y, after.y, tolerance)):
issues.append(_issue("placement_changed", "Component placement changed.", logical_key=logical_key, unit_id=before.unit_id))
if before.rotation != after.rotation:
issues.append(_issue("rotation_changed", "Component rotation changed.", logical_key=logical_key, unit_id=before.unit_id))
if before.mirrored != after.mirrored:
issues.append(_issue("mirror_changed", "Component mirror state changed.", logical_key=logical_key, unit_id=before.unit_id))
if before.symbol != after.symbol:
issues.append(_issue(
"library_symbol_changed",
"Library-controlled symbol identity changed.",
severity="info",
logical_key=logical_key,
unit_id=before.unit_id,
))
before_pins = {pin.number: pin for pin in before.pins}
after_pins = {pin.number: pin for pin in after.pins}
if before_pins.keys() != after_pins.keys():
issues.append(_issue("pin_set_changed", "Component pin-number set changed.", logical_key=logical_key, unit_id=before.unit_id))
return tuple(issues)
for number, before_pin in before_pins.items():
after_pin = after_pins[number]
if not (_within_tolerance(before_pin.x, after_pin.x, tolerance) and _within_tolerance(before_pin.y, after_pin.y, tolerance)):
issues.append(_issue("pin_position_changed", "Pin position changed.", logical_key=logical_key, unit_id=before.unit_id, pin_number=number))
if before_pin.net != after_pin.net:
issues.append(_issue("connectivity_changed", "Pin net identity changed.", logical_key=logical_key, unit_id=before.unit_id, pin_number=number))
if before_pin.name != after_pin.name:
issues.append(_issue(
"library_pin_name_changed",
"Library-controlled pin name changed.",
severity="info",
logical_key=logical_key,
unit_id=before.unit_id,
pin_number=number,
))
return tuple(issues)
def _compare_expected_component(
before: ComponentSnapshot,
after: ComponentSnapshot,
rule: MappingRule,
tolerance: Decimal,
) -> tuple[Issue, ...]:
issues = list(_component_evidence_issues(before))
issues.extend(_component_evidence_issues(after))
if _part_identity(before.part_number) != _part_identity(rule.old_part_number):
issues.append(_issue("source_part_number_mismatch", "Expected component does not have the rule source Part Number.", logical_key=before.logical_key))
if _part_identity(after.part_number) != _part_identity(rule.new_part_number):
issues.append(_issue("wrong_target_part_number", "Replaced component does not have the requested target Part Number.", logical_key=before.logical_key, actual=after.part_number, expected=rule.new_part_number))
if before.refdes != after.refdes:
issues.append(_issue("refdes_changed", "Component reference designator changed.", logical_key=before.logical_key))
before_units = {unit.unit_id: unit for unit in before.units}
after_units = {unit.unit_id: unit for unit in after.units}
if before_units.keys() != after_units.keys():
issues.append(_issue("unit_set_changed", "Component gate or slot set changed.", logical_key=before.logical_key))
return tuple(issues)
for unit_id, before_unit in before_units.items():
issues.extend(_compare_unit(before.logical_key, before_unit, after_units[unit_id], tolerance))
if before.attributes != after.attributes:
issues.append(_issue(
"library_attribute_changed",
"Library-controlled component attributes changed.",
severity="info",
logical_key=before.logical_key,
))
return tuple(issues)
def verify_replacement(
before: DesignSnapshot,
after: DesignSnapshot,
rule: MappingRule,
expected_logical_keys: Sequence[str],
coordinate_tolerance: Decimal = _DEFAULT_TOLERANCE,
) -> VerificationResult:
"""Verify that only the selected components changed under Library Wins rules."""
issues: list[Issue] = []
tolerance_error = _tolerance_issue(coordinate_tolerance)
if tolerance_error is not None:
issues.append(tolerance_error)
tolerance = _DEFAULT_TOLERANCE
else:
tolerance = Decimal(str(coordinate_tolerance))
if not _valid_rule(rule):
issues.append(_issue("invalid_mapping_rule", "Mapping rule has a blank Part Number."))
if before.project_id != after.project_id:
issues.append(_issue("project_id_changed", "Project identity changed between snapshots.", before=before.project_id, after=after.project_id))
if before.project_path != after.project_path:
issues.append(_issue("project_path_changed", "Project path changed between snapshots.", before=before.project_path, after=after.project_path))
before_index, _ = _component_index(before)
after_index, _ = _component_index(after)
issues.extend(_snapshot_ambiguity_issues(before))
issues.extend(_snapshot_ambiguity_issues(after))
before_keys = set(before_index)
after_keys = set(after_index)
if len(before.components) != len(after.components):
issues.append(_issue("component_count_changed", "Logical component count changed.", before=len(before.components), after=len(after.components)))
for component in before.components:
if component.logical_key not in after_keys:
issues.append(_issue("component_removed", "Logical component was removed.", logical_key=component.logical_key))
for component in after.components:
if component.logical_key not in before_keys:
issues.append(_issue("component_added", "Unexpected logical component was added.", logical_key=component.logical_key))
expected = tuple(expected_logical_keys)
expected_set = set(expected)
if len(expected) != len(expected_set):
issues.append(_issue("duplicate_expected_logical_key", "Expected logical-component keys are not unique."))
for logical_key in expected:
if logical_key not in before_index or logical_key not in after_index:
issues.append(_issue("expected_logical_key_missing", "Expected logical component is missing from a snapshot.", logical_key=logical_key))
continue
issues.extend(_compare_expected_component(before_index[logical_key], after_index[logical_key], rule, tolerance))
changed_keys: list[str] = []
for component in before.components:
logical_key = component.logical_key
if logical_key in after_index and _changed(component, after_index[logical_key]):
if logical_key not in changed_keys:
changed_keys.append(logical_key)
if logical_key not in expected_set:
issues.append(_issue("unexpected_changed_logical_key", "An unselected logical component changed.", logical_key=logical_key))
issues.append(_issue("unrelated_component_changed", "An unrelated logical component changed.", logical_key=logical_key))
return VerificationResult(
project_id=before.project_id,
rule=rule,
expected_logical_keys=expected,
changed_logical_keys=tuple(changed_keys),
issues=tuple(issues),
passed=not any(issue.severity == "error" for issue in issues),
)
@@ -0,0 +1,15 @@
"""Qt-free domain and persistence services for the evaluation task center."""
from .errors import TaskCenterError
from .models import ProjectRecord, ProjectStatus, RuleRecord, TaskRecord, TaskStatus
from .store import TaskStore
__all__ = [
"ProjectRecord",
"ProjectStatus",
"RuleRecord",
"TaskCenterError",
"TaskRecord",
"TaskStatus",
"TaskStore",
]
@@ -0,0 +1,136 @@
"""Desktop application bootstrap for DxDesigner part replacement."""
from __future__ import annotations
import argparse
import os
from pathlib import Path
import platform
import sys
from typing import Sequence
from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QApplication
from dx_productivity.trial_task_center.logging_setup import LoggingContext, configure_logging, install_exception_hooks
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.version import VERSION
_DEFAULT_HOME_PARTS = ("DxProductivity", "trial-task-center")
def _load_window():
"""Import Qt widgets only after diagnostics are ready for UI construction."""
from dx_productivity.trial_task_center.ui import TrialTaskCenterWindow
return TrialTaskCenterWindow
def _parse_arguments(argv: Sequence[str] | None) -> argparse.Namespace:
parser = argparse.ArgumentParser(prog="DxPartReplace")
parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS)
parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS)
parser.add_argument("--native-helper", action="store_true", help=argparse.SUPPRESS)
parser.add_argument("--snapshot", type=Path, help=argparse.SUPPRESS)
parser.add_argument("--sceneos-cli", action="store_true", help=argparse.SUPPRESS)
return parser.parse_args(list(argv) if argv is not None else None)
def _default_data_root() -> Path:
if bool(getattr(sys, "frozen", False)):
return Path(sys.executable).resolve().parent / "data"
local_app_data = os.environ.get("LOCALAPPDATA")
if local_app_data:
return Path(local_app_data).joinpath(*_DEFAULT_HOME_PARTS)
known_folder = _windows_local_app_data()
if known_folder is not None:
return known_folder.joinpath(*_DEFAULT_HOME_PARTS)
return Path.home().joinpath("AppData", "Local", *_DEFAULT_HOME_PARTS)
def _windows_local_app_data() -> Path | None:
"""Resolve Local AppData without inheriting the caller's environment."""
if os.name != "nt":
return None
import ctypes
buffer = ctypes.create_unicode_buffer(32_768)
result = ctypes.windll.shell32.SHGetFolderPathW(None, 0x001C, None, 0, buffer)
return Path(buffer.value) if result == 0 and buffer.value else None
def resolve_data_root(cli_value: Path | None) -> Path:
"""Choose the explicit command-line override, deployment override, or user default."""
if cli_value is not None:
return cli_value.expanduser().resolve()
deployment_override = os.environ.get("DX_TASK_CENTER_HOME")
if deployment_override:
return Path(deployment_override).expanduser().resolve()
return _default_data_root().resolve()
def _log_startup(context: LoggingContext, data_root: Path, database_path: Path) -> None:
context.logger.info(
"application_start version=%s executable=%s os=%s data_root=%s database=%s application_log=%s",
VERSION,
sys.executable,
platform.platform(),
data_root,
database_path,
context.application_log_path,
)
def _flush(context: LoggingContext) -> None:
for handler in context.logger.handlers:
handler.flush()
def main(argv: Sequence[str] | None = None) -> int:
"""Run the Qt shell, returning a conventional process status code."""
arguments = _parse_arguments(argv)
if arguments.native_helper:
if arguments.snapshot is None:
return 2
from dx_productivity.trial_task_center.native_helper import run
return run(arguments.snapshot)
data_root = resolve_data_root(arguments.data_root)
if arguments.sceneos_cli:
from dx_productivity.trial_task_center.sceneos_cli import run
return run(data_root)
logging_context = configure_logging(data_root)
install_exception_hooks(logging_context)
store: TaskStore | None = None
try:
database_path = data_root / "task-center.db"
_log_startup(logging_context, data_root, database_path)
store = TaskStore(database_path)
recovered = store.recover_interrupted_work()
if recovered:
logging_context.logger.warning("recovered_interrupted_projects=%s", ",".join(recovered))
else:
logging_context.logger.info("recovered_interrupted_projects=none")
service = TaskCenterService(store, logging_context)
qt_application = QApplication([sys.executable, *(argv or ())])
window = _load_window()(service)
window.show()
if arguments.smoke_test:
QTimer.singleShot(0, lambda: (window.close(), qt_application.quit()))
exit_code = qt_application.exec()
logging_context.logger.info("application_clean_shutdown exit_code=%s", exit_code)
_flush(logging_context)
return int(exit_code)
except Exception as error:
logging_context.report_exception("startup", error)
return 1
finally:
if store is not None:
store.close()
if __name__ == "__main__": # pragma: no cover - exercised by the frozen executable.
raise SystemExit(main())
@@ -0,0 +1,400 @@
"""Serial, confirmed queue execution with safe between-item pausing."""
from dataclasses import dataclass
from concurrent.futures import Future, ThreadPoolExecutor
import hashlib
import json
import os
from pathlib import Path
import shutil
from threading import Event
import time
from uuid import uuid4
from .errors import TaskCenterError
from .logging_setup import append_task_event
from .models import TaskStatus
from .quick_run import (
BATCH_FAILED_STATE,
BATCH_SAVED_UNVERIFIED_STATE,
TERMINAL_STATES,
QuickRunProgress,
QuickRunStepResult,
_path_key,
_write_uncertain_flag,
)
from .retention import maintain_quick_run_storage
from .schematic_backup import create_schematic_backup
_BACKUP_STATE_NAME = 'batch-backups.json'
_BACKUP_DIRECTORY_NAME = 'batch-backups'
@dataclass(frozen=True)
class BatchRunResult:
progress: QuickRunProgress
paused: bool
last_result: QuickRunStepResult | None = None
item_messages: tuple[str, ...] = ()
unbacked_project_paths: tuple[Path, ...] = ()
def execute_batch(
service,
task_id: str,
*,
expected_item,
stop_event: Event,
continue_after_backup_failure: bool = False,
) -> BatchRunResult:
preparer = service._quick_run_preparer
retention = maintain_quick_run_storage(preparer._data_root)
if retention.removed_entries or retention.skipped_entries:
service._logging.logger.info(
'quick_run_retention removed=%s removed_bytes=%s skipped=%s',
','.join(retention.removed_entries), retention.removed_bytes,
','.join(retention.skipped_entries),
)
task = service._store.get_task(task_id)
projects = service._store.list_projects(task_id)
rules = service._store.list_rules(task_id)
progress = preparer.progress(task_id, projects, rules, copy_part_number_to_value=task.copy_part_number_to_value)
mode = 'part_label' if task.copy_part_number_to_value else 'preserve'
actual = (str(progress.next_project_path), progress.next_old_part_number, progress.next_new_part_number, mode)
if progress.queue_complete:
progress = service._synchronize_quick_run_progress(task_id, progress=progress)
return BatchRunResult(progress, False)
if expected_item is None or actual != expected_item:
raise TaskCenterError('quick_run_selection_changed', '队列起点或 Value 选项发生变化,请重新确认。')
if (preparer._data_root / 'quick-run/uncertain.flag').exists():
raise TaskCenterError('quick_run_uncertain', '队列存在待核验步骤,不能绕过保护开始批量执行。')
if task.status is TaskStatus.PAUSED and not stop_event.is_set():
service._store.set_task_status(task_id, TaskStatus.RUNNING, summary='automatic queue resumed after confirmation')
session = preparer.begin_batch_session(
task_id,
projects,
rules,
copy_part_number_to_value=task.copy_part_number_to_value,
)
initial_progress = progress
progress = session.progress
backup_root = session.handoff.command_path.parent
backup_state_path = backup_root / _BACKUP_STATE_NAME
backup_state = _read_backup_state(backup_state_path, task_id)
backed_up_roots = {
root_key
for root_key, entry in backup_state.items()
if entry.get('status') == 'backed_up' and _reusable_backup(backup_root, root_key, entry)
}
unbacked_project_paths: list[Path] = [
Path(str(entry['project_path']))
for entry in backup_state.values()
if entry.get('status') == 'unbacked' and entry.get('project_path')
]
last_result = None
item_messages: list[str] = []
def backup_destination(root_key: str) -> Path:
return backup_root / _BACKUP_DIRECTORY_NAME / f'project-{_backup_key(root_key)}'
def record_backup_failure(project_path: Path, root_key: str, destination: Path, error: TaskCenterError) -> None:
backup_state[root_key] = {
'status': 'unbacked',
'project_path': str(project_path),
'destination': str(destination.relative_to(backup_root)),
'error_id': error.error_id,
'error': error.message,
}
_write_backup_state(backup_state_path, task_id, backup_state)
if not continue_after_backup_failure:
raise error
if project_path not in unbacked_project_paths:
unbacked_project_paths.append(project_path)
service._batch_feedback = (task_id, progress, f'备份失败已按确认跳过:{project_path.name}')
append_task_event(
service._logging,
level='WARNING',
task_id=task_id,
operation='quick_run_backup_override',
message='操作员明确确认在原理图精简备份失败后继续当前队列。',
error_id=error.error_id,
details={
'state': 'continued_without_backup',
'project_path': str(project_path),
'backup_error': error.message,
'rollback_available': False,
},
)
def record_backup_success(project_path: Path, root_key: str, destination: Path) -> None:
backup_state[root_key] = {
'status': 'backed_up',
'project_path': str(project_path),
'destination': str(destination.relative_to(backup_root)),
}
_write_backup_state(backup_state_path, task_id, backup_state)
backed_up_roots.add(root_key)
def backup_project(project_path: Path) -> None:
root_key = _path_key(project_path.resolve(strict=False).parent)
if root_key in backed_up_roots:
return
previous = backup_state.get(root_key)
if previous is not None and previous.get('status') == 'unbacked':
if not continue_after_backup_failure:
raise TaskCenterError(
'quick_run_backup',
f"工程此前备份失败,尚未建立可用回滚副本:{project_path};请排除原因后重试,或明确确认忽略备份失败。",
error_id=str(previous.get('error_id') or '') or None,
)
if project_path not in unbacked_project_paths:
unbacked_project_paths.append(project_path)
backed_up_roots.add(root_key)
return
service._batch_feedback = (task_id, progress, f'正在备份 {project_path.name}')
destination = backup_destination(root_key)
try:
_backup_project_root(
preparer._data_root,
project_path,
destination,
)
except TaskCenterError as error:
if error.code != 'quick_run_backup':
raise
record_backup_failure(project_path, root_key, destination, error)
else:
record_backup_success(project_path, root_key, destination)
backed_up_roots.add(root_key)
def next_backup_candidate(start_index: int, active_root_key: str) -> tuple[Path, str] | None:
for command in session.commands[start_index:]:
state = session.latest.get(command[1])
if state is not None and state[0] in TERMINAL_STATES:
continue
project_path = Path(command[2])
root_key = _path_key(project_path.resolve(strict=False).parent)
if root_key == active_root_key or root_key in backed_up_roots or root_key in backup_state:
continue
return project_path, root_key
return None
if session.progress.completed_items > initial_progress.completed_items:
discovered_no_match = session.progress.completed_items - initial_progress.completed_items
progress = service._synchronize_quick_run_progress(task_id, progress=session.progress)
session.progress = progress
append_task_event(
service._logging,
level='INFO',
task_id=task_id,
operation='quick_run_inventory_prefiltered',
message=f'只读枚举确认 {discovered_no_match} 项未命中,已跳过重复打开工程。',
details={
'state': 'no_match',
'prefiltered_items': discovered_no_match,
'completed_items': progress.completed_items,
'total_items': progress.total_items,
'completed_projects': len(progress.completed_project_paths),
},
)
service._logging.logger.info(
'quick_run_inventory_prefiltered task_id=%s items=%s total=%s',
task_id,
discovered_no_match,
progress.total_items,
)
else:
progress = session.progress
prefetched_backup: tuple[Path, str, Path, Future[None]] | None = None
def commit_prefetched_backup() -> None:
nonlocal prefetched_backup
if prefetched_backup is None:
return
project_path, root_key, destination, future = prefetched_backup
try:
future.result()
except TaskCenterError as error:
if error.code != 'quick_run_backup':
raise
record_backup_failure(project_path, root_key, destination, error)
else:
record_backup_success(project_path, root_key, destination)
prefetched_backup = None
with ThreadPoolExecutor(max_workers=1, thread_name_prefix='dxpart-backup') as backup_executor:
while not progress.queue_complete:
if stop_event.is_set():
commit_prefetched_backup()
return BatchRunResult(
progress, True, last_result, tuple(item_messages), tuple(unbacked_project_paths)
)
current = progress.next_project_path
if current is None:
raise TaskCenterError('quick_run_queue_progress', '队列未结束但找不到下一项,已停止。')
root_key = _path_key(current.resolve(strict=False).parent)
if root_key not in backed_up_roots:
if prefetched_backup is not None and prefetched_backup[1] == root_key:
service._batch_feedback = (task_id, progress, f'正在确认预备份 {current.name}')
commit_prefetched_backup()
else:
service._batch_feedback = (task_id, progress, f'正在备份 {current.name}')
backup_project(current)
if prefetched_backup is None:
next_backup = next_backup_candidate(session.next_index + 1, root_key)
if next_backup is not None:
project_path, next_root_key = next_backup
destination = backup_destination(next_root_key)
future = backup_executor.submit(
_backup_project_root,
preparer._data_root,
project_path,
destination,
)
prefetched_backup = (project_path, next_root_key, destination, future)
service._batch_feedback = (task_id, progress, f'正在处理 {current.name}')
if stop_event.is_set():
commit_prefetched_backup()
return BatchRunResult(
progress, True, last_result, tuple(item_messages), tuple(unbacked_project_paths)
)
expected = (str(current), progress.next_old_part_number, progress.next_new_part_number, mode)
sheet = f'{progress.next_schematic_name}:{progress.next_sheet_number}' if progress.next_schematic_name else '当前图页'
service._batch_feedback = (task_id, progress, f'正在执行 {current.name} | {sheet}:{expected[1]} → {expected[2]}')
last_result = preparer.execute_step(task_id, projects, rules, copy_part_number_to_value=task.copy_part_number_to_value,
expected_item=expected, batch_mode=True, batch_session=session)
if 'NC synced:' in last_result.message or last_result.state in {
BATCH_FAILED_STATE,
BATCH_SAVED_UNVERIFIED_STATE,
}:
item_messages.append(last_result.message)
if last_result.progress is None:
raise TaskCenterError('quick_run_queue_progress', '批量执行器未返回增量进度,队列已停止。')
candidate = last_result.progress
project_completed = candidate.completed_project_paths != progress.completed_project_paths
synchronize = (
progress.completed_items == 0
or project_completed
or candidate.queue_complete
or last_result.state in {BATCH_FAILED_STATE, BATCH_SAVED_UNVERIFIED_STATE}
)
updated = service._synchronize_quick_run_progress(task_id, progress=candidate) if synchronize else candidate
if updated.completed_items <= progress.completed_items or updated.total_items != progress.total_items:
_write_uncertain_flag(preparer._data_root / 'quick-run/uncertain.flag', 'batch_progress_mismatch')
raise TaskCenterError('quick_run_queue_progress', '执行器返回后队列进度异常,已停止,避免重复执行。')
if project_completed or updated.queue_complete or last_result.state in {
BATCH_FAILED_STATE,
BATCH_SAVED_UNVERIFIED_STATE,
}:
project_id = next(
(project.project_id for project in projects if _path_key(project.path) == _path_key(current)),
None,
)
event_level = 'WARNING' if last_result.state in {
BATCH_FAILED_STATE,
BATCH_SAVED_UNVERIFIED_STATE,
} else 'INFO'
append_task_event(service._logging, level=event_level,
task_id=task_id, project_id=project_id, operation='quick_run_executed', message=last_result.message,
details={'state': last_result.state, 'continue_queue': not updated.queue_complete,
'completed_items': updated.completed_items, 'total_items': updated.total_items,
'completed_projects': len(updated.completed_project_paths)})
service._logging.logger.info('quick_run_batch_item task_id=%s state=%s completed=%s total=%s',
task_id, last_result.state, updated.completed_items, updated.total_items)
progress = updated
feedback = '未命中已跳过,继续下一项' if last_result.state == 'no_match' else (
'已保存但回读校验失败,已记录,继续下一项'
if last_result.state == BATCH_SAVED_UNVERIFIED_STATE
else '失败已记录,继续下一项'
if last_result.state == BATCH_FAILED_STATE
else '已保存并校验,继续下一项'
)
service._batch_feedback = (task_id, progress, feedback)
return BatchRunResult(
progress, False, last_result, tuple(item_messages), tuple(unbacked_project_paths)
)
def _backup_key(root_key: str) -> str:
return hashlib.sha256(root_key.encode('utf-8')).hexdigest()[:16]
def _read_backup_state(path: Path, task_id: str) -> dict[str, dict[str, object]]:
if not path.is_file():
return {}
try:
payload = json.loads(path.read_text(encoding='utf-8'))
if not isinstance(payload, dict) or payload.get('format_version') != 1 or payload.get('task_id') != task_id:
raise ValueError('backup state does not belong to the current queue')
projects = payload.get('projects')
if not isinstance(projects, dict):
raise ValueError('backup state projects are invalid')
return {
str(root_key): dict(entry)
for root_key, entry in projects.items()
if isinstance(entry, dict) and entry.get('status') in {'backed_up', 'unbacked'}
}
except (OSError, UnicodeError, json.JSONDecodeError, ValueError) as error:
raise TaskCenterError('quick_run_backup', '当前队列的备份状态文件无效,已停止以避免重复或错误覆盖。') from error
def _write_backup_state(path: Path, task_id: str, projects: dict[str, dict[str, object]]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(f'.{path.name}.{uuid4().hex}.tmp')
payload = {'format_version': 1, 'task_id': task_id, 'projects': projects}
try:
with temporary.open('w', encoding='utf-8', newline='\n') as stream:
json.dump(payload, stream, ensure_ascii=False, indent=2)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
except OSError as error:
temporary.unlink(missing_ok=True)
raise TaskCenterError('quick_run_backup', '无法保存队列备份状态,已停止以避免重复执行。') from error
def _reusable_backup(backup_root: Path, root_key: str, entry: dict[str, object]) -> bool:
destination = backup_root / str(entry.get('destination') or '')
manifest = destination / '.dxpartreplace-backup.json'
if not manifest.is_file() or str(entry.get('destination') or '').replace('\\', '/') != (
f'{_BACKUP_DIRECTORY_NAME}/project-{_backup_key(root_key)}'
):
return False
try:
payload = json.loads(manifest.read_text(encoding='utf-8'))
return (
isinstance(payload, dict)
and payload.get('format_version') == 1
and payload.get('scope') == 'dxdesigner_schematic_essentials'
and isinstance(payload.get('files'), list)
)
except (OSError, UnicodeError, json.JSONDecodeError):
return False
def _backup_project_root(data_root: Path, project_path: Path, destination: Path) -> None:
last_error: OSError | None = None
for attempt in range(3):
try:
_backup_project_root_once(data_root, project_path, destination)
return
except OSError as error:
last_error = error
if destination.exists():
shutil.rmtree(destination, ignore_errors=True)
if attempt < 2:
time.sleep(0.4 * (2 ** attempt))
except TaskCenterError:
if destination.exists():
shutil.rmtree(destination, ignore_errors=True)
raise
assert last_error is not None
raise TaskCenterError(
'quick_run_backup',
f'工程备份失败,未打开工程、枚举图页或执行替换:{project_path};请关闭占用该工程的 DxDesigner 或其他程序后重试;{last_error}',
) from last_error
def _backup_project_root_once(data_root: Path, project_path: Path, destination: Path) -> None:
create_schematic_backup(data_root, project_path, destination)
@@ -0,0 +1,365 @@
"""Fail-closed comparison of before/after menu-probe profiles."""
from __future__ import annotations
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
import json
import math
from types import MappingProxyType
from typing import Any
from dx_productivity.part_replace.models import MappingRule
@dataclass(frozen=True, slots=True)
class ComparisonIssue:
code: str
message: str
logical_identity: str | None = None
def to_dict(self) -> dict[str, str | None]:
return {
"code": self.code,
"logical_identity": self.logical_identity,
"message": self.message,
}
@dataclass(frozen=True, slots=True)
class ProjectComparison:
passed: bool
matched_logical_identities: Mapping[MappingRule, tuple[str, ...]]
warnings: tuple[ComparisonIssue, ...] = ()
issues: tuple[ComparisonIssue, ...] = ()
def __post_init__(self) -> None:
object.__setattr__(self, "matched_logical_identities", MappingProxyType({
rule: tuple(identities)
for rule, identities in self.matched_logical_identities.items()
}))
object.__setattr__(self, "warnings", tuple(self.warnings))
object.__setattr__(self, "issues", tuple(self.issues))
@property
def matched(self) -> Mapping[MappingRule, tuple[str, ...]]:
return self.matched_logical_identities
def to_json(self) -> str:
matches = [
{
"logical_identities": list(identities),
"new_part_number": rule.new_part_number,
"old_part_number": rule.old_part_number,
}
for rule, identities in sorted(
self.matched_logical_identities.items(),
key=lambda item: (item[0].old_part_number.casefold(), item[0].new_part_number.casefold()),
)
]
return json.dumps(
{
"issues": [issue.to_dict() for issue in _ordered_issues(self.issues)],
"matches": matches,
"passed": self.passed,
"warnings": [warning.to_dict() for warning in _ordered_issues(self.warnings)],
},
ensure_ascii=True,
separators=(",", ":"),
sort_keys=True,
)
def canonical_json(self) -> str:
return self.to_json()
_PROTECTED_INTERFACES = (
"logical_identity", "part_number", "refdes", "hierarchy", "units",
"origin_x", "origin_y", "position_x", "position_y", "rotation",
"mirror", "pins", "nets",
)
_PROTECTED_FIELDS = (
"refdes", "hierarchy", "units", "origin", "position", "rotation", "mirror", "nets",
)
_REQUIRED_COMPONENT_FIELDS = ("part_number", *_PROTECTED_FIELDS, "pins")
_PRESENTATION_FIELDS = ("attributes", "parameter_probe")
def _issue(code: str, message: str, identity: str | None = None) -> ComparisonIssue:
return ComparisonIssue(code, message, identity)
def _ordered_issues(issues: Sequence[ComparisonIssue]) -> tuple[ComparisonIssue, ...]:
return tuple(sorted(issues, key=lambda issue: (issue.code, issue.logical_identity or "", issue.message)))
def _part_identity(value: object) -> str | None:
return value.strip().casefold() if isinstance(value, str) and value.strip() else None
def _available(profile: Mapping[str, object], name: str) -> bool:
interfaces = profile.get("interfaces")
if not isinstance(interfaces, Mapping):
return False
entry = interfaces.get(name)
return isinstance(entry, Mapping) and entry.get("available") is True
def _components(profile: Mapping[str, object], side: str, issues: list[ComparisonIssue]) -> dict[str, Mapping[str, object]]:
entries = profile.get("components")
if not isinstance(entries, list):
issues.append(_issue("missing_components", f"{side} profile does not contain component evidence."))
return {}
indexed: dict[str, Mapping[str, object]] = {}
for entry in entries:
if not isinstance(entry, Mapping):
issues.append(_issue("invalid_component", f"{side} profile contains an invalid component record."))
continue
identity = entry.get("logical_identity")
if not isinstance(identity, str) or not identity.strip():
issues.append(_issue("missing_logical_identity", f"{side} profile contains a component without a logical identity."))
continue
if identity in indexed:
issues.append(_issue("duplicate_logical_identity", f"{side} profile repeats a logical component identity.", identity))
continue
indexed[identity] = entry
return indexed
def _missing_evidence(component: Mapping[str, object], identity: str, issues: list[ComparisonIssue]) -> None:
for field in _REQUIRED_COMPONENT_FIELDS:
value = component.get(field)
if value is None or (field == "part_number" and _part_identity(value) is None):
issues.append(_issue("missing_protected_evidence", f"Protected field {field} is unavailable.", identity))
for field in ("origin", "position"):
value = component.get(field)
if isinstance(value, Mapping) and (value.get("x") is None or value.get("y") is None):
issues.append(_issue("missing_protected_evidence", f"Protected field {field} is incomplete.", identity))
def _finite_number(value: object) -> bool:
return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)
def _nonempty_string(value: object) -> bool:
return isinstance(value, str) and bool(value.strip())
def _valid_point(value: object) -> bool:
return isinstance(value, Mapping) and _finite_number(value.get("x")) and _finite_number(value.get("y"))
def _valid_pins(value: object) -> bool:
if not isinstance(value, list) or not value:
return False
numbers: set[str] = set()
for pin in value:
if not isinstance(pin, Mapping):
return False
if not _nonempty_string(pin.get("number")) or not _nonempty_string(pin.get("name")):
return False
if not _nonempty_string(pin.get("net_identity")):
return False
if not _finite_number(pin.get("x")) or not _finite_number(pin.get("y")):
return False
number = pin["number"].strip()
if number in numbers:
return False
numbers.add(number)
return True
def _valid_component(component: Mapping[str, object]) -> bool:
return (
_nonempty_string(component.get("logical_identity"))
and _nonempty_string(component.get("part_number"))
and _nonempty_string(component.get("refdes"))
and _nonempty_string(component.get("hierarchy"))
and type(component.get("units")) is int
and component["units"] > 0
and _valid_point(component.get("origin"))
and _valid_point(component.get("position"))
and type(component.get("rotation")) is int
and type(component.get("mirror")) is bool
and _valid_pins(component.get("pins"))
and isinstance(component.get("nets"), list)
and all(_nonempty_string(net) for net in component["nets"])
)
def _validate_components(index: Mapping[str, Mapping[str, object]], issues: list[ComparisonIssue]) -> None:
for identity, component in index.items():
if not _valid_component(component):
issues.append(_issue("invalid_protected_evidence", "Component protected evidence has an invalid schema.", identity))
def _validate_enumeration(
profile: Mapping[str, object],
side: str,
record_count: int,
issues: list[ComparisonIssue],
) -> None:
enumeration = profile.get("enumeration")
if not isinstance(enumeration, Mapping):
issues.append(_issue("enumeration_unavailable", f"{side} profile has no full-project enumeration evidence."))
return
if enumeration.get("available") is not True:
issues.append(_issue("enumeration_unavailable", f"{side} profile cannot enumerate the full project."))
count = enumeration.get("component_count")
if type(count) is not int or count < 0:
issues.append(_issue("enumeration_invalid", f"{side} profile has an invalid component count."))
elif count != record_count:
issues.append(_issue("component_count_mismatch", f"{side} profile component count disagrees with its records."))
if not _nonempty_string(enumeration.get("route")):
issues.append(_issue("enumeration_invalid", f"{side} profile has no enumeration route."))
def _pins_by_number(component: Mapping[str, object]) -> dict[str, Mapping[str, object]] | None:
pins = component.get("pins")
if not _valid_pins(pins):
return None
assert isinstance(pins, list)
return {str(pin["number"]).strip(): pin for pin in pins if isinstance(pin, Mapping)}
def _compare_pins(
before: Mapping[str, object],
after: Mapping[str, object],
identity: str,
issues: list[ComparisonIssue],
warnings: list[ComparisonIssue],
) -> None:
before_pins = _pins_by_number(before)
after_pins = _pins_by_number(after)
if before_pins is None or after_pins is None:
return
if before_pins.keys() != after_pins.keys():
issues.append(_issue("pins_changed", "Protected pin numbers changed.", identity))
return
hard_fields = ("net_identity", "x", "y")
hard_changed = any(
any(before_pins[number].get(field) != after_pins[number].get(field) for field in hard_fields)
for number in before_pins
)
if hard_changed:
issues.append(_issue("pins_changed", "Protected pin connectivity or coordinates changed.", identity))
if any(before_pins[number].get("name") != after_pins[number].get("name") for number in before_pins):
warnings.append(_issue("library_pin_name_changed", "Library-controlled pin name changed.", identity))
def _without_presentation(component: Mapping[str, object]) -> dict[str, object]:
return {key: value for key, value in component.items() if key not in _PRESENTATION_FIELDS}
def _attribute_values(component: Mapping[str, object]) -> dict[str, object]:
attributes = component.get("attributes")
if not isinstance(attributes, list):
return {}
result: dict[str, object] = {}
for attribute in attributes:
if isinstance(attribute, Mapping) and isinstance(attribute.get("name"), str):
result.setdefault(attribute["name"].strip().casefold(), attribute.get("value"))
return result
def _presentation_warnings(
before: Mapping[str, object], after: Mapping[str, object], identity: str, *, parameter_available: bool
) -> tuple[ComparisonIssue, ...]:
warnings: list[ComparisonIssue] = []
before_attributes = _attribute_values(before)
after_attributes = _attribute_values(after)
for name, code in (("part label", "part_label_changed"), ("value", "value_changed")):
if before_attributes.get(name) != after_attributes.get(name):
warnings.append(_issue(code, f"{name.title()} presentation changed.", identity))
if parameter_available and before.get("parameter_probe") != after.get("parameter_probe"):
warnings.append(_issue("parameter_probe_changed", "Parameter probe evidence changed.", identity))
return tuple(warnings)
def compare_profiles(
before: Mapping[str, object],
after: Mapping[str, object],
rules: Sequence[MappingRule],
) -> ProjectComparison:
"""Compare profiles by logical identity and allow only requested Part Number changes."""
issues: list[ComparisonIssue] = []
warnings: list[ComparisonIssue] = []
before_index = _components(before, "before", issues)
after_index = _components(after, "after", issues)
before_entries = before.get("components")
after_entries = after.get("components")
_validate_enumeration(before, "before", len(before_entries) if isinstance(before_entries, list) else 0, issues)
_validate_enumeration(after, "after", len(after_entries) if isinstance(after_entries, list) else 0, issues)
for profile, side in ((before, "before"), (after, "after")):
for interface in _PROTECTED_INTERFACES:
if not _available(profile, interface):
issues.append(_issue("protected_interface_unavailable", f"{side} profile does not support {interface}."))
if not _available(profile, "parameter_probe"):
warnings.append(_issue("parameter_presentation_unavailable", f"{side} profile cannot capture parameter presentation."))
presentation_available = _available(before, "parameter_probe") and _available(after, "parameter_probe")
for identity, component in before_index.items():
_missing_evidence(component, identity, issues)
for identity, component in after_index.items():
_missing_evidence(component, identity, issues)
_validate_components(before_index, issues)
_validate_components(after_index, issues)
matched: dict[MappingRule, tuple[str, ...]] = {}
expected_identities: set[str] = set()
for rule in rules:
old = _part_identity(rule.old_part_number)
target = _part_identity(rule.new_part_number)
if old is None or target is None:
issues.append(_issue("invalid_mapping_rule", "Mapping rule has a blank Part Number."))
matched[rule] = ()
continue
identities = tuple(sorted(
identity for identity, component in before_index.items()
if _part_identity(component.get("part_number")) == old
))
matched[rule] = identities
if not identities:
warnings.append(_issue("no_matching_source_part", "No component matches the source Part Number."))
for identity in identities:
expected_identities.add(identity)
after_component = after_index.get(identity)
if after_component is None:
issues.append(_issue("missing_logical_identity", "Matched component is absent after replacement.", identity))
continue
if _part_identity(after_component.get("part_number")) != target:
issues.append(_issue("wrong_target_part_number", "Matched component does not have the target Part Number.", identity))
before_component = before_index[identity]
for field in _PROTECTED_FIELDS:
if before_component.get(field) != after_component.get(field):
code = "unit_count_changed" if field == "units" else f"{field}_changed"
issues.append(_issue(code, f"Protected field {field} changed.", identity))
_compare_pins(before_component, after_component, identity, issues, warnings)
warnings.extend(_presentation_warnings(
before_component, after_component, identity, parameter_available=presentation_available
))
for identity in before_index.keys() - after_index.keys():
issues.append(_issue("component_removed", "Logical component was removed.", identity))
for identity in after_index.keys() - before_index.keys():
issues.append(_issue("component_added", "Unexpected logical component was added.", identity))
for identity in before_index.keys() & after_index.keys():
if identity in expected_identities:
continue
before_component = before_index[identity]
after_component = after_index[identity]
if _without_presentation(before_component) != _without_presentation(after_component):
issues.append(_issue("unrelated_component_changed", "An unrelated component changed.", identity))
warnings.extend(_presentation_warnings(
before_component, after_component, identity, parameter_available=presentation_available
))
return ProjectComparison(
passed=not issues,
matched_logical_identities=matched,
warnings=tuple(warnings),
issues=tuple(issues),
)
@@ -0,0 +1,29 @@
"""Stable, user-facing errors for trial task-center operations."""
from __future__ import annotations
from datetime import datetime, timezone
import secrets
class TaskCenterError(ValueError):
"""An operation failure with a durable support identifier and safe user text."""
def __init__(
self,
code: str,
message: str,
*,
error_id: str | None = None,
traceback_detail: str = "",
) -> None:
self.code = code
self.message = message
self.error_id = error_id or self._new_error_id()
self.traceback_detail = traceback_detail
super().__init__(f"{self.error_id} {code}: {message}")
@staticmethod
def _new_error_id() -> str:
date = datetime.now(timezone.utc).strftime("%Y%m%d")
return f"DXT-{date}-{secrets.token_hex(4).upper()}"
@@ -0,0 +1,271 @@
"""Immutable capture and validation of menu-probe profiles."""
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
import hashlib
import json
import ntpath
import os
from pathlib import Path
import stat
from uuid import uuid4
from .errors import TaskCenterError
_WINDOWS_EVIDENCE_PUBLICATION = os.name == "nt"
@dataclass(frozen=True, slots=True)
class ProbeStamp:
size: int
modified_ns: int
sha256: str
@dataclass(frozen=True, slots=True)
class CapturedProfile:
source: Path
destination: Path
stamp: ProbeStamp
project_identity: str
data: Mapping[str, object]
def _snapshot(path: Path) -> tuple[bytes, ProbeStamp] | None:
try:
with Path(path).open("rb") as handle:
data = handle.read()
status = os.fstat(handle.fileno())
except FileNotFoundError:
return None
except OSError as error:
raise TaskCenterError("profile_file", f"cannot read probe profile: {path}") from error
return data, ProbeStamp(len(data), status.st_mtime_ns, hashlib.sha256(data).hexdigest())
def profile_stamp(path: Path) -> ProbeStamp | None:
"""Return a content-addressed stamp for one opened byte snapshot."""
snapshot = _snapshot(path)
return None if snapshot is None else snapshot[1]
def load_captured_profile(
path: Path,
expected_project: Path,
expected_stamp: ProbeStamp,
) -> dict[str, object]:
"""Revalidate persisted profile bytes before using them as trusted evidence."""
snapshot = _snapshot(path)
if snapshot is None:
raise TaskCenterError("evidence_integrity", f"captured profile is missing: {path}")
data, stamp = snapshot
if stamp.size != expected_stamp.size or stamp.sha256 != expected_stamp.sha256:
raise TaskCenterError("evidence_integrity", f"captured profile content changed after capture: {path}")
profile = _parse_profile(data, path)
project = profile["project"]
assert isinstance(project, dict)
identity = project["identity"]
assert isinstance(identity, str)
if _project_identity(identity) != _project_identity(expected_project):
raise TaskCenterError("profile_project", "captured profile belongs to a different project")
return profile
def _reject_duplicates(pairs: list[tuple[str, object]]) -> dict[str, object]:
result: dict[str, object] = {}
for key, value in pairs:
if key in result:
raise TaskCenterError("profile_duplicate_key", f"probe profile repeats JSON key: {key}")
result[key] = value
return result
def _parse_profile(data: bytes, source: Path) -> dict[str, object]:
try:
loaded = json.loads(
data.decode("utf-8"),
object_pairs_hook=_reject_duplicates,
parse_constant=lambda value: (_ for _ in ()).throw(
TaskCenterError("profile_json", f"probe profile has non-finite JSON value: {value}")
),
)
except TaskCenterError:
raise
except (UnicodeError, json.JSONDecodeError) as error:
raise TaskCenterError("profile_json", f"probe profile is not valid JSON: {source}") from error
if not isinstance(loaded, dict):
raise TaskCenterError("profile_json", f"probe profile must be a JSON object: {source}")
if type(loaded.get("format_version")) is not int or loaded["format_version"] != 1:
raise TaskCenterError("profile_version", "probe profile format_version must be 1")
project = loaded.get("project")
if not isinstance(project, dict) or not isinstance(project.get("identity"), str):
raise TaskCenterError("profile_project", "probe profile does not contain a project identity")
return loaded
def _project_identity(path: str | Path) -> str:
text = str(path)
if os.name == "nt":
try:
text = str(Path(text).resolve())
except OSError as error:
raise TaskCenterError("profile_project", f"cannot canonicalize project identity: {path}") from error
return os.path.normcase(os.path.normpath(text))
if ntpath.splitdrive(text)[0]:
return ntpath.normcase(ntpath.normpath(text))
try:
return os.path.normpath(str(Path(text).resolve()))
except OSError as error:
raise TaskCenterError("profile_project", f"cannot canonicalize project identity: {path}") from error
def _absolute_lexical(path: Path) -> Path:
return Path(os.path.abspath(os.fspath(path)))
def _reject_reparse_components(path: Path) -> None:
absolute = _absolute_lexical(path)
current = Path(absolute.anchor)
for part in absolute.parts[1:]:
current /= part
try:
details = current.lstat()
except FileNotFoundError:
return
except OSError as error:
raise TaskCenterError("profile_publish_path", f"cannot validate publication path: {current}") from error
if stat.S_ISLNK(details.st_mode) or bool(
getattr(details, "st_file_attributes", 0) & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
):
raise TaskCenterError("profile_publish_path", f"publication path contains a reparse point: {current}")
def _parent_identity(parent: Path) -> tuple[int, int]:
try:
details = parent.lstat()
except OSError as error:
raise TaskCenterError("profile_publish_path", f"cannot identify publication directory: {parent}") from error
if not stat.S_ISDIR(details.st_mode) or stat.S_ISLNK(details.st_mode):
raise TaskCenterError("profile_publish_path", f"publication parent is not a regular directory: {parent}")
return details.st_dev, details.st_ino
def _prepare_destination_parent(destination: Path) -> tuple[int, int]:
_reject_reparse_components(destination)
try:
destination.parent.mkdir(parents=True, exist_ok=True)
except OSError as error:
raise TaskCenterError("profile_publish", f"cannot create publication directory: {destination.parent}") from error
_reject_reparse_components(destination)
return _parent_identity(destination.parent)
def _verify_destination_parent(destination: Path, expected: tuple[int, int]) -> None:
_reject_reparse_components(destination)
if _parent_identity(destination.parent) != expected:
raise TaskCenterError("profile_publish_path", "publication directory identity changed during capture")
def _publication_hook(destination: Path, temporary: Path) -> None:
"""Test seam executed while the staged-file handle remains open."""
del destination, temporary
def _reject_source_destination_alias(source: Path, destination: Path) -> None:
try:
source_canonical = source.resolve()
destination_canonical = destination.resolve()
same_file = source.exists() and destination.exists() and os.path.samefile(source, destination)
except OSError as error:
raise TaskCenterError("profile_source_destination_alias", "cannot validate source and destination identity") from error
if source_canonical == destination_canonical or same_file:
raise TaskCenterError("profile_source_destination_alias", "probe source and capture destination must differ")
def _publish_atomically(destination: Path, data: bytes) -> None:
if not _WINDOWS_EVIDENCE_PUBLICATION:
raise TaskCenterError(
"unsupported_platform",
"captured-profile publication requires Windows handle-relative security",
)
expected_parent = _prepare_destination_parent(destination)
try:
_publish_with_windows_handles(destination, data, expected_parent)
except TaskCenterError:
raise
except OSError as error:
raise TaskCenterError("profile_publish", f"cannot publish captured profile: {destination}") from error
def _publish_with_windows_handles(destination: Path, data: bytes, expected_parent: tuple[int, int]) -> None:
# Reuse the repository's hardened Windows handle primitives. The second
# staged-file validation is Task2-specific: it rejects a path substitution
# between staging and handle-relative publication.
from dx_productivity.part_replace.compatibility_profile import (
CompatibilityProfileError,
_close_handle,
_delete_staged_file,
_locked_destination_parent,
_open_staged_file,
_publish_staged_file,
_validate_staged_file,
_write_staged_file,
)
temporary = destination.parent / f".{destination.name}.{uuid4().hex}.tmp"
staged_handle: int | None = None
published = False
try:
with _locked_destination_parent(destination.parent) as parent_handle:
_verify_destination_parent(destination, expected_parent)
staged_handle = _open_staged_file(temporary)
_write_staged_file(staged_handle, data)
_validate_staged_file(staged_handle, temporary)
_publication_hook(destination, temporary)
_validate_staged_file(staged_handle, temporary)
_verify_destination_parent(destination, expected_parent)
_publish_staged_file(staged_handle, parent_handle, destination.name)
published = True
_verify_destination_parent(destination, expected_parent)
except CompatibilityProfileError as error:
raise TaskCenterError("profile_publish", error.message) from error
except OSError as error:
raise TaskCenterError("profile_publish", f"cannot publish captured profile: {destination}") from error
finally:
if staged_handle is not None:
try:
if not published:
_delete_staged_file(staged_handle)
except OSError:
pass
_close_handle(staged_handle)
def capture_profile(
source: Path,
destination: Path,
expected_project: Path,
previous: ProbeStamp | None,
) -> CapturedProfile:
"""Validate changed probe evidence and atomically copy its exact bytes."""
source = Path(source)
destination = Path(destination)
snapshot = _snapshot(source)
if snapshot is None:
raise TaskCenterError("profile_missing", f"probe profile does not exist: {source}")
data, stamp = snapshot
_reject_source_destination_alias(source, destination)
if previous is not None and stamp.sha256 == previous.sha256 and stamp.modified_ns == previous.modified_ns:
raise TaskCenterError("profile_unchanged", "probe profile did not change after operator action")
profile = _parse_profile(data, source)
project = profile["project"]
assert isinstance(project, dict)
identity = project["identity"]
assert isinstance(identity, str)
if _project_identity(identity) != _project_identity(expected_project):
raise TaskCenterError("profile_project", "probe profile belongs to a different project")
_publish_atomically(destination, data)
return CapturedProfile(source, destination, stamp, identity, profile)
@@ -0,0 +1,257 @@
"""Application diagnostics and durable per-task JSON Lines events."""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime, timezone
import hashlib
import json
import logging
from logging.handlers import RotatingFileHandler
import os
from pathlib import Path
import sys
import threading
import time
import traceback
from typing import Any, Mapping
from .errors import TaskCenterError
from .retention import rotate_text_log
_MAX_LOG_BYTES = 5 * 1024 * 1024
_BACKUP_COUNT = 5
_MAX_EVENT_LOG_BYTES = 5 * 1024 * 1024
_EVENT_BACKUP_COUNT = 5
_EVENT_KEYS = (
"sequence",
"timestamp_utc",
"level",
"task_id",
"project_id",
"operation",
"state_before",
"state_after",
"error_id",
"message",
"details",
)
@dataclass(slots=True)
class LoggingContext:
"""Paths, logger, and synchronization needed by diagnostic helpers."""
root: Path
application_log_path: Path
logger: logging.Logger
_event_lock: threading.RLock = field(default_factory=threading.RLock, repr=False)
def report_exception(
self,
operation: str,
error: BaseException,
traceback_object: object | None = None,
) -> TaskCenterError:
"""Write an exception traceback and return its safe support identifier."""
if isinstance(error, TaskCenterError):
reported = error
else:
reported = TaskCenterError("unhandled_exception", "发生未处理异常")
detail = "".join(
traceback.format_exception(type(error), error, traceback_object or error.__traceback__)
)
self.logger.error(
"error_id=%s operation=%s message=%s\n%s",
reported.error_id,
operation,
reported.message,
detail.rstrip(),
)
_flush_handlers(self.logger)
return reported
def configure_logging(root: Path) -> LoggingContext:
"""Create storage directories and a UTF-8 rotating application log handler."""
storage_root = Path(root).resolve()
log_path = storage_root / "logs" / "application.log"
log_path.parent.mkdir(parents=True, exist_ok=True)
(storage_root / "tasks").mkdir(parents=True, exist_ok=True)
logger_name = "dx_productivity.trial_task_center." + hashlib.sha256(
str(storage_root.resolve()).encode("utf-8")
).hexdigest()[:16]
logger = logging.getLogger(logger_name)
logger.setLevel(logging.DEBUG)
logger.propagate = False
if not any(
isinstance(handler, RotatingFileHandler) and Path(handler.baseFilename) == log_path
for handler in logger.handlers
):
handler = RotatingFileHandler(
log_path,
maxBytes=_MAX_LOG_BYTES,
backupCount=_BACKUP_COUNT,
encoding="utf-8",
)
formatter = logging.Formatter(
"%(asctime)s %(levelname)s %(name)s %(message)s", datefmt="%Y-%m-%dT%H:%M:%SZ"
)
formatter.converter = time.gmtime
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.info("logging configured root=%s application_log=%s", storage_root, log_path)
_flush_handlers(logger)
return LoggingContext(storage_root, log_path, logger)
def append_task_event(
context: LoggingContext,
*,
level: str,
task_id: str,
operation: str,
project_id: str | None = None,
state_before: str | None = None,
state_after: str | None = None,
error_id: str | None = None,
message: str = "",
details: Mapping[str, Any] | None = None,
) -> dict[str, Any]:
"""Durably append one canonical task event and return its decoded record."""
task_directory = _task_directory(context, task_id)
try:
details_value = dict(details or {})
json.dumps(details_value, ensure_ascii=False, allow_nan=False)
except (TypeError, ValueError) as error:
raise TaskCenterError("event_details", "task event details must be JSON-compatible") from error
path = task_directory / "events.jsonl"
with context._event_lock:
sequence = _next_event_sequence(path)
event = {
"sequence": sequence,
"timestamp_utc": _utc_now_text(),
"level": str(level).upper(),
"task_id": task_id,
"project_id": project_id,
"operation": str(operation),
"state_before": state_before,
"state_after": state_after,
"error_id": error_id,
"message": str(message),
"details": details_value,
}
encoded = json.dumps(event, ensure_ascii=False, separators=(",", ":"), allow_nan=False) + "\n"
try:
rotate_text_log(
path,
max_bytes=_MAX_EVENT_LOG_BYTES,
backup_count=_EVENT_BACKUP_COUNT,
)
with path.open("a", encoding="utf-8", newline="\n") as handle:
handle.write(encoded)
handle.flush()
os.fsync(handle.fileno())
except OSError as error:
raise TaskCenterError("event_write_failed", "cannot append task event") from error
context.logger.log(
_logging_level(event["level"]),
"task_event task_id=%s project_id=%s operation=%s sequence=%s",
task_id,
project_id or "",
operation,
sequence,
)
_flush_handlers(context.logger)
return event
def capture_subprocess_output(
context: LoggingContext,
*,
operation: str,
returncode: int,
stdout: str,
stderr: str,
) -> None:
"""Record complete subprocess outcome and both output streams in application.log."""
context.logger.info("operation=%s returncode=%s", operation, returncode)
if stdout:
context.logger.info("operation=%s stdout=%s", operation, stdout.rstrip())
if stderr:
context.logger.warning("operation=%s stderr=%s", operation, stderr.rstrip())
_flush_handlers(context.logger)
def install_exception_hooks(context: LoggingContext) -> None:
"""Route uncaught main and worker exceptions to the application diagnostic log."""
def main_exception_hook(
exception_type: type[BaseException], exception: BaseException, traceback_object: object
) -> None:
del exception_type
context.report_exception("uncaught_main_thread", exception, traceback_object)
def thread_exception_hook(arguments: threading.ExceptHookArgs) -> None:
thread_name = arguments.thread.name if arguments.thread is not None else "unknown"
context.report_exception(f"uncaught_worker_thread:{thread_name}", arguments.exc_value, arguments.exc_traceback)
sys.excepthook = main_exception_hook
threading.excepthook = thread_exception_hook
def _task_directory(context: LoggingContext, task_id: str) -> Path:
if not task_id or Path(task_id).name != task_id or task_id in {".", ".."}:
raise TaskCenterError("task_id", "task event requires a safe task identifier")
path = context.root / "tasks" / task_id
path.mkdir(parents=True, exist_ok=True)
return path
def _next_event_sequence(path: Path) -> int:
try:
for candidate in (path, path.with_name(f"{path.name}.1")):
if not candidate.exists():
continue
lines = _tail_utf8_lines(candidate, 1)
if lines:
record = json.loads(lines[-1])
return int(record["sequence"]) + 1
return 1
except (OSError, UnicodeError, ValueError, KeyError, TypeError) as error:
raise TaskCenterError("event_sequence", "cannot determine the next task event sequence") from error
def _tail_utf8_lines(path: Path, limit: int) -> tuple[str, ...]:
if limit < 1:
return ()
with Path(path).open("rb") as handle:
handle.seek(0, os.SEEK_END)
cursor = handle.tell()
chunks = []
newline_count = 0
while cursor > 0 and newline_count <= limit:
size = min(8192, cursor)
cursor -= size
handle.seek(cursor)
chunk = handle.read(size)
chunks.append(chunk)
newline_count += chunk.count(b"\n")
payload = b"".join(reversed(chunks))
if cursor > 0:
separator = payload.find(b"\n")
payload = payload[separator + 1:] if separator >= 0 else b""
return tuple(payload.decode("utf-8").splitlines()[-limit:])
def _utc_now_text() -> str:
return datetime.now(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
def _logging_level(level: str) -> int:
return getattr(logging, level.upper(), logging.INFO)
def _flush_handlers(logger: logging.Logger) -> None:
for handler in logger.handlers:
handler.flush()
@@ -0,0 +1,75 @@
"""Immutable domain records used by the task-center service and UI."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from pathlib import Path
class TaskStatus(str, Enum):
DRAFT = "draft"
READY = "ready"
RUNNING = "running"
PAUSED = "paused"
COMPLETED = "completed"
FAILED = "failed"
DELETED = "deleted"
class ProjectStatus(str, Enum):
PENDING = "pending"
CAPTURING_BEFORE = "capturing_before"
AWAITING_OPERATOR = "awaiting_operator"
CAPTURING_AFTER = "capturing_after"
VERIFYING = "verifying"
COMPLETED = "completed"
FAILED = "failed"
SKIPPED = "skipped"
@dataclass(frozen=True, slots=True)
class TaskRecord:
task_id: str
name: str
note: str
discovery_root: Path | None
status: TaskStatus
created_utc: datetime
updated_utc: datetime
started_utc: datetime | None = None
completed_utc: datetime | None = None
deleted_utc: datetime | None = None
status_before_delete: TaskStatus | None = None
error_id: str | None = None
summary: str = ""
copy_part_number_to_value: bool = False
@dataclass(frozen=True, slots=True)
class RuleRecord:
rule_id: str
task_id: str
position: int
old_part_number: str
new_part_number: str
enabled: bool
custom_value_enabled: bool = False
custom_value: str = ""
sync_nc: bool = True
@dataclass(frozen=True, slots=True)
class ProjectRecord:
project_id: str
task_id: str
display_name: str
path: Path
discovery_root: Path
selected: bool
available: bool
status: ProjectStatus
retry_count: int
error_id: str | None = None
summary: str = ""
@@ -0,0 +1,627 @@
"""Native current-sheet replacement adapter for the existing QuickPartReplace runner."""
import argparse
import ctypes
import hashlib
import json
import os
from pathlib import Path
import re
import sys
import threading
import time
import traceback
def decode(value):
characters = []
index = 0
while index < len(value):
match = re.match(r"%([0-9A-Fa-f]{4})", value[index:])
if match is not None:
characters.append(chr(int(match[1], 16)))
index += 5
continue
characters.append(value[index])
index += 1
try:
return "".join(characters).encode("utf-16-le", errors="surrogatepass").decode("utf-16-le")
except UnicodeError as error:
raise ValueError("VBS field contains malformed UTF-16") from error
def read_snapshot(path):
rows = [[decode(field) for field in line.split("\t")]
for line in Path(path).read_text(encoding="utf-8-sig").splitlines() if line]
metadata = [row for row in rows if row[0] == "M"]
components = [row for row in rows if row[0] == "C"]
if len(metadata) != 1 or len(metadata[0]) not in {5, 6, 8} or not components:
raise ValueError("Incomplete snapshot")
if len(metadata[0]) >= 6 and metadata[0][5] not in {"preserve", "part_label", "part_number", "custom"}:
raise ValueError("Invalid snapshot Value policy")
if len(metadata[0]) == 8:
if metadata[0][7] not in {"0", "1"} or (metadata[0][5] == "custom") != bool(metadata[0][6]):
raise ValueError("Invalid snapshot Value or NC option")
if any(len(row) != 8 for row in components):
raise ValueError("Invalid component snapshot")
if len({row[1] for row in components}) != len(components):
raise ValueError("Duplicate snapshot UID")
if metadata[0][2].casefold() == metadata[0][3].casefold():
raise ValueError("Source and target must differ")
return metadata[0], components
def snapshot_value_mode(metadata):
return metadata[5] if len(metadata) >= 6 else "part_label"
def snapshot_sha256(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def transaction_binding(snapshot, metadata, records, library_row, symbol, slot_count=1):
if len(library_row) < 6 or not str(library_row[4]).strip() or not str(library_row[5]).strip():
raise ValueError("Library target has incomplete identity fields")
slots = int(slot_count)
if slots < 1:
raise ValueError("Library target has no valid slots")
return {
"snapshot_sha256": snapshot_sha256(snapshot),
"project_path": os.path.normcase(os.path.abspath(metadata[1])),
"sheet_identity": metadata[4],
"old_part_number": metadata[2],
"new_part_number": metadata[3],
"source_uids": sorted(row[1] for row in records),
"library_row": [str(value) for value in library_row],
"target_symbol": str(symbol),
"slot_count": slots,
}
def require_resumable_transaction(snapshot, report, metadata, records):
if report.get("stage") not in {
"native_replace_started",
"native_replace_applied",
"pin_promotion_started",
"native_replace_verified",
}:
raise ValueError("Cannot prove that the native replacement belongs to this job")
binding = report.get("transaction")
expected = {
"snapshot_sha256": snapshot_sha256(snapshot),
"project_path": os.path.normcase(os.path.abspath(metadata[1])),
"sheet_identity": metadata[4],
"old_part_number": metadata[2],
"new_part_number": metadata[3],
"source_uids": sorted(row[1] for row in records),
}
if not isinstance(binding, dict) or any(binding.get(key) != value for key, value in expected.items()):
raise ValueError("Native replacement evidence does not match this snapshot")
library_row = binding.get("library_row")
if not isinstance(library_row, list) or len(library_row) < 6:
raise ValueError("Native replacement evidence has no target library identity")
return binding
def exact_target(rows, target):
matches = [row for row in rows if len(row[1]) >= 3 and row[1][1] == target]
if len(matches) != 1:
raise ValueError(f"Expected one exact library part/gate, found {len(matches)}: {target}")
if not matches[0][1][2].strip():
raise ValueError("Library target has no associated symbol")
return matches[0]
def wait_for(callback, description, timeout=15):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
result = callback()
if result:
return result
time.sleep(0.15)
raise TimeoutError(description)
def wait_for_library_rows(callback, target, timeout=30, stable_for=0.45, poll_interval=0.15):
deadline = time.monotonic() + timeout
previous = None
stable_since = None
latest = []
while time.monotonic() < deadline:
latest = callback()
signature = tuple(tuple(str(value) for value in columns) for _, columns in latest)
now = time.monotonic()
if signature != previous:
previous = signature
stable_since = now
exact = [row for row in latest if len(row[1]) >= 3 and row[1][1] == target]
if exact and stable_since is not None and now - stable_since >= stable_for:
return latest
time.sleep(poll_interval)
raise TimeoutError(f"Native DxDataBook did not finish loading target part: {target}")
def target_symbol_matches(displayed, library_symbol, slot_count):
actual = str(displayed).casefold()
expected = str(library_symbol).casefold()
if actual == expected:
return True
prefix = expected + "."
if not actual.startswith(prefix):
return False
suffix = actual[len(prefix):]
return suffix.isdigit() and 1 <= int(suffix) <= int(slot_count)
def is_replace_symbol_title(title):
normalized = str(title).replace("&", "").casefold()
return "\u66ff\u6362\u7b26\u53f7" in normalized or "replace symbol" in normalized
def replacement_command_from_resources(executable):
import win32api
import win32gui
if Path(executable).name.casefold() != "viewdraw.exe":
raise ValueError("Replacement command must come from the attached Viewdraw executable")
module = win32api.LoadLibraryEx(str(executable), 0, 0x22)
commands = set()
def visit(menu):
for index in range(win32gui.GetMenuItemCount(menu)):
submenu = win32gui.GetSubMenu(menu, index)
if submenu:
visit(submenu)
continue
title = ctypes.create_unicode_buffer(512)
ctypes.windll.user32.GetMenuStringW(menu, index, title, len(title), 0x400)
if is_replace_symbol_title(title.value):
command_id = win32gui.GetMenuItemID(menu, index)
if 0 < command_id < 0xFFFF:
commands.add(command_id)
try:
for resource in win32api.EnumResourceNames(module, 4):
menu = win32gui.LoadMenu(module, resource)
try:
visit(menu)
finally:
win32gui.DestroyMenu(menu)
finally:
win32api.FreeLibrary(module)
if len(commands) != 1:
raise ValueError("Cannot identify one native Replace Symbol command; no mouse fallback is allowed")
return commands.pop()
def attach():
import win32com.client
try:
import viewdraw_api as api
except ImportError:
api = win32com.client.gencache.EnsureModule(
"{4ADEF4E1-690A-11CE-9261-0020C5E26659}", 0, 1, 0)
app = api.IVdApp(win32com.client.GetActiveObject("Viewdraw.Application")._oleobj_)
return app, api
def attribute_value(component, name):
attribute = component.FindAttribute(name)
if attribute is None:
return ""
return str(attribute.InstanceValue or attribute.Value)
def selection(component, value):
import win32com.client.dynamic
item = win32com.client.dynamic.DumbDispatch(component._oleobj_)
item.Selected = bool(value)
def components_on_sheet(app, api):
return [api.IVdComp(component._oleobj_) for component in app.ActiveView.Query(128, 0)]
def check_active_context(app, metadata):
if os.path.normcase(os.path.abspath(app.GetProjectData().GetProjectFilePath())) != os.path.normcase(os.path.abspath(metadata[1])):
raise ValueError("Active project changed")
if f"{app.ActiveView.GetName(0)}:{app.ActiveView.Block.SheetNum}" != metadata[4]:
raise ValueError("Active sheet changed")
def check_context(app, api, metadata, records, require_selection=True):
check_active_context(app, metadata)
components = components_on_sheet(app, api)
wanted = {row[1] for row in records}
actual = {str(component.UID) for component in components if attribute_value(component, "Part Number").casefold() == metadata[2].casefold()}
if actual != wanted:
raise ValueError(f"Source batch changed since snapshot: expected={sorted(wanted)!r} actual={sorted(actual)!r}")
selected = {str(api.IVdComp(component._oleobj_).UID) for component in app.ActiveView.Query(128, 1)}
if require_selection and selected != wanted:
raise ValueError(f"Selected component set differs from snapshot: expected={sorted(wanted)!r} actual={sorted(selected)!r}")
return components
def select_snapshot_batch(app, api, metadata, records):
components = check_context(app, api, metadata, records, require_selection=False)
wanted = {row[1] for row in records}
for component in components:
selection(component, str(component.UID) in wanted)
return check_context(app, api, metadata, records)
def existing_replacement_uids(components, records, target, binding, require_part_label=True):
current_by_uid = {str(component.UID): component for component in components}
target_key = target.casefold()
current_by_refdes = {}
for component in components:
if attribute_value(component, "Part Number").casefold() == target_key:
current_by_refdes.setdefault(str(component.Refdes), []).append(component)
library_row = binding["library_row"]
expected_part_name = str(library_row[4]).strip().casefold()
expected_part_label = str(library_row[5]).strip().casefold()
matches = []
for record in records:
candidate = current_by_uid.get(record[1])
if candidate is None or attribute_value(candidate, "Part Number").casefold() != target_key:
candidates = current_by_refdes.get(record[2], ())
if len(candidates) != 1:
raise ValueError("Source batch changed since snapshot")
candidate = candidates[0]
part_name = attribute_value(candidate, "Part Name").strip().casefold()
part_label = attribute_value(candidate, "Part Label").strip().casefold()
if part_name != expected_part_name or (require_part_label and part_label != expected_part_label):
raise ValueError("Existing replacement does not match the recorded target library identity")
matches.append(str(candidate.UID))
if len(set(matches)) != len(records):
raise ValueError("Duplicate replacement association")
return matches
def promote_pin_numbers(app, api, replacement_uids, slot_count=1):
components = components_on_sheet(app, api)
replacement_uids = set(replacement_uids)
try:
for component in components:
selection(component, str(component.UID) in replacement_uids)
for slot in range(1, int(slot_count) + 1):
app.ActiveView.Block.PromoteSymbolNumbers(1, slot)
promoted = []
for item in app.ActiveView.Query(4096, 0):
pin = api.IVdCmpPin(item._oleobj_)
if str(pin.Component.UID) in replacement_uids:
if not str(pin.Number).strip():
raise ValueError("Native target-library pin number promotion failed")
promoted.append({"uid": str(pin.Component.UID), "number": str(pin.Number)})
if not promoted:
raise ValueError("Replacement produced no pins")
return promoted
finally:
for component in components:
selection(component, False)
def replacement_matches(components, records, target, require_part_label):
current_by_uid = {str(component.UID): component for component in components}
current_by_refdes = {}
for component in components:
current_by_refdes.setdefault(str(component.Refdes), []).append(component)
matches = []
for record in records:
candidate = current_by_uid.get(record[1])
if candidate is None:
candidates = current_by_refdes.get(record[2], ())
if len(candidates) != 1:
raise ValueError("Native replacement lost component identity")
candidate = candidates[0]
if attribute_value(candidate, "Part Number").casefold() != target.casefold():
return None
identity = str(candidate.Refdes).strip() or f"UID={candidate.UID}"
if not attribute_value(candidate, "Part Name"):
raise ValueError(
f"Native replacement Part Name readback failed; refdes={identity}; uid={candidate.UID}"
)
if require_part_label and not attribute_value(candidate, "Part Label"):
raise ValueError(
f"Native replacement Part Label readback failed; refdes={identity}; uid={candidate.UID}; "
"Part Label is required by the selected Value policy"
)
matches.append(str(candidate.UID))
if len(set(matches)) != len(records):
raise ValueError("Duplicate replacement association")
return matches
def run_native(snapshot, report):
import win32api
import win32con
import win32gui
import win32process
from pywinauto import Desktop
metadata, records = read_snapshot(snapshot)
require_part_label = snapshot_value_mode(metadata) == "part_label"
app, api = attach()
check_active_context(app, metadata)
components = components_on_sheet(app, api)
wanted = {row[1] for row in records}
source_uids = {
str(component.UID)
for component in components
if attribute_value(component, "Part Number").casefold() == metadata[2].casefold()
}
if source_uids != wanted:
binding = require_resumable_transaction(snapshot, report, metadata, records)
report["replaced_uids"] = existing_replacement_uids(
components, records, metadata[3], binding, require_part_label=require_part_label
)
if report.get("stage") == "native_replace_verified" and report.get("ok") is True:
report["already_replaced"] = True
return
report["stage"] = "pin_promotion_started"
save_report(snapshot, report)
slot_count = int(binding.get("slot_count", report.get("slot_count", 1)))
if slot_count < 1:
raise ValueError("Recorded replacement has no valid slots")
report["promoted_pins"] = promote_pin_numbers(app, api, report["replaced_uids"], slot_count)
report["already_replaced"] = True
report["stage"] = "native_replace_verified"
return
components = select_snapshot_batch(app, api, metadata, records)
before_uids = {str(component.UID) for component in components}
untouched = {str(component.UID): attribute_value(component, "Part Number") for component in components if str(component.UID) not in wanted}
view_handle = int(app.ActiveViewHandle)
process_id = win32process.GetWindowThreadProcessId(view_handle)[1]
main_handle = win32gui.GetAncestor(view_handle, 2)
desktop = Desktop(backend="uia")
def owned_windows(include_hidden=False):
handles = []
roots = []
def collect_root(handle, _):
if win32process.GetWindowThreadProcessId(handle)[1] == process_id:
roots.append(handle)
if include_hidden or win32gui.IsWindowVisible(handle):
handles.append(handle)
def collect_child(handle, _):
if include_hidden or win32gui.IsWindowVisible(handle):
handles.append(handle)
win32gui.EnumWindows(collect_root, None)
for root in roots:
win32gui.EnumChildWindows(root, collect_child, None)
return list(dict.fromkeys(handles))
def dlg_item(handle, identifier):
try:
return win32gui.GetDlgItem(handle, identifier)
except win32gui.error:
return 0
def replacement_dialog():
matches = [handle for handle in owned_windows() if win32gui.GetClassName(handle) == "#32770"
and dlg_item(handle, 1695) and dlg_item(handle, 1701)]
if len(matches) > 1:
raise ValueError("Multiple replacement dialogs")
return matches[0] if matches else None
def message(handle, code, wparam=0, lparam=0):
return win32gui.SendMessageTimeout(handle, code, wparam, lparam, win32con.SMTO_ABORTIFHUNG, 15000)
def control_text(control):
buffer = ctypes.create_unicode_buffer(2048)
message(control, win32con.WM_GETTEXT, len(buffer), ctypes.addressof(buffer))
return buffer.value
def click(control):
if not control or not win32gui.IsWindowEnabled(control):
raise ValueError("Required replacement control is unavailable")
message(control, 0x00F5)
def check_radio(dialog, identifier):
control = dlg_item(dialog, identifier)
if not control:
raise ValueError(f"Required native option {identifier} is unavailable")
if win32gui.SendMessage(control, 0x00F0, 0, 0) != 1:
click(control)
if win32gui.SendMessage(control, 0x00F0, 0, 0) != 1:
raise ValueError(f"Native option {identifier} was not enabled")
report.setdefault("native_options", {})[str(identifier)] = {
"text": control_text(control),
"checked": True,
}
if replacement_dialog():
raise ValueError("Close the existing replacement dialog before starting this job")
dialog = None
try:
process = win32api.OpenProcess(0x410, False, process_id)
try:
executable = Path(win32process.GetModuleFileNameEx(process, 0))
finally:
process.Close()
command_id = replacement_command_from_resources(executable)
check_context(app, api, metadata, records)
report["native_command"] = {"id": command_id, "executable": str(executable), "trigger": "resource_command"}
win32gui.PostMessage(main_handle, win32con.WM_COMMAND, command_id, 0)
dialog = wait_for(replacement_dialog, "Native replacement dialog did not open; no mouse input was injected", timeout=8)
check_radio(dialog, 1704)
check_radio(dialog, 1105)
check_radio(dialog, 1697)
check_radio(dialog, 1700)
report["databook"] = {
"main_visible_before_browse": bool(win32gui.IsWindowVisible(main_handle)),
"browse_button": int(dlg_item(dialog, 1366)),
}
click(dlg_item(dialog, 1366))
def part_list():
report["databook"]["main_visible_during_wait"] = bool(
win32gui.IsWindowVisible(main_handle)
)
for handle in owned_windows(include_hidden=True):
if win32gui.GetClassName(handle) == "SysListView32" and win32gui.GetDlgCtrlID(handle) == 4000:
return handle
return None
list_handle = wait_for(part_list, "Native DxDataBook part list did not open", timeout=30)
report["databook"].update(
list_handle=int(list_handle),
list_visible=bool(win32gui.IsWindowVisible(list_handle)),
main_visible_after_load=bool(win32gui.IsWindowVisible(main_handle)),
)
filter_handles = [handle for handle in owned_windows(include_hidden=True)
if win32gui.GetDlgCtrlID(handle) == 4006 and win32gui.GetClassName(handle) == "Edit"]
if len(filter_handles) != 1:
raise ValueError("Cannot uniquely identify native Part Number filter")
message(filter_handles[0], win32con.WM_SETTEXT, 0, metadata[3])
def current_library_rows():
return [(row, [text.window_text() for text in row.children(control_type="Text")])
for row in desktop.window(handle=list_handle).descendants(control_type="ListItem")]
rows = wait_for_library_rows(current_library_rows, metadata[3])
row, columns = exact_target(rows, metadata[3])
report["library_row"] = columns
symbol_parts = columns[2].split(":", 1)
if len(symbol_parts) != 2:
raise ValueError("Library symbol has no partition")
slot_count = int(app.GetProjectData().GetSlotsCount(symbol_parts[0], symbol_parts[1], metadata[3]))
report["slot_count"] = slot_count
if slot_count < 1:
raise ValueError("Library target has no valid slots")
rectangle = row.rectangle()
list_rectangle = win32gui.GetWindowRect(list_handle)
if rectangle.height() <= 0 or rectangle.top < list_rectangle[1] or rectangle.bottom > list_rectangle[3]:
raise ValueError("Exact library row is not visible")
point = win32gui.ScreenToClient(list_handle, (rectangle.left + 100, rectangle.top + 12))
report["row_rectangle"] = [rectangle.left, rectangle.top, rectangle.right, rectangle.bottom]
report["list_handle"] = list_handle
position = (point[1] << 16) | (point[0] & 0xFFFF)
for code, key in [(win32con.WM_LBUTTONDOWN, 1), (win32con.WM_LBUTTONUP, 0), (win32con.WM_LBUTTONDBLCLK, 1), (win32con.WM_LBUTTONUP, 0)]:
win32gui.PostMessage(list_handle, code, key, position)
def target_ready():
control = dlg_item(dialog, 1703)
inner = dlg_item(control, 1001)
report["target_text"] = control_text(inner or control)
report["symbol_text"] = control_text(dlg_item(dialog, 1701))
return report["target_text"] == metadata[3]
wait_for(target_ready, "Native target part did not update")
symbol = control_text(dlg_item(dialog, 1701))
if not target_symbol_matches(symbol, columns[2], slot_count):
raise ValueError(f"Native symbol does not match library row: {symbol}")
components = check_context(app, api, metadata, records, require_selection=False)
for component in components:
selection(component, str(component.UID) in wanted)
for identifier in (1704, 1105, 1697, 1700):
check_radio(dialog, identifier)
check_context(app, api, metadata, records)
report["transaction"] = transaction_binding(snapshot, metadata, records, columns, symbol, slot_count)
report["stage"] = "native_replace_started"
save_report(snapshot, report)
click(dlg_item(dialog, 1695))
replacement_poll_count = 0
def selected_replaced():
nonlocal replacement_poll_count
replacement_poll_count += 1
selected = [api.IVdComp(component._oleobj_) for component in app.ActiveView.Query(128, 1)]
if len(selected) == len(records):
matches = replacement_matches(selected, records, metadata[3], require_part_label)
if matches is not None:
return matches
if replacement_poll_count % 7 == 0:
return replacement_matches(
components_on_sheet(app, api), records, metadata[3], require_part_label
)
return None
report["replaced_uids"] = wait_for(
selected_replaced, "Native replacement did not complete", timeout=30
)
current = components_on_sheet(app, api)
if len(current) != len(before_uids):
raise ValueError("Component count changed during replacement")
current_by_uid = {str(component.UID): component for component in current}
for uid, number in untouched.items():
if uid not in current_by_uid or attribute_value(current_by_uid[uid], "Part Number") != number:
raise ValueError("An unselected component was changed")
verified_uids = replacement_matches(current, records, metadata[3], require_part_label)
if verified_uids is None or set(verified_uids) != set(report["replaced_uids"]):
raise ValueError("Native replacement verification changed after completion")
report["stage"] = "native_replace_applied"
save_report(snapshot, report)
report["stage"] = "pin_promotion_started"
save_report(snapshot, report)
report["promoted_pins"] = promote_pin_numbers(app, api, report["replaced_uids"], slot_count)
report["stage"] = "native_replace_verified"
finally:
if dialog and win32gui.IsWindow(dialog):
close_button = dlg_item(dialog, 1696)
if close_button and win32gui.IsWindowEnabled(close_button):
click(close_button)
def save_report(snapshot, report):
report_path = Path(str(snapshot) + ".native.json")
error_path = Path(str(snapshot) + ".native.error.txt")
atomic_text(report_path, json.dumps(report, ensure_ascii=False, indent=2))
if report.get("ok"):
error_path.unlink(missing_ok=True)
elif report.get("error"):
atomic_text(error_path, str(report["error"]))
def atomic_text(path, text):
path = Path(path)
temporary = path.with_name(f".{path.name}.{os.getpid()}.{threading.get_ident()}.tmp")
try:
with temporary.open("w", encoding="utf-8", newline="") as handle:
handle.write(text)
handle.flush()
os.fsync(handle.fileno())
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)
def run(snapshot):
snapshot = Path(snapshot)
report_path = Path(str(snapshot) + ".native.json")
report = {}
if report_path.is_file():
try:
previous = json.loads(report_path.read_text(encoding="utf-8"))
if isinstance(previous, dict):
report.update(previous)
except (OSError, UnicodeError, json.JSONDecodeError):
pass
report.setdefault("stage", "preflight")
report.update(snapshot=str(snapshot), ok=False)
report.pop("error", None)
report.pop("traceback", None)
def timeout():
report.update(ok=False, error="Native helper timed out; inspect schematic before retrying")
save_report(snapshot, report)
os._exit(2)
watchdog = threading.Timer(120, timeout)
watchdog.daemon = True
watchdog.start()
try:
run_native(snapshot, report)
report["ok"] = True
return 0
except Exception as error:
report["error"] = f"{type(error).__name__}: {error}"
report["traceback"] = traceback.format_exc()
return 1
finally:
watchdog.cancel()
save_report(snapshot, report)
def main(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument("--snapshot", required=True, type=Path)
args = parser.parse_args(argv)
return run(args.snapshot)
if __name__ == "__main__":
sys.exit(main())
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,215 @@
"""Reconcile an interrupted queue without repeating a native replacement."""
from __future__ import annotations
import hashlib
import json
import os
from pathlib import Path
import shutil
import stat
import subprocess
from uuid import uuid4
from .errors import TaskCenterError
from .native_helper import read_snapshot, require_resumable_transaction
from .quick_run import (
TERMINAL_STATES, IDLE_PROGRESS_TIMEOUT_SECONDS, QuickRunStepResult,
_native_helper_launch_arguments, _next_unfinished_command, _path_key,
_queue_matches_inputs, _queue_value_mode, _read_command_sheet_targets,
_read_command_options, _read_commands, _read_status_details, _safe_run_token,
_value_mode_matches_option, _write_status_details, _write_uncertain_flag,
)
from .retention import maintain_quick_run_storage
from .schematic_backup import create_schematic_backup
_REPARSE_POINT = getattr(stat, 'FILE_ATTRIBUTE_REPARSE_POINT', 0x400)
def _is_link_or_reparse(path: Path) -> bool:
details = path.lstat()
return stat.S_ISLNK(details.st_mode) or bool(
getattr(details, 'st_file_attributes', 0) & _REPARSE_POINT
)
def _hashes(
root: Path,
*,
link_error_code: str = 'quick_run_recovery',
link_error_message: str = '恢复备份中发现链接目录或文件,已停止。',
) -> dict[str, str]:
result = {}
for path in sorted(root.rglob('*')):
if _is_link_or_reparse(path):
raise TaskCenterError(link_error_code, link_error_message)
if path.is_file():
with path.open('rb') as stream:
result[path.relative_to(root).as_posix()] = hashlib.file_digest(stream, 'sha256').hexdigest()
return result
def _recovery_hashes(root: Path) -> dict[str, str]:
try:
return _hashes(root)
except OSError as error:
raise TaskCenterError(
'quick_run_recovery',
f'无法读取恢复范围:{root};工程仍被 DxDesigner 或其他程序占用。请关闭占用后重试,保护状态未解除。',
) from error
def _recovery_copytree(source: Path, destination: Path) -> None:
try:
shutil.copytree(source, destination)
except OSError as error:
raise TaskCenterError(
'quick_run_recovery',
f'无法建立恢复备份:{source};工程仍被 DxDesigner 或其他程序占用。请关闭占用后重试,保护状态未解除。',
) from error
def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=False, confirmed=False):
if not confirmed:
raise TaskCenterError('quick_run_recovery_confirmation', '核验恢复需要明确确认,不能作为自动重试执行。')
maintain_quick_run_storage(preparer._data_root)
root = preparer._data_root / 'quick-run'
uncertain = root / 'uncertain.flag'
if not preparer.has_interrupted(task_id):
raise TaskCenterError('quick_run_recovery', '当前没有待核验的中断保护记录。')
commands = _read_commands(root / 'command.tsv')
before = _read_status_details(root / 'status.tsv')
selected_projects = tuple(project for project in projects if project.selected and project.available)
enabled_rules = tuple(rule for rule in rules if rule.enabled)
mode = _queue_value_mode(root / 'command.tsv')
if {command[0] for command in commands} != {task_id} or not _queue_matches_inputs(
root / 'command.tsv', commands, selected_projects, enabled_rules):
raise TaskCenterError('quick_run_recovery', '当前工程或规则与中断队列不同,不能恢复其他任务。')
if not _value_mode_matches_option(mode, copy_part_number_to_value) or len({command[1] for command in commands}) != len(commands):
raise TaskCenterError('quick_run_recovery', 'Value 策略变化或队列编号重复,已停止恢复。')
selected = _next_unfinished_command(commands, before)
if selected is None:
raise TaskCenterError('quick_run_recovery', '队列记录已完成但仍有保护锁,需要单独核对,未自动解除。')
job_id = _safe_run_token(selected[1])
selected_mode, selected_custom_value, selected_sync_nc, selected_base_mode = _read_command_options(
root / 'command.tsv'
)[job_id]
sheet_targets = _read_command_sheet_targets(root / 'command.tsv')
selected_sheet = sheet_targets.get(job_id) if sheet_targets is not None else None
latest = {entry[0]: entry[1] for entry in before}
if any(state not in TERMINAL_STATES for other, state in latest.items() if other != job_id):
raise TaskCenterError('quick_run_recovery', '存在多个未确认步骤,不能只核验一项后解除全局保护。')
snapshot = root / f'snapshot-{job_id}.tsv'
try:
metadata, components = read_snapshot(snapshot)
snapshot_options = (
(metadata[5], metadata[6], metadata[7])
if len(metadata) == 8
else (metadata[5], '', '1')
)
if len(metadata) not in {6, 8} or (_path_key(metadata[1]), metadata[2], metadata[3]) != (
_path_key(selected[2]), selected[3], selected[4]) or snapshot_options != (
selected_mode, selected_custom_value, '1' if selected_sync_nc else '0'):
raise ValueError('snapshot command mismatch')
if selected_sheet is not None and metadata[4] != f'{selected_sheet[0]}:{selected_sheet[1]}':
raise ValueError('snapshot sheet mismatch')
report = json.loads(snapshot.with_suffix('.tsv.native.json').read_text(encoding='utf-8'))
binding = require_resumable_transaction(snapshot, report, metadata, components)
identity = binding['library_row'][4:6]
if any(not value or any(character in value for character in '\t\r\n') for value in identity):
raise ValueError('invalid library identity')
except (OSError, ValueError, KeyError, TypeError) as error:
raise TaskCenterError('quick_run_recovery', '快照或原生替换证据无法与此任务绑定,保护状态保持不变。') from error
if not uncertain.is_file():
_write_uncertain_flag(uncertain, 'recovery_in_progress')
try:
project = Path(selected[2]).resolve(strict=True)
except OSError as error:
raise TaskCenterError('quick_run_recovery', '中断队列对应的工程不存在或无法访问,保护状态未解除。') from error
if root.resolve().is_relative_to(project.parent):
raise TaskCenterError('quick_run_recovery', '工程目录包含任务数据目录,无法安全建立恢复备份。')
audit = preparer._data_root / 'quick-run-history' / ('recovery-' + uuid4().hex)
worker = audit / 'worker'
worker.mkdir(parents=True, exist_ok=False)
evidence_before = _recovery_hashes(root)
_recovery_copytree(root, audit / 'evidence-before')
try:
project_backup = create_schematic_backup(
preparer._data_root,
project,
audit / 'project-backup',
error_code='quick_run_recovery',
)
except OSError as error:
raise TaskCenterError(
'quick_run_recovery',
f'无法建立原理图精简恢复备份:{project};请关闭占用后重试,保护状态未解除。',
) from error
project_before = project_backup.fingerprints
if _recovery_hashes(audit / 'evidence-before') != evidence_before or _recovery_hashes(root) != evidence_before:
raise TaskCenterError('quick_run_recovery', '备份期间执行证据变化,已停止。')
script = worker / 'QuickPartReplace.vbs'
shutil.copyfile(preparer._required_script_source(), script)
shutil.copyfile(snapshot, worker / snapshot.name)
(worker / 'recovery.request').write_text(job_id, encoding='ascii')
option_fields = (selected_mode, selected_custom_value, '1' if selected_sync_nc else '0', selected_base_mode)
if selected_sheet is None:
header = 'task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\tcustom_value\tsync_nc\tbase_value_mode\trecovery_part_name\trecovery_part_label'
row = (*selected, *option_fields, *identity)
else:
header = 'task_id\tjob_id\tproject_path\tschematic_name\tsheet_number\told_part\tnew_part\tvalue_mode\tcustom_value\tsync_nc\tbase_value_mode\trecovery_part_name\trecovery_part_label'
row = (*selected[:3], *selected_sheet, *selected[3:], *option_fields, *identity)
shutil.copyfile(root / 'sheets.tsv', worker / 'sheets.tsv')
(worker / 'command.tsv').write_text(header + '\n' + '\t'.join(row) + '\n', encoding='utf-8')
_write_status_details(worker / 'status.tsv', ())
launch = (str(preparer._cscript_resolver()), '//nologo', str(script), str(worker),
*_native_helper_launch_arguments(), job_id)
try:
result = preparer._process_runner(launch, IDLE_PROGRESS_TIMEOUT_SECONDS)
except (OSError, subprocess.SubprocessError) as error:
raise TaskCenterError('quick_run_recovery', '恢复执行未能确认结束,原保护锁仍在;不要重新替换或删除证据。') from error
(audit / 'worker-output.txt').write_text(result.stdout + '\n' + result.stderr, encoding='utf-8')
after = _read_status_details(worker / 'status.tsv')
if result.returncode != 0 or len(after) != 1 or after[0][0] != job_id or after[0][1] not in {'restored_ok', 'retry_ready'}:
detail = result.stderr.strip() or result.stdout.strip() or (after[-1][3] if after else '没有返回匹配的核验结果')
raise TaskCenterError('quick_run_recovery', '恢复未通过,保护状态保留:' + detail[-2000:])
if _recovery_hashes(root) != evidence_before or (worker / snapshot.name).read_bytes() != snapshot.read_bytes():
raise TaskCenterError('quick_run_recovery', '核验期间原始证据变化,未提交恢复结果。')
state = after[0][1]
command_bytes = (root / 'command.tsv').read_bytes()
status_bytes = (root / 'status.tsv').read_bytes()
recovery_record = {'task_id': task_id, 'job_id': job_id, 'state': state, 'worker_result': after[0],
'snapshot_sha256': binding['snapshot_sha256'], 'evidence_before': evidence_before,
'project_before': project_before, 'native_replacement_called': False}
(audit / 'recovery.json').write_text(json.dumps(recovery_record, ensure_ascii=False, indent=2), encoding='utf-8')
try:
if state == 'retry_ready':
lines = (root / 'command.tsv').read_text(encoding='utf-8-sig').splitlines()
column = lines[0].split('\t').index('job_id')
retry_id = uuid4().hex + '_retry'
for index in range(1, len(lines)):
fields = lines[index].split('\t')
if fields[column] == job_id:
fields[column] = retry_id
lines[index] = '\t'.join(fields)
temporary = root / ('command-' + uuid4().hex + '.tmp')
temporary.write_text('\n'.join(lines) + '\n', encoding='utf-8')
os.replace(temporary, root / 'command.tsv')
_write_status_details(root / 'status.tsv', tuple(entry for entry in before if entry[0] != job_id))
else:
_write_status_details(root / 'status.tsv', (*before, after[0]))
os.replace(uncertain, audit / 'resolved-uncertain.flag')
except Exception:
(root / 'command.tsv').write_bytes(command_bytes)
(root / 'status.tsv').write_bytes(status_bytes)
if not uncertain.exists():
uncertain.write_text('recovery commit interrupted; reconciliation required', encoding='ascii')
raise
progress = preparer.progress(task_id, projects, rules, copy_part_number_to_value=copy_part_number_to_value)
message = ('磁盘工程与替换前快照一致,只读核验工程已关闭,已准备新的执行编号;尚未再次替换,请确认后执行。'
if state == 'retry_ready' else '已核验并恢复本项任务记录;没有重复执行原生替换。若补做了属性恢复,请保存当前工程。')
return QuickRunStepResult(root / 'QuickPartReplace.vbs', root / 'command.tsv', root / 'status.tsv',
audit / 'worker-output.txt', state, message, progress.next_project_path,
progress.next_old_part_number, progress.next_new_part_number,
progress.next_schematic_name, progress.next_sheet_number)
@@ -0,0 +1,129 @@
"""Bounded retention for quick-run logs and generated history."""
from __future__ import annotations
from dataclasses import dataclass
import os
from pathlib import Path
import re
import shutil
import time
QUICK_RUN_LOG_MAX_BYTES = 5 * 1024 * 1024
QUICK_RUN_LOG_BACKUPS = 3
HISTORY_MAX_AGE_DAYS = 30
HISTORY_MAX_ENTRIES = 100
HISTORY_MAX_BYTES = 5 * 1024 * 1024 * 1024
HISTORY_MIN_ENTRIES = 10
_HISTORY_NAME = re.compile(r"(?:batch|recovery|sheet-discovery|obsolete)-[A-Za-z0-9-]+\Z")
@dataclass(frozen=True, slots=True)
class RetentionResult:
removed_entries: tuple[str, ...] = ()
removed_bytes: int = 0
skipped_entries: tuple[str, ...] = ()
def rotate_text_log(
path: Path,
*,
max_bytes: int = QUICK_RUN_LOG_MAX_BYTES,
backup_count: int = QUICK_RUN_LOG_BACKUPS,
) -> bool:
path = Path(path)
if max_bytes < 1 or backup_count < 1:
raise ValueError("log retention limits must be positive")
if not path.exists() or path.stat().st_size <= max_bytes:
return False
if _is_link(path):
raise OSError(f"refusing to rotate linked log: {path}")
oldest = path.with_name(f"{path.name}.{backup_count}")
if oldest.exists():
if _is_link(oldest):
raise OSError(f"refusing to rotate linked log backup: {oldest}")
oldest.unlink()
for index in range(backup_count - 1, 0, -1):
source = path.with_name(f"{path.name}.{index}")
destination = path.with_name(f"{path.name}.{index + 1}")
if not source.exists():
continue
if _is_link(source):
raise OSError(f"refusing to rotate linked log backup: {source}")
os.replace(source, destination)
os.replace(path, path.with_name(f"{path.name}.1"))
return True
def maintain_quick_run_storage(
data_root: Path,
*,
now: float | None = None,
max_age_days: int = HISTORY_MAX_AGE_DAYS,
max_entries: int = HISTORY_MAX_ENTRIES,
max_bytes: int = HISTORY_MAX_BYTES,
min_entries: int = HISTORY_MIN_ENTRIES,
) -> RetentionResult:
if min_entries < 0 or max_entries < min_entries or max_bytes < 0 or max_age_days < 0:
raise ValueError("invalid quick-run history retention limits")
root = Path(data_root)
rotate_text_log(root / "quick-run" / "quick-part-replace.log")
history = root / "quick-run-history"
if not history.is_dir() or _is_link(history):
return RetentionResult()
canonical_history = history.resolve()
entries: list[tuple[Path, int, int]] = []
skipped: list[str] = []
for candidate in history.iterdir():
if not candidate.is_dir() or _HISTORY_NAME.fullmatch(candidate.name) is None:
continue
try:
if _is_link(candidate) or candidate.resolve().parent != canonical_history:
raise OSError("linked or redirected history entry")
entries.append((candidate, candidate.stat().st_mtime_ns, _tree_size(candidate)))
except OSError:
skipped.append(candidate.name)
entries.sort(key=lambda entry: (entry[1], entry[0].name))
remaining_count = len(entries)
remaining_bytes = sum(entry[2] for entry in entries)
cutoff_ns = int(((time.time() if now is None else now) - max_age_days * 86400) * 1_000_000_000)
removed: list[str] = []
removed_bytes = 0
for candidate, modified_ns, size in entries:
if remaining_count <= min_entries:
break
if not (
modified_ns < cutoff_ns
or remaining_count > max_entries
or remaining_bytes > max_bytes
):
break
try:
if _is_link(candidate) or candidate.resolve().parent != canonical_history:
raise OSError("history entry changed during retention")
shutil.rmtree(candidate)
except OSError:
skipped.append(candidate.name)
continue
removed.append(candidate.name)
removed_bytes += size
remaining_count -= 1
remaining_bytes -= size
return RetentionResult(tuple(removed), removed_bytes, tuple(dict.fromkeys(skipped)))
def _tree_size(root: Path) -> int:
total = 0
for path in root.rglob("*"):
if _is_link(path):
raise OSError(f"linked history content: {path}")
if path.is_file():
total += path.stat().st_size
return total
def _is_link(path: Path) -> bool:
return path.is_symlink() or bool(getattr(path, "is_junction", lambda: False)())
@@ -0,0 +1,777 @@
"""Durable, one-project-at-a-time execution for replacement trials."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
import json
from pathlib import Path
from dx_productivity.part_replace.models import MappingRule
from .comparison import ProjectComparison, compare_profiles
from .errors import TaskCenterError
from .evidence import ProbeStamp, capture_profile, load_captured_profile, profile_stamp
from .logging_setup import LoggingContext, append_task_event
from .models import ProjectRecord, ProjectStatus, RuleRecord, TaskRecord, TaskStatus
from .store import AttemptContext, TaskStore
@dataclass(frozen=True, slots=True)
class OperatorRule:
"""One verified source-to-target replacement instruction."""
old_part_number: str
new_part_number: str
match_count: int
logical_identities: tuple[str, ...]
@dataclass(frozen=True, slots=True)
class OperatorInstruction:
"""The native DxDesigner action the operator must perform next."""
project_id: str
project_path: Path
rules: tuple[OperatorRule, ...]
@dataclass(frozen=True, slots=True)
class RunnerSnapshot:
"""Immutable state passed from a worker to the UI."""
task: TaskRecord
projects: tuple[ProjectRecord, ...]
active_project: ProjectRecord | None
instruction: OperatorInstruction | None
evidence_directory: Path | None
class TrialRunner:
"""State machine that makes machine comparison the sole success path."""
def __init__(
self,
store: TaskStore,
logging_context: LoggingContext,
*,
probe_source_resolver: Callable[[TaskRecord, ProjectRecord], Path] | None = None,
) -> None:
self._store = store
self._logging = logging_context
self._probe_source_resolver = probe_source_resolver or self._default_probe_source
migration_recoveries = self._store.pending_migration_recoveries()
for recovery in migration_recoveries:
self._event_transition(
recovery.task_id,
recovery.project_id,
"recover_v1_attemptless_work",
recovery.project_before.value,
recovery.project_after.value,
"recording v1 migration recovery",
recovery.error_id,
"before",
recovery_event_id=f"v1-attemptless:{recovery.project_id}:project:before",
)
for recovery in migration_recoveries:
if recovery.task_before is not None and recovery.task_after is not None:
self._event_transition(
recovery.task_id,
None,
"recover_v1_attemptless_work",
recovery.task_before.value,
recovery.task_after.value,
"recording v1 migration task recovery",
recovery.error_id,
"before",
recovery_event_id=f"v1-attemptless:{recovery.project_id}:task:before",
)
for recovery in migration_recoveries:
self._event_transition(
recovery.task_id,
recovery.project_id,
"recover_v1_attemptless_work",
recovery.project_before.value,
recovery.project_after.value,
recovery.project_summary,
recovery.error_id,
"after",
recovery_event_id=f"v1-attemptless:{recovery.project_id}:project:after",
)
for recovery in migration_recoveries:
if recovery.task_before is not None and recovery.task_after is not None:
self._event_transition(
recovery.task_id,
None,
"recover_v1_attemptless_work",
recovery.task_before.value,
recovery.task_after.value,
recovery.task_summary or "migration interrupted active project; retry the project",
recovery.error_id,
"after",
recovery_event_id=f"v1-attemptless:{recovery.project_id}:task:after",
)
self._store.acknowledge_migration_recoveries(tuple(recovery.project_id for recovery in migration_recoveries))
interrupted_states = {
ProjectStatus.CAPTURING_BEFORE,
ProjectStatus.CAPTURING_AFTER,
ProjectStatus.VERIFYING,
}
interrupted = tuple(
project
for task in self._store.list_tasks()
for project in self._store.list_projects(task.task_id)
if project.status in interrupted_states
)
running_task_ids = {project.task_id for project in interrupted if self._store.get_task(project.task_id).status is TaskStatus.RUNNING}
for project in interrupted:
self._event_transition(
project.task_id,
project.project_id,
"recover_interrupted_work",
project.status.value,
ProjectStatus.FAILED.value,
"recovering interrupted project",
None,
"before",
)
for task_id in running_task_ids:
self._event_transition(
task_id,
None,
"recover_interrupted_work",
TaskStatus.RUNNING.value,
TaskStatus.PAUSED.value,
"recovering interrupted task",
None,
"before",
)
recovered_project_ids = self._store.recover_interrupted_work()
for project_id in recovered_project_ids:
project = self._project(project_id)
self._event_transition(
project.task_id,
project_id,
"recover_interrupted_work",
next(item.status.value for item in interrupted if item.project_id == project_id),
ProjectStatus.FAILED.value,
project.summary,
project.error_id,
"after",
)
for task_id in running_task_ids:
task = self._store.get_task(task_id)
self._event_transition(
task_id,
None,
"recover_interrupted_work",
TaskStatus.RUNNING.value,
task.status.value,
task.summary,
task.error_id,
"after",
)
for task in self._store.list_tasks(TaskStatus.RUNNING):
self._complete_if_terminal(task.task_id)
def start_task(self, task_id: str, *, disposable_copy_confirmed: bool) -> RunnerSnapshot:
if not disposable_copy_confirmed:
raise TaskCenterError("disposable_copy_required", "confirm that selected projects are disposable copies")
task = self._store.get_task(task_id)
selected = self._selected_available(task_id)
if not selected:
raise TaskCenterError("selected_project_required", "select at least one available project")
if not any(rule.enabled for rule in self._store.list_rules(task_id)):
raise TaskCenterError("enabled_rule_required", "add at least one enabled mapping rule")
if task.status is not TaskStatus.RUNNING and self._store.has_active_project():
raise TaskCenterError("active_project_exists", "another project is already active")
if task.status is not TaskStatus.RUNNING:
self._set_task(task_id, TaskStatus.RUNNING, "start_task", "trial started")
self._activate_next(task_id)
return self.snapshot(task_id)
def capture_before(self, task_id: str, project_id: str, probe_path: Path) -> RunnerSnapshot:
project = self._active_project(task_id, project_id, ProjectStatus.CAPTURING_BEFORE)
try:
context = self._require_attempt(project)
captured = capture_profile(
probe_path,
self._evidence_directory(project) / "before.json",
project.path,
self._probe_stamp(context.baseline_size, context.baseline_sha256, context.baseline_modified_ns),
)
profile = dict(captured.data)
if not compare_profiles(profile, profile, ()).passed:
raise TaskCenterError("before_profile_invalid", "before profile contains invalid protected evidence")
instruction = OperatorInstruction(
project_id=project_id,
project_path=project.path,
rules=self._operator_rules(profile, self._attempt_rules(context)),
)
self._event_transition(
task_id,
project_id,
"save_attempt_before",
ProjectStatus.CAPTURING_BEFORE.value,
ProjectStatus.CAPTURING_BEFORE.value,
"persisting before evidence and operator instruction",
None,
"before",
)
self._store.save_attempt_before(
project_id,
before_path=captured.destination,
before_size=captured.stamp.size,
before_sha256=captured.stamp.sha256,
before_modified_ns=captured.stamp.modified_ns,
instruction_json=self._instruction_json(instruction),
)
self._event_transition(
task_id,
project_id,
"save_attempt_before",
ProjectStatus.CAPTURING_BEFORE.value,
ProjectStatus.CAPTURING_BEFORE.value,
"persisted before evidence and operator instruction",
None,
"after",
)
self._set_project(project, ProjectStatus.AWAITING_OPERATOR, "capture_before", "before profile captured")
except TaskCenterError as error:
self._fail_project(task_id, project, "capture_before", error)
raise
return self.snapshot(task_id)
def confirm_native_attempt(self, task_id: str, project_id: str) -> RunnerSnapshot:
project = self._active_project(task_id, project_id, ProjectStatus.AWAITING_OPERATOR)
append_task_event(
self._logging,
level="INFO",
task_id=task_id,
project_id=project_id,
operation="confirm_native_attempt",
state_before=project.status.value,
state_after=project.status.value,
message="operator asserted that native replacement was attempted",
)
return self.snapshot(task_id)
def capture_after(self, task_id: str, project_id: str, probe_path: Path) -> RunnerSnapshot:
project = self._active_project(task_id, project_id, ProjectStatus.AWAITING_OPERATOR, allow_paused=True)
try:
context = self._require_attempt(project, require_before=True)
self._set_project(project, ProjectStatus.CAPTURING_AFTER, "capture_after", "capturing after profile")
project = self._project(project_id)
captured = capture_profile(
probe_path,
self._evidence_directory(project) / "after.json",
project.path,
self._probe_stamp(context.before_size, context.before_sha256, context.before_modified_ns),
)
self._set_project(project, ProjectStatus.VERIFYING, "capture_after", "verifying captured profiles")
project = self._project(project_id)
before_profile = load_captured_profile(
context.before_path,
project.path,
self._probe_stamp(context.before_size, context.before_sha256, context.before_modified_ns),
)
comparison = compare_profiles(
before_profile,
captured.data,
self._attempt_rules(context),
)
self._write_comparison(project, comparison)
if not comparison.passed:
raise TaskCenterError("comparison_failed", "captured profiles did not pass verification")
self._set_project(project, ProjectStatus.COMPLETED, "compare_profiles", "comparison passed")
except TaskCenterError as error:
current = self._project(project_id)
if current.status not in {ProjectStatus.FAILED, ProjectStatus.COMPLETED, ProjectStatus.SKIPPED}:
self._fail_project(task_id, current, "capture_after", error)
if current.status is ProjectStatus.COMPLETED:
self._reconcile_task(task_id)
raise
if self._store.get_task(task_id).status is TaskStatus.RUNNING:
self._activate_next(task_id)
self._complete_if_terminal(task_id)
return self.snapshot(task_id)
def pause_task(self, task_id: str) -> RunnerSnapshot:
task = self._store.get_task(task_id)
if task.status is not TaskStatus.RUNNING:
raise TaskCenterError("task_not_running", "only a running task can be paused")
self._set_task(task_id, TaskStatus.PAUSED, "pause_task", "trial paused")
return self.snapshot(task_id)
def resume_task(self, task_id: str) -> RunnerSnapshot:
task = self._store.get_task(task_id)
if task.status is not TaskStatus.PAUSED:
raise TaskCenterError("task_not_paused", "only a paused task can be resumed")
projects = self._store.list_projects(task_id)
active = next((project for project in projects if project.status in self._active_project_states()), None)
pending = next(
(project for project in projects if project.selected and project.available and project.status is ProjectStatus.PENDING),
None,
)
if active is not None:
self._set_task(task_id, TaskStatus.RUNNING, "resume_task", "trial resumed")
elif pending is not None:
self._claim_attempt(task, pending, "resume_task", "trial resumed", "project selected after resume")
else:
self._set_task(task_id, TaskStatus.RUNNING, "resume_task", "trial resumed")
self._complete_if_terminal(task_id)
return self.snapshot(task_id)
def retry_project(self, task_id: str, project_id: str) -> RunnerSnapshot:
project = self._require_project(task_id, project_id)
if project.status is not ProjectStatus.FAILED:
raise TaskCenterError("project_not_retryable", "only a failed project can be retried")
task = self._store.get_task(task_id)
if task.status not in {TaskStatus.FAILED, TaskStatus.PAUSED, TaskStatus.RUNNING}:
raise TaskCenterError("task_not_retryable", "task cannot start a retry from its current state")
self._claim_attempt(task, project, "retry_project", "retry started", "project selected for retry")
return self.snapshot(task_id)
def skip_project(self, task_id: str, project_id: str) -> RunnerSnapshot:
project = self._require_project(task_id, project_id)
if project.status in {ProjectStatus.COMPLETED, ProjectStatus.SKIPPED}:
raise TaskCenterError("project_not_skippable", "a terminal project cannot be skipped")
task = self._store.get_task(task_id)
if task.status is TaskStatus.FAILED:
self._set_task(task_id, TaskStatus.PAUSED, "skip_project", "resolving failed project")
self._set_task(task_id, TaskStatus.RUNNING, "skip_project", "finishing queue")
if project.status is not ProjectStatus.PENDING and project.status is not ProjectStatus.FAILED:
# The persisted state graph requires an audit-visible failure before a live capture can be skipped.
self._set_project(project, ProjectStatus.FAILED, "skip_project", "operator stopped project before verification")
project = self._project(project_id)
self._set_project(project, ProjectStatus.SKIPPED, "skip_project", "project skipped by operator")
if self._store.get_task(task_id).status is TaskStatus.RUNNING:
self._activate_next(task_id)
self._complete_if_terminal(task_id)
return self.snapshot(task_id)
def set_project_selected(self, task_id: str, project_id: str, selected: bool) -> RunnerSnapshot:
project = self._require_project(task_id, project_id)
if not selected and project.status in {
ProjectStatus.CAPTURING_BEFORE,
ProjectStatus.AWAITING_OPERATOR,
ProjectStatus.CAPTURING_AFTER,
ProjectStatus.VERIFYING,
}:
raise TaskCenterError("active_project_selection", "pause or finish the active project before clearing selection")
self._store.set_project_selected(project_id, selected)
self._reconcile_task(task_id)
return self.snapshot(task_id)
def set_projects_selected(
self,
task_id: str,
selected: bool,
*,
available_only: bool = False,
) -> RunnerSnapshot:
projects = self._store.list_projects(task_id)
if not selected and any(
project.status in self._active_project_states()
and (not available_only or project.available)
for project in projects
):
raise TaskCenterError("active_project_selection", "pause or finish the active project before clearing selection")
self._store.set_projects_selected(task_id, selected, available_only=available_only)
self._reconcile_task(task_id)
return self.snapshot(task_id)
def snapshot(self, task_id: str) -> RunnerSnapshot:
task = self._store.get_task(task_id)
projects = self._store.list_projects(task_id)
active = next(
(
project
for project in projects
if project.status in {
ProjectStatus.CAPTURING_BEFORE,
ProjectStatus.AWAITING_OPERATOR,
ProjectStatus.CAPTURING_AFTER,
ProjectStatus.VERIFYING,
}
),
None,
)
if task.status is TaskStatus.PAUSED:
active = None
return RunnerSnapshot(
task=task,
projects=projects,
active_project=active,
instruction=self._attempt_instruction(active) if active is not None else None,
evidence_directory=self._evidence_directory(active) if active is not None else None,
)
def expected_probe_path(self, task: TaskRecord, project: ProjectRecord) -> Path:
"""Expose the configured read-only menu probe source to the service/UI."""
return self._probe_source_resolver(task, project)
def _activate_next(self, task_id: str) -> None:
if self._store.get_task(task_id).status is not TaskStatus.RUNNING:
return
projects = self._store.list_projects(task_id)
if any(project.status in {ProjectStatus.CAPTURING_BEFORE, ProjectStatus.AWAITING_OPERATOR, ProjectStatus.CAPTURING_AFTER, ProjectStatus.VERIFYING} for project in projects):
return
next_project = next((project for project in projects if project.selected and project.available and project.status is ProjectStatus.PENDING), None)
if next_project is not None:
task = self._store.get_task(task_id)
baseline_path = self._probe_source_resolver(task, next_project)
baseline = profile_stamp(baseline_path)
if baseline is None:
error = TaskCenterError("probe_baseline_missing", "menu probe baseline does not exist at task start")
self._fail_project(task_id, next_project, "activate_project", error)
raise error
rules_json = json.dumps(
[
{"old_part_number": rule.old_part_number, "new_part_number": rule.new_part_number}
for rule in self._enabled_rules(task_id)
],
ensure_ascii=True,
separators=(",", ":"),
)
self._event_transition(
task_id,
next_project.project_id,
"activate_project",
ProjectStatus.PENDING.value,
ProjectStatus.CAPTURING_BEFORE.value,
"project selected for capture",
None,
"before",
)
started = self._store.begin_project_attempt(
task_id,
next_project.project_id,
probe_source=baseline_path,
baseline_size=baseline.size,
baseline_sha256=baseline.sha256,
baseline_modified_ns=baseline.modified_ns,
rules_json=rules_json,
)
self._event_transition(
task_id,
started.project_id,
"activate_project",
ProjectStatus.PENDING.value,
ProjectStatus.CAPTURING_BEFORE.value,
"project selected for capture",
None,
"after",
)
def _claim_attempt(
self,
task: TaskRecord,
project: ProjectRecord,
operation: str,
task_message: str,
project_message: str,
) -> None:
baseline_path = self._probe_source_resolver(task, project)
baseline = profile_stamp(baseline_path)
if baseline is None:
raise TaskCenterError("probe_baseline_missing", "menu probe baseline does not exist at task start")
rules_json = json.dumps(
[
{"old_part_number": rule.old_part_number, "new_part_number": rule.new_part_number}
for rule in self._enabled_rules(task.task_id)
],
ensure_ascii=True,
separators=(",", ":"),
)
self._event_transition(
task.task_id,
None,
operation,
task.status.value,
TaskStatus.RUNNING.value,
"claiming task for a new attempt",
None,
"before",
)
self._event_transition(
task.task_id,
project.project_id,
operation,
project.status.value,
ProjectStatus.CAPTURING_BEFORE.value,
"claiming project for a new attempt",
None,
"before",
)
started_task, started_project = self._store.claim_project_attempt(
task.task_id,
project.project_id,
expected_task_status=task.status,
expected_project_status=project.status,
probe_source=baseline_path,
baseline_size=baseline.size,
baseline_sha256=baseline.sha256,
baseline_modified_ns=baseline.modified_ns,
rules_json=rules_json,
task_summary=task_message,
project_summary=project_message,
)
self._event_transition(
task.task_id,
None,
operation,
task.status.value,
started_task.status.value,
task_message,
None,
"after",
)
self._event_transition(
task.task_id,
project.project_id,
operation,
project.status.value,
started_project.status.value,
project_message,
None,
"after",
)
def _complete_if_terminal(self, task_id: str) -> None:
task = self._store.get_task(task_id)
if task.status is not TaskStatus.RUNNING:
return
terminal = {ProjectStatus.COMPLETED, ProjectStatus.SKIPPED}
selected = self._selected_available(task_id)
if selected and all(project.status in terminal for project in selected):
self._set_task(task_id, TaskStatus.COMPLETED, "complete_task", "all selected projects reached terminal state")
def _reconcile_task(self, task_id: str) -> None:
task = self._store.get_task(task_id)
selected = self._selected_available(task_id)
terminal = {ProjectStatus.COMPLETED, ProjectStatus.SKIPPED}
if task.status is TaskStatus.FAILED:
if not selected:
self._set_task(task_id, TaskStatus.PAUSED, "reconcile_task", "no selected projects remain")
return
if all(project.status in terminal for project in selected):
self._set_task(task_id, TaskStatus.PAUSED, "reconcile_task", "resolving selected terminal projects")
self._set_task(task_id, TaskStatus.RUNNING, "reconcile_task", "completing selected terminal projects")
self._complete_if_terminal(task_id)
return
if task.status is TaskStatus.RUNNING:
self._activate_next(task_id)
self._complete_if_terminal(task_id)
def _fail_project(self, task_id: str, project: ProjectRecord, operation: str, error: TaskCenterError) -> None:
if project.status is not ProjectStatus.FAILED:
self._set_project(project, ProjectStatus.FAILED, operation, error.message, error.error_id)
task = self._store.get_task(task_id)
if task.status in {TaskStatus.RUNNING, TaskStatus.PAUSED}:
self._set_task(task_id, TaskStatus.FAILED, operation, error.message, error.error_id)
def _set_task(self, task_id: str, status: TaskStatus, operation: str, message: str, error_id: str | None = None) -> None:
current = self._store.get_task(task_id)
self._event_transition(task_id, None, operation, current.status.value, status.value, message, error_id, "before")
self._store.set_task_status(task_id, status, error_id=error_id, summary=message)
self._event_transition(task_id, None, operation, current.status.value, status.value, message, error_id, "after")
def _set_project(self, project: ProjectRecord, status: ProjectStatus, operation: str, message: str, error_id: str | None = None) -> None:
self._event_transition(project.task_id, project.project_id, operation, project.status.value, status.value, message, error_id, "before")
self._store.set_project_status(project.project_id, status, error_id=error_id, summary=message)
self._event_transition(project.task_id, project.project_id, operation, project.status.value, status.value, message, error_id, "after")
def _event_transition(
self,
task_id: str,
project_id: str | None,
operation: str,
before: str,
after: str,
message: str,
error_id: str | None,
phase: str,
*,
recovery_event_id: str | None = None,
) -> None:
details = {"phase": phase}
if recovery_event_id is not None:
details["recovery_event_id"] = recovery_event_id
with self._logging._event_lock:
if recovery_event_id is not None and self._recovery_event_is_durable(task_id, recovery_event_id):
return
append_task_event(
self._logging,
level="ERROR" if error_id else "INFO",
task_id=task_id,
project_id=project_id,
operation=operation,
state_before=before,
state_after=after,
error_id=error_id,
message=message,
details=details,
)
def _recovery_event_is_durable(self, task_id: str, recovery_event_id: str) -> bool:
path = self._logging.root / "tasks" / task_id / "events.jsonl"
if not path.exists():
return False
try:
events = (json.loads(line) for line in path.read_text(encoding="utf-8").splitlines())
return any(
isinstance(event.get("details"), dict)
and event["details"].get("recovery_event_id") == recovery_event_id
for event in events
)
except (OSError, UnicodeError, ValueError, TypeError) as error:
raise TaskCenterError("event_sequence", "cannot determine prior migration recovery events") from error
def _active_project(self, task_id: str, project_id: str, expected: ProjectStatus, *, allow_paused: bool = False) -> ProjectRecord:
task = self._store.get_task(task_id)
if task.status is not TaskStatus.RUNNING and not (allow_paused and task.status is TaskStatus.PAUSED):
raise TaskCenterError("task_not_running", "task is not accepting this action")
project = self._require_project(task_id, project_id)
if project.status is not expected:
raise TaskCenterError("project_not_active", "project is not at the required trial step")
return project
def _require_project(self, task_id: str, project_id: str) -> ProjectRecord:
project = self._project(project_id)
if project.task_id != task_id:
raise TaskCenterError("project_task_mismatch", "project does not belong to the task")
return project
def _project(self, project_id: str) -> ProjectRecord:
return self._store.get_project(project_id)
def _selected_available(self, task_id: str) -> tuple[ProjectRecord, ...]:
return tuple(project for project in self._store.list_projects(task_id) if project.selected and project.available)
@staticmethod
def _active_project_states() -> frozenset[ProjectStatus]:
return frozenset({
ProjectStatus.CAPTURING_BEFORE,
ProjectStatus.AWAITING_OPERATOR,
ProjectStatus.CAPTURING_AFTER,
ProjectStatus.VERIFYING,
})
def _enabled_rules(self, task_id: str) -> tuple[RuleRecord, ...]:
return tuple(rule for rule in self._store.list_rules(task_id) if rule.enabled)
def _evidence_directory(self, project: ProjectRecord) -> Path:
path = self._logging.root / "tasks" / project.task_id / "evidence" / project.project_id / f"attempt-{project.retry_count + 1}"
path.mkdir(parents=True, exist_ok=True)
return path
def _require_attempt(self, project: ProjectRecord, *, require_before: bool = False) -> AttemptContext:
context = self._store.current_attempt(project.project_id)
if context is None:
raise TaskCenterError("attempt_missing", "attempt context is missing; retry the project")
if require_before and (
context.before_path is None
or context.before_size is None
or context.before_sha256 is None
or context.before_modified_ns is None
or context.instruction_json is None
):
raise TaskCenterError("attempt_before_missing", "before evidence is missing; retry the project")
return context
@staticmethod
def _probe_stamp(size: int | None, sha256: str | None, modified_ns: int | None) -> ProbeStamp:
if size is None or sha256 is None or modified_ns is None:
raise TaskCenterError("attempt_before_missing", "attempt probe stamp is missing; retry the project")
return ProbeStamp(int(size), int(modified_ns), str(sha256))
@staticmethod
def _attempt_rules(context: AttemptContext) -> tuple[MappingRule, ...]:
try:
values = json.loads(context.rules_json)
if not isinstance(values, list) or not all(isinstance(item, dict) for item in values):
raise ValueError
rules = tuple(MappingRule(str(item["old_part_number"]), str(item["new_part_number"])) for item in values)
if not rules or any(not rule.old_part_number.strip() or not rule.new_part_number.strip() for rule in rules):
raise ValueError
return rules
except (KeyError, TypeError, ValueError, json.JSONDecodeError) as error:
raise TaskCenterError("attempt_rules", "attempt rule snapshot is invalid; retry the project") from error
@staticmethod
def _instruction_json(instruction: OperatorInstruction) -> str:
return json.dumps(
{
"project_id": instruction.project_id,
"project_path": str(instruction.project_path),
"rules": [
{
"old_part_number": rule.old_part_number,
"new_part_number": rule.new_part_number,
"match_count": rule.match_count,
"logical_identities": list(rule.logical_identities),
}
for rule in instruction.rules
],
},
ensure_ascii=True,
separators=(",", ":"),
)
def _attempt_instruction(self, project: ProjectRecord) -> OperatorInstruction | None:
context = self._store.current_attempt(project.project_id)
if context is None or context.instruction_json is None:
return None
try:
value = json.loads(context.instruction_json)
rules = tuple(
OperatorRule(
str(rule["old_part_number"]),
str(rule["new_part_number"]),
int(rule["match_count"]),
tuple(str(identity) for identity in rule["logical_identities"]),
)
for rule in value["rules"]
)
return OperatorInstruction(str(value["project_id"]), Path(str(value["project_path"])), rules)
except (KeyError, TypeError, ValueError, json.JSONDecodeError) as error:
raise TaskCenterError("attempt_instruction", "attempt instruction is invalid; retry the project") from error
def _default_probe_source(self, _task: TaskRecord, _project: ProjectRecord) -> Path:
return self._logging.root / "runs" / "menu-compatibility-profile.json"
@staticmethod
def _operator_rules(profile: dict[str, object], rules: tuple[RuleRecord, ...]) -> tuple[OperatorRule, ...]:
components = profile.get("components", ())
matches: list[OperatorRule] = []
for rule in rules:
identities: list[str] = []
if isinstance(components, list):
for component in components:
if not isinstance(component, dict):
continue
part_number = component.get("part_number")
identity = component.get("logical_identity")
if isinstance(part_number, str) and isinstance(identity, str) and part_number.strip().casefold() == rule.old_part_number.strip().casefold():
identities.append(identity)
if identities:
matches.append(OperatorRule(rule.old_part_number, rule.new_part_number, len(identities), tuple(sorted(identities))))
return tuple(matches)
@staticmethod
def _load_profile(path: Path) -> dict[str, object]:
try:
loaded = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as error:
raise TaskCenterError("evidence_read", "cannot read captured before profile") from error
if not isinstance(loaded, dict):
raise TaskCenterError("evidence_read", "captured before profile is invalid")
return loaded
def _write_comparison(self, project: ProjectRecord, comparison: ProjectComparison) -> None:
path = self._evidence_directory(project) / "comparison.json"
try:
path.write_text(comparison.to_json(), encoding="utf-8")
except OSError as error:
raise TaskCenterError("comparison_write", "cannot write comparison evidence") from error
@@ -0,0 +1,125 @@
"""Read-only project discovery for the trial task center."""
from __future__ import annotations
import os
from pathlib import Path
import re
import stat
from .errors import TaskCenterError
def _path_identity(path: Path) -> str:
normalized = os.path.normpath(str(path))
return os.path.normcase(normalized) if os.name == "nt" else normalized
_REPARSE_POINT = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
_PROJECT_HEADER_LIMIT = 256 * 1024
_DXD_FRONT_END = re.compile(rb'^\s*KEY\s+FrontEndSnapshot\s+"DxD"\s*$', re.IGNORECASE | re.MULTILINE)
_ICDB_DIRECTORY = re.compile(rb'^\s*KEY\s+iCDBDir\s+"[^"]+"\s*$', re.IGNORECASE | re.MULTILINE)
def _is_schematic_project(path: Path) -> bool:
with path.open("rb") as project_file:
contents = project_file.read(_PROJECT_HEADER_LIMIT)
return bool(_DXD_FRONT_END.search(contents) and _ICDB_DIRECTORY.search(contents))
def _reject_reparse(details: os.stat_result, path: Path) -> None:
if stat.S_ISLNK(details.st_mode) or bool(getattr(details, "st_file_attributes", 0) & _REPARSE_POINT):
raise TaskCenterError("discovery_reparse", f"discovery path contains a reparse point: {path}")
def _contained(root: Path, candidate: Path) -> bool:
try:
candidate.relative_to(root)
except ValueError:
return False
return True
def _lexical_path(path: Path) -> str:
return _path_identity(Path(os.path.abspath(path)))
def scan_projects(root: Path, *, excluded_roots: tuple[Path, ...] = ()) -> tuple[Path, ...]:
"""Discover DxDesigner schematic projects without selecting or modifying them."""
root = Path(root)
try:
if not root.exists() or not root.is_dir():
raise TaskCenterError("discovery_root", f"discovery root is not a directory: {root}")
root_details = root.lstat()
_reject_reparse(root_details, root)
canonical_root = root.resolve()
excluded = tuple(_lexical_path(Path(path)) for path in excluded_roots)
root_key = _lexical_path(root)
if any(root_key == blocked or root_key.startswith(blocked + os.sep) for blocked in excluded):
raise TaskCenterError("discovery_root", f"discovery root is inside task data: {root}")
def is_excluded(path: Path) -> bool:
key = _lexical_path(path)
return any(key == blocked or key.startswith(blocked + os.sep) for blocked in excluded)
candidates: dict[str, Path] = {}
visited: set[tuple[int, int]] = set()
def read_entries(directory: Path) -> tuple[tuple[Path, os.stat_result], ...]:
with os.scandir(directory) as entries:
result: list[tuple[Path, os.stat_result]] = []
for entry in sorted(entries, key=lambda item: item.name.casefold()):
candidate = Path(entry.path)
if is_excluded(candidate):
continue
entry_details = entry.stat(follow_symlinks=False)
_reject_reparse(entry_details, candidate)
result.append((candidate, entry_details))
return tuple(result)
root_entries = read_entries(root)
for candidate, entry_details in root_entries:
if (
stat.S_ISREG(entry_details.st_mode)
and candidate.suffix.casefold() == ".prj"
and _is_schematic_project(candidate)
):
canonical = candidate.resolve()
candidates.setdefault(_path_identity(canonical), canonical)
if candidates:
return tuple(sorted(candidates.values(), key=lambda path: str(path).casefold()))
def visit(
directory: Path,
directory_entries: tuple[tuple[Path, os.stat_result], ...] | None = None,
) -> None:
canonical_directory = directory.resolve()
if not _contained(canonical_root, canonical_directory):
raise TaskCenterError("discovery_containment", f"discovery path escapes its root: {directory}")
details = directory.lstat()
_reject_reparse(details, directory)
identity = details.st_dev, details.st_ino
if identity in visited:
return
visited.add(identity)
entries = directory_entries if directory_entries is not None else read_entries(directory)
for candidate, entry_details in entries:
if stat.S_ISDIR(entry_details.st_mode):
visit(candidate)
elif (
stat.S_ISREG(entry_details.st_mode)
and candidate.suffix.casefold() == ".prj"
and _is_schematic_project(candidate)
):
canonical = candidate.resolve()
if not _contained(canonical_root, canonical):
raise TaskCenterError("discovery_containment", f"project path escapes its root: {candidate}")
candidates.setdefault(_path_identity(canonical), canonical)
visit(root, root_entries)
return tuple(sorted(candidates.values(), key=lambda path: str(path).casefold()))
except TaskCenterError:
raise
except OSError as error:
raise TaskCenterError("discovery_access", f"cannot scan discovery root: {root}") from error
@@ -0,0 +1,106 @@
"""Bounded SceneOS JSON bridge for creating and scanning Replace tasks."""
from __future__ import annotations
import hashlib
import json
from pathlib import Path
import sys
from typing import Any, TextIO
from .errors import TaskCenterError
from .logging_setup import configure_logging
from .service import TaskCenterService
from .store import TaskStore
_MAX_REQUEST_CHARS = 256 * 1024
_SOURCE = "sceneos-cli/v1"
def run(data_root: Path, input_stream: TextIO | None = None, output_stream: TextIO | None = None) -> int:
source = input_stream or sys.stdin
target = output_stream or sys.stdout
if source is None or target is None:
return 2
logging_context = configure_logging(data_root)
store: TaskStore | None = None
try:
payload_text = source.read(_MAX_REQUEST_CHARS + 1)
if len(payload_text) > _MAX_REQUEST_CHARS:
raise TaskCenterError("sceneos_request_size", "SceneOS request is too large")
payload = _request(json.loads(payload_text))
input_value = payload["input"]
context = payload["context"]
request_hash = hashlib.sha256(
json.dumps(input_value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
).hexdigest()
project_root = Path(input_value["projectRoot"])
if not project_root.is_absolute():
raise TaskCenterError("sceneos_project_root", "projectRoot must be an absolute path")
store = TaskStore(Path(data_root) / "task-center.db")
service = TaskCenterService(store, logging_context)
task, projects, created = service.create_scanned_task(
source=_SOURCE,
idempotency_key=context["idempotencyKey"],
request_hash=request_hash,
name=input_value["taskName"],
note="Created by SceneOS. Replacement rules and execution remain in DxPartReplace.",
root=project_root,
)
response = {
"taskId": task.task_id,
"taskName": task.name,
"status": task.status.value,
"projectRoot": str(task.discovery_root),
"projectCount": len(projects),
"availableProjectCount": sum(project.available for project in projects),
"created": created,
}
target.write(json.dumps(response, ensure_ascii=False, separators=(",", ":")))
target.flush()
return 0
except (TaskCenterError, json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
reported = logging_context.report_exception("sceneos_cli", error)
target.write(json.dumps({
"error": reported.code,
"message": reported.message,
"errorId": reported.error_id,
}, ensure_ascii=False, separators=(",", ":")))
target.flush()
return 2
finally:
if store is not None:
store.close()
def _request(value: Any) -> dict[str, Any]:
if not isinstance(value, dict) or set(value) != {"protocol", "input", "context"}:
raise TaskCenterError("sceneos_request", "SceneOS request must contain protocol, input, and context")
if value["protocol"] != _SOURCE:
raise TaskCenterError("sceneos_protocol", "SceneOS CLI protocol is unsupported")
input_value = value["input"]
context = value["context"]
if not isinstance(input_value, dict) or set(input_value) != {"taskName", "projectRoot"}:
raise TaskCenterError("sceneos_input", "SceneOS input must contain taskName and projectRoot")
if not isinstance(context, dict) or set(context) != {"runId", "stepId", "idempotencyKey"}:
raise TaskCenterError("sceneos_context", "SceneOS context is invalid")
for key, limit in (("taskName", 120), ("projectRoot", 2048)):
if not isinstance(input_value[key], str) or not input_value[key].strip() or len(input_value[key]) > limit:
raise TaskCenterError("sceneos_input", f"{key} is invalid")
input_value[key] = input_value[key].strip()
for key in ("runId", "stepId", "idempotencyKey"):
if not isinstance(context[key], str) or not context[key].strip() or len(context[key]) > 256:
raise TaskCenterError("sceneos_context", f"{key} is invalid")
context[key] = context[key].strip()
return value
def main() -> int:
from .application import resolve_data_root
return run(resolve_data_root(None))
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,134 @@
"""Verified backups limited to files needed by DxDesigner schematics."""
from __future__ import annotations
from dataclasses import dataclass
import hashlib
import json
import os
from pathlib import Path
import shutil
import stat
from .errors import TaskCenterError
BACKUP_MANIFEST_NAME = '.dxpartreplace-backup.json'
EXCLUDED_DIRECTORY_NAMES = frozenset({
'.git', '.hg', '.svn', '__pycache__', 'backups', 'ces', 'log files', 'pcb', 'projectbackup',
})
EXCLUDED_DIRECTORY_PATHS = frozenset({
'database/cdbback', 'database/cdbsvr',
})
_REPARSE_POINT = getattr(stat, 'FILE_ATTRIBUTE_REPARSE_POINT', 0x400)
def _is_link_or_reparse(path: Path) -> bool:
details = path.lstat()
return stat.S_ISLNK(details.st_mode) or bool(
getattr(details, 'st_file_attributes', 0) & _REPARSE_POINT
)
@dataclass(frozen=True)
class SchematicBackupResult:
fingerprints: dict[str, tuple[int, str]]
excluded_directories: tuple[str, ...]
@property
def included_bytes(self) -> int:
return sum(size for size, _digest in self.fingerprints.values())
def create_schematic_backup(
data_root: Path,
project_path: Path,
destination: Path,
*,
error_code: str = 'quick_run_backup',
) -> SchematicBackupResult:
project_root = project_path.resolve(strict=True).parent
if data_root.resolve().is_relative_to(project_root):
raise TaskCenterError(error_code, '工程目录包含任务数据,无法安全备份。')
relative_paths, excluded_paths = _selected_paths(project_root, error_code=error_code)
before = _fingerprint_paths(project_root, relative_paths, error_code=error_code)
destination.mkdir(parents=True)
for relative_path in relative_paths:
target = destination / relative_path
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(project_root / relative_path, target)
copied_paths, _ = _selected_paths(destination, error_code=error_code)
source_after_paths, _ = _selected_paths(project_root, error_code=error_code)
if (
copied_paths != relative_paths
or source_after_paths != relative_paths
or _fingerprint_paths(destination, copied_paths, error_code=error_code) != before
or _fingerprint_paths(project_root, source_after_paths, error_code=error_code) != before
):
raise TaskCenterError(error_code, '备份期间工程发生变化,未开始图页枚举或替换。')
result = SchematicBackupResult(before, excluded_paths)
manifest = {
'format_version': 1,
'scope': 'dxdesigner_schematic_essentials',
'project_path': str(project_path.resolve(strict=True)),
'source_root': str(project_root),
'included_file_count': len(before),
'included_bytes': result.included_bytes,
'excluded_directories': list(excluded_paths),
'files': [
{'path': path, 'size': size, 'sha256': digest}
for path, (size, digest) in before.items()
],
}
(destination / BACKUP_MANIFEST_NAME).write_text(
json.dumps(manifest, ensure_ascii=False, indent=2), encoding='utf-8'
)
return result
def _selected_paths(root: Path, *, error_code: str) -> tuple[tuple[Path, ...], tuple[str, ...]]:
selected: list[Path] = []
excluded: list[str] = []
for current, directory_names, file_names in os.walk(root):
current_path = Path(current)
relative_root = current_path.relative_to(root)
kept_directories: list[str] = []
for directory_name in sorted(directory_names, key=str.casefold):
relative_path = relative_root / directory_name
normalized = relative_path.as_posix().casefold()
if directory_name.casefold() in EXCLUDED_DIRECTORY_NAMES or normalized in EXCLUDED_DIRECTORY_PATHS:
excluded.append(relative_path.as_posix())
continue
directory_path = current_path / directory_name
if _is_link_or_reparse(directory_path):
raise TaskCenterError(error_code, '工程精简备份范围中发现链接目录,已停止。')
kept_directories.append(directory_name)
directory_names[:] = kept_directories
for file_name in sorted(file_names, key=str.casefold):
if file_name.casefold() == BACKUP_MANIFEST_NAME.casefold():
continue
path = current_path / file_name
if _is_link_or_reparse(path):
raise TaskCenterError(error_code, '工程精简备份范围中发现链接文件,已停止。')
if path.is_file():
selected.append(path.relative_to(root))
selected.sort(key=lambda path: path.as_posix().casefold())
excluded.sort(key=str.casefold)
return tuple(selected), tuple(excluded)
def _fingerprint_paths(
root: Path,
relative_paths: tuple[Path, ...],
*,
error_code: str,
) -> dict[str, tuple[int, str]]:
result: dict[str, tuple[int, str]] = {}
for relative_path in relative_paths:
path = root / relative_path
if _is_link_or_reparse(path):
raise TaskCenterError(error_code, '工程精简备份范围中发现链接文件,已停止。')
with path.open('rb') as stream:
digest = hashlib.file_digest(stream, 'sha256').hexdigest()
result[relative_path.as_posix()] = (path.stat().st_size, digest)
return result
@@ -0,0 +1,746 @@
"""Qt-free application facade for the trial task center UI."""
from __future__ import annotations
from collections.abc import Callable
from contextlib import contextmanager
from datetime import datetime
import os
from pathlib import Path
import threading
from typing import TypeVar
from .errors import TaskCenterError
from .logging_setup import LoggingContext, _tail_utf8_lines, append_task_event
from .models import ProjectRecord, ProjectStatus, RuleRecord, TaskRecord, TaskStatus
from .quick_run import QuickRunPreparer, QuickRunProgress, QuickRunResult, QuickRunStepResult, _path_key
from .runner import OperatorInstruction, RunnerSnapshot, TrialRunner
from .scanner import scan_projects
from .store import TaskStore
_Result = TypeVar("_Result")
_QUICK_RUN_THREAD_LOCK = threading.Lock()
@contextmanager
def _quick_run_lease(root: Path):
if not _QUICK_RUN_THREAD_LOCK.acquire(blocking=False):
raise TaskCenterError("quick_run_busy", "another quick-run operation is already executing")
handle = None
locked = False
try:
lock_path = root / ".quick-run.execution.lock"
lock_path.parent.mkdir(parents=True, exist_ok=True)
handle = lock_path.open("a+b")
if handle.seek(0, os.SEEK_END) == 0:
handle.write(b"\0")
handle.flush()
handle.seek(0)
try:
if os.name == "nt":
import msvcrt
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError as error:
raise TaskCenterError("quick_run_busy", "another application instance is executing quick-run") from error
locked = True
yield
finally:
if handle is not None:
if locked:
handle.seek(0)
if os.name == "nt":
import msvcrt
msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
else:
import fcntl
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
handle.close()
_QUICK_RUN_THREAD_LOCK.release()
def _default_path_opener(path: Path) -> None:
if os.name != "nt":
raise TaskCenterError("path_opener", "opening evidence folders requires Windows")
os.startfile(path) # type: ignore[attr-defined]
class TaskCenterService:
"""The only API used by UI workers and widgets."""
def __init__(
self,
store: TaskStore,
logging_context: LoggingContext,
*,
path_opener: Callable[[Path], None] = _default_path_opener,
clock: Callable[[], datetime] = datetime.now,
probe_source_resolver: Callable[[TaskRecord, ProjectRecord], Path] | None = None,
quick_run_preparer: QuickRunPreparer | None = None,
) -> None:
self._store = store
self._logging = logging_context
self._path_opener = path_opener
self._clock = clock
self._runner = TrialRunner(store, logging_context, probe_source_resolver=probe_source_resolver)
self._quick_run_preparer = quick_run_preparer or QuickRunPreparer(logging_context.root)
self._batch_feedback = None
def create_task(self, name: str, *, note: str = "") -> TaskRecord:
return self._operation("create_task", None, lambda: self._store.create_task(name, note))
def get_task(self, task_id: str) -> TaskRecord:
return self._operation("get_task", task_id, lambda: self._store.get_task(task_id))
def tasks(self, status: TaskStatus | None = None) -> tuple[TaskRecord, ...]:
return self._operation("list_tasks", None, lambda: self._store.list_tasks(status))
def update_task(self, task_id: str, *, name: str, note: str) -> TaskRecord:
return self._idle_quick_run_operation(
"update_task", task_id, lambda: self._store.update_task(task_id, name=name, note=note)
)
def delete_task(self, task_id: str) -> TaskRecord:
return self._idle_quick_run_operation("delete_task", task_id, lambda: self._store.soft_delete_task(task_id))
def restore_task(self, task_id: str) -> TaskRecord:
return self._idle_quick_run_operation("restore_task", task_id, lambda: self._store.restore_task(task_id))
def purge_task(self, task_id: str, *, confirmed: bool = False) -> str:
def purge() -> str:
if confirmed is not True:
raise TaskCenterError("permanent_delete_confirmation", "permanent task deletion requires explicit confirmation")
if self._store.get_task(task_id).status is not TaskStatus.DELETED:
raise TaskCenterError("task_not_deleted", "move the task to deleted before permanently removing it")
return self._store.purge_task(task_id)
return self._operation("purge_task", task_id, purge)
def rules(self, task_id: str) -> tuple[RuleRecord, ...]:
return self._operation("list_rules", task_id, lambda: self._store.list_rules(task_id))
def add_rule(
self,
task_id: str,
old_part_number: str,
new_part_number: str,
*,
enabled: bool = True,
custom_value_enabled: bool = False,
custom_value: str = "",
sync_nc: bool = True,
) -> RuleRecord:
return self._idle_quick_run_operation(
"add_rule",
task_id,
lambda: self._editable_rules(
task_id,
lambda: self._store.add_rule(
task_id,
old_part_number,
new_part_number,
enabled=enabled,
custom_value_enabled=custom_value_enabled,
custom_value=custom_value,
sync_nc=sync_nc,
),
),
)
def update_rule(
self,
rule_id: str,
*,
old_part_number: str,
new_part_number: str,
enabled: bool,
custom_value_enabled: bool | None = None,
custom_value: str | None = None,
sync_nc: bool | None = None,
) -> RuleRecord:
return self._idle_quick_run_operation(
"update_rule",
None,
lambda: self._editable_rules(
self._store.get_rule(rule_id).task_id,
lambda: self._store.update_rule(
rule_id,
old_part_number=old_part_number,
new_part_number=new_part_number,
enabled=enabled,
custom_value_enabled=custom_value_enabled,
custom_value=custom_value,
sync_nc=sync_nc,
),
),
)
def delete_rule(self, rule_id: str) -> None:
self._idle_quick_run_operation(
"delete_rule",
None,
lambda: self._editable_rules(self._store.get_rule(rule_id).task_id, lambda: self._store.delete_rule(rule_id)),
)
def move_rule(self, rule_id: str, offset: int) -> tuple[RuleRecord, ...]:
return self._idle_quick_run_operation(
"move_rule",
None,
lambda: self._editable_rules(self._store.get_rule(rule_id).task_id, lambda: self._store.move_rule(rule_id, offset)),
)
def projects(self, task_id: str) -> tuple[ProjectRecord, ...]:
return self._operation("list_projects", task_id, lambda: self._store.list_projects(task_id))
def scan_projects(self, task_id: str, root: Path) -> tuple[ProjectRecord, ...]:
def scan_and_sync() -> tuple[ProjectRecord, ...]:
task = self._store.get_task(task_id)
if self._has_current_quick_run_evidence(task_id):
raise TaskCenterError(
"quick_run_options_locked",
"cannot rescan projects while automatic queue evidence exists",
)
if (
task.discovery_root is not None
and _path_key(task.discovery_root) != _path_key(root)
and self._has_current_quick_run_evidence(task_id)
):
raise TaskCenterError(
"discovery_root_locked",
"cannot change the discovery root while automatic queue evidence exists",
)
paths = scan_projects(root, excluded_roots=(self._logging.root,))
return self._store.sync_projects(task_id, root, paths)
return self._idle_quick_run_operation("scan_projects", task_id, scan_and_sync)
def create_scanned_task(
self,
*,
source: str,
idempotency_key: str,
request_hash: str,
name: str,
note: str,
root: Path,
) -> tuple[TaskRecord, tuple[ProjectRecord, ...], bool]:
def create_and_scan() -> tuple[TaskRecord, tuple[ProjectRecord, ...], bool]:
paths = scan_projects(root, excluded_roots=(self._logging.root,))
return self._store.create_scanned_task_for_request(
source=source,
idempotency_key=idempotency_key,
request_hash=request_hash,
name=name,
note=note,
discovery_root=root,
paths=paths,
)
return self._idle_quick_run_operation("create_scanned_task", None, create_and_scan)
def set_project_selected(self, project_id: str, selected: bool) -> ProjectRecord:
def set_selected() -> ProjectRecord:
project = self._project_owner(project_id)
if self._has_current_quick_run_evidence(project.task_id) and not self._retryable_quick_run(project.task_id):
raise TaskCenterError("quick_run_options_locked", "project selection is frozen while queue evidence exists")
snapshot = self._runner.set_project_selected(project.task_id, project_id, selected)
return next(item for item in snapshot.projects if item.project_id == project_id)
return self._idle_quick_run_operation("set_project_selected", None, set_selected)
def select_all_projects(self, task_id: str) -> tuple[ProjectRecord, ...]:
def select() -> tuple[ProjectRecord, ...]:
if self._has_current_quick_run_evidence(task_id) and not self._retryable_quick_run(task_id):
raise TaskCenterError("quick_run_options_locked", "project selection is frozen while queue evidence exists")
return self._runner.set_projects_selected(
task_id,
True,
available_only=True,
).projects
return self._idle_quick_run_operation("select_all_projects", task_id, select)
def clear_project_selection(self, task_id: str) -> tuple[ProjectRecord, ...]:
def clear() -> tuple[ProjectRecord, ...]:
if self._has_current_quick_run_evidence(task_id) and not self._retryable_quick_run(task_id):
raise TaskCenterError("quick_run_options_locked", "project selection is frozen while queue evidence exists")
return self._runner.set_projects_selected(task_id, False).projects
return self._idle_quick_run_operation("clear_project_selection", task_id, clear)
def start_task(self, task_id: str, *, disposable_copy_confirmed: bool) -> RunnerSnapshot:
return self._manual_operation(
"start_task",
task_id,
lambda: self._runner.start_task(task_id, disposable_copy_confirmed=disposable_copy_confirmed),
)
def capture_before(self, task_id: str, project_id: str, probe_path: Path) -> RunnerSnapshot:
return self._manual_operation(
"capture_before", task_id, lambda: self._runner.capture_before(task_id, project_id, probe_path)
)
def confirm_native_attempt(self, task_id: str, project_id: str) -> RunnerSnapshot:
return self._manual_operation(
"confirm_native_attempt", task_id, lambda: self._runner.confirm_native_attempt(task_id, project_id)
)
def capture_after(self, task_id: str, project_id: str, probe_path: Path) -> RunnerSnapshot:
return self._manual_operation(
"capture_after", task_id, lambda: self._runner.capture_after(task_id, project_id, probe_path)
)
def pause_task(self, task_id: str) -> RunnerSnapshot:
return self._manual_operation("pause_task", task_id, lambda: self._runner.pause_task(task_id))
def resume_task(self, task_id: str) -> RunnerSnapshot:
return self._manual_operation("resume_task", task_id, lambda: self._runner.resume_task(task_id))
def retry_project(self, task_id: str, project_id: str) -> RunnerSnapshot:
return self._manual_operation("retry_project", task_id, lambda: self._runner.retry_project(task_id, project_id))
def skip_project(self, task_id: str, project_id: str) -> RunnerSnapshot:
return self._manual_operation("skip_project", task_id, lambda: self._runner.skip_project(task_id, project_id))
def snapshot(self, task_id: str) -> RunnerSnapshot:
return self._operation("snapshot", task_id, lambda: self._runner.snapshot(task_id))
def current_instruction(self, task_id: str) -> OperatorInstruction | None:
return self._operation("current_instruction", task_id, lambda: self._runner.snapshot(task_id).instruction)
def expected_probe_path(self, task_id: str, project_id: str | None = None) -> Path:
def expected_path() -> Path:
task = self._store.get_task(task_id)
if project_id is None:
return self._logging.root / "runs" / "menu-compatibility-profile.json"
project = self._project_owner(project_id)
if project.task_id != task_id:
raise TaskCenterError("project_task_mismatch", "project does not belong to the task")
return self._runner.expected_probe_path(task, project)
return self._operation("expected_probe_path", task_id, expected_path)
def prepare_quick_run(self, task_id: str) -> QuickRunResult:
"""Create the legacy VBS handoff without starting a task-center trial."""
def prepare() -> QuickRunResult:
task = self._store.get_task(task_id)
result = self._quick_run_preparer.prepare(
task_id,
self._store.list_projects(task_id),
self._store.list_rules(task_id),
copy_part_number_to_value=task.copy_part_number_to_value,
)
append_task_event(
self._logging,
level="INFO",
task_id=task_id,
operation="quick_run_prepared",
message="quick-run script prepared",
details={
"script_path": str(result.script_path),
"command_path": str(result.command_path),
"status_path": str(result.status_path),
"log_path": str(result.log_path),
"vbs_root_compatible": result.vbs_root_compatible,
},
)
self._logging.logger.info("quick_run_prepared task_id=%s script_path=%s", task_id, result.script_path)
if not result.vbs_root_compatible:
self._logging.logger.warning(
"quick_run_vbs_root_mismatch task_id=%s data_root=%s expected_root=%s",
task_id,
result.script_path.parent.parent,
self._quick_run_preparer.vbs_data_root,
)
return result
with _quick_run_lease(self._logging.root):
return self._operation("prepare_quick_run", task_id, prepare)
@property
def layout_settings_path(self) -> Path:
return self._logging.root / "ui-layout.ini"
def can_edit_value_options(self, task_id: str) -> bool:
task = self._store.get_task(task_id)
return (
task.status in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.FAILED}
and not self._has_current_quick_run_evidence(task_id)
) or self._retryable_quick_run(task_id)
def set_copy_part_number_to_value(self, task_id: str, enabled: bool) -> TaskRecord:
def update() -> TaskRecord:
if not self.can_edit_value_options(task_id):
raise TaskCenterError("quick_run_options_locked", "queue Value policy is frozen; create a new task to change it")
task = self._store.set_copy_part_number_to_value(task_id, enabled)
append_task_event(self._logging, level="INFO", task_id=task_id, operation="value_policy_changed",
details={"copy_part_label_to_value": enabled})
return task
with _quick_run_lease(self._logging.root):
return self._operation("set_value_policy", task_id, update)
def execute_quick_run(self, task_id: str, *, expected_item: tuple[str, str, str, str] | None = None) -> QuickRunStepResult:
"""Execute one replacement rule through restoration and verification."""
def execute() -> QuickRunStepResult:
task = self._store.get_task(task_id)
result = self._quick_run_preparer.execute_step(
task_id,
self._store.list_projects(task_id),
self._store.list_rules(task_id),
copy_part_number_to_value=task.copy_part_number_to_value,
**({"expected_item": expected_item} if expected_item is not None else {}),
)
self._synchronize_quick_run_progress(task_id)
append_task_event(
self._logging,
level="INFO",
task_id=task_id,
operation="quick_run_executed",
message=result.message,
details={"state": result.state, "status_path": str(result.status_path), "log_path": str(result.log_path)},
)
self._logging.logger.info("quick_run_executed task_id=%s state=%s", task_id, result.state)
return result
with _quick_run_lease(self._logging.root):
return self._operation("execute_quick_run", task_id, execute)
def execute_quick_run_queue(
self,
task_id: str,
*,
expected_item,
stop_event: threading.Event,
continue_after_backup_failure: bool = False,
):
from .batch import execute_batch
with _quick_run_lease(self._logging.root):
if self._store.has_active_project():
raise TaskCenterError('active_project_exists', '人工流程已有活动工程,不能同时启动自动队列。')
if self._store.get_task(task_id).status not in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.RUNNING, TaskStatus.PAUSED}:
raise TaskCenterError('quick_run_task_state', '当前任务状态不允许启动自动队列。')
try:
result = self._operation(
'execute_quick_run_queue',
task_id,
lambda: execute_batch(
self,
task_id,
expected_item=expected_item,
stop_event=stop_event,
continue_after_backup_failure=continue_after_backup_failure,
),
)
if result.paused:
self._pause_quick_run_queue(task_id, 'queue paused at item boundary')
return result
except Exception:
self._pause_quick_run_queue(task_id, 'queue stopped after execution error')
raise
finally:
self._batch_feedback = None
def prepare_failed_quick_run(self, task_id: str) -> QuickRunProgress:
"""Reset only failed projects and discard the finished queue handoff."""
def prepare_retry() -> QuickRunProgress:
task = self._store.get_task(task_id)
if task.status is not TaskStatus.RUNNING:
raise TaskCenterError("quick_run_task_state", "当前任务没有可重试的失败项")
progress = self._quick_run_preparer.progress(
task_id,
self._store.list_projects(task_id),
self._store.list_rules(task_id),
copy_part_number_to_value=task.copy_part_number_to_value,
)
failed_paths = {
_path_key(path)
for path, _summary in getattr(progress, "failed_project_summaries", ())
}
failed_projects = tuple(
project for project in self._store.list_projects(task_id)
if project.status is ProjectStatus.FAILED
and project.selected
and project.available
and (not failed_paths or _path_key(project.path) in failed_paths)
)
if not failed_projects:
raise TaskCenterError("quick_run_complete", "当前队列没有可重试的失败工程")
self._quick_run_preparer.archive_current_handoff(task_id)
for project in failed_projects:
self._store.set_project_status(
project.project_id,
ProjectStatus.PENDING,
summary="project queued for retry",
)
append_task_event(
self._logging,
level="INFO",
task_id=task_id,
operation="quick_run_retry_prepared",
message="失败工程已重新加入队列",
details={"project_ids": [project.project_id for project in failed_projects]},
)
self._quick_run_preparer.ensure_batch_handoff(
task_id,
self._store.list_projects(task_id),
self._store.list_rules(task_id),
copy_part_number_to_value=task.copy_part_number_to_value,
)
return self._quick_run_preparer.progress(
task_id,
self._store.list_projects(task_id),
self._store.list_rules(task_id),
copy_part_number_to_value=task.copy_part_number_to_value,
)
with _quick_run_lease(self._logging.root):
return self._operation("prepare_failed_quick_run", task_id, prepare_retry)
def _pause_quick_run_queue(self, task_id: str, message: str) -> None:
if self._store.get_task(task_id).status is TaskStatus.RUNNING:
self._store.set_task_status(task_id, TaskStatus.PAUSED, summary=message)
append_task_event(self._logging, level='INFO', task_id=task_id,
operation='quick_run_queue_paused', message=message)
def batch_feedback(self):
return self._batch_feedback
def quick_run_phase(self, task_id: str) -> str:
"""Read the current task's local quick-run phase without executing COM work."""
def read_phase() -> str:
self._store.get_task(task_id)
if self._retryable_quick_run(task_id):
return "retry"
progress = self._synchronize_quick_run_progress(task_id)
if progress.queue_complete:
return "retry" if getattr(progress, "failed_items", 0) else "complete"
return "selection"
return self._operation("quick_run_phase", task_id, read_phase)
def has_interrupted_quick_run(self, task_id: str) -> bool:
return self._quick_run_preparer.has_interrupted(task_id)
def recover_quick_run(self, task_id: str, *, confirmed: bool = False) -> QuickRunStepResult:
from .recovery import recover
def reconcile() -> QuickRunStepResult:
task = self._store.get_task(task_id)
if task.status is TaskStatus.DELETED:
raise TaskCenterError("quick_run_recovery", "请先恢复已删除的任务记录,再核验其中断步骤。")
projects = self._store.list_projects(task_id)
if any(project.selected and project.status not in {ProjectStatus.PENDING, ProjectStatus.COMPLETED} for project in projects):
raise TaskCenterError("quick_run_recovery", "工程包含手动执行阶段或失败记录,不能混用自动队列恢复。")
result = recover(self._quick_run_preparer, task_id, projects,
self._store.list_rules(task_id), copy_part_number_to_value=task.copy_part_number_to_value,
confirmed=confirmed)
if task.status in {TaskStatus.PAUSED, TaskStatus.FAILED}:
self._store.set_task_status(task_id, TaskStatus.READY, summary="interrupted quick-run reconciled")
self._synchronize_quick_run_progress(task_id)
append_task_event(self._logging, level="INFO", task_id=task_id, operation="quick_run_recovered",
message=result.message, details={"state": result.state, "evidence": str(result.log_path.parent)})
return result
with _quick_run_lease(self._logging.root):
return self._operation("recover_quick_run", task_id, reconcile)
def quick_run_progress(self, task_id: str) -> QuickRunProgress:
return self._operation("quick_run_progress", task_id, lambda: self._synchronize_quick_run_progress(task_id))
def has_quick_run_evidence(self, task_id: str) -> bool:
return self._quick_run_preparer.evidence_path(task_id) is not None
def _has_current_quick_run_evidence(self, task_id: str) -> bool:
evidence = self._quick_run_preparer.evidence_path(task_id)
return evidence == self._quick_run_preparer._data_root / "quick-run"
def tail_log(self, task_id: str, *, limit: int = 100) -> tuple[str, ...]:
if limit < 1:
raise TaskCenterError("log_limit", "log line limit must be positive")
path = self._logging.root / "tasks" / task_id / "events.jsonl"
try:
return _tail_utf8_lines(path, limit) if path.exists() else ()
except (OSError, UnicodeError) as error:
raise TaskCenterError("log_read", "cannot read task event log") from error
def open_task_log(self, task_id: str) -> Path:
def open_path() -> Path:
self._store.get_task(task_id)
path = self._logging.root / "tasks" / task_id / "events.jsonl"
path.parent.mkdir(parents=True, exist_ok=True)
if not path.exists():
path.touch()
self._path_opener(path)
return path
return self._operation("open_task_log", task_id, open_path)
def report_ui_error(self, error: BaseException) -> TaskCenterError:
"""Record an unexpected presentation-layer failure with a stable support ID."""
return self._logging.report_exception("ui", error)
def open_evidence(self, task_id: str, project_id: str) -> Path:
def open_path() -> Path:
project = next((item for item in self._store.list_projects(task_id) if item.project_id == project_id), None)
if project is None:
raise TaskCenterError("unknown_project", "project does not belong to the task")
quick_run_path = self._quick_run_preparer.evidence_path(task_id, project.path)
if quick_run_path is not None:
self._path_opener(quick_run_path)
return quick_run_path
path = self._logging.root / "tasks" / task_id / "evidence" / project_id / f"attempt-{project.retry_count + 1}"
path.mkdir(parents=True, exist_ok=True)
self._path_opener(path)
return path
return self._operation("open_evidence", task_id, open_path)
def open_quick_run_evidence(self, task_id: str) -> Path:
def open_path() -> Path:
self._store.get_task(task_id)
path = self._quick_run_preparer.evidence_path(task_id)
if path is None:
raise TaskCenterError("evidence_missing", "quick-run evidence is unavailable for this task")
self._path_opener(path)
return path
return self._operation("open_quick_run_evidence", task_id, open_path)
def _operation(self, name: str, task_id: str | None, action: Callable[[], _Result]) -> _Result:
timestamp = self._clock().isoformat()
self._logging.logger.info("operation_start=%s task_id=%s at=%s", name, task_id or "", timestamp)
try:
result = action()
except TaskCenterError as error:
self._logging.report_exception(name, error)
raise
except Exception as error:
raise self._logging.report_exception(name, error) from error
completed_timestamp = self._clock().isoformat()
self._logging.logger.info("operation_complete=%s task_id=%s at=%s", name, task_id or "", completed_timestamp)
return result
def _idle_quick_run_operation(
self,
name: str,
task_id: str | None,
action: Callable[[], _Result],
) -> _Result:
with _quick_run_lease(self._logging.root):
return self._operation(name, task_id, action)
def _manual_operation(self, name: str, task_id: str, action: Callable[[], _Result]) -> _Result:
def checked_action():
if self._quick_run_preparer.evidence_path(task_id) is not None:
raise TaskCenterError('quick_run_manual_operation', '此任务属于自动队列,不能混用人工采集、跳过或重试。请使用继续队列或核验恢复。')
return action()
return self._idle_quick_run_operation(name, task_id, checked_action)
def _synchronize_quick_run_progress(
self,
task_id: str,
*,
progress: QuickRunProgress | None = None,
) -> QuickRunProgress:
task = self._store.get_task(task_id)
projects = self._store.list_projects(task_id)
if progress is None:
progress = self._quick_run_preparer.progress(
task_id,
projects,
self._store.list_rules(task_id),
copy_part_number_to_value=task.copy_part_number_to_value,
)
by_path = {os.path.normcase(os.path.abspath(str(project.path))): project.project_id for project in projects}
project_by_id = {project.project_id: project for project in projects}
summary_by_id = {
by_path[_path_key(path)]: summary
for path, summary in (
*progress.project_summaries,
*getattr(progress, "failed_project_summaries", ()),
)
if _path_key(path) in by_path
}
failed_project_ids = tuple(
project_id
for project_id, summary in summary_by_id.items()
if summary.partition("|")[0].rsplit(":", 1)[-1] == "failed"
)
completed_project_ids = tuple(
by_path[path_key]
for path in progress.completed_project_paths
if (path_key := os.path.normcase(os.path.abspath(str(path)))) in by_path
and by_path[path_key] not in failed_project_ids
)
changed_project_ids = tuple(
project_id
for project_id in completed_project_ids
if (
project_by_id[project_id].status is not ProjectStatus.COMPLETED
or project_by_id[project_id].summary != summary_by_id.get(
project_id,
"current-sheet quick-run queue completed",
)
)
)
changed_failed_project_ids = tuple(
project_id
for project_id in failed_project_ids
if (
project_by_id[project_id].status is not ProjectStatus.FAILED
or project_by_id[project_id].summary != summary_by_id.get(project_id, "")
)
)
retry_summary = "current-sheet quick-run queue completed with retryable failures"
task_state_changed = (
progress.completed_items > 0 and task.status in {TaskStatus.DRAFT, TaskStatus.READY}
) or (
progress.queue_complete
and (
(bool(failed_project_ids) and (task.status is not TaskStatus.RUNNING or task.summary != retry_summary))
or (not failed_project_ids and task.status is not TaskStatus.COMPLETED)
)
)
if task.status is not TaskStatus.DELETED and (changed_project_ids or changed_failed_project_ids or task_state_changed):
self._store.record_quick_run_progress(
task_id,
changed_project_ids,
failed_project_ids=changed_failed_project_ids,
has_progress=progress.completed_items > 0,
queue_complete=progress.queue_complete,
project_summaries={
project_id: summary_by_id[project_id]
for project_id in (*changed_project_ids, *changed_failed_project_ids)
if project_id in summary_by_id
},
)
return progress
def _editable_rules(self, task_id: str, action: Callable[[], _Result]) -> _Result:
if (
self._store.get_task(task_id).status in {TaskStatus.RUNNING, TaskStatus.PAUSED}
or self._has_current_quick_run_evidence(task_id)
) and not self._retryable_quick_run(task_id):
raise TaskCenterError("rules_locked", "mapping rules cannot change while a task attempt is active")
return action()
def _retryable_quick_run(self, task_id: str) -> bool:
task = self._store.get_task(task_id)
return (
task.status is TaskStatus.RUNNING
and task.summary == "current-sheet quick-run queue completed with retryable failures"
and any(project.status is ProjectStatus.FAILED for project in self._store.list_projects(task_id))
)
def _project_owner(self, project_id: str) -> ProjectRecord:
return self._store.get_project(project_id)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,5 @@
"""PySide6 task-center presentation layer."""
from .main_window import TrialTaskCenterWindow
__all__ = ["TrialTaskCenterWindow"]
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,62 @@
"""Ordered Part Number mapping table."""
from __future__ import annotations
from collections.abc import Callable, Iterable
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QAbstractItemView, QCheckBox, QHBoxLayout, QHeaderView, QTableWidget, QTableWidgetItem, QWidget
class MappingTable(QTableWidget):
def __init__(self, on_enabled_changed: Callable[[str, bool], None] | None = None) -> None:
super().__init__(0, 6)
self.setObjectName("mappingTable")
self.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
self.setHorizontalHeaderLabels(("旧物料编码", "新物料编码", "自定义 Value", "同步 NC", "启用", "顺序"))
header = self.horizontalHeader()
for section, width in ((0, 220), (1, 220), (2, 180), (3, 80), (4, 70), (5, 65)):
header.setSectionResizeMode(section, QHeaderView.ResizeMode.Interactive)
header.resizeSection(section, width)
header.setStretchLastSection(True)
self._on_enabled_changed = on_enabled_changed
self._rules_editable = True
def set_rules_editable(self, editable: bool) -> None:
self._rules_editable = editable
for row in range(self.rowCount()):
cell = self.cellWidget(row, 4)
if cell is not None:
for check in cell.findChildren(QCheckBox):
check.setEnabled(editable)
def populate(self, rules: Iterable[object]) -> None:
self.setRowCount(0)
for row, rule in enumerate(rules):
self.insertRow(row)
first = QTableWidgetItem(str(getattr(rule, "old_part_number")))
first.setData(32, str(getattr(rule, "rule_id")))
self.setItem(row, 0, first)
self.setItem(row, 1, QTableWidgetItem(str(getattr(rule, "new_part_number"))))
custom_value = str(getattr(rule, "custom_value", "")) if bool(getattr(rule, "custom_value_enabled", False)) else "不写入"
self.setItem(row, 2, QTableWidgetItem(custom_value))
self.setItem(row, 3, QTableWidgetItem("是" if bool(getattr(rule, "sync_nc", True)) else "否"))
enabled = QCheckBox()
enabled.setChecked(bool(getattr(rule, "enabled")))
enabled.setEnabled(self._rules_editable)
enabled.setToolTip("启用或停用此替换规则")
if self._on_enabled_changed is not None:
rule_id = str(getattr(rule, "rule_id"))
enabled.toggled.connect(lambda checked, item_id=rule_id: self._on_enabled_changed(item_id, checked))
enabled_cell = QWidget()
enabled_layout = QHBoxLayout(enabled_cell)
enabled_layout.setContentsMargins(0, 0, 0, 0)
enabled_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
enabled_layout.addWidget(enabled)
self.setCellWidget(row, 4, enabled_cell)
self.setItem(row, 5, QTableWidgetItem(str(getattr(rule, "position") + 1)))
self.resizeRowsToContents()
def current_rule_id(self) -> str | None:
item = self.item(self.currentRow(), 0)
return str(item.data(32)) if item is not None else None
@@ -0,0 +1,122 @@
"""Project selection table used by the task workspace."""
from __future__ import annotations
from collections.abc import Callable, Iterable
from PySide6.QtCore import Qt
from PySide6.QtGui import QColor
from PySide6.QtWidgets import QAbstractItemView, QCheckBox, QHeaderView, QTableWidget, QTableWidgetItem
PROJECT_STATUS_TEXT = {
"pending": "待处理",
"capturing_before": "采集替换前",
"awaiting_operator": "等待人工替换",
"capturing_after": "采集替换后",
"verifying": "正在核验",
"completed": "已完成",
"failed": "失败",
"skipped": "已跳过",
}
PROJECT_RESULT_TEXT = {
"project selected for capture": "工程已进入替换前采集",
"before profile captured": "替换前数据已采集",
"capturing after profile": "正在采集替换后数据",
"verifying captured profiles": "正在核验替换前后数据",
"comparison passed": "替换核验通过",
"project selected after resume": "继续处理此工程",
"project selected for retry": "工程已进入重试",
"project queued for retry": "工程已加入重试队列",
"project skipped by operator": "工程已由操作员跳过",
"operator stopped project before verification": "工程在核验前被操作员停止",
"current-sheet quick-run queue completed": "图页替换队列已校验,尚未保存",
}
PROJECT_STATUS_COLORS = {
"completed": "#245b35",
"failed": "#84251e",
"skipped": "#5a4600",
}
class ProjectTable(QTableWidget):
def __init__(self, on_selection_changed: Callable[[str, bool], None]) -> None:
super().__init__(0, 5)
self.setObjectName("projectTable")
self.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
self.setHorizontalHeaderLabels(("选择", "工程", "路径", "状态", "结果"))
header = self.horizontalHeader()
header.setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed)
header.resizeSection(0, 58)
for section, width in ((1, 150), (2, 360), (3, 90), (4, 210)):
header.setSectionResizeMode(section, QHeaderView.ResizeMode.Interactive)
header.resizeSection(section, width)
header.setStretchLastSection(True)
self._on_selection_changed = on_selection_changed
self._selection_enabled = True
def set_selection_enabled(self, enabled: bool) -> None:
self._selection_enabled = enabled
for row in range(self.rowCount()):
check = self.cellWidget(row, 0)
if check is not None:
check.setEnabled(enabled and bool(check.property('projectAvailable')))
def populate(self, projects: Iterable[object]) -> None:
vertical_position = self.verticalScrollBar().value()
horizontal_position = self.horizontalScrollBar().value()
current_project_id = self.current_project_id()
self.setRowCount(0)
current_row = -1
for row, project in enumerate(projects):
self.insertRow(row)
check = QCheckBox()
check.setChecked(bool(getattr(project, "selected")))
check.setProperty('projectAvailable', bool(getattr(project, 'available')))
check.setEnabled(self._selection_enabled and bool(check.property('projectAvailable')))
project_id = str(getattr(project, "project_id"))
check.toggled.connect(lambda checked, item_id=project_id: self._on_selection_changed(item_id, checked))
self.setCellWidget(row, 0, check)
name = QTableWidgetItem(str(getattr(project, "display_name")))
name.setData(Qt.ItemDataRole.UserRole, project_id)
self.setItem(row, 1, name)
if project_id == current_project_id:
current_row = row
self.setItem(row, 2, QTableWidgetItem(str(getattr(project, "path"))))
status = str(getattr(project, "status").value)
status_item = QTableWidgetItem(PROJECT_STATUS_TEXT.get(status, status))
self.setItem(row, 3, status_item)
raw_detail = str(getattr(project, "summary"))
detail = PROJECT_RESULT_TEXT.get(raw_detail, raw_detail)
if raw_detail.startswith("quick_run_result:"):
try:
_, replaced, missed, result_detail = raw_detail.split(":", 3)
saved, _, failure_detail = result_detail.partition("|")
if saved == "failed":
status = "failed"
status_item.setText("失败")
detail = failure_detail or "工程失败,失败原因请查看任务日志"
elif int(replaced) == 0:
status = "skipped"
status_item.setText("未命中跳过")
detail = f"未命中 {int(missed)} 项,未作替换"
else:
detail = f"替换校验 {int(replaced)} 项,未命中 {int(missed)} 项;" + ("已保存" if saved == "saved" else "尚未确认保存")
except ValueError:
detail = "结果记录格式异常,请查看证据"
error_id = getattr(project, "error_id")
color = PROJECT_STATUS_COLORS.get(status)
if color is not None:
status_item.setForeground(QColor(color))
self.setItem(row, 4, QTableWidgetItem(f"{error_id or ''} {detail}".strip()))
self.resizeRowsToContents()
if current_row >= 0:
self.setCurrentCell(current_row, 1)
self.verticalScrollBar().setValue(vertical_position)
self.horizontalScrollBar().setValue(horizontal_position)
def current_project_id(self) -> str | None:
item = self.item(self.currentRow(), 1)
return str(item.data(Qt.ItemDataRole.UserRole)) if item is not None else None
@@ -0,0 +1,71 @@
"""Operator guidance, commands, and read-only task log widgets."""
from __future__ import annotations
from PySide6.QtWidgets import QCheckBox, QHBoxLayout, QLabel, QProgressBar, QPushButton, QTextEdit, QToolButton, QVBoxLayout, QWidget
class RunPanel(QWidget):
def __init__(self) -> None:
super().__init__()
self.operator_band = QLabel("请选择任务,并扫描工程目录。", objectName="operatorBand")
self.operator_band.setWordWrap(True)
self.queue_summary = QLabel("未选择任务", objectName="queueSummary")
self.execution_status = QLabel("空闲", objectName="executionStatus")
self.execution_status.setWordWrap(True)
self.busy_indicator = QProgressBar(objectName="quickRunBusyIndicator")
self.busy_indicator.setRange(0, 0)
self.busy_indicator.setTextVisible(False)
self.busy_indicator.setFixedHeight(4)
self.busy_indicator.hide()
self.start_button = QPushButton("开始任务", objectName="startTaskButton")
self.quick_run_button = QPushButton("确认并执行替换", objectName="quickRunButton")
self.stop_queue_button = QPushButton("完成当前项后暂停", objectName="stopQueueButton")
self.stop_queue_button.hide()
self.continue_without_backup_button = QPushButton(
"忽略备份失败并继续", objectName="continueWithoutBackupButton"
)
self.continue_without_backup_button.setToolTip(
"仅在精简原理图备份失败后启用。继续执行将无法保证该工程可从本工具备份回滚。"
)
self.continue_without_backup_button.hide()
self.recover_button = QPushButton("核验并恢复中断任务", objectName="recoverQuickRunButton")
self.recover_button.setToolTip("先备份并核验已保存工程;不重复调用原生替换。混合状态或连接异常时保留保护。")
self.pause_button = QPushButton("暂停", objectName="pauseTaskButton")
self.resume_button = QPushButton("继续", objectName="resumeTaskButton")
self.capture_before_button = QPushButton("采集替换前结果", objectName="captureBeforeButton")
self.confirm_attempt_button = QPushButton("已完成原生替换", objectName="confirmNativeAttemptButton")
self.capture_after_button = QPushButton("采集替换后结果", objectName="captureAfterButton")
self.copy_value_check = QCheckBox("替换后将 Part Label 写入 Value", objectName="copyPartNumberToValue")
self.copy_value_check.setToolTip("勾选:将替换后目标器件的 Part Label 写入 Value。未勾选:保留原生替换后的 Value,不创建缺失字段。两种模式均继承已有 Value 的位置、字体等显示样式。队列生成后不可更改。")
self.toggle_log_button = QToolButton(objectName="toggleLogButton")
self.toggle_log_button.setText("显示日志")
self.toggle_log_button.setCheckable(True)
self.reset_layout_button = QToolButton(objectName="resetLayoutButton")
self.reset_layout_button.setText("重置布局")
self.log_view = QTextEdit(objectName="logView")
self.log_view.setReadOnly(True)
self.log_view.setMinimumHeight(40)
self.log_view.hide()
self.toggle_log_button.toggled.connect(self.log_view.setVisible)
self.toggle_log_button.toggled.connect(lambda checked: self.toggle_log_button.setText("收起日志" if checked else "显示日志"))
commands = QHBoxLayout()
for button in (
self.quick_run_button,
self.stop_queue_button,
self.continue_without_backup_button,
self.recover_button,
):
commands.addWidget(button)
commands.addStretch(1)
commands.addWidget(self.toggle_log_button)
commands.addWidget(self.reset_layout_button)
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self.queue_summary)
layout.addWidget(self.execution_status)
layout.addWidget(self.busy_indicator)
layout.addWidget(self.operator_band)
layout.addWidget(self.copy_value_check)
layout.addLayout(commands)
layout.addWidget(self.log_view, 1)
@@ -0,0 +1,38 @@
"""Restrained, work-focused styling for the trial task center."""
APP_STYLESHEET = """
QWidget { background: #f4f6f8; color: #17212b; font-size: 13px; }
QWidget#taskNavigation, QWidget#workspace, QTextEdit { background: #ffffff; border: 1px solid #cbd5df; }
QPushButton, QComboBox, QLineEdit, QTableWidget { border: 1px solid #aebdca; border-radius: 4px; background: #ffffff; }
QPushButton { min-height: 30px; padding: 2px 9px; }
QPushButton:hover { background: #edf4fa; }
QPushButton:disabled { color: #81909c; background: #e8edf1; }
QPushButton#quickRunButton { background: #1769aa; color: white; border-color: #1769aa; font-weight: 600; }
QPushButton#quickRunButton:hover { background: #12588f; }
QPushButton#quickRunButton:disabled { background: #d9e2e9; color: #667784; border-color: #cbd5df; }
QPushButton#deleteTaskButton, QPushButton#deleteMappingButton { color: #9f2018; border-color: #d5a29d; }
QPushButton#deleteTaskButton:hover, QPushButton#deleteMappingButton:hover { background: #fff0ee; }
QPushButton#deleteTaskButton:disabled, QPushButton#deleteMappingButton:disabled { color: #81909c; border-color: #cbd5df; background: #e8edf1; }
QLineEdit, QComboBox { min-height: 28px; padding: 0 6px; }
QTableWidget { gridline-color: #d8e0e7; selection-background-color: #dbeeff; selection-color: #17212b; }
QHeaderView::section { background: #e8edf1; border: 0; border-bottom: 1px solid #cbd5df; padding: 5px; font-weight: 600; }
QListWidget { background: #ffffff; border: 1px solid #cbd5df; }
QListWidget::item { padding: 6px; }
QListWidget::item:selected { background: #dbeeff; color: #17212b; }
QLabel#operatorBand { background: #fff8d9; border: 1px solid #dfbf4b; padding: 7px; color: #5a4600; }
QLabel#operatorBand[state="success"] { background: #edf8f1; border-color: #71a982; color: #245b35; }
QLabel#operatorBand[state="error"] { background: #fff0ee; border-color: #d58b84; color: #84251e; }
QLabel#operatorBand[state="busy"] { background: #edf4fa; border-color: #83abc9; color: #234f70; }
QLabel#operatorBand[state="info"] { background: #edf4fa; border-color: #83abc9; color: #234f70; }
QLabel#operatorBand[state="warning"] { background: #fff8d9; border-color: #dfbf4b; color: #5a4600; }
QLabel#queueSummary { color: #263b49; font-weight: 600; }
QLabel#executionStatus { color: #49616f; }
QProgressBar#quickRunBusyIndicator { border: 0; background: #dbe4ea; }
QProgressBar#quickRunBusyIndicator::chunk { background: #1769aa; }
QSplitter::handle { background: #bccbd8; border: 1px solid #e7edf2; }
QSplitter::handle:hover { background: #83abc9; }
QToolButton { background: #ffffff; border: 1px solid #aebdca; border-radius: 4px; padding: 4px 7px; }
QToolButton:hover { background: #edf4fa; }
QLabel#statusLabel { color: #49616f; }
QTextEdit { padding: 5px; font-family: Consolas, "Courier New", monospace; }
"""
@@ -0,0 +1,48 @@
"""Task navigation widget with Active, Completed, and Deleted filters."""
from __future__ import annotations
from collections.abc import Callable
from typing import Iterable
from PySide6.QtCore import Qt, QSignalBlocker
from PySide6.QtWidgets import QComboBox, QGridLayout, QListWidget, QListWidgetItem, QPushButton, QVBoxLayout, QWidget
class TaskList(QWidget):
def __init__(self, on_open: Callable[[str], None]) -> None:
super().__init__()
self.setObjectName("taskNavigation")
self.filter = QComboBox(objectName="taskFilter")
self.filter.addItems(("进行中", "已完成", "已删除"))
self.list = QListWidget(objectName="taskList")
self.new_button = QPushButton("新建", objectName="newTaskButton")
self.edit_button = QPushButton("编辑", objectName="editTaskButton")
self.delete_button = QPushButton("删除", objectName="deleteTaskButton")
self.restore_button = QPushButton("恢复", objectName="restoreTaskButton")
actions = QGridLayout()
actions.addWidget(self.new_button, 0, 0)
actions.addWidget(self.edit_button, 0, 1)
actions.addWidget(self.delete_button, 1, 0)
actions.addWidget(self.restore_button, 1, 1)
layout = QVBoxLayout(self)
layout.setContentsMargins(8, 8, 8, 8)
layout.addWidget(self.filter)
layout.addWidget(self.list, 1)
layout.addLayout(actions)
self.list.itemSelectionChanged.connect(lambda: on_open(self.current_task_id() or ""))
def current_task_id(self) -> str | None:
item = self.list.currentItem()
return str(item.data(Qt.ItemDataRole.UserRole)) if item is not None else None
def populate(self, tasks: Iterable[object]) -> None:
selected = self.current_task_id()
with QSignalBlocker(self.list):
self.list.clear()
for task in tasks:
item = QListWidgetItem(str(getattr(task, "name")))
item.setData(Qt.ItemDataRole.UserRole, str(getattr(task, "task_id")))
self.list.addItem(item)
if getattr(task, "task_id") == selected:
self.list.setCurrentItem(item)
@@ -0,0 +1,34 @@
"""Reusable QThreadPool wrappers for service calls that perform I/O."""
from __future__ import annotations
from collections.abc import Callable
from typing import Any
from PySide6.QtCore import QObject, QRunnable, Signal, Slot
class WorkerSignals(QObject):
"""Signals emitted for a single background callable."""
succeeded = Signal(object)
failed = Signal(object)
finished = Signal()
class ServiceWorker(QRunnable):
"""Run one service callable without blocking the Qt event loop."""
def __init__(self, action: Callable[[], Any]) -> None:
super().__init__()
self.action = action
self.signals = WorkerSignals()
@Slot()
def run(self) -> None:
try:
self.signals.succeeded.emit(self.action())
except Exception as error: # Service converts unexpected errors to stable TaskCenterError values.
self.signals.failed.emit(error)
finally:
self.signals.finished.emit()
@@ -0,0 +1 @@
VERSION = "1.0.0"
@@ -0,0 +1,229 @@
"""Monitor correlated work progress and request cancellation before escalation."""
from __future__ import annotations
import ctypes
import json
import os
from pathlib import Path
import queue
import re
import subprocess
import threading
import time
from uuid import uuid4
class WorkerMonitorError(subprocess.SubprocessError):
pass
class ProgressWatch:
def __init__(self, token: str, job_id: str, idle_timeout: float, started: float) -> None:
if idle_timeout <= 0:
raise ValueError('Idle timeout must be positive')
self.token = token
self.job_id = job_id
self.idle_timeout = idle_timeout
self.last_progress = started
self.sequence = 0
self.stop_requested = False
self.stage = 'starting'
self.done = 0
self.total = 0
self.safe_stop = True
def accept(self, line: bytes, now: float) -> bool:
try:
fields = line.decode('ascii').strip().split('\t')
if len(fields) != 8 or fields[:3] != ['DX_PROGRESS', self.token, self.job_id]:
return False
sequence, done, total, safe = (int(fields[index]) for index in (3, 5, 6, 7))
if not self.sequence < sequence <= 2**31 - 1 or not re.fullmatch('[a-z_]{1,64}', fields[4]):
return False
if done < 0 or total < 0 or (total and done > total) or safe not in {0, 1}:
return False
except (ValueError, UnicodeError):
return False
self.sequence = sequence
self.last_progress = now
self.stage, self.done, self.total, self.safe_stop = fields[4], done, total, bool(safe)
return True
def action(self, now: float) -> str | None:
idle = now - self.last_progress
if not self.stop_requested and idle >= self.idle_timeout:
self.stop_requested = True
return 'request_stop'
if self.stop_requested and idle >= self.idle_timeout * 2:
return 'unresponsive'
return None
def snapshot(self) -> dict:
return {name: getattr(self, name) for name in ('token', 'job_id', 'sequence', 'stage', 'done', 'total', 'safe_stop', 'stop_requested')}
def _atomic_text(path: Path, text: str) -> None:
temporary = path.with_name(path.name + '.tmp')
temporary.write_text(text, encoding='utf-8')
temporary.replace(path)
def _publish_progress(path: Path, snapshot: dict) -> None:
try:
_atomic_text(path, json.dumps(snapshot, ensure_ascii=False))
except OSError as error:
if not isinstance(error, PermissionError) and getattr(error, 'winerror', None) not in {5, 32, 33}:
raise
def _decode(data: bytes) -> str:
try:
return data.decode('utf-8')
except UnicodeError:
return data.decode('mbcs' if os.name == 'nt' else 'utf-8', errors='replace')
class _OwnedWorkers:
def __init__(self, token: str, allowed: set[str]) -> None:
import win32job
self.job = win32job.CreateJobObject(None, 'DxPartReplace-monitor-' + token)
self.allowed = {os.path.normcase(os.path.abspath(value)) for value in allowed}
def assign(self, process: subprocess.Popen) -> None:
import win32job
win32job.AssignProcessToJobObject(self.job, process._handle)
def stop_workers(self, process: subprocess.Popen) -> list[str]:
import win32api
import win32job
failures = []
query_name = ctypes.WinDLL('kernel32', use_last_error=True).QueryFullProcessImageNameW
query_name.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_wchar_p, ctypes.POINTER(ctypes.c_ulong)]
query_name.restype = ctypes.c_int
try:
process_ids = win32job.QueryInformationJobObject(self.job, win32job.JobObjectBasicProcessIdList)
for process_id in process_ids:
if process_id == process.pid:
continue
handle = None
try:
handle = win32api.OpenProcess(0x1000 | 0x0001, False, process_id)
size = ctypes.c_ulong(32768)
buffer = ctypes.create_unicode_buffer(size.value)
if not query_name(int(handle), 0, buffer, ctypes.byref(size)):
raise ctypes.WinError(ctypes.get_last_error())
executable = os.path.normcase(os.path.abspath(buffer.value))
if executable in self.allowed and Path(executable).name.casefold() != 'viewdraw.exe':
win32api.TerminateProcess(handle, 1)
else:
failures.append(f'preserved_non_worker pid={process_id}')
except Exception as error:
failures.append(f'child_cleanup pid={process_id} error={error}')
finally:
if handle is not None:
handle.Close()
except Exception as error:
failures.append(f'job_cleanup error={error}')
finally:
if process.poll() is None:
process.kill()
return failures
def close(self) -> None:
self.job.Close()
def run_monitored_process(command: tuple[str, ...], idle_timeout: float) -> subprocess.CompletedProcess[str]:
root = Path(command[3])
job_id = command[-1]
token = uuid4().hex
ready = root / f'monitor-{token}.ready'
stop = root / f'monitor-{token}.stop'
progress_path = root / 'worker-progress.json'
root.mkdir(parents=True, exist_ok=True)
watch = ProgressWatch(token, job_id, idle_timeout, time.monotonic())
owned = _OwnedWorkers(token, {command[0], command[4]})
process = None
threads = []
messages = queue.Queue(maxsize=1024)
stop_readers = threading.Event()
output = [bytearray(), bytearray()]
def read_stream(stream, channel):
try:
while not stop_readers.is_set():
line = stream.readline(16384)
if not line:
break
while not stop_readers.is_set():
try:
messages.put((channel, line), timeout=0.1)
break
except queue.Full:
pass
finally:
stream.close()
def receive(channel, line):
if channel == 0 and watch.accept(line, time.monotonic()):
_publish_progress(progress_path, watch.snapshot())
elif len(output[channel]) < 1024 * 1024:
output[channel].extend(line[:1024 * 1024 - len(output[channel])])
try:
process = subprocess.Popen((*command, token), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
creationflags=subprocess.CREATE_NO_WINDOW)
owned.assign(process)
for channel, stream in enumerate((process.stdout, process.stderr)):
thread = threading.Thread(target=read_stream, args=(stream, channel), daemon=True)
thread.start()
threads.append(thread)
_publish_progress(progress_path, watch.snapshot())
_atomic_text(ready, token)
while process.poll() is None:
try:
receive(*messages.get(timeout=min(0.1, idle_timeout / 10)))
for pending in range(128):
receive(*messages.get_nowait())
except queue.Empty:
pass
if process.poll() is not None:
break
action = watch.action(time.monotonic())
if action == 'request_stop':
_atomic_text(stop, token)
_publish_progress(progress_path, watch.snapshot())
elif action == 'unresponsive':
raise subprocess.TimeoutExpired(command, idle_timeout * 2)
drain_deadline = time.monotonic() + 5
while (any(thread.is_alive() for thread in threads) or not messages.empty()) and time.monotonic() < drain_deadline:
try:
receive(*messages.get(timeout=0.05))
except queue.Empty:
pass
_publish_progress(progress_path, watch.snapshot())
return subprocess.CompletedProcess(command, process.returncode, _decode(output[0]), _decode(output[1]))
except Exception as error:
if process is not None:
failures = owned.stop_workers(process)
process.wait(timeout=10)
for thread in threads:
thread.join(2)
diagnostic = watch.snapshot() | {'monitor_error': str(error), 'worker_cleanup_notes': failures}
try:
_atomic_text(progress_path, json.dumps(diagnostic, ensure_ascii=False))
except OSError:
pass
if isinstance(error, subprocess.TimeoutExpired):
raise
raise WorkerMonitorError(f'Worker monitoring failed after launch; execution requires reconciliation: {error}') from error
raise
finally:
stop_readers.set()
for thread in threads:
thread.join(0.2)
owned.close()