records = [
    {"user": "u1", "topic": "退款", "text": "已提交申请 R17，尚未批准"},
    {"user": "u1", "topic": "配送", "text": "偏好工作日收货"},
    {"user": "u2", "topic": "退款", "text": "另一位客户的私人记录"},
]


def context(user, topic, mandatory, budget_chars):
    if len(mandatory) > budget_chars:
        raise ValueError("必需上下文已超预算")
    parts = [mandatory]
    used = len(mandatory)
    for item in records:
        if item["user"] != user or item["topic"] != topic:
            continue
        cost = len(item["text"]) + 1
        if used + cost <= budget_chars:
            parts.append(item["text"])
            used += cost
    return "\n".join(parts)


result = context("u1", "退款", "任务：查询 R17 状态", 60)
assert "尚未批准" in result
assert "另一位客户" not in result
assert "工作日收货" not in result
assert len(result) <= 60
print(result)
