Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ packages/web-templates/src/generated/
packages/vscode-ide-companion/*.vsix

logs/
.repro-runs/
# GHA credentials
gha-creds-*.json

Expand Down Expand Up @@ -93,4 +94,4 @@ tmp/

# code graph skills
.venv
.codegraph
.codegraph
82 changes: 82 additions & 0 deletions .qwen/skills/agent-reproduce-align/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
---
name: agent-reproduce-align
description: Use after a Codex or Claude Code feature has been implemented in Qwen Code to run the selected reference agent and Qwen Code under the same scenario, capture HTTP and terminal traces, compare request bodies, tool/function schemas, outputs, and iterate until the reproduced behavior is close enough.
---

# Agent Reproduce Align

## Purpose

Use this skill when Qwen Code already has a candidate implementation and needs evidence-based parity with a selected reference agent: `codex` or `claude-code`. The goal is not byte-for-byte equality; it is matching the observable contract that matters for the feature.

Default target repo: the current working directory. Use a user-specified path only when the user explicitly provides one.

## Reference Agent Selection

Use the same reference agent selected during `$agent-reproduce-feature`. If the earlier choice is unavailable, ask once and record the answer in the scenario or run notes.

## Workflow

1. Re-state the parity target:
- feature name and trigger
- selected reference agent
- one baseline prompt or interaction script
- acceptable differences
- must-match fields
2. Run the reference agent and Qwen Code in separate capture directories with the same scenario.
3. Normalize traces with `scripts/normalize_trace.py`.
4. Compare normalized traces with `scripts/compare_traces.py`.
5. Inspect differences in this order:
- missing tool/function names
- schema shape and required fields
- model settings and response mode
- prompt role/order differences that affect behavior
- terminal-visible output and exit status
6. Patch Qwen Code, rerun the smallest failing scenario, and repeat.
7. Preserve only redacted minimal fixtures in the repo.

Read `references/alignment-workflow.md` before the first comparison pass.

## Common Commands

Normalize:

```sh
skills/agent-reproduce-align/scripts/normalize_trace.py \
.repro-runs/reference/http.jsonl \
> .repro-runs/reference/normalized.json
```

Compare:

```sh
skills/agent-reproduce-align/scripts/compare_traces.py \
.repro-runs/reference/normalized.json \
.repro-runs/qwen/normalized.json
```

Run a paired shell scenario:

```sh
skills/agent-reproduce-align/scripts/run_pair_capture.sh \
.repro-runs/slash-help \
"codex exec '/help'" \
"npm test -- --runInBand"
```

For Claude Code, replace the first command with the discovered Claude Code command. Use the paired runner only when shell quoting is simple. For interactive slash commands, run the two captures manually with tmux so each side can receive the same keystrokes.

## Comparison Rules

- Compare contracts before wording. Exact prompt text is usually implementation detail.
- Treat absent schemas, wrong required fields, or wrong argument names as high-signal failures.
- Treat output ordering as significant only when the user-visible workflow depends on it.
- Do not chase provider-specific endpoints, model names, IDs, timestamps, token counts, or ephemeral headers unless the feature depends on them.
- Stop when Qwen Code passes the user-visible scenario and the remaining trace differences are documented as intentional.

## Done Criteria

- Reference-agent and Qwen Code traces for the same scenario exist locally.
- The normalized comparison has no unexplained must-match differences.
- Qwen Code tests or smoke commands cover the fixed behavior.
- Any remaining mismatch is written down in the task notes or Qwen Code docs when it affects users.
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Alignment Workflow Reference

The alignment phase starts after Qwen Code has a candidate implementation. Use it to create a tight loop: run the selected reference agent and Qwen Code, compare traces, patch the target, and rerun only the failing scenario.

## Trace Inputs

Expected raw capture layout:

```text
.repro-runs/<scenario>/
reference/
http.jsonl
command.stdout
command.stderr
command.exit
qwen/
http.jsonl
command.stdout
command.stderr
command.exit
```

Use capture scripts from `$agent-reproduce-feature` for raw capture, or use `run_pair_capture.sh` for simple non-interactive shell scenarios.

## Normalization

`normalize_trace.py` reads mitm JSONL output and emits stable JSON:

- request method and URL path
- JSON request body summary
- message role order and brief content hashes
- tool/function names
- schema required fields
- response status code

It intentionally drops:

- timestamps
- authorization and cookie headers
- provider request IDs
- full message text unless needed for a hash

## Diff Triage

High priority:

- missing request entirely
- wrong endpoint family
- missing tool/function schema
- incompatible required fields or enum values
- slash command not routed to the same behavior class

Medium priority:

- prompt role ordering differences
- terminal output phrasing differences
- streaming versus non-streaming if users can observe it

Low priority:

- timestamps, IDs, token counts
- harmless wording differences
- extra target-side metadata ignored by the provider

## Iteration Loop

1. Pick the highest-priority unexplained mismatch.
2. Patch only the likely owner module in Qwen Code.
3. Run the focused test/smoke path.
4. Capture only the affected scenario again.
5. Normalize and compare again.

Stop when the target behavior is compatible and remaining differences are either irrelevant or explicitly documented.
85 changes: 85 additions & 0 deletions .qwen/skills/agent-reproduce-align/scripts/compare_traces.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
#!/usr/bin/env python3
"""Compare normalized reproduction traces and print actionable differences."""

from __future__ import annotations

import argparse
import json
from pathlib import Path
from typing import Any


def load(path: Path) -> dict[str, Any]:
return json.loads(path.read_text(encoding="utf-8"))


def tool_index(request: dict[str, Any]) -> dict[str, dict[str, Any]]:
return {
Comment thread
DragonnZhang marked this conversation as resolved.
Resolved
Comment thread
DragonnZhang marked this conversation as resolved.
Resolved
tool.get("name") or f"<unnamed-{idx}>": tool
for idx, tool in enumerate(request.get("tools") or [])
}


def compare_request(idx: int, left: dict[str, Any], right: dict[str, Any]) -> list[str]:
diffs: list[str] = []
prefix = f"request[{idx}]"
for key in ("method", "url_path", "model", "stream", "response_status"):
if left.get(key) != right.get(key):
diffs.append(f"{prefix}.{key}: {left.get(key)!r} != {right.get(key)!r}")

Comment thread
DragonnZhang marked this conversation as resolved.
Resolved
Comment thread
DragonnZhang marked this conversation as resolved.
Resolved
left_roles = [item.get("role") for item in left.get("messages") or []]
right_roles = [item.get("role") for item in right.get("messages") or []]
if left_roles != right_roles:
Comment thread
DragonnZhang marked this conversation as resolved.
Resolved
diffs.append(f"{prefix}.message_roles: {left_roles!r} != {right_roles!r}")

left_tools = tool_index(left)
right_tools = tool_index(right)
missing = sorted(set(left_tools) - set(right_tools))
extra = sorted(set(right_tools) - set(left_tools))
if missing:
diffs.append(f"{prefix}.tools_missing_in_right: {missing}")
if extra:
diffs.append(f"{prefix}.tools_extra_in_right: {extra}")

Comment thread
DragonnZhang marked this conversation as resolved.
Resolved
Comment thread
DragonnZhang marked this conversation as resolved.
Resolved
for name in sorted(set(left_tools) & set(right_tools)):
for key in ("required", "properties"):
if left_tools[name].get(key) != right_tools[name].get(key):
diffs.append(
f"{prefix}.tool[{name}].{key}: "
f"{left_tools[name].get(key)!r} != {right_tools[name].get(key)!r}"
)
return diffs


def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("left", type=Path, help="Reference normalized trace")
parser.add_argument("right", type=Path, help="Target normalized trace, usually Qwen Code")
args = parser.parse_args()

left = load(args.left)
right = load(args.right)
diffs: list[str] = []
Comment thread
DragonnZhang marked this conversation as resolved.
Resolved

if left.get("request_count") != right.get("request_count"):
diffs.append(
f"request_count: {left.get('request_count')!r} != {right.get('request_count')!r}"
)

for idx, (left_req, right_req) in enumerate(
zip(left.get("requests") or [], right.get("requests") or [])
):
diffs.extend(compare_request(idx, left_req, right_req))

if not diffs:
print("No normalized trace differences found.")
return 0

print("Normalized trace differences:")
for diff in diffs:
print(f"- {diff}")
Comment thread
DragonnZhang marked this conversation as resolved.
Resolved
return 1


if __name__ == "__main__":
raise SystemExit(main())
128 changes: 128 additions & 0 deletions .qwen/skills/agent-reproduce-align/scripts/normalize_trace.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
#!/usr/bin/env python3
"""Normalize mitm JSONL traces into a stable comparison format."""

from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path
from typing import Any
from urllib.parse import urlparse


def content_hash(value: str) -> str:
return hashlib.sha256(value.encode("utf-8")).hexdigest()[:16]


def json_body(record: dict[str, Any]) -> Any:

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.

[Suggestion] json_body() can return a list (e.g., OpenAI batch API requests: [{"method": "POST", ...}, ...]). In normalize(), body.keys() is guarded by isinstance(body, dict) (returns []), and summarize_body_values() also guards with if not isinstance(body, dict): return {}. Batch API requests silently produce empty body_keys and body_values — all body-level comparison is skipped.

Consider adding a body_kind field or content hash for non-dict bodies:

if isinstance(body, list):
    requests[-1]["body_kind"] = "list"
    requests[-1]["body_len"] = len(body)
    requests[-1]["body_hash"] = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()[:16]

— qwen3.7-max via Qwen Code /review

body = record.get("body") or {}
if body.get("json") is not None:
return body["json"]
text = body.get("text")
if not text:
return None
try:
return json.loads(text)
except json.JSONDecodeError:
return {"text_hash": content_hash(text), "text_len": len(text)}


def walk_tools(value: Any) -> list[dict[str, Any]]:

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.

[Suggestion] walk_tools() doesn't handle Gemini's functionDeclarations format. Gemini tools use {"tools": [{"functionDeclarations": [{"name": "...", "parameters": {...}}]}]} — summarize_tool() receives {"functionDeclarations": [...]} and finds no function, parameters, or input_schema keys, producing an empty summary.

The capture layer is provider-agnostic (mitmproxy intercepts all HTTP), but normalization is blind to Gemini tool definitions. Trace comparison would report "no differences" for tool sets that are completely different.

Suggested change
def walk_tools(value: Any) -> list[dict[str, Any]]:
def walk_tools(value: Any) -> list[dict[str, Any]]:
tools: list[dict[str, Any]] = []
if isinstance(value, dict):
for key in ("tools", "functions"):
if key in value and isinstance(value[key], list):
for item in value[key]:
# Gemini: {"functionDeclarations": [...]}
if "functionDeclarations" in item and isinstance(item["functionDeclarations"], list):
for decl in item["functionDeclarations"]:
tools.append(summarize_tool({"type": "function", "function": decl}))
elif key == "functions":
tools.append(summarize_tool({"type": "function", "function": item}))
else:
tools.append(summarize_tool(item))
return tools

— qwen3.7-max via Qwen Code /review

tools: list[dict[str, Any]] = []
if isinstance(value, dict):
if "tools" in value and isinstance(value["tools"], list):
for tool in value["tools"]:
Comment thread
DragonnZhang marked this conversation as resolved.
Resolved
tools.append(summarize_tool(tool))
if "functions" in value and isinstance(value["functions"], list):
for fn in value["functions"]:
tools.append(summarize_tool({"type": "function", "function": fn}))
for child in value.values():
tools.extend(walk_tools(child))
elif isinstance(value, list):
for child in value:
tools.extend(walk_tools(child))
return tools


def summarize_tool(tool: Any) -> dict[str, Any]:
if not isinstance(tool, dict):
return {"raw_type": type(tool).__name__}
fn = tool.get("function") if isinstance(tool.get("function"), dict) else tool
params = fn.get("parameters") if isinstance(fn, dict) else None
return {
"type": tool.get("type"),
"name": fn.get("name") if isinstance(fn, dict) else None,
"description_hash": content_hash(fn.get("description", ""))
if isinstance(fn, dict) and isinstance(fn.get("description"), str)
else None,
"required": sorted(params.get("required", []))
Comment thread
DragonnZhang marked this conversation as resolved.
Resolved
if isinstance(params, dict) and isinstance(params.get("required"), list)
else [],
"properties": sorted(params.get("properties", {}).keys())
Comment thread
DragonnZhang marked this conversation as resolved.
Resolved
if isinstance(params, dict) and isinstance(params.get("properties"), dict)
else [],
}


def summarize_messages(value: Any) -> list[dict[str, Any]]:
messages = None
if isinstance(value, dict):
if isinstance(value.get("messages"), list):
messages = value["messages"]
elif isinstance(value.get("input"), list):
messages = value["input"]
if messages is None:
Comment thread
DragonnZhang marked this conversation as resolved.
Resolved
return []
summary = []
for item in messages:
if not isinstance(item, dict):
continue
content = item.get("content", "")
if not isinstance(content, str):
content = json.dumps(content, ensure_ascii=False, sort_keys=True)
summary.append(
{
"role": item.get("role"),
"content_hash": content_hash(content),
"content_len": len(content),
}
)
return summary


def normalize(path: Path) -> dict[str, Any]:
requests = []
for line in path.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
raw = json.loads(line)
Comment thread
DragonnZhang marked this conversation as resolved.
Resolved
req = raw.get("request") or {}
Comment thread
DragonnZhang marked this conversation as resolved.
Resolved
resp = raw.get("response") or {}
parsed = urlparse(req.get("url", ""))
body = json_body(req)
Comment thread
DragonnZhang marked this conversation as resolved.
Resolved
requests.append(
{
"method": req.get("method"),
"url_path": parsed.path,
"body_keys": sorted(body.keys()) if isinstance(body, dict) else [],
"model": body.get("model") if isinstance(body, dict) else None,
"stream": body.get("stream") if isinstance(body, dict) else None,
"messages": summarize_messages(body),
"tools": sorted(walk_tools(body), key=lambda item: (item.get("name") or "")),
"response_status": resp.get("status_code") if isinstance(resp, dict) else None,
}
)
return {"source": str(path), "request_count": len(requests), "requests": requests}


def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("trace", type=Path)
args = parser.parse_args()
print(json.dumps(normalize(args.trace), ensure_ascii=False, indent=2, sort_keys=True))
return 0


if __name__ == "__main__":
raise SystemExit(main())
Loading
Loading