loom-workflow 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- loom/__init__.py +25 -0
- loom/agent/__init__.py +17 -0
- loom/agent/loop.py +129 -0
- loom/agent/provider.py +70 -0
- loom/agent/task_gen.py +101 -0
- loom/core/__init__.py +18 -0
- loom/core/contract.py +103 -0
- loom/core/pipeline.py +111 -0
- loom/core/result.py +40 -0
- loom/core/task.py +34 -0
- loom/graphite/__init__.py +18 -0
- loom/graphite/match_strategy.py +110 -0
- loom/graphite/processor.py +343 -0
- loom/graphite/schema.py +201 -0
- loom/graphite/schema_constraints.py +34 -0
- loom/graphite/schema_contract.py +21 -0
- loom_workflow-0.3.0.dist-info/METADATA +221 -0
- loom_workflow-0.3.0.dist-info/RECORD +20 -0
- loom_workflow-0.3.0.dist-info/WHEEL +5 -0
- loom_workflow-0.3.0.dist-info/top_level.txt +1 -0
loom/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Loom: domain-neutral orchestration and optional graph-IR support."""
|
|
2
|
+
|
|
3
|
+
from .core import (
|
|
4
|
+
Contract,
|
|
5
|
+
ContractException,
|
|
6
|
+
ContractResult,
|
|
7
|
+
Pipeline,
|
|
8
|
+
PipelineResult,
|
|
9
|
+
Result,
|
|
10
|
+
Task,
|
|
11
|
+
TaskResult,
|
|
12
|
+
Verifier,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"Result",
|
|
17
|
+
"Task",
|
|
18
|
+
"TaskResult",
|
|
19
|
+
"Pipeline",
|
|
20
|
+
"PipelineResult",
|
|
21
|
+
"Contract",
|
|
22
|
+
"ContractException",
|
|
23
|
+
"ContractResult",
|
|
24
|
+
"Verifier",
|
|
25
|
+
]
|
loom/agent/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Restricted agent orchestration for revisable Loom tasks."""
|
|
2
|
+
|
|
3
|
+
from .provider import Provider, PydanticAIProvider
|
|
4
|
+
from .task_gen import TaskGen, TaskSource
|
|
5
|
+
from .loop import Agent, AgentContext, AgentLoop, PipelineRunner, TaskFactories
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"Agent",
|
|
9
|
+
"AgentContext",
|
|
10
|
+
"AgentLoop",
|
|
11
|
+
"PipelineRunner",
|
|
12
|
+
"Provider",
|
|
13
|
+
"PydanticAIProvider",
|
|
14
|
+
"TaskGen",
|
|
15
|
+
"TaskFactories",
|
|
16
|
+
"TaskSource",
|
|
17
|
+
]
|
loom/agent/loop.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Agent-facing pipeline execution boundaries.
|
|
2
|
+
|
|
3
|
+
This module deliberately contains no model-provider integration. An adapter
|
|
4
|
+
such as Pydantic AI can implement :class:`Agent` and use :class:`AgentContext`
|
|
5
|
+
as its dependency object.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from types import MappingProxyType
|
|
13
|
+
from typing import Any, Callable, Mapping, Protocol, Type
|
|
14
|
+
|
|
15
|
+
from ..core import Pipeline, PipelineResult, Task
|
|
16
|
+
|
|
17
|
+
TaskFactory = Callable[[Pipeline], Task]
|
|
18
|
+
TaskFactories = Mapping[str, TaskFactory]
|
|
19
|
+
class PipelineRunner:
|
|
20
|
+
"""Capability for executing a human-owned pipeline.
|
|
21
|
+
|
|
22
|
+
The pipeline factory and input factory remain private. Callers can submit
|
|
23
|
+
implementations only for the explicitly editable task names.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(self, pipeline_class: Type[Pipeline], *,
|
|
27
|
+
editable_tasks: set[str] | frozenset[str],
|
|
28
|
+
pipeline_kwargs: Mapping[str, Any] | None = None,
|
|
29
|
+
forge: Mapping[str, str | Path] | None = None,
|
|
30
|
+
input_factory: Callable[[Any], Any] | None = None):
|
|
31
|
+
if not isinstance(pipeline_class, type) or not issubclass(pipeline_class, Pipeline):
|
|
32
|
+
raise TypeError("pipeline_class must be a Pipeline subclass.")
|
|
33
|
+
self._pipeline_class = pipeline_class
|
|
34
|
+
self._pipeline_kwargs = dict(pipeline_kwargs or {})
|
|
35
|
+
self._editable_tasks = frozenset(editable_tasks)
|
|
36
|
+
paths = {
|
|
37
|
+
name: Path(path) for name, path in (forge or {}).items()
|
|
38
|
+
}
|
|
39
|
+
unknown_paths = set(paths) - self._editable_tasks
|
|
40
|
+
if unknown_paths:
|
|
41
|
+
raise ValueError(
|
|
42
|
+
f"Task paths are not editable: {sorted(unknown_paths)!r}"
|
|
43
|
+
)
|
|
44
|
+
self._forge = MappingProxyType(paths)
|
|
45
|
+
self._input_factory = input_factory or (lambda value: value)
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def editable_tasks(self) -> frozenset[str]:
|
|
49
|
+
return self._editable_tasks
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def forge(self) -> Mapping[str, Path]:
|
|
53
|
+
return self._forge
|
|
54
|
+
|
|
55
|
+
def run(self, input: Any, task_factories: TaskFactories) -> PipelineResult:
|
|
56
|
+
"""Execute with candidate implementations for editable task slots."""
|
|
57
|
+
unknown = set(task_factories) - self._editable_tasks
|
|
58
|
+
if unknown:
|
|
59
|
+
raise ValueError(f"Tasks are not editable: {sorted(unknown)!r}")
|
|
60
|
+
pipeline = self._pipeline_class(
|
|
61
|
+
task_factories=task_factories,
|
|
62
|
+
**self._pipeline_kwargs,
|
|
63
|
+
)
|
|
64
|
+
result = pipeline.execute(self._input_factory(input))
|
|
65
|
+
if not isinstance(result, PipelineResult):
|
|
66
|
+
raise TypeError("pipeline must return PipelineResult")
|
|
67
|
+
return result
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass(frozen=True)
|
|
71
|
+
class AgentContext:
|
|
72
|
+
"""Dependencies exposed to an agent implementation."""
|
|
73
|
+
|
|
74
|
+
runner: PipelineRunner
|
|
75
|
+
input: Any
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def editable_tasks(self) -> frozenset[str]:
|
|
79
|
+
return self.runner.editable_tasks
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def forge(self) -> Mapping[str, Path]:
|
|
83
|
+
return self.runner.forge
|
|
84
|
+
|
|
85
|
+
def run(self, task_factories: TaskFactories) -> PipelineResult:
|
|
86
|
+
return self.runner.run(self.input, task_factories)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class Agent(Protocol):
|
|
90
|
+
"""Protocol suitable for a Pydantic AI-backed task reviser."""
|
|
91
|
+
|
|
92
|
+
def initial_tasks(self, context: AgentContext) -> TaskFactories:
|
|
93
|
+
...
|
|
94
|
+
|
|
95
|
+
def revise_tasks(self, context: AgentContext, *,
|
|
96
|
+
failure: Exception) -> TaskFactories:
|
|
97
|
+
...
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class AgentLoop:
|
|
101
|
+
"""Run candidate task implementations until the pipeline succeeds."""
|
|
102
|
+
|
|
103
|
+
def __init__(self, runner: PipelineRunner, *, max_attempts: int = 10):
|
|
104
|
+
if not isinstance(max_attempts, int) or isinstance(max_attempts, bool) \
|
|
105
|
+
or max_attempts <= 0:
|
|
106
|
+
raise ValueError("max_attempts must be a positive integer.")
|
|
107
|
+
self.runner = runner
|
|
108
|
+
self.max_attempts = max_attempts
|
|
109
|
+
|
|
110
|
+
def run(self, input: Any, agent: Agent) -> PipelineResult:
|
|
111
|
+
context = AgentContext(self.runner, input)
|
|
112
|
+
task_factories = agent.initial_tasks(context)
|
|
113
|
+
last_failure: Exception | None = None
|
|
114
|
+
|
|
115
|
+
for _ in range(self.max_attempts):
|
|
116
|
+
try:
|
|
117
|
+
return context.run(task_factories)
|
|
118
|
+
except Exception as failure:
|
|
119
|
+
# ContractException carries the PipelineResult and contract
|
|
120
|
+
# results; other exceptions are task/runtime errors.
|
|
121
|
+
last_failure = failure
|
|
122
|
+
task_factories = agent.revise_tasks(
|
|
123
|
+
context, failure=failure
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
raise RuntimeError(
|
|
127
|
+
f"agent loop exceeded max_attempts ({self.max_attempts}); "
|
|
128
|
+
f"last failure: {last_failure}"
|
|
129
|
+
) from last_failure
|
loom/agent/provider.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Provider abstractions for model-backed Loom agents."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from typing import Type
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Provider(ABC):
|
|
12
|
+
"""Generic interface for communicating with a language model."""
|
|
13
|
+
|
|
14
|
+
@abstractmethod
|
|
15
|
+
def generate(self, prompt: str, output_type: Type[BaseModel]) -> BaseModel:
|
|
16
|
+
"""Generate one structured response for ``prompt``."""
|
|
17
|
+
pass
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class PydanticAIProvider(Provider):
|
|
21
|
+
"""Provider backed by Pydantic AI.
|
|
22
|
+
|
|
23
|
+
Model identifiers and provider-specific routing are kept here so callers
|
|
24
|
+
such as :class:`~loom.agent.task_gen.TaskGen` need only use ``generate``.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, *, provider: str, model: str):
|
|
28
|
+
if not isinstance(provider, str) or not provider.strip():
|
|
29
|
+
raise ValueError("provider must be a non-empty string.")
|
|
30
|
+
if not isinstance(model, str) or not model.strip():
|
|
31
|
+
raise ValueError("model must be a non-empty string.")
|
|
32
|
+
self.provider = provider.strip().lower()
|
|
33
|
+
self.model = model.strip()
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def model_name(self) -> str:
|
|
37
|
+
"""Return the Pydantic AI model identifier for this configuration."""
|
|
38
|
+
prefixes = {
|
|
39
|
+
"openai": "openai-responses",
|
|
40
|
+
"claude": "anthropic",
|
|
41
|
+
"anthropic": "anthropic",
|
|
42
|
+
}
|
|
43
|
+
try:
|
|
44
|
+
prefix = prefixes[self.provider]
|
|
45
|
+
except KeyError as error:
|
|
46
|
+
raise ValueError(
|
|
47
|
+
f"Unsupported Pydantic AI provider {self.provider!r}."
|
|
48
|
+
) from error
|
|
49
|
+
return f"{prefix}:{self.model}"
|
|
50
|
+
|
|
51
|
+
def generate(self, prompt: str, output_type: Type[BaseModel]) -> BaseModel:
|
|
52
|
+
try:
|
|
53
|
+
from pydantic_ai import Agent
|
|
54
|
+
except ImportError as error:
|
|
55
|
+
raise ImportError(
|
|
56
|
+
"PydanticAIProvider requires Pydantic AI. Install it with "
|
|
57
|
+
"`pip install loom[agent]`."
|
|
58
|
+
) from error
|
|
59
|
+
|
|
60
|
+
agent = Agent(
|
|
61
|
+
self.model_name,
|
|
62
|
+
output_type=output_type,
|
|
63
|
+
system_prompt=(
|
|
64
|
+
"You write one complete Python Task module for Loom. "
|
|
65
|
+
"Return only the structured response. The task must use its "
|
|
66
|
+
"supplied pipeline constructor argument, preserve its assigned "
|
|
67
|
+
"task name, and modify no files itself."
|
|
68
|
+
),
|
|
69
|
+
)
|
|
70
|
+
return agent.run_sync(prompt).output
|
loom/agent/task_gen.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Model-backed generation of editable Loom task modules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib.util
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Iterable
|
|
8
|
+
from uuid import uuid4
|
|
9
|
+
|
|
10
|
+
from pydantic import BaseModel, Field
|
|
11
|
+
|
|
12
|
+
from ..core import ContractException, Pipeline, Task
|
|
13
|
+
from .loop import AgentContext, TaskFactories, TaskFactory
|
|
14
|
+
from .provider import Provider
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class TaskSource(BaseModel):
|
|
18
|
+
"""One complete task module produced by a model."""
|
|
19
|
+
|
|
20
|
+
class_name: str = Field(description="Name of the Task subclass in source.")
|
|
21
|
+
source: str = Field(description="Complete Python module, without Markdown fences.")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class TaskGen:
|
|
25
|
+
"""Generate selected task implementations through a generic provider."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, *, provider: Provider, tasks: Iterable[str]):
|
|
28
|
+
if not isinstance(provider, Provider):
|
|
29
|
+
raise TypeError("provider must be a Provider instance.")
|
|
30
|
+
self.provider = provider
|
|
31
|
+
self.tasks = frozenset(tasks)
|
|
32
|
+
if not self.tasks:
|
|
33
|
+
raise ValueError("tasks must contain at least one task name.")
|
|
34
|
+
|
|
35
|
+
def initial_tasks(self, context: AgentContext) -> TaskFactories:
|
|
36
|
+
return self.build_tasks(context)
|
|
37
|
+
|
|
38
|
+
def revise_tasks(self, context: AgentContext, *,
|
|
39
|
+
failure: Exception) -> TaskFactories:
|
|
40
|
+
return self.build_tasks(context, failure=failure)
|
|
41
|
+
|
|
42
|
+
def build_tasks(self, context: AgentContext, *,
|
|
43
|
+
failure: Exception | None = None) -> TaskFactories:
|
|
44
|
+
selected = self._selected_paths(context)
|
|
45
|
+
factories: dict[str, TaskFactory] = {}
|
|
46
|
+
for name, path in selected.items():
|
|
47
|
+
current_source = path.read_text(encoding="utf-8") if path.exists() else ""
|
|
48
|
+
proposal = self.provider.generate(
|
|
49
|
+
self._prompt(name, current_source, failure), TaskSource
|
|
50
|
+
)
|
|
51
|
+
if not isinstance(proposal, TaskSource):
|
|
52
|
+
raise TypeError("provider returned an invalid task source.")
|
|
53
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
54
|
+
path.write_text(proposal.source, encoding="utf-8")
|
|
55
|
+
factories[name] = self._factory(path, proposal.class_name)
|
|
56
|
+
return factories
|
|
57
|
+
|
|
58
|
+
def _selected_paths(self, context: AgentContext) -> dict[str, Path]:
|
|
59
|
+
unknown = self.tasks - context.editable_tasks
|
|
60
|
+
if unknown:
|
|
61
|
+
raise ValueError(f"Tasks are not editable: {sorted(unknown)!r}")
|
|
62
|
+
missing = self.tasks - set(context.forge)
|
|
63
|
+
if missing:
|
|
64
|
+
raise KeyError(f"Tasks have no forge path: {sorted(missing)!r}")
|
|
65
|
+
return {name: context.forge[name] for name in self.tasks}
|
|
66
|
+
|
|
67
|
+
@staticmethod
|
|
68
|
+
def _prompt(name: str, source: str, failure: Exception | None) -> str:
|
|
69
|
+
feedback = "No execution feedback is available yet."
|
|
70
|
+
if isinstance(failure, ContractException):
|
|
71
|
+
feedback = "Contract failures:\n" + "\n".join(
|
|
72
|
+
f"- {contract}: {result.failures}"
|
|
73
|
+
for contract, result in failure.failures.items()
|
|
74
|
+
)
|
|
75
|
+
elif failure is not None:
|
|
76
|
+
feedback = f"Task/runtime exception: {type(failure).__name__}: {failure}"
|
|
77
|
+
return (
|
|
78
|
+
f"Editable task name: {name}\n\n"
|
|
79
|
+
f"Current forge module:\n```python\n{source}\n```\n\n"
|
|
80
|
+
f"Execution feedback:\n{feedback}\n\n"
|
|
81
|
+
"Return a complete replacement module. Do not use Markdown fences "
|
|
82
|
+
"inside the source field."
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
@staticmethod
|
|
86
|
+
def _factory(path: Path, class_name: str) -> TaskFactory:
|
|
87
|
+
def factory(pipeline: Pipeline) -> Task:
|
|
88
|
+
module_name = f"loom_forge_{path.stem}_{uuid4().hex}"
|
|
89
|
+
spec = importlib.util.spec_from_file_location(module_name, path)
|
|
90
|
+
if spec is None or spec.loader is None:
|
|
91
|
+
raise ImportError(f"Cannot load task module from {path}")
|
|
92
|
+
module = importlib.util.module_from_spec(spec)
|
|
93
|
+
spec.loader.exec_module(module)
|
|
94
|
+
task_type = getattr(module, class_name)
|
|
95
|
+
task = task_type(pipeline)
|
|
96
|
+
if not isinstance(task, Task):
|
|
97
|
+
raise TypeError(
|
|
98
|
+
f"{class_name!r} from {path} did not create a Task instance."
|
|
99
|
+
)
|
|
100
|
+
return task
|
|
101
|
+
return factory
|
loom/core/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Domain-neutral task orchestration and verification."""
|
|
2
|
+
|
|
3
|
+
from .result import PipelineResult, Result, TaskResult
|
|
4
|
+
from .task import Task
|
|
5
|
+
from .pipeline import Pipeline
|
|
6
|
+
from .contract import Contract, ContractException, ContractResult, Verifier
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"Result",
|
|
10
|
+
"TaskResult",
|
|
11
|
+
"PipelineResult",
|
|
12
|
+
"Task",
|
|
13
|
+
"Pipeline",
|
|
14
|
+
"Contract",
|
|
15
|
+
"ContractException",
|
|
16
|
+
"ContractResult",
|
|
17
|
+
"Verifier",
|
|
18
|
+
]
|
loom/core/contract.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Contracts for verifying execution results."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any, Iterable
|
|
8
|
+
|
|
9
|
+
from .result import Result
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ContractException(Exception):
|
|
13
|
+
"""Raised when a contract rejects an execution result."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, result: Result,
|
|
16
|
+
contract_results: dict[str, ContractResult]):
|
|
17
|
+
self.result = result
|
|
18
|
+
self.contract_results = contract_results
|
|
19
|
+
self.failures = {
|
|
20
|
+
name: contract_result
|
|
21
|
+
for name, contract_result in contract_results.items()
|
|
22
|
+
if not contract_result.passed
|
|
23
|
+
}
|
|
24
|
+
super().__init__(
|
|
25
|
+
f"{len(self.failures)} contract(s) failed: "
|
|
26
|
+
f"{list(self.failures)}"
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class ContractResult:
|
|
32
|
+
"""Result of verifying one execution result."""
|
|
33
|
+
|
|
34
|
+
passed: bool
|
|
35
|
+
output: Any = None
|
|
36
|
+
failures: list[Any] = field(default_factory=list)
|
|
37
|
+
metrics: dict[str, Any] = field(default_factory=dict)
|
|
38
|
+
|
|
39
|
+
def __post_init__(self) -> None:
|
|
40
|
+
if type(self.passed) is not bool:
|
|
41
|
+
raise TypeError(
|
|
42
|
+
"ContractResult.passed must be an actual bool, "
|
|
43
|
+
f"got {type(self.passed).__name__}."
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Contract(ABC):
|
|
48
|
+
"""Human-defined acceptance criteria for a Task or Pipeline result."""
|
|
49
|
+
|
|
50
|
+
def __init__(
|
|
51
|
+
self,
|
|
52
|
+
*,
|
|
53
|
+
name: str,
|
|
54
|
+
):
|
|
55
|
+
if not name:
|
|
56
|
+
raise ValueError("Contract must have a name.")
|
|
57
|
+
self.name = name
|
|
58
|
+
|
|
59
|
+
def verify(self, result: Result) -> ContractResult:
|
|
60
|
+
"""Evaluate one explicit execution result."""
|
|
61
|
+
if not isinstance(result, Result):
|
|
62
|
+
raise TypeError("Contract.verify() requires a Result instance.")
|
|
63
|
+
contract_result = self.evaluate(result)
|
|
64
|
+
if not isinstance(contract_result, ContractResult):
|
|
65
|
+
raise RuntimeError(
|
|
66
|
+
f"contract {self.name} returned {type(contract_result).__name__}; "
|
|
67
|
+
"Contract.evaluate() must return ContractResult"
|
|
68
|
+
)
|
|
69
|
+
return contract_result
|
|
70
|
+
|
|
71
|
+
@abstractmethod
|
|
72
|
+
def evaluate(self, result: Result) -> ContractResult:
|
|
73
|
+
"""Evaluate one explicit TaskResult or PipelineResult."""
|
|
74
|
+
pass
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class Verifier:
|
|
78
|
+
"""Run every Contract and aggregate the individual results."""
|
|
79
|
+
|
|
80
|
+
def __init__(self, contracts: Iterable[Contract]):
|
|
81
|
+
self.contracts = list(contracts)
|
|
82
|
+
if not all(isinstance(contract, Contract) for contract in self.contracts):
|
|
83
|
+
raise TypeError("contracts must contain only Contract instances.")
|
|
84
|
+
|
|
85
|
+
def verify(self, result: Result) -> dict[str, ContractResult]:
|
|
86
|
+
"""Run all contracts, retaining failures from each contract."""
|
|
87
|
+
results: dict[str, ContractResult] = {}
|
|
88
|
+
for contract in self.contracts:
|
|
89
|
+
try:
|
|
90
|
+
results[contract.name] = contract.verify(result)
|
|
91
|
+
except Exception as error:
|
|
92
|
+
results[contract.name] = ContractResult(
|
|
93
|
+
passed=False,
|
|
94
|
+
failures=[f"{type(error).__name__}: {error}"],
|
|
95
|
+
)
|
|
96
|
+
if not self.passed(results):
|
|
97
|
+
raise ContractException(result, results)
|
|
98
|
+
return results
|
|
99
|
+
|
|
100
|
+
@staticmethod
|
|
101
|
+
def passed(results: dict[str, ContractResult]) -> bool:
|
|
102
|
+
"""Return whether every Contract passed."""
|
|
103
|
+
return all(result.passed for result in results.values())
|
loom/core/pipeline.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Pipeline abstractions for composing Tasks with custom Python logic."""
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from typing import Any, Callable, Optional
|
|
5
|
+
|
|
6
|
+
from .result import PipelineResult, TaskResult
|
|
7
|
+
from .task import Task
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Pipeline(ABC):
|
|
11
|
+
"""Abstract, stateless orchestration of Tasks."""
|
|
12
|
+
|
|
13
|
+
name: str
|
|
14
|
+
description: Optional[str] = None
|
|
15
|
+
|
|
16
|
+
def __init__(self, *, name: str, description: str | None = None,
|
|
17
|
+
max_iterations: int = 1000,
|
|
18
|
+
task_factories: dict[str, Callable[["Pipeline"], Task]] | None = None):
|
|
19
|
+
if not name:
|
|
20
|
+
raise ValueError("Pipeline must have a name.")
|
|
21
|
+
self.name = name
|
|
22
|
+
self.description = description
|
|
23
|
+
self._tasks: dict[str, Task] = {}
|
|
24
|
+
self.task_factories = dict(self.builtin_task_factories())
|
|
25
|
+
if task_factories:
|
|
26
|
+
self.task_factories.update(task_factories)
|
|
27
|
+
if not isinstance(max_iterations, int) or isinstance(max_iterations, bool) \
|
|
28
|
+
or max_iterations <= 0:
|
|
29
|
+
raise ValueError("max_iterations must be a positive integer.")
|
|
30
|
+
self.max_iterations = max_iterations
|
|
31
|
+
|
|
32
|
+
def builtin_task_factories(self) -> dict[str, Callable[["Pipeline"], Task]]:
|
|
33
|
+
"""Return the pipeline's default task factories."""
|
|
34
|
+
return {}
|
|
35
|
+
|
|
36
|
+
def register(self, name: str) -> Task:
|
|
37
|
+
"""Construct and register the task selected by ``name``."""
|
|
38
|
+
if name not in self.task_factories:
|
|
39
|
+
raise KeyError(f"No task factory registered for {name!r}.")
|
|
40
|
+
task = self.task_factories[name](self)
|
|
41
|
+
if not isinstance(task, Task):
|
|
42
|
+
raise TypeError(
|
|
43
|
+
f"Task factory {name!r} returned {type(task).__name__}; "
|
|
44
|
+
"task factories must return Task instances."
|
|
45
|
+
)
|
|
46
|
+
if task.name != name.strip().lower():
|
|
47
|
+
raise ValueError(
|
|
48
|
+
f"Task factory {name!r} created task named {task.name!r}."
|
|
49
|
+
)
|
|
50
|
+
return task
|
|
51
|
+
|
|
52
|
+
def _register_task(self, task: Task) -> None:
|
|
53
|
+
"""Register one task instance, rejecting duplicate task names."""
|
|
54
|
+
if not isinstance(task, Task):
|
|
55
|
+
raise TypeError("pipeline tasks must be Task instances.")
|
|
56
|
+
if task.name in self._tasks:
|
|
57
|
+
raise ValueError(
|
|
58
|
+
f"Pipeline {self.name!r} already has a task named {task.name!r}."
|
|
59
|
+
)
|
|
60
|
+
self._tasks[task.name] = task
|
|
61
|
+
|
|
62
|
+
@abstractmethod
|
|
63
|
+
def execute(self, input: Any) -> PipelineResult:
|
|
64
|
+
"""Run the pipeline's custom orchestration."""
|
|
65
|
+
pass
|
|
66
|
+
|
|
67
|
+
def __call__(self, input: Any) -> PipelineResult:
|
|
68
|
+
return self.execute(input)
|
|
69
|
+
|
|
70
|
+
def repeat(self, task: Task, value: Any, *,
|
|
71
|
+
max_iterations: int | None = None) -> TaskResult:
|
|
72
|
+
"""Run one Task repeatedly until it reports no modification."""
|
|
73
|
+
if not isinstance(task, Task):
|
|
74
|
+
raise TypeError("repeat() requires a Task instance.")
|
|
75
|
+
limit = self.max_iterations if max_iterations is None else max_iterations
|
|
76
|
+
if not isinstance(limit, int) or isinstance(limit, bool) or limit <= 0:
|
|
77
|
+
raise ValueError("max_iterations must be a positive integer.")
|
|
78
|
+
|
|
79
|
+
results: list[TaskResult] = []
|
|
80
|
+
ever_modified = False
|
|
81
|
+
for iteration in range(1, limit + 1):
|
|
82
|
+
result = task.execute(value)
|
|
83
|
+
if not isinstance(result, TaskResult):
|
|
84
|
+
raise RuntimeError(
|
|
85
|
+
f"task {task.name} returned {type(result).__name__}; "
|
|
86
|
+
"Task.execute() must return TaskResult"
|
|
87
|
+
)
|
|
88
|
+
results.append(result)
|
|
89
|
+
ever_modified |= result.modified
|
|
90
|
+
if not result.modified:
|
|
91
|
+
return TaskResult(
|
|
92
|
+
output=result.output,
|
|
93
|
+
modified=ever_modified,
|
|
94
|
+
metadata={
|
|
95
|
+
**result.metadata,
|
|
96
|
+
"iterations": iteration,
|
|
97
|
+
"converged": True,
|
|
98
|
+
"iteration_results": results,
|
|
99
|
+
},
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
return TaskResult(
|
|
103
|
+
output=results[-1].output,
|
|
104
|
+
modified=ever_modified,
|
|
105
|
+
metadata={
|
|
106
|
+
**results[-1].metadata,
|
|
107
|
+
"iterations": limit,
|
|
108
|
+
"converged": False,
|
|
109
|
+
"iteration_results": results,
|
|
110
|
+
},
|
|
111
|
+
)
|
loom/core/result.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Shared result types for Loom execution boundaries."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class Result:
|
|
11
|
+
"""Domain-neutral result produced by a Task or Pipeline."""
|
|
12
|
+
|
|
13
|
+
output: Any = None
|
|
14
|
+
modified: bool = False
|
|
15
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
16
|
+
|
|
17
|
+
def __post_init__(self) -> None:
|
|
18
|
+
if type(self.modified) is not bool:
|
|
19
|
+
raise TypeError(
|
|
20
|
+
"Result.modified must be an actual bool, "
|
|
21
|
+
f"got {type(self.modified).__name__}."
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class TaskResult(Result):
|
|
27
|
+
"""Result produced by one Task execution."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class PipelineResult(Result):
|
|
32
|
+
"""Result produced by one Pipeline execution."""
|
|
33
|
+
|
|
34
|
+
task_results: dict[str, TaskResult] = field(default_factory=dict)
|
|
35
|
+
|
|
36
|
+
def __post_init__(self) -> None:
|
|
37
|
+
super().__post_init__()
|
|
38
|
+
if not all(isinstance(result, TaskResult)
|
|
39
|
+
for result in self.task_results.values()):
|
|
40
|
+
raise TypeError("PipelineResult.task_results must contain TaskResult values.")
|
loom/core/task.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Task abstractions."""
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from typing import Any, Optional, TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
from .result import TaskResult
|
|
7
|
+
|
|
8
|
+
if TYPE_CHECKING:
|
|
9
|
+
from .pipeline import Pipeline
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Task(ABC):
|
|
13
|
+
"""Abstract, stateless unit of domain work."""
|
|
14
|
+
|
|
15
|
+
name: str
|
|
16
|
+
description: Optional[str] = None
|
|
17
|
+
|
|
18
|
+
def __init__(self, pipeline: "Pipeline", *, name: str | None = None,
|
|
19
|
+
description: str | None = None):
|
|
20
|
+
resolved_name = name or self.__class__.__name__
|
|
21
|
+
if not isinstance(resolved_name, str) or not resolved_name.strip():
|
|
22
|
+
raise ValueError("Task name must be a non-empty string.")
|
|
23
|
+
self.name = resolved_name.strip().lower()
|
|
24
|
+
self.description = description
|
|
25
|
+
self.pipeline = pipeline
|
|
26
|
+
pipeline._register_task(self)
|
|
27
|
+
|
|
28
|
+
@abstractmethod
|
|
29
|
+
def execute(self, input: Any) -> TaskResult:
|
|
30
|
+
"""Run the task's execution strategy."""
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
def __call__(self, input: Any) -> TaskResult:
|
|
34
|
+
return self.execute(input)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Graph-IR schemas, matching, and rewriting built on Heterograph."""
|
|
2
|
+
|
|
3
|
+
from .processor import GraphProcessor
|
|
4
|
+
from .match_strategy import DfsMatchStrategy, IsoMatchStrategy, MatchStrategy
|
|
5
|
+
from .schema import GraphSchema, Issue, Severity, ValidationReport
|
|
6
|
+
from .schema_contract import GraphSchemaContract
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"GraphProcessor",
|
|
10
|
+
"MatchStrategy",
|
|
11
|
+
"IsoMatchStrategy",
|
|
12
|
+
"DfsMatchStrategy",
|
|
13
|
+
"GraphSchema",
|
|
14
|
+
"Issue",
|
|
15
|
+
"Severity",
|
|
16
|
+
"ValidationReport",
|
|
17
|
+
"GraphSchemaContract",
|
|
18
|
+
]
|