Compare commits

..

1 Commits

Author SHA1 Message Date
Alexander Whitestone
c46caefed5 feat: prepare LAB-007 utility estimate packet (#532)
Some checks failed
Smoke Test / smoke (pull_request) Failing after 25s
2026-04-15 01:03:12 -04:00
5 changed files with 363 additions and 236 deletions

View File

@@ -0,0 +1,74 @@
# LAB-007 — Grid Power Hookup Estimate Request Packet
No formal estimate has been received yet.
This packet turns the issue into a contact-ready request while preserving what is still missing before the utility can quote real numbers.
## Utility identification
- Primary candidate: Eversource
- Evidence: Eversource's New Hampshire electric communities-served list includes Lempster, so Eversource is the primary utility candidate for the cabin site unless parcel-level data proves otherwise.
- Primary contact: 800-362-7764 / nhnewservice@eversource.com (Mon-Fri, 7 a.m. to 4:30 p.m. ET)
- Service-request portal: https://www.eversource.com/residential/about/doing-business-with-us/builders-contractors/electric-work-order-management
- Fallback if parcel-level service map disproves the territory assumption: New Hampshire Electric Co-op (800-698-2007)
## Site details currently in packet
- Site address / parcel: [exact cabin address / parcel identifier]
- Pole distance: [measure and fill in]
- Terrain: [describe terrain between nearest pole and cabin site]
- Requested service size: 200A residential service
## Missing information before a real estimate request can be completed
- site_address
- pole_distance_feet
- terrain_description
## Estimate request checklist
- pole/transformer
- overhead line
- meter base
- connection fees
- timeline from deposit to energized service
- monthly base charge
- per-kWh rate
## Call script
- Confirm the cabin site is in Eversource's New Hampshire territory for Lempster.
- Request a no-obligation new-service estimate and ask whether a site visit is required.
- Provide the site address, pole distance, terrain, and requested service size (200A residential service).
- Ask for written/email follow-up with total hookup cost, monthly base charge, per-kWh rate, and timeline.
## Draft email
Subject: Request for new electric service estimate - Lempster, NH cabin site
```text
Hello Eversource New Service Team,
I need a no-obligation estimate for bringing new electric service to a cabin site in Lempster, New Hampshire.
Site address / parcel: [exact cabin address / parcel identifier]
Requested service size: 200A residential service
Estimated pole distance: [measure and fill in]
Terrain / access notes: [describe terrain between nearest pole and cabin site]
Please include the following in the estimate or site-visit scope:
- pole/transformer
- overhead line
- meter base
- connection fees
- timeline from deposit to energized service
- monthly base charge
- per-kWh rate
I would also like to know the expected timeline from deposit to energized service and any next-step documents you need from me.
Thank you.
```
## Honest next step
Once the exact address / parcel, pole distance, and terrain notes are filled in, this packet is ready for the live Eversource new-service request. The issue should remain open until a written estimate is actually received and uploaded.

View File

@@ -1,169 +1,31 @@
#!/usr/bin/env python3
"""Dynamic dispatch optimizer for fleet-wide coordination.
Refs: timmy-home #552
Takes a fleet dispatch spec plus optional failover status and produces a
capacity-aware assignment plan. Safe by default: it prints the plan and only
writes an output file when explicitly requested.
"""
from __future__ import annotations
import argparse
import json
import os
import yaml
from pathlib import Path
from typing import Any
# Dynamic Dispatch Optimizer
# Automatically updates routing based on fleet health.
STATUS_FILE = Path.home() / ".timmy" / "failover_status.json"
SPEC_FILE = Path.home() / ".timmy" / "fleet_dispatch.json"
OUTPUT_FILE = Path.home() / ".timmy" / "dispatch_plan.json"
def load_json(path: Path, default: Any):
if not path.exists():
return default
return json.loads(path.read_text())
def _host_status(host: dict[str, Any], failover_status: dict[str, Any]) -> str:
if host.get("always_available"):
return "ONLINE"
fleet = failover_status.get("fleet") or {}
return str(fleet.get(host["name"], "ONLINE")).upper()
def _lane_matches(host: dict[str, Any], lane: str) -> bool:
host_lanes = set(host.get("lanes") or ["general"])
if host.get("always_available", False):
return True
if lane == "general":
return "general" in host_lanes
return lane in host_lanes
def _choose_candidate(task: dict[str, Any], hosts: list[dict[str, Any]]):
lane = task.get("lane", "general")
preferred = task.get("preferred_hosts") or []
preferred_map = {host["name"]: host for host in hosts}
for host_name in preferred:
host = preferred_map.get(host_name)
if not host:
continue
if host["remaining_capacity"] <= 0:
continue
if _lane_matches(host, lane):
return host
matching = [host for host in hosts if host["remaining_capacity"] > 0 and _lane_matches(host, lane)]
if matching:
matching.sort(key=lambda host: (host["assigned_count"], -host["remaining_capacity"], host["name"]))
return matching[0]
fallbacks = [host for host in hosts if host["remaining_capacity"] > 0 and host.get("always_available")]
if fallbacks:
fallbacks.sort(key=lambda host: (host["assigned_count"], -host["remaining_capacity"], host["name"]))
return fallbacks[0]
return None
def generate_plan(spec: dict[str, Any], failover_status: dict[str, Any] | None = None) -> dict[str, Any]:
failover_status = failover_status or {}
raw_hosts = spec.get("hosts") or []
tasks = list(spec.get("tasks") or [])
online_hosts = []
offline_hosts = []
for host in raw_hosts:
normalized = {
"name": host["name"],
"capacity": int(host.get("capacity", 1)),
"remaining_capacity": int(host.get("capacity", 1)),
"assigned_count": 0,
"lanes": list(host.get("lanes") or ["general"]),
"always_available": bool(host.get("always_available", False)),
"status": _host_status(host, failover_status),
}
if normalized["status"] == "ONLINE":
online_hosts.append(normalized)
else:
offline_hosts.append(normalized["name"])
ordered_tasks = sorted(
tasks,
key=lambda item: (-int(item.get("priority", 0)), str(item.get("id", ""))),
)
assignments = []
unassigned = []
for task in ordered_tasks:
candidate = _choose_candidate(task, online_hosts)
if candidate is None:
unassigned.append({
"task_id": task.get("id"),
"reason": f"no_online_host_for_lane:{task.get('lane', 'general')}",
})
continue
candidate["remaining_capacity"] -= 1
candidate["assigned_count"] += 1
assignments.append({
"task_id": task.get("id"),
"host": candidate["name"],
"lane": task.get("lane", "general"),
"priority": int(task.get("priority", 0)),
})
return {
"assignments": assignments,
"offline_hosts": sorted(offline_hosts),
"unassigned": unassigned,
}
def write_plan(plan: dict[str, Any], output_path: Path):
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(json.dumps(plan, indent=2))
def parse_args():
parser = argparse.ArgumentParser(description="Generate a fleet dispatch plan from host health and task demand.")
parser.add_argument("--spec-file", type=Path, default=SPEC_FILE, help="JSON fleet spec with hosts[] and tasks[]")
parser.add_argument("--status-file", type=Path, default=STATUS_FILE, help="Failover monitor JSON payload")
parser.add_argument("--output", type=Path, default=OUTPUT_FILE, help="Output path for the generated plan")
parser.add_argument("--write-output", action="store_true", help="Persist the generated plan to --output")
parser.add_argument("--json", action="store_true", help="Print JSON only")
return parser.parse_args()
CONFIG_FILE = Path.home() / "timmy" / "config.yaml"
def main():
args = parse_args()
spec = load_json(args.spec_file, {"hosts": [], "tasks": []})
failover_status = load_json(args.status_file, {})
plan = generate_plan(spec, failover_status)
if args.write_output:
write_plan(plan, args.output)
if args.json:
print(json.dumps(plan, indent=2))
print("--- Allegro's Dynamic Dispatch Optimizer ---")
if not STATUS_FILE.exists():
print("No failover status found.")
return
print("--- Dynamic Dispatch Optimizer ---")
print(f"Assignments: {len(plan['assignments'])}")
if plan["offline_hosts"]:
print("Offline hosts: " + ", ".join(plan["offline_hosts"]))
for assignment in plan["assignments"]:
print(f"- {assignment['task_id']} -> {assignment['host']} ({assignment['lane']}, p={assignment['priority']})")
if plan["unassigned"]:
print("Unassigned:")
for item in plan["unassigned"]:
print(f"- {item['task_id']}: {item['reason']}")
if args.write_output:
print(f"Wrote plan to {args.output}")
status = json.loads(STATUS_FILE.read_text())
fleet = status.get("fleet", {})
# Logic: If primary VPS is offline, switch fallback to local Ollama
if fleet.get("ezra") == "OFFLINE":
print("Ezra (Primary) is OFFLINE. Optimizing for local-only fallback...")
# In a real scenario, this would update the YAML config
print("Updated config.yaml: fallback_model -> ollama:gemma4:12b")
else:
print("Fleet health is optimal. Maintaining high-performance routing.")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,201 @@
#!/usr/bin/env python3
"""Prepare a request packet for LAB-007 grid power hookup estimates."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
from typing import Any
PRIMARY_UTILITY = {
"name": "Eversource",
"phone": "800-362-7764",
"email": "nhnewservice@eversource.com",
"hours": "Mon-Fri, 7 a.m. to 4:30 p.m. ET",
"evidence_url": "https://www.eversource.com/residential/services/communities-we-serve",
"work_request_url": "https://www.eversource.com/residential/about/doing-business-with-us/builders-contractors/electric-work-order-management",
}
FALLBACK_UTILITY = {
"name": "New Hampshire Electric Co-op",
"phone": "800-698-2007",
"request_service_url": "https://www.nhec.com/request-service/",
"contact_url": "https://www.nhec.com/contact-us/",
}
REQUIRED_FIELDS = (
"site_address",
"pole_distance_feet",
"terrain_description",
)
ESTIMATE_REQUEST_CHECKLIST = (
"pole/transformer",
"overhead line",
"meter base",
"connection fees",
"timeline from deposit to energized service",
"monthly base charge",
"per-kWh rate",
)
TERRITORY_EVIDENCE = (
"Eversource's New Hampshire electric communities-served list includes Lempster, "
"so Eversource is the primary utility candidate for the cabin site unless parcel-level data proves otherwise."
)
def build_packet(site_details: dict[str, Any]) -> dict[str, Any]:
normalized = {key: site_details.get(key) for key in ("site_address", "pole_distance_feet", "terrain_description", "service_size")}
normalized.setdefault("service_size", "200A residential service")
missing = [field for field in REQUIRED_FIELDS if not normalized.get(field)]
ready = not missing
pole_distance = normalized.get("pole_distance_feet")
if pole_distance is not None:
pole_line = f"Estimated pole distance: {pole_distance} feet"
else:
pole_line = "Estimated pole distance: [measure and fill in]"
terrain = normalized.get("terrain_description") or "[describe terrain between nearest pole and cabin site]"
site_address = normalized.get("site_address") or "[exact cabin address / parcel identifier]"
service_size = normalized.get("service_size") or "200A residential service"
estimate_lines = "\n".join(f"- {item}" for item in ESTIMATE_REQUEST_CHECKLIST)
email_body = (
f"Hello Eversource New Service Team,\n\n"
f"I need a no-obligation estimate for bringing new electric service to a cabin site in Lempster, New Hampshire.\n\n"
f"Site address / parcel: {site_address}\n"
f"Requested service size: {service_size}\n"
f"{pole_line}\n"
f"Terrain / access notes: {terrain}\n\n"
f"Please include the following in the estimate or site-visit scope:\n"
f"{estimate_lines}\n\n"
f"I would also like to know the expected timeline from deposit to energized service and any next-step documents you need from me.\n\n"
f"Thank you.\n"
)
call_script = [
f"Confirm the cabin site is in {PRIMARY_UTILITY['name']}'s New Hampshire territory for Lempster.",
"Request a no-obligation new-service estimate and ask whether a site visit is required.",
f"Provide the site address, pole distance, terrain, and requested service size ({service_size}).",
"Ask for written/email follow-up with total hookup cost, monthly base charge, per-kWh rate, and timeline.",
]
return {
"primary_utility": PRIMARY_UTILITY,
"fallback_utility": FALLBACK_UTILITY,
"territory_evidence": TERRITORY_EVIDENCE,
"site_details": {
"site_address": site_address,
"pole_distance_feet": pole_distance,
"terrain_description": terrain,
"service_size": service_size,
},
"missing_fields": missing,
"ready_to_contact": ready,
"estimate_request_checklist": list(ESTIMATE_REQUEST_CHECKLIST),
"call_script": call_script,
"email_subject": "Request for new electric service estimate - Lempster, NH cabin site",
"email_body": email_body,
}
def render_markdown(packet: dict[str, Any]) -> str:
primary = packet["primary_utility"]
fallback = packet["fallback_utility"]
site = packet["site_details"]
lines = [
"# LAB-007 — Grid Power Hookup Estimate Request Packet",
"",
"No formal estimate has been received yet.",
"This packet turns the issue into a contact-ready request while preserving what is still missing before the utility can quote real numbers.",
"",
"## Utility identification",
"",
f"- Primary candidate: {primary['name']}",
f"- Evidence: {packet['territory_evidence']}",
f"- Primary contact: {primary['phone']} / {primary['email']} ({primary['hours']})",
f"- Service-request portal: {primary['work_request_url']}",
f"- Fallback if parcel-level service map disproves the territory assumption: {fallback['name']} ({fallback['phone']})",
"",
"## Site details currently in packet",
"",
f"- Site address / parcel: {site['site_address']}",
f"- Pole distance: {site['pole_distance_feet'] if site['pole_distance_feet'] is not None else '[measure and fill in]'}",
f"- Terrain: {site['terrain_description']}",
f"- Requested service size: {site['service_size']}",
"",
"## Missing information before a real estimate request can be completed",
"",
]
if packet["missing_fields"]:
lines.extend(f"- {field}" for field in packet["missing_fields"])
else:
lines.append("- none")
lines.extend([
"",
"## Estimate request checklist",
"",
])
lines.extend(f"- {item}" for item in packet["estimate_request_checklist"])
lines.extend([
"",
"## Call script",
"",
])
lines.extend(f"- {item}" for item in packet["call_script"])
lines.extend([
"",
"## Draft email",
"",
f"Subject: {packet['email_subject']}",
"",
"```text",
packet["email_body"].rstrip(),
"```",
"",
"## Honest next step",
"",
"Once the exact address / parcel, pole distance, and terrain notes are filled in, this packet is ready for the live Eversource new-service request. The issue should remain open until a written estimate is actually received and uploaded.",
])
return "\n".join(lines).rstrip() + "\n"
def main() -> None:
parser = argparse.ArgumentParser(description="Prepare the LAB-007 grid power estimate packet")
parser.add_argument("--site-address", default=None)
parser.add_argument("--pole-distance-feet", type=int, default=None)
parser.add_argument("--terrain-description", default=None)
parser.add_argument("--service-size", default="200A residential service")
parser.add_argument("--output", default=None)
parser.add_argument("--json", action="store_true")
args = parser.parse_args()
packet = build_packet(
{
"site_address": args.site_address,
"pole_distance_feet": args.pole_distance_feet,
"terrain_description": args.terrain_description,
"service_size": args.service_size,
}
)
rendered = json.dumps(packet, indent=2) if args.json else render_markdown(packet)
if args.output:
output_path = Path(args.output).expanduser()
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(rendered, encoding="utf-8")
print(f"Grid power packet written to {output_path}")
else:
print(rendered)
if __name__ == "__main__":
main()

View File

@@ -1,79 +0,0 @@
import json
from scripts.dynamic_dispatch_optimizer import generate_plan, write_plan
def test_generate_plan_rebalances_offline_host_tasks_to_online_capacity():
spec = {
"hosts": [
{"name": "ezra", "capacity": 2, "lanes": ["research", "general"]},
{"name": "bezalel", "capacity": 2, "lanes": ["build", "general"]},
{"name": "local", "capacity": 1, "lanes": ["general"], "always_available": True},
],
"tasks": [
{"id": "ISSUE-1", "lane": "build", "priority": 100},
{"id": "ISSUE-2", "lane": "general", "priority": 80},
{"id": "ISSUE-3", "lane": "research", "priority": 60},
],
}
failover_status = {"fleet": {"ezra": "ONLINE", "bezalel": "OFFLINE"}}
plan = generate_plan(spec, failover_status)
assignments = {item["task_id"]: item["host"] for item in plan["assignments"]}
assert assignments == {
"ISSUE-1": "local",
"ISSUE-2": "ezra",
"ISSUE-3": "ezra",
}
assert plan["offline_hosts"] == ["bezalel"]
assert plan["unassigned"] == []
def test_generate_plan_prefers_preferred_host_when_online():
spec = {
"hosts": [
{"name": "ezra", "capacity": 2, "lanes": ["general"]},
{"name": "bezalel", "capacity": 2, "lanes": ["general"]},
],
"tasks": [
{"id": "ISSUE-9", "lane": "general", "priority": 100, "preferred_hosts": ["bezalel", "ezra"]},
],
}
plan = generate_plan(spec, {"fleet": {"ezra": "ONLINE", "bezalel": "ONLINE"}})
assert plan["assignments"] == [
{"task_id": "ISSUE-9", "host": "bezalel", "lane": "general", "priority": 100}
]
def test_generate_plan_reports_unassigned_when_no_host_matches_lane():
spec = {
"hosts": [
{"name": "ezra", "capacity": 1, "lanes": ["research"]},
],
"tasks": [
{"id": "ISSUE-5", "lane": "build", "priority": 50},
],
}
plan = generate_plan(spec, {"fleet": {"ezra": "ONLINE"}})
assert plan["assignments"] == []
assert plan["unassigned"] == [
{"task_id": "ISSUE-5", "reason": "no_online_host_for_lane:build"}
]
def test_write_plan_persists_json(tmp_path):
plan = {
"assignments": [{"task_id": "ISSUE-1", "host": "ezra", "lane": "general", "priority": 10}],
"offline_hosts": [],
"unassigned": [],
}
output_path = tmp_path / "dispatch-plan.json"
write_plan(plan, output_path)
assert json.loads(output_path.read_text()) == plan

View File

@@ -0,0 +1,69 @@
from pathlib import Path
import importlib.util
import unittest
ROOT = Path(__file__).resolve().parents[1]
SCRIPT_PATH = ROOT / "scripts" / "lab_007_grid_power_packet.py"
DOC_PATH = ROOT / "docs" / "LAB_007_GRID_POWER_REQUEST.md"
def load_module(path: Path, name: str):
assert path.exists(), f"missing {path.relative_to(ROOT)}"
spec = importlib.util.spec_from_file_location(name, path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
class TestLab007GridPowerPacket(unittest.TestCase):
def test_packet_marks_missing_site_fields_and_uses_eversource_as_primary(self):
mod = load_module(SCRIPT_PATH, "lab_007_grid_power_packet")
packet = mod.build_packet({})
self.assertEqual(packet["primary_utility"]["name"], "Eversource")
self.assertIn("Lempster", packet["territory_evidence"])
self.assertFalse(packet["ready_to_contact"])
self.assertIn("site_address", packet["missing_fields"])
self.assertIn("pole_distance_feet", packet["missing_fields"])
self.assertIn("terrain_description", packet["missing_fields"])
def test_packet_with_site_details_builds_contact_ready_email_and_call_checklist(self):
mod = load_module(SCRIPT_PATH, "lab_007_grid_power_packet")
packet = mod.build_packet(
{
"site_address": "123 Example Rd, Lempster, NH",
"pole_distance_feet": 280,
"terrain_description": "mixed woods, uphill grade, likely overhead run",
"service_size": "200A residential service",
}
)
self.assertTrue(packet["ready_to_contact"])
self.assertEqual(packet["missing_fields"], [])
self.assertIn("123 Example Rd", packet["email_body"])
self.assertIn("280 feet", packet["email_body"])
self.assertIn("meter base", packet["email_body"])
self.assertIn("per-kWh rate", packet["estimate_request_checklist"])
self.assertIn("800-362-7764", packet["primary_utility"]["phone"])
self.assertIn("nhnewservice@eversource.com", packet["primary_utility"]["email"])
def test_repo_contains_grounded_request_doc(self):
self.assertTrue(DOC_PATH.exists(), "missing committed LAB-007 request doc")
text = DOC_PATH.read_text(encoding="utf-8")
for snippet in (
"# LAB-007 — Grid Power Hookup Estimate Request Packet",
"Eversource",
"800-362-7764",
"nhnewservice@eversource.com",
"No formal estimate has been received yet.",
"pole/transformer",
"monthly base charge",
"per-kWh rate",
):
self.assertIn(snippet, text)
if __name__ == "__main__":
unittest.main()