Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
6a573bb
Keep known revocations over a restored older approvals file; log draf…
claude Nov 28, 2026
f4e2554
Rename a duplicate test binding so the trust store tests compile (#31)
lseongjoo Nov 28, 2026
907b9d0
Keep manual fixtures out of the user's data with a fixture-only home …
lseongjoo Nov 28, 2026
38b3953
Bring the manual fixtures up to per-app approval and current menus (#31)
lseongjoo Nov 28, 2026
06edb5c
Finish porting the pre-#13 fixtures and log a speech request in a fix…
lseongjoo Nov 28, 2026
31a0a62
Settle known revocations as pending denials, write only as socket hol…
claude Nov 28, 2026
17c8ec2
Update the full-list revocation test to merging without trimming (#31)
lseongjoo Nov 28, 2026
699a092
Wait for approval requests to expire instead of a fixed sleep (#31)
lseongjoo Nov 28, 2026
cc1548e
Order merged revocations so the file's own stay newest, bound the mer…
claude Nov 28, 2026
26f0969
Require the request list to stay empty past the helpers' signal windo…
lseongjoo Nov 28, 2026
29964c0
Never drop revocations; log only result, app or pid, and lengths (#31)
claude Nov 28, 2026
c3b8cf2
Compare the takeover merge as a set now that order no longer matters …
lseongjoo Nov 28, 2026
3218962
Fit a merge of two long revocation histories under the read limit, ke…
claude Nov 28, 2026
b1b6b35
Document how a merge over the read limit is fitted (#31)
claude Nov 28, 2026
0dd7d66
Fit only what is written; keep every revocation in memory and pending…
claude Nov 28, 2026
b4d4c2a
Forget the last read file once it is missing or unreadable; never ski…
claude Nov 28, 2026
ee78d9c
Fit after an unreadable file by the last intact file, not by nothing …
claude Nov 28, 2026
6262d82
Merge pull request #39 from codebasic/claude/project-thread-snd6be
lseongjoo Nov 28, 2026
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
3 changes: 3 additions & 0 deletions Helpers/AgentCatalogMCP.swift
Original file line number Diff line number Diff line change
Expand Up @@ -695,6 +695,9 @@ struct ClientKey {
#if TTS_AGENT_FIXTURE_KEYS
// Integration fixtures use their own synthetic key directory.
return ProcessInfo.processInfo.environment["TTS_AGENT_FIXTURE_KEY_DIR"].map { URL(fileURLWithPath: $0, isDirectory: true) }
#elseif TTS_FIXTURE_HOME
// Fixture builds keep keys under the fixture's home, never the user's.
return TTSRuntime.applicationSupport().appendingPathComponent("agent-client-keys", isDirectory: true)
#else
guard let entry = getpwuid(getuid()), let home = entry.pointee.pw_dir else { return nil }
return TTSRuntime.applicationSupport(home: URL(fileURLWithPath: String(cString: home), isDirectory: true))
Expand Down
24 changes: 17 additions & 7 deletions Sources/App/AgentSessionController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -820,7 +820,8 @@ import Security
private func adoptStoreAfterTakeover() {
let wasFailed = trust.readFailed
let priorKeys = Dictionary(trust.clients.map { ($0.id, $0.keyID) }, uniquingKeysWith: { first, _ in first })
trust.adoptDisk()
// Only the socket holder writes the file; another instance only reads it.
trust.adoptDisk(writeBack: pairingSocket != nil)
// A remembered instruction choice belongs to the key that was approved
// when it was made; a removed or replaced key does not inherit it.
let keys = Dictionary(trust.clients.map { ($0.id, $0.keyID) }, uniquingKeysWith: { first, _ in first })
Expand Down Expand Up @@ -983,7 +984,7 @@ import Security
}

private func block(_ peer: LocalInstructionPeer) {
let limit = AgentTrustStore.maxRevoked
let limit = 1024
if blockedPeers.count >= limit { blockedPeers.removeFirst() }
blockedPeers.append(peer)
}
Expand Down Expand Up @@ -1025,8 +1026,16 @@ import Security
let socket = LocalApprovedSocket(peer: pair.peer, endpoint: AgentPairing.draftEndpoint(slot: pair.slot), directory: directory,
lifetime: nil, maxFrame: AgentLimits.frameBytes,
verified: Self.verifier(for: pair)) { [weak self] bytes, active in
guard let request = Self.decode(bytes) else { return Self.reply("invalid") }
guard Self.isV2(request["schema_version"]) else { return Self.reply("upgrade_required") }
// The result, the app (its signing identity, or the helper pid for an
// unverified one) and the lengths only; never the text, title,
// instruction, request key or key material.
var lengths = (display: 0, speech: 0)
func answer(_ status: String) -> Data {
Log.agent.info("[AGENT-DRAFT] receipt host=\(pair.host ?? "unverified", privacy: .public) pid=\(pair.peer.pid, privacy: .public) result=\(status, privacy: .public) display_len=\(lengths.display, privacy: .public) speech_len=\(lengths.speech, privacy: .public)")
return Self.reply(status)
}
guard let request = Self.decode(bytes) else { return answer("invalid") }
guard Self.isV2(request["schema_version"]) else { return answer("upgrade_required") }
let base: Set<String> = ["schema_version", "idempotency_key", "display_text"]
let linkedKeys: Set<String> = ["profile", "revision", "body_sha256", "proof"]
var keys = Set(request.keys)
Expand All @@ -1040,10 +1049,11 @@ import Security
(request["title"] == nil || request["title"] is String),
ExplanationDraft(id: clientKey, display: display, speech: request["speech_text"] as? String,
title: request["title"] as? String) != nil else {
return Self.reply("invalid")
return answer("invalid")
}
let speech = request["speech_text"] as? String
let title = request["title"] as? String
lengths = (display.count, speech?.count ?? 0)
let response = Reply()
let signal = DispatchSemaphore(value: 0)
let responseDeadline = DispatchTime.now() + .milliseconds(750)
Expand Down Expand Up @@ -1112,8 +1122,8 @@ import Security
self.rates[pair.client] = rate
response.set(result.rawValue)
}
guard signal.wait(timeout: responseDeadline) == .success else { return Self.reply("unconfirmed") }
return Self.reply(response.get())
guard signal.wait(timeout: responseDeadline) == .success else { return answer("unconfirmed") }
return answer(response.get())
}
guard socket.start() else {
status = socket.requiresPathInspection ? LocalApprovedSocket.unknownPathMessage : "대본 받기 소켓을 시작할 수 없습니다."
Expand Down
11 changes: 10 additions & 1 deletion Sources/App/LocalSpeechSocket.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import Foundation
import Darwin
import CryptoKit

/// Single-login, opt-in IPC. No text is logged or persisted by this bridge.
/// Single-login, opt-in IPC. No text is logged or persisted by this bridge; each
/// request logs its result, the peer process and the text length only.
final class LocalSpeechSocket {
private let queue = DispatchQueue(label: "com.codebasic.tts.local-speech")
private var fd: Int32 = -1
Expand Down Expand Up @@ -74,12 +75,20 @@ final class LocalSpeechSocket {
if b == 10 { break }; buffer.append(b)
}
var status = "invalid"
var length = 0
defer {
var pid: pid_t = 0
var size = socklen_t(MemoryLayout<pid_t>.size)
let peer = getsockopt(client, SOL_LOCAL, LOCAL_PEERPID, &pid, &size) == 0 ? String(pid) : "unknown"
Log.agent.info("[AGENT-SPEECH] request pid=\(peer, privacy: .public) result=\(status, privacy: .public) len=\(length, privacy: .public)")
}
if buffer.count < 25 * 1024,
let object = try? JSONSerialization.jsonObject(with: Data(buffer)) as? [String: Any],
object.count == 2, let text = object["text"] as? String, let key = object["idempotency_key"] as? String,
text.utf8.count <= 4096, !text.contains("\0"), !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
!key.isEmpty, key.utf8.count <= 128,
key.utf8.allSatisfy({ (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) || $0 == 45 || $0 == 46 || $0 == 95 }) {
length = text.count
let semaphore = DispatchSemaphore(value: 0)
let deadline = DispatchTime.now() + .milliseconds(1000)
let lock = NSLock()
Expand Down
125 changes: 108 additions & 17 deletions Sources/Core/AgentTrustStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,11 @@ final class AgentTrustStore {
}

static let maxClients = AgentPairing.slotCount
static let maxRevoked = 64
/// Revocations are never dropped: any cut-off would let a restored older
/// copy bring a dropped key back. At about 70 bytes each, thousands fit
/// under this read limit; a file that would exceed it is not written, and
/// the denial stays pending (in effect here) and is retried.
static let maxFileBytes = 256 * 1024
// Approval does not expire. An approved app stays approved until the user
// revokes it, its key changes, or it is launched by a different app.

Expand Down Expand Up @@ -110,6 +114,8 @@ final class AgentTrustStore {
switch Self.readDisk(url) {
case .loaded(let loaded, let stamp):
file = loaded
onDisk = loaded
lastGood = loaded
loadedExisting = true
diskStamp = stamp
case .missing:
Expand All @@ -133,10 +139,15 @@ final class AgentTrustStore {
/// the file again when it takes the socket over and whenever the file changed
/// since its own last read or write. Missing or unreadable after this instance
/// knew approvals: nothing is trusted and receipt is off. The user's denials
/// not yet saved are applied again on top of what is read.
func adoptDisk() {
/// not yet saved are applied again on top of what is read. An instance that
/// does not hold the socket (`writeBack == false`) only reads: what it would
/// write stays pending for when it takes the socket over.
func adoptDisk(writeBack: Bool = true) {
let known = file.revoked
let disk = Self.readDisk(url)
guard case .loaded(let loaded, let stamp) = disk else {
// What was last read is no longer what the file holds.
onDisk = nil
if case .unreadable(let stamp) = disk {
diskStamp = stamp
needsAdopt = stamp == nil
Expand All @@ -158,25 +169,78 @@ final class AgentTrustStore {
readFailed = false
closedByDisk = false
diskStamp = stamp
onDisk = loaded
lastGood = loaded
needsAdopt = false
guard !pending.isEmpty else {
file = loaded
return
// Revocations are never undone (a revoked key cannot be approved again),
// so every revocation this run knows is kept, also over a restored older
// copy that predates it. Receipt choices are not merged this way: the user
// may have turned receipt back on through another instance in between.
// A missing one becomes a pending denial like the user's own, so a failed
// write-back is retried and only a re-read file holding it settles it.
for keyID in known where !Self.holds(loaded, .revoke(keyID)) && !pending.contains(.revoke(keyID)) {
pending.append(.revoke(keyID))
}
var merged = loaded
for denial in pending { Self.apply(denial, to: &merged) }
guard merged != loaded else {
// The file already says what the user asked for, except one app's off
// for a row it does not have: that stays for when the row comes back.
// The file already says what the user asked for (or nothing is
// pending), except one app's off for a row it does not have: that
// stays for when the row comes back.
file = loaded
// A file this run re-created never settles pending denials.
if !recreated { pending.removeAll { Self.holds(loaded, $0) } }
return
}
file = merged
guard writeBack else {
// Read again (and written) once this instance holds the socket.
needsAdopt = false
return
}
_ = commit(merged, byUser: false)
}

private static func encodedSize(_ file: File) -> Int {
(try? JSONEncoder().encode(file))?.count ?? Int.max
}

/// What is written when `file` would pass the read limit: every revocation
/// that removes a row of the file last read (that app would connect again),
/// every revocation that file already holds, then the newest others that fit.
/// Nil when even the first two do not fit. Memory keeps all of them either way.
private static func fitting(_ file: File, onDisk: File?) -> File? {
let rows = Set((onDisk?.clients ?? []).map(\.keyID))
let own = Set(onDisk?.revoked ?? [])
let required = file.revoked.filter { rows.contains($0) || own.contains($0) }
// Newest first, so the oldest are the first left out.
var others = Array(file.revoked.filter { !rows.contains($0) && !own.contains($0) }.reversed())
var fitted = file
func build() -> [String] {
let kept = Set(required).union(others)
return file.revoked.filter { kept.contains($0) }
}
fitted.revoked = required
guard encodedSize(fitted) <= maxFileBytes else { return nil }
// Each entry adds its quoted bytes and a comma; trim to that estimate,
// then drop the oldest others until the exact size fits.
var budget = maxFileBytes - encodedSize(fitted)
var count = 0
for keyID in others {
let cost = keyID.utf8.count + 3
guard cost <= budget else { break }
budget -= cost
count += 1
}
others = Array(others.prefix(count))
fitted.revoked = build()
while encodedSize(fitted) > maxFileBytes, !others.isEmpty {
others.removeLast()
fitted.revoked = build()
}
return fitted
}

private func close(failed: Bool) {
var closed = File()
closed.receiptChoice = .off
Expand Down Expand Up @@ -330,7 +394,7 @@ final class AgentTrustStore {
if let index = file.clients.firstIndex(where: { $0.id == id }) { file.clients[index].receivesDrafts = false }
case .revoke(let keyID):
file.clients.removeAll { $0.keyID == keyID }
if !file.revoked.contains(keyID) { revoke(keyID, in: &file) }
if !file.revoked.contains(keyID) { file.revoked.append(keyID) }
}
}

Expand All @@ -348,8 +412,7 @@ final class AgentTrustStore {
}

private static func revoke(_ keyID: String, in file: inout File) {
file.revoked.append(keyID)
if file.revoked.count > maxRevoked { file.revoked.removeFirst(file.revoked.count - maxRevoked) }
if !file.revoked.contains(keyID) { file.revoked.append(keyID) }
}

/// A denial is in effect here at once and stays pending until a re-read of
Expand Down Expand Up @@ -396,7 +459,27 @@ final class AgentTrustStore {
needsAdopt = true
return false
}
guard let bytes = try? JSONEncoder().encode(next), (try? write(bytes, url)) != nil else {
// Never replace the file with one that could not be read back. Past the
// limit only the most important revocations are written; the rest stay in
// effect here and pending.
var toWrite = next
if Self.encodedSize(next) > Self.maxFileBytes {
guard let fitted = Self.fitting(next, onDisk: lastGood) else {
if !pending.isEmpty { needsAdopt = true }
return false
}
toWrite = fitted
if !readFailed, !closedByDisk, toWrite == onDisk, diskStamp != nil, Self.stamp(url) == diskStamp {
// Nothing more fits: the file already holds all it can.
file = next
needsAdopt = false
lastCommitSeen = true
if !recreated { pending.removeAll { Self.holds(toWrite, $0) } }
return true
}
}
guard let bytes = try? JSONEncoder().encode(toWrite), bytes.count <= Self.maxFileBytes,
(try? write(bytes, url)) != nil else {
if !pending.isEmpty { needsAdopt = true }
return false
}
Expand All @@ -406,17 +489,25 @@ final class AgentTrustStore {
// Remember the file only if it is what was just written. Otherwise (another
// writer got in between, or it is gone) the next check reads it again and
// the user's denials are applied to it once more.
if case .loaded(let disk, let stamp) = Self.readDisk(url), disk == next {
if case .loaded(let disk, let stamp) = Self.readDisk(url), disk == toWrite {
diskStamp = stamp
onDisk = disk
lastGood = disk
needsAdopt = false
lastCommitSeen = true
if !recreated { pending.removeAll { Self.holds(next, $0) } }
if !recreated { pending.removeAll { Self.holds(toWrite, $0) } }
} else {
needsAdopt = true
}
return true
}

/// The file as this instance last read or wrote it.
private var onDisk: File?
/// The last file read or written intact, kept while the file is missing or
/// unreadable: what it held is still what the fit keeps first.
private var lastGood: File?

/// The last write was read back unchanged.
private var lastCommitSeen = false

Expand All @@ -432,11 +523,11 @@ final class AgentTrustStore {
guard fstat(fd, &meta) == 0 else { return .unreadable(nil) }
let fileStamp = stamp(meta)
guard (meta.st_mode & S_IFMT) == S_IFREG, meta.st_uid == getuid(),
meta.st_nlink == 1, meta.st_mode & 0o777 == 0o600, meta.st_size > 0, meta.st_size <= 256 * 1024
meta.st_nlink == 1, meta.st_mode & 0o777 == 0o600, meta.st_size > 0, meta.st_size <= maxFileBytes
else { return .unreadable(fileStamp) }
// A read error may be passing; only bytes that do not parse keep the stamp.
guard let bytes = try? reader.read(upToCount: 256 * 1024 + 1) else { return .unreadable(nil) }
guard bytes.count <= 256 * 1024,
guard let bytes = try? reader.read(upToCount: maxFileBytes + 1) else { return .unreadable(nil) }
guard bytes.count <= maxFileBytes,
let loaded = try? JSONDecoder().decode(File.self, from: bytes), loaded.version == 1,
loaded.clients.count <= maxClients,
loaded.clients.allSatisfy({ AgentPairingProof.keyID($0.publicKey) == $0.keyID }),
Expand Down
3 changes: 2 additions & 1 deletion Sources/Core/Logging.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ enum Log {
static let service = Logger(subsystem: subsystem, category: "service")
static let app = Logger(subsystem: subsystem, category: "app")
static let tts = Logger(subsystem: subsystem, category: "tts")
/// `[AGENT-CONN]` agent app connection and approval decisions. Never logs
/// `[AGENT-CONN]` agent app connection and approval decisions, `[AGENT-DRAFT]`
/// draft receipt results and `[AGENT-SPEECH]` speech request results. Never logs
/// draft text, instructions or key material; app identity is the code
/// signature (team/certificate + signing identifier), not user data.
static let agent = Logger(subsystem: subsystem, category: "agent")
Expand Down
Loading