Skip to content

Implement multi-turn conversation features with validation and reporting - #136

Merged
roark47 merged 22 commits into
mainfrom
feat/multi-turn-conversation
Jul 8, 2026
Merged

roark47 merged 22 commits into
mainfrom
feat/multi-turn-conversation

Conversation

@roark47

@roark47 roark47 commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator

This pull request introduces comprehensive support for multi-turn conversation evaluation, including new YAML configuration options for defining sequential user turns, per-turn gating and variable capture, and per-turn judge assertions. It also adds session resumption capabilities for supported agent engines, ensuring that conversations can be resumed across turns. Documentation and end-to-end tests have been updated to reflect these new features.

Multi-turn conversation evaluation:

  • Added support for defining input.turns in eval YAMLs, allowing sequential user turns with post_condition gates (must_contain_all, must_contain_any, must_not_contain, on_fail) and capture for regex-based variable extraction between turns. [1] [2] [3] [4] [5]
  • Introduced per-turn judge assertions (turn_response_contains, turn_response_not_contains, tool_called_in_turn, tool_not_called_in_turn), all scoped by turn number, for more granular evaluation. [1] [2] [3] [4] [5]

Session resumption and agent changes:

  • Implemented the SessionResumer interface for agents (notably ClaudeCodeAgent and QoderCLIAgent), allowing session resumption via engine-specific mechanisms (e.g., --resume for Claude, -r for QoderCLI). Added SessionID to SessionResult and new agent methods to support multi-turn flows. [1] [2] [3] [4] [5] [6]

Documentation updates:

  • Expanded both English and Chinese guides to document multi-turn YAML syntax, the difference between input.prompt and input.turns, post_condition semantics, variable capture, agent support matrix, and per-turn judge assertions. [1] [2]

End-to-end test updates:

  • Updated and expanded eval cases to use the new multi-turn format, including iterative refinement and phase-gated workflows, with per-turn gating, capture, and judge assertions. [1] [2] [3] [4]

Internal utilities and test coverage:

  • Added utility and tests for extracting session IDs from file paths, improving robustness of session management in agent code.

These changes collectively enable robust, fine-grained evaluation of multi-turn agent workflows, with improved reporting and documentation.

roark47 added 14 commits July 6, 2026 14:07
Add schema types and validation rules for multi-turn conversation evaluation:

Schema changes (internal/config/schema.go):
- Turn.Capture []CaptureRule for variable extraction from responses
- Turn.TimeoutSeconds for per-turn timeout control
- PostCondition.MustContainAll and MustNotContain fields
- CaptureRule type (Variable, Pattern, JSONPath)
- TurnResponseContainsRule, TurnResponseNotContainsRule
- ToolCalledInTurnRule, ToolNotCalledInTurnRule
- Rule struct extended with 4 per-turn assertion fields

Validation changes (internal/config/validator.go):
- Reject ambiguous input.prompt + input.turns combination
- Enforce input.turns[*].role must be "user"
- Validate post_condition.on_fail enum (fail, skip_remaining)
- Require at least one check in post_condition
- Validate capture variable identifier pattern
- Enforce exactly one extractor per capture rule
- Compile-time regex validation for capture patterns
- Per-turn judge rules: turn number range checks
- Required fields for turn_response_contains/not_contains
- Required name for tool_called_in_turn/tool_not_called_in_turn

All existing tests pass unchanged (backward compatible).
Introduce SessionResumer optional interface and SessionResult.SessionID field
to support multi-turn conversation evaluation:

Interface (internal/agent/agent.go):
- SessionResult.SessionID string field for session tracking across turns
- SessionResumer interface with RunTurn method
- Compile-time satisfaction checks for ClaudeCodeAgent, QoderCLIAgent

ClaudeCodeAgent (internal/agent/claude_code.go):
- Run populates SessionResult.SessionID from generated UUID
- RunTurn: empty sessionID delegates to Run (first turn)
- RunTurn: non-empty sessionID uses --resume flag
- buildClaudeResumeCmd for session resume commands
- Extract claudeRunEnvVars and handleClaudeRunResult helpers

QoderCLIAgent (internal/agent/qodercli.go):
- buildSessionResult extracts SessionID from session JSONL filename
- RunTurn: empty sessionID delegates to Run (first turn)
- RunTurn: non-empty sessionID uses -r flag
- buildQoderResumeCmd for session resume commands

Utilities (internal/agent/session_lookup.go):
- extractSessionIDFromPath strips directory and extension

All existing tests pass unchanged (backward compatible).
Implement the evaluator multi-turn engine that orchestrates per-turn
agent execution with post-condition gates, variable capture, and
template substitution:

Types (internal/evaluator/multiturn.go):
- TurnStatus: completed, skipped, failed, error
- TurnResult: per-turn outcome with response, transcript, captured vars
- multiTurnState: mutable state for the multi-turn loop

Engine (internal/evaluator/multiturn.go):
- executeMultiTurn: main loop — template substitution, agent invocation,
  post-condition evaluation, variable capture, result aggregation
- executeSingleTurn: per-turn timeout + resumer invocation
- buildTurnResult: construct TurnResult from agent SessionResult
- handlePostCondition: on_fail=fail (abort) / skip_remaining (mark rest)
- evaluatePostCondition: must_contain_all/any, must_not_contain checks
- captureVariables: regex named group (?P<value>...) or first group
- substituteTemplate: {{variable}} replacement with unresolved error
- buildAggregateResult: merge per-turn metrics into final SessionResult
- multiTurnStatus: derive case status from turn outcomes

Integration (internal/evaluator/evaluator.go):
- EvalResult.TurnResults []TurnResult field for per-turn data
- executeCaseOnce branches to multi-turn when len(turns)>1 AND agent
  implements SessionResumer; non-resumer agents fall through to the
  existing batch Run path (backward compatible)

Tests (internal/evaluator/multiturn_test.go):
- TestSubstituteTemplate (6 cases)
- TestEvaluatePostCondition (8 cases)
- TestCaptureVariables (6 cases)
- TestMultiTurnStatus (5 cases)
- TestExecuteMultiTurn_HappyPath
- TestExecuteMultiTurn_PostConditionFail
- TestExecuteMultiTurn_PostConditionSkipRemaining
- TestExecuteMultiTurn_TemplateSubstitution
- TestExecuteMultiTurn_AgentError
- TestExecuteMultiTurn_NoResumer
- TestExecuteMultiTurn_UnresolvedTemplate
Post Conditions:
- extractCaptureValue rejects multiple unnamed capture groups (requires
  exactly one or a named group 'value')

Capture Variables:
- Add comprehensive test coverage for edge cases: multiple unnamed groups
  error, case-sensitivity in post_condition matchers, named group priority

Tests:
- TestCaptureVariables_EdgeCases: multi-group error, named+unnamed priority
- TestPostConditionCaseSensitivity: explicit case-sensitive assertion
- TestExtractCaptureValue: unit tests for the extraction helper
- Split long test functions to satisfy funlen linter (80 stmt limit)

Lint:
- Replace fmt.Errorf (no formatting) with errors.New
- gofumpt formatting fixes
Judge Input:
- Add InputTurnResult type with TurnNumber, Content, Response,
  Transcript, Status, and Reason fields
- Add TurnResults []InputTurnResult field to judge.Input

Per-turn rule evaluators (internal/judge/rule_based.go):
- turn_response_contains: check contains_all/contains_any on a
  specific turn's response
- turn_response_not_contains: check forbidden keywords absence
- tool_called_in_turn: verify tool usage with optional partial args
- tool_not_called_in_turn: verify tool absence in a turn
- Shared lookupTurn helper: validates turn existence and completed
  status before content assertions

Evaluator wiring (internal/evaluator/evaluator.go):
- Add toJudgeTurnResults converter from evaluator.TurnResult to
  judge.InputTurnResult
- Pass TurnResults in judge.Input within evaluateCaseSession

Tests:
- 16 new test cases covering all 4 per-turn rules: positive/negative
  matching, missing turns, skipped turns, failed turns, args matching
- Table-driven patterns to satisfy dupl linter
CaseResult (internal/report/reporter.go):
- Add TurnResults []CaseTurnResult field (omitempty for backward compat)
- Define CaseTurnResult with TurnNumber, Content, Response, Status, Reason

JSON report:
- turn_results automatically serialized in result.json/report.json
- Omitted for single-turn cases (nil slice + omitempty)

HTML report (internal/report/html.go):
- Add embeddedTurn type and TurnResults field to embeddedCase
- caseTurnResultsToEmbedded converts report types to embedded JS data

JUnit report (internal/report/junit.go):
- buildFailureBody appends non-completed turn status/reason lines
- Turn-scoped assertion texts already contain turn numbers for CI

Runner wiring (internal/runner/runner.go):
- evalResultToCaseResult passes TurnResults via evalTurnResultsToReport
- Converter maps evaluator.TurnResult to report.CaseTurnResult
writing-evals.md (EN + ZH):
- New 'Multi-turn conversations' section covering input.prompt vs
  input.turns decision matrix, post_condition gate semantics,
  capture/template variable syntax, agent support matrix, and
  per-turn judge assertion examples.

e2e/testdata/multi-turn-conversation:
- phase-gate-skip-attempt.yaml: convert fake single-prompt to real
  input.turns with post_condition + turn_response_contains assertions.
- multi-turn-refinement.yaml: split into 2 real turns with capture
  and per-turn assertions.

skills/skill-upper:
- references/case-yaml.md: expand multi-turn section with capture
  field reference and per-turn judge assertion examples.
- assets/case.yaml.tmpl: add capture and per-turn judge commented
  examples.

CHANGELOG.md:
- Add [Unreleased] entries for multi-turn conversation feature,
  per-turn assertions, session resumption, and report TurnResults.
CodexAgent now implements the SessionResumer interface, enabling native
multi-turn conversation support via `codex resume <thread-id>`.

codex.go:
- Add RunTurn method: first turn (sessionID=="") delegates to Run;
  subsequent turns build a `codex resume --json` command with the
  thread ID obtained from the first turn's event stream.
- Set SessionResult.SessionID = streamParsed.threadID in buildSessionResult
  so the evaluator can pass it forward between turns.
- Add buildCodexResumeCmdWithLastMessage helper (mirrors the exec variant
  but uses `codex resume` subcommand with sessionID positional arg).

codex_test.go:
- TestCodexRunTurn_FirstTurnDelegatesToRun: verifies first turn uses
  `codex exec` and extracts thread ID into SessionID.
- TestCodexRunTurn_ResumeUsesCorrectCommand: verifies subsequent turns
  use `codex resume` with the session ID and instruction.
- TestBuildCodexResumeCmdWithLastMessage: unit test for command builder.

Docs: update agent support matrix in writing-evals.md (EN+ZH) and
CHANGELOG.md to reflect Codex multi-turn support.
The top-level 'codex resume' command is a TUI-only subcommand that does
not support --json, --skip-git-repo-check, or --output-last-message.

Switch to 'codex exec resume' which is the non-interactive equivalent
supporting all required flags. Remove the --sandbox flag from resume
commands since the session inherits sandbox settings from its initial
creation; use --dangerously-bypass-approvals-and-sandbox to ensure
non-interactive execution.
When assertions pass, the evidence field now includes the actual
keywords that were checked, making it possible to audit results
without referring back to the case YAML.

- turn_response_contains: evidence shows contains_all/contains_any lists
- turn_response_not_contains: evidence shows the forbidden keywords list
- output_contains: evidence shows all/any/not keyword lists
…lure

multiTurnStatus previously treated all TurnFailed results as hard
failures, skipping judge execution entirely. This broke the
on_fail=skip_remaining contract which is designed to skip subsequent
turns but still run the judge on whatever data was collected.

Distinguish the two modes by checking whether TurnSkipped entries
follow the failed turn — if so, it is a skip_remaining case and
the evaluator proceeds to judge evaluation.
- Show per-turn Prompt/Response cards when turn_results is available,
  replacing the previous single prompt/response view
- Synthesize FORMAL GRADES from turn post-condition failures when the
  judge was not executed (grading is null but turn_results has failures)
- Hide the top-level Prompt section for multi-turn cases to avoid
  showing only the first turn's content
@roark47
roark47 requested a review from zpzjzj July 7, 2026 03:45
@roark47 roark47 self-assigned this Jul 7, 2026
@roark47
roark47 requested a review from hittyt as a code owner July 7, 2026 03:45
@roark47 roark47 added the feature label Jul 7, 2026
@roark47
roark47 requested a review from Copilot July 7, 2026 03:45

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8fd23606d6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/evaluator/multiturn.go Resolved
Comment thread internal/evaluator/multiturn.go Resolved
Comment thread internal/evaluator/multiturn.go Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Note

Copilot couldn't run its full agentic review because no GitHub Actions runner was available. Make sure your repository has a runner available to run Copilot's review, or add a copilot-setup-steps.yml file specifying one with the runs-on attribute. See the docs for more details.

Adds first-class multi-turn evaluation support across config, evaluator, agents, judging, and reporting so scripted conversations can be executed turn-by-turn with gating, variable capture, and turn-scoped assertions.

Changes:

  • Introduces input.turns execution with per-turn post_condition, template substitution, and variable capture, plus aggregation into a single case result.
  • Adds session resumption (SessionResumer + SessionID) and implements RunTurn for supported CLI agents.
  • Extends rule-based judge + HTML/JUnit/JSON reporting to show and assert per-turn outcomes.

Reviewed changes

Copilot reviewed 32 out of 33 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
skills/skill-upper/references/case-yaml.md Documents capture and per-turn judge assertions in case YAML reference.
skills/skill-upper/assets/case.yaml.tmpl Updates scaffold template to include capture and per-turn judge rule examples.
internal/runner/runner.go Serializes evaluator turn results into report case results.
internal/report/templates/report.html Renders multi-turn conversations and synthesizes grading UI from turn failures.
internal/report/reporter.go Extends report JSON model with turn_results.
internal/report/junit.go Adds turn summary lines to JUnit failure body.
internal/report/html.go Embeds per-turn results into HTML report payload.
internal/judge/rule_based_test.go Adds unit tests for new per-turn rules.
internal/judge/rule_based.go Implements per-turn rule evaluators and improves evidence for output_contains.
internal/judge/judge.go Adds InputTurnResult and passes per-turn outcomes to judges.
internal/evaluator/multiturn_test.go Adds unit tests for multi-turn execution, gating, capture, and templating.
internal/evaluator/multiturn.go Implements the multi-turn execution engine (turn loop, gating, capture, aggregation).
internal/evaluator/evaluator.go Integrates multi-turn branch into case execution and passes turn results to judge input.
internal/config/validator_test.go Adds validation tests for turns, post conditions, capture, and per-turn judge rules.
internal/config/validator.go Enforces prompt/turns exclusivity and validates post_condition/capture/per-turn rule shapes.
internal/config/schema.go Extends schema for turns, capture rules, post_condition fields, and per-turn judge rules.
internal/agent/session_lookup.go Adds helper to derive session IDs from session file paths.
internal/agent/qodercli_test.go Tests qoder resume command and RunTurn behavior.
internal/agent/qodercli.go Implements session ID extraction + RunTurn resume flow for QoderCLI.
internal/agent/codex_test.go Tests Codex RunTurn behavior and resume command construction.
internal/agent/codex.go Implements RunTurn for Codex and populates SessionID.
internal/agent/claude_code_test.go Tests Claude resume command and RunTurn behavior including session ID propagation.
internal/agent/claude_code.go Populates SessionID, adds resume command builder, and implements RunTurn.
internal/agent/agent_test.go Tests extractSessionIDFromPath.
internal/agent/agent.go Adds SessionID to SessionResult and defines SessionResumer.
e2e/testdata/multi-turn-conversation/evals/cases/phase-gate-skip-attempt.yaml Converts E2E case to input.turns with per-turn judge assertions.
e2e/testdata/multi-turn-conversation/evals/cases/multi-turn-refinement.yaml Converts E2E case to multi-turn flow with gating + capture and per-turn assertions.
docs/zh/guide/writing-evals.md Documents multi-turn YAML, capture, agent support, and per-turn judge assertions (ZH).
docs/guide/writing-evals.md Documents multi-turn YAML, capture, agent support, and per-turn judge assertions (EN).
docs/design/multi-turn-conversation-implementation-plan.zh.md Adds Chinese design/implementation plan for multi-turn evaluation.
docs/design/multi-turn-conversation-implementation-plan.md Adds English design/implementation plan for multi-turn evaluation.
CHANGELOG.md Publishes 0.4.0 entry describing the multi-turn feature set.
.gitignore Ignores local verification workspace directory.
Comments suppressed due to low confidence (1)

skills/skill-upper/references/case-yaml.md:1

  • This states on_fail: skip_remaining marks the case as SKIP, but the implementation appears to proceed to judge evaluation when skip_remaining is used (and other docs in this PR describe “depends on judge”). Please align this reference doc (and ideally all docs) with the actual runtime semantics to avoid user confusion.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread internal/evaluator/multiturn.go Resolved
Comment thread internal/evaluator/evaluator.go Resolved
Comment thread internal/report/templates/report.html Resolved
Comment thread internal/judge/rule_based.go Resolved
Comment thread internal/agent/agent.go Resolved
Comment thread internal/evaluator/multiturn_test.go Resolved
@zpzjzj

zpzjzj commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator

Review: 多轮会话实现

整体设计很扎实——模块边界清晰、是真多轮(session resume 而非拼 prompt)、测试覆盖也充分。核心机制方向没问题,但有几处会影响正确性/体验的问题,按优先级列一下。

1. [正确性] claude_code 续轮的 transcript 是累积的,导致 per-turn 工具断言错判

RunTurn 续轮走 claude --resume <id> -p <text>(纯文本 print 模式,buildClaudeResumeCmd),再靠 buildSessionResult → parseSessionFile 回读磁盘上的 session JSONL 还原 transcript。但 parseSessionFile 读的是整段 session 文件 = 累积所有轮,于是:

  • 第 N 轮 tr.Transcript = [T1..TN];
  • evalToolCalledInTurn 直接 tr.Transcript.ToolCalls(),不按 turn 号过滤 → turn 1 用过的工具会让 tool_called_in_turn[turn=3] 假通过,tool_not_called_in_turn[turn=3] 假失败;
  • 聚合 transcript 也累积重复:executeMultiTurn 里 state.transcript = append(state.transcript, tr.Transcript...) → 最终 [T1] + [T1,T2] + [T1,T2,T3],T1 出现 3 次,影响报告展示与全局 tool_called。设计文档写了 "when an adapter returns a cumulative transcript, normalize/deduplicate before appending",但代码没做去重。

建议:续轮改用 claude 的 stream-json resume(claude --resume <id> -p --input-format stream-json --output-format stream-json --verbose),直接从 stdout 拿到"仅本轮"的 messages + tool_use + usage,和首轮 Run 的 stream-json 路径统一,就不必再解析累积 session 文件;或退一步,在 judge / 还原时按 Message.Turn 切分 transcript。

2. [正确性] token 双重计数

accumulateMetrics 逐轮 state.inputTokens += result.InputTokens,而 parseSessionFile 返回的是累积 session 的 max token。逐轮相加会显著放大总量。与第 1 点同源,改用 stream-json 续轮可一并解决。

3. [体验/正确性] fallback 静默降级 + 文档承诺的 warning 不存在

分发逻辑是:len(turns)>1 且 agent 实现 SessionResumer 才走多轮,否则静默 fall through 到 single-shot,把所有 turns 拼成一个 prompt。但 single-shot 路径从不设置 result.TurnResults,于是任何 per-turn 断言在 lookupTurn 里命中 turn N does not exist (executed 0 turns) → 断言失败。

结果:同一份 eval,仅把引擎从 claude_code 换到不支持 resume 的引擎,就会无故 FAIL 且无任何提示。而且文档(writing-evals.md)写了 "A warning is logged",但代码里这个 warning 并不存在(fall-through 分支没有任何 logging.Warn)。

建议:在 validator 阶段就对"多轮 case + 不支持 resume 的引擎"报错或告警,别等跑完一整轮拿到一堆假 FAIL;至少兑现文档里的 warning。

4. [文档] 支持矩阵漏了 qwen_code

docs/guide/writing-evals.md 的 Agent support matrix 只有 claude_code / qodercli / codex / custom 四行,完全没有 qwen_code(它可是一等内建引擎)。qwen 非交互模式是 printf ... | qwen --yolo,没有 session-id resume 能力,本期不做 resume 合理,但矩阵至少要补一行 qwen_code | Not yet | Falls back to batch mode,和第 3 点的告警配套。

5. [核对] codex / qodercli 续轮是否同样累积

codex/qodercli 的 RunTurn 也各自走 buildSessionResult,若它们同样读整段 rollout,则第 1、2 点的问题同理存在,建议一并核对。


一个概念澄清:session resume 本身已经是"真多轮"(上下文真实延续),stream-json 带来的不是"更真的会话",而是"每轮输出的准确归属"。所以正解是 session resume 保证多轮语义 + 续轮 stream-json 保证 per-turn 数据正确,两者不冲突。

roark47 commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

@zpzjzj 已在 93c6907 处理这几项:

  1. Claude/Qoder 这类返回累积 session transcript 的场景,现在在 evaluator 层按当前逻辑 turn 归一化,TurnResult.Transcript 只包含本轮消息,聚合 transcript 也不会重复追加旧轮次;per-turn tool 断言不会再被前序轮次污染。
  2. token 统计改成识别累积 usage 并按 delta/high-water 汇总,避免 turn1 + (turn1+turn2) + ... 的重复计数。
  3. input.turns 现在只要存在且 agent 支持 resume 就走多轮引擎,包括单轮 turns;不支持 SessionResumer 的 agent fallback 到 batch prompt 时会明确打 warning。
  4. 英文/中文文档的 Agent support matrix 已补 qwen_code | Not yet | Falls back to batch mode。
  5. 已核对 Codex/Qoder:Qoder/Claude session 文件是累积形态;Codex 通常优先用本次 JSON stdout,但 session-file fallback 也由 evaluator 归一化兜底。

没有改成 Claude stream-json resume,主要是把修复收敛在 evaluator 归一化层,避免扩大 agent 适配器改动面。已补单测覆盖,并通过 make verify 和 make test。

Copilot stopped work on behalf of roark47 due to an error July 7, 2026 07:31
Copilot stopped work on behalf of roark47 due to an error July 7, 2026 07:31
Copilot stopped work on behalf of roark47 due to an error July 7, 2026 07:31
Copilot stopped work on behalf of roark47 due to an error July 7, 2026 07:31
Copilot stopped work on behalf of roark47 due to an error July 7, 2026 07:31
Copilot stopped work on behalf of roark47 due to an error July 7, 2026 07:31

@zpzjzj zpzjzj left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@roark47
roark47 merged commit c0c15d3 into main Jul 8, 2026
64 of 118 checks passed
@github-project-automation github-project-automation Bot moved this from Backlog to Done in skill-up project Jul 8, 2026
@jwx0925
jwx0925 deleted the feat/multi-turn-conversation branch July 24, 2026 06:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants