henosis-engine 0.1.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.
Files changed (140) hide show
  1. henosis/__init__.py +11 -0
  2. henosis/_examples/cooper_basin/README.md +138 -0
  3. henosis/_examples/cooper_basin/components/deferment_attribution.py +132 -0
  4. henosis/_examples/cooper_basin/components/maintenance_schedule.py +292 -0
  5. henosis/_examples/cooper_basin/components/production_allocation.py +104 -0
  6. henosis/_examples/cooper_basin/components/schedule_dispatch.py +89 -0
  7. henosis/_examples/cooper_basin/components/work_order_dispatch.py +162 -0
  8. henosis/_examples/cooper_basin/glb_gen.py +156 -0
  9. henosis/_examples/cooper_basin/henosis.yaml +36 -0
  10. henosis/_examples/cooper_basin/legacy_fixtures.yaml +11752 -0
  11. henosis/_examples/cooper_basin/models/actions.yaml +20 -0
  12. henosis/_examples/cooper_basin/models/activity.yaml +92 -0
  13. henosis/_examples/cooper_basin/models/basin.yaml +58 -0
  14. henosis/_examples/cooper_basin/models/completed_intervention.yaml +56 -0
  15. henosis/_examples/cooper_basin/models/compressor.yaml +86 -0
  16. henosis/_examples/cooper_basin/models/crew.yaml +29 -0
  17. henosis/_examples/cooper_basin/models/defect.yaml +53 -0
  18. henosis/_examples/cooper_basin/models/field.yaml +101 -0
  19. henosis/_examples/cooper_basin/models/formation.yaml +29 -0
  20. henosis/_examples/cooper_basin/models/licence.yaml +54 -0
  21. henosis/_examples/cooper_basin/models/maintenance_strategy.yaml +31 -0
  22. henosis/_examples/cooper_basin/models/operator.yaml +15 -0
  23. henosis/_examples/cooper_basin/models/pipeline.yaml +107 -0
  24. henosis/_examples/cooper_basin/models/planned_intervention.yaml +54 -0
  25. henosis/_examples/cooper_basin/models/plant.yaml +77 -0
  26. henosis/_examples/cooper_basin/models/well.yaml +258 -0
  27. henosis/_examples/cooper_basin/models/well_event.yaml +36 -0
  28. henosis/_examples/cooper_basin/models/work_order.yaml +61 -0
  29. henosis/_examples/cooper_basin/seed_demo.py +554 -0
  30. henosis/_examples/energy_distributor/README.md +131 -0
  31. henosis/_examples/energy_distributor/components/work_order_dispatch.py +146 -0
  32. henosis/_examples/energy_distributor/glb_gen.py +165 -0
  33. henosis/_examples/energy_distributor/henosis.yaml +29 -0
  34. henosis/_examples/energy_distributor/models/actions.yaml +20 -0
  35. henosis/_examples/energy_distributor/models/connection_point.yaml +50 -0
  36. henosis/_examples/energy_distributor/models/defect.yaml +50 -0
  37. henosis/_examples/energy_distributor/models/distribution_transformer.yaml +92 -0
  38. henosis/_examples/energy_distributor/models/feeder.yaml +144 -0
  39. henosis/_examples/energy_distributor/models/operator.yaml +19 -0
  40. henosis/_examples/energy_distributor/models/outage.yaml +53 -0
  41. henosis/_examples/energy_distributor/models/service_area.yaml +50 -0
  42. henosis/_examples/energy_distributor/models/transformer.yaml +139 -0
  43. henosis/_examples/energy_distributor/models/work_order.yaml +57 -0
  44. henosis/_examples/energy_distributor/models/zone_substation.yaml +89 -0
  45. henosis/_examples/energy_distributor/seed_demo.py +935 -0
  46. henosis/cli/__init__.py +1 -0
  47. henosis/cli/cmd_compile.py +65 -0
  48. henosis/cli/cmd_explorer.py +23 -0
  49. henosis/cli/cmd_export.py +83 -0
  50. henosis/cli/cmd_graph.py +25 -0
  51. henosis/cli/cmd_init.py +134 -0
  52. henosis/cli/cmd_serve.py +46 -0
  53. henosis/cli/cmd_sync.py +49 -0
  54. henosis/cli/cmd_validate.py +41 -0
  55. henosis/cli/main.py +61 -0
  56. henosis/cli/progress.py +105 -0
  57. henosis/components/__init__.py +48 -0
  58. henosis/components/component_runner.py +49 -0
  59. henosis/components/contract.py +203 -0
  60. henosis/components/launcher.py +118 -0
  61. henosis/components/registry.py +93 -0
  62. henosis/connectors/__init__.py +1 -0
  63. henosis/connectors/attach/__init__.py +47 -0
  64. henosis/connectors/attach/_common.py +20 -0
  65. henosis/connectors/attach/file_glob.py +45 -0
  66. henosis/connectors/attach/mysql.py +45 -0
  67. henosis/connectors/attach/ogr.py +67 -0
  68. henosis/connectors/attach/postgres.py +45 -0
  69. henosis/connectors/attach/snowflake.py +301 -0
  70. henosis/connectors/attach/sqlite.py +36 -0
  71. henosis/connectors/attach_base.py +332 -0
  72. henosis/connectors/documents.py +62 -0
  73. henosis/connectors/duckdb_ext.py +83 -0
  74. henosis/connectors/fallback_base.py +165 -0
  75. henosis/connectors/pi_web_api.py +224 -0
  76. henosis/connectors/registry.py +197 -0
  77. henosis/connectors/rest.py +324 -0
  78. henosis/engine/__init__.py +3 -0
  79. henosis/engine/engine.py +1792 -0
  80. henosis/engine/mapper.py +79 -0
  81. henosis/engine/planner.py +861 -0
  82. henosis/engine/selection.py +607 -0
  83. henosis/engine/session.py +45 -0
  84. henosis/engine/types.py +364 -0
  85. henosis/explorer/__init__.py +0 -0
  86. henosis/explorer/router.py +41 -0
  87. henosis/explorer/static/assets/main.css +281 -0
  88. henosis/explorer/static/assets/main.js +979 -0
  89. henosis/explorer/static/index.html +108 -0
  90. henosis/graph/__init__.py +7 -0
  91. henosis/graph/store.py +92 -0
  92. henosis/graph/sync.py +183 -0
  93. henosis/ontology/__init__.py +1 -0
  94. henosis/ontology/compiler.py +401 -0
  95. henosis/ontology/loader.py +156 -0
  96. henosis/ontology/models.py +980 -0
  97. henosis/ontology/owl_export.py +328 -0
  98. henosis/ontology/probe.py +303 -0
  99. henosis/ontology/schema_gen.py +26 -0
  100. henosis/ontology/store.py +1055 -0
  101. henosis/ontology/validator.py +752 -0
  102. henosis/scaffold/__init__.py +26 -0
  103. henosis/scaffold/catalog.py +90 -0
  104. henosis/scaffold/templates.py +76 -0
  105. henosis/security/__init__.py +1 -0
  106. henosis/security/backends/__init__.py +1 -0
  107. henosis/security/backends/base.py +24 -0
  108. henosis/security/backends/env.py +25 -0
  109. henosis/security/backends/snowflake.py +44 -0
  110. henosis/security/backends/vault.py +10 -0
  111. henosis/security/credentials.py +40 -0
  112. henosis/serving/__init__.py +1 -0
  113. henosis/serving/api/__init__.py +0 -0
  114. henosis/serving/api/app.py +97 -0
  115. henosis/serving/api/contract.py +55 -0
  116. henosis/serving/api/deps.py +54 -0
  117. henosis/serving/api/routes/__init__.py +0 -0
  118. henosis/serving/api/routes/actions.py +82 -0
  119. henosis/serving/api/routes/connections.py +31 -0
  120. henosis/serving/api/routes/documents.py +41 -0
  121. henosis/serving/api/routes/entities.py +80 -0
  122. henosis/serving/api/routes/graph.py +33 -0
  123. henosis/serving/api/routes/health.py +15 -0
  124. henosis/serving/api/routes/observations.py +43 -0
  125. henosis/serving/api/routes/ontology.py +25 -0
  126. henosis/serving/api/routes/project.py +40 -0
  127. henosis/serving/api/routes/relationships.py +56 -0
  128. henosis/serving/api/routes/search.py +34 -0
  129. henosis/serving/api/routes/select.py +43 -0
  130. henosis/serving/locking.py +20 -0
  131. henosis/serving/mcp/__init__.py +1 -0
  132. henosis/serving/mcp/formats.py +136 -0
  133. henosis/serving/mcp/handlers.py +541 -0
  134. henosis/serving/mcp/instrumentation.py +80 -0
  135. henosis/serving/mcp/server.py +523 -0
  136. henosis_engine-0.1.0.dist-info/METADATA +255 -0
  137. henosis_engine-0.1.0.dist-info/RECORD +140 -0
  138. henosis_engine-0.1.0.dist-info/WHEEL +4 -0
  139. henosis_engine-0.1.0.dist-info/entry_points.txt +3 -0
  140. henosis_engine-0.1.0.dist-info/licenses/LICENSE +21 -0
henosis/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ """henosis — an open-source asset intelligence context framework."""
2
+
3
+ from importlib.metadata import PackageNotFoundError
4
+ from importlib.metadata import version as _distribution_version
5
+
6
+ try:
7
+ __version__ = _distribution_version("henosis-engine")
8
+ except PackageNotFoundError: # pragma: no cover - a source tree with no install
9
+ __version__ = "0+unknown"
10
+
11
+ __all__ = ["__version__"]
@@ -0,0 +1,138 @@
1
+ # Cooper Basin — upstream gas operation
2
+
3
+ A synthetic gas field you can interrogate: wells flowing through gathering
4
+ pipelines into a processing plant, with defects, work orders and a maintenance
5
+ schedule on top. Geography is modelled on real Cooper Basin licence areas;
6
+ every operational value is generated.
7
+
8
+ It exists to show the point of henosis — the asset register, the historian and
9
+ the maintenance system stay where they are, and you ask questions **across**
10
+ them. Nothing here is copied into henosis; it reads from a SQLite registry, a
11
+ folder of Parquet telemetry and a document store at query time.
12
+
13
+ If you are new to henosis, start here, then look at
14
+ `../energy_distributor/` for the same machinery in a different industry.
15
+
16
+ ## Run it
17
+
18
+ Needs henosis installed (`uv sync` or `pip install -e .` from the repo root).
19
+
20
+ ```bash
21
+ python seed_demo.py # build the source systems, compile, run actions, index the graph
22
+ henosis serve --mcp # REST + MCP on http://127.0.0.1:8000
23
+ henosis explorer # or: the built-in browser UI
24
+ ```
25
+
26
+ `seed_demo.py` takes ~25s and is safe to re-run — it rebuilds everything from
27
+ scratch. With `serve --mcp` running, point an agent at
28
+ `http://127.0.0.1:8000/mcp` and ask the questions below in plain English.
29
+
30
+ ## What you can ask it
31
+
32
+ There is one story running end to end: **a pipeline is constrained, so wells
33
+ behind it are shut in, so that becomes work.** Each step is a real call — the
34
+ outputs below are from an actual run.
35
+
36
+ **"Which gathering segments are running over capacity?"**
37
+
38
+ ```python
39
+ select("entity.type == 'Pipeline'",
40
+ project={"ratio": "derived(entity, 'constraint_ratio')"},
41
+ order_by="ratio", descending=True, limit=5)
42
+ ```
43
+
44
+ > `Gidgealpa to Moomba Trunkline` 1.10 · `Gidgealpa 35 Flowline` 1.06 ·
45
+ > `Moomba 12 Flowline` 1.01 …
46
+
47
+ `constraint_ratio` is not stored anywhere. It is declared on `Pipeline` as
48
+ latest `inlet_pressure` (from the Parquet historian) over `mawp_kpa` (from the
49
+ SQLite registry), and computed when you ask. Ask `get_type("Pipeline")` and it
50
+ will tell you that itself.
51
+
52
+ **"What's behind that trunkline?"**
53
+
54
+ ```python
55
+ traverse("pipeline:11", "feeds", direction="inbound", max_depth=3)
56
+ ```
57
+
58
+ > 8 nodes — 3 wells, 4 pipeline segments, 1 compressor
59
+
60
+ `feeds` is one relationship reused the whole way up the chain
61
+ (well → flowline → trunkline → plant), so a single traverse answers "everything
62
+ upstream of the bottleneck" without knowing the topology in advance.
63
+
64
+ **"Which wells are deferring the most gas?"**
65
+
66
+ ```python
67
+ select("entity.type == 'Well' && has_obs(entity, 'deferred_gas')",
68
+ project={"deferred": "latest(entity, 'deferred_gas')"},
69
+ order_by="deferred", descending=True, limit=5)
70
+ ```
71
+
72
+ > `Moomba 012` 273,389 m³/d · `Gidgealpa 022` 106,285 · `Gidgealpa 018` 47,251
73
+
74
+ `deferred_gas` only exists because `seed_demo.py` ran the
75
+ `run_deferment_attribution` action, which wrote to a store the
76
+ `deferment_attribution` component owns — and that store federates straight back
77
+ in as an observation on `Well`. Reads and writes use the same ontology.
78
+
79
+ **"Raise a work order for that."**
80
+
81
+ ```python
82
+ perform_action("raise_work_order", "defect:1", {"priority": "urgent"})
83
+ ```
84
+
85
+ Writes a `WorkOrder` into the store owned by the `work_order_dispatch`
86
+ component, which federates back in as an ordinary EntityType. Priority defaults
87
+ from the defect's severity if you omit it. The seed already raises one against
88
+ each of the 8 open defects, and re-raising the same defect won't duplicate it —
89
+ so to watch the count move, try a `Well` or `Pipeline` id instead.
90
+
91
+ ## What's in it
92
+
93
+ **17 EntityTypes**, every one deriving from a henosis base type:
94
+
95
+ | Base | Types |
96
+ |---|---|
97
+ | `PhysicalAsset` | `Well` (653) · `Pipeline` (389) · `Plant` · `Compressor` |
98
+ | `Location` | `Basin` · `Field` |
99
+ | `Actor` | `Operator` · `Crew` |
100
+ | `Event` | `Defect` · `WorkOrder` · `Activity` · `WellEvent` · `PlannedIntervention` · `CompletedIntervention` |
101
+ | `AbstractConcept` | `Formation` · `Licence` · `MaintenanceStrategy` |
102
+
103
+ Wells carry nine time-series properties (`gas_rate`, `water_cut`,
104
+ `tubing_head_pressure`, `deferred_gas`, …) and a derived `health_index`.
105
+
106
+ **Four source systems**, none of them henosis:
107
+
108
+ - `entities_db` — `data/entities.db`, SQLite: the asset registry.
109
+ - `scada` — `data/observations/`, Parquet: the historian.
110
+ - `doc_store` — `data/documents/`, files: a 3D wellhead model.
111
+ - `deferment_store` / `work_order_store` / `schedule_store` —
112
+ `components/*.parquet`, owned by the logic components, federated back in.
113
+
114
+ **Five actions**, covering both routed-write forms:
115
+
116
+ | Action | Subject | Form |
117
+ |---|---|---|
118
+ | `run_deferment_attribution` | `Basin` | component |
119
+ | `schedule_maintenance` | `Basin` | component |
120
+ | `dispatch_schedule` | `Basin` | component |
121
+ | `run_production_allocation` | `Field` | `execute` — SQL against `entities_db` |
122
+ | `raise_work_order` | `Well` · `Pipeline` · `Compressor` · `Defect` | component |
123
+
124
+ The `execute` form routes SQL to the source system. The `component` form calls
125
+ a Python class in `components/` that owns its own store.
126
+
127
+ ## Editing it
128
+
129
+ `legacy_fixtures.yaml` is the durable input — the wells, pipelines and licences
130
+ everything is generated from. `models/*.yaml` is the ontology. `data/`,
131
+ `.henosis/` and `components/*.parquet` are all regenerated by `seed_demo.py`
132
+ and gitignored, so change a model, re-run the seed, and ask again.
133
+
134
+ Pass `--no-actions` to seed and compile without running the actions, leaving
135
+ the component stores empty.
136
+
137
+ From an installed henosis with no checkout, `henosis init cooper-basin`
138
+ scaffolds and seeds all of this into a new directory.
@@ -0,0 +1,132 @@
1
+ """Deferment-attribution logic component (DEMO_SPEC.md §5.1) — the demo's
2
+ centrepiece question: *"how much gas are we deferring today, and where's the
3
+ bottleneck?"*
4
+
5
+ This is unanswerable by search and unanswerable by a single `select`: it needs
6
+ the physical network *and* per-well production math. The component:
7
+
8
+ 1. ranks the constrained segments (Pipeline.state.constraint_ratio ≥ a
9
+ threshold — a live inlet_pressure over mawp_kpa);
10
+ 2. for each, walks the `feeds` conveyance network INBOUND to the producing
11
+ wells behind it;
12
+ 3. attributes each well's deferment (well-test potential − actual gas_rate)
13
+ to the binding constraint — the highest-ratio segment it sits behind.
14
+
15
+ It reads everything through the read-only engine handle (`traverse`,
16
+ `get_entity`, `get_latest_observation`) and writes the result to a store it
17
+ OWNS (`deferment.parquet`), which the `deferment_store` connection federates
18
+ back in as `Well.deferred_gas`. henosis stores nothing itself (Principle I).
19
+
20
+ The network-solver app in DEMO_SPEC.md §6 is this same shape — traverse →
21
+ per-node compute → federate back — with a hydraulic solve in place of the
22
+ potential-minus-actual arithmetic.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from henosis.components import ComponentContext, ComponentResult
28
+
29
+ # Ordinary ontology names the component author knows from their own YAML.
30
+ _FEEDS_REL = "feeds"
31
+ _ACTUAL_OBS = "gas_rate"
32
+ _POTENTIAL_OBS = "test_gas_rate"
33
+ _CONSTRAINT_STATE = "constraint_ratio"
34
+ _OUTPUT_STORE = "deferment"
35
+ _DEFAULT_THRESHOLD = 1.0 # constraint_ratio ≥ 1.0 ⇒ segment at/over its mawp
36
+
37
+
38
+ def _latest(engine, entity_id: str, prop: str) -> float | None:
39
+ """Latest value of an observation, or None when the well has no such data."""
40
+ try:
41
+ obs = engine.get_latest_observation(entity_id, prop)
42
+ except Exception:
43
+ return None
44
+ if obs is None or obs.value is None:
45
+ return None
46
+ return float(obs.value)
47
+
48
+
49
+ def _constrained_segments(engine, threshold: float) -> list[dict]:
50
+ """Every pipeline segment whose live constraint_ratio ≥ threshold, ranked
51
+ most-constrained first. A segment with no mawp yields a NULL ratio and is
52
+ skipped."""
53
+ segments: list[dict] = []
54
+ for item in engine.list_entities("Pipeline", limit=1000).items:
55
+ try:
56
+ e = engine.get_entity(
57
+ "Pipeline", item.id, fields=["state.constraint_ratio", "identity.name"]
58
+ )
59
+ except Exception:
60
+ continue
61
+ ratio = (e.state or {}).get(_CONSTRAINT_STATE)
62
+ if ratio is None or float(ratio) < threshold:
63
+ continue
64
+ segments.append(
65
+ {"id": item.id, "name": (e.identity or {}).get("name"), "ratio": float(ratio)}
66
+ )
67
+ segments.sort(key=lambda s: -s["ratio"])
68
+ return segments
69
+
70
+
71
+ def _well_deferment(engine, well_id: str) -> tuple[float, float, float] | None:
72
+ """(potential, actual, deferred) for a well, or None when it has no well
73
+ test to establish an unconstrained potential."""
74
+ potential = _latest(engine, well_id, _POTENTIAL_OBS)
75
+ if potential is None:
76
+ return None
77
+ actual = _latest(engine, well_id, _ACTUAL_OBS) or 0.0
78
+ return potential, actual, potential - actual
79
+
80
+
81
+ class DefermentAttribution:
82
+ """The declared component. `run` is the whole contract."""
83
+
84
+ def run(self, ctx: ComponentContext) -> ComponentResult:
85
+ engine = ctx.open_engine() # read-only; a component may not mutate sources
86
+ production_date = str(ctx.job.params.get("production_date") or "")
87
+ threshold = float(ctx.job.params.get("constraint_threshold") or _DEFAULT_THRESHOLD)
88
+
89
+ segments = _constrained_segments(engine, threshold)
90
+
91
+ rows: list[dict] = []
92
+ claimed: set[str] = set() # a well attributes to its highest-ratio constraint
93
+ for seg in segments:
94
+ trace = engine.traverse(seg["id"], _FEEDS_REL, direction="inbound")
95
+ for node in trace.nodes:
96
+ if node.entity_type != "Well" or node.id in claimed:
97
+ continue
98
+ deferred = _well_deferment(engine, node.id)
99
+ if deferred is None:
100
+ continue
101
+ potential, actual, gap = deferred
102
+ if gap <= 0:
103
+ continue # producing at/above potential — nothing deferred
104
+ claimed.add(node.id)
105
+ raw_id = node.id.split(":", 1)[-1]
106
+ rows.append(
107
+ {
108
+ "production_date": production_date,
109
+ # Raw id as TEXT — well ids are identifiers, not ints
110
+ # (well:moomba-12), and the deferment_store federation
111
+ # joins Well.deferred_gas on this raw `well_id` column
112
+ # (well.yaml). A numeric cast makes the column mixed-type.
113
+ "well_id": raw_id,
114
+ "well": node.id,
115
+ "constraining_segment": seg["id"],
116
+ "segment_name": seg["name"],
117
+ "constraint_ratio": round(seg["ratio"], 4),
118
+ "potential_gas_m3d": round(potential, 1),
119
+ "actual_gas_m3d": round(actual, 1),
120
+ "deferred_gas_m3d": round(gap, 1),
121
+ }
122
+ )
123
+
124
+ writer = ctx.output(_OUTPUT_STORE)
125
+ writer.write(rows)
126
+ n = writer.commit()
127
+ return ComponentResult(
128
+ run_id=ctx.job.run_id,
129
+ status="completed",
130
+ output_store=_OUTPUT_STORE,
131
+ rows_written=n,
132
+ )
@@ -0,0 +1,292 @@
1
+ """Maintenance-scheduling logic component (SCHEDULING_DEMO_SPEC.md) — the
2
+ second demo arc: *"take the whole work-order backlog and build the schedule."*
3
+
4
+ This is a Primavera-P6-shaped scheduler. Where `work_order_dispatch` raises
5
+ orders one asset at a time (reactive), this turns the WHOLE backlog into a
6
+ resource-levelled activity network with a critical path — the network-solver app
7
+ of DEMO_SPEC.md §6 in its baby form. It reads three inputs no single system
8
+ holds together, then federates a schedule back:
9
+
10
+ 1. **Activities + durations** — each open WorkOrder becomes a P6 activity; its
11
+ duration comes from urgency (urgent = 2 days, else 1).
12
+ 2. **Precedence logic from the physical network** — if one order's asset is
13
+ upstream of another's on the `feeds` conveyance (`traverse(feeds, inbound)`),
14
+ the upstream activity must finish first (you fix the source before the
15
+ segment, and never shut in two connected assets at once). Those become P6
16
+ finish-to-start dependencies — the DAG the critical path runs over.
17
+ 3. **Resources (crews)** — activities are levelled across the Crew roster so no
18
+ crew runs more than its `jobs_per_day` concurrent jobs. A hard resourcing
19
+ constraint straight out of the Crew entity.
20
+
21
+ It then runs the P6 core: CPM forward/backward passes for early/late dates,
22
+ **total float**, and the **critical path** (zero-float chain); a serial
23
+ resource-levelling pass in production-recovery priority order for the actual
24
+ planned dates and crew assignment. The critical path is driven by the biggest
25
+ production loss — the cross-app join back to the deferment component
26
+ (`Well.deferred_gas`, DEMO_SPEC.md §5.1).
27
+
28
+ Everything is read through the read-only engine (`list_entities`, `get_entity`,
29
+ `get_relationships`, `traverse`, `get_latest_observation`); the plan is written
30
+ to a store it OWNS (`schedule.parquet`), federated back as the Activity
31
+ EntityType. henosis stores nothing itself (Principle I). Swap the greedy leveller
32
+ for a real RCPSP optimiser and the interface is unchanged.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ from datetime import datetime, timedelta
38
+
39
+ from henosis.components import ComponentContext, ComponentResult
40
+
41
+ # Ordinary ontology names the component author knows from their own YAML.
42
+ _FEEDS_REL = "feeds"
43
+ _ASSET_REL = "asset"
44
+ _DEFERRED_OBS = "deferred_gas"
45
+ _OUTPUT_STORE = "schedule"
46
+ _OPEN_STATUS = "open"
47
+
48
+ # Activity duration (working days) by work-order urgency — a P6 activity always
49
+ # carries a duration; the demo derives it from priority.
50
+ _DURATION_BY_PRIORITY = {"urgent": 5, "elevated": 3, "routine": 2}
51
+ _PRIORITY_RANK = {"urgent": 0, "elevated": 1, "routine": 2}
52
+
53
+
54
+ def _latest(engine, entity_id: str, prop: str) -> float:
55
+ """Latest value of an observation, or 0.0 when the entity has no such data."""
56
+ try:
57
+ obs = engine.get_latest_observation(entity_id, prop)
58
+ except Exception:
59
+ return 0.0
60
+ if obs is None or obs.value is None:
61
+ return 0.0
62
+ return float(obs.value)
63
+
64
+
65
+ def _upstream_assets(engine, asset_id: str) -> set[str]:
66
+ """Every asset that feeds INTO this one — the upstream set on the `feeds`
67
+ conveyance. Precedence runs upstream→downstream: an order on an upstream
68
+ asset must finish before one on a downstream asset (fix the source first;
69
+ never shut two connected assets in the same window)."""
70
+ up: set[str] = set()
71
+ try:
72
+ trace = engine.traverse(asset_id, _FEEDS_REL, direction="inbound")
73
+ except Exception:
74
+ return up
75
+ for node in trace.nodes:
76
+ if node.id != asset_id:
77
+ up.add(node.id)
78
+ return up
79
+
80
+
81
+ def _production_recovery(engine, asset_id: str, asset_type: str) -> float:
82
+ """Gas/day this order recovers if the constraint behind it clears. A Well
83
+ order recovers its own deferred gas; a Pipeline/Compressor order sits on a
84
+ shared conveyance, so it recovers the deferred gas of every well behind it
85
+ (`traverse(feeds, inbound)` sum). This is the cross-app join to the deferment
86
+ component — the loss it quantified becomes the schedule's priority."""
87
+ if asset_type == "Well":
88
+ return _latest(engine, asset_id, _DEFERRED_OBS)
89
+ total = 0.0
90
+ try:
91
+ trace = engine.traverse(asset_id, _FEEDS_REL, direction="inbound")
92
+ except Exception:
93
+ return 0.0
94
+ for node in trace.nodes:
95
+ if node.entity_type == "Well":
96
+ total += _latest(engine, node.id, _DEFERRED_OBS)
97
+ return total
98
+
99
+
100
+ def _open_orders(engine) -> list[dict]:
101
+ """The open work-order backlog, each an activity with asset, duration and
102
+ production recovery. Orders with no resolvable asset are skipped."""
103
+ acts: list[dict] = []
104
+ for item in engine.list_entities("WorkOrder", limit=1000).items:
105
+ try:
106
+ wo = engine.get_entity(
107
+ "WorkOrder",
108
+ item.id,
109
+ fields=["state.status", "state.priority", "identity.work_order",
110
+ "identity.name", "identity.description"],
111
+ )
112
+ except Exception:
113
+ continue
114
+ state = wo.state or {}
115
+ if state.get("status") != _OPEN_STATUS:
116
+ continue
117
+ rels = engine.get_relationships(item.id, _ASSET_REL)
118
+ if not rels.items:
119
+ continue
120
+ asset = rels.items[0].target
121
+ ident = wo.identity or {}
122
+ priority = state.get("priority") or "routine"
123
+ acts.append(
124
+ {
125
+ "aid": item.id.split(":", 1)[-1], # raw id → Activity/WorkOrder FK
126
+ # A short title + a detail line, carried straight from the work
127
+ # order (both already use the asset's friendly name).
128
+ "name": ident.get("name") or ident.get("work_order") or item.id,
129
+ "description": ident.get("description") or "",
130
+ "work_order": ident.get("work_order") or item.id,
131
+ "priority": priority,
132
+ "duration": _DURATION_BY_PRIORITY.get(priority, 1),
133
+ "asset_id": asset.id,
134
+ "asset_type": asset.type,
135
+ "recovery": _production_recovery(engine, asset.id, asset.type),
136
+ }
137
+ )
138
+ return acts
139
+
140
+
141
+ def _crew_units(engine) -> list[dict]:
142
+ """The crew roster expanded into resource units (a crew with jobs_per_day=2
143
+ is two units that can each run one activity at a time). Each unit levels
144
+ independently; its crew name labels the assignment."""
145
+ units: list[dict] = []
146
+ for item in engine.list_entities("Crew", limit=100).items:
147
+ try:
148
+ crew = engine.get_entity(
149
+ "Crew", item.id, fields=["identity.name", "identity.jobs_per_day"]
150
+ )
151
+ except Exception:
152
+ continue
153
+ ident = crew.identity or {}
154
+ raw = item.id.split(":", 1)[-1]
155
+ for _ in range(int(ident.get("jobs_per_day") or 1)):
156
+ units.append({"crew_id": raw, "name": ident.get("name") or item.id, "free_at": 0})
157
+ return units
158
+
159
+
160
+ def _cpm(acts: list[dict], preds: dict[str, list[str]]) -> None:
161
+ """Classic P6 CPM in place: forward pass (early start/finish), backward pass
162
+ (late start/finish), total float and the critical-path flag. Logic-only —
163
+ the resource-levelled dates come later; total_float here is the schedule
164
+ logic's float, exactly as P6 reports it in the activity network."""
165
+ by_id = {a["aid"]: a for a in acts}
166
+ succs: dict[str, list[str]] = {a["aid"]: [] for a in acts}
167
+ for aid, ps in preds.items():
168
+ for p in ps:
169
+ succs[p].append(aid)
170
+
171
+ # Forward pass in topological order (an activity after all its predecessors).
172
+ order = _topo(acts, preds)
173
+ for aid in order:
174
+ a = by_id[aid]
175
+ a["es"] = max((by_id[p]["ef"] for p in preds[aid]), default=0)
176
+ a["ef"] = a["es"] + a["duration"]
177
+ project = max((a["ef"] for a in acts), default=0)
178
+
179
+ # Backward pass.
180
+ for aid in reversed(order):
181
+ a = by_id[aid]
182
+ a["lf"] = min((by_id[s]["ls"] for s in succs[aid]), default=project)
183
+ a["ls"] = a["lf"] - a["duration"]
184
+ a["total_float"] = a["ls"] - a["es"]
185
+ a["is_critical"] = a["total_float"] == 0
186
+
187
+
188
+ def _topo(acts: list[dict], preds: dict[str, list[str]]) -> list[str]:
189
+ """Topological order of the activity DAG (Kahn). The precedence graph is
190
+ acyclic by construction — `feeds` is a directed conveyance."""
191
+ indeg = {a["aid"]: len(preds[a["aid"]]) for a in acts}
192
+ ready = [aid for aid, d in indeg.items() if d == 0]
193
+ succs: dict[str, list[str]] = {a["aid"]: [] for a in acts}
194
+ for aid, ps in preds.items():
195
+ for p in ps:
196
+ succs[p].append(aid)
197
+ order: list[str] = []
198
+ while ready:
199
+ aid = ready.pop(0)
200
+ order.append(aid)
201
+ for s in succs[aid]:
202
+ indeg[s] -= 1
203
+ if indeg[s] == 0:
204
+ ready.append(s)
205
+ # Any leftover (shouldn't happen) appended so nothing is dropped.
206
+ order += [a["aid"] for a in acts if a["aid"] not in order]
207
+ return order
208
+
209
+
210
+ class MaintenanceSchedule:
211
+ """The declared component. `run` is the whole contract."""
212
+
213
+ def run(self, ctx: ComponentContext) -> ComponentResult:
214
+ engine = ctx.open_engine() # read-only; a component may not mutate sources
215
+ params = ctx.job.params or {}
216
+ base = datetime.fromisoformat(str(params.get("schedule_start")))
217
+
218
+ acts = _open_orders(engine)
219
+ units = _crew_units(engine)
220
+
221
+ # Precedence from the physical network: a precedes b when a's asset is
222
+ # upstream of b's. Build the full relation (for CPM) and the single
223
+ # driving predecessor (the binding one — a clean edge for the graph).
224
+ upstream = {a["aid"]: _upstream_assets(engine, a["asset_id"]) for a in acts}
225
+ preds: dict[str, list[str]] = {}
226
+ for b in acts:
227
+ preds[b["aid"]] = [
228
+ a["aid"] for a in acts
229
+ if a["aid"] != b["aid"] and a["asset_id"] in upstream[b["aid"]]
230
+ ]
231
+
232
+ _cpm(acts, preds)
233
+
234
+ # Resource levelling — serial schedule generation. Process in CPM early-
235
+ # start order (keeps predecessors first), breaking ties by production
236
+ # recovery then urgency. Each activity starts at the later of its
237
+ # predecessors' finishes and the earliest free crew unit.
238
+ by_id = {a["aid"]: a for a in acts}
239
+ order = sorted(
240
+ acts,
241
+ key=lambda a: (a["es"], -a["recovery"], _PRIORITY_RANK.get(a["priority"], 9), a["aid"]),
242
+ )
243
+ for a in order:
244
+ ready_day = max((by_id[p]["planned_end_excl"] for p in preds[a["aid"]]), default=0)
245
+ unit = min(units, key=lambda u: (max(u["free_at"], ready_day), u["crew_id"]))
246
+ start = max(unit["free_at"], ready_day)
247
+ a["planned_start_day"] = start
248
+ a["planned_end_excl"] = start + a["duration"]
249
+ a["crew_id"] = unit["crew_id"]
250
+ a["crew_name"] = unit["name"]
251
+ unit["free_at"] = a["planned_end_excl"]
252
+
253
+ rows: list[dict] = []
254
+ for a in acts:
255
+ driver = max(preds[a["aid"]], key=lambda p: by_id[p]["ef"], default=None)
256
+ start_day = a["planned_start_day"]
257
+ rows.append(
258
+ {
259
+ "id": a["aid"], # one activity row per work order (stable)
260
+ "activity_id": f"A{a['aid']}",
261
+ "name": a["name"],
262
+ "description": a["description"],
263
+ "work_order_id": a["aid"],
264
+ "planned_start": (base + timedelta(days=start_day)).isoformat(),
265
+ # inclusive last working day = start + duration - 1
266
+ "planned_finish": (
267
+ base + timedelta(days=a["planned_end_excl"] - 1)
268
+ ).isoformat(),
269
+ "duration_days": a["duration"],
270
+ "total_float_days": a["total_float"],
271
+ "is_critical": bool(a["is_critical"]),
272
+ "priority": a["priority"],
273
+ "crew_id": a["crew_id"],
274
+ "crew_name": a["crew_name"],
275
+ "asset_id": a["asset_id"],
276
+ "asset_type": a["asset_type"],
277
+ "production_recovery_m3d": round(a["recovery"], 1),
278
+ "predecessor_id": driver or "", # driving predecessor (may be empty)
279
+ "predecessor_count": len(preds[a["aid"]]),
280
+ "status": "scheduled",
281
+ }
282
+ )
283
+
284
+ writer = ctx.output(_OUTPUT_STORE)
285
+ writer.write(rows)
286
+ n = writer.commit()
287
+ return ComponentResult(
288
+ run_id=ctx.job.run_id,
289
+ status="completed",
290
+ output_store=_OUTPUT_STORE,
291
+ rows_written=n,
292
+ )
@@ -0,0 +1,104 @@
1
+ """Production-allocation logic component — authored *in the example project*.
2
+
3
+ This is what a customer writes: it imports only henosis's PUBLIC component API
4
+ (`henosis.components`), never the engine's internals, and reaches source data
5
+ solely through the read-only engine handle `ctx.open_engine()` hands it. It
6
+ computes a **recursive, multi-level** allocation — the shape a `derived_from`
7
+ expr or an `execute` SQL statement can't express — and writes the result to a
8
+ store it OWNS (`network_allocation.parquet`), which a `parquet` source
9
+ connection then federates back in as ordinary ontology data. henosis stores
10
+ nothing itself (Principle I).
11
+
12
+ Allocation, per the classic scheme:
13
+ * each node's *basis* is its producing capacity that day — here, a well's
14
+ latest `gas_rate` (a totalised-meter basis; a well-test or manual estimate
15
+ would be another basis source);
16
+ * a node's *allocation factor* = its basis ÷ the sum of sibling bases;
17
+ * a node's allocated volume = its factor × the parent's volume;
18
+ * for multi-level networks the walk recurses parent→children, handing each
19
+ child its allocated volume as the next level's parent volume.
20
+
21
+ Registered via a `henosis.components` entry point in this project's packaging
22
+ (see the module docstring in demo_network_allocation.py for the in-repo path
23
+ that calls `register_component` directly, since the example isn't pip-installed).
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from henosis.components import ComponentContext, ComponentResult
29
+
30
+ # The relationship that defines an allocation parent's sibling sub-tree, and the
31
+ # observation used as each node's basis. Both are ordinary ontology names the
32
+ # component author knows from their own YAML — no engine internals.
33
+ _CHILDREN_REL = "contains"
34
+ _BASIS_OBS = "gas_rate"
35
+ _PARENT_TOTAL_OBS = "metered_gas"
36
+ _OUTPUT_STORE = "network_allocation"
37
+
38
+
39
+ def _basis(engine, node_id: str) -> float:
40
+ """This node's producing-capacity basis for the day, or 0.0 with no data."""
41
+ try:
42
+ obs = engine.get_latest_observation(node_id, _BASIS_OBS)
43
+ except Exception:
44
+ return 0.0
45
+ return float(obs.value) if obs is not None and obs.value is not None else 0.0
46
+
47
+
48
+ def _children(engine, node_id: str) -> list[str]:
49
+ """Ids of the node's allocation children (its sibling sub-tree)."""
50
+ rel = engine.get_relationships(node_id, _CHILDREN_REL)
51
+ return [r.id for r in rel.related]
52
+
53
+
54
+ def _allocate(engine, node_id: str, volume: float, out: list[dict]) -> None:
55
+ """Split `volume` across `node_id`'s children pro-rata to their basis, then
56
+ recurse into each child with its allocated share as the next parent volume.
57
+ A leaf (no children) is a terminal allocation target and records its volume."""
58
+ children = _children(engine, node_id)
59
+ if not children:
60
+ return
61
+ bases = {c: _basis(engine, c) for c in children}
62
+ total_basis = sum(bases.values())
63
+ if total_basis <= 0:
64
+ return
65
+ for child, basis in bases.items():
66
+ factor = basis / total_basis
67
+ allocated = factor * volume
68
+ out.append(
69
+ {
70
+ "parent": node_id,
71
+ "node": child,
72
+ "basis": basis,
73
+ "allocation_factor": factor,
74
+ "allocated_volume": allocated,
75
+ }
76
+ )
77
+ _allocate(engine, child, allocated, out) # multi-level reconciliation
78
+
79
+
80
+ class ProductionAllocation:
81
+ """The declared component. `run` is the whole contract."""
82
+
83
+ def run(self, ctx: ComponentContext) -> ComponentResult:
84
+ engine = ctx.open_engine() # read-only; a component may not mutate sources
85
+ root = ctx.job.entity_id
86
+ if root is None:
87
+ return ComponentResult(ctx.job.run_id, "failed", message="no acting entity")
88
+
89
+ # The parent boundary's own volume for the day — the metered total.
90
+ parent_obs = engine.get_latest_observation(root, _PARENT_TOTAL_OBS)
91
+ parent_volume = float(parent_obs.value) if parent_obs and parent_obs.value else 0.0
92
+
93
+ rows: list[dict] = []
94
+ _allocate(engine, root, parent_volume, rows)
95
+
96
+ writer = ctx.output(_OUTPUT_STORE)
97
+ writer.write(rows)
98
+ n = writer.commit()
99
+ return ComponentResult(
100
+ run_id=ctx.job.run_id,
101
+ status="completed",
102
+ output_store=_OUTPUT_STORE,
103
+ rows_written=n,
104
+ )