작업이 늘어나도 컨텍스트를 쓸모 있게 유지하기

읽는 데 약 22분분 걸린다, 10절에 5개 예제이(가) 있음.

2026.11.2판 예제 통과 2026년 11월 20 64개 예제 중 64개 통과 변경 사항

AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식

영어판 2026.11.2판을 번역한 것이다. 원문 읽기

이 장을 마치면 실행 한 번의 프롬프트에 남은 공간이 얼마인지 계산하고, 하네스가 프롬프트의 크기를 정확히 셀 수 없을 때 그 크기를 추정하며, 도구 호출과 그 결과를 떼어 내지 않고 실행의 오래된 단계를 압축할 수 있다.

모델은 매 단계마다 프롬프트 전체를 읽는다. 시스템 프롬프트, 도구 스키마, 이슈, 그리고 그때까지 실행이 한 모든 일이 여기에 들어간다. 이 프롬프트는 모델이 로드될 때 정해진 윈도우 안에 들어가야 하고, 응답도 같은 윈도우 안에 들어가야 한다. 파일을 계속 읽는 실행은 결국 공간이 부족해진다.

이 문제는 사례에서 가장 긴 실행에서 드러난다. 1장의 라이브러리인 unitcraft의 유지보수 에이전트는 파일을 읽고, 테스트를 실행하고, 수정을 시도하는데, 파일을 한 번 읽을 때마다 파일 전체가 프롬프트에 더해진다. 기록된 작업 세트에서 T-16은 2장에서 정한 단계 상한인 16단계에 도달했고, 마지막 프롬프트는 세트의 모든 단계 중 가장 컸다. 기록된 토큰 수를 기준으로 보면 그 마지막 프롬프트에는 토큰 612개의 여유가 남았으며, 기록된 실행들이 윈도우에 가장 가까이 다가간 지점이 바로 여기였다. 이 장의 나머지는 프롬프트가 들어가지 않을 때 하네스가 해야 할 일을 다룬다.

모델이 가진 윈도

기록된 모델은 Qwen3-4B-Instruct-2507이며, 1장에서 소개한 GGUF 파일로 실행한다. 하니스는 이 모델을 8192 토큰의 컨텍스트로 불러오고, 기록의 매니페스트에는 같은 값이 n_ctx로 저장된다. 이것은 하니스가 선택한 로드 설정이다. 모델 자체는 훨씬 더 긴 길이를 지원한다. 모델 카드는 네이티브 컨텍스트 길이를 262,144 토큰으로 밝히고 있다(모델 카드, 카드의 main 브랜치에서 확인했다). 이 책은 모델을 더 작은 윈도에서 실행하므로, 예산에 필요한 숫자는 실행이 불러온 값이다.

매니페스트에는 응답이 차지할 수 있는 최대량인 max_tokens도 저장된다. 그 값은 1024 토큰이다. 응답은 프롬프트와 같은 윈도에서 나오므로, 프롬프트는 응답이 남긴 만큼을 쓴다.

계산은 짧다. 8192 토큰에서 응답용 1024 토큰을 빼면, 모델이 한 단계에서 읽는 모든 내용에 쓸 수 있는 토큰이 7168개 남는다. 프롬프트에는 시스템 프롬프트, 도구 스키마, 이슈, 노트, 이전 단계, 마지막 도구 결과가 들어 있으며, 이 모두가 그 예산에 포함된다. 거부도 다른 도구 결과와 마찬가지로 하나의 도구 결과이다. 하니스는 그 텍스트를 도구 메시지로 모델에 돌려주므로, 거부도 예산에 포함된다. 이 장에서는 이것을 프롬프트 예산이라고 부른다.

budget-counts-tokens.py Python 3.12.15 · pydantic 2.14.3 통과
"""The context the harness loads the model with, the room the reply keeps, and each run's largest prompt against them.The point rests on the line of steps over the prompt budget: no recorded step reached it."""import jsonfrom lib.context import PROMPT_BUDGET, REPLY, WINDOWfrom lib.models import RECORDEDfolder = RECORDED / "task-set"manifest = json.loads((folder / "manifest.json").read_text(encoding="utf-8"))steps = [json.loads(line) for line in (folder / "replies.jsonl").read_text(encoding="utf-8").splitlines()]assert manifest["n_ctx"] == WINDOW and manifest["max_tokens"] == REPLY, "the budget comes from the recorded load settings"print("load setting, n_ctx, in tokens:", WINDOW)  # the harness's own load setting, not the model's native lengthprint("reply reservation, max_tokens, in tokens:", REPLY)print("prompt budget, in tokens:", PROMPT_BUDGET)print("steps recorded:", len(steps))# ties go to the later run and step, so the same step is named on every runlargest = max(steps, key=lambda s: (s["prompt_tokens"], s["run"], s["step"]))print("largest prompt, in tokens:", largest["prompt_tokens"])print("largest prompt, run:", largest["run"])print("largest prompt, step:", largest["step"])print("room left for the reply at the largest step:", WINDOW - largest["prompt_tokens"] - REPLY)print("steps over the prompt budget:", sum(s["prompt_tokens"] > PROMPT_BUDGET for s in steps))for task in sorted(manifest["tasks"], key=lambda t: t["task"]):    mine = [s["prompt_tokens"] for s in steps if s["run"] == task["task"]]    print(f"{task['task']}: steps {len(mine)}, largest prompt {max(mine)}")    assert len(mine) == task["steps"], "the stored step count must match the replies"
출력python budget-counts-tokens.py
load setting, n_ctx, in tokens: 8192
reply reservation, max_tokens, in tokens: 1024
prompt budget, in tokens: 7168
steps recorded: 220
largest prompt, in tokens: 6556
largest prompt, run: T-16
largest prompt, step: 16
room left for the reply at the largest step: 612
steps over the prompt budget: 0
T-01: steps 16, largest prompt 4519
T-02: steps 16, largest prompt 4419
T-03: steps 12, largest prompt 3429
T-04: steps 5, largest prompt 2545
T-05: steps 5, largest prompt 2389
T-06: steps 16, largest prompt 6143
T-07: steps 9, largest prompt 4919
T-08: steps 7, largest prompt 3123
T-09: steps 6, largest prompt 2400
T-10: steps 16, largest prompt 5493
T-11: steps 16, largest prompt 3139
T-12: steps 12, largest prompt 3997
T-13: steps 16, largest prompt 4880
T-14: steps 7, largest prompt 2763
T-15: steps 10, largest prompt 3052
T-16: steps 16, largest prompt 6556
T-17: steps 9, largest prompt 2878
T-18: steps 4, largest prompt 1559
T-19: steps 9, largest prompt 4204
T-20: steps 13, largest prompt 4183

코드는 무엇이든 출력하기 전에 기록의 매니페스트가 하니스와 같은 윈도와 응답 제한을 가리키는지 확인하고, 둘이 다르면 실행을 실패시킨다. 그런 다음 예산과, 그에 대비한 각 실행의 가장 큰 프롬프트를 출력한다.

호스팅 API는 윈도가 훨씬 크다. Anthropic API 문서의 컨텍스트 편집 페이지는 오래된 도구 결과를 지우는 기본 트리거로 입력 토큰 100,000개를 제시한다(컨텍스트 편집). 100,000 토큰의 트리거는 8192 토큰의 윈도에서는 결코 작동하지 않는다. 그래서 이 책은 예산을 기록 대상 모델의 로드 설정에서 가져오며, 공급자의 기본값에서는 가져오지 않는다.

작업 규칙: 윈도는 매니페스트에 기록된 대로 실행이 사용한 로드 설정에서 가져오고, 어떤 예산을 정하기 전에 응답의 제한을 뺀다. 모델이 내세우는 길이나 공급자의 기본값에서는 절대 가져오지 않는다. 더 큰 모델에서 복사한 예산은 예산이 작동하기 전에 실행이 윈도를 채우도록 만들기 때문이다.

기록된 실행이 예산에 가장 근접한 지점

기록에는 모든 단계에서 모델이 보고한 프롬프트 개수가 replies.jsonl에 저장되어 있다. 어댑터는 4장이 응답을 정의한 대로 그 개수를 prompt_tokens로 반환하므로, 이 값은 모델이 직접 센 개수다. 하니스가 추정한 값이 아니다.

이 개수를 기준으로 보면, 기록된 단계 중 프롬프트 예산에 도달한 것은 없다. 기록된 220개 단계 중 예산을 넘은 단계는 0개였다. 프롬프트가 가장 큰 단계는 T-16의 마지막 단계였고, 응답을 위한 공간을 따로 떼어 놓고도 컨텍스트 윈도우에 612 토큰이 남았다. 이 검사는 기록을 읽을 뿐 모델을 로드하지 않으므로, 기록을 만든 하드웨어가 없어도 누구나 실행할 수 있다. 새 기록에 같은 검사를 실행하면 그 프롬프트가 여전히 예산에 들어가는지 즉시 알 수 있으므로, 모델을 바꾼 뒤에는 가장 먼저 다시 실행할 검사다.

이 결과가 알려 주는 바는 겉보기보다 적다. 기록된 작업 집합은 도구 집합 v1로 실행되었고, 루프와 모델 사이에는 프롬프트를 줄이거나 거부할 수 있는 것이 아무것도 없었다. 압축된 것도 없었고, 예산에 맞추려고 잘린 단계도 없었다. 이 개수는 이 프롬프트들이 예산에 들어간다는 사실만 보여 준다. 프롬프트가 들어가지 않을 때 하니스가 어떻게 동작하는지는 보여 주지 않으며, 이 장의 나머지는 바로 그 경우를 다룬다.

작업 규칙: 실행에서 무엇이든 읽어 내기 전에, 모든 단계의 개수를 프롬프트 예산과 비교하라.

하네스가 프롬프트를 셀 수 없을 때는 추정한다

정확한 토큰 수는 모델 자체의 토크나이저에서 나오며, 토크나이저는 모델 파일의 일부다. 이 책의 예제는 오프라인으로 실행되며 그 파일을 열지 않는다. 그 파일은 약 2.5 GB이고 책에 들어 있지 않다. 그래서 하네스는 추정한다. 모든 메시지와 도구 스키마의 문자 수를 세어 3으로 나누고 올림한다. 토큰 하나당 3자로 계산하는 셈이다.

3이라는 값은 작업 세트 기록을 살펴보고 정했다. 처음 시도한 규칙은 토큰당 4자였다. 작업 세트의 220개 단계에서 4자 기준의 추정치는 그중 216개 단계에서 실제 수보다 낮게 나왔다. 실제 수보다 낮은 추정은 위험한 방향이다. 하네스가 모델에게는 없는 여유가 있다고 믿게 되기 때문이다. 그래서 3으로 바꾸었다.

각 단계의 추정치는 같은 단계에서 모델이 보고한 수와 견주어 볼 수 있다.

estimate-vs-recorded.py Python 3.12.15 · pydantic 2.14.3 통과
"""The estimate of each recorded request against the prompt count the model reported for it. The rule was chosen ontask-set; chapter-5-notes was recorded after the rule was fixed, so its lines are the held-out check. The point restson the steps below the recorded count: none, in either recording."""import jsonfrom lib.case import load_tasksfrom lib.context import CHARS_PER_TOKEN, PROMPT_BUDGET, Measured, Notes, characters, estimate, notes_toolsetfrom lib.loop import Stops, run_taskfrom lib.models import RECORDED, ReplayModelfrom lib.tools import V1from lib.trace import IdCounterdef replay(recording, tasks, tools, **limits):    """Every request the recorded runs sent: its messages, its tool schemas and the count the model reported."""    ids, requests = IdCounter(), []  # the replay rebuilds each request, so each estimate sees the messages the model saw    for task in tasks:        model = Measured(ReplayModel(recording, task.id))        run_task(model, task, tools, ids=ids, **limits).close()        requests += model.requests    return requestsdef report(name, requests):    """Prints the comparison of the estimate with the count, labelled with the recording's name, and returns the pairs."""    pairs = [(estimate(m, t), n) for m, t, n in requests]    print(f"{name} steps compared:", len(pairs))    print(f"{name} characters per token, recorded (all steps):",          f"{sum(characters(m, t) for m, t, _ in requests) / sum(n for _, n in pairs):.2f}")    print(f"{name} steps where the estimate is above the recorded count:", sum(e > n for e, n in pairs))    print(f"{name} steps where the estimate is below the recorded count:", sum(e < n for e, n in pairs))    print(f"{name} lowest estimate divided by the recorded count: {min(e / n for e, n in pairs):.2f}")    print(f"{name} highest estimate divided by the recorded count: {max(e / n for e, n in pairs):.2f}")    assert all(e >= n for e, n in pairs), f"{name}: the rule should never count fewer tokens than the model did"    return pairsmanifest = json.loads((RECORDED / "chapter-5-notes" / "manifest.json").read_text(encoding="utf-8"))assert manifest["context"]["chars_per_token"] == CHARS_PER_TOKEN, "the held-out recording used the same rule"print(f"estimate rule, characters per token: {CHARS_PER_TOKEN}")task_set = replay("task-set", load_tasks(), V1, max_steps=V1.step_cap)pairs = report("task-set", task_set)# four is the rule a reader would try first: it is the one the comparison is againstprint("task-set with 4 characters per token, steps below the recorded count:",      sum(estimate(m, t, 4) < n for m, t, n in task_set))print("task-set steps whose estimate is over the prompt budget:", sum(e > PROMPT_BUDGET for e, _ in pairs))print("of those, steps whose recorded count is within the budget:",      sum(e > PROMPT_BUDGET and n <= PROMPT_BUDGET for e, n in pairs))report("held-out", replay("chapter-5-notes", load_tasks(only=["T-01", "T-02", "T-06"]), notes_toolset(Notes()),                          max_steps=16, stops=Stops(repeat_limit=3, no_progress_limit=2)))
출력python estimate-vs-recorded.py
estimate rule, characters per token: 3
task-set steps compared: 220
task-set characters per token, recorded (all steps): 3.67
task-set steps where the estimate is above the recorded count: 220
task-set steps where the estimate is below the recorded count: 0
task-set lowest estimate divided by the recorded count: 1.14
task-set highest estimate divided by the recorded count: 1.35
task-set with 4 characters per token, steps below the recorded count: 216
task-set steps whose estimate is over the prompt budget: 3
of those, steps whose recorded count is within the budget: 3
held-out steps compared: 18
held-out characters per token, recorded (all steps): 3.74
held-out steps where the estimate is above the recorded count: 18
held-out steps where the estimate is below the recorded count: 0
held-out lowest estimate divided by the recorded count: 1.22
held-out highest estimate divided by the recorded count: 1.29

추정치는 220개 단계 모두에서 기록된 수보다 높았고, 낮은 경우는 한 번도 없었다. 추정치와 실제 수의 비율은 1.14에서 1.35까지였다. 기록된 수에는 추정이 세지 않는 채팅 템플릿의 토큰이 들어 있으므로, 토큰당 평균 3.67자라는 값은 텍스트만의 비율이 아니라 이 프롬프트 형식의 비율이다.

안전한 쪽을 택한 대가도 드러난다. 세 단계에서 추정치가 프롬프트 예산을 넘었는데, 세 단계 모두 모델이 센 수는 예산 안에 있었다. 추정치를 그대로 믿는 하네스였다면 그 단계들을 까닭 없이 압축했을 것이다.

이 규칙은 작업 세트 단계에서 골랐으므로, 그 단계들로는 규칙을 검증할 수 없다. 따로 떼어 둔 검증은 chapter-5-notes 기록이다. 이 기록은 규칙을 확정한 뒤에 만들었고, 그 수는 규칙을 고르는 데 쓰지 않았다. 이 기록의 18개 단계도 같은 양상을 보인다. 실제 수보다 낮은 경우는 없었고, 비율은 1.22에서 1.29까지였으며, 토큰당 3.74자였다. 같은 모델과 비슷한 텍스트이므로, 이 결과는 다른 토크나이저나 다른 언어, 기호가 많은 코드에도 이 규칙이 성립한다는 것을 보여 주지 않는다.

작업 규칙: 토큰당 3자로 추정하고, 새 모델을 처음 실행할 때는 추정치를 모델이 보고하는 수와 비교해 확인한다. 추정치가 보고된 수보다 낮아지는 경우가 한 번이라도 생기면, 예산을 믿기 전에 토큰당 문자 수를 더 작은 값으로 바꾼다.

마지막 결과는 끝에 둔다

프롬프트에서는 사실이 들어 있는지뿐 아니라 그 사실이 어디에 놓이는지도 중요하다. 2023년 논문에서 Liu와 동료들은 관련 정보가 긴 입력의 처음이나 끝에 있을 때 성능이 가장 높은 경우가 많았고, 정보가 중간에 있을 때는 성능이 떨어졌다는 것을 발견했다(Lost in the Middle). 그 모델들은 이 책이 기록하는 모델보다 오래된 것이므로, 이 논문은 이전 모델에서 나타난 경향을 설명할 뿐이며 Qwen3-4B-Instruct-2507이 긴 프롬프트를 어떻게 다루는지를 설명하지는 않는다.

이 책의 배치는 이슈와 메모를 앞쪽에 두고, 마지막 도구 결과를 맨 끝에 둔다. 그곳은 모델이 응답하기 전에 마지막으로 읽는 위치다. 이것은 이 책의 설계 규칙이다. 마지막 결과가 반드시 끝에 와야 한다고 말하는 자료는 여기에 없으며, 이 책도 이 모델에서 이 배치를 측정하지 않았다. 이 선택의 근거는 그 논문이다. 아래의 압축 예제는 마지막 호출에서 모델에 보내는 각 메시지를 순서대로 출력한다. 시스템 프롬프트, 이슈, 요약, 마지막 호출과 그 결과 순이다.

이 배치에는 대가가 따른다. 압축은 이전 단계들의 요약을 이슈와, 마지막 호출 및 그 결과 사이에 넣는데, 이곳이 프롬프트의 중간이다. 논문이 설명하는 경향에 따르면 모델이 정보를 가장 덜 잘 활용하는 위치가 바로 여기다. 이 책은 그 대가를 감수한다.

작업 규칙: 이슈와 메모를 먼저 두고 마지막 도구 결과를 맨 끝에 둔다. 이를 설계상의 선택으로 다루고, 자신의 작업에서 실행해 이득이 확인된 뒤에야 이득을 주장한다.

오래된 단계는 압축하고 마지막 쌍은 유지한다

추정치가 프롬프트 예산을 넘으면 하네스는 압축을 수행한다. 여기서 압축은 로컬에서 이루어진다. 요약은 하네스가 직접 작성하며, 모델은 요약이 작성되는 과정을 보지 못한다. 오래된 단계들은 단계마다 한 줄씩 담은 하나의 메시지가 된다. 한 줄에는 호출, 60자로 자른 인자, 그리고 역시 60자로 자른 결과의 첫 줄이 들어간다. 시스템 프롬프트와 이슈는 그대로 둔다. 마지막 단계의 호출과 결과는 한 글자도 바꾸지 않고 넣으므로, 모델은 가장 최근의 근거를 온전히 볼 수 있다.

벤더도 서버에서 압축 기능을 제공한다. Anthropic의 압축 가이드는 압축이 "대화의 오래된 턴을 Claude가 서버에서 작성한 요약으로 대체한다"고 설명한다(compaction). 요청 시 사용하는 형태는 베타이며 헤더 compact-2026-09-04 뒤에 있다. 이 책은 서버 방식을 사용하지 않으며, 이 장의 어떤 내용도 서버 방식의 동작에 의존하지 않는다. 우리는 해당 페이지를 읽었을 뿐 실행해 보지는 않았다.

로컬 하네스에서 중요한 것은 절단 규칙이다. 최근 턴을 유지하는 방법에 관한 벤더의 가이드는 이를 분명하게 서술한다. "열려 있는 도구 호출이 남지 않는 곳에서 자르고, 각 도구 호출과 그 결과는 같은 쪽에 둔다"(keeping recent turns). 도구 결과 위에서 자르면 그 결과를 요청한 호출이 없는 채로 결과만 남으므로, 하네스는 그런 절단을 거부한다.

예산이 추정 토큰 2000개일 때 읽기 네 번과 마무리 한 번이면 예산을 넘기기에 충분하다. 이 예산은 실제 값인 7168보다 훨씬 작게 잡았다. 작은 작업에서도 압축이 일어나게 하려는 의도적인 설정이다. 이 작업으로는 실제 예산에 도달하지 않는다.

compact-keeps-last-result.py Python 3.12.15 · pydantic 2.14.3 통과
"""Four reads of the case, then finish, under a small budget that the reads cross. The point rests on the callscompacted line and the last two lines: the summary replaces the older steps, and a cut that would leave the lastcall's result on its own is refused."""from lib.case import load_tasksfrom lib.chapter1 import callfrom lib.context import Compacting, Context, Measured, clean_cut, estimatefrom lib.loop import run_taskfrom lib.models import ScriptedModelfrom lib.tools import V2from lib.trace import IdCounter# estimated tokens: above the fixed part and one result, below the full transcript; the chapter's budget is 7168,# which the case's files never reachBUDGET = 2000replies = [call("read_file", path=p) for p in ("unitcraft/convert.py", "unitcraft/units.py", "unitcraft/parse.py",                                                "README.md")] + [call("finish", summary="Read four files.")]ctx = Context(prompt_budget=BUDGET)model = Compacting(Measured(ScriptedModel(replies)), ctx)run = run_task(model, load_tasks(only=["T-01"])[0], V2, max_steps=V2.step_cap, ids=IdCounter())sent, tools, _ = model.inner.requests[-1]# the last request: system prompt, issue, summary, the last call, its resultprint("budget, in estimated tokens:", BUDGET)print("steps:", run.steps)print("ended:", run.ended)print("calls compacted:", ctx.compactions)print("calls still over the budget:", ctx.over_budget)print("fixed part (system prompt, tool schemas, issue), estimated tokens:", estimate(sent[:2], tools))print("messages sent on the last call:", len(sent))for number, message in enumerate(sent, start=1):    print(f"message {number}, {message['role']}:", " ".join(message["content"].split()[:4]))# the summary's first line is its heading, so the steps start at the second lineprint("summary of the older steps:", *sent[2]["content"].splitlines()[1:], sep="\n  ")# the call is wrapped in <tool_call> tags, so its JSON is the second lineprint("kept call:", sent[3]["content"].strip().splitlines()[1][:60])print("kept result, in lines:", len(sent[4]["content"].splitlines()))print("cut before the last result alone, clean:", clean_cut(sent, len(sent) - 1))print("cut before the last call, clean:", clean_cut(sent, len(sent) - 2))assert ctx.compactions > 0 and not clean_cut(sent, len(sent) - 1) and clean_cut(sent, len(sent) - 2)
출력python compact-keeps-last-result.py
budget, in estimated tokens: 2000
steps: 5
ended: finish
calls compacted: 3
calls still over the budget: 0
fixed part (system prompt, tool schemas, issue), estimated tokens: 1289
messages sent on the last call: 5
message 1, system: You are a maintenance
message 2, user: `format_quantity` drops the trailing
message 3, user: Earlier steps, summarised by
message 4, assistant: <tool_call> {"name": "read_file", "arguments":
message 5, tool: # unitcraft unitcraft parses,
summary of the older steps:
  step 1: read_file({"path": "unitcraft/convert.py"}) -> """convert: change a quantity to another unit of the same di
  step 2: read_file({"path": "unitcraft/units.py"}) -> """The unit table: each symbol with its dimension and its fa
  step 3: read_file({"path": "unitcraft/parse.py"}) -> """parse_quantity: read a quantity written as text, such as
kept call: {"name": "read_file", "arguments": {"path": "README.md"}}
kept result, in lines: 42
cut before the last result alone, clean: False
cut before the last call, clean: True

이 실행에서는 오래된 호출 3개가 압축되었고, 마지막 호출과 그 결과는 온전하게 남았다. 그 호출은 README.md를 읽는 것이었고, 결과의 길이는 42줄이었다. 시스템 프롬프트, 도구 스키마, 이슈로 이루어진 고정 부분은 추정 토큰 1289개였다. 압축으로는 이 부분을 줄일 수 없으므로, 이보다 작은 예산은 어떤 압축으로도 맞출 수 없다.

마지막으로 두 가지 절단이 출력된다. 마지막 결과 바로 앞에서 자르는 절단은 거부되고, 그 호출 앞에서 자르는 절단은 깔끔하게 처리된다. 코드는 두 경우를 모두 단언하므로, 둘 중 하나라도 달라지면 실행이 실패한다.

작업 규칙: 마지막 호출과 그 결과를 함께 유지하고, 도구 결과 위에 놓이는 절단은 모두 거부하며, 나머지를 압축으로 맞추리라 기대하기 전에 고정 부분이 예산에 들어가는지 확인한다.

컨텍스트 바깥에 노트를 보관한다

압축은 설계상 세부 정보를 잃는다. 컨텍스트 엔지니어링에 관한 Anthropic의 엔지니어링 글은 이를 하나의 선택으로 설명한다. "압축의 기술은 무엇을 남기고 무엇을 버릴지 고르는 데 있다. 지나치게 공격적인 압축은 중요성이 나중에야 드러나는 미묘하지만 핵심적인 컨텍스트를 잃게 할 수 있기 때문이다" (Effective context engineering for AI agents). 같은 글은 이를 피하는 방법으로 윈도 바깥에 노트를 보관하는 방식을 소개하지만, 그 효과를 측정한 결과는 싣지 않는다.

하니스는 note 도구를 추가한다. 모델은 사실 하나당 한 줄씩 쓰고, 하니스는 매 단계마다 이슈 뒤에 노트를 보낸다. 노트는 이전 단계에 속하지 않으므로 압축이 노트를 자르지 않는다. 모델이 노트로 적은 사실은 모든 압축을 거쳐도 남는다. 이전 결과에만 남아 있는 사실은 기껏해야 그 결과의 첫 줄로만 보존된다.

notes-survive.py Python 3.12.15 · pydantic 2.14.3 통과
"""A note the agent writes keeps a fact that an older read result had, after a compaction. The summary keeps only thefirst line of each read, and the fact sits on line 18 of format.py, so the read's summary line lacks it while the notekeeps it whole. The point rests on the last assertions: the fact is in the notes block and not in the read's line."""from lib.case import load_tasksfrom lib.chapter1 import callfrom lib.context import Compacting, Context, Measured, Notes, notes_toolsetfrom lib.loop import run_taskfrom lib.models import ScriptedModelfrom lib.trace import IdCounterBUDGET = 2000  # estimated tokens: the notes and the reads cross it, the last request fits under it# each note states a fact the run has just read in the case, so every note is true of unitcraftnotes = [    "format_quantity strips trailing zeros on line 18 of format.py (frac.rstrip), so 3.50 kg prints as 3.5 kg",    "test_pads_to_two_places in tests/test_format.py expects 3.5 kg to print as 3.50 kg, so the strip fails it",    "round_places goes through float, so 2.675 rounds to 2.67, and test_tie_at_a_binary_float_edge expects 2.68",]replies = [call("read_file", path="unitcraft/format.py"), call("note", text=notes[0]),           call("read_file", path="tests/test_format.py"), call("note", text=notes[1]),           call("read_file", path="unitcraft/rounding.py"), call("note", text=notes[2]),           call("read_file", path="README.md"), call("finish", summary="Read the case and noted the failing tests.")]store = Notes()ctx = Context(notes=store, prompt_budget=BUDGET)  # the notes are kept outside the older steps, so compaction keeps themmodel = Compacting(Measured(ScriptedModel(replies)), ctx)run = run_task(model, load_tasks(only=["T-01"])[0], notes_toolset(store), max_steps=16, ids=IdCounter())sent = model.inner.requests[-1][0]block = next(m["content"] for m in sent if m["content"].startswith("Your notes so far"))summary = next(m["content"] for m in sent if m["content"].startswith("Earlier steps"))read_line = summary.splitlines()[1]  # the first step: the read of format.py, with its first result line cut shortprint("steps:", run.steps)print("ended:", run.ended)print("compactions:", ctx.compactions)print("notes written:", len(store.lines))print("notes whole in the notes block:", sum(line in block for line in store.lines))print("lines in the notes block that name the fact (rstrip):", sum("rstrip" in line for line in block.splitlines()))print("summary line for the read of format.py:", read_line)assert ctx.compactions > 0, "the run should compact"assert all(line in block for line in store.lines), "every note should be whole in the notes block"assert "format.py" in read_line and "rstrip" not in read_line, "the read's summary line must lack the fact"assert "rstrip" in block, "the note must keep the fact"
출력python notes-survive.py
steps: 8
ended: finish
compactions: 5
notes written: 3
notes whole in the notes block: 3
lines in the notes block that name the fact (rstrip): 1
summary line for the read of format.py: step 1: read_file({"path": "unitcraft/format.py"}) -> """format_quantity: write a quantity as text, such as ``3.50

이 예제는 모델이 아니라 스크립트다. ScriptedModel이(가) 파일 네 개를 읽고 노트 세 개를 쓰며, 각 노트는 그 노트의 출처가 된 읽기 직후에 쓴다. 사실은 파일의 18번째 줄에 있고 요약은 파일의 첫 줄만 보존하므로, 해당 읽기에 대한 요약의 줄에는 사실이 아니라 독스트링이 들어 있다. 실행에서 압축은 5번 일어났다. 노트 3개는 모두 마지막 요청의 노트 블록에 온전히 들어 있으며, 그 줄 가운데 1개가 해당 사실을 명시한다. 각 노트는 실행이 사례에서 읽은 내용을 진술하므로, 독자는 사례 파일과 대조해 각각을 확인할 수 있다.

이는 메커니즘을 보여 줄 뿐이다. 모델이 실제로 노트를 쓴다는 것까지 보여 주지는 않는다. 다음 절에서는 모델의 기록을 가지고 이를 확인한다.

작업 규칙: 이후 단계에서 필요한 사실은 요약에만 두지 말고 노트에도 쓴다. 요약은 일부만 골라 보존하며, 노트는 이 책이 사실을 온전하게 보관하는 유일한 곳이다.

기록된 모델이 예산으로 한 일

기록 chapter-5-notes은 3장의 도구 세트 v2, 메모 도구, 2장의 중단 규칙으로 만들었다. 이 기록의 세 실행은 T-01, T-02, T-06이다. 과제 세트 실행 가운데 일곱 건이 단계 상한 16에 도달했다(T-01, T-02, T-06, T-10, T-11, T-13, T-16). 기록의 스크립트는 이 세 건을 각각 그 상한에 닿은 긴 실행으로 지정하며, 나머지 네 건은 실행하지 않는다. 모델이 도구와 예산으로 무엇을 했는지 보기 위해 압축을 켠 상태에서 이 세 실행을 재생했다.

recorded-context-use.py Python 3.12.15 · pydantic 2.14.3 통과
"""The three recorded runs of chapter 5, replayed with the compaction on: how each ended, whether its check passed,its note calls and compactions, and its largest prompt by the estimate and by the count the model reported. The pointrests on the check lines and the zero counts: no run passed its check, and no run wrote a note or was compacted."""import jsonfrom lib.case import load_tasksfrom lib.context import Compacting, Context, Measured, Notes, estimate, notes_toolsetfrom lib.loop import Stops, run_taskfrom lib.models import RECORDED, ReplayModelfrom lib.trace import IdCountermanifest = json.loads((RECORDED / "chapter-5-notes" / "manifest.json").read_text(encoding="utf-8"))recorded = {t["task"]: t for t in manifest["tasks"]}  # the recording's own check result, stored with each runids, passed, notes_total, compact_total, est_max, rec_max = IdCounter(), 0, 0, 0, 0, 0for task in load_tasks(only=["T-01", "T-02", "T-06"]):    notes = Notes()    context = Context(notes=notes)  # the default budget, 7168 tokens, which no run reaches    model = Compacting(Measured(ReplayModel("chapter-5-notes", task.id)), context)    # the step cap of 16 and the stop rules are those the recording was made with    run = run_task(model, task, notes_toolset(notes), max_steps=16, ids=ids,                   stops=Stops(repeat_limit=3, no_progress_limit=2))    run.close()    print(f"{task.id} kind: {recorded[task.id]['kind']}")    print(f"{task.id} ended: {run.ended}")    print(f"{task.id} check passed: {'yes' if recorded[task.id]['done'] else 'no'}")    print(f"{task.id} note calls: {sum(r['tool'] == 'note' for r in run.trace.records)}")    print(f"{task.id} compactions: {context.compactions}")    passed += recorded[task.id]["done"]    notes_total += sum(r["tool"] == "note" for r in run.trace.records)    compact_total += context.compactions    est_max = max([est_max] + [estimate(m, t) for m, t, _ in model.inner.requests])    rec_max = max([rec_max] + [n for _, _, n in model.inner.requests])print("total note calls:", notes_total)print("total compactions:", compact_total)print("runs whose check passed:", passed)print("largest estimated prompt over the three runs, in tokens:", est_max)print("largest recorded prompt over the three runs, in tokens:", rec_max)assert notes_total == 0, "the recorded runs made no note calls"assert compact_total == 0, "the recorded runs were never compacted"assert passed == 0, "none of the three recorded runs passed its check"
출력python recorded-context-use.py
T-01 kind: fix
T-01 ended: ask_user
T-01 check passed: no
T-01 note calls: 0
T-01 compactions: 0
T-02 kind: fix
T-02 ended: finish
T-02 check passed: no
T-02 note calls: 0
T-02 compactions: 0
T-06 kind: implement
T-06 ended: no_progress
T-06 check passed: no
T-06 note calls: 0
T-06 compactions: 0
total note calls: 0
total compactions: 0
runs whose check passed: 0
largest estimated prompt over the three runs, in tokens: 4012
largest recorded prompt over the three runs, in tokens: 3189

세 실행 어디에서도 모델은 메모를 쓰지 않았고, 압축된 실행도 없었다. 추정치가 본 가장 큰 프롬프트는 4012 토큰이었고, 모델이 보고한 가장 큰 프롬프트는 3189 토큰이었다. 둘 다 프롬프트 예산보다 작다.

각 실행은 컨텍스트가 예산에 가까워지기 전에 끝났고, 어느 것도 검사를 통과하지 못했다. T-01은 ask_user로 끝났는데, 모델이 사람에게 질문을 했을 때였다. T-01은 수정 과제이므로 그 질문은 잘못된 인계였다. T-02는 finish로 끝났는데, 모델이 finish를 호출했을 때였고 검사는 통과하지 못했다. T-06은 no_progress로 끝났으며, 이는 2장의 중단 규칙에 따른 것이다. 연속으로 두 번 수정했는데도 테스트 수가 바뀌지 않았기 때문이다. 따라서 모델이 스스로 두 실행을 멈췄는데 둘 다 잘못된 중단이었고, 나머지 하나는 중단 규칙이 멈췄다. 실행별로 출력한 검사 결과는 세 건 중 0건이 통과했음을 보여 준다.

세 과제에 대한 세 번의 실행은 그 과제들에서 일어난 일을 보여 줄 뿐이며, 나머지 열일곱 과제에 대해서는 아무것도 말해 주지 않는다. 이 실행들은 예산도 메모도 시험하지 못한다.

작업 규칙: 기록을 근거로 예산이나 도구를 판단하기 전에 각 실행이 어떻게 끝났는지 확인한다. 일찍 멈춘 실행은 예산을 시험하지 못하고, 도구를 한 번도 호출하지 않는 모델은 그 도구를 시험하지 못한다.

효과를 인용하지 말고 측정하라

Chroma가 2025년 7월에 발표한 기술 보고서 "Context Rot"(Hong, Troynikov, Huber)은 "단순한 과제에서도 입력 길이가 달라지면 모델 성능이 크게 달라진다"는 결과를 보고했다(Context Rot). 이 보고서는 Qwen3를 포함해 여러 업체의 LLM 18개를 자체 과제로 평가한다. 이 장은 그 과제를 다시 실행하지 않았으므로, 그 과제에서 나온 효과 크기는 인용하지 않는다.

대신 이 책은 자체 실행을 측정한다. 10장은 같은 과제 집합을 하네스 두 버전에서 실행하고, 완료된 과제의 수로 두 버전을 비교한다. 하네스 v2는 예산 외에도 여러 변경을 함께 도입하므로, 이 비교만으로는 예산 하나의 효과를 말할 수 없다. 8장의 자식 실행은 자기 단계 수로 세는 고유한 예산을 따로 유지한다.

여기에 나오는 예제는 각각 다른 것을 측정한다. 예산 예제는 기록된 프롬프트가 어디에 놓였는지를 측정하고, 압축 예제와 노트 예제는 하네스가 무엇을 보존하는지를 측정한다. 어느 것도 길이가 모델의 답에 어떤 영향을 주는지는 측정하지 않으므로, 이 장은 긴 프롬프트가 정확도를 떨어뜨린다고 말하지 않는다.

작업 규칙: 예산이 도움이 된다고 주장하기 전에, 실행이 보고하는 수치로 예산이 여러분의 과제 집합을 어떻게 바꾸는지 측정하라. 공개된 효과는 실험 설정과 출처를 함께 밝히고, 그 보고서의 결과로서만 인용하라.

예산이 잘못되는 경우와 이를 알아차리는 방법

실제로 예산에서는 네 가지 문제가 생기며, 각각 알아차릴 수 있다.

첫째는 모델이 바뀐 경우다. 새 모델은 윈도, 토크나이저, 응답 한도가 다를 수 있다. 이때 점검은 계속 실행되고 이전 수치를 기준으로 계속 통과하므로, 오류 없이 예산만 틀린 상태가 된다. 기록의 매니페스트에 있는 윈도가 하니스가 쓰는 상수와 더 이상 일치하지 않을 때 이를 알아차릴 수 있다. 따라서 두 값을 연결해 두고 둘이 다르면 실행을 실패시킨다. 이 점검은 윈도 절에서 설명한다.

둘째는 추정이 어긋나는 경우다. 추정은 해당 모델과 눈앞의 텍스트에 대한 토큰당 문자 수 규칙만큼만 정확하다. 응답에는 이미 모델이 계산한 값이 들어 있으므로, 처음 몇 차례의 실제 실행에서는 매 단계마다 두 값을 비교하고 그 쌍을 기록한다. 추정이 계산값보다 작다면 조치해야 한다는 신호다. 하니스가 실제로는 없는 여유가 있다고 믿게 되기 때문이다.

셋째는 요약이 이후 단계에 필요한 내용을 빠뜨리는 경우다. 압축된 실행은 같은 도구를 다시 호출할 수 있다. 첫 번째 결과가 이제 요약 속의 한 줄이 되었기 때문이다. 2장의 중단 규칙은 정확히 같은 반복은 잡아내지만, 경로가 약간 다른 같은 파일 읽기처럼 거의 같은 반복은 통과한다. 한 실행이 같은 파일을 읽는 횟수를 세고, 반복이 나타나면 요약이 무언가를 잃었다는 신호로 본다.

넷째는 노트 블록이 커지는 경우다. 노트는 매 단계마다 전송되고 압축으로도 잘리지 않으며, 노트 하나의 길이나 노트의 개수를 제한하는 장치도 없다. 노트를 많이 쓰는 실행은 고정 부분이 계속 커져서, 결국 압축으로는 예산을 맞출 수 없게 된다. 컨텍스트는 압축 후에도 여전히 예산을 넘는 호출의 수를 over_budget에 센다. 이 값이 0보다 크면 그것이 신호다.

작업 규칙: 실제 실행의 매 단계마다 추정값과 보고된 계산값을 기록하고, 추정이 계산값보다 작으면 결함으로 본다. 실행이 자신의 요약이 이미 다루는 파일을 요청하면, 파일을 다시 읽기 전에 요약이 무엇을 남겼는지 확인한다.

이 장이 내린 결정

  • 프롬프트 예산은 로드 설정에서 응답 몫을 뺀 값이며, 모델이 공개한 길이가 아니라 로드 설정을 따른다.
  • 하네스는 프롬프트를 토큰당 세 글자로 추정한다. 이 규칙은 작업 집합 단계에서 정했고, 이 규칙을 정하지 않은 이후의 chapter-5-notes 녹화에서도 같은 양상이 나타난다.
  • 압축은 로컬에서 결정적으로 이루어지므로, 다시 재생한 실행은 원래 실행과 똑같이 압축된다. 오래된 단계는 한 줄씩으로 줄고, 마지막 호출과 그 결과는 한 글자도 바꾸지 않고 남는다. 도구 결과 위에 걸치는 절단은 거부된다.
  • 노트는 모델이 사용할 수 있는 도구다. 노트는 매 단계에서 이슈 뒤에 전송되므로 압축이 노트를 자르는 일은 없으며, 노트를 쓸지는 모델이 결정한다.
  • 이 책은 공급사의 서버 측 압축을 사용하지 않는다.

녹화는 프롬프트가 한도에 들어맞았으며, 두 단계 집합 모두에서 추정값이 실제 개수보다 높게 유지되었음을 보여 준다. 10장은 두 하네스 버전을 개수로 비교하는데, 예산 하나만으로는 그 차이를 설명할 수 없다.

작업 규칙: 예산이나 도구를 시험한 실행을 명시한다. 어떤 실행도 도달하지 못한 예산에 관한 주장은 모델이 아니라 설계에 관한 주장이다.

이 판의 이 장

2026.11.2판예제 통과 2026년 11월 20이 장에서 5개 예제개 중 5개가 통과한다

영어판 2026.11.2판을 번역한 것이다.

이 절 인용

형식

각 형식은 이 번역이 따르는 영문 원서를 출처로 표기한다.

모든 형식은 이 판을 명시한다. 링크는 현재 판을 열며, 여기서 절의 제목은 본문이 마지막으로 바뀐 시점을 알려 준다. 접근 날짜와 검색 날짜는 이 자료를 여는 날짜다.

이 페이지의 내용

12장 중 5장: 작업이 늘어나도 컨텍스트를 쓸모 있게 유지하기

  1. 모델이 가진 윈도
  2. 기록된 실행이 예산에 가장 근접한 지점
  3. 하네스가 프롬프트를 셀 수 없을 때는 추정한다
  4. 마지막 결과는 끝에 둔다
  5. 오래된 단계는 압축하고 마지막 쌍은 유지한다
  6. 컨텍스트 바깥에 노트를 보관한다
  7. 기록된 모델이 예산으로 한 일
  8. 효과를 인용하지 말고 측정하라
  9. 예산이 잘못되는 경우와 이를 알아차리는 방법
  10. 이 장이 내린 결정

맨 위로 돌아가기전체 장