Skip to content
Open
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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,14 @@ All notable changes to SkillOpt are documented here. This project adheres to
or directly after a negation (`no thanks`, `not great`) no longer counts as
approval, and curly apostrophes are normalized so `didn’t` is detected
(thanks @Vidwaansinghania, #457).
- SkillOpt-Sleep's heuristic miner respects the order of feedback. Its
docstring says "negative feedback present and no later positive -> fail",
but any negative signal gave `fail`, so a session where the user said
"that's wrong" and then "perfect, thanks" was mined as a failed task. The
Claude Code harvester now records signals per user turn
(`SessionDigest.feedback_by_turn`), and a task whose last negative turn is
followed by approval is mined as `success`. Harvesters that do not record
turn order keep the old rule (thanks @Vidwaansinghania).

### Security
- Prevent managed-identity credentials from being sent to non-Azure or
Expand Down
6 changes: 5 additions & 1 deletion skillopt_sleep/harvest.py
Original file line number Diff line number Diff line change
Expand Up @@ -542,6 +542,7 @@ def digest_transcript(path: str) -> Optional[SessionDigest]:
skills: List[str] = []
files: List[str] = []
feedback: List[str] = []
feedback_by_turn: List[List[str]] = []
n_user = 0
n_asst = 0

Expand Down Expand Up @@ -588,7 +589,9 @@ def digest_transcript(path: str) -> Optional[SessionDigest]:
if text and not _is_meta_prompt(text):
n_user += 1
user_prompts.append(text.strip())
feedback.extend(_detect_feedback(text))
turn_signals = _detect_feedback(text)
feedback.extend(turn_signals)
feedback_by_turn.append(turn_signals)
elif role == "assistant":
n_asst += 1
tools.extend(_tool_names_from_content(content))
Expand Down Expand Up @@ -622,6 +625,7 @@ def _dedup(xs: List[str]) -> List[str]:
skills_used=_dedup(skills),
files_touched=_dedup(files),
feedback_signals=feedback,
feedback_by_turn=feedback_by_turn,
n_user_turns=n_user,
n_assistant_turns=n_asst,
raw_path=path,
Expand Down
24 changes: 24 additions & 0 deletions skillopt_sleep/mine.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,25 @@ def _looks_positive(signals: List[str]) -> bool:
return any(s.startswith("pos:") for s in signals)


def _approved_after_last_negative(digest: SessionDigest) -> bool:
"""True if a user turn after the last negative one carries approval.

Needs the per-turn signals. The order is trusted only when
``feedback_signals`` is exactly those turns joined together: a harvester
that adds signals of its own (a tool error, a failed turn) or de-duplicates
them cannot say where they fall, so the unordered rule applies.
"""
turns = digest.feedback_by_turn or []
if not turns:
return False
if [s for turn in turns for s in turn] != list(digest.feedback_signals or []):
return False
negative_turns = [i for i, turn in enumerate(turns) if _looks_negative(turn)]
if not negative_turns:
return False
return any(_looks_positive(turn) for turn in turns[negative_turns[-1] + 1:])


_TARGET_STOPWORDS = {
"about", "after", "again", "agent", "agents", "all", "also", "always",
"and", "any", "are", "before", "being", "but", "can", "codex",
Expand Down Expand Up @@ -166,6 +185,9 @@ def heuristic_mine(
- positive feedback present -> "success"
- re-asks (multiple user turns) without resolution -> "mixed"
- otherwise -> "unknown"
"Later" needs turn order, so it applies when the harvester records
``feedback_by_turn`` (the Claude Code harvester does). Without it, any
negative signal gives "fail", as before.
* attempted_solution = the last assistant final (what was produced).
* reference_kind defaults to "none"; the consolidation step will use a
rubric judge for these. (Exact refs are added by the experiment data
Expand All @@ -180,6 +202,8 @@ def heuristic_mine(
continue
if _looks_positive(d.feedback_signals) and not _looks_negative(d.feedback_signals):
outcome = "success"
elif _approved_after_last_negative(d):
outcome = "success"
elif _looks_negative(d.feedback_signals):
outcome = "fail"
elif d.n_user_turns >= 3:
Expand Down
6 changes: 6 additions & 0 deletions skillopt_sleep/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ class SessionDigest:
skills_used: List[str] = field(default_factory=list)
files_touched: List[str] = field(default_factory=list)
feedback_signals: List[str] = field(default_factory=list) # "still broken", "perfect", ...
# The same signals grouped by user turn, in transcript order, so the miner
# can tell "wrong" followed by "perfect, thanks" from the reverse. Optional
# and default-empty: harvesters that do not record turn order, and digests
# persisted before this field existed, leave it [] and keep the unordered
# outcome rule.
feedback_by_turn: List[List[str]] = field(default_factory=list)
n_user_turns: int = 0
n_assistant_turns: int = 0
raw_path: str = ""
Expand Down
142 changes: 142 additions & 0 deletions tests/test_sleep_feedback_order.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
"""The heuristic miner respects the order of feedback within a session.

``heuristic_mine`` documents "negative feedback present and no later positive
-> fail". Before per-turn signals were recorded, any negative signal gave
"fail", so a session where the user said "that's wrong" and then "perfect,
thanks" was mined as a failure.

Pure-stdlib (unittest), deterministic, no API key, no third-party deps.
Run: python -m pytest tests/test_sleep_feedback_order.py
"""
from __future__ import annotations

import json
import os
import tempfile
import unittest

from skillopt_sleep.harvest import digest_transcript
from skillopt_sleep.mine import heuristic_mine
from skillopt_sleep.types import SessionDigest


def _digest(turns, *, signals=None, by_turn=True):
"""A digest whose user turns carry the given per-turn signals."""
flat = [s for turn in turns for s in turn]
return SessionDigest(
session_id="s1",
project="/p",
user_prompts=[f"user request number {i}" for i in range(len(turns))],
assistant_finals=["done"],
feedback_signals=flat if signals is None else signals,
feedback_by_turn=[list(t) for t in turns] if by_turn else [],
n_user_turns=len(turns),
)


def _outcome(digest):
tasks = heuristic_mine([digest])
assert len(tasks) == 1
return tasks[0].outcome


class TestOrderedOutcome(unittest.TestCase):
def test_negative_then_later_approval_is_success(self):
d = _digest([[], ["neg:wrong"], ["pos:perfect", "pos:thanks"]])
self.assertEqual(_outcome(d), "success")

def test_approval_then_later_negative_is_fail(self):
d = _digest([[], ["pos:thanks"], ["neg:still broken"]])
self.assertEqual(_outcome(d), "fail")

def test_negative_and_positive_in_the_last_turn_is_fail(self):
# "thanks, but it's still broken"
d = _digest([[], ["neg:still broken", "pos:thanks"]])
self.assertEqual(_outcome(d), "fail")

def test_negative_after_approval_after_negative_is_fail(self):
d = _digest([["neg:wrong"], ["pos:thanks"], ["neg:broken"]])
self.assertEqual(_outcome(d), "fail")

def test_only_negative_is_still_fail(self):
d = _digest([[], ["neg:wrong"]])
self.assertEqual(_outcome(d), "fail")

def test_only_positive_is_still_success(self):
d = _digest([[], ["pos:thanks"]])
self.assertEqual(_outcome(d), "success")


class TestFallsBackWithoutTrustworthyOrder(unittest.TestCase):
def test_without_per_turn_signals_any_negative_is_fail(self):
# Harvesters that do not record order, and digests persisted before
# the field existed, keep the old rule.
d = _digest([["neg:wrong"], ["pos:thanks"]], by_turn=False)
self.assertEqual(_outcome(d), "fail")

def test_signal_outside_any_turn_disables_ordering(self):
# A harvester-added signal (e.g. a tool error) has no turn position.
d = _digest(
[["neg:wrong"], ["pos:thanks"]],
signals=["neg:wrong", "pos:thanks", "neg:tool_error"],
)
self.assertEqual(_outcome(d), "fail")

def test_persisted_digest_without_the_field_loads(self):
old = {
"session_id": "s1", "project": "/p", "user_prompts": ["Fix the export bug"],
"feedback_signals": ["neg:wrong", "pos:thanks"], "n_user_turns": 2,
}
known = set(SessionDigest.__dataclass_fields__)
d = SessionDigest(**{k: v for k, v in old.items() if k in known})
self.assertEqual(d.feedback_by_turn, [])
self.assertEqual(_outcome(d), "fail")


def _user(text):
return {"type": "user", "message": {"role": "user", "content": text}}


def _assistant(text):
return {"type": "assistant", "message": {"role": "assistant", "content": text}}


class TestClaudeHarvesterRecordsTurns(unittest.TestCase):
def _harvest(self, rows):
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "session.jsonl")
with open(path, "w", encoding="utf-8") as handle:
handle.write("\n".join(json.dumps(row) for row in rows))
return digest_transcript(path)

def test_signals_are_grouped_by_user_turn(self):
digest = self._harvest([
_user("Export the report as CSV"),
_assistant("Here is the CSV."),
_user("The totals column is wrong"),
_assistant("Fixed the totals."),
_user("Perfect, thanks"),
])

self.assertEqual(len(digest.feedback_by_turn), 3)
self.assertEqual(digest.feedback_by_turn[0], [])
self.assertIn("neg:wrong", digest.feedback_by_turn[1])
self.assertTrue(all(s.startswith("pos:") for s in digest.feedback_by_turn[2]))
self.assertEqual(
[s for turn in digest.feedback_by_turn for s in turn],
digest.feedback_signals,
)
self.assertEqual(_outcome(digest), "success")

def test_session_left_broken_is_still_a_failure(self):
digest = self._harvest([
_user("Export the report as CSV"),
_assistant("Here is the CSV."),
_user("Thanks. Hmm, the totals column is still wrong"),
])

self.assertEqual(_outcome(digest), "fail")


if __name__ == "__main__":
unittest.main()