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
59 changes: 59 additions & 0 deletions add_obs_tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""Unit tests for untracked_evidence + pytest parser."""
test = '''
from pathlib import Path

from foreman.observation import ObservationBuilder, _pytest_summary_from_output, _untracked_evidence


def test_untracked_evidence_captures_new_test_file(tmp_path: Path) -> None:
(tmp_path / "test_new.py").write_text("def test_x():\\n assert True\\n", encoding="utf-8")
evidence = _untracked_evidence(tmp_path, "?? test_new.py", 12000)
assert "untracked: test_new.py" in evidence
assert "test_x" in evidence


def test_untracked_evidence_skips_binary_and_dirs(tmp_path: Path) -> None:
(tmp_path / "blob.bin").write_bytes(b"\\x00\\x01\\x02\\x00binary")
(tmp_path / "subdir").mkdir()
evidence = _untracked_evidence(tmp_path, "?? blob.bin\\n?? subdir/", 12000)
assert evidence == ""


def test_untracked_evidence_truncates_large_files(tmp_path: Path) -> None:
big = tmp_path / "big.txt"
big.write_text("x" * 9000, encoding="utf-8")
evidence = _untracked_evidence(tmp_path, "?? big.txt", 6000)
assert "truncated" in evidence
assert len(evidence) < 9000


def test_pytest_parser_extracts_pass_and_fail() -> None:
output = "running...\\n================= 2 passed in 0.01s =================\\ndone"
results = _pytest_summary_from_output(output)
assert len(results) == 1
assert results[0]["passed"] == 2
assert results[0]["failed"] == 0


def test_pytest_parser_extracts_failures() -> None:
output = "=========== 1 failed, 3 passed in 1.20s ==========="
results = _pytest_summary_from_output(output)
assert results[0]["passed"] == 3
assert results[0]["failed"] == 1


def test_pytest_parser_ignores_non_summary_lines() -> None:
assert _pytest_summary_from_output("just some text\\n2 passed something else entirely") == []
'''
open("tests/test_observation_evidence.py", "w").write(test)
import subprocess
r = subprocess.run(
[".venv/Scripts/python", "-m", "pytest", "tests/test_observation_grace_probe.py",
"tests/test_observation.py", "-q", "-p", "no:cacheprovider"],
capture_output=True, text=True, timeout=120, encoding="utf-8", errors="replace",
)
r2 = subprocess.run(
[".venv/Scripts/python", "-m", "pytest", "tests/test_observation.py", "-q", "-p", "no:cacheprovider"],
capture_output=True, text=True, timeout=120, encoding="utf-8", errors="replace",
)
print(r2.stdout[-400:])
26 changes: 26 additions & 0 deletions calib_step1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""Calibration fix candidates for the hermes evidence gap.

Fix 1: `git diff` misses UNTRACKED files (test_calc.py is `??`). Jev never
sees the test file content -> tests_sufficient stays ~0.05. Add
`git diff` + intent-to-add trick: `git add -N .` makes untracked files
appear in diff. Do it in the observation builder? No — mutating the repo
from an observer is wrong. Better: capture untracked file contents
separately into the observation via git status --porcelain parsing +
reading the files (bounded).

Simpler: add a `git ls-files --others --exclude-standard` list to
git_status evidence so Jev at least sees untracked file NAMES, and raise
the per-line cap. Let me check how git_status flows into the observation.
"""
import subprocess

r = subprocess.run(
["grep", "-n", "git_status\|test_results", "C:/repos/foreman/src/foreman/foreman/jev.py"],
capture_output=True, text=True, timeout=30,
)
print(r.stdout)
r2 = subprocess.run(
["sed", "-n", "121,160p", "C:/repos/foreman/src/foreman/foreman/jev.py"],
capture_output=True, text=True, timeout=30,
)
print(r2.stdout)
35 changes: 35 additions & 0 deletions calib_step2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""Calibration fix 1: untracked-file evidence.

`git diff` never shows untracked files. hermes workers write test_calc.py as
a NEW file -> it's untracked -> the diff (Jev's main implementation evidence)
only shows calc.py, and the test file is invisible except as a name in
git_status. Fix: in ObservationBuilder, run `git add --intent-to-add`-free
approach — capture untracked file NAMES via status porcelain (already there)
and extend the diff evidence with `git diff --no-index /dev/null <file>`-style
content? Simpler + non-mutating: `git ls-files --others --exclude-standard`
list is already in git_status (?? lines). The real gap is CONTENT of untracked
test files.

Plan: add an `untracked_evidence` field to FactoryObservation: for each
untracked *.py/*.md file (bounded count+size), include the head of its
content. Then Jev can see test_calc.py's tests.

Steps:
1. observation.py: parse git_status ?? entries; read bounded content of each
(up to 3 files, 4k chars each) into new field `untracked_evidence: str`.
2. Add to FactoryObservation model.
3. Unit test.
"""
import re

# 1. Model field
obs = open("src/foreman/observation.py").read()
if "untracked_evidence" not in obs:
obs = obs.replace(
" git_status: str\n git_diff: str",
" git_status: str\n git_diff: str\n untracked_evidence: str = \"\"",
)
open("src/foreman/observation.py", "w").write(obs)
print("model field added")
else:
print("model field already present")
67 changes: 67 additions & 0 deletions calib_step3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"""Calibration fix 1b: populate untracked_evidence in ObservationBuilder.build."""

src = open("src/foreman/observation.py").read()

helper = '''

def _untracked_evidence(repository: Path, git_status: str, limit: int) -> str:
"""Bounded head-of-content for untracked files named in git_status.

hermes-style workers write test files as new (untracked) files; `git diff`
never shows them, leaving the supervisor without test evidence. Include a
bounded excerpt of each untracked text file (up to 3 files, ~4k chars
total) so assessments can see new tests/source. Binary-looking files are
skipped. Read-only: the repository is never mutated.
"""
paths: list[str] = []
for line in git_status.splitlines():
line = line.strip()
if line.startswith("?? "):
candidate = line[3:].strip().strip('"')
if candidate and not candidate.endswith("/"):
paths.append(candidate)
if not paths:
return ""

per_file = max(500, limit // 3)
chunks: list[str] = []
collected = 0
for name in paths[:3]:
path = repository / name
try:
if not path.is_file() or path.stat().st_size > 1_000_000:
continue
raw = path.read_bytes()
except OSError:
continue
if b"\\x00" in raw[:4096]:
continue # binary
text = raw.decode("utf-8", errors="replace")
excerpt = text[:per_file]
if len(text) > per_file:
excerpt += f"\\n... (truncated, {len(text)} chars total)"
chunks.append(f"--- untracked: {name} ---\\n{excerpt}")
collected += len(excerpt)
if collected >= limit:
break
return "\\n".join(chunks)

'''

if "_untracked_evidence" not in src:
# insert helper before ObservationBuilder
src = src.replace(
"class ObservationBuilder:",
helper + "\n\nclass ObservationBuilder:",
)
# populate the field in build()
src = src.replace(
' git_status=git_status,\n git_diff=git_diff,',
' git_status=git_status,\n'
' git_diff=git_diff,\n'
' untracked_evidence=_untracked_evidence(repository, git_status, min(self.config.diff_limit, 12_000)),',
)
open("src/foreman/observation.py", "w").write(src)
print("builder patched")
else:
print("builder already patched")
58 changes: 58 additions & 0 deletions calib_step4.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""Add a unit test for untracked_evidence, then calibration fix 2:
TEST_RESULT evidence from worker output. When a worker's stdout contains
pytest-style results ('N passed'), foreman's test_results list is empty —
Jev's tests_sufficient has nothing to key on. Parse pytest lines from worker
stdout into test_results entries in the observation."""
src = open("src/foreman/observation.py").read()

if "PYTEST_LINE" not in src:
src = src.replace(
"import asyncio\nfrom datetime import UTC, datetime",
"import asyncio\nimport re\nfrom datetime import UTC, datetime",
)
helper = '''

_PYTEST_LINE = re.compile(
r"^(?:=+\\s*)?(?P<count>\\d+)\\s+passed(?P<failed>.*?)(?:\\s+in\\s+(?P<time>[\\d.]+)s)?(?:\\s*=+)?\\s*$"
)


def _pytest_summary_from_output(output: str) -> list[dict[str, Any]]:
"""Extract pytest summary lines from worker output into test_results
entries so assessments can key on executed test evidence even when the
backend streams no structured events (hermes buffers NDJSON on Windows).
"""
results: list[dict[str, Any]] = []
for line in output.splitlines():
match = _PYTEST_LINE.match(line.strip())
if match:
passed = int(match.group("count"))
failed_text = (match.group("failed") or "").strip()
failed = 0
failed_match = re.search(r"(\\d+)\\s+failed", failed_text)
if failed_match:
failed = int(failed_match.group(1))
results.append(
{
"source": "worker_output",
"passed": passed,
"failed": failed,
"summary": line.strip()[:200],
}
)
return results

'''
src = src.replace("\n\nclass ObservationBuilder:", helper + "\n\nclass ObservationBuilder:", 1)
src = src.replace(
" test_results=[],",
" test_results=_pytest_summary_from_output(\n"
" (latest.stdout or \"\") + \"\\n\" + (latest.stderr or \"\")\n"
" )\n"
" if latest\n"
" else [],",
)
open("src/foreman/observation.py", "w").write(src)
print("pytest parser added")
else:
print("already present")
7 changes: 7 additions & 0 deletions debug_parser.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
"""Debug the 2 parser failures: check what the regex matches."""
import sys
sys.path.insert(0, "src")
from foreman.observation import _pytest_summary_from_output

print("failed+passed:", _pytest_summary_from_output("=========== 1 failed, 3 passed in 1.20s ==========="))
print("junk line:", _pytest_summary_from_output("just some text\n2 passed something else entirely"))
49 changes: 49 additions & 0 deletions fix_parser.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""Fix the regex: pytest summary is 'N failed, M passed in Xs' — failed comes
BEFORE passed. Rewrite the parser to handle both orders and require 'in Xs'
suffix (the junk line lacks it)."""

src = open("src/foreman/observation.py").read()
old = src[src.find("_PYTEST_LINE = re.compile"):src.find("def _pytest_summary_from_output")]
new = '''_PYTEST_LINE = re.compile(
r"^(?:=+\\s*)?"
r"(?P<parts>(?:(?:\\d+\\s+\\w+)(?:,\\s*)?)+)"
r"\\s+in\\s+(?P<time>[\\d.]+)s"
"(?:\\\\s*=+)?\\\\s*$"
)


def _pytest_summary_from_output(output: str) -> list[dict[str, Any]]:
"""Extract pytest summary lines from worker output into test_results
entries so assessments can key on executed test evidence even when the
backend streams no structured events (hermes buffers NDJSON on Windows).
Handles 'N passed', 'N failed, M passed', 'N error' orderings.
"""
results: list[dict[str, Any]] = []
for line in output.splitlines():
match = _PYTEST_LINE.match(line.strip())
if not match:
continue
parts = {m.group(2).lower(): int(m.group(1)) for m in re.finditer(r"(\\d+)\\s+(\\w+)", match.group("parts"))}
if not parts:
continue
results.append(
{
"source": "worker_output",
"passed": parts.get("passed", 0),
"failed": parts.get("failed", 0) + parts.get("error", 0),
"summary": line.strip()[:200],
}
)
return results

'''
src = src.replace(old, new)
open("src/foreman/observation.py", "w").write(src)
print("parser rewritten")

# fix the test expectation for junk line (still shouldn't match: no 'in Xs')
r = __import__("subprocess").run(
[".venv/Scripts/python", "-m", "pytest", "tests/test_observation_evidence.py", "-q", "-p", "no:cacheprovider"],
capture_output=True, text=True, timeout=120, encoding="utf-8", errors="replace",
)
print(r.stdout[-400:])
17 changes: 17 additions & 0 deletions fix_parser2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
"""Group numbering bug: m.group(2) doesn't exist — the inner finditer groups
are separate. Use named groups in the parts pattern or simpler non-capturing
outer. Fix by finding all 'N word' pairs from the matched segment."""
src = open("src/foreman/observation.py").read()
src = src.replace(
' parts = {m.group(2).lower(): int(m.group(1)) for m in re.finditer(r"(\\d+)\\s+(\\w+)", match.group("parts"))}',
' parts = {\n'
' word.lower(): int(count)\n'
' for count, word in re.findall(r"(\\d+)\\s+([A-Za-z]+)", match.group("parts"))\n'
' }',
)
open("src/foreman/observation.py", "w").write(src)
r = __import__("subprocess").run(
[".venv/Scripts/python", "-m", "pytest", "tests/test_observation_evidence.py", "-q", "-p", "no:cacheprovider"],
capture_output=True, text=True, timeout=120, encoding="utf-8", errors="replace",
)
print(r.stdout[-300:])
59 changes: 59 additions & 0 deletions fix_parser3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""The old function body is still there after the new one (my replace only
swapped the header+regex, leaving a duplicate function def). Consolidate:
keep ONE _pytest_summary_from_output with the fixed body. Rewrite the whole
region cleanly with python."""

src = open("src/foreman/observation.py").read()
start = src.find("_PYTEST_LINE = re.compile")
# find the END of the duplicated function: the second 'def _pytest_summary_from_output' + its body end
# Simplest: find the marker 'return results' second occurrence end
first_def = src.find("def _pytest_summary_from_output")
second_def = src.find("def _pytest_summary_from_output", first_def + 10)
# find end of second function: next 'def ' or 'class ' at module level after second_def
import re as _re
m = _re.search(r"\n(def |class )", src[second_def + 10:])
end = second_def + 10 + m.start() if m else len(src)
# remove from first _PYTEST_LINE def through end of second function, then insert one clean version
new_block = '''_PYTEST_LINE = re.compile(
r"^(?:=+\\\\s*)?"
r"(?P<parts>(?:(?:\\\\d+\\\\s+\\\\w+)(?:,\\\\s*)?)+)"
r"\\\\s+in\\\\s+(?P<time>[\\\\d.]+)s"
r"(?:\\\\s*=+)?\\\\s*$"
)


def _pytest_summary_from_output(output: str) -> list[dict[str, Any]]:
"""Extract pytest summary lines from worker output into test_results
entries so assessments can key on executed test evidence even when the
backend streams no structured events (hermes buffers NDJSON on Windows).
Handles 'N passed', 'N failed, M passed', 'N error' orderings.
"""
results: list[dict[str, Any]] = []
for line in output.splitlines():
match = _PYTEST_LINE.match(line.strip())
if not match:
continue
parts = {
word.lower(): int(count)
for count, word in re.findall(r"(\\d+)\\s+([A-Za-z]+)", match.group("parts"))
}
if not parts:
continue
results.append(
{
"source": "worker_output",
"passed": parts.get("passed", 0),
"failed": parts.get("failed", 0) + parts.get("error", 0),
"summary": line.strip()[:200],
}
)
return results

'''
src = src[:start] + new_block + src[end:]
open("src/foreman/observation.py", "w").write(src)
r = __import__("subprocess").run(
[".venv/Scripts/python", "-m", "pytest", "tests/test_observation_evidence.py", "-q", "-p", "no:cacheprovider"],
capture_output=True, text=True, timeout=120, encoding="utf-8", errors="replace",
)
print(r.stdout[-300:])
Loading