변경을 일으키는 도구에 관문 두기

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

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

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

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

이 장을 마치면 에이전트의 변경을 사람이 승인할 때까지 에이전트 자신의 사본에만 두는 방법, 그 승인이 사람이 읽은 바로 그 변경을 대상으로 하는지 확인하는 방법, 거부를 에이전트의 실행이 멈춘 이유로 되돌려 주는 방법을 익힌다.

이 책의 에이전트는 unitcraft을(를) 유지보수한다. 이 라이브러리에 반영되는 모든 변경은 유지보수자가 책임지며, 에이전트는 이 라이브러리의 임시 사본에서 작업한다. 테스트와 편집은 모두 사본에서 이루어진다. 그래도 변경이 유지보수자가 소유한 라이브러리에 언제 반영될지는 누군가가 결정해야 하며, 여기서 유지보수자는 이슈를 등록한 사람이다. 작업 T-04가 이 문제를 분명히 보여 준다. 이 작업의 이슈는 단위를 하나, 곧 인치를 더 추가해 달라고 요청하고, 에이전트의 사본에는 인치를 추가하는 편집이 들어 있다. 이 편집을 반영할지는 사람이 내릴 결정이며, 에이전트가 사람을 대신해 내려서는 안 된다.

이 장은 그 결정을 묻는 하네스의 부분을 만든다. 에이전트의 파일 도구는 실행의 사본에만 쓰며, 라이브러리는 사람이 승인한 뒤 하네스가 그 실행의 diff를 적용할 때만 바뀐다. 그 위에 두 가지 검사가 놓인다. 하나는 finish에서 diff를 읽는 관문이고, 다른 하나는 모든 도구 호출 전후로 라이브러리의 바이트를 비교하는 감시 장치이다. 관문과 감시 장치는 학습용 코드이자 두 번째 방어층이며, 어느 쪽도 샌드박스가 아니다. 에이전트가 작성한 코드에 대한 1차 방어는 컨테이너나 가상 머신이며, 이는 7장에서 설명한다. 여기에 실린 예제는 어느 것도 이를 실행하지 않으며, 어떤 녹화 기록도 이를 보여 주지 않는다. 각 도구 호출은 사례 라이브러리의 바이트 비교로 감싸이고, 감시 장치는 안전한 쪽으로 닫히며 실패한다(fail closed). 라이브러리가 바뀌었다면 실행은 library_changed(으)로 끝나고, 하네스는 아무것도 적용하지 않으며 아무것도 복원하지 않는다. 첫 번째 절에서는 사본이 막지 못하는 것이 무엇인지 설명한다.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

The copy comes first

The agent's file tools reach files only through its copy. Each run gets its own copy, made by scratch_copy in run_task, and the tools work through a Workspace rooted at that copy. Workspace.locate resolves every path the model gives. It refuses a path that is absolute, one with a .. part, one with a NUL byte or a backslash, one that resolves through a symlink to a place outside the copy, and any write into .github/. Through these tools, a path that does not resolve inside the copy never reaches the disk.

Those checks cover the paths the tools take. They do not cover code the agent runs. run_tests runs pytest on the copy, and pytest runs whatever the model wrote there. A test module the model adds is code too. The test run imports it and runs it with the harness's own user rights and no sandbox, so it can write to any path that user can write, including the library. The runner does not load conftest.py files (run_pytest passes --noconftest), but it does collect test modules, and that is the route this section means. The gate cannot stop that write, because the gate reads only the diff at finish. The library guard, in its section, sees the write once run_tests returns, ends the run as library_changed, and restores nothing. It detects the write after it happens. It does not prevent it.

This is the open side of the harness, and it is the main limit of this chapter. Chapter 7 describes the book's teaching sandbox, which runs the agent's commands with caps and a clean environment. Its table lists what it leaves open, and writes outside the copy are on that list. A container or a virtual machine is the primary defence for running code a model wrote, and chapter 7 explains both. The checks in this chapter are teaching code, written so a reader can open them, copy them and test them. They are not a substitute for that isolation.

The library changes in one place. apply in lib/permissions.py writes new bytes into the library, and its only caller is the gate's answer to a proposal, after a yes. library_copy makes the throwaway library that the examples apply to, so the book's case folder is never written. When a run ends, Gate.settle reports what the copy still holds, and nothing in the copy is written back to the library.

A write can also fail partway through an apply. The next example gives a proposal of two files, and puts a folder where the second file goes, so the second write fails.

apply-all-or-nothing.py Python 3.12.15 · pydantic 2.14.3 통과
"""A proposal of two files where the second cannot be written, because a folder stands where it goes. The first fileis put back, the error goes back as the handoff, and the library holds the bytes it held before the finish."""from lib.case import CASEfrom lib.permissions import Gate, answer, gated, library_copyfrom lib.tasks import snapshotfrom lib.tools import V1, Workspacewith library_copy() as library, library_copy() as scratch:    (library / "unitcraft" / "extra.py").mkdir()    before = snapshot(library, ".")    (scratch / "README.md").write_text("A new line in the readme.\n", encoding="utf-8")    (scratch / "unitcraft" / "extra.py").write_text('"""Extra."""\nTOTAL = 1\n', encoding="utf-8")    gate = Gate(library, lambda p: answer(p, True))    result = gated(V1, gate).call(Workspace(scratch), "finish", {"summary": "Two files."})    print("ended:", result.end)    print("handoff:", result.question)    print("README as before:", snapshot(library, "README.md") == snapshot(CASE, "README.md"))    print("library bytes unchanged:", snapshot(library, ".") == before)    print("applied:", gate.counts["applied"], "refused:", gate.counts["refused"])    assert result.end == "ask_user" and "apply failed (IsADirectoryError)" in result.question    assert snapshot(library, ".") == before and gate.counts["applied"] == 0
출력python apply-all-or-nothing.py
ended: ask_user
handoff: p-1 was not applied: apply failed (IsADirectoryError); library restored
README as before: True
library bytes unchanged: True
applied: 0 refused: 1

apply puts back each file it had touched and each folder it had made, and the gate holds the proposal with the error as its reason: p-1 was not applied: apply failed (IsADirectoryError); library restored. The README, which was written first, is as it was before the finish, and the library's bytes are unchanged. The gate catches an OSError as a held proposal. Any other exception also puts the files back and is then raised, and no example here shows that path.

Working rule: Give each run its own copy, refuse every path that resolves outside it, and let exactly one function write to the original, called only after a yes. Then name what the run's code can still do to the original, check that with a guard, and do not count the gate as the protection.

이 하네스가 속한 모드

게이트는 먼저 한 가지 질문에 답해야 한다. 에이전트가 멈추고 물을 때 누가 답하는가? Claude Code의 대화형 모드는 세션 안의 사람에게 묻는다. Claude Agent SDK는 이 점에서 서로 다른 여러 권한 모드를 제공하며, 하네스는 자신이 어느 모드와 비슷한지 밝혀야 한다. 그 답에 따라, 승인이 필요한 호출을 아무도 응답할 수 없을 때 어떻게 처리할지가 정해지기 때문이다. 이 하네스에는 터미널도 세션도 없다. 헤드리스 실행이며, 답할 수 있는 주체는 호출자가 넘겨 주는 콜백뿐이다.

공급사 문서는 이 경우들을 구분해 설명한다. Claude Code의 권한 문서에 따르면 규칙은 거부, 확인, 허용 순서로 검사하며 처음 일치하는 규칙이 결과를 결정한다. 또한 Claude Code는 기본적으로 파일을 수정하기 전에 확인을 요청하고, 작업 디렉터리 안의 읽기 전용 작업은 확인 없이 실행한다고 한다. Agent SDK의 권한 문서는 dontAsk 모드를 설명한다. 이 모드에서는 원래 확인을 요청했을 모든 호출을 승인 콜백을 부르지 않고 거부한다. 이 장을 쓰기 위해 두 제품을 실행해 보지는 않았으므로, 두 제품에 관한 주장은 공급사의 것이며 그렇게 표시했다.

이 하네스는 콜백을 유지한다. 승인이 필요한 변경은 승인자를 호출하고 답을 기다린다. 공급사의 dontAsk 모드는 여기서 중요한 한 가지가 다르다. 그 모드는 이런 호출을 콜백 없이 거부하지만, 이 하네스는 항상 콜백을 호출한다. 이 책은 이를 dontAsk가 아니라 콜백이 있는 헤드리스 실행이라고 부른다. 게이트는 어떤 모델 어댑터로 실행하든 같다. 게이트는 모델이 아니라 도구를 감싸기 때문이다. 모델마다 달라지는 부분은 4장의 모델 프로토콜이다.

작업 규칙: 게이트를 추가하기 전에 모드의 이름을 정하라. 호출자에게 답할 수 있는 콜백이 있다면, 게이트가 그 콜백을 호출하고 답을 기다리게 하라. 승인자 없이 만든 게이트는 시작을 거부한다. 이 장의 코드는 오류를 발생시킨다. 답할 주체가 없을 때 다른 쪽으로 넘기는 설계에는 별도의 경로가 필요하며, 이 장의 어떤 예제도 그런 경로를 보여 주지 않는다.

게이트는 finish에 있다

에이전트가 하는 일의 대부분은 관리자가 소유한 어떤 것도 바꾸지 않는다. 에이전트는 파일을 나열하고, 읽고, 보이는 테스트를 실행한다. 사본에 가하는 편집은 에이전트 자신의 작업이며, 그렇게 하도록 의도된 것이다. 라이브러리에 대한 변경을 요청하는 호출은 finish 하나뿐이므로 게이트의 검사는 그곳에 있고, finish가 제안이 이루어지는 지점이다.

게이트는 집합의 모든 도구를 감싸며, 각 도구의 분류는 lib/permissions.py에 있는 하나의 표에서 나온다. 읽기 도구(list_files, read_file, run_tests, ask_user)는 그대로 통과하며, 라이브러리 가드가 그 각각을 감시한다. run_tests는 읽기 분류에 속하지만, 사본 절에서 설명하듯이 모델이 작성한 코드를 실행한다. 편집과 쓰기(edit_file, write_file)는 사본에서 실행되며, 게이트는 각 호출을 센다. finish는 제안이다. 그 분류는 하네스의 표에서 정해지며 모델이 작성한 어떤 것에도 좌우되지 않으므로, 모델의 요약도 도구 자체의 설명도 분류를 정하지 못한다. 모델에 전달되는 이름, 설명, 스키마는 게이트가 있든 없든 같으므로, 게이트가 걸린 도구로 보낸 요청은 게이트 없이 보낸 요청과 같은 요청이다.

제안은 모델이 쓴 요약이 아니라 라이브러리에 대한 사본의 전체 diff이다. pending는 바이트가 다른 파일을 각각 나열하고, diff_text는 파일마다 헤더 하나를 쓰고 그 뒤에 통합 diff를 붙인다. 제안의 식별자는 변경된 바이트의 해시이며, 이는 바인딩 절에서 설명한다. 승인자는 제안의 ID, 요약, 변경된 파일 목록, 표시된 그대로의 diff 텍스트, 해시를 받는다. 승인자는 예 또는 아니오, 이유, 그리고 자신이 답하는 대상의 ID와 해시로 응답한다. 요약은 변경에 대한 모델의 주장으로 표시될 뿐이며, 게이트는 이를 증거로 취급하지 않는다. 사본에 변경이 없으면 finish는 자체 결과와 함께 통과하므로, 아무것도 바꾸지 않은 실행에는 아무것도 묻지 않는다. 변경이 있으면 승인자는 도구 호출 안에서 호출되고, 실행은 답을 기다린다. 게이트가 강제 모드일 때 finish 도구 자체의 본문은 예라는 답이 온 뒤에만 실행된다.

과도한 행위 권한에 대한 OWASP의 지침은 영향이 큰 행동을 실행하기 전에 사람이 승인할 것, 그리고 에이전트가 필요한 도구만 가질 것을 요구한다. 이것은 측정이 아니라 지침이며, 이 장은 이를 설계의 근거로 다룰 뿐 설계가 작동한다는 증명으로 다루지 않는다.

과제 집합은 이 사례에 대한 20개의 과제이며, 대부분 숨겨진 검사로 채점된다(과제 집합에서 모두 다룬다). 이 실행들은 도구 집합 v1과 게이트 없이, 1장에서 재생하는 모델인 Qwen3-4B-Instruct-2507로 기록되었다. 게이트는 각 요청을 바꾸지 않으므로, 게이트를 거친 재생은 같은 요청을 보내고 기록된 같은 응답을 받는다. 작동해야 하는 경로부터 시작한다. 기록된 T-04 실행을 재생하고, 사람이 예라고 답한다.

gate-applies-only-on-yes.py Python 3.12.15 · pydantic 2.14.3 통과
"""The recorded T-04 run (add the inch) with the gate and a scripted yes: its one changed file reaches the library, andthe hidden check fails before the apply and passes after it. The second part shows two yeses that cannot apply: a copythat changed after the person looked, and an answer that names another proposal."""from lib.case import load_tasksfrom lib.permissions import Answer, Gate, gated, library_copy, replay_task, scriptedfrom lib.tasks import hidden_check_passesfrom lib.tools import V1, Workspacetask = load_tasks(only=["T-04"])[0]with library_copy() as library:    assert not hidden_check_passes(task, library)    gate = Gate(library, scripted((True, "")))    run = replay_task("T-04", gate, library)    print("ended:", run.ended)    print("proposals:", gate.counts["proposals"], "asked:", gate.counts["asked"])    print("applied:", gate.counts["applied"], "files applied:", gate.counts["files applied"])    print("visible tests after the apply:", Workspace(library).run_tests().splitlines()[0])    print("hidden check after the apply:", hidden_check_passes(task, library))    assert run.ended == "finish" and gate.counts["applied"] == 1 and hidden_check_passes(task, library)    run.close()with library_copy() as library, library_copy() as scratch:    ws = Workspace(scratch)    (scratch / "unitcraft" / "extra.py").write_text('"""Extra."""\nTOTAL = 1\n', encoding="utf-8")    def drift(proposal):  # the copy changes in the window between the person's yes and the apply        (scratch / "unitcraft" / "extra.py").write_text('"""Extra."""\nTOTAL = 2\n', encoding="utf-8")        return Answer(True, proposal.id, proposal.sha256)    late = gated(V1, Gate(library, drift)).call(ws, "finish", {"summary": "Add a constant."})    print("drifted copy, handoff:", late.question)    wrong = gated(V1, Gate(library, lambda p: Answer(True, "p-7", p.sha256)))    print("answer for another proposal, handoff:", wrong.call(ws, "finish", {"summary": "Add a constant."}).question)    assert late.end == "ask_user" and "changed after" in late.question    assert not (library / "unitcraft" / "extra.py").exists()
출력python gate-applies-only-on-yes.py
ended: finish
proposals: 1 asked: 1
applied: 1 files applied: 1
visible tests after the apply: 8 failed, 22 passed
hidden check after the apply: True
drifted copy, handoff: p-1 was not applied: the copy changed after the answer
answer for another proposal, handoff: p-1 was not applied: the answer is to another proposal or diff

예는 변경을 적용하며, 숨겨진 검사는 적용 이후에만 통과한다. 실행은 finish로 끝나고, 게이트는 자신이 물어본 제안을 적용한다. 변경이 반영되면 보이는 테스트 모음은 8 failed, 22 passed를 보고한다. 이 수치는 과제를 채점하지 않는다. 채점하는 것은 숨겨진 검사이며, 예제는 이 검사가 적용 전에는 실패하고 적용 후에는 통과함을 확인한다.

예제의 후반부는 적용될 수 없는 두 가지 예를 검사한다. 첫째에서는 사람이 사본을 본 뒤에 승인자 안에서 사본이 바뀐다. 둘째에서는 답이 다른 제안을 가리킨다. 각각 고유한 이유로 거부되는데, 첫째는 p-1 was not applied: the copy changed after the answer이고 둘째는 p-1 was not applied: the answer is to another proposal or diff이다. 두 경우 모두 라이브러리는 바뀌지 않은 채 남으며, 예제는 이를 단언한다.

finish 도구의 본문도 같은 규칙에 속한다.

finish-body-waits-for-yes.py Python 3.12.15 · pydantic 2.14.3 통과
"""A finish that publishes does its work only after a yes. With a no the body never runs; with a yes it runs once,after the change is applied to the library."""from dataclasses import replacefrom lib.permissions import Gate, answer, gated, library_copyfrom lib.tools import V1, ToolResult, Workspacepublished = []def finish_and_publish(ws, args):    published.append(args.summary)    return ToolResult("run ended", brief="finish", end="finish", summary=args.summary)publishing = replace(V1, tools=tuple(replace(t, run=finish_and_publish) if t.name == "finish" else t                                     for t in V1.tools))def finish_with(yes: bool):    with library_copy() as library, library_copy() as scratch:        gate = Gate(library, lambda p: answer(p, yes, "decided"))        (scratch / "unitcraft" / "n.py").write_text("N = 1\n", encoding="utf-8")        result = gated(publishing, gate).call(Workspace(scratch), "finish", {"summary": "Publish."})        return result, gate, (library / "unitcraft" / "n.py").exists()no_result, _, no_added = finish_with(False)print("no: ended", no_result.end, "| publish ran:", len(published), "| file added:", no_added)yes_result, gate, yes_added = finish_with(True)print("yes: ended", yes_result.end, "| publish ran:", len(published), "| file added:", yes_added)print("applied:", gate.counts["applied"])assert no_result.end == "ask_user" and len(published) == 1 and not no_addedassert yes_result.end == "finish" and yes_added and gate.counts["applied"] == 1
출력python finish-body-waits-for-yes.py
no: ended ask_user | publish ran: 0 | file added: False
yes: ended finish | publish ran: 1 | file added: True
applied: 1

코드는 실행에 무언가를 게시하는 finish를 주고, 같은 제안을 두 번 재생한다. 아니오에서는 게시 본문이 실행되지 않고 파일이 추가되지 않는다. 결과는 ended ask_user | publish ran: 0 | file added: False이다. 예에서는 파일이 추가되고 본문이 한 번 실행된다. 결과는 ended finish | publish ran: 1 | file added: True이다.

작업 규칙: 라이브러리를 바꿀 수 있는 단 하나의 호출에서 사본의 전체 diff를 제안하고, 적용 직전에 그 diff를 다시 해시한다. 사람이 본 뒤에 사본이 달라졌다면 답이 무엇이든 거부한다. 적용은 해시된 바이트를 쓰기 때문이다. 도구 자체의 본문은 예라는 답이 온 뒤에만 실행한다.

승인은 하나의 요청에 대한 답이다

승인은 사람이 읽은 변경에 대한 것일 때만 가치가 있다. 하나의 게이트가 둘 이상의 제안을 받는 순간 문제가 드러난다. 여러 실행이 하나의 게이트를 공유할 때가 그렇다. 둘을 묶는 장치가 없으면 한 변경에 준 답이 다음 변경에 그대로 넘어갈 수 있다.

게이트는 식별자로 이 둘을 묶는다. 각 제안은 게이트의 카운터에서 다음 ID를 받는다. 처음은 p-1이고 그다음은 p-2이며, 이런 식으로 이어진다. 제안에는 변경된 바이트의 SHA-256 해시도 함께 담긴다. 이 해시는 사람이 보는 텍스트만이 아니라 변경된 모든 파일의 정확한 바이트를 경로 순서대로 대상으로 한다. 답은 이 둘을 모두 명시해야 한다. 게이트는 무엇이든 적용하기 전에 두 값을 비교하고, 게이트 절에서 설명하듯 사본을 다시 해시한다. 도구 승인에 관한 Microsoft의 Agent Framework 문서도 같은 패턴을 설명한다. 이 문서에 따르면 로컬 승인 응답은 같은 세션에 기록된 보류 중인 승인 요청과 일치할 때만 도구 호출을 승인하며, 프레임워크는 묶이지 않은 응답을 무시하고 경고를 기록한다. 바인딩을 끄는 옵션에 대한 설명에서는 바인딩을 끄면 조작되거나 재전송된 응답이 권한이 필요한 호출을 승인할 수 있다고 밝힌다.

사람이 읽는 텍스트는 원본 그대로가 아니라 풀어 쓴 형태다. diff_text는 터미널이 동작으로 해석할 수 있는 모든 문자를 눈에 보이는 이스케이프로 써 준다. 그래서 캐리지 리턴이나 이스케이프 시퀀스는 diff에서 텍스트로 나타나며, UTF-8 텍스트가 아닌 파일은 바이트의 해시로만 표시된다.

hidden-diff-lines-shown.py Python 3.12.15 · pydantic 2.14.3 통과
"""Two files whose text would hide a line in a terminal: a carriage return that overwrites the line before it, and anescape that erases a line. The proposal shows both written out, so every line the person reads is in the file."""from lib.permissions import Gate, answer, gated, library_copyfrom lib.tools import V1, WorkspaceCR = "HIDDEN_CR = 'not shown'\r# a comment long enough to cover the line before it\n"ESC = "HIDDEN_ESC = 'not shown'\n\x1b[1A\x1b[2K# tidy\n"seen = []def person(proposal):    seen.append(proposal)    return answer(proposal, False, "not this change")with library_copy() as library, library_copy() as scratch:    gate = Gate(library, person)    tools, ws = gated(V1, gate), Workspace(scratch)    tools.call(ws, "write_file", {"path": "unitcraft/a_cr.py", "text": CR})    tools.call(ws, "write_file", {"path": "unitcraft/b_esc.py", "text": ESC})    tools.call(ws, "finish", {"summary": "Add two comment-only modules."})    shown = seen[0].diff    for line in (ln for ln in shown.splitlines() if "HIDDEN" in ln):        print("shown:", line)    print("headers that flag control characters:", shown.count("contains control characters"))    print("raw CR or ESC in the shown text:", sum(ch in shown for ch in "\r\x1b"))    print("applied:", gate.counts["applied"], "refused:", gate.counts["refused"])    assert "\r" not in shown and "\x1b" not in shown and shown.count("contains control characters") == 2    assert gate.counts["applied"] == 0
출력python hidden-diff-lines-shown.py
shown: +HIDDEN_CR = 'not shown'\r# a comment long enough to cover the line before it
shown: +HIDDEN_ESC = 'not shown'
headers that flag control characters: 2
raw CR or ESC in the shown text: 0
applied: 0 refused: 1

이 스크립트는 터미널에서 한 줄을 가릴 만한 내용의 파일 두 개를 쓴다. 하나에는 앞 줄을 덮어쓸 캐리지 리턴이 들어 있고, 다른 하나에는 한 줄을 지울 이스케이프가 들어 있다. 사람은 두 줄을 모두 이스케이프된 형태로 본다. 스크립트는 제어 문자를 표시한 헤더의 수를 2에, 표시된 텍스트에 남은 원본 CR 또는 ESC의 수를 0에 출력한다. 스크립트 속 사람은 거부로 답하므로 아무것도 적용되지 않는다.

answer-binds-bytes.py Python 3.12.15 · pydantic 2.14.3 통과
"""A file that is not UTF-8 text is shown by the hash of its bytes, and the yes binds to those bytes. When the copy'sbytes change after the yes, the apply is refused, even though both versions decode to the same replacement characters."""from lib.permissions import Change, Gate, answer, digest_changes, gated, library_copyfrom lib.tools import V1, Workspacewith library_copy() as library, library_copy() as scratch:    (scratch / "unitcraft" / "blob.bin").write_bytes(b"DATA \xff\n")    def swap_then_yes(proposal):        print("shown as:", proposal.diff.split(";")[0])        (scratch / "unitcraft" / "blob.bin").write_bytes(b"DATA \xfe\n")        return answer(proposal, True)    gate = Gate(library, swap_then_yes)    result = gated(V1, gate).call(Workspace(scratch), "finish", {"summary": "Add a blob."})    print("ended:", result.end)    print("handoff:", result.question)    print("applied:", gate.counts["applied"], "| blob in library:", (library / "unitcraft" / "blob.bin").exists())    one = digest_changes([Change("x.bin", None, b"\xff")])    two = digest_changes([Change("x.bin", None, b"\xfe")])    print("hashes differ for \\xff and \\xfe:", one != two)    assert result.end == "ask_user" and "changed after" in result.question and gate.counts["applied"] == 0    assert one != two
출력python answer-binds-bytes.py
shown as: == unitcraft/blob.bin: added, not UTF-8 text
ended: ask_user
handoff: p-1 was not applied: the copy changed after the answer
applied: 0 | blob in library: False
hashes differ for \xff and \xfe: True

이 스크립트는 나머지 절반을 보여 준다. 유효한 UTF-8이 아닌 바이트를 가진 파일을 추가하며, 승인자에게는 == unitcraft/blob.bin: added, not UTF-8 text가 표시된다. 승인 뒤에 사본의 바이트를 한 바이트에서 다른 바이트로 바꾸는데, 두 바이트는 모두 같은 대체 문자로 디코딩된다. 적용은 거부된다. p-1 was not applied: the copy changed after the answer. 스크립트는 두 바이트열의 해시가 서로 다르다는 것도 단언하므로, 이 해시는 디코딩된 텍스트의 해시가 아니다.

하나의 예제에서 두 실행이 게이트를 공유할 수 있다.

approval-in-transcript.py Python 3.12.15 · pydantic 2.14.3 통과
"""Two proposals in one transcript, through one gate: the recorded T-04 run is answered yes and its inch reaches thelibrary; a stored T-09 run (fix the Celsius offset) is answered no and handed back. Each answer is logged with theproposal ID and the hash of the diff it answers."""from lib.case import CASEfrom lib.permissions import Gate, library_copy, replay_task, scripted, stored_taskfrom lib.tasks import snapshotwith library_copy() as library:    gate = Gate(library, scripted((True, ""), (False, "not in this change")))    first = replay_task("T-04", gate, library)    second = stored_task("T-09", gate, library)    print("T-04 ended:", first.ended, "| T-09 ended:", second.ended)    print("transcript, T-04:", first.trace.lines()[-1])    print("transcript, T-09:", second.trace.lines()[-1])    for line in gate.log:        print("gate:", line)    print("applied:", gate.counts["applied"], "refused:", gate.counts["refused"])    assert first.ended == "finish" and second.ended == "ask_user" and gate.counts["applied"] == 1    assert snapshot(library, "unitcraft/units.py") != snapshot(CASE, "unitcraft/units.py")    assert snapshot(library, "unitcraft/temperature.py") == snapshot(CASE, "unitcraft/temperature.py")    first.close()    second.close()
출력python approval-in-transcript.py
T-04 ended: finish | T-09 ended: ask_user
transcript, T-04: step 5: finish: p-1 yes, applied 1 files
transcript, T-09: step 6: finish: p-2 was not applied: the person said no: not in this change
gate: p-1 1 files, diff 06ee73fd984f: asked
gate: p-1 answer yes, bound to p-1 and 06ee73fd984f
gate: p-1 applied: 1 files
gate: p-2 1 files, diff 95fb833675dd: asked
gate: p-2 answer no, bound to p-2 and 95fb833675dd
gate: p-2 not applied: the person said no: not in this change
applied: 1 refused: 1

이 코드는 기록된 T-04 실행을 돌리고 승인으로 답한다. 이어서 저장된 T-09 실행을 돌리고 거부로 답한다. T-09 실행은 기록된 요청을 그대로 재생하지 않는다. 도구 결과는 이 사본에서 나오며 기록과 다를 수 있으므로, 저장된 응답을 단계별로 주입한다. 각 답은 해당 제안 옆에 기록된다. T-09의 대화 기록 줄은 step 6: finish: p-2 was not applied: the person said no: not in this change라고 적혀 있고, T-04 줄은 승인과 적용으로 끝난다. 게이트의 로그에는 같은 쌍이 전부 담겨 있다. 답마다 한 줄이 있으며, 제안과 그 답이 명시한 해시의 처음 열두 글자를 적는다. 어떤 diff에 승인이 적용되었는지 알고 싶은 독자는 이 글자들을 표시되었던 제안과 대조할 수 있다. 두 개의 단언이 결과를 확인한다. T-04의 변경은 라이브러리에 반영되었고, T-09의 변경은 반영되지 않았다.

ID는 하나의 게이트 안에서만 증가하므로, 두 게이트가 모두 p-1을 발급할 수 있다. 이는 열려 있는 한계이며, 열린 한계 절에서 다룬다.

작업 규칙: 모든 제안에 ID와 그 바이트의 해시를 부여하고, 답이 둘 다 명시하도록 요구하며, 적용하기 전에 둘을 다시 확인한다. 사람에게는 모든 제어 문자를 풀어 쓴 텍스트를 보여 준다. 각 답을 제안 옆에 쌍으로 기록하여, 읽는 사람이 승인을 그 승인이 적용된 변경과 대조할 수 있게 한다.

일부 변경은 질문 없이 거부된다

일부 변경은 사람이 결정할 사안이 아니다. 이 사례의 규칙은 에이전트가 공개 이름을 바꾸는 일과 테스트를 변경하는 일을 금지하며, 승인으로는 이런 종류의 규칙을 풀 수 없다. 이런 변경을 사람에게 물으면 결정이 엉뚱한 곳으로 넘어가므로, 게이트는 질문하기 전에 이런 변경을 거부한다.

assess는 요약이 아니라 라이브러리와 비교한 diff에서 거부 사유를 계산한다. 거부하는 변경은 다섯 가지다. .github/ 아래의 변경은 거부된다. tests/ 아래에서 파일을 삭제하는 변경은 거부된다. tests/ 아래의 기존 파일을 수정하는 변경은 거부된다. tests/ 아래의 새 파일 중 test_*.py 모듈이 아닌 것은 거부된다. 제거된 이름도 거부된다. 라이브러리에는 정의되어 있으나 복사본에서는 더 이상 정의되지 않은 unitcraft/ 모듈의 최상위 공개 이름, 그리고 라이브러리에는 있으나 복사본에는 없는 최상위 test_ 함수가 여기에 해당한다. 새 test_*.py 모듈은 허용된다. 두 트리를 이름 단위로 비교하므로, 이름을 바꾸면 제거된 이름으로 나타난다. 거부 사유는 파일에서 계산되므로 모델이 쓴 말은 결과를 바꿀 수 없다.

never-class-refused.py Python 3.12.15 · pydantic 2.14.3 통과
"""A rename of a public name and the removal of a test, each an edit that succeeds on the copy, with a summary thatsays no approval is needed. The gate reads the diff: both are refused as never-class, and the person is never asked."""from lib.permissions import Gate, gated, library_copy, scriptedfrom lib.tools import V1, WorkspaceREMOVED = ('def test_parses_negative_value():\n    q = parse_quantity("-2 m")\n'           '    assert (q.value, q.unit) == (Decimal("-2"), "m")\n\n\n')with library_copy() as library, library_copy() as scratch:    gate = Gate(library, scripted((True, "")))    tools, ws = gated(V1, gate), Workspace(scratch)    rename = {"path": "unitcraft/parse.py", "old": "def parse_quantity(text: str)", "new": "def parse(text: str)"}    print("rename:", tools.call(ws, "edit_file", rename).text)    print("test removal:", tools.call(ws, "edit_file", {"path": "tests/test_parse.py", "old": REMOVED, "new": ""}).text)    result = tools.call(ws, "finish", {"summary": "Tidy-up: a rename and a removed flaky test. No approval needed."})    print("ended:", result.end)    print("reasons:", result.question)    print("asked:", gate.counts["asked"], "held as never:", gate.counts["held as never"])    assert result.end == "ask_user" and gate.counts["asked"] == 0    assert "removes public name parse_quantity" in result.question    assert "removes test test_parses_negative_value" in result.question
출력python never-class-refused.py
rename: edited unitcraft/parse.py
test removal: edited tests/test_parse.py
ended: ask_user
reasons: p-1 was not applied: the harness refuses it: changes the test file tests/test_parse.py; removes public name parse_quantity; removes test test_parses_negative_value
asked: 0 held as never: 1

이 예제에서는 두 가지 수정이 복사본에 들어간다. 하나는 공개 함수의 이름 변경이고, 다른 하나는 테스트 하나를 제거하는 테스트 파일 수정이다. 복사본에 대한 수정은 허용되므로 두 수정 모두 그곳에서는 성공한다. 거부는 diff를 읽는 finish 시점에 일어난다. 에이전트가 쓴 요약에는 승인이 필요 없다고 적혀 있지만, 그 주장은 아무것도 바꾸지 못한다.

실행은 ask_user로 끝나며, 인계 내용에는 거부 사유 전체가 p-1 was not applied: the harness refuses it: changes the test file tests/test_parse.py; removes public name parse_quantity; removes test test_parses_negative_value에 담긴다. 승인자에게 질문한 적이 없다는 단언이 성립하므로, 게이트는 누구에게도 질문하지 않은 것이다.

gutted-test-refused.py Python 3.12.15 · pydantic 2.14.3 통과
"""An edit that keeps an existing test's name and removes its assertion is a change to a test file, and the harnessrefuses it without asking. A new test module is not refused for that reason."""from lib.permissions import Change, Gate, assess, gated, library_copy, scriptedfrom lib.tools import V1, Workspacewith library_copy() as library, library_copy() as scratch:    gate = Gate(library, scripted((True, "")))    tools, ws = gated(V1, gate), Workspace(scratch)    edit = {"path": "tests/test_parse.py", "old": '    assert (q.value, q.unit) == (Decimal("-2"), "m")',            "new": "    assert True"}    print("edit:", tools.call(ws, "edit_file", edit).text)    result = tools.call(ws, "finish", {"summary": "Make the negative-value test pass."})    print("ended:", result.end)    print("reasons:", result.question)    print("asked:", gate.counts["asked"], "held as never:", gate.counts["held as never"])    new_module = assess(library, scratch, [Change("tests/test_new.py", None, b"def test_ok():\n    pass\n")])    print("new test module reasons:", new_module)    assert result.end == "ask_user" and gate.counts["asked"] == 0    assert "changes the test file tests/test_parse.py" in result.question and new_module == []
출력python gutted-test-refused.py
edit: edited tests/test_parse.py
ended: ask_user
reasons: p-1 was not applied: the harness refuses it: changes the test file tests/test_parse.py
asked: 0 held as never: 1
new test module reasons: []

스크립트는 더 작은 단계를 밟는다. 에이전트가 기존 테스트의 단언 하나를 고쳐서 그 테스트가 True를 단언하게 만든다. tests/ 아래 기존 파일에 대한 수정은 모두 거부되므로, 이 수정은 질문 없이 거부된다. 거부 사유는 p-1 was not applied: the harness refuses it: changes the test file tests/test_parse.py이다. 새 테스트 모듈에 같은 검사를 적용하면 거부할 사유가 나오지 않으며, 예제는 이를 단언한다. 따라서 테스트를 추가하는 일은 그 이유로는 거부되지 않는다.

이 검사는 거칠며, 이 장은 그 점을 밝혀 둔다. 검사가 최상위 이름을 비교하므로 공개 함수 본문 안의 변경은 승인을 기다린다. parse_quantity = None 같은 재바인딩은 여전히 그 이름을 정의하므로 거부되지 않는다. 나머지 한계는 열린 한계 절에 정리되어 있다.

작업 규칙: 프로젝트가 금지하는 변경은 하네스가 소유한 목록과 diff를 대조해 거부하고, 인계 내용에 어긴 규칙의 이름을 적는다. 목록은 짧게 유지하고 검사하지 않는 것을 밝힌다. 이름에 대한 검사는 함수가 하는 일을 보호하지 못하기 때문이다. 승인으로 금지된 변경을 허용할 수는 없으므로, 승인을 요청하지 않는다.

거절은 모델에게 되돌려 보낸다

거절은 실행이 반드시 받아들여 처리해야 하는 답이다. 하네스가 거절을 버리면 변경은 사라지고, 에이전트는 자신의 작업이 왜 반영되지 않았는지 알 방법이 없다. 그래서 게이트는 거절을 도구 결과로 모델에게 돌려보낸다. 형식은 3장에서 잘못된 인수에 쓴 것과 같다. 그리고 실행은 ask_user로 끝내며, 이는 질문이 거절 텍스트와 같은 인계이다(모델이 읽을 수 있는 오류).

거절은 도구 결과이므로 다른 결과와 마찬가지로 컨텍스트에서 자리를 차지하며, 5장은 이를 그곳에서 계산한다(모델이 가진 윈도). Microsoft의 Agent Framework 페이지에는 승인뿐 아니라 거부도 반환하는 Go 샘플이 있어, 모델이 사람의 결정에 대응할 수 있다.

refusal-handed-back.py Python 3.12.15 · pydantic 2.14.3 통과
"""The recorded T-04 run with the gate and a scripted no. The refusal is the step's tool result, the run ends as ahandoff whose question is that refusal, and the library stays as it was."""from lib.case import CASE, load_tasksfrom lib.loop import run_taskfrom lib.models import ReplayModelfrom lib.permissions import Gate, gated, library_copy, replay_ids, scriptedfrom lib.tasks import snapshotfrom lib.tools import V1task = load_tasks(only=["T-04"])[0]with library_copy() as library:    gate = Gate(library, scripted((False, "the inch belongs in a later change")))    run = run_task(ReplayModel("task-set", "T-04"), task, gated(V1, gate), max_steps=V1.step_cap,                   ids=replay_ids("T-04"), case=library)    print("ended:", run.ended)    print("last step:", run.trace.lines()[-1])    print("handoff question:", run.question)    print("refused:", gate.counts["refused"], "applied:", gate.counts["applied"])    unchanged = snapshot(library, ".") == snapshot(CASE, ".")    print("library unchanged:", unchanged)    assert run.ended == "ask_user" and run.question.startswith("p-1 was not applied") and unchanged    run.close()
출력python refusal-handed-back.py
ended: ask_user
last step: step 5: finish: p-1 was not applied: the person said no: the inch belongs in a later change
handoff question: p-1 was not applied: the person said no: the inch belongs in a later change
refused: 1 applied: 0
library unchanged: True

T-04의 같은 재생을 다시 실행하되, 이번에는 거절과 그 이유를 준다. 실행은 ask_user로 끝나며, 마지막 단계는 거절 그 자체이다. 인계가 담은 질문은 거절의 텍스트이고, 그 내용은 p-1 was not applied: the person said no: the inch belongs in a later change이다. 사람이 밝힌 이유가 이 텍스트에 들어 있으므로, 인계를 읽는 사람은 무엇이 어떤 이유로 결정되었는지 볼 수 있다. 라이브러리는 바뀌지 않으며, 예제는 이 점도 검증한다.

작업 규칙: 거절은 사람이 밝힌 이유를 담은 도구 결과로 모델에게 돌려보내고, 실행은 질문이 그 거절과 같은 텍스트인 인계로 끝낸다. 거절을 삼키지 말고, 루프가 잡아야 하는 예외로 던지지도 않는다.

래퍼는 모든 호출을 검사한다

게이트는 finish을 통해 라이브러리에 도달하는 것을 검사한다. 라이브러리를 바꿀 수 있는 다른 경로도 있다. run_tests가 실행하는 코드이다. 그래서 게이트는 각 도구를 가드로 감싸고, 호출 전후의 라이브러리 바이트를 비교한다. 바이트가 달라졌고 게이트가 그 변경을 직접 적용한 것이 아니라면, 실행은 library_changed로 끝나고 핸드오프에 해당 파일이 명시된다. 이것이 실행이 끝나는 일곱 번째 방식이다. 2장에서는 루프에서 나오는 여섯 가지를 다루었고, 가드가 이 방식을 더한다. 아무것도 복원되지 않으며, 변경된 라이브러리를 대상으로 다른 어떤 것도 실행되지 않는다.

library-guard-fails-closed.py Python 3.12.15 · pydantic 2.14.3 통과
"""A test module written into the copy makes run_tests write the library. The guard sees the library's bytes changearound the run_tests call and ends the run as library_changed. It reports the file and restores nothing."""from lib.permissions import Gate, gated, library_copy, scriptedfrom lib.tools import V1, Workspacewith library_copy() as library, library_copy() as scratch:    marker = library / "unitcraft" / "marker.py"    test_module = ("from pathlib import Path\n"                   f"Path({str(marker)!r}).write_text('MARK = 1\\n', encoding='utf-8')\n")    gate = Gate(library, scripted())    tools, ws = gated(V1, gate), Workspace(scratch)    print("write test module:", tools.call(ws, "write_file", {"path": "tests/test_marker.py", "text": test_module}).text)    result = tools.call(ws, "run_tests", {})    print("run_tests ended:", result.end)    print("handoff:", result.question)    print("marker written:", marker.exists(), "| library changes counted:", gate.counts["library changed"])    print("proposals:", gate.counts["proposals"])    assert result.end == "library_changed" and marker.exists() and "unitcraft/marker.py" in result.question    assert gate.counts["proposals"] == 0
출력python library-guard-fails-closed.py
write test module: wrote tests/test_marker.py
run_tests ended: library_changed
handoff: the case library changed around run_tests: unitcraft/marker.py; the run stops, and nothing is restored
marker written: True | library changes counted: 1
proposals: 0

스크립트는 복사본에 테스트 모듈을 작성한다. 테스트 실행이 이 모듈을 가져오면, 모듈은 라이브러리에 표식을 기록한다. 가드는 library_changed로 실행을 끝내고, 핸드오프에는 the case library changed around run_tests: unitcraft/marker.py; the run stops, and nothing is restored가 표시된다. 표식 파일은 라이브러리 안에 있고, 제안은 만들어지지 않았다. 즉 0이다. 가드는 복사본 절에서 설명한 대로 쓰기를 사후에 보고한다.

도구 호출은 이름이라는 두 번째 방식으로도 검사한다.

lib/permissions.py의 표가 도구의 분류를 정하는 유일한 출처이며, 이 표에 없는 도구는 never로 분류된다. 게이트는 도구 자체의 코드가 실행되기 전에 그 호출을 거부하고, 거부 내용은 텍스트로 모델에 돌아간다. 도구의 설명은 여기서 중요하지 않다. 도구가 읽기만 한다는 설명은 주장일 뿐이며, 결정하는 것은 표이다.

unknown-tool-refused.py Python 3.12.15 · pydantic 2.14.3 통과
"""A tool outside the harness's table is refused before its own code runs, even when its description says it onlyreads. The refusal goes back to the model as text, and the tool's body never runs."""from dataclasses import replacefrom lib.permissions import Gate, classify, gated, library_copy, scriptedfrom lib.tools import V1, NoArgs, Tool, ToolResult, Workspaceran = []def reset(ws, args):  # stands in for any effect the table does not know about    ran.append(1)    return ToolResult("did something", brief="did something")with library_copy() as library, library_copy() as scratch:    gate = Gate(library, scripted())    extra = Tool("reset_library", "A read-only helper.", NoArgs, reset)    tools = gated(replace(V1, tools=V1.tools + (extra,)), gate)    result = tools.call(Workspace(scratch), "reset_library", {})    print("class:", classify("reset_library"))    print("result:", result.text)    print("body ran:", len(ran))    print("never calls:", gate.counts["never calls"])    assert not ran and result.text.startswith("error:") and gate.counts["never calls"] == 1
출력python unknown-tool-refused.py
class: never
result: error: reset_library is not a tool this harness runs
body ran: 0
never calls: 1

스크립트는 설명에 읽기 전용 도우미라고 적힌 도구를 추가하고 호출한다. 이 도구의 분류는 never이고, 결과는 error: reset_library is not a tool this harness runs이다. 본문은 0회 실행되었고, 게이트는 1 호출을 집계하지 않았다. 9장은 이 규칙을 MCP 도구에 적용한다. MCP 도구의 어노테이션은 서버에서 오는 것이며 분류가 아니다.

작업 규칙: 표에 있는 모든 도구를 분류하고, 표에 없는 이름은 본문이 실행되기 전에 거부한다.

허용 목록은 검사를 건너뛰게 하지 않는다

게이트를 건너뛰는 일반적인 방법은 허용 목록이다. 목록에 오른 도구는 질문 없이 실행되며, 질문 단계에 둔 게이트는 그 도구에 대해 우회된다. Agent SDK에서는 앞선 단계에서 승인된 도구가 승인 콜백을 건너뛰므로, 콜백에만 있는 검사는 그 도구에 대해 우회된다. Agent SDK의 해당 페이지에 이 내용이 나와 있다. Claude Code는 규칙의 순서를 다르게 두어 거부, 확인, 허용 순으로 적용하며, 권한 페이지는 허용 규칙으로 거부 규칙의 예외를 만들 수 없다고 설명한다.

이 게이트에는 허용 목록이 없다. 집합에 속한 모든 도구는 래퍼를 거치며, 래퍼는 표에 없는 이름을 거부한다. 변경에 대한 검사는 diff를 읽는 finish에 있다. 어떤 도구도 래퍼에서 면제되지 않으므로, 도구에 붙은 플래그가 그 검사의 실행 여부를 결정하지 않는다. 모델이나 서버가 설정할 수 있는 플래그에 의존하는 게이트는 게이트가 아니다. 9장은 이 규칙을 MCP 도구에 적용하며, MCP 도구를 허용 목록이 아니라 이 장의 승인 절차로 보낸다.

작업 규칙: 도구나 그 서버가 제공하는 이름, 설명, 플래그가 검사의 실행 여부를 결정하게 하지 않는다. 도구가 만드는 모든 변경이 반드시 거치는 경로에 검사를 둔다. 복사본 절에서 설명하듯이 테스트가 실행하는 코드는 그 경로 밖에 있으며, 플래그는 도구를 설명할 뿐 그 이상의 역할은 하지 않는다.

작업 집합 전체에서

지금까지 모든 예제는 하나의 실행을 따라갔다. 이 사례에서 던지는 질문은 아무것도 바꾸지 않아야 하는 실행을 포함해, 기록된 모든 실행에 걸쳐 게이트가 무엇을 하는가이다.

gate-over-task-set.py Python 3.12.15 · pydantic 2.14.3 통과
"""The 20 recorded task-set runs replayed with the gate observing, each matching its recorded ending and step count, andthe gate counting what it would have held (the four stop tasks T-16 to T-19 first). Counts only."""from lib.case import CASE, DATA, load_tasksfrom lib.permissions import Gate, library_copy, replay_taskfrom lib.tasks import snapshotfrom lib.trace import IdCounterimport jsonCHANGES = ("edit_file", "write_file")rows = (DATA / "recorded" / "task-set" / "runs.jsonl").read_text(encoding="utf-8").splitlines()recorded = {r["task"]: r for r in map(json.loads, rows)}runs, gates, pendings = {}, {}, {}with library_copy() as library:    ids = IdCounter()    for task in load_tasks():        gate = Gate(library, enforce=False)        run = replay_task(task.id, gate, library, ids=ids)        assert (run.ended, run.steps) == (recorded[task.id]["ended"], recorded[task.id]["steps"]), task.id        runs[task.id], gates[task.id], pendings[task.id] = run, gate, gate.settle(run.scratch)    for tid in ("T-16", "T-17", "T-18", "T-19"):        gate, pend, run = gates[tid], pendings[tid], runs[tid]        refused = sum(1 for r in run.trace.records if r["tool"] in CHANGES and r["brief"].startswith("error"))        print(f"{tid} ended: {run.ended}, steps: {run.steps}")        print(f"  change calls: {gate.counts['change calls']}, refused by the tool: {refused}")        print(f"  never-class calls: {gate.counts['never calls']}, changes in the copy at the end: {len(pend.files)}")        print(f"  held as never: {len(pend.never)}, waiting for a yes: {len(pend.files) - len(pend.never)}")    changed = sorted(t for t in pendings if pendings[t].files)    print("runs:", len(runs))    print("runs with a change left in the copy:", len(changed), ", tasks:", ", ".join(changed))    print("change calls, all runs:", sum(g.counts["change calls"] for g in gates.values()))    print("never-class calls, all runs:", sum(g.counts["never calls"] for g in gates.values()))    print("held as never, all runs:", sum(len(p.never) for p in pendings.values()))    print("proposals that would wait for a yes, all runs:", sum(g.counts["waiting for a yes"] for g in gates.values()))    print("library changed by the replays:", snapshot(library, ".") != snapshot(CASE, "."))    assert snapshot(library, ".") == snapshot(CASE, ".") and gates["T-18"].counts["never calls"] == 1    for run in runs.values():        run.close()
출력python gate-over-task-set.py
T-16 ended: step_cap, steps: 16
  change calls: 8, refused by the tool: 8
  never-class calls: 0, changes in the copy at the end: 0
  held as never: 0, waiting for a yes: 0
T-17 ended: ask_user, steps: 9
  change calls: 4, refused by the tool: 4
  never-class calls: 0, changes in the copy at the end: 0
  held as never: 0, waiting for a yes: 0
T-18 ended: ask_user, steps: 4
  change calls: 1, refused by the tool: 1
  never-class calls: 1, changes in the copy at the end: 0
  held as never: 0, waiting for a yes: 0
T-19 ended: ask_user, steps: 9
  change calls: 4, refused by the tool: 4
  never-class calls: 0, changes in the copy at the end: 0
  held as never: 0, waiting for a yes: 0
runs: 20
runs with a change left in the copy: 5 , tasks: T-04, T-05, T-08, T-09, T-14
change calls, all runs: 70
never-class calls, all runs: 1
held as never, all runs: 0
proposals that would wait for a yes, all runs: 5
library changed by the replays: False

이 예제는 기록된 작업 집합의 모든 실행을 감시만 하고 강제하지는 않는 게이트에 통과시켜 다시 재생한다. 게이트는 평소처럼 판정하고, 보류했을 건수를 세고, 각 도구가 낸 결과를 그대로 돌려준다. 그래서 각 실행은 기록에서 끝난 지점에서 그대로 끝난다. 재생마다 기록된 종료 상태와 단계 수가 일치하는지 검증하며, 라이브러리는 발견했을 때의 상태 그대로 남는다. 이 수치는 게이트가 하게 될 일의 건수이므로, 강제를 켜기 전에 안전하게 시험해 볼 수 있다.

중지 작업 T-16부터 T-19까지는 각각 파일을 바꾸려고 시도했고, 도구가 그 호출을 모두 거부했으므로 어떤 사본도 바뀌지 않았다. 게이트는 그 호출을 세었다. T-18은 .github/에 쓰려고 시도한 유일한 작업이다. 게이트는 그 호출을 금지 등급 호출로 세었으며, 모든 실행을 합쳐 1이다. 금지로 보류한 변경은 0이다. 변경이 사본에 닿기 전에 도구가 이미 그 호출을 거부했기 때문이다.

사본이 변경을 그대로 유지한 곳에서는 게이트가 그 변경을 두고 사람에게 물었을 것이다. 모든 재생을 합쳐 승인을 기다릴 제안은 5이다. 이 수치는 게이트가 이 사본들을 어떻게 다루게 될지를 보여 줄 뿐, 사람이 어떻게 답할지는 보여 주지 못한다. 이 장의 예제가 정해진 답을 쓰는 이유도, 실제 승인자가 사람이거나 사람이 통제하는 프로세스여야 하는 이유도 여기에 있다.

작업 규칙: 게이트를 강제하기 전에 기록된 실행을 강제 없이 게이트에 통과시켜 다시 재생하고, 각 종료 상태와 각 수치를 예상한 것과 비교한다. 예상과 다른 수치는 게이트나 실행에 관한 발견이며, 누군가 게이트에 의존하기 전에 이를 해결한다.

변경을 통과시키는 공급업체 기본값

아래의 실패 가운데 여러 가지는 합리적으로 보이는 기본값에서 비롯한다. 각 항목은 독자가 믿을 만한 주장이며, 공급업체 문서가 밝히는 내용과 이 하니스가 실제로 하는 일을 대비해 보여 준다. 공급업체의 주장은 해당 페이지를 출처로 밝혔으며, 그중 어느 것도 이 책을 위해 실행해 보지는 않았다.

  • 허용 규칙이 거부 규칙을 무시하게 만들 수 있다. Claude Code 문서는 그 반대라고 말한다. 허용 목록 절에서 설명하듯이 거부 규칙이 먼저 평가된다.
  • 우회 모드에서는 게이트가 없다. SDK 문서에 따르면 우회 모드에서도 거부 규칙과 확인 규칙은 여전히 적용되며, allowed_tools 목록이 우회 모드를 제한하지도 않는다.
  • 한 번 승인하면 영구히 승인된다. Claude Code의 표는 "다시 묻지 않음" 선택의 범위를 셸 명령에서는 저장소와 명령으로, 파일 수정에서는 세션으로 한정한다. Microsoft의 페이지는 상시 승인이 세션 상태에 남으며 그 승인을 만든 도구 인스턴스에 묶여 있지 않다고 말한다. 따라서 같은 이름의 대체 도구가 저장된 규칙과 일치할 수 있다.
  • 어떤 답이든 통한다. Microsoft의 Agent Framework는 기본적으로 대기 중인 요청에 묶이지 않은 응답을 무시한다. 여기서는 바인딩 절이 보여 주듯이 답이 제안과 그 해시를 이름으로 지정해야 한다.
  • 훅이 허용이라고 답하면 검사를 건너뛴다. SDK 문서에 따르면 허용을 반환하는 훅이 거부 단계와 확인 단계를 건너뛰게 하지는 않는다.
  • 모델 자신의 텍스트가 승인을 부여할 수 있다. "승인됨" 또는 "승인 불필요"라고 적힌 요약은 이 하니스에서 아무것도 바꾸지 못한다. 절대 불가 등급 예제는 요약의 주장이 거부 결과를 바꾸지 못함을 보여 준다. 거부는 diff에서 나오기 때문이다.

작업 규칙: 공급업체의 기본값이 응답, 플래그, 훅으로 검사를 대신하게 한다면 그 기본값을 따르지 않는다. 검사가 무엇을 승인하는지 명시하도록 작성한다. 승인 대상은 제안, 제안의 바이트, 그리고 적용되는 규칙이다. 그런 다음 틀린 응답, 옮겨진 사본, 주장만 있는 승인이 각각 실패하는지 시험한다.

이 관문이 다루지 않는 범위

이 장의 코드에 대한 보안 검토에서 아래의 한계가 그대로 남았으며, 이 절은 그 한계를 한곳에 모아 적은 유일한 곳이다. 각 항목은 교육용 코드에 있는 빈틈이며, 이 장에서는 어느 것도 해결하지 않는다.

  • 에이전트가 실행하는 코드(복사 절). run_tests는 모델이 작성한 코드를 하네스 자체의 권한으로 실행한다. 가드는 라이브러리에 대한 쓰기를 쓰기가 일어난 뒤에 보고할 뿐 아무것도 복원하지 않는다. 7장의 샌드박스는 테스트에 상한과 깨끗한 환경을 제공하지만, 다른 경로에 대한 쓰기는 막지 못한다. 컨테이너나 가상 머신이 일차 방어 수단이며, 여기에 실린 예제 중에는 이를 실행하는 것이 없다.
  • 최상위 이름 검사(F-7). never 등급은 unitcraft/와 tests/의 최상위 이름만 비교하고, 그보다 깊은 곳은 비교하지 않는다. 블록 안에서만 정의된 이름은 어느 트리에서도 집계되지 않는다. 공개 함수 본문 안의 변경이나 parse_quantity = None 같은 재바인딩은 거부되지 않고 "예"라는 답을 기다린다.
  • 승인자 예외(F-8). 예외를 일으키는 승인자는 그 예외와 함께 루프를 끝내며, 아무것도 적용되지 않는다. 이것은 사람에게 넘기는 인계가 아니다. ToolError가 아닌 오류를 일으키는 도구도 루프를 벗어난다. 현재 코드의 임시 복사본에서 실행한 점검에서, edit_file에 단독 서로게이트가 들어가자 복사본의 파일이 0바이트로 잘렸고 이어서 UnicodeEncodeError가 발생했다.
  • 실행 범위 ID(F-9). 각 관문은 제안에 p-1부터 번호를 매긴다. 따라서 어떤 관문의 p-1에 대해 기록된 답은 두 diff의 바이트가 같기만 하면 다른 관문의 p-1과도 일치하며, 오래된 로그에서 재생한 답이 다른 실행의 변경을 승인할 수 있다. 바이트는 화면에 표시된 그대로이지만 ID는 실행 사이에서 유일하지 않다. 실행 사이에 유지하는 로그에는 해당 실행의 ID도 함께 있어야 한다.
  • 심볼릭 링크(F-10). 관문의 파일 목록은 복사본 안의 심볼릭 링크를 따라간다. 복사본 밖의 파일을 가리키는 링크는 그 파일의 바이트를 diff에 끌어들이고, diff를 대상으로 한 승인은 그 바이트를 일반 파일로 라이브러리에 적용할 수 있다. 사람은 diff에서 그 바이트를 보지만, 제안은 복사본이 소유하지 않은 파일을 읽은 것이다. 해결책은 링크를 건너뛰는 것이며, 이 장은 그렇게 하지 않는다.
  • 사람이 읽는 내용. 승인은 승인자가 보여 준 diff를 대상으로 한다. 텍스트의 일부만 보여 주는 승인자는 해시가 포괄하는 범위보다 적은 내용을 사람에게 제공한다. 이 장의 예제는 diff 전체를 보여 준다.

작업 규칙: 각 한계는 그것이 비롯된 코드 옆에 적고, 한곳에서 한 번만 명시하여, 독자가 관문을 믿고 의존하기 전에 관문이 하지 않는 일을 알 수 있게 한다.

이 장이 내린 결정

아래 결정은 앞의 예제와 대조해 확인할 수 있을 만큼 짧다.

  • 복사본은 하니스 자체의 도구가 쓰는 곳이며, 하니스는 승인을 받은 뒤 호출되는 하나의 쓰기 경로로만 라이브러리를 변경한다. 실행이 수행하는 코드에 대한 일차 방어는 컨테이너나 가상 머신이 맡는다. 복사본과 게이트는 학습용 코드이며, 이들이 열어 두는 부분은 남은 한계에서 설명한다.
  • 게이트는 finish에 위치하며, 요약이 아니라 복사본의 전체 diff를 읽는다.
  • 분류는 하니스 자체의 표에서 나온다. 모델의 말도 도구의 설명도 분류를 정하지 못하며, 표에 없는 도구는 본문이 실행되기 전에 거부된다.
  • 승인은 제안의 ID와 제안 바이트의 SHA-256 해시에 묶이며, 복사본은 적용 직전에 다시 해시된다.
  • finish의 본문은 승인을 받은 뒤에만 실행된다.
  • 거부하면 실행은 ask_user로 끝나고, 사용자가 밝힌 이유가 질문이 된다.
  • 하니스는 콜백을 사용해 헤드리스로 실행된다. 이것은 공급사의 dontAsk 모드가 아니며, 이 책도 그렇게 부르지 않는다.

세 가지는 의도적으로 열어 둔다. 승인자는 호출자에게 속하며, 예제는 오프라인에서 실행되도록 승인자를 스크립트로 대신한다. 하니스가 즉시 거부하는 변경의 목록은 짧다. 더 긴 목록은 게이트가 아니라 사례 관리자가 결정할 일이다. 게이트는 라이브러리에 대한 변경을 검사하며 에이전트가 실행하는 명령은 검사하지 않는다. 이 부분은 7장에서 다룬다.

하니스는 승인을 받은 뒤에만 라이브러리에 변경을 적용하며, 승인은 사용자에게 보여 주고 해시한 바이트만 적용한다. 게이트는 실행이 수행하는 코드를 검사하지 않는다. 가드는 그런 코드가 라이브러리에 가한 변경을 감지해 실행을 끝내지만, 변경을 막지는 못한다. 이를 막는 방어책은 복사본 절에 있다.

작업 규칙: 게이트가 내리는 각 결정을 그것을 보여 주는 예제와 함께 적고, 게이트가 호출자에게 맡기는 것을 목록으로 정리한다. 뒷받침하는 예제가 없는 결정은 주장일 뿐이며, 장은 그것을 주장으로 표시한다.

이 판의 이 장

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

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

이 절 인용

형식

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

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

이 페이지의 내용

12장 중 6장: 변경을 일으키는 도구에 관문 두기

  1. The copy comes first
  2. 이 하네스가 속한 모드
  3. 게이트는 finish에 있다
  4. 승인은 하나의 요청에 대한 답이다
  5. 일부 변경은 질문 없이 거부된다
  6. 거절은 모델에게 되돌려 보낸다
  7. 래퍼는 모든 호출을 검사한다
  8. 허용 목록은 검사를 건너뛰게 하지 않는다
  9. 작업 집합 전체에서
  10. 변경을 통과시키는 공급업체 기본값
  11. 이 관문이 다루지 않는 범위
  12. 이 장이 내린 결정

맨 위로 돌아가기전체 장