Skip to content

Commit 6a573bb

Browse files
committed
Keep known revocations over a restored older approvals file; log draft and speech results (#31)
- adoptDisk re-applies every revocation this run knows to whatever it reads, so an older copy restored after a saved revocation cannot bring the app back (Codex P-01 from the #33 promotion check). Test added. - [AGENT-DRAFT] and [AGENT-SPEECH] log lines with the result, the app (or peer pid) and lengths only (Codex P-05 / Claude P-04). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015LJG7KnMPqFcfTZ8A1C2qh
1 parent 28ae9e8 commit 6a573bb

7 files changed

Lines changed: 68 additions & 16 deletions

File tree

‎Sources/App/AgentSessionController.swift‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1025,8 +1025,14 @@ import Security
10251025
let socket = LocalApprovedSocket(peer: pair.peer, endpoint: AgentPairing.draftEndpoint(slot: pair.slot), directory: directory,
10261026
lifetime: nil, maxFrame: AgentLimits.frameBytes,
10271027
verified: Self.verifier(for: pair)) { [weak self] bytes, active in
1028-
guard let request = Self.decode(bytes) else { return Self.reply("invalid") }
1029-
guard Self.isV2(request["schema_version"]) else { return Self.reply("upgrade_required") }
1028+
// The result, the app and the lengths only; never the text.
1029+
var lengths = (display: 0, speech: 0)
1030+
func answer(_ status: String) -> Data {
1031+
Log.agent.info("[AGENT-DRAFT] receipt host=\(pair.host ?? "unverified", privacy: .public) client=\(pair.client.uuidString, privacy: .public) result=\(status, privacy: .public) display_len=\(lengths.display, privacy: .public) speech_len=\(lengths.speech, privacy: .public)")
1032+
return Self.reply(status)
1033+
}
1034+
guard let request = Self.decode(bytes) else { return answer("invalid") }
1035+
guard Self.isV2(request["schema_version"]) else { return answer("upgrade_required") }
10301036
let base: Set<String> = ["schema_version", "idempotency_key", "display_text"]
10311037
let linkedKeys: Set<String> = ["profile", "revision", "body_sha256", "proof"]
10321038
var keys = Set(request.keys)
@@ -1040,10 +1046,11 @@ import Security
10401046
(request["title"] == nil || request["title"] is String),
10411047
ExplanationDraft(id: clientKey, display: display, speech: request["speech_text"] as? String,
10421048
title: request["title"] as? String) != nil else {
1043-
return Self.reply("invalid")
1049+
return answer("invalid")
10441050
}
10451051
let speech = request["speech_text"] as? String
10461052
let title = request["title"] as? String
1053+
lengths = (display.count, speech?.count ?? 0)
10471054
let response = Reply()
10481055
let signal = DispatchSemaphore(value: 0)
10491056
let responseDeadline = DispatchTime.now() + .milliseconds(750)
@@ -1112,8 +1119,8 @@ import Security
11121119
self.rates[pair.client] = rate
11131120
response.set(result.rawValue)
11141121
}
1115-
guard signal.wait(timeout: responseDeadline) == .success else { return Self.reply("unconfirmed") }
1116-
return Self.reply(response.get())
1122+
guard signal.wait(timeout: responseDeadline) == .success else { return answer("unconfirmed") }
1123+
return answer(response.get())
11171124
}
11181125
guard socket.start() else {
11191126
status = socket.requiresPathInspection ? LocalApprovedSocket.unknownPathMessage : "대본 받기 소켓을 시작할 수 없습니다."

‎Sources/App/LocalSpeechSocket.swift‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@ import Foundation
22
import Darwin
33
import CryptoKit
44

5-
/// Single-login, opt-in IPC. No text is logged or persisted by this bridge.
5+
/// Single-login, opt-in IPC. No text is logged or persisted by this bridge; each
6+
/// request logs its result, the peer process and the text length only.
67
final class LocalSpeechSocket {
78
private let queue = DispatchQueue(label: "com.codebasic.tts.local-speech")
89
private var fd: Int32 = -1
@@ -74,12 +75,20 @@ final class LocalSpeechSocket {
7475
if b == 10 { break }; buffer.append(b)
7576
}
7677
var status = "invalid"
78+
var length = 0
79+
defer {
80+
var pid: pid_t = 0
81+
var size = socklen_t(MemoryLayout<pid_t>.size)
82+
let peer = getsockopt(client, SOL_LOCAL, LOCAL_PEERPID, &pid, &size) == 0 ? String(pid) : "unknown"
83+
Log.agent.info("[AGENT-SPEECH] request pid=\(peer, privacy: .public) result=\(status, privacy: .public) len=\(length, privacy: .public)")
84+
}
7785
if buffer.count < 25 * 1024,
7886
let object = try? JSONSerialization.jsonObject(with: Data(buffer)) as? [String: Any],
7987
object.count == 2, let text = object["text"] as? String, let key = object["idempotency_key"] as? String,
8088
text.utf8.count <= 4096, !text.contains("\0"), !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
8189
!key.isEmpty, key.utf8.count <= 128,
8290
key.utf8.allSatisfy({ (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) || $0 == 45 || $0 == 46 || $0 == 95 }) {
91+
length = text.count
8392
let semaphore = DispatchSemaphore(value: 0)
8493
let deadline = DispatchTime.now() + .milliseconds(1000)
8594
let lock = NSLock()

‎Sources/Core/AgentTrustStore.swift‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@ final class AgentTrustStore {
135135
/// knew approvals: nothing is trusted and receipt is off. The user's denials
136136
/// not yet saved are applied again on top of what is read.
137137
func adoptDisk() {
138+
let known = file.revoked
138139
let disk = Self.readDisk(url)
139140
guard case .loaded(let loaded, let stamp) = disk else {
140141
if case .unreadable(let stamp) = disk {
@@ -159,15 +160,17 @@ final class AgentTrustStore {
159160
closedByDisk = false
160161
diskStamp = stamp
161162
needsAdopt = false
162-
guard !pending.isEmpty else {
163-
file = loaded
164-
return
165-
}
163+
// Revocations are never undone (a revoked key cannot be approved again),
164+
// so every revocation this run knows is kept, also over a restored older
165+
// copy that predates it. Receipt choices are not merged this way: the user
166+
// may have turned receipt back on through another instance in between.
166167
var merged = loaded
168+
for keyID in known where !Self.holds(merged, .revoke(keyID)) { Self.apply(.revoke(keyID), to: &merged) }
167169
for denial in pending { Self.apply(denial, to: &merged) }
168170
guard merged != loaded else {
169-
// The file already says what the user asked for, except one app's off
170-
// for a row it does not have: that stays for when the row comes back.
171+
// The file already says what the user asked for (or nothing is
172+
// pending), except one app's off for a row it does not have: that
173+
// stays for when the row comes back.
171174
file = loaded
172175
// A file this run re-created never settles pending denials.
173176
if !recreated { pending.removeAll { Self.holds(loaded, $0) } }

‎Sources/Core/Logging.swift‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ enum Log {
1717
static let service = Logger(subsystem: subsystem, category: "service")
1818
static let app = Logger(subsystem: subsystem, category: "app")
1919
static let tts = Logger(subsystem: subsystem, category: "tts")
20-
/// `[AGENT-CONN]` agent app connection and approval decisions. Never logs
20+
/// `[AGENT-CONN]` agent app connection and approval decisions, `[AGENT-DRAFT]`
21+
/// draft receipt results and `[AGENT-SPEECH]` speech request results. Never logs
2122
/// draft text, instructions or key material; app identity is the code
2223
/// signature (team/certificate + signing identifier), not user data.
2324
static let agent = Logger(subsystem: subsystem, category: "agent")

‎Tests/AgentTrustStoreTests.swift‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,36 @@ import Foundation
265265
vanishing.adoptDisk()
266266
precondition(vanishing.clients.isEmpty && !vanishing.autoReceive)
267267

268+
// A saved revocation survives the file being removed and an older copy
269+
// (from before the revocation, receipt on) being put back: the key stays
270+
// revoked, its row does not come back, and the file is written again.
271+
let restoreURL = directory.appendingPathComponent("restore.json")
272+
let restoring = AgentTrustStore(url: restoreURL)
273+
let keptKey = P256.Signing.PrivateKey().publicKey.x963Representation
274+
let revokedKey = P256.Signing.PrivateKey().publicKey.x963Representation
275+
let kept = try restoring.trust(publicKey: keptKey, label: "K", host: hostA)
276+
let revokedRow = try restoring.trust(publicKey: revokedKey, label: "R", host: hostB)
277+
precondition(restoring.setAutoReceive(true))
278+
let beforeRevoke = try Data(contentsOf: restoreURL)
279+
precondition(restoring.forget(revokedRow.id) && !restoring.hasUnsavedDenials)
280+
precondition(unlink(restoreURL.path) == 0)
281+
restoring.adoptDisk()
282+
precondition(restoring.clients.isEmpty && restoring.lookup(keyID: revokedRow.keyID, host: hostB) == .revoked)
283+
try AgentTrustStore.writePrivately(beforeRevoke, restoreURL)
284+
restoring.adoptDisk()
285+
precondition(restoring.lookup(keyID: revokedRow.keyID, host: hostB) == .revoked)
286+
precondition(restoring.clients.map(\.id) == [kept.id] && !restoring.changedOnDisk)
287+
precondition(!restoring.setReceiptEnabled(true, for: revokedRow.id))
288+
let restoredAgain = AgentTrustStore(url: restoreURL)
289+
precondition(restoredAgain.lookup(keyID: revokedRow.keyID, host: hostB) == .revoked)
290+
precondition(restoredAgain.clients.map(\.id) == [kept.id])
291+
// The same when the old copy comes back while this instance holds it in
292+
// memory (no missing period in between).
293+
try AgentTrustStore.writePrivately(beforeRevoke, restoreURL)
294+
restoring.adoptDisk()
295+
precondition(restoring.lookup(keyID: revokedRow.keyID, host: hostB) == .revoked)
296+
precondition(AgentTrustStore(url: restoreURL).lookup(keyID: revokedRow.keyID, host: hostB) == .revoked)
297+
268298
// Reconnect policy shared with the helper.
269299
precondition(AgentReconnect.next(after: "receiving_only", attempt: 3) == .done)
270300
precondition(AgentReconnect.next(after: "ready", attempt: 0) == .done)

‎build.sh‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ case "${1:-install}" in
202202
echo "==> Compiling + running unit tests"
203203
mkdir -p "$BUILD_DIR"
204204
/usr/bin/python3 -B -m unittest discover -s "$HERE/Tests" -p 'test_mcp*.py' -v
205-
swiftc -O "$RUNTIME_SOURCE" "$HERE/Sources/Core/TextSplitter.swift" "$HERE/Sources/App/LocalSpeechSocket.swift" \
205+
swiftc -O "$RUNTIME_SOURCE" "$HERE/Sources/Core/TextSplitter.swift" "$HERE/Sources/Core/Logging.swift" "$HERE/Sources/App/LocalSpeechSocket.swift" \
206206
"$HERE/Tests/LocalSpeechGateTests.swift" -o "$BUILD_DIR/local-speech-gate-tests"
207207
"$BUILD_DIR/local-speech-gate-tests"
208208
catalog_fixture="$(mktemp -d "$BUILD_DIR/catalog-test.XXXXXX")"

‎docs/mcp-explanation-drafts.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ Helpers/tts_mcp_client.py --helper "<앱>/Contents/Helpers/CodebasicAgentMCP" se
6464

6565
## 연결 로그로 확인
6666

67-
앱은 연결 판단마다 `agent` 카테고리에 `[AGENT-CONN]` 한 줄을 남깁니다. 대본·지시·키는 기록하지 않습니다.
67+
앱은 연결 판단마다 `agent` 카테고리에 `[AGENT-CONN]` 한 줄을, 대본 접수와 음성 요청마다 각각 `[AGENT-DRAFT]`, `[AGENT-SPEECH]` 한 줄을 남깁니다. 대본·지시·키는 기록하지 않습니다.
6868

6969
```sh
7070
/usr/bin/log show --last 1h --info --style compact --predicate 'subsystem == "com.seongjoo.SelectedTextTTS" AND category == "agent"'
@@ -73,6 +73,8 @@ Helpers/tts_mcp_client.py --helper "<앱>/Contents/Helpers/CodebasicAgentMCP" se
7373
- `connect host=<앱 식별자|unverified> key=<키 ID 앞 12자> lookup=<trusted|unknown|revoked|host_changed> result=<상태>`: 재연결 때 앱을 알아봤는지와 결과. 승인한 앱이 재시작 후 `lookup=trusted result=ready`(또는 `receiving_only`)이면 재승인 없이 연결된 것입니다.
7474
- `approve host=… client=… scope=<persistent|this_run> result=ok|store_failed`: 승인. `this_run`은 앱을 식별할 수 없어 이번 실행에만 허용한 경우입니다.
7575
- `revoke host=… client=… result=ok|unsaved`: 승인 철회.
76+
- `[AGENT-DRAFT] receipt host=… client=… result=<accepted|duplicate|conflict|busy|rate_limited|instruction_required|unproven|invalid|upgrade_required|unconfirmed|disabled> display_len=<글자 수> speech_len=<글자 수>`: 대본 접수 결과. 본문은 남기지 않고 길이만 남깁니다.
77+
- `[AGENT-SPEECH] request pid=<요청 프로세스> result=<accepted|duplicate|conflict|busy|invalid|unconfirmed> len=<글자 수>`: 음성 소켓 요청 결과. 이 소켓은 앱별 승인이 없으므로 앱 대신 요청한 프로세스 번호를 남깁니다.
7678

7779
### 에이전트 탭 자동 연결 (#31)
7880

@@ -82,7 +84,7 @@ Helpers/tts_mcp_client.py --helper "<앱>/Contents/Helpers/CodebasicAgentMCP" se
8284

8385
승인·받기 설정은 `agent-approvals.json`에 저장하며, 페어링 소켓을 가진 앱 인스턴스만 바꿉니다. 같은 앱을 하나 더 띄우면 그 창에서는 바꿀 수 없다고 안내하고 `policy change refused reason=not_socket_owner`를 남깁니다. 소켓을 넘겨받을 때, 탭을 열 때, 도우미의 상태 확인·증명 때, 설정을 바꾸기 직전에 파일이 자신이 마지막으로 읽거나 쓴 뒤 바뀌었으면 다시 읽습니다(`policy adopt reason=external_change`). 그래서 이미 연결된 도우미에도 다른 인스턴스가 저장한 철회·끄기가 바로 적용됩니다. 파일을 쓴 직후 다시 읽어 방금 쓴 내용일 때만 그 상태를 기억하고, 아니면 다음 확인에서 다시 읽습니다.
8486

85-
승인을 알고 있던 상태에서 파일이 사라졌거나 읽을 수 없으면 승인 없음·받기 꺼짐으로 보고, 철회한 키는 계속 철회 상태로 둡니다. 읽을 수 없는 파일은 앱이 덮어쓰지 않고 탭에 안내하며, 다시 읽히면 그 내용을 채택합니다. 이때 끊긴 도우미는 철회로 보지 않고 다시 신호를 받습니다. 저장하지 못한 사용자의 거부(전체 받기 끄기, 앱별 받기 끄기, 승인 철회)는 이 인스턴스에서 바로 적용되고, 파일을 다시 읽을 때 그 내용 위에 다시 적용해 저장합니다. 파일을 읽을 수 없는 동안 사용자가 전체 받기를 켜면 승인 목록을 비운 새 설정으로 파일을 바꿉니다. 화면 잠금과 콘솔 사용자 전환은 따로 추적해 둘 다 풀렸을 때만 받기를 다시 엽니다.
87+
승인을 알고 있던 상태에서 파일이 사라졌거나 읽을 수 없으면 승인 없음·받기 꺼짐으로 보고, 철회한 키는 계속 철회 상태로 둡니다. 철회는 되돌릴 수 없으므로, 이 실행이 아는 철회는 파일을 다시 읽을 때마다 그 위에 다시 적용합니다. 철회 전에 만든 옛 사본이 되돌아와도 철회한 앱은 다시 연결되지 않고, 앱은 철회를 넣어 파일을 다시 저장합니다. 읽을 수 없는 파일은 앱이 덮어쓰지 않고 탭에 안내하며, 다시 읽히면 그 내용을 채택합니다. 이때 끊긴 도우미는 철회로 보지 않고 다시 신호를 받습니다. 저장하지 못한 사용자의 거부(전체 받기 끄기, 앱별 받기 끄기, 승인 철회)는 이 인스턴스에서 바로 적용되고, 파일을 다시 읽을 때 그 내용 위에 다시 적용해 저장합니다. 파일을 읽을 수 없는 동안 사용자가 전체 받기를 켜면 승인 목록을 비운 새 설정으로 파일을 바꿉니다. 화면 잠금과 콘솔 사용자 전환은 따로 추적해 둘 다 풀렸을 때만 받기를 다시 엽니다.
8688

8789
이전 빌드(#13 통합 브랜치, 배포된 적 없음)는 `agent-clients.json`을 썼습니다. 이 파일은 가져오지 않으므로 그 빌드에서 승인한 앱은 한 번 다시 승인해야 하며, 이전 빌드를 함께 띄워도 서로 다른 파일을 써서 철회나 끄기가 되살아나지 않습니다. 저장하지 못한 거부는 다음 확인(도우미 상태 확인, 탭 열기, 설정 변경) 때 다시 저장을 시도합니다. 읽을 수 없는 파일을 이번 클릭에서 처음 발견했다면 받기를 켜지 않고 먼저 안내하며, 다시 켜야 빈 목록으로 바꿉니다.
8890

0 commit comments

Comments
 (0)