Skip to content
Draft
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
1 change: 1 addition & 0 deletions MEMORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -322,3 +322,4 @@ Launcher의 `latest`/`next`는 rc.8이며 실제 모델 품질 평가는 인증
- 연구 방향(사용자 결정, 2026-11-29): 모델을 바꾸기보다 지금 수준 모델(agy `gemini-3.8-flash-low`)로 높은 성능을 내는 하네스를 연구한다. 핵심은 LLM에게 무엇을 어떻게 전달하고(메모리·도구·피드백) 실행 경로를 마련하느냐다. 측정은 공식 실행기 Harbor로 Terminal-Bench 2.1(89개)을 돌리고, 실패를 전달 관점(문맥 누락·도구 계약 오해·실행 경로 없음·검증 누락·형식 오류·루프/예산)으로 분류한다. 측정 도구는 `research/harbor-bench` 브랜치에 있다(아직 PR 전).
- agy 내장 manage_task(ADR-0096, 구현·실제 모델 검증): agy 1.5.18은 planner-only agent와 deny 설정에서도 `manage_task`를 실행하고 끌 방법이 없다(agent `disabledTools` 무시, settings 키 없음, deny 규칙 무효). 기준선의 정상 응답 14%가 이 호출을 포함해 Run이 Unknown으로 멈췄다. `Action=list` 단독 호출만 허용하고 나머지 native step은 계속 실패로 닫는다. 유도 목표 비교에서 기존 2/8 정지, 수정 0/10 정지. agy 쪽 과제: 이 도구를 끄는 설정이 생기면 허용을 제거한다.
- 기준선 중간 관찰(2026-11-29): 응답이 거절되면 모델은 `previousResponseRejection.meaning`의 일반 문구만 받고 구체 이유(빠진 필드, 문자열 안 제어 문자)를 받지 못해 같은 실수를 반복했다(write-compressor 3연속 → Run 거절). 사례를 더 모은 뒤 첫 개선 후보로 본다. agy 개인 할당량(약 3.5시간·호출 700여 회) 초과로 50개 과업이 오염되어 할당량을 확인하며 다시 돌리는 중이다.
- 형식 거절 분석(2026-11-29, ADR-0098 제안, 구현 전): 기준선 응답 1,482개 중 146개(9.9%)가 형식 거절이다. 갈래별로 문자열 escape 62(대부분 `bash -c` 안의 여러 줄 코드), 봉투 구조 71(Step 필드를 최상위에 펼침 46, 봉투 없는 Step 14), 안전 필터 문구 13이다. 제안은 고정 code `responseDefect`와 code별 문장으로 구체 이유를 전달하는 것이고, 선택으로 뜻이 하나뿐인 문자열 보정(날 제어 문자, 잘못된 escape; 오프라인 22건 회복)을 둔다. 2026-11-30 사용자 승인으로 1번 구현: 기준선 거절 146건 모두 구체 code로 분류(unclassified 0). agy transport의 응답 사전 JSON 검사를 빼서 agy도 같은 decoder 판정과 ADR-0068 보정을 받는다. 실측은 ADR-0097 실측 뒤.
121 changes: 121 additions & 0 deletions bench/harbor/classify_responses.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
#!/usr/bin/env python3
"""Classify rejected-shape bridge responses with xgen's response contract (ADR-0098 analysis).

Usage: python3 bench/harbor/classify_responses.py [--since EPOCH] [--log-dir /tmp/hb/bridge] [--repair]

Mirrors decode_chat_response: strict JSON (no raw control characters, no duplicate keys),
the four-field envelope, and step/dependency shapes. --repair also reports what the
unambiguous string repair (raw control characters, invalid escapes) would recover.
The rules are approximate; xgen's Rust decoder is authoritative.
"""
import argparse, collections, glob, json, os, re
class Dup(Exception): pass
def hook(pairs):
keys=[k for k,_ in pairs]
if len(keys)!=len(set(keys)): raise Dup(keys)
return dict(pairs)
PROP={"formatVersion","kind","steps","summary"}
STEP={"key","objective","dependsOn","capability","arguments"}
def classify(text):
t=text.strip()
if t.startswith("```"): return "markdown_fence"
try: v=json.loads(text, object_pairs_hook=hook)
except Dup: return "duplicate_key"
except json.JSONDecodeError as e:
m=e.msg
if "control character" in m: return "control_char_in_string"
if "Extra data" in m: return "trailing_data"
if "Invalid \\escape" in m or "escape" in m: return "invalid_escape"
if e.pos>=len(text.rstrip())-1 or "Expecting" in m and e.pos>len(text)-3: return "truncated_or_unclosed"
return "json_syntax:"+m.split(":")[0]
if not isinstance(v,dict): return "not_object"
missing=PROP-set(v); extra=set(v)-PROP
if missing: return "missing:"+",".join(sorted(missing))
if extra: return "unknown_field:"+",".join(sorted(extra))
if v["formatVersion"]!=1: return "format_version"
k=v["kind"]
if k not in ("plan","completion_candidate","response_candidate"): return "bad_kind:"+str(k)[:20]
if k=="plan":
if v["summary"]: return "plan_with_summary"
if not isinstance(v["steps"],list): return "steps_not_list"
for s in v["steps"]:
if not isinstance(s,dict): return "step_not_object"
if STEP-set(s): return "step_missing:"+",".join(sorted(STEP-set(s)))
if set(s)-STEP: return "step_unknown_field:"+",".join(sorted(set(s)-STEP))
c=s["capability"]
if not isinstance(c,dict) or set(c)!={"capabilityId","contractVersion"}: return "step_capability_shape"
for d in s["dependsOn"]:
if not isinstance(d,dict) or set(d)!={"kind","stepId","key"}: return "dependency_shape"
if d["kind"]=="existing_step" and not (d["stepId"] and not d["key"]): return "dependency_fields"
if d["kind"]=="proposed_step" and not (d["key"] and not d["stepId"]): return "dependency_fields"
if d["kind"] not in ("existing_step","proposed_step"): return "dependency_kind"
return "ok_plan"
if v["steps"] or not v["summary"]: return "candidate_with_steps_or_empty_summary"
return "ok_"+k


VALID = set('"\\/bfnrtu')


def repair_strings(text):
"""Escape raw control characters and lone backslashes inside strings; None if unchanged."""
out, in_string, i, changed = [], False, 0, False
while i < len(text):
ch = text[i]
if in_string:
if ch == "\\":
nxt = text[i + 1] if i + 1 < len(text) else ""
if nxt in VALID and not (nxt == "u" and not re.fullmatch(r"[0-9a-fA-F]{4}", text[i + 2:i + 6])):
out.append(ch + nxt)
i += 2
continue
out.append("\\\\")
changed = True
i += 1
continue
if ch == '"':
in_string = False
elif ord(ch) < 0x20:
out.append({"\n": "\\n", "\t": "\\t", "\r": "\\r"}.get(ch, "\\u%04x" % ord(ch)))
changed = True
i += 1
continue
elif ch == '"':
in_string = True
out.append(ch)
i += 1
return "".join(out) if changed else None


def main():
parser = argparse.ArgumentParser()
parser.add_argument("--since", type=float, default=0)
parser.add_argument("--log-dir", default="/tmp/hb/bridge")
parser.add_argument("--repair", action="store_true")
args = parser.parse_args()
counts, repaired = collections.Counter(), collections.Counter()
for path in sorted(glob.glob(f"{args.log_dir}/*.json")):
if int(os.path.basename(path).split("-")[0]) < args.since:
continue
record = json.load(open(path))
messages = record["request"].get("messages") or []
if record.get("error") or record.get("response") is None \
or any(m.get("content") == "ping" for m in messages):
continue
kind = classify(record["response"])
counts[kind] += 1
if args.repair and not kind.startswith("ok"):
fixed = repair_strings(record["response"])
if fixed is not None:
repaired[(kind, classify(fixed))] += 1
total = sum(counts.values())
bad = total - sum(n for k, n in counts.items() if k.startswith("ok"))
print(f"{total} responses, {bad} rejected-shape")
for kind, n in counts.most_common():
print(f"{n:6} {kind}")
for (before, after), n in sorted(repaired.items()):
print(f"repair {n:4} {before} -> {after}")


if __name__ == "__main__":
main()
29 changes: 17 additions & 12 deletions crates/xgen-cli/src/agy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use sha2::{Digest, Sha256};
use tempfile::TempDir;
use url::Url;
use xgen_provider_openai::parse_unique_json;
use xgen_runtime::PlannerPortFailure;
use xgen_runtime::{PlannerPortFailure, ResponseDefect};

pub const DEFAULT_MODEL: &str = "gemini-3.8-flash-low";
const AGENT: &str = include_str!("agy-agent.md");
Expand Down Expand Up @@ -384,12 +384,12 @@ impl Transport {
if request["model"].as_str() != Some(self.model.as_str()) {
return Err(PlannerPortFailure::ProviderLimit);
}
let system = request["messages"][0]["content"]
.as_str()
.ok_or(PlannerPortFailure::InvalidResponse)?;
let user = request["messages"][1]["content"]
.as_str()
.ok_or(PlannerPortFailure::InvalidResponse)?;
let system = request["messages"][0]["content"].as_str().ok_or(
PlannerPortFailure::InvalidResponse(ResponseDefect::Unclassified),
)?;
let user = request["messages"][1]["content"].as_str().ok_or(
PlannerPortFailure::InvalidResponse(ResponseDefect::Unclassified),
)?;
let prompt = format!(
"HOST SYSTEM INSTRUCTIONS:\n{system}\nHOST REQUEST AND OBSERVATIONS:\n{user}\n{}",
self.closing
Expand Down Expand Up @@ -420,19 +420,24 @@ impl Transport {
|| finals.len() != 1
|| finals[0]["result"]["status"] != "SUCCESS"
{
return Err(PlannerPortFailure::InvalidResponse);
return Err(PlannerPortFailure::InvalidResponse(
ResponseDefect::Unclassified,
));
}
let result = &finals[0]["result"];
let response = result["response"]
.as_str()
.ok_or(PlannerPortFailure::InvalidResponse)?;
parse_unique_json(response.as_bytes(), 64)?;
.ok_or(PlannerPortFailure::InvalidResponse(
ResponseDefect::Unclassified,
))?;
// The shared decoder parses the content and classifies a defect (ADR-0098), so it is not
// checked here.
let mut envelope = json!({"model":self.model,"choices":[{"index":0,"finish_reason":"stop","message":{"role":"assistant","content":response}}]});
if let Some(usage) = normalized_usage(&result["usage"]) {
envelope["usage"] = usage;
}
let encoded =
serde_json::to_vec(&envelope).map_err(|_| PlannerPortFailure::InvalidResponse)?;
let encoded = serde_json::to_vec(&envelope)
.map_err(|_| PlannerPortFailure::InvalidResponse(ResponseDefect::Unclassified))?;
if encoded.len() > max_response_bytes {
return Err(PlannerPortFailure::ProviderLimit);
}
Expand Down
2 changes: 1 addition & 1 deletion crates/xgen-cli/src/composition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2726,7 +2726,7 @@ fn map_planner_unavailable(run_id: String, failure: PlannerPortFailure) -> Local
),
};
}
PlannerPortFailure::InvalidResponse => ModelCallRejectionReason::PlannerInvalidResponse,
PlannerPortFailure::InvalidResponse(_) => ModelCallRejectionReason::PlannerInvalidResponse,
PlannerPortFailure::ProviderLimit => ModelCallRejectionReason::ProviderLimit,
PlannerPortFailure::RequestTooLarge => ModelCallRejectionReason::RequestTooLarge,
PlannerPortFailure::RateLimited => ModelCallRejectionReason::RateLimited,
Expand Down
3 changes: 2 additions & 1 deletion crates/xgen-cli/src/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -612,7 +612,8 @@ impl RunDriver {
// is usually a rare runaway repetition that a fresh sample avoids (ADR-0073).
if matches!(
failure,
PlannerPortFailure::InvalidResponse | PlannerPortFailure::OutputTruncated
PlannerPortFailure::InvalidResponse(_)
| PlannerPortFailure::OutputTruncated
) && rejected_responses_in_a_row < MAX_REJECTED_RESPONSE_RETRIES
{
rejected_responses_in_a_row += 1;
Expand Down
10 changes: 6 additions & 4 deletions crates/xgen-cli/src/final_response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ use serde_json::{Value, json};
use xgen_adapter_process::PROCESS_EXECUTE_CAPABILITY_ID;
use xgen_local_store::{RunStore, SqliteRunStore};
use xgen_provider_openai::{CompletionCheck, OpenAiPlanner};
use xgen_runtime::{PlanProposal, PlannerCallRequest, PlannerPort, PlannerPortFailure};
use xgen_runtime::{
PlanProposal, PlannerCallRequest, PlannerPort, PlannerPortFailure, ResponseDefect,
};
use xgen_workgraph::{EffectClass, RunEventBody, validate_completion_summary_candidate};

use crate::material_catalog::RunMaterialCatalog;
Expand Down Expand Up @@ -49,8 +51,8 @@ impl ReceiptReportPlanner {
// Read-only preflight can return a private snapshot. Open it after this
// call has been reserved, not when the planner is constructed.
let store = SqliteRunStore::open_existing_read_only(&self.database)
.map_err(|_| PlannerPortFailure::InvalidResponse)?;
let invalid = || PlannerPortFailure::InvalidResponse;
.map_err(|_| PlannerPortFailure::InvalidResponse(ResponseDefect::Unclassified))?;
let invalid = || PlannerPortFailure::InvalidResponse(ResponseDefect::Unclassified);
let (snapshot, mut receipts) = store
.load_with_execution_receipts()
.map_err(|_| invalid())?;
Expand Down Expand Up @@ -245,7 +247,7 @@ fn completion_report(
report["verification"] = completion_evidence(checks, commands, check_steps, boundary)
.map_err(|reason| {
eprintln!("XGEN_COMPLETION_CHECK reason={reason}");
PlannerPortFailure::InvalidResponse
PlannerPortFailure::InvalidResponse(ResponseDefect::CompletionCheckFailed)
})?;
report["format_version"] = json!(2);
}
Expand Down
1 change: 1 addition & 0 deletions crates/xgen-cli/tests/live_go50902_public.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1328,6 +1328,7 @@ fn require_workspace_completion(output: &Output, state_root: &Path) {
ModelCallSettlement::Rejected {
reason,
proposal: None,
..
},
..
} = record.event.body
Expand Down
50 changes: 50 additions & 0 deletions crates/xgen-cli/tests/workspace_discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2435,6 +2435,56 @@ fn a_truncated_response_is_sampled_again_with_its_reason() {
assert_eq!(result.status.code(), Some(0), "{}", stderr(&result));
}

#[test]
fn a_malformed_response_is_retried_with_its_defect_class() {
// ADR-0098: the retry names the broken part of the contract, not just "invalid".
let fixture = tempdir().unwrap();
let state = fixture.path().join("state");
let workspace = fixture.path().join("workspace");
fs::create_dir(&workspace).unwrap();
let answer = provider_response(&json!({
"formatVersion": 1, "kind": "response_candidate", "steps": [], "summary": "answer"
}));
let mut flattened: Value = serde_json::from_slice(&answer).unwrap();
flattened["choices"][0]["message"]["content"] = json!(
r#"{"formatVersion":1,"kind":"plan","key":"a","objective":"b","dependsOn":[],"capability":{"capabilityId":"x","contractVersion":"1"},"arguments":{},"summary":""}"#
);
let server =
SequentialServer::spawn_responses(vec![serde_json::to_vec(&flattened).unwrap(), answer]);
let result = bounded_output(xgen(&state).args([
"run",
"--workspace",
path_text(&workspace),
"--base-url",
&server.base_url,
"--model",
MODEL,
"--tokenizer",
TOKENIZER,
"--allow-dir",
".",
"--allow-remote-model-egress",
"--conversation-responses",
"Answer.",
]))
.unwrap();
let requests: Vec<_> = (0..2)
.map(|_| server.requests.recv_timeout(TEST_TIMEOUT).unwrap())
.collect();
server.handle.join().unwrap();
let rejection = &planning_context(&requests[1])["previousResponseRejection"];
assert_eq!(
rejection["reason"], "planner_invalid_response",
"{rejection}"
);
assert_eq!(
rejection["responseDefect"], "step_fields_at_top_level",
"{rejection}"
);
assert!(rejection["meaning"].to_string().contains("inside"));
assert_eq!(result.status.code(), Some(0), "{}", stderr(&result));
}

#[test]
#[cfg(unix)]
fn run_names_collections_that_must_be_rebuilt_and_does_not_start() {
Expand Down
Loading