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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions add_grace_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
"""Add a unit test for the cold-start grace branch."""
import re

test_src = open("tests/test_policy.py").read()
if "cold_start_grace" not in test_src:
# find an existing stuck/off-track test to mirror
anchor = test_src.find("def test_")
test = '''

def test_cold_start_grace_blocks_early_stop() -> None:
"""A worker younger than the grace window is CONTINUED, not stopped, even
when stuck/off-track scores exceed thresholds (hermes boots silently)."""
from datetime import UTC, datetime, timedelta

from foreman.config import FactoryConfig
from foreman.models import (
FactoryAssessment, FactoryState, WorkerRecord, WorkerStatus, WorkerType,
)
from foreman.policy import FactoryPolicy

config = FactoryConfig(cold_start_grace_seconds=30.0, stuck_threshold=0.80)
policy = FactoryPolicy(config=config)
started = datetime.now(UTC) - timedelta(seconds=3) # younger than grace
worker = WorkerRecord(
worker_id="worker-1", worker_type=WorkerType.CODING, mission="do work",
status=WorkerStatus.RUNNING, started_at=started,
)
state = FactoryState(
run_id="r1", job="job", repository="repo", max_workers=3, max_iterations=20,
)
state.workers.append(worker)
state.active_workers.append("worker-1")
assessment = FactoryAssessment(
implementation_complete=0.0, tests_sufficient=0.0, requirements_satisfied=0.0,
needs_verification=0.0, ready_to_finish=0.0, meaningful_progress=0.0,
worker_stuck=0.9, work_off_track=0.9, agents_md_drift=0.0, needs_human=0.0,
)
intervention = policy.decide(state, assessment)
assert intervention.action.value == "CONTINUE"
assert "cold-start grace" in intervention.reason


def test_cold_start_grace_expires_allows_stop() -> None:
"""Past the grace window a stuck worker is stopped as before."""
from datetime import UTC, datetime, timedelta

from foreman.config import FactoryConfig
from foreman.models import (
FactoryAssessment, FactoryState, WorkerRecord, WorkerStatus, WorkerType,
)
from foreman.policy import FactoryPolicy

config = FactoryConfig(cold_start_grace_seconds=10.0, stuck_threshold=0.80)
policy = FactoryPolicy(config=config)
started = datetime.now(UTC) - timedelta(seconds=30) # grace expired
worker = WorkerRecord(
worker_id="worker-1", worker_type=WorkerType.CODING, mission="do work",
worker_id=worker.worker_id if False else "worker-1",
status=WorkerStatus.RUNNING, started_at=started,
)
state = FactoryState(
run_id="r1", job="job", repository="repo", max_workers=3, max_iterations=20,
)
state.workers.append(worker)
state.active_workers.append("worker-1")
assessment = FactoryAssessment(
implementation_complete=0.0, tests_sufficient=0.0, requirements_satisfied=0.0,
needs_verification=0.0, ready_to_finish=0.0, meaningful_progress=0.0,
worker_stuck=0.9, work_off_track=0.9, agents_md_drift=0.0, needs_human=0.0,
)
intervention = policy.decide(state, assessment)
assert intervention.action.value == "STOP_WORKER"
'''
open("tests/test_policy_grace.py", "w").write(test)
print("grace test written")
49 changes: 49 additions & 0 deletions apply_grace_patch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""Cold-start grace patch for foreman policy: a worker that has been alive
less than N seconds cannot be judged stuck/off-track — hermes boots + falls
back before producing evidence, and early assessments on empty diffs mislead
Jev. Implements a `cold_start_grace_seconds` config knob (default 0 = old
behavior)."""
import re

src = open("src/foreman/config.py").read()
if "cold_start_grace_seconds" not in src:
src = src.replace(
" steering_grace_seconds: float = Field(default=30.0, ge=0.0)",
" steering_grace_seconds: float = Field(default=30.0, ge=0.0)\n"
" cold_start_grace_seconds: float = Field(default=0.0, ge=0.0)",
)
src = src.replace(
' "FOREMAN_STEERING_GRACE_SECONDS": ("steering_grace_seconds", float),',
' "FOREMAN_STEERING_GRACE_SECONDS": ("steering_grace_seconds", float),\n'
' "FOREMAN_COLD_START_GRACE_SECONDS": ("cold_start_grace_seconds", float),',
)
open("src/foreman/config.py", "w").write(src)
print("config.py patched")
else:
print("config.py already patched")

# policy: skip stuck/off-track/drift stop for workers younger than the grace window
pol = open("src/foreman/policy.py").read()
if "cold_start_grace_seconds" not in pol:
anchor = " if active_id:\n off_track = assessment.work_off_track >= self.config.off_track_threshold"
grace = (
" if active_id:\n"
" # Cold-start grace: a freshly launched worker (hermes boots in\n"
" # ~5-10s and streams no evidence until it works) cannot be\n"
" # meaningfully judged stuck/off-track. Skip the stop/steer branch\n"
" # until it has had the configured window to produce evidence.\n"
" _active = next((w for w in state.workers if w.worker_id == active_id), None)\n"
" _age = (_active.duration_seconds if _active and _active.started_at else None) or 0.0\n"
" if _age < self.config.cold_start_grace_seconds:\n"
" return result(\n"
" InterventionType.CONTINUE,\n"
" \"active worker is within the cold-start grace period\",\n"
" active_id,\n"
" )\n"
" off_track = assessment.work_off_track >= self.config.off_track_threshold"
)
pol = pol.replace(anchor, grace)
open("src/foreman/policy.py", "w").write(pol)
print("policy.py patched")
else:
print("policy.py already patched")
11 changes: 11 additions & 0 deletions check_coalesce.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
"""Check the new test_noisy_events_are_coalesced failure — is it caused by
the grace patch (policy now returns CONTINUE during grace, changing event
ordering) or pre-existing? Look at the failure detail."""
import subprocess

r = subprocess.run(
[".venv/Scripts/python", "-m", "pytest",
"tests/test_integration.py::test_noisy_events_are_coalesced", "-p", "no:cacheprovider"],
capture_output=True, text=True, timeout=120, encoding="utf-8", errors="replace",
)
print(r.stdout[-1800:])
15 changes: 15 additions & 0 deletions check_flake.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
"""The coalesce test is flaky (passed on rerun — timing-dependent, likely a
pre-existing flake under parallel load). The drift/steer failure is the
known Windows one. Verify the grace patch works: unit test for the grace
branch, then commit."""
import subprocess

r = subprocess.run(
[".venv/Scripts/python", "-m", "pytest",
"tests/test_integration.py::test_noisy_events_are_coalesced",
"tests/test_integration.py::test_noisy_events_are_coalesced",
"tests/test_integration.py::test_noisy_events_are_coalesced",
"-q", "-p", "no:cacheprovider"],
capture_output=True, text=True, timeout=180, encoding="utf-8", errors="replace",
)
print(r.stdout[-500:])
8 changes: 8 additions & 0 deletions check_grace_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
"""Check the collection error in test_policy_grace.py."""
import subprocess

r = subprocess.run(
[".venv/Scripts/python", "-m", "pytest", "tests/test_policy_grace.py", "-p", "no:cacheprovider"],
capture_output=True, text=True, timeout=120, encoding="utf-8", errors="replace",
)
print(r.stdout[-1200:])
14 changes: 14 additions & 0 deletions fix_grace_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"""Fix the duplicated worker_id kwarg in the second grace test."""
src = open("tests/test_policy_grace.py").read()
src = src.replace(
' worker_id=worker.worker_id if False else "worker-1",\n'
' status=WorkerStatus.RUNNING, started_at=started,',
' status=WorkerStatus.RUNNING, started_at=started,',
)
open("tests/test_policy_grace.py", "w").write(src)
print("fixed")
r = __import__("subprocess").run(
[".venv/Scripts/python", "-m", "pytest", "tests/test_policy_grace.py", "-q", "-p", "no:cacheprovider"],
capture_output=True, text=True, timeout=120, encoding="utf-8", errors="replace",
)
print(r.stdout[-400:])
18 changes: 18 additions & 0 deletions fix_state_kw.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"""FactoryState forbids extra - check the failing field. The extra_forbidden
error is likely from my WorkerRecord (worker_id duplicated earlier fixed) —
now the State: my tests pass max_workers=3 as kwarg but FactoryState may not
have it (it's on config). Check fields: run_id, job, repository, status,
iteration, max_iterations, workers... no max_workers. Remove those kwargs."""
import re

src = open("tests/test_policy_grace.py").read()
src = src.replace(
" state = FactoryState(\n run_id=\"r1\", job=\"job\", repository=\"repo\", max_workers=3, max_iterations=20,\n )",
" state = FactoryState(run_id=\"r1\", job=\"job\", repository=\"repo\", max_iterations=20)",
)
open("tests/test_policy_grace.py", "w").write(src)
r = __import__("subprocess").run(
[".venv/Scripts/python", "-m", "pytest", "tests/test_policy_grace.py", "-q", "-p", "no:cacheprovider"],
capture_output=True, text=True, timeout=120, encoding="utf-8", errors="replace",
)
print(r.stdout[-400:])
6 changes: 6 additions & 0 deletions src/foreman/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ class FactoryConfig(BaseModel):
steering_enabled: bool = True
max_steers_per_worker: int = Field(default=1, ge=0)
steering_grace_seconds: float = Field(default=30.0, ge=0.0)
cold_start_grace_seconds: float = Field(default=0.0, ge=0.0)
score_smoothing_alpha: float = Field(default=1.0, ge=0.0, le=1.0)
use_smoothed_scores: bool = False

human_threshold: float = Field(default=0.80, ge=0.0, le=1.0)
off_track_threshold: float = Field(default=0.80, ge=0.0, le=1.0)
Expand Down Expand Up @@ -78,6 +81,9 @@ def from_environment(cls) -> FactoryConfig:
),
"FOREMAN_MAX_STEERS_PER_WORKER": ("max_steers_per_worker", int),
"FOREMAN_STEERING_GRACE_SECONDS": ("steering_grace_seconds", float),
"FOREMAN_COLD_START_GRACE_SECONDS": ("cold_start_grace_seconds", float),
"FOREMAN_SCORE_SMOOTHING_ALPHA": ("score_smoothing_alpha", float),
"FOREMAN_USE_SMOOTHED_SCORES": ("use_smoothed_scores", _environment_bool),
}
values: dict[str, object] = {}
for env_name, (field_name, converter) in mapping.items():
Expand Down
2 changes: 2 additions & 0 deletions src/foreman/models/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ class FactoryState(BaseModel):
consecutive_assessment_failures: int = Field(default=0, ge=0)
verification_started: bool = False
verification_completed: bool = False
finish_thresholds_met: bool = False
smoothed_scores: dict[str, float] = Field(default_factory=dict)

@model_validator(mode="after")
def validate_worker_references(self) -> FactoryState:
Expand Down
54 changes: 52 additions & 2 deletions src/foreman/policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,33 @@ class FactoryPolicy:
def decide(self, state: FactoryState, assessment: FactoryAssessment) -> Intervention:
iteration = max(1, state.iteration)

# EMA score smoothing: per-assessment scores are independent and
# oscillate across backends (observed hermes: impl 0.75 ↔ 0.45,
# tests 0.16 ↔ 0.43 alternating while work is stable). Thresholding
# the smoothed estimate tracks genuine movement instead of noise.
# alpha=1 disables smoothing (default, upstream behavior).
smoothing_fields = (
"implementation_complete",
"tests_sufficient",
"requirements_satisfied",
"ready_to_finish",
"needs_human",
"needs_verification",
"meaningful_progress",
"worker_stuck",
"work_off_track",
"agents_md_drift",
)
if self.config.use_smoothed_scores and self.config.score_smoothing_alpha < 1.0:
alpha = self.config.score_smoothing_alpha
prev = state.smoothed_scores
for name in smoothing_fields:
raw = float(getattr(assessment, name))
prev_val = prev.get(name)
smoothed = raw if prev_val is None else alpha * raw + (1 - alpha) * prev_val
state.smoothed_scores[name] = smoothed
setattr(assessment, name, smoothed)

def result(
action: InterventionType, reason: str, worker_id: str | None = None
) -> Intervention:
Expand All @@ -41,6 +68,18 @@ def result(
return result(InterventionType.ESCALATE, "maximum Foreman iterations reached")

if active_id:
# Cold-start grace: a freshly launched worker (hermes boots in
# ~5-10s and streams no evidence until it works) cannot be
# meaningfully judged stuck/off-track. Skip the stop/steer branch
# until it has had the configured window to produce evidence.
_active = next((w for w in state.workers if w.worker_id == active_id), None)
_age = (_active.duration_seconds if _active and _active.started_at else None) or 0.0
if _age < self.config.cold_start_grace_seconds:
return result(
InterventionType.CONTINUE,
"active worker is within the cold-start grace period",
active_id,
)
off_track = assessment.work_off_track >= self.config.off_track_threshold
agents_drift = assessment.agents_md_drift >= self.config.agents_drift_threshold
stuck = assessment.worker_stuck >= self.config.stuck_threshold
Expand Down Expand Up @@ -97,12 +136,23 @@ def result(
and assessment.requirements_satisfied >= self.config.requirements_threshold
and assessment.tests_sufficient >= self.config.tests_threshold
)
if finish_ready:
# Sticky: persist so later noisy/idle assessments still finish
# (semantic scores are independent per assessment and oscillate
# across backends — observed hermes: 0.37 mid-work → 0.24 idle).
state.finish_thresholds_met = True
finish_met = state.finish_thresholds_met or finish_ready
verification_resolved = (
state.verification_completed
or assessment.needs_verification < self.config.verification_threshold
)
if not active_id and finish_ready and verification_resolved:
return result(InterventionType.FINISH, "completion thresholds satisfied")
if not active_id and finish_met and verification_resolved:
if finish_ready:
return result(InterventionType.FINISH, "completion thresholds satisfied")
return result(
InterventionType.FINISH,
"completion thresholds met earlier; idle reassessment finishes the job",
)

should_verify = (
not active_id
Expand Down
Loading